id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
138050 | <filename>double_check/application.py
from aiohttp.web import Application
from double_check.backends.ramos import configure_ramos
from double_check.handlers import about_hanlder
from double_check.request_token.routes import ROUTES as token_routes
def create_app():
configure_ramos()
app = Application()
ap... | StarcoderdataPython |
1689449 | from sklearn.model_selection import train_test_split
import pandas as pd
import re
import os
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras import layers
from tensorflow.keras.preprocessing.sequence import pad_sequences
import bert
def bert_encode(texts, toke... | StarcoderdataPython |
1655303 | <gh_stars>1-10
"""Tools for infix-based language games
Basic rules:
- <infix> is inserted after each group of consonants that is followed by a vowel
- if a word starts with a vowel, <infix> is inserted before this vowel
Extended rules:
- 'qu' is kept for syntactic purposes
"query" => "quaveravy"
- for 3+ character ... | StarcoderdataPython |
3247124 | <gh_stars>10-100
from context import aiolearn
import getpass
user = aiolearn.User(username='keh13',
password=getpass.getpass("input password:"))
semester = aiolearn.Semester(user)
print(user)
| StarcoderdataPython |
137656 | from neurosky._connector import Connector
from neurosky._processor import Processor
from neurosky._trainer import Trainer
from neurosky.utils import KeyHandler
__all__ = ['Connector', 'Processor', 'Trainer', 'KeyHandler']
| StarcoderdataPython |
4816905 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in compl... | StarcoderdataPython |
3205785 | import numpy as np
import matplotlib.pyplot as plt
import math
from matplotlib import cm
from mpl_toolkits.mplot3d.axes3d import Axes3D
def get_cost_function(h_theta_x, logistic=False):
def cost_func(thetas, training_set):
result = 0
for training_sample in training_set:
nonlocal logisti... | StarcoderdataPython |
196813 | _base_ = ['./mswin_par_small_patch4_512x512_160k_ade20k_pretrain_224x224_1K.py']
model = dict(
decode_head=dict(
mode='seq',
))
data = dict(samples_per_gpu=10)
| StarcoderdataPython |
5541 | import tensorflow as tf
FLIPPING_TENSOR = tf.constant([1.0, -1.0, 1.0])
@tf.function
def sample_data(points, labels, num_point):
if tf.random.uniform(shape=()) >= 0.5:
return points * FLIPPING_TENSOR, labels
return points, labels
mock_data = tf.constant([
[1., 2., 3.],
[4., 5., 6.],
[7.... | StarcoderdataPython |
3200783 | <reponame>HembramBeta777/Python-Programming
# Find multiplication table of number n
num = int(input("Enter a number: "))
for i in range(1,11):
mul = num * i
print(num," * ",i," = ",mul)
| StarcoderdataPython |
3397400 | <filename>build/zip.py
import zipfile
from io import BytesIO
class InMemoryZip(object):
def __init__(self):
# Create the in-memory file-like object for working w/imz
self.in_memory_zip = BytesIO()
self.files = []
def append(self, filename_in_zip, file_contents):
# Appends a fi... | StarcoderdataPython |
3228111 | ## NOTE: Requires Python 3.7 or higher
from collections import namedtuple
emp1 = ('Pankaj', 35, 'Editor')
emp2 = ('David', 40, 'Author')
for p in [emp1, emp2]:
print(p)
for p in [emp1, emp2]:
print(p[0], 'is a', p[1], 'years old working as', p[2])
# pythonic way
for p in [emp1, emp2]:
print('%s is a %d... | StarcoderdataPython |
110525 | <reponame>LeRoi46/opennero
import json
import constants
import OpenNero
import agent as agents
def factory(ai, *args):
cls = ai_map.get(ai, NeroTeam)
return cls(*args)
class TeamEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, NeroTeam):
return {
'... | StarcoderdataPython |
180844 | import msg
def readToken():
with open('token.txt', 'r') as f:
return f.readline().strip("\n")
def hasNick(update):
if update.message.from_user.username != None:
return True
return False
def getLinks(filename):
links = ""
count = 1
fn = 'Resources/' + filename
if filen... | StarcoderdataPython |
106297 | #!/usr/bin/python
import csv
import sys
with open("input.txt") as tsv:
checksum = 0
for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
lineLargest = 0
lineSmallest = sys.maxint
for valueString in line:
value = in... | StarcoderdataPython |
4803282 | <reponame>worms-maker/Python-123
# Declaration of Variable in Python
# Python Work with Indentation so, When Write code Then Most important is Formatting of Code.
# Python Variable name Only Start With (_)UnderScore or Alphabets.
# Other Keyboard Symbols are Not accept in NamingConvention.
# Use Different Type of Cas... | StarcoderdataPython |
23854 | """
:filename transformations.py
:author <NAME>
:email <EMAIL>
from
Classes of custom transformations that are applied during the training as additional augmentation of the depth maps.
"""
import torch
import random
import numpy as np
import torch.nn.functional as F
from random import randrange
from s... | StarcoderdataPython |
4841903 | # Copyright (c) <NAME> <<EMAIL>>
# See LICENSE file.
from _sadm.utils import path, systemd
__all__ = ['deploy']
# run as root at last pass
sumode = 'post'
def deploy(env):
destdir = env.settings.get('network.fail2ban', 'config.destdir')
jdisable = env.settings.getlist('network.fail2ban', 'jail.disable')
for jn i... | StarcoderdataPython |
4804568 | <filename>Development Resources/Miscellaneous Content/level1.py
health = 100
inventory = []
def level_1(health, inventory):
print("You step into a huge room. The door swings shut behind you.")
exit_room = False
door = 'locked'
sarcophagus = ['medalion', 'key', 'closed']
while not exit_room:... | StarcoderdataPython |
3372213 | <filename>morgan_stanley_problems/problem_1.py<gh_stars>0
"""This problem was asked by <NAME>.
In Ancient Greece, it was common to write text with the first line going left to right,
the second line going right to left, and continuing to go back and forth.
This style was called "boustrophedon".
Given a binary tree,... | StarcoderdataPython |
3304242 | <filename>ravens_torch/demos.py
# coding=utf-8
# Adapted from Ravens - Transporter Networks, Zeng et al., 2021
# https://github.com/google-research/ravens
"""Data collection script."""
import os
import numpy as np
from absl import app, flags
from ravens_torch import tasks
from ravens_torch.constants import EXPERIMENT... | StarcoderdataPython |
122661 | <reponame>gyungchan2110/ImageUtils
# In[]
import cv2
import numpy as np
import os
from operator import eq
import random
import matplotlib.pyplot as plt
from skimage import io
import shutil
listBase = "D:/[Data]/[Cardiomegaly]/1_ChestPA_Labeled_Baeksongyi/[PNG]_2_Generated_Data(2k)/Generated_Data_20180201_091700... | StarcoderdataPython |
1741703 | # List test
l = []
print l
l.append(2)
print l.__len__()
print l
l2 = []
l.append(l2)
print l
print list()
print [1, 2, 3]
| StarcoderdataPython |
3344333 | # Copyright 2021 Xilinx 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 by applicable law or agreed to in writing, sof... | StarcoderdataPython |
1682129 | <reponame>liweileev/SOMGAN
'''
Author: Liweileev
Date: 2022-01-03 17:00:02
LastEditors: Liweileev
LastEditTime: 2022-01-31 01:10:10
'''
import click
import dnnlib
import os
import re
import json
import torch
import tempfile
from training import training_loop
from torch_utils import training_stats
from torch_utils imp... | StarcoderdataPython |
3242949 | from .base import GnuRecipe
from ..version import Versions
class Sqlite3Recipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(Sqlite3Recipe, self).__init__(*args, **kwargs)
self.sha256 = 'd9d14e88c6fb6d68de9ca0d1f9797477' \
'd82fc3aed613558f87ffbdbbc5ceb74a'
s... | StarcoderdataPython |
11888 | <filename>parser.py<gh_stars>0
import lexer
import ast
class Parser:
block_end_tokens = [lexer.TokenKind.KW_RETURN, lexer.TokenKind.EOF,
lexer.TokenKind.KW_END, lexer.TokenKind.KW_ELSE,
lexer.TokenKind.KW_ELSEIF, lexer.TokenKind.KW_UNTIL]
priority_table = {
... | StarcoderdataPython |
1783604 | <filename>gtfs_converter/datagouv.py
import os
import requests
import logging
DATAGOUV_API = os.environ["DATAGOUV_API"]
TRANSPORT_ORGANIZATION_ID = os.environ["TRANSPORT_ORGANIZATION_ID"]
DATAGOUV_API_KEY = os.environ["DATAGOUV_API_KEY"]
ORIGINAL_URL_KEY = "transport:original_resource_url"
def delete_community_resou... | StarcoderdataPython |
1682233 | import requests
api_url = "https://jsonplaceholder.typicode.com/todos/10"
response = requests.get(api_url)
print(response.json())
response = requests.delete(api_url)
print(response.json())
print(response.status_code) | StarcoderdataPython |
3268507 | <gh_stars>1-10
#
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# https://leetcode.com/problems/valid-parentheses/description/
#
# algorithms
# Easy (39.76%)
# Likes: 6909
# Dislikes: 286
# Total Accepted: 1.3M
# Total Submissions: 3.3M
# Testcase Example: '"()"'
#
# Given a string s containi... | StarcoderdataPython |
128036 | <reponame>zhaokai0402/PyQt5-Study<gh_stars>0
import math
# -*- coding:utf-8 -*-
if __name__ == '__main__':
length = float(input("length: "))
print("squares:", length ** 2)
print("cubes:", length ** 3)
print("circles:", math.pi * length ** 2)
print("squares:", 4.0 / 3.0 * length ** 3 * math.pi)
| StarcoderdataPython |
163574 | <reponame>parkerwray/smuthi-1
# -*- coding: utf-8 -*-
"""Test spherical_functions"""
import smuthi.utility.math
import numpy as np
from sympy.physics.quantum.spin import Rotation
def test_wignerd():
l_test = 5
m_test = -3
m_prime_test = 4
beta_test = 0.64
wigd = smuthi.utility.math.wigner_d(l_tes... | StarcoderdataPython |
13784 | import logging
from django.utils import timezone
from typing import Union
from .exceptions import InvalidTrustchain, TrustchainMissingMetadata
from .models import FetchedEntityStatement, TrustChain
from .statements import EntityConfiguration, get_entity_configurations
from .settings import HTTPC_PARAMS
from .trust_ch... | StarcoderdataPython |
1770832 | #!/usr/bin/python
import pygame, sys, random
skier_images=["skier_down.png", "skier_right1.png", "skier_right2.png", "skier_left2.png", "skier_left1.png"]
class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")... | StarcoderdataPython |
101364 | #!/usr/bin/env python
"""
DiabloHorn - https://diablohorn.com
POC client on 'infected' machines to receive injected packets
intended to bypass IP whitelisting
"""
import sys
import time
import socket
from threading import Thread
from Queue import Queue, Empty
from scapy.all import *
conf.sniff_promisc = 0
... | StarcoderdataPython |
1744402 | # -*- coding: utf-8 -*-
r"""
:mod:`ganground` -- Lightweight framework for common ML workflow
================================================================
.. module:: ganground
:platform: Unix
:synopsis: Flexible wrapper of PyTorch which organizes boilerplate code.
"""
from ganground._version import *
from... | StarcoderdataPython |
4801067 | #!/usr/bin/env python3
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import argparse
import os
import numpy as np
import time
import sys
import signal
from conban_spanet.environment import Environment
from conban_spanet.conbanalg import *
from bite_selec... | StarcoderdataPython |
3275581 | <gh_stars>1-10
from binance.client import Client
import Settings
import json
api_key = Settings.BINANCE_API_KEY
api_secret = Settings.BINANCE_API_SECRET
client = Client(api_key, api_secret)
# I didn't know this endpoint existed, will use this endpoint next time.
# print(client.get_products())
# get all symbol pric... | StarcoderdataPython |
1655501 | <reponame>newtoallofthis123/PythonProjects
# Name of the Project : IJ-Speed.py
# Written by NoobScience : https://github.com/newtoallofthis123
# Modules Used : imdb (pip install speedtest)
# import the module as st
import speedtest as st
import tkinter as tk
from tkinter import *
def speedtest():
# defi... | StarcoderdataPython |
64230 | <filename>scripts/tag_mp3.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import argparse
import json
from mutagen.id3 import ID3, TDRL, COMM
from pathlib import Path
from pprint import pprint
parser = argparse.ArgumentParser(description="tag mp3 using vgmdb -J")
parser.add_argument("dir", help='dir of mp3')
parser.... | StarcoderdataPython |
1652887 | <reponame>BhargavRE25/Rover-Machine-Learning
#!/usr/bin/env python
# Converts laser scan to planar distance
# and segments into obstalces and just hills
import rospy
from std_msgs.msg import Header
from sensor_msgs.msg import LaserScan, Imu, Image
from tf.transformations import euler_from_quaternion
from cv_bridge imp... | StarcoderdataPython |
3207293 | import unittest
from otri.filtering.filters.generic_filter import GenericFilter
from otri.filtering.stream import Stream
def EXAMPLE_OP(x): return x + 1
class GenericFilterTest(unittest.TestCase):
def setUp(self):
self.s_A = Stream()
self.s_B = Stream()
self.gen_filter = GenericFilter(
... | StarcoderdataPython |
1710349 | <filename>tests/test_cli.py
import click.testing
import pytest
from easel.__main__ import cli
from tests.test_configs import TestSites
@pytest.fixture
def runner() -> click.testing.CliRunner:
return click.testing.CliRunner()
def test__help(runner):
result_01 = runner.invoke(cli, [])
result_02 = runner... | StarcoderdataPython |
3317941 | <filename>examples/runners/runners/__main__.py
from surround import Assembler
from .stages import ValidateData, HelloWorld
from .batch_runner import BatchRunner
# pylint: disable=unused-import
from .web_runner import WebRunner
def main():
assembler = Assembler("Default project", ValidateData(), HelloWorld())
... | StarcoderdataPython |
189169 |
def lprint(msg,*tuple):
print(msg)
if len(tuple)>1:
for obj in tuple:
print(obj)
print("结束") | StarcoderdataPython |
1680516 | <filename>cride/events/models/leagues.py
#Django
from django.db import models
#Utils
from cride.utils.models import BetmatcherModel
class League(BetmatcherModel):
"""League model"""
name = models.CharField(max_length = 15, blank = False)
sport = models.ForeignKey(
"events.Sport",
on_delete = models.CASC... | StarcoderdataPython |
3231681 | <gh_stars>10-100
import torch
import torch.nn.functional as F
class Optimization():
def __init__(self, train_loader, device):
self.train_loader = train_loader
self.device = device
def cdw_feature_distance(self, old_model, old_classifier, new_model):
"""cosine distance weight (cdw): ca... | StarcoderdataPython |
1688681 | <reponame>simeydk/adventofcode<gh_stars>0
from typing import List, Union
from statistics import median
def read_file(filename):
with open(filename) as f:
return [line.strip() for line in f.readlines()]
PAIRS = { '(': ')', '[': ']', '{': '}', '<': '>',}
OPENS = '([{<'
CLOSES = ')]}>'
POINTS = {
')': ... | StarcoderdataPython |
45904 | #
# This is a minimal server-side web application that authenticates visitors
# using Google Sign-in.
#
# See the README.md and LICENSE.md files for the purpose of this code.
#
# ENVIRONMENT VARIABLES YOU MUST SET
#
# The following values must be provided in environment variables for Google
# Sign-in to work.
#
# The... | StarcoderdataPython |
1732544 | <filename>examples/web/wiki/macros/wiki.py
"""Wiki macros"""
from genshi import builder
def title(macro, environ, *args, **kwargs):
"""Return the title of the current page."""
return builder.tag(environ["page.name"])
| StarcoderdataPython |
1613469 | <filename>app/routes.py
#import route libraries
from flask import render_template, request, redirect
from app import app, db
from app.models import Entry
jedi = "of the jedi"
@app.route('/')
@app.route('/index')
def index():
# entries = [
# {
# 'id' : 1,
# 'title': 'test title 1',
... | StarcoderdataPython |
142969 | <reponame>RIVeR-Lab/walrus<gh_stars>1-10
from walrus_system_configuration.util import *
from catkin.find_in_workspaces import find_in_workspaces
import sys
import os
from termcolor import colored
SYSINIT_CONFIG_FILE = '/etc/init/rc-sysinit.conf'
def wait_for_net():
f = open(SYSINIT_CONFIG_FILE)
found = False
... | StarcoderdataPython |
50167 | <reponame>NewShadesDAO/api<gh_stars>1-10
from typing import Optional
import requests
from app.config import get_settings
class TenorClient:
def __init__(self):
settings = get_settings()
self.api_key = settings.tenor_api_key
self.search_endpoint = "https://g.tenor.com/v1/search"
s... | StarcoderdataPython |
85871 | <filename>etc/ipython/ipython_config.py
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
"""
dotfiles.venv.venv_ipyconfig
==============================
venv_ipyconfig.py (venv)
Create virtual environment configurations
with a standard filesystem hierarchy overlay
and cd aliases for Bash,... | StarcoderdataPython |
4806033 | # -*- coding: utf-8 -*-
"""The graphical part of a Packmol step"""
import logging
import tkinter as tk
import tkinter.ttk as ttk
from packmol_step import PackmolParameters
import seamm
import seamm_widgets as sw
logger = logging.getLogger(__name__)
class TkPackmol(seamm.TkNode):
"""Graphical interface for usi... | StarcoderdataPython |
3244997 | # Copyright (C) 2016-2019 Virgil Security Inc.
#
# Lead Maintainer: <NAME> Inc. <<EMAIL>>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# (1) Redistributions of source code must retain... | StarcoderdataPython |
1784189 | from pytextrank import json_iter, parse_doc, pretty_print, normalize_key_phrases, render_ranks, text_rank, rank_kernel, top_sentences, limit_keyphrases, limit_sentences, make_sentence
import sys
## Stage 1:
## * perform statistical parsing/tagging on a document in JSON format
##
## INPUTS: <stage0>
## OUTPUT: JSON fo... | StarcoderdataPython |
4814823 | import os
import torch
import pandas as pd
import segmentation_models_pytorch as smp
from catalyst.dl.callbacks import DiceCallback, EarlyStoppingCallback, InferCallback, CheckpointCallback
from catalyst.dl.runner import SupervisedRunner
from catalyst.dl import utils
from sklearn.model_selection import train_test_spl... | StarcoderdataPython |
3286440 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import cobra.models.fields.foreignkey
import cobra.models.fields.bounded
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('organization', '0003_organization_a... | StarcoderdataPython |
33937 | import os
import random
from sklearn.metrics import mean_squared_error as mse
from core.composer.chain import Chain
from core.composer.composer import ComposerRequirements, DummyChainTypeEnum, DummyComposer
from core.models.data import OutputData
from core.models.model import *
from core.repository.dataset_t... | StarcoderdataPython |
1618844 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from struct import pack, unpack
from threading import Condition
from stucancommon.node import Service, CanNode, Timeout
from .addresses import RCC_GROUP_DEVICE_ID
logger = logging.getLogger(__name__)
class Request(Service):
"""
Base class for a re... | StarcoderdataPython |
118864 | from models.posts import (
BaseCreatePostModel,
BaseDeletePostModel,
CreatePostModel,
ReturnPostModel,
)
from core.errors import ConflictError
import sqlite3
from models.user import UserModel
class PostsCRUD:
def create(
self, conn: sqlite3.Connection, data: BaseCreatePostMode... | StarcoderdataPython |
1617194 | <gh_stars>1-10
class Item3rd:
appid = ''
market_hash_name = ''
url3rd = ''
market3rd = ''
name_in_market3rd = ''
lowest_sell_price = 0 | StarcoderdataPython |
102837 | import yaml
from torch import nn, optim
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from monai.losses import DiceCELoss
import factorizer as ft
from factorizer import datasets
from factorizer.utils.lightning import SemanticSegmen... | StarcoderdataPython |
178234 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import argparse
import pandas as pd
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
FEATURES = ["crim", "zn", "indus", "nox", "rm",
"age", "dis", "tax", "ptratio"]
LA... | StarcoderdataPython |
142605 | # Generated by Django 3.1.12 on 2021-09-24 11:41
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('teams', '0001_squashed_0003_auto_20210325_0812'),
]
operations = [
migrations.CreateModel(
... | StarcoderdataPython |
1775917 | import pandas as pd
data_path = 'data/'
business_df = None
def init_businesses():
global business_df
business_df = pd.read_csv(data_path + 'df.csv', sep='\t')
init_businesses()
def get_business_list(product):
return business_df[business_df['Product'] == product]
| StarcoderdataPython |
1734817 | import os
import docker
__docker_client = None
__management_network = None
def get_docker_client(cert_path, host_addr, host_port):
global __docker_client
if __docker_client:
return __docker_client
tls_config = docker.tls.TLSConfig(
ca_cert=os.path.join(cert_path, "ca.pem"),
clie... | StarcoderdataPython |
1615319 | """Settings for Rhasspy."""
import json
import logging
import os
from typing import Any, Dict, List
import pydash
from rhasspy.utils import recursive_update
# -----------------------------------------------------------------------------
logger = logging.getLogger(__name__)
class Profile:
"""Contains all setti... | StarcoderdataPython |
3249917 | <reponame>wilmerm/unolet-2022
from django.urls import path
from person import views
urlpatterns = [
path("person/create/", views.PersonCreateView.as_view(),
name="person-person-create"),
path("person/list/", views.PersonListView.as_view(),
name="person-person-list"),
path("person/list/<int:pk... | StarcoderdataPython |
148827 | '''
pass_flatten_basic02.py
Copyright (c) Seoul National University
Licensed under the MIT license.
Author: <NAME>
Basic functionality check for torch.flatten.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
a = torch.rand(2, 3, 4, 5, 6, 7)
b = torch.flatten(a)
# shape assertion
b + torch.ran... | StarcoderdataPython |
3337197 | <filename>spikey/snn/readout/template.py
"""
Translator from output neuron spike trains to actions
for the environment.
"""
import numpy as np
from spikey.module import Module, Key
class Readout(Module):
"""
Translator from output neuron spike trains to actions
for the environment.
Parameters
---... | StarcoderdataPython |
3255075 | <filename>pytext/torchscript/tensorizer/bert.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List, Optional, Tuple
import torch
from pytext.torchscript.utils import pad_2d_mask
from pytext.torchscript.vocab import ScriptVocabulary
from .tensorizer i... | StarcoderdataPython |
1781768 | <gh_stars>1-10
#!/usr/bin/env python3
# Copyright (c) 2014-2020, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice... | StarcoderdataPython |
3229879 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
151965 | import discord
import json
from discord.ext import commands
from discord.utils import get
sigma = commands.Bot(command_prefix='*', help_command=None)
warnings = {}
token = "TOKEN_BOT"
#Permet de mettre un statut au bot ^^
@sigma.event
async def on_ready():
print("Sigma est prêt !")
await sigma.... | StarcoderdataPython |
94059 | <reponame>arnoyu-hub/COMP0016miemie<filename>venv/Lib/site-packages/gensim/test/test_similarity_metrics.py
#!/usr/bin/env python
# encoding: utf-8
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated test to check similarity functions and isbow function.
"""
import l... | StarcoderdataPython |
3226588 | <filename>xmonitor/async/flows/introspect.py<gh_stars>0
# Copyright 2015 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.a... | StarcoderdataPython |
125433 | <gh_stars>1-10
"""Tests for Microsoft Visual C++ Compiler"""
def tests_compiler():
"""Test Compiler"""
import platform
from compilertools.compilers._core import _get_arch_and_cpu
from compilertools.compilers.msvc import Compiler
version = ""
def dummy_compiler():
"""platform.python_c... | StarcoderdataPython |
3264508 | <reponame>ratt-ru/pfb-clean
import numpy as np
class Dirac(object):
def __init__(self, nband, nx, ny, mask=None):
"""
Models image as a sum of Dirac deltas i.e.
x = H beta
where H is a design matrix that maps the Dirac coefficients onto the image cube.
Parameters
... | StarcoderdataPython |
1616420 |
import sys
import pprint
def get_positions(fh):
positions = []
for line in fh:
line = line.strip()
if len(line) == 0:
continue
elif len(positions) == 0:
positions = list(map(int,line.split(',')))
return positions
if __name__ == "__main__":
pp = pprin... | StarcoderdataPython |
4815529 | """Generic CSV file read and write operations."""
import csv
import os
FMT = dict(lineterminator="\n", quoting=csv.QUOTE_MINIMAL)
def check(enc):
if enc not in ['utf-8', 'windows-1251']:
raise ValueError("Encoding not supported: " + str(enc))
def yield_rows(path, enc='windows-1251', sep=";"):
"""Emi... | StarcoderdataPython |
1778744 | <reponame>DBrianKimmel/PyHouse_Install
"""
@name: PyHouse_Install/src/Install/Utility.py
@author: <NAME>
@contact: <EMAIL>
@copyright: (c) 2015-2016 by <NAME>
@license: MIT License
@note: Created on Oct 13, 2015
@Summary:
"""
# Import system type stuff
import getpass
import os
import s... | StarcoderdataPython |
131914 | <reponame>caburu/rl-baselines3-zoo<filename>julio/safe_evaluate_policy.py<gh_stars>0
from stable_baselines3.common.vec_env import VecEnv, DummyVecEnv
import numpy as np
# O método `evaluate_policy` original da biblioteca chama `reset` duas vezes por
# episódio se o ambiente passado usar DummyVecEnv (através da VecNorm... | StarcoderdataPython |
3239699 | """Build script for Lyve-SET Conda package"""
import os
import subprocess as sp
# Make rules to run
BASE_MAKE_RULES = [
'install-mkdir',
'install-SGELK',
'install-CGP',
'install-perlModules',
'install-config'
]
EXPENSIVE_MAKE_RULES = ['install-phast']
# Relative directory in conda env to install to
# Just put... | StarcoderdataPython |
3223028 | <reponame>pwnmeow/inceptor<filename>inceptor/signers/SigThief.py
#!/usr/bin/env python3
# LICENSE: BSD-3
# Copyright: <NAME> @midnite_runr
# Adapted by klezVirus @klezVirus
import argparse
import os.path
import sys
import struct
import shutil
import io
import tempfile
from pathlib import Path
from config.Config impor... | StarcoderdataPython |
107048 | import os
import caffe
import numpy as np
import skimage
import tensorflow as tf
from Preprocessor import Preprocessor
from datasets.ImageNet import ImageNet
from models.AlexNetConverter import AlexNetConverter
from models.SDNet import SDNet
from train.SDNetTrainer import SDNetTrainer
im_s = 227
def preprocess(img... | StarcoderdataPython |
1658155 | <filename>BackEnd/api/service/user_search.py
def build_user_search_schema(user_search):
mod = {}
mod['search_subject'] = user_search.search_subject
mod['search_id'] = user_search.search_id
return mod
| StarcoderdataPython |
1749976 | <reponame>codescribblr/project-manager-django3<filename>vapor_manager/users/forms.py
from django.contrib.auth import forms, get_user_model
User = get_user_model()
class UserChangeForm(forms.UserChangeForm):
class Meta(forms.UserChangeForm.Meta):
model = User
class UserCreationForm(forms.UserCreationFor... | StarcoderdataPython |
3350302 | # The Admin4 Project
# (c) 2013-2014 <NAME>
#
# Licensed under the Apache License,
# see LICENSE.TXT for conditions of usage
from _objects import ServerObject, DatabaseObject
from wh import xlt, YesNo
class Database(ServerObject):
typename=xlt("Database")
shortname=xlt("Database")
@staticmethod
def GetInst... | StarcoderdataPython |
4834354 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains unit tests of the arc.job.job module
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
import unittest
import os
import datetime
from arc.job.job import Job
from arc.settings import arc_path
###############... | StarcoderdataPython |
3387047 | from math import sin, cos, tan, radians
ang = float(input("Digite um ângulo: "))
angr = radians(ang)
print(f'O seno de {ang} é {sin(angr):.2f}')
print(f'O cosseno de {ang} é {cos(angr):.2f}')
print(f'A tangente de {ang} é {tan(angr):.2f}') | StarcoderdataPython |
3397431 | <filename>lang/py/cookbook/v2/source/cb2_15_8_exm_2.py
IOR:010000001d00000049444c3a466f7274756e652f436f6f6b69655365727665723
a312e300000000001000000000000005c000000010102000d0000003135382e313234
2e36342e330000f90a07000000666f7274756e6500020000000000000008000000010
0000000545441010000001c00000001000000010001000100000001... | StarcoderdataPython |
32761 | <filename>src/kalman_filter.py
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021 <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 lim... | StarcoderdataPython |
4815968 | import os
from pip._internal.req import parse_requirements
from setuptools import setup, find_packages
install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]
# Utility function to read the README file.
# Used for the long_description. It's nice, because now... | StarcoderdataPython |
1758720 | import re
from factom_did.client.constants import DID_METHOD_NAME
from factom_did.client.enums import KeyType, Network
def validate_alias(alias):
if not re.match("^[a-z0-9-]{1,32}$", alias):
raise ValueError(
"Alias must not be more than 32 characters long and must contain only lower-case "
... | StarcoderdataPython |
3378083 | from justgood import imjustgood
api = imjustgood("YOUR_APIKEY_HERE")
data = api.joox("lathi")
print(data)
# EXAMPLE GET CERTAIN ATTRIBUTES
result = "Singer : {}".format(data["result"]["singer"])
result += "\nTitle : {}".format(data["result"]["title"])
result += "\nDuration : {}".format(data["result"]["duratio... | StarcoderdataPython |
50029 | import supriya.nonrealtime
def test_01():
session = supriya.nonrealtime.Session()
assert session.offsets == [float("-inf"), 0.0]
assert session.duration == 0.0
def test_02():
session = supriya.nonrealtime.Session()
with session.at(0):
session.add_group()
assert session.offsets == [fl... | StarcoderdataPython |
1764793 | <gh_stars>1-10
import path_utils
from Evolve import Evolve
#e = Evolve('MountainCar-v0', NN='FFNN_multilayer')
#e = Evolve('CartPole-v0', NN='FFNN', search_method='bin_grid_search')
e = Evolve('MountainCar-v0', NN='FFNN', search_method='sparse_bin_grid_search')
#e = Evolve('MountainCar-v0', NN='FFNN')
evo_dict = e.ev... | StarcoderdataPython |
3740 | import math
from sys import exit
# итак, n - приблизительное число элементов в массиве, P - вероятность ложноположительного ответа, тогда размер
# структуры m = -(nlog2P) / ln2 (2 - основание), количество хеш-функций будет равно -log2P
# хеш-функции используются вида: (((i + 1)*x + p(i+1)) mod M) mod m,где - x - ключ,... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.