text
string
size
int64
token_count
int64
# Copyright 2014 Google Inc. All Rights Reserved. """Commands for reading and manipulating HTTP health checks.""" from googlecloudsdk.calliope import base class HttpHealthChecks(base.Group): """Read and manipulate HTTP health checks for load balanced instances.""" HttpHealthChecks.detailed_help = { 'brief': ...
410
116
##!/usr/bin/python # # ============================================================================ # # 06.02.18 <-- Date of Last Modification. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ---------------------------------------------------------------------------- # # BASIC TASK WRAPPER # # Command-line...
52,014
15,237
from .wideresnet import * from .wideresnet_lk import * WRN_MODELS = { 'WideResNet':WideResNet, 'WideResNet_Lk': WideResNet_Lk, }
154
66
# This script is based on moltres/python/extractSerpent2GCs.py import os import numpy as np import argparse import subprocess import serpentTools as sT def makePropertiesDir( outdir, filebase, mapFile, unimapFile, serp1=False, fromMain=False): """ Takes in a mapping...
8,954
2,703
import os from . import utils import numpy as np from scipy.stats import scoreatpercentile from scipy.optimize import curve_fit from scipy import exp import operator from copy import copy, deepcopy from collections import defaultdict, Counter import re from pyteomics import parser, mass, fasta, auxiliary as aux, achrom...
63,581
22,968
from django.conf.urls import url from django.views.generic import TemplateView from . import views urlpatterns = [ url(r"^list_signup/$", views.list_signup, name="waitinglist_list_signup"), url(r"^ajax_list_signup/$", views.ajax_list_signup, name="waitinglist_ajax_list_signup"), url(r"^survey/thanks/$", ...
1,099
428
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path from nokogiri.which_env import which_env from pickle import Unpickler class TQDMBytesReader(object): def __init__(self, fd, tqdm, total, desc=''): self.fd = fd self.tqdm = tqdm(total=total) self.tqdm.set_description(des...
1,162
410
# tests.test_contrib.test_prepredict # Test the prepredict estimator. # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Mon Jul 12 07:07:33 2021 -0400 # # ID: test_prepredict.py [] benjamin@bengfort.com $ """ Test the prepredict estimator. """ ##########################################################...
5,991
1,919
# input and print, with format strings s = input("What's your name?\n") print(f"hello, {s}")
94
35
import os, sys import numpy as np import matplotlib.pyplot as plt # Export library path rootname = "mesoscopic-functional-connectivity" thispath = os.path.dirname(os.path.abspath(__file__)) rootpath = os.path.join(thispath[:thispath.index(rootname)], rootname) print("Appending project path", rootpath) sys.path.append(...
2,259
867
''' A Gameplay Mechanic [TS4] By CozyGnomes (https://cozygnomes.tumblr.com/) This is an existing document that contains several things you can do in your gameplay on TS4. This program comes with the intention of automatically generating the related phrase without having to sear...
1,747
491
def display(a,b): print(f'a={a}') return None display(3,4) display(a=3,b=4) display(b=4,a=3)
101
57
# %% from collections import OrderedDict import dataloaders.base from dataloaders.datasetGen import SplitGen, PermutedGen train_dataset, val_dataset = dataloaders.base.__dict__["CIFAR10"]('data', False) # %% print(train_dataset) # %% train_dataset_splits, val_dataset_splits, task_output_space = SplitGen(train_data...
830
219
import sys import pyfits import numpy as np from PySpectrograph import Spectrum from PySpectrograph.Utilities.fit import interfit import pylab as pl def ncor(x, y): """Calculate the normalized correlation of two arrays""" d=np.correlate(x,x)*np.correlate(y,y) if d<=0: return 0 return np.correlate(x,y)...
4,631
2,137
################################################################################ # This is the main file for preprocessing smartphone sensor data # # # # Contributors: Anna Hakala & Ana Triana ...
62,936
19,889
# imports import visa import numpy as np import os import csv import time import datetime import tkinter as tk from tkinter.filedialog import askopenfilename, askdirectory from tkinter.ttk import Frame, Button, Style,Treeview, Scrollbar, Checkbutton from functools import partial import serial # This app uses an arduino...
15,570
5,341
#-*- coding:utf-8 -*- __author__ = "ChenJun" import theano import theano.tensor as T import numpy as np import cPickle as pickle from theano_models.qa_cnn import CNNModule from theano_models.layers import InteractLayer, MLP, MLPDropout, BatchNormLayer from theano_models.optimizer import Optimizer from data_process.load...
12,522
4,537
# Rest Server from flask import Flask, jsonify, abort, request # Eureka client from eureka.client import EurekaClient # Background tasks import threading import atexit import logging import socket import netifaces as ni import sys import os import time # Plotter libs from io import BytesIO import pymongo from pymongo ...
7,298
2,145
#Example for Jon Smirl on 28 Dec 1999, originally by Steve Muench, with improvements by Mike Brown and Jeremy Richman from Xml.Xslt import test_harness sheet_1 = """<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html> <head/> <body> <xsl:apply-template...
3,274
1,210
import tldextract from django.db.models import Q from docutils import nodes from docutils.transforms import Transform from django_docutils.favicon.models import get_favicon_model from ..nodes import icon Favicon = get_favicon_model() def resolve_favicon(url): """Given a URL to a website, see if a Favicon exist...
2,687
827
import dynet as dy import os from xnmt.serializer import Serializable class ModelContext(Serializable): yaml_tag = u'!ModelContext' def __init__(self): self.dropout = 0.0 self.weight_noise = 0.0 self.default_layer_dim = 512 self.dynet_param_collection = None self.serialize_params = ["dropout", ...
1,733
628
import csv from django.http import HttpResponse, HttpResponseForbidden from django.template.defaultfilters import slugify from django.db.models.loading import get_model def export(qs, fields=None): model = qs.model response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; ...
3,100
925
# -*- coding: utf-8 -*- # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import wx import serial # A new custom class that extends the wx.Frame class MyFrame(wx.Frame): def __init__(self, parent, title): super(MyFrame, self).__init__(parent, title=title, ...
1,668
580
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent from typing import Any, ContextManager import pytest from pants.backend.docker.subsystems.dockerfile_parser import rules a...
13,807
4,053
from .test_ai_model import TestAiModelExtension
48
15
#!/usr/bin/env python3 import logging from pathlib import Path import json from datetime import datetime, timedelta from typing import Set, Sequence, Any, Iterator from dataclasses import dataclass from .exporthelpers.dal_helper import PathIsh, Json, Res, datetime_naive from .exporthelpers.logging_helper import LazyLo...
5,100
1,523
import FWCore.ParameterSet.Config as cms from MuonAnalysis.MuonAssociators.muonL1Match_cfi import * muonHLTL1Match = cms.EDProducer("HLTL1MuonMatcher", muonL1MatcherParameters, # Reconstructed muons src = cms.InputTag("muons"), # L1 Muon collection, and preselection on that collection ...
1,287
453
lista = list() while True: lista.append(int(input("Digite um número inteiro:\t"))) while True: p = str(input("Digitar mais números?\t").strip())[0].upper() if p in 'SN': break else: print("\033[31mDigite uma opção válida!\033[m") if p == 'N': break par...
632
264
#! /usr/bin/env python # -*- coding: utf-8 -* import collections from census_data_downloader.core.tables import BaseTableConfig from census_data_downloader.core.decorators import register @register class PerCapitaIncomeDownloader(BaseTableConfig): # inflation adjusted PROCESSED_TABLE_NAME = "percapitaincome" ...
1,212
449
# Copyright 2018 Province of British Columbia # # 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...
844
268
class Solution: def intersect(self, q1, q2): if q1.isLeaf: return q1.val and q1 or q2 elif q2.isLeaf: return q2.val and q2 or q1 else: tLeft = self.intersect(q1.topLeft, q2.topLeft) tRight = self.intersect(q1.topRight, q2.topRight) ...
757
258
import Crypto.Random from Crypto.Cipher import AES import hashlib import base64 SALT_SIZE = 16 AES_MULTIPLE = 16 NUMBER_OF_ITERATIONS = 20 def generate_key(password, salt): key = password.encode('utf-8') + salt for i in range(NUMBER_OF_ITERATIONS): key = hashlib.sha256(str(key).encode('utf-8')).digest...
1,442
545
from xml.etree import ElementTree from xml.dom import minidom def get_pretty_xml(tree): """Transforms and pretty-prints a given xml-tree to string :param tree: XML-tree :type tree: object :returns: (Prettified) stringified version of the passed xml-tree :rtype: str """ stringified_tree = ...
462
152
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import time import GetOldTweets3 as Got3 if sys.version_info[0] < 3: raise Exception("Python 2.x is not supported. Please upgrade to 3.x") sys.path.append(os.path.join(os.path.dirname(__file__), "..")) def test_username(): tweet_criteria =...
1,745
698
import extsum as ext URL = "https://i.picsum.photos/id/42/1/1.jpg" # Uncomment for random Picsum photo # URL = "https://picsum.photos/1/1" if __name__ == '__main__': # Init photo = ext.Load(URL) photo_parsed = ext.Parse(photo) # Print found ID (if any) id_found = photo_parsed.find_id() if id_...
421
165
import subprocess from .base import Base class Kind(Base): def __init__(self, vim): super().__init__(vim) self.name = 'lab_browse' self.default_action = 'lab_browse' def action_lab_browse(self, context): for target in context['targets']: iid = target['word'] ...
931
253
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, outfile): from genomicode import filelib from genomicode import parallel ...
3,358
1,183
from plots import plot_experiment_APs, plot_experiment_no_diff, experiment_VI_plots import os # paths, names, title, out_dir, out_name data_dir = '/Users/amcg0011/Data/pia-tracking/dl-results/210512_150843_seed_z-1_y-1_x-1_m_centg' suffix = 'seed_z-1_y-1_x-1_m_centg' out_dir = os.path.join(data_dir, 'DL-vs-Dog') ap_pat...
1,098
498
""" Python Flight Mechanics Engine (PyFME). Copyright (c) AeroPython Development Team. Distributed under the terms of the MIT License. Velocity -------- The aircraft state has """ from abc import abstractmethod import numpy as np # TODO: think about generic changes from body to horizon that could be used for # vel...
2,925
1,003
# test while statements while 0: 1 while 0: 2 else: 3
68
30
from minds.sections.newsfeed import NewsfeedAPI from minds.sections.channel import ChannelAPI from minds.sections.notifications import NotificationsAPI from minds.sections.posting import PostingAPI from minds.sections.interact import InteractAPI
246
59
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ AUTHOR - Antti Suni <antti.suni@helsinki.fi> - Sébastien Le Maguer <lemagues@tcd.ie> DESCRIPTION usage: cwt_global_spectrum.py [-h] [-v] [-o OUTPUT] [-P] input_file Tool for extracting global wavel...
8,331
2,645
import sys import math import operator import re from os import listdir from os.path import isfile, join from PIL import Image IMAGE_WIDTH = 355 IMAGE_HEIGHT = 355 BORDER_DISCOUNT = 0.11 BLOCK_SIZE = 36 BLOCKS_SIZE = BLOCK_SIZE * BLOCK_SIZE X_BLOCK_SIZE = IMAGE_WIDTH / BLOCK_SIZE; Y_BLOCK_SIZE = IMAGE_HEIGHT / BLO...
4,177
1,390
import tensorflow as tf from tensorflow.contrib import learn from betahex.features import Features from betahex.training.common import make_train_model, make_policy_input_fn, accuracy from betahex.models import MODEL tf.logging.set_verbosity(tf.logging.INFO) def main(unused_argv): # Load training and eval data...
1,649
573
# -*- coding: utf-8 -*- """ BSD 3-Clause License Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. Redistribution and use in source and binary forms, with or without...
9,747
3,099
import math import numpy as np import pykokkos as pk @pk.workload class Advance_cycle: def __init__(self, num_part, p_pos_x, p_pos_y, p_pos_z, p_dir_y, p_dir_z, p_dir_x, p_mesh_cell, p_speed, p_time, dx, mesh_total_xsec, L, p_dist_travled, p_end_trans, rands): self.p_pos_x: pk.View1D[pk.double] = p...
10,726
4,538
from django.conf import settings from ..defaults import AUTHENTICATORS from ..utils import get_module authenticators = [] all_args = [] def collect_authenticators(): global authenticators, all_args authenticators = list(map(get_module, getattr(settings, 'GRAHENE_ADDONS_AUTHENTICATORS', AUTHENTICATORS))) ...
514
152
import face_recognition as fr def compare_faces(file1, file2): """ Compare two images and return True / False for matching. """ # Load the jpg files into numpy arrays image1 = fr.load_image_file(file1) image2 = fr.load_image_file(file2) # Get the face encodings for each face in each im...
1,123
345
import numpy as np import pandas as pd import pyproj as pyproj import shapely as shapely from shapely.geometry import Point from haversine import haversine import src.config.column_names as col_names def correlate_and_save(crime_df: pd.DataFrame, census_df: pd.DataFrame, ...
3,354
1,116
def increment(*numbers): print(numbers) def dance(*numbers): total = 1 for number in numbers: total *= number return total increment(3,4,5,6) print(dance(1,2,3,4,5,6))
197
76
from flask_restful import Resource from flask_restful import reqparse from sqlalchemy.exc import SQLAlchemyError from config import Configuration from models.tag import TagModel as TM class Tag(Resource): parser = reqparse.RequestParser() parser.add_argument('name', type=str, ...
2,386
718
# Generated by Django 3.0.7 on 2020-06-06 16:06 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comments', fields=[ ('id', models.AutoField...
2,198
610
""" 结合所有的 Manager,实现text-in text-out的交互式 agent 的接口 """ import os import sys import time import argparse import logging BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(BASE_DIR, '../..')) os.environ["CUDA_VISIBLE_DEVICES"]="1" from DM.DST.StateTracking import DialogStateTracker from D...
5,493
2,177
# -*- coding: utf-8 -*- from __future__ import print_function """ CLU’s Custom exception classes live here """ class BadDotpathWarning(Warning): """ Conversion from a path to a dotpath resulted in a bad dotpath … likely there are invalid characters like dashes in there. """ pass class CDBError(Ex...
1,712
453
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Prediction of likely occurance of Vehicle Accident', author='sea karki', license='', )
231
74
#!/usr/bin/env python import sys, time, os sys.path.append('../src') import numpy as np import matplotlib.pylab as plt import hla from hla import caget, caput def compare(o1, o2): print o1 print o2 npoint, nbpm, ntrim = np.shape(o1._rawmatrix) print "checking bpm" for i in range(nbpm): # ...
6,543
3,025
import numpy as np import cv2 #sample function - dummy callback function def nothing(x): pass #capture live video cap = cv2.VideoCapture(0) #window for trackbars cv2.namedWindow('Track') #defining trackbars to control HSV values of given video stream cv2.createTrackbar('L_HUE', 'Track', 0, 255, noth...
1,698
714
# Copyright 2021 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
15,934
4,779
import scrapy from ..items import BasicHouseItem from ..utils import generate_url class FundaListingsSpider(scrapy.Spider): name = 'funda_listings' allowed_domains = ["funda.nl"] custom_settings = { "FEED_EXPORT_FIELDS": ["address", "zipcode", "price", "house_size", "plot_size", "rooms", "url", "i...
2,008
579
from wfdb.io.record import (Record, MultiRecord, rdheader, rdrecord, rdsamp, wrsamp, dl_database, edf2mit, mit2edf, wav2mit, mit2wav, wfdb2mat, csv2mit, sampfreq, signame, wfdbdesc, wfdbtime, sigavg) from wfdb.io.annotation import (Anno...
754
265
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('reports', '0102_recordspec_group_key'), ] operations = [ migrations.AlterField( model_name='reportimage', ...
647
196
""" You are given a digital number written down on a sheet of paper. Your task is to figure out if you rotate the given sheet of paper by 180 degrees would the number still look exactly the same. input: "1" output: false input: "29562" output: true input: "77" output: false """ def digital_number(number): ...
936
365
import argparse import os, json, sys import azureml.core from azureml.core import Workspace from azureml.core import Experiment from azureml.core.model import Model import azureml.core from azureml.core import Run from azureml.core.webservice import AciWebservice, Webservice from azureml.core.conda_dependencies import...
5,196
1,655
from tools import instruction_helpers from tools.errors import InstructionNotFound from logs.logconfig import log_config LOG = log_config() class Instruction: binary_instruction = "" def __init__(self): inst = raw_input("Please type a single command\n") self.opcode = None self.binary...
2,048
631
from django.shortcuts import render from django.contrib.auth.decorators import login_required from chameleon.decorators import terms_required from django.contrib import messages from django.http import ( Http404, HttpResponseForbidden, HttpResponse, HttpResponseRedirect, HttpResponseNotAllowed, ...
19,377
5,144
class Solution: def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: distance = 0 for element in arr1: if not any(c for c in arr2 if abs(c-element) <= d): distance += 1 return distance
268
81
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # # pipe.py # # Copyright 2014 Giorgio Gilestro <gg@kozak> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the Licen...
2,193
687
import os import sys # A Python script that can be used to determine which files that require # patching have been touched between two points in the repo. def shell(command): stream = os.popen(command) result = stream.read() stream.close() return result def get_patches(): patches = {} for fil...
1,608
523
from pyautofinance.common.strategies.bracket_strategy import BracketStrategy class LiveTradingTestStrategy(BracketStrategy): def _open_long_condition(self) -> bool: return True def _open_short_condition(self) -> bool: return False
259
78
import json from docopt import docopt from bigip_utils.logger import logger from bigip_utils.bigip import * # # This script enforces all attack signatures that are ready to be enforced: # https://support.f5.com/csp/article/K60640453?utm_source=f5support&utm_medium=RSS # __doc__ = """ Usage: enforce-read...
5,624
1,709
# sysinstall.py vi:ts=4:sw=4:expandtab: # # Copyright (c) 2006-2008 Three Rings Design, Inc. # 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 the a...
13,358
3,631
""" This module is for fetching information from dynamo about different sites """ from .inventory import _get_inventory def _small_query(*args): """ This is a wrapper function for opening and closing inventory connection :param args: arguments to pass to query :returns: Result of the query :rty...
1,233
383
import shutil import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings from .models import BookCover, get_book_cover_image_path class Command(BaseCommand): help = "" def handle(self, *args, **options): qs = BookCover.objects.exclude(image__iregex=r"...
1,163
362
"""The admin_history database table. This is a stopgap representation of changes to the admin table until we have a group system and a group-based authorization system up and running. """ from __future__ import annotations from datetime import datetime from sqlalchemy import Column, DateTime, Enum, Index, Integer, ...
1,002
295
import traceback from ..models import ServerError def build_handled_query(query): def handled_query(*kwargs, **args): try: return query(*kwargs, **args) except: print('Stack Trace ==>', traceback.format_exc()) return ServerError() return handled_query
316
85
import re from typing import Any, Dict, Sequence, List, Optional, Tuple from .base import Parser from .components import InterestingFinding from .results import WPScanResults #################### CLI PARSER ###################### class WPScanCliParser(Parser): """Main interface to parse WPScan CLI output. ...
8,153
2,154
from typing import Any, Dict, Union from django.conf import settings from django.http.response import HttpResponseBase, HttpResponseRedirect from django.views.generic import TemplateView from django.contrib.auth.views import LoginView, redirect_to_login class LoginView(LoginView): template_name = "login_form.html...
1,095
319
import pytest from mcanitexgen.animation.generator import Animation, GeneratorError def frame(index: int, time: int): return {"index": index, "time": time} class Test_append: def test(self): anim1 = Animation(0, 10, [frame(0, 10)]) anim2 = Animation(10, 20, [frame(0, 10)]) anim1.ap...
3,220
1,201
#! /usr/bin/env python """ This is a "quick and dirty" solution to getting polarization data through the pipeline. This script creates new fits files with independent polarization states. Make sure you have plenty of diskspace. """ from __future__ import print_function import argparse import os from time import sleep...
2,214
761
from holoprot.models.trainer import Trainer
44
14
# 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...
3,233
972
# -*- coding: utf-8 -*- """ author: pwxcoo date: 2018-02-05 description: 抓取下载成语并保存 """ import requests, json from bs4 import BeautifulSoup def downloader(url): """ 下载成语并保存 """ response = requests.get(url) if response.status_code != 200: print(f'{url} is failed!') return ...
1,759
647
import os import sys import copy import ipdb import json import mat73 import numpy as np import scipy.io as sio sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from lib.camera.camera import CameraInfoPacket, catesian2homogenous rot = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]]) # rotate along the x ax...
21,563
10,409
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.LeadsOrderInfo import LeadsOrderInfo class KoubeiServindustryLeadsRecordBatchqueryResponse(AlipayResponse): def __init__(self): super(KoubeiServindustryL...
1,512
474
from django.contrib.admin.filters import RelatedFieldListFilter, AllValuesFieldListFilter from django.db import models from django.db.models.query_utils import Q from django.utils.translation import ugettext as _ from django.utils.encoding import smart_unicode class CellFilter(object): title = "" menu_labels ...
6,125
1,817
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker import settings engine = create_engine(settings.API_DATA) db_session = scoped_session(sessionmaker(bind=engine)) Base = declarative_base() Base.query = db_session.query...
332
101
# https://www.hackerrank.com/challenges/np-arrays/problem import numpy def arrays(arr): return numpy.array(arr, float)[::-1]
132
50
# -*- coding:utf-8 -*- """ PyCfg - R. Souweine, 2016. """ import sys import os import ConfigParser from datetime import datetime class Cfg(): def __init__(self, cfg_file, cfg_sections, debug=False): """ Lecture d'un fichier de configuation type. """ if os.path.isfile(cfg_file): ...
2,738
799
from .utils import get_filters, get_values, get_relations, set_values, set_relations def default_resolve(schema, model, data, **kwargs): filters = get_filters(schema, data) return model.objects.filter(**filters) def default_execute(schema, data, raw_data, **kwargs): values = get_values(schema, raw_data)...
504
155
from math import ceil, floor, trunc x = 1.4 y = 2.6 print(floor(x), floor(y)) print(floor(-x), floor(-y)) print(ceil(x), ceil(y)) print(ceil(-x), ceil(-y)) print(trunc(x), trunc(y)) print(trunc(-x), trunc(-y))
212
97
#!/usr/bin/env python import requests import json store = 'http://localhost:8080/source' print "post a document" doc = {'name': 'tom'} headers = {'Content-Type': 'application/json'} r = requests.post(store, headers=headers, data=json.dumps(doc)) print r.status_code docid = r.json()['id'] revid = r.json()['rev'] p...
513
186
import numpy as np import tensorflow as tf from tensorflow_probability.python.distributions import seed_stream import tensorflow_probability as tfp import mvg_distributions.covariance_representations as cov_rep from mvg_distributions.gamma import SqrtGamma tfd = tfp.distributions tfb = tfp.bijectors class SqrtGamma...
10,463
3,473
import json from datetime import datetime from django.utils.timezone import utc from .base import AnymailBaseWebhookView from ..signals import AnymailTrackingEvent, EventType, RejectReason, tracking class SendinBlueTrackingWebhookView(AnymailBaseWebhookView): """Handler for SendinBlue delivery and engagement tr...
3,606
1,081
"""Custom strategy""" from urllib.parse import urlencode from django.db import transaction from social_django.strategy import DjangoStrategy from main import features from profiles.models import LegalAddress, Profile class BootcampDjangoStrategy(DjangoStrategy): """Abstract strategy for botcamp app""" def ...
2,232
606
__version__ = '0.0.2' from pathlib import Path APP_DIR = Path(__file__).parent
83
34
# -*- coding: utf-8 -*- from addons.base.tests.base import OAuthAddonTestCaseMixin, AddonTestCase from addons.swift.provider import SwiftProvider from addons.swift.serializer import SwiftSerializer from addons.swift.tests.factories import SwiftAccountFactory class SwiftAddonTestCase(OAuthAddonTestCaseMixin, AddonTestC...
580
178
# -*- coding: utf-8 -*- ''' Mac hardware information, generated by system_profiler. This is a separate grains module because it has a dependency on plistlib. ''' import logging import salt.utils import salt.modules.cmdmod log = logging.getLogger(__name__) __virtualname__ = 'mac_sp' try: import plistlib has...
1,311
429
import json import requests import discord from discord.ext import commands class Fun_insult(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def insult(self, ctx): '''insult command''' _res = requests.get(url='https://evilinsu...
901
319
""" G2_RIGHTS. This module defines Monitor class to monitor CPU and memory utilization. Pre-requisite non-standard Python module(s): psutil """ import time import threading import psutil class Monitor(): def __init__(self, interval=1): """ Monitor constructor. Args: interval (i...
1,873
521
# Module which defines how the I/O system works import sys, os from Registers import * from random import * from binascii import * class IO_supervisor(Registers): def __init__(self,my_registers): self.i_o = 'stuff' self.num_devices = 2 # native OS files simulate devices worki...
2,888
954