id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3273163
from ticket.db import db_trans, populate_search from ticket.models import User from ticket.utils import hash_password def all_users() -> list[User]: """ Retorna a lista de todos os usuários com seus dados, para tela de administração. """ users: list[User] = [] with db_trans() as c: c.execu...
StarcoderdataPython
1725078
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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 a...
StarcoderdataPython
173535
from django import forms INTERVAL_CHOICES = [(k, k) for k in ('minutes', 'hours', 'days', 'weeks', 'months', 'years')] class StatsFilterForm(forms.Form): """Form for filtering the statistics shown in the admin interface .""" start = forms.DateTimeField() end = forms....
StarcoderdataPython
4816438
# -*- coding: utf-8 -*- """ ------------------------------------------------- date: 6/1/2020 ------------------------------------------------- Change Activity: 6/1/2020: ------------------------------------------------- """ from getData import getData import matplotlib.pyplot...
StarcoderdataPython
3326820
<gh_stars>0 from sentence_transformers import SentenceTransformer from sklearn.metrics.pairwise import cosine_similarity import sys import json as JSON import time def into_space(s): ret = '' for i in range(len(s)): ret += ' ' return ret class Model: existing_model = { 'minilm': "all...
StarcoderdataPython
1796846
"""Contains generic regular expression tests which run against the entire contents of files.""" import os import re from validator.contextgenerator import ContextGenerator from validator.decorator import define_post_init from .base import RegexTestBase class FileRegexTest(RegexTestBase): """Matches regular expre...
StarcoderdataPython
135542
# This code parses date/times, so please # # pip install python-dateutil # # To use this code, make sure you # # import json # # and then, to convert JSON from a string, do # # result = article_model_from_dict(json.loads(json_string)) from enum import Enum from dataclasses import dataclass from typing impo...
StarcoderdataPython
1651341
"""Tests for Argo checks.""" import numpy as np from numpy import ma import pytest import argortqcpy.profile from argortqcpy.checks import ArgoQcFlag, CheckOutput, PressureIncreasingCheck def test_check_is_required(fake_check): """Check that the base check is required.""" assert fake_check.is_required() d...
StarcoderdataPython
4818194
<filename>python_tips/Pytricks/namedtuple.py #!/usr/bin/python3 # -*- coding: utf-8 -*- """"""""""""""""""""""""""""""""""""""""""""""" " Filename: namedtuple.py " " Author: xss - <EMAIL> " Description: Named tuple as class " Create: 2018-08-13 11:15:19 """""""""""""""""""""""""""""""""""""""""""""...
StarcoderdataPython
170
<filename>autolatex-master/exemplos_codigo/certificados/certificados.py import os import sys import sqlite3 con = None filename = 'certificado' # Abrir banco de dados para ler nomes. try: con = sqlite3.connect('math.db') cur = con.cursor() cur.execute('select * from math') data = cur.fetchall() e...
StarcoderdataPython
1619395
<reponame>awoo424/algotrading<gh_stars>1-10 from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import Contract import threading import time class App(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def historicalData(self, reqId, bar): ...
StarcoderdataPython
3295368
<gh_stars>1-10 import typing as t from loguru import logger __all__ = ('resolve', ) def resolve( components: t.Dict[str, t.Any], ref: t.Optional[str] = None, ) -> t.Dict[str, t.Any]: raw_schema: t.Dict[str, t.Any] = {} while ref is not None: _, component, name = ref.replace('#/', '').split('...
StarcoderdataPython
77407
# encoding: utf-8 # # Task worker - design 2 # Adds pub-sub flow to receive and respond to kill signal # # Author: <NAME> (brainsik) <spork(dash)zmq(at)theory(dot)org> # import sys import time import zmq context = zmq.Context() # Socket to receive messages on receiver = context.socket(zmq.PULL) receiver.connec...
StarcoderdataPython
3216564
import collections import datetime import itertools import math import re import statistics from ipaddress import IPv4Address from operator import itemgetter, attrgetter from os.path import dirname from pathlib import Path from typing import List, Dict, TextIO, Tuple, Sequence, Optional, Any, Callable, NamedTuple from...
StarcoderdataPython
3231066
""" _SetupCMSSWPset_ Create a CMSSW PSet suitable for running a WMAgent job. """ from __future__ import print_function from builtins import next, object import json import logging import os import pickle import socket from PSetTweaks.PSetTweak import PSetTweak from PSetTweaks.WMTweak import makeJobTweak, makeOutpu...
StarcoderdataPython
4834148
<reponame>bopopescu/sage<filename>src/sage/tests/benchmark.py """ Benchmarks COMMENTS: Taken as a whole these benchmarks suggest that by far the fastest math software is MAGMA, Mathematica, and Sage (with appropriate tuning and choices -- it can also be very slow !). Maxima is very slow, at least in the form that c...
StarcoderdataPython
49925
if True: import numpy as np d = 3 K = 50 N = 10 ** 6 a = np.zeros(3) b = np.ones(3) orders = np.array([K for i in range(d)]) coeffs = np.random.random([k + 2 for k in orders]) points = np.random.random((N, d)) # each line is a vector points_c = points.T.copy() # each column i...
StarcoderdataPython
3257604
<gh_stars>0 from uuid import uuid4 from rdflib import Literal, URIRef from rdflib.namespace import RDF, XSD from utils.graph import create_bound_graph, QEX, OTD # Helper method to create a link between a dataset and a concept with # a given similarity-score # TODO: Write full doc # TODO: Refactor into central place...
StarcoderdataPython
3224689
#!/usr/bin/env python3 #encoding=utf-8 #--------------------------------------------- # Usage: python3 7-manage-instance-deco.py # Description: class decorator to trace external instance attribute fetches #--------------------------------------------- def tracer(klass): # on @ decorator class Wrapp...
StarcoderdataPython
3331649
<filename>helper_classes.py from botorch.acquisition import MCAcquisitionObjective from botorch.models.model import Model from botorch.posteriors import Posterior from botorch.sampling.samplers import MCSampler, SobolQMCNormalSampler from torch import Tensor class PosteriorMeanDummySampler(MCSampler): def __init_...
StarcoderdataPython
177298
# Copyright (c) 2016-present, Facebook, 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...
StarcoderdataPython
4805039
km = float(input('Insira a distância a ser percorrida (km) : ').strip()) if km <= 200: print('O total a pagar é R$ {:.2f} '.format(km*0.5)) else: print('O total a pagar é R$ {:.2f} '.format(km*0.45))
StarcoderdataPython
3393543
<gh_stars>1-10 # -*- coding: utf-8 -*- from django.db import models READ = 'RD' WRITE = 'WT' DELETE = 'DE' class PermissionManager(models.Manager): def get_permissions(self, permissions): if set([READ, WRITE, DELETE]).issubset(permissions): return self.none() return self.filter( ...
StarcoderdataPython
177804
<reponame>Pandinosaurus/videoavatars<gh_stars>100-1000 #!/usr/bin/env python2 # -*- coding: utf-8 -*- import logging __all__ = ['log'] FORMAT = "%(asctime)s [%(filename)s:%(funcName)s:%(lineno)d] %(message)s" log = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO, format=FORMAT)
StarcoderdataPython
3337335
from collections import defaultdict N, NUM_EDGES, Q = [int(x) for x in input().split()] edges = defaultdict(list) for i in range(NUM_EDGES): v1, v2 = [int(x) for x in input().split()] edges[v1].append(v2) edges[v2].append(v1) colors = [int(x) for x in input().split()] for i in range(Q): # print(colors)...
StarcoderdataPython
1778830
from fastapi import APIRouter, Depends from apps.climsoft.services import stationlocationhistory_service from apps.climsoft.schemas import stationlocationhistory_schema from utils.response import get_success_response, get_error_response from apps.climsoft.db.engine import SessionLocal from sqlalchemy.orm.session import...
StarcoderdataPython
3309418
import threading def sum_and_product(a, b): s, p = a + b, a * b print(f'{a}+{b}={s}, {a}*{b}={p}') t = threading.Thread( target=sum_and_product, name='SumProd', args=(3, 7) ) t.start() """ $ python start.py 3+7=10, 3*7=21 """
StarcoderdataPython
1705497
from behave import ( given, when, then, ) from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.common.action_chains import...
StarcoderdataPython
3275634
<reponame>comicdipesh99/Python-basics a,b = 0,1 while a < 20: print a a,b = b,a+b
StarcoderdataPython
1657128
import math import tkinter import beepy print('Classic Beepy Timer') def counter(count): secs = math.floor(count % 60) mins = math.floor((count / 60) % 60) hrs = math.floor((count / 3600)) label['text'] = f'Hours: {str(hrs)} Minutes: {str(mins)} Seconds: {str(secs)}' if count >= 0: gui_w...
StarcoderdataPython
179228
# Generated by Django 2.2.24 on 2021-11-01 03:46 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="TaskflowExecutedNodeStatistics", fields=[ ("id"...
StarcoderdataPython
1607347
import tkinter as tk from tkinter.font import BOLD import board import digitalio import adafruit_max31865 # Create sensor object, communicating over the board's default SPI bus spi = board.SPI() cs = digitalio.DigitalInOut(board.D5) # Chip select of the MAX31865 board. #sensor = adafruit_max31865.MAX31865(spi, cs) # ...
StarcoderdataPython
144121
class RPGinfo(): author = 'BigBoi' def __init__(self,name): self.title = name def welcome(self): print("Welcome to " + self.title) @staticmethod def info(): print("Made using my amazing powers and Raseberry Pi's awesome team") @classmethod def credits(c...
StarcoderdataPython
177105
#!./venv/bin/python from flask import Flask, render_template # creates the app instance using the name of the module app = Flask( __name__, template_folder='templates' ) print(__name__, " app created.") # DEBUG ONLY # https://replit.com/talk/learn/Flask-Tutorial/36529 @app.route('/') # Route the Function def ma...
StarcoderdataPython
1702407
<gh_stars>0 import openpyxl import openpyxl.chart from util.data import DataSet from typing import Union class CmplCdatReader: """Provides a converter from CMPL .cdat data files to DataSet instances. """ @staticmethod def read(filename: str) -> DataSet: """ Reads a .cdat file as used ...
StarcoderdataPython
1704553
# df_overview.pyのテスト import numpy as np import pandas as pd import sys sys.path.append('../') import df_overview df = pd.read_csv('test1.csv') ov = df_overview.df_overview(df) colSum = ov.cols_summary() colSum.to_csv('test1_result.csv', index=False)
StarcoderdataPython
29367
<reponame>Data-Mechanics/bps-simulated-students """ grid.py Module containing class for working with a street grid. """ import json import geojson import geopy.distance import shapely.geometry from geoql import geoql import geoleaflet import folium import rtree import networkx from tqdm import tqdm class Grid(): ...
StarcoderdataPython
3341556
<filename>resources/lib/settingsCommandline.py # -*- coding: utf-8 -*- # SPDX-License-Identifier: MIT """ The base settings module Copyright 2020, Mediathekview """ from resources.lib.settingsInterface import SettingsInterface class SettingsCommandline(SettingsInterface): """ Standalone implementation of the se...
StarcoderdataPython
1634912
<reponame>mayank-sfdc/dpu-utils import logging import os from collections import Counter from tempfile import TemporaryDirectory from typing import List, Optional, Sized, Union, Iterable import sentencepiece as spm import typing __all__ = ['BpeVocabulary'] SPIECE_UNDERLINE = u'▁' class BpeVocabulary(Si...
StarcoderdataPython
195445
<reponame>baverman/scribes-goodies def append_attr(obj, attr, value): """ Appends value to object attribute Attribute may be undefined For example: append_attr(obj, 'test', 1) append_attr(obj, 'test', 2) assert obj.test == [1, 2] """ try: getatt...
StarcoderdataPython
3373332
# -*- coding: utf-8 -*- ''' | 关联规则-Apriori算法实现 | | 关联规则分析(挖掘)用于发现项目或项目集合之间可能“频繁”出现的“紧密”关联模式(或因果结构), | 如“由于某些事件的发生而引起另外一些事件的发生”之类的规则。“频繁”和“紧密”程度通过 “支持度”和“置信度”来度量。 | 一个被津津乐道的案例是通过关联规则挖掘发现“买尿布的年轻父亲通常也会顺便为自己买啤酒”。 | | 关联规则数据集示例: | 编号, 交易清单 | 001, 可乐 & 鸡蛋 & 香肠 | 002, 可乐 & 尿布 & 啤酒 | 003, 可乐 & 尿布 & 啤酒 & 香肠 | 004, 尿布 & 啤酒 | ...
StarcoderdataPython
3363034
<filename>vigibot/trainers.py from chatterbot.trainers import Trainer from chatterbot import languages from chatterbot.conversation import Statement from chatterbot import utils import spacy import string import os class InfodengueCorpusTrainer(Trainer): """ Allows the chat bot to be trained using data from th...
StarcoderdataPython
3364311
import cv2 import numpy as np img = cv2.imread('C:/Users/Hardik/Documents/OpeCV/Tut9/eye.jpg',0) ret,thresh = cv2.threshold(img,127,255,0) image, contours, hierarchy= cv2.findContours(thresh,1,2) cnt = contours[0] area = cv2.contourArea(cnt) print "Area",area M = cv2.moments(cnt) #print M prin...
StarcoderdataPython
20269
#CIFAR from tensorflow import keras import numpy as np import matplotlib.pyplot as plt data = keras.datasets.cifar10 activations=[keras.activations.sigmoid, keras.activations.relu, keras.layers.LeakyReLU(), keras.activations.tanh] results=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] class_names=[0,1,2,3,4,5,6,7,8,9] ...
StarcoderdataPython
187561
import math import torch import torch.nn as nn from pytracking import TensorList from ltr.models.layers import activation class GNSteepestDescent(nn.Module): """General module for steepest descent based meta learning.""" def __init__(self, residual_module, num_iter=1, compute_losses=False, detach_length=float...
StarcoderdataPython
1726475
import urllib from collections import namedtuple import requests from django.utils.http import urlquote # There are some amazing APIs to query product information # like: # * https://www.semantics3.com # * http://www.simpleupc.com/ # - but those are enormously expensive :'(' # More UPC integration ideas: # # * h...
StarcoderdataPython
4809368
<gh_stars>1-10 #!/usr/bin/env python # Copyright (c) 2016 <NAME> <<EMAIL>> # # 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...
StarcoderdataPython
1725765
# Monitors a directory and if it sees a file or files newer that some time, # create a manifest and send a message to the message queue. from utils.dirmon import checkDir, find_most_recent from utils.manifest import generateFileManifest from utils.data_utils import excel_to_csv from utils.archive import archive import...
StarcoderdataPython
1670744
# # KSP server configuration # # *** Don't forget to restart KSP after modifying this file! *** # # Port on which to listen. The default value is recommended, unless you want to tweak your setup in a certain way. server_port = 45350 # IP to bind to, leave empty to bind to all network interfaces. server_host = '' # i...
StarcoderdataPython
84224
#!/usr/bin/env python from local_settings import PORT, PASSWORD from threading import Thread import logging import select import SocketServer import time logger = logging.getLogger("socket-state-server") logger.setLevel(logging.INFO) format_string = "%(asctime)s - %(client_ip)s:%(client_port)s - %(levelname)s - %(me...
StarcoderdataPython
1629052
<filename>cellulariot/SDL_Pi_HDC1000.py<gh_stars>10-100 # # SDL_Pi_HDC1000 # Raspberry Pi Driver for the SwitchDoc Labs HDC1000 Breakout Board # # SwitchDoc Labs # January 2017 # # Version 1.1 #constants # I2C Address HDC1000_ADDRESS = (0x40) # 1000000 # Registers HDC1000_TEMPERATURE_REGIST...
StarcoderdataPython
3381860
""" Adams2AbaqusRun.py, version 1.1.0 For use with Abaqus 6.13-1 (Python 2.6.2). Created by <NAME> <<EMAIL>> - The script which is responsible from running the created Abaqus deck. """ import sys, os, time from Adams2AbaqusPost import * def runAbaqus(superRef,anchoredPart,includeAnchoredP...
StarcoderdataPython
129348
<reponame>wliuxingxiangyu/HackingNeuralNetworks # -*- coding: utf-8 -*- ''' Please read the README.md for Exercise instructions! This code is a modified version of https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py If you want to train the model yourself, just head there and run the example. Don...
StarcoderdataPython
24419
# Copyright 2018 <NAME>. 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 applicable law or agree...
StarcoderdataPython
3306804
from __future__ import annotations from pathlib import Path from ferrite.components.cmake import CmakeRunnable from ferrite.components.conan import CmakeWithConan from ferrite.components.toolchain import Toolchain class CoreTest(CmakeWithConan, CmakeRunnable): def __init__( self, source_dir: Pa...
StarcoderdataPython
36069
import json import numpy as np import os import tensorflow as tf from keras.models import Sequential from keras.layers import Dense, Dropout, Embedding, Flatten, Activation, BatchNormalization from sklearn.model_selection import train_test_split class SuggestionModeler(object): """ A collection of functions ...
StarcoderdataPython
93853
from tornado.httputil import HTTPServerRequest def query_argument_contains_string(request: HTTPServerRequest, query_argument_name: str, containing_value: str) -> bool: return containing_value in str(request.query_arguments[query_argument_name][0])
StarcoderdataPython
3234235
<filename>src/training/training_manager-tfdata.py import os import shutil import pandas as pd import tensorflow as tf import gc from sklearn import preprocessing from src.data_process.config_paths import DataPathsManager from src.training.training_config import TrainingSetup, TrainingParams from training.trai...
StarcoderdataPython
3391044
<reponame>shinoyuki222/torch-light import argparse import os import torch import torch.optim as optim import numpy as np from darknet import DarkNet from img_loader import Data_loader from utils import load_classes, predict, evaluate parser = argparse.ArgumentParser(description='YOLO-v3 Train') parser.add_argument(...
StarcoderdataPython
1766875
<filename>kubernetes_typed/client/models/v1beta1_flow_schema_spec.py # Code generated by `typeddictgen`. DO NOT EDIT. """V1beta1FlowSchemaSpecDict generated type.""" from typing import TypedDict, List from kubernetes_typed.client import V1beta1FlowDistinguisherMethodDict, V1beta1PolicyRulesWithSubjectsDict, V1beta1Pri...
StarcoderdataPython
3359036
#!/usr/bin/env python # # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import azure.functions as func from onefuzztypes.enums import ErrorCode, ScalesetState from onefuzztypes.models import Error from onefuzztypes.requests import ( ScalesetCreate, ScalesetSearch, ScalesetStop, ...
StarcoderdataPython
1651675
from SCons.Script import BoolVariable, Dir, Environment, File, SCons, Variables def can_build(env, platform): return True def configure(env): envvars = Variables() envvars.Add(BoolVariable('builtin_runtime', 'Use the built-in libraries', True)) envvars.Add(BoolVariable('use_graphite2', 'Enable Graphit...
StarcoderdataPython
4834044
<reponame>WillemWybo/Electrical_compartmentalization_in_neurons import matplotlib # matplotlib.use("Agg") import matplotlib.pyplot as pl import matplotlib.animation as manimation from matplotlib.gridspec import GridSpec from matplotlib.patches import Rectangle from mpl_toolkits.axes_grid1 import make_axes_locatable fro...
StarcoderdataPython
3251132
<filename>src/ot_sparse_projection/log_utils.py<gh_stars>0 import sys def get_logger(verbose, indent_level=0, period=1): """ A factory for a log function object This function allows to set a log level format once and for all without having to use if statements everywhere. Args: verbose: an int o...
StarcoderdataPython
47270
#@ util help util.help() #@ util help, \? [USE:util help] \? util #@ util check_for_server_upgrade help util.help('check_for_server_upgrade') #@ util check_for_server_upgrade help, \? [USE:util check_for_server_upgrade help] \? check_for_server_upgrade # WL13807-TSFR_1_1 #@ util dump_instance help util.help('dump_i...
StarcoderdataPython
3355023
<gh_stars>0 ''' Provides function that will plot the reconstructed magnetic field caluctlated from the alogrithm in recconstruct.py ''' import math import sys import os.path import rad_ut as ru from constants import M_PROTON_G, ESU, C, V_PER_E import matplotlib as mpl mpl.use('Agg') # Headless plotting (avoids pyt...
StarcoderdataPython
123129
"""Unit test package for aws_data_toolkit."""
StarcoderdataPython
29236
<filename>homepage/views.py<gh_stars>0 from django.http import Http404, JsonResponse from django.shortcuts import render from chatbot.chatbot import create_chatbot import threading import pickle import collections from io import BytesIO import numpy as np import urllib.request import json import wave import librosa imp...
StarcoderdataPython
3240473
import itertools from random import shuffle from typing import List from colorama import Back, Style from .flask import Flask class Game: def __init__(self, initial_flasks: list = None, n_empty: int = 2, n_full: int = 4): self.__n = n_empty + n_full if initial_flasks is None: it = rang...
StarcoderdataPython
3256678
<reponame>317brian/rando-scripts #!/usr/bin/env python3 # /Users/brianle/rando-scripts/github-open-modified-files.py /usr/local/bin/ghpr import sys, pyperclip, os # Get the latest copy of the repo. os.system("git checkout master || git checkout main") os.system("git pull --rebase") if len(sys.argv) > 1: branch_n...
StarcoderdataPython
1618746
# Explains different data type conversions in python. number = input('Give a number: '); number = int(number, 10); print('Converting to an integer', number); print('Converting to a floating point', float(number)); print('Converting to a complex number', complex(number, 1)); print('Converting to a character', chr(numbe...
StarcoderdataPython
1731759
try: # this is temporary, remove when tests are moved in a separate folder import sys from os.path import dirname, abspath sys.path.append(dirname(dirname(abspath(__file__)))) except Exception as e: print(e) try: from unittest import TestCase import unittest from math import sqrt,...
StarcoderdataPython
1650073
#!/usr/bin/env python # # This library is free software, distributed under the terms of # the GNU Lesser General Public License Version 3, or any later version. # See the COPYING file included in this archive # # The docstrings in this module contain epytext markup; API documentation # may be created by processing this...
StarcoderdataPython
3271238
class DriverError(Exception): """Base class for driver-specific errors.""" class ConnectionFailed(DriverError): """A Connection error occurred.""" class Timeout(DriverError): """The request timed out."""
StarcoderdataPython
156891
#!/usr/bin/env python # -*- coding: utf-8 -*- """Includes the EPrime data source class.""" # TODO(janmtl): Provide an interface that deuglifies the _0 and channels in this # interface import pandas as pd import io import numpy as np from data_source import DataSource from schema import Schema, Or from utils import me...
StarcoderdataPython
1739585
# Install the python extension for VS Code # (https:#marketplace.visualstudio.com/items?itemName=ms-python.python). # The Debug Visualizer has no support for Python data extractors yet, # so to visualize data, your value must be a valid JSON string representing the data. # See readme for supported data schemas. from ...
StarcoderdataPython
1671586
# -*- coding: utf-8 -*- import scrapy from ..items import ImgItem class YunqiSpider(scrapy.Spider): name = 'yunqi' allowed_domains = ['yunqi.qq.com'] start_urls = ['http://yunqi.qq.com/bk/so2/n10p1'] def parse(self, response): """解析一级页面""" urls = response.xpath('//div[@class="book_inf...
StarcoderdataPython
1678752
import streamlit as st import backend as app import os def header(): """ """ st.markdown('# ADS bibtex extractor') st.text('Please provide the API token and bibcode in the sidebar') st.sidebar.markdown('# Input variables') def main(): """ Set up the streamlit application """ #...
StarcoderdataPython
3353902
from __future__ import absolute_import import responses from exam import fixture from mock import patch from social_auth.models import UserSocialAuth from sentry.models import Integration, OrganizationIntegration, Repository from sentry.testutils import PluginTestCase from sentry.utils import json from sentry_plugin...
StarcoderdataPython
1620401
""" Parts of the code are adapted from https://github.com/akanazawa/hmr """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import torch def compute_similarity_transform(S1, S2): """ Computes a similarity transform (sR, t) that ta...
StarcoderdataPython
1774941
import pyipmi import pyipmi.interfaces import time import os import glob import os.path as path import shutil import math import numpy import mmap import array import getopt import sys from os_parameters_define import * from utility_function import * from nm_ipmi_raw_to_str import * from error_messages_define import *...
StarcoderdataPython
1605642
from collections import namedtuple ''' A datatype defining either an array of qubits or classical bits. These are defined in-program using the following syntax: (def blocka 1 2) # A two-qubit block using qubits one and two (def blockb 1 3) # Qubits 1-3 (def blockc 1 2 classical) # Classical two-bit block f...
StarcoderdataPython
3216914
<reponame>NemoNessuno/BattleForBerlin<filename>auth/app.py import os import bcrypt from flask import Flask, session, render_template, request, redirect def get_hash(): if os.environ.get('FLASK_DEBUG') == 1: return None filename = os.environ.get('HASH_FILE', './hash.txt') with open(filename, 'rb') a...
StarcoderdataPython
3246288
import numpy as np from scipy.stats import multivariate_normal from to.probabilistic_model import ProbabilisticModel from evolution import chromosome as evolution from copy import deepcopy class MixtureModel(object): def __init__(self, allModels, alpha=False): self.model_list = allModels.copy() ...
StarcoderdataPython
1735200
<filename>post.py class Post(): def __init__(self, title, subtitle, author, date, id): self.title = title self.subtitle = subtitle self.author = author self.date = date self.id = id
StarcoderdataPython
3337541
<filename>advocacy_project/settings/production.py from .base import * import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn=os.getenv('SENTRY_SDK'), integrations=[DjangoIntegration()], traces_sample_rate=1.0, send_default_pii=True ) DEBUG = False ALLOWED_...
StarcoderdataPython
9691
<gh_stars>0 # Copyright 2020 The FastEstimator 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 requ...
StarcoderdataPython
1715831
from functools import wraps import json import sys from flask import jsonify, request from ocd_frontend.factory import create_app_factory from ocd_frontend.helpers import root_path, put_mapping_template def create_app(settings_override=None): """Returns the REST API application instance.""" app = create_app...
StarcoderdataPython
20380
""" * 보석과 돌 J는 보석이며, S는 갖고 있는 돌이다. S에는 보석이 몇 개나 있을까? 대소문자는 구분한다. - Example 1 Input : J = "aA", S = "aAAbbbb" Output : 3 - Example 2 Input : J = "z", S = "ZZ" Output : 0 """ import collections class Solution: # Counter로 계산 생략 def numJewelsInStones(self, J: str, S: str) -> int: freqs = collections.Count...
StarcoderdataPython
3247010
<reponame>Mr-Sheep/naiveproxy # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import common import json import logging import os import shutil import subprocess import tempfile import time import urllib2 ...
StarcoderdataPython
3359789
<reponame>unicef/un-partner-portal<filename>backend/unpp_api/apps/common/utils.py from django.conf import settings from rest_framework import serializers def get_countries_code_from_queryset(queryset): from common.serializers import CountryPointSerializer return list(set(map(lambda x: x.get("country_code"), C...
StarcoderdataPython
181278
<reponame>KuiyuanFu/PythonLeetCode<gh_stars>0 # @lc app=leetcode id=736 lang=python3 # # [736] Parse Lisp Expression # # https://leetcode.com/problems/parse-lisp-expression/description/ # # algorithms # Hard (50.40%) # Likes: 364 # Dislikes: 281 # Total Accepted: 17.2K # Total Submissions: 34K # Testcase Example:...
StarcoderdataPython
3266365
# Copyright 2017 <NAME> # # 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 the above copyright notice, this list of conditions and the following disclaimer. # # 2. Redistrib...
StarcoderdataPython
120252
<reponame>ilya16/graph-db from typing import List from graph_db.engine.label import Label from graph_db.engine.node import Node from graph_db.engine.relationship import Relationship from graph_db.engine.types import * from .record import Record class RecordEncoder: @staticmethod def encode_node(node: Node) -...
StarcoderdataPython
109675
<filename>test.py # x = y = 1 # y = 2 # print(x, y) #coding = utf-8 import pandas as pd import networkx as nx import matplotlib.pyplot as plt df = pd.read_csv('edge.txt',sep='\t', encoding='latin1') lst = [] '''''' for i in range(df.shape[0]): a, b, c = df['a'][i], df['b'][i], df['c'][i] lst.append((a,b,c)...
StarcoderdataPython
3241777
# -*- coding:utf-8 -*- from django.db import connections from django.test import TestCase class IsMariaDBTests(TestCase): def test_connections(self): for alias in connections: connection = connections[alias] if not hasattr(connection, 'mysql_version'): continue ...
StarcoderdataPython
3256588
import sys import socket import psutil import subprocess import multiprocessing import threading import time import os import signal import traceback from robolearn.old_envs.gazebo_ros_env_interface import GazeboROSEnvInterface init_roscore_port = 11312 init_gzserver_port = 11347 class RosGazebo(multiprocessing.Pro...
StarcoderdataPython
3291614
import redis from app.settings import REDIS_HOST, REDIS_PORT, REDIS_DB class redisDB: def __init__(self): self.db = redis.StrictRedis( host=REDIS_HOST, port=REDIS_PORT, socket_connect_timeout=20, db=REDIS_DB ) db = redisDB().db
StarcoderdataPython
142836
#!/usr/bin/env python3 import sys, os from glob import glob files = glob(os.path.join(sys.argv[1], '*.tmp')) assert len(files) == 1 with open(files[0]) as ifile, open(sys.argv[2], 'w') as ofile: ofile.write(ifile.read())
StarcoderdataPython
1768449
<filename>tests/conftest.py<gh_stars>0 """Defines fixtures available to all tests.""" # pylint: disable=redefined-outer-name,too-few-public-methods,invalid-name import os import shutil import pytest import webtest as wt from passaas.app import create_app from passaas.config import TestConfig, Config # These modules ...
StarcoderdataPython