content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import unittest from nose.tools import eq_, ok_, raises from sqlalchemy import create_engine, MetaData, Column, Integer, func from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from geoalchemy2 import Geometry from sqlalchemy.exc import DataError, IntegrityError, InternalError engine = create_engine('postgresql://gis:gis@localhost/gis', echo=True) metadata = MetaData(engine) Base = declarative_base(metadata=metadata) session = sessionmaker(bind=engine)() postgis_version = session.execute(func.postgis_version()).scalar() if not postgis_version.startswith('2.'): # With PostGIS 1.x the AddGeometryColumn and DropGeometryColumn # management functions should be used. Lake.__table__.c.geom.type.management = True
[ 11748, 555, 715, 395, 198, 6738, 9686, 13, 31391, 1330, 37430, 62, 11, 12876, 62, 11, 12073, 198, 198, 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 11, 30277, 6601, 11, 29201, 11, 34142, 11, 25439, 198, 6738, 44161, 282, 26599, 13,...
3.174089
247
from django.db import models # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13 ]
3.733333
15
#!/usr/bin/python # -*- utf-8 -*- # Definition for singly-linked list with a random pointer. # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None if __name__ == '__main__': from leetcode import RandomListNode head = RandomListNode.new(1,2,3,4,5,6) head.print() Solution().copyRandomList(head).print()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 30396, 329, 1702, 306, 12, 25614, 1351, 351, 257, 4738, 17562, 13, 198, 2, 1398, 14534, 8053, 19667, 25, 198, 2, 220, 220, 22...
2.331395
172
from data_reader import Vocabulary, transform_data, save_vocabularies, Corpus from model import build_model from keras.callbacks import ModelCheckpoint if __name__=="__main__": import argparse parser = argparse.ArgumentParser(description='') g=parser.add_argument_group("Reguired arguments") g.add_argument('-d', '--data', type=str, required=True, help='Training file') g.add_argument('-m', '--model_name', type=str, required=True, help='Name of the saved model') g.add_argument('--min_count_word', type=int, default=2, help='Frequency threshold, how many times a word must occur to be included in the vocabulary? (default %(default)d)') g.add_argument('--min_count_sense', type=int, default=2, help='Frequency threshold, how many times a verb sense must occur to be included in the vocabulary? (default %(default)d)') g.add_argument('--epochs', type=int, default=10, help='Number of training epochs') args = parser.parse_args() train(args)
[ 6738, 1366, 62, 46862, 1330, 47208, 22528, 11, 6121, 62, 7890, 11, 3613, 62, 18893, 397, 934, 444, 11, 44874, 198, 6738, 2746, 1330, 1382, 62, 19849, 198, 6738, 41927, 292, 13, 13345, 10146, 1330, 9104, 9787, 4122, 628, 628, 628, 628,...
3.012012
333
# Copyright 2022 AI Singapore # # 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 # # https://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. """Python package requirements checker.""" import collections import importlib import logging import subprocess import sys from pathlib import Path from typing import Any, Iterator, TextIO, Tuple, Union import pkg_resources as pkg logger = logging.getLogger(__name__) # pylint: disable=invalid-name PKD_NODE_PREFIX = "peekingduck.pipeline.nodes." PKD_REQ_TYPE_LEN = 6 # string length of either PYTHON or SYSTEM PKD_REQ_TYPE_PYTHON = "PYTHON" # type specifier for Python packages ROOT = Path(__file__).resolve().parents[1] OptionalRequirement = collections.namedtuple("OptionalRequirement", "name type") def check_requirements( identifier: str, requirements_path: Path = ROOT / "optional_requirements.txt" ) -> int: """Checks if the packages specified by the ``identifier`` in the requirements file at ``requirements_path`` are present on the system. If ``install`` is ``True``, attempts to install the packages. Args: identifier (:obj:`str`): A unique identifier, typically a pipeline node name, used to specify which packages to check for. requirements_path (Path): Path to the requirements file Returns: (:obj:`int`): The number of packages updated. """ with open(requirements_path) as infile: requirements = list(_parse_requirements(infile, identifier)) n_update = 0 for req in requirements: if req.type == PKD_REQ_TYPE_PYTHON: try: pkg.require(req.name) except (pkg.DistributionNotFound, pkg.VersionConflict): logger.info( f"{req.name} not found and is required, attempting auto-update..." ) try: logger.info( subprocess.check_output(["pip", "install", req.name]).decode() ) n_update += 1 except subprocess.CalledProcessError as exception: logger.error(exception) raise else: logger.warning( f"The {identifier} node requires {req.name.strip()} which needs to be " "manually installed. Please follow the instructions at " "https://peekingduck.readthedocs.io/en/stable/master.html#api-documentation " "and rerun. Ignore this warning if the package is already installed" ) return n_update def _split_type_and_name(string: str) -> Tuple[str, str]: """Split an optional requirement line into the requirement type and name. """ return string[:PKD_REQ_TYPE_LEN], string[PKD_REQ_TYPE_LEN:]
[ 2, 15069, 33160, 9552, 12551, 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, 733...
2.58008
1,255
from .base import * # EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' # filebased # '.' # EMAIL_FILE_PATH = '.' EMAIL_FILE_PATH = str(pathlib.Path(BASE_DIR).joinpath('logs')) ADMINS = [('Admin1', 'admin1@example.com')] # ADMINS DEBUG = True # EMAIL_BACKEND LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'email_backend': 'django.core.mail.backends.console.EmailBackend', } }, 'loggers': { 'django': { 'handlers': ['console', 'mail_admins'], 'level': 'INFO', }, } }
[ 6738, 764, 8692, 1330, 1635, 198, 198, 2, 220, 198, 27630, 4146, 62, 31098, 10619, 796, 705, 28241, 14208, 13, 7295, 13, 4529, 13, 1891, 2412, 13, 7753, 3106, 13, 15333, 7282, 437, 6, 198, 198, 2, 2393, 3106, 198, 2, 705, 2637, 22...
1.942197
519
from dateutil.relativedelta import relativedelta from uuid import uuid4 import unittest import pytz from django.test import TestCase from django.utils.timezone import datetime from core.tests.helpers import CoreProviderMachineHelper, CoreMachineRequestHelper, CoreInstanceHelper from service.machine import process_machine_request
[ 6738, 3128, 22602, 13, 2411, 265, 1572, 12514, 1330, 48993, 1572, 12514, 198, 6738, 334, 27112, 1330, 334, 27112, 19, 198, 198, 11748, 555, 715, 395, 198, 198, 11748, 12972, 22877, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 204...
3.786517
89
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability
[ 6738, 11485, 47960, 1330, 21520, 17633, 198, 6738, 1167, 45292, 1140, 62, 3262, 76, 380, 13, 26791, 13, 26791, 1330, 2198, 62, 15042, 62, 47274, 628, 220, 220, 220, 220, 198, 220, 220, 220, 220 ]
3.028571
35
from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import render from django.http.response import JsonResponse from nitmis_admin.serializers.UserSerializer import UserSerializer def create_user(role="Guest"): """ """ return fun_wrapper
[ 6738, 1334, 62, 30604, 13, 33571, 1330, 3486, 3824, 769, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 4023, 13, 26209, 1330, 449, 1559, 31077, 19...
3.47191
89
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Apr 2 10:00 2017 @author: Timo Hinzmann (hitimo@ethz.ch) """ import math from math import floor, ceil import numpy as np import matplotlib.pyplot as plt from scipy.sparse import linalg as sla from scipy import array, linalg, dot from enum import Enum import copy import pylab # References: # [1] Grisetti, Kuemmerle, Stachniss et al. "A Tutorial on Graph-Based SLAM" # Pose-graph optimization closely following Algorithm 1, 2D from [1]. if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3825, 2758, 362, 838, 25, 405, 2177, 198, 31, 9800, 25, 5045, 78, 29094, 89, 9038, 357, ...
2.738693
199
from django.utils.timezone import now def get_history_model_for_model(model): """Find the history model for a given app model.""" try: manager_name = model._meta.simple_history_manager_attribute except AttributeError: raise NotHistorical("Cannot find a historical model for " "{model}.".format(model=model)) return getattr(model, manager_name).model def bulk_history_create(model, history_model): """Save a copy of all instances to the historical model.""" historical_instances = [ history_model( history_date=getattr(instance, '_history_date', now()), history_user=getattr(instance, '_history_user', None), **dict((field.attname, getattr(instance, field.attname)) for field in instance._meta.fields) ) for instance in model.objects.all()] history_model.objects.bulk_create(historical_instances)
[ 6738, 42625, 14208, 13, 26791, 13, 2435, 11340, 1330, 783, 628, 198, 198, 4299, 651, 62, 23569, 62, 19849, 62, 1640, 62, 19849, 7, 19849, 2599, 198, 220, 220, 220, 37227, 16742, 262, 2106, 2746, 329, 257, 1813, 598, 2746, 526, 15931, ...
2.572207
367
""" A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not. The student decides on an encryption scheme that involves two large strings. The encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Determine this number. Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings. """ a = 'ceed' b = 'acbeef' total_len = len(a) + len(b) match_counter = 0 c = list(a) d = list(b) if len(a) <= len(b): for i in c: if i in d: match_counter += 2 d.remove(i) else: for i in d: if i in c: match_counter += 2 c.remove(i) min_num = total_len - match_counter print(min_num)
[ 37811, 198, 32, 3710, 318, 2263, 257, 45898, 1398, 290, 468, 1043, 281, 6713, 82, 284, 307, 845, 4465, 13, 220, 198, 7571, 13042, 389, 281, 6713, 82, 286, 1123, 584, 611, 262, 717, 4731, 338, 7475, 460, 307, 220, 198, 260, 3258, 5...
2.884521
407
from flask_login import LoginManager from PhoenixNow.model import User login_manager = LoginManager() login_manager.login_view = "regular.signin"
[ 6738, 42903, 62, 38235, 1330, 23093, 13511, 198, 6738, 9643, 3844, 13, 19849, 1330, 11787, 198, 198, 38235, 62, 37153, 796, 23093, 13511, 3419, 198, 38235, 62, 37153, 13, 38235, 62, 1177, 796, 366, 16338, 13, 12683, 259, 1, 198 ]
3.675
40
import os import datetime as dt import random import networkx # import matplotlib as mpl import matplotlib.pyplot as plt from const import * activity = {} with open(os.path.join(DATA_DIR, "mobiclique", "activity.csv")) as activity_fd: for line in activity_fd.readlines(): line = line.strip() if "#" in line: line = line[:line.index("#")] if not line: continue user_id, start_ts, end_ts = line.split(';') if user_id not in activity: activity[user_id] = [] activity[user_id].append( (int(start_ts), int(end_ts)) ) transmission = {} with open(os.path.join(DATA_DIR, "mobiclique", "transmission.csv")) as transmission_fd: for line in transmission_fd.readlines(): line = line.strip() if "#" in line: line = line[:line.index("#")] if not line: continue msg_type, msg_id, bytes, src_user_id, dst_user_id, ts, status = line.split(';') #if status != '0': # continue if src_user_id not in transmission: transmission[src_user_id] = {} if dst_user_id not in transmission[src_user_id]: transmission[src_user_id][dst_user_id] = [] ts = int(ts) transmission[src_user_id][dst_user_id].append(ts) reception = {} with open(os.path.join(DATA_DIR, "mobiclique", "reception.csv")) as reception_fd: for line in reception_fd.readlines(): line = line.strip() if "#" in line: line = line[:line.index("#")] if not line: continue msg_type, msg_id, src_user_id, dst_user_id, ts = line.split(';') if src_user_id not in reception: reception[src_user_id] = {} if dst_user_id not in reception[src_user_id]: reception[src_user_id][dst_user_id] = [] ts = int(ts) reception[src_user_id][dst_user_id].append(ts) drift_dict = {} for src_user_id in sorted(reception): for dst_user_id in sorted(reception[src_user_id]): for rcp_ts in reception[src_user_id][dst_user_id]: if src_user_id not in transmission: continue transmissions = transmission[src_user_id].get(dst_user_id, None) if transmissions is None: continue if (src_user_id, dst_user_id) not in drift_dict: drift_dict[(src_user_id, dst_user_id)] = [] diff = [abs(rcp_ts - trn_ts) for trn_ts in transmissions] idx = diff.index(min(diff)) trn_ts = transmission[src_user_id][dst_user_id][idx] drift = trn_ts - rcp_ts drift_dict[(src_user_id, dst_user_id)].append((trn_ts, drift)) for (src_user_id, dst_user_id) in sorted(drift_dict): print src_user_id, dst_user_id, drift_dict[(src_user_id, dst_user_id)] break proximity = {} with open(os.path.join(DATA_DIR, "mobiclique", "proximity.csv")) as proximity_fd: for line in proximity_fd.readlines(): line = line.strip() if "#" in line: line = line[:line.index("#")] if not line: continue ts, user_id, seen_user_id, major_code, minor_code = line.split(';') ts = int(ts) if ts not in proximity: proximity[ts] = [] proximity[ts].append((user_id, seen_user_id)) MAX_RNG = 75 timestamps = sorted(proximity) #write traces to user.dat files if 0: user_fds = {} for ts in timestamps: for (user_id, seen_id) in proximity[ts]: if user_id not in user_fds: fd = open(r"mobiclique\%s.dat" % user_id, 'w') last_ts = -1 user_fds[user_id] = [fd, last_ts] else: [fd, last_ts] = user_fds[user_id] if last_ts != ts: if last_ts > 0: fd.write('\n') fd.write("{} {} {}".format(ts, user_id, seen_id)) else: fd.write(",{}".format(seen_id)) user_fds[user_id][1] = ts for (fd, last_ts) in user_fds.values(): fd.close() # Graph using networkx if 1: idx = random.sample(xrange(len(timestamps)), 25) idx.sort() sample_timestamps = map(timestamps.__getitem__, idx) sample_dts = map(lambda ts: START_DT + dt.timedelta(seconds=ts),sample_timestamps) for ts in sample_timestamps: other_timestamps = filter(lambda x: abs(x-ts) < MAX_RNG, timestamps) edges = sorted(set(reduce(list.__add__, [proximity[x] for x in other_timestamps]))) G = networkx.Graph(edges) networkx.draw(G) fig_fname = os.path.join(r"C:\Users\Jon\Google Drive\Grad_School\CS 538\project\scripts\figures", "%s.png" % ts) plt.savefig(fig_fname) plt.close() networks = [] n_networks = [] max_size = [] idx = random.sample(xrange(len(timestamps)), 1500) idx.sort() sample_timestamps = map(timestamps.__getitem__, idx) sample_dts = map(lambda ts: START_DT + dt.timedelta(seconds=ts),sample_timestamps) for ts in sample_timestamps: other_timestamps = filter(lambda x: abs(x-ts) < MAX_RNG, timestamps) edges = sorted(set(reduce(list.__add__, [proximity[x] for x in other_timestamps]))) nodes = sorted(set(reduce(list.__add__, map(list, edges)))) new_networks = get_networks(nodes, edges) networks.append(new_networks) n_networks.append(len(new_networks)) max_size.append(max(map(len,new_networks))) fd = open("output2.csv", 'w') for vals in zip(sample_dts, n_networks, max_size): fd.write(','.join(map(str,(vals)))) fd.write('\n') fd.close() # Get networks if 0: networks = [] n_networks = [] max_size = [] idx = random.sample(xrange(len(timestamps)), 1500) idx.sort() sample_timestamps = map(timestamps.__getitem__, idx) sample_dts = map(lambda ts: START_DT + dt.timedelta(seconds=ts),sample_timestamps) for ts in sample_timestamps: other_timestamps = filter(lambda x: abs(x-ts) < MAX_RNG, timestamps) edges = sorted(set(reduce(list.__add__, [proximity[x] for x in other_timestamps]))) nodes = sorted(set(reduce(list.__add__, map(list, edges)))) new_networks = get_networks(nodes, edges) networks.append(new_networks) n_networks.append(len(new_networks)) max_size.append(max(map(len,new_networks))) fd = open("output2.csv", 'w') for vals in zip(sample_dts, n_networks, max_size): fd.write(','.join(map(str,(vals)))) fd.write('\n') fd.close()
[ 11748, 28686, 201, 198, 11748, 4818, 8079, 355, 288, 83, 201, 198, 11748, 4738, 201, 198, 11748, 3127, 87, 201, 198, 2, 1330, 2603, 29487, 8019, 355, 285, 489, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, ...
2.007676
3,387
"""Unit tests for the General Linear group.""" import warnings import tests.helper as helper import geomstats.backend as gs import geomstats.tests from geomstats.geometry.general_linear import GeneralLinear RTOL = 1e-5
[ 37811, 26453, 5254, 329, 262, 3611, 44800, 1448, 526, 15931, 198, 198, 11748, 14601, 198, 198, 11748, 5254, 13, 2978, 525, 355, 31904, 198, 198, 11748, 4903, 296, 34242, 13, 1891, 437, 355, 308, 82, 198, 11748, 4903, 296, 34242, 13, 4...
3.294118
68
from unittest import TestCase import os,sys,inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.insert(0, parent_dir) import feladatok
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 11748, 28686, 11, 17597, 11, 1040, 806, 198, 14421, 62, 15908, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 1040, 806, 13, 1136, 7753, 7, 1040, 8...
2.717647
85
from utils.Driver import Driver from pages.base_page import BasePage from pages.locators import MainPageLocators
[ 6738, 3384, 4487, 13, 32103, 1330, 12434, 201, 198, 201, 198, 6738, 5468, 13, 8692, 62, 7700, 1330, 7308, 9876, 201, 198, 6738, 5468, 13, 17946, 2024, 1330, 8774, 9876, 33711, 2024, 201 ]
3.545455
33
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-16 07:49 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 19, 319, 2177, 12, 2919, 12, 1433, 8753, 25, 2920, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.883117
77
import math import unittest import torch from nuscenes.prediction.models import mtp
[ 198, 11748, 10688, 198, 11748, 555, 715, 395, 198, 198, 11748, 28034, 198, 198, 6738, 299, 16241, 18719, 13, 28764, 2867, 13, 27530, 1330, 285, 34788, 628 ]
3.259259
27
#!/usr/bin/env python3 # Convert Yosys JSON to simple text hypergraph for performance testing import sys, json node_count = 0 edge2node = {} netlist = None with open(sys.argv[1]) as jf: netlist = json.load(jf) top_module = None for name, module in sorted(netlist["modules"].items()): if "attributes" not in module: continue if "top" not in module["attributes"]: continue if int(module["attributes"]["top"]) == 0: continue top_module = module break for cname, cell in sorted(top_module["cells"].items()): if "connections" not in cell: continue for pname, bits in sorted(cell["connections"].items()): for bit in bits: if bit in ("0", "1", "x", "z"): continue if bit not in edge2node: edge2node[bit] = set() edge2node[bit].add(node_count) node_count += 1 with open(sys.argv[2], "w") as hf: print("{} {}".format(node_count, len(edge2node)), file=hf) for n in range(node_count): print("N 0 0", file=hf) for e, nodes in sorted(edge2node.items()): print("E 1 {}".format(" ".join([str(x) for x in sorted(nodes)])), file=hf)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 38240, 575, 418, 893, 19449, 284, 2829, 2420, 8718, 34960, 329, 2854, 4856, 198, 198, 11748, 25064, 11, 33918, 198, 198, 17440, 62, 9127, 796, 657, 198, 14907, 17, 17440, ...
2.522459
423
from Tkinter import * import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd as autograd from torch.autograd import Variable master = Tk() goal = 0 var_goal = StringVar() GAMMA = 0.9 last_state = Variable(torch.Tensor([0,0,0,0,0,0])).unsqueeze(0) last_action = 0 last_reward = 0 model = Policy() model.initHidden() last_hidden = model.hidden_state last_cell = model.cell_state optimizer = optim.Adam(model.parameters(), lr=0.01) Button(master, text='S1', height = 10, width = 30, command=lambda:update(0)).grid(row=0, column=0, sticky=W, pady=4) Button(master, text='S2', height = 10, width = 30, command=lambda:update(1)).grid(row=0, column=1, sticky=W, pady=4) Button(master, text='goal 0', height = 10, width = 30, command=lambda:set_goal(0)).grid(row=1, column=0, sticky=W, pady=4) Button(master, text='goal 1', height = 10, width = 30, command=lambda:set_goal(1)).grid(row=1, column=1, sticky=W, pady=4) Label(master, height = 10, textvariable = var_goal).grid(row=2, sticky=EW, pady=4) mainloop( )
[ 6738, 309, 74, 3849, 1330, 1635, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034, 13, 40085, 355, 6436, 198, ...
2.657767
412
import os import sys compiler = r'../Binary/RelWithDebInfo/ShaderCompiler' #compiler = r'../Binary/Debug/ShaderCompiler' shader_dirs = ['.', './Editor'] count = 0 for d in shader_dirs: for fn in os.listdir(d): print(fn) ext = fn.split('.')[-1] if ext in ['surf', 'shader']: cmd = compiler + ' ' + os.path.abspath(os.path.join(d, fn)) print(cmd) if os.system(cmd) != 0: print("Compile ERROR: ", fn) sys.exit() count += 1 print("Done. {} shaders compiled.".format(count))
[ 11748, 28686, 198, 11748, 25064, 198, 198, 5589, 5329, 796, 374, 6, 40720, 33, 3219, 14, 6892, 3152, 16587, 12360, 14, 2484, 5067, 7293, 5329, 6, 198, 2, 5589, 5329, 796, 374, 6, 40720, 33, 3219, 14, 27509, 14, 2484, 5067, 7293, 532...
2.304147
217
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from rbb_swagger_server.models.base_model_ import Model from rbb_swagger_server.models.simulation_environment_detailed import SimulationEnvironmentDetailed # noqa: F401,E501 from rbb_swagger_server.models.simulation_run_detailed import SimulationRunDetailed # noqa: F401,E501 from rbb_swagger_server.models.simulation_summary import SimulationSummary # noqa: F401,E501 from rbb_swagger_server.models.task_detailed import TaskDetailed # noqa: F401,E501 from rbb_swagger_server import util
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 220, 1303, 645, 20402, 25, 376, 21844, 198, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 220...
3.161765
204
import docker import os import sys import pandas as pd import warnings from src.PRM import PRM from pathlib import Path from src.util import prepare_path_docker __all__ = ['PathLinker']
[ 11748, 36253, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 14601, 198, 6738, 12351, 13, 4805, 44, 1330, 4810, 44, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 12351, 13, 22602, 1330, 8335, 62...
3.339286
56
# -*- coding: utf-8 -*- from .base import Hypothesiser from ..base import Property from ..types.multihypothesis import MultipleHypothesis from ..types.prediction import (TaggedWeightedGaussianStatePrediction, WeightedGaussianStatePrediction) from ..types.state import TaggedWeightedGaussianState
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 764, 8692, 1330, 21209, 31690, 5847, 198, 6738, 11485, 8692, 1330, 14161, 198, 6738, 11485, 19199, 13, 16680, 4449, 4464, 313, 8497, 1330, 20401, 49926, 313, 8497, 1...
2.836207
116
from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework import serializers from apps.approval.models import CommitteeApplication, CommitteePriority from apps.authentication.serializers import UserSerializer
[ 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 3254, 24765, 12331, 355, 37770, 7762, 24765, 12331, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 6725, 13, 21064, 2100, 13, 27530, 1330, 4606, 23416, 11, 4606, 22442,...
4.464286
56
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split import utils import glob, os import pca.dataanalyzer as da, pca.pca as pca from sklearn.metrics import accuracy_score # visulaize the important characteristics of the dataset import matplotlib.pyplot as plt seed = 0 num_headers = 16 data_len = 54*num_headers #1460 dirs = ["C:/Users/salik/Documents/Data/LinuxChrome/{}/".format(num_headers), "C:/Users/salik/Documents/Data/WindowsFirefox/{}/".format(num_headers), "C:/Users/salik/Documents/Data/WindowsChrome/{}/".format(num_headers), "C:/Users/salik/Documents/Data/WindowsSalik/{}/".format(num_headers), "C:/Users/salik/Documents/Data/WindowsAndreas/{}/".format(num_headers)] # dirs = ["E:/Data/h5/https/", "E:/Data/h5/netflix/"] # step 1: get the data dataframes = [] num_examples = 0 for dir in dirs: for fullname in glob.iglob(dir + '*.h5'): filename = os.path.basename(fullname) df = utils.load_h5(dir, filename) dataframes.append(df) num_examples = len(df.values) # create one large dataframe data = pd.concat(dataframes) data.sample(frac=1, random_state=seed).reset_index(drop=True) num_rows = data.shape[0] columns = data.columns print(columns) # step 2: get features (x) and convert it to numpy array x = da.getbytes(data, data_len) # step 3: get class labels y and then encode it into number # get class label data y = data['label'].values # encode the class label class_labels = np.unique(y) label_encoder = LabelEncoder() y = label_encoder.fit_transform(y) # step 4: split the data into training set and test set test_percentage = 0.5 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_percentage, random_state=seed) plot_savename = "histogram_payload" from matplotlib import rcParams # Make room for xlabel which is otherwise cut off rcParams.update({'figure.autolayout': True}) # scatter plot the sample points among 5 classes # markers = ('s', 'd', 'o', '^', 'v', ".", ",", "<", ">", "8", "p", "P", "*", "h", "H", "+", "x", "X", "D", "|", "_") color_map = {0: '#487fff', 1: '#d342ff', 2: '#4eff4e', 3: '#2ee3ff', 4: '#ffca43', 5:'#ff365e', 6:'#626663'} plt.figure() for idx, cl in enumerate(np.unique(y_test)): # Get count of unique values values, counts = np.unique(x_test[y_test == cl], return_counts=True) # Maybe remove zero as there is a lot of zeros in the header # values = values[1:] # counts = counts[1:] n, bins, patches = plt.hist(values, weights=counts, bins=256, facecolor=color_map[idx], label=class_labels[cl], alpha=0.8) plt.legend(loc='upper right') plt.title('Histogram of : {}'.format(class_labels)) plt.tight_layout() # plt.savefig('{0}{1}.png'.format(plot_savename, int(perplexity)), dpi=300) plt.show()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 36052, 27195, 12342, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 8997, 3351, 36213, 198, 6738, 1341, 35720, 13, 19692, ...
2.595004
1,121
# SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries # # SPDX-License-Identifier: Unlicense import adafruit_board_toolkit.circuitpython_serial comports = adafruit_board_toolkit.circuitpython_serial.repl_comports() if not comports: raise Exception("No CircuitPython boards found") # Print the device paths or names that connect to a REPL. print([comport.device for comport in comports])
[ 2, 30628, 55, 12, 8979, 15269, 8206, 25, 15069, 357, 66, 8, 33448, 6035, 11023, 4835, 329, 1215, 1878, 4872, 20171, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 791, 43085, 198, 198, 11748, 512, 1878, 4872, 62, 3526, ...
3.34127
126
import time import uuid from random import random def exponential_backoff( attempts, base_delay, max_delay=None, jitter=True, ): """ Get the next delay for retries in exponential backoff. attempts: Number of attempts so far base_delay: Base delay, in seconds max_delay: Max delay, in seconds. If None (default), there is no max. jitter: If True, add a random jitter to the delay """ if max_delay is None: max_delay = float("inf") backoff = min(max_delay, base_delay * 2 ** max(attempts - 1, 0)) if jitter: backoff = backoff * random() return backoff
[ 11748, 640, 198, 11748, 334, 27112, 198, 6738, 4738, 1330, 4738, 628, 628, 628, 198, 4299, 39682, 62, 1891, 2364, 7, 198, 220, 220, 220, 6370, 11, 198, 220, 220, 220, 2779, 62, 40850, 11, 198, 220, 220, 220, 3509, 62, 40850, 28, 1...
2.682203
236
from dagster import job, op
[ 6738, 48924, 1706, 1330, 1693, 11, 1034, 628, 198 ]
3.333333
9
# -*- coding: utf-8 -*- import time import numpy as np from qulab.device import BaseDriver, QInteger, QOption, QReal, QString, QVector
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 640, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 10662, 377, 397, 13, 25202, 1330, 7308, 32103, 11, 1195, 46541, 11, 1195, 19722, 11, 1195, 15633, 11...
2.76
50
# -*- coding: utf-8 -*- import torch import torch.nn as nn """ 3510 batch=3, seq_len=5, Embedding=10 """ # LSTM1020,2LSTMLSTM bilstm = nn.LSTM(input_size=10, hidden_size=20, num_layers=2, bidirectional=True) # input = torch.randn(5, 3, 10) # h0 = torch.randn(4, 3, 20) # [bidirection*num_layers, batch_size, hidden_size] c0 = torch.randn(4, 3, 20) # [bidirection*num_layers, batch_size, hidden_size] # 2lstmoutputlstm output, (hn, cn) = bilstm(input, (h0, c0)) print("output shape", output.shape) # shapetorch.Size([5,3,40]),[seq_len,batch_size,2*hidden_size] print("hn shape", hn.shape) # shapetorch.Size([4,3,20]),[bidirection*num_layers,batch_size,hidden_size] print("cn shape", cn.shape) # shapetorch.Size([4,3,20]),[bidirection*num_layers,batch_size,hidden_size] # output = output.permute(1, 0, 2) # torch.Size([3,5,40]),[batch_size,seq_len,2*hidden_size] output = output.contiguous() # torch.view()permutecontiguousviewtensor batch_size = output.size(0) output = output.view(batch_size, -1) # torch.Size([3,200]),[batch_size,seq_len*2*hidden_size] fully_connected = nn.Linear(200, 2) output = fully_connected(output) print(output.shape) # torch.Size([3,2]),[batch_size,class] print(output)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 198, 37811, 198, 2327, 940, 198, 43501, 28, 18, 11, 33756, 62, 11925, 28, 20, 11, 13302, 6048, 278, 28, ...
2.319923
522
from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from apps.meiduo_admin.serializers.order import OrderInfoSerializer from apps.meiduo_admin.utils import PageNum from apps.orders.models import OrderInfo
[ 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330, 2223, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 1334, 62, 30604, 13, 1177, 28709, 1330, 9104, 7680, 7248, 198, 198, 6738, 6725, 13, 1326, 312, 20895, 62, 28482, 1...
3.855263
76
#!/usr/bin/python3.4 # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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. r""" Implements a Windows version of a client responder. This should run with the native Python for Windows. Install on a Windows server: Place the following lines in c:\autoexec.bat:: PATH=%PATH%;C:\Python26;C:\Python26\Scripts Now run (all on one line):: C:\Python26>python.exe %PYTHONLIB%\site-packages\pycopia\remote\WindowsServer.py --username DOMAIN\Administrator --password xxxxxxxx install OR, for system process that can interact with console:: C:\Python26>python.exe %PYTHONLIB%\site-packages\pycopia\remote\WindowsServer.py --interactive install Note: if you get an error about an account not existing, you may need to supply the username like this: .\Administrator If a username was supplied to run as, go to the Service Manger from the Windows control panel, and perform the following. - Select "Remote Agent Server" from the list. Right-clieck and select "properties". - Select the "Log On" tab. - Click the "This account:" radio button. - Enter DOMAIN\Administrator in the account box (or something else appropriate). - Enter the proper password (twice). - Click "Apply". You should confirm a message saying user is enabled to log in as a service. - Click "General" tab. - You may now start the service. You may also need to disable the Windows firewall for this to function properly. This service is a massive security hole, so only run it on a throw-away test machine on an isolated network. """ import os, sys, shutil, errno import threading # Pycopia imports from pycopia.aid import IF from pycopia.anypath import cygwin2nt, nt2cygwin from pycopia import shparser # returnable objects from pycopia.remote.WindowsObjects import ExitStatus # Windows stuff import msvcrt import win32api import win32file import win32net import win32process import win32event # constants import pywintypes import win32con import win32netcon # some constants that the API forgot... USE_WILDCARD = -1 USE_DISKDEV = 0 USE_SPOOLDEV = 1 USE_CHARDEV = 2 USE_IPC = 3 import Pyro import Pyro.util setConfig() Log=Pyro.util.Log import Pyro.core import Pyro.naming from Pyro.ext.BasicNTService import BasicNTService, getRegistryParameters _EXIT = False UserLog = Pyro.util.UserLogger() # msg, warn, or error methods split_command_line = shparser.get_command_splitter() # quick hack ... Windows sucks. No signal handling or anything useful, so it has to be faked. # A server that performs filer client operations. This mostly delegates to the # os module. But some special methods are provided for common functions. # md5sums callback for counting files ######## main program ##### def run_server(): os.chdir(r"C:\tmp") Pyro.core.initServer(banner=0, storageCheck=0) ns=Pyro.naming.NameServerLocator().getNS() daemon=Pyro.core.Daemon() daemon.useNameServer(ns) uri=daemon.connectPersistent(Win32Agent(), "Agents.%s" % (win32api.GetComputerName().lower(),)) daemon.requestLoop(_checkexit) daemon.shutdown() def _checkexit(): global _EXIT return not _EXIT if __name__ == '__main__': RemoteAgentService.HandleCommandLine()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 13, 19, 198, 2, 43907, 25, 912, 28, 19, 25, 2032, 28, 19, 25, 4215, 8658, 11338, 28, 19, 25, 27004, 8658, 25, 11201, 392, 8658, 198, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362...
3.154485
1,204
from locust import HttpLocust, TaskSet
[ 6738, 1179, 436, 1330, 367, 29281, 33711, 436, 11, 15941, 7248, 628, 628, 628 ]
3.142857
14
import nekos from ..utils import admin_cmd
[ 11748, 497, 46150, 198, 6738, 11485, 26791, 1330, 13169, 62, 28758, 198 ]
3.583333
12
import time import continuous_threading if __name__ == '__main__': # Run one option at a time import sys # Default test run # run_test = test_thread # run_test = test_continuous # run_test = test_pausable run_test = test_operation if len(sys.argv) > 1: value = str(sys.argv[1]).lower() if value == '0' or value == 'thread': run_test = test_thread elif value == '1' or 'continuous' in value: run_test = test_continuous elif value == '2' or 'paus' in value: run_test = test_pausable elif value == '3' or 'op' in value: run_test = test_operation run_test() # You should observe that python.exe is no longer a running process when the program finishes. # exit code should be 0
[ 11748, 640, 198, 11748, 12948, 62, 16663, 278, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 5660, 530, 3038, 379, 257, 640, 198, 220, 220, 220, 1330, 25064, 628, 220, 220, 2...
2.383041
342
import copy import torch.nn as nn from .transformer import (Encoder, EncoderLayer, MultiHeadedAttention, PositionwiseFeedforward, PositionalEncoding)
[ 11748, 4866, 198, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 198, 6738, 764, 7645, 16354, 1330, 357, 27195, 12342, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.748299
147
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-02-15 13:41 from __future__ import unicode_literals from django.db import migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 23, 319, 13130, 12, 2999, 12, 1314, 1511, 25, 3901, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.690909
55
import os import sys import globus_sdk from globus_sdk.tokenstorage import SQLiteAdapter from ._old_config import invalidate_old_config # internal constants _CLIENT_DATA_CONFIG_KEY = "auth_client_data" # env vars used throughout this module GLOBUS_ENV = os.environ.get("GLOBUS_SDK_ENVIRONMENT") GLOBUS_PROFILE = os.environ.get("GLOBUS_PROFILE") def internal_native_client(): """ This is the client that represents the CLI itself (prior to templating) """ template_id = _template_client_id() return globus_sdk.NativeAppAuthClient( template_id, app_name="Globus CLI (native client)" ) def internal_auth_client(): """ Pull template client credentials from storage and use them to create a ConfidentialAppAuthClient. In the event that credentials are not found, template a new client via the Auth API, save the credentials for that client, and then build and return the ConfidentialAppAuthClient. """ adapter = token_storage_adapter() client_data = adapter.read_config(_CLIENT_DATA_CONFIG_KEY) if client_data is not None: client_id = client_data["client_id"] client_secret = client_data["client_secret"] else: # register a new instance client with auth nc = internal_native_client() res = nc.post( "/v2/api/clients", data={"client": {"template_id": nc.client_id, "name": "Globus CLI"}}, ) # get values and write to config credential_data = res["included"]["client_credential"] client_id = credential_data["client"] client_secret = credential_data["secret"] adapter.store_config( _CLIENT_DATA_CONFIG_KEY, {"client_id": client_id, "client_secret": client_secret}, ) return globus_sdk.ConfidentialAppAuthClient( client_id, client_secret, app_name="Globus CLI" )
[ 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 15095, 385, 62, 21282, 74, 198, 6738, 15095, 385, 62, 21282, 74, 13, 30001, 35350, 1330, 16363, 578, 47307, 198, 198, 6738, 47540, 727, 62, 11250, 1330, 12515, 378, 62, 727, 62, 11250, ...
2.595918
735
#!/usr/bin/env python #coding:utf-8 __author__ = 'CoderZh and Tymur' import sys from time import sleep # Important for multithreading sys.coinit_flags = 0 # pythoncom.COINIT_MULTITHREADED import win32com import win32com.client import win32gui import win32con import pythoncom #import keyboard from pathlib import Path import os import re import subprocess import psutil #def connectToIEServer():
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 201, 198, 2, 66, 7656, 25, 40477, 12, 23, 201, 198, 201, 198, 834, 9800, 834, 796, 705, 34, 12342, 57, 71, 290, 309, 4948, 333, 6, 201, 198, 201, 198, 11748, 25064, 201, 198, 6738, 64...
2.702532
158
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'efrenfuentes' import unittest from plugin_MontoEscrito import numero_a_letras, numero_a_moneda if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 796, 705, 891, 918, 20942, 298, 274, 6, 198, 198, 11748, 555, 715, 395, 198, 6738, 13877, 62, 44, 595...
2.321839
87
#!/usr/bin/python # -*- coding: utf-8 -*- import os import setuptools setuptools.setup( name = "pconvert-python", version = "0.4.1", author = "Hive Solutions Lda.", author_email = "development@hive.pt", description = "PNG Convert", license = "Apache License, Version 2.0", keywords = "pconvert converted compositor", url = "http://pconvert.hive.pt", packages = [ "pconvert_py", "pconvert_py.test" ], test_suite = "pconvert_py.test", package_dir = { "" : os.path.normpath("src/python") }, ext_modules = [ setuptools.Extension( "pconvert", include_dirs = ["src/pconvert", "/usr/local/include"], libraries = [] if os.name in ("nt",) else ["m", "png"], library_dirs = ["/usr/local/lib"], extra_compile_args = [] if os.name in ("nt",) else [ "-O3", "-finline-functions", "-Winline" ], sources = [ "src/pconvert/extension.c", "src/pconvert/opencl.c", "src/pconvert/pconvert.c", "src/pconvert/stdafx.c", "src/pconvert/structs.c", "src/pconvert/util.c" ], define_macros = [ ("PCONVERT_EXTENSION", None), ("PASS_ERROR", None) ] ) ], classifiers = [ "Development Status :: 5 - Production/Stable", "Topic :: Utilities", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.0", "Programming Language :: Python :: 3.1", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7" ] )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 201, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 11748, 28686, 201, 198, 11748, 900, 37623, 10141, 201, 198, 201, 198, 2617, 37623, 10141, 13, 40406, 7, ...
1.982285
1,129
# SPDX-License-Identifier: Apache-2.0 """Graph Optimizer Base""" import copy from .. import logging, utils def _optimize(self, graph): """ Derived class should override this function. """ raise NotImplementedError
[ 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 628, 198, 37811, 37065, 30011, 7509, 7308, 37811, 198, 198, 11748, 4866, 198, 198, 6738, 11485, 1330, 18931, 11, 3384, 4487, 628, 198, 220, 220, 220, 825, 4808, 40...
2.926829
82
import numpy as np from pydub import AudioSegment import random import sys import io import os import glob import IPython from td_utils import * from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras.models import Model, load_model, Sequential from tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D from tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape from tensorflow.keras.optimizers import Adam Tx = 5511 # The number of time steps input to the model from the spectrogram n_freq = 101 # Number of frequencies input to the model at each time step of the spectrogram Ty = 1375 # The number of time steps in the output of our model X = np.load("./XY_train/X0.npy") Y = np.load("./XY_train/Y0.npy") X = np.concatenate((X, np.load("./XY_train/X1.npy")), axis=0) Y = np.concatenate((Y, np.load("./XY_train/Y1.npy")), axis=0) Y = np.swapaxes(Y, 1, 2) # Load preprocessed dev set examples X_dev = np.load("./XY_dev/X_dev.npy") Y_dev = np.load("./XY_dev/Y_dev.npy") # GRADED FUNCTION: model def modelf(input_shape): """ Function creating the model's graph in Keras. Argument: input_shape -- shape of the model's input data (using Keras conventions) Returns: model -- Keras model instance """ X_input = Input(shape = input_shape) ### START CODE HERE ### # Step 1: CONV layer (4 lines) X = Conv1D(196, kernel_size = 15, strides = 4)(X_input) # CONV1D X = BatchNormalization()(X) # Batch normalization X = Activation("relu")(X) # ReLu activation X = Dropout(0.8)(X) # dropout (use 0.8) # Step 2: First GRU Layer (4 lines) X = GRU(units = 128, return_sequences = True)(X) # GRU (use 128 units and return the sequences) X = Dropout(0.8)(X) # dropout (use 0.8) X = BatchNormalization()(X) # Batch normalization # Step 3: Second GRU Layer (4 lines) X = GRU(units = 128, return_sequences = True)(X) # GRU (use 128 units and return the sequences) X = Dropout(0.8)(X) # dropout (use 0.8) X = BatchNormalization()(X) # Batch normalization X = Dropout(0.8)(X) # dropout (use 0.8) # Step 4: Time-distributed dense layer (1 line) X = TimeDistributed(Dense(1, activation = "sigmoid"))(X) # time distributed (sigmoid) ### END CODE HERE ### model = Model(inputs = X_input, outputs = X) return model model = modelf(input_shape = (Tx, n_freq)) model.summary() opt = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, decay=0.01) model.compile(loss='binary_crossentropy', optimizer=opt, metrics=["accuracy"]) model.fit(X, Y, batch_size=20, epochs=100) loss, acc = model.evaluate(X_dev, Y_dev) print("Dev set accuracy = ", acc) from tensorflow.keras.models import model_from_json json_file = open('./models/model_new3.json', 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) model.load_weights('./models/model_new3.h5')
[ 11748, 299, 32152, 355, 45941, 198, 6738, 279, 5173, 549, 1330, 13491, 41030, 434, 198, 11748, 4738, 198, 11748, 25064, 198, 11748, 33245, 198, 11748, 28686, 198, 11748, 15095, 198, 11748, 6101, 7535, 198, 6738, 41560, 62, 26791, 1330, 16...
2.267722
1,453
# ===================================================== # Copyright (c) 2017-present, AUROMIND Ltd. # ===================================================== import os from network import NeuralNetwork from experiments import Experiment from utils import save_object, load_object # ----------------------------------------------------- # Exporting Method # ----------------------------------------------------- # ----------------------------------------------------- # Workspace Handler # -----------------------------------------------------
[ 2, 46111, 4770, 1421, 198, 2, 15069, 357, 66, 8, 2177, 12, 25579, 11, 317, 4261, 2662, 12115, 12052, 13, 198, 2, 46111, 4770, 1421, 198, 198, 11748, 28686, 198, 198, 6738, 3127, 1330, 47986, 26245, 198, 6738, 10256, 1330, 29544, 198, ...
6.054945
91
#!/usr/bin/env python # # ___INFO__MARK_BEGIN__ ####################################################################################### # Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering 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. ####################################################################################### # ___INFO__MARK_END__ # from .qconf_object import QconfObject
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 220, 198, 2, 46444, 10778, 834, 44, 14175, 62, 33, 43312, 834, 198, 29113, 29113, 14468, 4242, 21017, 198, 2, 15069, 1584, 12, 1238, 2481, 791, 12151, 10501, 357, 43561, 1202, 290, ...
4.129464
224
#!/usr/bin/env python3 import os import sys import runpy from intelhex import IntelHex #import lz4.frame import subprocess import shutil if __name__ == "__main__": script_directory = os.path.dirname(os.path.realpath(__file__)) lz4 = os.path.join(script_directory,'lz4') if not os.path.isfile(lz4): lz4 = shutil.which('lz4') assert(lz4 is not None) if (len(sys.argv) > 3) | (len(sys.argv) < 3) : print("ERROR: incorrect arguments") print("Usage:") print("prep.py <ihex> <metainfo>") exit() ihexf = sys.argv[1] metainfof = sys.argv[2] ih = IntelHex() ihgu = IntelHex() ih.loadhex(ihexf) all_sections = ih.segments() print("input hex file sections:") for sec in all_sections: print("0x%08X 0x%08X"%(sec[0],sec[1]-1)) file_globals = runpy.run_path(metainfof,init_globals={'prep_path':os.path.dirname(script_directory)}) comp_storage_start=file_globals["comp_storage"]['start'] comp_storage_end=file_globals["comp_storage"]['end'] map_load_size=file_globals["map_load_size"] map_run_size=file_globals["map_run_size"] grow_up=file_globals["grow_up"] comp_sections=file_globals["comp_sections"] linear_mode=get_file_global("linear_mode",True) start_at_end=get_file_global("start_at_end",False) use_seg_as_linear=get_file_global("use_seg_as_linear",False) print("%d sections to compress"%len(comp_sections)) for sec in comp_sections: print("load: 0x%08X -> 0x%08X, run: 0x%08X -> 0x%08X, size: 0x%X"%(sec['load'],sec['load']+sec['size']-1,sec['run'],sec['run']+sec['size']-1,sec['size'])) mapsize = (map_load_size+map_run_size)*len(comp_sections) map_storage=comp_storage_start comp_storage=comp_storage_start+mapsize #compress the sections for sec in comp_sections: #write the start address in the map LUT start_offset_bytes = (comp_storage-comp_storage_start).to_bytes(8,byteorder='little') for i in range(0,map_load_size): ihgu[map_storage] = start_offset_bytes[i] map_storage+=1 run_bytes = sec['run'].to_bytes(8,byteorder='little') for i in range(0,map_run_size): ihgu[map_storage] = run_bytes[i] map_storage+=1 data = ih[sec['load']:sec['load']+sec['size']] ba = bytearray() for bi in range(sec['load'],sec['load']+sec['size']): ba.append(ih[bi]) newfile=open('lz4_input.bin','wb') newfile.write(ba) newfile.close() cmd = [ lz4,'-9','-l','-f','lz4_input.bin','lz4_output.bin'] subprocess.run(cmd,check=True) size=0 with open('lz4_output.bin', "rb") as f: #skip the frame descriptor frame_descriptor = f.read(4) byte = f.read(1) while byte: ihgu[comp_storage] = int.from_bytes( byte, byteorder='little', signed=False ) comp_storage+=1 size+=1 byte = f.read(1) sec['comp_size']=size if comp_storage>comp_storage_end: print("ERROR: compressed storage overflow by %d"%(comp_storage - comp_storage_end)) exit(1) else: used = comp_storage - comp_storage_start free = comp_storage_end+1-comp_storage print("0x%08x bytes used in compressed storage"%(used)) print("0x%08x bytes free in compressed storage"%(free)) comp_storage_pad=0 if grow_up: #just rename ihex object iho = ihgu else: #reverse compressed area storage iho = IntelHex() map_storage=comp_storage_end+1 #if 0!=(free%16): # comp_storage_pad = free%16 # free-=comp_storage_pad comp_storage=comp_storage_start+free if 0!=(comp_storage%16): #add padding data for i in range(comp_storage-(comp_storage%16),comp_storage): iho[i]=0x55 #move the compressed data up print("copy 0x%X bytes from 0x%08X to 0x%08X"%(used,comp_storage_start+mapsize,comp_storage_start+free)) for i in range(0,used): iho[comp_storage_start+free+i] = ihgu[comp_storage_start+mapsize+i] #rebuild map for sec in comp_sections: sec['load']=comp_storage #write the start offset in the map LUT map_storage-=map_load_size+map_run_size start_offset_bytes = (comp_storage-comp_storage_start).to_bytes(8,byteorder='little') for i in range(0,map_load_size): iho[map_storage] = start_offset_bytes[i] map_storage+=1 run_bytes = sec['run'].to_bytes(8,byteorder='little') for i in range(0,map_run_size): iho[map_storage] = run_bytes[i] map_storage+=1 map_storage-=map_load_size+map_run_size comp_storage+=sec['comp_size'] #print("0x%x"%comp_storage) #print("0x%x"%map_storage) assert(map_storage==comp_storage+comp_storage_pad) #create a list of start address of the sections which have been compressed print("compressed sections load addresses:") comp_sections_start=[] for sec in comp_sections: print("0x%08X"%sec['load']) comp_sections_start.append(sec['load']) #copy all regular sections for sec in all_sections: print("copy section from %x to %x"%(sec[0],sec[1])) for i in range(sec[0],sec[1]): if (i<comp_storage_start) or (i>=comp_storage_end): iho[i]=ih[i] #copy start address #print("start address: ",ih.start_addr) iho.start_addr = ih.start_addr if not linear_mode or start_at_end or use_seg_as_linear: #need custom version of intelhex, get it here: https://github.com/sebastien-riou/intelhex iho.write_hex_file(ihexf+".lz4l.ihex",linear_mode=linear_mode,start_at_end=start_at_end,use_seg_as_linear=use_seg_as_linear) else: iho.write_hex_file(ihexf+".lz4l.ihex")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 1057, 9078, 198, 6738, 33649, 33095, 1330, 8180, 39, 1069, 198, 2, 11748, 300, 89, 19, 13, 14535, 198, 11748, 850, 14681, 198, 11748, 4...
2.080794
2,921
# -*- coding: utf-8 -*- from flask import make_response, Blueprint from app import derive_import_root, add_url_rules_for_blueprint from application import exception from application.model.service import Service from application.model.service_template import ServiceTemplate from application.util.database import session_scope from application.views.base_api import BaseNeedLoginAPI, ApiResult view = ServiceAPI bp = Blueprint(__name__.split('.')[-1], __name__) root = derive_import_root(__name__) add_url_rules_for_blueprint(root, bp)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 42903, 1330, 787, 62, 26209, 11, 39932, 198, 198, 6738, 598, 1330, 27099, 62, 11748, 62, 15763, 11, 751, 62, 6371, 62, 38785, 62, 1640, 62, 17585, 4798, 198, 673...
3.43949
157
import json import requests
[ 11748, 33918, 201, 198, 11748, 7007, 201, 198, 201, 198, 220, 220, 220, 220, 201, 198 ]
2.375
16
"""Exogenous parameters are anything "uncontrollable" that affect the design; these are what we consider robustness against and are typically drawn from some distribution """ from typing import Optional, Sequence, Tuple, Union import jax import jax.numpy as jnp from jax._src.prng import PRNGKeyArray import numpy as np from .exogenous_parameters import ExogenousParameters
[ 37811, 3109, 27897, 10007, 389, 1997, 366, 403, 3642, 2487, 540, 1, 326, 2689, 262, 1486, 26, 777, 389, 198, 10919, 356, 2074, 12373, 1108, 1028, 290, 389, 6032, 7428, 422, 617, 6082, 198, 37811, 198, 6738, 19720, 1330, 32233, 11, 458...
3.927083
96
import re from courspider.faculty_calendar_resources.department import Department from courspider.faculty_calendar_resources.url import URL from courspider.course import Course
[ 11748, 302, 198, 198, 6738, 1093, 2777, 1304, 13, 38942, 10672, 62, 9948, 9239, 62, 37540, 13, 10378, 1823, 1330, 2732, 198, 6738, 1093, 2777, 1304, 13, 38942, 10672, 62, 9948, 9239, 62, 37540, 13, 6371, 1330, 10289, 198, 6738, 1093, ...
3.708333
48
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs all the buildbot steps for ChromeDriver except for update/compile.""" import optparse import os import platform import shutil import subprocess import sys import tempfile import time import urllib2 import zipfile _THIS_DIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(_THIS_DIR, os.pardir, 'pylib')) from common import chrome_paths from common import util import archive GS_BUCKET = 'gs://chromedriver-prebuilts' GS_ZIP_PREFIX = 'chromedriver2_prebuilts' SLAVE_SCRIPT_DIR = os.path.join(_THIS_DIR, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir, 'scripts', 'slave') UPLOAD_SCRIPT = os.path.join(SLAVE_SCRIPT_DIR, 'skia', 'upload_to_bucket.py') DOWNLOAD_SCRIPT = os.path.join(SLAVE_SCRIPT_DIR, 'gsutil_download.py') if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 357, 66, 8, 2211, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, ...
2.481735
438
# ---------------------------------------------------------------------- # | # | CastExpressionParserInfo_UnitTest.py # | # | David Brownell <db@DavidBrownell.com> # | 2021-10-04 09:14:16 # | # ---------------------------------------------------------------------- # | # | Copyright David Brownell 2021 # | Distributed under the Boost Software License, Version 1.0. See # | accompanying file LICENSE_1_0.txt or copy at # | http://www.boost.org/LICENSE_1_0.txt. # | # ---------------------------------------------------------------------- """Unit test for CastExpressionParserInfo.py""" import os import pytest import CommonEnvironment from CommonEnvironmentEx.Package import InitRelativeImports # ---------------------------------------------------------------------- _script_fullpath = CommonEnvironment.ThisFullpath() _script_dir, _script_name = os.path.split(_script_fullpath) # ---------------------------------------------------------------------- with InitRelativeImports(): from ..CastExpressionParserInfo import * from ...Common.AutomatedTests import RegionCreator from ...Types.StandardTypeParserInfo import StandardTypeParserInfo # ---------------------------------------------------------------------- # ----------------------------------------------------------------------
[ 2, 16529, 23031, 201, 198, 2, 930, 201, 198, 2, 930, 220, 5833, 16870, 2234, 46677, 12360, 62, 26453, 14402, 13, 9078, 201, 198, 2, 930, 201, 198, 2, 930, 220, 3271, 4373, 695, 1279, 9945, 31, 11006, 20644, 695, 13, 785, 29, 201, ...
3.704485
379
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198 ]
3.625
8
''' # ReadQuickly ``` |-- Server |-- __init__.py |-- server.py () |-- content.py () |-- spider () |-- weather () |-- notice () ``` '''
[ 7061, 6, 198, 2, 4149, 21063, 306, 220, 198, 198, 15506, 63, 198, 91, 438, 9652, 198, 220, 220, 220, 44233, 11593, 15003, 834, 13, 9078, 198, 220, 220, 220, 44233, 4382, 13, 9078, 220, 220, 7499, 198, 220, 220, 220, 44233, 2695, 1...
2.168831
77
import collections import dataclasses import itertools def segments(): with open("inputs/5.txt") as f: points = f.readlines() points = (p.strip() for p in points) points = (p.split("->") for p in points) points = ((p1.split(","), p2.split(",")) for p1, p2 in points) for (p1x, p1y), (p2x, p2y) in points: yield Segment( Point(int(p1x), int(p1y)), Point(int(p2x), int(p2y)), ) # 13319, to high print( count_interception( s for s in segments() if s.start.x == s.stop.x or s.start.y == s.stop.y ) ) # 19172 print(count_interception(segments()))
[ 11748, 17268, 198, 11748, 4818, 330, 28958, 198, 11748, 340, 861, 10141, 628, 628, 198, 4299, 17894, 33529, 198, 220, 220, 220, 351, 1280, 7203, 15414, 82, 14, 20, 13, 14116, 4943, 355, 277, 25, 198, 220, 220, 220, 220, 220, 220, 22...
2.141414
297
"""Functions related to converting content into dict/JSON structures.""" import codecs import json import logging from pyquery import PyQuery log = logging.getLogger(__name__) def process_file(fjson_filename): """Read the fjson file from disk and parse it into a structured dict.""" try: with codecs.open(fjson_filename, encoding='utf-8', mode='r') as f: file_contents = f.read() except IOError: log.info('Unable to read file: %s', fjson_filename) raise data = json.loads(file_contents) sections = [] path = '' title = '' if 'current_page_name' in data: path = data['current_page_name'] else: log.info('Unable to index file due to no name %s', fjson_filename) if data.get('body'): body = PyQuery(data['body']) sections.extend(generate_sections_from_pyquery(body)) else: log.info('Unable to index content for: %s', fjson_filename) if 'title' in data: title = data['title'] if title.startswith('<'): title = PyQuery(data['title']).text() else: log.info('Unable to index title for: %s', fjson_filename) return { 'path': path, 'title': title, 'sections': sections, } def parse_content(content): """ Removes the starting text and . It removes the starting text from the content because it contains the title of that content, which is redundant here. """ content = content.replace('', '').strip() # removing the starting text of each content = content.split('\n') if len(content) > 1: # there were \n content = content[1:] # converting newlines to ". " content = '. '.join([text.strip().rstrip('.') for text in content]) return content
[ 37811, 24629, 2733, 3519, 284, 23202, 2695, 656, 8633, 14, 40386, 8573, 526, 15931, 198, 198, 11748, 40481, 82, 198, 11748, 33918, 198, 11748, 18931, 198, 198, 6738, 12972, 22766, 1330, 9485, 20746, 628, 198, 6404, 796, 18931, 13, 1136, ...
2.568376
702
import contextlib from redbot.core import commands, Config from redbot.core.utils.menus import menu, DEFAULT_CONTROLS import discord import aiohttp import random slytherin = "https://cdn.shopify.com/s/files/1/1325/3287/products/HP8040B_930f8033-607f-41ee-a8e4-fa90871ce7a7.png?v=1546231154" gryffindor = "https://cdn10.bigcommerce.com/s-9p3fydit/products/370/images/1328/gryff1c__34591.1449620321.1280.1280.PNG?c=2" ravenclaw = "https://cdn10.bigcommerce.com/s-9p3fydit/products/372/images/1332/raven1c__54237.1449620971.1200.1200.PNG?c=2" hufflepuff = "https://cdn.shopify.com/s/files/1/0221/1146/products/Hufflepuff_Embroidered_Patch_Scaled_large.png?v=1553528874" harry = "https://www.freepngimg.com/thumb/harry_potter/5-2-harry-potter-png-file.png" hermione = "https://66.media.tumblr.com/3ce8453be755f31f93381918985b4918/tumblr_nn2lopIypj1rxkqbso1_1280.png" voldemort = ( "https://vignette.wikia.nocookie.net/harrypotter/images/6/6e/VoldemortHeadshot_DHP1.png" ) snape = "https://vignette.wikia.nocookie.net/harrypotter/images/a/a3/Severus_Snape.jpg" draco = "https://vignette.wikia.nocookie.net/harrypotter/images/7/7e/Draco_Malfoy_TDH.png" dumbledore = "https://images.ctfassets.net/bxd3o8b291gf/5ocauY6zAsqGiIgeECw06e/8accc1c586d2be7d9de6a3d9aec37b90/AlbusDumbledore_WB_F1_DumbledoreSmiling_Still_080615_Port.jpg" ron = "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Ron_Weasley_poster.jpg/220px-Ron_Weasley_poster.jpg" hagrid = "https://vignette.wikia.nocookie.net/harrypotter/images/e/ee/Rubeushagrid.PNG/revision/latest?cb=20161123044204" ginny = "http://hp-intothefire.wdfiles.com/local--files/ginny/ginny.jpg" sirius = "https://vignette.wikia.nocookie.net/harrypotter/images/7/75/Sirius_Black_profile.jpg/revision/latest?cb=20150918055024" mcgonagall = "https://vignette.wikia.nocookie.net/harrypotter/images/6/65/ProfessorMcGonagall-HBP.jpg/revision/latest?cb=20100612114856" def cog_unload(self): self.bot.loop.create_task(self.session.close())
[ 11748, 4732, 8019, 198, 198, 6738, 2266, 13645, 13, 7295, 1330, 9729, 11, 17056, 198, 6738, 2266, 13645, 13, 7295, 13, 26791, 13, 3653, 385, 1330, 6859, 11, 5550, 38865, 62, 10943, 5446, 3535, 50, 198, 11748, 36446, 198, 198, 11748, 2...
2.21875
896
from django.shortcuts import render
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 201, 198, 201, 198 ]
3.25
12
idadevelho=0 s=0 f=0 for p in range(1,3): print('---{} pessoa---'.format(p)) nome=str(input('digite o {} nome: '.format(p))).strip() idade=int(input('digite a idade da {} pessoa: '.format(p))) peso=float(input('digite o peso da {} pessoa: '.format(p))) sexo=str(input('sexo[M/F]: ')).upper().strip() s+=idade if p==1 and sexo=='M': idadevelho=idade nomevelho=nome elif sexo=='M' and idade>idadevelho: idadevelho=idade nomevelho=nome print() if sexo=='F' and idade<20: f+=1 nomemulher=nome media=s/2 print('o nome do homem mais velho ',nomevelho) print('a mdia de idade {}'.format(media)) print('a quantidade de mulheres com menos de 20 anos {}'.format(f))
[ 312, 671, 626, 8873, 28, 15, 198, 82, 28, 15, 198, 69, 28, 15, 198, 1640, 279, 287, 2837, 7, 16, 11, 18, 2599, 198, 220, 220, 220, 220, 3601, 10786, 6329, 90, 92, 279, 408, 12162, 6329, 4458, 18982, 7, 79, 4008, 198, 220, 220,...
1.97954
391
# -*- coding: utf-8 -*- """ Created on Thu May 3 18:33:28 2018 @author: malopez """ import pandas as pd import matplotlib.pyplot as plt import cv2 images_folder = "C:/Users/malopez/Desktop/disksMD/images" data_folder = "C:/Users/malopez/Desktop/disksMD/data" output_video = './video4.mp4' particle_radius = 1.0 n_particles = 90 # TODO: Why 3 is the minimun number of particles? desired_collisions_per_particle = 10 n_collisions = n_particles*desired_collisions_per_particle size_X = 60 # System size X size_Y = 30 # System size Y size_X_inches = 6*(size_X/size_Y) size_Y_inches = 6 size_figure = (size_X_inches, size_Y_inches) # Fenomenological constant ;p circle_size = 11875*size_X_inches*size_Y_inches / (size_X*size_Y) # circle_size = particle_radius*427500 / (size_X*size_Y) for i in range(n_collisions): file_name_pos = data_folder + "/xy"+'{0:05d}'.format(i)+".dat" pos = pd.read_table(file_name_pos, sep='\s+', header = None, names =['x', 'y']) img_name = images_folder+'/img'+'{0:05d}'.format(i)+".png" fig, ax = plt.subplots(figsize=size_figure, dpi=250) ax.set_xlim([0,size_X]) ax.set_ylim([0,size_Y]) plt.scatter(pos.x, pos.y, s=circle_size) fig.savefig(img_name) print('Saving img n: '+str(i)) plt.close() images = [] for i in range(n_collisions): images.append(images_folder+'/img'+'{0:05d}'.format(i)+".png") # Height and Width from first image frame = cv2.imread(images[0]) height, width, channels = frame.shape # Definimos el codec y creamos un objeto VideoWriter fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case out = cv2.VideoWriter(output_video, fourcc, 30.0, (width, height)) print('Generating video, please wait') for image in images: frame = cv2.imread(image) # Write out frame to video out.write(frame) # Release everything if job is finished out.release() print("The output video is {}".format(output_video))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 1737, 220, 513, 1248, 25, 2091, 25, 2078, 2864, 198, 198, 31, 9800, 25, 6428, 20808, 198, 37811, 198, 11748, 19798, 292, 355, 279, 67, 1...
2.426799
806
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES # OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the License for the specific language governing permissions and # limitations under the License. # # BootPriority.py # # This file defines the BootPriority helper class. # The boot priority class defines helper methods associated with boot priority
[ 2, 198, 2, 15069, 357, 34, 8, 685, 42334, 60, 10898, 42990, 21852, 11, 3457, 13, 198, 2, 198, 2, 7473, 5222, 12, 49, 1797, 33538, 318, 11971, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 198, 2, 220, 357, 1169, 366, 34156, 15...
3.472727
220
from django import template from django.utils.safestring import mark_safe import bleach from bleach.sanitizer import BleachSanitizer from bleach.encoding import force_unicode from bootstrap3.renderers import FieldRenderer from bootstrap3.text import text_value import html5lib import re register = template.Library() pos = [(0, 0), (1, 0), (0, 1), (2, 3), (1, 2), (2, 1), (2, 2)] re_spaceless = re.compile("(\n|\r)+") class CrlfNode(template.Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): rendered = self.nodelist.render(context).strip() return re_spaceless.sub("", rendered)
[ 6738, 42625, 14208, 1330, 11055, 198, 6738, 42625, 14208, 13, 26791, 13, 49585, 395, 1806, 1330, 1317, 62, 21230, 198, 198, 11748, 49024, 198, 6738, 49024, 13, 12807, 3029, 263, 1330, 48469, 15017, 3029, 263, 198, 6738, 49024, 13, 12685, ...
2.723577
246
import pytest # from pytest_factoryboy import register
[ 11748, 12972, 9288, 198, 2, 422, 12972, 9288, 62, 69, 9548, 7081, 1330, 7881, 628, 628 ]
3.625
16
import subprocess from mimetypes import MimeTypes from os import devnull, getcwd, listdir, makedirs, walk from os.path import basename, dirname, exists, isfile, join, splitext from pprint import pprint from urllib.request import pathname2url ALLOWED_AUDIO_MIMETYPES = ['audio/mpeg'] ALLOWED_IMAGE_MIMETYPES = ['image/jpeg', 'image/png'] CWD = getcwd() MP3_DIR = join(CWD, 'mp3') # Setup necessary variables mime = MimeTypes() if __name__ == '__main__': main()
[ 11748, 850, 14681, 198, 6738, 17007, 2963, 12272, 1330, 337, 524, 31431, 198, 6738, 28686, 1330, 1614, 8423, 11, 651, 66, 16993, 11, 1351, 15908, 11, 285, 4335, 17062, 11, 2513, 198, 6738, 28686, 13, 6978, 1330, 1615, 12453, 11, 26672, ...
2.709302
172
print("\033[6;3HHello")
[ 4798, 7203, 59, 44427, 58, 21, 26, 18, 39, 15496, 4943, 198 ]
2
12
import sys import difflib import errno import json import logging import functools import os import pytest from shell import shell from diag_paranoia import diag_paranoia, filtered_overview, sanitize_errors VALIDATOR_IMAGE = "datawire/ambassador-envoy-alpine:v1.5.0-116-g7ccb25882" DIR = os.path.dirname(__file__) EXCLUDES = [ "__pycache__" ] # TESTDIR = os.path.join(DIR, "tests") TESTDIR = DIR DEFAULT_CONFIG = os.path.join(DIR, "..", "default-config") MATCHES = [ n for n in os.listdir(TESTDIR) if (n.startswith('0') and os.path.isdir(os.path.join(TESTDIR, n)) and (n not in EXCLUDES)) ] os.environ['SCOUT_DISABLE'] = "1" #### decorators #### Utilities #### Test functions
[ 11748, 25064, 198, 198, 11748, 814, 8019, 198, 11748, 11454, 3919, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 1257, 310, 10141, 198, 11748, 28686, 198, 11748, 12972, 9288, 198, 198, 6738, 7582, 1330, 7582, 198, 198, 6738, 2566, 363...
2.508961
279
#!/usr/bin/env python3 import json import googlemaps import sys import os gmaps = googlemaps.Client(key=os.environ["GOOGLE_API_KEY"]) print(gmaps) filename = sys.argv[1] with open(filename) as f: data = json.load(f) for d in data: if d.get("address") and not d.get("latitude"): result = gmaps.geocode(d["address"]) print(result) result = result[0]["geometry"]["location"] d["latitude"] = result["lat"] d["longitude"] = result["lng"] with open(filename, "w") as f: json.dump(data, f)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 33918, 198, 11748, 23645, 31803, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 70, 31803, 796, 23645, 31803, 13, 11792, 7, 2539, 28, 418, 13, 268, 2268, 14692, 38, 6684, 3...
2.309013
233
import logging import numpy as np import pandas as pd from numba import prange, njit from tardis import constants as const from tardis.plasma.exceptions import PlasmaException from tardis.plasma.properties.base import ( ProcessingPlasmaProperty, Input, TransitionProbabilitiesProperty, ) from tardis.plasma.properties.j_blues import JBluesDiluteBlackBody __all__ = [ "SpontRecombRateCoeff", "StimRecombRateCoeff", "PhotoIonRateCoeff", "PhotoIonEstimatorsNormFactor", "PhotoIonRateCoeffEstimator", "StimRecombRateCoeffEstimator", "CorrPhotoIonRateCoeff", "BfHeatingRateCoeffEstimator", "StimRecombCoolingRateCoeffEstimator", "SpontRecombCoolingRateCoeff", "RawRecombTransProbs", "RawPhotoIonTransProbs", "CollDeexcRateCoeff", "CollExcRateCoeff", "RawCollisionTransProbs", "AdiabaticCoolingRate", "FreeFreeCoolingRate", "FreeBoundCoolingRate", "BoundFreeOpacity", "LevelNumberDensityLTE", "PhotoIonBoltzmannFactor", "FreeBoundEmissionCDF", "RawTwoPhotonTransProbs", "TwoPhotonEmissionCDF", "TwoPhotonFrequencySampler", "CollIonRateCoeffSeaton", "CollRecombRateCoeff", "RawCollIonTransProbs", "BoundFreeOpacityInterpolator", "FreeFreeOpacity", "ContinuumOpacityCalculator", "FreeFreeFrequencySampler", "FreeBoundFrequencySampler", ] N_A = const.N_A.cgs.value K_B = const.k_B.cgs.value C = const.c.cgs.value H = const.h.cgs.value A0 = const.a0.cgs.value M_E = const.m_e.cgs.value E = const.e.esu.value BETA_COLL = (H ** 4 / (8 * K_B * M_E ** 3 * np.pi ** 3)) ** 0.5 F_K = ( 16 / (3.0 * np.sqrt(3)) * np.sqrt((2 * np.pi) ** 3 * K_B / (H ** 2 * M_E ** 3)) * (E ** 2 / C) ** 3 ) # See Eq. 19 in Sutherland, R. S. 1998, MNRAS, 300, 321 FF_OPAC_CONST = ( (2 * np.pi / (3 * M_E * K_B)) ** 0.5 * 4 * E ** 6 / (3 * M_E * H * C) ) # See Eq. 6.1.8 in http://personal.psu.edu/rbc3/A534/lec6.pdf logger = logging.getLogger(__name__) njit_dict = {"fastmath": False, "parallel": False} # It is currently not possible to use scipy.integrate.cumulative_trapezoid in # numba. So here is my own implementation. def get_ion_multi_index(multi_index_full, next_higher=True): """ Calculate the corresponding ion MultiIndex for a level MultiIndex. Parameters ---------- multi_index_full : pandas.MultiIndex (atomic_number, ion_number, level_number) next_higher : bool, default True If True use ion number of next higher ion, else use ion_number from multi_index_full. Returns ------- pandas.MultiIndex (atomic_number, ion_number) Ion MultiIndex for the given level MultiIndex. """ atomic_number = multi_index_full.get_level_values(0) ion_number = multi_index_full.get_level_values(1) if next_higher is True: ion_number += 1 return pd.MultiIndex.from_arrays([atomic_number, ion_number]) def get_ground_state_multi_index(multi_index_full): """ Calculate the ground-state MultiIndex for the next higher ion. Parameters ---------- multi_index_full : pandas.MultiIndex (atomic_number, ion_number, level_number) Returns ------- pandas.MultiIndex (atomic_number, ion_number) Ground-state MultiIndex for the next higher ion. """ atomic_number = multi_index_full.get_level_values(0) ion_number = multi_index_full.get_level_values(1) + 1 level_number = np.zeros_like(ion_number) return pd.MultiIndex.from_arrays([atomic_number, ion_number, level_number]) def cooling_rate_series2dataframe(cooling_rate_series, destination_level_idx): """ Transform cooling-rate Series to DataFrame. This function transforms a Series with cooling rates into an indexed DataFrame that can be used in MarkovChainTransProbs. Parameters ---------- cooling_rate_series : pandas.Series, dtype float Cooling rates for a process with a single destination idx. Examples are adiabatic cooling or free-free cooling. destination_level_idx : str Destination idx of the cooling process; for example 'adiabatic' for adiabatic cooling. Returns ------- cooling_rate_frame : pandas.DataFrame, dtype float Indexed by source_level_idx, destination_level_idx, transition_type for the use in MarkovChainTransProbs. """ index_names = [ "source_level_idx", "destination_level_idx", "transition_type", ] index = pd.MultiIndex.from_tuples( [("k", destination_level_idx, -1)], names=index_names ) cooling_rate_frame = pd.DataFrame( cooling_rate_series.values[np.newaxis], index=index ) return cooling_rate_frame def bf_estimator_array2frame(bf_estimator_array, level2continuum_idx): """ Transform a bound-free estimator array to a DataFrame. This function transforms a bound-free estimator array with entries sorted by frequency to a multi-indexed DataFrame sorted by level. Parameters ---------- bf_estimator_array : numpy.ndarray, dtype float Array of bound-free estimators (e.g., for the stimulated recombination rate) with entries sorted by the threshold frequency of the bound-free continuum. level2continuum_idx : pandas.Series, dtype int Maps a level MultiIndex (atomic_number, ion_number, level_number) to the continuum_idx of the corresponding bound-free continuum (which are sorted by decreasing frequency). Returns ------- pandas.DataFrame, dtype float Bound-free estimators indexed by (atomic_number, ion_number, level_number). """ bf_estimator_frame = pd.DataFrame( bf_estimator_array, index=level2continuum_idx.index ).sort_index() bf_estimator_frame.columns.name = "Shell No." return bf_estimator_frame class IndexSetterMixin(object):
[ 11748, 18931, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 997, 7012, 1330, 778, 858, 11, 299, 45051, 198, 6738, 256, 446, 271, 1330, 38491, 355, 1500, 198, 198, 6738, 256, 446, 271, ...
2.490886
2,414
#!/usr/bin/env python from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser import json import os import codecs from bs4 import BeautifulSoup import argparse import requests import sys import googleapiclient # MAIN if __name__ == "__main__": parser = argparse.ArgumentParser(description='Pull some youtube.') parser.add_argument("--key", help="https://cloud.google.com/console") args = parser.parse_args() # Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps # tab of # https://cloud.google.com/console # Please ensure that you have enabled the YouTube Data API for your project. DEVELOPER_KEY = args.key YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) for f in os.listdir("../flashpoint/videos/"): get_video_suggestions(youtube,f)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 2471, 291, 75, 1153, 13, 67, 40821, 1330, 1382, 198, 6738, 2471, 291, 75, 1153, 13, 48277, 1330, 367, 29281, 12331, 198, 6738, 267, 18439, 17, 16366, 13, 31391, 1330, 1822, ...
2.847458
354
# **************************************************************************** # # # # ::: :::::::: # # logger.py :+: :+: :+: # # +:+ +:+ +:+ # # By: darodrig <darodrig@42madrid.com> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/04/15 22:12:50 by darodrig #+# #+# # # Updated: 2020/04/15 22:12:50 by darodrig ### ########.fr # # # # **************************************************************************** # import time import functools from string import capwords import getpass import datetime
[ 2, 41906, 17174, 46068, 1303, 201, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.506042
662
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################### # Author: Mu yanru # Date : 2019.2 # Email : muyanru345@163.com ################################################################### from dayu_widgets.avatar import MAvatar from dayu_widgets.divider import MDivider from dayu_widgets.field_mixin import MFieldMixin from dayu_widgets.label import MLabel from dayu_widgets.push_button import MPushButton from dayu_widgets import dayu_theme from dayu_widgets.qt import QWidget, QVBoxLayout, MPixmap, QFormLayout, Qt, QHBoxLayout if __name__ == '__main__': import sys from dayu_widgets.qt import QApplication app = QApplication(sys.argv) test = AvatarExample() dayu_theme.apply(test) test.show() sys.exit(app.exec_())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 29113, 21017, 198, 2, 6434, 25, 8252, 331, 272, 622, 198, 2, 7536, 220, 1058, 13130, 13, 17, 198, 2, 9570, 1...
3.033708
267
#Assignment 9.4 #print('Hello World') fname = input('Enter name: ') if len(fname) < 1 : fname = 'mbox-short.txt' handle = open(fname) di = {} #create an empty dictionary for line in handle: line = line.rstrip() wds = line.split() #the second for-loop to print each word in the list for w in wds : #if the key is not in the dictionar the count starts with 0 ##oldcount = di.get(w,0) ##print(w, 'old', oldcount) ##newcount = oldcount + 1 ##di[w] = newcount ##print(w, 'new', newcount) di[w] = di.get(w, 0) + 1 #print(w, 'new', di[w]) #workflow: retrieve/created/update counter #if w in di: # di[w] = di[w] + 1 #print('*Existing*') #To provide a hint of what the programmes is doing # else: # di[w] = 1 #print('**New**') #To provide a hint of what the programmes is doing #print(di) #print the Most commoncommon word programme. #mulitiple for-loop largest = -1 theword = None for k, v in di.items() : # times looks for the elements in dictionary print(k, v) if v > largest : largest = v theword = k # catch/remember the word that was largest print('Most common', theword,largest)
[ 2, 8021, 16747, 860, 13, 19, 198, 2, 4798, 10786, 15496, 2159, 11537, 198, 198, 69, 3672, 796, 5128, 10786, 17469, 1438, 25, 705, 8, 198, 361, 18896, 7, 69, 3672, 8, 1279, 352, 1058, 277, 3672, 796, 705, 2022, 1140, 12, 19509, 13,...
2.335196
537
from bs4 import BeautifulSoup from difflib import SequenceMatcher
[ 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 814, 8019, 1330, 45835, 19044, 2044, 628, 628, 628, 628 ]
3.65
20
from django.contrib import admin from django import forms from .models import Annotation, Clip, Food, Image, Language, Website, UserProfile admin.site.register(Annotation, AnnotationAdmin) admin.site.register(Clip, ClipAdmin) admin.site.register(Food, FoodAdmin) admin.site.register(Image, ImageAdmin) admin.site.register(Language, LanguageAdmin) admin.site.register(Website, WebsiteAdmin) admin.site.register(UserProfile, UserProfileAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 764, 27530, 1330, 1052, 38983, 11, 42512, 11, 7318, 11, 7412, 11, 15417, 11, 15887, 11, 11787, 37046, 628, 198, 28482, 13, 15654, 13, 30238,...
3.355072
138
from os.path import abspath, join, dirname from colibris.conf import settings STATIC_PATH = abspath(join(dirname(__file__), 'swagger')) UI_URL = settings.API_DOCS_URL STATIC_URL = '{}/static'.format(UI_URL) APISPEC_URL = '{}/apispec'.format(UI_URL)
[ 6738, 28686, 13, 6978, 1330, 2352, 6978, 11, 4654, 11, 26672, 3672, 198, 198, 6738, 951, 571, 2442, 13, 10414, 1330, 6460, 198, 198, 35744, 2149, 62, 34219, 796, 2352, 6978, 7, 22179, 7, 15908, 3672, 7, 834, 7753, 834, 828, 705, 203...
2.49505
101
#!/usr/bin/env python from arc import models from arc import methods from arc import black_boxes from arc import others from arc import coverage
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 10389, 1330, 4981, 198, 6738, 10389, 1330, 5050, 198, 6738, 10389, 1330, 2042, 62, 29305, 198, 6738, 10389, 1330, 1854, 198, 6738, 10389, 1330, 5197, 198 ]
4.027778
36
# -*- coding: utf-8 -*- from qcloudsdkcore.request import Request
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 10662, 17721, 21282, 74, 7295, 13, 25927, 1330, 19390, 198 ]
2.576923
26
""" Step Chart ----------------- This example shows Google's stock price over time. """ import altair as alt from vega_datasets import data source = data.stocks() chart = alt.Chart(source).mark_line(interpolate = 'step-after').encode( x = 'date', y = 'price' ) chart.transform = [{"filter": "datum.symbol==='GOOG'"}]
[ 37811, 198, 8600, 22086, 198, 1783, 12, 198, 1212, 1672, 2523, 3012, 338, 4283, 2756, 625, 640, 13, 198, 37811, 198, 198, 11748, 5988, 958, 355, 5988, 198, 6738, 1569, 4908, 62, 19608, 292, 1039, 1330, 1366, 198, 198, 10459, 796, 1366...
2.836207
116
# -*- coding: utf-8 -*- """ file: graph_networkx.py Provides a NetworkX compliant Graph class. """ from graphit.graph import GraphBase from graphit.graph_exceptions import GraphitException, GraphitNodeNotFound from graphit.graph_algorithms import degree, size from graphit.graph_utils.graph_utilities import graph_undirectional_to_directional, graph_directional_to_undirectional
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 7753, 25, 4823, 62, 27349, 87, 13, 9078, 198, 198, 15946, 1460, 257, 7311, 55, 31332, 29681, 1398, 13, 198, 37811, 198, 198, 6738, 4823, 270, 13, 3496...
3.273504
117
import os import random #initiate a list called emails_list emails_list = [] Directory = '/home/azureuser/spam_filter/enron1/emails/' Dir_list = os.listdir(Directory) for file in Dir_list: f = open(Directory + file, 'r') emails_list.append(f.read()) f.close()
[ 11748, 28686, 198, 11748, 4738, 198, 2, 259, 8846, 378, 257, 1351, 1444, 7237, 62, 4868, 198, 368, 1768, 62, 4868, 796, 17635, 198, 43055, 796, 31051, 11195, 14, 1031, 495, 7220, 14, 2777, 321, 62, 24455, 14, 268, 1313, 16, 14, 368,...
2.708333
96
import cv2 as cv import mediapipe as mp if __name__ == "__main__": video = cv.VideoCapture(0) detector = PoseDetector() while True: success, img = video.read() image = detector.find_pose(img) cv.imshow("Image", image) cv.waitKey(1)
[ 11748, 269, 85, 17, 355, 269, 85, 198, 11748, 16957, 499, 3757, 355, 29034, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 2008, 796, 269, 85, 13, 10798, 49630, 7, 15, 8, 198, 220, 220, 220,...
2.141791
134
r""" This is the base module for all other objects of the package. + `LaTeX` returns a LaTeX string out of an `Irene` object. + `base` is the parent of all `Irene` objects. """ def LaTeX(obj): r""" Returns LaTeX representation of Irene's objects. """ from sympy.core.core import all_classes from Irene import SDPRelaxations, SDRelaxSol, Mom inst = isinstance(obj, SDPRelaxations) or isinstance( obj, SDRelaxSol) or isinstance(obj, Mom) if inst: return obj.__latex__() elif isinstance(obj, tuple(all_classes)): from sympy import latex return latex(obj)
[ 81, 37811, 198, 1212, 318, 262, 2779, 8265, 329, 477, 584, 5563, 286, 262, 5301, 13, 628, 220, 220, 220, 1343, 4600, 14772, 49568, 63, 5860, 257, 4689, 49568, 4731, 503, 286, 281, 4600, 40, 25924, 63, 2134, 13, 198, 220, 220, 220, ...
2.616667
240
from stanza.server import CoreNLPClient import os # example text print('---') print('input text') print('') # text = "Chris Manning is a nice person. Chris wrote a simple sentence. He also gives oranges to people." text = "PyTables is built on top of the HDF5 library, using the Python language and the NumPy package." print(text) # set up the client print('---') print('starting up Java Stanford CoreNLP Server...') # set up the client # with CoreNLPClient(annotators=['tokenize','ssplit','pos','lemma','ner','parse','depparse','coref'], timeout=60000, memory='4G', be_quiet=True) as client: with CoreNLPClient(annotators=['tokenize','ssplit','pos','parse','depparse'], timeout=60000, memory='4G', be_quiet=True) as client: # submit the request to the server ann = client.annotate(text) # print("ann is ", ann) # os.system("pause") # get the first sentence sentence = ann.sentence[0] print("sentence is ", sentence) os.system("pause") # get the dependency parse of the first sentence # print('---') # print('dependency parse of first sentence') # dependency_parse = sentence.basicDependencies # print(dependency_parse) # os.system("pause") # HDSKG's method print('---') print('enhanced++ dependency parse of first sentence') enhanced_plus_plus_dependency_parse = sentence.enhancedPlusPlusDependencies print(enhanced_plus_plus_dependency_parse) os.system("pause") # get the constituency parse of the first sentence # print('---') # print('constituency parse of first sentence') # constituency_parse = sentence.parseTree # print(constituency_parse) # os.system("pause") # get the first subtree of the constituency parse # print('---') # print('first subtree of constituency parse') # print(constituency_parse.child[0]) # os.system("pause") # get the value of the first subtree # print('---') # print('value of first subtree of constituency parse') # print(constituency_parse.child[0].value) # os.system("pause") # get the first token of the first sentence print('---') print('first token of first sentence') token = sentence.token[0] print(token) os.system("pause") # get the part-of-speech tag print('---') print('part of speech tag of token') token.pos print(token.pos) os.system("pause") # get the named entity tag print('---') print('named entity tag of token') print(token.ner) os.system("pause") # get an entity mention from the first sentence # print('---') # print('first entity mention in sentence') # print(sentence.mentions[0]) # os.system("pause") # access the coref chain # print('---') # print('coref chains for the example') # print(ann.corefChain) # os.system("pause") # Use tokensregex patterns to find who wrote a sentence. # pattern = '([ner: PERSON]+) /wrote/ /an?/ []{0,3} /sentence|article/' pattern = "([tag: NNP]{1,}) ([ tag:/VB.*/ ]) /an?/ ([pos:JJ]{0,3}) /sentence|article/" matches = client.tokensregex(text, pattern) print("tokensregex matches is ", matches) # sentences contains a list with matches for each sentence. assert len(matches["sentences"]) == 3 # length tells you whether or not there are any matches in this assert matches["sentences"][1]["length"] == 1 # You can access matches like most regex groups. # print("sentence is ",["sentences"][1]["0"]["text"]) matches["sentences"][1]["0"]["text"] == "Chris wrote a simple sentence" matches["sentences"][1]["0"]["1"]["text"] == "Chris" # # Use semgrex patterns to directly find who wrote what. # pattern = '{word:wrote} >nsubj {}=subject >dobj {}=object' # matches = client.semgrex(text, pattern) # # print("semgrex matches is", matches) # # sentences contains a list with matches for each sentence. # assert len(matches["sentences"]) == 3 # # length tells you whether or not there are any matches in this # assert matches["sentences"][1]["length"] == 1 # # You can access matches like most regex groups. # matches["sentences"][1]["0"]["text"] == "wrote" # matches["sentences"][1]["0"]["$subject"]["text"] == "Chris" # matches["sentences"][1]["0"]["$object"]["text"] == "sentence"
[ 6738, 336, 35819, 13, 15388, 1330, 7231, 45, 19930, 11792, 198, 11748, 28686, 198, 198, 2, 1672, 2420, 198, 4798, 10786, 6329, 11537, 198, 4798, 10786, 15414, 2420, 11537, 198, 4798, 7, 7061, 8, 198, 198, 2, 2420, 796, 366, 15645, 152...
2.855453
1,522
#!/usr/bin/env python # By Jinyuan Sun
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 2750, 449, 3541, 7258, 3825, 628, 198 ]
2.411765
17
import enum from typing import Optional, Dict import httpx from tea import serde from tea_client import errors from tea_client.models import TeaClientModel
[ 11748, 33829, 198, 6738, 19720, 1330, 32233, 11, 360, 713, 198, 198, 11748, 2638, 87, 198, 6738, 8887, 1330, 1055, 2934, 198, 198, 6738, 8887, 62, 16366, 1330, 8563, 198, 6738, 8887, 62, 16366, 13, 27530, 1330, 15777, 11792, 17633, 628,...
3.809524
42
import unittest from typing import List import Connector
[ 11748, 555, 715, 395, 198, 6738, 19720, 1330, 7343, 198, 198, 11748, 8113, 273, 628, 198 ]
3.75
16
import tensorflow as tf from tensorflow import keras
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 1330, 41927, 292, 198 ]
3.533333
15
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2020, Nigel Small # # 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 pytest import raises from py2neo import Transaction def test_should_fail_on_tx_create_object(): tx = Transaction(FakeGraph()) with raises(TypeError): tx.create(object()) def test_should_fail_on_tx_delete_object(): tx = Transaction(FakeGraph()) with raises(TypeError): tx.delete(object()) def test_should_fail_on_tx_merge_object(): tx = Transaction(FakeGraph()) with raises(TypeError): tx.merge(object()) def test_should_fail_on_tx_pull_object(): tx = Transaction(FakeGraph()) with raises(TypeError): tx.pull(object()) def test_should_fail_on_tx_push_object(): tx = Transaction(FakeGraph()) with raises(TypeError): tx.push(object()) def test_should_fail_on_tx_separate_object(): tx = Transaction(FakeGraph()) with raises(TypeError): tx.separate(object())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 2813, 12, 42334, 11, 28772, 10452, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, ...
2.954813
509
#from https://github.com/mfurukawa/imu_sensor/tree/master/src/Python # September 03, 2020 # Yuto Nakayachi from __future__ import unicode_literals ,print_function import serial from time import sleep import numpy as np import matplotlib.pyplot as plt import io import csv import time import datetime import struct import tensorflow as tf from tensorflow import keras # Variable to get real value MPU9250A_2g = 0.000061035156 # 0.000061035156 g/LSB MPU9250A_4g = 0.000122070312 # 0.000122070312 g/LSB MPU9250A_8g = 0.000244140625 # 0.000244140625 g/LSB MPU9250A_16g = 0.000488281250 # 0.000488281250 g/LSB MPU9250G_250dps = 0.007633587786 # 0.007633587786 dps/LSB MPU9250G_500dps = 0.015267175572 # 0.015267175572 dps/LSB MPU9250G_1000dps = 0.030487804878 # 0.030487804878 dps/LSB MPU9250G_2000dps = 0.060975609756 # 0.060975609756 dps/LSB MPU9250M_4800uT = 0.6 # 0.6 uT/LSB MPU9250T_85degC = 0.002995177763 # 0.002995177763 degC/LSB Magnetometer_Sensitivity_Scale_Factor = 0.15 # number of axis numVariable = 24 # 4ch * 6acc # Maximum time for measure minuteLength = 25 # sampling rate smplHz = 500 # Variable to count number of sampling smpl_cnt = 0 # Variable to count number of fail fail_cnt_byte = 0 fail_cnt_head = 0 # Array to store data buf = [[0 for i in range(numVariable + 2)] for j in range(smplHz*60*minuteLength)] # Array to store real value buf_f = [[0 for i in range(numVariable + 2)] for j in range(smplHz*60*minuteLength)] # define serial port ser = serial.Serial("COM3",921600,timeout=1) # Check serial connection if ser.is_open: print("Start Serial Connection") else: print("PORT ERROR") ser.close() exit() # Function to create csv file # Function to Measure # Start print("ready? --> press s key") while(1): ready_s = input() if ready_s == "s": break if ready_s == "r": print("over") ser.close() exit() # Measure the start time p_time = time.time() # Function to measure readByte() # Measure the end time e_time = time.time() # The time it took print("time: ",e_time - p_time) # Function to create csv file writeCSV() # close serial port ser.close() print("number of data: ",smpl_cnt) print("number of byte fail: ",fail_cnt_byte) print("number of header fail: ",fail_cnt_head) print("END")
[ 2, 6738, 3740, 1378, 12567, 13, 785, 14, 76, 38916, 2724, 6909, 14, 320, 84, 62, 82, 22854, 14, 21048, 14, 9866, 14, 10677, 14, 37906, 220, 198, 2, 2693, 7643, 11, 12131, 198, 2, 575, 9390, 22255, 323, 14299, 220, 198, 198, 6738, ...
2.373878
1,003
import matplotlib as mpl mpl.use('agg') import glob import argparse from time import time import numpy as np import pylab as plt import rficnn as rfc parser = argparse.ArgumentParser() parser.add_argument('--arch', required=False, help='choose architecture', type=str, default='1') parser.add_argument('--trsh', required=False, help='choose threshold', type=float, default=0.1) args = parser.parse_args() threshold = args.trsh rfc.the_print('Chosen architecture is: '+args.arch+' and threshod is: '+str(threshold),bgc='green') model_add = './models/model_'+args.arch+'_'+str(threshold) conv = ss.ConvolutionalLayers(nx=276,ny=400,n_channel=1,restore=1, model_add=model_add,arch_file_name='arch_'+args.arch) sim_files = glob.glob('../data/hide_sims_test/calib_1year/*.fits')) times = [] for fil in sim_files: fname = fil.split('/')[-1] print fname data,mask = read_chunck_sdfits(fil,label_tag=RFI,threshold=0.1,verbose=0) data = np.clip(np.fabs(data), 0, 200) data -= data.min() data /= data.max() lnx,lny = data.shape s = time() pred = conv.conv_large_image(data.reshape(1,lnx,lny,1),pad=10,lx=276,ly=400) e = time() times.append(e-s) mask = mask[10:-10,:] pred = pred[10:-10,:] fig, (ax1,ax2,ax3) = plt.subplots(3,1,figsize=(18,8)) ax1.imshow(data,aspect='auto') ax2.imshow(mask,aspect='auto') ax3.imshow(pred,aspect='auto') np.save('../comparison/'+fname+'_mask_'+sys.argv[1],mask) np.save('../comparison/'+fname+'_pred_'+sys.argv[1],pred) plt.subplots_adjust(left=0.04, right=0.99, top=0.99, bottom=0.04) plt.savefig('../comparison/'+fname+'_'+sys.argv[1]+'.jpg',dpi=30) plt.close() print np.mean(times)
[ 11748, 2603, 29487, 8019, 355, 285, 489, 198, 76, 489, 13, 1904, 10786, 9460, 11537, 198, 198, 11748, 15095, 198, 11748, 1822, 29572, 198, 6738, 640, 1330, 640, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 279, 2645, 397, 355, 458, ...
2.162762
811
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.header import Header from email.mime.base import MIMEBase from email import encoders import os import uuid import smtplib import re
[ 6738, 3053, 13, 76, 524, 13, 16680, 541, 433, 1330, 337, 3955, 3620, 586, 541, 433, 198, 6738, 3053, 13, 76, 524, 13, 5239, 220, 220, 220, 220, 220, 1330, 337, 3955, 2767, 2302, 198, 6738, 3053, 13, 76, 524, 13, 9060, 220, 220, ...
2.80198
101
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import *
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 33918, 198, 198, 6738, 435, 541, 323, 13, 64, 404, 13, 15042, 13, 9979, 415, 13, 22973, 34184, 1187, 1330, 163...
2.446809
47
#!/usr/bin/env python # # Copyright 2009 Facebook # # 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. """Implementation of an S3-like storage server based on local files. Useful to test features that will eventually run on S3, or if you want to run something locally that was once running on S3. We don't support all the features of S3, but it does work with the standard S3 client for the most basic semantics. To use the standard S3 client with this module: c = S3.AWSAuthConnection("", "", server="localhost", port=8888, is_secure=False) c.create_bucket("mybucket") c.put("mybucket", "mykey", "a value") print c.get("mybucket", "mykey").body """ import bisect import datetime import hashlib import os import os.path import urllib from tornado import escape from tornado import httpserver from tornado import ioloop from tornado import web def start(port, root_directory="/tmp/s3", bucket_depth=0): """Starts the mock S3 server on the given port at the given path.""" application = S3Application(root_directory, bucket_depth) http_server = httpserver.HTTPServer(application) http_server.listen(port) ioloop.IOLoop.instance().start()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 3717, 3203, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287,...
3.239089
527
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed 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. """Test results APIs.""" import typing # Non-standard docstrings are used to generate the API documentation. import endpoints from protorpc import message_types from protorpc import messages from protorpc import remote from multitest_transport.api import base from multitest_transport.models import messages as mtt_messages from multitest_transport.models import ndb_models from multitest_transport.models import sql_models from multitest_transport.util import tfc_client from multitest_transport.util import xts_result
[ 2, 15069, 33448, 3012, 11419, 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, 733...
3.815972
288
import numpy as np loss_arr = np.array(list()) with open("total_loss.txt", "r") as f_loss: cnt = 0 for loss in f_loss.readlines(): cnt += 1 # print(loss) loss_arr = np.append(loss_arr, float(loss)) print(cnt)
[ 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 22462, 62, 3258, 796, 45941, 13, 18747, 7, 4868, 28955, 201, 198, 4480, 1280, 7203, 23350, 62, 22462, 13, 14116, 1600, 366, 81, 4943, 355, 277, 62, 22462, 25, 201, 198, 220, 220, 22...
2
130
'''Image utils''' from io import BytesIO from PIL import Image import matplotlib.pyplot as plt def save_and_open(save_func): '''Save to in-memory buffer and re-open ''' buf = BytesIO() save_func(buf) buf.seek(0) bytes_ = buf.read() buf_ = BytesIO(bytes_) return buf_ def fig_to_pil(fig: plt.Figure): '''Convert matplot figure to PIL Image''' buf = save_and_open(fig.savefig) return Image.open(buf)
[ 7061, 6, 5159, 3384, 4487, 7061, 6, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198, 4299, 3613, 62, 392, 62, 9654, 7, 21928, 62...
2.356383
188
import hashlib import logging from struct import unpack import sys import time from . import (connector_wire_messages as cwm, AtLeastOnceSourceConnector, ProtocolError, ConnectorError) if sys.version_info.major == 2: from .base_meta2 import BaseMeta, abstractmethod else: from .base_meta3 import BaseMeta, abstractmethod def stream_added(self, stream): logging.debug("MultiSourceConnector added {}".format(stream)) source, acked = self.sources.get(stream.id, (None, None)) if source: if stream.point_of_ref != source.point_of_ref(): source.reset(stream.point_of_ref) # probably got this as part of the _handle_ok logic. Store the ack # and use when a source matching the stream id is added else: self.sources[stream.id] = [None, stream.point_of_ref] def stream_removed(self, stream): logging.debug("MultiSourceConnector removed {}".format(stream)) pass def stream_opened(self, stream): logging.debug("MultiSourceConnector stream_opened {}".format(stream)) source, acked = self.sources.get(stream.id, (None, None)) if source: if stream.id in self.joining: self.joining.remove(stream.id) if stream.point_of_ref != source.point_of_ref(): source.reset(stream.point_of_ref) self.open.add(stream.id) else: raise ConnectorError("Stream {} was opened for unknown source. " "Please use the add_source interface." .format(stream)) def stream_closed(self, stream): logging.debug("MultiSourceConnector closed {}".format(stream)) source, acked = self.sources.get(stream.id, (None, None)) if source: if stream.id in self.open: # source was open so move it back to joining state self.open.remove(stream.id) self.joining.add(stream.id) elif stream.id in self.pending_eos_ack: # source was pending eos ack, but that was interrupted # move it back to joining del self.pending_eos_ack[stream.id] self.joining.add(stream.id) elif stream.id in self.closed: logging.debug("tried to close an already closed source: {}" .format(Source)) else: pass else: pass def stream_acked(self, stream): logging.debug("MultiSourceConnector acked {}".format(stream)) source, acked = self.sources.get(stream.id, (None, None)) if source: # check if there's an eos pending this ack eos_point_of_ref = self.pending_eos_ack.get(stream.id, None) if eos_point_of_ref: logging.debug("Stream {} is awaiting EOS Ack for {}" .format(stream, eos_point_of_ref)) # source was pending eos ack # check ack's point of ref if stream.point_of_ref == eos_point_of_ref: # can finish closing it now self._close_and_delete_source(source) return elif stream.point_of_ref < eos_point_of_ref: pass else: raise ConnectorError("Got ack point of ref that is larger" " than the ended stream's point of ref.\n" "Expected: {}, Received: {}" .format(eos_point_of_ref, stream)) elif isinstance(acked, int): # acked may be 0 & use this clause! # regular ack (incremental ack of a live stream) if stream.point_of_ref < acked: logging.warning("got an ack for older point of reference" " for stream {}".format(stream)) source.reset(stream.point_of_ref) else: # source was added before connect()\handle_ok => reset source.reset(stream.point_of_ref) # update acked point of ref for the source self.sources[stream.id][1] = stream.point_of_ref elif stream.id in self.closed: pass else: raise ConnectorError("Stream {} was opened for unknown source. " "Please use the add_source interface." .format(stream))
[ 11748, 12234, 8019, 198, 11748, 18931, 198, 6738, 2878, 1330, 555, 8002, 198, 11748, 25064, 198, 11748, 640, 628, 198, 6738, 764, 1330, 357, 8443, 273, 62, 21809, 62, 37348, 1095, 355, 269, 26377, 11, 198, 220, 220, 220, 220, 220, 220...
2.034483
2,262
# Copyright The PyTorch Lightning team. # # 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. """ Device Stats Monitor ==================== Monitors and logs device stats during training. """ from typing import Any, Dict, Optional import pytorch_lightning as pl from pytorch_lightning.callbacks.base import Callback from pytorch_lightning.utilities.exceptions import MisconfigurationException from pytorch_lightning.utilities.types import STEP_OUTPUT
[ 2, 15069, 383, 9485, 15884, 354, 12469, 1074, 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, 1...
3.776892
251