text
string
size
int64
token_count
int64
import os import sys import unittest import torch import torch._C from pathlib import Path from test_nnapi import TestNNAPI from torch.testing._internal.common_utils import TEST_WITH_ASAN # Make the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.pa...
5,074
1,561
train_data_path = "../data/no_cycle/train.data" dev_data_path = "../data/no_cycle/dev.data" test_data_path = "../data/no_cycle/test.data" word_idx_file_path = "../data/word.idx" word_embedding_dim = 100 train_batch_size = 32 dev_batch_size = 500 test_batch_size = 500 l2_lambda = 0.000001 learning_rate = 0.001 epoch...
1,078
482
from PyQt5.QtWidgets import QLabel, QWidget, QGridLayout, QCheckBox, QGroupBox from InftyDoubleSpinBox import InftyDoubleSpinBox from PyQt5.QtCore import pyqtSignal, Qt import helplib as hl import numpy as np class dataControlWidget(QGroupBox): showErrorBars_changed = pyqtSignal(bool) ignoreFirstPoint_changed ...
7,506
2,342
import roslib roslib.load_manifest('sensor_msgs') roslib.load_manifest('dynamic_reconfigure') import rospy import sensor_msgs.msg import dynamic_reconfigure.srv import dynamic_reconfigure.encoding import numpy as np import time import os.path import queue class CameraHandler(object): def __init__(self,topic_pref...
6,425
2,010
import argparse import logging import numpy as np import os import pandas as pd import random import subprocess from pathlib import Path from hyperopt import hp from hyperopt.pyll.stochastic import sample from hfta.hfht import (tune_hyperparameters, attach_common_args, rearrange_algorithm_kwarg...
6,949
2,369
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-03-06 04:00 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trr', '0001_initial'), ] operations = [ migrations.AlterField( ...
444
156
# # Copyright(c) 2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # from core.test_run_utils import TestRun from utils.installer import install_iotrace, check_if_installed from utils.iotrace import IotracePlugin from utils.misc import kill_all_io from test_tools.fio.fio import Fio def dut_prepare...
1,409
486
from models import Song from random import choice def random_song(genre): results = Song.query().filter(Song.genre==genre).fetch() print(results) songs = choice(results) random_song = { "title": songs.song, "album": songs.album, "artist": songs.artist.lower(), "genre": g...
355
111
#!/usr/bin/python # custom_dialect.py import csv csv.register_dialect("hashes", delimiter="#") f = open('items3.csv', 'w') with f: writer = csv.writer(f, dialect="hashes") writer.writerow(("pencils", 2)) writer.writerow(("plates", 1)) writer.writerow(("books", 4))
288
113
from typing import Optional from flask_wtf import FlaskForm from wtforms import StringField, SelectField, SubmitField from wtforms.validators import DataRequired, Length, Email from servicex.models import UserModel class ProfileForm(FlaskForm): name = StringField('Full Name', validators=[DataRequired(), Length(...
996
272
def string_func(s, n):
24
12
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import os, sys import tensorflow as tf import tf_slim as slim from tensorflow.python.tools import freeze_graph sys.path.append('../../') from data.io.image_preprocess import short_side_resize_for_inference_data from libs.configs...
3,405
1,193
""" Adapter Removal templates """ # AdapterRemoval # # {0}: executable # {1}: fastq1 abs # {2}: fastq2 abs # {3}: fastq1 # {4}: fastq2 # {5}: minimum length # {6}: mismatch_rate # {7}: min base uality # {8}: min merge_length __ADAPTER_REMOVAL__=""" {0} --collapse --file1 {1} --file2 {2} --outputstats {3}....
983
395
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
1,745
544
class Input(object): def __init__(self, type, data): self.__type = type self.__data = deepcopy(data) def __repr__(self): return repr(self.__data) def __str__(self): return str(self.__type) + str(self.__data)
255
82
from os.path import join, abspath, dirname, exists from slybot import __version__ from setuptools import setup, find_packages from setuptools.command.bdist_egg import bdist_egg from setuptools.command.sdist import sdist def build_js(): root = abspath(dirname(__file__)) base_path = abspath(join(root, '..', 'sp...
2,154
752
import torch import torch.nn as nn from .yolo_layer import * from .yolov3_base import * class Yolov3(Yolov3Base): def __init__(self, num_classes=80): super().__init__() self.backbone = Darknet([1,2,8,8,4]) anchors_per_region = 3 self.yolo_0_pre = Yolov3UpsamplePrep([512, 1...
3,846
1,554
import os import pytest from modelkit.assets import errors from tests.conftest import skip_unless def _perform_driver_error_object_not_found(driver): with pytest.raises(errors.ObjectDoesNotExistError): driver.download_object("someasset", "somedestination") assert not os.path.isfile("somedestination"...
883
299
from django.test import TestCase from django.contrib.auth.models import User from wiki.models import Page # Create your tests here. def test_detail_page(self): """ Test to see if slug generated when saving a Page.""" # Create a user and save to the database user = User.objects.create() user.save() ...
2,163
694
from .multiarmedbandit import MultiArmedBandit from .eps_greedy_constant_stepsize import EpsilonGreedyConstantStepsize from .greedy_constant_stepsize import GreedyConstantStepsize from .epsilon_greedy_average_step import EpsilonGreedyAverageStep from .greedy_average_step import GreedyAverageStep from .greedy_bayes_upd...
419
133
from datetime import datetime from django.core.exceptions import FieldError from django.db.models import CharField, F, Q from django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import Lower from django.db.models.lookups import...
3,915
1,243
# This notebook implements a proof-of-principle for # Multi-Agent Common Knowledge Reinforcement Learning (MACKRL) # The entire notebook can be executed online, no need to download anything # http://pytorch.org/ from itertools import chain import torch import torch.nn.functional as F from torch.multiprocessing import...
16,356
6,078
import sys import os import glob import json from robot import rebot from robot.api import TestSuite sys.path.append(os.path.join(os.path.dirname(__file__), '..')) if __name__ == "__main__": main_suite = TestSuite('School Bus Scenario') main_suite.resource.imports.library('lib/simulation.py') testcas...
3,190
1,264
# The purpose of this script is to check all the maintenance branches of the # given repository, and find which pull requests are included in which # branches. The output is a JSON file that contains for each pull request the # list of all branches in which it is included. We look specifically for the # message "Merge ...
2,962
924
from datetime import datetime as dt import os import numpy as np import settings def mkdir(): now = dt.now().replace(second=0, microsecond=0) name_dir = "q_agent_train_" + now.strftime("%Y-%m-%d_%H:%M:%S") path = os.path.join(settings.MODELS_DIR, name_dir) try: os.mkdir(path) except File...
603
219
#----------------------------------------------------------------------------- # Copyright (c) 2013-2020, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt...
1,316
386
import inspect def get_default_args(func): """Get default arguments of a function. """ signature = inspect.signature(func) return { k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty }
278
80
""" Utilizando Lambdas Conhecidas por Expressões Lambdas, ou simplesmente Lambdas, são funções sem nome, ou seja, funções anónimas. # Função em Python def funcao(x): return 3 * x + 1 print(funcao(4)) print(funcao(7)) # Expressão Lambda lambda x: 3 * x + 1 # Como utlizar a expressão lambda? calc = lambda x...
2,059
876
# Lista dentro de dicionário campeonato = dict() gol = [] aux = 0 campeonato['Jogador'] = str(input('Digite o nome do jogador: ')) print() partidas = int(input('Quantas partidas ele jogou? ')) print() for i in range(0, partidas): aux = int(input(f'Quantos gols na partida {i + 1}? ')) gol.append(aux) ...
825
342
import numpy class InitialDataControlSine: def __init__(self, coefficients): self.coefficients = coefficients def __call__(self, x): u = numpy.zeros_like(x) for k, coefficient in enumerate(self.coefficients): u += coefficient * numpy.sin(k * numpy.pi * x) return...
533
171
import helpers import json import re datfilepath = "../github-data/labRepos_CreationHistory.json" allData = {} # Check for and read existing data file allData = helpers.read_existing(datfilepath) # Read repo info data file (to use as repo list) dataObj = helpers.read_json("../github-data/labReposInfo.json") # Popul...
5,030
1,810
#! /usr/bin/env python2.7 from __future__ import print_function import sys sys.path.append("../../include") import PyBool_public_interface as Bool if __name__ == "__main__": expr = Bool.parse_std("input.txt") expr = expr["main_expr"] expr = Bool.simplify(expr) expr = Bool.nne(expr) print(Bo...
341
126
from tkinter import * import random import time from PIL import Image from datetime import datetime from tinydb import * import os import pickle #from database1 import * from random import randint root = Tk() root.geometry("1600x800+0+0") root.title("Suman_dai_ko_DHOKAN") root.configure(bg="goldenrod4") text_Input =...
24,425
9,521
import torch import torch.nn as nn from mmcv.cnn import normal_init from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps from ..builder import build_loss from ..registry import HEADS from ..utils import ConvModule, Scale, bias_init_with_prob from IPython import embed INF = 1e8 ...
18,656
6,297
from . import db from sqlalchemy.dialects.mysql import LONGTEXT class Search(db.Model): __tablename__ = 'spots' id = db.Column(db.Integer, primary_key=True) search_string = db.Column(db.Text) lat = db.Column(db.Float) lon = db.Column(db.Float) location_name = db.Column(db.Text) json_result ...
863
320
import pandas as pd import numpy as np import plotly.offline as pyo import plotly.graph_objs as go df= pd.read_csv("Data/nst-est2017-alldata.csv") df2=df[df["DIVISION"] == '1'] df2.set_index("NAME",inplace=True) list_of_pop_col=[col for col in df2.columns if col.startswith('POP')] df2=df2[list_of_pop_col] data=[go....
471
189
""" test_markup ~~~~~~~~~~~ Test various Sphinx-specific markup extensions. :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import pytest from docutils import frontend, nodes, utils from docutils.parsers.rst import Parser as ...
21,993
7,913
from pandac.PandaModules import PStatCollector from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import Queue, invertDictLossless, makeFlywheelGen from direct.showbase.PythonUtil import itype, serialNum, safeRepr, fastRepr from direct.showbase.Job import Job import types, w...
50,253
12,794
# sql/default_comparator.py # Copyright (C) 2005-2018 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Default implementation of SQL comparison operations. """ from .. impor...
12,032
3,620
from django.contrib.auth.validators import UnicodeUsernameValidator from rest_framework import serializers from django.contrib.auth.models import User from recipes.models import Recipe, Ingredient, Step class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("usernam...
2,153
604
import numpy as np import pytest import torch from mmpose.models import TemporalRegressionHead def test_temporal_regression_head(): """Test temporal head.""" head = TemporalRegressionHead( in_channels=1024, num_joints=17, loss_keypoint=dict(type='MPJPELoss', use_target_wei...
1,652
640
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-31 23:20 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('leagues', '0001_initial'), ] operations = [ migrations.RenameField( mod...
415
146
class SnakeGame(object): def __init__(self, width,height,food): """ Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at ...
1,774
575
from itertools import ( chain, ) import logging from azul import ( config, require, ) from azul.logging import ( configure_script_logging, ) from azul.terra import ( TDRClient, TDRSourceName, ) log = logging.getLogger(__name__) def main(): configure_script_logging(log) tdr = TDRClien...
975
307
class Player: def __init__(self, nickname, vapor_id, player_id, ip): self.nickname = nickname self.vapor_id = vapor_id self.player_id = player_id self.ip = ip self.not_joined = True self.loads_map = True self.joined_after_change_map = True class Players: ...
3,584
1,075
""" Tools to "play notes for the editor clef", which may be thought of as "executing editor commands". NOTE: in the below, we often connect notes together "manually", i.e. using NoteSlur(..., previous_hash). As an alternative, we could consider `nouts_for_notes`. """ from s_address import node_for_s_address, s_dfs f...
17,835
5,307
"""Base for all Classes. Base mainly includes the description fields """ import logging from typing import Optional from .log import Log # type: ignore class BaseLog: """ Set a base logging. Use this as the base class for all your work. This adds a logging root. """ def __init__(self, log_roo...
636
185
import subprocess import re programs = input('Separe the programs with a space: ').split() secure_pattern = '[\w\d]' for program in programs: if not re.match(secure_pattern, program): print("Sorry we can't check that program") continue process = subprocess. run( ['which', program],...
620
190
from __future__ import absolute_import from django import forms from authentication.account.forms import BaseSignupForm from . import app_settings, signals from .adapter import get_adapter from .models import SocialAccount class SignupForm(BaseSignupForm): def __init__(self, *args, **kwargs): self.soc...
2,320
608
#!/usr/bin/env python """ Provides the primary interface into the library """ from __future__ import annotations import asyncio import logging from typing import Callable, Optional, Union from . import utils from . import controllers from .networking.connection import Connection from .networking.types import SSDPRes...
12,110
3,402
# Lista celulares # O departamento de marketing da sua empresa está interessado em obter apenas os números de telefone celular, separando-os dos telefones fixos. Para simplificar esta operação serão considerados números de celular apenas aqueles que, após o código de área, iniciarem com o dígito adicional 9. # Você rec...
1,673
635
import csv _iso_639_1_codes_file = open("files/ISO-639-1_Codes.csv", mode='r') _iso_639_1_codes_dictreader = csv.DictReader(_iso_639_1_codes_file) _iso_639_1_codes_dict: dict = {} for _row in _iso_639_1_codes_dictreader: _iso_639_1_codes_dict[_row['ISO-639-1 Code']] = _row['Language'] print(str(_iso_639_1_codes_...
326
159
import time import torch import warnings import numpy as np from tianshou.env import BaseVectorEnv from tianshou.data import Batch, ReplayBuffer,\ ListReplayBuffer from tianshou.utils import MovAvg class Collector(object): """docstring for Collector""" def __init__(self, policy, env, buffer=None, stat_si...
9,596
2,771
from drink_partners.contrib.samples import partner_bar_legal class TestSearchPartner: async def test_should_return_bad_request_for_str_coordinates( self, client, partner_search_with_str_coordinates_url ): async with client.get(partner_search_with_str_coordinates_url) as respon...
1,591
446
# -*- coding: utf-8 -*- # !/usr/bin/python ################################### PART0 DESCRIPTION ################################# # Filename: class_create_model_of_logistic_regression.py # Description: # # Author: Shuai Yuan # E-mail: ysh329@sina.com # Create: 2016-01-23 23:32:49 # Last: __author__ = 'yuens' ######...
17,858
5,384
import multiprocessing from typing import List, Optional import numpy as np from ..util import dill_for_apply class ImageSequenceWriter: def __init__(self, pattern, writer, *, max_index=None): if type(pattern) is not str: raise ValueError("Pattern must be string") if pattern.format(1...
3,341
946
# 377 Combination Sum IV # Given an integer array with all positive numbers and no duplicates, # find the number of possible combinations that add up to a positive integer target. # # Example: # # nums = [1, 2, 3] # target = 4 # # The possible combination ways are: # (1, 1, 1, 1) # (1, 1, 2) # (1, 2, 1) # (1, 3) # (2,...
1,495
517
from conans import ConanFile, CMake, tools import os STATIC_LIBS = ["nvtt", "squish", "rg_etc1", "nvimage", "bc6h", "posh", "bc7", "nvmath", "nvthread", "nvcore"] SHARED_LIBS = ["nvtt", "nvimage", "nvthread", "nvmath", "nvcore"] class NvidiatexturetoolsConan(ConanFile): name = "nvidia-texture-tools...
3,440
1,192
#!/usr/bin/env python3 """ train_args.py train_args.py command-line args. """ import argparse def get_args(): """ """ parser = argparse.ArgumentParser( description="This script lets you train and save your model.", usage="python3 train.py flowers/train --gpu --learning_rate 0.001 --epochs...
2,890
743
from django.http import HttpResponseRedirect from django.conf import settings from django.views.generic import TemplateView from apps.payment.models import PaymentLog from apps.payment.stripe import get_token, get_payment_charge from apps.subscription.views import start_subscription class ChargeView(TemplateView): ...
1,483
445
from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' # below piece of code is needed for automatic profile creation for user def ready(self): import users.signals
211
55
# -*- coding: utf-8 -*- """Console script for secure_data_store.""" import click from . import secure_data_store as sds CONFIG='~/.sdsrc' @click.group() def main(): """Wrapper for GoCryptFS""" @main.command() @click.argument('name') @click.option('--config', help='Path to config file', default='~/.sdsrc') def cr...
1,407
463
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2003 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~...
1,052
313
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may...
3,522
1,357
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
7,380
2,120
#!/usr/bin/env python # Copyright 2008 Orbitz WorldWide # # 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 ...
21,539
6,663
from PIL import Image import csv from ast import literal_eval as make_tuple from math import sqrt import argparse import os.path def load_img(image): # load an image as a PIL object im = Image.open(image).convert('RGBA') return im def color_distance(c_tuple1, c_tuple2): # calculate the color distanc...
2,619
874
# Xlib.ext.xinput -- XInput extension module # # Copyright (C) 2012 Outpost Embedded, LLC # Forest Bond <forest.bond@rapidrollout.com> # # This library 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...
17,824
6,679
from .loader import load
24
6
# Generated by Django 3.0.4 on 2020-04-16 23:10 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('YourJobAidApi', '0018_category_count_post'), ] operations = [ migrations.RemoveField( model_name='category', name='count_post...
340
118
# @Time : 2022/1/26 23:07 # @Author : zhaoyu # @Site : # @File : __init__.py.py # @Software: PyCharm # @Note : xx
129
69
from typing import Union from unittest import mock import graphene import pytest from django.core.exceptions import ValidationError from django.db.models import Q from django.template.defaultfilters import slugify from graphene.utils.str_converters import to_camel_case from saleor.core.taxes import zero_money from sa...
60,985
18,095
import os import json import cv2 import logging import boto3 import botocore s3 = boto3.client('s3') logger = logging.getLogger() logger.setLevel(logging.INFO) def upload_file(file_name, bucket, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to ...
3,557
1,209
from pyinstrument import Profiler p = Profiler(use_signal=False) p.start() def func(num): if num == 0: return b = 0 for x in range(1,100000): b += x return func(num - 1) func(900) p.stop() print(p.output_text()) with open('overflow_out.html', 'w') as f: f.write(p.output_html(...
323
137
#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2019, Linaro Limited # from __future__ import print_function from __future__ import division import argparse import sys import struct import re import hashlib try: from elftools.elf.elffile import ELFFile from elftools.elf.consta...
12,995
4,503
# The MIT License (MIT) # # Copyright (c) 2020 Jeff Epler for Adafruit Industries LLC # # 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 r...
1,864
588
# --- Klassendeklaration mit Konstruktor --- # class PC: def __init__(self, cpu, gpu, ram): self.cpu = cpu self.gpu = gpu self.__ram = ram # --- Instanziierung einer Klasse ---# # --- Ich bevorzuge die Initialisierung mit den Keywords --- # pc_instanz = PC(cpu='Ryzen 7', gpu='RTX2070Super'...
767
275
#!/usr/bin/env python3 """ The Coin Change Problem :author: Dela Anthonio :hackerrank: https://hackerrank.com/delaanthonio :problem: https://www.hackerrank.com/challenges/coin-change/problem """ from typing import List def count_ways(amount: int, coins: List[int]) -> int: """Return the number of ways we can cou...
723
258
from django.contrib import admin #from .models import * from . import models # Register your models here. admin.site.register(models.ClimbModel)
147
43
# coding: utf-8 from runpy import run_path from setuptools import setup # Get the version from the relevant file d = run_path('skaero/version.py') __version__ = d['__version__'] setup( name="scikit-aero", version=__version__, description="Aeronautical engineering calculations in Python.", author="Juan...
1,264
392
""" 8皇后问题 使用栈实现回溯法 """ def print_board(n,count): print(f"------解.{count}------") print(" ",end="") for j in range(n): print(f"{j:<2}" ,end="") print() for i in range(1,n+1): print(f"{i:<2}",end="") for j in range(1,n+1): if queens[i] == j: print("Q ",end="") else: print(" ",end="") print...
1,226
701
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: CC-BY-4.0 import os import cv2 from collections import namedtuple import imageio from PIL import Image from random import randrange import numpy as np from sklearn.decomposition import PCA from scipy.spatial.distance import...
24,820
7,415
import re import lxml.html from openstates.utils import LXMLMixin from billy.scrape.legislators import LegislatorScraper, Legislator class DELegislatorScraper(LegislatorScraper,LXMLMixin): jurisdiction = 'de' def scrape(self, chamber, term): url = { 'upper': 'http://legis.delaware.gov/l...
6,294
1,828
from header import * from .utils import * from .util_func import * '''Only for Testing''' class FineGrainedTestDataset(Dataset): def __init__(self, vocab, path, **args): self.args = args self.vocab = vocab self.vocab.add_tokens(['[EOS]']) self.pad = self.vocab.convert_tokens_...
10,386
3,407
# # PySNMP MIB module DABING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://..\DABING-MIB.mib # Produced by pysmi-0.3.4 at Tue Mar 22 12:53:47 2022 # On host ? platform ? version ? by user ? # Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] # OctetString, Objec...
4,396
1,801
import os import numpy as np save_stem='extra_vis_friday_harbor' data_dir='../../data/sdk_new_100' resolution=100 cre=False source_acronyms=['VISal','VISam','VISl','VISp','VISpl','VISpm', 'VISli','VISpor','VISrl','VISa'] lambda_list = np.logspace(3,12,10) scale_lambda=True min_vox=0 # save_file_name='...
956
396
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 20 09:42:39 2020 @author: niklas """ from mossepy.mosse_tracker import MOSSE # choose position of object in first frame # that should be done by mouse click objPos = [256, 256] # choose tracker type tracker = MOSSE() # initialize object position ...
396
152
def solve(polynomial): """ input is polynomial if more than one variable, returns 'too many variables' looks for formula to apply to coefficients returns solution or 'I cannot solve yet...' """ if len(polynomial.term_matrix[0]) > 2: return 'too many variables' elif len(polynomial...
3,194
1,120
"""Utility functions for parsing SVG styles.""" __all__ = ["cascade_element_style", "parse_style", "parse_color_string"] from xml.dom.minidom import Element as MinidomElement from colour import web2hex from ...utils.color import rgb_to_hex from typing import Dict, List CASCADING_STYLING_ATTRIBUTES: List[str] = [ ...
5,761
1,711
#!/usr/bin/env python #coding:utf-8 import os import RPi.GPIO as GPIO # import json from time import sleep # from twython import Twython f=open("tw_config.json",'r') config=json.load(f) f.close() CONSUMER_KEY =config['consumer_key'] CONSUMER_SECRET =config['consumer_secret'] ACCESS_TOKEN =config['access_token'] ACCE...
1,361
547
""" Unit tests for ``wheezy.templates.utils``. """ import unittest class FindAllBalancedTestCase(unittest.TestCase): """ Test the ``find_all_balanced``. """ def test_start_out(self): """ The start index is out of range. """ from wheezy.template.utils import find_all_balanced ...
2,293
779
# -*- coding:utf-8 -*- # /usr/bin/env python """ Date: 2019/10/21 12:08 Desc: 获取金十数据-数据中心-主要机构-宏观经济 """ import json import time import pandas as pd import requests from tqdm import tqdm from akshare.economic.cons import ( JS_CONS_GOLD_ETF_URL, JS_CONS_SLIVER_ETF_URL, JS_CONS_OPEC_URL, ) def macro_cons_...
34,967
19,042
############################################################################## # Written by: Cachen Chen <cachen@novell.com> # Date: 08/06/2008 # Description: Application wrapper for scrollbar.py # Used by the scrollbar-*.py tests ###################################################################...
1,811
513
import json from os import path from tweepy import OAuthHandler, Stream from tweepy.streaming import StreamListener from sqlalchemy.orm.exc import NoResultFound from database import session, Tweet, Hashtag, User consumer_key = "0qFf4T2xPWVIycLmAwk3rDQ55" consumer_secret = "LcHpujASn4fIIrQ8sikbCTQ3oyU6T6opchFVWBBqwI...
4,209
1,419
from flask import render_template, jsonify from app import app import random @app.route('/') @app.route('/index') def index(): # Feature flags init goes here! # # noinspection PyDictCreation flags = { "welcome_text": "welcome to my python FF tutorial!" } # Flag goes here! #...
907
313
# encoding: utf-8 ''' @author: yangsen @license: @contact: @software: @file: numpy_mat.py @time: 18-8-25 下午9:56 @desc: ''' import numpy as np a = np.arange(9).reshape(3,3) # 行 a[1] a[[1,2]] a[np.array([1,2])] # 列 a[:,1] a[:,[1,2]] a[:,np.array([1,2])]
254
149
import copy from typing import Callable, Dict, List, Optional import torch import torch.nn as nn import torch.optim as optim from ai_traineree import DEVICE from ai_traineree.agents import AgentBase from ai_traineree.agents.agent_utils import soft_update from ai_traineree.buffers import NStepBuffer, PERBuffer from ai...
17,002
5,151
from pycu.nvvm import (get_libdevice, ir_version, version, add_module_to_program, compile_program, create_program, destroy_program, get_compiled_result, get_compiled_result_size, get_program_log, get_program_log_size, lazy_add_module_to_program, verify_program) import os import sys from ctypes import c...
4,169
1,630
# Copyright (c) 2022, itsdve GmbH and Contributors # See license.txt # import frappe import unittest class TestFieldserviceSettings(unittest.TestCase): pass
160
55
# -*- coding: utf-8 -*- """ Created on Sun Nov 21 14:51:01 2021 @author: 75638 """ import pandas as pd import numpy as np pd.set_option('display.max_columns', None) pd.set_option('display.width', 10000) def process_data(path1,path2): ''' 1.path1: file path of different factor 2.path2:file path...
2,621
994