id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
140529 | import pandas as pd
import argparse
def writeOutFile(outputDF, outfile):
outputDF.to_csv(outfile, sep=',', encoding='utf-8', index=False)
def createOutputDF(inputDF, n):
diff = n - 1
outputDF = pd.DataFrame()
for i in range(int(inputDF.shape[0] / n)):
if i == 0:
dfl = pd.DataFram... | StarcoderdataPython |
3320537 | <reponame>abartoha/python-snippets-ref
'''Shutdown Windows'''
import os
#use with care
os.system('shutdown -s -t 0')
| StarcoderdataPython |
3384228 | #!/usr/bin/env python
"""
Copyright (c) 2016 <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, modify, merge, publ... | StarcoderdataPython |
3368072 | <filename>src/aggs/ping.py<gh_stars>1-10
# -*- coding:utf-8 -*-
"""
ping.py
~~~~~~~~
网络延迟报警
:author: kerrygao, Fufu, 2021/6/21
"""
from . import AggsPlugin
from ..libs.metric import Metric
class Ping(AggsPlugin):
"""ping 网络延迟报警"""
name = 'ping'
async def alarm(self, metric: Metric) -> M... | StarcoderdataPython |
193617 | import pdb
import copy
import numpy as np
from importlib_resources import files
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.figure import Figure
from .utilities import *
from .process_model import *
# Define font settings
fontsize = 12
font_files = font_manager.findSystemFont... | StarcoderdataPython |
3212390 | <filename>libs/approachAnalyser.py
import pandas as pd
from libs.utils import haversine, loadBook, getPerf, isaDiff, calcWindComponents
from configuration.units import runwayUnits
def findStop(flight):
return flight[flight.IAS > 20].index.max()
def isStable(approach, modelConfig, approachType, runwayTrack):
... | StarcoderdataPython |
3298768 | <reponame>hariom95/cosine_similarity_tfidf_nltk
import nltk
import string
# used for looping through folders/files
from os import listdir
from os.path import isfile, join
#Calc tfidf and cosine similarity
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarit... | StarcoderdataPython |
191009 | # Generated by Django 3.1.3 on 2021-02-09 11:15
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_bgp', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='community',
... | StarcoderdataPython |
3322037 | from django.contrib import admin
from .models import Portfolio, Contact, ProjectTech
class PortfolioAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ["title",]}
admin.site.register(Portfolio, PortfolioAdmin)
admin.site.register(ProjectTech)
admin.site.register(Contact)
| StarcoderdataPython |
179735 | <reponame>dxwayne/SAS_3DSpectrograps
__init__ = ["SpectrographUI_savejsondict","SpectrographUI_loadjsondict"]
def SpectrographUI_savejsondict(self,jdict):
'''Autogenerated code from ui's make/awk trick.'''
jdict['compLampSwitch'] = self.compLampSwitch.isChecked()
jdict['flatLampSwitch'] = self.flatLampSwitch.i... | StarcoderdataPython |
89191 | import logging
import pytest
from pyspark.sql import SparkSession
from pyspark.context import SparkContext
from pyspark.conf import SparkConf
def quiet_py4j():
"""Suppress spark logging for the test context."""
logger = logging.getLogger('py4j')
logger.setLevel(logging.WARN)
@pytest.fixture(scope="sess... | StarcoderdataPython |
3244814 | <filename>clubsuite/suite/tests/test_mdl_user.py<gh_stars>10-100
from django.test import TestCase
from suite.models import UserManager
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import check_password
from suite.models import Club
class UserTestCase(TestCase):
def setUp(self):
... | StarcoderdataPython |
35590 | <filename>src/py_call.py<gh_stars>0
#/bin/python3
import os
import subprocess
# Const:
with open("config",'r') as conf:
VENV_A = conf.read()
PYTHON="python"
PYTHON3_VENV_A = os.path.join(VENV_A, "bin", "python3")
PIP=""
PIP_VENV_A= os.path.join(VENV_A, "bin", "pip3")
# Functions:
def python_call(argv):
su... | StarcoderdataPython |
1768483 | <gh_stars>0
from typing import Any, Callable, List, Mapping, Optional
from snorkel.preprocess import BasePreprocessor
from snorkel.types import DataPoint
class LabelingFunction:
"""Base class for labeling functions.
A labeling function (LF) is a function that takes a data point
as input and produces an ... | StarcoderdataPython |
4800324 | <reponame>hesslink111/neuralnetworknibbles<filename>util/xorshift.py
class XorShift:
"""Class for generating pseudo-random numbers based on a seed. This allows us to generate predictable sequences
so we can play the same games. Based on xorshift+ from https://en.wikipedia.org/wiki/Xorshift"""
def __ini... | StarcoderdataPython |
147458 | <filename>output/models/nist_data/atomic/nmtoken/schema_instance/nistschema_sv_iv_atomic_nmtoken_enumeration_4_xsd/__init__.py
from output.models.nist_data.atomic.nmtoken.schema_instance.nistschema_sv_iv_atomic_nmtoken_enumeration_4_xsd.nistschema_sv_iv_atomic_nmtoken_enumeration_4 import (
NistschemaSvIvAtomicNmto... | StarcoderdataPython |
4819986 | <reponame>katajakasa/aetherguild4
from django.apps import AppConfig
from django.db.models.signals import post_save
class MainsiteConfig(AppConfig):
name = 'aether.main_site'
def ready(self):
from .signals import postprocess_newsitem
from .models import NewsItem
post_save.connect(postp... | StarcoderdataPython |
1724027 | from covid.utils.viz import plotly_wordcloud
| StarcoderdataPython |
3349112 | <filename>Calculator/Multiplication.py<gh_stars>0
def multiplication(a,b):
a = float(a)
b = float(b)
return a*b | StarcoderdataPython |
3246752 | <filename>activitysim/abm/test/test_misc/setup_utils.py
# ActivitySim
# See full license in LICENSE.txt.
import os
import logging
import pkg_resources
import openmatrix as omx
import numpy as np
import numpy.testing as npt
import pandas as pd
import pandas.testing as pdt
import pytest
import yaml
from activitysim.co... | StarcoderdataPython |
1688989 | <reponame>Chikiyaflix/server<filename>src/routes/streammap.py<gh_stars>0
import os
import urllib
import flask
import requests
import src.functions.config
streammapBP = flask.Blueprint("streammap", __name__)
@streammapBP.route("/api/v1/streammap")
async def streammapFunction():
a = flask.request.args.get("a") #... | StarcoderdataPython |
1604026 | from __future__ import annotations
__all__ = ['lock_seed', 'trace', 'trace_module', 'whereami']
import gc
import inspect
import os
import random
import types
from collections.abc import Iterator
from contextlib import suppress
from itertools import islice
from types import FrameType
import numpy as np
import wrapt
... | StarcoderdataPython |
53638 | <filename>detect_mcdonald_logo.py
#!/usr/bin/python
import sys, getopt
import copy
import matplotlib.pyplot as plt
import cv2 as cv
import modules.data_backend_operations as db
import modules.preprocessing as pr
import modules.segmentation as seg
import modules.classification as cls
def detect_logo(base_img, show_s... | StarcoderdataPython |
1651583 | import tweepy
import wget
import os
from PIL import Image
from pytesseract import *
from kafka import KafkaProducer
from kafka.errors import KafkaError
from collections import OrderedDict
import json
# twitter api auth
twitter_consumer_key = "pTHQmNMSbD6BJnZ1XtA8sJXY8"
twitter_consumer_secret = "<KEY>"
twitter_acce... | StarcoderdataPython |
132098 | def digitDifferenceSort(a):
def dg(n):
s = list(map(int, str(n)))
return max(s) - min(s)
ans = [(a[i], i) for i in range(len(a))]
A = sorted(ans, key = lambda x: (dg(x[0]), -x[1]))
return [c[0] for c in A]
| StarcoderdataPython |
94669 | # Copyright (c) 2013- The Spyder Development Team and Docrepr Contributors
#
# Distributed under the terms of the BSD BSD 3-Clause License
"""Simple tests of docrepr's output."""
# Standard library imports
import copy
import subprocess
import sys
import tempfile
from pathlib import Path
# Third party imports
import ... | StarcoderdataPython |
1642073 | import json
from docker.types import RestartPolicy
from wotemu.enums import NetworkConditions
from wotemu.topology.models import (Broker, BuiltinApps, Network, Node,
NodeApp, NodeResources, Service, Topology)
_ID_1 = "loc1"
_ID_2 = "loc2"
_THING_ID_DETECTOR = "urn:org:fundacioncti... | StarcoderdataPython |
1794055 | # Generated by Django 2.2.5 on 2019-10-27 19:10
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("plan", "0001_initial"),
]
operations = [
migrati... | StarcoderdataPython |
1745706 | <reponame>JackyCSer/WebServiceCompositionSystem<gh_stars>1-10
from __future__ import print_function
from . import pddl_types
def parse_condition(alist):
condition = parse_condition_aux(alist, False)
# TODO: The next line doesn't appear to do anything good,
# since uniquify_variables doesn't modify the con... | StarcoderdataPython |
108936 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
days_dict = {1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31,8:31, 9:30, 10:31, 11:30, 12:31}
start_week = {1:3, 2:6, 3:0, 4:3, 5:5, 6:1, 7:3, 8:6, 9:2, 10:4, 11:0, 12:2}
with open('Q3-output.txt', 'w') as f:
for i in range(1,13):
print('\n\n\t\t\t%d月'%i, file = f)... | StarcoderdataPython |
1660937 | """@file cluster_toolkit.py
Modeling using cluster_toolkit
"""
# Functions to model halo profiles
import numpy as np
import cluster_toolkit as ct
from . import func_layer
from . func_layer import *
from .parent_class import CLMModeling
from .. utils import _patch_rho_crit_to_cd2018
from .. cosmology.cluster_toolki... | StarcoderdataPython |
1729002 | <reponame>Keneral/atools
#!/usr/bin/env python3.4
#
# Copyright 2016 - The Android Open Source Project
#
# 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/... | StarcoderdataPython |
3286380 | import pytest
import time
import json
from datetime import datetime
from kubernetes.client.rest import ApiException
import backupstore
from backupstore import set_random_backupstore # NOQA
import common
from common import client, core_api, apps_api, batch_v1_beta_api # NOQA
from common import random_labels, volum... | StarcoderdataPython |
3340062 | <filename>backend/assets/create_users.py
AMOUNT_OF_ENTRIES = 3000
LOREM = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute... | StarcoderdataPython |
3375739 | <filename>snucovery/aws.py
import json
import boto3
from datetime import date, datetime
from snucovery.errors import (
UnknownServiceCall, InvalidServiceMappings,
)
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
... | StarcoderdataPython |
3238456 |
"""
Check url xpath
Check content xpath
parallel?
IP switch and headers
"""
import re
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.selector import Selector
from newscrawler.items import NewsItem
class HurriyetSpider(CrawlSpider):
"""
S... | StarcoderdataPython |
1785833 | <reponame>drobilc/nadlogar
from .generator_nalog import GeneratorNalogSolskiSlovar
from lxml import etree
import random
class NalogaGlasVsiljivec(GeneratorNalogSolskiSlovar):
IME = 'Poišči vsiljivca – glas'
NAVODILA = 'Med navedenimi glasovi (samoglasniki in soglasniki) v vsaki vrstici obkroži tisti glas, ki ... | StarcoderdataPython |
27548 | <filename>backend/accounts/serializers.py
from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField
from django.contrib.gis.geos import Point
from accounts.models import UserProfile
import datetime
from rest_framework_gis.pagination import GeoJsonPagination
from django.contrib... | StarcoderdataPython |
1631868 | <filename>tests/easy/test_valid_parentheses_20.py
from src.easy import valid_parentheses_20
def test_valid_parentheses():
s = valid_parentheses_20.Solution()
assert s.valid_parentheses("()[]{}") is True
assert s.valid_parentheses("({[]})") is True
assert s.valid_parentheses("{[}]()") is False | StarcoderdataPython |
154069 | <reponame>htetmyet/keyword-extraction
__author__ = "<NAME>"
from refo import finditer, Predicate, Plus
from collections import Counter
from StringIO import StringIO
from get_summary import summary
##from nltk.corpus import stopwords
import math
import nltk
import re
import copy
import glob
import numpy as ... | StarcoderdataPython |
136741 | <gh_stars>1-10
# Users: Make a class called User. Create two attributes called first_name and last_name,
# and then create several other attributes that are typically stored in a user profile.
# Make a method called describe_user() that prints a summary of the user’s information.
# Make another method called greet_... | StarcoderdataPython |
11706 | <filename>regtests/webclgl/call_external_method.py
"""external method"""
class myclass:
def __init__(self, i):
self.index = i
def get_index(self):
return self.index
def run(self, n):
self.intarray = new(Int16Array(n))
self.intarray[ self.index ] = 99
@returns( array=n )
@gpu.main
def gpufunc():
... | StarcoderdataPython |
3302056 | from api.cases.models import Advice
from api.cases.enums import AdviceLevel, AdviceType
from api.users.tests.factories import GovUserFactory
from test_helpers.clients import DataTestClient
from django.urls import reverse
class DeleteUserAdviceTests(DataTestClient):
def setUp(self):
super().setUp()
... | StarcoderdataPython |
3357672 | <reponame>glwagner/doublyPeriodicModels
import time, sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.append('../../')
from py2Periodic.physics import twoLayerQG
from numpy import pi
qgParams = {
'f0' : 1e-4,
'Lx' : 1e6,
'beta' : 1.5e-11,
'defRadius' : 1.5e4, ... | StarcoderdataPython |
4829458 | import datetime
import functools
import logging
import os
import sys
import click
import pkg_resources
from appdirs import AppDirs
from click._termui_impl import Editor
from .. import __version__
from ..aliases import aliases_database
from ..plugins import plugins_registry
from ..projects import ProjectsDb
from ..set... | StarcoderdataPython |
26404 | import numpy as np
import matplotlib.pyplot as plt
import cv2
class LaneIdentifier:
def __init__(self, smooth_factor, filter):
self.left_lane_inds = []
self.right_lane_inds = []
self.lane_gap = []
self.binary_warped = None
self.window_height = None
self.leftx_current... | StarcoderdataPython |
1763940 | <gh_stars>0
import numpy as np
import tensorflow as tf
# ------ Say hello
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
# ------ Assign the constants
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)
sess = tf.... | StarcoderdataPython |
1611654 | import os
import collections
import lamnfyc.context_managers
import lamnfyc.settings
import lamnfyc.packages.base
import subprocess
def three_two_installer(package, temp, env):
with lamnfyc.context_managers.chdir(os.path.join(temp, 'libffi-{}'.format(package.version))):
command = './configure --prefix={}... | StarcoderdataPython |
3306546 | <reponame>fvaleye/metadata-guardian
from metadata_guardian.source import ColumnMetadata
def test_column_metadata():
column_name = "column_name"
column_comment = "column_comment"
expected = [column_name, column_comment]
column_metadata = ColumnMetadata(
column_name=column_name, column_comment=... | StarcoderdataPython |
1714878 | # -*- coding: utf-8 -*-
from xml.etree import ElementTree
import sys
import csv
import subprocess
import os
def name_conversion(target):
if target == None:
return 'no_name'
else:
try:
target_name = target[:target.index("(")] # hoge(foo.var.fuga, piyo) -> hoge
target_para... | StarcoderdataPython |
67406 | #!/usr/bin/env python
# encoding: utf-8
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# 0001 XOR 0000 = 0001
# a XOR 0 = a
# a XOR a = 0
# a XOR b XOR a = a XOR a XOR b = b
a = 0
for num in nums:
a ^= num
return a
| StarcoderdataPython |
1726720 | # -*- coding: utf-8 -*-
import scrapy
from scrapy_demo.items import AosunItem
class AosunSpider(scrapy.Spider):
name = 'aosun_spider' # 定义爬虫的名称,用于区别spider,该名称必须是唯一的,不可为不同的spider设置相同的名字
allowed_domains = ['aosun.cloud'] # 定义允许爬取的域,若不是该列表内的域名则放弃抓取
custom_settings = {
'ITEM_PIPELINES': {'scrapy_dem... | StarcoderdataPython |
143870 | """
Load volumes into vpv from a toml config file. Just load volumes and no overlays
Examples
--------
Example toml file
orientation = 'sagittal'
[top]
specimens = [
'path1.nrrd',
'path2.nrrd',
'path3.nrrd']
[bottom]
specimens = [
'path1.nrrd',
'path2.nrrd',
'path3.nrrd']
"""
import sys
from pathlib import Path
... | StarcoderdataPython |
3393506 | <filename>Assignment_Ch03-3.py<gh_stars>1-10
print("Enter [R]ock, [P]aper, or [S]cissor")
player1 = input("Player 1: ")
print("Enter [R]ock, [P]aper, or [S]cissor")
player2 = input("Player 2: ")
try:
validInput = ["r", "R", "p", "P", "s", "S"]
if player1 not in validInput:
raise
elif pla... | StarcoderdataPython |
4842297 | from pathlib import Path
from typing import List
from qaz.managers import git, shell
from qaz.modules.base import Module
class Vim(Module):
name = "vim"
# Configuration files
zshrc_file = None
symlinks = {".vimrc": "~"}
# Other
vscode_extensions: List[str] = []
@classmethod
def ins... | StarcoderdataPython |
3321222 | """
Unit tests for `apetest.robots`.
"""
from logging import ERROR, INFO, WARNING, getLogger
from typing import Iterable, Mapping, Sequence, Tuple
from pytest import LogCaptureFixture, mark
from apetest.robots import (
lookup_robots_rules,
parse_robots_txt,
path_allowed,
scan_robots_txt,
)
logger = ... | StarcoderdataPython |
1732136 |
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
class MyMainWindow(QMainWindow):
def __init__(self):
super(QMainWindow, self).__init__()
self.title = 'PyQt5 Absolute positioning example'
self.left = 100
self.top = 100
self.width = 640
self.height = 4... | StarcoderdataPython |
1635528 | <reponame>coocos/advent-of-code-2018<filename>day9.py
from collections import defaultdict
from typing import DefaultDict
def play(player_count: int, last_marble: int) -> int:
"""
An awfully inefficient solution to the marble problem. What
makes this solution bad is the fact that Python lists do not
pr... | StarcoderdataPython |
185354 | from rstem.mcpi import minecraft, control, block
import time
from random import randint
control.show(hide_at_exit=True)
mc = minecraft.Minecraft.create()
ARENA_WIDTH = 3
GOLD_DEPTH = 0
gold_pos = mc.player.getTilePos()
gold_pos.x += randint(-ARENA_WIDTH, ARENA_WIDTH)
gold_pos.z += randint(-ARENA_WIDTH, ARENA_WIDTH)... | StarcoderdataPython |
48539 | from corehq.apps.commtrack.helpers import make_supply_point
from corehq.apps.commtrack.tests.util import CommTrackTest, make_loc
from corehq.apps.commtrack.const import DAYS_IN_MONTH
from corehq.apps.locations.models import Location
from corehq.apps.locations.bulk import import_location
from mock import patch
from core... | StarcoderdataPython |
1644377 | #!/usr/bin/python3
import argparse
import socket
DEFAULT_TARGET_PORT = 9
DEFAULT_TARGET_IP = '255.255.255.255'
def is_magic_packet(data):
"""
Checks if a packet is a magic packet, returns
True or False.
Args:
data (bytes): the payload from a packet
"""
# convert data to lowercase h... | StarcoderdataPython |
1616731 | <reponame>Shiro-Nakamura/Hacking
import socket
HOST = '127.0.0.1'
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
print("[+] start listen on {}".format((HOST,PORT)))
s.listen(1)
conn, addr = s.accept()
banner = 'simple tcp server'
conn.send(banner.en... | StarcoderdataPython |
1788862 | from base import BaseTrain
from tqdm import trange
import numpy as np
import logging
import time
from utils.utils import denorm
import skimage.io
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
# TODO: change tensorboard summaries to appropriate tags, generate sample of image and write to disk every _ epochs
cl... | StarcoderdataPython |
1774375 | from .cardPoolItemConfig import CardPoolItem
from .cardPoolProbabilityConfig import CardPoolProbability
from .userInfo import UserInfo
| StarcoderdataPython |
3221473 | <reponame>xbabka01/retdec-regression-tests<filename>tools/fileinfo/bugs/sha1-hash-segfault/test.py
from regression_tests import *
class Test(Test):
settings = TestSettings(
tool='fileinfo',
args='--json --verbose',
input='08A2437BFE40329F132CD98CA1988CB13B0F32E8CE57FEBDD3CA0A6B641219D4.dat... | StarcoderdataPython |
1640391 | <gh_stars>0
"""
@Project : DuReader
@Module : tokenizer.py
@Author : Deco [<EMAIL>]
@Created : 5/22/18 5:00 PM
@Desc :
"""
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
# import nltk
#
# nltk.download('punkt')
if __name__ == '__main__':
print(word_tokenize('Hello... | StarcoderdataPython |
1735847 | <reponame>MathiasSeguy-Android2EE/MigrationProjetsA2ee
#https://dl.google.com/dl/android/maven2/index.html
findreplace = [
('materialVersion','2.0.0-rc01'),
('core_commonVersion','2.0.0-rc01'),
('coreVersion','2.0.0-rc01'),
('core_testingVersion','2.0.0-rc01'),
('core_runtimeVersion','2.0.0-rc01'),
('lifecycle_c... | StarcoderdataPython |
3302559 | <reponame>tombh/deis
# -*- coding: utf-8 -*-
"""
Django admin app configuration for Deis API models.
"""
from __future__ import unicode_literals
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from .models import App
from .models import Build
from .models import Config
from .models imp... | StarcoderdataPython |
1627456 | <reponame>wemerson-henrique/kivy<filename>kivyeExemplosDocumentacao/view/exemplo1.py
#codigo ganbiarra
import os
os.environ['KIVY_GL_BACKEND'] = 'angle_sdl2'
#codigo ganbiarra
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
... | StarcoderdataPython |
3273255 | import jax.numpy as np
def chebval(x, c, tensor=True):
"""
Evaluate a Chebyshev series at points x.
If `c` is of length `n + 1`, this function returns the value:
.. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)
The parameter `x` is converted to an array only if it is a tuple or a
... | StarcoderdataPython |
157284 | # Generated by Django 3.2.3 on 2021-09-15 12:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ledgerapp', '0005_auto_20210909_1505'),
]
operations = [
migrations.AlterField(
model_name='entry',
name='account',
... | StarcoderdataPython |
3289563 | <reponame>WTRMQDev/leer<gh_stars>1-10
import functools
from secp256k1_zkp import PublicKey, ALL_FLAGS
import hashlib, base64
class Excess:
'''
Excess is public key with proof that it is public key (signature).
'''
def __init__(self, recoverable_signature=None, message=b'', version=0, raw=None):
... | StarcoderdataPython |
3380698 | #!/usr/bin/env python3
# via https://github.com/nicodv/kmodes/blob/master/kmodes.py
# copy-pasted on 2014-06-18
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__license__ = 'MIT'
__version__ = '0.8'
import random
import numpy as np
from collections import defaultdict
class KModes(object):
def __init__(self, k):
... | StarcoderdataPython |
1690779 | <reponame>PFedak/DAKompiler<filename>Cform.py
from symbolify import InstrResult as IR, Context
import basicTypes
import algebra
indent = ' '*4
def cformat(exp, spec):
if exp.op == '.' and isinstance(exp.args[0].type, basicTypes.Pointer):
return '{}->{}'.format(exp.args[0], exp.args[1])
def dummy(*args):
... | StarcoderdataPython |
1623019 | from random import random, shuffle
from copy import deepcopy
from math import sqrt
from utils.func import get_k_idx
class GAMutation(object):
"""
Class for providing an interface to easily extend the behavior of mutation operation.
"""
def __init__(self, mutation_rate=0.02):
self.mutation_ra... | StarcoderdataPython |
3266109 | #!/usr/bin/env python
"""
createCopyNumberStatsFacetedPlot.py
5 April 2011
dent earl dearl (a) soe ucsc edu
used in the assemblathon report project to
create a plot of excess, deficient and total copy bases
from a single copy stats xml file.
"""
##############################
# Copyright (C) 2009-2011 by
# <NAME> (<... | StarcoderdataPython |
3382974 | from collections import defaultdict
import csv
import json
import sys
def load_csv(file):
with open(file) as f:
yield from csv.DictReader(f)
def json_schema(schema_path):
fields = load_csv(schema_path + "field.csv")
enums = defaultdict(list)
for enum in load_csv(schema_path + "enum.csv"):
... | StarcoderdataPython |
170309 | <gh_stars>1-10
# Use dictionary
# 1-) Herhangi bir düğümü seçin, bitişikteki ziyaret edilmemiş köşeyi ziyaret edin,
# ziyaret edildi olarak işaretleyin, görüntüleyin ve bir sıraya ekleyin.
# 2-) Kalan bitişik tepe noktası yoksa, ilk tepe noktasını kuyruktan çıkarın
# 3-) Sıra boşalana veya istenen düğüm buluna... | StarcoderdataPython |
1618572 | '''
Created on Apr 24, 2013
@author: Chris
'''
import group, unit, trait, hexcrawl.player_type as player_type
import random
HORDE_RANGE = 3
HORDE_AGGRESSION = 3
HORDE_DELAY_BY_LEVEL = [3, 8, 14, 20, 24, 28, 32, 38]
horde_types_by_name = {}
class HordeType(object):
def __init__(self, name, leader_name, leve... | StarcoderdataPython |
3268624 | # -- coding:utf-8--
def hi(name,age,sex = "无性别的"):
print("hello!" + name)
print("你今年" + age + "岁了")
print("你是个" + sex + "孩子")
hi("宫逸君","15","女")
hi(age = "150" , name = '汪文博', sex = "狼")#先列出没有预设的
hi("汪文博","233333")
| StarcoderdataPython |
127214 | import _curses
from yacui import View
from fatjira import IncrementalSearch
from fatjira.views import IssueView
def extract_issue(issue):
"Experimental issue extractor"
f = issue['fields']
parts = [
issue['key'],
"k=" + issue['key'],
f['summary'] or "",
f['description'] or... | StarcoderdataPython |
1784235 | import os
from mkultra.soft_prompt import SoftPrompt
import torch
import json
def test_json(inference_resources):
model, tokenizer = inference_resources
# Arrange
sp_a = SoftPrompt.from_string(" a b c d e f g", model=model, tokenizer=tokenizer)
# Act
sp_str = sp_a.to_json()
sp_b = SoftPrompt.... | StarcoderdataPython |
4828005 | <reponame>mil-ad/stui<filename>stui/views/nodes.py
import urwid
import stui.widgets as widgets
class NodesTab(object):
def __init__(self, cluster):
super().__init__()
self.cluster = cluster
w = urwid.Text("Nodes: Under Construction ...")
w = urwid.Filler(w)
self.view = ... | StarcoderdataPython |
89700 | <gh_stars>1-10
#coding:utf-8
#
# id: bugs.core_6144
# title: Inconsistent behaviour of the NEW context variable in AFTER UPDATE OR DELETE triggers
# decription:
# Confirmed problem on: 4.0.0.1607, 3.0.5.33171 and 2.5.9.27143: new.v was assigned to 1 in AD trigger.
# ... | StarcoderdataPython |
147631 | <reponame>JasonJW/SinbadCogs
import os
import discord
import asyncio
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from .utils import checks
from cogs.utils.chat_formatting import box, pagify
class PermHandler:
"""
Save myself time with managing an alliance discord
"""
__autho... | StarcoderdataPython |
1709167 | <filename>config.py
def hic_ame_keyword(i):
return "hic" == i['message'].lower() or \
":_hic1::_hic2::_hic3:" == i['message']
def hic_ubye_keyword(i):
# this is enough in chinese chat
return "hic" in i['message'].lower()
| StarcoderdataPython |
3298662 | # Generated by Django 3.1.2 on 2021-10-22 23:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('abastece', '0014_producto_porcentaje_aporte'),
]
operations = [
migrations.AlterField(
model_name='producto',
name='... | StarcoderdataPython |
37160 | from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from animais.models import Animal
class AnimaisTestCase(LiveServerTestCase):
def setUp(self):
chrome_options = Options()
chrome_options.add_argument('--headless')
... | StarcoderdataPython |
35498 | <reponame>bhaving07/pyup
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2017 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of t... | StarcoderdataPython |
1706178 | <reponame>pbellec/SUITPy
# -*- coding: utf-8 -*-
"""Functions related to the documentation.
@author: maedbhking
docdict contains the standard documentation entries
used across SUITPy (source: Nilearn and Eric Larson and MNE-python team.
https://github.com/mne-tools/mne-python/blob/main/mne/utils/docs.py
"""
import s... | StarcoderdataPython |
143644 | '''ESTRUTURA DE REPETIÇÃO WHILE, LAÇOS DE REPETIÇÃO (PARTE 2)'''
print('*' * 40, '\nEquanto c < 10 faça:')
c = 0
while c < 10: #Enquanto c < 10 faça:
print(c, end=' ')
c += 1
print('END')
print('*' * 40, '\nEnquanto o valor digitado NÃO for 0 faça:')
n = 1
while n != 0: #condição de PARADA
n = int(input('D... | StarcoderdataPython |
1609943 | <reponame>rudecs/jumpscale_core7
from JumpScale import j
def cb():
from .openvstorage import OpenvStorageFactory
return OpenvStorageFactory()
j.base.loader.makeAvailable(j, 'clients')
j.clients._register('openvstorage', cb)
| StarcoderdataPython |
1764837 | from queue import Queue
myq = Queue([1,2,3,6])
print(myq.data)
myq2 = Queue([4,5,6])
def weave_queues(q_one, q_two):
if len(q_one.data) != len(q_two.data):
while len(q_one.data) < len(q_two.data):
q_one.data.append(0)
elif len(q_two.data) != len(q_one.data):
while len(q_two.data) ... | StarcoderdataPython |
3245134 | """Checkpoint averaging script."""
import argparse
import tensorflow as tf
from opennmt.utils.checkpoint import average_checkpoints
def main():
tf.logging.set_verbosity(tf.logging.INFO)
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--model_dir"... | StarcoderdataPython |
128996 | <reponame>adolli/pywinauto
"""
Uninstall script for 7zip 9.20 (64-bit)
Requirements:
- Win7 or Win8.1 x64, 64-bit Python
- pywinauto 0.5.2+
- UAC is fully disabled
"""
from __future__ import print_function
import pywinauto
pywinauto.Application().Start(r'explorer.exe')
explorer = pywinauto.Application().Connect... | StarcoderdataPython |
1743740 | # Copyright (c) 2019-2020, NVIDIA CORPORATION.
# 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... | StarcoderdataPython |
3216383 | <gh_stars>0
# Move: Contains all details about a Piece's move in the game.
# DO NOT MODIFY THIS FILE
# Never try to directly create an instance of this class, or modify its member variables.
# Instead, you should only be reading its variables and calling its functions.
from games.chess.game_object import GameObject
... | StarcoderdataPython |
3235093 | # vim: expandtab:ts=4:sw=4
from __future__ import absolute_import
import numpy as np
from sklearn.utils.linear_assignment_ import linear_assignment
import EKF
import pdb
from mbest_ilp import new_m_best_sol
from multiprocessing import Pool
from functools import partial
#from mbest_ilp import m_best_sol as new_m_best_so... | StarcoderdataPython |
1627535 | <filename>bin/bump_version.py
"""
bump __version__ = in (".py", ".md") files
and clean line endings.
"""
import re
import os
import sys
from contextlib import contextmanager
@contextmanager
def open_new(file_path, exists_ok=True):
try:
fd = os.open(file_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
... | StarcoderdataPython |
112730 | '''
Assign stellar mass/magnitude to subhalos via abundance matching.
Masses in log {M_sun}, luminosities in log {L_sun / h^2}, distances in {Mpc comoving}.
'''
# system -----
#from __future__ import division
import numpy as np
from numpy import log10, Inf
from scipy import integrate, interpolate, ndimage
# local ---... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.