text stringlengths 8 6.05M |
|---|
from ml import *
def main():
fs = fileio.FileStream(r"D:\Game\Steam\steamapps\common\Trails in the Sky FC\ed6_win_dump")
lines = []
xml = OrderedDict()
root = OrderedDict()
xml['ed6fc'] = root
root['text'] = lines
for l in fileio.readLines(r'ed6_fc_text2.txt'):
if not ... |
"""
Purpose of this script is to extract the list of pdb files required for download.
Output of this script are the downloaded pdb files from the chosen pdb website.
"""
# STEP 1
# Necessary packages
import os
from selenium import webdriver
import time
import csv
# STEP 2
main_folder = r'D:\PHML B factor... |
#import sys
#input = sys.stdin.readline
Q = 10**9 + 7
def main():
N = int( input())
A = list( map( int, input().split()))
T = [[0]*60 for _ in range(N)]
P = [0]*60
for i in range(N):
a = A[i]
for j in range(60):
T[i][j] = a%2
P[j] += a%2
a //= 2
... |
from PIL import Image
import requests
from io import BytesIO
# Company UUID provided to you
COMPANY_ID = 9
# Some sample token. Instead replace with the token returned by authentication endpoint
JWT_TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0IiwiaWFkIjoxLCJhY3AiOm51bGwsInRicCI6bnVsbCwiaWF0IjoxNTg4M... |
from djangorestframework.renderers import TemplateRenderer
from shopback.base.renderers import BaseJsonRenderer
class AsyncPrintHtmlRenderer(TemplateRenderer):
"""
Renderer which serializes to JSON
"""
media_type = 'text/html'
format = 'html'
template = 'asynctask/async_print_commit.html... |
from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment
from collections.abc import Iterable
from datetime import datetime
from depot.io.interfaces import StoredFile
class FileServeApp:
file: StoredFile
filename: str
last_modified: datetime
content_length: int
content_type: str
... |
def js_tag(url):
return "<script src=\"%s\"></script>" % url
def css_tag(url):
return "<link href=\"%s\" rel=\"stylesheet\">" % url
def js_asset_tag(base_url, path):
return js_tag("%s/static/js/%s" % (base_url, path) )
def css_asset_tag(base_url, path):
return css_tag("%s/static/css/%s" % (base_ur... |
# palindrome_recursive.py asks the user for a string and determines if it is palindromic using a recursive function
# import function for cleaning strings
from string_cleaner import strip_whitespace_and_punctuation_and_make_lowercase
def check_if_palindrome_recursively(phrase):
"""return True if the string is a p... |
#!/usr/bin/env python
# Funtion:
# Filename:
import socket
import os
client = socket.socket()
client.connect(('localhost', 9999))
while True:
cmd = input(">> ").strip()
if cmd == '':
continue
client.send(cmd.encode('utf-8'))
tol_file_size = client.recv(1024).decode()
if tol_file_siz... |
x = 40
y = 60
while x < 50 and y < 100:
x += 1
y += 1
print(x, y)
|
nam=input('who are you?\n')
print('welcome',nam)
|
##############b#############
# astring = input('่ฏท่พๅ
ฅไธไธชๅญ็ฌฆไธฒa๏ผ ')
# bsting = input('่ฏท่พๅ
ฅไธไธชๅญ็ฌฆไธฒb๏ผ ')
#
# if len(astring) != len(bsting):
# print('no')
# exit()
#
#
# for i, j in zip(astring, bsting):
# if i is not j:
# print('no')
# exit()
# else:
# print('yes')
##############c###############
... |
import chessBoard as cb
import unittest
class chessTest(unittest.TestCase):
def testPawn(self):
self.board = cb.chessBoard()
currPos = []
currPos.append(1) # (1,1)
currPos.append(1)
pieceType = 1 # Pawn
color = "Black"
self... |
from copy import deepcopy
N, K = map( int, input().split())
A = list( map( int, input().split()))
ans = N
for i in range(N):
B = [0]
V = [0]*(K+1)
for j in range(N):
if j == i:
continue
a = A[j]
C = []
for b in B:
if b + a <= K:
if V[b+... |
from django.shortcuts import render
from django.core.cache import cache
from django.utils import timezone
from scheduler.forms import FeedbackForm
from datetime import datetime, timedelta
from .schedalgo.schedule import sched
from .models import Course, Request
from .organize_data import organize, organize_output, orga... |
# -*- coding: utf-8 -*-
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
import sys
sys.path.append('..')
import os
import plotly.graph_objects as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Outpu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import matplotlib as mpl
mpl.rcParams['toolbar'] = 'None'
import matplotlib.pyplot as plt
from ising import IsingAnim
import threading
import time
from ext.colors import rundark
def main():
if len(args.shape) == 2:
animate_evolution()
e... |
# !/usr/bin/python
"""
-----------------------------------------------
Auto Layer Cast Light
Written By: Colton Fetters
Version: 1.0
First release: 9/2017
Production tool designed to add shadow light to
utility shadow layer
-----------------------------------------------
"""
# import modules
import ... |
l, N = map( int, input().split())
X = [ int( input()) for _ in range(N)]
L = [0]*(N+1)
R = [0]*(N+1)
RX = [ l - X[i] for i in range(N-1,-1,-1)]
for i in range(N):
L[i+1] = L[i]*2 + X[i]
R[i+1] = R[i]*2 + RX[i]
#ๅใใฎไฝ็ฝฎใใๅณๅทฆใซ้ ็ชใซๅพๅพฉใใๅ ดๅ
print(L)
print(R)
ans = L[N//2] + R[(N+1)//2]
print(ans)
|
# Generated by Django 3.1.6 on 2021-02-11 07:13
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('blogger', '0005_auto_20210210_0718'),
]
operations = [
... |
# -*- coding: utf-8 -*-
{
'name': "Optesis Sale Order Custom Validation Date",
'summary': """
La date saisie dans le sale.order doit etre considรฉrรฉe comme de confirmation et date prรฉvue du stock.picking associรฉ au sale order""",
'description': """
""",
'author': "Optesis SA, by R... |
#!/usr/bin/env python
# coding: utf-8
# # แ
แแแถแแแแแแถแแแขแแแแปแ (Binary Classification)
# แแแแ
แแธแแถแแแทแแแแถแแธแแแแถแแแแแแแแแถแแขแแแแแธแแฌแ
แแแพแแแถแแแแแแแผแแแแแแแแแแแแแแ แแถแแแแแ
แแแแทแแแแแแแแแแแแแแแแพแขแแแแแแแแแแแแแแแถแแถแแแแปแแ แ
แแถแ
แแแถแแแแแแถแแแแแแปแ(classification)แ แแถแแแทแแ
แแแถแแแแแแถแแแแแแปแ แแแขแถแ
แแแแ แถแแแถแแแถแแแแแแแแแผแแแแแแแแแแแแแแแแแแแ แแแแแ... |
from setuptools import setup
setup(
name="reorg",
version="0.1.0",
license="MIT",
author="Michael Hwang",
description="Command-line to reorganize documents stored in CLB6 structure to..",
packages=["reorg"],
install_requires=[],
entry_points={
"console_scripts": [
"r... |
import os,sys
import numpy as np
import scipy.sparse as sp
caffe_root = os.environ["CAFFE_ROOT"]
sys.path.insert(0, caffe_root + 'python')
os.chdir(caffe_root)
import caffe
def dump2file(mat, filename):
assert mat.dtype == np.float32
csr_m = sp.csr_matrix(mat)
f = open(filename, 'wb')
nnz = csr_m.ge... |
"""
Andrew Olin
axo4762
File to kill unwanted Services
"""
import os
os.system("service --status-all > currentServices.txt")
services = open("currentServices.txt","r")
print("Current running services:")
for line in services:
if line[3] == '+':
print(line)
processes = input("What processes should be ki... |
import os
import sys
os.chdir('/home/peitian_zhang/Codes/News-Recommendation')
sys.path.append('/home/peitian_zhang/Codes/News-Recommendation')
import torch
from utils.utils import evaluate,train,prepare,load_hparams,test
if __name__ == "__main__":
hparams = {
'name':'baseline-mha-cnn',
'dropout_... |
a,b = map(int, input().split())
s = max(a-b, a+b, a*b)
print("{}".format( s))
|
#!/bin/python3
def richie_rich(s, k):
s_len = len(s)
left = s[:s_len//2]
right = s[s_len//2:] if s_len % 2 == 0 else s[s_len//2+1:]
right = list(reversed(right))
changes = [0] * (s_len//2)
# see if a palindrome can be made
for i in range(s_len//2):
if left[i] != right[i] and k >= ... |
from django.urls import path
from .views import home_page_view
urlpatterns=[path("",home_page_view,name="home")]
|
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
class GameDriver():
def __init__(self, address, privatekey):
with open("code.js", "r") as text_file:
self.js = text_file.read()
driver = webdriver.Chrome('df_gym/envs/utils/chromedriver')
... |
import numpy as np
import matplotlib.pyplot as plt
circle = plt.Circle((1, 1), 1, color='r')
plt.gcf().gca().add_artist(circle)
plt.plot([0, 1, 2, 3], [0, 1, 2, 3])
plt.show()
|
"""open_pipelines URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
C... |
def generate_n_triangle_num(n):
return (n * (n + 1)) / 2
def count_divisors(n):
root = int(n ** 0.5)
return len(filter(lambda x: n % x == 0, (range(1, root)))) * 2
n = 0
while True:
n += 1
div_count = count_divisors(generate_n_triangle_num(n))
if div_count >= 500:
break
print generate_n_triangle_num... |
class MusicalInstrument:
no_of_major_keys = 12
class StringInsturment(MusicalInstrument):
type_of_wood = 'Tonewood'
class Guitar(StringInsturment):
def __init__(self):
self.no_of_strings = 6
print(
'This guitar consists of {} strings. It is made up of {} and it can play {} ke... |
def count_words(arr):
return {word: arr.count(word) for word in arr if type(word) == str and word.isalpha() == True}
print(count_words([1,])) |
for joel in 1,2,3,4,5:
print "current joel: ",joel
print"------------------"
fruits = ['banana','Apple','Mango']
for fruit in fruits:
print "current fruit: ", fruit
print"------------------"
for index in range(len(fruits)):
print "current fruit: ",fruits[index]
print "Good Bye"
|
# coding: utf-8
# flake8: noqa
"""
LoRa App Server REST API
For more information about the usage of the LoRa App Server (REST) API, see [https://docs.loraserver.io/lora-app-server/api/](https://docs.loraserver.io/lora-app-server/api/). # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: ht... |
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from xml.sax.saxutils import escape as _escape
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
class PangoMarkupRenderer(Renderer):
'''... |
from mailu import db, models
from mailu.internal import internal
import flask
@internal.route("/postfix/domain/<domain_name>")
def postfix_mailbox_domain(domain_name):
domain = models.Domain.query.get(domain_name) or \
models.Alternative.query.get(domain_name) or \
flask.abort(404)
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
n=int(raw_input())
a=[]
l=r=ans=chk=0
p,q=[0]*3,[0]*3
for i in range(n):
x,y=map(int,raw_input().split())
l,r=l+x,r+y
if x>y:
if x-y>p[0]-p[1]:
p=[x,y,i+1]
if x<y:
if y-x>q[1]-q[0]:
q=[x,y,i+1]
ll=abs((l-q[0]+q[1])-(r... |
import requests
class Fetcher(object):
def fetch(self):
return ""
class FilesystemFetcher(Fetcher):
def __init__(self, path):
self.path = path
def fetch(self):
with open(self.path) as f:
return f.read()
class HTTPFetcher(Fetcher):
def __init__(self, url):
... |
#!/usr/bin/env python
import os
import re
from sys import argv
parts = argv[1].rpartition("/.git/")
is_submodule = os.path.isfile(parts[0] + "/.git")
if is_submodule:
f = open(parts[0] + "/.git", 'r')
line = f.readline()
f.close()
gitdir = re.match('gitdir: (.*)', line).group(1)
if not os.path.isabs(gitdir):... |
import tcod
from input_handlers import handle_main_menu
from graphics.scene.main_menu import MainMenuScene
from globals import GameStates, RenderOrder, CONFIG
from game_map import GameMap
from components.fighter import Fighter
from components.inventory import Inventory
from components.equipment import Equipment
from c... |
from unfollowLogManager import UnfollowLogManager
logHandler = UnfollowLogManager("niclasguenther")
peopleToUnfollow = logHandler.getDataFromUnfollowLog()
|
def hi(name):
print(name)
print("hello")
print("how are you?")
return name
a=hi("sri")
print(a)
|
#dict_popitem
#popitem็ฑปไผผไบlist.pop,ๅ่
ไผ่ฟๅๅ่กจ็ๆๅไธไธชๅ
็ด ๏ผไฝไธๅ็ๆฏ๏ผpopitem่ฟๅ็ๆฏ้ๆบ้กนใ
#ๅ ไธบๅญๅ
ธๆฒกๆ้กบๅบ็ๆฆๅฟตๅๆ่ฐ็โๆๅ็ๅ
็ด โใ
d={'adam':89,'lisa':67,'bart':27,'paul':56,'name':'dcy','age':67}
print(len(d))
while len(d)!=0:
key,value=d.popitem()#่ฐ็จpopitemๆนๆณ้ๆบๅ ้ค้ฎ-ๅผๅฏน๏ผ้กน๏ผๅนถไปฅๅ
็ป็ๅฝขๅผ่ฟๅ,ๅฐๅ
ถ็ดๆฅ่ตๅผ็ปkeyๅvalueใ
print(key,value)
print(d.keys())#keys()ๆนๆณๅฐ... |
# s = 'azcbobobegghakl'
# numVowels = 0
#
# for char in s:
# if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':
# numVowels += 1
#
# print('Number of vowels: ' + str(numVowels))
s = 'bobobobobobobobobob'
# b = 0
# o = 0
# third = 0
#
# for letter in s:
# print('I am at the lett... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 13 14:22:16 2018
Multilayer Perceptron Implementation
with Tensorflow Framework
@author: zhaoyu
"""
import tensorflow as tf
import numpy as np
def loss_cross_entropy(pred, y):
return tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
def... |
import math
class Agent:
def __init__(self,env):
self.Q={}
self.C={}
self.pi={}
self.gamma=0.95
self.alpha=lambda d: 0.8
self.actions=env.actions
self.t=0
def get_a_exp(self,state,det=None):
"""
This function will return an action given a stationary policy given the current state.
:param state... |
#!/usr/bin/env python
#coding: utf-8
from google.appengine.ext import db
from webapp import webHandler
from api import datastore_api as api
from cgi import escape
import datastore
class ShoutBugHandler(webHandler):
def get(self):
if self.request.cookies.has_key("token"):
token = sel... |
# Challenge - Classes Exercise
# Add a method to the Car class called age
# that returns how old the car is (2019 - year)
# *Be sure to return the age, not print it
class Car:
def __init__(self, year, make, model):
self.year = year
self.make = make
self.model = model
def compute_age... |
from copy import deepcopy
from bt_scheme import PartialSolution, BacktrackingSolver, State, Solution
from typing import *
from random import random, seed
def horse_solve(tablero: "List[Tuple[int, int], ...]"):
class KnapsackPS(PartialSolution):
#def __init__(self, solucionParcial: Tuple[int, ...], valorAc... |
from rest_framework import serializers
from apiAnalisis import models
class LibroSerializer(serializers.ModelSerializer):
class Meta:
fields = (
'id',
'titulo',
'descripcion',
)
model = models.Libro
class ClienteSerializer(serializers.ModelSerializer):
... |
import warnings
import itertools
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing
warnings.filterwarnings("ignore")
plt.style.use('fivethirtyeight')
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_M... |
# Generated by Django 2.2.5 on 2019-11-11 11:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('appointments', '0002_auto_20191106_1714'),
('bms', '0003_auto_20191106_1837'),
]
operations = [
migrations.RenameModel(
old_name... |
from __future__ import unicode_literals
import os, threading, tinify
from urlparse import urlparse
from django.db.models.signals import post_save
from django.templatetags.static import StaticNode
from django.conf import settings
aws_key_id = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret = os.getenv('AWS_SECRET_ACCESS_KEY... |
# Generated by Django 2.1.4 on 2019-01-10 06:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0003_post_title'),
]
operations = [
migrations.AlterField(
model_name='post',
name='message',
f... |
# calculate age using Python
while True:
# exception
try:
age = int(input('Please enter the year you were born. for example = 2001 '))
age = 2021-age
print(f'You are {age} old')
except ValueError:
print('Please enter a number')
except ZeroDivisionError:
... |
#Simple script to publish data to a subscriber.
#Uses the REP messaging pattern.
import zmq
import time
from random import *
def main():
context = zmq.Context()
socket= context.socket(zmq.REP)
socket.connect("tcp://127.0.0.1:5200")#Here the REP can be used to connect
for i in range(100,200):
... |
# Generated by Django 3.0.2 on 2020-04-22 15:40
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('obsapp', '0029_auto_20200419_0006'),
]
operations = [
migrations.AddField(
model_name='games',
name=... |
from abc import ABC, abstractmethod, abstractproperty
import os, sys
from shlex import split
import argparse
from re import sub as substitute
class AbsHandler(ABC):
def __init__(self, info_handler = None, finish_handler = None, handling_params_string : str = None, handle_immediately : bool = False) -> None:
... |
#! usr/bin/python3
# -*- coding = utf-8 -*-
from RuntimeDecorate import runtime
data = {}
@runtime
def rob(nums: list) -> int:
if not nums:
return 0
l = len(nums)
if l == 1:
return nums[0]
elif l == 2:
return max(nums[0], nums[1])
elif l == 3:
retu... |
# sheldon woodward
# 2/10/19
from collections import defaultdict
def find_anagram(words):
"""
Takes a list of words and finds all anagram sets within the list. Instead of using a standard python dictionary
as a hashmap, this method uses the defaultdict object. defaultdict is more efficient than a standar... |
# La leyenda de Filius Bonacci
# Espiral Fibonacci
# Imprima ๐ nรบmeros de la sucesion de Fibonacci
# 0, 1, 1, 2, 3, 5, 8, 13, 21 ...
def fibonacci(n):
n_anterior = 0
n_actual = 1
sucesion = ""
for i in range(n):
if i == 0:
sucesion += "0"
elif i == 1:
sucesion += ", 1"
else:
aux = n_actual
n_ac... |
from flask import flash, redirect, url_for
from flask_admin import Admin, BaseView, expose
from ..admin import AdminPermissionRequiredMixin
from . import models
class DiscourseView(AdminPermissionRequiredMixin, BaseView):
@expose('/')
def index(self):
return self.render('admin/discourse_index.html')
... |
__author__ = 'Lucas Amaral'
class Pessoa:
_nome = "asdf"
_nascimento = "12345"
def __init__(self, new_name, data_nasc):
self._nome = new_name
self._nascimento = data_nasc
def setNome(self, new_name):
self._nome = new_name
def getNome(self):
return self._nome
... |
print('ะะฒะตะดััั ะฒะธัะพัั ะบะพะถะฝะพั ะดัะฐะณัะฐะผะธ ะคะตััะต, ะดะปั ะทะฐะบัะฝัะตะฝะฝั ะดะฒััั ะฝะฐะถะธะผะฐะนัะต enter')
a = int(input('-->> '))
rices = []
while True:
try:
rices.append(a)
a = int(input('-->> '))
except:
break
val = 1
for i in rices:
val *= i
print("ะัะปัะบัััั ััะฐัะบัะพััะน ะฝะฐ ะทะฐะดะฐะฝัะน ะดั... |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from .forms import *
from reports.models import *
from django.shortcuts import render_to_response, render, redirect
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_protect, c... |
import pytest
from page.home_page import *
from page.notice_list_page import *
import time
'''ๆต่ฏๅ
ฌๅๅ่กจ้กต'''
class TestNoticeList():
def enter_in_notice_page(self,driver,host,pkUser,pkCompany):
'''่ฟๅ
ฅๅ
ฌๅธๅ
ฌๅ้กต'''
HomePage(driver).open(host,pkUser,pkCompany)
list=NoticeListPage(driver)
list.... |
import eqparser
def createTreeCopy(root):
if root == None:
return None;
newRoot = eqparser.Node(root.type,[],root.leaf)
if isinstance(root.children,list) == False:
root.children = [root.children];
for i in range(len(root.children)):
newRoot.children.append(createTreeCopy(root.children[i]))
return newRoot
... |
import sys
T = int(sys.stdin.readline().rstrip())
for _ in range(T):
empty = sys.stdin.readline().rstrip()
N = int(sys.stdin.readline().rstrip())
total = 0
for _ in range(N):
i = int(sys.stdin.readline().rstrip())
total += i
if total % N == 0:
print("YES")
else:
... |
#-*- coding:utf-8 -*-
import datetime
import time
import json
from celery.task import task
from celery.task.sets import subtask
from shopback import paramconfig as pcfg
from shopback.items.tasks import updateUserItemsTask,updateUserProductSkuTask
from shopback.fenxiao.tasks import saveUserFenxiaoProductTask
from shopba... |
def composite_trapezoidal(fn, a, b, M):
h = (b-a) / M
s = 0
for k in range(1, M):
x = a + h * k
s += h * fn(x)
s += h / 2 * (fn(a) + fn(b))
return s
def composite_simpson(fn, a, b, M):
h = (b-a) / (2*M)
s1 = 0
s2 = 0
for k in range(1, M):
x = a + 2*h*k... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# By Antoine Maziรจres -- http://ant1.cc/
# For CorText Project -- http://cortext.fr/
# CC-BY-CA
#
# This script query a Seeks server ($seeks_node) and return a list of seeds URL to crawl
# usage for debug : python ./make_seeds.py | tee log.txt && wc -l log.txt
import json
im... |
import itertools
if __name__ == '__main__':
data, r = input().split()
results = []
for output in itertools.permutations(data, int(r)):
results.append(''.join(list(output)))
results.sort()
for text in results:
print(text)
|
import os #this library provides an interface between Python and an operating system
def add_preamble(directory):
for path, names, files in os.walk(directory): #os.walk(directory) returns the path, names of subdirectories and names of files of a directory, creating a directory treee
if names != 'vendor' o... |
age = input("Enter your age: ")
new_age = age + 50
print(new_age)
# input doesn't convert to a string anymore
# Python casts to highests number type
|
from django.shortcuts import render
import numpy as np
import pandas as pd
from . import forms
import pickle
import os
# Create your views here.
def readData(filepath='data/water_potability.csv'):
df = pd.read_csv(filepath)
X = df.iloc[:,0:len(df.columns)-1]
y = df.iloc[:, -1]
return X, y
def evalua... |
# python 2.7.3
import sys
import math
n = input()
print n * (n + 1) * (n + 2) / 2
|
# 10 binden kรผรงรผk fibonacci sayฤฑlarฤฑnฤฑn en bรผyรผฤรผnรผ bulan algoritma
fn1, fn2 = 1, 1
fn3 = 42 #fn3 e herhangi bir deฤer atamamฤฑz gerekiyordu tanฤฑmlฤฑ olmasฤฑ iรงin
while(fn3<10000): #10.000den kรผรงรผk olduฤu yerlerde yaptฤฑrmak istediฤimiz iลlemleri dรถngรผye aldฤฑk
fn3 = fn1 + fn2
fn1 = fn2
fn2 = fn3
pri... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import shutil
import torch
class Logger:
def __init__(self, output_dir):
# Remove and recreate output_dirs
shutil.rmtree(output_dir, ignore_errors=True)
os.makedirs(output_dir)
se... |
import weakref
from .._compat.typing import Callable, Any
from types import MethodType
__all__ = ['weak_method']
def weak_method(method: Callable) -> Callable:
assert isinstance(method, MethodType)
self_ref = weakref.ref(method.__self__)
function_ref = weakref.ref(method.__func__)
def wrapped(*arg... |
set1 = {1,2,3,5,"Print",5.3, 1, 2,3}
print(set1)
|
from django.shortcuts import render
from .models import Publicacion
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from .forms import PostForm
from django.shortcuts import redirect
# Create your views here.
def listar_pub(request):
pubs = Publicacion.objects.filter(fecha_... |
# For Practice
#Ask user their age
#Tell them how old they will be next year.
#CTI 110 #Assigment
#CTI 110 #Assigment
# Javonte Woods
#11/8/2018
# Header
# Get input number=int(input("Enter number:"))
#Calculate the answear answear = number*2
#Print output print("Your result is",answear)
print... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Ana")
process.load('FWCore.MessageService.MessageLogger_cfi')
##-------------------- Communicate with the DB -----------------------
process.load('Configuration.StandardSequences.Services_cff')
process.load('Configuration.StandardSequences.FrontierConditi... |
#!/usr/bin/env python3
import re
def word_frequencies(filename="src/alice.txt"):
d = {}
with open(filename, "r") as f:
for row in f:
r = list(row.split())
for w in r:
w = w.strip("""!"#$%&'()*,-./:;?@[]_""")
if w in d.keys():
d[... |
import operator as op
print(op.add(4, 5))
print(op.mul(4, 5))
print(op.contains([1, 2, 3], 4)) # 4 in [1, 2, 3]
x = [1, 2, 3]
#x ={"123": 3}
f = op.itemgetter(2) # f(x) == x[2]
#f = op.itemgetter("123") # f(x) == x["123"]
print(f(x)) |
import math
from typing import NamedTuple
from shared.vector import Vec2
class Ray(NamedTuple):
origin: Vec2
direction: Vec2
class LineSegment(NamedTuple):
a: Vec2
b: Vec2
# https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect/
def get_intersection(ray: R... |
from os import getcwd
from sys import path
path.insert(1,getcwd()+"\\Library\\")
import Library
vloop = "Y"
vask = "N"
while (vloop=="Y") or (vloop=="y"):
Library.main.main()
while (vask=="N"):
vloop= input ("\nDo you want to try another word? (Y/N) ")
if (vloop=="Y") ... |
#CSCI 1133 Homework 2
#Sid Lin
#Problem 2A
#fibonacci function
def newFib(first, second, term):
count = 0 # number of terms
while (count < term - 2): # -2 because the first 2 are printed in main()
next = first + second #previous terms added
print(next, end = " ")
first = second
... |
import os
import subprocess
import re
import argparse
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
y_names = ['toxic', 'severe_toxic', 'obscene',
'threat', 'insult', 'identity_hate']
upsample_id = 'xxxxxxxxxxxxxxxx'
def upsample():
''' upsample rare classes
... |
#can sort string with sorted()
from collections import defaultdict
def isPermutation1(str1, str2):
if len(str1) != len(str2):
return false
elif str1 == "" and str2 == "":
return True;
sorted1 = sorted(str1)
sorted2 = sorted(str2)
if sorted1 == sorted2:
return True
else: r... |
from mysql import connector
import mysql.connector.errors as CE
from urllib2 import urlopen
from multiprocessing import pool
import json
from time import sleep
from pprint import pprint
#db connection object
conn = connector.connect(host='localhost',user='root',passwd='root',db='cubito')
cursor = conn.cursor()
def g... |
import brownie
import pytest
from brownie import Wei
DEADLINE = 9999999999999
ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"
@pytest.fixture()
def liquid_lgt(lgt, accounts):
lgt.mint(50, {'from': accounts[0]})
lgt.addLiquidity(1, 51, 99999999999, {'from': accounts[0], 'value': "0.05 e... |
import random as r
import os, sys, time, threading, multiprocessing
numberOfCores=multiprocessing.cpu_count()
def task(cmd):
w=r.randint(2,5)
time.sleep(w)
return
# Run Multiple Thread
for i in range(16):
cmd=str(i+1)
msg="...Thread %s start...."%(cmd)
print(msg)
t = thread... |
{
PDBConst.Name: "bill",
PDBConst.Columns: [
{
PDBConst.Name: "ID",
PDBConst.Attributes: ["int", "not null", "auto_increment", "primary key"]
},
{
PDBConst.Name: "PID",
PDBConst.Attributes: ["int", "not null"]
},
{
PDBConst.Name: "Datetime",
PD... |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pickle
from presentNN import genPic,save2Pic
import math
BASE_DIR_PIC = './picDir/'
BASE = 0
MAX = 6000
STEP = 1000
THETA1 = 0
THETA2 = 10*2*math.pi/360
save2Pic(BASE_DIR_PIC,BASE,MAX,STEP,THETA1)
save2Pic(BASE_DIR_PIC,BASE,MAX,STEP,THETA2... |
from bs4 import BeautifulSoup
import requests
import re
## Time Pattern
TIME = re.compile('(\d{1,2}):(\d\d)\s*([AaPp]\.?\s*[Mm]\.?)?')
TIME_DAYS = re.compile('(\d{1,2}):(\d\d)\s+([A-Za-z]+)')
## Normalization for day
def norm_days(days: str) -> int:
DAYS = [('M', 0), ('TU', 1), ('W', 2), ('TH', 3), ('F', 4)]
... |
import click
import pkgutil
import shutil
import os.path
from datetime import datetime
from slackviewer.constants import SLACKVIEWER_TEMP_PATH
from slackviewer.utils.click import envvar, flag_ennvar
from slackviewer.reader import Reader
from slackviewer.archive import get_export_info
from jinja2 import Environment, P... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.