content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python3 # coding: utf-8 # author: Francesco Lumachi <francesco.lumachi@gmail.com> import pandas as pd import numpy as np from itertools import islice from sklearn.utils.validation import check_X_y
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 1772, 25, 27025, 1073, 18348, 14299, 1279, 8310, 1817, 1073, 13, 75, 388, 14299, 31, 14816, 13, 785, 29, 198, 198, 11748, 19798, 292, 35...
2.779221
77
import datetime import picmodels.models from picmodels.models.utils import filter_db_queryset_by_id from picmodels.models.care_advisors.navigator_models.services.read import filter_navigator_objs_by_f_and_l_name from picmodels.models.care_advisors.navigator_models.services.read import filter_navigator_objs_by_first_name from picmodels.models.care_advisors.navigator_models.services.read import filter_navigator_objs_by_last_name from picmodels.models.care_advisors.navigator_models.services.read import filter_navigator_objs_by_email from picmodels.models.care_advisors.navigator_models.services.read import filter_navigator_objs_by_mpn
[ 11748, 4818, 8079, 198, 198, 11748, 8301, 27530, 13, 27530, 198, 6738, 8301, 27530, 13, 27530, 13, 26791, 1330, 8106, 62, 9945, 62, 10819, 893, 316, 62, 1525, 62, 312, 198, 6738, 8301, 27530, 13, 27530, 13, 6651, 62, 324, 27681, 13, ...
3.140097
207
# Copyright 2018 TWO SIGMA OPEN SOURCE, 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. import argparse import sys import beakerx from notebook import notebookapp as app from .install import install, uninstall from .bkr2ipynb import main from beakerx_magics import Py4JServer
[ 2, 15069, 2864, 35288, 33993, 5673, 38303, 311, 31033, 11, 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...
3.70892
213
from datetime import datetime from typing import List import dateutil from datasets import TextDataset from miscc.config import cfg_from_file, cfg from torchvision.transforms import transforms from attnganw.train import GanTrainerWrapper, BirdGenerationFromCaption
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 19720, 1330, 7343, 198, 198, 11748, 3128, 22602, 198, 6738, 40522, 1330, 8255, 27354, 292, 316, 198, 6738, 2984, 535, 13, 11250, 1330, 30218, 70, 62, 6738, 62, 7753, 11, 30218, 70, 198, 6...
3.69863
73
''' @brief Base class for system data classes. This class defines the interface for cata classes which are intended to hold a specific data item (packet, channel, event). This data item includes the time of the data as well as data such as channel value or argument value. @date Created July 2, 2018 @author R. Joseph Paetz (rpaetz@jpl.nasa.gov) @bug No known bugs ''' from fprime.common.models.serialize import time_type from fprime_gds.common.templates import data_template import fprime_gds.common.utils.jsonable if __name__ == '__main__': pass
[ 7061, 6, 198, 31, 65, 3796, 7308, 1398, 329, 1080, 1366, 6097, 13, 198, 198, 1212, 1398, 15738, 262, 7071, 329, 269, 1045, 6097, 543, 389, 5292, 284, 1745, 198, 64, 2176, 1366, 2378, 357, 8002, 316, 11, 6518, 11, 1785, 737, 770, 1...
3.307692
169
## # Copyright (c) 2011-2015 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## from twext.enterprise.dal.syntax import SQLFragment from twisted.trial.unittest import TestCase from twistedcaldav import carddavxml from txdav.carddav.datastore.query.filter import Filter, FilterBase from txdav.common.datastore.sql_tables import schema from txdav.carddav.datastore.query.builder import buildExpression from txdav.common.datastore.query.generator import SQLQueryGenerator from txdav.carddav.datastore.index_file import sqladdressbookquery
[ 2235, 198, 2, 15069, 357, 66, 8, 2813, 12, 4626, 4196, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, ...
3.490196
306
# ERFNet full model definition for Pytorch # Sept 2017 # Eduardo Romera ####################### import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F #ERFNet
[ 2, 13793, 37, 7934, 1336, 2746, 6770, 329, 9485, 13165, 354, 198, 2, 2362, 2177, 198, 2, 40766, 13109, 3570, 8607, 198, 14468, 4242, 21017, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 204...
3.274194
62
#!/usr/bin/env python # -*- coding: utf-8 -*- """ WSGI script Setup Application, Authentication, ... """ import os from eve import Eve from evedom import loader # from your_app.authentication.token import TokenBasedAuth __author__ = "nam4dev" __created__ = '08/11/2017' ROOT_PATH = os.path.dirname( os.path.abspath(__file__) ) EVE_SETTINGS = os.path.join(ROOT_PATH, 'settings.py') def runner(*_, **options): """ A simple runner Args: *_: **options: Returns: Flask App run """ arguments = dict( debug=1, port=5000, ) arguments.update(options) if 'EVE_SETTINGS' not in os.environ: os.environ['EVE_SETTINGS'] = EVE_SETTINGS application = Eve( settings=EVE_SETTINGS, # auth=TokenBasedAuth, ) application.root_path = ROOT_PATH with application.app_context(): loader.init() return application.run(**arguments) if __name__ == "__main__": exit(runner())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 19416, 18878, 4226, 198, 198, 40786, 15678, 11, 48191, 11, 2644, 198, 198, 37811, 198, 11748, 28686, 1...
2.298405
439
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2019-01-18 17:16 from __future__ import unicode_literals 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, 17, 319, 13130, 12, 486, 12, 1507, 1596, 25, 1433, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.73913
69
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import random from util.util import pad, detect_aes_ecb, generate_key, ammend_plaintext, encrypt_random # Chosen plaintext plaintext = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" # Generate data and encrypt plaintext key = generate_key() plaintext = pad(ammend_plaintext(plaintext), 16) ciphertext = encrypt_random(key, plaintext) # Detect AES in ECB mode detect = detect_aes_ecb(ciphertext) # Print answer print("Plaintext: " + str(plaintext, 'latin-1')) print("Ciphertext: " + str(ciphertext, 'latin-1')) if (detect[1] == 6): print("Guess: ECB without CBC mode") elif (detect[1] == 4): print("Guess: ECB with CBC mode") else: raise Exception
[ 11748, 25064, 11, 28686, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 35514, 198, 11748, 4738, 198, 6738, 7736, 13,...
2.809701
268
# Copyright (c) 2017 Uber Technologies, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Initializes an UberRidesClient with OAuth 2.0 Credentials. This example demonstrates how to get an access token through the OAuth 2.0 Authorization Code Grant and use credentials to create an UberRidesClient. To run this example: (1) Set your app credentials in config.driver.yaml (2) Run `python authorize_driver.py` (3) A success message will print, 'Hello {YOUR_NAME}' (4) User OAuth 2.0 credentials are recorded in 'oauth_driver_session_store.yaml' """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import input from yaml import safe_dump from example import utils # NOQA from example.utils import fail_print from example.utils import response_print from example.utils import success_print from example.utils import import_app_credentials from uber_rides.auth import AuthorizationCodeGrant from uber_rides.client import UberRidesClient from uber_rides.errors import ClientError from uber_rides.errors import ServerError from uber_rides.errors import UberIllegalState def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) Filename to store OAuth 2.0 Credentials. Returns (UberRidesClient) An UberRidesClient with OAuth 2.0 Credentials. """ auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() login_message = 'Login as a driver and grant access by going to:\n\n{}\n' login_message = login_message.format(auth_url) response_print(login_message) redirect_url = 'Copy the URL you are redirected to and paste here:\n\n' result = input(redirect_url).strip() try: session = auth_flow.get_session(result) except (ClientError, UberIllegalState) as error: fail_print(error) return credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'redirect_url': credential.redirect_url, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } with open(storage_filename, 'w') as yaml_file: yaml_file.write(safe_dump(credential_data, default_flow_style=False)) return UberRidesClient(session, sandbox_mode=True) def hello_user(api_client): """Use an authorized client to fetch and print profile information. Parameters api_client (UberRidesClient) An UberRidesClient with OAuth 2.0 credentials. """ try: response = api_client.get_driver_profile() except (ClientError, ServerError) as error: fail_print(error) return else: profile = response.json first_name = profile.get('first_name') last_name = profile.get('last_name') email = profile.get('email') message = 'Hello, {} {}. Successfully granted access token to {}.' message = message.format(first_name, last_name, email) success_print(message) success_print(profile) success_print('---') response = api_client.get_driver_trips() trips = response.json success_print(trips) success_print('---') response = api_client.get_driver_payments() payments = response.json success_print(payments) if __name__ == '__main__': """Run the example. Get an access token through the OAuth 2.0 Authorization Code Grant and use credentials to create an UberRidesClient. """ credentials = import_app_credentials('config.driver.yaml') api_client = authorization_code_grant_flow( credentials, 'oauth_driver_session_store.yaml', ) hello_user(api_client)
[ 2, 15069, 357, 66, 8, 2177, 12024, 21852, 11, 3457, 13, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423...
2.908849
1,876
# -*- coding: utf-8 -*- """ A data clustering widget for the Orange3. This is a data clustering widget for Orange3, that implements the OPTICS algorithm. OPTICS stands for "Ordering Points To Identify the Clustering Structure". This is a very useful algorithm for clustering data when the dataset is unlabeled with Non-flat geometry or when it has uneven cluster sizes or variable cluster density. The package used is called "sklearn". Source: https://scikit-learn.org/stable/index.html To run the addon, just install it using 'pip install -e .' from its package folder. Don't forget to first activate the orange environment. __author__ = Panagiotis Papadopoulos __date__ = Feb 2020 __version__ = 0.1.0 __type__ = Orange Addon __platform__ = Windows (Orange enviroment) __email__ = 'Panagiotis Papadopoulos' <panatronic@outlook.com> __status__ = Dev """ import numpy as np from AnyQt.QtCore import Qt from AnyQt.QtGui import QColor from Orange.widgets import widget, gui from Orange.widgets import settings from Orange.widgets.widget import Msg from Orange.widgets.utils.signals import Input, Output from Orange.widgets.utils.widgetpreview import WidgetPreview from Orange.widgets.utils.slidergraph import SliderGraph from Orange.data import Table, Domain, DiscreteVariable from pyqtgraph import mkPen from pyqtgraph.functions import intColor from sklearn.cluster import OPTICS from sklearn.neighbors import VALID_METRICS """ OPTICS Parameters class sklearn.cluster.OPTICS( * min_samples=5, {default=5 or int > 1}, title: Min samples max_eps=inf, {default=np.inf}, not changed * metric='minkowski', {default='minkowski' or [1]}, title: Metric p=2, {default=2}, not changed cluster_method='xi', {default='xi'}, not changed eps=None, {default=None}, not changed * xi=0.05, {default=0.05 or float, between 0 and 1}, title: Minimum steepness predecessor_correction=True, {default=True}, not changed min_cluster_size=None, {default=None}, not changed * algorithm='auto', {default=auto or ball_tree, kd_tree, brute, auto}, title: Algorithm for nearest neighbors: leaf_size=30, {default=30}, not changed n_jobs=None, {default=None}, not changed ) [1] Valid values for metric are: from scikit-learn: [cityblock, cosine, euclidean, l1, l2, manhattan] from scipy.spatial.distance: [braycurtis, canberra, chebyshev, correlation, dice, hamming, jaccard, kulsinski, mahalanobis, minkowski, rogerstanimoto, russellrao, seuclidean, sokalmichener, sokalsneath, sqeuclidean, yule] See the documentation for scipy.spatial.distance for details on these metrics. """ OPTICS_METRICS = [ ("cityblock", "cityblock"), ("cosine", "cosine"), ("euclidean", "euclidean"), ("l1", "l1"), ("l2", "l2"), ("manhattan", "manhattan"), ("braycurtis", "braycurtis"), ("canberra", "canberra"), ("chebyshev", "chebyshev"), ("correlation", "correlation"), ("hamming", "hamming"), ("minkowski", "minkowski"), ("sqeuclidean", "sqeuclidean"), ] OPTICS_ALGORITHM = [ ("Auto","auto"), ("Ball Tree","ball_tree"), ("kd Tree","kd_tree"), ("Brute","brute"), ] if __name__ == "__main__": WidgetPreview(OPTICS_w).run(Table("iris-imbalanced"))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 317, 1366, 32966, 1586, 26295, 329, 262, 11942, 18, 13, 628, 220, 220, 220, 770, 318, 257, 1366, 32966, 1586, 26295, 329, 11942, 18, 11, 326, 23986, 262, 39852, ...
2.622613
1,309
import json from message_prototypes.exceptions import MissingModelException
[ 11748, 33918, 198, 198, 6738, 3275, 62, 11235, 13567, 13, 1069, 11755, 1330, 25639, 17633, 16922, 628 ]
4.588235
17
# -*- coding: utf-8 -* import pytest from pyleecan.Classes.Circle import Circle from pyleecan.Classes.Segment import Segment from pyleecan.Classes.SurfLine import SurfLine # Configuring the test of is_inside inside_test = list() # Test 1 : checking if a point is inside a circle of radius 1 at 0 + 0j C1 = Circle() inside_test.append({"surf": C1, "Z": 0, "result": True}) # inside inside_test.append({"surf": C1, "Z": 20, "result": False}) # outside inside_test.append({"surf": C1, "Z": 1, "result": False}) # online not OK inside_test.append({"surf": C1, "Z": 1, "if_online": True, "result": True}) # online OK # Test 2 : checking if a point is inside a "C-shape" surface A0 = 0 A1 = 0 + 4j A2 = 3 + 4j A3 = 3 + 3j A4 = 1 + 3j A5 = 1 + 1j A6 = 3 + 1j A7 = 3 line_list1 = list() line_list1.append(Segment(A0, A1)) line_list1.append(Segment(A1, A2)) line_list1.append(Segment(A2, A3)) line_list1.append(Segment(A3, A4)) line_list1.append(Segment(A4, A5)) line_list1.append(Segment(A5, A6)) line_list1.append(Segment(A6, A7)) line_list1.append(Segment(A7, A0)) C2 = SurfLine(line_list=line_list1, point_ref=A0) inside_test.append({"surf": C2, "Z": 0.5 + 2j, "result": True}) # inside inside_test.append({"surf": C2, "Z": 2 + 2j, "result": False}) # outside inside_test.append({"surf": C2, "Z": 2.03, "result": False}) # online not OK inside_test.append( {"surf": C2, "Z": 2.03, "if_online": True, "result": True} ) # online OK if __name__ == "__main__": for test_dict in inside_test: test_is_inside(test_dict)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 201, 198, 201, 198, 11748, 12972, 9288, 201, 198, 6738, 279, 2349, 721, 272, 13, 9487, 274, 13, 31560, 293, 1330, 16291, 201, 198, 6738, 279, 2349, 721, 272, 13, 9487, 274, 13,...
2.256374
706
import time from nitter_scraper import NitterScraper last_tweet_id = None with NitterScraper(port=8008) as nitter: while True: for tweet in nitter.get_tweets("dgnsrekt", pages=1, break_on_tweet_id=last_tweet_id): if tweet.is_pinned is True: continue if tweet.is_retweet is True: continue if tweet.tweet_id != last_tweet_id: print(tweet.json(indent=4)) last_tweet_id = tweet.tweet_id break time.sleep(0.1)
[ 11748, 640, 198, 198, 6738, 299, 1967, 62, 1416, 38545, 1330, 399, 1967, 3351, 38545, 198, 198, 12957, 62, 83, 7277, 62, 312, 796, 6045, 198, 198, 4480, 399, 1967, 3351, 38545, 7, 634, 28, 7410, 23, 8, 355, 299, 1967, 25, 198, 220...
1.915194
283
# Generated by Django 3.1.6 on 2021-02-25 00:50 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 21, 319, 33448, 12, 2999, 12, 1495, 3571, 25, 1120, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14...
3.019231
52
# flake8: noqa from .sampler import Sampler
[ 2, 781, 539, 23, 25, 645, 20402, 198, 198, 6738, 764, 37687, 20053, 1330, 3409, 20053, 198 ]
2.647059
17
from tools.com.alpha import Flow, Path
[ 6738, 4899, 13, 785, 13, 26591, 1330, 27782, 11, 10644, 201, 198, 201, 198 ]
3
14
import argparse import os import subprocess from subprocess import call if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("filename", help="the name of the solidity file") args = parser.parse_args() filename = args.filename cwd = os.getcwd() datadir = os.path.join(cwd, "data") contractsdir = os.path.join(cwd, "contracts") compile_separate()
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 198, 6738, 850, 14681, 1330, 869, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 28100, 1713, 46677...
2.783784
148
import re import joblib from sklearn.ensemble import RandomForestClassifier from typing import List, Tuple # Cleans up a messed up HTML / tabbed raw content into space delimited content # Flattens a list of tuples for (Sender, SenderDomain) into [Sender, SenderDomain] # By right there SHOULD only be a single pair but kept in list just in case! # Even indexes are Sender and odd indexs are SenderDomains # Retrieves a list of [Sender, SenderDomain] and returns domain names only # eg. ['Person', 'Person@Company.com'] # Returns [Company.com] # By right there should only be one entry but kept in list just in case # set list to remove duplicates
[ 11748, 302, 198, 11748, 1693, 8019, 198, 6738, 1341, 35720, 13, 1072, 11306, 1330, 14534, 34605, 9487, 7483, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 198, 198, 2, 3779, 504, 510, 257, 32621, 510, 11532, 1220, 7400, 3077, 8246, 2695...
3.611111
180
import os import sendgrid from sendgrid.helpers.mail import Content, Email, Mail from bs4 import BeautifulSoup
[ 11748, 28686, 198, 11748, 3758, 25928, 198, 6738, 3758, 25928, 13, 16794, 364, 13, 4529, 1330, 14041, 11, 9570, 11, 11099, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 628 ]
3.612903
31
import json
[ 11748, 33918, 201, 198 ]
3.25
4
#!/usr/bin/python3 ## Tommy from botbase import * _frankfurt_st = re.compile(r"Stand:\s*(\d\d?\. *\w+ 20\d\d, \d\d?(?::\d\d)?) Uhr") schedule.append(Task(8, 5, 12, 5, 360, frankfurt, 6412)) if __name__ == '__main__': frankfurt(googlesheets())
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2235, 19919, 198, 6738, 10214, 8692, 1330, 1635, 198, 62, 8310, 962, 29205, 62, 301, 796, 302, 13, 5589, 576, 7, 81, 1, 15480, 7479, 82, 9, 38016, 67, 59, 67, 30, 17405, 1635, 59, 8...
2.121739
115
# Copyright 2013-2018 Aerospike, 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. import signal import commands DEFAULT_TIMEOUT = 5.0 def timeout(timeout): """This decorator takes a timeout parameter in seconds.""" return wrap_function def default_timeout(function): """This simple decorator 'timesout' after DEFAULT_TIMEOUT seconds.""" return call_with_timeout(function) def getstatusoutput(command, timeout=DEFAULT_TIMEOUT): """This is a timeout wrapper aroung getstatusoutput.""" _gso = call_with_timeout(commands.getstatusoutput, timeout) try: return _gso(command) except TimeoutException: return (-1, "The command '%s' timed-out after %i seconds." % (command, timeout))
[ 2, 15069, 2211, 12, 7908, 15781, 2117, 522, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 1378...
3.372603
365
"""from django.contrib import admin from .models import DemoModel admin.site.register(DemoModel)"""
[ 37811, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 34588, 17633, 198, 198, 28482, 13, 15654, 13, 30238, 7, 11522, 78, 17633, 8, 37811, 198 ]
3.366667
30
import lanelines from compgraph import CompGraph, CompGraphRunner import numpy as np import cv2 func_dict = { 'grayscale': lanelines.grayscale, 'get_image_shape': lambda im : im.shape, 'canny': lanelines.canny, 'define_lanes_region': lanelines.define_lanes_region, 'apply_region_mask': lanelines.apply_region_mask, 'gaussian_blur': lanelines.gaussian_blur, 'hough_lines': lanelines.find_hough_lines, 'compute_line_tangents': lanelines.compute_line_tangents, 'extend_lines': lanelines.extend_lane_lines_grouped_by_slopes, 'average_endpoints_left': lanelines.average_lines_endpoints, 'average_endpoints_right': lanelines.average_lines_endpoints } func_io = { 'grayscale': ('image', 'image_gray'), 'get_image_shape': ('image_gray', ('n_rows', 'n_cols')), 'define_lanes_region': ( ('n_rows', 'n_cols', 'x_from', 'x_to', 'y_lim', 'left_offset', 'right_offset'), 'region_vertices' ), 'gaussian_blur': (('image_gray', 'blur_kernel'), 'blurred_image'), 'canny': (('blurred_image', 'canny_lo', 'canny_hi'), 'image_canny'), 'apply_region_mask': (('image_canny', 'region_vertices'), 'masked_image'), 'hough_lines': (('masked_image', 'rho', 'theta', 'hough_threshold', 'min_line_length', 'max_line_gap'), 'lines'), 'compute_line_tangents': ('lines', 'tangents'), 'extend_lines': (('lines', 'tangents', 'y_lim', 'n_rows', 'abs_slope_threshold'), ('extended_lines_left', 'extended_lines_right')), 'average_endpoints_left': ('extended_lines_left', 'avg_line_left'), 'average_endpoints_right': ('extended_lines_right', 'avg_line_right') } computational_graph = CompGraph(func_dict, func_io) parameters = { 'x_from': 560, 'x_to': 710, 'y_lim': 450, 'left_offset': 50, 'right_offset': 0, 'blur_kernel': 11, 'canny_lo': 70, 'canny_hi': 200, 'rho': 1, 'theta': np.pi/180, 'hough_threshold': 20, 'min_line_length': 7, 'max_line_gap': 1, 'abs_slope_threshold': 0.2 }
[ 11748, 26992, 20655, 198, 6738, 552, 34960, 1330, 3082, 37065, 11, 3082, 37065, 49493, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 628, 198, 20786, 62, 11600, 796, 1391, 198, 220, 220, 220, 705, 2164, 592, 38765, 10354,...
2.32948
865
import random from random import Random r = Random() f = open("extra_tests.txt", "w+") f.write("new int") c = 2 for _ in range(64): c = write_test_line(f, r, c, 0) c = write_test_line(f, r, c, 1) for _ in range(128): c = write_test_line(f, r, c, 0) c = write_test_line(f, r, c, 1) for _ in range(512): c = write_test_line(f, r, c, 5) for _ in range(20): c = write_insert_ordered_line(f, r, c) c = write_test_line(f, r, c, 1) for _ in range(20): c = write_test_line(f, r, c, 2, 2) c = write_insert_ordered_line(f, r, c) for _ in range(32): c = write_test_line(f, r, c, 2, 1) for _ in range(10): c = write_find_line(f, r, c) for _ in range(10): c = write_remove_value_line(f, r, c) c = write_test_line(f, r, c, 1) for _ in range(32): c = write_insert_ordered_line(f, r, c) for _ in range(10): c = write_find_line(f, r, c) for _ in range(10): c = write_remove_value_line(f, r, c) for _ in range(32): c = write_test_line(f, r, c, 2, 2) for _ in range(10): c = write_find_line(f, r, c) for _ in range(10): c = write_remove_value_line(f, r, c) f.close()
[ 198, 11748, 4738, 198, 6738, 4738, 1330, 14534, 198, 198, 81, 796, 14534, 3419, 198, 198, 69, 796, 1280, 7203, 26086, 62, 41989, 13, 14116, 1600, 366, 86, 10, 4943, 198, 198, 69, 13, 13564, 7203, 3605, 493, 4943, 198, 198, 66, 796, ...
2.063985
547
# LSTM(GRU) : KODEX200 (2010 ~ ) . # KODEX200 , 10, 40 10 . # 20 (step = 20) , . # ?? # # 2018.11.22, () # -------------------------------------------------------------------------- import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import pandas as pd from MyUtil import YahooData nInput = 3 nOutput = 3 nStep = 20 nNeuron = 50 # 2 . # return : xBatch - RNN # yBatch - RNN # # step = 2, n = 3 , # xData = [[1,2,3], [4,5,6], [7,8,9], [10,11,12], ...] # xBatch = [[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]], ...] # yBatch = [[[4,5,6], [7,8,9]], [[10,11,12], [13,14,15]], ...] # #df = YahooData.getStockDataYahoo('^KS11', start='2007-01-01') df = pd.read_csv('StockData/^KS11.csv', index_col=0, parse_dates=True) df = pd.DataFrame(df['Close']) df['ma_10'] = pd.DataFrame(df['Close']).rolling(window=10).mean() df['ma_40'] = pd.DataFrame(df['Close']).rolling(window=40).mean() df = df.dropna() df = (df - df.mean()) / df.std() # . data = np.array(df) xBatch, yBatch = createTrainData(data, nStep) # RNN (Wx, Wh). xBatch RNN . tf.reset_default_graph() x = tf.placeholder(tf.float32, [None, nStep, nInput]) rnn = tf.nn.rnn_cell.LSTMCell(nNeuron) #rnn = tf.nn.rnn_cell.GRUCell(nNeuron) output, state = tf.nn.dynamic_rnn(rnn, x, dtype=tf.float32) # RNN 3 y feed-forward network . (Wy) y = tf.placeholder(tf.float32, [None, nStep, nOutput]) inFC = tf.reshape(output, [-1, nNeuron]) fc1 = tf.contrib.layers.fully_connected(inputs=inFC, num_outputs=nNeuron) predY = tf.contrib.layers.fully_connected(inputs=fc1, num_outputs=nOutput, activation_fn=None) predY = tf.reshape(predY, [-1, nStep, nOutput]) # Mean square error (MSE) Loss . xBatch yBatch . loss = tf.reduce_sum(tf.square(predY - y)) optimizer = tf.train.AdamOptimizer(learning_rate=0.001) minLoss = optimizer.minimize(loss) # . . (Wx, Wh, Wy ) sess = tf.Session() sess.run(tf.global_variables_initializer()) lossHist = [] for i in range(300): sess.run(minLoss, feed_dict={x: xBatch, y: yBatch}) if i % 5 == 0: ploss = sess.run(loss, feed_dict={x: xBatch, y: yBatch}) lossHist.append(ploss) print(i, "\tLoss:", ploss) # 10 . 1 , 2 . # 10 . nFuture = 10 if len(data) > 100: lastData = np.copy(data[-100:]) # 100 else: lastData = np.copy(data) dx = np.copy(lastData) estimate = [dx[-1]] for i in range(nFuture): # nStep px = dx[-nStep:,] px = np.reshape(px, (1, nStep, nInput)) # . yHat = sess.run(predY, feed_dict={x: px})[0][-1] # estimate.append(yHat) # dx = np.vstack([dx, yHat]) # Loss history plt.figure(figsize=(8, 3)) plt.plot(lossHist, color='red') plt.title("Loss History") plt.xlabel("epoch") plt.ylabel("loss") plt.show() # . plt.figure(figsize=(8, 3)) plt.plot(df['Close'], color='red') plt.plot(df['ma_10'], color='blue') plt.plot(df['ma_40'], color='green') plt.title("KODEX-200 stock price") plt.show() # CLOSE = 0 # estimate = np.array(estimate) ax1 = np.arange(1, len(lastData[:, CLOSE]) + 1) ax2 = np.arange(len(lastData), len(lastData) + len(estimate)) plt.figure(figsize=(8, 3)) plt.plot(ax1, lastData[:, CLOSE], 'b-o', color='blue', markersize=4, label='Stock price', linewidth=1) plt.plot(ax2, estimate[:, CLOSE], 'b-o', color='red', markersize=4, label='Estimate') plt.axvline(x=ax1[-1], linestyle='dashed', linewidth=1) plt.legend() plt.title("KODEX-200 prediction") plt.show()
[ 2, 406, 2257, 44, 7, 10761, 52, 8, 220, 1058, 509, 3727, 6369, 2167, 220, 357, 10333, 5299, 1267, 220, 764, 198, 2, 509, 3727, 6369, 2167, 837, 838, 11, 2319, 220, 220, 220, 838, 220, 220, 220, 764, 198, 2, 220, 1160, 357, 9662,...
2.105326
1,671
"""media.py: Module for movie_trailer_website, contains Movie class""" import webbrowser import urllib import json
[ 37811, 11431, 13, 9078, 25, 19937, 329, 3807, 62, 9535, 5329, 62, 732, 12485, 11, 4909, 15875, 1398, 37811, 198, 198, 11748, 3992, 40259, 198, 11748, 2956, 297, 571, 198, 11748, 33918, 628 ]
3.545455
33
""" A collection of useful functions for manipulating/encoding pandas dataframes for data science. """
[ 37811, 198, 32, 4947, 286, 4465, 5499, 329, 29349, 14, 12685, 7656, 19798, 292, 1366, 37805, 329, 1366, 3783, 13, 198, 37811, 198 ]
4.478261
23
import torch import torchvision import torchvision.transforms as transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import numpy as np from model_utils import * # Creating an array of `t` values for the 7 intermediate frames between # reference frames I0 and I1. t = np.linspace(0.125, 0.875, 7) def getFlowCoeff (indices, device): """ Gets flow coefficients used for calculating intermediate optical flows from optical flows between I0 and I1: F_0_1 and F_1_0. F_t_0 = C00 x F_0_1 + C01 x F_1_0 F_t_1 = C10 x F_0_1 + C11 x F_1_0 where, C00 = -(1 - t) x t C01 = t x t C10 = (1 - t) x (1 - t) C11 = -t x (1 - t) Parameters ---------- indices : tensor indices corresponding to the intermediate frame positions of all samples in the batch. device : device computation device (cpu/cuda). Returns ------- tensor coefficients C00, C01, C10, C11. """ # Convert indices tensor to numpy array ind = indices.detach().numpy() C11 = C00 = - (1 - (t[ind])) * (t[ind]) C01 = (t[ind]) * (t[ind]) C10 = (1 - (t[ind])) * (1 - (t[ind])) return torch.Tensor(C00)[None, None, None, :].permute(3, 0, 1, 2).to(device), torch.Tensor(C01)[None, None, None, :].permute(3, 0, 1, 2).to(device), torch.Tensor(C10)[None, None, None, :].permute(3, 0, 1, 2).to(device), torch.Tensor(C11)[None, None, None, :].permute(3, 0, 1, 2).to(device) def getWarpCoeff (indices, device): """ Gets coefficients used for calculating final intermediate frame `It_gen` from backwarped images using flows F_t_0 and F_t_1. It_gen = (C0 x V_t_0 x g_I_0_F_t_0 + C1 x V_t_1 x g_I_1_F_t_1) / (C0 x V_t_0 + C1 x V_t_1) where, C0 = 1 - t C1 = t V_t_0, V_t_1 --> visibility maps g_I_0_F_t_0, g_I_1_F_t_1 --> backwarped intermediate frames Parameters ---------- indices : tensor indices corresponding to the intermediate frame positions of all samples in the batch. device : device computation device (cpu/cuda). Returns ------- tensor coefficients C0 and C1. """ # Convert indices tensor to numpy array ind = indices.detach().numpy() C0 = 1 - t[ind] C1 = t[ind] return torch.Tensor(C0)[None, None, None, :].permute(3, 0, 1, 2).to(device), torch.Tensor(C1)[None, None, None, :].permute(3, 0, 1, 2).to(device)
[ 11748, 28034, 198, 11748, 28034, 10178, 198, 11748, 28034, 10178, 13, 7645, 23914, 355, 31408, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, ...
2.259127
1,123
# -*- coding: utf-8 -*- """ In this file are all the needed functions to calculate an adaptive fractionation treatment plan. The value_eval and the result_calc function are the only ones that should be used This file requires all sparing factors to be known, therefore, it isnt suited to do active treatment planning but to analyze patient data. value_eval and result_calc_BEDNT are the most essential codes. The results from value_eval can be used to calculate a treatment plan with result_calc_BEDNT. The optimal policies for each fraction can be extracted manually(pol4 = first fraction, first index in pol is the last fraction and the last index is the first fraction). but one must know what index represents which sparing factor Note: This file does not assume all sparing factors to be known at the start, but simulates the treatment planning as if we would get a new sparing factor at each fraction! This program uses a discrete state space and does not interpolate between states. Therefore, it is less precise than the interpolation programs """ import numpy as np from scipy.stats import truncnorm import time from scipy.stats import invgamma def get_truncated_normal(mean=0, sd=1, low=0, upp=10): '''produces a truncated normal distribution''' return truncnorm((low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd) def std_calc(measured_data,alpha,beta): '''calculates the most likely standard deviation for a list of k sparing factors and an inverse-gamma conjugate prior measured_data: list/array with k sparing factors alpha: shape of inverse-gamma distribution beta: scale of inverse-gamme distrinbution return: most likely std based on the measured data and inverse-gamma prior''' n = len(measured_data) var_values = np.arange(0.00001,0.25,0.00001) likelihood_values = np.zeros(len(var_values)) for index,value in enumerate(var_values): likelihood_values[index] = value**(-alpha-1)/value**(n/2)*np.exp(-beta/value)*np.exp(-np.var(measured_data)*n/(2*value)) std = (np.sqrt(var_values[np.argmax(likelihood_values)])) return std def distribution_update(sparing_factors, alpha, beta): '''produces the updated probability distribution for each fraction based on Variance prior sparing_factors: list/array of k spraring factors alpha: shape of inverse-gamma distribution beta: scale of inverse-gamme distrinbution return: k-1 dimensional mean and std arrays starting from the second sparing factor (index 1) ''' means = np.zeros(len(sparing_factors)) stds = np.zeros(len(sparing_factors)) for i in range(len(sparing_factors)): means[i] = np.mean(sparing_factors[:(i+1)]) stds[i] = std_calc(sparing_factors[:(i+1)],alpha,beta) means = np.delete(means,0) stds = np.delete(stds,0) #we get rid of the first value as it is only the planning value and not used in a fraction return [means,stds] def updated_distribution_calc(data,sparing_factors): '''calculates the updated distribution based on prior data that is used to setup an inverse gamma distribution data shape: nxk where n is the amount of patients and k the amount of sparingfactors per patient sparing_factors shape: list/array with k entries with the first sparing factor being the planning sparing factor, therefore not being included in the treatment return: updated means and stds for k-1 fractions.''' variances = data.var(axis = 1) alpha,loc,beta = invgamma.fit(variances, floc = 0) #here beta is the scale parameter [means,stds] = distribution_update(sparing_factors,alpha,beta) return[means,stds] def probdistributions(means,stds): '''produces the truncated normal distribution for several means and standard deviations means: list/array of n means stds: list/array of n standard deviations return: n probability distributions for values [0.01,1.40]''' distributions = np.zeros(141*len(means)).reshape(len(means),141) for i in range(len(means)): X = get_truncated_normal(means[i], stds[i], low=0, upp=1.4) for index,value in enumerate(np.arange(0,1.41,0.01)): distributions[i][index] = X.cdf(value+0.004999999999999999999)-X.cdf(value-0.005) return distributions def value_eval(sparing_factors,data,abt = 10,abn = 3,bound = 90,riskfactor = 0): '''calculates the best policy for a list of k sparing factors with k-1 fractions based on a dynamic programming algorithm. Estimation of the probability distribution is based on prior patient data sparing_factors: list/array of k sparing factors. A planning sparing factor is necessary! data: nxk dimensional data of n prior patients with k sparing factors. abt: alpha beta ratio of tumor abn: alpha beta ratio of Organ at risk bound: upper limit of BED in OAR riskfactor: "risk reducing" factor of zero is a full adaptive fractionation algorithm while a sparing factor of 0.1 slightly forces the algorithm to stay close to the 6Gy per fraction plan. a risk factor of 1 results in a 6Gy per fraction plan. return: Values: a sparing_factor-2 x BEDT x sf dimensional matrix with the value of each BEDT/sf state Values4: Values of the first fraction policy: a sparing_factor-2 x BEDT x sf dimensional matrix with the policy of each BEDT/sf state. fourth index = first fraction, first index = last fraction policy4: policy of the first fraction''' sf= np.arange(0,1.41,0.01) #list of all possible sparing factors BEDT = np.arange(0,90.3,0.1) #list of all possible Biological effective doses Values = np.zeros(len(BEDT)*len(sf)*4).reshape(4,len(BEDT),len(sf)) #2d values list with first indice being the BED and second being the sf actionspace = np.arange(0,22.4,0.1) #list of all possible dose actions [means,stds] =updated_distribution_calc(data,sparing_factors) distributions = probdistributions(means,stds) policy = np.zeros((4,len(BEDT),len(sf))) upperbound = 90.2 start = time.time() #here we add the calculation of the distance to the standard treatment useless,calculator = np.meshgrid(np.zeros(len(actionspace)),sf) #calculator is matrix that has the correct sparing factors actionspace_expand,useless = np.meshgrid(actionspace,sf) risk_penalty = abs(6/calculator-actionspace_expand) delivered_doses = np.round(BED_calc(sf,abn,actionspace),1) BEDT_rew = BED_calc(1, abt,actionspace) #this is the reward for the dose deposited inside the normal tissue. BEDT_transformed, meaningless = np.meshgrid(BEDT_rew,np.zeros(len(sf))) risk_penalty[0] = risk_penalty[1] for update_loop in range (0,5): prob = distributions[update_loop] for state in range(0,5-update_loop): #We have five fractionations with 2 special cases 0 and 4 print(str(state+1) +' loop done') if state == 4: #first state with no prior dose delivered so we dont loop through BEDT future_bed = delivered_doses future_bed[future_bed > upperbound] = upperbound #any dose surpassing 95 is set to 95. Furthermore, 95 will be penalized so strong that the program avoids it at all costs. (95 is basically the upper bound and can be adapted) future_values_prob = (Values[state-1][(future_bed*10).astype(int)]*prob).sum(axis = 2) #in this array are all future values multiplied with the probability of getting there. shape = sparing factors x actionspace penalties = np.zeros(future_bed.shape) penalties[future_bed > bound] = -(future_bed[future_bed > bound]-bound)*5 Vs = future_values_prob + BEDT_transformed + penalties - risk_penalty*riskfactor policy4 = Vs.argmax(axis=1) Values4 = Vs.max(axis=1) else: future_values_prob_all = (Values[state-1]*prob).sum(axis = 1) for bed in range(len(BEDT)): #this and the next for loop allow us to loop through all states future_bed = delivered_doses + bed/10 future_bed[future_bed > upperbound] = upperbound #any dose surpassing 95 is set to 95. if state == 0: #last state no more further values to add penalties = np.zeros(future_bed.shape) penalties[future_bed > bound] = -(future_bed[future_bed > bound]-bound)*5 penalties[future_bed == upperbound] = -10000 #here we produced the penalties for all the values surpassing the limit Vs = BEDT_transformed + penalties# Value of each sparing factor for each action else: penalties = np.zeros(future_bed.shape) penalties[future_bed == upperbound] = -100 future_values_prob = (future_values_prob_all[(future_bed*10).astype(int)])#in this array are all future values multiplied with the probability of getting there. shape = sparing factors x actionspace Vs = future_values_prob + BEDT_transformed + penalties - risk_penalty*riskfactor best_action = Vs.argmax(axis=1) valer = Vs.max(axis=1) policy[state][bed] = best_action Values[state][bed] = valer end = time.time() print('time elapsed = ' +str(end - start)) return [Values,policy,Values4,policy4] def result_calc_BEDNT(pol4,pol,sparing_factors,abt = 10,abn = 3): #this function calculates the fractionation plan according to the reinforcement learning '''in this function gives the treatment plan for a set of sparing factors based on the sparing factors that have been used to calculate the optimal policy the pol4 and pol matrices are the ones that are returnedin the value_eval function pol4: first fraction policy pol: second - fifth fraction policy sparing_factors: sparing factors that should be used to make a plan. list starting from first fraction''' actionspace = np.arange(0,22.4,0.1) #list of all possible dose actions total_bedt = BED_calc0(actionspace[pol4[round(sparing_factors[0]*100)]],abt) total_bednt = BED_calc0(actionspace[pol4[round(sparing_factors[0]*100)]],abn,sparing_factors[0]) print('fraction 1 dose delivered: ',actionspace[pol4[round(sparing_factors[0]*100)]]) print('total accumulated biological effective dose in tumor; fraction 1 = ',round(total_bedt,1)) print('total accumulated biological effective dose in normal tissue; fraction 1 = ',round(total_bednt,1)) for index,fraction in enumerate(range(3,-1,-1)): if fraction == 0: dose_action = (-sparing_factors[index+1]+np.sqrt(sparing_factors[index+1]**2+4*sparing_factors[index+1]**2*(90-total_bednt)/abn))/(2*sparing_factors[index+1]**2/abn) else: dose_action = actionspace[pol[fraction][(round(total_bednt,1)*10).astype(int)][round(sparing_factors[index+1]*100)].astype(int)] dose_delivered = BED_calc0(dose_action,abt) total_bedt += dose_delivered total_bednt += BED_calc0(dose_action,abn,sparing_factors[index+1]) print('fraction ', index+2, 'dose delivered: ', round(dose_action,1)) print('total accumulated dose in tumor; fraction ', index+2, '=', round(total_bedt,1)) print('total accumulated dose in normal tissue; fraction ', index+2, '=', round(total_bednt,1))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 818, 428, 2393, 389, 477, 262, 2622, 5499, 284, 15284, 281, 29605, 13390, 341, 3513, 1410, 13, 383, 1988, 62, 18206, 290, 262, 1255, 62, 9948, 66...
2.664616
4,389
from django.contrib import admin # Register your models here. from ltc.base.models import Project, Test, Configuration # Register your models here. admin.site.register(Project) admin.site.register(Test) admin.site.register(Configuration)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 6738, 300, 23047, 13, 8692, 13, 27530, 1330, 4935, 11, 6208, 11, 28373, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 28482, 13, 15654, 13, ...
3.636364
66
import sys from PySide2.QtWidgets import QApplication from PySide2.QtGui import QColor from pivy import quarter, coin, graphics, utils def main(): app = QApplication(sys.argv) utils.addMarkerFromSvg("test.svg", "CUSTOM_MARKER", 40) viewer = quarter.QuarterWidget() root = graphics.InteractionSeparator(viewer.sorendermanager) root.pick_radius = 40 m1 = ConnectionMarker([[-1, -1, -1]]) m2 = ConnectionMarker([[-1, 1, -1]]) m3 = ConnectionMarker([[ 1, 1, -1]]) m4 = ConnectionMarker([[ 1, -1, -1]]) m5 = ConnectionMarker([[-1, -1, 1]]) m6 = ConnectionMarker([[-1, 1, 1]]) m7 = ConnectionMarker([[ 1, 1, 1]]) m8 = ConnectionMarker([[ 1, -1, 1]]) points = [m1, m2, m3, m4, m5, m6, m7, m8] l01 = ConnectionLine([m1, m2]) l02 = ConnectionLine([m2, m3]) l03 = ConnectionLine([m3, m4]) l04 = ConnectionLine([m4, m1]) l05 = ConnectionLine([m5, m6]) l06 = ConnectionLine([m6, m7]) l07 = ConnectionLine([m7, m8]) l08 = ConnectionLine([m8, m5]) l09 = ConnectionLine([m1, m5]) l10 = ConnectionLine([m2, m6]) l11 = ConnectionLine([m3, m7]) l12 = ConnectionLine([m4, m8]) lines = [l01, l02, l03, l04, l05, l06, l07, l08, l09, l10, l11, l12] p1 = ConnectionPolygon([m1, m2, m3, m4]) p2 = ConnectionPolygon([m8, m7, m6, m5]) p3 = ConnectionPolygon([m5, m6, m2, m1]) p4 = ConnectionPolygon([m6, m7, m3, m2]) p5 = ConnectionPolygon([m7, m8, m4, m3]) p6 = ConnectionPolygon([m8, m5, m1, m4]) polygons = [p1, p2, p3, p4, p5, p6] root += points + lines + polygons root.register() viewer.setSceneGraph(root) viewer.setBackgroundColor(QColor(255, 255, 255)) viewer.setWindowTitle("minimal") viewer.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
[ 11748, 25064, 198, 6738, 9485, 24819, 17, 13, 48, 83, 54, 312, 11407, 1330, 1195, 23416, 198, 6738, 9485, 24819, 17, 13, 48, 83, 8205, 72, 1330, 1195, 10258, 198, 6738, 16767, 88, 1330, 3860, 11, 10752, 11, 9382, 11, 3384, 4487, 628...
2.168246
844
""" Functions used in pre-processing of data for the machine learning pipelines. """ import pandas as pd from pandas.api.types import is_scalar from pathlib import Path from sklearn.model_selection import GroupShuffleSplit def concat_annotated(datadir): """ Concatenate all "annotated_df_*_parsed*.pkl" files in `datadir`. The pkl's of the core team should end with "dedup.pkl", i.e. they should be deduplicated by the `parse_annotations.py` script. The ze pkl's need not be deduplicated, as only notes that are not in the annotations of the core team are included. Parameters ---------- datadir: Path path to directory with data Returns ------- DataFrame df of concatenated parsed annotations """ # load core team annotations; pickles are deduplicated during processing annot = pd.concat([pd.read_pickle(fp) for fp in datadir.glob('*_dedup.pkl')], ignore_index=True) # load ze annotations and remove IAA files ze = pd.concat( [pd.read_pickle(fp) for fp in datadir.glob('annotated_df_ze_*.pkl')], ignore_index=True ).query("~NotitieID.isin(@annot.NotitieID)", engine='python') return pd.concat([annot, ze], ignore_index=True) def drop_disregard(df): """ If one token in a note is marked 'disregard', remove the whole note from df. Parameters ---------- df: DataFrame parsed token-level annotations df (created by `parse_annotations.py`) Returns ------- DataFrame df without 'disregard' notes """ df['disregard_note'] = df.groupby('NotitieID').disregard.transform('any') return df.query( "not disregard_note" ).drop(columns=['disregard', 'disregard_note']) def fix_week_14(df): """ For annotations from week 14: - Replace MBW values with `False` - Replace MBW-lvl values with NaN We remove this domain from week 14 since the guidelines for it were changed after this week. Parameters ---------- df: DataFrame parsed token-level annotations df (created by `parse_annotations.py`) Returns ------- DataFrame df without MBW and MBW_lvl labels for week 14 """ df['MBW'] = df.MBW.mask(df.batch == 'week_14', other=False) df['MBW_lvl'] = df.MBW_lvl.mask(df.batch == 'week_14') return df def pad_sen_id(id): """ Add padding zeroes to sen_id. """ note_id, sen_no = id.split('_') return '_'.join([note_id, f"{sen_no:0>4}"]) def anonymize(txt, nlp): """ Replace entities of type PERSON and GPE with 'PERSON', 'GPE'. Return anonymized text and its length. """ doc = nlp(txt) anonym = str(doc) to_repl = {str(ent):ent.label_ for ent in doc.ents if ent.label_ in ['PERSON', 'GPE']} for string, replacement in to_repl.items(): anonym = anonym.replace(string, replacement) return anonym, len(doc) def data_split_groups( df, X_col, y_col, group_col, train_size, ): """ Split data to train / dev / test, while taking into account groups that should stay together. Parameters ---------- df: DataFrame df with the data to split X_col: str name of the column with the data (text) y_col: str name of the column with the gold labels group_col: str name of the column with the groups to take into account when splitting train_size: float proportion of data that should go to the training set Returns ------- train, dev, test: DataFrame's df with train data, df with dev data, df with test data """ # create training set of `train_size` gss = GroupShuffleSplit(n_splits=1, test_size=1-train_size, random_state=19) for train_idx, other_idx in gss.split(df[X_col], df[y_col], groups=df[group_col]): train = df.iloc[train_idx] other = df.iloc[other_idx] # the non-train data is split 50/50 into development and test gss = GroupShuffleSplit(n_splits=1, test_size=0.5, random_state=19) for dev_idx, test_idx in gss.split(other[X_col], other[y_col], groups=other[group_col]): dev = other.iloc[dev_idx] test = other.iloc[test_idx] return train, dev, test def flatten_preds_if_necessary(df): """ Flatten predictions if they are a list in a list. This is necessary because of an issue with the predict.py script prior to the update performed on 15-09-2021. """ cols = [col for col in df.columns if 'pred' in col] for col in cols: test = df[col].iloc[0] if is_scalar(test[0]): continue df[col] = df[col].str[0] return df
[ 37811, 198, 24629, 2733, 973, 287, 662, 12, 36948, 286, 1366, 329, 262, 4572, 4673, 31108, 13, 198, 37811, 628, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 19798, 292, 13, 15042, 13, 19199, 1330, 318, 62, 1416, 282, 283, 198, 6...
2.539674
1,840
import numpy as np np.deprecate(1) # E: No overload variant np.deprecate_with_doc(1) # E: incompatible type np.byte_bounds(1) # E: incompatible type np.who(1) # E: incompatible type np.lookfor(None) # E: incompatible type np.safe_eval(None) # E: incompatible type
[ 11748, 299, 32152, 355, 45941, 198, 198, 37659, 13, 10378, 8344, 378, 7, 16, 8, 220, 1303, 412, 25, 1400, 31754, 15304, 198, 198, 37659, 13, 10378, 8344, 378, 62, 4480, 62, 15390, 7, 16, 8, 220, 1303, 412, 25, 27294, 2099, 198, 19...
2.628571
105
import time from colorama import Fore, Back, Style import speech_recognition as sr import os import pyttsx3 import datetime from rich.progress import Progress python = pyttsx3.init("sapi5") # name of the engine is set as Python voices = python.getProperty("voices") #print(voices) python.setProperty("voice", voices[1].id) python.setProperty("rate", 140) def speak(text): """[This function would speak aloud some text provided as parameter] Args: text ([str]): [It is the speech to be spoken] """ python.say(text) python.runAndWait() def greet(g): """Uses the datetime library to generate current time and then greets accordingly. Args: g (str): To decide whether to say hello or good bye """ if g == "start" or g == "s": h = datetime.datetime.now().hour text = '' if h > 12 and h < 17: text = "Hello ! Good Afternoon " elif h < 12 and h > 0: text = "Hello! Good Morning " elif h >= 17 : text = "Hello! Good Evening " text += " I am Python, How may i help you ?" speak(text) elif g == "quit" or g == "end" or g == "over" or g == "e": text = 'Thank you!. Good Bye ! ' speak(text) def hear(): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] Returns: [str]: [Speech of user as a string in English(en - IN)] """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") #time.sleep(0.5) speech = r.record(source, duration = 9) # option #speech = r.listen(source) # convert speech to text try: #print("Recognizing...") recognizing() speech = r.recognize_google(speech) print(speech + "\n") except Exception as exception: print(exception) return "None" return speech def recognizing(): """Uses the Rich library to print a simulates version of "recognizing" by printing a loading bar. """ with Progress() as pr: rec = pr.add_task("[red]Recognizing...", total = 100) while not pr.finished: pr.update(rec, advance = 1.0) time.sleep(0.01) def long_hear(duration_time = 60): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] the difference between the hear() and long_hear() is that - the hear() - records users voice for 9 seconds long_hear() - will record user's voice for the time specified by user. By default, it records for 60 seconds. Returns: [str]: [Speech of user as a string in English(en - IN)] """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") #time.sleep(0.5) speech = r.record(source, duration = duration_time) # option #speech = r.listen(source) # convert speech to text try: print(Fore.RED +"Recognizing...") #recognizing() speech = r.recognize_google(speech) #print(speech + "\n") except Exception as exception: print(exception) return "None" return speech def short_hear(duration_time = 5): """[It will process the speech of user using Google_Speech_Recognizer(recognize_google)] the difference between the hear() and long_hear() is that - the hear() - records users voice for 9 seconds long_hear - will record user's voice for the time specified by user. By default, it records for 60 seconds. Returns: [str]: [Speech of user as a string in English(en - IN)] """ r = sr.Recognizer() """Reconizer is a class which has lot of functions related to Speech i/p and o/p. """ r.pause_threshold = 1 # a pause of more than 1 second will stop the microphone temporarily r.energy_threshold = 300 # python by default sets it to 300. It is the minimum input energy to be considered. r.dynamic_energy_threshold = True # pyhton now can dynamically change the threshold energy with sr.Microphone() as source: # read the audio data from the default microphone print(Fore.RED + "\nListening...") #time.sleep(0.5) speech = r.record(source, duration = duration_time) # option #speech = r.listen(source) # convert speech to text try: print(Fore.RED +"Recognizing...") #recognizing() speech = r.recognize_google(speech) #print(speech + "\n") except Exception as exception: print(exception) return "None" return speech if __name__ == '__main__': # print("Enter your name") # name = hear() # speak("Hello " + name) # greet("s") # greet("e") pass #hear() #recognizing()
[ 11748, 640, 201, 198, 6738, 3124, 1689, 1330, 4558, 11, 5157, 11, 17738, 201, 198, 11748, 4046, 62, 26243, 653, 355, 19677, 201, 198, 11748, 28686, 201, 198, 11748, 12972, 83, 912, 87, 18, 201, 198, 11748, 4818, 8079, 201, 198, 6738, ...
2.39898
2,549
# Generated by Django 3.1.7 on 2021-05-06 23:57 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 22, 319, 33448, 12, 2713, 12, 3312, 2242, 25, 3553, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
import numpy as np import pandas as pd from scipy import signal,stats from flask import Flask,request,jsonify import json import re import os import data_utils as utils import sklearn.preprocessing as pre configpath=os.path.join(os.path.dirname(__file__),'config.txt') try: config = utils.py_configs(configpath) Signal_SERVER = config["Signal_SERVER"] Signal_PORT = config["Signal_PORT"] except: raise Exception("Configuration error") app = Flask(__name__) if __name__=="__main__": app.run(host=Signal_SERVER, port=int(Signal_PORT))
[ 11748, 299, 32152, 355, 45941, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 6738, 629, 541, 88, 1330, 6737, 11, 34242, 201, 198, 201, 198, 6738, 42903, 1330, 46947, 11, 25927, 11, 17752, 1958, 201, 198, 11748, 33918, 201, 198,...
2.609865
223
import torch import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerTuple from matplotlib.ticker import FormatStrFormatter #from tqdm import tqdm matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 plt.rc('xtick', labelsize=22) # fontsize of the tick labels plt.rc('ytick', labelsize=22) plt.rc('legend', fontsize=25) plt.rc('axes', labelsize=25) plt.rcParams["figure.figsize"] = (7.5, 6) colors = ['lightcoral', 'mediumseagreen', 'darkorange'] def train(model, dataloader, optimizer, criterion, initial, prev_m, device, depth=4): """ train model for alpha for one loop over dataloader """ epoch_loss = 0 model.train() # set model to train mode i = 0 for batch in dataloader: optimizer.zero_grad() bm, cn = batch X = model(bm.to(device), cn.to(device), prev_m[i*dataloader.batch_size:(i+1)*dataloader.batch_size], initial[i*dataloader.batch_size:(i+1)*dataloader.batch_size].to(device)) strategy = model.strategy loss = criterion(X, prev_m[i*dataloader.batch_size:(i+1)*dataloader.batch_size], strategy) loss.backward(retain_graph=True) optimizer.step() epoch_loss += loss.item() i+=1 return epoch_loss/len(dataloader) def train1(model, dataloader, optimizer, criterion, initial, prev_m, device, depth=4): """ train model for alpha for one loop over dataloader """ epoch_loss = 0 model.train() # set model to train mode i = 0 for batch in dataloader: optimizer.zero_grad() bm, cn, typeVec = batch X = model(bm.to(device), cn.to(device), typeVec.to(device), prev_m[i*dataloader.batch_size:(i+1)*dataloader.batch_size], initial[i*dataloader.batch_size:(i+1)*dataloader.batch_size].to(device)) strategy = model.strategy loss = criterion(X, prev_m[i*dataloader.batch_size:(i+1)*dataloader.batch_size], strategy) loss.backward(retain_graph=True) optimizer.step() epoch_loss += loss.item() i+=1 return epoch_loss/len(dataloader) def train2(model, dataloader, optimizer, criterion, initial, prev_m, prev_c, device, depth=4): """ train model for alpha for one loop over dataloader """ epoch_loss = 0 model.train() # set model to train mode i = 0 for batch in dataloader: optimizer.zero_grad() bm, cn, typeVec = batch X = model(bm.to(device), cn.to(device), typeVec.to(device), prev_m[i*dataloader.batch_size:(i+1)*dataloader.batch_size], prev_c[i*dataloader.batch_size:(i+1)*dataloader.batch_size], initial[i*dataloader.batch_size:(i+1)*dataloader.batch_size].to(device)) strategy = model.strategy loss = criterion(X, prev_m[i*dataloader.batch_size:(i+1)*dataloader.batch_size], strategy, prev_c[i*dataloader.batch_size:(i+1)*dataloader.batch_size]) loss.backward(retain_graph=True) optimizer.step() epoch_loss += loss.item() i+=1 return epoch_loss/len(dataloader) def plotSDE(benchmark, predicted, target_addr, title, filename, ylim=None, label1=None, label2=None, legendloc=None): """ input: benchmark -- list[paths] predicted -- list[paths] """ fig = plt.figure() if title: plt.title(title) if ylim: plt.ylim(ylim) t = [i/100 for i in range(101)] c = len(benchmark) lines = [] lines_pred = [] for i in range(c): l, = plt.plot(t, benchmark[i], color=colors[i], ls='-') lines.append(l) for i in range(c): l, = plt.plot(t, predicted[i], color=colors[i], ls='--', marker='.') lines_pred.append(l) if legendloc: plt.legend([tuple(lines), tuple(lines_pred)], [label1, label2], loc=legendloc, ncol=2, handler_map={tuple: HandlerTuple(ndivide=None)}) else: plt.legend([tuple(lines), tuple(lines_pred)], [label1, label2], loc="upper left", ncol=2, handler_map={tuple: HandlerTuple(ndivide=None)}) plt.xlabel(r"time $t$") plt.ylabel(r"$X_t$ and $\widehat{X}_t$") plt.tight_layout() fig.savefig(target_addr+'/'+filename+'.pdf') def plotC(benchmark, predicted, target_addr, title, filename, label1=None, label2=None, ylabel=None): """ input: benchmark -- list[paths] predicted -- list[paths] """ t = [i/100 for i in range(100)] fig = plt.figure() if title: plt.title(title) c = len(benchmark) lines = [] lines_pred = [] for i in range(c): l, = plt.plot(t, benchmark[i], color=colors[i], ls='-') lines.append(l) for i in range(c): l, = plt.plot(t, predicted[i], color=colors[i], ls='--', marker='.') lines_pred.append(l) plt.legend([tuple(lines), tuple(lines_pred)], [label1, label2], loc="upper left",ncol=2, handler_map={tuple: HandlerTuple(ndivide=None)}) plt.xlabel(r"time $t$") if ylabel: plt.ylabel(ylabel) plt.tight_layout() fig.savefig(target_addr+'/'+filename+'.pdf') def plotpi(benchmark, predicted, target_addr, title, filename, ylim = None, label1=None, label2=None, ylabel=None, legendloc = None): """ input: benchmark -- list[paths] predicted -- list[paths] """ fig = plt.figure() if title: plt.title(title) if ylim: plt.ylim(ylim) t = [i/100 for i in range(100)] c = len(benchmark) lines = [] lines_pred = [] for i in range(c): l, = plt.plot(t, benchmark[i], color=colors[i], ls='-') lines.append(l) for i in range(c): l, = plt.plot(t, predicted[i], color=colors[i], ls='--', marker='.') lines_pred.append(l) if legendloc: plt.legend([tuple(lines), tuple(lines_pred)], [label1, label2], loc=legendloc, ncol=2, handler_map={tuple: HandlerTuple(ndivide=None)}) else: plt.legend([tuple(lines), tuple(lines_pred)], [label1, label2], loc="upper left", ncol=2, handler_map={tuple: HandlerTuple(ndivide=None)}) plt.xlabel(r"time $t$") if ylabel: plt.ylabel(ylabel) plt.tight_layout() fig.savefig(target_addr+'/'+filename+'.pdf') def plotmC(benchmark, predicted, target_addr, title, filename, label1=None, label2=None, ylabel=None): """ input: benchmark -- list[paths] predicted -- list[paths] """ N = predicted.shape[1] t = [1/N*i for i in range(N)] fig = plt.figure() if title: plt.title(title) c = len(predicted) lines = [] lines_pred = [] l, = plt.plot(t, benchmark, color='darkgrey', ls='-', linewidth=5) lines.append(l) for i in range(c): l, = plt.plot(t, predicted[i], color=colors[i], ls='--', marker='.') lines_pred.append(l) plt.legend([tuple(lines), tuple(lines_pred)], [label1, label2], loc="upper left", ncol=2, handler_map={tuple: HandlerTuple(ndivide=None)}) plt.xlabel(r"time $t$") if ylabel: plt.ylabel(ylabel) plt.tight_layout() fig.savefig(target_addr+'/'+filename+'.pdf')
[ 198, 198, 11748, 28034, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 7203, 46384, 4943, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 1455, 437, 62, 30281, 1330, 3241...
2.048675
3,698
""" lambdata - a collection of Data Science helper functions """ import pandas as pd import sklearn
[ 37811, 198, 2543, 65, 7890, 532, 257, 4947, 286, 6060, 5800, 31904, 5499, 198, 37811, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 1341, 35720 ]
3.703704
27
""" pyJsConsole wrapper. Anime no Sekai - 2020 """ from .internal.javascript import classes as JSClass console = JSClass._Console() document = JSClass._Document() history = JSClass._History() Math = JSClass._Math() navigator = JSClass._Navigator() screen = JSClass._Screen() window = JSClass._Window() browser = JSClass.BrowserObject ''' import threading from lifeeasy import sleep def reloadElements(): global document global window lastURL = 'data:,' while True: sleep(0.1) try: if JSClass.evaluate('window.location.href') != lastURL: document = JSClass._Document() window = JSClass._Window() lastURL = JSClass.evaluate('window.location.href') except: break thread = threading.Thread(target=reloadElements) thread.daemon = True thread.start() '''
[ 37811, 198, 9078, 49044, 47581, 29908, 13, 628, 27812, 645, 37558, 1872, 532, 12131, 198, 37811, 198, 198, 6738, 764, 32538, 13, 37495, 1330, 6097, 355, 26755, 9487, 198, 198, 41947, 796, 26755, 9487, 13557, 47581, 3419, 198, 22897, 796, ...
2.638298
329
#!/usr/bin/env python """Tests the client file finder action.""" import collections import glob import hashlib import os import platform import shutil import subprocess import unittest import mock import psutil import unittest from grr.client import comms from grr.client.client_actions import file_finder as client_file_finder from grr.lib import flags from grr.lib import rdfvalue from grr.lib import utils from grr.lib.rdfvalues import client as rdf_client from grr.lib.rdfvalues import crypto as rdf_crypto from grr.lib.rdfvalues import file_finder as rdf_file_finder from grr.lib.rdfvalues import standard as rdf_standard from grr.test_lib import client_test_lib from grr.test_lib import test_lib def testLinkStat(self): """Tests resolving symlinks when getting stat entries.""" test_dir = os.path.join(self.temp_dir, "lnk_stat_test") lnk = os.path.join(test_dir, "lnk") lnk_target = os.path.join(test_dir, "lnk_target") os.mkdir(test_dir) with open(lnk_target, "wb") as fd: fd.write("sometext") os.symlink(lnk_target, lnk) paths = [lnk] link_size = os.lstat(lnk).st_size target_size = os.stat(lnk).st_size for expected_size, resolve_links in [(link_size, False), (target_size, True)]: stat_action = rdf_file_finder.FileFinderAction.Stat( resolve_links=resolve_links) results = self._RunFileFinder(paths, stat_action) self.assertEqual(len(results), 1) res = results[0] self.assertEqual(res.stat_entry.st_size, expected_size) class RegexMatcherTest(unittest.TestCase): class LiteralMatcherTest(unittest.TestCase): class ConditionTestMixin(object): # TODO(hanuszczak): Write tests for the metadata change condition. def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 51, 3558, 262, 5456, 2393, 1064, 263, 2223, 526, 15931, 198, 198, 11748, 17268, 198, 11748, 15095, 198, 11748, 12234, 8019, 198, 11748, 28686, 198, 11748, 3859, 198, 11748, 4423, ...
2.511968
752
from django.db import models # Create your models here. from django.db import models from users.models import UserProfile
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13, 628, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 2985, 13, 27530, 1330, 11787, 37046, 628, 628, 198 ]
3.685714
35
Client_ID = "<Your Client ID>" Authorization = "Bearer <Insert Bearer token Here>"
[ 11792, 62, 2389, 796, 33490, 7120, 20985, 4522, 24618, 201, 198, 13838, 1634, 796, 366, 3856, 11258, 1279, 44402, 1355, 11258, 11241, 3423, 24618 ]
3.458333
24
import socket host = 'localhost' # we need to define encode function for converting string to bytes string # this will be use for sending/receiving data via socket encode = lambda text: text.encode() # we need to define deocde function for converting bytes string to string # this will convert bytes string sent/recieved via socket to string decode = lambda byte_text: byte_text.decode() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Simple TCP echo client') parser.add_argument("--port", action="store", dest="port", type=int, required=True) parser.add_argument("--message", action="store", dest="message", required=False) get_args = parser.parse_args() port = get_args.port message = get_args.message if message: echo_client(port, message) else: echo_client(port)
[ 11748, 17802, 198, 198, 4774, 796, 705, 36750, 6, 198, 198, 2, 356, 761, 284, 8160, 37773, 2163, 329, 23202, 4731, 284, 9881, 4731, 198, 2, 220, 428, 481, 307, 779, 329, 7216, 14, 260, 344, 1412, 1366, 2884, 17802, 198, 268, 8189, ...
2.839009
323
from typing import Optional from my_collection.paxos.common import NodeId, Router, ProposalId, Value, PrepareRequest, is_majority, PrepareResponse, \ Proposal, ProposeRequest, ProposeResponse, CODE_OK
[ 6738, 19720, 1330, 32233, 198, 198, 6738, 616, 62, 43681, 13, 79, 897, 418, 13, 11321, 1330, 19081, 7390, 11, 48538, 11, 1041, 40007, 7390, 11, 11052, 11, 43426, 18453, 11, 318, 62, 35839, 11, 43426, 31077, 11, 3467, 198, 220, 220, ...
3.568966
58
# @lc app=leetcode id=749 lang=python3 # # [749] Contain Virus # # https://leetcode.com/problems/contain-virus/description/ # # algorithms # Hard (49.14%) # Likes: 190 # Dislikes: 349 # Total Accepted: 7.5K # Total Submissions: 15.2K # Testcase Example: '[[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]' # # A virus is spreading rapidly, and your task is to quarantine the infected # area by installing walls. # # The world is modeled as an m x n binary grid isInfected, where # isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 # represents cells contaminated with the virus. A wall (and only one wall) can # be installed between any two 4-directionally adjacent cells, on the shared # boundary. # # Every night, the virus spreads to all neighboring cells in all four # directions unless blocked by a wall. Resources are limited. Each day, you can # install walls around only one region (i.e., the affected area (continuous # block of infected cells) that threatens the most uninfected cells the # following night). There will never be a tie. # # Return the number of walls used to quarantine all the infected regions. If # the world will become fully infected, return the number of walls used. # # # Example 1: # # # Input: isInfected = # [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]] # Output: 10 # Explanation: There are 2 contaminated regions. # On the first day, add 5 walls to quarantine the viral region on the left. The # board after the virus spreads is: # # On the second day, add 5 walls to quarantine the viral region on the right. # The virus is fully contained. # # # # Example 2: # # # Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]] # Output: 4 # Explanation: Even though there is only one cell saved, there are 4 walls # built. # Notice that walls are only built on the shared boundary of two different # cells. # # # Example 3: # # # Input: isInfected = # [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]] # Output: 13 # Explanation: The region on the left only builds two new walls. # # # # Constraints: # # # m ==isInfected.length # n ==isInfected[i].length # 1 <= m, n <= 50 # isInfected[i][j] is either 0 or 1. # There is always a contiguous viral region throughout the described process # that will infect strictly more uncontaminated squares in the next round. # # # # @lc tags=hash-table # @lc imports=start from typing_extensions import get_args from imports import * # @lc imports=end # @lc idea=start # # # # @lc idea=end # @lc group= # @lc rank= # @lc code=start # @lc code=end # @lc main=start if __name__ == '__main__': print('Example 1:') print('Input : ') print( 'isInfected =[[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]' ) print('Exception :') print('10') print('Output :') print( str(Solution().containVirus([[0, 1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0]]))) print() print('Example 2:') print('Input : ') print('isInfected = [[1,1,1],[1,0,1],[1,1,1]]') print('Exception :') print('4') print('Output :') print(str(Solution().containVirus([[1, 1, 1], [1, 0, 1], [1, 1, 1]]))) print() print('Example 3:') print('Input : ') print( 'isInfected =[[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]' ) print('Exception :') print('13') print('Output :') print( str(Solution().containVirus([[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0]]))) print() pass # @lc main=end
[ 2, 2488, 44601, 598, 28, 293, 316, 8189, 4686, 28, 22, 2920, 42392, 28, 29412, 18, 198, 2, 198, 2, 685, 22, 2920, 60, 2345, 391, 40584, 198, 2, 198, 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 3642, 391, 12, 8...
2.227979
1,737
import json import os.path import socket import subprocess from pydub import AudioSegment from typing import Dict, List #--------------------- # Low level functions #--------------------- def recv(ip:str, port:int) -> str: conn = connect(ip, port) size = read_size(conn) data = read_data(conn, size) close(conn) return data.decode('utf-8') def send(ip:str, port:int, data:str): conn = connect(ip, port) size = len(data) conn.send(size.to_bytes(4, byteorder='big')) conn.send(data) close(conn) def connect(ip:str, port:int): conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.connect((ip, port)) return conn def close(conn:socket): conn.shutdown(1) conn.close() def read_size(conn:socket): b_size = conn.recv(4) return int.from_bytes(b_size, byteorder='big') def read_data(conn:socket, size:int): chunks = [] bytes_recved = 0 while bytes_recved < size: chunk = conn.recv(size - bytes_recved) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) bytes_recved += len(chunk) return b''.join(chunks) # Path to which OpenJTalk was installed OPENJTALK_BINPATH = '/usr/bin' OPENJTALK_DICPATH = '/var/lib/mecab/dic/open-jtalk/naist-jdic' OPENJTALK_VOICEPATH = '/usr/share/hts-voice/mei/mei_{emotion}.htsvoice' def make_wav(text, speed=1.0, emotion='normal', output_file='__temp.wav', output_dir=os.getcwd()): """ Function to make a wav file using OpenJTalk. args: speed: The speed of speech. (Default: 1.0) emotion: Voice emotion. You can specify 'normal', 'happy', 'bashful', 'angry', or 'sad'. output_file: The file name made by this function. (Default: '__temp.wav') output_dir: The directory of output_file. (Default: Current directory) """ open_jtalk = [OPENJTALK_BINPATH + '/open_jtalk'] mech = ['-x', OPENJTALK_DICPATH] htsvoice = ['-m', OPENJTALK_VOICEPATH.format(emotion=emotion)] speed = ['-r', str(speed)] outwav = ['-ow', os.path.join(output_dir, output_file)] cmd = open_jtalk + mech + htsvoice + speed + outwav c = subprocess.Popen(cmd,stdin=subprocess.PIPE) c.stdin.write(text.encode('utf-8')) c.stdin.close() c.wait() return os.path.join(output_dir, output_file)
[ 11748, 33918, 198, 11748, 28686, 13, 6978, 198, 11748, 17802, 198, 11748, 850, 14681, 198, 6738, 279, 5173, 549, 1330, 13491, 41030, 434, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 628, 198, 198, 2, 19351, 12, 198, 2, 7754, 1241, 549...
2.411523
972
import math main()
[ 11748, 10688, 628, 198, 12417, 3419, 198 ]
3
7
import pandas as pd exa = pd.read_csv('en_dup.csv') exa.loc[exa['label'] =='F', 'label']= 0 exa.loc[exa['label'] =='T', 'label']= 1 exa.loc[exa['label'] =='U', 'label']= 2 #label2, 01 exa0 = exa.loc[exa["label"] == 0] exa1 = exa.loc[exa["label"] == 1] exa = [exa0, exa1] exa = pd.concat(exa) exa.to_csv('train.csv', index=0)
[ 11748, 19798, 292, 355, 279, 67, 628, 198, 1069, 64, 796, 279, 67, 13, 961, 62, 40664, 10786, 268, 62, 646, 79, 13, 40664, 11537, 198, 198, 1069, 64, 13, 17946, 58, 1069, 64, 17816, 18242, 20520, 6624, 6, 37, 3256, 705, 18242, 205...
1.897143
175
""" Reader objects and main class for continuous data (time series) Depending on the storage format, the fitting reader is loaded and takes care of reading the files. .. todo:: unify with analyzer collection! eeg source and analyzer sink node should work together this connection should be documented when tested """ import os import glob import re import numpy import scipy from scipy.io import loadmat import warnings import csv from pySPACE.missions.support.windower import MarkerWindower import logging from pySPACE.resources.dataset_defs.base import BaseDataset from pySPACE.missions.support.WindowerInterface import AbstractStreamReader def parse_float(param): """ Work around to catch colon instead of floating point """ try: return float(param) except ValueError, e: warnings.warn("Failed float conversion from csv file.") try: return float(param.replace(".", "").replace(",", ".")) except: warnings.warn("Secondary attempt at conversion also failed. " + "Treating the value as string and return a 0 as " + "placeholder.") return float(0) def get_csv_handler(file_handler): """Helper function to get a DictReader from csv""" try: dialect = csv.Sniffer().sniff(file_handler.read(2048)) file_handler.seek(0) return csv.DictReader(file_handler, dialect=dialect) except csv.Error, e: warnings.warn(str(e)) csv.register_dialect("excel_space", excel_space) file_handler.seek(0) return csv.DictReader(file_handler, dialect=excel_space) def read(self, nblocks=1): """ Read *nblocks* of the stream and pass it to registers functions """ n = 0 while nblocks == -1 or n < nblocks: if not self.first_entry is None: samples, marker = self.first_entry, self.first_marker self.first_entry = None else: try: samples = self.DictReader.next() except IOError: break if not self.MarkerReader is None: if self.next_marker[0] == self.time_index: marker = self.next_marker[1] self.update_marker() else: marker = "" elif self.marker in samples.keys(): marker = samples.pop(self.marker) else: marker = "" # add marker to dict if not marker == "" and not marker in self._markerids: self._markerids[marker] = self.new_marker_id self._markerNames[self.new_marker_id] = marker self.new_marker_id += 1 # convert marker to array markers = numpy.ones(1)*(-1) if not marker == "": markers[0] = self._markerids[marker] # convert samples to array # special handling of marker in channel names # if the marker is in channelNames, if self.marker in self.channelNames: array_samples = numpy.zeros((len(self.channelNames)-1, 1)) else: array_samples = numpy.zeros((len(self.channelNames), 1)) offset = 0 for index, channel in enumerate(self.channelNames): if self.marker == channel: offset -= 1 else: array_samples[index + offset] = parse_float(samples[channel]) n += 1 for c in self.callbacks: c(array_samples, markers) self.time_index += 1 return n def update_marker(self): """Update `next_marker` from `MarkerReader` information""" try: next = self.MarkerReader.next() self.next_marker = (next["time"], next[self.marker]) except IOError: pass class EDFReader(AbstractStreamReader): """ Read EDF-Data On Instantiation it will automatically assign the value for the blocksize coded in the edf-file to its own attribute 'stdblocksize'. The Feature, that different signals can have different sampling rates is eliminated in a way, that every value of a lower sampled signal is repeated so that it fits the highest sampling rate present in the dataset. This is needed to have the same length for every signal in the returned array. """ def __init__(self, abs_edffile_path): """Initializes module and opens specified file.""" try: self.edffile = open(abs_edffile_path, "r") except IOError as io: warnings.warn(str("failed to open file at [%s]" % abs_edffile_path)) raise io # variables to later overwrite # the properties from AbstractStreamReader self.callbacks = list() self._dSamplingInterval = 0 self._stdblocksize = 0 self._markerids = dict() self._channelNames = dict() self._markerNames = dict() # gains, frequency for each channel self.gains = [] self.phy_min = [] self.dig_min = [] self.frequency = [] self.num_channels = 0 self.num_samples = [] self.edf_plus = False self.edf_header_length = 0 self.annotations = None self.num_samples_anno = None self.timepoint = 0.0 self.generate_meta_data() def read_edf_header(self): """Read edf-header information""" m = dict() m["version"] = self.edffile.read(8) m["subject_id"] = self.edffile.read(80).strip() m["recording_id"] = self.edffile.read(80).strip() m["start_date"] = self.edffile.read(8) m["start_time"] = self.edffile.read(8) m["num_bytes_header"] = int(self.edffile.read(8).strip()) m["edf_c_d"] = self.edffile.read(44).strip() m["num_data_records"] = self.edffile.read(8) m["single_record_duration"] = float(self.edffile.read(8)) m["num_channels"] = int(self.edffile.read(4)) m["channel_names"] = list() for i in range(m["num_channels"]): m["channel_names"].append(self.edffile.read(16).strip()) m["electrode_type"] = list() for i in range(m["num_channels"]): m["electrode_type"].append(self.edffile.read(80).strip()) m["phy_dims"] = list() for i in range(m["num_channels"]): m["phy_dims"].append(self.edffile.read(8).strip()) m["phy_min"] = list() for i in range(m["num_channels"]): m["phy_min"].append(float(self.edffile.read(8).strip())) m["phy_max"] = list() for i in range(m["num_channels"]): m["phy_max"].append(float(self.edffile.read(8).strip())) m["dig_min"] = list() for i in range(m["num_channels"]): m["dig_min"].append(float(self.edffile.read(8).strip())) m["dig_max"] = list() for i in range(m["num_channels"]): m["dig_max"].append(float(self.edffile.read(8).strip())) m["prefilter"] = list() for i in range(m["num_channels"]): m["prefilter"].append(self.edffile.read(80).strip()) m["single_record_num_samples"] = list() for i in range(m["num_channels"]): m["single_record_num_samples"].append(int(self.edffile.read(8).strip())) m["reserved"] = self.edffile.read(32*m["num_channels"]) # check position in file! assert self.edffile.tell() == m["num_bytes_header"], "EDF Header corrupt!" self.edf_header_length = self.edffile.tell() return m def read_edf_data(self): """read one record inside the data section of the edf-file""" edfsignal = [] edfmarkers = numpy.ones(max(self.num_samples))*(-1) # get markers from self.annotations if self.annotations is not None: current_annotations = numpy.where( numpy.array(self.annotations.keys()) < self.timepoint+self.delta)[0] for c in current_annotations: tmarker = self.annotations.keys()[c]-self.timepoint pmarker = int((tmarker/self.delta)*max(self.num_samples)) edfmarkers[pmarker] = self.markerids[self.annotations[self.annotations.keys()[c]]] self.annotations.pop(self.annotations.keys()[c]) self.timepoint += self.delta # in EDF+ the last channel has the annotations, # otherwise it is treated as regular signal channel if self.edf_plus: for i,n in enumerate(self.num_samples): data = self.edffile.read(n*2) if len(data) != n*2: raise IOError channel = numpy.fromstring(data, dtype=numpy.int16).astype(numpy.float32) signal = (channel - self.dig_min[i]) * self.gains[i] + self.phy_min[i] # simple upsampling for integer factors # TODO: may use scipy.resample .. if signal.shape[0] != max(self.num_samples): factor = max(self.num_samples)/signal.shape[0] assert type(factor) == int, str("Signal cannot be upsampled by non-int factor %f!" % factor) signal = signal.repeat(factor, axis=0) edfsignal.append(signal) else: for i,n in enumerate(self.num_samples): data = self.edffile.read(n*2) if len(data) != n*2: raise IOError channel = numpy.fromstring(data, dtype=numpy.int16).astype(numpy.float32) signal = (channel - self.dig_min[i]) * self.gains[i] + self.phy_min[i] # simple upsampling for integer factors # TODO: may use scipy.resample .. if signal.shape[0] != max(self.num_samples): factor = max(self.num_samples)/signal.shape[0] assert type(factor) == int, str("Signal cannot be upsampled by non-int factor %f!" % factor) signal = signal.repeat(factor, axis=0) edfsignal.append(signal) return edfsignal, edfmarkers def parse_annotations(self): """ Parses times and names of the annotations This is done beforehand - annotations are later added to the streamed data. """ self.edffile.seek(self.edf_header_length, os.SEEK_SET) self.annotations = dict() data_bytes_to_skip = sum(self.num_samples)*2 while True: self.edffile.read(data_bytes_to_skip) anno = self.edffile.read(self.num_samples_anno*2) if len(anno) != self.num_samples_anno*2: break anno = anno.strip() marker = anno.split(chr(20)) if marker[2][1:].startswith(chr(0)): continue base = float(marker[0]) offset = float(marker[2][1:]) name = str(marker[3]) self.annotations[base+offset] = name.strip() def generate_meta_data(self): """ Generate the necessary meta data for the windower """ m = self.read_edf_header() # calculate gain for each channel self.gains = [(px-pn)/(dx-dn) for px,pn,dx,dn in zip(m["phy_max"], m["phy_min"], m["dig_max"], m["dig_min"])] self.dig_min = m["dig_min"] self.phy_min = m["phy_min"] self._channelNames = m["channel_names"] self.num_channels = m["num_channels"] self.num_samples = m["single_record_num_samples"] # separate data from annotation channel if m["edf_c_d"] in ["EDF+D", "EDF+C"]: self.edf_plus = True # the annotation channel is called "EDF Annotations" and is the last channel assert "EDF Annotations" == m["channel_names"][-1], "Cannot determine Annotations Channel!" if m["edf_c_d"] in ["EDF+D"]: warnings.warn(str("The file %s contains non-continuous data-segments.\n" "This feature is not supported and may lead to unwanted results!") % self.edffile.name) self.num_samples_anno = self.num_samples.pop() # ignore sampling rate of the annotations channel else : self.edf_plus = False # calculate sampling interval for each channel self.frequency = [ns/m["single_record_duration"] for ns in self.num_samples] self._dSamplingInterval = max(self.frequency) self._stdblocksize = max(self.num_samples) self.delta = self.stdblocksize / max(self.frequency) # generate all marker names and ids self._markerids['null'] = 0 # in edf+ case we can parse them from annotations if self.edf_plus : self.parse_annotations() for i,(t,name) in enumerate(self.annotations.iteritems()): self._markerids[name] = i+1 else: warnings.warn("no marker channel is set - no markers will be streamed!") for s in range(1,256,1): self._markerids[str('S%3d' % s)] = s for r in range(1,256,1): self._markerids[str('R%3d' % r)] = r+256 # generate reverse mapping for k,v in zip(self._markerids.iterkeys(), self._markerids.itervalues()): self._markerNames[v] = k # reset file position to begin of data section self.edffile.seek(self.edf_header_length, os.SEEK_SET) # Register callback function # Forwards block of data until all data is send def read(self, nblocks=1, verbose=False): """read data and call registered callbacks """ n = 0 while nblocks == -1 or n < nblocks: try: samples, markers = self.read_edf_data() except IOError: break n += 1 for c in self.callbacks: c(samples, markers) return n class SETReader(AbstractStreamReader): """ Load eeglab .set format Read eeglab format when the data has not been segmented yet. It is further assumed that the data is stored binary in another file with extension .fdt. Further possibilities are .dat format or to store everything in the .set file. Both is currently not supported. """ def read_set_file(self): setdata = loadmat(self.abs_setfile_path + '.set', appendmat=False) # check if stream data ntrials = setdata['EEG']['trials'][0][0][0][0] assert(ntrials == 1), "Data consists of more than one trial. This is not supported!" # check if data is stored in fdt format datafilename = setdata['EEG']['data'][0][0][0] assert(datafilename.split('.')[-1] == 'fdt'), "Data is not in fdt format!" # collect meta information self._dSamplingInterval = setdata['EEG']['srate'][0][0][0][0] self._channelNames = numpy.hstack(setdata['EEG']['chanlocs'][0][0][ \ 'labels'][0]).astype(numpy.str_).tolist() self.nChannels = setdata['EEG']['nbchan'][0][0][0][0] self.marker_data = numpy.hstack(setdata['EEG']['event'][0][0][ \ 'type'][0]).astype(numpy.str_) for marker in numpy.unique(self.marker_data): marker_number = len(self._markerNames) self._markerNames[marker_number] = marker self._markerids[marker] = marker_number self.marker_times = numpy.hstack(setdata['EEG']['event'][0][0][ \ 'latency'][0]).flatten() self.abs_data_path = os.path.join(os.path.dirname(self.abs_setfile_path), datafilename) def regcallback(self, func): self.callbacks.append(func) def read(self, nblocks=1, verbose=False): readblocks = 0 while (readblocks < nblocks or nblocks == -1): ret, samples, markers = self.read_fdt_data() if ret: for f in self.callbacks: f(samples, markers) else: break readblocks += 1 return readblocks def read_fdt_data(self): if self.fdt_handle == None: return False, None, None num_samples = self.nChannels * self._stdblocksize markers = numpy.zeros(self._stdblocksize) markers.fill(-1) ###### READ DATA FROM FILE ###### try: samples = numpy.fromfile(self.fdt_handle, dtype=numpy.float32, count=num_samples) except MemoryError: # assuming, that a MemoryError only occurs when file is finished self.fdt_handle.close() self.fdt_handle = None return False, None, None # True when EOF reached in last or current block if samples.size < num_samples: self.fdt_handle.close() self.fdt_handle = None if samples.size == 0: return False, None, None temp = samples samples = numpy.zeros(num_samples) numpy.put(samples, range(temp.size), temp) # need channel x time matrix samples = samples.reshape((self.stdblocksize, self.nChannels)).T ###### READ MARKERS FROM FILE ###### for l in range(self.current_marker_index,len(self.marker_times)): if self.marker_times[l] > self.latency + self._stdblocksize: self.current_marker_index = l self.latency += self._stdblocksize break else: rel_marker_pos = (self.marker_times[l] - 1) % self._stdblocksize markers[rel_marker_pos] = self._markerids[self.marker_data[l]] return True, samples, markers class EEGReader(AbstractStreamReader): """ Load raw EEG data in the .eeg brain products format This module does the Task of parsing .vhdr, .vmrk end .eeg/.dat files and then hand them over to the corresponding windower which iterates over the aggregated data. """ # This function gathers meta information from the .vhdr and .vmrk files. # Only the relevant information is then stored in variables, the windower # accesses during the initialisation phase. def bp_meta(self): nChannels = 0 dSamplingInterval = 0 resolutions = list() channelNames = list() channelids = dict() markerids = dict() markerNames = dict() nmarkertypes = 0 prefix = '' # helper function to convert resolutions # 0 = 100 nV, 1 = 500 nV, 2 = 10 {mu}V, 3 = 152.6 {mu}V # Start with vhdr file file_path = self.abs_eegfile_path + '.vhdr' hdr = open(file_path) for line in hdr: if line.startswith(";"): continue # Read the words between brackets like "[Common Infos]" if line.startswith('['): prefix = line.partition("[")[2].partition("]")[0].lower() continue if line.find("=") == -1: continue # Common Infos and Binary Infos if(prefix == 'common infos' or prefix == 'binary infos'): key, value = line.split('=') key = key.lower() value = value.lower() if(key == 'datafile'): pass # something like filename.eeg elif(key == 'markerfile'): mrk_file = value elif(key == 'dataformat'): pass # usually BINARY elif(key == 'dataorientation'): eeg_data_or = value elif(key == 'datatype'): pass # something like TIMEDOMAIN elif(key == 'numberofchannels'): nChannels = int(value) elif(key == 'datapoints'): pass # the number of datapoints in the whole set elif(key == 'samplinginterval'): dSamplingInterval = int(1000000/float(value)) elif(key == 'binaryformat'): if re.match("int_16", value, flags=re.IGNORECASE) == None: self.eeg_dtype = numpy.float32 else: self.eeg_dtype = numpy.int16 elif(key == 'usebigendianorder'): bin_byteorder = value # Channel Infos # ; Each entry: Ch<Channel number>=<Name>,<Reference channel name>, # ; <Resolution in "Unit">,<Unit>, elif(prefix == 'channel infos'): key, value = line.split('=') if re.match("^[a-z]{2}[0-9]{1,3}", key, flags=re.IGNORECASE) == None: continue ch_id = int(re.findall(r'\d+', key)[0]) ch_name = value.split(',')[0] ch_ref = value.split(',')[1] if len(re.findall(r'\d+', value.split(',')[2])) == 0: ch_res_f = 0 else: ch_res_f = float(re.findall(r'\d+', value.split(',')[2])[0]) ch_res_unit = value.split(',')[3] channelNames.append(ch_name) channelids[ch_name] = ch_id resolutions.append(res_conv(ch_res_f, ch_res_unit)) # Everything thats left.. else: #print "parsing finished!" break hdr.close() # Continue with marker file # Priority: # 1: Path from .vhdr # 2: Path constructed from eegfile path prefix = '' markerNames[0] = 'null' try: self.mrk_handle = open(os.path.basename(self.abs_eegfile_path) + mrk_file) except IOError: try: self.mrk_handle = open(self.abs_eegfile_path + '.vmrk') except IOError: raise IOError, str("Could not open [%s.vmrk]!" % os.path.realpath(self.abs_eegfile_path)) # Parse file for line in self.mrk_handle: if line.startswith(";"): continue # Read the words between brackets like "[Common Infos]" if line.startswith('['): prefix = line.partition("[")[2].partition("]")[0].lower() continue if line.find("=") == -1: continue if prefix == "marker infos": mrk_name = line.split(',')[1] if mrk_name != "" and mrk_name not in markerNames.values(): markerNames[len(markerNames)] = mrk_name # rewinds the marker file self.mrk_handle.seek(0, os.SEEK_SET) # helper struct for finding markers self.mrk_info = dict() self.mrk_info['line'] = "" self.mrk_info['position'] = 0 # advance to first marker line while(re.match("^Mk1=", self.mrk_info['line'], re.IGNORECASE) == None): try: self.mrk_info['line'] = self.mrk_handle.next() except StopIteration: self.mrk_handle.close() raise StopIteration, str("Reached EOF while searching for first Marker in [%s]" % os.path.realpath(self.mrk_handle.name)) # TODO: Sort markerNames? for key in markerNames: markerids[markerNames[key]] = key markertypes = len(markerids) return nChannels, \ dSamplingInterval, \ resolutions, \ channelNames, \ channelids, \ markerids, \ markerNames, \ markertypes # This function reads the eeg-file and the marker-file for every # block of data which is processed. # string representation with interesting information # Register callback function # Reads data from .eeg/.dat file until EOF
[ 37811, 25342, 5563, 290, 1388, 1398, 329, 12948, 1366, 357, 2435, 2168, 8, 198, 198, 41156, 319, 262, 6143, 5794, 11, 262, 15830, 9173, 318, 9639, 290, 2753, 1337, 198, 1659, 3555, 262, 3696, 13, 198, 198, 492, 284, 4598, 3712, 555, ...
2.055004
11,781
from restapi.connectors import Connector from restapi.env import Env from restapi.services.authentication import BaseAuthentication, Role from restapi.tests import API_URI, BaseTests, FlaskClient from restapi.utilities.logs import log
[ 6738, 1334, 15042, 13, 8443, 669, 1330, 8113, 273, 198, 6738, 1334, 15042, 13, 24330, 1330, 2039, 85, 198, 6738, 1334, 15042, 13, 30416, 13, 41299, 3299, 1330, 7308, 47649, 3299, 11, 20934, 198, 6738, 1334, 15042, 13, 41989, 1330, 7824,...
3.746032
63
############################################################################### # SKA South Africa (http://ska.ac.za/) # # Author: cam@ska.ac.za # # Copyright @ 2013 SKA SA. All rights reserved. # # # # THIS SOFTWARE MAY NOT BE COPIED OR DISTRIBUTED IN ANY FORM WITHOUT THE # # WRITTEN PERMISSION OF SKA SA. # ############################################################################### """CaptureSession encompassing data capturing and standard observations with RTS. This defines the :class:`CaptureSession` class, which encompasses the capturing of data and the performance of standard scans with the RTS system. It also provides a fake :class:`TimeSession` class, which goes through the motions in order to time them, but without performing any real actions. """ import time import logging import sys import os.path import numpy as np import katpoint # This is used to document available spherical projections (and set them in case of TimeSession) from katcorelib.targets import Offset from .array import Array from .katcp_client import KATClient from .defaults import user_logger, activity_logger from katmisc.utils.utils import dynamic_doc # Obtain list of spherical projections and the default projection from antenna proxy projections, default_proj = Offset.PROJECTIONS.keys(), Offset.DEFAULT_PROJECTION # Move default projection to front of list projections.remove(default_proj) projections.insert(0, default_proj) def ant_array(kat, ants, name='ants'): """Create sub-array of antennas from flexible specification. Parameters ---------- kat : :class:`utility.KATCoreConn` object KAT connection object ants : :class:`Array` or :class:`KATClient` object, or list, or string Antennas specified by an Array object containing antenna devices, or a single antenna device or a list of antenna devices, or a string of comma-separated antenna names, or the string 'all' for all antennas controlled via the KAT connection associated with this session Returns ------- array : :class:`Array` object Array object containing selected antenna devices Raises ------ ValueError If antenna with a specified name is not found on KAT connection object """ if isinstance(ants, Array): return ants elif isinstance(ants, KATClient): return Array(name, [ants]) elif isinstance(ants, basestring): if ants.strip() == 'all': return kat.ants else: try: return Array(name, [getattr(kat, ant.strip()) for ant in ants.split(',')]) except AttributeError: raise ValueError("Antenna '%s' not found (i.e. no kat.%s exists)" % (ant, ant)) else: # The default assumes that *ants* is a list of antenna devices return Array(name, ants) def report_compact_traceback(tb): """Produce a compact traceback report.""" print '--------------------------------------------------------' print 'Session interrupted while doing (most recent call last):' print '--------------------------------------------------------' while tb: f = tb.tb_frame print '%s %s(), line %d' % (f.f_code.co_filename, f.f_code.co_name, f.f_lineno) tb = tb.tb_next print '--------------------------------------------------------' class TimeSession(CaptureSessionBase): """Fake CaptureSession object used to estimate the duration of an experiment.""" def __enter__(self): """Start time estimate, overriding the time module.""" return self def __exit__(self, exc_type, exc_value, traceback): """Finish time estimate, restoring the time module.""" self.end() # Do not suppress any exceptions that occurred in the body of with-statement return False def _azel(self, target, timestamp, antenna): """Target (az, el) position in degrees (including offsets in degrees).""" projection_type, x, y = self.projection az, el = target.plane_to_sphere(katpoint.deg2rad(x), katpoint.deg2rad(y), timestamp, antenna, projection_type) return katpoint.rad2deg(az), katpoint.rad2deg(el) def _teleport_to(self, target, mode='POINT'): """Move antennas instantaneously onto target (or nearest point on horizon).""" for m in range(len(self._fake_ants)): antenna = self._fake_ants[m][0] az, el = self._azel(target, self.time, antenna) self._fake_ants[m] = (antenna, mode, az, max(el, self.el_limit)) def _slew_to(self, target, mode='POINT', timeout=300.): """Slew antennas to target (or nearest point on horizon), with timeout.""" slew_times = [] for ant, ant_mode, ant_az, ant_el in self._fake_ants: def estimate_slew(timestamp): """Obtain instantaneous target position and estimate time to slew there.""" # Target position right now az, el = self._azel(target, timestamp, ant) # If target is below horizon, aim at closest point on horizon az_dist, el_dist = np.abs(az - ant_az), np.abs(max(el, self.el_limit) - ant_el) # Ignore azimuth wraps and drive strategies az_dist = az_dist if az_dist < 180. else 360. - az_dist # Assume az speed of 2 deg/s, el speed of 1 deg/s and overhead of 1 second slew_time = max(0.5 * az_dist, 1.0 * el_dist) + 1.0 return az, el, slew_time # Initial estimate of slew time, based on a stationary target az1, el1, slew_time = estimate_slew(self.time) # Crude adjustment for target motion: chase target position for 2 iterations az2, el2, slew_time = estimate_slew(self.time + slew_time) az2, el2, slew_time = estimate_slew(self.time + slew_time) # Ensure slew does not take longer than timeout slew_time = min(slew_time, timeout) # If source is below horizon, handle timeout and potential rise in that interval if el2 < self.el_limit: # Position after timeout az_after_timeout, el_after_timeout = self._azel(target, self.time + timeout, ant) # If source is still down, slew time == timeout, else estimate rise time through linear interpolation slew_time = (self.el_limit - el1) / (el_after_timeout - el1) * timeout \ if el_after_timeout > self.el_limit else timeout az2, el2 = self._azel(target, self.time + slew_time, ant) el2 = max(el2, self.el_limit) slew_times.append(slew_time) # print "%s slewing from (%.1f, %.1f) to (%.1f, %.1f) in %.1f seconds" % \ # (ant.name, ant_az, ant_el, az2, el2, slew_time) # The overall slew time is the max for all antennas - adjust current time to reflect the slew self.time += (np.max(slew_times) if len(slew_times) > 0 else 0.) # Blindly assume all antennas are on target (or on horizon) after this interval self._teleport_to(target, mode) def get_centre_freq(self): """Get RF (sky) frequency associated with middle CBF channel. Returns ------- centre_freq : float Actual centre frequency in MHz """ return 1284.0 def set_centre_freq(self, centre_freq): """Set RF (sky) frequency associated with middle CBF channel. Parameters ---------- centre_freq : float Desired centre frequency in MHz """ pass def standard_setup(self, observer, description, experiment_id=None, centre_freq=None, nd_params=None, stow_when_done=None, horizon=None, no_mask=False, **kwargs): """Perform basic experimental setup including antennas, LO and dump rate.""" self.ants = ant_array(self.kat, self.get_ant_names()) for ant in self.ants: try: self._fake_ants.append((katpoint.Antenna(ant.sensor.observer.get_value()), ant.sensor.mode.get_value(), ant.sensor.pos_actual_scan_azim.get_value(), ant.sensor.pos_actual_scan_elev.get_value())) except AttributeError: pass # Override provided session parameters (or initialize them from existing parameters if not provided) self.experiment_id = experiment_id = self.experiment_id if experiment_id is None else experiment_id self.nd_params = nd_params = self.nd_params if nd_params is None else nd_params self.stow_when_done = stow_when_done = self.stow_when_done if stow_when_done is None else stow_when_done self.horizon = self.horizon if horizon is None else horizon user_logger.info('Antennas used = %s' % (' '.join([ant[0].name for ant in self._fake_ants]),)) user_logger.info('Observer = %s' % (observer,)) user_logger.info("Description ='%s'" % (description,)) user_logger.info('Experiment ID = %s' % (experiment_id,)) # There is no way to find out the centre frequency in this fake session... maybe centre_freq = self.get_centre_freq() if centre_freq is None: user_logger.info('RF centre frequency = unknown to simulator, dump rate = %g Hz' % (1.0 / self.dump_period,)) else: user_logger.info('RF centre frequency = %g MHz, dump rate = %g Hz' % (centre_freq, 1.0 / self.dump_period)) if nd_params['period'] > 0: nd_info = "Will switch '%s' noise diode on for %g s and off for %g s, every %g s if possible" % \ (nd_params['diode'], nd_params['on'], nd_params['off'], nd_params['period']) elif nd_params['period'] == 0: nd_info = "Will switch '%s' noise diode on for %g s and off for %g s at every opportunity" % \ (nd_params['diode'], nd_params['on'], nd_params['off']) else: nd_info = "Noise diode will not fire automatically" user_logger.info(nd_info + " while performing canned commands") user_logger.info('--------------------------') def capture_start(self): """Starting capture has no timing effect.""" pass def label(self, label): """Adding label has no timing effect.""" if label: user_logger.info("New compound scan: '%s'" % (label,)) def on_target(self, target): """Determine whether antennas are tracking a given target.""" if not self._fake_ants: return False for antenna, mode, ant_az, ant_el in self._fake_ants: az, el = self._azel(target, self.time, antenna) # Checking for lock and checking for target identity considered the same thing if (az != ant_az) or (el != ant_el) or (mode != 'POINT'): return False return True def target_visible(self, target, duration=0., timeout=300., operation='scan'): """Check whether target is visible for given duration.""" if not self._fake_ants: return False # Convert description string to target object, or keep object as is target = target if isinstance(target, katpoint.Target) else katpoint.Target(target) horizon = katpoint.deg2rad(self.horizon) # Include an average time to slew to the target (worst case about 90 seconds, so half that) now = self.time + 45. average_el, visible_before, visible_after = [], [], [] for antenna, mode, ant_az, ant_el in self._fake_ants: az, el = target.azel(now, antenna) average_el.append(katpoint.rad2deg(el)) # If not up yet, see if the target will pop out before the timeout if el < horizon: now += timeout az, el = target.azel(now, antenna) visible_before.append(el >= horizon) # Check what happens at end of observation az, el = target.azel(now + duration, antenna) visible_after.append(el >= horizon) if all(visible_before) and all(visible_after): return True always_invisible = any(~np.array(visible_before) & ~np.array(visible_after)) if always_invisible: user_logger.warning("Target '%s' is never up during requested period (average elevation is %g degrees)" % (target.name, np.mean(average_el))) else: user_logger.warning("Target '%s' will rise or set during requested period" % (target.name,)) return False def fire_noise_diode(self, diode='coupler', on=10.0, off=10.0, period=0.0, align=True, announce=True): """Estimate time taken to fire noise diode.""" return False # XXX needs a rethink # if not self._fake_ants: # raise ValueError('No antennas specified for session - please run session.standard_setup first') # if self.dump_period == 0.0: # # Wait for the first correlator dump to appear # user_logger.info('waiting for correlator dump to arrive') # self.dump_period = self._requested_dump_period # time.sleep(self.dump_period) # user_logger.info('correlator dump arrived') # if period < 0.0 or (self.time - self.last_nd_firing) < period: # return False # if announce: # user_logger.info("Firing '%s' noise diode (%g seconds on, %g seconds off)" % (diode, on, off)) # else: # user_logger.info('firing noise diode') # self.time += on # self.last_nd_firing = self.time + 0. # self.time += off # user_logger.info('fired noise diode') # return True def set_target(self, target): """Setting target has no timing effect.""" if not self._fake_ants: raise ValueError('No antennas specified for session - please run session.standard_setup first') def track(self, target, duration=20.0, announce=True): """Estimate time taken to perform track.""" if not self._fake_ants: raise ValueError('No antennas specified for session - please run session.standard_setup first') target = target if isinstance(target, katpoint.Target) else katpoint.Target(target) if announce: user_logger.info("Initiating %g-second track on target '%s'" % (duration, target.name)) if not self.target_visible(target, duration): user_logger.warning("Skipping track, as target '%s' will be below horizon" % (target.name,)) return False self.fire_noise_diode(announce=False, **self.nd_params) if not self.on_target(target): user_logger.info('slewing to target') self._slew_to(target) user_logger.info('target reached') self.fire_noise_diode(announce=False, **self.nd_params) user_logger.info('tracking target') self.time += duration + 1.0 user_logger.info('target tracked for %g seconds' % (duration,)) self.fire_noise_diode(announce=False, **self.nd_params) self._teleport_to(target) return True def scan(self, target, duration=30.0, start=(-3.0, 0.0), end=(3.0, 0.0), index=-1, projection=default_proj, announce=True): """Estimate time taken to perform single linear scan.""" if not self._fake_ants: raise ValueError('No antennas specified for session - please run session.standard_setup first') scan_name = 'scan' if index < 0 else 'scan %d' % (index,) target = target if isinstance(target, katpoint.Target) else katpoint.Target(target) if announce: user_logger.info("Initiating %g-second scan across target '%s'" % (duration, target.name)) if not self.target_visible(target, duration): user_logger.warning("Skipping track, as target '%s' will be below horizon" % (target.name,)) return False self.fire_noise_diode(announce=False, **self.nd_params) projection = Offset.PROJECTIONS[projection] self.projection = (projection, start[0], start[1]) user_logger.info('slewing to start of %s' % (scan_name,)) self._slew_to(target, mode='SCAN') user_logger.info('start of %s reached' % (scan_name,)) self.fire_noise_diode(announce=False, **self.nd_params) # Assume antennas can keep up with target (and doesn't scan too fast either) user_logger.info('performing %s' % (scan_name,)) self.time += duration + 1.0 user_logger.info('%s complete' % (scan_name,)) self.fire_noise_diode(announce=False, **self.nd_params) self.projection = (projection, end[0], end[1]) self._teleport_to(target) return True def raster_scan(self, target, num_scans=3, scan_duration=30.0, scan_extent=6.0, scan_spacing=0.5, scan_in_azimuth=True, projection=default_proj, announce=True): """Estimate time taken to perform raster scan.""" if not self._fake_ants: raise ValueError('No antennas specified for session - please run session.standard_setup first') target = target if isinstance(target, katpoint.Target) else katpoint.Target(target) projection = Offset.PROJECTIONS[projection] if announce: user_logger.info("Initiating raster scan (%d %g-second scans extending %g degrees) on target '%s'" % (num_scans, scan_duration, scan_extent, target.name)) nd_time = self.nd_params['on'] + self.nd_params['off'] nd_time *= scan_duration / max(self.nd_params['period'], scan_duration) nd_time = nd_time if self.nd_params['period'] >= 0 else 0. if not self.target_visible(target, (scan_duration + nd_time) * num_scans): user_logger.warning("Skipping track, as target '%s' will be below horizon" % (target.name,)) return False # Create start and end positions of each scan, based on scan parameters scan_levels = np.arange(-(num_scans // 2), num_scans // 2 + 1) scanning_coord = (scan_extent / 2.0) * (-1) ** scan_levels stepping_coord = scan_spacing * scan_levels # Flip sign of elevation offsets to ensure that the first scan always starts at the top left of target scan_starts = zip(scanning_coord, -stepping_coord) if scan_in_azimuth else zip(stepping_coord, -scanning_coord) scan_ends = zip(-scanning_coord, -stepping_coord) if scan_in_azimuth else zip(stepping_coord, scanning_coord) self.fire_noise_diode(announce=False, **self.nd_params) # Perform multiple scans across the target for scan_index, (start, end) in enumerate(zip(scan_starts, scan_ends)): self.projection = (projection, start[0], start[1]) user_logger.info('slewing to start of scan %d' % (scan_index,)) self._slew_to(target, mode='SCAN') user_logger.info('start of scan %d reached' % (scan_index,)) self.fire_noise_diode(announce=False, **self.nd_params) # Assume antennas can keep up with target (and doesn't scan too fast either) user_logger.info('performing scan %d' % (scan_index,)) self.time += scan_duration + 1.0 user_logger.info('scan %d complete' % (scan_index,)) self.fire_noise_diode(announce=False, **self.nd_params) self.projection = (projection, end[0], end[1]) self._teleport_to(target) return True def end(self): """Stop data capturing to shut down the session and close the data file.""" user_logger.info('Scans complete, no data captured as this is a timing simulation...') user_logger.info('Ended data capturing session with experiment ID %s' % (self.experiment_id,)) activity_logger.info('Timing simulation. Ended data capturing session with experiment ID %s' % (self.experiment_id,)) if self.stow_when_done and self._fake_ants: user_logger.info("Stowing dishes.") activity_logger.info('Timing simulation. Stowing dishes.') self._teleport_to(katpoint.Target("azel, 0.0, 90.0"), mode="STOW") user_logger.info('==========================') duration = self.time - self.start_time # Let KATCoreConn know how long the estimated observation time was. self.kat.set_estimated_duration(duration) if duration <= 100: duration = '%d seconds' % (np.ceil(duration),) elif duration <= 100 * 60: duration = '%d minutes' % (np.ceil(duration / 60.),) else: duration = '%.1f hours' % (duration / 3600.,) msg = "Experiment estimated to last %s until this time" % (duration,) user_logger.info(msg + "\n") activity_logger.info("Timing simulation. %s" % (msg,)) # Restore time module functions time.time, time.sleep = self._realtime, self._realsleep # Restore logging for handler in user_logger.handlers: if isinstance(handler, logging.StreamHandler): handler.formatter.datefmt = handler.formatter.old_datefmt del handler.formatter.old_datefmt else: handler.setLevel(handler.old_level) del handler.old_level activity_logger.info("Timing simulation. ----- Script ended %s (%s). Output file None" % (sys.argv[0], ' '.join(sys.argv[1:])))
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 14277, 32, 2520, 5478, 357, 4023, 1378, 82, 4914, 13, 330, 13, 4496, 34729, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.405864
9,141
# -*- coding:utf-8 -*- from django.contrib import admin from .models import UserProfile # Register your models here. admin.site.register(UserProfile, UserProfileModelAdmin)
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 11787, 37046, 198, 198, 2, 17296, 534, 4981, 994, 13, 628, 198, 28482, 13, 15654, 13, 30238, 7,...
3.320755
53
''' axicli.py - Command line interface (CLI) for AxiDraw. For quick help: python axicli.py --help Full user guide: https://axidraw.com/doc/cli_api/ This script is a stand-alone version of AxiDraw Control, accepting various options and providing a facility for setting default values. ''' from axicli.axidraw_cli import axidraw_CLI if __name__ == '__main__': axidraw_CLI()
[ 7061, 6, 198, 897, 291, 4528, 13, 9078, 220, 220, 532, 9455, 1627, 7071, 357, 5097, 40, 8, 329, 12176, 72, 25302, 13, 198, 198, 1890, 2068, 1037, 25, 198, 220, 220, 220, 21015, 7877, 291, 4528, 13, 9078, 1377, 16794, 198, 198, 132...
2.731034
145
# code jam: Qualification Round 2017: Problem C. Bathroom Stalls T = read_int() x = 1 while x <= T: N, K = read_int_n() y, z = get_y_z(N, K) print 'Case #{}: {} {}'.format(x, y, z) x += 1
[ 2, 2438, 16853, 25, 9537, 2649, 10485, 2177, 25, 20647, 327, 13, 24967, 3823, 520, 5691, 198, 198, 51, 796, 1100, 62, 600, 3419, 198, 87, 796, 352, 198, 4514, 2124, 19841, 309, 25, 198, 220, 220, 220, 399, 11, 509, 796, 1100, 62, ...
2.157895
95
""" Integration Tests for vmc_vm_stats execution module """ import pytest
[ 37811, 198, 220, 220, 220, 38410, 30307, 329, 410, 23209, 62, 14761, 62, 34242, 9706, 8265, 198, 37811, 198, 11748, 12972, 9288, 628, 628, 198 ]
3.28
25
# MENTOL # At:Sun Nov 24 15:04:31 2019 if len(bytecode) == 0: print('\x1b[1;93mbyte code kosong\nharap masukkan bytecodenya\x1b[0m') exit() import marshal, sys, os, random, string, time try: from uncompyle6.main import decompile except: os.system('pip install uncompyle6') from uncompyle6.main import decompile n = ''.join((random.choice(string.ascii_lowercase) for _ in range(4))) fl = n + '-dec.py' logo = '\n+m 888 +h,8,"88b,\n+m e88 888 ,e e, e88\'888 e88 88e 888 888 8e +p888 88e Y8b Y888P +h " ,88P\'\n+md888 888 d88 88b d888 \'8 d888 888b 888 888 88b +p888 888b Y8b Y8P +h C8K\n+mY888 888 888 , Y888 , Y888 888P 888 888 888 +p888 888P Y8b Y +h e `88b,\n+m "88 888 "YeeP" "88,e8\' "88 88" 888 888 888 +p888 88" 888 +h"8",88P\'\n +p888 888\n +p888 888+p\n\t\t+ccoded by: +pZhu Bai Lee AKA AnonyMass\n\t\t+cteam : +pBlack Coder Crush' decom()
[ 2, 337, 3525, 3535, 220, 198, 2, 1629, 25, 16012, 5267, 1987, 1315, 25, 3023, 25, 3132, 13130, 220, 198, 361, 18896, 7, 26327, 8189, 8, 6624, 657, 25, 198, 220, 220, 220, 3601, 10786, 59, 87, 16, 65, 58, 16, 26, 6052, 76, 26327,...
1.699686
636
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 from typing import Any, Mapping import unittest from .abstract_gremlin_proxy_tests import abstract_gremlin_proxy_test_class from .roundtrip_janusgraph_proxy import RoundtripJanusGraphProxy
[ 2, 15069, 25767, 669, 284, 262, 1703, 917, 6248, 1628, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 6738, 19720, 1330, 4377, 11, 337, 5912, 198, 11748, 555, 715, 395, 198, 198, 6738, 764,...
3.373494
83
from builtins import str from builtins import range from builtins import object import os import fixtures import testtools from vn_test import VNFixture from vm_test import VMFixture from common.connections import ContrailConnections from policy_test import PolicyFixture from policy.config import AttachPolicyFixture from time import sleep from tcutils.commands import ssh, execute_cmd, execute_cmd_out
[ 6738, 3170, 1040, 1330, 965, 198, 6738, 3170, 1040, 1330, 2837, 198, 6738, 3170, 1040, 1330, 2134, 198, 11748, 28686, 198, 11748, 34609, 198, 11748, 1332, 31391, 198, 198, 6738, 410, 77, 62, 9288, 1330, 569, 21870, 9602, 198, 6738, 4588...
3.894231
104
import hydra import torch from tqdm import tqdm from deepspeech_pytorch.configs.inference_config import EvalConfig from deepspeech_pytorch.decoder import GreedyDecoder from deepspeech_pytorch.loader.data_loader import SpectrogramDataset, AudioDataLoader from deepspeech_pytorch.utils import load_model, load_decoder
[ 11748, 25039, 198, 11748, 28034, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 6738, 2769, 45862, 62, 9078, 13165, 354, 13, 11250, 82, 13, 259, 4288, 62, 11250, 1330, 26439, 16934, 198, 6738, 2769, 45862, 62, 9078, 13165, ...
3.357895
95
# pylint: disable=missing-module-docstring from fastapi import FastAPI from .routers import task, user tags_metadata = [ { 'name': 'task', 'description': 'Operations related to tasks.', }, ] app = FastAPI( title='Task list', description='Task-list project for the **Megadados** course', openapi_tags=tags_metadata, ) app.include_router(task.router, prefix='/task', tags=['task']) app.include_router(user.router, prefix='/user', tags=['user'])
[ 2, 279, 2645, 600, 25, 15560, 28, 45688, 12, 21412, 12, 15390, 8841, 198, 6738, 3049, 15042, 1330, 12549, 17614, 198, 198, 6738, 764, 472, 1010, 1330, 4876, 11, 2836, 198, 198, 31499, 62, 38993, 796, 685, 198, 220, 220, 220, 1391, 1...
2.653846
182
''' >List of functions 1. contain(value,limit) - contains a value between 0 to limit '''
[ 7061, 6, 198, 29, 8053, 286, 5499, 198, 197, 16, 13, 3994, 7, 8367, 11, 32374, 8, 197, 12, 197, 3642, 1299, 257, 1988, 1022, 657, 284, 4179, 198, 7061, 6, 198 ]
2.8125
32
from data import NumericalField, CategoricalField, Iterator from data import Dataset from synthesizer import MaskGenerator_MLP, ObservedGenerator_MLP, Discriminator, Handler, ObservedGenerator_LSTM from random import choice import multiprocessing import pandas as pd import numpy as np import torch import argparse import json import os parameters_space = { "batch_size":[64, 128, 256], "z_dim":[100, 200, 300], "gen_num_layers":[1,2,3], "gen_hidden_dim":[100, 200, 300, 400], "gen_feature_dim":[100, 200, 300, 400, 500], "gen_lstm_dim":[100,200,300,400,500], "dis_hidden_dim":[100, 200, 300], "dis_num_layers":[1,2,3], "lr":[0.0001,0.0002,0.0005], "cp":[0.01], "dis_train_num" :[1, 2, 5] } if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('configs', help='a json config file') parser.add_argument('gpu', default=0) args = parser.parse_args() gpu = int(args.gpu) if gpu >= 0: GPU = True os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) else: GPU = False with open(args.configs) as f: configs = json.load(f) try: os.mkdir("expdir") except: pass for config in configs: path = "expdir/"+config["name"]+"/" try: os.mkdir("expdir/"+config["name"]) except: pass source = pd.read_csv(config["source"]) target = pd.read_csv(config["target"]) fields = [] col_type = [] if "label" in config.keys(): cond = config["label"] for i, col in enumerate(list(source)): if "label" in config.keys() and col in cond: fields.append((col, CategoricalField("one-hot", noise=0))) col_type.append("condition") elif i in config["normalize_cols"]: fields.append((col,NumericalField("normalize"))) col_type.append("normalize") elif i in config["gmm_cols"]: fields.append((col, NumericalField("gmm", n=5))) col_type.append("gmm") elif i in config["one-hot_cols"]: fields.append((col, CategoricalField("one-hot", noise=0))) col_type.append("one-hot") elif i in config["ordinal_cols"]: fields.append((col, CategoricalField("dict"))) col_type.append("ordinal") source_dst, target_dst = Dataset.split( fields = fields, path = ".", col_type = col_type, train = config["source"], validation = config["target"], format = "csv", ) source_dst.learn_convert() target_dst.learn_convert() print("source row : {}".format(len(source_dst))) print("target row: {}".format(len(target_dst))) n_search = config["n_search"] jobs = [multiprocessing.Process(target=thread_run, args=(path, search, config, source_dst, target_dst, GPU)) for search in range(n_search)] for j in jobs: j.start() for j in jobs: j.join()
[ 6738, 1366, 1330, 399, 6975, 605, 15878, 11, 327, 2397, 12409, 15878, 11, 40806, 1352, 198, 6738, 1366, 1330, 16092, 292, 316, 198, 6738, 24983, 7509, 1330, 18007, 8645, 1352, 62, 5805, 47, 11, 11086, 8520, 8645, 1352, 62, 5805, 47, 1...
2.406643
1,114
# Test the Unicode versions of normal file functions # open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir import sys, os, unittest from test import support if not os.path.supports_unicode_filenames: raise unittest.SkipTest("test works only on NT+") filenames = [ 'abc', 'ascii', 'Gr\xfc\xdf-Gott', '\u0393\u03b5\u03b9\u03ac-\u03c3\u03b1\u03c2', '\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435', '\u306b\u307d\u3093', '\u05d4\u05e9\u05e7\u05e6\u05e5\u05e1', '\u66e8\u66e9\u66eb', '\u66e8\u05e9\u3093\u0434\u0393\xdf', ] # Destroy directory dirname and all files under it, to one level. if __name__ == "__main__": test_main()
[ 2, 6208, 262, 34371, 6300, 286, 3487, 2393, 5499, 198, 2, 1280, 11, 28686, 13, 9654, 11, 28686, 13, 14269, 13, 28686, 13, 4868, 15908, 11, 28686, 13, 918, 480, 11, 28686, 13, 28956, 11, 28686, 13, 28015, 15908, 11, 28686, 13, 354, ...
1.934383
381
import unittest import dbt.utils
[ 11748, 555, 715, 395, 198, 198, 11748, 288, 18347, 13, 26791, 628, 198 ]
2.769231
13
import argparse from pathlib import Path import numpy as np import yaml # this script takes in a folder path and then recursively collects all # results.yaml files in that directory. It averages them and prints # summary statistics parser = argparse.ArgumentParser(description="Analyze the results") parser.add_argument("path", type=str, help="path to the folder containing the results") args = parser.parse_args() results = [] keys = set() for path in Path(args.path).rglob("results.yaml"): with open(path, "r") as file: results.append(yaml.safe_load(file)) keys = keys.union(results[-1].keys()) print(f"Found {len(results)} files with {len(keys)} different metrics\n") output = {} for key in keys: vals = [result[key] for result in results if key in result] n = len(vals) mean = float(np.mean(vals)) std = float(np.std(vals)) output[key] = { "N runs": n, "mean": round(mean, 3), "std": round(std, 3) } print(yaml.dump(output))
[ 11748, 1822, 29572, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 331, 43695, 198, 198, 2, 428, 4226, 2753, 287, 257, 9483, 3108, 290, 788, 664, 1834, 2280, 26609, 477, 198, 2, 2482, 13, 88, ...
2.763736
364
# -*- coding: utf-8 -*- """ @author: lsl E-mail: cug_lsl@cug.edu.cn """ import sys import argparse sys.path.append("/home/aistudio/code") import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import time from Pgnet_structure import Pg_net from Pgnet_dataset import Mydata from loss_function import SAMLoss device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # hyper parameters test_batch_size = 1 parser = argparse.ArgumentParser(description='Paddle Pgnet') # model parser.add_argument('--model', type=str, default='Pgnet') # dataset parser.add_argument('--dataset', type=str, default='WV2') # train parser.add_argument('--in_nc', type=int, default=126, help='number of input image channels') parser.add_argument('--endmember', type=int, default=20, help='number of endmember') parser.add_argument('--batch_size', type=int, default=15, help='training batch size') parser.add_argument('--num_epochs', type=int, default=500, help='number of training epochs') parser.add_argument('--lr', type=float, default=2e-3, help='learning rate') parser.add_argument('--resume', type=str, default='', help='path to model checkpoint') parser.add_argument('--start_epoch', type=int, default=1, help='restart epoch number for training') parser.add_argument('--momentum', type=float, default=0.05, help='momentum') parser.add_argument('--step', type=int, default=100, help='Sets the learning rate to the initial LR decayed by momentum every n epochs, Default: n=100') # test parser.add_argument('--test', type=bool, default=False, help='test') parser.add_argument('--load_para', type=bool, default=False, help='if load model parameters') parser.add_argument('--test_batch_size', type=int, default=1, help='testing batch size') opt = parser.parse_args() print(opt)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 31, 9800, 25, 300, 6649, 201, 198, 36, 12, 4529, 25, 269, 1018, 62, 75, 6649, 31, 66, 1018, 13, 15532, 13, 31522, 201, 198, 37811, 201, 198, ...
2.814649
669
# # Copyright (c) 2014-2017 Qualcomm Atheros, Inc. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # trace-cmd pktlog plugin for ath10k, QCA Linux wireless driver # # TODO: # # o create class for struct ieee80211_hdr each packet headers with # pack() and unpack() methods import struct import binascii DEBUG = 1 CUR_PKTLOG_VER = 10010 PKTLOG_MAGIC_NUM = 7735225 IEEE80211_FCTL_TODS = 0x0100 IEEE80211_FCTL_FROMDS = 0x0200 TARGET_NUM_MSDU_DESC = (1024 + 400) MAX_PKT_INFO_MSDU_ID = 192 MAX_10_4_PKT_INFO_MSDU_ID = 1 PKTLOG_MAX_TXCTL_WORDS = 57 # must match with enum ath10k_hw_rev from ath10k and existing values # should not change ATH10K_PKTLOG_HW_QCA988X = 0 ATH10K_PKTLOG_HW_QCA6174 = 1 ATH10K_PKTLOG_HW_QCA99X0 = 2 ATH10K_PKTLOG_HW_QCA9888 = 3 ATH10K_PKTLOG_HW_QCA9984 = 4 ATH10K_PKTLOG_HW_QCA9377 = 5 ATH10K_PKTLOG_HW_QCA40XX = 6 ATH10K_PKTLOG_HW_QCA9887 = 7 ATH10K_PKTLOG_TYPE_TX_CTRL = 1 ATH10K_PKTLOG_TYPE_TX_STAT = 2 ATH10K_PKTLOG_TYPE_TX_MSDU_ID = 3 ATH10K_PKTLOG_TYPE_TX_FRM_HDR = 4 ATH10K_PKTLOG_TYPE_RX_STAT = 5 ATH10K_PKTLOG_TYPE_RC_FIND = 6 ATH10K_PKTLOG_TYPE_RC_UPDATE = 7 ATH10K_PKTLOG_TYPE_TX_VIRT_ADDR = 8 ATH10K_PKTLOG_TYPE_DBG_PRINT = 9 ATH10K_PKTLOG_FLG_TYPE_LOCAL_S = 0 ATH10K_PKTLOG_FLG_TYPE_REMOTE_S = 1 ATH10K_PKTLOG_FLG_TYPE_CLONE_S = 2 ATH10K_PKTLOG_FLG_TYPE_UNKNOWN_S = 3 # sizeof(ath10k_pktlog_txctl) = 12 + 4 * 57 ATH10K_PKTLOG_TXCTL_LEN = 240 ATH10K_PKTLOG_MAX_TXCTL_WORDS = 57 # sizeof(ath10k_pktlog_10_4_txctl)2 = 16 + 4 * 153 ATH10K_PKTLOG_10_4_TXCTL_LEN = 624 ATH10K_PKTLOG_10_4_MAX_TXCTL_WORDS = 153 msdu_len_tbl = {} output_file = None frm_hdr = None # struct ath10k_pktlog_hdr { # unsigned short flags; # unsigned short missed_cnt; # unsigned short log_type; # unsigned short size; # unsigned int timestamp; # unsigned char payload[0]; # } __attribute__((__packed__)); # struct ath10k_pktlog_10_4_hdr { # unsigned short flags; # unsigned short missed_cnt; # unsigned short log_type; # unsigned short size; # unsigned int timestamp; # unsigned int type_specific_data; # unsigned char payload[0]; # } __attribute__((__packed__)); def output_open(): global output_file # apparently no way to close the file as the python plugin doesn't # have unregister() callback output_file = open('pktlog.dat', 'wb') buf = struct.pack('II', PKTLOG_MAGIC_NUM, CUR_PKTLOG_VER) output_write(buf) def output_write(buf): global output_file output_file.write(buf) def pktlog_tx_frm_hdr(frame): global frm_hdr try: # struct ieee80211_hdr (frame_control, duration_id, addr1a, addr1b, addr1c, addr2a, addr2b, addr2c, addr3a, addr3b, addr3c, seq_ctrl) = struct.unpack_from('<HHI2BI2BI2BH', frame, 0) except struct.error as e: dbg('failed to parse struct ieee80211_hdr: %s' % (e)) return if frame_control & IEEE80211_FCTL_TODS: bssid_tail = (addr1b << 8) | addr1c sa_tail = (addr2b << 8) | addr2c da_tail = (addr3b << 8) | addr3c elif frame_control & IEEE80211_FCTL_FROMDS: bssid_tail = (addr2b << 8) | addr2c sa_tail = (addr3b << 8) | addr3c da_tail = (addr1b << 8) | addr1c else: bssid_tail = (addr3b << 8) | addr3c sa_tail = (addr2b << 8) | addr2c da_tail = (addr1b << 8) | addr1c resvd = 0 frm_hdr = struct.pack('HHHHHH', frame_control, seq_ctrl, bssid_tail, sa_tail, da_tail, resvd) dbg('frm_hdr %d B' % len(frm_hdr)) def pktlog_tx_ctrl(buf, hw_type): global frm_hdr if hw_type == ATH10K_PKTLOG_HW_QCA988X: hdr = Ath10kPktlogHdr() hdr.unpack(buf) hdr.size = ATH10K_PKTLOG_TXCTL_LEN num_txctls = ATH10K_PKTLOG_MAX_TXCTL_WORDS elif hw_type in [ATH10K_PKTLOG_HW_QCA99X0, ATH10K_PKTLOG_HW_QCA40XX, ATH10K_PKTLOG_HW_QCA9888, ATH10K_PKTLOG_HW_QCA9984]: hdr = Ath10kPktlog_10_4_Hdr() hdr.unpack(buf) hdr.size = ATH10K_PKTLOG_10_4_TXCTL_LEN num_txctls = ATH10K_PKTLOG_10_4_MAX_TXCTL_WORDS output_write(hdr.pack()) # write struct ath10k_pktlog_frame if frm_hdr: output_write(frm_hdr) else: tmp = struct.pack('HHHHHH', 0, 0, 0, 0, 0, 0) output_write(tmp) txdesc_ctl = hdr.payload[0:] for i in range(num_txctls): if len(txdesc_ctl) >= 4: txctl, = struct.unpack_from('<I', txdesc_ctl) txdesc_ctl = txdesc_ctl[4:] else: txctl = 0 output_write(struct.pack('I', txctl))
[ 2, 198, 2, 15069, 357, 66, 8, 1946, 12, 5539, 32903, 27751, 4951, 11, 3457, 13, 198, 2, 198, 2, 2448, 3411, 284, 779, 11, 4866, 11, 13096, 11, 290, 14, 273, 14983, 428, 3788, 329, 597, 198, 2, 4007, 351, 393, 1231, 6838, 318, ...
2.105816
2,476
from __future__ import annotations from typing import TYPE_CHECKING, Optional from ._base import TelegramObject if TYPE_CHECKING: # pragma: no cover from .location import Location
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 11, 32233, 198, 198, 6738, 47540, 8692, 1330, 50203, 10267, 198, 198, 361, 41876, 62, 50084, 2751, 25, 220, 1303, 23864, 2611, 25, 645, 3002, 198...
3.78
50
import random import argparse # TODO: Parse word lists from files words = { "codenames_adjective": [ "quantum", "loud", "red", "blue", "green", "yellow", "irate", "angry", "peeved", "happy", "slimy", "sleepy", "junior", "slicker", "united", "somber", "bizarre", "odd", "weird", "wrong", "latent", "chilly", "strange", "loud", "silent", "hopping", "orange", "violet", "violent", "desolate", "lone", "cold", "solemn", "raging", "intelligent", "american", ], "codenames_noun": [ "matrix", "wolf", "solace", "whisper", "felony", "moon", "sucker", "penguin", "waffle", "maestro", "night", "trinity", "deity", "monkey", "ark", "squirrel", "iron", "bounce", "farm", "chef", "trough", "net", "trawl", "glee", "water", "spork", "plow", "feed", "souffle", "route", "bagel", "montana", "analyst", "auto", "watch", "photo", "yard", "source", "monkey", "seagull", "toll", "spawn", "gopher", "chipmunk", "set", "calendar", "artist", "chaser", "scan", "tote", "beam", "entourage", "genesis", "walk", "spatula", "rage", "fire", "master" ], "codenames_suffix": [ " {}000", "-II", " {}.0", " rev{}", "-HX", " v{}", ] } if __name__ == "__main__": main(parse_args())
[ 11748, 4738, 198, 11748, 1822, 29572, 198, 198, 2, 16926, 46, 25, 2547, 325, 1573, 8341, 422, 3696, 198, 10879, 796, 1391, 198, 197, 1, 19815, 268, 1047, 62, 324, 752, 425, 1298, 685, 198, 197, 197, 1, 40972, 388, 1600, 198, 220, ...
1.714286
966
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Andre Anjos <andre.anjos@idiap.ch> # Mon 18 Nov 21:38:19 2013 """Extension building for using this package """ import numpy from pkg_resources import resource_filename from bob.extension import Extension as BobExtension # forward the build_ext command from bob.extension from bob.extension import build_ext, Library as BobLibrary from distutils.version import LooseVersion
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 43907, 25, 900, 2393, 12685, 7656, 28, 40477, 12, 23, 1058, 198, 2, 10948, 1052, 73, 418, 1279, 49078, 13, 272, 73, 418, 31, 19830, 499, 13, 354, 29, 198, 2, 2892, 1248, 5267, ...
3.375
128
from robot.api.deco import keyword from robot.libraries.BuiltIn import BuiltIn
[ 6738, 9379, 13, 15042, 13, 12501, 78, 1330, 21179, 198, 6738, 9379, 13, 75, 11127, 13, 39582, 818, 1330, 28477, 818 ]
3.714286
21
from ward import test, each, raises from homeassistant.core import HomeAssistant from hautomate.settings import HautoConfig from hautomate import Hautomate import pydantic from tests.fixtures import cfg_data_hauto
[ 6738, 15305, 1330, 1332, 11, 1123, 11, 12073, 198, 198, 6738, 1363, 562, 10167, 13, 7295, 1330, 5995, 48902, 198, 6738, 387, 315, 296, 378, 13, 33692, 1330, 367, 23736, 16934, 198, 6738, 387, 315, 296, 378, 1330, 367, 2306, 296, 378, ...
3.444444
63
import unittest import zserio from testutils import getZserioApi BIT4_LOWER_BOUND = 0 BIT4_UPPER_BOUND = 15
[ 11748, 555, 715, 395, 198, 11748, 1976, 2655, 952, 198, 198, 6738, 1332, 26791, 1330, 651, 57, 2655, 952, 32, 14415, 198, 198, 26094, 19, 62, 43, 36048, 62, 33, 15919, 796, 657, 198, 26094, 19, 62, 8577, 18973, 62, 33, 15919, 796, ...
2.444444
45
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-12-11 11:46 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 19, 319, 2864, 12, 1065, 12, 1157, 1367, 25, 3510, 201, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, ...
2.53125
64
import numpy as np import math import time
[ 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 640, 628 ]
3.666667
12
#!/usr/bin/env python # -*- coding: utf-8 -*- # from unittest import mock # from datakit_dworld.push import Push def test_push(capsys): """Sample pytest test function with a built-in pytest fixture as an argument. """ # cmd = Greeting(None, None, cmd_name='dworld push') # parsed_args = mock.Mock() # parsed_args.greeting = 'Hello world!' # cmd.run(parsed_args) # out, err = capsys.readouterr() # assert 'Hello world!' in out
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 422, 555, 715, 395, 1330, 15290, 628, 198, 2, 422, 4818, 461, 270, 62, 67, 6894, 13, 14689, 1330, 23691, 628, 19...
2.581006
179
import cv2 import numpy as np from scipy.interpolate import UnivariateSpline
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 3849, 16104, 378, 1330, 791, 42524, 26568, 500, 198 ]
3.08
25
import torch from metrics.swd import sliced_wasserstein_distance from evaluators.sample_evaluators.base_sample_evaluator import BaseSampleEvaluator from noise_creator import NoiseCreator
[ 11748, 28034, 201, 198, 6738, 20731, 13, 2032, 67, 1330, 26790, 62, 86, 24929, 5714, 62, 30246, 201, 198, 6738, 5418, 84, 2024, 13, 39873, 62, 18206, 84, 2024, 13, 8692, 62, 39873, 62, 18206, 84, 1352, 1330, 7308, 36674, 36, 2100, 8...
3.327586
58
""" Language enumeration. Part of the StoryTechnologies project. June 12, 2016 Brett Alistair Kromkamp (brett.kromkamp@gmail.com) """ from enum import Enum
[ 37811, 198, 32065, 27056, 341, 13, 2142, 286, 262, 8362, 25574, 5823, 1628, 13, 198, 198, 15749, 1105, 11, 1584, 198, 33, 11489, 978, 396, 958, 509, 398, 40899, 357, 4679, 926, 13, 74, 398, 40899, 31, 14816, 13, 785, 8, 198, 37811, ...
3.117647
51
# Generated by Django 4.0.3 on 2022-04-02 17:24 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 13, 18, 319, 33160, 12, 3023, 12, 2999, 1596, 25, 1731, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
""" .. module: lemur.roles.views :platform: Unix :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <kglisson@netflix.com> """ from flask import Blueprint from flask import make_response, jsonify, abort, g from flask.ext.restful import reqparse, fields, Api from lemur.roles import service from lemur.auth.service import AuthenticatedResource from lemur.auth.permissions import ViewRoleCredentialsPermission, admin_permission from lemur.common.utils import marshal_items, paginated_parser mod = Blueprint('roles', __name__) api = Api(mod) FIELDS = { 'name': fields.String, 'description': fields.String, 'id': fields.Integer, } api.add_resource(RolesList, '/roles', endpoint='roles') api.add_resource(Roles, '/roles/<int:role_id>', endpoint='role') api.add_resource(RoleViewCredentials, '/roles/<int:role_id>/credentials', endpoint='roleCredentials`') api.add_resource(AuthorityRolesList, '/authorities/<int:authority_id>/roles', endpoint='authorityRoles') api.add_resource(UserRolesList, '/users/<int:user_id>/roles', endpoint='userRoles')
[ 37811, 198, 492, 8265, 25, 443, 28582, 13, 305, 829, 13, 33571, 198, 220, 220, 220, 1058, 24254, 25, 33501, 198, 220, 220, 220, 1058, 22163, 4766, 25, 357, 66, 8, 1853, 416, 12074, 3457, 1539, 766, 37195, 20673, 329, 517, 198, 220, ...
2.959391
394
""" The roseguarden project Copyright (C) 2018-2020 Marcus Drobisch, This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ __authors__ = ["Marcus Drobisch"] __contact__ = "roseguarden@fabba.space" __credits__ = [] __license__ = "GPLv3" import copy from core.common.objDict import ObjDict
[ 37811, 198, 464, 8278, 5162, 5872, 1628, 198, 198, 15269, 357, 34, 8, 2864, 12, 42334, 220, 17068, 21045, 65, 25308, 11, 198, 198, 1212, 1430, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, 340, 739, 198, 1169...
3.645299
234
# Copyright (c) OpenMMLab. All rights reserved. import argparse import cv2 import mmcv import numpy as np import torch from torchvision.transforms import functional as F from mmdet.apis import init_detector from mmdet.datasets.pipelines import Compose try: import ffmpegcv except ImportError: raise ImportError( 'Please install ffmpegcv with:\n\n pip install ffmpegcv') if __name__ == '__main__': main()
[ 2, 15069, 357, 66, 8, 4946, 44, 5805, 397, 13, 1439, 2489, 10395, 13, 198, 11748, 1822, 29572, 198, 198, 11748, 269, 85, 17, 198, 11748, 8085, 33967, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 10178, 13, ...
2.906667
150
#! /usr/bin/env python """ Benchmark the rdomset (catlas level 1) algorithm, without I/O considerations. """ import sys, os # add spacegraphcats package to import path: sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import spacegraphcats from spacegraphcats.catlas import catlas import argparse import sys import time if __name__ == '__main__': sys.exit(main())
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 44199, 4102, 262, 374, 3438, 2617, 357, 9246, 21921, 1241, 352, 8, 11862, 11, 1231, 314, 14, 46, 18506, 13, 198, 37811, 198, 11748, 25064, 11, 28686, 198, 2, 751, 2272,...
2.984615
130
# # PYOB SET LABEL MIXIN #
[ 2, 220, 198, 2, 220, 350, 56, 9864, 25823, 406, 6242, 3698, 337, 10426, 1268, 198, 2, 220, 628 ]
1.631579
19
import time from hashlib import sha1
[ 11748, 640, 198, 6738, 12234, 8019, 1330, 427, 64, 16, 628 ]
3.454545
11
import pandas as pd import os from configparser import ConfigParser, NoSectionError, NoOptionError from datetime import datetime import numpy as np import glob from simba.rw_dfs import *
[ 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 28686, 201, 198, 6738, 4566, 48610, 1330, 17056, 46677, 11, 1400, 16375, 12331, 11, 1400, 19722, 12331, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 11748, 299, 32152, 355, 45...
3.25
60
import os import re import warnings import matplotlib import matplotlib.pyplot as plt import matplotlib.image as image from matplotlib import _pylab_helpers from matplotlib.cbook import exception_to_str import seaborn from SphinxReport.Component import * from SphinxReport import Config, Utils
[ 11748, 28686, 198, 11748, 302, 198, 11748, 14601, 198, 198, 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 9060, 355, 2939, 198, 6738, 2603, 29487, 8019, 1330, ...
3.413793
87
import cv2 import imageio import numpy as np import matplotlib.pyplot as plt from itertools import product, zip_longest import seaborn as sns
[ 11748, 269, 85, 17, 198, 11748, 2939, 952, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 340, 861, 10141, 1330, 1720, 11, 19974, 62, 6511, 395, 198, 11748, 384, 397, 1211,...
3.041667
48
"""Various sample data""" from binascii import unhexlify magic = 0xE9BEB4D9 # These keys are from addresses test script sample_pubsigningkey = unhexlify( '044a367f049ec16cb6b6118eb734a9962d10b8db59c890cd08f210c43ff08bdf09d' '16f502ca26cd0713f38988a1237f1fc8fa07b15653c996dc4013af6d15505ce') sample_pubencryptionkey = unhexlify( '044597d59177fc1d89555d38915f581b5ff2286b39d022ca0283d2bdd5c36be5d3c' 'e7b9b97792327851a562752e4b79475d1f51f5a71352482b241227f45ed36a9') sample_privsigningkey = \ b'93d0b61371a54b53df143b954035d612f8efa8a3ed1cf842c2186bfd8f876665' sample_privencryptionkey = \ b'4b0b73a54e19b059dc274ab69df095fe699f43b17397bca26fdf40f4d7400a3a' sample_ripe = b'003cd097eb7f35c87b5dc8b4538c22cb55312a9f' # stream: 1, version: 2 sample_address = 'BM-onkVu1KKL2UaUss5Upg9vXmqd3esTmV79' sample_factor = 66858749573256452658262553961707680376751171096153613379801854825275240965733 # G * sample_factor sample_point = ( 33567437183004486938355437500683826356288335339807546987348409590129959362313, 94730058721143827257669456336351159718085716196507891067256111928318063085006 ) sample_seed = 'TIGER, tiger, burning bright. In the forests of the night' # Deterministic addresses with stream 1 and versions 3, 4 sample_deterministic_ripe = b'00cfb69416ae76f68a81c459de4e13460c7d17eb' sample_deterministic_addr3 = 'BM-2DBPTgeSawWYZceFD69AbDT5q4iUWtj1ZN' sample_deterministic_addr4 = 'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK' sample_daddr3_512 = 18875720106589866286514488037355423395410802084648916523381 sample_daddr4_512 = 25152821841976547050350277460563089811513157529113201589004 sample_statusbar_msg = "new status bar message" sample_inbox_msg_ids = ['27e644765a3e4b2e973ee7ccf958ea20', '51fc5531-3989-4d69-bbb5-68d64b756f5b', '2c975c515f8b414db5eea60ba57ba455', 'bc1f2d8a-681c-4cc0-9a12-6067c7e1ac24'] # second address in sample_test_subscription_address is for the announcement broadcast sample_test_subscription_address = ['BM-2cWQLCBGorT9pUGkYSuGGVr9LzE4mRnQaq', 'BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw'] sample_subscription_name = 'test sub'
[ 37811, 40009, 6291, 1366, 37811, 198, 198, 6738, 9874, 292, 979, 72, 1330, 555, 33095, 75, 1958, 628, 198, 32707, 796, 657, 87, 36, 24, 12473, 33, 19, 35, 24, 198, 198, 2, 2312, 8251, 389, 422, 9405, 1332, 4226, 198, 39873, 62, 12...
2.051406
1,031
from urllib.parse import parse_qs from anticaptchaofficial.hcaptchaproxyless import hCaptchaProxyless from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from court_scraper.base.selenium_helpers import SeleniumHelpers from court_scraper.utils import dates_for_range from .search_results import SearchResultsPage from ..search_api import SearchApi
[ 6738, 2956, 297, 571, 13, 29572, 1330, 21136, 62, 48382, 198, 198, 6738, 47792, 2373, 354, 5488, 2108, 498, 13, 71, 27144, 354, 499, 42059, 1203, 1330, 289, 19209, 11693, 44148, 1203, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, ...
3.437037
135
from bitmovin_api_sdk.encoding.encodings.muxings.mp3.mp3_api import Mp3Api from bitmovin_api_sdk.encoding.encodings.muxings.mp3.customdata.customdata_api import CustomdataApi from bitmovin_api_sdk.encoding.encodings.muxings.mp3.information.information_api import InformationApi from bitmovin_api_sdk.encoding.encodings.muxings.mp3.mp3_muxing_list_query_params import Mp3MuxingListQueryParams
[ 6738, 1643, 76, 709, 259, 62, 15042, 62, 21282, 74, 13, 12685, 7656, 13, 12685, 375, 654, 13, 76, 2821, 654, 13, 3149, 18, 13, 3149, 18, 62, 15042, 1330, 337, 79, 18, 32, 14415, 198, 6738, 1643, 76, 709, 259, 62, 15042, 62, 2128...
2.481013
158
# 2022 eCTF # Bootloader Interface Emulator # Ben Janis # # (c) 2022 The MITRE Corporation # # This source file is part of an example system for MITRE's 2022 Embedded System # CTF (eCTF). This code is being provided only for educational purposes for the # 2022 MITRE eCTF competition, and may not meet MITRE standards for quality. # Use this code at your own risk! # # DO NOT CHANGE THIS FILE import argparse import os import logging import socket import select from pathlib import Path from typing import List, Optional, TypeVar Message = TypeVar("Message") LOG_FORMAT = "%(asctime)s:%(name)-s%(levelname)-8s %(message)s" if __name__ == "__main__": main()
[ 2, 33160, 304, 4177, 37, 198, 2, 18892, 29356, 26491, 2295, 8927, 198, 2, 3932, 2365, 271, 198, 2, 198, 2, 357, 66, 8, 33160, 383, 17168, 2200, 10501, 198, 2, 198, 2, 770, 2723, 2393, 318, 636, 286, 281, 1672, 1080, 329, 17168, ...
3.252427
206
# -*- coding: utf-8 -*- """ This is a script to demo how to open up a macro enabled excel file, write a pandas dataframe to it and save it as a new file name. Created on Mon Mar 1 17:47:41 2021 @author: Shane Gore """ import os import xlwings as xw import pandas as pd os.chdir(r"C:\Users\Shane Gore\Desktop\Roisin") wb = xw.Book("CAO_template.xlsm") worksheet = wb.sheets['EPOS_Closing_Stock_Detailed'] 'Create dataframe' cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'], 'Price': [22000,25000,27000,35000] } cars_df = pd.DataFrame(cars, columns = ['Brand', 'Price']) 'Write a dataframe to excel' worksheet.range('A1').value = cars_df 'Create a datafame from and excel sheet' excel_df = worksheet.range('A1').options(pd.DataFrame, expand='table').value 'Save the excel as a new workbook' newfilename = ('Test4.xlsm') wb.save(newfilename) 'close the workbook' wb.close()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 1212, 318, 257, 4226, 284, 13605, 703, 284, 1280, 510, 257, 15021, 9343, 27336, 2393, 11, 3551, 257, 19798, 292, 1366, 14535, 284, 340, 201, 198, ...
2.450633
395
from __future__ import division import numpy as np from scipy import linalg from matplotlib import pyplot as plt from fatiando.gravmag import sphere from fatiando import mesher, gridder, utils from fatiando.vis import mpl import scipy.special import scipy.interpolate def elipsoide (xp,yp,zp,inten,inc,dec,ellipsoids): ''' Calcula as tres componentes do campo magnetico de um elipsoide. a: escalar - semi eixo maior b: escalar - semi eixo intermediario c: escalar - semi eixo menor h: escalar - profundidade alfa: escalar - azimute do elipsoide em relacao ao "a" delta: escalar - inclinacao do elipsoide em relacao ao "a" gamma: escalar - angulo entre o semi eixo "b" e a projecao do centro do elipsoide no plano xy xp: matriz - malha do eixo x yp: matriz - malha do eixo y zp: matriz - malha do eixo z xc: escalar - posicao x do centro do elipsoide yc: escalar - posicao y do centro do elipsoide J: vetor - magnetizacao do corpo ''' # Calculo de parametros de direcao #l1 = l1_v (ellipsoids.alfa, ellipsoids.delta) #l2 = l2_v (ellipsoids.alfa, ellipsoids.delta, ellipsoids.gamma) #l3 = l3_v (ellipsoids.alfa, ellipsoids.delta, ellipsoids.gamma) #m1 = m1_v (ellipsoids.alfa, ellipsoids.delta) #m2 = m2_v (ellipsoids.alfa, ellipsoids.delta, ellipsoids.gamma) #m3 = m3_v (ellipsoids.alfa, ellipsoids.delta, ellipsoids.gamma) #n1 = n1_v (ellipsoids.delta) #n2 = n2_v (ellipsoids.delta, ellipsoids.gamma) #n3 = n3_v (ellipsoids.delta, ellipsoids.gamma) #ln = ln_v (ellipsoids.props['remanence'][2], ellipsoids.props['remanence'][1]) #mn = mn_v (ellipsoids.props['remanence'][2], ellipsoids.props['remanence'][1]) #nn = nn_v (ellipsoids.props['remanence'][1]) #mcon = np.array([[l1, m1, n1],[l2, m2, n2],[l3, m3, n3]]) #mconT = mcon.T #print mconT lt = ln_v (dec, inc) mt = mn_v (dec, inc) nt = nn_v (inc) #print l1,m1,n1 #print l2,m2,n2 #print l3,m3,n3 # Coordenadas Cartesianas elipsoide x1 = x1_e (xp,yp,zp,ellipsoids.xc,ellipsoids.yc,ellipsoids.zc,ellipsoids.l1,ellipsoids.m1,ellipsoids.n1) x2 = x2_e (xp,yp,zp,ellipsoids.xc,ellipsoids.yc,ellipsoids.zc,ellipsoids.l2,ellipsoids.m2,ellipsoids.n2) x3 = x3_e (xp,yp,zp,ellipsoids.xc,ellipsoids.yc,ellipsoids.zc,ellipsoids.l3,ellipsoids.m3,ellipsoids.n3) # Calculos auxiliares p0 = p0_e (ellipsoids.a,ellipsoids.b,ellipsoids.c,x1,x2,x3) p1 = p1_e (ellipsoids.a,ellipsoids.b,ellipsoids.c,x1,x2,x3) p2 = p2_e (ellipsoids.a,ellipsoids.b,ellipsoids.c,x1,x2,x3) p = p_e (p1,p2) q = q_e (p0,p1,p2) teta = teta_e (p,q) # Raizes da equacao cubica lamb = lamb_e (p,teta,p2) # Calculo de parametros para as integrais F,E,F2,E2,k,teta_linha = parametros_integrais(ellipsoids.a,ellipsoids.b,ellipsoids.c,lamb) # Magnetizacoes nas coordenadas do elipsoide #k_dec = np.array([[ellipsoids.props['k1'][2]],[ellipsoids.props['k2'][2]],[ellipsoids.props['k3'][2]]]) #k_int = np.array([[ellipsoids.props['k1'][0]],[ellipsoids.props['k2'][0]],[ellipsoids.props['k3'][0]]]) #k_inc = np.array([[ellipsoids.props['k1'][1]],[ellipsoids.props['k2'][1]],[ellipsoids.props['k3'][1]]]) #if ellipsoids.props['k1'][0] == ellipsoids.props['k2'][0] and ellipsoids.props['k1'][0] == ellipsoids.props['k3'][0]: # km = k_matrix2 (k_int,l1,l2,l3,m1,m2,m3,n1,n2,n3) #else: # Lr = Lr_v (k_dec, k_inc) # Mr = Mr_v (k_dec, k_inc) # Nr = Nr_v (k_inc) # km = k_matrix (k_int,Lr,Mr,Nr,l1,l2,l3,m1,m2,m3,n1,n2,n3) Ft = F_e (inten,lt,mt,nt,ellipsoids.l1,ellipsoids.l2,ellipsoids.l3,ellipsoids.m1,ellipsoids.m2,ellipsoids.m3,ellipsoids.n1,ellipsoids.n2,ellipsoids.n3) JN = JN_e (ellipsoids.props['remanence'][0],ellipsoids.ln,ellipsoids.mn,ellipsoids.nn,ellipsoids.l1,ellipsoids.l2,ellipsoids.l3,ellipsoids.m1,ellipsoids.m2,ellipsoids.m3,ellipsoids.n1,ellipsoids.n2,ellipsoids.n3) N1,N2,N3 = N_desmag (ellipsoids.a,ellipsoids.b,ellipsoids.c,F2,E2) JR = JR_e (ellipsoids.km,JN,Ft) JRD = JRD_e (ellipsoids.km,N1,N2,N3,JR) JRD_carte = (ellipsoids.mconT).dot(JRD) JRD_ang = utils.vec2ang(JRD_carte) #print Ft #print JN #print JRD #print N1,N2,N3 #print JRD_ang # Derivadas de lambda em relacao as posicoes dlambx1 = dlambx1_e (ellipsoids.a,ellipsoids.b,ellipsoids.c,x1,x2,x3,lamb) dlambx2 = dlambx2_e (ellipsoids.a,ellipsoids.b,ellipsoids.c,x1,x2,x3,lamb) dlambx3 = dlambx3_e (ellipsoids.a,ellipsoids.b,ellipsoids.c,x1,x2,x3,lamb) # Calculo das integrais A, B, C = integrais_elipticas(ellipsoids.a,ellipsoids.b,ellipsoids.c,k,teta_linha,F,E) # Geometria para o calculo de B (eixo do elipsoide) cte = cte_m (ellipsoids.a,ellipsoids.b,ellipsoids.c,lamb) V1, V2, V3 = v_e (ellipsoids.a,ellipsoids.b,ellipsoids.c,x1,x2,x3,lamb) # Calculo matriz geometria para B1 m11 = (cte*dlambx1*V1) - A m12 = cte*dlambx1*V2 m13 = cte*dlambx1*V3 # Calculo matriz geometria para B2 m21 = cte*dlambx2*V1 m22 = (cte*dlambx2*V2) - B m23 = cte*dlambx2*V3 # Calculo matriz geometria para B3 m31 = cte*dlambx3*V1 m32 = cte*dlambx3*V2 m33 = (cte*dlambx3*V3) - C # Problema Direto (Calcular o campo externo nas coordenadas do elipsoide) B1 = B1_e (m11,m12,m13,JRD,ellipsoids.a,ellipsoids.b,ellipsoids.c) B2 = B2_e (m21,m22,m23,JRD,ellipsoids.a,ellipsoids.b,ellipsoids.c) B3 = B3_e (m31,m32,m33,JRD,ellipsoids.a,ellipsoids.b,ellipsoids.c) #constante = constante_nova (a,b,c,lamb,JRD,x1,x2,x3) #B1 = B1_novo (constante,dlambx1,a,b,c,JRD,A) #B2 = B2_novo (constante,dlambx2,a,b,c,JRD,B) #B3 = B3_novo (constante,dlambx3,a,b,c,JRD,C) # Problema Direto (Calcular o campo externo nas coordenadas geograficas) Bx = Bx_c (B1,B2,B3,ellipsoids.l1,ellipsoids.l2,ellipsoids.l3) By = By_c (B1,B2,B3,ellipsoids.m1,ellipsoids.m2,ellipsoids.m3) Bz = Bz_c (B1,B2,B3,ellipsoids.n1,ellipsoids.n2,ellipsoids.n3) return Bx,By,Bz,JRD_ang # Problema Direto (Calcular o campo externo e anomalia nas coordenadas geograficas no SI) def bx_c(xp,yp,zp,inten,inc,dec,ellipsoids): if xp.shape != yp.shape != zp.shape: raise ValueError("Input arrays xp, yp, and zp must have same shape!") size = len(xp) res = np.zeros(size, dtype=np.float) ctemag = 1 for i in range(len(ellipsoids)): bx,by,bz,jrd_ang = elipsoide (xp,yp,zp,inten,inc,dec,ellipsoids[i]) res += bx res = res*ctemag return res def by_c(xp,yp,zp,inten,inc,dec,ellipsoids): if xp.shape != yp.shape != zp.shape: raise ValueError("Input arrays xp, yp, and zp must have same shape!") size = len(xp) res = np.zeros(size, dtype=np.float) ctemag = 1 for i in range(len(ellipsoids)): bx,by,bz,jrd_ang = elipsoide (xp,yp,zp,inten,inc,dec,ellipsoids[i]) res += by res = res*ctemag return res def bz_c(xp,yp,zp,inten,inc,dec,ellipsoids): if xp.shape != yp.shape != zp.shape: raise ValueError("Input arrays xp, yp, and zp must have same shape!") size = len(xp) res = np.zeros(size, dtype=np.float) ctemag = 1 for i in range(len(ellipsoids)): bx,by,bz,jrd_ang = elipsoide (xp,yp,zp,inten,inc,dec,ellipsoids[i]) res += bz res = res*ctemag return res def tf_c(xp,yp,zp,inten,inc,dec,ellipsoids): if xp.shape != yp.shape != zp.shape: raise ValueError("Input arrays xp, yp, and zp must have same shape!") size = len(xp) res = np.zeros(size, dtype=np.float) ctemag = 1 for i in range(len(ellipsoids)): bx,by,bz,jrd_ang = elipsoide (xp,yp,zp,inten,inc,dec,ellipsoids[i]) tf = bx*np.cos(inc)*np.cos(dec) + by*np.cos(inc)*np.sin(dec) + bz*np.sin(inc) res += tf res = res*ctemag return res,jrd_ang def l1_v (alfa, delta): ''' Orientacao do elipsoide com respeito ao eixo x. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) output: Direcao em radianos. ''' l1 = (-np.cos(alfa)*np.cos(delta)) return l1 def l2_v (alfa, delta, gamma): ''' Orientacao do elipsoide com respeito ao eixo y. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) gamma - Angulo entre o eixo-maior e a projecao vertical do centro do elipsoide com o plano. (-90<=gamma<=90) output: Direcao em radianos. ''' l2 = (np.cos(alfa)*np.cos(gamma)*np.sin(delta)+np.sin(alfa)*np.sin(gamma)) return l2 def l3_v (alfa, delta, gamma): ''' Orientacao do elipsoide com respeito ao eixo z. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) gamma - Angulo entre o eixo-maior e a projecao vertical do centro do elipsoide com o plano. (-90<=gamma<=90) output: Direcao em radianos. ''' l3 = (np.sin(alfa)*np.cos(gamma)-np.cos(alfa)*np.sin(gamma)*np.sin(delta)) return l3 def m1_v (alfa, delta): ''' Orientacao do elipsoide com respeito ao eixo x. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) output: Direcao em radianos. ''' m1 = (-np.sin(alfa)*np.cos(delta)) return m1 def m2_v (alfa, delta, gamma): ''' Orientacao do elipsoide com respeito ao eixo y. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) gamma - Angulo entre o eixo-maior e a projecao vertical do centro do elipsoide com o plano. (-90<=gamma<=90) output: Direcao em radianos. ''' m2 = (np.sin(alfa)*np.cos(gamma)*np.sin(delta)-np.cos(alfa)*np.sin(gamma)) return m2 def m3_v (alfa, delta, gamma): ''' Orientacao do elipsoide com respeito ao eixo z. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) gamma - Angulo entre o eixo-maior e a projecao vertical do centro do elipsoide com o plano. (-90<=gamma<=90) output: Direcao em radianos. ''' m3 = (-np.cos(alfa)*np.cos(gamma)-np.sin(alfa)*np.sin(gamma)*np.sin(delta)) return m3 def n1_v (delta): ''' Orientacao do elipsoide com respeito ao eixo x. input: delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) output: Direcao em radianos. ''' n1 = (-np.sin(delta)) return n1 def n2_v (delta, gamma): ''' Orientacao do elipsoide com respeito ao eixo y. input: delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) gamma - Angulo entre o eixo-maior e a projecao vertical do centro do elipsoide com o plano. (-90<=gamma<=90) output: Direcao em radianos. ''' n2 = (-np.cos(gamma)*np.cos(delta)) return n2 def n3_v (delta, gamma): ''' Orientacao do elipsoide com respeito ao eixo z. input: delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) gamma - Angulo entre o eixo-maior e a projecao vertical do centro do elipsoide com o plano. (-90<=gamma<=90) output: Direcao em radianos. ''' n3 = (np.sin(gamma)*np.cos(delta)) return n3 def ln_v (declinacao, inclinacao): ''' Orientacao do elipsoide com respeito ao eixo x. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) output: Direcao em radianos. ''' ln = (np.cos(declinacao)*np.cos(inclinacao)) return ln def mn_v (declinacao, inclinacao): ''' Orientacao do elipsoide com respeito ao eixo x. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) output: Direcao em radianos. ''' mn = (np.sin(declinacao)*np.cos(inclinacao)) return mn def nn_v (inclinacao): ''' Orientacao do elipsoide com respeito ao eixo x. input: alfa - Azimute com relacao ao eixo-maior. (0<=alfa<=360) delta - Inclinacao com relacao ao eixo-maior. (0<=delta<=90) output: Direcao em radianos. ''' nn = np.sin(inclinacao) return nn def Lr_v (k_dec, k_inc): ''' Cossenos diretores dos eixos dos vetores de susceptibilidade magnetica. input: k_dec - declinacoes dos vetores de susceptibilidade. k_inc - inclinacoes dos vetores de susceptibilidade. ''' Lr = np.zeros(3) for i in range (3): Lr[i] = np.cos(k_dec[i])*np.cos(k_inc[i]) return Lr def Mr_v (k_dec, k_inc): ''' Cossenos diretores dos eixos dos vetores de susceptibilidade magnetica. input: k_dec - declinacoes dos vetores de susceptibilidade. k_inc - inclinacoes dos vetores de susceptibilidade. ''' Mr = np.zeros(3) for i in range (3): Mr[i] = np.sin(k_dec[i])*np.cos(k_inc[i]) return Mr def Nr_v (k_inc): ''' Cossenos diretores dos eixos dos vetores de susceptibilidade magnetica. input: k_inc - inclinacoes dos vetores de susceptibilidade. ''' Nr = np.zeros(3) for i in range (3): Nr[i] = np.sin(k_inc[i]) return Nr def F_e (intensidadeT,lt,mt,nt,l1,l2,l3,m1,m2,m3,n1,n2,n3): ''' Transformacao do vetor campo magnetico da Terra para as coordenadas nos eixos do elipsoide. ''' Ft = intensidadeT*np.ravel(np.array([[(lt*l1+mt*m1+nt*n1)], [(lt*l2+mt*m2+nt*n2)], [(lt*l3+mt*m3+nt*n3)]])) return Ft def JN_e (intensidade,ln,mn,nn,l1,l2,l3,m1,m2,m3,n1,n2,n3): ''' transformacao do Vetor de magnetizacao remanente para as coordenadas nos eixos do elipsoide. ''' JN = intensidade*np.ravel(np.array([[(ln*l1+mn*m1+nn*n1)], [(ln*l2+mn*m2+nn*n2)], [(ln*l3+mn*m3+nn*n3)]])) return JN def N_desmag (a,b,c,F2,E2): ''' Fator de desmagnetizacao ao longo do eixo de revolucao (N1) e em relacao ao plano equatorial (N2). ''' N1 = ((4.*np.pi*a*b*c)/((a**2-b**2)*(a**2-c**2)**0.5)) * (F2-E2) N2 = (((4.*np.pi*a*b*c)*(a**2-c**2)**0.5)/((a**2-b**2)*(b**2-c**2))) * (E2 - ((b**2-c**2)/(a**2-c**2)) * F2 - ((c*(a**2-b**2))/(a*b*(a**2-c**2)**0.5))) N3 = ((4.*np.pi*a*b*c)/((b**2-c**2)*(a**2-c**2)**0.5)) * (((b*(a**2-c**2)**0.5)/(a*c)) - E2) return N1, N2, N3 def k_matrix (k_int,Lr,Mr,Nr,l1,l2,l3,m1,m2,m3,n1,n2,n3): ''' Matriz de tensores de susceptibilidade. ''' l = np.array([[l1],[l2],[l3]]) m = np.array([[m1],[m2],[m3]]) n = np.array([[n1],[n2],[n3]]) k = np.zeros([3,3]) for i in range (3): for j in range (3): for r in range (3): k[i,j] = k[i,j] + (k_int[r]*(Lr[r]*l[i] + Mr[r]*m[i] + Nr[r]*n[i])*(Lr[r]*l[j] + Mr[r]*m[j] + Nr[r]*n[j])) return k def k_matrix2 (k_int,l1,l2,l3,m1,m2,m3,n1,n2,n3): ''' Matriz de tensores de susceptibilidade. ''' l = np.array([[l1],[l2],[l3]]) m = np.array([[m1],[m2],[m3]]) n = np.array([[n1],[n2],[n3]]) k = np.zeros([3,3]) for i in range (3): for j in range (3): for r in range (3): k[i,j] = k[i,j] + (k_int[r]*(l[r]*l[i] + m[r]*m[i] + n[r]*n[i])*(l[r]*l[j] + m[r]*m[j] + n[r]*n[j])) return k def JR_e (km,JN,Ft): ''' Vetor de magnetizacao resultante sem correcao da desmagnetizacao. ''' JR = km.dot(Ft) + JN return JR def JRD_e (km,N1,N2,N3,JR): ''' Vetor de magnetizacao resultante com a correcao da desmagnetizacao. ''' I = np.identity(3) kn0 = km[:,0]*N1 kn1 = km[:,1]*N2 kn2 = km[:,2]*N3 kn = (np.vstack((kn0,kn1,kn2))).T A = I + kn JRD = (linalg.inv(A)).dot(JR) return JRD def x1_e (xp,yp,zp,xc,yc,h,l1,m1,n1): ''' Calculo da coordenada x no elipsoide input: xp,yp - Matriz: Coordenadas geograficas (malha). h - Profundidade do elipsoide. l1,m1,n1 - Orientacao do elipsoide (eixo x) output: x1 - Coordenada x do elipsoide. ''' x1 = (xp-xc)*l1+(yp-yc)*m1+(-zp-h)*n1 return x1 def x2_e (xp,yp,zp,xc,yc,h,l2,m2,n2): ''' Calculo da coordenada y no elipsoide input: xp,yp - Matriz: Coordenadas geograficas (malha). h - Profundidade do elipsoide. l2,m2,n2 - Orientacao do elipsoide (eixo y). output: x2 - Coordenada y do elipsoide. ''' x2 = (xp-xc)*l2+(yp-yc)*m2+(-zp-h)*n2 return x2 def x3_e (xp,yp,zp,xc,yc,h,l3,m3,n3): ''' Calculo da coordenada z no elipsoide input: xp,yp - Matriz: Coordenadas geograficas (malha). h - Profundidade do elipsoide. l3,m3,n3 - Orientacao do elipsoide (eixo z). output: x3 - Coordenada z do elipsoide. ''' x3 = (xp-xc)*l3+(yp-yc)*m3+(-zp-h)*n3 return x3 def p0_e (a,b,c,x1,x2,x3): ''' Constante da equacao cubica: s^3 + p2*s^2 + p0 = 0 input: a,b,c - Eixos do elipsoide. x1,x2,x3 - Eixo de coordenadas do elipsoide. output: p0 - Constante ''' p0 = (a*b*c)**2-(b*c*x1)**2-(c*a*x2)**2-(a*b*x3)**2 return p0 def p1_e (a,b,c,x1,x2,x3): ''' Constante da equacao cubica: s^3 + p2*s^2 + p0 = 0 input: a,b,c - Eixos do elipsoide. x1,x2,x3 - Eixo de coordenadas do elipsoide. output: p0 - Constante ''' p1 = (a*b)**2+(b*c)**2+(c*a)**2-(b**2+c**2)*x1**2-(c**2+a**2)*x2**2-(a**2+b**2)*x3**2 return p1 def p2_e (a,b,c,x1,x2,x3): ''' Constante da equacao cubica: s^3 + p2*s^2 + p0 = 0 input: a,b,c - Eixos do elipsoide. x1,x2,x3 - Eixo de coordenadas do elipsoide. output: p0 - Constante ''' p2 = a**2+b**2+c**2-x1**2-x2**2-x3**2 return p2 def p_e (p1,p2): ''' Constante input: p1,p2 - constantes da equacao cubica output: p - Constante. ''' p = p1-(p2**2)/3. return p def q_e (p0,p1,p2): ''' Constante input: p0,p1,p2 - constantes da equacao cubica output: q - Constante. ''' q = p0-((p1*p2)/3.)+2*(p2/3.)**3 return q def teta_e (p,q): ''' Constante angular (radianos) input: p - constante da equacao cubica q - constante output: teta - Constante. ''' teta = np.arccos(-q/(2*np.sqrt((-p/3.)**3))) #teta = np.arccos((-q/2.)*np.sqrt((-p/3.)**3)) return teta def lamb_e (p,teta,p2): ''' Maior raiz real da equacao cubica: s^3 + p2*s^2 + p0 = 0 input: p,p2 - constantes da equacao cubica teta - constante angular (radianos) output: lamb - Maior raiz real. ''' lamb = 2.*((-p/3.)**0.5)*np.cos(teta/3.)-(p2/3.) #lamb = 2*((-p/3.)*np.cos(teta/3.)-(p2/3.))**0.5 #lamb = 2*((-p/3.)*np.cos(teta/3.))**0.5 - (p2/3.) return lamb def mi_e (p,teta,p2): ''' Raiz intermediaria real da equacao cubica: s^3 + p2*s^2 + p0 = 0 input: p,p2 - constantes da equacao cubica teta - constante angular (radianos) output: mi - Raiz intermediaria real. ''' mi = -2.*((-p/3.)**0.5)*np.cos(teta/3.+np.pi/3.)-(p2/3.) return mi def ni_e (p,teta,p2): ''' Menor raiz real da equacao cubica: s^3 + p2*s^2 + p0 = 0 input: p,p2 - constantes da equacao cubica teta - constante angular (radianos) output: ni - Menor raiz real. ''' ni = -2.*np.sqrt(-p/3.)*np.cos(teta/3. - np.pi/3.)-(p2/3.) return ni def dlambx1_e (a,b,c,x1,x2,x3,lamb): ''' Derivada de lamb em relacao ao eixo x1 do elipsoide. input: a,b,c, - semi-eixos do elipsoide. x1,x2,x3 - Eixo de coordenadas do elipsoide. lamb - Maior raiz real da equacao cubica. output: dlambx1 - escalar ''' dlambx1 = (2*x1/(a**2+lamb))/((x1/(a**2+lamb))**2+(x2/(b**2+lamb))**2+((x3/(c**2+lamb))**2)) return dlambx1 def dlambx2_e (a,b,c,x1,x2,x3,lamb): ''' Derivada de lamb em relacao ao eixo x2 do elipsoide. input: a,b,c, - semi-eixos do elipsoide. x1,x2,x3 - Eixo de coordenadas do elipsoide. lamb - Maior raiz real da equacao cubica. output: dlambx2 - escalar ''' dlambx2 = (2*x2/(b**2+lamb))/((x1/(a**2+lamb))**2+(x2/(b**2+lamb))**2+((x3/(c**2+lamb))**2)) return dlambx2 def dlambx3_e (a,b,c,x1,x2,x3,lamb): ''' Derivada de lamb em relacao ao eixo x3 do elipsoide. input: a,b,c, - semi-eixos do elipsoide. x1,x2,x3 - Eixo de coordenadas do elipsoide. lamb - Maior raiz real da equacao cubica. output: dlambx3 - escalar ''' dlambx3 = (2*x3/(c**2+lamb))/((x1/(a**2+lamb))**2+(x2/(b**2+lamb))**2+((x3/(c**2+lamb))**2)) return dlambx3 def cte_m (a,b,c,lamb): ''' Fator geometrico do campo magnetico (fi) com relacao aos eixos do elipsoide input: a,b,c - semi-eixos do elipsoide lamb - Maior raiz real da equacao cubica. output: cte - constante escalar. ''' cte = 1/np.sqrt((a**2+lamb)*(b**2+lamb)*(c**2+lamb)) return cte def v_e (a,b,c,x1,x2,x3,lamb): ''' Constante do campo magnetico (fi) com relacao aos eixos do elipsoide input: a,b,c - semi-eixos do elipsoide x1,x2,x3 - Eixo de coordenadas do elipsoide. lamb - Maior raiz real da equacao cubica. output: v - matriz ''' V1 = x1/(a**2+lamb) V2 = x2/(b**2+lamb) V3 = x3/(c**2+lamb) return V1, V2, V3 def B1_e (m11,m12,m13,J,a,b,c): ''' Calculo do campo magnetico (Bi) com relacao aos eixos do elipsoide input: a,b,c - semi-eixos do elipsoide x1,x2,x3 - Eixo de coordenadas do elipsoide. dlambx1 - matriz: derivada de lambda em relacao ao eixo x1. cte - matriz v - matriz A - matriz: integrais do potencial J - vetor: magnetizacao output: B1 - matriz ''' B1 = 2*np.pi*a*b*c*(m11*J[0]+m12*J[1]+m13*J[2]) return B1 def B2_e (m21,m22,m23,J,a,b,c): ''' Calculo do campo magnetico (Bi) com relacao aos eixos do elipsoide input: a,b,c - semi-eixos do elipsoide x1,x2,x3 - Eixo de coordenadas do elipsoide. dlambx2 - matriz: derivada de lambda em relacao ao eixo x2. cte - matriz v - matriz B - matriz: integrais do potencial J - vetor: magnetizacao output: B2 - matriz ''' B2 = 2*np.pi*a*b*c*(m21*J[0]+m22*J[1]+m23*J[2]) return B2 def B3_e (m31,m32,m33,J,a,b,c): ''' Calculo do campo magnetico (Bi) com relacao aos eixos do elipsoide input: a,b,c - semi-eixos do elipsoide x1,x2,x3 - Eixo de coordenadas do elipsoide. dlambx3 - matriz: derivada de lambda em relacao ao eixo x3. cte - matriz v - matriz C - matriz: integrais do potencial J - vetor: magnetizacao output: B3 - matriz ''' B3 = 2*np.pi*a*b*c*(m31*J[0]+m32*J[1]+m33*J[2]) return B3 def Bx_c (B1,B2,B3,l1,l2,l3): ''' Calculo do campo magnetico (Bi) com relacao aos eixos geograficos input: B1,B2,B3 - vetores l1,l2,l3 - escalares. output: Bx - matriz ''' Bx = B1*l1+B2*l2+B3*l3 return Bx def By_c (B1,B2,B3,m1,m2,m3): ''' Calculo do campo magnetico (Bi) com relacao aos eixos geograficos input: B1,B2,B3 - vetores m1,m2,m3 - escalares. output: By - matriz ''' By = B1*m1+B2*m2+B3*m3 return By def Bz_c (B1,B2,B3,n1,n2,n3): ''' Calculo do campo magnetico (Bi) com relacao aos eixos geograficos input: B1,B2,B3 - vetores n1,n2,n3 - escalares. output: Bz - matriz ''' Bz = B1*n1+B2*n2+B3*n3 return Bz def Alambda_simp_ext3(a,b,c,lamb): ''' Integral do potencial utilizando o metodo de simpson. input: a,b,c - semi-eixos do elipsoide lamb - output: A - matriz ''' A = [] umax = 1000000.0 N = 300000 aux1 = 3./8. aux2 = 7./6. aux3 = 23./24. for l in np.ravel(lamb): h = (umax - l)/(N-1) u = np.linspace(l, umax, N) R = np.sqrt((a**2 + u) + (b**2 + u) + (c**2 + u)) f = 1./((a**2 + u)*R) aij = h*(aux1*f[0] + aux2*f[1] + aux3*f[2] + np.sum(f[3:N-3]) + aux3*f[-3] + aux2*f[-2] + aux1*f[-1]) A.append(aij) A = np.array(A).reshape((lamb.shape[0], lamb.shape[1])) return A def Blambda_simp_ext3(a,b,c,lamb): ''' Integral do potencial utilizando o metodo de simpson. input: a,b,c - semi-eixos do elipsoide lamb - output: B - matriz ''' B = [] umax = 1000000.0 N = 300000 aux1 = 3./8. aux2 = 7./6. aux3 = 23./24. for l in np.ravel(lamb): h = (umax - l)/(N-1) u = np.linspace(l, umax, N) R = np.sqrt((a**2 + u) + (b**2 + u) + (c**2 + u)) f = 1./((b**2 + u)*R) bij = h*(aux1*f[0] + aux2*f[1] + aux3*f[2] + np.sum(f[3:N-3]) + aux3*f[-3] + aux2*f[-2] + aux1*f[-1]) B.append(bij) B = np.array(B).reshape((lamb.shape[0], lamb.shape[1])) return B def Clambda_simp_ext3(a,b,c,lamb): ''' Integral do potencial utilizando o metodo de simpson. input: a,b,c - semi-eixos do elipsoide lamb - output: A - constante escalar ''' C = [] umax = 1000000.0 N = 300000 aux1 = 3./8. aux2 = 7./6. aux3 = 23./24. for l in np.ravel(lamb): h = (umax - l)/(N-1) u = np.linspace(l, umax, N) R = np.sqrt((a**2 + u) + (b**2 + u) + (c**2 + u)) f = 1./((c**2 + u)*R) cij = h*(aux1*f[0] + aux2*f[1] + aux3*f[2] + np.sum(f[3:N-3]) + aux3*f[-3] + aux2*f[-2] + aux1*f[-1]) C.append(cij) C = np.array(C).reshape((lamb.shape[0], lamb.shape[1])) return C def Dlambda_simp_ext3(a, b, c, lamb): ''' Integral do potencial utilizando o metodo de simpson. input: a,b,c - semi-eixos do elipsoide lamb - output: D - constante escalar ''' D = [] umax = 1000000.0 N = 300000 aux1 = 3./8. aux2 = 7./6. aux3 = 23./24. for l in np.ravel(lamb): h = (umax - l)/(N-1) u = np.linspace(l, umax, N) R = np.sqrt((a**2 + u) + (b**2 + u) + (c**2 + u)) f = 1./R dij = h*(aux1*f[0] + aux2*f[1] + aux3*f[2] + np.sum(f[3:N-3]) + aux3*f[-3] + aux2*f[-2] + aux1*f[-1]) D.append(dij) D = np.array(D).reshape((lamb.shape[0], lamb.shape[1])) return D def parametros_integrais(a,b,c,lamb): ''' a: escalar - semi eixo maior b: escalar - semi eixo intermediario c: escalar - semi eixo menor lamb - Maior raiz real da equacao cubica. ''' k = np.zeros_like(lamb) k1 = ((a**2-b**2)/(a**2-c**2))**0.5 k.fill(k1) k2 = ((a**2-b**2)/(a**2-c**2))**0.5 teta_linha = np.arcsin(((a**2-c**2)/(a**2+lamb))**0.5) teta_linha2 = np.arccos(c/a) F = scipy.special.ellipkinc(teta_linha, k) E = scipy.special.ellipeinc(teta_linha, k) F2 = scipy.special.ellipkinc(teta_linha2, k2) E2 = scipy.special.ellipeinc(teta_linha2, k2) return F,E,F2,E2,k,teta_linha def integrais_elipticas(a,b,c,k,teta_linha,F,E): ''' a: escalar - semi eixo maior b: escalar - semi eixo intermediario c: escalar - semi eixo menor k: matriz - parametro de geometria teta_linha: matriz - parametro de geometria F: matriz - integrais normais elipticas de primeiro tipo E: matriz - integrais normais elipticas de segundo tipo ''' A2 = (2/((a**2-b**2)*(a**2-c**2)**0.5))*(F-E) B2 = ((2*(a**2-c**2)**0.5)/((a**2-b**2)*(b**2-c**2)))*(E-((b**2-c**2)/(a**2-c**2))*F-((k**2*np.sin(teta_linha)*np.cos(teta_linha))/(1-k**2*np.sin(teta_linha)*np.sin(teta_linha))**0.5)) C2 = (2/((b**2-c**2)*(a**2-c**2)**0.5))*(((np.sin(teta_linha)*((1-k**2*np.sin(teta_linha)*np.sin(teta_linha))**0.5))/np.cos(teta_linha))-E) return A2,B2,C2
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 300, 1292, 70, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 198, 6738, 3735, 72, 25440, 13, 70, 4108, 1972...
1.791159
15,768
from do import DigitalOcean import argparse import json if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-token') args = parser.parse_args() # parse_input(args.file) do_play(args.token)
[ 6738, 466, 1330, 10231, 46607, 198, 198, 11748, 1822, 29572, 198, 11748, 33918, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, 220...
2.722222
90
import cPickle as pickle import pandas as pd if __name__ == '__main__': fnames = set(['clinton_tweets.json', 'trump_tweets.json']) for fname in fnames: df = pd.read_json('data/' + fname) df = df.transpose() df = df['text'] pickle.dump([(i, v) for i, v in zip(df.index, df.values)], open(fname, 'wb'))
[ 11748, 269, 31686, 293, 355, 2298, 293, 198, 11748, 19798, 292, 355, 279, 67, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 277, 14933, 796, 900, 7, 17816, 37821, 62, 83, 732, 1039, 13, 1775...
2.117284
162