content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import difflib import time
[ 11748, 814, 8019, 198, 11748, 640, 198 ]
3.857143
7
# # name_extractor.py # ATOM # # Created by Karthik V. # Updated copyright on 16/1/19 5:54 PM. # # Copyright 2019 Karthik Venkatesh. All rights reserved. # # Reference # Question link: https://stackoverflow.com/questions/20290870/improving-the-extraction-of-human-names-with-nltk # Answer link: https://stackoverflow.com/a/49500219/5019015 import nltk from nltk.corpus import wordnet
[ 2, 198, 2, 220, 1438, 62, 2302, 40450, 13, 9078, 198, 2, 220, 5161, 2662, 198, 2, 198, 2, 220, 15622, 416, 9375, 400, 1134, 569, 13, 198, 2, 220, 19433, 6634, 319, 1467, 14, 16, 14, 1129, 642, 25, 4051, 3122, 13, 198, 2, 198, ...
2.62
150
# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Node registry.""" import threading from typing import Any, FrozenSet # To resolve circular dependency caused by type annotations. base_node = Any # base_node.py imports this module. _node_registry = _NodeRegistry() def register_node(node: 'base_node.BaseNode'): """Register a node in the local thread.""" _node_registry.register(node) def registered_nodes() -> FrozenSet['base_node.BaseNode']: """Get registered nodes in the local thread.""" return frozenset(_node_registry.registered_nodes())
[ 2, 15069, 33448, 3012, 11419, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.648026
304
# stdlib from copy import deepcopy from functools import wraps import os import tempfile from time import time # 3p import mock # datadog from datadog import initialize, api, util from datadog.api import ( Distribution, Metric, ServiceCheck ) from datadog.api.exceptions import ApiError, ApiNotInitialized from datadog.util.compat import is_p3k from tests.unit.api.helper import ( DatadogAPIWithInitialization, DatadogAPINoInitialization, MyCreatable, MyUpdatable, MyDeletable, MyGetable, MyListable, MyListableSubResource, MyAddableSubResource, MyUpdatableSubResource, MyDeletableSubResource, MyActionable, API_KEY, APP_KEY, API_HOST, HOST_NAME, FAKE_PROXY ) from tests.util.contextmanagers import EnvVars
[ 2, 14367, 8019, 198, 6738, 4866, 1330, 2769, 30073, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 6738, 640, 1330, 640, 198, 198, 2, 513, 79, 198, 11748, 15290, 198, 198, 2, 4818, 324, 519,...
2.566343
309
""" Author: Jason Eisele Email: jeisele@shipt.com Date: August 1, 2020 """ import argparse import keras import tensorflow as tf import cloudpickle parser = argparse.ArgumentParser( description='Train a Keras feed-forward network for MNIST classification') parser.add_argument('--batch-size', '-b', type=int, default=128) parser.add_argument('--epochs', '-e', type=int, default=1) parser.add_argument('--learning_rate', '-l', type=float, default=0.05) parser.add_argument('--num-hidden-units', '-n', type=float, default=512) parser.add_argument('--dropout', '-d', type=float, default=0.25) parser.add_argument('--momentum', '-m', type=float, default=0.85) args = parser.parse_args() mnist = keras.datasets.mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train, X_test = X_train / 255.0, X_test / 255.0 model = keras.models.Sequential([ keras.layers.Flatten(input_shape=X_train[0].shape), keras.layers.Dense(args.num_hidden_units, activation=tf.nn.relu), keras.layers.Dropout(args.dropout), keras.layers.Dense(10, activation=tf.nn.softmax) ]) optimizer = keras.optimizers.SGD(lr=args.learning_rate, momentum=args.momentum) model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, epochs=args.epochs, batch_size=args.batch_size) test_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)
[ 37811, 198, 13838, 25, 8982, 412, 786, 293, 198, 15333, 25, 11223, 786, 293, 31, 1477, 10257, 13, 785, 198, 10430, 25, 2932, 352, 11, 12131, 198, 37811, 198, 11748, 1822, 29572, 198, 11748, 41927, 292, 198, 11748, 11192, 273, 11125, 3...
2.549372
557
# coding:utf-8 # version:python3.5.1 # author:kyh import flickrapi import datetime import psycopg2 import time # flickr # def db_connect(): try: connection = psycopg2.connect(database="PlaceEmotion", user="postgres", password="postgres", host="127.0.0.1", port="5432") cursor = connection.cursor() print("Database Connection has been opened completely!") return connection, cursor except Exception as e: with open('log.txt','a') as log: log.writelines(str(e)) # # flickr api # # # # if __name__ == '__main__': db_connection, db_cursor = db_connect() flickr, api_key = query_api(db_connection, db_cursor) location, lat, lon= query_location(db_connection, db_cursor) while location is not None: compute_time(db_connection, db_cursor, location, lat, lon, flickr) location, lat, lon= query_location(db_connection, db_cursor) print("All locations have been recorded!") release_api(db_connection, db_cursor, api_key) close_connection(db_connection)
[ 2, 19617, 25, 40477, 12, 23, 198, 2, 2196, 25, 29412, 18, 13, 20, 13, 16, 198, 2, 1772, 25, 2584, 71, 198, 198, 11748, 26810, 2416, 72, 198, 11748, 4818, 8079, 198, 11748, 17331, 22163, 70, 17, 198, 11748, 640, 628, 198, 2, 781,...
2.401302
461
# -*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup import sys import csv reload(sys) sys.setdefaultencoding('utf-8') if __name__ == '__main__': url_main = 'http://gz.lianjia.com' f = open(u'.csv', 'wb') f.write(unicode('\xEF\xBB\xBF', 'utf-8')) # writer = csv.writer(f) writer.writerow(['', '', '', '', '()', '(/)', '', '', '', '', '', '', '']) res = requests.get(url_main+'ershoufang') res = res.text.encode(res.encoding).decode('utf-8') soup = BeautifulSoup(res, 'html.parser') # print soup.prettify() districts = soup.find(name='div', attrs={'data-role':'ershoufang'}) # <div data-role="ershoufang"> # soup.select() for district in districts.find_all(name='a'): print district['title'] district_name = district.text # '', '', '', ''...... url = '%s%s' % (url_main, district['href']) # print url res = requests.get(url) res = res.text.encode(res.encoding).decode('utf-8') soup = BeautifulSoup(res,'html.parser') # print soup.prettify() page = soup.find('div', {'class':'page-box house-lst-page-box'}) if not page: # continue total_pages = dict(eval(page['page-data']))['totalPage'] # # print total_pages for j in range(1, total_pages+1): url_page = '%spg%d/' % (url, j) res = requests.get(url_page) res = res.text.encode(res.encoding).decode('utf-8') soup = BeautifulSoup(res, 'html.parser') # print soup.prettify() sells = soup.find(name='ul', attrs={'class':'sellListContent', 'log-mod':'list'}) if not sells: continue # <a class="title" data-bl="list" data-el="ershoufang" data-log_index="1" href="XX" target="_blank"> titles = soup.find_all(name='a', attrs={'class':'title', 'data-bl':'list', 'data-el':'ershoufang'}) # <a data-el="region" data-log_index="1" href="X" target="_blank"> regions = sells.find_all(name='a', attrs={'data-el':'region'}) infos = sells.find_all(name='div', class_='houseInfo') # <div class="houseInfo"> infos2 = sells.find_all(name='div', class_='positionInfo') # <div class="positionInfo"> prices = sells.find_all(name='div', class_='totalPrice') # <div class="totalPrice"> unit_prices = sells.find_all(name='div', class_='unitPrice') # <div class="unitPrice" data-hid="X" data-price="X" data-rid="X"> subways = sells.find_all(name='span', class_='subway') # <span class="subway"> taxs = sells.find_all(name='span', class_='taxfree') # <span class="taxfree"> N = max(len(titles), len(regions), len(prices), len(unit_prices), len(subways), len(taxs), len(infos), len(infos2)) # for title, region, price, unit_price, subway, tax, info, info2 in zip(titles, regions, prices, unit_prices, subways, taxs, infos, infos2): for i in range(N): room_type = area = orientation = decoration = elevator = floor = year = slab_tower = None title = titles[i] if len(titles) > i else None region = regions[i] if len(regions) > i else None price = prices[i] if len(prices) > i else None unit_price = unit_prices[i] if len(unit_prices) > i else None subway = subways[i] if len(subways) > i else None tax = taxs[i] if len(taxs) > i else None info = infos[i] if len(infos) > i else None info2 = infos2[i] if len(infos2) > i else None if title: print 'Title: ', title.text if region: region = region.text if price: price = price.text price = price[:price.find('')] if unit_price: unit_price = unit_price.span.text.strip() unit_price = unit_price[:unit_price.find('/')] if unit_price.find('') != -1: unit_price = unit_price[2:] if subway: subway = subway.text.strip() if tax: tax = tax.text.strip() if info: info = info.text.split('|') room_type = info[1].strip() # area = info[2].strip() # area = area[:area.find('')] orientation = info[3].strip().replace(' ', '') # decoration = '-' if len(info) > 4: # decoration = info[4].strip() # elevator = '' if len(info) > 5: elevator = info[5].strip() # if info2: info2 = filter(not_empty, info2.text.split(' ')) floor = info2[0].strip() info2 = info2[1] year = info2[:info2.find('')] slab_tower = info2[info2.find('')+1:] print district_name, region, room_type, area, price, unit_price, tax, orientation, decoration, elevator, floor, year, slab_tower writer.writerow([district_name, region, room_type, area, price, unit_price, tax, orientation, decoration, elevator, floor, year, slab_tower]) # break # break # break f.close()
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 25064, 198, 11748, 269, 21370, 198, 198, 260, 2220, 7, 17597, 8, 198, 17597, 13, 2617, 12286, ...
1.94669
2,870
import argparse import tempfile import unittest from pygolf.__main__ import get_arguments_warning, read_input_code, shorten
[ 11748, 1822, 29572, 198, 11748, 20218, 7753, 198, 11748, 555, 715, 395, 198, 198, 6738, 12972, 70, 4024, 13, 834, 12417, 834, 1330, 651, 62, 853, 2886, 62, 43917, 11, 1100, 62, 15414, 62, 8189, 11, 45381, 628 ]
3.315789
38
import sys import numpy as np from matplotlib import pyplot as pl xr = [1,] yr = [1,] koch(xr[0], yr[0], 1, 0, 5) pl.plot(xr, yr, 'r.-', lw = 0.5) ax = pl.gca() ax.set_aspect('equal') pl.grid() pl.show()
[ 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 198, 198, 87, 81, 796, 685, 16, 11, 60, 198, 2417, 796, 685, 16, 11, 60, 198, 74, 5374, 7, 87, 81, 58, 15, 4357, 42635, ...
1.990291
103
# -*- coding: utf-8 -*- """ Core views to provide custom operations """ import uuid from datetime import datetime from django.http import HttpResponseRedirect from threepio import logger from atmosphere import settings from django_cyverse_auth.decorators import atmo_login_required from django_cyverse_auth.models import Token as AuthToken from core.models import AtmosphereUser as DjangoUser
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 14055, 5009, 284, 2148, 2183, 4560, 198, 37811, 198, 11748, 334, 27112, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 4023, 1330, ...
3.544643
112
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from enum import Enum from indico.core.errors import IndicoError from indico.core.logger import Logger
[ 2, 770, 2393, 318, 636, 286, 1423, 3713, 13, 198, 2, 15069, 357, 34, 8, 6244, 532, 12131, 327, 28778, 198, 2, 198, 2, 1423, 3713, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 198, 2, 13096, 340, 739, 262, 2846,...
3.393617
94
#!/usr/bin/env python # -*- coding: utf-8 -*- """Check the state of an AWS AMI.""" from __future__ import annotations import json from typing import Any, Dict import boto3 print("Loading function get_image_status") ec2_client = boto3.client("ec2") # { # "instance_id": "i-identifier", # "kms_id": "KMS ID", # "account": "account_number", # "instance_status": "should be there if in loop" # "migrated_ami_id": "ami-identifier" # } def lambda_handler(event: Dict[str, Any], context: Any) -> str: """Handle signaling and entry into the AWS Lambda.""" print("Received event: " + json.dumps(event, indent=2)) migrated_ami_id: str = event["migrated_ami_id"] ami_state: Dict[str, Any] = ec2_client.describe_images(ImageIds=[migrated_ami_id]) return ami_state["Images"][0]["State"]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 9787, 262, 1181, 286, 281, 30865, 3001, 40, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 117...
2.617363
311
# constants from starfish.core.types import ( # noqa: F401 Axes, Clip, Coordinates, CORE_DEPENDENCIES, Features, LOG, OverlapStrategy, PHYSICAL_COORDINATE_DIMENSION, PhysicalCoordinateTypes, STARFISH_EXTRAS_KEY, TransformType, ) from starfish.core.types import CoordinateValue, Number # noqa: F401
[ 2, 38491, 198, 6738, 3491, 11084, 13, 7295, 13, 19199, 1330, 357, 220, 1303, 645, 20402, 25, 376, 21844, 198, 220, 220, 220, 12176, 274, 11, 198, 220, 220, 220, 42512, 11, 198, 220, 220, 220, 22819, 17540, 11, 198, 220, 220, 220, ...
2.388889
144
#!/usr/bin/env python # encoding: utf-8 # # dangerKey.py # # Created by John Donor on 10 April 2019 import re, time from yaml import YAMLObject from alertsActor import log
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 3514, 9218, 13, 9078, 198, 2, 198, 2, 15622, 416, 1757, 2094, 273, 319, 838, 3035, 13130, 198, 198, 11748, 302, 11, 640, 198, 6738...
2.830769
65
''' Created on June 24, 2019 @author: Andrew Habib ''' import copy import json import sys import math import numbers import intervals as I from abc import ABC, abstractmethod from greenery.lego import parse from intervals import inf as infinity import config import _constants from canoncalization import canoncalize_object from _normalizer import lazy_normalize from _utils import ( validate_schema, print_db, is_sub_interval_from_optional_ranges, is_num, is_list, is_dict, is_empty_dict_or_none, is_dict_or_true, one ) def JSONNumericFactory(s): if s.get("type") == "number": if s.get("multipleOf") and float(s.get("multipleOf")).is_integer(): s["type"] = "integer" if s.get("minimum") != None: # -I.inf: s["minimum"] = math.floor(s.get("minimum")) if s.get( "exclusiveMinimum") else math.ceil(s.get("minimum")) if s.get("maximum") != None: # I.inf: s["maximum"] = math.ceil(s.get("maximum")) if s.get( "exclusiveMaximum") else math.floor(s.get("maximum")) return JSONTypeInteger(s) else: return JSONTypeNumber(s) else: return JSONTypeInteger(s) typeToConstructor = { "string": JSONTypeString, "integer": JSONNumericFactory, "number": JSONNumericFactory, "boolean": JSONTypeBoolean, "null": JSONTypeNull, "array": JSONTypeArray, "object": JSONTypeObject } boolToConstructor = { "anyOf": JSONanyOf, "allOf": JSONallOf, "oneOf": JSONoneOf, "not": JSONnot } if __name__ == "__main__": s1_file = sys.argv[1] s2_file = sys.argv[2] print("Loading json schemas from:\n{}\n{}\n".format(s1_file, s2_file)) ####################################### with open(s1_file, 'r') as f1: s1 = json.load(f1, cls=JSONSchemaSubtypeFactory) with open(s2_file, 'r') as f2: s2 = json.load(f2, cls=JSONSchemaSubtypeFactory) print(s1) print(s2) print("Usage scenario 1:", s1.isSubtype(s2)) ####################################### with open(s1_file, 'r') as f1: s1 = json.load(f1) with open(s2_file, 'r') as f2: s2 = json.load(f2) print(s1) print(s2) print("Usage scenario 2:", JSONSubtypeChecker(s1, s2).isSubtype())
[ 7061, 6, 198, 41972, 319, 2795, 1987, 11, 13130, 198, 31, 9800, 25, 6858, 19654, 571, 198, 7061, 6, 198, 198, 11748, 4866, 198, 11748, 33918, 198, 11748, 25064, 198, 11748, 10688, 198, 11748, 3146, 198, 11748, 20016, 355, 314, 198, 67...
2.268269
1,040
""" Various utilities functions used by django_community and other apps to perform authentication related tasks. """ import hashlib, re import django.forms as forms from django.core.exceptions import ObjectDoesNotExist from django.forms import ValidationError import django.http as http from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.contrib.auth import logout as auth_logout from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django_community.models import UserOpenID, UserProfile def openid_logout(request): """ Clears session which effectively logs out the current OpenId user. """ request.session.flush() def handle_logout(request): """ Log out. """ auth_logout(request) def get_logged_user(request): """ Returns the current user who is logged in, checks for openid user first, then for regular user, return None if no user is currently logged in """ if settings.OPENID_ENABLED and hasattr(request, 'openid'): user = UserOpenID.objects.get_for_openid(request, request.openid) if not user: user = request.user return user def handle_login(request, data): """ Logs the user in based on form data from django_community.LoginForm. """ user = authenticate(username = data.get('username', None), password = data.get('password', None)) user_object = User.objects.get(username = data.get('username', None)) if user is not None: login(request, user) return user def handle_signup(request, data): """ Signs a user up based on form data from django_community.SignupForm. """ from django.contrib.auth.models import get_hexdigest username = data.get('username', None) email = data.get('email', None) password = data.get('password', None) try: user = User.objects.get(username = username, email = email) except ObjectDoesNotExist: user = User(username = username, email = email) user.save() user.set_password(password) user_profile = UserProfile.objects.get_user_profile(user) user = authenticate(username = username, password = password) login(request, user) return user def get_or_create_from_openid(openid): """ Returns an User with the given openid or creates a new user and associates openid with that user. """ try: user = User.objects.get(username = openid) except ObjectDoesNotExist: password = hashlib.sha256(openid).hexdigest() user = User(username = openid, email = '', password = password) user.save() user.display_name = "%s_%s" % ('user', str(user.id)) user.save() return user def generate_random_user_name(): """ Generates a random user name user_{user_id}_{salt} to be used for creating new users. """ import random current_users = User.objects.all().order_by('-id') if current_users: next_id = current_users[0].id + 1 else: next_id = 1 random_salt = random.randint(1, 5000) return 'user_%s_%s' % (str(next_id), str(random_salt)) def create_user_from_openid(request, openid): """ Creates a new User object associated with the given openid. """ from django_community.config import OPENID_FIELD_MAPPING from django_utils.request_helpers import get_ip username = generate_random_user_name() profile_attributes = {} for attribute in OPENID_FIELD_MAPPING.keys(): mapped_attribute = OPENID_FIELD_MAPPING[attribute] if openid.sreg and openid.sreg.get(attribute, ''): profile_attributes[mapped_attribute] = openid.sreg.get(attribute, '') new_user = User(username = username) new_user.save() new_openid = UserOpenID(openid = openid.openid, user = new_user) new_openid.save() new_user_profile = UserProfile.objects.get_user_profile(new_user) for filled_attribute in profile_attributes.keys(): setattr(new_user, filled_attribute, profile_attributes[filled_attribute]) new_user_profile.save() return new_user def get_anon_user(request): """ Returns an anonmymous user corresponding to this IP address if one exists. Else create an anonymous user and return it. """ try: anon_user = User.objects.get(username = generate_anon_user_name(request)) except ObjectDoesNotExist: anon_user = create_anon_user(request) return anon_user def create_anon_user(request): """ Creates a new anonymous user based on the ip provided by the request object. """ anon_user_name = generate_anon_user_name(request) anon_user = User(username = anon_user_name) anon_user.save() user_profile = UserProfile(user = anon_user, display_name = 'anonymous') user_profile.save() return anon_user def generate_anon_user_name(request): """ Generate an anonymous user name based on and ip address. """ from django_utils.request_helpers import get_ip ip = get_ip(request) return "anon_user_%s" % (str(ip)) def is_anon_user(user): """ Determine if an user is anonymous or not. """ return user.username[0:10] == 'anon_user_' def is_random(name): """ Determine if a user has a randomly generated display name. """ if len(name.split('_')) and name.startswith('user'): return True else: return False def process_ax_data(user, ax_data): """ Process OpenID AX data. """ import django_openidconsumer.config emails = ax_data.get(django_openidconsumer.config.URI_GROUPS.get('email').get('type_uri', ''), '') display_names = ax_data.get(django_openidconsumer.config.URI_GROUPS.get('alias').get('type_uri', ''), '') if emails and not user.email.strip(): user.email = emails[0] user.save() if not user.profile.display_name.strip() or is_random(user.profile.display_name): if display_names: user.profile.display_name = display_names[0] elif emails: user.profile.display_name = emails[0].split('@')[0] user.profile.save()
[ 37811, 198, 40009, 20081, 5499, 973, 416, 42625, 14208, 62, 28158, 290, 198, 847, 6725, 284, 1620, 18239, 3519, 8861, 13, 198, 37811, 198, 198, 11748, 12234, 8019, 11, 302, 198, 198, 11748, 42625, 14208, 13, 23914, 355, 5107, 198, 6738,...
2.609477
2,448
import os from pathlib import Path from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, SetEnvironmentVariable, Shutdown from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node
[ 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 257, 434, 62, 9630, 62, 29412, 13, 43789, 1330, 651, 62, 26495, 62, 20077, 62, 34945, 198, 6738, 4219, 1330, 21225, 11828, 198, 198, 6738, 4219, 13, 4658, 1330, 40348, 38296, ...
4.657534
73
# A Rapid Proof of Concept for the eDensiometer # Copyright 2018, Nikhil Patel. All Rights Reserved. Created with contributions from Billy Pierce. # Imports from PIL import Image from pprint import pprint import numpy as np import time as time_ start = millis() # Constants # BRIGHT_CUTOFF = 175 RED_CUTOFF = 200 GREEN_CUTOFF = 150 BLUE_CUTOFF = 200 # Pull from test.jpg image in local directory temp = np.asarray(Image.open('test.jpg')) print(temp.shape) # Variable Initialization result = np.zeros((temp.shape[0], temp.shape[1], temp.shape[2])) temp_bright = np.zeros((temp.shape[0], temp.shape[1])) count_total = 0 count_open = 0 # Cycle through image for row in range(0, temp.shape[0]): for element in range(0, temp.shape[1]): count_total += 1 temp_bright[row, element] = (int(temp[row][element][0]) + int(temp[row][element][1]) + int(temp[row][element][2]))/3 # bright = temp_bright[row][element] > BRIGHT_CUTOFF red_enough = temp[row][element][0] > RED_CUTOFF green_enough = temp[row][element][1] > GREEN_CUTOFF blue_enough = temp[row][element][2] > BLUE_CUTOFF if red_enough and green_enough and blue_enough: # print(temp[row, element]) count_open += 1 result[row, element] = [255, 255, 255] # Save filtered image as final.jpg final = Image.fromarray(result.astype('uint8'), 'RGB') final.save('final.jpg') # Return/Print Percent Coverage percent_open = count_open/count_total percent_cover = 1 - percent_open end = millis() print("Percent Open: " + str(percent_open)) print("Percent Cover: " + str(percent_cover)) runtime = end-start print("Runtime in MS: " + str(runtime))
[ 2, 317, 26430, 29999, 286, 26097, 329, 262, 304, 35, 641, 72, 15635, 198, 2, 15069, 2864, 11, 11271, 71, 346, 33110, 13, 1439, 6923, 33876, 13, 15622, 351, 9284, 422, 15890, 23023, 13, 198, 198, 2, 1846, 3742, 198, 6738, 350, 4146, ...
2.662461
634
import sys import os import matplotlib.pyplot as plt from matplotlib.pyplot import figure import matplotlib as mpl import config if __name__ == "__main__": sys.exit(main())
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 9078, 29487, 1330, 3785, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 11748, 4566, 198, 220, 220, 220...
2.84375
64
from core.utilities.functions import delete_message from core.utilities.message import message from core.database.repository.group import GroupRepository """ This function allows you to terminate the type of file that contains a message on telegram and filter it """
[ 6738, 4755, 13, 315, 2410, 13, 12543, 2733, 1330, 12233, 62, 20500, 198, 6738, 4755, 13, 315, 2410, 13, 20500, 1330, 3275, 198, 6738, 4755, 13, 48806, 13, 260, 1930, 37765, 13, 8094, 1330, 4912, 6207, 13264, 198, 37811, 198, 1212, 216...
4.222222
63
from mipsplusplus import utils from mipsplusplus import operations OPERATOR_ORDERING = [ ['addressof', 'not', 'neg'], ['*', '/', '%'], ['+', '-'], ['<<', '>>', '<<<', '>>>'], ['<', '>', '<=', '>='], ['==', '!='], ['and', 'or', 'xor', 'nor'], ['as'] ] EXPR_OPERATORS = set([op for ops in OPERATOR_ORDERING for op in ops] + ['(', ')'])
[ 6738, 285, 2419, 9541, 9541, 1330, 3384, 4487, 198, 6738, 285, 2419, 9541, 9541, 1330, 4560, 198, 198, 31054, 25633, 62, 12532, 1137, 2751, 796, 685, 198, 220, 37250, 2860, 33852, 69, 3256, 705, 1662, 3256, 705, 12480, 6, 4357, 198, 2...
2.240506
158
the_simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"] print(the_simpsons[::-1]) for char in the_simpsons[::-1]: print(f"{char} has a total of {len(char)} characters.") print(reversed(the_simpsons)) print(type(reversed(the_simpsons))) # generator object for char in reversed(the_simpsons): # laduje za kazda iteracja jeden element listy, a nie cala liste od razu, dobre przy duzych listach print(f"{char} has a total of {len(char)} characters.")
[ 1169, 62, 14323, 31410, 796, 14631, 39, 12057, 1600, 366, 44, 1376, 1600, 366, 33, 433, 1600, 366, 44203, 1600, 366, 44, 9460, 494, 8973, 198, 198, 4798, 7, 1169, 62, 14323, 31410, 58, 3712, 12, 16, 12962, 198, 198, 1640, 1149, 287,...
2.606742
178
from subprocess import call import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) import settings data_zip_path = os.path.join(settings.lfw10_root, "LFW10.zip") data_url = "http://cvit.iiit.ac.in/images/Projects/relativeParts/LFW10.zip" # Downloading the data zip and extracting it call(["wget", "--continue", # do not download things again "--tries=0", # try many times to finish the download "--output-document=%s" % data_zip_path, # save it to the appropriate place data_url]) call(["unzip -d %s %s" % (settings.lfw10_root, data_zip_path)], shell=True)
[ 6738, 850, 14681, 1330, 869, 198, 11748, 28686, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 5305, 6978, 7, 834, 7753, 834, 36911, 28686, ...
2.622951
244
""" Utility functions to retrieve information about available services and setting up security for the Hops platform. These utils facilitates development by hiding complexity for programs interacting with Hops services. """ import pydoop.hdfs import subprocess import os import stat import sys import threading import time import socket from hops import hdfs as hopshdfs from hops import tensorboard from hops import devices from hops import util import coordination_server run_id = 0 def launch(spark_session, notebook): """ Run notebook pointed to in HopsFS as a python file in mpirun Args: :spark_session: SparkSession object :notebook: The path in HopsFS to the notebook """ global run_id print('\nStarting TensorFlow job, follow your progress on TensorBoard in Jupyter UI! \n') sys.stdout.flush() sc = spark_session.sparkContext app_id = str(sc.applicationId) conf_num = int(sc._conf.get("spark.executor.instances")) #Each TF task should be run on 1 executor nodeRDD = sc.parallelize(range(conf_num), conf_num) server = coordination_server.Server(conf_num) server_addr = server.start() #Force execution on executor, since GPU is located on executor nodeRDD.foreachPartition(prepare_func(app_id, run_id, notebook, server_addr)) print('Finished TensorFlow job \n') print('Make sure to check /Logs/TensorFlow/' + app_id + '/runId.' + str(run_id) + ' for logfile and TensorBoard logdir') def get_ip_address(): """Simple utility to get host IP address""" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) return s.getsockname()[0] # The code generated by this function will be called in an eval, which changes the working_dir and cuda_visible_devices for process running mpirun
[ 37811, 198, 18274, 879, 5499, 284, 19818, 1321, 546, 1695, 2594, 290, 4634, 510, 2324, 329, 262, 367, 2840, 3859, 13, 198, 4711, 3384, 4487, 42699, 2478, 416, 11816, 13357, 329, 4056, 24986, 351, 367, 2840, 2594, 13, 198, 37811, 198, ...
3.070946
592
"""empty message Revision ID: e956985ff509 Revises: 4b471bbc0004 Create Date: 2020-12-02 22:47:08.536332 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e956985ff509' down_revision = '4b471bbc0004' branch_labels = None depends_on = None
[ 37811, 28920, 3275, 198, 198, 18009, 1166, 4522, 25, 304, 3865, 3388, 5332, 487, 29022, 198, 18009, 2696, 25, 604, 65, 38339, 11848, 66, 830, 19, 198, 16447, 7536, 25, 12131, 12, 1065, 12, 2999, 2534, 25, 2857, 25, 2919, 13, 44468, ...
2.577586
116
from behave.matchers import RegexMatcher from ahk import AHK from behave_classy import step_impl_base Base = step_impl_base() AHKSteps().register()
[ 6738, 17438, 13, 6759, 3533, 1330, 797, 25636, 19044, 2044, 198, 6738, 29042, 74, 1330, 28159, 42, 198, 6738, 17438, 62, 4871, 88, 1330, 2239, 62, 23928, 62, 8692, 198, 198, 14881, 796, 2239, 62, 23928, 62, 8692, 3419, 628, 198, 18429...
3.125
48
import pygame from pygame.locals import *
[ 11748, 12972, 6057, 198, 6738, 12972, 6057, 13, 17946, 874, 1330, 1635, 628, 198 ]
3.142857
14
""" An image store representing Rackspace specific images """ from __future__ import absolute_import, division, unicode_literals import attr from six import iteritems from mimic.model.rackspace_images import (RackspaceWindowsImage, RackspaceCentOSPVImage, RackspaceCentOSPVHMImage, RackspaceCoreOSImage, RackspaceDebianImage, RackspaceFedoraImage, RackspaceFreeBSDImage, RackspaceGentooImage, RackspaceOpenSUSEImage, RackspaceRedHatPVImage, RackspaceRedHatPVHMImage, RackspaceUbuntuPVImage, RackspaceUbuntuPVHMImage, RackspaceVyattaImage, RackspaceScientificImage, RackspaceOnMetalCentOSImage, RackspaceOnMetalCoreOSImage, RackspaceOnMetalDebianImage, RackspaceOnMetalFedoraImage, RackspaceOnMetalUbuntuImage) from mimic.model.rackspace_images import create_rackspace_images
[ 37811, 198, 2025, 2939, 3650, 10200, 37927, 13200, 2176, 4263, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 28000, 1098, 62, 17201, 874, 198, 11748, 708, 81, 198, 6738, 2237, 1330, 11629, 23814, 198, 67...
1.882075
636
TEST_CONFIG_OVERRIDE = { # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. "gcloud_project_env": "BUILD_SPECIFIC_GCLOUD_PROJECT", # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. "envs": { "GA_TEST_PROPERTY_ID": "276206997", "GA_TEST_ACCOUNT_ID": "199820965", "GA_TEST_USER_LINK_ID": "103401743041912607932", "GA_TEST_PROPERTY_USER_LINK_ID": "105231969274497648555", "GA_TEST_ANDROID_APP_DATA_STREAM_ID": "2828100949", "GA_TEST_IOS_APP_DATA_STREAM_ID": "2828089289", "GA_TEST_WEB_DATA_STREAM_ID": "2828068992", }, }
[ 51, 6465, 62, 10943, 16254, 62, 41983, 49, 14114, 796, 1391, 198, 220, 220, 220, 1303, 1052, 17365, 7785, 1994, 329, 13213, 262, 1628, 4686, 284, 779, 13, 9794, 340, 198, 220, 220, 220, 1303, 284, 705, 19499, 26761, 62, 48451, 30643, ...
2.275184
407
filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.pressure_downstream.txt'
[ 34345, 796, 705, 1003, 36802, 23601, 11994, 14, 7890, 14, 272, 15643, 81, 463, 62, 1129, 3070, 14, 19895, 425, 14, 22125, 39, 13, 36151, 62, 2902, 5532, 13, 14116, 6 ]
2.483871
31
import numpy as nm from sfepy.linalg import dot_sequences from sfepy.terms.terms import Term, terms from sfepy.terms.terms_diffusion import LaplaceTerm
[ 11748, 299, 32152, 355, 28642, 198, 198, 6738, 264, 69, 538, 88, 13, 75, 1292, 70, 1330, 16605, 62, 3107, 3007, 198, 6738, 264, 69, 538, 88, 13, 38707, 13, 38707, 1330, 35118, 11, 2846, 198, 198, 6738, 264, 69, 538, 88, 13, 38707,...
2.851852
54
# Generated by Django 3.1.1 on 2021-09-21 04:52 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 16, 319, 33448, 12, 2931, 12, 2481, 8702, 25, 4309, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
#!/usr/bin/env python # # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging import os import sys import tempfile from subprocess import PIPE, CalledProcessError, check_call # nosec from typing import List, Optional from onefuzztypes.models import NotificationConfig from onefuzztypes.primitives import PoolName from onefuzz.api import Command, Onefuzz from onefuzz.cli import execute_api SANITIZERS = ["address", "dataflow", "memory", "undefined"] if __name__ == "__main__": sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 628, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 20218, 7753, 198, ...
3.345679
162
from . import AWSObject, AWSProperty from .validators import * from .constants import * # -------------------------------------------
[ 6738, 764, 1330, 30865, 10267, 11, 30865, 21746, 198, 6738, 764, 12102, 2024, 1330, 1635, 198, 6738, 764, 9979, 1187, 1330, 1635, 628, 198, 2, 20368, 32284, 628, 198 ]
4.758621
29
""" Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality. """ from __future__ import absolute_import import logging import six from hystrix.group import Group from hystrix.command_metrics import CommandMetrics from hystrix.command_properties import CommandProperties log = logging.getLogger(__name__) # TODO: Change this to an AbstractCommandMetaclass # TODO: Change this to inherit from an AbstractCommand
[ 37811, 198, 38052, 284, 14441, 2438, 326, 481, 12260, 6196, 17564, 11244, 198, 7, 48126, 3616, 257, 2139, 869, 625, 262, 3127, 8, 351, 8046, 290, 24812, 198, 83, 37668, 11, 7869, 290, 2854, 20731, 8006, 11, 10349, 46408, 290, 198, 65,...
4.151724
145
import os from functools import lru_cache import numpy as np from qtpy.QtCore import Qt from qtpy import QtCore, QtGui, QtWidgets from matplotlib.colors import ColorConverter from glue.utils.qt import get_qapp from glue.config import viewer_tool from glue.core import BaseData, Data from glue.utils.qt import load_ui from glue.viewers.common.qt.data_viewer import DataViewer from glue.viewers.common.qt.toolbar import BasicToolbar from glue.viewers.common.tool import CheckableTool from glue.viewers.common.layer_artist import LayerArtist from glue.core.subset import ElementSubsetState from glue.utils.colors import alpha_blend_colors from glue.utils.qt import mpl_to_qt_color, messagebox_on_error from glue.core.exceptions import IncompatibleAttribute from glue.viewers.table.compat import update_table_viewer_state try: import dask.array as da DASK_INSTALLED = True except ImportError: DASK_INSTALLED = False __all__ = ['TableViewer', 'TableLayerArtist'] COLOR_CONVERTER = ColorConverter() def get_layer_artist(self, cls, layer=None, layer_state=None): return cls(self, self.state, layer=layer, layer_state=layer_state)
[ 11748, 28686, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 10662, 83, 9078, 13, 48, 83, 14055, 1330, 33734, 198, 6738, 10662, 83, 9078, 1330, 33734, 14055, 11, 33734, ...
2.987113
388
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321...
5.354167
96
# Copyright 2015 Google 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from contextlib import contextmanager import functools import logging from uuid import uuid4 import google.cloud.exceptions from .globals import queue_context from .storage import Storage from .task import Task, TaskResult from .utils import dumps, measure_time, unpickle, UnpickleError logger = logging.getLogger(__name__) PUBSUB_OBJECT_PREFIX = 'psq'
[ 2, 15069, 1853, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, ...
3.628253
269
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """`gcloud access-context-manager levels update` command.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.accesscontextmanager import levels as levels_api from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.accesscontextmanager import levels from googlecloudsdk.command_lib.accesscontextmanager import policies
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 1303, 198, 2, 15069, 2864, 3012, 11419, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198,...
3.797834
277
import wave import struct import subprocess import os import opusenc import base64 import zlib import sys tmp = sys.argv[1] + ".wav" subprocess.Popen(["ffmpeg", "-i", sys.argv[1], "-ar", "48000", "-ac", "2", "-y", tmp], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() f = open(sys.argv[2], "wb") e = zlib.compressobj(9) c = 0 b = "" opusenc.initialize(256000) wf = wave.open(tmp) while True: rc = wf.readframes(480) if len(rc) != 1920: break opus = opusenc.encode(rc) b += base64.b64encode(opus).decode("utf-8") + "\n" c += 1 if c >= 100: c = 0 f.write(e.compress(b.encode()) + e.flush(zlib.Z_SYNC_FLUSH)) b = "" f.write(e.compress(b.encode()) + e.flush(zlib.Z_SYNC_FLUSH)) f.close() wf.close() os.remove(tmp)
[ 11748, 6769, 201, 198, 11748, 2878, 201, 198, 11748, 850, 14681, 201, 198, 11748, 28686, 201, 198, 11748, 1034, 385, 12685, 201, 198, 11748, 2779, 2414, 201, 198, 11748, 1976, 8019, 201, 198, 11748, 25064, 201, 198, 201, 198, 22065, 796...
2.050265
378
from . import functions as _functions from .functions import * # noqa: F401,F403 from .quad_faces import quads_to_tris __all__ = _functions.__all__ + ["quads_to_tris"]
[ 6738, 764, 1330, 5499, 355, 4808, 12543, 2733, 198, 6738, 764, 12543, 2733, 1330, 1635, 220, 1303, 645, 20402, 25, 376, 21844, 11, 37, 31552, 198, 6738, 764, 47003, 62, 32186, 1330, 627, 5643, 62, 1462, 62, 2213, 271, 198, 198, 834, ...
2.698413
63
from collections import OrderedDict from pathlib import Path from typing import Dict, Optional, Set, Union from ._utils import _chained from .errors import DuplicateError from .mixins import MetadataMixin from .writable import Writable, _filter_out_nones PEGASUS_VERSION = "5.0" __all__ = ["File", "ReplicaCatalog"]
[ 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 11, 32233, 11, 5345, 11, 4479, 198, 198, 6738, 47540, 26791, 1330, 4808, 354, 1328, 198, 6738, 764, 48277, 1330, 49821, 5344,...
3.262626
99
word_list = ['ABOUT', 'ABOVE', 'ABUSE', 'ACTOR', 'ACUTE', 'ADMIT', 'ADOPT', 'ADULT', 'AFTER', 'AGAIN', 'AGENT', 'AGREE', 'AHEAD', 'ALARM', 'ALBUM', 'ALERT', 'ALIKE', 'ALIVE', 'ALLOW', 'ALONE', 'ALONG', 'ALTER', 'AMONG', 'ANGER', 'ANGLE', 'ANGRY', 'APART', 'APPLE', 'APPLY', 'ARENA', 'ARGUE', 'ARISE', 'ARRAY', 'ASIDE', 'ASSET', 'AUDIO', 'AUDIT', 'AVOID', 'AWARD', 'AWARE', 'BADLY', 'BAKER', 'BASES', 'BASIC', 'BASIS', 'BEACH', 'BEGAN', 'BEGIN', 'BEGUN', 'BEING', 'BELOW', 'BENCH', 'BILLY', 'BIRTH', 'BLACK', 'BLAME', 'BLIND', 'BLOCK', 'BLOOD', 'BOARD', 'BOOST', 'BOOTH', 'BOUND', 'BRAIN', 'BRAND', 'BREAD', 'BREAK', 'BREED', 'BRIEF', 'BRING', 'BROAD', 'BROKE', 'BROWN', 'BUILD', 'BUILT', 'BUYER', 'CABLE', 'CALIF', 'CARRY', 'CATCH', 'CAUSE', 'CHAIN', 'CHAIR', 'CHART', 'CHASE', 'CHEAP', 'CHECK', 'CHEST', 'CHIEF', 'CHILD', 'CHINA', 'CHOSE', 'CIVIL', 'CLAIM', 'CLASS', 'CLEAN', 'CLEAR', 'CLICK', 'CLOCK', 'CLOSE', 'COACH', 'COAST', 'COULD', 'COUNT', 'COURT', 'COVER', 'CRAFT', 'CRASH', 'CREAM', 'CRIME', 'CROSS', 'CROWD', 'CROWN', 'CURVE', 'CYCLE', 'DAILY', 'DANCE', 'DATED', 'DEALT', 'DEATH', 'DEBUT', 'DELAY', 'DEPTH', 'DOING', 'DOUBT', 'DOZEN', 'DRAFT', 'DRAMA', 'DRAWN', 'DREAM', 'DRESS', 'DRILL', 'DRINK', 'DRIVE', 'DROVE', 'DYING', 'EAGER', 'EARLY', 'EARTH', 'EIGHT', 'ELITE', 'EMPTY', 'ENEMY', 'ENJOY', 'ENTER', 'ENTRY', 'EQUAL', 'ERROR', 'EVENT', 'EVERY', 'EXACT', 'EXIST', 'EXTRA', 'FAITH', 'FALSE', 'FAULT', 'FIBER', 'FIELD', 'FIFTH', 'FIFTY', 'FIGHT', 'FINAL', 'FIRST', 'FIXED', 'FLASH', 'FLEET', 'FLOOR', 'FLUID', 'FOCUS', 'FORCE', 'FORTH', 'FORTY', 'FORUM', 'FOUND', 'FRAME', 'FRANK', 'FRAUD', 'FRESH', 'FRONT', 'FRUIT', 'FULLY', 'FUNNY', 'GIANT', 'GIVEN', 'GLASS', 'GLOBE', 'GOING', 'GRACE', 'GRADE', 'GRAND', 'GRANT', 'GRASS', 'GREAT', 'GREEN', 'GROSS', 'GROUP', 'GROWN', 'GUARD', 'GUESS', 'GUEST', 'GUIDE', 'HAPPY', 'HARRY', 'HEART', 'HEAVY', 'HENCE', 'HENRY', 'HORSE', 'HOTEL', 'HOUSE', 'HUMAN', 'IDEAL', 'IMAGE', 'INDEX', 'INNER', 'INPUT', 'ISSUE', 'JAPAN', 'JIMMY', 'JOINT', 'JONES', 'JUDGE', 'KNOWN', 'LABEL', 'LARGE', 'LASER', 'LATER', 'LAUGH', 'LAYER', 'LEARN', 'LEASE', 'LEAST', 'LEAVE', 'LEGAL', 'LEVEL', 'LEWIS', 'LIGHT', 'LIMIT', 'LINKS', 'LIVES', 'LOCAL', 'LOGIC', 'LOOSE', 'LOWER', 'LUCKY', 'LUNCH', 'LYING', 'MAGIC', 'MAJOR', 'MAKER', 'MARCH', 'MARIA', 'MATCH', 'MAYBE', 'MAYOR', 'MEANT', 'MEDIA', 'METAL', 'MIGHT', 'MINOR', 'MINUS', 'MIXED', 'MODEL', 'MONEY', 'MONTH', 'MORAL', 'MOTOR', 'MOUNT', 'MOUSE', 'MOUTH', 'MOVIE', 'MUSIC', 'NEEDS', 'NEVER', 'NEWLY', 'NIGHT', 'NOISE', 'NORTH', 'NOTED', 'NOVEL', 'NURSE', 'OCCUR', 'OCEAN', 'OFFER', 'OFTEN', 'ORDER', 'OTHER', 'OUGHT', 'PAINT', 'PANEL', 'PAPER', 'PARTY', 'PEACE', 'PETER', 'PHASE', 'PHONE', 'PHOTO', 'PIECE', 'PILOT', 'PITCH', 'PLACE', 'PLAIN', 'PLANE', 'PLANT', 'PLATE', 'POINT', 'POUND', 'POWER', 'PRESS', 'PRICE', 'PRIDE', 'PRIME', 'PRINT', 'PRIOR', 'PRIZE', 'PROOF', 'PROUD', 'PROVE', 'QUEEN', 'QUICK', 'QUIET', 'QUITE', 'RADIO', 'RAISE', 'RANGE', 'RAPID', 'RATIO', 'REACH', 'READY', 'REFER', 'RIGHT', 'RIVAL', 'RIVER', 'ROBIN', 'ROGER', 'ROMAN', 'ROUGH', 'ROUND', 'ROUTE', 'ROYAL', 'RURAL', 'SCALE', 'SCENE', 'SCOPE', 'SCORE', 'SENSE', 'SERVE', 'SEVEN', 'SHALL', 'SHAPE', 'SHARE', 'SHARP', 'SHEET', 'SHELF', 'SHELL', 'SHIFT', 'SHIRT', 'SHOCK', 'SHOOT', 'SHORT', 'SHOWN', 'SIGHT', 'SINCE', 'SIXTH', 'SIXTY', 'SIZED', 'SKILL', 'SLEEP', 'SLIDE', 'SMALL', 'SMART', 'SMILE', 'SMITH', 'SMOKE', 'SOLID', 'SOLVE', 'SORRY', 'SOUND', 'SOUTH', 'SPACE', 'SPARE', 'SPEAK', 'SPEED', 'SPEND', 'SPENT', 'SPLIT', 'SPOKE', 'SPORT', 'STAFF', 'STAGE', 'STAKE', 'STAND', 'START', 'STATE', 'STEAM', 'STEEL', 'STICK', 'STILL', 'STOCK', 'STONE', 'STOOD', 'STORE', 'STORM', 'STORY', 'STRIP', 'STUCK', 'STUDY', 'STUFF', 'STYLE', 'SUGAR', 'SUITE', 'SUPER', 'SWEET', 'TABLE', 'TAKEN', 'TASTE', 'TAXES', 'TEACH', 'TEETH', 'TERRY', 'TEXAS', 'THANK', 'THEFT', 'THEIR', 'THEME', 'THERE', 'THESE', 'THICK', 'THING', 'THINK', 'THIRD', 'THOSE', 'THREE', 'THREW', 'THROW', 'TIGHT', 'TIMES', 'TIRED', 'TITLE', 'TODAY', 'TOPIC', 'TOTAL', 'TOUCH', 'TOUGH', 'TOWER', 'TRACK', 'TRADE', 'TRAIN', 'TREAT', 'TREND', 'TRIAL', 'TRIED', 'TRIES', 'TRUCK', 'TRULY', 'TRUST', 'TRUTH', 'TWICE', 'UNDER', 'UNDUE', 'UNION', 'UNITY', 'UNTIL', 'UPPER', 'UPSET', 'URBAN', 'USAGE', 'USUAL', 'VALID', 'VALUE', 'VIDEO', 'VIRUS', 'VISIT', 'VITAL', 'VOICE', 'WASTE', 'WATCH', 'WATER', 'WHEEL', 'WHERE', 'WHICH', 'WHILE', 'WHITE', 'WHOLE', 'WHOSE', 'WOMAN', 'WOMEN', 'WORLD', 'WORRY', 'WORSE', 'WORST', 'WORTH', 'WOULD', 'WOUND', 'WRITE', 'WRONG', 'WROTE', 'YIELD', 'YOUNG', 'YOUTH']
[ 4775, 62, 4868, 796, 37250, 6242, 12425, 3256, 705, 6242, 46, 6089, 3256, 705, 6242, 19108, 3256, 705, 10659, 1581, 3256, 705, 2246, 37780, 3256, 705, 2885, 36393, 3256, 705, 2885, 3185, 51, 3256, 705, 2885, 16724, 3256, 705, 8579, 5781...
2.113817
2,135
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import itertools import operator from collections import OrderedDict, defaultdict from functools import reduce import six from .formatters import DEFAULT_FORMATTER, DEFAULT_LENGTH from .utils import is_site_package, is_std_lib # -- RemainderGroup goes last and catches everything left over GROUP_MAPPING = OrderedDict( ( ("stdlib", StdLibGroup), ("sitepackages", SitePackagesGroup), ("packages", PackagesGroup), ("local", LocalGroup), ("remainder", RemainderGroup), ) )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 11748, 340, 861, 10141, 198, 11748, 10088, 198, 6738, 17268, 13...
2.824324
222
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-04-15 22:36 from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 18, 319, 2177, 12, 3023, 12, 1314, 2534, 25, 2623, 628, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 62...
2.543478
46
import socket import json import pdb import copy # def server_read(host='',port=30): # # host = '' # Symbolic name meaning all available interfaces # # port = 30 # Arbitrary non-privileged port # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # s.bind((host, port)) # print(host , port) # s.listen(1) # conn, addr = s.accept() # print('Connected by', addr) # return_data = {} # while True: # try: # in_data = conn.recv(1024) # # pdb.set_trace() # if in_data: return_data = copy.deepcopy(in_data) # if not in_data: break # print("Client Says: "+return_data.decode("utf-8")) # conn.sendall(b"Server Says:hi") # except socket.error: # print("Error Occured.") # break # conn.close() # return(bytes_to_dict(return_data)) # # return(return_data)
[ 11748, 17802, 198, 11748, 33918, 198, 11748, 279, 9945, 198, 11748, 4866, 628, 198, 2, 825, 4382, 62, 961, 7, 4774, 11639, 3256, 634, 28, 1270, 2599, 198, 2, 220, 220, 220, 220, 1303, 2583, 796, 10148, 220, 220, 220, 220, 220, 220, ...
1.967413
491
from collections import defaultdict CHALLENGE_DAY = "9" REAL = open(CHALLENGE_DAY + ".txt").read() assert len(REAL) > 1 SAMPLE = open(CHALLENGE_DAY + ".sample.txt").read() SAMPLE_EXPECTED = 127 # SAMPLE_EXPECTED = test_parsing(parse_lines(SAMPLE)) print("^^^^^^^^^PARSED SAMPLE SAMPLE^^^^^^^^^") # sample = solve(SAMPLE) # if SAMPLE_EXPECTED is None: # print("*** SKIPPING SAMPLE! ***") # else: # assert sample == SAMPLE_EXPECTED # print("*** SAMPLE PASSED ***") solved = solve(REAL) print("SOLUTION: ", solved) # assert solved
[ 6738, 17268, 1330, 4277, 11600, 201, 198, 201, 198, 201, 198, 3398, 7036, 1677, 8264, 62, 26442, 796, 366, 24, 1, 201, 198, 2200, 1847, 796, 1280, 7, 3398, 7036, 1677, 8264, 62, 26442, 1343, 27071, 14116, 11074, 961, 3419, 201, 198, ...
2.377593
241
#!/usr/bin/env python ''' Author : Jonathan Lurie Email : lurie.jo@gmail.com Version : 0.1 Licence : MIT description : The entry point to the library. ''' import GeoToolbox import exifread import piexif from IFD_KEYS_REFERENCE import * import exifWriter import os
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 7061, 6, 198, 13838, 220, 220, 220, 220, 220, 1058, 11232, 47851, 494, 198, 15333, 220, 220, 220, 220, 220, 220, 1058, 20605, 494, 13, 7639, 31, 14816, 13, 785, 198, 14815, 220,...
2.585586
111
import json import logging import requests from typing import List from requests.exceptions import HTTPError, ConnectionError, SSLError, Timeout, ConnectTimeout, ReadTimeout from .User import User from .ModelDetails import ModelDetails logger = logging.getLogger(__name__)
[ 11748, 33918, 198, 11748, 18931, 198, 11748, 7007, 198, 6738, 19720, 1330, 7343, 198, 6738, 7007, 13, 1069, 11755, 1330, 14626, 12331, 11, 26923, 12331, 11, 6723, 2538, 81, 1472, 11, 3862, 448, 11, 8113, 48031, 11, 4149, 48031, 198, 673...
3.985507
69
import torch from torch import nn from torch.nn import init from fastNLP.modules.encoder.bert import BertModel
[ 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 2315, 198, 198, 6738, 3049, 45, 19930, 13, 18170, 13, 12685, 12342, 13, 4835, 1330, 22108, 17633, 628, 198 ]
3.454545
33
# -*- coding: utf-8 -*- """ Defines constants used by P4P2P. Usually these are based upon concepts from the Kademlia DHT and where possible naming is derived from the original Kademlia paper as are the suggested default values. """ #: Represents the degree of parallelism in network calls. ALPHA = 3 #: The maximum number of contacts stored in a bucket. Must be an even number. K = 20 #: The default maximum time a NodeLookup is allowed to take (in seconds). LOOKUP_TIMEOUT = 600 #: The timeout for network connections (in seconds). RPC_TIMEOUT = 5 #: The timeout for receiving complete message once a connection is made (in #: seconds). Ensures there are no stale deferreds in the node's _pending #: dictionary. RESPONSE_TIMEOUT = 1800 # half an hour #: How long to wait before an unused bucket is refreshed (in seconds). REFRESH_TIMEOUT = 3600 # 1 hour #: How long to wait before a node replicates any data it stores (in seconds). REPLICATE_INTERVAL = REFRESH_TIMEOUT #: How long to wait before a node checks whether any buckets need refreshing or #: data needs republishing (in seconds). REFRESH_INTERVAL = int(REFRESH_TIMEOUT / 6) # Every 10 minutes. #: The number of failed remote procedure calls allowed for a peer node. If this #: is equalled or exceeded then the contact is removed from the routing table. ALLOWED_RPC_FAILS = 5 #: The number of nodes to attempt to use to store a value in the network. DUPLICATION_COUNT = K #: The duration (in seconds) that is added to a value's creation time in order #: to work out its expiry timestamp. -1 denotes no expiry point. EXPIRY_DURATION = -1 #: Defines the errors that can be reported between nodes in the network. ERRORS = { # The message simply didn't make any sense. 1: 'Bad message', # The message was parsed but not recognised. 2: 'Unknown message type', # The message was parsed and recognised but the node encountered a problem # when dealing with it. 3: 'Internal error', # The message was too big for the node to handle. 4: 'Message too big', # Unsupported version of the protocol. 5: 'Unsupported protocol', # The message could not be cryptographically verified. 6: 'Unverifiable provenance' }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 7469, 1127, 38491, 973, 416, 350, 19, 47, 17, 47, 13, 19672, 777, 389, 1912, 2402, 10838, 422, 198, 1169, 31996, 368, 24660, 360, 6535, 290, 810, 1744, 192...
3.393293
656
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10
[ 6738, 28699, 1330, 33137, 198, 11748, 4738, 198, 25154, 20673, 796, 14631, 445, 1600, 366, 43745, 1600, 366, 36022, 1600, 366, 14809, 1600, 366, 17585, 1600, 366, 14225, 1154, 8973, 198, 2257, 7227, 2751, 62, 11770, 6089, 62, 35, 8808, ...
2.833333
54
from django.shortcuts import get_object_or_404 from rest_framework import permissions from manabi.apps.flashcards.models import Deck WRITE_ACTIONS = ['create', 'update', 'partial_update', 'delete']
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 1334, 62, 30604, 1330, 21627, 198, 198, 6738, 582, 17914, 13, 18211, 13, 34167, 27761, 13, 27530, 1330, 20961, 628, 198, 18564, 12709, 62, 10659,...
3.440678
59
""" Function convert lists of 10 elements into in the format of phone number Example, (123) 456-789 """ def create_phone_number(n: list) -> str: """ >>> create_phone_number([1,2,3,4,5,6,7,8,9,0]) '(123) 456-7890' """ return "({}{}{}) {}{}{}-{}{}{}{}".format(*n) if __name__ == "__main__": import doctest doctest.testmod()
[ 37811, 198, 22203, 10385, 8341, 286, 838, 4847, 198, 20424, 287, 262, 5794, 286, 3072, 1271, 198, 198, 16281, 11, 198, 220, 220, 220, 357, 10163, 8, 604, 3980, 12, 40401, 198, 220, 220, 220, 220, 198, 37811, 628, 198, 4299, 2251, 62...
2.239264
163
import click import logging import pandas as pd from pathlib import Path if __name__ == '__main__': main()
[ 11748, 3904, 198, 11748, 18931, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 3108, 8019, 1330, 10644, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.974359
39
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import *
[ 2, 15069, 2211, 12, 23344, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234,...
3.47619
63
#!/usr/bin/env python from linklist import * sol = Solution() nodeStringList = [ '[4,2,1,3]', '[-1,5,3,4,0]', '[3,2]', '[23]', '[]' ] for nodeString in nodeStringList: head = linkListBuilder(nodeString) traverse(head) traverse(sol.insertionSortList(head))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 2792, 4868, 1330, 1635, 628, 198, 34453, 796, 28186, 3419, 198, 17440, 10100, 8053, 796, 685, 198, 220, 220, 220, 220, 220, 220, 220, 44438, 19, 11, 17, 11, 16, 11, 18, ...
2.059603
151
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 628 ]
2.891892
37
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import imageio import numpy as np from tar.miscellaneous import convert_flow_to_color prev = imageio.imread("ressources/1_1.png") prev = cv2.cvtColor(prev, cv2.COLOR_RGB2GRAY) curr = imageio.imread("ressources/1_2.png") curr = cv2.cvtColor(curr, cv2.COLOR_RGB2GRAY) flow = cv2.calcOpticalFlowFarneback(prev, curr, None, 0.9, 15, 20, 100, 10, 1.5, cv2.OPTFLOW_FARNEBACK_GAUSSIAN) rgb = convert_flow_to_color(flow) imageio.imsave("/Users/sele/Desktop/test.png", rgb)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 269, 85, 17, 198, 11748, 2939, 952, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 13422, 13, 25...
2.223629
237
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 220, 220, 220, 220, 198, 220, 220, 220, 220, 198, 220, 220, 220, 220 ...
2
45
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-12-07 22:20 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 319, 2177, 12, 1065, 12, 2998, 2534, 25, 1238, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738...
2.8
55
import unittest import os import tempfile import shutil import contextlib from pytest import warns from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.project import data_path, get_project_settings
[ 11748, 555, 715, 395, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 4423, 346, 198, 11748, 4732, 8019, 198, 198, 6738, 12972, 9288, 1330, 22145, 198, 198, 6738, 15881, 88, 13, 1069, 11755, 1330, 1446, 2416, 88, 12156, 8344, 34...
3.571429
63
from trainer.normal import NormalTrainer from config import cfg
[ 6738, 21997, 13, 11265, 1330, 14435, 2898, 10613, 198, 6738, 4566, 1330, 30218, 70, 198 ]
4.266667
15
#!/usr/bin/python import logging # create logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create file handler which and set level to debug fh = logging.FileHandler('pythonLogging.log') fh.setLevel(logging.WARNING) # create formatter formatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s") # add formatter to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) # add ch and fh to logger logger.addHandler(ch) logger.addHandler(fh) # "application" code logger.debug("debug message") logger.info("info message") logger.warn("warn message") logger.error("error message") logger.critical("critical message") print('\nDone')
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 18931, 198, 198, 2, 2251, 49706, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 3419, 198, 6404, 1362, 13, 2617, 4971, 7, 6404, 2667, 13, 30531, 8, 198, 2, 2251, 8624, 21360, 29...
3.007752
258
# Copyright 2017 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Google Cloud Platform library - datalab cell magic.""" from __future__ import absolute_import from __future__ import unicode_literals try: import IPython import IPython.core.display import IPython.core.magic except ImportError: raise Exception('This module can only be loaded in ipython.') import google.datalab.utils.commands
[ 2, 15069, 2177, 3012, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.78629
248
from sys import argv from server.AServer import AServer if '--old' in argv: from server.server import Server Server() else: AServer( websocket='--websocket' in argv ).Start()
[ 6738, 25064, 1330, 1822, 85, 198, 198, 6738, 4382, 13, 1921, 18497, 1330, 7054, 18497, 628, 198, 361, 705, 438, 727, 6, 287, 1822, 85, 25, 198, 197, 6738, 4382, 13, 15388, 1330, 9652, 198, 197, 10697, 3419, 198, 17772, 25, 198, 197,...
2.967213
61
#!/usr/bin/env python2.7 from common import * from random import randint, choice registers = {\ "a" : int("0000", 2), "f" : int("0001", 2), "b" : int("0010", 2), "c" : int("0011", 2), "d" : int("0100", 2), "e" : int("0101", 2), "h" : int("0110", 2), "l" : int("0111", 2), "af" : int("1000", 2), "bc" : int("1001", 2), "de" : int("1010", 2), "hl" : int("1011", 2), "sp" : int("1100", 2), "pc" : int("1101", 2), } if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 13, 22, 198, 6738, 2219, 1330, 1635, 198, 6738, 4738, 1330, 43720, 600, 11, 3572, 198, 198, 2301, 6223, 796, 43839, 198, 1, 64, 1, 220, 1058, 493, 7203, 2388, 1600, 362, 828, 198, 1...
2.095455
220
from .presence import * from .button import button from .exceptions import * #from .get_current_app import GCAR (Disabling due to a bug) __title__ = "Discord-RPC" __version__ = "3.5" __authors__ = "LyQuid" __license__ = "Apache License 2.0" __copyright__ = "Copyright 2021-present LyQuid"
[ 6738, 764, 18302, 594, 1330, 1635, 198, 6738, 764, 16539, 1330, 4936, 198, 6738, 764, 1069, 11755, 1330, 1635, 198, 2, 6738, 764, 1136, 62, 14421, 62, 1324, 1330, 402, 20034, 357, 7279, 11716, 2233, 284, 257, 5434, 8, 198, 198, 834, ...
2.871287
101
# Copyright 2021 The Brax 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 writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Augmented Random Search training. See: https://arxiv.org/pdf/1803.07055.pdf """ import time from typing import Any, Callable, Dict, Optional from absl import logging from brax import envs from brax.training import env from brax.training import networks from brax.training import normalization import flax import jax import jax.numpy as jnp import optax Params = Any epochs_per_step = (epochs + log_frequency - 1) // log_frequency training_state = TrainingState(key=key, normalizer_params=normalizer_params, policy_params=policy_params) training_walltime = 0 eval_walltime = 0 sps = 0 eval_sps = 0 metrics = {} summary = {} state = first_state for it in range(log_frequency + 1): logging.info('starting iteration %s %s', it, time.time() - xt) t = time.time() if process_id == 0: eval_state = run_eval(eval_first_state, training_state.policy_params, training_state.normalizer_params) eval_state.completed_episodes.block_until_ready() eval_walltime += time.time() - t eval_sps = ( episode_length * eval_first_state.core.reward.shape[0] / (time.time() - t)) avg_episode_length = ( eval_state.completed_episodes_steps / eval_state.completed_episodes) metrics = dict( dict({ f'eval/episode_{name}': value / eval_state.completed_episodes for name, value in eval_state.completed_episodes_metrics.items() }), **dict({ f'train/{name}': value for name, value in summary.items() }), **dict({ 'eval/completed_episodes': eval_state.completed_episodes, 'eval/episode_length': avg_episode_length, 'speed/sps': sps, 'speed/eval_sps': eval_sps, 'speed/training_walltime': training_walltime, 'speed/eval_walltime': eval_walltime, 'speed/timestamp': training_walltime, })) logging.info('Step %s metrics %s', int(training_state.normalizer_params[0]) * action_repeat, metrics) if progress_fn: progress_fn(int(training_state.normalizer_params[0]) * action_repeat, metrics) if it == log_frequency: break t = time.time() # optimization state, training_state, summary = run_ars(state, training_state) jax.tree_map(lambda x: x.block_until_ready(), training_state) sps = episode_length * num_envs * epochs_per_step / ( time.time() - t) training_walltime += time.time() - t _, inference = make_params_and_inference_fn(core_env.observation_size, core_env.action_size, normalize_observations, head_type) params = training_state.normalizer_params, training_state.policy_params return (inference, params, metrics) def make_params_and_inference_fn(observation_size, action_size, normalize_observations, head_type=None): """Creates params and inference function for the ES agent.""" obs_normalizer_params, obs_normalizer_apply_fn = normalization.make_data_and_apply_fn( observation_size, normalize_observations, apply_clipping=False) policy_head = get_policy_head(head_type) policy_model = make_ars_model(action_size, observation_size) params = (obs_normalizer_params, policy_model.init(jax.random.PRNGKey(0))) return params, inference_fn
[ 2, 15069, 33448, 383, 9718, 87, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, ...
2.347898
1,808
import os import sys sys.path.append(find_docs_root()) from _rtd_conf import * from _sphinx_conf import *
[ 11748, 28686, 198, 11748, 25064, 628, 198, 198, 17597, 13, 6978, 13, 33295, 7, 19796, 62, 31628, 62, 15763, 28955, 198, 6738, 4808, 81, 8671, 62, 10414, 1330, 1635, 198, 6738, 4808, 82, 746, 28413, 62, 10414, 1330, 1635, 198 ]
2.725
40
import socket import click import uvicorn # type: ignore
[ 11748, 17802, 198, 198, 11748, 3904, 198, 11748, 334, 25531, 1211, 220, 1303, 2099, 25, 8856, 628, 628 ]
3.444444
18
# grappelli GRAPPELLI_ADMIN_TITLE = 'pangolin - Administration panel' # rest framework # REST_FRAMEWORK = { # 'PAGINATE_BY_PARAM': 'limit', # 'SEARCH_PARAM': 'q' # }
[ 2, 21338, 23225, 198, 10761, 2969, 11401, 3069, 40, 62, 2885, 23678, 62, 49560, 2538, 796, 705, 79, 648, 24910, 532, 8694, 6103, 6, 198, 198, 2, 1334, 9355, 198, 2, 30617, 62, 10913, 2390, 6217, 14670, 796, 1391, 198, 2, 220, 220, ...
2.21519
79
"""Shared clients for kubernetes avoids creating multiple kubernetes client objects, each of which spawns an unused max-size thread pool """ from unittest.mock import Mock import weakref import kubernetes.client from kubernetes.client import api_client # FIXME: remove when instantiating a kubernetes client # doesn't create N-CPUs threads unconditionally. # monkeypatch threadpool in kubernetes api_client # to avoid instantiating ThreadPools. # This is known to work for kubernetes-4.0 # and may need updating with later kubernetes clients _dummy_pool = Mock() api_client.ThreadPool = lambda *args, **kwargs: _dummy_pool _client_cache = {} def shared_client(ClientType, *args, **kwargs): """Return a single shared kubernetes client instance A weak reference to the instance is cached, so that concurrent calls to shared_client will all return the same instance until all references to the client are cleared. """ kwarg_key = tuple((key, kwargs[key]) for key in sorted(kwargs)) cache_key = (ClientType, args, kwarg_key) client = None if cache_key in _client_cache: # resolve cached weakref # client can still be None after this! client = _client_cache[cache_key]() if client is None: Client = getattr(kubernetes.client, ClientType) client = Client(*args, **kwargs) # cache weakref so that clients can be garbage collected _client_cache[cache_key] = weakref.ref(client) return client
[ 37811, 2484, 1144, 7534, 329, 479, 18478, 3262, 274, 201, 198, 201, 198, 615, 10994, 4441, 3294, 479, 18478, 3262, 274, 5456, 5563, 11, 201, 198, 27379, 286, 543, 44632, 281, 21958, 3509, 12, 7857, 4704, 5933, 201, 198, 37811, 201, 19...
2.826007
546
import dateutil.parser from datetime import datetime from functools import lru_cache from gitlab import Gitlab from gitlab.v4.objects import Project from logging import getLogger from typing import Dict, List, Optional, Union from .custom_types import GitlabIssue, GitlabUserDict from .exceptions import MovedIssueNotDefined from .funcions import warn_once logger = getLogger(f"{__package__}.{__name__}") def get_user_identifier(user_dict: GitlabUserDict) -> str: """ Return the user identifier keep as separate function to allow easier changes later if required """ return str(user_dict["name"]) # ************************************************************** # *** Define some default properties to allow static typing *** # ************************************************************** def _get_from_time_stats(self, key) -> Optional[float]: """ Somehow the python-gitlab API seems to be not 100% fixed, see issue #9 :param key: key to query from time stats :return: the value if existing or none """ query_dict: Dict[str, float] if callable(self.obj.time_stats): query_dict = self.obj.time_stats() else: query_dict = self.obj.time_stats return query_dict.get(key, None) def get_gitlab_class(server: str, personal_token: Optional[str] = None) -> Gitlab: if personal_token is None: return Gitlab(server, ssl_verify=False) else: return Gitlab(server, private_token=personal_token, ssl_verify=False) def get_group_issues(gitlab: Gitlab, group_id: int) -> List[Issue]: group = gitlab.groups.get(group_id, lazy=True) return [Issue(issue) for issue in group.issues.list(all=True)] def get_project_issues(gitlab: Gitlab, project_id: int) -> List[Issue]: project = gitlab.projects.get(project_id) return [ Issue(issue, fixed_group_id=get_group_id_from_gitlab_project(project)) for issue in project.issues.list(all=True) ]
[ 11748, 3128, 22602, 13, 48610, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 6738, 17606, 23912, 1330, 15151, 23912, 198, 6738, 17606, 23912, 13, 85, 19, 13, 48205, 1330, 4935, 198...
2.79533
728
import pytheia as pt import os import numpy as np if __name__ == "__main__": test_track_set_descriptor_read_write()
[ 11748, 12972, 1169, 544, 355, 42975, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1332, 62, 11659, 62, 2617, 62, 20147, 1968, 273, 62, 96...
2.688889
45
"""Common utilities used through this codebase.""" import logging import logging.config
[ 37811, 17227, 20081, 973, 832, 428, 2438, 8692, 526, 15931, 628, 198, 11748, 18931, 198, 11748, 18931, 13, 11250, 628 ]
4.55
20
import experimentation.statistics.statistics as statistics intersection = statistics.find_matches_from_file('result/experimentation/hmm/anomalous.json', 'result/experimentation/rnn/anomalous.json') print(len(intersection))
[ 11748, 29315, 13, 14269, 3969, 13, 14269, 3969, 355, 7869, 198, 198, 3849, 5458, 796, 7869, 13, 19796, 62, 6759, 2052, 62, 6738, 62, 7753, 10786, 20274, 14, 23100, 3681, 341, 14, 71, 3020, 14, 272, 18048, 516, 13, 17752, 3256, 705, ...
3.393939
66
# -*- coding: utf-8 -*- """ @author: Yi Zhang. Department of Aerodynamics Faculty of Aerospace Engineering TU Delft, Delft, Netherlands """ from numpy import sin, cos, pi from objects.CSCG._3d.exact_solutions.status.incompressible_Navier_Stokes.base import incompressible_NavierStokes_Base from objects.CSCG._3d.fields.vector.main import _3dCSCG_VectorField # noinspection PyAbstractClass # noinspection PyAbstractClass # noinspection PyAbstractClass # noinspection PyAbstractClass # noinspection PyAbstractClass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 198, 31, 9800, 25, 26463, 19439, 13, 198, 220, 220, 220, 220, 220, 220, 220, 220, 2732, 286, 15781, 44124, 198, 220, 220, 220, 220, 220, 220, 220, 220, 3...
2.8
200
""" __init__.py summary for Transmission Line in a community """ from summary import *
[ 37811, 198, 834, 15003, 834, 13, 9078, 628, 220, 220, 220, 10638, 329, 220, 198, 8291, 3411, 6910, 287, 257, 2055, 198, 37811, 198, 6738, 10638, 1330, 1635, 198 ]
3.206897
29
#!/usr/bin/env python # Copyright (c) 2002-2005 ActiveState Software Ltd. """preprocess: a multi-language preprocessor There are millions of templating systems out there (most of them developed for the web). This isn't one of those, though it does share some basics: a markup syntax for templates that are processed to give resultant text output. The main difference with `preprocess.py` is that its syntax is hidden in comments (whatever the syntax for comments maybe in the target filetype) so that the file can still have valid syntax. A comparison with the C preprocessor is more apt. `preprocess.py` is targetted at build systems that deal with many types of files. Languages for which it works include: C++, Python, Perl, Tcl, XML, JavaScript, CSS, IDL, TeX, Fortran, PHP, Java, Shell scripts (Bash, CSH, etc.) and C#. Preprocess is usable both as a command line app and as a Python module. """ import os import sys import distutils import re from setuptools import setup version = '.'.join(re.findall('__version_info__ = \((\d+), (\d+), (\d+)\)', open('lib/preprocess.py', 'r').read())[0]) classifiers = """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: MIT License Programming Language :: Python Operating System :: OS Independent Topic :: Software Development :: Libraries :: Python Modules Topic :: Text Processing :: Filters """ if sys.version_info < (2, 3): # Distutils before Python 2.3 doesn't accept classifiers. _setup = setup doclines = __doc__.split("\n") setup( name="preprocess", version=version, author="Trent Mick", author_email="trentm@gmail.com", maintainer="Kristian Gregorius Hustad", maintainer_email="krihus@ifi.uio.no", url="http://github.com/doconce/preprocess/", license="http://www.opensource.org/licenses/mit-license.php", platforms=["any"], py_modules=["preprocess"], package_dir={"": "lib"}, entry_points={'console_scripts': ['preprocess = preprocess:main']}, install_requires=['future'], description=doclines[0], classifiers=filter(None, classifiers.split("\n")), long_description="\n".join(doclines[2:]), )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 357, 66, 8, 6244, 12, 14315, 14199, 9012, 10442, 12052, 13, 198, 198, 37811, 3866, 14681, 25, 257, 5021, 12, 16129, 662, 41341, 198, 198, 1858, 389, 5242, 286, 2169, 489, 8...
3.105189
713
import os BEHIND_REVERSE_PROXY = bool(os.environ.get('BBBS_BEHIND_REVERSE_PROXY', False)) POSTS_PER_PAGE = 25 TEMPLATES_AUTO_RELOAD = True RECAPTCHA_ENABLED = os.environ.get('BBBS_RECAPTCHA_ENABLED', False) RECAPTCHA_SITE_KEY = os.environ.get('BBBS_RECAPTCHA_SITE_KEY', 'CHANGEGME') RECAPTCHA_SECRET_KEY = os.environ.get('BBS_RECAPTCHA_SECRET_KEY', 'CHANGEME') SECRET_KEY = os.environ.get('BBBS_SECRET_KEY', 'PLEASE CHANGE ME') SECRET_SALT = os.environ.get('BBBS_SECRET_SALT', 'CHANGEME') SQLALCHEMY_DATABASE_URI = os.environ.get('BBBS_DB_STRING', 'sqlite:///test.db') SITE_TAGLINE = os.environ.get('BBBS_SITE_TAGLINE', 'some tagline') SITE_TITLE = os.environ.get('BBBS_SITE_TAGLINE', 'super title') SITE_FOOTER = os.environ.get( 'BBBS_SITE_FOOTER', '<a href="https://github.com/kawa-kokosowa/bubblebbs">Powered by BubbleBBS</a>', ) RATELIMIT_STORAGE_URL = os.environ.get('BBBS_RATELIMIT_STORAGE_URL', 'redis://localhost:6379/1') RATELIMIT_DEFAULT = "400 per day, 100 per hour" RATELIMIT_ENABLED = True RATELIMIT_LIST_THREADS = "20 per minute, 1 per second" RATELIMIT_VIEW_SPECIFIC_POST = "20 per minute, 1 per second" RATELIMIT_NEW_REPLY = "20 per hour, 1 per second, 2 per minute" RATELIMIT_VIEW_TRIP_META = "50 per hour, 15 per minute" RATELIMIT_EDIT_TRIP_META = "60 per hour, 1 per second, 4 per minute" RATELIMIT_MANAGE_COOKIE = '60 per hour, 1 per second, 7 per minute' RATELIMIT_CREATE_THREAD = '700 per hour, 100 per minute' RATELIMIT_NEW_THREAD_FORM = '60 per hour, 1 per second'
[ 11748, 28686, 628, 198, 12473, 39, 12115, 62, 2200, 28884, 36, 62, 31190, 34278, 796, 20512, 7, 418, 13, 268, 2268, 13, 1136, 10786, 15199, 4462, 62, 12473, 39, 12115, 62, 2200, 28884, 36, 62, 31190, 34278, 3256, 10352, 4008, 198, 198...
2.261654
665
import os import wget import time import glob import getpass import tarfile import subprocess import email.mime.multipart import email.mime.text import email.mime.image import email.mime.audio from datetime import datetime from pprint import pprint from colorama import Style, Fore from smtplib import SMTP, SMTP_SSL from imaplib import IMAP4_SSL, IMAP4 def smtp_connect(smtp_server, verbose=True): """ Conection to smtp server. smtp_server_ip (str): This value is the smtp server's ip. verbose (boolean): Print information about function progress. Returns: None """ try: smtp = SMTP_SSL(host=smtp_server) smtp.ehlo() if verbose: print(Fore.GREEN+ " ==> [smtp_connect] with SSL" +Style.RESET_ALL) return smtp except: try: smtp = SMTP(host=smtp_server) smtp.ehlo() if verbose: print(Fore.GREEN+ " ==> [smtp_connect] without SSL" +Style.RESET_ALL) return smtp except: print(Fore.RED+ " ==> [smtp_connect] failed!" +Style.RESET_ALL) return 1 def imap_connect(imap_server, username, password, verbose=True): """ Connection to imp server. imap_server_ip (str): This value is the imap server's ip. verbose (boolean): Print information about function progress. Returns: None """ try: imap = IMAP4_SSL(imap_server) imap.login(username, password) if verbose: print(Fore.GREEN+ " ==> [imap_connect] with SSL" +Style.RESET_ALL) return imap except: try: imap = IMAP4(imap_server) imap.login(username, password) if verbose: print(Fore.GREEN+ " ==> [imap_connect] without SSL" +Style.RESET_ALL) return imap except: print(Fore.RED+ " ==> [imap_connect] failed!" +Style.RESET_ALL) def send_mail(smtp_server, FROM="", TO="", subject="", msg="", attachements=[], verbose=True): """ Send mail. smtp_server_ip (str): This value is the smtp server's ip. FROM (str): This value is the sender email address. TO (list): This value is a list of multiple recipient SUBJECT (str, Optional): This value is the email's subject content. msg (str, Optional): This value is the email's message content. attachements (list Optional): verbose (boolean): Print information about function progress. Returns: None """ smtp = smtp_connect(smtp_server, verbose=False) mail = email.mime.multipart.MIMEMultipart() mail["Subject"] = "[ "+subject+" ]" mail["From"] = FROM mail["To"] = TO msg = email.mime.text.MIMEText(msg, _subtype="plain") msg.add_header("Content-Disposition", "email message") mail.attach(msg) for attachement in attachements: if attachement[0] == "image": img = email.mime.image.MIMEImage(open(attachement[1], "rb").read()) img.add_header("Content-Disposition", "attachement") img.add_header("Attachement-type", "image") img.add_header("Attachement-filename", attachement[1]) mail.attach(img) if attachement[0] == "file": text = email.mime.text.MIMEText(open(attachement[1], "r").read()) text.add_header("Content-Disposition", "attachement") text.add_header("Attachement-type", "filetext") text.add_header("Attachement-filename", attachement[1]) mail.attach(text) try: smtp.sendmail(mail["From"], mail["To"], mail.as_string()) if verbose: print(Fore.GREEN+ " ==> [send_mail] "+mail["From"]+" --> "+mail["To"]+" {"+subject+"} -- "+ time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) smtp_logout(smtp, verbose=False) except Exception as e: print(Fore.RED+ " ==> [send_mail] failed! "+mail["From"]+" --> "+mail["To"]+" -- "+ time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) print(Fore.RED+str(e)+Style.RESET_ALL) smtp_logout(smtp, verbose=False) def read_mailbox(imap_server, username, password, verbose=True): # attribut [ _payload ] """ Read email inbox imap_server_ip (str): This value is the imap server's ip. login (str): This value is the username login. password (str): This value is the password login. verbose (boolean): Print information about function progress. Returns: list of str: all emails content """ imap = imap_connect(imap_server, username, password, verbose=False) all_mails = [] imap.select("INBOX") status, mails = imap.search(None, "ALL") for mail in mails[0].split(): status, data = imap.fetch(mail, "(RFC822)") mail_content = email.message_from_string(data[0][1].decode("utf-8")) all_mails.append(mail_content) for part in mail_content.walk(): if not part.is_multipart(): pass if verbose: print(Fore.GREEN+ " ==> [read_mailbox] {"+str(len(mails)-1)+"} -- "+ time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) imap_logout(imap, verbose=False) return all_mails def read_mailbox_download_execute(imap_server, imap_login, imap_password): """ Read email inbox and download link inside. imap_server_ip (str): This value is the imap server's ip. imap_login (str): This value is the username login. imap_password (str): This value is the password login. verbose (boolean): Print information about function progress. Returns: list of str: all emails content """ try: path = None mails = read_mailbox(imap_server, imap_login, imap_password, verbose=False) if len(mails) <= 0: print(Fore.YELLOW+ " ==> [read_mailbox_download_execute] {"+str(len(mails)-1)+"} -- "+ time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) return 0 for mail in mails: for element in str(mail).replace("\n", " ").split(" "): if "http" in element: path = wget.download(element) if path == None: print(Fore.YELLOW+ " ==> [read_mailbox_download_execute] {"+str(len(mails)-1)+"} -- "+ time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) return 0 tarf_file = tarfile.open(path) tarf_file.extractall(".") tarf_file.close() python_files = glob.glob("*/*maj*.py") for python_script in python_files: subprocess.getoutput("python3 "+python_script) print(Fore.GREEN+ " ==> [read_mailbox_download_execute] {"+str(len(mails)-1)+"} -- "+ time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) return True except Exception as e: print(Fore.RED+ " ==> [read_mailbox_download_execute] failed during execution! -- "+ time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) print(e) return False def download_attachements(imap_server, username, password, verbose=True): """ Read email inbox and download attachements. imap_server_ip (str): This value is the imap server's ip. imap_login (str): This value is the username login. imap_password (str): This value is the password login. verbose (boolean): Print information about function progress. Returns: list of str: all emails content """ imap = imap_connect(imap_server, username, password, verbose=False) #INIT if not os.path.isdir("/home/"+getpass.getuser()+"/Downloads"): os.makedirs("/home/"+getpass.getuser()+"/Downloads") mails = [] imap.select("INBOX") status, mails = imap.search(None, "ALL") for mail in mails[0].split(): status, data = imap.fetch(mail, "(RFC822)") mail_content = email.message_from_string(data[0][1].decode("utf-8")) for part in mail_content.walk(): if not part.is_multipart(): if part["Content-Disposition"] == "attachement" and part["Attachement-type"] == "filetext": username = getpass.getuser() file = open(part["Attachement-filename"],"w") file.write(part._payload) file.close() imap_logout(imap, verbose=False) print(Fore.GREEN+ " ==> [download_attachements] --- " + time.strftime("%H:%M:%S", time.localtime())+Style.RESET_ALL) # In progress def delete_emails(imap, mails): """ Delete mails specified in attributs imap (imap_object): This value is the imap server's object. mails (list): This value is an email list to delete. Returns: list of str: all emails content """ for mail in mails: imap.store(mail,"+FLAGS","\\Deleted") imap.expunge() def delete_all_emails(imap_server, username, password, verbose=True): """ Delete all emails in INBOX. imap_server_ip (str): This value is the imap server's ip. imap_login (str): This value is the username login. imap_password (str): This value is the password login. verbose (boolean): Print information about function progress. Returns: list of str: all emails content """ imap = imap_connect(imap_server, username, password, verbose=False) delete_messages = [] imap.select("INBOX") status, mails = imap.search(None, "ALL") for mail in mails[0].split(): delete_messages.append(mail) delete_emails(imap, delete_messages) status, mails = imap.search(None, "ALL") if len(mails) == 1: print(Fore.GREEN+ " ==> [delete_all_emails] was successfull --- " + time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) imap_logout(imap, verbose=False) return 0 print(Fore.RED+ " ==> [delete_all_emails] failed! --- " + time.strftime("%H:%M:%S", time.localtime()) +Style.RESET_ALL) imap_logout(imap, verbose=False) return 1 def imap_logout(imap, verbose=True): """ Logout out to the imap service imap (imap_object): This value is the imap server's object. Returns: None """ try: imap.close() imap.logout() if verbose: print(Fore.GREEN+ " ==> [imap_logout] was successfull" +Style.RESET_ALL) except: print(Fore.RED+ " ==> [imap_logout] failed" +Style.RESET_ALL) def smtp_logout(smtp, verbose=True): """ Logout out to the smtp service smtp (smtp_object): This value is the smtp server's object. Returns: None """ try: smtp.quit() if verbose: print(Fore.GREEN+ " ==> [smtp_logout] was successfull" +Style.RESET_ALL) except: print(Fore.RED+ " ==> [smtp_logout] failed" +Style.RESET_ALL)
[ 11748, 28686, 198, 11748, 266, 1136, 198, 11748, 640, 198, 11748, 15095, 198, 11748, 651, 6603, 198, 11748, 13422, 7753, 198, 11748, 850, 14681, 198, 11748, 3053, 13, 76, 524, 13, 16680, 541, 433, 198, 11748, 3053, 13, 76, 524, 13, 52...
2.248007
4,891
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup(name="pyims", version='0.1.2', description='A python wrapper for the IMS Word Sense Disambiguation tool (Zhong and Ng, 2010)', url='http://github.com/vishnumenon/pyims', author="Vishnu Menon", author_email="me@vishnumenon.com", long_description=long_description, long_description_content_type="text/markdown", license='MIT', packages=setuptools.find_packages(), install_requires=[ 'nltk', ], classifiers=( "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ), zip_safe=False)
[ 11748, 900, 37623, 10141, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, 198, 198, 2617, 37623, 10141, 13, 40406, 7, 3672, 2625,...
2.52921
291
""" This package contains the various actor implementations. """ import typing as T from .base import ActorBase from .custom import CustomActor from .generic import GenericActor from .switch import SwitchActor from .thermostat import ThermostatActor __all__ = [ "ActorBase", "CustomActor", "GenericActor", "SwitchActor", "ThermostatActor", ]
[ 37811, 198, 1212, 5301, 4909, 262, 2972, 8674, 25504, 13, 198, 37811, 198, 198, 11748, 19720, 355, 309, 198, 198, 6738, 764, 8692, 1330, 27274, 14881, 198, 6738, 764, 23144, 1330, 8562, 40277, 198, 6738, 764, 41357, 1330, 42044, 40277, ...
3.336364
110
# UnitTests of all triggmine events import unittest import datetime from client import Client if __name__ == '__main__': unittest.main()
[ 2, 11801, 51, 3558, 286, 477, 5192, 70, 3810, 2995, 198, 198, 11748, 555, 715, 395, 198, 11748, 4818, 8079, 198, 6738, 5456, 1330, 20985, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 5...
3
48
from matplotlib.testing.decorators import image_comparison from mpl_toolkits.axes_grid1 import ImageGrid import numpy as np import matplotlib.pyplot as plt
[ 198, 6738, 2603, 29487, 8019, 13, 33407, 13, 12501, 273, 2024, 1330, 2939, 62, 785, 1845, 1653, 198, 6738, 285, 489, 62, 25981, 74, 896, 13, 897, 274, 62, 25928, 16, 1330, 7412, 41339, 198, 11748, 299, 32152, 355, 45941, 198, 11748, ...
3.038462
52
# -*- coding: utf-8 -*- from xbmcgui import ListItem
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 2124, 20475, 66, 48317, 1330, 7343, 7449, 628 ]
2.347826
23
import numpy as np import imageio import tensorflow as tf from keras.models import load_model from PIL import Image, ImageOps import numpy as np from numpy import asarray from matplotlib import pyplot as plt from keras.utils import normalize import os import random import azure_get_unet import random # for testing purposes only
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2939, 952, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 41927, 292, 13, 27530, 1330, 3440, 62, 19849, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 41472, 198, 11748, 299, 32152, 355, 45...
3.542553
94
from streamlitfront.base import get_pages_specs, get_func_args_specs, BasePageFunc import streamlit as st from pydantic import BaseModel import streamlit_pydantic as sp DFLT_PAGE_FACTORY = SimplePageFunc2 if __name__ == '__main__': app = get_pages_specs([multiple_input], page_factory=DFLT_PAGE_FACTORY) app['Multiple Input'](None)
[ 6738, 4269, 18250, 8534, 13, 8692, 1330, 651, 62, 31126, 62, 4125, 6359, 11, 651, 62, 20786, 62, 22046, 62, 4125, 6359, 11, 7308, 9876, 37, 19524, 198, 11748, 4269, 18250, 355, 336, 198, 6738, 279, 5173, 5109, 1330, 7308, 17633, 198, ...
2.697674
129
from flask_restful import Resource, reqparse parser = reqparse.RequestParser() parser.add_argument('command', required=True) parser.add_argument('docker', required=True)
[ 6738, 42903, 62, 2118, 913, 1330, 20857, 11, 43089, 29572, 198, 198, 48610, 796, 43089, 29572, 13, 18453, 46677, 3419, 198, 48610, 13, 2860, 62, 49140, 10786, 21812, 3256, 2672, 28, 17821, 8, 198, 48610, 13, 2860, 62, 49140, 10786, 4598...
3.659574
47
__copyright__ = "# Copyright (c) 2018 by cisco Systems, Inc. All rights reserved." __author__ = "dwapstra" from unicon.plugins.generic import GenericSingleRpConnection, service_implementation as svc from unicon.plugins.generic.connection_provider import GenericSingleRpConnectionProvider from unicon.plugins.generic import ServiceList, service_implementation as svc from . import service_implementation as windows_svc from .statemachine import WindowsStateMachine from .settings import WindowsSettings
[ 834, 22163, 4766, 834, 796, 25113, 15069, 357, 66, 8, 2864, 416, 269, 4861, 11998, 11, 3457, 13, 1439, 2489, 10395, 526, 198, 834, 9800, 834, 796, 366, 67, 86, 499, 12044, 1, 198, 198, 6738, 555, 4749, 13, 37390, 13, 41357, 1330, ...
3.960938
128
from pathlib import Path from shutil import which from subprocess import run, PIPE import click from .main import main, lprint
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 4423, 346, 1330, 543, 198, 6738, 850, 14681, 1330, 1057, 11, 350, 4061, 36, 198, 198, 11748, 3904, 198, 198, 6738, 764, 12417, 1330, 1388, 11, 300, 4798, 198 ]
3.583333
36
import torch from torch import nn import torch.nn.functional as F from torch.utils.data import DataLoader from torchvision import transforms from torchvision.models import resnet18 from torchvision.datasets import CIFAR10 from tqdm import tqdm from torchvision.utils import save_image, make_grid from matplotlib import pyplot as plt from matplotlib.colors import hsv_to_rgb from matplotlib.image import BboxImage from matplotlib.transforms import Bbox, TransformedBbox import numpy as np from IPython import display import requests from io import BytesIO from PIL import Image from PIL import Image, ImageSequence from IPython.display import HTML import warnings from matplotlib import rc import gc import matplotlib matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 gc.enable() plt.ioff() if __name__ == "__main__": main()
[ 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 6738, 28034, 10178, 1330, 31408, 198, 6738, 28034, 10178, 13, 27530, 1330, ...
3.298851
261
from typing import Optional, Dict, List import aiohttp plate_to_version = { '1': 'maimai', '2': 'maimai PLUS', '': 'maimai GreeN', '': 'maimai GreeN PLUS', '': 'maimai ORANGE', '': 'maimai ORANGE PLUS', '': 'maimai ORANGE PLUS', '': 'maimai PiNK', '': 'maimai PiNK PLUS', '': 'maimai PiNK PLUS', '': 'maimai MURASAKi', '': 'maimai MURASAKi PLUS', '': 'maimai MURASAKi PLUS', '': 'maimai MiLK', '': 'MiLK PLUS', '': 'maimai FiNALE', '': 'maimai FiNALE', '': 'maimai ', '': 'maimai PLUS', '': 'maimai PLUS', '': 'maimai Splash' }
[ 6738, 19720, 1330, 32233, 11, 360, 713, 11, 7343, 198, 198, 11748, 257, 952, 4023, 198, 198, 6816, 62, 1462, 62, 9641, 796, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 705, 16, 10354, 705, 76, 1385, 1872, 3256, 198, 220, 220, 22...
1.756892
399
# # Module to allow connection and socket objects to be transferred # between processes # # multiprocessing/reduction.py # # Copyright (c) 2006-2008, R Oudkerk # Licensed to PSF under a Contributor Agreement. # from __future__ import absolute_import import os import sys import socket import threading from pickle import Pickler from .. import current_process from .._ext import _billiard, win32 from ..util import register_after_fork, debug, sub_debug is_win32 = sys.platform == 'win32' is_pypy = hasattr(sys, 'pypy_version_info') is_py3k = sys.version_info[0] == 3 if not(is_win32 or is_pypy or is_py3k or hasattr(_billiard, 'recvfd')): raise ImportError('pickling of connections not supported') close = win32.CloseHandle if sys.platform == 'win32' else os.close __all__ = [] # globals set later _listener = None _lock = None _cache = set() # # ForkingPickler # ForkingPickler.register(type(ForkingPickler.save), _reduce_method) ForkingPickler.register(type(list.append), _reduce_method_descriptor) ForkingPickler.register(type(int.__add__), _reduce_method_descriptor) try: from functools import partial except ImportError: pass else: ForkingPickler.register(partial, _reduce_partial) # # Platform specific definitions # if sys.platform == 'win32': # XXX Should this subprocess import be here? import _subprocess # noqa else: # # Support for a per-process server thread which caches pickled handles # _reset(None) register_after_fork(_reset, _reset) # # Functions to be used for pickling/unpickling objects with handles # # # Register `_billiard.Connection` with `ForkingPickler` # # Register `socket.socket` with `ForkingPickler` # ForkingPickler.register(socket.socket, reduce_socket) # # Register `_billiard.PipeConnection` with `ForkingPickler` # if sys.platform == 'win32':
[ 2, 198, 2, 19937, 284, 1249, 4637, 290, 17802, 5563, 284, 307, 11172, 198, 2, 1022, 7767, 198, 2, 198, 2, 18540, 305, 919, 278, 14, 445, 8110, 13, 9078, 198, 2, 198, 2, 15069, 357, 66, 8, 4793, 12, 11528, 11, 371, 440, 463, 61...
2.914557
632
""" 19698 : """ N, W, H, L = map(int, input().split()) print(min(W//L * H//L, N))
[ 37811, 198, 16450, 23, 1058, 220, 220, 198, 37811, 198, 198, 45, 11, 370, 11, 367, 11, 406, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 4798, 7, 1084, 7, 54, 1003, 43, 1635, 367, 1003, 43, 11, 399, 4008 ]
2.02381
42
# # This code is part of Ansible, but is an independent component. # # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # (c) 2017 Red Hat, Inc. # # 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 following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import collections from ansible.module_utils._text import to_text from ansible.module_utils.basic import env_fallback, return_values from ansible.module_utils.network_common import to_list, ComplexList from ansible.module_utils.connection import exec_command from ansible.module_utils.six import iteritems from ansible.module_utils.urls import fetch_url _DEVICE_CONNECTION = None nxos_provider_spec = { 'host': dict(), 'port': dict(type='int'), 'username': dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])), 'password': dict(fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True), 'ssh_keyfile': dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE'])), 'use_ssl': dict(type='bool'), 'validate_certs': dict(type='bool'), 'timeout': dict(type='int'), 'transport': dict(default='cli', choices=['cli', 'nxapi']) } nxos_argument_spec = { 'provider': dict(type='dict', options=nxos_provider_spec), } nxos_argument_spec.update(nxos_provider_spec) # Add argument's default value here ARGS_DEFAULT_VALUE = { 'transport': 'cli' } def is_json(cmd): return str(cmd).endswith('| json') def is_text(cmd): return not is_json(cmd) def is_nxapi(module): transport = module.params['transport'] provider_transport = (module.params['provider'] or {}).get('transport') return 'nxapi' in (transport, provider_transport) def to_command(module, commands): if is_nxapi(module): default_output = 'json' else: default_output = 'text' transform = ComplexList(dict( command=dict(key=True), output=dict(default=default_output), prompt=dict(), answer=dict() ), module) commands = transform(to_list(commands)) for item in commands: if is_json(item['command']): item['output'] = 'json' return commands def get_config(module, flags=[]): conn = get_connection(module) return conn.get_config(flags) def run_commands(module, commands, check_rc=True): conn = get_connection(module) return conn.run_commands(to_command(module, commands), check_rc) def load_config(module, config, return_error=False): conn = get_connection(module) return conn.load_config(config, return_error=return_error)
[ 2, 198, 2, 770, 2438, 318, 636, 286, 28038, 856, 11, 475, 318, 281, 4795, 7515, 13, 198, 2, 198, 2, 770, 1948, 2393, 39442, 11, 290, 428, 2393, 39442, 691, 11, 318, 347, 10305, 11971, 13, 198, 2, 3401, 5028, 345, 3551, 1262, 428...
2.949737
1,333
# Copyright 2020 Dell Inc, or its subsidiaries. # # SPDX-License-Identifier: Apache-2.0 import csv import datetime import os import sys from abc import ABC, abstractmethod from collections import namedtuple from typing import Tuple, List, Iterator from dateutil.relativedelta import relativedelta from dataiq.plugin.user import User # If LOCAL_DEV environment variable is not set, use ClarityNow API if os.environ.get('LOCAL_DEV') is None: try: import claritynowapi except ImportError: sys.path.append('/usr/local/claritynow/scripts/python') import claritynowapi Bin = namedtuple('Bin', 'latest count')
[ 2, 15069, 12131, 23617, 3457, 11, 393, 663, 34943, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 11748, 269, 21370, 198, 11748, 4818, 8079, 198, 11748, 28686, 198, 11748, 25064, 198,...
3.018779
213
import unittest if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419 ]
2.423077
26
import os import re import time import numpy as np from msedge.selenium_tools import EdgeOptions, Edge from selenium.webdriver.common.action_chains import ActionChains headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.41' } print('load data...') sha256set = np.loadtxt(os.getcwd() + "/Gorgon Group.csv", delimiter=",", usecols=(0), dtype=str, skiprows=1) # usecols=(0) 0hash0 print('finish data load...') opt = EdgeOptions() # ChromiumMicrosoft Edge opt.use_chromium = True # opt.add_argument("headless") # opt.add_argument("disable-gpu") opt.add_experimental_option('excludeSwitches', ['enable-logging']) driver = Edge(executable_path = os.getcwd() + "/msedgedriver.exe", options = opt) # msedgedriver.exewebdriver for filehash in sha256set: noerror = 1 while(noerror): try: fileurl = 'https://www.virustotal.com/gui/file/' + filehash + '/behavior/VirusTotal%20Cuckoofork' driver.get(fileurl) driver.implicitly_wait(7) driver.find_element_by_tag_name('body') time.sleep(1.5) print(driver.current_url) if driver.current_url == "https://www.virustotal.com/gui/captcha": # 60s ActionChains(driver).move_by_offset(342, 146).click().perform() # ActionChains(driver).move_by_offset(-342, -146).perform() time.sleep(90) # matchresult = re.findall(r"file.(.*?).detection", driver.current_url, re.M) with open(os.getcwd() + '/sha256.txt', 'a+', encoding='UTF-8') as f: # f.write(matchresult[0] + '\n') f.close() noerror = 0 except: noerror = 1
[ 11748, 28686, 198, 11748, 302, 198, 11748, 640, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 13845, 14907, 13, 741, 47477, 62, 31391, 1330, 13113, 29046, 11, 13113, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 2673, 6...
2.224439
802