content
stringlengths
5
1.05M
#!/usr/bin/python3 # -*-coding:utf-8-*- __author__ = "Bannings" from collections import OrderedDict def checkio(data): data = ["".join(OrderedDict.fromkeys(d)) for d in data] letters = sorted(set("".join(data))) ans = "" while letters: for letter in letters: if not any(letter in d...
import logging import os from phenoai.manager.weather_station_manager import WeatherStationManager from phenoai.manager.data_persistance_manager import DataPersistanceManager from typing import Optional from settings.constants import VITIGEOSS_CONFIG_FILE, VITIGEOSS_DATA_ROOT, VITIGEOSS_PHENO_PHASES_DIR from settings.i...
""" Binary search Slicing is O(k) Complexity: O(log(n)) """ def search_binary(input_array, value): low = 0 high = len(input_array) - 1 le = len(input_array) if le == 0: return False else: mid = (low + high) // 2 if input_array[mid] == value: return True ...
import os import pathlib import shutil import airsimdroneracinglab def mod_client_file(): as_path = pathlib.Path(airsimdroneracinglab.__file__).resolve().parent dir_path = os.path.dirname(os.path.realpath(__file__)) mod_path = os.path.join(dir_path, 'client.py') target_path = os.path.join(as_path, 'cl...
#!/usr/bin/python3 import os from formula import formula system = os.environ.get("RIT_SYSTEM") linux_os = os.environ.get("RIT_LINUX_OS") formula.Run(system, linux_os)
#notes: figure out how to import word2vec embeddings #pre-process -- text -> onehot --> padding? --> embed --> concat --> lstm # --> numeric input #create second model w/ NLP pipeline vocab_size = 1000 #revisit model_inputN = layers.Input(shape = (19,125)) #numeric...
#!/usr/bin/env python # manager class allows creation of manager object to use as a higher # level API to connect to and interact with the YANG models on the device from ncclient import manager device = { 'host': 'r1.lab.local', 'username': 'wwt', 'password': 'WWTwwt1!', 'port': 830 } ...
import pygame #def drawBall(window): # ball = pygame.image.load("ball2.png") # window.blit(ball,(int(ball_pos[x]-10),int(ball_pos[y]-10))) from INI import * #import pygame class Ball: def __init__(self, window): self.window = window #self.ball = pygame.image.load("ball2.png") se...
""" edx-lint ======== A collection of code quality tools: - A few pylint plugins to check for quality issues pylint misses. - A command-line tool to generate config files like pylintrc from a master file (part of edx_lint), and a repo-specific tweaks file. """ import setuptools def load_requirements(*requireme...
#!/usr/bin/env python3 # -*- coding: iso-8859-1 -*- #pylint: disable=missing-docstring, line-too-long, empty-docstring, too-many-locals, invalid-name, trailing-newlines #------------------------------------------------------------------------------- # # Project: ViRES-Aeolus # Purpose: Aeolus -- get ...
# # (C) 2014-2017 Seiji Matsuoka # Licensed under the MIT License (MIT) # http://opensource.org/licenses/MIT # """Debug utility""" import cProfile import os import pstats import sys from collections import deque from itertools import chain def total_size(obj, verbose=False): """Approximate memory size""" see...
from __future__ import annotations from typing import List from logger import logger from common_utils.base.basic import BasicLoadableHandler, BasicHandler from .objects import NDDS_Annotation_Object class NDDS_Annotation_Object_Handler( BasicLoadableHandler['NDDS_Annotation_Object_Handler', 'NDDS_Annotation_Obje...
import json from operator import attrgetter from os.path import expanduser from pathlib import Path from typing import List, Tuple from pydantic import BaseModel, ValidationError import pytest from reponews.config import ActivityPrefs, Configuration from reponews.types import ActivityType, Repository, User from reponew...
class CachedAttr: def __init__(self, name, func) -> None: self.name = name self.func = func def __get__(self, instance, owner): try: return instance.__dict__[self.name] except KeyError: result = self.func() instance.__dict__[self.name] = resul...
from datetime import datetime from .db import db class Song(db.Model): __tablename__ = "songs" id = db.Column(db.INTEGER, primary_key=True) user_id = db.Column(db.INTEGER, db.ForeignKey("users.id")) artist = db.Column(db.String(50)) name = db.Column(db.String(50), nullable=False) url = db.Colu...
from python.test.test_game_state import DEFAULT_ELEVATION_MAP from python.lib.board_state import BoardState from .constants import ( DEFAULT_ELEVATION_MAP_SHAPE, DEFAULT_ELEVATION_MAP, DEFAULT_EXPECTED_OUTPUT_GRID_MAP, ) def test_BoardState_create_grid_map_from_elevation_array(): elevation_map_2d = D...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
s1 = ["s1","s2","s3","s4","s5"] s2 = s1[2:4] print(f"Result: {s2}")
import json from os import path from punica.core.base_project import BaseProject from punica.exception.punica_exception import PunicaException, PunicaError class ProjectWithConfig(BaseProject): def __init__(self, project_dir: str = ''): super().__init__(project_dir) pj_config_file_path = path.jo...
# from ...geometry.Bisector import * from ...Util import * from ...graph.Vertex import * from Event import * from ...geometry.BisectorRay import * from ..Breakpoint import * class CircleEvent(Event): # def __init__(self, arc): def __init__(self, arc, causing_event_is_site_type): self....
import numpy as np from torch import nn from torchvision import models class FineTuneModel(nn.Module): """Model used to test a ResNet50 with finetuning FC layers""" def __init__(self, num_classes): super(FineTuneModel, self).__init__() # Everything except the last linear layer original...
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ import unittest from cfn_policy_validator.application_error import ApplicationError from cfn_policy_validator.parsers.utils.node_evaluator import NodeEvaluator from cfn_policy_validator.tests.parsers_tests import ...
""" Test an AppSettings without a prefix """ from django.test import TestCase, override_settings from . import app_settings_no_prefix, app_settings_with_prefix class TestAppSettingsWithoutPrefix(TestCase): def test_attribute_default(self): self.assertEqual(app_settings_no_prefix.UNSET_ATTRIBUTE, "default...
from rest_framework.routers import DefaultRouter from ..viewsets.dynamic_menu import DynamicMenuViewSet router = DefaultRouter() router.register(prefix=r'menu', viewset=DynamicMenuViewSet, basename='menu') urls = router.urls
""" Python implementation of full-gmm-test.cc """ import unittest import numpy as np from kaldi.base import math as kaldi_math from kaldi.matrix import Matrix, Vector from kaldi.matrix.common import MatrixTransposeType from kaldi.matrix.functions import vec_mat_vec from kaldi.matrix.packed import SpMatrix, TpMatrix fr...
from typing import Optional, Union, List, Dict import pandas as pd import torch def convert_pandas_to_torch_tensor( data_batch: pd.DataFrame, columns: Optional[Union[List[str], List[List[str]]]] = None, column_dtypes: Optional[Union[torch.dtype, List[torch.dtype]]] = None, ) -> Union[torch.Tensor, List[t...
#!/usr/bin/env python # coding: utf-8 # # Navigation # In this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893). # ### 1. Start the Environment import o...
import fileimput import random import json from State import State if __name__ == '__main__': state = State() # for line in fileinput.input(bufsize=1): # changes = json.loads(line)['cells'] # for change in changes: # state.change(change) # # print(state.getJSON())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Zoe Sysinfo - https://github.com/rmed/zoe-sysinfo # # Copyright (c) 2015 Rafael Medina García <rafamedgar@gmail.com> # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentati...
import socket class c: hp = 50 def client_program(message): global hp host = input('please enter the hostname: \n') # as both code is running on same pc port = int(input('please enter the port: \n')) # socket server port number client_socket = socket.socket() # instantiate ...
# Copyright (C) 2015-2016 Ammon Smith and Bradley Cai # Available for use under the terms of the MIT License. __all__ = [ 'depends', 'config_fields', 'run' ] from do_target import targetobj from testparser import TestParser import re import os import testobj depends = [ 'build', ] config_fields = { ...
import jsonlines import json from nltk.tokenize import sent_tokenize # def preproc(split): # data = [] # with jsonlines.open(f'{split}.txt') as reader: # for obj in reader: # # print(obj.keys()) # # print() # # print(obj['metadata']) # # print("SUMMURY",...
from java.util import Map from geoscript.util import xml from geoscript.feature.feature import Feature def writeGML(f, ver=2, format=True, bounds=False, xmldecl=False, nsprefix='gsf'): """ Writes a :class:`Feature <geoscript.feature.Feature>` object as GML. *ver* specifies the gml version to encode. Supported v...
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse('This is a bad request. Start with the music route.') def music(request): return HttpResponse('blues') def artist1(request): return HttpResponse('Muddy Waters') de...
# Generated by Django 2.2.5 on 2020-02-27 13:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('record', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='record', name='item', ), ...
import sys sys.path.append("..") from pyinsights import mlmodels, dataread, sklsetups
from database import db class Naf(db.Model): __tablename__ = "naf" id_naf = db.Column(db.Integer, primary_key=True) code_sous_classe = db.Column(db.String(255)) libelle_sous_classe = db.Column(db.String(255)) code_sous_classe_short = db.Column(db.String(255)) code_classe = db.Column(db.String(...
# TensorBoxPy3 https://github.com/SMH17/TensorBoxPy3 import tensorflow as tf from train import build_forward import cv2 import argparse import random import json import os def create_meta_graph(args, H): tf.reset_default_graph() x_in = tf.placeholder(tf.float32, name='x_in', shape=[H['image_height'], H['image...
import torch from torch import nn from torch.nn import functional as F class Encoder(nn.Module): def __init__( self, in_channels, channels=(32, 32, 64, 64), n_latent=20, n_hidden=256, size=64 ): super().__init__() self.size = size in_ch = in_channels l...
# Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ChromeOS family boards.""" from cros.factory.device.boards import linux from cros.factory.device import device_types from cros.factory.utils import ty...
import inspect import decorateme from mandos.model.apis.caching_pubchem_api import CachingPubchemApi from mandos.model.apis.chembl_api import ChemblApi from mandos.model.apis.chembl_scrape_api import ( CachingChemblScrapeApi, ChemblScrapeApi, QueryingChemblScrapeApi, ) from mandos.model.apis.g2p_api impor...
"""Provide custom gateway for tests changing apicast parameters.""" import pytest from weakget import weakget from testsuite.gateways import gateway from testsuite.gateways.apicast.template import TemplateApicast from testsuite.utils import blame from testsuite.utils import warn_and_skip @pytest.fixture(scope="modu...
#!/bin/python from . import halt, Settings, interface from time import sleep import random from threading import Thread from .evolution_generations import Generations import datetime import os import waitress import promoterz from version import VERSION def launchWebEvolutionaryInfo(): print("WEBSERVER MOD...
from contextlib import contextmanager try: import _winreg as wr except Exception, e: LOG.error("Can't load win reg to register commands: %s" % e) @contextmanager def closing(root, path, style, value=None): open_key = None try: open_key = wr.OpenKey(root, path, 0, style) yield open_key ...
# -*- coding: utf-8 -*- __author__ ='Charles Keith Brown' __email__ = 'charles.k.brown@gmail.com' __version__ = '0.1.1'
import time import datetime from train_v2 import Train from validation import Validation import parameters as param from build_dataset import BuildDataset from testing import Testing class Main: def __init__(self): # print('Mode: ', param.mode) self.run(mode=param.mode, train_restored_saved_model=...
# -*- coding: utf-8 -*- """ Calculation of the dry deposition velocity of aerosol particles on the surface of a vegetation. In CFD models, the deposition of the aerosol may be included in the concentration equation by an additional term, dc/dt = - LAD ud c, where c is the mass concentration, LAD is one-sided leaf are...
import time x = 0 while x <= 10: print x x+=1 time.sleep(0.5) print('I will trow an error now, lets see if you can catch it!') i = 12 print('err '+i)
import io import sys import wordcloud import numpy as np from matplotlib import pyplot as plt def custom_word_clouds(file_contents): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' # feel free to edit this list uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "...
import numpy as np import json A = np.load("basic_features.npy") b = np.load("basic_param.npy") print(A) print(b) data = {"features": A.tolist(), "param": b.tolist()} with open("simple_rep.json", "w") as outf: json.dump(data, outf)
import unittest from time import sleep from core.client import DealTapAut from pages.homepage import Home from pages.login import Login class TestLogin(unittest.TestCase): def setUp(self): self.dealtap_aut = DealTapAut() self.dealtap_aut.launch() self.home_page = Home() ...
#!/usr/bin/env python3 '''A testing script to evaluate action flows without accidentally running them at startup.''' import sys import time import board import busio from random import randint import adafruit_tca9548a import adafruit_tcs34725 import adafruit_hcsr04 from adafruit_bus_device.i2c_device import I2CDevice ...
from datetime import datetime import json def getPersonal(date): personal = [] with open('./lib/data/events.json', 'r') as f: file = json.load(f) for key in file['events'].keys(): if file['events'][key]['repeat'] is not None: if type(file['events'][key]['repeat']) == dict: ...
import argparse import json import sys import os import sh from sh import docker parentdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) os.sys.path.insert(0, parentdir) import time # import multiprocessing def reset(package: str): container_name = package + "_build" image_name = package +...
import logging from flask import jsonify, request, make_response, abort from app import app from app.errors import MyError import app.utils_routes as utils @app.errorhandler(400) def not_found(error): return make_response( jsonify({'error': 'Bad request, sosi hui, hz pochemu'}), 400) @app.errorhandler(4...
''' Mapping objects for translating between internal and external representations. ''' class FieldException(Exception): pass class EncoderException(Exception): pass class DecoderException(Exception): pass class FieldMap(object): name = None field_name = None value = None def __init__(s...
class Solution: def expand(self, s, i): left = i // 2 - (i % 2 == 0) right = i // 2 + 1 while(left >= 0 and right < len(s) and s[left] == s[right]): left -= 1 right += 1 return right - left - 1 def get_p(self, s, i, r): pivot = i // 2 retu...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 '''An example of handling errors with s3 functions. Disclaimer: this is only created to demonstrate unit testing''' import boto3 import os import json # configure aws authentication BUCKET_NAME = os.environ['S3_BUC...
from flask import Flask, render_template, Response import cv2 import eyesight import eyesight.services as services def construct_eyesight_pipeline(): # First, get camera camera = services.PiCamera() # camera = services.VideoFileReader() # Define services detector = services.ObjectDetector(camera...
# Copyright 2021 Matt Chaput and Marcos Pontes. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of ...
from dataclasses import dataclass @dataclass(frozen=True) class Price: """ A generic (and minimalist) representation of the current price """ last: float change: float change_pct: float
import sys def getbit(i, n): return (i >> n) & 1 def setbit(i, n, val=1): if val == 1: return i | (1 << n) return i & (~(1 << n)) def bitcmp(i1, i2, n): for i in range(0, n): b2 = getbit(i2, i) b1 = getbit(i1, i) if b1 != b2: return b1 - b2 return 0 ...
import os import pandas as pd import numpy as np import matplotlib.pyplot as plt from pathlib import Path pconfig = Path(__file__).parents[1] #aa = os.path.abspath(os.path.join(yourpath, os.pardir)) traindatapathForlogistic = "%s/data/raw/Social_Network_Ads.csv"%pconfig if __name__ == "__main__": print("羅吉斯訓練...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Jupyter ipython notebook utilities. # # This file is part of the pybgl project. # https://github.com/nokia/pybgl __author__ = "Marc-Olivier Buob" __maintainer__ = "Marc-Olivier Buob" __email__ = "marc-olivier.buob@nokia-bell-labs.com" __copyright__ = "Copyri...
#!/usr/bin/env python3 import can import logging import os import signal import socketcan import socketcanopen logging.basicConfig(level=logging.DEBUG) CAN_INTERFACE = "vcan0" can_bus = can.Bus(CAN_INTERFACE, bustype="socketcan") node_id = 0x02 canopen_od = socketcanopen.ObjectDictionary.from_eds(os.path.dirname(...
from video import * import sys header_color='#ffaa00' slide("title.png",48,[(50,"Creature Control in",header_color), (50,"a Fluid Environment",header_color), " ", (36,"paperid 0143"), (36,"SIGGRAPH 2009")]) slide("wind_blocks.png...
""" Import as: import dev_scripts.git.git_hooks.utils as dsgghout """ # NOTE: This file should depend only on Python standard libraries. import compileall import inspect import logging import os import re import string import subprocess import sys from typing import Any, List, Optional, Tuple _LOG = logging.getLogge...
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt import torch import torch.optim as optim import torch.utils.data as data_utils from torch.autograd import Variable from torchvision import models, data...
name = "autoclf" __all__ = ["classification", "datasets", "encoding", "getargs"]
from rest_framework import routers from .api import NetworkLocationViewSet from .api import NetworkSearchViewSet router = routers.SimpleRouter() router.register(r"networklocation", NetworkLocationViewSet, base_name="networklocation") router.register(r"networksearch", NetworkSearchViewSet, base_name="networksearch") ...
# Generated by Django 2.1.15 on 2022-02-13 17:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20220213_1703'), ] operations = [ migrations.AlterField( model_name='studyfile', name='size_kb', ...
from ._threads import _Thread from .utils import filter from .videobulk import _VideoBulk from ._http import _get_playlist_data from ._rgxs import _PlaylistPatterns as rgx from typing import List, Optional, Dict, Any class Playlist: __HEAD = 'https://www.youtube.com/playlist?list=' def __init__(self, playli...
import pandas as pd import numpy as np from sklearn.metrics import accuracy_score from sklearn.model_selection import KFold from models import MNBDocumentClassifier if __name__ == "__main__": # setup x_lab, y_lab x_lab = 'sentence' y_lab = 'class' # load training data with open('data/rotten_im...
from objects_superclass import Task from objects_superclass import Resource class ImagingMissions(Task): im_count = 0 tabu_freq = 0 def __init__(self, resource_reqd, tabu_tenure, name,size, lat, longi, payload_reqd, imaging_time, memory_reqd, look_angle_reqd, priority, repition): self.resour...
from behave import * from kelpy import cronjob from kubernetes import config, client from jinja2 import Environment, FileSystemLoader @when("the CronJob called {cronjob_name} is created") @given("the CronJob called {cronjob_name} exists") def step_impl(context, cronjob_name): cronjob_namespace = "default" e...
from measure_mate.settings.base import * DEBUG = os.environ.get('DJANGO_DEBUG', True) CSP_CONNECT_SRC += ( "ws://localhost:*", "ws://127.0.0.1:*", "http://localhost:*", "http://127.0.0.1:*" ) INSTALLED_APPS += ( 'django_extensions', )
# Import all python files within this folder from os.path import dirname, basename, isdir, realpath from commands import getstatusoutput as bash from nrutils import verbose,__pathsfile__ import glob # # list all py files within this directory # modules = [ basename(f)[:-3] for f in glob.glob(dirname(__file__)+"/*.py")...
from datetime import datetime import logging from pathlib import Path class LoggingMeta(type): _is_logging = True _log_location = Path.home() / ".crucyble" / "{}.log".format(datetime.now().isoformat()) def no_log(self): self._is_logging = False @property def is_logging(self): retu...
from typing import Callable, Coroutine from fastapi import Depends, Request from hibiapi.api.wallpaper import ( Config, EndpointsType, NetRequest, WallpaperCategoryType, WallpaperEndpoint, WallpaperOrderType, ) from hibiapi.utils.routing import SlashRouter, exclude_params __mount__, __config_...
class TextEditor: _content = '' def type(self, words): self._content = self._content + ' ' + words def get_content(self): return self._content.strip() editor = TextEditor() editor.type('This is the first sentence') editor.type('This is the second.') print(editor.get_content())
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Escreva um programa que leia dois números e mostre uma mensagem na tela: # - O primeiro valor é maior # - o segundo valor é maior # - Não exxiste valor maior, os dois são iguais n1 = float(input('Digite o 1° número: ')) n2 = float(input('Digite o 2° número: ')) if n1 > n2: print('{} é maior que {}.'.format(n1, n...
from osgeo import ogr, osr databaseServer = "localhost" databaseName = "te_data" databaseUser = "postgres" databasePW = "123456" connString = "PG: host=%s dbname=%s user=%s password=%s" % (databaseServer,databaseName,databaseUser,databasePW) def GetPGLayer( lyr_name ): conn = ogr.Open(connString) lyr = conn....
def isPalindrome(string): # Write your code here. i =0 while (i < len(string)//2): if string[i]!=string[-i-1]: return False else: i += 1 return True string = "abcdefghhgfedcba" print(isPalindrome(string)) string = "abcdefgghgfedcba" print(isPalindrome(string))
from ..registry import DETECTORS from .two_stage import TwoStageDetector @DETECTORS.register_module class FasterRCNN(TwoStageDetector): def __init__(self, backbone, rpn_head, bbox_roi_extractor, bbox_head, train_cfg,...
#!python3 import subprocess from typing import Tuple, List, Dict, Union from magLabUtilities.parametrictestutilities.testmanager import TestCase class GeometryGenerator: @staticmethod def fromScript(scriptFP:str, overrideParameterList:List[Tuple[str,Union[str,int,float]]]): cmdString = '' ...
__author__ = 'Qiao Zhang' from tianyancha.tianyancha import Tianyancha from tianyancha.tianyancha import WriterJson
""" Unit tests for the cluster renderer """ from __future__ import absolute_import from __future__ import unicode_literals import unittest from .. import clusterRenderer from ... import utils from ....filtering import clusters from ....filtering.filters import clusterFilter from ....system import lattice class Tes...
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
import os def read_file(file_path, split=False): """Read the contents of a file from disk. Args: file_name (string): full path to file on disk """ data = None if os.path.isfile(file_path): with open(file_path, 'r') as fs: data = fs.read().strip('\n') if s...
""" Runs a series of maintenance operations on the collection of entry files, updating the table of content files for each category as well as creating a statistics file. Counts the number of records each sub-folder and updates the overview. Sorts the entries in the contents files of each sub folder al...
# Filename: config.py """ Globe Indexer Configuration Module """ # Original data set DATA_SET_URL = 'http://download.geonames.org/export/dump/cities1000.zip' # Download file DATA_CHUNK_SIZE = 1024 # For proximity search limit DEFAULT_PROXIMITY_LIMIT = 5 # The radius of earth in kilometers EARTH_RADIUS = 6371 # Ne...
# -*- coding: utf-8 -*- # Copyright (c) 2013 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unittests for cros.""" from __future__ import print_function import sys from chromite.lib import commandline from chromi...
#!/usr/bin/env python3 import socket, time HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 10047 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print("Waiting for co...
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import sys import os import yaml class SingleCrawlerManifestManager(object): """ """ required_files = ["spider_manifest.json", "spider_manifest.py"] def __init__(self, config_path=None): print("Setting ETI path as: {}".format(config_path)) self.config_path = config_path def im...
L = [100] L.append(200) print L
#!/usr/bin/env python """ Determines the frequencies of residue pair contacts in molecular dynamics simulations. Given one or more MDContact outputs, this script determines the frequency of each unique interaction of the form (itype, residue 1, residue2), weighted by number of frames, across all inputs. The inputs are...
#import MySQLdb import psycopg2 import os DATABASE_URL = os.environ['DATABASE_URL'] db = psycopg2.connect(DATABASE_URL, sslmode='require') #db = psycopg2.connect(host = "localhost", user = "postgres", password = "test", database = "forensics") cursor = db.cursor() cursor.execute("SET SCHEMA '{}'".format('forensics'))...