content
stringlengths
5
1.05M
#!/usr/bin/env python3 class BarItem(object): valid_options = set(['full_text', 'short_text', 'color', 'min_width', 'align', 'name', 'instance', 'urgent', 'separator', 'separator_block_width']) COLOR_DEFAULT = '#FFFFFF' def __init__(self, name): a...
# a1.py advice for manhattan distance taken from # https://stackoverflow.com/questions/39759721/calculating-the-manhattan-distance-in-the-eight-puzzle # https://www.geeksforgeeks.org/sum-manhattan-distances-pairs-points/ from search import * import time import random # ... SOLVED_STATE = (1, 2, 3, 4, 5, 6, 7, 8, 0) ...
from requests_oauthlib import OAuth2Session from flask import Flask, request, redirect, session, url_for from flask.json import jsonify import os from requests_oauthlib.compliance_fixes import facebook_compliance_fix app = Flask(__name__) # This information is obtained upon registration of a new GitHub OAuth # applic...
############################################################################ # This Python file is part of PyFEM, the code that accompanies the book: # # # # 'Non-Linear Finite Element Analysis of Solids and Structures' # # R. ...
#!/usr/bin/env python ''' @todo: turn this into a real test runner for everything in the test subdir. ''' import sys from aisutils.BitVector import BitVector from aisutils import binary import ais_msg_1 import ais_msg_8 import sls.waterlevel if __name__=='__main__': # Try to parse some binary message if Fal...
import streamlit as st import pandas as pd from itertools import groupby from datetime import datetime import re from pretty_html_table import build_table st.set_page_config(layout='wide') JIRA_REGEX= "[A-Z]{2,}-\d+" def parse_blame(chunk): branch = chunk[0].split()[0] line_start = chunk[0].split()[1] ...
import ast import csv import korbinian import korbinian.utils as utils import numpy as np import os import pandas as pd import sys import time # import debugging tools from korbinian.utils import pr, pc, pn, aaa def get_TM_indices_from_TMSEG_topo_str(topo_str, TM_symbol="H"): """Get TM indices from TMSEG topology ...
# -*- coding: utf-8 -*- """ Swets NDVI filtering author: Laust Færch @ DHI GRAS Created on 2020/08/29 Based on the article: Swets, D.L, Reed, B.C., Rowland, J.D., Marko, S.E., 1999. A weighted least-squares approach to temporal NDVI smoothing. In: Proceedings of the 1999 ASPRS Annual Conference, Portland, Oregon, pp. ...
import json from django import forms from commons.file import file_utils from commons import file_name_tools from wikis.attachments import attachment_tool from django.core.exceptions import ValidationError from datetime import datetime from uzuwiki.settings_static_file_engine import MAX_FILE_SIZE, MAX_FILE_SIZE_MESSAGE...
# Jared Dyreson # CPSC 386-01 # 2021-11-29 # jareddyreson@csu.fullerton.edu # @JaredDyreson # # Lab 00-04 # # Some filler text # """ This module contains a basic "factory" pattern for generating new Display instances """ import abc import dataclasses import functools import json import pathlib import pygame import sy...
from intent_parser.server.intent_parser_server import app, IntentParserServer import os import logging.config import os logger = logging.getLogger(__name__) def _setup_logging(): logging.basicConfig(level=logging.INFO, format="[%(levelname)-8s] %(asctime)-24s %(filename)-23s line:%(lineno)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 10 21:32:34 2019 @author: teddy """ from docx import Document from docx.shared import RGBColor #from docx.dml.color import ColorFormat def getText(filename): doc = Document(filename) fullText = [] for para in doc.paragraphs: ...
######################################################## # Copyright (c) 2015-2017 by European Commission. # # All Rights Reserved. # ######################################################## extends("BaseKPI.py") """ Consumption (Wh) ------------------ Indexed by * scope * deli...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ ########################################################################## ZipMe : GAE Content Downloader ########################################################################## Just add this lines in your app.yaml : - url: /zipme script: zipme.py ####...
""" Models for mongo database """ # from pymongo.write_concern import WriteConcern from pymodm import MongoModel, fields class Testing(MongoModel): onefield = fields.CharField() # NOTE: do not touch connection here, see experiments/mongo.py # class Meta: # connection_alias = 'test' # # w...
# Generated by Django 2.2.1 on 2019-05-10 22:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wells', '0082_auto_20190510_0000'), ('wells', '0082_merge_20190510_1926'), ] operations = [ ]
from unittest import TestCase from semanticpy.vector_space import VectorSpace from nose.tools import * class TestSemanticPy(TestCase): def setUp(self): self.documents = ["The cat in the hat disabled", "A cat is a fine pet ponies.", "Dogs and cats make good pets.","I haven't got a hat."] def it_sh...
#! /usr/bin/env python from yices import * cfg = Config() cfg.default_config_for_logic('QF_BV') ctx = Context(cfg) bv32_t = Types.bv_type(32) x = Terms.new_uninterpreted_term(bv32_t, 'x') y = Terms.new_uninterpreted_term(bv32_t, 'y') zero = Terms.bvconst_integer(32, 0) fmla0 = Terms.bvsgt_atom(x, zero) fmla1 = Te...
"""A virtual pumpkin which flash neopixels and play sound""" import random import math import time import board import digitalio import audioio import busio import adafruit_vl53l0x import adafruit_thermistor import neopixel ######################### # -- slide switch to enable/disable running loop slide_switch = digit...
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import os import json import ctypes as ct from .._constants import VSCODE_CREDENTIALS_SECTION def _c_str(string): return ct.c_char_p(string.encode("utf-8")) clas...
# -*- coding: utf-8 -*- # # Copyright (C) 2021 Northwestern University. # # invenio-subjects-mesh is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see LICENSE file for more # details. """MeSH subjects_mesh.yaml writer.""" from pathlib import Path import yaml def writ...
# Copyright (c) 2013 eBay Inc. # Copyright (c) 2013 OpenStack Foundation # # 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 # # ...
# Задача 3. Вариант 30. #Напишите программу, которая выводит имя "Илья Арнольдович Файзильберг", и запрашивает его псевдоним. # Shemenev A.V # 14.03.16 print("Герой нашей программы Илья Арнольдович Файзильберг") print("Под каким именем мы знаем этого человека? Ваш ответ:") x=input() print ("Все верно, псевдоним - " +x)...
from models.generators.fcn32s import FCN32s from models.generators.fcn16s import FCN16s from models.generators.fcn8s import FCN8s
from django.conf.urls import url from messenger import views urlpatterns = [ url(r'^messenger/send', views.send, name='send'), url(r'^messenger/read', views.read, name='read') ]
#!/usr/bin/env python3 import argparse import progressbar import requests import os import sys sourceapp = "AS50559-DIVD_NL" def rest_get(call,resource,retries=3): url = "https://stat.ripe.net/data/{}/data.json?resource={}&sourceapp={}".format(call,resource,sourceapp) try: response = requests.get(url, timeout = ...
# Every line of these files consists of an image, i.e. 785 numbers between 0 and 255. size 28 x 28 # first no is label import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.l...
#!/usr/bin/env python """ @package mi.dataset.parser.test @file marine-integrations/mi/dataset/parser/test/ @author Jeff Roy @brief Test code for a wc_sbe_cspp data parser wc_sbe_cspp is based on cspp_base.py test_wc_sbe_cspp.py fully tests all of the capabilities of the base parser. That level of testing is omitted...
from datetime import datetime from os.path import dirname, join import pytest # noqa from city_scrapers_core.constants import ADVISORY_COMMITTEE, PASSED from city_scrapers_core.utils import file_response from freezegun import freeze_time from city_scrapers.spiders.cuya_audit import CuyaAuditSpider test_response = f...
from django.db import models from djchoices import DjangoChoices, ChoiceItem class UserStatuses(DjangoChoices): enter_address = ChoiceItem() enter_name = ChoiceItem() start = ChoiceItem() allowed = ChoiceItem() enter_org_name = ChoiceItem() enter_role = ChoiceItem() allowed_group = ChoiceI...
my_list= [3, 4, 6, 2] my_list1 = list(("Hello World"))
from itertools import product as product from math import sqrt as sqrt import numpy as np import torch import torch.nn as nn import torch.nn.init as init from torch.autograd import Function # from utils.box_utils import decode, nms # from utils.config import Config class L2Norm(nn.Module): def __init__(self, n_c...
from django.shortcuts import render from django.template import RequestContext, loader from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.http import JsonResponse import simplejson as json import requests from django import template import urllib from collections i...
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. # This file should only be present in a source checkout, and never in a release # package, to allow us to determine whether we're running in a development or # production mode.
import math if __name__ != "common": from objects import glob import time import json from common.ripple import userUtils def load_achievement_data(ACHIEVEMENT_BASE, ACHIEVEMENT_KEYS, ACHIEVEMENT_STRUCT): LENGTH = 0 ACHIEVEMENTS = [] for struct in ACHIEVEMENT_STRUCT: LENGTH = max(LENGTH, len(ACHIEVEMENT_KEYS...
from hashlib import pbkdf2_hmac, md5 import binascii from Crypto.Cipher import AES import os import sys def generate_key(title_id, pwd): # remove 00 padding from title id title_idGen = title_id[2:] # get secret string, append title id, and convert to binary string secret = binascii.unhexlify('fd040105...
# https://github.com/python-poetry/poetry/issues/11 import glob import os from distutils.command.build_ext import build_ext from distutils.core import Extension from distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError def filter_extension_module(name, lib_objs, lib_headers): return...
# -*- coding: utf-8 -*- # Created by: Michael Lan import os import sys import re from PySide2.QtWidgets import QApplication, QMainWindow from PySide2 import QtGui, QtWidgets, QtCore from ui_main import Ui_Dialog from pyside_material import apply_stylesheet from dbconnection import connect, insert_data, close, valida...
""" $lic$ Copyright (C) 2016-2017 by The Board of Trustees of Stanford University This program is free software: you can redistribute it and/or modify it under the terms of the Modified BSD-3 License as published by the Open Source Initiative. If you use this program in your research, we request that you reference th...
# Basic Frame Differencing Example # # Note: You will need an SD card to run this example. # # This example demonstrates using frame differencing with your OpenMV Cam. It's # called basic frame differencing because there's no background image update. # So, as time passes the background image may change resulting in iss...
import tetris.input.gamepad as gp import pygame pygame.init() if __name__ == "__main__": sticks = [] qs = gp.PygameEventReader.q for stick in gp.get_available(): print(gp.display_gamepad_info(stick) + '\n') sticks.append(gp.GamepadWrapper(stick.get_id())) print('Listening...') ...
import datetime # enables the start time elements in date and time format # Interaction for patient with learning disabilities # "psychol_assessment", # "iapt", # "cmh_for_smi" # Mental health interaction 1: Psychological assessment def psychol_assessment(patient, environment, patient_time): encounter = { ...
def temp(input, output): img = cv2.imread(input) xmap, ymap = utils.buildmap_1(Ws=800, Hs=800, Wd=800, Hd=800, fov=193.0) cv2.imwrite(output, cv2.remap(img, xmap,ymap,cv2.INTER_LINEAR))
from datetime import date # random person class Person: # def __new__(cls, name, age): # print("New object called") # # super.__new__(cls[name, age]) def __init__(self, name, age): print('__init__ called') self.name = name self.age = age @classmethod def from...
import logging from discord.ext import tasks, commands from naotomori.cogs.source.anime import _9anime, gogoanime from naotomori.cogs.sourcecog import SourceCog logger = logging.getLogger('NaoTomori') class AnimeCog(SourceCog): """ AnimeCog: extends the SourceCog. """ def __init__(self, bot): ...
def params_to_string(task: dict) -> dict: for k in task['parameters'].keys(): if (isinstance(task['parameters'][k], int) or isinstance(task['parameters'][k], float)): task['parameters'][k] = str(task['parameters'][k]) return task
from distutils.core import setup from Cython.Build import cythonize setup(ext_modules = cythonize('./source/cython_functions.pyx',compiler_directives={'language_level' : "3"}))
from .chem import BOND_TYPES, BOND_NAMES, set_conformer_positions, draw_mol_image, update_data_rdmol_positions, \ update_data_pos_from_rdmol, set_rdmol_positions, set_rdmol_positions_, get_atom_symbol, mol_to_smiles, \ remove_duplicate_mols, get_atoms_in_ring, get_2D_mol, draw_mol_svg, GetBestRMSD from ...
# -*- coding: utf-8 -*- """ Created on Thu June 17 11:53:42 2021 @author: Pavan Tummala """ import os, numpy as np import cv2 import random import torch import torch.utils.data as data import xml.etree.ElementTree as ET from abc import ABCMeta, abstractmethod import scipy.cluster.vq as vq import pickle import pandas a...
# Copyright (c) 2011-2013 Kunal Mehta. All rights reserved. # Use of this source code is governed by a BSD License found in README.md. from django.conf import settings from django.contrib.auth import authenticate, login, logout from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResp...
import unittest import torchtext.vocab as v import han.encode.sentence as s class SentenceEncoderTestCase(unittest.TestCase): def test(self): vocab = v.build_vocab_from_iterator([["apple", "is", "tasty"]]) sut = s.SentenceEncoder(vocab) res = sut.forward(["apple is tasty", "tasty is appl...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from pathlib import Path from typing import Any, Dict, List, Optional import torch from torch import Tensor from fairseq impo...
from .abstract_choices_factory import AbstractChoicesFactory from .choice import Choice from src.round import Output from random import randrange class PlayerVsComChoicesFactory(AbstractChoicesFactory): def make_player1_choice(): player_choice = Choice('placeholder') while not player_choice.is_val...
from apple_health.util import parse_date, parse_float DATE_COMPONENTS = "@dateComponents" ACTIVE_ENERGY_BURNED = "@activeEnergyBurned" ACTIVE_ENERGY_BURNED_GOAL = "@activeEnergyBurnedGoal" ACTIVE_ENERGY_BURNED_UNIT = "@activeEnergyBurnedUnit" APPLE_EXERCISE_TIME = "@appleExerciseTime" APPLE_EXERCISE_TIME_GOAL = "@appl...
# Warning: Don't edit file (autogenerated from python -m dev codegen). ROBOCODE_GET_LANGUAGE_SERVER_PYTHON = "robocode.getLanguageServerPython" # Get a python executable suitable to start the language server. ROBOCODE_GET_PLUGINS_DIR = "robocode.getPluginsDir" # Get the directory for plugins. ROBOCODE_CREATE_ACTIVIT...
import urllib2 import threading from bs4 import BeautifulSoup import re import json import sys import os import django from stock_list import getlist, getLSEList from extract_stock_info import get_info, getLSEInfo from extract_stock_history import get_historical_info from extract_sector_history import get_sector_histo...
import Tkinter as tk class NatnetView: def __init__(self, parent, reader): self.parent = parent self.reader = reader self.setup() def __del__(self): self.destroy() def destroy(self): self.frame.grid_forget() def setup(self): # container self.fr...
import gmpy2 from gmpy2 import ( mpz, powmod, mul, invert, ) B = 2 ** 20 p = mpz('13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171') g = mpz('117178298803662070095161175963353670885580849999989522...
#单一状态 class Borg: __shared_state = {"1":"2"} def __init__(self): self.x = 1 self.__dict__ = self.__shared_state b = Borg() b1 = Borg() b.x = 4 print("Borg Object b:",b) print("Borg Object b1:",b1) print("Object state b:",b.__dict__) print("Object state b1:",b1.__dict__)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 25 06:10:44 2018 @author: Kazuki """ import numpy as np import pandas as pd from tqdm import tqdm import gc, os from collections import defaultdict import sys sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary') #import lgbextension as...
# flake8: noqa ''' All step-related classes and factories ''' from .base_steps import ( BaseStep, BaseStepFactory, BaseValidation, ) from .steps import TestStep from .outputs import OutputValueStep from .steps_aggregator import StepsAggregator from .validations import ( Validation, XPathValidatio...
#!/usr/bin/env python # -*- coding: utf-8 -*- import csv import math # Respect seigot class Waypoint: way_point = 0 def __init__(self, path): self.points = [] # self.way_point = 0 with open(path) as f: lines = csv.reader(f) for l in lines: p...
import typing from ariadne import SchemaDirectiveVisitor from ariadne.types import GraphQLResolveInfo from graphql import default_field_resolver from pytimeparse import parse as parse_duration from .utils.rate_limit import RateLimit, TooManyRequests class DateDirective(SchemaDirectiveVisitor): def visit_field_d...
import random import math import operator from collections import Counter, defaultdict import twokenize import peewee from models import database, SMS, Contact class NaiveBayes(object): def __init__(self): self.doccounts = Counter() self.classcounts = Counter() self.wordcounts = defaultdic...
from LucidDynamodb import DynamoDb from LucidDynamodb.exceptions import ( TableNotFound ) import logging logging.basicConfig(level=logging.INFO) if __name__ == "__main__": try: db = DynamoDb() db.delete_table(table_name='dev_jobs') logging.info("Table deleted successfully") tabl...
from .queries import *
import Transformation import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl def calc_cov_ellipse(a, b, d): s = np.array([[a, b], [b, d]]) (w, v) = np.linalg.eig(s) angle = np.degrees(np.arctan2(v[1, 0], v[0, 0])) return 2*np.sqrt(w[0]), 2*np.sqrt(w[1]), angle class SubPlot: ...
from django.db import models from django.utils.text import gettext_lazy as _ from common.models import CommonData, ErrorMessages from jobs.models import JobOffer, Profile class Comment(CommonData): model_name = 'Comment' profile: Profile = models.ForeignKey( to=Profile, on_delete=models.PROT...
#!/usr/bin/env python # -*- coding: utf-8 -*-# # MIT License # # Copyright (c) 2019 Pim Witlox # # 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 limita...
from hello.hello import print_hello from world.world import print_world def main(): print_hello() print_world() return if __name__ == '__main__': main()
from django.contrib.sites.models import Site from .settings import CMS_TEMPLATES from django.contrib.auth.models import User # Default page settings Not used for installation # Content for adding a page # Still under development title = 'Django CMS setup' description = 'Open Source programming at its best' template =...
from .shared import replace_gender #TODO At some point, I want to be able to pass only part of the subject tree # to child snippets. class Snippet(object): ''' The base snippet class that all snippets will extend. Responsible for listing required and optional subject data, validating a passed subject, genera...
#!/usr/bin/python2.7 ############################################################### #### Assembled by: Ian M. Pendleton ###################### #### www.pendletonian.com ###################### ############################################################### # Updated December 17, 2019 ### T...
#!/usr/bin/env python from setuptools import setup from setuptools.command.install import install as _install class install(_install): def pre_install_script(self): pass def post_install_script(self): pass def run(self): self.pre_install_script() _install.run(self) ...
bg_black = "\u001b[48;5;0m" bg_gray = "\u001b[48;5;8m" bg_red = "\u001b[48;5;9m" bg_green = "\u001b[48;5;10m" bg_yellow = "\u001b[48;5;11m" bg_blue = "\u001b[48;5;12m" bg_purple = "\u001b[48;5;13m" bg_cyan = "\u001b[48;5;14m" bg_white = "\u001b[48;5;15m" def customColor(number): print(f"\u001b[48;5;{number}m")
# Copyright 2021 VMware, Inc. # SPDX-License: Apache-2.0 import logging import salt.exceptions import saltext.vmware.utils.common as utils_common import saltext.vmware.utils.esxi as utils_esxi from salt.defaults import DEFAULT_TARGET_DELIM from saltext.vmware.utils.connect import get_service_instance log = logging.ge...
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above...
a = int(input()) b = int(input()) cont = a if a <= b: for i in range(a, b+1): for n in range(1, 10+1): total = cont * n print(f'{cont} x {n} = {total}') print('-'*10) cont += 1 else: print('Nenhuma tabuada no intervalo!') ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 6 07:51:51 2018 @author: tuheenahmmed """ def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the leng...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """ Снежинка / Snowflake """ # Оригинал: http://www.cyberforum.ru/pascalabc/thread994987.html # uses graphABC; # const k=8; # var x,y:integer; # procedure snow (x0,y0,r,n:integer); # const t=2*pi/k; # var i,x,y:integer; # begin # for i:=1 to ...
## # Copyright (c) 2007-2016 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 l...
'''Author: Brandon Trabucco, Copyright 2019 Helper functions to display and run a simple game''' from game_engine.colors import * from game_engine.tiles import * from game_engine.stacks import * from game_engine.drawable import Drawable import random random.seed(12345) ##################################### # lets...
import rospy from geometry_msgs.msg import Twist from std_msgs.msg import String import time import sys, select, termios, tty import donkeycar as dk # import keyboard # using module keyboard from pynput import keyboard ############################################################################################# # ...
from os import getcwd from re import findall from re import match def parseStep(line): state = match(r"(on|off)", line).groups()[0] x1, x2, y1, y2, z1, z2 = map(int, findall(r"(-?\d+)", line)) return state, (x1, x2), (y1, y2), (z1, z2) def main(): with open(f"{getcwd()}/2021/day22/input.txt") as fi...
#!/usr/bin/env python # -*- coding: utf-8 -*- " Help code for sl training " import traceback import numpy as np import torch import torch.nn as nn from pysc2.lib.actions import RAW_FUNCTIONS as F from alphastarmini.core.arch.agent import Agent from alphastarmini.core.sl.feature import Feature from alphastarmini....
from ..catalogs.in_memory import Catalog from .dataframe import DataFrameAdapter import dask.dataframe import pandas class ExcelReader(Catalog): """ Read the sheets in an Excel file. This maps the Excel file, which may contain one of more spreadsheets, onto a "Catalog" of tabular structures. Ex...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tool to manage local 3D Beacon install .. currentmodule:: bio3dbeacon .. moduleauthor:: Ian Sillitoe <i.sillitoe@ucl.ac.uk> """ from .version import __version__, __release__ # noqa
import mido import cv2 #Color library using dictionary from RGB to velocity value of the Launchpad MK2 from ClearLaunchpad import RemoveNotes, ClearScreen from FirstMido import FillNotes cap = cv2.imread("Velocity2RGB.png") Complete = cap.copy() while(True): Mat = cv2.inRange(cap, (0, 0, 0), (254, 254, 254)) ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Copyright (c) 2012, Rui Carmo Description: In-process job management License: MIT (see LICENSE.md for details) """ import os, sys, logging, time, traceback, multiprocessing, gc from cPickle import loads, dumps from Queue import PriorityQueue, Empty from threading import T...
# Copyright 2019 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
#!/usr/bin/python # # Copyright 2019 Polyaxon, 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 o...
grk_tws = [['G946'], ['G5206'], ['G3428', 'G3429', 'G3430', 'G3431', 'G3432'], ['G3841'], ['G1041', 'G2379'], ['G281'], ['G32', 'G743', 'G2465'], ['G32', 'G743', 'G218', 'G1472', 'G2025', 'G3462', 'G5545', 'G5548'], ['G500'], ['G651', ' G652', ' G2491', ' G5376', ' G5570'], ['G322', 'G606', 'G1299', 'G1303', 'G1935', '...
import os # os is only used for finding a dynamic absolute path to the I/O files absolute_path = os.path.dirname(os.path.abspath(__file__)) inn = absolute_path + '/rom.in' outt = absolute_path + '/rom.out' # Open input files fin = open(inn) fout = open(outt, 'w') # Get first line for array size firstLine = fin.read...
import factory from karp.domain.model import Entry, Resource class ResourceFactory(factory.Factory): class Meta: model = Resource entity_id = factory.
#!/usr/bin/env python3 # Copyright 2020 Christian Henning # # 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 l...
import glob import os import pandas as pd import pytz from dateutil import parser, tz from matplotlib import pyplot as plt fp = "C:\\Users\\Robert\\Documents\\Uni\\SOLARNET\\HomogenizationCampaign\\rome\\" file = os.path.join(fp, "data.csv") data = pd.read_csv(file, delimiter=" ") print(data) converted_data = [] f...
from test.common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc def test_escapes_work_in_string_literals(): assert query_html_doc('', '"foo&#10;bar"') == expected_result(""" foo bar""") assert query_html_doc('', "'foo&#10;bar'") == expected_result(""" foo ...
import argparse import sys parser = argparse.ArgumentParser(description='Extract gold entities conll file.') parser.add_argument('--input_file') args = parser.parse_args() reading = 0 golds = [] sentences = [] with open(args.input_file, 'r') as i_file: for line in i_file: line = line.strip() if li...
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.contrib.auth.models import User from django.http import Http404 # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) pic = models.ImageField(upload_to='...
import torch import torch.utils.data import os import numpy as np from PIL import Image from utils.util import * def loaderAndResize(path): return Image.open(path).resize((128, 128)) def loader(path): return Image.open(path) class GlassandAttrFaceImageLoader(torch.utils.data.Dataset): def __init__(...