blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
a2a992f5ec919036c7b140d728f04d5c0d6585cb
252b3451ad9683166937152444fedec8b5da6647
/py/RepairUserDBPRefs.py
af964a133f91893c3a8aa04693308e54ac11ab7b
[ "MIT" ]
permissive
faithcomesbyhearing/dbp-etl
993c4c329d8f1950234f02f7fb048ec29b1883da
eb56863415d0d83f7f7928d0fcf927425c039f95
refs/heads/master
2023-08-08T15:11:37.815057
2023-07-10T16:10:21
2023-07-10T16:10:21
204,502,403
1
1
MIT
2023-07-24T23:39:37
2019-08-26T15:12:47
Python
UTF-8
Python
false
false
2,605
py
# RepairUserDBPRefs.py from SQLUtility import * class RepairUserDBPRefs: def __init__(self, db): self.db = db self.notFound = set() self.updateRows = [] def repairPlayListItemsFileset(self, dbpName, dbpUserName): sql = ("SELECT distinct bs.id, bf.book_id FROM %s.bible_filesets bs" " JOIN %s.bible_files bf ON bs.hash_id=bf.hash_id" " WHERE bs.set_type_code IN ('audio', 'audio_drama')" " AND length(bs.id) <= 12" % (dbpName, dbpName)) resultSet = self.db.select(sql, ()) print("-- num audio filesets and books", len(resultSet)) filesetMap = {} for (filesetId, bookId) in resultSet: bookSet = filesetMap.get(filesetId, set()) bookSet.add(bookId) filesetMap[filesetId] = bookSet print("-- num audio fileset", len(filesetMap.keys())) sql = ("SELECT id, playlist_id, fileset_id, book_id FROM %s.playlist_items WHERE fileset_id NOT IN" " (SELECT id FROM %s.bible_filesets) ORDER BY fileset_id, book_id") % (dbpUserName, dbpName) resultSet = self.db.select(sql, ()) for (playlistItemId, playlistId, filesetId, bookId) in resultSet: checkFilesetId = filesetId[:6] + "O" + filesetId[7:] found = self._checkPlaylists(filesetMap, checkFilesetId, bookId, playlistItemId) if not found: checkFilesetId = filesetId[:6] + "N" + filesetId[7:] found = self._checkPlaylists(filesetMap, checkFilesetId, bookId, playlistItemId) if not found: self.notFound.add((filesetId, bookId)) self._generateUpdate(dbpUserName) def _checkPlaylists(self, filesetMap, filesetId, bookId, playlistItemId): bookSet = filesetMap.get(filesetId) if bookSet == None: return False if not bookId in bookSet: return False self.updateRows.append((filesetId, playlistItemId)) return True def _generateUpdate(self, dbpUserName): for (filesetId, bookId) in sorted(list(self.notFound)): print("-- NOT FOUND", filesetId, bookId) for (filesetId, playlistItemId) in self.updateRows: sql = "UPDATE %s.playlist_items SET fileset_id = '%s' WHERE id = %s;" % (dbpUserName, filesetId, playlistItemId) print(sql) if (__name__ == '__main__'): from Config import * config = Config() db = SQLUtility(config) repair = RepairUserDBPRefs(db) repair.repairPlayListItemsFileset(config.database_db_name, config.database_user_db_name) db.close() """ SELECT DISTINCT fileset_id FROM dbp_users.playlist_items WHERE fileset_id NOT IN (SELECT id FROM dbp_210413.bible_filesets) SELECT distinct bs.id, bf.book_id FROM bible_filesets bs JOIN bible_files bf ON bs.hash_id=bf.hash_id WHERE bs.set_type_code like 'audio%' AND length(bs.id) <= 12 """
[ "gary@shortsands.com" ]
gary@shortsands.com
4e5640d32dece435226c3a04629c8428395dfdc8
926339e237914fffc4d95c6835a198f5038d2a9d
/python/examples/cam_isi_parallel_yolo.py
211e34acf19cb9f21d8cbcf11d6e1d9a0dd890f0
[]
no_license
YuehChuan/Kneron_Computer_Lab
34cb61523819683ddff2a77de09dee33c006d945
2c0e88556615b01b9613f10437bb3cbdd9744c8d
refs/heads/master
2023-01-05T13:23:03.820594
2020-11-06T03:34:20
2020-11-06T03:34:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,638
py
""" This is the example for cam isi yolo. """ import ctypes import sys import cv2 import time from common import constants from python_wrapper import kdp_wrapper def handle_result(inf_res, r_size, frames): """Handle the detected results returned from the model. Arguments: inf_res: Inference result data. r_size: Inference data size. frames: List of frames captured by the video capture instance. """ if r_size >= 4: header_result = ctypes.cast( ctypes.byref(inf_res), ctypes.POINTER(constants.ObjectDetectionRes)).contents box_result = ctypes.cast( ctypes.byref(header_result.boxes), ctypes.POINTER(constants.BoundingBox * header_result.box_count)).contents for box in box_result: x1 = int(box.x1) y1 = int(box.y1) x2 = int(box.x2) y2 = int(box.y2) frames[0] = cv2.rectangle(frames[0], (x1, y1), (x2, y2), (0, 0, 255), 3) cv2.imshow('detection', frames[0]) del frames[0] key = cv2.waitKey(1) if key == ord('q'): sys.exit() return 0 def user_test_cam_yolo(dev_idx, _user_id, test_loop): """User test cam yolo.""" image_source_h = 480 image_source_w = 640 app_id = constants.APP_TINY_YOLO3 image_size = image_source_w * image_source_h * 2 frames = [] # Setup video capture device. capture = kdp_wrapper.setup_capture(0, image_source_w, image_source_h) if capture is None: return -1 # Start ISI mode. if kdp_wrapper.start_isi_parallel(dev_idx, app_id, image_source_w, image_source_h): return -1 start_time = time.time() # Fill up the image buffers. ret, img_id_tx, img_left, buffer_depth = kdp_wrapper.fill_buffer( dev_idx, capture, image_size, frames) if ret: return -1 # Send the rest and get result in loop, with 2 images alternatively print("Companion image buffer depth = ", buffer_depth) kdp_wrapper.pipeline_inference( dev_idx, app_id, test_loop - buffer_depth, image_size, capture, img_id_tx, img_left, buffer_depth, frames, handle_result) end_time = time.time() diff = end_time - start_time estimate_runtime = float(diff/test_loop) fps = float(1/estimate_runtime) print("Parallel inference average estimate runtime is ", estimate_runtime) print("Average FPS is ", fps) return 0 def user_test_cam_isi_parallel_yolo(dev_idx, user_id): """User test cam isi yolo.""" #for i in range(10): user_test_cam_yolo(dev_idx, user_id, 1000) return
[ "kidd@KIDD_THINKPAD.localdomain" ]
kidd@KIDD_THINKPAD.localdomain
7302dce4d0794e688f937ea41f240a1aa6136abb
6527b66fd08d9e7f833973adf421faccd8b765f5
/yuancloud/addons/hr_payroll/report/report_payslip_details.py
d83a5bdbeb2c165176384bdbb5aa38a033c7ea3f
[]
no_license
cash2one/yuancloud
9a41933514e57167afb70cb5daba7f352673fb4d
5a4fd72991c846d5cb7c5082f6bdfef5b2bca572
refs/heads/master
2021-06-19T22:11:08.260079
2017-06-29T06:26:15
2017-06-29T06:26:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,062
py
#-*- coding:utf-8 -*- # Part of YuanCloud. See LICENSE file for full copyright and licensing details. from yuancloud.osv import osv from yuancloud.report import report_sxw class payslip_details_report(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(payslip_details_report, self).__init__(cr, uid, name, context) self.localcontext.update({ 'get_details_by_rule_category': self.get_details_by_rule_category, 'get_lines_by_contribution_register': self.get_lines_by_contribution_register, }) def get_details_by_rule_category(self, obj): payslip_line = self.pool.get('hr.payslip.line') rule_cate_obj = self.pool.get('hr.salary.rule.category') def get_recursive_parent(rule_categories): if not rule_categories: return [] if rule_categories[0].parent_id: rule_categories.insert(0, rule_categories[0].parent_id) get_recursive_parent(rule_categories) return rule_categories res = [] result = {} ids = [] for id in range(len(obj)): ids.append(obj[id].id) if ids: self.cr.execute('''SELECT pl.id, pl.category_id FROM hr_payslip_line as pl \ LEFT JOIN hr_salary_rule_category AS rc on (pl.category_id = rc.id) \ WHERE pl.id in %s \ GROUP BY rc.parent_id, pl.sequence, pl.id, pl.category_id \ ORDER BY pl.sequence, rc.parent_id''',(tuple(ids),)) for x in self.cr.fetchall(): result.setdefault(x[1], []) result[x[1]].append(x[0]) for key, value in result.iteritems(): rule_categories = rule_cate_obj.browse(self.cr, self.uid, [key]) parents = get_recursive_parent(rule_categories) category_total = 0 for line in payslip_line.browse(self.cr, self.uid, value): category_total += line.total level = 0 for parent in parents: res.append({ 'rule_category': parent.name, 'name': parent.name, 'code': parent.code, 'level': level, 'total': category_total, }) level += 1 for line in payslip_line.browse(self.cr, self.uid, value): res.append({ 'rule_category': line.name, 'name': line.name, 'code': line.code, 'total': line.total, 'level': level }) return res def get_lines_by_contribution_register(self, obj): payslip_line = self.pool.get('hr.payslip.line') result = {} res = [] for id in range(len(obj)): if obj[id].register_id: result.setdefault(obj[id].register_id.name, []) result[obj[id].register_id.name].append(obj[id].id) for key, value in result.iteritems(): register_total = 0 for line in payslip_line.browse(self.cr, self.uid, value): register_total += line.total res.append({ 'register_name': key, 'total': register_total, }) for line in payslip_line.browse(self.cr, self.uid, value): res.append({ 'name': line.name, 'code': line.code, 'quantity': line.quantity, 'amount': line.amount, 'total': line.total, }) return res class wrapped_report_payslipdetails(osv.AbstractModel): _name = 'report.hr_payroll.report_payslipdetails' _inherit = 'report.abstract_report' _template = 'hr_payroll.report_payslipdetails' _wrapped_report_class = payslip_details_report
[ "liuganghao@lztogether.com" ]
liuganghao@lztogether.com
3ee922ee2a29350a4af5ef743544db3cde942c9d
9089e7afd65ba2c6d5607999b7b7c7eacbc59b61
/python3/aboveaverage.py
07b5c840c9eb47438c2add8cfe6b55a8bb352e52
[]
no_license
TheChickenBoy/kattis
9e9fb88436991db9c2f290064c70881f46a13440
fdeb99faf5f630607c5179c678b03270869bae75
refs/heads/master
2023-03-19T10:18:10.084193
2021-03-18T14:53:34
2021-03-18T14:53:34
217,545,715
0
0
null
null
null
null
UTF-8
Python
false
false
260
py
import sys input() for l in sys.stdin: n=0 l = l.split() l = list(map(int, l)) tot = sum(l[1:l[0]+1]) avg = tot/l[0] for i in range(1,l[0]+1): if l[i]>avg: n+=1 print("%.3f" % ((n/l[0])*100)+'%')
[ "c16gws@cs.umu.se" ]
c16gws@cs.umu.se
2bb5e0c565e31cfd2f52b6a0a8799a13ad723fd2
a5d750f171119b6c40db155be17a79fb743f213d
/init_db.py
a6e10967e1eca58780a07169c53741ad9265e145
[]
no_license
ValentynZal/Low_Level_Rest_Api
4525aaab0c69aecaf89495985dbc67e764b9adef
38a5697a903eadf83cbfcf9494ade20e3956716d
refs/heads/master
2020-11-30T18:42:30.730894
2019-12-27T14:16:08
2019-12-27T14:16:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
500
py
from pymongo import MongoClient # client = MongoClient("mongodb://localhost:27017/") # db = client['database'] # users = db['users'] # install `mongodb` # > `sudo service mongodb start` # add path to mongo "connector" to the end of ~/.bashrc # > `source ~/.bashrc` client = MongoClient('mongodb+srv://valentyn:val11091994@cluster0-zl8k4.mongodb.net/test?retryWrites=true&w=majority') # --username valentyn db = client['database'] users = db['users'] # collection # print(users, 'USERS HERER')
[ "valentin11091994@gmail.com" ]
valentin11091994@gmail.com
4a4c1b576510a6956a1257700a407e6f513539af
054ef562d1d785568aaadae9b0d19f095fb23cb4
/py_file/ch01/pratice1.py
5f96ba5cff9e9bddf4ed8baaf3497f9d45dd784f
[]
no_license
danial1021/python-study
4653799f906983e4a5d1158d05dc2c50609bb5f9
e90b2876d5aa8c14c1875900ae994520373c592b
refs/heads/master
2022-01-23T02:49:31.000427
2019-07-22T14:30:00
2019-07-22T14:30:00
198,238,898
0
0
null
null
null
null
UTF-8
Python
false
false
532
py
# import json # from urllib.request import urlopen # url = "https://raw.githubusercontent.com/AstinChoi/introducing - python/master/intro/top_rated.json" # response = urlopen(url) # contents = response.read() # text = contents.decode('utf8') # data = json.loads(text) # for video in data['feed']['entry'][0:6]: # print(video['title']['$t']) # import requests # url = "www.google.com" # response = requests.get(url) # data = response.json() # for video in data['feed']['entry'][0:6]: # print(video['title']['$t'] print(1)
[ "41097199+danial1021@users.noreply.github.com" ]
41097199+danial1021@users.noreply.github.com
c3ac4d7052deeb6a92cc08d8afa96bfe69bad7c5
89b3278546cf9e8dd5a6a8b927ca722eb635dc02
/apps/global_crm/migrations/0004_gcrm_vehicle.py
556096849f1aa9cbeee1d9b87d8d1dae3fbcf9d1
[]
no_license
RichardHarleyson/greenhub_actual
27d2e33f97b70411198cf291239cdf1a97b153a1
0d00a23016a44dcf72b902222c225e98c8f933f9
refs/heads/master
2020-06-24T17:06:32.307639
2019-09-19T07:00:56
2019-09-19T07:00:56
199,023,995
0
0
null
null
null
null
UTF-8
Python
false
false
1,383
py
# Generated by Django 2.2.3 on 2019-09-13 06:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('global_crm', '0003_gcrm_files'), ] operations = [ migrations.CreateModel( name='GCrm_Vehicle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('veh_track_num', models.CharField(default='empty', max_length=30)), ('veh_w8_id', models.CharField(default='empty', max_length=30)), ('veh_VIN', models.CharField(default='empty', max_length=30)), ('veh_invoice_num', models.CharField(default='empty', max_length=30)), ('veh_win_date', models.CharField(default='empty', max_length=30)), ('veh_container_num', models.CharField(default='empty', max_length=30)), ('veh_incomming_date', models.CharField(default='empty', max_length=30)), ('veh_photo', models.CharField(default='empty', max_length=30)), ('veh_payed', models.BooleanField(default=False)), ('veh_client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='veh_client', to='global_crm.GCrm_Client')), ], ), ]
[ "richard.harleyson@gmail.com" ]
richard.harleyson@gmail.com
abd483a92b46bcc489964117d2d3e22fac094d51
554e71d2525122a97529da5241f2655a883217c2
/progclub/__init__.py
092a5b28564077275eee818decfa9c6a6fc76a5e
[]
no_license
jstankevicius/progclub
84c46a957adb46273e2aa9e7b3c520aebed7607d
04c2507be26ebbc6ef14af2d034968baebec8130
refs/heads/master
2023-05-30T15:33:40.040751
2020-06-07T22:55:26
2020-06-07T22:55:26
155,287,633
0
0
null
2023-05-01T20:32:31
2018-10-29T22:06:53
Python
UTF-8
Python
false
false
1,589
py
import os from flask import Flask def create_app(test_config=None): # test_config is an application configuration that makes launching easy. It's populated with values # that make things convenient, and should never be deployed. We pass it in during testing. app = Flask(__name__, instance_relative_config=True) # SECRET_KEY is set to a convenient value for testing. This should be changed once we actually deploy. # DATABASE is the path of our SQLite (or other) database. app.config.from_mapping(SECRET_KEY="dev") if test_config is None: # If there is a configured instance, we load that instead, if we are not testing. config.py # can be used to store real values that we don't want to be visible, like a real SECRET_KEY. app.config.from_pyfile("config.py", silent=False) else: # Otherwise, we load a test configuration to make stuff easier for ourselves. app.config.from_mapping(test_config) # We ensure that the application instance path exists. If it does, we simply ignore the error, # as everything is going as expected. try: os.makedirs(app.instance_path) except OSError: pass from . import auth from . import db from . import index from . import lab from . import admin from . import leaderboard app.register_blueprint(auth.bp) app.register_blueprint(index.bp) app.register_blueprint(lab.bp) app.register_blueprint(admin.bp) app.register_blueprint(leaderboard.bp) app.add_url_rule("/", endpoint="index") return app
[ "juuuuuustas@gmail.com" ]
juuuuuustas@gmail.com
82ac02823b951c6cdf88c7b3a83674150f9977c2
1efd2de8bf77ec00eb2fcaf5749278495946d920
/src/tests/ftest/security/cont_overwrite_acl.py
786f66c96bf3fd07316c9d50547e79efc4c662b2
[ "BSD-2-Clause", "BSD-2-Clause-Patent" ]
permissive
daos-stack/daos
6f55bf3061fd830d5b8d28506e1295e2d3a27c38
ed5eed5df43a68571afe123132a743824c02637a
refs/heads/master
2023-08-31T21:43:37.606145
2023-08-31T16:38:00
2023-08-31T16:38:00
69,390,670
631
300
NOASSERTION
2023-09-14T18:55:15
2016-09-27T19:21:29
C
UTF-8
Python
false
false
6,872
py
""" (C) Copyright 2020-2023 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ import os from avocado import fail_on from cont_security_test_base import ContSecurityTestBase from security_test_base import create_acl_file from exception_utils import CommandFailure class OverwriteContainerACLTest(ContSecurityTestBase): """Test Class Description: Test to verify ACL entry overwrite. :avocado: recursive """ def setUp(self): """Set up each test case.""" super().setUp() self.acl_filename = "test_overwrite_acl_file.txt" self.daos_cmd = self.get_daos_command() self.prepare_pool() self.add_container(self.pool) # List of ACL entries self.cont_acl = self.get_container_acl_list( self.pool.uuid, self.container.uuid) def test_acl_overwrite_invalid_inputs(self): """ JIRA ID: DAOS-3708 Test Description: Test that container overwrite command performs as expected with invalid inputs in command line and within ACL file provided. :avocado: tags=all,daily_regression :avocado: tags=vm :avocado: tags=security,container,container_acl,daos_cmd :avocado: tags=OverwriteContainerACLTest,test_acl_overwrite_invalid_inputs """ # Get list of invalid ACL principal values invalid_acl_filename = self.params.get("invalid_acl_filename", "/run/*") # Disable raising an exception if the daos command fails self.daos_cmd.exit_status_exception = False # Check for failure on invalid inputs test_errs = [] for acl_file in invalid_acl_filename: # Run overwrite command self.daos_cmd.container_overwrite_acl( self.pool.uuid, self.container.uuid, acl_file) test_errs.extend(self.error_handling( self.daos_cmd.result, "no such file or directory")) # Check that the acl file was unchanged self.acl_file_diff(self.cont_acl) if test_errs: self.fail("container overwrite-acl command expected to fail: \ {}".format("\n".join(test_errs))) def test_overwrite_invalid_acl_file(self): """ JIRA ID: DAOS-3708 Test Description: Test that container overwrite command performs as expected with invalid inputs in command line and within ACL file provided. :avocado: tags=all,daily_regression :avocado: tags=vm :avocado: tags=security,container,container_acl,daos_cmd :avocado: tags=OverwriteContainerACLTest,test_overwrite_invalid_acl_file """ invalid_file_content = self.params.get( "invalid_acl_file_content", "/run/*") path_to_file = os.path.join(self.tmp, self.acl_filename) # Disable raising an exception if the daos command fails self.daos_cmd.exit_status_exception = False test_errs = [] for content in invalid_file_content: create_acl_file(path_to_file, content) exp_err = "-1003" if content == []: exp_err = "no entries" # Run overwrite command self.daos_cmd.container_overwrite_acl( self.pool.uuid, self.container.uuid, path_to_file) test_errs.extend(self.error_handling(self.daos_cmd.result, exp_err)) # Check that the acl file was unchanged self.acl_file_diff(self.cont_acl) if test_errs: self.fail("container overwrite-acl command expected to fail: \ {}".format("\n".join(test_errs))) @fail_on(CommandFailure) def test_overwrite_valid_acl_file(self): """ JIRA ID: DAOS-3708 Test Description: Test that container overwrite command performs as expected with valid ACL file provided. :avocado: tags=all,daily_regression, :avocado: tags=vm :avocado: tags=security,container,container_acl,daos_cmd :avocado: tags=OverwriteContainerACLTest,test_overwrite_valid_acl_file """ valid_file_acl = self.params.get("valid_acl_file", "/run/*") path_to_file = os.path.join(self.tmp, self.acl_filename) # Disable raising an exception if the daos command fails self.daos_cmd.exit_status_exception = False # Run overwrite command, test will fail if command fails. for content in valid_file_acl: create_acl_file(path_to_file, content) self.daos_cmd.container_overwrite_acl( self.pool.uuid, self.container.uuid, path_to_file) # Check that the acl file was unchanged self.acl_file_diff(content) def test_cont_overwrite_acl_no_perm(self): """ JIRA ID: DAOS-3708 Test Description: Test that container overwrite command fails with no permission -1001 when user doesn't have the right permissions. :avocado: tags=all,daily_regression, :avocado: tags=vm :avocado: tags=security,container,container_acl,daos_cmd :avocado: tags=OverwriteContainerACLTest,test_cont_overwrite_acl_no_perm """ valid_file_content = self.params.get("valid_acl_file", "/run/*") path_to_file = os.path.join(self.tmp, self.acl_filename) # Let's give access to the pool to the root user self.get_dmg_command().pool_update_acl( self.pool.uuid, entry="A::EVERYONE@:rw") # The root user shouldn't have access to deleting container ACL entries self.daos_cmd.sudo = True # Disable raising an exception if the daos command fails self.daos_cmd.exit_status_exception = False # Let's check that we can't run as root (or other user) and overwrite # entries if no permissions are set for that user. test_errs = [] for content in valid_file_content: create_acl_file(path_to_file, content) self.daos_cmd.container_overwrite_acl( self.pool.uuid, self.container.uuid, path_to_file) test_errs.extend(self.error_handling(self.daos_cmd.result, "-1001")) # Check that the acl was unchanged. post_test_acls = self.get_container_acl_list( self.pool.uuid, self.container.uuid) if not self.compare_acl_lists(self.cont_acl, post_test_acls): self.fail("Previous ACL:\n{} Post command ACL:{}".format( self.cont_acl, post_test_acls)) if test_errs: self.fail("container overwrite-acl command expected to fail: \ {}".format("\n".join(test_errs)))
[ "noreply@github.com" ]
daos-stack.noreply@github.com
d1c4c957c81afd15f65046c44005c988470251f5
37786f3e0bee213f3fe19e77f6fd4b21fa35caa8
/mysite/settings.py
c38be37aaff4510073a8308bb732e36d37afd155
[]
no_license
Danush-TBR/mysite
753afbae4d1acdf405f532022c8224a2b7a650ee
69c61bae1ef220b3f4155747818fbb39c0cfffde
refs/heads/master
2023-05-02T19:06:53.625365
2021-06-01T11:40:06
2021-06-01T11:40:06
372,494,097
1
0
null
null
null
null
UTF-8
Python
false
false
3,161
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.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/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'b#s*_o(3t3ai_k(c5po@h7a=nj5#vjkd3u7ckhnx@)mi=8fn67' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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/3.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/3.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/3.0/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/3.0/howto/static-files/ STATIC_URL = '/static/' ALLOWED_HOSTS = ['*'] X_FRAME_OPTIONS = '*'
[ "" ]
5d9f9b56fad107e99ce1f288022325480df0eb8c
efb5f556f7937dd8d1507f4d293f4d541cf0c494
/test.py
1f26b376f757d16dca17f6d15f4408419e5b8ea8
[]
no_license
bomer/friend
32a45741e15482c7a81367870db74fc96615dfc1
13f0aed8c72f3457323bab7cf35d3eebc70634c8
refs/heads/master
2021-01-21T14:24:07.392570
2017-06-24T10:38:08
2017-06-24T10:38:08
95,275,545
0
0
null
null
null
null
UTF-8
Python
false
false
204
py
#!/usr/bin/python import requests import re url = 'https://www.facebook.com/jimmeyotoole' idre = re.compile('"entity_id":"([0-9]+)"') page = requests.get(url) print(idre.findall(page.content.decode()))
[ "jimmeyotoole@gmail.com" ]
jimmeyotoole@gmail.com
b325fdda2434f2dac699faab094d01d09f64c730
7cfc2f7776f1fd871a924fd97dc70f846b005ca1
/chef/api.py
6f7a9ef9f7aa7cc2a539d991ef04ca4abf3548bc
[]
no_license
cshoe/pychef
5468860cb14936bcbc3205fed2429ef58854d04c
1c80c4fe6de5639d4fee39147394a0599d66e20f
refs/heads/master
2021-01-18T03:01:45.892341
2012-03-09T22:51:45
2012-03-09T22:51:45
3,675,579
0
0
null
null
null
null
UTF-8
Python
false
false
8,081
py
import copy import datetime import itertools import logging import os import re import socket import threading import urllib2 import urlparse import weakref from chef.auth import sign_request from chef.exceptions import ChefServerError from chef.rsa import Key from chef.utils import json from chef.utils.file import walk_backwards api_stack = threading.local() log = logging.getLogger('chef.api') def api_stack_value(): if not hasattr(api_stack, 'value'): api_stack.value = [] return api_stack.value class UnknownRubyExpression(Exception): """Token exception for unprocessed Ruby expressions.""" class ChefRequest(urllib2.Request): """Workaround for using PUT/DELETE with urllib2.""" def __init__(self, *args, **kwargs): self._method = kwargs.pop('method', None) # Request is an old-style class, no super() allowed. urllib2.Request.__init__(self, *args, **kwargs) def get_method(self): if self._method: return self._method return urllib2.Request.get_method(self) class ChefAPI(object): """The ChefAPI object is a wrapper for a single Chef server. .. admonition:: The API stack PyChef maintains a stack of :class:`ChefAPI` objects to be use with other methods if an API object isn't given explicitly. The first ChefAPI created will become the default, though you can set a specific default using :meth:`ChefAPI.set_default`. You can also use a ChefAPI as a context manager to create a scoped default:: with ChefAPI('http://localhost:4000', 'client.pem', 'admin'): n = Node('web1') """ ruby_value_re = re.compile(r'#\{([^}]+)\}') def __init__(self, url, key, client, version='0.9.12'): self.url = url.rstrip('/') self.parsed_url = urlparse.urlparse(self.url) if not isinstance(key, Key): key = Key(key) self.key = key self.client = client self.version = version self.platform = self.parsed_url.hostname == 'api.opscode.com' if not api_stack_value(): self.set_default() @classmethod def from_config_file(cls, path): """Load Chef API paraters from a config file. Returns None if the config can't be used. """ log.debug('Trying to load from "%s"', path) if not os.path.isfile(path) or not os.access(path, os.R_OK): # Can't even read the config file log.debug('Unable to read config file "%s"', path) return url = key_path = client_name = None for line in open(path): if not line.strip() or line.startswith('#'): continue # Skip blanks and comments parts = line.split(None, 1) if len(parts) != 2: continue # Not a simple key/value, we can't parse it anyway key, value = parts value = value.strip().strip('"\'') def _ruby_value(match): expr = match.group(1).strip() if expr == 'current_dir': return os.path.dirname(path) log.debug('Unknown ruby expression in line "%s"', line) raise UnknownRubyExpression try: value = cls.ruby_value_re.sub(_ruby_value, value) except UnknownRubyExpression: continue if key == 'chef_server_url': url = value elif key == 'node_name': client_name = value elif key == 'client_key': # When http://tickets.opscode.com/browse/CHEF-2011 is resolved # there will need to be some post-processing here key_path = value if not url: # No URL, no chance this was valid log.debug('No Chef server URL found') return if not key_path: # Try and use ./client.pem key_path = os.path.join(os.path.dirname(path), 'client.pem') if not os.path.isfile(key_path) or not os.access(key_path, os.R_OK): # Can't read the client key log.debug('Unable to read key file "%s"', key_path) return if not client_name: client_name = socket.getfqdn() return cls(url, key_path, client_name) @staticmethod def get_global(): """Return the API on the top of the stack.""" while api_stack_value(): api = api_stack_value()[-1]() if api is not None: return api del api_stack_value()[-1] def set_default(self): """Make this the default API in the stack. Returns the old default if any.""" old = None if api_stack_value(): old = api_stack_value().pop(0) api_stack_value().insert(0, weakref.ref(self)) return old def __enter__(self): api_stack_value().append(weakref.ref(self)) return self def __exit__(self, type, value, traceback): del api_stack_value()[-1] def _request(self, method, url, data, headers): # Testing hook, subclass and override for WSGI intercept request = ChefRequest(url, data, headers, method=method) return urllib2.urlopen(request).read() def request(self, method, path, headers={}, data=None): auth_headers = sign_request(key=self.key, http_method=method, path=self.parsed_url.path+path.split('?', 1)[0], body=data, host=self.parsed_url.netloc, timestamp=datetime.datetime.utcnow(), user_id=self.client) headers = dict((k.lower(), v) for k, v in headers.iteritems()) headers['x-chef-version'] = self.version headers.update(auth_headers) try: response = self._request(method, self.url+path, data, dict((k.capitalize(), v) for k, v in headers.iteritems())) except urllib2.HTTPError, e: err = e.read() try: err = json.loads(err) raise ChefServerError.from_error(err['error'], code=e.code) except ValueError: pass raise return response def api_request(self, method, path, headers={}, data=None): headers = dict((k.lower(), v) for k, v in headers.iteritems()) headers['accept'] = 'application/json' if data is not None: headers['content-type'] = 'application/json' data = json.dumps(data) response = self.request(method, path, headers, data) return json.loads(response) def __getitem__(self, path): return self.api_request('GET', path) def autoconfigure(base_path=None): """Try to find a knife or chef-client config file to load parameters from, starting from either the given base path or the current working directory. The lookup order mirrors the one from Chef, first all folders from the base path are walked back looking for .chef/knife.rb, then ~/.chef/knife.rb, and finally /etc/chef/client.rb. The first file that is found and can be loaded successfully will be loaded into a :class:`ChefAPI` object. """ base_path = base_path or os.getcwd() # Scan up the tree for a knife.rb or client.rb. If that fails try looking # in /etc/chef. The /etc/chef check will never work in Win32, but it doesn't # hurt either. for path in walk_backwards(base_path): config_path = os.path.join(path, '.chef', 'knife.rb') api = ChefAPI.from_config_file(config_path) if api is not None: return api # The walk didn't work, try ~/.chef/knife.rb config_path = os.path.expanduser(os.path.join('~', '.chef', 'knife.rb')) api = ChefAPI.from_config_file(config_path) if api is not None: return api # Nothing in the home dir, try /etc/chef/client.rb config_path = os.path.join(os.path.sep, 'etc', 'chef', 'client.rb') api = ChefAPI.from_config_file(config_path) if api is not None: return api
[ "noah@coderanger.net" ]
noah@coderanger.net
b9a0408e0dabda6b8be355a48c7c23f94cc52019
9f0d2e04c0aa7b2874094f449c9b60fd25ba0fba
/oneflow/python/nn/modules/abs.py
15a3e01f9b3704bef3ada383fd1065945d6e1329
[ "Apache-2.0" ]
permissive
sunying1985/oneflow
47dcbfefbb5c3a0aa98c857e80f32a28fe99804f
19840dad68a8569179946c1065cc138aec05762a
refs/heads/master
2023-05-07T09:11:14.646646
2021-06-03T08:18:20
2021-06-03T08:18:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,675
py
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable 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. """ import oneflow as flow from oneflow.python.oneflow_export import oneflow_export, experimental_api from oneflow.python.nn.module import Module from oneflow.python.framework.tensor import register_tensor_op class Abs(Module): def __init__(self): super().__init__() self._op = flow.builtin_op("abs").Input("x").Output("y").Build() def forward(self, x): res = self._op(x)[0] return res @oneflow_export("abs") @register_tensor_op("abs") @experimental_api def abs_op(x): r"""Return the absolute value of each element in input tensor:math:`y = |x|` element-wise. Args: input (Tensor): the input tensor. For example: .. code-block:: python >>> import oneflow.experimental as flow >>> import numpy as np >>> flow.enable_eager_execution() >>> x = flow.Tensor(np.array([-1, 2, -3, 4]).astype(np.float32)) >>> flow.abs(x) tensor([1., 2., 3., 4.], dtype=oneflow.float32) """ return Abs()(x) if __name__ == "__main__": import doctest doctest.testmod()
[ "noreply@github.com" ]
sunying1985.noreply@github.com
fb083383c0c94fd158db93ea4b6ff27f779e3749
7bb4ed3368e8cad656a44a450c8269151530b9d5
/profiles/views.py
1ebf28aa989f0503206e41037b012711758a25f7
[]
no_license
AmyKeedwell/boutique_ado_v1
b2582e589bbde9c348f87a29b3dc41e1a57f1984
aa305cd8ed14acb42586c7b50e98bf070467f47a
refs/heads/master
2023-03-12T10:35:05.544308
2021-02-24T22:26:13
2021-02-24T22:26:13
333,544,376
0
0
null
null
null
null
UTF-8
Python
false
false
1,447
py
from django.shortcuts import render, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import UserProfile from .forms import UserProfileForm from checkout.models import Order @login_required def profile(request): """ Display the user's profile. """ profile = get_object_or_404(UserProfile, user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, 'Profile updated successfully') else: messages.error(request, 'Update Failed. Please ensure the form is valid.') else: form = UserProfileForm(instance=profile) orders = profile.orders.all() template = 'profiles/profile.html' context = { 'form': form, 'orders': orders, 'on_profile_page': True, } return render(request, template, context) def order_history(request, order_number): order = get_object_or_404(Order, order_number=order_number) messages.info(request, ( f'This is a past confirmation for order number {order_number}. ' 'A confirmation email was sent on the order date.' )) template = 'checkout/checkout_success.html' context = { 'order': order, 'from_profile': True, } return render(request, template, context)
[ "amii1595@live.co.uk" ]
amii1595@live.co.uk
0deaced6af485fc7f0776b21c7ae87698979dd38
6c137e70bb6b1b618fbbceddaeb74416d387520f
/lantz/lantz/drivers/sutter/__init__.py
f709816f89e0bcceb3dc86f45da921b110797cce
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
zhong-lab/code
fe497c75662f8c3b7ab3c01e7e351bff6d5e8d15
b810362e06b44387f0768353c602ec5d29b551a2
refs/heads/master
2023-01-28T09:46:01.448833
2022-06-12T22:53:47
2022-06-12T22:53:47
184,670,765
2
7
BSD-2-Clause
2022-12-08T21:46:15
2019-05-02T23:37:39
Python
UTF-8
Python
false
false
403
py
# -*- coding: utf-8 -*- """ lantz.drivers.sutter ~~~~~~~~~~~~~~~~~~~~ :company: Sutter Instrument. :description: Biomedical and scientific instrumentation. :website: http://www.sutter.com/ --- :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from .lambda103 import Lambda103 __all__ = ['Lambda103', ]
[ "none" ]
none
52cd2578eea6bc7e17510763df69c81f4119dc49
f6e84c31d892479443d4e6aaf23bfab08684be33
/uva10407.py
388577120166078717ee9a63a3f6e540ebcb0adb
[]
no_license
engrjislam/uva_python
92a9cf04aac597083a78f5e8d7ebe31f3229de6a
00eb4cd514cf26524bcf242e66bfedaee971450e
refs/heads/master
2021-08-17T07:32:00.015545
2017-11-20T23:08:57
2017-11-20T23:08:57
111,472,624
0
0
null
null
null
null
UTF-8
Python
false
false
472
py
''' uva: 10407 description: https://uva.onlinejudge.org/external/104/10407.pdf ''' def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(str(i)) if n > 1: factors.append(str(n)) return factors def main(): while True: n = int(input()) if n == 0: break print(prime_factors(n)) main()
[ "noreply@github.com" ]
engrjislam.noreply@github.com
a98a0e4a4eaff54681612508e9d55ab2ee5e152f
ea76f885ffa65f2136203bbc31d7b7e7d424df7e
/snakemake/wrappers/.snakemake.y61_7wgk.merge_bams_wrapper.py
1ebad7c6f176114d26b4fbe750201714d4e748a8
[ "BSD-2-Clause" ]
permissive
saketkc/EE-546-project
b193e6075641b974bb87f3a08d1ecf56fdd99b2e
fb7eacd90f6c0a2cb3061837ec5427a14f521aa5
refs/heads/master
2021-10-21T04:42:44.796718
2019-03-03T03:08:15
2019-03-03T03:08:15
157,302,728
2
0
null
null
null
null
UTF-8
Python
false
false
5,792
py
######## Snakemake header ######## import sys; sys.path.append("/home/cmb-panasas2/skchoudh/software_frozen/anaconda27/envs/riboraptor/lib/python3.5/site-packages"); import pickle; snakemake = pickle.loads(b'\x80\x03csnakemake.script\nSnakemake\nq\x00)\x81q\x01}q\x02(X\x06\x00\x00\x00outputq\x03csnakemake.io\nOutputFiles\nq\x04)\x81q\x05X\x12\x00\x00\x00bams/SRX399823.bamq\x06a}q\x07X\x06\x00\x00\x00_namesq\x08}q\tsbX\x07\x00\x00\x00threadsq\nK\x01X\x03\x00\x00\x00logq\x0bcsnakemake.io\nLog\nq\x0c)\x81q\r}q\x0eh\x08}q\x0fsbX\x04\x00\x00\x00ruleq\x10X\n\x00\x00\x00merge_bamsq\x11X\x06\x00\x00\x00paramsq\x12csnakemake.io\nParams\nq\x13)\x81q\x14X\x04\x00\x00\x00/tmpq\x15a}q\x16(X\x07\x00\x00\x00tmp_dirq\x17h\x15h\x08}q\x18h\x17K\x00N\x86q\x19subX\x05\x00\x00\x00inputq\x1acsnakemake.io\nInputFiles\nq\x1b)\x81q\x1c(X\x17\x00\x00\x00bams_srr/SRR1062555.bamq\x1dX\x17\x00\x00\x00bams_srr/SRR1062556.bamq\x1eX\x17\x00\x00\x00bams_srr/SRR1062557.bamq\x1fX\x17\x00\x00\x00bams_srr/SRR1062558.bamq X\x17\x00\x00\x00bams_srr/SRR1062559.bamq!X\x17\x00\x00\x00bams_srr/SRR1062560.bamq"X\x17\x00\x00\x00bams_srr/SRR1062561.bamq#X\x17\x00\x00\x00bams_srr/SRR1062562.bamq$X\x17\x00\x00\x00bams_srr/SRR1062563.bamq%X\x17\x00\x00\x00bams_srr/SRR1062564.bamq&X\x17\x00\x00\x00bams_srr/SRR1062565.bamq\'X\x17\x00\x00\x00bams_srr/SRR1062566.bamq(X\x17\x00\x00\x00bams_srr/SRR1062567.bamq)X\x17\x00\x00\x00bams_srr/SRR1062568.bamq*X\x17\x00\x00\x00bams_srr/SRR1062569.bamq+X\x17\x00\x00\x00bams_srr/SRR1062570.bamq,X\x17\x00\x00\x00bams_srr/SRR1062571.bamq-X\x17\x00\x00\x00bams_srr/SRR1062572.bamq.X\x17\x00\x00\x00bams_srr/SRR1062573.bamq/X\x17\x00\x00\x00bams_srr/SRR1062574.bamq0X\x17\x00\x00\x00bams_srr/SRR1062575.bamq1X\x17\x00\x00\x00bams_srr/SRR1062576.bamq2X\x17\x00\x00\x00bams_srr/SRR1062577.bamq3X\x17\x00\x00\x00bams_srr/SRR1062578.bamq4X\x17\x00\x00\x00bams_srr/SRR1062579.bamq5X\x17\x00\x00\x00bams_srr/SRR1062580.bamq6X\x17\x00\x00\x00bams_srr/SRR1062581.bamq7X\x17\x00\x00\x00bams_srr/SRR1062582.bamq8X\x17\x00\x00\x00bams_srr/SRR1062583.bamq9X\x17\x00\x00\x00bams_srr/SRR1062584.bamq:X\x17\x00\x00\x00bams_srr/SRR1062585.bamq;X\x17\x00\x00\x00bams_srr/SRR1062586.bamq<X\x17\x00\x00\x00bams_srr/SRR1062587.bamq=X\x17\x00\x00\x00bams_srr/SRR1062588.bamq>X\x17\x00\x00\x00bams_srr/SRR1062589.bamq?X\x17\x00\x00\x00bams_srr/SRR1062590.bamq@X\x17\x00\x00\x00bams_srr/SRR1062591.bamqAX\x17\x00\x00\x00bams_srr/SRR1062592.bamqBX\x17\x00\x00\x00bams_srr/SRR1062593.bamqCX\x17\x00\x00\x00bams_srr/SRR1062594.bamqDX\x17\x00\x00\x00bams_srr/SRR1062595.bamqEX\x17\x00\x00\x00bams_srr/SRR1062596.bamqFX\x17\x00\x00\x00bams_srr/SRR1062597.bamqGX\x17\x00\x00\x00bams_srr/SRR1062598.bamqHX\x17\x00\x00\x00bams_srr/SRR1062599.bamqIX\x17\x00\x00\x00bams_srr/SRR1062600.bamqJX\x17\x00\x00\x00bams_srr/SRR1062601.bamqKX\x17\x00\x00\x00bams_srr/SRR1062602.bamqLX\x17\x00\x00\x00bams_srr/SRR1062603.bamqMX\x17\x00\x00\x00bams_srr/SRR1062604.bamqNX\x17\x00\x00\x00bams_srr/SRR1062605.bamqOX\x17\x00\x00\x00bams_srr/SRR1062606.bamqPX\x17\x00\x00\x00bams_srr/SRR1062607.bamqQX\x17\x00\x00\x00bams_srr/SRR1062608.bamqRX\x17\x00\x00\x00bams_srr/SRR1062609.bamqSX\x17\x00\x00\x00bams_srr/SRR1062610.bamqTX\x17\x00\x00\x00bams_srr/SRR1062611.bamqUX\x17\x00\x00\x00bams_srr/SRR1062612.bamqVX\x17\x00\x00\x00bams_srr/SRR1062613.bamqWX\x17\x00\x00\x00bams_srr/SRR1062614.bamqXX\x17\x00\x00\x00bams_srr/SRR1062615.bamqYX\x17\x00\x00\x00bams_srr/SRR1062616.bamqZX\x17\x00\x00\x00bams_srr/SRR1062617.bamq[X\x17\x00\x00\x00bams_srr/SRR1062618.bamq\\X\x17\x00\x00\x00bams_srr/SRR1062619.bamq]X\x17\x00\x00\x00bams_srr/SRR1062620.bamq^X\x17\x00\x00\x00bams_srr/SRR1062621.bamq_X\x17\x00\x00\x00bams_srr/SRR1062622.bamq`X\x17\x00\x00\x00bams_srr/SRR1062623.bamqaX\x17\x00\x00\x00bams_srr/SRR1062624.bamqbX\x17\x00\x00\x00bams_srr/SRR1062625.bamqcX\x17\x00\x00\x00bams_srr/SRR1062626.bamqdX\x17\x00\x00\x00bams_srr/SRR1062627.bamqeX\x17\x00\x00\x00bams_srr/SRR1062628.bamqfX\x17\x00\x00\x00bams_srr/SRR1062629.bamqgX\x17\x00\x00\x00bams_srr/SRR1062630.bamqhX\x17\x00\x00\x00bams_srr/SRR1062631.bamqiX\x17\x00\x00\x00bams_srr/SRR1062632.bamqjX\x17\x00\x00\x00bams_srr/SRR1062633.bamqkX\x17\x00\x00\x00bams_srr/SRR1062634.bamqlX\x17\x00\x00\x00bams_srr/SRR1062635.bamqmX\x17\x00\x00\x00bams_srr/SRR1062636.bamqnX\x17\x00\x00\x00bams_srr/SRR1062637.bamqoX\x17\x00\x00\x00bams_srr/SRR1062638.bamqpe}qqh\x08}qrsbX\t\x00\x00\x00wildcardsqscsnakemake.io\nWildcards\nqt)\x81quX\t\x00\x00\x00SRX399823qva}qw(X\x06\x00\x00\x00sampleqxhvh\x08}qyX\x06\x00\x00\x00sampleqzK\x00N\x86q{subX\t\x00\x00\x00resourcesq|csnakemake.io\nResources\nq})\x81q~(K\x01K\x01e}q\x7f(X\x06\x00\x00\x00_coresq\x80K\x01X\x06\x00\x00\x00_nodesq\x81K\x01h\x08}q\x82(h\x80K\x00N\x86q\x83h\x81K\x01N\x86q\x84uubX\x06\x00\x00\x00configq\x85}q\x86X\x0b\x00\x00\x00config_pathq\x87X\x1b\x00\x00\x00configs/GRCz10_SRP034750.pyq\x88sub.'); from snakemake.logging import logger; logger.printshellcmds = True ######## Original script ######### import os import tempfile from snakemake.shell import shell if len(snakemake.input) > 1: with tempfile.TemporaryDirectory(dir=snakemake.params.tmp_dir) as temp_dir: cmd = ' -in '.join(snakemake.input) shell(r'''bamtools merge -in {cmd} -out {snakemake.output}.unsorted \ && samtools sort -@ {snakemake.threads} \ -T {temp_dir}/{snakemake.wildcards.sample}_merge_bam \ -o {snakemake.output} {snakemake.output}.unsorted \ && samtools index {snakemake.output} \ && yes | rm -rf {snakemake.output}.unsorted''') elif len(snakemake.input) == 1: source = os.path.abspath(str(snakemake.input[0])) destination = os.path.abspath(str(snakemake.output)) shell('''cp {source} {destination} && cp {source}.bai {destination}.bai''')
[ "saketkc@gmail.com" ]
saketkc@gmail.com
4dbc084d2391baf59d7cde123f2e02c50a6245dd
9fad5a74c85cd84ab32e39fbbeb17201761b36e9
/example/01自然语言处理库Jieba介绍/03基于TF-IDF算法的关键词抽取.py
569edcefe094ba8f706cdd3c088b9ef02ebdc056
[ "Apache-2.0" ]
permissive
hanyanze/FS_AILPA
4bcd3b75c23e20024c811036f7d4eda870e30d77
78cc2f196895972ba1c77f58140e224cdda79ae1
refs/heads/master
2022-10-25T20:04:56.129628
2020-06-19T08:41:38
2020-06-19T08:41:38
272,838,399
1
0
null
null
null
null
UTF-8
Python
false
false
280
py
import jieba.analyse file = "ai.txt" topK = 12 content = open(file, 'rb').read() tags = jieba.analyse.extract_tags(content, topK=topK) print(tags) # withWeight=True:将权重值一起返回 tags = jieba.analyse.extract_tags(content, topK=topK, withWeight=True) print(tags)
[ "825537984@qq.com" ]
825537984@qq.com
05230055fc67f20dc0ec377ab0ff22129b514146
99038ddca74c58511f7ca0c5df42fe7803175d48
/python/Angle between hour and minute hand.py
677efb5b7e8cf16efdbc77b1a7027ee41c7c0d2e
[]
no_license
agrawal-prateek/GeeksForGeeks
ba5ecad3244b7ce31e8cf4514d473169569e3188
7d62787f8e9b92218608107b947841e5b1c72dd9
refs/heads/master
2020-09-23T01:00:50.014385
2019-12-08T17:53:14
2019-12-08T17:53:14
225,360,773
6
1
null
null
null
null
UTF-8
Python
false
false
948
py
""" Calculate the angle between hour hand and minute hand. There can be two angles between hands, we need to print minimum of two. Also, we need to print floor of final result angle. For example, if the final angle is 10.61, we need to print 10. Input: The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consists of one line conatining two space separated numbers h and m where h is hour and m is minute. Output: Coresponding to each test case, print the angle b/w hour and min hand in a separate line. Constraints: 1 ≤ T ≤ 100 1 ≤ h ≤ 12 1 ≤ m ≤ 60 Example: Input 2 9 60 3 30 Output 90 75 """ t = int(input().strip()) for _ in range(t): h, m = [float(x) for x in input().strip().split()] if h == 12: h = 0 if m == 60: m = 0 h = (h * 5) + (m / 12) angle = 6 * abs(m - h) print(int(min(360 - angle, angle)))
[ "prateekagrawal89760@gmail.com" ]
prateekagrawal89760@gmail.com
4a0f75b53e79c596a27d59894857f06c5efba9ef
ebb9e1bbec3a33b5ca60c91debde0d4ad31313fc
/agenda/migrations/0010_alocarveiculos.py
23fdfda4db15e875cb3452c7c96ac619ce696f59
[]
no_license
KennyaLacerda/hackathon
2c9a17930d8ed21678439dd94094e720f0f80bd2
12ddaeb7f4cb9fff8148cd590f5bca5272d9250b
refs/heads/master
2020-03-30T05:38:55.823063
2018-09-29T20:13:38
2018-09-29T20:13:38
150,811,476
1
0
null
null
null
null
UTF-8
Python
false
false
887
py
# Generated by Django 2.0.5 on 2018-09-29 14:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('agenda', '0009_auto_20180929_1031'), ] operations = [ migrations.CreateModel( name='AlocarVeiculos', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('data_viagem', models.DateField()), ('alocado', models.BooleanField()), ('qtd_cabe', models.IntegerField()), ('Veiculo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='agenda.Veiculo')), ('agenda', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='agenda.AgendarConsulta')), ], ), ]
[ "kennyalacerda7@gmail.com" ]
kennyalacerda7@gmail.com
a6784b42db1a770abe4cd1adbbd98bbf547484ac
27bf045d1e09cb7c01aa3d1d7f2ae9cc40638d0b
/RBE/main/admin.py
76789cb92b02f15c8b88bc1f66c82d8e5e8bf2e1
[ "Unlicense" ]
permissive
rodgar-nvkz/RBE
bb8f43ed104ca1b3ec4e0ccfc77d96d793dcff30
72c7f0074a2cf95b7687bac385431a0980a1cc4a
refs/heads/master
2020-04-22T17:16:27.810101
2013-08-25T04:19:19
2013-08-25T04:19:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
181
py
__author__ = 'rd' from django.contrib import admin from RBE.main.models import Post, Comment, Tag admin.site.register(Tag) admin.site.register(Post) admin.site.register(Comment)
[ "rodgar.nvkz@gmail.com" ]
rodgar.nvkz@gmail.com
4977570fdaf2585c078ab21fa82c8161cbaa0966
8297f75acb278645d40944172f97a8fe5a0c93b2
/.github/多任务/utils/data_generator.py
4d303b1b3f7725ced88ad65026cd756fc8eae2ee
[]
no_license
zhuangzhuangliu2345/DCASE_task5
506c6dd934c98ee1666ee04f8e64a555d320940c
8aaa66a523e545b4a16a48bdffc2b54c200c73d2
refs/heads/master
2022-10-25T10:29:38.476796
2020-06-15T14:48:29
2020-06-15T14:48:29
272,459,594
1
0
null
null
null
null
UTF-8
Python
false
false
12,469
py
import numpy as np import h5py import csv import time import logging import os import glob import matplotlib.pyplot as plt import logging from utilities import scale import config class Base(object): def __init__(self): pass def load_hdf5(self, hdf5_path): '''Load hdf5 file. Returns: {'audio_name': (audios_num,), 'feature': (audios_num, frames_num, mel_bins), (if exist) 'fine_target': (audios_num, classes_num), (if exist) 'coarse_target': (audios_num, classes_num)} ''' data_dict = {} with h5py.File(hdf5_path, 'r') as hf: if 'audio_name' in hf.keys(): data_dict['audio_name'] = np.array( [audio_name.decode() for audio_name in hf['audio_name'][:]]) if 'feature' in hf.keys(): data_dict['feature'] = hf['feature'][:].astype(np.float32) if 'spacetime' in hf.keys(): data_dict['spacetime'] = hf['spacetime'][:].astype(np.float32) if 'fine_target' in hf.keys(): data_dict['fine_target'] = \ hf['fine_target'][:].astype(np.float32) if 'coarse_target' in hf.keys(): data_dict['coarse_target'] = \ hf['coarse_target'][:].astype(np.float32) if 'label_targets' in hf.keys(): data_dict['label_targets'] = \ hf['label_targets'][:].astype(np.float32) return data_dict def transform(self, x): return scale(x, self.scalar['mean'], self.scalar['std']) def transform2(self,x): return scale(x, self.scalar2['mean'],self.scalar2['std']) class DataGenerator(Base): def __init__(self, train_hdf5_path, validate_hdf5_path, holdout_fold, scalar, batch_size, seed=1234): '''Data generator for training and validation. Args: train_hdf5_path: string validate_hdf5_path: string holdout_fold: '1' | 'None', where '1' indicates using validation and 'None' indicates using full data for training scalar: object, containing mean and std value batch_size: int seed: int, random seed ''' self.scalar = scalar self.batch_size = batch_size self.random_state = np.random.RandomState(seed) # Load training data load_time = time.time() # external_hdf5_path=os.path.join(os.path.dirname(train_hdf5_path),'pre19_train.h5') # # external_hdf5_path="/home/liuzhuangzhuang/pycharm_P/task5-多任务0.0/work_space/features/logmel_64frames_64melbins/pre_train.h5" # with h5py.File('/home/liuzhuangzhuang/pycharm_P/task5-多任务0.0/work_space/scalars/logmel_64frames_64melbins/pre19_train.h5','r') as hf: # mean = hf['mean'][:] # std = hf['std'][:] # # self.scalar2 = {'mean': mean, 'std': std} # self.external_data_dict = self.load_hdf5(external_hdf5_path) # self.external_data_indexes = np.arange( # len(self.external_data_dict['audio_name'])) # logging.info('External audio num: {}'.format( # len( self.external_data_indexes))) # self.random_state.shuffle(self.external_data_indexes) # self.pointer2 = 0 self.train_data_dict = self.load_hdf5(os.path.join(os.path.dirname(train_hdf5_path), 'train.h5')) self.validate_data_dict = self.load_hdf5(validate_hdf5_path) self.train_space_data_dict = self.load_hdf5(os.path.join(os.path.dirname(train_hdf5_path), 'trainspacetime.h5')) self.validate_space_data_dict = self.load_hdf5(os.path.join(os.path.dirname(validate_hdf5_path), 'validatespacetime.h5')) # Combine train and validate data for training if holdout_fold == 'none': self.train_data_dict, self.validate_data_dict, self.train_space_data_dict,self.validate_space_data_dict= \ self.combine_train_validate_data( self.train_data_dict, self.validate_data_dict,self.train_space_data_dict,self.validate_space_data_dict) self.train_audio_indexes = np.arange( len(self.train_data_dict['audio_name'])) self.validate_audio_indexes = np.arange( len(self.validate_data_dict['audio_name'])) logging.info('Load data time: {:.3f} s'.format( time.time() - load_time)) logging.info('Training audio num: {}'.format( len(self.train_audio_indexes))) logging.info('Validation audio num: {}'.format( len(self.validate_audio_indexes))) self.random_state.shuffle(self.train_audio_indexes) self.pointer = 0 def combine_train_validate_data(self, train_data_dict, validate_data_dict,train_space_data_dict,validate_space_data_dict): '''Combining train and validate data to full train data. ''' new_train_data_dict = {} new_validate_data_dict = {} new_train_space_data_dict={} new_validate_space_data_dict={} for key in train_data_dict.keys(): new_train_data_dict[key] = np.concatenate( (train_data_dict[key], validate_data_dict[key]), axis=0) new_validate_data_dict[key] = np.array([]) for key in train_space_data_dict.keys(): new_train_space_data_dict[key] = np.concatenate( (train_space_data_dict[key], validate_space_data_dict[key]), axis=0) new_validate_space_data_dict[key] = np.array([]) return new_train_data_dict, new_validate_data_dict,new_train_space_data_dict,new_validate_space_data_dict def generate_train(self): '''Generate mini-batch data for training. Returns: batch_data_dict: {'audio_name': (batch_size,), 'feature': (batch_size, frames_num, mel_bins), (if exist) 'fine_target': (batch_size, classes_num), (if exist) 'coarse_target': (batch_size, classes_num)} ''' while True: # Reset pointer if self.pointer >= len(self.train_audio_indexes): self.pointer = 0 self.random_state.shuffle(self.train_audio_indexes) # Get batch audio_indexes batch_audio_indexes = self.train_audio_indexes[ self.pointer: self.pointer + self.batch_size] self.pointer += self.batch_size # # if self.pointer2 >= len(self.external_data_indexes): # self.pointer2 = 0 # self.random_state.shuffle(self.external_data_indexes) # # batch_external_indexes = self.external_data_indexes[ # self.pointer2: self.pointer2 + self.batch_size] # # self.pointer2 += self.batch_size # batch_external_feature = self.external_data_dict['feature'][batch_external_indexes] # batch_external_feature = self.transform2(batch_external_feature) # batch_data_dict['external_feature'] = batch_external_feature # batch_data_dict['external_audio_name'] = \ # self.external_data_dict['audio_name'][batch_external_indexes] # # batch_data_dict['external_target'] = \ # self.external_data_dict['label_targets'][batch_external_indexes] batch_data_dict = {} # logging.info(self.external_data_dict.keys()) batch_data_dict['audio_name'] = \ self.train_data_dict['audio_name'][batch_audio_indexes] batch_feature = self.train_data_dict['feature'][batch_audio_indexes] batch_feature = self.transform(batch_feature) batch_data_dict['feature'] = batch_feature batch_data_dict['fine_target'] = \ self.train_data_dict['fine_target'][batch_audio_indexes] batch_data_dict['coarse_target'] = \ self.train_data_dict['coarse_target'][batch_audio_indexes] batch_data_dict['spacetime'] = \ self.train_space_data_dict['spacetime'][batch_audio_indexes] yield batch_data_dict def generate_validate(self, data_type, max_iteration=None): '''Generate mini-batch data for validation. Args: data_type: 'train' | 'validate' max_iteration: None | int, use maximum iteration of partial data for fast evaluation Returns: batch_data_dict: {'audio_name': (batch_size,), 'feature': (batch_size, frames_num, mel_bins), (if exist) 'fine_target': (batch_size, classes_num), (if exist) 'coarse_target': (batch_size, classes_num)} ''' batch_size = self.batch_size if data_type == 'train': data_dict = self.train_data_dict space_data_dict = self.train_space_data_dict audio_indexes = np.array(self.train_audio_indexes) elif data_type == 'validate': data_dict = self.validate_data_dict space_data_dict = self.validate_space_data_dict audio_indexes = np.array(self.validate_audio_indexes) else: raise Exception('Incorrect argument!') iteration = 0 pointer = 0 while True: if iteration == max_iteration: break # Reset pointer if pointer >= len(audio_indexes): break # Get batch audio_indexes batch_audio_indexes = audio_indexes[pointer: pointer + batch_size] pointer += batch_size iteration += 1 batch_data_dict = {} batch_data_dict['audio_name'] = \ data_dict['audio_name'][batch_audio_indexes] batch_feature = data_dict['feature'][batch_audio_indexes] batch_feature = self.transform(batch_feature) batch_data_dict['feature'] = batch_feature batch_data_dict['fine_target'] = \ data_dict['fine_target'][batch_audio_indexes] batch_data_dict['coarse_target'] = \ data_dict['coarse_target'][batch_audio_indexes] batch_data_dict['spacetime'] = \ space_data_dict['spacetime'][batch_audio_indexes] yield batch_data_dict class TestDataGenerator(Base): def __init__(self, hdf5_path, scalar, batch_size, seed=1234): self.scalar = scalar self.batch_size = batch_size self.random_state = np.random.RandomState(seed) self.evalspacetime=self.load_hdf5(os.path.join(os.path.dirname(hdf5_path), 'evalspacetime.h5')) # Load training data self.data_dict = self.load_hdf5(hdf5_path) self.audio_indexes = np.arange( len(self.data_dict['audio_name'])) logging.info('Audio num to be inferenced: {}'.format( len(self.audio_indexes))) self.pointer = 0 def generate(self, max_iteration=None): batch_size = self.batch_size data_dict = self.data_dict audio_indexes = np.array(self.audio_indexes) iteration = 0 pointer = 0 while True: if iteration == max_iteration: break # Reset pointer if pointer >= len(audio_indexes): break # Get batch audio_indexes batch_audio_indexes = audio_indexes[pointer: pointer + batch_size] pointer += batch_size iteration += 1 batch_data_dict = {} batch_data_dict['audio_name'] = \ data_dict['audio_name'][batch_audio_indexes] batch_feature = data_dict['feature'][batch_audio_indexes] batch_feature = self.transform(batch_feature) batch_data_dict['feature'] = batch_feature batch_data_dict['spacetime'] = \ self.evalspacetime['spacetime'][batch_audio_indexes] yield batch_data_dict
[ "noreply@github.com" ]
zhuangzhuangliu2345.noreply@github.com
381d8016164de334a61bb618bd91fafe9877e24e
a5de1b3e011ef93d297624e2b186f729940e6bf0
/pages/migrations/0001_initial.py
bc49072a72b8a8383681b18e77c4c2ef3e7f5c03
[]
no_license
pradeep1841/carzone-gitproject
6654d1e764c9a5d738d041fc30fa33b43a6ead06
84406f9788a5027ace531af57ba9185a1aa9c0f8
refs/heads/master
2023-08-15T19:56:04.448615
2021-10-16T14:55:35
2021-10-16T14:55:35
417,097,962
0
0
null
null
null
null
UTF-8
Python
false
false
983
py
# Generated by Django 3.2.5 on 2021-10-16 10:07 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Teams', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=255)), ('last_name', models.CharField(max_length=255)), ('designation', models.CharField(max_length=255)), ('photo', models.ImageField(upload_to='photos/%Y/%m/%d/')), ('facebook_link', models.URLField(max_length=100)), ('twitter_link', models.URLField(max_length=100)), ('google_plus_link', models.URLField(max_length=100)), ('created_date', models.DateTimeField(auto_now_add=True)), ], ), ]
[ "pradeep0987.kr@gmail.com" ]
pradeep0987.kr@gmail.com
e83bf85c244afddcbffdd016450cd21b44cd5649
8977cf50896c5a4da46fff2a7ad1d17566f7d868
/Solutions/problem70.py
19ab0c2e78b244515d18e678cb31f9f65b77a8e2
[]
no_license
njenga5/python-problems-and-solutions
2d45d0252b63948f1052bf4d0fef5ac3b681e7c0
4413336c2851f42f35d84103fe10b0c58be476f7
refs/heads/master
2023-02-21T06:36:19.014934
2021-01-22T14:42:29
2021-01-22T14:42:29
331,972,084
0
0
null
null
null
null
UTF-8
Python
false
false
225
py
''' Question 70: Write assert statements to verify that every number in the list [2,4,6,8] is even. Hints: Use "assert expression" to make assertion. ''' even_nums = [2, 4, 6, 8] for i in even_nums: assert(i % 2 == 0)
[ "joninduati31@gmail.com" ]
joninduati31@gmail.com
fe0e76eeecca2a5753dd92495ee49dd5b15f970e
088a1927cd9935aca23bba2a48b3edf181812ce9
/10.topological_sort/python/main.py
0e9dbc2f46a4757835b940827bbc069a9029f99a
[]
no_license
litcoderr/AlgorithmArchive
0aa60a9d4d7549df50e8662cbc69b89e9934caad
ad820808423fcca47d70cda0ddb3436abd638781
refs/heads/main
2023-05-06T06:20:54.163634
2021-05-29T05:18:22
2021-05-29T05:18:22
364,423,720
5
0
null
null
null
null
UTF-8
Python
false
false
1,332
py
import argparse from typing import List parser = argparse.ArgumentParser() parser.add_argument("--input_file", type=str) args = parser.parse_args() class Node: def __init__(self, idx): self.idx = idx self.in_dim = 0 self.out = [] if __name__ == "__main__": nodes = [] # initialize nodes with open(args.input_file) as reader: N: int = int(reader.readline()) for idx in range(N): nodes.append(Node(idx)) for line in reader.readlines(): from_to: List[Node] = list(map(lambda x: nodes[int(x)], line.split(" "))) from_to[1].in_dim += 1 from_to[0].out.append(from_to[1]) print("{} {}".format(from_to[0].idx, from_to[1].idx)) queue = [] for node in nodes: if node.in_dim <= 0: queue.append(node) # topological sort result = [] while len(queue) > 0: temp_node = queue.pop(0) result.append(temp_node) for out_node in temp_node.out: out_node.in_dim -= 1 if out_node.in_dim <=0: queue.append(out_node) if len(result) != len(nodes): print("Unable to topologically sort") else: print("Topologically sorted !!") for node in result: print(node.idx, end=" ")
[ "litcoderr@gmail.com" ]
litcoderr@gmail.com
21dfea0a3be2fd814fe476fc8aa4942aab81cab0
f707277b4b9cd9ba9c8aaadf92baee1c3b4bef70
/venv/bin/easy_install
1896bb33f637f871aeec26d8edc35caef5e25250
[]
no_license
mseslami/py_facedetection
e3a8dc8ac26df2c2c7e1d751c18cb20425f610fc
69c6a7e1e4cab16184fd4b3fba9076b0c9ab4878
refs/heads/master
2020-03-29T10:30:13.405801
2018-10-27T10:52:13
2018-10-27T10:52:13
149,808,219
0
0
null
null
null
null
UTF-8
Python
false
false
284
#!/home/maryam/PycharmProjects/facedetectionproject/venv/bin/python3 # -*- coding: utf-8 -*- import re import sys from setuptools.command.easy_install import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "m.eslami46@gmail.com" ]
m.eslami46@gmail.com
99faa28d8b599b1accf51cbc1bb5d6340c659602
ce6703fc254e9a4fca5e5a85a40b9521fc9ef180
/A/a.py
ab0b6027c817460c5cf2ee7b726674b7c10019fa
[]
no_license
adams-brian/icpc2018
154327afdd184895d05c96a682ebabbc7ca29222
2b326fb750a84acfb2dd5b4ea37db2795af04022
refs/heads/master
2020-04-24T13:44:46.388382
2019-02-28T04:33:13
2019-02-28T04:33:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,017
py
import glob, os, time def solve(filename): print(filename) start = time.time() stationCount = 0 busEvents = [] with open(filename, "r") as file: for i, line in enumerate(file): row = line.split(' ') if i == 0: stationCount = int(row[1]) elif i > 1: bus = [i -2, int(row[0]), int(row[1]), float(row[4])] busEvents.append([int(row[2]), bus, False]) busEvents.append([int(row[3]), bus, True]) print(f' parse time: {time.time() - start}') startSort = time.time() busEvents.sort(key=lambda event: event[0]) print(f' sort time: {time.time() - startSort}') startProcess = time.time() probability = [0] * stationCount probability[1] = 1 arrivalProbability = {} index = len(busEvents) - 1 while index >= 0: t = busEvents[index][0] newProbabilities = [] while index >= 0 and busEvents[index][0] == t: bus = busEvents[index][1] if busEvents[index][2]: arrivalProbability[bus[0]] = probability[bus[2]] else: newProbabilities.append([ bus[1], (bus[3] * arrivalProbability[bus[0]]) + ((1 - bus[3]) * probability[bus[1]]) ]) index -= 1 for newP in newProbabilities: if newP[1] > probability[newP[0]]: probability[newP[0]] = newP[1] p = probability[0] end = time.time() print(f' process time: {end - startProcess}') print(f' total time: {end - start}') if end - start > 10: print(' **************************************** TOO SLOW ****************************************') answerKey = 0 with open(os.path.splitext(filename)[0] + ".ans", "r") as file: answerKey = float(file.read().strip()) print(f' result: {p}, answer: {answerKey}') if abs(answerKey - p) < 0.000001: print(' pass') else: print(' **************************************** INCORRECT ****************************************') os.chdir("../../icpc2018data/A-catch") for index, file in enumerate(glob.glob("*.in")): solve(file)
[ "brian.lives.outdoors@gmail.com" ]
brian.lives.outdoors@gmail.com
faed20c0c949adb7bbe19ac384abbff88c24bbb5
0c799e226a5d30d9f94283de25c83b2ab9bcdf2d
/reddit/urls.py
c735827ef500cf755132745f6c14813b1a45d14c
[ "MIT" ]
permissive
RaghuDalal/Django-Reddit-API
fa5c0d1b939e641d17d6d565eae915f766b8acfe
bdaba40f003da59be5ba4cf7ab6d83b6bae7b99b
refs/heads/master
2022-11-23T13:46:11.906039
2020-07-20T08:25:06
2020-07-20T08:25:06
281,020,668
0
0
null
null
null
null
UTF-8
Python
false
false
390
py
from django.contrib import admin from django.urls import path, include from posts import views urlpatterns = [ path('admin/', admin.site.urls), path('api/posts', views.PostList.as_view()), path('api/posts/<int:pk>/vote', views.VoteCreate.as_view()), path('api-auth/', include('rest_framework.urls')), path('api/posts/<int:pk>', views.PostRetrieveDestroy.as_view()), ]
[ "raghvender002@gmail.com" ]
raghvender002@gmail.com
1d7501c04e7e41331f36b5085202c7c1da7aa91b
3af0b3d83893e94858e0113decfbdf4a6bf9eeab
/4_Tuples/tuples_basics.py
14445ce16e0f4b5749c8c9edc9384fb8165d0cb2
[]
no_license
MarKuchar/intro_to_algorithms
a34668359dc83bce938387fd4a08e6235a310aeb
48bc8f0ce7a809fd530798e0f0ebc2789f6bf04b
refs/heads/master
2021-01-06T23:33:36.384334
2020-02-11T01:26:21
2020-02-11T01:26:21
241,514,048
0
0
null
null
null
null
UTF-8
Python
false
false
970
py
# Tuples are almost identical to lists # The only big difference between lists and tuples is that tuples cannot be modified (Immutable) # You can NOT add(append), changed(replace), or delete "IMMUTABLE LIST" # elements from the tuple vowels = ("a", "e", "i", "o", "u") # consonants (b, c, d, ...) print(vowels[0]) print("k" in vowels) # vowels[0] = "A" # Error # Methods vowels.index("e") vowels.count("i") # Use cases # 1. return multiple values from a function def a(): return (1, "Mars") # example def get_combo(name): if name == "Big-mac": return ("Coke", "Big-mac", "Fries") # 2. check if an item is in a tuple print("a" in vowels) # 3. multiple assignments year, country = (2020, "Canada") _, country, provice = (2020, "Canada", "BC") # underscore we use when we want to ignore part of assignment # swap x = 10 y = 20 # I want to swap x and y # in python x, y = y, x # in other languages temp = x # temporary variable x = y y = temp
[ "martin.kuchar@MacBook-Pro.hitronhub.home" ]
martin.kuchar@MacBook-Pro.hitronhub.home
33d9b8e295d573f6c414da2b3aff9d11ebb3ada6
5253e2d58cacc4f4d32748aa3db8757b078e8467
/www/wsgi.py
d3d721a8d1b1282f35c07439b3cac4c5e715cf26
[]
no_license
dinopetrone/skills-assessment
865d6db73521c01733184a3d8ae2220a673b57cf
e9b910668d211fa525169d7637f52ed9b83eb5b2
refs/heads/master
2020-04-09T00:30:44.696754
2012-08-08T13:07:26
2012-08-08T13:07:26
5,330,145
0
1
null
null
null
null
UTF-8
Python
false
false
1,128
py
""" WSGI config for www project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "www.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
[ "dinopetrone@gmail.com" ]
dinopetrone@gmail.com
12aeb18c431ea99533d5b3c5bccaa60d085562dd
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_176/ch49_2019_05_22_00_59_15_784231.py
6287c21ef8e2f638ee853d9f682aadb6d254c24b
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
131
py
n = int(input("digite números inteiros positivos")) lista = [] while n > 0: lista.append(n) if n <= 0: print (lista[:-1])
[ "you@example.com" ]
you@example.com
118a6ec75ee5d79d8967f3b128c733cada513d6e
20f44972c4012d498e97aabb23f57e409867dbae
/Week_01/1_two_sum.py
05a29fe97daf749ef2af974cdf5322edcc866aa1
[]
no_license
Moziofmoon/algorithm-python
246b8e9364ee122e2cc8f241dc3bb9f4ea9e5038
e04453be648157a4d7dc8e264503d7301a46ef67
refs/heads/master
2022-12-07T13:19:23.816305
2020-09-04T11:18:39
2020-09-04T11:18:39
255,344,051
0
0
null
null
null
null
UTF-8
Python
false
false
1,040
py
# 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 # # 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 # # 示例: # # 给定 nums = [2, 7, 11, 15], target = 9 # # 因为 nums[0] + nums[1] = 2 + 7 = 9 # 所以返回 [0, 1] # # Related Topics 数组 哈希表 from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """ 解题思路:利用hashmap存储数组,计算差值是否在list中 时间复杂度:O(n) 空间复杂度:O(n) :param nums: :param target: :return: """ hashmap = {} for i, num in enumerate(nums): if target - num in hashmap: # i 为当前index, hashmap.get(target - num) 为前面的index return [hashmap.get(target - num), i] hashmap[num] = i
[ "yuesf23165498GZP!" ]
yuesf23165498GZP!
31f11f0509a0c188a835bb0feefd1baf2f8b72d2
85a9ffeccb64f6159adbd164ff98edf4ac315e33
/pysnmp/Unisphere-Data-Fractional-T1-CONF.py
740a9c14e64b0cef168f696b297277fa62cadab5
[ "Apache-2.0" ]
permissive
agustinhenze/mibs.snmplabs.com
5d7d5d4da84424c5f5a1ed2752f5043ae00019fb
1fc5c07860542b89212f4c8ab807057d9a9206c7
refs/heads/master
2020-12-26T12:41:41.132395
2019-08-16T15:51:41
2019-08-16T15:53:57
237,512,469
0
0
Apache-2.0
2020-01-31T20:41:36
2020-01-31T20:41:35
null
UTF-8
Python
false
false
3,439
py
# # PySNMP MIB module Unisphere-Data-Fractional-T1-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-Fractional-T1-CONF # Produced by pysmi-0.3.4 at Mon Apr 29 21:24:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection") AgentCapabilities, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "ModuleCompliance", "NotificationGroup") ObjectIdentity, IpAddress, MibIdentifier, Counter32, NotificationType, Unsigned32, TimeTicks, Counter64, Integer32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, ModuleIdentity, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "IpAddress", "MibIdentifier", "Counter32", "NotificationType", "Unsigned32", "TimeTicks", "Counter64", "Integer32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "ModuleIdentity", "Bits") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") usDataAgents, = mibBuilder.importSymbols("Unisphere-Data-Agents", "usDataAgents") usdFt1Group, usdFt1Group2 = mibBuilder.importSymbols("Unisphere-Data-FRACTIONAL-T1-MIB", "usdFt1Group", "usdFt1Group2") usdFractionalT1Agent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 16)) usdFractionalT1Agent.setRevisions(('2001-03-29 22:03',)) if mibBuilder.loadTexts: usdFractionalT1Agent.setLastUpdated('200103292203Z') if mibBuilder.loadTexts: usdFractionalT1Agent.setOrganization('Unisphere Networks, Inc.') usdFractionalT1AgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 16, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdFractionalT1AgentV1 = usdFractionalT1AgentV1.setProductRelease('Version 1 of the Fractional T1 component of the Unisphere Routing\n Switch SNMP agent. This version of the Fractional T1 component was\n supported in the Unisphere RX 1.0 system release.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdFractionalT1AgentV1 = usdFractionalT1AgentV1.setStatus('obsolete') usdFractionalT1AgentV2 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 16, 2)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdFractionalT1AgentV2 = usdFractionalT1AgentV2.setProductRelease('Version 2 of the Fractional T1 component of the Unisphere Routing\n Switch SNMP agent. This version of the Fractional T1 component is\n supported in the Unisphere RX 1.1 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdFractionalT1AgentV2 = usdFractionalT1AgentV2.setStatus('current') mibBuilder.exportSymbols("Unisphere-Data-Fractional-T1-CONF", usdFractionalT1AgentV2=usdFractionalT1AgentV2, PYSNMP_MODULE_ID=usdFractionalT1Agent, usdFractionalT1Agent=usdFractionalT1Agent, usdFractionalT1AgentV1=usdFractionalT1AgentV1)
[ "dcwangmit01@gmail.com" ]
dcwangmit01@gmail.com
4b0dc3c03e8582628985d5f723c7b8a0ca1da2a9
59b34e241e101b282c92add9c7b6a06c2745b79d
/movieRent/startProgram.py
6afe4cd4323567d80ae23597e17383dc7b8b74f5
[]
no_license
lakatosandrei/FP
6effc15995c5eaad41cea5acb782f99024cae6bc
8157454e964f032aeb374b7b699e4e5c9b7caf76
refs/heads/master
2021-01-18T14:05:39.121685
2014-11-28T21:21:41
2014-11-28T21:21:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
763
py
from Repository.clientRepository import clientRepository from Domain.Validator import clientValidator, movieValidator from Controller.Controller import clientController, movieController, rentController from UI.Console import Console from Repository.movieRepository import movieRepository from Repository.rentRepository import rentRepository clientRepo = clientRepository() clientValidator = clientValidator() movieRepo = movieRepository() movieValidator = movieValidator() rentRepo = rentRepository() clientController = clientController(clientRepo, clientValidator) movieController = movieController(movieRepo, movieValidator) rentController = rentController(rentRepo) ui = Console(clientController, movieController, rentController) ui.showUI()
[ "alakatos@e1p5.cluj.42.fr" ]
alakatos@e1p5.cluj.42.fr
bc75e0e8b53d166ef35ad1e672c590b261e0b2be
12dff81bf8d1c0c33939c6bfff3153391f5f4038
/sktime/forecasting/compose/__init__.py
faff16bdaf07a320dec9bcc093216a0eb7e21d65
[ "BSD-3-Clause" ]
permissive
xuyxu/sktime
be5c823036deb342d1cf1c30fe13643391928e54
50765a6a5bf3a78096dcca10223b3320cf2aa5f0
refs/heads/main
2023-05-08T09:59:24.613214
2021-06-04T08:41:26
2021-06-04T08:41:26
373,827,188
1
0
BSD-3-Clause
2021-06-04T11:59:55
2021-06-04T11:59:54
null
UTF-8
Python
false
false
1,773
py
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- # copyright: sktime developers, BSD-3-Clause License (see LICENSE file) __author__ = ["Markus Löning"] __all__ = [ "EnsembleForecaster", "TransformedTargetForecaster", "DirectTabularRegressionForecaster", "DirectTimeSeriesRegressionForecaster", "MultioutputTabularRegressionForecaster", "MultioutputTimeSeriesRegressionForecaster", "RecursiveTabularRegressionForecaster", "RecursiveTimeSeriesRegressionForecaster", "DirRecTabularRegressionForecaster", "DirRecTimeSeriesRegressionForecaster", "StackingForecaster", "MultiplexForecaster", "ReducedForecaster", "make_reduction", ] from sktime.forecasting.compose._ensemble import EnsembleForecaster from sktime.forecasting.compose._pipeline import TransformedTargetForecaster from sktime.forecasting.compose._reduce import DirRecTabularRegressionForecaster from sktime.forecasting.compose._reduce import DirRecTimeSeriesRegressionForecaster from sktime.forecasting.compose._reduce import DirectTabularRegressionForecaster from sktime.forecasting.compose._reduce import DirectTimeSeriesRegressionForecaster from sktime.forecasting.compose._reduce import MultioutputTabularRegressionForecaster from sktime.forecasting.compose._reduce import MultioutputTimeSeriesRegressionForecaster from sktime.forecasting.compose._reduce import RecursiveTabularRegressionForecaster from sktime.forecasting.compose._reduce import RecursiveTimeSeriesRegressionForecaster from sktime.forecasting.compose._stack import StackingForecaster from sktime.forecasting.compose._multiplexer import MultiplexForecaster from sktime.forecasting.compose._reduce import ReducedForecaster from sktime.forecasting.compose._reduce import make_reduction
[ "noreply@github.com" ]
xuyxu.noreply@github.com
60e6e23108885383dcd50b191fa4248e922bf38e
40654c67fa5e471050eba41385bc1e660825f91d
/apars/migrations/0003_auto_20200327_0102.py
716fa0888fb608c55319d6e625cf4c91e52be72e
[]
no_license
PokidovaJulia/Avito_parser
346ce45e7987c39cf09ab8f65c41c3380afdcfb0
8a6b32c35d0c9a0e68d64b8a3bb5933b4635fd60
refs/heads/master
2022-04-15T17:13:50.315590
2020-04-04T20:11:20
2020-04-04T20:11:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
424
py
# Generated by Django 2.2.4 on 2020-03-26 22:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('apars', '0002_auto_20200327_0028'), ] operations = [ migrations.AlterField( model_name='product', name='currency', field=models.TextField(blank=True, null=True, verbose_name='Валюта'), ), ]
[ "pokidova93@bk.ru" ]
pokidova93@bk.ru
efe60abd98a36cdb0614ab2e9e77ad6f49327781
88c4308e708ca4d0906eafef12b12069356bbb19
/pytest_django/funcargs.py
d7a79141b518dc6ea4651dd0320698c95c37ecd2
[ "BSD-3-Clause" ]
permissive
johtso/pytest_django
0167f816d81e5bc8b0d067f2fce6d4b3a55534c3
cbae5a64741267261a39703a6fce54f56be4efb6
refs/heads/master
2021-01-15T22:58:00.043820
2012-05-16T07:11:30
2012-05-16T07:11:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,241
py
import copy import os from django.conf import settings from django.contrib.auth.models import User from django.db import connections from django.test.client import RequestFactory, Client try: from django.test.testcases import LiveServerThread LIVE_SERVER_SUPPORT = True except ImportError: LIVE_SERVER_SUPPORT = False def pytest_funcarg__client(request): """ Returns a Django test client instance. """ return Client() def pytest_funcarg__admin_client(request): """ Returns a Django test client logged in as an admin user. """ try: User.objects.get(username='admin') except User.DoesNotExist: user = User.objects.create_user('admin', 'admin@example.com', 'password') user.is_staff = True user.is_superuser = True user.save() client = Client() client.login(username='admin', password='password') return client def pytest_funcarg__rf(request): """ Returns a RequestFactory instance. """ return RequestFactory() def pytest_funcarg__settings(request): """ Returns a Django settings object that restores any changes after the test has been run. """ old_settings = copy.deepcopy(settings) def restore_settings(): for setting in dir(old_settings): if setting == setting.upper(): setattr(settings, setting, getattr(old_settings, setting)) request.addfinalizer(restore_settings) return settings class LiveServer(object): def __init__(self, host, possible_ports): connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to # the server thread. if (conn.settings_dict['ENGINE'] == 'django.db.backends.sqlite3' and conn.settings_dict['NAME'] == ':memory:'): # Explicitly enable thread-shareability for this connection conn.allow_thread_sharing = True connections_override[conn.alias] = conn self.thread = LiveServerThread(host, possible_ports, connections_override) self.thread.daemon = True self.thread.start() self.thread.is_ready.wait() if self.thread.error: raise self.thread.error def __unicode__(self): return 'http://%s:%s' % (self.thread.host, self.thread.port) def __repr__(self): return '<LiveServer listenting at %s>' % unicode(self) def __add__(self, other): # Support string concatenation return unicode(self) + other def get_live_server_host_ports(): # This code is copy-pasted from django/test/testcases.py specified_address = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', 'localhost:8081') # The specified ports may be of the form '8000-8010,8080,9200-9300' # i.e. a comma-separated list of ports or ranges of ports, so we break # it down into a detailed list of all possible ports. possible_ports = [] try: host, port_ranges = specified_address.split(':') for port_range in port_ranges.split(','): # A port range can be of either form: '8000' or '8000-8010'. extremes = map(int, port_range.split('-')) assert len(extremes) in [1, 2] if len(extremes) == 1: # Port range of the form '8000' possible_ports.append(extremes[0]) else: # Port range of the form '8000-8010' for port in range(extremes[0], extremes[1] + 1): possible_ports.append(port) except Exception: raise Exception('Invalid address ("%s") for live server.' % specified_address) return (host, possible_ports) def pytest_funcarg__live_server(request): if not LIVE_SERVER_SUPPORT: raise Exception('The kwarg liveserver is not supported in Django <= 1.3') def setup_live_server(): return LiveServer(*get_live_server_host_ports()) def teardown_live_server(live_server): live_server.thread.join() return request.cached_setup(setup=setup_live_server, teardown=teardown_live_server, scope='session')
[ "andreas@pelme.se" ]
andreas@pelme.se
76ebeb5ca4de657e6a309f8e153f6d65e1abc80f
5af92dd3504608af59e1dde5de8e4f8f742ef6a4
/Python/TheOnlineStore.PY
f2c5501773e647b887fed5488565bb9987f8ee90
[]
no_license
ccpink/Resume-Repository
e1fad1950db757600e9030e94bf1c70680aa7442
3270c6d8911345b83fe7ae496fa87929e5effb16
refs/heads/master
2021-06-24T05:41:41.964489
2021-04-16T07:57:59
2021-04-16T07:57:59
212,234,321
1
0
null
null
null
null
UTF-8
Python
false
false
1,923
py
#Don't forget to rename this file after copying the template #for a new program! """ Student Name: Program Title: Description: """ def main(): #<-- Don't change this line! #Write your code below. It must be indented! #I need to create variables for total for order, Country and Provinces as well as taxes for the provinces originalPrice = 0.0 country = "" province = "" alb = "alberta" nS = "nova scotia" ont = "ontario" newB = "new brunswick" albTax = 0.05 ontTax = 0.15 newBTax = 0.15 novaScotiatax = 0.15 otherPrv = 0.11 endtotal = 0.0 canada = "canada" #Welcome message print("Hello welcome to the Online Store checkout.") #Ask user for their country and original price originalPrice = float(input("What is your current total before taxes.: ")) country = input("Please input your country in which you live!: ") endtotal = originalPrice #If canada if canada == country.lower(): #if so they have taxes print("You have taxes!") #Ask what province province = input("Please input your province: ").lower() if province == alb: endtotal = (originalPrice * albTax + originalPrice) elif province == nS: endtotal = (originalPrice * novaScotiatax + originalPrice) elif province == ont: endtotall = (originalPrice + ontTax + originalPrice) elif province == newB: endtotal = (originalPrice + newBTax + originalPrice) else: endtotal = (originalPrice * otherPrv + originalPrice) #Else print there are no taxes else: print("You have no taxes") print("Your total is ""{0:.2f}".format(endtotal)) #Your code ends on the line above #Do not change any of the code below! if __name__ == "__main__": main()
[ "noreply@github.com" ]
ccpink.noreply@github.com
aa04ef433275e7caf4d0845d3d7fc69236b6ad02
58af681bc688fc5f9a5582c19f16b2e338d915a9
/userapp/admin.py
e4552818003917c6bfc1f037c7224541d5fd0670
[]
no_license
byIlusion/GB_GeekShop
60cde2cc001032abe29b8cb881a4deb27749df87
11acfa71ae59decf536c55ff72cb799fe1585752
refs/heads/main
2023-04-07T16:51:38.767740
2021-04-07T07:08:42
2021-04-07T07:08:42
330,924,424
0
0
null
2021-04-07T07:08:42
2021-01-19T09:15:47
CSS
UTF-8
Python
false
false
729
py
from django.contrib import admin from userapp.models import User # admin.site.register(User) @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display = ('id', 'username', 'first_name', 'last_name', 'date_joined', 'last_login', 'is_staff', 'is_superuser', 'is_active') list_display_links = ('id', 'username') search_fields = ('username', 'first_name', 'last_name') ordering = ('-is_superuser', '-is_staff', '-is_active', 'username') fields = ('username', ('first_name', 'last_name'), 'email', ('is_active', 'is_staff', 'is_superuser'), 'avatar', 'age', 'user_permissions', 'groups', 'password') readonly_fields = ('username', 'password')
[ "by_Ilusion@mail.ru" ]
by_Ilusion@mail.ru
c791b9edce3e0692bce8c7708e6e86eaf8c17daf
2bacd64bd2679bbcc19379947a7285e7ecba35c6
/1-notebook-examples/keras-udemy-course/svm_class/util.py
04e8003b05e99bcd2186fea5bcceb671635c0246
[ "MIT" ]
permissive
vicb1/deep-learning
cc6b6d50ae5083c89f22512663d06b777ff8d881
23d6ef672ef0b3d13cea6a99984bbc299d620a73
refs/heads/master
2022-12-12T15:56:55.565836
2020-03-06T01:55:55
2020-03-06T01:55:55
230,293,726
0
0
MIT
2022-12-08T05:27:43
2019-12-26T16:23:18
Jupyter Notebook
UTF-8
Python
false
false
4,450
py
# https://deeplearningcourses.com/c/support-vector-machines-in-python # https://www.udemy.com/support-vector-machines-in-python from __future__ import print_function, division from builtins import range # Note: you may need to update your version of future # sudo pip install -U future import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.utils import shuffle from sklearn.preprocessing import StandardScaler def getKaggleMNIST(): # MNIST data: # column 0 is labels # column 1-785 is data, with values 0 .. 255 # total size of CSV: (42000, 784) train = pd.read_csv('../large_files/train.csv').values.astype(np.float32) train = shuffle(train) Xtrain = train[:-1000,1:] Ytrain = train[:-1000,0].astype(np.int32) Xtest = train[-1000:,1:] Ytest = train[-1000:,0].astype(np.int32) # scale the data Xtrain /= 255. Xtest /= 255. # scaler = StandardScaler() # Xtrain = scaler.fit_transform(Xtrain) # Xtest = scaler.transform(Xtest) return Xtrain, Ytrain, Xtest, Ytest def get_spiral(): # Idea: radius -> low...high # (don't start at 0, otherwise points will be "mushed" at origin) # angle = low...high proportional to radius # [0, 2pi/6, 4pi/6, ..., 10pi/6] --> [pi/2, pi/3 + pi/2, ..., ] # x = rcos(theta), y = rsin(theta) as usual radius = np.linspace(1, 10, 100) thetas = np.empty((6, 100)) for i in range(6): start_angle = np.pi*i / 3.0 end_angle = start_angle + np.pi / 2 points = np.linspace(start_angle, end_angle, 100) thetas[i] = points # convert into cartesian coordinates x1 = np.empty((6, 100)) x2 = np.empty((6, 100)) for i in range(6): x1[i] = radius * np.cos(thetas[i]) x2[i] = radius * np.sin(thetas[i]) # inputs X = np.empty((600, 2)) X[:,0] = x1.flatten() X[:,1] = x2.flatten() # add noise X += np.random.randn(600, 2)*0.5 # targets Y = np.array([0]*100 + [1]*100 + [0]*100 + [1]*100 + [0]*100 + [1]*100) return X, Y def get_xor(): X = np.zeros((200, 2)) X[:50] = np.random.random((50, 2)) / 2 + 0.5 # (0.5-1, 0.5-1) X[50:100] = np.random.random((50, 2)) / 2 # (0-0.5, 0-0.5) X[100:150] = np.random.random((50, 2)) / 2 + np.array([[0, 0.5]]) # (0-0.5, 0.5-1) X[150:] = np.random.random((50, 2)) / 2 + np.array([[0.5, 0]]) # (0.5-1, 0-0.5) Y = np.array([0]*100 + [1]*100) return X, Y def get_donut(): N = 200 R_inner = 5 R_outer = 10 # distance from origin is radius + random normal # angle theta is uniformly distributed between (0, 2pi) R1 = np.random.randn(N//2) + R_inner theta = 2*np.pi*np.random.random(N//2) X_inner = np.concatenate([[R1 * np.cos(theta)], [R1 * np.sin(theta)]]).T R2 = np.random.randn(N//2) + R_outer theta = 2*np.pi*np.random.random(N//2) X_outer = np.concatenate([[R2 * np.cos(theta)], [R2 * np.sin(theta)]]).T X = np.concatenate([ X_inner, X_outer ]) Y = np.array([0]*(N//2) + [1]*(N//2)) return X, Y def get_clouds(): N = 1000 c1 = np.array([2, 2]) c2 = np.array([-2, -2]) # c1 = np.array([0, 3]) # c2 = np.array([0, 0]) X1 = np.random.randn(N, 2) + c1 X2 = np.random.randn(N, 2) + c2 X = np.vstack((X1, X2)) Y = np.array([-1]*N + [1]*N) return X, Y def plot_decision_boundary(model, resolution=100, colors=('b', 'k', 'r')): np.warnings.filterwarnings('ignore') fig, ax = plt.subplots() # Generate coordinate grid of shape [resolution x resolution] # and evaluate the model over the entire space x_range = np.linspace(model.Xtrain[:,0].min(), model.Xtrain[:,0].max(), resolution) y_range = np.linspace(model.Xtrain[:,1].min(), model.Xtrain[:,1].max(), resolution) grid = [[model._decision_function(np.array([[xr, yr]])) for yr in y_range] for xr in x_range] grid = np.array(grid).reshape(len(x_range), len(y_range)) # Plot decision contours using grid and # make a scatter plot of training data ax.contour(x_range, y_range, grid.T, (-1, 0, 1), linewidths=(1, 1, 1), linestyles=('--', '-', '--'), colors=colors) ax.scatter(model.Xtrain[:,0], model.Xtrain[:,1], c=model.Ytrain, lw=0, alpha=0.3, cmap='seismic') # Plot support vectors (non-zero alphas) # as circled points (linewidth > 0) mask = model.alphas > 0. ax.scatter(model.Xtrain[:,0][mask], model.Xtrain[:,1][mask], c=model.Ytrain[mask], cmap='seismic') # debug ax.scatter([0], [0], c='black', marker='x') plt.show()
[ "vbajenaru@gmail.com" ]
vbajenaru@gmail.com
d85e4b271e3cd7413f1cccb16badfcd4789785dc
a34afa627a19c4b8247761119af31424afb6950f
/node_modules/midi/build/config.gypi
4e1f5ccb7eb3a6f01377c959615b546964a0fa09
[ "Unlicense", "MIT" ]
permissive
stephenmurray2/kano-theremin
f8b4fd1c1e6feedbef15ca48edd6984010aface2
6a5d198ddf2659ce6208b43a173f65a0ee33f8fb
refs/heads/master
2020-03-13T17:34:04.044349
2018-04-26T23:32:35
2018-04-26T23:32:35
131,219,584
3
0
null
null
null
null
UTF-8
Python
false
false
4,335
gypi
# Do not edit. File was generated by node-gyp's "configure" step { "target_defaults": { "cflags": [], "default_configuration": "Release", "defines": [], "include_dirs": [], "libraries": [] }, "variables": { "asan": 0, "coverage": "false", "debug_devtools": "node", "force_dynamic_crt": 0, "host_arch": "x64", "icu_data_file": "icudt58l.dat", "icu_data_in": "../../deps/icu-small/source/data/in/icudt58l.dat", "icu_endianness": "l", "icu_gyp_path": "tools/icu/icu-generic.gyp", "icu_locales": "en,root", "icu_path": "deps/icu-small", "icu_small": "true", "icu_ver_major": "58", "llvm_version": 0, "node_byteorder": "little", "node_enable_d8": "false", "node_enable_v8_vtunejit": "false", "node_install_npm": "true", "node_module_version": 48, "node_no_browser_globals": "false", "node_prefix": "/usr/local", "node_release_urlbase": "https://nodejs.org/download/release/", "node_shared": "false", "node_shared_cares": "false", "node_shared_http_parser": "false", "node_shared_libuv": "false", "node_shared_openssl": "false", "node_shared_zlib": "false", "node_tag": "", "node_use_bundled_v8": "true", "node_use_dtrace": "true", "node_use_etw": "false", "node_use_lttng": "false", "node_use_openssl": "true", "node_use_perfctr": "false", "node_use_v8_platform": "true", "openssl_fips": "", "openssl_no_asm": 0, "shlib_suffix": "48.dylib", "target_arch": "x64", "uv_parent_path": "/deps/uv/", "uv_use_dtrace": "true", "v8_enable_gdbjit": 0, "v8_enable_i18n_support": 1, "v8_inspector": "true", "v8_no_strict_aliasing": 1, "v8_optimized_debug": 0, "v8_random_seed": 0, "v8_use_snapshot": "false", "want_separate_host_toolset": 0, "xcode_version": "7.0", "nodedir": "/Users/stephenmurray/.node-gyp/6.11.1", "copy_dev_lib": "true", "standalone_static_library": 1, "dry_run": "", "legacy_bundling": "", "save_dev": "", "browser": "", "only": "", "viewer": "man", "also": "", "rollback": "true", "usage": "", "globalignorefile": "/usr/local/etc/npmignore", "init_author_url": "", "maxsockets": "50", "shell": "/bin/bash", "parseable": "", "shrinkwrap": "true", "init_license": "ISC", "if_present": "", "cache_max": "Infinity", "init_author_email": "", "sign_git_tag": "", "cert": "", "git_tag_version": "true", "local_address": "", "long": "", "fetch_retries": "2", "npat": "", "registry": "https://registry.npmjs.org/", "key": "", "message": "%s", "versions": "", "globalconfig": "/usr/local/etc/npmrc", "always_auth": "", "cache_lock_retries": "10", "global_style": "", "heading": "npm", "fetch_retry_mintimeout": "10000", "proprietary_attribs": "true", "access": "", "json": "", "description": "true", "engine_strict": "", "https_proxy": "", "init_module": "/Users/stephenmurray/.npm-init.js", "userconfig": "/Users/stephenmurray/.npmrc", "node_version": "6.11.1", "user": "", "editor": "vi", "save": "", "tag": "latest", "global": "", "progress": "true", "optional": "true", "bin_links": "true", "force": "", "searchopts": "", "depth": "Infinity", "rebuild_bundle": "true", "searchsort": "name", "unicode": "true", "fetch_retry_maxtimeout": "60000", "ca": "", "save_prefix": "^", "strict_ssl": "true", "tag_version_prefix": "v", "dev": "", "fetch_retry_factor": "10", "group": "20", "save_exact": "", "cache_lock_stale": "60000", "version": "", "cache_min": "10", "cache": "/Users/stephenmurray/.npm", "searchexclude": "", "color": "true", "save_optional": "", "user_agent": "npm/3.10.10 node/v6.11.1 darwin x64", "ignore_scripts": "", "cache_lock_wait": "10000", "production": "", "save_bundle": "", "init_version": "1.0.0", "umask": "0022", "git": "git", "init_author_name": "", "scope": "", "onload_script": "", "tmp": "/var/folders/qm/swqn6yw105zdm7s_3q8zgjv00000gn/T", "unsafe_perm": "true", "link": "", "prefix": "/usr/local" } }
[ "stephenandrewmurray@gmail.com" ]
stephenandrewmurray@gmail.com
bea38af7cab7cbe4cdbba7d9b3882797557e1005
976fb11b4e6bd0a1ec0bb66052f970dba823b558
/create_rwht_options/create_rwht_options/create_rwht_options.py
1732ae516239dbd1500da8baba82789c37cf2b90
[]
no_license
accastonguay/dynamind_modules
c206b13965f8a78b3ce330de20d154e325463c26
d7ab0d85571a0418f29d1e8df9db6a694e0edec4
refs/heads/master
2020-04-15T15:23:21.998244
2018-08-06T02:03:43
2018-08-06T02:03:43
52,499,444
0
0
null
null
null
null
UTF-8
Python
false
false
115
py
""" @author Adam Castonguay <adam.charette.castonguay@monash.edu> """ from create_rwht_options import *
[ "kyrielle53@yahoo.ca" ]
kyrielle53@yahoo.ca
c57e39808d7c0426819b078e11ed25f61e133f8a
140c0d57e1b0daf855320681ab32f73b18ae2e1a
/PythonCode/ex2.py
d4b03a88f57cbca91b2a7cc592509f317cf5b767
[]
no_license
ItManHarry/Python
f457a91624219b920c5477583d2750971a950f23
d07e10ece76519e424f175fd07f3ba5ac54a0df7
refs/heads/master
2023-02-17T12:43:12.775037
2023-02-14T01:53:57
2023-02-14T01:53:57
122,717,872
0
0
null
null
null
null
UTF-8
Python
false
false
287
py
#comment , this is so you can read you program later #Anything after the # is ignored by python print "I could have code like this." #and the comment after is ignored #you can also use a comment to "disabled" or comment out a piece of code : #print "This won't run" print "This will run"
[ "jack_chengqian@163.com" ]
jack_chengqian@163.com
89cb3c4b47c6622b7c32df010a025f6394d09fa9
9dba277eeb0d5e9d2ac75e2e17ab5b5eda100612
/19100305/findyourselfloveyourself/d5_exercise_array.py
f19885fe0dec957bac30875e3e8ad24fcc156e0c
[]
no_license
shen-huang/selfteaching-python-camp
e8410bfc06eca24ee2866c5d890fd063e9d4be89
459f90c9f09bd3a3df9e776fc64dfd64ac65f976
refs/heads/master
2022-05-02T05:39:08.932008
2022-03-17T07:56:30
2022-03-17T07:56:30
201,287,222
9
6
null
2019-08-08T15:34:26
2019-08-08T15:34:25
null
UTF-8
Python
false
false
239
py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a=[1,2,3,4,5,6,7,8,9] a.reverse() print(a) b=[str(i)for i in a] print(b) c="".join(b) print(c) letter=c letter=letter[2:-1:1] print(letter) d=letter print(d) d = int(letter) print(bin(d), oct(d), hex(d))
[ "48744155+findyourselfloveyourself@users.noreply.github.com" ]
48744155+findyourselfloveyourself@users.noreply.github.com
4f63f863fe4ee61773d99af195ac113c5119a300
6437af616b0752b24e1b62bc98d302b2e04a7c85
/pagnition/supplier/www.houzz.co.uk/pagination.py
2478507174a2e07118bb0eda483547590d10f403
[]
no_license
kangqiwang/imageWebCrawler
4c7ebc0c93fd52b27f08a0f79302885d95f53a6e
76fe21802a5a03638e324e6d18fe5698a69aba70
refs/heads/master
2022-05-31T00:51:39.649907
2019-08-28T15:06:37
2019-08-28T15:06:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
915
py
import pandas as pd import numpy as np import requests def pagnition(): df=pd.read_csv("pagnition/input/houzz_co.uk.csv",usecols=['Category URL','Product Count']) tmpList=['url'] for url, count in zip(df['Category URL'],df['Product Count']): urltmp='' numbertmp=0 # if "categories/" in str(url): # urltmp = url.split("categories/")[0] # numbertmp=url.split("categories/")[1] perpageCount=90 pageNum=int(count/perpageCount)+1 for i in range(pageNum): # if urltmp !='': urltmp = url+'?fi='+str(i*perpageCount) # else: # tmpurl = url +'?Nao='+str(21*(i+1))+'&Ns=None&storeSelection=2408,2414,2409,2407,2404' print(urltmp) tmpList.append(urltmp) savedf=pd.Series(tmpList) savedf.to_csv("pagnition/output/houzz_co.uk.csv",index=False) pagnition()
[ "kang@sourcemogul.com" ]
kang@sourcemogul.com
9f5875e4b9a79aceced353ef4c7aeb17f642ce8e
657d549ffa47c4ef599aa5e0f5760af8de77fec4
/src/model/metrics.py
d77019b7766851c1baa07e13c6c79cfbd9865c45
[]
no_license
Tung-I/Incremental_Learning
68357d3db5a646aa6b3df844b85e12fa45e3eb3e
95602f404ab8dd627c5dd5fcc94a4a071ad330ab
refs/heads/master
2021-01-14T15:18:21.941132
2020-03-30T04:04:13
2020-03-30T04:04:13
242,659,450
2
0
null
null
null
null
UTF-8
Python
false
false
1,589
py
import torch import torch.nn as nn class Accuracy(nn.Module): """The accuracy for the classification task. """ def __init__(self): super().__init__() def forward(self, output, target): """ Args: output (torch.Tensor) (N, C): The model output. target (torch.LongTensor) (N, C): The data target. Returns: metric (torch.Tensor) (0): The accuracy. """ pred = output.argmax(dim=1, keepdim=True) return (pred == target).float().mean() def get_name(self): return 'Accuracy' class Dice(nn.Module): """The Dice score. """ def __init__(self): super().__init__() def forward(self, output, target): """ Args: output (torch.Tensor) (N, C, *): The model output. target (torch.LongTensor) (N, 1, *): The data target. Returns: metric (torch.Tensor) (C): The dice scores for each class. """ # Get the one-hot encoding of the prediction and the ground truth label. pred = output.argmax(dim=1, keepdim=True) pred = torch.zeros_like(output).scatter_(1, pred, 1) target = torch.zeros_like(output).scatter_(1, target, 1) # Calculate the dice score. reduced_dims = list(range(2, output.dim())) # (N, C, *) --> (N, C) intersection = (pred * target).sum(reduced_dims) cardinality = pred.sum(reduced_dims) + target.sum(reduced_dims) score = (2 * intersection / cardinality.clamp(min=1)).mean(dim=0) return score
[ "dong893610@gmail.com" ]
dong893610@gmail.com
21791f32c425cacd10fde375a9274782dd3e7f23
720e1b08abda01ad9645b043103050643142e519
/ops/dataset.py
e043f59d96e226d68303ab88e8a07ef416a65a9a
[ "Apache-2.0" ]
permissive
KevinQian97/actionpose-release
8ba0f4a0c5458bf5b54727522a5c053ba68e841f
0bf7ae1c30d1b2a1a6a18fc662e22da519d41e0c
refs/heads/main
2023-04-20T16:18:15.772245
2021-05-16T00:30:11
2021-05-16T00:30:11
367,750,764
0
0
null
null
null
null
UTF-8
Python
false
false
7,448
py
import torch.utils.data as data from avi_r import AVIReader from PIL import Image import os import torch import numpy as np from numpy.random import randint import cv2 import json import decord from decord import VideoReader from decord import cpu, gpu import torchvision import gc import math from ops.record import VideoRecord_NTU as VideoRecord decord.bridge.set_bridge('torch') class TSNDataSet(data.Dataset): def __init__(self, root_path, list_file, num_segments=3, new_length=1, modality='RGB', image_tmpl='img_{:05d}.jpg', transform=None, random_shift=True, test_mode=False, remove_missing=False, dense_sample=False, twice_sample=False, all_sample=False, analysis=False): self.root_path = root_path self.list_file = list_file self.num_segments = num_segments self.new_length = new_length self.modality = modality self.image_tmpl = image_tmpl self.transform = transform self.random_shift = random_shift self.test_mode = test_mode self.remove_missing = remove_missing self.dense_sample = dense_sample # using dense sample as I3D self.twice_sample = twice_sample # twice sample for more validation self.all_sample = all_sample #all sample for r21d on MEVA self.analysis = analysis if self.dense_sample: print('=> Using dense sample for the dataset...') if self.twice_sample: print('=> Using twice sample for the dataset...') if self.modality == 'RGBDiff': self.new_length += 1 # Diff needs one more image to calculate diff self._parse_list() # also modify it to video loader def _load_image(self, frames, directory, idx, start): if self.modality == 'RGB' or self.modality == 'RGBDiff' or self.modality == 'PoseAction': try: if idx >= len(frames): idx = len(frames)-1 return [frames[idx]] except Exception: print('error loading video:{} whose idx is {}'.format(os.path.join(self.root_path, directory),start+idx)) return [frames[0]] # parse_list for json input def _parse_list(self): tmp = json.load(open(self.list_file,"r"))["database"] items = tmp.keys() self.video_list = [VideoRecord(tmp[item],item,self.root_path) for item in items] print('video number:%d' % (len(self.video_list))) def _sample_indices(self, record): """ :param record: VideoRecord :return: list """ if self.dense_sample: # i3d dense sample sample_pos = max(1, 1 + record.num_frames - 64) t_stride = 64 // self.num_segments start_idx = 0 if sample_pos == 1 else np.random.randint(0, sample_pos - 1) offsets = [(idx * t_stride + start_idx) % record.num_frames for idx in range(self.num_segments)] return np.array(offsets) if self.all_sample: return np.array(range(record.num_frames)) else: # normal sample average_duration = (record.num_frames - self.new_length + 1) // self.num_segments if average_duration > 0: offsets = np.multiply(list(range(self.num_segments)), average_duration) + randint(average_duration, size=self.num_segments) elif record.num_frames > self.num_segments: offsets = np.sort(randint(record.num_frames - self.new_length + 1, size=self.num_segments)) else: offsets = np.zeros((self.num_segments)) return offsets def _get_val_indices(self, record): if self.dense_sample: # i3d dense sample sample_pos = max(1, 1 + record.num_frames - 64) t_stride = 64 // self.num_segments start_idx = 0 if sample_pos == 1 else np.random.randint(0, sample_pos - 1) offsets = [(idx * t_stride + start_idx) % record.num_frames for idx in range(self.num_segments)] return np.array(offsets) if self.all_sample: return np.array(range(record.num_frames)) else: if record.num_frames > self.num_segments + self.new_length - 1: tick = (record.num_frames - self.new_length + 1) / float(self.num_segments) offsets = np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segments)]) else: offsets = np.zeros((self.num_segments,)) return offsets def _get_test_indices(self, record): if self.dense_sample: sample_pos = max(1, 1 + record.num_frames - 64) t_stride = 64 // self.num_segments start_list = np.linspace(0, sample_pos - 1, num=10, dtype=int) offsets = [] for start_idx in start_list.tolist(): offsets += [(idx * t_stride + start_idx) % record.num_frames for idx in range(self.num_segments)] return np.array(offsets) if self.all_sample: return np.array(range(record.num_frames)) elif self.twice_sample: tick = (record.num_frames - self.new_length + 1) / float(self.num_segments) offsets = np.array([int(tick / 2.0 + tick * x) for x in range(self.num_segments)] + [int(tick * x) for x in range(self.num_segments)]) return offsets else: tick = (record.num_frames - self.new_length + 1) / float(self.num_segments) offsets = np.array([int(tick / 2.0 + tick * x)-1 for x in range(self.num_segments)]) return offsets def __getitem__(self, index): record = self.video_list[index] if not self.test_mode: segment_indices = self._sample_indices(record) if self.random_shift else self._get_val_indices(record) else: segment_indices = self._get_test_indices(record) return self.get(record, segment_indices) # get for json input def get(self, record, indices): # print(indices) images = list() frames = record.frames() for seg_ind in indices: p = int(seg_ind) for i in range(self.new_length): seg_imgs = self._load_image(frames,record.name,p,record.start) images.extend(seg_imgs) if p < record.num_frames: p += 1 # images = torch.stack(images,dim=0).float() # for image in images: # print(type(image)) process_data = self.transform(images) if self.modality == "PoseAction": skels = torch.FloatTensor(record.joints()) joints = [] for seg_ind in indices: p = int(seg_ind) joints.append(skels[:,p]) joints = torch.stack(joints,dim=1) if not self.analysis: return {"vid":process_data,"joints":joints}, record.label else: return {"vid":process_data,"joints":joints}, record.label, record.path else: if self.analysis: return process_data, record.label, record.path else: return process_data, record.label def __len__(self): return len(self.video_list)
[ "kevinqianyijun@gmail.com" ]
kevinqianyijun@gmail.com
76ccb21b726255190d7d6b15440749c4858d0266
d65f89ffa07c0d8ae868003dd102a8950a19f1b4
/Strings/2242.py
c25e43ec95e7bbeacd272d6bb2db466d7b9e3ba9
[]
no_license
BarthJr/URI-Online-Judge
5258fc573c593365e2f3e2d998fb806345cf777d
caf0cafe4c0fd8857f81a5dd81252e7ab42fda7e
refs/heads/master
2020-04-20T20:26:18.901890
2019-02-20T22:09:59
2019-02-20T22:09:59
169,076,767
5
1
null
null
null
null
UTF-8
Python
false
false
683
py
# https://www.urionlinejudge.com.br/judge/en/problems/view/2242 def verify_laugh(laugh): chunks = [] for char in laugh: if char in 'aeiou': chunks.append(char) laugh_without_consonants = ''.join(chunks) if laugh_without_consonants == ''.join(reversed(laugh_without_consonants)): return 'S' else: return 'N' def tests(): assert verify_laugh('hahaha') == 'S' assert verify_laugh('riajkjdhhihhjak') == 'N' assert verify_laugh('a') == 'S' assert verify_laugh('huaauhahhuahau') == 'S' def uri_format(): laugh = input() print(verify_laugh(laugh)) if __name__ == '__main__': tests() uri_format()
[ "juniior.barth@gmail.com" ]
juniior.barth@gmail.com
007fc890d58d95dd64e1189dc62371f0b7d0f23f
c4acd268a81eab784adf8ad61090200e06e9c81c
/agents/dqn_v1/actions/discrete.py
e583fcbb280dae340f25aa6b00261d7582e59a31
[ "MIT" ]
permissive
pedMatias/matias_hfo
7100d6d7ce12cb59bf103252054fbe8566d6ca6e
6d88e1043a1455f5c1f6cc11b9380869772f4176
refs/heads/master
2021-03-08T07:36:52.517964
2021-01-08T21:17:27
2021-01-08T21:17:27
246,330,403
1
1
MIT
2021-01-08T21:17:28
2020-03-10T14:56:45
Python
UTF-8
Python
false
false
8,269
py
import random from hfo import MOVE_TO, DRIBBLE_TO, KICK_TO, NOOP, SHOOT, PASS, MOVE from agents.base.hfo_attacking_player import HFOAttackingPlayer from agents.dqn_v1.features.discrete_features import \ DiscFeatures1Teammate class DiscreteActions: """ This class uniforms Move and Dribble actions. It allows agent to only have to select between 10 actions, instead of 18 actions """ action_w_ball = ["KICK_TO_GOAL", "PASS", "LONG_DRIBBLE_UP", "LONG_DRIBBLE_DOWN", "LONG_DRIBBLE_LEFT", "LONG_DRIBBLE_RIGHT", "SHORT_DRIBBLE_UP", "SHORT_DRIBBLE_DOWN", "SHORT_DRIBBLE_LEFT", "SHORT_DRIBBLE_RIGHT"] action_w_out_ball = ["NOOP", "NOOP", "LONG_MOVE_UP", "LONG_MOVE_DOWN", "LONG_MOVE_LEFT", "LONG_MOVE_RIGHT", "SHORT_MOVE_UP", "SHORT_MOVE_DOWN", "SHORT_MOVE_LEFT", "SHORT_MOVE_RIGHT"] num_actions = len(action_w_ball) long_action_num_episodes = 20 short_action_num_episodes = 10 def get_num_actions(self): return self.num_actions def map_action_to_str(self, action_idx: int, has_ball: bool) -> str: if has_ball: return self.action_w_ball[action_idx] else: return self.action_w_out_ball[action_idx] def dribble_to_pos(self, pos: tuple, features: DiscFeatures1Teammate, game_interface: HFOAttackingPlayer): """ The agent keeps dribbling until reach the position expected """ curr_pos = features.get_pos_tuple(round_ndigits=1) while pos != curr_pos: hfo_action = (DRIBBLE_TO, pos[0], pos[1]) status, observation = game_interface.step(hfo_action, features.has_ball()) # Update features: features.update_features(observation) curr_pos = features.get_pos_tuple(round_ndigits=1) def move_to_pos(self, pos: tuple, features: DiscFeatures1Teammate, game_interface: HFOAttackingPlayer): """ The agent keeps moving until reach the position expected """ curr_pos = features.get_pos_tuple(round_ndigits=1) while pos != curr_pos: hfo_action = (MOVE_TO, pos[0], pos[1]) status, observation = game_interface.step(hfo_action, features.has_ball()) # Update features: features.update_features(observation) curr_pos = features.get_pos_tuple(round_ndigits=1) def kick_to_pos(self, pos: tuple, features: DiscFeatures1Teammate, game_interface: HFOAttackingPlayer): """ The agent kicks to position expected """ hfo_action = (KICK_TO, pos[0], pos[1], 2) status, observation = game_interface.step(hfo_action, features.has_ball()) # Update features: features.update_features(observation) def shoot_ball(self, game_interface: HFOAttackingPlayer, features: DiscFeatures1Teammate): """ Tries to shoot, if it fail, kicks to goal randomly """ attempts = 0 # while game_interface.in_game() and features.has_ball(): # if attempts > 3: # break # elif attempts == 3: # # Failed to kick four times # # print("Failed to SHOOT 3 times. WILL KICK") # y = 0 # TODO random.choice([0.17, 0, -0.17]) # hfo_action = (KICK_TO, 0.9, y, 2) # else: # hfo_action = (SHOOT,) # _, obs = game_interface.step(hfo_action, features.has_ball()) # features.update_features(obs) # attempts += 1 hfo_action = (KICK_TO, 0.9, 0, 2) _, obs = game_interface.step(hfo_action, features.has_ball()) features.update_features(obs) return game_interface.get_game_status(), \ game_interface.get_observation_array() def pass_ball(self, game_interface: HFOAttackingPlayer, features: DiscFeatures1Teammate): """ Tries to use the PASS action, if it fails, Kicks in the direction of the teammate""" attempts = 0 while game_interface.in_game() and features.has_ball(): if attempts > 2: break elif attempts == 2: # Failed to pass 2 times # print("Failed to PASS two times. WILL KICK") hfo_action = (KICK_TO, features.teammate_coord[0], features.teammate_coord[1], 1.5) else: hfo_action = (PASS, 11) _, obs = game_interface.step(hfo_action, features.has_ball()) features.update_features(obs) attempts += 1 return game_interface.get_game_status(), \ game_interface.get_observation_array() def move_agent(self, action_name, game_interface: HFOAttackingPlayer, features: DiscFeatures1Teammate): """ Agent Moves/Dribbles in a specific direction """ # print("move_agent!") if "SHORT" in action_name: num_repetitions = 10 elif "LONG" in action_name: num_repetitions = 20 else: raise ValueError("ACTION NAME is WRONG") # Get Movement type: if "MOVE" in action_name: action = MOVE_TO elif "DRIBBLE" in action_name: action = DRIBBLE_TO else: raise ValueError("ACTION NAME is WRONG") if "UP" in action_name: action = (action, features.agent_coord[0], - 0.9) elif "DOWN" in action_name: action = (action, features.agent_coord[0], 0.9) elif "LEFT" in action_name: action = (action, -0.8, features.agent_coord[1]) elif "RIGHT" in action_name: action = (action, 0.8, features.agent_coord[1]) else: raise ValueError("ACTION NAME is WRONG") attempts = 0 while game_interface.in_game() and attempts < num_repetitions: status, observation = game_interface.step(action, features.has_ball()) features.update_features(observation) attempts += 1 return game_interface.get_game_status(), \ game_interface.get_observation_array() def do_nothing(self, game_interface: HFOAttackingPlayer, features: DiscFeatures1Teammate): action = (NOOP,) status, observation = game_interface.step(action, features.has_ball()) return status, observation def no_ball_action(self, game_interface: HFOAttackingPlayer, features: DiscFeatures1Teammate) -> int: action = (MOVE,) status, observation = game_interface.step(action, features.has_ball()) features.update_features(observation) return status def execute_action(self, action_idx: int, game_interface: HFOAttackingPlayer, features: DiscFeatures1Teammate): """ Receiving the idx of the action, the agent executes it and returns the game status """ action_name = self.map_action_to_str(action_idx, features.has_ball()) # KICK/SHOOT to goal if action_name == "KICK_TO_GOAL": status, observation = self.shoot_ball(game_interface, features) # PASS ball to teammate elif action_name == "PASS": status, observation = self.pass_ball(game_interface, features) # MOVE/DRIBBLE elif "MOVE" in action_name or "DRIBBLE" in action_name: status, observation = self.move_agent(action_name, game_interface, features) # DO NOTHING elif action_name == "NOOP": status, observation = self.do_nothing(game_interface, features) else: raise ValueError("Action Wrong name") # Update Features: features.update_features(observation) return status
[ "pedrosantox2@gmail.com" ]
pedrosantox2@gmail.com
8e63316e92985c4b390459b7b3b79bd847202bb9
07273d9d20d1c96940a99d70892f9546679c4430
/back-end/modelo.py
5439ec5a065e48e70d51e91db516482f137fe865
[]
no_license
biiabauer/Av3
a60fbbb2dce3f648d01fcb373bbf33b6c1993538
aa22e39c19a7f444acbb6db8726299912e13a505
refs/heads/master
2022-12-22T01:37:04.902184
2020-09-23T19:36:13
2020-09-23T19:36:13
298,024,399
0
0
null
null
null
null
UTF-8
Python
false
false
1,582
py
from config import * class Livro(db.Model): # atributos do livro nome = db.Column(db.String(254), primary_key=True) autor = db.Column(db.String(254)) ano = db.Column(db.String(254)) # método para expressar o livro em forma de texto def __str__(self): return f''' - Cadeira({self.id}) - nome: {self.nome} - cor: {self.cor} - fabricante: {self.fabricante} - descrição: {self.descricao} - material: {self.material} ''' # expressao da classe no formato json def json(self): return { "nome": self.nome, "autor": self.autor, "ano": self.ano, } # teste if __name__ == "__main__": # apagar o arquivo, se houver if os.path.exists(arquivobd): os.remove(arquivobd) # criar tabelas db.create_all() # teste da classe Pessoa l1 = Livro (nome = "A noiva fantasma", autor = "Yangsze Choo", ano = "2015") l2 = Livro (nome = "Névoa", autor = "Kathyn James", ano = "2014") l3 = Livro (nome = "Gelo", autor = "Kathyn James", ano = "2014") l4 = Livro (nome = "Brida", autor = "Paulo Coelho", ano = "1990" ) l5 = Livro (nome = "Anjos e Demônios", autor = "Dan Brown", ano = "2003") db.session.add(l1) db.session.add(l2) db.session.add(l3) db.session.add(l4) db.session.add(l5) db.session.commit() print(l1.json()) print(l2.json()) print(l3.json()) print(l4.json()) print(l5.json())
[ "biiia.bauer16@gmail.com" ]
biiia.bauer16@gmail.com
677b3d3e7b112eccf5480e5f571cbf708d0806f0
9d67af6c44e74120cabd011a44d75fb2a0e9b671
/test/validate.py
4cf7e4460cfac889819c615fd06920b58e025473
[]
no_license
taiwan-hero/localmeasure-reports
d946591884de804cc9e36cc5b4b1cb268d711ce9
e7ff2975f5a74787ba54cd35ad0988387004c5b2
refs/heads/master
2021-01-25T10:15:48.692713
2016-01-02T20:09:12
2016-01-02T20:09:12
34,374,327
0
1
null
null
null
null
UTF-8
Python
false
false
5,453
py
from pymongo import MongoClient import pymongo import argparse import datetime import calendar from bson import ObjectId DESCRIPTION = 'validates the reports' args = None db = None metrics_db = None months = ['2014Jun', '2014Jul', '2014Aug', '2014Sep', '2014Oct', '2014Nov', '2014Dec', '2015Jan', '2015Feb', '2015Mar', '2015Apr', '2015May'] def get_options(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument('mongodb', help='db to connect to i.e. mongodb://127.0.0.1:27017') parser.add_argument('merchant_id', help='merchant id to validate i.e. 54fe13816f5e2268db95caf1') parser.add_argument('month', help='merchant id to validate i.e. 2015Mar') return parser.parse_args() def parse_args(): global args args = get_options() def connect_db(): print 'Connecting to', args.mongodb global db global metrics_db client = MongoClient(args.mongodb) db = client.localmeasure metrics_db = client.localmeasure_metrics def setup(): parse_args() connect_db() def validate_content(merchant_id, month): erroneous_reports = [] content_reports = metrics_db.content.find({'merchant_id': merchant_id}) places = db.places.find({'merchant_id': ObjectId(merchant_id)}) venues = [] for place in places: for venue_id in place['venue_ids']: venues.append(venue_id) print "venue_ids = {}".format(venues) start = datetime.datetime.strptime(month + '01', "%Y%b%d") end = datetime.datetime.strptime(month + '31', "%Y%b%d") post_count = db.posts.find({'secondary_venue_ids': {'$in': venues}, 'post_time': {'$gt': start, '$lt': end}}).count() print 'posts found {} '.format(post_count) def find_all_venue_mentions(merchant_id): mentions = [] places = db.places.find({'merchant_id': ObjectId(merchant_id)}) for place in places: for venue_id in place['venue_ids']: venue = db.venues.find_one({'_id': venue_id}) if venue and 'type' in venue: if venue['type'] == 'mention': mentions.append(venue['term']) return mentions def find_all_handle_mentions(merchant_id): mentions = [] merchant = db.merchants.find_one({'_id': ObjectId(merchant_id)}) if merchant and 'linked_accounts' in merchant: if 'instagram' in merchant['linked_accounts']: for ig in merchant['linked_accounts']['instagram']: mentions.append(ig['name']) if 'twitter' in merchant['linked_accounts']: for tw in merchant['linked_accounts']['twitter']: mentions.append(tw['name']) return mentions def get_mentions(merchant_id, month, mentions): keyword_mentions = metrics_db.keywords.find({'merchant_id': merchant_id, 'post_month': month, 'word': {'$in': mentions}}) for km in keyword_mentions: print '{} : {} : {}'.format(km['place_name'], km['word'], km['total']) def validate_interactions(merchant_id, month): print month places = db.places.find({'merchant_id': ObjectId(merchant_id)}) for place in places: venues = place['venue_ids'] if not venues: continue start = datetime.datetime.strptime(month + '01', "%Y%b%d") next_month = int(start.strftime('%m')) + 1 year = int(start.strftime('%Y')) if next_month == 13: next_month = 1 year = year + 1 end = datetime.datetime.strptime(str(year) + str(next_month).zfill(2) + '01', "%Y%m%d") post_count = db.posts.find({'secondary_venue_ids': {'$in': venues}, 'post_time': {'$gt': start, '$lt': end}, 'tag_ids': {'$in': [ObjectId("5433518d6f5e223cbd4dd921"), ObjectId("5433c142c62697253474f18c")]} }).count() print ' {} : {}'.format(place['name'], post_count) def list_users_interactions(user_name, month): start = datetime.datetime.strptime(month + '01', "%Y%b%d") next_month = int(start.strftime('%m')) + 1 year = int(start.strftime('%Y')) if next_month == 13: next_month = 1 year = year + 1 end = datetime.datetime.strptime(str(year) + str(next_month).zfill(2) + '01', "%Y%m%d") this_months_likes = db.audits.find({'actor.label': user_name, 'type': 'like', 'created_at': {'$gt': start, '$lt': end}}) for like in this_months_likes: orig_post = db.posts.find_one({'_id': like['subject']['origin_id']}) if not orig_post: continue print 'liked: {} at:'.format(orig_post['_id']) venues = orig_post['secondary_venue_ids'] post_places = db.places.find({'venue_ids': {'$in': venues}}) for post_place in post_places: print ' place: {} - {}'.format(post_place['name'], post_place['merchant_id']) def validate_segment_totals(): for segment in metrics_db.segments.find({}): totals = segment['counts']['total'] sums = {"FB": 0, "IG": 0, "4S": 0, "TW": 0} for i in range(24): for source in sums: sums[source] += segment['counts']["%02d"%i][source] for source in sums: print '{} {}'.format(sums[source], totals[source]) if sums[source] != totals[source]: print 'problem' if __name__ == '__main__': setup() validate_segment_totals()
[ "tim@getlocalmeasure.com" ]
tim@getlocalmeasure.com
8c0f4f5a3feb660a745ddf7a9d1e49e23a35f7fe
e4713c248c857b06a3cb0e9d0d15dd5513b1a8e9
/phonenumbers/data/region_FO.py
5c06031d809a3c236e20fd875c24b55bdfcb84b5
[ "Apache-2.0", "MIT" ]
permissive
igushev/fase_lib
8f081e0f6b956b186dc759906b21dc3fc449f045
182c626193193b196041b18b9974b5b2cbf15c67
refs/heads/master
2023-05-14T14:35:05.727202
2022-04-15T23:55:37
2022-04-15T23:55:37
107,228,694
10
0
MIT
2023-05-01T19:38:09
2017-10-17T06:47:07
Python
UTF-8
Python
false
false
1,273
py
"""Auto-generated file, do not edit by hand. FO metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_FO = PhoneMetadata(id='FO', country_code=298, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[2-9]\\d{5}', possible_number_pattern='\\d{6}', possible_length=(6,)), fixed_line=PhoneNumberDesc(national_number_pattern='(?:20|[3-4]\\d|8[19])\\d{4}', example_number='201234', possible_length=(6,)), mobile=PhoneNumberDesc(national_number_pattern='(?:[27][1-9]|5\\d)\\d{4}', example_number='211234', possible_length=(6,)), toll_free=PhoneNumberDesc(national_number_pattern='80[257-9]\\d{3}', possible_number_pattern='\\d{6}', example_number='802123', possible_length=(6,)), premium_rate=PhoneNumberDesc(national_number_pattern='90(?:[1345][15-7]|2[125-7]|99)\\d{2}', possible_number_pattern='\\d{6}', example_number='901123', possible_length=(6,)), voip=PhoneNumberDesc(national_number_pattern='(?:6[0-36]|88)\\d{4}', possible_number_pattern='\\d{6}', example_number='601234', possible_length=(6,)), national_prefix_for_parsing='(10(?:01|[12]0|88))', number_format=[NumberFormat(pattern='(\\d{6})', format='\\1', domestic_carrier_code_formatting_rule='$CC \\1')])
[ "igushev@gmail.com" ]
igushev@gmail.com
d065c3b4020660fea2bb8f0b5fbe6f5b277616d3
e7d6f748c1ff6c77544e544ede904380690be5c0
/SRCNN for CoLab/tests.py
bfd27203c081daa3bea0f3179d6fb0299c4582f9
[]
no_license
SirRacha/SRCNN_Satellite
1550ee873aaa0a4ba549be5f16ef84a2ecff3885
0615834e0e07fa85f027f81cf3a9f5540743cca4
refs/heads/master
2023-07-29T12:12:40.680674
2020-02-12T00:32:54
2020-02-12T00:32:54
235,240,785
3
0
null
2023-07-06T21:39:38
2020-01-21T02:34:36
Python
UTF-8
Python
false
false
5,272
py
from __future__ import print_function, division from keras.utils.vis_utils import plot_model import models import img_utils if __name__ == "__main__": path = r"headline_carspeed.jpg" val_path = "val_images/" scale = 2 """ Plot the models """ model = models.ImageSuperResolutionModel(scale).create_model() plot_model(model, to_file="architectures/SRCNN.png", show_shapes=True, show_layer_names=True) # model = models.ExpantionSuperResolution(scale).create_model() # plot_model(model, to_file="architectures/ESRCNN.png", show_layer_names=True, show_shapes=True) # model = models.DenoisingAutoEncoderSR(scale).create_model() # plot_model(model, to_file="architectures/Denoise.png", show_layer_names=True, show_shapes=True) # model = models.DeepDenoiseSR(scale).create_model() # plot_model(model, to_file="architectures/Deep Denoise.png", show_layer_names=True, show_shapes=True) # model = models.ResNetSR(scale).create_model() # plot_model(model, to_file="architectures/ResNet.png", show_layer_names=True, show_shapes=True) # model = models.GANImageSuperResolutionModel(scale).create_model(mode='train') # plot_model(model, to_file='architectures/GAN Image SR.png', show_shapes=True, show_layer_names=True) # model = models.DistilledResNetSR(scale).create_model() # plot_model(model, to_file='architectures/distilled_resnet_sr.png', show_layer_names=True, show_shapes=True) # model = models.NonLocalResNetSR(scale).create_model() # plot_model(model, to_file='architectures/non_local_resnet_sr.png', show_layer_names=True, show_shapes=True) """ Train Super Resolution """ sr = models.ImageSuperResolutionModel(scale) sr.create_model() sr.fit(nb_epochs=250) """ Train ExpantionSuperResolution """ # esr = models.ExpantionSuperResolution(scale) # esr.create_model() # esr.fit(nb_epochs=250) """ Train DenoisingAutoEncoderSR """ # dsr = models.DenoisingAutoEncoderSR(scale) # dsr.create_model() # dsr.fit(nb_epochs=250) """ Train Deep Denoise SR """ # ddsr = models.DeepDenoiseSR(scale) # ddsr.create_model() # ddsr.fit(nb_epochs=180) """ Train Res Net SR """ # rnsr = models.ResNetSR(scale) # rnsr.create_model(load_weights=True) # rnsr.fit(nb_epochs=50) """ Train ESPCNN SR """ # espcnn = models.EfficientSubPixelConvolutionalSR(scale) # espcnn.create_model() # espcnn.fit(nb_epochs=50) """ Train GAN Super Resolution """ # gsr = models.GANImageSuperResolutionModel(scale) # gsr.create_model(mode='train') # gsr.fit(nb_pretrain_samples=10000, nb_epochs=10) """ Train Non Local ResNets """ # non_local_rnsr = models.NonLocalResNetSR(scale) # non_local_rnsr.create_model() # non_local_rnsr.fit(nb_epochs=50) """ Evaluate Super Resolution on Set5/14 """ sr = models.ImageSuperResolutionModel(scale) sr.evaluate(val_path) """ Evaluate ESRCNN on Set5/14 """ #esr = models.ExpantionSuperResolution(scale) #esr.evaluate(val_path) """ Evaluate DSRCNN on Set5/14 cannot be performed at the moment. This is because this model uses Deconvolution networks, whose output shape must be pre determined. This causes the model to fail to predict different images of different image sizes. """ #dsr = models.DenoisingAutoEncoderSR(scale) #dsr.evaluate(val_path) """ Evaluate DDSRCNN on Set5/14 """ #ddsr = models.DeepDenoiseSR(scale) #ddsr.evaluate(val_path) """ Evaluate ResNetSR on Set5/14 """ # rnsr = models.ResNetSR(scale) # rnsr.create_model(None, None, 3, load_weights=True) # rnsr.evaluate(val_path) """ Distilled ResNetSR """ # distilled_rnsr = models.DistilledResNetSR(scale) # distilled_rnsr.create_model(None, None, 3, load_weights=True) # distilled_rnsr.evaluate(val_path) """ Evaluate ESPCNN SR on Set 5/14 """ # espcnn = models.EfficientSubPixelConvolutionalSR(scale) # espcnn.evaluate(val_path) """ Evaluate GAN Super Resolution on Set 5/14 """ # gsr = models.GANImageSuperResolutionModel(scale) # gsr.evaluate(val_path) """ Evaluate Non Local ResNetSR on Set 5/14 """ # non_local_rnsr = models.NonLocalResNetSR(scale) # non_local_rnsr.evaluate(val_path) """ Compare output images of sr, esr, dsr and ddsr models """ #sr = models.ImageSuperResolutionModel(scale) #sr.upscale(path, save_intermediate=False, suffix="sr") #esr = models.ExpantionSuperResolution(scale) #esr.upscale(path, save_intermediate=False, suffix="esr") #dsr = models.DenoisingAutoEncoderSR(scale) #dsr.upscale(path, save_intermediate=False, suffix="dsr") # ddsr = models.DeepDenoiseSR(scale) # ddsr.upscale(path, save_intermediate=False, suffix="ddsr") # rnsr = models.ResNetSR(scale) # rnsr.create_model(None, None, 3, load_weights=True) # rnsr.upscale(path, save_intermediate=False, suffix="rnsr") #gansr = models.GANImageSuperResolutionModel(scale) #gansr.upscale(path, save_intermediate=False, suffix='gansr')
[ "chrisholland@Chriss-MacBook-Pro.local" ]
chrisholland@Chriss-MacBook-Pro.local
aedbffcd2437f3fc1881c7e8bda22a1f01b9f8d2
6a7c6902c199593dbd3e9febb3767accc749b994
/core/pytest/test_kek.py
dcff1fda1b6a1c97539121e48928f4e6a2b6069c
[]
no_license
AlexCPU7/inst
98335cad228389f8c839c98a219aa438ce87fe29
3e34bff6dbfe41028f09209f0ced11dace8050a9
refs/heads/master
2022-11-24T14:00:04.937285
2020-02-27T05:08:41
2020-02-27T05:08:41
163,030,158
0
0
null
null
null
null
UTF-8
Python
false
false
72
py
import pytest class TestKek: def test_kek(self): assert 0
[ "Ja54So67N" ]
Ja54So67N
c0abc65a918a5dcc8f92067eb5e744b23f0e514d
d46bb796c04adcbd8a93377c55c41980f12a24cd
/image_classification_program.py
5104ca0cae6a67900c197f72ea37ce1542c68b01
[]
no_license
pujith1997/image-clssification
e7483871af691338506acc3f1e7d8ee990a8217b
7a7788b0fc591b67851578b070e1b276337b98ee
refs/heads/master
2022-04-26T04:27:23.881045
2020-04-30T17:31:18
2020-04-30T17:31:18
260,274,838
1
0
null
null
null
null
UTF-8
Python
false
false
1,743
py
#!/usr/bin/env python # coding: utf-8 # In[1]: # import libraries import pandas as pd # Import Pandas for data manipulation using dataframes import numpy as np # Import Numpy for data statistical analysis # In[2]: from matplotlib import pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split get_ipython().run_line_magic('matplotlib', 'inline') # In[14]: data = pd.read_csv(r"C:\Users\pujith\OneDrive\Desktop\input23\fashion-mnist_train.csv") # In[15]: data.head() # In[ ]: #extracting the data from dataset and viewing them up close # In[16]: a = data.iloc[3,1:].values # In[17]: #reshaping the extracted data into resonable size a = a.reshape(28,28).astype('uint8') plt.imshow(a) # In[18]: #preparing the data #separating lables and data values df_x = data.iloc[:,1:] df_y = data.iloc[:,0] # In[19]: #creating test and train sizes x_train,x_test,y_train,y_test = train_test_split(df_x,df_y,test_size = 0.2,random_state=4) # In[20]: #checking the data x_train.head() # In[21]: y_train.head() # In[23]: #call rf classifier rf = RandomForestClassifier(n_estimators=100) # In[24]: #fit the model rf.fit(x_train,y_train) # In[25]: #prediction on the test data pred = rf.predict(x_test) # In[26]: pred # In[27]: #check prediction accuracy correct = y_test.values #calculate no of correctly predicted values count = 0 for i in range (len(pred)): if pred[i]==correct[i]: count+=1 # In[28]: count # In[29]: #total values that prediction was run for len(pred) # In[30]: #accuracy rate 10520/12000 # In[31]: 87.66 # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
[ "noreply@github.com" ]
pujith1997.noreply@github.com
3928aed4434b497e2f556e81f17a369cb7fd1d55
66985fd3b12efa317136d6db5ab29988faa0f539
/Python3.6/refprop.py
92c503265e75d30497395246c40595aba56eb946
[ "MIT" ]
permissive
RaphaelGervaisLavoie/REFPROP-v10-Python-wrapper
cccb7f960b25b74b5f166b437750eaaa2216a11c
2dd2f5fa95e46c9552f156bd0555e4ab7bdea5cb
refs/heads/master
2020-03-28T10:56:38.346588
2018-09-10T15:11:42
2018-09-10T15:11:42
148,161,933
2
0
null
null
null
null
UTF-8
Python
false
false
213,854
py
#------------------------------------------------------------------------------- #Name: refprop #Purpose: Call out fluid properties from REFPROP # #Author: Thelen, B.J. # thelen_ben@yahoo.com # #10 september 2018: #Modified by Raphaël Gervais Lavoie # raphael.gervaislavoie@uqtr.ca #Had to removed functions: - cvcpk # - dpdd # - dpddk # - dpdt # - dpdtk # - dddp # - dddt #------------------------------------------------------------------------------- # #Recognitions #------------------------------------------------------------------------------- #Creators / Developers of REFPROP, #Lemmon, E.W., #Huber, M.L., #McLinden, M.O., #NIST Standard Reference Database 23: Reference Fluid Thermodynamic and #Transport Properties-REFPROP, #Version 9.1, #National Institute of Standards and Technology, #Standard Reference Data Program, Gaithersburg, 2010. # #Initial developer of Python link to REFPROP, #Bruce Wernick #------------------------------------------------------------------------------- ''' This Python module compiled and linked the Database REFPROP (REFerence fluid PROPerties) for usage in Python. REFPROP software is a proprietary and need to be installed on the computer in order for this module to function. Please contact the National Institute ofStandards and Technology (NIST) to obtain REFPROP The subroutine SETUP must be called to initialize the pure fluid or mixture components. The call to SETUP will allow the choice of one of three standard reference states for entropy and enthalpy and will automatically load the "NIST-recommended" models for the components as well as mixing rules.The routine SETMOD allows the specification of other models. To define another reference state, or to apply one of the standard states to a mixture of a specified composition, the subroutine SETREF may be used.These additional routines should be called only if the fluids and/or models (or reference state) are changed. The sequence is: call SETMOD (optional) or GERG04 (Optional) call SETUP (REQUIRED) call SETKTV (optional) call PREOS (optional) call SETAGA (optional) call SETREF (optional) Subroutine PUREFLD allows the user to calculate the properties of a pure fluid when a mixture has been loaded and the fluid is one of the constituents in the mixture. Units ---------------------------------------------------------------------------- temperature K pressure, fugacity kPa density mol/L composition mole fraction quality mole basis (moles vapor/total moles) enthalpy, internal energy J/mol Gibbs, Helmholtz free energy J/mol entropy, heat capacity J/(mol.K) speed of sound m/s Joule-Thompson coefficient K/kPa d(p)/d(rho) kPa.L/mol d2(p)/d(rho)2 kPa.(L/mol)^2 viscosity microPa.s (10^-6 Pa.s) thermal conductivity W/(m.K) dipole moment debye surface Tension N/m ---------------------------------------------------------------------------- ''' #imports from fnmatch import fnmatch from os import listdir, path from platform import system from copy import copy from decimal import Decimal if system() == 'Linux': from ctypes import ( c_long, create_string_buffer, c_double, c_char, byref, RTLD_GLOBAL, CDLL) elif system() == 'Windows': from ctypes import ( c_long, create_string_buffer, c_double, c_char, byref, RTLD_GLOBAL, windll) #Declarations #strings testresult = '' _setwarning = 'on' _seterror = 'on' _seterrordebug = 'off' _setinputerrorcheck = 'on' _fpath = '' #Dict _fldext = {} _setupprop = {} _set = {} #Intergers _fixicomp = 0 _nmxpar = 6 _maxcomps = 20 #Nones (_rp, _gerg04_pre_rec, _setmod_pre_rec, _setup_rec, _setmod_rec, _gerg04_rec, _setref_rec, _purefld_rec, _setktv_rec, _setaga_rec, _preos_rec) \ = (None,)*11 #c_long (_icomp, _jcomp, _kph, _kq, _kguess, _nc, _ixflag, _v, _nroot, _k1, _k2, _k3, _ksat, _ierr, _kr, _iderv) = (c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long()) #create_string_buffer _routine = create_string_buffer(2) _hrf, _htype, _hmodij, _hmix, _hcode = ( create_string_buffer(3), create_string_buffer(3), create_string_buffer(3), create_string_buffer(3), create_string_buffer(3)) _hname, _hcas = (create_string_buffer(12), create_string_buffer(12)) _hn80 = create_string_buffer(80) _hpth, _hmxnme, _hfmix, _hbinp, _hmxrul, _hfm, _hcite, _herr, _hfile = ( create_string_buffer(255), create_string_buffer(255), create_string_buffer(255), create_string_buffer(255), create_string_buffer(255), create_string_buffer(255), create_string_buffer(255), create_string_buffer(255), create_string_buffer(255)) _hfld = create_string_buffer(10000) #C-doubles * _x, _x0, _xliq, _xvap, _xkg, _xbub, _xdew, _xlkg, _xvkg, _u, _f, _dadn, _dnadn \ = ((c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)()) _fij = (c_double * _nmxpar)() #c_chars _hcomp = ((c_char * 3) * _maxcomps)() #some error with ctypes or refpropdll the following should work but doesnot #_hfij = ((c_char * 8) * _nmxpar)() _hfij = ((c_char * (8 * _nmxpar)) * _nmxpar)() #c_doubles 26 (_tcrit, _pcrit, _Dcrit, _zcrit, _t, _D, _p, _e, _h, _s, _A, _G, _cv, _cp, _w, _Z, _hjt, _xkappa, _beta, _dpdD, _d2pdD2, _dpdt, _dDdt, _dDdp, _spare1, _spare2, _spare3, _spare4, _xisenk, _xkt, _betas, _bs, _xkkt, _thrott, _pint, _spht, _Ar, _Gr, _dhdt_D, _dhdt_p, _dhdD_t, _dhdD_p, _dhdp_t, _dhdp_D, _b, _dbt, _c, _d, _Dliq, _Dvap, _t1, _p1, _D1, _t2, _p2, _D2, _t3, _p3, _D3, _csat, _cv2p, _tcx, _qkg, _wmix, _wmm, _ttrp, _tnbpt, _acf, _dip, _Rgas, _tmin, _tmax, _Dmax, _pmax, _Dmin, _tbub, _tdew, _pbub, _pdew, _Dlbub, _Dvdew, _wliq, _wvap, _de, _sigma, _eta, _h0, _s0, _t0, _p0, _vE, _eE, _hE, _sE, _aE, _gE, _pr, _er, _hr, _sr, _cvr, _cpr, _ba, _ca, _dct, _dct2, _Fpv, _cs, _ts, _Ds, _ps, _ws, _var1, _var2, _q) \ = (c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double(), c_double()) #classes class _Setuprecord(): 'record setmod, setup, setktv, setref, purefld input values for def reset' object_list = [] #add record def __init__(self, record, objectname): self.record = record self.objectname = objectname self.object_list.append(self.objectname) #del record def __del__(self): self.object_list.remove(self.objectname) class SetWarning: 'Return RefpropdllWarning status (on / off)' def __repr__(self): return _setwarning @staticmethod def on(): 'Sets RefpropdllWarning on, initiate Error on Refpropdll ierr value < 0' global _setwarning _setwarning = 'on' if 'SetWarng' in _set: _set.pop('SetWarning') return _prop() @staticmethod def off(): 'Sets RefpropdllWarning off, no Error raised on Refpropdll ierr value < 0' global _setwarning _setwarning = 'off' _set['SetWarning'] = 'off' return _prop() class SetError: 'Return RefpropdllError status (on / off)' def __repr__(self): return _seterror @staticmethod def on(): 'Sets RefpropdllError on, initiate Error on Refpropdll ierr value != 0' global _seterror _seterror = 'on' if 'SetError' in _set: _set.pop('SetError') return _prop() @staticmethod def off(): 'Sets RefpropdllError off, no Error raised on Refpropdll ierr value != 0' global _seterror _seterror = 'off' _set['SetError'] = 'off' return _prop() class SetErrorDebug: 'Return SetErrorDebug status (on / off)' def __repr__(self): return _seterrordebug @staticmethod def on(): 'Sets error debug mode on, displays error message only' global _seterrordebug _seterrordebug = 'on' _set['SetDebug'] = 'on' return _prop() @staticmethod def off(): 'Sets error debug mode off, displays error message only' global _seterrordebug _seterrordebug = 'off' if 'SetDebug' in _set: _set.pop('SetDebug') return _prop() class SetInputErrorCheck: 'Return SetInputErrorCheck status (on / off)' def __repr__(self): return _setinputerrorcheck @staticmethod def on(): 'Sets errorinputerror mode on, displays input error message' global _setinputerrorcheck _setinputerrorcheck = 'on' if 'SetInputErrorCheck' in _set: _set.pop('SetInputErrorCheck') return _prop() @staticmethod def off(): 'Sets errorinputerror mode off, no input error displays message' global _setinputerrorcheck _setinputerrorcheck = 'off' _set['SetInputErrorCheck'] = 'off' return _prop() class RefpropError(Exception): 'General RepropError for python module' pass class RefpropinputError(RefpropError): 'Error for incorrect input' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class RefproproutineError(RefpropError): 'Error if routine input is unsupported' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class RefpropdllError(RefpropError): 'General RepropError from refprop' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class RefpropicompError(RefpropError): 'Error for incorrect component no input' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class RefpropnormalizeError(RefpropError): 'Error if sum component input does not match value 1' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class RefpropWarning(RefpropError): 'General Warning for python module' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class RefpropdllWarning(RefpropWarning): 'General RepropWarning from refprop' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class SetupWarning(RefpropWarning): 'General SetupWarning from refprop' def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class FluidModel(): '''return string of current loaded fluid model array includes: setmod / gerg04 setup setktv preos setaga setref purefld''' def __repr__(self): global _setup_rec, _setmod_rec, _gerg04_rec, _setref_rec, _purefld_rec global _setktv_rec, _setaga_rec, _preos_rec fldsetup = '' if '_setmod_rec' in _Setuprecord.object_list: fldsetup += 'setmod ==> ' + str(_setmod_rec.record) + '\n' if '_gerg04_rec' in _Setuprecord.object_list: fldsetup += 'gerg04 ==> ' + str(_gerg04_rec.record) + '\n' if '_setup_rec' in _Setuprecord.object_list: fldsetup += 'setup ==> ' + str(_setup_rec.record) + '\n' if '_setktv_rec' in _Setuprecord.object_list: fldsetup += 'setktv ==> ' + str(_setktv_rec.record) + '\n' if '_preos_rec' in _Setuprecord.object_list: fldsetup += 'preos ==> ' + str(_preos_rec.record) + '\n' if '_setaga_rec' in _Setuprecord.object_list: fldsetup += 'setaga ==> ' + str(_setaga_rec.record) + '\n' if '_setref_rec' in _Setuprecord.object_list: fldsetup += 'setref ==> ' + str(_setref_rec.record) + '\n' if '_purefld_rec' in _Setuprecord.object_list: fldsetup += 'purefld ==> ' + str(_purefld_rec.record) + '\n' return fldsetup #Functions #additional functions (not from refprop) def _checksetupmodel(model): 'Raise warning if multiple models are being set' models = [] #add setmod if called already if '_setmod_rec' in _Setuprecord.object_list: models.append('setmod') #add setktv if called already if '_setktv_rec' in _Setuprecord.object_list: models.append('setktv') #add gerg04 if called already if '_gerg04_rec' in _Setuprecord.object_list: models.append('gerg04') #add called model if not included already if model not in models: models.append(model) #raise warning on multiple model calls and if warning is on if len(models) > 1 and str(SetWarning()) == 'on': raise SetupWarning('''Warning, calling multiple model setups (setmod, setktv and gerg04 and others) could result in unexpected results. Furthermore these multiple model calls are not supported by function "resetup' and consequentely in the extention module "multiRP"''') def _outputierrcheck(ierr, herr, defname, prop): #_ierr correction, some unknown reason the value is # increased by 2**32 ierr_max = 9999 ierr_corr = 2**32 if ierr > ierr_max: ierr = ierr - ((ierr + ierr_max) // ierr_corr) * ierr_corr def mes_string(ERorWA): string = '*' * 80 + '\n' string += '*' * 80 + '\n' string += ERorWA + ' raised' + '\n' string += 'setup details' + '\n' string += str(FluidModel()) + '\n' string += 'refprop dll call details' + '\n' string += str(defname) + '\n' string += 'error details' + '\n' string += str(ierr) + '\n' string += str(herr) + '\n' string += 'prop output' + '\n' string += str(prop) + '\n' string += '*' * 80 + '\n'*3 return string if ierr < 0 \ and str(SetWarning()) == 'on' \ and str(SetError()) == 'on': #raise warning #warning string if str(SetErrorDebug()) == 'on': print(mes_string('warning')) raise RefpropdllWarning(herr.decode('utf-8')) elif ierr > 0 and str(SetError()) == 'on': #raise error #error string if str(SetErrorDebug()) == 'on': print(mes_string('error')) raise RefpropdllError(herr.decode('utf-8')) def _prop(**prop): global _fixicomp, _setupprop, _set prop.update(_setupprop) prop.update(_set) #local declarations icomp = prop.get('icomp') jcomp = prop.get('jcomp') nc = prop.get('nc') hfld = prop.get('hfld') _fixicomp = prop.get('fixicomp') ierr = prop.get('ierr') #one time hfld correction by icomp if icomp != None and nc != None: if icomp == 0 or icomp > nc: raise RefpropicompError ('undefined "icomp: ' + str(icomp) + '" value, select mixture component ' + 'number between 1 and ' + str(nc)) prop['icomp'] = [icomp, hfld[icomp - 1]] #one time hfld correction by jcomp if jcomp != None and nc != None: if jcomp == 0 or jcomp > nc: raise RefpropicompError ('undefined "jcomp: ' + str(jcomp) + '" value, select mixture component ' + 'number between 1 and ' + str(nc)) prop['jcomp'] = [jcomp, hfld[jcomp - 1]] #multiple time hfld correction by fixicomp / purefld if _fixicomp != None: del prop['fixicomp'] #assign purefluid in prop if nc != None and _fixicomp != None and _fixicomp > nc: raise RefpropicompError ('undefined "icomp: ' + str(_fixicomp) + '" value, select mixture component ' + 'number below ' + str(nc)) elif _fixicomp == 0: if 'purefld' in prop: del prop['purefld'] elif nc != None and _fixicomp != None and 0 < _fixicomp <= nc: prop['purefld'] = [_fixicomp, hfld[_fixicomp - 1]] #raise error if ierr != None: _outputierrcheck(ierr, prop['herr'], prop['defname'], prop) del prop['ierr'], prop['herr'], prop['defname'] return prop def _inputerrorcheck(deflocals): if str(SetInputErrorCheck()) == 'off': return None #from time import time# checkstring = ['hmxnme', 'hrf', 'htype', 'hmix', 'path', 'routine', 'hmodij', 'hfmix'] checkint = ['icomp', 'kph', 'nc', 'ixflag', 'kguess', 'ksat', 'jcomp', 'kq'] checkfloat = ['t', 'D', 'h0', 's0', 't0', 'p0', 's', 'h', 'e', 'p', 'var1', 'var2', 'tbub', 'tdew', 'pbub', 'pdew', 'Dlbub', 'Dvdew', 'q', 'qkg', 'v'] checklistcomp = ['x', 'xkg', 'xbub', 'xdew', 'xlkg', 'xvkg'] checklist = ['fij', 'x0'] checkliststring = ['hfld', 'hcomp'] for key in deflocals: value = deflocals[key] if key in checkstring: if not type(value) == str: raise RefpropinputError ('expect "str" input for ' + key + ' instead of "' + str(value.__class__) +'"') elif key in checkint: if not type(value) == int: raise RefpropinputError ('expect "int" input for ' + key + ' instead of "' + str(value.__class__) +'"') elif key in checkfloat: if not type(value) == float \ and not type(value) == int: raise RefpropinputError ('expect "float" or "int" input for ' + key + ' instead of "' + str(value.__class__) +'"') elif key in checklistcomp: if not value: pass else: lenvalue = len(value) if not type(value) == list: raise RefpropinputError('expect "list" input for ' + key + ' instead of "' + str(value.__class__) + '"') elif lenvalue != _nc_rec.record: if '_purefld_rec' in _Setuprecord.object_list \ and lenvalue != 1: raise RefpropicompError('input value ' + key + ' does not match the setup ' 'fluid selection.') elif '_purefld_rec' not in _Setuprecord.object_list: raise RefpropicompError('input value ' + key + ' does not match the setup ' + 'fluid selection') if sum(value) != 1: raise RefpropnormalizeError('sum input value ' + key + 'is unequal to 1') elif key in checklist: if not type(value) == list: raise RefpropinputError ('expect "list" input for ' + key + ' instead of "' + str(value.__class__) +'"') elif len(value) > _nmxpar: raise RefpropinputError ('input value ' + key + ' larger then max. value ' + str(_nmxpar)) elif key in checkliststring: for each in value: if type(each) == list: for other in each: if not type(other) == str: raise RefpropinputError ('expect "list of str"' + ''' or "strs's" input for ''' + str(each) + ' instead of "' + str(other.__class__) +'"') elif not type(each) == str: raise RefpropinputError ('expect "list of str" or' + ''' "strs's" input for ''' + str(each) + ' instead of "' + str(each.__class__) +'"') def normalize(x): '''Normalize the sum of list x value's to 1''' lsum = sum x = [Decimal(each) for each in x] norm = lsum(x) while float(norm) != 1: x = [each / norm for each in x] norm = lsum(x) x = [float(each) for each in x] return _prop(x = x) def getphase(fld): '''Return fluid phase input: fld--fluid dictionary containing: p--pressure t--temperature x--fluid composition q--quality (optional)* h--enthalpy (optional)* s--entropy (optional)* *one of these three needs to be included output: fluid phase: "vapor"--vapor phase "saturated vapor"--fluid at dew point "gas"--gasious phase (e.g. above critical temperature "liquid"--liquid phase "saturated liquid"--fluid at bubble point "compressible liquid"--(e.g. above critical pressure) "Supercritical fluid" "2 phase"--both liquid and vapor phase"''' _inputerrorcheck(locals()) #get critical parameters crit = critp(fld['x']) #check if fld above critical pressure if fld['p'] > crit['pcrit']: #check if fld above critical pressure if fld['t'] > crit['tcrit']: return "Supercritical fluid" else: return "compressible liquid" #check if fld above critical pressure elif fld['t'] > crit['tcrit']: return "gas" #check if ['q'] in fld if not 'q' in fld: if 'h' in fld: fld['q'] = flsh('ph', fld['p'], fld['h'], fld['x'])['q'] elif 's' in fld: fld['q'] = flsh('ps', fld['p'], fld['s'], fld['x'])['q'] #check q if fld['q'] > 1: return "vapor" elif fld['q'] == 1: return "saturated vapor" elif 0 < fld['q'] < 1: return "2 phase" elif fld['q'] == 0: return "saturated liquid" elif fld['q'] < 0: return "liquid" def fluidlib(): '''Displays all fluids and mixtures available on root directory. If root other then default directories: 'c:/program files/refprop/' 'c:/program files (x86)/refprop/' '/usr/local/lib/refprop/ call setpath to correct''' return _fluidextention() def _fluidextention(): """return fluid library""" global _fldext, _fpath if _fldext == {}: fldext = {} fluidslistdir = listdir(_fpath + 'fluids/') mixtureslistdir = listdir(_fpath + 'mixtures/') fldext[_fpath + 'fluids/'] = [(each[:-4].upper()) for each in fluidslistdir if fnmatch(each, '*.FLD')] fldext[_fpath + 'fluids/'].extend([each for each in fluidslistdir if fnmatch(each, '*.PPF')]) fldext[_fpath + 'mixtures/'] = [(each[:-4].upper()) for each in mixtureslistdir if fnmatch (each, '*.MIX')] _fldext = fldext.copy() return _fldext def resetup(prop, force=False): '''Resetup models and re-initialize arrays. This will compare the loaded models vs requested model and re-setup refprop models if deemed required in the following sequence: setmod / gerg04 setup setktv preos setaga setref purefld This enables calculating of dual fluid flows through exchangers, static mixures etc. input: props--standard dictinary output from refprop functions force--force resetup (True or False (standard input)''' global _gerg04_pre_rec, _setmod_pre_rec prop = setup_details(prop) #only resetup if loaded models are unequal to request (or force) if force == True or setup_setting() != prop: #delete any pre-setup request such as gerg04 and setmod if '_setmod_pre_rec' in _Setuprecord.object_list: _setmod_pre_rec = None if '_gerg04_pre_rec' in _Setuprecord.object_list: _gerg04_pre_rec = None #initialize setmod if deemed req. stmd = prop.get('setmod') if stmd != None: setmod(stmd['htype'], stmd['hmix'], stmd['hcomp']) #initialize gerg04 if deemed req. grg4 = prop.get('gerg04') if grg4 != None: gerg04(grg4['ixflag']) #initialize setup: hmxnme = prop.get('hmxnme') if hmxnme != None: setup(prop['hrf'], hmxnme, hfmix=prop['hfmix']) else: setup(prop['hrf'], prop['hfld'], hfmix=prop['hfmix']) #initialize setktv stktv = prop.get('setktv') if stktv != None: setktv(stktv['icomp'], stktv['jcomp'], stktv['hmodij'], stktv['fij'], stktv['hfmix']) #initialize preos prs = prop.get('preos') if prs != None: preos(prs['ixflag']) #initialize setaga stg = prop.get('setaga') if stg != None: setaga() #initialize setref strf = prop.get('setref') if strf != None: if not 'ixflag' in strf: prop['setref']['ixflag'] = 1 if not 'x0' in strf: prop['setref']['x0'] = [1] if not 'h0' in strf: prop['setref']['h0'] = 0 if not 's0' in strf: prop['setref']['s0'] = 0 if not 't0' in strf: prop['setref']['t0'] = 273 if not 'p0' in strf: prop['setref']['p0'] =100 setref(strf['hrf'][0], strf['ixflag'], strf['x0'], strf['h0'], strf['s0'], strf['t0'], strf['p0']) if len(strf['hrf']) == 2: setref(strf['hrf'][1], strf['ixflag'], strf['x0'], strf['h0'], strf['s0'], strf['t0'], strf['p0']) #initialize purefld prfld = prop.get('purefluid') if prfld != None: purefld(prfld[0]) #reset SetError if 'SetError' in prop: SetError.off() else: SetError.on() #reset SetWarning if 'SetWarning' in prop: SetWarning.off() else: SetWarning.on() #reset SetErrorDebug if 'SetDebug' in prop: SetErrorDebug.on() else: SetErrorDebug.off() #reset SetInputErrorCheck if 'SetInputErrorCheck' in prop: SetInputErrorCheck.off() else: SetInputErrorCheck.on() return setup_details(_prop()) def setup_setting(): '''Returns current loaded setup settings output--Minimized dict. with basic refprop settings''' return setup_details(_prop()) def setup_details(prop): '''Returns basic setup details of input fluid. Setup details from the following module functions: setmod / gerg04 setup setktv preos setags setref purefld input: prop--standard dictinary output from refprop functions output prop--Minimized dict. with basic refprop settings''' prps = {} if prop.__class__ == dict: #setmod if 'setmod' in prop: prps['setmod'] = prop['setmod'] #gerg04 if 'gerg04' in prop: prps['gerg04'] = prop['gerg04'] #setup if 'hrf' in prop: prps['hrf'] = prop['hrf'] if 'hfld' in prop: prps['hfld'] = prop['hfld'] if 'hfmix' in prop: prps['hfmix'] = prop['hfmix'] if 'hmxnme' in prop: prps['hmxnme'] = prop['hmxnme'] if 'nc' in prop: prps['nc'] = prop['nc'] #setktv if 'setktv' in prop: prps['setktv'] = prop['setktv'] #preos if 'preos' in prop: prps['preos'] = prop['preos'] #setaga if 'setaga' in prop: prps['setaga'] = prop['setaga'] #setref if 'setref' in prop: prps['setref'] = prop['setref'] #purefld if 'purefld' in prop: prps['purefld'] = prop['purefld'] #seterror if 'SetError' in prop: prps['SetError'] = 'off' #setwarning if 'SetWarning' in prop: prps['SetWarning'] = 'off' #seterrordebug if 'SetDebug' in prop: prps['SetDebug'] = 'on' #setinputerrorceck if 'SetInputErrorCheck' in prop: prps['SetInputErrorCheck'] = 'off' return prps def _test(): '''execute detailed test run of refprop''' import rptest rptest.settest('refprop') def test(criteria=0.00001): '''verify that the user's computer is returning proper calculations The calculated values are compared with NIST calculated values. The percent difference between Calculated and NIST should be within the acceptance criteria '0.00001' is standard. input: criteria--acceptance criteria between Calculated and NIST value output: print screen of NIST value, Calculated value, abs. difference and True / False for acceptance.''' global testresult truefalse = True testresult = '' #create def for printout def printresults(nist, calculated, truefalse): global testresult calculated = float(calculated) testresult += '\nNIST = ' + str(nist) testresult += '\nCalculated = ' + str(calculated) testresult += '\nabs relative difference = ' + str( abs((nist - calculated) / nist)) testresult += '\n' + str(abs((nist - calculated) / nist) < criteria) + '\n\n' truefalse = truefalse and abs((nist - calculated) / nist) < criteria return truefalse #SetWarning off due to many warnings displayed if str(SetWarning()) == 'off': sw = SetWarning.off elif str(SetWarning()) == 'on': sw = SetWarning.on SetWarning.off() #test no. 1 prop = setup('def', 'air') prop = wmol(prop['x']) testresult += 'check molar mass of air' truefalse = printresults(28.958600656, prop['wmix'], truefalse) #test no. 2 setup('def', 'argon') prop = flsh('pD', 2 * 1000, 15 / wmol([1])['wmix'], [1]) testresult += 'check temperature of Argon' truefalse = printresults(637.377588657857, prop['t'], truefalse) #test no. 3 setup('def', 'r134a') prop = flsh('tD', 400, 50 / wmol([1])['wmix'], [1]) testresult += 'check pressure of r134a' truefalse = printresults(1.45691892789737, prop['p'] / 1000, truefalse) ##test no. 4 #setup('def', 'ethylene') #setref(ixflag=2, x0=[1]) #wmix = wmol([1])['wmix'] #prop = flsh('ts', 300, 3 * wmix, [1]) #testresult += 'check enthalphy of ethylene' #truefalse = printresults(684.996521090598, prop['h'] / wmix, truefalse) ##NIST(as per spreadsheet) = 684.996521090598 ##Calculated(confirmed by NIST GUI) = 651.5166149584808 #test no. 5 setup('def', 'oxygen') prop = trnprp(100, tprho(100, 1 * 1000, [1], 1)['D'], [1]) testresult += 'check Viscosity of Oxygen' truefalse = printresults(153.886680663753, prop['eta'], truefalse) #test no. 6 setup('def', 'nitrogen') prop = trnprp(100, satt(100, [1], 1)['Dliq'], [1]) testresult += 'check Thermal Conductivity of Nitrogen' truefalse = printresults(100.111748964945, prop['tcx'] * 1000, truefalse) #test no. 7 setup('def', 'air') x = setup('def', 'air')['x'] setref(ixflag=2, x0=x) wmix = wmol(x)['wmix'] prop = tprho(((70 - 32) * 5 / 9) + 273.15, 14.7 / 14.50377377 * (10**5) / 1000, x) testresult += 'check Density of Air' truefalse = printresults(0.0749156384666842, prop['D'] * wmix * 0.062427974, truefalse) #test no. 8 setup('def', 'R32', 'R125') x = [0.3, 0.7] '''Use the following line to calculate enthalpies and entropies on a reference state based on the currently defined mixture, or to change to some other reference state. The routine does not have to be called, but doing so will cause calculations to be the same as those produced from the graphical interface for mixtures.''' setref(ixflag=2, x0=x) prop = flsh('ps', 10 * 1000, 110, x) testresult += 'check enthalpy of R32 / R125' truefalse = printresults(23643.993624382, prop['h'], truefalse) #test no. 9 setup('def', 'ethane', 'butane') x = xmole([0.5, 0.5])['x'] setref(ixflag=2, x0=x) wmix = wmol(x)['wmix'] prop = flsh('dh', 30 * 0.45359237 / 0.028316846592 / wmix, 283 * 1.05435026448889 / 0.45359237 * wmix, x) testresult += 'check Temperature of Ethene / Butane' truefalse = printresults(298.431320311048, ((prop['t'] - 273.15) * 9 / 5) + 32, truefalse) #test no. 10 setup('def', 'ammonia', 'water') x = [0.4, 0.6] setref(ixflag=2, x0=x) prop = flsh('tp', ((300 - 32) * 5 / 9) + 273.15, 10000 / 14.50377377 * (10**5) / 1000, x) testresult += 'check speed of Sound of Ammonia / water' truefalse = printresults(5536.79144924071, prop['w'] * 1000 / 25.4 / 12, truefalse) #test no. 11 setup('def', 'r218', 'r123') x = [0.1, 0.9] setref(ixflag=2, x0=x) wmix = wmol(x)['wmix'] prop = flsh('ph', 7 * 1000, 180 * wmix, x) testresult += 'check Density of R218 / R123' truefalse = printresults(1.60040403489036, prop['D'] * wmix / 1000, truefalse) #test no. 12 setup('def', 'methane', 'ethane') x = xmole(normalize([40, 60])['x'])['x'] wmix = wmol(x)['wmix'] prop = flsh('tD', 200, 300 / wmix, x) prop = qmass(prop['q'], prop['xliq'], prop['xvap']) testresult += 'check quality of methane / ethane' truefalse = printresults(0.0386417701326453, prop['qkg'], truefalse) #test no. 13 setup('def', 'methane', 'ethane') x = xmole(normalize([40, 60])['x'])['x'] setref(ixflag=2, x0=x) prop = flsh('tp', 200, 2.8145509 * 1000, x) prop = qmass(prop['q'], prop['xliq'], prop['xvap']) testresult += 'check quality of methane / ethane' truefalse = printresults(0.0386406167132601, prop['qkg'], truefalse) #NIST = 0.0386406167132601 #Calculated = 1.0297826927241274 #test no. 14 setup('def', 'methane', 'ethane') x = xmole(normalize([40, 60])['x'])['x'] setref(ixflag=2, x0=x) prop = flsh('tp', 200, 2814.5509, x) testresult += 'check quality of methane / ethane' truefalse = printresults(0.0500926636198064, prop['q'], truefalse) #test no. 15 setup('def', 'octane') wmix = wmol([1])['wmix'] prop = satt(100 + 273.15, [1]) Dliq = prop['Dliq'] Dvap = prop['Dvap'] prop = therm(100 + 273.15, Dliq, [1]) hliq = prop['h'] prop = therm(100 + 273.15, Dvap, [1]) hvap = prop['h'] testresult += 'check Heat of Vaporization of Octane' truefalse = printresults(319.167499870568, (hvap - hliq) / wmix, truefalse) #test no. 16 setup('def', 'butane', 'hexane') x = [0.25, 0.75] setref(ixflag=2, x0=x) testresult += 'check viscosity of Butane / Hexane' truefalse = printresults(283.724837443674, trnprp(300, flsh('th', 300, -21 * wmol(x)['wmix'], x, 2)['D'], x)['eta'], truefalse) #test no. 17 setup('def', 'CO2', 'nitrogen') x = xmole([0.5, 0.5])['x'] setref(ixflag=2, x0=x) wmix = wmol(x)['wmix'] prop = flsh('th', 250, 220 * wmix, x, 2) prop = trnprp(250, prop['D'], x) testresult += 'check Thermal Conductivity of CO2 / Nitrogen' truefalse = printresults(120.984794685581, prop['tcx'] * 1000, truefalse) #test no. 18 setup('def', 'ethane', 'propane') prop = satt(300, [0.5, 0.5]) prop = dielec(300, prop['Dvap'], [0.5, 0.5]) testresult += 'check Dielectric Constant of Ethane / Propane' truefalse = printresults(1.03705806204418, prop['de'], truefalse) #test no. 19 prop = setup('def', 'R410A') testresult += 'check Mole Fraction of R410A' truefalse = printresults(0.697614699375863, prop['x'][0], truefalse) #test no. 20 prop = xmass(prop['x']) testresult += 'check mass Fraction of R410A' truefalse = printresults(0.5, prop['xkg'][0], truefalse) #test no. 21 prop = xmole(prop['xkg']) testresult += 'check mole Fraction of R410A' truefalse = printresults(0.697614699375862, prop['x'][0], truefalse) #test no. 22 setup('def', 'Methane', 'Ethane', 'Propane', 'Butane') x = [0.7, 0.2, 0.05, 0.05] setref(ixflag=2, x0=x) wmix = wmol(x)['wmix'] prop = flsh('td', 150, 200 / wmix, x) Dliq = prop['Dliq'] wmix = wmol(prop['xliq'])['wmix'] testresult += 'check Liquid Density of Methane / Ethane / Propane / Butane' truefalse = printresults(481.276038325628, Dliq * wmix, truefalse) #restore SetWarning to original value sw() return(truefalse) def psliq(p, s, x): '''flsh1 calculations with boundery check, raise RefpropinputError when input is outside bounderies Inputs: p--pressure [kPa] s--entropy [J/(mol*K)] x--composition [array of mol frac]''' #check if input is in critical region pcrit = critp(x)['pcrit'] if p > pcrit: raise RefpropinputError('p value input is critical condition') #calculate the properties (t and D) prop = flsh1('ps', p, s, x, 1) t = prop['t'] D = prop['D'] #check if input is with liquid stage tbub = satp(p, x, 1)['t'] if t >= tbub: raise RefpropinputError('value input is not liquid condition') #check if input is with general refprop bounderies try: limitx(x, 'EOS', t, D, p) except RefpropWarning: pass #get remaining values prop = therm(t, D, x) #add q prop['q'] = -1 #correct input values prop['p'] = p prop['s'] = s #return full properties return prop def psvap(p, s, x): '''flsh1 calculations with boundery check, raise RefpropinputError when input is outside bounderies Inputs: p--pressure [kPa] s--entropy [J/(mol*K)] x--composition [array of mol frac]''' #check if input is in critical region (pressure) prop = critp(x) pcrit = prop['pcrit'] tcrit = prop['tcrit'] if p > pcrit: raise RefpropinputError('p value input is critical condition') #calculate the properties (t and D) prop = flsh1('ps', p, s, x, 2) t = prop['t'] D = prop['D'] #check if input is in critical region (temperature) if t > tcrit: raise RefpropinputError('value input is critical condition') #check if input is with gas stage tdew = satp(p, x, 2)['t'] if t <= tdew: raise RefpropinputError('value input is not gas condition') #check if input is with general refprop bounderies try: limitx(x, 'EOS', t, D, p) except RefpropWarning: pass #get values prop = therm(t, D, x) #add q prop['q'] = 2 #correct input values prop['p'] = p prop['s'] = s #return full properties return prop def ps2ph(p, s, x): '''flsh2 calculations with boundery check, raise RefpropinputError when input is outside bounderies Inputs: p--pressure [kPa] s--entropy [J/(mol*K)] x--composition [array of mol frac]''' #check if input is in critical region pcrit = critp(x)['pcrit'] if p > pcrit: raise RefpropinputError('p value input is critical condition') #calculate the properties prop = _abfl2('ps', p, s, x) D = prop['D'] t = prop['t'] Dliq = prop['Dliq'] Dvap = prop['Dvap'] q = prop['q'] xliq = prop['xliq'] xvap = prop['xvap'] #calculate properties at bubble point propliq = therm(t, Dliq, xliq) #calculate properties at cond. point propvap = therm(t, Dvap, xvap) #calculate e and h prop['e'] = (1 - q) * propliq['e'] + q * propvap['e'] prop['h'] = (1 - q) * propliq['h'] + q * propvap['h'] #check if input is within 2 phase stage tbub = prop['tbub'] tdew = prop['tdew'] if not tbub < t < tdew: raise RefpropinputError('value input is not 2-phase condition') #check if input is with general refprop bounderies try: limitx(x, 'EOS', t, D, p) except RefpropWarning: pass #return values return prop def phliq(p, h, x): '''flsh1 calculations with boundery check, raise RefpropinputError when input is outside bounderies Inputs: p--pressure [kPa] h--enthalpy [J/mol] x--composition [array of mol frac]''' #check if input is in critical region pcrit = critp(x)['pcrit'] if p > pcrit: raise RefpropinputError('p value input is critical condition') #calculate the properties (t and D) prop = flsh1('ph', p, h, x, 1) t = prop['t'] D = prop['D'] #check if input is with liquid stage tbub = satp(p, x, 1)['t'] if t >= tbub: raise RefpropinputError('value input is not liquid condition') #check if input is with general refprop bounderies try: limitx(x, 'EOS', t, D, p) except RefpropWarning: pass #get values prop = therm(t, D, x) #add q prop['q'] = -1 #correct input values prop['p'] = p prop['h'] = h #return full properties return prop def phvap(p, h, x): '''flsh1 calculations with boundery check, raise RefpropinputError when input is outside bounderies Inputs: p--pressure [kPa] h--enthalpy [J/mol] x--composition [array of mol frac]''' #check if input is in critical region (pressure) prop = critp(x) pcrit = prop['pcrit'] tcrit = prop['tcrit'] if p > pcrit: raise RefpropinputError('p value input is critical condition') #calculate the properties (t and D) prop = flsh1('ph', p, h, x, 2) t = prop['t'] D = prop['D'] #check if input is in critical region (temperature) if t > tcrit: raise RefpropinputError('value input is critical condition') #check if input is with gas stage tdew = satp(p, x, 2)['t'] if t <= tdew: raise RefpropinputError('value input is not gas condition') #check if input is with general refprop bounderies try: limitx(x, 'EOS', t, D, p) except RefpropWarning: pass #get values prop = therm(t, D, x) #add q prop['q'] = 2 #correct input values prop['p'] = p prop['h'] = h #return full properties return prop def ph2ph(p, h, x): '''flsh2 calculations with boundery check, raise RefpropinputError when input is outside bounderies Inputs: p--pressure [kPa] h--enthalpy [J/mol] x--composition [array of mol frac]''' #check if input is in critical region pcrit = critp(x)['pcrit'] if p > pcrit: raise RefpropinputError('p value input is critical condition') #calculate the properties prop = _abfl2('ph', p, h, x) D = prop['D'] t = prop['t'] Dliq = prop['Dliq'] Dvap = prop['Dvap'] q = prop['q'] xliq = prop['xliq'] xvap = prop['xvap'] #calculate properties at bubble point propliq = therm(t, Dliq, xliq) #calculate properties at cond. point propvap = therm(t, Dvap, xvap) #calculate e and h prop['e'] = (1 - q) * propliq['e'] + q * propvap['e'] prop['s'] = (1 - q) * propliq['s'] + q * propvap['s'] #check if input is within 2 phase stage tbub = prop['tbub'] tdew = prop['tdew'] if not tbub < t < tdew: raise RefpropinputError('value input is not 2-phase condition') #check if input is with general refprop bounderies try: limitx(x, 'EOS', t, D, p) except RefpropWarning: pass #return values return prop def setpath(path=None): '''Set Directory to refprop root containing fluids and mixtures. Default value = '/usr/local/lib/refprop/'. This function must be called before SETUP if path is not default. Note, all fluids and mixtures to be filed under root/fluids and root/mixtures. Input in string format. ''' global _purefld_rec, _setref_rec, _setaga_rec, _preos_rec global _gerg04_pre_rec, _gerg04_rec, _setmod_pre_rec, _setmod_rec global _setup_rec, _setktv_rec, _fixicomp, _fpath #reset fixicomp from def purefld() _fixicomp = 0 #local declaration object_list = _Setuprecord.object_list if '_purefld_rec' in object_list: _purefld_rec = None if '_setref_rec' in object_list: _setref_rec = None if '_setaga_rec' in object_list: _setaga_rec = None if '_preos_rec' in object_list: _preos_rec = None if '_setktv_rec' in object_list: _setktv_rec = None if '_gerg04_pre_rec' in object_list: _gerg04_pre_rec = None if '_gerg04_rec' in object_list: _gerg04_rec = None if '_setmod_pre_rec' in object_list: _setmod_pre_rec = None if '_setmod_rec' in object_list: _setmod_rec = None if '_setup_rec' in object_list: _setup_rec = None #load refprop path = _loadfile(path) #set global path value _fpath = path def _loadfile(fpath): global _rpsetup0_, _rpsetmod_, _rpgerg04_, _rpsetref_, _rpsetmix_, \ _rpcritp_, _rptherm_, _rptherm0_, _rpresidual_, _rptherm2_, \ _rptherm3_, _rpchempot_, _rppurefld_, _rpname_, _rpentro_, \ _rpenthal_, _rpcvcp_, _rpcvcpk_, _rpgibbs_, _rpag_, _rppress_, \ _rpdpdd_, _rpdpddk_, _rpdpdd2_, _rpdpdt_, _rpdpdtk_, _rpdddp_, \ _rpdddt_, _rpdcdt_, _rpdcdt2_, _rpdhd1_, _rpfugcof_, _rpdbdt_, \ _rpvirb_, _rpvirc_, _rpvird_, _rpvirba_, _rpvirca_, _rpsatt_, \ _rpsatp_, _rpsatd_, _rpsath_, _rpsate_, _rpsats_, _rpcsatk_, \ _rpdptsatk_, _rpcv2pk_, _rptprho_, _rptpflsh_, _rptdflsh_, \ _rpthflsh_, _rptsflsh_, _rpteflsh_, _rppdflsh_, _rpphflsh_, \ _rppsflsh_, _rppeflsh_, _rphsflsh_, _rpesflsh_, _rpdhflsh_, \ _rpdsflsh_, _rpdeflsh_, _rptqflsh_, _rppqflsh_, _rpthfl1_, \ _rptsfl1_, _rptefl1_, _rppdfl1_, _rpphfl1_, _rppsfl1_, _rppefl1_, \ _rphsfl1_, _rpdhfl1_, _rpdsfl1_, _rpdefl1_, _rptpfl2_, _rpdhfl2_, \ _rpdsfl2_, _rpdefl2_, _rpthfl2_, _rptsfl2_, _rptefl2_, _rptdfl2_, \ _rppdfl2_, _rpphfl2_, _rppsfl2_, _rppefl2_, _rptqfl2_, _rppqfl2_, \ _rpabfl2_, _rpinfo_, _rprmix2_, _rpxmass_, _rpxmole_, _rplimitx_, \ _rplimitk_, _rplimits_, _rpqmass_, _rpqmole_, _rpwmoldll_, \ _rpdielec_, _rpsurft_, _rpsurten_, _rpmeltt_, _rpmeltp_, _rpsublt_, \ _rpsublp_, _rptrnprp_, _rpgetktv_, _rpgetmod_, _rpsetktv_, \ _rpsetaga_, _rpunsetaga_, _rppreos_, _rpgetfij_, _rpb12_, \ _rpexcess_, _rpphiderv_, _rpcstar_, _rpsetpath_, _rpfgcty_, _rpfpv_ #set fpath and filename if system() == 'Linux': if fpath == None: fpath = '/usr/local/lib/refprop/' filename = fpath.rsplit('refprop/')[0] + 'librefprop.so' if not path.isfile(filename): raise RefpropError('can not find' + filename) _rp = CDLL(str(filename), mode=RTLD_GLOBAL) elif system() == 'Windows': if fpath == None: #use the standard 2 windows options fpath='c:/program files/refprop/' #test 1 try: listdir(fpath) except WindowsError: fpath='c:/program files (x86)/refprop/' #test 2 listdir(fpath) filename = fpath + 'refprop.dll' if not path.isfile(filename): raise RefpropError('can not find' + filename) _rp = windll.LoadLibrary(str(filename)) #refprop functions if system() == 'Linux': (_rpsetup0_, _rpsetmod_, _rpgerg04_, _rpsetref_, _rpsetmix_, _rpcritp_, _rptherm_, _rptherm0_, _rpresidual_, _rptherm2_, _rptherm3_, _rpchempot_, _rppurefld_, _rpname_, _rpentro_, _rpenthal_, _rpcvcp_, _rpgibbs_, _rpag_, _rppress_, _rpdpdd2_, _rpdcdt_, _rpdcdt2_, _rpdhd1_, _rpfugcof_, _rpdbdt_, _rpvirb_, _rpvirc_, _rpvird_, _rpvirba_, _rpvirca_, _rpsatt_, _rpsatp_, _rpsatd_, _rpsath_, _rpsate_, _rpsats_, _rpcsatk_, _rpdptsatk_, _rpcv2pk_, _rptprho_, _rptpflsh_, _rptdflsh_, _rpthflsh_, _rptsflsh_, _rpteflsh_, _rppdflsh_, _rpphflsh_, _rppsflsh_, _rppeflsh_, _rphsflsh_, _rpesflsh_, _rpdhflsh_, _rpdsflsh_, _rpdeflsh_, _rptqflsh_, _rppqflsh_, _rpthfl1_, _rptsfl1_, _rptefl1_, _rppdfl1_, _rpphfl1_, _rppsfl1_, _rppefl1_, _rphsfl1_, _rpdhfl1_, _rpdsfl1_, _rpdefl1_, _rptpfl2_, _rpdhfl2_, _rpdsfl2_, _rpdefl2_, _rpthfl2_, _rptsfl2_, _rptefl2_, _rptdfl2_, _rppdfl2_, _rpphfl2_, _rppsfl2_, _rppefl2_, _rptqfl2_, _rppqfl2_, _rpabfl2_, _rpinfo_, _rprmix2_, _rpxmass_, _rpxmole_, _rplimitx_, _rplimitk_, _rplimits_, _rpqmass_, _rpqmole_, _rpwmoldll_, _rpdielec_, _rpsurft_, _rpsurten_, _rpmeltt_, _rpmeltp_, _rpsublt_, _rpsublp_, _rptrnprp_, _rpgetktv_, _rpgetmod_, _rpsetktv_, _rpsetaga_, _rpunsetaga_, _rppreos_, _rpgetfij_, _rpb12_, _rpexcess_, _rpphiderv_, _rpcstar_, _rpsetpath_, _rpfgcty_, _rpfpv_) = \ (_rp.setup0_, _rp.setmod_, _rp.gerg04_, _rp.setref_, _rp.setmix_, _rp.critp_, _rp.therm_, _rp.therm0_, _rp.residual_, _rp.therm2_, _rp.therm3_, _rp.chempot_, _rp.purefld_, _rp.name_, _rp.entro_, _rp.enthal_, _rp.cvcp_, _rp.gibbs_, _rp.ag_, _rp.press_, _rp.dpdd2_, _rp.dcdt_, _rp.dcdt2_, _rp.dhd1_, _rp.fugcof_, _rp.dbdt_, _rp.virb_, _rp.virc_, _rp.vird_, _rp.virba_, _rp.virca_, _rp.satt_, _rp.satp_, _rp.satd_, _rp.sath_, _rp.sate_, _rp.sats_, _rp.csatk_, _rp.dptsatk_, _rp.cv2pk_, _rp.tprho_, _rp.tpflsh_, _rp.tdflsh_, _rp.thflsh_, _rp.tsflsh_, _rp.teflsh_, _rp.pdflsh_, _rp.phflsh_, _rp.psflsh_, _rp.peflsh_, _rp.hsflsh_, _rp.esflsh_, _rp.dhflsh_, _rp.dsflsh_, _rp.deflsh_, _rp.tqflsh_, _rp.pqflsh_, _rp.thfl1_, _rp.tsfl1_, _rp.tefl1_, _rp.pdfl1_, _rp.phfl1_, _rp.psfl1_, _rp.pefl1_, _rp.hsfl1_, _rp.dhfl1_, _rp.dsfl1_, _rp.defl1_, _rp.tpfl2_, _rp.dhfl2_, _rp.dsfl2_, _rp.defl2_, _rp.thfl2_, _rp.tsfl2_, _rp.tefl2_, _rp.tdfl2_, _rp.pdfl2_, _rp.phfl2_, _rp.psfl2_, _rp.pefl2_, _rp.tqfl2_, _rp.pqfl2_, _rp.abfl2_, _rp.info_, _rp.rmix2_, _rp.xmass_, _rp.xmole_, _rp.limitx_, _rp.limitk_, _rp.limits_, _rp.qmass_, _rp.qmole_, _rp.wmoldll_, _rp.dielec_, _rp.surft_, _rp.surten_, _rp.meltt_, _rp.meltp_, _rp.sublt_, _rp.sublp_, _rp.trnprp_, _rp.getktv_, _rp.getmod_, _rp.setktv_, _rp.setaga_, _rp.unsetaga_, _rp.preos_, _rp.getfij_, _rp.b12_, _rp.excess_, _rp.phiderv_, _rp.cstar_, _rp.setpath_, _rp.fgcty_, _rp.fpv_) elif system() == 'Windows': (_rpsetup0_, _rpsetmod_, _rpgerg04_, _rpsetref_, _rpsetmix_, _rpcritp_, _rptherm_, _rptherm0_, _rpresidual_, _rptherm2_, _rptherm3_, _rpchempot_, _rppurefld_, _rpname_, _rpentro_, _rpenthal_, _rpcvcp_, _rpcvcpk_, _rpgibbs_, _rpag_, _rppress_, _rpdpdd_, _rpdpddk_, _rpdpdd2_, _rpdpdt_, _rpdpdtk_, _rpdddp_, _rpdddt_, _rpdhd1_, _rpfugcof_, _rpdbdt_, _rpvirb_, _rpvirc_, _rpvirba_, _rpvirca_, _rpsatt_, _rpsatp_, _rpsatd_, _rpsath_, _rpsate_, _rpsats_, _rpcsatk_, _rpdptsatk_, _rpcv2pk_, _rptprho_, _rptpflsh_, _rptdflsh_, _rpthflsh_, _rptsflsh_, _rpteflsh_, _rppdflsh_, _rpphflsh_, _rppsflsh_, _rppeflsh_, _rphsflsh_, _rpesflsh_, _rpdhflsh_, _rpdsflsh_, _rpdeflsh_, _rptqflsh_, _rppqflsh_, _rppdfl1_, _rpphfl1_, _rppsfl1_, _rpinfo_, _rpxmass_, _rpxmole_, _rplimitx_, _rplimitk_, _rplimits_, _rpqmass_, _rpqmole_, _rpwmoldll_, _rpdielec_, _rpsurft_, _rpsurten_, _rpmeltt_, _rpmeltp_, _rpsublt_, _rpsublp_, _rptrnprp_, _rpgetktv_, _rpsetktv_, _rpsetaga_, _rpunsetaga_, _rppreos_, _rpgetfij_, _rpb12_, _rpcstar_, _rpsetpath_, _rpfgcty_, _rpfpv_) = \ (_rp.SETUPdll, _rp.SETMODdll, _rp.GERG04dll, _rp.SETREFdll, _rp.SETMIXdll, _rp.CRITPdll, _rp.THERMdll, _rp.THERM0dll, _rp.RESIDUALdll, _rp.THERM2dll, _rp.THERM3dll, _rp.CHEMPOTdll, _rp.PUREFLDdll, _rp.NAMEdll, _rp.ENTROdll, _rp.ENTHALdll, _rp.CVCPdll, _rp.CVCPKdll, _rp.GIBBSdll, _rp.AGdll, _rp.PRESSdll, _rp.DPDDdll, _rp.DPDDKdll, _rp.DPDD2dll, _rp.DPDTdll, _rp.DPDTKdll, _rp.DDDPdll, _rp.DDDTdll, _rp.DHD1dll, _rp.FUGCOFdll, _rp.DBDTdll, _rp.VIRBdll, _rp.VIRCdll, _rp.VIRBAdll, _rp.VIRCAdll, _rp.SATTdll, _rp.SATPdll, _rp.SATDdll, _rp.SATHdll, _rp.SATEdll, _rp.SATSdll, _rp.CSATKdll, _rp.DPTSATKdll, _rp.CV2PKdll, _rp.TPRHOdll, _rp.TPFLSHdll, _rp.TDFLSHdll, _rp.THFLSHdll, _rp.TSFLSHdll, _rp.TEFLSHdll, _rp.PDFLSHdll, _rp.PHFLSHdll, _rp.PSFLSHdll, _rp.PEFLSHdll, _rp.HSFLSHdll, _rp.ESFLSHdll, _rp.DHFLSHdll, _rp.DSFLSHdll, _rp.DEFLSHdll, _rp.TQFLSHdll, _rp.PQFLSHdll, _rp.PDFL1dll, _rp.PHFL1dll, _rp.PSFL1dll, _rp.INFOdll, _rp.XMASSdll, _rp.XMOLEdll, _rp.LIMITXdll, _rp.LIMITKdll, _rp.LIMITSdll, _rp.QMASSdll, _rp.QMOLEdll, _rp.WMOLdll, _rp.DIELECdll, _rp.SURFTdll, _rp.SURTENdll, _rp.MELTTdll, _rp.MELTPdll, _rp.SUBLTdll, _rp.SUBLPdll, _rp.TRNPRPdll, _rp.GETKTVdll, _rp.SETKTVdll, _rp.SETAGAdll, _rp.UNSETAGAdll, _rp.PREOSdll, _rp.GETFIJdll, _rp.B12dll, _rp.CSTARdll, _rp.SETPATHdll, _rp.FGCTYdll, _rp.FPVdll) #set path for refprop _hpth.value = fpath.encode('ascii') _rpsetpath_(byref(_hpth), c_long(255)) return fpath #REFPROP functions def setup(hrf, *hfld, hfmix='HMX.BNC'): '''Define models and initialize arrays. A call to this routine is required. Inputs 'in string format': hrf - reference state for thermodynamic calculations 'def' : Default reference state as specified in fluid file is applied to each pure component. 'nbs' : h,s = 0 at pure component normal boiling point(s). 'ash' : h,s = 0 for sat liquid at -40 C (ASHRAE convention) 'iir' : h = 200, s = 1.0 for sat liq at 0 C (IIR convention) Other choises are possible but require a separate call to SETREF *hfld - file names specifying fluid mixture components select from user fluid.FLD and mixture.MIX files at root directory input without extention. Pseudo-Pure Fluids (PPF) files are required to have the extention included hfmix--file name [character*255] containing parameters for the binary mixture model''' global _nc_rec, _fpath, _gerg04_pre_rec, _setmod_pre_rec, _setup_rec global _setmod_rec, _gerg04_rec, _setref_rec, _purefld_rec, _setktv_rec global _setaga_rec, _preos_rec, _setupprop _inputerrorcheck(locals()) #define setup record for Fluidmodel _setup_rec = _Setuprecord(copy(locals()), '_setup_rec') #empty global setup storage for new population _setupprop = {} #load refprop shared library if _fpath == '': setpath() fluidname = '' listhfld = [] #create listing of input *hfld (in either list format or *arg string format) for each in hfld: if each.__class__ is list: for other in each: listhfld.append(other.upper()) elif each.__class__ is str: listhfld.append(each.upper()) #create RP input format with file directory structure and file extention for each in listhfld: if _fluidextention()[_fpath + 'fluids/'].__contains__(each): if each[-4:] == '.PPF': fluidname += _fpath + 'fluids/' + each + '|' else: fluidname += _fpath + 'fluids/' + each + '.FLD|' elif _fluidextention()[_fpath + 'mixtures/'].__contains__(each): fluidname += _fpath + 'mixtures/' + each + '.MIX|' nc = len(listhfld) _nc_rec = _Setuprecord(nc, '_nc_rec') if '_preos_rec' in _Setuprecord.object_list: _preos_rec = None if '_setaga_rec' in _Setuprecord.object_list: _setaga_rec = None if '_setref_rec' in _Setuprecord.object_list: _setref_rec = None if '_setktv_rec' in _Setuprecord.object_list: _setktv_rec = None if '_purefld_rec' in _Setuprecord.object_list: _purefld_rec = None #determine if SETMOD needs to be called if '_setmod_pre_rec' in _Setuprecord.object_list: #call setmod ierr, herr = _setmod(nc, _setmod_pre_rec.record['htype'], _setmod_pre_rec.record['hmix'], _setmod_pre_rec.record['hcomp']) _prop(ierr = ierr, herr = herr, defname = '_setmod') #reset SETMOD from record elif '_setmod_rec' in _Setuprecord.object_list: _setmod_rec = None #determine if GERG04 needs to be called if '_gerg04_pre_rec' in _Setuprecord.object_list: ierr, herr = _gerg04(nc, _gerg04_pre_rec.record['ixflag']) _prop(ierr = ierr, herr = herr, defname = '_gerg04') #reset GERG04 from record elif '_gerg04_rec' in _Setuprecord.object_list: _gerg04_rec = None #determine standard mix (handled by setmix) or user defined mixture #(handled by setupdll) if fluidname.__contains__('.MIX|'): if len(listhfld) > 1: raise RefpropinputError ('too many standard mixture input, ' + 'can only select one') for item in listhfld: mix = str(item) return _setmix(mix, hrf, hfmix) else: if 'hmxnme' in _setupprop: _setupprop.__delitem__('hmxnme') _setupprop['hfld'], _setupprop['nc'] = listhfld, nc _setupprop['hrf'], _setupprop['hfmix'] = hrf.upper(), hfmix return _setup0(nc, fluidname, hfmix, hrf) def setmod(htype='NBS', hmix='NBS', *hcomp): '''Set model(s) other than the NIST-recommended ('NBS') ones. This subroutine must be called before SETUP; it need not be called at all if the default (NIST-recommended) models are desired. inputs 'in string format': htype - flag indicating which models are to be set [character*3]: 'EOS': equation of state for thermodynamic properties 'ETA': viscosity 'TCX': thermal conductivity 'STN': surface tension 'NBS': reset all of the above model types and all subsidiary component models to 'NBS'; values of hmix and hcomp are ignored hmix--mixture model to use for the property specified in htype [character*3]: ignored if number of components = 1 some allowable choices for hmix: 'NBS': use NIST recommendation for specified fluid/mixture 'HMX': mixture Helmholtz model for thermodynamic properties 'ECS': extended corresponding states for viscosity or therm. cond. 'STX': surface tension mixture model hcomp--component model(s) to use for property specified in htype [array (1..nc) of character*3]: 'NBS': NIST recommendation for specified fluid/mixture some allowable choices for an equation of state: 'FEQ': Helmholtz free energy model 'BWR': pure fluid modified Benedict-Webb-Rubin (MBWR) 'ECS': pure fluid thermo extended corresponding states some allowable choices for viscosity: 'ECS': extended corresponding states (all fluids) 'VS1': the 'composite' model for R134a, R152a, NH3, etc. 'VS2': Younglove-Ely model for hydrocarbons 'VS4': Generalized friction theory of Quinones-Cisneros and Deiters 'VS5': Chung et al. (1988) predictive model some allowable choices for thermal conductivity: 'ECS': extended corresponding states (all fluids) 'TC1': the 'composite' model for R134a, R152a, etc. 'TC2': Younglove-Ely model for hydrocarbons 'TC5': Chung et al. (1988) predictive model some allowable choices for surface tension: 'ST1': surface tension as f(tau); tau = 1 - T/Tc''' global _setmod_pre_rec _inputerrorcheck(locals()) #hcomp correction #no input for hcomp if len(hcomp) == 0: hcomp = [] #list input for hcomp elif hcomp[0].__class__ is list: hcomp = hcomp[0] #str's input for hcomp else: hcomp = [each for each in hcomp] #define setup record for FluidModel _setmod_pre_rec = _Setuprecord(copy(locals()), '_setmod_pre_rec') def gerg04(ixflag=0): '''set the pure model(s) to those used by the GERG 2004 formulation. This subroutine must be called before SETUP; it need not be called at all if the default (NIST-recommended) models are desired. To turn off the GERG settings, call this routine again with iflag=0, and then call the SETUP routine to reset the parameters of the equations of state. inputs: ixflag--set to 1 to load the GERG 2004 equations, set to 0 for defaults''' global _gerg04_pre_rec _inputerrorcheck(locals()) _gerg04_pre_rec = _Setuprecord(copy(locals()), '_gerg04_pre_rec') if not (ixflag == 0 or ixflag == 1): raise RefpropinputError('ixflag value for function "gerg04" ' + 'should either be 0 (default) or 1') #refprop functions def _setup0(nc, fluidname, hfmix, hrf): global _fpath _nc.value = nc _hfld.value = fluidname.encode('ascii') if hfmix == 'HMX.BNC': _hfmix.value = (_fpath + 'fluids/HMX.BNC').encode('ascii') else: _hfmix.value = hfmix.encode('ascii') _hrf.value = hrf.upper().encode('ascii') _rpsetup0_(byref(_nc), byref(_hfld), byref(_hfmix), byref(_hrf), byref(_ierr), byref(_herr), c_long(10000), c_long(255), c_long(3), c_long(255)) return _prop(ierr = _ierr.value, herr = _herr.value, defname = '_setup0') def _setmod(nc, htype, hmix, hcomp): global _setmod_rec, _setmod_pre_rec, _setupprop #verify multiple model calls _checksetupmodel('setmod') #define setup record for FluidModel if '_setmod_pre_rec' in _Setuprecord.object_list: if htype.upper() == 'NBS': if '_setmod_rec' in _Setuprecord.object_list: _setmod_rec = None if 'setmod' in _setupprop: _setupprop.__delitem__('setmod') else: _setmod_rec = _Setuprecord(_setmod_pre_rec.record, '_setmod_rec') if nc == 1: _setmod_rec.record.__delitem__('hmix') _setupprop['setmod'] = _setmod_rec.record _setmod_pre_rec = None _nc.value = nc _htype.value = htype.encode('ascii') _hmix.value = hmix.encode('ascii') for each in range(len(hcomp)): _hcomp[each].value = hcomp[each].encode('ascii') _rpsetmod_(byref(_nc), byref(_htype), byref(_hmix), byref(_hcomp), byref(_ierr), byref(_herr), c_long(3), c_long(3), c_long(3), c_long(255)) return _ierr.value, _herr.value def _gerg04(nc, ixflag): global _gerg04_rec, _gerg04_pre_rec, _setupprop #verify multiple model calls _checksetupmodel('gerg04') #define setup record for FluidModel if '_gerg04_pre_rec' in _Setuprecord.object_list: if ixflag == 1: _gerg04_rec = _Setuprecord(_gerg04_pre_rec.record, '_gerg04_rec') _setupprop['gerg04'] = _gerg04_pre_rec.record if ixflag == 0: if '_gerg04_rec' in _Setuprecord.object_list: _gerg04_rec = None if 'gerg04' in _setupprop: _setupprop.__delitem__('gerg04') _gerg04_pre_rec = None if ixflag == 1: _nc.value = nc _ixflag.value = ixflag _rpgerg04_(byref(_nc), byref(_ixflag), byref(_ierr), byref(_herr), c_long(255)) return _ierr.value, _herr.value #system tweak as refprop call gerg04(ixflag=0) does not reset properly elif ixflag == 0: return 0, '' def setref(hrf='DEF', ixflag=1, x0=[1], h0=0, s0=0, t0=273, p0=100): '''set reference state enthalpy and entropy This subroutine must be called after SETUP; it need not be called at all if the reference state specified in the call to SETUP is to be used. inputs: hrf--reference state for thermodynamic calculations [character*3] 'NBP': h,s = 0 at normal boiling point(s) 'ASH': h,s = 0 for sat liquid at -40 C (ASHRAE convention) 'IIR': h = 200, s = 1.0 for sat liq at 0 C (IIR convention) 'DEF': default reference state as specified in fluid file is applied to each component (ixflag = 1 is used) 'OTH': other, as specified by h0, s0, t0, p0 (real gas state) 'OT0': other, as specified by h0, s0, t0, p0 (ideal gas state) '???': change hrf to the current reference state and exit. ixflag--composition flag: 1 = ref state applied to pure components 2 = ref state applied to mixture icomp following input has meaning only if ixflag = 2 x0--composition for which h0, s0 apply; list(1:nc) [mol frac] this is useful for mixtures of a predefined composition, e.g. refrigerant blends such as R410A following inputs have meaning only if hrf = 'OTH' h0--reference state enthalpy at t0,p0 {icomp} [J/mol] s0--reference state entropy at t0,p0 {icomp} [J/mol-K] t0--reference state temperature [K] t0 = -1 indicates saturated liquid at normal boiling point (bubble point for a mixture) p0--reference state pressure [kPa] p0 = -1 indicates saturated liquid at t0 {and icomp} p0 = -2 indicates saturated vapor at t0 {and icomp}''' _inputerrorcheck(locals()) global _setref_rec, _setupprop #define setup record for FluidModel if hrf.upper() != 'DEF': _setref_rec = _Setuprecord(copy(locals()), '_setref_rec') elif 'setref_rec' in _Setuprecord.object_list: _setref_rec = None for each in range(_maxcomps): _x0[each] = 0 for each in range(len(x0)): _x0[each] = x0[each] _hrf.value = hrf.upper().encode('ascii') _ixflag.value = ixflag _h0.value, _s0.value, _t0.value, _p0.value = h0, s0, t0, p0 _rpsetref_(byref(_hrf), byref(_ixflag), byref(_x0), byref(_h0), byref(_s0), byref(_t0), byref(_p0), byref(_ierr), byref(_herr), c_long(3), c_long(255)) if (hrf.upper() != 'DEF' and hrf.upper() != 'NBP' and hrf.upper() != 'ASH' and hrf.upper() != 'IIR'): href = {} if hrf == '???': href['hrf'] = [_setupprop['setref']['hrf'][0], hrf] if 'ixflag' in _setupprop['setref']: href['ixflag'] = _setupprop['setref']['ixflag'] if 'x' in _setupprop['setref']: href['x0'] = _setupprop['setref']['x0'] if 'h0' in _setupprop['setref']: href['h0'] = _setupprop['setref']['h0'] if 's0' in _setupprop['setref']: href['s0'] = _setupprop['setref']['s0'] if 't0' in _setupprop['setref']: href['t0'] = _setupprop['setref']['t0'] if 'p0' in _setupprop['setref']: href['p0'] = _setupprop['setref']['p0'] else: href['hrf'] = [hrf.upper()] href['ixflag'] = ixflag if ixflag == 2: href['x0'] = x0 if hrf.upper() == 'OTH': href['h0'] = h0 href['s0'] = s0 href['t0'] = t0 href['p0'] = p0 _setupprop['setref'] = href elif hrf.upper() != 'DEF': _setupprop['setref'] = {'hrf':[hrf.upper()]} else: if 'setref' in _setupprop: _setupprop.__delitem__('setref') return _prop(ierr = _ierr.value, herr = _herr.value, defname = 'setref') def _setmix(hmxnme, hrf, hfmix): global _nc_rec, _setupprop _inputerrorcheck(locals()) _hmxnme.value = (hmxnme + '.MIX').encode('ascii') _hfmix.value = hfmix.encode('ascii') _hrf.value = hrf.upper().encode('ascii') _rpsetmix_(byref(_hmxnme), byref(_hfmix), byref(_hrf), byref(_nc), byref(_hfld), _x, byref(_ierr), byref(_herr), c_long(255), c_long(255), c_long(3), c_long(10000), c_long(255)) hfld = [] _nc_rec = _Setuprecord(_nc.value, '_nc_rec') for each in range(_nc.value): hfld.append(_name(each + 1)) x = normalize([_x[each] for each in range(_nc.value)])['x'] _setupprop['hmxnme'], _setupprop['hrf'] = hmxnme, hrf.upper() _setupprop['nc'], _setupprop['hfld'] = _nc.value, hfld _setupprop['hfmix'] = hfmix return _prop(x = x, ierr = _ierr.value, herr = _herr.value, defname = 'setmix') def critp(x): '''critical parameters as a function of composition input: x--composition [list of mol frac] outputs: tcrit--critical temperature [K] pcrit--critical pressure [kPa] Dcrit--critical density [mol/L]''' _inputerrorcheck(locals()) for each in range(len(x)): _x[each] = x[each] _rpcritp_(_x, byref(_tcrit), byref(_pcrit), byref(_Dcrit), byref(_ierr), byref(_herr), c_long(255)) return _prop(x = x, tcrit = _tcrit.value, pcrit = _pcrit.value, Dcrit = _Dcrit.value, ierr = _ierr.value, herr = _herr.value, defname = 'critp') def therm(t, D, x): '''Compute thermal quantities as a function of temperature, density and compositions using core functions (Helmholtz free energy, ideal gas heat capacity and various derivatives and integrals). Based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994, Appendix A for pressure-explicit equations (e.g. MBWR) and c Baehr & Tillner-Roth, Thermodynamic Properties of Environmentally Acceptable Refrigerants, Berlin: Springer-Verlag (1995) for Helmholtz-explicit equations (e.g. FEQ). inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: p--pressure [kPa] e--internal energy [J/mol] h--enthalpy [J/mol] s--entropy [J/mol-K] cv--isochoric heat capacity [J/mol-K] cp--isobaric heat capacity [J/mol-K] w--speed of sound [m/s] hjt--isenthalpic Joule-Thompson coefficient [K/kPa]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rptherm_(byref(_t), byref(_D), _x, byref(_p), byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_hjt)) return _prop(x = x, D = D, t = t, p = _p.value, e = _e.value, h = _h.value, s = _s.value, cv = _cv.value, cp = _cp.value, w = _w.value, hjt = _hjt.value) def therm0(t, D, x): '''Compute ideal gas thermal quantities as a function of temperature, density and compositions using core functions. This routine is the same as THERM, except it only calculates ideal gas properties (Z=1) at any temperature and density inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: p--pressure [kPa] e--internal energy [J/mol] h--enthalpy [J/mol] s--entropy [J/mol-K] cv--isochoric heat capacity [J/mol-K] cp--isobaric heat capacity [J/mol-K] w--speed of sound [m/s] A--Helmholtz energy [J/mol] G--Gibbs free energy [J/mol]''' _inputerrorcheck(locals()) _t.value = t _D.value = D for each in range(len(x)): _x[each] = x[each] _rptherm0_(byref(_t), byref(_D), _x, byref(_p), byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_A), byref(_G)) return _prop(x = x, D = D, t = t, p = _p.value, e = _e.value, h = _h.value, s = _s.value, cv = _cv.value, cp = _cp.value, w = _w.value, A = _A.value, G = _G.value) def residual (t, D, x): '''compute the residual quantities as a function of temperature, density, and compositions (where the residual is the property minus the ideal gas portion). inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: pr--residual pressure [kPa] (p-rho*R*T) er--residual internal energy [J/mol] hr--residual enthalpy [J/mol] sr--residual entropy [J/mol-K] Cvr--residual isochoric heat capacity [J/mol-K] Cpr--residual isobaric heat capacity [J/mol-K] Ar--residual Helmholtz energy [J/mol] Gr--residual Gibbs free energy [J/mol]''' _inputerrorcheck(locals()) _t.value = t _D.value = D for each in range(len(x)): _x[each] = x[each] _rpresidual_(byref(_t), byref(_D), _x, byref(_pr), byref(_er), byref(_hr), byref(_sr), byref(_cvr), byref(_cpr), byref(_Ar), byref(_Gr)) return _prop(x = x, D = D, t = t, pr = _pr.value, er = _er.value, hr = _hr.value, sr = _sr.value, cvr = _cvr.value, cpr = _cpr.value, Ar = _Ar.value, Gr = _Gr.value) def therm2(t, D, x): '''Compute thermal quantities as a function of temperature, density and compositions using core functions (Helmholtz free energy, ideal gas heat capacity and various derivatives and integrals). This routine is the same as THERM, except that additional properties are calculated inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: p--pressure [kPa] e--internal energy [J/mol] h--enthalpy [J/mol] s--entropy [J/mol-K] cv--isochoric heat capacity [J/mol-K] cp--isobaric heat capacity [J/mol-K] w--speed of sound [m/s] Z--compressibility factor (= PV/RT) [dimensionless] hjt--isenthalpic Joule-Thompson coefficient [K/kPa] A--Helmholtz energy [J/mol] G--Gibbs free energy [J/mol] xkappa--isothermal compressibility (= -1/V dV/dp = 1/D dD/dp) [1/kPa] beta--volume expansivity (= 1/V dV/dt = -1/D dD/dt) [1/K] dpdD--derivative dP/dD [kPa-L/mol] d2pdD2--derivative d^2p/dD^2 [kPa-L^2/mol^2] dpdt--derivative dp/dt [kPa/K] dDdt--derivative dD/dt [mol/(L-K)] dDdp--derivative dD/dp [mol/(L-kPa)] spare1 to 4--space holders for possible future properties''' _inputerrorcheck(locals()) _t.value = t _D.value = D for each in range(len(x)): _x[each] = x[each] _rptherm2_(byref(_t), byref(_D), _x, byref(_p), byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_Z), byref(_hjt), byref(_A), byref(_G), byref(_xkappa), byref(_beta), byref(_dpdD), byref(_d2pdD2), byref(_dpdt), byref(_dDdt), byref(_dDdp), byref(_spare1), byref(_spare2), byref(_spare3), byref(_spare4)) return _prop(x = x, D = D, t = t, p = _p.value, e = _e.value, h = _h.value, s = _s.value, cv = _cv.value, cp = _cp.value, w = _w.value, Z = _Z.value, hjt = _hjt.value, A = _A.value, G = _G.value, xkappa = _xkappa.value, beta = _beta.value, dpdD = _dpdD.value, d2pdD2 = _d2pdD2.value, dpdt = _dpdt.value, dDdt = _dDdt.value, dDdp = _dDdp.value) def therm3(t, D, x): '''Compute miscellaneous thermodynamic properties inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: xkappa--Isothermal compressibility beta--Volume expansivity xisenk--Isentropic expansion coefficient xkt--Isothermal expansion coefficient betas--Adiabatic compressibility bs--Adiabatic bulk modulus xkkt--Isothermal bulk modulus thrott--Isothermal throttling coefficient pint--Internal pressure spht--Specific heat input''' _inputerrorcheck(locals()) _t.value = t _D.value = D for each in range(len(x)): _x[each] = x[each] _rptherm3_(byref(_t), byref(_D), _x, byref(_xkappa), byref(_beta), byref(_xisenk), byref(_xkt), byref(_betas), byref(_bs), byref(_xkkt), byref(_thrott), byref(_pint), byref(_spht)) return _prop(x = x, D = D, t = t, xkappa = _xkappa.value, beta = _beta.value, xisenk = _xisenk.value, xkt = _xkt.value, betas = _betas.value, bs = _bs.value, xkkt = _xkkt.value, thrott = _thrott.value, pint = _pint.value, spht = _spht.value) def fpv(t, D, p, x): '''Compute the supercompressibility factor, Fpv. inputs: t--temperature [K] D--molar density [mol/L] p--pressure [kPa] x--composition [array of mol frac] outputs: Fpv--sqrt[Z(60 F, 14.73 psia)/Z(T,P)].''' #odd either t, d or t, p should be sufficient? _inputerrorcheck(locals()) _t.value = t _D.value = D _p.value = p for each in range(len(x)): _x[each] = x[each] _rpfpv_(byref(_t), byref(_D), byref(_p), _x, byref(_Fpv)) return _prop(x = x, D = D, t = t, p = p, Fpv = _Fpv.value) def chempot(t, D, x): '''Compute the chemical potentials for each of the nc components of a mixture inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: u--array (1..nc) of the chemical potentials [J/mol].''' _inputerrorcheck(locals()) _t.value = t _D.value = D for each in range(len(x)): _x[each] = x[each] _rpchempot_(byref(_t), byref(_D), _x, _u, byref(_ierr), byref(_herr), c_long(255)) return _prop(x = x, D = D, t = t, ierr = _ierr.value, herr = _herr.value, u = [_u[each] for each in range(_nc_rec.record)], defname = 'chempot') def purefld(icomp=0): '''Change the standard mixture setup so that the properties of one fluid can be calculated as if SETUP had been called for a pure fluid. Calling this routine will disable all mixture calculations. To reset the mixture setup, call this routine with icomp=0. inputs: icomp--fluid number in a mixture to use as a pure fluid''' global _purefld_rec _inputerrorcheck(locals()) #define setup record for FluidModel if icomp != 0: _purefld_rec = _Setuprecord(copy(locals()), '_purefld_rec') else: #del record if '_purefld_rec' in _Setuprecord.object_list: _purefld_rec = None _icomp.value = icomp _rppurefld_(byref(_icomp)) return _prop(fixicomp = icomp) def _name(icomp=1): _inputerrorcheck(locals()) _icomp.value = icomp _rpname_(byref(_icomp), byref(_hname), byref(_hn80), byref(_hcas), c_long(12), c_long(80), c_long(12)) return _hname.value.decode('utf-8').strip().upper() def name(icomp=1): '''Provides name information for specified component input: icomp--component number in mixture; 1 for pure fluid outputs: hname--component name [character*12] hn80--component name--long form [character*80] hcas--CAS (Chemical Abstracts Service) number [character*12]''' _inputerrorcheck(locals()) _icomp.value = icomp _rpname_(byref(_icomp), byref(_hname), byref(_hn80), byref(_hcas), c_long(12), c_long(80), c_long(12)) return _prop(icomp = icomp, hname = _hname.value.decode('utf-8').strip().upper(), hn80 = _hn80.value.decode('utf-8').strip().upper(), hcas = _hcas.value.decode('utf-8').strip().upper()) def entro(t, D, x): '''Compute entropy as a function of temperature, density and composition using core functions (temperature derivative of Helmholtz free energy and ideal gas integrals) based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994, equations A5, A19 - A26 inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: s--entropy [J/mol-K]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpentro_(byref(_t), byref(_D), _x, byref(_s)) return _prop(x = x, D = D, t = t, s = _s.value) def enthal(t, D, x): '''Compute enthalpy as a function of temperature, density, and composition using core functions (Helmholtz free energy and ideal gas integrals) based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994, equations A7, A18, A19 inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: h--enthalpy [J/mol]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpenthal_(byref(_t), byref(_D), _x, byref(_h)) return _prop(x = x, D = D, t = t, h = _h.value) def cvcp(t, D, x): '''Compute isochoric (constant volume) and isobaric (constant pressure) heat capacity as functions of temperature, density, and composition using core functions based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994, equation A15, A16 inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: cv--isochoric heat capacity [J/mol-K] cp--isobaric heat capacity [J/mol-K]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpcvcp_(byref(_t), byref(_D), _x, byref(_cv), byref(_cp)) return _prop(x = x, D = D, t = t, cv = _cv.value, cp = _cp.value) def cvcpk(icomp, t, D): '''Compute isochoric (constant volume) and isobaric (constant pressure) heat capacity as functions of temperature for a given component. analogous to CVCP, except for component icomp, this is used by transport routines to calculate Cv & Cp for the reference fluid (component zero) inputs: icomp--component number in mixture (1..nc); 1 for pure fluid t--temperature [K] D--molar density [mol/L] outputs: cv--isochoric heat capacity [J/mol-K] cp--isobaric heat capacity [J/mol-K]''' _inputerrorcheck(locals()) _icomp.value, _t.value, _D.value = icomp, t, D _rpcvcpk_(byref(_icomp), byref(_t), byref(_D), byref(_cv), byref(_cp)) return _prop(icomp = icomp, D = D, t = t, cv = _cv.value, cp = _cp.value) def gibbs(t, D, x): '''Compute residual Helmholtz and Gibbs free energy as a function of temperature, density, and composition using core functions N.B. The quantity calculated is G(T, D) - G0(T, P*) = G(T, D) - G0(T, D) + RTln(RTD/P*) where G0 is the ideal gas state and P* is a reference pressure which is equal to the current pressure of interest. Since Gr is used only as a difference in phase equilibria calculations where the temperature and pressure of the phases are equal, the (RT/P*) part of the log term will cancel and is omitted. "normal" (not residual) A and G are computed by subroutine AG based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994, equations A8 - A12 inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: Ar--residual Helmholtz free energy [J/mol] Gr--residual Gibbs free energy [J/mol]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpgibbs_(byref(_t), byref(_D), _x, byref(_Ar), byref(_Gr)) return _prop(x = x, D = D, t = t, Ar = _Ar.value, Gr = _Gr.value) def ag(t, D, x): '''Ccompute Helmholtz and Gibbs energies as a function of temperature, density, and composition. N.B. These are not residual values (those are calculated by GIBBS). inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: A--Helmholtz energy [J/mol] G--Gibbs free energy [J/mol]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpag_(byref(_t), byref(_D), _x, byref(_A), byref(_G)) return _prop(x = x, D = D, t = t, A = _A.value, G = _G.value) def press(t, D, x): '''Compute pressure as a function of temperature, density, and composition using core functions direct implementation of core function of corresponding model inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: p--pressure [kPa]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rppress_(byref(_t), byref(_D), _x, byref(_p)) return _prop(x = x, D = D, t = t, p = _p.value) def dpdd(t, D, x): '''Compute partial derivative of pressure w.r.t. density at constant temperature as a function of temperature, density, and composition inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: dpdD--dP/dD [kPa-L/mol]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpdpdd_(byref(_t), byref(_D), _x, byref(_dpdD)) return _prop(x = x, D = D, t = t, dpdD = _dpdD.value) def dpddk(icomp, t, D): '''Compute partial derivative of pressure w.r.t. density at constant temperature as a function of temperature and density for a specified component analogous to dpdd, except for component icomp, this is used by transport routines to calculate dP/dD for the reference fluid (component zero) inputs: icomp--component number in mixture (1..nc); 1 for pure fluid t--temperature [K] D--molar density [mol/L] output: dpdD--dP/dD [kPa-L/mol]''' _inputerrorcheck(locals()) _icomp.value, _t.value, _D.value = icomp, t, D _rpdpddk_(byref(_icomp), byref(_t), byref(_D), byref(_dpdD)) return _prop(icomp = icomp, D = D, t = t, cv = _dpdD.value) def dpdd2(t, D, x): '''Compute second partial derivative of pressure w.r.t. density at const. temperature as a function of temperature, density, and composition. inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: d2pdD2--d^2P/dD^2 [kPa-L^2/mol^2]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpdpdd2_(byref(_t), byref(_D), _x, byref(_d2pdD2)) return _prop(x = x, D = D, t = t, d2pdD2 = _d2pdD2.value) def dpdt(t, D, x): '''Compute partial derivative of pressure w.r.t. temperature at constant density as a function of temperature, density, and composition. inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: dpdt--dp/dt [kPa/K]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpdpdt_(byref(_t), byref(_D), _x, byref(_dpdt)) return _prop(x = x, D = D, t = t, dpt = _dpdt.value) def dpdtk(icomp, t, D): '''Compute partial derivative of pressure w.r.t. temperature at constant density as a function of temperature and density for a specified component analogous to dpdt, except for component icomp, this is used by transport routines to calculate dP/dT inputs: icomp--component number in mixture (1..nc); 1 for pure fluid t--temperature [K] D--molar density [mol/L] output: dpdt--dP/dT [kPa/K]''' _inputerrorcheck(locals()) _icomp.value, _t.value, _D.value = icomp, t, D _rpdpdtk_(byref(_icomp), byref(_t), byref(_D), byref(_dpdt)) return _prop(icomp = icomp, D = D, t = t, dpdt = _dpdt.value) def dddp(t, D, x): '''ompute partial derivative of density w.r.t. pressure at constant temperature as a function of temperature, density, and composition. inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: dDdp--dD/dP [mol/(L-kPa)]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpdddp_(byref(_t), byref(_D), _x, byref(_dDdp)) return _prop(x = x, D = D, t = t, dDdp = _dDdp.value) def dddt(t, D, x): '''Compute partial derivative of density w.r.t. temperature at constant pressure as a function of temperature, density, and composition. inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: dDdt--dD/dT [mol/(L-K)]; (D)/d(t) = -d(D)/dp x dp/dt = -dp/dt / (dp/d(D))''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpdddt_(byref(_t), byref(_D), _x, byref(_dDdt)) return _prop(x = x, D = D, t = t, dDdt = _dDdt.value) def dcdt(t, x): '''Compute the 1st derivative of C (C is the third virial coefficient) with respect to T as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] outputs: dct--1st derivative of C with respect to T [(L/mol)^2-K]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpdcdt_(byref(_t), _x, byref(_dct)) return _prop(x = x, t = t, dct = _dct.value) def dcdt2(t, x): '''Compute the 2nd derivative of C (C is the third virial coefficient) with respect to T as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] outputs: dct2--2nd derivative of C with respect to T [(L/mol-K)^2]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpdcdt2_(byref(_t), _x, byref(_dct2)) return _prop(x = x, t = t, dct2 = _dct2.value) def dhd1(t, D, x): '''Compute partial derivatives of enthalpy w.r.t. t, p, or D at constant t, p, or D as a function of temperature, density, and composition inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: dhdt_D--dh/dt [J/mol-K] dhdt_p--dh/dt [J/mol-K] dhdD_t--dh/dD [J-L/mol^2] dhdD_p--dh/dD [J-L/mol^2] dhdp_t--dh/dt [J/mol-kPa] dhdp_D--dh/dt [J/mol-kPA]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpdhd1_(byref(_t), byref(_D), _x, byref(_dhdt_D), byref(_dhdt_p), byref(_dhdD_t), byref(_dhdD_p), byref(_dhdp_t), byref(_dhdp_D)) return _prop(x = x, D = D, t = t, dhdt_D = _dhdt_D.value, dhdt_p = _dhdt_p.value, dhdD_t = _dhdD_t.value, dhdD_p = _dhdD_p.value, dhdp_t = _dhdp_t.value, dhdtp_D = _dhdp_D.value) def fgcty(t, D, x): '''Compute fugacity for each of the nc components of a mixture by numerical differentiation (using central differences) of the dimensionless residual Helmholtz energy based on derivations in E.W. Lemmon, MS Thesis, University of Idaho (1991); section 3.2 inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] output: f--array (1..nc) of fugacities [kPa]''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpfgcty_(byref(_t), byref(_D), _x, _f) return _prop(x = x, D = D, t = t, f = [_f[each] for each in range(_nc_rec.record)]) def fgcty2(t, D, x): '''Compute fugacity for each of the nc components of a mixture by analytical differentiation of the dimensionless residual Helmholtz energy. based on derivations in the GERG-2004 document for natural gas inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: f--array (1..nc) of fugacities [kPa] fgcty2 does not work proper on either Linux and Windows operating platform''' raise RefproproutineError('function "fgcty2" unsupported in Linux & Windows') #fgcty2 returns value of fgcty and next refprop call is being #blocked by ctypes #~ _inputerrorcheck(locals()) #~ _t.value, _D.value = t, D #~ for each in range(len(x)): _x[each] = x[each] #~ #~ raise RefproproutineError('function "fgcty2" unsupported in Linux') #~ return _prop(x = x, D = D, t = t, f = [_f[each] for each in range(_nc_rec.record)]) def fugcof(t, D, x): '''Compute the fugacity coefficient for each of the nc components of a mixture. inputs: t--temperature [K] D--molar density [mol/L] x--composition [array of mol frac] outputs: f--array (1..nc) of the fugacity coefficients''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpfugcof_(byref(_t), byref(_D), _x, _f, byref(_ierr), byref(_herr), c_long(255)) return _prop(x = x, D = D, t = t, f = [_f[each] for each in range(_nc_rec.record)], ierr = _ierr.value, herr = _herr.value, defname = 'fugcof') def dbdt(t, x): '''Compute the 2nd derivative of B (B is the second virial coefficient) with respect to T as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] outputs: dbt--2nd derivative of B with respect to T [L/mol-K]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpdbdt_(byref(_t), _x, byref(_dbt)) return _prop(x = x, t = t, dbt = _dbt.value) def virb(t, x): '''Compute second virial coefficient as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] outputs: b--second virial coefficient [L/mol]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpvirb_(byref(_t), _x, byref(_b)) return _prop(x = x, t = t, b = _b.value) def virc(t, x): '''Compute the third virial coefficient as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] outputs: c--third virial coefficient [(L/mol)^2]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpvirc_(byref(_t), _x, byref(_c)) return _prop(x = x, t = t, c = _c.value) def vird(t, x): '''Compute the fourth virial coefficient as a function of temperature and composition. Routine not supported in Windows inputs: t--temperature [K] x--composition [array of mol frac] outputs: c--third virial coefficient [(L/mol)^3]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpvird_(byref(_t), _x, byref(_d)) return _prop(x = x, t = t, d = _d.value) def virba (t, x): '''Compute second acoustic virial coefficient as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] outputs: ba--second acoustic virial coefficient [L/mol]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpvirba_(byref(_t), _x, byref(_ba)) return _prop(x = x, t = t, ba = _ba.value) def virca(t, x): '''Compute third acoustic virial coefficient as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] outputs: ca--third acoustic virial coefficient [(L/mol)^2]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpvirca_(byref(_t), _x, byref(_ca)) return _prop(x = x, t = t, ca = _ca.value) def satt(t, x, kph=2): '''Iterate for saturated liquid and vapor states given temperature and the composition of one phase inputs: t--temperature [K] x--composition [array of mol frac] (phase specified by kph) kph--phase flag: 1 = input x is liquid composition (bubble point) 2 = input x is vapor composition (dew point) 3 = input x is liquid composition (freezing point) 4 = input x is vapor composition (sublimation point) outputs: p--pressure [kPa] Dliq--molar density [mol/L] of saturated liquid Dvap--molar density [mol/L] of saturated vapor For a pseudo pure fluid, the density of the equilibrium phase is not returned. Call SATT twice, once with kph=1 to get pliq and Dliq, and once with kph=2 to get pvap and Dvap. xliq--liquid phase composition [array of mol frac] xvap--vapor phase composition [array of mol frac]''' _inputerrorcheck(locals()) _t.value, _kph.value = t, kph for each in range(len(x)): _x[each] = x[each] _rpsatt_(byref(_t), _x, byref(_kph), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_ierr), byref(_herr), c_long(255)) xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x'] xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xliq): xliq = [xliq[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xvap): xvap = [xvap[_purefld_rec.record['icomp'] - 1]] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xliq): xliq = [xliq[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xvap): xvap = [xvap[_purefld_rec.record['icomp'] - 1]] return _prop(t = t, x = x, kph = kph, p = _p.value, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, ierr = _ierr.value, herr = _herr.value, defname = 'satt') def satp(p, x, kph=2): '''Iterate for saturated liquid and vapor states given pressure and the composition of one phase. inputs: p--pressure [kPa] x--composition [array of mol frac] (phase specified by kph) kph--phase flag: 1 = input x is liquid composition (bubble point) 2 = input x is vapor composition (dew point) 3 = input x is liquid composition (freezing point) 4 = input x is vapor composition (sublimation point) outputs: t--temperature [K] Dliq--molar density [mol/L] of saturated liquid Dvap--molar density [mol/L] of saturated vapor For a pseudo pure fluid, the density of the equilibrium phase is not returned. Call SATP twice, once with kph=1 to get tliq and Dliq, and once with kph=2 to get tvap and Dvap. xliq--liquid phase composition [array of mol frac] xvap--vapor phase composition [array of mol frac]''' _inputerrorcheck(locals()) _p.value, _kph.value = p, kph for each in range(len(x)): _x[each] = x[each] _rpsatp_(byref(_p), _x, byref(_kph), byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_ierr), byref(_herr), c_long(255)) xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x'] xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xliq): xliq = [xliq[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xvap): xvap = [xvap[_purefld_rec.record['icomp'] - 1]] return _prop(p = p, x = x, kph = kph, t = _t.value, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, ierr = _ierr.value, herr = _herr.value, defname = 'satp') def satd(D, x, kph=2): '''Iterate for temperature and pressure given a density along the saturation boundary and the composition. inputs: D--molar density [mol/L] x--composition [array of mol frac] kph--flag specifying desired root for multi-valued inputs has meaning only for water at temperatures close to its triple point -1 = return middle root (between 0 and 4 C) 1 = return highest temperature root (above 4 C) 3 = return lowest temperature root (along freezing line) outputs: t--temperature [K] p--pressure [kPa] Dliq--molar density [mol/L] of saturated liquid Dvap--molar density [mol/L] of saturated vapor xliq--liquid phase composition [array of mol frac] xvap--vapor phase composition [array of mol frac] kr--phase flag: 1 = input state is liquid 2 = input state is vapor in equilibrium with liq 3 = input state is liquid in equilibrium with solid 4 = input state is vapor in equilibrium with solid N.B. kr = 3,4 presently working only for pure components either (Dliq, xliq) or (Dvap, xvap) will correspond to the input state with the other pair corresponding to the other phase in equilibrium with the input state''' _inputerrorcheck(locals()) _D.value, _kph.value = D, kph for each in range(len(x)): _x[each] = x[each] _rpsatd_(byref(_D), _x, byref(_kph), byref(_kr), byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_ierr), byref(_herr), c_long(255)) xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x'] xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xliq): xliq = [xliq[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xvap): xvap = [xvap[_purefld_rec.record['icomp'] - 1]] return _prop(D = D, x = x, kph = kph, kr = _kr.value, t = _t.value, p = _p.value, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, ierr = _ierr.value, herr = _herr.value, defname = 'satd') def sath(h, x, kph=2): '''Iterate for temperature, pressure, and density given enthalpy along the saturation boundary and the composition. inputs: h--molar enthalpy [J/mol] x--composition [array of mol frac] kph--flag specifying desired root: 0 = return all roots along the liquid-vapor line 1 = return only liquid VLE root 2 = return only vapor VLE roots 3 = return liquid SLE root (melting line) 4 = return vapor SVE root (sublimation line) outputs: nroot--number of roots. Set to one for kph=1,3,4 if ierr=0 k1--phase of first root (1-liquid, 2-vapor, 3-melt, 4-subl) t1--temperature of first root [K] p1--pressure of first root [kPa] D1--molar density of first root [mol/L] k2--phase of second root (1-liquid, 2-vapor, 3-melt, 4-subl) t2--temperature of second root [K] p2--pressure of second root [kPa] D2--molar density of second root [mol/L] The second root is always set as the root in the vapor at temperatures below the maximum enthalpy on the vapor saturation line. If kph is set to 2, and only one root is found in the vapor (this occurs when h < hcrit) the state point will be placed in k2,t2,p2,d2. If kph=0 and this situation occurred, the first root (k1,t1,p1,d1) would be in the liquid (k1=1, k2=2). N.B. kph = 3,4 presently working only for pure components''' _inputerrorcheck(locals()) _h.value, _kph.value = h, kph for each in range(len(x)): _x[each] = x[each] _rpsath_(byref(_h), _x, byref(_kph), byref(_nroot), byref(_k1), byref(_t1), byref(_p1), byref(_D1), byref(_k2), byref(_t2), byref(_p2), byref(_D2), byref(_ierr), byref(_herr), c_long(255)) return _prop(h = h, x = x, kph = kph, nroot = _nroot.value, k1 = _k1.value, t1 = _t1.value, p1 = _p1.value, D1 = _D1.value, k2 = _k2.value, t2 = _t2.value, p2 = _p2.value, D2 = _D2.value, ierr = _ierr.value, herr = _herr.value, defname = 'sath') def sate(e, x, kph=2): '''Iterate for temperature, pressure, and density given energy along the saturation boundary and the composition. inputs: e--molar energy [J/mol] x--composition [array of mol frac] kph--flag specifying desired root: 0 = return all roots along the liquid-vapor line 1 = return only liquid VLE root 2 = return only vapor VLE roots 3 = return liquid SLE root (melting line) 4 = return vapor SVE root (sublimation line) outputs: nroot--number of roots. Set to one for kph=1,3,4 if ierr=0 k1--phase of first root (1-liquid, 2-vapor, 3-melt, 4-subl) t1--temperature of first root [K] p1--pressure of first root [kPa] D1--molar density of first root [mol/L] k2--phase of second root (1-liquid, 2-vapor, 3-melt, 4-subl) t2--temperature of second root [K] p2--pressure of second root [kPa] D2--molar density of second root [mol/L] The second root is always set as the root in the vapor at temperatures below the maximum energy on the vapor saturation line. If kph is set to 2, and only one root is found in the vapor (this occurs when h < hcrit) the state point will be placed in k2,t2,p2,d2. If kph=0 and this situation occurred, the first root (k1,t1,p1,d1) would be in the liquid (k1=1, k2=2). N.B. kph = 3,4 presently working only for pure components''' _inputerrorcheck(locals()) _e.value, _kph.value = e, kph for each in range(len(x)): _x[each] = x[each] _rpsate_(byref(_e), _x, byref(_kph), byref(_nroot), byref(_k1), byref(_t1), byref(_p1), byref(_D1),byref(_k2), byref(_t2), byref(_p2), byref(_D2), byref(_ierr), byref(_herr), c_long(255)) return _prop(e = e, x = x, kph = kph, nroot = _nroot.value, k1 = _k1.value, t1 = _t1.value, p1 = _p1.value, D1 = _D1.value, k2 = _k2.value, t2 = _t2.value, p2 = _p2.value, D2 = _D2.value, ierr = _ierr.value, herr = _herr.value, defname = 'sate') def sats(s, x, kph=2): '''Iterate for temperature, pressure, and density given entropy along the saturation boundary and the composition. inputs: s--entrophy [J/(mol K)] x--composition [array of mol frac] kph--flag specifying desired root: 0 = return all roots along the liquid-vapor line 1 = return only liquid VLE root 2 = return only vapor VLE roots 3 = return liquid SLE root (melting line) 4 = return vapor SVE root (sublimation line) outputs: nroot--number of roots. Set to one for kph=1,3,4 if ierr=0 k1--phase of first root (1-liquid, 2-vapor, 3-melt, 4-subl) t1--temperature of first root [K] p1--pressure of first root [kPa] D1--molar density of first root [mol/L] k2--phase of second root (1-liquid, 2-vapor, 3-melt, 4-subl) t2--temperature of second root [K] p2--pressure of second root [kPa] D2--molar density of second root [mol/L] k3--phase of third root (1-liquid, 2-vapor, 3-melt, 4-subl) t3--temperature of third root [K] p3--pressure of third root [kPa] D3--molar density of third root [mol/L] The second root is always set as the root in the vapor at temperatures below the maximum energy on the vapor saturation line. If kph is set to 2, and only one root is found in the vapor (this occurs when h < hcrit) the state point will be placed in k2,t2,p2,d2. If kph=0 and this situation occurred, the first root (k1,t1,p1,d1) would be in the liquid (k1=1, k2=2). The third root is the root with the lowest temperature. For fluids with multiple roots: When only one root is found in the vapor phase (this happens only at very low temperatures past the region where three roots are located), the value of the root is still placed in k3,t3,p3,d3. For fluids that never have more than one root (when there is no maximum entropy along the saturated vapor line), the value of the root is always placed in k1,t1,p1,d1. N.B. kph = 3,4 presently working only for pure components''' _inputerrorcheck(locals()) _s.value, _kph.value = s, kph for each in range(len(x)): _x[each] = x[each] _rpsats_(byref(_s), _x, byref(_kph), byref(_nroot), byref(_k1), byref(_t1), byref(_p1), byref(_D1), byref(_k2), byref(_t2), byref(_p2), byref(_D2), byref(_k3), byref(_t3), byref(_p3), byref(_D3), byref(_ierr), byref(_herr), c_long(255)) return _prop(s = s, x = x, kph = kph, nroot = _nroot.value, k1 = _k1.value, t1 = _t1.value, p1 = _p1.value, D1 = _D1.value, k2 = _k2.value, t2 = _t2.value, p2 = _p2.value, D2 = _D2.value, k3 = _k3.value, t3 = _t3.value, p3 = _p3.value, D3 = _D3.value, ierr = _ierr.value, herr = _herr.value, defname = 'sats') def csatk(icomp, t, kph=2): '''Compute the heat capacity along the saturation line as a function of temperature for a given component csat can be calculated two different ways: Csat = Cp - t(DvDt)(DpDtsat) Csat = Cp - beta/D*hvap/(vliq - vvap), where beta is the volume expansivity inputs: icomp--component number in mixture (1..nc); 1 for pure fluid t--temperature [K] kph--phase flag: 1 = liquid calculation 2 = vapor calculation outputs: p--saturation pressure [kPa] D--saturation molar density [mol/L] csat--saturation heat capacity [J/mol-K]''' _inputerrorcheck(locals()) _icomp.value, _t.value, _kph.value = icomp, t, kph _rpcsatk_(byref(_icomp), byref(_t), byref(_kph), byref(_p), byref(_D), byref(_csat), byref(_ierr), byref(_herr), c_long(255)) return _prop(icomp = icomp, t = t, kph = kph, p = _p.value, D = _D.value, csat = _csat.value, ierr = _ierr.value, herr = _herr.value, defname = 'csatk') def dptsatk(icomp, t, kph=2): '''Compute the heat capacity and dP/dT along the saturation line as a function of temperature for a given component. See also subroutine CSATK. inputs: icomp--component number in mixture (1..nc); 1 for pure fluid t--temperature [K] kph--phase flag: 1 = liquid calculation 2 = vapor calculation outputs: p--saturation pressure [kPa] D--saturation molar density [mol/L] csat--saturation heat capacity [J/mol-K] (same as that called from CSATK) dpdt--dp/dT along the saturation line [kPa/K] (this is not dp/dt "at" the saturation line for the single phase state, but the change in saturated vapor pressure as the saturation temperature changes.)''' _inputerrorcheck(locals()) _icomp.value, _t.value, _kph.value = icomp, t, kph _rpdptsatk_(byref(_icomp), byref(_t), byref(_kph), byref(_p), byref(_D), byref(_csat), byref(_dpdt), byref(_ierr), byref(_herr), c_long(255)) return _prop(icomp = icomp, t = t, kph = kph, p = _p.value, D = _D.value, csat = _csat.value, dpdt = _dpdt.value, ierr = _ierr.value, herr = _herr.value, defname = 'dptsatk') def cv2pk(icomp, t, D=0): '''Compute the isochoric heat capacity in the two phase (liquid+vapor) region. inputs: icomp--component number in mixture (1..nc); 1 for pure fluid t--temperature [K] D--density [mol/l] if known If D=0, then a saturated liquid state is assumed. outputs: cv2p--isochoric two-phase heat capacity [J/mol-K] csat--saturation heat capacity [J/mol-K] (Although there is already a csat routine in REFPROP, it is also returned here. However, the calculation speed is slower than csat.)''' _inputerrorcheck(locals()) _icomp.value, _t.value, _D.value = icomp, t, D _rpcv2pk_(byref(_icomp), byref(_t), byref(_D), byref(_cv2p), byref(_csat), byref(_ierr), byref(_herr), c_long(255)) return _prop(icomp = icomp, t = t, D = D, cv2p = _cv2p.value, csat = _csat.value, ierr = _ierr.value, herr = _herr.value, defname = 'cv2pk') def tprho(t, p, x, kph=2, kguess=0, D=0): '''Iterate for density as a function of temperature, pressure, and composition for a specified phase. The single-phase temperature-pressure flash is called many times by other routines, and has been optimized for speed; it requires a specific calling sequence. *********************************************************************** WARNING: Invalid densities will be returned for T & P outside range of validity, i.e., pressure > melting pressure, pressure less than saturation pressure for kph=1, etc. *********************************************************************** inputs: t--temperature [K] p--pressure [kPa] x--composition [array of mol frac] kph--phase flag: 1 = liquid 2 = vapor 0 = stable phase--NOT ALLOWED (use TPFLSH) (unless an initial guess is supplied for rho) -1 = force the search in the liquid phase -2 = force the search in the vapor phase kguess--input flag: 1 = first guess for D provided 0 = no first guess provided D--first guess for molar density [mol/L], only if kguess = 1 outputs: D--molar density [mol/L]''' _inputerrorcheck(locals()) _t.value, _p.value, _kph.value = t, p, kph _kguess.value, _D.value = kguess, D for each in range(len(x)): _x[each] = x[each] _rptprho_(byref(_t), byref(_p), _x, byref(_kph), byref(_kguess), byref(_D), byref(_ierr), byref(_herr), c_long(255)) return _prop(t = t, p = p, x = x, kph = kph, kguess = kguess, D = _D.value, ierr = _ierr.value, herr = _herr.value, defname = 'tprho') def flsh(routine, var1, var2, x, kph=1): '''Flash calculation given two independent variables and bulk composition These routines accept both single-phase and two-phase states as the input; if the phase is known, the specialized routines are faster inputs: routine--set input variables: 'TP'--temperature; pressure 'TD'--temperature; Molar Density 'TH'--temperature; enthalpy 'TS'--temperature; entropy 'TE'--temperature; internal energy 'PD'--pressure; molar density 'PH'--pressure; enthalpy 'PS'--pressure; entropy 'PE'--pressure; internal energy 'HS'--enthalpy; entropy 'ES'--internal energy; entropy 'DH'--molar density; enthalpy 'DS'--molar density; entropy 'DE'--molar density; internal energy 'TQ'--temperature; vapour quality 'PQ'--pressure; vapour qaulity var1, var2--two of the following as indicated by the routine input: t--temperature [K] p--pressure [kPa] e--internal energy [J/mol] h--enthalpy [J/mol] s--entropy [[J/mol-K] q--vapor quality on molar basis [moles vapor/total moles] q = 0 indicates saturated liquid 0 < q < 1 indicates 2 phase state q = 1 indicates saturated vapor q < 0 or q > 1 are not allowed and will result in warning x--overall (bulk) composition [array of mol frac] kph--phase flag: N.B. only applicable for routine setting 'TE', 'TH' and 'TS' 1=liquid, 2=vapor in equilibrium with liq, 3=liquid in equilibrium with solid, 4=vapor in equilibrium with solid. outputs: t--temperature [K] p--pressure [kPa] D--overall (bulk) molar density [mol/L] Dliq--molar density [mol/L] of the liquid phase Dvap--molar density [mol/L] of the vapor phase if only one phase is present, Dl = Dv = D xliq--composition of liquid phase [array of mol frac] xvap--composition of vapor phase [array of mol frac] if only one phase is present, x = xliq = xvap q--vapor quality on a MOLAR basis [moles vapor/total moles] q < 0 indicates subcooled (compressed) liquid q = 0 indicates saturated liquid 0 < q < 1 indicates 2 phase state q = 1 indicates saturated vapor q > 1 indicates superheated vapor q = 998 superheated vapor, but quality not defined (t > Tc) q = 999 indicates supercritical state (t > Tc) and (p > Pc) e--overall (bulk) internal energy [J/mol] h--overall (bulk) enthalpy [J/mol] s--overall (bulk) entropy [J/mol-K] cv--isochoric (constant V) heat capacity [J/mol-K] cp--isobaric (constant p) heat capacity [J/mol-K] w--speed of sound [m/s] cp, cv and w are not defined for 2-phase states in such cases''' _inputerrorcheck(locals()) _kph.value = kph for each in range(len(x)): _x[each] = x[each] if routine.upper() == 'TP': _t.value, _p.value = var1, var2 _rptpflsh_(byref(_t), byref(_p), _x, byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TD': _t.value, _D.value = var1, var2 _rptdflsh_(byref(_t), byref(_D), _x, byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TH': _t.value, _h.value = var1, var2 _rpthflsh_(byref(_t), byref(_h), _x, byref(_kph), byref(_p), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TS': _t.value, _s.value = var1, var2 _rptsflsh_(byref(_t), byref(_s), _x, byref(_kph), byref(_p), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TE': _t.value, _e.value = var1, var2 _rpteflsh_(byref(_t), byref(_e), _x, byref(_kph), byref(_p), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PD': _p.value, _D.value = var1, var2 _rppdflsh_(byref(_p), byref(_D), _x, byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PH': _p.value, _h.value = var1, var2 _rpphflsh_(byref(_p), byref(_h), _x, byref(_t), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PS': _p.value, _s.value = var1, var2 _rppsflsh_(byref(_p), byref(_s), _x, byref(_t), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PE': _p.value, _e.value = var1, var2 _rppeflsh_(byref(_p), byref(_e), _x, byref(_t), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'HS': _h.value, _s.value = var1, var2 _rphsflsh_(byref(_h), byref(_s), _x, byref(_t), byref(_p), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'ES': _e.value, _s.value = var1, var2 _rpesflsh_(byref(_e), byref(_s), _x, byref(_t), byref(_p), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_h), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DH': _D.value, _h.value = var1, var2 _rpdhflsh_(byref(_D), byref(_h), _x, byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DS': _D.value, _s.value = var1, var2 _rpdsflsh_(byref(_D), byref(_s), _x, byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DE': _D.value, _e.value = var1, var2 _rpdeflsh_(byref(_D), byref(_e), _x, byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TQ': _t.value, _q.value = var1, var2 _rptqflsh_(byref(_t), byref(_q), _x, byref(c_long(1)), byref(_p), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PQ': _p.value, _q.value = var1, var2 _rppqflsh_(byref(_p), byref(_q), _x, byref(c_long(1)), byref(_t), byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr), byref(_herr), c_long(255)) else: raise RefpropinputError('Incorrect "routine" input, ' + str(routine) + ' is an invalid input') xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x'] xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xliq): xliq = [xliq[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xvap): xvap = [xvap[_purefld_rec.record['icomp'] - 1]] if _cp.value < 0: return _prop(x = x, p = _p.value, q = _q.value, kph = kph, t = _t.value, D = _D.value, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, e = _e.value, h = _h.value, s = _s.value, ierr = _ierr.value, herr = _herr.value, defname = 'flsh') else: return _prop(x = x, p = _p.value, q = _q.value, kph = kph, t = _t.value, D = _D.value, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, e = _e.value, h = _h.value, s = _s.value, cv = _cv.value, cp = _cp.value, w = _w.value, ierr = _ierr.value, herr = _herr.value, defname = 'flsh') def flsh1(routine, var1, var2, x, kph=1, Dmin=0, Dmax=0): '''Flash calculation given two independent variables and bulk composition These routines accept only single-phase states and outside critical region as inputs. They will be faster than the corresponding general routines, but will fail if called with an incorrect phase specification. The phase-specific subroutines also do not check limits, so may fail if called outside the range of the equation of state. inputs: routine--set input variables: 'TH'--temperature; enthalpy* 'TS'--temperature; entropy* 'TE'--temperature; energy* 'PD'--pressure; molar density 'PH'--pressure; entalphy 'PS'--pressure; entropy 'PE'--pressure; internal energy* 'HS'--enthalpy; entropy* 'DH'--molar density; enthalpy* 'DS'--molar density; entropy* 'DE'--molar density; internal energy* * routine not supported in Windows var1, var2--two of the following as indicated by the routine input: t--temperature [K] p--pressure [kPa] e--internal energy [J/mol] h--enthalpy [J/mol] s--entropy [[J/mol-K] x--overall (bulk) composition [array of mol frac] kph--phase flag: N.B. only applicable for routine setting 'TE', 'TH' and 'TS' 1 = liquid, 2 = vapor Dmin--lower bound on density [mol/L] Dmax--upper bound on density [mol/L] outputs: t--temperature [K] D--overall (bulk) molar density [mol/L]''' defname = 'flsh1' _inputerrorcheck(locals()) _kph.value, _Dmin.value, _Dmax.value = kph, Dmin, Dmax for each in range(len(x)): _x[each] = x[each] if routine.upper() == 'TH': _t.value, _h.value = var1, var2 _rpthfl1_(byref(_t), byref(_h), _x, byref(_Dmin), byref(_Dmax), byref(_D), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TS': _t.value, _s.value = var1, var2 _rptsfl1_(byref(_t), byref(_s), _x, byref(_Dmin), byref(_Dmax), byref(_D), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TE': _t.value, _e.value = var1, var2 _rptefl1_(byref(_t), byref(_e), _x, byref(_Dmin), byref(_Dmax), byref(_D), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PD': _p.value, _D.value = var1, var2 _rppdfl1_(byref(_p), byref(_D), _x, byref(_t), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PH': _p.value, _h.value = var1, var2 _rpphfl1_(byref(_p), byref(_h), _x, byref(_kph), byref(_t), byref(_D), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PS': _p.value, _s.value = var1, var2 _rppsfl1_(byref(_p), byref(_s), _x, byref(_kph), byref(_t), byref(_D), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PE': #wrong value return _p.value, _e.value = var1, var2 _rppefl1_(byref(_p), byref(_e), _x, byref(_kph), byref(_t), byref(_D), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'HS': _h.value, _s.value = var1, var2 _rphsfl1_(byref(_h), byref(_s), _x, byref(_Dmin), byref(_Dmax), byref(_t), byref(_D), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DH': _D.value, _h.value = var1, var2 _rpdhfl1_(byref(_D), byref(_h), _x, byref(_t), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DS': _D.value, _s.value = var1, var2 _rpdsfl1_(byref(_D), byref(_s), _x, byref(_t), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DE': _D.value, _e.value = var1, var2 _rpdefl1_(byref(_D), byref(_e), _x, byref(_t), byref(_ierr), byref(_herr), c_long(255)) else: raise RefpropinputError('Incorrect "routine" input, ' + str(routine) + ' is an invalid input') if routine.upper() == 'TH': return _prop(x = x, t = var1, Dmin = _Dmin.value, Dmax = _Dmax.value, D = _D.value, h = var2, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'TS': return _prop(x = x, t = var1, D = _D.value, s = var2, Dmin = _Dmin.value, Dmax = _Dmax.value, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'TE': return _prop(x = x, t = var1, D = _D.value, e = var2, Dmin = _Dmin.value, Dmax = _Dmax.value, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'PD': return _prop(x = x, t = _t.value, D = var2, kph = kph, p = var1, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'PH': return _prop(x = x, t = _t.value, D = _D.value, kph = kph, p = var1, h = var2, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'PS': return _prop(x = x, t = _t.value, D = _D.value, kph = kph, p = var1, s = var2, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'PE': return _prop(x = x, t = _t.value, D = _D.value, kph = kph, p = var1, e = var2, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'HS': return _prop(x = x, t = _t.value, D = _D.value, h = var1, s = var2, ierr = _ierr.value, herr = _herr.value, Dmin = _Dmin.value, Dmax = _Dmax.value, defname = defname) elif routine.upper() == 'DH': return _prop(x = x, t = _t.value, D = var1, h = var2, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'DS': return _prop(x = x, t = _t.value, D = var1, s = var2, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'DE': return _prop(x = x, t = _t.value, D = var1, e = var2, ierr = _ierr.value, herr = _herr.value, defname = defname) def flsh2(routine, var1, var2, x, kq=1, ksat=0, tbub=0, tdew=0, pbub=0, pdew=0, Dlbub=0, Dvdew=0, xbub=None, xdew=None): '''Flash calculation given two independent variables and bulk composition These routines accept only two-phase (liquid + vapor) states as inputs. They will be faster than the corresponding general routines, but will fail if called with an incorrect phase specification. The phase-specific subroutines also do not check limits, so may fail if called outside the range of the equation of state. Some two-phase flash routines have the option to pass the dew and bubble point conditions as inputs if these values are known (from a previous call to SATT or SATP, for example), these two-phase routines will be significantly faster than the corresponding general FLSH routines described above. Otherwise, the general routines will be more reliable. inputs: routine--set input variables: 'TP'--temperature; pressure* 'DH'--molar density; enthalpy* 'DS'--molar density; entropy* 'DE'--molar density; internal energy* 'TH'--temperature; enthalpy* 'TS'--temperature; entropy* 'TE'--temperature; internal energy* 'TD'--temperature; Molar Density* 'PD'--pressure; molar density* 'PH'--pressure; entalphy* 'PS'--pressure; entropy* 'PE'--pressure; internal energy* 'TQ'--temperature; vapour quality* 'PQ'--pressure; vapour qaulity* 'DQ'--molar density; vapour quality*/** * NOT supported with Windows ** return value is incorrect var1, var2--two of the following as indicated by the routine input: t--temperature [K] p--pressure [kPa] D--molar density [mol/L] e--internal energy [J/mol] h--enthalpy [J/mol] s--entropy [[J/mol-K] q--vapor quality on molar basis [moles vapor/total moles] x--overall (bulk) composition [array of mol frac] kq--flag specifying units for input quality NB only for routine (TQ and PQ) kq = 1 quality on MOLAR basis [moles vapor/total moles] kq = 2 quality on MASS basis [mass vapor/total mass] ksat--flag for bubble and dew point limits NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ) 0 = dew and bubble point limits computed within routine 1 = must provide values for following: tbub--bubble point temperature [K] at (p,x=z) NB only for routine (PD, PH, PS, PE and PQ) tdew--dew point temperature [K] at (p,y=z) NB only for routine (PD, PH, PS, PE and PQ) pbub--bubble point pressure [kPa] at (t,x=z) NB only for routine (TH, TS, TE, TD and TQ) pdew--dew point pressure [kPa] at (t,y=z) NB only for routine (TH, TS, TE, TD and TQ) Dlbub--liquid density [mol/L] at bubble point NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ) Dvdew--vapor density [mol/L] at dew point NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ) xbub--vapor composition [array of mol frac] at bubble point NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ) xdew--liquid composition [array of mol frac] at dew point NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ) outputs: t--temperature [K] p--pressure [kPa] Dliq--molar density [mol/L] of the liquid phase Dvap--molar density [mol/L] of the vapor phase if only one phase is present, Dl = Dv = D xliq--composition of liquid phase [array of mol frac] xvap--composition of vapor phase [array of mol frac] if only one phase is present, x = xliq = xvap q--vapor quality on a MOLAR basis [moles vapor/total moles] tbub--bubble point temperature [K] at (p,x=z) NB only for routine (PD, PH, PS, PE and PQ) tdew--dew point temperature [K] at (p,y=z) NB only for routine (PD, PH, PS, PE and PQ) pbub--bubble point pressure [kPa] at (t,x=z) NB only for routine (TH, TS, TE, TD and TQ) pdew--dew point pressure [kPa] at (t,y=z) NB only for routine (TH, TS, TE, TD and TQ) Dlbub--liquid density [mol/L] at bubble point NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ) Dvdew--vapor density [mol/L] at dew point NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ) xbub--vapor composition [array of mol frac] at bubble point NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ) xdew--liquid composition [array of mol frac] at dew point NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)''' defname = 'flsh2' _inputerrorcheck(locals()) for each in range(len(x)): _x[each] = x[each] if xdew: _xdew[each] = xdew[each] if xbub: _xbub[each] = xbub[each] _ksat.value, _tbub.value, _kq.value = ksat, tbub, kq _tdew.value, _pbub.value, _pdew.value = tdew, pbub, pdew _Dlbub.value, _Dvdew.value = Dlbub, Dvdew if routine.upper() == 'TP': _t.value, _p.value = var1, var2 _rptpfl2_(byref(_t), byref(_p), _x, byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DH': _D.value, _h.value = var1, var2 _rpdhfl2_(byref(_D), byref(_h), _x, byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DS': _D.value, _s.value = var1, var2 _rpdsfl2_(byref(_D), byref(_s), _x, byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DE': _D.value, _e.value = var1, var2 _rpdefl2_(byref(_D), byref(_e), _x, byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TH': _t.value, _h.value = var1, var2 _rpthfl2_(byref(_t), byref(_h), _x, byref(_ksat), byref(_pbub), byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TS': _t.value, _s.value = var1, var2 _rptsfl2_(byref(_t), byref(_s), _x, byref(_ksat), byref(_pbub), byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TE': _t.value, _e.value = var1, var2 _rptefl2_(byref(_t), byref(_e), _x, byref(_ksat), byref(_pbub), byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TD': _t.value, _D.value = var1, var2 _rptdfl2_(byref(_t), byref(_D), _x, byref(_ksat), byref(_pbub), byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PD': _p.value, _D.value = var1, var2 _rppdfl2_(byref(_p), byref(_D), _x, byref(_ksat), byref(_tbub), byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PH': _p.value, _h.value = var1, var2 _rpphfl2_(byref(_p), byref(_h), _x, byref(_ksat), byref(_tbub), byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PS': _p.value, _s.value = var1, var2 _rppsfl2_(byref(_p), byref(_s), _x, byref(_ksat), byref(_tbub), byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PE': _p.value, _e.value = var1, var2 _rppefl2_(byref(_p), byref(_e), _x, byref(_ksat), byref(_tbub), byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'TQ': _t.value, _q.value = var1, var2 _rptqfl2_(byref(_t), byref(_q), _x, byref(_kq), byref(_ksat), byref(_pbub), byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'PQ': _p.value, _q.value = var1, var2 _rppqfl2_(byref(_p), byref(_q), _x, byref(_kq), byref(_ksat), byref(_tbub), byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_ierr), byref(_herr), c_long(255)) elif routine.upper() == 'DQ': _D.value, _q.value = var1, var2 raise RefproproutineError('function "DQFL2" unsupported in Linux') ##~ _rpdqfl2_(byref(_D), byref(_q), _x, byref(_kq), byref(_t), #~ byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, #~ byref(_ierr), byref(_herr), 255) else: raise RefpropinputError('Incorrect "routine" input, ' + str(routine) + ' is an invalid input') xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x'] xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xliq): xliq = [xliq[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xvap): xvap = [xvap[_purefld_rec.record['icomp'] - 1]] if routine.upper() in ['TH', 'TS', 'TE', 'TD', 'PD', 'PH', 'PS', 'PE', 'TQ', 'PQ', 'DQ']: xdew = normalize([_xdew[each] for each in range(_nc_rec.record)])['x'] xbub = normalize([_xbub[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xdew): xdew = [xdew[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xbub): xbub = [xbub[_purefld_rec.record['icomp'] - 1]] if routine.upper() == 'TP': return _prop(x = x, t = var1, p = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'DH': return _prop(x = x, D = var1, h = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value,t = _t.value, p = _p.value, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'DS': return _prop(x = x, D = var1, s = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, p = _p.value, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'DE': return _prop(x = x, D = var1, e = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, p = _p.value, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'TH': if ksat == 0: return _prop(x = x, t = var1, h = var2, Dliq = _Dliq.value, ksat = ksat, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, p = _p.value, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, defname = defname) elif ksat == 1: return _prop(x = x, t = var1, h = var2, Dliq = _Dliq.value, ksat = ksat, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, p = _p.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, defname = defname) elif routine.upper() == 'TS': if ksat == 0: return _prop(x = x, t = var1, s = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, p = _p.value, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) elif ksat == 1: return _prop(x = x, t = var1, s = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, p = _p.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) elif routine.upper() == 'TE': if ksat == 0: return _prop(x = x, t = var1, e = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, p = _p.value, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) elif ksat == 1: return _prop(x = x, t = var1, e = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, p = _p.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) elif routine.upper() == 'TD': if ksat == 0: return _prop(x = x, t = var1, D = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, p = _p.value, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) elif ksat == 1: return _prop(x = x, t = var1, D = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, p = _p.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) elif routine.upper() == 'PD': if ksat == 0: return _prop(x = x, p = var1, D = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, ierr = _ierr.value, herr = _herr.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) return prop elif ksat == 1: return _prop(x = x, p = var1, D = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) elif routine.upper() == 'PH': if ksat == 0: return _prop(x = x, p = var1, h = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, ierr = _ierr.value, herr = _herr.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) elif ksat == 1: return _prop(x = x, p = var1, h = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) elif routine.upper() == 'PS': if ksat == 0: return _prop(x = x, p = var1, s = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, ierr = _ierr.value, herr = _herr.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) elif ksat == 1: return _prop(x = x, p = var1, s = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) elif routine.upper() == 'PE': if ksat == 0: return _prop(x = x, p = var1, e = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, ierr = _ierr.value, herr = _herr.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) elif ksat == 1: return _prop(x = x, p = var1, e = var2, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, q = _q.value, t = _t.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) elif routine.upper() == 'TQ': if ksat == 0: return _prop(x = x, t = var1, q = var2, Dliq = _Dliq.value, kq = kq, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, p = _p.value, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) elif ksat == 1: return _prop(x = x, t = var1, q = var2, Dliq = _Dliq.value, kq = kq, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, p = _p.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) elif routine.upper() == 'PQ': if ksat == 0: return _prop(x = x, p = var1, q = var2, Dliq = _Dliq.value, kq = kq, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, t = _t.value, ierr = _ierr.value, herr = _herr.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ksat = ksat, defname = defname) elif ksat == 1: return _prop(x = x, p = var1, q = var2, Dliq = _Dliq.value, kq = kq, Dvap = _Dvap.value, xliq = xliq, xvap = xvap, t = _t.value, tbub = _tbub.value, tdew = _tdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew, ierr = _ierr.value, herr = _herr.value, ksat = ksat, defname = defname) #~ elif routine.upper() == 'DQ': #~ return _prop(x = x, D = var1, q = var2, Dliq = _Dliq.value, kq = kq, #~ Dvap = _Dvap.value, xliq = xliq, xvap = xvap, t = _t.value, #~ p = _p.value, ierr = _ierr.value, herr = _herr.value, defname = defname) def _abfl2(routine, var1, var2, x, kq=1, ksat=0, tbub=0, tdew=0, pbub=0, pdew=0, Dlbub=0, Dvdew=0, xbub=None, xdew=None): '''General flash calculation given two inputs and composition. Valid properties for the first input are temperature and pressure. Valid properties for the second input are density, energy, enthalpy, entropy, or quality. The character string ab specifies the inputs. Note that the input TP is not allowed here, but is done by calling TPFLSH or TPFL2. This routine calls TPFL2 within a secant-method iteration for pressure to find a solution. Initial guesses are based on liquid density at the bubble point and vapor density at the dew point. inputs: routine--character*2 string defining the inputs, e.g., 'TD' or 'PQ' var1--first property (either temperature or pressure) var2--second property (density, energy, enthalpy, entropy, or quality) x--overall (bulk) composition [array of mol frac] kq--flag specifying units for input quality when b=quality kq = 1 [default] quality on MOLAR basis [moles vapor/total moles] kq = 2 quality on MASS basis [mass vapor/total mass] ksat--flag for bubble and dew point limits 0 [default] = dew and bubble point limits computed here 1 = must provide values for the following: (for a=pressure): tbub--bubble point temperature [K] at (p,x=z) tdew--dew point temperature [K] at (p,y=z) (for a=temperature): pbub--bubble point pressure [kPa] at (t,x=z) pdew--dew point pressure [kPa] at (t,y=z) (for either case): Dlbub--liquid density [mol/L] at bubble point Dvdew--vapor density [mol/L] at dew point xbub--vapor composition [array of mol frac] at bubble point xdew--liquid composition [array of mol frac] at dew point outputs: t--temperature [K] p--pressure [kPa] D--molar density [mol/L] Dliq--molar density [mol/L] of the liquid phase Dvap--molar density [mol/L] of the vapor phase xliq--composition of liquid phase [array of mol frac] xvap--composition of vapor phase [array of mol frac] q--vapor quality on a MOLAR basis [moles vapor/total moles]''' defname = '_abfl2' _inputerrorcheck(locals()) for each in range(len(x)): _x[each] = x[each] if xdew: for each in range(len(xdew)): _xdew[each] = xdew[each] if xbub: for each in range(len(xbub)): _xbub[each] = xbub[each] _ksat.value, _tbub.value, _kq.value = ksat, tbub, kq _tdew.value, _pbub.value, _pdew.value = tdew, pbub, pdew _Dlbub.value, _Dvdew.value = Dlbub, Dvdew _var1.value, _var2.value = var1, var2 _routine.value = routine.upper().encode('ascii') _rpabfl2_(byref(_var1), byref(_var2), _x, byref(_kq), byref(_ksat), byref(_routine), byref(_tbub), byref(_tdew), byref(_pbub), byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew, byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(2), c_long(255)) #define various x values xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x'] xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x'] xdew = normalize([_xdew[each] for each in range(_nc_rec.record)])['x'] xbub = normalize([_xbub[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xliq): xliq = [xliq[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xvap): xvap = [xvap[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xdew): xdew = [xdew[_purefld_rec.record['icomp'] - 1]] if len(x) != len(xbub): xbub = [xbub[_purefld_rec.record['icomp'] - 1]] #Dvap and Dliq Dvap, Dliq = _Dvap.value, _Dliq.value #define q if routine.upper()[1] == 'Q': q = var2 else: q = _q.value #calculate D if routine.upper()[1] == 'D': D = var2 else: if Dliq == 0: D = Dvap elif Dvap == 0: D = Dliq else: D = 1 / (((1 / Dvap) * q) + ((1 / Dliq) * (1 - q))) #raise error if routine input is incorrect if not routine.upper()[0] in 'PT': raise RefpropinputError('Incorrect "routine" input, ' + str(routine) + ' is an invalid input') if not routine.upper()[1] in 'DEHSQ': raise RefpropinputError('Incorrect "routine" input, ' + str(routine) + ' is an invalid input') #return correction on the first input variable if routine.upper()[0] == 'P': #return correction on the second input variable if routine.upper()[1] == 'S': return _prop(x = x, t = _t.value, p = var1, s = var2, D = D, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, tbub = _tbub.value, tdew = _tdew.value, defname = defname) elif routine.upper()[1] == 'H': return _prop(x = x, t = _t.value, p = var1, h = var2, D = D, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, tbub = _tbub.value, tdew = _tdew.value, defname = defname) elif routine.upper()[1] == 'D': return _prop(x = x, t = _t.value, p = var1, D = var2, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, tbub = _tbub.value, tdew = _tdew.value, defname = defname) elif routine.upper()[1] == 'E': return _prop(x = x, t = _t.value, p = var1, e = var2, D = D, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, tbub = _tbub.value, tdew = _tdew.value, defname = defname) elif routine.upper()[1] == 'Q': return _prop(x = x, t = _t.value, p = var1, D = D, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, tbub = _tbub.value, tdew = _tdew.value, defname = defname) elif routine.upper()[0] == 'T': #return correction on the second input variable if routine.upper()[1] == 'S': return _prop(x = x, t = var1, p = _p.value, s = var2, D = D, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, defname = defname) elif routine.upper()[1] == 'H': return _prop(x = x, t = var1, p = _p.value, h = var2, D = D, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, defname = defname) elif routine.upper()[1] == 'D': return _prop(x = x, t = var1, p = _p.value, D = var2, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, defname = defname) elif routine.upper()[1] == 'E': return _prop(x = x, t = var1, p = _p.value, e = var2, D = D, q = q, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, defname = defname) elif routine.upper()[1] == 'Q': return _prop(x = x, t = var1, p = _p.value, D = D, q = var2, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub, xvap = xvap, ksat = ksat, kq = kq, ierr = _ierr.value, herr = _herr.value, pbub = _pbub.value, pdew = _pdew.value, Dlbub = _Dlbub.value, Dvdew = _Dvdew.value, xdew = xdew, defname = defname) def info(icomp=1): '''Provides fluid constants for specified component input: icomp--component number in mixture; 1 for pure fluid outputs: wmm--molecular weight [g/mol] ttrp--triple point temperature [K] tnbpt--normal boiling point temperature [K] tcrit--critical temperature [K] pcrit--critical pressure [kPa] Dcrit--critical density [mol/L] zcrit--compressibility at critical point [pc/(Rgas*Tc*Dc)] acf--accentric factor [-] dip--dipole moment [debye] Rgas--gas constant [J/mol-K]''' _inputerrorcheck(locals()) _icomp.value = icomp _rpinfo_(byref(_icomp), byref(_wmm), byref(_ttrp), byref(_tnbpt), byref(_tcrit), byref(_pcrit), byref(_Dcrit), byref(_zcrit), byref(_acf), byref(_dip), byref(_Rgas)) return _prop(icomp = icomp, wmm = _wmm.value, ttrp = _ttrp.value, tnbpt = _tnbpt.value, tcrit = _tcrit.value, Dcrit = _Dcrit.value, zcrit = _zcrit.value, acf = _acf.value, dip = _dip.value, Rgas = _Rgas.value) def rmix2(x): '''Return the gas "constant" as a combination of the gas constants for the pure fluids inputs: x--composition [array of mol frac] outputs: Rgas--gas constant [J/mol-K]''' _inputerrorcheck(locals()) for each in range(len(x)): _x[each] = x[each] _rprmix2_(_x, byref(_Rgas)) return _prop(x = x, Rgas = _Rgas.value) def xmass(x): '''Converts composition on a mole fraction basis to mass fraction input: x--composition array [array of mol frac] outputs: xkg--composition array [array of mass frac] wmix--molar mass of the mixture [g/mol], a.k.a. "molecular weight"''' _inputerrorcheck(locals()) for each in range(len(x)): _x[each] = x[each] _rpxmass_(_x, _xkg, byref(_wmix)) xkg = normalize([_xkg[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(x) == 1: if len(x) != len(xkg): xkg = [xkg[_purefld_rec.record['icomp'] - 1]] return _prop(x = x, xkg = xkg, wmix = _wmix.value) def xmole(xkg): '''Converts composition on a mass fraction basis to mole fraction input: xkg--composition array [array of mass frac] outputs: x--composition array [array of mol frac] wmix--molar mass of the mixture [g/mol], a.k.a. "molecular weight"''' _inputerrorcheck(locals()) for each in range(len(xkg)): _xkg[each] = xkg[each] _rpxmole_(_xkg, _x, byref(_wmix)) x = normalize([_x[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and len(xkg) == 1: if len(xkg) != len(x): x = [x[_purefld_rec.record['icomp'] - 1]] return _prop(xkg = xkg, x = x, wmix = _wmix.value) def limitx(x, htype='EOS', t=0, D=0, p=0): '''returns limits of a property model as a function of composition and/or checks input t, D, p against those limits Pure fluid limits are read in from the .FLD files; for mixtures, a simple mole fraction weighting in reduced variables is used. Attempting calculations below the mininum temperature and/or above the maximum density will result in an error. These will often correspond to a physically unreasonable state; also many equations of state do not extrapolate reliably to lower T's and higher D's. A warning is issued if the temperature is above the maximum but below 1.5 times the maximum; similarly pressures up to twice the maximum result in only a warning. Most equations of state may be extrapolated to higher T's and P's. Temperatures and/or pressures outside these extended limits will result in an error. When calling with an unknown temperature, set t to -1 to avoid performing the melting line check inputs: x--composition array [mol frac] htype--flag indicating which models are to be checked [character*3] 'EOS': equation of state for thermodynamic properties 'ETA': viscosity 'TCX': thermal conductivity 'STN': surface tension t--temperature [K] D--molar density [mol/L] p--pressure [kPa] N.B.--all inputs must be specified, if one or more are not available, (or not applicable as in case of surface tension) use reasonable values, such as: t = tnbp D = 0 p = 0 outputs: tmin--minimum temperature for model specified by htyp [K] tmax--maximum temperature [K] Dmax--maximum density [mol/L] pmax--maximum pressure [kPa]''' _inputerrorcheck(locals()) _htype.value = htype.upper().encode('ascii') for each in range(len(x)): _x[each] = x[each] _t.value, _D.value, _p.value = t, D, p _rplimitx_(byref(_htype), byref(_t), byref(_D), byref(_p), _x, byref(_tmin), byref(_tmax), byref(_Dmax), byref(_pmax), byref(_ierr), byref(_herr), c_long(3), c_long(255)) return _prop(x = x, t = t, D = D, htype = htype.upper(), p = p, tmin = _tmin.value, tmax = _tmax.value, Dmax = _Dmax.value, pmax = _pmax.value, ierr = _ierr.value, herr = _herr.value, defname = 'limitx') def limitk(htype='EOS', icomp=1, t='tnbp', D=0, p=0): '''Returns limits of a property model (read in from the .FLD files) for a mixture component and/or checks input t, D, p against those limits This routine functions in the same manner as LIMITX except that the composition x is replaced by the component number icomp. Attempting calculations below the minimum temperature and/or above the maximum density will result in an error. These will often correspond to a physically unreasonable state; also many equations of state do not extrapolate reliably to lower T's and higher D's. A warning is issued if the temperature is above the maximum but below 1.5 times the maximum; similarly pressures up to twice the maximum result in only a warning. Most equations of state may be extrapolated to higher T's and P's. Temperatures and/or pressures outside these extended limits will result in an error. inputs: htyp--flag indicating which models are to be checked [character*3] 'EOS': equation of state for thermodynamic properties 'ETA': viscosity 'TCX': thermal conductivity 'STN': surface tension icomp--component number in mixture; 1 for pure fluid t--temperature [K] D--molar density [mol/L] p--pressure [kPa] N.B.--all inputs must be specified, if one or more are not available, (or not applicable as in case of surface tension) use reasonable values, such as: t = tnbp (normal boiling point temperature) D = 0 p = 0 outputs: tmin--minimum temperature for model specified by htyp [K] tmax--maximum temperature [K] Dmax--maximum density [mol/L] pmax--maximum pressure [kPa]''' if t == 'tnbp': t = info(icomp)['tnbpt'] _inputerrorcheck(locals()) _htype.value = htype.upper().encode('ascii') _icomp.value = icomp _t.value, _D.value, _p.value = t, D, p _rplimitk_(byref(_htype), byref(_icomp), byref(_t), byref(_D), byref(_p), byref(_tmin), byref(_tmax), byref(_Dmax), byref(_pmax), byref(_ierr), byref(_herr), c_long(3), c_long(255)) return _prop(icomp = icomp, t = t, D = D, htype = htype.upper(), p = p, tmin = _tmin.value, tmax = _tmax.value, Dmax = _Dmax.value, pmax = _pmax.value, ierr = _ierr.value, herr = _herr.value, defname = 'limitl') def limits(x, htype='EOS'): '''Returns limits of a property model as a function of composition. Pure fluid limits are read in from the .FLD files; for mixtures, a simple mole fraction weighting in reduced variables is used. inputs: htype--flag indicating which models are to be checked [character*3] 'EOS': equation of state for thermodynamic properties 'ETA': viscosity 'TCX': thermal conductivity 'STN': surface tension x--composition array [mol frac] outputs: tmin--minimum temperature for model specified by htyp [K] tmax--maximum temperature [K] Dmax--maximum density [mol/L] pmax--maximum pressure [kPa]''' _inputerrorcheck(locals()) _htype.value = htype.upper().encode('ascii') for each in range(len(x)): _x[each] = x[each] _rplimits_(byref(_htype), _x, byref(_tmin), byref(_tmax), byref(_Dmax), byref(_pmax), c_long(3)) return _prop(x = x, htype = htype.upper(), tmin = _tmin.value, tmax = _tmax.value, Dmax = _Dmax.value, pmax = _pmax.value) def qmass(q, xliq, xvap): '''converts quality and composition on a mole basis to a mass basis inputs: q--molar quality [moles vapor/total moles] qmol = 0 indicates saturated liquid qmol = 1 indicates saturated vapor 0 < qmol < 1 indicates a two-phase state mol < 0 or qmol > 1 are not allowed and will result in warning xliq--composition of liquid phase [array of mol frac] xvap--composition of vapor phase [array of mol frac] outputs: qkg--quality on mass basis [mass of vapor/total mass] xlkg--mass composition of liquid phase [array of mass frac] xvkg--mass composition of vapor phase [array of mass frac] wliq--molecular weight of liquid phase [g/mol] wvap--molecular weight of vapor phase [g/mol]''' _inputerrorcheck(locals()) _q.value = q for each in range(len(xliq)): _xliq[each] = xliq[each] for each in range(len(xvap)): _xvap[each] = xvap[each] _rpqmass_(byref(_q), _xliq, _xvap, byref(_qkg), _xlkg, _xvkg, byref(_wliq), byref(_wvap), byref(_ierr), byref(_herr), c_long(255)) xlkg = normalize([_xlkg[each] for each in range(_nc_rec.record)])['x'] xvkg = normalize([_xvkg[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and (len(xliq) == 1 or len(xvap) == 1): if len(xliq) != len(xlkg): xlkg = [xlkg[_purefld_rec.record['icomp'] - 1]] if len(xvap) != len(xvkg): xvkg = [xvkg[_purefld_rec.record['icomp'] - 1]] return _prop(q = q, xliq = xliq, xvap = xvap, qkg = _qkg.value, xlkg = xlkg, xvkg = xvkg, wliq = _wliq.value, wvap = _wvap.value, ierr = _ierr.value, herr = _herr.value, defname = 'qmass') def qmole(qkg, xlkg, xvkg): '''Converts quality and composition on a mass basis to a molar basis. inputs: qkg--quality on mass basis [mass of vapor/total mass] qkg = 0 indicates saturated liquid qkg = 1 indicates saturated vapor 0 < qkg < 1 indicates a two-phase state qkg < 0 or qkg > 1 are not allowed and will result in warning xlkg--mass composition of liquid phase [array of mass frac] xvkg--mass composition of vapor phase [array of mass frac] outputs: q--quality on mass basis [mass of vapor/total mass] xliq--molar composition of liquid phase [array of mol frac] xvap--molar composition of vapor phase [array of mol frac] wliq--molecular weight of liquid phase [g/mol] wvap--molecular weight of vapor phase [g/mol]''' _inputerrorcheck(locals()) _qkg.value = qkg for each in range(len(xlkg)): _xlkg[each] = xlkg[each] for each in range(len(xvkg)): _xvkg[each] = xvkg[each] _rpqmole_(byref(_qkg), _xlkg, _xvkg, byref(_q), _xliq, _xvap, byref(_wliq), byref(_wvap), byref(_ierr), byref(_herr), c_long(255)) xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x'] xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x'] if '_purefld_rec' in _Setuprecord.object_list \ and (len(xlkg) == 1 or len(xvkg) == 1): if len(xlkg) != len(xliq): xliq = [xliq[_purefld_rec.record['icomp'] - 1]] if len(xvkg) != len(xvap): xvap = [xvap[_purefld_rec.record['icomp'] - 1]] return _prop(qkg = qkg, xlkg = xlkg, xvkg = xvkg, q = _q.value, xliq = xliq, xvap = xvap, wliq = _wliq.value, wvap = _wvap.value, ierr = _ierr.value, herr = _herr.value, defname = 'qmole') def wmol(x): '''Molecular weight for a mixture of specified composition input: x--composition array [array of mol frac] output (as function value): wmix--molar mass [g/mol], a.k.a. "molecular weight''' _inputerrorcheck(locals()) for each in range(len(x)): _x[each] = x[each] _rpwmoldll_(_x, byref(_wmix)) return _prop(x = x, wmix = _wmix.value) def dielec(t, D, x): '''Compute the dielectric constant as a function of temperature, density, and composition. inputs: t--temperature [K] d--molar density [mol/L] x--composition [array of mol frac] output: de--dielectric constant''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpdielec_(byref(_t), byref(_D), _x, byref(_de)) return _prop(x = x, t = t, D= D, de = _de.value) def surft(t, x): '''Compute surface tension inputs: t--temperature [K] x--composition [array of mol frac] (liquid phase input only) outputs: D--molar density of liquid phase [mol/L] if D > 0 use as input value < 0 call SATT to find density sigma--surface tension [N/m]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpsurft_(byref(_t), byref(_D), _x, byref(_sigma), byref(_ierr), byref(_herr), c_long(255)) return _prop(x = x, t = t, D = _D.value, sigma = _sigma.value, ierr = _ierr.value, herr = _herr.value, defname = 'surft') def surten(t, Dliq, Dvap, xliq, xvap): '''Compute surface tension inputs: t--temperature [K] Dliq--molar density of liquid phase [mol/L] Dvap--molar density of vapor phase [mol/L] if either Dliq or Dvap < 0 call SATT to find densities xliq--composition of liquid phase [array of mol frac] xvap--composition of liquid phase [array of mol frac] (xvap is optional input if Dliq < 0 or Dvap < 0) outputs: sigma--surface tension [N/m]''' _inputerrorcheck(locals()) _t.value, _Dliq.value, _Dvap.value = t, Dliq, Dvap for each in range(len(xliq)): _xliq[each] = xliq[each] for each in range(len(xvap)): _xvap[each] = xvap[each] _rpsurten_(byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_sigma), byref(_ierr), byref(_herr), c_long(255)) return _prop(t = t, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xvap = xvap, sigma = _sigma.value, ierr = _ierr.value, herr = _herr.value, defname = 'surten') def meltt(t, x): '''Compute the melting line pressure as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] output: p--melting line pressure [kPa] Caution if two valid outputs the function will returns the highest''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpmeltt_(byref(_t), _x, byref(_p), byref(_ierr), byref(_herr), c_long(255)) return _prop(t = t, x = x, p = _p.value, ierr = _ierr.value, herr = _herr.value, defname = 'meltt') def meltp(p, x): '''Compute the melting line temperature as a function of pressure and composition. inputs: p--melting line pressure [kPa] x--composition [array of mol frac] output: t--temperature [K]''' _inputerrorcheck(locals()) _p.value = p for each in range(len(x)): _x[each] = x[each] _rpmeltp_(byref(_p), _x, byref(_t), byref(_ierr), byref(_herr), c_long(255)) return _prop(p = p, x = x, t = _t.value, ierr = _ierr.value, herr = _herr.value, defname = 'meltp') def sublt(t, x): '''Compute the sublimation line pressure as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] output: p--sublimation line pressure [kPa]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpsublt_(byref(_t), _x, byref(_p), byref(_ierr), byref(_herr), c_long(255)) return _prop(t = t, x = x, p = _p.value, ierr = _ierr.value, herr = _herr.value, defname = 'sublt') def sublp(p, x): '''Compute the sublimation line temperature as a function of pressure and composition. inputs: p--melting line pressure [kPa] x--composition [array of mol frac] output: t--temperature [K]''' _inputerrorcheck(locals()) _p.value = p for each in range(len(x)): _x[each] = x[each] _rpsublp_(byref(_p), _x, byref(_t), byref(_ierr), byref(_herr), c_long(255)) return _prop(p = p, x = x, t = _t.value, ierr = _ierr.value, herr = _herr.value, defname = 'sublp') def trnprp(t, D, x): '''Compute the transport properties of thermal conductivity and viscosity as functions of temperature, density, and composition inputs: t--temperature [K] D--molar density [mol/L] x--composition array [mol frac] outputs: eta--viscosity (uPa.s) tcx--thermal conductivity (W/m.K)''' _inputerrorcheck(locals()) _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rptrnprp_(byref(_t), byref(_D), _x, byref(_eta), byref(_tcx), byref(_ierr), byref(_herr), c_long(255)) return _prop(x = x, D = D, t = t, eta = _eta.value, tcx = _tcx.value, ierr = _ierr.value, herr = _herr.value, defname = 'trnprp') def getktv(icomp, jcomp): '''Retrieve mixture model and parameter info for a specified binary This subroutine should not be called until after a call to SETUP. inputs: icomp--component i jcomp--component j outputs: hmodij--mixing rule for the binary pair i,j (e.g. LJ1 or LIN) [character*3] fij--binary mixture parameters [array of dimension nmxpar; currently nmxpar is set to 6]; the parameters will vary depending on hmodij; hfmix--file name [character*255] containing parameters for the binary mixture model hfij--description of the binary mixture parameters [character*8 array of dimension nmxpar] for example, for the Lemmon-Jacobsen model (LJ1): fij(1) = zeta fij(2) = xi fij(3) = Fpq fij(4) = beta fij(5) = gamma fij(6) = 'not used' hbinp--documentation for the binary parameters [character*255] terminated with ASCII null character hmxrul--description of the mixing rule [character*255]''' _inputerrorcheck(locals()) _icomp.value, _jcomp.value = icomp, jcomp _rpgetktv_(byref(_icomp), byref(_jcomp), byref(_hmodij), _fij, byref(_hfmix), _hfij, byref(_hbinp), byref(_hmxrul), c_long(3), c_long(255), c_long(8), c_long(255), c_long(255)) return _prop(icomp = icomp, jcomp = jcomp, hmodij = _hmodij.value.decode('utf-8'), fij = [_fij[each] for each in range(_nmxpar)], hfmix = _hfmix.value.decode('utf-8'), hbinp = _hbinp.value.decode('utf-8').rstrip(), hmxrul = _hmxrul.value.decode('utf-8').rstrip(), #correction on system error #hfij = [_hfij[each].value.decode('utf-8').strip() # for each in range(_nmxpar)]) hfij = [_hfij[0].value.decode('utf-8')[each * 8: each * 8 + 8].strip() for each in range(_nmxpar)]) def getmod(icomp, htype): '''Retrieve citation information for the property models used inputs: icomp--pointer specifying component number zero and negative values are used for ECS reference fluid(s) htype--flag indicating which model is to be retrieved [character*3] 'EOS': equation of state for thermodynamic properties 'CP0': ideal part of EOS (e.g. ideal-gas heat capacity) 'ETA': viscosity 'VSK': viscosity critical enhancement 'TCX': thermal conductivity 'TKK': thermal conductivity critical enhancement 'STN': surface tension 'DE ': dielectric constant 'MLT': melting line (freezing line, actually) 'SBL': sublimation line 'PS ': vapor pressure equation 'DL ': saturated liquid density equation 'DV ': saturated vapor density equation outputs: hcode--component model used for property specified in htype some possibilities for thermodynamic properties: 'FEQ': Helmholtz free energy model 'BWR': pure fluid modified Benedict-Webb-Rubin (MBWR) 'ECS': pure fluid thermo extended corresponding states some possibilities for viscosity: 'ECS': extended corresponding states (all fluids) 'VS1': the 'composite' model for R134a, R152a, NH3, etc. 'VS2': Younglove-Ely model for hydrocarbons 'VS4': generalized friction theory of Quinones-Cisneros and Dieters 'VS5': Chung et al model some possibilities for thermal conductivity: 'ECS': extended corresponding states (all fluids) 'TC1': the 'composite' model for R134a, R152a, etc. 'TC2': Younglove-Ely model for hydrocarbons 'TC5': predictive model of Chung et al. (1988) some possibilities for surface tension: 'ST1': surface tension as f(tau); tau = 1 - T/Tc hcite--component model used for property specified in htype; the first 3 characters repeat the model designation of hcode and the remaining are the citation for the source''' _inputerrorcheck(locals()) _icomp.value, _htype.value = icomp, htype.upper().encode('ascii') _rpgetmod_(byref(_icomp), byref(_htype), byref(_hcode), byref(_hcite), c_long(3), c_long(3), c_long(255)) return _prop(icomp = icomp, htype = htype, hcode = _hcode.value.decode('utf-8'), hcite = _hcite.value.decode('utf-8').rstrip()) def setktv(icomp, jcomp, hmodij, fij=([0] * _nmxpar), hfmix='HMX.BNC'): '''Set mixture model and/or parameters This subroutine must be called after SETUP, but before any call to SETREF; it need not be called at all if the default mixture parameters (those read in by SETUP) are to be used. inputs: icomp--component jcomp--component j hmodij--mixing rule for the binary pair i,j [character*3] e.g.: 'LJ1' (Lemmon-Jacobsen model) 'LM1' (modified Lemmon-Jacobsen model) or 'LIN' (linear mixing rules) 'RST' indicates reset all pairs to values from original call to SETUP (i.e. those read from file) [all other inputs are ignored] fij--binary mixture parameters [array of dimension nmxpar; currently nmxpar is set to 6] the parameters will vary depending on hmodij; for example, for the Lemmon-Jacobsen model (LJ1): fij(1) = zeta fij(2) = xi fij(3) = Fpq fij(4) = beta fij(5) = gamma fij(6) = 'not used' hfmix--file name [character*255] containing generalized parameters for the binary mixture model; this will usually be the same as the corresponding input to SETUP (e.g.,':fluids:HMX.BNC')''' global _setktv_rec, _fpath, _setupprop #verify multiple model calls _checksetupmodel('setktv') _inputerrorcheck(locals()) #define setup record for FluidModel if hmodij.upper() != 'RST': _setktv_rec = _Setuprecord(copy(locals()), '_setktv_rec') _icomp.value, _jcomp.value = icomp, jcomp _hmodij.value = hmodij.upper().encode('ascii') if hfmix == 'HMX.BNC': _hfmix.value = (_fpath + 'fluids/HMX.BNC').encode('ascii') else: _hfmix.value = hfmix.encode('ascii') for each in range(_nmxpar): _fij[each] = fij[each] _rpsetktv_(byref(_icomp), byref(_jcomp), byref(_hmodij), _fij, byref(_hfmix), byref(_ierr), byref(_herr), c_long(3), c_long(255), c_long(255)) if hmodij.upper() != 'RST': stktv = {} stktv['icomp'] = icomp stktv['jcomp'] = jcomp stktv['hmodij'] = hmodij.upper() stktv['fij'] = fij stktv['hfmix'] = hfmix _setupprop['setktv'] = stktv elif hmodij.upper() == 'RST': if 'setktv' in _setupprop: _setupprop.__delitem__('setktv') if '_setktv_rec' in _Setuprecord.object_list: _setktv_rec = None return _prop(ierr = _ierr.value, herr = _herr.value, defname = 'setktv') def setaga(): '''Set up working arrays for use with AGA8 equation of state. input: none outputs: none''' global _setaga_rec, _setupprop #verify multiple model calls _checksetupmodel('setaga') #define setup record for FluidModel _setaga_rec = _Setuprecord(copy(locals()), '_setaga_rec') _rpsetaga_(byref(_ierr), byref(_herr), c_long(255)) _setupprop['setaga'] = True return _prop(ierr = _ierr.value, herr = _herr.value, defname = 'setaga') def unsetaga(): '''Load original values into arrays changed in the call to SETAGA. This routine resets the values back to those loaded when SETUP was called.''' global _setaga_rec, _setupprop _rpunsetaga_() if 'setaga' in _setupprop: _setupprop.__delitem__('setaga') if '_setaga_rec' in _Setuprecord.object_list: _setaga_rec = None return _prop() def preos(ixflag=0): '''Turn on or off the use of the PR cubic equation. inputs: ixflag--flag specifying use of PR: 0 - Use full equation of state (Peng-Robinson off) 1 - Use full equation of state with Peng-Robinson for sat. conditions (not currently working) 2 - Use Peng-Robinson equation for all calculations -1 - return value with current usage of PR: 0, 1, or 2.''' #return value gives error return on preos global _preos_rec, _setupprop #verify multiple model calls _checksetupmodel('preos') _inputerrorcheck(locals()) _ixflag.value = ixflag _rppreos_(byref(_ixflag)) #return settings if ixflag == -1: #some unknown reason the value is less 2*32 return _ixflag.value + 2**32 #reset all preos values elif ixflag == 0: if 'preos' in _setupprop: _setupprop.__delitem__('preos') if '_preos_rec' in _Setuprecord.object_list: _preos_rec = None else: _setupprop['preos'] = ixflag #define setup record for FluidModel _preos_rec = _Setuprecord({'ixflag':ixflag}, '_preos_rec') return _prop() def getfij(hmodij): '''Retrieve parameter info for a specified mixing rule This subroutine should not be called until after a call to SETUP. inputs: hmodij--mixing rule for the binary pair i,j (e.g. LJ1 or LIN) [character*3] outputs: fij--binary mixture parameters [array of dimension nmxpar; currently nmxpar is set to 6]; the parameters will vary depending on hmodij; hfij--description of the binary mixture parameters [character*8 array of dimension nmxpar] hmxrul--description of the mixing rule [character*255]''' _inputerrorcheck(locals()) _hmodij.value = hmodij.upper().encode('ascii') _rpgetfij_(byref(_hmodij), _fij, _hfij, byref(_hmxrul), c_long(3), c_long(8), c_long(255)) return _prop(hmodij = hmodij.upper(), fij = [_fij[each] for each in range(_nmxpar)], hmxrul = _hmxrul.value.decode('utf-8').rstrip(), #correction on system error #hfij = [_hfij[each].value.decode('utf-8').strip() # for each in range(_nmxpar)]) hfij = [_hfij[0].value.decode('utf-8')[each * 8:each * 8 + 8].strip() for each in range(_nmxpar)]) def b12(t, x): '''Compute b12 as a function of temperature and composition. inputs: t--temperature [K] x--composition [array of mol frac] outputs: b--b12 [(L/mol)^2]''' _inputerrorcheck(locals()) _t.value = t for each in range(len(x)): _x[each] = x[each] _rpb12_(byref(_t), _x, byref(_b)) return _prop(t = t, x = x, b = _b.value) def excess(t, p, x, kph=0): '''Compute excess properties as a function of temperature, pressure, and composition. NOT supported on Windows inputs: t--temperature [K] p--pressure [kPa] x--composition [array of mol frac] kph--phase flag: 1 = liquid 2 = vapor 0 = stable phase outputs: D--molar density [mol/L] (if input less than 0, used as initial guess) vE--excess volume [L/mol] eE--excess energy [J/mol] hE--excess enthalpy [J/mol] sE--excess entropy [J/mol-K] aE--excess Helmholtz energy [J/mol] gE--excess Gibbs energy [J/mol]''' _inputerrorcheck(locals()) _t.value, _p.value, _kph.value = t, p, kph for each in range(len(x)): _x[each] = x[each] _rpexcess_(byref(_t), byref(_p), _x, byref(_kph), byref(_D), byref(_vE), byref(_eE), byref(_hE), byref(_sE), byref(_aE), byref(_gE), byref(_ierr), byref(_herr), c_long(255)) return _prop(t = t, p = p, x = x, kph = kph, D = _D.value, vE = _vE.value, eE = _eE.value, hE = _hE.value, sE = _sE.value, aE = _aE.value, gE = _gE.value, ierr = _ierr.value, herr = _herr.value, defname = 'excess') def phiderv(iderv, t, D, x): '''Calculate various derivatives needed for VLE determination based on derivations in the GERG-2004 document for natural gas inputs: iderv: set to 1 for first order derivatives only (dadn and dnadn)#### set to 2 for full calculations### t--temperature (K) D--density (mol/L) x--composition [array of mol frac] outputs: (where n is mole number, the listed equation numbers are those in the GERG manuscript) dnadn--partial(n*alphar)/partial(ni) Eq. 7.15 dadn--n*partial(alphar)/partial(ni) Eq. 7.16 daddn--del*n*par.(par.(alphar)/par.(del))/par.(ni) Eq. 7.17 dvdn--n*[partial(Vred)/partial(ni)]/Vred Eq. 7.18 (=-n*[partial(Dred)/partial(ni)]/Dred) dtdn--n*[partial(Tred)/partial(ni)]/Tred Eq. 7.19 dadxi--partial(alphar)/partial(xi) Eq. 7.21g sdadxi--sum[xi*partial(alphar)/partial(xi)] Eq. 7.21g dadxij--partial^2(alphar)/partial(xi)/partial(xj) Eq. 7.21i daddx--del*partial^2(alphar)/partial(xi)/partial(del) Eq. 7.21j dadtx--tau*partial^2(alphar)/partial(xi)/partial(tau) Eq. 7.21k dphidT--par.(ln(phi))/par.(T) (constant p,n,x) Eq. 7.29 dphidp--par.(ln(phi))/par.(p) (constant T,n,x) Eq. 7.30 dphidnj--n*par.[ln(phi(i))]/par(nj) (constant T,p) Eq. 7.31 dlnfinidT--par.[ln(fi/ni)]/par(T) Eq. 7.36 dlnfinidV--n*par.[ln(fi/ni)]/par(V) Eq. 7.37 d2adbn-- par.[par.(n*alphar)/par.(ni)]/par.(T) Eq. 7.44 d2adnn--n*partial^2(n*alphar)/partial(ni)/partial(nj) Eq. 7.46 and 7.47 (similar to 7.38) d2addn--del*par.[n*par.(alphar)/par.(ni)]/par.(del) Eq. 7.50 d2adtn--tau*par.[n*par.(alphar)/par.(ni)]/par.(tau) Eq. 7.51 d2adxn-- par.[n*par.(alphar)/par.(ni)]/par.(xj) Eq. 7.52 other calculated variables: ddrdxn--par.[n*par.(Dred)/par.(ni)]/par.(xj) Eq. 7.55 dtrdxn--par.[n*par.(Tred)/par.(ni)]/par.(xj) Eq. 7.56 dpdn--n*partial(p)/partial(ni) Eq. 7.63 constant T,V,nj dpdxi--partial(p)/partial(xi) constant T,V d2adxnTV--par.[n*par.(alphar)/par.(ni)]/par.(xj) constant T,V dadxiTV--partial(alphar)/partial(xi) constant T,V daddxiTV--del*partial^2(alphar)/partial(xi)/partial(del)constant T,V dphidxj--par.(ln(phi))/par.(xj) constant T,p,x xlnfi--Log of modified fugacity''' _inputerrorcheck(locals()) _iderv.value = iderv _t.value, _D.value = t, D for each in range(len(x)): _x[each] = x[each] _rpphiderv_(byref(_iderv), byref(_t), byref(_D), _x, _dadn, _dnadn, byref(_ierr), byref(_herr), c_long(255)) dadn = [_dadn[each] for each in range(_nc_rec.record)] dnadn = [_dnadn[each] for each in range(_nc_rec.record)] return _prop(iderv = iderv, t = t, D = D, x = x, dnadn = dnadn, dadn = dadn, ierr = _ierr.value, herr = _herr.value, defname = 'phinderv') def cstar(t, p, v, x): '''Calculate the critical flow factor, C*, for nozzle flow of a gas (subroutine was originally named CCRIT) inputs: t--temperature [K] p--pressure [kPa] v--plenum velocity [m/s] (should generally be set to 0 for calculating stagnation conditions) x--composition [array of mol frac] outputs: cs--critical flow factor [dimensionless] ts--nozzle throat temperature [K] Ds--nozzle throat molar density [mol/L] ps--nozzle throat pressure [kPa] ws--nozzle throat speed of sound [m/s]''' _inputerrorcheck(locals()) _v.value = v _t.value, _p.value = t, p for each in range(len(x)): _x[each] = x[each] _rpcstar_(byref(_t), byref(_p), byref(_v), _x, byref(_cs), byref(_ts), byref(_Ds), byref(_ps), byref(_ws), byref(_ierr), byref(_herr), c_long(255)) return _prop(t = t, p = p, v = v, x = x, cs = _cs.value, ts = _ts.value, Ds = _Ds.value, ps = _ps.value, ws = _ws.value, ierr = _ierr.value, herr = _herr.value, defname = 'cstar') #compilations #missing to do #SATTP #CRTPNT #SATGV #MAXP #DERVPVT #DBDT2 #VIRBCD #HEAT """ subroutine SATTP (t,p,x,iFlsh,iGuess,d,Dl,Dv,xliq,xvap,q,ierr, & herr) c c Estimate temperature, pressure, and compositions to be used c as initial guesses to SATTP c c inputs: c iFlsh--Phase flag: 0 - Flash calculation (T and P known) c 1 - T and xliq known, P and xvap returned c 2 - T and xvap known, P and xliq returned c 3 - P and xliq known, T and xvap returned c 4 - P and xvap known, T and xliq returned c if this value is negative, the retrograde point will be returned c t--temperature [K] (input or output) c p--pressure [MPa] (input or output) c x--composition [array of mol frac] c iGuess--if set to 1, all inputs are used as initial guesses for the calculation c outputs: c d--overall molar density [mol/L] c Dl--molar density [mol/L] of saturated liquid c Dv--molar density [mol/L] of saturated vapor c xliq--liquid phase composition [array of mol frac] c xvap--vapor phase composition [array of mol frac] c q--quality c ierr--error flag: 0 = successful c 1 = unsuccessful c herr--error string (character*255 variable if ierr<>0) c c broutine CRTPNT (z,tc,pc,rhoc,ierr,herr) c c Subroutine for the determination of true critical point of a c mixture using the Method of Michelsen (1984) c c The routine requires good initial guess values of pc and tc. c On convergence, the values of bb and cc should be close to zero c and dd > 0 for a two-phase critical point. c bb=0, cc=0 and dd <= 0 for an unstable critical point. c c inputs: c z--composition [array of mol frac] c c outputs: c tc--critical temperature [K] c pc--critical pressure [kPa] c rhoc--critical density [mol/l] c ierr--error flag c herr--error string (character*255 variable if ierr<>0) c subroutine SATGV (t,p,z,vf,b,ipv,ityp,isp,rhox,rhoy,x,y,ierr,herr) c c Calculates the bubble or dew point state using the entropy or density method c of GV. The caculation method is similar to the volume based algorithm of GERG. c The cricondenbar and cricondentherm are estimated using the method in: M.L. c Michelsen, Saturation point calculations, Fluid Phase Equilibria, 23:181, 1985. c c inputs: c t--temperature [K] c p--pressure [kPa] c z--overall composition [array of mol frac] c vf--vapor fraction (0>=vf>=1) c set vf=0 for liquid and vf=1 for vapor c for ityp=6, vf=1 assumes x is liquid and y is vapor, c and vf=0 assumes y is liquid and x is vapor c b--input value, either entropy [J/mol-K] or density [mol/l] c ipv--pressure or volume based algorithm c 1 -> pressure based c 2 -> volume based c ityp--input values c 0 -> given p, calculate t c 1 -> given t, calculate p c 2 -> cricondentherm condition, calculate t,p (ipv=1 only) c 3 -> cricondenbar condition, calculate t,p (ipv=1 only) c 5 -> given entropy, calculate t,p c 6 -> given density, calculate t,p c isp--use values from Splines as initial guesses if set to 1 c c outputs: (initial guesses must be sent in all variables (unless isp=1)) c t--temperature [K] c p--pressure [kPa] c rhox--density of x phase [mol/l] c rhoy--density of y phase [mol/l] c x--composition of x array [array of mol frac] c y--composition of y array [array of mol frac] c ierr--error flag: 0 = successful c 1 = LUdecomp failed c 2 = derivatives are not available in RDXHMX c 71 = no convergence c 72 = log values too large c 73 = p or T out of range c 74 = trival solution c 75 = unacceptable F c 76 = False roots c 77 = density out of range c 80 = vf < 0 or vf > 1 c 81 = sum(z)<>1 c 82 = input rho<=0 c herr--error string (character*255 variable if ierr<>0) c c c equations to be solved simultaneously are: c --pressure based: c f(1:n)=log(y/x)-log((fxi/nxi)/(fyi/nyi))=0 c f(n+1)=sum(y(i)-x(i))=0 c f(n+2)=b/binput-1=0, where b = p, t, d, or s c c --volume based: c f(1:n) - log(y/x)-log((fxi/nxi)/(fyi/nyi))=0 c f(n+1) - sum(y(i)-x(i))=0 c f(n+2) - py=px c f(n+3) - b/binput-1=0, where b = p, t, d, or s c c variables: c 1 to nc - log(k(i)) c nc+1 - log(t) c nc+2 - log(p) or log(rhox) c nc+3 - log(rhoy) c subroutine MAXP (x,tm,pm,Dm,ierr,herr) c c values at the maximum pressure along the saturation line, these are c returned from the call to SATSPLN and apply only to the composition x c sent to SATSPLN. c c input: c x--composition [array of mol frac] c outputs: c tm--temperature [K] c pm--pressure [kPa] c Dm--density [mol/L] c ierr--error flag: 0 = successful c herr--error string (character*255 variable if ierr<>0) c subroutine DERVPVT (t,rho,x, & dPdD,dPdT,d2PdD2,d2PdT2,d2PdTD, & dDdP,dDdT,d2DdP2,d2DdT2,d2DdPT, & dTdP,dTdD,d2TdP2,d2TdD2,d2TdPD) c c compute derivatives of temperature, pressure, and density c using core functions for Helmholtz free energy equations only c c inputs: c t--temperature [K] c rho--molar density [mol/L] c x--composition [array of mol frac] c outputs: c dPdD--derivative dP/drho [kPa-L/mol] c dPdT--derivative dP/dT [kPa/K] c dDdP--derivative drho/dP [mol/(L-kPa)] c dDdT--derivative drho/dT [mol/(L-K)] c dTdP--derivative dT/dP [K/kPa] c dTdD--derivative dT/drho [(L-K)/mol] c d2PdD2--derivative d^2P/drho^2 [kPa-L^2/mol^2] c d2PdT2--derivative d2P/dT2 [kPa/K^2] c d2PdTD--derivative d2P/dTd(rho) [J/mol-K] subroutine DBDT2 (t,x,dbt2) c c compute the 2nd derivative of B (B is the second virial coefficient) with c respect to T as a function of temperature and composition. c c inputs: c t--temperature [K] c x--composition [array of mol frac] c outputs: c dbt2--2nd derivative of B with respect to T [L/mol-K^2] c subroutine VIRBCD (t,x,b,c,d) c c Compute virial coefficients as a function of temperature c and composition. The routine currently works only for pure fluids and c for the Helmholtz equation. c All values are computed exactly based on the terms in the eos, not c as done in VIRB by calculating properties at rho=1.d-8. c c inputs: c t--temperature [K] c x--composition [array of mol frac] c outputs: c b--second virial coefficient [l/mol] c c-- third virial coefficient [(l/mol)^2] c d--fourth virial coefficient [(l/mol)^3] c subroutine HEAT (t,rho,x,hg,hn,ierr,herr) c c Compute the ideal gas gross and net heating values. c c inputs: c t--temperature [K] c rho--molar density [mol/L] c x--composition [array of mol frac] c c outputs: c hg--gross (or superior) heating value [J/mol] c hn--net (or inferior) heating value [J/mol] c ierr--error flag: 0 = successful c 1 = error in chemical formula c 2 = not all heating values available c herr--error string (character*255 variable if ierr<>0) c """ if __name__ == '__main__': _test() #import profile #profile.run('_test()')
[ "noreply@github.com" ]
RaphaelGervaisLavoie.noreply@github.com
820fcbb59fcb12f681d3af5a64927c5a4fa8d240
3e4117cd55b73eaca9833950baf1a5e9c02c7739
/pythonclubapp/tests.py
f878c081fbae5d4b8a8f03fd904aadcb362c3515
[]
no_license
ppjjhh0515/ITC-172-Assignment-10
72abc315551b0b501d274c3723280638eb73d7d6
4ab381e8a4fa08c06dafd42cf625affe0210ad1a
refs/heads/master
2021-04-24T14:51:49.485990
2020-03-26T01:25:51
2020-03-26T01:25:51
250,131,283
0
0
null
null
null
null
UTF-8
Python
false
false
2,122
py
from django.test import TestCase from .models import Meeting, MeetingMinutes, Resource, Event # Create your tests here. class MeetingTest(TestCase): def test_string(self): type=Meeting(meetingtitle='Weekly team meeting') self.assertEqual(str(type), type.meetingtitle) def test_table(self): self.assertEqual(str(Meeting._meta.db_table), 'Meeting Name') class MeetingMinutesTest(TestCase): def test_string(self): type=MeetingMinutes(minutename='Interview Session') self.assertEqual(str(type), type.minutename) def test_table(self): self.assertEqual(str(MeetingMinutes._meta.db_table), 'Minute Name') class ResourceTest(TestCase): def test_string(self): type=Resource(resourcename='zoom') self.assertEqual(str(type), type.resourcename) def test_table(self): self.assertEqual(str(Resource._meta.db_table), 'Resource') class EventTest(TestCase): def test_string(self): type=Event(eventtitle='Board meeting') self.assertEqual(str(type), type.eventtitle) def test_table(self): self.assertEqual(str(Event._meta.db_table), 'Event') class New_Meeting_authentication_test(TestCase): def setUp(self): self.test_user=User.objects.create_user(username='testuser1', password='P@ssw0rd1') self.type=Meeting.objects.create(typename='testmeeting') self.md = Meeting.objects.create(meetingtitle='meeting1', meetingdate='2020-03-26', meetingtime='11:00', location='Seattle', agenda='fortesting') def test_redirect_if_not_logged_in(self): response=self.client.get(reverse('newMeeting')) self.assertRedirects(response, '/accounts/login/?next=/pythonclubapp/newMeeting/') def test_Logged_in_uses_correct_template(self): login=self.client.login(username='testuser1', password='P@ssw0rd1') response=self.client.get(reverse('newmeeting')) self.assertEqual(str(response.context['user']), 'testuser1') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'pythonclubapp/newmeeting.html')
[ "junghopark@Junghoui-MacBookPro.local" ]
junghopark@Junghoui-MacBookPro.local
636458db00bcc39eb9441aac4a51211715e8b496
eee10d85c99089a115664d377a4084d2a468355e
/exercises/ex20.py
8a72cf5adb8d2d0338b9c08922d9890fe94b0dc9
[]
no_license
girishkumarkh/python-workshop
3589654ceae0a4cdfece24419526dd439b03cfc7
bea862670a15ada59713de1b8120b7abde8f1742
refs/heads/master
2020-04-10T15:54:47.437850
2016-06-13T22:59:20
2016-06-13T22:59:20
21,092,494
0
0
null
null
null
null
UTF-8
Python
false
false
634
py
# Exercise 20: Functions and Files from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
[ "girishkumarkh@gmail.com" ]
girishkumarkh@gmail.com
57151cf7756f98812c554aba0234b269823b8459
81874a500500652324e8f4997a9420107f9d4d2e
/index_podcast/reports/views.py
99e78f087bffdd363da1e17f9c1a0b0b057629f7
[]
no_license
mishabeliy15/startup
23b10588bc95985b094321bedb1403e69397e1e3
d34ccc26fe95ab6ee6030a7fa5e1a496be45eb9f
refs/heads/master
2022-04-27T20:09:53.659394
2019-12-27T12:59:41
2019-12-27T12:59:41
189,312,750
0
0
null
2022-04-22T22:41:25
2019-05-29T23:28:00
HTML
UTF-8
Python
false
false
479
py
from django.views.generic import ListView from mypodcasts.models import Podcast, Episode from easy_pdf.views import PDFTemplateResponseMixin class PodcastHTMLView(ListView): model = Podcast template_name = 'reports/podcasts.html' class EpisodesView(ListView): model = Podcast template_name = 'reports/episodes.html' class PodcastsPdf(PDFTemplateResponseMixin, PodcastHTMLView): pass class EpisodesPDF(PDFTemplateResponseMixin, EpisodesView): pass
[ "misha.beliy15@gmail.com" ]
misha.beliy15@gmail.com
b2e14eec1e0c1bfd6420d5440f10d412656dc152
ce60a51c868e2073d419d74ac560d9d7c5d6b86b
/socketIO/socketcli3.py
29161315adab6211a715feb5c7b7e36463925fa2
[]
no_license
ramanraja/Home4
af2226bcae69a9482887d13ea25e6927dd934d7e
473fe422e8442a175bd332fac425162db5e66332
refs/heads/master
2023-02-14T17:57:16.769046
2021-01-07T18:37:50
2021-01-07T18:37:50
286,188,654
0
0
null
null
null
null
UTF-8
Python
false
false
1,905
py
# Python socket IO client through Nginx # Test it with socketser3.py # https://python-socketio.readthedocs.io/en/latest/client.html # sync client: pip install "python-socketio[client]" # Async client: pip install "python-socketio[asyncio_client]" import sys import socketio ##from time import sleep sio = socketio.Client() @sio.event def connect(): print ("Socket connected.") @sio.event def connect_error (payload): print ("Connection failed:") print (payload) @sio.event def disconnect(): print ("Socket disconnected.") @sio.event def message (payload): # built in event print ('Received message:') print (payload) sio.emit ('client-event', 'Got it!') @sio.on ('update-count') # custom event def on_counter (payload): print ('Received update-count event:') print (payload) @sio.on ('server-event') # custom event def on_server_event (payload): print ('Received server-event:') print (payload) #----------------------------------- # main #----------------------------------- connected = False PORT = 8000 # NOTE: this works through Nginx #PORT = 5000 # direct port url = 'http://localhost:{}'.format(PORT) print ('server URL: ', url) print ('Trying to connect to socket server..') while True: try: sio.connect (url) connected = True print ('Connected. SID= ', sio.sid) break; except KeyboardInterrupt: break except Exception: pass if not connected: print ('Connection failed.') sys.exit(0) print ('Waiting for server events..[^C to quit]') while True: try: sio.sleep (0.5) except KeyboardInterrupt: break # aliter: #sio.wait() sio.disconnect() print ('Bye!')
[ "noreply@github.com" ]
ramanraja.noreply@github.com
458e7d62bcf33adbfdaed761fb31e5a463c2ba99
2589c8398c107236cdc9ebf38d32da79d62cdf62
/maturanc/profil/migrations/0002_auto_20170207_1951.py
4c31201c752aca592f07f197a76a11d08be4f057
[]
no_license
jrizmal/maturanc
a7baf5fdb218b8b150d77f689a7628082ad8fbea
17400dc4b2bd3b503827a82fc82ad89dca9bb7ab
refs/heads/master
2021-01-11T09:09:53.007664
2017-02-24T17:23:18
2017-02-24T17:23:18
77,273,635
2
0
null
null
null
null
UTF-8
Python
false
false
506
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-07 18:51 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('profil', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='socialnaomrezja', name='google', ), migrations.RemoveField( model_name='socialnaomrezja', name='soundcloud', ), ]
[ "jrizmal@gmail.com" ]
jrizmal@gmail.com
b7ff03bfeb0f3c4ee4b5add07364b51fd0e52105
e14b357df0b8dc66bcc00690406121b57b09df79
/src/app/model/source_code.py
52308cd30736f72aae51828331ac072b886e0a07
[]
no_license
arthur-samarin/SoftwareDesignProject
102f295627651bdf710ea6ad9ee069057f8ff41f
9858fcb16d98c2e5950214d3c839c7ae2c2a4912
refs/heads/master
2020-04-06T15:33:46.678018
2018-12-08T00:39:50
2018-12-08T00:39:50
157,583,298
0
0
null
2018-12-05T15:48:05
2018-11-14T17:08:02
Python
UTF-8
Python
false
false
191
py
class SourceCode: def __init__(self, filename: str, code: bytes, language_name: str): self.filename = filename self.code = code self.language_name = language_name
[ "asamarin97@gmail.com" ]
asamarin97@gmail.com
6356c3fd54fe41f7cbafe1ee9e95d8bbc6ac1949
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/4/usersdata/106/2074/submittedfiles/swamee.py
76d128a83e81bb740dd88476ec555cd6abb8854e
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
544
py
# -*- coding: utf-8 -*- from __future__ import division import math #COMECE SEU CÓDIGO AQUI #entrada f = input ('Digite um valor para f: ') L = input ('Digite um valor para L: ') Q = input ('Digite um valor para Q: ') deltaH = input ('Digite um valor para deltaH: ') v = input ('Digite um valor para v: ') #processamento: g= 9.81 E = 0.000002 D = (( 8*f*L*(Q**2))/((math.pi**2)*g*deltaH))**0.2 Rey = (4*Q)/(math.pi*D*v) x = (E/(3.7*D)) + (5.74/(Rey**0.9)) k = 0.25 / (log10(x)**2 #saída print (D) print ( '%.4f' %Rey ) print ( '%.4f' %k )
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
b66800b5d03f8156fa96aa2312351ab92891d789
329761e079663d7eb6316d0836db7dc8abb7f756
/My Script Mods/WickedWhims_Scripts/Scripts/wickedwhims/nudity/nudity_privacy.py
eeab7ec3f19868ba84a78b7b87914d736ac46081
[]
no_license
ColonolNuttyFork/WickedWhims-lol-update
6feafede44b18a1c93d806865463300d26031c82
5f702be84458ceb233cb60728d439f3ce7c56f12
refs/heads/master
2023-03-15T15:55:27.197407
2018-06-21T21:26:48
2018-06-21T21:26:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,978
py
from enums.interactions_enum import SimInteraction from turbolib.events.privacy import PrivacyResult, register_privacy_sim_test_event_method from turbolib.interaction_util import TurboInteractionUtil from turbolib.math_util import TurboMathUtil from turbolib.privacy_util import TurboPrivacyUtil from turbolib.resource_util import TurboResourceUtil from turbolib.sim_util import TurboSimUtil from wickedwhims.nudity.nudity_settings import NuditySetting, get_nudity_setting from wickedwhims.nudity.permissions.test import has_sim_permission_for_nudity PRIVACY_NUDE_INTERACTIONS = (13073, 13076, 13084, 120340, 120341, 120342, 121575, 120339, 120337, 13087, 154400, 145422, 120336, 121573, 117263, 13950, 154397, 39965, 24332, 23839, 141926, 39860, 39845, 134251, 134250, 134165, 134534, 136684, 134609, 136718, 14427, 14428, 14434, SimInteraction.WW_MIRROR_ADMIRE_YOUR_BODY, 17681256309946806522) @register_privacy_sim_test_event_method(unique_id='WickedWhims', priority=1) def _wickedwhims_special_additional_los_test(privacy_instance, tested_sim): privacy_interaction = TurboPrivacyUtil.get_privacy_interaction(privacy_instance) if TurboResourceUtil.Resource.get_guid64(privacy_interaction) == SimInteraction.WW_MIRROR_ADMIRE_YOUR_BODY: sim = TurboInteractionUtil.get_interaction_sim(privacy_interaction) line_of_sight = TurboMathUtil.LineOfSight.create(TurboSimUtil.Location.get_routing_surface(sim), TurboSimUtil.Location.get_position(sim), 10.0) if not TurboPrivacyUtil.is_sim_allowed_by_privacy(tested_sim, privacy_instance) and TurboMathUtil.LineOfSight.test(line_of_sight, TurboSimUtil.Location.get_position(tested_sim)): return PrivacyResult.BLOCK return PrivacyResult.ALLOW return PrivacyResult.DEFAULT @register_privacy_sim_test_event_method(unique_id='WickedWhims', priority=2) def _wickedwhims_is_sim_allowed_for_nudity(privacy_instance, tested_sim): if get_nudity_setting(NuditySetting.NUDITY_PRIVACY, variable_type=bool) or TurboResourceUtil.Resource.get_guid64(TurboPrivacyUtil.get_privacy_interaction(privacy_instance)) in PRIVACY_NUDE_INTERACTIONS: return PrivacyResult.ALLOW if get_nudity_setting(NuditySetting.NUDITY_SWITCH_STATE, variable_type=bool): privacy_interaction = TurboPrivacyUtil.get_privacy_interaction(privacy_instance) if TurboResourceUtil.Resource.get_guid64(privacy_interaction) in PRIVACY_NUDE_INTERACTIONS: (sim_has_permission, _) = has_sim_permission_for_nudity(TurboInteractionUtil.get_interaction_sim(privacy_interaction), ignore_location_test=True, targets=(tested_sim,)) if sim_has_permission is True: (target_has_permission, _) = has_sim_permission_for_nudity(tested_sim, ignore_location_test=True, targets=(TurboInteractionUtil.get_interaction_sim(privacy_interaction),)) if target_has_permission is True: return PrivacyResult.ALLOW return PrivacyResult.DEFAULT
[ "ColonolNutty@hotmail.com" ]
ColonolNutty@hotmail.com
94b4bb9304e20d9e75d252235ee0e1115c6fcfe0
147fe82a8bfbd07a9f01b7d4bcba910ade1ad249
/models.py
4c160ccc1295749b09586b51ae6b563272e010c2
[]
no_license
m-aravind11/memehub
4a4376dca83bf4f87e63d7a1e542d1094970fa9c
936fbbc0b3f90c1ab907899c716bc20262984318
refs/heads/main
2023-02-17T13:15:23.799063
2021-01-17T18:12:47
2021-01-17T18:12:47
329,445,905
1
0
null
2021-01-16T15:43:11
2021-01-13T22:23:57
Python
UTF-8
Python
false
false
1,097
py
from flask_sqlalchemy import SQLAlchemy db=SQLAlchemy() class MemeTemplate(db.Model): __tablename__ = "memetemplate" memeID = db.Column(db.Integer, primary_key=True) memeTemplateSavePathURI = db.Column(db.String(500)) dialogue_template_name = db.Column(db.String(200)) movieName = db.Column(db.String(100)) tags = db.relationship('MemeTag', backref='memetemplateID') def __repr__ (self): return '<Meme %r>' % self.memeID def __init__(self,memeTemplateSavePathURI,dialogue_template_name,movieName): self.memeTemplateSavePathURI = memeTemplateSavePathURI self.dialogue_template_name = dialogue_template_name self.movieName = movieName class MemeTag(db.Model): __tablename__ = "memetag" meme_tag_id = db.Column(db.Integer, primary_key=True) meme_tag = db.Column(db.String(50)) memeID = db.Column(db.Integer, db.ForeignKey('memetemplate.memeID')) def __repr__ (self): return '<Tag %r>' % self.meme_tag_id def __init__ (self,memetag,memeID): self.meme_tag=memetag self.memeID=memeID
[ "maravind2000@gmail.com" ]
maravind2000@gmail.com
3c029f0bc892281ef80ed0ce9e7f74ec8bfadb64
97c9bcfe1ee5e1884c4be5b7f2320118539ef67a
/boj_implementation/G/G4/15685/boj_G4_15685_Heegun.py
45f1ea82020769a91b3ecc8b03b97bb641ef3f83
[]
no_license
hhheegunnn/Algorithm_Study
1c20d9b1632f1a52796d5982bd9d89b6244538cf
a3734776d16bf721b94d6fdb5e00250997d9e8a0
refs/heads/main
2023-02-24T22:59:47.089341
2021-02-03T07:29:12
2021-02-03T07:29:12
306,534,653
0
8
null
2021-01-19T03:13:31
2020-10-23T05:07:02
Java
UTF-8
Python
false
false
1,641
py
"""https://www.acmicpc.net/problem/15685""" """ 드래곤 커브 """ # git add boj_implementation/G/G4/15685/boj_G4_15685_Heegun.py # git commit -m "[김희건] boj 드래곤 커브" from collections import deque delta =[(0,1),(-1,0),(0,-1),(1,0)] find_s = [(0,1),(1,0),(0,-1)] def draw(x,y,d,g): d_list = [d] for _ in range(g): lend = len(d_list) for j in range(lend-1,-1,-1): tmp = (d_list[j] + 1)%4 d_list.append(tmp) for dt in d_list: board[y][x] = 1 y = y + delta[dt][0] x = x + delta[dt][1] if 0<= y < k and 0<= x<k: if board[y][x] == 0: board[y][x] = 1 def find_square(): s_cnt = 0 for r in range(k): for c in range(k): cnt = 0 if board[r][c] == 1: #print(r,c) tr = r tc = c for dr,dc in find_s: nr = tr + dr nc = tc + dc if 0<= nr < k and 0<= nc < k and board[nr][nc]==1: cnt += 1 tr = nr tc = nc else: break if cnt == 3: s_cnt += 1 return s_cnt N = int(input()) k = 101 board = [[0 for _ in range(k)] for _ in range(k)] for _ in range(N): x,y,d,g = map(int,input().split()) draw(x,y,d,g) #print(board) print(find_square()) """ 6 1 1 0 0 1 2 0 0 1 3 0 0 2 1 0 0 2 2 0 0 2 3 0 0 """ """ 3 3 3 0 1 4 2 1 3 4 2 2 1 """
[ "khg878@gmail.com" ]
khg878@gmail.com
b8574b7ea40fd02f63183a6e0855458821731d6b
d97eae6cccd3cb464cead8bc4fbfa2503e953af2
/contacts/migrations/0001_initial.py
517ab601c803e41f9aa6424e5960d97db3e879ab
[]
no_license
badreldenbeko/sharp
3124d0ec8836d828e929bef1703f165ecd9827f9
8375ce1e6e37cb38298db9821391d722ab0ac48c
refs/heads/master
2022-12-15T15:39:30.520917
2018-05-01T16:54:03
2018-05-01T16:54:03
54,642,355
0
0
null
null
null
null
UTF-8
Python
false
false
1,294
py
# Generated by Django 2.0.3 on 2018-04-21 18:45 from django.db import migrations, models import sharp.utls class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('en_contact_name', models.CharField(max_length=250)), ('ar_contact_name', models.CharField(blank=True, max_length=250, null=True)), ('email', models.EmailField(max_length=254, unique=True)), ('phone', models.IntegerField(blank=True, null=True)), ('subject', models.CharField(blank=True, max_length=250, null=True)), ('message', models.TextField(blank=True, null=True)), ('replayed', models.BooleanField(default=False)), ('slug', models.SlugField(max_length=200, unique=True)), ('image', models.ImageField(blank=True, null=True, upload_to=sharp.utls.upload_location)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], ), ]
[ "badrelden@hotmail.com" ]
badrelden@hotmail.com
cf7e072beb75dd4d3d4cb7156e69de57a8955a2a
1be1bb6167b298679939d216e10397c94a9a54a2
/SCE_Tables_15degrees_1Bus_1Opa_1Rpa_4Ipu.py
d153ed43423a46dfbfb1ce02745398b53574fae8
[]
no_license
Reece821/Reece821
aaba1b32ee6e6dc7fb2a7df73390cddfb18b6cc9
1c2833362f33d4ccb241280e4ff7e598e61ef590
refs/heads/main
2023-06-20T02:12:18.238175
2021-07-23T15:34:56
2021-07-23T15:34:56
388,496,125
0
0
null
2021-07-22T15:11:47
2021-07-22T14:43:24
Python
UTF-8
Python
false
false
4,544
py
import sys import struct import time import msfe ###################################################################### def run(scpa, fd): def Transmit (scpa, fd, mess): scpa.send(mess) fd.write(str(mess)) fd.write('Sent request nr %s (exch id=%s)\n' % (send_count, mess.hdr.exch_id)) time.sleep(1.0) def TxWaitRx(msg): scpa.send(msg) fd.write(str(msg) + '\n') resp = scpa.poll(req=msg) fd.write('Got response = %s\n' % resp) return resp # # Clear out any response messages that might be left over from other scripts while 1: resp = scpa.poll(timeout=1.0) if not resp: break # send_count = 0 mess = msfe.sce.SceRequest() mess.hdr.function = 16 # Download Table # Table config # Constant Values FireAngle = 15 CollisionAvoidance = 0 SyncState = 6 DtC = 12 #Detection Window Count DtD = 5 #Detection Window Degrees DtB = 7 #Detection Window Bits OpStat = 1 #Operational Status of Equipment # # OMU Map # Bus OmuId OMUmap = [ (1, 1) ] # # IPU Map # Bus Fdr DetPt IPU IPUmap = [ (1, 1, 'A', 0), (1, 1, 'B', 1), (1, 1, 'C', 2), (1, 1, 'N', 3) ] # # OMU Parameters # OmuId OMUparm = [ (1, FireAngle, FireAngle, FireAngle, FireAngle, FireAngle, FireAngle, CollisionAvoidance) ] # # Receiver Parameters # RpaId RPAparm = [ (1, SyncState) ] # # Detection parameters: # Bus Fdr MultBit DetCor ChSet ChMap GChSet GChMap LGPhD LLPhD DetWC DetWD DetWB NScal PhScal AdFilt BitOp1 BitOp2 # Min 1 1 0 crc A 000001 A 000001 5 5 12 5 7 1 1 0 0x00 0x00 # Max 254 254 1 crc_hamm F 111111 F 111111 175 175 100 100 255 0xFF 0xFF DetParm = [ (1, 1, 0, 'crc_hamm', 'A', '000001','A', '111111',130, 130, DtC, DtD, DtB, 100, 100, 0, 0x20, 0x00) ] # # Equipment Table # EqType EqId OpStat PhMap HwV HwV2 SwV SwV2 # 1 OMU 1-12 1 0 0 0 0 0 # 2 RPA 1-4 # 3 SCPA 0 # 7 IPU 0-127 EqTab = [ (1, 1, OpStat, 0, 0, 0, 0, 0), (2, 1, OpStat, 0, 0, 0, 0, 0), (3, 0, OpStat, 0, 0, 0, 0, 0), (7, 0, OpStat, 0, 0, 0, 0, 0), (7, 1, OpStat, 0, 0, 0, 0, 0), (7, 2, OpStat, 0, 0, 0, 0, 0), (7, 3, OpStat, 0, 0, 0, 0, 0) ] # # tables = [msfe.tables.OMU_Map(OMUmap), msfe.tables.IPU_Map(IPUmap), msfe.tables.OMU_Params(OMUparm), msfe.tables.Rcvr_Params(RPAparm), msfe.tables.Det_Params(DetParm), msfe.tables.Eq_Table(EqTab) ] # Lock the Tables mess = msfe.sce.LockTablesRequest(tables) Transmit(scpa, fd, mess) send_count += 1 resp = scpa.poll(req=mess, timeout=60.0) if resp: fd.write('Got response = %s\n' % resp) if resp.hdr.executionStatus != 0: fd.write('ERROR - BAD EXECUTION STATUS %s\n' % resp.hdr.executionStatus) else: # Download the Tables for table in tables: mess = msfe.sce.DownloadTableRequest(table) Transmit(scpa, fd, mess) send_count += 1 resp = scpa.poll(req=mess, timeout=60.0) if resp: fd.write('Got response = %s\n' % resp) if resp.hdr.executionStatus != 0: fd.write('ERROR - BAD EXECUTION STATUS %s\n' % resp.hdr.executionStatus) else: fd.write('ERROR - No Response Received') else: fd.write('ERROR - No Response Received') # Unlock the Tables mess = msfe.sce.UnlockTablesRequest(tables) Transmit(scpa, fd, mess) send_count += 1 resp = scpa.poll(req=mess, timeout=60.0) if resp: fd.write('Got response = %s\n' % resp) if resp.hdr.executionStatus != 0: fd.write('ERROR - BAD EXECUTION STATUS %s\n' % resp.hdr.executionStatus) else: fd.write('ERROR - No Response Received') # Done return
[ "noreply@github.com" ]
Reece821.noreply@github.com
4b4eac2d7433b10b20bd7d4e0a44fb950d028511
6a562077f79213f6b2bb89e92d6a16d931268089
/frappe/email/doctype/email_queue_recipient/email_queue_recipient.py
42956a118022fb05aa61d0bd07aa57727245e5d8
[ "MIT" ]
permissive
libracore/frappe
74fe917b75aa1cfad38c71519914180d5d5f1366
92d94a73a3445a252a2828de0053dcce86a18f17
refs/heads/v12
2023-07-17T04:58:08.622228
2023-06-28T17:27:33
2023-06-28T17:27:33
89,392,790
6
8
MIT
2023-08-29T16:29:03
2017-04-25T18:19:40
Python
UTF-8
Python
false
false
275
py
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class EmailQueueRecipient(Document): pass
[ "rmehta@gmail.com" ]
rmehta@gmail.com
7d41f1a2f4f3e1f9a3b0a893cd8b7b2a12bce6ad
5ab128e01ea98fc26b4e6e59c63308cadce78608
/Liquidity/Spread Scrape.py
ec9c38f72c30f7adde8d46ac871ea82d6fd6e2ee
[]
no_license
Tsuna5D/Projects
64e79e481dfbb34aab696bf394281e248d497054
b4d44140629eeb32d8ab9a9341c92cb38c9c7aeb
refs/heads/master
2022-04-20T01:07:27.632247
2020-04-17T03:09:19
2020-04-17T03:09:19
256,352,752
0
0
null
null
null
null
UTF-8
Python
false
false
875
py
from selenium import webdriver from bs4 import BeautifulSoup import requests import re import time def spread(): url1=requests.get('https://quotes.wsj.com/bond/BX/TMUBMUSD10Y?mod=md_home_overview_quote').text soup1=BeautifulSoup(url1,'lxml') yield_rate_10=soup1.find('li',attrs={'class':'crinfo_quote'}) url2=requests.get('https://quotes.wsj.com/bond/BX/TMUBMUSD01Y?mod=md_home_overview_quote').text soup2=BeautifulSoup(url2,'lxml') yield_rate_10=soup1.find('li',attrs={'class':'crinfo_quote'}) yield_rate_1=soup2.find('li',attrs={'class':'crinfo_quote'}) inf_dic1={} yield_10=yield_rate_10.find('span').get_text().replace('%','') yield_1=yield_rate_1.find('span').get_text().replace('%','') print(float(yield_10.strip())-float(yield_1.strip())) return float(yield_10.strip())-float(yield_1.strip()) #spread()
[ "noreply@github.com" ]
Tsuna5D.noreply@github.com
5c63e28f3076414e4c692687f99ac0ebe70b0138
d97e884adf638cf938884d630717b9ffbcfd6745
/smapp/smapp/migrations/0001_initial.py
21da6c397b7fd6b270d2aa87a36d42c111bd7529
[]
no_license
safemailsaccount/smapp
5df4c06f23f999b2ffed929996cb862a26f350be
d0d8dd955509a0edd245a531287fcc261649a363
refs/heads/master
2023-03-29T07:32:54.789384
2021-03-30T18:48:41
2021-03-30T18:48:41
353,071,731
0
0
null
null
null
null
UTF-8
Python
false
false
593
py
# Generated by Django 3.1.7 on 2021-03-17 20:11 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('msg_id', models.CharField(max_length=50)), ('receiver', models.TextField()), ('email_content', models.TextField()), ], ), ]
[ "k@safemails.net" ]
k@safemails.net
fe8d4c3acebcdb5aa7a8f6bcf347d61cba4310f4
5b034abe9e20c8017fcb0f406b52d09b41ce9f00
/pages/modular.py
abecf31cc691f6cf6570f48278634334067328fa
[]
no_license
Mrxiaog3389/ymsp
d1bbe2d746d47ce89757b295c415018ee9b1bb05
2e64a361ad5d2d3b34c91dffe15567543655bbfb
refs/heads/master
2023-03-06T15:09:23.332959
2021-02-21T13:22:42
2021-02-21T13:22:42
329,933,124
0
0
null
null
null
null
UTF-8
Python
false
false
1,781
py
from common.slideVerfication import SlideVerificationCode from common.Driver import Driver import time class testzh(Driver): def open(self): self.driver.get("https://qzone.qq.com/") def login(self): self.driver.switch_to.frame("login_frame") self.driver.find_element_by_id("switcher_plogin").click() self.driver.find_element_by_id("u").send_keys("350978786") self.driver.find_element_by_id("p").send_keys("12131311") time.sleep(2) self.driver.find_element_by_id("login_button").click() iframe_sli = self.driver.find_element_by_id("tcaptcha_iframe") self.driver.switch_to.frame(iframe_sli) # 3.1 定位滑块背景图 bg_ele = self.driver.find_element_by_id("slideBg") # 3.2 定位滑动的图片 block_ele = self.driver.find_element_by_id("slideBlock") # 3.3 定位滑动的按钮 sil_btn = self.driver.find_element_by_id("tcaptcha_drag_thumb") # 3.4 创建一个验证码滑动的对象 sli_code = SlideVerificationCode() # 3.5、获取验证码背景图的缺口位置 x = sli_code.get_element_slide_distance(block_ele, bg_ele) # 3.6 根据页面图片的缩放比进行调整 loc_x = x * (280 / 680) - 31 # 3.7模拟拖动鼠标进行滑动验证 sli_code.slide_verification(self.driver, sil_btn, loc_x) # # 1.2 打开qq登录页面 # driver.get("https://e.oppomobile.com/") # first_window=driver.current_window_handle # time.sleep(3) # driver.find_element_by_link_text("广告投放管理").click() # time.sleep(3) # #切换窗口 # windows=driver.window_handles # for i in windows: # if i == first_window: # continue # else: # driver.switch_to.window(i)
[ "18483663883@163.com" ]
18483663883@163.com
9f28092981deee83a5167b32972805649befa762
e75298fd9c6acf4d63c4578715d6fe7cdf546330
/create_cloud.py
184d40918c4fc4853288816191c6ed711305e373
[]
no_license
5arthak01/RMHS-marathi-wordcloud
5bb8be63e7a089478c4c934e76c1d8d7c2eb8e39
f6886c2288a394e31faa84bb492eaeb340ac018e
refs/heads/master
2023-03-06T22:25:41.658187
2021-02-21T08:58:06
2021-02-21T08:58:06
340,664,126
0
0
null
null
null
null
UTF-8
Python
false
false
3,278
py
import csv from wordcloud import WordCloud import matplotlib.pyplot as plt from cltk.corpus.marathi.alphabet import ( VOWELS, SEMI_VOWELS, VELAR_CONSONANTS, PALATAL_CONSONANTS, RETROFLEX_CONSONANTS, DENTAL_CONSONANTS, LABIAL_CONSONANTS, ADDITIONAL_CONSONANTS, FRIACTIVE_CONSONANTS, SIBILANTS, DIGITS, ) STOP_LIST = [ "न", "तरी", "तो", "हें", "तें", "कां", "आणि", "जें", "जे", "मग", "ते", "मी", "जो", "परी", "गा", "हे", "ऐसें", "आतां", "तैसें", "परि", "नाहीं", "तेथ", "हा", "तया", "असे", "म्हणे", "काय", "म्हणौनि", "कीं", "जैसें", "तंव", "तूं", "होय", "जैसा", "आहे", "पैं", "तैसा", "जरी", "म्हणोनि", "एक", "ऐसा", "जी", "ना", "मज", "एथ", "या", "जेथ", "जया", "तुज", "तेणें", "तैं", "पां", "असो", "करी", "ऐसी", "येणें", "जाहला", "तेंचि", "आघवें", "होती", "जैं", "कांहीं", "होऊनि", "एकें", "मातें", "ठायीं", "ये", "अर्जुना", "सकळ", "केलें", "जेणें", "जाण", "जैसी", "होये", "जेवीं", "एऱ्हवीं", "मीचि", "किरीटी", "दिसे", "देवा", "हो", "तरि", "कीजे", "तैसे", "आपण", "तिये", "कर्म", "नोहे", "इये", "पडे", "पार्था", "माझें", "तैसी", "लागे", "नाना", "जंव", "कीर", ] ALPHABET = ( VOWELS + SEMI_VOWELS + VELAR_CONSONANTS + PALATAL_CONSONANTS + RETROFLEX_CONSONANTS + DENTAL_CONSONANTS + LABIAL_CONSONANTS + ADDITIONAL_CONSONANTS + FRIACTIVE_CONSONANTS + SIBILANTS + DIGITS ) stpwrds = [] with open("marathi_stopwords.txt", "r", encoding="utf-8") as f: stpwrds = f.readlines() stopwords = set(STOP_LIST + [x.strip(" \n") for x in stpwrds] + ALPHABET) words = "" with open("./loksatta/all_loksatta_articles.csv", "r") as csvfile: spamreader = csv.reader(csvfile, delimiter="|") count = 0 for article in spamreader: words += article[-1] + " " words = words.replace(" ", " ") wordcloud = WordCloud( font_path="Lohit-Marathi.ttf", width=800, height=800, background_color="white", stopwords=stopwords, min_font_size=10, regexp=r"[\u0900-\u097F]+", ).generate(words) wordcloud.to_file("loksatta_wordcloud.png") # # plot the WordCloud image # plt.figure(figsize=(8, 8), facecolor=None) # plt.imshow(wordcloud) # plt.axis("off") # plt.tight_layout(pad=0) # plt.show()
[ "sarthak.agrawal@research.iiit.ac.in" ]
sarthak.agrawal@research.iiit.ac.in
56855bc05488a7576e9ddbe9a0e4cc1ae6861d38
d7645461674e7159362e8cf558655cf31ace8f63
/TP4/Ejercicio-2/Graficos/Gráficos_sensibilidades.py
1449636474152fb5a2a7d09089853420a38068e5
[]
no_license
tlondero/LABO
845ee7d5a839d62c4f48fe5a414efc358cede8f3
30b3e0b34ba0714207d72ee53c8b0f7f665d8b65
refs/heads/master
2020-07-02T22:23:26.745748
2019-11-19T21:04:36
2019-11-19T21:04:36
201,685,330
0
1
null
null
null
null
UTF-8
Python
false
false
6,452
py
import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker import matplotlib.patches as mpatches frecuencia_medida=[1.00E+01, 1.50E+01, 2.00E+01, 2.50E+01, 3.00E+01, 3.50E+01, 4.00E+01, 4.50E+01, 5.00E+01, 5.50E+01, 6.00E+01, 6.50E+01, 7.00E+01, 7.50E+01, 8.00E+01, 8.50E+01, 9.00E+01, 9.50E+01, 1.00E+02, 1.05E+02, 1.10E+02, 1.15E+02, 1.20E+02, 1.25E+02, 1.30E+02, 1.35E+02, 1.40E+02, 1.45E+02, 1.50E+02, 1.55E+02, 1.60E+02, 1.65E+02, 1.70E+02, 1.75E+02, 1.80E+02, 1.85E+02, 1.90E+02, 1.95E+02, 2.00E+02] Sensibilidad_16K_R_1=[0.0197411902, 0.0296117853, 0.0394823804, 0.0493529755, 0.0592235705, 0.0690941656, 0.0789647607, 0.0888353558, 0.0987059509, 0.1085765460, 0.1184471411, 0.1283177362, 0.1381883313, 0.1480589264, 0.1579295215, 0.1678001165, 0.1776707116, 0.1875413067, 0.1974119018, 0.2072824969, 0.2171530920, 0.2270236871, 0.2368942822, 0.2467648773, 0.2566354724, 0.2665060675, 0.2763766625, 0.2862472576, 0.2961178527, 0.3059884478, 0.3158590429, 0.3257296380, 0.3356002331, 0.3454708282, 0.3553414233, 0.3652120184, 0.3750826135, 0.3849532086, 0.3948238036 ] Sensibilidad_16K_R_3=[0.0197411902, 0.0296117853, 0.0394823804, 0.0493529755, 0.0592235705, 0.0690941656, 0.0789647607, 0.0888353558, 0.0987059509, 0.1085765460, 0.1184471411, 0.1283177362, 0.1381883313, 0.1480589264, 0.1579295215, 0.1678001165, 0.1776707116, 0.1875413067, 0.1974119018, 0.2072824969, 0.2171530920, 0.2270236871, 0.2368942822, 0.2467648773, 0.2566354724, 0.2665060675, 0.2763766625, 0.2862472576, 0.2961178527, 0.3059884478, 0.3158590429, 0.3257296380, 0.3356002331, 0.3454708282, 0.3553414233, 0.3652120184, 0.3750826135, 0.3849532086, 0.3948238036 ] Sensibilidad_K8_R_1=[0.001, 0.002, 0.002, 0.002, 0.003, 0.003, 0.004, 0.004, 0.004, 0.005, 0.005, 0.005, 0.006, 0.006, 0.006, 0.007, 0.007, 0.007, 0.007, 0.008, 0.008, 0.008, 0.008, 0.009, 0.009, 0.009, 0.009, 0.009, 0.010, 0.010, 0.010, 0.010, 0.010, 0.010, 0.011, 0.011, 0.011, 0.011, 0.011, ] Sensibilidad_K8_R_3=[0.023, 0.024, 0.024, 0.025, 0.026, 0.026, 0.027, 0.027, 0.028, 0.028, 0.029, 0.029, 0.030, 0.031, 0.031, 0.032, 0.032, 0.033, 0.033, 0.034, 0.034, 0.035, 0.036, 0.036, 0.037, 0.037, 0.038, 0.038, 0.039, 0.039, 0.040, 0.041, 0.041, 0.042, 0.042, 0.043, 0.043, 0.044, 0.044 ] Sensibilidad_8K_R_1=[0.007, 0.010, 0.011, 0.012, 0.013, 0.014, 0.015, 0.015, 0.016, 0.016, 0.017, 0.017, 0.017, 0.018, 0.018, 0.018, 0.018, 0.018, 0.019, 0.019, 0.019, 0.019, 0.019, 0.019, 0.019, 0.019, 0.019, 0.020, 0.020, 0.020, 0.020, 0.020, 0.020, 0.020, 0.020, 0.020, 0.020, 0.020, 0.020 ] Sensibilidad_8K_R_3=[0.033, 0.039, 0.045, 0.050, 0.056, 0.061, 0.067, 0.072, 0.078, 0.084, 0.089, 0.095, 0.100, 0.106, 0.112, 0.117, 0.123, 0.128, 0.134, 0.139, 0.145, 0.151, 0.156, 0.162, 0.167, 0.173, 0.179, 0.184, 0.190, 0.195, 0.201, 0.207, 0.212, 0.218, 0.223, 0.229, 0.234, 0.240, 0.246 ] fig, ax1 = plt.subplots() ax1.set_xlabel('Frecuencia [KHz]') ax1.set_ylabel('$\Delta V_D $[mV]') ax1.plot(frecuencia_medida, Sensibilidad_16K_R_1, "blue", linestyle='-', label='Sensibilidad $R_1$') ax1.plot(frecuencia_medida, Sensibilidad_16K_R_3, "yellow", linestyle=':', label='Sensibilidad $R_3$') ax1.set_xticks([10,25,50,75,100,125,150,175,200]) #ax1.tick_params(axis='y') #ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis #ax2.set_ylabel('Fase [°]') # we already handled the x-label with ax1 #ax2.plot(frecuencia_medida, fase_medida, "blue", linestyle=':', label='Fase(Empírica)') #ax2.plot(data["f"], data["pha"], "red", linestyle=':', label='Fase (Simulada)') #ax2.tick_params(axis='y') #ax1.set_yticks([]) #ax2.set_yticks([90,75,60,45,30,15,0]) fig.tight_layout() # otherwise the right y-label is slightly clipped #plt.show() #plt.yscale("linear") #plt.title('Diagrama de Bode - Filtro Pasa-bajos') # agregamos patches patches = [ mpatches.Patch(color="blue", linestyle='-', label='Sensibilidad $R_1$'), mpatches.Patch(color="yellow", linestyle=':', label='Sensibilidad $R_3$'), ] # agregamos leyenda plt.legend(handles=patches) #plt.ylabel('|H($)| [dB]') #plt.xlabel('Frecuencia[Hz]') #plt.plot(fmed, hmed, "blue", label='Módulo de la Transferencia (Empírico)') #plt.plot(fmed, fase, "blue", linestyle=':', label='Fase') # pongo una grilla plt.minorticks_on() ax1.xaxis.grid(True) plt.grid(which='major', axis='both', linestyle='-', linewidth=0.3, color='black') plt.grid(which='minor', axis='both', linestyle=':', linewidth=0.1, color='black') plt.grid(True, which="both") plt.show() ############################### fig2, ax2 = plt.subplots() ax2.set_xlabel('Frecuencia [Hz]') ax2.set_ylabel('$\Delta V_D $[V]') ax2.plot(frecuencia_medida, Sensibilidad_K8_R_1, "blue", linestyle='-', label='Sensibilidad $R_1$') ax2.plot(frecuencia_medida, Sensibilidad_K8_R_3, "red", linestyle='-', label='Sensibilidad $R_3$') ax2.set_xticks([10E3,25E3,50E3,75E3,100E3,125E3,150E3,175E3,200E3]) fig2.tight_layout() # otherwise the right y-label is slightly clipped # agregamos patches patches = [ mpatches.Patch(color="blue", linestyle='-', label='Sensibilidad R_1'), mpatches.Patch(color="red", linestyle='-', label='Sensibilidad R_3'), ] # agregamos leyenda plt.legend(handles=patches) # pongo una grilla plt.minorticks_on() ax2.xaxis.grid(True) plt.grid(which='major', axis='both', linestyle='-', linewidth=0.3, color='black') plt.grid(which='minor', axis='both', linestyle=':', linewidth=0.1, color='black') plt.grid(True, which="both") plt.show() ############################### fig3, ax3 = plt.subplots() ax3.set_xlabel('Frecuencia [Hz]') ax3.set_ylabel('$\Delta V_D $[V]') ax3.plot(frecuencia_medida, Sensibilidad_8K_R_1, "blue", linestyle='-', label='Sensibilidad $R_1$') ax3.plot(frecuencia_medida, Sensibilidad_8K_R_3, "red", linestyle='-', label='Sensibilidad $R_3$') ax3.set_xticks([10E3,25E3,50E3,75E3,100E3,125E3,150E3,175E3,200E3]) fig3.tight_layout() # otherwise the right y-label is slightly clipped # agregamos patches patches = [ mpatches.Patch(color="blue", linestyle='-', label='Sensibilidad R_1'), mpatches.Patch(color="red", linestyle='-', label='Sensibilidad R_3'), ] # agregamos leyenda plt.legend(handles=patches) # pongo una grilla plt.minorticks_on() ax3.xaxis.grid(True) plt.grid(which='major', axis='both', linestyle='-', linewidth=0.3, color='black') plt.grid(which='minor', axis='both', linestyle=':', linewidth=0.1, color='black') plt.grid(True, which="both") plt.show()
[ "gbertachini@itba.edu.ar" ]
gbertachini@itba.edu.ar
b3c05fdfc6a2576165f4dfc5303f74eb9ccf9879
5864e86954a221d52d4fa83a607c71bacf201c5a
/sensorsuite/overlay/spacelocations.py
1394f5b7959e96607dfc7cc3d2481a418f1a7f1b
[]
no_license
connoryang/1v1dec
e9a2303a01e5a26bf14159112b112be81a6560fd
404f2cebf13b311e754d45206008918881496370
refs/heads/master
2021-05-04T02:34:59.627529
2016-10-19T08:56:26
2016-10-19T08:56:26
71,334,417
0
0
null
null
null
null
UTF-8
Python
false
false
1,551
py
#Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\packages\sensorsuite\overlay\spacelocations.py import weakref from utillib import KeyVal class SpaceLocations: def __init__(self): self.locationsBySiteId = {} self.locationsByBallId = {} def Clear(self): self.locationsBySiteId.clear() self.locationsByBallId.clear() def AddLocation(self, ball, bracket, siteData): locationData = KeyVal(ballRef=weakref.ref(ball), bracket=bracket, siteData=siteData, ballID=ball.id) self.locationsBySiteId[siteData.siteID] = locationData self.locationsByBallId[ball.id] = locationData def RemoveLocation(self, siteID): locData = self.GetBySiteID(siteID) del self.locationsBySiteId[siteID] del self.locationsByBallId[locData.ballID] def GetBracketByBallID(self, ballID): locData = self.locationsByBallId.get(ballID) if locData: return locData.bracket else: return None def GetBracketBySiteID(self, siteID): locData = self.locationsBySiteId.get(siteID) if locData: return locData.bracket else: return None def GetBySiteID(self, siteID): return self.locationsBySiteId[siteID] def ContainsSite(self, siteID): return siteID in self.locationsBySiteId def GetLocations(self): return self.locationsBySiteId.values() def IterLocations(self): return self.locationsBySiteId.itervalues()
[ "le02005@163.com" ]
le02005@163.com
c28782d9cd3ed823786d7aac39ac3747779265e3
7af4f4f11126152def21c136603254637f34017d
/.shadow/python/plot_main.py
3a366614cdaf3305fe4e8ddcdd964a9a1d065e36
[]
no_license
reotyan/dot_files
9489fa1c12e19d4349baf1c4a835aa1a8fc8fab9
f64fc9bbbd42d20fc3a9335605e60b3ae413d9b8
refs/heads/master
2021-06-13T21:55:47.914223
2017-03-14T13:30:33
2017-03-14T13:30:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
723
py
#!/usr/bin/python3 import numpy as np import pandas as pd import matplotlib.pyplot as plt import pandas.tseries.offsets as offsets import matplotlib.finance as mpf import sys import threading from modules.plot_def import * SPAN_s = 13 SPAN_m = 21 SPAN_l = 13 SPAN_ll = 30 HL_BAND_PERIOD = 5 if len(sys.argv) < 2: print('Usage: python3 ' + sys.argv[0] + ' quotes.csv [ohlc]') exit(1) csv = pd.read_csv(sys.argv[1]) usdjpy = csv_to_df(csv) ohlc = TF_ohlc(usdjpy) tohlc = ohlc_to_tohlc(ohlc) ax = plt.subplot() close = ohlc['Close'] plot_ohlc(sys.argv, close, ax, tohlc, SPAN_s, SPAN_m, SPAN_l, SPAN_ll, HL_BAND_PERIOD) ax.grid() #グリッド表示 plt.legend() plt.show() #plt.savefig('image.png')
[ "reosan@laptop.localdomain" ]
reosan@laptop.localdomain
72f86c2d2fb7ee29ce2222d99f4735d121c670a5
9cfc06cefd959091fee1009898b22f674e038d91
/best_valid_acc.py
449862088e0ce917963ee2bd786e03643df0ecee
[ "MIT" ]
permissive
TommyLitlle/OpenNMT-entmax
c4c2f2bdc5818ab12c7398bb56d4bb51fe63d80f
d9d0e7bc8a7da6624e0fe75434f7aa106250254a
refs/heads/master
2022-01-04T20:20:00.662746
2019-03-03T14:50:12
2019-03-03T14:50:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
134
py
#!/usr/bin/env python import sys print(max(float(line.strip().split()[-1]) for line in sys.stdin if 'Validation accuracy' in line))
[ "bpeters@coli.uni-saarland.de" ]
bpeters@coli.uni-saarland.de
ca5f5aa08a2c23c38b41e8fa92f081c92eb9468f
41e9d6edf49701c62471bddf2a5ccd041ec5c31e
/libraries/mathy_python/mathy/agents/zero/config.py
477e99a507c9cec583f9a4a1b53da533ff6ac7a7
[ "MIT" ]
permissive
Guillemdb/mathy
b0fc5537aa267c4e9f386d36d3c17ff74fd4d0ab
06204396ac39445b732c199078076b18fd1bbccc
refs/heads/master
2021-05-22T18:57:59.097614
2020-04-02T19:25:55
2020-04-02T19:25:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
891
py
from ...agents.base_config import BaseConfig class SelfPlayConfig(BaseConfig): batch_size = 128 # PyTorch models need padded batches of the max length a sequence might be. # Mathy expressions can occasionally go over 128 nodes, but I've never made # an expression more than 256. If we go over this limit, it might be time to # introduce the Reformer. max_sequence_length: int = 256 epochs = 10 mcts_sims: int = 50 temperature_threshold: float = 0.5 self_play_problems: int = 64 training_iterations: int = 100 cpuct: float = 1.0 normalization_style: str = "batch" # When profile is true and workers == 1 the main thread will output worker_0.profile on exit profile: bool = False # Don't use the LSTM with Zero agents because the random sampling breaks # timestep correlations across the batch. use_lstm: bool = False
[ "justin@dujardinconsulting.com" ]
justin@dujardinconsulting.com
354c6d328e80a9197233d307c408e6d77934fd43
d69928b40a714527b6fae698ddf77a0d4d1711ca
/manage.py
b1997b630cddae6676f12dae6b45c2c3d5226a5f
[]
no_license
hongsa/flask-restful-skeleton
b1a90e1bfe1aad80ab6606ef017365e17c6f21c9
e19f4cd6eeadff322a1953f812605999e1dfd17f
refs/heads/master
2020-12-30T11:59:03.704811
2018-08-29T15:41:25
2018-08-29T15:41:25
91,459,209
1
0
null
null
null
null
UTF-8
Python
false
false
39
py
from apps import manager manager.run()
[ "hsasung@gmail.com" ]
hsasung@gmail.com
0520927a3d479dd233e099358624f5fa16f6c280
c577b023ee14e497c8f10130f6acce6430333e28
/makesense/management/commands/link_2word_terms.py
e0a237b71da3df16b473793ffcfd130d63fd7d6c
[]
no_license
LorenDavie/htms
05d2a79c60281e124194a61fa2bb01a206de4c71
d20fa39dc5b5f7cd50c7a4b3a2a4d9c24615e439
refs/heads/master
2023-04-22T09:35:57.469544
2017-04-01T15:24:45
2017-04-01T15:24:45
365,309,925
0
1
null
null
null
null
UTF-8
Python
false
false
1,739
py
""" Links 2-word terms into ACE """ from makesense.models import Term, Page from django.core.management.base import BaseCommand from django.utils.text import slugify import re class Command(BaseCommand): """ Command class. """ def execute(self,*args,**kwargs): """ Execute method. """ for term in Term.objects.all(): if term.term and len(term.term.split()) > 1: print 'linking multi word term',term.term termlist = term.term.split() term_pattern = r'\s'.join(termlist) split_pattern = '(%s)' % term_pattern print 'matching pattern:',term_pattern for page in Page.objects.all(): matches = re.findall(term_pattern,page.body,re.IGNORECASE) if matches: num_matches = len(matches) term.total_usage += num_matches term.usage.add(page) body_list = re.split(split_pattern,page.body,flags=re.IGNORECASE) new_body = '' for token in body_list: if term.term.lower() == token.lower(): replace_term = '<a href="/term/%s/%s/" class="term-link">%s</a>' % (term.word_type_slug,term.term_slug,token) new_body += replace_term else: new_body += token page.body = new_body page.save() page.push_to_library() term.save()
[ "code@axilent.com" ]
code@axilent.com
8921d70c5716ad7c3276206ec45d1d439730d130
b226ab6d84f76707b961b268e9b0fd9b6309c630
/image/image-yuv-downsample-luma.py
46724cbcc5b07126cbb0a8466bcf1fe989686079
[]
no_license
brycekelleher/pythondev
5f68aa2ec49f30e1019994db708694702edd157e
a505298d517bb3fe37bb4cfe594662d1cc9f8f50
refs/heads/master
2020-09-12T21:32:08.449270
2016-09-09T01:48:38
2016-09-09T01:48:38
67,559,247
0
0
null
null
null
null
UTF-8
Python
false
false
553
py
#!/usr/bin/env python import os, sys import Image def split_image(filename): im = Image.open(filename) yuv = im.convert("YCbCr") y, u, v = yuv.split() # downsample the y component then rescale it to the u and v planes y = y.resize((y.size[0] / 2, y.size[1] / 2), Image.BICUBIC) y = y.resize((y.size[0] * 2, y.size[1] * 2), Image.NEAREST) im = Image.merge("YCbCr", (y, u, v)) im = im.convert("RGB") f, e = os.path.splitext(filename) im.save(f + '-downsampled-luma' + e) def main(): for arg in sys.argv[1:]: split_image(arg) main()
[ "bryce_kelleher@hotmail.com" ]
bryce_kelleher@hotmail.com
e9c2bd7d529fc16f37154d73f886b38093c340e7
9478a2ab7a96ecc41b5856f4dca97df4638a1904
/优美的彩虹.py
4391a75c77cfa768c0f21a9518f8ed27d33561d5
[]
no_license
hulk17666234872/djm
a85665feaf90ac2e787454574b2b157f0199b9d4
76234ed985a96721f19307e21764d5e07a1cc26b
refs/heads/master
2023-06-09T19:55:28.002513
2021-07-01T10:06:56
2021-07-01T10:06:56
262,927,377
1
0
null
null
null
null
UTF-8
Python
false
false
257
py
import turtle q = turtle.Pen() turtle.bgcolor("black") sides = 7 colors =["red","orange","yellow","green","cyan","blue","blue","purple"] for x in range(360): q.pencolor(colors[x%sides]) q.forward(x*3/sides+x) q.left(360/sides+1) q.width(x*sides/200)
[ "65145999+hulk17666234872@users.noreply.github.com" ]
65145999+hulk17666234872@users.noreply.github.com
8db943a4a1c2d29b88b32a953193c3d524724074
9c25fc79ad89d2281de39e75c62051cc3c8b6dbe
/CBSE-CS-Practical-File/q15.py
b41a141d3fc3247d3eef28d9e86776c0178b1791
[]
no_license
devxnsh/Coursework
cab14711d79d41ef21d0f3b71d4eafc59048246c
c67ed1b64b565a57ff2e0ddb2fe51609985892ee
refs/heads/main
2023-08-24T11:22:12.661877
2021-09-07T19:30:02
2021-09-07T19:30:02
370,786,632
0
0
null
2021-05-25T18:09:48
2021-05-25T18:09:48
null
UTF-8
Python
false
false
1,532
py
def isempty(stk): if stk==[]: return True else: return False def push(stk,item): stk.append(item) top=len(stk)-1 def pop(stk): if isempty(stk): return "UNDERFLOW" else: item=stk.pop() if len(stk)==0: top=None else: top=len(stk)-1 return item def peek(stk): if isempty(stk): return "UNDERFLOW" else: top=len(stk)-1 return stk[top] def display(stk): if isempty(stk): print("Stack Empty") else: top=len(stk)-1 print(stk[top],"<-top") for a in range(top-1,-1,-1): print(stk[a]) stack=[] top=None while True: print("STACK OPERATIONS") print("1. PUSH") print("2. POP") print("3. PEEK") print("4. DISPLAY STACK") print("5. EXIT") ch=int(input("Enter your choice(1-5): ")) if ch==1: item=int(input("Enter item: ")) push(stack,item) elif ch==2: item=pop(stack) if item=="UNDERFLOW": print("UNDERFLOW ! stack is empty ") else: print("Popped item is ",item) elif ch==3: item=peek(stack) if item=="UNDERFLOW": print("UNDERFLOW ! stack is empty ") else: print("Topmost item is ",item) elif ch==4: display(stack) elif ch==5: break else: print("Invalid choice")
[ "noreply@github.com" ]
devxnsh.noreply@github.com
9ec0c3308ffbd7c066ac3e99e27840db3e0a1040
90aa8a1bef4af425476fa933bd77415e932dd11c
/mainGui1.py
ad8525501ad4d91a6539d973dda771cbac31c652
[]
no_license
DJ-Man-2099/Memory-Allocation
3a29564a915268885a78a75647084f96eafd610e
b03216a5f9f7cea8d49e11c835b9e0cf4f0159fd
refs/heads/master
2022-09-13T08:24:55.313055
2020-06-01T10:50:33
2020-06-01T10:50:33
261,878,749
1
4
null
null
null
null
UTF-8
Python
false
false
12,584
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainGui1.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from mem_drawing3 import * from holes_window import Ui_holes_Form from segments_window import Ui_segment_Form from copy import deepcopy class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(571, 600) ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## # style sheet MainWindow.setStyleSheet('background-color: lightyellow') ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") font = QtGui.QFont() font.setPointSize(8) self.submit_hole_button = QtWidgets.QPushButton(self.centralwidget) self.submit_hole_button.setGeometry(QtCore.QRect(220, 182, 120, 60)) self.submit_hole_button.setObjectName("submit_hole_button") self.submit_process_button = QtWidgets.QPushButton(self.centralwidget) self.submit_process_button.setGeometry(QtCore.QRect(220, 310, 120, 60)) self.submit_process_button.setObjectName("submit_process_button") self.submit_all_btn = QtWidgets.QPushButton(self.centralwidget) self.submit_all_btn.setGeometry(QtCore.QRect(200, 470, 151, 60)) self.submit_all_btn.setObjectName("submit_all_btn") self.title_label = QtWidgets.QLabel(self.centralwidget) self.title_label.setGeometry(QtCore.QRect(70, -20, 461, 101)) font = QtGui.QFont() font.setPointSize(14) font.setBold(True) font.setWeight(75) self.title_label.setFont(font) self.title_label.setObjectName("title_label") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionNew = QtWidgets.QAction(MainWindow) self.actionNew.setObjectName("actionNew") self.actionOpen = QtWidgets.QAction(MainWindow) self.actionOpen.setObjectName("actionOpen") self.actionSave = QtWidgets.QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.actionSave_As = QtWidgets.QAction(MainWindow) self.actionSave_As.setObjectName("actionSave_As") self.actionSave_All = QtWidgets.QAction(MainWindow) self.actionSave_All.setObjectName("actionSave_All") self.actionQuit = QtWidgets.QAction(MainWindow) self.actionQuit.setObjectName("actionQuit") self.actionUndo = QtWidgets.QAction(MainWindow) self.actionUndo.setObjectName("actionUndo") self.actionSelect_AlL = QtWidgets.QAction(MainWindow) self.actionSelect_AlL.setObjectName("actionSelect_AlL") self.actionHorizontal_Lay_Out = QtWidgets.QAction(MainWindow) self.actionHorizontal_Lay_Out.setObjectName("actionHorizontal_Lay_Out") self.actionVertical_Lay_Out = QtWidgets.QAction(MainWindow) self.actionVertical_Lay_Out.setObjectName("actionVertical_Lay_Out") self.actionToolbars = QtWidgets.QAction(MainWindow) self.actionToolbars.setObjectName("actionToolbars") self.actionPrefrences = QtWidgets.QAction(MainWindow) self.actionPrefrences.setObjectName("actionPrefrences") self.actionMaximize = QtWidgets.QAction(MainWindow) self.actionMaximize.setObjectName("actionMaximize") self.actionMinimize = QtWidgets.QAction(MainWindow) self.actionMinimize.setObjectName("actionMinimize") self.actionAbout_project = QtWidgets.QAction(MainWindow) self.actionAbout_project.setObjectName("actionAbout_project") ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## # style sheets ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## self.submit_hole_button.setStyleSheet('background-color:lightblue ') self.submit_process_button.setStyleSheet('background-color:lightblue') self.submit_all_btn.setStyleSheet('background-color:lightblue') ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## # Buttons Handling Events connections ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## self.submit_hole_button.clicked.connect(self.submit_hole_clicked) self.submit_process_button.clicked.connect(self.submit_process_clicked) self.submit_all_btn.clicked.connect(self.show_memory_layout_clicked) ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Memory Allocation Project")) self.submit_hole_button.setText(_translate("MainWindow", "Add Holes")) self.submit_process_button.setText(_translate("MainWindow", "Add process")) self.submit_all_btn.setText(_translate("MainWindow", "Show Memory Layout")) self.title_label.setText(_translate("MainWindow", "Memory Allocation Project using Segmentation")) ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## # Buttons Handling Events functions ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## ############################################################################################################################## def submit_hole_clicked(self): self.Form = QtWidgets.QWidget() self.ui = Ui_holes_Form() self.ui.setupUi(self.Form) self.Form.show() def submit_process_clicked(self): self.segment_Form = QtWidgets.QWidget() self.ui = Ui_segment_Form() self.ui.setupUi(self.segment_Form) self.ui.process_list_table.itemClicked.connect(self.ui.fill_seg_table) self.segment_Form.show() def show_memory_layout_clicked(self): self.Form = QMainWindow() self.ui = Main() self.ui.setupUi(self.Form) for i in Ui_holes_Form.processes_list: Ui_holes_Form.total_memory_for_holes_window.DeAllocate(i.Name) self.ui.SHOW() self.ui.pro_choose.activated \ .connect(self.ui.show_segments_table) self.ui.dealloc_reserve.clicked.connect(self.ui.reserve) self.ui.alloc_all.clicked.connect(self.ui.allocate_process_clicked) self.ui.alloc.clicked.connect(self.ui.alloc_btn) self.ui.dealloc_current.clicked.connect(self.ui.deallocate_process) # self.ui.show_segments_table({30: ['Process 1', 'Segment 1', 120], 200: ['Process 2', 'Segment 1', 75], 300: ['Process 2', 'Segment 2', 75]}) self.Form.show() if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
[ "noreply@github.com" ]
DJ-Man-2099.noreply@github.com
f858baaa5cc11f3c856dbd213518417ef68e62fc
ab98b3c9f3d9496cd280c7e9c7cf5e6563069ed7
/Cifar/Cifar_result/worker6/MDC-ASGD_6/average.py
619d80b1b22817387c4612d2e9c043133888017f
[]
no_license
Tantao122200/DASGD
c3d14c475fccfba9a53a06e4997d723a667f3ed8
d7ceb7bbd4d015165158be243e592312147377b6
refs/heads/master
2021-01-08T04:03:27.586266
2020-02-21T05:58:51
2020-02-21T05:58:51
241,906,787
0
0
null
null
null
null
UTF-8
Python
false
false
1,421
py
import pandas as pd import numpy as np import os, shutil MYCOUNT = 5 import csv def mypath(path): if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) def read(in_dir, out_dir): data = [] for i in range(1, MYCOUNT + 1): temp_data = pd.read_csv(in_dir + str(i) + ".csv", header=None, usecols=[0, 1, 2, 3, 4, 5, 6]).values data.extend(temp_data.tolist()) data.sort() out = open(out_dir, 'a', newline='') csv_write = csv.writer(out, dialect='excel') for i in range(161): temp = [] for row in data: if row[0] < i * 390: pass elif row[0] == i * 390: row[0] = i temp.append(row) else: break if len(temp) > 0: csv_write.writerow(list_avg(temp)) def list_add(a, b): a = np.array(a) b = np.array(b) return list(a + b) def list_avg(temp): sum = temp[0] for i in range(1, len(temp)): sum = list_add(sum, temp[i]) sum = np.array(sum) return list(sum / len(temp)) if __name__ == "__main__": mypath("./msg") in_dir = ["./train_ASGDMK_0.1_62400_128_6_", "./test_ASGDMK_0.1_62400_128_6_"] out_dir = ["./msg/train_ASGDMK_0.1_62400_128_6.csv", "./msg/test_ASGDMK_0.1_62400_128_6.csv"] for index in range(len(in_dir)): read(in_dir=in_dir[index], out_dir=out_dir[index])
[ "1169311978@qq.com" ]
1169311978@qq.com
a4f008605b6f409bfc30dcd869f51a932a500b00
7ac6cbfb7bfc96ed683c40630385afe7ed17e217
/Time Dimension/TimePolicy_generator.py
2de47c184ec5af2e5ed6ae2c171887dd545c7160
[]
no_license
MahdiShahrabi/COVID19-Simulation
44c281c36871eccb15424240674e7c91c825b84b
c05750a5880d4093907f00659d6be6cbb9c1487d
refs/heads/master
2022-10-05T13:53:21.227089
2020-06-03T16:16:51
2020-06-03T16:16:51
259,633,668
1
0
null
2020-06-03T12:58:15
2020-04-28T12:41:58
Jupyter Notebook
UTF-8
Python
false
false
2,070
py
import networkx as nx import random def chunkIt(seq, num): avg = len(seq) / float(num) out = [] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return out ############################ def TimePolicy_generator(Graph,Maximum_Time=10000, method = {'name':'','divide':{'group_num':2},'node_centrality':{'how':'degree','prc':10,'group_num':2}}): # Size of Graph lng = Graph.number_of_nodes() Nodes_dict = dict(Graph.nodes(data=True)) Nodes_list = list(Nodes_dict) if method['name'] is 'divide': # Assigning groups random.shuffle(Nodes_list) group_num = method['divide']['group_num'] List = chunkIt(Nodes_list, group_num) group_node = {k:v for (k,v) in zip(list(range(1,group_num+1)),List)} time_node = {k:set(group_node[i%group_num+1]) for (k,i) in zip(list(range(1,Maximum_Time+1)),list(range(1,Maximum_Time+1)))} return(time_node) elif method['name'] is 'node_centrality': Dict = method['node_centrality'] how = Dict['how'] prc = Dict['prc'] group_num = Dict['group_num'] func_centrality = {'degree':nx.degree_centrality,'eigen':nx.eigenvector_centrality} sorted_cen = sorted(func_centrality[how](Graph).items(), key=lambda item: item[1],reverse=True) central_nodes = [x[0] for x in sorted_cen[0:int(prc/100*len(sorted_cen))]] Nodes_list_updated = [x for x in Nodes_list if x not in central_nodes] random.shuffle(Nodes_list_updated) List = chunkIt(Nodes_list_updated, group_num) group_node = {k:v for (k,v) in zip(list(range(1,group_num+1)),List)} time_node_temp = {k:set(group_node[i%group_num+1]) for (k,i) in zip(list(range(1,Maximum_Time+1)),list(range(1,Maximum_Time+1)))} time_node = {x[0]:x[1].union(central_nodes) for x in time_node_temp.items()} return(time_node) else: raise ValueError('Wrong input for method["name"]!')
[ "m.m.shahrabi@gmail.com" ]
m.m.shahrabi@gmail.com
0a31c7fbe65242518acfc8b6b2429742b309fa0a
e29bd9096fb059b42b6dde5255f39d443f69caee
/metapict/debug/mp2tikz.py
df71d3dfe7d261717d6a2d5b77c301581499ba87
[]
no_license
soegaard/metapict
bfe2ccdea6dbc800a6df042ec00c0c77a4915ed3
d29c45cf32872f8607fca3c58272749c28fb8751
refs/heads/master
2023-02-02T01:57:08.843234
2023-01-25T17:06:46
2023-01-25T17:06:46
16,359,210
52
12
null
2023-01-25T17:06:48
2014-01-29T21:11:46
Racket
UTF-8
Python
false
false
16,601
py
# mp2tikz.py # (c) 2012 JL Diaz # # This module contains classes and functions to implement Jonh Hobby's # algorithm to find a smooth curve which passes through a serie of given # points. The algorithm is used in METAFONT and MetaPost, but the source code # of these programs is hard to read. I tried to implement it in a more # modern way, which makes the algorithm more understandandable and perhaps portable # to other languages # # It can be imported as a python module in order to generate paths programatically # or used from command line to convert a metapost path into a tikz one # # For the second case, the use is: # # $ python mp2tikz.py <metapost path> <options> # # Where: # <metapost path> is a path using metapost syntax with the following restrictions: # * All points have to be explicit (no variables or expressions) # * All joins have to be "curved" ( .. operator) # * Options in curly braces next to the nodes are ignored, except # for {curl X} at end points # * tension can be specified using metapost syntax # * "cycle" as end point denotes a cyclic path, as in metapost # Examples: # (0,0) .. (60,40) .. (40,90) .. (10,70) .. (30,50) .. cycle # (0,0) .. (60,40) .. (40,90) .. (10,70) .. (30,50) # (0,0){curl 10} .. (60,40) .. (40,90) .. (10,70) .. (30,50) # (0,0) .. (60,40) .. (40,90) .. tension 3 .. (10,70) .. (30,50) .. cycle # (0,0) .. (60,40) .. (40,90) .. tension 1 and 3 .. (10,70) .. (30,50) .. cycle # # <options> can be: # tension = X. The given tension is applied to all segments in the path by default # (but tension given at specific points override this setting at those points) # curl = X. The given curl is applied by default to both ends of the open path # (but curl given at specific endings override this setting at that point) # any other options are considered tikz options. # # The script prints in standard output a tikz command which draws the given path # using the given options. In this path all control points are explicit, as computed # by the string using Hobby's algorith. # # For example: # # $ python mp2tikz.py "(0,0) .. (10,10) .. (20,0) .. (10, -10) .. cycle" "tension =3, blue" # # Would produce # \draw[blue] (0.0000, 0.0000) .. controls (-0.00000, 1.84095) and (8.15905, 10.00000).. # (10.0000, 10.0000) .. controls (11.84095, 10.00000) and (20.00000, 1.84095).. # (20.0000, 0.0000) .. controls (20.00000, -1.84095) and (11.84095, -10.00000).. # (10.0000, -10.0000) .. controls (8.15905, -10.00000) and (0.00000, -1.84095)..(0.0000, 0.0000); # from math import sqrt, sin, cos, atan2, atan, degrees, radians, pi # Coordinates are stored and manipulated as complex numbers, # so we require cmath module import cmath def arg(z): return atan2(z.imag, z.real) def direc(angle): """Given an angle in degrees, returns a complex with modulo 1 and the given phase""" phi = radians(angle) return complex(cos(phi), sin(phi)) def direc_rad(angle): """Given an angle in radians, returns a complex with modulo 1 and the given phase""" return complex(cos(phi), sin(phi)) class Point(): """This class implements the coordinates of a knot, and all kind of auxiliar parameters to compute a smooth path passing through it""" z = complex(0,0) # Point coordinates alpha = 1 # Tension at point (1 by default) beta = 1 theta = 0 # Angle at which the path leaves phi = 0 # Angle at which the path enters xi = 0 # angle turned by the polyline at this point v_left = complex(0,0) # Control points of the Bezier curve at this point u_right = complex(0,0) # (to be computed later) d_ant = 0 # Distance to previous point in the path d_post = 0 # Distance to next point in the path def __init__(self, z, alpha=1, beta=1, v=complex(0,0), u=complex(0,0)): """Constructor. Coordinates can be given as a complex number or as a tuple (pair of reals). Remaining parameters are optional and take sensible default vaules.""" if type(z)==complex: self.z=z else: self.z=complex(z[0], z[1]) self.alpha = alpha self.beta = beta self.v_left = v self.u_right = u self.d_ant = 0 self.d_post = 0 self.xi = 0 def __str__(self): """Creates a printable representation of this object, for debugging purposes""" return """\ z=(%.3f, %.3f) alpha=%.2f beta=%.2f theta=%.2f phi=%.2f [v=(%.2f, %.2f) u=(%.2f, %.2f) d_ant=%.2f d_post=%.2f xi=%.2f]""" % \ (self.z.real, self.z.imag, self.alpha, self.beta, degrees(self.theta), degrees(self.phi), self.v_left.real, self.v_left.imag, self.u_right.real, self.u_right.imag, self.d_ant, self.d_post, degrees(self.xi)) class Path(): """This class implements a path, which is a list of Points""" p = None # List of points cyclic = True # Is the path cyclic? curl_begin = 1 # If not, curl parameter at endpoints curl_end = 1 def __init__(self, p, tension=1, cyclic=True, curl_begin=1, curl_end=1): self.p = [] for pt in p: self.p.append(Point(pt, alpha=1.0/tension, beta=1.0/tension)) self.cyclic = cyclic self.curl_begin = curl_begin self.curl_end = curl_end def range(self): """Returns the range of the indexes of the points to be solved. This range is the whole length of p for cyclic paths, but excludes the first and last points for non-cyclic paths""" if self.cyclic: return range(len(self.p)) else: return range(1, len(self.p)-1) # The following functions allow to use a Path object like an array # so that, if x = Path(...), you can do len(x) and x[i] def append(self, data): self.p.append(data) def __len__(self): return len(self.p) def __getitem__(self, i): """Gets the point [i] of the list, but assuming the list is circular and thus allowing for indexes greater than the list length""" i %= len(self.p) return self.p[i] # Stringfication def __str__(self): """The printable representation of the object is one suitable for feeding it into tikz, producing the same figure than in metapost""" r = [] L = len(self.p) last = 1 if self.cyclic: last = 0 for k in range(L-last): post = (k+1)%L z = self.p[k].z u = self.p[k].u_right v = self.p[post].v_left r.append("(%.4f, %.4f) .. controls (%.5f, %.5f) and (%.5f, %.5f)" %\ (z.real, z.imag, u.real, u.imag, v.real, v.imag)) if self.cyclic: last_z = self.p[0].z else: last_z = self.p[-1].z r.append("(%.4f, %.4f)" % (last_z.real, last_z.imag)) return "..".join(r) def __repr__(self): """Dumps internal parameters, for debugging purposes""" r = ["Path information"] r.append("Cyclic=%s, curl_begin=%s, curl_end=%s" % (self.cyclic, self.curl_begin, self.curl_end)) for pt in self.p: r.append(str(pt)) return "\n".join(r) # Now some functions from John Hobby and METAFONT book. # "Velocity" function def f(theta, phi): n = 2+sqrt(2)*(sin(theta)-sin(phi)/16)*(sin(phi)-sin(theta)/16)*(cos(theta)-cos(phi)) m = 3*(1 + 0.5*(sqrt(5)-1)*cos(theta) + 0.5*(3-sqrt(5))*cos(phi)) return n/m def control_points(z0, z1, theta=0, phi=0, alpha=1, beta=1): """Given two points in a path, and the angles of departure and arrival at each one, this function finds the appropiate control points of the Bezier's curve, using John Hobby's algorithm""" i = complex(0,1) u = z0 + cmath.exp(i*theta)*(z1-z0)*f(theta, phi)*alpha v = z1 - cmath.exp(-i*phi)*(z1-z0)*f(phi, theta)*beta return(u,v) def pre_compute_distances_and_angles(path): """This function traverses the path and computes the distance between adjacent points, and the turning angles of the polyline which joins them""" for i in range(len(path)): v_post = path[i+1].z - path[i].z v_ant = path[i].z - path[i-1].z # Store the computed values in the Points of the Path path[i].d_ant = abs(v_ant) path[i].d_post = abs(v_post) path[i].xi = arg(v_post/v_ant) if not path.cyclic: # First and last xi are zero path[0].xi = path[-1].xi = 0 # Also distance to previous and next points are zero for endpoints path[0].d_ant = 0 path[-1].d_post = 0 def build_coefficients(path): """This function creates five vectors which are coefficients of a linear system which allows finding the right values of "theta" at each point of the path (being "theta" the angle of departure of the path at each point). The theory is from METAFONT book.""" A=[]; B=[]; C=[]; D=[]; R=[] pre_compute_distances_and_angles(path) if not path.cyclic: # In this case, first equation doesnt follow the general rule A.append(0) B.append(0) curl = path.curl_begin alpha_0 = path[0].alpha beta_1 = path[1].beta xi_0 = (alpha_0**2) * curl / (beta_1**2) xi_1 = path[1].xi C.append(xi_0*alpha_0 + 3 - beta_1) D.append((3 - alpha_0)*xi_0 + beta_1) R.append(-D[0]*xi_1) # Equations 1 to n-1 (or 0 to n for cyclic paths) for k in path.range(): A.append( path[k-1].alpha / ((path[k].beta**2) * path[k].d_ant)) B.append((3-path[k-1].alpha) / ((path[k].beta**2) * path[k].d_ant)) C.append((3-path[k+1].beta) / ((path[k].alpha**2) * path[k].d_post)) D.append( path[k+1].beta / ((path[k].alpha**2) * path[k].d_post)) R.append(-B[k] * path[k].xi - D[k] * path[k+1].xi) if not path.cyclic: # The last equation doesnt follow the general form n = len(R) # index to generate C.append(0) D.append(0) curl = path.curl_end beta_n = path[n].beta alpha_n_1 = path[n-1].alpha xi_n = (beta_n**2) * curl / (alpha_n_1**2) A.append((3-beta_n)*xi_n + alpha_n_1) B.append(beta_n*xi_n + 3 - alpha_n_1) R.append(0) return (A, B, C, D, R) import numpy as np # Required to solve the linear equation system def solve_for_thetas(A, B, C, D, R): """This function receives the five vectors created by build_coefficients() and uses them to build a linear system with N unknonws (being N the number of points in the path). Solving the system finds the value for theta (departure angle) at each point""" L=len(R) a = np.zeros((L, L)) for k in range(L): prev = (k-1)%L post = (k+1)%L a[k][prev] = A[k] a[k][k] = B[k]+C[k] a[k][post] = D[k] b = np.array(R) print a print b return np.linalg.solve(a,b) def solve_angles(path): """This function receives a path in which each point is "open", i.e. it does not specify any direction of departure or arrival at each node, and finds these directions in such a way which minimizes "mock curvature". The theory is from METAFONT book.""" # Basically it solves # a linear system which finds all departure angles (theta), and from # these and the turning angles at each point, the arrival angles (phi) # can be obtained, since theta + phi + xi = 0 at each knot""" x = solve_for_thetas(*build_coefficients(path)) L = len(path) for k in range(L): path[k].theta = x[k] print("theta(",k,")=",path[k].theta) for k in range(L): path[k].phi = - path[k].theta - path[k].xi print("phi(",k,")=", path[k].phi) for k in range(L): print("psi(",k,")=",path[k].xi) def find_controls(path): """This function receives a path in which, for each point, the values of theta and phi (leave and enter directions) are known, either because they were previously stored in the structure, or because it was computed by function solve_angles(). From this path description this function computes the control points for each knot and stores it in the path. After this, it is possible to print path to get a string suitable to be feed to tikz.""" r = [] for k in range(len(path)): z0 = path[k].z z1 = path[k+1].z theta = path[k].theta phi = path[k+1].phi alpha = path[k].alpha beta = path[k+1].beta u,v=control_points(z0, z1, theta, phi, alpha, beta) path[k].u_right = u path[k+1].v_left = v def mp_to_tikz(path, command=None, options=None): """Utility funcion which receives a string containing a metapost path and uses all the above to generate the tikz version with explicit control points. It does not make a full parsing of the metapost path. Currently it is not possible to specify directions nor tensions at knots. It uses default tension = 1, default curl =1 for both ends in non-cyclic paths and computes the optimal angles at each knot. It does admit however cyclic and non-cyclic paths. To summarize, the only allowed syntax is z0 .. z1 .. z2, where z0, z1, etc are explicit coordinates such as (0,0) .. (1,0) etc.. And optionally the path can ends with the literal "cycle".""" tension = 1 curl = 1 if options: opt = [] for o in options.split(","): o=o.strip() if o.startswith("tension"): tension = float(o.split("=")[1]) elif o.startswith("curl"): curl = float(o.split("=")[1]) else: opt.append(o) options = ",".join(opt) new_path = mp_parse(path, default_tension = tension, default_curl = curl) # print repr(new_path) solve_angles(new_path) find_controls(new_path) if command==None: command="draw" if options==None: options = "" else: options = "[%s]" % options return "\\%s%s %s;" % (command, options, str(new_path)) def mp_parse(mppath, default_tension = 1, default_curl = 1): """This function receives a string which contains a path in metapost syntax, and returns a Path object which stores the same path in the structure required to compute the control points. The path should only contain explicit coordinates and numbers. Currently only "curl" and "tension" keywords are understood. Direction options are ignored.""" if mppath.endswith(";"): # Remove last semicolon mppath=mppath[:-1] pts = mppath.split("..") # obtain points pts = [p.strip() for p in pts] # remove extra spaces if pts[-1] == "cycle": is_cyclic = True pts=pts[:-1] # Remove this last keyword else: is_cyclic = False path = Path([], cyclic=is_cyclic) path.curl_begin = default_curl path.curl_end = default_curl alpha = beta = 1.0/default_tension k=0 for p in pts: if p.startswith("tension"): aux = p.split() alpha = 1.0/float(aux[1]) if len(aux)>3: beta = 1.0/float(aux[3]) else: beta = alpha else: aux = p.split("{") # Extra options at the point p = aux[0].strip() if p.startswith("curl"): if k==0: path.curl_begin=float(aux[1]) else: path.curl_end = float(aux[1]) elif p.startswith("dir"): # Ignored by now pass path.append(Point(eval(p))) # store the pair of coordinates # Update tensions path[k-1].alpha = alpha path[k].beta = beta alpha = beta = 1.0/default_tension k = k + 1 if is_cyclic: path[k-1].alpha = alpha path[k].beta = beta return path def main(): """Example of conversion. Takes a string from stdin and outputs the result in stdout. """ import sys if len(sys.argv)>2: opts = sys.argv[2] else: opts = None path = sys.argv[1] print mp_to_tikz(path, options = opts) if __name__ == "__main__": main()
[ "jensaxel@soegaard.net" ]
jensaxel@soegaard.net
6a11aaf1bc257f2f416c231f044632aa65ec9aa7
2981d4badf5fe011000ba53721601e8ebca73d62
/main.py
7e707080b48efc3463e752f30a4b3b33eace5017
[]
no_license
rishabh33333/CRD-operations
a298a272137a64c2e774e1b4919fb0d231b5482c
1d8328c97f15d48d870e401ecdc995df477fdd98
refs/heads/main
2023-02-08T12:47:47.289465
2021-01-01T08:57:10
2021-01-01T08:57:10
325,937,859
0
0
null
null
null
null
UTF-8
Python
false
false
1,868
py
import threading from threading import* import time dictionary={} def create(key,value,t_out=0): if key in d: print("Error") else: if(key.isalpha()): if len(dictionary)<(1024*1024*1024) and value<=(16*1024*1024): if t_out==0: lst=[value,t_out] else: lst=[value,time.time()+t_out] if len(key)<=32: dictionary[key]=lst else: print("Error") else: print("Error") def read(key): if key not in dictionary: print("Error") else: var=dictionary[key] if var[1]!=0: if time.time()<var[1]: string=str(key)+":"+str(var[0]) return string else: print("Error") else: string=str(key)+":"+str(var[0]) return string def delete(key): if key not in dictionary: print("Error") else: var=dictionary[key] if var[1]!=0: if time.time()<var[1]: del dictionary[key] print("key is Deleted") else: print("Error") else: del dictionary[key] print("key is successfully deleted") def modify(key,value): var=dictionary[key] if var[1]!=0: if time.time()<var[1]: if key not in dictionary: print("Error") else: lst=[] lst.append(value) lst.append(var[1]) dictionary[key]=lst else: print("Error") else: if key not in dictionary: print("Error") else: lst=[] lst.append(value) lst.append(var[1]) d[key]=lst
[ "noreply@github.com" ]
rishabh33333.noreply@github.com
adaa3deb4da40a41e388cf7cf2be1f9380c5b2a1
042c4a9e4fcc82f2583e2f694ffe87362ff4018a
/rssit/generators/flickr.py
d22b36cbe2baec58484416ae909fbc57c2bed0ca
[ "MIT" ]
permissive
Greenrenge/rssit
afcd4e3961d1a94562060c4088be5dd065564369
da04ee775fb9cb2e8a34cf8878690dc74ad5e005
refs/heads/master
2020-08-27T05:02:58.748837
2019-08-21T20:26:43
2019-08-21T20:26:43
217,251,598
1
0
null
2019-10-24T08:37:45
2019-10-24T08:37:44
null
UTF-8
Python
false
false
7,885
py
# -*- coding: utf-8 -*- import re import rssit.util import datetime import urllib.parse from dateutil.tz import * import sys import pprint def get_modelExport(data): jsondatare = re.search(r"modelExport: *(?P<json>.*?), *\n", str(data)) if jsondatare == None: return None jsondata = jsondatare.group("json") jsondata = rssit.util.fix_surrogates(jsondata) return rssit.util.json_loads(jsondata) def get_url(config, url): match = re.match(r"^(https?://)?(?:\w+\.)?flickr\.com/photos/(?P<user>[^/]*)/*", url) if match is None: return None data = rssit.util.download(url) if not data: return None decoded = get_modelExport(data) if not decoded: return None return "/photos/" + decoded["photostream-models"][0]["owner"]["id"] photo_size_order = ["o", "k", "h", "b", "c", "n", "m", "t", "sq", "s"] def get_photo_url_website(sizes): for o in photo_size_order: if o in sizes: return sizes[o]["url"] return None def get_photo_url_api(photo): if "originalsecret" in photo and False: return "https://farm%i.staticflickr.com/%s/%s_%s_o.%s" % ( photo["farm"], photo["server"], photo["id"], photo["originalsecret"], photo["originalformat"] ) for o in photo_size_order: key = "url_" + o if key in photo: return photo[key] return None def generate_photos_url(config, user): url = "https://www.flickr.com/photos/" + user data = rssit.util.download(url) decoded = get_modelExport(data) photostream = decoded["photostream-models"][0] username = photostream["owner"]["username"] author = username if not config["author_username"] and "realname" in photostream["owner"]: if len(photostream["owner"]["realname"]) > 0: author = photostream["owner"]["realname"] feed = { "title": author, "description": "%s's flickr" % username, "url": url, "author": username, "social": True, "entries": [] } photopage = photostream["photoPageList"]["_data"] for photo in photopage: if not photo: continue if "title" in photo: caption = photo["title"] else: caption = "" newcaption = str(photo["id"]) + " " + caption newcaption = newcaption.strip() date = datetime.datetime.fromtimestamp(int(photo["stats"]["datePosted"]), None).replace(tzinfo=tzlocal()) images = [urllib.parse.urljoin(url, get_photo_url_website(photo["sizes"]))] if not images[0]: print("Skipping flickr image " + caption) continue feed["entries"].append({ "url": "https://www.flickr.com/photos/%s/%s" % ( user, photo["id"] ), "caption": caption, "media_caption": newcaption, "similarcaption": caption, "author": username, "date": date, "images": images, "videos": [] }) return feed websiteapikey = None def update_api_key(): global websiteapikey data = rssit.util.download("https://www.flickr.com") match = re.search(r"^root\.YUI_config\.flickr\.api\.site_key *= *['\"]([^['\"]*)['\"] *; *$", data, re.M) websiteapikey = match.group(1) def do_api_call(endpoint, *args, **kwargs): if "__times" in kwargs and kwargs["__times"] > 3: sys.stderr.write("Warning: >3 times called for flickr API\n") return if not websiteapikey: update_api_key() url = "https://api.flickr.com/services/rest?csrf=&api_key=%s&format=json&nojsoncallback=1&method=%s" % ( websiteapikey, endpoint ) times = 0 if "__times" in kwargs: times = kwargs["__times"] del kwargs["__times"] querystring = urllib.parse.urlencode(kwargs) if querystring: url = url + "&" + querystring data = rssit.util.download(url) ret = rssit.util.json_loads(data) if "code" in ret and ret["code"] == 100: update_api_key() kwargs["__times"] = times + 1 return do_api_call(endpoint, *args, **kwargs) return ret def get_user_info(config, user): if "@N" in user: return do_api_call("flickr.people.getInfo", user_id=user)["person"] else: return do_api_call("flickr.people.findByUserName", username=user)["user"] def generate_photos_api(config, user): userinfo = get_user_info(config, user) mediacount = userinfo["photos"]["count"] username = userinfo["username"]["_content"] author = username if not config["author_username"] and "realname" in userinfo: if len(userinfo["realname"]["_content"]) > 0: author = userinfo["realname"]["_content"] feed = { "title": author, "description": "%s's flickr" % username, "url": "https://www.flickr.com/photos/" + user, "author": username, "social": True, "entries": [] } mediacount = 0 if config["count"] < 0: mediacount = userinfo["photos"]["count"] count = config["count"] if count < 0 or count == 1: count = 500 def func(page): if not page: page = 1 photos_api = do_api_call("flickr.people.getPublicPhotos", user_id = user, safe_search = 3, per_page = count, page = 1, extras = "original_format,date_upload,url_o,url_k,url_h,url_b,url_c,url_z,url_n,url_m,url_t")["photos"] if not photos_api: return None photos = photos_api["photo"] page = page + 1 return (photos, page, None) photos = rssit.util.paginate(config, mediacount, func) for photo in photos: if "title" in photo: caption = photo["title"] else: caption = "" newcaption = str(photo["id"]) + " " + caption newcaption = newcaption.strip() myentry = { "url": "https://www.flickr.com/photos/%s/%s" % ( user, photo["id"] ), "caption": caption, "media_caption": newcaption, "similarcaption": caption, "author": username, "date": rssit.util.localize_datetime(datetime.datetime.fromtimestamp(int(photo["dateupload"]))), "images": [get_photo_url_api(photo)], "videos": [], } if myentry["images"][0] is None: sys.stderr.write("Skipping image " + photo["title"] + "\n") continue feed["entries"].append(myentry) return feed def generate_photos(config, user): if config["prefer_api"]: return ("social", generate_photos_api(config, user)) else: return ("social", generate_photos_url(config, user)) def process(server, config, path): if path.startswith("/photos/"): return generate_photos(config, path[len("/photos/"):]) infos = [{ "name": "flickr", "display_name": "Flickr", "endpoints": { "photos": { "name": "User's feed", "process": lambda server, config, path: generate_photos(config, path) } }, "config": { "author_username": { "name": "Author = Username", "description": "Set the author's name to be their username", "value": False }, "prefer_api": { "name": "Prefer API over website", "description": "Prefers the use of the flickr API instead of scraping the website", "value": True } }, "get_url": get_url, "process": process }]
[ "qsniyg@mail.com" ]
qsniyg@mail.com
1f14d4d88744b36e960d170bd87c5ffdbc7c4033
2e15bd293fa7b341c9359d241dc8654a6d556974
/test.py
5a33ad990cd39b197f097502c834393e081ba638
[]
no_license
LeeJinbeom/studymc
0c8f563f0cc3e02cc4791728f2c5748160322f34
4b89e37aabc4af5196acc5c6d7ce7718cabfa4a5
refs/heads/master
2020-06-24T23:13:31.629889
2019-07-27T06:49:58
2019-07-27T06:49:58
199,120,957
0
0
null
2019-07-27T06:40:34
2019-07-27T05:34:11
null
UTF-8
Python
false
false
18
py
안녕하세요?!
[ "jinbomang@gmail.com" ]
jinbomang@gmail.com
40636878bc957e7a001c89e44464577dd0c9069c
4f6ca4efa79a74853c8ef5d417aef55d0900df82
/blacksheep/server/errors.py
0453a1135b5988fe93384208178e203b44d41e8c
[ "MIT" ]
permissive
kun1996/BlackSheep
b9c079e6ee23a1f881c77ad59f1ff3e6f10728f7
02303499b55cae835cca7c55c8f5e48eb5beae31
refs/heads/main
2023-04-03T13:31:25.194283
2021-04-24T07:17:59
2021-04-24T07:17:59
362,502,399
1
0
MIT
2021-04-28T14:42:04
2021-04-28T14:42:03
null
UTF-8
Python
false
false
1,679
py
import html import traceback from blacksheep.contents import HTMLContent from blacksheep.messages import Request, Response from blacksheep.server.asgi import get_request_url from blacksheep.server.resources import get_resource_file_content def _load_error_page_template() -> str: error_css = get_resource_file_content("error.css") error_template = get_resource_file_content("error.html") assert "/*STYLES*/" in error_template # since later it is used in format_map... error_css = error_css.replace("{", "{{").replace("}", "}}") return error_template.replace("/*STYLES*/", error_css) class ServerErrorDetailsHandler: """ This class is responsible of producing a detailed response when the Application is configured to show error details to the client, and an unhandled exception happens. """ def __init__(self) -> None: self._error_page_template = _load_error_page_template() def produce_response(self, request: Request, exc: Exception) -> Response: tb = traceback.format_exception(exc.__class__, exc, exc.__traceback__) info = "" for item in tb: info += f"<li><pre>{html.escape(item)}</pre></li>" content = HTMLContent( self._error_page_template.format_map( { "info": info, "exctype": exc.__class__.__name__, "excmessage": str(exc), "method": request.method, "path": request.url.value.decode(), "full_url": get_request_url(request), } ) ) return Response(500, content=content)
[ "noreply@github.com" ]
kun1996.noreply@github.com
5ba6490e8b6c7bbfb345d1c1f2a2e5a6fa6a8975
68b27892c5eac64a5c11dd2c091f2c825724465e
/aep/__init__.py
26f39d63548fa4b6bf0ec8bf47e8c91ec3fb755b
[]
no_license
aoki-marika/aeptools
170df57004be5a14db5038f46eb26d1251a6888e
d1b0b5b8a0243a7449e067da27e7ecfcbf56d23f
refs/heads/main
2023-02-06T04:25:25.161128
2020-12-19T18:51:37
2020-12-19T18:51:39
321,742,554
4
0
null
null
null
null
UTF-8
Python
false
false
102
py
from .bin import Architecture, BinaryDecoder, BinaryEncoder from .json import JsonDecoder, JsonEncoder
[ "marika@waifu.club" ]
marika@waifu.club
fc879af89453fdb1a9365988678c037439c3c6df
bbaf96b7055a9cf9be20f4795200dfe4aa27127f
/employee/migrations/0001_initial.py
d8e1d4c0343de1785a67f2038c2186b1263f8eef
[]
no_license
Ajaychaudhari01/empoloyee-manage-system
d4b3f4cb2681346dcbeb8be031e631e9f8123a8a
af5122cc92ee66a3596f7593c6550cf7f00ba6df
refs/heads/main
2022-12-28T21:19:06.239651
2020-10-14T15:52:45
2020-10-14T15:52:45
304,061,541
0
0
null
null
null
null
UTF-8
Python
false
false
928
py
# Generated by Django 3.0.2 on 2020-01-19 17:08 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('designation', models.CharField(max_length=40)), ('salary', models.IntegerField(blank=True, null=True)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('-salary',), }, ), ]
[ "noreply@github.com" ]
Ajaychaudhari01.noreply@github.com
80dc0d7cb644b7c68b7d08b5079a4f055b44b30c
162b051018b90c06d8218de502ba95d6952ff3df
/Medidor de Rendimiento/rendimiento.py
7f94f0878f228d66c746a7f058e50e797dfd1cfa
[]
no_license
VinicioPazmino/MedidorEvaluadorRendimiento
3f9e065f5c3a47d3b57f05e76e723caa15f56d96
7d3b3ec391dd3ef1f076da8c7ff930c8fb70a8a6
refs/heads/master
2022-11-18T22:13:36.039217
2020-07-20T22:30:55
2020-07-20T22:30:55
281,238,646
0
0
null
null
null
null
UTF-8
Python
false
false
1,377
py
# Vinicio Pazmiño & Alexander Benalcazar # 2020/5/27 # vinidavid_17@hotmail.com # Universidad Autonoma de Madrid import sys import os import psutil import statistics from gpuinfo import GPUInfo import time from random import * vram=8088 # MB file = open("RendimientoAgrupados.txt", "w") tiempo = int(input("Ingrese tiempo para tomar datos (segundos)[ejem 120s]: ")) intervalo = float(input("Ingrese intervalo de tiempo entre muestra (segundos)[ejem 0.5s]: ")) muestras = int(tiempo/intervalo) while True: selecOption= input("realizar Experimento[y / n]: ") if selecOption == "n": break else: label = input("Nombre del Experimento [ejem: 320x240]: ") for x in range(muestras): cpu_per= psutil.cpu_percent(interval=intervalo) # % de uso CPU aux = psutil.virtual_memory() ram = aux[2] # % de uso Ram gpu_percent,gpu_memory=GPUInfo.gpu_usage() gpu=gpu_percent[0]+round(random(),1) # % de uso GPU gpu_vram=round((gpu_memory[0]*100)/vram,1) # % uso RAM GPU file.write(str(cpu_per)+" ") file.write(str(ram)+" ") file.write(str(gpu)+" ") file.write(str(gpu_vram)+" ") file.write(label+"\n") file.close() print("TiempoTranscurrido(s)="+str(tiempo)+" NúmeroMuestras="+str(muestras)) time.sleep(8)
[ "vinidavid_17@hotmail.com" ]
vinidavid_17@hotmail.com
fb51e844fdd96bd691e03109506a829551947b9a
8536d38f770900cd01cae2d082634226bd5c1246
/apps/dogs/migrations/0006_alter_dog_origin.py
43f3a882d54dd5efd7e2489e80d3d0dca6f868db
[]
no_license
Mutuba/Public_API_data
6da197e87297bcb5e7956df1efba7f860741d642
be5ad8e9d3d4bdbbe1000b9f0037c7852ace2bb5
refs/heads/master
2023-05-26T19:22:46.859821
2021-06-19T12:08:40
2021-06-19T12:09:25
373,883,565
0
0
null
null
null
null
UTF-8
Python
false
false
376
py
# Generated by Django 3.2.4 on 2021-06-03 10:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("dogs", "0005_auto_20210603_1051"), ] operations = [ migrations.AlterField( model_name="dog", name="origin", field=models.TextField(null=True), ), ]
[ "danielmutubait@gmail.com" ]
danielmutubait@gmail.com
550963b0476668c3fa07aaabf2e0cb13082c0b40
b1541fbff1276e557f6b594375cfdfb578ff26a7
/FuncTokTagCount.py
febf2687b97e9099262cc5b0e17a3b19a362d3dd
[]
no_license
OrangeXenon54/Group-13-Computational-Linguistics-Team-Lab-2019
974a281d34bfd2e174f78c1ff0b6d5bb9670edc4
4b8ffdde31916b81d1301bec55fdbe0adbceb5c9
refs/heads/master
2020-05-09T22:03:16.838841
2019-08-02T20:45:04
2019-08-02T20:45:04
181,457,604
0
0
null
null
null
null
UTF-8
Python
false
false
1,733
py
import re def TagCandP(TagNum) : tagN = [] if TagNum == 1 : for keyT, valT in alltokens.items() : if len(valT) == 1 : tokenPOScount = [keyT, valT] tagN.append(tokenPOScount) else : continue else : for keyT, valT in alltokens.items() : if len(valT) == TagNum : for keyP, valP in alltokens[keyT].items() : tokenPOScount = [keyT, keyP, valP] tagN.append(tokenPOScount) else : continue if len(tagN) < 1 : print("No tokens with just ", TagNum, " POS tags \n") else : tagNpercent = len(tagN) / nc / tokentotal print("--", TagNum, " POS Tag Count: ", len(tagN)) print(tagNpercent, " of all tokens\n") filename = input("Please type file name:") devtext = open(filename) alltokens = {} tagcount = {} print("Starting data reading: ") for line in devtext : if line == "\n" : continue else : stripped = line.strip() word = re.findall('(^\S*)\s', stripped)[0] postag = re.findall('\s(\S*$)', stripped)[0] if word not in alltokens : alltokens[word] = {} alltokens[word][postag] = 1 elif postag not in alltokens[word] : alltokens[word][postag] = 1 elif postag in alltokens[word] : alltokens[word][postag] += 1 tokentotal = len(alltokens) print("Data reading finished") print("---------------") print("Total Number of Tokens: ", tokentotal, "\n") nc = 1 while True : TagCandP(nc) nc += 1 if nc == 49 : break
[ "noreply@github.com" ]
OrangeXenon54.noreply@github.com
eec3aeabbd3dd7ca1c053ea0256e669cb5ef1b77
5434c1e952766297ac49a9164eb98b6fdb764f1b
/testObj.py
405f276d15214a6fc0bd0a8597940bdb8647e1d6
[]
no_license
luohuaizhi/test
365f97a1f615cebcd7588d3625f2a7a6b95eb898
296c983dfb2724b2925f2307d470538216cc50a5
refs/heads/master
2021-04-25T20:52:18.538204
2018-06-04T08:11:52
2018-06-04T08:11:52
109,222,335
0
2
null
2018-02-05T07:13:42
2017-11-02T05:41:31
Python
UTF-8
Python
false
false
763
py
# -*- encoding:utf-8-*- class Obj(object): def __call__(self, name): print "__call__ of %s" % name def __new__(cls, name): print "__new__" return super(Obj, cls).__new__(cls) # def __new__(cls, name, bases, attrs): # print "__new__" # return super(Obj, cls).__new__(cls, name, bases, attrs) def __init__(self, name): self.name = name print "__init__" def __del__(self): print "I'm del" def mydefault(self, *args): print "default" def __getattr__(self, name): print "call fn: ", name return self.mydefault def main(): obj = Obj("test") print obj.name obj("james") obj.tt() if __name__ == '__main__': main()
[ "luohuaizhi@9ffenqigo.com" ]
luohuaizhi@9ffenqigo.com
52596f51edd99aee66662e55c745507c75817742
8fa6ac43fe6dc73862606907c6b0e37ecda366f1
/stubs/asn1crypto/algos.py
917a6303d2953757237514cbf57262fcd2183266
[ "MIT" ]
permissive
joernheissler/cryptokey
b0999172ada29278e0ac2728c81a10e225664eae
d288a42c2234b7b48de23247a909c8f2d04398dd
refs/heads/master
2021-05-12T12:29:32.776279
2019-11-11T07:27:48
2019-11-11T07:27:48
117,415,948
0
0
null
null
null
null
UTF-8
Python
false
false
140
py
from __future__ import annotations from .core import Sequence class DigestInfo(Sequence): ... class DSASignature(Sequence): ...
[ "nosuchaddress@joern.heissler.de" ]
nosuchaddress@joern.heissler.de
fbd33584bdbd458d6858b8e8fc763fe54ff0bc6a
61eac29f7e6112e3b5a8aaa39bdc440ed4351aea
/src/tests/test_logger.py
da0f9341ecee4af458cb56483959722b3b5f79a3
[ "HPND", "MIT", "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
ArisBee/PyBitmessage
cf9285a2e1a7bf97376a5b691d8b34c9702fdb52
dbfd96315b4f227aa641033ecbfa758f206d88cc
refs/heads/v0.6
2023-07-09T19:55:44.755629
2021-08-16T19:32:04
2021-08-16T19:32:04
347,017,788
0
1
NOASSERTION
2021-03-29T13:28:37
2021-03-12T09:53:11
null
UTF-8
Python
false
false
1,173
py
""" Testing the logger configuration """ import os import tempfile from .test_process import TestProcessProto class TestLogger(TestProcessProto): """A test case for logger configuration""" pattern = r' <===> ' conf_template = ''' [loggers] keys=root [handlers] keys=default [formatters] keys=default [formatter_default] format=%(asctime)s {1} %(message)s [handler_default] class=FileHandler level=NOTSET formatter=default args=('{0}', 'w') [logger_root] level=DEBUG handlers=default ''' @classmethod def setUpClass(cls): cls.home = tempfile.mkdtemp() cls._files = cls._files[2:] + ('logging.dat',) cls.log_file = os.path.join(cls.home, 'debug.log') with open(os.path.join(cls.home, 'logging.dat'), 'wb') as dst: dst.write(cls.conf_template.format(cls.log_file, cls.pattern)) super(TestLogger, cls).setUpClass() def test_fileConfig(self): """Check that our logging.dat was used""" self._stop_process() data = open(self.log_file).read() self.assertRegexpMatches(data, self.pattern) self.assertRegexpMatches(data, 'Loaded logger configuration')
[ "4glitch@gmail.com" ]
4glitch@gmail.com
bb0fd8139104d65db7a2325b4dcf41355b88aa0f
103facfefd464cd02c17efe652a0252447365855
/ex01a.py
ef1173e91ac0079f76fc80ed49d7e37a7253fcbc
[]
no_license
mascarenhasl/pythontest
390712795e3bf66110ea4e3c6b7b8c2cc0e9fffe
437891f66dfda61b10b466921852b3dff0edf6b5
refs/heads/master
2020-03-24T16:09:29.929540
2018-07-30T03:21:05
2018-07-30T03:21:05
142,814,669
0
0
null
null
null
null
UTF-8
Python
false
false
8
py
# Ex01a
[ "madcarenhasl@yahoo.com" ]
madcarenhasl@yahoo.com