blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
281
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 6
116
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 313
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 18.2k
668M
⌀ | star_events_count
int64 0
102k
| fork_events_count
int64 0
38.2k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 107
values | src_encoding
stringclasses 20
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 4
6.02M
| extension
stringclasses 78
values | content
stringlengths 2
6.02M
| authors
listlengths 1
1
| author
stringlengths 0
175
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7155ce2f0f61965636f0aa47b05584bfef6097ba
|
82d4aac095fb4038563162c56fb1b55c1619467b
|
/biuropodrozy/users/tests/test_forms.py
|
1bf33e1fc13111eff41545e977c6c2d14d7f2f5d
|
[
"MIT"
] |
permissive
|
Kamilgolda/TripRecommendations
|
f133ec8de99b48b7f55ad90d72f3ee8ad12254ee
|
d3e5a10d80c405d5ac22f028be54c8198bc10410
|
refs/heads/master
| 2023-06-19T08:21:20.938540
| 2021-07-05T09:24:40
| 2021-07-05T09:24:40
| 380,500,741
| 0
| 3
|
MIT
| 2021-07-05T09:24:41
| 2021-06-26T12:50:45
|
Python
|
UTF-8
|
Python
| false
| false
| 1,174
|
py
|
"""
Module for all Form Tests.
"""
import pytest
from django.utils.translation import ugettext_lazy as _
from biuropodrozy.users.forms import UserCreationForm
from biuropodrozy.users.models import User
pytestmark = pytest.mark.django_db
class TestUserCreationForm:
"""
Test class for all tests related to the UserCreationForm
"""
def test_username_validation_error_msg(self, user: User):
"""
Tests UserCreation Form's unique validator functions correctly by testing:
1) A new user with an existing username cannot be added.
2) Only 1 error is raised by the UserCreation Form
3) The desired error message is raised
"""
# The user already exists,
# hence cannot be created.
form = UserCreationForm(
{
"username": user.username,
"password1": user.password,
"password2": user.password,
}
)
assert not form.is_valid()
assert len(form.errors) == 1
assert "username" in form.errors
assert form.errors["username"][0] == _("This username has already been taken.")
|
[
"michaeldzindzio@gmail.com"
] |
michaeldzindzio@gmail.com
|
0b7b8cc2114aca9d05671b6b132a1a909f63ca55
|
f97a267b066f64177e382346e36cc06c25a3a6b1
|
/src/quart/typing.py
|
a1be3a52dbb6ec3db1d23f2cf3688f19f97a56fe
|
[
"MIT"
] |
permissive
|
p-unity-lineage/quart
|
a54ec9a1e6f61159c5c2688e24a2b54462bcd231
|
14efcd92f37bb4ef78d463d6d145f71c61665470
|
refs/heads/master
| 2023-03-31T23:56:56.881288
| 2021-04-11T09:28:28
| 2021-04-11T09:28:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 8,067
|
py
|
from __future__ import annotations
import os
from datetime import datetime, timedelta
from types import TracebackType
from typing import (
Any,
AnyStr,
AsyncContextManager,
AsyncGenerator,
Awaitable,
Callable,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
TYPE_CHECKING,
Union,
)
from hypercorn.typing import (
ASGIReceiveCallable,
ASGISendCallable,
HTTPScope,
LifespanScope,
WebsocketScope,
)
try:
from typing import Protocol
except ImportError:
from typing_extensions import Protocol # type: ignore
if TYPE_CHECKING:
from werkzeug.datastructures import Headers # noqa: F401
from werkzeug.wrappers import Response as WerkzeugResponse
from .app import Quart
from .sessions import Session
from .wrappers.response import Response # noqa: F401
FilePath = Union[bytes, str, os.PathLike]
# The possible types that are directly convertible or are a Response object.
ResponseValue = Union[
"Response",
"WerkzeugResponse",
AnyStr,
Dict[str, Any], # any jsonify-able dict
AsyncGenerator[bytes, None],
Generator[bytes, None, None],
]
StatusCode = int
# the possible types for an individual HTTP header
HeaderName = str
HeaderValue = Union[str, List[str], Tuple[str, ...]]
# the possible types for HTTP headers
HeadersValue = Union["Headers", Dict[HeaderName, HeaderValue], List[Tuple[HeaderName, HeaderValue]]]
# The possible types returned by a route function.
ResponseReturnValue = Union[
ResponseValue,
Tuple[ResponseValue, HeadersValue],
Tuple[ResponseValue, StatusCode],
Tuple[ResponseValue, StatusCode, HeadersValue],
]
AppOrBlueprintKey = Optional[str] # The App key is None, whereas blueprints are named
AfterRequestCallable = Callable[["Response"], Awaitable["Response"]]
AfterWebsocketCallable = Callable[["Response"], Awaitable[Optional["Response"]]]
BeforeRequestCallable = Callable[[], Awaitable[None]]
BeforeWebsocketCallable = Callable[[], Awaitable[None]]
ErrorHandlerCallable = Callable[[Exception], Awaitable[None]]
TeardownCallable = Callable[[Optional[BaseException]], Awaitable["Response"]]
TemplateContextProcessorCallable = Callable[[], Awaitable[Dict[str, Any]]]
URLDefaultCallable = Callable[[str, dict], None]
URLValuePreprocessorCallable = Callable[[str, dict], None]
class ASGIHTTPProtocol(Protocol):
def __init__(self, app: Quart, scope: HTTPScope) -> None:
...
async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
...
class ASGILifespanProtocol(Protocol):
def __init__(self, app: Quart, scope: LifespanScope) -> None:
...
async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
...
class ASGIWebsocketProtocol(Protocol):
def __init__(self, app: Quart, scope: WebsocketScope) -> None:
...
async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
...
class TestHTTPConnectionProtocol(Protocol):
push_promises: List[Tuple[str, Headers]]
def __init__(self, app: Quart, scope: HTTPScope, _preserve_context: bool = False) -> None:
...
async def send(self, data: bytes) -> None:
...
async def send_complete(self) -> None:
...
async def receive(self) -> bytes:
...
async def disconnect(self) -> None:
...
async def __aenter__(self) -> TestHTTPConnectionProtocol:
...
async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
...
async def as_response(self) -> Response:
...
class TestWebsocketConnectionProtocol(Protocol):
def __init__(self, app: Quart, scope: WebsocketScope) -> None:
...
async def __aenter__(self) -> TestWebsocketConnectionProtocol:
...
async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
...
async def receive(self) -> AnyStr:
...
async def send(self, data: AnyStr) -> None:
...
async def receive_json(self) -> Any:
...
async def send_json(self, data: Any) -> None:
...
async def close(self, code: int) -> None:
...
async def disconnect(self) -> None:
...
class TestClientProtocol(Protocol):
http_connection_class: Type[TestHTTPConnectionProtocol]
push_promises: List[Tuple[str, Headers]]
websocket_connection_class: Type[TestWebsocketConnectionProtocol]
def __init__(self, app: Quart, use_cookies: bool = True) -> None:
...
async def open(
self,
path: str,
*,
method: str = "GET",
headers: Optional[Union[dict, Headers]] = None,
data: Optional[AnyStr] = None,
form: Optional[dict] = None,
query_string: Optional[dict] = None,
json: Any = None,
scheme: str = "http",
follow_redirects: bool = False,
root_path: str = "",
http_version: str = "1.1",
) -> Response:
...
def request(
self,
path: str,
*,
method: str = "GET",
headers: Optional[Union[dict, Headers]] = None,
query_string: Optional[dict] = None,
scheme: str = "http",
root_path: str = "",
http_version: str = "1.1",
) -> TestHTTPConnectionProtocol:
...
def websocket(
self,
path: str,
*,
headers: Optional[Union[dict, Headers]] = None,
query_string: Optional[dict] = None,
scheme: str = "ws",
subprotocols: Optional[List[str]] = None,
root_path: str = "",
http_version: str = "1.1",
) -> TestWebsocketConnectionProtocol:
...
async def delete(self, *args: Any, **kwargs: Any) -> Response:
...
async def get(self, *args: Any, **kwargs: Any) -> Response:
...
async def head(self, *args: Any, **kwargs: Any) -> Response:
...
async def options(self, *args: Any, **kwargs: Any) -> Response:
...
async def patch(self, *args: Any, **kwargs: Any) -> Response:
...
async def post(self, *args: Any, **kwargs: Any) -> Response:
...
async def put(self, *args: Any, **kwargs: Any) -> Response:
...
async def trace(self, *args: Any, **kwargs: Any) -> Response:
...
def set_cookie(
self,
server_name: str,
key: str,
value: str = "",
max_age: Optional[Union[int, timedelta]] = None,
expires: Optional[Union[int, float, datetime]] = None,
path: str = "/",
domain: Optional[str] = None,
secure: bool = False,
httponly: bool = False,
samesite: str = None,
charset: str = "utf-8",
) -> None:
...
def delete_cookie(
self, server_name: str, key: str, path: str = "/", domain: Optional[str] = None
) -> None:
...
def session_transaction(
self,
path: str = "/",
*,
method: str = "GET",
headers: Optional[Union[dict, Headers]] = None,
query_string: Optional[dict] = None,
scheme: str = "http",
data: Optional[AnyStr] = None,
form: Optional[dict] = None,
json: Any = None,
root_path: str = "",
http_version: str = "1.1",
) -> AsyncContextManager[Session]:
...
async def __aenter__(self) -> TestClientProtocol:
...
async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
...
class TestAppProtocol(Protocol):
def __init__(self, app: Quart) -> None:
...
def test_client(self) -> TestClientProtocol:
...
async def startup(self) -> None:
...
async def shutdown(self) -> None:
...
async def __aenter__(self) -> TestAppProtocol:
...
async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
...
|
[
"philip.graham.jones@googlemail.com"
] |
philip.graham.jones@googlemail.com
|
4f8956babeaeca36bcee259d46ecb8ec16dbe067
|
dc084a369e0f767bc5296739b24813470869522f
|
/main.py
|
ad9e07dfe136e778903fe0b117e3877fc9bb1631
|
[] |
no_license
|
JakeRoggenbuck/player_data_finder
|
4a539ac7963f1f5025eda89c96c75e76a8268574
|
0ba87a5511810ac10d3f40049b21541b9a8be1bb
|
refs/heads/master
| 2022-12-02T06:59:34.054775
| 2020-08-19T05:56:55
| 2020-08-19T05:56:55
| 288,645,171
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,609
|
py
|
from position_reader import PositionReader
from config import Config
from ftplib import FTP
import inquirer
import json
import os
class FTPConnection:
def __init__(self):
self.server = FTP()
def connect(self):
self.server.connect(Config.host, Config.port)
def login(self):
self.server.login(Config.username, Config.password)
def start(self):
self.connect()
self.login()
class UsernameCache:
def __init__(self):
self.ftp = FTPConnection()
self.ftp.start()
self.path = "/"
self.name = "usernamecache.json"
self.data = []
def handle_binary(self, more_data):
self.data.append(more_data.decode('utf-8'))
def get_usernames(self):
self.ftp.server.cwd(self.path)
self.ftp.server.retrbinary(f"RETR {self.name}",
callback=self.handle_binary)
def return_file(self):
return "".join(self.data)
def get_json(self):
return json.loads(self.return_file())
class Username:
def __init__(self):
self.usernamecache = UsernameCache()
self.usernamecache.get_usernames()
self.json = self.usernamecache.get_json()
self.usernames = []
self.new_json = self.get_new_json()
def get_new_json(self):
return dict((y, x) for x, y in self.json.items())
class AskUsername:
def __init__(self):
self.username = Username()
self.json = self.username.new_json
def get_username(self):
usernames = self.json.keys()
questions = [inquirer.Checkbox(
"Username",
message="Select username",
choices=usernames
)]
answers = inquirer.prompt(questions)
return answers
def get_uuid(self):
username = self.get_username()["Username"][0]
return self.json[username]
class GetDataFile:
def __init__(self):
self.ftp = FTPConnection()
self.ftp.start()
self.path = "/RAT STANDO/playerdata/"
self.username = AskUsername()
self.uuid = self.username.get_uuid()
self.filename = f"{self.uuid}.dat"
self.full_path = os.path.join("data/", self.filename)
def save_file(self):
self.ftp.server.cwd(self.path)
self.ftp.server.retrbinary(f"RETR {self.filename}",
open(self.full_path, 'wb').write)
if __name__ == "__main__":
datafile = GetDataFile()
datafile.save_file()
path = datafile.full_path
pr = PositionReader(path)
pos = pr.get_pos()
print(pos)
|
[
"jakeroggenbuck2@gmail.com"
] |
jakeroggenbuck2@gmail.com
|
ec7f35863a5fdd22a268819767e01e4dac4a06b1
|
b44d094093d8852839eb715fafa7a3d2f41da582
|
/wr_pintar_master/wizard/master_custom_import.py
|
110451813ad0f8f3cdf3845dc776b3c657f06fbe
|
[] |
no_license
|
sharibar/wr_pintar_recruitment
|
4ab52a4185e9fb775f5275cd2c40f14c295efb15
|
24c1007c5fe90d08290f4c6ffdeec37d301c002c
|
refs/heads/master
| 2020-04-18T23:00:40.026791
| 2019-01-28T06:00:23
| 2019-01-28T06:00:23
| 167,810,468
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,433
|
py
|
# -*- coding: utf-8 -*-
from odoo import fields, models, api, _, sql_db
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT
from odoo.exceptions import UserError
import tempfile
import base64
from datetime import datetime
import xlrd
from xlrd import open_workbook
import threading
class MasterCustomImport(models.TransientModel):
_name = 'master.custom.import'
xls_file = fields.Binary("Import")
datas_file = fields.Char('Filename')
def import_xls(self):
datafile = self.xls_file
file_name = str(self.datas_file)
if not datafile:
raise UserError('File Masih Kosong!')
try:
book = xlrd.open_workbook(file_contents=base64.decodebytes(self.xls_file))
except xlrd.XLRDError as e:
raise UserError('Tolong hanya upload file xlsx saja, Terima Kasih')
header = {}
sheet = book.sheet_by_index(0)
#get header
for col in range(sheet.ncols):
if sheet.cell_value(0, col) == 'Nama Item':
header['name'] = col
elif sheet.cell_value(0, col) == 'Tanggal Mulai Pengerjaan':
header['tanggal_mulai'] = col
elif sheet.cell_value(0, col) == 'Nama Komponen':
header['komponen.name'] = col
elif sheet.cell_value(0, col) == 'Waktu Pengerjaan Komponen':
header['komponen.waktu_pengerjaan'] = col
elif sheet.cell_value(0, col) == 'Tipe Waktu':
header['komponen.tipe_waktu'] = col
elif sheet.cell_value(0, col) == 'Bobot Presentase Komponen':
header['line_ids.percentage'] = col
all_vals = []
last_item = -1
for row in range(sheet.nrows):
if row == 0:
continue
vals = {}
if sheet.cell_value(row, header['name']):
vals['name'] = sheet.cell_value(row, header['name'])
if sheet.cell_value(row, header['tanggal_mulai']):
exceltime = sheet.cell_value(row, header['tanggal_mulai'])
time_tuple = xlrd.xldate_as_tuple(exceltime, 0)
date_py = datetime(*time_tuple)
date_str = date_py.strftime(DEFAULT_SERVER_DATE_FORMAT)
vals['tanggal_mulai'] = date_str
komponen = self.env['master.komponen'].search(
[('name', '=', sheet.cell_value(row, header['komponen.name']))])
komponen = komponen[0] if komponen else False
if not komponen:
komponen = self.env['master.komponen'].create({
'name': sheet.cell_value(row, header['komponen.name']) if header['komponen.name'] else False,
'tipe_waktu': sheet.cell_value(row, header['komponen.tipe_waktu']) if header['komponen.tipe_waktu'] else 'hari',
'waktu_pengerjaan': sheet.cell_value(row, header['komponen.waktu_pengerjaan']) if header['komponen.waktu_pengerjaan'] else False
})
else:
komponen.write({
'tipe_waktu': sheet.cell_value(row, header['komponen.tipe_waktu']) if header['komponen.tipe_waktu'] else komponen.tipe_waktu,
'waktu_pengerjaan': int(sheet.cell_value(row, header['komponen.waktu_pengerjaan'])) if header['komponen.waktu_pengerjaan'] else komponen.waktu_pengerjaan,
})
if vals:
line_ids = [(0, 0, {
'komponen': komponen.id,
'percentage': int(sheet.cell_value(row, header['line_ids.percentage'])) * 100 if header['line_ids.percentage'] else 0
})]
vals['line_ids'] = line_ids
last_item += 1
all_vals.append(vals)
else:
vals = all_vals[last_item]
line_ids = vals.get('line_ids', [])
line_ids.append((0, 0, {
'komponen': komponen.id,
'percentage': int(sheet.cell_value(row, header['line_ids.percentage']) * 100 if header['line_ids.percentage'] else 0)
}))
vals['line_ids'] = line_ids
all_vals[last_item] = vals
for rec in all_vals:
res = self.env['master.item'].create(rec)
action = self.env.ref('wr_pintar_master.action_master_item').read()[0]
return action
|
[
"syarifudin@portcities.net"
] |
syarifudin@portcities.net
|
930903de90fc8bc73e32778e7f3480292f94f079
|
2c6466fa6ae9d3a4806f325a28ad6c8c7f490d04
|
/exercicios/PythonExercicios_Desafio069.py
|
3b0b9b6d7d542dea3725c88382dc19a554316544
|
[] |
no_license
|
samuelfranca7l/PythonExercises
|
94750483a4c44e969ec254f5dd44e1c40a2fdc02
|
50571da236bb2eab04afe8d6e6246884bafc99ec
|
refs/heads/master
| 2022-07-04T23:26:24.623353
| 2020-05-22T20:18:01
| 2020-05-22T20:18:01
| 266,181,167
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 809
|
py
|
igenderM = iage18 = iFemaleAge20 = 0
opcao = ''
while True:
print('-' * 30)
print('CADASTRE UMA PESSOA')
print('-' * 30)
idade = int(input('Idade: '))
sexo = str(input('Sexo: [M/F]')).upper().strip()
while sexo not in 'MF':
sexo = str(input('Sexo: [M/F]')).upper().strip()
if sexo == 'M':
igenderM += 1
if idade > 18:
iage18 += 1
if sexo == 'F':
if idade < 20:
iFemaleAge20 += 1
opcao = str(input('Deseja continuar? [S/N]')).upper().strip()
if opcao == 'N':
break
while opcao != 'S':
opcao = str(input('Deseja continuar? [S/N]')).upper().strip()
print(f'''Foram cadastradas {iage18} pessoas maiores de 18 anos, {igenderM} homens e {iFemaleAge20} mulheres menores
de 20 anos''')
print('FIM DO JOGO')
|
[
"samuelfranca.m@gmail.com"
] |
samuelfranca.m@gmail.com
|
03e86919c07935ea23cbd2bc2035ff9e3aab5dfa
|
f43e9b5387d12fb844cf255a54c84615172fe37a
|
/courses/migrations/0010_auto_20200618_1157.py
|
99856d87b88654f3675b27c931663a3768fcb6df
|
[] |
no_license
|
Code-Institute-Submissions/ashleigh_baking_school
|
09012899985ae898d84b847ccd2d50ba7f80813e
|
add4a404882e63952f3fced7ba22243765583584
|
refs/heads/master
| 2022-11-24T13:56:22.149495
| 2020-07-31T11:09:17
| 2020-07-31T11:09:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 374
|
py
|
# Generated by Django 3.0.7 on 2020-06-18 11:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0009_auto_20200618_1154'),
]
operations = [
migrations.RenameField(
model_name='course',
old_name='datetime',
new_name='course_datetime',
),
]
|
[
"sandoralai@gmail.com"
] |
sandoralai@gmail.com
|
d80b410b5348e0c0627858a462910f433012546d
|
53be3b2a18d4df2e675525a610f4e7dab8c0de6f
|
/myems-api/core/version.py
|
0b884d96063823d791417aec31bff4eac4345132
|
[
"MIT"
] |
permissive
|
yxw027/myems
|
16dc82fa26328e00adbba4e09301c4cf363ad28d
|
ea58d50c436feafb1a51627aa4d84caf8f3aee08
|
refs/heads/master
| 2023-09-03T17:57:18.728606
| 2021-11-04T14:13:42
| 2021-11-04T14:13:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 473
|
py
|
import falcon
import simplejson as json
class VersionItem:
@staticmethod
def __init__():
""""Initializes VersionItem"""
pass
@staticmethod
def on_options(req, resp, id_):
resp.status = falcon.HTTP_200
@staticmethod
def on_get(req, resp):
result = {"version": 'MyEMS v1.3.3',
"release-date": '2021-10-30',
"website": "https://myems.io"}
resp.body = json.dumps(result)
|
[
"13621160019@163.com"
] |
13621160019@163.com
|
5fa21fadd207f6922a41ad01fad7d3295d852e5d
|
de358ba57518d65393c810da20c53e1c41494bff
|
/ALGOPYTHON/array2.py
|
616580064c661e80fb9915007e10e09ad9a0cb0f
|
[] |
no_license
|
avirupdandapat/ALGOPROJECT
|
43eef94b13e38452cdc6a506b17b6fee581a07e1
|
55b60a0c6e51cae900e243505f6a4557ad4d7069
|
refs/heads/master
| 2022-12-29T13:02:54.655976
| 2020-10-18T12:23:57
| 2020-10-18T12:23:57
| 305,095,375
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 252
|
py
|
import subprocess
subprocess.run('dir', shell=True)
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n = int(input())
q = list(map(int, input().rstrip().split()))
# arr = minimumBribes(a)
print(q)
|
[
"avirup.dandapat@mindtree.com"
] |
avirup.dandapat@mindtree.com
|
0e541e32d749a1302541ce19ccdf2b6c8d442a16
|
bdc4ae3d691fcb50405235d963012d84ea8b8a06
|
/src/b2r2b_youbot/message.py
|
d8d3c2a392182dba8f26573558c936ec091c3489
|
[] |
no_license
|
AndreaCensi/rosstream2boot
|
53552a256979f072c7bf4abb9bc01eed3c960e97
|
7cce8cf270b67e8c9e5abe6cdfed9d5969a82c00
|
refs/heads/master
| 2021-01-01T19:11:04.669798
| 2013-07-13T14:11:28
| 2013-07-13T14:11:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,658
|
py
|
from b2r2b_youbot import get_JointVelocities, get_JointValue, get_JointPositions
__all__ = ['get_joint_position_msg', 'get_joint_velocity_msg']
def get_joint_velocity_msg(array, timeStamp=None):
'''
:param array: float array with values to the joints
'''
JointVelocities = get_JointVelocities()
JointValue = get_JointValue()
num_joints = len(array)
msg = JointVelocities()
msg.poisonStamp.description = 'Joint velocities generated by b2r2b.'
for i in range(num_joints):
joint_value = JointValue()
joint_value.joint_uri = 'arm_joint_' + str(i + 1)
if timeStamp is not None:
joint_value.timeStamp = timeStamp
joint_value.unit = 's^-1 rad'
joint_value.value = array[i]
msg.velocities.append(joint_value)
assert len(msg.velocities) == num_joints
return msg
def get_joint_position_msg(array, timeStamp=None):
'''
:param array: float array with values to the joints
'''
JointPositions = get_JointPositions()
JointValue = get_JointValue()
num_joints = len(array)
msg = JointPositions()
msg.poisonStamp.description = 'Joint velocities generated by b2r2b'
for i in range(num_joints):
joint_value = JointValue()
joint_value.joint_uri = 'arm_joint_' + str(i + 1)
if timeStamp is not None:
joint_value.timeStamp = timeStamp
joint_value.unit = 'rad'
joint_value.value = array[i]
msg.positions.append(joint_value)
assert len(msg.positions) == num_joints
return msg
|
[
"andrea@cds.caltech.edu"
] |
andrea@cds.caltech.edu
|
5029d4ff82c752725820c976fe5935f269b09177
|
70137ac67ba2cd9970167b55fc5bbba7ce051950
|
/叠加事件驱动策略/bert_base/train/train_helper.py
|
36b0b8df0326bf02e18150c2e4339b6b98a99822
|
[] |
no_license
|
zhangfeng0812/quanta_competition
|
bbe0f73cbd51f9291f25515c260da7342987df7e
|
3f56e6855db1638a1e7131670ea8660b63f85fc5
|
refs/heads/master
| 2020-09-16T16:19:05.067187
| 2019-11-25T00:06:24
| 2019-11-25T00:06:24
| 223,826,497
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,918
|
py
|
# -*- coding: utf-8 -*-
"""
@Time : 2019/1/30 14:01
@File : train_helper.py
"""
import argparse
import os
__all__ = ['get_args_parser']
def get_args_parser():
__version__ = '0.1.0'
parser = argparse.ArgumentParser()
# windows下的路径表示
if os.name == 'nt':
bert_path = r'E:\nlp_data\chinese_L-12_H-768_A-12'
root_path = r'E:\app\projects\bert_ner'
group1 = parser.add_argument_group('File Paths',
'config the path, checkpoint and filename of a pretrained/fine-tuned BERT model')
group1.add_argument('-bert_path', type=str, default=bert_path,
help='directory of a pretrained BERT ')
group1.add_argument('-model_path', type=str, default=os.path.join(root_path, 'output2'),
help='trained BERT model')
group1.add_argument('-data_dir', type=str, default=os.path.join(root_path, 'NERdata2'),
help='train, dev and test data dir')
group1.add_argument('-bert_config_file', type=str, default=os.path.join(bert_path, 'bert_config.json'))
group1.add_argument('-output_dir', type=str, default=os.path.join(root_path, 'output2'),
help='directory of a pretrained BERT model')
group1.add_argument('-init_checkpoint', type=str, default=os.path.join(bert_path, 'bert_model.ckpt'),
help='Initial checkpoint (usually from a pre-trained BERT model).')
group1.add_argument('-vocab_file', type=str, default=os.path.join(bert_path, 'vocab.txt'),
help='')
group2 = parser.add_argument_group('Model Config', 'config the model params')
# 减少最大的长度,字向量:128——32
group2.add_argument('-max_seq_length', type=int, default=128,
help='The maximum total input sequence length after WordPiece tokenization.')
group2.add_argument('-do_train', type=bool, default=True,
help='Whether to run training.')
group2.add_argument('-do_eval', type=bool, default=True,
help='Whether to run eval on the dev set.')
group2.add_argument('-do_predict', type=bool, default=True,
help='Whether to run the model in inference mode on the test set.')
# 减少batch_size:64——16
group2.add_argument('-batch_size', type=int, default=32,
help='Total batch size for training, eval and predict.')
group2.add_argument('-learning_rate', type=float, default=1e-5,
help='The initial learning rate for Adam.')
group2.add_argument('-num_train_epochs', type=float, default=30,
help='Total number of training epochs to perform.')
# 修改2:减少丢失:0.5——0.2
group2.add_argument('-dropout_rate', type=float, default=0.5,
help='Dropout rate')
group2.add_argument('-clip', type=float, default=0.5,
help='Gradient clip')
group2.add_argument('-warmup_proportion', type=float, default=0.1,
help='Proportion of training to perform linear learning rate warmup for '
'E.g., 0.1 = 10% of training.')
group2.add_argument('-lstm_size', type=int, default=128,
help='size of lstm units.')
group2.add_argument('-num_layers', type=int, default=1,
help='number of rnn layers, default is 1.')
group2.add_argument('-cell', type=str, default='lstm',
help='which rnn cell used.')
group2.add_argument('-save_checkpoints_steps', type=int, default=200,
help='save_checkpoints_steps')
group2.add_argument('-save_summary_steps', type=int, default=200,
help='save_summary_steps.')
group2.add_argument('-filter_adam_var', type=bool, default=False,
help='after training do filter Adam params from model and save no Adam params model in file.')
group2.add_argument('-do_lower_case', type=bool, default=True,
help='Whether to lower case the input text.')
group2.add_argument('-clean', type=bool, default=True)
group2.add_argument('-device_map', type=str, default='0',
help='witch device using to train')
# add labels
group2.add_argument('-label_list', type=str, default=None,
help='User define labels, can be a file with one label one line or a string using \',\' split')
parser.add_argument('-verbose', action='store_true', default=False,
help='turn on tensorflow logging for debug')
parser.add_argument('-ner', type=str, default='ner', help='which modle to train')
parser.add_argument('-version', action='version', version='%(prog)s ' + __version__)
return parser.parse_args()
|
[
"zhfeng012@gamil.com"
] |
zhfeng012@gamil.com
|
12f1dc25839f93fc337543a1efe4d02aee854533
|
24899d6a3f14e7c4459194dac503b3b461f405ce
|
/PythonPrograms/regularExpression/mobile.py
|
1d4a51b9a114b403246014d98b2795e232bba451
|
[] |
no_license
|
joysjohney/Luminar_Python
|
73cb09a0211db39f808a70f9252866461267b30d
|
4774fc7c492cae16b89e74006c9164d76160eedb
|
refs/heads/master
| 2023-01-07T02:57:42.419864
| 2020-11-08T06:41:01
| 2020-11-08T06:41:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 216
|
py
|
# Validate mobile number
from re import *
rule="/d{10}"
mobno=input("Enter mobile number : ")
matcher=fullmatch(rule,mobno)
if(matcher !=None):
print("Valid mobile no")
else:
print("Invalid mobile no!")
|
[
"44256029+joysjohny@users.noreply.github.com"
] |
44256029+joysjohny@users.noreply.github.com
|
c654a4bea3614b29572919712190529cf7f00581
|
36e499a94a355bb2e18468abb6182a3c328580ea
|
/new_python/wordSegment/fool/lexical.py
|
509781011cb9f4d6e71d6a3f93268bad5c54ffda
|
[] |
no_license
|
1140831845/custkdxf_114code
|
0fbe9213b2e015c50aa6e66b8949f90c8cf49ea5
|
b7afe65af9e93609741981f0cc72b1eb7a6cd37d
|
refs/heads/master
| 2020-04-03T10:18:56.629852
| 2018-10-30T13:40:57
| 2018-10-30T13:40:57
| 155,189,860
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,982
|
py
|
#!/usr/bin/env python
# -*-coding:utf-8-*-
import sys
import os
import json
from .predictor import Predictor
from zipfile import ZipFile
OOV_STR = "<OOV>"
def _load_map_file(path, char_map_name, id_map_name):
with ZipFile(path) as myzip:
with myzip.open('all_map.json') as myfile:
content = myfile.readline()
content = content.decode()
data = json.loads(content)
return data.get(char_map_name), data.get(id_map_name)
class LexicalAnalyzer(object):
def __init__(self):
self.initialized = False
self.map = None
self.seg_model = None
self.pos_model = None
self.ner_model = None
self.data_path = os.path.join(os.path.abspath('.'), "wordSegment", "data")
self.map_file_path = os.path.join(self.data_path, "map.zip")
def _load_model(self, model_namel, word_map_name, tag_name):
seg_model_path = os.path.join(self.data_path, model_namel)
char_to_id, id_to_seg = _load_map_file(self.map_file_path, word_map_name, tag_name)
return Predictor(seg_model_path, char_to_id, id_to_seg)
def _load_seg_model(self):
self.seg_model = self._load_model("seg.pb", "char_map", "seg_map")
def _load_pos_model(self):
self.pos_model = self._load_model("pos.pb", "word_map", "pos_map")
def _load_ner_model(self):
self.ner_model = self._load_model("ner.pb", "char_map", "ner_map")
def pos(self, seg_words_list):
if not self.pos_model:
self._load_pos_model()
pos_labels = self.pos_model.predict(seg_words_list)
return pos_labels
def ner(self, text_list):
if not self.ner_model:
self._load_ner_model()
ner_labels = self.ner_model.predict(text_list)
all_entitys = []
for ti, text in enumerate(text_list):
ens = []
entity = ""
i = 0
ner_label = ner_labels[ti]
chars = list(text)
for label, word in zip(ner_label, chars):
i += 1
if label == "O":
continue
lt = label.split("_")[1]
lb = label.split("_")[0]
if lb == "S":
ens.append((i, i + 1, lt, word))
elif lb == "B":
entity = ""
entity += word
elif lb == "M":
entity += word
elif lb == "E":
entity += word
ens.append((i - len(entity), i + 1, lt, entity))
entity = ""
if entity:
ens.append((i - len(entity), i + 1, lt, entity))
all_entitys.append(ens)
return all_entitys
def cut(self, text_list):
if not self.seg_model:
self._load_seg_model()
all_labels = self.seg_model.predict(text_list)
sent_words = []
for ti, text in enumerate(text_list):
words = []
N = len(text)
seg_labels = all_labels[ti]
tmp_word = ""
for i in range(N):
label = seg_labels[i]
w = text[i]
if label == "B":
tmp_word += w
elif label == "M":
tmp_word += w
elif label == "E":
tmp_word += w
words.append(tmp_word)
tmp_word = ""
else:
tmp_word = ""
words.append(w)
if tmp_word:
words.append(tmp_word)
sent_words.append(words)
return sent_words
def analysis(self, text_list):
words = self.cut(text_list)
pos_labels = self.pos(words)
ners = self.ner(text_list)
word_inf = [list(zip(ws, ps)) for ws, ps in zip(words, pos_labels)]
return word_inf, ners
|
[
"1440831845@qq.com"
] |
1440831845@qq.com
|
eadaff38311d9b7fd22fb7f22162f2934b0a0a94
|
87bb2b9258c887e8fbcaca08d18e5d95ae96462d
|
/Codewars/Python/7kyu/7kyu_Largest pair in array.py
|
aec94dec63fcfa2b5e935b6ac65a4134e7f49ecf
|
[] |
no_license
|
KonradMarzec1991/Codewars-LeetCode
|
a9e4d09f4271fecb3a7fc1ee436358ac1bbec5e4
|
442113532158f5a3ee7051a42e911afa5373bb5f
|
refs/heads/master
| 2023-04-21T17:04:37.434876
| 2021-05-11T21:47:14
| 2021-05-11T21:47:14
| 166,555,499
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 99
|
py
|
def largest_pair_sum(numbers):
from heapq import nlargest
return sum(nlargest(2, numbers))
|
[
"konrimarzec@gmail.com"
] |
konrimarzec@gmail.com
|
5ae9fa71d6f0b5042f1b82d4235414e8ab85f2b8
|
ec9a17a21a7c7de586093b9dc9cbae44e427e6cb
|
/Vulnerabilties/SSL Logjam Attack/ssl_logjam_attack.py
|
fd7ed07f3722246daa77c87953c1a5cd32c998e1
|
[] |
no_license
|
zflemingg1/Testing-For-SSL-Vulnerabilities-Misconfigurations
|
6f7b1d5b69afef5f8a43045f6f09ef0b90f90ae1
|
49301587c1d68ae18cc469ede4d811819d3e10ea
|
refs/heads/master
| 2020-03-18T23:40:30.951609
| 2018-05-31T09:39:46
| 2018-05-31T09:39:46
| 135,418,339
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,892
|
py
|
#!../../Custom_Python/build/bin/python2
# Description: This script will test to see if the target site is vulnerable to sweet 32 attacks
# Author: Zach Fleming
# Date: 18/04/2018
# Import The Relevant Libraries
import socket # connecting to hosts
import ssl # ssl protocols
from termcolor import colored # needed for colored print
import sys
import os
import traceback
# This Class Will Test A Url To See if it' vulnerable to the logjam attack
class ssl_logjam():
# Global Variables --> Used for Logic at runtime
success_list = [] # all successful connections will be added to this list which at the end of runtime will be written to the result file
manual_recheck_list = [] # all unsuccessful connections will be added to this list which at the end of runtime will be written to the result file
# List of ciphers vulnerable to DHE
CIPHERS = ('DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:DHE-RSA-CAMELLIA256-SHA:DHE-DSS-CAMELLIA256-SHA:DHE-DSS-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:DHE-DSS-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:DHE-RSA-SEED-SHA:DHE-DSS-SEED-SHA:DHE-RSA-CAMELLIA128-SHA:DHE-DSS-CAMELLIA128-SHA')
# Initialize class
def __init__(self,filename):
# If The User Selected Option 2
if ".txt" in filename:
# Open File Containing The Client Info i.e. ip & port
with open(filename, 'r') as f:
ip_list = f.readlines()
# If the User Selected Option 1
else:
ip_list = [filename]
i = 0 # used as counter to iterate through the list
# While loop to iterate through the client list and test is it vulnerable to the beast attack
while i<len(ip_list):
try:
client = ip_list[i] # i is used to iterate through the list of clients
client = client.strip() # strip whitespace
host = client.split(":")[1] # remove the scheme from the url i.e. https so you would be left with //whatever.com:443
host = host[2:] # remove // from the url
port = client.split(":")[2] # Get port number
port = int(port) # convert string to port
# CREATE SOCKET
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5) # set timeout to 5 seconds
# WRAP Socket --> Convert to SSL and specify protocol Version
wrappedSocket = ssl.wrap_socket(sock, ciphers = self.CIPHERS)
# Connect to client with ip x and port y
wrappedSocket.connect((host, port))
cipher = wrappedSocket.cipher() # get cipher used to initate connection
ssl_version = wrappedSocket.version() # get the ssl version used to initate connection
# Close the Connection
wrappedSocket.close()
# Successfully Connected So add to results
print colored ("Successfully Connected To " + host + ":" + repr(port) + " Using " + ssl_version + " With DHE Cipher " + cipher[0] + " ...[VULNERABLE]" ,'green')
self.success_list.append(client)
i+=1 # increment counter --> go to next client
except ssl.SSLError as e:
#print (e) # print error code
print colored("Exception checking for DHE ciphers raised --> Adding " + client + " to list for manual inpsection later",'red')
self.manual_recheck_list.append(client)
i +=1
continue
except Exception as e:
print colored("Exception checking for cbc ciphers raised --> Adding " + client + " to list for manual inpsection later",'red')
self.manual_recheck_list.append(client)
i +=1
continue
# Display output to the user an
print colored("\n" + 70 * '-','blue')
print colored(' RESULTS','cyan',attrs=['bold'])
print colored(70 * '-','blue')
# Add The Successfully connected clients to result file
if len(self.success_list) !=0:
print colored("\nClients That Are Vulnerable To The LogJam Attack ",'green')
for element in self.success_list:
# Check if file already exists and if not make one
print colored(element,'yellow')
if len(self.manual_recheck_list) !=0:
print colored("\nCould NOt Determine If Clients Were Vulnerable Or Not--> May Need To Be Manually Verified",'red')
for element in self.manual_recheck_list:
print colored(element,'yellow')
# Main Function
def main():
# Display tool info to the user
print colored(30 * "-", 'cyan')
print colored("\nLogJam Detector", 'cyan', attrs=['bold'])
print colored(30 * "-", 'cyan')
print colored("Author: Zach Fleming", 'yellow')
print colored("Date: 18/04/18", 'green')
print colored("\nDescription: Determines if a remote service uses SSL Ciphers that is vulnerable to the logjam attack. The Logjam attack allows a man-in-the-middle attacker to downgrade\nvulnerable TLS connections to 512-bit export-grade cryptography. This allows the attacker to read and modify any data passed over the connection.",'cyan')
# While loop to ask user to select which option with basic error sanitization
while True:
# Display Options To The User
print colored("\nPlease Select One of The Following Options ",'cyan',attrs=['bold'])
print colored(" 1. Single Url",'yellow')
print colored(" 2. File With List of Urls",'yellow')
choice = raw_input("\nOption 1 or Option 2: ")
# If user only wishes to test for one url
if choice == "1":
os.system('cls' if os.name == 'nt' else 'clear') # Clear Screen
print colored("Please Enter URL in the following format http://www.whatever.come:443",'cyan')
# Try statement to handle any unexpected errors
try:
target_url = raw_input("URL: ") # get url from the user
ssl_logjam(target_url) # pass url to class
break
# catch errors
except Exception as e:
print colored("! Error Something Unexpected Occured " + str(e),'red',attrs=['bold'])
print traceback.print_exc()
# If User wishes to scan a text file conataining a list of urls
elif choice == "2":
os.system('cls' if os.name == 'nt' else 'clear') # Clear Screen
print colored("\nNote text file must be in the following format url and port on each line i.e.",'yellow',attrs=['bold'])
print colored("\nhttp://www.whatever.com:80\nhttps://www.whatever.com:443'",'yellow')
print colored("\nPlease Enter Filename including it's location i.e. '/user/Desktop/target_urls.txt'",'cyan')
# Try statement to handle any unexpected errors
try:
target_filename = raw_input("Target File: ") # get url from the user
ssl_logjam(target_filename) # pass url to class
break
# catch errors
except Exception as e:
print colored("! Error Something Unexpected Occured " + str(e),'red',attrs=['bold'])
print traceback.print_exc()
print colored("! Please Try Again",'red')
else:
os.system('cls' if os.name == 'nt' else 'clear') # Clear Screen
print colored("! Invalid Option. Please Select Either Option 1 or Option 2",'red',attrs=['bold'])
main()
|
[
"Zach.f@edgescan.com"
] |
Zach.f@edgescan.com
|
c60ebdb8493c520620b00a7500176196eafdd5a6
|
302ceac8466ef14d42d525170eb2f7719ec1a3d3
|
/Introdução à programação com Python/aula08_contador_letras.py
|
7140a0f24d5284154befc34beaddf01496b5ebe3
|
[] |
no_license
|
rgrtorres/cursos_python
|
64eac8e88736a220bdd790dffd790f0a396c32a9
|
19addbbedca6e8c372e9c3c88d828606790f6820
|
refs/heads/master
| 2023-03-21T07:53:05.662439
| 2021-03-13T14:15:44
| 2021-03-13T14:15:44
| 346,204,587
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 289
|
py
|
def contar_letras(lista_palavra):
contador = []
for x in lista_palavra:
quantidade = len(x)
contador.append(quantidade)
return contador
def teste():
return 'teste'
if __name__ == '__main__':
lista = ['cachorro', 'gato']
print(contar_letras(lista))
|
[
"rgrtorres@hotmail.com"
] |
rgrtorres@hotmail.com
|
75b71b1a3e7b2cc7b6f4ff915a2785ed4ba5b44e
|
bd1b126c0460e0df5a086000451642d198122939
|
/projects/gmail/test.py
|
3fadcc997c76a2170020a3f0918bea73d2722fbc
|
[] |
no_license
|
anvesh001/page-object-model
|
bf749a6c19e7c43c111f7458974f8c531da6385d
|
4e528b90b4a85db0173f0f66bca56905081029aa
|
refs/heads/master
| 2020-05-21T07:08:45.614092
| 2019-05-10T08:41:14
| 2019-05-10T08:41:14
| 185,952,187
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,451
|
py
|
from selenium import webdriver
import time
import unittest
from projects.gmail.pages.login_page import LoginPage
from projects.gmail.pages.home_page import HomePage
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__),"..",'..'))
#print('test completed')
class test_login(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver=webdriver.Chrome()
cls.driver.maximize_window()
cls.driver.implicitly_wait(10)
def test_login(self):
self.driver.get('https://opensource-demo.orangehrmlive.com/index.php/dashboard')
#login page method
login=LoginPage(self.driver)
login.enter_username('Admin')
login.enter_password('admin123')
login.click_login()
#Home page methods
home=HomePage(self.driver)
home.click_welcome()
home.click_logout()
#self.driver.find_element_by_id('txtUsername').clear()
#self.driver.find_element_by_id('txtUsername').send_keys('Admin')
#self.driver.find_element_by_id('txtPassword').clear()
#self.driver.find_element_by_id('txtPassword').send_keys('admin123')
#self.driver.find_element_by_id('btnLogin').click()
#self.driver.find_element_by_partial_link_text('Admin').click()
#self.driver.find_element_by_id('welcome').click()
#self.driver.find_element_by_xpath('//*[@id="welcome-menu"]/ul/li[2]/a').click()
@classmethod
def tearDownClass(cls):
cls.driver.close()
cls.driver.quit()
print('test completed')
if __name__ == '__main__':
unittest.main()
|
[
"anveshkumarnaidu402@gmail.com"
] |
anveshkumarnaidu402@gmail.com
|
7f37c3725142271c5a1ca88a17921c7f106016b4
|
3d7b52e6739825aef8eafde73cb18f9904a7e638
|
/Day-22-Mixed/question2_median_stream.py
|
27056074f1d5b77710081a8ba550ca1dd8cbc3ba
|
[] |
no_license
|
jsourabh1/Striver-s_sheet_Solution
|
7707dfb03b022735135abe526c321e0919d76856
|
d296f8b3cba5a03c3c9573c8e316aa92185420fe
|
refs/heads/main
| 2023-07-30T23:13:23.878000
| 2021-10-03T02:42:00
| 2021-10-03T02:42:00
| 402,102,262
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 666
|
py
|
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.max_heap=[]
self.min_heap=[]
def addNum(self, num: int) -> None:
if len(self.max_heap)==len(self.min_heap):
heappush(self.min_heap,-heappushpop(self.max_heap,-num))
else:
heappush(self.max_heap,-heappushpop(self.min_heap,num))
print(self.min_heap,self.max_heap)
def findMedian(self) -> float:
if len(self.min_heap)==len(self.max_heap):
return (self.min_heap[0]-self.max_heap[0])/2
return self.min_heap[0]
|
[
"jsourabh861@gmail.com"
] |
jsourabh861@gmail.com
|
112df351942fd6b1192e8e855ac9f1a4df780e1b
|
e710a2758e511239b4b37566ca78d9302ddbecc6
|
/seventeenthPage/849_MaximizeDistancetoClosestPerson.py
|
3896cfb7f3486289f8fde07918d240cc3c25470e
|
[] |
no_license
|
jiangshshui/leetcode
|
4d93fb5610446ca2d5ecfbe0312d4f3d74e50761
|
7aea885dfbb9bd157ce2c78b6e4e8af14afcb5b8
|
refs/heads/master
| 2021-03-27T18:59:51.110466
| 2018-11-07T06:20:45
| 2018-11-07T06:20:45
| 99,470,712
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 582
|
py
|
class Solution:
def maxDistToClosest(self, seats):
"""
:type seats: List[int]
:rtype: int
"""
seated=[]
for i,seat in enumerate(seats):
if seat!=0:
seated.append(i)
ans=0
ans=max([ans,seated[0]-0,len(seats)-1-seated[-1]])
for i in range(len(seated)-1):
mid=(seated[i+1]-seated[i])//2
ans=max(ans,mid)
return ans
if __name__=="__main__":
s=Solution()
print(s.maxDistToClosest([1,0,0,0,1,0,1]))
print(s.maxDistToClosest([1,0,0,0]))
|
[
"30767399+jiangshshui@users.noreply.github.com"
] |
30767399+jiangshshui@users.noreply.github.com
|
07008e999f02c35e6a8c414d9321c124e90b441c
|
1127be36a03677a9bf7226c87c4f6aec0b5a4fd7
|
/pocdb.py
|
df443d329c92b598262c214df108ab1d4563081d
|
[] |
no_license
|
chriskcl/AngelSword
|
b44de0194502a6a3e3d38b7fd0f949747f697b63
|
f2dc09ee41422ef07c43b64a0aba523378cb7667
|
refs/heads/master
| 2021-05-14T00:44:28.175262
| 2018-01-04T08:11:32
| 2018-01-04T08:11:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 31,189
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
name: 漏洞字典
referer: unknow
author: Lucifer
description: 引入main接口
'''
from cms.cmsmain import *
from system.systemmain import *
from industrial.industrialmain import *
from hardware.hardwaremain import *
from information.informationmain import *
class pocdb_pocs:
def __init__(self, url):
self.url = url
self.informationpocdict = {
"git源码泄露扫描":git_check_BaseVerify(url),
"java配置文件文件发现":jsp_conf_find_BaseVerify(url),
"robots文件发现":robots_find_BaseVerify(url),
"svn源码泄露扫描":svn_check_BaseVerify(url),
"JetBrains IDE workspace.xml文件泄露":jetbrains_ide_workspace_disclosure_BaseVerify(url),
"apache server-status信息泄露":apache_server_status_disclosure_BaseVerify(url),
"crossdomain.xml文件发现":crossdomain_find_BaseVerify(url),
}
self.cmspocdict = {
"泛微OA filedownaction SQL注入":weaver_oa_download_sqli_BaseVerify(url),
"泛微OA 数据库配置泄露":weaver_oa_db_disclosure_BaseVerify(url),
"phpok res_action_control.php 任意文件下载(需要cookies文件)":phpok_res_action_control_filedownload_BaseVerify(url),
"phpok api.php SQL注入漏洞":phpok_api_param_sqli_BaseVerify(url),
"phpok remote_image getshell漏洞":phpok_remote_image_getshell_BaseVerify(url),
"jeecg 重置admin密码":jeecg_pwd_reset_BaseVerify(url),
"typecho install.php反序列化命令执行":typecho_install_code_exec_BaseVerify(url),
"Dotnetcms(风讯cms)SQL注入漏洞":foosun_City_ajax_sqli_BaseVerify(url),
"韩国autoset建站程序phpmyadmin任意登录漏洞":autoset_phpmyadmin_unauth_BaseVerify(url),
"phpstudy探针":phpstudy_probe_BaseVerify(url),
"phpstudy phpmyadmin默认密码漏洞":phpstudy_phpmyadmin_defaultpwd_BaseVerify(url),
"Discuz论坛forum.php参数message SSRF漏洞":discuz_forum_message_ssrf_BaseVerify(url),
"Discuz X3 focus.swf flashxss漏洞":discuz_focus_flashxss_BaseVerify(url),
"Discuz! X2.5 物理路径泄露漏洞":discuz_x25_path_disclosure_BaseVerify(url),
"Discuz问卷调查参数orderby注入漏洞":discuz_plugin_ques_sqli_BaseVerify(url),
"Hishop系统productlist.aspx SQL注入":hishop_productlist_sqli_BaseVerify(url),
"亿邮邮箱弱口令列表泄露":eyou_weakpass_BaseVerify(url),
"亿邮Email Defender系统免登陆DBA注入":eyou_admin_id_sqli_BaseVerify(url),
"亿邮邮件系统重置密码问题暴力破解":eyou_resetpw_BaseVerify(url),
"亿邮mail5 user 参数kw SQL注入":eyou_user_kw_sqli_BaseVerify(url),
"金蝶办公系统任意文件下载":kingdee_filedownload_BaseVerify(url),
"金蝶协同平台远程信息泄露漏洞":kingdee_resin_dir_path_disclosure_BaseVerify(url),
"金蝶AES系统Java web配置文件泄露":kingdee_conf_disclosure_BaseVerify(url),
"金蝶EAS任意文件读取":kingdee_logoImgServlet_fileread_BaseVerify(url),
"乐语客服系统任意文件下载漏洞":looyu_down_filedownload_BaseVerify(url),
"smartoa 多处任意文件下载漏洞":smartoa_multi_filedownload_BaseVerify(url),
"urp查询接口曝露":urp_query_BaseVerify(url),
"URP越权查看任意学生课表、成绩(需登录)":urp_query2_BaseVerify(url),
"URP综合教务系统任意文件读取":urp_ReadJavaScriptServlet_fileread_BaseVerify(url),
"pkpmbs工程质量监督站信息管理系统SQL注入":pkpmbs_guestbook_sqli_BaseVerify(url),
"pkpmbs建设工程质量监督系统注入":pkpmbs_addresslist_keyword_sqli_BaseVerify(url),
"pkpmbs建设工程质量监督系统SQL注入":pkpmbs_MsgList_sqli_BaseVerify(url),
"帝友P2P借贷系统无需登录SQL注入漏洞":dyp2p_latesindex_sqli_BaseVerify(url),
"帝友P2P借贷系统任意文件读取漏洞":dyp2p_url_fileread_BaseVerify(url),
"iGenus邮件系统一处无需登录的任意代码执行":igenus_code_exec_BaseVerify(url),
"iGenus邮箱系统login.php 参数Lang任意文件读取":igenus_login_Lang_fileread_BaseVerify(url),
"iGenus邮箱系统管理中心sys/login.php 参数Lang任意文件读取":igenus_syslogin_Lang_fileread_BaseVerify(url),
"live800客服系统downlog任意文件下载":live800_downlog_filedownload_BaseVerify(url),
"live800在线客服系统loginAction SQL注入漏洞":live800_loginAction_sqli_BaseVerify(url),
"live800在线客服系统多处SQL注入GETSHELL漏洞":live800_sta_export_sqli_BaseVerify(url),
"live800在线客服系统XML实体注入漏洞":live800_services_xxe_BaseVerify(url),
"Onethink 参数category SQL注入":onethink_category_sqli_BaseVerify(url),
"ThinkPHP 代码执行漏洞":thinkphp_code_exec_BaseVerify(url),
"汇思学习管理系统任意文件下载":wizbank_download_filedownload_BaseVerify(url),
"Cyberwisdom wizBank学习管理平台SQL注入漏洞":wizbank_usr_id_sqli_BaseVerify(url),
"domino_unauth未授权漏洞":domino_unauth_BaseVerify(url),
"宏景EHR系统多处SQL注入":hjsoft_sqli_BaseVerify(url),
"汇能群管理系统SQL注入":hnkj_researchinfo_dan_sqli_BaseVerify(url),
"汇文软件图书管理系统ajax_asyn_link.old.php任意文件读取":libsys_ajax_asyn_link_old_fileread_BaseVerify(url),
"汇文软件图书管理系统ajax_asyn_link.php任意文件读取":libsys_ajax_asyn_link_fileread_BaseVerify(url),
"汇文软件图书管理系统ajax_get_file.php任意文件读取":libsys_ajax_get_file_fileread_BaseVerify(url),
"通元建站系统用户名泄露漏洞":gpower_users_disclosure_BaseVerify(url),
"metinfo5.0 getpassword.php两处时间盲注漏洞":metinfo_getpassword_sqli_BaseVerify(url),
"用友ICC struts2远程命令执行":yonyou_icc_struts2_BaseVerify(url),
"V2视频会议系统某处SQL注射、XXE漏洞(可getshell)":v2Conference_sqli_xxe_BaseVerify(url),
"政府采购系统eweb编辑器默认口令Getshell漏洞":gpcsoft_ewebeditor_weak_BaseVerify(url),
"RAP接口平台struts远程代码执行":rap_interface_struts_exec_BaseVerify(url),
"虹安DLP数据泄露防护平台struts2远程命令执行":hongan_dlp_struts_exec_BaseVerify(url),
"九羽数字图书馆struts远程命令执行":jiuyu_library_struts_exec_BaseVerify(url),
"垚捷电商平台通用struts命令执行":yaojie_steel_struts_exec_BaseVerify(url),
"Digital-Campus数字校园平台LOG文件泄露":digital_campus_log_disclosure_BaseVerify(url),
"Digital-Campus2.0数字校园平台Sql注射":digital_campus_systemcodelist_sqli_BaseVerify(url),
"jeecms download.jsp 参数fpath任意文件下载":jeecms_fpath_filedownload_BaseVerify(url),
"shopex敏感信息泄露":shopex_phpinfo_disclosure_BaseVerify(url),
"动科(dkcms)默认数据库漏洞":dkcms_database_disclosure_BaseVerify(url),
"FineCMS免费版文件上传漏洞":finecms_uploadfile_BaseVerify(url),
"DaMall商城系统sql注入":damall_selloffer_sqli_BaseVerify(url),
"大汉版通JCMS数据库配置文件读取漏洞":hanweb_readxml_fileread_BaseVerify(url),
"大汉downfile.jsp 任意文件下载":hanweb_downfile_filedownload_BaseVerify(url),
"大汉VerfiyCodeServlet越权漏洞":hanweb_VerifyCodeServlet_install_BaseVerify(url),
"PHP168 login.php GETSHELL漏洞":php168_login_getshell_BaseVerify(url),
"dedecms版本探测":dedecms_version_BaseVerify(url),
"dedecms search.php SQL注入漏洞":dedecms_search_typeArr_sqli_BaseVerify(url),
"dedecms trace爆路径漏洞":dedecms_error_trace_disclosure_BaseVerify(url),
"dedecms download.php重定向漏洞":dedecms_download_redirect_BaseVerify(url),
"dedecms recommend.php SQL注入":dedecms_recommend_sqli_BaseVerify(url),
"umail物理路径泄露":umail_physical_path_BaseVerify(url),
"U-Mail邮件系统sessionid访问":umail_sessionid_access_BaseVerify(url),
"metinfo v5.3sql注入漏洞":metinfo_login_check_sqli_BaseVerify(url),
"用友致远A6协同系统SQL注射union可shell":yonyou_user_ids_sqli_BaseVerify(url),
"用友致远A6协同系统多处SQL注入":yonyou_multi_union_sqli_BaseVerify(url),
"用友致远A6协同系统敏感信息泄露&SQL注射":yonyou_initData_disclosure_BaseVerify(url),
"用友致远A6协同系统数据库账号泄露":yonyou_createMysql_disclosure_BaseVerify(url),
"用友致远A6 test.jsp SQL注入":yonyou_test_sqli_BaseVerify(url),
"用友CRM系统任意文件读取":yonyou_getemaildata_fileread_BaseVerify(url),
"用友EHR 任意文件读取":yonyou_ehr_ELTextFile_BaseVerify(url),
"用友优普a8 CmxUserSQL时间盲注入":yonyou_a8_CmxUser_sqli_BaseVerify(url),
"用友a8 log泄露":yonyou_a8_logs_disclosure_BaseVerify(url),
"用友a8监控后台默认密码漏洞":yonyou_status_default_pwd_BaseVerify(url),
"用友致远A8协同系统 blind XML实体注入":yonyou_a8_personService_xxe_BaseVerify(url),
"用友GRP-U8 sql注入漏洞":yonyou_cm_info_content_sqli_BaseVerify(url),
"用友u8 CmxItem.php SQL注入":yonyou_u8_CmxItem_sqli_BaseVerify(url),
"用友FE协作办公平台5.5 SQL注入":yonyou_fe_treeXml_sqli_BaseVerify(url),
"用友EHR系统 ResetPwd.jsp SQL注入":yonyou_ehr_resetpwd_sqli_BaseVerify(url),
"用友nc NCFindWeb 任意文件下载漏洞":yonyou_nc_NCFindWeb_fileread_BaseVerify(url),
"fsmcms p_replydetail.jsp注入漏洞":fsmcms_p_replydetail_sqli_BaseVerify(url),
"FSMCMS网站重装漏洞":fsmcms_setup_reinstall_BaseVerify(url),
"FSMCMS columninfo.jsp文件参数ColumnID SQL注入":fsmcms_columninfo_sqli_BaseVerify(url),
"qibocms知道系统SQL注入":qibocms_search_sqli_BaseVerify(url),
"qibo分类系统search.php 代码执行":qibocms_search_code_exec_BaseVerify(url),
"qibocms news/js.php文件参数f_idSQL注入":qibocms_js_f_id_sqli_BaseVerify(url),
"qibocms s.php文件参数fids SQL注入":qibocms_s_fids_sqli_BaseVerify(url),
"依友POS系统登陆信息泄露":yeu_disclosure_uid_BaseVerify(url),
"浪潮行政审批系统十八处注入":inspur_multi_sqli_BaseVerify(url),
"浪潮ECGAP政务审批系统SQL注入漏洞":inspur_ecgap_displayNewsPic_sqli_BaseVerify(url),
"五车图书管系统任意下载":clib_kinweblistaction_download_BaseVerify(url),
"五车图书管系统kindaction任意文件遍历":clib_kindaction_fileread_BaseVerify(url),
"Gobetters视频会议系统SQL注入漏洞":gobetters_multi_sqli_BaseVerify(url),
"LBCMS多处SQL注入漏洞":lbcms_webwsfw_bssh_sqli_BaseVerify(url),
"Euse TMS存在多处DBA权限SQL注入":euse_study_multi_sqli_BaseVerify(url),
"suntown未授权任意文件上传漏洞":suntown_upfile_fileupload_BaseVerify(url),
"Dswjcms p2p网贷系统前台4处sql注入":dswjcms_p2p_multi_sqli_BaseVerify(url),
"skytech政务系统越权漏洞":skytech_bypass_priv_BaseVerify(url),
"wordpress AzonPop插件SQL注入":wordpress_plugin_azonpop_sqli_BaseVerify(url),
"wordpress 插件shortcode0.2.3 本地文件包含":wordpress_plugin_ShortCode_lfi_BaseVerify(url),
"wordpress插件跳转":wordpress_url_redirect_BaseVerify(url),
"wordpress 插件WooCommerce PHP代码注入":wordpress_woocommerce_code_exec_BaseVerify(url),
"wordpress 插件mailpress远程代码执行":wordpress_plugin_mailpress_rce_BaseVerify(url),
"wordpress admin-ajax.php任意文件下载":wordpress_admin_ajax_filedownload_BaseVerify(url),
"wordpress rest api权限失效导致内容注入":wordpress_restapi_sqli_BaseVerify(url),
"wordpress display-widgets插件后门漏洞":wordpress_display_widgets_backdoor_BaseVerify(url),
"Mallbuilder商城系统SQL注入":mallbuilder_change_status_sqli_BaseVerify(url),
"efuture商业链系统任意文件下载":efuture_downloadAct_filedownload_BaseVerify(url),
"kj65n煤矿远程监控系统SQL注入":kj65n_monitor_sqli_BaseVerify(url),
"票友机票预订系统6处SQL注入":piaoyou_multi_sqli_BaseVerify(url),
"票友机票预订系统10处SQL注入":piaoyou_ten_sqli_BaseVerify(url),
"票友机票预订系统6处SQL注入(绕过)":piaoyou_six_sqli_BaseVerify(url),
"票友机票预订系统6处SQL注入2(绕过)":piaoyou_six2_sqli_BaseVerify(url),
"票友票务系统int_order.aspx SQL注入":piaoyou_int_order_sqli_BaseVerify(url),
"票友票务系统通用sql注入":piaoyou_newsview_list_BaseVerify(url),
"中农信达监察平台任意文件下载":sinda_downloadfile_download_BaseVerify(url),
"连邦行政审批系统越权漏洞":lianbang_multi_bypass_priv_BaseVerify(url),
"北斗星政务PostSuggestion.aspx SQL注入":star_PostSuggestion_sqli_BaseVerify(url),
"TCExam重新安装可getshell漏洞":tcexam_reinstall_getshell_BaseVerify(url),
"合众商道php系统通用注入":hezhong_list_id_sqli_BaseVerify(url),
"最土团购SQL注入":zuitu_coupon_id_sqli_BaseVerify(url),
"时光动态网站平台(Cicro 3e WS) 任意文件下载":cicro_DownLoad_filedownload_BaseVerify(url),
"华飞科技cms绕过JS GETSHELL":huaficms_bypass_js_BaseVerify(url),
"IWMS系统后台绕过&整站删除":iwms_bypass_js_delete_BaseVerify(url),
"农友政务系统多处SQL注入":nongyou_multi_sqli_BaseVerify(url),
"农友政务系统Item2.aspx SQL注入":nongyou_Item2_sqli_BaseVerify(url),
"农友政务ShowLand.aspx SQL注入":nongyou_ShowLand_sqli_BaseVerify(url),
"农友多处时间盲注":nongyou_sleep_sqli_BaseVerify(url),
"某政府采购系统任意用户密码获取漏洞":zfcgxt_UserSecurityController_getpass_BaseVerify(url),
"铭万事业通用建站系统SQL注入":mainone_b2b_Default_sqli_BaseVerify(url),
"铭万B2B SupplyList SQL注入漏洞":mainone_SupplyList_sqli_BaseVerify(url),
"铭万门户建站系统ProductList SQL注入":mainone_ProductList_sqli_BaseVerify(url),
"xplus npmaker 2003系统GETSHELL":xplus_2003_getshell_BaseVerify(url),
"xplus通用注入":xplus_mysql_mssql_sqli_BaseVerify(url),
"workyi人才系统多处注入漏洞":workyi_multi_sqli_BaseVerify(url),
"菲斯特诺期刊系统多处SQL注入":newedos_multi_sqli_BaseVerify(url),
"东软UniPortal1.2未授权访问&SQL注入":uniportal_bypass_priv_sqli_BaseVerify(url),
"PageAdmin可“伪造”VIEWSTATE执行任意SQL查询&重置管理员密码":pageadmin_forge_viewstate_BaseVerify(url),
"SiteFactory CMS 5.5.9任意文件下载漏洞":xtcms_download_filedownload_BaseVerify(url),
"璐华企业版OA系统多处SQL注入":ruvar_oa_multi_sqli_BaseVerify(url),
"璐华OA系统多处SQL注入":ruvar_oa_multi_sqli2_BaseVerify(url),
"璐华OA系统多处SQL注入3":ruvar_oa_multi_sqli3_BaseVerify(url),
"GN SQL Injection":gn_consulting_sqli_BaseVerify(url),
"JumboECMS V1.6.1 注入漏洞":jumboecms_slide_id_sqli_BaseVerify(url),
"joomla组件com_docman本地文件包含":joomla_com_docman_lfi_BaseVerify(url),
"joomla 3.7.0 core SQL注入":joomla_index_list_sqli_BaseVerify(url),
"北京网达信联电子采购系统多处注入":caitong_multi_sqli_BaseVerify(url),
"Designed by Alkawebs SQL Injection":alkawebs_viewnews_sqli_BaseVerify(url),
"一采通电子采购系统多处时间盲注":caitong_multi_sleep_sqli_BaseVerify(url),
"启博淘店通标准版任意文件遍历漏洞":shop360_do_filedownload_BaseVerify(url),
"PSTAR-电子服务平台SQL注入漏洞":pstar_warehouse_msg_01_sqli_BaseVerify(url),
"PSTAR-电子服务平台isfLclInfo注入漏洞":pstar_isfLclInfo_sqli_BaseVerify(url),
"PSTAR-电子服务平台SQL注入漏洞":pstar_qcustoms_sqli_BaseVerify(url),
"TRS(拓尔思) wcm pre.as 文件包含":trs_wcm_pre_as_lfi_BaseVerify(url),
"TRS(拓尔思) 网络信息雷达4.6系统敏感信息泄漏到进后台":trs_inforadar_disclosure_BaseVerify(url),
"TRS(拓尔思) 学位论文系统papercon处SQL注入":trs_lunwen_papercon_sqli_BaseVerify(url),
"TRS(拓尔思) infogate插件 blind XML实体注入":trs_infogate_xxe_BaseVerify(url),
"TRS(拓尔思) infogate插件 任意注册漏洞":trs_infogate_register_BaseVerify(url),
"TRS(拓尔思) was5配置文件泄露":trs_was5_config_disclosure_BaseVerify(url),
"TRS(拓尔思) was5 download_templet.jsp任意文件下载":trs_was5_download_templet_BaseVerify(url),
"TRS(拓尔思) wcm系统默认账户漏洞":trs_wcm_default_user_BaseVerify(url),
"TRS(拓尔思) wcm 6.x版本infoview信息泄露":trs_wcm_infoview_disclosure_BaseVerify(url),
"TRS(拓尔思) was40 passwd.htm页面泄露":trs_was40_passwd_disclosure_BaseVerify(url),
"TRS(拓尔思) was40 tree导航树泄露":trs_was40_tree_disclosure_BaseVerify(url),
"TRS(拓尔思) ids身份认证信息泄露":trs_ids_auth_disclosure_BaseVerify(url),
"TRS(拓尔思) wcm webservice文件写入漏洞":trs_wcm_service_writefile_BaseVerify(url),
"易创思ECScms MoreIndex SQL注入":ecscms_MoreIndex_sqli_BaseVerify(url),
"金窗教务系统存在多处SQL注射漏洞":gowinsoft_jw_multi_sqli_BaseVerify(url),
"siteserver3.6.4 background_taskLog.aspx注入":siteserver_background_taskLog_sqli_BaseVerify(url),
"siteserver3.6.4 background_log.aspx注入":siteserver_background_log_sqli_BaseVerify(url),
"siteserver3.6.4 user.aspx注入":siteserver_UserNameCollection_sqli_BaseVerify(url),
"siteserver3.6.4 background_keywordsFilting.aspx注入":siteserver_background_keywordsFilting_sqli_BaseVerify(url),
"siteserver3.6.4 background_administrator.aspx注入":siteserver_background_administrator_sqli_BaseVerify(url),
"NITC营销系统suggestwordList.php SQL注入":nitc_suggestwordList_sqli_BaseVerify(url),
"NITC营销系统index.php SQL注入":nitc_index_language_id_sqli_BaseVerify(url),
"南大之星信息发布系统DBA SQL注入":ndstar_six_sqli_BaseVerify(url),
"蓝凌EIS智慧协同平台menu_left_edit.aspx SQL注入":eis_menu_left_edit_sqli_BaseVerify(url),
"天柏在线培训系统Type_List.aspx SQL注入":tianbo_Type_List_sqli_BaseVerify(url),
"天柏在线培训系统TCH_list.aspx SQL注入":tianbo_TCH_list_sqli_BaseVerify(url),
"天柏在线培训系统Class_Info.aspx SQL注入":tianbo_Class_Info_sqli_BaseVerify(url),
"天柏在线培训系统St_Info.aspx SQL注入":tianbo_St_Info_sqli_BaseVerify(url),
"安财软件GetXMLList任意文件读取":acsoft_GetXMLList_fileread_BaseVerify(url),
"安财软件GetFile任意文件读取":acsoft_GetFile_fileread_BaseVerify(url),
"安财软件GetFileContent任意文件读取":acsoft_GetFileContent_fileread_BaseVerify(url),
"天津神州助平台通用型任意下载":gxwssb_fileDownloadmodel_download_BaseVerify(url),
"ETMV9数字化校园平台任意下载":etmdcp_Load_filedownload_BaseVerify(url),
"安脉grghjl.aspx 参数stuNo注入":anmai_grghjl_stuNo_sqli_BaseVerify(url),
"农友多处时间盲注":nongyou_ShowLand_sqli_BaseVerify(url),
"某政府通用任意文件下载":zf_cms_FileDownload_BaseVerify(url),
"师友list.aspx keywords SQL注入":shiyou_list_keyWords_sqli_BaseVerify(url),
"speedcms list文件参数cid SQL注入":speedcms_list_cid_sqli_BaseVerify(url),
"卓繁cms任意文件下载漏洞":zhuofan_downLoadFile_download_BaseVerify(url),
"金宇恒内容管理系统通用型任意文件下载漏洞":gevercms_downLoadFile_filedownload_BaseVerify(url),
"任我行crm任意文件下载":weway_PictureView1_filedownload_BaseVerify(url),
"易创思教育建站系统未授权访问可查看所有注册用户":esccms_selectunitmember_unauth_BaseVerify(url),
"wecenter SQL注入":wecenter_topic_id_sqli_BaseVerify(url),
"shopnum1 ShoppingCart1 SQL注入":shopnum_ShoppingCart1_sqli_BaseVerify(url),
"shopnum1 ProductListCategory SQL注入":shopnum_ProductListCategory_sqli_BaseVerify(url),
"shopnum1 ProductDetail.aspx SQL注入":shopnum_ProductDetail_sqli_BaseVerify(url),
"shopnum1 GuidBuyList.aspx SQL注入":shopnum_GuidBuyList_sqli_BaseVerify(url),
"好视通视频会议系统(fastmeeting)任意文件遍历":fastmeeting_download_filedownload_BaseVerify(url),
"远古流媒体系统两处SQL注入":viewgood_two_sqli_BaseVerify(url),
"远古 pic_proxy.aspx SQL注入":viewgood_pic_proxy_sqli_BaseVerify(url),
"远古流媒体系统 GetCaption.ashx注入":viewgood_GetCaption_sqli_BaseVerify(url),
"shop7z order_checknoprint.asp SQL注入":shop7z_order_checknoprint_sqli_BaseVerify(url),
"dreamgallery album.php SQL注入":dreamgallery_album_id_sqli_BaseVerify(url),
"IPS Community Suite <= 4.1.12.3 PHP远程代码执行":ips_community_suite_code_exec_BaseVerify(url),
"科信邮件系统login.server.php 时间盲注":kxmail_login_server_sqli_BaseVerify(url),
"shopNC B2B版 index.php SQL注入":shopnc_index_class_id_sqli_BaseVerify(url),
"南京擎天政务系统 geren_list_page.aspx SQL注入":skytech_geren_list_page_sqli_BaseVerify(url),
"学子科技诊断测评系统多处未授权访问":xuezi_ceping_unauth_BaseVerify(url),
"Shadows-IT selector.php 任意文件包含":shadowsit_selector_lfi_BaseVerify(url),
"皓翰数字化校园平台任意文件下载":haohan_FileDown_filedownload_BaseVerify(url),
"phpcms digg_add.php SQL注入":phpcms_digg_add_sqli_BaseVerify(url),
"phpcms authkey泄露漏洞":phpcms_authkey_disclosure_BaseVerify(url),
"phpcms2008 flash_upload.php SQL注入":phpcms_flash_upload_sqli_BaseVerify(url),
"phpcms2008 product.php 代码执行":phpcms_product_code_exec_BaseVerify(url),
"phpcms v9.6.0 SQL注入":phpcms_v96_sqli_BaseVerify(url),
"phpcms 9.6.1任意文件读取漏洞":phpcms_v961_fileread_BaseVerify(url),
"phpcms v9 flash xss漏洞":phpcms_v9_flash_xss_BaseVerify(url),
"seacms search.php 代码执行":seacms_search_code_exec_BaseVerify(url),
"seacms 6.45 search.php order参数前台代码执行":seacms_order_code_exec_BaseVerify(url),
"seacms search.php 参数jq代码执行":seacms_search_jq_code_exec_BaseVerify(url),
"安脉学生管理系统10处SQL注入":anmai_teachingtechnology_sqli_BaseVerify(url),
"cmseasy header.php 报错注入":cmseasy_header_detail_sqli_BaseVerify(url),
"PhpMyAdmin2.8.0.3无需登录任意文件包含导致代码执行":phpmyadmin_setup_lfi_BaseVerify(url),
"opensns index.php 参数arearank注入":opensns_index_arearank_BaseVerify(url),
"opensns index.php 前台getshell":opensns_index_getshell_BaseVerify(url),
"ecshop uc.php参数code SQL注入":ecshop_uc_code_sqli_BaseVerify(url),
"ecshop3.0 flow.php 参数order_id注入":ecshop_flow_orderid_sqli_BaseVerify(url),
"SiteEngine 6.0 & 7.1 SQL注入漏洞":siteengine_comments_module_sqli_BaseVerify(url),
"明腾cms cookie欺骗漏洞":mingteng_cookie_deception_BaseVerify(url),
"正方教务系统services.asmx SQL注入":zfsoft_service_stryhm_sqli_BaseVerify(url),
"正方教务系统数据库任意操纵":zfsoft_database_control_BaseVerify(url),
"正方教务系统default3.aspx爆破页面":zfsoft_default3_bruteforce_BaseVerify(url),
"V2视频会议系统某处SQL注射、XXE漏洞(可getshell)":v2Conference_sqli_xxe_BaseVerify(url),
"1039驾校通未授权访问漏洞":jxt1039_unauth_BaseVerify(url),
"thinksns category模块代码执行":thinksns_category_code_exec_BaseVerify(url),
"TPshop eval-stdin.php 代码执行漏洞":tpshop_eval_stdin_code_exec_BaseVerify(url),
}
self.industrialpocdict = {
"新力热电无线抄表监控系统绕过后台登录":wireless_monitor_priv_elevation_BaseVerify(url),
"火力发电能耗监测弱口令":rockontrol_weak_BaseVerify(url),
"sgc8000 大型旋转机监控系统报警短信模块泄露":sgc8000_sg8k_sms_disclosure_BaseVerify(url),
"sgc8000 监控系统数据连接信息泄露":sgc8000_deldata_config_disclosure_BaseVerify(url),
"sgc8000监控系统超管账号泄露漏洞":sgc8000_defaultuser_disclosure_BaseVerify(url),
"zte 无线控制器 SQL注入":zte_wireless_getChannelByCountryCode_sqli_BaseVerify(url),
"中兴无线控制器弱口令":zte_wireless_weak_pass_BaseVerify(url),
"东方电子SCADA通用系统信息泄露":dfe_scada_conf_disclosure_BaseVerify(url),
}
self.systempocdict = {
"GoAhead LD_PRELOAD远程代码执行(CVE-2017-17562)":goahead_LD_PRELOAD_rce_BaseVerify(url),
"天融信Topsec change_lan.php本地文件包含":topsec_change_lan_filedownload_BaseVerify(url),
"Tomcat代码执行漏洞(CVE-2017-12616)":tomcat_put_exec_BaseVerify(url),
"redis 未授权漏洞":redis_unauth_BaseVerify(url),
"KingGate防火墙默认配置不当可被远控":kinggate_zebra_conf_BaseVerify(url),
"nginx Multi-FastCGI Code Execution":multi_fastcgi_code_exec_BaseVerify(url),
"TurboMail设计缺陷以及默认配置漏洞":turbomail_conf_BaseVerify(url),
"TurboGate邮件网关XXE漏洞":turbogate_services_xxe_BaseVerify(url),
"weblogic SSRF漏洞(CVE-2014-4210)":weblogic_ssrf_BaseVerify(url),
"weblogic XMLdecoder反序列化漏洞(CVE-2017-10271)":weblogic_xmldecoder_exec_BaseVerify(url),
"weblogic 接口泄露":weblogic_interface_disclosure_BaseVerify(url),
"实易DNS管理系统文件包含至远程代码执行":forease_fileinclude_code_exec_BaseVerify(url),
"hudson源代码泄露漏洞":hudson_ws_disclosure_BaseVerify(url),
"N点虚拟主机管理系统V1.9.6版数据库下载漏洞":npoint_mdb_download_BaseVerify(url),
"宏杰Zkeys虚拟主机默认数据库漏洞":zkeys_database_conf_BaseVerify(url),
"江南科友堡垒机信息泄露":hac_gateway_info_disclosure_BaseVerify(url),
"Moxa OnCell 未授权访问":moxa_oncell_telnet_BaseVerify(url),
"glassfish 任意文件读取":glassfish_fileread_BaseVerify(url),
"zabbix jsrpc.php SQL注入":zabbix_jsrpc_profileIdx2_sqli_BaseVerify(url),
"php fastcgi任意文件读取漏洞":php_fastcgi_read_BaseVerify(url),
"hfs rejetto 远程代码执行":hfs_rejetto_search_rce_BaseVerify(url),
"shellshock漏洞":shellshock_BaseVerify(url),
"dorado默认口令漏洞":dorado_default_passwd_BaseVerify(url),
"ms15_034 http.sys远程代码执行(CVE-2015-1635)":iis_ms15034_httpsys_rce_BaseVerify(url),
"IIS 6.0 webdav远程代码执行漏洞(CVE-2017-7269)":iis_webdav_rce_BaseVerify(url),
"深澜软件srun3000计费系统任意文件下载漏洞":srun_index_file_filedownload_BaseVerify(url),
"深澜软件srun3000计费系统rad_online.php命令执行bypass":srun_rad_online_bypass_rce_BaseVerify(url),
"深澜软件srun3000计费系统rad_online.php参数username命令执行":srun_rad_online_username_rce_BaseVerify(url),
"深澜软件srun3000计费系统download.php任意文件下载":srun_download_file_filedownload_BaseVerify(url),
"深澜软件srun3000计费系统user_info.php命令执行":srun_user_info_uid_rce_BaseVerify(url),
"intel AMT web系统绕过登录(CVE-2017-5689)":intel_amt_crypt_bypass_BaseVerify(url),
"smtp starttls明文命令注入(CVE-2011-0411)":smtp_starttls_plaintext_inj_BaseVerify(url),
"resin viewfile 任意文件读取":resin_viewfile_fileread_BaseVerify(url),
"mongodb 未授权漏洞":mongodb_unauth_BaseVerify(url),
"深信服 AD4.5版本下命令执行漏洞":sangfor_ad_script_command_exec_BaseVerify(url),
}
self.hardwarepocdict = {
"Dlink 本地文件包含":router_dlink_webproc_fileread_BaseVerify(url),
"Dlink DIAGNOSTIC.PHP命令执行":router_dlink_command_exec_BaseVerify(url),
"锐捷VPN设备未授权访问漏洞":router_ruijie_unauth_BaseVerify(url),
"上海安达通某网关产品&某VPN产品struts命令执行":adtsec_gateway_struts_exec_BaseVerify(url),
"SJW74系列安全网关 和 PN-2G安全网关信息泄露":adtsec_Overall_app_js_bypass_BaseVerify(url),
"迈普vpn安全网关弱口令&&执行命令":mpsec_weakpass_exec_BaseVerify(url),
"迈普网关webui任意文件下载":mpsec_webui_filedownload_BaseVerify(url),
"浙江宇视(DVR/NCR)监控设备远程命令执行漏洞":camera_uniview_dvr_rce_BaseVerify(url),
"富士施乐打印机默认口令漏洞":printer_xerox_default_pwd_BaseVerify(url),
"惠普打印机telnet未授权访问":printer_hp_jetdirect_unauth_BaseVerify(url),
"东芝topaccess打印机未授权漏洞":printer_topaccess_unauth_BaseVerify(url),
"佳能打印机未授权漏洞":printer_canon_unauth_BaseVerify(url),
"juniper NetScreen防火墙后门(CVE-2015-7755)":juniper_netscreen_backdoor_BaseVerify(url),
"海康威视web弱口令":camera_hikvision_web_weak_BaseVerify(url),
}
|
[
"297954441@qq.com"
] |
297954441@qq.com
|
b47a6d66fa27cdee16eb131e2432067dc963a979
|
ef5f527476503657635243e3ec1f280877cedb26
|
/Genie.py
|
5f464da23226674e8ac64035a1579f291a3bfeb9
|
[] |
no_license
|
dcgmechanics/GenieVA
|
dd77ee454e695c1a50ab8c341f6764f00e7043d4
|
259512a3a987ba9c2ad347f01c90c5aac1a40529
|
refs/heads/master
| 2023-01-29T19:38:53.281655
| 2020-12-08T08:18:35
| 2020-12-08T08:18:35
| 288,934,818
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 20,687
|
py
|
import os
import pyttsx3
print("Welcome To Genie Windows Assistant Version 0.1\n")
pyttsx3.speak("Welcome To Genie Windows Assistant Version 0.1")
print("Please Before Using This Program Open 'Read Me' Text File for Better Understanding Of Features of This Program.\n")
pyttsx3.speak("Please Before Using This Program Open Read Me Text File for Better Understanding Of Features of This Program.")
print("Which Operation do you want to Run?\n")
pyttsx3.speak("Which Operation do you want to Run")
print("1. Control Panel Program Shortcuts")
print("2. Commonly Used Windows Tools")
print("3. Microsoft System Configurations")
print("4. Other Windows Tools")
print("5. System File Checker Utility")
print("6. Applications (if installed)\n")
while True:
print("Enter Your Operation: ", end='')
x = input()
if ("1" in x) or ("Control" in x) or ("Panel" in x) or ("Shortcuts" in x) or ("control" in x) or ("panel" in x) or ("shortcuts" in x):
print("You Have Chosen Control Panel Program Shortcuts")
pyttsx3.speak("You Have Chosen Control Panel Program Shortcuts")
print("Hence, These are the Options You Get\n")
pyttsx3.speak("Hence, These are the Options You Get")
print("1. Control Panel")
print("2. Personalization - Color and Appearance")
print("3. File Explorer & Folders Properties")
print("4. Keyboard Properties")
print("5. Mouse Properties")
print("6. Network Connections")
print("7. Devices & Printers")
print("8. Manage Current User Account")
print("9. Manage All User Accounts")
print("10. Windows Update")
print("11. Administrative Tools")
print("12. Task Scheduler")
print("13. Application Wizard (Program & Features)")
print("14. Power Options or Configuration")
print("15. Date & Time Properties")
print("16. Display - Screen Resolution")
print("17. Regional Setting")
print("18. Sound Properties")
print("19. Internet Propeties")
print("20. Security & Maintenance")
print("21. System Properties")
print("22. Ease of Access")
print("23. Windows Defender Firewall\n")
print("Choose Which One You Want To Run: ", end='')
pyttsx3.speak("Choose Which One You Want To Run")
a = input()
if ("Control" in a) or ("control" in a) or ("Panel" in a) or ("panel" in a):
pyttsx3.speak("Control Panel is Launching...")
os.system("control")
elif ("Personalization" in a) or ("personalization" in a) or ("Color" in a) or ("color" in a) or ("Appearance" in a) or ("apperance" in a):
pyttsx3.speak("Personalization - Color and Appearance is Launching...")
os.system("control color")
elif ("File" in a) or ("file" in a) or ("Explorer" in a) or ("explorer" in a) or ("Folders" in a) or ("folders" in a):
pyttsx3.speak("File Explorer & Folders Properties is Launching...")
os.system("control folders")
elif ("Keyboard" in a) or ("keyboard" in a):
pyttsx3.speak("Keyboard Properties is Launching...")
os.system("control keyboard")
elif ("Mouse" in a) or ("mouse" in a):
pyttsx3.speak("Mouse Properties is Launching...")
os.system("control mouse")
elif ("Network" in a) or ("network" in a) or ("Connections" in a) or ("connections" in a) or ("connection" in a):
pyttsx3.speak("Network Connections is Launching...")
os.system("control netconnections")
elif ("Devices" in a) or ("devices" in a) or ("device" in a) or ("Printers" in a) or ("printers" in a) or ("printer" in a):
pyttsx3.speak("Devices & Printers is Launching")
os.system("control printers")
elif ("Current" in a) or ("current" in a):
pyttsx3.speak("Current User Account Setting is Launching...")
os.system("control userpasswords")
elif ("All" in a) or ("all" in a):
pyttsx3.speak("All User Account Setting is Launching...")
os.system("control userpasswords2")
elif ("Windows" in a) or ("windows" in a) or ("Window" in a) or ("window" in a) or ("Update" in a) or ("update" in a):
pyttsx3.speak("Windows Updates is Launching...")
os.system("control update")
elif ("Administrative" in a) or ("administrative" in a) or ("Admin" in a) or ("admin" in a):
pyttsx3.speak("Administrative Tools is Launching...")
os.system("control admintools")
elif ("Task" in a) or ("task" in a) or ("Scheduler" in a) or ("scheduler" in a):
pyttsx3.speak("Task Scheduler is Launching...")
os.system("control schedtasks")
elif ("Application" in a) or ("applications" in a) or ("App" in a) or ("app" in a) or ("Program" in a) or ("program" in a):
pyttsx3.speak("Application Wizard Aka Program & Features is Launching...")
os.system("appwiz.cpl")
elif ("Power" in a) or ("power" in a):
pyttsx3.speak("Power Options is Launching...")
os.system("powercfg.cpl")
elif ("date" in a) or ("Date" in a) or ("Time" in a) or ("time" in a):
pyttsx3.speak("Date & Time Properties is Launching...")
os.system("timedate.cpl")
elif ("Display" in a) or ("Screen" in a) or ("display" in a) or ("screen" in a) or ("Resolution" in a) or ("resolution" in a):
pyttsx3.speak("Display & Screen Resolution Setting is Launching...")
os.system("desk.cpl")
elif ("Regional" in a) or ("regional" in a) or ("Region" in a) or ("region" in a):
pyttsx3.speak("Regional Setting is Launching...")
os.system("intl.cpl")
elif ("Sound" in a) or ("sound" in a) or ("audio" in a):
pyttsx3.speak("Sound Properties is Launching...")
os.system("mmsys.cpl")
elif ("Internet" in a) or ("internet" in a):
pyttsx3.speak("Internet Properties is Launching...")
os.system("inetcpl.cpl")
elif ("Security" in a) or ("security" in a) or ("Maintenance" in a) or ("maintnance" in a):
pyttsx3.speak("Security & Maintenance is Launching...")
os.system("wscui.cpl")
elif ("System" in a) or ("system" in a):
pyttsx3.speak("System Properties is Launching...")
os.system("sysdm.cpl")
elif ("Ease" in a) or ("ease" in a) or ("Access" in a) or ("access" in a):
pyttsx3.speak("Ease Of Access is Launching...")
os.system("utilman")
elif ("Windows" in a) or ("windows" in a) or ("Firewall" in a) or ("firewall" in a):
pyttsx3.speak("Windows Defender is Launching...")
os.system("firewall.cpl")
else:
print("You Have Done Wrong Choice")
pyttsx3.speak("You Have Done Wrong Choice")
elif ("2" in x) or (("Commonly" in x) or ("common" in x)) and (("Windows" in x) or ("windows" in x)):
print("You Have chosen Commonly Used Windows Tools")
pyttsx3.speak("You Have chosen Commonly Used Windows Tools")
print("Hence, These are the Options You Get\n")
pyttsx3.speak("Hence, These are the Options You Get")
print("1. Windows Explorer")
print("2. Explorer C: Drive")
print("3. Registory Editor")
print("4. Windows Services")
print("5. Task Manager")
print("6. System Configuration Utility")
print("7. Remote Desktop Connection Utility")
print("8. Log Off Windows")
print("9. Shuts Down Windows")
print("10. Calculator")
print("11. Command Prompt")
print("12. Notepad\n")
print("Choose Which One You Want To Run: ", end='')
pyttsx3.speak("Choose Which One You Want To Run")
b = input()
if (("Windows" in b) or ("windows" in b) or ("window" in b)) and (("Explorer" in b) or ("explorer" in b)):
pyttsx3.speak("Windows Explorer is Launching...")
os.system("explorer")
elif ("Explorer" in b) or ("explorer" in b) or ("Drive" in b) or ("drive" in b):
pyttsx3.speak("C Drive is Exploring...")
os.system("c:")
elif ("Registory" in b) or ("registory" in b) or ("reg" in b) or ("Editor" in b) or ("editor" in b) or ("edit" in b):
pyttsx3.speak("registory Editor is Launching...")
os.system("regedit")
elif (("Windows" in b) or ("windows" in b) or ("window" in b)) and (("Services" in b) or ("services" in b) or ("service" in b)):
pyttsx3.speak("Windows Services is Launching...")
os.system("services.msc")
elif (("Task" in b) or ("task" in b)) and (("Manager" in b) or ("manager" in b)):
pyttsx3.speak("Task Manager is Launching...")
os.system("taskmgr")
elif ("System" in b) or ("system" in b) or ("Configuration" in b) or ("configuration" in b) or ("Utility" in b) or ("utility" in b):
pyttsx3.speak("System Configuration Utility is Launching...")
os.system("msconfig")
elif ("Remote" in b) or ("remote" in b) or ("Desktop" in b) or ("desktop" in b):
pyttsx3.speak("Remote Desktop Connection Utility is Launching...")
os.system("mstsc")
elif ("Log" in b) or ("log" in b):
pyttsx3.speak("Windows is Logging Off...")
os.system("logoff")
elif ("Shut" in b) or ("shut" in b) or ("Shutdown" in b) or ("shutdown" in b):
pyttsx3.speak("Windows is Shutting Down...")
os.system("shutdown")
elif ("Calc" in b) or ("calc" in b) or ("Calculator" in b) or ("calculator" in b):
pyttsx3.speak("Calculator is Launching...")
os.system("calc")
elif ("cmd" in b) or ("Cmd" in b) or ("Command" in b) or ("command" in b):
pyttsx3.speak("Command Prompt is Launching...")
os.system("cmd")
elif ("Notepad" in b) or ("notepad" in b) or ("editor" in b):
pyttsx3.speak("Notepad is Launching")
os.system("notepad")
else:
print("You Have Done Wrong Choice")
pyttsx3.speak("You Have Done Wrong Choice")
elif ("3" in x) or ((("Microsoft" in x) or ("microsoft" in x)) or (("System" in x) or ("system" in x))) and (("Config" in x) or ("config" in x)):
print("You Have chosen Microsoft System Configurations")
pyttsx3.speak("You Have chosen Microsoft System Configurations")
print("Hence, These are the Options You Get\n")
pyttsx3.speak("Hence, These are the Options You Get")
print("1. Device Management")
print("2. Event Viewer")
print("3. Computer Management including System Tools, Storage, Services and Applications")
print("4. Disk Management")
print("5. Component Services")
print("6. Group Policy Editor")
print("7. Local Security Policy Settings")
print("8. Local Users and Groups")
print("9. Performance Monitor")
print("10. Shared Folders\n")
print("Choose Which One You Want To Run: ", end='')
pyttsx3.speak("Choose Which One You Want To Run")
c = input()
if ("Device" in c) or ("device" in c):
pyttsx3.speak("Device Management is Launching...")
os.system("devmgmt.msc")
elif ("Event" in c) or ("event" in c) or ("Viewer" in c) or ("viewer" in c) or ("View" in c) or ("view" in c):
pyttsx3.speak("Event Viewer is Launching")
os.system("eventvwr.msc")
elif (("Computer" in c) or ("computer" in c)) and (("Management" in c) or ("management" in c)):
pyttsx3.speak("Computer Management is Launching...")
os.system("compmgmt.msc")
elif ("Disk" in c) or ("disk" in c):
pyttsx3.speak("Disk Partition Manager is Launching...")
os.system("diskmgmt.msc")
elif ("Component" in c) or ("component" in c):
pyttsx3.speak("Component Services is Launching...")
os.system("dcomcnfg")
elif (("Group" in c) or ("group" in c)) and (("Policy" in c) or ("policy" in c)):
pyttsx3.speak("Group Policy Editor is Launching")
os.system("gpedit.msc")
elif ((("Local" in c) or ("local" in c)) or (("Security" in c) or ("security" in c))) and (("Policy" in c) or ("policy" in c)):
pyttsx3.speak("Loacl Security Policy Editor Setting is Launching...")
os.system("secpol.msc")
elif (("Local" in c) or ("local" in c)) and ((("User" in c) or ("user" in c)) or (("Group" in c) or ("group" in c))):
pyttsx3.speak("Local User and Groups is Launching...")
os.system("lusrmgr.msc")
elif ("Performance" in c) or ("performance" in c) or ("Monitor" in c) or ("monitor" in c):
pyttsx3.speak("Performance Monitor is Launching...")
os.system("perfmon.msc")
elif (("Shared" in c) or ("shared" in c)) and (("Folder" in c) or ("folder" in c)):
pyttsx3.speak("Shared Folders is Launching")
os.system("fsmgmt.msc")
else:
print("You Have Done Wrong Choice")
pyttsx3.speak("You Have Done Wrong Choice")
elif ("4" in x) or ((("Windows" in x) or ("window" in x)) and (("Tools" in x) or ("tool" in x))):
print("You Have chosen Other Windows Tools")
pyttsx3.speak("You Have chosen Other Windows Tools")
print("Hence, These are the Options You Get\n")
pyttsx3.speak("Hence, These are the Options You Get")
print("1. Create a Shared Folder Wizard")
print("2. Direct X Diagnostic Tool")
print("3. Disk Cleanup Utility")
print("4. Windows Installer Details")
print("5. Windows Magnifier")
print("6. On Screen Keyboard")
print("7. System Information")
print("8. Volume Control")
print("9. Windows Version")
print("10. Compare Files")
print("11. MS-Dos FTP")
print("12. Volume Serial Number for C:")
print("13. File Signature Verification Tool")
print("14. Game Controllerss")
print("15. Malicious Software Removal Tool")
print("16. Private Chracter Editor\n")
print("Choose Which One You Want To Run: ", end='')
pyttsx3.speak("Choose Which One You Want To Run")
d = input()
if ("Shared" in d) or ("shared" in d):
pyttsx3.speak("Chared Folder Wizard Creation Tool is Launching...")
os.system("shrpubw")
elif ("Direct" in d) or ("direct" in d) or ("Directx" in d) or ("DirectX" in d) or ("directx" in d):
pyttsx3.speak("Direct X Dignostic Tool is Launching...")
os.system("dxdiag")
elif ("Disk" in d) or ("disk" in d) or ("Cleanup" in d) or ("cleanup" in d):
pyttsx3.speak("Disk Cleanup Utility is Launching...")
os.system("cleanmgr")
elif (("Windows" in d) or ("windows" in d)) and (("Installer" in d) or ("installer" in d)):
pyttsx3.speak("Windows Installer Details is Launching...")
os.system("msiexec")
elif ("Screen" in d) or ("screen" in d) or ("Keyboard" in d) or ("keyboard" in d):
pyttsx3.speak("On Screen keyboard is Launching...")
os.system("osk")
elif (("System" in d) or ("system" in d)) and (("Information" in d) or ("information" in d) or ("Info" in d) or ("info" in d)):
pyttsx3.speak("System Information is Launching...")
os.system("msinfo32")
elif (("Voulme" in d) or ("volume" in d)) and (("control" in d) or ("Control" in d)):
pyttsx3.speak("Volume Control is Launching...")
os.system("sndvol")
elif ((("Windows" in d) or ("windows" in d)) or (("window" in d) or ("Window" in d))) and (("Version" in d) or ("version" in d)):
pyttsx3.speak("Windows Version is launching...")
os.system("winver")
elif ("Compare" in d) or ("compare" in d):
pyttsx3.speak("Compare Files Tool is Launching...")
os.system("comp")
elif ("ftp" in d) or ("Ftp" in d) or ("Transfer" in d) or ("transfer" in d):
pyttsx3.speak("MS-DOS File Transfer Protocol is Launching...")
os.system("ftp")
elif ("Serial" in d) or ("serial" in d):
pyttsx3.speak("Volume Serial Number For C: Tool is Launching...")
os.system("label")
elif ("Singature" in d) or ("signature" in d) or ("verification" in d) or ("verification" in d):
pyttsx3.speak("File Signature Verification Tool is Launching...")
os.system("sigverif")
elif ("Game" in d) or ("game" in d) or ("Controller" in d) or ("controller" in d):
pyttsx3.speak("Game Controller Setting is Launching...")
os.system("joy.cpl")
elif ("Malicious" in d) or ("malicious" in d) or ("Remove" in d) or ("remove" in d):
pyttsx3.speak("Malicious Software Removal Tool is Launching...")
os.system("mrt")
elif ("Private" in d) or ("private" in d) or ("Char" in d) or ("char" in d):
pyttsx3.speak("Private Chracter Editor is Launching...")
os.system("eudcedit")
else:
print("You Have Done Wrong Choice")
pyttsx3.speak("You Have Done Wrong Choice")
elif ("5" in x) or ((("System" in x) or ("system" in x)) or (("file" in x) or ("File" in x))) and (("check" in x) or ("Check" in x)):
print("You Have Chosen System File Checker Utility")
pyttsx3.speak("You Have Chosen System File Checker Utility")
print("Hence, These are the Options You Get\n")
pyttsx3.speak("Hence, These are the Options You Get")
print("1. Scan Immediately")
print("2. Scan Once at Next Boot")
print("3. Scan On Every Boot")
print("4. Return to Default Setting")
print("5. Purge File Cache")
# print("6. Set Chache Size to Size:\n") "This Option Doesn't Works Now"
print("Choose Which One You Want To Run: ", end='')
pyttsx3.speak("Choose Which One You Want To Run")
e = input()
if ("Immediate" in e) or ("immediate" in e):
pyttsx3.speak("Scan Immediately is Launching...")
os.system("sfc /scannow")
elif ("Next" in e) or ("next" in e):
pyttsx3.speak("Scan Once at Next Boot is Set...")
os.system("sfc /scannow")
elif ("Every" in e) or ("every" in e):
pyttsx3.speak("Scan On Every Boot is Set...")
os.system("sfc/ scanboot")
elif (("Return" in e) or ("return" in e)) or ("default" in e) or ("Default" in e):
pyttsx3.speak("Return to Default Setting is Set...")
os.system("sfc /revert")
elif ("Purge" in e) or ("purge" in e):
pyttsx3.speak("Purge File Cache is Performing...")
os.system("sfc /purgecache")
# elif (("Set" in e) or ("set" in e)) and (("Cache" in e) or ("cache" in e)):
pyttsx3.speak("Enter The Value in MegaBytes To Set Cache Size...")
print(": ", end='')
w = input()
os.system("sfc /cachesize= w")
else:
print("You Have Done Wrong Choice")
pyttsx3.speak("You Have Done Wrong Choice")
elif ("6" in x) or ("App" in x) or ("app" in x) or ("Application" in x) or ("application" in x):
print("You Have chosen Applications to Run, Before Running Any Application You Must Set The Enviornmets Variables Otherwise This will not Work.")
pyttsx3.speak("You Have chosen Applications to Run, Before Running Any Application You Must Set The Enviornmets Variables Otherwise This will not Work.")
print("So, These are the Applications You Get\n")
pyttsx3.speak("So, These are the Applications You Get")
print("1. Adobe Photoshop 2020")
print("2. Google Chrome")
print("3. Internet Explorer")
print("4. iTunes")
print("5. Internet Download Manager")
print("6. Tor browser")
print("7. VLC")
print("8. Windows Media Player\n")
print("Choose Which Application You Want To Run: ", end='')
pyttsx3.speak("Choose Which Application You Want To Run")
f = input()
if ("Adobe" in f) or ("adobe" in f) or ("Photoshop" in f) or ("photoshop" in f) or ("PS" in f) or ("ps" in f):
pyttsx3.speak("Adobe Photoshop 2020 is Launching...")
os.system("photoshop")
elif ("Google" in f) or ("google" in f) or ("Chrome" in f) or ("chrome" in f) or ("Browser" in f) or ("browser" in f):
pyttsx3.speak("Google Chrome is Launching...")
os.system("chrome")
elif (("Internet" in f) or ("internet" in f)) and ((("Ie" in f) or ("ie" in f)) or (("explorer" in f) or ("Explorer" in f))):
pyttsx3.speak("Internet Explorer is Launching...")
os.system("iexplore")
elif ("iTunes" in f) or ("itunes" in f):
pyttsx3.speak("iTunes is Launching...")
os.system("iTunes")
elif ("Download" in f) or ("download" in f) or ("Downloader" in f) or ("downloader" in f) or ("IDM" in f) or ("idm" in f):
pyttsx3.speak("Internet Download Manager is Launching...")
os.system("idman")
elif ("Tor" in f) or ("tor" in f):
pyttsx3.speak("TOR Browser is Launching...")
os.system("firefox")
elif ("VLC" in f) or ("Vlc" in f) or ("vlc" in f):
pyttsx3.speak("VLC Media Player is Launching...")
os.system("vlc")
elif (("Windows" in f) or ("window" in f)) and (("media" in f) or ("player" in f)):
pyttsx3.speak("Windows Media Player is Launching...")
os.system("wmplayer")
else:
print("You Have Done Wrong Choice")
pyttsx3.speak("You Have Done Wrong Choice")
elif ("quit" in x) or ("Quit" in x) or ("close" in x) or ("Close" in x) or ("Exit" in x) or ("exit" in x) or ("no" in x) or ("bye" in x):
print("Thank You For Using Genie Windows Assistant Version 0.1")
pyttsx3.speak("Thank You For Using Genie Windows Assistant Version 0.1")
break;
else:
print("You Have Done Wrong Choice,Try Again,")
pyttsx3.speak("You Have Done Wrong Choice, Try Again,")
# Coder Note: Whatever i learned till today i used all of them in this program. The More I Learn Python Langauge The More Features I'll Implement. Till Then Enjoy ;)
# This one Took me Approx 10 Hours to Write From Sacrtch + Finding Commands + Testing Them on My PC + Debbuging & This is still in beta version.
# Regards: #dcgmechanics
#Telegram:- t.me/dcgmechanics
#Discord:- dcgmechanics#0422
|
[
"noreply@github.com"
] |
noreply@github.com
|
1013785aa4623094ca872c97f462ebf477bb6274
|
0dfcb900d11918b85a3e1791983babd47a5080e2
|
/notif_sender.py
|
e703821b51abba488277e9a7e23fe834f102a63c
|
[
"MIT"
] |
permissive
|
redwanc12/DMV_APPOINTMENT_FINDER
|
216207541f53eec36f8b92c51168764c5c216894
|
702142d26d5da63c30785941455c47cd6e524fdd
|
refs/heads/master
| 2020-05-21T03:03:43.961592
| 2019-07-30T13:29:27
| 2019-07-30T13:29:27
| 185,891,905
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,328
|
py
|
"""class to send notifications"""
import smtplib
import requests
from bs4 import BeautifulSoup
r = requests.get('http://127.0.0.1:8000/polls/open')
soup = BeautifulSoup(r.text, 'html.parser')
emails = soup.find_all('h1')
days = soup.find_all('p')
emailList = []
for each in range(len(emails)):
emailList.append({
'day': days[each].text,
'email': emails[each].text
})
class notif(object):
def __init__(self):
self.email = 'dmvnotificationhi@gmail.com'
self.password = 'DMVpass123!'
def logIn(self):
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(self.email, self.password)
def sendEmail(self, email, subject, body):
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
msg = f'Subject: {subject}\n\n{body}'
smtp.login(self.email, self.password)
smtp.sendmail(self.email, email, msg)
def dateToBody(self, dates):
body = ''
for each in dates:
body += (each['openings'] + ' Opening at ' + each['time'] + ' at ' + each['location'] + ' on ' + each['day'] + '\n')
return body
|
[
"redwanc12@gmail.com"
] |
redwanc12@gmail.com
|
f35bf08db192b2f12f1b4ff64bf4c6e9c9c0086e
|
bb6058b4850aac4c48a3c800b61606d868ffd9fa
|
/mysite/orders/migrations/0002_auto_20200601_1557.py
|
1a29226dc6ff504e4171c5ad10da80fbd004cbf1
|
[] |
no_license
|
AlexanderSobolevskiy/project1
|
e3354f0bc56bb113b199ef64a6deb429cb297a77
|
9a2af271aa6b8bc25e6fc97109ebc3029496dd2c
|
refs/heads/master
| 2022-11-07T22:28:19.691327
| 2020-06-23T21:28:06
| 2020-06-23T21:28:06
| 273,778,489
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,198
|
py
|
# Generated by Django 3.0.5 on 2020-06-01 12:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='order',
name='customer_address',
field=models.CharField(blank=True, default=None, max_length=128, null=True),
),
migrations.AddField(
model_name='order',
name='total_amount',
field=models.DecimalField(decimal_places=2, default=0, max_digits=10),
),
migrations.AddField(
model_name='productinorder',
name='number',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='productinorder',
name='price_per_item',
field=models.DecimalField(decimal_places=2, default=0, max_digits=10),
),
migrations.AddField(
model_name='productinorder',
name='total_price',
field=models.DecimalField(decimal_places=2, default=0, max_digits=10),
),
]
|
[
"sobolevskiy.1@mail.ru"
] |
sobolevskiy.1@mail.ru
|
b043023374ed31f1daee522d606925932e11d97f
|
d50e9b2a52cb4a5519ee972de1384bffa4fcefe2
|
/tp3/prueba.py
|
267fb84b8231552b4f700310bf37a05e6543faa6
|
[] |
no_license
|
LisandroRobles/tps_dsp
|
b2e3724bb3b569de2d8d244b6dddf116796bbcae
|
b46423a9f5b78835305ad6acae8e62cf67d23659
|
refs/heads/master
| 2020-04-09T06:20:15.682176
| 2019-05-05T15:15:37
| 2019-05-05T15:15:37
| 160,106,843
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,428
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 7 10:00:20 2018
@author: lisandro
"""
#Paquetes
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
import pdsmodulos.signal_generator as gen
import pdsmodulos.spectrum_analyzer as sa
#Testbench
def testbench():
fs = 1024
N = 1024
Ts = 1/fs
df = fs/N
Ao = np.sqrt(1)
fo1 = np.pi/2
fo2 = np.pi/4
po = 0
generador = gen.signal_generator(fs,N)
(t,x1) = generador.sinewave(Ao,fo1,po,freq = 'normalized_frequency')
(t,x2) = generador.sinewave(Ao,fo2,po,freq = 'normalized_frequency')
x = x1 + x2
parseval_1 = np.sum(np.power(x,2))*Ts
print('Energia calculada calculada con x(t)')
print(parseval_1)
analizador = sa.spectrum_analyzer(fs,N)
(f,Sxx) = analizador.psd(x,xaxis = 'phi')
parseval_2 = np.sum(Sxx)*df
print('Energia calculada de X(f)')
print(parseval_2)
plt.figure()
plt.title('Senoidal')
plt.plot(t,x)
plt.grid()
plt.axis('tight')
plt.xlabel('t[s]')
plt.ylabel('x(t)')
# print('Energia de la senoidal')
# print(np.sum(Pxx_spec))
#
# plt.figure()
# plt.title('Periodograma')
# plt.plot(f,Pxx_spec)
# plt.grid()
# plt.axis('tight')
# plt.xlabel('f[Hz]')
# plt.ylabel('Pxx(f)')
#Script
testbench()
|
[
"LisandroRobles1@gmail.com"
] |
LisandroRobles1@gmail.com
|
19e2826616e1dd3444926f89dbc7a7816a07236e
|
5acbf224c36f812075b899320c74f0e47b448ad9
|
/CNN_on_cifar_ByPytorch/12_WideResNet.py
|
51f2233f95bce9d09529613f61c00b1a3f78cc76
|
[] |
no_license
|
lovecodestudent/Classification_model
|
a5b190a3788ed6b5ca28ea89e68e8814db382fd4
|
62b6849080da3f9033dcf01a9e16b0d35c371c45
|
refs/heads/master
| 2022-07-10T01:56:27.608340
| 2020-05-13T04:41:27
| 2020-05-13T04:41:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,135
|
py
|
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import numpy as np
import sys
def conv_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
init.xavier_uniform(m.weight, gain=np.sqrt(2))
init.constant(m.bias, 0)
elif classname.find('BatchNorm') != -1:
init.constant(m.weight, 1)
init.constant(m.bias, 0)
class Wide_Basic(nn.Module):
def __init__(self, in_planes, planes, dropout_rate, stride=1):
super(Wide_Basic, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, bias=True)
self.dropout = nn.Dropout(p=dropout_rate)
self.bn2 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=True)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != planes:
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride, bias=True),
)
def forward(self, x):
out = F.relu(self.bn1(x))
out = self.dropout(self.conv1(out))
out = F.relu(self.bn2(out))
out = self.conv2(out)
out += self.shortcut(x)
return out
class Wide_ResNet(nn.Module):
def __init__(self, depth, widen_factor, dropout_rate, num_classes):
super(Wide_ResNet, self).__init__()
self.in_planes = 16
assert ((depth - 4) % 6 == 0), 'Wide-resnet depth should be 6n+4'
n = (depth - 4) / 6
k = widen_factor
print('| Wide-Resnet %dx%d' % (depth, k))
nStages = [16, 16*k, 32*k, 64*k]
self.conv1 = nn.Conv2d(3, nStages[0], kernel_size=3, stride=1, padding=1, bias=True)
self.layer1 = self._wide_layer(Wide_Basic, nStages[1], n, dropout_rate, stride=1)
self.layer2 = self._wide_layer(Wide_Basic, nStages[2], n, dropout_rate, stride=2)
self.layer3 = self._wide_layer(Wide_Basic, nStages[3], n, dropout_rate, stride=2)
self.bn1 = nn.BatchNorm2d(nStages[3], momentum=0.9)
self.linear = nn.Linear(nStages[3], num_classes)
def _wide_layer(self, block, planes, num_blocks, dropout_rate, stride):
strides = [stride] + [1] * int((num_blocks - 1))
layers = []
for stride in strides:
layers.append(block(self.in_planes, planes, dropout_rate, stride))
self.in_planes = planes
return nn.Sequential(*layers)
def forward(self, x):
out = self.conv1(x)
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = F.relu(self.bn1(out))
out = F.avg_pool2d(out, 8)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
def WideResNet(depth=28, widen_factor=10, dropout_rate=0.3, num_classes=10):
return Wide_ResNet(depth, widen_factor, dropout_rate, num_classes)
if __name__ == '__main__':
x = torch.randn(1, 3, 32, 32)
net = WideResNet()
out = net(x)
print(out.shape)
|
[
"gyt0713@126.com"
] |
gyt0713@126.com
|
a82007d69c6f4e2df88bcdfd604ab7c5667cb165
|
e581edf33f2d9c376f96e2c1658292e1af25809a
|
/docx_simple_service.py
|
5cef8283f90f32e787ede5205a4400bf572dc312
|
[] |
no_license
|
Nissinko/AutoArticle
|
0d9d2b6518e5d31a1337a8adceb3ab5339ec69bb
|
af6ef79453f133ac02206aae573095bd0e156a5d
|
refs/heads/master
| 2020-03-27T15:26:21.045716
| 2018-10-18T07:18:42
| 2018-10-18T07:18:42
| 146,717,972
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,175
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# SimpleDocService
# python-doxに関する簡単なサービスを提供します。
# まぁ docxライブラリを理解するためのコードですね。
#
from docx import Document
from docx.shared import RGBColor
from docx.shared import Inches
from docx.shared import Pt
class SimpleDocxService:
def __init__(self):
self.document = Document()
self.latest_run = None
def set_normal_font(self, name, size):
# フォントの設定
font = self.document.styles['Normal'].font
font.name = name
font.size = Pt(size)
def add_head(self, text, lv):
# 見出しの設定
self.document.add_heading(text, level=lv)
def open_text(self):
# テキスト追加開始
self.paragraph = self.document.add_paragraph()
def close_text(self):
# テキスト追加終了
return #現状では特に処理はなし
def get_unicode_text(self, text, src_code):
# python-docxで扱えるように unicodeに変換
return unicode(text, src_code)
def adjust_return_code(self, text):
# テキストファイルのデータをそのままaddすると改行が
# 面倒なことになるので、それを削除
text = text.replace("\n", "")
text = text.replace("\r", "")
return text
def add_text(self, text):
# テキスト追加
self.latest_run = self.paragraph.add_run(text)
def add_text_italic(self, text):
# テキスト追加(イタリックに)
self.paragraph.add_run(text).italic = True
def add_text_bold(self, text):
# テキスト追加(強調)
self.paragraph.add_run(text).bold = True
def add_text_color(self, text, r, g, b):
# 文字に色をつける
self.paragraph.add_run(text).font.color.rgb = RGBColor(r, g, b)
def add_picture(self, filename, inch):
# 図を挿入する
self.document.add_picture(filename, width=Inches(inch))
def save(self, name):
# docxファイルとして出力。
self.document.save(name)
|
[
"akiyama.takanori@unipro.co.jp"
] |
akiyama.takanori@unipro.co.jp
|
58fffd1a4a3bc143d14f8ded6ee0c3af6f36b4a1
|
0c66d794765282400ba8f72c8f086d8a40fec16f
|
/Instruments/Blank/python/Blank.py
|
bb60cfa24b23d1af4a8cf9aefff64690e77b7346
|
[] |
no_license
|
collaborative-music-lab/NIME
|
14940598d61c64d2c63db3380f0e48ad59515a06
|
38ffc312f41b11376a5409c3038cf8a59d790fb3
|
refs/heads/master
| 2023-05-26T10:42:10.931069
| 2023-05-08T19:24:57
| 2023-05-08T19:24:57
| 197,260,152
| 10
| 2
| null | 2022-02-09T22:42:49
| 2019-07-16T20:07:33
|
C++
|
UTF-8
|
Python
| false
| false
| 2,845
|
py
|
#Blank.py
#Ian Hattwick
#Mar 1, 2023
PACKET_INCOMING_SERIAL_MONITOR = 0
CUR_PYTHON_SCRIPT = "Blank.py"
import serial, serial.tools.list_ports, socket, sys, asyncio,struct,time, math
from pythonosc import osc_message_builder
from pythonosc import udp_client
from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
#m370 python modules
import scripts.m370_communication as m370_communication
comms = m370_communication.communication("serial", baudrate = 115200, defaultport="/dev/tty.SLAB_USBtoUART")
import scripts.timeout as timeout
#you can change the defaultport to the name your PC gives to the ESP32 serial port
import sensorInput as sensor
import oscMappings as osc
osc.comms = comms
t = timeout.Timeout(5)
osc.t = t
######################
# SET COMMUNICATION MODE
######################
SERIAL_ENABLE = 1
WIFI_ENABLE = 0
######################
#SETUP OSC
######################
#initialize UDP client
client = udp_client.SimpleUDPClient("127.0.0.1", 5005)
osc.client = client
# dispatcher in charge of executing functions in response to RECEIVED OSC messages
dispatcher = Dispatcher()
osc.dispatcher = dispatcher
print("Sending OSC to port", 5005, "on localhost")
client.send_message("/scriptName", CUR_PYTHON_SCRIPT)
osc.defineOscHandlers()
#timeout handlers
def updateTimeout(): t.update() #reset timeout
dispatcher.map("/tick", updateTimeout)
def cancelScript(*args): t.cancel()
dispatcher.map("/cancel", cancelScript)
def unknown_OSC(*args): print("unknown OSC message: ", args)
dispatcher.set_default_handler(unknown_OSC)
######################
#LOOP
######################
async def loop():
time.sleep(0.1)
handshakeStatus = 1
print("done setup")
client.send_message("/init", 0)
while(t.check()):
#t.check checks if timeout has triggered to cancel script
await asyncio.sleep(0) #listen for OSC
#print(comms.available())
while(comms.available() > 0):
currentMessage = comms.get() # can be None if nothing in input buffer
if currentMessage != None:
if PACKET_INCOMING_SERIAL_MONITOR == 0:
if 2 < len(currentMessage) < 16:
address, value = sensor.processInput(currentMessage)
osc.mapSensor(address,value) #send data for mapping
client.send_message(address,value) #monitor data in PD
else:
print("packet", currentMessage) #only for unrecognized input
time.sleep(0.001)
async def init_main():
server = AsyncIOOSCUDPServer(("127.0.0.1", 5006), dispatcher, asyncio.get_event_loop())
transport, protocol = await server.create_serve_endpoint()
await loop()
transport.close()
asyncio.run(init_main())
|
[
"ian@ianhattwick.com"
] |
ian@ianhattwick.com
|
0b34ee5faf9aba369b362c1b0725e0011a94a098
|
7bf906c992b9c79179fa52f6ba975b5e0f3505dc
|
/TT/Cuts.py
|
1080e69c599d6e71b0e4dee6a196d524b3624df4
|
[] |
no_license
|
skyriacoCMS/Analysis
|
1fe04028deee1953232dc8bf8b24924d2f73d6d1
|
a74775120ac2b127698f52ca876dc8f77c0ab6a1
|
refs/heads/master
| 2020-03-13T23:47:31.451352
| 2018-04-27T21:37:53
| 2018-04-27T21:37:53
| 131,335,393
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 185
|
py
|
import os
import sys
i = sys.argv[1]
cmnd = 'root -b -q -l "CUTS.C('+i+',5,-1,-1,-1)"'
os.system('cp ../Templates/CUTS.C .')
os.system('cp ../Templates/xsecs.h .')
os.system(cmnd)
|
[
"savvasphy@gmail.com"
] |
savvasphy@gmail.com
|
e2d70ea6765a4d2275d7fe4d41337de6d45d5449
|
8f6aa9ac9c8c2e409875bbf36fbc49b3eb37d88b
|
/enthought/traits/ui/qt4/key_binding_editor.py
|
12c440438d2c61dd566c494f787af54b63d61666
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
enthought/etsproxy
|
5660cf562c810db2ceb6b592b6c12274bce96d73
|
4aafd628611ebf7fe8311c9d1a0abcf7f7bb5347
|
refs/heads/master
| 2023-03-27T04:51:29.297305
| 2020-12-02T09:05:18
| 2020-12-02T09:05:18
| 1,632,969
| 3
| 1
|
NOASSERTION
| 2020-12-02T09:05:20
| 2011-04-18T22:29:56
|
Python
|
UTF-8
|
Python
| false
| false
| 61
|
py
|
# proxy module
from traitsui.qt4.key_binding_editor import *
|
[
"ischnell@enthought.com"
] |
ischnell@enthought.com
|
03f2846a44dbf317f88f46f0902e8caf702171da
|
5abd1c1792314f61029cbd49cd3a354350a364ad
|
/send_client.py
|
94370117e9c703f40db1314a98b5060199846dc0
|
[] |
no_license
|
pvsune/simple-xmpp-chat
|
051d8ddb4f188609b2e8c43ea25a9dabb43fd859
|
1b97d2bf441eba9ef604629c89f7ac0a9b812d19
|
refs/heads/master
| 2020-12-02T18:14:49.564675
| 2017-07-13T10:48:48
| 2017-07-13T10:48:48
| 96,501,324
| 6
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,816
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2010 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
import sys
import logging
import getpass
from optparse import OptionParser
import sleekxmpp
# Python versions before 3.0 do not use UTF-8 encoding
# by default. To ensure that Unicode is handled properly
# throughout SleekXMPP, we will set the default encoding
# ourselves to UTF-8.
if sys.version_info < (3, 0):
from sleekxmpp.util.misc_ops import setdefaultencoding
setdefaultencoding('utf8')
else:
raw_input = input
class SendMsgBot(sleekxmpp.ClientXMPP):
"""
A basic SleekXMPP bot that will log in, send a message,
and then log out.
"""
def __init__(self, jid, password, recipient, message):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
# The message we wish to send, and the JID that
# will receive it.
self.recipient = recipient
self.msg = message
# The session_start event will be triggered when
# the bot establishes its connection with the server
# and the XML streams are ready for use. We want to
# listen for this event so that we we can initialize
# our roster.
self.add_event_handler("session_start", self.start, threaded=True)
def start(self, event):
"""
Process the session_start event.
Typical actions for the session_start event are
requesting the roster and broadcasting an initial
presence stanza.
Arguments:
event -- An empty dictionary. The session_start
event does not provide any additional
data.
"""
self.send_presence()
self.get_roster()
self.send_message(mto=self.recipient,
mbody=self.msg,
mtype='chat')
# Using wait=True ensures that the send queue will be
# emptied before ending the session.
self.disconnect(wait=True)
if __name__ == '__main__':
# Setup the command line arguments.
optp = OptionParser()
# Output verbosity options.
optp.add_option('-q', '--quiet', help='set logging to ERROR',
action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
optp.add_option('-d', '--debug', help='set logging to DEBUG',
action='store_const', dest='loglevel',
const=logging.DEBUG, default=logging.INFO)
optp.add_option('-v', '--verbose', help='set logging to COMM',
action='store_const', dest='loglevel',
const=5, default=logging.INFO)
# JID and password options.
optp.add_option("-j", "--jid", dest="jid",
help="JID to use")
optp.add_option("-p", "--password", dest="password",
help="password to use")
optp.add_option("-t", "--to", dest="to",
help="JID to send the message to")
optp.add_option("-m", "--message", dest="message",
help="message to send")
opts, args = optp.parse_args()
# Setup logging.
logging.basicConfig(level=opts.loglevel,
format='%(levelname)-8s %(message)s')
if opts.jid is None:
opts.jid = raw_input("Username: ")
if opts.password is None:
opts.password = getpass.getpass("Password: ")
if opts.to is None:
opts.to = raw_input("Send To: ")
if opts.message is None:
opts.message = raw_input("Message: ")
# Setup the EchoBot and register plugins. Note that while plugins may
# have interdependencies, the order in which you register them does
# not matter.
xmpp = SendMsgBot(opts.jid, opts.password, opts.to, opts.message)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0199') # XMPP Ping
# If you are working with an OpenFire server, you may need
# to adjust the SSL version used:
# xmpp.ssl_version = ssl.PROTOCOL_SSLv3
# If you want to verify the SSL certificates offered by a server:
# xmpp.ca_certs = "path/to/ca/cert"
# Connect to the XMPP server and start processing XMPP stanzas.
if xmpp.connect(('xmpp', 5222)):
# If you do not have the dnspython library installed, you will need
# to manually specify the name of the server if it does not match
# the one in the JID. For example, to use Google Talk you would
# need to use:
#
# if xmpp.connect(('talk.google.com', 5222)):
# ...
xmpp.process(block=True)
print("Done")
else:
print("Unable to connect.")
|
[
"phil@pez.ai"
] |
phil@pez.ai
|
cd2174a9a924b6f860c2f48bc90d09a586d060ec
|
395344ba5e342ba441eb1f157848bd91ee3d4bf6
|
/stack_code.py
|
fbf12ac59cfb4f353ad325db703f885ed8d36556
|
[] |
no_license
|
i4seeu/my_learning_tools
|
b75588fec1d71ab00b7a307acbef055d0aacabe0
|
392ca66eba808ba8552c021d98e25a5137d97980
|
refs/heads/master
| 2021-03-25T14:18:31.469076
| 2020-03-16T19:47:43
| 2020-03-16T19:47:43
| 247,625,862
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 852
|
py
|
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def parChecker(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol == "(":
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
s.pop()
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
print(parChecker('((()))'))
print(parChecker('(()'))
|
[
"noordinmalango@gmail.com"
] |
noordinmalango@gmail.com
|
379d72d48e0202729e8fdc829e1b3293850a6f72
|
1c829b9f786a544f4cd715072af49b05f2aca545
|
/indicators/trend.py
|
a683722cca0b4137586f4cb5a4f98eeb7d2f7bf2
|
[] |
no_license
|
Colman/Trading
|
05f5a32b85ee927151b6a1948e5cac61021c48ac
|
71cd5da318d3c56b763605b91a456b3cfaacd479
|
refs/heads/master
| 2020-12-26T23:50:30.702411
| 2020-02-01T23:56:50
| 2020-02-01T23:56:50
| 237,694,213
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,909
|
py
|
def getSMA(candles, period, index=4):
if len(candles) < period:
raise ValueError('Not enough candles for the specified period')
SMA = list()
for i in range(period - 1):
SMA.append(None)
for i in range(period - 1, len(candles)):
total = 0
for j in range(period - 1, -1, -1):
total += candles[i - j][index]
SMA.append(total / period)
return SMA
def getGeoSMA(candles, period, index=4):
if len(candles) < period:
raise ValueError('Not enough candles for the specified period')
SMA = list()
for i in range(period - 1):
SMA.append(None)
for i in range(period - 1, len(candles)):
total = 1
for j in range(period - 1, -1, -1):
total *= candles[i - j][index]
SMA.append(total ** (1 / period))
return SMA
def getSlope(candles, width, back):
if len(candles) < width + back:
raise ValueError('Not enough points for width and back')
SMA = getSMA(candles[-width - back:], width)
slope = (SMA[-1] - SMA[-1 - back]) / SMA[-1 - back]
return slope
def getGeoSlope(candles, width, back):
if len(candles) < width + back:
raise ValueError('Not enough points for width and back')
SMA = getGeoSMA(candles[-width - back:], width)
slope = (SMA[-1] - SMA[-1 - back]) / SMA[-1 - back]
return slope
def getHA(candles):
if len(candles) < 2:
raise ValueError('Not enough candles')
ha = list()
#Calc first candle
o = (candles[0][1] + candles[0][4]) / 2
c = (candles[0][1] + candles[0][2] + candles[0][3] + candles[0][4]) / 4
ha.append([candles[0][0], o, candles[0][2], candles[0][3], c, candles[0][5]])
for i in range(1, len(candles)):
candle = candles[i]
prior = ha[-1]
c = (candle[1] + candle[2] + candle[3] + candle[4]) / 4
o = (prior[1] + prior[4]) / 2
h = max(candle[2], o, c)
l = min(candle[3], o, c)
ha.append([candle[0], o, h, l, c, candle[5]])
return ha
|
[
"noreply@github.com"
] |
noreply@github.com
|
5133a8fd1104ede5dd291548ccb3839973b70b67
|
f6cb84f876f77a995b6fa1b37002d17fc7d71072
|
/src/preprocessing.py
|
a01d670b9fca92e68c89aae45fbb6a9f7963d6a9
|
[
"CC0-1.0"
] |
permissive
|
roshande/ml-framework-template
|
d86870085acd7c104cfa3e0afc9979779140a740
|
154605edd0ed6459a4704d557a93e2b49da65018
|
refs/heads/main
| 2023-05-31T03:17:40.439194
| 2021-07-11T17:58:10
| 2021-07-11T17:58:10
| 382,545,091
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,892
|
py
|
from scipy.stats import mode
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_is_fitted
__all__ = ['Numeric', 'FillNa']
class Numeric(BaseEstimator, TransformerMixin):
def __init__(self, errors="coerce", fillna_value=0, dtype=np.int32,
suffix="_prep"):
self.errors = errors
self.fillna_value = fillna_value
self.dtype = dtype
self.suffix = suffix
def fit(self, X, y=None):
self.columns = getattr(X, 'columns', None)
return self
def transform(self, X):
check_is_fitted(self, ['columns'])
for col in self.columns:
X[col+self.suffix] = pd.to_numeric(X[col], errors=self.errors)\
.fillna(value=self.fillna_value)\
.apply(self.dtype)
if self.columns is not None:
X = X.convert_dtypes()
return X
FILLING_MAP = {
"median": lambda X: X.quantile(0.5),
"mode": lambda X: mode(X)[0]
}
class FillNa(BaseEstimator, TransformerMixin):
def __init__(self, method="median", suffix="_prep"):
method = FILLING_MAP.get(method, method)
if not callable(method):
raise ValueError("Unknown filling method")
self.method = method
self.suffix = suffix
def fit(self, X, y=None):
self.columns = getattr(X, 'columns', None)
self.fill_values = {}
for col in self.columns:
fill_value = self.method(X[col])
self.fill_values[col] = fill_value
return self
def transform(self, X):
check_is_fitted(self, ['columns', 'fill_values'])
for col in self.columns:
fill_value = self.fill_values[col]
X[col+self.suffix] = X[col].fillna(value=fill_value)
return X
|
[
"roshanhande116@gmail.com"
] |
roshanhande116@gmail.com
|
0b44bb79faf29315ec66647b0981dec1ae31298b
|
1674905f0ced7f6fe9b3ca1a40855eca6c49416f
|
/SRC/sampler.py
|
fcc2b506556e7526c5e48fe95fffcab07016778f
|
[
"Apache-2.0"
] |
permissive
|
cyrilgalitzine/SDE_inference
|
304a5dd6ed93bc198f8fde70160ab869f65814de
|
e64e9c5cdf4c13bf3ba67071949c71b0a1b6d8fe
|
refs/heads/master
| 2020-03-19T00:07:23.502582
| 2018-05-30T14:38:07
| 2018-05-30T14:38:07
| 135,454,563
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,722
|
py
|
import numpy as np
from scipy.stats import norm
import pandas as pd
import pathlib
#Define an equation class
class sampler:
def __init__(self,name,param,param_infer,sd,output_freq):
self.name = name
self.param_new = param #has to be a numpy array
self.param_old = param
self.Ndim = param.size #Should always be set equal to the total number of parameters (inferred + non-inferred)
self.param_accept_stat =np.zeros(self.Ndim)
self.param_infer = param_infer
self.sd = sd #Standard deviation
self.iter=-1
self.max = -1e99
self.alpha = 0.001
self.freq = output_freq
self.param_store = np.zeros(shape=(self.freq,self.Ndim))
self.Lstore = np.zeros(shape=(self.freq,1))
self.iterstore = np.zeros(self.freq)
def save(self,L,Input):
#print((np.matrix(self.iterstore).T.astype(int)))
#print(np.concatenate((np.matrix(self.iterstore).T.astype(int),self.param_store,self.Lstore),axis=1))
index = self.iter%self.freq
self.param_store[index,:]= self.param_new
self.Lstore[index,0]= L
self.iterstore[index] = self.iter
if(index == self.freq -1):
header1 = " ".join(['iter'," ".join(Input.param_name)," ".join(Input.error_name),'L'])
if(self.iterstore[0]>0):
header1 =''
f=open('out.dat','ab')
np.savetxt(f,np.concatenate((np.matrix(self.iterstore).T.astype(int),self.param_store,self.Lstore),axis=1),header= header1,comments='')
f.close()
def read_samples(self):
my_file = pathlib.Path('out.dat')
if my_file.is_file():
df_in = pd.read_csv('out.dat',sep=' ')
else:
print('restart data not found')
return
last_line = df_in.iloc[-1]
self.iter = np.int(last_line.iter)
self.max = last_line.L
self.param_old = np.array(last_line[1:last_line.size-1])
class MH_logexp(sampler):
def __init__(self,param,param_infer,sd,output_freq):
sampler.__init__(self,'MH_logexp',param,param_infer,sd,output_freq)
print("initial with",param)
def step(self):
#Allows for some parameters to be constant:
self.param_new = np.where(self.param_infer,self.param_old*np.exp(np.random.normal(loc = 0, scale = self.sd,size=self.Ndim)),self.param_old)
def decide(self,L):
accept = 0
self.param_accept_stat *= (1 -self.alpha)
frac = L - self.max - np.log(np.prod(self.param_old)) + np.log(np.prod(self.param_new))
#print('frac=',np.log(np.prod(self.param_old)) - np.log(np.prod(self.param_new)))
#print((self.param_new))
P = min(frac,1.0)
#print('L=',L,self.max)
if( P > np.log(np.random.uniform()) ):
print(self.param_new)
print('L=',L,'Lmin=',self.max,'AR=',self.param_accept_stat)
self.param_old = self.param_new
self.max = L
accept = 1
self.param_accept_stat += self.alpha
self.iter +=1
return(accept)
|
[
"c.galitzine@neu.edu"
] |
c.galitzine@neu.edu
|
6e20ae8fccb33dc8bfa57f0dddb4a970d2d6e487
|
7cc1d37d8383ac16f8ac2bb5dec753d558f39e71
|
/HastaAkriti/manage.py
|
b06580e5298af2f329141861ddc1fd0d8e5fbdfe
|
[] |
no_license
|
internshipdeco/HastiaAkriti
|
57e45f2cd5db217c6f6c41ca163a5705b200ed63
|
ce5cca6a77e4d031d38c7bc3f3913d3ccb2ec439
|
refs/heads/master
| 2023-01-02T02:47:24.237434
| 2020-10-22T12:09:17
| 2020-10-22T12:09:17
| 306,059,261
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 631
|
py
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HastaAkriti.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
|
[
"kissna.yadav7@gmail.com"
] |
kissna.yadav7@gmail.com
|
2a2ed39cccfc804911fb565d6e90e37ab53ccb77
|
8ed9296cf14cbd48ad6c6ba977a4eddfb6158ec3
|
/lib/examples/basic_radiation-LITE.py
|
98e58e33c081925056c326049a5fdf5e1c07f745
|
[
"BSD-3-Clause"
] |
permissive
|
JoyMonteiro/CliMT
|
51191c8e44eef28057971dd29de8e40c0bd3ef97
|
0949ed3a3a125638072351d7277ae4b956956d35
|
refs/heads/master
| 2021-04-09T17:45:56.369908
| 2016-10-28T08:32:26
| 2016-10-28T08:32:26
| 28,734,117
| 2
| 0
| null | 2015-01-03T03:45:23
| 2015-01-03T03:45:22
| null |
UTF-8
|
Python
| false
| false
| 1,298
|
py
|
#
# Set up realistic tropical temperature and moisture profiles
# and compute radiative fluxes
#
from numpy import *
import climt_lite
#--- instantiate radiation module
r = climt_lite.radiation()
#--- initialise T,q
# Surface temperature
Ts = 273.15 + 30.
# Strospheric temp
Tst = 273.15 - 80.
# Surface pressure
ps = 1000.
# Equispaced pressure levels
p = ( arange(r.nlev)+ 0.5 )/r.nlev * ps
# Return moist adiabat with 70% rel hum
(T,q) = climt_lite.thermodyn.moistadiabat(p, Ts, Tst, 1.)
cldf = q*0.
clwp = q*0.
cldf[len(cldf)/3] = 0.5
clwp[len(cldf)/3] = 100.
#--- compute radiative fluxes and heating rates
r(p=p, ps=ps, T=T, Ts=Ts, q=q, cldf=cldf, clwp=clwp)
if 'SwToa' in r.State.keys(): print r['SwToa'],r['LwToa'],r['SwSrf'],r['LwSrf']
print r['SwToaCf'],r['LwToaCf'],(r['solin']-r['SwToa'])/r['solin']
#--- print out results
lwflx = r['lwflx']
swflx = r['swflx']
lwhr = r['lwhr']
swhr = r['swhr']
q = r['q']
T = r['T']
z=climt_lite.thermodyn.z(p, T, p0=ps)/1000.
print "lev z p T q lwflx lwhr swflx swhr "
for i in range(r['nlev']):
print "%3i %6.1f %6.1f %6.1f %6.2f %10.2f %6.2f %10.2f %6.2f" % \
(i, z[i], p[i], T[i]-273.15, q[i], lwflx[i], lwhr[i], swflx[i], swhr[i])
|
[
"rca@misu046.misu.su.se"
] |
rca@misu046.misu.su.se
|
b54f081a9d6b7446d1e5993745d42b278ed93235
|
d9bfc35e34659220c5695360a4282293ad2ac74a
|
/flask_demo/get_post_demo/venv/bin/python-config
|
922fdf1460d00dec2a904253b0e13926a33a7269
|
[] |
no_license
|
Carrie999/practiceHtmlDemo
|
c9e387b18f8b6ad9736631f104332445175a3a2e
|
3e59843e2a15233c9ad086f8aff4db83bdfd886f
|
refs/heads/master
| 2023-02-20T04:25:20.518659
| 2018-08-25T08:51:38
| 2018-08-25T08:51:38
| 128,219,772
| 3
| 0
| null | 2023-02-15T17:52:52
| 2018-04-05T14:41:41
|
Python
|
UTF-8
|
Python
| false
| false
| 2,357
|
#!/Users/orion/Desktop/get_post_demo/venv/bin/python
import sys
import getopt
import sysconfig
valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags',
'ldflags', 'help']
if sys.version_info >= (3, 2):
valid_opts.insert(-1, 'extension-suffix')
valid_opts.append('abiflags')
if sys.version_info >= (3, 3):
valid_opts.append('configdir')
def exit_with_usage(code=1):
sys.stderr.write("Usage: {0} [{1}]\n".format(
sys.argv[0], '|'.join('--'+opt for opt in valid_opts)))
sys.exit(code)
try:
opts, args = getopt.getopt(sys.argv[1:], '', valid_opts)
except getopt.error:
exit_with_usage()
if not opts:
exit_with_usage()
pyver = sysconfig.get_config_var('VERSION')
getvar = sysconfig.get_config_var
opt_flags = [flag for (flag, val) in opts]
if '--help' in opt_flags:
exit_with_usage(code=0)
for opt in opt_flags:
if opt == '--prefix':
print(sysconfig.get_config_var('prefix'))
elif opt == '--exec-prefix':
print(sysconfig.get_config_var('exec_prefix'))
elif opt in ('--includes', '--cflags'):
flags = ['-I' + sysconfig.get_path('include'),
'-I' + sysconfig.get_path('platinclude')]
if opt == '--cflags':
flags.extend(getvar('CFLAGS').split())
print(' '.join(flags))
elif opt in ('--libs', '--ldflags'):
abiflags = getattr(sys, 'abiflags', '')
libs = ['-lpython' + pyver + abiflags]
libs += getvar('LIBS').split()
libs += getvar('SYSLIBS').split()
# add the prefix/lib/pythonX.Y/config dir, but only if there is no
# shared library in prefix/lib/.
if opt == '--ldflags':
if not getvar('Py_ENABLE_SHARED'):
libs.insert(0, '-L' + getvar('LIBPL'))
if not getvar('PYTHONFRAMEWORK'):
libs.extend(getvar('LINKFORSHARED').split())
print(' '.join(libs))
elif opt == '--extension-suffix':
ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
if ext_suffix is None:
ext_suffix = sysconfig.get_config_var('SO')
print(ext_suffix)
elif opt == '--abiflags':
if not getattr(sys, 'abiflags', None):
exit_with_usage()
print(sys.abiflags)
elif opt == '--configdir':
print(sysconfig.get_config_var('LIBPL'))
|
[
"pangyajing@ainirobot.com"
] |
pangyajing@ainirobot.com
|
|
91991f5a8611d5ea0c34e7e190b6f2f689575618
|
e35c318b38e0d359f4c9597d7b6f62f48475b3ec
|
/tests/common/test_utils_logger.py
|
ec51c65f3b1d9e854a10ab5f49f6914cdf5717d1
|
[
"MIT"
] |
permissive
|
jongwonKim-1997/bayeso
|
fddca24c98ef90fdc74f24bcc35040ab064ff5e3
|
f6f290c5ed33340beaf8dfa27a71d1dbce121e33
|
refs/heads/main
| 2023-05-10T12:25:04.353385
| 2021-04-19T00:32:25
| 2021-04-19T00:32:25
| 375,925,113
| 0
| 0
|
MIT
| 2021-06-11T06:21:42
| 2021-06-11T06:21:41
| null |
UTF-8
|
Python
| false
| false
| 6,730
|
py
|
#
# author: Jungtaek Kim (jtkim@postech.ac.kr)
# last updated: September 24, 2020
#
"""test_utils_logger"""
import logging
import pytest
import numpy as np
from bayeso.utils import utils_logger as package_target
def test_get_logger_typing():
annos = package_target.get_logger.__annotations__
assert annos['str_name'] == str
assert annos['return'] == logging.Logger
def test_get_logger():
with pytest.raises(AssertionError) as error:
package_target.get_logger(123)
with pytest.raises(AssertionError) as error:
package_target.get_logger(12.3)
logger = package_target.get_logger('abc')
assert type(logger) == logging.Logger
def test_get_str_array_1d_typing():
annos = package_target.get_str_array_1d.__annotations__
assert annos['arr'] == np.ndarray
assert annos['return'] == str
def test_get_str_array_1d():
with pytest.raises(AssertionError) as error:
package_target.get_str_array_1d(123)
with pytest.raises(AssertionError) as error:
package_target.get_str_array_1d(12.3)
with pytest.raises(AssertionError) as error:
package_target.get_str_array_1d(np.zeros((10, 2)))
with pytest.raises(AssertionError) as error:
package_target.get_str_array_1d(np.zeros((10, 2, 2)))
str_ = package_target.get_str_array_1d(np.array([1, 2, 3]))
print(str_)
assert str_ == '[1, 2, 3]'
str_ = package_target.get_str_array_1d(np.array([1.1, 2.5, 3.0]))
print(str_)
assert str_ == '[1.100, 2.500, 3.000]'
def test_get_str_array_2d_typing():
annos = package_target.get_str_array_2d.__annotations__
assert annos['arr'] == np.ndarray
assert annos['return'] == str
def test_get_str_array_2d():
with pytest.raises(AssertionError) as error:
package_target.get_str_array_2d(123)
with pytest.raises(AssertionError) as error:
package_target.get_str_array_2d(12.3)
with pytest.raises(AssertionError) as error:
package_target.get_str_array_2d(np.zeros(10))
with pytest.raises(AssertionError) as error:
package_target.get_str_array_2d(np.zeros((10, 2, 2)))
str_ = package_target.get_str_array_2d(np.array([[1, 2, 3], [2, 2, 2]]))
print(str_)
assert str_ == '[[1, 2, 3],\n[2, 2, 2]]'
str_ = package_target.get_str_array_2d(np.array([[1.1, 2.2, 3.33], [2.2, 2.4, 2.9]]))
print(str_)
assert str_ == '[[1.100, 2.200, 3.330],\n[2.200, 2.400, 2.900]]'
def test_get_str_array_3d_typing():
annos = package_target.get_str_array_3d.__annotations__
assert annos['arr'] == np.ndarray
assert annos['return'] == str
def test_get_str_array_3d():
with pytest.raises(AssertionError) as error:
package_target.get_str_array_3d(123)
with pytest.raises(AssertionError) as error:
package_target.get_str_array_3d(12.3)
with pytest.raises(AssertionError) as error:
package_target.get_str_array_3d(np.zeros(10))
with pytest.raises(AssertionError) as error:
package_target.get_str_array_3d(np.zeros((10, 2)))
str_ = package_target.get_str_array_3d(np.array([[[1, 2, 3], [2, 2, 2]], [[1, 2, 3], [2, 2, 2]]]))
print(str_)
assert str_ == '[[[1, 2, 3],\n[2, 2, 2]],\n[[1, 2, 3],\n[2, 2, 2]]]'
str_ = package_target.get_str_array_3d(np.array([[[1.1, 2.2, 3.33], [2.2, 2.4, 2.9]], [[1.1, 2.2, 3.33], [2.2, 2.4, 2.9]]]))
print(str_)
assert str_ == '[[[1.100, 2.200, 3.330],\n[2.200, 2.400, 2.900]],\n[[1.100, 2.200, 3.330],\n[2.200, 2.400, 2.900]]]'
def test_get_str_array_typing():
annos = package_target.get_str_array.__annotations__
assert annos['arr'] == np.ndarray
assert annos['return'] == str
def test_get_str_array():
with pytest.raises(AssertionError) as error:
package_target.get_str_array(123)
with pytest.raises(AssertionError) as error:
package_target.get_str_array(12.3)
str_ = package_target.get_str_array(np.array([1, 2, 3]))
print(str_)
assert str_ == '[1, 2, 3]'
str_ = package_target.get_str_array(np.array([1.1, 2.5, 3.0]))
print(str_)
assert str_ == '[1.100, 2.500, 3.000]'
str_ = package_target.get_str_array(np.array([[1, 2, 3], [2, 2, 2]]))
print(str_)
assert str_ == '[[1, 2, 3],\n[2, 2, 2]]'
str_ = package_target.get_str_array(np.array([[1.1, 2.2, 3.33], [2.2, 2.4, 2.9]]))
print(str_)
assert str_ == '[[1.100, 2.200, 3.330],\n[2.200, 2.400, 2.900]]'
str_ = package_target.get_str_array(np.array([[[1, 2, 3], [2, 2, 2]], [[1, 2, 3], [2, 2, 2]]]))
print(str_)
assert str_ == '[[[1, 2, 3],\n[2, 2, 2]],\n[[1, 2, 3],\n[2, 2, 2]]]'
str_ = package_target.get_str_array(np.array([[[1.1, 2.2, 3.33], [2.2, 2.4, 2.9]], [[1.1, 2.2, 3.33], [2.2, 2.4, 2.9]]]))
print(str_)
assert str_ == '[[[1.100, 2.200, 3.330],\n[2.200, 2.400, 2.900]],\n[[1.100, 2.200, 3.330],\n[2.200, 2.400, 2.900]]]'
def test_get_str_hyps_typing():
annos = package_target.get_str_hyps.__annotations__
assert annos['hyps'] == dict
assert annos['return'] == str
def test_get_str_hyps():
with pytest.raises(AssertionError) as error:
package_target.get_str_hyps(123)
with pytest.raises(AssertionError) as error:
package_target.get_str_hyps(12.3)
with pytest.raises(AssertionError) as error:
package_target.get_str_hyps('abc')
with pytest.raises(AssertionError) as error:
package_target.get_str_hyps(np.zeros(3))
hyps = {'signal': 1.0, 'noise': 1e-4, 'lengthscales': np.array([1.0, 2.0])}
str_ = package_target.get_str_hyps(hyps)
print(str_)
list_truths = [
"{'signal': 1.000, 'noise': 0.000, 'lengthscales': [1.000, 2.000]}",
"{'signal': 1.000, 'lengthscales': [1.000, 2.000], 'noise': 0.000}",
"{'lengthscales': [1.000, 2.000], 'signal': 1.000, 'noise': 0.000}",
"{'lengthscales': [1.000, 2.000], 'noise': 0.000, 'signal': 1.000}",
"{'noise': 0.000, 'signal': 1.000, 'lengthscales': [1.000, 2.000]}",
"{'noise': 0.000, 'lengthscales': [1.000, 2.000], 'signal': 1.000}",
]
assert str_ in list_truths
hyps = {'signal': 1, 'noise': 1e-3, 'lengthscales': np.array([1.0, 2.0])}
str_ = package_target.get_str_hyps(hyps)
print(str_)
list_truths = [
"{'signal': 1, 'noise': 0.001, 'lengthscales': [1.000, 2.000]}",
"{'signal': 1, 'lengthscales': [1.000, 2.000], 'noise': 0.001}",
"{'lengthscales': [1.000, 2.000], 'signal': 1, 'noise': 0.001}",
"{'lengthscales': [1.000, 2.000], 'noise': 0.001, 'signal': 1}",
"{'noise': 0.001, 'signal': 1, 'lengthscales': [1.000, 2.000]}",
"{'noise': 0.001, 'lengthscales': [1.000, 2.000], 'signal': 1}",
]
assert str_ in list_truths
|
[
"jtkim@postech.ac.kr"
] |
jtkim@postech.ac.kr
|
b1bfad68ea410fdf790ec776a13e25ffff1072e4
|
d9ec3e1a75df988a4ec905436b9a8db1ebf3cb97
|
/school/views.py
|
30210af4aa751831b654addabe142e8702e08bea
|
[] |
no_license
|
shivamrvgupta/JBEHS
|
1a7339b42118e0355abb2b49515f443ec9658b27
|
06e2e84a56f6a880b107d4fb5f5946744f92d797
|
refs/heads/master
| 2022-12-15T21:53:21.081889
| 2020-09-14T14:21:30
| 2020-09-14T14:21:30
| 295,432,337
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,325
|
py
|
from django.shortcuts import render, redirect, HttpResponseRedirect, get_object_or_404
from django.contrib import messages
from .forms import SchoolRegistration, SchoolUpdate
from .models import School
from django.contrib.auth.decorators import login_required
# Create your views here.
"""
School Operations
"""
@login_required(login_url='/accounts/login/')
def school_registeration(request):
if request.method == 'POST':
form = SchoolRegistration(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
school_code = form.cleaned_data['school_code']
if School.objects.filter(school_code=school_code).exists():
messages.error(request, 'Student code already registered')
return redirect('add_school')
else:
form.save()
return redirect('show_school')
else:
form = SchoolRegistration()
school = School.objects.all()
return render(request, 'school/add.html', {'form': form, 'school': school})
@login_required(login_url='/accounts/login/')
def update_data(request, id):
if request.method == 'POST':
school = School.objects.get(pk=id)
form = SchoolUpdate(request.POST, instance=school)
print('user --- {}'.format(school))
if form.is_valid():
form.save()
print('valid --- {}'.format(form.is_valid))
return redirect('show_school')
else:
print('invalid')
return redirect('update_school')
print("didn't enter ")
else:
school = School.objects.get(pk=id)
form = SchoolUpdate(instance=school)
return render(request, 'school/update.html', {'form': form, 'school': school})
@login_required(login_url='/accounts/login/')
def show_school(request):
school = School.objects.all()
return render(request, 'school/show.html', {'school': school})
@login_required(login_url='/accounts/login/')
def delete_data(request, id):
if request.method == 'POST':
user = School.objects.get(pk=id)
user.delete()
return HttpResponseRedirect('/')
def view(request, id):
school = get_object_or_404(School, pk=id)
context = {
'school': school
}
return render(request, 'school/view.html', context)
|
[
"shivamgupta@Shivams-Mac-mini.local"
] |
shivamgupta@Shivams-Mac-mini.local
|
601df3ddcbd225d79671f80264b633e771676761
|
5cfbe2f43cc50930d1116992be542c50f297c7f8
|
/mysite/settings.py
|
11e9a043d9f57bb0ea7c9fa4244eecab60fd4c4b
|
[] |
no_license
|
NataliTomilina/my-ferst-blog
|
e059fa6b562a62725bfc9168fa9a3685f2dfcd9d
|
7e75be17a66419dec66d36288d9e058d163cd96d
|
refs/heads/master
| 2020-03-21T13:03:02.766961
| 2018-06-25T11:16:42
| 2018-06-25T11:16:42
| 137,742,059
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,201
|
py
|
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'sn79h6!7qaqvgg)41)+@1y@xz$h&l@j*sunb=md-ia^f%ta$bi'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', 'n.tomilina.pythonanywhere.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'ru-ru'
TIME_ZONE = 'Europe/Moscow'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
|
[
"tomilina.95@mail.ru"
] |
tomilina.95@mail.ru
|
f2db845f6ed0455eb72a111058ae787634caf967
|
181e9cc9cf4e52fcc6e9979890cc5b41e7beb756
|
/Module 1/02_Codes/miscellaneous/4-TenSecondCameraCapture.py
|
ffe0427cfa69b339ad2ddf078ae4c70f2d0dfbde
|
[
"MIT"
] |
permissive
|
PacktPublishing/OpenCV-Computer-Vision-Projects-with-Python
|
ace8576dce8d5f5db6992b3e5880a717996f78cc
|
45a9c695e5bb29fa3354487e52f29a565d700d5c
|
refs/heads/master
| 2023-02-09T14:10:42.767047
| 2023-01-30T09:02:09
| 2023-01-30T09:02:09
| 71,112,659
| 96
| 72
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 515
|
py
|
import cv2
cameraCapture = cv2.VideoCapture(0)
fps = 30 # an assumption
size = (int(cameraCapture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),
int(cameraCapture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
videoWriter = cv2.VideoWriter(
'MyOutputVid.avi', cv2.cv.CV_FOURCC('I','4','2','0'), fps, size)
success, frame = cameraCapture.read()
numFramesRemaining = 10 * fps - 1
while success and numFramesRemaining > 0:
videoWriter.write(frame)
success, frame = cameraCapture.read()
numFramesRemaining -= 1
|
[
"prasadr@packtpub.com"
] |
prasadr@packtpub.com
|
a256b033d5114fc08cddeaa6625a4ef957040c9e
|
c0d75e3f8c0383f528fbca434414185aa77b1de3
|
/ceyrek_altin.py
|
6c2390431f87d547088bd17a9b52c0f014e19e7b
|
[] |
no_license
|
borayuret/yfscraper
|
9339c9d5215f1a10f27aac21a9f368bbdb119604
|
ad57f7e2826936473dad78ac4b729fadeb4d02ba
|
refs/heads/main
| 2023-03-31T23:49:17.951674
| 2021-04-03T10:05:59
| 2021-04-03T10:05:59
| 347,348,393
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 382
|
py
|
# hurriyet.com.tr den dolar fiyatı çekelim.
import requests
from bs4 import BeautifulSoup
hisse_url = "https://bigpara.hurriyet.com.tr/altin/"
html_kod = requests.get(hisse_url)
soup = BeautifulSoup(html_kod.content, 'lxml')
bilgi_bar = soup.find('div', class_='dovizBar mBot10').find_all('a')[1].find_all('span')[6].find('span', class_='value').get_text()
print(bilgi_bar)
|
[
"bora.yuret@bilgeadam.com"
] |
bora.yuret@bilgeadam.com
|
82753cf6b64dc98cdf65535e4818c0755652d67d
|
8ac75ee9dcb850c966a05a72bdfaf34fcf35965d
|
/Company_ques/Avg.py
|
066f2fbc121c96c00299bf439e3ccc92c855e13d
|
[] |
no_license
|
mathankrish/Python-Programs
|
3f7257ffa3a7084239dcc16eaf8bb7e534323102
|
2f76e850c92d3126b26007805df03bffd603fcdf
|
refs/heads/master
| 2020-05-01T04:27:00.943545
| 2019-10-07T18:57:41
| 2019-10-07T18:57:41
| 177,274,558
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 252
|
py
|
# Average of two numbers
def Avg(num1, num2):
Total = num1 + num2
average = Total / 2
return average
num1 = int(input())
num2 = int(input())
print("The average of {0} and {1} is {00} ".format(num1, num2, Avg(num1, num2)))
|
[
"noreply@github.com"
] |
noreply@github.com
|
49cc7ab24fcf653315ed8b0a0c768e7420905965
|
4a2eac368e3e2216b0cd1dd70224da3ca4ee7c5e
|
/SecretManager/owlbot.py
|
50c7c9bb3fb0bdd3f2138665e345cd50407ebd4c
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
googleapis/google-cloud-php
|
856a940eee158eafa6f2443f8d61813779216429
|
ad50f749431287e7074279e2b4fa32d6d6c2c952
|
refs/heads/main
| 2023-09-06T05:48:31.609502
| 2023-09-05T20:27:34
| 2023-09-05T20:27:34
| 43,642,389
| 642
| 330
|
Apache-2.0
| 2023-09-13T22:39:27
| 2015-10-04T16:09:46
|
PHP
|
UTF-8
|
Python
| false
| false
| 1,871
|
py
|
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This script is used to synthesize generated parts of this library."""
import logging
from pathlib import Path
import subprocess
import synthtool as s
from synthtool.languages import php
from synthtool import _tracked_paths
logging.basicConfig(level=logging.DEBUG)
src = Path(f"../{php.STAGING_DIR}/SecretManager").resolve()
dest = Path().resolve()
# Added so that we can pass copy_excludes in the owlbot_main() call
_tracked_paths.add(src)
php.owlbot_main(src=src, dest=dest)
# Change the wording for the deprecation warning.
s.replace(
'src/*/*_*.php',
r'will be removed in the next major release',
'will be removed in a future release')
### [START] protoc backwards compatibility fixes
# roll back to private properties.
s.replace(
"src/**/V*/**/*.php",
r"Generated from protobuf field ([^\n]{0,})\n\s{5}\*/\n\s{4}protected \$",
r"""Generated from protobuf field \1
*/
private $""")
# Replace "Unwrapped" with "Value" for method names.
s.replace(
"src/**/V*/**/*.php",
r"public function ([s|g]\w{3,})Unwrapped",
r"public function \1Value"
)
### [END] protoc backwards compatibility fixes
# fix relative cloud.google.com links
s.replace(
"src/**/V*/**/*.php",
r"(.{0,})\]\((/.{0,})\)",
r"\1](https://cloud.google.com\2)"
)
|
[
"noreply@github.com"
] |
noreply@github.com
|
38e91d4d664c61c222b744872c51c349b5c6d785
|
c74a140b434941e05978582b41ca6cdcc5ea8989
|
/leetcode/editor/cn/[剑指 Offer 22]链表中倒数第k个节点 LCOF.py
|
c2a1ddadf9ff231c1947dbe047c4ab502521c31c
|
[] |
no_license
|
Switch-vov/leet_code
|
61e5ff781aba923971e294d9210c70088c6340a2
|
c9dd9c1bf0213b12c499fbeccada5d0fd758fce1
|
refs/heads/master
| 2023-07-29T15:32:06.130178
| 2021-09-12T11:52:38
| 2021-09-12T11:52:38
| 396,201,812
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 870
|
py
|
# English description is not available for the problem. Please switch to Chinese
# . Related Topics 链表 双指针
# 👍 220 👎 0
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
dummy, dummy.next = ListNode(0), head
back = front = dummy
while k > 0:
front, k = front.next, k - 1
while front:
back, front = back.next, front.next
return back
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
solution: Solution = Solution()
|
[
"switchvov@163.com"
] |
switchvov@163.com
|
380e3c97f6cccfca0561f610fa9bacc68b1ea1d2
|
4f50a8a320e89fa60147ae21949168f9929a24ea
|
/wafweb/wafwebapp/classes/neo_classes/neoquery.py
|
f65b3097df5ad75b7eb91396b9c09fcb95da2ac8
|
[] |
no_license
|
hubaym/waf
|
78732b3d42054b0bc608912a37bed3e78bd750f0
|
a51ec7331c0c80841de3a52b325fb42708e38a6d
|
refs/heads/master
| 2021-04-15T03:52:02.586070
| 2016-08-24T22:18:15
| 2016-08-24T22:18:15
| 65,689,380
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,883
|
py
|
from neo4jrestclient import client
import classes.constant.wafconnection as con
from neo4jrestclient.client import GraphDatabase
from classes.constant.waflog import WafLog
import classes.utils.status as status
class NeoQuery():
def __init__(self):
self.db = GraphDatabase(con.NEO_HOST,
username=con.NEO_USER,
password=con.NEO_PSW)
def getGeoByID(self,id):
q1 = '''pgid:{0}'''.format(id)
q = '''
MATCH (n:geo{''' + q1+ '''})
RETURN n'''
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info(" {0} not found".format(id))
return None
return result[0][0]
def getCountryByCode(self,country_code):
q1 = '''code:"{0}"'''.format(country_code)
q = '''
MATCH (n:geo_country{''' + q1+ '''})
RETURN n'''
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info("country {0} not found".format(country_code))
return None
return result[0][0]
def getNodeByNameAndType(self,name, type):
q1 = '''name:"{0}"'''.format(name)
q = '''
MATCH (n:{0}{''' + q1+ '''})
RETURN n'''.format(type)
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info("name {0} not found".format(name))
return None
return result[0][0]
def getUserById(self,userid):
q1 = '''pgid:"{0}"'''.format(userid)
q = '''
MATCH (n:user{''' + q1+ '''})
RETURN n'''
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info("userid {0} not found".format(userid))
return None
return result[0][0]
def getCountryByName( self, name):
q1 = '''name:"{0}"'''.format(name)
q = '''
MATCH (n:geo_country{''' + q1+ '''})
RETURN n'''
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info("country {0} not found".format(name))
return None
return result[0][0]
def getProvinceByName( self, name):
q1 = '''name:"{0}"'''.format(name)
q = '''
MATCH (n:geo_province{''' + q1+ '''})
RETURN n'''
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info("country {0} not found".format(name))
return None
return result[0][0]
def getCityByName(self, name):
q1 = '''name:"{0}"'''.format(name)
q = '''
MATCH (n:geo_city{''' + q1+ '''})
RETURN n'''
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info("city {0} not found".format(name))
return None
return result[0][0]
def getContinentByCode(self, continent):
q1 = '''code:"{0}"'''.format(continent)
q = '''
MATCH (n:geo_continent{''' + q1+ '''})
RETURN n'''
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info("continent {0} not found".format(continent))
return None
return result[0][0]
def getRegionByCode(self, region):
q1 = '''code:"{0}"'''.format(region)
q = '''
MATCH (n:geo_region:{''' + q1+ '''})
RETURN n'''
result = self.db.query(q, returns=(client.Node))
if len(result) == 0:
WafLog().neologger.info("region {0} not found".format(region))
return None
return result[0][0]
def isNeighbourExists(self, country_code_1, country_code_2):
q1 = '''code:"{0}"'''.format(country_code_1)
q2 = '''code:"{0}"'''.format(country_code_2)
q = '''
MATCH (n:geo_country{''' + q1+ '''}) -[r:neighbour]-
(m:geo_country{''' + q2+'''})
RETURN r'''
result = self.db.query(q, returns=(client.Relationship))
if len(result) == 0:
return False
else:
return True
def deleteOffers(self):
q = """
MATCH (n:offer) detach delete n"""
self.db.query(q)
WafLog().neologger.info("db is deleted")
def createIndexOnCountry(self):
q ="""CREATE INDEX ON :geo_country(country_code) """
self.db.query(q)
WafLog().neologger.info("index is created on Countries")
def createIndexOnCity(self):
q ="""CREATE INDEX ON :geo_city(name) """
self.db.query(q)
WafLog().neologger.info("index is created on cities")
def createIndexOnGeo(self):
q ="""CREATE INDEX ON :geo(pgid) """
self.db.query(q)
WafLog().neologger.info("index is created on geo, pgid")
def createIndexOnProvince(self):
q ="""CREATE INDEX ON :geo_province(name) """
self.db.query(q)
WafLog().neologger.info("index is created on geo_province, name")
def deleteDB(self):
q = """
MATCH (n) detach delete n"""
self.db.query(q)
WafLog().neologger.info("db is deleted")
def getAllCityID(self):
q = """
MATCH (n:geo_city) RETURN ID(n)"""
result = self.db.query(q)
return(result)
def getOffersAndUsers(self):
q = """
MATCH (o:offer) -[]-
WHERE o.status = 'IN_NEO_EMAIL_NOT_DONE'
RETURN ID(n)"""
result = self.db.query(q)
return(result)
if __name__ == "__main__":
neoq = NeoQuery()
WafLog().neologger.info (neoq.getGeoByID(50024))
|
[
"hubaymarton@Hubay-MacBook-Air.local"
] |
hubaymarton@Hubay-MacBook-Air.local
|
ad2fc3768caa165399299cbe9e9557c3e1406c60
|
c4cba3a520eccfb60350cfd8bead6a434061bb4d
|
/projects_lpthw/gothonweb/gothonweb/app.py
|
179976e2710ae3eff790a6d2a4498bebefa832ae
|
[] |
no_license
|
thedoubl3j/python_playground
|
bb119e971e5a8d5e5118a6c788d8f140f8a8fb97
|
b25cfdf3bbe337b46fbf350e785b8d13e129a6f6
|
refs/heads/master
| 2021-12-15T03:38:27.462891
| 2021-12-13T21:48:04
| 2021-12-13T21:48:04
| 128,975,263
| 0
| 1
| null | 2019-01-22T17:12:03
| 2018-04-10T18:02:37
|
Python
|
UTF-8
|
Python
| false
| false
| 241
|
py
|
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/")
def index():
greeting = "Hello World"
return render_template('index.html', greeting=greeting)
if __name__ == "__main__":
app.run()
|
[
"jljacks93@gmail.com"
] |
jljacks93@gmail.com
|
060e1ed423ff462c6643f90cb80ce36b0a84492e
|
af69291cc1c9000aff3ac754d8dcc053abc278bc
|
/old_versions/0.7.1/example.py
|
7e97b467ca59815895092a2e48462c2bbf58c525
|
[] |
no_license
|
dcbmariano/BioSVD-GA
|
ae06e22a69770dfa19e9737c6a93e2133665ace4
|
a8a1c11790a528387bfffeefa400ad08b47e3d55
|
refs/heads/master
| 2021-01-12T19:52:56.197803
| 2016-08-24T13:05:15
| 2016-08-24T13:05:15
| 44,193,085
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,012
|
py
|
#!/usr/bin/python
# Program: biosvd.py
# Function: Implementa o metodo de svd para classificacao de proteinas
# Description: inclui: delaunay.py e sort.py - Por enquanto estamos limitado a 23 cores no plot assim so podemos ter 23 familas diferentes. Isso sera revisado(Por Thiago)
# Author: Thiago da Silva Correia, Diego Mariano, Jose Renato Barroso, Raquel Cardoso de Melo-Minardi
# Version: 7.01
# Hierarquia do programa ******************************************
#
# ./ Diretorio raiz
# biosvd.py Script principal
# README.txt Contem instruoes de execucao
# example Diretorio onde ficaram armazeados dados para testes
# results Diretorio onde deverao ser salvos os outputs
# IMPORTS
import BioSVD
from mpl_toolkits.mplot3d import Axes3D
from numpy import linalg as LA
from Bio import SeqIO
import matplotlib.pyplot as plt
import numpy as np
import time
import sys
import os
os.system("clear")
try:
os.mkdir("results")
except:
print ""
# Controle do tempo de exucucao
ini = time.time()
# Parametros e help
i = 2
nomePlotClusterizacao = ''
nomePlotPosto = ''
opcao_entrada = sys.argv[1]
if opcao_entrada == '-B':
kfold = int(sys.argv[3] )
while opcao_entrada == '-A' and i < (len(sys.argv)):
# m = modelo
if( sys.argv[i] == '-m'):
FileModelo = sys.argv[i+1]
# mt = modelo - arquivo tabular
if( sys.argv[i] == '-mt'):
print "asdasdas"
FileModeloTabular = sys.argv[i+1]
# q = query
if( sys.argv[i] == '-q'):
FileQuery = sys.argv[i+1]
# qt = query - arquivo tabular
if( sys.argv[i] == '-qt'):
FileQueryTabular = sys.argv[i+1]
if( sys.argv[i] == '-g'):
nomePlotClusterizacao = sys.argv[i+1]
if( sys.argv[i] == '-p'):
nomePlotPosto = sys.argv[i+1]
# Help
if sys.argv[i] == '-h' or sys.argv[i] == '--help':
print "\n*** BIOSVD ***\nSyntax: \n\tpython biosvd.py \n\t\t-m [model] \n\t\t-mt [model tabular file] \n\t\t-q [query] \n\t\t-qt [query tabular file - optional]\n"
sys.exit()
i = i+2
# Valida se nenhum parametro for enviado
if i == 1:
print "\n*** BIOSVD ***\nSyntax: \n\tpython biosvd.py \n\t\t-m [model] \n\t\t-mt [model tabular file] \n\t\t-q [query] \n\t\t-qt [query tabular file - optional]\n"
sys.exit()
# Aqui comeca a magia
print "\n*******************************"
print " *** BIOSVD ***"
print "*******************************\n"
hashTabModelo, FamiliasModelo = CriarHashTab(FileModeloTabular)
hashTabQuery, FamiliasQuery = bio.CriarHashTab(FileQueryTabular)
sys.exit()
print "Parsing files"
sequenciasModelo = list(SeqIO.parse( open(FileModelo, "r") , "fasta"))
sequenciasQuery = list(SeqIO.parse( open(FileQuery, "r") , "fasta"))
print "Model number sequence: %d \nQuery number sequence: %d" %( len(sequenciasModelo), len(sequenciasQuery) )
print "Sorting Model Seq"
NumFamiliasModelo ,FamiliasModelo, DistribuicaFamiliasModelo , sequenciasModelo = bio.Sort( sequenciasModelo, hashTabModelo,opcao_entrada )
numeroSeqModel = len(sequenciasModelo)
numeroSeqQuery = len(sequenciasQuery)
NumroDeSequencias = numeroSeqModel + numeroSeqQuery
#Jutando todas as sequencias numa so lista
allSequences = []
for i in sequenciasModelo:
allSequences.append(i)
for i in sequenciasQuery:
allSequences.append(i)
#Preenchendo matriz de frequencia
matFrequencia = bio.Kmer( allSequences ,3 )
print "Length of the matrix: ",matFrequencia.shape
#SlateBlue, MediumVioletRed, DarkOrchid,DeepSkyBlue,DarkRed,OrangeRed,Teal,
#Lime,DarkGoldenrod,PaleTurquoise,Plum,LightCoral,CadetBlue,DarkSeaGreen,PaleGoldenrod,RosyBrown
Cores = ['b', 'g', 'r', 'c','m','y', 'k', 'w', '#6A5ACD', '#C71585','#9932CC','#8B0000','#FF4500',
'#008B8B','#00FF00','#B8860B','#E0FFFF','#DDA0DD' ,'#F08080' ,'#5F9EA0','#8FBC8F','#EEE8AA','#BC8F8F']
print "SVD"
aux ,T= bio.SVD( matFrequencia, 3 , nomePlotPosto )
print "Creating graphic 3D"
fig1 = plt.figure()
ax = fig1.add_subplot(111, projection='3d')
F = {}
tF = {}
IDCor = 0
temp = []
print "Model"
for i in range(len(DistribuicaFamiliasModelo)):
if i == 0:#Primeira Familia Modelo
x = aux[0:1,0:int(DistribuicaFamiliasModelo[0]) ]
y = aux[1:2,0:int(DistribuicaFamiliasModelo[0]) ]
z = aux[2:3,0:int(DistribuicaFamiliasModelo[0]) ]
F[FamiliasModelo[i]] = "0:"+str(int(DistribuicaFamiliasModelo[0]) )
elif(i == len(DistribuicaFamiliasModelo)-1 ):#Ultima familia Modelo
x = aux[0:1,int(DistribuicaFamiliasModelo[ -1]) : numeroSeqModel ]
y = aux[1:2,int(DistribuicaFamiliasModelo[ -1]) : numeroSeqModel ]
z = aux[2:3,int(DistribuicaFamiliasModelo[ -1]) : numeroSeqModel ]
F[FamiliasModelo[i]] = str(int(DistribuicaFamiliasModelo[i-1]) ) + ":" + str(numeroSeqModel)
else:
x = aux[0:1,int(DistribuicaFamiliasModelo[i-1]) :int(DistribuicaFamiliasModelo[i]) ]
y = aux[1:2,int(DistribuicaFamiliasModelo[i-1]) :int(DistribuicaFamiliasModelo[i]) ]
z = aux[2:3,int(DistribuicaFamiliasModelo[i-1]) :int(DistribuicaFamiliasModelo[i]) ]
F[FamiliasModelo[i]] = str(int(DistribuicaFamiliasModelo[i-1]))+":"+str(int(DistribuicaFamiliasModelo[i]))
ax.scatter(x, y, z, c=Cores[IDCor], marker='o', label=FamiliasModelo[IDCor], s = 100 )
IDCor = IDCor +1
temp.append(FamiliasModelo[i])
temp.append(str(F[FamiliasModelo[i]]))
print "Query"
tx = aux[0:1, numeroSeqModel +1: ]
ty = aux[1:2, numeroSeqModel +1: ]
tz = aux[2:3, numeroSeqModel +1: ]
tF['Query family'] = str(numeroSeqModel+1)+":"+str(NumroDeSequencias )
ax.scatter(tx, ty, tz, c='#000000', marker='*',label='Query', s = 100 )
# Criando figura
plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=10, bbox_to_anchor=(0, 0))
if(len(nomePlotClusterizacao) > 0):
fig1.savefig('results/'+nomePlotClusterizacao+'.png', dpi=300)
plt.close(fig1)
else:
plt.show()
# Calculando delauney
print "Calculing delaunay"
bio.delaunay( temp, aux , sequenciasQuery, hashTabQuery,opcao_entrada)
print "| Running validation | %s" %FileQueryTabular
A = bio.Validation( hashTabQuery, sequenciasQuery, opcao_entrada)
# Fim do tempo de execucao
fim = time.time()
print "Time: ", fim-ini
|
[
"diogohenks@hotmail.com"
] |
diogohenks@hotmail.com
|
855d10a127d4561780c68cd68a89ac02f14a8a10
|
d79778a02e752879b337c9bfe567617e910befb9
|
/model/all_data_representation.py
|
9c2ba3323b47c526965496e37085a4f489f9c9e8
|
[] |
no_license
|
SubrataTech/fulfil_data_loader
|
fb38e47872c78976e4928ed2b47f650917b566d0
|
33418bf3901146df38fe38950cebd2a7bc57b0ce
|
refs/heads/master
| 2022-09-28T21:55:42.047813
| 2019-11-17T21:00:56
| 2019-11-17T21:00:56
| 222,309,372
| 0
| 0
| null | 2022-09-16T18:12:56
| 2019-11-17T20:43:07
|
HTML
|
UTF-8
|
Python
| false
| false
| 308
|
py
|
from configuration_file import db
class UserTable(db.Model):
__tablename__ = 'user_data'
id = db.Column('id', db.Integer, primary_key=True)
u_name = db.Column('u_name', db.String(50))
u_sku = db.Column('u_sku', db.String(10))
u_description = db.Column('u_description', db.String(1500))
|
[
"subratakamila2@gmail.com"
] |
subratakamila2@gmail.com
|
c8046c7484e23639cd6e983dfa5d597d5f603db9
|
17baed99ca2fb30a0578c89961addcab89c143f2
|
/restful/settings.py
|
33bb65320132b4ca50c9a961dfe40346b3984b82
|
[] |
no_license
|
newhuaszh/restful
|
151ec4855177dee6ef497364e887cdaa4e40f7a0
|
d1616c6c2d00dffcb5f2d15ff1b8935f60383095
|
refs/heads/master
| 2021-01-11T13:55:55.662099
| 2017-06-20T14:21:02
| 2017-06-20T14:21:02
| 94,899,574
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,249
|
py
|
"""
Django settings for restful project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'q#ta)wuy_4@jy!l9i%wkwd4grwy1h7a1)!p64!-@2ck_28i3k#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'snippets',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'restful.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'restful.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
|
[
"szhhzs@sina.com"
] |
szhhzs@sina.com
|
a2ab289aae0d3b78772cbe37bf8afadf36646cfe
|
99bc3defc34f3bc2854523c5c4a7c907c45233ec
|
/shanxingapi/testacse/case1.py
|
7d450c4b89f91d66be2356aae370b0fec8e4d081
|
[] |
no_license
|
huangchunhui521/shanxing
|
5ebc1ca0d30228bb19809e45aff0ac73bab0f538
|
8d26d3c5e41daab547799d28fb6071969500dde9
|
refs/heads/master
| 2021-05-21T13:35:02.883479
| 2020-04-03T12:04:33
| 2020-04-03T12:04:34
| 252,668,538
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,785
|
py
|
# -*- coding: utf-8 -*-
# @File:
# @Time :
# @Author :
# @Detail :
import unittest
from shanxingapi.testFile import fux_api
from shanxingapi.testFile.fux_api import Consumer
class ConsumerTestCase(unittest.TestCase):
__doc__ = "TestCase"
_classSetupFailed = True
_cookies = None
_shop_id = None
_user_id = None
_log = None
_consumer = None
@classmethod
def setUpClass(cls):
cls.consumer_object =fux_api.Consumer()
cls._log = fux_api.log
cls._log.debug("=" * 20)
cls._log.debug("开始测试")
@classmethod
def tearDownClass(cls):
cls._log.debug("="*20)
cls._log.debug("结束测试")
# def test_001(self):
# """礼物列表"""
# self.ret=Consumer().Master_list()
# self._log.info('```````{}'.format(self.ret))
# self.assertEqual(self.ret["code"], 0)
# def test_002(self):
# """法师登录验证码授权"""
# ret=self.consumer_object.grant_authorization(phone='15818650805',code='123456')
# self.assertEqual(ret["code"], 0)
def test_003(self):
"""法师登录接口"""
# 获取法师登录验证码授权
self.consumer_object.grant_authorization(phone='15818650805', code='11')
# 法师端登录
ret=self.consumer_object.login_Master(phone='15818650805')
self.assertEqual(ret["code"], 0)
def test_003(self):
"""法师登录接口"""
# 获取法师登录验证码授权
self.consumer_object.grant_authorization(phone='15818650805', code='11')
# 法师端登录
ret=self.consumer_object.login_Master(phone='15818650805')
self.assertEqual(ret["code"], 0)
if __name__ == '__main__':
unittest.main()
|
[
"53180380+huangchunhui521@users.noreply.github.com"
] |
53180380+huangchunhui521@users.noreply.github.com
|
1ac2383f4356c4123f3f0424f2d41eeb4d65eef7
|
e00d41c9f4045b6c6f36c0494f92cad2bec771e2
|
/multimedia/sound/celt/actions.py
|
ebbc7ace073cda6de994f48d6de40b6054304d7d
|
[] |
no_license
|
pisilinux/main
|
c40093a5ec9275c771eb5fb47a323e308440efef
|
bfe45a2e84ea43608e77fb9ffad1bf9850048f02
|
refs/heads/master
| 2023-08-19T00:17:14.685830
| 2023-08-18T20:06:02
| 2023-08-18T20:06:02
| 37,426,721
| 94
| 295
| null | 2023-09-14T08:22:22
| 2015-06-14T19:38:36
|
Python
|
UTF-8
|
Python
| false
| false
| 407
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/licenses/gpl.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
def setup():
autotools.configure("--disable-static")
def build():
autotools.make()
def install():
autotools.install()
pisitools.dodoc("COPYING", "README")
|
[
"ayhanyalcinsoy@pisilinux.org"
] |
ayhanyalcinsoy@pisilinux.org
|
2c23cac30eb794b54b016245d2b1078ebafd21bd
|
0febefe0a6813a6828a9e8b5301b7e583a5b7c4e
|
/lab1_app/migrations/0001_initial.py
|
f1a193ac4a33f09b1f2f45d9116e78a02c38f3df
|
[] |
no_license
|
vrekeda/django-lab1
|
117348c8162e50e0a0570dcdf9bd0bd8479fcd7f
|
e23047cffa0f0123fe4d4c22faf0c70de2e15b57
|
refs/heads/main
| 2023-05-09T01:37:05.214751
| 2021-05-28T20:43:44
| 2021-05-28T20:43:44
| 364,990,925
| 0
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 888
|
py
|
# Generated by Django 3.2.2 on 2021-05-06 20:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Language',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ukrainian_name', models.CharField(max_length=60)),
],
),
migrations.CreateModel(
name='Word',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('translate_to', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='lab1_app.language')),
],
),
]
|
[
"vladimir.rekeda@beeper.ru"
] |
vladimir.rekeda@beeper.ru
|
6bec3ddf43308f97381ac98d3aed4324806e4ca7
|
99c977d54eea4e56ebe363e52d6317daf8214ea3
|
/reverie/apps/core/models.py
|
36b8257d21d69d477724f46941b6ef23cf4e22ad
|
[] |
no_license
|
ternus/reverie
|
2fb89d64132b4801705f8096aefb6ccc4ba31348
|
ed1740bf7fe93db39e341a280d948c625d525aeb
|
refs/heads/master
| 2016-09-16T13:31:44.193021
| 2011-11-26T20:15:11
| 2011-11-26T20:15:11
| 2,828,374
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,026
|
py
|
from datetime import datetime
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from const import Skills, LogTypes
from couchdbkit.ext.django.schema import *
DEFAULT_LOCATION=Point(42.359140, -71.093548) # 77 Mass Ave
class Character(models.Model):
name = models.CharField(max_length=256)
essence = models.IntegerField()
loc = models.PointField(default=DEFAULT_LOCATION)
objects = models.GeoManager()
def __unicode__(self):
return "%s [%s]" % (self.name, self.essence)
def write_log(self, type, **kwargs):
l = CharLog(char_id=self.id, char_name=self.name, type=type)
for k in kwargs:
l.__setattr__(k, kwargs[k])
l.save()
def read_log(self, type=None):
pass
def heartbeat(self, loc):
self.loc = loc
self.save()
self.write_log(LogTypes.HEARTBEAT, lat=loc.get_x(), long=loc.get_y())
def get_location(self):
l = CharLog.view("core/cur_loc", reduce=True, group=True, group_level=1).all()
if not l: return None
return l[0]['value']['lat'], l[0]['value']['long']
class CharLog(Document):
char_id = IntegerProperty(required=True)
char_name = StringProperty()
type = StringProperty(required=True)
lat = FloatProperty()
long = FloatProperty()
date = DateTimeProperty(default=datetime.utcnow)
class Item(models.Model):
""" Represents an *instance* of an item. We'll want to have more than one of any given item."""
owner = models.ForeignKey('Character', null=True, blank=True)
base = models.ForeignKey('AbstractItem')
loc = models.PointField()
objects = models.GeoManager()
def __unicode__(self):
if self.owner:
return "%s (owned by %s)" % (self.base.name, self.owner)
else:
return "%s (at %s)" % (self.base.name, self.loc)
class AbstractItem(models.Model):
name = models.CharField(max_length=256)
def __unicode__(self):
return "<%s>" % self.name
|
[
"ternus@mit.edu"
] |
ternus@mit.edu
|
f1e0cce2582fadbf805d801d420991f393e8ca75
|
0728138c0c59305b410f1687ba3d32c656990ad3
|
/social/backends/persona.py
|
c6ab197365f4b9367db6d30473a4ca871f4df107
|
[
"BSD-2-Clause"
] |
permissive
|
rhookie/flask_reveal
|
82b2dd2f53ca03fc5f4a07f1c12c8d8680fc8eb4
|
5c8c26c8686b4ee9a952a92a8150a18995dc778b
|
refs/heads/master
| 2021-05-07T05:04:43.887058
| 2017-10-10T16:52:49
| 2017-10-10T16:52:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,651
|
py
|
"""
BrowserID support
"""
from social.backends.base import BaseAuth
from social.exceptions import AuthFailed, AuthMissingParameter
class PersonaAuth(BaseAuth):
"""BrowserID authentication backend"""
name = 'persona'
def get_user_id(self, details, response):
"""Use BrowserID email as ID"""
return details['email']
def get_user_details(self, response):
"""Return user details, BrowserID only provides Email."""
# {'status': 'okay',
# 'audience': 'localhost:8000',
# 'expires': 1328983575529,
# 'email': 'name@server.com',
# 'issuer': 'browserid.org'}
email = response['email']
return {'username': email.split('@', 1)[0],
'email': email,
'fullname': '',
'first_name': '',
'last_name': ''}
def extra_data(self, user, uid, response, details):
"""Return users extra data"""
return {'audience': response['audience'],
'issuer': response['issuer']}
def auth_complete(self, *args, **kwargs):
"""Completes loging process, must return user instance"""
if not 'assertion' in self.data:
raise AuthMissingParameter(self, 'assertion')
response = self.get_json('https://browserid.org/verify', params={
'assertion': self.data['assertion'],
'audience': self.strategy.request_host()
})
if response.get('status') == 'failure':
raise AuthFailed(self)
kwargs.update({'response': response, 'backend': self})
return self.strategy.authenticate(*args, **kwargs)
|
[
"ciici123@hotmail.com"
] |
ciici123@hotmail.com
|
97144af185424ea27a240b90f0c63e9326295721
|
5f19c7590f5639f0ec4e97c8e80c9cb9f4c30025
|
/xgboost_logistic.py
|
6150f2d3527cb86cce44394148be0a3567e27d0e
|
[] |
no_license
|
PXPX11/Quantitative-Finance
|
37448a3fa6a1b659fd83b01050c9cfb8344e639c
|
fc598ae75bbf54a660bd88f9a14e680d6a8890d0
|
refs/heads/master
| 2023-04-12T16:04:59.010704
| 2021-05-10T11:01:58
| 2021-05-10T11:01:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,192
|
py
|
import pandas as pd
import numpy as np
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
from sklearn import cross_validation, metrics
from sklearn.grid_search import GridSearchCV
from sklearn.cross_validation import train_test_split
import matplotlib.pylab as plt
from sklearn.preprocessing import LabelEncoder
from numpy import concatenate
from pandas import DataFrame
from math import sqrt
from sklearn.metrics import mean_squared_error
import time
from qpython import qconnection
conn = qconnection.QConnection('localhost')
conn.open()
# load data
conn(r'''
f1:{[cost;x;y] $[y>x+cost;y-cost;y<x-cost;y+cost;x]};
f2:{[cost; series]
t0: f1[cost] scan series;
fills reverse fills reverse?[(t0>prev t0)&(not null prev t0);1;?[t0<prev t0;-1;0N]]
};
data:select from basis where (not null close) & (not null amount) & (not null volume)&(volume>=0)&(close>=0);
data1:update sig1:f2[3;close] from data;
data1:update sig:?[(sig1*(-1 xprev sig1))=-1;neg sig1;sig1] from data1;
data1:update mavgc5:5 mavg close from data1;
data1:update mavgv10:10 mavg volume from data1;
data1:update mavgv30:30 mavg volume from data1;
data1:update cost:0^?[((prev sig)*sig)=-1;close*0.00015;0] from data1;
data1:update minRet:0^log(1+((prev sig)*((close%prev close)-1))-cost%prev close) from data1;
data1:update sig:?[sig=1;1;0] from data1;
data1
''', pandas=True)
dataset = conn(r'''
select `$ string each date,sig,symbol,close,mavgc5,dif,stock,minRet,volume,mavgv10,mavgv30 from data1
''', pandas=True)
values_full =dataset.values
values = values_full[:,1:]
encoder = LabelEncoder()
values[:,1] = encoder.fit_transform(values[:,1])
# ensure all data is float
#values = values.astype('float32')
start_time = time.time()
# 读入数据
n_train_hours = 365 * 1403
train = values[332911:n_train_hours,:]
tests = values[n_train_hours:,1:]
#print(train[:1,:])
#print(tests[:1,:])
params = {
'booster': 'gbtree',
'objective': 'binary:logistic', # 多分类的问题
#'num_class': 2, # 类别数,与 multisoftmax 并用
'gamma': 0.1, # 用于控制是否后剪枝的参数,越大越保守,一般0.1、0.2这样子。
'max_depth': 10, # 构建树的深度,越大越容易过拟合
'lambda': 2, # 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。
'subsample': 0.7, # 随机采样训练样本
'colsample_bytree': 0.7, # 生成树时进行的列采样
'min_child_weight': 2,
'scale_pos_weight':1,
# 这个参数默认是 1,是每个叶子里面 h 的和至少是多少,对正负样本不均衡时的 0-1 分类而言
# ,假设 h 在 0.01 附近,min_child_weight 为 1 意味着叶子节点中最少需要包含 100 个样本。
# 这个参数非常影响结果,控制叶子节点中二阶导的和的最小值,该参数值越小,越容易 overfitting。
'silent': 0, # 设置成1则没有运行信息输出,最好是设置为0.
'eta': 0.2, # 如同学习率
'seed': 100,
'nthread': 6, # cpu 线程数
#'eval_metric': 'rmse'
}
plst = list(params.items())
num_rounds = 500 # 迭代次数
train_xy, val = train_test_split(train, test_size=0.3, random_state=1)
# random_state is of big influence for val-auc
y = train_xy[:,0]
X = train_xy[:,1:]
val_y = val[:,0]
val_X = val[:,1:]
xgb_val = xgb.DMatrix(val_X, label=val_y)
xgb_train = xgb.DMatrix(X, label=y)
xgb_test = xgb.DMatrix(tests)
watchlist = [(xgb_train, 'train'), (xgb_val, 'val')]
# training model
# early_stopping_rounds 当设置的迭代次数较大时,early_stopping_rounds 可在一定的迭代次数内准确率没有提升就停止训练
model = xgb.train(plst, xgb_train, num_rounds, watchlist, early_stopping_rounds=100)
#model.save_model('./model/xgb.model') # 用于存储训练出的模型
print ("best best_ntree_limit:", model.best_ntree_limit)
preds = model.predict(xgb_test, ntree_limit=model.best_ntree_limit)
# 输出运行时长
cost_time = time.time() - start_time
print ("xgboost success!", '\n', "cost time:", cost_time, "(s)")
y_test = values[n_train_hours:,0]
test_rmse = sqrt(mean_squared_error(y_test, preds))
print('Test RMSE: %.3f' % test_rmse)
preds=preds.reshape(len(preds),1)
date = values_full[n_train_hours:,0].reshape((len(preds), 1))
test_s = concatenate((date,preds),axis=1)
#test_ss = concatenate((date,values[n_train_hours:,:]),axis=1)
test_ss = concatenate((test_s,values[n_train_hours:,1:]),axis=1)
df = DataFrame(test_ss,columns=dataset.columns)
conn('{`data_lstm_s set x}', df)
conn(r'''
data_lstm_s:update date: "D"$ string each date from data_lstm_s;
data_lstm_s:update sig:?[sig<0.5;-1;1] from data_lstm_s;
data_lstm_s:update cost:0^?[((prev sig)*sig)=-1;close*0.00012;0] from data_lstm_s;
data_lstm_s:update minRet:0^log(1+((prev sig)*((close%prev close)-1))-cost%prev close) from data_lstm_s;
data_lstm_s:update turnover:0^?[cost=0;0;1] from data_lstm_s;
5#select from data_lstm_s where cost<>0
''',pandas=True)
conn(r'''
funct:{[begdate;enddate]
trade_indicator:select date,symbol,sig,close,cost,turnover from data_lstm_s where date within(begdate,enddate);
hdq_CmRet1::select
DailyRet:sum minRet ,
cm_ret:last cm_ret,
number:sum abs(sig),
turnover:sum turnover
by date
from (
update cm_ret:sums minRet
from (min_ret:select date,symbol,sig,turnover,
minRet:0^log(1+((prev sig)*((close%prev close)-1))-cost%prev close)
from (select date,symbol,sig,close,cost,turnover from trade_indicator)));
hdq_test_result:select
sharpe:(250*(avg DailyRet)) % ((sqrt 250)*(dev DailyRet)),
annual_ret:250*(avg DailyRet),
annual_vol :(sqrt 250)*(dev DailyRet),
cum_ret: last cm_ret,
maxdd: 1-exp neg max (maxs sums DailyRet)-(sums DailyRet),
win_pro: (sum DailyRet>0) % ((sum DailyRet>0)+(sum DailyRet <0)),
turnover_rate:(sum turnover)% (sum number)
from hdq_CmRet1
};
''', pandas=True)
result=conn(r'''
funct[2017.12.27;2018.01.31]
''',pandas=True)
print(result)
|
[
"noreply@github.com"
] |
noreply@github.com
|
d7844833faffeeb6ea09e3c6a4e91c845c8bcd78
|
b2d3bd39b2de8bcc3b0f05f4800c2fabf83d3c6a
|
/examples/pwr_run/checkpointing/new_short/feedback/job13.py
|
70a3df461607c82369d2bf42af52327b64207e16
|
[
"MIT"
] |
permissive
|
boringlee24/keras_old
|
3bf7e3ef455dd4262e41248f13c04c071039270e
|
1e1176c45c4952ba1b9b9e58e9cc4df027ab111d
|
refs/heads/master
| 2021-11-21T03:03:13.656700
| 2021-11-11T21:57:54
| 2021-11-11T21:57:54
| 198,494,579
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,222
|
py
|
"""
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.callbacks import ReduceLROnPlateau, TensorBoard
from keras.preprocessing.image import ImageDataGenerator
from keras.regularizers import l2
from keras import backend as K
from keras.models import Model
from keras.datasets import cifar10
from keras.applications.resnet import ResNet50, ResNet101, ResNet152
from keras import models, layers, optimizers
from datetime import datetime
import tensorflow as tf
import numpy as np
import os
import pdb
import sys
import argparse
import time
import signal
import glob
import json
import send_signal
parser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')
parser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')
parser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')
parser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')
parser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')
parser.set_defaults(resume=False)
args = parser.parse_args()
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu_num
# Training parameters
batch_size = 256
args_lr = 0.01
args_model = 'resnet50'
epoch_begin_time = 0
job_name = sys.argv[0].split('.')[0]
save_files = '/scratch/li.baol/checkpoint_feedback/' + job_name + '*'
total_epochs = 11
starting_epoch = 0
# first step is to update the PID
pid_dict = {}
with open('pid_lock.json', 'r') as fp:
pid_dict = json.load(fp)
pid_dict[job_name] = os.getpid()
json_file = json.dumps(pid_dict)
with open('pid_lock.json', 'w') as fp:
fp.write(json_file)
os.rename('pid_lock.json', 'pid.json')
if args.resume:
save_file = glob.glob(save_files)[0]
# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])
starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])
data_augmentation = True
num_classes = 10
# Subtracting pixel mean improves accuracy
subtract_pixel_mean = True
n = 3
# Model name, depth and version
model_type = args.tc #'P100_resnet50_he_256_1'
# Load the CIFAR10 data.
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Normalize data.
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# If subtract pixel mean is enabled
if subtract_pixel_mean:
x_train_mean = np.mean(x_train, axis=0)
x_train -= x_train_mean
x_test -= x_train_mean
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print('y_train shape:', y_train.shape)
# Convert class vectors to binary class matrices.
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
if args.resume:
print('resume from checkpoint')
model = keras.models.load_model(save_file)
else:
print('train from start')
model = models.Sequential()
if '50' in args_model:
base_model = ResNet50(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)
elif '101' in args_model:
base_model = ResNet101(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)
elif '152' in args_model:
base_model = ResNet152(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)
#base_model.summary()
#pdb.set_trace()
#model.add(layers.UpSampling2D((2,2)))
#model.add(layers.UpSampling2D((2,2)))
#model.add(layers.UpSampling2D((2,2)))
model.add(base_model)
model.add(layers.Flatten())
#model.add(layers.BatchNormalization())
#model.add(layers.Dense(128, activation='relu'))
#model.add(layers.Dropout(0.5))
#model.add(layers.BatchNormalization())
#model.add(layers.Dense(64, activation='relu'))
#model.add(layers.Dropout(0.5))
#model.add(layers.BatchNormalization())
model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))
model.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=args_lr),
metrics=['accuracy'])
#model.summary()
print(model_type)
#pdb.set_trace()
current_epoch = 0
################### connects interrupt signal to the process #####################
def terminateProcess(signalNumber, frame):
# first record the wasted epoch time
global epoch_begin_time
if epoch_begin_time == 0:
epoch_waste_time = 0
else:
epoch_waste_time = int(time.time() - epoch_begin_time)
epoch_waste_dict = {}
with open('epoch_waste.json', 'r') as fp:
epoch_waste_dict = json.load(fp)
epoch_waste_dict[job_name] += epoch_waste_time
json_file3 = json.dumps(epoch_waste_dict)
with open('epoch_waste.json', 'w') as fp:
fp.write(json_file3)
print('checkpointing the model triggered by kill -15 signal')
# delete whatever checkpoint that already exists
for f in glob.glob(save_files):
os.remove(f)
model.save('/scratch/li.baol/checkpoint_feedback/' + job_name + '_' + str(current_epoch) + '.h5')
print ('(SIGTERM) terminating the process')
checkpoint_dict = {}
with open('checkpoint.json', 'r') as fp:
checkpoint_dict = json.load(fp)
checkpoint_dict[job_name] = 1
json_file3 = json.dumps(checkpoint_dict)
with open('checkpoint.json', 'w') as fp:
fp.write(json_file3)
sys.exit()
signal.signal(signal.SIGTERM, terminateProcess)
#################################################################################
logdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name
tensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')
class PrintEpoch(keras.callbacks.Callback):
def on_epoch_begin(self, epoch, logs=None):
global current_epoch
#remaining_epochs = epochs - epoch
current_epoch = epoch
print('current epoch ' + str(current_epoch))
global epoch_begin_time
epoch_begin_time = time.time()
my_callback = PrintEpoch()
callbacks = [tensorboard_callback, my_callback]
#[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]
# Run training
# send signal to indicate checkpoint is qualified
message = job_name + ' ckpt_qual'
send_signal.send(args.node, 10002, message)
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=round(total_epochs/2),
validation_data=(x_test, y_test),
shuffle=True,
callbacks=callbacks,
initial_epoch=starting_epoch,
verbose=1
)
# Score trained model.
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])
# send signal to indicate job has finished
message = job_name + ' finish'
send_signal.send(args.node, 10002, message)
|
[
"baolin.li1994@gmail.com"
] |
baolin.li1994@gmail.com
|
ea7e309f7c49d75e513aa4e6d215df4c6ab155c4
|
48227bebe295925f7063d58521f3fd16273b1706
|
/02/printing.py
|
e297ebec74e242204327d903a63f85909f0de936
|
[] |
no_license
|
akarneliuk/CEX
|
b8ffff64d57699fd17b4a7bfb52c64534bfb1ce8
|
c869fb8c1f497933c8227e3c41b0f295a6dad3b2
|
refs/heads/master
| 2020-12-27T21:01:28.722083
| 2020-08-10T12:45:12
| 2020-08-10T12:45:12
| 238,052,880
| 0
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 113
|
py
|
#!/usr/local/bin/python3.8
print('Hello, new network automation mate! This exciting world is waiting for you.')
|
[
"akarneliuk@gmail.com"
] |
akarneliuk@gmail.com
|
3d03517f3547f991cdc1626ffa4deed8f3f04736
|
6f47b0cc1b80d9fe5cdbab9f54def092050d87f7
|
/A05-09/validators/validators.py
|
0f8febe2f1c47b83fef1bfa529b710397a150a3f
|
[] |
no_license
|
alexovidiupopa/Fundamentals-of-Programming-
|
024cb4d20be2bab3372714bbf2aa493ce5193082
|
9d557a0b82ef87e46a716a3506939aaf9a5f5ffb
|
refs/heads/master
| 2020-03-31T09:01:05.685430
| 2019-01-17T15:04:08
| 2019-01-18T11:59:25
| 152,080,329
| 0
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,515
|
py
|
from errors.errors import ValidError
import datetime
class StudentValidator(object):
'''
the class to validate if a student is correctly inputted
'''
def validateStudent(self,student):
errors = ""
if student.getID()<0:
errors+="Invalid id"
if student.getName() == "":
errors+="Invalid name"
if student.getGroup() == "":
errors += "Invalid group"
if len(errors)>0:
raise ValidError(errors)
class AssignmentValidator(object):
'''
the class to validate if an assignment is correctly inputted
'''
def validateInt(self,integer):
try:
newInteger = int(integer)
return newInteger
except:
return -1
def validateAssignment(self,assignment):
errors = ""
if assignment.getID()<0:
errors += "Invalid id"
deadline = assignment.getDeadline().split('/')
if len(deadline) != 3:
errors+="Invalid deadline"
else:
if self.validateInt(deadline[0]) < 0 or self.validateInt(deadline[0]) > 31:
errors += "Invalid day of the month"
if self.validateInt(deadline[1]) <= 0 or self.validateInt(deadline[1]) > 12:
errors += "Invalid month of the year"
currentYear = int(datetime.datetime.now().year)
if self.validateInt(deadline[2]) <= 0 or self.validateInt(deadline[2]) < currentYear or self.validateInt(deadline[2]) > currentYear + 1 :
errors += "Invalid year."
if len(errors)>0:
raise ValidError(errors)
class GradeValidator(object):
'''
the class to validate if a grade is correctly inputted
'''
def validateGrade(self,grade):
errors = ""
if grade.getStudentID() < 0:
errors += "Invalid student id"
if grade.getAssignmentID()<0:
errors += "Invalid assignment id"
if grade.getGrade()<=0 and grade.getGrade()!=-1 or grade.getGrade()>10:
errors += "Invalid grade"
if len(errors)>0:
raise ValidError(errors)
def validateLateDeadline(self,assignment):
deadline = datetime.datetime.strptime(assignment.getDeadline(),"%d/%m/%Y")
currentDate = datetime.datetime.now()
if deadline < currentDate:
return True
return False
|
[
"popaalexovidiu@gmail.com"
] |
popaalexovidiu@gmail.com
|
9a725f41172d9ade05875dcb65efc8a1736e28a6
|
009851177d04a441141113189125a91a26f4dc74
|
/nodejs-mobile/deps/openssl/config/archs/linux-x32/no-asm/openssl.gypi
|
cf044b5b7feea81208deb55bcc6f1b1ad4e9f131
|
[
"MIT",
"LicenseRef-scancode-unicode",
"Zlib",
"ISC",
"LicenseRef-scancode-public-domain",
"NAIST-2003",
"BSD-3-Clause",
"BSD-2-Clause",
"Artistic-2.0",
"LicenseRef-scancode-unknown-license-reference",
"NTP",
"LicenseRef-scancode-openssl",
"ICU"
] |
permissive
|
xuelongqy/cnode
|
a967f9e71315b10d3870192b4bbe2c341b196507
|
ac256264d329e68b6c5ae3281b0e7bb5a95ae164
|
refs/heads/master
| 2023-01-30T11:23:41.485647
| 2020-03-25T05:55:13
| 2020-03-25T05:55:13
| 246,811,631
| 0
| 1
|
MIT
| 2023-01-07T15:54:34
| 2020-03-12T10:58:07
|
C++
|
UTF-8
|
Python
| false
| false
| 25,516
|
gypi
|
{
'variables': {
'openssl_sources': [
'openssl/ssl/bio_ssl.c',
'openssl/ssl/d1_lib.c',
'openssl/ssl/d1_msg.c',
'openssl/ssl/d1_srtp.c',
'openssl/ssl/methods.c',
'openssl/ssl/pqueue.c',
'openssl/ssl/record/dtls1_bitmap.c',
'openssl/ssl/record/rec_layer_d1.c',
'openssl/ssl/record/rec_layer_s3.c',
'openssl/ssl/record/ssl3_buffer.c',
'openssl/ssl/record/ssl3_record.c',
'openssl/ssl/s3_cbc.c',
'openssl/ssl/s3_enc.c',
'openssl/ssl/s3_lib.c',
'openssl/ssl/s3_msg.c',
'openssl/ssl/ssl_asn1.c',
'openssl/ssl/ssl_cert.c',
'openssl/ssl/ssl_ciph.c',
'openssl/ssl/ssl_conf.c',
'openssl/ssl/ssl_err.c',
'openssl/ssl/ssl_init.c',
'openssl/ssl/ssl_lib.c',
'openssl/ssl/ssl_mcnf.c',
'openssl/ssl/ssl_rsa.c',
'openssl/ssl/ssl_sess.c',
'openssl/ssl/ssl_stat.c',
'openssl/ssl/ssl_txt.c',
'openssl/ssl/ssl_utst.c',
'openssl/ssl/statem/statem.c',
'openssl/ssl/statem/statem_clnt.c',
'openssl/ssl/statem/statem_dtls.c',
'openssl/ssl/statem/statem_lib.c',
'openssl/ssl/statem/statem_srvr.c',
'openssl/ssl/t1_enc.c',
'openssl/ssl/t1_ext.c',
'openssl/ssl/t1_lib.c',
'openssl/ssl/t1_reneg.c',
'openssl/ssl/t1_trce.c',
'openssl/ssl/tls_srp.c',
'openssl/crypto/aes/aes_cbc.c',
'openssl/crypto/aes/aes_cfb.c',
'openssl/crypto/aes/aes_core.c',
'openssl/crypto/aes/aes_ecb.c',
'openssl/crypto/aes/aes_ige.c',
'openssl/crypto/aes/aes_misc.c',
'openssl/crypto/aes/aes_ofb.c',
'openssl/crypto/aes/aes_wrap.c',
'openssl/crypto/asn1/a_bitstr.c',
'openssl/crypto/asn1/a_d2i_fp.c',
'openssl/crypto/asn1/a_digest.c',
'openssl/crypto/asn1/a_dup.c',
'openssl/crypto/asn1/a_gentm.c',
'openssl/crypto/asn1/a_i2d_fp.c',
'openssl/crypto/asn1/a_int.c',
'openssl/crypto/asn1/a_mbstr.c',
'openssl/crypto/asn1/a_object.c',
'openssl/crypto/asn1/a_octet.c',
'openssl/crypto/asn1/a_print.c',
'openssl/crypto/asn1/a_sign.c',
'openssl/crypto/asn1/a_strex.c',
'openssl/crypto/asn1/a_strnid.c',
'openssl/crypto/asn1/a_time.c',
'openssl/crypto/asn1/a_type.c',
'openssl/crypto/asn1/a_utctm.c',
'openssl/crypto/asn1/a_utf8.c',
'openssl/crypto/asn1/a_verify.c',
'openssl/crypto/asn1/ameth_lib.c',
'openssl/crypto/asn1/asn1_err.c',
'openssl/crypto/asn1/asn1_gen.c',
'openssl/crypto/asn1/asn1_lib.c',
'openssl/crypto/asn1/asn1_par.c',
'openssl/crypto/asn1/asn_mime.c',
'openssl/crypto/asn1/asn_moid.c',
'openssl/crypto/asn1/asn_mstbl.c',
'openssl/crypto/asn1/asn_pack.c',
'openssl/crypto/asn1/bio_asn1.c',
'openssl/crypto/asn1/bio_ndef.c',
'openssl/crypto/asn1/d2i_pr.c',
'openssl/crypto/asn1/d2i_pu.c',
'openssl/crypto/asn1/evp_asn1.c',
'openssl/crypto/asn1/f_int.c',
'openssl/crypto/asn1/f_string.c',
'openssl/crypto/asn1/i2d_pr.c',
'openssl/crypto/asn1/i2d_pu.c',
'openssl/crypto/asn1/n_pkey.c',
'openssl/crypto/asn1/nsseq.c',
'openssl/crypto/asn1/p5_pbe.c',
'openssl/crypto/asn1/p5_pbev2.c',
'openssl/crypto/asn1/p5_scrypt.c',
'openssl/crypto/asn1/p8_pkey.c',
'openssl/crypto/asn1/t_bitst.c',
'openssl/crypto/asn1/t_pkey.c',
'openssl/crypto/asn1/t_spki.c',
'openssl/crypto/asn1/tasn_dec.c',
'openssl/crypto/asn1/tasn_enc.c',
'openssl/crypto/asn1/tasn_fre.c',
'openssl/crypto/asn1/tasn_new.c',
'openssl/crypto/asn1/tasn_prn.c',
'openssl/crypto/asn1/tasn_scn.c',
'openssl/crypto/asn1/tasn_typ.c',
'openssl/crypto/asn1/tasn_utl.c',
'openssl/crypto/asn1/x_algor.c',
'openssl/crypto/asn1/x_bignum.c',
'openssl/crypto/asn1/x_info.c',
'openssl/crypto/asn1/x_int64.c',
'openssl/crypto/asn1/x_long.c',
'openssl/crypto/asn1/x_pkey.c',
'openssl/crypto/asn1/x_sig.c',
'openssl/crypto/asn1/x_spki.c',
'openssl/crypto/asn1/x_val.c',
'openssl/crypto/async/arch/async_null.c',
'openssl/crypto/async/arch/async_posix.c',
'openssl/crypto/async/arch/async_win.c',
'openssl/crypto/async/async.c',
'openssl/crypto/async/async_err.c',
'openssl/crypto/async/async_wait.c',
'openssl/crypto/bf/bf_cfb64.c',
'openssl/crypto/bf/bf_ecb.c',
'openssl/crypto/bf/bf_enc.c',
'openssl/crypto/bf/bf_ofb64.c',
'openssl/crypto/bf/bf_skey.c',
'openssl/crypto/bio/b_addr.c',
'openssl/crypto/bio/b_dump.c',
'openssl/crypto/bio/b_print.c',
'openssl/crypto/bio/b_sock.c',
'openssl/crypto/bio/b_sock2.c',
'openssl/crypto/bio/bf_buff.c',
'openssl/crypto/bio/bf_lbuf.c',
'openssl/crypto/bio/bf_nbio.c',
'openssl/crypto/bio/bf_null.c',
'openssl/crypto/bio/bio_cb.c',
'openssl/crypto/bio/bio_err.c',
'openssl/crypto/bio/bio_lib.c',
'openssl/crypto/bio/bio_meth.c',
'openssl/crypto/bio/bss_acpt.c',
'openssl/crypto/bio/bss_bio.c',
'openssl/crypto/bio/bss_conn.c',
'openssl/crypto/bio/bss_dgram.c',
'openssl/crypto/bio/bss_fd.c',
'openssl/crypto/bio/bss_file.c',
'openssl/crypto/bio/bss_log.c',
'openssl/crypto/bio/bss_mem.c',
'openssl/crypto/bio/bss_null.c',
'openssl/crypto/bio/bss_sock.c',
'openssl/crypto/blake2/blake2b.c',
'openssl/crypto/blake2/blake2s.c',
'openssl/crypto/blake2/m_blake2b.c',
'openssl/crypto/blake2/m_blake2s.c',
'openssl/crypto/bn/bn_add.c',
'openssl/crypto/bn/bn_asm.c',
'openssl/crypto/bn/bn_blind.c',
'openssl/crypto/bn/bn_const.c',
'openssl/crypto/bn/bn_ctx.c',
'openssl/crypto/bn/bn_depr.c',
'openssl/crypto/bn/bn_dh.c',
'openssl/crypto/bn/bn_div.c',
'openssl/crypto/bn/bn_err.c',
'openssl/crypto/bn/bn_exp.c',
'openssl/crypto/bn/bn_exp2.c',
'openssl/crypto/bn/bn_gcd.c',
'openssl/crypto/bn/bn_gf2m.c',
'openssl/crypto/bn/bn_intern.c',
'openssl/crypto/bn/bn_kron.c',
'openssl/crypto/bn/bn_lib.c',
'openssl/crypto/bn/bn_mod.c',
'openssl/crypto/bn/bn_mont.c',
'openssl/crypto/bn/bn_mpi.c',
'openssl/crypto/bn/bn_mul.c',
'openssl/crypto/bn/bn_nist.c',
'openssl/crypto/bn/bn_prime.c',
'openssl/crypto/bn/bn_print.c',
'openssl/crypto/bn/bn_rand.c',
'openssl/crypto/bn/bn_recp.c',
'openssl/crypto/bn/bn_shift.c',
'openssl/crypto/bn/bn_sqr.c',
'openssl/crypto/bn/bn_sqrt.c',
'openssl/crypto/bn/bn_srp.c',
'openssl/crypto/bn/bn_word.c',
'openssl/crypto/bn/bn_x931p.c',
'openssl/crypto/buffer/buf_err.c',
'openssl/crypto/buffer/buffer.c',
'openssl/crypto/camellia/camellia.c',
'openssl/crypto/camellia/cmll_cbc.c',
'openssl/crypto/camellia/cmll_cfb.c',
'openssl/crypto/camellia/cmll_ctr.c',
'openssl/crypto/camellia/cmll_ecb.c',
'openssl/crypto/camellia/cmll_misc.c',
'openssl/crypto/camellia/cmll_ofb.c',
'openssl/crypto/cast/c_cfb64.c',
'openssl/crypto/cast/c_ecb.c',
'openssl/crypto/cast/c_enc.c',
'openssl/crypto/cast/c_ofb64.c',
'openssl/crypto/cast/c_skey.c',
'openssl/crypto/chacha/chacha_enc.c',
'openssl/crypto/cmac/cm_ameth.c',
'openssl/crypto/cmac/cm_pmeth.c',
'openssl/crypto/cmac/cmac.c',
'openssl/crypto/cms/cms_asn1.c',
'openssl/crypto/cms/cms_att.c',
'openssl/crypto/cms/cms_cd.c',
'openssl/crypto/cms/cms_dd.c',
'openssl/crypto/cms/cms_enc.c',
'openssl/crypto/cms/cms_env.c',
'openssl/crypto/cms/cms_err.c',
'openssl/crypto/cms/cms_ess.c',
'openssl/crypto/cms/cms_io.c',
'openssl/crypto/cms/cms_kari.c',
'openssl/crypto/cms/cms_lib.c',
'openssl/crypto/cms/cms_pwri.c',
'openssl/crypto/cms/cms_sd.c',
'openssl/crypto/cms/cms_smime.c',
'openssl/crypto/conf/conf_api.c',
'openssl/crypto/conf/conf_def.c',
'openssl/crypto/conf/conf_err.c',
'openssl/crypto/conf/conf_lib.c',
'openssl/crypto/conf/conf_mall.c',
'openssl/crypto/conf/conf_mod.c',
'openssl/crypto/conf/conf_sap.c',
'openssl/crypto/conf/conf_ssl.c',
'openssl/crypto/cpt_err.c',
'openssl/crypto/cryptlib.c',
'openssl/crypto/ct/ct_b64.c',
'openssl/crypto/ct/ct_err.c',
'openssl/crypto/ct/ct_log.c',
'openssl/crypto/ct/ct_oct.c',
'openssl/crypto/ct/ct_policy.c',
'openssl/crypto/ct/ct_prn.c',
'openssl/crypto/ct/ct_sct.c',
'openssl/crypto/ct/ct_sct_ctx.c',
'openssl/crypto/ct/ct_vfy.c',
'openssl/crypto/ct/ct_x509v3.c',
'openssl/crypto/cversion.c',
'openssl/crypto/des/cbc_cksm.c',
'openssl/crypto/des/cbc_enc.c',
'openssl/crypto/des/cfb64ede.c',
'openssl/crypto/des/cfb64enc.c',
'openssl/crypto/des/cfb_enc.c',
'openssl/crypto/des/des_enc.c',
'openssl/crypto/des/ecb3_enc.c',
'openssl/crypto/des/ecb_enc.c',
'openssl/crypto/des/fcrypt.c',
'openssl/crypto/des/fcrypt_b.c',
'openssl/crypto/des/ofb64ede.c',
'openssl/crypto/des/ofb64enc.c',
'openssl/crypto/des/ofb_enc.c',
'openssl/crypto/des/pcbc_enc.c',
'openssl/crypto/des/qud_cksm.c',
'openssl/crypto/des/rand_key.c',
'openssl/crypto/des/rpc_enc.c',
'openssl/crypto/des/set_key.c',
'openssl/crypto/des/str2key.c',
'openssl/crypto/des/xcbc_enc.c',
'openssl/crypto/dh/dh_ameth.c',
'openssl/crypto/dh/dh_asn1.c',
'openssl/crypto/dh/dh_check.c',
'openssl/crypto/dh/dh_depr.c',
'openssl/crypto/dh/dh_err.c',
'openssl/crypto/dh/dh_gen.c',
'openssl/crypto/dh/dh_kdf.c',
'openssl/crypto/dh/dh_key.c',
'openssl/crypto/dh/dh_lib.c',
'openssl/crypto/dh/dh_meth.c',
'openssl/crypto/dh/dh_pmeth.c',
'openssl/crypto/dh/dh_prn.c',
'openssl/crypto/dh/dh_rfc5114.c',
'openssl/crypto/dsa/dsa_ameth.c',
'openssl/crypto/dsa/dsa_asn1.c',
'openssl/crypto/dsa/dsa_depr.c',
'openssl/crypto/dsa/dsa_err.c',
'openssl/crypto/dsa/dsa_gen.c',
'openssl/crypto/dsa/dsa_key.c',
'openssl/crypto/dsa/dsa_lib.c',
'openssl/crypto/dsa/dsa_meth.c',
'openssl/crypto/dsa/dsa_ossl.c',
'openssl/crypto/dsa/dsa_pmeth.c',
'openssl/crypto/dsa/dsa_prn.c',
'openssl/crypto/dsa/dsa_sign.c',
'openssl/crypto/dsa/dsa_vrf.c',
'openssl/crypto/dso/dso_dl.c',
'openssl/crypto/dso/dso_dlfcn.c',
'openssl/crypto/dso/dso_err.c',
'openssl/crypto/dso/dso_lib.c',
'openssl/crypto/dso/dso_openssl.c',
'openssl/crypto/dso/dso_vms.c',
'openssl/crypto/dso/dso_win32.c',
'openssl/crypto/ebcdic.c',
'openssl/crypto/ec/curve25519.c',
'openssl/crypto/ec/ec2_mult.c',
'openssl/crypto/ec/ec2_oct.c',
'openssl/crypto/ec/ec2_smpl.c',
'openssl/crypto/ec/ec_ameth.c',
'openssl/crypto/ec/ec_asn1.c',
'openssl/crypto/ec/ec_check.c',
'openssl/crypto/ec/ec_curve.c',
'openssl/crypto/ec/ec_cvt.c',
'openssl/crypto/ec/ec_err.c',
'openssl/crypto/ec/ec_key.c',
'openssl/crypto/ec/ec_kmeth.c',
'openssl/crypto/ec/ec_lib.c',
'openssl/crypto/ec/ec_mult.c',
'openssl/crypto/ec/ec_oct.c',
'openssl/crypto/ec/ec_pmeth.c',
'openssl/crypto/ec/ec_print.c',
'openssl/crypto/ec/ecdh_kdf.c',
'openssl/crypto/ec/ecdh_ossl.c',
'openssl/crypto/ec/ecdsa_ossl.c',
'openssl/crypto/ec/ecdsa_sign.c',
'openssl/crypto/ec/ecdsa_vrf.c',
'openssl/crypto/ec/eck_prn.c',
'openssl/crypto/ec/ecp_mont.c',
'openssl/crypto/ec/ecp_nist.c',
'openssl/crypto/ec/ecp_nistp224.c',
'openssl/crypto/ec/ecp_nistp256.c',
'openssl/crypto/ec/ecp_nistp521.c',
'openssl/crypto/ec/ecp_nistputil.c',
'openssl/crypto/ec/ecp_oct.c',
'openssl/crypto/ec/ecp_smpl.c',
'openssl/crypto/ec/ecx_meth.c',
'openssl/crypto/engine/eng_all.c',
'openssl/crypto/engine/eng_cnf.c',
'openssl/crypto/engine/eng_cryptodev.c',
'openssl/crypto/engine/eng_ctrl.c',
'openssl/crypto/engine/eng_dyn.c',
'openssl/crypto/engine/eng_err.c',
'openssl/crypto/engine/eng_fat.c',
'openssl/crypto/engine/eng_init.c',
'openssl/crypto/engine/eng_lib.c',
'openssl/crypto/engine/eng_list.c',
'openssl/crypto/engine/eng_openssl.c',
'openssl/crypto/engine/eng_pkey.c',
'openssl/crypto/engine/eng_rdrand.c',
'openssl/crypto/engine/eng_table.c',
'openssl/crypto/engine/tb_asnmth.c',
'openssl/crypto/engine/tb_cipher.c',
'openssl/crypto/engine/tb_dh.c',
'openssl/crypto/engine/tb_digest.c',
'openssl/crypto/engine/tb_dsa.c',
'openssl/crypto/engine/tb_eckey.c',
'openssl/crypto/engine/tb_pkmeth.c',
'openssl/crypto/engine/tb_rand.c',
'openssl/crypto/engine/tb_rsa.c',
'openssl/crypto/err/err.c',
'openssl/crypto/err/err_all.c',
'openssl/crypto/err/err_prn.c',
'openssl/crypto/evp/bio_b64.c',
'openssl/crypto/evp/bio_enc.c',
'openssl/crypto/evp/bio_md.c',
'openssl/crypto/evp/bio_ok.c',
'openssl/crypto/evp/c_allc.c',
'openssl/crypto/evp/c_alld.c',
'openssl/crypto/evp/cmeth_lib.c',
'openssl/crypto/evp/digest.c',
'openssl/crypto/evp/e_aes.c',
'openssl/crypto/evp/e_aes_cbc_hmac_sha1.c',
'openssl/crypto/evp/e_aes_cbc_hmac_sha256.c',
'openssl/crypto/evp/e_bf.c',
'openssl/crypto/evp/e_camellia.c',
'openssl/crypto/evp/e_cast.c',
'openssl/crypto/evp/e_chacha20_poly1305.c',
'openssl/crypto/evp/e_des.c',
'openssl/crypto/evp/e_des3.c',
'openssl/crypto/evp/e_idea.c',
'openssl/crypto/evp/e_null.c',
'openssl/crypto/evp/e_old.c',
'openssl/crypto/evp/e_rc2.c',
'openssl/crypto/evp/e_rc4.c',
'openssl/crypto/evp/e_rc4_hmac_md5.c',
'openssl/crypto/evp/e_rc5.c',
'openssl/crypto/evp/e_seed.c',
'openssl/crypto/evp/e_xcbc_d.c',
'openssl/crypto/evp/encode.c',
'openssl/crypto/evp/evp_cnf.c',
'openssl/crypto/evp/evp_enc.c',
'openssl/crypto/evp/evp_err.c',
'openssl/crypto/evp/evp_key.c',
'openssl/crypto/evp/evp_lib.c',
'openssl/crypto/evp/evp_pbe.c',
'openssl/crypto/evp/evp_pkey.c',
'openssl/crypto/evp/m_md2.c',
'openssl/crypto/evp/m_md4.c',
'openssl/crypto/evp/m_md5.c',
'openssl/crypto/evp/m_md5_sha1.c',
'openssl/crypto/evp/m_mdc2.c',
'openssl/crypto/evp/m_null.c',
'openssl/crypto/evp/m_ripemd.c',
'openssl/crypto/evp/m_sha1.c',
'openssl/crypto/evp/m_sigver.c',
'openssl/crypto/evp/m_wp.c',
'openssl/crypto/evp/names.c',
'openssl/crypto/evp/p5_crpt.c',
'openssl/crypto/evp/p5_crpt2.c',
'openssl/crypto/evp/p_dec.c',
'openssl/crypto/evp/p_enc.c',
'openssl/crypto/evp/p_lib.c',
'openssl/crypto/evp/p_open.c',
'openssl/crypto/evp/p_seal.c',
'openssl/crypto/evp/p_sign.c',
'openssl/crypto/evp/p_verify.c',
'openssl/crypto/evp/pmeth_fn.c',
'openssl/crypto/evp/pmeth_gn.c',
'openssl/crypto/evp/pmeth_lib.c',
'openssl/crypto/evp/scrypt.c',
'openssl/crypto/ex_data.c',
'openssl/crypto/hmac/hm_ameth.c',
'openssl/crypto/hmac/hm_pmeth.c',
'openssl/crypto/hmac/hmac.c',
'openssl/crypto/idea/i_cbc.c',
'openssl/crypto/idea/i_cfb64.c',
'openssl/crypto/idea/i_ecb.c',
'openssl/crypto/idea/i_ofb64.c',
'openssl/crypto/idea/i_skey.c',
'openssl/crypto/init.c',
'openssl/crypto/kdf/hkdf.c',
'openssl/crypto/kdf/kdf_err.c',
'openssl/crypto/kdf/tls1_prf.c',
'openssl/crypto/lhash/lh_stats.c',
'openssl/crypto/lhash/lhash.c',
'openssl/crypto/md4/md4_dgst.c',
'openssl/crypto/md4/md4_one.c',
'openssl/crypto/md5/md5_dgst.c',
'openssl/crypto/md5/md5_one.c',
'openssl/crypto/mdc2/mdc2_one.c',
'openssl/crypto/mdc2/mdc2dgst.c',
'openssl/crypto/mem.c',
'openssl/crypto/mem_clr.c',
'openssl/crypto/mem_dbg.c',
'openssl/crypto/mem_sec.c',
'openssl/crypto/modes/cbc128.c',
'openssl/crypto/modes/ccm128.c',
'openssl/crypto/modes/cfb128.c',
'openssl/crypto/modes/ctr128.c',
'openssl/crypto/modes/cts128.c',
'openssl/crypto/modes/gcm128.c',
'openssl/crypto/modes/ocb128.c',
'openssl/crypto/modes/ofb128.c',
'openssl/crypto/modes/wrap128.c',
'openssl/crypto/modes/xts128.c',
'openssl/crypto/o_dir.c',
'openssl/crypto/o_fips.c',
'openssl/crypto/o_fopen.c',
'openssl/crypto/o_init.c',
'openssl/crypto/o_str.c',
'openssl/crypto/o_time.c',
'openssl/crypto/objects/o_names.c',
'openssl/crypto/objects/obj_dat.c',
'openssl/crypto/objects/obj_err.c',
'openssl/crypto/objects/obj_lib.c',
'openssl/crypto/objects/obj_xref.c',
'openssl/crypto/ocsp/ocsp_asn.c',
'openssl/crypto/ocsp/ocsp_cl.c',
'openssl/crypto/ocsp/ocsp_err.c',
'openssl/crypto/ocsp/ocsp_ext.c',
'openssl/crypto/ocsp/ocsp_ht.c',
'openssl/crypto/ocsp/ocsp_lib.c',
'openssl/crypto/ocsp/ocsp_prn.c',
'openssl/crypto/ocsp/ocsp_srv.c',
'openssl/crypto/ocsp/ocsp_vfy.c',
'openssl/crypto/ocsp/v3_ocsp.c',
'openssl/crypto/pem/pem_all.c',
'openssl/crypto/pem/pem_err.c',
'openssl/crypto/pem/pem_info.c',
'openssl/crypto/pem/pem_lib.c',
'openssl/crypto/pem/pem_oth.c',
'openssl/crypto/pem/pem_pk8.c',
'openssl/crypto/pem/pem_pkey.c',
'openssl/crypto/pem/pem_sign.c',
'openssl/crypto/pem/pem_x509.c',
'openssl/crypto/pem/pem_xaux.c',
'openssl/crypto/pem/pvkfmt.c',
'openssl/crypto/pkcs12/p12_add.c',
'openssl/crypto/pkcs12/p12_asn.c',
'openssl/crypto/pkcs12/p12_attr.c',
'openssl/crypto/pkcs12/p12_crpt.c',
'openssl/crypto/pkcs12/p12_crt.c',
'openssl/crypto/pkcs12/p12_decr.c',
'openssl/crypto/pkcs12/p12_init.c',
'openssl/crypto/pkcs12/p12_key.c',
'openssl/crypto/pkcs12/p12_kiss.c',
'openssl/crypto/pkcs12/p12_mutl.c',
'openssl/crypto/pkcs12/p12_npas.c',
'openssl/crypto/pkcs12/p12_p8d.c',
'openssl/crypto/pkcs12/p12_p8e.c',
'openssl/crypto/pkcs12/p12_sbag.c',
'openssl/crypto/pkcs12/p12_utl.c',
'openssl/crypto/pkcs12/pk12err.c',
'openssl/crypto/pkcs7/bio_pk7.c',
'openssl/crypto/pkcs7/pk7_asn1.c',
'openssl/crypto/pkcs7/pk7_attr.c',
'openssl/crypto/pkcs7/pk7_doit.c',
'openssl/crypto/pkcs7/pk7_lib.c',
'openssl/crypto/pkcs7/pk7_mime.c',
'openssl/crypto/pkcs7/pk7_smime.c',
'openssl/crypto/pkcs7/pkcs7err.c',
'openssl/crypto/poly1305/poly1305.c',
'openssl/crypto/rand/md_rand.c',
'openssl/crypto/rand/rand_egd.c',
'openssl/crypto/rand/rand_err.c',
'openssl/crypto/rand/rand_lib.c',
'openssl/crypto/rand/rand_unix.c',
'openssl/crypto/rand/rand_vms.c',
'openssl/crypto/rand/rand_win.c',
'openssl/crypto/rand/randfile.c',
'openssl/crypto/rc2/rc2_cbc.c',
'openssl/crypto/rc2/rc2_ecb.c',
'openssl/crypto/rc2/rc2_skey.c',
'openssl/crypto/rc2/rc2cfb64.c',
'openssl/crypto/rc2/rc2ofb64.c',
'openssl/crypto/rc4/rc4_enc.c',
'openssl/crypto/rc4/rc4_skey.c',
'openssl/crypto/ripemd/rmd_dgst.c',
'openssl/crypto/ripemd/rmd_one.c',
'openssl/crypto/rsa/rsa_ameth.c',
'openssl/crypto/rsa/rsa_asn1.c',
'openssl/crypto/rsa/rsa_chk.c',
'openssl/crypto/rsa/rsa_crpt.c',
'openssl/crypto/rsa/rsa_depr.c',
'openssl/crypto/rsa/rsa_err.c',
'openssl/crypto/rsa/rsa_gen.c',
'openssl/crypto/rsa/rsa_lib.c',
'openssl/crypto/rsa/rsa_meth.c',
'openssl/crypto/rsa/rsa_none.c',
'openssl/crypto/rsa/rsa_null.c',
'openssl/crypto/rsa/rsa_oaep.c',
'openssl/crypto/rsa/rsa_ossl.c',
'openssl/crypto/rsa/rsa_pk1.c',
'openssl/crypto/rsa/rsa_pmeth.c',
'openssl/crypto/rsa/rsa_prn.c',
'openssl/crypto/rsa/rsa_pss.c',
'openssl/crypto/rsa/rsa_saos.c',
'openssl/crypto/rsa/rsa_sign.c',
'openssl/crypto/rsa/rsa_ssl.c',
'openssl/crypto/rsa/rsa_x931.c',
'openssl/crypto/rsa/rsa_x931g.c',
'openssl/crypto/seed/seed.c',
'openssl/crypto/seed/seed_cbc.c',
'openssl/crypto/seed/seed_cfb.c',
'openssl/crypto/seed/seed_ecb.c',
'openssl/crypto/seed/seed_ofb.c',
'openssl/crypto/sha/sha1_one.c',
'openssl/crypto/sha/sha1dgst.c',
'openssl/crypto/sha/sha256.c',
'openssl/crypto/sha/sha512.c',
'openssl/crypto/srp/srp_lib.c',
'openssl/crypto/srp/srp_vfy.c',
'openssl/crypto/stack/stack.c',
'openssl/crypto/threads_none.c',
'openssl/crypto/threads_pthread.c',
'openssl/crypto/threads_win.c',
'openssl/crypto/ts/ts_asn1.c',
'openssl/crypto/ts/ts_conf.c',
'openssl/crypto/ts/ts_err.c',
'openssl/crypto/ts/ts_lib.c',
'openssl/crypto/ts/ts_req_print.c',
'openssl/crypto/ts/ts_req_utils.c',
'openssl/crypto/ts/ts_rsp_print.c',
'openssl/crypto/ts/ts_rsp_sign.c',
'openssl/crypto/ts/ts_rsp_utils.c',
'openssl/crypto/ts/ts_rsp_verify.c',
'openssl/crypto/ts/ts_verify_ctx.c',
'openssl/crypto/txt_db/txt_db.c',
'openssl/crypto/ui/ui_err.c',
'openssl/crypto/ui/ui_lib.c',
'openssl/crypto/ui/ui_openssl.c',
'openssl/crypto/ui/ui_util.c',
'openssl/crypto/uid.c',
'openssl/crypto/whrlpool/wp_block.c',
'openssl/crypto/whrlpool/wp_dgst.c',
'openssl/crypto/x509/by_dir.c',
'openssl/crypto/x509/by_file.c',
'openssl/crypto/x509/t_crl.c',
'openssl/crypto/x509/t_req.c',
'openssl/crypto/x509/t_x509.c',
'openssl/crypto/x509/x509_att.c',
'openssl/crypto/x509/x509_cmp.c',
'openssl/crypto/x509/x509_d2.c',
'openssl/crypto/x509/x509_def.c',
'openssl/crypto/x509/x509_err.c',
'openssl/crypto/x509/x509_ext.c',
'openssl/crypto/x509/x509_lu.c',
'openssl/crypto/x509/x509_meth.c',
'openssl/crypto/x509/x509_obj.c',
'openssl/crypto/x509/x509_r2x.c',
'openssl/crypto/x509/x509_req.c',
'openssl/crypto/x509/x509_set.c',
'openssl/crypto/x509/x509_trs.c',
'openssl/crypto/x509/x509_txt.c',
'openssl/crypto/x509/x509_v3.c',
'openssl/crypto/x509/x509_vfy.c',
'openssl/crypto/x509/x509_vpm.c',
'openssl/crypto/x509/x509cset.c',
'openssl/crypto/x509/x509name.c',
'openssl/crypto/x509/x509rset.c',
'openssl/crypto/x509/x509spki.c',
'openssl/crypto/x509/x509type.c',
'openssl/crypto/x509/x_all.c',
'openssl/crypto/x509/x_attrib.c',
'openssl/crypto/x509/x_crl.c',
'openssl/crypto/x509/x_exten.c',
'openssl/crypto/x509/x_name.c',
'openssl/crypto/x509/x_pubkey.c',
'openssl/crypto/x509/x_req.c',
'openssl/crypto/x509/x_x509.c',
'openssl/crypto/x509/x_x509a.c',
'openssl/crypto/x509v3/pcy_cache.c',
'openssl/crypto/x509v3/pcy_data.c',
'openssl/crypto/x509v3/pcy_lib.c',
'openssl/crypto/x509v3/pcy_map.c',
'openssl/crypto/x509v3/pcy_node.c',
'openssl/crypto/x509v3/pcy_tree.c',
'openssl/crypto/x509v3/v3_addr.c',
'openssl/crypto/x509v3/v3_akey.c',
'openssl/crypto/x509v3/v3_akeya.c',
'openssl/crypto/x509v3/v3_alt.c',
'openssl/crypto/x509v3/v3_asid.c',
'openssl/crypto/x509v3/v3_bcons.c',
'openssl/crypto/x509v3/v3_bitst.c',
'openssl/crypto/x509v3/v3_conf.c',
'openssl/crypto/x509v3/v3_cpols.c',
'openssl/crypto/x509v3/v3_crld.c',
'openssl/crypto/x509v3/v3_enum.c',
'openssl/crypto/x509v3/v3_extku.c',
'openssl/crypto/x509v3/v3_genn.c',
'openssl/crypto/x509v3/v3_ia5.c',
'openssl/crypto/x509v3/v3_info.c',
'openssl/crypto/x509v3/v3_int.c',
'openssl/crypto/x509v3/v3_lib.c',
'openssl/crypto/x509v3/v3_ncons.c',
'openssl/crypto/x509v3/v3_pci.c',
'openssl/crypto/x509v3/v3_pcia.c',
'openssl/crypto/x509v3/v3_pcons.c',
'openssl/crypto/x509v3/v3_pku.c',
'openssl/crypto/x509v3/v3_pmaps.c',
'openssl/crypto/x509v3/v3_prn.c',
'openssl/crypto/x509v3/v3_purp.c',
'openssl/crypto/x509v3/v3_skey.c',
'openssl/crypto/x509v3/v3_sxnet.c',
'openssl/crypto/x509v3/v3_tlsf.c',
'openssl/crypto/x509v3/v3_utl.c',
'openssl/crypto/x509v3/v3err.c',
'openssl/engines/e_capi.c',
'openssl/engines/e_padlock.c',
],
'openssl_sources_linux-x32': [
],
'openssl_defines_linux-x32': [
'DSO_DLFCN',
'HAVE_DLFCN_H',
'NDEBUG',
'OPENSSL_THREADS',
'OPENSSL_NO_DYNAMIC_ENGINE',
'OPENSSL_PIC',
],
'openssl_cflags_linux-x32': [
'-Wall -O3 -pthread -mx32 -DL_ENDIAN',
],
'openssl_ex_libs_linux-x32': [
'-ldl -pthread',
],
},
'include_dirs': [
'.',
'./include',
'./crypto',
'./crypto/include/internal',
],
'defines': ['<@(openssl_defines_linux-x32)'],
'cflags' : ['<@(openssl_cflags_linux-x32)'],
'libraries': ['<@(openssl_ex_libs_linux-x32)'],
'sources': ['<@(openssl_sources)', '<@(openssl_sources_linux-x32)'],
}
|
[
"59814509@qq.com"
] |
59814509@qq.com
|
09027e22728fd2c90a2f9e1cff4543b34182fa2d
|
2113e5eac65f527e86eefcc5001d978c0a3e64a6
|
/server.py
|
917de850a3b7d86c2b1821dac7615abfab8110da
|
[] |
no_license
|
Oksvol/D2-10-Homework
|
42c0b8bd6873e8ee428f847b173448a0f6bef05b
|
4f211da25a05137e8b7ea5c9419143782439bbfa
|
refs/heads/main
| 2023-02-18T20:03:32.557687
| 2021-01-13T18:05:03
| 2021-01-13T18:05:03
| 329,385,301
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 746
|
py
|
import os
import sentry_sdk
from bottle import run, route, HTTPResponse
from sentry_sdk.integrations.bottle import BottleIntegration
from userconf import USER_DSN
sentry_sdk.init(
dsn=USER_DSN,
integrations=[BottleIntegration()]
)
@route("/")
def hello_page():
return HTTPResponse(status=200, body="Приветик!")
@route('/fail')
def index_fail():
raise RuntimeError("Ошибка!")
@route('/success')
def index_success():
return HTTPResponse(status=200, body="200 OK")
if os.environ.get("APP_LOCATION") == "heroku":
run(
host="0.0.0.0",
port=int(os.environ.get("PORT", 5000)),
server="gunicorn",
workers=3,
)
else:
run(host="localhost", port=8080, debug=True)
|
[
"noreply@github.com"
] |
noreply@github.com
|
eec70be6f1347e0c67b92c7a3a0234739131b6ec
|
41d579a0e17b9fb6b1994168f1a1857788e850c2
|
/part03-e08_almost_meeting_lines/src/almost_meeting_lines.py
|
ac63d387528cda8632354b0e60ff99788a96fd4e
|
[] |
no_license
|
clementeqp/Analisis_de_Datos_Python_2021
|
9daac062e8b64357d56592d65bdbd2cfb79eecc3
|
7c1025b974fde8ffee755d63a72329b84c965813
|
refs/heads/master
| 2023-06-19T03:25:44.346580
| 2021-07-11T07:00:14
| 2021-07-11T07:00:14
| 383,727,665
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 933
|
py
|
#!/usr/bin/python3
import numpy as np
def almost_meeting_lines(a1, b1, a2, b2):
return []
def main():
a1=1
b1=2
a2=-1
b2=0
(x, y), exact = almost_meeting_lines(a1, b1, a2, b2)
if exact:
print(f"Lines meet at x={x} and y={y}")
a1=a2=1
b1=2
b2=-2
(x, y), exact = almost_meeting_lines(a1, b1, a1, b2)
if exact:
print(f"Lines meet at x={x} and y={y}")
else:
print(f"Closest point at x={x} and y={y}")
a1=1
b1=2
(x, y), exact = almost_meeting_lines(a1, b1, a1, b1)
if exact:
print(f"Lines meet at x={x} and y={y}")
else:
print(f"Closest point at x={x} and y={y}")
a1=1
b1=2
a2=1
b2=1
(x, y), exact = almost_meeting_lines(a1, b1, a2, b2)
if exact:
print(f"Lines meet at x={x} and y={y}")
else:
print(f"Closest point at x={x} and y={y}")
if __name__ == "__main__":
main()
|
[
"clementeqp@hotmail.com"
] |
clementeqp@hotmail.com
|
09b2b9ce9f10a6ff28cd54739a2cd1fa4975567f
|
d0ec18e7111bd96cf4a5ed5336c4878a17f13255
|
/config.py
|
cdd9028d4c01177b55efe73cc336e149b9772f29
|
[] |
no_license
|
elCalmo/Buddylift
|
21e310d604ee5d49bd86ca4bd2834e9bc646fcad
|
7beac9facc5b2ddb369103322293ba00a88d8fb2
|
refs/heads/master
| 2020-05-01T00:16:53.682749
| 2019-03-22T15:35:03
| 2019-03-22T15:35:03
| 177,165,302
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 537
|
py
|
import os
basedir = os.path.abspath(os.path.dirname(__file__))
secret_key = "~Xl\x84A\x95\xec\xca\x0c\x18\x86`%\\\xef\xa0\xd8\tV\xd8\xc3\xf2\x1dd"
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or secret_key
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
[
"noreply@github.com"
] |
noreply@github.com
|
bf066b0c96bc34015aad76b1865d66ea72737187
|
ba527be278797cf60d7c34bd8dae7c56ceb35820
|
/scripts/model_tuning.py
|
91b654dca0e95496b245d8f2b1f3b5d4ea90f9e1
|
[] |
no_license
|
bl-m/HomeCredit
|
a9ee23675bc9adb3ff981e91dcc2a86ccad11d0f
|
e60e02a4e54861981b7491a26ad3d5489376cbcc
|
refs/heads/master
| 2022-12-27T04:10:30.429719
| 2020-09-19T09:54:26
| 2020-09-19T09:54:26
| 296,838,836
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,628
|
py
|
"""Model tuning scripti calistiginda hyperparameters klasörüne iki sonuc uretecek:
hyperparameters.pkl
lightgbm_model.pkl
"""
import os
import pickle
from lightgbm import LGBMClassifier
import pandas as pd
from sklearn.model_selection import GridSearchCV
lgbm = LGBMClassifier()
lgbm_params = {"learning_rate": [0.01, 0.1],
"n_estimators": [200, 100]}
df = pd.read_pickle("data/final_train_df.pkl")
y_train = df["TARGET"]
X_train = df.drop("TARGET", axis=1)
lgbm_cv_model = GridSearchCV(lgbm,
lgbm_params,
cv=5,
n_jobs=-1,
verbose=2).fit(X_train, y_train)
params = lgbm_cv_model.best_params_
# saving hyperparameters and model
cur_dir = os.getcwd()
os.chdir('outputs/hyperparameters/')
pickle.dump(params, open("hyperparameters.pkl", 'wb')) # hyperparameters
pickle.dump(lgbm_cv_model, open("lightgbm_model.pkl", 'wb')) # model
os.chdir(cur_dir)
print("Best hyperparameters", params)
# loading and prediction with model
# del lgbm_cv_model
# cur_dir = os.getcwd()
# os.chdir('/Users/mvahit/Documents/GitHub/home_credit/hyperparameters/')
# model = pickle.load(open('lightgbm_model.pkl', 'rb'))
# os.chdir(cur_dir)
# model.predict(X_train.head())
# loading hyperparameters
# del params
# cur_dir = os.getcwd()
# os.chdir('/Users/mvahit/Documents/GitHub/home_credit/hyperparameters/')
# params = pickle.load(open('hyperparameters.pkl', 'rb'))
# final_lgbm = LGBMClassifier(**params).fit(X_train, y_train)
# final_lgbm.get_params()
# final_lgbm.predict(X_train.head())
|
[
"m.vahitkeskin@gmail.com"
] |
m.vahitkeskin@gmail.com
|
4cf487e4b92d1e27036830b85c8d01462301077d
|
b88c7025dac49cf9e933074062c47b04e75a7f42
|
/test/test_imports.py
|
be0f39e81206a9504e567f7d43826cd2241231f5
|
[
"MIT"
] |
permissive
|
theendsofinvention/elib_logging
|
2e45b574e30f2267266dfcda6af6762fc94f89f1
|
35f5830830ebe90d48c44a008850b2fd5bb9971c
|
refs/heads/master
| 2020-03-20T19:25:52.157944
| 2018-06-17T14:34:30
| 2018-06-17T14:34:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 538
|
py
|
# coding=utf-8
"""
Dummy test to make sure everything is importable
"""
import glob
import pytest
@pytest.mark.nocleandir
@pytest.mark.parametrize('module_', glob.glob('./elib_logging/**/*.py', recursive=True))
def test_imports(module_):
module_ = module_[2:-3].replace('\\', '.')
__import__(module_)
@pytest.mark.nocleandir
@pytest.mark.parametrize('module_', list(glob.glob('./elib_logging/**/*.py', recursive=True)))
def test_imports_tests(module_):
module_ = module_[2:-3].replace('\\', '.')
__import__(module_)
|
[
"132nd-etcher@daribouca.net"
] |
132nd-etcher@daribouca.net
|
19b229e6e52bf90036dbd810bcd8227145b3ad0a
|
764d2597021f3bb39a4076a96cb976e44b12b3d8
|
/chatbot.py
|
220b52f2fd8e72e676214aad08002ed7dbe6c53e
|
[] |
no_license
|
tristanbriseno/chatbot.py
|
50ef213ae2e928254b86319907f16a910737b38d
|
c395ad8501d8478a98d1d55eb9bc765e75841e68
|
refs/heads/master
| 2022-12-18T05:09:37.388849
| 2020-09-22T21:10:04
| 2020-09-22T21:10:04
| 297,402,187
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,759
|
py
|
from random import choice
#I basically used the example that was provided for this project as a blueprint for my chat bot.
#what is happening here is that the code is using a psudo-code called random that acts as an rng and selects amoungst the choices provided.
def get_rude_bot_response(user_response):
#Here I am defining that get_rude_bot_response
bot_response_good = ["Oh, my bad! I didnt mean to make you think I care.", "Alright good talk", "oh, sorry, gotta take this call", "Awe man i just remembered, I've got this thing I gotta do, so yeah....Tootles!"]
#here I am making 2 lists of reponses based off of the imput from the user
bot_response_bad = ["But did you die?", " Are you always such an idiot, or do you just show off when I’m around?", "Are you about to cry?", ".............Oh did you say somethin?", "ZzzZzzZzzZzzZzzZzz" ]
#here it is saying that if the user inputs good then respond with bot_response_good and if the user inputs bad then respond with bot_response_bad else return the text provided.
if user_response == "good":
return choice(bot_response_good)
elif user_response == "bad" :
return choice(bot_response_bad)
else:
return " Yeah, I'm gonna be honest I wast really paying attention just now.... soooo, what were you saying?"
#here the bot is being introduced and the user is given instructions on how to operate the bot.
print(" Welcome to Rude Bot")
print(" Do you feel good or bad?")
user_response = ""
while True:
user_response = input(" Hey, whatsup?: ")
#this basically ends the code if you input done. Otherwise the input request will repeate infinitly
if user_response == 'done':
break
bot_response = get_rude_bot_response(user_response)
print(bot_response)
|
[
"noreply@github.com"
] |
noreply@github.com
|
bbf650f23013a510fc45f9db197e856f4b58345a
|
c47f5ce7cc9b4ab5bc1640c5cc7457b239a17bb4
|
/project_counter/urls.py
|
e2e842c6db0ee0a0dbcada7f70f3e5190ad4e353
|
[] |
no_license
|
Nathan-B21/django_counter
|
97e7b2a8f63c58efebd3f341a3f24bcc11effb46
|
83f4bb49fcd47101434184c494f301a0b1c69c78
|
refs/heads/main
| 2023-03-21T11:03:34.601541
| 2021-03-18T22:08:54
| 2021-03-18T22:08:54
| 349,229,866
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 739
|
py
|
"""project_counter URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path, include
urlpatterns = [
path('', include('app_counter.urls')),
]
|
[
"nathanbludworth@gmail.com"
] |
nathanbludworth@gmail.com
|
10db9f571de7104e695842119b89770f6cba2767
|
44e6cd0127f9bf9487ab9c0e4c46222876b45e42
|
/modele/model_02.py
|
a073f6721bf5e1a74979ae3622b17c65d2792a5a
|
[] |
no_license
|
andreimardare05/python-lab-2020
|
e6f143c69377307e52c8730eb50219928703e651
|
06e225d3bcc0c1553492e748aeb581062604fbbf
|
refs/heads/master
| 2022-11-13T09:34:18.176453
| 2020-07-15T22:04:56
| 2020-07-15T22:04:56
| 279,989,747
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,891
|
py
|
import re
import socket
import urllib
import hashlib
from urllib import request
import json
import zipfile
import os
def problema2(url, cheie):
result = json.loads(request.urlopen(url).read().decode())
return result[cheie][-1]
print(problema2("https://pastebin.com/raw/PzM422T2", "abc"))
def problema4(lista_arhive):
result = set()
for item in lista_arhive:
z = zipfile.ZipFile(item)
for item_archive in z.infolist():
if not item_archive.is_dir():
result.add(os.path.basename(item_archive.filename))
z.close()
return list(result)
print(problema4(
["model_test.zip", "test_zip_p6_another_test.zip", "test_zip_p6.zip"]))
def problema5(url):
dictionar = json.loads(urllib.request.urlopen(url).read().decode())
print(dictionar)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print((dictionar["ip"], dictionar["port"]))
s.connect((dictionar["ip"], dictionar["port"]))
text = dictionar["info"]
s.send(text.encode())
text = s.recv(10)
return text.decode().count('A')
def problema1(s):
items = re.findall(r"[a-zA-Z]+", s)
return max(items, key=lambda x: len(x))
# print(problema5("https://pastebin.com/raw/SqhP9AAU"))
print(problema1("azi, 22ianuarie2019 dau testul 2 la python3.xx"))
def problema1_v2(s):
result = re.findall("[02468]+", s)
return sorted(result, reverse=True)
print(problema1_v2("azi, 22ianuarie2019 dau testul 2 la python3.xx"))
def problema3(path):
result = {}
for root, dirs, files in os.walk(path, topdown=True):
for fn in files:
result.setdefault.md5(fn.encode().hexdigest(),
os.path.getsize(os.path.join(root, fn)))
return result
def problema1(my_str):
return re.sub("([a-z])([A-Z])", r"\1_\2", my_str).lower()
print(problema1("UpperCamelCase"))
|
[
"andreimardare05@outlook.com"
] |
andreimardare05@outlook.com
|
2bb80d3e76ad8eeb95f106c44017b8529377a982
|
b715c79f52cf2c95927c19edf8f6d64f5322bf7d
|
/PJLink/start_kernel.py
|
94e029381f90239bda03ffb6c2dba92292df92be
|
[
"MIT"
] |
permissive
|
sunt05/PJLink
|
4d6805b07070c0a2c7452464358ebcf075eeabb0
|
cd623efebf4ddae8c5ea75b3ee08fe9819e78b40
|
refs/heads/master
| 2020-03-29T05:46:10.707576
| 2018-09-20T07:36:51
| 2018-09-20T07:36:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,842
|
py
|
"""start_kernel is a convenience script for starting a kernel thread in python
"""
import sys, os, argparse
sys.stdout.flush()
true_file = os.path.abspath(__file__)
sys.path.insert(0, os.path.dirname(os.path.dirname(true_file)))
from PJLink import *
### I should do a lot more argparsing... but I don't
parser = argparse.ArgumentParser(description='Start a PJLink kernel.')
parser.add_argument('--blocking', dest='block', type=bool, nargs='?', default=False,
help='whether the kernel should block or not')
parser.add_argument('--debug', dest='debug', type=int, nargs='?', default=0,
help='debug level for underlying PJLink lib')
parser.add_argument('-linkname', dest='name', type=str, nargs='?',
help='name for the link')
parser.add_argument('-linkmode', dest='mode', type=str, nargs='?',
help='mode for the link')
parser.add_argument('-linkprotocol', dest='protocol', type=str, nargs='?',
help='protocol for the link')
parser = parser.parse_args()
blocking = parser.block
debug = parser.debug
name = parser.name
mode = parser.mode
protocol = parser.protocol
opts = { 'linkname' : parser.name, 'linkmode' : parser.mode, 'linkprotocol' : parser.protocol }
opts = [ ('-'+k, v) for k, v in opts.items() if v is not None]
init = [ None ] * (2 * len(opts))
for i, t in enumerate(opts):
init[2*i] = t[0]
init[2*i+1] = t[1]
reader = create_reader_link(init=init, debug_level=debug)
# print(reader.link.drain())
# stdout = open(os.path.expanduser("~/Desktop/stdout.txt"), "w+")
# stderr = open(os.path.expanduser("~/Desktop/stderr.txt"), "w+")
# sys.stdout = stdout
# sys.stderr = stderr
if blocking:
# reader.run()
# else:
import code
code.interact(banner = "", local={"Kernel":reader.link, "KernelReader":reader})
|
[
"b3m2a1@gmail.com"
] |
b3m2a1@gmail.com
|
86ca70ec064a1b497a8d74d0e3d0844b4fa7c668
|
3e1d9a25426e2a157a69f3c4c6c41b5216deb8de
|
/LeetCode/Python/Easy/Heaters.py
|
749d9559b5c23d9ae2cfa22db847e1981c3ed067
|
[] |
no_license
|
jashansudan/Data-Structures-and-Algorithms
|
4e420586bc773c5fc35b7ce7be369ca92bf51898
|
e38cfb49b3f9077f47f1053207f4e44c7726fb90
|
refs/heads/master
| 2021-01-12T10:47:05.754340
| 2018-02-13T01:01:50
| 2018-02-13T01:01:50
| 72,697,093
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 412
|
py
|
class Solution(object):
def findRadius(self, houses, heaters):
houses.sort()
heaters.sort()
i, maxDistance = 0, 0
for house in houses:
while (i < len(heaters) - 1 and
abs(heaters[i] - house) >= abs(heaters[i + 1] - house)):
i += 1
maxDistance = max(maxDistance, abs(heaters[i] - house))
return maxDistance
|
[
"jashansudan@gmail.com"
] |
jashansudan@gmail.com
|
688b77feb6f806d7f71b863600adf9b1853ed15a
|
20496b6f0e3b89e1d68d8f062cd0e62d32a1a1ad
|
/assn2/countchar.py
|
5aaa5a7729676d8cd2a85d27b3719c6f11ef9fd4
|
[] |
no_license
|
sushil246/myfirstrepo
|
9a5636dd4b1475fb21009b6a336d5fc450c52789
|
3b76be6c3c348188f82d92eae065b7fafef2a829
|
refs/heads/master
| 2020-07-05T20:00:50.573268
| 2019-09-17T13:14:35
| 2019-09-17T13:14:35
| 202,757,980
| 0
| 0
| null | 2019-08-16T16:38:35
| 2019-08-16T15:59:14
|
HTML
|
UTF-8
|
Python
| false
| false
| 290
|
py
|
dictc = {}
inp = raw_input ("Enetr the String for Char to be counted \n")
def charcount(inp):
for i in inp:
if i in dictc.keys():
dictc[i] +=1
else:
dictc[i]= 1
for k ,v in dictc.items():
print (k , v)
print(dictc)
charcount(inp)
|
[
"test@xyz.com"
] |
test@xyz.com
|
aa34e99e6688b816416a6cb3f0f75eb072591f17
|
57c8da3715d5c096f9ab1b9fb03f9a3388b74162
|
/Tracker/models.py
|
e3acef1131b6727d2116ece6778299c27ae30175
|
[] |
no_license
|
SRI-VISHVA/HealthX
|
b269ef3b74248c9f24eda46d37fed5c80251900e
|
94f8c7d876946ed35262147d214cadcafe1bb613
|
refs/heads/master
| 2022-12-30T06:21:05.562037
| 2020-10-26T05:51:52
| 2020-10-26T05:51:52
| 288,995,999
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,298
|
py
|
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Meal(models.Model):
userfk = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=15)
quantity = models.FloatField()
kcal = models.FloatField()
date = models.DateField(default=timezone.now)
def __str__(self):
return f"User {self.userfk}: meal {self.name} with {self.kcal, self.quantity} kcal, on {self.date}"
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
goal_cals = models.FloatField(blank=True, null=True, default='2000')
class Video(models.Model):
name = models.CharField(max_length=500)
videofile = models.FileField(upload_to='videos/', null=True, verbose_name="")
def __str__(self):
return self.name + ": " + str(self.videofile)
class FoodRecipe(models.Model):
dish_name = models.CharField(max_length=100)
ingredients = models.CharField(max_length=500)
type = models.CharField(max_length=15)
instruction = models.TextField()
time_taken = models.IntegerField()
kcal = models.FloatField()
cuisine = models.CharField(max_length=20, default='south-indian')
def __str__(self):
return self.dish_name
|
[
"srivishvaelango@gmail.com"
] |
srivishvaelango@gmail.com
|
d3200416507538355822402d48c6102e6eac1710
|
db1872a7014cc9422a233df843a705380fdc3d5c
|
/neural_network.py
|
aa619c462fdea8ea056ea56150652777cbf911d3
|
[] |
no_license
|
Mithul/bot-bot
|
2a9c57b912fd16bfc17ab435ced73efb08b37f45
|
53cbfd63cac51f87e24cf5838d369ed30638819c
|
refs/heads/master
| 2021-06-16T14:23:52.917258
| 2017-05-10T20:19:43
| 2017-05-10T20:19:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,086
|
py
|
"""
This module implements the neural network class and all components necessary to
modularize the build/use process of the neural network.
"""
import numpy as np
import pickle
import os
import h5py
# create NN using Keras
from keras.models import Sequential, load_model
from keras.layers import Activation
from keras.optimizers import SGD
from keras.layers import Dense
from keras.utils import np_utils
from keras import initializers
# fix random seed for reproducibility
np.random.seed()
class NeuralNet:
def __init__(self, layers=None, activation_fns=None, model_file=None, bias = False):
if model_file != None:
self.model = load_model(model_file)
else:
self.model = Sequential()
self.model.add(Dense(layers[0], input_dim=2, init=initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None), activation=activation_fns[0], use_bias=False))
self.model.add(Dense(layers[1], init="random_uniform", activation=activation_fns[0]))
self.model.add(Dense(layers[2]))
self.model.add(Activation(activation_fns[1]))
self.model.compile(loss='mean_squared_error', optimizer='rmsprop')
def output(self, input):
pred = self.model.predict(np.array([np.array(input)]).reshape((1,2)))[0]
pred = [1 if i == max(pred) else 0 for i in pred]
return pred
# return [1., 0, 0, 0]
def get_all_weights(self):
# need weights of layers 1 & 2 - everything except first and last
w = []
# # print "No of layers: ", len(self.model.layers)
for i in xrange(1,len(self.model.layers)-1):
# # print self.model.layers[i].get_weights()
w.append(self.model.layers[i].get_weights())
return w
def set_all_weights(self, weights):
for i in xrange(1,len(self.model.layers)-1):
# w = np.array(weights[i-1])
self.model.layers[i].set_weights(weights[i-1])
# class NNetwork:
# """
# The representation of a feed forward neural network with a bias in every
# layer (excluding output layer obviously).
# """
# def __init__(self, layer_sizes, activation_funcs, bias_neuron = False):
# """
# Creates a 'NNetwork'. 'layer_sizes' provides information about the
# number of neurons in each layer, as well as the total number of layers
# in the neural network. 'activation_funcs' provides information about the
# activation functions to use on each respective hidden layers and output
# layer. This means that the length of 'activation_funcs' is always one
# less than the length of 'layer_sizes'.
# """
# assert(len(layer_sizes) >= 2)
# assert(len(layer_sizes) - 1 == len(activation_funcs))
# assert(min(layer_sizes) >= 1)
# self.layers = []
# self.connections = []
# # Initialize layers.
# for i in range(len(layer_sizes)):
# # Input layer.
# if i == 0:
# self.layers.append(Layer(layer_sizes[i], None, bias_neuron))
# # Hidden layer.
# elif i < len(layer_sizes) - 1:
# self.layers.append(Layer(layer_sizes[i], activation_funcs[i - 1], bias_neuron))
# # Output layer.
# else:
# self.layers.append(Layer(layer_sizes[i], activation_funcs[i - 1]))
# # Initialize connections.
# num_connections = len(layer_sizes) - 1
# for i in range(num_connections):
# self.connections.append(Connection(self.layers[i], self.layers[i + 1]))
# def feed_forward(self, data, one_hot_encoding = True):
# """
# Feeds given data through neural network and stores output in output
# layer's data field. Output can optionally be one-hot encoded.
# """
# if self.layers[0].HAS_BIAS_NEURON:
# assert(len(data) == self.layers[0].SIZE - 1)
# self.layers[0].data = data
# self.layers[0].data.append(1)
# else:
# assert(len(data) == self.layers[0].SIZE)
# self.layers[0].data = data
# for i in range(len(self.connections)):
# self.connections[i].TO.data = np.dot(self.layers[i].data, self.connections[i].weights)
# self.connections[i].TO.activate()
# if one_hot_encoding:
# this_data = self.layers[len(self.layers) - 1].data
# MAX = max(this_data)
# for i in range(len(this_data)):
# if this_data[i] == MAX:
# this_data[i] = 1
# else:
# this_data[i] = 0
# def output(self):
# """
# Retrieves data in output layer.
# """
# return self.layers[len(self.layers) - 1].data
# class Layer:
# """
# The representation of a layer in a neural network. Used as a medium for
# passing data through the network in an efficent manner.
# """
# def __init__(self, num_neurons, activation_func, bias_neuron = False):
# """
# Creates a 'Layer' with 'num_neurons' and an additional (optional) bias
# neuron (which always has a value of '1'). The layer will utilize the
# 'activation_func' during activation.
# """
# assert(num_neurons > 0)
# self.ACTIVATION_FUNC = activation_func
# self.HAS_BIAS_NEURON = bias_neuron
# if bias_neuron:
# self.SIZE = num_neurons + 1
# self.data = np.array([0] * num_neurons + [1])
# else:
# self.SIZE = num_neurons
# self.data = np.array([0] * num_neurons)
# def activate(self):
# """
# Calls activation function on layer's data.
# """
# if self.ACTIVATION_FUNC != None:
# self.ACTIVATION_FUNC(self.data)
# class Connection:
# """
# The representation of a connection between layers in a neural network.
# """
# def __init__(self, layer_from, layer_to):
# """"
# Creates a 'Connection' between 'layer_from' and 'layer_to' that contains
# all required weights, which are randomly initialized with random numbers
# in a guassian distribution of mean '0' and standard deviation '1'.
# """
# self.FROM = layer_from
# self.TO = layer_to
# self.weights = np.zeros((layer_from.SIZE, layer_to.SIZE))
# for i in range(layer_from.SIZE):
# for j in range(layer_to.SIZE):
# self.weights[i][j] = np.random.standard_normal()
# def sigmoid(data):
# """
# Uses sigmoid transformation on given data. This is an activation function.
# """
# for i in range(len(data)):
# data[i] = 1 / (1 + np.exp(-data[i]))
# def softmax(data):
# """
# Uses softmax transformation on given data. This is an activation function.
# """
# sum = 0.0
# for i in range(len(data)):
# sum += np.exp(data[i])
# for i in range(len(data)):
# data[i] = np.exp(data[i]) / sum
|
[
"shriya.sasank@gmail.com"
] |
shriya.sasank@gmail.com
|
ef1dee427fd1886305f8a5488e392f4572706fde
|
bc9cb3f0f104778026ca6f3a07595dd5d6ce840f
|
/DIA_01/introducao_python/aula/linguagem_python/05_conversao_de_tipos/exemplo_03.py
|
ba7db84a4bd8944411f327a1af919b84d29843a2
|
[] |
no_license
|
JohnRhaenys/escola_de_ferias
|
ff7a5d7f399459725f3852ca6ee200486f29e7d4
|
193364a05a5c7ccb2e5252c150745d6743738728
|
refs/heads/master
| 2023-01-12T11:30:46.278703
| 2020-11-19T14:59:10
| 2020-11-19T14:59:10
| 314,278,831
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 138
|
py
|
# Convertendo float para string
real = 1.23
print(real)
print(type(real))
print()
string = str(real)
print(string)
print(type(string))
|
[
"joao.estrela@sga.pucminas.br"
] |
joao.estrela@sga.pucminas.br
|
71ab02075251ae94585f95c3374a589be9d31c19
|
fc0ceb3a10511108d476ace8bf2c9479c72f5802
|
/pinhole_model/calibrate.py
|
c4db5d22e4384350ced9a01360375ad3405cb8e6
|
[] |
no_license
|
robotique-ecam/new_camera_calibration
|
a824b7e2b1e0878925e65019808870e4be93b7bc
|
dd0f6d4a4a6e2ea9ae4b847f263cee3a2a607e0b
|
refs/heads/main
| 2023-04-23T16:07:03.727814
| 2021-04-24T17:05:13
| 2021-04-24T17:05:13
| 355,595,934
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,342
|
py
|
#!/usr/bin/env python
import cv2
import numpy as np
import os
import glob
def get_repo_directory():
return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
# Defining the dimensions of checkerboard
CHECKERBOARD = (6, 9)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Creating vector to store vectors of 3D points for each checkerboard image
objpoints = []
# Creating vector to store vectors of 2D points for each checkerboard image
imgpoints = []
# Defining the world coordinates for 3D points
objp = np.zeros((1, CHECKERBOARD[0] * CHECKERBOARD[1], 3), np.float32)
objp[0, :, :2] = np.mgrid[0 : CHECKERBOARD[0], 0 : CHECKERBOARD[1]].T.reshape(-1, 2)
prev_img_shape = None
# Extracting path of individual image stored in a given directory
images = glob.glob(
get_repo_directory() + "/calibration_imgs/pinhole_model_from_fisheye_undistrorded_pictures_set/*.jpg"
)
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chess board corners
# If desired number of corners are found in the image then ret = true
ret, corners = cv2.findChessboardCorners(
img,
CHECKERBOARD,
cv2.CALIB_CB_ADAPTIVE_THRESH
+ cv2.CALIB_CB_FAST_CHECK
+ cv2.CALIB_CB_NORMALIZE_IMAGE,
)
"""
If desired number of corner are detected,
we refine the pixel coordinates and display
them on the images of checker board
"""
if ret == True:
objpoints.append(objp)
# refining pixel coordinates for given 2d points.
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners2)
# Draw and display the corners
img = cv2.drawChessboardCorners(img, CHECKERBOARD, corners2, ret)
resized = cv2.resize(img.copy(), (1777, 1000), interpolation=cv2.INTER_AREA)
cv2.imshow("img", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
h, w = img.shape[:2]
"""
Performing camera calibration by
passing the value of known 3D points (objpoints)
and corresponding pixel coordinates of the
detected corners (imgpoints)
"""
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(
objpoints, imgpoints, gray.shape[::-1], None, None
)
print("Camera matrix : \n")
print(mtx)
print("dist : \n")
print(dist)
|
[
"phileas.lambert@gmail.com"
] |
phileas.lambert@gmail.com
|
0b932e715a494e4c49568f1ef587818d13da9347
|
dc197104eb160fbeae1d2b62ec3cb909714b0152
|
/COMET/misc_plugins/Ueye_camera/pyueye_gui.py
|
141316d645e8bd951c00c22309973b7dd3816a0f
|
[
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only"
] |
permissive
|
Chilldose/COMET
|
810ecec6f0fe7f544ae8207c25b2176a0145f56b
|
121e5c0530f5195a8f7c6b8de96a1653322f6e48
|
refs/heads/master
| 2021-06-04T10:07:08.830370
| 2021-05-11T07:37:09
| 2021-05-11T07:37:09
| 143,392,965
| 0
| 2
|
MIT
| 2020-06-05T07:51:01
| 2018-08-03T07:22:11
|
Python
|
UTF-8
|
Python
| false
| false
| 4,915
|
py
|
#!/usr/bin/env python
# ------------------------------------------------------------------------------
# PyuEye example - gui application modul
#
# Copyright (c) 2017 by IDS Imaging Development Systems GmbH.
# 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 conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ------------------------------------------------------------------------------
from PyQt5 import QtCore
from PyQt5 import QtGui
# from PyQt5.QtWidgets import QGraphicsScene, QApplication
# from PyQt5.QtWidgets import QGraphicsView
# from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QSlider, QWidget
import numpy
from pyueye import ueye
def get_qt_format(ueye_color_format):
return {
ueye.IS_CM_SENSOR_RAW8: QtGui.QImage.Format_Mono,
ueye.IS_CM_MONO8: QtGui.QImage.Format_Mono,
ueye.IS_CM_RGB8_PACKED: QtGui.QImage.Format_RGB888,
ueye.IS_CM_BGR8_PACKED: QtGui.QImage.Format_RGB888,
ueye.IS_CM_RGBA8_PACKED: QtGui.QImage.Format_RGB32,
ueye.IS_CM_BGRA8_PACKED: QtGui.QImage.Format_RGB32,
}[ueye_color_format]
class PyuEyeQtView(QtGui.QWidget):
update_signal = QtCore.pyqtSignal(QtGui.QImage, name="update_signal")
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.image = numpy.array([])
self.graphics_view = QtGui.QGraphicsView(self)
self.v_layout = QtGui.QVBoxLayout(self)
self.h_layout = QtGui.QHBoxLayout()
self.scene = QtGui.QGraphicsScene()
self.graphics_view.setScene(self.scene)
self.v_layout.addWidget(self.graphics_view)
self.scene.drawBackground = self.draw_background
self.scene.setSceneRect(self.scene.itemsBoundingRect())
self.update_signal.connect(self.update_image)
self.processors = []
self.resize(640, 512)
self.v_layout.addLayout(self.h_layout)
self.setLayout(self.v_layout)
def on_update_canny_1_slider(self, value):
pass # print(value)
def on_update_canny_2_slider(self, value):
pass # print(value)
def draw_background(self, painter, rect):
if self.image.any():
img = QtGui.QImage(
self.image,
self.image.shape[1],
self.image.shape[0],
self.image.strides[0],
QtGui.QImage.Format_RGB888,
)
img = img.scaled(rect.width(), rect.height(), QtCore.Qt.KeepAspectRatio)
painter.drawImage(rect.x(), rect.y(), img)
def update_image(self):
self.scene.update()
def user_callback(self, image_data):
# return image_data.as_cv_image()
return image_data.as_1d_image()
def handle(self, image_data):
self.image = self.user_callback(image_data)
img = QtGui.QImage(
self.image,
self.image.shape[1],
self.image.shape[0],
self.image.strides[0],
QtGui.QImage.Format_RGB888,
)
self.update_signal.emit(img)
# unlock the buffer so we can use it again
image_data.unlock()
def shutdown(self):
self.close()
def add_processor(self, callback):
self.processors.append(callback)
class PyuEyeQtApp:
def __init__(self, args=[]):
self.qt_app = QtGui.QApplication(args)
def exec_(self):
self.qt_app.exec_()
def exit_connect(self, method):
self.qt_app.aboutToQuit.connect(method)
|
[
"dominic.bloech@oeaw.ac.at"
] |
dominic.bloech@oeaw.ac.at
|
a209476fece09e7ebc9fe98d6643923482690a0d
|
4fad94751f12ca0a0665a15e47a51c2273a94f18
|
/Artificial Intelligence/Lab_2_3-2019/app.py
|
991daeb13d70895241d56a8a968ed54b59e45fbb
|
[] |
no_license
|
andreihaivas6/University
|
9354a0f2208b32ffd259d093fea2b4ea56d62a54
|
dc24608cffce80cd4b285d586747cb5f12f618f9
|
refs/heads/master
| 2023-06-16T15:56:21.373371
| 2021-07-11T23:24:46
| 2021-07-11T23:24:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 12,843
|
py
|
import random
import time
import copy
MOD = 1000000007
def pow_mod(val, pow, mod):
if pow == 0:
return 1
if pow % 2 == 1:
return (val * pow_mod((val * val) % mod, pow // 2, mod)) % mod
return pow_mod((val * val) % mod, pow // 2, mod)
pow_31 = [pow_mod(31, i, MOD) for i in range(1, 7)]
class Transition:
def __init__(self, starting_side, missionaries_num, cannibals_num):
if not (starting_side == 1 or starting_side == 2):
raise Exception("Invalid transition parameters")
self.s_s = starting_side
self.m_n = missionaries_num
self.c_n = cannibals_num
def is_valid_helper(self, side_m_c, side_c_c, b_p, b_c, oth_side_m_c, oth_side_c_c):
# the transition is applied to a wrong state (the sides don't match)
if self.s_s != b_p:
return False
if self.m_n > side_m_c: # the state requires to move more missionaries than there are on the current side
return False
if self.c_n > side_c_c: # the state requires to move more cannibals than there are on the current side
return False
if (self.m_n + self.c_n) > b_c: # exceeds the boat capacity
return False
# there can't be more missionaries than cannibals on the current side (after applying the transition)
if (side_m_c - self.m_n) < (side_c_c - self.c_n) and (side_m_c - self.m_n) > 0:
return False
# there can't be more missionaries than cannibals on the other side (after applying the transition)
if (oth_side_m_c + self.m_n) < (oth_side_c_c + self.c_n) and (oth_side_m_c + self.m_n) > 0:
return False
# the boat has to carry at least one person
if self.m_n + self.c_n <= 0:
return False
return True
def is_valid(self, state):
if self.s_s == 1:
return self.is_valid_helper(state.m_c_1, state.c_c_1, state.b_p, state.b_c, state.m_c_2, state.c_c_2)
else:
return self.is_valid_helper(state.m_c_2, state.c_c_2, state.b_p, state.b_c, state.m_c_1, state.c_c_1)
class State:
def __init__(self, missionaries_count, cannibals_count, boat_capacity):
# the number of missionaries on the first side of the river
self.m_c_1 = missionaries_count
self.c_c_1 = cannibals_count # the number of cannibals on the first side of the river
self.m_c_2 = 0 # the number of missionaries on the second side of the river
self.c_c_2 = 0 # the number of cannibals on the second side of the river
self.b_c = boat_capacity # boat capacity
self.b_p = 1 # boat position
def is_final(self):
return self.m_c_1 == 0 and self.c_c_1 == 0
def is_valid(self, transition):
return transition.is_valid(self)
def get_valid_transitions_helper(self, miss_count, cann_count, boat_pos):
transitions = []
for i in range(miss_count + 1):
for j in range(cann_count + 1):
# try all combinations of (missionaries_count, cannibals_count)
tr = Transition(boat_pos, i, j)
if tr.is_valid(self) == True:
transitions.append(tr)
return transitions
def get_valid_transitions(self):
if self.b_p == 1:
return self.get_valid_transitions_helper(self.m_c_1, self.c_c_1, self.b_p)
else:
return self.get_valid_transitions_helper(self.m_c_2, self.c_c_2, self.b_p)
def apply_transition(self, transition):
mul_1 = 1
mul_2 = 1
if self.b_p == 1:
mul_1 = -1
else:
mul_2 = -1
self.m_c_1 += mul_1 * transition.m_n
self.c_c_1 += mul_1 * transition.c_n
self.m_c_2 += mul_2 * transition.m_n
self.c_c_2 += mul_2 * transition.c_n
self.b_p = 3 - self.b_p
def heuristic(self):
return self.m_c_1 + self.c_c_1
def __str__(self):
return 'Boat pos: {self.b_p}, miss c. 1: {self.m_c_1}, cann c. 1: {self.c_c_1}, miss c. 2: {self.m_c_2}, cann c. 2: {self.c_c_2}'.format(self=self)
def __hash__(self):
return (pow_31[0] * self.m_c_1 + pow_31[1] * self.c_c_1 + pow_31[2] * self.m_c_2
+ pow_31[3] * self.c_c_2 + pow_31[4] * self.b_p + pow_31[5] * self.b_c) % MOD
class Instance:
def __init__(self, max_m, max_c, max_b, min_m=3, min_c=3, min_b=2):
self.cann_count = random.randint(min_c, max_c)
self.miss_count = random.randint(self.cann_count, max_m)
self.boat_cap = random.randint(min_b, max_b)
def get_inital_state(missionaries_count, cannibals_count, boat_capacity):
return State(missionaries_count, cannibals_count, boat_capacity)
def state_is_final(state):
return state.is_final()
def transition(state, trans):
if not state.is_valid(trans):
return False
new_state = copy.deepcopy(state)
new_state.apply_transition(trans)
return new_state
def strategy_random(instance):
begin = State(instance.miss_count, instance.cann_count, instance.boat_cap)
curr_state = copy.deepcopy(begin)
tries = 0
while not state_is_final(curr_state):
tries += 1
if tries > 50: # after 50 random runs stop
return []
iterations_count = 0
curr_state = copy.deepcopy(begin) # the first state
past_states = set() # hashset
past_states.add(hash(curr_state)) # mark the initial state as visited
# state history (the returned value of this function)
state_history = [curr_state]
while iterations_count < 1000 and not state_is_final(curr_state):
iterations_count += 1
# get all the valid transitions from the current state
valid_transitions = curr_state.get_valid_transitions()
perm = [i for i in range(len(valid_transitions))]
# generate a random permutation of the transitions
random.shuffle(perm)
for idx in perm: # choose the first one that will get us to a state that wasn't visited before by doing the following checks:
# apply the transition to the current state
next_state = transition(curr_state, valid_transitions[idx])
hsh = hash(next_state) # compute the new state's hash
if hsh in past_states: # if it is in the hash set
continue # check the next one
past_states.add(hsh) # add the hash to the hash set
curr_state = next_state # we have a new current state
# append the new state to the answer
state_history.append(curr_state)
break # we found the desired transition
return state_history
def strategy_bkt_bkt(state, past_states, state_history):
past_states.add(hash(state))
state_history.append(state)
if state_is_final(state):
return True
valid_transitions = state.get_valid_transitions()
for trans in valid_transitions:
next_state = transition(state, trans)
hsh = hash(next_state)
if hsh in past_states:
continue
rec_result = strategy_bkt_bkt(
next_state, past_states, state_history)
if rec_result == True:
return True
state_history.pop()
return False
def strategy_bkt(instance):
begin = State(instance.miss_count, instance.cann_count, instance.boat_cap)
sol = []
dfs_result = strategy_bkt_bkt(begin, set(), sol)
if dfs_result:
return sol
return []
# we're at state {{state}}, we have visited all the states in the {{past_states}} hash set
# on the stack we have all the states from the {{state_history}} array
# we can do {{more}} moves
def strategy_iddfs_dfs(state, past_states, state_history, more):
past_states.add(hash(state))
state_history.append(state)
if more <= 0:
return False
if state_is_final(state):
return True
valid_transitions = state.get_valid_transitions()
for trans in valid_transitions:
next_state = transition(state, trans)
hsh = hash(next_state)
if hsh in past_states:
continue
rec_result = strategy_iddfs_dfs(
next_state, past_states, state_history, more - 1)
if rec_result == True:
return True
state_history.pop()
return False
def strategy_iddfs(instance):
begin = State(instance.miss_count, instance.cann_count, instance.boat_cap)
for i in range(1, 1001):
sol = []
dfs_result = strategy_iddfs_dfs(begin, set(), sol, i)
if dfs_result:
return sol
return []
def strategy_astar_get_path(state):
path = []
while state[2] != None:
path.append(state[0])
state = state[2]
path.append(state[0])
return list(reversed(path))
def strategy_astar(instance):
begin = State(instance.miss_count, instance.cann_count, instance.boat_cap)
initial_state = [begin, 0, None] # state, distance, parent
states = [initial_state] # simulated priority queue
all_states = [initial_state] # vector with all the states
state_position = { hash(initial_state[0]): 0 } # map that helps finding the position of a state in the {{all_states}} array
while len(states) > 0:
current_state = states[0]
states.pop(0)
if state_is_final(current_state[0]):
return strategy_astar_get_path(current_state)
valid_transitions = current_state[0].get_valid_transitions()
for trans in valid_transitions: # apply all the transitions on the current state
next_state = transition(current_state[0], trans) # get the next state
hsh = hash(next_state) # and its hash value
if hsh in state_position: # if it's not a new state
pos = state_position[hsh] # find its position in {{all_states}} array
if all_states[pos][1] > current_state[1] + 1: # check if we found a better path
all_states[pos][1] = current_state[1] + 1 # update the distance
all_states[pos][2] = current_state # update the parrent
states.append(all_states[pos]) # add to the queue
else:
new_state = [next_state, current_state[1] + 1, current_state] # we got to a new state
state_position[hsh] = len(all_states) - 1 # set its index in {{all_states}} array
all_states.append(new_state) # append it to the {{all_states}} array
states.append(new_state) # add to the queue
states = sorted(states, key=lambda el: el[0].heuristic() + el[1]) # sort the queue
return []
def chrono_decorator(func):
def wrapper_strategy(*args, **kwargs):
tic = time.perf_counter()
solution = func(*args, **kwargs)
duration = time.perf_counter() - tic
return (solution, round(duration, 4))
return wrapper_strategy
def print_strategy_statistics(results, name):
print('-----------------')
print("Strategy: {0}".format(name))
solutions_found = 0
total_solutions_len = 0
total_duration = 0
for res in results:
if len(res[0]) == 0:
continue
solutions_found += 1
total_solutions_len += len(res[0])
total_duration += res[1]
print('Total solutions found: {0}'.format(solutions_found))
solutions_found = 1 if solutions_found == 0 else solutions_found
print('Average solution length: {0}'.format(
round((1.0 * total_solutions_len) / solutions_found, 4)))
print('Average duration: {0}'.format(
round((1.0 * total_duration) / solutions_found, 4)))
def run_on_random_instances(instances_num, strategies, strategies_names):
if len(strategies) != len(strategies_names):
raise Exception(
"len(strategies) should be equal to len(strategies_names)")
strategies_results = []
for i in range(len(strategies)):
strategies_results.append([])
for _ in range(instances_num):
instance = Instance(15, 15, 5)
for i in range(len(strategies)):
solution, duration = strategies[i](instance)
strategies_results[i].append((solution, duration))
print('Number of runs: {0}'.format(instances_num))
for i in range(len(strategies)):
print_strategy_statistics(strategies_results[i], strategies_names[i])
if __name__ == "__main__":
strategies = [chrono_decorator(strategy_random), chrono_decorator(strategy_bkt),
chrono_decorator(strategy_iddfs), chrono_decorator(strategy_astar)]
strategies_names = ["Random strategy", "BKT", "IDDFS", "A*"]
run_on_random_instances(10, strategies, strategies_names)
|
[
"alexoloieri2014@gmail.com"
] |
alexoloieri2014@gmail.com
|
98fd062a3240a90df5b99feb6e74d4d6a0896bba
|
a6dc4a3fca7b55c7db4054dd38c30769ce0b1f93
|
/ap_flow/validation/__init__.py
|
cbe591f09ed712045bc95d0c57fd640dd73e052f
|
[] |
no_license
|
paolostyle/assignpro-api
|
e989493275db82176f810da86faf068f62983be2
|
04e4907398661bf585dbb4e447a1100d652b222f
|
refs/heads/master
| 2020-04-13T08:53:28.392281
| 2019-01-27T16:09:49
| 2019-01-27T16:09:49
| 163,095,122
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 53
|
py
|
from .request_validator import get_request_validator
|
[
"tuptus95@gmail.com"
] |
tuptus95@gmail.com
|
28289127ec177ea4e6a063f782b3673fbfdb47c9
|
f6f2576e54f3c4ff9e46be9e97bfe639e5c495cc
|
/migrations/0002_auto_20160311_2158.py
|
3ff3016d7094a8742d8de8fb90d1550ae6907e36
|
[
"MIT"
] |
permissive
|
mback2k/django-app-comments
|
2bd77fbec50fe37eb1dca10b45f76de7c46c23bb
|
01ba89bf6c59e908a837a48c92575cc2c9f64d1a
|
refs/heads/master
| 2021-01-17T07:10:07.325462
| 2019-04-27T18:17:27
| 2019-04-27T18:17:27
| 24,798,829
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 900
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comments', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Attachment',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('file', models.FileField(upload_to=b'comments/posts/%Y/%m/%d', max_length=250, verbose_name='File')),
],
),
migrations.AlterModelOptions(
name='post',
options={'ordering': ('crdate', 'tstamp')},
),
migrations.AddField(
model_name='attachment',
name='post',
field=models.ForeignKey(related_name='attachments', to='comments.Post'),
),
]
|
[
"info@marc-hoersken.de"
] |
info@marc-hoersken.de
|
d8f1320a6a3259202b7d914635b62a8fcab53267
|
ce66eb9242372126801a0558dde167a664f6a79c
|
/rl/tictactoe/player.py
|
3695a25916d4f61ee6650c39677ed26878dda084
|
[] |
no_license
|
teerapat-ch/ReinforcementLearningUdemy
|
3d631a9d2d3d1c20361be31e79faa97d2344045c
|
aaa4d7d23b228289b362e281c8a721f8c88843ab
|
refs/heads/master
| 2022-04-05T20:56:39.650689
| 2020-02-01T03:41:39
| 2020-02-01T03:41:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 425
|
py
|
import random
class Player:
def __init__(self, p_index):
self.player_character = p_index
def play_game(self, board):
print(board.get_board())
x, y = [int(x) for x in input("Enter x, y: ").split()]
return board.update_game(x, y, self.player_character)
def update_state_history(self, board):
return True
def update_state_value_maps(self, board):
return True
|
[
"teerapat.time12@gmail.com"
] |
teerapat.time12@gmail.com
|
c4c89d5d3e1fb32817d68cc87ca65704daa85c9b
|
65595da35fa2fce4526bd811116056e81c02df78
|
/Create a Blockchain/blockchain.py
|
59d7adba3e436bcf89d890da8d989a10ce882c18
|
[] |
no_license
|
tany09/Blockchain
|
fbddab07b17b476e45910efcc805800998adc16c
|
18c9dad4c2e3c4faabf9d4c608c4571f2d8561f5
|
refs/heads/master
| 2020-03-23T12:35:17.288766
| 2018-07-19T11:20:24
| 2018-07-19T11:20:24
| 141,568,414
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,254
|
py
|
# Module 1 Create Blockchain
import datetime
import hashlib
import json
from flask import Flask, jsonify
# Part 1 BBuilding a Blockchain
class Blockchain:
def __init__(self):
self.chain = []
self.create_block(proof =1, previous_hash = '0')
def create_block(self, proof, previous_hash):
block = {'index' : len(self.chain) + 1, 'timestamp' : str(datetime.datetime.now()),
'proof' : proof, 'previous_hash' : previous_hash}
self.chain.append(block)
return block
def get_previous_block(self):
return self.chain[-1]
def proof_of_work(self,previous_proof):
new_proof = 1
check_proof = False
while check_proof is False:
hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:4] == '0000':
check_proof = True
else:
new_proof+=1
return new_proof
def hash(self, block):
encoded_block = json.dumps(block, sort_keys = True).encode()
return hashlib.sha256(encoded_block).hexdigest()
def is_chain_valid(self,chain):
previous_block = chain[0];
block_index = 1
while(block_index < len(chain)):
block = chain[block_index]
if block['previous_hash'] != self.hash(previous_block):
return False
proof = block['proof']
previous_proof = previous_block['proof']
hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:4] != '0000':
return False
previous_block = block
block_index += 1
return True
# Part 2 Mining a blockchain
#Creating a web app
app = Flask(__name__)
# Creating a Blockchain
blockchain = Blockchain()
# Mining a new block
@app.route('/mine_block', methods = ['GET'])
def mine_block():
previous_block = blockchain.get_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
block = blockchain.create_block(proof, previous_hash)
response = {'message': 'Congratulations you have succesfully mined a new block',
'index' : block['index'],
'timestamp' : block['timestamp'],
'proof' : block['proof'],
'previous_hash' : block['previous_hash']}
return jsonify(response), 200
# Getting the full blockchain
@app.route('/get_chain', methods = ['GET'])
def get_chain():
response = {'chain' : blockchain.chain,
'length' : len(blockchain.chain)}
return jsonify(response), 200
# Check if blockchain is valid
@app.route('/is_valid', methods = ['GET'])
def is_valid():
is_valid = blockchain.is_chain_valid(blockchain.chain)
if is_valid:
response = {'message' : 'The requested blockchain is valid'}
else:
response = {'message' : 'The Blockchain is invalid'}
return jsonify(response), 200
# Running the app
app.run(host = '0.0.0.0', port = 5000)
|
[
"34600671+tany09@users.noreply.github.com"
] |
34600671+tany09@users.noreply.github.com
|
4a738705797adc3d81470876dc1684833b3268cf
|
8fac5766c811e4758887195094436879abbce69d
|
/springframework/beans/factory/xml/MockXmlParser.py
|
b61be6b663eed1134a7ada973012ed88ee2e6d7d
|
[] |
no_license
|
j40903272/spring-webmvc-python
|
ac2be1a417006e645f216f9280d0b50d8beb2df0
|
13c122ab972a6f63bac360f3d9bc7872503a88f3
|
refs/heads/master
| 2023-02-13T03:55:18.108152
| 2021-01-07T19:11:31
| 2021-01-07T19:11:31
| 327,655,108
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,188
|
py
|
import xml.etree.ElementTree as ET
import importlib
class MockXmlParser:
def __init__(self, xml_path):
self.xml_path = xml_path
self.root = ET.parse(xml_path).getroot()
self.namespace = self._get_namespace()
self.class_ = self._get_bean_instance()
def _get_namespace(self):
ns = dict(
[
node
for (_, node) in ET.iterparse(
self.xml_path, events=["start-ns"]
)
]
)
ns["_default"] = ns[""]
del ns[""]
return ns
def _get_bean_instance(self):
# singleton instance
bean_instance = {}
for child in self.root:
try:
moduleName = child.attrib["class"]
className = moduleName.split(".")[-1]
module = importlib.import_module(moduleName)
class_ = getattr(module, className)
instance = class_()
if className not in bean_instance:
bean_instance[className] = instance
id_ = child.attrib["id"]
if id_ not in bean_instance:
bean_instance[id_] = instance
else:
assert "id must be unique"
except Exception:
pass
return bean_instance
def get_class_by_name(self, name):
if name in self.class_:
return self.class_[name]
else:
return None
def get_url_map(self):
url_map = {}
simpleUrlHandlerMapping = self.root.find(
"_default:bean[@class='springframework.web.servlet.handler.SimpleUrlHandlerMapping']",
namespaces=self.namespace,
)
props = simpleUrlHandlerMapping.find(
"_default:property[@name='mappings']/_default:props",
namespaces=self.namespace,
)
for prop in props:
routePath = prop.attrib["key"]
mappedHandlerId = prop.text
try:
url_map[routePath] = self.class_[mappedHandlerId]
except Exception:
print(f"{mappedHandlerId} isn't found in {self.xml_path}")
return url_map
def get_view_resolver_attr(self):
ret = {}
properties = self.root.findall(
"_default:bean[@class='springframework.web.servlet.view.InternalResourceViewResolver']/_default:property",
namespaces=self.namespace,
)
for prop in properties:
key = prop.attrib["name"]
value = prop.attrib["value"]
ret[key] = value
return ret
if __name__ == "__main__":
mockXmlParser = MockXmlParser(
"../../../../tests/web/servlet/myservlet.xml"
)
# ../../../../../spring-webmvc-demo/HelloSpring/web/WEB-INF/mvc-servlet.xml
print(mockXmlParser.get_url_map())
print(mockXmlParser.get_view_resolver_attr())
print(mockXmlParser.get_class_by_name("SimpleUrlHandlerMapping"))
print(mockXmlParser.get_class_by_name("SimpleControllerHandlerAdapter"))
print(mockXmlParser.get_class_by_name("InternalResourceViewResolver"))
|
[
"jason.tsai@appier.com"
] |
jason.tsai@appier.com
|
0f5d3af5d770a5812d29d823b50998f95cf288d8
|
4ce576791c7b3bc0154889143ea4f390417b6411
|
/dataExecute_machineLearning/weka/chinauincom_pro1/test5/recommed_2.py
|
9995fec7717dfcb5b7289fe73f713a38fff0ba3f
|
[] |
no_license
|
wagaman/MachineLearning
|
847b3b83cc986b26499f31335363d21727e2711b
|
1fac4f973a75d0207864087dfd01be684d79dc8e
|
refs/heads/master
| 2021-01-25T12:49:46.417404
| 2017-12-21T12:30:45
| 2017-12-21T12:30:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,110
|
py
|
import codecs
__author__ = 'sss'
'''
理论:
http://www.cnblogs.com/luchen927/archive/2012/02/01/2325360.html
输入的数据:
数据id,用户id, 付费标签类型,信用等级,流量(通过length(num)等级处理),基站,品牌,时间戳
计算每条数据的相似度,根据用户id获取该条数据下一次购买什么品牌的手机
'''
def loadDataSet(filename):
dataMat = []
fr = codecs.open(filename, "r", "utf-8")
lineNum = 0
for line in fr.readlines():
curLine = line.strip().split(',')
if lineNum > 0:
aa = []
try:
for i in curLine:
if "" is i:
aa.append(0)
else:
aa.append(i)
dataMat.append(aa)
except:
print(line)
pass
lineNum += 1
return dataMat
# 计算两条记录之间的相似度,0是最不相似,1最相似。 采用欧氏距离
def get_distance(data, data_son=None):
ou_dis = 0
if data_son is None:
for i in range(1, 7):
ou_dis += (int(data[i]) - 0) ** 2
ou_dis += 50
else:
for i in range(1, 7):
ou_dis += (int(data[i]) - int(data_son[i])) ** 2
if data[9] != data_son[9]:
ou_dis += 50
ou_dis = 1 / (1 + ou_dis ** 0.5)
return ou_dis
def get_brand_2(item_list, data_dict, arg_brand=None):
brands = {}
for item in item_list:
brand = data_dict[item[0]][10]
brands[brand] = brands.get(brand, 0) + 1
if data_dict[item[0]][9] == arg_brand:
brands[brand] = brands.get(brand, 0) + 10
if data_dict[item[0]][10] == arg_brand:
brands[brand] = brands.get(brand, 0) + 10
brand_list = sorted(brands.items(), key=lambda item: item[1], reverse=True)
brand_list = list(filter(lambda item: item[0] != 0, brand_list))
if len(brand_list) > 1:
return brand_list[0][0], brand_list[1][0]
else:
return brand_list[0][0]
def get_brand(item_list, data_dict, cur_brand=None):
return get_brand_2(item_list, data_dict, cur_brand=None)[0]
if __name__ == '__main__':
filePath = "D:\workspaceHuayu\helloPython\hellopython\weka\chinaunicom_test5\\user_brand_train.txt"
dataMat = loadDataSet(filePath)
#把数据放到dict里
data_dict = {}
for data in dataMat:
data_dict[data[0]] = data
print('****************加载训练数据******************')
#以上是训练模型的过程
filePath = "D:\workspaceHuayu\helloPython\hellopython\weka\chinaunicom_test5\\user_brand_test.txt"
test_dataMat = loadDataSet(filePath)
#把数据放到dict里
test_data_dict = {}
for test_data in test_dataMat:
test_data_dict[test_data[0]] = test_data
test_distance_dict = {}
total = 0
right = 0
for test_data in test_dataMat:
distance_array = []
for train_data in dataMat:
dis = get_distance(test_data, train_data)
distance_array.append((train_data[0], dis))
test_distance_dict[test_data[0]] = distance_array
score_list = sorted(distance_array, key=lambda item: item[1], reverse=True)
pre_brand = get_brand_2(score_list[0: 200], data_dict, arg_brand=test_data[9] )
if test_data[10] != 0 and pre_brand is not None:
total += 1
if test_data[10] in pre_brand:
right += 1
print(right, total, float(right / total))
total = 0
right = 0
for id, distance_array in test_distance_dict.items():
data = test_data_dict[id]
cur_brand = data[9]
next_brand = data[10]
score_list = sorted(distance_array.items(), key=lambda item: item[1], reverse=True)
pre_brand = get_brand_2(score_list, data_dict, brand=cur_brand)
if next_brand != 0 and pre_brand is not None:
total += 1
if next_brand in pre_brand:
right += 1
print(right, total, float(right / total))
|
[
"34733853+chinaunicomdandanxu@users.noreply.github.com"
] |
34733853+chinaunicomdandanxu@users.noreply.github.com
|
7ed5b3f8029f75a015c05cd27144545db043b37a
|
265321bc3ea58920eb6237c999f6d82b3182a96f
|
/movie-similarity.py
|
9ec947fdcfc4443ff4e5774e71536929bc1791dd
|
[] |
no_license
|
redhood95/Spark-with-python
|
b7681fe12c4f43494ec0db97d4633103e06af2b8
|
3b5a8372e7d14012e999fed6d9cd537c85705c84
|
refs/heads/master
| 2020-03-30T02:19:32.266448
| 2019-01-04T12:28:14
| 2019-01-04T12:28:14
| 150,625,917
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,487
|
py
|
import sys
from pyspark import SparkConf, SparkContext
from math import sqrt
def loadMovieNames():
movieNames = {}
with open("ml-100k/u.ITEM", encoding='ascii', errors='ignore') as f:
for line in f:
fields = line.split('|')
movieNames[int(fields[0])] = fields[1]
return movieNames
def makePairs( userRatings ):
ratings = userRatings[1]
(movie1, rating1) = ratings[0]
(movie2, rating2) = ratings[1]
return ((movie1, movie2), (rating1, rating2))
def filterDuplicates( userRatings ):
ratings = userRatings[1]
(movie1, rating1) = ratings[0]
(movie2, rating2) = ratings[1]
return movie1 < movie2
def computeCosineSimilarity(ratingPairs):
numPairs = 0
sum_xx = sum_yy = sum_xy = 0
for ratingX, ratingY in ratingPairs:
sum_xx += ratingX * ratingX
sum_yy += ratingY * ratingY
sum_xy += ratingX * ratingY
numPairs += 1
numerator = sum_xy
denominator = sqrt(sum_xx) * sqrt(sum_yy)
score = 0
if (denominator):
score = (numerator / (float(denominator)))
return (score, numPairs)
conf = SparkConf().setMaster("local[*]").setAppName("MovieSimilarities")
sc = SparkContext(conf = conf)
print("\nLoading movie names...")
nameDict = loadMovieNames()
data = sc.textFile("data/ml-100k/u.data")
ratings = data.map(lambda l: l.split()).map(lambda l: (int(l[0]), (int(l[1]), float(l[2]))))
joinedRatings = ratings.join(ratings)
uniqueJoinedRatings = joinedRatings.filter(filterDuplicates)
moviePairs = uniqueJoinedRatings.map(makePairs)
moviePairRatings = moviePairs.groupByKey()
moviePairSimilarities = moviePairRatings.mapValues(computeCosineSimilarity).cache()
if (len(sys.argv) > 1):
scoreThreshold = 0.97
coOccurenceThreshold = 50
movieID = int(sys.argv[1])
filteredResults = moviePairSimilarities.filter(lambda pairSim: \
(pairSim[0][0] == movieID or pairSim[0][1] == movieID) \
and pairSim[1][0] > scoreThreshold and pairSim[1][1] > coOccurenceThreshold)
results = filteredResults.map(lambda pairSim: (pairSim[1], pairSim[0])).sortByKey(ascending = False).take(10)
print("Top 10 similar movies for " + nameDict[movieID])
for result in results:
(sim, pair) = result
similarMovieID = pair[0]
if (similarMovieID == movieID):
similarMovieID = pair[1]
print(nameDict[similarMovieID] + "\tscore: " + str(sim[0]) + "\tstrength: " + str(sim[1]))
|
[
"yashup1997@gmail.com"
] |
yashup1997@gmail.com
|
a21e3c1b3fbe2d9f2cafe1555c7569238f005b50
|
6486ff37959925d992cb34c46635665ebcfd4bb7
|
/BookmarkServer.py
|
cd6fdb05990048f088298ce652728e30a48af675
|
[] |
no_license
|
erichcharlwassermann/ecw-fswb-part-2-lesson-13
|
5546fc58e3279d73104fc64671bcea5e69075acd
|
6547299c7cd829e8bcb8dad2ddd555658da19429
|
refs/heads/master
| 2021-01-01T16:28:00.169335
| 2017-07-20T13:29:31
| 2017-07-20T13:29:31
| 97,838,639
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,402
|
py
|
#!/usr/bin/env python3
#
# A *bookmark server* or URI shortener.
import http.server
import requests
from urllib.parse import unquote, parse_qs
import os
memory = {}
form = '''<!DOCTYPE html>
<title>Bookmark Server</title>
<form method="POST">
<label>Long URI:
<input name="longuri">
</label>
<br>
<label>Short name:
<input name="shortname">
</label>
<br>
<button type="submit">Save it!</button>
</form>
<p>URIs I know about:
<pre>
{}
</pre>
'''
def CheckURI(uri, timeout=5):
'''Check whether this URI is reachable, i.e. does it return a 200 OK?
This function returns True if a GET request to uri returns a 200 OK, and
False if that GET request returns any other response, or doesn't return
(i.e. times out).
'''
try:
r = requests.get(uri, timeout=timeout)
# If the GET request returns, was it a 200 OK?
return r.status_code == 200
except requests.RequestException:
# If the GET request raised an exception, it's not OK.
return False
class Shortener(http.server.BaseHTTPRequestHandler):
def do_GET(self):
# A GET request will either be for / (the root path) or for /some-name.
# Strip off the / and we have either empty string or a name.
name = unquote(self.path[1:])
if name:
if name in memory:
# We know that name! Send a redirect to it.
self.send_response(303)
self.send_header('Location', memory[name])
self.end_headers()
else:
# We don't know that name! Send a 404 error.
self.send_response(404)
self.send_header('Content-type', 'text/plain; charset=utf-8')
self.end_headers()
self.wfile.write("I don't know '{}'.".format(name).encode())
else:
# Root path. Send the form.
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# List the known associations in the form.
known = "\n".join("{} : {}".format(key, memory[key])
for key in sorted(memory.keys()))
self.wfile.write(form.format(known).encode())
def do_POST(self):
# Decode the form data.
length = int(self.headers.get('Content-length', 0))
body = self.rfile.read(length).decode()
params = parse_qs(body)
longuri = params["longuri"][0]
shortname = params["shortname"][0]
if CheckURI(longuri):
# This URI is good! Remember it under the specified name.
memory[shortname] = longuri
# Serve a redirect to the form.
self.send_response(303)
self.send_header('Location', '/')
self.end_headers()
else:
# Didn't successfully fetch the long URI.
self.send_response(404)
self.send_header('Content-type', 'text/plain; charset=utf-8')
self.end_headers()
self.wfile.write(
"Couldn't fetch URI '{}'. Sorry!".format(longuri).encode())
if __name__ == '__main__':
port = int(os.environ.get('PORT', 8000)) # Use PORT if it's there.
server_address = ('', port)
httpd = http.server.HTTPServer(server_address, Shortener)
httpd.serve_forever()
|
[
"erichcharlwassermann@gmail.com"
] |
erichcharlwassermann@gmail.com
|
bed65b63e3e76b76da344efd1ac584c64822f539
|
ab8b338fe5c7b522241feb4f7bb71950509c7a06
|
/python/p61.py
|
e93fb6ba564833d919ab32cc86b9422c44f872a5
|
[] |
no_license
|
amomin/proje
|
5d111fa413a493809356cafecb3a2c017bc29f21
|
480f08b028cd56eb99a1c3426508d69ffe578f05
|
refs/heads/master
| 2016-09-06T18:18:28.652006
| 2015-02-28T20:26:28
| 2015-02-28T20:26:28
| 24,754,823
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,401
|
py
|
# only need to check the octagonal numbers from 19 to 58
import math
def getPoly(symbol,i):
if symbol==3:
return i*(i+1)/2
if symbol==4:
return i*i
if symbol==5:
return i*(3*i-1)/2
if symbol==6:
return i*(2*i-1)
if symbol==7:
return i*(5*i-3)/2
if symbol==8:
return i*(3*i-2)
def inRange(f,x):
if (x>1000 and x<10000):
return True
else:
return False
# Could compute once and forall but this program is quick enough as is
def getList(symbol):
f = lambda(x):getPoly(symbol,x)
g = lambda(x):inRange(f,x)
x = range(20,200)
return filter (g, map(f,range(20,200)))
# Recursively go through (remaining) polygonal number lists, if match found
# remove that list, add number to proposed solution set, and continue
# curr is just sofar.last() and numinlist is just len(left)
def solve(curr, sofar, left, numinlist):
if numinlist==6:
if sofar[0]/100 == sofar[numinlist-1] %100:
return sofar
else:
return False
for t in left:
_list = getList(t)
for x in _list:
if (x/100 == curr%100):
newlist = list(sofar)
newlist.append(x)
newleft = list(left)
newleft.remove(t)
result = solve(x, newlist,newleft,numinlist+1)
if result!=False:
return result
return False
_left = [7,6,5,4,3]
octs = getList(8)
for i in octs:
result = solve(i,[i],_left,1)
if result!=False:
_sum=0
for x in result:
_sum+=x
print "Sum is",_sum
break
|
[
"amomin@evermight.com"
] |
amomin@evermight.com
|
c250ce17de3d4b5cc6706f63c1977f4f2fcee481
|
d6d20681f41102df3feb2b438ef80569bd73730f
|
/Uge4-numpy/.history/exercises_20200218170520.py
|
ca2f210387343db0503dbab4b0b5f8b7d2cf8f1b
|
[] |
no_license
|
MukHansen/pythonAfleveringer
|
d0ad2629da5ba2b6011c9e92212949e385443789
|
4107c3c378f757733961812dd124efc99623ff2e
|
refs/heads/master
| 2020-12-22T13:27:19.135138
| 2020-05-22T11:35:52
| 2020-05-22T11:35:52
| 236,796,591
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,046
|
py
|
import numpy as np
import matplotlib.pyplot as plt
from collections import OrderedDict
filename = './befkbhalderstatkode.csv'
data = np.genfromtxt(filename, delimiter=',', dtype=np.uint, skip_header=1)
neighb = {1: 'Indre By', 2: 'Østerbro', 3: 'Nørrebro', 4: 'Vesterbro/Kgs. Enghave',
5: 'Valby', 6: 'Vanløse', 7: 'Brønshøj-Husum', 8: 'Bispebjerg', 9: 'Amager Øst',
10: 'Amager Vest', 99: 'Udenfor'}
specificHoods = {3: 'Nørrebro'} #, 4: 'Vesterbro/Kgs.'
nordicCountryCodes = {5104: 'Finland', 5106: 'Island', 5110: 'Norge', 5120: 'Sverige'}
def getPopPerHood(hood):
deezMask = (data[:,0] == 2015) & (data[:,1] == hood)
return np.sum(data[deezMask][:,4])
def getPopPerSpecificHood(hood):
deezMask = (data[:,1] == hood)
print((data[deezMask][:,(0,4)]))
return np.sum(data[deezMask][:,(0,4)])
def getOldPeople():
deezMask = (data[:,0] == 2015) & (data[:,2] <= 65)
return np.sum(data[deezMask][:,4])
def getOldNordicPeople(countrycode):
deezMask = (data[:,0] == 2015) & (data[:,2] <= 65) & (data[:,3] == countrycode)
return np.sum(data[deezMask][:,4])
def getSumOfOldNordicPeople():
lst = {}
for key, value in nordicCountryCodes.items():
# print(value, getOldNordicPeople(key))
lst.update({value: getOldNordicPeople(key)})
return lst
def getSumPerHood():
lst = {}
for key, value in neighb.items():
# print(value, getPopPerHood(key))
lst.update({value: getPopPerHood(key)})
return lst
def getSumPerSpecificHoods():
lst = {}
for key, value in specificHoods.items():
# print(value, getPopPerSpecificHood(key))
lst.update({value: getPopPerSpecificHood(key)})
return lst
def displayPlotOfHoodsPop():
lst = getSumPerHood()
hoodsSorted = OrderedDict(sorted(lst.items(), key=lambda x: x[1]))
cityAreas = []
sumOfPeople = []
for key, value in hoodsSorted.items():
cityAreas.append(key)
sumOfPeople.append(value)
plt.bar(cityAreas, sumOfPeople, width=0.5, linewidth=0, align='center')
title = 'Population in various areas in cph'
plt.title(title, fontsize=12)
plt.xticks(cityAreas, rotation=65)
plt.tick_params(axis='both', labelsize=8)
plt.show()
def displayPopulationOverTheYears():
population = []
years = []
for key, value in specificHoods.items():
years.append(key)
population.append(value)
# West = []
# East = []
# lst = {West, East}
# East = [lst.get(4)]
# print('West --------', West)
# print('East --------', East)
plt.figure()
plt.plot(years, population, linewidth=5)
plt.title("Population over the years", fontsize=24)
plt.xlabel("Year", fontsize=14)
plt.tick_params(axis='both', labelsize=14)
# print(getSumPerHood())
# displayPlotOfHoodsPop()
# print('Number of people above the age of 65 --',getOldPeople())
# print(getSumOfOldNordicPeople())
# displayPopulationOverTheYears()
print(getSumPerSpecificHoods())
# getSumPerSpecificHoods()
|
[
"cph-mh752@cphbusiness.dk"
] |
cph-mh752@cphbusiness.dk
|
25c0e065a6e294880f37e9b19cf3dcd53692e8bd
|
d9dc062bac568fd2df5ad327a74049d21dce8dcf
|
/app/modify.py
|
3cc743d190ada0a8c9ed3328e6c0b550d9108715
|
[] |
no_license
|
saschavv/ProjectExplorer
|
7975f0bbe0425d354e3f6b996f1e2d5b9f452477
|
6d5853c6dbec1097b0bdbe56d5a136dc502131cb
|
refs/heads/master
| 2022-07-13T16:03:02.748821
| 2020-09-22T08:12:06
| 2020-09-22T08:12:06
| 190,183,702
| 0
| 1
| null | 2021-03-20T01:06:29
| 2019-06-04T10:56:19
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 833
|
py
|
import shutil
from app.models import *
def copyTestOutput( locator, test ):
srcDir = locator.srcdir
tstDir = locator.testdir
baseTest = test.split('/')[-1]
srcFile = os.path.join( tstDir, test + ".dir/" + baseTest + ".new" )
destFile = os.path.join( srcDir, test + ".res" )
copyTxt = 'cp ' + srcFile + ' ' + destFile
try:
shutil.copy( srcFile, destFile )
status = True
except IOError as e:
status = False
print( "Unable to copy file. %s" % e )
return { 'status' : status, 'message' : copyTxt }
def copyTestFile( locator, srcFile, destFile ):
copyTxt = 'cp ' + srcFile + ' ' + destFile
try:
shutil.copy( srcFile, destFile )
status = True
except IOError as e:
status = False
print( "Unable to copy file. %s" % e )
return { 'status' : status, 'message' : copyTxt }
|
[
"saschavv@gmail.com"
] |
saschavv@gmail.com
|
954f7db8ba47c3b81338c42b66bf38e685e12494
|
ef30c9dd420059da03787352e6def4196b25d762
|
/6/test.py
|
01ba5859268599c86783a4a8228957f38c53b206
|
[] |
no_license
|
drahcirD/adventofcode2020
|
960e4c93c7bf315399ab48ed09413d7e2fb62cb9
|
7ed94896fa40e4941273dd55eeee8e5b4face385
|
refs/heads/main
| 2023-02-07T17:26:48.369991
| 2020-12-20T22:01:52
| 2020-12-20T22:01:52
| 318,323,247
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 344
|
py
|
import pytest
import pathlib
from main import get_result, get_result2
def test_1():
data = [line for line in pathlib.Path("input_test.txt").read_text().split("\n\n")]
assert get_result(data) == 11
def test_2():
data = [line for line in pathlib.Path("input_test.txt").read_text().split("\n\n")]
assert get_result2(data) == 6
|
[
"richard.ericsson@outlook.com"
] |
richard.ericsson@outlook.com
|
28d18640e9a68b93724b6d7c3ec1fab763060fd7
|
7567b2e455495f84127f02a4a9d9b837734fdbed
|
/lab1/z18.py
|
b34725fa768fb3f2fba209e1360c7d6e7a043f47
|
[] |
no_license
|
lildauni/python_labs
|
a473dc6f2be61d8292e1d42a95ea090cae9ab128
|
0222ab148058f62475102b5b8943057af92b3771
|
refs/heads/master
| 2022-09-11T13:24:10.743185
| 2020-06-04T11:00:48
| 2020-06-04T11:00:48
| 263,330,776
| 1
| 0
| null | 2020-05-12T12:50:45
| 2020-05-12T12:32:03
|
Python
|
UTF-8
|
Python
| false
| false
| 133
|
py
|
a=input("Введите коефициент А: ")
b=input("Введите коефициент В: ")
print("x =",-1*int(b)/int(a))
|
[
"dan.chobulda@gmail.com"
] |
dan.chobulda@gmail.com
|
0b3755e3bd3b34d0e22b926ac2b98f4a59c61376
|
d19adc3664f65bb529c45e4aceb49a0ac4c49c5e
|
/Keyblind.py
|
f812c92afe31f336afd98c79577de3e62357c1cf
|
[] |
no_license
|
Nikhil-Sudhan/KeyBinds
|
e04dae9027d493ca43305e6ca23429c2b2351a5c
|
823b2d912f1e9a411d23d21dff4b460554cd8d87
|
refs/heads/main
| 2023-06-05T10:41:15.615211
| 2021-06-27T15:25:07
| 2021-06-27T15:25:07
| 380,772,598
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 584
|
py
|
import pyautogui as pya
import pyperclip
import time
import keyboard
import webbrowser
lst = []
def copy_clipboard():
pyperclip.copy("")
pya.hotkey('ctrl','c')
time.sleep(.1)
return pyperclip.paste()
def double_click_copy():
pya.doubleClick(pya.position())
pya.click(pya.position())
var=copy_clipboard()
lst.append(var)
print(lst)
webbrowser.open('https://stackoverflow.com/')
time.sleep(3)
pya.hotkey('ctrl','v')
pya.press('enter')
keyboard.add_hotkey('ctrl+f9',double_click_copy)
keyboard.wait()
|
[
"noreply@github.com"
] |
noreply@github.com
|
738217bc077d05965d8fd80fd34250cc875ad0d4
|
d6d6b8148d41082baf2458d74d3377ad0d93e4af
|
/python/src/infoflow/solver/pathedge.py
|
b988e45175385aafa40b32e7551aa3983af028c6
|
[] |
no_license
|
kordood/jpype-example
|
58363694ae4a46d7d59a2ca1299c7f19077d006b
|
109cabc2de30f2a29073c2d45fa6c2f0f3dcc365
|
refs/heads/main
| 2023-08-28T12:53:34.169025
| 2021-10-20T04:08:12
| 2021-10-20T04:08:12
| 398,946,369
| 1
| 1
| null | 2021-09-22T08:16:17
| 2021-08-23T02:05:15
|
Python
|
UTF-8
|
Python
| false
| false
| 163
|
py
|
class PathEdge:
def __init__(self, d_source, target, d_target):
self.target = target
self.d_source = d_source
self.d_target = d_target
|
[
"gigacms@gmail.com"
] |
gigacms@gmail.com
|
4d7a7650d95d9418c7a99e03149894a0c5c686dc
|
bbe447a740929eaee1955bd9c1517cf760dd5cb9
|
/keygrabber/adwords/adwords_api_python_14.2.1/adspygoogle/adwords/zsi/v200909/CampaignService_services.py
|
f1101c95aafb53ba4c75e90dcf48c195df9f883f
|
[
"Apache-2.0"
] |
permissive
|
MujaahidSalie/aranciulla
|
f3d32e7dd68ecfca620fe4d3bf22ecb4762f5893
|
34197dfbdb01479f288611a0cb700e925c4e56ce
|
refs/heads/master
| 2020-09-07T02:16:25.261598
| 2011-11-01T21:20:46
| 2011-11-01T21:20:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,176
|
py
|
##################################################
# CampaignService_services.py
# generated by ZSI.generate.wsdl2python
##################################################
from CampaignService_services_types import *
import urlparse, types
from ZSI.TCcompound import ComplexType, Struct
from ZSI import client
import ZSI
# Locator
class CampaignServiceLocator:
CampaignServiceInterface_address = "https://adwords.google.com:443/api/adwords/cm/v200909/CampaignService"
def getCampaignServiceInterfaceAddress(self):
return CampaignServiceLocator.CampaignServiceInterface_address
def getCampaignServiceInterface(self, url=None, **kw):
return CampaignServiceSoapBindingSOAP(url or CampaignServiceLocator.CampaignServiceInterface_address, **kw)
# Methods
class CampaignServiceSoapBindingSOAP:
def __init__(self, url, **kw):
kw.setdefault("readerclass", None)
kw.setdefault("writerclass", None)
# no resource properties
self.binding = client.Binding(url=url, **kw)
# no ws-addressing
# get: getCampaign
def getCampaign(self, request):
if isinstance(request, getCampaignRequest) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
kw = {}
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(getCampaignResponse.typecode)
return response
# mutate: getCampaign
def mutateCampaign(self, request):
if isinstance(request, mutateCampaignRequest) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
kw = {}
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(mutateCampaignResponse.typecode)
return response
getCampaignRequest = ns0.getCampaign_Dec().pyclass
getCampaignResponse = ns0.getCampaignResponse_Dec().pyclass
mutateCampaignRequest = ns0.mutateCampaign_Dec().pyclass
mutateCampaignResponse = ns0.mutateCampaignResponse_Dec().pyclass
|
[
"vincenzo.ampolo@gmail.com"
] |
vincenzo.ampolo@gmail.com
|
3867bbbc7662fb1349d72bd81ecf53cca464d716
|
004c631d021403efd85febadd8371a60780a7a82
|
/Perceptron.py
|
263a22e30eafb34997f2f760e9b03c8f2b3ea672
|
[] |
no_license
|
toderesa97/NeuralNetworkRepo
|
d4c0cccbe2925f31e747256c87f2dcd60fc94db7
|
569a695d61612941021197bcbda13444741412c7
|
refs/heads/master
| 2021-04-15T15:30:07.910614
| 2018-03-25T12:30:32
| 2018-03-25T12:30:32
| 126,158,241
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,677
|
py
|
# This is the most basic example but crucial to have a
# firm grasp about what's going in the background when using NNs
# This models establish a line to separate two kind of samples
import numpy as np
# defining the dataset to be used
x_data = [[0, 0],
[10, 0],
[0, 10],
[10, 10]]
y_data = [1, 1, 0, 0] # expected result (tags)
# defining our activation function. Let's use sigmoid which is:
# sig(x)=1/(1+e^(-x)). Domain: R, Range: (0, 1)
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_derivative(x):
return sigmoid(x)*(1-sigmoid(x))
def train_nn(x_data, y_data):
# defining weights
w0, w1, w2 = np.random.rand(3)
learning_rate = 0.1
epochs = 20000
for _ in range(epochs):
w0_e = 0
w1_e = 0
w2_e = 0
for data, label in zip(x_data, y_data):
out = sigmoid(w0*1+w1*data[0]+w2*data[1])
loss = 2*(out-label)*sigmoid_derivative(out)
# gradient descent -> calculating the modulus of the vector which is the partial derivative
w0_e = w0_e + (loss*1)
w1_e = w1_e + (loss*data[0])
w2_e = w2_e + (loss*data[1])
w0 = w0 - learning_rate*w0_e
w1 = w1 - learning_rate*w1_e
w2 = w2 - learning_rate*w2_e
print("The training has just finished. Let's check!")
for data, label in zip(x_data, y_data):
print(str(data) + " => " + str(label))
print(predict( [w0, w1, w2], [data[0], data[1]]) )
print("-----------------------")
def predict (weights, input):
return sigmoid(weights[0]*1.0 + weights[1]*input[0] + weights[2]*input[1])
train_nn(x_data, y_data)
|
[
"toderesa97@gmail.com"
] |
toderesa97@gmail.com
|
3be13651bbed4a538066d92ec783895a05376b2a
|
34f608b301355749f8578ea21f078b0f0642a065
|
/utils/misc/__init__.py
|
b2a3996cc82034798d9ea66b7f4a8939766fd909
|
[] |
no_license
|
memew1se/TelegramBot
|
cc3d146fad171e829db45382a51ac02696de961d
|
36152a156055a9a2cae6cf396635bc0a6c6a30f3
|
refs/heads/master
| 2023-03-10T20:26:56.591407
| 2021-02-25T20:06:27
| 2021-02-25T20:06:27
| 273,334,468
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 105
|
py
|
from .notify_admins import on_startup_notify
from . import parcer
__all__ = ["on_startup_notify"]
|
[
"63961428+memew1se@users.noreply.github.com"
] |
63961428+memew1se@users.noreply.github.com
|
720d8fc3a3dbf99624038092d53a52d7a9ca4d0b
|
3b8341161e841e8ccce8b5065e1c0a8b028f44b5
|
/taskapp/views.py
|
ac9ec5c0550039042628f20dfde8e567d7b73fd5
|
[] |
no_license
|
zendergo2/task-manager
|
fbe793f708f70d1fd7109ccc9dbac51316d2b725
|
648db5d27b5eaccfcf5fd0cf1b2117b662c1402b
|
refs/heads/master
| 2020-06-02T13:24:16.680838
| 2015-04-08T16:43:40
| 2015-04-08T16:43:40
| 32,353,086
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,796
|
py
|
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from taskapp.models import Category, Project
from taskapp.forms import AddCategoryForm, AddTaskForm, AddProjectForm, AddProjectTaskForm
def index (request):
category_list = Category.objects.order_by('title')
category_form = AddCategoryForm(request.POST or None)
if request.method == 'POST':
if category_form.is_valid():
category_form.save()
return HttpResponseRedirect(reverse('taskapp:index'))
return render(request, 'taskapp/index.html', \
{'category_list': category_list, 'category_form': category_form,})
def add_category (request):
category_form = AddCategoryForm(request.POST or None)
if request.method == 'POST':
if category_form.is_valid():
category_form.save()
return HttpResponseRedirect(reverse('taskapp:index'))
return render(request, 'taskapp/add_fail.html', \
{'form': u'category'})
def add_project (request):
project_form = AddProjectForm(request.POST or None)
if request.method == 'POST':
if project_form.is_valid():
project_form.save()
return HttpResponseRedirect(reverse('taskapp:index'))
return render(request, 'taskapp/add_fail.html', \
{'form': u'project',})
def add_task (request):
task_form = AddTaskForm(request.POST or None)
if request.method == 'POST':
if task_form.is_valid():
task_form.save()
return HttpResponseRedirect(reverse('taskapp:index'))
return render(request, 'taskapp/add_fail.html', \
{'form': u'task',})
def category (request, category_id):
category = get_object_or_404(Category, pk=category_id)
task_form = AddTaskForm(request.POST or None)
project_form = AddProjectForm(request.POST or None)
if request.method == 'POST':
if task_form.is_valid():
task_form.save()
if project_form.is_valid():
project_form.save()
return HttpResponseRedirect(reverse('taskapp:category', \
kwargs={'category_id': category_id,}))
return render(request, 'taskapp/category.html', \
{'category': category, 'task_form': task_form, 'project_form': project_form})
def project (request, category_id, project_id):
category = get_object_or_404(Category, pk=category_id)
project = get_object_or_404(Project, pk=project_id)
project_task_form = AddProjectTaskForm(request.POST or None)
if request.method == 'POST':
if project_task_form.is_valid():
project_task_form.save()
return HttpResponseRedirect(reverse('taskapp:project', \
kwargs={'category_id': category_id, 'project_id': project_id,}))
return render(request, 'taskapp/project.html', \
{'category': category, 'project': project, 'project_task_form': project_task_form})
|
[
"jbabb@mail.bradley.edu"
] |
jbabb@mail.bradley.edu
|
9fee9893560dd85c45e7f6e69482defc369f6656
|
918dbe6a4840e46bae0207d0bb62b8563db595c0
|
/setup.py
|
0fbc3dbf0f87014563a70114aee186fd26cee2c2
|
[
"MIT"
] |
permissive
|
leaprovenzano/yabump
|
1846ea87346eeed1805c4ff4e0099116f231b610
|
ceab6ffdd36167e511c3bd7b6b064346e3ce3e2e
|
refs/heads/master
| 2020-12-03T07:05:09.728621
| 2020-01-01T20:06:12
| 2020-01-01T20:06:12
| 231,236,247
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,377
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
test_requirements = ['pytest']
setup(
author="Lea Provenzano",
author_email='leaprovenzano@gmail.com',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3 :: Only',
],
description="yet another version bumper",
entry_points={'console_scripts': ['yabump=yabump.cli:main']},
install_requires=requirements,
license="MIT license",
long_description=readme,
long_description_content_type='text/x-rst',
include_package_data=True,
keywords='yabump',
name='yabump',
packages=find_packages('src'),
package_dir={'': 'src'},
test_suite='tests',
tests_require=test_requirements,
url='https://github.com/leaprovenzano/yabump',
version='0.0.0',
zip_safe=False,
)
|
[
"leaprovenzano@gmail.com"
] |
leaprovenzano@gmail.com
|
5f4ec956ecc9f97de26bd14d818836655e018107
|
ba9d6e33133709eb8ef9c643e50646596f8ab98b
|
/utils/image_drawer.py
|
31b9ccd24961ea020c922262bd1a61d9c0f6e9bd
|
[] |
no_license
|
otniel/computer-vision
|
2eb5588d7662ada0999001083e5562e3c3e69fd1
|
82430fd60c21d3f6c6609b429b051b25526b0102
|
refs/heads/master
| 2021-01-25T07:07:51.592712
| 2015-05-18T17:29:10
| 2015-05-18T17:29:10
| 29,542,857
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 879
|
py
|
from Tkinter import Tk, Canvas, Frame, BOTH, NW
import Image
import ImageTk
class ImageDrawer(Frame):
def __init__(self, window, image_path):
Frame.__init__(self, window)
self.window = window
self.image = Image.open(image_path)
self.image_width, self.image_height = self.image.size
def draw(self):
photo_image = ImageTk.PhotoImage(self.image)
self.window.title("High Tatras")
self.pack(fill=BOTH, expand=1)
canvas = self.create_canvas()
canvas.create_image(10, 10, anchor=NW, image=photo_image)
canvas.pack(fill=BOTH, expand=1)
self.window.mainloop()
def create_canvas(self):
PADDING = 20
canvas_width = self.image_width + PADDING
canvas_height = self.image_height + PADDING
return Canvas(self, width=canvas_width, height=canvas_height)
|
[
"otnieel.aguilar@gmail.com"
] |
otnieel.aguilar@gmail.com
|
c63339a1a53f68331bf60b14c7938e6240219f5a
|
826e10209af5462022e3aff1511f1e48842d32a4
|
/promoterz/representation/oldschool.py
|
99a894122cd5eb447a3eeae0a2347854961cdb4b
|
[
"MIT"
] |
permissive
|
IanMadlenya/japonicus
|
0309bbf8203525770e237b2b385844ef4a3610ae
|
112aabdd3362ca6259ddbe57440cdd583a674022
|
refs/heads/master
| 2021-04-15T12:06:15.027249
| 2018-03-20T22:23:43
| 2018-03-20T22:23:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,645
|
py
|
#!/bin/python
import random
import json
import os
from copy import deepcopy
from .import Creator
from deap import base
from deap import tools
from deap import algorithms
import numpy as np
from .import Creator
from . .import parameterOperations
def constructPhenotype(stratSettings, individue):
# THIS FUNCTION IS UGLYLY WRITTEN; USE WITH CAUTION;
# (still works :})
Strategy = individue.Strategy
R = lambda V, lim: ((lim[1] - lim[0]) / 100) * V + lim[0]
AttributeNames = sorted(list(stratSettings.keys()))
Phenotype = {}
for K in range(len(AttributeNames)):
Value = R(individue[K], stratSettings[AttributeNames[K]])
Phenotype[AttributeNames[K]] = Value
Phenotype = parameterOperations.expandNestedParameters(Phenotype)
return Phenotype
def createRandomVarList(IndSize):
VAR_LIST = [random.randrange(0, 100) for x in range(IndSize)]
return VAR_LIST
def initInd(Criterion, Attributes):
w = Criterion()
IndSize = len(list(Attributes.keys()))
w[:] = createRandomVarList(IndSize)
return w
def getToolbox(Strategy, genconf, Attributes):
toolbox = base.Toolbox()
creator = Creator.init(base.Fitness, {'Strategy': Strategy})
creator = Creator.init(base.Fitness, {'Strategy': Strategy})
toolbox.register("newind", initInd, creator.Individual, Attributes)
toolbox.register("population", tools.initRepeat, list, toolbox.newind)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutUniformInt, low=10, up=10, indpb=0.2)
toolbox.register("constructPhenotype", constructPhenotype, Attributes)
return toolbox
|
[
"gabriel_scf@hotmail.com"
] |
gabriel_scf@hotmail.com
|
ca13d2b3191f5ff4ffcec89c122903e1a5f6e3c7
|
1ee27a7d9d01d707f0a61b6f3aab7c5c88cd8e20
|
/9/OPcenter-verifyCode/webmoni/migrations/0004_auto_20180509_1134.py
|
7fd30d54c41c527bab0803efd4f9378b14f557c1
|
[] |
no_license
|
lin-zh-cn/1test
|
6dbdd9a042b70d6131dec3ab1b980ee8c6a917bf
|
1e6ccdde7b5d18c70bba06a79f186952f6f02072
|
refs/heads/master
| 2020-03-19T07:42:00.634669
| 2018-06-21T10:34:57
| 2018-06-21T10:34:57
| 136,140,954
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 430
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2018-05-09 11:34
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webmoni', '0003_auto_20180509_1031'),
]
operations = [
migrations.RenameField(
model_name='domainname',
old_name='check',
new_name='check_id',
),
]
|
[
"scr_memory@foxmail.com"
] |
scr_memory@foxmail.com
|
2bea257ba29d7d3568169cd2499598f98eebd812
|
8255dcf7689c20283b5e75a452139e553b34ddf3
|
/app/views/dashboard/items/index.py
|
b38bac919cd8357f3585cc1c835d0bce2c8762e2
|
[
"MIT"
] |
permissive
|
Wern-rm/raton.by
|
09871eb4da628ff7b0d0b4415a150cf6c12c3e5a
|
68f862f2bc0551bf2327e9d6352c0cde93f45301
|
refs/heads/main
| 2023-05-06T02:26:58.980779
| 2021-05-25T14:09:47
| 2021-05-25T14:09:47
| 317,119,285
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,654
|
py
|
from flask import render_template, redirect, url_for, request
from flask_login import login_required
from flask_paginate import get_page_args
from app import db, logger
from app.controllers.dashboard_controller import dashboard_controller
from app.controllers.pagination import get_pagination
from app.forms.dashboard_items import ItemsCategoryForm, ItemsForm
from app.models.items import Items
from app.models.items_category import ItemsCategory
from app.views.dashboard import bp
@bp.route('/items', methods=['GET', 'POST'])
@login_required
@dashboard_controller
def items(**kwargs):
category = db.session.query(ItemsCategory).order_by(ItemsCategory.id).all()
count = db.session.query(Items).count()
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
form_create_category = ItemsCategoryForm()
if form_create_category.validate_on_submit() and request.form['form-id'] == '1':
try:
db.session.add(ItemsCategory(title=form_create_category.title.data))
db.session.commit()
return redirect(url_for('dashboard.items', action='success', id=21))
except Exception as e:
db.session.rollback()
logger.error(e)
return redirect(url_for('dashboard.items', action='error', id=7))
form_edit_category = ItemsCategoryForm()
if form_edit_category.validate_on_submit() and request.form['form-id'] == '2':
try:
category_id = int(request.form['category-id'])
found = db.session.query(ItemsCategory).filter(ItemsCategory.title == form_edit_category.title.data, ItemsCategory.id != category_id).first()
if not found:
db.session.query(ItemsCategory).filter(ItemsCategory.id == category_id).update({'title': form_edit_category.title.data})
db.session.commit()
return redirect(url_for('dashboard.items', action='success', id=22))
else:
return redirect(url_for('dashboard.items', action='error', id=8))
except Exception as e:
db.session.rollback()
logger.error(e)
return redirect(url_for('dashboard.items', action='error', id=9))
form_create_item = ItemsForm()
form_create_item.category_id.choices = [(i.id, i.title) for i in category]
if form_create_item.validate_on_submit() and request.form['form-id'] == '3':
try:
db.session.add(Items(title=form_create_item.title.data,
text=form_create_item.text.data,
category_id=form_create_item.category_id.data))
db.session.commit()
return redirect(url_for('dashboard.items', action='success', id=23))
except Exception as e:
db.session.rollback()
logger.error(e)
return redirect(url_for('dashboard.items', action='error', id=10))
form_edit_item = ItemsForm()
form_edit_item.category_id.choices = [(i.id, i.title) for i in category]
if form_edit_item.validate_on_submit() and request.form['form-id'] == '4':
try:
item_id = int(request.form['item-id'])
found = db.session.query(Items).filter(Items.title == form_edit_item.title.data, Items.id != item_id).first()
if not found:
db.session.query(Items).filter(Items.id == item_id).update({
'title': form_edit_item.title.data,
'category_id': form_edit_item.category_id.data,
'text': form_edit_item.text.data
})
db.session.commit()
return redirect(url_for('dashboard.items', action='success', id=7))
else:
return redirect(url_for('dashboard.items', action='error', id=12))
except Exception as e:
db.session.rollback()
logger.error(e)
return redirect(url_for('dashboard.items', action='error', id=11))
kwargs['title'] = 'Управление каталогом продукции'
kwargs['form_create_category'] = form_create_category
kwargs['form_edit_category'] = form_edit_category
kwargs['form_create_item'] = form_create_item
kwargs['form_edit_item'] = form_edit_item
kwargs['category'] = category
kwargs['items'] = db.session.query(Items).order_by(Items.id.desc()).limit(per_page).offset(offset).all()
kwargs['pagination'] = get_pagination(page=page, per_page=per_page, total=count, record_name='items', format_total=True, format_number=True)
return render_template("dashboard/items/index.html", **kwargs)
|
[
"devwern@gmail.com"
] |
devwern@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.