text stringlengths 8 6.05M |
|---|
#!/usr/bin/python
import numpy as np
import pylab as py
from COMMON import nanosec,yr,week,grav,msun,light,mpc,hub0,h0,omm,omv
from PREPARING_EPTA_DATA import EPTA_data
from scipy import integrate
from scipy.ndimage import gaussian_filter
import pyPdf,os
#Input parameters:
outputdir='../plots/'
maxreds=100000 #I will ... |
rows_of_the_field = int(input())
all_rows = []
destroyed_ships = 0
for _ in range(rows_of_the_field):
current_row = list(map(int, input().split(" ")))
all_rows.append(current_row)
all_squares_to_attack = input().split(" ")
for square_to_attack in all_squares_to_attack:
square_to_attack = square_to_attac... |
#!/usr/bin/env python
"""
Author Paula Dwan
Email paula.dwan@gmail.com
Student ID 13208660
Module COMP47270 (Computational Network Analysis and Modeling)
Course MSc ASE
Due date 11-May-2015
Lecturer Dr. Neil Hurley
CASE STUDY 2 : ... |
from scipy.stats import loguniform, uniform
import numpy as np
import argparse
import os
import sys
import time
import json
import pandas as pd
from IPython import embed
def convert(o):
if isinstance(o, np.int64): return int(o)
raise TypeError
def select_hyperparams(config, output_name, model, is_arc, scor... |
#https://docs.pycom.io/tutorials/networks/wlan/#connecting-to-a-router
#https://docs.pycom.io/firmwareapi/micropython/usocket/
import os, _thread, sys, machine, utime, time
from network import WLAN
import irc, oauth
global serial = machine.UART(1, 19200)
def setupSerial():
serial.init(19200, bits=8, parity=None, s... |
import numpy as np
import matplotlib.pylab as plt
def sigmoid(x):
return 1 / (1 + np.exp(-x))
X = np.arange(-6.0, 6.0, 0.2)
Y = sigmoid(X)
plt.plot(X, Y, linestyle='--')
plt.ylim(-0.2, 1.2)
plt.show()
|
import pathlib
import os
import pyglet
BACKGROUND_DIR = 'assets/backgrounds'
### FONTS ###
# Add font directory; Enables pyglet to search fonts found in this directory
pyglet.font.add_directory("assets/fonts")
# Loading fonts
subFont = pyglet.font.load("Press Start")
buttonFont = pyglet.font.load("Segoe UI Black")
... |
from enum import Enum
import orm
from ..db.basemodel import BaseModel
from ..db.database import database, metadata
class QuestionChoices(Enum):
num1 = '你是谁'
num2 = '你叫什么'
num3 = '你想咋地'
class Questions(BaseModel):
__tablename__ = 'questions'
__database__ = database
__metadata__ = metadata
... |
import requests
response = requests.get("http://api.open-notify.org/astros.json")
print(response.content) |
def main():
pilaantumislaskuri = 0
pilaantumissumma = 0
tuloslaskuri = 1
mittaustulos = int(0)
rivi = input("Syötä mittausten lukumäärä: ")
mittausten_lkm = int(rivi) # Luodaan ketju, joka jatkuu kunnes mittaustulosten määrä on saavutettu, tai... |
h = open('Day9/numbers.txt', 'r')
# Reading from the file
content = h.readlines()
for x in range(25, len(content)):
found = False
for y in range(1, 26):
if found:
break
for z in range(1, 26):
sum = 0
if int(content[x-y]) != int(content[x-z]):
... |
from __future__ import print_function
import json
import os
import jedi.api
from subprocess import Popen, PIPE
class JediRemote(object):
'''Jedi remote process communication client
This class provide jedi compatible API.
'''
python = 'python'
remote_command = 'jedi-remote-command.py'
jedi_... |
# 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 Li... |
n = int(input().strip())
arr = []
current=[]
for a in range(0,n):
row =list(map(int,input().strip().split(" ")))
row.pop(0)
arr.append(row)
current.append(-1)
q = int(input().strip())
def clearCurrnet(k):
for a in range(k,n):
current[a] = -1
def addToRow(k,h):
k= k-1
arr[k].append... |
import pika
class Server():
def __init__(self,host,exchange='',exchange_type=''):
self.host = host
self.exchange = exchange
self.exchange_type = exchange_type
self.severity = None
self.connection = pika.BlockingConnection(
pika.Connection... |
from flask import Blueprint, request, jsonify, Response
from ..controller import Aset
from ..controller import Pekerjaan
from flask_cors import cross_origin
import json
from ..controller.utils import upload_file
Aset_routes = Blueprint('Aset', __name__)#
@Aset_routes.route("/all", methods=['GET'])#view semua data
@c... |
from django.core.management.base import BaseCommand
from core.jet_tree_convert import convert_jet
class Command(BaseCommand):
'''
Run test
'''
def handle(self, *args, **options):
print('Start test')
convert_jet()
print('End test')
|
from sqlalchemy import desc, asc
from flask_login import UserMixin
from server import db, app
import json
import hashlib
from werkzeug.security import check_password_hash, generate_password_hash
import datetime
from random import randint
import jwt
from time import time
'''
User Class
'''
class User(db.Model, UserMix... |
import numpy as np
from fnp.module.bert_for_sequence_classification_multi_head import BertForSequenceClassificationMultiHead
from fnp.ml.csv_classifier import CSVClassifier
class CSVClassifierMultiHead(CSVClassifier):
def load_model(self, num_labels=2):
model = BertForSequenceClassificationMultiHead.fro... |
#-------------------------------------------------------------------------------------------------
# DISPLAY CLASS -------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------
import pygame
class... |
# homework2
# Filtering, Smoothing/Binning, and Multiplots
# author @ Yiqing Liu
# Question 1: How many people have been killed on each day between Jan 1st, 2013 - Feb 1st, 2013
# Question 2: How many people have been injured on each day between Jan 1st, 2013 - Feb 1st, 2013
# Question 3: How many people have been kil... |
import math
import numpy as np
import pandas as pd
from vivarium.testing_utilities import get_randomness, build_table
from vivarium_public_health.testing.utils import make_uniform_pop_data
import vivarium_public_health.population.data_transformations as dt
def test_assign_demographic_proportions():
pop_data = d... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2018-09-17 16:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exam', '0001_initial'),
]
operations = [
migrations.AlterField(
mo... |
#!/usr/bin/env python
# coding: utf-8
# In[6]:
def fizzbuzz(x_list):
#print number divisible by 3 as Fizz and divisible by 5 as Buzz, Divisible by both 3 and 5 and FizzBuzz. From 1~100
for num in x_list:
#where num represents the value from 1~100
if num%3==0 and num%5==0:
print(nu... |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
python indexlot.py IndexLotDatasetAPITask --local-scheduler
python tasks/indexlot.py IndexLotDatasetCSVTask --local-scheduler
"""
import luigi
import pandas as pd
from collections import Orde... |
#Ejercicio 13
"""
Un supermercado está estableciendo el precio de venta para nuevos productos, de estos productos desean
generar el 27 % de ganancia.
"""
precio_producto = float (input("Ingrese el precio del producto: "))
ganancia = precio_producto * 27 / 100
nuevo_producto = precio_producto + ganancia
print ("El... |
from django.contrib import admin
from .models import ViewTestModel
# from .views import TestParserModel
admin.site.register(ViewTestModel)
# admin.site.register(TestParserModel)
|
# -*- coding: utf-8 -*-
import inject
import logging
import psycopg2
import asyncio
from asyncio import coroutine
from autobahn.asyncio.wamp import ApplicationSession
from model.config import Config
from model.systems.camaras.camaras import Camaras
class WampCamaras(ApplicationSession):
def __init__(self, confi... |
from django.urls import path
from . import views
urlpatterns = [
path('users/login', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
path('', views.movieList.as_view()),
path('searchResults/<str:name>', views.getMovies),
path('movies/<str:id>', views.getMovieById),
path('genre/<s... |
from keras.models import load_model
import sys, os
from sklearn.metrics import classification_report, confusion_matrix
from setting import BATCH_SIZE,CLASSES, NUM_CLASSES
import matplotlib.pyplot as plt
import numpy as np
import itertools
model = load_model(sys.argv[1])
def evaluate():
print("Evaluating the mod... |
import boto3
from botocore.exceptions import ClientError
import csv
# with open('instances.csv', 'r') as f:
# csv_reader = csv.reader(f)
# instances = list(csv_reader)
ec2client = boto3.client('ec2', region_name='us-west-2')
responses = ec2client.describe_instances()
instance_result = set()
for reservation... |
# -*- coding: utf-8 -*-
"""
This module holds two types of objects:
1. general-use functions, and
2. classes derived from wx that could be usable outside
of `threepy5`.
"""
import wx
import wx.lib.stattext as st
import wx.lib.newevent as ne
from math import sqrt
######################
# Auxiliary classes
###########... |
#-*- coding:utf8 -*-
# Copyright (c) 2020 barriery
# Python release: 3.7.0
# Create time: 2020-07-13
import json
import requests
class BDCaller(object):
def __init__(self, home=None):
self.home_ = home
def callAPI(self, params, home=None):
if home is None:
home = self.home_
... |
#!/usr/bin/env python
# pairselect: randomly assign students to pairs
import getopt
import random
import sys
def print_usage(outstream):
usage = ("Usage: ./pairselect [options] students.txt\n"
" Options:\n"
" -h|--help print this help message and exit\n"
" -o|--out: FI... |
"""This module has a class to clean the raw data """
import numpy as np
import pandas as pd
class clean:
''' This class has the raw data and will clean it'''
def __init__(self,origin_data):
'''the constructor is to get the raw data'''
self.raw_data = origin_data
def clean_data(self):
... |
import datetime
import os
import tkinter
import numpy as np
from PIL import Image as Img
from PIL import ImageTk
import pytesseract
import cv2
from tkinter import *
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
specs_ori = cv2.imread('img/glass.png', -1)
cigar_ori = cv2.imread('img/ciga... |
K=int(input("Write month number: "))
def action1():
print("31")
def action2():
print("28")
def action3():
print("30")
def unknown_action():
print("'Error'")
if ((K==1)or(K==3)or(K==5)or(K==7)or(K==8)or(K==10)or(K==12)):
action1()
elif (K==2):
action2()
elif ((K==4)or(K==6)or(K==9)or(K==11)):
... |
import cx_Oracle
import sys
import common
import os.path
from vehicle import register_person
def print_opts():
print('Select one of the options:')
print('(1) Register a new person.')
print('(2) Create a licence for a person.')
print(' Or type \'exit\' to go back.')
def register_licence(conn):
... |
#
# from wang.dataPretreatment import *
# #嵌入矩阵的维度
# embed_dim = 32
# #用户ID个数
# uid_max = max(features.take(0,1)) + 1 # 6040
# #性别个数
# gender_max = max(features.take(2,1)) + 1 # 1 + 1 = 2
# #年龄类别个数
# age_max = max(features.take(3,1)) + 1 # 6 + 1 = 7
# #职业个数
# job_max = max(features.take(4,1)) + 1# 20 + 1 = 21
#
# #电影ID... |
#Standard imports
from __future__ import unicode_literals
import datetime
#Django imports
from django.core.cache import cache
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
import requests
import json
#Extra mo... |
from email.mime.text import MIMEText
from email.header import Header
from django.shortcuts import render, render_to_response, redirect
from django.template.context_processors import csrf
from django.contrib.auth.models import User
import smtplib
from .models import *
def open_server():
server = smtplib.SMTP('smt... |
#=============================================================================
# This script looks at the mean climate patterns during drought events.
# author: Michael P. Erb
# date : 12/12/2019
#=============================================================================
import sys
sys.path.append('/home/mpe... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-04-19 07:27
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('lhcbpr_api', '0001_initial'),
]
operations = [
... |
from django.contrib import admin
from pruebas.models import BaseTestResult, DocumentTestResult, \
FrameAnnotation, DocumentAnnotation
admin.site.register(BaseTestResult)
admin.site.register(FrameAnnotation)
admin.site.register(DocumentTestResult)
admin.site.register(DocumentAnnotation)
|
import gobject
import pygst
pygst.require("0.10")
import gst
import settings
import webservice
import time
INIT_VOLUME = 0.5
class ClientPlay:
def __init__ (self, on_eos, on_error):
self.on_eos = on_eos
self.on_error = on_error
self.is_playing = False
self.volume = INIT_VOLUME
self.pipeline = None
self.w... |
import csv
import time
# data comes from: https://www.kaggle.com/wendykan/lending-club-loan-data
# Column 2 is : loan_amnt
# Column 3 is : funded_amnt
# Column 5 is : term
# Column 6 is : int_rate
# Column 8 is : grade
# Column 10 is : emp_title
# Column 13 is : annual_inc
# Column 16 is :... |
import shutil
from pathlib import Path
import unittest
from datasets.config import HF_DATASETS_CACHE
from fewshot.challenges import registry
from fewshot import make_challenge
class TestChallenge(unittest.TestCase):
def test_challenge_hashes(self):
shutil.rmtree(Path(HF_DATASETS_CACHE) / 'flex_challenge',... |
"""
name @ utils
utilities to work with names and strings
"""
import maya.cmds as mc
def removeSuffix(name):
"""
remove suffix from given name/string
@param name: given name string to process
@return str, name without characters beyond last '_'
"""
edits = name.split('_')
if len(edit... |
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchane_declare(exchange='topic_logs', type='topic')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
binding_keys = sy... |
# 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... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2018-06-11 07:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course', '0006_video_learn_times'),
]
operations = [
migrations.AddField(
... |
import numpy as np
one_dimensional_array = np.array([1.2, 2.4, 3.5, 4.7, 6.1, 7.2, 8.3, 9.5])
print('one_dimensional_array\n', one_dimensional_array)
two_dimensional_array = np.array([[6, 5], [11, 7], [4, 8]])
print('two_dimensional_array\n', two_dimensional_array)
sequence_of_integers = np.arange(5, 12)
print('seq... |
#!/usr/bin/python2
import cgitb,cgi,commands,random
print "Contant-type:text/html"
print ""
cgitb.enable()
x=cgi.FieldStorage()
p1=x.getvalue("cho")
u=x.getvalue('uname')
p=x.getvalue('pas')
port=random.randint(6000,7000)
commands.getoutput("sudo systemctl restart docker")
if p1=="1" :
ip=commands.getstatusoutput(... |
import sys
import calendar
from datetime import datetime
# from kivy.config import Config
# Config.set('graphics', 'width', '600')
# Config.set('graphics', 'height', '1024')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.logger import Logger
from kivy.uix.popup im... |
# Main Python file that connects to InBloom and fetches Data
# Once all the data is retrieved, index.html is rendered for display
#
from flask import Flask, redirect, url_for, request, jsonify, render_template
import requests
import numpy as np
import pandas as pd
import simplejson as json
params = {
'base_url': '... |
import sys
class Genotype(object):
def __init__(self, variant, gt):
self.format = dict()
self.variant = variant
self.set_format('GT', gt)
def set_formats(self, fields, values):
format_set = self.variant.format_set
add_to_active = self.variant.active_formats.add
... |
from flask import request
from flask_restplus import Namespace, Resource, abort
from app.utils.exceptions import OdooIsDeadError
api_company = Namespace('companies', description='Request to odoo companies.')
@api_company.route("/")
class Company(Resource):
def get(self):
"""Get all companies from odoo.... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pickle
class APIConfig:
def __init__(self):
self.project_name = None
self.api_key = None
self.city_code = None
self.city_latitude = None
self.city_longitude = None
def setParameter(self, _project_name, _api_key, _city_co... |
from __future__ import absolute_import, division, unicode_literals
from twisted.trial.unittest import SynchronousTestCase
from twisted.internet.task import Clock
from mimic.core import MimicCore
from mimic.resource import MimicRoot
from mimic.test.helpers import json_request
class ValkyrieAPITests(SynchronousTestCa... |
from mpi4py import MPI
import sys
size = MPI.COMM_WORLD.Get_size()
rank = MPI.COMM_WORLD.Get_rank()
print("Helloworld! I am process %d of %d.\n" % (rank, size))
|
def belt_count(dictionary):
belts = list(dictionary.values())
for belt in set(belts):
num = belts.count(belt)
print(f"There are {num} {belt} belts")
ninja_belts = {}
def ninjaIntro(dict):
for key, val in dict.items():
print(f"I am {key}, and I am a {val} belt")
while True:
ninja_name = input("Enter a ninja ... |
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
result = [[0 for i in range(n)] for j in range(n)]
direction = 1
i = j = 0
for x in xrange(1,n*n+1):
result[i][j] = x
if direction == 1:
if j+1<n and result[i][j+1] == 0:... |
#!/usr/bin/python
import os
import json
import subprocess
import json
import shutil
def main():
release_repository_path = 'release_repository'
package_json_path = 'package.json'
makedir(release_repository_path)
package_json_file = open(package_json_path, 'r')
package_json_str = package_json_file.... |
from .utils import *
from .inference import *
|
import multiprocessing
from mu.mel import mel
from pype import servos
class Pipe(object):
def __init__(self, pitch: mel.SimplePitch):
self._pitch = pitch
@property
def pitch(self) -> mel.SimplePitch:
return self._pitch
class ServoPipe(Pipe):
def __init__(
self,
pit... |
# encoding: utf-8
from string import punctuation
from zhon import hanzi
import re
import jieba
# 单例
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
# 去除... |
import matplotlib.pyplot as plt
import re
import os
def main():
seq = inlezen()
waardelijst,lijst = tellen(seq)
grafiek(waardelijst,lijst)
def inlezen():
file = open('identity.txt','r')
seq = []
for line in file:
line = line.split('\t')
for thing in line:
thing = t... |
from django.urls import path
from authnz import views as authnz_views
urlpatterns = [
path('authnz/register/', authnz_views.RegisterView.as_view(), name='register'),
path('authnz/login/', authnz_views.LoginView.as_view(), name='login'),
]
|
import urllib.request, json
with urllib.request.urlopen("https://pomber.github.io/covid19/timeseries.json") as url:
data = json.loads(url.read().decode())
import json
import csv
import copy
import pandas as pd
import argparse
import matplotlib.pyplot as plt
def getValue(keys,value):
key = keys.split('... |
from typing import List
from typing import Dict
from typing import Set
from typing import Tuple
import networkx as nx
def _compute_articulation_points(G: nx.Graph) -> List[int]:
"""
An articulation point or cut vertex is any node whose removal (along with all its incident edges) increases the number of connected c... |
__author__ = 'Justin'
import os
import sys
import json
import networkx as nx
from numpy import std,linspace,argsort,array,linspace,unique
from DisplayNetwork import networkdisplay
from ParetoFrontier import rand_paretofront
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from os.path import isfil... |
import tigger.cluda.dtypes as dtypes
from tigger.core.transformation import *
from tigger.cluda.kernel import render_prelude, render_template
class Argument:
def __init__(self, name, dtype):
self.dtype = dtype
self.ctype = dtypes.ctype(dtype)
self.load = load_macro_call(name)
self... |
import numpy as np
import sys
sys.path.append("game/")
import skimage
from skimage import transform, color, exposure
import keras
from keras.models import Sequential, Model, load_model
from keras.layers import Dense, Flatten, Activation, Input
from keras.layers.convolutional import Convolution2D
from keras.optimizers ... |
from numpy.ctypeslib import as_ctypes as as_c
import numpy as np
import ctypes as C
from .ctype_helper import load_lib
lib = load_lib("libSigPyProcTim.so")
class TimeSeries(np.ndarray):
"""Class for handling pulsar data in time series.
:param input_array: 1 dimensional array of shape (nsamples)
:type inp... |
#!/usr/bin/env python
# This search CMIP5 data available on raijin that matches constraints passed on by user and return paths for all available versions.
"""
Copyright 2016 ARC Centre of Excellence for Climate Systems Science
author: Paola Petrelli <paola.petrelli@utas.edu.au>
Licensed under the Apache License, Vers... |
import tensorflow as tf
a=tf.placeholder("float")
b=tf.placeholder("float")
x=tf.constant(2.0)
c=tf.multiply(a,b)
with tf.Session() as sess:
for i in range(11):
feed_dict={a:i,b:x}
print(sess.run(c,feed_dict))
|
import datetime
from dateutil.relativedelta import relativedelta
import time
import requests
import json
import random
import os
import os.path
import pandas as pd
import shutil
import zipfile
#for text cleaning
import string
import re
class RedditHandler:
'''
class responsible for extracting and processing ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 15:14:01 2019
@author: murillon2003_00
"""
money_slips = {
'20' : 5,
'50' : 5,
'100' : 5
}
accounts_list = {
'0001-02' : {
'password' : '123456',
'name' : 'Fulano da Silva Sauro',
'value' : 100,
'admin' : False
... |
# -*- coding: utf-8 -*-
# @Author: Fallen
# @Date: 2020-04-24 09:56:43
# @Last Modified by: Fallen
# @Last Modified time: 2020-04-24 17:25:18
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-22 10:48:58
# @Author : Fallen (xdd043@qq.com)
# @Link : https://github.com/fallencrasher/python-learni... |
def replacewords(array):
house=[flat,apartment,]
with open("countries.txt") as f:
content = f.readlines()
content = [x.strip() and x.split() for x in content]
for index, i in enumerate(array):
if i == "COUNTRY":
for country in content:
... |
# coding=utf8
""" 生成手机图片, 只作缩小. """
from PIL import Image, ImageEnhance
import os, sys
# 执行转换的文件后缀
EXTS = set(['.jpg', '.jpeg'])
# 调整宽度
WIDTH = 600
#WIDTH = 480
# JPEG quality
QUALITY = 87
# 保存目录
THUMB_DIR = '模特细节图_手机'
# 覆盖存在
OVERRIDE = False
def list_images(path='.'):
for f in os.listdi... |
import math
t = int(input("Program kac defa calısacak : "))
if t <=0:
print("Döngü sıfırdan küçük olamaz")
for i in range(0,t):
sayi1 = int(input("Birinci Sayıyı Giriniz: "))
sayi2 = int(input("İkinci Sayıyı Giriniz: "))
islem = input("Yapılmasını İstediğiniz İşlemi Giriniz: ")
if islem == "+":
... |
a = {'1': 'a', '2': 'b'}
b = {'3': 'c'}
dictMerged2 = dict( a, **b )
print(dictMerged2) |
import collections
class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
d = collections.defaultdict(int)
for i, s in enumerate(list1):
if s in list2:
d[s] = i
for i, s in enumerate(list2):
if s in list1:
... |
from datetime import datetime
from pythonping import ping
#il faudrait récupérer les valeurs envoyées par le master dans l'init
def __init__ (self):
self.ip = #receive de l'ip du master
self.tempsheure = #receive le datetime du master
#lancement du ddos
def ddos(ip, tempsheure):
format = "%Y-%m-... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
File Name: project.py
Description: 处理与项目(增减改)相关的工作
Author: Dexter Chen
Date:2017-09-04
-------------------------------------------------
Development Note:
1. 扫描所有项目文件夹,项目文件夹数可大于csv中登记数
2. 根据需要新建项目,生... |
import numpy as np
import pandas as pd
from integration import *
filepathH = 'Hamiltonian.xls'
filepathVec='Eigenvectors.xlsx'
filepathVal='Eigenvalues.xlsx'
m=0
n=0
#length in meters
L=(5.0)*10.0**(-10)
#Length in angstroms
#L=5
# this was an epxiremental attempt to numerically solve the integral it doesn't work yet
d... |
# 3. Elabore um programa recursivo em C que calcule o n-ésimo termo da
# sequência: 1, 2, 4, 8, 16, 32... .
# O termo deverá ser impresso na função main().
numero = 1
def multiplica(n):
global numero
if n == 0:
return
numero = numero * 2
n -= 1
multiplica(n)
if __name__ == '__ma... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import sys
sys.path.append(f'{os.getcwd()}/SentEval')
import tensorflow as tf
# Prevent TF from claiming all GPU memory so there is some left for pytorch.
gpus = tf.config.list_physical_devices('GPU')
if gpus:
# Memory growth needs to be the same across GPUs.
fo... |
from rest_framework.response import Response
from rest_framework import status
def syllable_required(syllable_id, syllable_type=None, is_get_request=False):
def decorator(func):
def _wrapped_view(request, *args, **kwargs):
data = request.GET if is_get_request else request.data
r =... |
import numpy as np
from ensemble_boxes import *
import glob
import os
import argparse
SAVE_FOLDER = ""
class WBF_VTX(object):
name2idx = {"person": 0}
idx2name = {0: "person"}
def __init__(self, opts, model_weighted, iou_thr=0.6, skip_box_thr=0.0001):
self.opt = opts
self.model_weighted =... |
from lxml import html
import requests
import sqlite3
from time import sleep
base_url = 'http://stackoverflow.com'
conn = sqlite3.connect('morpheus11.db')
c = conn.cursor()
# Create table
for row in c.execute('SELECT count(*) FROM post_tb'):
code = row[0]
print code
conn.close()
|
from __future__ import unicode_literals
from contextlib import contextmanager
import os
from tempfile import NamedTemporaryFile
@contextmanager
def example_file(json_for_file):
ntf = NamedTemporaryFile(delete=False)
try:
ntf.write(json_for_file)
ntf.close()
yield ntf.name
finally:... |
def mad_libs():
person1 = input("Enter the first person of the mad_libs story:")
person2 = input("Enter the second person of the mad_libs story:")
person3 = input("Enter the third person of the mad_libs story:")
place = input("Enter the setting of the story:")
adjective = input("Enter an adjective f... |
import re
aa_codes = dict(
ALA='A',
ARG='R',
ASN='N',
ASP='D',
CYS='C',
GLU='E',
GLN='Q',
GLY='G',
HIS='H',
ILE='I',
LEU='L',
LYS='K',
MET='M',
PHE='F',
PRO='P',
SER='S',
THR='T',
TRP='W',
TYR='Y',
VAL='V',
)
def parse_aa(gene: str,
... |
import pygame
import logging
import os
cwd = os.getcwd()
class Sound:
def __init__(self, soundlog, settings):
pygame.mixer.init()
self.channels = {}
global volume, log
log = soundlog
if settings['audio']['enabled']:
volume = float(settings['audio']['volume'])/10... |
class TipoA:
def __init__(self, f1, f2):
self.nombre = "Tipo A"
self.filaA = f1+1
self.filaB = f2+1
class TipoB:
def __init__(self, f1, c1):
self.nombre = "Tipo B"
self.filaC = f1+1
self.constanteA = c1
class TipoC:
def __init__(sel... |
import sys
import re
# This script generates the swb code list. This is to be looped through for other scripts.
# For example, if you have a batch - you can run 'for line in file' in bash or zsh.
# Where the 'file' is the output of this script.
filename = sys.argv[1]
five_code = re.search(r"[0-9]{5}", filename).group(... |
#!/usr/bin/env
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
# @autor: Jorge de la Rosa #
# Date: 14/08/2021 #
# #
# Perceptron training using #
# GA to simulate AND gate #
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
import numpy as np
import random
def activation_function(arg):
#... |
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django.db.models import Q
from .models import funds
"""
time:2020-01-17
author:JZ
function:获取基金数据(分页)
"""
def get_funds(request):
print('----get_funds_data------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.