text
string
size
int64
token_count
int64
def weather_info (temp):
26
10
from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from comments.models import Comment # Create your models here. class PostManager(models.Manager): def active(self, *args, **kwargs): return super(PostManager, self) def upload_location(instanc...
2,863
856
from django.db import models # Create your models here. class MyModel(models.Model): aname = models.CharField(max_length=100, null=True, blank=True) anint = models.IntegerField(default=999) astring = models.CharField(max_length=50) date = models.DateField('Date', null=True, blank=True)
305
102
def print_(origfn, *args, **kwargs): print args print kwargs
69
23
''' ======================== Wrapper_pyca module ======================== Created on Nov.7, 2017 @author: Xu Ronghua @Email: rxu22@binghamton.edu @TaskDescription: This module provide cryptography function based on pyca API. @Reference:https://cryptography.io/en/latest/ ''' from cryptography.fernet import Fernet from...
7,621
2,855
import logging import json from src.utils.ucm import app_id, env class JsonLogFormatter(logging.Formatter): def format(self, record): msg = '' if record.exc_text is None: msg = record.message else: msg = record.exc_text data = { 'app_id': ''+app...
693
212
""" Afterglow Core: job plugin package A job plugin must define a custom model subclassing from :class:`afterglow_core.models.jobs.Job`, along with the optional custom result and settings models (subclassing from :class:`afterglow_core.models.jobs.JobResult` and :class:`afterglow_core.schemas.AfterglowSchema`, respect...
363
109
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Wrapper class for dictionaries to represent Things. """ import six from wotpy.wot.dictionaries.base import WotBaseDict from wotpy.wot.dictionaries.interaction import PropertyFragmentDict, ActionFragmentDict, EventFragmentDict from wotpy.wot.dictionaries.link import L...
4,909
1,308
__all__ = ['app_config'] import sys, os, os.path try: import ConfigParser as configparser except ImportError: import configparser try: import simplejson as json except ImportError: import json from .base_utils import * class AppConfig(configparser.RawConfigParser): config_filename = 'my-app.ini' main_sectio...
1,044
341
import torch import torch.nn as nn from utils.se3_torch import se3_transform_list _EPS = 1e-6 class CorrCriterion(nn.Module): """Correspondence Loss. """ def __init__(self, metric='mae'): super().__init__() assert metric in ['mse', 'mae'] self.metric = metric def forward(se...
1,131
418
from infrastructure.repository.token_snapshot_repo import TokenSnapshotRepo from http import HTTPStatus def get_snapshot_by_address(address): balance = TokenSnapshotRepo().get_token_balance(address) if balance is None: data = None statusCode = HTTPStatus.BAD_REQUEST.value message = "A...
501
137
from typing import Callable, Tuple from epimargin.models import SIR import pandas as pd from epimargin.estimators import analytical_MPVS from epimargin.etl.covid19india import data_path, get_time_series, load_all_data import epimargin.plots as plt from epimargin.smoothing import notched_smoothing from epimargin.utils ...
5,015
2,014
from flask import Blueprint main = Blueprint('main', __name__) @main.route('/') def main_index(): return '<div align="center"><img src="https://source.unsplash.com/1200x800/?technology,matrix,hacker,women"><p>Thanks Unsplash for nice photo</p></div>', 200
263
96
# Copyright 2011 Viewfinder Inc. All Rights Reserved. """Tests for IdAllocator data object. """ __author__ = 'spencer@emailscrubbed.com (Spencer Kimball)' import unittest from viewfinder.backend.base import util from viewfinder.backend.base.testing import async_test from viewfinder.backend.db.id_allocator import Id...
1,514
549
# # ayame.link # # Copyright (c) 2012-2021 Akinori Hattori <hattya@gmail.com> # # SPDX-License-Identifier: MIT # import urllib.parse from . import core, markup, uri, util from . import model as mm from .exception import ComponentError __all__ = ['Link', 'ActionLink', 'PageLink'] # HTML elements _A = markup.QNa...
2,429
821
import requests import datetime import time UPDATE_URL = "http://www.trac-us.appspot.com/api/updates/" #UPDATE_URL = "http://localhost:8000/api/updates/" def post_split(reader_code, tag_code, time): formatted_time = time.strftime("%Y/%m/%d %H:%M:%S.%f") payload = {'r': reader_code, '...
885
335
import pygame import numpy as np import random import torch from torch import nn from torch.nn import functional as F class CNN(torch.nn.Module): def __init__(self): super(CNN, self).__init__() torch.manual_seed(50) self.layer1 = nn.Sequential( # input: (1, 1, 10, 10) ...
5,775
2,125
import logging from random import randint from flask import Flask, render_template from flask_ask import Ask, statement, question, session from firebase import firebase import time firebase = firebase.FirebaseApplication('https://iotdev-6b58b.firebaseio.com', None) app = Flask(__name__) ask = Ask(app, "/") #lo...
1,289
448
# Generated by Django 3.0.5 on 2020-04-12 02:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home_app', '0002_auto_20200408_2205'), ] operations = [ migrations.RemoveField( model_name='topsites', ...
763
300
# -*- coding: utf-8 -*- # pylint: disable=missing-docstring,unused-import,reimported import pytest # type: ignore import tests.context as ctx import license_screening.license_screening as lis def test_parse_ok_empty_string(): assert lis.parse('') is NotImplemented def test_parse_ok_known_tree(): assert l...
349
126
import sys from .display import Display class PercentMetric(Display): def __init__(self, metric: str): super().__init__() self.metric = metric def update(self, metrics: dict, width=25, height=1): sys.stdout.write("%s: %3d%% \n" % (self.metric, metrics[self.metric]))
301
97
"""Add user journal table Revision ID: 6b8cf99be000 Revises: 36c4ecbfd11a Create Date: 2020-12-21 15:08:07.784568 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import func # revision identifiers, used by Alembic. revision = "6b8cf99be000" down_revision = "36c4ecbfd11a" branch_labels = None ...
762
311
import telebot from pyowm import OWM from pyowm.utils.config import get_default_config bot = telebot.TeleBot("telegram API-key") @bot.message_handler(commands=['start']) def welcome(message): bot.send_message(message.chat.id, 'Добро пожаловать, ' + str(message.from_user.first_name) + ',\n/start - запуск бота\n/help ...
1,906
847
version = '0.38'
17
10
"""The package indicator for serve.push.stream. Modules for transferring and registering servable stream data on the server. """
130
34
from django.db import models from django.db.models.fields.related import ForeignKey # Create your models here. class Country(models.Model): code = models.CharField(max_length=10) name = models.CharField(max_length=150) abrev = models.CharField(max_length=4) status = models.BooleanField() created_...
2,828
922
"""The limitlessled component."""
34
10
"""Project and user settings API""" import json from projectroles.models import AppSetting, APP_SETTING_TYPES, SODAR_CONSTANTS from projectroles.plugins import get_app_plugin, get_active_plugins # SODAR constants APP_SETTING_SCOPE_PROJECT = SODAR_CONSTANTS['APP_SETTING_SCOPE_PROJECT'] APP_SETTING_SCOPE_USER = SODAR_...
14,427
3,820
#! /usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE from __future__ import print_function import sys from optparse import OptionParser try: import pyfits except ImportError: try: from astropy.io import fits as pyfits except ImportError: raise ImportError("Cann...
2,835
1,068
from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.orm import relationship from models.base import Base from models.servers import Server from models.users import User class Nickname(Base): __tablename__ = 'nicknames' id = Column(Integer, primary_key=True) user_id = Column(Integer...
682
197
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.leveleditor.worldData.tortuga_building_int_10 from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Ambien...
6,749
3,837
import sys from . import base from . import cmd from . import reentry class MercurialInProcManager(cmd.Mercurial, base.RepoManager): """ A RepoManager implemented by invoking the hg command in-process. """ def _invoke(self, *params): """ Run the self.exe command in-process with the s...
755
220
from django.test import TestCase from django.contrib.auth import get_user_model from core import models from django.utils import timezone def sample_user(email='test@mail.com', password='testpass'): # Create a sample user return get_user_model().objects.create_user(email, password) class ModelTests(TestCase...
1,882
561
from flask import redirect, url_for, render_template from flask_login import current_user from components.pagination import html_pagination from db_session import create_session class Controller: __view__ = None __title__ = "Page" view_includes = {} jquery_enabled = True db_session = None de...
1,775
504
def quick_sort(arr): if len(arr) < 2: return arr pivot = arr.pop() left = [] right = [] for num in arr: if num > pivot: right.append(num) else: left.append(num) return quick_sort(left) + [pivot] + quick_sort(right) arr = [1,2,2,...
371
158
from gtts import gTTS import os f=open("1.txt") x=f.read() language='en' audio=gTTS(text=x,lang=language,slow=False) audio.save("1.wav") os.system("1.wav")
157
74
#! /usr/bin/env python from PyFoam.Applications.SymlinkToFile import SymlinkToFile SymlinkToFile()
101
41
#!/usr/bin/env python from distutils.core import setup import setuptools import os root_dir = os.path.abspath(os.path.dirname(__file__)) with open(f'{root_dir}/README.md') as f: readme = f.read() with open(f'{root_dir}/requirements.txt') as f: requirements = f.read().split() packages = setuptools.find_pack...
1,172
369
""" Created on 19. 12. 2018 Module for home section of the application. :author: Martin Dočekal :contact: xdocek09@stud.fit.vubtr.cz """ from .widget_manager import WidgetManager from .section_router import SectionRouter from functools import partial from .models import ListLastExperiments from PySide2.QtCore ...
1,679
478
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: #(r'^philly_legislative/', include('philly_legislative.foo.urls')), # Uncomment the admin/doc line below and add 'django....
829
299
from corsikaio import CorsikaFile from fact.io import to_h5py from multiprocessing import Pool, cpu_count from tqdm import tqdm import os import click import pandas as pd import numpy as np from glob import glob def get_headers(f): with CorsikaFile(f) as cf: run_header, event_headers, run_end = cf.read_he...
2,510
859
# -*- coding: utf-8 -*- import pytest from pibooth.pictures.factory import PilPictureFactory, OpenCvPictureFactory footer_texts = ('This is the main title', 'Footer text 2', 'Footer text 3') footer_fonts = ('Amatic-Bold', 'DancingScript-Regular', 'Roboto-LightItalic') footer_colors = ((10, 0, 0), (0, 50, 0), (0, 50, ...
3,101
1,206
"""## Question 3: Scrap Hotel Data The below code is for India and can be extended to other countries by adding an outer loop given in the last part. The below codes takes several minutes to run. """ import requests import pandas as pd from bs4 import BeautifulSoup hotelname_list = [] city_list = [] countries_list ...
6,452
2,301
import pyscreenshot as ImageGrab i=0 src_path ="C:\\Users\\Public\\ROV\OCR\\" if __name__ == "__main__": # part of the screen im=ImageGrab.grab(bbox=(200,100,1100,600)) # X1,Y1,X2,Y2 im.save(src_path + 'init.png')
234
118
# -*- coding: utf-8 -*- import threading import time import bottle import ephemeral_port_reserve import pytest import umsgpack from bravado_core.content_type import APP_JSON from bravado_core.content_type import APP_MSGPACK from six.moves import urllib ROUTE_1_RESPONSE = b'HEY BUDDY' ROUTE_2_RESPONSE = b'BYE BUDDY' ...
3,008
1,010
import torch import torch.utils.data from torchvision import datasets, transforms import numpy as np from udlp.autoencoder.convVAE import ConvVAE import argparse parser = argparse.ArgumentParser(description='VAE MNIST Example') parser.add_argument('--lr', type=float, default=0.0001, metavar='N', he...
1,479
519
#coding=utf-8 ''' Created on 2013年9月20日 @author: Wangliaofan ''' import bayes import feedparser from time import * if __name__== '__main__': listOPosts,listClasses = bayes.loadDataSet() print listOPosts,listClasses myVocabList = bayes.createVocabList(listOPosts) print myVocabList trainMat=[] f...
673
266
# -*- coding: utf-8 -*- from socket import gethostname def ResponseInjectHeader(get_response): def middleware(request): setattr(request, '_dont_enforce_csrf_checks', True) response = get_response(request) # response['Access-Control-Allow-Origin'] = '*' # response['Access-Control-...
573
190
import logging import socketio logger = logging.getLogger("handshake.socket") sio = socketio.AsyncClient(logger=logger) async def get_connection( url: str, api_key: str, watch_chain: bool = True, watch_mempool: bool = True, ) -> socketio.AsyncClient: """ see https://hsd-dev.org/guides/events.html ""...
1,334
440
def create_catchment_list(simulation): from os.path import join channel_manning = simulation.args.channel_manning CatchmentList = [ [join('Model', 'Bdy', 'Catchment.csv'), 100.0], [join('Model', 'Bdy', 'FineCatchment.csv'), 36.0], [join('Model', 'Bdy', 'CreekBanks.csv'), 8...
5,768
2,504
from unittest.mock import patch from flask import url_for, Response, request from flask_testing import TestCase from random import randint from app import app class TestBase(TestCase): def create_app(self): return app class TestResponse(TestBase): def rand_country(self): countries = ['German...
869
268
import argparse import torch import assets.utils as utils def log_args(args, tf_summary): args_dict = args.__dict__ from pytablewriter import MarkdownTableWriter writer = MarkdownTableWriter() writer.table_name = "Configurations (Args)" writer.headers = ["Parameter", "Value"] print('# INFO: ...
14,640
4,465
from google_drive_downloader import GoogleDriveDownloader as gdd import sys import os import requests def get_platform(): platforms = { 'linux1' : 'Linux', 'linux2' : 'Linux', 'darwin' : 'OS X', 'win32' : 'Windows' } if sys.platform not in platforms: return sys.plat...
687
215
#!/bin/python3 import math import os import random import re import sys # Complete the climbingLeaderboard function below. def climbingLeaderboard(scores, alice): li=[] lis=[0 for i in range(len(scores))] lis[0]=1 for i in range(1,len(scores)): #print(i) if scores[i]<scores[i-1]: ...
1,231
464
#!/usr/bin/python3 # -*- coding: utf-8 -*- from datetime import datetime import pprint import random import copy import torch import torch.nn as nn from model.deepqnet import DeepQNetwork,DeepQNetwork_v2 import omegaconf from hydra import compose, initialize import os from tensorboardX import SummaryWriter from col...
25,661
8,058
# Generated by Django 3.2 on 2021-05-13 15:20 import uuid from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("erp", "0122_auto_20210513_1720"), ] operations = [ migrations.AlterField( model_name="erp", name="uuid", ...
405
151
from mkt.constants import regions from mkt.developers.cron import exclude_new_region def run(): exclude_new_region([ regions.CR, regions.EC, regions.FR, regions.GT, regions.IT, regions.NI, regions.PA, regions.SV, ])
290
90
#!/usr/bin/env python3 # Copyright (c) 2019 The Energi Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import logging...
2,959
1,015
import os from setuptools import find_packages, setup DIR = os.path.dirname(os.path.abspath(__file__)) setup( name='graceful', version='1.2.0', description='test of graceful shutdown', url='https://github.com/qubitdigital/graceful/python', author='Infra', author_email='infra@qubit.com', l...
648
236
# -*- coding: utf-8 -*- import os import logging import logging.handlers import time def init_logger(log_file): dir_path = os.path.dirname(log_file) try: if not os.path.exists(dir_path): os.makedirs(dir_path) except Exception as e: pass handler = logging.handlers.Rotat...
812
278
import glob import os import subprocess import shutil source_file_list = glob.glob("../source/assets/*.glb") for input_file_name in source_file_list: base_file_name = os.path.split(input_file_name)[1] output_file_name = "../dist/assets/{}.usdz".format(os.path.splitext(base_file_name)[0]) print(...
637
239
from csv_json.csv_json_conv import *
36
13
COLUMNS = ['First Name', 'Last Name', 'Class Standing', 'Cum GPA', 'Major Code', 'Dept', 'Email'] DEPTS = ['CSE', 'ECE', 'MATH', 'BENG'] CLASS_STANDINGS = ['SO', 'JR', 'SR'] DEPTS_MAJORS = dict() # bit of a faux-pas... DEPTS_MAJORS['CSE'] = ['CS25', 'CS26', 'CS27', 'CS28'] DEPTS_MAJORS['ECE'] = ['EC26', 'EC27', 'EC28'...
463
249
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ from django.contrib import admin from .models import PERSON from .models import FACE # Register your models here. admin.site.register(PERSON) admin.site.register(FACE)
258
97
#!/usr/bin/env python import re import sys import socket import SocketServer import struct import fcntl import sys def getip(ethname): if ethname=="": ethname="eth0" try: s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ip=socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0X8915, struct.pack('256s', ethname[:15]))[2...
933
376
""" Idiomatic Go examples converted to use goless. """ from __future__ import print_function import time from . import BaseTests import goless class Examples(BaseTests): def test_select(self): # https://gobyexample.com/select c1 = goless.chan() c2 = goless.chan() def func1(): ...
2,190
710
from slackclient import SlackClient import requests import os from Config import slack_env_var_token, slack_username """ These functions take care of sending slack messages and emails """ def slack_chat_messenger(message): # NEVER LEAVE THE TOKEN IN YOUR CODE ON GITHUB, EVERYBODY WOULD HAVE ACCESS TO THE CHANN...
3,211
1,102
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: spaceone/api/monitoring/v1/alert.proto """Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _m...
71,403
27,764
import numpy as np import scipy.sparse as sp from scipy.ndimage import map_coordinates from scipy.sparse.linalg import factorized import operators as ops class Fluid: def __init__(self, shape, viscosity, quantities): self.shape = shape # Defining these here keeps the code somewhat more readable v...
3,364
961
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() PROJECT_URLS = { 'Bug Tracker': 'https://github.com/ngocjr7/geneticpython/issues', 'Documentation': 'https://github.com/ngocjr7/geneticpython/blob/master/README.md', 'Source Code': 'https://gith...
879
300
v = float(input('Valor do produto? R$')) d = float(input('Porcentagem de desconto: ')) ds = (d*v)/100 p = v-ds print(f'Você recebeu R${ds} de desconto, e pagará somente R${p} reais')
182
83
# Package modules from gavia import camera from gavia import vizualise from gavia import nav from gavia import gps from gavia import log from gavia import time # For nested packages from gavia import image
208
57
#!/usr/bin/env python3 # coding=utf-8 # ---------------------------------------------------------------------------------------------------- import socket import os # ---------------------------------------------------------------------------------------------------- # 类 netester # -------------------------------------...
1,241
287
""" Creates solvers for the Chemical Master Equation (CME). """ import numpy from cmepy import cme_matrix, domain, ode_solver, other_solver, state_enum from cmepy import model as mdl def create_packing_functions(domain_enum): """ create_packing_functions(domain_enum) -> (pack, unpack) where ...
7,121
1,960
import json import os import sys from server_common.ioc_data_source import IocDataSource from server_common.mysql_abstraction_layer import SQLAbstraction from server_common.utilities import print_and_log, SEVERITY def register_ioc_start(ioc_name, pv_database=None, prefix=None): """ A helper function to regis...
1,290
425
import bpy from bpy.props import StringProperty, IntProperty, CollectionProperty, EnumProperty, BoolProperty from bpy.types import PropertyGroup, UIList, Operator, Panel from bpy_extras.io_utils import ImportHelper from .rman_ui_base import _RManPanelHeader from ..txmanager3 import txparams from ..rman_utils import tex...
12,799
4,070
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: # condition to be cousin: (1)...
943
288
import pytest from django.core.exceptions import ValidationError from rest_framework.exceptions import \ ValidationError as RestFameworkValidationError from ..models import Question, QuestionSet from ..serializers.v1 import QuestionSerializer from ..validators import QuestionLockedValidator def test_create(db): ...
5,581
1,521
""" SAM macro definitions """ from six import string_types import copy import uuid import samtranslator.model.eventsources import samtranslator.model.eventsources.pull import samtranslator.model.eventsources.push import samtranslator.model.eventsources.cloudwatchlogs from .api.api_generator import ApiGenerator from ....
80,373
21,990
from django.conf.urls.defaults import * from media_logs.models import * audio_list = { 'queryset': Audio.objects.all(), } audio_set_list = { 'queryset': AudioSet.objects.all(), } urlpatterns = patterns('', url( regex = '^sets/(?P<slug>[-\w]+)/$', view = 'django.views.generic.list_detail.object_de...
928
358
#!/usr/bin/env python '''gopro control over mavlink for the solo-gimbal To use this module connect to a Solo with a GoPro installed on the gimbal. ''' import time, os from MAVProxy.modules.lib import mp_module from pymavlink import mavutil class GoProModule(mp_module.MPModule): def __init__(self, mpstate): ...
2,964
953
help = '''Hey 👋 \n\n /signup nick: enter your nick and sign up \n\n /atm: see your balance \n\n /send nick amount: send this nick that amount of buxx 💰 \n ''' signup = '''Hi! Type /signup to sign up.''' user_created = '''Created user. Welcome to Paybot 🤑''' user_exists = '''User already exists ☹️''' not_enough_buxx ...
343
136
import os import sys import numpy as np from PIL import Image num=1 path ="/Users/pection/Documents/mn_furniture/AddwatermarkProgram/Lastday/" #we shall store all the file names in this list filelist=[] for root, dirs, files in os.walk(path): for file in files: if(file.endswith(".jpg")): filelis...
1,609
628
import tensorflow as tf from BrainML.activation import Activator from BrainML.layers import * from BrainML.optimizer import Optimizer from tensorflow.python.util import deprecation ##deprecation._PRINT_DEPRECATION_WARNINGS = False ##tf.compat.v1.disable_eager_execution() import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = ...
1,986
706
#encoding=utf-8 import logging import time def print_calling(fn): def wrapper(*args1, ** args2): s = "calling function %s"%(fn.__name__) logging.info(s) start = time.time() ret = fn(*args1, **args2) end = time.time() # s = "%s. time used = %f seconds"%(s, (end - start...
2,900
962
""" First of all a tree of N nodes must have exactly N-1 edges. 2 nodes need 1 edge to connect. 3 nodes need 2 edges to connect... Just draw one or two, you will know it. Valid tree don't have cycles, there are two ways to detect it. DFS. and union find. Union find is more suitable in this sutuation. 1. Union find. W...
2,955
1,050
"""Configuration class for icons updating.""" import os from configparser import ConfigParser _DESTINATION_NAME = 'dst' _MAGICK_NAME = 'path' _SOURCES_NAME = 'src' class Config: """Configuration class.""" def __init__(self, config_file=None, src=None, dst=None): """Constructor.""" parser =...
1,336
377
""" Django settings for project project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from datetime...
8,831
3,064
#Author: Calvin Ryan import sensor, image, time, pyb, ustruct, math, utime def get_gain(): gain_reg_val = sensor.__read_reg(0x00) #print("gain_reg_val: " + str(gain_reg_val)) bitwise_gain_range = (gain_reg_val & 0b11110000) >> 4 #get the highest four bits which correspond to gain range. Depends on the bit...
15,142
6,053
""" This script was made to anaylse the relation between JEL and areas in ANPEC. The idea is that checking the JEL code of each paper, it can be vizualized whether some papers were published in area (from ANPEC meeting) not expected by their JEL code. """ import os import pandas as pd import
297
87
"""This script tests garage.tf.spaces.dict functionality.""" import unittest from garage.misc import ext from garage.tf.envs import TfEnv from tests.fixtures.envs.dummy import DummyDictEnv class TestDictSpace(unittest.TestCase): def test_dict_space(self): ext.set_seed(0) # A dummy dict env ...
1,311
448
import argparse import os import cv2 import numpy as np import hdf5storage as hdf5 from scipy.io import loadmat from matplotlib import pyplot as plt from SpectralUtils import savePNG, projectToRGB from EvalMetrics import computeMRAE BIT_8 = 256 # read path def get_files(path): # read a folder, return the complet...
3,429
1,324
# -*- coding:utf-8 -*- import gzip import re import http.cookiejar import urllib.request import urllib.parse # from logreg.sender import use_sender, sender def send_message(handle, content, captcha): def ungzip(data): return gzip.decompress(data) def get_csrf(data): cer = re.compile('data-csr...
2,435
915
import tokenize, operator macro_list = {} def chomp(state, with_defined=False): token = state.next_expanded_token() while token is not None: if name_of(token) == "macro": for token in run_macro(state): yield token elif state.processing: yield token ...
22,725
6,685
#!/usr/bin/env python from __future__ import print_function import argparse import carmcmc as cm import numpy as np import os import plotutils.autocorr as ac import sys if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input', required=True, metavar='FILE', help='input fil...
2,177
774
from revscoring.features import Feature, wikitext from revscoring.features.modifiers import div, log, max, sub def _process_new_longest(p_longest, r_longest): if r_longest > p_longest: return r_longest else: return 1 parent = [ log(wikitext.revision.parent.chars + 1), log(wikitext.re...
3,946
1,444
# Copyright 2017, Google 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
2,240
760
from django.urls import reverse from rest_framework.test import APITestCase from rest_framework import status from nose.tools import eq_ from faker import Faker import factory from ..models import Demand from .factories import DemandFactory from ..serializers import DemandSerializer from droidio.users.test.factorie...
3,494
1,133
# https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3250/ # time: O(n) # space: O(n) class Solution: def checkIfExist(self, arr: List[int]) -> bool: if not arr: return False nums = set() for x in arr: if 2*x in nums or x/2 in...
422
150
# coding=utf-8 # Copyright 2021 Google LLC. # # 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 ...
2,743
945