text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 Takeshi HASEGAWA
#
# 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/l... | 3,717 | 1,410 |
import math
import os
import random
import numpy as np
import torch
from tensorboardX import SummaryWriter
from tqdm import tqdm
from ..methods import DDPG, TD3, SAC
from envs.abb.models import utils
class Solver(object):
def __init__(self, args, env, project_path):
self.args = args
self.env = e... | 11,867 | 3,665 |
"""
Copyright 2018 Splunk, 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 to in writing, softwar... | 8,536 | 2,458 |
#!/usr/local/bin/env python3
import sys
# TODO: This is more generic than just for temperatures!
import temperature.temperature_file_tools
try:
filename = sys.argv[1]
except IndexError:
print("please provide filename as first and only argument")
else:
try:
data_gen = temperature.temperature_file_... | 639 | 186 |
import numpy as np
import pickle
#this file will do
#1. read from list of .pkl files that will become training data
#2. save wMean.dat and wSd.dat
for input in ["inputHeart/","inputBow/","inputAcrobat/"]:
fileList=[
'data_train.pkl',
]
collect=[]
for f in fileList:
#data=np.load('input/'+f) #(2,-)
dataLis... | 641 | 273 |
import copy
import logging
from typing import List, Tuple, Dict
import numpy as np
from metadrive.component.lane.abs_lane import AbstractLane
from metadrive.component.road_network.road import Road
from metadrive.component.road_network.base_road_network import BaseRoadNetwork
from metadrive.constants import Decoration
... | 10,553 | 3,111 |
###################################################################################
# Copyright (c) 2020-2021 STMicroelectronics.
# All rights reserved.
# This software is licensed under terms that can be found in the LICENSE file in
# the root directory of this software component.
# If no LICENSE file c... | 1,468 | 445 |
#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: nico
@file: views.py
@time: 2018/08/16
"""
from rest_framework import viewsets, mixins, filters, permissions, status, response
from rest_framework.decorators import action
from dry_rest_permissions.generics import DRYPermissions, DRYGlobalPer... | 1,905 | 660 |
import unittest
from QueryPharos import QueryPharos
class QueryPharosTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.pharos = QueryPharos()
def test_query_drug_name_to_targets(self):
# bte_result = self.pharos.query_drug_name_to_targets('paclitaxel')
# # TODO: B... | 7,243 | 2,697 |
from setuptools import setup
import codecs
# Copied from (and hacked):
# https://github.com/pypa/virtualenv/blob/develop/setup.py#L42
def get_version(filename):
import os
import re
here = os.path.dirname(os.path.abspath(__file__))
f = codecs.open(os.path.join(here, filename), encoding='utf-8')
ve... | 2,016 | 649 |
import discord
from discord.ext import commands
from ref_bot.data_models import Article, Tag, ArticleOwner
from ref_bot.article_scraper import scrape_article
class ArticleRefs(commands.Cog):
def __init__(self, bot, db_session):
self.bot = bot
self.db_session = db_session
self._last_member =... | 10,646 | 3,107 |
import numpy as np
import sklearn.metrics
def log_loss(y_true, y_pred):
return sklearn.metrics.log_loss(y_true, y_pred, eps=1e-6)
def accuracy_score(y_true, y_pred):
return sklearn.metrics.accuracy_score(y_true, np.round(y_pred))
def roc_auc_score(y_true, y_pred):
return sklearn.metrics.roc_auc_score(... | 694 | 299 |
#!/usr/bin/env python
#Reference: the baxter_stocking_stuffer project by students in Northwestern's MSR program - Josh Marino, Sabeen Admani, Andrew Turchina and Chu-Chu Igbokwe
#Service provided - ObjLocation service - contains x,y,z coordinates of object in baxter's stationary body frame, whether it is ok to grasp an... | 3,015 | 1,159 |
__version__ = '1.0.12'
from .smartcar import (AuthClient, is_expired, get_user_id, get_vehicle_ids)
from .vehicle import Vehicle
from .exceptions import (
SmartcarException, ValidationException, AuthenticationException,
PermissionException, ResourceNotFoundException, StateException,
RateLimitingException, ... | 410 | 121 |
#!/usr/bin/env python3
# Path: Discord Webhook Automation/discord_webhook.py
import requests
discord_webhook_url = 'your webhook url'
Message = {
"content": "./Hello_World",
"username": "Name for your discord webhook",
"avatar_url": "Your Avatar Image URL",
"tts": False,
"embeds": [
{
"title": "Tit... | 2,060 | 629 |
#!/usr/bin/python
# _*_ coding : utf-8 _*_
import pandas as pd
def run_main():
csv_path = 'Advertising.csv'
# pandas 读取数据
data = pd.read_csv(csv_path)
x = data[['TV', 'Radio', 'Newspaper']]
y = data['Sales']
# 绘制1
plt.plot
if __name__ == '__main__':
run_main() | 298 | 133 |
import settrade.openapi
from settrade.openapi import Investor
############################# login #############################
investor = Investor(
app_id="8uuaMP1npccDixrg",
app_secret="APX6wnqzk/yoVLIRyQ4ps4Fm13uzbC4tL5nyjAwwCKue",
app_code="SANDBOX",
broker_id="SANDBOX",
is_auto_qu... | 561 | 225 |
import codecs
import copy
import os
import re
import subprocess
import sys
import time
import unittest
from tfsnippet.utils import TemporaryDirectory, humanize_duration
from tests.examples.helper import skipUnlessRunExamplesTests
class ExamplesTestCase(unittest.TestCase):
"""
Test case to ensure all examples... | 2,135 | 583 |
# Solution to problem #
# Student: Niamh O'Leary#
#ID: GG00376339 #
# Write a program that outputs today's date and time in the format. "Monday, January 19th 2019 at 1.15pm"#
import datetime
now = datetime.datetime.now() #selects todays date and time#
print ("Current date and time: "
print (now.s... | 705 | 283 |
'''
Objektorientiert Programmierung
Eine Klasse für ein Quadrat
Version 1.00, 27.02.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
# Quadrat
import math
from bewegt_klasse impo... | 1,888 | 671 |
import urllib2
from bs4 import BeautifulSoup
from collections import defaultdict
def fetch_html():
resp = urllib2.urlopen("http://somafm.com/listen/")
html = resp.read()
return html
def make_soup(ingredients):
return BeautifulSoup(ingredients, 'html.parser')
def get_stations(soup):
stations =... | 2,858 | 946 |
from .models import *
from nltk.tokenize import TweetTokenizer
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
import seaborn as sns
import numpy as np
import time
import re
import json
def hashtag_demographics(route, label):
"""Return most-used hashtags."""
data... | 5,015 | 1,714 |
import numpy as np
import mxnet as mx
from mxnet import nd
from mxnet.gluon import Block, HybridBlock, nn, rnn
from config import ROWS, COLUMES, FLOW_OUTPUT_DIM, FLOW_OUTPUT_LEN
from model.structure import MFDense, ResUnit
N_LOC = ROWS * COLUMES
class CNN(Block):
""" Convolutional neural network """
... | 2,838 | 1,041 |
#!/usr/bin/env python
#
import urllib2
import datetime
import time
import os
APIKEY = 'c881ae04-2d79-46f4-8857-900a0ba71f5e'
URLBASE = 'https://na.api.pvp.net/api/lol/na/v4.1/game/ids?beginDate='
start = datetime.date(year=2015, month=4, day=1)
epoch = int(start.strftime("%s"))
now = int(time.time())
#print epoch
cu... | 883 | 378 |
import numpy as np
import pandas as pd
df = pd.read_csv("eurostat_hicpv2.csv")
eu_inflations = df.iloc[6:]
print(eu_inflations)
| 129 | 54 |
from enum import Enum
from importlib import import_module
class Solvers(Enum):
CPLEX = 1
GUROBI = 2
class MissingSolver(Exception):
pass
def init_solver(solver):
try:
module = import_module(__solver_module_names[solver], __package__)
return module
except (ImportError, NameError... | 543 | 186 |
class multiplot(object):
'''
plot class (let's see)
'''
def __init__(self,time,asymm,title,nscan,histoLength):
'''
input: if suite is the multiple run instance
time, asymm - 1d and 2d numpy arrays
e.g. from rebin(suite.time,suite.asymmetry_multirun(),(0,200... | 7,315 | 2,395 |
from tensorflow.keras.layers import Layer
from tensorflow.keras.layers import Conv2D
from tenning.generic_utils import get_object_config
import tensorflow as tf
class SVDO(Layer):
""" Performs symmetric orthogonalization as detailed in the paper
'An Analysis of SVD for Deep Rotation Estimation'
(h... | 1,308 | 441 |
"""
This is the module containing the graphical user interface for
my Newegg tracker application
"""
from tkinter import *
from tkinter import ttk
import webbrowser
from PIL import ImageTk, Image #Tkinter's image management is outdated
root = Tk()
root.config(bg="#2D2D2D")
root.title("Newegg tracker by Joey-Boivin ... | 3,836 | 1,301 |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 5 21:31:02 2017
@author: thuzhang
"""
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegres... | 1,344 | 555 |
from unittest.mock import patch, Mock
from remote_host_event_logging.public import RemoteHostEventLogger
from ..filesystem_mounting import FilesystemMountCommand
from ..device_identification import DeviceIdentificationCommand
from .utils import MigrationCommanderTestCase
class TestFilesystemMountCommand(MigrationC... | 3,072 | 942 |
from typing import Any, Callable
from math import sqrt, sin, acos, cos, pi
import turtle
def _is_int(result: Any) -> bool:
try:
int(result)
return True
except Exception:
return False
def _is_float(result: Any) -> bool:
try:
float(result)
return True
except Exc... | 7,416 | 2,357 |
"""
Authors: Salvatore Mandra (salvatore.mandra@nasa.gov),
Jeffrey Marshall (jeffrey.s.marshall@nasa.gov)
Copyright © 2021, United States Government, as represented by the Administrator
of the National Aeronautics and Space Administration. All rights reserved.
The HybridQ: A Hybrid Simulator for Quantum Circ... | 6,820 | 2,267 |
"""
Operations for process things like exit codes, forking etc
"""
import enum
import sys
class ExitCode(enum.Enum):
"""
Exit codes and conditions for consistency in the CLI
"""
ok = 0
failed = 2
obj_store_failed = 5 # Special value for compat with the object store ops return codes
def doe... | 693 | 226 |
from abstract.instruccion import *
from tools.console_text import *
from tools.tabla_tipos import *
from tools.tabla_simbolos import *
from storage import jsonMode as funciones
from error.errores import *
from instruccion.P_Key import *
from instruccion.F_Key import *
from instruccion.unique_simple import *
from instru... | 10,299 | 3,300 |
#!/usr/bin/env python
# Copyright (C) 2020 Toitware ApS. All rights reserved.
import grpc
import os
import sys
import getpass
from toit.api import auth_pb2_grpc, auth_pb2, device_pb2_grpc, device_pb2
def create_channel(access_token=None):
credentials = grpc.ssl_channel_credentials()
if access_token is not None:
... | 1,079 | 355 |
from typing import Dict, Tuple, List
import numpy as np
from .continuous_sensor import ContinuousSensor
from ..ball_placing_task import BallPlacingTask
class GripperVelocity2DSensor(ContinuousSensor[BallPlacingTask]):
def __init__(self, robot_name: str, linear_limit_lower: np.ndarray, linear_limit_upper: np.nda... | 3,771 | 1,134 |
import tweepy
import csv
import time
consumer_key = 'YOUR_KEY_HERE'
consumer_secret = 'YOUR_SECRET_HERE'
access_token = 'YOUR_TOKEN_HERE'
access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET_HERE'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = twe... | 1,986 | 680 |
# the source codes of transE are from https://github.com/mklimasz/TransE-PyTorch
from absl import app
from absl import flags
import os
import numpy as np
import torch.optim as optim
from torch.utils import data as torch_data
from torch.utils import tensorboard
from collections import Counter
from torch.utils import dat... | 19,434 | 6,379 |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
import gdal
import urllib.request
import xarray as xr
import numpy as np
import time
from datetime import datetime, date, time, timedelta
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import urllib
import requests
import... | 5,361 | 2,261 |
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['TestAppQueriesSnapshot::test_equipment_against_snapshot equipment_snapshot_resp'] = {
'data': {
'levels': [
{
... | 896 | 282 |
"""
This test for nurses end point
"""
import unittest
from healthtools.manage import app
from healthtools.search.nurses import get_nurses_from_nc_registry
class TestSetup(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
class TestNurseRegistery(TestSetup):
"""
This tests nurse... | 3,753 | 1,210 |
import logging
import numpy as np
import pandas as pd
import os, os.path as osp
from ..builder import build_dataset, build_dataloader
def get_train_val_test_splits(cfg, df):
if 'split' in df.columns and cfg.data.use_fixed_splits:
train_df = df[df.split == 'train']
valid_df = df[df.split == 'vali... | 2,626 | 936 |
#!/usr/bin/env python
import os, sys, time
import Image
import pprint
import numpy as np
def imgtotoggle (path, outpath):
image = Image.open(path)
image = image.convert("L")
pixels = image.load()
size = image.size
for j in range(size[0]):
for i in range(size[1]):
if pixels[j, i] < 200:
pixels[j, i] = ... | 376 | 173 |
import sys
import os
import subprocess
EXEC = sys.executable #local pythonw.exe
def run_py_file(py_path):
result = subprocess.run([EXEC, py_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
return str(result.stdout)
def run_py_codes(py_codes):
codes = str(py_codes)
if ... | 1,578 | 553 |
import matplotlib.pyplot as plt
import numpy as np
import sys
import csv
###########################################
# [HISTOGRAM]: Data for HISTOGRAM event.
async_script_histogram_data = {"kLoad": 0, "kUse": 0, "kReload": 0, "kRevalidate": 0}
def PlotRevalidationPolicyHistogramData():
x_name = async_script_histog... | 7,796 | 2,772 |
#!/usr/bin/env python3
## std library imports on top
import os
## 3rd party imports below
import paramiko
## work assigned to a junior programming asset on our team
from jrprogrammer import cmdissue
def get_creds():
ip = input("IP: ")
user = input("Username: ")
# return [ip, user]
# return {"ip": i... | 2,062 | 649 |
""" Collects the files of index files of a folder"""
from pathlib import Path
from collections import Counter
from functools import wraps
import datetime
from typing import Tuple, List, Dict, Union, Collection
# import re
# import copy
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEB... | 4,909 | 1,489 |
# Generated by Django 3.1.7 on 2021-03-26 19:53
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Employee',
fields=[
('empid', models.Intege... | 1,271 | 358 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Image handling utilities
License_info:
# ==============================================================================
# ISC License (ISC)
# Copyright 2020 Christian Doppler Laboratory for Embedded Machine Learning
#
# Permission to use, copy, modify, and/or distribu... | 4,102 | 1,311 |
# Copyright 2020 Carnegie Mellon University.
# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING
# INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON
# UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS
# TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANT... | 2,013 | 772 |
# Copyright 2014 Mirantis, 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 to in writing... | 18,329 | 6,389 |
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length = 100,unique=True)
def __str__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length = 50,unique=True)
def __str__(self):
... | 1,143 | 358 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import multiprocessing as mp
from maro.communication import Proxy, SessionType
def worker(group_name):
"""
The main worker logic includes initialize proxy and handle jobs from the master.
Args:
group_name (str): Identifie... | 3,100 | 856 |
from sleekxmpp.xmlstream.stanzabase import ElementBase
class MethodTimeout(ElementBase):
name = 'methodTimeout'
namespace = 'jabber:iq:rpc'
plugin_attrib = 'method_timeout'
interfaces = set(('timeout',))
subinterfaces = set(())
plugin_attrib_map = {}
plugin_tag_map = {}
def get_timeou... | 475 | 155 |
from setuptools import setup
setup(
name="rospy-builder",
version="0.2.0",
description="rospy package build tool",
author="Tamamki Nishino",
author_email="otamachan@gmail.com",
url="https://rospypi.github.io/simple",
packages=["rospy_builder"],
install_requires=[
"catkin_pkg",
... | 543 | 194 |
"""
Module that defines classes for matchers other than gazetteers which match e.g. regular expressions
of strings or annotations.
"""
class StringRegexMatcher:
"""
NOT YET IMPLEMENTED
"""
pass
# class AnnotationRegexMatcher:
# """ """
# pass
| 270 | 84 |
import logging
from ..comm import Client, Server
from ..link import Address, LocalBroadcast, PDU
from .bvlpdu import ForwardedNPDU, OriginalBroadcastNPDU, OriginalUnicastNPDU, ReadBroadcastDistributionTableAck, \
ReadForeignDeviceTableAck, Result, WriteBroadcastDistributionTable, ReadBroadcastDistributionTable, \
... | 5,045 | 1,575 |
'''
Trains TensorFlow DNNClassifier on training examples in TFRecord format, with
each training example comprising methylation betas for one aliquot and the 0/1
label.
Outputs statistics on the number of input features with non-zero weights in the
hidden layer (dnn/hiddenlayer_0/kernel).
Upon completion of training, wr... | 8,174 | 2,887 |
from typing import List, Deque, Dict, Set, Iterable
Symbol = str
State = str
class FAConfiguration:
def __init__(self, tape: List[Symbol], state: State, symbol_read: Symbol, prev_index: int, epsilon_set=None):
if epsilon_set is None:
epsilon_set = set()
self.tape = tape
self.... | 4,721 | 1,229 |
import math
from sklearn import neighbors
import os
from os import environ
import os.path
import pickle
import face_recognition
from face_recognition.face_recognition_cli import image_files_in_folder
import sys
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
THRESHOLD = os.getenv('THRESHOLD', 'TRUE')
def predict_frame(... | 5,893 | 1,903 |
# -*- coding: utf-8 -*-
"""
pip_services_runtime.cache.__init__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cache module initialization
:copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
__all__ = ['CacheEntry', 'Ab... | 510 | 155 |
# coding: utf-8
import doctest
import datetime
def d2s(date):
"""
日期转为字符串
>>> d2s(datetime.date(2016, 8, 16))
'2016-08-16'
:param date:
:return:
"""
return date.strftime("%Y-%m-%d")
if __name__ == "__mian__":
doctest.testmod()
| 269 | 129 |
# -*- coding: UTF-8 -*-
import os.path
from flask import _request_ctx_stack, current_app, request, url_for
from flask.ext import login
from flask.ext.principal import identity_changed, Identity, AnonymousIdentity
from itsdangerous import URLSafeTimedSerializer, BadTimeSignature
from sqlalchemy.orm.exc import NoResultFo... | 4,342 | 1,327 |
#=========================================================================
# VStructuralTranslatorL4.py
#=========================================================================
"""Provide SystemVerilog structural translator implementation."""
from textwrap import dedent
from pymtl3.passes.backends.generic.structura... | 9,449 | 3,315 |
"""
Load args and model from a directory
"""
import torch
from torch.utils.data import DataLoader, TensorDataset
from argparse import Namespace
import h5py
import json
import meshio
import numpy as np
def load_args(run_dir):
with open(run_dir + '/args.txt') as args_file:
args = Namespace(**json.load(arg... | 4,822 | 1,927 |
# Copyright 2009-2015 Yelp and Contributors
#
# 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 i... | 2,324 | 763 |
from django import template
from app.plugins import get_active_plugins
import itertools
register = template.Library()
@register.simple_tag(takes_context=False)
def get_plugins_js_includes():
# Flatten all urls for all plugins
js_urls = list(itertools.chain(*[plugin.get_include_js_urls() for plugin in get_acti... | 931 | 294 |
from dask.store import Store
from operator import add, mul
from dask.utils import raises
def inc(x):
return x + 1
def test_basic():
s = Store()
s['x'] = 1
s['y'] = (inc, 'x')
s['z'] = (add, 'x', 'y')
assert s.data == set(['x'])
assert s['z'] == 3
assert 'x' in s.data
assert s.c... | 1,114 | 452 |
# Copyright 2020 Broadband Forum
#
# 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 writi... | 4,132 | 1,326 |
import dash_html_components as html
import dash_core_components as core
from dash.dependencies import Input, Output
from ..dash_id import init_ids
import json
import pandas
import numpy
import plotly.figure_factory as ff
import gsiqcetl.load
from gsiqcetl.runreport.constants import CacheSchema
page_name = "runreport/... | 4,269 | 1,465 |
from flask import Flask, escape, request, make_response
import os
import requests
from Crypto.Cipher import AES
import urllib
import base64
from datetime import datetime, timedelta
# These variables should be configured as per your own parameters for each application in your API Gateway Maintanence portal.
# They can ... | 4,570 | 1,522 |
import asyncio
from typing import AsyncIterator
class OppoStreamIterator:
def __init__(self, reader: asyncio.StreamReader):
self._reader = reader
def __aiter__(self):
return self
async def __anext__(self):
val = await self._reader.readuntil(b'\r')
if val == b'':
raise StopAsyncIterati... | 948 | 291 |
from PIL import ImageTk
import PIL.Image
from tkinter import *
import urllib
from bs4 import BeautifulSoup
import requests
from selenium import webdriver
# -------URL generator----------
def url_gen(search_term):
search_term = (urllib.parse.quote(search_term, safe=''))
template = f"https://www.google.com/sea... | 3,455 | 1,235 |
"""
To run this module, execute `python -m cooper.demo.sweep_weights`
from this repository's base directory.
To save the outputs to a file, use stdout redirection:
`python -m cooper.demo.sweep_weights > data.csv`
"""
from typing import List
from typing_extensions import TypeAlias
from multiprocessing import P... | 1,910 | 841 |
import json
words_sheet = open('key_words_en.json', 'r')
try:
reader = json.load(words_sheet)
words_sheet.close()
for item in reader:
key_word = item['Environmental Keywords in English']
symbol = item['symbol']
f = open(key_word + '.json', 'r')
gf = json.load(f)
f.cl... | 494 | 167 |
#!/sr/bin/python
# Filename: sweepdown.py
import singlepulse
import time
version = '0.1'
def sweepdown(channel,pulse_width,min_amp_val,max_amp_val,slope_decay,delay_val,repetitions,ems):
min_val = min_amp_val
max_val = max_amp_val
slope = slope_decay
delay = delay_val
reps = re... | 866 | 303 |
#/!/usr/bin/env python
# Copyright 2016 Google Inc. 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 require... | 12,718 | 3,899 |
import yfinance as yf
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from arch import arch_model
from volatility.utils import get_percent_chg, Option, set_plot, get_ATR
start = datetime(2000, 1, 1)
end = datetime(2021, 3, 17)
symbol = 'QQQ'
tickerData = yf.Ticker(... | 2,453 | 1,072 |
from .event import event
def enhanced_item(name, unit_price, quantity=None, item_id=None,
category=None, brand=None, variant=None, **extra_data):
payload = {
'nm': name, 'pr': str(unit_price), 'qt': quantity or 1
}
if item_id:
payload['id'] = item_id
if category:
paylo... | 1,588 | 506 |
import json
import threading
from rich import print
from modules.request import request
import modules.vars as horsy_vars
import os
import zipfile
from modules.virustotal import scan_to_cli
from modules.http_status import handle
from ezzdl import dl
def install(package):
"""
Install an app
:param package:... | 5,022 | 1,675 |
#!/usr/bin/env python3
# coding=utf-8
import sys
import download_wrapper
from setuptools import setup, find_packages
cmdclass = {}
try:
from sphinx.setup_command import BuildDoc
cmdclass = {'build_sphinx': BuildDoc}
except ImportError:
pass
name = download_wrapper.__NAME__
version = download_wrapper.__V... | 1,310 | 392 |
from .accessor import PositionAccessor
# from .algorithms import *
# from .scalar import flat_earth, great_circle
__version__ = '0.0.5'
__all__ = ['PositionAccessor'] | 167 | 53 |
from tubbs.formatter.scala.breaker import VimBreaker
from tubbs.formatter.scala.indenter import VimIndenter
__all__ = ('VimBreaker', 'VimIndenter')
| 149 | 53 |
import unittest
import numpy
import os
from unittest.mock import (Mock, patch)
from raviewer.parser.yuv import ParserYUV420, ParserYUV422, ParserYUV420Planar, ParserYUV422Planar
from enum import Enum
class DummyPixelFormat(Enum):
YUV = 1
YVU = 2
UYVY = 3
YUYV = 4
class DummyEndianness(Enum):
LIT... | 9,055 | 3,340 |
"""
This class wraps date-picker(ngx-daterangepicker-material) input and allows to interact with it.
Time is set accoring to client time zone!
"""
from datetime import date, datetime
from typing import Callable, Optional
from combo_e2e.helpers.exceptions import DatePickerNotFound, DatePickerException, DatePickerAttri... | 7,179 | 2,076 |
# Generated by Django 3.2.7 on 2021-09-30 23:04
from django.db import migrations, models
import timewebapp.models
class Migration(migrations.Migration):
dependencies = [
('timewebapp', '0076_alter_timewebmodel_funct_round'),
]
operations = [
migrations.AddField(
model_name='... | 542 | 174 |
import io
import json
import logging
import os
import shutil
from pathlib import Path
import pandas as pd
from django.db import models
from datalakes.util import get_wanted_file
logger = logging.getLogger(__name__)
class LocalDatalake(models.Model):
root_path = models.CharField(max_length=500, default="", blan... | 2,249 | 737 |
# Copyright 2016 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 json
import tempfile
from tracing.value import add_shared_diagnostic
def AddDeviceInfo(histograms_json_filename, chrome_version, os_name, os_version... | 766 | 249 |
# encoding: utf-8
"""
@desc:
"""
import numpy as np
import math
from fairseq.data import data_utils
from fairseq.tasks.translation import TranslationTask
from fairseq.data.language_pair_dataset import LanguagePairDataset
from tqdm import tqdm
from multiprocessing import Pool
from typing import Tuple
from fast_k... | 9,803 | 3,217 |
n, inputs = [int(n) for n in input().split(" ")]
list = [0]*(n+1)
for _ in range(inputs):
print('\n')
x, y, incr = [int(n) for n in input().split(" ")]
list[x-1] += incr
if((y) <= len(list)):
list[y] -= incr
print(list)
max = x = 0
for i in list:
x = x+i
if(max < x):
max =... | 334 | 148 |
from flask import Flask, request, jsonify
from utils import generate_headlines
import tensorflow as tf
import json
tf.enable_eager_execution()
import numpy as np
app = Flask(__name__)
char2idx = json.loads(open("./data/st_char2idx.txt", 'br').read().decode(encoding='utf-8'))
idx2char = np.array(json.loads(open("./da... | 1,993 | 630 |
import datetime
from dateutil.parser import parse as date_parser
from mongoengine import Document, StringField, ListField
from django.conf import settings
from cybox.common import String, DateTime
from cybox.core import Observable
from cybox.objects.address_object import Address, EmailAddress
from cybox.objects.email_... | 9,572 | 2,604 |
'''
Adaptation of Tomostream orthoslice code for doing full 3d reconstructions
Then to apply DL-based image processing or computer vision steps.
'''
import pvaccess as pva
import numpy as np
import queue
import time
import h5py
import threading
import signal
import util
import log
from epics import PV
import so... | 18,147 | 5,859 |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
"""Userbot help command"""
from userbot import CMD_HELP
from userbot.events import register
@register(out... | 1,351 | 479 |
###############################################################################
##
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary for... | 4,076 | 1,138 |
from typing import List, Optional, Union
from cognite.client import utils
from cognite.client._api_client import APIClient
from cognite.experimental._constants import HANDLER_FILE_NAME, LIST_LIMIT_CEILING, LIST_LIMIT_DEFAULT, MAX_RETRIES
from cognite.experimental.data_classes import (
OidcCredentials,
Transfo... | 5,300 | 1,266 |
# -*- coding: utf-8 -*-
"""Advent Of Code 2020, Day 13
@author: Matevz
"""
from sympy.ntheory.modular import crt
def get_input(file_name):
"""Process input text file."""
try:
file = open(file_name, 'r')
content = file.read()
except IOError:
print('Cannot read file {}'.format(fil... | 2,110 | 695 |
def make_log_msg(title, status, detail=None, extra=None, sep='::'):
"""
Make a message that looks like this:
Title::status::detail::extra
Any None will be skipped.
"""
strings = [title, status, detail, extra]
return sep.join(filter(None, strings))
| 276 | 85 |
from bigbrain.ai import AI
__version__ = "0.1.2" | 49 | 23 |