diff --git "a/3542.jsonl" "b/3542.jsonl" new file mode 100644--- /dev/null +++ "b/3542.jsonl" @@ -0,0 +1,740 @@ +{"seq_id":"114531548","text":"# from nltk.tokenize import word_tokenize\nfrom nltk.util import ngrams\nfrom pyjarowinkler import distance\nimport re\n\ndef get_ngrams(text, n ):\n n_grams = ngrams(text.split(), n)\n return [ ' '.join(grams) for grams in n_grams]\n\ndef toTeks(ng):\n teks_ = []\n for i in ng:\n a = i.split()\n a = \"\".join(a)\n teks_.append(a)\n return \" \".join(teks_)\n\ndef hapusKosong(ass):\n apa = []\n for i in ass:\n if i != '':\n apa.append(i)\n return apa\ndef cek_tipo(kunci_jawaban, jawaban, toleransi=0.97):\n kunci_jawaban_split = kunci_jawaban.split()\n jawaban_split = jawaban.split()\n #n_jawaban = jawaban_split\n for i in range(len(jawaban_split)):\n w_1 = []\n n_jawaban = jawaban_split\n kunci_jawaban_ = []\n for j in kunci_jawaban_split:\n w_1.append(distance.get_jaro_distance(jawaban_split[i], j, winkler=True, scaling=0.1))\n kunci_jawaban_.append(j)\n if max(w_1) >= toleransi:\n index = w_1.index(max(w_1))\n n_jawaban[i]= kunci_jawaban_[index]\n else:\n n_jawaban[i]=\"\"\n x= hapusKosong(n_jawaban)\n \n return \" \".join(x)\n\ndef pisahKata(dicari, jawaban):\n dicari_split = dicari.split()\n jawaban_split = jawaban.split()\n for h in dicari_split:\n for ct, i in enumerate(jawaban_split) :\n p_dicari = len(h)\n index_depan = 0\n if re.search(h, i):\n index_depan = re.search(h, i).start()\n index_akhir = re.search(h, i).end()\n if len(i) >= p_dicari:\n if re.search(h, i):\n i = [x for x in i]\n i.insert(index_akhir, \" \")\n if index_depan != 0:\n i.insert(index_depan, \" \")\n i = \"\".join(i)\n jawaban_split[ct] = i\n return \" \".join(jawaban_split)\n\ndef en_geram(kunci,teks):\n \n panjangTkes = teks.split()\n #print(len(panjangTkes))\n if len(panjangTkes)<2:\n return teks\n elif len(panjangTkes)<3:\n ng2 = get_ngrams(teks,2)\n tks = ng2\n jawaban = toTeks(tks)\n # return jawaban\n return cek_tipo(kunci, jawaban)\n elif len(panjangTkes)<4:\n ng3 = get_ngrams(teks,3)\n ng2 = get_ngrams(teks,2)\n tks = ng2+ng3\n jawaban = toTeks(tks)\n # return jawaban\n return cek_tipo(kunci, jawaban)\n elif len(panjangTkes) >= 4:\n ng3 = get_ngrams(teks,3)\n ng2 = get_ngrams(teks,2)\n ng4 = get_ngrams(teks,4)\n tks = ng2+ng3+ng4\n jawaban = toTeks(tks)\n # return jawaban\n return cek_tipo(kunci, jawaban)","sub_path":"ES/Nawa/ngram.py","file_name":"ngram.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"437630913","text":"import binascii\nimport json\nimport logging\nfrom collections import OrderedDict\nfrom enum import Enum\nfrom typing import Optional, Dict, Union\nfrom decimal import Decimal\n\nimport requests\nfrom secp256k1 import PrivateKey\n\nfrom .exceptions import (\n BinanceChainAPIException, BinanceChainRequestException\n)\nfrom .dex_pb2 import NewOrder, CancelOrder, TokenFreeze, TokenUnfreeze, StdTx, StdSignature\nfrom .segwit_addr import decode_address\nfrom .utils import encode_number, varint_encode\n\n\n# An identifier for tools triggering broadcast transactions, set to zero if unwilling to disclose.\nBROADCAST_SOURCE = 1\n\n\nclass KlineInterval(str, Enum):\n ONE_MINUTE = '1m'\n THREE_MINUTES = '3m'\n FVE_MINUTES = '5m'\n FIFTEEN_MINUTES = '15m'\n THIRTY_MINUTES = '30m'\n ONE_HOUR = '1h'\n TWO_HOURS = '2h'\n FOUR_HOURS = '4h'\n SIX_HOURS = '6h'\n EIGHT_HOURS = '8h'\n TWELVE_HOURS = '12h'\n ONE_DAY = '1d'\n THREE_DAYS = '3d'\n ONE_WEEK = '1w'\n ONE_MONTH = '1M'\n\n\nclass OrderStatus(str, Enum):\n ACK = 'Ack'\n PARTIAL_FILL = 'PartialFill'\n IOC_NO_FILL = 'IocNoFill'\n FULLY_FILL = 'FullyFill'\n CANCELED = 'Canceled'\n EXPIRED = 'Expired'\n FAILED_BLOCKING = 'FailedBlocking'\n FAILED_MATCHING = 'FailedMatching'\n\n\nclass OrderSide(str, Enum):\n BUY = 'buy'\n SELL = 'sell'\n\n\nclass TimeInForce(str, Enum):\n GOOD_TILL_EXPIRE = \"GTE\"\n IMMEDIATE_OR_CANCEL = \"IOC\"\n\n\nclass TransactionSide(str, Enum):\n RECEIVE = 'RECEIVE'\n SEND = 'SEND'\n\n\nclass TransactionType(str, Enum):\n NEW_ORDER = 'NEW_ORDER'\n ISSUE_TOKEN = 'ISSUE_TOKEN'\n BURN_TOKEN = 'BURN_TOKEN'\n LIST_TOKEN = 'LIST_TOKEN'\n CANCEL_ORDER = 'CANCEL_ORDER'\n FREEZE_TOKEN = 'FREEZE_TOKEN'\n UN_FREEZE_TOKEN = 'UN_FREEZE_TOKEN'\n TRANSFER = 'TRANSFER'\n PROPOSAL = 'PROPOSAL'\n VOTE = 'VOTE'\n\n\nclass OrderType(str, Enum):\n LIMIT = \"LIMIT\"\n MARKET = \"MARKET\"\n\n\nclass PeerType(str, Enum):\n NODE = 'node'\n WEBSOCKET = 'ws'\n\n\nclass Wallet:\n\n def __init__(self, address, private_key):\n\n self._address = address\n self._private_key = private_key\n\n self._pk = PrivateKey(bytes(bytearray.fromhex(private_key)))\n self._public_key = self._pk.pubkey.serialize(compressed=True)\n\n @property\n def address(self):\n return self._address\n\n @property\n def private_key(self):\n return self._private_key\n\n @property\n def public_key(self):\n return self._public_key\n\n def sign_message(self, msg_bytes):\n sig = self._pk.ecdsa_sign(msg_bytes)\n return self._pk.ecdsa_serialize_compact(sig)\n\n\nclass Signature:\n\n def __init__(self, msg, account, data=None, chain_id='Binance-Chain-Nile', memo=''):\n self._msg = msg\n self._account = account\n self._chain_id = chain_id\n self._data = data\n self._memo = memo\n self._source = BROADCAST_SOURCE\n\n def to_json(self):\n return json.dumps(OrderedDict([\n ('account_number', str(self._account['account_number'])),\n ('chain_id', self._chain_id),\n ('data', self._data),\n ('memo', self._memo),\n ('msgs', [self._msg.to_dict(self._account)]),\n ('sequence', str(self._account['sequence'])),\n ('source', str(self._source))\n ]), separators=(',', ':'), ensure_ascii=False)\n\n def to_bytes_json(self):\n print(f\"json sig:{self.to_json()}\")\n return self.to_json().encode()\n\n def sign(self, wallet):\n # sign string\n json_bytes = self.to_bytes_json()\n\n signed = wallet.sign_message(json_bytes)\n print(f\"signed: len:{len(signed)}:{signed}\")\n return signed[-64:]\n\n\nclass Msg:\n\n AMINO_MESSAGE_TYPE = \"\"\n INCLUDE_AMINO_LENGTH_PREFIX = False\n\n def to_dict(self, account) -> Dict:\n return {}\n\n def to_protobuf(self, account):\n pass\n\n def to_amino(self, account):\n proto = self.to_protobuf(account)\n # wrap with type\n\n if type(proto) != bytes:\n proto = proto.SerializeToString()\n\n type_bytes = b\"\"\n if self.AMINO_MESSAGE_TYPE:\n type_bytes = binascii.unhexlify(self.AMINO_MESSAGE_TYPE)\n print(f'msg len: {self.AMINO_MESSAGE_TYPE} {(len(proto) + len(type_bytes))} varint:{binascii.hexlify(varint_encode((len(proto) + len(type_bytes))))}')\n varint_length = varint_encode(len(proto) + len(type_bytes))\n else:\n print(f'sig len:{len(proto)} varint:{binascii.hexlify(varint_encode(len(proto)))}')\n varint_length = varint_encode(len(proto))\n\n msg = b\"\"\n if self.INCLUDE_AMINO_LENGTH_PREFIX:\n msg += varint_length\n msg += type_bytes + proto\n\n print(f\"msg {self.AMINO_MESSAGE_TYPE} {binascii.hexlify(msg)}\")\n\n return msg\n\n\nclass NewOrderMsg(Msg):\n\n ORDER_SIDE_INT = {\n OrderSide.BUY: 1,\n OrderSide.SELL: 2\n }\n\n ORDER_TYPE_INT = {\n OrderType.MARKET: 1,\n OrderType.LIMIT: 2\n }\n\n TIME_IN_FORCE_INT = {\n TimeInForce.GOOD_TILL_EXPIRE: 1,\n TimeInForce.IMMEDIATE_OR_CANCEL: 3\n }\n\n AMINO_MESSAGE_TYPE = b\"CE6DC043\"\n\n def __init__(self, symbol: str, time_in_force: TimeInForce, order_type: OrderType, side: OrderSide,\n price: Union[int, float, Decimal], quantity: Union[int, float, Decimal]):\n \"\"\"NewOrder transaction creates a new order to buy and sell tokens on Binance DEX.\n\n :param symbol: symbol for trading pair in full name of the tokens e.g. 'ANN-457_BNB'\n :param time_in_force: TimeInForce type (GOOD_TILL_EXPIRE, IMMEDIATE_OR_CANCEL)\n :param order_type: OrderType (LIMIT, MARKET)\n :param side: OrderSide (BUY, SELL)\n :param price: price of the order e.g. Decimal(0.000396000) or 0.002384\n :param quantity: quantity of the order Decimal(12) or 12\n\n \"\"\"\n self._symbol = symbol\n self._time_in_force = NewOrderMsg.TIME_IN_FORCE_INT[time_in_force]\n self._order_type = NewOrderMsg.ORDER_TYPE_INT[order_type]\n self._side = NewOrderMsg.ORDER_SIDE_INT[side]\n self._price = encode_number(price)\n self._quantity = encode_number(quantity)\n\n def to_dict(self, account) -> Dict:\n order_id = self._generate_order_id(account)\n return OrderedDict([\n ('id', order_id),\n ('ordertype', self._order_type),\n ('price', self._price),\n ('quantity', self._quantity),\n ('sender', account['address']),\n ('side', self._side),\n ('symbol', self._symbol),\n ('timeinforce', self._time_in_force),\n ])\n\n def to_protobuf(self, account) -> NewOrder:\n pb = NewOrder()\n account_code = decode_address(account['address'])\n pb.sender = account_code\n pb.id = self._generate_order_id(account)\n pb.symbol = self._symbol.encode()\n pb.timeinforce = self._time_in_force\n pb.ordertype = self._order_type\n pb.side = self._side\n pb.price = self._price\n pb.quantity = self._quantity\n return pb\n\n def _generate_order_id(self, account):\n account_code = decode_address(account['address'])\n order_id = f\"{binascii.hexlify(account_code).decode().upper()}-{(account['sequence'] + 1)}\"\n return order_id\n\n\nclass CancelOrderMsg(Msg):\n\n AMINO_MESSAGE_TYPE = b\"166E681B\"\n\n def __init__(self, symbol: str, order_id: str):\n \"\"\"Cancel transactions cancel the outstanding (unfilled) orders from the Binance DEX. After cancel success,\n the locked quantity on the orders would return back to the address' balance and become free to use,\n i.e. transfer or send new orders.\n\n :param symbol: symbol for trading pair in full name of the tokens\n :param order_id: order id of the one to cancel\n \"\"\"\n self._symbol = symbol\n self._order_id = order_id\n\n def to_dict(self, account):\n return OrderedDict([\n ('refid', self._order_id),\n ('sender', account['address']),\n ('symbol', self._symbol),\n ])\n\n def to_protobuf(self, account) -> CancelOrder:\n pb = CancelOrder()\n account_code = decode_address(account['address'])\n pb.sender = account_code\n pb.refid = self._order_id\n pb.symbol = self._symbol.encode()\n return pb\n\n\nclass FreezeMsg(Msg):\n\n AMINO_MESSAGE_TYPE = b\"E774B32D\"\n\n def __init__(self, symbol: str, amount: Union[int, float, Decimal]):\n \"\"\"Freeze transaction moves the amount of the tokens into a frozen state,\n in which it cannot be used to transfer or send new orders.\n\n :param symbol: token symbol, in full name with \"-\" suffix\n :param amount: amount of token to freeze\n \"\"\"\n self._symbol = symbol\n self._amount = encode_number(amount)\n\n def to_dict(self, account):\n return OrderedDict([\n ('amount', self._amount),\n ('from', account['address']),\n ('symbol', self._symbol),\n ])\n\n def to_protobuf(self, account) -> TokenFreeze:\n pb = TokenFreeze()\n account_code = decode_address(account['address'])\n setattr(pb, 'from', account_code)\n pb.symbol = self._symbol.encode()\n pb.amount = self._amount\n return pb\n\n\nclass UnFreezeMsg(Msg):\n\n AMINO_MESSAGE_TYPE = b\"6515FF0D\"\n\n def __init__(self, symbol: str, amount: Union[int, float, Decimal]):\n \"\"\"Turn the amount of frozen tokens back to free state.\n\n :param symbol: token symbol, in full name with \"-\" suffix\n :param amount: amount of token to unfreeze\n \"\"\"\n self._symbol = symbol\n self._amount = encode_number(amount)\n\n def to_dict(self, account):\n return OrderedDict([\n ('amount', self._amount),\n ('from', account['address']),\n ('symbol', self._symbol),\n ])\n\n def to_protobuf(self, account) -> TokenUnfreeze:\n pb = TokenUnfreeze()\n account_code = decode_address(account['address'])\n setattr(pb, 'from', account_code)\n pb.symbol = self._symbol.encode()\n pb.amount = self._amount\n return pb\n\n\nclass SignatureMsg(Msg):\n\n AMINO_MESSAGE_TYPE = None\n\n def __init__(self, signature: Signature, wallet: Wallet):\n self._signature = signature\n self._wallet = wallet\n\n def to_protobuf(self, account) -> NewOrder:\n pub_key_msg = PubKeyMsg(self._wallet)\n std_sig = StdSignature()\n std_sig.sequence = account['sequence']\n std_sig.account_number = account['account_number']\n std_sig.pub_key = pub_key_msg.to_amino(account)\n std_sig.signature = self._signature.sign(self._wallet)\n return std_sig\n\n\nclass StdTxMsg(Msg):\n\n AMINO_MESSAGE_TYPE = b\"F0625DEE\"\n INCLUDE_AMINO_LENGTH_PREFIX = True\n\n def __init__(self, msg, signature: SignatureMsg, data='', memo=''):\n self._msg = msg\n self._signature = signature\n self._data = data\n self._memo = memo\n self._source = BROADCAST_SOURCE\n\n def to_protobuf(self, account) -> NewOrder:\n stdtx = StdTx()\n stdtx.msgs.extend([self._msg.to_amino(account)])\n stdtx.signatures.extend([self._signature.to_amino(account)])\n stdtx.data = self._data.encode()\n stdtx.memo = self._memo\n stdtx.source = self._source\n return stdtx\n\n\nclass PubKeyMsg(Msg):\n\n AMINO_MESSAGE_TYPE = b\"EB5AE987\"\n\n def __init__(self, wallet: Wallet):\n self._public_key = wallet.public_key\n\n def to_protobuf(self, account):\n return self._public_key\n\n def to_amino(self, account):\n proto = self.to_protobuf(account)\n\n type_bytes = binascii.unhexlify(self.AMINO_MESSAGE_TYPE)\n\n varint_length = varint_encode(len(proto))\n\n msg = type_bytes + varint_length + proto\n\n return msg\n\n\nclass Client:\n\n TESTNET_API_URL = 'https://testnet-dex.binance.org'\n API_VERSION = 'v1'\n\n def __init__(self, api_url: Optional[str] = None, wallet: Optional[Wallet] = None,\n requests_params: Optional[Dict] = None):\n \"\"\"Binance Chain API Client constructor\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html\n\n :param requests_params: (optional) Dictionary of requests params to use for all calls\n :type requests_params: dict.\n\n .. code:: python\n\n client = Client(api_key, api_secret\n\n \"\"\"\n\n self.API_URL = api_url or self.TESTNET_API_URL\n\n self._wallet = wallet\n self._requests_params = requests_params\n self.session = self._init_session()\n\n def _init_session(self):\n\n session = requests.session()\n headers = {\n 'Accept': 'application/json',\n 'User-Agent': 'python-binance-chain',\n }\n session.headers.update(headers)\n return session\n\n def _create_path(self, path):\n return '/api/{}/{}'.format(self.API_VERSION, path)\n\n def _create_uri(self, path):\n return '{}{}'.format(self.API_URL, path)\n\n def _request(self, method, path, **kwargs):\n\n # set default requests timeout\n kwargs['timeout'] = 10\n\n # add our global requests params\n if self._requests_params:\n kwargs.update(self._requests_params)\n\n kwargs['data'] = kwargs.get('data', {})\n kwargs['headers'] = kwargs.get('headers', {})\n\n full_path = self._create_path(path)\n uri = self._create_uri(full_path)\n\n if kwargs['data'] and method == 'get':\n kwargs['params'] = kwargs['data']\n del(kwargs['data'])\n\n if method == 'post':\n kwargs['headers']['content-type'] = 'text/plain'\n\n response = getattr(self.session, method)(uri, **kwargs)\n return self._handle_response(response)\n\n @staticmethod\n def _handle_response(response):\n \"\"\"Internal helper for handling API responses from the server.\n Raises the appropriate exceptions when necessary; otherwise, returns the\n response.\n \"\"\"\n\n if not str(response.status_code).startswith('2'):\n raise BinanceChainAPIException(response)\n try:\n res = response.json()\n\n if 'code' in res and res['code'] != \"200000\":\n raise BinanceChainAPIException(response)\n\n if 'success' in res and not res['success']:\n raise BinanceChainAPIException(response)\n\n # by default return full response\n # if it's a normal response we have a data attribute, return that\n if 'data' in res:\n res = res['data']\n return res\n except ValueError:\n raise BinanceChainRequestException('Invalid Response: %s' % response.text)\n\n def _get(self, path, **kwargs):\n return self._request('get', path, **kwargs)\n\n def _post(self, path, **kwargs):\n return self._request('post', path, **kwargs)\n\n def _put(self, path, **kwargs):\n return self._request('put', path, **kwargs)\n\n def _delete(self, path, **kwargs):\n return self._request('delete', path, **kwargs)\n\n def get_time(self):\n \"\"\"Get the server timestamp\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1time\n\n .. code:: python\n\n time = client.get_time()\n\n :return: API Response\n\n .. code-block:: python\n\n {\n \"ap_time\": \"2019-02-24T09:23:35Z\",\n \"block_time\": \"2019-02-24T09:23:34Z\"\n }\n\n \"\"\"\n return self._get(\"time\")\n\n def get_node_info(self):\n \"\"\"Get node runtime information\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1node-info\n\n .. code:: python\n\n node_info = client.get_node_info()\n\n :return: API Response\n\n \"\"\"\n return self._get(\"node-info\")\n\n def get_validators(self):\n \"\"\"Gets the list of validators used in consensus\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1validators\n\n .. code:: python\n\n validators = client.get_validators()\n\n :return: API Response\n\n \"\"\"\n return self._get(\"validators\")\n\n def get_peers(self, peer_type: Optional[PeerType] = None):\n \"\"\"Gets the list of network peers\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1peers\n\n .. code:: python\n\n peers = client.get_peers()\n\n :return: API Response\n\n \"\"\"\n peers = self._get(\"peers\")\n if peer_type:\n peers = [p for p in peers if peer_type in p['capabilities']]\n\n return peers\n\n def get_account(self, address: str):\n \"\"\"Gets account metadata for an address\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1accountaddress\n\n .. code:: python\n\n account = client.get_account('tbnb185tqzq3j6y7yep85lncaz9qeectjxqe5054cgn')\n\n :return: API Response\n\n \"\"\"\n return self._get(f\"account/{address}\")\n\n def get_account_sequence(self, address: str):\n \"\"\"Gets an account sequence for an address.\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1accountaddresssequence\n\n .. code:: python\n\n account_seq = client.get_account_sequence('tbnb185tqzq3j6y7yep85lncaz9qeectjxqe5054cgn')\n\n :return: API Response\n\n .. code-block:: python\n\n \"\"\"\n return self._get(f\"account/{address}/sequence\")\n\n def get_transaction(self, transaction_hash: str):\n \"\"\"Gets transaction metadata by transaction ID\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1txhash\n\n .. code:: python\n\n account_seq = client.get_transaction('E81BAB8E555819E4211D62E2E536B6D5812D3D91C105F998F5C6EB3AB8136482')\n\n :return: API Response\n\n \"\"\"\n\n data = {\n 'format': 'json'\n }\n\n return self._get(f\"tx/{transaction_hash}?format=json\", data=data)\n\n def get_tokens(self):\n \"\"\"Gets a list of tokens that have been issued\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1tokens\n\n .. code:: python\n\n tokens = client.get_tokens()\n\n :return: API Response\n\n \"\"\"\n return self._get(\"tokens\")\n\n def get_markets(self):\n \"\"\"Gets the list of market pairs that have been listed\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1markets\n\n .. code:: python\n\n markets = client.get_markets()\n\n :return: API Response\n\n \"\"\"\n return self._get(\"markets\")\n\n def get_fees(self):\n \"\"\"Gets the current trading fees settings\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1fees\n\n .. code:: python\n\n fees = client.get_fees()\n\n :return: API Response\n\n \"\"\"\n return self._get(\"fees\")\n\n def get_order_book(self, symbol: str):\n \"\"\"Gets the order book depth data for a given pair symbol\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1depth\n\n :param symbol: required e.g NNB-0AD_BNB\n\n .. code:: python\n\n order_book = client.get_order_book('NNB-0AD_BNB')\n\n :return: API Response\n\n \"\"\"\n data = {\n 'symbol': symbol\n }\n return self._get(\"depth\", data=data)\n\n def broadcast_msg(self, msg: Msg, sync: bool = False):\n \"\"\"Broadcast a message\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1broadcast\n\n :param msg: Type of NewOrderMsg, CancelOrderMsg, FreezeMsg, UnfreezeMsg\n :param sync: Synchronous broadcast (wait for DeliverTx)?\n\n .. code:: python\n\n # new order example\n # construct the message\n new_order_msg = NewOrderMsg(\n symbol=\"ANN-457_BNB\",\n time_in_force=TimeInForce.GTE,\n order_type=OrderType.LIMIT,\n side=OrderSide.BUY,\n price=Decimal(0.000396000),\n quantity=Decimal(12)\n )\n # then broadcast it\n res = client.broadcast_msg(new_order_msg, wallet)\n\n # cancel order example\n cancel_order_msg = CancelOrderMsg(\n order_id=\"09F8B32D33CBE2B546088620CBEBC1FF80F9BE001ACF42762B0BBFF0A729CE3\",\n symbol='ANN-457_BNB',\n )\n res = client.broadcast_msg(cancel_order_msg, wallet)\n\n :return: API Response\n\n \"\"\"\n\n # fetch account detail\n account = self.get_account(self._wallet.address)\n\n signature = Signature(msg, account)\n signature_msg = SignatureMsg(signature, self._wallet)\n\n std_tx = StdTxMsg(msg, signature_msg)\n logging.debug(f'std_tx_amino:{std_tx.to_amino(account)}')\n\n data = binascii.hexlify(std_tx.to_amino(account))\n logging.debug(f'data:{data}')\n\n req_path = 'broadcast'\n if sync:\n req_path += f'?sync=1'\n\n return self._post(req_path, data=data)\n\n def get_klines(self, symbol: str, interval: KlineInterval, limit: Optional[int] = 300,\n start_time: Optional[int] = None, end_time: Optional[int] = None):\n \"\"\"Gets candlestick/kline bars for a symbol. Bars are uniquely identified by their open time\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1klines\n\n :param symbol: required e.g NNB-0AD_BNB\n :param interval: required e.g 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M\n :param limit:\n :param start_time:\n :param end_time:\n\n .. code:: python\n\n klines = client.get_klines('NNB-0AD_BNB', KlineInterval.ONE_DAY)\n\n :return: API Response\n\n \"\"\"\n data = {\n 'symbol': symbol,\n 'interval': interval\n }\n if limit is not None:\n data['limit'] = limit\n if start_time is not None:\n data['startTime'] = start_time\n if end_time is not None:\n data['endTime'] = end_time\n\n return self._get(\"klines\", data=data)\n\n def get_closed_orders(\n self, address: str, symbol: Optional[str] = None, status: Optional[OrderStatus] = None,\n side: Optional[OrderSide] = None, offset: Optional[int] = 0, limit: Optional[int] = 500,\n start_time: Optional[int] = None, end_time: Optional[int] = None, total: Optional[int] = 0\n ):\n \"\"\"Gets closed (filled and cancelled) orders for a given address\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1ordersclosed\n\n :param address: required\n :param symbol: e.g NNB-0AD_BNB\n :param status: order status type\n :param side: order side. 1 for buy and 2 for sell.\n :param offset: start with 0; default 0.\n :param limit: default 500; max 1000.\n :param start_time:\n :param end_time:\n :param total: total number required, 0 for not required and 1 for required, default not required, return total=-1\n\n .. code:: python\n\n orders = client.get_closed_orders('tbnb185tqzq3j6y7yep85lncaz9qeectjxqe5054cgn')\n\n :return: API Response\n\n \"\"\"\n data = {\n 'address': address\n }\n if symbol is not None:\n data['symbol'] = symbol\n if status is not None:\n data['status'] = status\n if side is not None:\n data['side'] = side\n if offset is not None:\n data['offset'] = offset\n if limit is not None:\n data['limit'] = limit\n if start_time is not None:\n data['start'] = start_time\n if end_time is not None:\n data['end'] = end_time\n if total is not None:\n data['total'] = total\n\n return self._get(\"orders/closed\", data=data)\n\n def get_open_orders(\n self, address: str, symbol: Optional[str] = None, offset: Optional[int] = 0, limit: Optional[int] = 500,\n total: Optional[int] = 0\n ):\n \"\"\"Gets open orders for a given address\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1ordersopen\n\n :param address: required\n :param symbol: e.g NNB-0AD_BNB\n :param offset: start with 0; default 0.\n :param limit: default 500; max 1000.\n :param total: total number required, 0 for not required and 1 for required, default not required, return total=-1\n\n .. code:: python\n\n orders = client.get_open_orders('tbnb185tqzq3j6y7yep85lncaz9qeectjxqe5054cgn')\n\n :return: API Response\n\n \"\"\"\n data = {\n 'address': address\n }\n if symbol is not None:\n data['symbol'] = symbol\n if offset is not None:\n data['offset'] = offset\n if limit is not None:\n data['limit'] = limit\n if total is not None:\n data['total'] = total\n\n return self._get(\"orders/open\", data=data)\n\n def get_order(self, order_id: str):\n \"\"\"Gets metadata for an individual order by its ID\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1ordersid\n\n :param order_id: required\n\n .. code:: python\n\n orders = client.get_order('')\n\n :return: API Response\n\n \"\"\"\n\n return self._get(f\"orders/{order_id}\")\n\n def get_ticker(self, symbol: str):\n \"\"\"Gets 24 hour price change statistics for a market pair symbol\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1ticker24hr\n\n :param symbol: required\n\n .. code:: python\n\n ticker = client.get_ticker('NNB-0AD_BNB')\n\n :return: API Response\n\n \"\"\"\n data = {\n 'symbol': symbol\n }\n\n return self._get(\"ticker/24hr\", data=data)\n\n def get_trades(\n self, address: Optional[str] = None, symbol: Optional[str] = None,\n side: Optional[OrderSide] = None, quote_asset: Optional[str] = None, buyer_order_id: Optional[str] = None,\n seller_order_id: Optional[str] = None, height: Optional[str] = None, offset: Optional[int] = 0,\n limit: Optional[int] = 500, start_time: Optional[int] = None, end_time: Optional[int] = None,\n total: Optional[int] = 0\n ):\n \"\"\"Gets a list of historical trades\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1trades\n\n :param address:\n :param symbol:\n :param side:\n :param quote_asset:\n :param buyer_order_id:\n :param seller_order_id:\n :param height:\n :param offset:\n :param limit:\n :param start_time:\n :param end_time:\n :param total:\n\n .. code:: python\n\n trades = client.get_trades('')\n\n :return: API Response\n\n \"\"\"\n data = {}\n if address is not None:\n data['address'] = address\n if symbol is not None:\n data['symbol'] = symbol\n if side is not None:\n data['side'] = side\n if quote_asset is not None:\n data['quoteAsset'] = quote_asset\n if buyer_order_id is not None:\n data['buyerOrderId'] = buyer_order_id\n if seller_order_id is not None:\n data['sellerOrderId'] = seller_order_id\n if height is not None:\n data['height'] = height\n if offset is not None:\n data['offset'] = offset\n if limit is not None:\n data['limit'] = limit\n if start_time is not None:\n data['start'] = start_time\n if end_time is not None:\n data['end'] = end_time\n if total is not None:\n data['total'] = total\n\n return self._get(\"trades\", data=data)\n\n def get_transactions(\n self, address: str, symbol: Optional[str] = None,\n side: Optional[TransactionSide] = None, tx_asset: Optional[str] = None,\n tx_type: Optional[TransactionType] = None, height: Optional[str] = None, offset: Optional[int] = 0,\n limit: Optional[int] = 500, start_time: Optional[int] = None, end_time: Optional[int] = None\n ):\n \"\"\"Gets a list of transactions\n\n https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1transactions\n\n :param address:\n :param symbol:\n :param side:\n :param tx_asset:\n :param tx_type:\n :param height:\n :param offset:\n :param limit:\n :param start_time:\n :param end_time:\n\n .. code:: python\n\n transactions = client.get_transactions('')\n\n :return: API Response\n\n \"\"\"\n data = {\n 'address': address\n }\n if symbol is not None:\n data['symbol'] = symbol\n if side is not None:\n data['side'] = side\n if tx_asset is not None:\n data['txAsset'] = tx_asset\n if tx_type is not None:\n data['txType'] = tx_type\n if height is not None:\n data['blockHeight'] = height\n if offset is not None:\n data['offset'] = offset\n if limit is not None:\n data['limit'] = limit\n if start_time is not None:\n data['start'] = start_time\n if end_time is not None:\n data['end'] = end_time\n\n return self._get(\"transactions\", data=data)\n","sub_path":"binance_chain/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":29555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"393818416","text":"\n# pacman imports\nfrom pacman.model.constraints.abstract_constraints\\\n .abstract_key_allocator_constraint import AbstractKeyAllocatorConstraint\nfrom pacman.model.constraints.key_allocator_constraints\\\n .key_allocator_fixed_mask_constraint import KeyAllocatorFixedMaskConstraint\nfrom pacman.model.routing_tables.multicast_routing_tables import \\\n MulticastRoutingTables\nfrom pacman.operations.routing_info_allocator_algorithms\\\n .malloc_based_routing_allocator.key_field_generator \\\n import KeyFieldGenerator\nfrom pacman.model.constraints.key_allocator_constraints\\\n .key_allocator_fixed_key_and_mask_constraint \\\n import KeyAllocatorFixedKeyAndMaskConstraint\nfrom pacman.model.constraints.key_allocator_constraints\\\n .key_allocator_contiguous_range_constraint \\\n import KeyAllocatorContiguousRangeContraint\nfrom pacman.model.routing_info.routing_info import RoutingInfo\nfrom pacman.model.routing_info.base_key_and_mask import BaseKeyAndMask\nfrom pacman.model.routing_info.subedge_routing_info import SubedgeRoutingInfo\nfrom pacman.utilities import utility_calls\nfrom pacman.exceptions import PacmanRouteInfoAllocationException\nfrom pacman.utilities.algorithm_utilities.element_allocator_algorithm import \\\n ElementAllocatorAlgorithm\nfrom pacman.utilities.utility_objs.progress_bar import ProgressBar\nfrom pacman.utilities.algorithm_utilities import \\\n routing_info_allocator_utilities\n\n# general imports\nimport math\nimport numpy\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass MallocBasedRoutingInfoAllocator(ElementAllocatorAlgorithm):\n \"\"\" A Routing Info Allocation Allocator algorithm that keeps track of\n free keys and attempts to allocate them as requested\n \"\"\"\n\n def __init__(self):\n ElementAllocatorAlgorithm.__init__(self, 0, math.pow(2, 32))\n\n def __call__(self, subgraph, n_keys_map, routing_paths):\n\n # check that this algorithm supports the constraints\n utility_calls.check_algorithm_can_support_constraints(\n constrained_vertices=subgraph.subedges,\n supported_constraints=[\n KeyAllocatorFixedMaskConstraint,\n KeyAllocatorFixedKeyAndMaskConstraint,\n KeyAllocatorContiguousRangeContraint],\n abstract_constraint_type=AbstractKeyAllocatorConstraint)\n\n routing_tables = MulticastRoutingTables()\n\n # Get the partitioned edges grouped by those that require the same key\n same_key_groups = \\\n routing_info_allocator_utilities.get_edge_groups(subgraph)\n\n # Go through the groups and allocate keys\n progress_bar = ProgressBar(len(same_key_groups),\n \"Allocating routing keys\")\n routing_infos = RoutingInfo()\n for group in same_key_groups:\n # Check how many keys are needed for the edges of the group\n edge_n_keys = None\n for edge in group:\n n_keys = n_keys_map.n_keys_for_partitioned_edge(edge)\n if edge_n_keys is None:\n edge_n_keys = n_keys\n elif edge_n_keys != n_keys:\n raise PacmanRouteInfoAllocationException(\n \"Two edges require the same keys but request a\"\n \" different number of keys\")\n\n # Get any fixed keys and masks from the group and attempt to\n # allocate them\n keys_and_masks = routing_info_allocator_utilities.\\\n get_fixed_key_and_mask(group)\n fixed_mask, fields = \\\n routing_info_allocator_utilities.get_fixed_mask(group)\n\n if keys_and_masks is not None:\n\n self._allocate_fixed_keys_and_masks(keys_and_masks, fixed_mask)\n else:\n keys_and_masks = self._allocate_keys_and_masks(\n fixed_mask, fields, edge_n_keys)\n\n # Allocate the routing information\n for edge in group:\n subedge_info = SubedgeRoutingInfo(keys_and_masks, edge)\n routing_infos.add_subedge_info(subedge_info)\n\n # update routing tables with entries\n routing_info_allocator_utilities.add_routing_key_entries(\n routing_paths, subedge_info, edge, routing_tables)\n\n progress_bar.update()\n progress_bar.end()\n return {'routing_infos': routing_infos,\n 'routing_tables': routing_tables}\n\n @staticmethod\n def _get_key_ranges(key, mask):\n \"\"\" Get a generator of base_key, n_keys pairs that represent ranges\n allowed by the mask\n\n :param key: The base key\n :param mask: The mask\n \"\"\"\n unwrapped_mask = utility_calls.expand_to_bit_array(mask)\n first_zeros = list()\n remaining_zeros = list()\n pos = len(unwrapped_mask) - 1\n\n # Keep the indices of the first set of zeros\n while pos >= 0 and unwrapped_mask[pos] == 0:\n first_zeros.append(pos)\n pos -= 1\n\n # Find all the remaining zeros\n while pos >= 0:\n if unwrapped_mask[pos] == 0:\n remaining_zeros.append(pos)\n pos -= 1\n\n # Loop over 2^len(remaining_zeros) to produce the base key,\n # with n_keys being 2^len(first_zeros)\n n_sets = 2 ** len(remaining_zeros)\n n_keys = 2 ** len(first_zeros)\n unwrapped_key = utility_calls.expand_to_bit_array(key)\n for value in xrange(n_sets):\n generated_key = numpy.copy(unwrapped_key)\n unwrapped_value = utility_calls.expand_to_bit_array(value)[\n -len(remaining_zeros):]\n generated_key[remaining_zeros] = unwrapped_value\n yield utility_calls.compress_from_bit_array(generated_key), n_keys\n\n @staticmethod\n def _get_possible_masks(n_keys):\n \"\"\" Get the possible masks given the number of keys\n\n :param n_keys: The number of keys to generate a mask for\n \"\"\"\n\n # TODO: Generate all the masks - currently only the obvious\n # mask with the zeros at the bottom is generated but the zeros\n # could actually be anywhere\n n_zeros = int(math.ceil(math.log(n_keys, 2)))\n n_ones = 32 - n_zeros\n return [(((1 << n_ones) - 1) << n_zeros)]\n\n def _allocate_fixed_keys_and_masks(self, keys_and_masks, fixed_mask):\n\n # If there are fixed keys and masks, allocate them\n for key_and_mask in keys_and_masks:\n\n # If there is a fixed mask, check it doesn't clash\n if fixed_mask is not None and fixed_mask != key_and_mask.mask:\n raise PacmanRouteInfoAllocationException(\n \"Cannot meet conflicting constraints\")\n\n # Go through the mask sets and allocate\n for key, n_keys in self._get_key_ranges(\n key_and_mask.key, key_and_mask.mask):\n self._allocate_elements(key, n_keys)\n\n def _allocate_keys_and_masks(self, fixed_mask, fields, edge_n_keys):\n\n # If there isn't a fixed mask, generate a fixed mask based\n # on the number of keys required\n masks_available = [fixed_mask]\n if fixed_mask is None:\n masks_available = self._get_possible_masks(edge_n_keys)\n\n # For each usable mask, try all of the possible keys and\n # see if a match is possible\n mask_found = None\n key_found = None\n mask = None\n for mask in masks_available:\n\n logger.debug(\"Trying mask {} for {} keys\".format(hex(mask),\n edge_n_keys))\n\n key_found = None\n key_generator = KeyFieldGenerator(mask, fields,\n self._free_space_tracker)\n for key in key_generator:\n\n logger.debug(\"Trying key {}\".format(hex(key)))\n\n # Check if all the key ranges can be allocated\n matched_all = True\n index = 0\n for (base_key, n_keys) in self._get_key_ranges(key, mask):\n logger.debug(\"Finding slot for {}, n_keys={}\".format(\n hex(base_key), n_keys))\n index = self._find_slot(base_key, lo=index)\n logger.debug(\"Slot for {} is {}\".format(\n hex(base_key), index))\n if index is None:\n matched_all = False\n break\n space = self._check_allocation(index, base_key,\n n_keys)\n logger.debug(\"Space for {} is {}\".format(\n hex(base_key), space))\n if space is None:\n matched_all = False\n break\n\n if matched_all:\n logger.debug(\"Matched key {}\".format(hex(key)))\n key_found = key\n break\n\n # If we found a matching key, store the mask that worked\n if key_found is not None:\n logger.debug(\"Matched mask {}\".format(hex(mask)))\n mask_found = mask\n break\n\n # If we found a working key and mask that can be assigned,\n # Allocate them\n if key_found is not None and mask_found is not None:\n for (base_key, n_keys) in self._get_key_ranges(\n key_found, mask):\n self._allocate_elements(base_key, n_keys)\n\n # If we get here, we can assign the keys to the edges\n keys_and_masks = list([BaseKeyAndMask(base_key=key_found,\n mask=mask)])\n return keys_and_masks\n\n raise PacmanRouteInfoAllocationException(\n \"Could not find space to allocate keys\")\n","sub_path":"pacman/operations/routing_info_allocator_algorithms/malloc_based_routing_allocator/malloc_based_routing_info_allocator.py","file_name":"malloc_based_routing_info_allocator.py","file_ext":"py","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"490813534","text":"import numpy as np\r\nfrom NRCS import constants as const\r\nfrom NRCS.spec import kudryavtsev05\r\nfrom NRCS.spec.kudryavtsev05 import param\r\nfrom NRCS.spec.kudryavtsev05 import spec_peak\r\nfrom NRCS.modulation.Bragg_modulation import Trans_func\r\n\r\ndef const_wbmo(kr, K, theta, azimuth, u_10, fetch, wind_dir, div, polarization):\r\n \"\"\"\r\n :param kp:\r\n :param kr:\r\n :param theta:\r\n :param azi:\r\n :param u_10:\r\n :param fetch:\r\n :return:\r\n \"\"\"\r\n if polarization == 'VH':\r\n print('no modulation cross-pol')\r\n return\r\n\r\n nphi = theta.shape[0]\r\n\r\n ind = np.where(np.degrees(azimuth) == wind_dir)[0]\r\n\r\n # NRCS of plumes\r\n wb0 = np.exp(-np.tan(theta)**2/const.Swb)/(np.cos(theta)**4*const.Swb)+const.yitawb/const.Swb # Kudryavstev 2003a equation (60)\r\n knb = min(const.br*kr, const.kwb)\r\n\r\n # tilting transfer function\r\n dtheta = theta[1]-theta[0]\r\n Mwb = np.gradient(wb0, dtheta)/wb0\r\n\r\n # distribution function\r\n # in radians azimuth of breaking surface area: -pi/2,pi/2\r\n # phi1 = np.linspace(-np.pi/2, np.pi/2, nphi)\r\n phi1 = np.linspace(-np.pi, np.pi, nphi)\r\n nk = 1024\r\n\r\n q = np.zeros([div.shape[0],div.shape[1]])\r\n WB = np.zeros([div.shape[0],div.shape[1]])\r\n\r\n KK = np.linspace(10 * spec_peak(u_10, fetch), knb, nk)\r\n n, alpha = param(KK, u_10, fetch)\r\n\r\n for ii in np.arange(div.shape[0]):\r\n for jj in np.arange(div.shape[1]):\r\n T = Trans_func(KK, K[ii, jj], u_10, fetch, azimuth, div[ii, jj])\r\n Bkdir = kudryavtsev05(KK.reshape(nk, 1), u_10, fetch, phi1)* (1+abs(T.reshape(nk,1)))\r\n lamda = (Bkdir/alpha.reshape(nk, 1))**(n.reshape(nk, 1)+1)/(2*KK.reshape(nk, 1)) # distribution of breaking front lengths\r\n lamda_k = np.trapz(lamda, phi1, axis=1)\r\n lamda = np.trapz(lamda, KK, axis=0)\r\n lamda_k = np.trapz(lamda_k, KK)\r\n q[ii, jj] = const.cq * lamda_k\r\n Awb = np.trapz(np.cos(phi1 - azimuth[ind]) * lamda, phi1) / lamda_k\r\n WB[ii, jj] = wb0[jj]*(1+Mwb[jj]*const.theta_wb*Awb)\r\n return WB, q","sub_path":"NRCS/modulation/const_wbmo.py","file_name":"const_wbmo.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"650364910","text":"\"\"\"Example on using Redis for caching\"\"\"\n\nfrom flask import Flask, jsonify\nimport sqlite3\n\nconn = sqlite3.connect('black_ips.db')\napp = Flask(__name__)\n\n\ndef is_black_ip(ip):\n \"\"\"Check in database if IP is black\"\"\"\n cur = conn.cursor()\n cur.execute('SELECT COUNT(ip) FROM black_ips WHERE ip = ?', (ip,))\n\n row = cur.fetchone()\n return row[0] > 0\n\n\n@app.route('/check_ip/')\ndef check_ip(ip):\n \"\"\"ip for host API endpoint\"\"\"\n \n is_black = is_black_ip(ip)\n return jsonify(ip=ip, is_black=is_black)\n\n\nif __name__ == '__main__':\n app.run(port=8080)","sub_path":"FasterPythonServices/Ch02/02_01/black_ips.py","file_name":"black_ips.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"375846991","text":"\"\"\"\nSome layers, in particular BatchNormalization layer and the Dropout layer, have different behaviors during\ntraining and inference. For such layers, it is standard practice to expose a training(boolean) argument\nin the call method By exposing this argument in call, you enable the built-in training and evaluation loops\nto correctly use the layer in training and inference\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\n\nclass CustomDropout(keras.layers.Layer):\n def __init__(self, rate, **kwargs):\n super(CustomDropout, self).__init__(**kwargs)\n self.rate = rate\n \n def call(self, inputs, training=None):\n if training:\n return tf.nn.dropout(inputs, rate=self.rate)\n return inputs\n\n","sub_path":"Tesnorflow2_05-12-20/05_custom_layers_models/06_CustomLayers_train_inf_mode.py","file_name":"06_CustomLayers_train_inf_mode.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"272141921","text":"import web3.utils.utils as utils\nimport web3.utils.abi as abi\nfrom web3.solidity.coder import coder\nimport web3.web3.formatters as formatters\nfrom web3.utils.crypto import sha3\n\n\nclass SolidityFunction(object):\n\n def __init__(self, eth, json, address):\n self._eth = eth\n self._inputTypes = [i[\"type\"] for i in json[\"inputs\"]]\n self._outputTypes = [o[\"type\"] for o in json[\"outputs\"]]\n self._constant = json[\"constant\"]\n self._name = abi.transformToFullName(json)\n self._address = address\n\n def extractDefaultBlock(self, args):\n if (len(args) > len(self._inputTypes) and utils.isObject(args[-1])):\n return formatters.inputDefaultBlockNumberFormatter(args.pop())\n\n def toPayload(self, args, **kwargs):\n \"\"\"\n Should be used to create payload from arguments\n \"\"\"\n options = {}\n if len(args) > len(self._inputTypes) and utils.isObject(args[-1]):\n options = args[-1]\n options[\"to\"] = self._address\n options[\"data\"] = \"0x\" + \\\n self.signature() + coder.encodeParams(self._inputTypes, args)\n\n for key in kwargs:\n options[key] = kwargs[key]\n\n return options\n\n def signature(self):\n \"\"\"\n Should be used to get function signature\n \"\"\"\n return sha3(self._name)[:8]\n\n def unpackOutput(self, output):\n if not output:\n return\n\n if len(output) >= 2:\n output = output[2:]\n\n result = coder.decodeParams(self._outputTypes, output)\n\n if len(result) == 1:\n return result[0]\n\n return result\n\n def call(self, *arguments):\n \"\"\"\n Calls a contract function.\n \"\"\"\n args = list(arguments)\n defaultBlock = self.extractDefaultBlock(args)\n payload = self.toPayload(args)\n\n output = self._eth.call(payload, defaultBlock)\n return self.unpackOutput(output)\n\n def sendTransaction(self, *arguments, **kwargs):\n \"\"\"\n Should be used to sendTransaction to solidity function\n \"\"\"\n args = [a for a in arguments if a]\n payload = self.toPayload(args, **kwargs)\n\n return self._eth.sendTransaction(payload)\n\n def estimateGas(self, *arguments):\n \"\"\"\n Should be used to estimateGas of solidity function\n \"\"\"\n args = [a for a in arguments if a]\n payload = self.toPayload(args)\n\n return self._eth.estimateGas(payload)\n\n def getData(self, *arguments):\n \"\"\"\n Return the encoded data of the call\n \"\"\"\n args = [a for a in arguments if a]\n payload = self.toPayload(args)\n\n return payload[\"data\"]\n\n def displayName(self):\n \"\"\"\n Should be used to get function display name\n \"\"\"\n return abi.extractDisplayName(self._name)\n\n def typeName(self):\n \"\"\"\n Should be used to get function type name\n \"\"\"\n return abi.extractTypeName(self._name)\n\n def request(self, *arguments):\n \"\"\"\n Should be called to get rpc requests from solidity function\n \"\"\"\n return {\n \"method\": \"eth_call\" if self._constant else \"eth_sendTransaction\",\n \"params\": [self.toPayload(arguments)],\n \"format\": self.unpackOutput\n }\n\n def execute(self, *arguments, **kwargs):\n transaction = not self._constant\n\n if transaction:\n return self.sendTransaction(*arguments, **kwargs)\n else:\n return self.call(*arguments)\n\n def attachToContract(self, contract):\n execute = self.execute\n \"\"\"\n displayName = self.displayName()\n # still missing arguments here\n print(displayName, self.typeName())\n try:\n getattr(contract, displayName)\n except AttributeError:\n setattr(contract, displayName, execute)\n m = getattr(contract, displayName)\n setattr(m, self.typeName(), execute)\n \"\"\"\n setattr(contract, self.displayName(), execute)\n # setattr(contract, self.typeName(), execute)\n","sub_path":"web3/web3/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"472850003","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2017 SHIELD, UBIWHERE\n# ALL RIGHTS RESERVED.\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#\n# Neither the name of the SHIELD, UBIWHERE nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n#\n# This work has been performed in the framework of the SHIELD project,\n# funded by the European Commission under Grant number 700199 through the\n# Horizon 2020 program. The authors would like to acknowledge the contributions\n# of their colleagues of the SHIELD partner consortium (www.shield-h2020.eu).\n\n\nimport logging\n\nfrom dashboardutils.pipe import PipeConsumer\nfrom tornado.websocket import WebSocketClosedError\n\n\nclass VNSFSocket(PipeConsumer):\n \"\"\"\n Handles the web socket server to notify the Dashboard of new vNSF notification policies acting as a consumer\n for such notifications.\n\n How a web socket server gets up and running is the responsibility of this class. When it does this is up to a\n pipe manager provided upon instantiation. All this class needs to do for the manager is to present itself as an\n events consumer.\n\n This class is to be used as an output sink for a pipe manager which consumes the notifications and feeds them\n through a web socket. Thus it must implement two distinct behaviours: (i) act as a consumer and (ii) feed the\n socket. The first behaviour is already mentioned above and relates to the manager. The second behaviour needs a\n little hack as the web socket handler class has no direct relationship to this consumer class.\n\n When a producer notifies this class of a new policy it must convey it through the socket. The issue here is that\n this class doesn't play a part in instantiating the socket handler class and thus has no access to the socket\n itself. To make this all work together a hack is provided to the socket handler class whereas the socket\n 'controller' class is supplied. This is only done with the purpose of allowing the socket handler class to\n register itself as a socket within the consumer class. This in turn allows the consumer class to convey the\n notification to the other party using the underlying socket.\n \"\"\"\n\n # Clients connected to the socket.\n # the dictionary will store the tenant as the key\n clients = dict()\n\n def __init__(self, pipe):\n \"\"\"\n :param pipe: The pipe manager where this instance is to be identified as an events consumer.\n \"\"\"\n\n super().__init__()\n self.logger = logging.getLogger(__name__)\n # Get the socket up and running.\n self.pipe = pipe\n self.pipe.boot_out_sink(self)\n\n def setup(self):\n \"\"\"\n The method currently is doing nothing since the setup is the server socket responsibility\n \"\"\"\n pass\n\n def bootup(self):\n \"\"\"\n The method currently is doing nothing since the bootup is the server socket responsibility\n \"\"\"\n pass\n\n def register_socket(self, socket, **kwargs):\n \"\"\"\n Register a socket handler instance as the underlying socket for communicating the notification.\n\n :param socket: The socket handler instance where to convey the notifications.\n :param kwargs: A tenant is given as keyword argument to be associated with the client\n \"\"\"\n tenant = kwargs.get('tenant', None)\n self.logger.debug('Registered socket {} for tenant {}'.format(socket, tenant))\n if tenant and tenant in self.clients:\n self.clients[tenant].append(socket)\n elif tenant:\n self.clients[tenant] = [socket]\n else:\n # Discard the client since no tenant was provided\n self.logger.debug('Socket not registered as no tenant was provided')\n return\n\n def unroll_socket(self, socket, **kwargs):\n \"\"\"\n Register a socket handler instance as the underlying socket for communicating the notification.\n\n :param socket: The socket handler instance where to convey the notifications.\n :param kwargs: A tenant is given as keyword argument to ease the search for the client\n \"\"\"\n tenant = kwargs.get('tenant', None)\n self.logger.debug('Unrolled socket {} for tenant {}'.format(socket, tenant))\n if tenant and self.clients.get(tenant):\n self.clients.get(tenant).remove(socket)\n\n def update(self, data, **kwargs):\n \"\"\"\n Called when a new notification is received in the input pipe.\n\n :param data: The notification data provided.\n :param kwargs: A tenant is given as keyword argument so the notification is sent only to the clients connected\n to the same tenant\n \"\"\"\n tenant = kwargs.get('tenant', None)\n if not tenant:\n self.logger.debug('No tenant provided')\n return\n for socket in self.clients.get(tenant, []):\n self.logger.debug('Socket {} | tenant {} | message - {}'.format(socket, tenant, data))\n\n try:\n socket.write_message(data)\n except WebSocketClosedError:\n self.logger.debug('Socket not available %r', socket)\n","sub_path":"backend/dare/dashboarddare/socket_vnsf.py","file_name":"socket_vnsf.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"415844777","text":"from parallelComputingEuclidianDistance import point\n\ndef main():\n\n infile = open('100000Points.txt', 'r')\n\n\n points = []\n for line in infile.readlines():\n coordinates = line.split('\\t')\n points.append(point.Point(float(coordinates[0]), float(coordinates[1])))\n\n\n print(len(points))\n\n\n\nmain()","sub_path":"EuclidianDistance.py","file_name":"EuclidianDistance.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"169032580","text":"\"\"\"\r\nCreated on Fri Jul 19 12:35:11 2019\r\n\r\n@author: Valerie Langat\r\n\"\"\"\r\n### SPRINT CHALLENGE PART ONE ###\r\nimport sqlite3\r\n\r\n#Connecting to the database\r\nconn = sqlite3.connect('demo_data.sqlite')\r\ncurs = conn.cursor()\r\n\r\n#Making sure we dont have duplicate tables\r\ncurs.execute(\"DROP TABLE IF EXISTS demo\")\r\n\r\n#Making our table\r\ncreate_demo_table = \"\"\"\r\n CREATE TABLE demo (\r\n s TEXT PRIMARY KEY,\r\n x INT,\r\n y INT\r\n);\r\n\"\"\"\r\n#Executing\r\ncurs.execute(create_demo_table)\r\n\r\n#Adding data through tuples for reporducibility and commit\r\nrow_tuples = [('g', 3, 9),\r\n ('v', 5, 7),\r\n ('f', 8, 7)]\r\n\r\nfor row in row_tuples:\r\n insert_row = \"INSERT INTO demo VALUES\" + str(row)\r\n curs.execute(insert_row)\r\n \r\nconn.commit()\r\n\r\n#(not working well, no time to debug)\r\n#for i in range(len(sprint_questions)):\r\n# print(sprint_questions[i])\r\n# curs.execute(sprint_queries[i])\r\n# print(curs.fetchall()[i][0])\r\n# print('\\n')\r\n\r\n\r\n\r\n#Answering questions from Part 1\r\nsprint_questions = ['1: Count how many rows you have - should get 3'\r\n '2: How many rows are there where x and y are at least 5?'\r\n '3: How many unique values of y?']\r\n\r\nsprint_queries = [\"SELECT COUNT(*) FROM demo;\",\r\n \"SELECT COUNT(*) FROM demo WHERE x >= 5 AND y >= 5;\",\r\n \"SELECT COUNT(DISTINCT y) FROM demo;\"]\r\n\r\nprint('''Answers\r\n 1: 3\r\n 2: 2\r\n 3: 2 \\n''')\r\n\r\n\r\n\r\n \r\n","sub_path":"demo_data.py","file_name":"demo_data.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"634248039","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.insert(0,\"uygulamam/\")\nfrom veriseti_hazirlama import *\nfrom sklearn.model_selection import train_test_split\n\ndef goruntuleri_don(veri):\n goruntuler = []\n\n for i in veri:\n goruntuler.append(cv2.cvtColor(i, cv2.COLOR_BGR2GRAY))\n\n return goruntuler\n \ndef verileri_arraye_cevir():\n X_train=[]\n for i in range(1,523):#1,523\n img=cv2.imread(\"uygulamam/yapilar2/\"+str(i)+\".jpg\",0)\n X_train.append(img)\n X_train=np.array(X_train)\n \n return X_train\n\n#verinin cekilmesi\n\nX_train_ham=verileri_arraye_cevir()\nX_train_ham,X_test=train_test_split(X_train_ham,test_size=0.2)\n\nX_train = []\n#arka arkaya 3 tane verilmesi\nfor i in range(3):\n for j in range(X_train_ham.shape[0]):\n X_train.append(X_train_ham[j])\nX_train=np.array(X_train)\n\n#gurultu uygulanmasi\nX_train_noisy,yntmler=yontemleri_uygula_coklu2(X_train)\nX_train_noisy_ham=np.array(X_train_noisy)\n\nX_test_noisy,yntmler=yontemleri_uygula_coklu2(X_test)\nX_test_noisy_ham=np.array(X_test_noisy)\n\n\nnp.save(\"uygulamam/yapilar2/X_train\",X_train)\nnp.save(\"uygulamam/yapilar2/X_test\",X_test)\nnp.save(\"uygulamam/yapilar2/X_train_noisy\",X_train_noisy)\nnp.save(\"uygulamam/yapilar2/X_test_noisy\",X_test_noisy)\n","sub_path":"dataset_preparation.py","file_name":"dataset_preparation.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"340814951","text":"from setuptools import setup\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\n\nsetup(\n name='htmd',\n version='1.5.0',\n packages=['htmd'],\n include_package_data=True,\n install_requires=requirements,\n entry_points='''\n [console_scripts]\n htmd=htmd.cli:cli\n ''',\n zip_safe=False, # Required to have template files as files (not strings)\n)\n","sub_path":"pypi_install_script/htmd-1.5.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"527392984","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# =============================================================================\n# Question 2\n# =============================================================================\n\n# =============================================================================\n# Generating training data\n# =============================================================================\nsigma = 0.07\neps = np.random.normal(0, sigma, 30)\nxpoints = np.array(sorted(np.random.uniform(0,1,30)))\nypoints = np.sin(2*np.pi*xpoints)**2+eps\n\n# =============================================================================\n# Helper Functions\n# =============================================================================\n\ndef phiMatrix(points, degree):\n \"\"\" \n Function to produce a k dimensional polynomial basis for the data points\n \n Keyword Arguments:\n points -- the x coordinates of the training data\n degree -- the chosen dimension of the basis\n \n Returns:\n phi -- the phi matrix in the polynomial basis\n \"\"\"\n \n phi = np.zeros((np.size(points), degree))\n for i in range(np.size(points)):\n for j in range(degree):\n phi[i][j] = np.power((points[i]),j)\n\n return phi\n\ndef phiMatrixSin(points, degree):\n \"\"\" \n Function to produce a k dimensional sinusoidal basis for the data points\n \n Keyword Arguments:\n points -- the x coordinates of the training data\n degree -- the chosen dimension of the basis\n \n Returns:\n phi -- the phi matrix in the sin basis\n \"\"\"\n phi = np.zeros((np.size(points), degree))\n for i in range(np.size(points)):\n for j in range(degree):\n phi[i][j] = np.sin((j+1)*np.pi*points[i])\n return phi\n\ndef ls_estimate(phi, ypoints):\n \"\"\"\n Function to provide the least-squares estimate of the coefficients\n \n Keyword Arguments:\n phi -- the matrix of basis functions\n ypoints -- the y coordinates of the training data\n \n Returns:\n w -- the least squares estimate of the regression coefficients\n \"\"\"\n \n XTX = np.dot(phi.T, phi)\n XTY = np.dot(phi.T, ypoints.reshape((np.size(ypoints),1)))\n w = np.flip(np.linalg.solve(XTX, XTY))\n w1 = np.flip((np.linalg.lstsq(phi, ypoints))[0])\n\n # Which method????\n return w1\n\ndef fitPolynomials(k, xpoints, ypoints):\n \"\"\"\n Function to fit the polynomial curves using a polynomial basis (phiMatrix)\n and least squares (ls_estimate).\n \n Keyword Arguments:\n k -- degree of polynomial\n xpoints -- training x data\n ypoints -- training y data\n \n Returns:\n wCoef -- a list of the the coefficients of the fitted polynomial curves \n up to degree k\n \"\"\"\n \n wCoef = []\n phi = phiMatrix(xpoints, k)\n for i in range(1,k+1):\n phiK = phi[:,:i]\n wK = ls_estimate(phiK, ypoints)\n wCoef.append(wK)\n return wCoef\n\ndef fitSinBasis(k, xpoints, ypoints):\n \"\"\"\n Same as fitPolynomials, except for the sin basis\n \"\"\"\n \n wCoef = []\n phi = phiMatrixSin(xpoints, k)\n for i in range(1,k+1):\n phiK = phi[:,:i]\n wK = ls_estimate(phiK, ypoints)\n wCoef.append(wK)\n return wCoef\n \n\n\ndef plotPolynomialFits(xpoints, ypoints):\n \"\"\"\n Function to plot the fitted polynomials for k= 2,5,10,14,18\n \"\"\"\n x_range = np.linspace(0,1,100)\n plt.plot(xpoints, ypoints, 'o')\n plt.xlim(0,1)\n plt.ylim(-0.2,1.8)\n for k in [2,5,10,14,18]:\n phi = phiMatrix(xpoints, k)\n w = ls_estimate(phi, ypoints)\n y_predicted = np.polyval(w, x_range)\n plt.plot(x_range, y_predicted, label='k={}'.format(k))\n \n plt.legend(loc='upper right')\n plt.show()\n \ndef plotSinFits(xpoints, ypoints):\n \"\"\"\n Function to plot the fitted polynomials for k= 2,5,10,14,18\n \"\"\"\n x_range = np.linspace(0,1,100)\n plt.plot(xpoints, ypoints, 'o')\n plt.xlim(0,1)\n plt.ylim(-0.2,1.8)\n for k in [2,5,10,14,18]:\n phi = phiMatrixSin(xpoints, k)\n w = ls_estimate(phi, ypoints)\n y_predicted = sinEval(w, x_range)\n plt.plot(x_range, y_predicted, label='k={}'.format(k))\n \n plt.legend(loc='upper right')\n plt.show()\n \n \ndef calculateMeanSquareError(wCoef, xpoints, ypoints , indicator=1):\n \"\"\"\n Function to calculate the MSE of all the fitted polynomials.\n \n Keyword Arguments:\n wCoef -- a list of the coefficients for the fitted polynomial curves\n xpoints, ypoints -- training data\n \n Returns:\n meanSquareError -- an array of the MSE for all the polynomial fits\n \"\"\"\n k = np.size(wCoef)\n meanSquareError = np.zeros(k)\n N = np.size(xpoints)\n if(indicator):\n for i in range(k):\n meanSquareError[i] = (np.sum((np.polyval(wCoef[i],xpoints) - ypoints)**2)/(N))\n else:\n for i in range(k):\n meanSquareError[i] = (np.sum((sinEval(wCoef[i],xpoints) - ypoints)**2)/(N))\n \n return meanSquareError\n\ndef generateDataSet(size):\n \"\"\"\n Function to generate the required data set \n -- gσ(x) := sin^2(2πx) + eps\n \n Keyword Arguments:\n size -- number of points in data set requested\n \"\"\"\n sigma = 0.07\n eps = np.random.normal(0, sigma, size)\n xpoints = np.array(np.random.uniform(0,1,size))\n ypoints = (np.sin(2*np.pi*xpoints))**2+eps\n return xpoints, ypoints\n\n\ndef calculateTestError(wMatrix, numberOfTests, indicator=1):\n \"\"\"\n Function to calculate the test error for Question 2 (c)\n \n Keyword Arguments:\n wMatrix -- the matrix of least squares estimates of the coefficients\n numberOfTests -- number of test points requested\n \n Returns\n nothing -- prints the Log of the Test Error against the Dimension of the Basis used.\n \"\"\"\n \n testX, testY = generateDataSet(numberOfTests)\n testError = np.log(calculateMeanSquareError(wMatrix, testX, testY, indicator))\n kInts = [i+1 for i in range(18)]\n plt.xlabel('Basis Dimension')\n plt.ylabel('Log of Test Error')\n plt.plot(kInts, testError)\n plt.show()\n\n# =============================================================================\n# Specific function to calculate the average training and test errors for 2d.)\n# =============================================================================\ndef averageTrainingAndTestError(numberOfRuns, indicator=1):\n \"\"\"\n Function to calculate the average training and test error over a certain numberOfRuns.\n Generates 30 training points and a 1000 test points, and for each run, estimates\n the polynomial coefficients and computes the training and test MSE\n \n Keyword Arguments:\n numberOfRuns --\n \n Returns:\n Average training and test error over numberOfRuns.\n \"\"\"\n trainingError = np.zeros(18)\n testError = np.zeros(18)\n xTraining, yTraining = generateDataSet(30)\n xTest, yTest = generateDataSet(1000)\n \n if(indicator):\n for i in range(numberOfRuns):\n w = fitPolynomials(18, xTraining, yTraining)\n trainingError = trainingError + calculateMeanSquareError(w, xTraining, yTraining)\n testError = testError + calculateMeanSquareError(w, xTest, yTest)\n \n else:\n for i in range(numberOfRuns):\n w = fitSinBasis(18, xTraining, yTraining)\n trainingError = trainingError + calculateMeanSquareError(w, xTraining, yTraining, 0)\n testError = testError + calculateMeanSquareError(w, xTest, yTest, 0)\n \n \n \n trainingError = np.log(trainingError/numberOfRuns)\n testError = np.log(testError/numberOfRuns)\n return trainingError, testError\n\n# =============================================================================\n# Produces plots for Question 2 (i) and (ii)\n# =============================================================================\nx_range = np.linspace(0,1,100)\nplt.plot(xpoints, ypoints,'o')\nplt.plot(x_range, np.sin(2*np.pi*x_range)**2)\nplt.show()\n\nplotPolynomialFits(xpoints, ypoints)\n\n\n# =============================================================================\n# Produces plot for Question 2 (b)\n# =============================================================================\nw = fitPolynomials(18, xpoints, ypoints)\ntrainingError = np.log(calculateMeanSquareError(w, xpoints, ypoints))\nkInts = [i+1 for i in range(18)]\nplt.plot(kInts, trainingError)\nplt.xlabel('Degree of Polynomial')\nplt.ylabel('Log of training error')\nplt.show()\n\n\n# =============================================================================\n# Produces plot for Question 2 (c)\n# =============================================================================\ncalculateTestError(w, 1000)\n\n# =============================================================================\n# Producs plot for Question 2 (d)\n# =============================================================================\ntraining, test = averageTrainingAndTestError(100)\nk = [i+1 for i in range(18)]\nplt.plot(k, training, label='Training Error')\nplt.plot(k, test, label='Test Error')\nplt.xlabel('Degree of Polynomial')\nplt.ylabel('Log of Average MSE')\nplt.legend(loc='upper right')\nplt.show()\n\n# =============================================================================\n# Question 3 - repeating (b) - (d) with sin basis.\n# =============================================================================\ndef sinEval(w, x):\n \"\"\"\n Function to evaluate the predicted values, using the coefficients w and the sin basis.\n \n Keyword Arguments:\n w -- the estimated regression coefficients found using a sin basis\n x -- the training or test points\n \n Returns:\n ypredicted -- the predicted value of y given points x and regression coefficients w.\n \"\"\"\n ypredicted = 0\n w = np.flip(w)\n for i in range(0, np.size(w)):\n ypredicted += w[i]*np.sin((i+1)*np.pi*x)\n return ypredicted\n\nw_2 = fitSinBasis(18, xpoints, ypoints)\ntrainingError_2 = np.log(calculateMeanSquareError(w_2, xpoints, ypoints, 0))\nkInts = [i+1 for i in range(18)]\nplt.plot(kInts, trainingError_2)\nplt.xlabel('Basis Dimension')\nplt.ylabel('Log of training error')\nplt.show()\n\ncalculateTestError(w_2, 1000, 0)\n\nplotSinFits(xpoints, ypoints)\ntraining_2, test_2 = averageTrainingAndTestError(100, 0)\nk = [i+1 for i in range(18)]\nplt.plot(k, training_2, label='Training Error')\nplt.plot(k, test_2, label='Test Error')\nplt.xlabel('Basis Dimension')\nplt.ylabel('Log of Average MSE')\nplt.legend(loc='upper right')\nplt.show()\n","sub_path":"Supervised_Learning/sl_asst_1_code/SLQ2.py","file_name":"SLQ2.py","file_ext":"py","file_size_in_byte":10601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"363601032","text":"import os\n\nfrom aiogram import Bot\nfrom environs import Env\nfrom aiogram.types import Message\nfrom PicImageSearch import AsyncSauceNAO, NetWork\nfrom loguru import logger\n\nasync def saucenao_search(message: Message, api_key: str, photo_path: str):\n \"\"\"Api saucenao search\n\n Args:\n message (aiogram.types.Message): sending a message to a user\n api_key (str): to access the api\n photo_path (str): the path to the photo that is searched for\n \"\"\"\n async with NetWork() as client:\n saucenao = AsyncSauceNAO(client=client, api_key=api_key)\n res = await saucenao.search(photo_path)\n\n try:\n est_time = f\"☁ Est Time: {res.origin['results'][0]['data']['est_time']}\\n\"\n except KeyError:\n est_time = ''\n\n try:\n part = f\"☁ Part: {res.origin['results'][0]['data']['part']}\\n\"\n except KeyError:\n part = ''\n\n res = res.raw[0]\n author = f\"☁ Author: {res.author}\\n\" if res.author else ''\n\n await message.answer(f\"☁ Title: {res.title}\\n\"\n f\"☁ Similarity: {res.similarity}%\\n\"\n f\"{author}\"\n f\"{est_time}\"\n f\"{part}\"\n f\"☁ Url: {res.url}\")\n\n\nasync def search_source(message: Message):\n \"\"\"The function gets the message,\n takes the photo id from it and downloads\n the photo, then searches for the original source\n\n Args:\n message (Message): aiogram.types.Message\n \"\"\"\n # Get token and sauce api from env\n env = Env()\n env.read_env()\n\n token = env.str(\"BOT_TOKEN\")\n api_key = env.str(\"SAUCE_API\")\n\n photo_path = os.path.join('tgbot', 'photos', 'search_photo.jpg')\n\n # Download photo\n bot = Bot(token=token, parse_mode='html')\n file_id = message.photo[-1].file_id\n file = await bot.get_file(file_id)\n file_path = file.file_path\n\n await bot.download_file(file_path, photo_path)\n\n try:\n await saucenao_search(message, api_key, photo_path)\n except Exception as err:\n logger.debug(err)\n","sub_path":"tgbot/modules/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"85147050","text":"from zope.interface import implements\nfrom zope.component import adapts\nfrom Products.Archetypes.atapi import *\nfrom Products.ATContentTypes.content import folder, document\nfrom Products.ATContentTypes.content.schemata import finalizeATCTSchema\nfrom kk.optik.interfaces import IProdukte\nfrom kk.optik.config import PROJECTNAME\nfrom Products.ATContentTypes.configuration import zconf\n\nclass Produkte(folder.ATFolder, document.ATDocument):\n \"\"\" Produkte \"\"\"\n schema =folder.ATFolderSchema.copy() + Schema((\n ImageField(\n 'image',\n widget = ImageWidget(\n label = 'Image',\n label_msgid = 'label_image',\n description_msgid = 'help_image',\n i18n_domain = 'kombinat'),\n sizes = {\n 'mini': (120,120),\n 'small': (140,123),\n 'normal': (350,350),\n 'big': (800,800),\n },\n ),\n ImageField(\n 'logo',\n widget = ImageWidget(\n label = 'Logo',\n label_msgid = 'label_logo',\n description_msgid = 'help_logo',\n i18n_domain = 'kombinat'),\n sizes = {\n 'mini': (74,37),\n 'small': (100,50),\n 'normal': (100,50),\n 'big': (800,800),\n },\n ),\n\t\tStringField(\n\t \t'link',\n\t \t\tsearchable=1,\n\t \t\twidget = StringWidget(\n\t\t\tlabel = 'Link',\n\t\t\tlabel_msgid = 'label_link',\n\t\t\tdescription_msgid = 'help_link',\n i18n_domain = 'optikkoenik'),\n\t\t),\n TextField(\n 'maintext',\n searchable = 1,\n\t \tdefault_content_type=('text/html'),\n allowable_content_types = (\n 'text/plain',\n 'text/html'),\n widget = RichWidget(\n label = 'Maintext',\n label_msgid = 'label_maintext',\n description_msgid = 'help_maintext',\n i18n_domain = 'optikkoenig'),\n ),\n ))\n \n implements(IProdukte)\n portal_type=meta_type=\"Produkte\"\n \n\nregisterType(Produkte, PROJECTNAME)","sub_path":"src/kk.optik/kk/optik/content/produkte.py","file_name":"produkte.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"102864622","text":"import pygame as pg\r\nimport pieces\r\nimport shots\r\nimport config\r\nimport Handler\r\nimport random\r\n\r\nDEBUG = False\r\n\r\ninit_start = (5, 10) if DEBUG else (5, 0) # 放置新方塊的位置\r\n\r\n\r\ndef getRandomPiece():\r\n shape = random.choice(list(config.shapes.keys()))\r\n piece = pieces.Piece(*init_start, shape)\r\n return piece\r\n\r\n\r\ndef update(screen, shot, piece, next_piece, font):\r\n screen.fill(config.background_color)\r\n\r\n for y in range(config.rows):\r\n for x in range(config.columns):\r\n if shot.status[y][x] != 2:\r\n shot.status[y][x] = 0\r\n\r\n for y, x in Handler.getCellsAbsolutePosition(piece):\r\n if 0 <= y < config.rows and 0 <= x < config.columns:\r\n shot.color[y][x] = piece.color\r\n shot.status[y][x] = 1\r\n\r\n for y, line in enumerate(shot.color):\r\n for x, color in enumerate(line):\r\n if shot.status[y][x] == 0:\r\n color = (0, 0, 0)\r\n pg.draw.rect(screen, color, (\r\n x * config.grid,\r\n y * config.grid,\r\n config.grid,\r\n config.grid\r\n ))\r\n\r\n # score\r\n textsurface = font.render('Score: {}'.format(\r\n shot.score), False, (255, 255, 255))\r\n screen.blit(textsurface, config.score_pos)\r\n\r\n # line\r\n textsurface = font.render('Line: {}'.format(\r\n shot.line_count), False, (255, 255, 255))\r\n screen.blit(textsurface, config.line_pos)\r\n\r\n # next piece (background)\r\n for y in range(-2, 3):\r\n for x in range(-2, 3):\r\n pg.draw.rect(screen, (50, 50, 50), (\r\n config.next_piece_pos[0] + x * config.grid,\r\n config.next_piece_pos[1] + y * config.grid,\r\n config.grid,\r\n config.grid\r\n ))\r\n\r\n # next piece\r\n for y, x in next_piece.getCells():\r\n color = next_piece.color\r\n pg.draw.rect(screen, color, (\r\n config.next_piece_pos[0] + x * config.grid,\r\n config.next_piece_pos[1] + y * config.grid,\r\n config.grid,\r\n config.grid\r\n ))\r\n\r\n\r\ndef main():\r\n pg.init()\r\n pg.font.init()\r\n myfont = pg.font.SysFont(*config.font)\r\n fpsClock = pg.time.Clock()\r\n screen = pg.display.set_mode((config.width, config.height))\r\n pg.display.set_caption(\"Tetris\")\r\n shot = shots.Shot()\r\n\r\n piece = getRandomPiece()\r\n next_piece = getRandomPiece()\r\n\r\n update(screen, shot, piece, next_piece, myfont)\r\n run = True\r\n counter = 0\r\n key_ticker = {}\r\n while run:\r\n if not DEBUG and counter == config.difficulty:\r\n Handler.drop(shot, piece)\r\n counter -= config.difficulty # 重設計時器\r\n for event in pg.event.get(): # 檢查各種事件\r\n if event.type == pg.QUIT: # 關閉視窗\r\n run = False\r\n elif event.type == pg.KEYDOWN: # 遍歷所有按下鍵盤的事件並觸發動作\r\n if event.key == pg.K_ESCAPE: # 按下 esc\r\n run = False\r\n if event.key == pg.K_UP: # 按下上方向鍵時\r\n Handler.rotate(shot, piece)\r\n if event.key == pg.K_DOWN: # 按下下方向鍵時\r\n key_ticker[pg.K_DOWN] = 13\r\n Handler.drop(shot, piece)\r\n if event.key == pg.K_LEFT: # 按下左方向鍵時\r\n key_ticker[pg.K_LEFT] = 13\r\n Handler.moveLeft(shot, piece)\r\n if event.key == pg.K_RIGHT: # 按下右方向鍵時\r\n key_ticker[pg.K_RIGHT] = 13\r\n Handler.moveRight(shot, piece)\r\n if event.key == pg.K_SPACE: # 按下空白鍵時\r\n Handler.instantDrop(shot, piece)\r\n keys = pg.key.get_pressed()\r\n if keys[pg.K_LEFT] and key_ticker[pg.K_LEFT] == 0: # 持續按著左方向鍵時\r\n key_ticker[pg.K_LEFT] = 6\r\n Handler.moveLeft(shot, piece)\r\n if keys[pg.K_RIGHT] and key_ticker[pg.K_RIGHT] == 0: # 持續按著右方向鍵時\r\n key_ticker[pg.K_RIGHT] = 6\r\n Handler.moveRight(shot, piece)\r\n if keys[pg.K_DOWN] and key_ticker[pg.K_DOWN] == 0: # 持續按著下方向鍵時\r\n key_ticker[pg.K_DOWN] = 6\r\n Handler.drop(shot, piece)\r\n for k in key_ticker.keys():\r\n if key_ticker[k] > 0:\r\n key_ticker[k] -= 1\r\n if piece.is_fixed: # 正把方塊固定時觸發的動作\r\n Handler.eliminateFilledRows(shot, piece)\r\n piece, next_piece = next_piece, getRandomPiece()\r\n if not Handler.isDefeat(shot, piece):\r\n update(screen, shot, piece, next_piece, myfont)\r\n else:\r\n run = False\r\n pg.display.update()\r\n fpsClock.tick(config.fps)\r\n counter += 1\r\n print(\"Game Over!!\")\r\n print(\"Score:\", shot.score)\r\n print(\"Eliminated line:\", shot.line_count)\r\n pg.quit()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"347827108","text":"# 1st party packages\nfrom collections import defaultdict\nfrom datetime import date\n\n# 3rd party packages\nfrom flask import Flask, render_template, request\n\n# Self Written Modules\nfrom models import F1_Database, Image_Handler, Search, Sort\n\napp = Flask(__name__)\ndata = F1_Database()\nsearch = Search()\n\n@app.route('/')\ndef home():\n # homepage controller\n \n today = date.today()\n current_month = str(today).split(\"-\")[1]\n month_name = today.strftime('%B')\n current_year = str(today).split(\"-\")[0]\n\n # get homepage data\n current_month_drivers = data.get_drivers_from_month(current_month)\n popular_drivers = data.get_random_drivers()\n driver_standings = data.get_driver_standings_from_year(current_year)\n popularCircuits = data.get_random_circuits()\n constructor_standings = data.get_constructor_standings_from_year(current_year)\n recent_races = data.get_races('year',int(current_year))\n\n return render_template(\n 'home.html', recentRaces=recent_races[:5], monthDrivers=current_month_drivers,\n driverSeasonStandings=driver_standings[:5],\n constructorSeasonStandings=constructor_standings[:5],\n year=current_year, monthName=month_name, popularCircuits=popularCircuits,\n popularDrivers=popular_drivers\n )\n\n\n@app.route('/about')\ndef about():\n # about page controller\n return render_template('about.html')\n\n\n@app.route('/models_drivers')\ndef driver_model():\n # driver model page controller\n\n # get request args\n query = request.args.get('search', '', type=str).rstrip()\n filtered = request.args.get('filtered', '', type=str)\n sort = request.args.get('sort', '', type=str)\n\n # filter drivers\n driver_list = search.get_driver_list(filtered, query)\n driver_list = Sort.sort_models(driver_list, sort, filtered)\n\n # get driver card information\n drivers = []\n for driver in driver_list:\n\n if 'driverId' in driver.keys():\n\n drivers.append({\n 'driverId': driver['driverId'], 'driverRef': driver['driverRef'],\n 'surname': driver['surname'], 'forename': driver['forename'],\n 'nationality': driver['nationality']\n })\n\n if 'constructor' not in driver:\n\n con = list(data.db.results.find({'driverId': driver['driverId']}))\n\n all_constructors = []\n for c in con:\n\n constructor_id = c['constructorId']\n constructor_name = data.db.constructors.find_one({'constructorId': c['constructorId']})['name']\n constructor = {'id': constructor_id, 'name': constructor_name}\n\n if constructor not in all_constructors:\n all_constructors.append(constructor)\n\n all_constructors.reverse() # newest to oldest\n # print(all_constructors)\n\n data.db.drivers.update_one(\n {'_id': driver['_id']},\n {'$set': {'constructor': all_constructors[0]}})\n data.db.drivers.update_one(\n {'_id': driver['_id']},\n {'$set': {'all_constructors': all_constructors}})\n\n else:\n # print('found constructor for driver: '+str(driver['driverId']))\n drivers[-1].update({'constructor': driver['constructor']})\n\n drivers[-1].update({'link': 'drivers?id='+str(driver['driverId'])})\n\n # Get image\n driver_ref = driver['driverRef']\n img_path = Image_Handler.build_image_path(driver_ref, 'drivers')\n drivers[-1].update({'imgpath': img_path})\n\n page = request.args.get('page', 1, type=int)\n page = page - 1\n\n PER_PAGE = 18\n pages = int(len(drivers)/PER_PAGE)\n drivers = drivers[page*PER_PAGE: page*PER_PAGE+PER_PAGE]\n\n return render_template(\n 'drivers-model.html', drivers=drivers, pages=pages, page=page, query=query,\n filtered=filtered, sort=sort\n )\n\n\n@app.route('/models_constructors')\ndef constructor_model():\n # constructor model page controller\n\n # get request args\n query = request.args.get('search', '', type=str).rstrip()\n filtered = request.args.get('filtered', '', type=str)\n sort = request.args.get('sort', '', type=str)\n\n # filter constructors\n constructor_list = [] \n constructor_list = search.get_constructor_list(filtered, query)\n constructor_list = Sort.sort_models(constructor_list, sort, filtered)\n\n # get constructor card information\n constructors = []\n for constructor in constructor_list:\n\n if 'constructorId' in constructor.keys():\n\n constructors.append({\n 'constructorId': constructor['constructorId'],\n 'constructorRef': constructor['constructorRef'],\n 'name': constructor['name'], 'nationality': constructor['nationality']\n })\n\n if 'topDriverName' in constructor.keys():\n constructors[-1].update({'top_driver': constructor['topDriverName']})\n else:\n constructors[-1].update({'top_driver': 'N/A'})\n constructors[-1].update({'link': 'constructors?id='+str(constructor['constructorId'])})\n\n # Get image\n constructor_ref = constructor['constructorRef']\n img_path = Image_Handler.build_image_path(constructor_ref , 'constructors')\n constructors[-1].update({'imgpath': img_path})\n\n page = request.args.get('page', 1, type=int)\n page = page - 1\n \n PER_PAGE = 18\n pages = int(len(constructors)/PER_PAGE)\n constructors = constructors[page*PER_PAGE: page*PER_PAGE+PER_PAGE]\n\n return render_template(\n 'constructors-model.html', constructors=constructors, pages=pages, page=page, \n query=query, filtered=filtered, sort=sort\n )\n\n\n@app.route('/models_circuits')\ndef circuit_model():\n # circuit model page controller\n\n # get circuits from search, filtering, and sorting\n query = request.args.get('search', '', type=str).rstrip()\n filtered = request.args.get('filtered', '', type=str)\n sort = request.args.get('sort', '', type=str)\n\n circuit_list = search.get_circuit_list(filtered, query)\n circuit_list = Sort.sort_models(circuit_list, sort, filtered)\n\n # get circuit card information\n circuits = []\n for circuit in circuit_list:\n if 'circuitId' in circuit.keys():\n\n circuits.append({\n 'circuitId': circuit['circuitId'], 'circuitRef': circuit['circuitRef'],\n 'name': circuit['name'], 'location': circuit['location'],\n 'country': circuit['country']\n })\n\n if 'most_recent_race' not in circuit.keys():\n\n mrr = data.db.races.find({'circuitId': circuit['circuitId']}).sort([('date', -1)])\n mrr = list(mrr)\n if len(mrr) > 0:\n mrr = mrr[0]\n # print(mrr['name']+' '+mrr['date'])\n\n data.db.circuits.update_one(\n {'_id': circuit['_id']},\n {'$set': {'most_recent_race': mrr['name']+' '+mrr['date']}})\n else:\n data.db.circuits.update_one(\n {'_id': circuit['_id']},\n {'$set': {'most_recent_race': 'N/A'}})\n\n else:\n # print('found most recent race for circuit: ' + str(circuit['circuitId']))\n circuits[-1].update({'most_recent_race': circuit['most_recent_race']})\n circuits[-1].update({'link': 'circuits?id=' + str(circuit['circuitId'])})\n\n # Get image\n circuit_ref = circuit['circuitRef']\n img_path = Image_Handler.build_image_path(circuit_ref , 'circuits')\n circuits[-1].update({'imgpath': img_path})\n\n page = request.args.get('page', 1, type=int)\n page = page - 1\n\n PER_PAGE = 16\n pages = int(len(circuits) / PER_PAGE)\n circuits = circuits[page * PER_PAGE: page * PER_PAGE + PER_PAGE]\n\n return render_template(\n 'circuits-model.html', circuits=circuits, pages=pages, page=page, query=query,\n filtered=filtered, sort=sort\n )\n\n\n@app.route('/drivers')\ndef driver_instance():\n # driver instance page controller\n\n # identify driver and get information from db\n driver_id = int(request.args['id'])\n driver = data.get_driver('driverId' , driver_id)\n name = driver['forename'] + ' ' + driver['surname']\n dob = driver['dob']\n code = driver['code']\n nationality = driver['nationality']\n number = driver['number']\n url = driver['url']\n bio = driver['bio']\n teams = driver['all_constructors']\n cur_constructor = driver['constructor']\n\n victories = []\n results = data.get_result('driverId' , driver_id)\n for result in results:\n if result['position'] == 1:\n victories.append(result)\n\n # find driver's 5 latest races\n victories = sorted(victories, key=lambda i: i['raceDate'], reverse=True)\n latest = sorted(results, key=lambda i: i['raceDate'], reverse=True)\n if len(latest) >= 5:\n latest = latest[:5]\n\n # Get image\n driver_ref = driver['driverRef']\n img_path = Image_Handler.build_image_path(driver_ref , 'drivers')\n\n return render_template(\n 'drivers-instance.html', name=name, code=code, dob=dob, nation=nationality,\n number=number, teams=teams, url=url, img_path=img_path, victories=victories,\n latest=latest, bio=bio, constructor=cur_constructor\n )\n\n\n@app.route('/constructors')\ndef constructor_instance():\n #constructor instance page controller\n\n # identify constructor and get information from db\n constructor_id = int(request.args['id'])\n constructor = data.get_constructor('constructorId', constructor_id)\n team_drivers = data.get_drivers('constructor.id' , constructor_id)\n name = constructor['name']\n nation = constructor['nationality']\n url = constructor['url']\n bio = constructor['bio']\n top_driver = {'id': constructor['topDriverId'], 'name': constructor['topDriverName'],\n 'points': constructor['topDriverPoints']\n }\n \n # find 5 latest victories\n wins = data.get_constructor_standings_from_position(1, constructor_id)\n wins = sorted(wins, key=lambda i: i['raceDate'], reverse=True)\n total_wins = len(wins)\n if total_wins >= 5:\n wins = wins[:5]\n\n # find 5 latest races\n latest_races = data.get_constructor_results('constructorId' , constructor_id)\n latest_races = sorted(latest_races, key=lambda i: i['raceDate'], reverse=True)\n if len(latest_races) >= 5:\n latest_races = latest_races[:5]\n\n # Get image\n constructor_ref = constructor['constructorRef']\n img_path = Image_Handler.build_image_path(constructor_ref , 'constructors')\n\n return render_template(\n 'constructors-instance.html', name=name, nation=nation, drivers=team_drivers, \n wins=wins, img_path=img_path, url=url, bio=bio, total_wins=total_wins,\n top_driver=top_driver, latest_races=latest_races\n )\n\n\n@app.route('/circuits')\ndef circuit_instance():\n # circuit instance page controller\n\n # identify circuit and get information from db\n circuit_id = request.args['id']\n circuit = data.get_circuit('circuitId', int(circuit_id))\n print(circuit)\n name = circuit['name']\n location = circuit['location']\n lat = circuit['lat']\n longitude = circuit['lng']\n country = circuit['country']\n circuit_id = circuit['circuitId']\n url = circuit['url']\n bio = circuit['bio']\n\n # get latest race results\n latest_race = data.get_circuit_latest_race(circuit_id)\n latest_race_name = latest_race['name']\n latest_race_id = latest_race['raceId']\n latest_race_results = data.get_result('raceId' , latest_race_id)\n latest_race_results = sorted(latest_race_results, key=lambda i: i['position'])\n\n # get 5 fastest laptimes\n fastest_lap_times = data.get_lap_times('circuitId' , circuit_id)\n if len(fastest_lap_times) >= 5:\n fastest_lap_times = fastest_lap_times[:5]\n\n # Get image\n circuit_ref = circuit['circuitRef']\n img_path = Image_Handler.build_image_path(circuit_ref , 'circuits')\n\n return render_template(\n 'circuits-instance.html', name=name, lat=lat, long=longitude, locality=location,\n country=country, url=url, img_path=img_path, circuit_id=circuit_id,\n latest_results=latest_race_results, latest_race_name=latest_race_name, bio=bio, \n lap_times=fastest_lap_times\n )\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"548181314","text":"from utility.database.connection import Mongo\nfrom services.transaction.models import Transaction, Transfer\n\n\nmongo = Mongo()\n\nif __name__ == \"__main__\":\n try:\n\n mongo.connect()\n\n numberdata = Transaction.objects.count()\n print(\"\\nnumber of Transactions: \", numberdata)\n\n numberdata = Transfer.objects.count()\n print(\"\\nnumber of Transfers: \", numberdata)\n\n postdata = Transaction.objects.first()\n print(\"\\nfirst data of Transactions: \", postdata.to_json())\n print(postdata.created_date)\n\n postdata = Transfer.objects.first()\n print(\"\\nfirst data of Transfers: \", postdata.to_json())\n\n exit(1)\n except Exception as e:\n\n print(\"Error! {}\".format(e))\n exit(0)\n","sub_path":"web_api/main/data_check.py","file_name":"data_check.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"254110824","text":"import math\nimport urllib2\nimport sqlite3\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import ticker\nimport os.path\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import norm\nimport seaborn as sns\nfrom datetime import date\nfrom black_scholes_option_pricing import Option\n\n# Stock:\n# https://stooq.pl/q/d/l/?s=wig20&i=d\n#\n# Option:\n# https://stooq.pl/q/d/l/?s=ow20f192175.pl&i=d\n\nDATE = 'date'\nOPENNING_PRICE = 'openning_price'\nMAX_PRICE = 'max_price'\nLOW_PRICE = 'low_price'\nENDING_PRICE = 'ending_price'\nVOLUME = 'volume'\nLOP = 'lop'\n\n\nclass Stooq(object):\n\n def __init__(self, database=':memory:'):\n self.baseurl = 'https://stooq.pl/q/d/l/?s'\n self.endurl = '&i=d'\n self.db_conn = sqlite3.connect(database=database)\n self.db_cursor = self.db_conn.cursor()\n\n def create_table(self, table_name):\n \"\"\"\n Create DB table if not exists.\n :param table_name: Table name\n \"\"\"\n\n sql_query = \"\"\"\n CREATE TABLE IF NOT EXISTS {} (\n id integer PRIMARY KEY,\n {} text NOT NULL,\n {} text,\n {} text,\n {} text,\n {} text,\n {} text,\n {} text\n );\n \"\"\".format(table_name, DATE, OPENNING_PRICE, MAX_PRICE, LOW_PRICE, ENDING_PRICE, VOLUME, LOP)\n\n self.db_cursor.execute(sql_query)\n\n def put_data(self, table_name, data):\n \"\"\"\n Insert data into desired table.\n :param table_name: Table name\n :param data: Data to be inserted\n \"\"\"\n for date, value in data.items():\n current_date = date\n current_data = value\n\n sql_query = '''INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}) VALUES (\"{}\", \"{}\", \"{}\", \"{}\", \"{}\", \"{}\", \"{}\");''' \\\n .format(table_name, DATE, OPENNING_PRICE, MAX_PRICE, LOW_PRICE, ENDING_PRICE, VOLUME, LOP, current_date,\n current_data[OPENNING_PRICE], current_data[MAX_PRICE], current_data[LOW_PRICE],\n current_data[ENDING_PRICE], current_data[VOLUME], current_data[LOP])\n\n self.db_cursor.execute(sql_query)\n\n def get_stock(self, stock):\n \"\"\"\n To get historical data for option\n :param stock: Stock symbol\n :return: header and historical trading\n \"\"\"\n\n url = \"{}={}{}\".format(self.baseurl, stock, self.endurl)\n req = urllib2.urlopen(url)\n data = req.readlines()\n\n header, stock_data = self.data_parser(data, asset=stock)\n\n return header, stock_data\n\n def get_option(self, option):\n \"\"\"\n To get historical data for option\n :param option: Option symbol\n :return: header and historical trading\n \"\"\"\n\n url = \"{}={}{}{}\".format(self.baseurl, option, '.pl', self.endurl)\n req = urllib2.urlopen(url)\n data = req.readlines()\n\n header, option_data = self.data_parser(data, asset=option)\n\n return header, option_data\n\n def data_parser(self, data, asset):\n \"\"\"\n Parse data from input for given asset and insert it into DB.\n\n :param data: Data gathered for given asset\n :param asset: Asset\n :return: Header and gathered data\n \"\"\"\n\n # Create relevant table\n self.create_table(table_name=asset)\n\n asset_data = {}\n header = None\n i = 0\n\n for line in data:\n if i == 0:\n header = line\n i += 1\n else:\n single_line = line.rstrip().split(\",\")\n date = single_line[0]\n openning_price = single_line[1]\n max_price = single_line[2]\n low_price = single_line[3]\n ending_price = single_line[4]\n volume = single_line[5]\n lop = single_line[6] if len(single_line) == 7 else 0\n\n asset_data[date] = {\n OPENNING_PRICE: openning_price,\n MAX_PRICE: max_price,\n LOW_PRICE: low_price,\n ENDING_PRICE: ending_price,\n VOLUME: volume,\n LOP: lop\n }\n\n self.put_data(table_name=asset, data=asset_data)\n\n return header, asset_data\n\n def plot_asset(self, asset, years):\n \"\"\"\n Plot data for asset.\n\n :param asset: Asset\n :param years: Plots for given years ranger\n \"\"\"\n\n sql = '''select * from {} order by date({}) ASC;'''.format(asset, DATE)\n\n data = self.db_cursor.execute(sql).fetchall()\n\n dates = []\n openings = []\n\n is_data_found = False\n\n for d in data:\n y = int(d[1].split(\"-\")[0])\n if y in years:\n is_data_found = True\n dates.append(d[1])\n openings.append(float(d[2]))\n\n if is_data_found:\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16,6), facecolor='w')\n\n # Find Gaussian distribution parameters\n mean, standard_deviation = norm.fit(openings)\n\n # First plot: Price vs time\n ax1.grid()\n ax1.set(xlabel='Time (days)', ylabel='Price (pln)', title='{} price'.format(asset))\n\n ax1.plot(dates, openings, lw=1, label='Open Price')\n ax1.plot(dates, [mean for a in openings], lw=1, label='$\\mu$ Price')\n\n # For x (time) axis\n every_xaxis_tick = int(0.05*len(dates)) if len(dates) > 100 else 1\n ax1.xaxis.set_ticks(dates[::every_xaxis_tick])\n ax1.set_xticklabels(dates[::every_xaxis_tick], minor=False, rotation=30)\n\n # Fox y (Price) axis\n every_yaxis_tick = (max(openings) - min(openings))/10\n start, end = ax1.get_ylim()\n ax1.yaxis.set_ticks(np.arange(start, end, every_yaxis_tick))\n ax1.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x}'))\n\n # Set up grid, legend, and limits\n ax1.legend(frameon=False)\n\n print(\"Saving data, number of points: {}\".format(len(dates)))\n\n # Second plot: Histogram and Gauss distribution fit\n ax2.grid()\n ax2.set(xlabel='Price (pln)', ylabel='Number of shares',\n title=\"{} Histogram, $\\sigma$ = {:.2f}, $\\mu$ = {:.2f}\".format(asset, standard_deviation, mean))\n\n sns.distplot(openings, ax=ax2)\n\n # ax2.hist(openings, color='green', bins=15, density=False)\n ax2.legend(frameon=False)\n fig.tight_layout()\n plt.savefig(\"{}.png\".format(asset))\n else:\n print(\"No data for asset: {}, for year: {}\".format(asset, years))\n\n def plot_option_and_asset(self, option, asset, year, volatility=None, r=None):\n \"\"\"\n Plot data for asset.\n\n :param option: Option\n :param asset: Asset\n :param years: Plots for given year\n \"\"\"\n\n K = float(option[-4::])\n r = 0.025\n\n sql_option = '''select * from {} order by date({}) ASC;'''.format(option, DATE)\n option_data = self.db_cursor.execute(sql_option).fetchall()\n\n sql_asset = '''select * from {} order by date({}) ASC;'''.format(asset, DATE)\n asset_data = self.db_cursor.execute(sql_asset).fetchall()\n\n # Days lists\n option_dates = []\n asset_dates = []\n\n # Option, open price from market\n option_openings = []\n\n # Option, Black-Scholes price (calulated)\n option_bs_price = []\n\n # Expiration time in days\n expiration_time = []\n\n # Stock, open price from market\n asset_openings = []\n\n is_data_found = False\n\n # Make Option prices\n for d in option_data:\n y = int(d[1].split(\"-\")[0])\n if y == year:\n is_data_found = True\n option_dates.append(d[1])\n option_openings.append(float(d[2]))\n\n # Make Stock prices\n for e in asset_data:\n if e[1] in option_dates:\n asset_dates.append(e[1])\n asset_openings.append(float(e[2]))\n\n # Make expiration time (days)\n for a in asset_dates:\n T = self.expiration_time_days(a, asset_dates[-1])\n expiration_time.append(T)\n\n # Make volatility if volatility is not set\n if not volatility:\n volatility = self.calculate_volatility(asset=asset_openings)\n\n # Black-Scholes calculus - vanilla option\n i = 0\n\n for T in expiration_time[:-1]:\n stock_price = asset_openings[i]\n bs_calculus = Option(stock_price, K, T, r, volatility)\n bs_price = bs_calculus.euro_vanilla_call()\n option_bs_price.append(bs_price)\n i += 1\n\n # Boundary condition\n option_bs_price.append(max(asset_openings[-1] - K, 0))\n\n if is_data_found:\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16,6), facecolor='w')\n\n # Find Gaussian distribution parameters\n mean, standard_deviation = norm.fit(asset_openings)\n\n # First plot: Price vs time\n ax1.grid()\n ax1.set(xlabel='Time (days)', ylabel='Price (pln)', title='{} price'.format(option))\n\n ax1.plot(option_dates, option_openings, lw=1, label='Option, market data')\n ax1.plot(option_dates, option_bs_price, lw=2, label=\"Black-Scholes computation, \"\n \"\\nhistorical volatility = {:.2f}, \"\n \"\\nS(T) = {:.2f}, \"\n \"\\nK = {}, \"\n \"\\nr = {}, \"\n \"\\nc(T) = max(S(T) - k, 0) = {}\".\n format(volatility, asset_openings[-1], K, r, max(asset_openings[-1] -K, 0)))\n\n # Set up grid, legend, and limits\n ax1.legend(loc='upper left', shadow=False)\n ax1.legend(frameon=True)\n\n # For x (time) axis\n every_xaxis_tick = int(0.05*len(option_dates)) if len(option_dates) > 100 else 1\n ax1.xaxis.set_ticks(option_dates[::every_xaxis_tick])\n ax1.set_xticklabels(option_dates[::every_xaxis_tick], minor=False, rotation=30)\n\n # Fox y (Price) axis\n every_yaxis_tick = (max(option_openings) - min(option_openings))/10\n start, end = ax1.get_ylim()\n ax1.yaxis.set_ticks(np.arange(start, end, every_yaxis_tick))\n ax1.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x}'))\n\n print(\"Saving data, number of points: {}\".format(len(option_dates)))\n\n # Second plot: Histogram and Gauss distribution fit\n ax2.grid()\n ax2.set(xlabel='Time (days)', ylabel='Price (pln)',\n title=\"{} price, $\\sigma$ = {:.2f}, $\\mu$ = {:.2f}\".format(asset, standard_deviation, mean))\n\n # ax2.hist(openings, color='green', bins=15, density=False)\n ax2.plot(asset_dates, asset_openings, lw=1, label='Open price, asset: {}'.format(asset))\n\n # For x (time) axis\n every_xaxis_tick = int(0.05 * len(asset_dates)) if len(asset_dates) > 100 else 1\n ax2.xaxis.set_ticks(asset_dates[::every_xaxis_tick])\n ax2.set_xticklabels(asset_dates[::every_xaxis_tick], minor=False, rotation=30)\n\n # Fox y (Price) axis\n every_yaxis_tick = (max(asset_openings) - min(asset_openings)) / 10\n start, end = ax1.get_ylim()\n ax1.yaxis.set_ticks(np.arange(start, end, every_yaxis_tick))\n ax1.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x}'))\n\n ax2.legend(frameon=True)\n fig.tight_layout()\n plt.savefig(\"{}_{}.png\".format(option, asset))\n else:\n print(\"No data for option: {}, for year: {}\".format(option, year))\n\n def calculate_volatility(self, asset):\n \"\"\"\n Calculate volatility for given asset.\n\n :param asset: Stock prices\n\n :return: volatility\n \"\"\"\n\n vol = []\n\n i = 0\n for _ in asset[:-1]:\n v = (asset[i + 1] - asset[i])/asset[i]\n vol.append(v)\n i += 1\n\n volatility = reduce(lambda x, y : x + y, vol)/len(vol)\n\n volatility = math.sqrt(252) * volatility\n\n return volatility\n\n def calculate_option_price(self, asset_price, r, sigma, K, current_date, expiration_date):\n \"\"\"\n Calculates call price at the basis of Black-Scholes model.\n\n :param asset_price: Current asset price\n :param r: Risk free\n :param sigma: Asset volatility\n :param K: Strike price\n :param current_date: Current date\n :param expiration_date: Expiration date\n\n :return: Call price\n \"\"\"\n\n T = self.expiration_time_days(current_date=current_date, expiration_date=expiration_date)\n\n o = Option(asset_price, K, T, r, sigma)\n\n call_price = o.euro_vanilla_call()\n\n return call_price\n\n def expiration_time_days(self, current_date, expiration_date):\n \"\"\"\n Calculates days between two dates: current and expiration date.\n\n :param current_date: Current date\n :param expiration_date: Expiration date\n\n :return: Date between dates\n \"\"\"\n\n current_date = map(lambda x: int(x), current_date.split(\"-\"))\n expiration_date = map(lambda x: int(x), expiration_date.split(\"-\"))\n days_obj = date(expiration_date[0], expiration_date[1], expiration_date[2]) - date(current_date[0], current_date[1], current_date[2])\n\n days = days_obj.days\n\n return days\n\n def end_connection(self):\n \"\"\"\n Commit changes and close db connection.\n \"\"\"\n\n self.db_conn.commit()\n self.db_conn.close()\n\n\nif __name__ == \"__main__\":\n\n db_name = '/var/tmp/stooq.db'\n\n is_db_initialized = os.path.isfile(db_name)\n s = Stooq(db_name)\n\n if not is_db_initialized:\n s.get_stock('wig20')\n s.get_option('ow20f192175')\n\n s.plot_asset('wig20', [2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])\n s.plot_asset('ow20f192175', [2018, 2019])\n s.plot_option_and_asset(option='ow20f192175', asset='wig20', year=2019, r=0.02, volatility=0.2)\n s.end_connection()\n","sub_path":"stooq_trader.py","file_name":"stooq_trader.py","file_ext":"py","file_size_in_byte":14513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"27996743","text":"import os\nfrom datetime import datetime\nimport logging\nimport time\nfrom logging.handlers import RotatingFileHandler\nimport inspect\n\n\n\n\nclass Log(object):\n def __init__(self, name, console=1, logfile=None, show_details=False):\n self._level = logging.DEBUG\n self._mode = \"a\"\n self._max_bytes = 10 * 1024 * 1024\n self._rotate_count = 5\n self._log_file = logfile\n self._console = console\n self._lock_file = None\n self._fp = None\n\n self._logger = logging.getLogger(name)\n self._logger.setLevel(self._level)\n\n self._show_details = show_details\n\n logging.Formatter.converter = time.gmtime\n formatter = logging.Formatter(\n \"%(asctime)s %(levelname)-8s %(threadName)s %(message)s\")\n\n if self._console == 1:\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(formatter)\n self._logger.addHandler(stream_handler)\n\n if self._log_file is not None:\n self._lock_file = logfile + \".lock\"\n\n rotate_handler = RotatingFileHandler(\n filename=self._log_file,\n mode=self._mode,\n maxBytes=self._max_bytes,\n backupCount=self._rotate_count)\n rotate_handler.setFormatter(formatter)\n self._logger.addHandler(rotate_handler)\n\n def set_debug_level(self):\n if self._logger is not None:\n self._logger.setLevel(logging.DEBUG)\n\n def set_info_level(self):\n if self._logger is not None:\n self._logger.setLevel(logging.INFO)\n\n def set_warning_level(self):\n if self._logger is not None:\n self._logger.setLevel(logging.WARNING)\n\n def set_error_level(self):\n if self._logger is not None:\n self._logger.setLevel(logging.ERROR)\n\n def set_critical_level(self):\n if self._logger is not None:\n self._logger.setLevel(logging.CRITICAL)\n\n def _lock(self):\n if self._lock_file is not None:\n self._fp = open(self._lock_file, 'w')\n if self._fp is not None:\n lock(self._fp, LOCK_EX)\n\n def _unlock(self):\n if self._fp is not None:\n unlock(self._fp)\n self._fp.close()\n\n def debug(self, msg, *args, **kwargs):\n if self._logger is not None:\n self._logger.debug(self.show_detail(msg), *args, **kwargs)\n\n def info(self, msg, *args, **kwargs):\n if self._logger is not None:\n self._logger.info(self.show_detail(msg), *args, **kwargs)\n\n def warning(self, msg, *args, **kwargs):\n if self._logger is not None:\n self._logger.warning(self.show_detail(msg), *args, **kwargs)\n\n def error(self, msg, *args, **kwargs):\n if self._logger is not None:\n self._logger.error(self.show_detail(msg), *args, **kwargs)\n\n def critical(self, msg, *args, **kwargs):\n if self._logger is not None:\n self._logger.critical(self.show_detail(msg), *args, **kwargs)\n\n def show_detail(self, message):\n if not self._show_details:\n return message\n lastframe = inspect.currentframe().f_back.f_back\n funcName = lastframe.f_code.co_name\n filelineno = lastframe.f_lineno\n fileName = os.path.basename(lastframe.f_code.co_filename)\n return \"%s (%s:%i)\\t%s\" % (\n funcName,\n fileName,\n filelineno,\n message)\n\ndef Logger(logname):\n base_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n log_path = os.path.join(base_path, \"logs\")\n\n log_time = datetime.today().strftime('%Y-%m-%d')\n log_file = os.path.join(log_path, logname+\"-\" + str(log_time) + \".log\")\n if not os.path.isdir(log_path):\n os.makedirs(log_path)\n\n logger_instance = Log(logname, console=1, logfile=log_file, show_details=True)\n return logger_instance\n\n","sub_path":"core/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"462233903","text":" #Model Classes\n\nclass Doctor:\n\tdef __init__(self,doctorid=None,name=None,address=None,phone=None,qualification=None,gender=None,visitcharges=None):\n\t\tself.doctorid=doctorid\n\t\tself.name=name\n\t\tself.address=address\n\t\tself.phone=phone\n\t\tself.qualification=qualification\n\t\tself.gender=gender\n\t\tself.visitcharges=visitcharges\n\n\nclass Patient:\n\tdef __init__(self,patientno=None,name=None,age=None,gender=None,address=None,contactno=None):\n\t\tself.patientno=patientno\n\t\tself.name=name\n\t\tself.age=age\n\t\tself.gender=gender\n\t\tself.address=address\n\t\tself.contactno=contactno\n\n\nclass Room:\n\tdef __init__(self,roomno=None,roomtype=None,occupancy=None,roomcharges=None):\n\t\tself.roomno=roomno\n\t\tself.roomtype=roomtype\n\t\tself.occupancy=occupancy\n\t\tself.roomcharges=roomcharges\n\n\nclass Diagnosis:\n\tdef __init__(self,diagnosisid=None,admissionno=None,dod=None,report=None):\n\t\tself.diagnosisid=diagnosisid\n\t\tself.admissionno=admissionno\n\t\tself.dod=dod\n\t\tself.report=report\n\nclass Admission:\n\tdef __init__(self,admissionno=None, patientno=None, doctorid=None, roomno=None, admiton=None, dischargedon=None):\n\t\tself.admissionno=admissionno\n\t\tself.patientno=patientno\n\t\tself.doctorid=doctorid\n\t\tself.roomno=roomno\n\t\tself.admiton=admiton\n\t\tself.dischargedon=dischargedon\n\nclass BillDetails:\n\tdef __init__(self, billno=None, admissionno=None, date=None, roomcharges=None, pathologyfees=None, doctorfees=None, misccharges=None):\t\t\n\t\tself.billno=billno\n\t\tself.admissionno=admissionno\n\t\tself.date=date\n\t\tself.roomcharges=roomcharges\n\t\tself.pathologyfees=pathologyfees\n\t\tself.doctorfees=doctorfees\n\t\tself.misccharges=misccharges\n","sub_path":"Projects/Console/Hospital Management System/HMS/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"606362663","text":"from flask import Flask, render_template\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_pyfile('settings.py')\n\n @app.route('/')\n def home():\n return render_template('home.html',header='About me')\n\n @app.route('/projects/')\n def projects():\n projects = [\n {\n 'title': 'ML fine art price prediction',\n 'body': 'Check if ML can predict the price of paintings.',\n 'url': 'fine_art'\n },\n {\n 'title': 'Confocal microscopy',\n 'body': 'Tumour cell detection on confocal microscopy images',\n 'url': 'confocal_microscopy'\n },\n {\n 'title': 'Deutsch Meister',\n 'body': 'Python and Starlette based app helping me and my friends to follow and repeat what have we learned.',\n 'url': 'deutsch_meister'\n },\n {\n 'title': 'QuantX Backtest',\n 'body': 'Backtesting engine for stock market.',\n 'url': 'quantx_backtest'\n },\n {\n 'title': 'Jigsaw Puzzle Solver',\n 'body': 'AI approach for solving jigsaw puzzles.',\n 'url': 'jigsaw_puzzle_solver'\n }\n ]\n return render_template('projects.html', projects=projects)\n\n @app.route('/blog/')\n def blog():\n posts = [\n {\n 'title': 'pytest mini tutorial',\n 'date': '1.11.2019',\n 'body': 'This is mini pytest tutorial',\n 'url': 'pytest_mini_tutorial'\n },\n {\n 'title': 'ML Conference',\n 'date': '29.09.2019',\n 'body': 'I was on a conference...',\n 'url': 'ml_conference'\n },\n {\n 'title': 'HackYeah',\n 'date': '10.10.2019',\n 'body': 'Events on HackYeah...',\n 'url': 'hackyeah2019'\n }\n ]\n return render_template('blog.html', posts=posts)\n\n @app.route('/cv/')\n def cv():\n return render_template('cv.html')\n\n @app.route('/projects//')\n def project_page(project_url):\n return render_template(f'projects/{project_url}.html')\n\n @app.route('/blog//')\n def blog_page(post_url):\n return render_template(f'posts/{post_url}.html')\n\n @app.errorhandler(404)\n def not_found(exc):\n return 'Not found 404'\n\n return app\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"294862906","text":"import os\nimport typing\n\nfrom qtpy import QtCore as QC\nfrom qtpy import QtWidgets as QW\n\nfrom hydrus.core import HydrusData\nfrom hydrus.core import HydrusExceptions\nfrom hydrus.core import HydrusGlobals as HG\nfrom hydrus.core import HydrusSerialisable\nfrom hydrus.client import ClientConstants as CC\nfrom hydrus.client import ClientSerialisable\nfrom hydrus.client.gui import ClientGUIDragDrop\nfrom hydrus.client.gui import ClientGUICommon\nfrom hydrus.client.gui import ClientGUICore as CGC\nfrom hydrus.client.gui import ClientGUIFunctions\nfrom hydrus.client.gui import ClientGUIShortcuts\nfrom hydrus.client.gui import QtPorting as QP\n\ndef SafeNoneInt( value ):\n \n return -1 if value is None else value\n \ndef SafeNoneStr( value ):\n \n return '' if value is None else value\n \nclass BetterListCtrl( QW.QTreeWidget ):\n \n listCtrlChanged = QC.Signal()\n \n def __init__( self, parent, name, height_num_chars, sizing_column_initial_width_num_chars, columns, data_to_tuples_func, use_simple_delete = False, delete_key_callback = None, activation_callback = None, style = None ): \n \n QW.QTreeWidget.__init__( self, parent )\n \n self.setAlternatingRowColors( True )\n self.setColumnCount( len(columns) )\n self.setSortingEnabled( False ) # Keeping the custom sort implementation. It would be better to use Qt's native sorting in the future so sort indicators are displayed on the headers as expected.\n self.setSelectionMode( QW.QAbstractItemView.ExtendedSelection )\n self.setRootIsDecorated( False )\n \n self._data_to_tuples_func = data_to_tuples_func\n \n self._use_simple_delete = use_simple_delete\n \n self._menu_callable = None\n \n self._sort_column = 0\n self._sort_asc = True\n \n # eventually have it look up 'name' in some options somewhere and see previous height, width, and column selection\n # this thing should deal with missing entries but also have some filtered defaults for subs listctrl, which will have a bunch of possible columns\n \n self._indices_to_data_info = {}\n self._data_to_indices = {}\n \n sizing_column_initial_width = self.fontMetrics().boundingRect( 'x' * sizing_column_initial_width_num_chars ).width()\n total_width = self.fontMetrics().boundingRect( 'x' * sizing_column_initial_width_num_chars ).width()\n \n resize_column = 1\n \n for ( i, ( name, width_num_chars ) ) in enumerate( columns ):\n \n if width_num_chars == -1:\n \n width = -1\n \n resize_column = i + 1\n \n else:\n \n width = self.fontMetrics().boundingRect( 'x' * width_num_chars ).width()\n \n total_width += width\n \n \n self.headerItem().setText( i, name )\n \n self.setColumnWidth( i, width )\n \n \n # Technically this is the previous behavior, but the two commented lines might work better in some cases (?)\n self.header().setStretchLastSection( False )\n self.header().setSectionResizeMode( resize_column - 1 , QW.QHeaderView.Stretch )\n #self.setColumnWidth( resize_column - 1, sizing_column_initial_width )\n #self.header().setStretchLastSection( True )\n \n # hydev looked at this problem. the real answer I think will be to move to column size memory and let the last section resize\n # start with decent values and then we can remember whatever the user ends up liking later. this will be simpler\n \n self.setMinimumWidth( total_width )\n \n self.GrowShrinkColumnsHeight( height_num_chars )\n \n self._delete_key_callback = delete_key_callback\n self._activation_callback = activation_callback\n \n self._widget_event_filter = QP.WidgetEventFilter( self )\n self._widget_event_filter.EVT_KEY_DOWN( self.EventKeyDown )\n self.itemDoubleClicked.connect( self.EventItemActivated )\n \n self.header().setSectionsClickable( True )\n self.header().sectionClicked.connect( self.EventColumnClick )\n \n \n def _AddDataInfo( self, data_info ):\n \n ( data, display_tuple, sort_tuple ) = data_info\n \n if data in self._data_to_indices:\n \n return\n \n \n append_item = QW.QTreeWidgetItem()\n \n for i in range( len( display_tuple ) ):\n \n text = display_tuple[i]\n \n if len( text ) > 0:\n \n text = text.splitlines()[0]\n \n \n append_item.setText( i, text )\n append_item.setToolTip( i, text )\n \n \n self.addTopLevelItem( append_item )\n \n index = self.topLevelItemCount() - 1 \n \n self._indices_to_data_info[ index ] = data_info\n self._data_to_indices[ data ] = index\n \n \n def _GetDisplayAndSortTuples( self, data ):\n \n ( display_tuple, sort_tuple ) = self._data_to_tuples_func( data )\n \n better_sort = []\n \n for item in sort_tuple:\n \n if isinstance( item, str ):\n \n item = HydrusData.HumanTextSortKey( item )\n \n \n better_sort.append( item )\n \n \n sort_tuple = tuple( better_sort )\n \n return ( display_tuple, sort_tuple )\n \n \n def _GetSelected( self ): \n \n indices = []\n \n for i in range( self.topLevelItemCount() ):\n \n if self.topLevelItem( i ).isSelected(): indices.append( i )\n \n return indices\n \n \n def _RecalculateIndicesAfterDelete( self ):\n \n indices_and_data_info = sorted( self._indices_to_data_info.items() )\n \n self._indices_to_data_info = {}\n self._data_to_indices = {}\n \n for ( index, ( old_index, data_info ) ) in enumerate( indices_and_data_info ):\n \n ( data, display_tuple, sort_tuple ) = data_info\n \n self._data_to_indices[ data ] = index\n self._indices_to_data_info[ index ] = data_info\n \n \n \n def _ShowMenu( self ):\n \n try:\n \n menu = self._menu_callable()\n \n except HydrusExceptions.DataMissing:\n \n return\n \n \n CGC.core().PopupMenu( self, menu )\n \n \n def _SortDataInfo( self ):\n \n data_infos = list( self._indices_to_data_info.values() )\n \n def sort_key( data_info ):\n \n ( data, display_tuple, sort_tuple ) = data_info\n \n return ( sort_tuple[ self._sort_column ], sort_tuple ) # add the sort tuple to get secondary sorting\n \n \n data_infos.sort( key = sort_key, reverse = not self._sort_asc )\n \n return data_infos\n \n \n def _SortAndRefreshRows( self ):\n \n selected_data_quick = set( self.GetData( only_selected = True ) )\n \n self.clearSelection()\n \n sorted_data_info = self._SortDataInfo()\n \n self._indices_to_data_info = {}\n self._data_to_indices = {}\n \n for ( index, data_info ) in enumerate( sorted_data_info ):\n \n self._indices_to_data_info[ index ] = data_info\n \n ( data, display_tuple, sort_tuple ) = data_info\n \n self._data_to_indices[ data ] = index\n \n self._UpdateRow( index, display_tuple )\n \n if data in selected_data_quick:\n \n self.topLevelItem( index ).setSelected( True )\n \n \n \n \n def _UpdateRow( self, index, display_tuple ):\n \n for ( column_index, value ) in enumerate( display_tuple ):\n \n if len( value ) > 0:\n \n value = value.splitlines()[0]\n \n \n tree_widget_item = self.topLevelItem( index )\n \n existing_value = tree_widget_item.text( column_index )\n \n if existing_value != value:\n \n tree_widget_item.setText( column_index, value )\n tree_widget_item.setToolTip( column_index, value )\n \n \n \n \n def AddDatas( self, datas: typing.Iterable[ object ] ):\n \n for data in datas:\n \n ( display_tuple, sort_tuple ) = self._GetDisplayAndSortTuples( data )\n \n self._AddDataInfo( ( data, display_tuple, sort_tuple ) )\n \n \n self.listCtrlChanged.emit()\n \n \n def AddMenuCallable( self, menu_callable ):\n \n self._menu_callable = menu_callable\n \n self.setContextMenuPolicy( QC.Qt.CustomContextMenu )\n self.customContextMenuRequested.connect( self.EventShowMenu )\n \n \n def DeleteDatas( self, datas: typing.Iterable[ object ] ):\n \n deletees = [ ( self._data_to_indices[ data ], data ) for data in datas ]\n \n deletees.sort( reverse = True )\n \n # The below comment is most probably obsolote (from before the Qt port), but keeping it just in case it is not and also as an explanation.\n #\n # I am not sure, but I think if subsequent deleteitems occur in the same event, the event processing of the first is forced!!\n # this means that button checking and so on occurs for n-1 times on an invalid indices structure in this thing before correcting itself in the last one\n # if a button update then tests selected data against the invalid index and a selection is on the i+1 or whatever but just got bumped up into invalid area, we are exception city\n # this doesn't normally affect us because mostly we _are_ deleting selections when we do deletes, but 'try to link url stuff' auto thing hit this\n # I obviously don't want to recalc all indices for every delete\n # so I wrote a catch in getdata to skip the missing error, and now I'm moving the data deletion to a second loop, which seems to help\n \n for ( index, data ) in deletees:\n \n self.takeTopLevelItem( index )\n \n \n for ( index, data ) in deletees:\n \n del self._data_to_indices[ data ]\n \n del self._indices_to_data_info[ index ]\n \n \n self._RecalculateIndicesAfterDelete()\n \n self.listCtrlChanged.emit()\n \n \n def DeleteSelected( self ):\n \n indices = self._GetSelected()\n \n indices.sort( reverse = True )\n \n for index in indices:\n \n ( data, display_tuple, sort_tuple ) = self._indices_to_data_info[ index ]\n \n item = self.takeTopLevelItem( index )\n \n del item\n \n del self._data_to_indices[ data ]\n \n del self._indices_to_data_info[ index ]\n \n \n self._RecalculateIndicesAfterDelete()\n \n self.listCtrlChanged.emit()\n \n \n def EventColumnClick( self, col ):\n \n if col == self._sort_column:\n \n self._sort_asc = not self._sort_asc\n \n else:\n \n self._sort_column = col\n \n self._sort_asc = True\n \n \n self._SortAndRefreshRows()\n \n \n def EventItemActivated( self, item, column ):\n \n if self._activation_callback is not None:\n \n self._activation_callback()\n \n \n \n def EventKeyDown( self, event ):\n \n ( modifier, key ) = ClientGUIShortcuts.ConvertKeyEventToSimpleTuple( event )\n \n if key in ClientGUIShortcuts.DELETE_KEYS_QT:\n \n self.ProcessDeleteAction()\n \n elif key in ( ord( 'A' ), ord( 'a' ) ) and modifier == QC.Qt.ControlModifier:\n \n self.selectAll()\n \n else:\n \n return True # was: event.ignore()\n \n \n \n def EventShowMenu( self ):\n \n QP.CallAfter( self._ShowMenu )\n \n \n def GetData( self, only_selected = False ):\n \n if only_selected:\n \n indices = self._GetSelected()\n \n else:\n \n indices = list(self._indices_to_data_info.keys())\n \n \n result = []\n \n for index in indices:\n \n # this can get fired while indices are invalid, wew\n if index not in self._indices_to_data_info:\n \n continue\n \n \n ( data, display_tuple, sort_tuple ) = self._indices_to_data_info[ index ]\n \n result.append( data )\n \n \n return result\n \n \n def GrowShrinkColumnsHeight( self, ideal_rows ):\n \n # +2 for the header row and * 1.25 for magic rough text-to-rowheight conversion\n \n existing_min_width = self.minimumWidth()\n \n ( width_gumpf, ideal_client_height ) = ClientGUIFunctions.ConvertTextToPixels( self, ( 20, int( ( ideal_rows + 2 ) * 1.25 ) ) )\n \n QP.SetMinClientSize( self, ( existing_min_width, ideal_client_height ) )\n \n \n def HasData( self, data: object ):\n \n return data in self._data_to_indices\n \n \n def HasOneSelected( self ):\n \n return len( self.selectedItems() ) == 1\n \n \n def HasSelected( self ):\n \n return len( self.selectedItems() ) > 0 \n \n \n def ProcessDeleteAction( self ):\n \n if self._use_simple_delete:\n \n self.ShowDeleteSelectedDialog()\n \n elif self._delete_key_callback is not None:\n \n self._delete_key_callback()\n \n \n \n def SelectDatas( self, datas: typing.Iterable[ object ] ):\n \n for data in datas:\n \n if data in self._data_to_indices:\n \n index = self._data_to_indices[ data ]\n \n self.topLevelItem( index ).setSelected( True )\n \n \n \n \n def SetData( self, datas: typing.Iterable[ object ] ):\n \n existing_datas = set( self._data_to_indices.keys() )\n \n # useful to preserve order here sometimes (e.g. export file path generation order)\n datas_to_add = [ data for data in datas if data not in existing_datas ]\n datas_to_update = [ data for data in datas if data in existing_datas ]\n datas_to_delete = existing_datas.difference( datas )\n \n if len( datas_to_delete ) > 0:\n \n self.DeleteDatas( datas_to_delete )\n \n \n if len( datas_to_update ) > 0:\n \n self.UpdateDatas( datas_to_update )\n \n \n if len( datas_to_add ) > 0:\n \n self.AddDatas( datas_to_add )\n \n \n self._SortAndRefreshRows()\n \n self.listCtrlChanged.emit()\n \n \n def ShowDeleteSelectedDialog( self ):\n \n from hydrus.client.gui import ClientGUIDialogsQuick\n \n result = ClientGUIDialogsQuick.GetYesNo( self, 'Remove all selected?' )\n \n if result == QW.QDialog.Accepted:\n \n self.DeleteSelected()\n \n \n \n def Sort( self, col = None, asc = None ):\n \n if col is not None:\n \n self._sort_column = col\n \n \n if asc is not None:\n \n self._sort_asc = asc\n \n \n self._SortAndRefreshRows()\n \n self.listCtrlChanged.emit()\n \n \n def UpdateDatas( self, datas: typing.Optional[ typing.Iterable[ object ] ] = None ):\n \n if datas is None:\n \n # keep it sorted here, which is sometimes useful\n \n indices_and_datas = sorted( ( ( index, data ) for ( data, index ) in self._data_to_indices.items() ) )\n \n datas = [ data for ( index, data ) in indices_and_datas ]\n \n \n sort_data_has_changed = False\n \n for data in datas:\n \n ( display_tuple, sort_tuple ) = self._GetDisplayAndSortTuples( data )\n \n data_info = ( data, display_tuple, sort_tuple )\n \n index = self._data_to_indices[ data ]\n \n existing_data_info = self._indices_to_data_info[ index ]\n \n if data_info != existing_data_info:\n \n if not sort_data_has_changed:\n \n ( existing_data, existing_display_tuple, existing_sort_tuple ) = existing_data_info\n \n if sort_tuple[ self._sort_column ] != existing_sort_tuple[ self._sort_column ]: # this does not govern secondary sorts, but let's not spam sorts m8\n \n sort_data_has_changed = True\n \n \n \n self._indices_to_data_info[ index ] = data_info\n \n self._UpdateRow( index, display_tuple )\n \n \n \n self.listCtrlChanged.emit()\n \n return sort_data_has_changed\n \n\n def SetNonDupeName( self, obj: object ):\n\n current_names = { o.GetName() for o in self.GetData() if o is not obj }\n\n HydrusSerialisable.SetNonDupeName( obj, current_names )\n \n \n def ReplaceData( self, old_data: object, new_data: object ):\n \n new_data = QP.ListsToTuples( new_data )\n \n data_index = self._data_to_indices[ old_data ]\n\n ( display_tuple, sort_tuple ) = self._GetDisplayAndSortTuples( new_data )\n \n data_info = ( new_data, display_tuple, sort_tuple )\n \n self._indices_to_data_info[ data_index ] = data_info\n \n del self._data_to_indices[ old_data ]\n \n self._data_to_indices[ new_data ] = data_index\n \n self._UpdateRow( data_index, display_tuple )\n \n \nclass BetterListCtrlPanel( QW.QWidget ):\n \n def __init__( self, parent ):\n \n QW.QWidget.__init__( self, parent )\n \n self._vbox = QP.VBoxLayout()\n \n self._buttonbox = QP.HBoxLayout()\n \n self._listctrl = None\n \n self._permitted_object_types = []\n self._import_add_callable = lambda x: None\n self._custom_get_callable = None\n \n self._button_infos = []\n \n \n def _AddAllDefaults( self, defaults_callable, add_callable ):\n \n defaults = defaults_callable()\n \n for default in defaults:\n \n add_callable( default )\n \n \n self._listctrl.Sort()\n \n \n def _AddButton( self, button, enabled_only_on_selection = False, enabled_only_on_single_selection = False, enabled_check_func = None ):\n \n QP.AddToLayout( self._buttonbox, button, CC.FLAGS_VCENTER )\n \n if enabled_only_on_selection:\n \n enabled_check_func = self._HasSelected\n \n \n if enabled_only_on_single_selection:\n \n enabled_check_func = self._HasOneSelected\n \n \n if enabled_check_func is not None:\n \n self._button_infos.append( ( button, enabled_check_func ) )\n \n \n \n def _AddSomeDefaults( self, defaults_callable, add_callable ):\n \n defaults = defaults_callable()\n \n selected = False\n \n choice_tuples = [ ( default.GetName(), default, selected ) for default in defaults ]\n \n from hydrus.client.gui import ClientGUITopLevelWindowsPanels\n from hydrus.client.gui import ClientGUIScrolledPanelsEdit\n \n with ClientGUITopLevelWindowsPanels.DialogEdit( self, 'select the defaults to add' ) as dlg:\n \n panel = ClientGUIScrolledPanelsEdit.EditChooseMultiple( dlg, choice_tuples )\n \n dlg.SetPanel( panel )\n \n if dlg.exec() == QW.QDialog.Accepted:\n \n defaults_to_add = panel.GetValue()\n \n for default in defaults_to_add:\n \n add_callable( default )\n \n \n \n \n self._listctrl.Sort()\n \n \n def _Duplicate( self ):\n \n dupe_data = self._GetExportObject()\n \n if dupe_data is not None:\n \n dupe_data = dupe_data.Duplicate()\n \n self._ImportObject( dupe_data )\n \n \n self._listctrl.Sort()\n \n \n def _ExportToClipboard( self ):\n \n export_object = self._GetExportObject()\n \n if export_object is not None:\n \n json = export_object.DumpToString()\n \n HG.client_controller.pub( 'clipboard', 'text', json )\n \n \n \n def _ExportToJSON( self ):\n \n export_object = self._GetExportObject()\n \n if export_object is not None:\n \n json = export_object.DumpToString()\n \n with QP.FileDialog( self, 'select where to save the json file', default_filename = 'export.json', wildcard = 'JSON (*.json)', acceptMode = QW.QFileDialog.AcceptSave, fileMode = QW.QFileDialog.AnyFile ) as f_dlg:\n \n if f_dlg.exec() == QW.QDialog.Accepted:\n \n path = f_dlg.GetPath()\n \n if os.path.exists( path ):\n \n from hydrus.client.gui import ClientGUIDialogsQuick\n \n message = 'The path \"{}\" already exists! Ok to overwrite?'.format( path )\n \n result = ClientGUIDialogsQuick.GetYesNo( self, message )\n \n if result != QW.QDialog.Accepted:\n \n return\n \n \n \n with open( path, 'w', encoding = 'utf-8' ) as f:\n \n f.write( json )\n \n \n \n \n \n \n def _ExportToPNG( self ):\n \n export_object = self._GetExportObject()\n \n if export_object is not None:\n \n from hydrus.client.gui import ClientGUITopLevelWindowsPanels\n from hydrus.client.gui import ClientGUISerialisable\n \n with ClientGUITopLevelWindowsPanels.DialogNullipotent( self, 'export to png' ) as dlg:\n \n panel = ClientGUISerialisable.PNGExportPanel( dlg, export_object )\n \n dlg.SetPanel( panel )\n \n dlg.exec()\n \n \n \n \n def _ExportToPNGs( self ):\n \n export_object = self._GetExportObject()\n \n if export_object is None:\n \n return\n \n \n if not isinstance( export_object, HydrusSerialisable.SerialisableList ):\n \n self._ExportToPNG()\n \n return\n \n \n from hydrus.client.gui import ClientGUITopLevelWindowsPanels\n from hydrus.client.gui import ClientGUISerialisable\n \n with ClientGUITopLevelWindowsPanels.DialogNullipotent( self, 'export to pngs' ) as dlg:\n \n panel = ClientGUISerialisable.PNGsExportPanel( dlg, export_object )\n \n dlg.SetPanel( panel )\n \n dlg.exec()\n \n \n \n def _GetExportObject( self ):\n \n if self._custom_get_callable is None:\n \n to_export = HydrusSerialisable.SerialisableList()\n \n for obj in self._listctrl.GetData( only_selected = True ):\n \n to_export.append( obj )\n \n \n else:\n \n to_export = [ self._custom_get_callable() ]\n \n \n if len( to_export ) == 0:\n \n return None\n \n elif len( to_export ) == 1:\n \n return to_export[0]\n \n else:\n \n return to_export\n \n \n \n def _HasSelected( self ):\n \n return self._listctrl.HasSelected()\n \n \n def _HasOneSelected( self ):\n \n return self._listctrl.HasOneSelected()\n \n \n def _ImportFromClipboard( self ):\n \n try:\n \n raw_text = HG.client_controller.GetClipboardText()\n \n except HydrusExceptions.DataMissing as e:\n \n QW.QMessageBox.critical( self, 'Error', str(e) )\n \n return\n \n \n try:\n \n obj = HydrusSerialisable.CreateFromString( raw_text )\n \n self._ImportObject( obj )\n \n except Exception as e:\n \n QW.QMessageBox.critical( self, 'Error', 'I could not understand what was in the clipboard' )\n \n \n self._listctrl.Sort()\n \n \n def _ImportFromJSON( self ):\n \n with QP.FileDialog( self, 'select the json or jsons with the serialised data', acceptMode = QW.QFileDialog.AcceptOpen, fileMode = QW.QFileDialog.ExistingFiles, wildcard = 'JSON (*.json)|*.json' ) as dlg:\n \n if dlg.exec() == QW.QDialog.Accepted:\n \n paths = dlg.GetPaths()\n \n self._ImportJSONs( paths )\n \n \n \n self._listctrl.Sort()\n \n \n def _ImportFromPNG( self ):\n \n with QP.FileDialog( self, 'select the png or pngs with the encoded data', acceptMode = QW.QFileDialog.AcceptOpen, fileMode = QW.QFileDialog.ExistingFiles, wildcard = 'PNG (*.png)|*.png' ) as dlg:\n \n if dlg.exec() == QW.QDialog.Accepted:\n \n paths = dlg.GetPaths()\n \n self._ImportPNGs( paths )\n \n \n \n self._listctrl.Sort()\n \n \n def _ImportObject( self, obj ):\n \n bad_object_type_names = set()\n \n if isinstance( obj, HydrusSerialisable.SerialisableList ):\n \n for sub_obj in obj:\n \n self._ImportObject( sub_obj )\n \n \n else:\n \n if isinstance( obj, self._permitted_object_types ):\n \n self._import_add_callable( obj )\n \n else:\n \n bad_object_type_names.add( HydrusData.GetTypeName( type( obj ) ) )\n \n \n \n if len( bad_object_type_names ) > 0:\n \n message = 'The imported objects included these types:'\n message += os.linesep * 2\n message += os.linesep.join( bad_object_type_names )\n message += os.linesep * 2\n message += 'Whereas this control only allows:'\n message += os.linesep * 2\n message += os.linesep.join( ( HydrusData.GetTypeName( o ) for o in self._permitted_object_types ) )\n \n QW.QMessageBox.critical( self, 'Error', message )\n \n \n \n def _ImportJSONs( self, paths ):\n \n for path in paths:\n \n try:\n \n with open( path, 'r', encoding = 'utf-8' ) as f:\n \n payload = f.read()\n \n \n except Exception as e:\n \n QW.QMessageBox.critical( self, 'Error', str(e) )\n \n return\n \n \n try:\n \n obj = HydrusSerialisable.CreateFromString( payload )\n \n self._ImportObject( obj )\n \n except:\n \n QW.QMessageBox.critical( self, 'Error', 'I could not understand what was encoded in \"{}\"!'.format( path ) )\n \n return\n \n \n \n \n def _ImportPNGs( self, paths ):\n \n for path in paths:\n \n try:\n \n payload = ClientSerialisable.LoadFromPNG( path )\n \n except Exception as e:\n \n QW.QMessageBox.critical( self, 'Error', str(e) )\n \n return\n \n \n try:\n \n obj = HydrusSerialisable.CreateFromNetworkBytes( payload )\n \n self._ImportObject( obj )\n \n except:\n \n QW.QMessageBox.critical( self, 'Error', 'I could not understand what was encoded in \"{}\"!'.format( path ) )\n \n return\n \n \n \n \n def _UpdateButtons( self ):\n \n for ( button, enabled_check_func ) in self._button_infos:\n \n if enabled_check_func():\n \n button.setEnabled( True )\n \n else:\n \n button.setEnabled( False )\n \n \n \n \n def AddBitmapButton( self, bitmap, clicked_func, tooltip = None, enabled_only_on_selection = False, enabled_only_on_single_selection = False, enabled_check_func = None ):\n \n button = ClientGUICommon.BetterBitmapButton( self, bitmap, clicked_func )\n \n if tooltip is not None:\n \n button.setToolTip( tooltip )\n \n \n self._AddButton( button, enabled_only_on_selection = enabled_only_on_selection, enabled_only_on_single_selection = enabled_only_on_single_selection, enabled_check_func = enabled_check_func )\n \n self._UpdateButtons()\n \n \n def AddButton( self, label, clicked_func, enabled_only_on_selection = False, enabled_only_on_single_selection = False, enabled_check_func = None ):\n \n button = ClientGUICommon.BetterButton( self, label, clicked_func )\n \n self._AddButton( button, enabled_only_on_selection = enabled_only_on_selection, enabled_only_on_single_selection = enabled_only_on_single_selection, enabled_check_func = enabled_check_func )\n \n self._UpdateButtons()\n \n \n def AddDefaultsButton( self, defaults_callable, add_callable ):\n \n import_menu_items = []\n \n all_call = HydrusData.Call( self._AddAllDefaults, defaults_callable, add_callable )\n some_call = HydrusData.Call( self._AddSomeDefaults, defaults_callable, add_callable )\n \n import_menu_items.append( ( 'normal', 'add them all', 'Load all the defaults.', all_call ) )\n import_menu_items.append( ( 'normal', 'select from a list', 'Load some of the defaults.', some_call ) )\n \n self.AddMenuButton( 'add defaults', import_menu_items )\n \n \n def AddDeleteButton( self, enabled_check_func = None ):\n \n if enabled_check_func is None:\n \n enabled_only_on_selection = True\n \n else:\n \n enabled_only_on_selection = False\n \n \n self.AddButton( 'delete', self._listctrl.ProcessDeleteAction, enabled_check_func = enabled_check_func, enabled_only_on_selection = enabled_only_on_selection )\n \n \n def AddImportExportButtons( self, permitted_object_types, import_add_callable, custom_get_callable = None ):\n \n self._permitted_object_types = permitted_object_types\n self._import_add_callable = import_add_callable\n self._custom_get_callable = custom_get_callable\n \n export_menu_items = []\n \n export_menu_items.append( ( 'normal', 'to clipboard', 'Serialise the selected data and put it on your clipboard.', self._ExportToClipboard ) )\n export_menu_items.append( ( 'normal', 'to json file', 'Serialise the selected data and export to a json file.', self._ExportToJSON ) )\n export_menu_items.append( ( 'normal', 'to png file', 'Serialise the selected data and encode it to an image file you can easily share with other hydrus users.', self._ExportToPNG ) )\n \n if self._custom_get_callable is None:\n \n all_objs_are_named = False not in ( issubclass( o, HydrusSerialisable.SerialisableBaseNamed ) for o in self._permitted_object_types )\n \n if all_objs_are_named:\n \n export_menu_items.append( ( 'normal', 'to pngs', 'Serialise the selected data and encode it to multiple image files you can easily share with other hydrus users.', self._ExportToPNGs ) )\n \n \n \n import_menu_items = []\n \n import_menu_items.append( ( 'normal', 'from clipboard', 'Load a data from text in your clipboard.', self._ImportFromClipboard ) )\n import_menu_items.append( ( 'normal', 'from json files', 'Load a data from .json files.', self._ImportFromJSON ) )\n import_menu_items.append( ( 'normal', 'from png files (you can also drag and drop pngs onto this list)', 'Load a data from an encoded png.', self._ImportFromPNG ) )\n \n self.AddMenuButton( 'export', export_menu_items, enabled_only_on_selection = True )\n self.AddMenuButton( 'import', import_menu_items )\n self.AddButton( 'duplicate', self._Duplicate, enabled_only_on_selection = True )\n \n self.setAcceptDrops( True )\n self.installEventFilter( ClientGUIDragDrop.FileDropTarget( self, filenames_callable = self.ImportFromDragDrop ) )\n \n \n def AddMenuButton( self, label, menu_items, enabled_only_on_selection = False, enabled_check_func = None ):\n \n button = ClientGUICommon.MenuButton( self, label, menu_items )\n \n self._AddButton( button, enabled_only_on_selection = enabled_only_on_selection, enabled_check_func = enabled_check_func )\n \n self._UpdateButtons()\n \n \n def AddSeparator( self ):\n \n self._buttonbox.insertStretch( -1, 1 )\n \n \n def AddWindow( self, window ):\n \n QP.AddToLayout( self._buttonbox, window, CC.FLAGS_VCENTER )\n \n \n def EventContentChanged( self, parent, first, last ):\n \n if not self._listctrl:\n \n return\n \n \n self._UpdateButtons()\n \n \n def EventSelectionChanged( self ):\n \n if not self._listctrl:\n \n return\n \n \n self._UpdateButtons()\n \n \n def ImportFromDragDrop( self, paths ):\n \n from hydrus.client.gui import ClientGUIDialogsQuick\n \n message = 'Try to import the ' + HydrusData.ToHumanInt( len( paths ) ) + ' dropped files to this list? I am expecting json or png files.'\n \n result = ClientGUIDialogsQuick.GetYesNo( self, message )\n \n if result == QW.QDialog.Accepted:\n \n ( jsons, pngs ) = HydrusData.PartitionIteratorIntoLists( lambda path: path.endswith( '.png' ), paths )\n \n self._ImportPNGs( pngs )\n self._ImportJSONs( jsons )\n \n self._listctrl.Sort()\n \n \n \n def NewButtonRow( self ):\n \n self._buttonbox = QP.HBoxLayout()\n \n QP.AddToLayout( self._vbox, self._buttonbox, CC.FLAGS_BUTTON_SIZER )\n \n \n def SetListCtrl( self, listctrl ):\n \n self._listctrl = listctrl\n \n QP.AddToLayout( self._vbox, self._listctrl, CC.FLAGS_EXPAND_SIZER_BOTH_WAYS )\n QP.AddToLayout( self._vbox, self._buttonbox, CC.FLAGS_BUTTON_SIZER )\n \n self.setLayout( self._vbox )\n \n self._listctrl.itemSelectionChanged.connect( self.EventSelectionChanged )\n \n self._listctrl.model().rowsInserted.connect( self.EventContentChanged )\n self._listctrl.model().rowsRemoved.connect( self.EventContentChanged )\n \n \n def UpdateButtons( self ):\n \n self._UpdateButtons()\n \n","sub_path":"hydrus/client/gui/ClientGUIListCtrl.py","file_name":"ClientGUIListCtrl.py","file_ext":"py","file_size_in_byte":37552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"653993664","text":"from __future__ import print_function\nfrom __future__ import division\nimport os\nimport pickle\nimport numpy as np\nfrom torch.utils.data import Dataset\n\nclass DataFeeder(Dataset):\n def __init__(self, data_path, box_num=None):\n self._pos_prefix = 'positive'\n self.data_path = data_path\n self.load_data(data_path)\n self.box_num = box_num\n \n def load_data(self, data_path):\n self.names = os.listdir(data_path)\n self.labels = [ int(name.startswith(self._pos_prefix)) \\\n for name in self.names]\n # self.N = len(self.names)\n # _,feat,_,_ = self.__getitem__(0)\n # self.C, self.T, self.V, self.M = feat.shape\n\n def __len__(self):\n return len(self.names)\n\n\n def __getitem__(self, index):\n path = os.path.join(self.data_path, self.names[index])\n data = np.load(path, allow_pickle=True, encoding='bytes')\n num_obj, det, feat, ffeat = data['num_obj'],data['det'],data['feat'],data['ffeat']\n # det, feat, ffeat = data[0],data[1],data[2]\n label = self.labels[index]\n return self.names[index], num_obj, det, feat, ffeat, label\n # return det, feat, ffeat, label\n\n\nif __name__ == \"__main__\":\n dataset = DataFeeder('data/ef_proposal_0113/training')\n N = 20\n for name, num_obj, det, feat, ffeat, label in dataset:\n conf = det[:,:,4]\n idx = np.argsort(conf, axis=-1)\n idx = idx[:,::-1]\n det = np.array([det[i][idx[i]] for i in range(len(det))])\n feat = np.array([feat[i][idx[i]] for i in range(len(feat))])\n conf = det[:,:,4]\n num_obj.fill(N)\n det = det[:,:N]\n feat = feat[:,:N]\n np.savez('data/ef_proposal_0113_20p/training/{}'.format(name), num_obj=num_obj,det=det, feat=feat, ffeat=ffeat)","sub_path":"predictor/lib/dataset/data_feeder.py","file_name":"data_feeder.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"518597027","text":"\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom numpy import *\nfrom scipy import *\nfrom pylab import *\n\n#2C----------------------------------------------------------------------------------------\n'''Set the control parameters (R, sigma, b)'''\n\nr=28.\ns=10.\nb=8./3.\n\n'''First things first, I need to define the coupled differential equations that I will \nbe investigating.'''\n\ndef xdot(x,y,z):\t\t\t\t\n return s*(-x+y)\n\ndef ydot(x,y,z):\n\treturn r*x-y-x*z\n\t\t\ndef zdot(x,y,z):\n\treturn -b*z+x*y\n\n'''Here, I set my initial conditions to (1,1,1). '''\n\nx=1.\ny=1.\nz=1.\ndt=0.01\nt=0.\nexes=[]\nwhys=[]\nzees=[]\nN=50000\ntrans=1000\n\n'''Here, I use an RK4 integrator that we perfected in PHYS 501 to generate my\ntrajectories. I then plot the trajectory on various axes and show them simultaneously.'''\n'''\nfor i in range(N):\n\tk1=dt*xdot(x,y,z)\n\tl1=dt*ydot(x,y,z)\n\tm1=dt*zdot(x,y,z)\n\tk2=dt*xdot(x+k1/2.,y+l1/2.,z+m1/2.)\n\tl2=dt*ydot(x+k1/2.,y+l1/2.,z+m1/2.)\n\tm2=dt*zdot(x+k1/2.,y+l1/2.,z+m1/2.)\n\tk3=dt*xdot(x+k2/2.,y+l2/2.,z+m2/2.)\n\tl3=dt*ydot(x+k2/2.,y+l2/2.,z+m2/2.)\n\tm3=dt*zdot(x+k2/2.,y+l2/2.,z+m2/2.)\n\tk4=dt*xdot(x+k3,y+l3,z+m3)\n\tl4=dt*ydot(x+k3,y+l3,z+m3)\n\tm4=dt*zdot(x+k3,y+l3,z+m3)\n\tx=x+(1./6.)*(k1+2.*k2+2.*k3+k4)\n\ty=y+(1./6.)*(l1+2.*l2+2.*l3+l4)\n\tz=z+(1./6.)*(m1+2.*m2+2.*m3+m4)\n\tif i>trans:\n\t\texes.append(x)\n\t\twhys.append(y)\n\t\tzees.append(z)\n\n'''\t\n'''\nfig = figure()\t\n\nax = fig.add_subplot(221, projection='3d')\nax.scatter(exes, whys, zees,s=0.0001)\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\nax.set_xticks([]) \nax.set_yticks([]) \nax.set_zticks([])\n\nax = fig.add_subplot(222)\nax.scatter(exes, whys,s=0.0001)\nxlabel('x')\nylabel('y')\nax.set_xticks([]) \nax.set_yticks([]) \n\nax = fig.add_subplot(223)\nax.scatter(exes, zees,s=0.0001)\nxlabel('x')\nylabel('z')\nax.set_xticks([]) \nax.set_yticks([]) \n\nax = fig.add_subplot(224)\nax.scatter(whys, zees,s=0.0001)\nxlabel('y')\nylabel('z')\nax.set_xticks([]) \nax.set_yticks([]) \nshow()\n'''\n#2E and F---------------------------------------------------------------------------------------\n\n'''Now to create the embedding, I need to loop through my x values and save them to a\nnew vector created from xi, xi+t, and xi+2t'''\n'''\nembedding=[]\nembeddingt=[]\nembedding2t=[]\ntau=25\t\n\nfor i in range(len(exes)-2*tau):\n\tembedding.append(exes[i])\n\tembeddingt.append(exes[i+tau])\n\tembedding2t.append(exes[i+2*tau])\n\t\nfig = figure()\t\n\nax = fig.add_subplot(111)\nax.scatter(embedding, embeddingt,s=0.0001)\nxlabel(r'$x_i$')\nylabel(r'$x_{i+\\tau}$')\nax.set_xticks([]) \nax.set_yticks([]) \n\nshow()\n'''\n'''Tau=10 has the \"nicest\" value because it looks the most like the original Lorenz\nattractor. As tau gets larger, the embedded plot begins to fold over onto itself,\nwhich is not a good sign. '''\n\n#3---------------------------------------------------------------------------------------\n'''For a two scale attractor, we need lambda1^d + lambda2^d = 1. We also know that d is\ngoing to be between 0 and 1 so we can iterate through until we get the right value of d!\nWhen d=0, we lambda1^d + lambda2^d=2, and when d=1, the sum is less than 1.\n'''\n\nalpha=2.502907875095892\nlambda1=1./alpha\nlambda2=1./(alpha**2)\nd=0.\nstep=0.0001\n\nfor i in range(N):\n\tif 1.-step 100 or movie_id > 50:\n # continue\n corpus.append((user_id, movie_id, rating))\n num_users = max(num_users, user_id + 1)\n num_movies = max(num_movies, movie_id + 1)\n\n corpus_data = np.array(corpus)\n np.random.shuffle(corpus_data)\n np.random.shuffle(corpus_data)\n N = np.shape(corpus_data)[0]\n Ndv = N // 20 * 17\n Ndv2 = N // 10 * 9\n train = corpus_data[:Ndv, :]\n valid = corpus_data[Ndv:Ndv2, :]\n test = corpus_data[Ndv2:, :]\n\n return num_movies, num_users, train, valid, test\n\n\ndef load_movielens1m_mapped(path):\n num_movies, num_users, train, valid, test = load_movielens1m(path)\n\n user_movie = []\n user_movie_score = []\n for i in range(num_users):\n user_movie.append([])\n user_movie_score.append([])\n movie_user = []\n movie_user_score = []\n for i in range(num_users):\n movie_user.append([])\n movie_user_score.append([])\n\n for i in range(np.shape(train)[0]):\n user_id = train[i, 0]\n movie_id = train[i, 1]\n rating = train[i, 2]\n user_movie[user_id].append(movie_id)\n user_movie_score[user_id].append(rating)\n movie_user[movie_id].append(user_id)\n movie_user_score[movie_id].append(rating)\n\n return num_movies, num_users, train, valid, test, \\\n user_movie, user_movie_score, movie_user, movie_user_score\n\n","sub_path":"Bayesian PMF/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"583689678","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom travelport.models.type_result_message_type_5 import TypeResultMessageType5\n\n__NAMESPACE__ = \"http://www.travelport.com/schema/common_v34_0\"\n\n\n@dataclass\nclass TypeResultMessage5:\n \"\"\"\n Used to identify the results of a requests.\n\n Parameters\n ----------\n value\n code\n type_value\n Indicates the type of message (Warning, Error, Info)\n \"\"\"\n class Meta:\n name = \"typeResultMessage\"\n\n value: str = field(\n default=\"\",\n metadata={\n \"required\": True,\n }\n )\n code: None | int = field(\n default=None,\n metadata={\n \"name\": \"Code\",\n \"type\": \"Attribute\",\n \"required\": True,\n }\n )\n type_value: None | TypeResultMessageType5 = field(\n default=None,\n metadata={\n \"name\": \"Type\",\n \"type\": \"Attribute\",\n }\n )\n","sub_path":"travelport/models/type_result_message_5.py","file_name":"type_result_message_5.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"283822681","text":"import os\nimport subprocess\nimport psutil\nname = \"java.exe\"\n\n\nls = []\nfor p in psutil.process_iter(attrs=[\"name\", \"exe\"]):\n if name == p.info['name'] or p.info['exe'] and os.path.basename(p.info['exe']) == name:\n ls.append(p)\n a=p.pid\n psutil.Process(a).kill()\n \n ","sub_path":"getpid.py","file_name":"getpid.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"398503307","text":"import numpy as np\nimport cv2\nimport scipy.ndimage as ndimage\nfrom matplotlib import pyplot as plt\n\nfrom visual_utils import *\nfrom post_proc_utils import *\n\ndir = '/home/andrea/Downloads/RoadNet/DeepSegmentor-master/results/roadnet/test_latest/images/'\n\n#img_code = '1-6-3' # straight\nimg_code = '1-9-8' # small curve\n#img_code = '1-1-8' # bad curve \n\n# load the images\nimage_bgr = cv2.imread(dir + img_code + '_image.png', cv2.IMREAD_COLOR)\nlabel_gt_bgr = cv2.imread(dir + img_code + '_label_gt.png', cv2.IMREAD_COLOR)\nlabel_pred_bgr = cv2.imread(dir + img_code + '_label_pred.png', cv2.IMREAD_COLOR)\n\n# Dilate label_gt to make it more visible\nthick_gt_bgr = thick(label_gt_bgr)\n\n# Create the mask\nkernel = np.ones((3,3), np.uint8)\nmask_bgr = cv2.dilate(label_gt_bgr, kernel, iterations=20, borderType=cv2.BORDER_REFLECT)\n\noverlaid_bgr = overlayImages([image_bgr, green(thick_gt_bgr), red(mask_bgr)],[1.0, 1.0, 0.4])\ncv2.imshow('image and mask overlay', overlaid_bgr)\n\n# Mask the predictions\nmasked_pred_bgr = cv2.bitwise_and(label_pred_bgr, label_pred_bgr, mask = mask_bgr[:,:,0])\ncv2.imshow('Masked Predictions', masked_pred_bgr)\ncv2.imshow('Original Predictions', label_pred_bgr)\n\ncv2.imwrite('/tmp/1_masked_preds.png', masked_pred_bgr)\ncv2.imwrite('/tmp/2_original_preds.png', label_pred_bgr)\n\n\n########################################################################################################################\n\n\n# Thresholding the masked_pred\nthreshold = 100\nmasked_pred_gray = cv2.cvtColor(masked_pred_bgr, cv2.COLOR_BGR2GRAY)\n_, binary_masked_pred_gray = cv2.threshold(masked_pred_gray, 40, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\noverlaid_bgr = overlayImages([red(mask_bgr), grayToBGR(binary_masked_pred_gray)], [0.4, 1.0])\ncv2.imshow('Binary Predictions', overlaid_bgr)\n\n\"\"\"\n# Fill holes applying the closing operator\nclosing_kernel = np.ones((9,9), np.uint8)\nclosing = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, closing_kernel)\ncv2.imshow('Closed inary Image', closing)\n\"\"\"\n\n# Find Contours of the thresholded masked_pred\n_, contours, hierarchy = cv2.findContours(binary_masked_pred_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\npred_contours_bgr = np.zeros_like(masked_pred_bgr)\nfor i in range(len(contours)):\n cv2.drawContours(pred_contours_bgr, contours, i, (0, 255, 0), 1, cv2.LINE_8, hierarchy, 0)\n\noverlaid_bgr = overlayImages([mask_bgr, masked_pred_bgr, pred_contours_bgr], [0.2, 1.0, 1.0])\ncv2.imshow('Edges of masked predictions', overlaid_bgr)\n\n\n# Find the edges thresholding the contours\nbinary_edges_gray = cv2.bitwise_not(pred_contours_bgr[:,:,1])\ncv2.imshow('Binary Edges', binary_edges_gray)\n\ncv2.imwrite('/tmp/3_binary_edges.png', binary_edges_gray)\n\n\n# Perform the distance transform algorithm\ndistance_transform_gray = cv2.distanceTransform(binary_edges_gray, cv2.DIST_L2, 3)\nnorm_distance_transform_gray = np.zeros_like(distance_transform_gray)\nnorm_distance_transform_gray = cv2.normalize(distance_transform_gray, norm_distance_transform_gray, 0, 1.0, cv2.NORM_MINMAX) # Normalize the distance image for range = {0.0, 1.0} so we can visualize and threshold it\ncv2.imshow('Distance Transform Image', norm_distance_transform_gray)\n\ncv2.imwrite('/tmp/4_distance_transform.png', norm_distance_transform_gray)\n\n\n# Keep the distance values only on the centerline\nmasked_norm_dist_gray = cv2.bitwise_and(norm_distance_transform_gray, norm_distance_transform_gray, mask=thick(label_gt_bgr,3)[:,:,0])\ncv2.imshow('/tmp/Distance transform on the centerline', masked_norm_dist_gray)\n\n\n# Plot the histogram of the distance in the centerline\nkernel = np.ones((3,3), np.uint8)\ncenterline_3px = cv2.dilate(label_gt_bgr, kernel, iterations=1, borderType=cv2.BORDER_REFLECT)\nmasked_dist = cv2.bitwise_and(distance_transform_gray, distance_transform_gray, mask=centerline_3px[:,:,-1])\n\nx = np.array([d for d in masked_dist.flatten() if d != 0])\nbins = 25\nbin_width = (x.max()-0.1)/bins\nplt.hist(x, bins=bins, range=(0.1, x.max()), rwidth=0.9*bin_width)\nticks = [0.1 + bin_width * i for i in range(bins)]\nplt.xticks(ticks=ticks, rotation=70)\nmean = np.mean(x)\nvar = np.std(x)\nplt.title(\"mean: \" + str(mean) + \" std: \" + str(var))\n#plt.show()\n\n\n########################################################################################################################\n\n\n# Find Road Instances from the gt centerline\n\n\n# Find where a road starts from the border of the image\nstart_points = findRoadStartingPoints(label_gt_bgr[:,:,-1])\ncv2.imshow(\"Starting points\", addCircles(red(thick_gt_bgr), start_points))\n\n\n# DFS algorithm to find all instances\ndiscovered_gray = DFS(label_gt_bgr[:,:,0], start_points)\n\n\n# Draw the road instances with different colors\nroad_instances_bgr = colorInstances(discovered_gray, np.unique(discovered_gray))\ncv2.imshow('Road Instances', road_instances_bgr)\n\n\ncv2.imwrite('/tmp/5_road_instances.png', road_instances_bgr)\n\n\nroad_instances_points = {}\nbaricenters = {}\nfor i in np.unique(discovered_gray):\n if i > 0:\n y = []\n x = []\n for row in range(discovered_gray.shape[0]):\n for col in range(discovered_gray.shape[1]):\n if discovered_gray[row,col] == i:\n y.append(row)\n x.append(col)\n y = np.array(y)\n x = np.array(x)\n road_instances_points[i] = np.stack([y, x])\n b = intBaricenter(road_instances_points[i])\n baricenters[i] = b\n\ncv2.imshow('Baricenters', addCircles(road_instances_bgr, list(baricenters.values())))\n\n\nb = baricenters[1]\n\ntranslation_region = [_ for _ in range(-20, 20)]\ncorrelations = []\nfor dy in translation_region:\n for dx in translation_region:\n M = np.float32([1, 0, dx, 0, 1, dy]).reshape((2,3))\n rows, cols, ch = road_instances_bgr.shape\n translated_gray = cv2.warpAffine((discovered_gray==1).astype(np.float32), M, (cols, rows))\n white_binary_edges_gray = cv2.bitwise_not(binary_edges_gray)\n corr = np.sum(np.multiply(translated_gray, white_binary_edges_gray))\n correlations.append((dy,dx,corr))\n\nres = np.array(correlations)\nprint(res[np.argmax(res[:,-1])])\n\n# Show the result\nres_ = res[np.argmax(res[:,-1])]\ndy = res_[0]\ndx = res_[1]\nM = np.float32([1, 0, dx, 0, 1, dy]).reshape((2,3))\nrows, cols, ch = road_instances_bgr.shape\ndst = cv2.warpAffine((discovered_gray==1).astype(np.float32), M, (cols, rows))\nbinary_edges_gray = dst.astype(np.uint8)*255\n\ncv2.imshow('Road Edges', overlayImages([image_bgr, grayToBGR(binary_edges_gray, 0, 0, 1)],[0.5, 1]))\n\n\n########################################################################################################################\n\n\n# Estimate the width for each road instance\nestimated_road_gray = np.zeros(label_gt_bgr.shape[:2], dtype=np.uint8)\nfor i in np.unique(discovered_gray):\n if i > 0:\n inst = np.zeros(label_gt_bgr.shape[:2], dtype=np.float32)\n inst[discovered_gray==i] = masked_dist[discovered_gray==i]\n\n x = np.array([d for d in inst.flatten() if d != 0])\n unique, counts = np.unique(x, return_counts=True)\n #estimated_width = unique[np.argmax(counts)]\n estimated_width = np.mean(x)\n print(estimated_width)\n\n temp = np.zeros(label_gt_bgr.shape[:2], dtype=np.uint8)\n temp[discovered_gray==i] = 255\n temp = cv2.dilate(temp, kernel, iterations=int(estimated_width), borderType=cv2.BORDER_REFLECT)\n\n estimated_road_gray = cv2.bitwise_or(estimated_road_gray, temp)\n\n# Overlap the estimated road on the image\noverlaid_bgr = overlayImages([image_bgr, thick_gt_bgr, grayToBGR(estimated_road_gray, 0, 0, 1)],[1.0, 1.0, 0.8])\ncv2.imshow('Road Estimation', overlaid_bgr)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"houston/post-proc/post_proc.py","file_name":"post_proc.py","file_ext":"py","file_size_in_byte":7686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"313682617","text":"#Author : Dhaval Harish Sharma\n#Red ID : 824654344\n#Assignment 3, Question A and B, Using user defined edge detection\n\"\"\"Finding the edges in an image using user defined edge detection and changing the colors \nof edges of different objects. After that, adding salt and pepper noise to the image, \nagain applying edge detection algorithm and then removing the noise using median filter.\"\"\"\n\n\n#Importing the required libraries\nimport skimage.io as io\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport colorsys\n\n#Initializing the input image\nin_img = io.imread(\"pepper.jpg\")\nheight = in_img.shape[0]\nwidth = in_img.shape[1]\n\n\n#Question A begins!\n#Defining the convolution function\ndef convolution(h, w, window, in_img, out_img):\n sum_of_elem = 0\n \n for i in range(3):\n for j in range(3):\n sum_of_elem = sum_of_elem + (np.average(in_img[h - 1 + i][w - 1 + j]) * window[i][j])\n \n out_img[h][w] = sum_of_elem\n \ndef sobel_edge_detection(in_img):\n grad_x = np.zeros(shape = (height, width), dtype = np.uint8)\n grad_y = np.zeros(shape = (height, width), dtype = np.uint8)\n magnitude = np.zeros(shape = (height, width), dtype = np.uint8)\n edge_img_1 = np.zeros(shape = (height, width, 3), dtype = np.uint8)\n \n #Output image with x gradient \n for i in range(1, height - 1):\n for j in range(1, width - 1):\n convolution(i, j, [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], in_img, grad_x)\n \n #Thresholding the image \n for i in range(height):\n for j in range(width):\n if grad_x[i][j] < 64:\n grad_x[i][j] = 255\n \n # Output image with y gradient\n for i in range(1, height - 1):\n for j in range(1, width - 1):\n convolution(i, j, [[-1, -2, -1], [0, 0, 0], [1, 2, 1]], in_img, grad_y)\n \n #Thresholding the image \n for i in range(height):\n for j in range(width):\n if grad_y[i][j] < 64:\n grad_y[i][j] = 255\n \n #Output image with magnitude\n for i in range(1, height - 1):\n for j in range(1, width - 1):\n magnitude[i][j] = math.sqrt((grad_x[i][j]) ** 2 + (grad_y[i][j]) ** 2)\n \n #Thresholding the image \n for i in range(height):\n for j in range(width):\n if magnitude[i][j] < 128:\n magnitude[i][j] = 0\n \n #Adding colors to the image\n edges = []\n \n for i in range(height):\n for j in range(width):\n if magnitude[i][j] != 0:\n edge_img_1[i][j] = in_img[i][j]\n edges.append(edge_img_1[i][j])\n \n #Finding the mean and standard deviation of all the rgb channels in the edges \n edges = np.array(edges)\n mean = np.mean(edges, axis = 0)\n std_dev = np.std(edges, axis = 0)\n \n #Changing the color of the found edges to the respective colors in the question\n for i in range(height):\n for j in range(width):\n if magnitude[i][j] != 0:\n if edge_img_1[i][j][0] > (mean[0] - std_dev[0]) and edge_img_1[i][j][1] < mean[1] and edge_img_1[i][j][2] < mean[2]:\n edge_img_1[i][j][0] = 0\n edge_img_1[i][j][1] = 255\n edge_img_1[i][j][2] = 0\n elif edge_img_1[i][j][1] > (mean[1] - std_dev[1]) and edge_img_1[i][j][0] < mean[0] and edge_img_1[i][j][2] < mean[2]:\n edge_img_1[i][j][0] = 0\n edge_img_1[i][j][1] = 0\n edge_img_1[i][j][2] = 255\n elif edge_img_1[i][j][2] > (mean[2] - std_dev[2]) and edge_img_1[i][j][0] < mean[0] and edge_img_1[i][j][1] < mean[1]:\n edge_img_1[i][j][0] = 255\n edge_img_1[i][j][1] = 0\n edge_img_1[i][j][2] = 0\n elif edge_img_1[i][j][0] > (mean[0] - std_dev[0]) and edge_img_1[i][j][1] > (mean[1] - std_dev[1]) and edge_img_1[i][j][2] < mean[2]:\n edge_img_1[i][j][0] = 0\n edge_img_1[i][j][1] = 255\n edge_img_1[i][j][2] = 255\n elif edge_img_1[i][j][0] < mean[0] and edge_img_1[i][j][1] > (mean[1] - std_dev[1]) and edge_img_1[i][j][2] > (mean[2] - std_dev[2]):\n edge_img_1[i][j][0] = 255\n edge_img_1[i][j][1] = 0\n edge_img_1[i][j][2] = 255\n elif edge_img_1[i][j][0] > (mean[0] - std_dev[0]) and edge_img_1[i][j][1] < mean[1] and edge_img_1[i][j][2] > (mean[2] - std_dev[2]):\n edge_img_1[i][j][0] = 255\n edge_img_1[i][j][1] = 255\n edge_img_1[i][j][2] = 0\n else:\n edge_img_1[i][j][0] = 255\n edge_img_1[i][j][1] = 255\n edge_img_1[i][j][2] = 255\n return edge_img_1\n\n#Finding edges using sobel_edge_detecton\nedge_img_1 = sobel_edge_detection(in_img)\n#Question A ends!\n\n\n#Question B begins!\n#Adding salt and pepper noise in the image\ndef salt_pepper(no_of_sp):\n for iteration in range(no_of_sp):\n x_coord = np.random.randint(0, height)\n y_coord = np.random.randint(0, width)\n s_p_img[x_coord][y_coord] = np.random.choice([0, 255])\n \ns_p_img = np.copy(in_img)\nno_of_sp = int(0.2 * height * width)\nsalt_pepper(no_of_sp)\n\n#Detecting the edges using canny edge detection\nedge_img_2 = sobel_edge_detection(s_p_img)\n\n#Initializing the output image and applying median filter to the image\nfilt_img = np.zeros(shape = (height, width, 3), dtype = np.uint8)\n\ndef med_filt(h, w):\n win_elem = []\n \n for i in range(5):\n for j in range(5):\n win_elem.append(s_p_img[h - 1 + i][w - 1 + j])\n \n win_elem.sort(key=lambda rgb: colorsys.rgb_to_hsv(*rgb))\n filt_img[h][w] = win_elem[12]\n\n#Loop for traversing through the input image \nfor i in range(3, height - 3):\n for j in range(3, width - 3):\n med_filt(i, j)\n#Question B ends!\n \n\n#Printing the output image\nfig, ax = plt.subplots(nrows = 2, ncols = 2)\nax[0][0].imshow(in_img)\nax[0][1].imshow(edge_img_1)\nax[1][0].imshow(s_p_img)\nax[1][1].imshow(edge_img_2, cmap = 'gray')\nplt.show()","sub_path":"Assignment 3/QuestionAB_Sobel.py","file_name":"QuestionAB_Sobel.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"57596132","text":"from trie import Trie\r\nfrom gameLogic import wordSearch, treasure, runGame\r\nfrom gameboardGraph import gameboardGraph\r\nfrom pynput.keyboard import Key, Controller\r\nimport random\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\n\r\ndef buildTrie():\r\n t = Trie()\r\n with open(\"words.txt\", \"r\") as f:\r\n\r\n for word in f.readlines():\r\n t.insert(word[:-1])\r\n\r\n return t\r\n\r\n\r\ndef convertwords():\r\n\r\n new = open(\"words.txt\", \"w+\")\r\n\r\n with open(\"usa2.txt\", \"r\") as f:\r\n for line in f.readlines():\r\n cap = line.upper()\r\n if cap[:-1].isalpha() and len(cap) > 4 and len(cap) < 9:\r\n new.write(cap)\r\n\r\n\r\ndef main():\r\n\r\n t = buildTrie()\r\n\r\n g = gameboardGraph()\r\n\r\n runGame(t, g)\r\n\r\n\r\n\r\n ''' This is in case of a character death\r\n while True:\r\n wordShuff = [\"R\", \"G\", \"T\", \"O\", \"I\", \"L\", \"Y\"]\r\n random.shuffle(wordShuff)\r\n word = ''.join(wordShuff[:7])\r\n if trie.search(word):\r\n print(word)'''\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342223253","text":"from odoo import api, fields, models\nfrom datetime import datetime\nimport calendar\n\n\nclass MonthlySummaryWizard(models.TransientModel):\n _name = \"monthly.summary.wizard\"\n\n @api.model\n def default_get(self, fields):\n res = super(MonthlySummaryWizard, self).default_get(fields)\n current_month = datetime.today().month\n current_year = datetime.now().year\n last_day_of_month = calendar.monthrange(current_year, current_month)[1]\n first_day = datetime(current_year, current_month, 1)\n last_day = datetime(current_year, current_month, last_day_of_month)\n res['period_start'] = first_day\n res['period_stop'] = last_day\n return res\n\n period_start = fields.Date(\"Period From\", required=True)\n period_stop = fields.Date(\"Period To\", required=True)\n\n @api.multi\n def print_report(self):\n data = {\n 'period_start': self.period_start,\n 'period_stop': self.period_stop,\n }\n return self.env.ref('monthly_summary_report.summary_report').report_action(self, data=data)","sub_path":"Medical_09122019/monthly_summary_report/wizard/wiz_summary_report.py","file_name":"wiz_summary_report.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"365092442","text":"# -*- coding:utf-8 -*-\n__author__ = 'shisanjun'\n\nimport os,sys\nBASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(BASE_DIR)\nfrom src.rpc_server import RpcServer\nfrom conf import settings\n\nif __name__ == \"__main__\":\n #queue_name为本地ip地址\n queue_name =settings.LOCAL_HOST\n server = RpcServer(queue_name)\n server.start()","sub_path":"RPC/bin/rpcserver/bin/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"383907243","text":"fi = open(\"05-23-2020.csv\",\"r\")\nfi.readline() # skip over first title line\ndatarows = fi.readlines()\nfi.close()\n\nfo = open(\"totalconfirmed.txt\",\"w\")\n\ntotal= 0\n\nfor line in datarows:\n templist = line.split(\",\")\n a= templist[7]\n a= int(a)\n total= total +(a)\n a= 0\n \nfo.write (str(total))\n \n \nfo.close()","sub_path":"findtotalconfirmed.py","file_name":"findtotalconfirmed.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"68443311","text":"# import module\r\nimport discord\r\nimport os\r\n\r\n# embed_message\r\ndef embed_message(embed_title, embed_url, embed_color, embed_icon, embed_message, embed_field_value):\r\n\tembed = discord.Embed(title=str(embed_title), url=str(embed_url), color=embed_color)\r\n\tembed.set_thumbnail(url=str(embed_icon))\r\n\tembed.add_field(name=str(embed_message), value=str(embed_field_value), inline=False)\r\n\treturn embed\r\n\r\n# 상수\r\nclient = discord.Client()\r\nconst_img_error = os.environ[\"IMG_ERROR\"]\r\nconst_img_naver = os.environ[\"IMG_NAVER\"]\r\nconst_img_google = os.environ[\"IMG_GOOGLE\"]\r\nconst_img_youtube = os.environ[\"IMG_YOUTUBE\"]\r\nconst_img_profile = os.environ[\"IMG_PROFILE\"]\r\nconst_hex_white = 0xffffff\r\nconst_hex_naver = 0x03cf5d\r\nconst_hex_error = 0xff0000\r\naccess_token = os.environ[\"BOT_TOKEN\"]\r\n\r\n# 명령어 목록\r\nlist_command = [\"help\", \"도움말\", \"검색\"]\r\n\r\n# 명령어 - 검색\r\nengine_naver = [\"네이버\", \"naver\", \"Naver\"]\r\nengine_google = [\"구글\", \"google\", \"Google\"]\r\nengine_youtube = [\"유튜브\", \"youtube\", \"Youtube\"]\r\nurl_naver = \"https://search.naver.com/search.naver?query=\"\r\nurl_google = \"https://www.google.com/search?q=\"\r\nurl_youtube = \"https://www.youtube.com/results?search_query=\"\r\n\r\n# 처음 시작시\r\n@client.event\r\nasync def on_ready():\r\n print(client.user.id)\r\n print(\"ready\")\r\n\r\n\r\n@client.event\r\nasync def on_message(message):\r\n\tif message.content.startswith(\">\"):\r\n\t\tif message.content.split(\" \")[0] == \">\": # 유저가 \">\"만 입력\r\n\t\t\tembed = discord.Embed(title=\"ERROR!\", description=\"명령어를 입력해 주세요!\", color=const_hex_error)\r\n\t\t\tembed.set_thumbnail(url=const_img_error)\r\n\t\t\tembed.add_field(name=\"<도움말>\", value=\"\\t혹시, 명령어를 모르시겠다면 '>help 혹은 >도움말'을 입력하여 명령어를 확인하세요!\", inline=True)\r\n\t\t\tawait message.channel.send(embed=embed)\r\n\t\t\t\r\n\t\telse:\r\n\t\t\tuser_txt = message.content[1:] # 명령어 내용 원본\r\n\t\t\tuser_txt_part = user_txt.split(\" \") # 명령어 split 한 것\r\n\t\t\r\n\t\tif user_txt_part[0] not in list_command: # 명령어가 잘못 되었을 때\r\n\t\t\tembed = discord.Embed(title=\"ERROR!\", description=\"잘못된 명령어를 입력하셨습니다.\", color=const_hex_error)\r\n\t\t\tembed.set_thumbnail(url=const_img_error)\r\n\t\t\tembed.add_field(name=\"<도움말>\", value=\"\\t혹시, 명령어를 모르시겠다면 '>help 혹은 >도움말'을 입력하여 명령어를 확인하세요!\", inline=True)\r\n\t\t\tawait message.channel.send(embed=embed)\r\n\t\t\t\r\n\t\telif user_txt_part[0] == \"검색\":\r\n\t\t\tif len(user_txt_part)==1 or user_txt_part[1]==\"\":\r\n\t\t\t\tembed = discord.Embed(title=\"ERROR!\", description=\"\\\"검색\\\" 명령어를 잘못된 형식으로 입력하셨습니다.\", color=const_hex_error)\r\n\t\t\t\tembed.set_thumbnail(url=const_img_error)\r\n\t\t\t\tembed.add_field(name=\"<도움말>\", value=\"\\t혹시, 명령어를 모르시겠다면 '>help 혹은 >도움말'을 입력하여 명령어를 확인하세요!\", inline=True)\r\n\t\t\t\tawait message.channel.send(embed=embed)\r\n\r\n\t\t\telse:\r\n\t\t\t\tif user_txt_part[1] in engine_naver: # 네이버 케이스\r\n\t\t\t\t\tsrc = \"\"\r\n\t\t\t\t\tfor i in user_txt_part[1:]:\r\n\t\t\t\t\t\tsrc = i + \" \"\r\n\t\t\t\t\tsrc = src[:len(src)-1]\r\n\t\t\t\t\tembed = embed_message(\"[검색결과]\", url_naver+src.replace(\" \",\"%20\"), const_hex_naver, const_img_naver, src+\"에 대한 네이버 검색결과입니다.\", url_naver+src)\r\n\t\t\t\t\tawait message.channel.send(embed=embed)\r\n\r\n\t\t\t\telif user_txt_part[1] in engine_google: # 구글 케이스\r\n\t\t\t\t\tsrc = \"\"\r\n\t\t\t\t\tfor i in user_txt_part[1:]:\r\n\t\t\t\t\t\tsrc = i + \" \"\r\n\t\t\t\t\tsrc = src[:len(src)-1]\r\n\t\t\t\t\tembed = embed_message(\"[검색결과]\", url_google+src.replace(\" \",\"%20\"), const_hex_white, const_img_google, src+\"에 대한 구글 검색결과입니다.\", url_google+src)\r\n\t\t\t\t\tawait message.channel.send(embed=embed)\r\n\r\n\t\t\t\telif user_txt_part[1] in engine_youtube: # 유튜브 케이스\r\n\t\t\t\t\tsrc = \"\"\r\n\t\t\t\t\tfor i in user_txt_part[1:]:\r\n\t\t\t\t\t\tsrc = i + \" \"\r\n\t\t\t\t\tsrc = src[:len(src)-1]\r\n\t\t\t\t\tembed = embed_message(\"[검색결과]\", url_youtube+src.replace(\" \",\"%20\"), const_hex_white, const_img_youtube, src+\"에 대한 유튜브 검색결과입니다.\", url_youtube+src)\r\n\t\t\t\t\tawait message.channel.send(embed=embed)\r\n\t\t\t\t\t\t\r\n\t\t\t\telif user_txt_part[1] not in (engine_naver + engine_google + engine_youtube):\r\n\t\t\t\t\tembed = discord.Embed(title=\"ERROR!\", description=\"지원하지 않는 검색 엔진입니다.\", color=const_hex_error)\r\n\t\t\t\t\tembed.set_thumbnail(url=const_img_error)\r\n\t\t\t\t\tembed.add_field(name=\"<지원 검색 엔진>\", value=\"\\t네이버, 구글, 유튜브\", inline=True)\r\n\t\t\t\t\tawait message.channel.send(embed=embed)\r\n\t\t\t\t\t\r\n\t\telif user_txt_part[0] in [\"help\", \"도움말\"]:\r\n\t\t\tembed = discord.Embed(title=\"[도움말]\", description=\"호구마봇의 도움말입니다.\", color=const_hex_white)\r\n\t\t\tembed.set_thumbnail(url=const_img_profile)\r\n\t\t\tembed.add_field(name=\">help : 호구마봇의 도움말을 표시합니다.\\n>도움말 : help와 같은 기능입니다.\\n>검색 : 웹사이트에서 검색합니다.\", value=\"\\t감사합니다 :D\", inline=True)\r\n\t\t\tawait message.channel.send(embed=embed)\r\n\t\t\t\t\r\n\t\t# else:\r\n\t\t\t\t\r\n\telse:\r\n\t\tif message.content == \"호구마 안녕!\":\r\n\t\t\tawait message.channel.send(\"그래 안녀어어어엉! :sweet_potato:\")\r\n\t\t\t\r\n\t\tif message.content == \"호구마!\":\r\n\t\t\tawait message.channel.send(\":sweetpotato:\")\r\n\t\t\t\r\n\t\tif message.content == \"뭐해?\":\r\n\t\t\tawait message.channel.send(\"야자하고 있어ㅠ\")\r\n\t\t\t\r\n\t\tif message.content == \"사진 보여줘!\":\r\n\t\t\tembed = discord.Embed()\r\n\t\t\tembed.set_image(url=const_img_profile)\r\n\t\t\tawait message.channel.send(embed=embed)\r\n\r\nclient.run(access_token)\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"343547726","text":"import gym\nimport numpy as np\n\nfrom numpy.random import random, choice\nimport matplotlib.pyplot as plt\n\ndef epsilon_greedy(state, Q, epsilon):\n\n actions_values = Q[state,:]\n greedy_action = np.argmax(actions_values)\n explore = (random() < epsilon)\n\n if explore:\n return choice([a for a in range(len(actions_values))])\n else:\n return greedy_action\n\nenv = gym.make(\"FrozenLake-v0\")\n\n# parameters for TD(lambda)\nepisodes = 10000\ngamma = 1.0\nalpha = 0.1\nepsilon = 0.1\neligibility_decay = 0.3\n\nn_states = env.observation_space.n\nn_actions = env.action_space.n\n\nQ = np.zeros((n_states, n_actions))\n\naverage_returns = []\n\nfor episode in range(episodes):\n\n state = env.reset()\n action = epsilon_greedy(state, Q, epsilon)\n\n R = [None]\n E = np.zeros((n_states, n_actions))\n\n while True:\n\n E = eligibility_decay * gamma * E\n E[state, action] += 1\n\n new_state, reward, done, info = env.step(action)\n new_action = epsilon_greedy(new_state, Q, epsilon)\n\n R.append(reward)\n\n delta = reward + gamma * Q[new_state, new_action] - Q[state, action]\n Q = Q + alpha * delta * E \n\n state, action = new_state, new_action\n\n if done:\n break\n\n T = len(R)\n G = np.zeros(T)\n\n # t = T-2, T-3, ..., 0\n t = T - 2\n\n while t >= 0:\n G[t] = R[t+1] + gamma * G[t+1]\n t = t - 1\n\n average_returns.append(np.mean(G))\n\nplt.plot(np.cumsum(average_returns),linewidth=2)\nplt.xlabel(\"Numer of episodes\")\nplt.ylabel(\"Cummulative mean reward over each episode\")\nplt.show()","sub_path":"sarsa_lambda.py","file_name":"sarsa_lambda.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"106101825","text":"\"\"\"\nCreated on Sat Nov 25 12:39:26 2017\n\n@author: yuliabarannikova\n\"\"\"\n\nfrom pymongo import MongoClient\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nplt.rcParams['figure.figsize'] = (10, 9)\n\n\nclient = MongoClient()\n\ndb = client.league_of_legends\n\nplaytraces_gt_27 = db.playtraces_gt_27\n\nactionTypes = playtraces_gt_27.distinct('playtrace.type')\ndf = pd.DataFrame(list(playtraces_gt_27.find()))\n\ndef get_period_range_list(end,n):\n period_range_list = []\n start = 0\n period_len = end/n\n for i in range(n):\n period_range_list.append((int(start), int(start+period_len)))\n start += period_len\n return period_range_list\n \n# create a df qith action counts for n periods\ndef divide(df,n):\n action_count_dict = {k:0 for k in [\"%s_count_%s\" % (a,p) for p in range(n) for a in actionTypes]}\n action_count_dict['id'] = ''\n new_df = pd.DataFrame(columns=action_count_dict.keys())\n for i in range(len(df)):\n row = df.iloc[i,:].copy()\n row_action_count_dict = action_count_dict.copy()\n if row['playtrace'] != []:\n last_action_time=row['playtrace'][-1]['timestamp']\n period_range_list = get_period_range_list(last_action_time,n)\n for action in row['playtrace']:\n for p in period_range_list:\n if action['timestamp'] in range(p[0],p[1]):\n t = period_range_list.index(p)\n k = \"%s_count_%s\" % (action['type'], t)\n row_action_count_dict[k] += 1\n row_action_count_dict['id']=row['id']\n new_df=new_df.append(row_action_count_dict, ignore_index=True)\n return new_df\n\n\nfrom sklearn.cluster import KMeans\ndf_4_periods = divide(df,4)\nX_4 = df_4_periods.iloc[:,:-1].values\nX_1 = df_1_period.iloc[:,:-1].values\nX_6 = df_6_periods.iloc[:,:-1].values\nX_10 = df_10_periods.iloc[:,:-1].values\nX_20 = df_20_periods.iloc[:,:-1].values\n\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=2)\nX_6_pca = pca.fit_transform(X_6)\nf1 = X_6_pca[:,0]\nf2 = X_6_pca[:,1]\nplt.scatter(f1,f2, s=1, c='black')\n\n\npca = PCA(n_components=2)\nX_4_pca = pca.fit_transform(X_4)\nvariance4=pca.explained_variance_ratio_\nf1 = X_4_pca[:,0]\nf2 = X_4_pca[:,1]\nplt.scatter(f1,f2, s=1, c='black')\n\npca = PCA()\nX_10_pca = pca.fit_transform(X_10)\nvariance10=pca.explained_variance_ratio_\nf1 = X_10_pca[:,0]\nf2 = X_10_pca[:,1]\nplt.scatter(f1,f2, s=1, c='black')\nplt.show()\n\ns=MinMaxScaler()\nX_10_scaled=s.fit_transform(X_10)\nX_10_pca_scaled = pca.fit_transform(X_10_scaled)\nvariance10_scaled=pca.explained_variance_ratio_\nf1 = X_10_pca_scaled[:,0]\nf2 = X_10_pca_scaled[:,1]\nplt.scatter(f1,f2, s=1, c='black')\nplt.show()\n\n\npca = PCA()\nX_20_pca = pca.fit_transform(X_20)\nvariance20=pca.explained_variance_ratio_\nf1 = X_20_pca[:,0]\nf2 = X_20_pca[:,1]\nplt.scatter(f1,f2, s=1, c='black')\nplt.show()\n\ns=MinMaxScaler()\nX_20_scaled=s.fit_transform(X_20)\nX_20_pca_scaled = pca.fit_transform(X_20_scaled)\nvariance10_scaled=pca.explained_variance_ratio_\nf1 = X_20_pca_scaled[:,0]\nf2 = X_20_pca_scaled[:,1]\nplt.scatter(f1,f2, s=1, c='black')\nplt.show()\n\n\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nsc = StandardScaler()\nX_20= sc.fit_transform(X_20)\n\ns = MinMaxScaler()\nX_4 = s.fit_transform(X_4)\n\ns=MinMaxScaler()\nX_10_scaled=s.fit_transform(X_10)\n\ns=MinMaxScaler()\nX_6=s.fit_transform(X_6)\n\n\ns=MinMaxScaler()\nX_20=s.fit_transform(X_20)\n\n\nkmeans = KMeans(n_clusters=2)\n# Fitting the input data\nkmeans.fit(X_6_pca)\n# Getting the cluster labels\nlabels = kmeans.predict(X_6_pca)\n# Centroid values\ncentroids = kmeans.cluster_centers_\n\nplt.scatter(f1, f2, c=labels, s=1, cmap='rainbow')\nplt.scatter(centroids[:, 0], centroids[:, 1], c='black', s=10)\n\nfrom scipy.spatial.distance import cdist\ndistortions=[]\nfor k in range(1,10):\n kmeans = KMeans(n_clusters=k)\n kmeans.fit(X_4_pca)\n distortions.append(sum(np.min(cdist(X_4_pca, kmeans.cluster_centers_, 'euclidean'), axis=1)) / X_4_pca.shape[0])\n\nplt.plot(range(1,10), distortions, 'bx-')\nplt.xlabel('k')\nplt.ylabel('Distortion')\nplt.title('The Elbow Method showing the optimal k')\nplt.show()\n\n","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"101098720","text":"tag_dictionary = {\n 'mixer': 'mixer',\n 'vs_unit': 'vsUnit',\n 'vs_track_no': 'vsTrackNo',\n 'mute': 'mute',\n 'solo': 'solo',\n 'master_track': 'masterTrack',\n 'time_signal': 'timeSig',\n 'pos_mes': 'posMes',\n 'numerator': 'nume',\n 'denominator': 'denomi',\n 'tempo': 'tempo',\n 'position_tick': 'posTick',\n 'bpm': 'bpm',\n 'vs_track': 'vsTrack',\n 'track_name': 'trackName',\n 'musical_part': 'musicalPart',\n 'play_time': 'playTime',\n 'note': 'note',\n 'duration_tick': 'durTick',\n 'note_number': 'noteNum',\n 'lyric': 'lyric',\n}\n","sub_path":"ccs/utils/v3/tag_dictionary.py","file_name":"tag_dictionary.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"198628811","text":"import os\nfrom flask import Flask\nfrom flask_restful import Api\nfrom reseauentreprise.init_models import db, ma\n\n\ndef create_app(config=None):\n \"\"\"\n App Factory\n :param config:\n :return:\n \"\"\"\n app = Flask(__name__)\n\n if config is None and 'PROJECT_SETTINGS' in os.environ:\n app.config.from_object(os.environ['PROJECT_SETTINGS'])\n else:\n app.config.from_object(config)\n\n api = Api(app)\n db.app = app\n db.init_app(app)\n\n load_resources(api)\n\n return app\n\n\ndef load_resources(flask_restful_api):\n \"\"\"\n Load blueprints.\n :param flask_restful_api:\n :return:\n \"\"\"\n from reseauentreprise.mod_tripod.resources import HelloWorld\n flask_restful_api.add_resource(HelloWorld, '/')\n","sub_path":"server/reseauentreprise/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"172614031","text":"high = 100\nlow = 0\nans = ''\nguess = (high + low)/2\n\nprint('Please think of a number between 0 and 100!')\n\nwhile ans != 'c':\n ans = input(\"Is your secret number \" + str(int(guess)) + \"?\\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. \")\n while str(ans) != 'c' and str(ans) != 'h' and str(ans) != 'l':\n ans = input(\"Sorry, I did not understand your input.\\nIs your secret number \" + str(int(guess)) + \"?\\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. \")\n if ans == 'h':\n high = int(guess)\n guess = (int(high) + int(low))/2\n elif ans == 'l':\n low = int(guess)\n guess = (int(high) + int(low))/2\n else:\n break\n\nprint('Game over. Your secret number was: ' + str(int(guess)))","sub_path":"2ndWeek-Exercise(GuessMyNumber).py","file_name":"2ndWeek-Exercise(GuessMyNumber).py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"516306389","text":"from sklearn.base import TransformerMixin\nimport pandas as pd\nfrom time import time\n\nclass StaticTransformer(TransformerMixin):\n \n def __init__(self, case_id_col, cat_cols, num_cols, fillna=True):\n self.case_id_col = case_id_col\n self.cat_cols = cat_cols\n self.num_cols = num_cols\n self.fillna = fillna\n \n self.columns = None\n \n self.fit_time = 0\n self.transform_time = 0\n \n \n def fit(self, X, y=None):\n return self\n \n \n def transform(self, X, y=None):\n start = time()\n \n dt_first = X.groupby(self.case_id_col).first()\n \n # transform numeric cols\n dt_transformed = dt_first[self.num_cols]\n \n # transform cat cols\n if len(self.cat_cols) > 0:\n dt_cat = pd.get_dummies(dt_first[self.cat_cols])\n dt_transformed = pd.concat([dt_transformed, dt_cat], axis=1)\n\n # fill NA with 0 if requested\n if self.fillna:\n dt_transformed = dt_transformed.fillna(0)\n \n # add missing columns if necessary\n if self.columns is not None:\n missing_cols = [col for col in self.columns if col not in dt_transformed.columns]\n for col in missing_cols:\n dt_transformed[col] = 0\n dt_transformed = dt_transformed[self.columns]\n else:\n self.columns = dt_transformed.columns\n \n self.transform_time = time() - start\n return dt_transformed","sub_path":"transformers/StaticTransformer.py","file_name":"StaticTransformer.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"127421418","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt \nimport numpy as np \nfrom matplotlib import style\nimport os\nimport pandas as pd\n\n#plt.switch_backend('agg')\n#print style.available \nplt.style.use('seaborn-paper')\nmpl.rcParams['xtick.direction'] = 'in'\nmpl.rcParams['ytick.direction'] = 'in'\nmpl.rcParams['xtick.major.size'] = 0\nmpl.rcParams['ytick.major.size'] = 0\nmpl.rcParams['mathtext.default'] = 'regular'\nfont = {'family': 'Times New Roman',\n 'style': 'italic',\n 'weight': 'normal',\n 'color': 'black', \n 'size': 18,\n }\n\n#os.chdir('/home/wktang/testfb/p3e5e5n1e4o3e2fb0.20kp10kc1e6')\n#Arguments\nImax = 499\nL = 1\nLmax = 3\nrs = 310 \ndrs = rs+L*(Imax+1)\ntlast = 4000\ntstep = 50\nttotal = (tlast-1000)*tstep\nt = np.linspace(0,ttotal,tlast-999)\np = np.loadtxt('Profile0.dat')\nc = abs(p[rs,1]/(p[rs,2]*p[rs,5]))\n#rmpmax = 9.9\n#ts = (rmpmax*1000+10000)/50\n\nww=[]\nphase=[]\nfor i in range(1000,tlast+1):\n A = np.loadtxt('xy'+str(i)+'.dat')\n ww.append(np.sqrt(np.sqrt(np.square(A[drs-1,4])+np.square(A[drs-1,5]))*c)*4)\n a = A[:,4]\n b = A[:,5]\n a = a.reshape(Imax+1,Lmax+1,order='F')\n b = b.reshape(Imax+1,Lmax+1,order='F')\n a = a+1j*b\n phase.append(np.angle(a[rs-1,1]))\n\nomega = np.ones(tlast-999)\nfor i in range(0,tlast-1000):\n if phase[i+1]-phase[i] < 4.5:\n omega[i] = (phase[i+1]-phase[i])/tstep\n else:\n omega[i] = (phase[i+1]-phase[i]-np.pi*2)/tstep\nomega[tlast-1000] = omega[tlast-1001]\n\ndf = pd.DataFrame(ww) \ndf.to_csv('width.csv') \ndf = pd.DataFrame(omega) \ndf.to_csv('omega.csv') \n\n#rmp = np.ones(tlast-999)\n#for i in range(0,tlast-999):\n# if i < 200:\n# rmp[i] = 0\n# elif 200 <= i <= ts:\n# rmp[i] = 1e-3*(i*50-10000)\n# else:\n# rmp[i] = rmpmax\n\nfig = plt.figure()\n#ax1 = fig.add_subplot(211)\nplt.plot(t,ww,'-',label='$w{_2}{_/}{_1}$')\nplt.grid(linestyle = '--')\n#ax2 = ax1.twinx()\n#ax2.plot(t,rmp,'-',label = 'RMP',color = '#ffaa00ff')\n#plt.semilogy(a[:,0],a[:,12],'-',label='$E{_3}{_/}{_2}$')\nplt.title('Island Width',fontdict = font)\n#plt.xlabel(r'$t/\\tau_a$',fontsize=13)\n#plt.xlim((0,1))\n#plt.xticks(np.linspace(-1, 1, 5))\nplt.ylabel('w/a',fontdict = font)\n#ax2.set_ylim([-0.8,10])\n#plt.xlabel(r'rmp($10^{-4}$)',fontdict = font)\n#plt.ylim((0,1))\n#plt.yticks([0, 0.5], ['$minimum$', 'normal'])\n#plt.autoscale(tight=True) \nplt.legend(loc='upper right')\n#ax2.legend(loc='upper right')\n#plt.subplot(212)\n#plt.plot(t,-omega,'r-',label=r'$\\omega{_2}{_/}{_1}$')\n#plt.semilogy(a[:,0],a[:,12],'-',label='$E{_3}{_/}{_2}$')\nplt.grid(linestyle = '--')\n#plt.title(r'$Mode$ $Frequence$',fontsize=14)\nplt.xlabel(r'$t/\\tau_a$',fontdict = font)\n#plt.xlim((0,1))\n#plt.xticks(np.linspace(-1, 1, 5))\n#plt.ylabel(r'$\\omega$',fontdict = font)\n#plt.ylim((0,1))\n#plt.yticks([0, 0.5], ['$minimum$', 'normal'])\n#plt.autoscale(tight=True) \n#plt.legend(loc='upper left')\n\n#plt.savefig(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\hehe.png\")\nplt.savefig(\"3.png\")\n# plt.show()\n","sub_path":"python/width.py","file_name":"width.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"459843323","text":"import unittest\n\nfrom .test_get_course_data import get_course_data_fake\nfrom timeedit_lnu_api.internals import parse_course_data\n\n\nclass TestParseCourseData(unittest.TestCase):\n def test_parse_course_data_with_working_data(self):\n raw_data = get_course_data_fake('229781')\n data = parse_course_data(raw_data)\n self.assertTrue(data is not None)\n\n def test_parse_course_data_with_working_data_check_return_type(self):\n raw_data = get_course_data_fake('229781')\n data = parse_course_data(raw_data)\n self.assertTrue(isinstance(data, dict))\n\n def test_parse_course_data_match_with_predefined_dict(self):\n d = {'course_code': '0KT002',\n 'course_id': 229781,\n 'course_language': 'Svenska',\n 'course_location': 'Växjö',\n 'course_points': '7,5 hp',\n 'course_reg': '69225',\n 'course_speed': '50%',\n 'name_en': 'Chemistry, preparatory Course 2',\n 'name_sv': 'Kemi Bas 2',\n 'semester': 'VT16',\n 'syllabus_en': 'http://api.kursinfo.lnu.se/GenerateDocument.ashx?templatetype=coursesyllabus&code=0KT002&documenttype=pdf&lang=en',\n 'syllabus_sv': 'http://api.kursinfo.lnu.se/GenerateDocument.ashx?templatetype=coursesyllabus&code=0KT002&documenttype=pdf&lang=sv',\n 'url': 'https://lnu.se/kurs/0KT002'}\n raw_data = get_course_data_fake('229781')\n data = parse_course_data(raw_data)\n self.assertTrue(data == d)\n\n def test_parse_course_data_with_bad_data(self):\n data = parse_course_data({'some': 'bad data'})\n self.assertTrue(data is None)\n\n def test_parse_course_data_with_bad_data_1(self):\n data = parse_course_data(None)\n self.assertTrue(data is None)\n","sub_path":"tests/test_parse_course_data.py","file_name":"test_parse_course_data.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"344613218","text":"class Solution:\n def findJudge(self, N: int, trust: List[List[int]]) -> int:\n if N == 1:\n return 1\n elif not trust:\n return -1\n elif len(trust) == 1:\n return trust[0][1]\n \n trust_mapping = collections.defaultdict(set)\n for t in trust:\n trust_mapping[t[0]].add(t[1])\n \n judge = 1\n for i in range(1, N + 1):\n if judge not in trust_mapping[i]:\n judge = i\n \n for i in range(1, N + 1):\n if i != judge and judge not in trust_mapping[i] or i in trust_mapping[judge]:\n print(judge, i)\n return -1\n \n return judge\n","sub_path":"Python/997FindtheTownJudge.py","file_name":"997FindtheTownJudge.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"472719104","text":"from progressivis.core.utils import indices_len, last_row, fix_loc\nfrom progressivis.core.dataframe import DataFrameModule\nfrom progressivis.core.slot import SlotDescriptor\nfrom progressivis.core.synchronized import synchronized\n\nimport numpy as np\nimport pandas as pd\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass IdxMax(DataFrameModule):\n parameters = [('history', np.dtype(int), 3)]\n\n def __init__(self, **kwds):\n self._add_slots(kwds,'input_descriptors',\n [SlotDescriptor('df', type=pd.DataFrame, required=True)])\n self._add_slots(kwds,'output_descriptors',\n [SlotDescriptor('max', type=pd.DataFrame, required=False)])\n super(IdxMax, self).__init__(**kwds)\n self._max = None\n self.default_step_size = 10000\n\n def max(self):\n return self._max\n\n def get_data(self, name):\n if name=='max':\n return self.max()\n return super(IdxMax,self).get_data(name)\n\n def is_ready(self):\n if self.get_input_slot('df').has_created():\n return True\n return super(IdxMax, self).is_ready()\n\n @synchronized\n def run_step(self,run_number,step_size,howlong):\n dfslot = self.get_input_slot('df')\n dfslot.update(run_number)\n if dfslot.has_updated() or dfslot.has_deleted(): \n dfslot.reset()\n self._df = None\n dfslot.update(run_number)\n indices = dfslot.next_created(step_size) # returns a slice\n steps = indices_len(indices)\n if steps==0:\n return self._return_run_step(self.state_blocked, steps_run=0)\n input_df = dfslot.data()\n op = self.filter_columns(input_df, fix_loc(indices)).idxmax()\n\n op[self.UPDATE_COLUMN] = run_number\n if self._max is None:\n max = pd.Series([np.nan], index=op.index) # the UPDATE_COLUMN is included\n max[self.UPDATE_COLUMN] = run_number\n for col in op.index:\n if col==self.UPDATE_COLUMN: continue\n max[col] = input_df.loc[op[col], col] # lookup value, is there a better way?\n self._max = pd.DataFrame([max], columns=op.index)\n self._df = pd.DataFrame([op], columns=op.index)\n else:\n prev_max = last_row(self._max)\n prev_idx = last_row(self._df)\n max = pd.Series(prev_max)\n max[self.UPDATE_COLUMN] = run_number\n for col in op.index:\n if col==self.UPDATE_COLUMN: continue\n val = input_df.loc[op[col], col]\n if np.isnan(val):\n pass\n elif np.isnan(max[col]) or val > max[col]:\n op[col] = prev_idx[col]\n max[col] = val\n op[self.UPDATE_COLUMN] = run_number\n with self.lock:\n self._df = self._df.append(op, ignore_index=True)\n self._max = self._max.append(max, ignore_index=True)\n if len(self._df) > self.params.history:\n self._df = self._df.loc[self._df.index[-self.params.history:]]\n self._max = self._max.loc[self._max.index[-self.params.history:]]\n\n return self._return_run_step(dfslot.next_state(), steps_run=steps)\n","sub_path":"progressivis/stats/idxmax.py","file_name":"idxmax.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"235781629","text":"import os\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\n\n\nclass CarvanaDataset(Dataset):\n def __init__(self, image_dir=None, mask_dir=None, transform=None):\n self.image_dir = image_dir\n self.mask_dir = mask_dir\n self.transform = transform\n\n self.images = np.array(os.listdir(self.image_dir))\n self.masks = np.array(os.listdir(self.mask_dir))\n\n sort_index = np.argsort(self.images)\n self.images = self.images[sort_index]\n self.masks = self.masks[sort_index]\n\n def __len__(self):\n return len(self.images)\n\n def __getitem__(self, index):\n img_path = os.path.join(self.image_dir, self.images[index])\n mask_path = os.path.join(self.mask_dir, self.masks[index])\n\n image = np.asarray(Image.open(img_path).convert(\"RGB\"))\n mask = np.asarray(Image.open(mask_path).convert(\"L\"), dtype=np.float32)\n mask[mask == 255.0] = 1.0\n\n if self.transform is not None:\n augmentations = self.transform(image=image, mask=mask)\n image = augmentations[\"image\"]\n mask = augmentations[\"mask\"]\n\n return image, mask\n\n\ndef make_dataloaders(\n batch_size=32, n_workers=4, pin_memory=False, shuffle=True, **kwargs\n): # A handy function to make our dataloaders\n dataset = CarvanaDataset(**kwargs)\n\n dataloader = DataLoader(\n dataset,\n batch_size=batch_size,\n num_workers=n_workers,\n pin_memory=pin_memory,\n shuffle=shuffle,\n )\n return dataloader\n\n","sub_path":"Unet-implementation/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"1619947","text":"from django.contrib import messages\nfrom django.shortcuts import redirect, render\nfrom django.urls import reverse\n\nfrom comments.forms import CommentForm\n\n\ndef process_post_add_comment(request, context,\n datapackage, force_anonymous_user,\n success_view_name,\n failure_template_name):\n if force_anonymous_user:\n logged_user = None\n else:\n logged_user = request.user\n\n comment_form = CommentForm(request.POST, datapackage_id=datapackage.id, logged_user=logged_user, allow_private=True)\n\n if comment_form.is_valid():\n comment_form.save()\n messages.success(request, 'Comment saved')\n return redirect(reverse(success_view_name, kwargs={'uuid': datapackage.uuid}))\n\n else:\n messages.error(request, 'Error saving the comment. Check below for the error messages')\n context['comment_form'] = comment_form\n context['datapackage'] = datapackage\n\n return render(request, failure_template_name, context)\n","sub_path":"SchemaCollaboration/comments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"165668971","text":"import gym\nfrom torch_rl.utils import *\n\nfrom torch_rl.models import SimpleNetwork\nfrom torch_rl.envs import NormalisedActionsWrapper, NormalisedObservationsWrapper\nfrom torch_rl.memory import SequentialMemory, HindsightMemory\nfrom torch_rl.training import DDPGTrainer\nfrom torch_rl.envs import SparseRewardGoalEnv\nfrom torch_rl.stats import RLTrainingStats\nimport datetime\nimport argparse\nimport numpy as np\n\"\"\"\n Implementation of deep deterministic policy gradients with soft updates.\n\n\"\"\"\n\n# Training parameters\nnum_episodes = 2000\nbatch_size = 8*8 + 8\ntau = 0.001\nepsilon = 1.0\ndepsilon = 1. / 50000\ngamma = 0.99\nreplay_capacity = 1000000\nwarmup = 2000\nmax_episode_length = 500\nactor_learning_rate = 1e-4\ncritic_learning_rate = 1e-3\nmiddle_layer_size = [400, 300]\nweight_init_sigma = 0.003\n\n\nif __name__ == '__main__':\n\n\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('--hindsight', \"-hi\", action=\"store_true\", default=False,\n help='Use hindsight replay buffer.')\n parser.add_argument('--epsilon', \"-e\", default=1.0, type=float,\n help='Epsilon for exploration with linear decay.')\n parser.add_argument('--depsilon', \"-de\", default=5000., type=float,\n help='Slope of linear decay of epsilon per step.')\n parser.add_argument('--gamma', \"-g\", default=.99, type=float,\n help='Reward discount factor')\n parser.add_argument('--batch', \"-bs\", default=16*4+16, type=int,\n help='Batch size, in case of hindsight replay has to be equal to hindsight_size*transitions + transitions')\n parser.add_argument('--replay_capacity', \"-rc\", default=1000000, type=int,\n help=\"Capacity of the replay buffer.\")\n parser.add_argument('--max_episode_length', \"-mel\", default=500, type=int,\n help='Max number of steps per episode')\n parser.add_argument('--actor_learning_rate', \"-aler\", default=1e-4, type=float,\n help='Learning rate of actor.')\n parser.add_argument('--critic_learning_rate', \"-cler\", default=1e-3, type=float,\n help='Learning rate of critic.')\n parser.add_argument('--warmup', \"-w\", default=2000, type=int,\n help='Number of steps to use for warmup.')\n parser.add_argument('--wsigma', \"-ws\", default=1e-3, type=float,\n help='Sigma to use for weight initialization Gauss distribution.')\n parser.add_argument('--tau', \"-t\", default=1e-3, type=float,\n help='Tau for soft updates of target actor and critic.')\n parser.add_argument('--hindsight_size', \"-hs\", default=4, type=int,\n help='Size of hindsight per transition.')\n parser.add_argument('--config', \"-c\", default=None, type=str,\n help='Path to config file for the training.')\n p = Parameters.from_args(parser.parse_args())\n\n hindsight = p.hindsight\n suff = \"_her\" if hindsight else \"\"\n\n goal_indices = np.asarray([0,1])\n\n replay_memory = HindsightMemory(limit=p.replay_capacity, window_length=1, hindsight_size=p.hindsight_size,\n goal_indices=goal_indices) if hindsight else SequentialMemory(p.replay_capacity, window_length=1)\n\n env = SparseRewardGoalEnv(NormalisedObservationsWrapper(\n NormalisedActionsWrapper(gym.make(\"Pendulum-v0\"))), precision=1e-1, indices=goal_indices)\n\n env.reset()\n num_actions = env.action_space.shape[0]\n num_observations = env.observation_space.shape[0]+2\n relu, tanh = tor.nn.ReLU(), tor.nn.Tanh()\n\n actor = cuda_if_available(SimpleNetwork([num_observations, middle_layer_size[0], middle_layer_size[1], num_actions],\n activation_functions=[relu, relu, tanh]))\n\n critic = cuda_if_available(\n SimpleNetwork([num_observations + num_actions, middle_layer_size[0], middle_layer_size[1], 1],\n activation_functions=[relu, relu]))\n\n actor.apply(gauss_init(0, p.wsigma))\n critic.apply(gauss_init(0, p.wsigma))\n\n # Training\n trainer = DDPGTrainer(env=env, actor=actor, critic=critic,\n tau=p.tau, epsilon=p.epsilon, batch_size=p.batch, depsilon=p.epsilon, gamma=p.gamma,\n lr_actor=p.actor_learning_rate, lr_critic=p.critic_learning_rate, warmup=p.warmup, replay_memory=replay_memory\n )\n\n output_dir = \"/disk/no_backup/vlasteli/Projects/torch_rl/examples/ddpg\"+ suff + \"_\" + str(datetime.datetime.now()).replace(\" \", \"_\")\n\n stats = RLTrainingStats(save_destination=output_dir)\n p.to_json(os.path.join(output_dir, \"config.json\"))\n\n trainer.train(8000, max_episode_len=p.max_episode_length, verbose=True, callbacks=[stats])\n\n\n","sub_path":"examples/ddpg_her.py","file_name":"ddpg_her.py","file_ext":"py","file_size_in_byte":4853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"647281477","text":"'''\n15. 3Sum\n\nGiven an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.\n\nNote: The solution set must not contain duplicate triplets.\n\nFor example, given array S = [-1, 0, 1, 2, -1, -4],\n\nA solution set is:\n[\n [-1, 0, 1],\n [-1, -1, 2]\n]\n'''\nclass Solution(object):\n def threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n nums.sort()\n print(nums)\n pairs = set()\n for k in range(len(nums)):\n i, j = 0, k - 1\n while i < j:\n print(nums[i] , nums[j] , nums[k])\n if nums[i] + nums[j] + nums[k] == 0:\n pairs.add((nums[i], nums[j], nums[k]))\n i += 1\n elif nums[i] + nums[j] + nums[k] < 0:\n i += 1\n else:\n j -= 1\n pairs = [list(p) for p in pairs]\n return pairs\n\nif __name__ == \"__main__\":\n s = [-1, 0, 1, 2, -1, -4]\n res = Solution().threeSum(s)\n print(res)\n","sub_path":"15_threeSum.py","file_name":"15_threeSum.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"309793848","text":"# MIT License\n#\n# Copyright (c) 2021 EASE lab\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport grpc\nimport argparse\nimport boto3\nimport logging as log\nimport socket\n\nimport sklearn.datasets as datasets\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.svm import LinearSVR\nfrom sklearn.linear_model import LinearRegression, Lasso\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import roc_auc_score\nimport numpy as np\nimport pickle\n\n# adding python tracing sources to the system path\nsys.path.insert(0, os.getcwd() + '/../proto/')\nsys.path.insert(0, os.getcwd() + '/../../../../utils/tracing/python')\nimport tracing\nimport stacking_pb2_grpc\nimport stacking_pb2\nimport destination as XDTdst\nimport source as XDTsrc\nimport utils as XDTutil\n\n\n\nfrom concurrent import futures\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-dockerCompose\", \"--dockerCompose\", dest=\"dockerCompose\", default=False, help=\"Env docker compose\")\nparser.add_argument(\"-sp\", \"--sp\", dest=\"sp\", default=\"80\", help=\"serve port\")\nparser.add_argument(\"-zipkin\", \"--zipkin\", dest=\"zipkinURL\",\n default=\"http://zipkin.istio-system.svc.cluster.local:9411/api/v2/spans\",\n help=\"Zipkin endpoint url\")\n\nargs = parser.parse_args()\n\nif tracing.IsTracingEnabled():\n tracing.initTracer(\"trainer\", url=args.zipkinURL)\n tracing.grpcInstrumentClient()\n tracing.grpcInstrumentServer()\n\nINLINE = \"INLINE\"\nS3 = \"S3\"\nXDT = \"XDT\"\n\n# set aws credentials:\nAWS_ID = os.getenv('AWS_ACCESS_KEY', \"\")\nAWS_SECRET = os.getenv('AWS_SECRET_KEY', \"\")\n\n\ndef get_self_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n # doesn't even have to be reachable\n s.connect(('10.255.255.255', 1))\n IP = s.getsockname()[0]\n except Exception:\n IP = '127.0.0.1'\n finally:\n s.close()\n return IP\n\n\ndef model_dispatcher(model_name):\n if model_name == 'LinearSVR':\n return LinearSVR\n elif model_name == 'Lasso':\n return Lasso\n elif model_name == 'LinearRegression':\n return LinearRegression\n elif model_name == 'RandomForestRegressor':\n return RandomForestRegressor\n elif model_name == 'KNeighborsRegressor':\n return KNeighborsRegressor\n elif model_name == 'LogisticRegression':\n return LogisticRegression\n else:\n raise ValueError(f\"Model {model_name} not found\")\n\n\nclass TrainerServicer(stacking_pb2_grpc.TrainerServicer):\n def __init__(self, transferType, XDTconfig=None):\n\n self.benchName = 'vhive-stacking'\n self.transferType = transferType\n self.trainer_id = \"\"\n if transferType == S3:\n self.s3_client = boto3.resource(\n service_name='s3',\n region_name=os.getenv(\"AWS_REGION\", 'us-west-1'),\n aws_access_key_id=AWS_ID,\n aws_secret_access_key=AWS_SECRET\n )\n elif transferType == XDT:\n if XDTconfig is None:\n log.fatal(\"Empty XDT config\")\n self.XDTconfig = XDTconfig\n\n def put(self, obj, key):\n msg = \"Driver uploading object with key '\" + key + \"' to \" + self.transferType\n log.info(msg)\n with tracing.Span(msg):\n pickled = pickle.dumps(obj)\n if self.transferType == S3:\n s3object = self.s3_client.Object(bucket_name=self.benchName, key=key)\n s3object.put(Body=pickled)\n elif self.transferType == XDT:\n log.fatal(\"XDT is not supported\")\n\n return key\n\n def get(self, key):\n msg = \"Driver gets key '\" + key + \"' from \" + self.transferType\n log.info(msg)\n with tracing.Span(msg):\n response = None\n if self.transferType == S3:\n obj = self.s3_client.Object(bucket_name=self.benchName, key=key)\n response = obj.get()\n elif self.transferType == XDT:\n log.fatal(\"XDT is not yet supported\")\n\n return pickle.loads(response['Body'].read())\n\n def Train(self, request, context):\n self.trainer_id = request.trainer_id\n log.info(f\"Trainer {self.trainer_id} is invoked\")\n\n dataset = self.get(request.dataset_key)\n\n with tracing.Span(\"Training a model\"):\n model_config = pickle.loads(request.model_config)\n\n # Init model\n model_class = model_dispatcher(model_config['model'])\n model = model_class(**model_config['params'])\n\n # Train model and get predictions\n y_pred = cross_val_predict(model, dataset['features'], dataset['labels'], cv=5)\n model.fit(dataset['features'], dataset['labels'])\n print(f\"{model_config['model']} score: {roc_auc_score(dataset['labels'], y_pred)}\")\n\n # Write to S3\n model_key = f\"model_{self.trainer_id}\"\n pred_key = f\"pred_model_{self.trainer_id}\"\n\n self.put(model, model_key)\n self.put(y_pred, pred_key)\n\n return stacking_pb2.TrainReply(\n model=b'',\n model_key=model_key,\n pred_key=pred_key\n )\n\n\ndef serve():\n transferType = os.getenv('TRANSFER_TYPE', S3)\n if transferType == S3:\n log.info(\"Using inline or s3 transfers\")\n max_workers = int(os.getenv(\"MAX_SERVER_THREADS\", 10))\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers))\n stacking_pb2_grpc.add_TrainerServicer_to_server(\n TrainerServicer(transferType=transferType), server)\n server.add_insecure_port('[::]:' + args.sp)\n server.start()\n server.wait_for_termination()\n elif transferType == XDT:\n log.fatal(\"XDT not yet supported\")\n XDTconfig = XDTutil.loadConfig()\n else:\n log.fatal(\"Invalid Transfer type\")\n\n\nif __name__ == '__main__':\n log.basicConfig(level=log.INFO)\n serve()\n","sub_path":"function-images/tests/stacking-training/trainer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"392696559","text":"import re\n\n\ndef process_row(row, conll_2003=False):\n # remove 'sk' prefix from wikiann datasets\n cleaned = re.sub(r'^sk:', '', row)\n splitted = cleaned.split()\n if len(splitted) <= 0:\n return\n text = re.sub(r'[^\\w\\s.,!?]', '', splitted[0])\n tag = splitted[1]\n if len(text) > 0:\n if conll_2003:\n return ' '.join([text, '.', 'O', tag])\n else:\n return ' '.join([text, tag])\n\n\ndef clean_wikiann(in_path, out_path):\n '''Clean raw wikiANN data and save in txt iob format'''\n with open(in_path) as in_f:\n with open(out_path, 'w') as out_f:\n content = in_f.read()\n for chunk in content.split('\\n\\n'):\n for row in chunk.split('\\n'):\n cleaned = process_row(row, conll_2003=True)\n if cleaned is not None:\n print(cleaned, file=out_f)\n print('', file=out_f)\n\n\ndef main():\n datasets = ['test', 'dev', 'train']\n for dataset in datasets:\n in_path = f'raw_data/{dataset}.txt'\n out_path = f'txt_iob_format/{dataset}_cleaned.txt'\n clean_wikiann(in_path, out_path)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"wikiann/clean_wikiann.py","file_name":"clean_wikiann.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"539536350","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom newsReptile.items import Article\nimport datetime\nfrom scrapy.selector import Selector\n\nclass HuxiuSpider(scrapy.Spider):\n name = 'huxiu'\n\n def __init__(self, *args, **kwargs):\n super(HuxiuSpider, self).__init__(*args, **kwargs)\n\n self.allowed_domains = ['huxiu.com']\n\n self.keywords = []\n for k, v in kwargs.items():\n if k.isdigit():\n self.keywords.append(v)\n\n # print('????????????????')\n # print(kwargs)\n # print('????????????????')\n\n baseUrl = 'https://www.huxiu.com/search.html?s='\n if len(self.keywords) > 0:\n baseUrl = baseUrl + self.keywords[0]\n for keyword in self.keywords[1:]:\n baseUrl = baseUrl + '%20' + keyword\n\n baseUrl = baseUrl + '&sort=dateline:desc'\n\n self.start_urls = [baseUrl,\n baseUrl + '&per_page=2',\n baseUrl + '&per_page=3']\n\n\n def parse(self, response):\n lists = response.xpath('//ul[@class=\"search-wrap-list-ul\"]//li').extract()\n article = Article()\n article['source'] = '虎嗅网'\n\n timed = datetime.timedelta(3)\n today = datetime.datetime.now()\n\n for li in lists:\n print('**************************************')\n newsTime = Selector(text=li).xpath('//span[@class=\"time\"]/text()').extract()[0]\n newsDatetime = datetime.datetime.strptime(newsTime, \"%Y-%m-%d %H:%M\")\n if today - newsDatetime <= timed:\n titleParts = Selector(text=li).xpath('//h2//text()').extract()\n title = ''\n for part in titleParts:\n title = title + part\n\n url = Selector(text=li).xpath('//h2/a/@href').extract()[0]\n\n article['title'] = title\n article['url'] = 'https://www.huxiu.com' + url\n article['date'] = newsTime\n article['keyword'] = ''\n article['text'] = ''\n\n yield article\n \n\n","sub_path":"backend/newsReptile/newsReptile/spiders/huxiu.py","file_name":"huxiu.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"545025951","text":"import asyncio\nimport types\n\nfrom botworx.run.policy import Policy\n\nclass Message:\n def __init__(self, txt):\n self.future = None\n self.txt = txt\n\nclass Agent(Policy):\n def __init__(self):\n super().__init__()\n self.loop = asyncio.get_event_loop()\n self.posts = []\n\n def run(self):\n #asyncio.run(coro, *, debug=False)\n #asyncio.run(self.main, debug=True)\n #asyncio.run(task, debug=True)\n self.loop.run_until_complete(self.main())\n #loop.run_forever()\n\n async def main(self):\n print(\"I'm an Agent\")\n\n\n async def process_posts(self):\n print('process')\n for post in self.posts:\n for rule in self.__class__.rules:\n print(rule)\n if(rule[0] == post.txt):\n self.loop.create_task(rule[1](self))\n\n '''\n future = post.future\n if future:\n future.set_result(None)\n '''\n def post(self, msg):\n self.posts.append(msg)\n self.loop.create_task(self.process_posts())\n\n async def call(self, msg):\n loop = self.loop\n future = loop.create_future()\n msg.future = future\n self.posts.append(msg)\n loop.create_task(self.process_posts())\n await future\n return 2\n","sub_path":"botworx/run/agent (copy).py","file_name":"agent (copy).py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"101740177","text":"import numpy as np\nimport requests\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, LSTM, TimeDistributed\nfrom tensorflow.keras.optimizers import Adam\nimport sys\nimport constants as constants\n\n\ndef get_confirm_token(response):\n for key, value in response.cookies.items():\n if key.startswith('download_warning'):\n return value\n\n return None\n\n\ndef save_response_content(response, destination):\n CHUNK_SIZE = 32768\n\n with open(destination, \"wb\") as f:\n for chunk in response.iter_content(CHUNK_SIZE):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n\n\ndef download_file_from_google_drive(id, destination):\n url = \"https://docs.google.com/uc?export=download\"\n\n session = requests.Session()\n\n response = session.get(url, params={'id': id}, stream=True)\n token = get_confirm_token(response)\n\n if token:\n params = {'id': id, 'confirm': token}\n response = session.get(url, params=params, stream=True)\n\n save_response_content(response, destination)\n\n\ndef get_empty_model(largest=constants.LARGEST, symbols=constants.SYMBOLS, lr=1e-4) -> Sequential:\n out = Sequential()\n out.add(LSTM(1024, return_sequences=True, input_shape=[largest, symbols]))\n out.add(Dropout(0.2))\n out.add(LSTM(1024, return_sequences=True))\n out.add(Dropout(0.2))\n out.add(LSTM(1024, return_sequences=True))\n out.add(Dropout(0.2))\n out.add(LSTM(1024, return_sequences=True))\n out.add(Dropout(0.2))\n out.add(TimeDistributed(Dense(symbols, activation='softmax')))\n adam_opti = Adam(lr=lr)\n out.compile(loss='categorical_crossentropy', optimizer=adam_opti, metrics=['categorical_accuracy'])\n return out\n\n\ndef load_weights_to_model(model, weights_id=None, optimizer=Adam(lr=0.0001), path=None):\n \"\"\"\n functions that load weights to model\n :param model: here we gonna load weights\n :param weights_id: I suppose that we are to store weights in google\n :param path: or in directory\n :param optimizer:\n :return:\n \"\"\"\n if path is None and weights_id is None:\n print('Lol, no idea where are weights. Give me id or path, lol')\n return 1\n if path is None:\n weight_path = 'weights.hdf5'\n download_file_from_google_drive(weights_id, weight_path)\n else:\n weight_path = path\n\n model.load_weights(weight_path)\n\n model.compile(loss='categorical_crossentropy',\n optimizer=optimizer, metrics=['categorical_accuracy'])\n\n\ndef get_jokes(model, init_word='мужик', jokes_num=1, joke_len=30, largest=constants.LARGEST, symbols=constants.SYMBOLS,\n decoder=constants.num_char) -> list:\n out = []\n for jokes in range(jokes_num):\n gen = np.zeros([1, largest, symbols], dtype='int8')\n gen[0][0][1] = 1\n joke = init_word\n for i in range(1, joke_len):\n pred = model.predict(gen)\n pred = pred[0][i - 1]\n letter = np.random.choice(symbols, p=pred)\n if letter == 0 or letter == 1:\n break\n joke += decoder[letter]\n gen[0][i][letter] = 1\n out.append(joke)\n return out\n","sub_path":"j_generator.py","file_name":"j_generator.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"25252190","text":"import re\r\nimport string\r\n\r\ntry:\r\n\tL0 = long(0)\r\nexcept:\r\n\tL0 = 0\r\n\tlong = int\r\n\r\nofpp = {\r\n\t0xffffff00: \"max\",\r\n\t0xfffffff8: \"in_port\",\r\n\t0xfffffff9: \"table\",\r\n\t0xfffffffa: \"normal\",\r\n\t0xfffffffb: \"flood\",\r\n\t0xfffffffc: \"all\",\r\n\t0xfffffffd: \"controller\",\r\n\t0xfffffffe: \"local\",\r\n\t0xffffffff: \"any\"\r\n\t}\r\n\r\ndef is_delimiter(c):\r\n\treturn c in \",\" or c in string.whitespace\r\n\r\nre_value = re.compile(r\"^(\\s*=?\\s*)([^,=/\\s]+)(\\s*/\\s*([^,=/\\s]+))?\")\r\ndef get_value(unparsed):\r\n\treturn re_value.match(unparsed).groups()\r\n\r\n\r\nre_unit = re.compile(r\"^(\\s*,?\\s*)([^,=\\s]+)(\\s*=?\\s*)(.*)\")\r\ndef get_unit(unparsed):\r\n\treturn re_unit.match(unparsed).groups()\r\n\r\n\r\ndef longest(s, char_set):\r\n\t'''returns the maximum continuous length of string, which is made from char_set.'''\r\n\ti = 0\r\n\tfor c in s:\r\n\t\tif c in char_set:\r\n\t\t\ti += 1\r\n\t\telse:\r\n\t\t\tbreak\r\n\treturn i\r\n\r\ndef parseInt(unparsed):\r\n\tif unparsed.startswith(\"-\"):\r\n\t\tl = 1 + longest(unparsed[1:], \"0123456789\")\r\n\t\treturn -long(unparsed[1:l]), l\r\n\t\r\n\tif unparsed.startswith(\"0x\") or unparsed.startswith(\"0X\"):\r\n\t\tl = 2 + longest(unparsed[2:], \"0123456789abcdefABCDEF\")\r\n\t\treturn long(unparsed[2:l], 16), l\r\n\telif unparsed.startswith(\"0\") and len(unparsed)>2 and unparsed[1] in \"01234567\":\r\n\t\tl = 1 + longest(unparsed[1:], \"01234567\")\r\n\t\treturn long(unparsed[1:l], 8), l\r\n\telse:\r\n\t\tl = longest(unparsed, \"0123456789\")\r\n\t\treturn long(unparsed[:l]), l\r\n\r\ndef parseFloat(unparsed):\r\n\tneg = False\r\n\tif unparsed.startswith(\"-\"):\r\n\t\tneg = True\r\n\t\tunparsed = unparsed[1:]\r\n\t\r\n\tl = longest(unparsed, \"0123456789\")\r\n\tret = long(unparsed[:l])\r\n\tif unparsed[l:].startswith(\".\"):\r\n\t\tl2 = longest(unparsed[l+1:], \"0123456789\")\r\n\t\tret += float(long(unparsed[l+1:l+l2+1]))/(10**l2)\r\n\t\tl += l2+1\r\n\t\r\n\treturn ret, l\r\n","sub_path":"ofpstr/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"144194083","text":"import nltk\n\nclass Analyzer():\n \"\"\"Implements sentiment analysis.\"\"\"\n\n def __init__(self, positives, negatives):\n \"\"\"Initialize Analyzer.\"\"\"\n # read positive list and store each word into a set\n positive_file = open(positives, 'r')\n self.positive_set = set()\n for line in positive_file:\n self.positive_set.add(line.rstrip())\n # read negative list and store each word into a set\n negative_file = open(negatives, 'r')\n self.negative_set = set()\n for line in negative_file:\n self.negative_set.add(line.rstrip())\n # initialize a score counter\n self.score = 0\n\n def analyze(self, text):\n \"\"\"Analyze text for sentiment, returning its score.\"\"\"\n tokenizer = nltk.tokenize.TweetTokenizer()\n tokens = tokenizer.tokenize(text)\n for token in tokens:\n if (token in self.positive_set):\n self.score += 1\n elif (token in self.negative_set):\n self.score -=1\n else: \n self.score += 0\n return self.score\n","sub_path":"analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"526699544","text":"from natto import MeCab\r\nfreq = {}\r\nstopwords ={'それ','これ','私','の','もの','よう','ん','ら','ため','そう'}\r\nwith MeCab('-F%m,%f[0]') as mc:\r\n with open('neko.txt', 'r') as f:\r\n for s in f:\r\n for w in mc.parse(s, as_nodes=True):\r\n flist = w.feature.split(',')\r\n if len(flist)>1:\r\n word = flist[0]\r\n pos = flist[1]\r\n if pos == '名詞': \r\n if not word in stopwords: \r\n if word in freq:\r\n freq[word]=freq[word]+1\r\n else:\r\n freq[word]=1\r\n\r\n# 単語ID辞書を構築\r\nword2id = {}\r\nid2word = []\r\nfor s in freq:\r\n if not s in word2id:\r\n if freq[s]>=10:\r\n word2id[s]=len(id2word)\r\n id2word.append(s)\r\n\r\nprint('■ID順')\r\nfor i in range(min(10,len(id2word))):\r\n print('ID=',i,':',id2word[i])\r\n\r\nprint('')\r\nprint('■頻度順')\r\nsa = sorted(freq.items(), key=lambda x: x[1], reverse=True)\r\nfor a in sa[:10]:\r\n print('ID='+str(word2id[a[0]]),':',a[0],'(頻度=',a[1],')')\r\n","sub_path":"py/prog3-13.py","file_name":"prog3-13.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"517160874","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nAdds support for texting Indian mobile numbers\n\"\"\"\n\nfrom datetime import datetime\nfrom pytz import timezone, UTC\nimport requests\n# from urllib2 import urlopen, URLError\n# from urllib import urlencode\n\nfrom flask import current_app, flash, request\nfrom baseframe import _\nfrom lastuser_core.models import db, SMSMessage, SMS_STATUS\nfrom .. import lastuser_ui\n\n# SMS GupShup sends delivery reports with this timezone\nSMSGUPSHUP_TIMEZONE = timezone('Asia/Kolkata')\n\n\ndef send_message(msg):\n if msg.phone_number.startswith('+91'): # Indian number. Use Exotel\n if len(msg.phone_number) != 13:\n raise ValueError(_(\"Invalid Indian mobile number\"))\n # All okay. Send!\n if not (current_app.config.get('SMS_EXOTEL_SID') and current_app.config.get('SMS_EXOTEL_TOKEN')):\n raise ValueError(_(\"This server is not configured to send SMS\"))\n else:\n sid = current_app.config['SMS_EXOTEL_SID']\n token = current_app.config['SMS_EXOTEL_TOKEN']\n try:\n r = requests.post('https://twilix.exotel.in/v1/Accounts/{sid}/Sms/send.json'.format(sid=sid),\n auth=(sid, token),\n data={\n 'From': current_app.config.get('SMS_EXOTEL_FROM'),\n 'To': msg.phone_number,\n 'Body': msg.message\n })\n if r.status_code in (200, 201):\n # All good\n jsonresponse = r.json()\n if isinstance(jsonresponse, (list, tuple)) and jsonresponse:\n msg.transaction_id = jsonresponse[0].get('SMSMessage', {}).get('Sid')\n else:\n msg.transaction_id = jsonresponse.get('SMSMessage', {}).get('Sid')\n else:\n # FIXME: This function should not be sending messages to the UI\n flash(_(\"Message could not be sent\"), 'danger')\n except requests.ConnectionError:\n flash(_(\"The SMS delivery engine is not reachable at the moment. Please try again\"), 'danger')\n else:\n # No number validation\n # All okay. Send!\n if not (current_app.config.get('SMS_TWILIO_SID') and current_app.config.get('SMS_TWILIO_TOKEN')):\n raise ValueError(_(\"This server is not configured to send SMS\"))\n else:\n sid = current_app.config['SMS_TWILIO_SID']\n token = current_app.config['SMS_TWILIO_TOKEN']\n try:\n r = requests.post('https://api.twilio.com/2010-04-01/Accounts/{sid}/Messages.json'.format(sid=sid),\n auth=(sid, token),\n data={\n 'From': current_app.config.get('SMS_TWILIO_FROM'),\n 'To': msg.phone_number,\n 'Body': msg.message\n })\n if r.status_code in (200, 201):\n # All good\n jsonresponse = r.json()\n msg.transaction_id = jsonresponse.get('sid', '')\n else:\n # FIXME: This function should not be sending messages to the UI\n flash(_(\"Message could not be sent\"), 'danger')\n except requests.ConnectionError:\n flash(_(\"The SMS delivery engine is not reachable at the moment. Please try again\"), 'danger')\n\n # # TODO: Also check if we have SMS GupShup credentials in settings.py\n # params = urlencode(dict(\n # method='SendMessage',\n # send_to=msg.phone_number[1:], # Number with leading +\n # msg=msg.message,\n # msg_type='TEXT',\n # format='text',\n # v='1.1',\n # auth_scheme='plain',\n # userid=current_app.config['SMS_SMSGUPSHUP_USER'],\n # password=current_app.config['SMS_SMSGUPSHUP_PASS'],\n # mask=current_app.config['SMS_SMSGUPSHUP_MASK']\n # ))\n # try:\n # response = urlopen('https://enterprise.smsgupshup.com/GatewayAPI/rest?%s' % params).read()\n # r_status, r_phone, r_id = [item.strip() for item in response.split('|')]\n # if r_status == 'success':\n # msg.status = SMS_STATUS.PENDING\n # msg.transaction_id = r_id\n # except URLError, e:\n # # FIXME: This function should not be sending messages to the UI\n # flash(\"Message could not be sent. Error: %s\" % e)\n\n\ndef send_phone_verify_code(phoneclaim):\n msg = SMSMessage(phone_number=phoneclaim.phone,\n message=current_app.config['SMS_VERIFICATION_TEMPLATE'].format(code=phoneclaim.verification_code))\n # Now send this\n send_message(msg)\n db.session.add(msg)\n\n\n@lastuser_ui.route('/report/smsgupshup')\ndef report_smsgupshup():\n externalId = request.args.get('externalId')\n deliveredTS = request.args.get('deliveredTS')\n status = request.args.get('status')\n phoneNo = request.args.get('phoneNo')\n cause = request.args.get('cause')\n\n # Find a corresponding message and ensure the parameters match\n msg = SMSMessage.query.filter_by(transaction_id=externalId).first()\n if not msg:\n return _(\"No such message\"), 404\n elif msg.phone_number != '+' + phoneNo:\n return _(\"Incorrect phone number\"), 404\n else:\n if status == 'SUCCESS':\n msg.status = SMS_STATUS.DELIVERED\n elif status == 'FAIL':\n msg.status = SMS_STATUS.FAILED\n else:\n msg.status == SMS_STATUS.UNKNOWN\n msg.fail_reason = cause\n if deliveredTS:\n deliveredTS = float(deliveredTS) / 1000.0\n # This delivery time is in IST, GMT+0530\n # Convert this into a naive UTC timestamp before saving\n local_status_at = datetime.fromtimestamp(deliveredTS)\n msg.status_at = SMSGUPSHUP_TIMEZONE.localize(local_status_at).astimezone(UTC)\n db.session.commit()\n return _(\"Status updated\")\n","sub_path":"lastuser_ui/views/sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":6025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"644357545","text":"from queue import Queue\nfrom watchdog.observers import Observer\nfrom uploader.event_handler import DirectoryChangeEventHandler\nfrom threading import Thread\n\n\nclass DirectoryWatcher(Thread):\n def __init__(self, base_gid, root_path, notification_queue = Queue()):\n self.base_gid = base_gid\n self.root_path = root_path\n self.notification_queue = notification_queue\n self.event_handler = DirectoryChangeEventHandler(base_gid, root_path, notification_queue)\n self.event_observer = Observer()\n self.running = False\n\n def start(self):\n self.event_handler.start()\n self.event_observer.schedule(\n self.event_handler,\n self.root_path,\n recursive=True\n )\n self.event_observer.start()\n self.running = True\n\n def stop(self):\n self.event_observer.stop()\n self.event_handler.stop()\n self.event_observer.join()\n self.event_handler.join()\n self.running = False\n\n def current_tree(self):\n return self.event_handler.current_tree\n\n def get_next_notification(self):\n return self.notification_queue.get()","sub_path":"uploader/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"480685224","text":"\"\"\"\nHomework 1\nDeadline: 16 AUG, 20:00\n\"\"\"\n\n\"\"\"\nProblem 1.\n\nGive examples of integer, string and float values.\nThen use type() function to prove it. \n\"\"\"\nexample_of_integer = 44\nexample_of_string = \"a text message\"\nexample_of_float = 5.5\n\nprint(type(example_of_integer))\nprint(type(example_of_string))\nprint(type(example_of_float))\n\n\"\"\"\nProblem 2.\n\nCreate variables movie1 and movie2, assign your 2 favourite movies to those variables.\nPut the variables in the text \"My 2 favourite movies are ____, ____.\" and print it. \n\"\"\"\nmovie1 = \"Star Wars\"\nmovie2 = \"The Proposal\"\nprint(\"My 2 favourite movies are \", movie1, movie2)\n\n\"\"\"\nProblem 3.\n\nCalculate your age using the value of the year you were born and the value of current year.\n\"\"\"\ncurrent_year = 2021\nyear_i_was_born = 1997\nmy_age = current_year - year_i_was_born\nprint(\"I am \" + str(my_age) + \" years old.\")\n\n\"\"\"\nProblem 4.\n\nWhat is wrong with this variable name? Correct it.\n\"\"\"\nmy_first_name = \"Poghos\"\n\n\"\"\"\nProblem 5.\n\nPetros is 20 years old.\nPrint \"Petros is younger than me.\" if his age is smaller than yours.\nPrint \"Petros is older than me.\" if his age is greater than yours.\nPrint \"Petros is my age\" if his age equals yours.\n\"\"\"\npetros_age = 20\n\nif petros_age < my_age:\n print(\"Petros is younger than me.\")\nif petros_age > my_age:\n print(\"Petros is older than me.\")\nif petros_age == my_age:\n print(\"Petros is my age\")\n\n\n\"\"\"\nProblem 6.\n\nCreate a string variable.\nTransform it into integer.\n\"\"\"\nvar = '47567'\nprint(float(var))\n","sub_path":"homework_1_sol.py","file_name":"homework_1_sol.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"178739652","text":"import reprlib\nimport sys\n\nclass MyRepr(reprlib.Repr):\n def repr_TextIOWrapper(self, obj, level):\n if obj.name in {'', '', ''}:\n return obj.name\n return repr(obj)\n\naRepr = MyRepr()\nprint(aRepr.repr(sys.stdin)) # prints ''\n","sub_path":"23/04/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"31765208","text":"import argparse\r\nimport glob\r\nimport os\r\nimport cv2\r\nimport torch\r\nimport time\r\nimport logging\r\nimport os\r\nimport json\r\nimport copy\r\nimport numpy as np\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime\r\nfrom collections import OrderedDict\r\nfrom torch.nn.parallel import DistributedDataParallel\r\n\r\n# Detectron2 Packages\r\nfrom detectron2 import model_zoo\r\nimport detectron2.utils.comm as comm\r\nfrom detectron2.structures import BoxMode\r\nfrom detectron2.data import transforms as T\r\nfrom detectron2.config import get_cfg, CfgNode\r\nfrom detectron2.data import detection_utils as utils\r\nfrom detectron2.engine import DefaultPredictor, DefaultTrainer\r\nfrom detectron2.engine import default_argument_parser, default_setup, launch\r\nfrom detectron2.checkpoint import DetectionCheckpointer, PeriodicCheckpointer\r\n\r\n# Different Detectron2 Evaluators\r\nfrom detectron2.evaluation import (\r\n CityscapesInstanceEvaluator,\r\n CityscapesSemSegEvaluator,\r\n COCOEvaluator,\r\n COCOPanopticEvaluator,\r\n DatasetEvaluators,\r\n LVISEvaluator,\r\n PascalVOCDetectionEvaluator,\r\n SemSegEvaluator,\r\n inference_on_dataset,\r\n print_csv_format,\r\n)\r\n\r\n# Model Trainer Libraries\r\nfrom detectron2.data import (\r\n DatasetMapper,\r\n MetadataCatalog,\r\n DatasetCatalog,\r\n build_detection_test_loader,\r\n build_detection_train_loader,\r\n)\r\n\r\n# Libraries for model logging\r\nfrom detectron2.utils.events import (\r\n CommonMetricPrinter,\r\n EventStorage,\r\n JSONWriter,\r\n TensorboardXWriter,\r\n)\r\n\r\n# Libraries for custom training loop\r\nfrom detectron2.modeling import build_model\r\nfrom detectron2.solver import build_lr_scheduler, build_optimizer\r\n\r\nlogger = logging.getLogger(\"detectron2\")\r\n\r\ndef get_roadstress_dicts(img_dir):\r\n # Load and read json file stores information about annotations\r\n json_file = os.path.join(img_dir, \"via_export_json.json\")\r\n with open(json_file) as f:\r\n imgs_anns = json.load(f)\r\n\r\n dataset_dicts = [] # list of annotations info for every images in the dataset\r\n for idx, v in enumerate(imgs_anns.values()):\r\n if(v[\"regions\"]):\r\n record = {} # a dictionary to store all necessary info of each image in the dataset\r\n \r\n # open the image to get the height and width\r\n filename = os.path.join(img_dir, v[\"filename\"])\r\n height, width = cv2.imread(filename).shape[:2]\r\n \r\n record[\"file_name\"] = filename\r\n record[\"image_id\"] = idx\r\n record[\"height\"] = height\r\n record[\"width\"] = width\r\n \r\n # getting annotation for every instances of object in the image\r\n annos = v[\"regions\"]\r\n objs = []\r\n for anno in annos:\r\n anno = anno[\"shape_attributes\"]\r\n px = anno[\"all_points_x\"]\r\n py = anno[\"all_points_y\"]\r\n poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)]\r\n poly = [p for x in poly for p in x]\r\n\r\n obj = {\r\n \"bbox\": [np.min(px), np.min(py), np.max(px), np.max(py)],\r\n \"bbox_mode\": BoxMode.XYXY_ABS,\r\n \"segmentation\": [poly],\r\n \"category_id\": 0,\r\n \"iscrowd\": 0\r\n }\r\n objs.append(obj)\r\n record[\"annotations\"] = objs\r\n dataset_dicts.append(record)\r\n return dataset_dicts\r\n\r\ndef get_evaluator(cfg, dataset_name, output_folder=None):\r\n \"\"\"\r\n Create evaluator(s) for a given dataset.\r\n This uses the special metadata \"evaluator_type\" associated with each builtin dataset.\r\n For your own dataset, you can simply create an evaluator manually in your\r\n script and do not have to worry about the hacky if-else logic here.\r\n \"\"\"\r\n if output_folder is None:\r\n output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\r\n evaluator_list = []\r\n evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type\r\n if evaluator_type in [\"sem_seg\", \"coco_panoptic_seg\"]:\r\n evaluator_list.append(\r\n SemSegEvaluator(\r\n dataset_name,\r\n distributed=True,\r\n num_classes=cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES,\r\n ignore_label=cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE,\r\n output_dir=output_folder,\r\n )\r\n )\r\n if evaluator_type in [\"coco\", \"coco_panoptic_seg\"]:\r\n evaluator_list.append(COCOEvaluator(dataset_name, cfg, True, output_folder))\r\n if evaluator_type == \"coco_panoptic_seg\":\r\n evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder))\r\n if evaluator_type == \"cityscapes_instance\":\r\n assert (\r\n torch.cuda.device_count() >= comm.get_rank()\r\n ), \"CityscapesEvaluator currently do not work with multiple machines.\"\r\n return CityscapesInstanceEvaluator(dataset_name)\r\n if evaluator_type == \"cityscapes_sem_seg\":\r\n assert (\r\n torch.cuda.device_count() >= comm.get_rank()\r\n ), \"CityscapesEvaluator currently do not work with multiple machines.\"\r\n return CityscapesSemSegEvaluator(dataset_name)\r\n if evaluator_type == \"pascal_voc\":\r\n return PascalVOCDetectionEvaluator(dataset_name)\r\n if evaluator_type == \"lvis\":\r\n return LVISEvaluator(dataset_name, cfg, True, output_folder)\r\n if len(evaluator_list) == 0:\r\n raise NotImplementedError(\r\n \"no Evaluator for the dataset {} with the type {}\".format(dataset_name, evaluator_type)\r\n )\r\n if len(evaluator_list) == 1:\r\n return evaluator_list[0]\r\n return DatasetEvaluators(evaluator_list)\r\n\r\n\r\n'''\r\n Future Usage: Will try more image augmentation for model training\r\n'''\r\ndef customMapper(dataset_dict):\r\n dataset_dict = copy.deepcopy(dataset_dict)\r\n image = utils.read_image(dataset_dict[\"file_name\"], format=\"BGR\")\r\n\r\n transform_list = [\r\n T.Resize((600, 800)),\r\n T.RandomFlip(prob=0.6, horizontal=True, vertical=False),\r\n T.RandomFlip(prob=0.6, horizontal=False, vertical=True),\r\n ]\r\n image, transforms = T.apply_transform_gens(transform_list, image)\r\n dataset_dict[\"image\"] = torch.as_tensor(image.transpose(2, 0, 1).astype(\"float32\"))\r\n annos = [\r\n\t\tutils.transform_instance_annotations(obj, transforms, image.shape[:2])\r\n\t\tfor obj in dataset_dict.pop(\"annotations\")\r\n\t\tif obj.get(\"iscrowd\", 0) == 0\r\n\t]\r\n instances = utils.annotations_to_instances(annos, image.shape[:2])\r\n dataset_dict[\"instances\"] = utils.filter_empty_instances(instances)\r\n return dataset_dict\r\n\r\n'''\r\n Evaluate the model performance with the COCO metrics (AP score)\r\n'''\r\ndef do_test(cfg, model):\r\n results = OrderedDict()\r\n for dataset_name in cfg.DATASETS.TEST: # perform inference on all testing dataset\r\n data_loader = build_detection_test_loader(cfg, dataset_name, mapper=DatasetMapper(cfg, False))\r\n evaluator = get_evaluator(\r\n cfg, dataset_name, os.path.join(cfg.OUTPUT_DIR, \"inference\", dataset_name)\r\n )\r\n results_i = inference_on_dataset(model, data_loader, evaluator)\r\n results[dataset_name] = results_i\r\n if comm.is_main_process():\r\n logger.info(\"Evaluation results for {} in csv format:\".format(dataset_name))\r\n print_csv_format(results_i)\r\n if len(results) == 1:\r\n results = list(results.values())[0]\r\n return results\r\n\r\n'''\r\n Functionality: Custom training loop for detectron2\r\n Usage: Will use to implement early stopping for model training\r\n'''\r\ndef do_train(cfg, model, resume=False):\r\n model.train()\r\n optimizer = build_optimizer(cfg, model)\r\n scheduler = build_lr_scheduler(cfg, optimizer)\r\n\r\n checkpointer = DetectionCheckpointer(\r\n model, cfg.OUTPUT_DIR, optimizer=optimizer, scheduler=scheduler\r\n )\r\n start_iter = (\r\n checkpointer.resume_or_load(cfg.MODEL.WEIGHTS, resume=resume).get(\"iteration\", -1) + 1\r\n )\r\n max_iter = cfg.SOLVER.MAX_ITER\r\n\r\n periodic_checkpointer = PeriodicCheckpointer(\r\n checkpointer, cfg.SOLVER.CHECKPOINT_PERIOD, max_iter=max_iter\r\n )\r\n\r\n writers = (\r\n [\r\n CommonMetricPrinter(max_iter),\r\n JSONWriter(os.path.join(cfg.OUTPUT_DIR, \"metrics.json\")),\r\n TensorboardXWriter(cfg.OUTPUT_DIR),\r\n ]\r\n if comm.is_main_process()\r\n else []\r\n )\r\n\r\n # compared to \"train_net.py\", we do not support accurate timing and\r\n # precise BN here, because they are not trivial to implement\r\n data_loader = build_detection_train_loader(cfg, mapper=customMapper)\r\n logger.info(\"Starting training from iteration {}\".format(start_iter))\r\n with EventStorage(start_iter) as storage:\r\n for data, iteration in zip(data_loader, range(start_iter, max_iter)):\r\n iteration = iteration + 1\r\n storage.step()\r\n\r\n loss_dict = model(data)\r\n losses = sum(loss_dict.values())\r\n assert torch.isfinite(losses).all(), loss_dict\r\n\r\n loss_dict_reduced = {k: v.item() for k, v in comm.reduce_dict(loss_dict).items()}\r\n losses_reduced = sum(loss for loss in loss_dict_reduced.values())\r\n if comm.is_main_process():\r\n storage.put_scalars(total_loss=losses_reduced, **loss_dict_reduced)\r\n\r\n optimizer.zero_grad()\r\n losses.backward()\r\n optimizer.step()\r\n storage.put_scalar(\"lr\", optimizer.param_groups[0][\"lr\"], smoothing_hint=False)\r\n scheduler.step()\r\n\r\n if (\r\n cfg.TEST.EVAL_PERIOD > 0\r\n and iteration % cfg.TEST.EVAL_PERIOD == 0\r\n and iteration != max_iter\r\n ):\r\n print(\"Run inference and evaluation inside do_train\")\r\n do_test(cfg, model)\r\n comm.synchronize()\r\n\r\n if iteration - start_iter > 5 and (iteration % 20 == 0 or iteration == max_iter):\r\n for writer in writers:\r\n writer.write()\r\n periodic_checkpointer.step(iteration)\r\n\r\nfrom imantics import Polygons, Mask\r\nfrom PIL import Image, ImageDraw\r\n\r\ndef mask_to_poly(bin_mask):\r\n return Mask.create(bin_mask).polygons().segmentation\r\n\r\ndef poly_to_mask(polygon, width, height):\r\n img = Image.new('L', (width, height), 0)\r\n ImageDraw.Draw(img).polygon(polygon, outline=1, fill=1)\r\n mask = np.array(img).astype(bool)\r\n return mask","sub_path":"detectron2/projects/RoadStress/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"513381028","text":"from itertools import repeat, product as cartesian\nfrom collections import OrderedDict\n\nfrom numpy import dtype\n\nfrom enum import Enum\n\nclass BasicType:\n\t'''A base class for all GLSL basic types:\n\n\t- :py:class:`Scalar`\n\t- :py:class:`Vector`\n\t- :py:class:`Matrix`\n\t- :py:class:`Sampler`\n\n\tIt supports construction from a string representation of the GLSL type for convenience:\n\n\t.. testsetup::\n\n\t from GLPy.GLSL import BasicType, Vector\n\n\t>>> BasicType('vec3') is Vector.vec3\n\tTrue\n\t'''\n\n\tdef __new__(self, datatype):\n\t\tfor basic_type in [Scalar, Vector, Matrix, Sampler]:\n\t\t\ttry:\n\t\t\t\treturn basic_type[datatype]\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\telse:\n\t\t\traise ValueError(\"No such GLSL type.\")\n\nscalar_types = ['bool', 'int', 'uint', 'float', 'double']\n\nclass Scalar(str, BasicType, Enum):\n\t'''The basic GLSL scalars.\n\n\tScalars define the following attributes:\n\n\t*prefix*\n\t The prefix used for related types, e.g. ``'b'`` for ``Scalar.bool`` as a\n\t 3-vector of booleans is a **b**\\ vec3\n\t*scalar_type*\n\t The scalar type of a scalar is itself\n\t*machine_type*\n\t The machine representation of this GLSL type as a :py:class:`numpy.dtype`\n\t*opaque*\n\t Whether the datatype is an opaque type (:py:obj:`False`)\n\t'''\n\n\t__prefixes__ = { 'bool': 'b'\n\t , 'int': 'i'\n\t , 'uint': 'u'\n\t , 'float': ''\n\t , 'double': 'd' }\n\t__machine_types__ = {'bool': dtype('uint32')\n\t\t\t\t\t\t,'int': dtype('int32')\n\t\t\t\t\t\t,'uint': dtype('uint32')\n\t\t\t\t\t\t,'float': dtype('float32')\n\t\t\t\t\t\t,'double': dtype('float64')}\n\n\tdef __init__(self, value):\n\t\tself.prefix = self.__prefixes__[self.name]\n\t\tself.machine_type = self.__machine_types__[self.name]\n\t\tself.scalar_type = self\n\t\tself.opaque = False\nscalar_doc = Scalar.__doc__\nScalar = Enum('Scalar', ((s, s) for s in scalar_types), type=Scalar)\nScalar.__doc__ = scalar_doc\n\nfloating_point_scalars = { Scalar.float, Scalar.double }\n\nsampler_dims = range(1, 4)\nsampler_data_types = {Scalar.float, Scalar.int, Scalar.uint}\nsampler_types = [ \"{}sampler{}D\".format(scalar_type.prefix, ndim)\n for scalar_type, ndim in cartesian(sampler_data_types, sampler_dims) ]\nclass Sampler(str, BasicType, Enum):\n\t'''The GLSL sampler types.\n\n\tScalars difine the following attributes:\n\n\t*opaque*\n\t Whether the datatype is an opaque type (:py:obj:`True`)\n\t'''\n\t__ndims__ = { \"{}sampler{}D\".format(scalar_type.prefix, ndim): ndim\n\t for scalar_type, ndim in cartesian(sampler_data_types, sampler_dims) }\n\n\tdef __init__(self, value):\n\t\tself.ndim = self.__ndims__[self.name]\n\t\tself.opaque = True\nsampler_doc = Sampler.__doc__\nSampler = Enum('Sampler', ((s, s) for s in sampler_types), type=Sampler)\nSampler.__doc__ = sampler_doc\n\nvector_sizes = range(2, 5)\nvector_types = [\"{}vec{}\".format(scalar_type.prefix, size)\n for scalar_type, size in cartesian(Scalar, vector_sizes) ]\nclass Vector(str, BasicType, Enum):\n\t'''The GLSL vector types.\n\n\tVectors define the following attributes:\n\n\t*scalar_type*\n\t The :py:class:`Scalar` type that defines a single element of the vector\n\t*shape*\n\t A 1-tuple of the number of elements in the vector\n\t*machine_type*\n\t The machine representation of this GLSL type as a :py:class:`numpy.dtype`\n\t*opaque*\n\t Whether the datatype is an opaque type (:py:obj:`False`)\n\t'''\n\t__scalar_types__ = { \"{}vec{}\".format(scalar_type.prefix, size): scalar_type\n\t for scalar_type, size in cartesian(Scalar, vector_sizes) }\n\t__shapes__ = { \"{}vec{}\".format(scalar_type.prefix, size): (size,)\n\t for scalar_type, size in cartesian(Scalar, vector_sizes) }\n\n\tdef __init__(self, value):\n\t\tself.scalar_type = self.__scalar_types__[self.name]\n\t\tself.shape = self.__shapes__[self.name]\n\t\tself.machine_type = dtype((self.scalar_type.machine_type, self.shape))\n\t\tself.opaque = False\n\n\t@classmethod\n\tdef fromType(cls, scalar_type, size):\n\t\treturn cls[''.join((scalar_type.prefix, 'vec', str(size)))]\n\nvector_doc = Vector.__doc__\nVector = Enum('Vector', ((v, v) for v in vector_types), type=Vector)\nVector.__doc__ = vector_doc\n\nmatrix_types = ( [\"{}mat{}\".format(scalar_type.prefix, size)\n for scalar_type, size in cartesian(floating_point_scalars, vector_sizes)]\n + [\"{}mat{}x{}\".format(scalar_type.prefix, size1, size2)\n for scalar_type, size1, size2\n in cartesian(floating_point_scalars, vector_sizes, vector_sizes)] )\nclass Matrix(str, BasicType, Enum):\n\t'''The GLSL matrix types.\n\n\tMatrices define the following attributes:\n\n\t*scalar_type*\n\t The :py:class:`Scalar` type that defines a single element of the matrix\n\t*shape*\n\t A 2-tuple of the number of elements along each dimension\n\t*opaque*\n\t Whether the datatype is an opaque type (:py:obj:`False`)\n\t'''\n\n\t__scalar_types__ = { \"{}mat{}\".format(scalar_type.prefix, size): scalar_type\n\t for scalar_type, size in cartesian(floating_point_scalars, vector_sizes) }\n\t__scalar_types__.update({ \"{}mat{}x{}\".format(scalar_type.prefix, size1, size2): scalar_type\n\t for scalar_type, size1, size2\n\t in cartesian(floating_point_scalars, vector_sizes, vector_sizes) })\n\n\t__shapes__ = { \"{}mat{}\".format(scalar_type.prefix, size): (size, size)\n\t for scalar_type, size in cartesian(floating_point_scalars, vector_sizes) }\n\t__shapes__.update({ \"{}mat{}x{}\".format(scalar_type.prefix, size1, size2): (size1, size2)\n\t for scalar_type, size1, size2\n\t in cartesian(floating_point_scalars, vector_sizes, vector_sizes) })\n\n\tdef __init__(self, value):\n\t\tself.shape = self.__shapes__[self.name]\n\t\tself.scalar_type = self.__scalar_types__[self.name]\n\t\tself.machine_type = dtype((self.scalar_type.machine_type, self.shape))\n\t\tself.opaque = False\n\n\t@classmethod\n\tdef fromType(cls, scalar_type, shape):\n\t\tcolumns, rows = shape\n\t\treturn cls[''.join((scalar_type.prefix, 'mat', str(columns), 'x', str(rows)))]\n\n\t@property\n\tdef rows(self):\n\t\treturn self.shape[1]\n\n\t@property\n\tdef columns(self):\n\t\treturn self.shape[0]\n\n\tdef __getitem__(self, idx):\n\t\tif idx >= self.shape[0]:\n\t\t\traise IndexError(\"Index {} out of bounds for {}\".format(idx, self))\n\t\treturn Vector.fromType(self.scalar_type, self.shape[1])\nmatrix_doc = Matrix.__doc__\nMatrix = Enum('Matrix', ((m, m) for m in matrix_types), type=Matrix)\nMatrix.__doc__ = matrix_doc\n\nglsl_types = [Scalar, Vector, Matrix, Sampler]\n\nclass Struct:\n\t'''A GLSL ``struct``\n\n\t:param str name: The name of the struct\n\t:param \\\\*contents: The contents of the struct\n\t:type \\\\*contents: [:py:class:`.Variable`]\n\t'''\n\n\tdef __init__(self, name, *contents):\n\t\tself.name = name\n\t\tself.contents = OrderedDict((var.name, var) for var in contents)\n\n\tdef __str__(self):\n\t\tcontents = '; '.join(str(c) for c in self.contents)\n\t\treturn \"struct {} {{ {}; }}\".format(self.name, contents)\n\n\tdef __repr__(self):\n\t\treturn \"{}(name='{}' contents={})\".format(type(self).__name__, self.name, self.contents)\n\n\tdef __len__(self):\n\t\t'''Returns the number of members of the struct.\n\n\t\t:rtype: :py:obj:`int`\n\t\t'''\n\t\treturn len(self.contents)\n\n\tdef __getitem__(self, idx):\n\t\t'''Returns a member of the struct.\n\n\t\t:rtype: :py:class:`.Variable`\n\t\t'''\n\t\treturn self.contents[idx]\n\n\tdef __iter__(self):\n\t\t'''Iterates over the members of the struct.\n\n\t\t:rtype: [:py:class:`.Variable`]\n\t\t'''\n\t\treturn iter(self.contents.values())\n\n\tdef __hash__(self):\n\t\treturn hash((self.name, tuple(self.contents.items())))\n\n\tdef __eq___(self):\n\t\treturn self.name == other.name and self.contents == other.contents\n\ndef formatShape(shape):\n\tarray = ']['.join(str(s) for s in shape)\n\treturn '[{}]'.format(array)\n\nclass Array:\n\t'''A GLSL array.\n\n\t:param element: The OpenGL type of one element of this array.\n\t:type element: :py:class:`.Scalar`, :py:class:`.Vector`\n\t :py:class:`.Matrix`, :py:class:`.Sampler` or :py:class:`.Struct`,\n\t :py:class:`.Array` or :py:obj:`str`\n\t:param shape: The shape of the array. A sequence will be transformed into\n\t an array of arrays.\n\t:type shape: :py:obj:`int` or [:py:obj:`int`]\n\t'''\n\tdef __init__(self, base, shape=1):\n\t\ttry:\n\t\t\tbase = BasicType(base)\n\t\texcept ValueError:\n\t\t\tpass\n\n\t\ttry:\n\t\t\tshape, *child_shapes = shape\n\t\texcept TypeError:\n\t\t\tchild_shapes = ()\n\n\t\tself.array_shape = shape\n\t\tself.element = base if not child_shapes else Array(base, child_shapes)\n\n\t@property\n\tdef full_shape(self):\n\t\t'''The shape of this array and all child arrays.'''\n\t\treturn (self.array_shape, ) + getattr(self.element, 'full_shape', ())\n\n\t@property\n\tdef base(self):\n\t\t'''The non-array base of this array.'''\n\t\treturn getattr(self.element, 'base', self.element)\n\n\tdef __str__(self):\n\t\treturn ''.join((self.base.name, formatShape(self.full_shape)))\n\n\tdef __getitem__(self, idx):\n\t\t'''Returns an element of the array.\n\n\t\t:rtype: :py:class:`BasicType` or :py:class:`Struct` or :py:class:`Array`\n\t\t'''\n\t\tif not 0 <= idx < self.array_shape:\n\t\t\traise IndexError(\"No such array element '{}'\".format(idx))\n\t\treturn self.element # All elements identical\n\n\tdef __len__(self):\n\t\t'''Returns the numer of elements in the array\n\n\t\t:rtype: :py:obj:`int`\n\t\t'''\n\t\treturn self.array_shape\n\n\tdef __iter__(self):\n\t\t'''Iterates over all elements in the array.\n\n\t\t:rtype: [:py:class:`BasicType`] or [:py:class:`Struct`] or [:py:class:`Array`]\n\t\t'''\n\t\treturn iter(repeat(self.element, self.array_shape))\n\n\tdef __eq__(self, other):\n\t\treturn self.element == other.element and self.array_shape == other.array_shape\n\n\tdef __hash__(self):\n\t\treturn hash((self.element, self.array_shape))\n","sub_path":"GLPy/GLSL/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":9518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"395073712","text":"import csv\r\nimport os\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport ast\r\n\r\n\r\ndef get_day_data(file):\r\n \"\"\" function that returns the python dictionary data\r\n which contains all needed information of the test data\r\n for plotting\"\"\"\r\n\r\n timestamps = []\r\n data = {}\r\n\r\n with open(file, 'r') as csv_file:\r\n csv_reader = csv.DictReader(csv_file)\r\n\r\n for row in csv_reader:\r\n if row['timestamp'] not in timestamps:\r\n timestamps.append(row['timestamp'])\r\n\r\n for timestamp in timestamps:\r\n data[timestamp] = {}\r\n data[timestamp]['totalTradedWatts'] = []\r\n data[timestamp]['averagePrice'] = []\r\n data[timestamp]['maximumPrice'] = []\r\n data[timestamp]['minimumPrice'] = []\r\n data[timestamp]['runningTime'] = []\r\n data[timestamp]['numberOfProducers'] = []\r\n data[timestamp]['numberOfConsumers'] = []\r\n data[timestamp]['dataPrepTime'] = []\r\n data[timestamp]['usedReductions'] = []\r\n\r\n with open(file, 'r') as csv_file:\r\n csv_reader = csv.DictReader(csv_file)\r\n\r\n for row in csv_reader:\r\n for timestamp in data.keys():\r\n if row['timestamp'] == timestamp:\r\n data[timestamp]['totalTradedWatts'].append(float(row['totalTradedWatts']))\r\n data[timestamp]['averagePrice'].append(float(row['averagePrice']))\r\n data[timestamp]['maximumPrice'].append(float(row['maximumPrice']))\r\n data[timestamp]['minimumPrice'].append(float(row['minimumPrice']))\r\n data[timestamp]['runningTime'].append(float(row['runningTime']))\r\n data[timestamp]['dataPrepTime'].append(float(row['dataPrepTime']))\r\n data[timestamp]['numberOfProducers'].append(float(row['numberOfProducers']))\r\n data[timestamp]['numberOfConsumers'].append(float(row['numberOfConsumers']))\r\n data[timestamp]['usedReductions'].append(row['usedReductions'])\r\n\r\n return data\r\n\r\n\r\ndef get_timestamps(data):\r\n \"\"\" function that returns a list of all timestamps\"\"\"\r\n\r\n timestamps = []\r\n for timestamp, values in data.items():\r\n # add timestamp to timestamp list\r\n timestamps.append(timestamp[11:16].replace('_', ':'))\r\n\r\n return timestamps\r\n\r\n\r\ndef pretty_ticker(timestamps):\r\n \"\"\" create ticker for x-axis on the plot\r\n returns the list timeForTicker\"\"\"\r\n\r\n timeForTicker = []\r\n for ts in timestamps:\r\n if ts[3:5] == str('00'):\r\n timeForTicker.append(ts)\r\n else:\r\n timeForTicker.append(None)\r\n\r\n return timeForTicker\r\n\r\n\r\n\r\ndef get_usedReductions(data):\r\n \"\"\" function that returns lists with used reductions for each day\"\"\"\r\n nested_konzessionsDifference = []\r\n nested_netCostDifference = []\r\n nested_lokalDistance = []\r\n nested_numberOfPairs = []\r\n\r\n for k, v in data.items():\r\n ts_konzessionsDifference = []\r\n ts_netCostDifference = []\r\n ts_lokalDistance = []\r\n ts_numberOfPairs = []\r\n\r\n for i in v['usedReductions']:\r\n usedReductions = ast.literal_eval(i)\r\n ts_konzessionsDifference.append(usedReductions['konzessionsDifference'])\r\n ts_netCostDifference.append(usedReductions['netCostDifference'])\r\n ts_lokalDistance.append(usedReductions['lokalDistance'])\r\n ts_numberOfPairs.append(usedReductions['numberOfPairs'])\r\n\r\n nested_konzessionsDifference.append(ts_konzessionsDifference[0])\r\n nested_lokalDistance.append(ts_lokalDistance[0])\r\n nested_netCostDifference.append(ts_netCostDifference[0])\r\n nested_numberOfPairs.append(ts_numberOfPairs[0])\r\n\r\n return nested_netCostDifference, nested_numberOfPairs, nested_lokalDistance, nested_konzessionsDifference\r\n\r\n\r\ndef plot_usedReductions(timestamps,timeForTicker,nested_netCostDifference, nested_numberOfPairs, nested_lokalDistance, nested_konzessionsDifference):\r\n \"\"\" function that plots all used reductions using matplotlib\"\"\"\r\n\r\n # setup plot\r\n fig1= plt.figure(1, figsize=(10, 6))\r\n averageCommunityPrice = fig1.add_subplot()\r\n\r\n # create title\r\n averageCommunityPrice.set_title('Simplex: eingesetzte rechtliche Rahmenbedingungen 01. Juli 2020')\r\n\r\n # set axes labels\r\n averageCommunityPrice.set_xlabel(\"Uhrzeit\")\r\n averageCommunityPrice.set_ylabel(\"rechtliche Rahmenbedingungen\")\r\n averageCommunityPrice.set_ylim(0,100)\r\n\r\n # set tickers for x\r\n averageCommunityPrice.set_xticklabels(timeForTicker, fontsize=10, rotation=45)\r\n averageCommunityPrice.margins(x=0)\r\n\r\n plt.plot(timestamps, nested_numberOfPairs, color = 'green', alpha = 0.7)\r\n plt.plot(timestamps, nested_lokalDistance, color = 'black', alpha = 0.7)\r\n plt.plot(timestamps, nested_konzessionsDifference, color = 'red', alpha = 0.7)\r\n plt.plot(timestamps, nested_netCostDifference, color = 'blue')\r\n\r\n # legend\r\n # from matplotlib.lines import Line2D\r\n # legend_elements = [Line2D([0], [0], color='green', label='number of pairs'),\r\n # Line2D([0], [0], color='black', label='local distance'),\r\n # Line2D([0], [0], color='red', label='konzessions difference'),\r\n # Line2D([0], [0], color='blue', label='netCost difference')]\r\n\r\n #plt.legend(handles=legend_elements, loc='best')\r\n\r\n fig = plt.gcf()\r\n fig.set_size_inches(10, 6)\r\n\r\n fig.savefig(\"simplex_kruskal_usedReductions.svg\")\r\n fig.savefig(\"simplex_usedReductions.pdf\")\r\n\r\n plt.show()\r\n\r\n return 0\r\n\r\n\r\ndef main():\r\n\r\n data = get_day_data('01_07.csv')\r\n\r\n nested_netCostDifference, nested_numberOfPairs, nested_lokalDistance, nested_konzessionsDifference = get_usedReductions(\r\n data)\r\n\r\n timestamps = get_timestamps(data)\r\n timeForTicker = pretty_ticker(timestamps)\r\n\r\n print(nested_numberOfPairs)\r\n\r\n print(\"Anzahl der Handelspaare in diesem Intervall\")\r\n print(max(nested_numberOfPairs))\r\n\r\n print(\"Anzahl lokaler Zusammenhang\")\r\n print(max(nested_lokalDistance))\r\n print(\"Anzahl Netzentgeltdifferenzen\")\r\n print(max(nested_netCostDifference))\r\n\r\n print(\"Anzahl Konzessionsabgabendifferenzen\")\r\n print(max(nested_konzessionsDifference))\r\n\r\n print(plot_usedReductions(timestamps,timeForTicker,nested_netCostDifference, nested_numberOfPairs, nested_lokalDistance, nested_konzessionsDifference))\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"simplex/usedReductions.py","file_name":"usedReductions.py","file_ext":"py","file_size_in_byte":6530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"469028308","text":"from data import *\nfrom functions import *\n\ndef main():\n again = True\n while(again):\n cls()\n askUserkey = input(\"Key ? \\t\")\n print(cesarDecrypt(\"T ks noc bofovkdsyxc k pksbo Doxoj fyec zbodc\", int(askUserkey)))\n\n askAgain = input(\"Again ? (y/n) \\t\")\n if(askAgain.lower() == 'n'):\n again = False\n\nmain()\npause()\n","sub_path":"Crypteur/Crypthor.py","file_name":"Crypthor.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"215726688","text":"from frontend.setting import *\n\n\nb_left_pins = 0 \nb_right_pins =0 \ni_left_pins = 0\ni_right_pins = 0\npin_wires_top = 0\npin_wires_bottom = 0\n\n\ndef line_generator(screen, pos1, pos2, color, board, item, ratio ):\n if type(color) != list:\n color = list(eval(\"color\" +',color'*(len(pos1)- 1)))\n #color = lambda selected_color : selected_color if type(selected_color) == list else [selected_color for i in range(len(pos1))]\n global b_left_pins \n global b_right_pins \n global i_left_pins \n global i_right_pins \n global pin_wires_top \n global pin_wires_bottom \n\n for index, start in enumerate(pos1):\n case = [0,0]\n end = pos2[index]\n start = (start[0], start[1] + ratio/2)\n start_finish = ()\n # side for starting position\n # right\n if start[0] > board.board_rect.center[0]:\n b_right_pins += 1\n start = (start[0] + ratio, start[1]) \n x1 = start[0] + b_right_pins*ratio*2\n case[0] = 0\n #left\n elif start[0] <= board.board_rect.center[0]:\n b_left_pins += 1\n x1 = start[0] - b_left_pins*ratio*2\n case[0] = 1 \n # side for ending position\n # right\n if end[0] > item.item_rect.center[0]:\n i_right_pins += 1\n x2 = end[0] + i_right_pins*ratio/2\n case[1] = 0\n # left\n elif end[0] <= item.item_rect.center[0]:\n i_left_pins += 1\n x2 = end[0] - i_left_pins*ratio/2\n case[1] = 1\n \n # y axis\n # item left side\n if item.item_rect.center[0] < board.board_rect.center[0]:\n # facing each other\n if case == [1, 0]:\n y1 = end[1]\n # right board to left item or left board to right item\n elif case == [0, 1] or case == [1, 0]:\n if item.item_rect.center[1] <= board.board_rect.center[1]:\n pin_wires_top += 1\n y1 = min(board.board[1] , item.item[1]) - pin_wires_top*2*ratio\n else:\n pin_wires_bottom += 1\n y1 = max(board.board[3], item.item[3]) + pin_wires_bottom*2*ratio\n # right board to right item\n else:\n if case == [1, 1]:\n x1 = x2\n if item.item_rect.center[1] < board.board_rect.center[1]:\n #if end[1] < board.board_rect.center[1]:\n pin_wires_top += 1\n if end[1] < board.board[1] - pin_wires_top*2*ratio:\n y1 = end[1]\n else:\n y1 = board.board[1] - pin_wires_top*2*ratio\n else:\n pin_wires_bottom += 1 \n if end[1] > board.board[3] - pin_wires_bottom*2*ratio:\n y1 = end[1]\n else:\n y1 = max(board.board[3], item.item[3]) + pin_wires_bottom*2*ratio\n # item right side\n else:\n # facing each other\n if case == [0, 1]:\n y1 = start[1]\n # right board to left item or left board to right item\n elif case == [0, 1] or case == [1, 0]:\n if item.item_rect.center[1] < board.board_rect.center[1]:\n pin_wires_top += 1\n y1 = min(board.board[1] , item.item[1]) - pin_wires_top*2*ratio\n else:\n pin_wires_bottom += 1\n y1 = max(board.board[3], item.item[3]) + pin_wires_bottom*2*ratio\n else:\n if case == [0, 0]:\n x1 = x2\n if item.item_rect.center[1] < board.board_rect.center[1]:\n #if end[1] < board.board_rect.center[1]:\n pin_wires_top += 1\n if end[1] < board.board[1] - pin_wires_top*2*ratio:\n y1 = end[1]\n else:\n y1 = board.board[1] - pin_wires_top*2*ratio\n else:\n pin_wires_bottom += 1 \n if end[1] > board.board[3] - pin_wires_bottom*2*ratio:\n y1 = end[1]\n else:\n y1 = max(board.board[3], item.item[3]) + pin_wires_bottom*2*ratio\n \n \n start_finish += (start,)\n start_finish += ((x1, start[1]),)\n start_finish += ((x1, y1),)\n start_finish += ((x2, y1),)\n start_finish += ((x2, end[1]),)\n start_finish += (end,)\n \n \n pg.draw.lines(screen, color[index], False, start_finish, int(ratio/2))\n","sub_path":"program/Schemetic/line_generator.py","file_name":"line_generator.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"370539861","text":"from string import digits, ascii_uppercase\r\nfrom random import choice\r\n\r\nrobotName = []\r\nwhile len(robotName) < 2:\r\n robotName.append(choice(ascii_uppercase)) # choisit 2 lettres aleatoires et les ajoute au nom\r\n\r\nwhile len(robotName) < 5:\r\n robotName.append(choice(digits)) # choisit 3 chiffres aleatoires au nom\r\n\r\nrobotName = \"\".join(robotName)\r\nprint(\"Le nom du robot est:\", robotName) # afffiche le nom du robot\r\n","sub_path":"RobotNameGenerator.py","file_name":"RobotNameGenerator.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"492034688","text":"\n#!/usr/bin/env python\n\n# University of Pittsburgh\n# Center for Simulation and Modeling\n# Esteban Meneses\n# Date: 03/20/15\n\nimport sys\nimport re\nimport datetime\nimport time\nimport os\nimport glob\nfrom math import *\nimport matplotlib as mtl\nmtl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import pylab\nimport numpy as np\nimport collections\n# import scipy.stats as ss\n# from collections import defaultdict\n# import collections\n# from datetime import date, timedelta\n# import seaborn as sns\n# from datetime import date, timedelta, datetime as dt\n# import calendar as cl\n# #import squarify\n# import matplotlib.patches as mpatches\n# import matplotlib.gridspec as gridspec\n\n\n\t\ndef fr_nodes(file_name, workload_dirName):\n\t#\"\"\" Reads a failure log file and correlates job IDs with MOAB log files in the directory \"\"\"\n\tfile_count = 0\n\tline_count = 0\n\tpathFileName = []\n\tpathFileName_workload = []\n\tworkload_node_req = []\n\tdata_node_req = []\n\tdata_node_fail = []\n\tdata_node_req_fail = {}\n\tcount_nodes_failed_nodes = 0 \n\n\tyear_text = \"\"\n\tformat = '%Y-%m-%d %H:%M:%S'\n\tmake_file = False\n\t\n\t#read the workload filter \n\ttry:\n\t\tfile = open(\"workload_filter.txt\", \"r\") \n\t\tworkload_node_req.clear()\n\t\tfor line in file: \n\t\t\tworkload_node_req.append(line)\n\t\tprint(\"Workload file loaded\")\n\texcept IOError:\n\t\tmake_file = True\n\t\tprint(\"Workload file created\")\n\t\n\t#############################################################\n\t#############################################################\n\t#extract workload data\n\t#get all files of the year\n\tif make_file == True:\n\t\tfor path, dirs, files in os.walk(workload_dirName):\n\t\t\tfor d in dirs:\n\t\t\t\tfor f in glob.iglob(os.path.join(path, d, '*')):\n\t\t\t\t\tpathFileName_workload.append(f)\n\t\t\n\t\tl = len(pathFileName_workload)\n\t\tcount = 0\n\t\tfor file_name_workload in pathFileName_workload:\t\n\t\t\tprint (\"Workload stage / Progress: %d%%\"% (count/l*100),end=\"\\r\")\t\n\t\t\tcount += 1\n\t\t\twith open(file_name_workload) as log_workload:\n\t\t\t\tfor event_workload in log_workload:\n\t\t\t\t\tc = event_workload.split()\n\t\t\t\t\tobjid = c[3]\n\t\t\t\t\tif c[2] != \"job\" or c[4] != \"JOBEND\":\n\t\t\t\t\t\tcontinue\n\t\t\n\t\t\t\t\tif objid == \"0\":\n\t\t\t\t\t\tprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\t\t\t\t\t\tprint(\"id 2224753: \"+c[5] +\" - \"+str(ceil(int(c[5])/16)) +\" - \"+str(ceil(int(c[6])/16)))\n\t\t\t\t\t\tprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\t\t\t\t\t\n\t\t\t\t\tcolumns_check = event_workload.split()\n\t\t\t\t\tif \"STARTTIME\" in event_workload:\n\t\t\t\t\t\tfor item in columns_check:\n\t\t\t\t\t\t\tif \"REQUESTEDTC\" in item.strip():\n\t\t\t\t\t\t\t\treq_nodes = ceil(int(item[12:])/16)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif c[5] == 0:\n\t\t\t\t\t\t\treq_nodes = int(c[5])\n\t\t\t\t\t\telse: req_nodes = ceil(int(c[6])/16)\n\t\t\t\t\t\n\t\t\t\t\t#if req_nodes != 0:\n\t\t\t\t\tworkload_node_req.append(objid + \" \" + str(req_nodes) + \" \" + file_name_workload)\n\t\t\t\n\t\t\t\n\t\twl = open(\"workload_filter.txt\", 'w')\n\t\tfor n in workload_node_req:\n\t\t\twl.write(n + \"\\n\")\n\t\twl.close()\n\t\t\t\n\t#############################################################\n\t#############################################################\n\t\n\t\n\t# start timer\n\tstartTime = time.clock()\n\tcount = 0\n\t#size of failure file\n\twith open(file_name) as f:\n\t\tl = len(f.readlines())\n\t\n\t#list to contein data\n\telements = []\n\tfor i in range(l):\n\t\telements.append([])\n\t\n\t\n\t#initializing dictionary to store node req and node fail\n\tfor i in range(l):\n\t\tdata_node_req_fail[i] = \"\"\n\t\n\twith open(file_name) as log:\n\t\t\n\t\tif line_count == 1:\n\t\t\tnext(log)\n\t\tfor line in log:\n\t\t\tprint (\"Filter stage / Progress: %d%%\"% (count/l*100),end=\"\\r\")\t\n\t\t\titem = line.split(\"|\")\n\t\t\tjobid = item[2].strip()\n\t\t\tdateAndTime = item[3].strip()\t\t\t\t\t\t\t\t\t\t\t\t# reading time\n\t\t\tmonth = dateAndTime[5:-12] \n\t\t\tall_nodes = item[9].strip().split()\n\t\t\tcount_nodes_failed_nodes = len(all_nodes)\n\t\t\t\n\t\t\tfound = False\n\t\t\tfor n in workload_node_req:\n\t\t\t\ti = n.split()\n\t\t\t\tif i[0].strip() == jobid:\n\t\t\t\t\t#data_node_req.append(i[1])\n\t\t\t\t\t#data_node_fail.append(count_nodes_failed_nodes)\n\t\t\t\t\t#data_node_req_fail[i[1]] = i[1] +\"|\"+str(count_nodes_failed_nodes) + \"|\" + i[2]\n\t\t\t\t\telements[count].append(int(i[1]))\n\t\t\t\t\telements[count].append(count_nodes_failed_nodes)\n\t\t\t\t\telements[count].append(month)\n\t\t\t\t\t\n\t\t\t\t\t#elements[count].append(i[2])\n\t\t\t\t\t#elements[count].append(jobid)\n\t\t\t\t\tfound = True\n\t\t\t\t\tbreak\n\t\t\tif found == False:\n\t\t\t\tprint(\"ID \" + jobid + \" does not found in workload dataset / \" )\n\t\t\tcount += 1\n\t\t\t\n\t\n\t#od = collections.OrderedDict(sorted(data_node_req_fail.items()))\n\tnew_elements = []\n\tfor n in elements:\n\t\tprint(n)\n\t\n\tnew_elements = filter(None, elements)#elements[1:]\n\tnew_elements = sorted(new_elements,key=lambda l:l[0])\n\t\n\t# print(\"-----------------------\")\n\t# print(new_elements)\n\tnfail = []\n\tnreq = []\n\tnode_month = []\n\tfor i in new_elements:\n\t\tnfail.append(i[1])\n\t\tnreq.append(i[0])\n\t\tnode_month.append(int(i[2]))\n\t\n\tprint(\"-----------------------\")\n\tprint(nfail)\n\t\n\tprint(\"-----------------------\")\n\tprint(nreq)\n\t\n\tfig = plt.figure()\n\tax = plt.gca()\n\tax.plot(nreq,nfail, '.', color='black')\n\tax.set_xscale('log')\n\tax.set_yscale('log')\n\tax.set_xlabel(\"Requested Node\")\n\tax.set_ylabel(\"Failed Node\")\n\tplt.savefig(\"PLOT_node_req_node_fail\" + \".pdf\")\n\t\n\tprint(\"\\nPLOT_node_req_node_fail\" + workload_dirName[5:-1] + \".pdf\")\n\t\n\tfig = plt.figure()\n\tax = plt.gca()\n\tcm = plt.cm.get_cmap('Paired')\n\tsc = plt.scatter(nreq, nfail, c=node_month, vmin=1, vmax=12, s=15, cmap=cm, linewidth=0.3, edgecolors=\"black\")\n\tcb = plt.colorbar(sc)\n\tcb.set_label(\"Month\")\n\t\n\tax.set_xscale('log')\n\tax.set_yscale('log')\n\tax.set_xlabel(\"Requested Node\")\n\tax.set_ylabel(\"Failed Node\")\n\tplt.savefig(\"PLOT_node_req_node_fail\" + \"_2.pdf\")\n\t\n\tprint(\"\\nPLOT_node_req_node_fail\" + workload_dirName[5:-1] + \".pdf\")\n\t\n\t\n\treturn \n\t\n\t\nif len(sys.argv) >= 1:\n\tfileName = sys.argv[1]\n\tworkload_dirName = sys.argv[2]\n\tfr_nodes(fileName, workload_dirName)\nelse:\n\tprint (\"ERROR, usage: %s \" % sys.argv[0])\n\tsys.exit(0)","sub_path":"plot_failednodes_vs_reqnodes.py","file_name":"plot_failednodes_vs_reqnodes.py","file_ext":"py","file_size_in_byte":5896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"11550351","text":"\"\"\"\nThe number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime\n\nThere are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.\n\nHow many circular primes are there below one million?\n\nhttps://projecteuler.net/problem=35\n\"\"\"\nfrom problems.base import BaseProblem\nfrom utils.utils import primes\n\n\nclass Problem35(BaseProblem):\n\n def run(self):\n primes_set = {str(prime) for prime in primes(1000000)}\n counter = 0\n for prime in primes_set:\n rotated_numbers = {prime[x:] + prime[:x] for x in range(len(prime))}\n if rotated_numbers.issubset(primes_set):\n counter += 1\n return counter\n","sub_path":"problems/problem_35.py","file_name":"problem_35.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"436474851","text":"\"\"\"Provide implementation for html parser CLI application which extracts all links from the given url.\"\"\"\n\n\nimport argparse\nimport requests\nimport csv\nfrom pycallgraph import PyCallGraph\nfrom pycallgraph.output import GraphvizOutput\nfrom url_validator import URLValidator\nfrom link_extractor import LinkExtractor\n\n\nclass ParserApplication:\n \"\"\"Representation of simple html parser application.\"\"\"\n\n def __init__(self, arg_parser, outfile=None):\n \"\"\"Return an ParserApplication object.\"\"\"\n # save CLI args parser\n self._arg_parser = arg_parser\n self._outfile = outfile\n self._args = None\n self._url = None\n self._response = None\n self._html_content = None\n self._link_extractor_obj = None\n self._links = []\n \n def _collect_args(self):\n \"\"\"Parse CLI arguments.\"\"\"\n # collect arg from CLI\n self._args = self._arg_parser.parse_args()\n \n def _is_valid_args(self) -> bool:\n \"\"\"Perform validation of CLI arguments.\"\"\"\n validation_result = False\n\n # if user entered url and it's valid url\n if self._args.url is not None and URLValidator(self._args.url).is_url_valid:\n validation_result = True\n \n return validation_result\n \n def _create_report(self):\n \"\"\"Write the results of parsing process to output file.\"\"\"\n if self._links:\n with open(self._outfile, 'w', newline='') as csvfile:\n # create csv output configuration\n cvswriter = csv.writer(csvfile,\n delimiter=',',\n quotechar='|',\n quoting=csv.QUOTE_MINIMAL)\n \n for idx, (link, stats, has_get_params) in enumerate(self._links):\n row = str(idx) + link + \" \" + str(stats) + \" \" + str(has_get_params)\n cvswriter.writerow(row)\n \n def execute(self):\n \"\"\"Perform execution of a parser application.\"\"\"\n self._collect_args()\n\n if self._is_valid_args():\n # save the target url\n self._url = self._args.url\n # get response\n self._response = requests.get(self._url)\n # obtain html code\n self._html_content = self._response.text\n\n # create instance of link ectractor\n self._link_extractor_obj = LinkExtractor(self._html_content)\n # parse\n self._link_extractor_obj.parse()\n\n links = []\n\n for link, stats in self._link_extractor_obj.link_stats.items():\n has_get_parameters = False\n\n raw_link, *rest = link.split(\"?\")\n\n if rest:\n has_get_parameters = True\n \n links.append((raw_link, stats, has_get_parameters))\n \n # save results\n self._links = links\n\n # if user secified the output file\n if self._outfile:\n # write results to the given file\n self._create_report()\n\n else:\n err_msg = \"Please enter a valid url for parsing.\\n\"\n\n if self._args.url is None:\n err_msg += \"You did not enter a url. Please use command line arguments.\"\n else:\n err_msg += F\"The url: {self._args.url} is invalid.\"\n \n print(err_msg)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\"Extracts all links (href attribute from all tags) from the given url.\")\n parser.add_argument('--url', help=\"url help\")\n parser_app = ParserApplication(parser, \"stats.csv\")\n parser_app.execute()","sub_path":"parser_application.py","file_name":"parser_application.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"4160165","text":"import os\nimport sys\nmachines = {}\n\ndef add_machine(name, compiler, c_flags, l_flags, gsl_dir):\n machine = {}\n machine['NAME'] = name\n machine['COMPILER'] = compiler\n machine['COMPILER_FLAGS'] = c_flags\n machine['LIB_FLAGS'] = l_flags\n machine['GSL_DIR'] = gsl_dir\n machines[name] = machine\n\ndef get_machine():\n for key in machines:\n if machines[key]['NAME'] in os.uname()[1]:\n #if os.uname()[1] == machines[key]['NAME']:\n return machines[key]\n print('UNKNOWN MACHINE ' + os.uname()[1])\n sys.exit()\n\nadd_machine(name='meade', \n compiler='h5pcc', \n #c_flags='-O3 -Wall -Werror -fdiagnostics-color -fopenmp',\n #l_flags='',\n c_flags='-O3 -std=c99 -Wall -fopenmp -g',\n l_flags='-lm -lgsl -lgslcblas',\n gsl_dir='/home/brryan/Software/gsl')\n\nadd_machine(name='bh',\n compiler='h5pcc',\n c_flags='-O3 -std=c99 -Wall -fopenmp -g',\n l_flags='-lm -lgsl -lgslcblas',\n gsl_dir='')\n\nadd_machine(name='bh21',\n compiler='h5pcc',\n c_flags='-O3 -std=c99 -Wall -fopenmp -g',\n l_flags='-lm -lgsl -lgslcblas',\n gsl_dir='')\n\nadd_machine(name='bh27',\n compiler='h5pcc',\n c_flags='-O3 -std=c99 -Wall -fopenmp -g',\n l_flags='-lm -lgsl -lgslcblas',\n gsl_dir='')\n\nadd_machine(name='lmc',\n compiler='h5pcc',\n c_flags='-O3 -std=c99 -Wall -fopenmp -g',\n l_flags='-lm -lgsl -lgslcblas',\n gsl_dir='')\n\nadd_machine(name='stampede2',\n compiler='h5pcc',\n c_flags='-O3 -std=c99 -Wall -fopenmp -g',\n l_flags='-lm -lgsl -lgslcblas',\n gsl_dir='/opt/apps/intel17/gsl/2.3')\n\n","sub_path":"machines.py","file_name":"machines.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"36643669","text":"# Copyright (C) 2016 Joseph B. Bak-Colema\n#This software may be modified and distributed under the terms of the MIT \n#license. See the LICENSE file for details\nfrom __future__ import division, print_function, absolute_import\nimport h5py\nimport numpy as np\n\ndef read_field(path, field, subdir='fields'):\n \"\"\"\n Returns a specified field from a fovea output (.h5) file\n \n Parameters\n ----------\n path : str\n The absolute or relative path to the specified datafile\n field : str\n The name of the specific field\n subdir : str, default is 'field'\n The h5 subdirectory where the field is found. Usual output\n is found in 'field'\n \"\"\"\n hf = h5py.File(path)\n flist = hf[subdir] #Get a list of fields\n \n val_return = np.empty(flist[field].shape)#Create empty np array\n \n flist[field].read_direct(val_return) #Store in numpy array\n hf.close() #Close File\n\n return val_return\n\ndef view_fields(path,subdir='fields'):\n \"\"\"\n Returns a list of all fields contained within a fovea output\n \n path : str\n The absolute or relative path to the specified file (.h5)\n subdir : str, default 'fields'\n Where in the file all fields of interest are found\n \"\"\"\n\n hf = h5py.File\n hf = h5py.File(path)\n flist = hf[subdir]\n flist = [item for item in flist]\n \n return flist\n\ndef count_fish(path,check='x',idx=0):\n \"\"\"\n Returns the number of fish in a foveator file\n path : str\n The absolute or relative path to the specified datafile (.h5)\n check : str, default 'x'\n Which field to check for number of fish\n idx : int, default 0\n Which axis of check indicates the correct number of fish. \n \"\"\"\n \n test_dat = read_field(path, check)\n return np.shape(test_dat)[0]\n\ndef count_frames(path, check='x',idx=0):\n \"\"\"\n Returns the number of frames in a foveator file\n path : str\n The absolute or relative path to the specified datafile (.h5)\n check : str, default 'x'\n Which field to check for the length of the file\n idx : int, default 0\n Which axis of check indicates the correct number of fish. \n \"\"\"\n\n test_dat = read_field(path, check)\n return np.shape(test_dat)[1]\n\n\n","sub_path":"build/lib/foveator/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"259306493","text":"#!/usr/bin/python\nimport json\nimport os\nimport sys\n\nexecute_sql = '/home/ztron/app_software/wdl_script/execute_sql.sh'\n\n\ndef get_samples():\n sql = \"select s.status, s.sampleid, s.jobname, j.cromwellid, s.tmppath, s.samplename from bp_auto.t_dl_sample s left join bp_auto.t_dl_job j on s.jobname = j.jobname where status = 'completed' and s.configname like 'PFI%';\"\n lines = execute_sql([sql], True)[2:][:-2]\n for line in lines:\n tmp = line.split('|')\n sample_id = tmp[1].strip()\n cromwell_id = tmp[3].strip().split(\",\")[-1]\n path = tmp[4].strip()\n samplename = tmp[5].strip() if tmp[5].strip() else sample_id\n result_path = os.path.join(path) #, samplename)\n if not os.path.exists(result_path):\n print(result_path, \"not exists\")\n analysis_path = \"/storeData/ztron/analysis/pfi_test/%s/call-Pfi/execution/result/Result\" % cromwell_id\n\n if not os.path.exists(analysis_path):\n print(result_path, \"analysis path not exists\")\n\n cmd = \"cp -fr %s/* %s\" % (analysis_path, result_path)\n print(cmd)\n\n\ndef execute_sql(sqls, readlines=False):\n with open(\"temp.sql\", 'w') as fh:\n fh.write(\"\\n\".join(sqls))\n cmd = \"sh /home/ztron/app_software/wdl_script/execute_sql.sh temp.sql\"\n fh = os.popen(cmd, 'r')\n if readlines:\n r = fh.readlines()\n else:\n r = fh.read()\n print(\"execute log: \" + str(r))\n fh.close()\n return r\n\nget_samples()","sub_path":"installer/migration_pfi_result.py","file_name":"migration_pfi_result.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"624723078","text":"import numpy as np\nnp.random.seed(1000)\nncases = 8\n\ndef clean(data, ncases):\n\tX = np.delete(data, 0, 0)\n\t(rows, cols) = X.shape\n\tY = X[:,cols-1]\n\tX = np.delete(X, cols-1,1)\n\tX = X.astype('float32')\n\treturn (X,Y) \n\n#train data\ndata = np.genfromtxt('output/train/train.csv', delimiter = ';')\n(X_train,Y_train) = clean(data, ncases)\n\n#test data\ndata = np.genfromtxt('output/test/test.csv', delimiter = ';')\n(X_test, Y_test) = clean(data, ncases)\ndel data\n\nfrom sklearn import svm\nmodel = svm.SVC(\n\tprobability = True,\n\tkernel = 'rbf',\n\tC = 1,\n\tgamma = 0.0001\n)\nmodel = model.fit(X_train, Y_train)\n\n\n#test the model\nfrom sklearn.metrics import accuracy_score, log_loss\nY_pred = model.predict(X_train)\nY_prob = model.predict_proba(X_train)\nprint('The accuracy obtained for train data is {:.4f} and the cross entropy is {:.4f}'\n\t.format(accuracy_score(Y_train, Y_pred), \n\tlog_loss(Y_train,Y_prob)))\n\nY_pred = model.predict(X_test)\nY_prob = model.predict_proba(X_test)\nprint('The accuracy obtained for test data is {:.4f} and the cross entropy is {:.4f}'\n\t.format(accuracy_score(Y_test, Y_pred), \n\tlog_loss(Y_test,Y_prob)))\n\n#metrics of the model\nfrom sklearn.metrics import classification_report, confusion_matrix\nnames = ['case' + str(s) for s in range(0,ncases)]\nprint(classification_report(Y_test, Y_pred, target_names = names))\nprint(confusion_matrix(Y_test, Y_pred))\n\n#save the model\nfrom sklearn.externals import joblib\njoblib.dump(model, 'analysis/models/svm.pkl')\n","sub_path":"analysis/classify/kernelmethod.py","file_name":"kernelmethod.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"340800964","text":"import cx_Oracle\r\nimport csv\r\nimport codecs\r\n\r\nusername = 'TESTING'\r\npassword = '1111'\r\ndatabaseName = \"localhost/db11g\"\r\n\r\nconnection = cx_Oracle.connect (username,password,databaseName)\r\n\r\ncursor = connection.cursor()\r\n\r\ntables = [\"matches\", \"faction\", \"game_expansion\", \"player\"]\r\n\r\nfor i in tables:\r\n\tquery = (\"DELETE FROM \" + i)\r\n\tcursor.execute (query)\r\n\r\ndef transform_csv_data(raw_list):\r\n\taddons_dict = {\"WoL\":\"Wings of Liberty\", \"HotS\":\"Heart of the Swarm\", \"LotV\":\"Legacy of the Void\"}\r\n\traces_dict = {\"Z\":\"Zerg\", \"P\":\"Protoss\", \"T\":\"Terran\"}\r\n\tif (raw_list[2] == \"[winner]\"):\r\n\t\traw_list[2] = 1\r\n\telse:\r\n\t\traw_list[2] = 0\r\n\tfor i, j in addons_dict.items():\r\n\t\traw_list[3] = raw_list[3].replace(i, j)\r\n\tfor i, j in races_dict.items():\r\n\t\traw_list[6] = raw_list[6].replace(i, j)\r\n\t\traw_list[7] = raw_list[7].replace(i, j)\r\n\ttry:\r\n\t\tquery = '''INSERT INTO matches (match_id, match_date, victory_status, expansion_name, player1_name, player2_name, player1_faction, player2_faction) \r\n\t\t\tVALUES (:match_id, TO_DATE(:match_date,'mm-dd-yyyy'), :victory_status, :expansion_name, :player1_name, :player2_name, :player1_faction, :player2_faction)'''\r\n\t\tcursor.execute(query, raw_list)\r\n\texcept:\r\n\t\tprint(\"err\")\r\n\treturn raw_list \r\n\r\nplayers = set()\r\nmatches_SC = []\r\nfactions = [\"Zerg\", \"Protoss\", \"Terran\"]\r\nexpansions = [\"Wings of Liberty\", \"Heart of the Swarm\", \"Legacy of the Void\"]\r\n\r\n\r\nwith codecs.open(\"sc2-matches-history.csv\", \"r\", \"utf-8\") as file:\r\n line_count = 0\r\n converted = csv.reader(file)\r\n for line in converted:\r\n try:\r\n if line_count == 10000:\r\n break\r\n if line_count > 0:\r\n \tplayer1 = line[1]\r\n \tplayer2 = line[4]\r\n \tsingle_match = transform_csv_data([line_count, line[0], line[2], line[8], player1, player2, line[6], line[7]])\r\n \tmatches_SC.append(single_match)\r\n \tprint(single_match)\r\n \tplayers.add(player1)\r\n \tplayers.add(player2)\r\n line_count += 1\r\n except:\r\n continue\r\n\r\nfor i in factions:\r\n\tquery = (\"INSERT INTO faction(faction_name) VALUES (\\'\" + i + \"\\')\")\r\n\tcursor.execute (query)\r\nfor i in expansions:\r\n\tquery = (\"INSERT INTO game_expansion(expansion_name) VALUES (\\'\" + i + \"\\')\")\r\n\tcursor.execute (query)\r\nfor i in players:\r\n\ttry:\r\n\t\tquery = (\"INSERT INTO player(player_name) VALUES (\\'\" + i + \"\\')\")\r\n\t\tcursor.execute (query)\r\n\texcept:\r\n\t\tcontinue\r\n\r\n\r\n\r\n#query = '''INSERT INTO matches (match_id, match_date, victory_status, expansion_name, player1_name, player2_name, player1_faction, player2_faction) \r\n# VALUES (:match_id, TO_DATE(:match_date,'mm-dd-yyyy'), :victory_status, :expansion_name, :player1_name, :player2_name, :player1_faction, :player2_faction)'''\r\n\r\n#cursor.prepare(query)\r\n\r\n#cursor.executemany(query, matches_SC)\r\n\r\n#for mtch in matches_SC:\r\n# try:\r\n# cursor.execute(query, datum)\r\n# except:\r\n# \tcontinue\r\n\r\n\r\ncursor.close()\r\nconnection.commit()","sub_path":"kaggle_import.py","file_name":"kaggle_import.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"87503075","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. 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#\n\nfrom collections.abc import Iterable\nfrom typing import Any, List, Optional\n\nimport numpy as np\nimport pandas\nimport torch\nfrom torch.utils.data import Dataset, DistributedSampler\n\nfrom raydp.spark.context import save_to_ray\nfrom raydp.spark.resource_manager.exchanger import SharedDataset\nfrom raydp.spark.utils import BLOCK_SIZE_BIT, divide_blocks\n\n\nclass _Dataset(Dataset):\n def __init__(self,\n feature_columns: List[str] = None,\n feature_shapes: Optional[List[Any]] = None,\n feature_types: Optional[List[torch.dtype]] = None,\n label_column: str = None,\n label_type: Optional[torch.dtype] = None):\n \"\"\"\n :param feature_columns: the feature columns in df\n :param feature_shapes: the each feature shape that need to return when loading this\n dataset. If it is not None, it's size must match the size of feature_columns.\n If it is None, we guess all are scalar value and return all as a tensor when\n loading this dataset.\n :param feature_types: the feature types. All will be casted into torch.float by default\n :param label_column: the label column in df\n :param label_type: the label type. It will be casted into torch.float by default.\n \"\"\"\n super(_Dataset, self).__init__()\n self._feature_columns = feature_columns\n self._feature_shapes = feature_shapes\n self._feature_types = feature_types\n self._label_column = label_column\n self._label_type = label_type\n\n self._feature_tensor = None\n self._label_tensor = None\n\n def _check_and_convert(self):\n # convert to list for convenience\n if not isinstance(self._feature_columns, List):\n self._feature_columns = [self._feature_columns]\n\n if self._feature_shapes:\n if not isinstance(self._feature_shapes, list):\n self._feature_shapes = [self._feature_shapes]\n\n assert len(self._feature_columns) == len(self._feature_shapes), \\\n \"The feature_shapes size must match the feature_columns\"\n for i in range(len(self._feature_shapes)):\n if not isinstance(self._feature_shapes[i], Iterable):\n self._feature_shapes[i] = [self._feature_shapes[i]]\n\n if self._feature_types:\n if not isinstance(self._feature_types, list):\n self._feature_types = [self._feature_types]\n\n assert len(self._feature_columns) == len(self._feature_types), \\\n \"The feature_types size must match the feature_columns\"\n for i in range(len(self._feature_types)):\n assert all(isinstance(dtype, torch.dtype) for dtype in self._feature_types), \\\n \"All value in feature_types should be torch.dtype instance\"\n\n if not self._feature_shapes and self._feature_types:\n assert all(dtype == self._feature_types[0] for dtype in self._feature_types), \\\n \"All dtypes should be same when feature_shapes doesn't provide\"\n\n if not self._feature_types:\n self._feature_types = [torch.float] * len(self._feature_columns)\n\n if not self._label_type:\n self._label_type = torch.float\n\n def _convert_to_tensor(self, df):\n if self._feature_shapes:\n tensors = []\n for col, shape, dtype in zip(self._feature_columns, self._feature_shapes,\n self._feature_types):\n column = df[col].values\n if column.dtype == np.object:\n if isinstance(column[0], np.ndarray):\n column = np.stack(column)\n elif isinstance(column[0], (list, tuple)):\n column = list(column)\n else:\n raise Exception(\n f\"Column {col}'s type: {type(column[0])} is not supported. It must \"\n \"be numpy built in type or numpy object of (ndarray, list, tuple)\")\n\n t = torch.as_tensor(column, dtype=dtype)\n if shape != [0]:\n t = t.view(*(-1, *shape))\n tensors.append(t)\n self._feature_tensor = tensors\n else:\n feature_columns = (self._feature_columns if\n len(self._feature_columns) > 1 else self._feature_columns[0])\n feature_df = df[feature_columns].values\n t = torch.as_tensor(feature_df, dtype=self._feature_types[0])\n self._feature_tensor = [t]\n\n label_df = df[self._label_column].values\n self._label_tensor = torch.as_tensor(label_df, dtype=self._label_type)\n\n def _get_next(self, index):\n label = self._label_tensor[index]\n features = [tensor[index] for tensor in self._feature_tensor]\n return (*features, label)\n\n\nclass RayDataset(_Dataset):\n \"\"\"\n Store Spark DataFrame or koalas.DataFrame into ray object store and wrap into a torch\n Dataset which could be used by torch DataLoader.\n \"\"\"\n def __init__(self,\n df: Any = None,\n feature_columns: List[str] = None,\n feature_shapes: Optional[List[Any]] = None,\n feature_types: Optional[List[torch.dtype]] = None,\n label_column: str = None,\n label_type: Optional[torch.dtype] = None):\n \"\"\"\n :param df: Spark DataFrame or Koalas.DataFrame\n \"\"\"\n super(RayDataset, self).__init__(feature_columns, feature_shapes,\n feature_types, label_column, label_type)\n self._unresolved_shared_dataset: SharedDataset = None\n self._resolved_shared_dataset: SharedDataset = None\n self._previous_block_index = -1\n\n self._check_and_convert()\n\n if df is not None:\n self._unresolved_shared_dataset = save_to_ray(df)\n\n def _resolve_with_indices(self,\n indices: List[int],\n plasma_store_socket_name: Optional[str]):\n resolved_shared_dataset = self._unresolved_shared_dataset.subset(indices)\n resolved_shared_dataset.set_plasma_store_socket_name(plasma_store_socket_name)\n resolved_shared_dataset.resolve()\n self._resolved_shared_dataset = resolved_shared_dataset\n\n def __getitem__(self, index):\n block_index = index >> BLOCK_SIZE_BIT\n block_inner_index = (block_index << BLOCK_SIZE_BIT) ^ index\n if block_index != self._previous_block_index:\n self._previous_block_index = block_index\n df = self._resolved_shared_dataset[block_index]\n self._convert_to_tensor(df)\n return self._get_next(block_inner_index)\n\n def __len__(self):\n \"\"\"Get the total size\"\"\"\n return self._unresolved_shared_dataset.total_size()\n\n def block_sizes(self) -> List[int]:\n \"\"\"Get the block sizes\"\"\"\n return self._unresolved_shared_dataset.partition_sizes()\n\n @classmethod\n def _custom_deserialize(cls,\n data_set: SharedDataset,\n feature_columns: List[str],\n feature_shapes: List[Any],\n feature_types: List[torch.dtype],\n label_column: str,\n label_type: torch.dtype):\n instance = cls(\n None, feature_columns, feature_shapes, feature_types, label_column, label_type)\n instance._unresolved_shared_dataset = data_set\n return instance\n\n def __reduce__(self):\n return (RayDataset._custom_deserialize,\n (self._unresolved_shared_dataset, self._feature_columns, self._feature_shapes,\n self._feature_types, self._label_column, self._label_type))\n\n\nclass BlockSetSampler(DistributedSampler):\n \"\"\"\n A distributed sampler for BlockSet.\n\n We will shuffle the blocks order and then shuffle the block inner if shuffle is set to True.\n \"\"\"\n def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, init_lazy=True):\n assert isinstance(dataset, RayDataset)\n self._args = (dataset, num_replicas, rank, shuffle)\n self._inited = False\n\n self._block_indices = None\n self._selected_indices = None\n\n if not init_lazy:\n self._init_lazy()\n\n def _init_lazy(self):\n \"\"\"\n This is a workaround because of ray sgd call initialize the data creator before of\n setup distributed components.\n \"\"\"\n if not self._inited:\n super(BlockSetSampler, self).__init__(*self._args)\n self._split_blocks()\n self._inited = True\n\n def _split_blocks(self):\n block_indexes, packed_selected_indexes = divide_blocks(\n self.dataset.block_sizes(), self.num_replicas, self.rank, self.shuffle)\n self._block_indices = block_indexes\n self._selected_indices = packed_selected_indexes\n\n def resolve(self, plasma_store_socket_name: Optional[str] = None):\n \"\"\"Manually trigger the underlying object transfer.\"\"\"\n self._init_lazy()\n self.dataset._resolve_with_indices(self._block_indices,\n plasma_store_socket_name)\n\n @property\n def block_indices(self):\n return self._block_indices\n\n def __iter__(self):\n self.resolve()\n # deterministically shuffle based on epoch\n np.random.seed(self.epoch)\n block_indices = list(range(len(self._block_indices)))\n if self.shuffle:\n np.random.shuffle(block_indices)\n\n indices = []\n for index in block_indices:\n tmp = self._selected_indices[index]\n tmp = np.copy(tmp)\n if self.shuffle:\n np.random.shuffle(tmp)\n indices += tmp.tolist()\n\n return iter(indices)\n\n def __len__(self):\n # if we use `if sampler` to determine whether the sampler is None,\n # it will call this method. This can be happened when the BlockSetSampler\n # used in the evaluation in ray TorchTrainer.\n self._init_lazy()\n return self.num_samples\n\n\nclass PandasDataset(_Dataset):\n \"\"\"\n A pandas dataset which support feature columns with different shapes.\n \"\"\"\n def __init__(self,\n df: pandas.DataFrame = None,\n feature_columns: List[str] = None,\n feature_shapes: Optional[List[Any]] = None,\n feature_types: Optional[List[torch.dtype]] = None,\n label_column: str = None,\n label_type: Optional[torch.dtype] = None):\n \"\"\"\n :param df: pandas DataFrame\n \"\"\"\n super(PandasDataset, self).__init__(feature_columns, feature_shapes,\n feature_types, label_column, label_type)\n self._check_and_convert()\n\n self._size = len(df)\n self._convert_to_tensor(df)\n\n def __getitem__(self, index):\n return self._get_next(index)\n\n def __len__(self):\n return self._size\n","sub_path":"python/raydp/spark/torch/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":12009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"5289702","text":"import random\r\nimport time\r\nfrom colorama import Fore, Back, Style\r\nimport haravasto as hv\r\nimport alkuvalikko as av\r\nimport tilastot as ti\r\n\r\n\r\ntila = {\r\n \"nakyva\": None, #Näkyvä kenttä\r\n \"piilossa\": None, #Piilossa oleva täytetty kenttä\r\n \"vapaat\": 0 #Avaamattomien ruutujen määrä\r\n}\r\n\r\n\r\nnapit = {\r\n hv.HIIRI_VASEN: \"vasen\",\r\n hv.HIIRI_KESKI: \"keski\",\r\n hv.HIIRI_OIKEA: \"oikea\"\r\n} \r\n\r\ndef kasittele_hiiri(x, y, nappi, muokkausnapit):\r\n \"\"\"\r\n Tätä funktiota kutsutaan kun käyttäjä klikkaa sovellusikkunaa hiirellä.\r\n Antaa hiiren sijainnin(x, y koordinaateilla) sekä painetun napin(hiiren vasen-, oikea tai keskinäppäin).\r\n \"\"\"\r\n x,s = divmod(x, 40)\r\n y,t = divmod(y, 40) \r\n #Pelin kulku: \r\n if tila[\"nakyva\"][y][x] != tila[\"piilossa\"][y][x] and nappi == hv.HIIRI_VASEN and tila[\"nakyva\"][y][x] != \"0\": #Ruudun aukaisu(ilman tulvatäyttöä)\r\n tila[\"nakyva\"][y][x] = tila[\"piilossa\"][y][x]\r\n ti.aika[\"vuorot\"] += 1\r\n if nappi == hv.HIIRI_OIKEA: #Merkkaus\r\n if tila[\"nakyva\"][y][x] == \" \":\r\n tila[\"nakyva\"][y][x] = \"f\"\r\n elif tila[\"nakyva\"][y][x] == \"f\":\r\n tila[\"nakyva\"][y][x] = \" \"\r\n if tila[\"piilossa\"][y][x] == \"x\" and nappi == hv.HIIRI_VASEN: #Miinaan osuminen(Häviö)\r\n tila[\"piilossa\"] == tila[\"nakyva\"]\r\n hv.lopeta()\r\n print(\"____________________\" + \"\\n\" + \"\\n\" + Fore.RED + \"ASTUIT MIINAAN! PELI OHI!\"+ \"\\n\")\r\n print(Style.RESET_ALL + \"____________________\")\r\n ti.aika[\"lopetus\"] = time.time()\r\n ti.tallenna(\"Häviö\", av.alkutiedot[\"miinat\"], av.alkutiedot[\"leveys\"], av.alkutiedot[\"korkeus\"], ti.aika[\"vuorot\"])\r\n if tila[\"piilossa\"][y][x] == \"0\" and nappi == hv.HIIRI_VASEN: #Tulvatäyttö\r\n tulvataytto(tila[\"nakyva\"], x, y, tila[\"piilossa\"])\r\n tila[\"vapaat\"] = 0 #Voitto tarkistus\r\n for j, ruudut in enumerate(tila[\"nakyva\"]): \r\n for i, ruudut in enumerate(ruudut):\r\n if tila[\"nakyva\"][j][i] == tila[\"piilossa\"][j][i]:\r\n pass\r\n else:\r\n tila[\"vapaat\"] += 1 \r\n if tila[\"vapaat\"] <= av.alkutiedot[\"miinat\"]: #Voitto(Avaamattomien ruutujen määrä = miinojen määrä\r\n hv.lopeta()\r\n print(\"____________________\"+ \"\\n\" + \"\\n\" + Fore.GREEN + \"KAIKKI MIINAT HARAVOITU! ONNEKSI OLKOON!\"+ \"\\n\")\r\n print(Style.RESET_ALL + \"____________________\")\r\n ti.aika[\"lopetus\"] = time.time()\r\n ti.tallenna(\"Voitto\", av.alkutiedot[\"miinat\"], av.alkutiedot[\"leveys\"], av.alkutiedot[\"korkeus\"], ti.aika[\"vuorot\"])\r\n\r\ndef piirra_kentta():\r\n \"\"\"\r\n Käsittelijäfunktio, joka piirtää kaksiulotteisena listana kuvatun miinakentän\r\n ruudut näkyviin peli-ikkunaan. Funktiota kutsutaan aina kun pelimoottori pyytää\r\n ruudun näkymän päivitystä.\r\n \"\"\"\r\n hv.tyhjaa_ikkuna()\r\n hv.piirra_tausta()\r\n hv.aloita_ruutujen_piirto()\r\n for y, ruutu in enumerate(tila[\"nakyva\"]):\r\n for x, ruutux in enumerate(ruutu):\r\n hv.lisaa_piirrettava_ruutu(tila[\"nakyva\"][y][x], (x*40), (y*40))\r\n hv.piirra_ruudut()\r\n hv.piirra_tekstia(\"\", 1, 1, vari=(0, 0, 0, 255), fontti=\"serif\", koko=32)\r\n\r\ndef laske_miinat(x, y, lista):\r\n \"\"\"\r\n Laskee valitun ruudun(x ja y koordinaattien mukaan annettu) ympärillä olevat miinat.\r\n \"\"\"\r\n korkeus = len(lista) - 1\r\n leveys = len(lista[0]) - 1\r\n n = 0\r\n if x == 0:\r\n xalku = x\r\n xloppu = x + 1\r\n elif x == leveys:\r\n xloppu = x\r\n xalku = x - 1\r\n else:\r\n xalku = x - 1\r\n xloppu = x + 1\r\n \r\n if y == 0:\r\n yalku = y\r\n yloppu = y + 1\r\n elif y == korkeus:\r\n yalku = y -1\r\n yloppu = y\r\n else:\r\n yalku = y - 1\r\n yloppu = y + 1\r\n for x in range(xalku, xloppu + 1):\r\n for y in range(yalku, yloppu + 1):\r\n if lista[y][x] == \"x\":\r\n n +=1\r\n return n\r\n \r\ndef miinoita(kentta, jaljella, n):\r\n \"\"\"\r\n Asettaa kentällä N kpl miinoja satunnaisiin paikkoihin.\r\n \"\"\"\r\n for miinat in range(n):\r\n ruutu = random.choice(jaljella)\r\n jaljella.remove(ruutu)\r\n kentta[ruutu[1]][ruutu[0]] = \"x\"\r\n \r\n \r\ndef numeroi(piilossaKentta):\r\n \"\"\"\r\n Numeroi ruudut sen mukaan kuinka monta miinaa on sen ympärillä(8 ruutua).\r\n \"\"\"\r\n for y, ruudut in enumerate(piilossaKentta):\r\n for x, ruutu in enumerate(ruudut):\r\n numero = laske_miinat(x, y, piilossaKentta)\r\n if piilossaKentta[y][x] == \"x\":\r\n pass\r\n else:\r\n piilossaKentta[y][x] = (\"{}\").format(numero)\r\n \r\n\r\ndef tulvataytto(nakyva, alku_x, alku_y, piilo):\r\n \"\"\"\r\n Avaa kentällä vierekkäin olevat tyhjien ruutujen alueet siten, että\r\n se aloitetaan annetusta x, y -pisteestä.\r\n \"\"\"\r\n lista = [[alku_x, alku_y]]\r\n while lista:\r\n pari = lista.pop()\r\n nakyva[pari[1]][pari[0]] = \"0\"\r\n korkeus = len(nakyva) - 1\r\n leveys = len(nakyva[0]) - 1\r\n x = pari[0]\r\n y = pari[1]\r\n if x == 0:\r\n xalku = x\r\n xloppu = x + 1\r\n elif x == leveys:\r\n xloppu = x\r\n xalku = x - 1\r\n else:\r\n xalku = x - 1\r\n xloppu = x + 1 \r\n if y == 0:\r\n yalku = y\r\n yloppu = y + 1\r\n elif y == korkeus:\r\n yalku = y - 1\r\n yloppu = y\r\n else:\r\n yalku = y - 1\r\n yloppu = y + 1\r\n for x in range(xalku, xloppu + 1):\r\n for y in range(yalku, yloppu + 1):\r\n if nakyva[y][x] == nakyva[pari[1]][pari[0]]:\r\n pass\r\n else: \r\n if piilo[y][x] == \"0\":\r\n lista.append((x, y))\r\n if piilo[y][x] == \"1\" or piilo[y][x] == \"2\" or piilo[y][x] == \"3\" or piilo[y][x] == \"4\" or piilo[y][x] == \"5\" or piilo[y][x] == \"6\" or piilo[y][x] == \"7\" or piilo[y][x] == \"8\":\r\n nakyva[y][x] = piilo[y][x]\r\n \r\n\r\ndef luo_kentta(leveys, korkeus):\r\n \"\"\"\r\n Luo näkyvän(tyhjän) kentän, piilossa olevan täytettävän kentän ja \r\n miinoitus funktioon tarvittavan jaljellä kentän.\r\n \"\"\"\r\n kentta = []\r\n piilossaKentta = []\r\n for rivi in range(korkeus):\r\n piilossaKentta.append([])\r\n for sarake in range(leveys):\r\n piilossaKentta[-1].append(\"0\")\r\n for rivi in range(korkeus):\r\n kentta.append([])\r\n for sarake in range(leveys):\r\n kentta[-1].append(\" \")\r\n jaljella = []\r\n for x in range(leveys):\r\n for y in range(korkeus):\r\n jaljella.append((x, y)) \r\n return kentta, piilossaKentta, jaljella \r\n \r\n\r\ndef main():\r\n hv.lataa_kuvat(\"spritet\")\r\n hv.luo_ikkuna(av.alkutiedot[\"leveys\"]*40, av.alkutiedot[\"korkeus\"]*40)\r\n hv.aseta_piirto_kasittelija(piirra_kentta)\r\n hv.aseta_hiiri_kasittelija(kasittele_hiiri)\r\n print(\"Peli käynnissä...\")\r\n hv.aloita()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n while av.valikko():\r\n tila[\"nakyva\"], tila[\"piilossa\"], jaljella = luo_kentta(av.alkutiedot[\"leveys\"], av.alkutiedot[\"korkeus\"]) #Luo kentät\r\n miinoita(tila[\"piilossa\"], jaljella, av.alkutiedot[\"miinat\"]) #Miinoittaa kentän\r\n numeroi(tila[\"piilossa\"]) #Asettaa numerot kentälle\r\n ti.aika[\"aloitus\"] = time.time() #Aloittaa keston laskun\r\n main()","sub_path":"Ville_Lahdenpera_Miinaharava_Python/miinaharava.py","file_name":"miinaharava.py","file_ext":"py","file_size_in_byte":7525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"52177237","text":"#encoding:utf-8\nnums=[6,11,7,9,4,2,1]\nn=len(nums)\nfor i in list(range(n)):\n for j in list(range(i,n)):\n if nums[i]>nums[j]:\n c=nums[j]\n nums[j]=nums[i]\n nums[i]=c\nprint(nums)\n\n'''\n功能ok, 继续加油\n'''\n\n\n#enconding:utf-8\n\nprint(max(nums))\nprint(min(nums))\n\na=max(nums)\nb=min(nums)\nend=n-1\nstar=0\nq=input('please write a number ')\nq=int(q)\nwhile True:\n middle = (end + star) // 2\n if qnums[middle]:\n star=middle+1\n middle=(end+middle)//2\n else :\n print(middle)\n break\n if star>end:\n print('no this')\n break\n\n'''\n功能ok,继续加油\n改进,找下代码中的无意义的代码并删除\n'''\n","sub_path":"02/wupeng/wupeng test2.py","file_name":"wupeng test2.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"364099624","text":"from typing import Dict, Optional, List\n\nimport numpy\nfrom overrides import overrides\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom allennlp.common.checks import ConfigurationError\nfrom allennlp.data import Vocabulary\nfrom allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder, Attention\nfrom allennlp.models.model import Model\nfrom allennlp.nn import InitializerApplicator, RegularizerApplicator\nfrom allennlp.nn import util\nfrom allennlp.training.metrics import CategoricalAccuracy\n\nfrom library.modules.global_attention import GlobalAttention\n\n@Model.register( \"han\" )\nclass HAN( Model ):\n \"\"\"\n Model of \"Hierarchical Attention Networks for Document Classification\"\n\n Parameters\n ----------\n vocab : ``Vocabulary``\n A Vocabulary, required in order to compute sizes for input/output projections.\n text_field_embedder : ``TextFieldEmbedder``\n Used to embed the ``tokens`` ``TextField`` we get as input to the model.\n inference_encoder: ``Seq2SeqEncoder``\n Used to encode the sentences.\n matching_layer: ``NeuralTensorNetwork``\n Used to compute similarities between two tensor\n pool_layer: ``kMaxPool``\n get k max value from each channel of feature maps and concatenate them.\n output_feedforward : ``FeedForward``\n output logits for classification task \n initializer : ``InitializerApplicator``, optional (default=``InitializerApplicator()``)\n Used to initialize the model parameters.\n regularizer : ``RegularizerApplicator``, optional (default=``None``)\n If provided, will be used to calculate the regularization penalty during training.\n \"\"\"\n def __init__( self, vocab: Vocabulary,\n text_field_embedder: TextFieldEmbedder,\n word_encoder: Seq2SeqEncoder,\n word_attention: GlobalAttention,\n sentence_encoder: Seq2SeqEncoder,\n sentence_attention: GlobalAttention,\n output_feedforward: FeedForward,\n initializer: InitializerApplicator = InitializerApplicator(),\n regularizer: Optional[RegularizerApplicator] = None ) -> None:\n super( HAN, self ).__init__( vocab, regularizer )\n\n self._text_field_embedder = text_field_embedder\n self._word_encoder = word_encoder\n self._word_attention = word_attention\n self._sentence_encoder = sentence_encoder\n self._sentence_attention = sentence_attention\n self._output_feedforward = output_feedforward\n self.metrics = {\n \"accuracy\": CategoricalAccuracy() \n }\n self._loss = nn.CrossEntropyLoss()\n\n initializer( self )\n\n @overrides\n def forward( self,\n file_id: List[str],\n doc: Dict[str, torch.LongTensor],\n label: torch.IntTensor = None ) -> Dict[str, torch.Tensor]:\n \"\"\"\n Parameters\n ----------\n file_id : List[str]\n From a ``MetadataField``, used to track the document\n doc: Dict[str, torch.LongTensor]\n From a ``ListField`` of ``TextField``, LongTensor has a shape of \n [batch_size, max_num_sentence, max_num_words]\n label : torch.IntTensor, optional (default = None)\n From a ``LabelField``\n\n Returns\n -------\n An output dictionary consisting of:\n\n label_logits : torch.FloatTensor\n A tensor of shape ``(batch_size, num_labels)`` representing unnormalised log\n probabilities of the label.\n label_probs : torch.FloatTensor\n A tensor of shape ``(batch_size, num_labels)`` representing probabilities of the\n label.\n loss : torch.FloatTensor, optional\n A scalar loss to be optimised.\n \"\"\"\n embedded_word = self._text_field_embedder( doc )\n word_mask = util.get_text_field_mask( doc, num_wrapping_dims = 1 )\n \n bs, ns, nw, ed = embedded_word.shape\n # combine the first two dimension\n embedded_word_combine = embedded_word.reshape( bs * ns, nw, ed )\n word_mask_combine = word_mask.reshape( bs * ns, nw )\n\n # encode each sentence in the batch, shape [bs*ns, nw, ed]\n encoded_word_combine = self._word_encoder( embedded_word_combine, word_mask_combine )\n\n # calculate attention weights, shape [bs*ns, 1, nw]\n word_attention_weights = self._word_attention( encoded_word_combine ).unsqueeze( 1 )\n\n # do attention to get sentence representations, [bs, ns, d]\n sentence_representation = word_attention_weights.bmm( encoded_word_combine ).squeeze( 1 ).reshape( bs, ns, -1 )\n\n sentence_mask = ( word_mask.sum( dim = 2 ) > 0 )\n # shape [bs, ns, d]\n encoded_sentence = self._sentence_encoder( sentence_representation, sentence_mask )\n # calculate attention weights, shape [bs, 1, ns]\n sentence_attention_weights = self._sentence_attention( encoded_sentence ).unsqueeze( 1 )\n\n doc_representation = sentence_attention_weights.bmm( encoded_sentence ).squeeze( 1 )\n\n label_logits = self._output_feedforward( doc_representation )\n label_probs = F.softmax( label_logits, dim = -1 )\n output_dict = {\"label_logits\": label_logits, \"label_probs\": label_probs}\n\n if label is not None:\n loss = self._loss( label_logits, label.long().view(-1) )\n for metric in self.metrics.values():\n metric( label_logits, label )\n output_dict[\"loss\"] = loss\n\n return output_dict\n\n @overrides\n def get_metrics( self, reset: bool = False ) -> Dict[str, float]:\n return {metric_name: metric.get_metric( reset )\n for metric_name, metric in self.metrics.items() }","sub_path":"library/models/HAN.py","file_name":"HAN.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"473298798","text":"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\nfrom model1 import Model1\nfrom dataset import Dataset\n\n\nif __name__ == '__main__':\n root = 'digit_data'\n train_root = os.path.join(root, 'train')\n val_root = os.path.join(root, 'val')\n\n num_epoch = 50\n learning_rate = .001\n\n model = Model1(10, learning_rate)\n\n train_dset = Dataset(train_root)\n val_dset = Dataset(val_root)\n train_dset.load_numpy_data(augment=True)\n val_dset.load_numpy_data(augment=True)\n\n train_images, train_labels = train_dset.images, train_dset.labels\n val_images, val_labels = val_dset.images, val_dset.labels\n\n assert len(train_images) == len(train_labels)\n assert len(val_images) == len(val_labels)\n\n len_train_data = len(train_images)\n len_val_data = len(val_images)\n\n train_loss_list = []\n train_acc_list = []\n\n val_loss_list = []\n val_acc_list = []\n\n for epoch in range(num_epoch):\n print('[{}/{}] '.format(epoch + 1, num_epoch), end='')\n train_loss = 0\n train_acc = 0\n\n val_loss = 0\n val_acc = 0\n\n for i in range(len_train_data):\n x_, y_ = train_images[i], train_labels[i]\n output = model.forward(x_)\n loss = model.cross_entropy(output, y_).sum() / len(y_)\n model.backward(x_, output, y_)\n\n if np.argmax(output) == np.argmax(y_):\n train_acc += 1\n\n train_loss += loss\n\n for i in range(len_val_data):\n x_, y_ = val_images[i], val_labels[i]\n output = model.forward(x_)\n loss = model.cross_entropy(output, y_).sum() / len(y_)\n\n if np.argmax(output) == np.argmax(y_):\n val_acc += 1\n\n val_loss += loss\n\n train_loss_list.append(train_loss / len_train_data)\n train_acc_list.append(train_acc / len_train_data)\n\n val_loss_list.append(val_loss / len_val_data)\n val_acc_list.append(val_acc / len_val_data)\n\n print(' {} {} {} {}'.format(train_loss_list[-1], train_acc_list[-1], val_loss_list[-1], val_acc_list[-1]))\n\n plt.figure(1)\n plt.title('Train/Validation Loss')\n plt.plot([i for i in range(num_epoch)], train_loss_list, 'r-', label='train')\n plt.plot([i for i in range(num_epoch)], val_loss_list, 'b-', label='val')\n plt.legend()\n\n plt.figure(2)\n plt.title('Train/Validation Accuracy')\n plt.plot([i for i in range(num_epoch)], train_acc_list, 'r-', label='train')\n plt.plot([i for i in range(num_epoch)], val_acc_list, 'b-', label='val')\n plt.legend()\n\n plt.show()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351692630","text":"import pandas as pd\n\nclass Trade(object):\n\n def __init__(self,ticker,trade_date,trade_price,trade, point_value):\n self.ticker = ticker\n self.trade_date = trade_date\n self.trade_price = trade_price\n self.trade = trade\n self.point_value = point_value\n self.quantity = None #need to change this -> how much of an asset we need i.e. how many lots\n self.trade_id = None\n self.trade_vector = pd.DataFrame()\n self.active = True\n self.size = None #this needs to be updated by position handler\n self.upnl, self.rpnl = 0,0\n self.close_date = None\n\n def updateTradeSize(self):\n self.size = self.trade * self.quantity * self.point_value #in spec\n\nclass Strategy(object):\n\n def __init__(self):\n self.instruments = ['ty','gld']\n self.indicators = ['ind']\n self._grid = pd.DataFrame()\n self.current_cob = None\n self._point_values = self.getPointValues()\n\n def getPointValues(self):\n d = {}\n for instrument in self.instruments:\n d[instrument] = 100000 * 0.0001 #would get this from db\n return d\n\n def dataHandler(self,tick):\n '''\n :param tick:\n :return: dict-> {ticker : Trade()}\n '''\n self._grid = self._grid.append(tick.data.to_dict(), ignore_index = True)\n self.current_cob = tick.cob\n grid = self.prepGrid()\n trade_set = {} #container for trades on the latest market data tick\n\n if grid.empty:\n return trade_set\n else:\n for ticker in self.instruments:#for each instrument generate a signal\n signal = self.generateSignal(grid,ticker)\n if signal:\n trade = Trade(ticker,self.current_cob,grid.loc[self.current_cob][ticker],signal,self._point_values[ticker])\n trade_set[ticker] = trade\n return trade_set\n\n def prepGrid(self):\n df = self._grid.copy(True)\n df.set_index(['cob'], inplace=True)\n return df\n\n def generateSignal(self,grid,ticker):\n if len(grid) > 2:\n price = grid.loc[self.current_cob][ticker]\n if price > 100:\n return 1 #long\n else:\n return -1 #short\n\n\nclass Tick(object):\n\n def __init__(self,cob,data):\n self.cob = cob\n self.data = data\n\n\nclass DataHandler(object):\n\n def __init__(self,start,end):\n self.start = start\n self.end = end\n self.history = pd.date_range(self.start,self.end,freq='B')\n\n self.data_handler = None\n\n self._instruments = None\n self._indicators = None\n\n self.tick_grid = None\n\n @staticmethod\n def createFrame(ticker):\n return pd.read_csv(r'.\\test_data\\{}.csv'.format(ticker), delimiter='|') # todo: needs to point to db\n\n @staticmethod\n def prepFrame(df, ticker):\n df['cob'] = pd.to_datetime(df['cob'])\n df.rename(columns = {'val': ticker}, inplace=True)\n df.set_index(['cob'], inplace=True)\n return df\n\n def createFrameList(self,lst):\n return [self.prepFrame(self.createFrame(l),l) for l in lst]\n\n def createTickGrid(self):\n instruments = pd.concat(self.createFrameList(self._instruments), axis=1)\n indicators = pd.concat(self.createFrameList(self._indicators), axis=1)\n df = instruments.merge(indicators, left_index=True, right_index=True)\n df['cob'] = df.index\n self.tick_grid = df\n\n def runLoop(self):\n for cob,frame in self.tick_grid.iterrows(): #iterate over each tick\n current_tick = Tick(cob,frame)\n self.data_handler(current_tick)\n\n\nclass Account(object):\n #keep track of what funds we have. precedent to size trades / manage risk\n def __init__(self,equity):\n self.equity = equity\n self.equity_df = pd.DataFrame()\n\n def update(self,tick,tradehandler):\n '''\n :param tick: Tick()\n :param tradehandler: TradeHandler()\n :return:\n '''\n try:\n upnl = tradehandler.upnl[tradehandler.upnl['cob'] == tick.cob]['upnl'].values[0]\n except:\n upnl = 0.0\n try:\n rpnl = tradehandler.rpnl[tradehandler.rpnl['cob'] == tick.cob]['rpnl'].values[0]\n except:\n rpnl = 0.0\n self.equity += rpnl\n mtm = self.equity + upnl\n self.equity_df = self.equity_df.append({'cob': tick.cob, 'equity': mtm}\n , ignore_index=True)\n\n\nclass RiskManager(object):\n\n def __init__(self,risk_per_trade = 0.002):\n self.rpt = risk_per_trade #per clenow set this to daily impact on portfolio e.g. 0.2% (scale out by sqrt(252) for annualized)\n self.trades = None\n\n def riskAllocation(self): #generic method - could use risk parity -> research\n '''\n :return: dict {ticker, float}\n '''\n nos_of_tickers = len(self.trades.keys())#equal weighting\n vol = 2.5 #e.g. average true range\n return {k:((1/nos_of_tickers) * self.rpt * (1 / vol)) for k in self.trades.keys()}\n\n\nclass PositionHandler(object):\n # needs a risk manager to decide risk appetite, risk limits, leverage\n def __init__(self,riskmanager):\n self.riskmanager = riskmanager\n\n def sizePositions(self,trades,account,existing_positions):\n '''\n :param trades: dict-> {ticker : Trade()}\n :param account: int\n :param existing_positions: dict-> {ticker: total quantity}\n :return: dict-> {ticker: Trade()}\n '''\n sized_positions = {}\n self.riskmanager.trades = trades #provide risk manager with trades\n allocations = self.riskmanager.riskAllocation() #problem!!\n for ticker,trade in trades.items():\n trade.quantity = (allocations[ticker] * account) / trade.point_value # nos of contract per clenow\n trade.updateTradeSize()\n sized_positions[ticker] = trade\n\n return sized_positions\n\nclass TradeHandler(object):\n\n def __init__(self):\n self.trade_book = {}\n self.upnl = pd.DataFrame(columns = ['cob','upnl'])\n self.rpnl = pd.DataFrame(columns = ['cob', 'rpnl'])\n self.latest_trade = {}\n self.current_positions = {}\n # assign portfolio\n\n def updateTrades(self,tick):\n upnl = 0; rpnl = 0\n active_trade_ids, active_trades = self.getActiveTrades()\n if active_trade_ids:\n for active_trade in active_trade_ids:\n trade = active_trades[active_trade]\n if trade.trade == self.latest_trade[trade.ticker].trade: #e.g. if latest is long and this trade is long\n trade.upnl = self.pnl(tick.data[trade.ticker],trade.trade_price,trade.size)\n trade.trade_vector = trade.trade_vector.append({'cob':tick.cob,'tick':tick.data[trade.ticker],\n 'upnl':trade.upnl,'rpnl':0}\n , ignore_index = True)\n upnl += trade.upnl\n else: #e.g. if latest trade is long and this is short we would need to close out and realize pnl.\n trade.rpnl = self.pnl(tick.data[trade.ticker], trade.trade_price, trade.size)\n trade.trade_vector = trade.trade_vector.append({'cob':tick.cob,'tick':tick.data[trade.ticker],\n 'upnl':0,'rpnl':trade.rpnl}\n , ignore_index = True)\n trade.active = False #close trade\n trade.close_date = tick.cob #set close date\n rpnl += trade.rpnl\n self.upnl = self.upnl.append({'cob':tick.cob,'upnl':upnl}, ignore_index = True)\n self.rpnl = self.rpnl.append({'cob': tick.cob, 'rpnl': rpnl}, ignore_index=True)\n #update current_positions\n\n @staticmethod\n def pnl(current_val,original_val,trade_size):\n return (current_val - original_val) * trade_size\n\n def getActiveTrades(self):\n active_trades = {} #dict of active trades agnostic of ticker as we will each by trade_id\n active_trade_ids = [] #list of active trade ids\n if len(self.trade_book.items()):\n for ticker,trades in self.trade_book.items():\n active_trade_ids_by_ticker = []\n for trade in trades:\n if trade.active:\n active_trade_ids.append(trade.trade_id)\n active_trade_ids_by_ticker.append(trade.trade_id)\n active_trades[trade.trade_id] = trade\n active_trade_ids_by_ticker.sort(reverse = True)\n if active_trade_ids_by_ticker:\n self.latest_trade[ticker] = active_trades[max(active_trade_ids_by_ticker)] #get max trade id for a given ticker\n return active_trade_ids, active_trades\n else:\n return None,None\n\n def updatePositions(self):\n pass\n\nclass PerformanceAnalyst(object):\n pass\n\nclass Trader(object):\n\n def __init__(self,strategy,equity,risk_manager):\n self.strategy = strategy\n self._account = Account(equity)\n self._pos_handler = PositionHandler(risk_manager)\n self.trade_id = 1\n self._trade_handler = TradeHandler()\n self._market_data = pd.DataFrame()\n self.response = None\n\n def eventHandler(self,tick):\n '''\n Trader handles each cob dates data vector. Gets strategy to generate trades. Determines size of trades and updates positions.\n :param tick: dataframe\n :return: None\n '''\n self._market_data = self._market_data.append(tick.data.to_dict(), ignore_index=True)\n self.response = self.strategy.dataHandler(tick) #response is 1 or more trades to execute (or nothing)\n if len(self.response.keys()):\n #we need to determine position of each trade i.e. # of units. function of equity, weighting to instrument, existing positions\n sized_trades = self._pos_handler.sizePositions(self.response,self._account.equity,self._trade_handler.current_positions)\n #for ticker,trade in self.response.items(): #...in sized trades\n for ticker,trade in sized_trades.items():\n trade.trade_id = self.trade_id #assign trade id\n if self._trade_handler.trade_book.__contains__(ticker):\n self._trade_handler.trade_book[ticker].append(trade)\n else:\n self._trade_handler.trade_book[ticker] = [trade]\n self.trade_id += 1 #increment trade id for next trade\n self._trade_handler.updateTrades(tick)\n self._account.update(tick,self._trade_handler) #update account equity by using trade handlers pnl vector\n i = 1\n\n\n def resultGrid(self):\n result_df = self._market_data.merge(self._trade_handler.upnl, how = 'left', on = ['cob'])\n result_df = result_df.merge(self._trade_handler.rpnl, how ='left', on = ['cob'])\n result_df = result_df.merge(self._account.equity_df, how='left', on=['cob'])\n\n trade_results = []\n for ticker,trades in self._trade_handler.trade_book.items():\n for trade in trades:\n df = trade.trade_vector\n df['ticker'] = trade.ticker\n df['trade_id'] = trade.trade_id\n trade_results.append(df)\n result_df.to_csv(r'.\\test_data\\test_result.csv')\n\n trades_df = pd.concat(trade_results,axis=0)\n trades_df.to_csv(r'.\\test_data\\trade_results_by_id.csv')\n\n def startTrading(self,start,end):\n\n d = DataHandler(start,end)\n d._instruments = self.strategy.instruments\n d._indicators = self.strategy.indicators\n d.data_handler = self.eventHandler\n d.createTickGrid()\n d.runLoop()\n\n self.resultGrid()\n print('complete')\n\ndef main():\n #set strategy, equity, position sizing (portfolio)\n b = Trader(Strategy(),100000, RiskManager())\n b.startTrading('2019-01-01','2019-01-14')\n\nif __name__== \"__main__\":\n main()","sub_path":"tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":12277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161594348","text":"import re\nfrom operator import itemgetter\nimport argparse\n\ndef printer(name, listed):\n \n args.Outfile.write(str(name)+'\\t')\n\n indexes = [1,2,5,7,11,19]\n #1 = match\n #2 = % contigs match\n #5 = contigs\n #7 = dupe probe matches\n #11 = contigs removed for matching multiple contigs\n #19 = contigs removed for matching multiple UCE loci\n \n print_list = itemgetter(*indexes)(listed)\n print_list = list(print_list)\n print_list[1] = print_list[1].strip(\"()%\")\n\n string = '\\t'.join(map(str,print_list))\n args.Outfile.write(str(string)+'\\n')\n\n\nparser = argparse.ArgumentParser(description='Process output From phyluce_assembly_match_contigs_to_probes log file')\ngroup1 = parser.add_argument_group('Required Argument')\ngroup1.add_argument('Infile', type=argparse.FileType('r'), help='Location of the log file from the match contigs script')\ngroup2 = parser.add_argument_group('Optional Argument')\ngroup2.add_argument('Outfile', nargs='?', type=argparse.FileType('w'), help='Name of the outfile', default='Parsed.txt')\nargs = parser.parse_args()\n\nargs.Outfile.write('taxon'+'\\t'+ 'Loci'+'\\t'+'PercContigs'+'\\t'+'Contigs'+'\\t'+'DupeProbeMatch'+'\\t'+'RemovedMultiContigHits'+'\\t'+'RemovedMultiUCEHits'+'\\n')\n\nfor line in args.Infile:\n\n line = line.strip('\\;\\n')\n\n if re.search(', ', line):\n\n split_line = re.split(' - INFO - ', line)\n taxon_split = re.split(':', split_line[1])\n info_split = re.split(' ', taxon_split[1])\n\n printer(taxon_split[0], info_split)\n ","sub_path":"match_contigs_log_parse.py","file_name":"match_contigs_log_parse.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"26296349","text":"#take final data from MH_MCMC.py and extract final result\nfrom pylab import *\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\n#f = '20150928T2324_cp17544_long0.npz'\nf ='20140903T1918_cp17059_long1.npz'\n#f = '5000loglike_.1_.1,2,5,6,6,6,5_1,2,5,6,6,6,5_2,2,4,5,5,5,4_2,2,4,5,5,5,4_1,2,3,5,5,5,4_1,2,3,5,5,5,4.npz'\n#initial = np.array([1,2,5,6,6,6,5,1,2,5,6,6,6,5,2,2,4,5,5,5,4,2,2,4,5,5,5,4,1,2,3,5,5,5,4,1,2,3,5,5,5,4])\n#initial = np.array([1,2,4,5,5,4,4,3,3,3,4,5,4,3,1,1,2,5,3,4,3,1,2,3,4,5,6,4,2,2,3,4,5,5,4,2,3,5,7,6,5,4])\ninitial = np.zeros(42)\n#np.load(f).files #shows what categorexecfiies are saved in the file\nparams = np.load(f)['params']\n#plot loglike of parameter vs step number to find the burn in time\nmax_n = len(params)\nn = np.arange(max_n)\nplot(n, params[:,42], 'o')\nxlabel('Number of iterations')\nylabel('Log likelihood')\nmin_loglike = min(params[:,42])\nmax_loglike = max(params[:,42])\n\n#plot the variation of individual parameters over time\nf0, ax0 = subplots(7, 6, sharey = True, sharex = True, figsize = (10, 10))\nk = 0\nfor i in xrange(6):\n\tfor j in xrange(6, -1, -1):\n\t\tax0[j][i].locator_params(nbins=4)\n\t\tax0[j][i].scatter(n, params[:,k], s = 8, linewidth = .05)\n\t\tax0[j][i].plot([0,len(params)], [initial[k], initial[k]])\n\t\tax0[j][i].set_title('Charge ' + str(k+1), fontsize = 9)\n\t\tax0[j][i].set_xlim(0, max_n)\n\t\tax0[j][i].set_ylim(-2,10)\n\t\tk = k + 1\nax0[6][2].set_xlabel('Number of iterations')\nax0[3][0].set_ylabel('Charge [$\\mu$C]')\n\n#plot the variation of individual parameters against loglike square\nf2, ax2 = subplots(7, 6, sharey = True, sharex = True, figsize = (10, 10))\nk = 0\nfor i in xrange(6):\n\tfor j in xrange(6, -1, -1):\n\t\tim = ax2[j][i].scatter(params[:,42], params[:,k], c = n, s = 8, linewidth = .05)#cmap = 'Reds',\n\t\tax2[j][i].locator_params(nbins=4)\n\t\tax2[j][i].plot([min_loglike, max_loglike], [initial[k], initial[k]], c = 'b')\n\t\tax2[j][i].set_title('Charge ' + str(k+1), fontsize = 9)\n\t\tax2[j][i].set_xlim(min_loglike, max_loglike)\n\t\tax2[j][i].set_ylim(-2,10)\n\t\tk = k + 1\nax2[6][2].set_xlabel('Log likelihood')\nax2[3][0].set_ylabel('Charge [$\\mu$C]')\n\nf2.subplots_adjust(right=0.8)\ncbar_ax = f2.add_axes([0.825, 0.15, 0.01, 0.7])\nf2.colorbar(im, cax=cbar_ax, label = 'Event number')\n\nmax_loglike_arg = np.argmax(params[:,42])\nr = np.around(params[max_loglike_arg], decimals = 3)\nresult = r[:-1]\nresult = (result.reshape((6,7))).T\n\nprint(\"The lowest loglike is: {}\".format(params[max_loglike_arg][42]))\nprint('And the charge distribution with lowest loglike squared is:')\nfor row in reversed(result):\n\taligned_row = \"{:^8} {:^8} {:^8} {:^8} {:^8} {:^8}\".format(*row)\n\tprint(aligned_row)\n\nfor i in r:\n\tprint(\"%.1f,\" %i)\n\n'''\nclean = params\n# Print Monte Carlo estimate of parameters\na = np.arange(42)\nprint('Means: {}'.format(np.mean(clean[:,a], axis = 0)))\nprint('Sigma: {}'.format(np.std(clean[:,a], axis = 0)))\n\n# define a Gaussian\ndef gauss(x, A, mu, sigma):\n return A*numpy.exp(-(x-mu)**2/(2.*sigma**2))\n\n# plot histograms of individual params, fit a gaussian and report fitted mean\nf1, ax1 = subplots(5, 3, sharey = True, sharex = True, figsize = (5, 12))\nk = 0\nm = range(len(clean))\ngauss_fit = []\nfor i in xrange(3):\n\tfor j in xrange(4, -1, -1):\n\t\t#histogram data and fit a gaussian\n\t\thisto, bin_edges = np.histogram(clean[:,k], range = [0,10], bins = 20)\n\t\terrors = np.sqrt(histo)\n\t\t#if item == 0, error = 1 and if less than 5 events in the bin, error = number of events in the bin\n\t\tfor ind, item in enumerate(histo):\n\t\t\tif item == 0:\n\t\t\t\tnp.put(errors, ind, 1)\n\t\t\telif item < 5:\n\t\t\t\tnp.put(errors, ind, item)\n\t\tp0 = [np.amax(histo), mean(clean[:,k]), 0.5]\n\t\ttry:\n\t\t\tpfit, pcov = curve_fit(gauss, bin_edges[:-1], histo, p0 = p0, sigma = errors)\n\t\t\tgauss_fit.append(pfit[1])\n\t\texcept RuntimeError:\n\t\t\tgauss_fit.append(0)\n\n\t\tax1[j][i].hist(clean[:,k], bins = 20, histtype = 'step', lw = 2, range = [0,10])\n\t\txx = np.linspace(0,10, 50)\n\t\tax1[j][i].plot(xx, gauss(xx, *pfit))\n\t\tax1[j][i].set_title('Charge ' + str(k+1))\n\t\tk = k + 1\nprint('The gauss fit means: {}'.format(gauss_fit))\n'''\n\n# Convergence checks: there are no theoretical criteria for convergence\n# Burn-in perion: reject the first samples to reduce dependence on the first point\t\n# Run multiple chains from different starting points and check that results are the same\n# Discard first half of MCMC chain and thin out the rest to reduce autocorrelations\n","sub_path":"run4/analyze_MH_6x7.py","file_name":"analyze_MH_6x7.py","file_ext":"py","file_size_in_byte":4379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"243400816","text":"#!/usr/bin/env python\nimport rospy\nimport tf\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Point\nfrom math import cos, sin, sqrt, atan2, tan\nimport numpy as np\nfrom numpy import array, dot\nfrom numpy.random import randn\nfrom filterpy.kalman import ExtendedKalmanFilter as EKF\nimport matplotlib.pyplot as plt\n\nclass LocalizeEKF(EKF):\n def __init__(self, dt, wheelbase):\n EKF.__init__(self, 3, 2, 2)\n rospy.init_node('ekf', anonymous=True)\n #self.sub = rospy.Subscriber('/odom', Odometry, self.getOdom)\n self.pub = rospy.Publisher('/odom_ekf', Odometry, queue_size=0)\n self.tf_br = tf.TransformBroadcaster()\n self.dt = dt\n self.wheelbase = wheelbase\n self.OdomFiltered = Odometry()\n self.m = array([[0,0]])\n self.u = array([.0, .0])\n self.PP = np.mat(np.diag([0.0]*3))\n rospy.wait_for_message(\"/odom\", Odometry)\n rospy.sleep(1)\n \n def getOdom(self):\n data = rospy.wait_for_message(\"/odom\", Odometry)\n x = data.pose.pose.position.x\n y = data.pose.pose.position.y\n self.original_quat = data.pose.pose.orientation\n \n b = np.array([[x,y]]) \n \n self.m = np.concatenate((self.m, b), axis=0)\n self.m = np.delete(self.m, 0, 0)\n self.u = array([data.twist.twist.linear.x, data.twist.twist.angular.z])\n \n def publishOdom(self, x, y): \n self.OdomFiltered.header.stamp = rospy.Time.now()\n self.OdomFiltered.header.frame_id = '/odom_ekf'\n self.OdomFiltered.child_frame_id = '/map'\n\n self.OdomFiltered.pose.pose.position = Point(x.item(0), y.item(0), 0)\n self.OdomFiltered.pose.pose.orientation = self.original_quat\n\n \n p_cov = np.array([0.0]*36).reshape(6,6)\n\n # position covariance\n p_cov[0:2,0:2] = self.PP[0:2,0:2]\n # orientation covariance for Yaw\n # x and Yaw\n p_cov[5,0] = p_cov[0,5] = self.PP[2,0]\n # y and Yaw\n p_cov[5,1] = p_cov[1,5] = self.PP[2,1]\n # Yaw and Yaw\n p_cov[5,5] = self.PP[2,2]\n \n self.OdomFiltered.pose.covariance = tuple(p_cov.ravel().tolist())\n\n pos = (self.OdomFiltered.pose.pose.position.x,\n self.OdomFiltered.pose.pose.position.y,\n self.OdomFiltered.pose.pose.position.z)\n\n ori = (self.OdomFiltered.pose.pose.orientation.x,\n self.OdomFiltered.pose.pose.orientation.y,\n self.OdomFiltered.pose.pose.orientation.z,\n self.OdomFiltered.pose.pose.orientation.w)\n rospy.loginfo(self.OdomFiltered)\n self.pub.publish(self.OdomFiltered)\n\n self.tf_br.sendTransform(pos, ori, self.OdomFiltered.header.stamp, self.OdomFiltered.child_frame_id, self.OdomFiltered.header.frame_id)\n \n def getU(self):\n return self.u\n \n def getM(self):\n return self.m\n \n def predict(self, u): \n self.x = self.move(self.x, u, self.dt)\n\n h = self.x[2, 0]\n v = u[0]\n steering_angle = u[1]\n\n dist = v*self.dt\n\n if abs(steering_angle) < 0.0001:\n r = 1.e-30\n else:\n r = self.wheelbase / tan(steering_angle)\n \n b = dist / self.wheelbase * tan(steering_angle)\n \n sinh = sin(h)\n sinhb = sin(h + b)\n cosh = cos(h)\n coshb = cos(h + b)\n\n F = array([[1., 0., -r*cosh + r*coshb],\n [0., 1., -r*sinh + r*sinhb],\n [0., 0., 1.]])\n\n w = self.wheelbase\n\n F = array([[1., 0., (-w*cosh + w*coshb)/tan(steering_angle)],\n [0., 1., (-w*sinh + w*sinhb)/tan(steering_angle)],\n [0., 0., 1.]])\n\n V = array(\n [[-r*sinh + r*sinhb, 0],\n [r*cosh + r*coshb, 0],\n [0, 0]])\n\n t2 = tan(steering_angle)**2\n V = array([[0, w*sinh*(-t2-1)/t2 + w*sinhb*(-t2-1)/t2],\n [0, w*cosh*(-t2-1)/t2 - w*coshb*(-t2-1)/t2],\n [0,0]])\n\n t2 = tan(steering_angle)**2\n\n a = steering_angle\n d = v*self.dt\n it = self.dt*v*tan(a)/w + h\n\n V[0,0] = self.dt*cos(d/w*tan(a) + h)\n V[0,1] = (self.dt*v*(t2+1)*cos(it)/tan(a) -\n w*sinh*(-t2-1)/t2 +\n w*(-t2-1)*sin(it)/t2)\n\n V[1,0] = self.dt*sin(it)\n\n V[1,1] = (d*(t2+1)*sin(it)/tan(a) + w*cosh/t2*(-t2-1) -\n w*(-t2-1)*cos(it)/t2)\n\n V[2,0] = self.dt/w*tan(a)\n V[2,1] = d/w*(t2+1)\n\n M = array([[0.1*v**2, 0],\n [0, sigma_steer**2]])\n\n self.P = dot(F, self.P).dot(F.T) + dot(V, M).dot(V.T)\n \n def move(self, x, u, dt):\n dt = dt/10.\n h = x[2, 0]\n v = u[0]\n steering_angle = u[1]\n\n dist = v*dt\n\n if abs(steering_angle) < 0.0001:\n # approximate straight line with huge radius\n r = 1.e-30\n else:\n r = self.wheelbase / tan(steering_angle) # radius\n \n b = dist / self.wheelbase * tan(steering_angle)\n \n\n sinh = sin(h)\n sinhb = sin(h + b)\n cosh = cos(h)\n coshb = cos(h + b)\n to_return = x + array([[-r*sinh + r*sinhb],\n [r*cosh - r*coshb],\n [b]])\n #rospy.loginfo(to_return)\n return to_return \n \n def H_of(self, x, p):\n \"\"\" compute Jacobian of H matrix where h(x) computes the range and\n bearing to a landmark for state x \"\"\"\n \n px = p[0]\n py = p[1]\n hyp = (px - x[0, 0])**2 + (py - x[1, 0])**2\n dist = np.sqrt(hyp)\n \n H = array(\n [[-(px - x[0, 0]) / dist, -(py - x[1, 0]) / dist, 0],\n [ (py - x[1, 0]) / hyp, -(px - x[0, 0]) / hyp, -1]])\n return H\n\n def Hx(self, x, p):\n \"\"\" takes a state variable and returns the measurement that would\n correspond to that state.\n \"\"\"\n px = p[0]\n py = p[1]\n dist = np.sqrt((px - x[0, 0])**2 + (py - x[1, 0])**2)\n \n Hx = array([[dist],\n [atan2(py - x[1, 0], px - x[0, 0]) - x[2, 0]]])\n return Hx\n \n def normalize_angle(self, x, index):\n if x[index] > np.pi:\n x[index] -= 2*np.pi\n if x[index] < -np.pi:\n x[index] = 2*np.pi\n \n def residual(self, a,b):\n y = a - b\n self.normalize_angle(y, 1)\n return y\n\nif __name__ == '__main__':\n sigma_r = 0.01\n sigma_h = np.radians(1)\n sigma_steer = np.radians(1)\n wheelbase = 0.1\n frequency = 10\n dt = 1/frequency\n \n ekf = LocalizeEKF(dt, wheelbase)\n \n ekf.P = np.diag([1., 1., 1.])\n ekf.R = np.diag([sigma_r**2, sigma_h**2])\n c = [0, 1, 2]\n \n xp = ekf.x.copy()\n \n rate = rospy.Rate(frequency)\n\n ekf.getOdom()\n \n ekf.x = array([[0, 0, 0]]).T\n \n while not rospy.is_shutdown():\n ekf.getOdom()\n u = ekf.getU()\n m = ekf.getM()\n ekf.predict(u)\n #rospy.loginfo(u)\n for lmark in m:\n d = sqrt((lmark[0] - xp[0, 0])**2 + (lmark[1] - xp[1, 0])**2) + randn()*sigma_r\n a = atan2(lmark[1] - xp[1, 0], lmark[0] - xp[0, 0]) - xp[2, 0] + randn()*sigma_h\n z = np.array([[d], [a]])\n \n ekf.update(z, HJacobian=ekf.H_of, Hx=ekf.Hx, residual=ekf.residual, args=(lmark), hx_args=(lmark))\n\n ekf.publishOdom(ekf.x[0], ekf.x[1])\n rate.sleep() \n\n if rospy.is_shutdown():\n rospy.signal_shutdown('ekf')","sub_path":"src/ekf/ekf_uwb.py","file_name":"ekf_uwb.py","file_ext":"py","file_size_in_byte":7627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"452008905","text":"# coding:utf-8\n\n\"\"\"\nrequest请求类\n:author: huiwenhua\n:date: 2019-09-02\n\"\"\"\n\nimport requests\n\nclass Request():\n 'Request 类'\n\n def __init__(self):\n pass\n\n @classmethod\n def get(cls, url, params={}, headers={}):\n \"\"\"\n get 请求\n \"\"\"\n try:\n r = requests.get(url, params=params, headers=headers)\n json_r = r.json()\n return json_r\n except Exception as e:\n print(\"请求失败\",str(e))\n\n @classmethod\n def post(cls, url, params={}, headers={}):\n try:\n r = requests.post(url, data=params, headers=headers)\n json_r = r.json()\n return json_r\n except BaseException as e:\n print(\"请求失败!\", str(e))","sub_path":"utils/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"220427407","text":"import os\nimport nltk\n\n\ndef isquerytype(taglist):\n\tverbclasslist = ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']\n\tnounclasslist = ['NN', 'NNP', 'NNS', 'NNPS']\n\tif (containsverb(taglist, verbclasslist) and containsnoun(taglist, nounclasslist)):\n\t\treturn 1\n\telif (numnouns(taglist, nounclasslist)>1):\n\t\treturn 1\n\telse: \n\t\treturn 0\n\ndef containsverb(taglist, verbclasslist):\n\tfor tag in taglist:\n\t\tif tag in verbclasslist:\n\t\t\treturn 1\n\treturn 0\n\ndef containsnoun(taglist, nounclasslist):\n\tfor tag in taglist:\n\t\tif tag in nounclasslist:\n\t\t\treturn 1\n\treturn 0\n\ndef numnouns(taglist, nounclasslist):\n\tcounter = 0\n\tfor tag in taglist:\n\t\tif tag in nounclasslist:\n\t\t\tcounter+=1\n\treturn counter\n\n\n\nf = open(\"newqtags\", \"r+\")\ntokenized = []\npostags = []\ntagclasses = []\nclasslist = []\nflag = 0\nhashtags = []\nnountags = []\nnountagspos = []\n\nfor line in f:\n\thashtags.append(line)\n\ttokenized.append(nltk.word_tokenize(line))\n\t\nfor tags in tokenized:\n\tpostags.append(nltk.pos_tag(tags))\n\ni = 0\n\nfor item in postags:\n\tfor wordtagtuple in item:\n\t\tclasslist.append(wordtagtuple[1])\n\t\tif(isquerytype(classlist)):\n\t\t\tflag = 1\n\tif(flag ==1 ):\n\t\tnountags.append(hashtags[i])\n\t\tnountagspos.append(' '.join(classlist))\n\tclasslist = []\n\ti += 1\n\tflag = 0\n\nfw = open(\"querytags\", \"w+\")\n\ni = 0\nfor line in nountags:\n\tfw.write(nountags[i]+\" \"+nountagspos[i]+'\\n')\n\ti+=1\n","sub_path":"postag1.py","file_name":"postag1.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"543024425","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 21 11:36:46 2019\n\n@author: x270\n\"\"\"\n\nimport sqlite3\n\nsqlite_file = '/home/x270/Desktop/Python/roster.sqlite' # name of the sqlite database file\ntable_name = 'employees' # name of the table to be created\nid_column = 'employeeid' # name of the PRIMARY KEY column\nnew_column1 = 'skill' # name of the new column\nnew_column2 = 'Available' # name of the new column\ndate_col = 'date'\ntime_col = 'time'\ndate_time_col = 'date_time'\ncolumn_type = 'TEXT' # E.g., INTEGER, TEXT, NULL, REAL, BLOB\ndefault_val = 'Yes' # a default value for the new column rows\n\n# Connecting to the database file\nconn = sqlite3.connect(sqlite_file)\nc = conn.cursor()\n\nc.execute(\"ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}\"\\\n .format(tn = table_name, cn=id_column, ct=column_type))\n\n# A) Adding a new column without a row value\nc.execute(\"ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}\"\\\n .format(tn=table_name, cn=new_column1, ct=column_type))\n\n# B) Adding a new column with a default row value\nc.execute(\"ALTER TABLE {tn} ADD COLUMN '{cn}' {ct} DEFAULT '{df}'\"\\\n .format(tn=table_name, cn=new_column2, ct=column_type, df=default_val))\n\n# B) Adding a new column with a date\nc.execute(\"ALTER TABLE {tn} ADD COLUMN '{cn}' {ct} DEFAULT '{df}'\"\\\n .format(tn=table_name, cn=date_col, ct=column_type, df=default_val))\n# B) Adding a new column with a default row value\nc.execute(\"ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}\"\\\n .format(tn=table_name, cn=time_col, ct=column_type))\n# B) Adding a new column with a default row value\nc.execute(\"ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}\"\\\n .format(tn=table_name, cn=date_time_col, ct=column_type))\n\n\n\n\n# Committing changes and closing the connection to the database file\nconn.commit()\nconn.close()\n","sub_path":"add_new_column.py","file_name":"add_new_column.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"113738957","text":"#lire le fichier jenkins.dat avec la commande with open(filename) as file\n#ouvrir un fichier .ret en ecriture\n#avec une liste comprehension selectionner que les lignes qui contiennent WARNING\n#ecrire toutes ces lignes dans le fichier .ret\n\n#files setting\nfile = open(\"jenkins.dat\",\"r\")\noutput = open(\"Tran_Olivier.ret\", \"w\")\n\n#split file in lines\ndata = file.read().split(\"\\n\")\n\n#split lines in sub elements\nfor x in range(len(data)):\n\n data.append(data[x].split(\"\\t\"))\n\n#looking for warnings and writing in new file\nfor x in range(len(data)):\n\n for y in range(len(data[x])):\n\n if data[x][y].find(\"WARNING\") != -1:\n\n line = str(data[x]).replace(\"[\",\"\").replace(\"]\",\"\")\n print(\"warning found:\",line)\n output.write(line)\n\n\n\nfile.close()\noutput.close()","sub_path":"Read_jenkins_OT.py","file_name":"Read_jenkins_OT.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"547047525","text":"from unittest import mock\nfrom datetime import datetime\n\nfrom flask import url_for\n\nfrom app import db\nfrom app.models.views import FlatDBView\nfrom app.models import User, DBRequest\nfrom app.flats.views import FlatsSearchView\nfrom app.flats.forms import FlatForm\nfrom database.models import *\n\nfrom tests.app import AppTestCase\n\n\nclass FlatsSearchViewTest(AppTestCase):\n config = \"testing_psql\"\n\n def create_offer_with_flats(self):\n RegionType.insert(db.session)\n\n self.region = Region(name=\"District\", type=RegionType.get(db.session, \"kraj\"))\n self.city = Region(\n name=\"City\", type=RegionType.get(db.session, \"miasto\"),\n parent=self.region\n )\n db.session.add_all([self.region, self.city])\n\n offer = Offer(\n title=\"Test Offer\", end_date=datetime(2019, 1, 1),\n region=self.region,\n latitude=52.1723808620083,\n longitude=20.9960452687791\n )\n offer2 = Offer(\n title=\"Fake Offer\", end_date=datetime(2015, 6, 1),\n region=self.city,\n latitude=52.2301773353402,\n longitude=20.9416645634342\n )\n dbtrace = DBUpdateTrace(timestamp=datetime(2015, 1, 1))\n db.session.add_all([\n offer, offer2, dbtrace,\n Flat(\n number=\"1\", fid=\"1\", area=27.10, rooms=1, floor=0, offer=offer,\n garden=\"5.10\", status=Status(\n value=Status.AVAILABLE, dbtrace=dbtrace, \n timestamp=dbtrace.timestamp\n )\n ),\n Flat(\n number=\"2\", fid=\"2\", area=56.50, rooms=3, floor=1, offer=offer,\n garden=\"0.0\", balcony=\"5.50\", status=Status(\n value=Status.AVAILABLE, dbtrace=dbtrace,\n timestamp=dbtrace.timestamp\n )\n ),\n Flat(\n number=\"3\", fid=\"3\", area=70.30, rooms=3, floor=1, offer=offer,\n balcony=\"10.5\", status=Status(\n value=Status.SOLD, dbtrace=dbtrace,\n timestamp=dbtrace.timestamp\n )\n ),\n Flat(\n number=\"1\", fid=\"1\", area=50.50, rooms=3, floor=1, offer=offer2,\n status=Status(\n value=Status.AVAILABLE, dbtrace=dbtrace,\n timestamp=dbtrace.timestamp\n )\n )\n ])\n db.session.commit()\n OfferReport.update_or_create(db.session, dbtrace, offer)\n DBUpdateReport.update_or_create(db.session, dbtrace)\n db.session.commit()\n return offer\n\n def setUp(self):\n super().setUp()\n self.offer = self.create_offer_with_flats()\n FlatDBView.refresh(db.session, False)\n\n def test_render_proper_template(self):\n self.client.get(url_for(\"flats.search\"))\n\n self.assert_template_used(\"flats/search.html\")\n\n def test_search_flats_with_get_request(self):\n self.client.get(\n url_for(\"flats.search\"),\n query_string={\n \"rooms[range]\": \"2;3\", \"garden\": \"None\",\n \"offer_id\": [str(self.offer.id)], \"action\": \"Szukaj\"\n }\n )\n\n flats = self.get_context_variable(\"flats\")\n self.assertEqual(len(flats), 1)\n\n flat_ref = db.session.query(Flat).filter(Flat.number == \"2\").one()\n self.assertEqual(flats[0].id, flat_ref.id)\n\n def test_search_flats_on_the_base_of_area(self):\n self.client.get(\n url_for(\"flats.search\"), \n query_string={\"area[range]\": \"50;60\"}\n ) \n\n flats = self.get_context_variable(\"flats\")\n\n self.assertEqual(len(flats), 2)\n\n def test_sort_results_ascending_by_flat_area(self):\n self.client.get(\n url_for(\"flats.search\"), \n query_string={\"area[range]\": \"50;60\", \"sort\": \"area\"}\n ) \n\n flats = self.get_context_variable(\"flats\")\n self.assertTrue(flats[0].area < flats[1].area) \n\n def test_sort_results_descending_by_flat_area(self):\n self.client.get(\n url_for(\"flats.search\"), \n query_string={\"area[range]\": \"50;60\", \"sort\": \"-area\"}\n ) \n\n flats = self.get_context_variable(\"flats\")\n self.assertTrue(flats[0].area > flats[1].area) \n\n def test_search_flats_on_the_base_of_floor(self):\n self.client.get(\n url_for(\"flats.search\"), \n query_string={\"floor[range]\": \";0\"}\n ) \n\n flats = self.get_context_variable(\"flats\")\n\n self.assertEqual(len(flats), 1)\n\n def test_search_flats_on_the_base_of_garden_availability(self):\n self.client.get(url_for(\"flats.search\"), query_string={\"garden\": \"True\"}) \n\n flats = self.get_context_variable(\"flats\")\n\n self.assertEqual(len(flats), 1)\n\n @mock.patch(\"app.flats.views.datetime\")\n def test_search_flats_from_offers_that_will_be_soon_complete(self, datetime_mock):\n datetime_mock.now.return_value = datetime(2015, 1, 1)\n self.client.get(\n url_for(\"flats.search\"), \n query_string={\"completion_time\": 12}\n ) \n\n flats = self.get_context_variable(\"flats\")\n\n self.assertEqual(len(flats), 1)\n\n def test_search_flats_from_regions(self):\n self.client.get(\n url_for(\"flats.search\"), \n query_string={\"region_id\": [str(self.region.id)]}\n )\n\n flats = self.get_context_variable(\"flats\")\n self.assertEqual(len(flats), 3)\n\n def test_search_flats_on_the_base_of_the_coordinates(self):\n self.client.get(\n url_for(\"flats.search\"), query_string={\n \"latitude\": 52.1764150988765,\n \"longitude\": 20.9911370201285,\n \"radius\": 1.5\n }\n )\n\n flats = self.get_context_variable(\"flats\")\n self.assertEqual(len(flats), 2)\n\n def test_limit_results_with_page_and_limit_params(self):\n self.client.get(\n url_for(\"flats.search\"), query_string={\n \"limit\": 1, \"page\": 1\n }\n )\n\n flats = self.get_context_variable(\"flats\")\n self.assertEqual(len(flats), 1)\n\n def test_search_returns_flats_without_attributes(self):\n '''\n There are flats in db without some attributes e.g. rooms. Range \n inputs are set be default to min-max range. Test whether default\n settings enable to search for flats without attributes.\n '''\n flat = Flat(\n number=\"5\", fid=\"5\", area=125.10, rooms=None, floor=0, \n offer=self.offer,\n garden=\"5.10\", status=Status(\n value=Status.AVAILABLE, \n dbtrace=DBUpdateTrace(timestamp=datetime(2017, 1, 1)), \n timestamp=datetime(2017, 1, 1)\n )\n )\n db.session.add(flat)\n FlatDBView.refresh(db.session, False)\n db.session.commit()\n\n self.client.get(\n url_for(\"flats.search\"), query_string={\n \"area[range]\": \"120;\", \"offer_id\": [str(self.offer.id)],\n \"action\": \"Szukaj\", \n \"rooms[range]\": \"%d;%d\" % (\n FlatsSearchView.range_filters_config[\"rooms\"][\"min\"],\n FlatsSearchView.range_filters_config[\"rooms\"][\"max\"]\n )\n\n }\n )\n\n flats = self.get_context_variable(\"flats\")\n self.assertEqual(len(flats), 1)\n self.assertEqual(flats[0].id, flat.id)\n\n def test_search_returns_flats_with_large_area(self):\n '''\n There are flats in db with especially high value of attributes. Range \n inputs are set be default to min-max range. Max value is considered\n in general as \"max or more\". Test whether is possible to search for\n huge apartments.\n '''\n flat = Flat(\n number=\"5\", fid=\"5\", area=255.10, rooms=None, floor=0, \n offer=self.offer,\n garden=\"5.10\", status=Status(\n value=Status.AVAILABLE, \n dbtrace=DBUpdateTrace(timestamp=datetime(2017, 1, 1)), \n timestamp=datetime(2017, 1, 1)\n )\n )\n db.session.add(flat)\n FlatDBView.refresh(db.session, False)\n db.session.commit()\n\n self.client.get(\n url_for(\"flats.search\"), query_string={\n \"offer_id\": [str(self.offer.id)],\n \"action\": \"Szukaj\", \n \"area[range]\": \"%d;%d\" % (\n # user cannot set greater values\n FlatsSearchView.range_filters_config[\"area\"][\"max\"],\n FlatsSearchView.range_filters_config[\"area\"][\"max\"]\n )\n\n }\n )\n\n flats = self.get_context_variable(\"flats\")\n self.assertEqual(len(flats), 1)\n self.assertEqual(flats[0].id, flat.id)\n\n\nclass FlatDetailViewTest(AppTestCase):\n config = \"testing_psql\"\n\n def create_flat(self, **attrs):\n offer = Offer(title=\"Test Offer\", latitude=52.24, longitude=20.91)\n default_attrs = {\n \"fid\": \"1\", \"number\": \"1\",\n \"area\": 65.30, \"rooms\": 3, \"floor\": 2,\n \"offer\": offer\n }\n flat = Flat(**{ **default_attrs, **attrs })\n db.session.add(flat)\n db.session.commit()\n\n dbtrace_2015 = DBUpdateTrace(timestamp=datetime(2015, 1, 1))\n dbtrace_2016 = DBUpdateTrace(timestamp=datetime(2016, 1, 1))\n db.session.add_all([\n Status(value=Status.AVAILABLE, dbtrace=dbtrace_2015, flat=flat),\n Status(value=Status.SOLD, dbtrace=dbtrace_2016, flat=flat)\n ])\n db.session.commit()\n\n db.session.add_all(Event.create_many(dbtrace_2015))\n db.session.add_all(Event.create_many(dbtrace_2016))\n db.session.commit()\n\n FlatDBView.refresh(db.session, False)\n return flat\n\n def test_build_url_for_flat_info(self):\n flat = self.create_flat()\n\n flat_info_url = url_for(\"flats.flat_info\", flat_id=flat.id)\n self.assertIsNotNone(flat_info_url)\n\n def test_render_proper_template(self):\n flat = self.create_flat()\n\n self.client.get(url_for(\"flats.flat_info\", flat_id=flat.id))\n\n self.assert_template_used(\"flats/flat_info.html\")\n\n def test_pass_proper_flat_to_template(self):\n flat_fake = self.create_flat(fid=\"2\", number=\"2\")\n flat = self.create_flat()\n\n self.client.get(url_for(\"flats.flat_info\", flat_id=flat.id))\n\n flat_val = self.get_context_variable(\"flat\")\n self.assertEqual(flat.id, flat_val.id)\n\n def test_show_404_page_when_flat_does_not_exist(self):\n response = self.client.get(url_for(\"flats.flat_info\", flat_id=101))\n\n self.assert_404(response)\n\n def test_pass_events_associated_with_flat_to_template(self):\n flat = self.create_flat()\n\n self.client.get(url_for(\"flats.flat_info\", flat_id=flat.id))\n\n events_val = self.get_context_variable(\"events\")\n events = db.session.query(Event).filter(Event.flat_id == flat.id).all()\n\n self.assertEqual(len(events_val), len(events))\n\n def test_find_similar_flats_within_flat_offer(self):\n flat = self.create_flat(area=65.30, rooms=3, floor=2)\n dbtrace = db.session.query(DBUpdateTrace).all()[-1]\n\n flat_2 = Flat(\n fid=\"2\", number=\"2\", area=55.50, rooms=2, floor=1, offer=flat.offer, \n status=Status(value=Status.SOLD, dbtrace=dbtrace)\n )\n flat_3 = Flat(\n fid=\"3\", number=\"3\", area=35.50, rooms=2, floor=1, offer=flat.offer, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n flat_4 = Flat(\n fid=\"4\", number=\"4\", area=60.30, rooms=3, floor=2, offer=flat.offer, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n db.session.add_all([flat_2, flat_3, flat_4])\n db.session.commit()\n FlatDBView.refresh(db.session, False)\n\n self.client.get(url_for(\"flats.flat_info\", flat_id=flat.id))\n\n flats_sim = self.get_context_variable(\"flats_offer\")\n\n self.assertEqual(len(flats_sim), 1)\n self.assertEqual(flats_sim[0].number, \"4\")\n\n def test_find_similar_flats_from_neighbour(self):\n flat = self.create_flat(area=65.30, rooms=3, floor=2)\n dbtrace = db.session.query(DBUpdateTrace).all()[-1]\n\n offer_near = Offer(title=\"Near Offer\", latitude=52.24, longitude=20.91)\n offer_far = Offer(title=\"Far Away Offer\", latitude=52.31, longitude=20.97)\n\n flat_2 = Flat(\n fid=\"2\", number=\"2\", area=25.50, rooms=2, floor=1, offer=offer_near, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n flat_3 = Flat(\n fid=\"3\", number=\"3\", area=65.50, rooms=2, floor=1, offer=offer_far, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n flat_4 = Flat(\n fid=\"4\", number=\"4\", area=60.30, rooms=3, floor=2, offer=offer_near, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n db.session.add_all([flat_2, flat_3, flat_4])\n db.session.commit()\n FlatDBView.refresh(db.session, False)\n\n self.client.get(url_for(\"flats.flat_info\", flat_id=flat.id))\n\n flats_sim = self.get_context_variable(\"flats_neighbour\")\n\n self.assertEqual(len(flats_sim), 1)\n self.assertEqual(flats_sim[0].number, \"4\")\n\n def test_find_similar_flats_when_some_attributes_are_missing(self):\n flat = self.create_flat(area=65.30, rooms=None, floor=None)\n dbtrace = db.session.query(DBUpdateTrace).all()[-1]\n\n flat_1 = Flat(\n fid=\"3\", number=\"3\", area=None, rooms=2, floor=1, offer=flat.offer, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n flat_2 = Flat(\n fid=\"4\", number=\"4\", area=60.30, rooms=3, floor=2, offer=flat.offer, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n db.session.add_all([flat_1, flat_2])\n db.session.commit()\n FlatDBView.refresh(db.session, False)\n\n self.client.get(url_for(\"flats.flat_info\", flat_id=flat.id))\n\n flats_sim = self.get_context_variable(\"flats_offer\")\n\n self.assertEqual(len(flats_sim), 1)\n self.assertEqual(flats_sim[0].number, \"4\")\n\n def test_render_flats_with_all_missing_attributes(self):\n flat = self.create_flat(area=None, rooms=None, floor=None)\n dbtrace = db.session.query(DBUpdateTrace).all()[-1]\n\n flat_1 = Flat(\n fid=\"3\", number=\"3\", area=None, rooms=2, floor=1, offer=flat.offer, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n flat_2 = Flat(\n fid=\"4\", number=\"4\", area=60.30, rooms=3, floor=2, offer=flat.offer, \n status=Status(value=Status.AVAILABLE, dbtrace=dbtrace)\n )\n db.session.add_all([flat_1, flat_2])\n db.session.commit()\n FlatDBView.refresh(db.session, False)\n\n self.client.get(url_for(\"flats.flat_info\", flat_id=flat.id))\n\n flats_sim = self.get_context_variable(\"flats_offer\")\n flats_sim_neighbour = self.get_context_variable(\"flats_neighbour\")\n\n self.assertEqual(len(flats_sim), 0)\n self.assertEqual(len(flats_sim_neighbour), 0)\n\n\n\nclass FlatEditViewTest(AppTestCase):\n config = \"testing_psql\"\n\n def create_flat(self, **attrs):\n offer = Offer(title=\"Test Offer\", latitude=52.24, longitude=20.91)\n default_attrs = {\n \"fid\": \"1\", \"number\": \"1\",\n \"area\": 65.30, \"rooms\": 3, \"floor\": 2,\n \"offer\": offer\n }\n flat = Flat(**{ **default_attrs, **attrs })\n db.session.add(flat)\n db.session.commit()\n FlatDBView.refresh(db.session, False)\n return flat\n\n def test_build_url_for_flat_edit_view(self):\n flat = self.create_flat()\n\n flat_info_url = url_for(\"flats.edit\", flat_id=flat.id)\n self.assertIsNotNone(flat_info_url)\n\n def test_render_proper_template(self):\n user = self.create_user()\n self.login_user()\n\n flat = self.create_flat()\n\n self.client.get(url_for(\"flats.edit\", flat_id=flat.id))\n\n self.assert_template_used(\"flats/edit.html\")\n\n def test_render_404_template_when_flat_does_not_exist(self):\n user = self.create_user()\n self.login_user()\n\n response = self.client.get(url_for(\"flats.edit\", flat_id=1))\n\n self.assertEqual(response.status_code, 404)\n\n self.assert_template_used(\"flats/404.html\")\n\n def test_pass_form_to_template(self):\n user = self.create_user()\n self.login_user()\n \n flat = self.create_flat()\n\n self.client.get(url_for(\"flats.edit\", flat_id=flat.id))\n\n form = self.get_context_variable(\"form\")\n\n self.assertIsInstance(form, FlatForm)\n\n def test_not_authenticated_user_cannot_access_edit_view(self):\n flat = self.create_flat()\n\n response = self.client.get(url_for(\"flats.edit\", flat_id=flat.id))\n\n self.assertEqual(response.status_code, 401)\n self.assert_template_used(\"flats/401.html\")\n\n def test_create_new_dbrequest_with_post_request(self):\n user = self.create_user()\n self.login_user()\n\n flat = self.create_flat()\n\n self.client.post(\n url_for(\"flats.edit\", flat_id=flat.id),\n data = dict(area=35.10, rooms=1)\n )\n\n dbrequest = db.session.query(DBRequest).first()\n\n self.assertIsNotNone(dbrequest)\n self.assertEqual(dbrequest.action, \"update\")\n self.assertEqual(dbrequest.instance_id, flat.id)\n self.assertEqual(dbrequest.user, user)\n\n data = json.loads(dbrequest.data)\n self.assertEqual(data[\"area\"], 35.10)\n self.assertEqual(data[\"rooms\"], 1)\n\n def test_execute_dbrequest_when_user_has_update_privilege(self):\n user = self.create_user(role_name=\"Moderator\")\n self.login_user()\n\n flat = self.create_flat()\n\n self.client.post(\n url_for(\"flats.edit\", flat_id=flat.id),\n data = dict(area=35.10, rooms=1)\n )\n\n dbrequest = db.session.query(DBRequest).first()\n\n self.assertIsNotNone(dbrequest)\n self.assertTrue(dbrequest.executed)\n\n def test_flat_number_cannot_be_changed_and_it_is_ignored(self):\n user = self.create_user()\n self.login_user()\n\n flat = self.create_flat()\n\n self.client.post(\n url_for(\"flats.edit\", flat_id=flat.id),\n data = dict(area=35.10, rooms=1, number=\"A10\")\n )\n\n dbrequest = db.session.query(DBRequest).first()\n data = json.loads(dbrequest.data)\n self.assertNotIn(\"number\", data)","sub_path":"tests/app/flats/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":18849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"167083111","text":"# Build entry point.\n\nimport os\n\nenv = Environment (\n ENV = os.environ,\n LIBPATH = ['/usr/local/lib'],\n CPPPATH = ['/usr/local/include/', '#/'],\n CCCOMSTR = \"Compiling $TARGET\",\n CXXFLAGS = \"-std=c++0x\", #enable c++ 11\n CPPDEFINES = ['ENABLE_CASTLE_ASSERTS'],\n LINKCOMSTR = \"Linking $TARGET\",\n LINKFLAGS = '-v')\n\n# would be good to do this automatically, but i'm not sure how to yet...\nenv.Append(\n LIBPATH = [\n '#contrib/zmalloc',\n '#contrib/ae',\n '#contrib/anet',\n '#lib/castle',\n '#lib/sukoa'\n ])\n\nsubdirs = [\n 'contrib/zmalloc',\n 'contrib/anet',\n 'contrib/ae',\n 'lib/castle',\n 'lib/sukoa',\n 'src/dummy',\n 'src/sukoad',\n 'src/sukoac'\n]\n\n# The exports attribute allows you to pass variables to the subdir SConscripts\nfor dir in subdirs:\n SConscript(\n os.path.join(dir, 'SConscript'),\n exports = ['env'])\n\nenv.Clean('.', '.sconsign.dblite')\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"343116339","text":"\"\"\"\nmistral_gpt2.py\n\nCustom Implementation of the GPT-2 LM-Head Model (and auxiliary classes) with support for adaptive/custom number of\ngradient checkpoints (for fine-grained tweaking of memory footprint vs. speed).\n\nReference: https://github.com/huggingface/transformers/blob/master/src/transformers/models/gpt2/modeling_gpt2.py\n\"\"\"\nimport logging\nfrom typing import Tuple\n\nimport torch\nimport torch.nn as nn\nfrom torch.cuda.amp import autocast\nfrom transformers import GPT2Config, GPT2LMHeadModel, GPT2Model\nfrom transformers.modeling_outputs import BaseModelOutputWithPastAndCrossAttentions\nfrom transformers.models.gpt2.modeling_gpt2 import Attention, Block\n\n\n# Nest Overwatch under root `mistral` logger, inheriting formatting!\noverwatch = logging.getLogger(\"mistral.models.gpt2_gc\")\n\n\nclass MistralGPT2LMHeadModel(GPT2LMHeadModel):\n def __init__(\n self,\n config: GPT2Config,\n reorder_attn: bool = True,\n upcast_attn: bool = True,\n gradient_checkpointing: bool = True,\n gc_checkpoint_every: int = 1,\n ):\n super().__init__(config)\n self.reorder_attn, self.upcast_attn = reorder_attn, upcast_attn\n\n # Turn on Gradient Checkpointing if Necessary\n if gradient_checkpointing:\n self.create_checkpointed_model(gc_checkpoint_every)\n else:\n self.create_model()\n\n # @MERCURY =>> Reconfigure GPT2LMHead to take custom, partial checkpoint model instance!\n def create_checkpointed_model(self, gc_checkpoint_every: int):\n # Reinitalize GPT-2 Model w/ Custom GC Wrapper\n self.transformer = MistralGPT2Model(self.config, gc_checkpoint_every, self.reorder_attn, self.upcast_attn)\n\n # @MERCURY =>> Reconfigure GPT2LMHead to Initialize Standard (non-checkpointed) model instance!\n def create_model(self):\n # Reinitialize Custom GPT-2 Model\n self.transformer = MistralGPT2Model(\n self.config, gc_checkpoint_every=-1, reorder_attn=self.reorder_attn, upcast_attn=self.upcast_attn\n )\n\n\nclass MistralGPT2Model(GPT2Model):\n # @MERCURY =>> GPT-2 Model Instance now takes `gc_checkpoint_every` parameter.\n def __init__(self, config: GPT2Config, gc_checkpoint_every: int, reorder_attn: bool, upcast_attn: bool):\n super().__init__(config)\n self.h = nn.ModuleList(\n [\n MistralGPT2Block(\n config.n_ctx, config, i + 1, scale=True, reorder_attn=reorder_attn, upcast_attn=upcast_attn\n )\n for i in range(config.n_layer)\n ]\n )\n self.init_weights()\n\n if getattr(self.config, \"gradient_checkpointing\", False):\n assert 1 <= gc_checkpoint_every <= len(self.h)\n self.gc_checkpoint_every = gc_checkpoint_every\n\n def forward(\n self,\n input_ids=None,\n past_key_values=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n use_cache=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = input_ids.size()\n input_ids = input_ids.view(-1, input_shape[-1])\n batch_size = input_ids.shape[0]\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n batch_size = inputs_embeds.shape[0]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n if token_type_ids is not None:\n token_type_ids = token_type_ids.view(-1, input_shape[-1])\n if position_ids is not None:\n position_ids = position_ids.view(-1, input_shape[-1])\n\n if past_key_values is None:\n past_length = 0\n past_key_values = tuple([None] * len(self.h))\n else:\n past_length = past_key_values[0][0].size(-2)\n if position_ids is None:\n position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)\n position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])\n\n # GPT2Attention mask.\n if attention_mask is not None:\n assert batch_size > 0, \"batch_size has to be defined and > 0\"\n attention_mask = attention_mask.view(batch_size, -1)\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n attention_mask = attention_mask[:, None, None, :]\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility\n attention_mask = (1.0 - attention_mask) * -10000.0\n\n # If a 2D ou 3D attention mask is provided for the cross-attention\n # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]\n if self.config.add_cross_attention and encoder_hidden_states is not None:\n encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()\n encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)\n if encoder_attention_mask is None:\n encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)\n encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)\n else:\n encoder_attention_mask = None\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # head_mask has shape n_layer x batch x n_heads x N x N\n head_mask = self.get_head_mask(head_mask, self.config.n_layer)\n\n if inputs_embeds is None:\n inputs_embeds = self.wte(input_ids)\n position_embeds = self.wpe(position_ids)\n hidden_states = inputs_embeds + position_embeds\n\n if token_type_ids is not None:\n token_type_embeds = self.wte(token_type_ids)\n hidden_states = hidden_states + token_type_embeds\n\n hidden_states = self.drop(hidden_states)\n\n output_shape = input_shape + (hidden_states.size(-1),)\n\n presents: Tuple = () if use_cache else None\n all_self_attentions: Tuple = () if output_attentions else None\n all_cross_attentions: Tuple = () if output_attentions and self.config.add_cross_attention else None\n all_hidden_states: Tuple = () if output_hidden_states else None\n\n for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):\n\n # Model parallel\n if self.model_parallel:\n torch.cuda.set_device(hidden_states.device)\n # Ensure layer_past is on same device as hidden_states (might not be correct)\n if layer_past is not None:\n layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)\n # Ensure that attention_mask is always on the same device as hidden_states\n if attention_mask is not None:\n attention_mask = attention_mask.to(hidden_states.device)\n if isinstance(head_mask, torch.Tensor):\n head_mask = head_mask.to(hidden_states.device)\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # @MERCURY =>> Single line change, `and (i % self.gc_checkpoint_every) == 0` --> partial-checkpointing!\n if (\n getattr(self.config, \"gradient_checkpointing\", False)\n and self.training\n and (i % self.gc_checkpoint_every) == 0\n ):\n if use_cache:\n overwatch.warning(\n \"`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting \"\n \"`use_cache=False`...\"\n )\n use_cache = False\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n # None for past_key_value\n return module(*inputs, use_cache, output_attentions)\n\n return custom_forward\n\n outputs = torch.utils.checkpoint.checkpoint( # type:ignore[attr-defined]\n create_custom_forward(block),\n hidden_states,\n None,\n attention_mask,\n head_mask[i],\n encoder_hidden_states,\n encoder_attention_mask,\n )\n\n else:\n outputs = block(\n hidden_states,\n layer_past=layer_past,\n attention_mask=attention_mask,\n head_mask=head_mask[i],\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n )\n\n hidden_states = outputs[0]\n if use_cache is True:\n presents = presents + (outputs[1],)\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)\n if self.config.add_cross_attention:\n all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)\n\n # Model Parallel: If it's the last layer for that device, put things on the next device\n if self.model_parallel:\n for k, v in self.device_map.items():\n if i == v[-1] and \"cuda:\" + str(k) != self.last_device:\n hidden_states = hidden_states.to(\"cuda:\" + str(k + 1))\n\n hidden_states = self.ln_f(hidden_states)\n\n hidden_states = hidden_states.view(*output_shape)\n # Add last hidden state\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)\n\n return BaseModelOutputWithPastAndCrossAttentions(\n last_hidden_state=hidden_states,\n past_key_values=presents,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n cross_attentions=all_cross_attentions,\n )\n\n\nclass MistralGPT2Attention(Attention):\n def __init__(\n self,\n nx,\n n_ctx,\n config,\n layer_num,\n scale=False,\n is_cross_attention=False,\n reorder_attn=True,\n upcast_attn=True,\n log_activations=False,\n ):\n super().__init__(nx, n_ctx, config, scale, is_cross_attention)\n\n self.log_activations = log_activations\n if self.log_activations:\n self.activation_stats = {\n \"attention_weight_max\": None,\n \"attention_weight_min\": None,\n }\n assert layer_num > 0\n self.layer_num = layer_num\n\n # Numerical Stability\n self.reorder_attn, self.upcast_attn = reorder_attn, upcast_attn\n\n def _attn(self, q, k, v, attention_mask=None, head_mask=None, output_attentions=False):\n \"\"\"\n Taken from:\n https://github.com/huggingface/transformers/blob/v4.5.0/src/transformers/models/gpt2/modeling_gpt2.py#L167\n\n We log extra statistics about the attention weights!\n \"\"\"\n # @MERCURY =>> Reorder Scaled Dot-Product Attention Computation, Upcast to FP32\n # Q :: [bsz, num_heads, seq_len, dk], K :: [bsz, num_heads, dk, seq_len]\n if self.scale:\n # Get QKV Dimensions\n bsz, num_heads, seq_len, dk = q.size()\n\n # @MERCURY =>> Scale by SQRT(head_dim) * layer_number -- taken from Megatron LM!\n scale_factor = 1 / ((float(v.size(-1)) ** 0.5) * self.layer_num)\n\n if self.reorder_attn:\n # Preallocate Scaled Dot-Product Tensor\n w = torch.empty( # type: ignore\n bsz * num_heads,\n seq_len,\n seq_len,\n dtype=q.dtype,\n device=torch.cuda.current_device(),\n )\n\n # Upcasting --> Disable autocast AND manually call .float()\n if self.upcast_attn:\n # Reorder via `baddbmm` Time (Scale K by 1 / root(dk) first!)\n with autocast(enabled=False):\n q, k = q.reshape(-1, seq_len, dk), k.reshape(-1, dk, seq_len)\n w = torch.baddbmm(\n w.float(),\n q.float(),\n k.float(),\n beta=0.0,\n alpha=scale_factor,\n )\n w = w.reshape(bsz, num_heads, seq_len, seq_len)\n\n # No Upcasting\n else:\n q, k = q.reshape(-1, seq_len, dk), k.reshape(-1, dk, seq_len)\n w = torch.baddbmm(w, q, k, beta=0.0, alpha=scale_factor)\n w = w.reshape(bsz, num_heads, seq_len, seq_len)\n\n else:\n # Upcasting --> Disable autocast AND manually call .float()\n if self.upcast_attn:\n with autocast(enabled=False):\n w = torch.matmul(q.float(), k.float())\n w *= scale_factor\n\n # No Upcasting\n else:\n w = torch.matmul(q, k)\n w *= scale_factor\n\n else:\n w = torch.matmul(q, k)\n\n # Add extra logging of the attention weight\n if self.log_activations:\n with torch.no_grad():\n self.activation_stats[\"attention_weight_max\"] = w.max().item()\n self.activation_stats[\"attention_weight_min\"] = w.min().item()\n\n nd, ns = w.size(-2), w.size(-1)\n if not self.is_cross_attention:\n # if only \"normal\" attention layer implements causal mask\n mask = self.bias[:, :, ns - nd : ns, :ns]\n w = torch.where(mask.bool(), w, self.masked_bias.to(w.dtype))\n\n if attention_mask is not None:\n # Apply the attention mask\n w = w + attention_mask\n\n w = nn.Softmax(dim=-1)(w)\n\n # verify upcasting is happening\n if self.upcast_attn:\n if w.dtype != torch.float32:\n overwatch.critical(\"Upcasting Error. w does not have dtype torch.float32\")\n raise RuntimeError(\"Upcasting Error. w does not have dtype torch.float32\")\n\n # @MERCURY =>> Downcast (if necessary) back to V dtype (fp16 if mixed-precision)!\n # Note: This is a No-Op if Upcasting is disabled...\n w = w.type(v.dtype)\n\n w = self.attn_dropout(w)\n\n # Mask heads if we want to\n if head_mask is not None:\n w = w * head_mask\n\n outputs: Tuple = (torch.matmul(w, v),)\n if output_attentions:\n outputs += (w,)\n return outputs\n\n\nclass MistralGPT2Block(Block):\n def __init__(self, n_ctx, config, layer_num, scale=False, reorder_attn=True, upcast_attn=True):\n super().__init__(n_ctx, config, scale)\n hidden_size = config.n_embd\n self.attn = MistralGPT2Attention(\n hidden_size, n_ctx, config, layer_num, scale=scale, reorder_attn=reorder_attn, upcast_attn=upcast_attn\n )\n","sub_path":"src/models/mistral_gpt2.py","file_name":"mistral_gpt2.py","file_ext":"py","file_size_in_byte":17082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"623689280","text":"\n\ndef angka1():\n angka=input(\"Tebak aku dong antara 1-9:\")\n return angka\n if cek(angka):\n return int(angka)\n else:\n print(\"Invalid\")\n angka1()\n\n \ndef cek(angka2):\n try:\n angka=int(angka2)\n except: \n return False\n return 1<=angka<=9\n\n \n \ndef run():\n print(\"Games Tebak Angka :\")\n \n \n while True:\n angka=int(angka1())\n if angka>5:\n print(\"Kegedean bos\")\n elif angka<5:\n print(\"Terlalu mungil\")\n else :\n print(\"Jawaban benar\")\n break\n \nrun()\n\n","sub_path":"funtebakangka.py","file_name":"funtebakangka.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"230528553","text":"\"\"\"\nFlask-Router\n==================\n\nInstall Flask-Router\n\"\"\"\nfrom setuptools import setup\nimport setuptools\n\nrequires = [\n 'Flask',\n]\n\nsetup(\n name='Flask-Router',\n version='0.1.1',\n url='https://github.com/Hardtack/Flask-Router',\n author='GunWoo Choi',\n author_email='6566gun@gmail.com',\n description='Tuned flask\\'s URL routing library',\n long_description=__doc__,\n packages=setuptools.find_packages(),\n include_package_data=True,\n zip_safe=False,\n platforms='any',\n install_requires=requires,\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n ],\n)\n","sub_path":"pypi_install_script/Flask-Router-0.1.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"365593542","text":"import view\nimport tables as tab\nimport random as rnd\nimport numpy as np\nimport theano as t\nimport matplotlib.pyplot as plt\nfrom scipy.misc import imread \nfrom scipy.io import loadmat\nfrom skimage import color, filters\n\ndef shared_type(data, name, dtype=t.config.floatX, borrow=True):\n #return t.shared(np.asarray(data, dtype=dtype), name=name, borrow=borrow)\n return np.asarray(data, dtype=dtype)\n\ndef imnorm(img,imax=None):\n if imax is None:\n imax = np.amax(img)\n return np.array(img,dtype=np.float32) / imax \n\ndef idx_to_bin_img(img,idx,gauss=None):\n idx[:,0] = np.clip(np.round(idx[:,0]),0,img.shape[0]-1) \n idx[:,1] = np.clip(np.round(idx[:,1]),0,img.shape[1]-1)\n for j in range(0,len(idx)):\n img[int(idx[j,1]),int(idx[j,0])] = 1\n if gauss is not None:\n img = filters.gaussian(img, gauss)\n return img\n\ndef split_tvt(data_x, data_y):\n \n def quarter_split(data, rnd_order):\n data = data[rnd_order,:,:]\n q = data.shape[0] // 4\n train = data[ :2*q,:,:]\n valid = data[1+2*q:3*q,:,:]\n tests = data[1+3*q: ,:,:]\n return [train, valid, tests]\n \n # randomly shuffle\n rnd_order = np.arange(0,data_x.shape[0])\n rnd.seed(1234)\n rnd.shuffle(rnd_order)\n \n # split into sets\n [xtrain,xvalid,xtests] = quarter_split(data_x, rnd_order)\n [ytrain,yvalid,ytests] = quarter_split(data_y, rnd_order)\n \n return [xtrain, ytrain, xvalid, yvalid, xtests, ytests] \n\ndef scores(N=100):\n \n print('Loading Data...')\n \n imgslug = 'D:\\IMG\\hist\\CRC-HP\\Detection\\img#\\img#.bmp'\n matslug = 'D:\\IMG\\hist\\CRC-HP\\Detection\\img#\\img#_detection.mat' \n\n # read the data\n imgx = np.zeros((100,500,500),dtype=np.float32)\n imgy = np.zeros((100,500,500),dtype=np.float32)\n for i in range(0,N):\n # inputs\n imgrgb = imread(imgslug.replace('#',str(i+1)))\n imgx[i,:,:] = imnorm(imgrgb[:,:,0]) # R channel\n # labels\n nucidx = np.floor(loadmat(matslug.replace('#',str(i+1)))['detection'])\n imgy[i,:,:] = imnorm(idx_to_bin_img(imgy[i,:,:], nucidx, gauss=2))\n # debug\n #view.imshow(np.squeeze(imgx[i,:,:]))\n #view.imshow(np.squeeze(imgy[i,:,:,:]))\n \n # assign to sets\n [xtrain, ytrain, xvalid, yvalid, xtests, ytests] = split_tvt(imgx, imgy)\n \n print('Done')\n return [xtrain,ytrain,xvalid,yvalid,xtests,ytests] \n ","sub_path":"loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"134715600","text":"# -*- coding: utf-8 -*-\nimport time\n\nfrom odoo import models, fields, api\n\n\nclass Suppliers_History(models.Model):\n _name = 'suppliers.history'\n\n res_partner_id = fields.Many2one('res.partner')\n date = fields.Char()\n hired = fields.Float()\n delivered = fields.Float()\n pending = fields.Float(compute=\"_compute_pending\", store=False, readonly=True)\n progressbar = fields.Float(compute=\"_compute_progressbar\")\n\n @api.one\n @api.depends('hired','delivered')\n def _compute_pending(self):\n self.pending = self.hired - self.delivered\n\n @api.one\n @api.depends('hired','delivered')\n def _compute_progressbar(self):\n if self.hired and self.delivered:\n self.progressbar = (self.delivered * 100) / self.hired\n\n # @api.one\n # def _compute_year(self):\n # self.date = time.strftime(\"%Y\") #solo se ejecuta al guardar el registro//Eror\n # str(time.strftime(\"%Y\"))\n\nclass Record_Partner(models.Model):\n _inherit = \"res.partner\"\n\n suppliers_history_ids = fields.One2many('suppliers.history','res_partner_id')\n last_year_contract = fields.Char(compute=\"_compute_last_year\", store=True)\n tons_hired = fields.Float(compute=\"_compute_hired\")\n\n # @api.onchange('suppliers_history_ids')\n @api.one\n @api.depends('suppliers_history_ids')\n def _compute_last_year(self):\n year = 0\n for line in self.suppliers_history_ids:\n try:\n if not isinstance(line.date, int):\n if int(line.date) > year:\n year = int(line.date)\n except ValueError:\n year = 0\n if year > 1:\n self.last_year_contract = str(year)\n else:\n self.last_year_contract = ''\n\n @api.one\n @api.depends('suppliers_history_ids')\n def _compute_hired(self):\n year = 0\n for line in self.suppliers_history_ids:\n try:\n if not isinstance(line.date, int):\n if int(line.date) > year:\n year = int(line.date)\n self.tons_hired = line.hired\n except ValueError:\n year = 0\n","sub_path":"partner_data/models/suppliers_history.py","file_name":"suppliers_history.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"14546426","text":"import numpy as np\nimport matplotlib.pyplot as plt\ndef f(x):\n return np.sin(x)\n\ndef integral_analitica():\n return 0.5\n\ndef integral_monte_carlo(N=100):\n x = np.random.exponential(size=N) # esto ya no es una distribucion uniforme!\n return np.sum(f(x))/N\n\n\nn_intentos = 30\npuntos = np.int_(np.logspace(1,5,n_intentos))\ndiferencias = np.ones(n_intentos) # aqui guardaremos la diferencia entre la sol. numerica y la analitica\nfor i in range(n_intentos):\n a = integral_analitica()\n b = integral_monte_carlo(N=puntos[i])\n diferencias[i] = (np.abs((a-b)/a))\n\n\nplt.plot(puntos, diferencias*100)\nplt.loglog()\nplt.xlabel(\"$N_{puntos}$\")\nplt.ylabel(\"Diferencia porcentual Monte Carlo vs. Analitica\")\nplt.show()\n","sub_path":"Otros Codigos/Montecarlo_Integration.py","file_name":"Montecarlo_Integration.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"455806365","text":"from odin_data.ipc_channel import IpcChannel, IpcChannelException\nfrom odin_data.ipc_message import IpcMessage, IpcMessageException\nfrom odin_data.shared_buffer_manager import SharedBufferManager, SharedBufferManagerException\nfrom .frame_processor_config import FrameProcessorConfig\nfrom percival_emulator_frame_decoder import PercivalEmulatorFrameDecoder, PercivalFrameHeader, PercivalFrameData\nfrom excalibur_frame_decoder import ExcaliburFrameDecoder, ExcaliburFrameHeader, ExcaliburFrameData\n\nimport time\nimport datetime\nimport threading\nimport logging\nimport sys\nfrom struct import Struct\n\nclass FrameProcessor(object):\n \n def __init__(self):\n\n # Initialise the logging module with log messages directed to stdout\n #logging.basicConfig(format='%(asctime)s %(levelname)s FrameProcessor - %(message)s', level=logging.DEBUG)\n #ch = logging.StreamHandler(sys.stdout)\n #logging.addHandler(ch)\n\n # create logger\n self.logger = logging.getLogger('frame_processor')\n self.logger.setLevel(logging.DEBUG)\n \n # create console handler and set level to debug\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(logging.DEBUG)\n \n # create formatter\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s - %(message)s')\n \n # add formatter to ch\n ch.setFormatter(formatter)\n \n # add ch to logger\n self.logger.addHandler(ch)\n\n # Instantiate a configuration container object, which will be populated\n # with sensible default values\n self.config = FrameProcessorConfig(\"FrameProcessor\", \"FrameProcessor - test harness to simulate operation of FrameProcessor application\")\n \n # Create the appropriate IPC channels\n self.ctrl_channel = IpcChannel(IpcChannel.CHANNEL_TYPE_REQ)\n self.ready_channel = IpcChannel(IpcChannel.CHANNEL_TYPE_SUB)\n self.release_channel = IpcChannel(IpcChannel.CHANNEL_TYPE_PUB)\n\n # Zero frames recevied counter\n self.frames_received = 0\n \n # Create the thread to handle frame processing\n self.frame_processor = threading.Thread(target=self.process_frames)\n self.frame_processor.daemon = True\n \n self._run = True\n \n def map_shared_buffer(self):\n \n success = False\n \n # Check if the current configuration object has a shared buffer name defined, otherwise request one from the\n # upstream frameReceiver\n if self.config.sharedbuf is None:\n if not self.request_shared_buffer_config():\n return success\n \n # Map the shared buffer manager\n try:\n self.shared_buffer_manager = SharedBufferManager(self.config.sharedbuf, boost_mmap_mode=self.config.boost_mmap_mode)\n success = True\n except SharedBufferManagerException as e:\n self.logger.error(\"Failed to create shared buffer manager: %s\" % str(e))\n \n return success\n \n def request_shared_buffer_config(self):\n \n success = False\n\n max_request_retries = 10\n max_reply_retries = 10\n \n request_retries = 0\n config_request = IpcMessage(msg_type='cmd', msg_val='request_buffer_config') \n \n while success is False and request_retries < max_request_retries:\n\n self.logger.debug(\"Sending buffer config request {}\".format(request_retries + 1))\n self.release_channel.send(config_request.encode())\n reply_retries = 0\n \n while success is False and reply_retries < max_reply_retries:\n if self.ready_channel.poll(100):\n config_msg = self.ready_channel.recv()\n config_decoded = IpcMessage(from_str = config_msg)\n self.logger.debug(\n 'Got buffer configuration response with shared buffer name: {}'.format(\n config_decoded.get_param('shared_buffer_name')\n )\n )\n self.config.sharedbuf = config_decoded.get_param('shared_buffer_name')\n success = True\n else:\n reply_retries += 1\n \n request_retries += 1\n \n # temp hack\n if not success:\n self.logger.error(\"Failed to obtain shared buffer configuration\")\n \n return success\n \n def run(self):\n \n self.logger.info(\"Frame processor starting up\")\n\n # Connect the IPC channels\n self.ctrl_channel.connect(self.config.ctrl_endpoint)\n self.ready_channel.connect(self.config.ready_endpoint)\n self.release_channel.connect(self.config.release_endpoint)\n\n # Ready channel subscribes to all topics\n self.ready_channel.subscribe(b'')\n \n # Map the shared buffer manager - quit if this fails \n if not self.map_shared_buffer():\n self._run = False\n return\n \n self.logger.info(\"Mapped shared buffer manager ID %d with %d buffers of size %d\" % \n (self.shared_buffer_manager.get_manager_id(), \n self.shared_buffer_manager.get_num_buffers(),\n self.shared_buffer_manager.get_buffer_size()))\n \n if self.config.sensortype == 'percivalemulator': \n self.frame_decoder = PercivalEmulatorFrameDecoder(self.shared_buffer_manager)\n self.logger.debug('Loaded frame decoder for PERCIVAL emulator sensor type')\n elif self.config.sensortype == 'excalibur':\n self.frame_decoder = ExcaliburFrameDecoder(self.shared_buffer_manager)\n self.logger.debug('Loaded frame decoder for EXCALIBUR sensor type')\n else:\n self.frame_decoder = None\n self.logger.error(\"Unrecognised sensor type specified: %s\" % self.config.sensortype)\n return\n \n\n # Launch the frame processing thread\n self.frame_processor.start()\n \n try:\n while self._run:\n \n if self.config.frames and self.frames_received >= self.config.frames:\n self.logger.info(\"Specified number of frames (%d) received, terminating\" % self.config.frames)\n self._run = False\n else: \n msg = IpcMessage(msg_type='cmd', msg_val='status')\n #self.logger.debug(\"Sending status command message\")\n self.ctrl_channel.send(msg.encode())\n \n reply = self.ctrl_channel.recv()\n reply_decoded = IpcMessage(from_str=reply)\n \n #self.logger.debug(\"Got reply, msg_type = \" + reply_decoded.get_msg_type() + \" val = \" + reply_decoded.get_msg_val())\n time.sleep(1) \n \n except KeyboardInterrupt:\n \n self.logger.info(\"Got interrupt, terminating\")\n self._run = False\n \n self.frame_processor.join()\n self.logger.info(\"Frame processor shutting down\")\n \n def process_frames(self):\n \n self.frame_header = Struct(' 1:\n try:\n split_pieces[1] = split_pieces[1].replace(\" \", \"\", 1)\n result[split_pieces[0]] = split_pieces[1]\n except:\n print('badcarvalue')\n else:\n split_pieces[1] = split_pieces[1].replace(\" \", \"\", 1)\n result[split_pieces[0]] = split_pieces[1]\n else:\n result['car'] = split_pieces[0]\n try:\n int(split_pieces[0][0:4]) \n except:\n result['model year'] = \"\"\n else:\n result['model year'] = split_pieces[0][0:4]\n price = soup.find_all('span', attrs={'class':'price'})\n try:\n price[0].string.strip('$')\n except:\n result['price'] = '0'\n result['model year'] = \"\"\n else:\n result['price'] = price[0].string.strip('$')\n\n counter += 1\n return result\n\nif __name__ == '__main__':\n # Make sure path to db is specified on Linux:\n # Create DB Connection and Cursor:\n conn = sqlite3.connect('cars.db')\n c = conn.cursor()\n\n # Create Tables for DB, Used for Tossing Out\n # Previously Mailed Urls\n # Also Allows Storage of User Emails and Requested Criteria\n c.execute('''CREATE TABLE IF NOT EXISTS car\n (url STRING)''')\n c.execute('''CREATE TABLE IF NOT EXISTS goodlinks\n (url STRING)''')\n c.execute('''CREATE TABLE IF NOT EXISTS users\n (name STRING, email STRING, minprice STRING, maxprice STRING)''')\n \n # Query all the names of Users\n c.execute(\"SELECT name FROM users\")\n\n # Store as array:\n allusers = c.fetchall()\n\n # Loop through every user\n for u in allusers:\n # Query their data (email and search criteria)\n # and store values as variables\n name = u[0]\n c.execute(\"SELECT * FROM users WHERE name = ?\", (name,))\n userinfo = c.fetchone()\n user_name = userinfo[0]\n user_email = userinfo[1]\n user_min_price = str(userinfo[2])\n user_max_price = str(userinfo[3])\n user_postal = str(userinfo[4])\n user_distance = str(userinfo[5])\n\n # Prints for Debugging:\n print(user_name)\n print(user_email)\n print(user_min_price)\n print(user_max_price)\n\n # Build our custom Url:\n url = urlManager('sfbay', 'owner') + postedToday() + addMinPrice(user_min_price) + addMaxPrice(user_max_price) + addPostal('94804') + addDistance('20')\n\n # Find all listings with given criteria and print for debugging:\n array = findCarLinks(url)\n print(array)\n\n # Loop through individual listings:\n for link in array:\n #Print to make sure we entered the loop:\n print(link)\n\n # Try to find the Url in DB:\n c.execute(\"SELECT rowid FROM car WHERE url = ?\", (link,))\n data=c.fetchone()\n\n # If URL does not Exist:\n if data is None:\n # Insert value into DB\n ## ERROR HERE: if two users have overlapping price ranges, \n ### then another user should not get the email,\n ## as it should be added to DB and committed and checked \n ## when that users criteria is being looped through\n ## HOWEVER: Although this error should occur, it does not.\n ## I get the same emails my friend does.\n ## I also get listings from his range that are not in mine\n ## This should not happen\n c.execute(f\"INSERT INTO car VALUES ('{link}')\")\n conn.commit()\n\n # Parse the current link and get the dictionary of meta data\n info = parsePages(link)\n\n # Check for title status\n if 'title status' in info.keys():\n # Make sure we entered the conditional, print to verify:\n print(info)\n\n # We only are interested in clean titles, salvaged cars are a \n # bitch and a half to insure\n if info['title status'] == 'clean':\n # If its clean and matches our criteria, grab that email again:\n # Shouldn't need to do this, but I need a list to pass to my send \n # mail function\n c.execute(\"SELECT email FROM users WHERE name = ?\", (user_name,))\n user = c.fetchall()\n\n # Print to make sure we got an array\n print(user_email)\n\n # Send that email!\n send_email(str(user_email), info['car'], link)\n\n # Add to good links, IDK why I did this, future reference I guess\n c.execute(f\"INSERT INTO goodlinks VALUES ('{link}')\")\n print(info)\n else:\n # Car is salvaged so we print to debug\n # and pass it up\n print('salvaged')\n \n # Make sure we're committing our db changes\n conn.commit()\n else:\n # We Found The Listing So just print to debug:\n print('found in db')\n\n # Commit once more and close connection:\n conn.commit()\n conn.close()","sub_path":"craigslistparser.py","file_name":"craigslistparser.py","file_ext":"py","file_size_in_byte":7037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"521467795","text":"from discord.ext import commands\nimport os\nimport discord\n\nbot = commands.Bot(command_prefix='-_-;', help_command=None)\ntoken = os.environ['DISCORD_BOT_TOKEN']\n\n@bot.event\nasync def on_ready():\n print(\"Logged in ^^\")\n \n@bot.command\nasync def change(change, data=None, content=None):\n if content == None or data == None:\n return\n with oepn(\"test.json\", \"r\") as f:\n test = json.load(f)\n test[str(data)] = str(content)\n with open(\"test.json\", \"w\") as f:\n json.dump(test, f, indent=4)\n await change.send(\"jsonのデータ追加してやったぞ...\\nだっる。\")\n\nbot.run(token)\n","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"582025667","text":"import pymongo\nfrom bson import ObjectId\n\nmclient = pymongo.MongoClient(host=\"127.0.0.1\", port=27017)\n\nmongo_db = mclient[\"learn\"]\n\nres = list(mongo_db.tielemao.find())\nfor i in res:\n print(i)\n\nres1 = mongo_db.tielemao.find_one({'_id': ObjectId('5b9877e898a1bd23b8dfad58')})\nprint(res1.get(\"_id\"),type(res1.get(\"_id\")))\n\n# res2 = mongo_db.tielemao.insert_one({\"name\":\"白夜行\"})\n# print(res2,res2.inserted_id)\n\n# res3 = mongo_db.tielemao.insert_many([{\"name\":\"小树叶\",\"age\":12},{\"name\":\"夏实\",\"age\":20}])\n# print(res3,res3.inserted_ids)\n\n# res4 = mongo_db.tielemao.insert_many([{\"name\":\"夏帆\",\"age\":22},{\"name\":\"天狼星\",\"age\":200}])\n# print(res4,dir(res4))\n\nres5 = mongo_db.tielemao.update_one({\"name\":\"天狼星\"},{\"$set\":{\"name\":\"李小狼\"}})\nprint(res5,dir(res5),res5.raw_result)\n","sub_path":"conn_mongo.py","file_name":"conn_mongo.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"575218754","text":"################################################################################\n############################# IMPORTING ########################################\n################################################################################\n\nimport os\nimport shelve\nimport numpy as np\nimport constants as const\nimport pickle\nfrom classes import Population\nfrom supFunctions import plot_performance\n\n################################################################################\n############################## EXPERIMENTS #####################################\n################################################################################\n\ndef ensure_dir(file_path):\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n\ndef load(filename):\n with open(filename, \"rb\") as f:\n while True:\n try:\n yield pickle.load(f)\n except EOFError:\n break\n\ndef save_object(obj, filename):\n with open(filename, 'wb') as output:\n pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)\n \ndef save_global_vars_txt(path):\n tmpDir = [item for item in dir(const) if not item.startswith(\"__\") and item.isupper()]\n with open(path + 'global_vars.txt', 'w') as output: \n for key in tmpDir:\n try:\n output.write(key + ': ' + str(getattr(const,key)) + '\\n') \n except TypeError:\n print('ERROR writing') \n\ndef save_global_vars(path):\n # save global variables\n \n #using pickles\n #tmpDir = [item for item in dir(const) if not item.startswith(\"__\") and item.isupper()]\n\n #with open(filename, 'wb') as output: # 'wb' instead 'w' for binary file\n # for key in tmpDir:\n # print key\n # pickle.dump(getattr(const,key), output, pickle.HIGHEST_PROTOCOL)\n\n #using shelve\n tmpShelf = shelve.open(path + 'global_vars.out','n') # 'n' for new \n tmpDir = [item for item in dir(const) if not item.startswith(\"__\") and item.isupper()]\n for key in tmpDir:\n try:\n tmpShelf[key] = getattr(const, key)\n except TypeError:\n #\n # __builtins__, my_shelf, and imported modules can not be shelved.\n #\n print('ERROR shelving: {0}'.format(key))\n tmpShelf.close() \n\ndef load_global_vars(filename):\n # load global variables\n \n #using shelve\n tmpShelf = shelve.open(filename) \n for key in tmpShelf:\n try:\n setattr(const,key,tmpShelf[key])\n except TypeError:\n #\n # __builtins__, my_shelf, and imported modules can not be shelved.\n #\n print('ERROR shelving: {0}'.format(key))\n tmpShelf.close() \n\ndef run_instance(fileDir, env):\n #run a simulation instance\n\n #initialisation \n POP = Population(const.POP_SIZE)\n performance = np.empty(shape = (int(const.GENERATIONS/env.numGensPerEnvironment),4), dtype='float64') \n \n #main\n for gener in range(const.GENERATIONS):\n \n # print progress (%)\n if (float(gener)/const.GENERATIONS*100) % 2 == 0:\n print(\"%.2f\"% (float(gener)/const.GENERATIONS*100) + \"%\") \n \n # change environment\n env.generate_environment(gener)\n \n # next generation \n POP.next_gen(envCues=env.get_cues(), target=env.get_target()) \n \n # store performance evaluation\n if gener % env.numGensPerEnvironment == 0:\n performance[int(gener / env.numGensPerEnvironment),:] = np.array([POP.get_top_fitness(), POP.get_mean_fitness(), \n POP.get_top_training_performance(env), POP.get_mean_training_performance(env)])\n \n #save data\n #generate directory\n path = os.path.abspath(fileDir) + '/'\n print(path)\n ensure_dir(path)\n \n #store simulation specifications - global variables\n save_global_vars(path)\n \n #store simulation specifications - global variables - txt file\n save_global_vars_txt(path)\n \n #store population\n #save_object(POP, path + 'population.p')\n \n #store and show figures \n plot_performance(performance,filePath=path,saveData = True, showFig = False, saveFig = True)\n POP.get_best_individual().plot_reaction_norm(env, filePath=path, showFig = False, saveFig = True) \n ind = POP.get_best_individual().get_weights()\n print(ind)\n \n ","sub_path":"plasticitygrain/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"637077492","text":"from sqlalchemy.sql import expression\nfrom sqlalchemy.ext.compiler import compiles\n\nfrom razi.functions import functions, _get_function\n\ntry:\n from sqlalchemy.sql.functions import Function\nexcept ImportError:\n # SQLAlchemy<0.9\n Function = expression.Function\n\n\nclass ChemElement(object):\n \"\"\"Represents a molecular structure value.\"\"\"\n\n def __str__(self):\n return self.desc\n\n def __repr__(self):\n return \"<%s at 0x%x; %r>\" % (self.__class__.__name__,\n id(self), self.desc)\n\n def __getattr__(self, name):\n return getattr(functions, name)(self)\n\n\nclass TxtChemElement(Function):\n \"\"\"Represents a chemical value expressed within application code (e.g a\n SMILES string).\n\n Extends expression.Function so that in a SQL expression context the value\n is interpreted as 'txt_to_mol(value)' or as the equivalent function in\n the currently used database as appropriate for the given type.\n \"\"\"\n\n def __init__(self, desc):\n assert isinstance(desc, basestring)\n self.desc = desc\n Function.__init__(self, \"\")\n\n\n@compiles(TxtChemElement)\ndef __compile_txtchemelement(element, compiler, **kw):\n function = _get_function(element, compiler, [element.desc],\n kw.get('within_columns_clause', False))\n return compiler.process(function)\n\n\nclass MoleculeElement(ChemElement):\n pass\n\n\nclass TxtMoleculeElement(MoleculeElement, TxtChemElement):\n \"\"\"Represents a Molecule value expressed within application code (a SMILES).\n \"\"\"\n\n def __init__(self, desc):\n TxtChemElement.__init__(self, desc)\n\n\nclass PersistentMoleculeElement(MoleculeElement):\n \"\"\"Represents a Molecule value loaded from the database.\"\"\"\n\n def __init__(self, desc):\n self.desc = desc\n\n\nclass QMoleculeElement(ChemElement):\n pass\n\n\nclass TxtQMoleculeElement(QMoleculeElement, TxtChemElement):\n \"\"\"Represents a chemical fragment pattern expressed within application code\n (i.e. a SMARTS string)\n \"\"\"\n\n def __init__(self, desc):\n TxtChemElement.__init__(self, desc)\n\n\nclass PersistentQMoleculeElement(QMoleculeElement):\n \"\"\"Represents a Molecule value loaded from the database.\"\"\"\n\n def __init__(self, desc):\n self.desc = desc\n\n\nclass BitFingerprintElement(ChemElement):\n pass\n\n\nclass PersistentBitFingerprintElement(BitFingerprintElement):\n \"\"\"Represents a BitFingerprint value loaded from the database.\"\"\"\n\n def __init__(self, desc):\n self.desc = desc\n\n\nclass CntFingerprintElement(ChemElement):\n pass\n\n\nclass PersistentCntFingerprintElement(CntFingerprintElement):\n \"\"\"Represents a CntFingerprint value loaded from the database.\"\"\"\n\n def __init__(self, desc):\n self.desc = desc\n\n\ndef _to_mol(value):\n \"\"\"Interpret a value as a Molecule-compatible construct.\"\"\"\n\n if hasattr(value, '__clause_element__'):\n return value.__clause_element__()\n elif isinstance(value, (expression.ClauseElement, MoleculeElement)):\n return value\n elif isinstance(value, basestring):\n return TxtMoleculeElement(value)\n elif value is None:\n return None\n else:\n raise TypeError\n\n\ndef _to_bfp(value):\n \"\"\"Interpret a value as a BitFingerprint-compatible construct.\"\"\"\n\n if hasattr(value, '__clause_element__'):\n return value.__clause_element__()\n elif isinstance(value, (expression.ClauseElement, BitFingerprintElement)):\n return value\n elif value is None:\n return None\n else:\n raise TypeError\n\n\ndef _to_cfp(value):\n \"\"\"Interpret a value as a IntFingerprint-compatible construct.\"\"\"\n\n if hasattr(value, '__clause_element__'):\n return value.__clause_element__()\n elif isinstance(value, (expression.ClauseElement, CntFingerprintElement)):\n return value\n elif value is None:\n return None\n else:\n raise TypeError\n","sub_path":"razi/expression.py","file_name":"expression.py","file_ext":"py","file_size_in_byte":3918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"413617881","text":"import time\n\nfrom logger import logger\n\nfrom perfrunner.helpers.rest import RestHelper\n\n\nclass Monitor(RestHelper):\n\n POLLING_INTERVAL = 5\n MAX_RETRY = 10\n\n DISK_QUEUE_METRICS = (\n 'ep_queue_size',\n 'ep_flusher_todo',\n )\n TAP_REPLICATION_METRICS = (\n 'vb_replica_queue_size',\n 'ep_tap_replica_queue_itemondisk',\n 'ep_tap_rebalance_queue_backfillremaining',\n 'ep_tap_replica_qlen',\n )\n\n def monitor_rebalance(self, host_port):\n logger.info('Monitoring rebalance status')\n is_running = True\n while is_running:\n time.sleep(self.POLLING_INTERVAL)\n\n is_running, progress = self.get_rebalance_status(host_port)\n\n if progress is not None:\n logger.info('Rebalance progress: {} %'.format(progress))\n logger.info('Rebalance completed')\n\n def _wait_for_null_metric(self, host_port, bucket, metric):\n retry = 0\n while retry < self.MAX_RETRY:\n time.sleep(self.POLLING_INTERVAL)\n\n bucket_stats = self.get_bucket_stats(host_port, bucket)\n try:\n value = bucket_stats['op']['samples'][metric][-1]\n except KeyError:\n logger.warn('Got broken bucket stats')\n retry += 1\n continue\n else:\n retry = 0\n\n if value:\n logger.info('Current value of {}: {}'.format(metric, value))\n else:\n logger.info('{} reached 0'.format(metric))\n return\n logger.interrupt('Failed to get bucket stats after {} attempts'.format(\n self.MAX_RETRY\n ))\n\n def monitor_disk_queue(self, host_port, bucket):\n logger.info('Monitoring disk queue: {}'.format(bucket))\n for metric in self.DISK_QUEUE_METRICS:\n self._wait_for_null_metric(host_port, bucket, metric)\n\n def monitor_tap_replication(self, host_port, bucket):\n logger.info('Monitoring TAP replication: {}'.format(bucket))\n for metric in self.TAP_REPLICATION_METRICS:\n self._wait_for_null_metric(host_port, bucket, metric)\n\n def monitor_xdcr_replication(self, host_port, bucket):\n logger.info('Monitoring XDCR replication: {}'.format(bucket))\n metric = 'replication_changes_left'\n self._wait_for_null_metric(host_port, bucket, metric)\n\n def monitor_task(self, host_port, task_type):\n logger.info('Monitoring task: {}'.format(task_type))\n\n while True:\n time.sleep(self.POLLING_INTERVAL)\n\n tasks = [task for task in self.get_tasks(host_port)\n if task.get('type') == task_type]\n if tasks:\n for task in tasks:\n logger.info('{}: {}%, bucket: {}, ddoc: {}'.format(\n task_type, task.get('progress'),\n task.get('bucket'), task.get('designDocument')\n ))\n else:\n break\n logger.info('Task {} successfully completed'.format(task_type))\n\n def monitor_warmup(self, memcahed, host, bucket):\n logger.info('Monitoring warmup status: {}@{}'.format(bucket, host))\n while True:\n stats = memcahed.get_stats(host, bucket, 'warmup')\n state = stats['ep_warmup_state']\n if state == 'done':\n return float(stats['ep_warmup_time'])\n else:\n logger.info('Warmpup status: {}'.format(state))\n time.sleep(self.POLLING_INTERVAL)\n","sub_path":"perfrunner/helpers/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"447977922","text":"# -*- coding: utf-8 -*-\nDB_HOST = '127.0.0.1'\n# DB_HOST = '127.0.0.1'\nDB_USER = 'root'\n# DB_USER = 'root'\nDB_PWD = ''\n# DB_PWD = '084358'\nDB_NAME = 'my_tornado'\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base() # create Base lei\nengine = create_engine('mysql://%s:%s@%s/%s?charset=utf8' %\n (DB_USER, DB_PWD, DB_HOST, DB_NAME),\n encoding='utf-8', echo=False,\n pool_size=100, pool_recycle=10)\n\n\ndef init_db():\n Base.metadata.create_all(engine)\n","sub_path":"db_use/core/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"148588137","text":"# -*- coding: utf-8 -*-\n\n# 1. 列表生成式练习\nL1 = ['Hello', 'World', 18, 'Kay', None]\n\ndef listcreator(L):\n L2 = [s.lower() for s in L if isinstance(s, str)] # if isinstance(s, str) == True\n print(L2)\n\n# 2. 斐波那契数列 Generator练习\ndef fib(num):\n n, a, b = 0, 0, 1\n while n < num:\n yield b\n a, b = b, a + b\n n += 1\n return 'Done'\n\n# 3. 杨辉三角\ndef yangtri(grade):\n # 建立一个计算杨辉三角的generator,用yield返回它的值\n def triangle(grade):\n L = [1]\n n = 0\n while n < grade:\n yield L\n L.append(0)\n L = [L[i - 1] + L[i] for i in range(len(L))]\n n = n + 1\n\n # 用for循环来迭代输出\n for n in triangle(grade):\n print(n)\n return 'Done'\n\n","sub_path":"advanced_features.py","file_name":"advanced_features.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"67373678","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n\turl(r\"^failures/$\", views.UploadFailuresListView.as_view(), name=\"failures_list\"),\n\turl(\n\t\tr\"^upload/(?P[\\w-]+)/$\", views.UploadDetailView.as_view(),\n\t\tname=\"upload_detail\"\n\t),\n]\n","sub_path":"hsreplaynet/uploads/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"392873090","text":"from html.parser import HTMLParser\n\n# create a subclass and override the handler methods\n\n\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n print(\"Start :\", tag)\n for attr in attrs:\n print(\"-> {} > {}\".format(attr[0], attr[1]))\n\n def handle_endtag(self, tag):\n print(\"End :\", tag)\n\n def handle_startendtag(self, tag, attrs):\n print(\"Empty :\", tag)\n for attr in attrs:\n print(\"-> {} > {}\".format(attr[0], attr[1]))\n\n\nn = int(input())\ntext = \"\"\nfor _ in range(n):\n text += input()\n\nparser = MyHTMLParser()\nparser.feed(text)\n","sub_path":"Python Practice/HTML_Parser_1.py","file_name":"HTML_Parser_1.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"167919116","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 25 13:02:05 2018\n\n@author: jie\n\"\"\"\n\nimport os\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\n\n\nclass LINE(object):\n def __init__(self, n_embedding, epislon = 0.1, max_iteration = 1000, \n alpha_1 = 10, alpha_2 = 10):\n self.n_embedding = n_embedding\n self.max_iterations = max_iteration\n self.epislon = epislon\n self.alpha_1 = alpha_1\n self.alpha_2 = alpha_2\n \n def calc_laplace_matrix(self, matrix):\n matrix_s = np.dot(matrix, matrix.T)\n matrix_d = np.diag(np.sum(matrix_s, axis = 1))\n matrix_d_neg_sqrt = np.power(matrix_d, -1/2)\n matrix_d_neg_sqrt[np.isinf(matrix_d_neg_sqrt)] = 0\n# matrix_d_neg_sqrt = np.power(np.linalg.matrix_power(matrix_d, -1), 0.5)\n\n matrix_laplace = np.dot(matrix_d_neg_sqrt, \n np.dot(matrix_s, matrix_d_neg_sqrt))\n \n return matrix_laplace\n \n def get_k_eigen_vector(self, eigen_value, eigen_vector, k):\n index_choice = np.argsort(-eigen_value)[0:k]\n return eigen_vector[:, index_choice]\n \n def solve_formula(self, variable, matrix_laplace,\n matrix_u_a, matrix_u_g, matrix_u_y, matrix_h):\n \n\n if variable == 'g':\n matrix_sum = (matrix_laplace + \n self.alpha_1 * np.dot(matrix_u_a, matrix_u_a.T) + \n self.alpha_2 * np.dot(matrix_u_y, matrix_u_y.T) + \n np.dot(matrix_h, matrix_h.T))\n \n elif variable == 'a':\n matrix_sum = (self.alpha_1 * matrix_laplace + \n self.alpha_1 * np.dot(matrix_u_g, matrix_u_g.T) + \n np.dot(matrix_u_y, matrix_u_y.T) + \n np.dot(matrix_h, matrix_h.T))\n \n elif variable == 'y':\n matrix_sum = (self.alpha_2 * matrix_laplace + \n self.alpha_2 * np.dot(matrix_u_g, matrix_u_g.T) + \n np.dot(matrix_u_y, matrix_u_y.T) + \n np.dot(matrix_h, matrix_h.T))\n \n elif variable == 'h':\n matrix_sum = (np.dot(matrix_u_g, matrix_u_g.T) +\n np.dot(matrix_u_a, matrix_u_a.T) + \n np.dot(matrix_u_y, matrix_u_y.T))\n else:\n print(\"Variable error\")\n \n eigen_value, eigen_vector = np.linalg.eig(matrix_sum)\n return self.get_k_eigen_vector(eigen_value, eigen_vector, self.n_embedding)\n \n \n \n def fit(self, data, attribute, labels):\n laplace_g = self.calc_laplace_matrix(data)\n laplace_a = self.calc_laplace_matrix(attribute)\n laplace_y = self.calc_laplace_matrix(labels)\n \n matrix_u_g = np.random.random([data.shape[0], self.n_embedding])\n matrix_u_a = np.random.random([data.shape[0], self.n_embedding])\n matrix_u_y = np.random.random([data.shape[0], self.n_embedding])\n matrix_h = np.random.random([data.shape[0], self.n_embedding])\n\n for i in range(self.max_iterations):\n matrix_u_g = self.solve_formula('g', laplace_g, matrix_u_a, matrix_u_g, matrix_u_y, matrix_h)\n matrix_u_a = self.solve_formula('a', laplace_a, matrix_u_a, matrix_u_g, matrix_u_y, matrix_h)\n matrix_u_y = self.solve_formula('y', laplace_y, matrix_u_a, matrix_u_g, matrix_u_y, matrix_h)\n matrix_h = self.solve_formula('h', None, matrix_u_a, matrix_u_g, matrix_u_y, matrix_h)\n \n return matrix_h\n \n \ndef main():\n pass\n\n\ndef shuffle_sample(data, ratio, seed = None):\n '''\n Input: data to be divide, and the ratio of dev data\n Output: train data and dev data\n '''\n population = data.shape[0]\n index_all = np.array(range(data.shape[0]))\n random.seed(10)\n index_valid = random.sample(range(population), int(ratio * population))\n index_train = np.delete(index_all, index_valid, axis = 0)\n return index_train, index_valid\n\ndef read_data(file = \"../input/washington/washington_adj.txt\", sep = '\\t', describe = False):\n df1 = pd.read_csv(file, sep = sep, header = None)\n if describe == True:\n print(\"------------------------------------------------\")\n print(df1.describe())\n print(\"-------------------------------------------------\")\n return np.array(df1)\n\n\nif __name__ == \"__main__\":\n root_path = \"../input/\"\n nmi_list = []\n label_list = os.listdir(root_path)\n for k, folder in enumerate(os.listdir(root_path)):\n file_path = os.path.join(root_path, folder)\n print(\"\\nfile is: \\t\", folder)\n \n labels_init = read_data(file = file_path + \"/\" + folder + \"_label.txt\").flatten()\n data1 = read_data(file = file_path + \"/\" + folder + \"_adj.txt\")\n attrib1 = read_data(file = file_path + \"/\" + folder + \"_feature.txt\")\n\n color = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']\n plt.figure()\n \n labels1 = labels_init\n \n labels1 = labels1.reshape(labels1.shape[0], -1)\n enc = OneHotEncoder()\n enc.fit(labels1)\n labels_onehot = enc.transform(labels1).toarray()\n \n (G_1, G_2, attr_train, attr_test, y_train, y_test, \n labels_onehot_train, labels_onehot_test) = train_test_split(data1, attrib1, labels_init, labels_onehot, test_size=0.2, random_state = 666)\n \n X_train = G_1[0:G_1.shape[0], 0:G_1.shape[0]]\n X_test = G_2[0:G_2.shape[0], 0:G_2.shape[0]]\n \n if k == 0 or k == 1:\n continue\n\n plt.figure()\n for i, alpha_1 in enumerate([0.01, 0.5, 2, 5, 5, 10, 20]):\n acc_list = []\n for alpha_2 in [0.01, 0.1, 0.5, 2, 5, 10, 20]:\n embed = LINE(n_embedding=100, epislon=0.01, max_iteration=200, alpha_1 = alpha_1, alpha_2 = alpha_2)\n embedding_train = embed.fit(X_train, attr_train, labels_onehot_train)\n \n clf = KNeighborsClassifier(10)\n clf.fit(embedding_train, y_train)\n \n eta = 0.5\n embedding_test = (np.dot(G_2, np.linalg.pinv(np.dot(np.linalg.pinv(embedding_train), G_1))) + \n eta * np.dot(attr_test, np.linalg.pinv(np.dot(np.linalg.pinv(embedding_train), attr_train))))\n predict = clf.predict(embedding_test)\n \n accuracy = clf.score(embedding_test, y_test)\n acc_list.append(accuracy)\n plt.plot([0.01, 0.1, 0.5, 2, 5, 10, 20], acc_list, color = color[i], label = \"alpha_1 = {}\".format(alpha_1))\n plt.legend(loc='upper right')\n plt.xlabel(\"alpha_2\")\n plt.ylabel(\"accuracy\")\n plt.show()","sub_path":"network_embedding/code/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"54230807","text":"#Importing libraries\nimport numpy as np\nimport pandas as pd\n\n#reading excel file (if it's in the same folder)\nfile_name = 'Data.xlsx'\npd.read_excel(file_name)\n\n#assigning data from excel file to a data frame\nfile_name = 'Data.xlsx'\ndf = pd.read_excel(file_name)\nprint(df)\n\n#prints list of columns in a dataframe and their data types \ndf.dtypes\n","sub_path":"Code_snippets.py","file_name":"Code_snippets.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"77234461","text":"import random\nimport matplotlib.pyplot as plt\n\nno_of_prog = 3\n\n\ndef get_perc_intel(gen):\n cnt = 0\n for child in gen:\n if child == '11111':\n cnt += 1\n else:\n break\n\n return cnt*100/len(gen)\n\n\ndef flip_bit(bit, index):\n bit_list = list(bit)\n if bit_list[index] == '0':\n bit_list[index] = '1'\n else:\n bit_list[index] = '0'\n\n bit = ''.join(bit_list)\n return bit\n\n\ndef eliminate(gen):\n\n ability = dict()\n survivors = []\n for index in range(len(gen)):\n number = list(gen[index])\n number = [int(i) for i in number]\n one_bits = sum(number)\n\n ability[index] = one_bits\n\n ability = sorted(ability.items(), key=lambda x: x[1], reverse=True)\n\n # print(\"ability\", ability)\n surviving_number = int(3*len(gen) / 4)\n cnt = 0\n for index in ability:\n survivors.append(gen[index[0]])\n cnt += 1\n #if cnt > surviving_number:\n # break\n\n return survivors\n\n\ndef get_random_elements(progeny, choices):\n \"\"\"\n\n :param progeny: (list) total available options\n :param choices: (int) total no of choices\n :return: list: choices\n \"\"\"\n # print(\"prog\", progeny)\n return random.sample(progeny, choices)\n\n\ndef get_a_child(parent1, parent2):\n \"\"\"\n\n :param parent1: (str) parent1\n :param parent2: (str) parent2\n :return: returns a child\n \"\"\"\n\n # getting a new child without any new character\n parents = [parent1, parent2]\n child = ''\n for i in range(len(parent1)):\n choice = random.randint(0, 1)\n child += parents[choice][i]\n\n # determining how much change will be there\n # there can be atmost half of length change and at least one change\n no_of_changes = random.randint(1, int(len(parent1) / 4)) # new character\n indices_of_changes = random.sample(range(0, len(parent1)), no_of_changes)\n\n # setting new changes to the child\n for bit in indices_of_changes:\n child = flip_bit(child, bit)\n\n return child\n\n\ndef get_next_gen_of_one_family(parent1, parent2):\n children = []\n for choice in range(no_of_prog):\n children.append(get_a_child(parent1, parent2))\n\n return children\n\n\ndef get_next_gen_raw(prev_gen):\n # making two element pairs\n # making new families\n if len(prev_gen) <= 1:\n return []\n possibilities = [i for i in prev_gen]\n next_population = []\n # print(\"possibilities\", prev_gen)\n\n while len(possibilities) > 1:\n new_gen = []\n # print(\"possibilities\", possibilities)\n new_possibility = get_random_elements(possibilities, 2)\n # print(\"new indices\", new_indices)\n possibilities.remove(new_possibility[0])\n possibilities.remove(new_possibility[1])\n\n new_gen.append(get_next_gen_of_one_family(new_possibility[0], new_possibility[1]))\n\n # print(new_gen)\n for gen in new_gen[0]:\n next_population.append(gen)\n\n return next_population\n\n\ngen = ['00111', '00110']\nintel = []\nindex = []\nno_of_prog = random.randint(2, 4)\nfor i in range(15):\n talent = get_perc_intel(gen)\n index.append(i)\n intel.append(talent)\n print(\"level\", i)\n # print(gen)\n gen = get_next_gen_raw(gen)\n length = len(gen)\n print(\"POPULATION\", length)\n gen = eliminate(gen)\n if len(gen) == 0:\n print(\"SPECIES DID NOT SURVIVE\")\n break\n print(\"percentage intelligent\", talent)\n \"\"\"\n if length != len(gen):\n print(\"elemination took place\")\n else:\n print(\"no eleminations\")\n \"\"\"\n\nprint(\"final gen\", gen)\n\ntalent = get_perc_intel(gen)\nindex.append(i + 1)\nintel.append(talent)\n\ncnt = 0\nfor child in gen:\n if child == '11111':\n cnt += 1\n else:\n break\n\nif len(gen) > 5:\n plt.plot(index, intel)\n plt.show()\nprint(\"percentage intelligent\", cnt*100/len(gen), \"people intelligent\", cnt)\n","sub_path":"human_cradle.py","file_name":"human_cradle.py","file_ext":"py","file_size_in_byte":3874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"288962419","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nConfig module.\n\nAuthor: HuangTao\nDate: 2018/05/03\nEmail: huangtao@ifclover.com\n\"\"\"\n\nimport json\n\nfrom quant.utils import tools\nfrom quant.utils import logger\n\n\nclass Config:\n \"\"\" Config module will load a json file like `config.json` and parse the content to json object.\n 1. Configure content must be key-value pair, and `key` will be set as Config module's attributes;\n 2. Invoking Config module's attributes cat get those values;\n 3. Some `key` name is upper case are the build-in, and all `key` will be set to lower case:\n SERVER_ID: Server id, every running process has a unique id.\n RUN_TIME_UPDATE: If this server support run-time-update(receive EventConfig), True or False, default is False.\n LOG: Logger print config.\n RABBITMQ: RabbitMQ config, default is None.\n MONGODB: MongoDB config, default is None.\n REDIS: Redis config, default is None.\n PLATFORMS: Trading Exchanges config, default is {}.\n ACCOUNTS: Trading Exchanges config list, default is [].\n HEARTBEAT: Server heartbeat config, default is {}.\n HTTP_SERVER: HTTP server config, default is None.\n PROXY: HTTP proxy config, default is None.\n \"\"\"\n\n def __init__(self):\n self.server_id = None\n self.run_time_update = False\n self.log = {}\n self.rabbitmq = {}\n self.mongodb = {}\n self.redis = {}\n self.platforms = {}\n self.accounts = []\n self.heartbeat = {}\n self.http_server = None\n self.proxy = None\n\n def initialize(self):\n if self.run_time_update:\n from quant.event import EventConfig\n EventConfig(self.server_id).subscribe(self._on_event_config)\n\n def loads(self, config_file=None):\n \"\"\" Load config file.\n\n Args:\n config_file: config json file.\n \"\"\"\n configures = {}\n if config_file:\n try:\n with open(config_file) as f:\n data = f.read()\n configures = json.loads(data)\n except Exception as e:\n print(e)\n exit(0)\n if not configures:\n print(\"config json file error!\")\n exit(0)\n self._update(configures)\n\n async def _on_event_config(self, data):\n \"\"\" Config event update.\n\n Args:\n data: New config received from ConfigEvent.\n \"\"\"\n server_id = data[\"server_id\"]\n params = data[\"params\"]\n if server_id != self.server_id:\n logger.error(\"Server id error:\", server_id, caller=self)\n return\n if not isinstance(params, dict):\n logger.error(\"params format error:\", params, caller=self)\n return\n\n params[\"SERVER_ID\"] = self.server_id\n params[\"RUN_TIME_UPDATE\"] = self.run_time_update\n self._update(params)\n logger.info(\"config update success!\", caller=self)\n\n def _update(self, update_fields):\n \"\"\" Update config attributes.\n\n Args:\n update_fields: Update fields.\n \"\"\"\n self.server_id = update_fields.get(\"SERVER_ID\", tools.get_uuid1())\n self.run_time_update = update_fields.get(\"RUN_TIME_UPDATE\", False)\n self.log = update_fields.get(\"LOG\", {})\n self.rabbitmq = update_fields.get(\"RABBITMQ\", None)\n self.mongodb = update_fields.get(\"MONGODB\", None)\n self.redis = update_fields.get(\"REDIS\", None)\n self.platforms = update_fields.get(\"PLATFORMS\", {})\n self.accounts = update_fields.get(\"ACCOUNTS\", [])\n self.heartbeat = update_fields.get(\"HEARTBEAT\", {})\n self.http_server = update_fields.get(\"HTTP_SERVER\", None)\n self.proxy = update_fields.get(\"PROXY\", None)\n\n if self.http_server:\n port = self.http_server.get(\"port\")\n apis = self.http_server.get(\"apis\")\n middlewares = self.http_server.get(\"middlewares\", [])\n ext_uri = self.http_server.get(\"ext_uri\", [])\n if not isinstance(port, int) or port < 1024 or port > 65535:\n logger.error(\"http port error! port:\", port, caller=self)\n exit(0)\n if not isinstance(apis, list):\n logger.error(\"http api pathes error! apis:\", apis, caller=self)\n exit(0)\n if not isinstance(middlewares, list):\n logger.error(\"http middlewares error! middlewares:\", middlewares, caller=self)\n exit(0)\n if not isinstance(ext_uri, list):\n logger.error(\"http ext_uri error! ext_uri:\", ext_uri, caller=self)\n exit(0)\n\n for k, v in update_fields.items():\n setattr(self, k, v)\n\n\nconfig = Config()\n","sub_path":"quant/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"328118506","text":"#!/usr/bin/env python3\nimport argparse\nimport logging\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--log\", default=\"INFO\", choices=[\"INFO\", \"DEBUG\"], help=\"Set log level: INFO,DEBUG\")\nargs = parser.parse_args()\nif args.log == 'INFO':\n loglev = logging.INFO\nelse:\n loglev = logging.DEBUG\n\n# the following sets up the root logger so all subsequent calls get a reference to this one\nfrom ShowControl.utils.ShowControlConfig import LOG_DIR\nlogging.basicConfig(level=loglev,\n filename=LOG_DIR + '/ShowMixer.log', filemode='w',\n format='%(name)s %(levelname)s %(message)s')\n\nfrom ShowMixer.main import main\n\nlogging.info('in cue-engine.py before call to main()')\nmain()\nlogging.info('in cue-engine.py after call to main()')","sub_path":"show-mixer.py","file_name":"show-mixer.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"61177833","text":"from AlgorithmVisualizer import Tracer, Array1DTracer, LogTracer, Layout, VerticalLayout, ChartTracer, randomize\n\n# define tracer variables {\nchart = ChartTracer(\"Bubble Sort - Graph\")\ntracer = Array1DTracer(\"Bubble Sort - Array\")\nlogger = LogTracer()\nLayout.setRoot(VerticalLayout([chart, tracer, logger]))\narray = randomize.Array1D(15).array\ntracer.set(array)\ntracer.chart(chart)\nTracer.delay()\n# }\n\nstring_array = [str(int) for int in array]\nprintln('original array = ['+','.join(string_array)+']')\n\nswapped=True\nn=len(array)\nwhile(swapped):\n\tswapped=False\n\t# visualize {\n\ttracer.select(n-1)\n\tTracer.delay()\n\t# }\n\tfor i in range(1,n):\n\t\t# visualize {\n\t\ttracer.select(i-1,i)\n\t\tTracer.delay()\n\t\t# }\n\t\tif(array[i-1]>array[i]):\n\t\t\tprintln('swap '+str(array[i - 1])+ ' and '+ str(array[i]))\n\t\t\tarray[i - 1], array[i] = array[i], array[i - 1]\n\t\t\tswapped=True\n\t\t\t# visualize {\n\t\t\ttracer.patch(i - 1, array[i - 1])\n\t\t\ttracer.patch(i, array[i])\n\t\t\tTracer.delay()\n\t\t\ttracer.depatch(i - 1)\n\t\t\ttracer.depatch(i)\n\t\t\t# }\n\t\t# visualize {\n\t\ttracer.deselect(i-1,i)\n\t\t# }\n\t# visualize {\n\ttracer.deselect(n-1)\n\ttracer.selectTrue(n-1)\n\t# }\n\tif not swapped:\n\t\t# visualize {\n\t\ttracer.selectTrue(0,n - 1)\n\t\t# }\n\tn-=1\n\nstring_array = [str(int) for int in array]\nprintln('sorted array = ['+','.join(string_array)+']')","sub_path":"src/Algorithms/Sorting/Bubble Sort/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"536130204","text":"import pandas as pd\nfrom tqdm import tqdm\ntqdm.pandas()\nimport json\nimport numpy as np\nimport pickle\nimport os\nimport torch\nfrom sklearn.metrics import f1_score, accuracy_score\n\ndef convert_lines(df, tokenizer, max_seq_length):\n outputs = np.zeros((len(df), max_seq_length))\n \n cls_id = 0 # \n eos_id = 2 # \n pad_id = 1\n\n pbar = tqdm(df.iterrows(), total=len(df))\n pbar.set_description(\"BPE encode\")\n for idx, row in pbar:\n input_ids = tokenizer.encode(row.text, add_special_tokens=True) # add and \n if len(input_ids) > max_seq_length:\n input_ids = input_ids[:max_seq_length]\n input_ids[-1] = eos_id\n else:\n input_ids = input_ids + [pad_id, ]*(max_seq_length - len(input_ids))\n outputs[idx,:] = np.array(input_ids)\n return outputs\n\ndef seed_everything(SEED):\n np.random.seed(SEED)\n torch.manual_seed(SEED)\n torch.cuda.manual_seed(SEED)\n torch.backends.cudnn.deterministic = True\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef get_f1_score(y_true, y_pred):\n new_y_true = y_true.squeeze().detach().cpu().numpy()\n new_y_pred = y_pred.squeeze().detach().cpu().numpy() > 0.5\n new_y_pred = list(map(lambda x: int(x), new_y_pred))\n return f1_score(new_y_true, new_y_pred, average='binary')\n\n\ndef get_accuracy(y_true, y_pred):\n new_y_true = y_true.squeeze().detach().cpu().numpy()\n new_y_pred = y_pred.squeeze().detach().cpu().numpy() > 0.5\n new_y_pred = list(map(lambda x: int(x), new_y_pred))\n return accuracy_score(new_y_true, new_y_pred)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66852014","text":"import requests\n\nfrom Response import Response\n\nclass PingPong:\n\n\tSERVER_ADDRESS = ''\n\n\tTOKEN = ''\n\n\tdef request(self, endpoint: str) -> Response:\n\t\treturn requests.post(self.SERVER_ADDRESS + '/' + endpoint, headers={'Authorization': 'Bearer ' + self.TOKEN})\n\n\tdef ping(self) -> bool:\n\t\tresponse = self.request('ping')\n\t\treturn response.status_code == 200\n\n\tdef connect(self) -> bool:\n\t\tself.request('connect')\n\nif __name__ == '__main__':\n\tpingPong = PingPong()\n\n\tsuccess = pingPong.ping()\n\n\tif (success == False):\n\t\tpingPong.connect()","sub_path":"PingPong.py","file_name":"PingPong.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"437790505","text":"\"\"\"\nMDB.\n\nhttps://github.com/GII/MDB\n\"\"\"\n\n# Python 2 compatibility imports\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom future import standard_library\n\nstandard_library.install_aliases()\nfrom builtins import * # noqa pylint: disable=unused-wildcard-import,wildcard-import\n\n# Standard imports\nimport math\n\n# Library imports\nimport numpy as np\nimport rospy\nfrom std_msgs.msg import Int32, String\n\n# MDB imports\nfrom mdb_common.srv import CandAct\nfrom mdb_motiven.forward_model import ForwardModel\nfrom mdb_motiven.action_chooser import ActionChooser\n\n\nclass CandidateStateEvaluator(object):\n def __init__(self):\n # self.MotivManager = MotivationManager()\n self.ForwModel = ForwardModel()\n self.actionChooser = ActionChooser()\n # Variables to control the Brownian motion (intrinsic motivation)\n self.n_random_steps = 0\n self.max_random_steps = 3\n self.intrinsic_exploration_type = \"Novelty\" # 'Brownian' or 'Novelty'\n self.n = 0.5 # Coefficient that regulates the balance between the relevance of distant and near states\n self.init_ros()\n\n def init_ros(self):\n self.getCandidateActions = rospy.ServiceProxy(\"/candidate_actions\", CandAct)\n\n def getEvaluation(self, candidates, corr_sens, tipo, SimData, sensoriz_t):\n \"\"\"Return the list os candidates actions sorted according to their value\n\n :param candidates: list o candidate actions\n :param corr_sens: number of the correlated sensor. 1 - sensor 1, 2 - sensor 2 ... n-sensor n\n :param tipo: type of the correlation: positive ('pos') or negative ('neg')\n :param SimData: data from the simulator needed to adjust the ForwardModel (baxter_pos, ball_pos, ball_situation, box_pos)\n :param sensoriz_t: actual sensorization to calculate the valuation\n :return: list of candidates actions with its valuation according to the active correlation\n \"\"\"\n # type = type of the correlation: positive ('pos') or negative ('neg')\n evaluated_candidates = []\n for i in range(len(candidates.candidates)):\n valuation = self.getValuation(candidates.candidates[i], corr_sens, tipo, SimData, sensoriz_t)\n evaluated_candidates.append((candidates.candidates[i],) + (valuation,))\n # Ordenor los estados evaluados\n evaluated_candidates.sort(key=lambda x: x[-1])\n return evaluated_candidates\n\n def getValuation(self, candidate, sensor, tipo, SimData, sens_t):\n \"\"\"Return the valuation for each individual candidate\n\n :param candidate: candidate action to evaluate\n :param sensor: number of the correlated sensor. 1 - sensor 1, 2 - sensor 2 ... n-sensor n\n :param tipo: type of the correlation: positive ('pos') or negative ('neg')\n :param SimData: data from the simulator needed to adjust the ForwardModel (baxter_pos, ball_pos, ball_situation, box_pos)\n :param sens_t: actual sensorization to calculate the valuation\n :return: valuation of the candidate state\n \"\"\"\n # Obtengo valoracion aplicando la accion candidata en el modelo de mundo\n sens_t1 = self.ForwModel.predictedState(candidate, SimData)\n # print \"Predicted state Valuation: \", sens_t1, \"Candidate action: \", candidate.baxter_action\n if tipo == \"pos\": # Tengo que alejarme, aumentar la distancia\n valuation = sens_t1[sensor - 1] - sens_t[sensor - 1]\n elif tipo == \"neg\": # Tengo que acercarme, disminuir la distancia\n valuation = sens_t[sensor - 1] - sens_t1[sensor - 1]\n return valuation\n\n def getAction(self, explorationType, SimData, sensorialStateT1, corr_sensor, corr_type, intrinsicMemory):\n # explorationType = self.MotivManager.getActiveMotivation()\n if explorationType == \"Int\": # Intrinsic Motivation\n if self.intrinsic_exploration_type == \"Brownian\":\n # Brownian motion\n self.n_random_steps += 1\n if self.n_random_steps > self.max_random_steps:\n action = np.random.uniform(-45, 45)\n self.max_random_steps = np.random.randint(1, 4)\n self.n_random_steps = 0\n else:\n action = 0\n elif self.intrinsic_exploration_type == \"Novelty\":\n candidate_actions = self.getCandidateActions(Int32(25), Int32(110), String(\"Int\"))\n candidates_eval = self.getNoveltyEvaluation(candidate_actions, intrinsicMemory, SimData)\n print(\"Evaluated Candidates Novelty: \", candidates_eval[-1])\n action = self.actionChooser.chooseAction(candidates_eval)\n else: # Extrinsic motivation -> Correlations\n candidate_actions = self.getCandidateActions(Int32(25), Int32(110), String(\"Ext\"))\n # print candidate_actions\n candidates_eval = self.getEvaluation(candidate_actions, corr_sensor, corr_type, SimData, sensorialStateT1)\n action = self.actionChooser.chooseAction(candidates_eval)\n print(\"action\", action)\n return action\n\n def getNoveltyEvaluation(self, candidates, trajectoryBuffer, SimData):\n \"\"\"Return the list of candidates actions sorted according to their novelty value\n\n :param candidates: list o candidate actions\n :param trajectoryBuffer: buffer that stores the last perceptual states the robot has experienced\n :return: list of candidates actions sorted according to its novelty valuation\n \"\"\"\n evaluated_candidates = []\n for i in range(len(candidates.candidates)):\n valuation = self.getNovelty(candidates.candidates[i], trajectoryBuffer, SimData)\n evaluated_candidates.append((candidates.candidates[i],) + (valuation,))\n # Ordenor los estados evaluados\n evaluated_candidates.sort(key=lambda x: x[-1])\n return evaluated_candidates\n\n def getNovelty(self, candidate_action, trajectoryBuffer, SimData):\n \"\"\"Return the novelty for each individual candidate\n\n :param candidate: candidate action to evaluate its novelty\n :param trajectoryBuffer: buffer that stores the last perceptual states the robot has experienced\n :return: novelty of the candidate state\n \"\"\"\n candidate_state = self.ForwModel.predictedState(candidate_action, SimData)\n novelty = 0\n for i in range(len(trajectoryBuffer)):\n novelty += pow(self.getDistance(candidate_state, trajectoryBuffer[i]), self.n)\n novelty = novelty / len(trajectoryBuffer)\n return novelty\n\n def getDistance(self, p1, p2):\n \"\"\"Return the distance between two points\"\"\"\n (x1, y1, z1) = p1\n (x2, y2, z2) = p2\n return math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2))\n","sub_path":"mdb_motiven/src/mdb_motiven/candidate_state_evaluator.py","file_name":"candidate_state_evaluator.py","file_ext":"py","file_size_in_byte":6871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"621148234","text":"# Loads a simple shout bot from storage\nimport sys\nsys.path.append('..')\n\nfrom persistence.bot_reader import BotReader\n\n\ndef main():\n bot = BotReader('../bots/demo.json').load()\n print(bot.explain('Hi, world!'))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"botkit/scripts/load_file.py","file_name":"load_file.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"128237609","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('about_us', views.about, name='about_us'),\n path('officer/edit', views.edit_officer, name=\"edit_officer\"),\n path('select_officer_edit', views.selectofficertoedit, name='select_officer_edit'),\n path('remove_officer', views.delete_officer, name='remove_officer'),\n path('newofficer', views.new_officer, name=\"new_officer\"),\n path('edit_description', views.edit_description, name = 'edit_description')\n]","sub_path":"about/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"382172296","text":"nuclearwating = -1\nimport random\nclass minseong:\n\n def __init__(self):\n self.hp = random.randrange(250, 300)\n self.mp = random.randrange(40, 50)\n self.atk = random.randrange(30, 50)\n\n def attack(self):\n return self.atk\n\n\n def defend(self, damage):\n self.mp = self.mp + random.randrange(20, 40)\n if(c == 1):\n self.hp = self.hp - damage\n print('일반공격을 시전하엿다!')\n elif(c == 2):\n self.Feedback()\n print('환류를 시전하엿다!')\n elif(c == 3):\n self.nuclear()\n print('핵공격이 감지되엇습니다')\n\n\n def nuclear(self):\n print('사용자는 3턴간 움직이지 못하며 3턴뒤 폭*파 합니다')\n\n def Feedback(self):\n self.mp = self.mp - self.mp/2\n if (turn == 0):\n player2.hp = player2.hp - player2.mp\n player2.mp = 0\n if (turn == 1):\n player1.hp = player1.hp - player1.mp\n player1.mp = 0\n\n def see_hp1(self):\n return self.hp\n\n\nplayer1 = minseong()\nplayer2 = minseong()\nturn = 0\nwhile(player1.hp > 0 or player2.hp > 0):\n print(\"player1 hp\", player1.hp, \" player2 hp\", player2.hp)\n print(\"player1 mp\", player1.mp, \" player2 mp\", player2.mp)\n print(\"player1 atk\", player1.atk, \" player2 atk\", player2.atk)\n if(turn == 0):\n c = int(input('enter the number(plater1 turn)(1, attack)'))\n if(c == 1):\n print(\"Selct attck\")\n d = player1.attack()\n player2.defend(d)\n\n elif(c == 2):\n print('select attatck')\n d = player1.attack()\n player1.defend(d)\n turn = 1\n\n else:\n c = int(input('enter the number(plater2 turn)(1, attack)'))\n if (c == 1):\n d = player2.attack()\n player1.defend(d)\n turn = 0\n elif(c == 2):\n d = player2.attack()\n player1.defend(d)\n turn = 0\n elif(c == 3):\n d = player2.attack()\n player1.defend(d)\n turn = 0\n\n\n","sub_path":"carictor.py","file_name":"carictor.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"527927339","text":"import datetime\n\nfrom .base import *\n\nSITE_ID = 1\nDEBUG = True\nTEMPLATE_DEBUG = True\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'edtrac',\n 'USER': 'mtrack',\n 'PASSWORD': 'mtrack',\n 'HOST': 'localhost',\n }\n}\n\nINSTALLED_APPS += (\n # 'django_extensions',\n 'django.contrib.staticfiles',\n #'debug_toolbar',\n)\n\n#MIDDLEWARE_CLASSES += (\n# 'debug_toolbar.middleware.DebugToolbarMiddleware',\n#)\n\nINTERNAL_IPS += ('127.0.0.1', '::1')\nDEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False\n}\n\nLOGGING['handlers']['mail_admins'] = {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler',\n }\n\nLOGGING['loggers']['django.request'] = {\n 'handlers': ['mail_admins'],\n 'level': 'DEBUG',\n 'propagate': True,\n }\n\nSPREADSHEETS_PATH = filedir\n\nTEMPLATE_DIRS = { '/home/fsarker/projects/rapidsms-sandbox/edtrac/edtrac-env/django/contrib/admin/templates/' }\n\nSTATICFILES_DIR = { '/home/fsarker/projects/rapidsms-sandbox/edtrac/edtrac-env/django/contrib/admin/static/admin/' }\n","sub_path":"edtrac_project/settings/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"366930461","text":"\"\"\"\nDjango settings for jemimaolivia project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n\nimport os\nfrom django.core.exceptions import ImproperlyConfigured\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nDEBUG = False\nwith open('/home/chriswmann/.env_vars', 'r') as fin:\n for l in fin:\n if l.startswith('JO_DB_PASSWORD'):\n JO_DB_PASSWORD = l.split('=')[1].rstrip()\n if l.startswith('ENV_ROLE'):\n ENV_ROLE = l.split('=')[-1]\n if l.startswith('SECRET_KEY'):\n SECRET_KEY = l.split('=')[-1]\n\nif ENV_ROLE == 'debug':\n DEBUG = TEMPLATE_DEBUG = True\n ALLOWED_HOSTS = ['*']\nelse:\n DEBUG = TEMPLATE_DEBUG = False\n ALLOWED_HOSTS = ['www.jemimaolivia.com', 'jemimaolivia.com', '138.68.143.100', 'localhost']\n #ALLOWED_HOSTS = ['*']\n\n# Application definition\nINSTALLED_APPS = (\n 'apps.base',\n 'apps.home',\n 'apps.gallery',\n 'apps.about',\n 'apps.contact',\n 'apps.collection',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n)\n\nMIDDLEWARE_CLASSES = (\n 'common.redirect.RedirectTrailingSlashMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'jemimaolivia.urls'\n\nWSGI_APPLICATION = 'jemimaolivia.wsgi.application'\n\nAPPEND_SLASH = False\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'jemimaolivia_db',\n 'USER': 'jemimaolivia_db_user',\n 'PASSWORD': JO_DB_PASSWORD,\n 'HOST': 'localhost',\n 'PORT': '',\n }\n}\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'APP_DIRS': True,\n 'DIRS': os.path.join(BASE_DIR, 'templates').replace('\\\\','/'),\n 'OPTIONS': {\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth'\n ],\n \t},\n\t},\n]\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-gb'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\nSTATIC_ROOT = os.path.join(BASE_DIR, \"static/\")\nSTATIC_URL = '/static/' #if DEBUG else 'http://jemimaolivia.com/static/'\n\n# Logging\n\nLOG_PATH = BASE_DIR\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'error_file': {\n 'level': 'ERROR',\n 'filename': os.path.join(LOG_PATH, 'error.log'),\n 'class':'logging.handlers.RotatingFileHandler',\n 'maxBytes': 1 * 1024 * 1024,\n 'backupCount': 2\n\t\t},\n 'gunicorn_error_file': {\n 'level': 'DEBUG',\n 'filename': os.path.join(LOG_PATH, 'gunicorn_error.log'),\n 'class':'logging.handlers.RotatingFileHandler',\n 'maxBytes': 1 * 1024 * 1024,\n 'backupCount': 2\n\t\t},\n 'access_file': {\n 'class':'logging.handlers.RotatingFileHandler',\n 'filename': os.path.join(LOG_PATH, 'access.log'),\n }\n },\n 'loggers': {\n 'django': {\n 'handlers': ['error_file'],\n 'level': 'ERROR',\n 'propagate': True\n },\n 'gunicorn.error': {\n 'level': 'DEBUG',\n 'handlers': ['gunicorn_error_file'],\n 'propagate': True,\n },\n 'gunicorn.access': {\n 'level': 'INFO',\n 'handlers': ['access_file'],\n 'propagate': False,\n },\n }\n}\n","sub_path":"jemimaolivia/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"207916019","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\venues\\cafe_venue\\cafe_friend_sim_situation.py\n# Compiled at: 2015-09-29 03:46:46\n# Size of source mod 2**32: 4270 bytes\nfrom sims4.tuning.instances import lock_instance_tunables\nfrom situations.bouncer.bouncer_types import BouncerExclusivityCategory\nfrom situations.situation import Situation\nfrom situations.situation_complex import CommonSituationState, SituationComplexCommon, SituationStateData, TunableSituationJobAndRoleState\nfrom situations.situation_types import SituationCreationUIOption\nfrom venues.cafe_venue.cafe_situations_common import _OrderCoffeeState, _PreOrderCoffeeState\n\nclass _FriendBehaviorState(CommonSituationState):\n pass\n\n\nclass CafeFriendSimSituation(SituationComplexCommon):\n INSTANCE_TUNABLES = {'pre_order_coffee_state':_PreOrderCoffeeState.TunableFactory(description='\\n The situation state used for when a Sim is arriving as a Cafe\\n Friend Sim.\\n ',\n tuning_group=SituationComplexCommon.SITUATION_STATE_GROUP,\n display_name='01_pre_order_coffee_situation_state'), \n 'order_coffee_state':_OrderCoffeeState.TunableFactory(description='\\n The situation state used for when a Sim is ordering coffee as a Cafe\\n Friend Sim.\\n ',\n tuning_group=SituationComplexCommon.SITUATION_STATE_GROUP,\n display_name='02_order_coffee_situation_state'), \n 'friend_behavior_state':_FriendBehaviorState.TunableFactory(description='\\n The main state of the situation. This is where Sims will do \\n behavior after ordering coffee\\n ',\n tuning_group=SituationComplexCommon.SITUATION_STATE_GROUP,\n display_name='03_friend_behavior_state'), \n 'cafe_friend_job':TunableSituationJobAndRoleState(description=\"\\n The default job for a Sim in this situation. This shouldn't\\n actually matter because the Situation will put the Sim in the Order\\n Coffee State when they are added.\\n \")}\n REMOVE_INSTANCE_TUNABLES = Situation.NON_USER_FACING_REMOVE_INSTANCE_TUNABLES\n\n def __init__(self, *arg, **kwargs):\n (super().__init__)(*arg, **kwargs)\n self._friend_sim = None\n\n @classmethod\n def _states(cls):\n return (SituationStateData(1, _PreOrderCoffeeState, factory=(cls.pre_order_coffee_state)),\n SituationStateData(2, _OrderCoffeeState, factory=(cls.order_coffee_state)),\n SituationStateData(3, _FriendBehaviorState, factory=(cls.friend_behavior_state)))\n\n @classmethod\n def _get_tuned_job_and_default_role_state_tuples(cls):\n return [(cls.cafe_friend_job.job, cls.cafe_friend_job.role_state)]\n\n def _on_set_sim_job(self, sim, job_type):\n super()._on_set_sim_job(sim, job_type)\n self._friend_sim = sim\n\n def get_order_coffee_state(self):\n return self.order_coffee_state()\n\n def get_post_coffee_state(self):\n return self.friend_behavior_state()\n\n @classmethod\n def default_job(cls):\n return cls.cafe_friend_job.job\n\n def start_situation(self):\n super().start_situation()\n self._change_state(self.pre_order_coffee_state())\n\n def sim_of_interest(self, sim_info):\n if self._friend_sim is not None:\n if self._friend_sim.sim_info is sim_info:\n return True\n return False\n\n\nlock_instance_tunables(CafeFriendSimSituation, exclusivity=(BouncerExclusivityCategory.NORMAL),\n creation_ui_option=(SituationCreationUIOption.NOT_AVAILABLE),\n _implies_greeted_status=False)","sub_path":"Scripts/simulation/venues/cafe_venue/cafe_friend_sim_situation.py","file_name":"cafe_friend_sim_situation.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"587405208","text":"\"\"\"Tests for creating stories and parsing stuff\"\"\"\n\nfrom io import BytesIO\n\nfrom PIL import Image\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nimport pytest\n\n# from apps.markup.models import BlockTag\nfrom apps.photo.models import ImageFile\nfrom apps.stories.models import Byline, Section, Story, StoryImage, StoryType\nfrom apps.stories.models.sections import default_story_type\n\n\ndef image_data(size=(100, 100), mode='RGB', image_format='png', color='white'):\n \"\"\"Creates binary file content of single color dummy image\"\"\"\n im = Image.new(mode, size, color)\n blob = BytesIO()\n im.save(blob, image_format)\n return blob.getvalue()\n\n\n@pytest.fixture\ndef no_story_types():\n StoryType.objects.all().delete()\n Section.objects.all().delete()\n\n\n@pytest.fixture\ndef dummy_image():\n return ImageFile.objects.create(\n original=SimpleUploadedFile(\n 'dummy.jpg', image_data(image_format='jpeg', color='black')\n ),\n description='blackness',\n )\n\n\n@pytest.fixture\ndef another_hope():\n story = Story(\n title='Another Hope',\n kicker='Episode IV',\n lede=\"\"\"\n It is a period of civil war.\n Rebel spaceships, striking\n from a hidden base, have won\n their first victory against\n the evil Galactic Empire.\n \"\"\",\n bodytext_markup=\"\"\"\n @txt:During the battle, Rebel\n spies managed to steal secret\n plans to the Empire's\n ultimate weapon, the DEATH\n STAR, an armored space\n station with enough power\n to destroy an entire planet.\n\n @txt:Pursued by the Empire's\n sinister agents, Princess\n Leia races home aboard her\n starship, custodian of the\n stolen plans that can save her\n people and restore\n freedom to the galaxy....\n \"\"\"\n )\n story.save()\n Byline.create('text: George Lucas, film director', story)\n return story\n\n\n@pytest.mark.django_db\ndef test_fixture(another_hope, dummy_image):\n \"\"\"Fixture story with fixture story image.\"\"\"\n another_hope.publication_status = Story.STATUS_FROM_DESK\n another_hope.clean()\n another_hope.save()\n StoryImage.objects.create(\n imagefile=dummy_image,\n parent_story=another_hope,\n caption='Dark: total blackness',\n creditline='created by the universe',\n )\n another_hope.refresh_from_db()\n assert another_hope.byline_set.count() == 1\n assert another_hope.images.count() == 1\n\n\n@pytest.mark.django_db\ndef test_that_db_is_empty(no_story_types):\n \"\"\"There should be no content\"\"\"\n assert Story.objects.count() == 0\n assert Section.objects.count() == 0\n assert StoryType.objects.count() == 0\n\n # create one section and story type\n default_story_type()\n assert Section.objects.count() == 1\n assert StoryType.objects.count() == 1\n\n\n@pytest.mark.django_db\ndef test_new_story(no_story_types):\n \"\"\"It's possible to create an empty story\"\"\"\n story = Story.objects.create()\n assert story.pk\n assert story.get_html() == ''\n assert story.get_absolute_url() == f'/{story.section}/{story.pk}/'\n\n\n@pytest.mark.django_db\ndef test_new_story_type():\n \"\"\"It's possible to create an empty story\"\"\"\n stype = StoryType.objects.create(name='Test Story Type')\n assert stype.slug == 'test-story-type'\n","sub_path":"django/apps/stories/tests/test_new_story.py","file_name":"test_new_story.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"76376869","text":"from django import forms\nfrom .models import Course\n\n\nclass CourseForm(forms.ModelForm):\n class Meta:\n model = Course\n fields = ['name', 'description', 'status']\n widgets = {\n 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Name'}),\n 'description': forms.Textarea(\n attrs={'rows': 10, 'class': 'form-control', 'style': 'resize:vertical;',\n 'placeholder': 'Write some thing...'}),\n 'status': forms.Select(\n attrs={'class': 'form-control selector', 'title': 'Status'})\n }\n\n def __init__(self, *args, **kwargs):\n super(CourseForm, self).__init__(*args, **kwargs)\n\n\n","sub_path":"apps/courses/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"378927273","text":"import sys\nimport os\nimport json \nfrom argparse import ArgumentParser\nimport matplotlib.pyplot as plt\n\ndef stats(data, graphname):\n fig, ax = plt.subplots()\n markers = ['o', '*', '^', 's']\n # i is only used to change the markers in the scatter plot\n i = 0\n for fname, responses in data:\n size_latency_pairs = []\n for response in responses:\n if response['type'] == 'LAYER':\n size_latency_pairs.append((response['size']/(1024*1024), response['duration']))\n\n size_latency_pairs.sort(key = lambda x: x[0])\n zippedlist = list(zip(*size_latency_pairs))\n ax.scatter(zippedlist[0], zippedlist[1], label=fname, marker=markers[i])\n i += 1\n ax.set(xlabel='size of layers (mb)', ylabel='latency (seconds)', title='latency for different layer sizes: '+graphname)\n ax.grid()\n ax.legend()\n fig.savefig(graphname[:])\n plt.show()\n\n\n\n\ndef main():\n parser = ArgumentParser(description='Input json file name')\n parser.add_argument('-i', '--inputs', dest='inputs', nargs='+', required=True,\n help = 'input the json files that contain the data for the scatter plot')\n parser.add_argument('-n', '--name', dest='gname', required=True, help='A name for the graph')\n\n args = parser.parse_args()\n fnames = args.inputs\n gname = args.gname\n data = []\n for fname in fnames:\n with open(fname, 'r') as fp:\n data.append((fname[:-5], json.load(fp)))\n \n stats(data, gname)\n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"run/results/clientresults/latencygraph.py","file_name":"latencygraph.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"120274686","text":"#!/usr/bin/env python3\nimport hashlib\nimport itertools\n\n\ndef keystream(seed):\n i = 0\n while (True):\n m = '{}{}'.format(seed, i)\n for k in range(0, 2017):\n m = hashlib.md5(m.encode('ascii')).hexdigest()\n yield i,m\n i += 1\n\n\ndef search3(key):\n for i in range(0, len(key) - 2):\n c = key[i]\n xx = c * 3\n if key[i:i+3] == xx:\n return c\n\ndef search5(i, key, c):\n xx = c[0] * 5\n if xx in key:\n # print('found ', xx, ' in ', i, key)\n return True\n return False\n\n\ndef solve(problem):\n seed = problem\n goal = 64\n\n total = 0\n last_index = -1\n\n keys = keystream(seed)\n\n while total < goal:\n i,key = next(keys)\n\n match3 = search3(key)\n if match3:\n keys, g1 = itertools.tee(keys)\n\n valid = False\n for k in range(0, 1000):\n ii,sub = next(g1)\n if search5(ii, sub, match3):\n valid = True\n break\n\n if valid:\n last_index = i\n total += 1\n\n # print(total, i, key)\n\n return last_index\n\n\ndef test():\n assert next(keystream('abc')) == (0, 'a107ff634856bb300138cac6568c0f24')\n assert solve('abc') == 22551\n\n\ndef getinput():\n import fileinput\n with fileinput.input() as f:\n return ''.join(f).strip()\n\n\nif __name__ == '__main__':\n # test()\n print(solve(getinput()))\n","sub_path":"code/14-2-one_time_pad/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"58134677","text":"D={1:'a',2:('aa','bb'),3:33}\nprint(\"Given Dictionary is : \",D)\nL1=[]\nL=D.values()\nfor i in L:\n L1.append(i)\nL1.reverse()\n\nb=0\nfor k in D.keys():\n D[k]=L1[b]\n b+=1\n\n# print(L1,type(L1))\nprint(\"Reversing the values of the Dictionary\",D,type(D))","sub_path":"Reversing_Dictionary_Vaues.py","file_name":"Reversing_Dictionary_Vaues.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"76427385","text":"#encoding: utf-8\nfrom OpenOrange import *\nfrom Supplier import Supplier\n\nParentReturnSupplierDoc = SuperClass(\"ReturnSupplierDoc\",\"Document\",__file__)\nclass ReturnSupplierDoc(ParentReturnSupplierDoc):\n\n def printAditionalReturnSupplier(self, var):\n self.printRecordFields(\"Supplier\",var.SupCode)\n total = 0\n totqty = 0\n for rsrow in var.Items:\n total = total + rsrow.Qty*rsrow.Price\n totqty = totqty + rsrow.Qty\n self.setStringValue(\"Total\", total)\n self.setStringValue(\"TotalQty\", totqty)\n \n supplier = Supplier.bring(var.SupCode)\n if supplier:\n address = \"%s - %s\" %(supplier.Address,supplier.City) \n if supplier.ZipCode:\n address += \" (%s)/%s \" %(supplier.ZipCode,supplier.Province)\n else:\n address += \" / %s\" %(supplier.Province)\n self.setStringValue(\"Supplier.AddressCityZipCode\", address)\n self.setStringValue(\"Supplier.TaxRegTypes\", Supplier.TaxRegTypes[supplier.TaxRegType])\n","sub_path":"standard/documents/ReturnSupplierDoc.py","file_name":"ReturnSupplierDoc.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"159383422","text":"from pandas import DataFrame, read_csv, to_datetime, DateOffset\n\nclass TblMessage:\n\tdef __init__(self):\n\t\tself.data = {}\n\t\tself.banIdMap = {}\n\t\tself.unitNumberMap = {}\n\t\tself.switch()\n\n\tdef switch(self):\n\t\torig = read_csv('smart-cell_dealer-outlet/2015073002111471474-smart-cell_communications-report-220-commission_activity_-_event-2014-12-01.csv', encoding='utf-8')\n\t\tmsg = read_csv('tblCrmMessages-orig.csv', encoding='utf-8')\n\t\tprint('finished reading')\n\t\tmsg_banIds = list(set(msg['ban_id']))\n\t\tprint(msg_banIds)\n\n\t\tvalues = {}\n\t\tnewVals = []\n\n\t\tfor index, row in orig.iterrows():\n\t\t\tif row['UNIT NUMBER'] not in values.keys():\n\t\t\t\tvalues[row['UNIT NUMBER']] = row['BAN #']\n\t\t\t\tnewVals.append([row['BAN #'], row['UNIT NUMBER']])\n\n\t\tfor msg_banId, newValues in zip(msg_banIds, newVals):\n\t\t\tself.data[msg_banId] = newValues\n\n\t\tfor msg_banId, newValues in self.data.items():\n\t\t\tmsg.ix[msg['ban_id']==msg_banId, 'message_to'] \t= newValues[1]\n\t\t\tself.banIdMap[msg_banId] = newValues[0]\n\t\tprint(self.banIdMap)\n\t\tprint('before replace')\n\t\tmsg = msg.replace(to_replace={'ban_id':self.banIdMap})\n\t\tprint('after replace')\n\t\tmsg.to_csv('tblCrmMessages.csv', enoding='utf-8', index=False)\n","sub_path":"app/functions/tblMessage.py","file_name":"tblMessage.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"388694915","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import Counter\nfrom sklearn.decomposition import PCA\nfrom sklearn.neighbors import KNeighborsClassifier\nimport PCA_lab10 as lab10\n\n\ndef process_data(data, train_ratio):\n df = pd.read_csv(data)\n train_ratio = 0.75\n\n num_rows = df.shape[0]\n train_set_size = int(num_rows * train_ratio)\n\n as_list = list(range(num_rows))\n\n train_indices = as_list[:train_set_size]\n test_indices = as_list[train_set_size:]\n\n train_data = df.iloc[train_indices, :]\n test_data = df.iloc[test_indices, :]\n\n train_features = train_data.drop(\"digit\", axis=1, inplace=False)\n train_labels = train_data.loc[:, \"digit\"]\n\n test_features = test_data.drop(\"digit\", axis=1, inplace=False)\n test_labels = test_data.loc[:, \"digit\"]\n\n return train_features, train_labels, test_features, test_labels\n\n\ndef scree_plot(eigen):\n plt.plot(range(64), eigen, \"ro-\", label=\"Scree plot\")\n plt.xlabel(\"Principle Component\")\n plt.ylabel(\"Proportion of Variance Explained\")\n plt.title(\"Proportion of Variance Explained by each Principle Component\")\n legend = plt.legend(loc=\"upper right\", fontsize=\"medium\")\n plt.show()\n\n\ns_data = process_data(\"data_lab10.csv\", 0.75) # Split data by 3:1 ration\n\npca = PCA(n_components=2)\nx_train = pca.fit_transform(s_data[0])\nx_test = pca.transform(s_data[2])\n\nneigh = KNeighborsClassifier(n_neighbors=5)\nneigh.fit(x_train, s_data[1])\ny_pred = neigh.predict(x_test)\n\nerr_predictions = 0\n\nfor i in range(len(s_data[3])):\n if s_data[3].values[i] != y_pred[i]:\n err_predictions += 1\n\nprint(\n \"Percentage of misclassifications for features = 2:\\t\"\n + str(100 * err_predictions / len(y_pred))\n)\n\nlab10.plot_decision_regions(x_train, s_data[1], neigh)\n\npca_none = PCA(n_components=None)\npca_none.fit(s_data[0])\neigen = pca_none.explained_variance_ratio_\nscree_plot(eigen)\n\n# From the plot the elbow appears to be at principle component = 7\n\npca_min = PCA(n_components=7)\nx_train_min = pca_min.fit_transform(s_data[0])\nx_test_min = pca_min.transform(s_data[2])\n\nneigh_min = KNeighborsClassifier(n_neighbors=5)\nneigh_min.fit(x_train_min, s_data[1])\ny_pred_min = neigh_min.predict(x_test_min)\n\nerr_predictions_min = 0\n\nfor i in range(len(s_data[3])):\n if s_data[3].values[i] != y_pred_min[i]:\n err_predictions_min += 1\n\nprint(\n \"Percentage of misclassifications for features = 7:\\t\"\n + str(100 * err_predictions_min / len(y_pred_min))\n)\n","sub_path":"Lab 10/PCA_lab10_Wasty_Jeffery.py","file_name":"PCA_lab10_Wasty_Jeffery.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"204101732","text":"'''\r\n Copyright (C) 2017, AT&T Inc. All rights reserved. Proprietary materials, property of AT&T. For internal use only,\r\n not for disclosure to parties outside of AT&T or its affiliates.\r\n'''\r\n\r\n'''\r\n This is the Entity Name Extraction Service.\r\n

\r\n This service will provide the list of entity names and entities for the given\r\n input text or input file. End User can configure the Library name, Language\r\n and type of entity classes\r\n

\r\n \r\n @author mn461x\r\n @since Jan 23, 2017\r\n @version $Id$\r\n'''\r\nfrom src.main.python.com.att.cmlp.common.nlp.extractentities.LibraryName import *\r\nfrom src.main.python.com.att.cmlp.common.nlp.extractentities.LanguageName import *\r\nfrom src.main.python.com.att.cmlp.common.nlp.extractentities.EntityExtractorException import *\r\nfrom src.main.python.com.att.cmlp.common.nlp.extractentities.EntityExtractorUsingNLTK import *\r\nfrom src.main.python.com.att.cmlp.common.nlp.extractentities.EntityExtractorUsingSpacy import *\r\n\r\nimport os\r\nclass EntityExtractor(object):\r\n \r\n ''' \r\n Constructor for the class EntityExtractor\r\n \r\n @param LibraryName: which library is going to extract for the entities\r\n @param LanguageName: Language for the input text\r\n '''\r\n def __init__(self, LibraryName, LanguageName):\r\n \r\n if LanguageName == None:\r\n raise EntityExtractorException(\"Language should not be null\")\r\n \r\n if LibraryName == None: \r\n raise EntityExtractorException(\"LibraryName should not be null\");\r\n\r\n self.LanguageName = LanguageName\r\n self.LibraryName = LibraryName\r\n\r\n ''' \r\n Method to extract the entities when the input is file\r\n \r\n @param FileDir: Filepath for the input text\r\n @param FileName: Input text file name\r\n '''\r\n \r\n def extractEntitiesFromFile(self, FilePath):\r\n \r\n if FilePath == None:\r\n raise EntityExtractorException(\"File path should not be null\")\r\n \r\n if len(FilePath) == 0:\r\n raise EntityExtractorException(\"File path should not be empty\")\r\n \r\n if FilePath.find('/') >= 0:\r\n inText = open(FilePath, 'r').read()\r\n else:\r\n inText = open(os.getcwd()+'\\\\__pycache__\\\\'+FilePath, 'r').read()\r\n\r\n if self.LibraryName == LibraryName.NLTKPython:\r\n entNLTK = EntityExtractorUsingNLTK(self.LanguageName)\r\n outputData = entNLTK.entityExtract(inText)\r\n elif self.LibraryName == LibraryName.spaCy:\r\n entSpacy = EntityExtractorUsingSpacy(self.LanguageName)\r\n outputData = entSpacy.entityExtract(inText)\r\n \r\n return outputData\r\n \r\n ''' \r\n Method to extract the entities when the input is file\r\n \r\n @param inputText: Input text for finding entities\r\n '''\r\n def extractEntitiesFromText(self, inputText):\r\n \r\n if inputText == None:\r\n raise EntityExtractorException(\"Input text should not be null\")\r\n \r\n if len(inputText) == 0:\r\n raise EntityExtractorException(\"Input text should not be empty\") \r\n \r\n if self.LibraryName == LibraryName.NLTKPython:\r\n entNLTK = EntityExtractorUsingNLTK(self.LanguageName)\r\n outputData = entNLTK.entityExtract(inputText)\r\n elif self.LibraryName == LibraryName.spaCy:\r\n entSpacy = EntityExtractorUsingSpacy(self.LanguageName)\r\n outputData = entSpacy.entityExtract(inputText)\r\n \r\n return outputData\r\n\r\n \"\"\"\r\n Method to extract supported list of entities from NLTK library\r\n \"\"\" \r\n def getEntities(self):\r\n if self.LibraryName == LibraryName.NLTKPython:\r\n entNLTK = EntityExtractorUsingNLTK(self.LanguageName)\r\n \r\n return entNLTK.getEntities()\r\n elif self.LibraryName == LibraryName.spaCy:\r\n entSpacy = EntityExtractorUsingSpacy(self.LanguageName)\r\n return entSpacy.getEntities()\r\n\r\nif __name__ == '__main__':\r\n \r\n inText = \"One year ago, several hours before cities across the United States started their annual fireworks displays, a different type of fireworks were set off at the European Center for Nuclear Research (CERN) in Switzerland. At 9:00 a.m., physicists announced to the world that they had found something they had been searching for nearly 50 years: the elusive Higgs boson. Today, on the anniversary of its discovery, are we any closer to figuring out what that particle's true identity is? The Higgs boson is popularly referred to as the God particle, perhaps because of its role in giving other particles their mass. However, it's not the boson itself that gives mass. Back in 1964, Peter Higgs proposed a theory that described a universal field (similar to an electric or a magnetic field) that particles interacted with.\"\r\n # NLTK method using input text\r\n entExtractor = EntityExtractor(LibraryName.NLTKPython, LanguageName.english) \r\n for ent in entExtractor.extractEntitiesFromText(inText):\r\n print (\"Entity Name :\" , ent.getEntityName(), \"Entity Type :\" ,ent.getEntityType())\r\n \r\n for ent in entExtractor.getEntities():\r\n print(ent)\r\n \r\n # spaCy method using input text\r\n entExtractor = EntityExtractor(LibraryName.spaCy, LanguageName.english)\r\n for ent in entExtractor.extractEntitiesFromText(inText):\r\n print (\"Entity Name :\" , ent.getEntityName(), \"Entity Type :\" ,ent.getEntityType())\r\n \r\n for ent in entExtractor.getEntities():\r\n print(ent)\r\n \r\n inText = \"Pierre Vinken , 61 years old , will join the board as a nonexecutive director Nov. 29 . Mr . Vinken is chairman of Elsevier N.V. , the Dutch publishing group .Rudolph Agnew , 55 years old and former chairman of Consolidated Gold Fields PLC , was named a director of this British industrial conglomerate.\"\r\n\r\n # spaCy method using input text\r\n entExtractor = EntityExtractor(LibraryName.spaCy, LanguageName.english) \r\n ents = entExtractor.extractEntitiesFromText(inText) \r\n for ent in ents:\r\n print (\"Entity Name :\" , ent.getEntityName() ,\"Entity Type :\" ,ent.getEntityType())\r\n \r\n for ent in entExtractor.getEntities():\r\n print(ent)\r\n","sub_path":"EntityExtractionUsingPython/src/main/python/com/att/cmlp/common/nlp/extractentities/EntityExtractor.py","file_name":"EntityExtractor.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"498643349","text":"import unittest\nimport mock\nimport os\nimport yaml\nfrom peon import Peon\n\nclass TestPeon(unittest.TestCase):\n\n @mock.patch('peon.os')\n def test_mocks(self, mock_os):\n Peon().rm(\"any path\")\n mock_os.remove.assert_called_with(\"any path\")\n\n def test_is_a_class(self):\n \tself.assertIsInstance(Peon(), Peon)\n\n def test_it_can_read_yaml_file(self):\n testYaml = 'examples/test.yaml'\n expected = yaml.load(open(testYaml, 'r'))\n result = Peon().readYaml(testYaml)\n self.assertEqual(result, expected)\n\n def test_it_can_generate_site(self):\n site = { 'map': 'test.app', 'to': '/var/www/test' }\n expected = open('examples/test.app', 'r').read()\n result = Peon().generateSite(site)\n self.assertEqual(result, expected)\n\n @mock.patch('peon.os')\n def test_it_can_write_a_file(self, mock_os):\n filePath = '.dump/test.app'\n contents = 'test contents'\n mock_file = 'file_stream'\n mock_os.open.return_value = mock_file\n mock_os.O_RDWR = os.O_RDWR\n mock_os.O_CREAT = os.O_CREAT\n result = Peon().writeFile(filePath, contents)\n mock_os.open.assert_called_with(filePath, os.O_RDWR|os.O_CREAT)\n mock_os.write.assert_called_with(mock_file, contents)\n\n @mock.patch('peon.subprocess')\n def test_it_can_restart_nginx(self, subprocess_mock):\n result = Peon().restartNginx()\n callArgs = [\"sudo\", \"systemctl\", \"restart\", \"nginx.service\"]\n subprocess_mock.check_output.assert_called_with(callArgs)\n\n\n\n\n","sub_path":"tests/test_peon.py","file_name":"test_peon.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"61481526","text":"import os\nimport re\n\n###############################\n#\n# Begin index file re-writing into temp directory\n# This function exists to read a (real) indexes.conf file from the filesystem and to change and/or add any lines that \n# we require into the indexes.conf file\n# We write that out to a new directory so that we can run differencing between existing and new file\n#\n###############################\ndef outputIndexFilesIntoTemp(logging, confFilesRequiringChanges, indexList, path, indexesRequiringChanges, replaceSlashes=True):\n #Create the required directory\n try:\n os.mkdir(path, 0o750)\n except OSError:\n #Debug level because this directory may already exist after previous runs\n logging.debug(\"Creation of the directory %s failed\" % path)\n\n #At this point we have a list of files requiring changes, a list of indexes with that file that require changing\n #we now read through the file and output an equivalent file in the working path that is the tuned version\n #we can (outside this script) diff the 2 files and / or implement the new file as required on the cluster master\n regex = re.compile(\"^\\s*([^= ]+)\")\n \n for aFile in confFilesRequiringChanges:\n with open(aFile) as file:\n #TODO find a nicer way to do this\n #there is no obvious way to determine the end of an index stanza entry or any stanza entry in the indexes.conf file, therefore we know\n #that we have finished the stanza entry when we have either reached a new entry or the end of the file\n #however that means we'd have [indexxxx]...\\n\\n\\n[nextindexyyy]...\n #to ensure we have [indexxxx]...\\n\\n[nextindexyyy]...the script prints 2 lines behind to the file...\n previousLine = False\n prevPreviousLine = False\n indexName = \"\"\n changesRequired = False\n maxDataSizeDone = False\n maxTotalDataSizeDone = False \n\n #name the output file based on the location on disk of the conf file\n #which means we replace / with _ symbols\n if replaceSlashes:\n outputFile = aFile[aFile.find(\"slave-apps\"):].replace(\"/\", \"_\")\n else:\n outputFile = aFile[aFile.find(\"slave-apps\")+11:]\n #output a new file in the working directory with our tuning modifications\n outputH = open(path + \"/\" + outputFile, \"w\")\n\n for line in file:\n if (prevPreviousLine):\n outputH.write(prevPreviousLine)\n\n #We found a stanza\n if (line.find(\"[\") == 0):\n #We don't need to do much with a volume stanza\n if (line.find(\"[volume:\") == -1):\n #We have moved onto a new index entry, but did we finish our previous job?\n #It's possible that maxTotalDataSizeMB was never specified in the stanza as it's optional\n #therefore we now write it out\n if (changesRequired != False):\n outputEdgeCase(logging, changesRequired, indexList, maxDataSizeDone, maxTotalDataSizeDone, outputH, indexName)\n \n #Some items are written into every index entry such as maxDataSize and maxTotalDataSize\n maxDataSizeDone = False\n maxTotalDataSizeDone = False\n \n end = line.find(\"]\") \n indexName = line[1:end]\n if (indexesRequiringChanges.has_key(indexName) and indexList[indexName].has_key(\"checked\")):\n changesRequired = indexesRequiringChanges[indexName].split(\"_\")\n logging.debug(\"index list info: %s\" % (indexList[indexName]))\n else:\n changesRequired = False\n else:\n changesRequired = False\n \n #We are somewhere after the [index...] stanza\n if (changesRequired != False):\n result = regex.match(line)\n stanza = result.group(1)\n \n #If we have changes and we come across the stanza that requires changes, write it out, potentially with a comment we created earlier\n if ((\"bucket\" in changesRequired) and stanza == \"maxDataSize\"):\n recBucketSize = indexList[indexName]['recBucketSize']\n comment = indexList[indexName]['changeComment']['bucket']\n #strip off the newline character from the line before adding to the log, otherwise the log has random newlines in it\n logging.debug(\"Old line %s, new line %s (newline) maxDataSize = %s\" % (line[:-1], comment[:-1], recBucketSize))\n #overwrite the old line with the new one\n line = \"%smaxDataSize = %s\\n\" % (comment, recBucketSize)\n maxDataSizeDone = True\n elif ((\"sizing\" in changesRequired) and stanza == \"maxTotalDataSizeMB\"):\n calcMaxTotalDataSizeMB = indexList[indexName]['calcMaxTotalDataSizeMB']\n comment = indexList[indexName]['changeComment']['sizing']\n #strip off the newline character from the line before adding to the log\n logging.debug(\"Old line %s, new line of %s (newline) maxTotalDataSizeMB = %s\" % (line[:-1], comment[:-1], calcMaxTotalDataSizeMB))\n line = \"%smaxTotalDataSizeMB = %s\\n\" % (comment, calcMaxTotalDataSizeMB)\n maxTotalDataSizeDone = True\n elif ((\"sizing\" in changesRequired) and stanza == \"homePath.maxDataSizeMB\"):\n homePathMaxDataSizeMB = indexList[indexName]['homePathMaxDataSizeMB']\n #strip off the newline character from the line before adding to the log\n logging.debug(\"Old line %s, new line homePath.maxDataSizeMB = %s\" % (line[:-1], homePathMaxDataSizeMB))\n line = \"homePath.maxDataSizeMB = %s\\n\" % (homePathMaxDataSizeMB)\n elif ((\"sizing\" in changesRequired) and stanza == \"coldPath.maxDataSizeMB\"):\n coldPathMaxDataSizeMB = indexList[indexName]['coldPathMaxDataSizeMB']\n #strip off the newline character from the line before adding to the log\n logging.debug(\"Old line %s, new line coldPath.maxDataSizeMB = %s\" % (line[:-1], coldPathMaxDataSizeMB)) \n line = \"coldPath.maxDataSizeMB = %s\\n\" % (coldPathMaxDataSizeMB)\n #record the previous, previous line if we have recorded a previous line already\n if (previousLine):\n prevPreviousLine = previousLine\n previousLine = line\n \n #This is an edge case but what if changes required and they were not done already\n #and we hit the end of the file?\n #Then we print out all the required information now\n if (changesRequired == False):\n pass\n else:\n outputEdgeCase(logging, changesRequired, indexList, maxDataSizeDone, maxTotalDataSizeDone, outputH, indexName)\n \n #print out the remaining lines\n outputH.write(prevPreviousLine)\n outputH.write(previousLine)\n\n#After we get to a new index entry we might have missed stanzas from the last index entry we were working on\n#add them to the output file now\ndef outputEdgeCase(logging, changesRequired, indexList, maxDataSizeDone, maxTotalDataSizeDone, outputH, indexName):\n if (\"bucket\" in changesRequired and not \"sizing\" in changesRequired and not maxDataSizeDone):\n recBucketSize = indexList[indexName]['recBucketSize']\n comment = indexList[indexName]['changeComment']['bucket']\n logging.debug(\"Never found this so writing it now %s (newline) maxDataSize = %s with a preceding comment of %s\" % (comment[:-1], recBucketSize))\n #Write the comment before the bucket sizing, so we record why this was changed\n outputH.write(comment)\n outputH.write(\"maxDataSize = %s\\n\" % (recBucketSize))\n elif (\"sizing\" in changesRequired and not \"bucket\" in changesRequired and not maxTotalDataSizeDone):\n calcMaxTotalDataSizeMB = indexList[indexName]['calcMaxTotalDataSizeMB']\n comment = indexList[indexName]['changeComment']['sizing']\n outputH.write(comment)\n logging.debug(\"Never found this so writing it now %s (newline) maxTotalDataSizeMB = %s\" % (comment[:-1], calcMaxTotalDataSizeMB))\n outputH.write(\"maxTotalDataSizeMB = %s\\n\" % (calcMaxTotalDataSizeMB))\n elif (\"bucket\" in changesRequired and \"sizing\" in changesRequired):\n recBucketSize = indexList[indexName]['recBucketSize']\n calcMaxTotalDataSizeMB = indexList[indexName]['calcMaxTotalDataSizeMB']\n \n #If we have not yet written the maxDataSize or maxTotalDataSize entries we write them together\n if (not maxDataSizeDone):\n comment = indexList[indexName]['changeComment']['bucket']\n logging.debug(\"Never found this so writing it now %s (newline) maxDataSize = %s\" % (comment[:-1], recBucketSize))\n outputH.write(comment)\n outputH.write(\"maxDataSize = %s\\n\" % (recBucketSize))\n if (not maxTotalDataSizeDone):\n comment = indexList[indexName]['changeComment']['sizing']\n logging.debug(\"Never found this so writing it now %s (newline) maxTotalDataSizeMB = %s\" % (comment[:-1], calcMaxTotalDataSizeMB))\n outputH.write(comment)\n outputH.write(\"maxTotalDataSizeMB = %s\\n\" % (calcMaxTotalDataSizeMB))\n #If we have a sizing comment to add and it was not added, do it now...\n if (changesRequired != False and \"sizingcomment\" in changesRequired):\n comment = indexList[indexName]['changeComment']['sizingcomment']\n outputH.write(comment)\n logging.debug(\"Wrote the sizing comment as %s\" % (comment[:-1]))\n","sub_path":"bin/indextuning_indextempoutput.py","file_name":"indextuning_indextempoutput.py","file_ext":"py","file_size_in_byte":10281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"212946121","text":"\"\"\"Filesystem store plugin.\"\"\"\n\n\nimport json\nimport os\n\n\nclass FileStore:\n \"\"\"A plugin to store records on the filesystem.\"\"\"\n\n def __init__(self, path='/tmp/cloudmarker'):\n \"\"\"Initialize object of this class with specified parameters.\n\n Arguments:\n path (str): Path of directory where files are written to.\n\n \"\"\"\n self._path = path\n self._record_types = set()\n os.makedirs(path, exist_ok=True)\n\n def write(self, record):\n \"\"\"Write JSON records to the file system.\n\n This method is called once for every record read from a cloud.\n In this example implementation of a store, we simply write the\n record in JSON format to a file. The list of records is\n maintained as JSON array in the file. The record type is used to\n determine the filename.\n\n The records are written to a .tmp file because we don't want to\n delete the existing complete and useful .json file prematurely.\n\n Note that other implementations of a store may choose to buffer\n the records in memory instead of writing each record to the\n store immediately. They may then flush the buffer to the store\n based on certain conditions such as buffer size, time interval,\n etc.\n\n Arguments:\n record (dict): Data to write to the file system.\n\n \"\"\"\n record_type = record['record_type']\n\n # If this is the first time we have encountered this\n # record_type, we create a new file for it and write an opening\n # bracket to start a JSON array.\n tmp_file_path = os.path.join(self._path, record_type) + '.tmp'\n if record_type not in self._record_types:\n with open(tmp_file_path, 'w') as f:\n f.write('[\\n')\n\n # Write the record dictionary as JSON object literal.\n self._record_types.add(record_type)\n with open(tmp_file_path, 'a') as f:\n f.write(json.dumps(record, indent=2) + ',\\n')\n\n def done(self):\n \"\"\"Perform final cleanup tasks.\n\n This method is called after all records have been written. In\n this example implementation, we properly terminate the JSON\n array in the .tmp file. Then we rename the .tmp file to .json\n file.\n\n Note that other implementations of a store may perform tasks\n like closing a connection to a remote store or flushing any\n remaining records in a buffer.\n\n \"\"\"\n for record_type in self._record_types:\n # End the JSON array by writing a closing bracket.\n tmp_file_path = os.path.join(self._path, record_type) + '.tmp'\n with open(tmp_file_path, 'a') as f:\n f.write(']\\n')\n\n # Rename the temporary file to a JSON file.\n json_file_path = os.path.join(self._path, record_type) + '.json'\n os.rename(tmp_file_path, json_file_path)\n","sub_path":"cloudmarker/stores/filestore.py","file_name":"filestore.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"484205126","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n***************************************************************************\n* *\n* This program 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 2 of the License, or *\n* (at your option) any later version. *\n* *\n***************************************************************************\n\"\"\"\n\nfrom qgis.PyQt.QtCore import QCoreApplication\nfrom qgis.core import (QgsProcessing,\n QgsProcessingException,\n QgsProcessingAlgorithm,\n QgsDataSourceUri,\n QgsProcessingParameterRasterDestination,\n QgsProcessingParameterEnum,\n QgsProcessingParameterRasterLayer)\nfrom qgis import processing\nfrom pcraster import *\n\n\nclass PCRasterBooleanOperatorsAlgorithm(QgsProcessingAlgorithm):\n \"\"\"\n This is an example algorithm that takes a vector layer and\n creates a new identical one.\n\n It is meant to be used as an example of how to create your own\n algorithms and explain methods and variables used to do it. An\n algorithm like this will be available in all elements, and there\n is not need for additional work.\n\n All Processing algorithms should extend the QgsProcessingAlgorithm\n class.\n \"\"\"\n\n # Constants used to refer to parameters and outputs. They will be\n # used when calling the algorithm from another algorithm, or when\n # calling from the QGIS console.\n\n INPUT_BOOLEAN1 = 'INPUT'\n INPUT_OPERATOR = 'INPUT1'\n INPUT_BOOLEAN2 = 'INPUT2'\n OUTPUT = 'OUTPUT'\n\n def tr(self, string):\n \"\"\"\n Returns a translatable string with the self.tr() function.\n \"\"\"\n return QCoreApplication.translate('Processing', string)\n\n def createInstance(self):\n return PCRasterBooleanOperatorsAlgorithm()\n\n def name(self):\n \"\"\"\n Returns the algorithm name, used for identifying the algorithm. This\n string should be fixed for the algorithm, and must not be localised.\n The name should be unique within each provider. Names should contain\n lowercase alphanumeric characters only and no spaces or other\n formatting characters.\n \"\"\"\n return 'booleanoperators'\n\n def displayName(self):\n \"\"\"\n Returns the translated algorithm name, which should be used for any\n user-visible display of the algorithm name.\n \"\"\"\n return self.tr('boolean operators')\n\n def group(self):\n \"\"\"\n Returns the name of the group this algorithm belongs to. This string\n should be localised.\n \"\"\"\n return self.tr('PCRaster')\n\n def groupId(self):\n \"\"\"\n Returns the unique ID of the group this algorithm belongs to. This\n string should be fixed for the algorithm, and must not be localised.\n The group id should be unique within each provider. Group id should\n contain lowercase alphanumeric characters only and no spaces or other\n formatting characters.\n \"\"\"\n return 'pcraster'\n\n def shortHelpString(self):\n \"\"\"\n Returns a localised short helper string for the algorithm. This string\n should provide a basic description about what the algorithm does and the\n parameters and outputs associated with it..\n \"\"\"\n return self.tr(\n \"\"\"Boolean operators\n \n
PCRaster documentation\n \n Parameters:\n \n * Input boolean raster layer (required) - boolean raster layer\n * Boolean operator (required) - AND, OR, XOR, NOT\n * Input boolean raster layer (required) - boolean raster layer\n * Output raster (required) - boolean raster layer\n \"\"\"\n )\n\n def initAlgorithm(self, config=None):\n \"\"\"\n Here we define the inputs and output of the algorithm, along\n with some other properties.\n \"\"\"\n\n self.addParameter(\n QgsProcessingParameterRasterLayer(\n self.INPUT_BOOLEAN1,\n self.tr('Input Boolean raster')\n )\n )\n \n self.unitoption = [self.tr('AND'),self.tr('NOT'),self.tr('OR'),self.tr('XOR')]\n self.addParameter(\n QgsProcessingParameterEnum(\n self.INPUT_OPERATOR,\n self.tr('Boolean operator'),\n self.unitoption,\n defaultValue=0\n )\n )\n\n self.addParameter(\n QgsProcessingParameterRasterLayer(\n self.INPUT_BOOLEAN2,\n self.tr('Input Boolean raster')\n )\n )\n\n \n self.addParameter(\n QgsProcessingParameterRasterDestination(\n self.OUTPUT,\n self.tr('Output Boolean raster')\n )\n )\n\n def processAlgorithm(self, parameters, context, feedback):\n \"\"\"\n Here is where the processing itself takes place.\n \"\"\"\n\n input_boolean1 = self.parameterAsRasterLayer(parameters, self.INPUT_BOOLEAN1, context)\n input_boolean2 = self.parameterAsRasterLayer(parameters, self.INPUT_BOOLEAN2, context)\n booleanoperator = self.parameterAsEnum(parameters, self.INPUT_OPERATOR, context)\n setclone(input_boolean1.dataProvider().dataSourceUri())\n Expression1 = readmap(input_boolean1.dataProvider().dataSourceUri())\n Expression2 = readmap(input_boolean2.dataProvider().dataSourceUri())\n if booleanoperator == 0:\n ResultBoolean = pcrand(Expression1,Expression2)\n elif booleanoperator == 1:\n ResultBoolean = pcrnot(Expression1,Expression2)\n elif booleanoperator == 2:\n ResultBoolean = pcror(Expression1,Expression2)\n else:\n ResultBoolean = pcrxor(Expression1,Expression2)\n\n outputFilePath = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)\n\n report(ResultBoolean,outputFilePath)\n\n results = {}\n results[self.OUTPUT] = outputFilePath\n \n return results\n","sub_path":"collections/qgis_pcrasterscripts/processing/pcraster_booleanoperators_algorithm.py","file_name":"pcraster_booleanoperators_algorithm.py","file_ext":"py","file_size_in_byte":6552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"324633647","text":"#!/usr/bin/python\n\nimport os\nimport random\nimport string\nimport time\nfrom hashlib import sha512\nfrom binascii import unhexlify\n\nimport nacl.signing\n\nimport feeds.feed as feed\n\nclass InFeed(feed.BaseFeed):\n\n def __init__(self, rename_infeed, kill_me, already_wait, logger, config, connection, debug, db_connector):\n feed.BaseFeed.__init__(self, kill_me, logger, debug, 'infeed-{}-{}'.format(*connection[1]))\n self.infeed_hooks = config.get('rules', None)\n self.config = config['config']\n self.already_wait = already_wait\n self.rename_infeed = rename_infeed\n self.socket = connection[0]\n self.polltimeout = -1\n self._db_connector = db_connector\n self._auth_data = None\n self.caps = [\n '101 i support to the following:',\n 'VERSION 2',\n 'IMPLEMENTATION artificial NNTP processing unit SRNd v0.1',\n 'READER',\n 'POST',\n 'IHAVE',\n 'LIST ACTIVE NEWSGROUPS OVERVIEW.FMT',\n 'STREAMING'\n ]\n # append caps\n if self.config['srndgzip']:\n self.caps.append('SRNDGZIP')\n if self.config['support']:\n self.caps.append('SUPPORT')\n if self.config['auth_required'] > 0:\n if 'nntp' in self.config['auth_support']:\n self.caps.append('AUTHINFO USER PASS')\n if 'srnd' in self.config['auth_support']:\n self.caps.append('SRNDAUTH')\n self.welcome = '200 welcome much to artificial NNTP processing unit some random NNTPd v0.1, posting allowed'\n self.current_group_id = -1\n self.current_group_name = None\n self.current_article_id = -1\n self.message_id_wait = ''\n # get flag srnd-infeed-access from db\n self._srnd_infeed_access = self._db_connector('censor', timeout=60).fetchone('SELECT flag FROM commands WHERE command=\"srnd-infeed-access\"')\n self._srnd_infeed_access = 0 if self._srnd_infeed_access is None else int(self._srnd_infeed_access[0])\n # list not sending headers in READER MODE.\n self._remove_headers = ('X-I2P-DESTHASH',)\n # switcher for reader mode\n self.READER_SEND = {\n 'HEAD': ('221', True, False, 'send_head'),\n 'BODY': ('222', False, True, 'send_body'),\n 'ARTICLE': ('220', True, True, 'send_article')\n }\n # OVERVIEW.FMT reply\n self._OVERVIEW_FMT = ['subject:', 'from:', 'date:', 'message-id:', 'references:', ':bytes', ':lines']\n\n def bump_qsize(self):\n self.qsize = len(self.articles_queue)\n\n def i_wait(self, message_id):\n return message_id in self.articles_queue\n\n def main_loop(self):\n self.log(self.logger.INFO, 'connection established')\n self.send(self.welcome)\n self.state = 'idle'\n poll = self._create_poll()\n self.sqlite_dropper = self._db_connector('dropper', timeout=60)\n while self.running and not self.con_broken:\n if poll(self.polltimeout):\n self._handle_received()\n self.bump_qsize()\n if not self.qsize:\n time.sleep(0.5)\n self.sqlite_dropper.close()\n if self.running:\n self.log(self.logger.INFO, 'client disconnected, terminating')\n else:\n self.log(self.logger.INFO, 'bye')\n\n def _get_infeed_name_by_key(self, key):\n _censordb = self._db_connector('censor', timeout=60)\n try:\n # return new name if srnd-infeed-access present, else None\n result = _censordb.fetchone('SELECT local_name FROM keys WHERE key = ? and (cast(flags as integer) & ?) = ?', (key, self._srnd_infeed_access, self._srnd_infeed_access))\n if result is None:\n return None\n # remove bad chars\n new_name = result[0].encode('ascii', 'ignore').replace(' ', '')\n if len(new_name) < 3 or new_name.startswith('1'):\n return key\n # name must have unique\n if int(_censordb.fetchone('SELECT count(local_name) FROM keys WHERE local_name = ?', (result[0],))[0]) == 1:\n return new_name\n else:\n return key\n finally:\n _censordb.close()\n\n def _infeed_SRNDAUTH(self, cmd_list):\n if len(cmd_list) < 2 or cmd_list[0] not in self._SRNDAUTH_REQU:\n # empty, bad or issued request\n self.send('482 Authentication commands issued. Allow only {}'.format(' or '.join(self._SRNDAUTH_REQU)), 'SRNDAUTH')\n elif cmd_list[0] == self._SRNDAUTH_REQU[0]:\n # SRNDAUTH PUBKEY KEY - first clien request. Generate and send secret, save pubkey and secret\n if self._auth_data is not None:\n # stop flood\n time.sleep(random.uniform(5, 15))\n # reset data and send new secret\n self._auth_data = dict()\n self._auth_data[self._SRNDAUTH_REQU[0]] = cmd_list[1].lower()\n self._auth_data['secret'] = ''.join(random.choice(string.ascii_uppercase+string.digits) for x in range(333))\n self.send('SRNDAUTH {}'.format(self._auth_data['secret']), 'SRNDAUTH')\n elif cmd_list[0] == self._SRNDAUTH_REQU[1]:\n # SRNDAUTH SIGNATURE signature - client send signature\n if self._auth_data is not None and self._SRNDAUTH_REQU[0] in self._auth_data:\n # save signature and check user data\n self._auth_data[self._SRNDAUTH_REQU[1]] = cmd_list[1].lower()\n self._infeed_SRNDAUTH_check()\n else:\n # user send signature and not send pubkey. WTF?\n self.send('482 send your pubkey before signature', 'SRNDAUTH')\n\n def _infeed_AUTHINFO(self, cmd_list):\n if len(cmd_list) < 2 or cmd_list[0] not in ('USER', 'PASS'):\n self.send('482 Authentication commands issued out of sequence')\n elif cmd_list[0] == 'USER':\n # ignore username, get private key\n self.send('381 send me your private key, kekeke')\n elif cmd_list[0] == 'PASS':\n pubkey = self._key_from_private(cmd_list[1])\n if pubkey is None:\n self.log(self.logger.WARNING, 'bad private key')\n # stop flood\n time.sleep(random.uniform(5, 15))\n self.send('481 Authentication failed/rejected')\n else:\n new_name = self._get_infeed_name_by_key(pubkey)\n if new_name is not None:\n self._srnd_auth = True\n self.send('281 {} access granted'.format(pubkey), 'AUTHINFO_ok')\n if self.config['pretty_name']:\n # rename infeed using pubkey or local_name\n self._set_infeed_pretty_name(new_name)\n self.log(self.logger.INFO, 'access granted for {}'.format(new_name))\n self._auth_data = {self._SRNDAUTH_REQU[0]: pubkey}\n else:\n self.log(self.logger.WARNING, '{} not allowed at this server'.format(pubkey))\n # stop flood\n time.sleep(random.uniform(5, 15))\n self.send('481 {} key not allowed at this server'.format(pubkey), 'AUTHINFO_reject')\n\n def _infeed_SRNDAUTH_check(self):\n new_name = None\n if self._check_sign(self._auth_data):\n new_name = self._get_infeed_name_by_key(self._auth_data[self._SRNDAUTH_REQU[0]])\n if new_name is not None:\n self._srnd_auth = True\n self.send('281 {} access granted'.format(self._auth_data[self._SRNDAUTH_REQU[0]]), 'SRNDAUTH_ok')\n else:\n self.send('481 {} key not allowed at this server'.format(self._auth_data[self._SRNDAUTH_REQU[0]]), 'SRNDAUTH_reject')\n self.log(self.logger.WARNING, '{} not allowed at this server'.format(self._auth_data[self._SRNDAUTH_REQU[0]]))\n else:\n self.send('482 bad key or signature', 'SRNDAUTH_error')\n self.log(self.logger.WARNING, 'bad key or signature, key=\"{}\" signature=\"{}\"'.format(self._auth_data[self._SRNDAUTH_REQU[0]], self._auth_data[[1]]))\n del self._auth_data['secret'], self._auth_data[self._SRNDAUTH_REQU[1]]\n if self._srnd_auth:\n if self.config['pretty_name']:\n # rename infeed using pubkey or local_name\n self._set_infeed_pretty_name(new_name)\n self.log(self.logger.INFO, 'access granted for {}'.format(new_name))\n else:\n del self._auth_data[self._SRNDAUTH_REQU[0]]\n\n def _set_infeed_pretty_name(self, to_name):\n new_name = 'infeed-' + to_name\n new_name_ = self.rename_infeed(self.name, new_name)\n if new_name_ is not None:\n self.name = new_name_\n else:\n self.log(self.logger.WARNING, 'Error rename to {}'.format(new_name))\n\n def _check_sign(self, data):\n try:\n nacl.signing.VerifyKey(unhexlify(data[self._SRNDAUTH_REQU[0]])).verify(sha512(data['secret']).digest(), unhexlify(data[self._SRNDAUTH_REQU[1]]))\n except Exception as e:\n self.log(self.logger.DEBUG, 'could not verify signature: {}'.format(e))\n return False\n else:\n return True\n\n def _allow_groups(self, newsgroups):\n if newsgroups == '' or self.infeed_hooks is None:\n return True\n groups = newsgroups.split(';') if ';' in newsgroups else newsgroups.split(',')\n for group in groups:\n if not self._isgroup_in_rules(group, self.infeed_hooks['whitelist']) or self._isgroup_in_rules(group, self.infeed_hooks['blacklist']):\n return False\n return True\n\n @staticmethod\n def _isgroup_in_rules(group, regexp_list):\n for regexp in regexp_list:\n if regexp == group or regexp == '*' or regexp[-1] == '*' and group.startswith(regexp[:-1]):\n return True\n return False\n\n def handle_multiline(self, handle_incoming):\n # TODO if variant != POST think about using message_id in handle_singleline for self.outfile = open(tmp/$message_id, 'w')\n # TODO also in handle_singleline: if os.path.exists(tmp/$message_id): retry later\n if self.waitfor == 'article':\n self.byte_transfer += handle_incoming.read_byte\n self.time_transfer += handle_incoming.transfer_time\n message_id_ = handle_incoming.message_id\n self._handle_article(handle_incoming)\n self.articles_queue.discard(message_id_)\n else:\n self.log(self.logger.INFO, 'should handle multi line while waiting for %s:' % self.waitfor)\n self.log(self.logger.INFO, ''.join(handle_incoming.header))\n self.log(self.logger.INFO, 'should handle multi line end')\n self.waitfor = ''\n self.variant = ''\n self.message_id_wait = ''\n\n def _handle_article(self, handle_incoming):\n # variant: (error, ok)\n variants = {\n 'IHAVE': ('437', '235'),\n 'TAKETHIS': ('439', '239'),\n 'POST': ('240', '240')\n }\n if self.variant not in variants:\n self.log(self.logger.ERROR, 'Unknown variant \"{}\". Interrupt processing article'.format(self.variant))\n return\n error = ''\n add_headers = list()\n\n # check for errors\n if not handle_incoming.body_found:\n error += 'no body found, '\n if handle_incoming.newsgroups == '':\n error += 'no newsgroups found, '\n if handle_incoming.message_id == '':\n if self.variant == 'POST':\n rnd = ''.join(random.choice(string.ascii_lowercase) for x in range(10))\n handle_incoming.message_id = '<{}{}@POSTED.{}>'.format(rnd, int(time.time()), self.config.get('instance_name', 'SRNd'))\n add_headers.append('Message-ID: {0}'.format(handle_incoming.message_id))\n elif self.valid_message_id(self.message_id_wait):\n handle_incoming.message_id = self.message_id_wait\n add_headers.append('Message-ID: {0}'.format(handle_incoming.message_id))\n else:\n error += 'no message-id in article, '\n elif not self.valid_message_id(handle_incoming.message_id):\n error += 'message-id invalid, '\n if error != '':\n self.send('{} {} invalid article: {}'.format(variants[self.variant][0], self.message_id_wait, error[:-2]))\n # save in articles/invalid for manual debug\n add_headers.append('X-SRNd-invalid: {0}'.format(error[:-2]))\n add_headers.append('X-SRNd-source: {0}'.format(self.name))\n add_headers.append('X-SRNd-variant: {0}'.format(self.variant))\n handle_incoming.move_to(os.path.join('articles', 'invalid', '{0}-{1}'.format(self.name, int(time.time()))), add_headers)\n self.log(self.logger.INFO, 'article invalid %s: %s' % (handle_incoming.message_id, error[:-2]))\n return\n self.log(self.logger.DEBUG, 'article received {}. Large: {}'.format(handle_incoming.message_id, handle_incoming.file_large))\n # save article in tmp and mv to incoming\n if os.path.exists(os.path.join('articles', handle_incoming.message_id)) or os.path.exists(os.path.join('incoming', handle_incoming.message_id)):\n self.send('{} {} i know this article already'.format(variants[self.variant][0], handle_incoming.message_id))\n self.log(self.logger.DEBUG, 'rejecting already known article %s' % handle_incoming.message_id)\n elif os.path.exists(os.path.join('articles', 'censored', handle_incoming.message_id)):\n self.send('{} {} article is blacklisted'.format(variants[self.variant][0], handle_incoming.message_id))\n self.log(self.logger.DEBUG, 'rejecting blacklisted article %s' % handle_incoming.message_id)\n elif not self._allow_groups(handle_incoming.newsgroups):\n self.send('{} {} article reject. group {} is blacklisted'.format(variants[self.variant][0], handle_incoming.message_id, handle_incoming.newsgroups))\n self.log(self.logger.DEBUG, 'rejecting article {}: group {} is blacklisted'.format(handle_incoming.message_id, handle_incoming.newsgroups))\n else:\n self.send('{} {} article received'.format(variants[self.variant][1], handle_incoming.message_id))\n handle_incoming.move_to(os.path.join('incoming', handle_incoming.message_id), add_headers)\n self.log(self.logger.INFO, 'article received and accepted %s' % handle_incoming.message_id)\n\n def handle_line(self, line):\n self.log(self.logger.VERBOSE, 'in: %s' % line)\n commands = line.upper().split(' ')\n if len(commands) == 0:\n self.log(self.logger.VERBOSE, 'should handle empty line')\n elif commands[0] == 'CAPABILITIES':\n # send CAPABILITIES. Work before authentication\n self.sendM(self.caps, 'CAPABILITIES')\n self.sendM(None, 'CAPABILITIES')\n elif commands[0] == 'SRNDGZIP':\n if self.config['srndgzip']:\n if self._srndgzip is None:\n self.send('952 ok go gzip')\n self._enable_gzip()\n self.log(self.logger.INFO, 'Enable compression')\n else:\n self.send('952 gzip already enabled.')\n else:\n self.send('954 gzip not supported')\n elif commands[0] == 'QUIT':\n self.send('205 bye bye')\n self.state = 'closing down'\n self.running = False\n elif commands[0] == 'SRNDAUTH' and self.config['auth_required'] > 0 and not self._srnd_auth and 'srnd' in self.config['auth_support']:\n # allow SRNDAUTH\n self._infeed_SRNDAUTH(commands[1:])\n elif commands[0] == 'AUTHINFO' and self.config['auth_required'] > 0 and not self._srnd_auth and 'nntp' in self.config['auth_support']:\n # allow AUTHINFO\n self._infeed_AUTHINFO(commands[1:])\n elif not self._srnd_auth and self.config['auth_required'] == 2:\n # not authenticated and authentication required\n self.send('480 Authentication required')\n elif commands[0] == 'SUPPORT':\n # 191 - initial SUPPORT reply\n self.send('191 i support:', 'SUPPORT')\n # send support options. Format ' '\n if self.config['support']:\n self.send(self.config['support'], 'SUPPORT')\n self.send('.', 'SUPPORT')\n elif commands[0] == 'MODE' and len(commands) == 2 and commands[1] == 'STREAM':\n self._handshake_state = True\n self.send('203 stream as you like')\n self._current_mode = self._MODE['stream']\n elif commands[0] == 'MODE' and commands[1] == 'READER':\n #200 Posting allowed\n #201 Posting prohibited\n #502 Reading service permanently unavailable\n #TODO: add self.reader_mode true/false and reader_mode switcher to config\n self.send('200 Posting allowed')\n self._current_mode = self._MODE['reader']\n self.log(self.logger.DEBUG, 'switch to MODE READER')\n elif commands[0] == 'CHECK' and len(commands) == 2:\n message_id = line.split(' ', 1)[1]\n if '/' in message_id:\n self.send('438 {0} illegal message-id'.format(message_id))\n elif os.path.exists(os.path.join('articles', message_id)) or os.path.exists(os.path.join('incoming', message_id)):\n self.send('438 {0} i know this article already'.format(message_id))\n elif os.path.exists(os.path.join('articles', 'censored', message_id)):\n self.send('438 {0} article is blacklisted'.format(message_id))\n elif self.already_wait(self.name, message_id):\n self.send('431 {0} try again later'.format(message_id))\n else:\n self.articles_queue.add(message_id)\n self.qsize = len(self.articles_queue)\n self.send('238 {0} go ahead, send to the article'.format(message_id))\n elif commands[0] == 'TAKETHIS' and len(commands) == 2:\n self.waitfor = 'article'\n self.variant = 'TAKETHIS'\n self.message_id_wait = line.split(' ', 1)[1]\n self.in_buffer.set_multiline()\n elif commands[0] == 'POST':\n self._handshake_state = True\n self.send('340 go ahead, send to the article')\n self.waitfor = 'article'\n self.variant = 'POST'\n self.in_buffer.set_multiline()\n # remove UA from POST\n self.incoming_file.remove_headers(headers=['user-agent',])\n self._current_mode = self._MODE['post']\n elif commands[0] == 'IHAVE':\n self._handshake_state = True\n arg = line.split(' ', 1)[1]\n if '/' in arg:\n self.send('435 illegal message-id')\n elif os.path.exists(os.path.join('articles', arg)) or os.path.exists(os.path.join('incoming', arg)):\n self.send('435 already have this article')\n elif os.path.exists(os.path.join('articles', 'censored', arg)):\n self.send('435 article is blacklisted')\n elif self.already_wait(self.name, arg):\n self.send('436 {0} try again later'.format(arg))\n else:\n self.articles_queue.add(arg)\n self.send('335 go ahead, send to the {}'.format(arg))\n self.waitfor = 'article'\n self.variant = 'IHAVE'\n self.message_id_wait = arg\n self.in_buffer.set_multiline()\n self._current_mode = self._MODE['ihave']\n elif commands[0] == 'STAT':\n message_uid, message_id = self._article_check(line.split(' ')[1:])\n if message_uid:\n self.send('223 {} {}'.format(message_id, message_uid))\n elif commands[0] == 'LIST':\n self._response_LIST(commands[1:])\n elif commands[0] == 'XOVER':\n min_id, max_id = self._check_id_range(commands[1:])\n if min_id:\n all_articles = self._get_article_range(min_id, max_id)\n if all_articles:\n self._send_header_XOVER(all_articles)\n else:\n self.send('423 No articles in that range')\n elif commands[0] == 'NEWGROUPS':\n # not implemented yet, return all groups\n self._response_LIST_ACTIVE([])\n elif commands[0] == 'GROUP':\n if len(commands) != 2:\n self.send('501 Syntax Error')\n else:\n group_data = self.sqlite_dropper.fetchone('SELECT article_count, lowest_id, highest_id, group_name, group_id FROM groups WHERE group_name = ?', (line.split(' ')[1],))\n if not group_data:\n self.send('411 {} is unknown'.format(line.split(' ')[1]))\n else:\n self.send('211 {}'.format(' '.join(str(xx) for xx in group_data[:-1])))\n self.current_article_id = group_data[1]\n self.current_group_id = group_data[4]\n self.current_group_name = line.split(' ')[1]\n elif commands[0] in self.READER_SEND:\n # BODY, HEAD or ARTICLE\n message_uid, message_id = self._article_check(line.split(' ')[1:])\n if message_uid:\n self._send_article_READER(message_uid, message_id, commands[0])\n else:\n self.send('500 {} unknown, I much recommend in speak to the proper NNTP based on CAPABILITIES'.format(commands[0]))\n\n def _article_check(self, cmd):\n \"\"\" Check BODY, HEAD or ARTICLE command. return 2 strings contains name and id. If name is None - do nothing\"\"\"\n message_id = None\n message_uid = None\n if self.current_group_id == -1:\n self.send('412 No newsgroup selected')\n elif not cmd and self.current_article_id == -1:\n self.send('420 Current article number is invalid')\n elif not cmd or cmd[0].isdigit():\n # current article number used else article number specified\n message_id = self.current_article_id if not cmd else cmd[0]\n message_uid = self.sqlite_dropper.execute('SELECT message_id FROM articles WHERE group_id = ? AND article_id = ?', (self.current_group_id, message_id)).fetchone()\n if message_uid is None:\n self.send('423 No article with that {}'.format(message_id))\n else:\n message_uid = message_uid[0]\n else:\n # message-id specified\n message_uid = os.path.basename(cmd[0])\n message_id = 0\n if message_uid is not None and not os.path.isfile(os.path.join('articles', message_uid)):\n if message_id == 0:\n self.send('430 No article with that {}'.format(message_uid))\n else:\n self.send('423 No article with that {}'.format(message_id))\n message_uid = None\n return message_uid, message_id\n\n def _check_id_range(self, cmd):\n \"\"\"Return min, max id from XOVER. If min_id is None - do nothing\"\"\"\n min_id, max_id = None, None\n if self.current_group_id == -1:\n self.send('412 No newsgroup selected')\n elif not cmd and self.current_article_id == -1:\n self.send('420 No article(s) selected')\n elif not cmd:\n # current article number used\n min_id, max_id = self.current_article_id, self.current_article_id\n elif cmd[0].isdigit():\n # article number\n min_id, max_id = cmd[0], cmd[0]\n else:\n # article number range\n min_id, _, max_id = cmd[0].partition('-')\n if not min_id.isdigit() or (max_id and not max_id.isdigit()):\n self.send('423 invalid id')\n min_id = None\n if min_id is None:\n pass\n elif not max_id:\n # XOVER X-. Set +1000\n max_id = int(min_id) + 1000\n elif int(max_id) - int(min_id) > 1000:\n # very large range\n self.send('502 very large article_id range')\n min_id = None\n return min_id, max_id\n\n def _get_article_range(self, min_id, max_id):\n \"\"\"return list *(article_id, message_id)\"\"\"\n all_data = list()\n for data in self.sqlite_dropper.fetchall('SELECT article_id, message_id FROM articles WHERE group_id = ? AND article_id >= ? AND article_id <= ?', (self.current_group_id, min_id, max_id)):\n if os.path.isfile(os.path.join('articles', data[1])):\n all_data.append(data)\n return all_data\n\n def _send_header_XOVER(self, all_data):\n self.send('224 Overview information follows')\n start_time = time.time()\n sending = 0\n for article_id, message_uid in all_data:\n article_path = os.path.join('articles', message_uid)\n data = [''] * (len(self._OVERVIEW_FMT) + 1)\n data[0] = str(article_id)\n data[6] = str(os.path.getsize(article_path))\n with open(article_path, 'rb') as fd:\n for line in self._read_article(fd, True, False):\n head, _, value = line.partition(' ')\n head = head.lower()\n if head in self._OVERVIEW_FMT:\n data[self._OVERVIEW_FMT.index(head) + 1] = value\n a, _ = self.sendM('\\t'.join(data), 'XOVER')\n sending += a\n if self.con_broken:\n break\n if not self.con_broken:\n a, _ = self.sendM(None, 'XOVER')\n self.byte_transfer += sending + a\n self.time_transfer += time.time() - start_time\n\n def _send_article_READER(self, message_uid, message_id, mode):\n \"\"\"Send body, head or full article in MODE READER. mode in ('HEAD', 'BODY', 'ARTICLE')\"\"\"\n # don't check header if send body\n head_complit = True if mode == 'BODY' else False\n mode = self.READER_SEND[mode]\n\n self.log(self.logger.DEBUG, '{} {}'.format(mode[3], message_uid))\n start_time = time.time()\n sending = 0\n self.sendM('{} {} {}'.format(mode[0], message_id, message_uid))\n with open(os.path.join('articles', message_uid), 'rb') as fd:\n for to_send in self._read_article(fd, mode[1], mode[2]):\n if not head_complit:\n if to_send == '':\n head_complit = True\n elif to_send.split(': ')[0].upper() in self._remove_headers:\n continue\n a, _ = self.sendM(to_send, mode[3])\n sending += a\n if self.con_broken:\n break\n if not self.con_broken:\n a, _ = self.sendM(None, mode[3])\n self.byte_transfer += sending + a\n self.time_transfer += time.time() - start_time\n\n def _response_LIST(self, commands):\n if not commands or commands[0] == 'ACTIVE':\n self._response_LIST_ACTIVE(commands[1:])\n elif commands[0] == 'NEWSGROUPS':\n self.sendM('215 information follows')\n for line in self.sqlite_dropper.fetchall('SELECT group_name FROM groups'):\n self.sendM(line[0])\n self.sendM()\n elif commands[0] == 'OVERVIEW.FMT':\n self.sendM('215 Order of fields in overview database:')\n self.sendM(self._OVERVIEW_FMT)\n self.sendM()\n else:\n self.send('503 program error, {} not performed'.format(commands[0]))\n\n def _response_LIST_ACTIVE(self, commands):\n if commands:\n self.send('501 Syntax Error')\n else:\n self.sendM('215 list of newsgroups follows')\n for line in self.sqlite_dropper.fetchall('SELECT group_name, highest_id, lowest_id, flag FROM groups'):\n self.sendM(' '.join(str(xx) for xx in line))\n self.sendM()\n","sub_path":"feeds/infeed.py","file_name":"infeed.py","file_ext":"py","file_size_in_byte":25213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"631791853","text":"import textwrap\n\nimport more_itertools\nimport pytest\n\nfrom .. import blacken\nfrom ..formats import rst\nfrom .data import rst as data\n\n\n@pytest.mark.parametrize(\n \"lines,expected\",\n (\n pytest.param(data.lines[0], None, id=\"none\"),\n pytest.param(data.lines[2:5], None, id=\"no_code\"),\n pytest.param(data.lines[67:70], None, id=\"code_other_language\"),\n pytest.param(\n data.lines[8:15],\n ((1, 8), rst.name, \"\\n\".join(data.lines[8:15])),\n id=\"code\",\n ),\n pytest.param(\n data.lines[17:24],\n ((1, 8), rst.name, \"\\n\".join(data.lines[17:24])),\n id=\"code-block\",\n ),\n pytest.param(\n data.lines[27:34],\n ((1, 8), rst.name, \"\\n\".join(data.lines[27:34])),\n id=\"ipython\",\n ),\n pytest.param(data.lines[38:47], None, id=\"ipython-prompt\"),\n pytest.param(data.lines[52:64], None, id=\"ipython-prompt-cell-decorator\"),\n pytest.param(\n data.lines[73:79],\n ((1, 7), rst.name, \"\\n\".join(data.lines[73:79])),\n id=\"testsetup\",\n ),\n pytest.param(\n data.lines[80:83],\n ((1, 4), rst.name, \"\\n\".join(data.lines[80:83])),\n id=\"testcode\",\n ),\n pytest.param(\n data.lines[84:87],\n ((1, 4), rst.name, \"\\n\".join(data.lines[84:87])),\n id=\"testcleanup\",\n ),\n pytest.param(\n [\".. ipython:: python\", ' print(\"abc\")'],\n (\n (1, 3),\n rst.name,\n textwrap.dedent(\n \"\"\"\\\n .. ipython:: python\n print(\"abc\")\n \"\"\"\n ).rstrip(),\n ),\n id=\"missing option separator\",\n ),\n ),\n)\ndef test_detection_func(lines, expected):\n lines = tuple(more_itertools.always_iterable(lines))\n lines_ = more_itertools.peekable(enumerate(lines, start=1))\n\n actual = rst.detection_func(lines_)\n\n leftover_lines = tuple(lines_)\n\n assert actual == expected\n assert expected is not None or len(lines) == len(leftover_lines)\n\n\n@pytest.mark.parametrize(\n \"code,expected\",\n (\n pytest.param(\n textwrap.dedent(\"\\n\".join(data.lines[8:15])),\n (\n {\n \"name\": \"code\",\n \"language\": \"python\",\n \"options\": (\":okwarning:\",),\n \"prompt_length\": 3,\n \"n_header_lines\": 3,\n },\n textwrap.dedent(\"\\n\".join(data.lines[11:15])),\n ),\n id=\"code\",\n ),\n pytest.param(\n textwrap.dedent(\"\\n\".join(data.lines[17:24])),\n (\n {\n \"name\": \"code-block\",\n \"language\": \"python\",\n \"options\": (),\n \"prompt_length\": 4,\n \"n_header_lines\": 2,\n },\n textwrap.dedent(\"\\n\".join(data.lines[19:24])),\n ),\n id=\"code_block\",\n ),\n pytest.param(\n textwrap.dedent(\"\\n\".join(data.lines[27:34])),\n (\n {\n \"name\": \"ipython\",\n \"language\": None,\n \"options\": (),\n \"prompt_length\": 4,\n \"n_header_lines\": 2,\n },\n rst.hide_magic(textwrap.dedent(\"\\n\".join(data.lines[29:34]))),\n ),\n id=\"ipython\",\n ),\n pytest.param(\n textwrap.dedent(\n \"\"\"\\\n .. ipython:: python\n print(\"abc\")\n \"\"\"\n ).rstrip(),\n (\n {\n \"name\": \"ipython\",\n \"language\": \"python\",\n \"options\": (),\n \"prompt_length\": 4,\n \"n_header_lines\": 2,\n },\n 'print(\"abc\")',\n ),\n id=\"missing sep and eof line\",\n ),\n pytest.param(\n textwrap.dedent(\n \"\"\"\\\n .. ipython:: python\n print(\"abc\")\n \"\"\"\n ),\n (\n {\n \"name\": \"ipython\",\n \"language\": \"python\",\n \"options\": (),\n \"prompt_length\": 4,\n \"n_header_lines\": 2,\n },\n \"\\n\".join(['print(\"abc\")', \"\"]),\n ),\n id=\"missing sep line\",\n ),\n ),\n)\ndef test_extraction_func(code, expected):\n actual = rst.extraction_func(code)\n\n assert expected == actual\n\n\n@pytest.mark.parametrize(\n \"code,directive,expected\",\n (\n pytest.param(\n textwrap.dedent(\"\\n\".join(data.lines[11:15])),\n {\n \"name\": \"code\",\n \"language\": \"python\",\n \"options\": (\":okwarning:\",),\n \"prompt_length\": 3,\n },\n textwrap.dedent(\"\\n\".join(data.lines[8:15])),\n id=\"code\",\n ),\n pytest.param(\n textwrap.dedent(\"\\n\".join(data.lines[19:24])),\n {\n \"name\": \"code-block\",\n \"language\": \"python\",\n \"options\": (),\n \"prompt_length\": 4,\n },\n textwrap.dedent(\"\\n\".join(data.lines[17:24])),\n id=\"code_block\",\n ),\n pytest.param(\n textwrap.dedent(\"\\n\".join(data.lines[29:34])),\n {\"name\": \"ipython\", \"language\": None, \"options\": (), \"prompt_length\": 4},\n textwrap.dedent(\"\\n\".join(data.lines[27:34])),\n id=\"ipython\",\n ),\n ),\n)\ndef test_reformatting_func(code, directive, expected):\n actual = rst.reformatting_func(code, **directive)\n\n assert expected == actual\n\n\ndef test_blacken():\n labeled = tuple(\n ((min_ + 1, max_ + 1), label, \"\\n\".join(data.lines[slice(min_, max_)]))\n for label, (min_, max_) in zip(data.line_labels, data.line_ranges)\n )\n actual = tuple(blacken(labeled))\n\n assert len(\"\\n\".join(actual).split(\"\\n\")) == 76\n","sub_path":"blackdoc/tests/test_rst.py","file_name":"test_rst.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"114567767","text":"\n\"\"\"\nEqualAreaPolygon.py: Splits a polygon into equal north south areas.\n\nThis script is for an ArcMap Python Toolbox that splits a polygon into two north south equal areas. All features in the\nfeature class are merged into one feature before processing. The tool honors selections and will export only the\nselected layers before merging the selected layers and processing.\n\"\"\"\n\n__author__ = \"Mark Buie | GIS Coordinator | City of Mesquite\"\n__credits__ = [\"Lynne Buie | City of Plano\"]\n__maintainer__ = \"Mark Buie\"\n__email__ = \"mbuie@cityofmesquite.com\"\n__status__ = \"Production\"\n\n\nimport arcpy\nimport os\n\n########################################################################################################################\n#\n# TOOL PARAMETERS\n#\n########################################################################################################################\n\n# in_fc: POLYGON the input polygon layer from the ArcMap tool\n# tolerance: DOUBLE the tool first splits the polygon in the middle of the extent. The tolerance is calculated as the\n# polygon with the smallest area / by the polygon with the greatest area. The tool runs until this metric is above the\n# the user defined tolerance.\n# save_location: POLYGON the location for the resulting split polygon\n\nin_fc = arcpy.GetParameterAsText(0)\ntolerance = float(arcpy.GetParameterAsText(1))\nsave_location = arcpy.GetParameterAsText(2)\n\n\n########################################################################################################################\n#\n# FUNCTIONS\n#\n########################################################################################################################\n\n\ndef getExtent(in_feature):\n \"\"\"\n Return the extent of a feature class\n\n :param in_feature: FEATURE CLASS the feature class to calculate the extent\n :return: the value of the top, bottom, left, and right extent\n \"\"\"\n describe = arcpy.Describe(in_feature)\n X_max = describe.extent.XMax\n X_min = describe.extent.XMin\n Y_max = describe.extent.YMax\n Y_min = describe.extent.YMin\n return X_max, X_min, Y_max, Y_min\n\n\ndef bisectExtent(line_fc, X_max, X_min, Y_max, Y_min, start_x, start_y, end_x, end_y):\n \"\"\"\n Return the middle extent of a feature class.\n\n Populates a feature class with polylines representing the extent of a feature class with a bisecting line.\n\n :param line_fc: POLYLINE The feature class to populate.\n :param X_max: DOUBLE The right extent of a feature class.\n :param X_min: DOUBLE The left extent of a feature class.\n :param Y_max: DOUBLE The top extent of a feature class.\n :param Y_min: DOUBLE The bottom extent of a feature class.\n :param start_x: DOUBLE X coordinate for start of bisecting line.\n :param start_y: DOUBLE Y coordinate for start of bisecting line.\n :param end_x: DOUBLE X coordinate for end of bisecting line.\n :param end_y: DOUBLE Y coordinate for end of bisecting line.\n :return: VOID\n \"\"\"\n coordlist = [[1, X_max, Y_max],\n [1, X_min, Y_max],\n [1, X_min, Y_max],\n [1, X_min, Y_min],\n [1, X_min, Y_min],\n [1, X_max, Y_min],\n [1, X_max, Y_min],\n [1, X_max, Y_max],\n [2, start_x, start_y],\n [2, end_x, end_y ]]\n\n cursor = arcpy.da.InsertCursor(line_fc, [\"SHAPE@\"])\n\n array = arcpy.Array()\n\n ID = -1\n for coord in coordlist:\n if ID == -1:\n ID = coord[0]\n\n if ID != coord[0]:\n cursor.insertRow([arcpy.Polyline(array)])\n array.removeAll()\n array.add(arcpy.Point(coord[1], coord[2]))\n ID = coord[0]\n\n cursor.insertRow([arcpy.Polyline(array)])\n\n\ndef getArea(in_fc):\n \"\"\"\n Returns the total area of a all features in a feature class.\n\n :param in_fc: POLYGON The input feature class\n :return: DOUBLE The total area.\n \"\"\"\n cursor = arcpy.da.SearchCursor(in_fc, [\"SHAPE@AREA\"])\n area = 0.0\n for row in cursor:\n area += row[0]\n return area\n\n\ndef checkEquality(in_fc):\n \"\"\"\n Check which of two north south polygons have the greatest area.\n\n Calculates which of two polygons, that are stacked north and south, have the greatest area and determines which way\n the bisecting line should be moved to make them equal\n\n :param in_fc: POLYGON input polygon feature class with two features stacked on top of each other.\n :return: ratio DOUBLE the polygon with smallest area divided by the polygon with greatest area.\n :return: direction TEXT the direction the bisecting line should be moved to make the polygons equal.\n :return: high_area DOUBLE the value of the polygon with the greatest area\n :return: low_area DOUBLE the value of the polygon with the lowest area\n \"\"\"\n\n attributes = []\n cursor = arcpy.da.SearchCursor(in_fc, [\"SHAPE@AREA\", \"SHAPE@XY\"])\n for row in cursor:\n attributes.append([row[0], row[1]])\n\n attributes.sort(reverse=True)\n\n high_area = attributes[0][0]\n low_area = attributes[1][0]\n\n ratio = low_area / high_area\n\n high_area_y = attributes[0][1][1]\n low_area_y = attributes[1][1][1]\n\n if high_area_y > low_area_y:\n return ratio, \"up\", high_area, low_area\n elif high_area_y == low_area_y:\n return ratio, \"equal\", high_area, low_area\n else:\n return ratio, \"down\", high_area, low_area\n\n\n########################################################################################################################\n#\n# ENVIRONMENT SETTINGS\n#\n########################################################################################################################\n\n\n# Set workspace to in_memory. Uses computer RAM for increased performance, but may cause issues with larger datasets.\narcpy.env.workspace = 'in_memory'\n\n\n########################################################################################################################\n#\n# VARIALBES\n#\n########################################################################################################################\n\n# in_fc_copy: POLYGON The path to a copy of the user input feature class to be split\n# in_fc_copy_diss: POLYGON The path to the dissolve of in_fc_copy\n# in_fc_spatialref: SPATIAL REFERENCE The spatial reference of the input feature class. Needed for the create feature\n# class parameter when creating feature class for polyline.\n# line_fc_path: STRING The path for the polyline feature class.\n# line_fc_filename: STRING The filename for the polyline feature class.\n# line_fc: STRING The full path name for the polyline feature class.\n# ftop_fc: POLYGON Path for output of feature to polygon geoprocessing tool.\n# clip_fc: POLYGON Path for output of clip geoprocessing tool.\n# ratio: DOUBLE The starting ratio\n# tolerance_divider: INT the number to divide the tolerance by after each change of direction.\n\nin_fc_copy = r\"in_memory\\copy\"\nin_fc_copy_diss = r'in_memory\\copy_diss'\nin_fc_spatialref = arcpy.Describe(in_fc).spatialReference\nline_fc_path = r\"in_memory\"\nline_fc_filename = \"split_line\"\nline_fc = os.path.join(line_fc_path, line_fc_filename)\nftop_fc = r\"in_memory\\feature_to_polygon\"\nclip_fc = r\"in_memory\\clip\"\nratio = 0.0\ntolerance_divider = 10\n\n\n########################################################################################################################\n#\n# SCRIPT\n#\n########################################################################################################################\n\n# Make a copy of the input feature class so we don't mess it up. This also extracts and isolates any user selected\n# features.\narcpy.CopyFeatures_management(in_fc, in_fc_copy)\n\n# Dissolve all features into one feature.\narcpy.Dissolve_management(in_fc_copy, in_fc_copy_diss)\n\n# Calculate the total area of features in the feature class.\ntotal_area = getArea(in_fc_copy_diss)\n\n# Get the extent of the feature class.\nx_max, x_min, y_max, y_min = getExtent(in_fc_copy_diss)\n\n# calculate the coordinates of the bisecting line.\nstart_x = x_max\nstart_y = (y_max - y_min) / 2 + y_min\nend_y = (y_max - y_min) / 2 + y_min\nend_x = x_min\nincrement = ((y_max - y_min) / 2) / tolerance_divider\n\n# While the ratio is less than the tolerance, move the bisecting line towards the polygon with the greatest area.\nstarted = False\nmoving = \"nowhere\"\nwhile ratio <= tolerance:\n\n # Make the polyline feature class that will have the bisecting line.\n arcpy.CreateFeatureclass_management(line_fc_path, line_fc_filename, \"POLYLINE\", None, None, None, in_fc_spatialref)\n\n # Insert lines into the line_fc that represent the perimeter of the extent with a bisecting line through the middle.\n bisectExtent(line_fc, x_max, x_min, y_max, y_min, start_x, start_y, end_x, end_y)\n\n # Convert the lines to polygons\n arcpy.FeatureToPolygon_management(line_fc, ftop_fc)\n\n # Clip the polygons with the original feature class\n arcpy.Clip_analysis(ftop_fc, in_fc_copy_diss, clip_fc)\n\n # Find the ratio of area between the two polygons and the direction we need to move the bisecting line to make them\n # equal.\n ratio, direction, high, low = checkEquality(clip_fc)\n\n arcpy.AddMessage(\"The area ratio is {0}, adjusting bisect line {1}\".format(ratio, direction))\n\n # Each time the line changes direction reduce the amount the line is incremented by. The precision of feature class\n # extents is 9. If the increment value drops below this the tool will get hung. Therefore, we add clause that breaks\n # the loop if the precision drops below 9.\n if started:\n if moving != direction:\n increment = increment / 10\n if 0.00000001 > increment > 0.000000001:\n increment = 0.000000001\n elif increment < 0.000000001:\n break\n arcpy.AddMessage(\"Reducing line increment to {0}\".format(increment))\n\n if direction == \"up\":\n start_y += increment\n end_y += increment\n else:\n start_y -= increment\n end_y -= increment\n\n moving = direction\n\n started = True\n\narcpy.CopyFeatures_management(clip_fc, save_location)\n\n\n########################################################################################################################\n#\n# DONE\n# Mark Buie\n# City of Mesquite, Texas\n#\n########################################################################################################################\n","sub_path":"Editing/EqualAreaPolygon.py","file_name":"EqualAreaPolygon.py","file_ext":"py","file_size_in_byte":10816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"299850659","text":"#Potentiometer board v1.0p test code\n\nfrom machine import Pin\nfrom pyb import CAN, ADC\nimport utime\n\nprint(\"initializing\")\ncan = CAN(1, CAN.NORMAL)\ncan.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126))\n\n\n#Setup Pins\nhbt_led = Pin(\"D5\", Pin.OUT)\nfunc_butt = Pin(\"E7\", Pin.IN, Pin.PULL_UP) \ncan_wakeup = Pin(\"D6\", Pin.OUT)\ncan_wakeup.value(0)\n\na_button = Pin(\"E13\", Pin.IN, Pin.PULL_UP) \nb_button = Pin(\"E12\", Pin.IN, Pin.PULL_UP) \na_pot = ADC(\"A1\")\nb_pot = ADC(\"A0\")\n\ncolumn_a = Pin(\"E4\", Pin.OUT, Pin.PULL_DOWN) \ncolumn_b = Pin(\"E3\", Pin.OUT, Pin.PULL_DOWN) \ncolumn_a.value(1) #When the column is HIGH the column is OFF, write them to OFF on initialization\ncolumn_b.value(1)\n\nrow_0 = Pin(\"D0\", Pin.OUT) \nrow_1 = Pin(\"D1\", Pin.OUT) \nrow_2 = Pin(\"E2\", Pin.OUT) \nrow_3 = Pin(\"E1\", Pin.OUT) \nrow_4 = Pin(\"A5\", Pin.OUT) \nrow_5 = Pin(\"A4\", Pin.OUT) \nrow_6 = Pin(\"A3\", Pin.OUT) \nrow_7 = Pin(\"A2\", Pin.OUT) \n\nrow = [row_0,row_1,row_2,row_3,row_4,row_5,row_6,row_7]\n\n\n#Setup hbt timer\nhbt_state = 0\nhbt_interval = 500\nstart = utime.ticks_ms()\nnext_hbt = utime.ticks_add(start, hbt_interval)\nhbt_led.value(hbt_state)\n\nprint(\"starting pot test\")\nprint(\"v1.0\")\n\ndef chk_hbt():\n global next_hbt\n global hbt_state\n now = utime.ticks_ms()\n if utime.ticks_diff(next_hbt, now) <= 0:\n if hbt_state == 1:\n hbt_state = 0\n hbt_led.value(hbt_state)\n #print(\"hbt\")\n else:\n hbt_state = 1\n hbt_led.value(hbt_state) \n \n next_hbt = utime.ticks_add(next_hbt, hbt_interval)\n\ndef chk_buttons():\n global next_button_chk\n now = utime_ms()\n if utime.ticks_diff(next_button_chk, now) <= 0:\n pass\n \n\ndef send():\n can.send('EVZRTST', 123) # send a message with id 123\n \ndef get():\n mess = can.recv(0)\n print(mess)\n light_sweep('a')\n light_sweep('b')\n \ndef light_sweep(side):\n if(side == 'a'):\n column_a.value(0)\n for i in range(8):\n row[i].value(1)\n utime.sleep_ms(200)\n row[i].value(0)\n column_a.value(1)\n else:\n column_b.value(0)\n for i in range(8):\n row[i].value(1)\n utime.sleep_ms(200)\n row[i].value(0)\n column_b.value(1)\n \nwhile True:\n chk_hbt()\n if not (func_butt.value()):\n print(\"function button\")\n send()\n light_sweep('a')\n light_sweep('b')\n utime.sleep_ms(200)\n \n if(can.any(0)):\n get()\n \n if not (a_button.value()):\n print(\"A button, a_pot:\", a_pot.read())\n utime.sleep_ms(200)\n light_sweep('a')\n if not (b_button.value()):\n print(\"B button, b_pot:\", b_pot.read())\n light_sweep('b')\n utime.sleep_ms(200)","sub_path":"examples/example1.py","file_name":"example1.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"597659418","text":"from django import forms\nfrom django.utils.safestring import mark_safe\n\nfrom .models import Client\n\n\nclass ClientAddForm(forms.ModelForm):\n\n class Meta:\n model = Client\n fields = ('name', 'commercial_name', 'email', 'tva_number', 'billing_address', 'city', 'zip_code', 'country',\n 'website', 'google_plus_page', 'no_gplus_notes', 'additional_info')\n\n def __init__(self, *args, **kwargs):\n super(ClientAddForm, self).__init__(*args, **kwargs)\n self.fields['google_plus_page'].initial = \"http://plus.google.com/\"\n self.fields['no_gplus_notes'].help_text = mark_safe(\"If this client doesn't have a Google+ page, \"\n \"write down the reason. Steps to follow: \"\n \"Instructions.\")\n\n def clean_google_plus_page(self):\n gplus_url = self.cleaned_data.get('google_plus_page')\n gplus_notes = self.cleaned_data.get('no_gplus_notes')\n\n if not gplus_url or gplus_url == \"http://plus.google.com/\" and not gplus_notes:\n raise forms.ValidationError(\"Please fill in a reason.\")\n return gplus_url","sub_path":"tracktool/clients/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"98793241","text":"from __future__ import print_function\nfrom flask import Flask\nfrom flask import send_file\n###############################################################################\nimport glob\nimport Image\nimport threading\nimport io\nimport serial\nimport struct\nimport sys\nimport time, math\nimport re\nimport random\n#import os\n###############################################################################\nbackground_color = 0, 0, 0\ndelay0 = 0.1\ndelay1 = 0.1\nallaBilder = []\nrgb0 = []\nrgb1 = []\ncurrentBuff = 1\n###\ncurrentBuff = 0\nallaBilder = []\n###############################################################################\napp = Flask(__name__)\n\n# The start.\n@app.route('/')\ndef index( ):\n\n\tout = '

FREAK-control-pixlor!

'\n\tout += 'List Of GIFs
'\n\tout += 'Test
'\n\treturn out\n\n# Presents a list of all GIFs.\n@app.route('/gifs/')\ndef gifs( ):\t\n\treturn writeHTML(listGifFiles( ))\n\n# Access to the local GIF-files.\n@app.route('/get_image/')\ndef get_image(filename): \n return send_file(filename, mimetype='image/gif')\n\n# Calling function for GIFs.\n@app.route('/rungif//')\ndef runy(gif):\n\tunGifIt(gif)\n\treturn writeHTML(listGifFiles( ))\n\n###############################################################################\ndef listGifFiles( ):\t\n\n\tgifList = ''\n\tgifList += 'Back To Index'\n\tgifList += '\\n'\n\tgifList += '\t\\n'\n\tgifList += '\t\t\\n'\n\n\tcnt = 1\n\t\n\tfor file in sorted(glob.glob(\"*.gif\")):\n\t\t\n\t\tif(cnt==0):\n\t\t\tgifList += '\t\\n'\n\t\t\n\t\tgifList += '\t\t\\n'\n\t\tcnt += 1\n\n\t\tif(cnt==20):\n\t\t\tgifList += '\t\\n'\n\t\t\tcnt = 0\n\n\tgifList += '
'\n\t\tgifList += '\t\t
\\n'\n\n\treturn gifList\n\ndef writeHTML(inner):\t\n\t\n\tout = '\\n'\n\tout += '\\n'\n\tout += '\t\\n'\n\tout += '\t\\n'\n\tout += '\\n'\n\tout += '\\n'\n\n\tout += inner + '\\n'\n\n\tout += '\\n'\n\tout += '\\n'\n\t\n\treturn out\n\n###############################################################################\ndef unGifIt(infile):\n\n # Opening the GIF picture.\n\ttry:\n\t\tim = Image.open(infile)\n\texcept IOError:\n\t\t#print \"Cant load\"\n\t\tsys.exit(1)\n\n\ti = 0\n\tmypalette = im.getpalette( )\n\tname = infile.rsplit(\".\",1)[0]\n\n # Parsing out the background and updatetime. \t\n\tm = re.match(r\"(\\w+)\\((\\w+)\\,(\\w+)\\,(\\w+)\\,(\\w+)\\)\", infile)\n\tif(currentBuff == 0):\n\t\tif(m is not None):\n\t\t\tbackground_color = int(m.group(3)), int(m.group(4)), int(m.group(5))\n\t\t\tdelay1 = float(m.group(2))/1000\n\t\telse:\n\t\t\tbackground_color = 0,0,0\n\t\t\tdelay1 = 0.25\n\telse:\n\t\tif(m is not None):\n\t\t\tbackground_color = int(m.group(3)), int(m.group(4)), int(m.group(5))\n\t\t\tdelay0 = float(m.group(2))/1000\n\t\telse:\n\t\t\tbackground_color = 0,0,0\n\t\t\tdelay0 = 0.25\n\n # Extracting the data out of the pictures.\n\tlist = []\n\ttry:\n\t\twhile 1:\n\t\t\tim.putpalette(mypalette)\n\t\t\timt = im.convert(\"RGBA\")\n\n\t\t\tnew_im = Image.new(\"RGB\", imt.size, background_color)\n\t\t\trotated = imt.rotate(270)\n\t\t\tnew_im.paste(rotated,None, rotated)\n\n\t\t\tpixeldata = new_im.load( )\n\t\t\t(w, h) = new_im.size\n\n\t\t\tfor j in range(h):\n\t\t\t\tfor k in range(w):\n\t\t\t\t\tlist.append(([str(l) for l in pixeldata[j,k]]))\n\n\t\t\ti += 1\n\t\t\tim.seek(im.tell( ) + 1)\n\n\texcept EOFError:\n\t\tpass\n\t\n\tif(currentBuff == 0):\n\t\trgb1 = []\n\t\tfor i in range(len(list)/256):\n\t\t\tpic = \"\"\n\t\t\tfor j in range(256):\n\t\t\t\tpixdat = ''.join([chr(int((float(v)/255.0)**math.e*255.0)) for v in list[i*256+j]])\n\t\t\t\tif len(pixdat) != 3:\n\t\t\t\t\traise Exception(\"WTF! %s\" % repr(pixdat))\n\t\t\t\tpic += pixdat \n\n\t\t\trgb1.append(pic[::-1])\n\t\tcurrentBuff = 1\n\telse:\n\t\trgb0 = []\n\t\tfor i in range(len(list)/256):\n\t\t\tpic = \"\"\n\t\t\tfor j in range(256):\n\t\t\t\tpixdat = ''.join([chr(int((float(v)/255.0)**math.e*255.0)) for v in list[i*256+j]])\n\t\t\t\tif len(pixdat) != 3:\n\t\t\t\t\traise Exception(\"WTF! %s\" % repr(pixdat))\n\t\t\t\tpic += pixdat \n\n\t\t\trgb0.append(pic[::-1])\n\t\tcurrentBuff = 0\n\ndef gifSender( ):\n\n\twhile(1):\n\n\t\tif(currentBuff == 0):\n\t\t\tfor p in range(len(rgb0)):\n\t\t\t\tser.write(rgb0[p])\n\t\t\t\tser.flush( )\n\t\t\t\ttime.sleep(delay0)\n\t\telse:\n\t\t\tfor p in range(len(rgb1)):\n\t\t\t\tser.write(rgb1[p])\n\t\t\t\tser.flush( )\n\t\t\t\ttime.sleep(delay1)\n\t\t\t\t\ndef randomRun( ):\n\n\t\n\trunTime = 10.0\n\ttime.sleep(runTime)\n\n\twhile(1):\n\n\t\tbajs = random.randrange(0,len(allaBilder)-1)\n\t\tranStr = allaBilder[bajs]\n\t\tunGifIt(ranStr)\n\t\ttime.sleep(runTime)\n\n###############################################################################\nif __name__ == '__main__':\n\n\n\tcurrentBuff = 0\n\tser = serial.Serial('/dev/ttyUSB0',baudrate=1500000)\n\t\n\tfor file in glob.glob(\"*.gif\"):\n\t \tallaBilder.append(str(file))\n\n\tunGifIt(\"char00(100,0,0,0).gif\")\n\n\tt = threading.Thread(target=gifSender)\n\tt.setDaemon(True)\n\tt.start()\n\n\tr = threading.Thread(target=randomRun)\n\tr.setDaemon(True)\n\tr.start()\n\n#\tapp.run(host='0.0.0.0')","sub_path":"pythonServer/hello2.py","file_name":"hello2.py","file_ext":"py","file_size_in_byte":5074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"383265825","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.ram = [0]*256\n self.reg = [0] * 8\n self.pc = 0 # Program Counter, address of the currently executing instruction\n self.sp = 7 # stack pointer location R7\n self.branchtable = {\n 1: self.handle_HLT,\n 130: self.handle_LDI,\n 71: self.handle_PRN,\n 160: self.handle_ADD,\n 162: self.handle_MUL,\n 69: self.handle_PUSH,\n 70: self.handle_POP,\n 80: self.handle_CALL,\n 17: self.handle_RET\n }\n\n def load(self, file):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n\n with open(file) as f:\n for line in f:\n comments = line.split(\"#\")\n num = comments[0].strip()\n\n try: \n val = int(f'{num}',2)\n except ValueError:\n continue\n\n self.ram[address] = val\n address += 1 \n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n elif op == \"SUB\": \n self.reg[reg_a] -= self.reg[reg_b]\n elif op == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\n elif op == \"DIV\":\n self.reg[reg_a] /= self.reg[reg_b]\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n #self.fl,\n #self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n # halt\n def handle_HLT(self):\n self.pc +=1\n sys.exit(1)\n\n # load to register\n def handle_LDI(self):\n regAddress = self.ram_read(self.pc+1)\n integer = self.ram_read(self.pc+2)\n self.reg[regAddress] = integer\n self.pc +=3\n\n # print\n def handle_PRN(self):\n print(self.reg[self.ram_read(self.pc+1)])\n self.pc +=2\n\n def handle_ADD(self):\n regAddressA = self.ram_read(self.pc+1)\n regAddressB = self.ram_read(self.pc+2)\n self.alu('ADD', regAddressA, regAddressB)\n self.pc +=3\n\n def handle_MUL(self):\n regAddressA = self.ram_read(self.pc+1)\n regAddressB = self.ram_read(self.pc+2)\n self.alu('MUL', regAddressA, regAddressB)\n self.pc +=3\n\n # handles stack addition\n def handle_PUSH(self):\n regAddress = self.ram[self.pc + 1]\n value = self.reg[regAddress]\n self.reg[self.sp] -= 1 # decrement the pointer address\n self.ram[self.reg[self.sp]] = value\n self.pc += 2\n\n # handles stack removal\n def handle_POP(self):\n regAddress = self.ram[self.pc + 1]\n value = self.ram[self.reg[self.sp]]\n self.reg[regAddress] = value\n self.reg[self.sp] += 1\n self.pc += 2\n\n # handles functions calls\n def handle_CALL(self):\n self.reg[self.sp] -= 1\n self.ram[self.reg[self.sp]] = self.pc+2\n regAddress = self.ram[self.pc+1]\n self.reg[6] = self.pc+2\n self.pc = self.reg[regAddress]\n\n # handles function returns\n def handle_RET(self):\n pc = self.ram[self.reg[self.sp]]\n self.reg[self.sp] += 1\n self.pc = self.reg[6]\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n while True:\n ir = self.ram_read(self.pc) # Instruction Register, currently executing instruction\n self.branchtable[ir]()\n\n # accepts the address to read and return the value stored there.\n # MAR = Memory Address Register, address that is being read or written to\n def ram_read(self, MAR):\n return self.ram[MAR]\n\n # accepts a value to write, and the address to write it to.\n # MAR = Memory Address Register, address that is being read or written to\n # MDR = Memory Data Register, address that is being read or written to\n def ram_write(self, MDR, MAR):\n self.ram[MAR] = MDR","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"212273216","text":"from collections import deque\n\n\n# python 实现相关的队列的方式\nclass Node:\n def __init__(self,data):\n self.data=data\n self.next=None\n\nclass Queue:\n\n def __init__(self):\n self.rear=None\n self.front=None\n self.r=0\n self.f=0\n\n def isEMpty(self):\n if self.r==self.f:\n print(\"The queue is empty\")\n else:\n print(\"The queue is not empty\")\n\n def dequeue(self,data):\n if self.f==self.r:\n q=Node(data)\n self.rear=q\n self.front=q\n self.r=0\n self.f=1\n else:\n q=Node(data)\n self.rear.next=q\n self.rear=q\n self.f+=1\n\n def enqueue(self):\n if self.r==self.f:\n print(\"The Queue is empty\")\n #return false\n else:\n self.front=self.front.next\n self.f=self.f-1\n\n def top(self):\n if self.r==self.f:\n print(\"empty\")\n else:\n print(self.front.data)\n\nif __name__ == '__main__':\n queue = Queue()\n queue.dequeue(123)\n print(queue.top())\n queue.enqueue()\n print(queue.top())","sub_path":"LanguageDatastruct/PythonLearn/dataStruct/queue/pyqueue.py","file_name":"pyqueue.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"328919773","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as tick\nimport sys\nfrom matplotlib.ticker import ScalarFormatter\nfrom matplotlib import rcParams\nrcParams.update({'figure.autolayout': True}) #used for fiting the subplot\nrcParams.update({'xtick.labelsize':10})\nrcParams.update({'ytick.labelsize':10})\n\ndef readFile(filePath):\n\n\tf=open(filePath)\n\tx=[]\n\tfor line in f:\n\t\tval=float(line.strip('\\n'))\n\t\tif val>0.009:\n\t\t\tx+=val,\n\n\treturn x\n\n# def y_fmt(x, y):\n# return '{:2.2e}'.format(x).replace('e', 'x10^')\n\n\n\nif __name__==\"__main__\":\n\t#degree distribution \n\tfolder=\"/Users/dongqingxiao/Documents/uncertainGraphProject/allDataSet/input/\"\n\t\n\txlabel_='Edge-Probability'\n\tdataset=['dblp','bright','ppi']\n\tfig, axs = plt.subplots(3,1,figsize=(3,8))\n\tfor i in xrange(3):\n\t\tdata=dataset[i]\n\t\tx=readFile(folder+data+\"_p_e.txt\")\n\t\tax=axs[i]\n\t\tax.hist(x,bins=100)\n\t\ty_formatter=ScalarFormatter(useMathText=True)\n\t\ty_formatter.set_powerlimits((5,5))\n\t\tax.yaxis.set_major_formatter(y_formatter)\n\t\tax.set_ylabel('Frequency',fontsize=12)\n\t\tax.set_xlabel(xlabel_,fontsize=12)\n\t\tif data=='bright':\n\t\t\tdata=\"Brightkite\"\n\t\tax.set_title(data.upper(),fontsize=12)\n\t\tax.locator_params(axis='x',nbins=5)\n\t\tax.locator_params(axis='y',nbins=4)\n\t\tax.set_xlim([0,1])\n\tplt.show()\n\n\n\t\n\t\n\n\n\n","sub_path":"ill/edge-Prob-Diff.py","file_name":"edge-Prob-Diff.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"431767249","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'spellchecker_app'\nurlpatterns = [\n # default index\n url(r'^$', views.index, name='index'),\n url(r'^correction/$', views.correction , name='correction'),\n url(r'^result/$', views.result, name='result'),\n]\n\n","sub_path":"spellchecker_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"277948319","text":"# Linked List hash table key/value pair\n\nclass LinkedPair:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\n# Fill this in\n\n# Resizing hash table\n\nclass HashTable:\n def __init__(self, capacity):\n self.storage = [None] * capacity\n self.capacity = capacity\n self.count = 0\n\n# Research and implement the djb2 hash function\n\ndef hash(string, max):\n hash = 5381\n \n for character in string:\n hash = ((hash << 5) + hash) + ord(character)\n \n return hash % max\n\n# Fill this in.\n\n# Hint: Used the LL to handle collisions\n\ndef hash_table_insert(hash_table, key, value):\n # Generate index for key using hash function.\n index = hash(key, hash_table.capacity)\n print(f\"Insert Print Statement {key} {index}\")\n\n # Lets retrieve the current pair at the specified index.\n current_pair = hash_table.storage[index]\n\n # Loop if the current pair already is a LL.\n # If the key already exists in the LL we just change the value for that key.\n while current_pair is not None and current_pair.key != key:\n # Assign current pair to the next pair.\n current_pair = current_pair.next\n \n # if current pair is None then the key does not exist in our hash table because it is new.\n if current_pair is None:\n # Create a new pair for our new key and value.\n new_pair = LinkedPair(key, value)\n # Grab old head.\n old_head = hash_table.storage[index]\n # Assign the LL head to the new pair.\n hash_table.storage[index] = new_pair\n new_pair.next = old_head\n\n if new_pair.next is None: # [LL(2 Pairs), LL(1 Pair), None]\n hash_table.count += 1\n else:\n # The key does exist already in hash table so just assign a new value to it.\n current_pair.value = value\n\n# Fill this in.\n\n# If you try to remove a value that isn't there, print a warning.\n\ndef hash_table_remove(hash_table, key):\n # Generate index for key using hash function.\n index = hash(key, hash_table.capacity)\n # Lets get current pair at the specified index.\n current_pair = hash_table.storage[index]\n prev_pair = None\n\n if current_pair is not None:\n # Loop if the current pair already is a LL.\n # We also need to check if the key exists in the LL.\n while current_pair is not None and current_pair.key != key:\n # Assign the current pair to the previous pair.\n # Assign the current pair to the next pair.\n prev_pair = current_pair\n current_pair = current_pair.next\n \n # If the previous pair is none and the current pair key equals key.\n # Then, remove the only pair that existed at the current index position in the hash table.\n if prev_pair is None and current_pair.key == key:\n hash_table.storage[index] = None\n hash_table.count -= 1\n # If current pair is None the key does not exist in our hash table.\n elif current_pair is None:\n print(f\"Error 1: {key} not found.\")\n else:\n # We found the key!! We change the next pointer of previous pair to None.\n prev_pair.next = None\n else:\n print(f\"Error 2: {key} not found.\")\n\n# Fill this in.\n\n# Should return None if the key is not found.\n\ndef hash_table_retrieve(hash_table, key):\n # Generate index for key using hash function.\n index = hash(key, hash_table.capacity)\n print(f\"Retrieve Print Statement {key} {index}\")\n \n # Lets retrieve current pair at the specified index.\n current_pair = hash_table.storage[index]\n\n if current_pair is not None:\n # Loop if the current pair already is a LL.\n # We also need to check if the key exists in the LL.\n while current_pair is not None and current_pair.key != key:\n # Assign current pair to the next pair.\n current_pair = current_pair.next\n \n # if current pair is None then the key does not exist in our hash table.\n if current_pair is None:\n print(f\"Error: {key} not found.\")\n else:\n # We found the key!! Return the value for the key!\n return current_pair.value\n else:\n print(f\"Error: {key} not found.\")\n\n# Fill this in\n\ndef hash_table_resize(hash_table):\n # Create a new hash table and give it a new capacity (e.g Double the old capacity).\n new_hash_table = HashTable(hash_table.capacity * 2)\n\n for x in range(hash_table.count):\n current_pair = hash_table.storage[x]\n\n while current_pair is not None:\n hash_table_insert(new_hash_table, current_pair.key, current_pair.value)\n current_pair = current_pair.next\n \n # Use the function below to check your new hash table!\n # check_hash_table(new_hash_table)\n \n return new_hash_table\n\ndef check_hash_table(hash_table):\n arr = []\n\n for x in range(hash_table.count):\n arr.append([])\n current_pair = hash_table.storage[x]\n\n while current_pair is not None:\n if current_pair.next is None:\n arr[x].append((current_pair.key, current_pair.value, None))\n else:\n arr[x].append((current_pair.key, current_pair.value, current_pair.next.key))\n current_pair = current_pair.next\n \n print('new hash table', arr)\n\ndef Testing():\n ht = HashTable(2)\n\n hash_table_insert(ht, \"line_1\", \"Tiny hash table\")\n hash_table_insert(ht, \"line_2\", \"Filled beyond capacity\")\n hash_table_insert(ht, \"line_3\", \"Linked list saves the day!\")\n\n print(hash_table_retrieve(ht, \"line_1\"))\n print(hash_table_retrieve(ht, \"line_2\"))\n print(hash_table_retrieve(ht, \"line_3\"))\n\n old_capacity = len(ht.storage)\n ht = hash_table_resize(ht)\n new_capacity = len(ht.storage)\n\n print(\"Resized hash table from \" + str(old_capacity) + \" to \" + str(new_capacity) + \".\")\n\nTesting()","sub_path":"resizing_hashtable/r_hashtables.py","file_name":"r_hashtables.py","file_ext":"py","file_size_in_byte":5533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"401602826","text":"# Adapted from Magenta console commands\n\nimport os\nfrom magenta.models.arbitrary_image_stylization import arbitrary_image_stylization_build_model as build_model\nfrom magenta.models.image_stylization import image_utils\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nimport tf_slim as slim\n\n\nclass Magenta_Model():\n\n def __init__(self, checkpoint,\n content_square_crop=False, style_square_crop=False,\n style_image_size=256, content_image_size=256):\n\n tf.disable_v2_behavior()\n tf.Graph().as_default()\n sess = tf.Session()\n\n # Defines place holder for the style image.\n self.style_img_ph = tf.placeholder(tf.float32, shape=[None, None, 3])\n\n if style_square_crop:\n style_img_preprocessed = image_utils.center_crop_resize_image(\n style_img_ph, style_image_size)\n else:\n style_img_preprocessed = image_utils.resize_image(self.style_img_ph,\n style_image_size)\n\n # Defines place holder for the content image.\n content_img_ph = tf.placeholder(tf.float32, shape=[None, None, 3])\n if content_square_crop:\n content_img_preprocessed = image_utils.center_crop_resize_image(\n content_img_ph, content_image_size)\n else:\n content_img_preprocessed = image_utils.resize_image(\n content_img_ph, content_image_size)\n\n # Defines the model.\n stylized_images, _, _, bottleneck_feat = build_model.build_model(\n content_img_preprocessed,\n style_img_preprocessed,\n trainable=False,\n is_training=False,\n inception_end_point='Mixed_6e',\n style_prediction_bottleneck=100,\n adds_losses=False)\n\n checkpoint = tf.train.latest_checkpoint(checkpoint)\n init_fn = slim.assign_from_checkpoint_fn(checkpoint, slim.get_variables_to_restore())\n sess.run([tf.local_variables_initializer()])\n init_fn(sess)\n\n self.sess = sess\n self.stylized_images = stylized_images\n self.content_img_preprocessed = content_img_preprocessed\n self.style_img_preprocessed = style_img_preprocessed\n self.content_img_ph = content_img_ph\n self.bottleneck_feat = bottleneck_feat\n\n\n def process_data(self, style_images_paths, content_images_paths):\n\n # Gets the list of the input images.\n\n style_img_list = tf.gfile.Glob(style_images_paths)\n content_img_list = tf.gfile.Glob(content_images_paths)\n\n for content_i, content_img_path in enumerate(content_img_list):\n content_img_np = image_utils.load_np_image_uint8(content_img_path)[:, :, :3]\n content_img_name = os.path.basename(content_img_path)[:-4]\n\n # Saves preprocessed content image.\n inp_img_croped_resized_np = self.sess.run(\n self.content_img_preprocessed, feed_dict={\n self.content_img_ph: content_img_np})\n\n # Computes bottleneck features of the style prediction network for the\n # identity transform.\n identity_params = self.sess.run(\n self.bottleneck_feat, feed_dict={self.style_img_ph: content_img_np})\n\n for style_i, style_img_path in enumerate(style_img_list):\n style_img_name = os.path.basename(style_img_path)[:-4]\n style_image_np = image_utils.load_np_image_uint8(style_img_path)[:, :, :3]\n\n self.content_img_np = content_img_np\n self.style_image_np = style_image_np\n self.identity_params = identity_params\n self.style_img_name = style_img_name\n self.content_img_name = content_img_name\n\n\n def run(self, output_dir, interpolation_weights):\n\n style_params = self.sess.run(\n self.bottleneck_feat, feed_dict={self.style_img_ph: self.style_image_np})\n\n for interp_i, wi in enumerate(interpolation_weights):\n stylized_image_res = self.sess.run(\n self.stylized_images,\n feed_dict={\n self.bottleneck_feat:\n self.identity_params * (1 - wi) + style_params * wi,\n self.content_img_ph:\n self.content_img_np\n })\n\n # Saves stylized image.\n image_utils.save_np_image(\n stylized_image_res,\n os.path.join(output_dir, '%s_stylized_%s_%d.jpg' % \\\n (self.content_img_name, self.style_img_name, interp_i)))\n\n\nmagenta_model = Magenta_Model(\"/mnt/disks/ssd_disk/final/models/\",\n content_square_crop=False, style_square_crop=False,\n style_image_size=256, content_image_size=256)\n\nmagenta_model.process_data(style_images_paths=\"/mnt/disks/ssd_disk/final/data/content_images/*\",\n content_images_paths=\"/mnt/disks/ssd_disk/final/data/content_images/*\")\n\nmagenta_model.run(\"/mnt/disks/ssd_disk/final/tmp/\", [0., 1.])\n","sub_path":"model/magenta_app.py","file_name":"magenta_app.py","file_ext":"py","file_size_in_byte":4985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"192629539","text":"import argparse\nimport numpy as np\nimport json\nfrom keras.models import load_model\nimport codecs\nimport random, string, sys, os\nimport h5py, h5ToJson, jsonToH5\nfrom shutil import copyfile\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-f\",\"--files\", nargs='+',help=\"Locations of HD5 File Weights as JSON\")\nparser.add_argument(\"-m\",\"--originalmodel\", help=\"Location of the original model HD5 File\")\n\nargs = parser.parse_args()\n\nfileNames = args.files\n\noriginalModel = args.originalmodel\n\nmodelsWeightsArray = []\n\nTotalWeightsMap = {}\nTotalConfigMap = {}\n\nfor file in fileNames:\n data = json.load(open(file))\n modelsWeightsArray.append(data)\n\nfor layerName in modelsWeightsArray[0][\"weights\"].iterkeys():\n layerWeightsAll = []\n for model in modelsWeightsArray:\n a_new = np.asarray(model[\"weights\"][layerName])\n layerWeightsAll.append(a_new)\n TotalWeightsMap[layerName]=layerWeightsAll\n\nfor configVar in modelsWeightsArray[0][\"config\"].iterkeys():\n configValuesAll = []\n for model in modelsWeightsArray:\n a_new = np.asarray(model[\"config\"][configVar])\n configValuesAll.append(a_new)\n TotalConfigMap[configVar] = configValuesAll\n\n\ndef average(listOfNP):\n return np.mean(listOfNP, axis=0)\n\nfinalWeightsMap = {}\nfinalConfigMap = {}\n\nfor key in TotalWeightsMap.iterkeys():\n avg = average(TotalWeightsMap[key])\n finalWeightsMap[key]=avg\n\nfor key in TotalConfigMap.iterkeys():\n avg = np.mean(TotalConfigMap[key])\n finalConfigMap[key]=avg\n\nloaded_model = load_model(originalModel)\n\nnewModelName = (''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(20))) + \".h5\"\n\nloaded_model.save(newModelName)\n\nh5File2 = h5py.File(newModelName)\n\nfor dSetName in h5File2[\"model_weights\"].iterkeys():\n for layer in h5File2[\"model_weights\"][dSetName].iterkeys():\n for layerConfig in h5File2[\"model_weights\"][dSetName][layer].iterkeys():\n key = dSetName+\"/\"+layer+\"/\"+layerConfig\n del h5File2[\"model_weights\"][key]\n dset = h5File2[\"model_weights\"].create_dataset(key, data=finalWeightsMap[key])\n\nattributes = h5File2.attrs\n\nobj = json.loads(attributes.get(\"training_config\"))\nfor key in TotalConfigMap.iterkeys():\n obj[\"optimizer_config\"][\"config\"][key] = TotalConfigMap[key][0].tolist()\n\nattributes.modify(\"training_config\", json.dumps(obj))\n\nsys.stdout.write(newModelName)\n\n","sub_path":"averageJsonH5.py","file_name":"averageJsonH5.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"58655554","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom datetime import timedelta\n\nfrom odoo import fields, tests\nfrom odoo.tests.common import Form\n\n\nclass TestReportStockQuantity(tests.TransactionCase):\n def setUp(self):\n super().setUp()\n self.product1 = self.env['product.product'].create({\n 'name': 'Mellohi',\n 'default_code': 'C418',\n 'type': 'product',\n 'categ_id': self.env.ref('product.product_category_all').id,\n 'tracking': 'lot',\n 'barcode': 'scan_me'\n })\n self.wh = self.env['stock.warehouse'].create({\n 'name': 'Base Warehouse',\n 'code': 'TESTWH'\n })\n self.categ_unit = self.env.ref('uom.product_uom_categ_unit')\n self.uom_unit = self.env['uom.uom'].search([('category_id', '=', self.categ_unit.id), ('uom_type', '=', 'reference')], limit=1)\n self.customer_location = self.env.ref('stock.stock_location_customers')\n self.supplier_location = self.env.ref('stock.stock_location_suppliers')\n # replenish\n self.move1 = self.env['stock.move'].create({\n 'name': 'test_in_1',\n 'location_id': self.supplier_location.id,\n 'location_dest_id': self.wh.lot_stock_id.id,\n 'product_id': self.product1.id,\n 'product_uom': self.uom_unit.id,\n 'product_uom_qty': 100.0,\n 'state': 'done',\n 'date': fields.Datetime.now(),\n })\n self.quant1 = self.env['stock.quant'].create({\n 'product_id': self.product1.id,\n 'location_id': self.wh.lot_stock_id.id,\n 'quantity': 100.0,\n })\n # ship\n self.move2 = self.env['stock.move'].create({\n 'name': 'test_out_1',\n 'location_id': self.wh.lot_stock_id.id,\n 'location_dest_id': self.customer_location.id,\n 'product_id': self.product1.id,\n 'product_uom': self.uom_unit.id,\n 'product_uom_qty': 120.0,\n 'state': 'partially_available',\n 'date': fields.Datetime.add(fields.Datetime.now(), days=3),\n 'date_deadline': fields.Datetime.add(fields.Datetime.now(), days=3),\n })\n self.env['base'].flush()\n\n def test_report_stock_quantity(self):\n from_date = fields.Date.to_string(fields.Date.add(fields.Date.today(), days=-1))\n to_date = fields.Date.to_string(fields.Date.add(fields.Date.today(), days=4))\n report = self.env['report.stock.quantity'].read_group(\n [('date', '>=', from_date), ('date', '<=', to_date), ('product_id', '=', self.product1.id)],\n ['product_qty', 'date', 'product_id', 'state'],\n ['date:day', 'product_id', 'state'],\n lazy=False)\n forecast_report = [x['product_qty'] for x in report if x['state'] == 'forecast']\n self.assertEqual(forecast_report, [0, 100, 100, 100, -20, -20])\n\n def test_report_stock_quantity_with_product_qty_filter(self):\n from_date = fields.Date.to_string(fields.Date.add(fields.Date.today(), days=-1))\n to_date = fields.Date.to_string(fields.Date.add(fields.Date.today(), days=4))\n report = self.env['report.stock.quantity'].read_group(\n [('product_qty', '<', 0), ('date', '>=', from_date), ('date', '<=', to_date), ('product_id', '=', self.product1.id)],\n ['product_qty', 'date', 'product_id', 'state'],\n ['date:day', 'product_id', 'state'],\n lazy=False)\n forecast_report = [x['product_qty'] for x in report if x['state'] == 'forecast']\n self.assertEqual(forecast_report, [-20, -20])\n\n def test_replenishment_report_1(self):\n self.product_replenished = self.env['product.product'].create({\n 'name': 'Security razor',\n 'type': 'product',\n 'categ_id': self.env.ref('product.product_category_all').id,\n })\n # get auto-created pull rule from when warehouse is created\n self.wh.reception_route_id.rule_ids.unlink()\n self.env['stock.rule'].create({\n 'name': 'Rule Supplier',\n 'route_id': self.wh.reception_route_id.id,\n 'location_id': self.wh.lot_stock_id.id,\n 'location_src_id': self.env.ref('stock.stock_location_suppliers').id,\n 'action': 'pull',\n 'delay': 1.0,\n 'procure_method': 'make_to_stock',\n 'picking_type_id': self.wh.in_type_id.id,\n })\n delivery_picking = self.env['stock.picking'].create({\n 'location_id': self.wh.lot_stock_id.id,\n 'location_dest_id': self.ref('stock.stock_location_customers'),\n 'picking_type_id': self.ref('stock.picking_type_out'),\n })\n self.env['stock.move'].create({\n 'name': 'Delivery',\n 'product_id': self.product_replenished.id,\n 'product_uom_qty': 500.0,\n 'product_uom': self.uom_unit.id,\n 'location_id': self.wh.lot_stock_id.id,\n 'location_dest_id': self.ref('stock.stock_location_customers'),\n 'picking_id': delivery_picking.id,\n })\n delivery_picking.action_confirm()\n\n # Trigger the manual orderpoint creation for missing product\n self.env['stock.move'].flush()\n self.env['stock.warehouse.orderpoint'].action_open_orderpoints()\n\n orderpoint = self.env['stock.warehouse.orderpoint'].search([\n ('product_id', '=', self.product_replenished.id)\n ])\n self.assertTrue(orderpoint)\n self.assertEqual(orderpoint.location_id, self.wh.lot_stock_id)\n self.assertEqual(orderpoint.qty_to_order, 500.0)\n orderpoint.action_replenish()\n self.env['stock.warehouse.orderpoint'].action_open_orderpoints()\n\n move = self.env['stock.move'].search([\n ('product_id', '=', self.product_replenished.id),\n ('location_dest_id', '=', self.wh.lot_stock_id.id)\n ])\n # Simulate a supplier delay\n move.date = fields.datetime.now() + timedelta(days=1)\n orderpoint = self.env['stock.warehouse.orderpoint'].search([\n ('product_id', '=', self.product_replenished.id)\n ])\n self.assertFalse(orderpoint)\n\n orderpoint_form = Form(self.env['stock.warehouse.orderpoint'])\n orderpoint_form.product_id = self.product_replenished\n orderpoint_form.location_id = self.wh.lot_stock_id\n orderpoint = orderpoint_form.save()\n\n self.assertEqual(orderpoint.qty_to_order, 0.0)\n self.env['stock.warehouse.orderpoint'].action_open_orderpoints()\n self.assertEqual(orderpoint.qty_to_order, 0.0)\n","sub_path":"addons/stock/tests/test_report_stock_quantity.py","file_name":"test_report_stock_quantity.py","file_ext":"py","file_size_in_byte":6706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"297799461","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 28 19:50:36 2020\r\n\r\n@author: Varsha\r\n\"\"\"\r\n\r\n#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the jumpingOnClouds function below.\r\ndef jumpingOnClouds(c,n):\r\n j=0\r\n b=0\r\n while(j=n or c[j+2]==1):\r\n j=j+1\r\n b=b+1\r\n else:\r\n j=j+2\r\n b=b+1\r\n return b\r\n\r\n\r\nn = int(input())\r\nc = list(map(int, input().rstrip().split()))\r\nprint(jumpingOnClouds(c,n))\r\n","sub_path":"Code library/122.jumping on clouds.py","file_name":"122.jumping on clouds.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"219900729","text":"\r\nsum = float(input())\r\nmesec = int(input())\r\n\r\nsimple = sum\r\ncomplex = sum\r\n\r\nfor i in range(mesec):\r\n\r\n simple += (sum * 0.03)\r\n complex += complex * 0.027\r\n\r\n\r\nprint(\"Simple interest rate: \", end = \"\")\r\nprint(str(\"%.2f\" % simple) + \" lv.\")\r\nprint(\"Complex interest rate: \", end = \"\")\r\nprint(str(\"%.2f\" % complex) + \" lv.\")\r\n\r\n\r\nif simple >= complex:\r\n win = simple - complex\r\n win = \"%.2f\" % win\r\n print(\"Choose a simple interest rate. You will win \" + str(win) + \" lv.\")\r\n\r\nelse:\r\n win = complex - simple\r\n win = \"%.2f\" % win\r\n print(\"Choose a complex interest rate. You will win \" + str(win) + \" lv.\")\r\n\r\n\r\n\r\n\r\n","sub_path":"Newbie-Python/newbie-python-59.py","file_name":"newbie-python-59.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"572113949","text":"#!/usr/bin/env python\nfrom ase.calculators.aims import Aims\nfrom ase import Atom, Atoms\n\natoms = Atoms('PtCO', ([0, 0, 0], [0, 0, 1.6], [0, 0, 2.8]),\n cell=(10, 10, 10))\natoms.pbc=[True, True, True]\natoms.center()\ncalc = Aims(label='bulk/pt-co-relax',\n xc='pbe',\n spin='none',\n kpts=[7, 7, 7],\n relativistic = 'atomic_zora scalar',\n sc_accuracy_etot=1e-4,\n sc_accuracy_eev=1e-2,\n sc_accuracy_rho=1e-4,\n sc_accuracy_forces=1e-3,\n relax_geometry = 'bfgs 0.5e-3')\natoms.set_calculator(calc)\nprint('energy = {0} eV'.format(atoms.get_potential_energy()))\npos = atoms.get_positions()\nprint('----------------------------')\nprint('#bond bond length (A)')\nprint(' Pt-C {0:1.4f}'.format(((pos[1] - pos[0])**2).sum()**0.5))\nprint(' C-O {0:1.4f}'.format(((pos[2] - pos[1])**2).sum()**0.5))\n\nimport os\nos.system('nohup ./sclu-pt-co-vib.py > datas/sclu-pt-co-vib.dat &')\n","sub_path":"sbul-pt-co-relax.py","file_name":"sbul-pt-co-relax.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"341816549","text":"import json\n\nfrom .models import Order, Cart, PaymentOption, Card, Coupon, BillingAddress, WishList\nfrom products.models import Product\nfrom account.models import User\nfrom account.utils import login_check\n\nfrom django.views import View\nfrom django.http import HttpResponse, JsonResponse\nfrom django.db.models import F, ExpressionWrapper, DecimalField\n\nclass WishListView(View):\n @login_check\n def post(self, request):\n try:\n data = json.loads(request.body)\n product = Product.objects.get(id=data['id'])\n wishlist = WishList.objects.filter(user=request.user, product_id=data['id'])\n\n if wishlist.exists():\n wishlist.update(quantity=data['quantity'])\n\n return HttpResponse(status=200)\n\n WishList.objects.create(product=product,\n user=request.user,\n quantity=data['quantity'])\n\n return HttpResponse(status=200)\n\n except Product.DoesNotExist:\n return JsonResponse({'message': 'INVALID_PRDUCT_ID'}, status=400)\n\n except KeyError:\n return JsonResponse({'message': 'INVALID_KEY'}, status=400)\n\n @login_check\n def get(self, request):\n saved_list = [\n {\n 'name' : item.product.name,\n 'price' : item.product.price,\n 'small_image' : item.product.small_image,\n 'quantity' : item.quantity\n } for item in WishList.objects.filter(user=request.user)\n ]\n return JsonResponse({'wishlist': saved_list}, status=200)\n\n @login_check\n def delete(self, request):\n data = json.loads(request.body)\n wishlist = WishList.objects.filter(user=request.user, product_id=data['id'])\n\n if wishlist.exists():\n wishlist.get().delete()\n\n return HttpResponse(status=200)\n\n return JsonResponse({'message': 'INVALID_INPUT'}, status=400)\n\nclass CartView(View):\n @login_check\n def post(self, request):\n try:\n data = json.loads(request.body)\n product = Product.objects.filter(id=data['id'], is_in_stock=True)\n\n if not product.exists():\n return JsonResponse({'message': 'OUT_OF_STOCK'}, status=200)\n\n cart = Cart.objects.filter(user=request.user, product_id=data['id'])\n order = Order.objects.filter(user=request.user, is_closed=False)\n\n if order.exists():\n if cart.exists():\n cart.update(quantity=data['quantity'])\n order.update(package_type_id=data['package_type_id'])\n\n return HttpResponse(status=200)\n\n Cart.objects.create(\n user = request.user,\n order = order.get(),\n product_id = data['id'],\n quantity = data['quantity']\n )\n return HttpResponse(status=200)\n\n else:\n Cart.objects.create(\n user = request.user,\n order = Order.objects.create(user=request.user),\n product_id = data['id'],\n quantity = data['quantity']\n )\n return HttpResponse(status=200)\n\n except KeyError:\n return JsonResponse({'message': 'INVALID_KEYS'}, status=400)\n\n @login_check\n def delete(self, request):\n data = json.loads(request.body)\n cart = Cart.objects.filter(user=request.user, product_id=data['id'])\n\n if cart.exists():\n cart.get().delete()\n\n return HttpResponse(status=200)\n\n return JsonResponse({'message': 'INVALID_INPUT'}, status=400)\n\nclass OrderView(View):\n @login_check\n def get(self, request):\n try:\n saved_order = Order.objects.get(user=request.user, is_closed=False)\n cart = saved_order.cart_set.all()\n\n saved_cart = [\n {\n 'name' : prop.product.name,\n 'price' : prop.product.price,\n 'small_image' : prop.product.small_image,\n 'quantity' : prop.quantity\n } for prop in cart\n ]\n\n total_quantity = sum(item['quantity'] for item in saved_cart)\n total_price = Cart.objects.annotate(price=ExpressionWrapper(F('quantity') * F('product__price'), output_field=DecimalField(10, 2)))\n\n base = 0\n for each_price in total_price:\n base += each_price.price\n saved_order.total_price = base + saved_order.package_type.price\n saved_order.save()\n\n shipping_address = request.user.user_address_set.get(address_id__is_default=True)\n\n res = [saved_cart,\n {\"total_quantity\" : total_quantity},\n {\"total_price\" : saved_order.total_price},\n {\"address1\" : shipping_address.address.address1},\n {\"address2\" : shipping_address.address.address2},\n {\"city\" : shipping_address.address.city},\n {\"state\" : shipping_address.address.state},\n {\"postcode\" : shipping_address.address.postcode.postcode},\n {\"country\" : shipping_address.address.country},\n {\"shipping_cost\" : shipping_address.address.postcode.shipping_cost}\n ]\n return JsonResponse({'cart': res}, status=200)\n\n except Order.DoesNotExist():\n return JsonResponse({\"message\":\"NO_ORDERS\"}, status=400)\n\n except Cart.DoesNotExist():\n return JsonResponse({\"message\":\"NO_CARTS\"}, status=400) \n\n @login_check\n def post(self,request):\n try:\n data = json.loads(request.body)\n open_order = Order.objects.filter(user = request.user, is_closed = False)\n coupon = Coupon.objects.get(discount_code=data['discount_code'])\n payment = PaymentOption.objects.get(payment=data['payment'])\n\n BillingAddress(\n user = request.user,\n is_shipping_address = data['is_shipping_address'],\n first_name = data['first_name'],\n last_name = data['last_name'],\n address_1 = data['address_1'],\n address_2 = data['address_2'],\n city = data['city'],\n country = data['country'],\n state = data['state'],\n postcode = data['postcode']\n ).save()\n billing = BillingAddress.objects.filter(user=request.user).order_by('-id')[0]\n\n shipping_cost = request.user.user_address_set.get(address_id__is_default=True).address.postcode.shipping_cost\n\n Order(\n billing_address_id = open_order.update(billing_address_id=billing),\n coupon_id = open_order.update(coupon_id=coupon),\n payment_option_id = open_order.update(payment_option_id=payment.id),\n total_price = open_order.get().total_price * (1 - coupon.discount_rate if coupon.discount_rate is not None else 0) + shipping_cost\n ).save()\n\n coupon.is_used= True\n\n return HttpResponse(status=200)\n\n except Coupon.DoesNotExist:\n return JsonResponse({\"message\":\"INVALID_COUPONS\"}, status=400)\n\n except Order.DoesNotExist:\n return JsonResponse({'message': 'INVALID_ACTION'}, status=400)\n\n except KeyError:\n return JsonResponse({'message': 'INVALID_KEYS'}, status=400)\n\nclass ReceiptView(View):\n @login_check\n def get(self, request):\n saved_order = Order.objects.get(user=request.user, is_closed=False)\n cart = saved_order.cart_set.all()\n\n saved_cart = [\n {\n 'name': prop.product.name,\n 'price': prop.product.price,\n 'quantity': prop.quantity\n } for prop in cart\n ]\n\n shipping_address = request.user.user_address_set.get(address_id__is_default=True)\n\n saved_order.is_closed = True\n saved_order.save()\n\n res = [saved_order.user.first_name,\n saved_order.user.last_name,saved_order.payment_option.payment,\n shipping_address.address.address1,\n shipping_address.address.address2,\n shipping_address.address.city,\n shipping_address.address.state,\n shipping_address.address.postcode.postcode,\n shipping_address.address.country,\n saved_cart,\n saved_order.total_price,\n saved_order.package_type.package\n ]\n\n return JsonResponse({'receipt': res}, status=200)\n","sub_path":"order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"526645521","text":"'''2给定两个由小写字母构成的字符串A和B ,只要我们可以通过交换\nA中的两个字母得到与B相等的结果,就返回true ;否则返回false 。\n示例1:\n输入: A = \"ab\", B = \"ba\"\n输出: true\n\n示例2:\n输入: A = \"ab\", B = \"ab\"\n输出: false\n\n示例3:\n输入: A = \"aa\", B = \"aa\"\n输出: true\n\n示例4:\n输入: A = \"aaaaaaabc\", B = \"aaaaaaacb\"\n输出: true\n\n示例5:\n输入: A = \"\", B = \"aa\"\n输出: false'''\n# while True:\nwhile True:\n A =input('输入字符串A:')\n B =input('输入字符串B:')\n if sorted(A)==sorted(B):\n print('true')\n else:\n print('false')","sub_path":"0604/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138158039","text":"\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom django.http import Http404\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils import timezone\n\nfrom .forms import AddValueForm\nfrom .models import Value, Category, User\n\n\nLOGIN_URL = '/login/'\n\ndef Login(request):\n\n next = request.GET.get('next', '/home/')\n\n if request.method == \"POST\":\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n\n if user is not None:\n if user.is_active:\n login(request, user)\n return HttpResponseRedirect(next)\n else:\n return HttpResponse(\"Inactive user.\")\n else:\n return HttpResponseRedirect(LOGIN_URL)\n\n return render(request, \"balanceapp/login.html\", {'redirect_to': next})\n\n@login_required\ndef Home(request):\n\n next = request.GET.get('next', '/home/')\n\n context = {\n 'msg' : 'Home',\n 'redirect_to': next,\n }\n\n return render(request, 'balanceapp/home.html' , context)\n\n@login_required\ndef History(request, value_id=None):\n\n if value_id != None: #should delete\n #print(value_id)\n Value.objects.all().filter(id=value_id).delete()\n\n total_others = 0 #total calculado de gastos de outros\n total_html = 0 #total mostrado na pagina summary\n total_label = 'Total:' #label relacionado com total_html\n value_list = Value.objects.all() #lista de todos elementos\n total_users = 0 #numbero total de usuarios\n filter_user = 0 #filtro selecionado pelo usuario\n list_users = User.objects.all() #lista de usuarios\n\n if(request.method == \"POST\"): #should apply some filter. User is interacting with\n\n filter_user = int(request.POST['filter_user'])\n\n if filter_user != 0 : #Lays or Fernando\n\n value_list = Value.objects.all().filter(user_id=filter_user)\n\n total_users = len(list_users)\n total_label = 'Total ' + list_users.filter(pk=filter_user)[0].user_name + ':'\n\n total_others = 0\n value_list_others = Value.objects.all().exclude(user_id=filter_user)\n for obj in value_list_others:\n total_others += obj.value_float\n\n for obj in value_list:\n total_html += obj.value_float\n\n context = { \"html_value_list\" : value_list,\n \"category_list\" : Category.objects.all(),\n \"html_total\" : total_html,\n \"total_label\" : total_label,\n \"filter_user\" : filter_user,\n \"list_users\" : list_users,\n \"x\" : 0,\n }\n\n if(total_others != 0): #esta sendo utilizando um filtro, e quero a diferenca\n\n aux = total_html + total_others #aux = 70 + 30\n aux = aux / total_users # 100 / 2 = 50\n aux = total_html - aux #70 - 50 = 20\n\n if aux > 0 :\n context['total_others'] = '+' + str(aux)\n else:\n context['total_others'] = str(aux)\n\n return render(request, 'balanceapp/history.html' , context)\n\n@login_required\ndef AddValue(request):\n\n form = AddValueForm(request.POST or None)\n\n context = {}\n\n if(form.is_valid()):\n # instance = form.save(commit=False)\n\n value_float = request.POST['Value']\n\n #assert False, value_float\n\n v = Value()\n v.value_float=value_float\n v.pub_date=timezone.now()\n v.description_text = request.POST['Description']\n v.category_id = Category.objects.all().filter(pk=request.POST['Category'])[0]\n v.user_id = User.objects.all().filter(pk=request.POST['User'])[0]\n\n v.save()\n\n context[\"template_value\"] = value_float # retorna o value e informa o sucesso operacao\n\n\n\n else: #new add form\n\n list_users = User.objects.all() #lista de usuarios\n list_category = Category.objects.all()\n\n context = {\n \"list_category\" : list_category,\n \"list_users\" : list_users,\n \"template_form\" : form,\n }\n\n return render(request, 'balanceapp/addvalue.html' , context)\n\ndef Logout(request):\n logout(request) #desconecta\n return HttpResponseRedirect(LOGIN_URL) #redireciona para pagina de login\n\n\n\n\n\n\n\n\n\n","sub_path":"balanceapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"420836863","text":"# Enter the students score's which are stored in a dictionary\nstudents = {}\n\n\ndef student_info(n):\n value = ['Name', 'Score', 'Score', 'Score']\n avg = 0\n for i in range(n):\n value[0] = input('Name: ')\n for j in range(1, 4): # Enter student scores\n value[j] = eval(input('Score: '))\n avg += value[j]\n students[value[0]] = avg # Assigns student's average to a dictionary key\n\n\ndef main():\n n = int(input('How many students: '))\n student_info(n)\n print(students)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Programs/studentAverage.py","file_name":"studentAverage.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"38802925","text":"import numpy as np\r\nimport pickle\r\nimport seaborn as sns\r\nfrom sklearn import metrics as skmetrics\r\nfrom pathlib import Path\r\nimport matplotlib.pyplot as plt\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\ndef lgb_MaF(preds, dtrain):\r\n Y = np.array(dtrain.get_label(), dtype=np.int32)\r\n preds = preds.reshape(-1, len(Y))\r\n Y_pre = np.argmax(preds, axis=0)\r\n return 'macro_f1', float(F1(preds.shape[0], Y_pre, Y, 'macro')), True\r\n\r\n\r\ndef lgb_precision(preds, dtrain):\r\n Y = dtrain.get_label()\r\n preds = preds.reshape(-1, len(Y))\r\n Y_pre = np.argmax(preds, axis=0)\r\n return 'precision', float(Counter(Y == Y_pre)[True]/len(Y)), True\r\n\r\n\r\nid2lab = [[-1, -1]]*20\r\nfor a in range(1, 11):\r\n for s in [1, 2]:\r\n id2lab[a-1+(s-1)*10] = [a, s]\r\n\r\n\r\nclass Metrictor:\r\n def __init__(self):\r\n self._reporter_ = {\"ACC\": self.ACC, \"AUC\": self.AUC, \"Precision\": self.Precision,\r\n \"Recall\": self.Recall, \"F1\": self.F1, \"LOSS\": self.LOSS}\r\n\r\n def __call__(self, report, end='\\n'):\r\n res = {}\r\n for mtc in report:\r\n v = self._reporter_[mtc]()\r\n print(f\" {mtc}={v:6.3f}\", end=';')\r\n res[mtc] = v\r\n print(end=end)\r\n return res\r\n\r\n def set_data(self, Y_prob_pre, Y, threshold=0.5):\r\n self.Y = Y.astype('int')\r\n if len(Y_prob_pre.shape) > 1:\r\n self.Y_prob_pre = Y_prob_pre[:, 1]\r\n self.Y_pre = Y_prob_pre.argmax(axis=-1)\r\n else:\r\n self.Y_prob_pre = Y_prob_pre\r\n self.Y_pre = (Y_prob_pre > threshold).astype('int')\r\n\r\n @staticmethod\r\n def table_show(resList, report, rowName='CV'):\r\n lineLen = len(report)*8 + 6\r\n print(\"=\"*(lineLen//2-6) + \"FINAL RESULT\" + \"=\"*(lineLen//2-6))\r\n print(f\"{'-':^6}\" + \"\".join([f\"{i:>8}\" for i in report]))\r\n for i, res in enumerate(resList):\r\n print(f\"{rowName+'_'+str(i+1):^6}\" +\r\n \"\".join([f\"{res[j]:>8.3f}\" for j in report]))\r\n print(f\"{'MEAN':^6}\" +\r\n \"\".join([f\"{np.mean([res[i] for res in resList]):>8.3f}\" for i in report]))\r\n print(\"======\" + \"========\"*len(report))\r\n\r\n def each_class_indictor_show(self, id2lab):\r\n print('Waiting for finishing...')\r\n\r\n def ACC(self):\r\n return ACC(self.Y_pre, self.Y)\r\n\r\n def AUC(self):\r\n return AUC(self.Y_prob_pre, self.Y)\r\n\r\n def Precision(self):\r\n return Precision(self.Y_pre, self.Y)\r\n\r\n def Recall(self):\r\n return Recall(self.Y_pre, self.Y)\r\n\r\n def F1(self):\r\n return F1(self.Y_pre, self.Y)\r\n\r\n def LOSS(self):\r\n return LOSS(self.Y_prob_pre, self.Y)\r\n\r\n\r\ndef calc_ROC(y_test, y_score, savePath, timestamp, plot=True):\r\n picklefile = f'logs/ROC_{savePath}_{timestamp}.pkl' # create log with unique timestamp\r\n plotfile = f'logs/plot_ROC_{savePath}_{timestamp}.png' # create log with unique timestamp\r\n all_metrics = dict()\r\n fpr = dict()\r\n tpr = dict()\r\n roc_auc = dict()\r\n\r\n fpr['class'], tpr['class'], _ = skmetrics.roc_curve(y_test, y_score)\r\n roc_auc['class'] = skmetrics.auc(fpr['class'], tpr['class'])\r\n\r\n # Compute micro-average ROC curve and ROC area\r\n fpr[\"micro\"], tpr[\"micro\"], _ = skmetrics.roc_curve(y_test.ravel(), y_score.ravel())\r\n roc_auc[\"micro\"] = skmetrics.auc(fpr[\"micro\"], tpr[\"micro\"])\r\n\r\n all_metrics['fpr'] = fpr\r\n all_metrics['tpr'] = tpr\r\n all_metrics['roc_auc'] = roc_auc\r\n\r\n pickle.dump(all_metrics, open(picklefile, 'wb'))\r\n\r\n if plot:\r\n plt.figure()\r\n lw = 2\r\n plt.plot(fpr['class'], tpr['class'], color='darkorange',\r\n lw=lw, label='ROC curve (area = %0.2f)' % roc_auc['class'])\r\n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\r\n plt.xlim([0.0, 1.0])\r\n plt.ylim([0.0, 1.05])\r\n plt.xlabel('False Positive Rate', fontsize=12)\r\n plt.ylabel('True Positive Rate', fontsize=12)\r\n plt.title('Receiver operating characteristic', fontsize=16)\r\n plt.legend(loc=\"lower right\", fontsize=8)\r\n plt.savefig(plotfile, dpi=300)\r\n plt.clf() # clear the plot object\r\n\r\n\r\ndef calc_conf_matrix(y_true, y_pred, savePath, timestamp, plot=True):\r\n logfile = f'logs/CM_{savePath}_{timestamp}.txt' # create log with unique timestamp\r\n plotfile = f'logs/plot_CM_{savePath}_{timestamp}.png' # create log with unique timestamp\r\n y_pred = np.round(np.clip(y_pred, 0, 1)) # predicted values from continuous to 0,1\r\n tn, fp, fn, tp = skmetrics.confusion_matrix(y_true, y_pred).ravel()\r\n\r\n header = ['TN', 'FP', 'FN', 'TP', '\\n']\r\n with open(logfile, 'a') as out:\r\n out.write(','.join(header))\r\n out.write(f'{tn},{fp},{fn},{tp}\\n')\r\n\r\n if plot:\r\n sns.set(rc={'figure.figsize':(8,6), 'axes.labelsize': 14})\r\n y_pred = np.round(np.clip(y_pred, 0, 1))\r\n cm = skmetrics.confusion_matrix(y_true, y_pred, normalize=None)\r\n ax = sns.heatmap(cm, annot=True, fmt='g', cmap=plt.cm.cividis)\r\n ax.set(xlabel='Actual', ylabel='Predicted')\r\n plt.savefig(plotfile, dpi=300)\r\n plt.clf() # clear the plot object\r\n\r\nclass MetricLog:\r\n \"\"\"\r\n log train and validation loss\r\n \"\"\"\r\n def __init__(self, savePath, timestamp, to_report):\r\n Path(\"logs\").mkdir(parents=True, exist_ok=True)\r\n self.logger = f'logs/train_val_{savePath}_{timestamp}.txt' # create log with unique timestamp\r\n self.best_results = f'logs/best_{savePath}_{timestamp}.txt' # create log with unique timestamp\r\n self.plot_log = f'logs/learn_curve_{savePath}_{timestamp}.png' # create plot file with unique timestamp\r\n self.to_report = to_report\r\n self.save_train = list()\r\n self.save_val = list()\r\n header = [f'{mtc}_train' for mtc in to_report] + [f'{mtc}_valid' for mtc in to_report]\r\n self.header_best = header + [f'{mtc}_test' for mtc in to_report]\r\n self.write_header(header)\r\n\r\n def log_train_val(self, train, val):\r\n train_temp = [train[mtc] for mtc in self.to_report] # log LOSS and additional params in to_report param\r\n val_temp = [val[mtc] for mtc in self.to_report] # log LOSS and additional params in to_report param\r\n self.save_train.append(train_temp)\r\n self.save_val.append(val_temp)\r\n\r\n train_formatted = [f'{train[mtc]:.3f}' for mtc in self.to_report] # format to 3 digit floats\r\n val_formatted = [f'{val[mtc]:.3f}' for mtc in self.to_report] # format to 3 digit floats\r\n self.write_log(train_formatted, val_formatted)\r\n\r\n def write_header(self, header):\r\n with open(self.logger, 'a') as out:\r\n out.write(f'{\",\".join(header)}\\n')\r\n\r\n def write_log(self, train_mtc, val_mtc):\r\n \"\"\"\r\n write all metrics in to_report for train and test\r\n \"\"\"\r\n with open(self.logger, 'a') as out:\r\n out.write(f'{\",\".join(train_mtc)},{\",\".join(val_mtc)}\\n')\r\n\r\n def write_best(self, train, val, test):\r\n test_form = [f'{test[mtc]:.3f}' for mtc in self.to_report] # format to 3 digit floats\r\n train_form = [f'{train[mtc]:.3f}' for mtc in self.to_report] # format to 3 digit floats\r\n val_form = [f'{val[mtc]:.3f}' for mtc in self.to_report] # format to 3 digit floats\r\n\r\n with open(self.best_results, 'w') as out:\r\n out.write(f'{\",\".join(self.header_best)}\\n')\r\n out.write(f'{\",\".join(train_form)},{\",\".join(val_form)},{\",\".join(test_form)}\\n')\r\n\r\n def plot_curve(self):\r\n \"\"\"\r\n default learn curve plotting with just LOSS\r\n \"\"\"\r\n idx = self.to_report.index('LOSS')\r\n x = [i for i in range(1, len(self.save_train)+1)]\r\n\r\n plt.figure(figsize=(10, 8))\r\n fig, ax = plt.subplots()\r\n ax.plot(x, [item[idx] for item in self.save_train], label='train loss', c='blue')\r\n ax.plot(x, [item[idx] for item in self.save_val],label='validation loss', c='orange')\r\n ax.tick_params(axis='both', which='major', labelsize=14)\r\n ax.tick_params(axis='both', which='minor', labelsize=12)\r\n plt.xticks(np.arange(0, max(x)+1, 16))\r\n\r\n plt.legend(fontsize=12)\r\n plt.title('Learning curve', fontsize=18)\r\n plt.xlabel('Epochs', fontsize=16)\r\n plt.ylabel('Loss', fontsize=16)\r\n\r\n plt.savefig(self.plot_log, dpi=300)\r\n\r\n\r\ndef ACC(Y_pre, Y):\r\n return (Y_pre == Y).sum() / len(Y)\r\n\r\n\r\ndef AUC(Y_prob_pre, Y):\r\n return skmetrics.roc_auc_score(Y, Y_prob_pre)\r\n\r\n\r\ndef Precision(Y_pre, Y):\r\n return skmetrics.precision_score(Y, Y_pre)\r\n\r\n\r\ndef Recall(Y_pre, Y):\r\n return skmetrics.recall_score(Y, Y_pre)\r\n\r\n\r\ndef F1(Y_pre, Y):\r\n return skmetrics.f1_score(Y, Y_pre)\r\n\r\n\r\ndef LOSS(Y_prob_pre, Y):\r\n Y_prob_pre, Y = Y_prob_pre.reshape(-1), Y.reshape(-1)\r\n Y_prob_pre[Y_prob_pre > 0.99] -= 1e-3\r\n Y_prob_pre[Y_prob_pre < 0.01] += 1e-3\r\n return -np.mean(Y*np.log(Y_prob_pre) + (1-Y)*np.log(1-Y_prob_pre))\r\n","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":8986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"563944021","text":"import autograd.numpy as np\nfrom autograd import multigrad\n\ncases = {\n\t1: {'HA': 'Ma, Nb -> MNab', 'HAT': 'MNab, Oab -> MNO'},\n\t2: {'HA': 'Ma, Nab -> MNb', 'HAT': 'MNb, Ob -> MNO'},\n\t3: {'HA': 'Mab, Na -> MNb', 'HAT': 'MNb, Ob -> MNO'},\n\t4: {'HA': 'Ma, Na -> MNa', 'HAT': 'MNa, Oa -> MNO'}\n}\n\n\ndef multiply_case(H, A, T, case):\n\tHA = np.einsum(cases[case]['HA'], H, A)\n\tHAT = np.einsum(cases[case]['HAT'], HA, T)\n\treturn HAT\n\n\ndef cost_abs(H, A, T, E_np_masked, case):\n\tHAT = multiply_case(H, A, T, case)\n\tmask = ~np.isnan(E_np_masked)\n\terror = (HAT - E_np_masked)[mask].flatten()\n\treturn np.sqrt((error ** 2).mean())\n\n\ndef cost_rel(H, A, T, E_np_masked, case):\n\tHAT = multiply_case(H, A, T, case)\n\tmask = ~np.isnan(E_np_masked)\n\terror = (HAT - E_np_masked)[mask].flatten() / (1 + E_np_masked[mask].flatten())\n\treturn np.sqrt((error ** 2).mean())\n\n\ndef set_known(A, W):\n\tmask = ~np.isnan(W)\n\tA[:, :mask.shape[1]][mask] = W[mask]\n\treturn A\n\n\ndef learn_HAT(case, E_np_masked, a, b, num_iter=2000, lr=0.1, dis=False, cost_function='abs', H_known=None,\n A_known=None, T_known=None):\n\tnp.random.seed(0)\n\tif cost_function == 'abs':\n\t\tcost = cost_abs\n\telse:\n\t\tcost = cost_rel\n\tmg = multigrad(cost, argnums=[0, 1, 2])\n\n\tparams = {}\n\tparams['M'], params['N'], params['O'] = E_np_masked.shape\n\tparams['a'] = a\n\tparams['b'] = b\n\tH_dim_chars = list(cases[case]['HA'].split(\",\")[0].strip())\n\tH_dim = tuple(params[x] for x in H_dim_chars)\n\tA_dim_chars = list(cases[case]['HA'].split(\",\")[1].split(\"-\")[0].strip())\n\tA_dim = tuple(params[x] for x in A_dim_chars)\n\tT_dim_chars = list(cases[case]['HAT'].split(\",\")[1].split(\"-\")[0].strip())\n\tT_dim = tuple(params[x] for x in T_dim_chars)\n\tH = np.random.rand(*H_dim)\n\n\tA = np.random.rand(*A_dim)\n\tT = np.random.rand(*T_dim)\n\n\t# GD procedure\n\tfor i in range(num_iter):\n\t\tdel_h, del_a, del_t = mg(H, A, T, E_np_masked, case)\n\t\tH -= lr * del_h\n\t\tA -= lr * del_a\n\t\tT -= lr * del_t\n\t\t# Projection to known values\n\t\tif H_known is not None:\n\t\t\tH = set_known(H, H_known)\n\t\tif A_known is not None:\n\t\t\tA = set_known(A, A_known)\n\t\tif T_known is not None:\n\t\t\tT = set_known(T, T_known)\n\t\t# Projection to non-negative space\n\t\tH[H < 0] = 0\n\t\tA[A < 0] = 0\n\t\tT[T < 0] = 0\n\t\tif i % 500 == 0:\n\t\t\tif dis:\n\t\t\t\tprint(cost(H, A, T, E_np_masked, case))\n\treturn H, A, T\n","sub_path":"aaai/tensor_custom_core.py","file_name":"tensor_custom_core.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"240174665","text":"from sklearn.model_selection import train_test_split\n\nfrom datasets.tools import ColumnType, load_csv\n\n\ndef load_dataset(test_set_fraction: float = 0.3, rnd_seed: int = 0):\n\t\"\"\"\n\tLoads the Breast Cancer Wisconsin (Diagnostic) Data Set. https://www.kaggle.com/uciml/breast-cancer-wisconsin-data\n\n\t:return:\n\t\"\"\"\n\tcolumn_types = [\n\t\tColumnType.DISCARD,\n\t\tColumnType.LABEL\n\t] + 30 * [ColumnType.NUMERIC]\n\n\tdata, labels = load_csv(\"/home/philipp/MEGA/Studium/PlanQK/MA/Projekt/datasets/breast_cancer_wisconsin/data.csv\", column_types)\n\tinput_train, input_test, target_train, target_test = train_test_split(\n\t\tdata, labels, test_size=test_set_fraction, random_state=rnd_seed, shuffle=True)\n\n\treturn input_train, target_train, input_test, target_test\n\n\nif __name__ == \"__main__\":\n\tload_dataset()\n","sub_path":"datasets/breast_cancer_wisconsin/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"298489383","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import api, models, fields\nfrom odoo.osv import expression\nimport time\nimport base64\nfrom odoo.exceptions import UserError\n\n\nclass ProjectIssue(models.Model):\n \"\"\" Helpdesk Cases \"\"\"\n\n _description = \"Helpdesk\"\n _inherit = 'project.issue'\n _rec_name = 'of_code'\n\n # le champ Etat, remplacer par les valeurs traduites\n# Migration\n# def _of_finish_install(self, cr, uid):\n# cr.execute(\"SELECT * FROM information_schema.columns WHERE table_name='of_sav_docs' AND column_name='state'\")\n# if cr.fetchone():\n# cr.execute(\"UPDATE of_sav_docs SET state = 'Brouillon' WHERE state = 'Draft' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'Ouverte' WHERE state = 'Open' \");\n# cr.execute(u\"UPDATE of_sav_docs SET state = 'Pay\\u00E9' WHERE state = 'Paid' \");\n# cr.execute(u\"UPDATE of_sav_docs SET state = 'Annul\\u00E9e' WHERE state = 'Cancelled' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'Devis' WHERE state = 'Quotation' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'Attente de planification' WHERE state = 'Waiting Schedule' \");\n# cr.execute(u\"UPDATE of_sav_docs SET state = '\\u00C0 facturer' WHERE state = 'To Invoice' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'En cours' WHERE state = 'In Progress' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'Exception d''envoi' WHERE state = 'Shipping Exception' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'Incident de facturation' WHERE state = 'Invoice Exception' \");\n# cr.execute(u\"UPDATE of_sav_docs SET state = 'Termin\\u00E9' WHERE state = 'Done' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'Demandes de prix' WHERE state = 'Request for Quotation' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'En attente' WHERE state = 'Waiting' \");\n# cr.execute(\"UPDATE of_sav_docs SET state = 'En attente d''approbation' WHERE state = 'Waiting Approval' \");\n# cr.execute(u\"UPDATE of_sav_docs SET state = 'Confirm\\u00E9 par fournisseur' WHERE state = 'Approved' \");\n\n @api.model\n def _of_set_code(self):\n \"\"\" Fonction lancée à l'installation, après la création de la séquence.\n Remplit la colonne 'of_code' pour tous les SAV déjà saisis\n \"\"\"\n to_set_of_code = self.sudo().search(['|',('of_code', '=', ''),('of_code', '=', False)])\n if to_set_of_code:\n seq_obj = self.env['ir.sequence']\n query = \"UPDATE project_issue SET of_code='%s' WHERE id=%s\"\n for helpdesk_id in to_set_of_code [::-1]:\n of_code = seq_obj.sudo().get('of.project.issue')\n if not of_code:\n # La séquence n'a pas été trouvée\n break\n self._cr.execute(query % (of_code, helpdesk_id.id))\n\n @api.depends\n def _get_partner_invoices(self):\n invoice_obj = self.env['account.invoice']\n tre = {}\n for h in self:\n if h.partner_id:\n tre[h.id] = invoice_obj.search([('partner_id', '=', h.partner_id.id)])\n else:\n tre[h.id] = []\n return tre\n\n @api.depends\n def _get_fournisseurs(self):\n fourns = {}\n for sav in self:\n f_ids = []\n for doc in sav.doc_ids:\n partner = doc.partner_id\n if partner and partner.supplier and partner.id not in f_ids:\n f_ids.append(partner.id)\n fourns[sav.id] = f_ids\n return fourns\n\n @api.depends\n def _get_fourn_messages(self):\n mail_obj = self.env['mail.message']\n result = {}\n models = [('purchase.order','name'), ('account.invoice','internal_number')]\n\n for sav in self.read(['of_code']):\n of_codes = [sav['of_code']]\n\n mails = mail_obj.search([('model','=',self._name),('res_id','=',sav['id']),('partner_id.supplier','=',True)])\n model_ids = {model:[] for model,_ in models}\n\n while of_codes:\n of_code = of_codes.pop()\n for model,of_code_field in models:\n mod_ids = self.pool[model].search([('partner_id.supplier','=',True),('origin','like',of_code),('id','not in',model_ids[model])])\n if mod_ids:\n model_ids[model] += mod_ids\n mails += mail_obj.search([('model','=',model),('res_id','in',mod_ids)])\n vals = self.pool[model].read(mod_ids, [of_code_field])\n of_codes += [v[of_code_field] for v in vals]\n # On remet les mails dans l'ordre\n if mails:\n mails = mail_obj.search([('id','in',mails)])\n result[sav['id']] = mails\n return result\n\n # Migration\n # @api.depends\n # def _get_show_partner_shop(self, name, arg, context):\n # res = {}\n # for helpdesk in self:\n # res[helpdesk.id] = helpdesk.shop_id.id != helpdesk.partner_shop_id.id\n # return res\n\n # Migration\n # def _get_categ_parent_id(self, cr, uid, ids, *args):\n # result = {}\n # for sav in self.browse(cr, uid, ids):\n # if sav.categ_id:\n # if sav.categ_id.parent_id:\n # categ_id = sav.categ_id.parent_id.id\n # else:\n # categ_id = sav.categ_id.id\n # else:\n # categ_id = False\n # result[sav.id] = categ_id\n # return result\n\n\n of_code = fields.Char('Code', size=64, required=True, readonly=True, select=True, default='Nouveau') # Migration 9 states={'draft': [('readonly', False)]},\n partner_note = fields.Text(\"Note client\", related='partner_id.comment', readonly=False)\n invoice_ids = fields.One2many('account.invoice', compute='_get_partner_invoices', string='Factures du client', method=True, readonly=True)\n of_categorie_id = fields.Many2one('of.project.issue.categorie', u'Catégorie', required=False, ondelete='restrict')\n of_categorie_mere_id = fields.Many2one(related=\"of_categorie_id.pparent_id\", string=u'Catégorie mère', store=True)\n of_canal_id = fields.Many2one('of.project.issue.canal', u'Canal', required=False, ondelete='restrict')\n of_garantie = fields.Boolean('Garantie', default=False)\n of_payant_client = fields.Boolean('Payant client', default=False)\n of_payant_fournisseur = fields.Boolean('Payant fournisseur', default=False)\n of_intervention = fields.Text(\"Nature de l'intervention\")\n of_piece_commande = fields.Text('Pièces à commander')\n # Migration 'shop_id' : fields_oldapi.many2one('sale.shop', 'Magasin'),\n # Migration 'partner_shop_id' : fields_oldapi.related('partner_id','partner_maga', type=\"many2one\", relation=\"sale.shop\", string=\"Magasin client\", readonly=True),\n doc_ids = fields.One2many('of.sav.docs', 'project_issue_id', string=\"Liste de documents\")\n fourn_ids = fields.One2many('res.partner', compute='_get_fournisseurs', string=\"Fournisseurs\", readonly=True, domain=[('supplier','=',True)])\n fourn_msg_ids = fields.One2many('mail.message', compute='_get_fourn_messages', string=\"Historique fournisseur\")\n #Migration 9 'categ_parent_id' : fields_oldapi.function(_get_categ_parent_id, method=True, string=u\"Catégorie parent\", type='many2one', relation='crm.case.categ',\n # store={'project.issue': (lambda self, cr, uid, ids, *a:ids, ['categ_id'], 10),\n # 'categ_id' : (lambda self, cr, uid, ids, *a:self.pool['of.project.issue'].search(cr, uid, [('categ_id','in',ids)]), ['parent_id'], 10),\n # }),\n interventions_liees = fields.One2many('of.planning.intervention', 'sav_id', u'Interventions liées', readonly=False)\n # Migration 'show_partner_shop' : fields_oldapi.function(_get_show_partner_shop, type=\"boolean\", string=\"Magasin différent\"),\n of_partner_id_ref = fields.Char(u'Réf. contact', related='partner_id.ref', readonly=True)\n of_partner_id_address = fields.Char('Adresse', related='partner_id.contact_address', readonly=True)\n of_partner_id_phone = fields.Char(u'Téléphone', related='partner_id.phone', readonly=True)\n of_partner_id_mobile = fields.Char(u'Mobile', related='partner_id.mobile', readonly=True)\n of_partner_id_function = fields.Char(u'Fonction', related='partner_id.function', readonly=True)\n\n\n _defaults = {\n 'date' : lambda *a: time.strftime('%Y-%m-%d %H:%M:00'),\n # Migration 'show_partner_shop' : False,\n }\n\n _order = \"date desc\"\n\n @api.onchange('project_id')\n def _on_change_project_id(self):\n if not self.project_id:\n partner_id = self.partner_id\n email_from = self.email_from\n super(ProjectIssue, self)._onchange_project_id()\n self.partner_id = partner_id\n self.email_from = email_from\n else:\n super(ProjectIssue, self)._onchange_project_id()\n\n\n # Quand on clique sur le bouton \"Ouvrir\" dans la liste des SAV pour aller sur le SAV\n @api.multi\n def button_open_of_sav(self):\n if self.ensure_one():\n return {\n 'name': 'SAV',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'project.issue',\n 'res_id': self._ids[0],\n 'type': 'ir.actions.act_window',\n }\n\n\n # Migration magasin non migré\n # @api.onchange('shop_id')\n # def onchange_shop_id(self, shop_id, partner_shop_id):\n # return {'value': {'show_partner_shop': shop_id != partner_shop_id}}\n\n # Migration ok\n @api.multi\n def liste_docs_partner(self):\n \"\"\" Renvoie la liste des documents (devis/commande, facture, commande fournisseur) liés à un partenaire\n Fonction appelée par onchange_partner_id et search de of_sav_docs\"\"\"\n self.ensure_one()\n partner_id = self.partner_id.id\n docs = []\n\n if partner_id:\n invoice_ids = self.env['account.invoice'].search([('partner_id', '=', partner_id)])\n sale_order_ids = self.env['sale.order'].search([('partner_id', '=', partner_id)])\n # Migration achats fournisseurs inhibés provisoirement car of_appro pas encore migré\n # Migration purchase_order_ids = self.env['purchase.order'].search(cr, uid, [('client_id', '=', partner_id)])\n if invoice_ids:\n for inv in invoice_ids:\n docs.append({\n 'name': 'Facture',\n 'doc_objet': 'account.invoice',\n 'date': inv.date_invoice or False,\n 'number': inv.number or '',\n 'partner_id': partner_id,\n 'user_id': inv.user_id and inv.user_id.id or False,\n 'date_due': inv.date_due or False,\n 'origin': inv.origin or '',\n 'residual': inv.residual or 0,\n 'amount_untaxed': inv.amount_untaxed or 0,\n 'amount_total': inv.amount_total or 0,\n 'state': inv.state,\n 'invoice_id': inv.id,\n })\n if sale_order_ids:\n for s_order in sale_order_ids:\n docs.append({\n 'name': 'Devis/Commande Client',\n 'doc_objet': 'sale.order',\n 'date': s_order.date_order or False,\n 'number': s_order.name or '',\n 'partner_id': partner_id,\n 'user_id': s_order.user_id and s_order.user_id.id or False,\n 'date_due': s_order.validity_date or False,\n 'origin': s_order.origin or '',\n 'amount_untaxed': s_order.amount_untaxed or 0,\n 'amount_total': s_order.amount_total or 0,\n 'state': s_order.state,\n 'sale_order_id': s_order.id,\n })\n # Migration achats fournisseurs inhibés provisoirement car of_appro pas encore migré\n # if purchase_order_ids:\n # for p_order in self.env['purchase.order'].browse(cr, uid, purchase_order_ids):\n # docs.append({\n # 'name': 'Commande Fournisseur',\n # 'doc_objet': 'purchase.order',\n # 'date': p_order.date_order or False,\n # 'number': p_order.name or '',\n # 'partner_id': p_order.partner_id.id,\n # 'user_id': p_order.validator and p_order.validator.id or False,\n # 'date_due': p_order.date_approve or False,\n # 'origin': p_order.origin or '',\n # 'amount_untaxed': p_order.amount_untaxed or 0,\n # 'amount_total': p_order.amount_total or 0,\n # 'state': p_order.state,\n # 'purchase_order_id': p_order.id,\n # })\n docs.sort(key=lambda k: k['date'], reverse=True) # Trie des résultats en fonction de la date\n return docs\n\n\n @api.onchange('partner_id')\n def _onchange_partner_id(self):\n # Pour actualiser l'adresse et la liste des documents liés au partenaire\n super(ProjectIssue, self)._onchange_partner_id()\n docs = [(5, )]\n for i in self.liste_docs_partner(): # On récupère la liste des documents liés au partenaire (factures, ...)\n docs.append((0, 0, i))\n\n self.doc_ids = docs\n\n # Migration of_magasin pas encore migré\n # if partner_id:\n # partner = self.pool['res.partner'].browse(cr, uid, partner_id)\n # partner_maga_id = partner.partner_maga and partner.partner_maga.id or False\n # res['value'].update({\n # 'shop_id' : partner_maga_id,\n # 'partner_shop_id' : partner_maga_id,\n # 'show_partner_shop': False,\n # })\n\n @api.multi\n def action_creer_rdv(self):\n res = {\n 'name': 'Rendez-vous',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'of.planning.intervention',\n 'type': 'ir.actions.act_window',\n 'target': 'current',\n }\n if 'active_ids' in self._context.keys():\n active_ids = isinstance(self._context['active_ids'], (int,long)) and [self._context['active_ids']] or self._context['active_ids']\n if active_ids:\n project_issue = self.browse(active_ids[0])\n res['context'] = {'default_sav_id': project_issue.id}\n if project_issue.partner_id:\n res['context']['default_partner_id'] = project_issue.partner_id.id\n return res\n\n\n @api.model\n def open_purchase_order(self):\n res = {\n 'name': 'Demande de prix',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'purchase.order',\n 'type': 'ir.actions.act_window',\n 'target': 'current',\n }\n if 'active_ids' in self._context.keys():\n active_ids = isinstance(self._context['active_ids'], (int,long)) and [self._context['active_ids']] or self._context['active_ids']\n if active_ids:\n project_issue = self.browse(active_ids[0])\n if project_issue.partner_id:\n res['context'] = {'client_id' : project_issue.partner_id.id,\n 'default_origin': project_issue.of_code}\n else:\n res['context'] = {'default_origin': project_issue.of_code}\n return res\n\n @api.model\n def open_sale_order(self):\n res = {\n 'name': 'Devis',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'sale.order',\n 'type': 'ir.actions.act_window',\n 'target': 'current',\n }\n if 'active_ids' in self._context.keys():\n active_ids = isinstance(self._context['active_ids'], (int,long)) and [self._context['active_ids']] or self._context['active_ids']\n if active_ids:\n project_issue = self.browse(active_ids[0])\n if project_issue.partner_id:\n res['context'] = {'default_partner_id': project_issue.partner_id.id,\n 'default_origin' : project_issue.of_code}\n else:\n res['context'] = {'default_origin': project_issue.of_code}\n return res\n\n @api.model\n def create(self, vals):\n if vals.get('of_code', 'Nouveau') == 'Nouveau':\n vals['of_code'] = self.env['ir.sequence'].next_by_code('of.project.issue') or 'New'\n return super(ProjectIssue, self).create(vals)\n\n\n @api.one\n @api.returns('self', lambda value: value.id)\n def copy(self, default=None):\n if not default:\n default = {}\n default.update({\n 'of_code': self.env['ir.sequence'].get('of.project.issue'),\n })\n return super(ProjectIssue, self).copy(default)\n\n @api.model\n def remind_partner(self, attach=False):\n # Appelée par bouton \"Envoyer un rappel\" courriel responsable\n return self.remind_user(attach, destination=False)\n\n @api.multi\n def remind_user(self, attach=False, destination=True):\n # Appelée par bouton \"Envoyer un rappel\" courriel client\n for case in self:\n if not destination and not case.email_from:\n raise UserError(\"Erreur ! (#SAV105)\\n\\nL'adresse courriel SAV du client n'est pas renseignée.\")\n if not case.user_id.user_email:\n raise UserError(\"Erreur ! (#SAV110)\\n\\nL'adresse courriel du responsable n'est pas renseignée.\")\n if destination:\n case_email = self.env.user.user_email\n if not case_email:\n case_email = case.user_id.user_email\n else:\n case_email = case.user_id.user_email\n src = case_email\n dest = case.user_id.user_email or \"\"\n body = case.description or \"\"\n for message in case.message_ids:\n if message.email_from and message.body_text:\n body = message.body_text\n break\n\n if not destination:\n src, dest = dest, case.email_from\n if body and case.user_id.signature:\n if body:\n body += '\\n\\n%s' % (case.user_id.signature)\n else:\n body = '\\n\\n%s' % (case.user_id.signature)\n\n body = self.format_body(body)\n\n attach_to_send = {}\n\n if attach:\n attach_ids = self.env['ir.attachment'].search([('res_model', '=', self._name), ('res_id', '=', case.id)])\n attach_to_send = self.env['ir.attachment'].read(attach_ids, ['datas_fname', 'datas'])\n attach_to_send = dict(map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send))\n\n # Send an email\n subject = \"Rappel SAV [%s] %s\" % (case.of_code, case.name)\n\n return {\n 'name': \"Courriel SAV\",\n 'view_mode': 'form',\n 'view_id': False,\n 'view_type': 'form',\n 'res_model': 'of.project.issue.mail.wizard',\n 'type': 'ir.actions.act_window',\n 'nodestroy': True,\n 'target': 'new',\n 'domain': '[]',\n 'context': {\n 'src': src,\n 'dest': dest,\n 'subject': subject,\n 'body': body,\n 'model': self._name,\n 'reply_to': case.section_id.reply_to,\n 'res_id': case.id,\n 'attachments': attach_to_send,\n 'context': self._context\n }\n }\n\n# Migration\n# class of_project_issue_mail_wizard(osv.TransientModel):\n# \"\"\"\n# Interface envoi rappel courriel depuis SAV\n# \"\"\"\n# _name = 'of.project.issue.mail.wizard'\n# _description = \"Interface envoi rappel courriel depuis SAV\"\n#\n# _columns={\n# 'src': fields_oldapi.char('De', size=128, required=True),\n# 'dest': fields_oldapi.char('À', size=128, required=True),\n# 'subject': fields_oldapi.text('Sujet', required=True),\n# 'body': fields_oldapi.text('Contenu', required=True),\n# 'model': fields_oldapi.char('Model', size=64, required=False),\n# 'reply_to': fields_oldapi.char('Répondre à', size=128, required=False),\n# 'res_id': fields_oldapi.integer(\"res_id\"),\n# 'context': fields_oldapi.text('Contexte', required=False)\n# }\n# \n# def default_get(self, cr, uid, fields_list=None, context=None):\n# \"\"\" Remplie les champs de l'interface courriel avec les valeurs par défaut\"\"\" \n# if not context:\n# return False\n# result = {'src': context.get('src', []),\n# 'dest': context.get('dest', []),\n# 'subject': context.get('subject', []),\n# 'body': context.get('body', []),\n# 'model': context.get('model', []),\n# 'reply_to': context.get('reply_to', []),\n# 'res_id': context.get('res_id', []),\n# }\n# result.update(super(of_project_issue_mail_wizard, self).default_get(cr, uid, fields_list, context=context))\n# return result\n# \n# def envoyer_courriel(self, cr, uid, ids, context=None):\n# # On récupère les données du wizard\n# wizard = self.browse(cr, uid, ids[0], context=context)\n# src = wizard.src\n# dest = wizard.dest\n# subject = wizard.subject\n# body = wizard.body\n# model = wizard.model\n# reply_to = wizard.reply_to\n# res_id = wizard.res_id\n# attachments = {}\n# \n# if not src or not dest or not subject or not body or not model or not res_id:\n# return False\n# \n# body = self.pool['base.action.rule'].format_body(body)\n# \n# mail_message = self.pool['mail.message']\n# mail_message.schedule_with_attach(cr, uid,\n# src,\n# [dest],\n# subject,\n# body,\n# model=model,\n# reply_to=reply_to,\n# res_id=res_id,\n# attachments=attachments,\n# context=context\n# )\n# return {'type': 'ir.actions.act_window_close'} \n\n\n\n# Migration 9 plus crm_case_categ\n# class crm_case_categ(osv.Model):\n# \"\"\" Category of Case \"\"\"\n# _name = \"crm.case.categ\"\n# _inherit = \"crm.case.categ\"\n# \n# # Migration ok\n# def name_get(self, cr, uid, ids, context=None):\n# if not len(ids):\n# return []\n# reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)\n# res = []\n# for record in reads:\n# name = record['name']\n# if record['parent_id']:\n# name = record['parent_id'][1]+' / '+name\n# res.append((record['id'], name))\n# return res\n# \n# # Migration ok\n# def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):\n# res = self.name_get(cr, uid, ids, context=context)\n# return dict(res)\n# \n# _columns = {\n# 'complete_name': fields_oldapi.function(_name_get_fnc, type=\"char\", string='Catégorie'),\n# 'parent_id': fields_oldapi.many2one('crm.case.categ', u'Cat\\u00E9gorie parent', select=True, ondelete='cascade'),\n# 'child_id': fields_oldapi.one2many('crm.case.categ', 'parent_id', string=u'Cat\\u00E9gories enfants'),\n# 'parent_left': fields_oldapi.integer('Parent gauche', select=1),\n# 'parent_right': fields_oldapi.integer(u'Parent droit', select=1),\n# }\n# \n# _constraints = [\n# (osv.Model._check_recursion, u'Erreur ! Vous ne pouvez pas cr\\u00E9er de cat\\u00E9gories r\\u00E9cursives', ['parent_id'])\n# ]\n# \n# _parent_name = \"parent_id\"\n# _parent_store = True\n# _parent_order = 'name'\n# _order = 'parent_left'\n# \n# # Migration ok\n# def _get_children(self, cr, uid, ids, context=None):\n# \"\"\" Retourne la liste des ids ainsi que leurs enfants et petits-enfants en respectant self._order\n# \"\"\"\n# domain = ['|' for _ in xrange(len(ids)-1)]\n# for categ in self.read(cr, uid, ids, ['parent_left','parent_right'], context=context):\n# domain += ['&',('parent_left','>=',categ['parent_left']),('parent_right','<=',categ['parent_right'])]\n# return self.search(cr, uid, domain, context=context)\n# \n# # Migration ok\n# def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):\n# if args is None:\n# args = []\n# if context is None:\n# context = {}\n# args = args[:]\n# # optimize out the default criterion of ``ilike ''`` that matches everything\n# if not (name == '' and operator == 'ilike'):\n# args += [(self._rec_name, operator, name)]\n# access_rights_uid = name_get_uid or user\n# ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)\n# ids = self._get_children(cr, user, ids, context=None)\n# res = self.name_get(cr, access_rights_uid, ids, context)\n# return res\n\n\n# Catégorie de SAV\nclass OfProjectIssueCategorie(models.Model):\n _name = \"of.project.issue.categorie\"\n\n name = fields.Char(u'Catégorie', size=32)\n parent_id = fields.Many2one('of.project.issue.categorie', 'Catégorie parente', select=True, ondelete='restrict')\n pparent_id = fields.Many2one('of.project.issue.categorie', string='Catégorie mère', readonly=True)\n sequence = fields.Integer(u'Séquence', help=u\"Ordre d'affichage (plus petit en premier)\")\n parent_left = fields.Integer('Left Parent', select=1)\n parent_right = fields.Integer('Right Parent', select=1)\n\n _constraints = [\n (models.Model._check_recursion, 'Error ! You can not create recursive category.', ['parent_id'])\n ]\n\n _defaults = {\n 'sequence' : 10\n }\n\n _parent_name = \"parent_id\"\n _parent_store = True\n _parent_order = 'sequence, name'\n _order = 'parent_left'\n\n # Pour afficher la hiérarchie des catégories\n @api.multi\n def name_get(self):\n if not self._ids:\n return []\n res = []\n for record in self:\n name = [record.name]\n parent = record.parent_id\n while parent:\n name.append(parent.name)\n parent = parent.parent_id\n name = ' / '.join(name[::-1])\n res.append((record.id, name))\n return res\n\n @api.multi\n def _get_children(self):\n \"\"\" Retourne la liste des ids ainsi que leurs enfants et petits-enfants en respectant self._order\n \"\"\"\n domain = ['|' for _ in xrange(len(self.ids)-1)]\n for categ in self.read(['parent_left','parent_right']):\n domain += ['&',('parent_left','>=',categ['parent_left']),('parent_right','<=',categ['parent_right'])]\n return self.search(domain)\n\n @api.model\n def name_search(self, name, args=None, operator='ilike', limit=100):\n \"\"\"Pour inclure la recherche sur le nom des parents\"\"\"\n args = list(args or [])\n negation = operator in expression.NEGATIVE_TERM_OPERATORS\n if negation:\n operator = expression.TERM_OPERATORS_NEGATION[operator]\n if not (name == '' and operator == 'ilike'):\n args += [(self._rec_name, operator, name)]\n categs = self.search(args)\n categs = categs._get_children()\n if negation:\n categs = self.search([('id', 'not in', categs._ids)], limit=limit)\n else:\n categs = categs[:limit]\n res = categs.name_get()\n return res\n\n @api.model\n def create(self, vals):\n res = super(OfProjectIssueCategorie, self).create(vals)\n res.pparent_id = res.parent_id and res.parent_id.pparent_id or res\n return res\n\n @api.multi\n def write(self, vals):\n res = super(OfProjectIssueCategorie, self).write(vals)\n\n if 'parent_id' in vals:\n for categ in self:\n parent = categ\n while parent.parent_id:\n parent = parent.parent_id\n\n categs = self.search([('parent_left', '>=', categ.parent_left), ('parent_left', '<', categ.parent_right)])\n categs.write({'pparent_id': parent.id})\n return res\n\n# Canal SAV\nclass of_project_issue_canal(models.Model):\n _name = \"of.project.issue.canal\"\n \n name = fields.Char(u'Catégorie', size=32)\n\n\n\nclass of_sav_docs(models.TransientModel):\n\n _name = 'of.sav.docs'\n _description = 'Liste des documents'\n\n name = fields.Char('Type du document', size=16)\n doc_objet = fields.Char('Objet du document', size=32)\n date = fields.Date('Date')\n number = fields.Char(u'Numéro', size=64)\n partner_id = fields.Many2one('res.partner', 'Partner')\n user_id = fields.Many2one('res.users', 'Responsable')\n date_due = fields.Date(u\"Date d'échéance\")\n origin = fields.Char(\"Document d'origine\", size=64)\n residual = fields.Float('Balance', digits=(16, 2))\n amount_untaxed = fields.Float('HT', digits=(16, 2))\n amount_total = fields.Float('Total', digits=(16, 2))\n state = fields.Char('État', size=64)\n project_issue_id = fields.Many2one('project.issue', 'SAV')\n invoice_id = fields.Many2one('account.invoice', 'Facture')\n sale_order_id = fields.Many2one('sale.order', 'Devis/Commande Client')\n purchase_order_id = fields.Many2one('purchase.order', 'Commande Fournisseur')\n\n @api.model\n def search(self, args, offset=0, limit=None, order=None, count=False):\n # On détourne la fonction search pour peupler la liste de documents (onglet infos supplémentaires) à l'amorce de l'affichage de la vue\n res = super(of_sav_docs, self).search(args=args, offset=offset, limit=limit, order=order, count=count)\n if args and len(args) == 1 and len(args[0]) == 3 and args[0][0] == \"project_issue_id\":\n # Si la liste des docs a été mise à jour il y a moins de 15 s, c'est un appel répétitif, on ne génère pas une nouvelle liste\n if res:\n self._cr.execute(\"Select (extract(epoch from now() at time zone 'UTC') - extract(epoch from create_date)) FROM of_sav_docs WHERE id = %s limit 1\", (res[0].id,))\n if self._cr.fetchone()[0] < 15:\n return res\n\n # On extrait l'id du SAV dans la requête du search\n if isinstance(args[0][2], list):\n sav_id = args[0][2][0]\n else:\n sav_id = args[0][2]\n # On supprime les enregistrements existants\n if sav_id:\n if res:\n res.unlink()\n obj_sav = self.env['project.issue']\n sav = obj_sav.browse(sav_id)\n if sav.partner_id:\n # On récupère la liste des documents liés au partenaire (factures, ...)\n res_ids = []\n for i in sav.liste_docs_partner():\n i.update({'project_issue_id': sav_id})\n res_ids.append(self.create(i).id)\n res = self.browse(res_ids)\n return res\n\n # Quand on clique sur le bouton \"Ouvrir\" de la liste des documents dans la vue SAV\n @api.multi\n def button_open_of_sav(self):\n if self._ids:\n res_model = self.doc_objet\n if res_model == 'account.invoice':\n name = 'Factures Clients'\n res_id = self.invoice_id.id\n elif res_model == 'sale.order':\n name = 'Devis / Commandes Clients'\n res_id = self.sale_order_id.id\n elif res_model == 'purchase.order':\n name = 'Demande de prix / Commandes Fournisseurs'\n res_id = self.purchase_order_id.id\n\n return {\n 'name': name,\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': res_model,\n 'res_id': res_id,\n 'type': 'ir.actions.act_window',\n 'target': 'new',\n }\n\n# Ajout historique SAV dans vue partenaires\nclass ResPartner(models.Model):\n _inherit = 'res.partner'\n\n @api.multi\n @api.depends('child_ids.project_issue_ids')\n def _compute_project_issue_ids(self):\n \"\"\"Pour afficher les SAV de tous les enfants du partenaire dans l'historique\"\"\"\n issue_obj = self.env['project.issue']\n for partner in self:\n partners = [partner]\n\n ind = 0\n while ind < len(partners):\n partners += partners[ind].child_ids\n ind += 1\n partner_ids = [p.id for p in partners]\n partner.project_issue_ids = issue_obj.search([('partner_id','in',partner_ids)])\n\n project_issue_ids = fields.One2many('project.issue', compute='_compute_project_issue_ids', string='SAV')\n\n\n# Migration\n# def _get_courriels(self, cr, uid, ids, *args):\n# result = {}\n# for part in self.browse(cr, uid, ids):\n# email = ''\n# if part.supplier:\n# emails = []\n# for adr in part.address:\n# email = adr.email\n# if email and email not in emails:\n# emails.append(email)\n# email = ' || '.join(emails)\n# result[part.id] = email\n# return result\n# \n# _columns = {\n# 'courriels': fields_oldapi.function(_get_courriels, string=\"Courriels\", type='char', size=256),\n# }\n\n\nclass OfPlanningIntervention(models.Model):\n _name = \"of.planning.intervention\"\n _inherit = \"of.planning.intervention\"\n\n sav_id = fields.Many2one('project.issue', string='SAV', readonly=False)\n","sub_path":"of_project_issue/models/of_project_issue.py","file_name":"of_project_issue.py","file_ext":"py","file_size_in_byte":34731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"177212712","text":"import numpy as np\nimport math\nimport re\nimport mysql.connector\nfrom multi_elo import EloPlayer, calc_elo\n\n# Connects to database\ndb = mysql.connector.connect(host=\"HOST\", user=\"USER\", password=\"PASSWORD\", database=\"DATABASE\")\n\nmycursor = db.cursor()\n\nmycursor.execute(\"SELECT * FROM players\")\ndb_result = mycursor.fetchall()\n\nplayer_dic = {}\n\ndef get_db():\n global player_dic\n mycursor.execute(\"SELECT * FROM players\")\n db_result = mycursor.fetchall()\n\n player_dic = {\n \"PLAYER 1\": re.sub('\\D', '', str(db_result[0])),\n \"PLAYER 2\": re.sub('\\D', '', str(db_result[1])),\n \"PLAYER 3\": re.sub('\\D', '', str(db_result[2])),\n \"PLAYER 4\": re.sub('\\D', '', str(db_result[3])),\n \"PLAYER 5\": re.sub('\\D', '', str(db_result[4])),\n \"PLAYER 6\": re.sub('\\D', '', str(db_result[5]))\n }\n\ndef reset_elo():\n print(\"You are trying to delete all scores, are you sure?\")\n print(\"Type YES to confirm\")\n if input() == \"YES\":\n sql = \"UPDATE players SET Rating = 1000\"\n mycursor.execute(sql)\n db.commit()\n print(\"Scoreboard reset\")\n else:\n print(\"Aborted\")\n\ndef get_scoreboard():\n mycursor.execute(\"SELECT * FROM players\")\n db_result = mycursor.fetchall()\n print(db_result)\n\ndef calc_game_2p(p1_place, p1_r, p2_place, p2_r, name1, name2):\n elo_players = [EloPlayer(p1_place, p1_r), EloPlayer(p2_place, p2_r)]\n new_elos = calc_elo(elo_players)\n\n sql1 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[0], name1)\n sql2 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[1], name2)\n\n mycursor.execute(sql1)\n mycursor.execute(sql2)\n db.commit()\n\n print(new_elos)\n \n\ndef calc_game_3p(p1_place, p1_r, p2_place, p2_r, p3_place, p3_r, name1, name2, name3):\n elo_players = [EloPlayer(p1_place, p1_r), EloPlayer(p2_place, p2_r), EloPlayer(p3_place, p3_r)]\n new_elos = calc_elo(elo_players)\n\n sql1 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[0], name1)\n sql2 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[1], name2)\n sql3 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[2], name3)\n\n mycursor.execute(sql1)\n mycursor.execute(sql2)\n mycursor.execute(sql3)\n db.commit()\n\n print(new_elos)\n\ndef calc_game_4p(p1_place, p1_r, p2_place, p2_r, p3_place, p3_r, p4_place, p4_r, name1, name2, name3, name4):\n elo_players = [EloPlayer(p1_place, p1_r), EloPlayer(p2_place, p2_r), EloPlayer(p3_place, p3_r), EloPlayer(p4_place, p4_r)]\n new_elos = calc_elo(elo_players)\n \n sql1 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[0], name1)\n sql2 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[1], name2)\n sql3 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[2], name3)\n sql4 = \"UPDATE players SET Rating = %d WHERE Name = '%s'\" % (new_elos[3], name4)\n\n mycursor.execute(sql1)\n mycursor.execute(sql2)\n mycursor.execute(sql3)\n mycursor.execute(sql4)\n db.commit()\n\n print(new_elos)\n\ndef game_2p():\n get_db()\n\n print(\"Who's player 1?, and what place did they come?\")\n p1 = input()\n print(\"Who's player 2?, and what place did they come?\")\n p2 = input()\n\n p1_name = str(p1[:len(p1)-2])\n p2_name = str(p2[:len(p2)-2])\n\n calc_game_2p(\n int(p1[-1]), int(player_dic[p1_name]),\n int(p2[-1]), int(player_dic[p2_name]),\n p1_name, p2_name\n )\n\ndef game_3p():\n get_db()\n\n print(\"Who's player 1?, and what place did they come?\")\n p1 = input()\n print(\"Who's player 2?, and what place did they come?\")\n p2 = input()\n print(\"Who's player 3?, and what place did they come?\")\n p3 = input()\n\n p1_name = str(p1[:len(p1)-2])\n p2_name = str(p2[:len(p2)-2])\n p3_name = str(p3[:len(p3)-2])\n\n calc_game_3p(\n int(p1[-1]), int(player_dic[p1_name]),\n int(p2[-1]), int(player_dic[p2_name]),\n int(p3[-1]), int(player_dic[p3_name]),\n p1_name, p2_name, p3_name\n )\n\n\ndef game_4p():\n get_db()\n\n print(\"Who's player 1?, and what place did they come?\")\n p1 = input()\n print(\"Who's player 2?, and what place did they come?\")\n p2 = input()\n print(\"Who's player 3?, and what place did they come?\")\n p3 = input()\n print(\"Who's player 4?, and what place did they come?\")\n p4 = input()\n\n\n p1_name = str(p1[:len(p1)-2])\n p2_name = str(p2[:len(p2)-2])\n p3_name = str(p3[:len(p3)-2])\n p4_name = str(p4[:len(p4)-2])\n\n calc_game_4p(\n int(p1[-1]), int(player_dic[p1_name]),\n int(p2[-1]), int(player_dic[p2_name]),\n int(p3[-1]), int(player_dic[p3_name]),\n int(p4[-1]), int(player_dic[p4_name]),\n p1_name, p2_name, p3_name, p4_name\n )\n\nwhile 1:\n command = input(\" Mario Kart WII elo calculator\\nCommands:\\n [scoreboard] Displays the current scoreboard\\n [reset] Resets every players elo-rating to 1000\\n [end] Ends the program\\n [2p] Log 2-player game\\n [3p] Log 3-player game\\n [4p] Log 4-player game\\nEnter your command: \")\n if command == \"end\":\n db.close()\n break\n if command == \"scoreboard\":\n get_scoreboard()\n if command == \"reset\":\n reset_elo()\n if command == \"2p\":\n game_2p()\n if command == \"3p\":\n game_3p()\n if command == \"4p\":\n game_4p()\n\n\n ","sub_path":"elo_sql.py","file_name":"elo_sql.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"62317526","text":"from app1.models import *\nfrom app1.util.utils import *\n\ndef delAdvance(request):\n '''\n get:\n http://127.0.0.1:8000/app1/delAdvance?ano=007\n 调用参数:\n ano:预排课表编号\n post:\n http://127.0.0.1:8000/app1/delAdvance\n '''\n try:\n if(request.method=='POST'):\n teadata=json.loads(request.body)\n data=teadata[\"data\"]\n # aid=request.GET.get(\"ano\")\n\n aid=data[\"ano\"]\n\n result=Advance.objects.filter(ano=aid).delete()\n\n result=Advance.objects.all().values()\n return showJsonresult(result)\n except Exception as e:\n response={}\n response['msg']=str(e)\n response['err_num']=1\n return showJsonerror(response)","sub_path":"day12/Django/app1/dateview/delAdvance.py","file_name":"delAdvance.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"604189231","text":"# _*_ coding: utf-8 _*_\nimport datetime\nfrom functools import wraps\n\nimport os\nfrom werkzeug.utils import secure_filename\n\n__author__ = 'mtianyan'\n__date__ = '2017/8/26 17:07'\n\nimport uuid\nfrom werkzeug.security import generate_password_hash\nfrom app import db, app\nfrom home.forms import RegistForm, LoginForm, UserdetailForm\nfrom app.models import User, Userlog\nfrom . import home\nfrom flask import render_template, url_for, redirect, flash, session, request\n\n\ndef change_filename(filename):\n \"\"\"\n 修改文件名称\n \"\"\"\n fileinfo = os.path.splitext(filename)\n filename = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\") + str(uuid.uuid4().hex) + fileinfo[-1]\n return filename\n\n\ndef user_login_req(f):\n \"\"\"\n 登录装饰器\n \"\"\"\n\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if \"user\" not in session:\n return redirect(url_for(\"home.login\", next=request.url))\n return f(*args, **kwargs)\n\n return decorated_function\n\n\n@home.route(\"/login/\", methods=[\"GET\", \"POST\"])\ndef login():\n \"\"\"\n 登录\n \"\"\"\n form = LoginForm()\n if form.validate_on_submit():\n data = form.data\n user = User.query.filter_by(name=data[\"name\"]).first()\n if not user.check_pwd(data[\"pwd\"]):\n flash(\"密码错误!\", \"err\")\n return redirect(url_for(\"home.login\"))\n session[\"user\"] = user.name\n session[\"user_id\"] = user.id\n userlog = Userlog(\n user_id=user.id,\n ip=request.remote_addr\n )\n db.session.add(userlog)\n db.session.commit()\n return redirect(url_for(\"home.user\"))\n return render_template(\"home/login.html\", form=form)\n\n\n@home.route(\"/logout/\")\ndef logout():\n \"\"\"\n 退出登录\n \"\"\"\n # 重定向到home模块下的登录。\n session.pop(\"user\", None)\n session.pop(\"user_id\", None)\n return redirect(url_for('home.login'))\n\n\n@home.route(\"/register/\", methods=[\"GET\", \"POST\"])\ndef register():\n \"\"\"\n 会员注册\n \"\"\"\n form = RegistForm()\n if form.validate_on_submit():\n data = form.data\n user = User(\n name=data[\"name\"],\n email=data[\"email\"],\n phone=data[\"phone\"],\n pwd=generate_password_hash(data[\"pwd\"]),\n uuid=uuid.uuid4().hex\n )\n db.session.add(user)\n db.session.commit()\n flash(\"注册成功!\", \"ok\")\n return render_template(\"home/register.html\", form=form)\n\n\n@home.route(\"/user/\", methods=[\"GET\", \"POST\"])\n@user_login_req\ndef user():\n form = UserdetailForm()\n user = User.query.get(int(session[\"user_id\"]))\n form.face.validators = []\n if request.method == \"GET\":\n # 赋初值\n form.name.data = user.name\n form.email.data = user.email\n form.phone.data = user.phone\n form.info.data = user.info\n if form.validate_on_submit():\n data = form.data\n if form.face.data != \"\":\n file_face = secure_filename(form.face.data.filename)\n if not os.path.exists(app.config[\"FC_DIR\"]):\n os.makedirs(app.config[\"FC_DIR\"])\n os.chmod(app.config[\"FC_DIR\"])\n user.face = change_filename(file_face)\n form.face.data.save(app.config[\"FC_DIR\"] + user.face)\n\n name_count = User.query.filter_by(name=data[\"name\"]).count()\n if data[\"name\"] != user.name and name_count == 1:\n flash(\"昵称已经存在!\", \"err\")\n return redirect(url_for(\"home.user\"))\n\n email_count = User.query.filter_by(email=data[\"email\"]).count()\n if data[\"email\"] != user.email and email_count == 1:\n flash(\"邮箱已经存在!\", \"err\")\n return redirect(url_for(\"home.user\"))\n\n phone_count = User.query.filter_by(phone=data[\"phone\"]).count()\n if data[\"phone\"] != user.phone and phone_count == 1:\n flash(\"手机已经存在!\", \"err\")\n return redirect(url_for(\"home.user\"))\n\n # 保存\n user.name = data[\"name\"]\n user.email = data[\"email\"]\n user.phone = data[\"phone\"]\n user.info = data[\"info\"]\n db.session.add(user)\n db.session.commit()\n flash(\"修改成功!\", \"ok\")\n return redirect(url_for(\"home.user\"))\n return render_template(\"home/user.html\", form=form, user=user)\n\n\n@home.route(\"/pwd/\")\n@user_login_req\ndef pwd():\n \"\"\"\n 修改密码\n \"\"\"\n return render_template(\"home/pwd.html\")\n\n\n@home.route(\"/comments/\")\n@user_login_req\ndef comments():\n \"\"\"\n 评论记录\n \"\"\"\n return render_template(\"home/comments.html\")\n\n\n@home.route(\"/loginlog/\")\n@user_login_req\ndef loginlog():\n \"\"\"\n 登录日志\n \"\"\"\n return render_template(\"home/loginlog.html\")\n\n\n@home.route(\"/moviecol/\")\n@user_login_req\ndef moviecol():\n \"\"\"\n 收藏电影\n \"\"\"\n return render_template(\"home/moviecol.html\")\n#\n\n\n@home.route(\"/\")\ndef index():\n \"\"\"\n 首页电影列表\n \"\"\"\n return render_template(\"home/index.html\")\n\n\n@home.route(\"/animation/\")\ndef animation():\n \"\"\"\n 首页轮播动画\n \"\"\"\n return render_template(\"home/animation.html\")\n\n\n@home.route(\"/search/\")\ndef search():\n \"\"\"\n 搜索\n \"\"\"\n return render_template(\"home/search.html\")\n\n\n@home.route(\"/play/\")\ndef play():\n \"\"\"\n 播放\n \"\"\"\n return render_template(\"home/play.html\")\n\n\n","sub_path":"app/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"550635771","text":"# Copyright 2008-2013 the original author or authors\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\nimport re\n\n\ndef get_regex_for_routing_key(routing_key):\n regex = ['^']\n parts = routing_key.split(\".\")\n while parts:\n part = parts.pop(0)\n if part == '#':\n regex.append('[^.]+(\\.[^.]+)*')\n elif part == '*':\n regex.append(r'[^.]+')\n else:\n regex.append(re.escape(part))\n regex.append(r'\\.')\n regex[-1:] = [r'$']\n return re.compile(''.join(regex))\n\n\ndef get_regex_for_routing_keys(routing_keys):\n return [get_regex_for_routing_key(rk) for rk in routing_keys]\n\n\ndef match(routing_keys, msg):\n for expr in get_regex_for_routing_keys(routing_keys):\n if expr.match(msg):\n return True\n return False\n","sub_path":"pubbot/main/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"269312445","text":"import pygame # 动态模块.dll.pyd 静态模块:.py 静态的必须导入模块名.\nimport sys\nfrom pygame.locals import *\nimport time\nimport random\n\n\"\"\"\n1.创建窗口\n2.加载背景图片\n3.贴图\n4.刷新\n\n子弹的y = 英雄飞机的y - 子弹的高度\n子弹的x = 英雄飞机的x + 英雄飞机宽的一半 - 子弹宽的一半\n\"\"\"\n\n\nclass Bullet:\n\t\"\"\"子弹类\"\"\"\n\n\tdef __init__(self, img_path, x, y, window):\n\t\tself.img = pygame.image.load(img_path) # 子弹图片\n\t\tself.x = x # 记录子弹位置\n\t\tself.y = y\n\t\tself.window = window # 将来子弹所在的窗口\n\n\tdef display(self):\n\t\t\"\"\"显示子弹\"\"\"\n\t\tself.window.blit(self.img, (self.x, self.y))\n\n\tdef move(self):\n\t\t\"\"\"子弹移动\"\"\"\n\t\tprint('bullet move up')\n\t\tself.y -= 10\n\n\tdef __del__(self):\n\t\t\"\"\"验证子弹是否销毁\"\"\"\n\t\tprint('子弹销毁了')\n\n\nclass BasePlane:\n\t\"\"\"飞机基类\"\"\"\n\n\tdef __init__(self, img_path, x, y, window):\n\t\tself.img = pygame.image.load(img_path) # 飞机图片\n\t\tself.x = x # 记录飞机位置\n\t\tself.y = y\n\t\tself.window = window # 将来飞机所在的窗口\n\n\tdef display(self):\n\t\t\"\"\"显示飞机\"\"\"\n\t\tself.window.blit(self.img, (self.x, self.y))\n\n\nclass EnemyPlane(BasePlane):\n\t\"\"\"敌机类\"\"\"\n\n\tdef move_down(self):\n\t\t\"\"\"敌机下移\"\"\"\n\t\tprint('down')\n\t\tself.y += 5\n\t\tif self.y >= 768:\n\t\t\tself.y = -68\n\t\t\tself.x = random.randint(0, 412)\n\t\t\tself.img = pygame.image.load('res/img-plane_%d.png' % random.randint(1, 7))\n\n\nclass HeroPlane(BasePlane):\n\t\"\"\"英雄飞机类\"\"\"\n\n\tdef __init__(self, img_path, x, y, window):\n\t\tsuper().__init__(img_path, x, y, window)\n\t\tself.bullets = [] # 保存所有子弹\n\n\tdef display(self):\n\t\t\"\"\"显示英雄飞机\"\"\"\n\t\tself.window.blit(self.img, (self.x, self.y))\n\n\tdef move_left(self):\n\t\t\"\"\"飞机左移\"\"\"\n\t\tprint('left')\n\t\tself.x -= 5\n\n\tdef move_right(self):\n\t\t\"\"\"飞机右移\"\"\"\n\t\tprint('right')\n\t\tself.x += 5\n\n\tdef fire(self):\n\t\t\"\"\"开火\"\"\"\n\t\t# 1.创建子弹对象\n\t\tprint('----')\n\t\tbullet = Bullet('res/bullet_14.png', self.x + 50, self.y - 56, self.window)\n\t\tself.bullets.append(bullet) # 添加到子弹列表\n\n\tdef display_bullet(self):\n\t\t\"\"\"处理子弹的显示问题\"\"\"\n\t\ttemp_list = [] # 记录要销毁的子弹\n\t\tfor bullet in self.bullets:\n\t\t\tif bullet.y > -56: # 没有飞出去,继续贴图\n\t\t\t\tbullet.display() # 重复贴子弹图\n\t\t\t\tbullet.move()\n\t\t\telse:\n\t\t\t\t# self.bullets.remove(bullet) # 飞出去销毁子弹\n\t\t\t\ttemp_list.append(bullet) # 把超出窗口的子弹回收\n\t\tfor del_bullet in temp_list:\n\t\t\tself.bullets.remove(del_bullet)\n\n\ndef main():\n\t# 1.创建窗口\n\twindow = pygame.display.set_mode((512, 768))\n\t# 2.加载背景图片\n\tbg_image = pygame.image.load('res/img_bg_level_1.jpg')\n\t# 2.1 创建英雄飞机实例对象\n\thero_plane = HeroPlane('res/hero2.png', 196, 500, window)\n\t# 创建敌机实例对象\n\tenemy_plane_list = []\n\n\tfor i in range(5):\n\t\tenemy_plane = EnemyPlane('res/img-plane_%d.png' % random.randint(1, 5), random.randint(0, 412),\n\t\t\t\t\t\t\t\t random.randint(-300, -68), window)\n\t\tenemy_plane_list.append(enemy_plane)\n\n\twhile True:\n\t\t# 3.把背景图片贴到窗口上\n\t\twindow.blit(bg_image, (0, 0))\n\t\t# 3.1把飞机图贴到窗口上 重复贴\n\t\thero_plane.display()\n\t\t# 调用子弹显示方法\n\t\thero_plane.display_bullet()\n\t\t# 3.3 贴敌机图\n\t\tfor enemy_plane in enemy_plane_list:\n\t\t\tenemy_plane.display()\n\t\t\tenemy_plane.move_down()\n\n\t\t# 4.刷新窗口,不刷没法显示以上效果\n\t\tpygame.display.update()\n\n\t\t# 获取新事件\n\t\tfor event in pygame.event.get():\n\t\t\t# 1. 鼠标点击关闭窗口事件\n\t\t\tif event.type == QUIT: # 判断是不是退出\n\t\t\t\tprint(\"点击关闭窗口按钮\")\n\t\t\t\tsys.exit() # 关闭程序\n\n\t\t\t# 2. 键盘按下事件 # 只是一个单按事件,单击事件\n\t\t\tif event.type == KEYDOWN:\n\t\t\t\t# 判断用户按键\n\t\t\t\tif event.key == K_SPACE:\n\t\t\t\t\tprint(\"space\")\n\t\t\t\t\thero_plane.fire() # 这里只会贴一次\n\n\t\t# 键盘长按事件\n\t\tpressed_keys = pygame.key.get_pressed()\n\t\tif pressed_keys[pygame.K_LEFT] or pressed_keys[pygame.K_a]:\n\t\t\thero_plane.fire()\n\t\t\thero_plane.move_left()\n\t\tif pressed_keys[pygame.K_RIGHT] or pressed_keys[pygame.K_d]:\n\t\t\thero_plane.fire()\n\t\t\thero_plane.move_right()\n\n\t\ttime.sleep(0.02) # 执行到这里的时候,程序会暂停0.02秒,为了让cpu缓一缓 提高效率cpu.\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"学习路线/1.python基础/day13/09-抽取飞机基类.py","file_name":"09-抽取飞机基类.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"369777560","text":"#作业:远程交互输入命令,并显示结果\nimport socket,struct\n\nphone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nphone.connect(('127.0.0.1',8080))\n\nwhile True: #通信循环\n #发消息\n cmd=input('>>:').strip()\n if not cmd:continue\n phone.send(bytes(cmd,encoding='utf-8'))\n\n #收报头\n baotou=phone.recv(4)\n data_size=struct.unpack('i',baotou)[0]\n\n #收消息\n recv_size=0\n recv_data=b''\n while recv_size < data_size:\n data=phone.recv(1024)\n recv_size+=len(data)\n recv_data+=data\n\n print(recv_data.decode('utf-8'))\n\n # print(data.decode('utf-8')) #若windows则用gbk解码\n\nphone.close()\n","sub_path":"py_fullstack_s4/day37/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"212913262","text":"import speedtest\nst = speedtest.Speedtest()\noption = int(input(''''what speed you want to test:\n 1) Download Speed\n 2) Upload Speed\n 3) Ping\n Your choice: '''))\nif option==1:\n print(st.download())\nelif option==2:\n print(st.upload())\nelif option==3:\n servernames= []\n st.get_servers(servernames)\n print(st.results.ping)\nelse:\n print(\"Pictureslease enter the valid choice\")\n","sub_path":"speedtest.py","file_name":"speedtest.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"263241794","text":"from tokenizer import Tokenizer\nimport numpy as np\n\nclass NaiveBayes(object):\n\tdef __init__(self):\n\t\tself.tokenizer = Tokenizer()\n\n\tdef loadData(self, filepath):\n\t\tf = open(filepath)\n\t\tmails = []\n\t\tcategories = []\n\t\tfor line in f.readlines():\n\t\t\tdatas = line.strip().split('\\t')\n\t\t\tif datas[0] == 'ham':\n\t\t\t\tcategories.append(0)\n\t\t\telif datas[0] == 'spam':\n\t\t\t\tcategories.append(1)\n\n\t\t\twords = self.tokenizer.tokenize(datas[1])\n\t\t\tmails.append(words)\n\t\treturn mails, categories\n\n\tdef createVocabularyList(self, mails):\n\t\tvocabularySet = set()\n\t\tfor words in mails:\n\t\t\tvocabularySet = vocabularySet | set(words)\n\t\tvocabularyList = list(vocabularySet)\n\t\treturn vocabularyList\n\n\tdef setMarkVector(self, vocabularyList, mails):\n\t\tmarkedList = []\n\t\tfor words in mails:\n\t\t\tmarked = [0] * len(vocabularyList)\n\t\t\tfor word in words:\n\t\t\t\tif word in vocabularyList:\n\t\t\t\t\tmarked[vocabularyList.index(word)] += 1\n\t\t\tmarkedList.append(marked)\n\t\treturn markedList\n\n\tdef train(self, markedArray, categories):\n\t\tnumTraining = len(markedArray)\n\t\tnumWords = len(markedArray[0])\n\n\t\tpSpam = sum(categories) / len(categories)\n\n\t\tspamWords = np.zeros(numWords)\n\t\thamWords = np.zeros(numWords)\n\t\tspamWordsNum = 0\n\t\thamWordsNum = 0\n\n\t\tfor i in range(numTraining):\n\t\t\tif categories[i] == 1:\n\t\t\t\tspamWords += markedArray[i]\n\t\t\t\tspamWordsNum += sum(markedArray[i])\n\t\t\telse:\n\t\t\t\thamWords += markedArray[i]\n\t\t\t\thamWordsNum += sum(markedArray[i])\n\t\tpSpamWords = spamWords / spamWordsNum\n\t\tpHamWords = hamWords / hamWordsNum\n\n\t\treturn pSpamWords, pHamWords, pSpam\n\n\tdef classify(self, vocabularyList, pSpamWords, pHamWords, pSpam, words):\n\t\tmarked = [0] * len(vocabularyList)\n\t\tfor word in words:\n\t\t\tif word in vocabularyList:\n\t\t\t\tmarked[vocabularyList.index(word)] += 1\n\t\tmarkedArray = np.array(marked)\n\t\tp1 = sum(markedArray * pSpamWords) * pSpam\n\t\tp0 = sum(markedArray * pHamWords) * (1 - pSpam)\n\t\treturn p1 > p0","sub_path":"naive_bayes/spam_filtering/naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"300048596","text":"from multiprocessing import Pool, Manager\nimport os\n\n\ndef copyFileTask(name, oldFolderName, newFolderName, q):\n q.put(name)\n\n fr = open(oldFolderName + \"/\" + name)\n fw = open(newFolderName + \"/\" + name, \"w\")\n\n content = fr.read()\n fw.write(content)\n\n fw.close()\n fr.close()\n\n\ndef main():\n # 0.获取永远要copy的文件夹的名字\n oldFolderName = input(\"请输入文件夹的名字:\")\n\n # 1.创建一个文件夹\n newFolderName = oldFolderName + \"-复件\"\n os.mkdir(newFolderName)\n\n # 2.获取old文件夹中的所有的文件名字\n fileNames = os.listdir(oldFolderName)\n\n # 3.使用多进程的方式copy 原文件夹中的所有文件到新的文件夹\n pool = Pool(5)\n\n q = Manager().Queue()\n\n for name in fileNames:\n pool.apply_async(copyFileTask, (name, oldFolderName, newFolderName, q))\n\n pool.close()\n pool.join()\n\n num = 0\n allNum = len(fileNames)\n while not q.empty():\n q.get()\n num += 1\n copyRate = num / allNum\n print(\"\\r copy的进度是:%.2f%%\" % (copyRate * 100), end=\"\")\n\n print(\"已完成copy\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"py_base/2.2 linux系统编程/2.2.1 系统编程-进程/多进程拷贝文件.py","file_name":"多进程拷贝文件.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"570450711","text":"import shutil\nimport random\nimport glob\nimport os\n'''\n2割の画像をテストデータ用のディレクトリに移動する\n'''\n\n# 学習対象の女優\nnames = [\"asuka\",\"mana\",\"mikami\",\"tsubomi\",\"uehara\"]\n\n# テストデータ用のディレクトリ作成\nos.makedirs(\"/app/resources/test\", exist_ok=True)\n\n# HACK: \nfor name in names:\n in_dir = \"/app/resources/face/\"+name+\"/*\"\n in_jpg=glob.glob(in_dir)\n img_file_name_list=os.listdir(\"/app/resources/face/\"+name+\"/\")\n # ランダムな2割の画像をテスト用ディテクトリに移動させる\n random.shuffle(in_jpg)\n os.makedirs('/app/resources/test/' + name, exist_ok=True)\n for t in range(len(in_jpg)//5):\n shutil.move(str(in_jpg[t]), \"/app/resources/test/\"+name)","sub_path":"01.aihub/app/src/devide_train_test.py","file_name":"devide_train_test.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"401841261","text":"from flask_restful import Resource, Api\nfrom flask import Flask, request\nimport server\nimport json\nimport unittest\nimport factory\nimport scoring\n\napp = Flask(__name__)\napi = Api(app)\n\n\nclass TestServerResponses(unittest.TestCase):\n def setUp(self):\n data = [factory.gen_fake_patient() for x in range(100)]\n accepted_mean, accepted_std, canceled_mean, canceled_std, response_time_mean, response_time_std = scoring.get_data_stats(\n data\n )\n scored_data = scoring.calculate_intrinsic_score(\n data,\n accepted_mean,\n accepted_std,\n canceled_mean,\n canceled_std,\n response_time_mean,\n response_time_std,\n )\n\n self.app = app.test_client()\n api.add_resource(\n server.Top_Patients,\n \"/patients\",\n resource_class_kwargs={\"data\": scored_data},\n ) # Route_1\n\n self.app.testing = True\n\n def test_post(self):\n # missing value field = bad\n item = {\"longitude\": -13}\n response = self.app.post(\"http://127.0.0.1:5002/patients\", data=item)\n\n self.assertEqual(response.status_code, 400)\n data = json.loads(response.get_data())\n self.assertEqual(\n data, {\"error\": \"Invalid Argument: latitude missing from input\"}\n )\n\n item = {\"latitude\": -13}\n response = self.app.post(\"http://127.0.0.1:5002/patients\", data=item)\n\n self.assertEqual(response.status_code, 400)\n data = json.loads(response.get_data())\n self.assertEqual(\n data, {\"error\": \"Invalid Argument: longitude missing from input\"}\n )\n\n item = factory.gen_fake_location()\n response = self.app.post(\"http://127.0.0.1:5002/patients\", data=item)\n self.assertEqual(response.status_code, 200)\n data = json.loads(response.get_data())\n\n self.assertEqual(len(data), 10)\n self.assertTrue(max([r[\"score\"] for r in data]) <= 10)\n self.assertTrue(min([r[\"score\"] for r in data]) >= 1)\n # ensure max element at front of list and min element at end\n self.assertEqual(max([r[\"score\"] for r in data]), data[0][\"score\"])\n self.assertEqual(min([r[\"score\"] for r in data]), data[-1][\"score\"])\n\n item = {\n \"latitude\": \"asdad\",\n \"longitude\": \"asdfasd\",\n } # lets pass in giberish and force a server error\n # in practice there should be more hadnling for mal formed inputs like this put lets at least confirm we handle interal errors\n response = self.app.post(\"http://127.0.0.1:5002/patients\", data=item)\n self.assertEqual(response.status_code, 500)\n data = json.loads(response.get_data())\n print(data)\n\n self.assertTrue(\"error\" in data)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"code/server_test.py","file_name":"server_test.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"644808814","text":"########################################################\n#Members: Joshua Authement, Ian Duncan, Victoria Grillo\n#Description: Final Pi Project CSC 132-Event Horizon\n########################################################\n\n\n#imports modules\nimport pygame, sys\nimport random\nfrom time import sleep\nfrom pygame import mixer\n\n#color white RGB code\nWHITE = (255, 255, 255)\n\n#function that allows text to be displayed\nfont_name = pygame.font.match_font('arial')\ndef draw_text(surf, text, size, x, y):\n font = pygame.font.Font(font_name, size)\n text_surface = font.render(text, True, WHITE)\n text_rect = text_surface.get_rect()\n text_rect.midtop = (x, y)\n surf.blit(text_surface, text_rect)\n\n \n#defines how the player appears and both the player and bullet are in the same position \nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.image = pygame.image.load(\"pcship.png\").convert_alpha()\n self.rect = self.image.get_rect(center = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))\n\n def update(self):\n self.rect.center = pygame.mouse.get_pos()\n\n def create_bullet(self):\n return Bullet(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])\n \n#defines what the bullets look like and how fast they move\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, pos_x, pos_y):\n super().__init__()\n self.image = pygame.image.load(\"laser.png\").convert_alpha()\n self.rect = self.image.get_rect(center = (pos_x, pos_y))\n\n def update(self):\n self.rect.x += 8\n\n if self.rect.x >= SCREEN_WIDTH + 200:\n self.kill()\n\n#defining enemies by the pygame sprite\nclass Enemy(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.image = pygame.image.load(\"enemy.png\").convert_alpha()\n self.rect = self.image.get_rect(center=(random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),random.randint(0, SCREEN_HEIGHT),))\n #Will be how fast the enemy moves\n self.speed = 1\n \n #getting the sprite to move based on the speed\n #removing it when it goes past the left edge of the screen\n def update(self):\n self.rect.move_ip(-self.speed, 0)\n if self.rect.right < 0:\n self.kill()\n\n#defines how the background will look\nclass Background(pygame.sprite.Sprite):\n def __init__(self, image_file, location):\n self.image = pygame.image.load(image_file)\n self.rect = self.image.get_rect()\n self.rect.left, self.rect.top = location\n\n#game instructions\ninstructions= \"Use the mouse to move around. Use the left mouse button to shoot. Don't get hit.\"\n#initializes pygame\npygame.init()\n#setup for sound\nmixer.init()\n#frames per second\nclock = pygame.time.Clock()\n#screen dimensions\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 400\n#prints instructions then waits for a second\nprint(instructions)\nsleep(7)\n#makes the display\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\npygame.mouse.set_visible(False) \n\n#calls the player class and makes a player group for sprites\nplayer = Player()\nplayer_group = pygame.sprite.Group()\nplayer_group.add(player)\n#defines the sprites groups\nall_sprites = pygame.sprite.Group()\nall_sprites.add(player)\nenemy= pygame.sprite.Group()\nbullet = pygame.sprite.Group()\n#displays the title of the game & creates the background image\npygame.display.set_caption(\"Event Horizon\")\nBackground = Background('space.png', [0,0])\n#creates enemys within the game\nADDENEMY = pygame.USEREVENT + 1\npygame.time.set_timer(ADDENEMY, 250)\n#load and play background music\n#Sound Source: http://ccmixter.org/files/stevebass60/62131\n#License: http://creativecommons.org/licenses/by-nc/3.0/legalcode\nmixer.music.load(\"stevebass60_-_Black_in_Space_1.mp3\")\nmixer.music.play(-1)\n#defines score and sets value to zero\nscore = 0\n################################################\n# Main Program\n################################################\n\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n #when left side of the mouse is pressed, one bullet is fired per click \n elif event.type == pygame.MOUSEBUTTONDOWN:\n bullet.add(player.create_bullet())\n \n #adding a new enemy\n elif event.type == ADDENEMY:\n #creating the new enemy and add it to the sprite groups\n new_enemy = Enemy()\n enemy.add(new_enemy)\n all_sprites.add(new_enemy)\n\n all_sprites.update()\n #if yes, player dies and the loop stops and game is over\n hits = pygame.sprite.spritecollide(player, enemy, False)\n if hits:\n pygame.quit()\n print(\"Game Over. Your score was \" + str(score) + '.')\n break\n\n #when the bullet hits the enemy, the enemy dies\n hits = pygame.sprite.groupcollide(enemy, bullet, True, True)\n for hit in hits:\n score += 1\n e = Enemy()\n all_sprites.add(e)\n enemy.add(e)\n\n\n #drawing things/ objects on the display\n screen.fill((0, 0, 0))\n screen.blit(Background.image, Background.rect)\n enemy.draw(screen)\n bullet.draw(screen)\n player_group.draw(screen)\n draw_text(screen, str(score), 18, SCREEN_WIDTH/2, 10)\n player_group.update()\n bullet.update()\n enemy.update()\n pygame.display.flip()\n #frames per second\n clock.tick(120)\n","sub_path":"Final Pi Project-132.py","file_name":"Final Pi Project-132.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"45010711","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom education_mgmt import settings\nfrom api.views import *\nfrom rest_framework.authtoken import views as tokenView\n\nurlpatterns = patterns('',\n url(r'^login/', tokenView.obtain_auth_token),\n url(r'^register/$', user_registration, name='user_registration'),\n\n url(r'^school/add/$', school_create, name='school-create'),\n url(r'^school/list/$', school_list, name='school-list'),\n url(r'^school/details/(?P[0-9]+)/$', school_details, name='school-detail'),\n url(r'^school/update/(?P[0-9]+)/$', school_update, name='school-update'),\n url(r'^school/delete/(?P[0-9]+)/$', school_delete, name='schoolt-delete'),\n\n url(r'^university/list1/$', university_list1, name='university_list1'),\n url(r'^university/list2/$', university_list2, name='university_list2'),\n url(r'^university/delete/(?P[0-9]+)/$', university_delete, name='university_delete'),\n url(r'^university/add/$', add_university, name='add-university'),\n\n url(r'^student/add/$', student_create, name='student-create'),\n\n\n)\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"584207992","text":"\"\"\"\nModule containing functions to differentiate functions using pytorch.\n\"\"\"\nimport functools\n\ntry:\n import torch\nexcept ImportError:\n torch = None\nelse:\n from torch import autograd\n\nfrom ._backend import Backend\nfrom .. import make_tracing_backend_decorator\nfrom ...tools import flatten_arguments, group_return_values\n\n\nclass _PyTorchBackend(Backend):\n def __init__(self):\n super().__init__(\"PyTorch\")\n\n @staticmethod\n def is_available():\n return torch is not None and torch.__version__ >= \"0.4.1\"\n\n @Backend._assert_backend_available\n def is_compatible(self, function, arguments):\n return callable(function)\n\n @Backend._assert_backend_available\n def compile_function(self, function, arguments):\n flattened_arguments = flatten_arguments(arguments)\n\n if len(flattened_arguments) == 1:\n @functools.wraps(function)\n def unary_function(argument):\n return function(torch.from_numpy(argument)).numpy()\n return unary_function\n\n @functools.wraps(function)\n def nary_function(arguments):\n return function(\n *map(torch.from_numpy, flatten_arguments(arguments))).numpy()\n return nary_function\n\n def _sanitize_gradient(self, tensor):\n if tensor.grad is None:\n return torch.zeros(tensor.shape, dtype=tensor.dtype).numpy()\n return tensor.grad.numpy()\n\n def _sanitize_gradients(self, tensors):\n return list(map(self._sanitize_gradient, tensors))\n\n @Backend._assert_backend_available\n def compute_gradient(self, function, arguments):\n flattened_arguments = flatten_arguments(arguments)\n\n if len(flattened_arguments) == 1:\n def unary_gradient(argument):\n torch_argument = torch.from_numpy(argument)\n torch_argument.requires_grad_()\n function(torch_argument).backward()\n return self._sanitize_gradient(torch_argument)\n return unary_gradient\n\n def nary_gradient(arguments):\n torch_arguments = []\n for argument in flatten_arguments(arguments):\n torch_argument = torch.from_numpy(argument)\n torch_argument.requires_grad_()\n torch_arguments.append(torch_argument)\n function(*torch_arguments).backward()\n return self._sanitize_gradients(torch_arguments)\n return group_return_values(nary_gradient, arguments)\n\n @Backend._assert_backend_available\n def compute_hessian(self, function, arguments):\n flattened_arguments = flatten_arguments(arguments)\n\n if len(flattened_arguments) == 1:\n def unary_hessian(point, vector):\n x = torch.from_numpy(point)\n v = torch.from_numpy(vector)\n x.requires_grad_()\n fx = function(x)\n (grad_fx,) = autograd.grad(fx, x, create_graph=True,\n allow_unused=True)\n (grad_fx * v).sum().backward()\n return self._sanitize_gradient(x)\n return unary_hessian\n\n def nary_hessian(points, vectors):\n xs = []\n for point in flatten_arguments(points):\n x = torch.from_numpy(point)\n x.requires_grad_()\n xs.append(x)\n vs = [torch.from_numpy(vector)\n for vector in flatten_arguments(vectors)]\n fx = function(*xs)\n fx.requires_grad_()\n gradients = autograd.grad(fx, xs, create_graph=True,\n allow_unused=True)\n dot_product = 0\n for gradient, vector in zip(gradients, vs):\n dot_product += (gradient * vector).sum()\n dot_product.backward()\n return self._sanitize_gradients(xs)\n return group_return_values(nary_hessian, arguments)\n\n\nPyTorch = make_tracing_backend_decorator(_PyTorchBackend)\n","sub_path":"pymanopt/autodiff/backends/_pytorch.py","file_name":"_pytorch.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"275160478","text":"cache = {} # cache fib series\n\n\ndef fib(n):\n if n in cache:\n return cache[n] # return value if been calculated\n else:\n cache[n] = n if n < 2 else fib(n - 2) + fib(n - 1) # recursion part\n return cache[n]\n\n\nprint(fib(10))\nprint(cache)\n","sub_path":"ADS/fib_recursion.py","file_name":"fib_recursion.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"68881401","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport io\nimport os\n\nfrom setuptools import find_packages, setup\n\n# Package meta-data.\nNAME = 'canopy-toolkit'\nDESCRIPTION = 'Nifty utilities to access Canopy resources via python.'\nURL = 'https://github.com/Mesitis/aws-lambdas/utilities/canopy-toolkit'\nEMAIL = 'niranjan.rajendran@canopy.cloud'\nAUTHOR = 'Niranjan Rajendran'\nREQUIRES_PYTHON = '>=3.6.0'\n\nREQUIRED = [\n 'hvac', 'requests', 'botocore', 'async-property'\n]\n\nEXTRAS = {\n 'psycopg2': ['psycopg2-binary'],\n 'asyncpg': ['asyncpg', 'asyncio-helpers'],\n 'api': ['pyotp', 'requests-toolbelt', 'websockets'],\n 'crypto': ['pycryptodomex']\n}\n\nall_extras = set()\nfor dependencies in EXTRAS.values():\n for dependency in dependencies:\n all_extras.add(dependency)\n\nEXTRAS['all'] = list(all_extras)\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\ntry:\n with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = '\\n' + f.read()\nexcept FileNotFoundError:\n long_description = DESCRIPTION\n\nabout = {}\nproject_slug = NAME.lower().replace('-', '_')\nwith open(os.path.join(here, project_slug, '__version__.py')) as f:\n exec(f.read(), about)\n\nsetup(\n name=NAME,\n version=about['__version__'],\n description=DESCRIPTION,\n long_description=long_description,\n long_description_content_type='text/markdown',\n author=AUTHOR,\n author_email=EMAIL,\n python_requires=REQUIRES_PYTHON,\n url=URL,\n packages=find_packages(exclude=['tests', '*.tests', '*.tests.*', 'tests.*']),\n install_requires=REQUIRED,\n extras_require=EXTRAS,\n include_package_data=True,\n license='proprietary',\n classifiers=[\n # Trove classifiers\n # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers\n 'License :: Other/Proprietary License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Programming Language :: Python :: Implementation :: PyPy'\n ],\n)\n","sub_path":"pypi_install_script/canopy-toolkit-1.0.14.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"111080599","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nimport urllib.parse as urlparse\nfrom scrapy.selector import Selector\nfrom scrapy.conf import settings\n\n\nclass IcrawlerSpider(CrawlSpider):\n name = 'icrawler'\n\n def __init__(self, *args, **kwargs):\n # We are going to pass these args from our django view.\n # To make everything dynamic, we need to override them\n # inside __init__ method\n self.url = kwargs.get('url')\n self.domain = kwargs.get('domain')\n self.start_urls = [self.url]\n self.allowed_domains = [self.domain]\n if kwargs.get('depth', None):\n settings.overrides['DEPTH_LIMIT'] = kwargs.get('depth')\n\n IcrawlerSpider.rules = [\n Rule(LinkExtractor(unique=True), callback='parse_item'),\n ]\n super(IcrawlerSpider, self).__init__(*args, **kwargs)\n\n def parse_item(self, response):\n content = Selector(response=response).xpath('//body')\n for nodes in content:\n # build absolute URLs\n img_urls = [urlparse.urljoin(response.url, src)\n for src in nodes.xpath('//img/@src').extract()]\n\n item = {}\n item[\"page_link\"] = response.url\n\n # use \"image_urls\" instead of \"image_url\"\n item['image_urls'] = img_urls\n\n yield item\n","sub_path":"web_crawler/scrapy_app/scrapy_app/spiders/icrawler.py","file_name":"icrawler.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"563984942","text":"\"\"\"project33_one_to_many URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/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 app33 import views\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.showIndex,name='index'),\n path('add_bt/',views.add_bt,name='add_bt'),\n path('save_bt/',views.save_bt,name='save_bt'),\n path('show_bt/',views.show_bt,name='show_bt'),\n path('add_b/',views.add_b,name='add_b'),\n path('save_b',views.save_b,name='save_b'),\n path('show_b/',views.show_b,name='show_b')\n]\n","sub_path":"project33_one_to_many/project33_one_to_many/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"92949744","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAs BioSTEAM objects are created, they are automatically registered. The `find` object allows the user to find any Unit, Stream or System instance. When `find` is called, it simply looks up the item and returns it. \n\n\"\"\"\nfrom thermosteam.utils import Registry\nfrom ._digraph import make_digraph, save_digraph\nfrom thermosteam import Stream\nfrom . import Unit, System\n\n__all__ = ('find', 'Flowsheet')\n\n# %% Flowsheet search \n\nclass Flowsheets:\n __getattribute__ = __getitem__ = object.__getattribute__\n \n def __setattr__(self, key, value):\n raise TypeError(f\"'{type(self).__name__}' object does not support attribute assignment\")\n __setitem__ = __setattr__\n \n def __iter__(self):\n yield from self.__dict__.values()\n \n def __delattr__(self, key):\n if key == find.ID:\n raise AttributeError('cannot delete main flowsheet')\n else:\n super().__delattr__(key)\n \n def __repr__(self):\n return f'Register:\\n ' + '\\n '.join([repr(i) for i in self])\n \n \nclass Flowsheet:\n \"\"\"Create a Flowsheet object which stores references to all stream, unit, and system objects.\"\"\"\n \n #: [Register] All flowsheets.\n flowsheet = Flowsheets()\n \n def __init__(self, ID): \n #: [Register] Contains all System objects as attributes.\n self.system = Registry()\n \n #: [Register] Contains all Unit objects as attributes.\n self.unit = Registry()\n \n #: [Register] Contains all Stream objects as attributes.\n self.stream = Registry()\n \n #: [str] ID of flowsheet.\n self._ID = ID\n self.flowsheet.__dict__[ID] = self\n \n def __setattr__(self, key, value):\n if hasattr(self, '_ID'):\n raise TypeError(f\"'{type(self).__name__}' object does not support attribute assignment\")\n else:\n super().__setattr__(key, value)\n \n @property\n def ID(self):\n return self._ID\n \n def diagram(self, kind='surface', file=None, format='svg', **graph_attrs):\n \"\"\"Display all units and attached streams.\n \n Parameters\n ----------\n kind='surface' : Must be one of the following\n * **'thorough':** Thoroughly display every unit.\n * **'surface':** Display units and recycle systems.\n * **'minimal':** Minimally display flowsheet as a box with feeds and products.\n \n \"\"\"\n if kind == 'thorough':\n return self._thorough_diagram(file, format, **graph_attrs)\n elif kind == 'surface':\n return self._surface_diagram(file, format, **graph_attrs)\n elif kind == 'minimal':\n return self._minimal_diagram(file, format, **graph_attrs)\n else:\n raise ValueError(f\"kind must be either 'thorough', 'surface', or 'minimal'.\")\n \n def _thorough_diagram(self, file, format, **graph_attrs):\n units = list(self.unit)\n units.reverse()\n streams = set()\n for u in units:\n streams.update(u._ins)\n streams.update(u._outs)\n f = make_digraph(units, streams, format=format, **graph_attrs)\n save_digraph(f, file, format)\n \n def _minimal_diagram(self, file, format, **graph_attrs):\n from . import _system\n streams = list(self.stream)\n feeds = set(filter(_system._isfeed, streams))\n products = set(filter(_system._isproduct, streams))\n product = Stream(None)\n product._ID = ''\n feed = Stream(None)\n feed._ID = ''\n _system._streamUnit('\\n'.join([i.ID for i in feeds]),\n None, feed)\n _system._streamUnit('\\n'.join([i.ID for i in products]),\n product, None)\n unit = _system._systemUnit(self.ID, feed, product)\n unit.line = 'flowsheet'\n unit.diagram(1, file, format, **graph_attrs)\n \n def _surface_diagram(self, file, format, **graph_attrs):\n from . import _system\n units = set(self.unit)\n StrUnit = _system._streamUnit\n refresh_units = set()\n for i in self.system:\n if i.recycle and not any(sub.recycle for sub in i.subsystems):\n outs = []\n ins = []\n feeds = []\n products = []\n for s in i.streams:\n source = s._source\n sink = s._sink\n if source in i.units and sink not in i.units:\n if sink: outs.append(s)\n else: products.append(s)\n u_io = (source, tuple(source.ins), tuple(source.outs))\n refresh_units.add(u_io)\n elif sink in i.units and source not in i.units:\n if source: ins.append(s)\n else: feeds.append(s)\n u_io = (sink, tuple(sink.ins), tuple(sink.outs))\n refresh_units.add(u_io)\n \n if len(feeds) > 1:\n feed = Stream(None)\n feed._ID = ''\n units.add(StrUnit('\\n'.join([i.ID for i in feeds]),\n None, feed))\n ins.append(feed)\n else: ins += feeds\n \n if len(products) > 1:\n product = Stream(None)\n product._ID = ''\n units.add(StrUnit('\\n'.join([i.ID for i in products]),\n product, None))\n outs.append(product)\n else: outs += products\n \n subsystem_unit = _system._systemUnit(i.ID, ins, outs)\n units.difference_update(i.units)\n units.add(subsystem_unit)\n \n sys = _system.System(None, units)\n sys._thorough_diagram(file, format, **graph_attrs)\n for u, ins, outs in refresh_units:\n u._ins[:] = ins\n u._outs[:] = outs\n \n def __call__(self, ID):\n \"\"\"Return requested biosteam item.\n \n Parameters\n ----------\n ID : str\n ID of the requested item.\n \n \"\"\"\n ID = ID.replace(' ', '_')\n obj = (self.stream.search(ID)\n or self.unit.search(ID)\n or self.system.search(ID))\n if not obj: raise LookupError(f\"no registered item '{ID}'\")\n return obj\n \n def __str__(self):\n return self.ID\n \n def __repr__(self):\n return f'<{type(self).__name__}: {self.ID}>'\n\n\nclass MainFlowsheet(Flowsheet):\n \"\"\"Create a MainFlowsheet object which automatically registers biosteam objects as they are created.\"\"\"\n __slots__ = ()\n \n @staticmethod\n def set_flowsheet(flowsheet):\n \"\"\"Set main flowsheet that is updated with new biosteam objects.\"\"\"\n if isinstance(flowsheet, Flowsheet):\n dct = flowsheet.__dict__\n elif isinstance(flowsheet, str):\n if flowsheet in find.flowsheet:\n dct = find.flowsheet[flowsheet].__dict__\n else:\n new_flowsheet = Flowsheet(flowsheet)\n find.flowsheet.__dict__[flowsheet] = new_flowsheet\n dct = new_flowsheet.__dict__\n else:\n raise TypeError('flowsheet must be a Flowsheet object')\n Stream.registry = dct['stream']\n System.registry = dct['system']\n Unit.registry = dct['unit']\n object.__setattr__(find, '__dict__', dct)\n \n __setattr__ = Flowsheets.__setattr__\n \n def __new__(cls):\n raise TypeError('cannot create new find object.')\n\n def __repr__(self):\n return f'<{type(self).__name__}: {self.ID}>'\n \n \n#: [find] Find BioSTEAM objects by ID.\nfind = object.__new__(MainFlowsheet)\nfind.set_flowsheet('default')\n \n\n# %% Attempt at contantly rendered digraph\n\n# #: [bool] True if flowsheet is contantly rendered\n# self.live = True\n\n# def _show_once(self):\n # fig = plt.figure()\n # plt.axis('off')\n # f = open('diagram.png', 'wb')\n # diagram = make_digraph(self.unit.values()).pipe(format='png')\n # f.write(diagram)\n # img = mpimg.imread('diagram.png')\n # plt.imshow(img, interpolation='spline36')\n # fig.show()\n # # img = Image.open('diagram.png')\n # # img.show() \n \n # def _show(self):\n # fig = plt.figure()\n # plt.axis('off')\n # f = open('diagram.png', 'wb')\n # for i in range(3):\n # diagram = make_digraph(self.unit.values()).pipe(format='png')\n # f.write(diagram)\n # img = mpimg.imread('diagram.png')\n # plt.clf() \n # plt.imshow(img, interpolation='spline36')\n # fig.show()\n # time.sleep(10)\n # f.close()\n # os.remove('diagram.png')\n \n # def show(self):\n # t1 = threading.Thread(target=self._show())\n # t1.start()","sub_path":"biosteam/_flowsheet.py","file_name":"_flowsheet.py","file_ext":"py","file_size_in_byte":9061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"41251382","text":"import datetime\n\nimport pytz\n\nfrom dateutil.relativedelta import relativedelta\n\nfrom django.db.models import Q\nfrom django.utils import timezone\n\nfrom .models import (\n AssessmentTask,\n MedicationTask,\n PatientTask,\n SymptomTask,\n VitalTask,\n TeamTask,\n)\nfrom .api.serializers import (\n PatientTaskTodaySerializer,\n MedicationTaskTodaySerializer,\n SymptomTaskTodaySerializer,\n AssessmentTaskTodaySerializer,\n VitalTaskTodaySerializer,\n TeamTaskTodaySerializer,\n)\nfrom apps.plans.models import CareTeamMember\n\n\ndef calculate_task_percentage(patient):\n \"\"\"\n This method calculates the percentage of the tasks that are completed.\n This will retrieve the following tasks of the given `patient`:\n - :model:`tasks.AssessmentTask`\n - :model:`tasks.MedicationTask`\n - :model:`tasks.PatientTask`\n - :model:`tasks.SymptomTask`\n \"\"\"\n now = timezone.now()\n past_30_days = now - relativedelta(days=30)\n kwargs = {\n 'appear_datetime__range': (past_30_days, now)\n }\n\n # Patient tasks\n patient_tasks = PatientTask.objects.filter(\n patient_template__plan__patient=patient,\n **kwargs\n )\n completed_patient_tasks = patient_tasks.filter(status='done')\n\n # Medication tasks\n medication_tasks = MedicationTask.objects.filter(\n medication_task_template__plan__patient=patient,\n **kwargs\n )\n completed_medication_tasks = medication_tasks.filter(status='done')\n\n # Symptom tasks\n symptom_tasks = SymptomTask.objects.filter(\n symptom_template__plan__patient=patient,\n **kwargs\n )\n completed_symptom_tasks = symptom_tasks.filter(is_complete=True)\n\n # Assessment tasks\n assessment_tasks = AssessmentTask.objects.filter(\n assessment_template__plan__patient=patient,\n **kwargs\n )\n completed_assessment_tasks = assessment_tasks.filter(is_complete=True)\n\n total_tasks = patient_tasks.count() + medication_tasks.count() + \\\n symptom_tasks.count() + assessment_tasks.count()\n completed_tasks = completed_patient_tasks.count() + \\\n completed_medication_tasks.count() + \\\n completed_symptom_tasks.count() + \\\n completed_assessment_tasks.count()\n\n if total_tasks > 0:\n percentage = (completed_tasks / total_tasks) * 100\n return round(percentage)\n return total_tasks\n\n\ndef get_all_tasks_of_patient_today(patient):\n \"\"\"\n Retrieves all tasks of the patient that are due for current day.\n \"\"\"\n tasks = []\n today = timezone.now().date()\n today_min = datetime.datetime.combine(today,\n datetime.time.min,\n tzinfo=pytz.utc)\n today_max = datetime.datetime.combine(today,\n datetime.time.max,\n tzinfo=pytz.utc)\n\n patient_tasks = PatientTask.objects.filter(\n patient_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max)\n )\n medication_tasks = MedicationTask.objects.filter(\n medication_task_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n symptom_tasks = SymptomTask.objects.filter(\n symptom_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n assessment_tasks = AssessmentTask.objects.filter(\n assessment_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n vital_tasks = VitalTask.objects.filter(\n vital_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n\n if patient_tasks.exists():\n serializer = PatientTaskTodaySerializer(\n patient_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n if medication_tasks.exists():\n serializer = MedicationTaskTodaySerializer(\n medication_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n if symptom_tasks.exists():\n serializer = SymptomTaskTodaySerializer(\n symptom_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n if assessment_tasks.exists():\n serializer = AssessmentTaskTodaySerializer(\n assessment_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n if vital_tasks.exists():\n serializer = VitalTaskTodaySerializer(\n vital_tasks.all(),\n many=True\n )\n tasks += serializer.data\n return tasks\n\n\ndef get_all_team_tasks_for_plan_today(user, plan, **kwargs):\n \"\"\"\n Retrieves all team tasks for the given plan on the day given\n \"\"\"\n if user.is_employee:\n date_object = kwargs.pop('date_object', timezone.now().date())\n today_min = datetime.datetime.combine(date_object,\n datetime.time.min,\n tzinfo=pytz.utc)\n today_max = datetime.datetime.combine(date_object,\n datetime.time.max,\n tzinfo=pytz.utc)\n next_checkin = None\n team_tasks = TeamTask.objects.filter(\n team_template__plan=plan,\n due_datetime__range=(today_min, today_max)\n )\n return team_tasks.all()\n else:\n return []\n\n\ndef get_all_tasks_for_today(user, **kwargs):\n \"\"\"\n Retrieves all tasks for the given user that are due for current day.\n \"\"\"\n tasks = []\n date_object = kwargs.pop('date_object', timezone.now().date())\n plan_template = kwargs.pop('plan_template', None)\n plan = kwargs.pop('plan', None)\n today_min = datetime.datetime.combine(date_object,\n datetime.time.min,\n tzinfo=pytz.utc)\n today_max = datetime.datetime.combine(date_object,\n datetime.time.max,\n tzinfo=pytz.utc)\n exclude_done = kwargs.pop('exclude_done', True)\n next_checkin = None\n\n if user.is_employee:\n employee = user.employee_profile\n assigned_roles = employee.assigned_roles.all()\n if plan:\n assigned_roles = assigned_roles.filter(plan=plan)\n\n roles = assigned_roles.values_list('role', flat=True).distinct()\n team_tasks = TeamTask.objects.filter(\n Q(team_template__custom_roles__id__in=roles) |\n (\n Q(team_template__custom_roles__isnull=True) &\n Q(team_template__team_task_template__roles__id__in=roles)\n ),\n team_template__plan__care_team_members__in=assigned_roles,\n due_datetime__range=(today_min, today_max)\n )\n if exclude_done:\n team_tasks = team_tasks.exclude(status='done')\n\n if plan_template:\n team_tasks = team_tasks.filter(\n team_template__plan__plan_template=plan_template)\n\n if plan:\n team_tasks = team_tasks.filter(team_template__plan=plan)\n\n if team_tasks.exists():\n serializer = TeamTaskTodaySerializer(\n team_tasks.distinct(),\n many=True\n )\n tasks += serializer.data\n\n recent_checkin = employee.assigned_roles.all().order_by('next_checkin').first()\n next_checkin = recent_checkin.next_checkin if recent_checkin else None\n elif user.is_patient:\n patient = user.patient_profile\n patient_tasks = PatientTask.objects.filter(\n patient_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n medication_tasks = MedicationTask.objects.filter(\n medication_task_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n symptom_tasks = SymptomTask.objects.filter(\n symptom_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n assessment_tasks = AssessmentTask.objects.filter(\n assessment_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n vital_tasks = VitalTask.objects.filter(\n vital_template__plan__patient__id=patient.id,\n due_datetime__range=(today_min, today_max))\n if exclude_done:\n patient_tasks = patient_tasks.exclude(status='done')\n medication_tasks = medication_tasks.exclude(status='done')\n symptom_tasks = symptom_tasks.filter(is_complete=False)\n assessment_tasks = assessment_tasks.filter(is_complete=False)\n vital_tasks = vital_tasks.filter(is_complete=False)\n\n if plan_template:\n patient_tasks = patient_tasks.filter(\n patient_template__plan__plan_template=plan_template)\n medication_tasks = medication_tasks.filter(\n medication_task_template__plan__plan_template=plan_template)\n symptom_tasks = symptom_tasks.filter(\n symptom_template__plan__plan_template=plan_template)\n assessment_tasks = assessment_tasks.filter(\n assessment_template__plan__plan_template=plan_template)\n vital_tasks = vital_tasks.filter(\n vital_template__plan__plan_template=plan_template)\n\n if patient_tasks.exists():\n serializer = PatientTaskTodaySerializer(\n patient_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n if medication_tasks.exists():\n serializer = MedicationTaskTodaySerializer(\n medication_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n if symptom_tasks.exists():\n serializer = SymptomTaskTodaySerializer(\n symptom_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n if assessment_tasks.exists():\n serializer = AssessmentTaskTodaySerializer(\n assessment_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n if vital_tasks.exists():\n serializer = VitalTaskTodaySerializer(\n vital_tasks.all(),\n many=True\n )\n tasks += serializer.data\n\n recent_checkin = CareTeamMember.objects.filter(plan__patient__id=patient.id) \\\n .order_by('next_checkin') \\\n .first()\n next_checkin = recent_checkin.next_checkin if recent_checkin else None\n\n return {\"tasks\": tasks, \"next_checkin\": next_checkin}\n","sub_path":"Services/apps/tasks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"243385480","text":"\"\"\"\n 功能:欧拉螺线(羊角螺线)\n 作者:焦奎洸\n 版本:3.0\n 2.0新增功能:运算次数增大,呈现螺旋\n 3.0新增功能:火树银花\n 日期:2020/5/16\n\"\"\"\nimport turtle\n# 引入turtle绘图库\n\n\ndef draw_clothoid_line(fun_length, fun_angle, fun_times):\n \"\"\"\n 功能:绘图函数(迭代)\n :param fun_length: 函数内部单位长度\n :param fun_angle:函数内部单位角度\n :param fun_times:函数循环次数\n :return: 循环次数\n \"\"\"\n for i in range(1, fun_times):\n turtle.left(fun_angle)\n turtle.forward(fun_length)\n fun_angle += 1\n set_position = turtle.position()\n set_direction = turtle.towards(0, 0)\n print(set_position)\n print(set_direction)\n\n\ndef main():\n \"\"\"\n 主函数:控制迭代次数\n :return:\n \"\"\"\n # 修改项目\n # 迭代次数\n cycle_times = 200\n # 长度\n unit_length = 5\n # 角度\n unit_angle = 7\n # 速度(0, 10)\n unit_speed = 9\n\n turtle.title(\"Welcome to see the clothoid lines!\")\n\n # 画笔宽度\n turtle.pensize(2)\n # 设置画笔颜色\n turtle.pencolor(\"red\")\n # 初始绘画\n # 定位\n turtle.penup()\n turtle.setpos(50, 0)\n turtle.pendown()\n # 直线\n turtle.forward(unit_length)\n # 画笔速度\n turtle.speed(unit_speed)\n\n # 循环计时器\n add_cycle_times = 1\n # 循环使用绘图\n while add_cycle_times < cycle_times:\n draw_clothoid_line(unit_length, unit_angle, add_cycle_times)\n add_cycle_times += 1\n\n turtle.exitonclick()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"clothoid_3.0.py","file_name":"clothoid_3.0.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"596567655","text":"from tkinter import *\nimport pymysql\n\nwindow=Tk()\nwindow.title(\"Note Taking\")\n\n\n\ndb=pymysql.connect(\"localhost\",'window','hemoo317145','hemu')\ncursor=db.cursor()\n\n\ndef add():\n add_window=Tk()\n list=[]\n\n\n def update():\n for i in list:\n mylist.insert(\"end\",i)\n\n\n def save():\n sub = entry.get(\"1.0\", END)\n notes = save_text.get(\"1.0\", END)\n cursor.execute(\"insert into hemu values('\" + sub+ \"','\" + notes + \"');\")\n db.commit()\n list.append(sub)\n update()\n\n\n label = Label(add_window, text=\"Subject\", bg=\"blue\", font=\"bold 18\")\n label.place(x=20,y=10)\n entry=Text(add_window,height=\"2\",width=\"45\")\n entry.place(x=20,y=45)\n save_text=Text(add_window,height=\"30\",width=\"60\")\n save_text.place(x=20,y=90)\n save_button = Button(add_window, text=\"Save\", font=\"bold 13\", bg=\"green\", fg=\"blue\", command=save)\n save_button.place(x=390, y=45)\n add_window.minsize(600,600)\n\n\n\ndef show_all():\n show_window=Tk()\n show_window.minsize(600,600)\n qr=cursor.execute(\"select subject from hemu;\")\n a=cursor.fetchall()\n for k in a:\n for p in i:\n \n print(p)\n\n\n\ndef search_notes():\n qr=cursor.execute(\"select subject from hemu\")\n get_subject=cursor.fetchall()\n for i in range(len(get_subject)):\n list.append(get_subject[i][0])\n srch=search_entry.get(\"1.0\",END)\n for subs in list:\n if srch==subs:\n fetchdata(notes)\n break\n\n\nadd_button=Button(window,text=\"Add New Note>>\",font=\"bold 18\",bg=\"blue\",fg=\"black\",command=add)\nadd_button.place(x=20,y=70)\n\n\nlist_all_notes_button=Button(window,text=\"List All Notes>>\",font=\"bold 18\",bg=\"blue\",fg=\"black\",command=show_all)\nlist_all_notes_button.place(x=300,y=70)\n\n\nlabel=Label(window,text=\"Search Notes\",font=\"bold 18\")\nlabel.place(x=20,y=20)\n\n\nsearch_entry = Text(window,width=46,height=\"2\")\nsearch_entry.place(x=20,y=20)\n\n\nsearch_button=Button(window,text=\"Search\",font=\"bold 13\",bg=\"red\",fg=\"black\",command=search_notes)\nsearch_button.place(x=400,y=20)\n\n\nlabel=Label(window,text=\"--Notes--\",font=\"bold 20\")\nlabel.place(x=20,y=160)\n\n\nscrollbar=Scrollbar(window,orient=\"vertical\")\nscrollbar.place(x=532,y=200,height=370)\n\n\nmylist=Listbox(window,height=\"23\",width=\"85\",yscrollcommand=scrollbar.set)\nmylist.place(x=20,y=200)\n\n\n\nscrollbar.config(command=mylist.yview)\n\n\nwindow.geometry(\"550x600\")\nwindow.resizable(False,False)\nwindow.maxsize(600,600)\nwindow.minsize(500,500)\nwindow.mainloop()","sub_path":"note_taking.py","file_name":"note_taking.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"545394962","text":"import pandas as pd\nimport numpy as np\nimport json\ndata = pd.read_csv(\"data/stereotype_list.csv\")\nX_1 = data[\"male\"].values.tolist() + data[\"female\"].values.tolist()\n\ndata = pd.read_csv(\"data/GenderWords.csv\")\nX_2 = data[\"word\"].values.tolist()\n\nwith open(\"data/weat.json\") as f:\n data = json.load(f)\nX_3 = []\nfor name, words in data.items():\n X_3.extend(words)\n\nX_4 = []\nbias_analogy_f = open(\"data/Sembias\")\nfor sub_idx, l in enumerate(bias_analogy_f):\n l = l.strip().split()\n for i, word_pair in enumerate(l):\n word_pair = word_pair.split(':')\n X_4.append(word_pair[0])\n X_4.append(word_pair[1])\n\nX = [\"he\", \"she\"] + X_1 + X_2 + X_3 + X_4\nX = np.array(list(set(X))).reshape(-1, 1)\n\nX = pd.DataFrame(X, columns=[\"Vocabulary\"])\nX.to_csv(\"Vocabulary.csv\", index=False)\n","sub_path":"build_vocab.py","file_name":"build_vocab.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"334176339","text":"import multiprocessing\nimport time\n\nclass MyQueue:\n \"\"\"An asynchronous queuing library.\"\"\"\n \n def __init__(self, parallelism=1):\n #* Constructs a new Queue.\n #* @constructor\n #* @param {Number} [parallelism=1] Maximum number of tasks to run in parallel;\n # cannot be less than 1 or an error is raised.\n # @returns {Queue} A new queue object.\n if (parallelism < 1):\n raise Exception(\"parallelism cannot be less than 1\")\n \n self._parallelism = parallelism\n self._tasks = multiprocessing.Queue()\n self._jobs = multiprocessing.Queue()\n self._isRunning = multiprocessing.Value('b', False)\n \n def size(self):\n #* @returns {Number} Number of tasks awaiting execution. Does not count any tasks that are in flight\n return self._tasks.qsize()\n \n def isRunning(self):\n #* @returns {Boolean} Whether the queue is running or not.\n \n return self._isRunning.value\n \n def inFlight(self):\n #* @returns {Number} Number of tasks currently executing.\n \n return self._jobs.qsize()\n \n def addTask(self, function):\n # * Adds a new task to the queue. When executed, the task will be passed a callback used to signal the task has completed:\n # *\n # * task(callback)\n # *\n # * @param {Function} task Function which begins the asynchronous task,\n # * taking a callback to be invoked upon task completion.\n # * @returns The queue object.\n self._tasks.put(function)\n \n def addCallback(self, function):\n # * Adds a callback to be invoked when all tasks have been completed:\n # *\n # * callback.call(queue)\n # *\n # * @param {Function} callback Function to invoke when all tasks have completed;\n # * it will be passed the queue object.\n # * @returns The queue object.\n self._callBack = function\n \n def start(self):\n # * Begin executing queued tasks.\n # *\n # * Queued tasks execute in order queued, but tasks do not wait for prior tasks\n # * to complete -- this implies the order of task completion is undefined. No more\n # * than `parallelism` tasks will run at once.\n # *\n # * Queue will continue executing tasks until all have completed, at which point it\n # * executes all registered callbacks. Calling `start` repeatedly while the queue is\n # * running has no effect (though the queue can be started again with new tasks once\n # * it completes).\n # *\n # * @returns The queue object.\n \n # don't don't don't let's start #tmbg\n # don't start if we've started\n if self._isRunning.value:\n return\n \n self._isRunning.value = True\n #fire up our processes\n for x in range(0, self._parallelism):\n \n p = multiprocessing.Process(target=self.worker, args=(self._tasks, self._jobs, self._isRunning))\n \n p.start()\n\n def worker(self, tasksQueue, jobsQueue, isRunning):\n \n while (tasksQueue.qsize() > 0):\n #potential race condition between multiple processors\n try:\n myFunction = tasksQueue.get()\n except (Queue.Empty):\n break;\n # we're tracing this for the ability to count inflight jobs\n # the actual value here is inconsequential, but may be useful if you wanted to poll your queue\n jobsQueue.put(myFunction)\n \n try:\n myFunction()\n #remove something from the jobs queue after complete. Doesn't really matter what we're just using this as a counter\n jobsQueue.get()\n except:\n # maybe add some logging here?\n pass\n \n if (tasksQueue.qsize() == 0 and jobsQueue.qsize() == 0):\n \n try:\n self._callBack(self)\n except:\n pass\n isRunning.value = False\n # def __del__(self):\n # self._tasks.close()\n # self._jobs.close()\n ","sub_path":"projects/asynchronousqueue/myqueue.py","file_name":"myqueue.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"237635714","text":"from urllib.request import HTTPHandler,Request,build_opener\r\n\r\n#创建\r\nhttp = HTTPHandler()\r\n#创建opener\r\nopener = build_opener(http)\r\n\r\nurl = 'http://www.baidu.com'\r\n#返回浏览器request\r\nb = Request(url)\r\n#返回response\r\na = opener.open(b)\r\n\r\n#读取全部数据\r\ndata = a.read()\r\n\r\nprint(data.decode('utf-8'))","sub_path":"spider/0508/demo2.py","file_name":"demo2.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"212967335","text":"import matplotlib\r\nmatplotlib.use('Agg')\r\n\r\nimport numpy as np\r\n\r\nimport Augmentor\r\nfrom keras.layers.advanced_activations import LeakyReLU\r\nfrom keras.optimizers import Adadelta\r\n\r\nfrom random import randint, Random\r\nfrom time import time\r\n\r\nfrom core.nn.misc.cluster_count_uncertainity import measure_cluster_count_uncertainity\r\nfrom core.nn.misc.hierarchical_clustering import hierarchical_clustering\r\n\r\nfrom impl.nn.try00.cluster_nn_try00_v122 import ClusterNNTry00_V122\r\n\r\nif __name__ == '__main__':\r\n\r\n # Difference to test_cluster_nn_try00.py: No embedding is used and the network always returns that 10 clusters were\r\n # found, but some of them may be empty\r\n\r\n from sys import platform\r\n\r\n from impl.data.audio.timit_data_provider import TIMITDataProvider\r\n from impl.data.image.facescrub_data_provider import FaceScrubDataProvider\r\n from impl.data.image.birds200_data_provider import Birds200DataProvider\r\n from impl.nn.base.embedding_nn.cnn_embedding import CnnEmbedding\r\n\r\n is_linux = platform == \"linux\" or platform == \"linux2\"\r\n top_dir = \"/cluster/home/meierbe8/data/MT_gpulab/\" if is_linux else \"G:/tmp/\"\r\n ds_dir = \"./\" if is_linux else \"../\"\r\n\r\n p = Augmentor.Pipeline()\r\n p.random_distortion(probability=1, grid_width=4, grid_height=4, magnitude=8)\r\n p.flip_left_right(probability=0.5)\r\n # p.flip_top_bottom(probability=0.5)\r\n # p.rotate90(probability=0.5)\r\n # p.rotate270(probability=0.5)\r\n\r\n rnd = Random()\r\n rnd.seed(1729)\r\n TIMIT_lst = TIMITDataProvider.load_speaker_list(ds_dir + 'datasets/TIMIT/traininglist_100/testlist_200.txt')\r\n rnd.shuffle(TIMIT_lst)\r\n\r\n dp = TIMITDataProvider(\r\n # data_dir=top_dir + \"/test/TIMIT_mini\", cache_directory=top_dir + \"/test/cache\",\r\n data_dir=top_dir + \"/TIMIT\", cache_directory=top_dir + \"/test/cache\",\r\n min_cluster_count=1,\r\n max_cluster_count=5,\r\n return_1d_audio_data=False,\r\n test_classes=TIMIT_lst[:100],\r\n validate_classes=TIMIT_lst[100:],\r\n concat_audio_files_of_speaker=True,\r\n\r\n minimum_snippets_per_cluster=2,\r\n window_width=128\r\n )\r\n en = CnnEmbedding(\r\n output_size=256, cnn_layers_per_block=1, block_feature_counts=[32, 64, 128],\r\n fc_layer_feature_counts=[256], hidden_activation=LeakyReLU(), final_activation=LeakyReLU(),\r\n batch_norm_for_init_layer=False, batch_norm_after_activation=True, batch_norm_for_final_layer=True\r\n )\r\n\r\n def get_cnn():\r\n c_nn = ClusterNNTry00_V122(dp, 20, en, lstm_layers=14, internal_embedding_size=96*3, cluster_count_dense_layers=1, cluster_count_dense_units=256,\r\n output_dense_layers=0, output_dense_units=256, cluster_count_lstm_layers=1, cluster_count_lstm_units=128,\r\n kl_embedding_size=128, kl_divergence_factor=0., simplified_center_loss_factor=0.)\r\n c_nn.include_self_comparison = False\r\n c_nn.weighted_classes = True\r\n c_nn.class_weights_approximation = 'stochastic'\r\n c_nn.minibatch_size = 25\r\n c_nn.class_weights_post_processing_f = lambda x: np.sqrt(x)\r\n c_nn.set_loss_weight('similarities_output', 5.0)\r\n c_nn.optimizer = Adadelta(lr=5.0)\r\n\r\n validation_factor = 10\r\n c_nn.early_stopping_iterations = 15001\r\n c_nn.validate_every_nth_epoch = 10 * validation_factor\r\n c_nn.validation_data_count = c_nn.minibatch_size * validation_factor\r\n # c_nn.prepend_base_name_to_layer_name = False\r\n return c_nn\r\n c_nn = get_cnn()\r\n\r\n print_loss_plot_every_nth_itr = 100\r\n\r\n # c_nn.f_cluster_count = lambda: 10\r\n # c_nn.minibatch_size = 200\r\n\r\n # c_nn._get_keras_loss()\r\n\r\n # i = 0\r\n # start = time()\r\n # while True:\r\n # try:\r\n # print(i)\r\n # c = dp.get_data(50, 200)\r\n # print(\"Min cluster count: {}, Max cluster count: {}\".format(min(map(len, c)), max(map(len, c))))\r\n # now = time()\r\n # i += 1\r\n # print(\"Avg: {}\".format((now - start) / i))\r\n # except:\r\n # print(\"ERROR\")\r\n\r\n c_nn.build_networks(print_summaries=False)\r\n\r\n # Enable autosave and try to load the latest configuration\r\n autosave_dir = top_dir + '/autosave_ClusterNNTry00_V122'\r\n c_nn.register_autosave(autosave_dir, example_count=10, nth_iteration=500, train_examples_nth_iteration=2000, print_loss_plot_every_nth_itr=print_loss_plot_every_nth_itr)\r\n c_nn.try_load_from_autosave(autosave_dir)\r\n\r\n # Train a loooong time\r\n c_nn.train(1000000)\r\n\r\n # Load the best weights and create some examples\r\n c_nn.try_load_from_autosave(autosave_dir, config='best')\r\n c_nn.test_network(count=30, output_directory=autosave_dir + '/examples_final', data_type='test', create_date_dir=False)\r\n c_nn.test_network(count=300, output_directory=autosave_dir + '/examples_final_metrics', data_type='test', create_date_dir=False, only_store_scores=True)\r\n\r\n #########################################################################################\r\n # Do some advanced tests: Use forward dropout to measure how \"confident\" the network is.\r\n #########################################################################################\r\n confident_test_n = 5 # the number of such confidence tests\r\n\r\n output_dir = autosave_dir + '/measure_cluster_count_uncertainity'\r\n tests = []\r\n # Build the network with the forward pass dropout\r\n c_nn = get_cnn()\r\n c_nn.build_networks(build_training_model=False, additional_build_config={\r\n 'forward_pass_dropout': True\r\n })\r\n c_nn.try_load_from_autosave(autosave_dir, config='best')\r\n for i in range(confident_test_n):\r\n current_output_dir = output_dir + '/test{:02d}'.format(i)\r\n print(\"Current output directory: {}\".format(current_output_dir))\r\n\r\n print(\"Do the forward pass dropout test\")\r\n # 1) Create some test data records\r\n records = c_nn.input_count\r\n fd_data, fd_additional_obj_info, fd_hints = c_nn.data_provider.get_data(elements_per_cluster_collection=records, data_type='test', cluster_collection_count=1)\r\n fd_x_data, _ = c_nn._build_Xy_data(fd_data, ignore_length=True)\r\n fd_i_data = c_nn.data_to_cluster_indices(fd_data)\r\n # Use only the first cluster collection\r\n fd_x_data = list(map(lambda x: x[0], fd_x_data[:-1]))\r\n fd_i_data = fd_i_data[0]\r\n # 2) Do the forward dropout test\r\n x = measure_cluster_count_uncertainity(c_nn, fd_x_data,\r\n show_progress=False, output_directory=current_output_dir,\r\n input_permutation=True, forward_pass_dropout=True)\r\n\r\n # Use hierarchical clustering to test the created embeddings\r\n\r\n # 1) Generate some data (e.g. 50 records)\r\n print(\"Try to use hierarchical clustering on the embeddings\")\r\n records = 50\r\n data, _, _ = c_nn.data_provider.get_data(elements_per_cluster_collection=records, data_type='test', cluster_collection_count=1)\r\n x_data, _ = c_nn._build_Xy_data(data, ignore_length=True)\r\n i_data = c_nn.data_to_cluster_indices(data)\r\n # Only use the first cluster collection\r\n x_data = list(map(lambda x: x[0], x_data[:-1]))\r\n i_data = i_data[0]\r\n\r\n # 2) Do the test\r\n hierarchical_clustering(\r\n x_data, i_data, c_nn, plot_filename=output_dir + '/{:02d}_rand_example_hierarchical_clustering.png'.format(i)\r\n )\r\n hierarchical_clustering(\r\n x_data, i_data, c_nn, plot_filename=output_dir + '/{:02d}_rand_example_hierarchical_clustering_euclidean.png'.format(i),\r\n metric='euclidean'\r\n )\r\n\r\n # 3) Also do the test with the forward pass dropout data\r\n hierarchical_clustering(\r\n fd_x_data, fd_i_data, c_nn, plot_filename=current_output_dir + '/example_hierarchical_clustering.png'\r\n )\r\n hierarchical_clustering(\r\n fd_x_data, fd_i_data, c_nn, plot_filename=current_output_dir + '/example_hierarchical_clustering.png',\r\n metric='euclidean'\r\n )\r\n\r\n tests.append({\r\n 'directory': current_output_dir,\r\n 'fd_data': (fd_data, fd_additional_obj_info, fd_hints)\r\n })\r\n\r\n #########################################################################################\r\n # Do a \"normal\" test with the data of the forward dropout test: This really helps to\r\n # get a feeling for the data.\r\n #########################################################################################\r\n c_nn = get_cnn()\r\n c_nn.build_networks(build_training_model=False)\r\n c_nn.try_load_from_autosave(autosave_dir, config='best')\r\n for test in tests:\r\n directory = test['directory']\r\n c_nn.test_network(output_directory=directory, create_date_dir=False, data=test['fd_data'])\r\n\r\n\r\n","sub_path":"app2/test_cluster_nn_try00_v122.py","file_name":"test_cluster_nn_try00_v122.py","file_ext":"py","file_size_in_byte":8906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"480048899","text":"import numpy as np\n#from gym import error, spaces, utils\n#from gym.utils import seeding\n#from .cap_view2d import CaptureView2D\nfrom .const import *\n#from .create_map import CreateMap\nfrom .enemy_ai import EnemyAI\n\nclass Agent():\n \"\"\"This is a parent class for all agents.\n It creates an instance of agent in specific location\"\"\"\n\n def __init__(self, loc, map_only):\n \"\"\"\n Constructor\n\n Parameters\n ----------\n self : object\n Agent object\n loc : list\n [X,Y] location of unit\n \"\"\"\n self.isAlive = True\n self.atHome = True\n self.x, self.y = loc\n self.step = UGV_STEP\n self.range = UGV_RANGE\n self.a_range = UGV_A_RANGE\n self.air = False\n self.ai = EnemyAI(map_only)\n\n def move(self, action):\n x, y = self.x, self.y\n if action == \"X\":\n pass\n elif action == \"W\":\n x -= self.step\n elif action == \"E\":\n x += self.step\n elif action == \"N\":\n y -= self.step\n elif action == \"S\":\n y += self.step\n else:\n print(\"error: wrong action selected\")\n\n self.x = x#max(min(WORLD_W-1, x), 0)\n self.y = y#max(min(WORLD_H-1, y), 0)\n\n def get_loc(self):\n return self.x, self.y\n\n def report_loc(self):\n print(\"report: position x:%d, y:%d\" % (self.x, self.y))\n\nclass GroundVehicle(Agent):\n \"\"\"This is a child class for ground agents. Inherited from Ageng class.\n It creates an instance of UGV in specific location\"\"\"\n def __init__(self, loc, map_only):\n \"\"\"\n Constructor\n\n Parameters\n ----------\n self : object\n CapEnv object\n \"\"\"\n Agent.__init__(self, loc, map_only)\n\nclass AerialVehicle(Agent):\n \"\"\"This is a child class for aerial agents. Inherited from Ageng class.\n It creates an instance of UAV in specific location\"\"\"\n def __init__(self, loc, map_only):\n \"\"\"\n Constructor\n\n Parameters\n ----------\n self : object\n CapEnv object\n \"\"\"\n Agent.__init__(self, loc, map_only)\n self.step = UAV_STEP\n self.range = UAV_RANGE\n self.a_range = UAV_A_RANGE\n self.air = True\n\nclass CivilAgent(GroundVehicle):\n \"\"\"This is a child class for civil agents. Inherited from UGV class.\n It creates an instance of civil in specific location\"\"\"\n def __init__(self, loc, map_only):\n \"\"\"\n Constructor\n\n Parameters\n ----------\n self : object\n CapEnv object\n \"\"\"\n Agent.__init__(self, loc, map_only)\n self.direction = [0, 0]\n self.isDone = False\n # ! not used for now\n\n# def move():\n# if not self.isDone:\n# self.l\n#\n# def check_complete(self):\n# return self.isDone","sub_path":"gym_cap/build/lib/gym_cap/envs/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"436843147","text":"# Copyright 2021 Nokia\n# Licensed under the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom flask import Blueprint, request, jsonify\nimport json\nimport datetime\nfrom tpm import tpm\nfrom claims import claimstructure\n\nuefi_endpoint = Blueprint('uefi_endpoint', __name__)\n\n\n\n@uefi_endpoint.route('/eventlog', methods=['GET','POST'])\ndef returnEVENTLOGRREAD():\n tpmdevice = tpm.TPM()\n\n c = claimstructure.Claim()\n c.addHeaderItem(\"ta_received\",str(datetime.datetime.now(datetime.timezone.utc)))\n q = tpmdevice.readEventLog()\n c.addPayloadItem(\"eventlog\",q)\n c.addHeaderItem(\"ta_complete\",str(datetime.datetime.now(datetime.timezone.utc)))\n c.addHeaderItem(\"ak_name\",\"whatever the AK name is here\") \n c.sign()\n rc = c.getClaim()\n\n return jsonify(rc), 200\n\n\n","sub_path":"t10/A10httprest/endpoints/uefi/uefi_endpoint.py","file_name":"uefi_endpoint.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"553042877","text":"# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018-2019 Fetch.AI Limited\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#\n# ------------------------------------------------------------------------------\n\n\"\"\"Tests for the webhook connection and channel.\"\"\"\n\nimport asyncio\nimport logging\nimport subprocess # nosec\nimport time\n\n# from unittest import mock\n# from unittest.mock import Mock\n#\n# from aiohttp import web # type: ignore\n#\n# from multidict import CIMultiDict, CIMultiDictProxy # type: ignore\n\nimport pytest\n\n# from yarl import URL # type: ignore\n\nfrom packages.fetchai.connections.webhook.connection import WebhookConnection\n\nfrom ....conftest import (\n get_host,\n get_unused_tcp_port,\n)\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.asyncio\nclass TestWebhookConnect:\n \"\"\"Tests the webhook connection's 'connect' functionality.\"\"\"\n\n @classmethod\n def setup_class(cls):\n \"\"\"Initialise the class.\"\"\"\n cls.address = get_host()\n cls.port = get_unused_tcp_port()\n cls.agent_address = \"some string\"\n\n cls.webhook_connection = WebhookConnection(\n address=cls.agent_address,\n webhook_address=cls.address,\n webhook_port=cls.port,\n webhook_url_path=\"/webhooks/topic/{topic}/\",\n )\n cls.webhook_connection.loop = asyncio.get_event_loop()\n\n async def test_initialization(self):\n \"\"\"Test the initialisation of the class.\"\"\"\n assert self.webhook_connection.address == self.agent_address\n\n @pytest.mark.asyncio\n async def test_connection(self):\n \"\"\"Test the connect functionality of the webhook connection.\"\"\"\n await self.webhook_connection.connect()\n assert self.webhook_connection.connection_status.is_connected is True\n\n\n@pytest.mark.asyncio\nclass TestWebhookDisconnection:\n \"\"\"Tests the webhook connection's 'disconnect' functionality.\"\"\"\n\n @classmethod\n def setup_class(cls):\n \"\"\"Initialise the class.\"\"\"\n cls.address = get_host()\n cls.port = get_unused_tcp_port()\n cls.agent_address = \"some string\"\n\n cls.webhook_connection = WebhookConnection(\n address=cls.agent_address,\n webhook_address=cls.address,\n webhook_port=cls.port,\n webhook_url_path=\"/webhooks/topic/{topic}/\",\n )\n cls.webhook_connection.loop = asyncio.get_event_loop()\n\n @pytest.mark.asyncio\n async def test_disconnect(self):\n \"\"\"Test the disconnect functionality of the webhook connection.\"\"\"\n await self.webhook_connection.connect()\n assert self.webhook_connection.connection_status.is_connected is True\n\n await self.webhook_connection.disconnect()\n assert self.webhook_connection.connection_status.is_connected is False\n\n\n# ToDo: testing webhooks received\n# @pytest.mark.asyncio\n# async def test_webhook_receive():\n# \"\"\"Test the receive functionality of the webhook connection.\"\"\"\n# admin_address = \"127.0.0.1\"\n# admin_port = 8051\n# webhook_address = \"127.0.0.1\"\n# webhook_port = 8052\n# agent_address = \"some agent address\"\n#\n# webhook_connection = WebhookConnection(\n# address=agent_address,\n# webhook_address=webhook_address,\n# webhook_port=webhook_port,\n# webhook_url_path=\"/webhooks/topic/{topic}/\",\n# )\n# webhook_connection.loop = asyncio.get_event_loop()\n# await webhook_connection.connect()\n#\n#\n#\n# # # Start an aries agent process\n# # process = start_aca(admin_address, admin_port)\n#\n# received_webhook_envelop = await webhook_connection.receive()\n# logger.info(received_webhook_envelop)\n\n# webhook_request_mock = Mock()\n# webhook_request_mock.method = \"POST\"\n# webhook_request_mock.url = URL(val=\"some url\")\n# webhook_request_mock.version = (1, 1)\n# webhook_request_mock.headers = CIMultiDictProxy(CIMultiDict(a=\"Ali\"))\n# webhook_request_mock.body = b\"some body\"\n#\n# with mock.patch.object(web.Request, \"__init__\", return_value=webhook_request_mock):\n# received_webhook_envelop = await webhook_connection.receive()\n# logger.info(received_webhook_envelop)\n#\n# # process.terminate()\n\n\ndef start_aca(admin_address: str, admin_port: int):\n process = subprocess.Popen( # nosec\n [\n \"aca-py\",\n \"start\",\n \"--admin\",\n admin_address,\n str(admin_port),\n \"--admin-insecure-mode\",\n \"--inbound-transport\",\n \"http\",\n \"0.0.0.0\",\n \"8000\",\n \"--outbound-transport\",\n \"http\",\n \"--webhook-url\",\n \"http://127.0.0.1:8052/webhooks\",\n ]\n )\n time.sleep(4.0)\n return process\n","sub_path":"tests/test_packages/test_connections/test_webhook/test_webhook.py","file_name":"test_webhook.py","file_ext":"py","file_size_in_byte":5337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"405393673","text":"#/usr/bin/python\n#\n\nimport os, glob, zipfile\nimport psycopg2\nimport argparse\nimport importlib\nimport fa\nimport pysftp\n\nclass MyPeak ():\n\n def __init__(self, dye, size_s, size_bp, height):\n\n self.dye = dye\n self.size_s = size_s\n self.size_bp = size_bp\n self.height = height\n\n def __repr__(self):\n return \"\" % (\n self.dye, self.size_s, self.size_bp, self.height )\n\ndef main():\n \n nrecords = 2\n print_all = False\n use_db = True\n scp_files = True # only used if use_db = True\n\n if scp_files:\n f = open('dbinfo')\n lines = f.readlines()\n f.close()\n username = lines[1].rstrip('\\n')\n keyfile = lines[2].rstrip('\\n')\n\n sftp = pysftp.Connection('ebase-c.neb.com', username=username, private_key=keyfile)\n\n files = {} # dictionary containing directories and names of files within directories\n\n if use_db:\n\n # open the database\n try:\n f = open('dbinfo')\n conn_str = f.readlines()[0]\n f.close()\n conn = psycopg2.connect(conn_str)\n except:\n print(\"I am unable to connect to the database\")\n\n cur = conn.cursor()\n\n # get all the fields for one entry and print them to the screen\n if print_all:\n try:\n ex0 = \"SELECT column_name FROM information_schema.columns WHERE table_name = 'ce_experiments' AND table_schema = 'public';\"\n cur.execute(ex0)\n fields = [item[0] for item in cur.fetchall()]\n\n ex1 = \"SELECT \" + ', '.join(fields) + \" FROM ce_experiments LIMIT \" + str(nrecords) + \";\"\n cur.execute(ex1)\n rows = cur.fetchall()\n\n for row in rows:\n for field, value in zip(fields, row):\n print(field, \": \", value)\n\n except Exception as e:\n print(e)\n\n # get sets of filenames and directories\n try:\n ex = \"SELECT id, data_file_name, peaks_table_file_name FROM ce_experiments LIMIT \" + str(nrecords) + \";\"\n cur.execute(ex)\n rows = cur.fetchall()\n\n for row in rows:\n \n id, zipped_files, peaks_table_file_name = row[0], row[1], row[2]\n\n print(\"peaks_table_file_name: \",peaks_table_file_name)\n\n basedir = \"/var/www/ebase/shared/shared_uploads/ce_experiments/\" + str(id)\n full_zipped_files_name = basedir + \"/\" + zipped_files\n full_peaks_table_file_name = basedir + \"/\" + peaks_table_file_name\n\n if scp_files:\n sftp.get(full_zipped_files_name)\n full_zipped_files_name = zipped_files\n sftp.get(full_peaks_table_file_name)\n \n fileroot = zipped_files[:-4]\n if not os.path.isdir(fileroot):\n os.makedirs(fileroot)\n os.chdir(fileroot)\n os.rename(\"../\"+zipped_files,zipped_files)\n os.rename(\"../\"+peaks_table_file_name,peaks_table_file_name)\n \n with zipfile.ZipFile(full_zipped_files_name) as zip_ref:\n zip_ref.extractall(\".\")\n if scp_files:\n os.remove(zipped_files)\n os.chdir(\"..\")\n \n file_list = \"\"\n files[id] = (fileroot, peaks_table_file_name, file_list) \n\n if scp_files:\n sftp.close()\n \n except Exception as e:\n print(e)\n\n # read from local files instead of database\n else:\n fileroot = \"trace-Jul-25-2013-Jul26-13-32-28_full\"\n file_list = \"GL8-044D3-10.fsa\"\n peaks_table_file_name = \"GL8-044.csv\"\n\n files['2'] = (fileroot, peaks_table_file_name, file_list)\n\n\n for key, info in files.items():\n \n file_list = info[2]\n file_root = info[0]\n\n fa_args = ['--align',\n '--panel=GS120LIZ',\n '--ladder_rfu_threshold=1000',\n '--nonladder_rfu_threshold=50',\n '--call',\n #'--plot', '--ladderplot',\n '--allelemethod=leastsquare',\n '--baselinemethod=median',\n '--baselinewindow=399',\n '--listpeaks',\n '--peaks_format=peakscanner',\n '--verbose=0',\n '--indir='+file_root]\n\n if file_list!=\"\":\n fa_args.append('--file='+file_list)\n\n if file_list!=\"\" and len(file_list.split(','))==1:\n fa_args.append('--outfile='+fileroot+\"/\"+fileroot+\"_\"+file_list+\".out\")\n else:\n fa_args.append('--outfile='+fileroot+\"/\"+fileroot+\".out\")\n\n try:\n parser = fa.init_argparser()\n args = parser.parse_args(fa_args)\n fa.main(args)\n\n except Exception as e:\n print(e)\n\n # do some cleanup of the output directory\n if use_db:\n\n os.chdir(file_root)\n\n # first get list of badfiles\n f = open(file_root+'_badfiles.out','r')\n badfiles = f.read().splitlines()\n f.close()\n\n badfiles = [ i.split(':')[1].strip() for i in badfiles ]\n \n print(\"badfiles: \", badfiles)\n \n for fsa_filename in glob.glob(\"*.fsa\"):\n #print(\"file: \", fsa_filename)\n if fsa_filename not in badfiles:\n os.remove(fsa_filename)\n else:\n print(\"keeping file \",fsa_filename)\n os.chdir(\"..\")\n \n\nif __name__ == '__main__':\n\n main()\n","sub_path":"fatools/scripts/ebase.py","file_name":"ebase.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"358478594","text":"from django.db import models\n#from countdowntimer_model.models import CountdownTimer\n\n#class Time(models.Model,CountdownTimer):\n# pass\n# duration_in_minutes = models.CharField(max_length = 200,null=True)\n# state = models.IntegerField(blank=True,primary_key=True);\n\n\n\nclass Stud(models.Model):\n studid = models.IntegerField(blank=True,primary_key=True)\n name = models.CharField(max_length = 80) # name of student\n fname = models.CharField(max_length = 80,null=True) # Familly name\n klass = models.CharField(max_length = 8) # Classe of the student\n \n \n class Meta:\n #app_label = \"mu_stud\"\n #managed = True\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\n\nclass Multi(models.Model):\n \n testid = models.AutoField(primary_key=True)\n #studid = models.ForeignKey(Stud, default=0, to_field=\"stuid\", on_delete=models.SET_DEFAULT)\n studid = models.ForeignKey(Stud, on_delete=models.CASCADE)\n #studid = models.IntegerField(default=0)\n week = models.PositiveSmallIntegerField(null=True,default=45) # Week of the test\n date = models.CharField(max_length=80,null=True) # Date of the test\n start = models.CharField(max_length=80,null=True) # Start of the test\n end = models.CharField(max_length=80,null=True) # End of the test\n tid = models.CharField(max_length=80,null=True) # Time in minutes\n correct = models.IntegerField(null=True) # Nb of Correct answers\n errors = models.IntegerField(null=True) # Nb of Wrong answers\n\n \n #timer = Time.objects.create(\n #duration_in_minutes=5,\n\n #state=Time.STATE.RUNNING,\n #)\n \n #remtid = timer.remaining_time_in_minutes()\n #print(remtid)\n \n test_120 = [\n [6,6],[8,4],[6,3],[2,2],[5,9],[7,5],\n [3,7],[9,9],[8,6],[6,7],[3,8],[9,4],\n [4,8],[6,4],[7,7],[9,3],[4,6],[6,8],\n [3,9],[8,8],[9,6],[4,7],[5,8],[8,3],\n [6,9],[7,3],[4,9],[3,6],[7,4],[10,10],\n [7,7],[8,6],[1,5],[8,8],[6,9],[0,7],\n [5,3],[9,9],[8,7],[7,3],[3,2],[4,8],\n [6,7],[8,7],[7,3],[3,2],[4,8],[9,7],\n [3,8],[4,7],[6,8],[3,6],[5,9],[4,6],\n [9,6],[3,0],[7,6],[8,4],[3,7],[5,5],\n [6,0],[7,6],[1,1],[4,6],[8,7],[7,3],\n [9,9],[8,6],[6,3],[6,9],[8,8],[9,6],\n [7,4],[3,8],[7,9],[6,5],[9,8],[6,6],\n [8,9],[6,7],[2,4],[9,4],[7,7],[4,8],\n [3,9],[7,8],[6,8],[9,7],[1,4],[9,2],\n [7,4],[9,6],[7,8],[9,9],[7,6],[8,3],\n [6,6],[4,9],[8,8],[4,7],[9,3],[7,7],\n [7,9],[4,6],[8,4],[9,7],[8,6],[7,3],\n [6,4],[9,8],[6,7],[8,9],[3,7],[6,9],\n [6,8],[2,0],[8,7],[6,3],[7,2],[10,1]]\n\n i = 0\n for m in test_120:\n i = i + 1\n label = '{}: {}x{}'.format(i,m[0],m[1])\n #print(label)\n locals()[label] = models.CharField(blank=True, null=True,max_length=4,default='')\n \n del locals()['label']\n \n\n class Meta:\n #app_label = \"mu_multi\"\n #managed = True\n ordering = ['testid']\n def __str__(self):\n return self.testid\n\n\n\nclass Results(models.Model):\n CLASSES = [\n (\"1a\",\"1a\"),\n (\"2a\",\"2a\"),\n (\"3a\",\"3a\"),\n (\"4a\",\"4a\"),\n (\"5a\",\"5a\"),\n (\"9b\",\"9b\")\n ]\n\n name = models.CharField(max_length=20,default='Me')\n klasser = models.CharField(max_length=2,\n choices=CLASSES,\n default=(\"1a\",\"1a\"))\n class Meta:\n \n ordering = ['name','klasser']\n\n def __str__(self):\n return self.klasser\n","sub_path":"mu/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"127264817","text":"# -*- coding: utf-8 -*-\n\"\"\"\ncalcium_imaging_data_fast.py\nLibrary of functions for calcium imaging data\n\nCreated on Wed Oct 12 16:20:15 2016\n\n@author: jcoleman, jtrinity\ncopyright UF Pediatrics\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tkFileDialog\nimport csv\nfrom copy import deepcopy\nfrom collections import OrderedDict\n\nclass SRPdecoder:\n def __init__(self, *args, **kwargs):\n\n self.voltageThreshold = 2.5\n self.stimLength = 500\n self.baseline = 25\n\n\n #Gives back chunks of the input signalChannel corresponding to flip and flop stim lists\n def GetStimLists(self, signalChannel, numStims, avgLength, flipTimeStamps, flopTimeStamps, frame_timestamps):\n frame_timestamps = np.array(frame_timestamps).astype(np.float)\n flips = OrderedDict()\n flops = OrderedDict()\n grays = OrderedDict()\n sessions = OrderedDict()\n block = 0\n \n last_flop_frame_end = None\n \n for i in range(len(flopTimeStamps)):\n\n if self.StimLength(flopTimeStamps[i]) < 0.5*avgLength:\n first_flip_frame = (np.abs(frame_timestamps - flipTimeStamps[i][0])).argmin()\n current_flip_block = OrderedDict()\n current_flop_block = OrderedDict()\n current_gray_block = OrderedDict()\n\n if last_flop_frame_end is not None: \n #first_flip_frame = (np.abs(frame_timestamps - flipTimeStamps[i][0])).argmin()\n #current_gray_block[(last_flop_frame_end, first_flip_frame)] = signalChannel[last_flop_frame_end:first_flip_frame]\n grays[block - 1] = {\"ts\":(last_flop_frame_end, first_flip_frame), \"data\":signalChannel[last_flop_frame_end:first_flip_frame]}\n for j in range(numStims):\n flip_frame = (np.abs(frame_timestamps - flipTimeStamps[i+j][0])).argmin()\n flip_frame_end = (np.abs(frame_timestamps - (flipTimeStamps[i+j][0] + self.stimLength))).argmin()\n current_flip_block[(flip_frame, flip_frame_end)] = (signalChannel[flip_frame:flip_frame_end])\n flips[block] = current_flip_block.copy()\n for j in range(numStims - 1):\n flop_frame = (np.abs(frame_timestamps - flopTimeStamps[1+i+j][0])).argmin()\n flop_frame_end = (np.abs(frame_timestamps - (flopTimeStamps[1+i+j][0] + self.stimLength))).argmin()\n #gray_frame_end = (np.abs(frame_timestamps - (flopTimeStamps[1+i+j][0] + 2 * self.stimLength))).argmin()\n current_flop_block[(flop_frame, flop_frame_end)] = (signalChannel[flop_frame:flop_frame_end])\n #current_gray_block[(flop_frame_end, gray_frame_end)] = signalChannel[flop_frame_end:gray_frame_end]\n #split the last long block into flip/flop\n last_flop_frame = (np.abs(frame_timestamps - (flipTimeStamps[i + numStims - 1][0] + self.stimLength))).argmin()\n last_flop_frame_end = (np.abs(frame_timestamps - (flipTimeStamps[i + numStims - 1][0] + 2 * self.stimLength))).argmin()\n #last_gray_frame_end = (np.abs(frame_timestamps - (flipTimeStamps[i + numStims - 1][0] + 3 * self.stimLength))).argmin()\n current_flop_block[(last_flop_frame, last_flop_frame_end)] = (signalChannel[last_flop_frame:last_flop_frame_end])\n #current_gray_block[(last_flop_frame_end, last_gray_frame_end)] = signalChannel[last_flop_frame_end:last_gray_frame_end]\n \n flops[block] = current_flop_block.copy()\n \n sessions[block] = {\"ts\":(first_flip_frame, last_flop_frame_end),\"data\":signalChannel[first_flip_frame:last_flop_frame_end]}\n \n block = block + 1\n current_flip_block.clear()\n current_flop_block.clear()\n current_gray_block.clear()\n \n gray_length = grays[0][\"ts\"][1] - grays[0][\"ts\"][0]\n current_gray_block[(last_flop_frame_end, last_flop_frame_end + gray_length)] = signalChannel[last_flop_frame_end:last_flop_frame_end + gray_length]\n grays[block - 1] = {\"ts\":(last_flop_frame_end, last_flop_frame_end + gray_length), \"data\":signalChannel[last_flop_frame_end:last_flop_frame_end + gray_length]}\n \n \n return flips, flops, grays, sessions\n \n #Averages flips/flops in sequential groups of numStims\n def GetAverages(self, flips, numStims):\n avgs = []\n for i in range(0, len(flips), numStims):\n avg = np.zeros(len(flips[0]))\n for j in range(numStims):\n avg += np.array(flips[i+j]-np.average(flips[i+j][:self.baseline]))\n avg /= numStims\n #avg += i*np.ones(len(flips[0]))\n avgs.append(avg)\n \n return avgs\n \n \n #Detects the number of stims in a session\n def StimsPerSession(self, flipLengths, flopLengths, avgLength):\n start = 0\n end = 0\n while(flopLengths[start] > avgLength*0.5):\n start += 1\n while(flipLengths[end] < avgLength*1.5):\n end += 1\n return end - start + 1\n \n #Make this take and return list of lists for using more than 2 channels (maybe a dictionary)\n def GetStimLengths(self, flipTimeStamps, flopTimeStamps):\n flipLengths = [self.StimLength(flip) for flip in flipTimeStamps]\n flopLengths = [self.StimLength(flop) for flop in flopTimeStamps]\n return flipLengths, flopLengths\n \n #takes a list of encoding channels and gives the code at sample point i\n def Decode(self, i, channels):\n return sum(2**a for (a,j) in enumerate([channel[i] for channel in channels]) if j > self.voltageThreshold)\n \n #Returns a code list corresponding to the sample in the signal\n #passes signal for standardization of channel length\n def GetCodeList(self, sig, channels):\n return[self.Decode(i, channels) for i in range(len(sig))]\n \n #Gives total number of sessions\n def GetTotalSessions(self, flopTimeStamps):\n return sum(self.StimLength(i) < 0.5*self.AvgStimLength([flopTimeStamps]) for i in flopTimeStamps)\n \n #Gives (rise, fall) timestamps corresponding to given code (1 for flop, 2 for flip)\n def GetTimeStamps(self, code, timeCodes): \n rise = [i for i in range (1, len(timeCodes)) if timeCodes[i] == code and timeCodes[i-1] != code]\n fall = [i for i in range (1, len(timeCodes)) if timeCodes[i] != code and timeCodes[i-1] == code]\n return zip(rise, fall)\n \n #gives average stim length. input must be in a list, i.e. f([flipTimeStamps]) or f([flipTimes, flopTimes]) but not f(flipTimeStamps)\n def AvgStimLength(self, timeStampsLists):\n return sum(sum(y-x for (x,y) in stampsList)/len(stampsList) for stampsList in timeStampsLists)/len(timeStampsLists)\n \n def StimLength(self, stim):\n return stim[1]- stim[0]\n \n\n \nclass FileHandler():\n def __init__(self):\n self.strobe_up = list()\n self.strobe_down = list()\n self.onset_up = list()\n self.onset_down = list()\n \n self.stim_up = list()\n self.stim_down = list()\n \n self.Bframe_up = list()\n self.Bframe_down = list()\n \n \n #Opens event channel Data from csv\n def open_event_csv(self):\n files = tkFileDialog.askopenfilenames()\n if files:\n files = list(files)\n with open(files[0], 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter = ',')\n reader = list(reader)\n r = [row[2:9] for row in reader]\n r = r[8:]\n r = np.array(r).astype(np.float64)\n \n return r\n \n #Opens intensity Data from csv\n def open_intensity_csv(self):\n files = tkFileDialog.askopenfilenames()\n if files:\n files = list(files)\n with open(files[0], 'rU') as csvfile:\n reader = csv.reader(csvfile, delimiter = ',')\n reader = list(reader)\n reader = np.array(reader)\n \n return reader\n \n #Gets indices of upward value swing\n def get_upswing(self, channel, threshold):\n return [index for index in range(1, len(channel)) if (channel[index] > threshold) and (channel[index - 1] < threshold)]\n \n #Gets indices of downward value swing\n def get_downswing(self, channel, threshold):\n return [index for index in range(1, len(channel)) if (channel[index] < threshold) and (channel[index - 1] > threshold)]\n \n #Gets cell data, roi area, and x-y coordinate arrays from intensity csv\n def get_cells(self, c):\n cellsraw = list()\n cellsmean = list()\n areas = list()\n xcoords = list()\n ycoords = list()\n for i in range(len(c[0])):\n # String keys from FIJI\n if 'RawIntDen' in c[0][i]:\n cellsraw.append(np.array(c[1:, i]).astype(np.float64))\n if 'Mean' in c[0][i]:\n cellsmean.append(np.array(c[1:, i]).astype(np.float64))\n if 'Area' in c[0][i]:\n areas.append(np.array(c[1:, i]).astype(np.float64))\n if 'X' in c[0][i]:\n xcoords.append(np.array(c[1:, i]).astype(np.float64))\n if 'Y' in c[0][i]:\n ycoords.append(np.array(c[1:, i]).astype(np.float64))\n \n if len(cellsmean) == 0:\n print ('no Mean column, manually computing mean intensity')\n for roi in range(len(cellsraw)): \n cellsmean.append(cellsraw[roi]/areas[roi])\n \n return cellsraw, cellsmean, areas, xcoords, ycoords\n \n def get_cells_from_smoothed(self, c):\n cells = list()\n for i in range(len(c[0])):\n cells.append(np.array(c[1:, i]).astype(np.float64))\n return cells\n \n #Gets channels from event csv \n def get_channels(self, r):\n channels = [r[0:, i] for i in range(len(r[0]))]\n return channels\n \n #Gets event timestamp data from channels\n def get_event_stamps(self, channels, threshold):\n self.strobe_up = self.get_upswing(channels[1], threshold)\n self.strobe_down = self.get_downswing(channels[1], threshold)\n self.onset_up = self.get_upswing(channels[2], threshold)\n self.onset_down = self.get_downswing(channels[2], threshold)\n \n self.stim_up = self.get_upswing(channels[3], threshold)\n self.stim_down = self.get_downswing(channels[3], threshold)\n \n self.Bframe_up = self.get_upswing(channels[6], threshold)\n self.Bframe_down = self.get_downswing(channels[6], threshold)\n \n #Gets nearest value in array to input\n def get_nearest(self, x, array):\n keylist = np.array(array)\n index = (np.abs(keylist-x)).argmin()\n return keylist[index]\n \n #Gives maximum difference in ms bewteen frame onsets and stim onset\n def max_frame_error(self, frame_timestamps, event_timestamps):\n deviations = list()\n for ts in event_timestamps:\n dev = np.abs(np.array(frame_timestamps) - ts).min()\n deviations.append(dev)\n return deviations\n \n #Gives flip and flop dictionaries\n #key is (start, end) frames for that stimulus\n #value is intensity data\n def get_flip_flops(self, cell, strobe_timestamps, stim_timestamps, frame_timestamps):\n #cell, Data.strobe_down, Data.stim_up, Data.Bframe_up\n duration = strobe_timestamps[1] - strobe_timestamps[0]\n flips = OrderedDict()\n flops = OrderedDict()\n gray = OrderedDict()\n for ts in stim_timestamps:\n closest_flip = self.get_nearest(ts, strobe_timestamps)\n closest_flop = self.get_nearest(ts + duration, strobe_timestamps)\n \n flip_frame_ts = self.get_nearest(closest_flip, frame_timestamps)\n flop_frame_ts = self.get_nearest(closest_flop, frame_timestamps)\n \n flip_frame_ts_end = self.get_nearest(closest_flip + duration, frame_timestamps)\n flop_frame_ts_end = self.get_nearest(closest_flop + duration, frame_timestamps)\n gray_frame_ts_end = self.get_nearest(closest_flop + 2*duration, frame_timestamps)\n \n #frames are counted by how many times Bframe channel pulses up and down\n #target frame number should be the array index for the nearest timestamp\n flip_frame = (np.abs(frame_timestamps - flip_frame_ts)).argmin()\n flop_frame = (np.abs(frame_timestamps - flop_frame_ts)).argmin()\n gray_frame = (np.abs(frame_timestamps - gray_frame_ts_end)).argmin()\n \n flip_frame_end = (np.abs(frame_timestamps - flip_frame_ts_end)).argmin()\n flop_frame_end = (np.abs(frame_timestamps - flop_frame_ts_end)).argmin()\n \n \n flips[(flip_frame, flip_frame_end)] = cell[flip_frame:flip_frame_end]\n flops[(flop_frame, flop_frame_end)] = cell[flop_frame: flop_frame_end]\n gray[(flop_frame_end, gray_frame)] = cell[flop_frame_end: gray_frame]\n \n return flips, flops, gray\n \n def get_stim_block(self, cell, stim_up, stim_down, frame_timestamps):\n stim_up.sort()\n stim_down.sort()\n stamps = zip(stim_up, stim_down)\n blocks = OrderedDict()\n for ts in stamps:\n onset_frame_ts = self.get_nearest(ts[0], frame_timestamps)\n offset_frame_ts = self.get_nearest(ts[1], frame_timestamps)\n \n frame_start = (np.abs(frame_timestamps - onset_frame_ts)).argmin()\n frame_end = (np.abs(frame_timestamps - offset_frame_ts)).argmin()\n \n blocks[(frame_start, frame_end)] = cell[frame_start:frame_end]\n return blocks\n \n \n #gets the average of flips or flops for a cell\n def get_avg(self, flips):\n return np.mean(np.array(flips).astype(np.float64), axis = 0)\n\ndef Decode(i, channels, thresh):\n return sum(2**a for (a,j) in enumerate([channel[i] for channel in channels]) if j > thresh)\n \n#Returns a code list corresponding to the sample in the signal\ndef GetCodeList(sig, channels, thresh):\n return[Decode(i, channels, thresh) for i in range(len(sig))]\n\n#Gives (rise, fall) timestamps corresponding to given code (1 for flop, 2 for flip)\ndef GetTimeStamps(code, timeCodes): \n rise = [i for i in range (1, len(timeCodes)) if timeCodes[i] == code and timeCodes[i-1] != code]\n fall = [i for i in range (1, len(timeCodes)) if timeCodes[i] != code and timeCodes[i-1] == code]\n return zip(rise, fall) \n\ndef run_deltaf_ewma(data, t_0, t_1, t_2, samplingfreq): \n import process_function_jc as pf \n \"\"\"\n From Konnerth lab Nature Protocols paper, for 30Hz:\n t_0 = 0.2\n t_1 = 0.75\n t_2 = 3\n samplingfreq = 30\n \"\"\" \n dff = OrderedDict()\n dff_ewma = OrderedDict()\n dff_offset = []\n for i in range(len(data)):\n dff[i], dff_ewma[i], dff_offset = pf.process_function(data[i], t_0, t_1, t_2, samplingfreq)\n if dff_offset > 0:\n dffnans = np.zeros(dff_offset)\n dffnans[:] = np.NAN\n for j in range(len(dff)):\n dff[j] = np.append(dffnans,dff[j])\n dff_ewma[j] = np.append(dffnans,dff_ewma[j]) \n return dff, dff_ewma, dff_offset\n \ndef chunkSessions(sessions, grays):\n # Chunk up stim and gray sessions\n stimsession_cell = list()\n for cell in sessions:\n temp_session = np.array([sessions[cell][s][\"data\"] for s in sessions[cell]])\n stimsession_cell.append(temp_session) \n graysession_cell = list()\n for cell in grays:\n temp_gray = np.array([grays[cell][s][\"data\"] for s in grays[cell]])\n graysession_cell.append(temp_gray) \n return stimsession_cell, graysession_cell\n \ndef combineGrayStim(stimsession_cell, graysession_cell, flop_i, gray_i):\n # Combine STIM and GRAY session DATA (all sessions)\n sessions_stimgray = list()\n for i in range(len(stimsession_cell)):\n temp_stimgray = np.array([np.concatenate((stimsession_cell[i][s], graysession_cell[i][s]), axis=0) for s in range(len(stimsession_cell[i]))]) # zip?\n sessions_stimgray.append(temp_stimgray) \n # Combine GRAY and STIM session DATA (sessions 2-6 only)\n sessions_graystim = list()\n for i in range(len(stimsession_cell)):\n temp_graystim = np.array([np.concatenate((graysession_cell[i][s-1], stimsession_cell[i][s]), axis=0) for s in range(1,len(stimsession_cell[i]))]) # zip?\n sessions_graystim.append(temp_graystim) \n # Indicii for gray onset (for avg sesssion, after last flop, which is the max from flop_i + the time interval for the last flop +1)\n gray_session_onset_i = 1 + (flop_i[-1][1]+(flop_i[-1][1] - flop_i[-2][1])) \n # Need indicii for STIM onset (for avg sesssion, after gray, which is the max from gray_i + the time interval for the last flop +1)\n stim_session_onset_i = (gray_i[0][1]-gray_i[0][0])-1\n return sessions_stimgray, sessions_graystim, gray_session_onset_i, stim_session_onset_i\n \ndef meanGrayStimSort(sessions_graystim):\n # Find the min length of graystim sessions for averaging, calc. means and sort\n minlength_graystimsession = list()\n for cell in range(len(sessions_graystim)):\n graystim_sessionlengths = list()\n for i in range(len(sessions_graystim[cell])):\n tempval = len(sessions_graystim[cell][i])\n graystim_sessionlengths.append(tempval)\n minlength_graystimsession.append(min(graystim_sessionlengths))\n minlength_graystimsession=min(minlength_graystimsession) \n avgs_graystim = list()\n for cell in range(len(sessions_graystim)):\n tempval=list()\n for s in range(len(sessions_graystim[cell])):\n tempval.append(sessions_graystim[cell][s][0:minlength_graystimsession])\n avgs_graystim.append(np.nanmean(tempval, axis = 0))\n # zero avgs\n for i in range(len(avgs_graystim)):\n tempdenom = np.nanmean(avgs_graystim[i])\n avgs_graystim[i] = avgs_graystim[i]-tempdenom \n # Sort cells by latency to max intensity value \n sorted_graystimavgs = sorted(avgs_graystim, key=lambda x: x.argmax())\n sorted_graystimavgs_keys = np.argsort(np.argmax(avgs_graystim, axis=1))\n sorted_graystimavgs_axis_labels = [x+1 for x in sorted_graystimavgs_keys] \n #Normalize all data (0-1) \n norm_graystimavgs = deepcopy(sorted_graystimavgs) #.copy()\n for key in range(len(norm_graystimavgs)):\n norm_graystimavgs[key] -= min(norm_graystimavgs[key])\n norm_graystimavgs[key] /= max(norm_graystimavgs[key])\n norm_graystimavgs[key] = np.array(norm_graystimavgs[key]).astype(np.float) \n return minlength_graystimsession, avgs_graystim, sorted_graystimavgs, norm_graystimavgs, sorted_graystimavgs_keys, sorted_graystimavgs_axis_labels\n \n \ndef plotSessionTraces(nrows, ncols, sessiondata, avgdata, stimonset, plottitle, mode):\n if mode == 'share xy':\n fig, axes = plt.subplots(nrows, ncols, sharex='all', sharey='all') \n elif mode == 'share off':\n fig, axes = plt.subplots(nrows, ncols) \n for i in range(nrows):\n for j in range(ncols):\n try:\n for k in range(len(sessiondata[i*ncols+j])):\n axes[i,j].plot(sessiondata[i*ncols+j][k])\n axes[i,j].plot(avgdata[i*ncols+j], linewidth=2, color='k')\n axes[i,j].text(.5, .8,'Cell '+str(i*ncols+j+1), ha='left', va='center', transform=axes[i,j].transAxes)\n axes[i,j].axvline(x=stimonset, linewidth=0.5, color='k')\n if i==0 and j==0 and mode == 'share xy':\n axes[i,j].tick_params(axis=u'both', which=u'both',length=0)\n elif i>0 or j>0 and mode == 'share xy':\n axes[i,j].axis('off')\n except IndexError:\n pass\n fig.suptitle(plottitle, fontsize=11)\n \n \ndef subplotCellTraces(nrows, ncols, avgdata, skipval, stimonset, mode): #skipval = number of traces per plot\n if mode == 'share xy':\n fig, axes = plt.subplots(nrows, ncols, sharex='all', sharey='all') \n elif mode == 'share off':\n fig, axes = plt.subplots(nrows, ncols)\n index = 0\n for i in range(nrows):\n for j in range(ncols): \n for k in range(skipval):\n try:\n axes[i,j].plot(avgdata[index])\n axes[i,j].axvline(x=stimonset, linewidth=0.5, color='k')\n if i==0 and j==0 and mode == 'share xy':\n axes[i,j].tick_params(axis=u'both', which=u'both',length=0)\n elif i>0 or j>0 and mode == 'share xy':\n axes[i,j].axis('off')\n if mode == 'share off':\n axes[i,j].tick_params(axis=u'both', which=u'both',length=0)\n except IndexError:\n pass\n #print(str(index))\n index += 1\n \n \ndef get_colormaps(delta_f, keys, minimum, maximum):\n delta_f = np.array(delta_f).astype(np.float)\n fig, ax = plt.subplots()\n heatmap = ax.pcolor(delta_f, vmin = minimum, vmax = maximum)\n ax.set_yticks(np.arange(len(delta_f))+0.5, minor=False)\n ax.set_yticklabels(keys, minor=False, fontsize = 8)\n ax.invert_yaxis()\n plt.colorbar(heatmap)\n plt.show()\n \n \ndef plotHeatAvgs(data, datakeys, stimonset, minheat, maxheat, plottitle):\n get_colormaps(data, datakeys, minheat, maxheat)\n plt.title(plottitle)\n plt.axvline(x = stimonset, color = 'green', ls = 'dashed')\n plt.axis('tight') \n \n","sub_path":"calcium_imaging_data_fast.py","file_name":"calcium_imaging_data_fast.py","file_ext":"py","file_size_in_byte":22071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"390616759","text":"import unittest\nimport sys, os.path\nimport bottle\nfrom wsgiref.util import setup_testing_defaults\n\n\n\ndef wsgi_status(**kargs):\n return test_all(**kargs)[0]\n\ndef wsgi_header(**kargs):\n return test_all(**kargs)[1]\n \ndef wsgi_body(**kargs):\n return test_all(**kargs)[2]\n\n \nclass TestWsgi(unittest.TestCase):\n\n def setUp(self):\n self.wsgi = bottle.Bottle()\n\n def simulate(self, url, **kargs):\n environ = {}\n meta = {}\n out = ''\n url = url.split('?')\n environ['PATH_INFO'] = url[0]\n if len(url) > 1: environ['QUERY_STRING'] = url[1]\n environ.update(kargs)\n setup_testing_defaults(environ)\n def start_response(status, header):\n meta['status'] = int(status.split()[0])\n meta['header'] = dict(header)\n for part in self.wsgi(environ, start_response):\n out += part\n return meta['status'], meta['header'], out\n\n def test_404(self):\n \"\"\" WSGI: 404 \"\"\"\n self.wsgi.add_route('/post/only', lambda: 'test', method='POST')\n self.assertEqual(404, self.simulate('/not/found')[0])\n self.assertEqual(404, self.simulate('/post/only')[0])\n \n def test_500(self):\n \"\"\" WSGI: 500 \"\"\"\n self.wsgi.add_route('/error/500', lambda: 1/0)\n self.assertEqual(500, self.simulate('/error/500')[0])\n \n def test_200(self):\n \"\"\" WSGI: 200 \"\"\"\n self.wsgi.add_route('/page1', lambda: 'test')\n self.wsgi.add_route('/page2', lambda: ['t','e','st'])\n self.assertEqual(200, self.simulate('/page1')[0])\n self.assertEqual(200, self.simulate('/page2')[0])\n self.assertEqual('test', self.simulate('/page1')[2])\n self.assertEqual('test', self.simulate('/page2')[2])\n \n def test_json(self):\n \"\"\" WSGI: json \"\"\"\n self.wsgi.add_route('/json', lambda: {'a':1})\n self.assertEqual(200, self.simulate('/json')[0])\n self.assertEqual('application/json', self.simulate('/json')[1].get('Content-Type',''))\n self.assertEqual(r'{\"a\": 1}', self.simulate('/json')[2])\n\n\nsuite = unittest.TestSuite()\nsuite.addTest(unittest.makeSuite(TestWsgi))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"evolution/evolution_0014/test/test_wsgi.py","file_name":"test_wsgi.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"227359034","text":"import json\nfrom django.shortcuts import render\nfrom django import forms\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db.models import When, F, Q\n# Create your views here.\n\nfrom django.http import HttpResponse, JsonResponse\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework import viewsets\n\nfrom .models import FetchJobRecord, FetchSerializer\n\nclass FetchManager():\n \n @staticmethod\n @csrf_exempt\n def create_jobs(request):\n if request.method is not 'POST': \n return HttpResponse()\n\n jobs = request.POST.get('jobs') or []\n data = []\n for job in jobs:\n\n # jq = FetchJobRecord(*job)\n # jq.save()\n # data.append(json.loads(str(jq)))\n\n serializer = FetchSerializer(data=job)\n if serializer.is_valid():\n serializer.save()\n data.append(serializer.data)\n\n\n result = json.dumps({\"success\": True, \"data\": json.dumps(data)})\n return HttpResponse(result, content_type='application/json')\n\n\n @staticmethod\n def list_jobs(request):\n limit = request.GET.get('limit') or 20\n offset = request.GET.get('offset') or 0\n lq = FetchJobRecord.objects.filter()[offset:limit]\n try:\n data = lq.all() or []\n except ObjectDoesNotExist:\n data = []\n \n count = len(data)\n result = json.dumps({\n \"success\": True, \n \"count\": count, \n \"data\": json.dumps(data)\n })\n return HttpResponse(result, content_type='application/json')\n # Entry.objects.filter(pub_date__lte='2006-01-01')\n\n # Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)\n\n @staticmethod\n def pause_jobs(request):\n return HttpResponse(\"Hello, pause. \")\n\n @staticmethod\n def delete_jobs(request):\n id = request.GET.get('id')\n if id:\n jq = FetchJobRecord(pk=id)\n jq.delete()\n\n return HttpResponse('{\"success\": true}')\n\nfrom django import forms\n\nclass CommentForm(forms.Form):\n name = forms.CharField()\n url = forms.URLField()\n comment = forms.CharField(widget=forms.Textarea)","sub_path":"backend/main/fetch/viewsv0.py","file_name":"viewsv0.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"290370533","text":"def findKthUgly(k):\n ugly = []\n ugly.append(1)\n index = 1\n index2 = 0\n index3 = 0\n index5 = 0\n while index < k:\n val = min(ugly[index2]*2, ugly[index3]*3, ugly[index5]*5)\n if ugly[index2]*2 == val:\n index2 += 1\n if ugly[index3]*3 == val:\n index3 += 1\n if ugly[index5]*5 == val:\n index5 += 1\n ugly.append(val)\n index += 1\n return ugly[-1]\nk=int(input())\nprint(findKthUgly(k))\n","sub_path":"Code/CodeRecords/2111/60715/299773.py","file_name":"299773.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"389196125","text":"\n#python日志\n# coding=utf-8\nimport logging\nimport time\nimport socket\nimport os,sys\nimport traceback\nimport multiprocessing\nsys.path.append(\"../\")\nfrom base.get_config import MyConfig as myconfig\n#print(logging.__file__)\n# import setting\n \n#rq = time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))\nrq = time.strftime('%Y-%m-%d',time.localtime(time.time()))\n\nproject_path=myconfig(\"project\",\"project_path\").value\nlog_path=myconfig(\"project\",\"log_path\").value\nlogpath=project_path+log_path+\"/\"\nsetting = {\n\t'logpath': logpath,\n\t'filename': rq+'.log'\n}\n# localIP = socket.gethostbyname(socket.gethostname())\n \nclass Log(object):\n\tdef __init__(self,path=setting['logpath'],logger=\"00000\"):\n\t\tself.path = path\n\t\tself.filename = setting['filename']\n\t\tself.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(threadName)s - %(name)s - %(message)s')\n\t\t# self.logger = logging.getLogger(logging.basicConfig(level=logging.NOTSET))\n\t\tself.logger = logging.getLogger(logger)\n\t\tself.loggerName = logger\n\t\tself.name =socket.gethostbyname(socket.gethostname())#获取主机名称和IP\n\t\t###########################################################################\n\t\tself.logger = logging.getLogger(self.name)\n\t\t#self.logger = logging.getLogger(\"pid\"+str(multiprocessing.current_process().pid))\n\t\tself.logger.setLevel(logging.DEBUG)\n\t\t# self.logger.setLevel(logging.basicConfig(level=logging.NOTSET))\n\t\t# self.fh = logging.FileHandler(self.path + self.filename)\n\t\t###########################################################################\n\t\tself.fh = logging.FileHandler(self.path + self.filename)\n\t\t# self.fh.setLevel(logging.DEBUG)\n\t\tself.fh.setFormatter(self.formatter)\n\t\tself.logger.addHandler(self.fh)\n\t\tself.pid=str(multiprocessing.current_process().pid).ljust(8,\" \")\n\t\t###############\n\t\t# self.fh.setLevel(logging.DEBUG)\n\t\t# self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(threadName)s - %(name)s - %(message)s')\n\t\t# self.fh.setFormatter(self.formatter)\n\t\t# self.logger.addHandler(self.fh)\n \n\tdef close(self):\n\t\tif rq != self.fileHandlerName:\n\t\t\t################\n\t\t\tif self.fileHandler != None:\n\t\t\t\tself.logger.removeHandler(self.fileHandler)\n\t\t\t ##################\n\t\t\t\t# self.logger.addHandler(self.fh)\n\t\t\t\t# self.logger.addHandler(fh)\n\t\t\t\tself.logger.removeHandler(self.fh)\n \n##############################################################################################################\n \n\tdef _fmtInfo(self, msg):\n\t\tif len(msg) == 0:\n\t\t\tmsg = traceback.format_exc()\n\t\t\treturn msg\n\t\telse:\n\t\t\t_tmp = [msg[0]]\n\t\t\t_tmp.append(traceback.format_exc())\n\t\t\treturn '\\n**********\\n'.join(_tmp)\n \n \n###################################################################################3###########################\n \n \n \n \n\t# def notset(self, msg):\n\t#\t self.logger.notset(msg)\n \n\tdef debug(self, msg):\n\t\tself.msg=\"pid:\"+self.pid+\" : \"+str(msg)\n\t\tself.logger.debug(self.msg)\n\t\tself.logger.handlers.clear()\n\n\tdef info(self, msg):\n\t\tself.msg=\"pid:\"+self.pid+\" : \"+str(msg)\n\t\tself.logger.info(self.msg)\n\t\tself.logger.handlers.clear()\n \n\tdef warning(self, msg):\n\t\tself.msg=\"pid:\"+self.pid+\" : \"+str(msg)\n\t\tself.logger.warning(self.msg)\n\t\tself.logger.handlers.clear()\n \n \n\tdef error(self, msg):\n\t\tself.msg=\"pid:\"+self.pid+\" : \"+str(msg)\n\t\tself.logger.error(self.msg)\n\t\tself.logger.handlers.clear()\n \n \n\tdef critical(self,msg):\n\t\tself.msg=\"pid:\"+self.pid+\" : \"+str(msg)\n\t\tself.logger.critical(self.msg)\n\t\tself.logger.handlers.clear()\n \n \n\tdef close(self):\n\t\t self.logger.addHandler(self.fh)\n\t\t self.logger.removeHandler(self.fh)\n \n# if __name__ == \"__main__\":\n#\t logger = Log(\"info\")\n\n\n\nif __name__==\"__main__\":\n\tprint(\"yes!\")\n\tLog().info(\"信息!\")\n\tLog().warning(\"警告!\")\n\tLog().debug(\"调试!\")\n\tLog().critical(\"致命!\")\n\t# t_0=time.time()\n\t# for i in range(100):\n\t# \twrit_log(str(i))\n\n\t# print(time.time()-t_0)","sub_path":"测试/接口性能/测试工具_Postman/PythonInterface/util/write_log.py","file_name":"write_log.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"379240573","text":"\"\"\"\nQuestion: https://leetcode.com/problems/group-anagrams/\nGiven an array of strings strs, group the anagrams together. You can return the answer in any order.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using\nall the original letters exactly once.\n\nExample 1:\n\nInput: strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\nOutput: [[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]\nExample 2:\n\nInput: strs = [\"\"]\nOutput: [[\"\"]]\nExample 3:\n\nInput: strs = [\"a\"]\nOutput: [[\"a\"]]\n\nConstraints:\n\n1 <= strs.length <= 104\n0 <= strs[i].length <= 100\nstrs[i] consists of lower-case English letters.\n\"\"\"\nfrom collections import defaultdict\nfrom typing import List\n\nfrom implementations.utils.list_utils import prod_list\n\n\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n return self.second_implementation(strs)\n\n def first_implementation(self, strs: List[str]) -> List[List[str]]:\n \"\"\"\n Place the strings in buckets under a sorted key.\n Using a hashmap to get their proper location in the dict bucket.\n Return the dict bucket\n Time Complexity: O(n * k log k)\n O(n): Iteration over the input strings\n O(k log k): Sorting the strs\n\n \"\"\"\n buckets = defaultdict(list)\n\n # O(n)\n for cur in strs:\n # O( k log k)\n tmp = sorted(cur)\n buckets[tuple(tmp)].append(cur)\n\n return list(buckets.values())\n\n def second_implementation(self, strs: List[str]) -> List[List[str]]:\n \"\"\"\n Eliminate the need to sort by assigning a weight to each letter in the alphabet.\n Can't use their order as 'c' => 'ab' in that case.\n Using prime numbers and their multiplied values producing unique hashes.\n Brings the complexity from O(n * k log k) => O(nk)\n \"\"\"\n primes = {'a': 2, 'b': 3, 'c': 5, 'd': 7, 'e': 11, 'f': 13, 'g': 17, 'h': 19, 'i': 23, 'j': 29, 'k': 31,\n 'l': 37, 'm': 41, 'n': 43, 'o': 47, 'node_p': 53, 'node_q': 59, 'r': 61, 's': 67, 't': 71, 'u': 73,\n 'v': 79, 'w': 83, 'x': 89, 'y': 97, 'z': 101}\n buckets = defaultdict(list)\n for cur in strs:\n buckets[prod_list([primes[c] for c in cur])].append(cur)\n\n return list(buckets.values())\n","sub_path":"python/coding_challenges/leet_code/group_anagrams.py","file_name":"group_anagrams.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351604798","text":"from random import randint\nfrom wget import download\nfrom requests import get\nx=randint(1,2)\nif(x==1):\n photo=get('https://aws.random.cat/meow')\n photo=photo.json()\n z=photo['file']\n download(z, './Pictures')\nelse:\n photo = get('https://random.dog/woof.json')\n photo = photo.json()\n z=photo['url']\n download(z, './Pictures')\n","sub_path":"CatDog.py","file_name":"CatDog.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"486952808","text":"from vpython import *\r\nfrom random import *\r\n# this code was writen by Paulo H. Acioli from \r\n# the Department of Physics and Astronomy\r\n# of Northeastern Illinois University\r\n# any use and publications that use this code or modifications\r\n# should cite the manuscript arXiv:2003.11449 [physics.ed-ph]\r\n# or the Published Version as Paulo H. Acioli, Am. J. Phys. XX, XXXX (2020).\r\n\r\ndef gasdev():\r\n g = 0\r\n while g == 0:\r\n v1 = 2.*random()-1.\r\n v2 = 2.*random()-1.\r\n r = v1**2 + v2**2\r\n if r <= 1. and r !=0:\r\n fac = sqrt(-2.*log(r)/r)\r\n gx = v1*fac\r\n gy = v2*fac\r\n g = 1\r\n return gx,gy\r\nhab={}\r\nnblocks = int(input('enter the number of simulations'))\r\nnsteps = int(input('enter the total number of steps '))\r\nrho = float(input('enter the pop density hab/m^2 '))\r\nNpop = int(input('enter the total population '))\r\nD = float(input('enter the diffusion constant '))\r\nprob = float(input('enter prob of infection '))\r\nrsafe = float(input('enter the safe distance'))\r\ntinc = float(input('enter incubation period in days'))\r\ndt = float(input('entertime step in units of day'))\r\n# compute the size of the simulation cell\r\nL = sqrt(Npop/rho)\r\nscene = canvas(title='Corona',center=[L/2,L/2,0],background=color.white,width=800,height=800)\r\nscene.range = L/2+20\r\ncell = curve(pos=[(0,0,0),(0,L,0),(L,L,0),(L,0,0),(0,0,0)],color=color.black,thickness=0.1)\r\n\r\n# create the population at random\r\n\r\navh = [0. for i in range(90)]\r\navi = [0. for i in range(90)]\r\navr = [0. for i in range(90)]\r\navh2 = [0. for i in range(90)]\r\navi2 = [0. for i in range(90)]\r\navr2 = [0. for i in range(90)]\r\nfor iblock in range(nblocks):\r\n healthy = []\r\n nhealthy =0\r\n nrec = 0\r\n for i in range(Npop):\r\n x = L*random()\r\n y = L*random()\r\n if iblock==0:\r\n hab[i] = sphere(pos=(x,y,0),radius=0.015*L)\r\n else:\r\n hab[i].color=color.white\r\n hab[i].health = 0\r\n hab[i].timeinf = 0.\r\n healthy.append(i)\r\n nhealthy +=1\r\n # chose at random 1% individuals in the population to be sick\r\n Nsick0 = int(0.01*Npop)\r\n sick = []\r\n ninf = 0\r\n for isick in range(Nsick0):\r\n ih = int(Npop*random())\r\n hab[ih].heath = 1\r\n hab[ih].color = color.red\r\n hab[ih].timeinf=tinc\r\n t = 0.\r\n if ih not in sick:\r\n sick.append(ih)\r\n healthy.remove(ih)\r\n nhealthy -=1\r\n ninf += 1\r\n for istep in range(nsteps):\r\n # move every individual and calculate their distances\r\n for i in range(Npop):\r\n xp = gasdev()\r\n hab[i].pos[0] = abs(hab[i].pos[0]+sqrt(2*D*dt)*xp[0])\r\n hab[i].pos[1] = abs(hab[i].pos[1]+sqrt(2*D*dt)*xp[1])\r\n if(hab[i].pos[0] > L): hab[i].pos[0] -= 2*sqrt(2*D*dt)*xp[0]\r\n if(hab[i].pos[1] > L): hab[i].pos[1] -= 2*sqrt(2*D*dt)*xp[1]\r\n for i in sick:\r\n hab[i].timeinf -= dt\r\n for j in healthy:\r\n dist = mag(hab[i].pos-hab[j].pos)\r\n if dist < rsafe: # test if individuals are less than the safe distance\r\n xt = random()\r\n if xt < prob:\r\n hab[j].heath = 1\r\n hab[j].timeinf = tinc\r\n hab[j].color = color.red\r\n sick.append(j)\r\n healthy.remove(j)\r\n ninf += 1\r\n nhealthy -= 1\r\n if hab[i].timeinf <=0:\r\n hab[i].health = 2\r\n hab[i].timeinf = 0\r\n hab[i].color=color.green\r\n sick.remove(i)\r\n nrec +=1\r\n if istep%100 ==0:\r\n ibox = int(istep/100)\r\n avh[ibox] += nhealthy\r\n avi[ibox] += ninf\r\n avr[ibox] += nrec\r\n avh2[ibox] += nhealthy**2\r\n avi2[ibox] += ninf**2\r\n avr2[ibox] += nrec**2\r\n \r\n t += dt\r\n print('Finished block %.0f of %.0f days'%(iblock,nsteps*dt))\r\nprint(\"Day Heathy Infec Cured sigma(H) sigma(Inf) Sigma(cured)\")\r\nfor i in range(90):\r\n stdevh = sqrt(avh2[i]/nblocks-(avh[i]/nblocks)**2)/sqrt(nblocks)\r\n stdevi = sqrt(avi2[i]/nblocks-(avi[i]/nblocks)**2)/sqrt(nblocks)\r\n stdevr = sqrt(avr2[i]/nblocks-(avr[i]/nblocks)**2)/sqrt(nblocks)\r\n print('%.0f %.3f %.3f %.3f %.3f %.3f %.3f' % (i , avh[i]/nblocks\r\n , avi[i]/nblocks , avr[i]/nblocks,\r\n stdevh,stdevi,stdevr))","sub_path":"20-12-Ventilation_vs_Infectivity/201215_Diffusion_Model.py","file_name":"201215_Diffusion_Model.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"641195300","text":"\nimport chess\nimport time\nfrom random import randrange, choice\nfrom math import sqrt, log\nimport state\nimport tensorflow as tf\nimport numpy as np\n\n\ndef monte_python_search(root_state, timer, board_classifier=None):\n root_node = Node(root_state)\n i = 0\n timeout = time.time() + timer\n while time.time() < timeout:\n next_node = tree_policy(root_node)\n if not board_classifier:\n outcome = default_policy(next_node.state)\n else:\n outcome = default_nn_policy(next_node.state, board_classifier)\n backup(next_node, outcome)\n i += 1\n print(i)\n return best_child(root_node, 0).parent_action\n\n\ndef tree_policy(node):\n curr_node = node\n while not curr_node.state.is_terminal():\n if curr_node.unexplored_actions:\n return expand(curr_node)\n else:\n curr_node = best_child(curr_node)\n return curr_node\n\n\ndef expand(node):\n unexplored_actions = node.unexplored_actions\n rand_ind = randrange(len(unexplored_actions))\n unexplored_actions[rand_ind], unexplored_actions[-1] = \\\n unexplored_actions[-1], unexplored_actions[rand_ind]\n action = unexplored_actions.pop()\n new_state = state.State((node.state, action))\n new_child_node = Node(new_state, parent=node, parent_action=action)\n node.add_child(new_child_node)\n return new_child_node\n\n\ndef best_child(node, c_value=sqrt(2)):\n max_uct = state.MIN_VALUE\n best_child_node = None\n for child_node in node.children:\n child_uct = (child_node.reward / child_node.visits) \\\n + c_value * sqrt(log(node.visits) / child_node.visits)\n if child_uct > max_uct:\n max_uct = child_uct\n best_child_node = child_node\n return best_child_node\n\n\ndef default_policy(curr_state):\n curr_state = curr_state\n while not curr_state.is_terminal():\n action = choice(curr_state.legal_actions)\n curr_state = state.State((curr_state, action))\n return terminal_state_to_outcome(curr_state)\n\n\ndef default_nn_policy(curr_state, board_classifier):\n pred_state = curr_state.get_input_layers()\n pred_input_fn = tf.estimator.inputs.numpy_input_fn(\n x=np.asarray(pred_state),\n num_epochs=1,\n shuffle=False)\n predictions = board_classifier.predict(pred_input_fn)\n prediction_dict = next(predictions)\n class_name = prediction_dict[\"classes\"]\n probability = prediction_dict[\"probabilities\"][class_name]\n\n print(class_name, probability)\n return [-1, 0, 1][class_name]\n\n\ndef backup(node, reward):\n curr_node = node\n if curr_node.parent_turn == chess.BLACK:\n reward = - reward\n while curr_node:\n curr_node.visits += 1\n curr_node.reward += reward\n reward = -reward\n curr_node = curr_node.parent\n\n\nclass Node:\n # parent_action is the Move taken by the parent to get to this node\n def __init__(self, my_state, parent=None, parent_action=None):\n\n self.state = my_state\n self.parent = parent\n self.parent_action = parent_action\n self.children = []\n self.visits = 0\n self.reward = 0\n self.parent_turn = not self.state.turn\n self.unexplored_actions = [action for action in self.state.legal_actions]\n\n def update_and_backprop(self, outcome_value):\n self.reward += outcome_value\n if self.parent:\n self.parent.update_and_backprop(outcome_value)\n\n def add_child(self, child):\n self.children.append(child)\n\n\ndef terminal_state_to_outcome(state_to_check):\n if state_to_check.rep_count[state_to_check.board.epd()] > 2:\n result = \"1/2-1/2\"\n else:\n result = state_to_check.board.result(claim_draw=True)\n\n if result == \"1-0\":\n return 1\n if result == \"0-1\":\n return -1\n if result == \"1/2-1/2\":\n return 0\n","sub_path":"montepython/mc_search.py","file_name":"mc_search.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"512999292","text":"import unittest\n\nimport sqlalchemy\nimport testing.postgresql\n\nfrom pedsnetdcc.utils import (make_conn_str, stock_metadata)\nfrom pedsnetdcc.transform_runner import TRANSFORMS\nfrom pedsnetdcc.not_nulls import set_not_nulls, drop_not_nulls\n\n\ndef setUpModule():\n # Generate a Postgresql class which caches the init-ed database across\n # multiple ephemeral database cluster instances.\n global Postgresql\n Postgresql = testing.postgresql.PostgresqlFactory(\n cache_intialized_db=True)\n\n\ndef tearDownModule():\n # Clear cached init-ed database at end of tests.\n Postgresql.clear_cache()\n\n\nclass NotNulls(unittest.TestCase):\n\n def setUp(self):\n # Create a postgres database in a temp directory.\n self.postgresql = Postgresql()\n self.dburi = self.postgresql.url()\n self.conn_str = make_conn_str(self.dburi)\n self.model_version = '2.2.0'\n self.engine = sqlalchemy.create_engine(self.dburi)\n\n # Create transformed pedsnet metadata and instantiate\n self.metadata = stock_metadata(self.model_version)\n for t in TRANSFORMS:\n self.metadata = t.modify_metadata(self.metadata)\n self.metadata.create_all(self.engine)\n\n def tearDown(self):\n # Destroy the postgres database.\n self.postgresql.stop()\n\n def test_not_nulls(self):\n\n care_site_cols = self.metadata.tables['care_site'].columns\n concept_cols = self.metadata.tables['concept'].columns\n\n drop_not_nulls(self.conn_str, self.model_version)\n\n # Verify effectiveness of drop for a non-vocab table.\n care_site = sqlalchemy.Table('care_site',\n sqlalchemy.MetaData(), autoload=True,\n autoload_with=self.engine)\n num_not_null = 0\n for col in care_site_cols:\n if not col.nullable and not col.primary_key:\n num_not_null += 1\n self.assertTrue(care_site.columns[col.name].nullable,\n 'non-vocab drop works')\n self.assertNotEqual(num_not_null, 0) # Sanity check\n\n # Verify that a vocabulary table has not been affected by the drop.\n concept = sqlalchemy.Table('concept',\n sqlalchemy.MetaData(), autoload=True,\n autoload_with=self.engine)\n num_not_null = 0\n for col in concept_cols:\n if not col.nullable and not col.primary_key:\n num_not_null += 1\n self.assertFalse(concept.columns[col.name].nullable,\n 'non-vocab drop does not affect vocab')\n self.assertNotEqual(num_not_null, 0) # Sanity check\n\n # Now drop NOT NULLs on vocabulary.\n drop_not_nulls(self.conn_str, self.model_version, vocabulary=True)\n\n # Verify drop for a vocab table.\n concept = sqlalchemy.Table('concept',\n sqlalchemy.MetaData(), autoload=True,\n autoload_with=self.engine)\n for col in concept_cols:\n if not col.nullable and not col.primary_key:\n self.assertTrue(concept.columns[col.name].nullable,\n 'vocab drop works')\n\n set_not_nulls(self.conn_str, self.model_version)\n\n # Verify that setting nulls worked for a non-vocab table.\n care_site = sqlalchemy.Table('care_site',\n sqlalchemy.MetaData(), autoload=True,\n autoload_with=self.engine)\n for col in care_site_cols:\n if not col.nullable and not col.primary_key:\n self.assertFalse(care_site.columns[col.name].nullable,\n 'non-vocab set works')\n\n # Verify that a vocab table is unaffected by setting not nulls.\n concept = sqlalchemy.Table('concept',\n sqlalchemy.MetaData(), autoload=True,\n autoload_with=self.engine)\n for col in concept_cols:\n if not col.nullable and not col.primary_key:\n self.assertTrue(concept.columns[col.name].nullable,\n 'non-vocab set does not affect vocab')\n\n set_not_nulls(self.conn_str, self.model_version, vocabulary=True)\n\n # Verify set for a vocab table.\n concept = sqlalchemy.Table('concept',\n sqlalchemy.MetaData(), autoload=True,\n autoload_with=self.engine)\n for col in concept_cols:\n if not col.nullable and not col.primary_key:\n self.assertFalse(concept.columns[col.name].nullable,\n 'vocab set works')\n","sub_path":"pedsnetdcc/tests/not_nulls_test.py","file_name":"not_nulls_test.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"327778948","text":"\"\"\"Main endpoints module.\"\"\"\nfrom urllib.parse import urlencode\n\nimport requests\n\n\ndef get_latlon_from_address(address):\n \"\"\"Submit a request to nominatim and return the lat/lon of first result.\"\"\"\n querystring = {\"format\": \"json\"}\n params = urlencode(querystring)\n url = \"https://nominatim.openstreetmap.org/search/%s?%s\" % (address, params)\n req = requests.get(url)\n data = req.json()\n if not data:\n return None, None\n place = data[0]\n lat, lon = place[\"lat\"], place[\"lon\"]\n return lat, lon\n","sub_path":"requester.py","file_name":"requester.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"141178983","text":"#!/bin/env python2\r\n'''\r\nController for GPIO attached LEDs.\r\n'''\r\n\r\nimport gpio\r\n\r\n# GPIO pin definitions\r\n_pins = {'blue': 20, 'white': 21, 'green': 21}\r\n\r\n\r\ngpio.setup_output_pins(_pins.values())\r\n\r\n'''\r\nSwitch LEDs on or off.\r\n\r\nParams:\r\n\tcolor = green, blue\r\n\tvalue = True or False\r\n'''\r\ndef setLight(color, value):\r\n\t\r\n\tif color in [None, 'none']:\r\n\t\treturn\r\n\t\r\n\tif color not in _pins:\r\n\t\traise Exception('Unsupported light color.')\r\n\tprint('set light', color, value)\r\n\tgpio.write(_pins[color], value)\r\n\r\n","sub_path":"Software Immuprobe/python/immuprobe/lights.py","file_name":"lights.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"10769349","text":"from rest_framework import serializers\n\nfrom Category.serializers import CategorySerializer\nfrom Comments.serializers import CommentSerializer\nfrom Like.serializers import LikeSerializer\nfrom Products.models import Product, ProductImages\n\n\nclass ProductSerializer(serializers.ModelSerializer):\n class Meta:\n model = Product\n fields = '__all__'\n\n def create(self, validated_data):\n # print(validated_data)\n request = self.context.get('request')\n # print(\"Файлы: \", request.FILES)\n images_data = request.FILES\n created_product = Product.objects.create(**validated_data)\n print(created_product)\n print(\"Work\", images_data.getlist('image'))\n print(\"is not work: \", images_data)\n # for image_data in images_data.getlist('images'):\n # PostImages.objects.create(post=created_post, image=image_data)\n images_obj = [\n ProductImages(product=created_product, image=image) for image in images_data.getlist('image')\n ]\n ProductImages.objects.bulk_create(images_obj)\n return created_product\n\n def to_representation(self, instance): # он отвечает за то в каком виде возвращается Response\n representation = super().to_representation(\n instance) # подтягиваем родительский метод и добавляем свою переменную\n # и так в instance сейчас хранится Product, чтобы вытащить все картинки этого поста\n # мы можем обратиться через related_name = 'images' типа Product.images.all()\n\n representation['images'] = ProductImageSerializer(instance.images.all(), many=True, context=self.context).data\n # representation2['feedbacks'] = FeedbackSerializer(instance.feedbacks.all(), many=True,\n # context=self.context).data\n return representation\n\n\n\nclass ProductImageSerializer(serializers.ModelSerializer):\n class Meta:\n model = ProductImages\n fields = '__all__'\n\n def _get_image_url(self, obj):\n if obj.image:\n url = obj.image.url\n request = self.context.get('request')\n if request is not None:\n url = request.build_absolute_uri(url)\n else:\n url = ''\n return url\n\n def to_representation(self, instance):\n representation = super().to_representation(instance)\n representation['image'] = self._get_image_url(instance)\n return representation\n\nclass ProductCommentSerializer(serializers.ModelSerializer):\n class Meta:\n model = Product\n fields = ('id', 'title')\n\n def to_representation(self, instance):\n representation = super().to_representation(\n instance)\n representation['comments'] = CommentSerializer(instance.comments.all(), many=True,\n context=self.context).data\n return representation","sub_path":"Products/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"375011199","text":"import hashlib\nimport logging\nimport time\nimport requests\n\n\nlogger = logging.getLogger(__name__)\n\nAPI_BASE_URL = 'https://smartapi.vesync.com'\nAPI_RATE_LIMIT = 30\nAPI_TIMEOUT = 5\nDEV15ASTATUS = '/15a/v1/device/devicestatus'\nDEV15ADETAILS = '/15a/v1/device/devicedetail'\nDEVICEAPI = '/platform/v1/app/devices'\n\n\nclass VeSync(object):\n def __init__(self, username, password):\n self.username = username\n self.password = password\n self.tk = None\n self.account_id = None\n self.devices = None\n self.enabled = False\n\n self.update_interval = API_RATE_LIMIT\n self.last_update_ts = None\n self.in_process = False\n\n def calculate_hex(self, hex_string):\n \"\"\"Convert Hex Strings to Values\"\"\"\n \"\"\" CREDIT FOR CONVERSION TO ITSNOTLUPUS/vesync_wsproxy \"\"\"\n hex_conv = hex_string.split(':')\n converted_hex = (int(hex_conv[0],16) + int(hex_conv[1],16))/8192 \n return converted_hex\n\n def call_api(self, api, method, json=None, headers=None):\n response = None\n\n try:\n logger.debug(\"[%s] calling '%s' api\" % (method, api))\n if method == 'get':\n r = requests.get(API_BASE_URL + api, json=json, headers=headers, timeout=API_TIMEOUT)\n elif method == 'post':\n r = requests.post(API_BASE_URL + api, json=json, headers=headers, timeout=API_TIMEOUT)\n elif method == 'put':\n r = requests.put(API_BASE_URL + api, json=json, headers=headers, timeout=API_TIMEOUT)\n except requests.exceptions.RequestException as e:\n logger.error(e)\n except Exception as e:\n logger.error(e)\n else:\n if r.status_code == 200:\n response = r.json()\n finally:\n return response\n \n def get_15A_details(self, uuid):\n if uuid is not None:\n \"\"\"mobileID required by API - Random 16digit numbers work\"\"\"\n mobileId = '1234567890123456' \n body = {'accountID': self.account_id, 'token': self.tk, 'uuid': uuid, 'mobileId': mobileId}\n response = self.call_api(DEV15ADETAILS, 'post', headers=self.get_headers(), json=body)\n return response\n else:\n return None\n\n def get_7A_details(self, cid):\n if cid is not None:\n response = self.call_api('/v1/device/' + cid + '/detail', 'get', headers=self.get_headers())\n if response is not None:\n return response\n else:\n return None\n \n def get_15A_status(self, uuid, status=None):\n if uuid is not None and status is not None:\n body = {'accountID': self.account_id, 'token': self.tk, 'uuid': uuid, 'status' : status}\n response = self.call_api(DEV15ASTATUS, 'put', headers=self.get_headers(), json=body)\n return response\n else:\n response = None\n \n def get_active_time(self, cid, uuid=None):\n \"\"\"Return active time of a device in minutes\"\"\"\n if uuid is None:\n response = self.get_7A_details(cid)\n\n elif uuid is not None:\n response = self.get_15A_details(uuid)\n \n else: \n response = None\n \n if response is not None and response:\n if 'activeTime' in response and response['activeTime']:\n if response['activeTime'] >= 0:\n return response['activeTime']\n \n return 0\n\n\n def get_devices(self):\n \"\"\"Return list of VeSync devices\"\"\"\n\n device_list = []\n\n if self.enabled:\n self.in_process = True\n\n response = self.call_api(DEVICEAPI, 'post', headers=self.get_headers(), json=self.get_device_body())\n devresponse = response['devices']\n if devresponse is not None and devresponse:\n for device in devresponse:\n if 'type' in device and 'wifi-switch' in device['type']:\n device_list.append(VeSyncSwitch(device, self))\n\n self.in_process = False\n\n return device_list\n\n def get_headers(self):\n return {'tk': self.tk, 'accountID': self.account_id}\n\n def get_device_body(self):\n return {'accountID': self.account_id, 'token': self.tk}\n\n def get_kwh_today(self, cid, uuid=None):\n \"\"\"Return total energy for day in kWh of a device\"\"\"\n if uuid is None:\n response = self.get_7A_details(cid)\n \n elif uuid is not None:\n response = self.get_15A_details(uuid)\n \n if response is not None and response:\n if 'energy' in response and response['energy']:\n watts = float(response['energy'])\n return watts\n else: \n return 0\n\n def get_power(self, cid, uuid=None):\n \"\"\"Return current power in watts of a device\"\"\"\n if uuid is None:\n response = self.get_7A_details(cid)\n if response is not None and response:\n if 'power' in response and response['power']:\n watts = float(self.calculate_hex(response['power']))\n return watts\n else:\n return 0\n \n elif uuid is not None:\n response = self.get_15A_details(uuid)\n if response is not None and response:\n if 'power' in response and response['power']:\n watts = float(response['power'])\n return watts\n else:\n return 0\n else:\n return 0\n \n def get_voltage(self, cid, uuid=None):\n \"\"\" Return Current Voltage \"\"\"\n if uuid is None:\n response = self.get_7A_details(cid)\n if response is not None and response:\n if 'voltage' in response and response['voltage']:\n voltage = self.calculate_hex(response['voltage'])\n return voltage\n else:\n return 0\n \n elif uuid is not None:\n response = self.get_15A_details(uuid)\n if response is not None and response:\n if 'voltage' in response and response['voltage']:\n voltage = float(response['voltage'])\n return voltage\n else:\n return 0\n \n else:\n return 0\n\n def get_weekly_energy_total(self, cid, uuid=None):\n \"\"\"Returns the total weekly energy usage \"\"\"\n response = self.call_api('/v1/device/' + cid + '/energy/week', 'get', headers=self.get_headers())\n\n if response is not None and response:\n if 'totalEnergy' in response and response['totalEnergy']:\n return response['totalEnergy']\n \n return 1\n \n def get_monthly_energy_total(self, cid, uuid=None):\n \"\"\"Returns total energy usage over the month\"\"\"\n response = self.call_api('/v1/device/' + cid + '/energy/month', 'get', headers=self.get_headers())\n\n if response is not None and response:\n if 'totalEnergy' in response and response['totalEnergy']:\n return response['totalEnergy']\n \n return 0\n \n def get_yearly_energy_total(self, cid, uuid=None):\n \"\"\"Returns total energy usage over the year\"\"\"\n response = self.call_api('/v1/device/' + cid + '/energy/year', 'get', headers=self.get_headers())\n\n if response is not None and response:\n if 'totalEnergy' in response and response['totalEnergy']:\n return response['totalEnergy']\n \n return 0\n \n def get_week_daily_energy(self, cid, uuid=None):\n \"\"\"Returns daily energy usage over the week\"\"\"\n response = self.call_api('/v1/device/' + cid + '/energy/week', 'get', headers=self.get_headers())\n if response is not None and response:\n if 'data' in response and response['data']:\n return response['data']\n\n return 0\n\n\n def login(self):\n \"\"\"Return True if log in request succeeds\"\"\"\n\n try:\n jd = {'account': self.username, 'password': hashlib.md5(self.password.encode('utf-8')).hexdigest()}\n except ValueError:\n logger.error(\"Unable to read username and password\")\n\n return False\n else:\n response = self.call_api('/vold/user/login', 'post', json=jd)\n\n if response is not None and response and 'tk' in response and 'accountID' in response:\n self.tk = response['tk']\n self.account_id = response['accountID']\n self.enabled = True\n\n return True\n\n return False\n\n def turn_off(self, cid, uuid=None):\n \"\"\"Return True if device has beeeen turned off\"\"\"\n if uuid is None:\n response = self.call_api('/v1/wifi-switch-1.3/' + cid + '/status/off', 'put', headers=self.get_headers())\n \n elif uuid is not None:\n response = self.get_15A_status(uuid, status='off')\n\n if response is not None and response:\n return True\n else:\n return False\n\n def turn_on(self, cid, uuid=None):\n \"\"\"Return True if device has beeeen turned on\"\"\"\n if uuid is None:\n response = self.call_api('/v1/wifi-switch-1.3/' + cid + '/status/on', 'put', headers=self.get_headers())\n\n elif uuid is not None:\n response = self.get_15A_status(uuid, status='on')\n \n if response is not None and response:\n return True\n else:\n return False\n\n def update(self):\n \"\"\"Fetch updated information about devices\"\"\"\n\n if self.last_update_ts == None or (time.time() - self.last_update_ts) > self.update_interval:\n \n if not self.in_process:\n updated_device_list = self.get_devices()\n\n if updated_device_list is not None and updated_device_list:\n for new_device in updated_device_list:\n \n if self.devices is not None and self.devices: # Check if device is already known\n was_found = False\n\n for device in self.devices:\n if device.cid == new_device.cid:\n device.set_config(new_device)\n\n was_found = True\n break\n\n if not was_found:\n self.devices.append(new_device)\n else:\n self.devices = []\n self.devices.append(new_device) \n\n self.last_update_ts = time.time()\n\n\nclass VeSyncSwitch(object):\n def __init__(self, details, manager):\n self.manager = manager\n\n self.device_name = None\n self.device_image = None\n self.cid = None\n self.device_status = None\n self.connection_type = None\n self.connection_status = None\n self.device_type = None\n self.configModule = None\n self.uuid = None\n\n self.configure(details)\n\n def configure(self, details):\n try:\n self.device_name = details['deviceName']\n except ValueError:\n logger.error(\"cannot set device_name\")\n\n try:\n self.device_image = details['deviceImg']\n except ValueError:\n logger.error(\"cannot set device_image\")\n\n try:\n self.cid = details['cid']\n except ValueError:\n logger.error(\"cannot set cid\")\n\n try:\n self.device_status = details['deviceStatus']\n except ValueError:\n logger.error(\"cannot set device_status\")\n\n try:\n self.connection_type = details['connectionType']\n except ValueError:\n logger.error(\"cannot set connection_type\")\n\n try:\n self.connection_status = details['connectionStatus']\n except ValueError:\n logger.error(\"cannot set connection_status\")\n\n try:\n self.type = details['type']\n except ValueError:\n logger.error(\"Unable to set value for device type\")\n\n try:\n self.device_type = details['deviceType']\n except ValueError:\n logger.error(\"Unable to set switch value for device type\")\n\n try:\n self.uuid = details['uuid']\n except ValueError:\n logger.error('Unable to set uuid')\n\n try:\n self.configModule = details['configModule']\n except ValueError:\n logger.error('Unable to set configModule')\n\n def get_active_time(self):\n return self.manager.get_active_time(self.cid, self.uuid)\n\n def get_kwh_today(self):\n return self.manager.get_kwh_today(self.cid, self.uuid)\n\n def get_power(self):\n return self.manager.get_power(self.cid, self.uuid)\n \n def get_voltage(self):\n return self.manager.get_voltage(self.cid, self.uuid)\n\n def get_monthly_energy_total(self):\n return self.manager.get_monthly_energy_total(self.cid, self.uuid)\n\n def get_weekly_energy_total(self):\n return self.manager.get_weekly_energy_total(self.cid, self.uuid)\n\n def get_yearly_energy_total(self):\n return self.manager.get_yearly_energy_total(self.cid, self.uuid)\n \n def get_week_daily_energy(self):\n return self.manager.get_week_daily_energy(self.cid, self.uuid)\n\n def set_config(self, switch):\n self.device_name = switch.device_name\n self.device_image = switch.device_image\n self.device_status = switch.device_status\n self.connection_type = switch.connection_type\n self.connection_status = switch.connection_status\n self.device_type = switch.device_type\n self.configModule = switch.configModule\n self.type = switch.type\n\n def turn_off(self):\n if self.manager.turn_off(self.cid, self.uuid):\n self.device_status = \"off\"\n\n def turn_on(self):\n if self.manager.turn_on(self.cid, self.uuid):\n self.device_status = \"on\"\n\n def update(self):\n self.manager.update()\n","sub_path":"src/pyvesync-v2/vesync.py","file_name":"vesync.py","file_ext":"py","file_size_in_byte":14349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"111637920","text":"#!/usr/bin/env python\n# encoding=utf8\nfrom __future__ import print_function\nfrom flexbe_core import EventState, Logger\nimport rospy\nfrom wm_nlu.srv import AnswerQuestion\nfrom std_msgs.msg import String\n\n\nclass SaraNLUspr(EventState):\n '''\n Use wm_nlu to parse a sentence and return the answer.\n ># sentence string sentence to parse\n #> answer string answer\n\n <= understood Finished job.\n <= not_understood Finished job but no commands detected.\n <= fail service unavailable.\n '''\n\n def __init__(self):\n # See example_state.py for basic explanations.\n super(SaraNLUspr, self).__init__(outcomes=['understood', 'not_understood', 'fail'], input_keys=['sentence'],\n output_keys=['answer'])\n\n serviceName = \"/answer_question\"\n\n Logger.loginfo(\"waiting forservice: \" + serviceName)\n rospy.wait_for_service(serviceName)\n\n self.service = rospy.ServiceProxy(serviceName, AnswerQuestion)\n\n def execute(self, userdata):\n\n # Call the NLU service\n response = self.service(String(userdata.sentence))\n\n # Checking the validity of the response\n if response.str.data is \"\":\n userdata.answer = response.str.data\n return \"fail\"\n\n userdata.answer = response.str.data\n return \"understood\"\n","sub_path":"sara_flexbe_states/src/sara_flexbe_states/sara_nlu_spr.py","file_name":"sara_nlu_spr.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"464731086","text":"# encoding=utf8\nimport socket\nimport re\nimport time\nimport sys\nimport _thread\nimport codecs\n\nthreshold = 5 * 60 # five minutes, make this whatever you want\n\n\nclass irc:\n\n def __init__(self, config):\n self.config = config\n self.ircBuffer = \"\"\n self.connect()\n\n def nextMessage(self):\n while \"\\r\\n\" not in self.ircBuffer:\n read = self.sock.recv(1024)\n if not read:\n print(\"Connection was lost\")\n self.connect() # Reconnect.\n else:\n self.ircBuffer += read.decode()\n line, self.ircBuffer = self.ircBuffer.split(\"\\r\\n\", 1)\n if line.startswith(\"PING\"):\n self.sock.send(str(line.replace(\"PING\", \"PONG\") + \"\\r\\n\").encode())\n return line\n\n def check_for_message(self, data):\n if re.match(\n r'^:[a-zA-Z0-9_]+\\![a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.tmi\\.twitch\\.tv' +\n '|\\.testserver\\.local) PRIVMSG #[a-zA-Z0-9_]+ :.+$', data):\n return True\n\n def check_for_join(self, data):\n if re.match(\n r'^:[a-zA-Z0-9_]+\\![a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.tmi\\.twitch\\.tv' +\n '|\\.testserver\\.local) JOIN #[a-zA-Z0-9_]', data):\n return True\n\n def check_for_part(self, data):\n if re.match(\n r'^:[a-zA-Z0-9_]+\\![a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.tmi\\.twitch\\.tv' +\n '|\\.testserver\\.local) PART #[a-zA-Z0-9_]', data):\n return True\n\n def check_is_command(self, message, valid_commands):\n for command in valid_commands:\n if command == message:\n return True\n\n def check_for_connected(self, data):\n if re.match(r'^:.+ 001 .+ :connected to TMI$', data):\n return True\n\n def get_logged_in_users(self, data):\n if data.find('353'):\n return True\n\n def check_for_ping(self, data):\n last_ping = time.time()\n # if data[0:4] == \"PING\":\n if data.find('PING') != -1:\n self.sock.send(str('PONG ' + data.split()[1] + '\\r\\n').encode())\n last_ping = time.time()\n if (time.time() - last_ping) > threshold:\n sys.exit()\n\n def get_message(self, data):\n return re.match(\n r'^:(?P.*?)!.*?PRIVMSG (?P.*?) ' +\n ':(?P.*)', data).groupdict()\n\n def check_login_status(self, data):\n if re.match(\n r'^:(testserver\\.local|tmi\\.twitch\\.tv) NOTICE \\* :' +\n 'Login unsuccessful\\r\\n$', data):\n return False\n else:\n return True\n\n def send_message(self, channel, message):\n # message can be any of the formats:\n # None - sends nothing\n # String - sends this line as a message\n # List - sends each line individually.\n # -- technically since this is recursive you can have a tree\n # -- [[\"1\", [\"2\", \"3\"]], \"4\"] will send \"1\", \"2\", \"3\", \"4\".\n if not message:\n return\n if isinstance(message, str):\n self.sock.send('PRIVMSG %s :%s\\r\\n'.encode() % (\n channel.encode(), message.encode()))\n if type(message) == list:\n for line in message.decode(\"utf8\"):\n self.send_message(channel, line)\n\n def connect(self):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.settimeout(10)\n try:\n print((\n \"Connecting to {}:{}\".format(self.config[\n 'server'], self.config['port'])))\n sock.connect((self.config['server'], self.config['port']))\n except:\n print(('Cannot connect to server (%s:%s).' % (\n self.config['server'], self.config['port']), 'error'))\n sys.exit()\n sock.settimeout(None)\n sock.send('USER %s\\r\\n'.encode() % self.config['username'].encode())\n sock.send('PASS %s\\r\\n'.encode() % self.config[\n 'oauth_password'].encode())\n sock.send('NICK %s\\r\\n'.encode() % self.config['username'].encode())\n self.sock = sock\n loginMsg = self.nextMessage()\n # :tmi.twitch.tv NOTICE * :Login unsuccessful\n # or\n # :tmi.twitch.tv 001 theepicsnail :Welcome, GLHF!\n if \"unsuccessful\" in loginMsg:\n print(\n \"Failed to login. Check your oath_password and username \" +\n \"in src/config/config.py\")\n sys.exit(1)\n # Wait until we're ready before starting stuff.\n while \"376\" not in self.nextMessage():\n pass\n self.join_channels(self.channels_to_string(self.config['channels']))\n\n def channels_to_string(self, channel_list):\n channels = [''.join(channel_list)]\n print(channels)\n return channels\n\n def join_channels(self, channels):\n print(('Joining channels %s.' % channels[0]))\n self.sock.send('JOIN %s\\r\\n'.encode() % channels[0].encode())\n print('Joined channels.')\n\n def leave_channels(self, channels):\n print(('Leaving channels %s,' % channels[0]))\n self.sock.send('PART %s\\r\\n'.encode() % channels[0].encode())\n print('Left channels.')\n","sub_path":"src/lib/irc.py","file_name":"irc.py","file_ext":"py","file_size_in_byte":5184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351600348","text":"\n\nfrom xai.brain.wordbase.verbs._lubricate import _LUBRICATE\n\n#calss header\nclass _LUBRICATING(_LUBRICATE, ):\n\tdef __init__(self,): \n\t\t_LUBRICATE.__init__(self)\n\t\tself.name = \"LUBRICATING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"lubricate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_lubricating.py","file_name":"_lubricating.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"581789800","text":"import matplotlib.pyplot as plt\nimport math\nimport matplotlib.pylab as lab\n\n\n\nplt.ion()\n\nx0,y0 = 0.0,2.0\n\nlist_x,list_y, list_z = [],[],[]\n\nx_end= 10.0\n\nh1=10**(-2)\nh2 = 10**(-5)\n\n\nwhile x0 < x_end:\n x1 = x0+h1\n y1 = y0+ h1*( 100*y0 - 101 * math.exp(-x0) - 100)\n x0,y0 = x1,y1\n list_x.append(x0)\n list_y.append(y0)\n\nplt.plot(list_x,list_y,label = \"h = $10^{-2}$\",color = \"red\")\nplt.legend()\n\ny0,x0 = 0.0,2.0\nlist_x,list_y,list_ye = [] , [] , []\nx_end = 10.0\n\nwhile x0 < x_end:\n x1 = x0+h2\n y1 = y0+ h2*( 100*y0 - 101 * math.exp(-x0) - 100)\n x0,y0 = x1,y1\n list_x.append(x0)\n list_y.append(y0)\n\nplt.plot(list_x,list_y,label = \"h = $10^{-5}$\",color = \"blue\")\nplt.legend()\n\ny0,x0 = 0.0,2.0\nlist_x,list_y,list_ye = [] , [] , []\nx_end = 10.0\n\nwhile x0 < x_end:\n x1 = x0+h1\n y1 = y0+ h1*( 100*y0 - 101 * math.exp(-x0) - 100)\n x0,y0 = x1,y1\n list_x.append(x0)\n list_y.append(y0)\n list_ye.append(math.exp(-x0)+1)\n\nplt.plot(list_x,list_ye , label = \"exato\" , color = \"g\")\nplt.legend(loc = \"upper left\")\naxes = plt.gca()\naxes.set_ylim([-2,2])\n\n\n","sub_path":"p1/p1_3/p1_3.py","file_name":"p1_3.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"9046535","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='User',\n fields=[\n ('user_id', models.AutoField(serialize=False, primary_key=True)),\n ('user_email', models.CharField(max_length=50)),\n ('join_date', models.DateTimeField(verbose_name=b'date of join')),\n ('user_full_name', models.CharField(max_length=50)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"userpanel/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"311383707","text":"keys = []\n\nwith open(\"input.txt\") as file:\n for line in file:\n keys.append(int(line.strip()))\n\ndivisor = 20201227\nsubject_number = 7\n\nvalue = 1\nn = 0\n\nwhile value != keys[0]:\n value *= subject_number\n value = value % divisor\n n += 1\n\nvalue = 1\nfor i in range(n):\n value *= keys[1]\n value = value % divisor\n\nprint(value)","sub_path":"2020/25/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"275485611","text":"\r\nimport torch\r\nfrom pytorch_models.utils import create_mask, map_dict_builder\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom collections import OrderedDict\r\nimport logging\r\nimport numpy as np\r\nfrom collections import Counter\r\nimport pandas as pd\r\n\r\n\r\n\r\nfrom pytorch_models.xfmrs import docs2wordpiece, get_embeddings, CLS\r\nfrom pytorch_models.utils import pad1D, pad2D, truncate_sequences\r\n\r\n\r\nfrom constants import *\r\n\r\nclass DocSimilarityDataset(Dataset):\r\n \"\"\"\r\n This dataset contains a list of numbers in the range [a,b] inclusive\r\n \"\"\"\r\n def __init__(self, ids, X, xfmr_type, xfmr_dir, \\\r\n max_len = 512, \r\n num_workers = 6, \r\n batch_size = 100,\r\n ):\r\n super(DocSimilarityDataset, self).__init__()\r\n\r\n logging.info(\"DocSimilarityDataset\")\r\n \r\n self.ids = ids\r\n self.X = X\r\n self.xfmr_type = xfmr_type\r\n self.xfmr_dir = xfmr_dir\r\n \r\n self.max_len = max_len\r\n self.num_workers = num_workers\r\n self.batch_size = batch_size\r\n\r\n\r\n # Sequence count \r\n self.seq_count = len(self.X)\r\n \r\n # Get word pieces\r\n wp_toks, wp_ids = docs2wordpiece( \\\r\n docs = self.X,\r\n model_type = self.xfmr_type,\r\n model_dir = self.xfmr_dir)\r\n logging.info(\"\\tWords mapped to IDs\")\r\n \r\n # Double check token mapping\r\n for w in wp_toks:\r\n assert w[0] == CLS\r\n \r\n # Truncate long documents\r\n wp_ids = truncate_sequences(wp_ids, self.max_len, bin_size=20)\r\n logging.info(\"\\tSequences truncated\")\r\n \r\n # Get embeddings\r\n logging.info(\"\\tGenerating sequence embeddings\")\r\n seq_embed = get_embeddings( \\\r\n word_piece_ids = wp_ids, \r\n tok_idx = None, \r\n model_type = self.xfmr_type, \r\n model_dir = self.xfmr_dir, \r\n seq_length = self.max_len,\r\n num_workers = self.num_workers,\r\n batch_size = self.batch_size)\r\n logging.info(\"\\tSequence embeddings extracted\")\r\n\r\n # Check lengths \r\n for i, e in zip(wp_ids, seq_embed):\r\n assert len(i) == len(e)\r\n\r\n # Get document-level embedding\r\n self.X_embed = torch.Tensor([seq[0] for seq in seq_embed])\r\n logging.info(\"\\tExtracted document-level representation\")\r\n \r\n assert len(self.X_embed) == len(self.X)\r\n assert len(self.ids) == len(self.X_embed)\r\n \r\n def __len__(self):\r\n return self.seq_count\r\n \r\n def __getitem__(self, index):\r\n '''\r\n Define how to iterate across documents\r\n '''\r\n return (self.ids[index], self.X_embed[index])\r\n\r\n ","sub_path":"code/pytorch_models/doc_similarity_dataset.py","file_name":"doc_similarity_dataset.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"463225909","text":"\"\"\"Decorator to quickly add statsd (graphite) instrumentation to Celery\ntask functions.\n\nWith some slight modification, this could be used to instrument just\nabout any (non-celery) function and be made abstract enough to customize\nmetric names, etc.\n\nStats reported include number of times the task was accepted by a worker\n(`started`), the number of successes, and the number of times the task\nraised an exception. In addition, it also reports how long the task took\nto complete. Usage:\n\n>>> @task\n>>> @instrument_task\n>>> def mytask():\n>>> # do stuff\n>>> pass\n\nPlease note that the order of decorators is important to Celery. See\nhttp://ask.github.com/celery/userguide/tasks.html#decorating-tasks\nfor more information.\n\nUses `simple_decorator` from\nhttp://wiki.python.org/moin/PythonDecoratorLibrary#Property_Definition\n\nLimitation: Does not readily work on subclasses of celery.tasks.Task\nbecause it always reports `task_name` as 'run'\n\"\"\"\n\n# statsd instrumentation\nfrom celery import current_app\nimport statsd\n\n@simple_decorator\ndef instrument_task(func):\n \"\"\"Wraps a celery task with statsd instrumentation code\"\"\"\n\n def instrument_wrapper(*args, **kwargs):\n stats_conn = statsd.connection.Connection(\n host = current_app.conf['STATSD_HOST'],\n port = current_app.conf['STATSD_PORT'],\n sample_rate = 1)\n\n task_name = func.__name__\n\n counter = statsd.counter.Counter('celery.tasks.status',stats_conn)\n counter.increment('{task_name}.started'.format(**locals()))\n\n timer = statsd.timer.Timer('celery.tasks.duration', stats_conn)\n timer.start()\n\n try:\n ret = func(*args, **kwargs)\n except:\n counter.increment('{task_name}.exceptions'.format(**locals()))\n raise\n else:\n counter.increment('{task_name}.success'.format(**locals()))\n timer.stop('{task_name}.success'.format(**locals()))\n return ret\n finally:\n try:\n del timer\n del counter\n del stats_conn\n except:\n pass\n\n return instrument_wrapper\n\ndef simple_decorator(decorator):\n \"\"\"Borrowed from:\n http://wiki.python.org/moin/PythonDecoratorLibrary#Property_Definition\n\n Original docstring:\n This decorator can be used to turn simple functions\n into well-behaved decorators, so long as the decorators\n are fairly simple. If a decorator expects a function and\n returns a function (no descriptors), and if it doesn't\n modify function attributes or docstring, then it is\n eligible to use this. Simply apply @simple_decorator to\n your decorator and it will automatically preserve the\n docstring and function attributes of functions to which\n it is applied.\"\"\"\n def new_decorator(f):\n g = decorator(f)\n g.__name__ = f.__name__\n g.__module__ = f.__module__ # or celery throws a fit\n g.__doc__ = f.__doc__\n g.__dict__.update(f.__dict__)\n return g\n # Now a few lines needed to make simple_decorator itself\n # be a well-behaved decorator.\n new_decorator.__name__ = decorator.__name__\n new_decorator.__doc__ = decorator.__doc__\n new_decorator.__dict__.update(decorator.__dict__)\n return new_decorator\n\n","sub_path":"dockerized-gists/2018362/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"574366197","text":"#!/usr/bin/env python\n\n\n\"\"\"\nhttp://practice.geeksforgeeks.org/problems/index-of-first-1-in-a-sorted-array-of-0s-and-1s/0\n\"\"\"\n\n\ndef find_first_one(array):\n if array[-1] == 0:\n return -1\n if array[0] == 1:\n return 0\n \n size = len(array)\n if size == 1:\n return 0\n left = 0\n right = size - 1\n middle = int((right - left)/2) + left\n while True:\n print(left, right, middle, array[middle:middle+2])\n if array[middle:middle+2] == [0, 1]:\n return middle+1\n elif array[middle:middle+2] == [0, 0]:\n left = middle\n middle = int((right - left)/2) + left\n elif array[middle:middle+2] == [1, 1]:\n right = middle\n middle = int((right - left)/2) + left\n\n\nt = int(input())\nfor i in range(0, t):\n n = int(input())\n arr = [int(v) for v in input().strip().split(' ')]\n print(find_first_one(arr))\n","sub_path":"basic/indexoffirstone.py","file_name":"indexoffirstone.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"1585643","text":"# ----------------------\n# Modifed from Hull_HW12.py\n# 11162020\n# Functions to be used by Hull_HW12.py\n# ----------------------\n\n# %%\n# ----------------------------------------------------------------------------------\n# Define modules\n# ----------------------------------------------------------------------------------\nimport pandas as pd\n# import geopandas as gpd\nimport numpy as np\nimport json\nimport urllib.request as req\nimport urllib\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import MaxAbsScaler\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.preprocessing import Normalizer\nfrom sklearn.preprocessing import QuantileTransformer\nfrom sklearn.preprocessing import PowerTransformer\nimport geopandas as gpd\nfrom shapely.geometry import Point\n\n\n# %%\n# ----------------------------------------------------------------------------------\n# Define functions\n# ----------------------------------------------------------------------------------\ndef clean_dataset(df):\n \"\"\"Removes all infinity, nan, and numbers out of range\n from: https://stackoverflow.com/questions/31323499/\n sklearn-error-valueerror-input-contains-nan-infinity-or-a-value-too-large-for\n \"\"\"\n assert isinstance(df, pd.DataFrame), \"df needs to be a pd.DataFrame\"\n df.dropna(inplace=True)\n indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)\n return df[indices_to_keep].astype(np.float64)\n\n\ndef makemodel(x, y):\n \"\"\"returns a multiple regression model\n\n using sklearn linear regression tool\n\n returns the model object = model\n returns the score = score\n\n takes 2 required variables, x and y\n x is the predictive (independent) variable(s)\n y is the predicted (dependent) variable\n\n both x and y need to be pandas dataframes, where x\n contains ALL of the predictive (independent) variables\n to be used.\n\n IMPORTANT: 'x' needs to be a list of column titles, even\n if only one predictive variable is passed\n\n if dimensions[x] = 1, then single predictive variable\n if dimensions[x] > 1, then multiple predictive variables\n\n example:\n x = train_week[['flow_tm1']] # use double brackets here\n y = train_week['flow'] # use single brackets here\n m, x = makemodel(x,y)\n \"\"\"\n\n model = LinearRegression()\n y = y.values\n if x.shape[1] == 1:\n x = x.values.reshape(-1, 1)\n model.fit(x, y)\n score = model.score(x, y)\n return model, score\n\n\ndef extractmasonet(base_url, args):\n \"\"\"takes\n 1) a string of 'base_url'\n 2) a dictionary of api arguments\n 3) a string of 'token'\n specific to the metamot API\n\n See more about metamot:\n https://developers.synopticdata.com/mesonet/explorer/\n https://developers.synopticdata.com/about/station-variables/\n https://developers.synopticdata.com/mesonet/v2/getting-started/\n\n returns a dictionary\n containing the response of a JSON 'query'\n \"\"\"\n\n # concat api arguments (careful with commas)\n apiString = urllib.parse.urlencode(args)\n apiString = apiString.replace('%2C', ',')\n\n # concat the API string to the base_url to create full_URL\n fullUrl = base_url + '?' + apiString\n print('full url =', fullUrl, '\\n')\n\n # process data (use url to query data)\n # return as dictionary\n response = req.urlopen(fullUrl)\n responseDict = json.loads(response.read())\n\n return responseDict\n\n\ndef assemble_data_masonet(base_url, args, stationDict,\n data_join,\n station_condition='ACTIVE',\n station_name=False):\n \"\"\"takes the basics for a data extraction\n and pulls out only the stations that meet a certain condition\n\n base_url = url at masonet for extraction\n args = arguments, including token and parameters\n station_Dict = a previously created response Dictionary\n of stations\n data_join = an external pandas dataset to join the data to.\n Must contain a datetime index\n station_condition = the condition used to crete response for data\n default is to look for only active stations. Only acceptable\n values are 'ACTIVE' and 'INACTIVE'\n station_name = by default FALSE. If specified a string, will\n only look for stations by the name specified.\n\n note by default resamples the data daily on the max\n\n returns a panda dataframe containint he data wanted\n \"\"\"\n\n # 2b) Assemble all relevant dictionaries into a list, based on station name\n stationList = []\n for station in stationDict['STATION']:\n # station name and if is active\n print(station['STID'], station['STATUS'], station[\"PERIOD_OF_RECORD\"],\n \"\\n\")\n # time series data args\n args['stids'] = station['STID']\n # extract data from active/inactive stations\n if station['STATUS'] == station_condition:\n # if a station name is specified\n if station_name is not False:\n if (station['STID'] == station_name):\n # extract data\n responseDict = extractmasonet(base_url, args)\n # create a list of all stations\n stationList.append(responseDict)\n # if station name is not specified\n else:\n # extract data\n responseDict = extractmasonet(base_url, args)\n # create a list of all stations\n stationList.append(responseDict)\n\n # Checks to see if the API Call returned valid data\n if stationList[0]['SUMMARY']['RESPONSE_CODE'] == -1:\n print(stationList[0]['SUMMARY']['RESPONSE_MESSAGE'])\n return \"nothing\"\n\n # 2d) convert all data pd\n # list of keys under observations (for use in inner loop)\n for station in stationList:\n # if station id has the station_name, or station_name is False\n if (station['STATION'][0]['STID'] == station_name) or \\\n (station_name is False):\n print(station['STATION'][0]['STID'])\n for key, value in station[\"STATION\"][0]['OBSERVATIONS'].items():\n # creates a list of value related to key\n # temp = station[\"STATION\"][0]['OBSERVATIONS'][key]\n if (key == 'date_time'):\n # create index\n df = pd.DataFrame({key: pd.to_datetime(value)})\n else:\n # concat df\n df = pd.concat([df, pd.DataFrame({key: value})], axis=1)\n # # set index for df\n df = df.set_index('date_time')\n # resample on day\n df = df.resample('D').max()\n # join df to data dataframe\n data_join = data_join.join(df,\n rsuffix=\"_\"+station['STATION'][0]['STID'\n ])\n df = pd.DataFrame()\n return data_join\n\n\ndef Kelvin_2_Faren(K_temp):\n \"\"\"takes a temperature in Kelvin\n\n returns a temperature in Fareignheit\n \"\"\"\n return (K_temp - 273.15)*(9/5) + 32\n\n\ndef norm_it(startdate, enddate, dfin, dfname, l_back=1, toscale=True,\n cscaler=MinMaxScaler(feature_range=(0, 1))):\n \"\"\"\n This function noramlizes a column of data from a pandas dataframe\n using the predefined scaler feature of sklearn\n to create a ~ normal distribution\n and allow for better fitting between different types of variables\n in a multivariable regression\n\n It also lags the data by a specified number of weeks (look_back)\n\n Takes:\n A start and end date (strings)\n startdate =\n enddate =\n A dataframe (pandas)\n dfin =\n The name of a single column of data to normalize (string)\n dfname =\n A specified number of look backs (integer)\n l_back = [1]\n A Boolean to decide if to scale the data (i.e. if not desired or already done)\n toscale = [True]\n An optional scaler\n cscaler = [MinMaxScaler(feature_range=(0, 1))]\n\n Returns:\n The dataframe with a column of normalized, and lagged, data\n The scaler model that can be used to 'inverse' transform\n \"\"\"\n\n # # subset\n dfin = dfin.loc[startdate:enddate]\n if toscale is True:\n # # normalize\n scaler = cscaler\n # # add normalized to dataset\n dfin[dfname+'_norm'] = scaler.fit_transform(dfin[\n dfname].to_numpy().reshape(-1, 1))\n # # lag\n dfin[dfname+'_norm'+str(l_back)] = dfin[dfname+'_norm'].shift(l_back)\n return dfin, scaler\n else:\n dfin[dfname+str(l_back)] = dfin[dfname].shift(l_back)\n return dfin\n\n\n\ndef denorm_it(val, scaler):\n \"\"\"De normalizes a single value\n\n Takes:\n A scaled value (a single number)\n val =\n A scaler from sklearn\n scaler =\n \"\"\"\n # # inverse transform a single value\n newval = scaler.inverse_transform(val.reshape(1, -1))\n return newval\n\n\ndef investigate_gdp(gdp):\n \"\"\"The function reads in a geodataframe\n with the intention of printing interesting\n attributes of that dataframe.\n\n mostly print statements\n\n returns the given gdp\n \"\"\"\n\n print(\"Details from the given geodataframe: \", \"\\n\")\n # initial attributes\n print(\"type =\", type(gdp), \"\\n\")\n print(\"columns =\", gdp.columns, \"\\n\")\n print(\"shape =\", gdp.shape, \"\\n\")\n gdp.head()\n print(\"\\n\")\n\n # Looking at the read-only method\n print(vars(gdp))\n print(\"geom =\", gdp.geom_type, \"\\n\")\n print(\"crs =\", gdp.crs, \"\\n\")\n print(\"spatial bounds =\", gdp.total_bounds, \"\\n\")\n\n\ndef add_pt_gdf(point_l, crs_i, gpd_in, nm_pts):\n \"\"\"The function reads in a numpy array of one or multiple spatial data values\n with the intention of converting that into a pandas dataframe\n and then appending this to the end of an existing pandas geodataframe\n\n inputs:\n point_l = a 2-D numpy array of spatial data values (like easting, northing)\n or (like lat, long)\n crs_in = the coordinate system of the dataframe, a crs object\n gpd_in = the pandas dataframe containing geodataframe info\n nm_pts = the name you would like to give the new row in the dataframe\n\n output:\n the inputted pandas dataframe container of gdp and other info\n with a new record containing a gdp oflat / long data\n \"\"\"\n\n # make these into spatial features\n point_geom = [Point(xy) for xy in point_l]\n\n # create point_df geodataframe\n point_df = gpd.GeoDataFrame(point_geom, columns=['geometry'],\n crs=crs_i)\n\n # add to gpd_df\n gpd_in = gpd_in.append({'names': nm_pts,\n 'file': '', 'gpd': point_df},\n ignore_index=True)\n\n return gpd_in\n\n# %%\n","sub_path":"Submissions/Code_Submission2/Hull_HW13_fxns.py","file_name":"Hull_HW13_fxns.py","file_ext":"py","file_size_in_byte":11044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"425437020","text":"#**********************************************************************\n# Copyright 2020 Advanced Micro Devices, Inc\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#********************************************************************\nimport time\nimport numpy as np\n\nfrom pxr import Usd, UsdAppUtils, Glf, Tf, UsdGeom\nfrom pxr import UsdImagingGL, UsdImagingLite\n\nimport bpy\nimport bgl\n\nfrom .engine import Engine\nfrom ..utils import gl, time_str\nfrom ..utils import usd as usd_utils\nfrom ..export import object, world\n\nfrom ..utils import logging\nlog = logging.Log(tag='final_engine')\n\n\nclass FinalEngine(Engine):\n \"\"\" Final render engine \"\"\"\n\n TYPE = 'FINAL'\n\n def __init__(self, render_engine):\n super().__init__(render_engine)\n\n self.width = 0\n self.height = 0\n\n self.render_layer_name = None\n\n self.status_title = \"\"\n\n def notify_status(self, progress, info):\n \"\"\" Display export/render status \"\"\"\n self.render_engine.update_progress(progress)\n self.render_engine.update_stats(self.status_title, info)\n log(f\"Status [{progress:.2}]: {info}\")\n\n def _render_gl(self, scene):\n CLEAR_COLOR = (0.0, 0.0, 0.0, 0.0)\n CLEAR_DEPTH = 1.0\n\n # creating draw_target\n draw_target = Glf.DrawTarget(self.width, self.height)\n draw_target.Bind()\n draw_target.AddAttachment(\"color\", bgl.GL_RGBA, bgl.GL_FLOAT, bgl.GL_RGBA)\n\n # creating renderer\n renderer = UsdImagingGL.Engine()\n self._sync_render_settings(renderer, scene)\n\n # setting camera\n self._set_scene_camera(renderer, scene)\n\n renderer.SetRenderViewport((0, 0, self.width, self.height))\n renderer.SetRendererAov('color')\n\n bgl.glEnable(bgl.GL_DEPTH_TEST)\n bgl.glViewport(0, 0, self.width, self.height)\n bgl.glClearColor(*CLEAR_COLOR)\n bgl.glClearDepth(CLEAR_DEPTH)\n bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)\n\n root = self.stage.GetPseudoRoot()\n params = UsdImagingGL.RenderParams()\n params.renderResolution = (self.width, self.height)\n params.frame = Usd.TimeCode.Default()\n params.clearColor = CLEAR_COLOR\n\n try:\n renderer.Render(root, params)\n except Exception as e:\n log.error(e)\n\n self.update_render_result({\n 'Combined': gl.get_framebuffer_data(self.width, self.height)\n })\n\n draw_target.Unbind()\n\n # it's important to clear data explicitly\n draw_target = None\n renderer = None\n\n def _render(self, scene):\n # creating renderer\n renderer = UsdImagingLite.Engine()\n self._sync_render_settings(renderer, scene)\n\n renderer.SetRenderViewport((0, 0, self.width, self.height))\n renderer.SetRendererAov('color')\n\n # setting camera\n self._set_scene_camera(renderer, scene)\n\n params = UsdImagingLite.RenderParams()\n render_images = {\n 'Combined': np.empty((self.width, self.height, 4), dtype=np.float32)\n }\n\n renderer.Render(self.stage.GetPseudoRoot(), params)\n\n time_begin = time.perf_counter()\n while True:\n if self.render_engine.test_break():\n break\n\n percent_done = renderer.GetRenderStats()['percentDone']\n self.notify_status(percent_done / 100, f\"Render Time: {time_str(time.perf_counter() - time_begin)} | Done: {round(percent_done)}%\")\n\n if renderer.IsConverged():\n break\n\n renderer.GetRendererAov('color', render_images['Combined'].ctypes.data)\n self.update_render_result(render_images)\n\n renderer.GetRendererAov('color', render_images['Combined'].ctypes.data)\n self.update_render_result(render_images)\n\n # its important to clear data explicitly\n renderer = None\n\n def _set_scene_camera(self, renderer, scene):\n if scene.hdusd.final.nodetree_camera != '' and scene.hdusd.final.data_source:\n usd_camera = UsdAppUtils.GetCameraAtPath(self.stage, scene.hdusd.final.nodetree_camera)\n else:\n usd_camera = UsdAppUtils.GetCameraAtPath(self.stage, Tf.MakeValidIdentifier(scene.camera.data.name))\n \n gf_camera = usd_camera.GetCamera()\n renderer.SetCameraState(gf_camera.frustum.ComputeViewMatrix(),\n gf_camera.frustum.ComputeProjectionMatrix())\n\n def render(self, depsgraph):\n if not self.stage:\n return\n\n scene = depsgraph.scene\n log(f\"Start render [{self.width}, {self.height}]. \"\n f\"Hydra delegate: {scene.hdusd.final.delegate}\")\n if self.render_engine.bl_use_gpu_context:\n self._render_gl(scene)\n else:\n self._render(scene)\n\n self.notify_status(1.0, \"Finish render\")\n\n def sync(self, depsgraph):\n scene = depsgraph.scene\n settings = scene.hdusd.final\n view_layer = depsgraph.view_layer\n\n self.render_layer_name = view_layer.name\n self.status_title = f\"{scene.name}: {self.render_layer_name}\"\n self.notify_status(0.0, \"Start syncing\")\n\n # Preparations for syncing\n time_begin = time.perf_counter()\n\n border = ((0, 0), (1, 1)) if not scene.render.use_border else \\\n ((scene.render.border_min_x, scene.render.border_min_y),\n (scene.render.border_max_x - scene.render.border_min_x,\n scene.render.border_max_y - scene.render.border_min_y))\n\n screen_width = int(scene.render.resolution_x * scene.render.resolution_percentage / 100)\n screen_height = int(scene.render.resolution_y * scene.render.resolution_percentage / 100)\n\n self.width = int(screen_width * border[1][0])\n self.height = int(screen_height * border[1][1])\n\n self._sync(depsgraph)\n\n usd_utils.set_variant_delegate(self.stage, settings.is_gl_delegate)\n\n if self.render_engine.test_break():\n log.warn(\"Syncing stopped by user termination\")\n return\n\n # setting enabling/disabling gpu context in render() method\n self.render_engine.bl_use_gpu_context = settings.is_gl_delegate\n\n log.info(\"Scene synchronization time:\", time_str(time.perf_counter() - time_begin))\n self.notify_status(0.0, \"Start render\")\n\n def _sync(self, depsgraph):\n pass\n\n def update_render_result(self, render_images):\n result = self.render_engine.begin_result(0, 0, self.width, self.height,\n layer=self.render_layer_name)\n render_passes = result.layers[0].passes\n\n images = []\n for p in render_passes:\n image = render_images.get(p.name)\n if image is None:\n image = np.zeros((self.width, self.height, p.channels), dtype=np.float32)\n\n if p.channels != image.shape[2]:\n image = image[:, :, 0:p.channels]\n\n images.append(image.flatten())\n\n # efficient way to copy all AOV images\n render_passes.foreach_set('rect', np.concatenate(images))\n self.render_engine.end_result(result)\n\n def _sync_render_settings(self, renderer, scene):\n settings = scene.hdusd.final\n\n renderer.SetRendererPlugin(settings.delegate)\n if settings.delegate == 'HdRprPlugin':\n hdrpr = settings.hdrpr\n quality = hdrpr.quality\n denoise = hdrpr.denoise\n\n renderer.SetRendererSetting('renderMode', 'batch')\n renderer.SetRendererSetting('progressive', True)\n renderer.SetRendererSetting('enableAlpha', False)\n\n renderer.SetRendererSetting('renderDevice', hdrpr.device)\n renderer.SetRendererSetting('renderQuality', hdrpr.render_quality)\n renderer.SetRendererSetting('coreRenderMode', hdrpr.render_mode)\n\n renderer.SetRendererSetting('aoRadius', hdrpr.ao_radius)\n\n renderer.SetRendererSetting('maxSamples', hdrpr.max_samples)\n renderer.SetRendererSetting('minAdaptiveSamples', hdrpr.min_adaptive_samples)\n renderer.SetRendererSetting('varianceThreshold', hdrpr.variance_threshold)\n\n renderer.SetRendererSetting('maxRayDepth', quality.max_ray_depth)\n renderer.SetRendererSetting('maxRayDepthDiffuse', quality.max_ray_depth_diffuse)\n renderer.SetRendererSetting('maxRayDepthGlossy', quality.max_ray_depth_glossy)\n renderer.SetRendererSetting('maxRayDepthRefraction', quality.max_ray_depth_refraction)\n renderer.SetRendererSetting('maxRayDepthGlossyRefraction',\n quality.max_ray_depth_glossy_refraction)\n renderer.SetRendererSetting('maxRayDepthShadow', quality.max_ray_depth_shadow)\n renderer.SetRendererSetting('raycastEpsilon', quality.raycast_epsilon)\n renderer.SetRendererSetting('enableRadianceClamping', quality.enable_radiance_clamping)\n renderer.SetRendererSetting('radianceClamping', quality.radiance_clamping)\n\n renderer.SetRendererSetting('enableDenoising', denoise.enable)\n renderer.SetRendererSetting('denoiseMinIter', denoise.min_iter)\n renderer.SetRendererSetting('denoiseIterStep', denoise.iter_step)\n\n\nclass FinalEngineScene(FinalEngine):\n def _sync(self, depsgraph):\n stage = self.cached_stage.create()\n\n UsdGeom.SetStageMetersPerUnit(stage, 1)\n UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)\n\n root_prim = stage.GetPseudoRoot()\n\n objects_len = sum(1 for _ in object.ObjectData.depsgraph_objects(\n depsgraph, use_scene_cameras=False))\n for i, obj_data in enumerate(object.ObjectData.depsgraph_objects(\n depsgraph, use_scene_cameras=False)):\n if self.render_engine.test_break():\n return\n\n self.notify_status(0.0, f\"Syncing object {i}/{objects_len}: {obj_data.object.name}\")\n\n object.sync(root_prim, obj_data)\n\n world.sync(root_prim, depsgraph.scene.world)\n\n object.sync(stage.GetPseudoRoot(), object.ObjectData.from_object(depsgraph.scene.camera),\n scene=depsgraph.scene)\n\n\nclass FinalEngineNodetree(FinalEngine):\n def _sync(self, depsgraph):\n settings = depsgraph.scene.hdusd.final\n output_node = bpy.data.node_groups[settings.data_source].get_output_node()\n\n if output_node is None:\n log.warn(\"Syncing stopped due to invalid output_node\", output_node)\n return\n\n stage = output_node.cached_stage()\n self.cached_stage.assign(stage)\n","sub_path":"src/hdusd/engine/final_engine.py","file_name":"final_engine.py","file_ext":"py","file_size_in_byte":11200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"279791001","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n## plot depth of deep isopycnal for a random day\nrand_day = np.random.randint(0,time_len)\ndep_map = max_dep_bob_isoZ[rand_day, :, :]\nhy_dt_rand = hy_dt[rand_day]\n\nplt.figure(figsize=(12,5))\nplt.subplot(1,1,1)\nplt.pcolormesh(lon_bob, lat_bob, dep_map.T, cmap=plt.cm.rainbow)\nplt.title('Maximum depths of control volume on %s (day %s)' %(hy_dt_rand.strftime('%b-%d-%Y'), rand_day))\nplt.clim(50,180)\nplt.colorbar()\nplt.xlim(78,100)\nplt.ylim(10,25)\nplt.axis('equal')\nplt.show()\n\nplt.savefig(\"../py_plots/max_dep_map_%s.png\" %(rand_day))\n## Make cross-section movie\n\n\n#plot mean velocity across southline versus average depth of deep isopyc in BoB\nmax_dep_bob_isoZ = dep_bob_isoZ.max(axis=1)\nmax_dep_isoZ_xboxmeans = max_dep_bob_isoZ[:, :-1, :] + np.diff(max_dep_bob_isoZ, axis=1)/2\nmax_dep_isoZ_xyboxmeans = max_dep_isoZ_xboxmeans[:, :, :-1] + np.diff(max_dep_isoZ_xboxmeans, axis=2)/2\ndA_mat_ma = np.ma.masked_where(max_dep_isoZ_xyboxmeans[0,...].mask, dA_mat)\nbob_area_atmaxdep = np.sum(dA_mat_ma.flatten())\ndA_bob_wghts = dA_mat_ma.flatten()/bob_area_atmaxdep\nmean_max_depth = np.sum(dA_bob_wghts*max_dep_isoZ_xyboxmeans.reshape(time_len,-1), axis=1)\n\nplt.figure(figsize=(13,5))\n\nax1 = plt.gca()\nax1.plot(hy_dt, vvel_sline_mean, color='red', label='mean velocity across 10N', alpha=0.6)\nax1.set_ylabel('Velocity (m/s)', color='red')\nax1.legend(loc=2)\n#ax1.set_ylim(33,34.5)\nplt.grid(True)\nplf.formatDates(ax1)\n\n\nax2 = ax1.twinx()\nax2.plot(hy_dt, mean_max_depth, color='green', label='Mean max depth (BoB)')\nax2.plot(hy_dt, mean_maxdep_sline, color='teal', label='Mean max depth (10N)')\n\n#plt.grid(True)\n#ax2.set_title(\"Mean depth of deep isopycnal and mean velocity across 10N\", fontsize=fntsz)\nax2.set_ylabel(\"Depth (m)\", fontsize=fntsz, color='green')\nax2.legend(loc=1)\nax2.set_ylim(150,80)\nplf.formatDates(ax2)\n\n#change colors of axis labels\nfor tl in ax1.get_yticklabels():\n tl.set_color('red') \n \nfor tl in ax2.get_yticklabels():\n tl.set_color('green') \nplt.show()\n\n\n#plot mean salinity across sline\n\n\nplt.figure(figsize=(13,5))\n\nax1 = plt.gca()\nax1.plot(hy_dt, sal_sline_smean, color='red', label='mean salinty across 10N')\nax1.set_ylabel('Salinity (PSU)')\nax1.legend(loc=0)\nax1.set_ylim(33.8,34.4)\nplt.grid(True)\nplf.formatDates(ax1)\nplt.show()\n\n\n\n## compute change in monthly mean salinity\ndsal_bob_monmean = np.diff(sal_bob_monmean)\ndsal_bob_monmean_err1 = np.diff(sal_bob_monmean_err, axis=1)\ndsal_bob_monmean_err1 = dsal_bob_monmean_err1.flatten()\ndsal_bob_monmean_err = np.diff(dsal_bob_monmean_err1, axis=0)/2 + dsal_bob_monmean_err1[:-1]\ndsal_bob_monmean_lower = dsal_bob_monmean-dsal_bob_monmean_err/2\ndsal_bob_monmean_upper = dsal_bob_monmean+dsal_bob_monmean_err/2\n\n\n## plot volume mean salinities\nplt.figure(figsize=(13,5))\nplt.subplot(1,1,1)\nax = plt.gca()\nax.plot(hy_dt, sal_bob_volmean1, color='blue', label='mean salinity (v1)')\nax.plot(hy_dt_mon, sal_volmean1_monmean,'o', color='blue')\n\nax.plot(hy_dt, sal_bob_volmean2+0.1, label='mean salinity (v2-offset)', color='red')\nax.plot(hy_dt_mon, sal_volmean2_monmean+0.1,'o', color='red')\n#ax.plot(hy_dt, sal_bob_volmean3, label='mean salinity (v3)')\nplt.grid(True)\nax.set_ylabel('Salinity (PSU)')\nax.legend(loc=0)\n#ax.set_ylim(33,34.5)\nplf.formatDates(ax)\nplt.show()\n\n\n## plot volume mean volumes\nplt.figure(figsize=(13,5))\nplt.subplot(1,1,1)\nax = plt.gca()\nax.plot(hy_dt, vol_tseries_pdens/1e14, label='volume timeseries (pdens)')\nax.plot(hy_dt, vol_tseries_sal/1e14, label='volume timeseries (sal)')\nax.plot(hy_dt, vol_tseries/1e14, label='volume timeseries (from dep)')\nplt.grid(True)\nax.set_ylabel('volume ($10^{14}$ m$^3$)')\nax.legend(loc=0)\n#ax.set_ylim(33,34.5)\nplf.formatDates(ax)\nplt.show()\n\n\n#plot all of the precip salt flux estimates\nplt.figure(figsize=(13,5))\nax = plt.subplot(1,1,1)\nax.plot(hy_dt, precip_smass_flux1/1e12, label='precip-salt flux (v1)', alpha=0.4)\nax.plot(hy_dt, 0.5+precip_smass_flux2/1e12, label='precip-salt flux+0.5 (v2)', alpha=0.4)\nax.plot(hy_dt, 1+precip_smass_flux3/1e12, label='precip-salt flux+1 (v3)', alpha=0.4)\nax.set_ylabel('Salt mass x 10$^{12}$(kg)')\nax.set_title(\"Virtual salt flux due to precipitation \", fontsize=fntsz)\nax.legend(loc=3)\nax.grid(True)\n#ax2.set_ylim(33,34.5)\nplf.formatDates(ax)\nplt.show()\n\n#plot salinity tendency associated with precip \nplt.figure(figsize=(13,5))\nax = plt.subplot(1,1,1)\nax.plot(hy_dt, precip_salflux*30, color='red', label='precip salflux (daily mean)', alpha=0.4)\nax.plot(hy_dt, precip_salflux_lp*30, color='crimson', label='%s day low passed' %(Tcut), linewidth=1.5)\nax.plot(hy_dt_mon, precip_salflux_monmean*30, 'o', color='crimson', label='monthly mean', linewidth=1.5)\nax.plot(hy_dt_mon_m1, dsal_bob_monmean, color='blue', label='monthly mean sal change', linewidth=1.5)\n#ax.fill_between(hy_dt_mon_m1, dsal_bob_monmean_lower, dsal_bob_monmean_upper, color='blue', alpha=0.5)\n\n#compute dsal from smass and compare\n#sal_bob_volmean2 = 1000*smass_bob_volsum1/(pdens_bob_volmean1*vol_tseries_pdens)\npdens_bob_volmean1_monmean = plf.compute_monmeans(hy_dt, pdens_bob_volmean1)[0]\nvol_tseries_monmean = plf.compute_monmeans(hy_dt, vol_tseries_sal)[0]\nsal_volmean3_monmean = 1000*smass_bob_monmean/(pdens_bob_volmean1_monmean*vol_tseries_monmean)\ndsal_volmean3_monmean = np.diff(sal_volmean3_monmean)\n\nax.plot(hy_dt_mon_m1, dsal_volmean3_monmean, color='purple', label='monthly mean sal change (v2)', linewidth=1.5)\n\nax.set_ylabel('Salinity change (PSU per month)')\nax.legend(loc=0)\nax.grid(True)\nplf.formatDates(ax)\nplt.show()\n\n#plot and compare salinities\nplt.figure(figsize=(13,5))\nplt.subplot(1,1,1)\nax = plt.gca()\nax.plot(hy_dt_mon, sal_volmean1_monmean,'o-', color='blue', label='mean salinity (v1)')\nax.plot(hy_dt_mon, sal_volmean2_monmean+0.1,'o-', color='red', label='mean salinity (v2+0.1)')\nax.plot(hy_dt_mon, sal_volmean3_monmean, 'o-', color='black', label='mean salinity (v3)')\nplt.grid(True)\nax.set_ylabel('Salinity (PSU)')\nax.legend(loc=0)\n#ax.set_ylim(33,34.5)\nplf.formatDates(ax)\nplt.show()\n\n#plot components of sal_volmean3_monmean\nplt.figure(figsize=(13,9))\nplt.subplot(3,1,1)\nax = plt.gca()\nax.plot(hy_dt_mon, smass_bob_monmean/1e15, 'o-', label=\"Salt mass x 10$^{15}$(kg)\")\nax.grid(True)\nax.set_ylabel(\"Salt mass x 10$^{15}$(kg)\")\nplf.formatDates(ax)\n\nplt.subplot(3,1,2)\nax = plt.gca()\nax.plot(hy_dt_mon, pdens_bob_volmean1_monmean-1000, 'o-', label='Volume mean density-1000 (kg/m$^3$)')\nax.grid(True)\nax.set_ylabel('Density-1000 (kg/m$^3$)')\nplf.formatDates(ax)\n\nplt.subplot(3,1,3)\nax = plt.gca()\nax.plot(hy_dt_mon, vol_tseries_monmean/1e14, 'o-', label='BoB volume ($10^{14}$ m$^3$)')\nax.grid(True)\nax.set_ylabel('volume ($10^{14}$ m$^3$)')\nplf.formatDates(ax)\nplt.show()\n\n\n#plot flux terms\nsmass_flux_sline_sum_lp_midavg = smass_flux_sline_sum_lp[:-1] + np.diff(smass_flux_sline_sum_lp)\nsmass_flux_sline_sum_midavg = smass_flux_sline_sum[:-1] + np.diff(smass_flux_sline_sum)\nprecip_smass_flux4_lp_midavg = precip_smass_flux4_lp[:-1] + np.diff(precip_smass_flux4_lp)\n\n\nplt.figure(figsize=(13,5))\nax = plt.gca()\n#ax.plot(hy_dt[:-1], dsmass_bob_volsum/1e13, color='blue', alpha=0.4)\nax.plot(hy_dt[:-1], dsmass_bob_volsum/1e13, color='blue', label='change in total salt mass', linewidth=1.5)\nax.plot(hy_dt[:-1], smass_flux_sline_sum_lp_midavg/1e13, color='red', label='salt flux across south lat-line', linewidth=1.5)\nax.plot(hy_dt[:-1], precip_smass_flux4_lp_midavg/1e13, color='green', label='virtual salt flux (precip)', linewidth=1.5)\n#ax.plot(hy_dt[:-1], (dsmass_bob_volsum-smass_flux_sline_sum_lp_midavg)/1e13, color='k', label='$\\Delta S_{mass}-S_{flux}$', linewidth=1.5)\n\nplt.grid(True)\nax.set_title(\"Salt budget terms\", fontsize=fntsz)\nax.set_ylabel(\"Salt flux (10$^{13}$ kg/day)\", fontsize=fntsz)\n#ax.legend(loc=0)\nplf.formatDates(ax)\nax.hlines(0,hy_dt[0], hy_dt[-1])\nplt.show()\n\n#same as above but with monthly means\nsmass_flux_sline_monmeans = plf.compute_monmeans(hy_dt, smass_flux_sline_sum_lp)[0]\ndsmass_bob_monmean = np.diff(smass_bob_monmean)\n\nplt.figure(figsize=(13,5))\nax = plt.gca()\nax.plot(hy_dt_mon_m1, dsmass_bob_monmean/1e14, color='blue', label='change in total salt mass', linewidth=1.5)\nax.plot(hy_dt_mon, 30*smass_flux_sline_monmeans/1e14, color='red', label='salt flux across south lat-line', linewidth=1.5)\nax.plot(hy_dt_mon, 30*precip_smass_flux4_monmean/1e14, color='green', label='virtual salt flux (precip)', linewidth=1.5)\nplt.grid(True)\nax.set_title(\"Salt budget terms (monthly means)\", fontsize=fntsz)\nax.set_ylabel(\"Salt flux (10$^{14}$ kg/month)\", fontsize=fntsz)\nax.legend(loc=0)\nplf.formatDates(ax)\nax.hlines(0,hy_dt[0], hy_dt[-1])\nplt.show()\n\n\n\n\nimport matplotlib.dates as mdates\nmyFmt = mdates.DateFormatter('%b')\nplt.figure()\nplt.plot(mvec, flux_m)\nplt.gca().xaxis.set_major_formatter(myFmt)\nplt.show()\n\n\n#make movie of salinity on sigma=25 surface\n# fig = plt.figure(figsize=(8,6))\n# quad = plt.pcolormesh(lon_bob, lat_bob, sal_bob_at_isoZ[0,...].T, cmap=plt.cm.RdYlGn_r)\n# #quad = plt.pcolormesh([],[], cmap=plt.cm.RdYlGn_r)\n# # plt.clim(34.5,35.5)\n# # plt.colorbar()\n#\n# def init():\n# quad.set_array(np.array([]))\n# return quad,\n#\n# def update(i):\n# plt.pcolormesh(lon_bob, lat_bob, sal_bob_at_isoZ[i,:,:].T, cmap=plt.cm.RdYlGn_r)\n# plt.clim(34.5,35.5)\n# plt.colorbar()\n#\n# # z=sal_bob_at_isoZ[i,...].T\n# # quad.set_array(z.ravel())\n# # quad.set_clim(34.5, 35.5)\n# # quad.colorbar()\n# #\n# # return quad,\n#\n# anim = animation.FuncAnimation(fig, update, init_func=init,frames=10, interval=20, blit=True)\n#\n# anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])\n#\n# plt.show()\n#\n \n \n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"BoB_work/sal_budget_plots.py","file_name":"sal_budget_plots.py","file_ext":"py","file_size_in_byte":9649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"99369122","text":"# -*- coding: utf-8 -*-\n\nimport base\nimport v2_swagger_client\nfrom v2_swagger_client.rest import ApiException\n\nclass Artifact(base.Base):\n def get_reference_info(self, project_name, repo_name, reference, **kwargs):\n client = self._get_client(**kwargs)\n params = {}\n if \"with_signature\" in kwargs:\n params[\"with_signature\"] = kwargs[\"with_signature\"]\n return client.get_artifact_with_http_info(project_name, repo_name, reference, **params )\n\n def add_label_to_reference(self, project_name, repo_name, reference, label_id, **kwargs):\n client = self._get_client(**kwargs)\n label = v2_swagger_client.Label(id = label_id)\n return client.add_label_with_http_info(project_name, repo_name, reference, label)\n\n def copy_artifact(self, project_name, repo_name, _from, expect_status_code = 201, expect_response_body = None, **kwargs):\n client = self._get_client(**kwargs)\n\n try:\n data, status_code, _ = client.copy_artifact_with_http_info(project_name, repo_name, _from)\n except ApiException as e:\n base._assert_status_code(expect_status_code, e.status)\n if expect_response_body is not None:\n base._assert_status_body(expect_response_body, e.body)\n return\n\n base._assert_status_code(expect_status_code, status_code)\n base._assert_status_code(201, status_code)\n return data\n","sub_path":"tests/apitests/python/library/artifact.py","file_name":"artifact.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"27117894","text":"from xml.etree import ElementTree\nfrom datetime import datetime\nimport pytz\nfrom corehq.apps.callcenter.indicator_sets import CallCenterIndicators\nfrom corehq.apps.users.models import CommCareUser\nfrom dimagi.utils.logging import notify_exception\n\nutc = pytz.utc\n\n\ndef should_sync(domain, last_sync, utcnow=None):\n # definitely sync if we haven't synced before\n if not last_sync or not last_sync.date:\n return True\n\n try:\n timezone = pytz.timezone(domain.default_timezone)\n except pytz.UnknownTimeZoneError:\n timezone = utc\n\n # check if user has already synced today (in local timezone). Indicators only change daily.\n last_sync_utc = last_sync.date if last_sync.date.tzinfo else utc.localize(last_sync.date)\n last_sync_local = timezone.normalize(last_sync_utc.astimezone(timezone))\n\n utcnow = utcnow if utcnow else utc.localize(datetime.utcnow())\n current_date_local = timezone.normalize(utcnow.astimezone(timezone))\n\n if current_date_local.date() != last_sync_local.date():\n return True\n\n return False\n\n\ndef indicators_fixture_generator(user, version, last_sync=None):\n assert isinstance(user, CommCareUser)\n\n domain = user.project\n fixtures = []\n\n if not domain or not (hasattr(domain, 'call_center_config') and domain.call_center_config.enabled):\n return fixtures\n\n if not should_sync(domain, last_sync):\n return fixtures\n\n try:\n fixtures.append(gen_fixture(user, CallCenterIndicators(domain, user)))\n except Exception: # blanket exception catching intended\n notify_exception(None, 'problem generating callcenter fixture', details={\n 'user_id': user._id,\n 'domain': user.domain\n })\n\n return fixtures\n\n\ndef gen_fixture(user, indicator_set):\n \"\"\"\n Generate the fixture from the indicator data.\n\n :param user: The user.\n :param indicator_set: A subclass of SqlIndicatorSet\n \"\"\"\n \"\"\"\n Example output:\n\n indicator_set.name = 'demo'\n indicator_set.get_data() = {'user_case1': {'indicator_a': 1, 'indicator_b': 2}}\n\n \n \n \n 1\n 2\n \n \n \n \"\"\"\n name = indicator_set.name\n data = indicator_set.get_data()\n\n fixture = ElementTree.Element('fixture', attrib={\n 'id': 'indicators:%s' % name,\n 'user_id': user.user_id,\n 'date': indicator_set.reference_date.isoformat()\n })\n indicators_node = ElementTree.SubElement(fixture, 'indicators')\n for case_id, indicators in data.iteritems():\n group = ElementTree.SubElement(indicators_node, 'case', attrib={'id': case_id})\n for name, value in indicators.items():\n indicator = ElementTree.SubElement(group, name)\n indicator.text = str(value)\n\n return fixture\n","sub_path":"corehq/apps/callcenter/fixturegenerators.py","file_name":"fixturegenerators.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"479897512","text":"import constraintSatisfier as cs\nimport sudgen as s\nimport operator\nimport copy\n\ndef getCoord(cell, boardWidth):\n return (int(cell / boardWidth), cell % boardWidth)\n\ndef getCell(row, col, boardWidth):\n return row * boardWidth + col\n\ndef assignConstraints(board, S, D):\n C = set()\n size = int(len(board) ** 0.5)\n for i in range(len(board)):\n for j in range(len(board) - 1):\n for k in range(j, len(board)):\n if j != k:\n # i row, j k col\n jcell = getCell(i, j, len(board))\n kcell = getCell(i, k, len(board))\n if board[i][j] == 0 and board[i][k] == 0:\n C.add((operator.ne, jcell, kcell))\n elif board[i][j] == 0:\n D[jcell] -= {board[i][k]}\n elif board[i][k] == 0:\n D[kcell] -= {board[i][j]}\n # i col, j k row\n jcell = getCell(j, i, len(board))\n kcell = getCell(k, i, len(board))\n if board[j][i] == 0 and board[k][i] == 0:\n C.add((operator.ne, jcell, kcell))\n elif board[j][i] == 0:\n D[jcell] -= {board[k][i]}\n elif board[k][i] == 0:\n D[kcell] -= {board[j][i]}\n # i is block id\n # j k cell ids\n block_row = int(i / size) * size\n block_col = (i % size) * size\n j_block_row = int(j / size) + block_row\n j_block_col = int(j % size) + block_col\n k_block_row = int(k / size) + block_row\n k_block_col = int(k % size) + block_col\n jcell = getCell(j_block_row, j_block_col, len(board))\n kcell = getCell(k_block_row, k_block_col, len(board))\n if board[j_block_row][j_block_col] == 0 and board[k_block_row][k_block_col] == 0:\n C.add((operator.ne, jcell, kcell))\n elif board[j_block_row][j_block_col] == 0:\n D[jcell] -= {board[k_block_row][k_block_col]}\n elif board[k_block_row][k_block_col] == 0:\n D[kcell] -= {board[j_block_row][j_block_col]}\n return list(C)\n\ndef assignDomain(values, board, domain, D):\n for v in values:\n coord = getCoord(v, len(domain))\n D[v] = set(domain)\n return D\n\ndef getVariables(board):\n S = []\n for i in range(len(board)):\n for j in range(len(board)):\n if board[i][j] == 0:\n S.append(getCell(i, j, len(board)))\n return S\n\ndef printBoard(board):\n size = int(len(board))\n block_size = int(size ** 0.5)\n print(str(len(board)) + \"\\t\" + str(size))\n for i in range(size):\n for j in range(size):\n print(board[i][j], end=\" \")\n if j % block_size == block_size - 1:\n print(' ', end='')\n print()\n if i % block_size == block_size - 1:\n print()\n\ndef assignBoard(board, assignment):\n for v in assignment.keys():\n coord = getCoord(v, len(board))\n board[coord[0]][coord[1]] = assignment[v]\n\ndef runSudokuTrial(missing, order, inference, block_size = 3):\n board = s.makeSudokuBoard(missing, block_size)\n printBoard(board)\n S = getVariables(board)\n print(S)\n D = assignDomain(S, board, range(1, 1 + block_size ** 2), {})\n C = assignConstraints(board, S, D)\n csp = {'S': S, 'D': D, 'C': C, 'order': order, 'inference': inference}\n cs.backtrackingSearch(csp)\n assignBoard(board, csp['assignment'])\n printBoard(board)\n return csp\n\nrunSudokuTrial(50, cs.randomOrder, cs.forwardChecking, 3)\n","sub_path":"project1b/old/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"514339088","text":"#\n# URLs related to managing teams of users\n#\nfrom django.conf.urls import patterns, include, url\nfrom support.views import RequestInformationView, UserManualView\nfrom views import *\n\nurlpatterns = patterns('support.views',\n\n # REST api for teams\n url(r'^api/team/$', APITeamListView.as_view(), name='api_team_list'),\n url(r'^api/team/(?P\\d+)/$', APITeamDetailView.as_view(), name='api_team_detail'),\n url(r'^api/team/(?P\\d+)/nonmember/$', APITeamNonmembersListView.as_view(),\n name='api_team_nonmembers'),\n\n # team management\n url(r'^team/$', TeamCreateView.as_view(), name='team_create'),\n url(r'^team/(?P\\d+)/manage$', TeamManagementView.as_view(), name='team_manage'),\n url(r'^team/(?P\\d+)/edit$', TeamEditView.as_view(), name='team_edit'),\n )\n\n","sub_path":"Greenscope/teams/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"251917062","text":"#!/usr/bin/env python\n\nimport sys\n\nfrom csvkit import convert\nfrom csvkit.cli import CSVFileType, CSVKitUtility\n\nclass In2CSV(CSVKitUtility):\n description = 'Convert common, but less awesome, tabular data formats to CSV.'\n epilog='Some command line flags only pertain to specific input formats.'\n override_flags = ['f']\n\n def add_arguments(self):\n self.argparser.add_argument('file', metavar=\"FILE\", nargs='?', default=sys.stdin,\n help='The CSV file to operate on. If omitted, will accept input on STDIN.')\n self.argparser.add_argument('-f', '--format', dest='format',\n help='The format of the input file. If not specified will be inferred from the file type. Supported formats: %s.' % ', '.join(sorted(convert.SUPPORTED_FORMATS)))\n self.argparser.add_argument('-s', '--schema', dest='schema', type=CSVFileType(),\n help='Specifies a CSV-formatted schema file for converting fixed-width files. See documentation for details.')\n self.argparser.add_argument('-k', '--key', dest='key',\n help='Specifies a top-level key to use look within for a list of objects to be converted when processing JSON.')\n self.argparser.add_argument('-y', '--snifflimit', dest='snifflimit', type=int,\n help='Limit CSV dialect sniffing to the specified number of bytes. Specify \"0\" to disable sniffing entirely.')\n self.argparser.add_argument('--sheet', dest='sheet',\n help='The name of the XLSX sheet to operate on.')\n self.argparser.add_argument('--no-inference', dest='no_inference', action='store_true',\n help='Disable type inference when parsing the input.')\n\n\n def main(self):\n if self.args.format:\n format = self.args.format\n\n if format not in convert.SUPPORTED_FORMATS:\n self.argparser.error('\"%s\" is not a supported format' % self.args.format)\n\n elif self.args.schema:\n format = 'fixed'\n elif self.args.key:\n format = 'json'\n else:\n if self.args.file == sys.stdin:\n self.argparser.error('You must specify a format when providing data via STDIN (pipe).')\n\n format = convert.guess_format(self.args.file)\n\n if not format:\n self.argparser.error('Unable to automatically determine the format of the input file. Try specifying a format with --format.')\n\n if isinstance(self.args.file, file):\n f = self.args.file\n elif format in ('xls', 'xlsx'):\n f = open(self.args.file, 'rb')\n else:\n f = open(self.args.file, 'rU')\n\n kwargs = self.reader_kwargs\n\n if self.args.schema:\n kwargs['schema'] = self.args.schema\n\n if self.args.key:\n kwargs['key'] = self.args.key\n\n if self.args.snifflimit:\n kwargs['snifflimit'] = self.args.snifflimit\n\n if self.args.sheet:\n kwargs['sheet'] = self.args.sheet\n\n if self.args.no_inference:\n kwargs['type_inference'] = False\n\n if format == 'csv' and self.args.no_header_row:\n kwargs['no_header_row'] = True\n\n # Fixed width can be processed as a stream\n if format == 'fixed':\n kwargs['output'] = self.output_file\n\n self.output_file.write(convert.convert(f, format, **kwargs))\n\ndef launch_new_instance():\n utility = In2CSV()\n utility.main()\n \nif __name__ == \"__main__\":\n launch_new_instance()\n\n","sub_path":"csvkit/utilities/in2csv.py","file_name":"in2csv.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"79348724","text":"import csv\nimport pygal\nwith open('database_for_alcohol.csv', 'r') as csv_file:\n csv_reader = csv.reader(csv_file)\n sample_list = []\n for line in csv_reader:\n sample_list.append(line)\n header = list(map(int, sample_list[0]))\n line_1 = list(map(float, sample_list[1]))\n for i in range(len(line_1)):\n if line_1[i] == 0:\n line_1[i] = None\nline_chart = pygal.Line()\nline_chart.title = 'Average alcohol expenditure per household in 2543-2546'\nline_chart.x_labels = header\nline_chart.add('THB (adjusted for inflation)',line_1)\nline_chart.render_to_file('graph_1.svg')\n","sub_path":"code_graph_1.py","file_name":"code_graph_1.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"421179755","text":"from selenium import webdriver\nfrom time import sleep,localtime,strftime\nfrom random import randint\nclass Goldbot():\n def __init__(self):\n self.driver = webdriver.Chrome()\n def videovalik(self):\n self.driver.get(\"https://novaator.err.ee/k/goldbergimasin\")\n sleep(1)\n otsing = self.driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[1]/div[2]/div/div/div/div/div[2]/div[1]/input')\n self.driver.execute_script('arguments[0].scrollIntoView()', otsing)\n otsing.send_keys('vesilind')\n def hääleta(self):\n video = self.driver.find_element_by_xpath('//*[@id=\"mediaId_0\"]') \n video.click()\n video.click()\nwhile True:\n bot = Goldbot()\n bot.videovalik()\n sleep(1)\n bot.hääleta()\n print(\"Chrome, hääletatud kell:\",strftime(\"%H:%M:%S\", localtime()))\n sleep(3)\n bot.driver.close()\n sleep(randint(3605,3900))\n","sub_path":"Chromebot.py","file_name":"Chromebot.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"551199130","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.contrib.postgres.fields\nimport json_field.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('legislator', '0002_legislatordetail_elected_party'),\n ('candidates', '0003_auto_20151112_0917'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Terms',\n fields=[\n ('id', models.CharField(max_length=70, serialize=False, primary_key=True)),\n ('ad', models.IntegerField(db_index=True)),\n ('number', models.IntegerField(db_index=True, null=True, blank=True)),\n ('priority', models.IntegerField(db_index=True, null=True, blank=True)),\n ('name', models.CharField(max_length=100)),\n ('gender', models.CharField(max_length=100, null=True, blank=True)),\n ('party', models.CharField(db_index=True, max_length=100, null=True, blank=True)),\n ('constituency', models.IntegerField(db_index=True)),\n ('county', models.CharField(max_length=100, db_index=True)),\n ('district', models.CharField(db_index=True, max_length=100, null=True, blank=True)),\n ('votes', models.IntegerField(null=True, blank=True)),\n ('votes_percentage', models.CharField(max_length=100, null=True, blank=True)),\n ('elected', models.NullBooleanField(db_index=True)),\n ('contact_details', json_field.fields.JSONField(default='null', help_text='Enter a valid JSON object', null=True)),\n ('education', models.TextField(null=True, blank=True)),\n ('experience', models.TextField(null=True, blank=True)),\n ('remark', models.TextField(null=True, blank=True)),\n ('image', models.URLField(null=True, blank=True)),\n ('links', json_field.fields.JSONField(default='null', help_text='Enter a valid JSON object', null=True)),\n ('platform', models.TextField(null=True, blank=True)),\n ('politicalcontributions', json_field.fields.JSONField(default='null', help_text='Enter a valid JSON object', null=True)),\n ],\n ),\n migrations.AddField(\n model_name='candidates',\n name='former_names',\n field=django.contrib.postgres.fields.ArrayField(default=None, null=True, base_field=models.CharField(max_length=100), size=None),\n ),\n migrations.AlterUniqueTogether(\n name='candidates',\n unique_together=set([]),\n ),\n migrations.AlterIndexTogether(\n name='candidates',\n index_together=set([]),\n ),\n migrations.AddField(\n model_name='terms',\n name='candidate',\n field=models.ForeignKey(to='candidates.Candidates'),\n ),\n migrations.AddField(\n model_name='terms',\n name='latest_term',\n field=models.OneToOneField(null=True, blank=True, to='legislator.LegislatorDetail'),\n ),\n migrations.AddField(\n model_name='terms',\n name='legislator',\n field=models.OneToOneField(related_name='elected_candidate', null=True, blank=True, to='legislator.LegislatorDetail'),\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='ad',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='constituency',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='contact_details',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='county',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='district',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='education',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='elected',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='experience',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='gender',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='image',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='latest_term',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='legislator',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='links',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='number',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='party',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='platform',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='politicalcontributions',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='remark',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='votes',\n ),\n migrations.RemoveField(\n model_name='candidates',\n name='votes_percentage',\n ),\n migrations.AlterIndexTogether(\n name='terms',\n index_together=set([('ad', 'county', 'constituency')]),\n ),\n ]\n","sub_path":"candidates/migrations/0004_auto_20151126_0855.py","file_name":"0004_auto_20151126_0855.py","file_ext":"py","file_size_in_byte":5712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"297684568","text":"# -*- coding:utf-8 -*-\n\n\"\"\"Test app module.\"\"\"\n\nfrom io import BytesIO\n\nimport pytest\n\n\n@pytest.mark.parametrize(\n 'sample_file, file_name, file_hash',\n [\n (b'\\xc3\\x96l\\xc3\\x96l', 'sample.txt', '77ef24eaa0fc1ab5f21b040638cf6ef8'),\n (b'\\xE2\\x82\\xAC', '0', 'bca53fde466a76b7bee3e18997e94a7a'),\n ],\n)\ndef test_http_api(client, sample_file, file_name, file_hash):\n \"\"\"Test HTTP API.\"\"\"\n\n def test_upload_file(client, sample_file, file_name, file_hash):\n \"\"\"Test file upload.\"\"\"\n global new_hash\n data = {\n 'file': (\n BytesIO(sample_file),\n file_name,\n ),\n }\n res = client.post('/upload', data=data)\n new_hash = res.json['hash']\n assert res.status_code == 200\n assert new_hash == file_hash\n\n def test_download_file(client, new_hash):\n \"\"\"Test file download.\"\"\"\n url = '/download/{0}'.format(new_hash)\n res = client.get(url)\n assert res.status_code == 200\n\n def test_delete_file(client, new_hash):\n \"\"\"Test file delete.\"\"\"\n url = '/delete/{0}'.format(new_hash)\n res = client.delete(url)\n assert res.status_code == 200\n\n test_upload_file(client, sample_file, file_name, file_hash)\n test_download_file(client, new_hash)\n test_delete_file(client, new_hash)\n\n\n@pytest.mark.parametrize('data', [\n {'f': (BytesIO(b'\\xE2\\x82\\xAC'), 'test')},\n {'file': (BytesIO(b'\\xE2\\x82\\xAC'), )},\n])\ndef test_upload(client, data):\n \"\"\"Test upload function.\"\"\"\n res = client.post('/upload', data=data)\n assert res.status_code == 400\n\n\n@pytest.mark.parametrize('hash, response_code', [\n ('bca53fde466a76b7bee3e1899', 400),\n ('bca53fde466a76b7bee3e18997e94a7a', 404),\n])\ndef test_download(client, hash, response_code):\n \"\"\"Test download function.\"\"\"\n url = '/download/{0}'.format(hash)\n res = client.get(url)\n assert res.status_code == response_code\n\n\n@pytest.mark.parametrize('hash, response_code', [\n ('bca53fde466a76b7bee3e1899', 400),\n ('bca53fde466a76b7bee3e18997e94a7a', 404),\n])\ndef test_delete(client, hash, response_code):\n \"\"\"Test delete function.\"\"\"\n url = '/delete/{0}'.format(hash)\n res = client.delete(url)\n assert res.status_code == response_code\n","sub_path":"tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"626550697","text":"from lab.lab_node import LabNode\n\n\nclass Nexus(LabNode):\n\n def __init__(self, node_id, role, lab, hostname):\n super(Nexus, self).__init__(node_id=node_id, role=role, lab=lab, hostname=hostname)\n self._actual_vpc = []\n self._actual_pc = {}\n self._actual_vlans = {}\n self._actual_ports = {}\n\n def __repr__(self):\n ip, username, password = self.get_oob()\n return u'{l} {id} sshpass -p {p} ssh {u}@{ip} use http://{ip} for NX-API'.format(l=self.lab(), id=self.get_id(), p=password, u=username, ip=ip)\n\n def get_pcs_to_fi(self):\n \"\"\"Returns a list of pcs used on connection to peer N9K and both FIs\"\"\"\n return set([str(x.get_pc_id()) for x in self._downstream_wires if x.is_n9_fi()])\n\n def _allow_feature_nxapi(self):\n from fabric.api import settings, run\n\n oob_ip, oob_u, oob_p = self.get_oob()\n with settings(host_string='{user}@{ip}'.format(user=oob_u, ip=oob_ip), password=oob_p):\n if 'disabled'in run('sh feature | i nxapi', shell=False):\n run('conf t ; feature nxapi', shell=False)\n\n def _rest_api(self, commands, timeout=2):\n import requests\n import json\n from lab.logger import lab_logger\n lab_logger.info('{0} commands: {1}'.format(self, \", \".join(commands)))\n\n oob_ip, oob_u, oob_p = self.get_oob()\n body = [{\"jsonrpc\": \"2.0\", \"method\": \"cli\", \"params\": {\"cmd\": command, \"version\": 1}, \"id\": 1} for command in commands]\n try:\n data = json.dumps(body)\n result = requests.post('http://{0}/ins'.format(oob_ip), auth=(oob_u, oob_p), headers={'content-type': 'application/json-rpc'}, data=data, timeout=timeout)\n return result.json()\n except requests.exceptions.ConnectionError:\n self._allow_feature_nxapi()\n return self._rest_api(commands=commands, timeout=timeout)\n\n def get_hostname(self):\n res = self.cmd(['sh switchname'])\n return res['result']['body']['hostname']\n\n def cmd(self, commands, timeout=15):\n if isinstance(commands, basestring): # it might be provided as a string where commands are separated by ','\n commands = commands.strip('[]')\n commands = commands.split(',')\n\n results = self._rest_api(commands=commands, timeout=int(timeout))\n if len(commands) == 1:\n results = [results]\n for i, x in enumerate(results, start=0):\n if 'error' in x:\n raise NameError('{cmd} : {msg}'.format(msg=x['error']['data']['msg'].strip('%\\n'), cmd=commands[i]))\n return dict(results[0])\n\n def change_port_state(self, port_no, port_state=\"no shut\"):\n \"\"\"\n Change port state of the port\n :param port_no: should be in full format like e1/3 or po1\n :param port_state: 'shut' or 'no shut'\n \"\"\"\n self.cmd(['conf t', 'int {port}'.format(port=port_no), '{0}'.format(port_state)])\n\n def show_port_channel_summary(self):\n res = self.cmd(['show port-channel summary'])\n return [x['port-channel'] for x in res['result']['body']['TABLE_channel']['ROW_channel']]\n\n def show_interface_switchport(self, name):\n res = self.cmd(['show interface {0} switchport'.format(name)])\n vlans_str = res['result']['body']['TABLE_interface']['ROW_interface']['trunk_vlans']\n vlans = set()\n for vlan_range in vlans_str.split(','): # from 1,2,5-7 to (1, 2, 5, 6, 7)\n se = vlan_range.split('-')\n if len(se) == 2:\n vlans = vlans | set(range(int(se[0]), int(se[1]) + 1))\n elif len(se) == 1:\n vlans.add(int(se[0]))\n return sorted(vlans)\n\n def n9_show_port_channels(self):\n ans = self.cmd(['sh port-channel summary'])\n if ans['result']:\n pcs = ans['result']['body'][u'TABLE_channel'][u'ROW_channel']\n pcs = [pcs] if isinstance(pcs, dict) else pcs # if there is only one port-channel the API returns dict but not a list. Convert to list\n port_channels = {}\n for pc_dict in pcs:\n pc_id = pc_dict['group']\n if 'TABLE_member' in pc_dict:\n ports = pc_dict['TABLE_member']['ROW_member'] # if pc has only one port - it's a dict, otherwise - list\n ports = [ports] if type(ports) == dict else ports\n port_ids = map(lambda x: x['port'].replace('Ethernet', ''), ports)\n else:\n port_ids = []\n port_channels[pc_id] = port_ids\n return port_channels\n else:\n return []\n\n def delete_port_channels(self, skip_list=None):\n skip_list = skip_list or []\n for pc_id, port_ids in self.n9_show_port_channels().iteritems():\n if pc_id in skip_list:\n continue\n self.cmd(['conf t', 'no int port-channel {0}'.format(pc_id)], timeout=60)\n if port_ids:\n self.cmd(['conf t', 'int ethernet {0}'.format(','.join(port_ids)), 'description --'])\n\n def n9_configure_port(self, pc_id, port_id, vlans_string, desc, speed):\n actual_port_info = self._actual_ports['Ethernet' + port_id]\n actual_state, actual_desc = actual_port_info['state'], actual_port_info.get('name', '--') # for port with no description this field either -- or not in dict\n\n if actual_state == 'xcvrAbsent':\n raise RuntimeError('N9K {}: Port {} seems to be not connected. Check your configuration'.format(self, port_id))\n\n actual_port_channel = filter(lambda x: port_id in x[1], self._actual_pc.items())\n actual_pc_id = int(actual_port_channel[0][0]) if actual_port_channel else 0\n\n if actual_pc_id:\n if actual_pc_id == pc_id: # this port already part of required port-channel, so just change description once again\n self.cmd(['conf t', 'int ether ' + port_id, 'desc {0}'.format(desc)])\n return\n else:\n raise RuntimeError('N9K {}: Port {} belongs to different port-channel {}. Check your configuration'.format(self, port_id, actual_pc_id))\n # at hist point we know that port does not participate in port-channel\n\n if actual_state == 'down':\n self.cmd(['conf t', 'int ether ' + port_id, 'no shut'])\n\n if actual_desc != '--': # if description is not default try to check which lab using it\n if not actual_desc.startswith(str(self.lab())): # if it says the current lab, (almost) nothing to worry about\n raise RuntimeError('N9K {}: Port {} seems to belong to other lab (with description {}). Check your configuration'.format(self, port_id, actual_desc))\n # at this point we known that this port is not in port-channel and not possible belongs to other lab, so configure it\n self.cmd(['conf t', 'int ether ' + port_id, 'desc {0}'.format(desc), 'switchport', 'switchport mode trunk', 'switchport trunk allowed vlan {0}'.format(vlans_string), 'speed {0}'.format(speed)])\n\n def n9_create_port_channel(self, pc_id, desc, port_ids, speed, vlans_string, is_peer_link_pc=False):\n \"\"\"\n :param is_peer_link_pc:\n :param desc: some text to describe port channel and it's ports\n :param vlans_string: string like '1, 12, 333-444'\n :param speed: int like 10000\n :param port_ids: port like '1/15' it's a single value, one need to call this method few times with different port_id to add more ports to port-channel\n :param pc_id: id in range 1-4096\n :return:\n \"\"\"\n for port_id in port_ids:\n self.n9_configure_port(pc_id=pc_id, port_id=port_id, vlans_string=vlans_string, desc=desc, speed=speed)\n\n actual_port_ids = self._actual_pc.get(str(pc_id), [])\n if actual_port_ids: # port channel with this id already exists\n if port_ids != actual_port_ids: # make sure that requested list of port-ids equals to actual list\n raise RuntimeError('{}: port-channel {} has different list of ports ({}) then requested ({})'.format(self, pc_id, actual_port_ids, port_ids))\n self.cmd(['conf t', 'int port-channel {0}'.format(pc_id), 'switchport trunk allowed vlan add {0}'.format(vlans_string)])\n else: # port channel is not yet created\n self.cmd(['conf t', 'int port-channel {0}'.format(pc_id), 'descr {0}'.format(desc), 'switchport', 'switchport mode trunk', 'switchport trunk allowed vlan add {0}'.format(vlans_string),\n 'spanning-tree port type edge trunk', 'speed {0}'.format(speed), 'shut', 'no lacp suspend-individual', 'no shut'])\n for port_id in port_ids: # add ports to the port-channel\n self.cmd(['conf t', 'int ethernet ' + port_id, 'channel-group {0} force mode active'.format(pc_id)])\n if is_peer_link_pc:\n self.n9_create_vpc_peer_link(pc_id)\n\n def n9_create_vpc(self, pc_id):\n if not self._actual_vpc:\n self.n9_get_status()\n if str(pc_id) not in self._actual_vpc:\n self.cmd(['conf t', 'int port-channel {0}'.format(pc_id), 'vpc {0}'.format(pc_id)], timeout=60)\n\n def n9_get_status(self):\n self._actual_vpc = self.n9_show_vpc()\n self._actual_pc = self.n9_show_port_channels()\n self._actual_vlans = self.n9_show_vlans()\n self._actual_ports = self.n9_show_ports()\n\n def n9_show_ports(self):\n ans_st = self.cmd(['sh int st'])\n ans_br = self.cmd(['sh int br'])\n\n list_of_dicts = ans_br['result']['body'][u'TABLE_interface'][u'ROW_interface']\n result = {x['interface']: x for x in list_of_dicts}\n for dic in ans_st['result']['body'][u'TABLE_interface'][u'ROW_interface']:\n result[dic['interface']]['name'] = dic.get('name', '')\n return result\n\n def n9_show_vpc(self):\n ans = self.cmd(['sh vpc'])\n if ans['result']:\n vpc = ans['result']['body'][u'TABLE_vpc'][u'ROW_vpc']\n vpc = [vpc] if isinstance(vpc, dict) else vpc # if there is only one vpc the API returns dict but not a list. Convert to list\n return map(lambda x: str(x['vpc-id']), vpc)\n else:\n return []\n\n def n9_create_vpc_peer_link(self, pc_id):\n self.cmd(['conf t', 'int port-channel {0}'.format(pc_id), 'spanning-tree port type network', 'vpc peer-link'], timeout=180)\n\n def n9_show_vlans(self):\n vlans = self.cmd(['sh vlan'])\n if vlans['result']:\n vlans = vlans['result']['body'][u'TABLE_vlanbrief'][u'ROW_vlanbrief']\n vlans = [vlans] if isinstance(vlans, dict) else vlans\n result = {x['vlanshowbr-vlanid-utf']: {'name': x['vlanshowbr-vlanname'], 'ports': x['vlanshowplist-ifidx']} for x in vlans}\n return result\n else:\n return {}\n\n def n9_show_cdp_neighbor(self):\n cdp_neis = self.cmd(['sh cdp nei det'])\n return cdp_neis['result']['body']['TABLE_cdp_neighbor_detail_info']['ROW_cdp_neighbor_detail_info']\n\n def n9_show_users(self):\n res = self.cmd(['show users'])\n if res == 'timeout':\n return []\n if res['result']:\n return res['result']['body']['TABLE_sessions']['ROW_sessions']\n else:\n return [] # no current session\n\n def delete_vlans(self, slice_vlans=64):\n vlans = [x['vlanshowbr-vlanid-utf'] for x in self.n9_show_vlans() if x['vlanshowbr-vlanid-utf'] != '1']\n vlan_delete_str = ['conf t'] + ['no vlan ' + ','.join(vlans[i:i+slice_vlans]) for i in range(0, len(vlans), slice_vlans)]\n self.cmd(vlan_delete_str)\n\n def clean_interfaces(self):\n interfaces = set([x.get_own_port(self) for x in self._peer_link_wires + self._downstream_wires])\n clean_cmd = ['conf t']\n [clean_cmd.extend(['int e{0}'.format(x), 'no description', 'switchport trunk allowed vlan none', 'exit']) for x in interfaces]\n self.cmd(clean_cmd, timeout=60)\n\n def clean_vpc_domain(self):\n old_vpc_domain = self.cmd(['sh vpc'])['result']['body']['vpc-domain-id']\n if old_vpc_domain != 'not configured':\n self.cmd(['conf t', 'no vpc domain {0}'.format(old_vpc_domain)], timeout=60)\n\n def n9_configure_vxlan(self, asr_port):\n import re\n\n number_in_node_id = map(int, re.findall(r'\\d+', self.get_id()))[0]\n lo1_ip = '1.1.1.{0}'.format(number_in_node_id)\n lo2_ip = '2.2.2.{0}'.format(number_in_node_id)\n router_ospf = '111'\n router_area = '0.0.0.0'\n eth48_ip = '169.0.{0}.1'.format(number_in_node_id)\n self.cmd(['conf t', 'feature ospf'])\n self.cmd(['conf t', 'feature pim'])\n self.cmd(['conf t', 'interface loopback 1'])\n self.cmd(['conf t', 'interface loopback 2'])\n self.cmd(['conf t', 'interface loopback 1', 'ip address {0}/32'.format(lo1_ip)])\n self.cmd(['conf t', 'interface loopback 1', 'ip router ospf {0} area {1}'.format(router_ospf, router_area)])\n self.cmd(['conf t', 'interface loopback 2', 'ip address {0}/32'.format(lo2_ip)])\n self.cmd(['conf t', 'interface loopback 2', 'ip router ospf {0} area {1}'.format(router_ospf, router_area)])\n self.cmd(['conf t', 'interface ethernet {0}'.format(asr_port), 'no switchport'])\n self.cmd(['conf t', 'interface ethernet {0}'.format(asr_port), 'ip address {0}/30'.format(eth48_ip)])\n self.cmd(['conf t', 'interface ethernet {0}'.format(asr_port), 'ip router ospf {0} area {1}'.format(router_ospf, router_area)])\n\n def n9_configure_vpc_domain(self, peer_ip, domain_id=1):\n self.cmd(['conf t', 'feature vpc'])\n self.cmd(['conf t', 'vpc domain {0}'.format(domain_id), 'peer-keepalive destination {0}'.format(peer_ip)], timeout=60)\n\n def get_peer_link_id(self):\n return self._peer_link_wires[0].get_pc_id()\n\n def cleanup(self):\n self.delete_port_channels()\n self.delete_vlans()\n self.clean_interfaces()\n self.clean_vpc_domain()\n\n def n9_add_vlan_range(self, interfaces):\n vlan_range = self.lab().vlan_range().replace(':', '-')\n commands = ['conf t', 'vlan {0}'.format(vlan_range), 'no shut', 'exit', 'int e{0}'.format(',e'.join(interfaces)), 'switchport trunk allowed vlan add {0}'.format(vlan_range), 'end']\n self.cmd(commands)\n\n def n9_configure_vlans(self):\n if not self._actual_vlans:\n self.n9_get_status()\n vlans = []\n for net in self.lab().get_all_nets().values():\n vlan_id = str(net.get_vlan())\n if vlan_id == '1':\n continue\n vlans.append(vlan_id)\n vlan_name = '{}-{}{}{}'.format(self._lab, net.get_name(), '-VTS' if net.is_vts() else '', '-SSH' if net.is_ssh() else '')\n if vlan_id in self._actual_vlans:\n actual_vlan_name, actual_vlan_ports = self._actual_vlans[vlan_id]['name'], self._actual_vlans[vlan_id]['ports']\n if actual_vlan_name.lower() != vlan_name.lower():\n raise RuntimeError('{}: vlan id {} already active with name {}. Don know what to do. please decide manually'.format(self, vlan_id, actual_vlan_name))\n self.log(message='VLAN id={} already active'.format(vlan_id))\n else:\n self.cmd(['conf t', 'vlan {}'.format(vlan_id), 'name ' + vlan_name, 'no shut'])\n return vlans\n\n def n9_configure_for_lab(self, topology):\n from lab.logger import lab_logger\n\n lab_logger.info('Configuring {0}'.format(self))\n\n self.n9_get_status()\n self.cmd(['conf t', 'feature lacp'])\n\n all_vlan_ids = self.n9_configure_vlans()\n\n self.n9_configure_peer_link(all_vlan_ids=all_vlan_ids)\n self.n9_configure_ports(wires=self._upstream_wires)\n self.n9_configure_ports(wires=self._downstream_wires)\n\n if topology == self.lab().TOPOLOGY_VXLAN:\n self.n9_configure_asr1k()\n\n def n9_configure_ports(self, wires):\n pc_id_vs_list_of_wires_dict = self.collect_port_channels(wires)\n for pc_id, wires in pc_id_vs_list_of_wires_dict.items():\n ports = reduce(lambda lst, w: lst + [w.get_own_port(self)], wires, [])\n if 'MGMT' in ports: # don;t process MGMT ports\n continue\n description = str(wires[0].get_peer_node(self)) if not wires[0].is_n9_tor() else 'TOR uplink'\n vlans_string = ','.join(map(lambda x: str(x), wires[0].get_vlans())) # the same list of vlans should on each wire\n if str(pc_id).startswith('FAKE-PC-ID'): # this is actually a single port not participating in port-channel\n self.n9_configure_port(pc_id=pc_id, port_id=ports[0], vlans_string=vlans_string, desc=description, speed=10000)\n else:\n self.n9_create_port_channel(pc_id=pc_id, desc=description, port_ids=ports, vlans_string=vlans_string, speed=10000)\n if self._peer_link_wires:\n self.n9_create_vpc(pc_id)\n\n @staticmethod\n def collect_port_channels(wires):\n pc_id_vs_list_of_wires_dict = {}\n no_pc_wires_count = 0\n for wire in wires:\n pc_id = wire.get_pc_id()\n if pc_id is None:\n no_pc_wires_count += 1\n pc_id = 'FAKE-PC-ID-' + str(no_pc_wires_count)\n pc_id_vs_list_of_wires_dict.setdefault(pc_id, [])\n pc_id_vs_list_of_wires_dict[pc_id].append(wire)\n return pc_id_vs_list_of_wires_dict\n\n def n9_configure_peer_link(self, all_vlan_ids):\n if not self._peer_link_wires: # this N9K is not in per-link configuration\n return\n pc_id_vs_list_of_wires_dict = self.collect_port_channels(self._peer_link_wires)\n if len(pc_id_vs_list_of_wires_dict) != 1:\n raise ValueError('{}: Check lab config since peer-link port-channel needs to be formed from wires on the same port-channel-id')\n pc_id, wires = pc_id_vs_list_of_wires_dict.items()[0]\n peer_n9ks = map(lambda x: x.get_peer_node(self), wires)\n if len(set(peer_n9ks)) != 1:\n raise ValueError('{}: Check lab config since peer-link port-channel is form from ports wired to different devices: {}'.format(self, peer_n9ks))\n\n ports = map(lambda x: x.get_own_port(self), wires)\n\n vlans_string = ','.join(map(lambda x: str(x), all_vlan_ids)) # all vlans which go via peer-link: actually all lab vlans\n ip, _, _ = peer_n9ks[0].get_oob()\n self.n9_configure_vpc_domain(peer_ip=ip)\n self.n9_create_port_channel(pc_id=pc_id, desc='N9K peer-link', port_ids=ports, vlans_string=vlans_string, speed=10000, is_peer_link_pc=True)\n\n def n9_configure_asr1k(self):\n self.cmd(['conf t', 'int po{0}'.format(self.get_peer_link_id()), 'shut'])\n asr = filter(lambda x: x.is_n9_asr(), self._upstream_wires)\n self.n9_configure_vxlan(asr[0].get_own_port(self))\n\n def form_mac(self, pattern):\n pass\n","sub_path":"lab/n9k.py","file_name":"n9k.py","file_ext":"py","file_size_in_byte":19020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"448797628","text":"f = open(\"菜单\", mode=\"r+\", encoding=\"utf-8\") # r+最常见\ns = f.read(1) # 读取一个字符\nprint(s)\nf.write(\"胡辣汤\") # r+模式. 如果你执行读了操作. 那么写操作的时候. 都是写在文件的末尾. 和光标没有关系\n# f.write(\"ab\") # 在文件开头写入. 写入的是字节,把原来的内容盖上\n\n# for line in f:\n# print(line)\n# f.write(\"蛋炒饭\")\n# 正确用法: 先读后写\nf.close()","sub_path":"Python全栈第14期/1-python基础部分/day08 文件操作/07 读写���式.py","file_name":"07 读写模式.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"173035072","text":"import tornado\nimport config.routes as router\n\ndef init_app():\n return tornado.web.Application(\n router.get_routes()\n )\n\nif __name__ == \"__main__\":\n print('hello tornado')\n app = init_app()\n app.listen(8888)\n tornado.ioloop.IOLoop.current().start()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"453464751","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import fields, models\n\n\nclass Orderpoint(models.Model):\n \"\"\" Defines Minimum stock rules. \"\"\"\n _inherit = \"stock.warehouse.orderpoint\"\n\n no_batch = fields.Boolean(\n string='One Per Order',\n required=True,\n default=False,\n help=\"The MRP planning engine only will generate orders for quantity\"\n \" of 1. This product will not be built in batches.\")\n","sub_path":"mrp_mrp/models/stock_orderpoint.py","file_name":"stock_orderpoint.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"619905535","text":"\"\"\"online_exam_app URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/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,include\nfrom . import views\nurlpatterns = [\n path('main_admin', views.main_admin, name='main_admin'),\n path('create_teacher', views.create_teacher, name='create_teacher'),\n path('add_teacher', views.add_teacher, name='add_teacher'),\n path('create_student', views.create_student, name='create_student'),\n path('add_student', views.add_student, name='add_student'),\n path('create_class', views.create_class, name='create_class'),\n path('add_class', views.add_class, name='add_class'),\n\n]\n","sub_path":"Admin_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"579577187","text":"#Scraping Numbers from HTML using BeautifulSoup\n#In this assignment you will write a Python program similar \n#to http://www.pythonlearn.com/code/urllink2.py. The program will use urllib to read the HTML from the data files below, \n#and parse the data, extracting numbers and compute the sum of the numbers in the file. \n\n#Data Format\n\n#The file is a table of names and comment counts. You can ignore most of the data in the file except for lines like the following:\n\n#Modu90\n#Kenzie88\n#Hubert87\n\nimport urllib\nimport re\ncount = 0\nfrom BeautifulSoup import *\n\nurl = \"http://python-data.dr-chuck.net/comments_283399.html\"\n\nhtml = urllib.urlopen(url).read()\nsoup = BeautifulSoup(html)\n\ntags = soup(\"span\")\n\nfor tag in tags:\n\tstringnumber = tag.contents\n\tnumber= int(stringnumber[0-1])\n\tcount = count+ number\nprint (count)\n","sub_path":"python3.x/Scraping HTML data with BeautifulSoup.py","file_name":"Scraping HTML data with BeautifulSoup.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"165811707","text":"from django.shortcuts import render, render_to_response\nfrom django.views import View\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .models import Lot\n\n\nclass MyView(View):\n def get(self, request):\n context = {}\n all_lots = Lot.objects.order_by('start_date')\n context['all_lots'] = all_lots\n current_page = Paginator(all_lots, 10)\n page = request.GET.get('page')\n try:\n # Если существует, то выбираем эту страницу\n context['lot_lists'] = current_page.page(page)\n except PageNotAnInteger:\n # Если None, то выбираем первую страницу\n context['lot_lists'] = current_page.page(1)\n except EmptyPage:\n # Если вышли за последнюю страницу, то возвращаем последню��\n context['lot_lists'] = current_page.page(current_page.num_pages)\n\n return render_to_response('auction/index.html', context)\n","sub_path":"auction/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"116684985","text":"import numpy as np\nfrom scipy.constants import speed_of_light\nfrom simphony import Model\nfrom simphony.pins import Pin, PinList\nfrom simphony.tools import interpolate\n\nimport gdsfactory as gf\nimport gdsfactory.simulation.lumerical as sim\nfrom gdsfactory.component import Component\n\n\ndef model_from_gdsfactory(\n component: Component, dirpath=gf.CONFIG[\"sparameters\"], **kwargs\n) -> Model:\n \"\"\"Return simphony model from gdsfactory Component Sparameters.\n\n Args:\n component: component factory or instance.\n dirpath: sparameters directory.\n kwargs: settings.\n\n \"\"\"\n kwargs.pop(\"function_name\", \"\")\n kwargs.pop(\"module\", \"\")\n component = gf.call_if_func(component, **kwargs)\n pins, f, s = sim.read_sparameters_lumerical(component=component, dirpath=dirpath)\n\n def interpolate_sp(freq):\n return interpolate(freq, f, s)\n\n Model.pin_count = len(pins)\n m = Model()\n m.pins = PinList([Pin(component=m, name=pins[i]) for i, _ in enumerate(pins)])\n m.__setattr__(\"sparams\", (f, s))\n m.s_parameters = interpolate_sp\n m.freq_range = (m.sparams[0][0], m.sparams[0][-1])\n m.wavelengths = speed_of_light / np.array(f)\n m.s = s\n return m\n\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n\n c = model_from_gdsfactory(gf.c.mmi2x2())\n # c = model_from_gdsfactory(gf.c.mmi2x2())\n # c = model_from_gdsfactory(gf.c.bend_euler())\n # wav = np.linspace(1520, 1570, 1024) * 1e-9\n # f = speed_of_light / wav\n # s = c.s_parameters(freq=f)\n\n wav = c.wavelengths\n s = c.s\n plt.plot(wav * 1e9, np.abs(s[:, 1] ** 2))\n plt.show()\n","sub_path":"gdsfactory/simulation/simphony/model_from_gdsfactory.py","file_name":"model_from_gdsfactory.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"19907024","text":"# -*- coding:utf-8 -*-\n\nimport scrapy\nfrom lianjiascrapy.items import LJwechatxiaoquItem\nfrom lianjiascrapy.settings import WX_BASE_URL\nfrom lianjiascrapy.utils.projects import get_authorization\nimport json\nimport requests\nimport time\n\nclass LJwechatxiaoqudetSpider(scrapy.Spider):\n name = 'ljwechat'\n allowed_domains = ['wechat.lianjia.com']\n\n # WX_BASE_URL = 'https://wechat.lianjia.com'\n \n def __init__(self, *args, **kwargs):\n super(LJwechatxiaoqudetSpider, self).__init__(*args, **kwargs)\n self.base_url = WX_BASE_URL\n self.api = \"/xiaoqu/detail?resblock_code=\"\n self.new_resblock = self.base_url + self.api\n self.headers = {\n \"time-stamp\": str(int(time.time()*1000)),\n \"lianjia-source\": \"ljwxapp\",\n \"authorization\": \"\"\n }\n\n def start_requests(self):\n start_urls = []\n with open('new10.json', encoding='utf-8') as f:\n for item in f.readlines():\n item = json.loads(item)\n xiaoqunum = item['id']\n url = self.new_resblock + str(xiaoqunum)\n self.headers[\"authorization\"] = get_authorization(url)\n req = scrapy.Request(\n url=url,\n headers=self.headers\n )\n start_urls.append(req)\n return start_urls\n\n def parse(self, response):\n item = LJwechatxiaoquItem()\n text = json.loads(response.text)\n if text['data']['info']['name']:\n item['name'] = text['data']['info']['name']\n else:\n item['name'] = '暂无信息'\n\n if text['data']['info']['cycle_line_name']:\n item['xiaoqu_location'] = text['data']['info']['cycle_line_name']\n else:\n item['xiaoqu_location'] = '暂无信息'\n \n if text['data']['info']['point_lat']:\n item['point_lat'] = text['data']['info']['point_lat']\n item['point_lng'] = text['data']['info']['point_lng']\n else:\n item['point_lat'] = '暂无信息'\n item['point_lng'] = '暂无信息'\n if 'quality' in text['data'].keys():\n item['trade_auth'] = text['data']['quality']['xiaoqugaikuang']['hdicInfo'][1]['value']\n else:\n item['trade_auth'] = '暂无信息'\n\n if 'quality' in text['data'].keys():\n item['heat'] = text['data']['quality']['wuyepinzhi']['hdicInfo'][3]['value']\n else:\n item['heat'] = '暂无信息'\n\n if 'quality' in text['data'].keys():\n item['xiaoquoffon'] = text['data']['quality']['wuyepinzhi']['hdicInfo'][4]['value']\n else:\n item['xiaoquoffon'] = '暂无信息'\n\n if 'quality' in text['data'].keys():\n item['carlocation'] = text['data']['quality']['tingcheqingkuang']['hdicInfo'][2]['value']\n else:\n item['carlocation'] = '暂无信息'\n\n if 'quality' in text['data'].keys():\n item['traffic_type'] = text['data']['quality']['tingcheqingkuang']['hdicInfo'][3]['value']\n else:\n item['traffic_type'] = '暂无信息'\n yield item\n ","sub_path":"lianjiascrapy/spiders/box/ljwechatxiaoqudet.py","file_name":"ljwechatxiaoqudet.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"126837428","text":"import threading\n\nfrom . timeline import Timeline\nfrom . database import Database\n\nclass Dashboard:\n\n def __init__(self):\n self.database = Database()\n\n def get_dashboard(self, access_token, since=\"-0 year\", until=\"-0 year\"):\n dashboard = Timeline().getTimeline(access_token, since, until)\n updateDatabase_thread = threading.Thread(target=self.database.update_dashboard, args=(dashboard['_uid'], dashboard['name'], dashboard['reactions']['data'], dashboard['comments']['data']), daemon= True)\n updateDatabase_thread.start()\n return dashboard\n\n def get_all_top(self, uid):\n data = self.database.get_all_top(uid)\n return {\n '_uid' : data['_uid'],\n 'name' : data['name'],\n 'comments' : {\n 'data' : data['comments']\n },\n 'reactions' : {\n 'data' : data['reactions']\n }\n }","sub_path":"modules/dashboard/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"327059898","text":"#\nfrom battlecode import BCAbstractRobot, SPECS\nimport battlecode as bc\nfrom bots.first_bot.utils import *\n\n\nclass CombatManager(object):\n \"\"\"\n manages combat action, movement and GIVING of resources\n \"\"\"\n my_team = -1\n\n my_castles = []\n my_military = []\n my_civil = []\n my_signaling_units = []\n\n enemy_castles = []\n enemy_military = []\n enemy_civil = []\n enemy_signaling_units = []\n\n attackable = []\n attackable_by_allies = []\n i_am_attackable = []\n seen = []\n\n def __init__(self, bc):\n self.my_team = team(bc.me)\n\n\n def turn(self, bc):\n \"\"\"\n The loop which checks visible units and bins them into lists\n :param bc: battlecode_object\n \"\"\"\n self._reset_lists()\n\n im_military = bc.me.unit == SPECS['CRUSADER'] \\\n or bc.me.unit == SPECS['PROPHET'] \\\n or bc.me.unit == SPECS['PREACHER'] \\\n or bc.me.unit == SPECS['CASTLE']\n\n for r in bc.vision_list: # For each robot visible\n # Check if is signaling and not in vision range\n if not bc.is_visible(r):\n # this robot isn't actually in our vision range,\n # it just turned up because we heard its radio broadcast.\n if r.team == self.my_team:\n self.my_signaling_units.append(r)\n else:\n self.enemy_signaling_units.append(r)\n bc.log('Enemy signaling unit at: {}'.format((r.x, r.y)))\n # bc.log(r)\n continue\n\n # Check if it is your team\n if r.team == self.my_team: # MY TEAM\n # bc.log('Ally unit:')\n # bc.log(r)\n # Castle, Civil or Military ?\n if r.unit == SPECS['CASTLE'] or r.unit == SPECS['CHURCH']:\n if not loc_in_list(locate(r), bc.map_process.my_castles):\n bc.map_process.my_castles.append(locate(r))\n self.my_castles.append(r)\n continue\n if r.unit == SPECS['PILGRIM']:\n self.my_civil.append(r)\n continue\n if r.unit == SPECS['CRUSADER'] \\\n or r.unit == SPECS['PROPHET'] \\\n or r.unit == SPECS['CASTLE'] \\\n or r.unit == SPECS['PREACHER']:\n self.my_military.append(r)\n continue\n\n # Check if is other team\n else: # ENEMY TEAM\n # Castle, Civil or Military ?\n if r.unit == SPECS['CASTLE'] or r.unit == SPECS['CHURCH']:\n if not loc_in_list(locate(r), bc.map_process.enemy_castles):\n bc.map_process.enemy_castles.append(locate(r))\n self.enemy_castles.append(r)\n if r.unit == SPECS['PILGRIM']:\n self.enemy_civil.append(r)\n if r.unit == SPECS['CRUSADER'] \\\n or r.unit == SPECS['PROPHET'] \\\n or r.unit == SPECS['PREACHER'] \\\n or r.unit == SPECS['CASTLE'] \\\n or r.unit == SPECS['CASTLE']:\n self.enemy_military.append(r)\n\n # Am I attackable by it?\n if am_i_attackable(bc, r):\n self.i_am_attackable.append(r)\n\n if im_military:\n # Is attackable by me?\n if is_attackable(bc, r):\n self.attackable.append(r)\n\n bc.log('Enemy unit: {}'.format(TYPES[r.unit]))\n\n # END FOR\n\n # Is attackable by allied military?\n if im_military:\n for enemy in self.attackable:\n for ally in self.my_military:\n if is_attackable_unit(ally, enemy):\n self.attackable_by_allies.append(enemy)\n break\n\n # # Debug\n # self.log_lists(bc)\n\n # # Yay, coding for things that cannot be done\n # def lowest_health_enemy(self):\n # min_health = 10000\n # enemy = None\n # for r in self.attackable:\n # if r.health < min_health:\n # min_health = r.health\n # enemy = r\n # return enemy\n\n def lowest_health_enemy(self):\n min_health = 10000\n enemy = None\n unit_specs = SPECS['UNITS']\n for r in self.attackable:\n hp = unit_specs[r.unit]['STARTING_HP']\n if hp < min_health:\n min_health = hp\n enemy = r\n return enemy\n\n def closest_visible_enemy(self, bc):\n enemies_lists = [self.enemy_castles, self.enemy_military, self.enemy_civil]\n min_dist = 10000\n enemy = None\n for lista in enemies_lists:\n for r in lista:\n # bc.log(r)\n dist = distance(locate(bc.me), locate(r))\n if dist < min_dist:\n min_dist = dist\n enemy = r\n return enemy\n\n # TODO test\n def best_spot_to_move(self, bc):\n bc.log('Choosing best tile for combat')\n if self.favorable_fight(bc):\n return (0, 0)\n\n candidates = {}\n max_points = -9999\n chosen_spot = None\n tiles = passable_movement_tiles(bc, *locate(bc.me))\n\n for spot in tiles:\n candidates[spot] = 0\n\n for robot in self.enemy_military:\n for spot in tiles:\n if can_be_attacked(spot, robot):\n candidates[spot] -= 1\n\n bc.log('Good Movements {}'.format(candidates))\n # May break\n for spot in candidates.keys():\n points = candidates[spot]\n if points > max_points:\n max_points = points\n chosen_spot = spot\n\n return tuple([int(x) for x in chosen_spot.split(',')]) # FUCK JAVASCRIPT AND YOUR TRANSPILER, REALLY\n\n\n # TODO test\n # do we outgun castle?\n def can_we_outgun_castle(self, bc):\n\n return (len(self.my_military) - len(self.enemy_military) > 3)\n\n def favorable_fight(self, bc):\n\n return (len(self.my_military) - len(self.enemy_military) > 0)\n\n def heavily_outgunned(self, bc):\n\n return (len(self.my_military) - len(self.enemy_military) < -4)\n\n\n # TODO new targeting to oneshot castle if possible\n # TODO target civil units\n # TODO the 3 different targetings needed\n # TODO check if i have been attacked and if im going to lose the combat then retreat\n\n\n\n # TODO test\n def are_there_closeby_churches(self, bc):\n bc.log(' my_castles: {}'.format(bc.map_process.my_castles))\n for church in bc.map_process.my_castles:\n if man_distance(locate(bc.me), church) < 7:\n return True\n return False\n\n def get_deposit(self, bc):\n bc.log(' my_deposits: {}'.format(bc.map_process.my_castles))\n return bc.map_process.my_castles\n\n def are_enemies_near(self, bc):\n \"\"\" True if yes \"\"\"\n return (len(self.enemy_castles) > 0) or (len(self.enemy_civil) > 0) or (len(self.enemy_military) > 0)\n\n def _reset_lists(self):\n \"\"\" resets all lists for each turn \"\"\"\n self.my_castles = []\n self.my_military = []\n self.my_civil = []\n self.my_signaling_units = []\n self.enemy_castles = []\n self.enemy_military = []\n self.enemy_civil = []\n self.enemy_signaling_units = []\n self.attackable = []\n self.attackable_by_allies = []\n self.i_am_attackable = []\n\n def log_lists(self, bc):\n bc.log('my_castles: {}'.format(len(self.my_castles)))\n bc.log('my_military: {}'.format(len(self.my_military)))\n bc.log('my_civil: {}'.format(len(self.my_civil)))\n bc.log('my_signaling_units: {}'.format(len(self.my_signaling_units)))\n bc.log('enemy_castles: {}'.format(len(self.enemy_castles)))\n bc.log('enemy_military: {}'.format(len(self.enemy_military)))\n bc.log('enemy_civil: {}'.format(len(self.enemy_civil)))\n bc.log('enemy_signaling_units: {}'.format(len(self.enemy_signaling_units)))\n bc.log('attackable: {}'.format(len(self.attackable)))\n bc.log('attackable_by_allies: {}'.format(len(self.attackable_by_allies)))\n bc.log('i_am_attackable: {}'.format(len(self.i_am_attackable)))\n\n\n#\n","sub_path":"bots/first_bot/utils/combat.py","file_name":"combat.py","file_ext":"py","file_size_in_byte":8479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"55704119","text":"# -*- coding: utf-8 -*-\n\"\"\"\n proxy.py\n ~~~~~~~~\n ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on\n Network monitoring, controls & Application development, testing, debugging.\n\n :copyright: (c) 2013-present by Abhinav Singh and contributors.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nfrom abc import abstractmethod\nimport socket\nimport selectors\nfrom typing import Any, Optional, Dict\n\nfrom ...http.parser import HttpParser, httpParserTypes\nfrom ...common.types import Readables, Writables\nfrom ...common.utils import text_\n\nfrom ..connection import TcpServerConnection\nfrom .tcp_server import BaseTcpServerHandler\n\n\nclass BaseTcpTunnelHandler(BaseTcpServerHandler):\n \"\"\"Base TCP tunnel interface.\"\"\"\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self.request = HttpParser(httpParserTypes.REQUEST_PARSER)\n self.upstream: Optional[TcpServerConnection] = None\n\n @abstractmethod\n def handle_data(self, data: memoryview) -> Optional[bool]:\n pass # pragma: no cover\n\n def initialize(self) -> None:\n self.client.connection.setblocking(False)\n\n def shutdown(self) -> None:\n if self.upstream:\n print('Connection closed with upstream {0}:{1}'.format(\n text_(self.request.host), self.request.port))\n self.upstream.close()\n super().shutdown()\n\n def get_events(self) -> Dict[socket.socket, int]:\n # Get default client events\n ev: Dict[socket.socket, int] = super().get_events()\n # Read from server if we are connected\n if self.upstream and self.upstream._conn is not None:\n ev[self.upstream.connection] = selectors.EVENT_READ\n # If there is pending buffer for server\n # also register for EVENT_WRITE events\n if self.upstream and self.upstream.has_buffer():\n if self.upstream.connection in ev:\n ev[self.upstream.connection] |= selectors.EVENT_WRITE\n else:\n ev[self.upstream.connection] = selectors.EVENT_WRITE\n return ev\n\n def handle_events(\n self,\n readables: Readables,\n writables: Writables) -> bool:\n # Handle client events\n do_shutdown: bool = super().handle_events(readables, writables)\n if do_shutdown:\n return do_shutdown\n # Handle server events\n if self.upstream and self.upstream.connection in readables:\n data = self.upstream.recv()\n if data is None:\n # Server closed connection\n print('Connection closed by server')\n return True\n # tunnel data to client\n self.client.queue(data)\n if self.upstream and self.upstream.connection in writables:\n self.upstream.flush()\n return False\n\n def connect_upstream(self) -> None:\n assert self.request.host and self.request.port\n self.upstream = TcpServerConnection(\n text_(self.request.host), self.request.port)\n self.upstream.connect()\n print('Connection established with upstream {0}:{1}'.format(\n text_(self.request.host), self.request.port))\n","sub_path":"proxy/core/base/tcp_tunnel.py","file_name":"tcp_tunnel.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"172841991","text":"import os,nltk\n\nfilePath = 'D:/pdf2txts/'\nlst = os.listdir(filePath)\noutlines = []\n\nprint(len(lst))\ncount = 0\nfor i in lst:\n try:\n count += 1\n f = open(filePath+i,'r',encoding='utf-8')\n lines = f.readlines()\n f.close()\n\n for line in lines:\n if line.strip() == '' or line[0] == '#' or line[0] == '.':\n continue\n for j in nltk.sent_tokenize(line):\n if(len(j)<=32):\n continue\n # print(j)\n outlines.append(j + '\\n')\n\n print(count,' ',i)\n except:\n with open('process_failed.txt', 'a', encoding='utf-8') as f:\n f.write(filePath + i + '\\n')\n f.close()\n\nprint('writing...')\noutlines = [i for i in set(outlines)]\nf = open('Docs.txt','w',encoding='utf-8')\nf.writelines(outlines)\nf.close()","sub_path":"python/transdata.py","file_name":"transdata.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"411623090","text":"\"\"\"Configuration data container with interactive ipywidgets GUI\"\"\"\n\nimport json\n\nimport ipywidgets\nimport jsonschema\n\n\nclass DictWidget():\n \"\"\"Container class for configuration data\n\n Constructed from a JSON Schema. Use like a dictionary to store and retrieve configuration data.\n Will also create a ipywidget interactive representation via `gui()`. Also supports nested schemata\n (i.e. a schema tha contains `object` properties, which are themselves configuration containers.\"\"\"\n\n def __init__(self, schema):\n \"\"\"Construct a Configuration object from a JSON schema definition\"\"\"\n\n self.schema = schema\n self.data = {}\n self.callback = None\n self.children = {}\n\n # Create GUI\n # Widget objects are collected in a dictionary (for update in __setitem__())\n # as well as a list (together with their description labels to create a VBox for display).\n self.widgets = {}\n self.widgetlist = []\n for name, props in self.schema['properties'].items():\n minimum = props.get('minimum', None)\n maximum = props.get('maximum', None)\n description = props.get('description', '')\n # Containers create new `Configuration` instances - save those children for later\n if props['type'] == 'object':\n subschema = {\"title\": name, \"type\": \"object\", \"properties\": props['properties']}\n self.children[name] = Configuration(subschema)\n else:\n # Scalar data elements are displayed as is\n if props['type'] == 'integer':\n value = self.data.get(name, props.get('default', 0))\n widget = ipywidgets.IntSlider(description=name, min=minimum, max=maximum, value=value)\n elif props['type'] == 'number':\n value = self.data.get(name, props.get('default', 0.0))\n widget = ipywidgets.FloatSlider(description=name, min=minimum, max=maximum, value=value)\n elif props['type'] == 'string':\n # also supports drop down\n value = self.data.get(name, props.get('default', ''))\n if 'choices' in props:\n widget = ipywidgets.Dropdown(options=props['choices'].split(';'), value=value, description=name)\n else:\n widget = ipywidgets.Text(description=name, value=value)\n elif props['type'] == 'boolean':\n value = self.data.get(name, props.get('default', False))\n widget = ipywidgets.Checkbox(description=name, value=value)\n else:\n widget = ipywidgets.Label(description=name, value=f\"Don't know how to draw {props['type']}\")\n\n widget.observe(self.on_value_change, names='value')\n # save for self-reference\n self.widgets[name] = widget \n self.widgetlist.append(ipywidgets.HBox([widget, ipywidgets.Label(value=description)]))\n\n # Add all saved children in a Tab\n if self.children:\n widget = ipywidgets.Tab([c._gui for c in self.children.values()])\n for i, c in enumerate(self.children.keys()):\n widget.set_title(i, c)\n widget.observe(self.on_value_change, names='value')\n # save for self-reference\n self.widgets['_children'] = widget \n self.widgetlist.append(widget)\n\n # Return all widgets in a VBox\n self._gui = ipywidgets.VBox(self.widgetlist)\n\n\n def from_dict(self, dict_in):\n \"\"\"Load configuration data from a dictionary.\n\n Will validate input against schema used in object construction.\"\"\"\n\n jsonschema.validate(dict_in, self.schema)\n for key, value in dict_in.items():\n if isinstance(value, dict):\n self.children[key].from_dict(value)\n else:\n self[key] = value\n\n\n def from_json(self, json_in):\n \"\"\"Load configuration data from JSON.\"\"\"\n\n temp = json.loads(json_in)\n self.from_dict(temp)\n\n\n def to_json(self):\n \"\"\"Dump configuration data as JSON.\"\"\"\n\n if not self.data:\n return None\n return json.dumps(self.to_dict())\n\n\n def to_dict(self):\n \"\"\"Dump configuration data as dictionary.\"\"\"\n\n ret = dict(self.data)\n for name, child in self.children.items():\n ret[name] = child.to_dict()\n return ret\n\n\n def __repr__(self):\n return 'Configuration \"' + self.schema['title'] + '\" ' + str(self.data)\n\n\n def __getitem__(self, item):\n \"\"\"Allow using dict syntax for object retrievel.\n\n Will first try to locate a child configuration object. If that's not found,\n it will then look for a data item.\"\"\"\n\n if item in self.children:\n return self.children[item]\n return self.data.__getitem__(item)\n\n\n def __setitem__(self, item, value):\n \"\"\"Allow using dict syntax for setting values.\n\n Will only allow setting values in accordance with schema used for object\n generation.\"\"\"\n\n if item not in self.schema['properties']:\n raise KeyError(f'\"{item}\" not in schema')\n temp = dict(self.data)\n temp.__setitem__(item, value)\n jsonschema.validate(temp, self.schema)\n self.data.__setitem__(item, value)\n # update any gui that may exist\n if item in self.widgets:\n self.widgets[item].value = value\n\n\n def on_value_change(self, change):\n \"\"\"Callback for GUI updates.\"\"\"\n\n key = change['owner'].description\n self[key] = change['new']\n if self.callback:\n self.callback(self.to_dict()) # TODO: expensive!\n\n def interact(self, callback=None):\n \"\"\"Return an interactive ipywidgets GUI for setting configuration values.\n\n Will call `callback` with a dictionary of data values on change.\"\"\"\n\n self.callback = callback\n # Update children's callbacks, too.\n for c in self.children.values():\n c.callback = callback\n return self._gui\n","sub_path":"rfsoc_qpsk/dict_widget.py","file_name":"dict_widget.py","file_ext":"py","file_size_in_byte":6175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"532238745","text":"import theano as th\nimport theano.tensor as T\nimport numpy as np\nfrom theano.tensor.shared_randomstreams import RandomStreams\nfrom sklearn.utils import shuffle\nfrom utils import error_rate, create_graph, one_hot_encoding\n\nclass HiddenLayer(object):\n def __init__(self, M1, M2, h_id):\n self.id = h_id\n self.M1 = M1\n self.M2 = M2\n W_init = np.random.randn(M1, M2)\n b_init = np.zeros(M2)\n self.W = th.shared(W_init, 'W_{}'.format(h_id))\n self.b = th.shared(b_init, 'b_{}'.format(h_id))\n self.params = [self.W, self.b]\n \n def forward(self, X):\n return T.nnet.relu(X.dot(self.W) + self.b)\n \n\nclass MultiLayerNN(object):\n def __init__(self, D, K, h_layer_sizes, ps_keep):\n self.dropout_rates = ps_keep\n self.hidden_layers = []\n self.mask_generator = RandomStreams()\n M1 = D\n M2 = None\n count = 0\n for M2 in h_layer_sizes:\n self.hidden_layers.append(HiddenLayer(M1, M2, count))\n M1 = M2\n count += 1\n \n W = np.random.randn(M1, K) \n b = np.zeros(K)\n self.W = th.shared(W, 'W_last')\n self.b = th.shared(b, 'b_last')\n \n self.thX = T.matrix('X')\n self.thT = T.matrix('T')\n # Collect params for future i=use of gradient descent\n self.params = [self.W, self.b]\n for h in self.hidden_layers:\n self.params += h.params\n \n \n def forward(self, X):\n Z = X\n for hidden_layer in self.hidden_layers:\n Z = hidden_layer.forward(Z)\n \n return T.nnet.softmax(Z.dot(self.W) + self.b)\n \n def forward_train(self, X):\n Z = X\n for hidden_layer, p_keep in zip(self.hidden_layers, self.dropout_rates):\n mask = self.mask_generator.binomial(n=1, p=p_keep, size=Z.shape)\n Z = Z * mask\n Z = hidden_layer.forward(Z)\n \n return T.nnet.softmax(Z.dot(self.W) + self.b)\n \n def fit(self, Xtrain, Ytrain, Xtest, Ytest, learning_rate=0.0001, mu=0.9, decay=0.999, epochs=9, batch_sz=100):\n Xtrain = Xtrain.astype(np.float32)\n Ytrain = Ytrain.astype(np.int32)\n Xtest = Xtest.astype(np.float32)\n Ytest = Ytest.astype(np.int32)\n \n Yp_train = self.forward_train(self.thX)\n cost = -T.mean(self.thT*T.log(Yp_train))\n \n # Find all gradients at once\n grads = T.grad(cost, self.params)\n \n # For momentum\n m_params = [th.shared(np.zeros_like(p.get_value())) for p in self.params]\n \n # For rmsprop\n caches = [th.shared(np.ones_like(p.get_value())) for p in self.params]\n eps = 10e-10\n \n new_caches = [decay*cache + (1-decay)*grad*grad for cache, grad in zip(caches, grads)]\n new_m_params = [mu*m_param + learning_rate*g/T.sqrt(new_cache + eps) for m_param, g, new_cache in zip(m_params, grads, new_caches)]\n new_params = [param - new_m_param for param, new_m_param in zip(self.params, new_m_params)] \n \n updates = [\n (cache, new_cache) for cache, new_cache in zip(caches, new_caches)\n ] + [\n (m_param, new_m_param) for m_param, new_m_param in zip(m_params, new_m_params)\n ] + [\n (param, new_param) for param, new_param in zip(self.params, new_params)\n ]\n \n train_op = th.function(\n inputs=[self.thX, self.thT],\n updates=updates\n )\n \n Yp_predict = self.forward(self.thX)\n cost_predict = -(self.thT*T.log(Yp_predict)).mean()\n cost_predict_op = th.function(inputs=[self.thX, self.thT], outputs=[cost_predict, Yp_predict])\n \n n_batches = len(Xtrain) // batch_sz\n costs, errors = [], []\n \n for i in range(epochs):\n Xtrain, Ytrain = shuffle(Xtrain, Ytrain)\n \n for j in range(n_batches):\n Xbatch = Xtrain[j*batch_sz:(j+1)*batch_sz]\n Ybatch = Ytrain[j*batch_sz:(j+1)*batch_sz]\n \n train_op(Xbatch, Ybatch)\n c, Yp = cost_predict_op(Xtest, Ytest)\n err = error_rate(np.argmax(Yp, axis=1), np.argmax(Ytest, axis=1))\n costs.append(c)\n errors.append(err)\n if j % 20 == 0:\n print('Accuracy: ', 1 - err)\n print('Cost: ', c)\n \n return costs, errors\n \n \n \ndef main():\n Nclass = 500\n D = 2\n X1 = np.random.randn(Nclass, D) + np.array([0, 2])\n X2 = np.random.randn(Nclass, D) + np.array([-2, 2])\n X3 = np.random.randn(Nclass, D) + np.array([-2, 0])\n X = np.vstack([X1, X2, X3])\n \n Y = np.array([0]*Nclass + [1]*Nclass + [2]*Nclass)\n Y = one_hot_encoding(Y)\n \n \n N = 1500\n H = 10\n K = 3\n \n Xtrain = X[:-100]\n Ytrain = Y[:-100]\n Xtest = X[-100:]\n Ytest = Y[-100:]\n \n model = MultiLayerNN(D, K, [10, 10], [0.5, 0.5])\n costs, errors = model.fit(Xtrain, Ytrain, Xtest, Ytest, epochs=1000)\n \n create_graph(costs, 'cost.png', y_label='cost', x_label='iteration')\n create_graph(errors, 'error.png', y_label='error', x_label='iteration')\n\nif __name__ == '__main__':\n main()\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"neural_nets/NN_with_dropout/theano_version/multilayer_NN.py","file_name":"multilayer_NN.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"298784422","text":"\"\"\"Dataset and data loader for SR3D.\"\"\"\n\nfrom copy import deepcopy\nimport csv\nfrom six.moves import cPickle\nimport os.path as osp\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nimport torch.multiprocessing\n# torch.multiprocessing.set_sharing_strategy('file_system')\n\nfrom data.create_sr3d_programs import (\n PROXIMITY_CLOSE_RELS, PROXIMITY_FAR_RELS,\n BETWEENS, VIEW_DEP_RELS, OTHER_RELS,\n utterance2program\n)\nfrom src.data_handling.lang_data_handlers import SR3DDataUtils\nfrom src.data_handling.visual_data_handlers import Scan, ScanNetMappings\n\n\nclass SR3DDataset(Dataset):\n \"\"\"Dataset utilities for SR3D.\"\"\"\n\n def __init__(self, annos_path, scan_path, split='train', seed=1184,\n pkl_path='/projects/katefgroup/language_grounding', low_shot=None, rotate_scene=False):\n \"\"\"Initialize dataset (here for Sr3D utterances).\"\"\"\n self.annos_path = annos_path\n self.scan_path = scan_path\n self.split = split\n self.seed = seed\n self.low_shot = low_shot\n self.rotate_scene = rotate_scene\n self.annos = self.load_annos()\n self.sr3d = SR3DDataUtils(annos_path)\n print('Loading %s files, take a breath!' % split)\n split = 'test' if split != 'train' else 'train'\n if not osp.exists(f\"{pkl_path}/{split}_scans.pkl\"):\n save_data(f\"{pkl_path}/{split}_scans.pkl\", scan_path, split)\n _, self.scans = unpickle_data(f\"{pkl_path}/{split}_scans.pkl\")\n\n def load_annos(self):\n \"\"\"Load annotations.\"\"\"\n split = 'train' if self.split == 'train' else 'test'\n with open('data/extra/sr3d_%s_scans.txt' % split) as fid:\n scan_ids = set(eval(fid.read()))\n with open(self.annos_path) as fid:\n csv_reader = csv.reader(fid)\n headers = next(csv_reader)\n headers = {header: h for h, header in enumerate(headers)}\n annos = [\n {\n 'scan_id': line[headers['scan_id']],\n 'target_id': int(line[headers['target_id']]),\n 'distractor_ids': eval(line[headers['distractor_ids']]),\n 'utterance': line[headers['utterance']],\n 'target': line[headers['instance_type']],\n 'anchors': eval(line[headers['anchors_types']])\n }\n for line in csv_reader\n if line[headers['scan_id']] in scan_ids\n and ',' in line[headers['utterance']]\n ]\n if self.split == 'train':\n extra_annos = []\n for anno in annos:\n if ',' in anno['utterance']:\n advcl = anno['utterance'].split(', ')[0] + ', '\n advcl = advcl.replace('side you sit on it', 'its front')\n advcl = advcl.replace('front', 'back')\n text = anno['utterance'].split(', ')[1]\n if 'right' in text:\n text = text.replace('right', 'left')\n elif 'left' in text:\n text = text.replace('left', 'right')\n elif 'in front of' in text:\n text = text.replace('in front of', 'behind')\n elif 'on the back of' in text or 'behind' in text:\n text = text.replace('on the back of', 'in front of')\n text = text.replace('behind', 'in front of')\n extra_anno = deepcopy(anno)\n extra_anno['utterance'] = advcl + text\n extra_annos.append(extra_anno)\n annos += extra_annos\n if self.split == 'train' or True:\n proxim = PROXIMITY_FAR_RELS + PROXIMITY_CLOSE_RELS\n annos = [\n anno for anno in annos\n if not any(word in anno['utterance'] for word in proxim)\n ]\n if self.split == 'train' and self.low_shot is not None:\n np.random.seed(self.seed)\n inds = np.random.permutation(np.arange(len(annos)))\n annos = np.array(annos)[inds]\n rels = BETWEENS + VIEW_DEP_RELS + OTHER_RELS\n keep_inds = []\n for rel in rels:\n if rel == 'on':\n continue\n ind = 0\n cnt = 0\n while cnt < self.low_shot and ind < len(annos):\n if rel in annos[ind]['utterance'] and ind not in keep_inds:\n keep_inds.append(ind)\n cnt += 1\n ind += 1\n annos = annos[np.array(keep_inds)]\n return annos\n\n def __getitem__(self, index):\n \"\"\"Get current batch for input index.\"\"\"\n anno = self.annos[index]\n # Pointcloud\n scan = deepcopy(self.scans[anno['scan_id']])\n if self.rotate_scene and self.split == 'train':\n theta = np.random.rand() * 360\n scan.pc = rot_z(scan.pc, theta)\n scan.color = rot_z(scan.color, theta)\n labels = [obj['instance_label'] for obj in scan.three_d_objects]\n point_clouds = [\n torch.from_numpy(scan.get_object_pc(obj_id)).float()\n for obj_id in range(len(scan.three_d_objects))\n ]\n # Mine tags\n utterance, tag_dict = self.sr3d.tag_utterance(\n anno['utterance'], anno['anchors'][0]\n )\n # Program ground-truth (should not need this)\n program_list = utterance2program(' '.join(utterance))\n for op in program_list:\n if 'relational_concept' in op:\n op['relational_concept'] = [\n tag_dict[con][0][0] for con in op['relational_concept']\n ]\n elif 'concept' in op:\n op['concept'] = [tag_dict[con][0][0] for con in op['concept']]\n return {\n \"utterance\": ' '.join(utterance),\n \"raw_utterance\": anno['utterance'],\n \"tag_dict\": tag_dict,\n \"program_list\": program_list,\n \"scan_id\": anno['scan_id'],\n \"point_cloud\": point_clouds,\n \"obj_labels\": labels,\n \"target_id\": torch.as_tensor(anno['target_id']).long()\n }\n\n def __len__(self):\n \"\"\"Return number of utterances.\"\"\"\n return len(self.annos)\n\n\ndef sr3d_collate_fn(batch):\n \"\"\"\n Collate function for SR3D grounding.\n See sr3d_parser_collate_fn for most arguments.\n \"\"\"\n return {\n \"utterances\": [ex[\"utterance\"] for ex in batch],\n \"raw_utterances\": [ex[\"raw_utterance\"] for ex in batch],\n \"tag_dicts\": [ex[\"tag_dict\"] for ex in batch],\n \"program_list\": [ex[\"program_list\"] for ex in batch],\n \"scan_ids\": [ex[\"scan_id\"] for ex in batch],\n \"point_clouds\": [ex[\"point_cloud\"] for ex in batch],\n \"obj_labels\": [ex[\"obj_labels\"] for ex in batch],\n \"target_ids\": [ex[\"target_id\"] for ex in batch]\n }\n\n\ndef rot_z(pc, theta):\n \"\"\"Rotate along z-axis.\"\"\"\n theta = theta * np.pi / 180\n return np.matmul(\n np.array([\n [np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0],\n [0, 0, 1.0]\n ]),\n pc.T\n ).T\n\n\ndef scannet_loader(iter_obj):\n \"\"\"Load the scans in memory, helper function.\"\"\"\n scan_id, scan_path, scannet = iter_obj\n return Scan(scan_id, scan_path, scannet, True)\n\n\ndef save_data(filename, scan_path, split):\n \"\"\"Save all scans to pickle.\"\"\"\n import multiprocessing as mp\n\n # Read all scan files\n with open('data/extra/sr3d_%s_scans.txt' % split) as fid:\n scan_ids = eval(fid.read())\n print('{} scans found.'.format(len(scan_ids)))\n scannet = ScanNetMappings()\n\n # Load data\n n_items = len(scan_ids)\n n_processes = 4 # min(mp.cpu_count(), n_items)\n pool = mp.Pool(n_processes)\n chunks = int(n_items / n_processes)\n print(n_processes, chunks)\n all_scans = dict()\n iter_obj = [\n (scan_id, scan_path, scannet)\n for scan_id in scan_ids\n ]\n for i, data in enumerate(\n pool.imap(scannet_loader, iter_obj, chunksize=chunks)\n ):\n all_scans[scan_ids[i]] = data\n pool.close()\n pool.join()\n\n # Save data\n print('pickle time')\n pickle_data(filename, scannet, all_scans)\n\n\ndef pickle_data(file_name, *args):\n \"\"\"Use (c)Pickle to save multiple objects in a single file.\"\"\"\n out_file = open(file_name, 'wb')\n cPickle.dump(len(args), out_file, protocol=2)\n for item in args:\n cPickle.dump(item, out_file, protocol=2)\n out_file.close()\n\n\ndef unpickle_data(file_name, python2_to_3=False):\n \"\"\"Restore data previously saved with pickle_data().\"\"\"\n in_file = open(file_name, 'rb')\n if python2_to_3:\n size = cPickle.load(in_file, encoding='latin1')\n else:\n size = cPickle.load(in_file)\n\n for _ in range(size):\n if python2_to_3:\n yield cPickle.load(in_file, encoding='latin1')\n else:\n yield cPickle.load(in_file)\n in_file.close()","sub_path":"script/sr3d_dataset.py","file_name":"sr3d_dataset.py","file_ext":"py","file_size_in_byte":9048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"441166337","text":"\"\"\"\nBuild and train the model of NN\n\n@author: Malwina\n\"\"\"\n\nimport tensorflow\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import model_from_json\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ntar_size = 512\nshape = (tar_size, tar_size, 3)\n\nmodel = tensorflow.keras.Sequential() # rodzaj modelu sieci\n\n# 1. Warstwa konwolucyjna, rozmiar okna: 3x3, głębia jądra: 32\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=shape))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# 2. Warstwa konwolucyjna, rozmiar okna: 3x3, głębia jądra: 64\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# 3. Warstwa konwolucyjna, rozmiar okna: 3x3, głębia jądra: 128\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\nmodel.add(layers.Conv2D(256, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# 4. Warstwa spłaszczająca dane (z 2D na 1D)\nmodel.add(layers.Flatten())\n\n# 5. Warstwa odrzucająca 20% danych\nmodel.add(layers.Dropout(0.2))\n\n# 6. Warstwa gęsta, 256 neuronów\nmodel.add(layers.Dense(256, activation='relu'))\n\n# 7. Warstwa wyjściowa - 1 neuron, bez funkcji aktywacji bo wyjściem ma być wartość wyjściowa (wiek)\nmodel.add(layers.Dense(1))\n\n# Funkcja printująca podsumowanie modelu sieci\nmodel.summary()\n\n# Optymalizator - Adam (prawie zawsze daje najlepsze wyniki)\noptim = optimizers.Adam()\n\n# Kompilacja modelu, loss - funkcja straty, metrics - metryka\n# Funkcja straty: mse, czyli błąd średniokwadratowy, bo wyjściem jest liczba a nie klasa\n# Metryka: mae, czyli średni błąd bezwględny, tak jak wyżej\nmodel.compile(loss='mse', optimizer=optim, metrics=['mae'])\n\ncallbacks = [\n keras.callbacks.ModelCheckpoint( # zapisywanie najlepszego modelu\n filepath=path_dir + 'model_cnn.h5',\n monitor='val_loss',\n save_best_only=True,\n ),\n\n keras.callbacks.EarlyStopping( # zatrzymywanie uczenia po braku poprawy metryki\n monitor='mae',\n patience=4,\n ),\n\n keras.callbacks.ReduceLROnPlateau( # poprawianie lr po utknięciu w minimum\n monitor='val_loss',\n factor=0.1,\n patience=4,\n ),\n]\n\n# Wczytanie danych do pandas df\npath_dir = r'/content/drive/My Drive/colab_files/imdb/'\ndf = pd.read_csv(path_dir + 'train.csv', sep=',', header=0, names=['filepath', 'age'])\ndf_val = pd.read_csv(path_dir + 'test.csv', sep=',', header=0, names=['filepath', 'age'])\n\n# Przetworzenie zdjęć z augumentacją, czyli \"dorabianiem\" nowych zdjęc\n# dane treningowe\ntrain_datagen = ImageDataGenerator(\n rescale=1. / 255,\n rotation_range=10,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n# dane testowe\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\n# Generatory do uczenia sieci\ntrain_generator = train_datagen.flow_from_dataframe(\n dataframe=df,\n directory='',\n x_col='filepath',\n y_col='age',\n target_size=(tar_size, tar_size),\n batch_size=128,\n class_mode='raw', )\n\nvalidation_generator = test_datagen.flow_from_dataframe(\n dataframe=df_val,\n directory='',\n x_col='filepath',\n y_col='age',\n target_size=(tar_size, tar_size),\n batch_size=128,\n class_mode='raw', )\n\n# Wytrenowanie modelu\nhistory = model.fit(\n train_generator,\n steps_per_epoch=20,\n epochs=30,\n validation_data=validation_generator,\n callbacks=callbacks)\n\n# Wykres\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(len(loss))\n\nplt.figure()\nplt.plot(epochs, loss, 'bo', label='Dane treningowe')\nplt.plot(epochs, val_loss, 'b', label='Dane walidacyjne')\nplt.title('Wartości funkcji straty procesu uczenia')\nplt.xlabel('Epoki')\nplt.ylabel('Wartość funkcji straty')\nplt.legend()\nplt.grid(True)\n\nplt.show()\n\n# Zapisanie modelu do pliku json (model) i h5 (wagi)\nmodel_json = model.to_json()\nwith open(path_dir + 'model_cnn.json', 'w') as json_file:\n json_file.write(model_json)\n\n# model.save_weights(path_dir + 'model_cnn.h5')\nprint('Saved model to disk')","sub_path":"NN_Model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"613703994","text":"from django.db import models\nfrom django.core.validators import RegexValidator, MinValueValidator\nfrom django.core.exceptions import ValidationError\nfrom decimal import *\ngetcontext().prec = 2\n\n# Enumeration makes further modifications, if necessary, easier\nRECORD_TYPES = (\n ('S', 'Start'),\n ('E', 'End'),\n)\n\n# Here we define what a valid phone number is,\n# following the repository's guidelines\n# Phone numbers have to be all digits (0-9)\n# Their length has to be between 10 (2 area digits + 8 phone digits)\n# and 11 (2 area digits + 9 phone digits)\nphone_validator_regex = RegexValidator(\n regex=r'^\\d{10,11}$',\n code=\"invalid_phone_number\",\n message='Phone numbers must be all digits,'\n + ' with 2 area code digits and 8 or 9 phone number digits.'\n)\n\n\n# CallRecord models the start and end of a phone call\nclass CallRecord(models.Model):\n # Call records can be either Start or End records\n # Type of the record model.\n type = models.CharField(\n max_length=1,\n choices=RECORD_TYPES\n )\n\n # Timestamp of the event\n timestamp = models.DateTimeField()\n\n # Unique-pair call ID.\n # MinValueValidator is included due to SQLite not verifying\n # for negative numbers even with PositiveIntegerField\n call_id = models.PositiveIntegerField(\n validators=[MinValueValidator(0)]\n )\n\n # Since call_id is not unique, but a unique-pair, we need to define\n # a combination of fields for uniqueness\n class Meta:\n # This makes it so we can have one Start record\n # and one End record with the same call_id, but never more than\n # one of each.\n # Additionally, we can prevent repeated records by checking\n # the call_id and timestamp\n unique_together = (\n ('type', 'call_id'),\n ('call_id', 'timestamp')\n )\n\n # Source (caller) phone number.\n # Uses phone_validator_regex for validation\n source = models.CharField(\n validators=[phone_validator_regex],\n max_length=11,\n null=True\n )\n # Destination (called) phone number.\n # Uses phone_validator_regex for validation\n destination = models.CharField(\n validators=[phone_validator_regex],\n max_length=11,\n null=True\n )\n\n # Additional validation for the record model\n # If we are creating a End Call Record, it should not have any\n # phone numbers stored.\n def validate_end_record_with_numbers(self):\n '''\n Validates end call records have no source or destination numbers\n in its structure\n '''\n if ((self.source or self.destination is not None) and\n self.type == 'E'):\n raise ValidationError('End records must not have numbers.')\n\n def validate_source_and_destination(self):\n '''\n Validates that call records cannot have the same source and\n destination, or one of these fields and not the other\n '''\n if self.source is not None:\n if self.destination is None:\n raise ValidationError(\n 'Cannot create a call with source and no destination'\n )\n if self.source == self.destination:\n raise ValidationError(\n 'Cannot create a call where source is the same as'\n + ' the destination.'\n )\n elif self.destination is not None:\n if self.source is None:\n raise ValidationError(\n 'Cannot create a call with destination and no source'\n )\n\n def validate_source_and_timestamp(self):\n '''\n Validates the uniqueness between a call's source and timestamp\n i.e. a person cannot call two people at once\n '''\n if self.source is not None:\n conflict = CallRecord.objects.filter(\n source=self.source,\n timestamp=self.timestamp\n )\n if self.id is not None:\n conflict = conflict.exclude(pk=self.id)\n if conflict.exists():\n raise ValidationError(\n 'Cannot create a call when there is already a record for'\n + ' this source and timestamp'\n )\n\n def validate_destination_and_timestamp(self):\n '''\n Validates the uniqueness between a call's destination and\n timestamp, i.e. a person cannot receive two calls at once\n '''\n if self.destination is not None:\n conflict = CallRecord.objects.filter(\n destination=self.destination,\n timestamp=self.timestamp\n )\n if self.id is not None:\n conflict = conflict.exclude(pk=self.id)\n if conflict.exists():\n raise ValidationError(\n 'Cannot create a call when there is already a record for'\n + ' this destination and timestamp'\n )\n\n \n def validate_call_id(self):\n '''\n Validates the existence of a start call record if there is an\n attempt to insert an end call record with a given call_id\n '''\n if self.type == 'E':\n start = CallRecord.objects.filter(\n type='S',\n call_id=self.call_id\n )\n if not start.exists():\n raise ValidationError(\n 'Cannot create an end call report with no previous'\n + ' start call report (no start report with this call ID)'\n )\n\n def validate_overlap(self):\n '''\n Validates that calls cannot start before another call has ended\n and if there's an attempt to add a start call record, that it\n cannot exist if there's an end call record in a timestamp\n after its own\n '''\n if self.type == 'S':\n started_calls = CallRecord.objects.filter(\n source=self.source,\n type='S',\n timestamp__lte=self.timestamp\n )\n ended_calls = CallRecord.objects.filter(\n call_id__in=[call.call_id for call in started_calls],\n type='E',\n )\n conflict = ended_calls.filter(\n timestamp__gte=self.timestamp\n )\n if conflict.exists():\n raise ValidationError(\n 'Cannot create a start call report when there is an'\n + ' end call report with a later timestamp for the'\n + ' same source'\n )\n unended_calls = started_calls.exclude(\n call_id__in=[call.call_id for call in ended_calls]\n )\n if unended_calls.exists():\n raise ValidationError(\n 'Cannot create a start call report when there is an'\n + ' unfinished call report for the same source'\n + ' (Unpaired call_id)'\n )\n\n def validate_end_call_timestamp(self):\n '''\n Validates that an end call record cannot have a timestamp\n before its own start call record pair\n '''\n if self.type == 'E':\n started_call = CallRecord.objects.get(\n call_id=self.call_id,\n type='S'\n )\n if self.timestamp <= started_call.timestamp:\n raise ValidationError(\n 'The end call record timestamp cannot be a period in'\n + ' time which comes before the start call period'\n )\n\n def validate_numbers(self):\n '''\n If it's a start call record, check for the correctness of its\n phone number fields\n '''\n if self.type == 'S':\n self.clean_fields()\n\n def validate_save(self):\n '''\n Runs the validation routines\n '''\n self.validate_numbers()\n self.validate_end_record_with_numbers()\n self.validate_source_and_destination()\n self.validate_source_and_timestamp()\n self.validate_destination_and_timestamp()\n self.validate_call_id()\n self.validate_end_call_timestamp()\n self.validate_overlap()\n\n # We override the models.Model.save() method to ensure\n # we don't create a record in which there are invalid or\n # inconsistent fields, using the custom validation methods\n def save(self, *args, **kwargs):\n self.validate_save()\n super(CallRecord, self).save(*args, **kwargs)\n\n\n# PhoneBill represents a single billing of a pair of call records\nclass PhoneBill(models.Model):\n # The destination number of the call. Follows the same validation\n # as the CallRecord phone numbers.\n destination = models.CharField(\n validators=[phone_validator_regex],\n max_length=11\n )\n\n # The starting timestamp of the call.\n start_timestamp = models.DateTimeField()\n\n # The duration of the call in seconds.\n # MinValueValidator is included due to SQLite not verifying\n # for negative numbers even with PositiveIntegerField\n call_duration = models.PositiveIntegerField(\n validators=[MinValueValidator(0)]\n )\n\n # The full value charge of the phone call.\n # Using DecimalFields to avoid float precision loss.\n charge = models.DecimalField(\n decimal_places=2,\n max_digits=15,\n validators=[MinValueValidator(Decimal('0.00'))]\n )\n\n # We override the models.Model.save() method to ensure\n # we don't create a record in which there are invalid or\n # inconsistent fields\n def save(self, *args, **kwargs):\n self.clean_fields()\n super(PhoneBill, self).save(*args, **kwargs)\n\n\n# CallTariff represents the tariffs referring to a call in a certain\n# period of time\nclass CallTariff(models.Model):\n\n # Base flat charge for all calls\n base_tariff = models.DecimalField(\n decimal_places=2,\n max_digits=15,\n validators=[MinValueValidator(Decimal('0.00'))]\n )\n\n # Tariff added per full minute in the normal time period\n minute_charge = models.DecimalField(\n decimal_places=2,\n max_digits=15,\n validators=[MinValueValidator(Decimal('0.00'))]\n )\n\n # Tariff added per full minute in the discounted time period\n discount_charge = models.DecimalField(\n decimal_places=2,\n max_digits=15,\n validators=[MinValueValidator(Decimal('0.00'))]\n )\n\n # This tariff applies to everything after this date and before\n # the next tariff's valid_after field\n valid_after = models.DateField()\n\n def validate_discount(self):\n '''\n Validates that a discount tariff can't be greater than the\n usual tariff (makes sense, right?)\n '''\n if self.discount_charge > self.minute_charge:\n raise ValidationError(\n 'Cannot create a tariff where the discount charge is greater'\n + ' than the minute charge'\n )\n\n # We override the models.Model.save() method to ensure\n # we don't create a record in which there are invalid or\n # inconsistent fields\n def save(self, *args, **kwargs):\n self.clean_fields()\n self.validate_discount()\n super(CallTariff, self).save(*args, **kwargs)\n","sub_path":"olistphone/rest/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"29101572","text":"class MyList:\n \"\"\"\n a proxy class for built-in list\n so that we can add the attribute `heap_size` to list\n \"\"\"\n def __init__(self, l):\n self.wrapped = l\n def __getattr__(self, name):\n return getattr(self.wrapped, name)\n def __setattr__(self, name, value):\n self.__dict__[name] = value\n\ndef max_heapify(A, i):\n \"\"\"\n :param A: the heap list.\n :param i: the ith index of heap tree node, and the (i-1)th index of A.\n remember that the heap tree starts with index 1, and the list A \n starts with index 0.\n\n the blow picture is the heap tree.\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\ /\n 8 9 10\n\n :param A.heap_size: the length of A \n \"\"\"\n l = (i << 1)\n r = (i << 1) + 1\n if l <= A.heap_size and A[l-1] > A[i-1]:\n largest = l\n else:\n largest = i\n if r <= A.heap_size and A[r-1] > A[largest-1]:\n largest = r\n if largest != i:\n A[i-1], A[largest-1] = A[largest-1], A[i-1]\n max_heapify(A, largest)\n\ndef build_max_heap(A):\n A.heap_size = len(A)\n for i in range(len(A)/2, 0, -1):\n max_heapify(A, i)\n\ndef heapsort(A):\n build_max_heap(A)\n for i in range(len(A), 1, -1):\n A[i-1], A[0] = A[0], A[i-1]\n A.heap_size -= 1\n max_heapify(A, 1)\n #print A\n return A\n\n\nif __name__ == '__main__':\n test = MyList([0, 1, 2, 3, 4, 4, 3, 6, -1])\n heapsort(test)\n\n","sub_path":"introduction-to-algorithms/chapter6/heapsort.py","file_name":"heapsort.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"309627426","text":"# -*- coding: utf-8 -*-\nimport sys\nfrom data import messages\nfrom data.game import Game\nfrom data.const import TextOptions\n\nwhile True:\n print(messages.WELCOME)\n choice = input(\">>> \").lower()\n\n if choice in (\"n\", \"new\", \"nowa\"):\n game = Game()\n elif choice in (\"w\", \"load\", \"wczytaj\"):\n import os\n import pickle\n save = None\n while save is None:\n for i, file in enumerate(os.listdir(\"./saves\")):\n print(\"{}{}) {}\".format(TextOptions.txtgrn, i, file+TextOptions.txtrst))\n print(TextOptions.txtred+\"\\nb) wróć\\n\"+TextOptions.txtrst)\n selected = input(TextOptions.txtcyn+messages.SELECT_SAVE+TextOptions.txtrst)\n print()\n if selected in (\"b\", \"back\", \"powrót\", \"wróć\"):\n break\n try:\n with open(\"./saves/{}\".format(os.listdir(\"./saves\")[int(selected)]), \"rb\") as f:\n game = pickle.load(f).loop()\n except pickle.UnpicklingError:\n print(messages.SAVE_CORRUPTED)\n except ValueError:\n continue\n elif choice in (\"x\", \"q\", \"exit\", \"quit\"):\n sys.exit(1)","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"607370186","text":"#!/bin/python3\n\n\nclass ListNode:\n \"\"\"Node for doubly linked list\"\"\"\n def __init__(self, data=None, next=None, prev=None):\n self.data = data\n self.next = next\n self.prev = prev\n\n def __repr__(self):\n \"\"\"Return the string representation of the data.\"\"\"\n return repr(self.data)\n\n\nclass LinkedList:\n \"\"\"Create new doubly linked list.\"\"\"\n def __init__(self):\n \"\"\"Function initialises head node.\n Takes O(1) time.\n \"\"\"\n self.head = None\n\n def __repr__(self):\n \"\"\"\n Return a string representation of the list.\n Takes O(n) time.\n \"\"\"\n nodes = []\n current = self.head\n while current:\n nodes.append(repr(current))\n current = current.next\n return '[' + ', '.join(nodes) + ']'\n\n def print_data(self):\n \"\"\"Function to print linked list data.\"\"\"\n current = self.head\n while current:\n print(current.data)\n current = current.next\n\n def prepend(self, data):\n \"\"\"Insert new node at the beginning.\n Time complexity O(1)\n \"\"\"\n new_head = ListNode(data=data, next=self.head)\n if self.head:\n self.head.prev = new_head\n self.head = new_head\n\n def append(self, data):\n \"\"\"Insert the new node at the end of the linked list.\n Time complexity O(n)\n \"\"\"\n if not self.head:\n self.head = ListNode(data=data)\n current = self.head\n while current.next:\n current = current.next\n current.next = ListNode(data=data, prev=current)\n\n def search(self, data):\n current = self.head\n while current and current.data != data:\n current = current.next\n return current # Return None if not found\n\n def remove_node(self, node):\n \"\"\"Unlink the node\n Time complexity O(n)\n \"\"\"\n if node.prev:\n node.prev.next = node.next\n if node.next:\n node.next.prev = node.prev\n if node is self.head:\n self.head = node.next\n node.next = None\n node.prev = None\n\n def remove(self, data):\n \"\"\"Remove the first occurance of data.\n Time complexity O(n)\n \"\"\"\n element = self.search(data)\n if not element:\n return\n self.remove_node(element)\n\n def reverse(self):\n \"\"\"\n Reverse the list in-place.\n Takes O(n) time.\n \"\"\"\n current = self.head\n prev_node = None\n while current:\n prev_node = current.prev\n current.prev = current.next\n current.next = prev_node\n current = current.prev\n self.head = prev_node.prev\n\n\nif __name__ == '__main__':\n linked_lst = LinkedList()\n linked_lst.prepend(10)\n linked_lst.prepend(11)\n linked_lst.append(20)\n linked_lst.append(21)\n linked_lst.print_data()\n element = linked_lst.search(10)\n linked_lst.remove_node(element)\n linked_lst.remove(10)\n linked_lst.reverse()\n","sub_path":"contents/data_structure/linked_list/doubly_linked_list.py","file_name":"doubly_linked_list.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"226854425","text":"\"\"\"\nTest the landing page.\n\"\"\"\nfrom google.cloud import ndb\n\nfrom django.urls import reverse\n\nfrom app.datastore import get_client\n\nfrom bouncer.tests.base import DatastoreTestCase\nfrom bouncer.models import Redirect\n\n\nURL_LANDING = reverse('bouncer:landing')\n\n\nclass LandingPageTests(DatastoreTestCase):\n \"\"\"Tests for the landing page.\"\"\"\n\n\n def test_list_redirect_links(self):\n \"\"\"Test link redirect links.\"\"\"\n with self.ds_client.context():\n r1 = Redirect(\n name='Example 1 name',\n key=ndb.Key(Redirect, 'example-one'),\n destination_url='https://example.com/r1',\n )\n r1.put()\n r2 = Redirect(\n name='Example 2 name',\n key=ndb.Key(Redirect, 'example-two'),\n destination_url='https://example.com/r2',\n )\n r2.put()\n\n res = self.client.get(URL_LANDING)\n\n self.assertEqual(res.status_code, 200)\n for r in [r1, r2]:\n url = reverse('bouncer:redirect', kwargs={'slug': r.key.id()})\n self.assertContains(res, url)\n self.assertContains(res, r.name)","sub_path":"app/bouncer/tests/test_landing.py","file_name":"test_landing.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"11257903","text":"li = list(map(int, input().split()))\nsum = int(input())\ncs, d = 0, {}\nfor i in range(len(li)):\n cs += li[i]\n if cs == sum:\n print(li[0:i+1])\n break\n if cs-sum in d:\n print(li[d[cs-sum]+1:i+1])\n break\n d[cs] = i\nelse:\n print(\"not found\")\n","sub_path":"python programs/subarray.py","file_name":"subarray.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"239383904","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom lstm.tools import Stack\n\nfrom lstm.tools import data_reader\nfrom lstm.tools.generate_test_data import is_nonterminal, is_terminal, stop_words\n\nflags = tf.flags\nlogging = tf.logging\n\nflags.DEFINE_string(\n \"model\", \"small\",\n \"A type of model. Possible options are: small, medium, large.\")\nflags.DEFINE_string(\"data_path\", '../data/',\n \"Where the training/test data is stored.\")\nflags.DEFINE_string(\"save_path\", '../data/test/',\n \"Model output directory.\")\nflags.DEFINE_bool(\"use_fp16\", False,\n \"Train using 16-bit floats instead of 32bit floats\")\nflags.DEFINE_bool(\"decode\", False,\n \"Set to True for interactive decoding.\")\nflags.DEFINE_bool(\"generate\", False, \"Set to True for interactive generating.\")\nflags.DEFINE_bool(\"test\", False, \"Set to True for interactive generating.\")\n\nFLAGS = flags.FLAGS\n\nword_to_id = data_reader.get_word_to_id(FLAGS.data_path)\nnameSet = [word_to_id['ClassDef'], word_to_id['FunctionDef'], word_to_id['Assign'], word_to_id['AsyncFunctionDef']]\n\n\ndef data_type():\n return tf.float16 if FLAGS.use_fp16 else tf.float32\n\n\nclass NoInitInput(object):\n \"\"\"The input data.\"\"\"\n\n def __init__(self, config, data, name=None, isDecode=False):\n if isDecode:\n self.num_steps = len(data) + 1\n X = [[0]]\n X[0] = data\n data = tf.convert_to_tensor(X, name=\"data\", dtype=tf.int32)\n self.input_data = data\n self.targets = data # 这个没有用\n self.batch_size = 1\n self.epoch_size = 1\n else:\n self.batch_size = batch_size = config.batch_size\n self.num_steps = num_steps = config.num_steps\n self.epoch_size = ((len(data) // batch_size) - 1) // num_steps\n self.input_data, self.targets = data_reader.data_producer(\n data, batch_size, num_steps, name=name)\n\n\nclass NoInitModel(object):\n \"\"\"The NoInit model.\"\"\"\n\n def __init__(self, is_training, config, input_, START_MARK, END_MARK, PAD_MARK):\n self._input = input_\n\n batch_size = input_.batch_size\n num_steps = input_.num_steps - 1\n size = config.hidden_size\n vocab_size = config.vocab_size\n\n # Slightly better results can be obtained with forget gate biases\n # initialized to 1 but the hyperparameters of the model would need to be\n # different than reported in the paper.\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(size, forget_bias=0.0, state_is_tuple=True)\n if is_training and config.keep_prob < 1:\n lstm_cell = tf.contrib.rnn.DropoutWrapper(\n lstm_cell, output_keep_prob=config.keep_prob)\n # cell=lstm_cell\n cell = tf.contrib.rnn.MultiRNNCell([lstm_cell] * config.num_layers, state_is_tuple=True)\n\n self._initial_state = cell.zero_state(batch_size, data_type())\n self.state_stack = Stack.Stack()\n\n with tf.device(\"/cpu:0\"):\n embedding = tf.get_variable(\n \"embedding\", [vocab_size, size], dtype=data_type())\n inputs = tf.nn.embedding_lookup(embedding, input_.input_data)\n\n if is_training and config.keep_prob < 1:\n inputs = tf.nn.dropout(inputs, config.keep_prob)\n self._input_data = input_.input_data\n\n test = []\n self._test = test\n # self._inputs=inputs\n # Simplified version of tensorflow.models.rnn.rnn.py's rnn().\n # This builds an unrolled LSTM for tutorial purposes only.\n # In general, use the rnn() or state_saving_rnn() from rnn.py.\n #\n # The alternative version of the code below is:\n #\n # inputs = tf.unstack(inputs, num=num_steps, axis=1)\n # outputs, state = tf.nn.rnn(cell, inputs, initial_state=self._initial_state)\n outputs = []\n state = self._initial_state # [1,hidden_size]\n\n # def func_push(state,batch):\n # self.state_stack.push(state)\n # return state[0][0][batch], state[0][1][batch], state[1][0][batch], state[1][1][batch]\n #\n # def func_pop(batch):\n # state = self.state_stack.pop()\n # return state[0][0][batch], state[0][1][batch], state[1][0][batch], state[1][1][batch]\n #\n # def func_default(state,batch):\n # return state[0][0][batch], state[0][1][batch], state[1][0][batch], state[1][1][batch]\n\n def updateState(state, time_step):\n state = ((state[0][0], state[0][1]), (state[1][0], state[1][1]))\n\n (out, newstate) = cell(inputs[:, time_step, :], state)\n\n # print('------------------------------hhhhhh----------------------------')\n tf.get_variable_scope().reuse_variables()\n return newstate\n\n def f_default(state):\n return state\n\n def func_proceed_name(state, time_step):\n (cell_output, newstate) = cell(inputs[:, time_step, :], state)\n tf.get_variable_scope().reuse_variables()\n (cell_output, newstate) = cell(inputs[:, time_step, :], newstate)\n tf.get_variable_scope().reuse_variables()\n\n return newstate\n\n def func_not_proceed_name(state):\n return state\n\n def func_push(state):\n \"\"\"\n 传入一个LSTMTuple\n 1. push\n 2. 返回4个state\n :param state:\n :param time_step:\n :return:\n \"\"\"\n\n self.state_stack.push(state)\n return state[0][0], state[0][1], state[1][0], state[1][1]\n\n def func_pop(time_step,state):\n (cell_output,state)=cell(inputs[:,time_step,:],state)\n state=self.state_stack.pop()\n (cell_output,state)=cell(cell_output,state)\n return state[0][0],state[0][1],state[1][0],state[1][1]\n\n def func_default(state):\n return state[0][0], state[0][1], state[1][0], state[1][1]\n\n with tf.variable_scope(\"RNN\"):\n for time_step in range(num_steps):\n if time_step > 0: tf.get_variable_scope().reuse_variables()\n # if time_step=num_steps/2:\n # new_state=func_pop()\n # else:\n # new_state=func_default(state)\n\n maybeUpdateState = tf.cond(tf.logical_or(\n tf.logical_or(tf.equal(self._input_data[0][time_step-1], nameSet[0]), tf.equal(self._input_data[0][time_step-1], nameSet[1])),\n tf.logical_or(tf.equal(self._input_data[0][time_step-1], nameSet[2]), tf.equal(self._input_data[0][time_step-1], nameSet[3])),\n ),lambda: func_proceed_name(state, time_step),lambda: func_not_proceed_name(state))\n\n new_state = tf.cond(tf.equal(self._input_data[0][time_step], START_MARK),\n lambda: func_push(maybeUpdateState), lambda: func_default(maybeUpdateState))\n #state经过push更新之后需要回到初始时的状态,然后进行后续的cell计算\n new_state=state[0][0], state[0][1], state[1][0], state[1][1]\n # # fixme : func_default(state) 是不是应该是func_default(new_state)?\n new_state = tf.cond(tf.equal(self._input_data[0][time_step], END_MARK), lambda: func_pop(),\n lambda: func_default(state))\n\n state = ((new_state[0], new_state[1]), (new_state[2], new_state[3]))\n\n (cell_output, state) = cell(inputs[:, time_step, :], state)\n outputs.append(cell_output)\n\n output = tf.reshape(tf.concat(outputs, 1), [-1, size])\n softmax_w = tf.get_variable(\n \"softmax_w\", [size, vocab_size], dtype=data_type())\n softmax_b = tf.get_variable(\"softmax_b\", [vocab_size], dtype=data_type())\n logits = tf.matmul(output, softmax_w) + softmax_b\n loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example(\n [logits],\n [tf.reshape(input_.targets, [-1])],\n [tf.ones([batch_size * num_steps], dtype=data_type())])\n self._cost = cost = tf.reduce_sum(loss) / batch_size\n self._final_state = state\n self._targets = input_.targets\n self._logits = logits\n\n if not is_training:\n return\n\n self._lr = tf.Variable(0.0, trainable=False)\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars),\n config.max_grad_norm)\n optimizer = tf.train.GradientDescentOptimizer(self._lr)\n self._train_op = optimizer.apply_gradients(\n zip(grads, tvars),\n global_step=tf.contrib.framework.get_or_create_global_step())\n\n self._new_lr = tf.placeholder(\n tf.float32, shape=[], name=\"new_learning_rate\")\n self._lr_update = tf.assign(self._lr, self._new_lr)\n\n def assign_lr(self, session, lr_value):\n session.run(self._lr_update, feed_dict={self._new_lr: lr_value})\n\n def step(self, session):\n output = session.run(self._logits)\n return output\n\n @property\n def input(self):\n return self._input\n\n @property\n def initial_state(self):\n return self._initial_state\n\n @property\n def cost(self):\n return self._cost\n\n @property\n def final_state(self):\n return self._final_state\n\n @property\n def lr(self):\n return self._lr\n\n @property\n def train_op(self):\n return self._train_op\n\n\nclass SmallConfig(object):\n \"\"\"Small config.\"\"\"\n init_scale = 0.1\n learning_rate = 0.1\n max_grad_norm = 5\n num_layers = 2\n max_data_row = None\n num_steps = 60\n hidden_size = 200\n max_epoch = 4\n max_max_epoch = 13\n keep_prob = 1.0\n lr_decay = 0.5\n batch_size = 1\n vocab_size = 5000\n\n\nclass MediumConfig(object):\n \"\"\"Medium config.\"\"\"\n init_scale = 0.05\n learning_rate = 1\n max_grad_norm = 5\n num_layers = 2\n num_steps = 35\n hidden_size = 1024\n max_epoch = 6\n max_max_epoch = 39\n keep_prob = 0.5\n lr_decay = 0.8\n batch_size = 200\n vocab_size = 10000\n\n\nclass LargeConfig(object):\n \"\"\"Large config.\"\"\"\n init_scale = 0.04\n learning_rate = 1.0\n max_grad_norm = 10\n num_layers = 2\n num_steps = 35\n hidden_size = 1024\n max_epoch = 14\n max_max_epoch = 55\n keep_prob = 0.35\n lr_decay = 1 / 1.15\n batch_size = 200\n vocab_size = 10000\n\n\nclass TestConfig(object):\n \"\"\"Tiny config, for testing.\"\"\"\n init_scale = 0.1\n learning_rate = 1.0\n max_grad_norm = 1\n num_layers = 1\n num_steps = 2\n hidden_size = 2\n max_epoch = 1\n max_max_epoch = 1\n keep_prob = 1.0\n lr_decay = 0.5\n batch_size = 20\n vocab_size = 10000\n\n\ndef run_epoch(session, model, eval_op=None, verbose=False, id_to_word=None, end_id=None, isDecode=False):\n \"\"\"Runs the model on the given data.\"\"\"\n if isDecode:\n output = model.step(session)\n return output\n start_time = time.time()\n costs = 0.0\n iters = 0\n state = session.run(model.initial_state)\n\n SUM = 0\n correct_tok = 0\n\n fetches = {\n \"cost\": model.cost,\n \"final_state\": model.final_state,\n \"input_data\": model._input_data,\n \"targets\": model._targets,\n \"pred_output\": model._logits\n }\n if eval_op is not None:\n fetches[\"eval_op\"] = eval_op\n\n for step in range(model.input.epoch_size):\n feed_dict = {}\n for i, (c, h) in enumerate(model.initial_state):\n feed_dict[c] = state[i].c\n feed_dict[h] = state[i].h\n\n vals = session.run(fetches, feed_dict)\n cost = vals[\"cost\"]\n state = vals[\"final_state\"]\n\n costs += cost\n iters += model.input.num_steps\n\n # todo add 计算accuracy\n midInputData = vals[\"input_data\"]\n midTargets = vals[\"targets\"]\n pred_output = vals[\"pred_output\"]\n try:\n for i in range(model.input.batch_size):\n for j in range(model.input.num_steps - 1):\n SUM += 1\n trueOutput = id_to_word[midTargets[i][j]]\n tmp = list(pred_output[i * (model.input.num_steps - 1) + j])\n # todo topN这里注释\n predOutput = id_to_word[tmp.index(max(tmp))]\n if midInputData[i][j] == end_id:\n SUM -= 1\n break\n if trueOutput == predOutput:\n correct_tok += 1\n # todo topN使用这里\n # predOutput=[]\n # for m in range(N):\n # index=tmp.index(max(tmp))\n # predOutput.append(id_to_word[index])\n # tmp[index]=-100\n # if trueOutput in predOutput:\n # correct_tok+=1\n except:\n print(\"--------ERROR 计算acc----\")\n pass\n\n if verbose and step % (model.input.epoch_size // 10) == 10:\n print(\"%.3f perplexity: %.3f speed: %.0f wps\" %\n (step * 1.0 / model.input.epoch_size, np.exp(costs / iters),\n iters * model.input.batch_size / (time.time() - start_time)))\n\n if True:\n midInputData = vals[\"input_data\"]\n midTargets = vals[\"targets\"]\n pred_output = vals[\"pred_output\"]\n global num_steps\n try:\n for i in range(1):\n inputStr = ''\n trueOutput = ''\n predOutput = ''\n for j in range(num_steps):\n inputStr += id_to_word[midInputData[i][j]] + ' '\n\n trueOutput += id_to_word[midTargets[i][j]] + ' '\n\n tmp = list(pred_output[i * num_steps + j])\n predOutput += id_to_word[tmp.index(max(tmp))] + ' '\n print('Input: %s \\n True Output: %s \\n Pred Output: %s \\n' % (inputStr, trueOutput, predOutput))\n except:\n pass\n\n acc = correct_tok * 1.0 / SUM\n print(\"Accuracy : %.3f\" % acc)\n return np.exp(costs / iters)\n\n\ndef get_config():\n if FLAGS.model == \"small\":\n return SmallConfig()\n elif FLAGS.model == \"medium\":\n return MediumConfig()\n elif FLAGS.model == \"large\":\n return LargeConfig()\n elif FLAGS.model == \"test\":\n return TestConfig()\n else:\n raise ValueError(\"Invalid model: %s\", FLAGS.model)\n\n\nnum_steps = 0\n\n\ndef train():\n if not FLAGS.data_path:\n raise ValueError(\"Must set --data_path to PTB data directory\")\n config = get_config()\n\n word_to_id = data_reader.get_word_to_id(FLAGS.data_path)\n # todo raw_data还应包含weights\n raw_data = data_reader.raw_data(max_data_row=config.max_data_row, data_path=FLAGS.data_path, word_to_id=word_to_id,\n max_length=config.num_steps)\n train_data, test_data, voc_size, end_id, _, START_MARK, END_MARK, PAD_MARK = raw_data\n id_to_word = data_reader.reverseDic(word_to_id)\n\n config = get_config()\n global num_steps\n num_steps = config.num_steps - 1\n\n eval_config = get_config()\n # eval_config.batch_size = 1\n # eval_config.num_steps = 1\n\n # 使用动态vocab_size\n # config.vocab_size=voc_size\n # eval_config.voc_size=voc_size\n\n\n with tf.Graph().as_default():\n initializer = tf.random_uniform_initializer(-config.init_scale,\n config.init_scale)\n\n with tf.name_scope(\"Train\"):\n train_input = NoInitInput(config=config, data=train_data, name=\"TrainInput\")\n with tf.variable_scope(\"Model\", reuse=None, initializer=initializer):\n m = NoInitModel(is_training=True, config=config, input_=train_input,\n START_MARK=START_MARK, END_MARK=END_MARK, PAD_MARK=PAD_MARK)\n tf.summary.scalar(\"Training Loss\", m.cost)\n tf.summary.scalar(\"Learning Rate\", m.lr)\n\n # with tf.name_scope(\"Valid\"):\n # valid_input = NoInitInput(config=config, data=valid_data, name=\"ValidInput\")\n # with tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n # mvalid = NoInitModel(is_training=False, config=config, input_=valid_input)\n # tf.scalar_summary(\"Validation Loss\", mvalid.cost)\n\n with tf.name_scope(\"Test\"):\n test_input = NoInitInput(config=eval_config, data=test_data, name=\"TestInput\")\n with tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n mtest = NoInitModel(is_training=False, config=eval_config, input_=test_input,\n START_MARK=START_MARK, END_MARK=END_MARK, PAD_MARK=PAD_MARK)\n\n sv = tf.train.Supervisor(logdir=FLAGS.save_path)\n with sv.managed_session() as session:\n for i in range(config.max_max_epoch):\n lr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.0)\n m.assign_lr(session, config.learning_rate * lr_decay)\n\n print(\"Epoch: %d Learning rate: %.3f\" % (i + 1, session.run(m.lr)))\n train_perplexity = run_epoch(session, m, eval_op=m.train_op, verbose=True, id_to_word=id_to_word,\n end_id=end_id)\n print(\"Epoch: %d Train Perplexity: %.3f\" % (i + 1, train_perplexity))\n # valid_perplexity = run_epoch(session, mvalid, id_to_word=id_to_word)\n # print(\"Epoch: %d Valid Perplexity: %.3f\" % (i + 1, valid_perplexity))\n\n test_perplexity = run_epoch(session, mtest, id_to_word=id_to_word, end_id=end_id)\n print(\"Test Perplexity: %.3f\" % test_perplexity)\n\n if FLAGS.save_path:\n print(\"Saving model to %s.\" % FLAGS.save_path)\n sv.saver.save(session, FLAGS.save_path, global_step=sv.global_step)\n\n\ndef decode():\n choice = ['1', '2', '3', '4', '5', 'q']\n if not FLAGS.data_path:\n raise ValueError(\"Must set --data_path to PTB data directory\")\n config = get_config()\n\n word_to_id = data_reader.get_word_to_id(FLAGS.data_path)\n # todo raw_data还应包含weights\n raw_data = data_reader.raw_data(max_data_row=config.max_data_row, data_path=FLAGS.data_path, word_to_id=word_to_id,\n max_length=config.num_steps)\n train_data, test_data, voc_size, end_id, _, START_MARK, END_MARK, PAD_MARK = raw_data\n id_to_word = data_reader.reverseDic(word_to_id)\n\n config = get_config()\n global num_steps\n num_steps = config.num_steps - 1\n\n sys.stdout.write(\"> \")\n sys.stdout.flush()\n token = sys.stdin.readline().strip('\\n').split(' ')\n for i in range(len(token)):\n if token[i] not in word_to_id:\n token[i] = word_to_id['UNK']\n else:\n token[i] = word_to_id[token[i]]\n\n while True:\n with tf.Graph().as_default():\n initializer = tf.random_uniform_initializer(-config.init_scale,\n config.init_scale)\n\n with tf.name_scope(\"Train\"):\n decode_input = NoInitInput(config=config, data=token, name=\"TrainInput\", isDecode=True)\n with tf.variable_scope(\"Model\", reuse=None, initializer=initializer):\n decode_model = NoInitModel(is_training=False, config=config, input_=decode_input,\n START_MARK=START_MARK, END_MARK=END_MARK, PAD_MARK=PAD_MARK)\n\n # ckpt = tf.train.get_checkpoint_state(FLAGS.save_path)\n # if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):\n # print(\"Reading model parameters from %s\" % ckpt.model_checkpoint_path)\n # # model.saver.restore(session, ckpt.model_checkpoint_path)\n # else:\n # print(\"Created model with fresh parameters.\")\n Config = tf.ConfigProto()\n Config.gpu_options.allow_growth = True\n sv = tf.train.Supervisor(logdir=FLAGS.save_path)\n with sv.managed_session(config=Config) as session:\n output = run_epoch(session, decode_model, id_to_word, end_id=end_id, isDecode=True)\n # output = decode_model.step(session)\n # print(output)\n tmp = list(output[-1])\n\n # output=id_to_word[tmp.index(max(tmp))]\n # print('next token --> %s'%output)\n # ------------\n\n # todo 输出top5\n predOutput = []\n count = 0\n while count < 5:\n index = tmp.index(max(tmp))\n if index == PAD_MARK:\n tmp[index] = -100\n continue\n predOutput.append(id_to_word[index])\n count += 1\n tmp[index] = -100\n\n print('next token --> ')\n for i in range(len(predOutput)):\n print('%d: %s' % (i + 1, predOutput[i]))\n print('You Choose: ')\n x = sys.stdin.readline().strip('\\n')\n if x != 'q' and x in choice:\n token.append(word_to_id[predOutput[int(x) - 1]])\n elif x not in choice:\n if x not in word_to_id:\n token.append(word_to_id['UNK'])\n else:\n token.append(word_to_id[x])\n else:\n break\n\n\ndef test(type, filename):\n # wfname='data/'+type+'.txt'\n # wf=open(wfname,'w')\n if not FLAGS.data_path:\n raise ValueError(\"Must set --data_path to PTB data directory\")\n config = get_config()\n\n word_to_id = data_reader.get_word_to_id(FLAGS.data_path)\n # todo raw_data还应包含weights\n raw_data = data_reader.raw_data(FLAGS.data_path, word_to_id, config.num_steps)\n train_data, test_data, voc_size, end_id, _, START_MARK, END_MARK, PAD_MARK = raw_data\n id_to_word = data_reader.reverseDic(word_to_id)\n\n config = get_config()\n global num_steps\n num_steps = config.num_steps - 1\n SUM = 0\n correct_tok = 0\n\n f = open(filename)\n data = f.readlines()\n for i in range(len(data)):\n try:\n SUM += 1\n code = data[i].strip('\\n').split(' ')\n # print(data)\n testInput = code[0:len(code) - 1]\n testTarget = code[-1]\n if testTarget not in word_to_id:\n testTarget = 'UNK'\n for j in range(len(testInput)):\n if testInput[j] not in word_to_id:\n testInput[j] = word_to_id['UNK']\n else:\n testInput[j] = word_to_id[testInput[j]]\n\n with tf.Graph().as_default():\n initializer = tf.random_uniform_initializer(-config.init_scale,\n config.init_scale)\n with tf.name_scope(\"Train\"):\n decode_input = NoInitInput(config=config, data=testInput, name=\"TrainInput\", isDecode=True)\n with tf.variable_scope(\"Model\", reuse=None, initializer=initializer):\n decode_model = NoInitModel(is_training=True, config=config, input_=decode_input,\n START_MARK=START_MARK, END_MARK=END_MARK, PAD_MARK=PAD_MARK)\n\n # ckpt = tf.train.get_checkpoint_state(FLAGS.save_path)\n # if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):\n # print(\"Reading model parameters from %s\" % ckpt.model_checkpoint_path)\n # # model.saver.restore(session, ckpt.model_checkpoint_path)\n # else:\n # print(\"Created model with fresh parameters.\")\n\n sv = tf.train.Supervisor(logdir=FLAGS.save_path)\n with sv.managed_session() as session:\n output = run_epoch(session, decode_model, id_to_word, end_id=end_id, isDecode=True)\n tmp = list(output[-1])\n\n # top10\n predOutput = []\n count = 0\n while count < 10:\n index = tmp.index(max(tmp))\n # todo fix me\n if index == PAD_MARK or id_to_word[index] in stop_words:\n tmp[index] = -100\n continue\n predOutput.append(id_to_word[index])\n count += 1\n tmp[index] = -100\n # sv.saver.save(session, FLAGS.save_path, global_step=sv.global_step)\n\n if type == 'T':\n for i in range(len(predOutput)):\n if is_terminal(predOutput[i]):\n print(\"%s,%s\" % (predOutput[i], testTarget))\n if (predOutput[i] == testTarget):\n correct_tok += 1\n break\n else:\n for i in range(len(predOutput)):\n if is_nonterminal(predOutput[i]):\n print(\"%s,%s\" % (predOutput[i], testTarget))\n if (predOutput[i] == testTarget):\n correct_tok += 1\n break\n print(' %d %d' % (correct_tok, SUM))\n acc = correct_tok * 1.0 / SUM\n print(\"Accuracy : %.3f\" % acc)\n except:\n pass\n acc = correct_tok * 1.0 / SUM\n print(\"Final Accuracy : %.3f\" % acc)\n\n\ndef main(_):\n if FLAGS.decode:\n decode()\n if FLAGS.test:\n test('NT', r'../data/train_nonterminal-60-60.txt')\n else:\n train()\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"model/SLSTM_add_input_info.py","file_name":"SLSTM_add_input_info.py","file_ext":"py","file_size_in_byte":23640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"623288904","text":"from datetime import datetime\n\nfrom pytz import timezone\nfrom dateutil.rrule import rrule, DAILY, HOURLY, MONTHLY, YEARLY\nfrom dateutil.parser import parse as capture\n\nfrom .exceptions import DeloreanInvalidDatetime\nfrom .dates import Delorean, is_datetime_naive, datetime_timezone\n\nUTC = \"UTC\"\nutc = timezone(\"utc\")\n\nNAIVEMODE_UTC = \"utc\"\nNAIVEMODE_NAIVE = \"naive\"\nNAIVEMODE_RAISE = \"raise\"\nNAIVE_MODES = (NAIVEMODE_UTC, NAIVEMODE_NAIVE, NAIVEMODE_RAISE)\n\ndef parse(s, dayfirst=True, yearfirst=True, naivemode=NAIVEMODE_UTC):\n \"\"\"\n Parses a datetime string in it and returns a `Delorean` object.\n\n If a timezone is detected in the datetime string it will be\n normalized to UTC, and a Delorean object with that datetime and\n timezone will be returned.\n\n If a timezone is not detected, the resulting timezone (and return object)\n depends on the value of the naivemode argument:\n '{mode_utc}' -- UTC is assumed\n '{mode_raise}' -- An exception is raised\n '{mode_naive}' -- Returns a naive datetime object (NOT a `Delorean`).\n\n Note that in the case of naivemode=='{mode_naive}' a Delorean object is\n not returned. This is because Delorean objects should always be timezone\n aware.\n\n \"\"\"\n\n if not naivemode in NAIVE_MODES:\n raise ValueError(\"Unknown naivemode value: '%s'\" % naivemode)\n\n try:\n dt = capture(s, dayfirst=dayfirst, yearfirst=yearfirst)\n except:\n # raise a parsing error.\n raise ValueError(\"Unknown string format\")\n if dt.tzinfo is None:\n if naivemode == NAIVEMODE_UTC:\n # assuming datetime object passed in is UTC\n do = Delorean(datetime=dt, timezone=UTC)\n elif naivemode == NAIVEMODE_RAISE:\n raise DeloreanInvalidDatetime(\"Unable to determine timezone info\")\n elif naivemode == NAIVEMODE_NAIVE:\n do = dt #note that we are *not* returning a Delorean here\n else:\n dt = utc.normalize(dt)\n # makeing dt naive so we can pass it to Delorean\n dt = dt.replace(tzinfo=None)\n # if parse string has tzinfo we return a normalized UTC\n # delorean object that represents the time.\n do = Delorean(datetime=dt, timezone=UTC)\n return do\ntry:\n parse.__doc__ = parse.__doc__.format(mode_utc=NAIVEMODE_UTC,\n mode_raise=NAIVEMODE_RAISE,\n mode_naive=NAIVEMODE_NAIVE)\nexcept AttributeError:\n #must be running with -OO\n pass\n\ndef range_daily(start=None, stop=None, timezone=UTC, count=None):\n \"\"\"\n This an alternative way to generating sets of Delorean objects with\n DAILY stops\n \"\"\"\n return stops(start=start, stop=stop, freq=DAILY, timezone=timezone, count=count)\n\n\ndef range_hourly(start=None, stop=None, timezone=UTC, count=None):\n \"\"\"\n This an alternative way to generating sets of Delorean objects with\n HOURLY stops\n \"\"\"\n return stops(start=start, stop=stop, freq=HOURLY, timezone=timezone, count=count)\n\n\ndef range_monthly(start=None, stop=None, timezone=UTC, count=None):\n \"\"\"\n This an alternative way to generating sets of Delorean objects with\n MONTHLY stops\n \"\"\"\n return stops(start=start, stop=stop, freq=MONTHLY, timezone=timezone, count=count)\n\n\ndef range_yearly(start=None, stop=None, timezone=UTC, count=None):\n \"\"\"\n This an alternative way to generating sets of Delorean objects with\n YEARLY stops\n \"\"\"\n return stops(start=start, stop=stop, freq=YEARLY, timezone=timezone, count=count)\n\n\ndef stops(freq, interval=1, count=None, wkst=None, bysetpos=None,\n bymonth=None, bymonthday=None, byyearday=None, byeaster=None,\n byweekno=None, byweekday=None, byhour=None, byminute=None,\n bysecond=None, timezone=UTC, start=None, stop=None):\n \"\"\"\n This will create a list of delorean objects the apply to\n setting possed in.\n \"\"\"\n # check to see if datetimees passed in are naive if so process them\n # with given timezone.\n if is_datetime_naive(start) and is_datetime_naive(stop):\n pass\n else:\n raise DeloreanInvalidDatetime('Provide a naive datetime object')\n\n # if no datetimes are passed in create a proper datetime object for\n # start default because default in dateutil is datetime.now() :(\n if start is None:\n start = datetime_timezone(timezone)\n\n for dt in rrule(freq, interval=interval, count=count, wkst=wkst, bysetpos=bysetpos,\n bymonth=bymonth, bymonthday=bymonthday, byyearday=byyearday, byeaster=byeaster,\n byweekno=byweekno, byweekday=byweekday, byhour=byhour, byminute=byminute,\n bysecond=bysecond, until=stop, dtstart=start):\n # make the delorean object\n # yield it.\n # doing this to make sure delorean receives a naive datetime.\n dt = dt.replace(tzinfo=None)\n d = Delorean(datetime=dt, timezone=timezone)\n yield d\n\n\ndef epoch(s):\n dt = datetime.utcfromtimestamp(s)\n return Delorean(datetime=dt, timezone=UTC)\n\n\ndef flux():\n print(\"If you put your mind to it, you can accomplish anything.\")\n\n\ndef utcnow():\n \"\"\"\n Return a delorean object, with utcnow as the datetime\n \"\"\"\n return Delorean()\n\n\ndef now():\n \"\"\"\n Return a delorean object, with utcnow as the datetime\n \"\"\"\n return utcnow()\n","sub_path":"delorean/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":5338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138702043","text":"\"\"\"\nAuthor: angles\n28/01/17 - 16:27\n\"\"\"\n\nfrom glob import glob\nimport os\nfrom utils import get_batch\nfrom random import shuffle\nimport tensorflow as tf\n\nsamples_per_side = 8 # For the grid of samples\nbatch_size = samples_per_side ** 2\n\nflags = tf.app.flags\nflags.DEFINE_string(\"dataset\", \"8random\", \"The name of the dataset\")\nflags.DEFINE_float(\"learning_rate\", 0.0002, \"Adam's learning rate\")\nflags.DEFINE_float(\"beta1\", 0.5, \"Adam's momentum term\")\nflags.DEFINE_integer(\"z_dim\", 100, \"dimension of the representation\")\nflags.DEFINE_integer(\"epochs\", 50000, \"Number of training epochs\")\nflags.DEFINE_integer(\"batch_size\", batch_size, \"Training batch size\")\nflags.DEFINE_integer(\"image_size\", 178, \"Original images' size (without cropping)\")\nflags.DEFINE_boolean(\"is_crop\", True, \"Crop the original images?\")\nflags.DEFINE_integer(\"output_size\", 64, \"Generated images' size, also cropping size\")\nflags.DEFINE_boolean(\"is_grayscale\", False, \"Use grascale images?\")\nflags.DEFINE_integer(\"nb_channels_output\", 3, \"3:RGB, 1:Gray-scale\")\nFLAGS = flags.FLAGS\n\ndata = glob(os.path.join('./datasets', FLAGS.dataset, '*.JPEG'))\nnb_imgs = len(data)\nimgs_to_memorize = get_batch(data, FLAGS)\nshuffle(data)\n","sub_path":"analyze_distances.py","file_name":"analyze_distances.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"73805099","text":"from numpy.random import uniform, random, exponential\nfrom numpy import sort, append \nfrom definitions import Transmitter\n\nclass ThresholdFunction:\n def __init__ (self, x_range, y_range):\n self.threshold = uniform (low=0, high=random())\n self.alpha = random ()\n self.x_range = x_range\n self.y_range = y_range \n def func (self, x):\n if (x < self.threshold):\n return 0\n else:\n return (self.alpha * self.threshold ** 2) / x\n def setThreshold (self, threshold):\n self.threshold = threshold\n def neighbourhood_threshold (self, epsilon, size):\n ''' \n epsilon defines the size of the neighbourhood \n we return a list containing points in this neighbourhood \n ''' \n neighbourhood = uniform (low=self.threshold-epsilon, high=self.threshold+epsilon, size=size)\n append (neighbourhood, self.threshold)\n return sort (neighbourhood)\n \ndef MonteCarloIntegral (function, x_range, y_range, num_points=10_000):\n # creating the random points \n\n x_points = uniform (low=x_range [0], high=x_range[1], size=(num_points,))\n y_points = uniform (low=y_range [0], high=y_range[1], size=(num_points,))\n\n count = 0\n for x, y in zip (x_points, y_points):\n point = function (x)\n if (point < y and point > 0 and y > 0):\n count += 1\n elif point < 0 and y < 0 and point > y:\n count -= 1\n return count * (x_range[1]-x_range[0]) * (y_range[1]-y_range[0]) / num_points\n\ndef weightedMCI (list, x_range, y_range, num_points=10_000):\n function = lambda x: x*exponential (scale=5)\n return (MonteCarloIntegral(\n function, x_range, y_range, num_points\n ))\n\n ","sub_path":"Channel-Efficiencies/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"595712250","text":"from fobi.base import form_element_plugin_widget_registry\nfrom fobi.contrib.plugins.form_elements.fields.date.widgets import (\n BaseDatePluginWidget\n)\nfrom fobi.contrib.themes.bootstrap3 import UID\n\n__title__ = 'fobi.contrib.themes.bootstrap3.widgets.form_elements.' \\\n 'date_bootstrap3_widget.fobi_form_elements'\n__author__ = 'Artur Barseghyan '\n__copyright__ = '2014-2017 Artur Barseghyan'\n__license__ = 'GPL 2.0/LGPL 2.1'\n__all__ = ('DatePluginWidget',)\n\n\nclass DatePluginWidget(BaseDatePluginWidget):\n \"\"\"Date plugin widget for Bootstrap 3.\"\"\"\n\n theme_uid = UID\n media_js = [\n 'js/moment-with-locales.js',\n 'bootstrap3/js/bootstrap-datetimepicker.min.js',\n 'bootstrap3/js/fobi.plugin.date-bootstrap3-widget.js',\n ]\n media_css = [\n 'bootstrap3/css/bootstrap-datetimepicker.min.css',\n # 'datetime/css/fobi.plugin.date-bootstrap3-widget.css',\n ]\n\n\n# Registering the widget\nform_element_plugin_widget_registry.register(DatePluginWidget)\n","sub_path":"events/contrib/themes/bootstrap3/widgets/form_elements/date_bootstrap3_widget/fobi_form_elements.py","file_name":"fobi_form_elements.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"588700025","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2015 ICTSTUDIO ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\nimport logging\n\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import ValidationError\n\n_logger = logging.getLogger(__name__)\n\nclass SaleDiscount(models.Model):\n _name = \"sale.discount\"\n\n company_id = fields.Many2one(\n comodel_name='res.company',\n string='Company',\n required=True,\n default=lambda self: self.env.user.company_id\n )\n name = fields.Char(\n string=\"Discount\",\n required=True\n )\n start_date = fields.Date(string='Start date')\n end_date = fields.Date(string='End date')\n active = fields.Boolean(\n string='Discount active',\n default=lambda self: self._get_default_active()\n ) # TODO: Change default with lambda function\n product_id = fields.Many2one(\n comodel_name='product.product',\n string=\"Discount Product\",\n help=\"This product will be used to create lines on order regarding discount\"\n )\n discount_base = fields.Selection(\n selection=[\n ('sale_order', 'Base discount on Order amount'),\n ('sale_line', 'Base discount on Line amount')\n ],\n string=\"Discount Base on\",\n required=True,\n help=\"Base the discount on \"\n )\n\n pricelists = fields.Many2many(\n comodel_name='product.pricelist',\n relation='pricelist_sale_discount_rel',\n column1='discount_id',\n column2='pricelist_id',\n string=\"Pricelists\"\n )\n\n rules = fields.One2many(\n comodel_name='sale.discount.rule',\n inverse_name='sale_discount_id',\n string=\"Discount Rules\"\n )\n\n # sale_discounts = fields.Many2many(\n # comodel_name='sale.order.line',\n # relation='sale_line_sale_discount_rel',\n # column1='discount_id',\n # column2='sale_line_id',\n # string=\"Order Lines\"\n # )\n\n def _get_default_active(self):\n return True\n\n def check_active_date(self, check_date=None):\n if not check_date:\n check_date = fields.Datetime.now()\n if self.start_date and self.end_date and (check_date >= self.start_date and check_date < self.end_date):\n return True\n if self.start_date and not self.end_date and (check_date >= self.start_date):\n return True\n if not self.start_date and self.end_date and (check_date < self.end_date):\n return True\n elif not self.start_date or not self.end_date:\n return True\n else:\n return False\n\n @api.multi\n def _calculate_discount(self, base, qty):\n assert len(self) == 1\n for discount in self:\n for rule in discount.rules:\n if rule.max_base > 0 and rule.max_base > base:\n _logger.debug(\"No Discount\")\n continue\n\n if rule.discount_type == 'perc':\n _logger.debug(\"Calculate Discount Perc\")\n return base * rule.discount / 100\n else:\n _logger.debug(\"Calculate Discount Amount\")\n return min(rule.discount * qty, base)\n","sub_path":"sale_discount_advanced/models/sale_discount.py","file_name":"sale_discount.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"498226141","text":"import sys\nimport os\nimport progressbar\nimport logging\nimport numpy as np\nimport pandas as pd\nimport qutip\n\nif '../../' not in sys.path:\n sys.path.append('../../')\nimport src.optimization as optimization\nimport src.rabi_model as rabi_model\nimport src.protocol_ansatz as protocols\nfrom src.utils import ground_state\n\nN = 100\nOmega = N\ntf_list = np.linspace(0, 2, 400)\ntime_ratios_list = np.linspace(0, 0.5, 400)\nheights_list = np.asarray([40, 60, 80, 100])\n\nrabi = rabi_model.RabiModel(N=N, Omega=Omega)\ninitial_state = ground_state(rabi.H0)\ntarget_state = ground_state(rabi.hamiltonian(lambda_=np.sqrt(Omega) / 2.))\n\n\n# ------ set up logger\noutput_file_name = 'scan_' + os.path.basename(__file__)[7:-3]\nlogFormatter = logging.Formatter(\"%(asctime)s [%(threadName)-12.12s]\"\n \"[%(levelname)-5.5s] %(message)s\")\nrootLogger = logging.getLogger()\nrootLogger.setLevel(logging.INFO)\nfileHandler = logging.FileHandler(output_file_name + '.log')\nfileHandler.setFormatter(logFormatter)\nfileHandler.setLevel(logging.INFO)\nrootLogger.addHandler(fileHandler)\nlogging.info('Output file name will be \"{}\"'.format(output_file_name))\n\n# ------ GOGOGOGO\nlogging.info('Starting super iteration loop')\nfor height_idx, height in enumerate(heights_list):\n logging.info('Working on height {}/{}'.format(height_idx,\n len(heights_list)))\n results = np.zeros(shape=(len(tf_list) * len(time_ratios_list), 3))\n idx = 0\n for out_idx, tf in enumerate(tf_list):\n logging.info('Starting iteration {}/{}'.format(out_idx + 1, len(list(tf_list))))\n for ratio in time_ratios_list:\n protocol = protocols.DoubleBangProtocolAnsatz()\n protocol.fill_hyperpar_value(tf=tf)\n fun = protocol.time_dependent_fun(np.asarray([height, ratio * tf, 0]))\n output_state = optimization.evolve_state([rabi.H0, [rabi.H1, fun]],\n initial_state, tf)\n results[idx] = [tf, ratio, qutip.fidelity(output_state, target_state)**2]\n idx += 1\n results = pd.DataFrame(results, columns=['tf', 'ratio', 'fid'])\n\n results.to_csv(output_file_name + '_height{:03}.csv'.format(height))\n","sub_path":"results/rabi_doublebang_scans_20190306/script_Omega100_megascan_bigheights_finer.py","file_name":"script_Omega100_megascan_bigheights_finer.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"373796230","text":"import sys\nimport os\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cycler import cycler\n\nimport fym.logging as logging\n\n\nBASE_DATA_DIR = \"data\"\n\nplt.rc(\"font\", **{\n \"family\": \"sans-serif\",\n # \"sans-serif\": [\"Helvetica\"],\n})\n# plt.rc(\"text\", usetex=True)\nplt.rc(\"lines\", linewidth=1.3)\nplt.rc(\"axes\", grid=True)\nplt.rc(\"grid\", linestyle=\"--\", alpha=0.8)\n\n\ncanvas = []\nfig, axes = plt.subplots(2, 1, sharex=True)\naxes[0].set_ylabel(r\"$\\beta$ [deg]\")\naxes[1].set_ylabel(r\"$r$ [deg/sec]\")\naxes[1].set_xlabel(\"Time [sec]\")\ncanvas.append((fig, axes))\n\nfig, axes = plt.subplots(2, 1, sharex=True)\naxes[0].set_ylabel(r\"$\\phi$ [deg]\")\naxes[1].set_ylabel(r\"$p$ [deg/sec]\")\naxes[1].set_xlabel(\"Time [sec]\")\ncanvas.append((fig, axes))\n\n# fig, axes = plt.subplots(2, 1, sharex=True)\n# axes[0].set_ylabel(r\"$\\delta_a$ [deg]\")\n# axes[1].set_ylabel(r\"$\\delta_r$ [deg]\")\n# axes[1].set_xlabel(\"Time [sec]\")\n# canvas.append((fig, axes))\n\n\ndef get_data(exp, prefix=BASE_DATA_DIR):\n path = os.path.join(prefix, exp + \".h5\")\n return logging.load(path)\n\n\ndef plot_single(data, color=\"k\", name=None):\n time = data[\"time\"]\n beta, phi, p, r = data[\"state\"][\"main\"][:, :4].T\n # aileron, rudder = data[\"control\"].T\n\n canvas[0][1][0].plot(time, beta, color=color, label=name)\n canvas[0][1][1].plot(time, r, color=color)\n\n canvas[1][1][0].plot(time, phi, color=color, label=name)\n canvas[1][1][1].plot(time, p, color=color)\n\n # canvas[2][1][0].plot(time, aileron, color=color, label=name)\n # canvas[2][1][1].plot(time, rudder, color=color)\n\n\ndef plot_mult(dataset, color_cycle=None, names=None):\n if color_cycle is None:\n color_cycle = cycler(\n color=plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\n )\n\n if names is not None:\n for data, color, name in zip(dataset, color_cycle(), names):\n plot_single(data, color=color[\"color\"], name=name)\n\n for fig, axes in canvas:\n axes[0].legend(*axes[0].get_legend_handles_labels())\n else:\n for data, color in zip(dataset, color_cycle()):\n plot_single(data, color=color[\"color\"])\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file\", nargs=\"*\")\n parser.add_argument(\"--all\", action=\"store_true\")\n args = parser.parse_args()\n\n color_cycle = cycler(color=plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"])\n\n path_list = args.file\n if args.all:\n path_list = sorted(glob.glob(os.path.join(BASE_DATA_DIR, \"*.h5\")))\n else:\n path_list = sorted(filter(lambda x: x.endswith(\".h5\"), path_list))\n\n dataset = []\n for path, c in zip(path_list, color_cycle()):\n dataset.append(logging.load(path))\n\n names = [os.path.basename(os.path.splitext(path)[0]) for path in path_list]\n\n print(\"Plotting ...\")\n print(\"\\n\".join(path_list))\n plot_mult(dataset, color_cycle, names=names)\n","sub_path":"test/figures.py","file_name":"figures.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"84206792","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport os\nimport stat\n\nfrom subprocess import call\n\nimport pandas as pd\n\nfrom scipy.optimize import curve_fit\n\nAPROF_LOGGER = 'aprof_logger.txt'\nPATH = os.path.dirname(os.path.realpath(__file__))\n\n\ndef generate_test_case(i):\n return str((i + 1) * 100)\n\n\ndef run_command():\n for i in range(0, 30):\n if os.path.exists(APROF_LOGGER):\n new_name = APROF_LOGGER.split('.')[0] + '_' + str(i) + '.txt'\n os.rename(APROF_LOGGER, new_name)\n\n command = ['./a.out ', ' ', generate_test_case(i)]\n with open('test.sh', 'w') as run_script:\n run_script.writelines(command)\n st = os.stat('test.sh')\n os.chmod('test.sh', st.st_mode | stat.S_IEXEC)\n\n call(['/bin/bash', 'test.sh'])\n\n # delete temp test.sh\n os.remove('test.sh')\n\n\ndef clean_temp_files():\n for dirname, dirnames, filenames in os.walk('.'):\n # print path to all filenames.\n for filename in filenames:\n if filename.endswith('.txt') or filename.endswith('.csv'):\n os.remove(\n os.path.join(PATH, os.path.join(\n dirname[2:], filename)))\n\n print('Clean all temp files!')\n\n\ndef _parser(file_name, run_id):\n result = []\n with open(file_name, 'r') as f:\n lines = f.readlines()\n for line in lines:\n # FIXME:: TOO BAD!!!\n items = line.strip('\\n').split(';')\n func_id = items[0].strip().split(' ')[1]\n rms = items[1].strip().split(' ')[1]\n cost = items[2].strip().split(' ')[1]\n result.append([func_id, rms, cost, run_id])\n\n return result\n\n\ndef parse_log_file():\n results = []\n for dirname, dirnames, filenames in os.walk('.'):\n # print path to all filenames.\n index = 1\n for filename in filenames:\n if filename.endswith('.txt') and 'aprof_logger' in filename:\n result = _parser(filename, index)\n index += 1\n for item in result:\n results.append(item)\n\n df = pd.DataFrame(data=results, columns=['func_id', 'rms', 'cost', 'run_id'])\n df.to_csv('mozilla416628_result.csv', index=False)\n\n\ndef calculate_curve_fit():\n \"\"\"\n calculate the expression of target function\n :return:\n \"\"\"\n\n def fund(x, a, b):\n return x ** a + b\n\n df = pd.read_csv('mozilla416628_result.csv')\n df = df.loc[df['func_id'] == 10]\n xdata = df[['rms']].apply(pd.to_numeric)\n ydata = df[['cost']].apply(pd.to_numeric)\n\n xdata = [item[0] for item in xdata.values]\n ydata = [item[0] for item in ydata.values]\n\n popt, pcov = curve_fit(fund, xdata, ydata)\n # print y = x^a +/- b\n op_code = '+'\n if popt[1] < 0:\n op_code = '-'\n popt[1] = popt[1] * -1\n\n to_str = ['y = x^', '%.2f' % popt[0], ' ', op_code, ' ', '%.2f' % popt[1]]\n print(''.join(to_str))\n\n\nif __name__ == '__main__':\n # clean_temp_files()\n # run_command()\n parse_log_file()\n # calculate_curve_fit()\n # if you want to save result csv,\n # you can comment the follow line code.\n # clean_temp_files()\n","sub_path":"stubs/mozilla/mozilla416628/run_mozilla416628.py","file_name":"run_mozilla416628.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"188136170","text":"from resume.error.error import error\nfrom resume.dummy.dummyapi import dummyApi\nfrom resume.extraction.resumeextraction import ResumeExtract\nfrom flask import Flask, jsonify, request, Blueprint\nfrom flask_cors import CORS, cross_origin\nimport os\nimport json\nimport nltk\n\nmain = Blueprint('main', __name__)\n#nltk.download('popular')\n\n@main.route('/', methods=['GET'])\ndef hello():\n return 'Whatup bitch Head over to'\n\n\n@main.route('/api/v1/dummy')\ndef api():\n return dummyApi()\n\n\n@main.route('/api/v1/postResume', methods=['POST'])\n@cross_origin()\ndef index():\n dataList = list()\n if request.method == 'POST':\n try:\n if not request.files or request.files['file'].filename == '':\n raise Exception(\"Select a file\")\n for file in request.files.getlist('file'):\n fileName = file.filename\n if fileName.endswith('.pdf'):\n file.save(file.filename)\n ext = ResumeExtract(fileName)\n dataList.append(ext.get_data())\n os.remove(fileName)\n return json.dumps(dataList)\n except Exception as e:\n return error(str(e.args), 415)\n","sub_path":"api/resume/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"400022498","text":"import numpy as np\n\n\ndef solution(num):\n first = np.identity(num-1) + np.ones((num-1,num-1))\n examples = [first]\n if num%2 == 0:\n numbercount = num//2-2\n base=2\n else:\n numbercount = num//2-1\n base=1\n for i in range(numbercount):\n a =examples[-1][:-1,:-1] + np.diag(np.ones(num-(3+(2*i))), k=i+1) + np.diag(np.ones(i+1), k=-(num-(3+(2*i)))) + np.diag(np.ones(i), k=-(num-(2+(2*i))))\n examples.append(a)\n final_ans = sum([len(element) for element in examples])+base\n return final_ans\n\nstairs = int(input(\"Number of stairs: \"))\nprint(f\"Ways to climb to the top: {solution(stairs)}\")\n\n\n\"\"\"\nYou are climbing a stair case. It takes n steps to reach to the top.\nEach time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n\nFor example, if the stair has 4 steps, there are 5 ways to climb to the top:\n1) 1, 1, 1, 1\n2) 1, 2, 1\n3) 1, 1, 2\n4) 2, 1, 1\n5) 2, 2\n\nThe following class calculates the total ways to climb a stair with the specified number of steps.\nIt also counts the number of calculations performed which indicates the efficiency of the code.\nTry if you can improve the performance of the code.\n\"\"\"\n\"\"\"\nclass ClimbStairs:\n def __init__(self, total_steps=10): \n self.total_steps = total_steps\n self.calculation_count = 0\n\n def calc_solutions(self, i):\n # If the current step is already larger than total steps, there's 0 solution\n if i > self.total_steps:\n return 0\n\n # If the current step equals to the total steps, there is only one solution because I've reached the top\n if i == self.total_steps:\n return 1\n\n # If I am still in the middle of the stair, continue calculating\n self.calculation_count += 1\n\n # Call the current function recursively. \n # The number of solutions at the ith step equals to the number of solutions at the (i+1)th step \n # plus the number of solutions at the (i+2)th step\n return(self.calc_solutions(i+1) + self.calc_solutions(i+2))\n\n def get_calculation_count(self):\n return self.calculation_count\n\n def solve(self):\n return self.calc_solutions(0)\n\ntotal_steps = input(\"How many steps in the stair?\")\nnew_challenge = ClimbStairs(int(total_steps))\nprint('Ways to climb to top: ' + str(new_challenge.solve()))\nprint('Total calculations performed: ' + str(new_challenge.get_calculation_count()))\n\"\"\"\n","sub_path":"your-code/bonus.py","file_name":"bonus.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"16164336","text":"import time\r\nfrom time import gmtime, strftime\r\nfrom datetime import datetime\r\n\r\nimport webbrowser\r\nimport pandas as pd\r\n\r\nimport os\r\nimport sys\r\nimport alsaaudio\r\n\r\nm = alsaaudio.Mixer('PCM')\r\ncurrent_volume = m.getvolume() # Get the current Volume\r\n\r\nclass radio():\r\n\r\n data_radio = pd.read_csv('data-radio-tet.csv', sep=';')\r\n row, col = data_radio.shape\r\n #data_history = pd.read_csv('data-history.csv', sep=';')\r\n #d = {'content': ['First'], 'start': ['08:00:00'], 'stop': ['09:00:00']}\r\n #df = pd.DataFrame(data=d)\r\n #print(\"Original DataFrame\")\r\n #df.to_csv('data-history.csv', sep=';')\r\n \r\n \r\n #print(data_radio)\r\n\r\n def timenow(self):\r\n now = datetime.now()\r\n realtime = now.strftime(\"%H:%M:%S\")\r\n return realtime\r\n\r\n def isTime(self):\r\n now = datetime.now()\r\n realtime = now.strftime(\"%H:%M:%S\")\r\n start_trigger = self.data_radio[self.data_radio['start']==realtime].index.tolist()\r\n stop_trigger = self.data_radio[self.data_radio['stop']==realtime].index.tolist()\r\n if len(start_trigger)!=0:\r\n #os.system('pkill -3 chromium')\r\n #time.sleep(1)\r\n link = \"python3 -m webbrowser -t \" + str(self.data_radio.iloc[start_trigger[0], 5])\r\n os.system(link)\r\n m.setvolume(self.data_radio.iloc[start_trigger[0], 2])\r\n print(\"Open: \"+ self.data_radio.iloc[start_trigger[0], 6] +\" at \"+self.time_display())\r\n #record = {'content': [self.data_radio.iloc[start_trigger[0], 6]], 'start': [self.data_radio.iloc[start_trigger[0], 3]], 'stop': [self.data_radio.iloc[start_trigger[0], 4]]}\r\n #print(record)\r\n #self.data_history = pd.read_csv('data-history.csv', sep=';')\r\n #self.data_history.append(record, ignore_index=True)\r\n #self.data_history.to_csv('data-history.csv', sep=';')\r\n if len(stop_trigger)!=0:\r\n #os.system('pkill -3 chromium')\r\n os.system('pkill -3 chromium')\r\n print(\"Close\"+\" at \"+self.time_display()+ \", \" + self.measure_temp())\r\n self.update_data_table()\r\n print(self.data_radio[['no.', 'comment', 'competed']].to_string(index=False))\r\n\r\n \r\n def time_display(self): \r\n now = datetime.now()\r\n string = now.strftime(\"%H:%M:%S - %d/%m/%Y\")\r\n return string\r\n \r\n def measure_temp(self):\r\n res = os.popen('vcgencmd measure_temp').readline()\r\n return \"T=\" + str(res.replace(\"temp=\",\"\").replace(\"'C\\n\",\"\")) + \"'C\"\r\n def time_to_seconde(self, timexx):\r\n timelist = [int(i) for i in timexx.split(':') if i.isdigit()]\r\n return (timelist[0]*3600 + timelist[1]*60 + timelist[2])\r\n def update_data_table(self):\r\n self.data_radio = pd.read_csv('data-radio-tet.csv', sep=';')\r\n for i in range(self.row):\r\n time_now = self.time_to_seconde(self.timenow())\r\n time_start = self.time_to_seconde(self.data_radio.iloc[i, 3])\r\n time_stop = self.time_to_seconde(self.data_radio.iloc[i, 4])\r\n percent = int(((time_now-time_start)/(time_stop-time_start))*100)\r\n if percent > 100:\r\n self.data_radio.iloc[i,1] = \"100%\"\r\n elif percent < 0:\r\n self.data_radio.iloc[i,1]= \"0%\"\r\n else:\r\n self.data_radio.iloc[i,1]= str(percent)+\"%\"\r\n \r\n def reset_Pi3(self,reboot_time):\r\n if reboot_time==self.timenow():\r\n os.system(\"sudo reboot\")\r\n \r\n#Main loop \r\n def __init__(self):\r\n print(\"Automation RADIO - author: Mr.Tony Tran\")\r\n print(\"---------------------------------------------------------------\")\r\n print(\"Today Radio Listing:\")\r\n self.update_data_table()\r\n pd.set_option('display.max_columns', None)\r\n print(self.data_radio[['no.', 'comment', 'start', 'stop', 'link']].to_string(index=False))\r\n print('---------------------------------------------------------------')\r\n print('History record:')\r\n \r\n while True:\r\n self.update_data_table()\r\n self.isTime()\r\n self.reset_Pi3('01:00:00')\r\n time.sleep(1) \r\n \r\n \r\nif __name__ == \"__main__\":\r\n radio = radio()\r\n","sub_path":"radioAM_new.py","file_name":"radioAM_new.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"569867365","text":"from flask import Flask\r\nimport routes\r\nfrom flask_cors import CORS, cross_origin\r\n\r\napplication = Flask(__name__) \r\nCORS(application)\r\n\r\nfor route in routes.ALL_ROUTES:\r\n application.add_url_rule(rule=route.url, view_func=route.func, methods=route.methods)\r\n\r\n@application.route('/')\r\ndef index():\r\n return \"hello world!\"\r\n\r\nif __name__ == '__main__':\r\n application.run()","sub_path":"backend/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"446492220","text":"import cmath\nfrom numpy.random import rand\nimport numpy as np\nimport scipy.special as bessel\nimport plotly.io as pio\nimport angular_distribution as ad\nimport plotly.graph_objects as go\nimport plotly\nfrom plotly.subplots import make_subplots\n\npio.renderers.default = \"browser\"\n\n\ndef plotter(ampl, file_name, fig_header, resolution, S, M, x_setup, y_setup, UE_x, UE_y, x, y, wH=None, all_in=True, mini=None,\n maxi=None):\n \"\"\"plots the calculated grid and the surrounding area\"\"\"\n UE = ampl[UE_y][UE_x]\n amplis = [20 * np.log10(i / UE) for i in ampl]\n if mini is not None and maxi is None:\n maxi = max([max(i) for i in ampl])\n elif maxi is not None and mini is None:\n mini = min([min(i) for i in ampl])\n\n '''bubble'''\n values_edge_bubble = []\n dist_by_angle = []\n for i in range(0, 360):\n angle = i * np.pi / 180\n x_step = np.cos(angle)\n y_step = np.sin(angle)\n ix = UE_x\n ij = UE_y\n inter = amplis[ij][ix]\n prev_val = inter\n dist = 0\n while prev_val >= inter:\n try:\n prev_val = inter\n ix += x_step\n ij += y_step\n if ix % 1 != 0 and ij % 1 != 0:\n x1 = int(ix)\n x2 = x1 + 1\n y1 = int(ij)\n y2 = y1 + 1\n dx = abs(ix - x1)\n inter1 = amplis[y1][x1] * (1 - dx) + dx * amplis[y1][x2]\n inter2 = amplis[y2][x1] * (1 - dx) + dx * amplis[y2][x2]\n dy = abs(ij - y1)\n inter = inter1 * (1 - dy) + inter2 * dy\n elif ix % 1 == 0 and ij % 1 != 0:\n y1 = int(ij)\n y2 = y1 + 1\n dy = abs(ij - y1)\n inter = amplis[y1][int(ix)] * (1 - dy) + amplis[y2][int(ix)] * dy\n elif ij % 1 == 0 and ix % 1 != 0:\n x1 = int(ix)\n x2 = x1 + 1\n dx = abs(ix - x1)\n inter = amplis[int(ij)][x1] * (1 - dx) + dx * amplis[int(ij)][x2]\n else:\n inter = amplis[int(ij)][int(ix)]\n dist += resolution\n except IndexError as e:\n inter = prev_val + resolution\n dist += resolution\n print(angle)\n dist -= resolution\n dist_by_angle.append(dist)\n values_edge_bubble.append(prev_val)\n\n if all_in:\n '''Avg intersection'''\n tot = amplis[int(len(x) / 2)][int(len(y) / 2):-1]\n for i in range(1, 360):\n angle = i * np.pi / 180\n x_step = np.cos(angle)\n y_step = np.sin(angle)\n ix = int(len(amplis) / 2)\n ij = int(len(amplis) / 2)\n graph = [amplis[ij][ix]]\n for j in range(int(len(amplis) / 2)-1):\n ix += x_step\n ij += y_step\n if ix % 1 != 0 and ij % 1 != 0:\n x1 = int(ix)\n x2 = x1 + 1\n y1 = int(ij)\n y2 = y1 + 1\n dx = abs(ix - x1)\n inter1 = amplis[y1][x1] * (1 - dx) + dx * amplis[y1][x2]\n inter2 = amplis[y2][x1] * (1 - dx) + dx * amplis[y2][x2]\n dy = abs(ij - y1)\n inter = inter1 * (1 - dy) + inter2 * dy\n graph.append(inter)\n elif ix % 1 == 0 and ij % 1 != 0:\n y1 = int(ij)\n y2 = y1 + 1\n dy = abs(ij - y1)\n inter = amplis[y1][int(ix)] * (1 - dy) + amplis[y2][int(ix)] * dy\n graph.append(inter)\n elif ij % 1 == 0 and ix % 1 != 0:\n x1 = int(ix)\n x2 = x1 + 1\n dx = abs(ix - x1)\n inter = amplis[int(ij)][x1] * (1 - dx) + dx * amplis[int(ij)][x2]\n graph.append(inter)\n else:\n inter = amplis[int(ij)][int(ix)]\n graph.append(inter)\n tot = tot + graph\n tot = tot / 360\n\n '''radi pat'''\n theta_deg = np.linspace(-180, 180 + 0.01, num=10000)\n theta_rad = np.linspace(-np.pi, np.pi + 0.01, num=10000)\n temp = [cmath.polar(i) for i in wH] # wH = antenna weights\n amplitude = [i[0] for i in temp]\n phase = [i[1] for i in temp]\n rad_pat = []\n for i in range(len(wH)):\n rad_pat.append(amplitude[i] * np.exp(1j * (phase[i])) * np.exp(1j * i * np.pi * np.cos(theta_rad - np.pi / 2)))\n radi_pattern = sum(rad_pat)\n\n '''angular pwr'''\n ang_pwr = ad.weighted_power(S, M, x_setup, y_setup, 16, plotter='plotly')\n\n \"\"\"plotting\"\"\"\n fig = make_subplots(rows=2, cols=4, column_widths=[250, 250, 250, 850],\n specs=[[{\"colspan\": 3}, None, None, {\"rowspan\": 2}],\n [{\"type\": \"polar\"}, {\"type\": \"Barpolar\"}, {\"type\": \"polar\"}, None]])\n w = np.linspace(0, int(len(amplis) / 2) + 0.01, num=1000)\n w = w * resolution\n fig.add_trace(go.Scatter(x=w, y=20 * np.log10(abs(bessel.j0(2 * np.pi * w))), showlegend=False), row=1,\n col=1)\n fig.add_trace(go.Scatter(x=(np.linspace(0, int(len(amplis) / 2) + 0.01, num=len(tot))) * resolution, y=tot,\n showlegend=False), row=1, col=1)\n fig.add_trace(ang_pwr, row=2, col=2)\n fig.add_trace(go.Scatterpolar(theta=theta_deg, r=abs(radi_pattern), mode='lines', showlegend=False), row=2, col=1)\n fig.add_trace(\n go.Scatterpolar(theta=np.linspace(0, 360, 360), r=dist_by_angle, mode='lines', showlegend=False),\n row=2, col=3)\n\n fig.add_trace(go.Heatmap(\n z=amplis,\n x=x,\n y=y,\n colorscale='Jet',\n zmin=mini,\n zmax=maxi\n ), row=1, col=4)\n fig.add_trace(go.Scatter(\n x=x_setup[-1 - S:-1],\n y=y_setup[-1 - S:-1],\n mode='markers',\n name='scatterers',\n marker_color='blue',\n marker=dict(size=3)\n ), row=1, col=4)\n fig.add_trace(go.Scatter(\n x=[x_setup[-1]],\n y=[y_setup[-1]],\n name='antenna',\n mode='markers',\n text=str(ampl[int(len(ampl) / 2)][int(len(ampl[0]) / 2)]),\n marker_symbol=\"circle-x\",\n marker_color=\"red\",\n marker_line_color=\"white\",\n marker_line_width=0.5,\n marker_size=5\n ), row=1, col=4)\n fig.add_trace(go.Scatter(\n x=x_setup[:M],\n y=y_setup[:M],\n name='BS',\n mode='markers',\n marker_color='red',\n marker=dict(size=3)\n ), row=1, col=4)\n fig.add_trace(go.Scatter(\n x=[0, 800],\n y=[0, 800],\n mode='markers',\n name='dom',\n opacity=1,\n marker_color='white',\n marker=dict(size=3)\n ), row=1, col=4)\n fig.update_layout(autosize=False,\n width=1550,\n height=800,\n title=fig_header,\n font=dict(size=10),\n polar=dict(radialaxis=dict(visible=False)),\n polar2=dict(radialaxis=dict(visible=False)))\n plotly.offline.plot(fig, filename=file_name)\n fig.show()\n else:\n fig = go.Figure(data=go.Heatmap(\n z=amplis,\n x=x,\n y=y,\n colorscale='Jet',\n zmin=mini,\n zmax=maxi\n ))\n\n fig.add_trace(go.Scatter(\n x=x_setup[-S - 1:-1],\n y=y_setup[-S - 1:-1],\n mode='markers',\n name='scatterers',\n marker_color='blue',\n marker=dict(size=3)\n ))\n\n fig.add_trace(go.Scatter(\n x=[x_setup[-1]],\n y=[y_setup[-1]],\n name='antenna',\n mode='markers',\n marker_symbol=\"y-down\",\n marker_line_color=\"red\",\n marker_line_width=2,\n marker_size=5,\n text=str(ampl[int(len(ampl) / 2)][int(len(ampl[0]) / 2)])\n ))\n fig.add_trace(go.Scatter(\n x=x_setup[:M],\n y=y_setup[:M],\n name='BS',\n mode='markers',\n marker_color='red',\n marker=dict(size=3)\n ))\n fig.add_trace(go.Scatter(\n x=[0, 800],\n y=[0, 800],\n mode='markers',\n name='dom',\n opacity=1,\n marker_color='white',\n marker=dict(size=3)\n ))\n fig.update_layout(autosize=False,\n width=850,\n height=800,\n title=fig_header,\n font=dict(size=10))\n plotly.offline.plot(fig, filename=file_name)\n fig.show()\n return [np.var(dist_by_angle), np.average(dist_by_angle), np.var(values_edge_bubble), np.average(values_edge_bubble)]\n\n\n\n\n\ndef IQ(array):\n I = []\n Q = []\n for i in range(len(array)):\n if i % 2 == 0:\n I.append(array[i])\n else:\n Q.append(array[i])\n if len(I) != len(Q):\n I = Q = None\n return I, Q\n\n\n# def data_to_voltage_lvl(array):\n# for i in range(len(array)):\n# if array[i] == 0:\n# array[i] = -1 # /sqrt(2)\n# # elif array[i] == 1:\n# # array[i] = 1/sqrt(2)\n\n\ndef data_to_voltage_lvl(array, tech):\n technr = np.log2(np.sqrt(tech))\n if len(array) % technr != 0:\n return [1]\n array_a = []\n temp = technr\n n = 0\n for i in range(len(array)):\n if i % technr == 0:\n array_a.append(1 - 2 ** technr + n * 2)\n temp = technr\n n = 0\n n += array[i] * 2 ** (temp - 1)\n temp -= 1\n array_a.append(1 - 2 ** technr + n * 2)\n return [int(i) for i in array_a[1:]]\n\n\ndef avg(array):\n gem = 0\n for i in range(0, len(array)):\n gem += array[i]\n return gem / len(array)\n\n\ndef rho(x):\n return bessel.j0(2 * np.pi * x) # Bessel function 1st kind, 0th order\n\n\ndef hd(dx, h):\n e = 0.2 * rand(1)[0] + 0.9 # innovation factor\n return rho(dx) * h + (np.sqrt(1 - (abs(rho(dx))) ** 2) * e)\n\n\n'''Test zone'''\n# a = [0,1,1,1,0,1,1,0,1,0,0,0,1,0,0,1]\n# a = data_to_voltage_lvl(a, 16)\n# print(a)","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":10591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"197523176","text":"# Create the areas list\nareas = [\"hallway\", 11.25, \"kitchen\", 18.0, \"living room\", 20.0, \"bedroom\", 10.75, \"bathroom\", 9.50]\n\nx = 0\ni = 0\nwhile x != 18.0:\n print(\"Result not found\")\n x = areas[i]\n i = i+1\nprint(\"Result Found. result Location is\")\nprint(i-1)\n\n","sub_path":"class-2.py","file_name":"class-2.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"252779948","text":"import os\nimport shutil\n\nbase = os.path.join(os.path.expanduser('~'), '301_KUXIN', 'out')\n\nif __name__ == '__main__':\n new_path = os.path.join(os.path.expanduser('~'), '301_KUXIN', 'subj_COT1')\n if not os.path.exists(new_path):\n os.makedirs(new_path)\n\n move_no = 0\n for subj_name in os.listdir(base):\n subj_path = os.path.join(base, subj_name)\n\n if not os.path.isdir(subj_path):\n continue\n\n for file_name in os.listdir(subj_path):\n if file_name.startswith('co') and file_name.endswith('.nii'):\n move_no += 1\n print('%s %s: %s. ' % (move_no, subj_name, file_name))\n\n new_file_name = subj_name + '_cot1.nii'\n shutil.copy2(os.path.join(subj_path, file_name), os.path.join(new_path, new_file_name))\n","sub_path":"scripts/copy_mv_file.py","file_name":"copy_mv_file.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"432876066","text":"def main():\n module = AnsibleModule(argument_spec=dict(host=dict(type='str', default='127.0.0.1'), timeout=dict(type='int', default=300), connect_timeout=dict(type='int', default=5), delay=dict(type='int', default=0), port=dict(type='int'), active_connection_states=dict(type='list', default=['ESTABLISHED', 'FIN_WAIT1', 'FIN_WAIT2', 'SYN_RECV', 'SYN_SENT', 'TIME_WAIT']), path=dict(type='path'), search_regex=dict(type='str'), state=dict(type='str', default='started', choices=['absent', 'drained', 'present', 'started', 'stopped']), exclude_hosts=dict(type='list'), sleep=dict(type='int', default=1), msg=dict(type='str')))\n host = module.params['host']\n timeout = module.params['timeout']\n connect_timeout = module.params['connect_timeout']\n delay = module.params['delay']\n port = module.params['port']\n state = module.params['state']\n path = module.params['path']\n search_regex = module.params['search_regex']\n msg = module.params['msg']\n if (search_regex is not None):\n compiled_search_re = re.compile(search_regex, re.MULTILINE)\n else:\n compiled_search_re = None\n if (port and path):\n module.fail_json(msg='port and path parameter can not both be passed to wait_for')\n if (path and (state == 'stopped')):\n module.fail_json(msg='state=stopped should only be used for checking a port in the wait_for module')\n if (path and (state == 'drained')):\n module.fail_json(msg='state=drained should only be used for checking a port in the wait_for module')\n if ((module.params['exclude_hosts'] is not None) and (state != 'drained')):\n module.fail_json(msg='exclude_hosts should only be with state=drained')\n for _connection_state in module.params['active_connection_states']:\n try:\n get_connection_state_id(_connection_state)\n except:\n module.fail_json(msg=('unknown active_connection_state (%s) defined' % _connection_state))\n start = datetime.datetime.utcnow()\n if delay:\n time.sleep(delay)\n if ((not port) and (not path) and (state != 'drained')):\n time.sleep(timeout)\n elif (state in ['absent', 'stopped']):\n end = (start + datetime.timedelta(seconds=timeout))\n while (datetime.datetime.utcnow() < end):\n if path:\n try:\n f = open(path)\n f.close()\n except IOError:\n break\n elif port:\n try:\n s = _create_connection(host, port, connect_timeout)\n s.shutdown(socket.SHUT_RDWR)\n s.close()\n except:\n break\n time.sleep(module.params['sleep'])\n else:\n elapsed = (datetime.datetime.utcnow() - start)\n if port:\n module.fail_json(msg=(msg or ('Timeout when waiting for %s:%s to stop.' % (host, port))), elapsed=elapsed.seconds)\n elif path:\n module.fail_json(msg=(msg or ('Timeout when waiting for %s to be absent.' % path)), elapsed=elapsed.seconds)\n elif (state in ['started', 'present']):\n end = (start + datetime.timedelta(seconds=timeout))\n while (datetime.datetime.utcnow() < end):\n if path:\n try:\n os.stat(path)\n except OSError as e:\n if (e.errno != 2):\n elapsed = (datetime.datetime.utcnow() - start)\n module.fail_json(msg=(msg or ('Failed to stat %s, %s' % (path, e.strerror))), elapsed=elapsed.seconds)\n else:\n if (not compiled_search_re):\n break\n try:\n f = open(path)\n try:\n if re.search(compiled_search_re, f.read()):\n break\n finally:\n f.close()\n except IOError:\n pass\n elif port:\n alt_connect_timeout = math.ceil(_timedelta_total_seconds((end - datetime.datetime.utcnow())))\n try:\n s = _create_connection(host, port, min(connect_timeout, alt_connect_timeout))\n except:\n pass\n else:\n if compiled_search_re:\n data = ''\n matched = False\n while (datetime.datetime.utcnow() < end):\n max_timeout = math.ceil(_timedelta_total_seconds((end - datetime.datetime.utcnow())))\n (readable, w, e) = select.select([s], [], [], max_timeout)\n if (not readable):\n continue\n response = s.recv(1024)\n if (not response):\n break\n data += to_native(response, errors='surrogate_or_strict')\n if re.search(compiled_search_re, data):\n matched = True\n break\n s.shutdown(socket.SHUT_RDWR)\n s.close()\n if matched:\n break\n else:\n s.shutdown(socket.SHUT_RDWR)\n s.close()\n break\n time.sleep(module.params['sleep'])\n else:\n elapsed = (datetime.datetime.utcnow() - start)\n if port:\n if search_regex:\n module.fail_json(msg=(msg or ('Timeout when waiting for search string %s in %s:%s' % (search_regex, host, port))), elapsed=elapsed.seconds)\n else:\n module.fail_json(msg=(msg or ('Timeout when waiting for %s:%s' % (host, port))), elapsed=elapsed.seconds)\n elif path:\n if search_regex:\n module.fail_json(msg=(msg or ('Timeout when waiting for search string %s in %s' % (search_regex, path))), elapsed=elapsed.seconds)\n else:\n module.fail_json(msg=(msg or ('Timeout when waiting for file %s' % path)), elapsed=elapsed.seconds)\n elif (state == 'drained'):\n end = (start + datetime.timedelta(seconds=timeout))\n tcpconns = TCPConnectionInfo(module)\n while (datetime.datetime.utcnow() < end):\n try:\n if (tcpconns.get_active_connections_count() == 0):\n break\n except IOError:\n pass\n time.sleep(module.params['sleep'])\n else:\n elapsed = (datetime.datetime.utcnow() - start)\n module.fail_json(msg=(msg or ('Timeout when waiting for %s:%s to drain' % (host, port))), elapsed=elapsed.seconds)\n elapsed = (datetime.datetime.utcnow() - start)\n module.exit_json(state=state, port=port, search_regex=search_regex, path=path, elapsed=elapsed.seconds)","sub_path":"Data Set/bug-fixing-5/402b095841d901b012f20e9473bdee6b0f43a398-
-bug.py","file_name":"402b095841d901b012f20e9473bdee6b0f43a398-
-bug.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"146691867","text":"from django.shortcuts import render, redirect\nfrom accounts.forms import RegistrationForm\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\n\n\ndef index(request):\n\tname='Harsha Deuri'\n\tnumbers=[1,2,3,4,5]\n\targs={'myName':name, 'myNumbers':numbers}\n\treturn render(request,'accounts/landingPage.html',args)\n\ndef register(request):\n\tif request.method=='POST':\n\t\tform=RegistrationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn redirect(reverse('accounts:login'))\n\telse:\n\t\tform=RegistrationForm()\n\n\targs={'form':form}\n\treturn render(request, 'accounts/registration.html', args)\n\ndef profile(request):\n\targs={'user':request.user}\n\n\treturn render(request, 'accounts/profile.html', args)","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"341627584","text":"from django.urls import path\nfrom .views import HomePageView, AboutPageView, ContactPageView, RequestReceivedPageView, ProjectListView, ProjectView\n\nurlpatterns = [\n path('', HomePageView.as_view(), name='home'),\n path('about/', AboutPageView.as_view(), name='about'),\n path('contact/', ContactPageView.as_view(), name='contact'),\n path('project_list/', ProjectListView.as_view(), name='project_list'),\n path('project_list/', ProjectView.as_view(), name='project'),\n path('request_received/', RequestReceivedPageView.as_view(), name='request_received'),\n ]\n","sub_path":"main_pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"529074694","text":"from kivy.uix.screenmanager import Screen\nfrom kivy.properties import ObjectProperty, NumericProperty, DictProperty, StringProperty, ListProperty\nfrom kivymd.app import MDApp\nfrom kivymd.uix.snackbar import Snackbar\nfrom kivy.uix.boxlayout import BoxLayout\nfrom datetime import datetime\n\n\nclass TestingScreen(Screen):\n\n\t# questions[0] - Вопрос\n\t# questions[1] - Варианты ответа\n\tquestions = {\n\t\t11: ['Вы употребляли вчера алкоголь?', {'A': 'Да, крепкий алкоголь', 'B': 'Да, слабоалкогольные напитки', 'C': 'Нет'}],\n\t\t12: ['Сколько вы спали прошлой ночью?', {'A': '1-5 часов', 'B': '6-8 часов', 'C': '9-12 часов'}],\n\t\t13: ['Сколько раз за день вы поели?', {'A': '1 раз', 'B': '2-3 раза', 'C': 'Больше 3 раз'}],\n\t\t14: ['У вас вчера болела голова?', {'A': 'Да', 'B': 'Да, но не сильно', 'C': 'Нет'}],\n\t}\n\n\tq_current = NumericProperty()\n\tq_count = NumericProperty()\n\tanswers = DictProperty()\n\n\tdef on_enter(self, *args):\n\t\tself.q_count = len(self.questions)\n\t\tself.q_current = 0\n\n\t\tfor question_num, question in self.questions.items():\n\t\t\tcard = QuestionCard(text=question[0], testing_screen=self, number=question_num)\n\t\t\ti = 1\n\t\t\tfor num, variant in question[1].items():\n\t\t\t\tcard.add_height()\n\t\t\t\tcard.ids.answers_vars.add_widget(QuestionRow(\n\t\t\t\t\tquestion_number=num,\n\t\t\t\t\ttext=variant,\n\t\t\t\t\tquestion_card=card,\n\t\t\t\t\tcheckbox_group=question[0],\n\t\t\t\t))\n\t\t\t\ti += 1\n\t\t\ti = 0\n\t\t\tself.ids.grid.add_widget(card)\n\n\tdef on_answers(self, obj, value):\n\t\tself.q_current = len(value)\n\t\tif self.q_current == self.q_count:\n\t\t\tself.ids.done_btn.disabled = False\n\n\tdef update_answers(self, question_number, answer_variant):\n\t\tself.answers.update({question_number: answer_variant})\n\n\tdef save(self):\n\t\tapp_instance = MDApp.get_running_app()\n\t\tres = app_instance.db.patch_daily_testing(self.answers)\n\n\t\tif 'data' in app_instance.user_data:\n\t\t\tnew_data = {**app_instance.user_data['data'], **{str(int(datetime.today().timestamp())): self.answers}}\n\t\telse:\n\t\t\tnew_data = {int(datetime.today().timestamp()): self.answers}\n\n\t\tapp_instance.user_data['data'] = new_data\n\n\t\tif not res:\n\t\t\tSnackbar(text='Не удалось записать тестирование на сервер').show()\n\t\telse:\n\t\t\tself.manager.current = 'manage'\n\t\t\tapp_instance.user_data = {**app_instance.user_data, **{'lastTestingTime': res}}\n\t\t\tSnackbar(text='Данные успешно записаны').show()\n\n\tdef on_leave(self, *args):\n\t\tself.ids.grid.clear_widgets()\n\t\tself.q_current = 0\n\t\tself.q_count = 0\n\t\tself.answers = {}\n\t\tself.ids.done_btn.disabled = True\n\n\nclass QuestionCard(BoxLayout):\n\tnumber = NumericProperty()\n\ttext = StringProperty()\n\tcard_height = NumericProperty(10)\n\tselected_answer = StringProperty()\n\ttesting_screen = ObjectProperty()\n\n\tdef on_selected_answer(self, obj, value):\n\t\tself.testing_screen.update_answers(self.number, self.selected_answer)\n\n\tdef add_height(self):\n\t\tself.card_height = self.card_height + 50\n\n\nclass QuestionRow(BoxLayout):\n\tquestion_number = StringProperty()\n\ttext = StringProperty()\n\tcheckbox_group = StringProperty()\n\tquestion_card = ObjectProperty()\n\n\tdef __init__(self, **kwargs):\n\t\tsuper().__init__(**kwargs)\n\t\tself.checkbox = self.ids.question_check\n\t\tself.checkbox.bind(active=self.on_checkbox_active)\n\n\tdef on_checkbox_active(self, checkbox, value):\n\t\tif value:\n\t\t\tself.question_card.selected_answer = self.question_number\n","sub_path":"src/Screens/testing_screen.py","file_name":"testing_screen.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"493065673","text":"from flask import flash, redirect, request, current_app\r\nfrom flask_login import current_user\r\nfrom flask_babel import _\r\nfrom app import db\r\nfrom models import Task, TaskVersion, BotTask\r\nfrom util import get_extension\r\n\r\ndef get_invalid_messages(form):\r\n messages = ''\r\n for fieldName, errorMessages in form.errors.items():\r\n for err in errorMessages:\r\n if len(messages) == 0:\r\n messages = _('[%(field)s: %(error)s]'\r\n ,error=err\r\n , field=form[fieldName].label.text)\r\n else:\r\n messages = messages + ', ' + _('[%(field)s: %(error)s]'\r\n ,error=err\r\n , field=form[fieldName].label.text)\r\n return messages\r\n\r\ndef upload(task_name, file,bot_id=None):\r\n if file == '' or file == None:\r\n flash(_('No selected file, please select a file'))\r\n return redirect(request.url)\r\n \r\n task = Task(name=task_name, user= current_user)\r\n taskVersion = TaskVersion(task = task)\r\n file_content = file.read()\r\n extension = get_extension(file.filename)\r\n current_app.logger.info(\"File content %s, and extension %s\" % (file_content,extension))\r\n taskVersion.set_task_body(body=file_content, extension=extension)\r\n if bot_id is not None:\r\n bot_task = BotTask(bot_id=bot_id, task=task)\r\n db.session.add(bot_task)\r\n db.session.add(taskVersion)\r\n db.session.commit()\r\n flash(_(\"Task '%(task)s' was uploaded successfully\",task=task_name))","sub_path":"app/main/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"438526275","text":"#a 99% solution. This can probably be done in one pass.\nclass Solution:\n def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:\n ctr = 0\n if r * c != len(nums) * len(nums[0]):\n return nums\n flat = []\n \n new = []\n \n #gross, it's o(2N). can probably do in one pass.\n \n for i in range(len(nums)):\n for j in range(len(nums[0])):\n flat.append(nums[i][j])\n \n for i in range(r):\n row = []\n for j in range(c):\n row.append(flat.pop(0))\n \n new.append(row)\n return new\n \n'''\n566. Reshape the Matrix\nEasy\n\nIn MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.\n\nYou're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.\n\nThe reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.\n\nIf the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.\n\nExample 1:\n\nInput: \nnums = \n[[1,2],\n [3,4]]\nr = 1, c = 4\nOutput: \n[[1,2,3,4]]\nExplanation:\nThe row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.\n\nExample 2:\n\nInput: \nnums = \n[[1,2],\n [3,4]]\nr = 2, c = 4\nOutput: \n[[1,2],\n [3,4]]\nExplanation:\nThere is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.\n\n\n'''","sub_path":"leet/matrixReshape/matrixReshape.py","file_name":"matrixReshape.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"453989146","text":"#!/usr/bin/env python3\n\nfrom collections import defaultdict\nimport fileinput, itertools, math, nltk, random, re\n\nfrom cleaners import Cleaner\nfrom conversation import *\n\nsentence_splitter = nltk.data.load('tokenizers/punkt/english.pickle')\n\nBEGIN = [0]\nEND = [-1]\nEARLY_END = [-2]\nCITATION = [2]\n\n# basically an enum of phrase types. Some may be mutually exclusive, some may not.\nQUESTION = 0\nDECLARATION = 1\nFACT = 2\n\nFACT_WORDS = set([\"hence\", \"therefore\", \"is\", \"can\", \"proven\", \"cannot\", \"must\", \"should\"])\n\ndef lower(token):\n return token.lower() if hasattr(token, 'lower') else token\n\ndef islower(token):\n return token.islower() if hasattr(token, 'islower') else True\n\n\nclass GramNode(object):\n def __init__(self, parent):\n self.occurrences = defaultdict(lambda : 0)\n self.parent = parent\n self.children = defaultdict(self.make_child)\n\n def make_child(self):\n return GramNode(self)\n\n def add_occurrence(self, phrase_type):\n self.occurrences[phrase_type] += 1\n\n def likelihood(self, phrase_type):\n # take log of occurrences + 1 so that 0 occurrences = 0, and very common phrases\n # do not completely dominate our phrases\n return sum(map(lambda x: x.likelihood(phrase_type), self.children.values())) + math.log(self.occurrences[phrase_type] + 1)\n\n def get(self, keys):\n if len(keys) == 0:\n return self\n return self.children[keys[0]].get(keys[1:])\n\n def delete(self, key):\n if key in self.children:\n del self.children[key]\n for child in self.children.values():\n child.delete(key)\n\n def pick(self, phrase_type):\n skip = random.random() * (self.likelihood(phrase_type) - math.log(self.occurrences[phrase_type] + 1))\n for token in self.children:\n skip -= self.children[token].likelihood(phrase_type)\n if skip <= 0:\n return token, self.children[token]\n\n return random.choice(list(self.children.items()) or [(EARLY_END[0], None)])\n\n def has(self, keys):\n if len(keys) == 0:\n return False\n elif len(keys) == 1:\n return keys[0] in self.children\n return keys[0] in self.children and self.children[keys[0]].has(keys[1:])\n\n def pick_best(self, keys, phrase_type):\n oldKeys = keys\n while (not self.has(keys)) and len(keys) > 0:\n keys = keys[1:]\n result = self.get(keys).pick(phrase_type)\n return result\n\n def merge_into(self, other, weight=1.0):\n for phrase_type, count in self.occurrences.items():\n other.occurrences[phrase_type ]+= count * weight\n for key in self.children:\n self.children[key].merge_into(other.children[key], weight)\n\n def traverse(self, f):\n for child in self.children.values():\n child.traverse(f)\n f(self)\n\n def show(self, spaces):\n for token, node in self.children.items():\n print(\"{}-> {}\".format(spaces, token))\n node.show(spaces + \"-\")\n\n\nPRE_PUNCT_SPACE_MATCHER = re.compile(r\"\\s+([.,:)}'?!]+)\")\nPOST_PUNCT_SPACE_MATCHER = re.compile(r\"([\\({])\\s+\")\n\n\nclass GeneratedSentence(object):\n def __init__(self, detokenized, length, interrupted):\n self.detokenized = detokenized\n self.length = length\n self.interrupted = interrupted\n\n @staticmethod\n def for_tokens(tokens):\n interrupted = tokens[-1] == EARLY_END[0]\n tokens = tokens[1:-1]\n detokenized = GeneratedSentence.detokenize_sentence(tokens)\n return GeneratedSentence(detokenized, len(tokens), interrupted)\n\n @staticmethod\n def detokenize_sentence(sentence):\n result = \" \".join(sentence)\n result = result[0].upper() + result[1:]\n result = PRE_PUNCT_SPACE_MATCHER.sub(r\"\\1\", result)\n result = POST_PUNCT_SPACE_MATCHER.sub(r\"\\1\", result)\n\n return result\n\n\n def __str__(self):\n return self.detokenized\n\nclass Corpus(object):\n def __init__(self, gram_length=5):\n self.counts = GramNode(None)\n self.gram_length = gram_length\n self.cleaner = Cleaner()\n\n @staticmethod\n def tokenize_sentence(sentence):\n return BEGIN + nltk.word_tokenize(sentence) + END\n\n @staticmethod\n def deduce_phrase_type(tokens):\n if tokens[-2] == \"?\" or tokens[-1] == \"?\": # -1 may be END\n return QUESTION\n if len(tokens) < 15 and FACT_WORDS.intersection(set(map(lambda t: lower(t), tokens))):\n return FACT\n return DECLARATION\n\n def add_document(self, doc):\n sentences = self.cleaner.clean_sentences(sentence_splitter.tokenize(doc))\n\n for s in sentences:\n tokens = self.cleaner.clean_phrase(self.tokenize_sentence(s))\n\n if len(tokens) < 2:\n continue\n self.add_sentence(tokens)\n\n def add_sentence(self, tokens, phrase_type=None):\n if type(tokens) is str:\n tokens = self.tokenize_sentence(tokens)\n phrase_type = phrase_type or self.deduce_phrase_type(tokens)\n\n grams = list(nltk.ngrams(tokens, self.gram_length, pad_right=True, pad_symbol=None))\n for g in grams:\n if None in g:\n g = g[:g.index(None)]\n # we don't need the padding!\n self.counts.get(g).add_occurrence(phrase_type)\n\n def add_sentences(self, sentences, phrase_type=None):\n for s in sentences:\n self.add_sentence(s, phrase_type)\n\n def add_prefixes(self, prefixes, phrase_type):\n for p in prefixes:\n tokens = self.tokenize_sentence(p)[:-1] # remove END token\n self.add_sentence(tokens, phrase_type)\n\n def add_suffixes(self, suffixes, phrase_type):\n for s in suffixes:\n tokens = self.tokenize_sentence(s)[1:] # remove BEGIN token\n self.add_sentence(tokens, phrase_type)\n\n def pick_next_token(self, previous, phrase_type):\n return self.counts.pick_best(previous, phrase_type)\n\n def generate_sentence(self, phrase_type, citation_name=\"Socrates\"):\n words = BEGIN + BEGIN\n while words[-1] != END[0] and words[-1] != EARLY_END[0]:\n # choose number of previous tokens to consider, trending towards more as our sentence grows\n context = self.gram_length - 1 - math.floor(random.random() ** math.log(len(words)) * (self.gram_length - 1))\n token, node = self.pick_next_token(words[-context:], phrase_type)\n words.append(token)\n words = self.replace_citation_special(words, citation_name)\n return GeneratedSentence.for_tokens(words[1:])\n\n def replace_citation_special(self, phrase, name):\n year = random.randrange(1600, 2016)\n while CITATION[0] in phrase:\n at = phrase.index(CITATION[0])\n phrase = phrase[0:at] + [\"(\", name, str(year), \")\"] + phrase[at + 1:]\n return phrase\n\n def word_set(self, node=None):\n node = node or self.counts\n all_words = set(node.children.keys()) - {BEGIN[0], END[0]} # strings only\n\n for child in node.children.values():\n all_words.update(self.word_set(child))\n return all_words\n\n def fix_casing(self):\n all_words = self.word_set()\n\n # if a word only shows up title cased, it is probably a name eg. Socrates\n no_lower = {lower(w) for w in all_words} - {w for w in all_words if islower(w)}\n self.to_lower(self.counts, no_lower)\n\n def to_lower(self, node, exempt):\n for child in node.children.values():\n self.to_lower(child, exempt)\n\n # make a list so that we don't get tripped up while deleting/adding keys\n for key in list(node.children.keys()):\n low_key = lower(key)\n if low_key in exempt or low_key == key:\n continue\n\n node.children[key].merge_into(node.children[low_key])\n del node.children[key]\n\n def show(self):\n self.counts.show(\"\")\n\n\nif __name__ == '__main__':\n corpus = Corpus()\n add_all_conversation(corpus)\n\n for l in fileinput.input():\n corpus.add_document(l)\n\n corpus.counts.delete(\"\\\\\")\n corpus.counts.delete(\"\\\\\\\\\")\n corpus.counts.delete(\"\\\\\")\n corpus.counts.delete(\"\\\\1\")\n\n corpus.fix_casing()\n\n\n for i in range(6):\n print(\"{}: {}\".format(i, corpus.generate_sentence(i % 3).detokenized))\n","sub_path":"phrases.py","file_name":"phrases.py","file_ext":"py","file_size_in_byte":8390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"534057120","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: build\\bdist.win-amd64\\egg\\xicam\\plugins\\EZPluginTest.py\n# Compiled at: 2018-08-27 17:21:07\nimport base\n\ndef runtest():\n import numpy as np\n img = np.random.random((100, 100, 100))\n EZTest.setImage(img)\n hist = np.histogram(img, 100)\n EZTest.plot(hist[1][:-1], hist[0])\n\n\ndef opentest(filepaths):\n import fabio\n for filepath in filepaths:\n img = fabio.open(filepath).data\n EZTest.setImage(img)\n\n\nEZTest = base.EZplugin(name='EZTest', toolbuttons=[\n (\n 'xicam/gui/icons_34.png', runtest)], parameters=[{'name': 'Test', 'value': 10, 'type': 'int'}, {'name': 'Fooo', 'value': True, 'type': 'bool'}], openfileshandler=opentest)","sub_path":"pycfiles/xicam-1.2.26-py2.7/EZPluginTest.py","file_name":"EZPluginTest.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"477015019","text":"#\n# @lc app=leetcode id=99 lang=python3\n#\n# [99] Recover Binary Search Tree\n#\n\n# @lc code=start\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\nfrom typing import Optional\nclass Solution:\n def recoverTree(self, root: Optional[TreeNode]) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n tmp = []\n def _in_order(node):\n if node != None:\n _in_order(node.left)\n tmp.append(node)\n _in_order(node.right)\n\n def _quick_sort(b, e):\n i, j = b, e\n x = tmp[(i + j) // 2]\n while True:\n while tmp[i].val < x.val:\n i += 1\n while tmp[j].val > x.val:\n j -= 1\n if i <= j:\n tmp[i].val, tmp[j].val = tmp[j].val, tmp[i].val\n i += 1\n j -= 1\n if i >= j:\n break\n if i < e:\n _quick_sort(i, e)\n if j > b:\n _quick_sort(b, j)\n \n _in_order(root)\n _quick_sort(0, len(tmp) - 1)\n \n# @lc code=end\n\n","sub_path":"Difficulty/Medium/99.recover-binary-search-tree.py","file_name":"99.recover-binary-search-tree.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"400509198","text":"from flask import Flask, request\nimport random\n\napp = Flask(__name__)\napp.config.update({\n 'SECRET_KEY': 'asdasdasd',\n 'DEBUG': True,\n 'WTF_CSRF_ENABLED': False\n})\n\n\ndef seed_operator():\n global FLASK_SEED\n FLASK_SEED = str('flask_user_') + str(random.randint(1, 1000))\n print(FLASK_SEED)\n\n\ndef create_number(FLASK_SEED):\n random.seed(FLASK_SEED)\n n = random.randint(1, 10)\n print(n)\n return n\n\n\nclass Game():\n def __init__(self, player_guess, FLASK_SEED):\n self.imagine_number = create_number(FLASK_SEED)\n self.player_guess = str(dict(player_guess))\n print(self.player_guess)\n\n\n def iteration(self):\n if int(self.player_guess[-4]) < int(self.imagine_number):\n return '<'\n elif int(self.player_guess[-4]) > int(self.imagine_number):\n return '>'\n else:\n seed_operator()\n return '='\n\n\n@app.route('/', methods=['GET'])\ndef add_user():\n if request.method == 'GET':\n global FLASK_SEED\n seed_operator()\n return b'Choose a number'\n\n\n@app.route('/guess', methods=['POST'])\ndef play_choosing_game():\n if request.method == 'POST':\n answer = Game(request.form, FLASK_SEED)\n return answer.iteration()\n\n\nif __name__ == \"__main__\":\n FLASK_SEED = str()\n app.run()\n","sub_path":"Flask/guessing_game/flask_example.py","file_name":"flask_example.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"193666903","text":"#!/usr/bin/env python3\n# coding=utf-8\n# date 2020-03-11 11:18:22\n# author calllivecn \n\nimport sys\nimport time \nfrom tkinter import Tk \n\ntk = Tk()\n\nx = None\nwhile True:\n t = tk.selection_get(selection=\"CLIPBOARD\")\n if x != t:\n x = t \n print(t)\n\n #with open(\"./tmp.txt\", 'a') as f:\n # timestamp = time.strftime(\"%Y_%m_%d_%H_%M_%S\", time.localtime())\n # f.write(timestamp + '\\n' + x + '\\n\\n')\n time.sleep(1)\n","sub_path":"clipboard--/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"116055290","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# Necessary imports\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport requests\nfrom bs4 import BeautifulSoup\n\n# Part 1\nwith open('hygdata_v3.csv', 'r') as f:\n lines = f.read().split('\\n') # split each line\n\ndata = []\nfor line in lines[1:-1]:\n data.append(line.split(',')) # split each element\n\n# Extract necessary information\nra = [float(data[i][7]) for i in range(len(data))]\ndec = [float(data[i][8]) for i in range(len(data))]\nmag = [float(data[i][13]) for i in range(len(data))]\nspec = [data[i][15] for i in range(len(data))]\nvar = [data[i][-3] for i in range(len(data))]\nvar_min = [data[i][-2] for i in range(len(data))]\nvar_max = [data[i][-1] for i in range(len(data))]\n\n# return list with either zero or proportional to star's incident flux\ndef marker_size(mag, indices):\n# print(len(mag))\n ms = [0] * len(data)\n for i in range(len(mag)):\n if i in indices:\n ms[i] = (10**(-mag[i]/2.5))*1500\n# print(i) # To test speed, turns out this for loop is the cause of latency. There doesn't seem to be a better way.\n# print('xx')\n return ms\n\n# Find indices corresponding to stars belonging to required spectral class.\no_ind, b_ind, f_ind, m_ind = [], [], [], []\nfor i in range(len(spec)):\n if spec[i] == '':\n continue\n elif spec[i][0] == 'O':\n o_ind.append(i)\n elif spec[i][0] == 'B':\n b_ind.append(i)\n elif spec[i][0] == 'F':\n f_ind.append(i)\n elif spec[i][0] == 'M':\n m_ind.append(i)\n# print(len(o_ind), len(b_ind), len(f_ind), len(m_ind))\n\n# Let's plot...\nplt.style.use(['dark_background']) # For dark background\nfig1 = plt.figure(figsize=(20,12))\n\n# projection='mollweide' makes a Molleweide projection\nax1 = fig1.add_subplot(221, projection='mollweide')\nax2 = fig1.add_subplot(222, projection='mollweide')\nax3 = fig1.add_subplot(223, projection='mollweide')\nax4 = fig1.add_subplot(224, projection='mollweide')\n\n# Plots the stars\nax1.scatter(ra, dec, c='white',s=marker_size(mag, o_ind))\nax2.scatter(ra, dec, c='white', s=marker_size(mag, b_ind))\nax3.scatter(ra, dec, c='white',s=marker_size(mag, f_ind))\nax4.scatter(ra, dec, c='white',s=marker_size(mag, m_ind))\n\n# projection='molleweide' overrides the ax.set_label(), so using fig.text()\nfig1.text(0.30, 0.9, 'Spectral class O', ha='center', va='center', size=14)\nfig1.text(0.72, 0.9, 'Spectral class B', ha='center', va='center', size=14)\nfig1.text(0.30, 0.48, 'Spectral class F', ha='center', va='center', size=14)\nfig1.text(0.72, 0.48, 'Spectral class M', ha='center', va='center', size=14)\n\nax1.grid(True)\nax2.grid(True)\nax3.grid(True)\nax4.grid(True)\n\n\n\n# Now, Part 2.\n# Webscraping, scrape the given AstroSat CZTI GRB Archive.\npage = requests.get('http://astrosat.iucaa.in/czti/?q=grb')\nsoup = BeautifulSoup(page.content, 'lxml')\n\ny = soup.find_all('table')[0].find_all('tr')\ns = []\nfor i in range(1,len(y)):\n s.append(y[i].find_all('td')[3].get_text())\n\ngrb_data = []\nfor i in range(len(s)):\n l = (s[i].strip('\\n').strip('\\t').split('\\xa0')) # Data has several \\n, \\t, \\xa0( ).\n s[i] = ''\n for j in range(len(l)):\n s[i] += l[j]\n a = []\n if s[i] != '--, --' and s[i] != '' and s[i] != '--':\n a.append(s[i].split(','))\n a = a[0]\n if len(a) != 2:\n continue\n a[0], a[1] = float(a[0]), float(a[1])\n if a[0] > 180.0:\n a[0] = 180.0 - a[0] # It has ra from (0, 360). But the plot has range (-180, 180)\n grb_data.append(a)\nprint(grb_data)\n\n# Counting the variable stars\nc1, c2, c3, c4 = 0, 0, 0, 0\nfor i in range(len(data)):\n if var[i] != '' and var_max[i] == '':\n c1 += 1;\n elif var[i] == '' and var_max[i] != '':\n c2 += 1;\n elif var[i] != '' and var_max[i] != '':\n c3 += 1;\n elif var[i] == '' and var_max[i] == '':\n c4 += 1\n# print(c1, c2, c3, c4)\n\n# c1, c2, c3 are the stars which show variable magnitude. (Either they have a variable type specified and/or var_min and var_max is given.\n# You can check that either both var_max and var_min are specified or none of them is.\n\n# Getting the indices of variable stars\nindices = []\nfor i in range(len(data)):\n if var[i] == '' and var_max[i] == '':\n continue\n else:\n indices.append(i)\n# len(indices)\n\n# Adding variable stars' location\nra_new = [ra[i] for i in indices]\ndec_new = [dec[i] for i in indices]\n\n# Adding GRBs' location\nfor item in grb_data:\n ra_new.append(item[0]*(np.pi/180))\n dec_new.append(item[1]*(np.pi/180))\n\n# Let's plot, again...\nplt.style.use(['dark_background'])\nfig2 = plt.figure(figsize=(12,8))\n\nax = fig2.add_subplot(111, projection='mollweide')\nax.grid(True)\n\ncolor = ['y']*len(ra_new)\nfor i in range(len(indices), len(ra_new)):\n color[i] = 'b'\n\nax.scatter(ra_new, dec_new, s=7, c=color)\n\n# Get the plots\nplt.show()\n","sub_path":"KSP Assingment 2.py","file_name":"KSP Assingment 2.py","file_ext":"py","file_size_in_byte":4848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138178096","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright 2019 SAP SE or an SAP affiliate company. All rights reserved\n# ============================================================================\n\"\"\" Data Statistics Analysis Generator NZa \"\"\"\n\nimport sys\nsys.path.append('../')\n\nimport warnings\n\nfrom PyPDF2 import PdfFileReader\nfrom datetime import datetime\n\nimport unittest\nfrom xai.compiler import Configuration, Controller\nfrom tests.compiler.util import (\n prepare_template,\n prepare_output_path,\n read_json_source,\n time_in_range,\n remove_temp\n)\n\n\nclass TestDataStatisticsAnalysisNZa(unittest.TestCase):\n \"\"\"\n Test case: Create Report using nza dataset with ONLY Data Analysis (p1)\n - refer to README in sample_input for more info on dataset\n - please update the config to include other feature in p1\n \"\"\"\n\n def setUp(self) -> None:\n warnings.simplefilter(\"ignore\", ResourceWarning)\n \"\"\" Specify Config Files \"\"\"\n self.json = prepare_template(\n filename='data-statistics-analysis_nza.json')\n json_obj = read_json_source(self.json)\n self.json_report_name = json_obj[\"name\"]\n json_writers = json_obj[\"writers\"]\n for writer in json_writers:\n if writer[\"class\"] == \"Pdf\":\n self.json_writer_pdf_name = writer[\"attr\"][\"name\"]\n self.json_writer_pdf_page_number = 8\n\n self.out_path = prepare_output_path(working_path='sample_output')\n\n def tearDown(self) -> None:\n \"\"\" Remove working temp files \"\"\"\n remove_temp()\n\n def test_json_generate_report(self):\n \"\"\" Test report rendering with json config file \"\"\"\n start_time = datetime.now().replace(microsecond=0)\n controller = Controller(config=Configuration(self.json))\n controller.render()\n end_time = datetime.now().replace(microsecond=0)\n\n # -- PDF Report --\n output = \"%s/%s.pdf\" % (self.out_path, self.json_writer_pdf_name)\n print(\"JSON-PDF report generated %s:\" % output)\n\n with open(output, 'rb') as f:\n pdf = PdfFileReader(f)\n info = pdf.getDocumentInfo()\n number_of_pages = pdf.getNumPages()\n\n print(info)\n self.assertEqual(info['/Title'], self.json_report_name)\n\n # print(info['/CreationDate'])\n report_time = datetime.strptime(\n info['/CreationDate'], 'D:%Y%m%d%H%M%S')\n self.assertTrue(time_in_range(start_time, end_time, report_time))\n\n print(number_of_pages)\n self.assertEqual(number_of_pages, self.json_writer_pdf_page_number)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/compiler/test_data_statistics_analysis_nza.py","file_name":"test_data_statistics_analysis_nza.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"320295154","text":"#! /usr/bin/env python\n\nfrom __future__ import division\nfrom __future__ import print_function\n# #from builtins import str # this breaks all sorts of other scripts which test type(x)==str # this breaks all sorts of other scripts which test type(x)==str\nfrom past.utils import old_div\nimport sys\n\nimport os\nimport os.path\nimport argparse\nfrom collections import defaultdict, OrderedDict\n\nimport numpy as np\nimport numpy.random as rand\nimport re\n\nimport pandas as pd\n\nimport pysam\n\nfrom jkutils import *\n\nif __name__ == '__main__':\n \n opts = argparse.ArgumentParser()\n\n opts.add_argument('--mipTableIn', action='append', dest='mipTableIn')\n\n opts.add_argument('--inDesignName', action='append', dest='inDesignName')\n\n opts.add_argument('--mipTableOut', default=None, dest='mipTableOut')\n\n o = opts.parse_args()\n\n \"\"\"\n\n #specify --mipTableIn file --inDesignName name for each design to be concatenated\n\n join_multi_design_tables.py --mipTableIn design1.pairs.txt --inDesignName design1 --mipTableIn design2.pairs.txt --inDesignName design2 [ ... ] --mipTableOut\n\n \"\"\"\n\n idesi=0\n mDesiToOuterCorng={}\n for fn in o.mipTableIn:\n desi=o.inDesignName[idesi]\n mDesiToOuterCorng[desi]=set()\n tblCur = pd.read_csv(fn,sep='\\t')\n for _,r in tblCur.iterrows():\n mDesiToOuterCorng[desi].add( (r.chrom,r.start,r.end) )\n idesi+=1\n\n sOuterAlreadyRecorded=set()\n\n lTables = [ ]\n idesi=0\n idxBase=0\n for fn in o.mipTableIn:\n lTables.append( pd.read_csv(fn,sep='\\t') )\n \n desi=o.inDesignName[idesi]\n\n lDesiMultiNames=[]\n\n for _,r in lTables[-1].iterrows():\n lDesiMultiNames.append('_'.join( [ o.inDesignName[jdesi] for jdesi in range(len(o.inDesignName)) \n if (r.chrom,r.start,r.end) in mDesiToOuterCorng[o.inDesignName[jdesi]] ] ))\n\n lTables[-1]['design']=lDesiMultiNames\n\n lKeepEntry = [ (r.chrom,r.start,r.end) not in sOuterAlreadyRecorded \n for _,r in lTables[-1].iterrows() ]\n\n lTables[-1] = lTables[-1].loc[lKeepEntry]\n\n sOuterAlreadyRecorded = sOuterAlreadyRecorded.union(\n [ (r.chrom,r.start,r.end) for _,r in lTables[-1].iterrows() ] )\n\n lTables[-1]['mip_index']=lTables[-1]['mip_index']+idxBase\n idesi+=1\n idxBase=lTables[-1]['mip_index'].max()+1\n\n mipTblOut=pd.concat(lTables)\n\n mipTblOut.to_csv(o.mipTableOut,sep='\\t',index=False)\n\n\n\n\n\n","sub_path":"mimips/join_multi_design_tables.py","file_name":"join_multi_design_tables.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"586007714","text":"# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nfrom pyiron_atomistics.lammps.interactive import LammpsInteractive\n\n__author__ = \"Joerg Neugebauer, Sudarsan Surendralal, Jan Janssen\"\n__copyright__ = (\n \"Copyright 2021, Max-Planck-Institut für Eisenforschung GmbH - \"\n \"- Computational Materials Design (CM) Department\"\n)\n__version__ = \"1.0\"\n__maintainer__ = \"Sudarsan Surendralal\"\n__email__ = \"surendralal@mpie.de\"\n__status__ = \"production\"\n__date__ = \"Sep 1, 2017\"\n\n\nclass Lammps(LammpsInteractive):\n \"\"\"\n Class to setup and run and analyze LAMMPS simulations.\n\n Example:\n\n >>> job = pr.create.job.Lammps(job_name='lmp_example')\n >>> job.structure = pr.create.structure.bulk('Fe', cubic=True)\n >>> job.run()\n\n How to set potential: Look up potentials via `job.view_potentials()` (detailed data frame)\n or via `job.list_potentials()` (potential names). Assign the potential e.g. via:\n\n >>> job.potential = job.list_potentials()[0]\n\n Lammps has 3 modes: `static`, `md` and `minimize`. Set a mode e.g. via:\n\n >>> job.calc_minimize()\n\n Args:\n project (pyiron_atomistics.project.Project instance): Specifies the project path among other attributes\n job_name (str): Name of the job\n\n Attributes:\n input (lammps.Input instance): Instance which handles the input\n \"\"\"\n\n def __init__(self, project, job_name):\n super(Lammps, self).__init__(project, job_name)\n\n self._executable_activate(enforce=True)\n","sub_path":"pyiron_atomistics/lammps/lammps.py","file_name":"lammps.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"223005665","text":"import numpy as np\nimport scipy, collections\n\nfrom itertools import permutations\nfrom itertools import combinations\n\nyear = 2017\ninput = sorted([int(c) for c in str(year)])\nlargest = int(str(max(input))*len(input))\nsmallest = int(str(min(input))*len(input))\n\ninput_int = sorted([c for c in str(year)])\n\nX = []\nfor i in range(len(input)):\n if i != 0:\n X += [''.join(p) for p in list(permutations(input_int, i+1))]\nX = [int(e) for e in X if int(e) > 0]\nfor i in input:\n for j in range(len(input)+1):\n if i > 0 and j > 0:\n X.append(int(str(i) * j))\n\nS = dict()\nfor i in X:\n for j in X:\n v = i*j\n k = str(i) + '^2 + ' + str(j) + '^2 = ' + str(v)\n raw = collections.Counter(k)\n if raw['7'] >= 8:\n S[k] = v\n\n\n\nS = sorted(S)\n\n\n\n\n\nX_num = sorted([int(e) for e in X])\n\n","sub_path":"brain.py","file_name":"brain.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"316310824","text":"# Create your views here.\nfrom django.shortcuts import redirect, render\n\ndef index(request):\n template_name = 'index.html'\n\n return render(request, template_name, {\"current_page\":\"index\"})\n\ndef portal(request):\n template_dict = {}\n groups = request.user.groups.values_list('name', flat=True)\n if request.user.is_authenticated() and (\"acpc_admin\" in groups):\n template_name = 'index.html'\n template_dict.update({\"current_page\":\"index\",'authenticate':True})\n else:\n template_name = '404.html'\n template_dict.update({\"current_page\":\"404\",'authenticate':False})\n\n return render(request, template_name, template_dict)\n\ndef web(request):\n template_dict = {}\n if request.user.is_authenticated():\n template_name = 'index.html'\n template_dict.update({\"current_page\":\"index\",'authenticate':True})\n else:\n template_name = '404.html'\n template_dict.update({\"current_page\":\"404\",'authenticate':False})\n\n return render(request, template_name, template_dict)","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"376571939","text":"from tensorflow.keras import Model\nfrom tensorflow.keras.layers import Conv2D\n\nclass FeatureMapper(Model):\n def __init__(self):\n super(FeatureMapper, self).__init__()\n self.conv1 = Conv2D(16, kernel_size=(5, 5), strides=(2, 2), activation=\"relu\", padding=\"same\")\n self.conv2 = Conv2D(16, kernel_size=(3, 3), activation=\"relu\", padding=\"same\")\n self.conv3 = Conv2D(16, kernel_size=(3, 3), activation=\"relu\", padding=\"same\")\n\n def call(self, input):\n x = self.conv1(input)\n x = self.conv2(x)\n output = self.conv3(x)\n return output\n","sub_path":"deep_mask/feature_mapper.py","file_name":"feature_mapper.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"450694891","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport sys,os\nsys.path.append(os.path.dirname(__file__) + os.sep + '../')\nfrom FINDER import FINDER\nimport numpy as np\nfrom tqdm import tqdm\nimport time\nimport networkx as nx\nimport pandas as pd\nimport pickle as cp\nimport graph\n\n\ndef GetSolution(STEPRATIO, MODEL_FILE_CKPT):\n ######################################################################################################################\n ##................................................Get Solution (model).....................................................\n dqn = FINDER()\n data_test_path = '../data/real/'\n# data_test_name = ['Crime','HI-II-14','Digg','Enron','Gnutella31','Epinions','Facebook','Youtube','Flickr']\n data_test_name = ['Crime','HI-II-14']\n model_file_path = './FINDER_ND/models/'\n model_file_ckpt = MODEL_FILE_CKPT\n model_file = model_file_path + model_file_ckpt\n ## save_dir\n save_dir = '../results/FINDER_ND/real'\n if not os.path.exists(save_dir):\n os.mkdir(save_dir)\n \n ## begin computing...\n print ('The best model is :%s'%(model_file))\n dqn.LoadModel(model_file)\n df = pd.DataFrame(np.arange(1*len(data_test_name)).reshape((1,len(data_test_name))),index=['time'], columns=data_test_name)\n #################################### modify to choose which stepRatio to get the solution\n stepRatio = STEPRATIO\n\n for j in range(len(data_test_name)):\n print ('\\nTesting dataset %s'%data_test_name[j])\n data_test = data_test_path + data_test_name[j] + '.txt'\n solution, time = dqn.EvaluateRealData(model_file, data_test, save_dir, stepRatio)\n df.iloc[0,j] = time\n print('Data:%s, time:%.2f'%(data_test_name[j], time))\n save_dir_local = save_dir + '/StepRatio_%.4f' % stepRatio\n if not os.path.exists(save_dir_local):\n os.mkdir(save_dir_local)\n df.to_csv(save_dir_local + '/sol_time.csv', encoding='utf-8', index=False)\n\n\ndef EvaluateSolution(STEPRATIO, MODEL_FILE_CKPT, STRTEGYID):\n #######################################################################################################################\n ##................................................Evaluate Solution.....................................................\n dqn = FINDER()\n data_test_path = '../data/real/'\n# data_test_name = ['Crime', 'HI-II-14', 'Digg', 'Enron', 'Gnutella31', 'Epinions', 'Facebook', 'Youtube', 'Flickr']\n data_test_name = ['Crime', 'HI-II-14']\n save_dir = '../results/FINDER_ND/real/StepRatio_%.4f/'%STEPRATIO\n ## begin computing...\n df = pd.DataFrame(np.arange(2 * len(data_test_name)).reshape((2, len(data_test_name))), index=['solution', 'time'], columns=data_test_name)\n for i in range(len(data_test_name)):\n print('\\nEvaluating dataset %s' % data_test_name[i])\n data_test = data_test_path + data_test_name[i] + '.txt'\n solution = save_dir + data_test_name[i] + '.txt'\n t1 = time.time()\n # strategyID: 0:no insert; 1:count; 2:rank; 3:multiply\n ################################## modify to choose which strategy to evaluate\n strategyID = STRTEGYID\n score, MaxCCList = dqn.EvaluateSol(data_test, solution, strategyID, reInsertStep=0.001)\n t2 = time.time()\n df.iloc[0, i] = score\n df.iloc[1, i] = t2 - t1\n result_file = save_dir + '/MaxCCList_Strategy_' + data_test_name[i] + '.txt'\n with open(result_file, 'w') as f_out:\n for j in range(len(MaxCCList)):\n f_out.write('%.8f\\n' % MaxCCList[j])\n print('Data: %s, score:%.6f' % (data_test_name[i], score))\n df.to_csv(save_dir + '/solution_score.csv', encoding='utf-8', index=False)\n\n\ndef main():\n model_file_ckpt = 'nrange_30_50_iter_78000.ckpt'\n GetSolution(0.01, model_file_ckpt)\n EvaluateSolution(0.01, model_file_ckpt, 0)\n\n\n\nif __name__==\"__main__\":\n main()\n","sub_path":"code/FINDER_ND/testReal.py","file_name":"testReal.py","file_ext":"py","file_size_in_byte":3911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"231628479","text":"#!/usr/bin/env python3\n\"\"\"Intellect Macro Script\n\n- Dependencies:\n\n Python\n Selenium\n Browsers\n Associated webdrivers\n\n (Tested with chrome and firefox)\n\n- Requirements:\n\n $ pip install selenium\n\n- Config:\n\n All the configuration is written at the top of this file\n\n- Running:\n\n python automation.py\n\n- Change the loglevel to WARNING after script is working\n\n- If errors occur, screenshots are saved as *.png in the working directory\n\n\"\"\"\n\nimport logging\nimport time\nfrom typing import List\nfrom typing import Optional\nfrom typing import Union\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.chrome.options import Options as CHOptions\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.firefox.options import Options as FFOptions\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom selenium.webdriver.support.select import Select\n\n# loglevel = 'DEBUG'\nloglevel = 'INFO'\n# loglevel = 'WARNING'\n# loglevel = 'ERROR'\n\nbrowser = 'chrome'\nheadless = True\n\nusername = 'admin'\npassword = '1nt3ll3ct'\n\npublish_timeout_minutes = 720\nrestore_timeout_minutes = 10\nretries = 30\ninterval = 2\nimplicit_wait = 2\npage_load_timeout = 120\n\nlogging.basicConfig(level=loglevel)\nlogger = logging.getLogger(__name__)\nlogger.setLevel(loglevel)\n\n\ndef main():\n design_index = -1\n while 1:\n design_index += 1\n site = Site(browser)\n try:\n # Restore publishdesign backup entry\n url = 'https://publishdesign.intellect.com/intellect/admin'\n try:\n restore_backup(site, url, design_index)\n except IndexError:\n msg = f'Design site backup index {design_index} not found! END.'\n logger.info(msg)\n raise IndexError(msg)\n # Restore publishlive backup entry\n url = 'https://publishlive.intellect.com/intellect/admin'\n index = 0\n restore_backup(site, url, index)\n # Publish\n publish(site)\n except IndexError:\n break\n except Exception as e:\n site.screenshot('uncaught-exception')\n logger.exception(f'Uncaught exception: {e}')\n logger.info('Webdriver QUIT')\n site.driver.quit()\n\n\ndef restore_backup(site, url, index):\n logger.info(f\"----- RESTORE index={index} at {url} -----\")\n site.activate_window('main')\n site.login(url)\n # Click Open Backup & Restore Window\n # (there will always be 1 backup however the name will change)\n site.click_backup_and_restore_a_btn()\n site.name_new_window('backup_and_restore', activate=True)\n # Click on Restore Tab and click Next\n site.select_restore_tab()\n # Select the first backup file to restore, and click Next,\n # click Restore (another pop up window will appear)\n site.restore_backup(index)\n # Type password and click OK\n site.name_new_window('password', activate=True)\n site.enter_popup_password()\n # wait five minutes for completion, and verify success\n site.activate_window('backup_and_restore')\n site.wait_for_restore_success(restore_timeout_minutes * 60)\n site.close_window('password')\n site.close_window('backup_and_restore')\n\n\ndef publish(site):\n logger.info(\"----- PUBLISH -----\")\n site.activate_window('main')\n site.login('https://publishdesign.intellect.com/intellect/admin')\n\n # Go to publish Tab\n site.click('#SectionPublishButton')\n # Click on the publish button\n site.switch_to_frame('#PublishSites')\n site.click('#PublishButton_0')\n # Pop up screen will appear, click next\n site.name_new_window('publish', activate=True)\n site.click('#NextButton')\n # Uncheck backup publish site database (it will come as checked)\n site.click('#BackupPublishSite')\n # Click Publish\n site.click('#PublishButton')\n # a popup window will appear asking for password\n site.name_new_window('password', activate=True)\n # Type 1nt3ll3ct as password, then click OK\n # This will initiate the publish process, and system will 'do the rest'.\n site.enter_popup_password()\n time.sleep(0.5)\n site.close_window('password', then_focus='publish')\n\n # Once completed, pop up window will update with green success message.\n # If an error occurs, it will update the window with red error message.\n logger.info(\"Wait for 'Publish' action to complete\")\n _status = ''\n for i in range(publish_timeout_minutes * 60):\n time.sleep(1)\n try:\n site.activate_window(\"publish\", quiet=True)\n site.switch_to_default_content(quiet=True)\n try:\n el = site.find(\"span#lblPublishStatus\")\n except Exception as e:\n site.screenshot('cant-find-lblPublishStatus')\n msg = f\"Can't find span#lblPublishStatus: {e}: ABORT\"\n logger.exception(msg)\n break\n status = el.text\n # Log status\n if status != _status:\n logger.info(status)\n _status = status\n except TimeoutException as e:\n logger.exception(e)\n site.screenshot('chrome-renderer-timeout-exception')\n _status = f\"ignoring chrome renderer timeout\"\n continue\n except Exception as e:\n logger.exception(e)\n continue\n # Error\n if 'Publish site database corrupted' in status:\n site.screenshot('publication-error')\n msg = f'Publication ERROR. ({status})'\n logger.error(msg)\n break\n # Warning\n elif 'Completed with Warnings' in status:\n site.screenshot('publication-warning')\n msg = f'Publication WARNING. ({status})'\n logger.warning(msg)\n break\n # SUCCESS\n elif 'Completed successfully' in status:\n msg = f'Publication Completed. ({status})'\n logger.warning(msg)\n break\n # OOPS\n if 'oops' in status.lower():\n site.screenshot('publication-exception')\n msg = f'Publication UNHANDLED ERROR. ({status})'\n logger.error(msg)\n break\n # \"References Outside Designer Tab.\n elif len(site.driver.window_handles) > len(site.activated):\n site.name_new_window('expected_popup', activate=True)\n site.click('#OKButton')\n site.close_window('expected_popup', then_focus='publish')\n site.switch_to_default_content()\n continue\n else:\n msg = \"Publication TIMEOUT ERROR.\"\n logger.warning(msg)\n\n\nclass Site:\n\n def __init__(self, driver_type: str):\n if driver_type == 'chrome':\n options = CHOptions()\n if headless:\n options.add_argument(\"--headless\")\n options.add_argument(\"start-maximized\")\n options.add_argument(\"enable-automation\")\n options.add_argument(\"--no-sandbox\")\n options.add_argument(\"--disable-infobars\")\n options.add_argument(\"--disable-dev-shm-usage\")\n options.add_argument(\"--disable-browser-side-navigation\")\n options.add_argument(\"--disable-gpu\")\n self.driver = webdriver.Chrome(options=options)\n elif driver_type == 'firefox':\n options = FFOptions()\n options.headless = True\n self.driver = webdriver.Firefox(options=options)\n else:\n self.driver = getattr(webdriver, driver_type).webdriver.WebDriver()\n self.driver.implicitly_wait(implicit_wait)\n self.driver.set_page_load_timeout(page_load_timeout)\n self.activated = {}\n while not self.activated.get('main', None):\n self.activated['main'] = self.driver.current_window_handle\n self.active_window = 'main'\n time.sleep(0.2)\n\n def login(self, login_url):\n logger.info(f\"Login at {login_url} as {username}:{password}\")\n self.driver.get(login_url)\n self.send_keys('#Username', username, clear=True, tab=True)\n self.send_keys('#Password', password, clear=True, tab=True)\n self.click('#Button1')\n\n def screenshot(self, tag):\n n = str(time.time())\n fn = f'{tag}-{n}.png'\n self.driver.get_screenshot_as_file(fn)\n logger.warning(f'Screenshot saved as {fn}')\n return fn\n\n def click_backup_and_restore_a_btn(self):\n logger.info(\"Click Backup & Restore button (a.button)\")\n self.click('a.button')\n\n def name_new_window(self, name, activate=None):\n activate = activate if activate else None\n if name in self.activated:\n msg = f'Window name used twice \"{name}\"'\n raise RuntimeError(msg)\n logger.info(f'Waiting for new window \"{name}\"')\n for i in range(5):\n handles = self.driver.window_handles\n new_wh = [h for h in handles if h not in self.activated.values()]\n if new_wh:\n self.activated[name] = new_wh[0]\n break\n time.sleep(1)\n else:\n msg = f'New window did not appear \"{name}\"'\n raise RuntimeError(msg)\n logger.info(f\"{name}={self.activated[name]}\")\n if activate:\n self.activate_window(name)\n time.sleep(1)\n\n def activate_window(self, name, quiet=False):\n self.switch_to_window(self.activated[name])\n self.active_window = name\n if not quiet:\n logger.info(f'Activated window \"{name}\"')\n\n def close_window(self, name, then_focus=None):\n then_focus = then_focus if then_focus else \"main\"\n try:\n wh = self.activated[name]\n self.switch_to_window(wh)\n self.driver.close()\n except Exception: # noqa\n pass\n finally:\n del (self.activated[name])\n logger.info(f'Closed window {name}')\n self.activate_window(then_focus)\n\n def select_restore_tab(self):\n self.switch_to_frame('[name=\"Header\"]')\n time.sleep(1)\n logger.info('Click link \"RestoreDB\"')\n self.click('a[href^=\"RestoreDB\"]')\n\n time.sleep(1)\n self.switch_to_default_content()\n time.sleep(1)\n self.switch_to_frame('[name=\"Main\"]')\n time.sleep(1)\n logger.info('Click #NextButton')\n self.click('#NextButton')\n self.page_contains_text('select the backup file that you want')\n\n self.switch_to_default_content()\n\n def restore_backup(self, index):\n self.switch_to_frame('[name=\"Main\"]')\n options = self.list_options('select#lstDBBackupFiles')\n option = options[index]\n self.select_option('select#lstDBBackupFiles', option)\n time.sleep(1)\n self.click('#NextButton')\n self.click('#RestoreButton')\n\n def enter_popup_password(self):\n self.send_keys('#Password', password)\n self.click('#OK')\n\n def wait_for_restore_success(self, timeout):\n self.switch_to_frame('[name=\"Main\"]')\n logger.info(\"Wait for restore to complete\")\n try:\n self.switch_to_default_content(quiet=True)\n self.page_contains_text('Completed successfully', timeout, 1)\n logger.info('Restore Completed Successfully')\n except Exception as e:\n msg = f'Restore Failed (\"Completed Successfully\" not found) {e}'\n self.screenshot('restore-failed')\n raise RuntimeError(msg)\n\n def list_options(self, css):\n el = self.find(css)\n options = [o.text for o in el.options]\n optstr = '\",\"'.join(options)\n logger.info(f'{css}: found {len(options)} options: \"{optstr}\"')\n return options\n\n def select_option(self, css, text):\n logger.info(f'selecting \"{text}\" from {css}')\n el = self.find(css)\n el.select_by_visible_text(text)\n\n def switch_to_window(self, window_handle):\n self.driver.switch_to.window(window_handle)\n\n def switch_to_frame(self, selector):\n time.sleep(1)\n self.driver.switch_to.default_content()\n time.sleep(1)\n logger.info(f'Switching to IFRAME with selector {selector}')\n frame = self.find(f'{selector}')\n self.driver.switch_to.frame(frame)\n time.sleep(1)\n\n def switch_to_default_content(self, quiet=False):\n if not quiet:\n logger.info(\"Switch focus to the default frame\")\n self.driver.switch_to.default_content()\n\n def send_keys(self, el_or_css: Union[WebElement, str],\n keys: Union[List, str], clear=True, tab=True,\n expect: Optional[str] = None,\n unexpect: Optional[Union[List[str], str]] = None):\n logger.info(f\"Send keys {keys} to element {el_or_css}\")\n el = self.find(el_or_css) if isinstance(el_or_css, str) else el_or_css\n if not el:\n msg = f\"Can't find element specified by {el_or_css}\"\n raise RuntimeError(msg)\n if isinstance(keys, list):\n for _keys in keys:\n self._send_keys(el, el_or_css, _keys, clear, tab, expect,\n unexpect)\n else:\n self._send_keys(el, el_or_css, keys, clear, tab, expect, unexpect)\n\n def _send_keys(self, el, el_or_css, keys, clear, tab, expect, unexpect):\n if clear:\n el.clear()\n for key in keys:\n el.send_keys(key)\n if tab:\n el.send_keys(Keys.TAB)\n\n if expect and not self.page_contains_text(expect):\n logger.warning(f\"Entered '{keys}' into '{el_or_css}': \"\n f\"expected text not found: '{expect}'\")\n\n if unexpect \\\n and isinstance(unexpect, str) \\\n and self.page_contains_text(unexpect):\n logger.warning(f\"Entered '{keys}' into '{el_or_css}': \"\n f\"unexpected text found: '{unexpect}'\")\n\n if unexpect and isinstance(unexpect, list):\n for un in unexpect:\n if self.page_contains_text(un):\n logger.warning(f\"Entered '{keys}' into '{el_or_css}': \"\n f\"unexpected text found: '{un}'\")\n\n def page_contains_text(self, text, retries=None, interval=None):\n interval = interval if interval else 1\n retries = retries if retries else 10\n for x in range(retries):\n try:\n if text in self.driver.page_source:\n return True\n except WebDriverException:\n pass\n time.sleep(interval)\n\n def click(self, css, retries=None, interval=None):\n logger.info(f'Clicking {css}')\n self.find(css, retries, interval).click()\n\n def find(self, css, retries=None, interval=None):\n interval = interval if interval else 1\n retries = retries if retries else 10\n for x in range(1, retries):\n el = self.driver.find_element_by_css_selector(css)\n if el:\n if el.tag_name == 'select':\n return Select(el)\n return el\n time.sleep(interval)\n return False\n\n def finds(self, css, retries=None, interval=None):\n interval = interval if interval else 1\n retries = retries if retries else 10\n for x in range(1, retries):\n els = self.driver.find_elements_by_css_selector(css)\n if els:\n return els\n time.sleep(interval)\n return []\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"automation.py","file_name":"automation.py","file_ext":"py","file_size_in_byte":15674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"129161164","text":"from rest_framework import viewsets, serializers\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import action\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom ..clinics.models import Clinic\nfrom ..clinics.api import ClinicSerializer\nfrom ..providers.api import Provider\nfrom ..providers.api import ProviderSerializer\nfrom ..accounts.models import PTUser\n\n\nclass AccountViewSet(viewsets.ViewSet):\n @action(detail=False, methods=['get'])\n def whoami(self, request):\n user = request.user\n\n if user.is_authenticated:\n out = {\n 'user': UserSerializer(user).data\n }\n\n if Clinic.objects.filter(owner=user).exists():\n out['clinic'] = ClinicSerializer(user.clinic).data\n elif Provider.objects.filter(owner=user).exists():\n out['provider'] = ProviderSerializer(user.provider).data\n\n return Response(out)\n else:\n return Response({'user': None})\n\n @action(detail=False, methods=['post'])\n def register(self, request):\n if PTUser.objects.filter(email=request.data['email']).exists():\n return Response({'success': False, 'error': 'This email address is already in use.'}, 400)\n\n user = PTUser.objects.create(\n email=request.data['email'],\n username=request.data['email'],\n first_name=request.data['first_name'],\n last_name=request.data['last_name'],\n city=request.data['city'],\n state=request.data['state']\n )\n\n user.set_password(request.data['password'])\n user.save()\n\n user = authenticate(request, username=request.data['email'], password=request.data['password'])\n login(request, user)\n \n return Response({'success': True, 'user': UserSerializer(user).data})\n\n @action(detail=False, methods=['post'])\n def create_clinic(self, request):\n if request.user == None:\n return Response({'success': False}, 403)\n\n serializer = ClinicSerializer(data=request.data)\n if not serializer.is_valid():\n return Response({'success': False, 'errors': serializer.errors})\n \n clinic = serializer.create(request.user, serializer.validated_data)\n\n return Response({'success': True, 'clinic': ClinicSerializer(clinic).data})\n\n @action(detail=False, methods=['post'])\n def create_provider(self, request):\n if request.user == None:\n return Response({'success': False}, 403)\n\n serializer = ProviderSerializer(data=request.data)\n if not serializer.is_valid():\n return Response({'success': False, 'errors': serializer.errors})\n \n provider = serializer.create(request.user, serializer.validated_data)\n\n return Response({'success': True, 'provider': ProviderSerializer(provider).data})\n\n @action(detail=False, methods=['get', 'post'])\n def logout(self, request):\n logout(request)\n return Response(\"Goodbye\")\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = PTUser\n fields = ('id', 'email', 'first_name', 'last_name')","sub_path":"ptshyft/accounts/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"548680584","text":"from process.logging import Logger as log\nfrom process.globals import config\nfrom database import db\n\nclass ReviewQueue(object):\n cached_tagging = True\n cached_tags = {}\n\n @staticmethod\n def addMatch(job_id, oldId, newId, action, match):\n #log.info(\"Found a match: {old} -> {new} : {match}\".format(old=oldId, new=newId, match=match))\n db.get_db(config.drupal_schema).execute(\"\"\"\n INSERT INTO donor_review_queue\n SET\n job_id = %(job_id)s,\n old_id = %(old_id)s,\n new_id = %(new_id)s,\n action_id = %(action_id)s,\n match_description = %(match)s\n \"\"\", {\n 'job_id': job_id,\n 'old_id': oldId,\n 'new_id': newId,\n 'action_id': action.id,\n 'match': match,\n })\n\n @staticmethod\n def tag(contact_id, tag):\n if ReviewQueue.cached_tagging:\n if tag not in ReviewQueue.cached_tags:\n ReviewQueue.cached_tags[tag] = []\n\n ReviewQueue.cached_tags[tag].append(contact_id)\n else:\n ReviewQueue.tag_single(contact_id, tag)\n\n @staticmethod\n def commit():\n log.info(\"Committing tags...\")\n for tag, contacts in ReviewQueue.cached_tags.items():\n log.info(\"Bulk tagging {num} contacts with tag <{tag}>\".format(num=len(contacts), tag=tag.name))\n ReviewQueue.tag_many(contacts, tag)\n\n @staticmethod\n def tag_many(contacts, tag):\n sets = [ \"('civicrm_contact', {contact_id}, {tag_id})\".format(contact_id=contact_id, tag_id=tag.id)\n for contact_id in contacts ]\n values = \", \".join(sets)\n\n db.get_db(config.civicrm_schema).execute(\"\"\"\n INSERT IGNORE INTO civicrm_entity_tag\n (entity_table, entity_id, tag_id)\n VALUES\n %s\n \"\"\" % values)\n\n @staticmethod\n def tag_single(contact_id, tag):\n db.get_db(config.civicrm_schema).execute(\"\"\"\n INSERT IGNORE INTO civicrm_entity_tag\n SET\n entity_table = 'civicrm_contact',\n entity_id = %(contact_id)s,\n tag_id = %(tag_id)s\n \"\"\", {\n 'contact_id': contact_id,\n 'tag_id': tag.id,\n })\n","sub_path":"dedupe/review_queue.py","file_name":"review_queue.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"644368750","text":"from layer import Layer\nfrom regparser.tree.struct import Node\n\n\nclass ParagraphMarkers(Layer):\n\n def process(self, node):\n \"\"\"Look for any leading paragraph markers.\"\"\"\n marker = ParagraphMarkers.marker(node)\n if node.text.strip().startswith(marker):\n return [{\n \"text\": marker,\n \"locations\": [0]\n }]\n\n @staticmethod\n def marker(node):\n m = [l for l in node.label if l != Node.INTERP_MARK][-1]\n\n if 'Interpretations' in node.label or 'Interp' in node.label:\n m = m + '.'\n else:\n m = '(%s)' % m\n return m\n","sub_path":"regparser/layer/paragraph_markers.py","file_name":"paragraph_markers.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"129514067","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport codecs\nimport collections\nimport hashlib\nimport json\nimport urllib2\n\n\n# 文件夹ID,调用api获取\n# https://grafana.com/docs/http_api/folder/#get-all-folders\ng_grafanaFolderId = 0\n# 一级业务\ng_dashboardBusiL1 = \"\"\n# 二级业务\ng_dashboardBusiL2 = \"\"\n# 模块\ng_dashboardModule = \"\"\n# 属性描述列表\ng_attrList = []\n# 输入文件的绝对路径文件夹,生成的文件都保存到该目录下\ng_dirname = \"\"\n# 用于生成go文件的文件名称\ng_filename = \"\"\n# 模块英文名,用于生成attr.go\ng_dashboardModuleEn = \"\"\n\n\ndef AttentionStr(str, color):\n if color == \"green\":\n return \"\\033[1;32m%s\\033[0m\" % str\n elif color == \"red\":\n return \"\\033[1;31m%s\\033[0m\" % str\n\n\ndef ParseAttrFile(filePath):\n global g_dashboardBusiL1\n global g_dashboardBusiL2\n global g_dashboardModule\n global g_attrList\n global g_dirname\n global g_filename\n global g_dashboardModuleEn\n\n # 检查文件格式是否正确,\n if not os.path.isfile(filePath):\n return False\n realpath = os.path.realpath(filePath)\n g_dirname = os.path.dirname(realpath)\n g_filename = os.path.basename(realpath)\n fd = codecs.open(filePath, mode=\"r\", encoding=\"utf-8\")\n lineNo = 0\n validNo = 0\n pickBusi = False\n hasModuleName = False\n for line in fd:\n lineNo += 1\n if line.startswith(\"#\") or line == \"\\r\\n\" or line == \"\\n\":\n continue\n validNo += 1\n if validNo == 1:\n # 如果第一行就是属性,g_dashboardModuleEn取值为\"attr\"\n # 如果第一行是模块名,g_dashboardModuleEn取值为模块名\n cols = line.split(\",\")\n if len(cols) != 10:\n hasModuleName = True\n g_dashboardModuleEn = line.strip(\"\\r\\n\").strip(\"\\n\")\n continue\n else:\n g_dashboardModuleEn = \"attr\"\n pass\n\n cols = line.split(\",\")\n if len(cols) != 10:\n print(AttentionStr(('line:%d error, missing coloum or \",\" incorrect' % lineNo), \"red\"))\n fd.close()\n return False\n\n if pickBusi == False:\n pickBusi = True\n g_dashboardBusiL1 = cols[2]\n g_dashboardBusiL2 = cols[3]\n g_dashboardModule = cols[4]\n else:\n if cols[2] != g_dashboardBusiL1 or cols[3] != g_dashboardBusiL2 or cols[4] != g_dashboardModule:\n print(AttentionStr(('line:%d error, business or module different' % lineNo), \"red\"))\n fd.close()\n return False\n\n if int(cols[0]) == 0:\n print(AttentionStr(\"id is 0 invalid\", \"red\"))\n fd.close()\n return False\n fd.close()\n\n # 文件格式正确,获取相关值\n fd = codecs.open(filePath, mode=\"r\", encoding=\"utf-8\")\n validNo = 0\n for line in fd:\n if line.startswith(\"#\") or line == \"\\r\\n\" or line == \"\\n\":\n continue\n validNo += 1\n if validNo == 1 and hasModuleName == True:\n continue\n cols = line.split(\",\")\n attr = collections.OrderedDict()\n g_attrList.append(attr)\n attr[\"id\"] = int(cols[0])\n attr[\"type\"] = cols[1]\n attr[\"name\"] = cols[5]\n attr[\"macro\"] = cols[6]\n attr[\"min\"] = int(cols[7])\n attr[\"max\"] = int(cols[8])\n attr[\"owner\"] = cols[9]\n fd.close()\n return True\n\n\ndef GenGoFile(dirname, filename, dashboardModuleEn, attrList):\n tmp = filename.replace(\".desc\", \"\")\n gofile = \"%s/%s.go\" % (dirname, tmp)\n fd = codecs.open(gofile, mode=\"w\", encoding=\"utf-8\")\n fd.write(\"// This file is automatically generated by %s\\n\\n\" % sys.argv[0])\n fd.write(\"package %s\\n\\n\" % dashboardModuleEn)\n fd.write(\"const (\\n\")\n for i in range(len(attrList)):\n attr = attrList[i]\n fd.write(\"\\t%s = %d\\n\" % (attr[\"macro\"], attr[\"id\"]))\n fd.write(\")\\n\")\n fd.close()\n print(\"Generate %s ... %s\" % (gofile, AttentionStr(\"success\", \"green\")))\n\n\ndef GetGrafanaConfig(grafanaHost, grafanaAuthorization, uid):\n destUrl = \"http://%s/api/dashboards/uid/%s\" % (grafanaHost, uid)\n req = urllib2.Request(url=destUrl)\n req.add_header('Accept', 'application/json')\n req.add_header('Content-Type', 'application/json')\n req.add_header('Authorization', grafanaAuthorization)\n try:\n rsp = urllib2.urlopen(req)\n except Exception as e:\n return {}\n else:\n body = rsp.read()\n v = json.loads(body)\n return v\n\n\ndef GenGrafanaConfig(grafanaHost, grafanaAuthorization, grafanaDataSource, grafanaFolderId, dashboardBusiL1, dashboardBusiL2, dashboardModule, dirname, filename, attrList):\n title = \"%s-%s-%s\" % (dashboardBusiL1, dashboardBusiL2, dashboardModule)\n md5 = hashlib.md5()\n md5.update(title)\n uid = md5.hexdigest()[8:-8]\n oridb = GetGrafanaConfig(grafanaHost, grafanaAuthorization, uid)\n\n # gen\n view = collections.OrderedDict()\n view[\"folderId\"] = grafanaFolderId\n view[\"overwrite\"] = True\n view[\"message\"] = \"commit by tools\"\n\n dashboard = collections.OrderedDict()\n view[\"dashboard\"] = dashboard\n\n dashboard[\"title\"] = title\n dashboard[\"uid\"] = uid\n dashboard[\"id\"] = None\n dashboard[\"gnetId\"] = None\n dashboard[\"editable\"] = True\n dashboard[\"graphTooltip\"] = 0\n dashboard[\"timezone\"] = \"browser\"\n dashboard[\"version\"] = 0\n dashboard[\"iteration\"] = 0\n dashboard[\"refresh\"] = False\n dashboard[\"schemaVersion\"] = 16\n dashboard[\"style\"] = \"dark\"\n\n dashboard_tags_list = []\n dashboard[\"tags\"] = dashboard_tags_list\n dashboardTag = \"%s-%s\" % (dashboardBusiL1, dashboardBusiL2)\n dashboard_tags_list.append(dashboardTag)\n\n dashboard_links_list = []\n dashboard[\"links\"] = dashboard_links_list\n\n dashboard[\"description\"] = \"\"\n\n dashboard_annotations = collections.OrderedDict()\n dashboard[\"annotations\"] = dashboard_annotations\n dashboard_annotations_list = []\n dashboard_annotations[\"list\"] = dashboard_annotations_list\n\n dashboard_annotations_list.append(collections.OrderedDict())\n dashboard_annotations_list[0][\"builtIn\"] = 1\n dashboard_annotations_list[0][\"datasource\"] = \"-- Grafana --\"\n dashboard_annotations_list[0][\"enable\"] = True\n dashboard_annotations_list[0][\"hide\"] = True\n dashboard_annotations_list[0][\"iconColor\"] = \"rgba(0, 211, 255, 1)\"\n dashboard_annotations_list[0][\"name\"] = \"Annotations & Alerts\"\n dashboard_annotations_list[0][\"type\"] = \"dashboard\"\n\n dashboard_templating = collections.OrderedDict()\n dashboard[\"templating\"] = dashboard_templating\n dashboard_templating_list = []\n dashboard_templating[\"list\"] = dashboard_templating_list\n\n templating_host_use_old = False\n if \"dashboard\" in oridb:\n if \"templating\" in oridb[\"dashboard\"]:\n if \"list\" in oridb[\"dashboard\"][\"templating\"]:\n for i in range(len(oridb[\"dashboard\"][\"templating\"][\"list\"])):\n if \"name\" in oridb[\"dashboard\"][\"templating\"][\"list\"][i]:\n if oridb[\"dashboard\"][\"templating\"][\"list\"][i][\"name\"] == \"host\":\n templating_host_use_old = True\n dashboard_templating_list.append(oridb[\"dashboard\"][\"templating\"][\"list\"][i])\n\n if templating_host_use_old == False:\n dashboard_templating_list.append(collections.OrderedDict())\n dashboard_templating_list[0][\"name\"] = \"host\"\n dashboard_templating_list[0][\"label\"] = \"服务器\"\n dashboard_templating_list[0][\"allValue\"] = \".+\"\n dashboard_templating_list_current = collections.OrderedDict()\n dashboard_templating_list[0][\"current\"] = dashboard_templating_list_current\n dashboard_templating_list_current[\"text\"] = \"All\"\n dashboard_templating_list_current[\"value\"] = [\"$__all\"]\n dashboard_templating_list[0][\"datasource\"] = grafanaDataSource\n dashboard_templating_list[0][\"hide\"] = 0\n dashboard_templating_list[0][\"includeAll\"] = True\n dashboard_templating_list[0][\"multi\"] = True\n dashboard_templating_list[0][\"options\"] = []\n dashboard_templating_list[0][\"query\"] = \"label_values(monitor_0_value, host)\"\n dashboard_templating_list[0][\"refresh\"] = 1\n dashboard_templating_list[0][\"regex\"] = \"\"\n dashboard_templating_list[0][\"sort\"] = 1\n dashboard_templating_list[0][\"tagValuesQuery\"] = \"\"\n dashboard_templating_list[0][\"tags\"] = []\n dashboard_templating_list[0][\"tagsQuery\"] = \"\"\n dashboard_templating_list[0][\"type\"] = \"query\"\n dashboard_templating_list[0][\"useTags\"] = False\n\n dashboard_templating_list.append(collections.OrderedDict())\n dashboard_templating_list[1][\"auto\"] = False\n dashboard_templating_list[1][\"auto_count\"] = 300\n dashboard_templating_list[1][\"auto_min\"] = \"5m\"\n dashboard_templating_list[1][\"current\"] = {\"text\":\"1m\", \"value\":\"1m\"}\n dashboard_templating_list[1][\"hide\"] = 0\n dashboard_templating_list[1][\"label\"] = \"数据粒度\"\n dashboard_templating_list[1][\"name\"] = \"interval\"\n dashboard_templating_list_interval_options_list = []\n dashboard_templating_list[1][\"options\"] = dashboard_templating_list_interval_options_list\n dashboard_templating_list_interval_options_list.append(collections.OrderedDict())\n dashboard_templating_list_interval_options_list[0][\"text\"] = \"1m\"\n dashboard_templating_list_interval_options_list[0][\"value\"] = \"1m\"\n dashboard_templating_list_interval_options_list[0][\"selected\"] = True\n dashboard_templating_list_interval_options_list.append(collections.OrderedDict())\n dashboard_templating_list_interval_options_list[1][\"text\"] = \"5m\"\n dashboard_templating_list_interval_options_list[1][\"value\"] = \"5m\"\n dashboard_templating_list_interval_options_list[1][\"selected\"] = False\n dashboard_templating_list_interval_options_list.append(collections.OrderedDict())\n dashboard_templating_list_interval_options_list[2][\"text\"] = \"10m\"\n dashboard_templating_list_interval_options_list[2][\"value\"] = \"10m\"\n dashboard_templating_list_interval_options_list[2][\"selected\"] = False\n dashboard_templating_list_interval_options_list.append(collections.OrderedDict())\n dashboard_templating_list_interval_options_list[3][\"text\"] = \"1h\"\n dashboard_templating_list_interval_options_list[3][\"value\"] = \"1h\"\n dashboard_templating_list_interval_options_list[3][\"selected\"] = False\n dashboard_templating_list_interval_options_list.append(collections.OrderedDict())\n dashboard_templating_list_interval_options_list[4][\"text\"] = \"1d\"\n dashboard_templating_list_interval_options_list[4][\"value\"] = \"1d\"\n dashboard_templating_list_interval_options_list[4][\"selected\"] = False\n dashboard_templating_list[1][\"query\"] = \"1m,5m,10m,1h,1d\"\n dashboard_templating_list[1][\"refresh\"] = 2\n dashboard_templating_list[1][\"type\"] = \"interval\"\n\n dashboard[\"time\"] = {\"from\":\"now/d\", \"to\":\"now/d\"}\n dashboard[\"timepicker\"] = {\"hidden\":False, \"nowDelay\":\"1m\", \"refresh_intervals\":[\"5s\",\"10s\",\"30s\",\"1m\",\"5m\",\"15m\",\"30m\",\"1h\",\"2h\",\"1d\"], \"time_options\":[\"5m\",\"15m\",\"1h\",\"6h\",\"12h\",\"24h\",\"2d\",\"7d\",\"30d\"]}\n\n panels = []\n dashboard[\"panels\"] = panels\n\n panel1 = collections.OrderedDict()\n panels.append(panel1)\n panel1[\"title\"] = \"视图列表链接\"\n panel1[\"type\"] = \"dashlist\"\n panel1[\"id\"] = 1\n panel1_pos = collections.OrderedDict()\n panel1[\"gridPos\"] = panel1_pos\n panel1_pos[\"h\"] = 10\n panel1_pos[\"w\"] = 12\n panel1_pos[\"x\"] = 0\n panel1_pos[\"y\"] = 0\n panel1[\"folderId\"] = grafanaFolderId\n panel1[\"headings\"] = False\n panel1[\"recent\"] = False\n panel1[\"search\"] = True\n panel1[\"starred\"] = False\n panel1[\"limit\"] = 100\n panel1[\"query\"] = \"\"\n panel1[\"links\"] = []\n panel1[\"tags\"] = [dashboardTag]\n\n panel2 = collections.OrderedDict()\n panels.append(panel2)\n panel2[\"title\"] = \"本视图告警列表\"\n panel2[\"type\"] = \"alertlist\"\n panel2[\"id\"] = 2\n panel2_pos = collections.OrderedDict()\n panel2[\"gridPos\"] = panel2_pos\n panel2_pos[\"h\"] = 10\n panel2_pos[\"w\"] = 12\n panel2_pos[\"x\"] = 12\n panel2_pos[\"y\"] = 0\n panel2[\"limit\"] = 100\n panel2[\"links\"] = []\n panel2[\"onlyAlertsOnDashboard\"] = True\n panel2[\"show\"] = \"current\"\n panel2[\"sortOrder\"] = 1\n panel2[\"stateFilter\"] = []\n\n for i in range(len(attrList)):\n attr = attrList[i]\n\n panel = collections.OrderedDict()\n panels.append(panel)\n panel[\"title\"] = \"%d %s / every $interval\" % (attr[\"id\"], attr[\"name\"])\n panel[\"type\"] = \"graph\"\n panel[\"id\"] = 2 + (i + 1)\n panel[\"description\"] = attr[\"macro\"]\n panel[\"datasource\"] = None\n panel[\"interval\"] = \"1m\"\n\n x = (i % 3) * 8\n y = (i / 3) * 8 + 10\n panel_pos = collections.OrderedDict()\n panel[\"gridPos\"] = panel_pos\n panel_pos[\"h\"] = 8\n panel_pos[\"w\"] = 8\n panel_pos[\"x\"] = x\n panel_pos[\"y\"] = y\n\n panel_targets = []\n panel[\"targets\"] = panel_targets\n panel_target_A = collections.OrderedDict()\n panel_target_B = collections.OrderedDict()\n panel_targets.append(panel_target_A)\n panel_targets.append(panel_target_B)\n panel_target_A[\"refId\"] = \"A\"\n panel_target_B[\"refId\"] = \"B\"\n target_expr_A = \"\"\n target_expr_B = \"\"\n target_legend_format = \"\"\n if attr[\"type\"] == \"L\":\n target_expr_A = 'sum(delta(monitor_%d_total{host=~\"$host\"}[$interval]))' % (attr[\"id\"])\n target_expr_B = 'sum(delta(monitor_%d_total{host=~\".+\"}[1m]))' % (attr[\"id\"])\n target_legend_format = \"\"\n elif attr[\"type\"] == \"S\":\n target_expr_A = 'monitor_%d_value{host=~\"$host\"}' % (attr[\"id\"])\n target_expr_B = 'monitor_%d_value{host=~\".+\"}' % (attr[\"id\"])\n target_legend_format = \"{{host}}\"\n panel_target_A[\"expr\"] = target_expr_A\n panel_target_B[\"expr\"] = target_expr_B\n panel_target_A[\"format\"] = \"time_series\"\n panel_target_B[\"format\"] = \"time_series\"\n panel_target_A[\"hide\"] = False\n panel_target_B[\"hide\"] = True\n panel_target_A[\"instant\"] = False\n panel_target_B[\"instant\"] = False\n panel_target_A[\"interval\"] = \"$interval\"\n panel_target_B[\"interval\"] = \"1m\"\n panel_target_A[\"intervalFactor\"] = 1\n panel_target_B[\"intervalFactor\"] = 1\n panel_target_A[\"legendFormat\"] = target_legend_format\n panel_target_B[\"legendFormat\"] = target_legend_format\n\n panel_legend = collections.OrderedDict()\n panel[\"legend\"] = panel_legend\n panel_legend[\"alignAsTable\"] = False\n panel_legend[\"avg\"] = False\n panel_legend[\"current\"] = True\n panel_legend[\"hideEmpty\"] = False\n panel_legend[\"hideZero\"] = False\n panel_legend[\"max\"] = True\n panel_legend[\"min\"] = True\n panel_legend[\"rightSide\"] = False\n panel_legend[\"show\"] = True\n panel_legend[\"total\"] = True\n panel_legend[\"values\"] = True\n\n panel[\"aliasColors\"] = {\"{}\":\"#447ebc\"}\n panel[\"bars\"] = False\n panel[\"dashLength\"] = 10\n panel[\"dashes\"] = False\n panel[\"lines\"] = True\n panel[\"linewidth\"] = 2\n panel[\"links\"] = []\n panel[\"nullPointMode\"] = \"null\"\n panel[\"percentage\"] = False\n panel[\"pointradius\"] = 5\n panel[\"points\"] = False\n panel[\"renderer\"] = \"flot\"\n panel[\"seriesOverrides\"] = []\n panel[\"spaceLength\"] = 10\n panel[\"stack\"] = False\n panel[\"steppedLine\"] = False\n panel[\"fill\"] = 1\n panel[\"transparent\"] = False\n panel[\"timeFrom\"] = None\n panel[\"timeShift\"] = None\n panel[\"tooltip\"] = {\"shared\":True, \"sort\":0, \"value_type\":\"individual\"}\n\n panel[\"xaxis\"] = {\"buckets\":None, \"mode\":\"time\", \"name\":None, \"show\":True, \"values\":[]}\n panel[\"yaxes\"] = [\n {\"format\":\"none\", \"label\":None, \"logBase\":1, \"max\":None, \"min\":\"0\", \"decimals\": 0, \"show\":True},\n {\"format\":\"none\", \"label\":None, \"logBase\":1, \"max\":None, \"min\":None, \"decimals\": 0, \"show\":False}\n ]\n\n # 注意:阈值线只支持第一个conditions的值,这里取max\n if attr[\"max\"] == 0:\n panel[\"thresholds\"] = []\n else:\n panel[\"thresholds\"] = [\n {\"colorMode\": \"critical\", \"fill\": True, \"line\": True, \"op\": \"gt\", \"value\": attr[\"max\"]}\n ]\n\n if attr[\"min\"] != 0 or attr[\"max\"] != 0:\n if attr[\"min\"] < attr[\"max\"] or attr[\"max\"] == 0:\n alert = collections.OrderedDict()\n panel[\"alert\"] = alert\n\n # 第一个判断的optype为\"and\"\n op_type_first_flag = True\n conditions = []\n alert[\"conditions\"] = conditions\n if attr[\"max\"] != 0:\n op_type_first_flag = False\n condition_max = collections.OrderedDict()\n conditions.append(condition_max)\n condition_max[\"evaluator\"] = {\"params\":[attr[\"max\"]], \"type\":\"gt\"}\n condition_max[\"operator\"] = {\"type\": \"and\"}\n condition_max[\"query\"] = {\"params\":[\"B\", \"5m\", \"now-2m\"]}\n condition_max[\"reducer\"] = {\"params\":[], \"type\":\"max\"}\n condition_max[\"type\"] = \"query\"\n if attr[\"min\"] != 0:\n condition_min = collections.OrderedDict()\n conditions.append(condition_min)\n condition_min[\"evaluator\"] = {\"params\":[attr[\"min\"]], \"type\":\"lt\"}\n if op_type_first_flag:\n condition_min[\"operator\"] = {\"type\":\"and\"}\n else:\n condition_min[\"operator\"] = {\"type\":\"or\"}\n condition_min[\"query\"] = {\"params\":[\"B\", \"5m\", \"now-2m\"]}\n condition_min[\"reducer\"] = {\"params\":[], \"type\":\"min\"}\n condition_min[\"type\"] = \"query\"\n\n alert[\"executionErrorState\"] = \"keep_state\"\n alert[\"frequency\"] = \"60s\"\n alert[\"handler\"] = 1\n alert[\"message\"] = attr[\"owner\"]\n\n minstr = str(attr[\"min\"])\n maxstr = str(attr[\"max\"])\n brackets = \"]\"\n if attr[\"max\"] == 0:\n maxstr = \"+inf\"\n brackets = \")\"\n if attr[\"type\"] == \"L\":\n alert[\"name\"] = \"%s %d %s 1分钟量正常范围[%s,%s%s\" % (dashboard[\"title\"], attr[\"id\"], attr[\"name\"], minstr, maxstr, brackets)\n elif attr[\"type\"] == \"S\":\n alert[\"name\"] = \"%s %d %s 瞬时值正常范围[%s,%s%s\" % (dashboard[\"title\"], attr[\"id\"], attr[\"name\"], minstr, maxstr, brackets)\n alert[\"noDataState\"] = \"ok\"\n alert[\"notifications\"] = [{\"id\":1}]\n\n body = json.dumps(view, ensure_ascii=False, indent=2)\n tmp = filename.replace(\".desc\", \"\")\n grafanafile = \"%s/%s.dashboard\" % (dirname, tmp)\n fd = codecs.open(grafanafile, mode=\"w\", encoding=\"utf-8\")\n fd.write(body)\n fd.close()\n print(\"Generate %s ... %s\" % (grafanafile, AttentionStr(\"success\", \"green\")))\n return grafanafile\n\n\ndef UpdateGrafanaConfig(grafanaHost, grafanaAuthorization, filename):\n f = open(filename)\n data2send = f.read()\n destUrl = \"http://%s/api/dashboards/db\" % grafanaHost\n req = urllib2.Request(url=destUrl, data=data2send)\n req.add_header('Accept', 'application/json')\n req.add_header('Content-Type', 'application/json')\n req.add_header('Authorization', grafanaAuthorization)\n rsp = urllib2.urlopen(req)\n result = rsp.read()\n v = json.loads(result)\n if v.has_key(\"status\") and v[\"status\"] == \"success\":\n print(\"Update %s to Grafana:%s ... %s\" % (filename, grafanaHost, AttentionStr(\"success\", \"green\")))\n id = 0\n uid = \"\"\n ver = 0\n if v.has_key(\"id\"):\n id = v[\"id\"]\n if v.has_key(\"uid\"):\n uid = v[\"uid\"]\n if v.has_key(\"version\"):\n ver = v[\"version\"]\n print(\" id : %d\" % id)\n print(\" uid : %s\" % uid)\n print(\" version : %d\" % ver)\n else:\n print(\"Update %s to Grafana:%s ... %s\" % (filename, grafanaHost, AttentionStr(\"failed\", \"red\")))\n print(\" Result: %s\" % result)\n f.close()\n\n\nif __name__ == \"__main__\":\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n\n configFileName = sys.argv[0].replace(\".py\", \".json\")\n fd = codecs.open(configFileName, mode=\"r\", encoding=\"utf-8\")\n configStr = fd.read()\n configDict = json.loads(configStr)\n\n if len(sys.argv) == 2 or len(sys.argv) == 3:\n filePath = sys.argv[1]\n if len(sys.argv) == 3:\n g_grafanaFolderId = int(sys.argv[2])\n else:\n print(\"failed\")\n print(\"Usage: python %s file [grafanaFolderId(default=0)]\" % (sys.argv[0]))\n print(\" e.g.: python %s ./model01/attr.desc 1\" % (sys.argv[0]))\n print(\" e.g.: python %s ./model02/attr.desc 2\" % (sys.argv[0]))\n sys.exit()\n\n rc = ParseAttrFile(filePath)\n if rc != True:\n print(\"Parse %s failed\" % (sys.argv[1]))\n sys.exit()\n\n # business\n GenGoFile(g_dirname, g_filename, g_dashboardModuleEn, g_attrList)\n for host in configDict[\"GrafanaHostList\"]:\n filename = GenGrafanaConfig(host, configDict[\"GrafanaAuthorization\"], configDict[\"GrafanaDataSource\"], g_grafanaFolderId, g_dashboardBusiL1, g_dashboardBusiL2, g_dashboardModule, g_dirname, g_filename, g_attrList)\n UpdateGrafanaConfig(host, configDict[\"GrafanaAuthorization\"], filename)\n","sub_path":"dashboard/gen_dashboard.py","file_name":"gen_dashboard.py","file_ext":"py","file_size_in_byte":21855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"275051991","text":"from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nimport pandas as pd \nimport nltk\nfrom sklearn.naive_bayes import MultinomialNB, GaussianNB\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.model_selection import train_test_split\nimport webbrowser as rowreader\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk import word_tokenize\nfrom sklearn.metrics import classification_report, accuracy_score\nimport numpy as np\nfrom sklearn.preprocessing import FunctionTransformer\n\nclass LemmaTokenizer(object):\n def __init__(self):\n self.wnl = WordNetLemmatizer()\n def __call__(self, articles):\n return [self.wnl.lemmatize(t) for t in word_tokenize(articles)]\n\ndef create_pipeline(estimator):\n steps = [\n ('vectorizer', CountVectorizer(tokenizer= LemmaTokenizer(),\n stop_words='english',\n ngram_range=(2,2),\n lowercase=True)),\n ('transformer', FunctionTransformer(lambda x: x.todense(), accept_sparse=True))\n ]\n\n steps.append(('classifier', estimator))\n return Pipeline(steps)\n\nnltk.download(\"stopwords\")\nfile = \"movie_review.csv\"\ncol_list = ['text', 'tag', 'datz']\n\nread = pd.read_csv(file, sep=',', usecols=col_list)\n\nX = read['text']\ny = read['tag']\nz = read['datz']\n\nif z is not np.NaN:\n rowreader.open(z[0])\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=632)\n\nmodels = []\nmodels.append(create_pipeline(GaussianNB()))\nmodels.append(create_pipeline(MultinomialNB()))\n\nfor model in models:\n model.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n print(classification_report(y_test, y_pred))\n\n\n\n\n","sub_path":"movie-reviews.py","file_name":"movie-reviews.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"133544025","text":"# -*- coding: utf-8 -*-\n\nimport threading\nimport queue as q\nimport time\nimport nwae.utils.Log as lg\nfrom inspect import getframeinfo, currentframe\nimport nwae.utils.StringUtils as su\n\n\n#\n# Puts threads to a single group, so we can start/kill everything together\n#\nclass ThreadGroup(threading.Thread):\n\n def __init__(\n self,\n thread_group_name\n ):\n super(ThreadGroup, self).__init__()\n self.thread_group_name = thread_group_name\n self.thread_collection = {}\n return\n\n #\n # Returns True of False, if successful or not\n #\n def add_thread(\n self,\n new_thread_name,\n new_thread\n ):\n # if type(new_thread) is not threading.Thread:\n # errmsg = str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\\\n # + ': [' + str(self.thread_group_name) + '] New thread \"' + str(new_thread_name)\\\n # + '\" not correct type, instead of type \"' + str(type(new_thread)) + '\".'\n # lg.Log.error(errmsg)\n # raise Exception(errmsg)\n\n key = su.StringUtils.trim(str(new_thread_name))\n # If existing thread of the same name exists\n if key == '':\n errmsg = str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\\\n + ': [' + str(self.thread_group_name) + '] Thread name must not be empty!'\n lg.Log.warning(errmsg)\n return False\n\n if key in self.thread_collection.keys():\n errmsg = str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\\\n + ': [' + str(self.thread_group_name) + '] Thread \"' + str(new_thread_name)\\\n + '\" already exists in collection!'\n lg.Log.warning(errmsg)\n return False\n\n self.thread_collection[key] = new_thread\n return True\n\n def start_thread_group(\n self\n ):\n for th_name in self.thread_collection.keys():\n th = self.thread_collection[th_name]\n lg.Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': [' + str(self.thread_group_name) + '] Starting thread \"' + str(th_name) + '\"..'\n )\n th.start()\n\n def run(self):\n sleep_while = 2\n lg.Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': [' + str(self.thread_group_name) + '] Starting thread group..'\n )\n is_any_thread_dead = False\n while True:\n if is_any_thread_dead:\n # Kill all threads\n for th_name in self.thread_collection.keys():\n th = self.thread_collection[th_name]\n lg.Log.info(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': [' + str(self.thread_group_name) + '] Joining Thread \"' + str(th_name) + '\"..'\n )\n th.join()\n lg.Log.info(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': All threads of thread group \"' + str(self.thread_group_name) + '\" joined..'\n )\n break\n\n for th_name in self.thread_collection.keys():\n th = self.thread_collection[th_name]\n if not th.isAlive():\n lg.Log.info(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': [' + str(self.thread_group_name) + '] Thread \"' + str(th_name)\n + '\" no longer alive. Killing everyone else.'\n )\n is_any_thread_dead = True\n break\n\n if not is_any_thread_dead:\n lg.Log.info(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': [' + str(self.thread_group_name) + '] All threads OK.'\n )\n time.sleep(sleep_while)\n\n\nif __name__ == '__main__':\n class TaskThread(threading.Thread):\n def __init__(self, thread_name, sleep_time):\n super(TaskThread, self).__init__()\n self.thread_name = thread_name\n self.sleep_time = sleep_time\n self.stoprequest = threading.Event()\n\n def join(self, timeout=None):\n print('Thread ' + self.thread_name + ' join called.')\n self.stoprequest.set()\n super(TaskThread, self).join(timeout=timeout)\n return\n\n def run(self):\n # Break sleep into small pieces\n quantum = 2\n count = 0\n run_quantized_sleeps = True\n while True:\n if self.stoprequest.isSet():\n print('Thread ' + self.thread_name + ' stop request received..')\n break\n # Task is to sleep\n if run_quantized_sleeps:\n time.sleep(quantum)\n count = count+1\n if count*quantum > self.sleep_time:\n break\n else:\n time.sleep(self.sleep_time)\n print('Sleep done for thread \"' + str(self.thread_name) + '\"..')\n\n lg.Log.LOGLEVEL = lg.Log.LOG_LEVEL_INFO\n\n #\n # We demo starting t1 thread whose job is to sleep for 5 secs.\n # t2 and t3 has a harder job to sleep for 500/800 secs.\n # However when the the tg thread group detects that t1 is dead,\n # its job is to kill t2 and t3.\n #\n t1 = TaskThread(thread_name='t1', sleep_time=5)\n t2 = TaskThread(thread_name='t2', sleep_time=500)\n t3 = TaskThread(thread_name='t3', sleep_time=800)\n\n tg = ThreadGroup(thread_group_name='tg')\n tg.add_thread(new_thread_name=t1.thread_name, new_thread=t1)\n tg.add_thread(new_thread_name=t2.thread_name, new_thread=t2)\n tg.add_thread(new_thread_name=t3.thread_name, new_thread=t3)\n\n tg.start_thread_group()\n tg.start()\n\n exit(0)\n","sub_path":"src/nwae/utils/ThreadGroup.py","file_name":"ThreadGroup.py","file_ext":"py","file_size_in_byte":6187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"286556993","text":"from os import path\r\nfrom pydub import AudioSegment\r\nfrom pydub.utils import mediainfo\r\nimport argparse\r\nparser = argparse.ArgumentParser(description='Huong dan su dung')\r\nparser.add_argument('-pw','--src', help='folder wav file', required=True)\r\nparser.add_argument('-pt','--dst', help='folder txt file', required=True)\r\n\r\n\r\n# files \r\n\r\n# convert wav to mp3\r\n\r\ndef convertToWav(src, dst,bitrate=\"256k\" ):\r\n sound = AudioSegment.from_mp3(src)\r\n sound.export(dst, format=\"wav\", bitrate=bitrate)\r\n\r\nif __name__ == \"__main__\": \r\n args = vars(parser.parse_args())\r\n\r\n src = args['src']\r\n dst = args['dst'] \r\n convertToWav(src, dst )","sub_path":"convertToWav.py","file_name":"convertToWav.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"449174561","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.remote.command import Command\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver import Firefox\nfrom selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\nimport requests\nimport json\nimport os\nimport math\nfrom urllib import request\n\n\n\ndef login():\n global lastPageScenceId\n\n\n getLogin_url = 'https://services.trax-cloud.cn'\n\n\n\n username = wait.until(EC.presence_of_element_located((By.NAME, \"username\")))\n # username = browser.find_element_by_name(\"username\")\n # submit_next = browser.find_element_by_name(\"login\")\n submit_next = wait.until(EC.presence_of_element_located((By.NAME, \"login\")))\n\n username.clear()\n username.send_keys(\"chenqinghai@swirebev.com\")\n time.sleep(1)\n submit_next.click()\n\n # password_input = browser.find_element_by_name(\"password\")\n # submit_login = browser.find_element_by_name(\"login\")\n password_input = wait.until(EC.presence_of_element_located((By.NAME, \"password\")))\n submit_login = wait.until(EC.presence_of_element_located((By.NAME, \"login\")))\n\n password_input.clear()\n password_input.send_keys(\"Trax12345\")\n time.sleep(1)\n submit_login.click()\n\n\n Explorer = wait.until(EC.presence_of_element_located((By.XPATH, \"/html/body/ui-view/div/ui-view/div/div/div[1]/div[2]/a\")))\n Explorer.click()\n\n # Explorer = browser.find_element_by_xpath(\"/html/body/ui-view/div/ui-view/div/div/div[1]/div[2]/a\").click()\n # /html/body/ui-view/div/ui-view/div/div/div[1]/div[2]/a\n\n Scenes = browser.find_element_by_xpath(\"/html/body/ui-view/div/ui-view/ui-view/div/div[2]/div[2]\").click()\n\n DateRange = wait.until(EC.presence_of_element_located((By.XPATH, \"/html/body/ui-view/div/ui-view/ui-view/ui-view/div/div[1]/div/ui-view/div/div/trax-date-picker/div/div\"))).click()\n\n # https://services.trax-cloud.cn/trax-one/api/projects/swirecn/explore/scenes/all/?limit=200&from=2019-02-01&to=2019-02-02&direction=first\n FromDate = wait.until(EC.presence_of_element_located((By.XPATH, \"/html/body/ui-view/div/ui-view/ui-view/ui-view/div/div[1]/div/ui-view/div/div/trax-date-picker/div/div[2]/div[1]/input[1]\")))\n ToDate = wait.until(EC.presence_of_element_located((By.XPATH, \"/html/body/ui-view/div/ui-view/ui-view/ui-view/div/div[1]/div/ui-view/div/div/trax-date-picker/div/div[2]/div[1]/input[2]\")))\n # '12 Mar, 2019' '14 Mar, 2019' Mar Feb Jan\n FromDate.clear()\n FromDate.send_keys(\"13 Mar, 2019\")\n\n ToDate.clear()\n ToDate.send_keys(\"13 Mar, 2019\")\n time.sleep(1)\n Apply_btn = wait.until(EC.presence_of_element_located((By.XPATH, \"/html/body/ui-view/div/ui-view/ui-view/ui-view/div/div[1]/div/ui-view/div/div/trax-date-picker/div/div[2]/div[6]/button[2]\")))\n Apply_btn.click()\n #\n # page = browser.page_source\n\n # 进入场景\n time.sleep(5)\n # getFirstScencesList()\n getNextScencesList(lastPageScenceId)\ndef saveCookies():\n cookies = browser.get_cookies()\n jsonCookies = json.dumps(cookies)\n with open('cookies.json', 'w') as f:\n f.write(jsonCookies)\n print(cookies)\n\n# 获取cookies\ndef getCookies():\n with open('cookies.json', 'r', encoding='utf-8') as f:\n listCookies = json.loads(f.read())\n cookie = [item[\"name\"] + \"=\" + item[\"value\"] for item in listCookies]\n cookiestr = '; '.join(item for item in cookie)\n\n return cookiestr\n\n# 获取localStorage\ndef getLocalStorage(key):\n # getItem = 'localStorage.getItem(\"temp2\")'\n print(key)\n res = browser.execute_script(\"return localStorage.getItem({})\".format(key))\n return res\ndef getLabelResults(index):\n print('发起请求...')\n base_url = 'https://services.trax-cloud.cn/trax-one/api/projects/swirecn/scene/' + str(index)\n headers = {\n \"authentication_token\": getLocalStorage(\"'authentication_token'\"),\n \"authorization_token\": getLocalStorage(\"'authorization_token'\"),\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\",\n \"refresh_token\": getLocalStorage(\"'refresh_token'\"),\n \"cookie\": getCookies()\n }\n try:\n rec_response = requests.get(base_url, headers=headers).text\n rec_response = json.loads(rec_response)\n scence_path = date_path + \"/{}\".format(str(index))\n mkdir(scence_path)\n # saveResults(scence_path + \"/{}\".format(str(index)), rec_response)\n saveResultsByJson(scence_path + \"/{}\".format(str(index)), rec_response)\n imagesList = rec_response[\"probeImages\"]\n for img in imagesList:\n img_url = 'https://services.traxretail.com/images/traxus' + img[\"probe_image_path\"].partition('http://traxus.s3.amazonaws.com')[2] + '/original'\n img_name = img[\"probe_image_path\"].split('/')[-1]\n try:\n saveimage(img_url, scence_path + \"/{}.jpeg\".format(img_name))\n except Exception as e:\n print(\"图片保存失败:\", e)\n print('爬取成功...')\n except:\n print(\"爬取失败\")\n time.sleep(2)\n # print(rec_response)\n\ndef goToNextPage():\n # span.xp-navigate-description.trax-tst-pagination-paging-summary\n page_location = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span.xp-navigate-description.trax-tst-pagination-paging-summary')))\n print('page_location:', page_location.text)\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span[title=\"next\"]'))).click()\n # 进入场景\n time.sleep(5)\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a[href^=\"trax-one/swirecn/explore/scene/\"]'))).click()\n\n\ndef getNextSence():\n\n scence_location = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'body > ui-view > div > ui-view > ui-view > div > div.is-subheader.is-viewer-subheader.sp-flex-shrink > span.is-subheader-center > ui-view > div > siblings-navigator > span > span > span.items-list.trax-tst-viewer-serializationText')))\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'body > ui-view > div > ui-view > ui-view > div > div.is-subheader.is-viewer-subheader.sp-flex-shrink > span.is-subheader-center > ui-view > div > siblings-navigator > span > span > span.trax-icons.trax-icons-page-back.rotated-to-down-arrow.trax-tst-viewer-next'))).click()\n scence_index = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'body > ui-view > div > ui-view > ui-view > div > div.is-subheader.is-viewer-subheader.sp-flex-shrink > span.is-subheader-left > ui-view > div > span > span:nth-child(4)')))\n print('scence_location:', scence_location.text, 'scence_index:', scence_index.text)\n\ndef getFirstScencesList():\n global pageNumber\n global totalPages\n print('发起场景列表请求...')\n base_url = 'https://services.trax-cloud.cn/trax-one/api/projects/swirecn/explore/scenes/all/'\n headers = {\n \"authentication_token\": getLocalStorage(\"'authentication_token'\"),\n \"authorization_token\": getLocalStorage(\"'authorization_token'\"),\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\",\n \"refresh_token\": getLocalStorage(\"'refresh_token'\"),\n \"cookie\": getCookies()\n }\n request_data = {\n \"limit\": 200,\n \"from\": from_date,\n \"to\": to_date,\n \"direction\": 'first',\n # \"last_known_primary_key\": last_known_primary_key\n }\n\n scencesList_res = requests.get(url=base_url, headers=headers, params=request_data).text\n scencesList_res = json.loads(scencesList_res)\n saveResultsByJson(date_path +'/' + date + '_' + str(pageNumber + 1), scencesList_res)\n print(scencesList_res)\n totalItemsCount = scencesList_res[\"totalItems\"][\"total_items\"]\n items = scencesList_res[\"items\"]\n print(\"totalItemsCount:\",totalItemsCount, \"items:\", items)\n pageNumber += 1\n totalPages = math.ceil(int(totalItemsCount) / 200)\n for i in range(0, 200):\n index = items[i][\"scene_id\"]\n print(\"正在爬取第{}页的第{}条,共{}页,共{}条\".format(pageNumber, i+1, totalPages, totalItemsCount))\n try:\n getLabelResults(index)\n if i == 199 and pageNumber <= totalPages:\n getNextScencesList(index)\n except Exception as e:\n print('获取下个场景失败', e)\n\n\ndef getNextScencesList(last_known_primary_key):\n global pageNumber\n global totalPages\n print('发起场景列表请求...')\n base_url = 'https://services.trax-cloud.cn/trax-one/api/projects/swirecn/explore/scenes/all/'\n headers = {\n \"authentication_token\": getLocalStorage(\"'authentication_token'\"),\n \"authorization_token\": getLocalStorage(\"'authorization_token'\"),\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\",\n \"refresh_token\": getLocalStorage(\"'refresh_token'\"),\n \"cookie\": getCookies()\n }\n request_data = {\n \"limit\": 200,\n \"from\": from_date,\n \"to\": to_date,\n \"direction\": 'next',\n \"last_known_primary_key\": last_known_primary_key\n }\n\n scencesList_res = requests.get(url=base_url, headers=headers, params=request_data).text\n scencesList_res = json.loads(scencesList_res)\n\n # print(scencesList_res)\n # saveResultsByJson(str(2019), scencesList_res)\n saveResultsByJson(date_path + '/' + date + '_' + str(pageNumber + 1), scencesList_res)\n print(scencesList_res)\n totalItemsCount = scencesList_res[\"totalItems\"][\"total_items\"]\n items = scencesList_res[\"items\"]\n print(\"totalItemsCount:\", totalItemsCount, \"items:\", items)\n pageNumber += 1\n totalPages = math.ceil(int(totalItemsCount) / 200)\n for i in range(0, 200):\n index = items[i][\"scene_id\"]\n print(\"正在爬取第{}页的第{}条,共{}页,共{}条\".format(pageNumber, i + 1, totalPages, totalItemsCount))\n try:\n getLabelResults(index)\n if i == 199 and pageNumber <= totalPages:\n getNextScencesList(index)\n except Exception as e:\n print('获取下个场景失败', e)\n\n\ndef saveimage(imgUrl, imgPath):\n request.urlretrieve(imgUrl, imgPath)\n\ndef saveResults(filename, data):\n with open(\"{}.json\".format(filename), \"w\", encoding='utf-8') as f:\n f.write(data)\n\ndef saveResultsByJson(filename, data):\n with open(\"{}.json\".format(filename), 'w', encoding='utf-8') as json_file:\n json.dump(data, json_file, ensure_ascii=False)\n\ndef mkdir(path):\n path = path.strip()\n path = path.rstrip(\"\\\\\")\n isExists = os.path.exists(path)\n if not isExists:\n os.makedirs(path)\n print(\"{}创建成功\".format(path))\n return True\n else:\n print(\"{}已存在\".format(path))\n return False\n\nif __name__ == \"__main__\":\n from_date = '2019-03-13'\n to_date = '2019-03-13'\n date = from_date.replace('-', '')\n date_path = \"./scence/{}\".format(date)\n lastPageScenceId = 9237427\n pageNumber = 5\n totalPages = 0\n mkdir(date_path)\n # chromeOptions = webdriver.ChromeOptions()\n # chromeOptions.add_argument('--proxy-server=https://210.16.189.230:16816')\n # browser = webdriver.Chrome(chrome_options=chromeOptions)\n browser = webdriver.Chrome()\n wait = WebDriverWait(browser, 10)\n login()\n","sub_path":"python-script/trax/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"119066017","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\n\nsetup_requires = []\ninstall_requires = [\n 'filelock',\n 'nose',\n 'numpy>=1.9.0',\n 'protobuf',\n 'six>=1.9.0',\n]\n\nsetup(\n name='chainer',\n version='2.0.0a1',\n description='A flexible framework of neural networks',\n author='Seiya Tokui',\n author_email='tokui@preferred.jp',\n url='http://chainer.org/',\n license='MIT License',\n packages=['chainer',\n 'chainer.dataset',\n 'chainer.datasets',\n 'chainer.functions',\n 'chainer.functions.activation',\n 'chainer.functions.array',\n 'chainer.functions.caffe',\n 'chainer.functions.connection',\n 'chainer.functions.evaluation',\n 'chainer.functions.loss',\n 'chainer.functions.math',\n 'chainer.functions.noise',\n 'chainer.functions.normalization',\n 'chainer.functions.pooling',\n 'chainer.functions.theano',\n 'chainer.functions.util',\n 'chainer.function_hooks',\n 'chainer.iterators',\n 'chainer.initializers',\n 'chainer.links',\n 'chainer.links.activation',\n 'chainer.links.caffe',\n 'chainer.links.caffe.protobuf2',\n 'chainer.links.caffe.protobuf3',\n 'chainer.links.connection',\n 'chainer.links.loss',\n 'chainer.links.model',\n 'chainer.links.model.vision',\n 'chainer.links.normalization',\n 'chainer.links.theano',\n 'chainer.optimizers',\n 'chainer.serializers',\n 'chainer.testing',\n 'chainer.training',\n 'chainer.training.extensions',\n 'chainer.training.triggers',\n 'chainer.utils'],\n zip_safe=False,\n setup_requires=setup_requires,\n install_requires=install_requires,\n tests_require=['mock',\n 'nose'],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"119482381","text":"from __future__ import absolute_import\n\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom sentry.api.base import Endpoint\n\nfrom sentry.integrations.atlassian_connect import AtlassianConnectValidationError, get_integration_from_jwt\nfrom sentry.models import sync_group_assignee_inbound\n\n\nclass JiraIssueUpdatedWebhook(Endpoint):\n authentication_classes = ()\n permission_classes = ()\n\n @csrf_exempt\n def dispatch(self, request, *args, **kwargs):\n return super(JiraIssueUpdatedWebhook, self).dispatch(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n try:\n token = request.META['HTTP_AUTHORIZATION'].split(' ', 1)[1]\n except (KeyError, IndexError):\n return self.respond(status=400)\n\n data = request.DATA\n\n assignee_changed = any(\n item for item in data['changelog']['items'] if item['field'] == 'assignee'\n )\n\n if not assignee_changed:\n return self.respond()\n\n try:\n integration = get_integration_from_jwt(\n token, request.path, request.GET, method='POST'\n )\n except AtlassianConnectValidationError:\n return self.respond(status=400)\n\n assignee = data['issue']['fields']['assignee']\n issue_key = data['issue']['key']\n\n if assignee is None:\n sync_group_assignee_inbound(\n integration, None, issue_key, assign=False,\n )\n else:\n sync_group_assignee_inbound(\n integration, assignee['emailAddress'], issue_key, assign=True,\n )\n\n return self.respond()\n","sub_path":"src/sentry/integrations/jira/webhooks.py","file_name":"webhooks.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"471366758","text":"# -*- coding: utf-8 -*-\n\n###########################################################\n# Aldebaran Behavior Complementary Development Kit\n# Pose Library\n# Author A. Mazel\n# Aldebaran Robotics (c) 2010 All Rights Reserved - This file is confidential.\n###########################################################\n\n\"Pose Library: handle position, compare between them, fusion them...\"\n\nprint( \"importing abcdk.poselibrary\" );\n\nimport math\n\nimport arraytools\nimport debug\nimport naoqitools\nimport numeric\nimport stringtools\nimport system\nimport test\nimport typetools\n\nglobal_dicoGroupDefinition = None; # bit precalc\nclass PoseLibrary():\n \"A module to store Nao position, compare position between them and help user use them\"\n\n @staticmethod\n def getCurrentPosition():\n \"get a list of joint name and their current position value in radians ['HeadYaw'=1.0; 'HeadPitch'=1.0;... work even if no stiffness\"\n motion = naoqitools.myGetProxy( \"ALMotion\" );\n listJointName = motion.getJointNames('Body');\n listJointName.remove( \"RHipYawPitch\" ); # when using dcm: remove this joint\n listJointsDCMValue = []; # la liste des clés de chaque joint dans la stm\n for strJointName in listJointName:\n listJointsDCMValue.append( \"Device/SubDeviceList/%s/Position/Sensor/Value\" % strJointName );\n # add TorsoX and Y and AccZ\n listJointsDCMValue.append( \"Device/SubDeviceList/InertialSensor/AngleX/Sensor/Value\" );\n listJointsDCMValue.append( \"Device/SubDeviceList/InertialSensor/AngleY/Sensor/Value\" );\n listJointsDCMValue.append( \"Device/SubDeviceList/InertialSensor/AccZ/Sensor/Value\" );\n stm = naoqitools.myGetProxy( \"ALMemory\" );\n listJointValue = stm.getListData( listJointsDCMValue );\n dicoConstructed = dict([]);\n for i in range( len( listJointName ) ):\n dicoConstructed[listJointName[i]] = listJointValue[i];\n dicoConstructed['TorsoX'] = listJointValue[len( listJointName )];\n dicoConstructed['TorsoY'] = listJointValue[len( listJointName ) + 1];\n dicoConstructed['TorsoAccZ'] = listJointValue[len( listJointName ) + 2] * math.pi / 180;\n# debug.debug( \"poselibrary::PoseLibrary::getCurrentPosition: \" + stringtools.dictionnaryToString( dicoConstructed ) );\n return dicoConstructed;\n # getJointPos - end\n\n @staticmethod\n def getGroupDefinition():\n \"get list of group, group can contains some subgroups\"\n global global_dicoGroupDefinition;\n if( global_dicoGroupDefinition != None ):\n return global_dicoGroupDefinition;\n dicoGroup = {\n 'All': ['Torsos', 'Body'],\n 'Torsos': ['TorsoX','TorsoY', 'TorsoAccZ'],\n 'Body': ['UpperBody', 'BottomBody'],\n 'UpperBody': ['Head', 'Arms', 'ForeArms'],\n 'BottomBody': ['Legs'],\n 'Head': ['HeadYaw', 'HeadPitch'],\n 'Arms': ['LArm', 'RArm'],\n 'Legs': ['LLeg', 'RLeg'],\n 'ForeArms': ['LForeArm', 'RForeArm'],\n 'LArm': ['LShoulderPitch','LShoulderRoll','LElbowRoll', 'LElbowYaw'],\n 'RArm': ['RShoulderPitch','RShoulderRoll','RElbowRoll', 'RElbowYaw'],\n 'LLeg': ['LHipYawPitch','LHipPitch','LHipRoll', 'LKneePitch', 'LAnkleRoll', 'LAnklePitch' ],\n 'RLeg': ['LHipYawPitch','RHipPitch','RHipRoll', 'RKneePitch', 'RAnkleRoll', 'RAnklePitch' ], # LHipYawPitch because it's better to send order to this one\n 'LForeArm': ['LWristYaw','LHand' ],\n 'RForeArm': ['RWristYaw','RHand' ],\n 'LFullArm': ['LForeArm','LArm' ],\n 'RFullArm': ['RForeArm','RArm' ], \n 'FullArm': ['LFullArm','RFullArm' ],\n 'Hands': ['LHand','RHand' ],\n };\n # patch on the fly!\n if( system.isOnRomeo() ):\n dicoGroup[\"Body\"].append( \"TrunkYaw\" );\n dicoGroup[\"LLeg\"].append( \"LHipYaw\" );\n dicoGroup[\"RLeg\"].append( \"RHipYaw\" );\n dicoGroup[\"Head\"] = [\"NeckPitch\", \"NeckYaw\", \"HeadPitch\", \"HeadRoll\"];\n if( True ):\n # add eyes groups\n dicoGroup[\"Eyes\"] = [\"LeftEye\", \"RightEye\"];\n dicoGroup[\"LeftEye\"] = [\"LEyePitch\", \"LEyeYaw\"];\n dicoGroup[\"RightEye\"] = [\"REyePitch\", \"REyeYaw\"];\n dicoGroup[\"All\"].append( \"Eyes\" );\n for strSide in ['L', 'R']:\n strGroupName = strSide + \"ForeArm\";\n dicoGroup[strGroupName].append( strSide + \"Wrist\" + \"Roll\" );\n dicoGroup[strGroupName].append( strSide + \"Wrist\" + \"Pitch\" );\n for k,v in dicoGroup.iteritems():\n for i, strJoint in enumerate( v ):\n if( \"ShoulderRoll\" in strJoint ):\n dicoGroup[k][i] = strJoint.replace( \"Roll\", \"Yaw\" );\n \n # remove all non present final joint\n motion = naoqitools.myGetProxy( \"ALMotion\" );\n listCurrentJoint = motion.getJointNames('Body');\n for k,v in dicoGroup.iteritems():\n i = 0;\n while( i < len(v) ):\n if( not v[i] in dicoGroup.keys() and not v[i] in listCurrentJoint and not \"Torso\" in v[i] ):\n print( \"abcdk.poselibrary.getGroupDefinition: removing '%s' from list because not present seen by motion\" % v[i] );\n del v[i];\n else:\n i += 1;\n \n global_dicoGroupDefinition = dicoGroup;\n #~ print( dicoGroup );\n return dicoGroup;\n # getGroupDefinition - end\n \n @staticmethod\n def getListJoints( listGroup, bRemoveHipYawPitch = False ):\n \"\"\"\n get list of joints from a group name or a list of group:\n eg: [\"Head\", \"LHand\", \"RArm\"] => ['HeadYaw', 'HeadPitch', 'LHand', 'RShoulderPitch', 'RShoulderRoll', 'RElbowRoll', 'RElbowYaw']\n \"Head;LHand;RArm\" => idem (alternate form)\n bRemoveHipYawPitch: remove all HipYawPitch from the list\n \"\"\"\n if( not isinstance( listGroup, list ) ):\n #~ print( \"interpreting joint from string %s =>\" % str( listGroup ) );\n listGroup = listGroup.split( \";\" );\n for i in range( len( listGroup ) ):\n listGroup[i] = listGroup[i].strip(); # remove surrounding space(s)\n #~ print( \"%s\" % str( listGroup ) );\n dicoGroup = PoseLibrary.getGroupDefinition();\n bGroupExploded = True;\n while( bGroupExploded ):\n listGroupExploded = [];\n bGroupExploded = False;\n for group in listGroup:\n# debug.debug( \"group: \" + str( group ) );\n if( group in dicoGroup ):\n listGroupExploded.extend( dicoGroup[group] );\n# debug.debug( \"listGroupExploded: \" + str( listGroup ) );\n bGroupExploded = True; # begin another time, because there's some new group\n else:\n listGroupExploded.append( group ); # here group is just a joint name\n listGroup = listGroupExploded;\n \n if( bRemoveHipYawPitch ): \n for i in range( len( listGroup ) ):\n if( i >= len( listGroup ) ):\n break; # la liste diminue en direct\n if( listGroup[i] in [ \"RHipYawPitch\", \"LHipYawPitch\" ] ):\n del listGroup[i];\n i -=1;\n\n return listGroup;\n # getListJoints - end\n \n @staticmethod\n def getGroupLimits( listGroup, rCoef = 1., bOrderedByMinMax = False ):\n \"get list of limits from a group name or a list of group\"\n \"rCoef: you can reduce the list by a ratio (0.5, will get halt the limits)\" \n \"order default: list of min,max,acc for each joint\"\n \"order bOrderedByMinMax: list of min of each joint, then list of max of each joint...\"\n listJoints = PoseLibrary.getListJoints( listGroup );\n listLimits = [];\n if( bOrderedByMinMax ):\n listLimits = [[],[],[]];\n motion = naoqitools.myGetProxy( 'ALMotion' );\n for strJointName in listJoints:\n limitForThisJoint = motion.getLimits( strJointName );\n # gestion 1.7.25 et rétrocompatibilité\n if( len( limitForThisJoint ) > 1 ):\n limitForThisJoint = limitForThisJoint[1];\n limitForThisJoint = limitForThisJoint[0];\n print( \"getGroupLimits: %s => %s\" % ( strJointName, str( limitForThisJoint ) ) );\n if( not bOrderedByMinMax ):\n limitForThisJoint[0] *= rCoef;\n limitForThisJoint[1] *= rCoef;\n limitForThisJoint[2] *= rCoef; \n listLimits.append( limitForThisJoint );\n else:\n listLimits[0].append( limitForThisJoint[0]*rCoef );\n listLimits[1].append( limitForThisJoint[1]*rCoef );\n listLimits[2].append( limitForThisJoint[2]*rCoef );\n return listLimits;\n # getGroupLimits - end \n\n @staticmethod\n def filterPosition( aPos, listGroupToRemove, bKeepInsteadOfRemove = False ):\n \"\"\"\n remove a group of joint from a position\n return the filtered list\n listGroupToRemove: list of joint to remove can contains a joint or a torso/gyro, or one of the groups in the dicoGroup: (ask for getGroupDefinition to see complete list of group)\n bKeepInsteadOfRemove: when set, the list of joint is the one to keep !\n \"\"\"\n #~ print( \"DBG: filterPosition:\\npos: %s\\nlistGroupToRemove: %s\\nbKeepInsteadOfRemove: %s\" % (aPos, listGroupToRemove, bKeepInsteadOfRemove) );\n # construct the list of joint with group transformed in a list of joint name\n dicoGroup = PoseLibrary.getGroupDefinition();\n# debug.debug( \"dicoGroup:\" + str( dicoGroup ) );\n bGroupExploded = True;\n while( bGroupExploded ):\n listGroupExploded = [];\n bGroupExploded = False;\n for group in listGroupToRemove:\n# debug.debug( \"group: \" + str( group ) );\n if( group in dicoGroup ):\n listGroupExploded.extend( dicoGroup[group] );\n# debug.debug( \"listGroupExploded: \" + str( listGroupExploded ) );\n bGroupExploded = True; # begin another time, because there's some new group\n else:\n listGroupExploded.append( group ); # here group is just a joint name\n listGroupToRemove = listGroupExploded;\n# debug.debug( \"poselibrary::PoseLibrary::filterPosition: final joint list to remove: %s\" % str( listGroupToRemove ) );\n aKeeped = dict();\n for strJointName in listGroupToRemove:\n if( strJointName in aPos ):\n if( not bKeepInsteadOfRemove ):\n del aPos[strJointName];\n else:\n aKeeped[strJointName] = aPos[strJointName];\n\n if( bKeepInsteadOfRemove ):\n return aKeeped;\n return aPos;\n # filterPosition - end\n\n @staticmethod\n def setPosition( aPosToSet, rTimeSec = 1.4, bWaitEnd = True, bDontUseLegs = False ):\n \"\"\"\n set a position on Nao (with optionnal time in sec to go to the position)\n bWaitEnd: thread command and return the motion id\n \"\"\"\n# print( \"poselibrary::PoseLibrary::setPosition( %d angles, time: %f, bWaitEnd: %d )\" % ( len( aPosToSet ), rTimeSec, bWaitEnd ) );\n motion = naoqitools.myGetProxy( \"ALMotion\" );\n aJointName = [];\n aPos = [];\n listJointToExclude = [];\n if( bDontUseLegs ):\n listJointToExclude = PoseLibrary.getListJoints( ['Legs'] );\n for k, v in aPosToSet.iteritems():\n if( k.find( \"Torso\" ) == -1 and ( not k in listJointToExclude ) ):\n aJointName.append( k );\n aPos.append( v );\n if( bWaitEnd ):\n motion.angleInterpolation( aJointName, aPos, rTimeSec, True );\n return -1;\n nId = motion.post.angleInterpolation( aJointName, aPos, rTimeSec, True );\n return nId;\n\n # setPosition - end\n \n @staticmethod\n def setPositionWithSpeed( aPosToSet, nSpeed = 30, bWaitEnd = True, bDontUseLegs = False ):\n \"set a position on Nao (with optionnal speed in % to go to the position)\"\n \"if not bWaitEnd return a post call threaded method id\"\n \"return the naoqi id if bWaitEnd is false\"\n print( \"poselibrary.setPositionWithSpeed( nSpeed: %d )\" % nSpeed );\n motion = naoqitools.myGetProxy( \"ALMotion\" );\n aJointName = [];\n aPos = [];\n listJointToExclude = [];\n if( bDontUseLegs ):\n listJointToExclude = PoseLibrary.getListJoints( ['Legs'] );\n for k, v in aPosToSet.iteritems():\n if( k.find( \"Torso\" ) == -1 and ( not k in listJointToExclude ) ):\n aJointName.append( k );\n aPos.append( v );\n if( bWaitEnd ):\n motion.angleInterpolationWithSpeed( aJointName, aPos, nSpeed/100. );\n return -1;\n nId = motion.post.angleInterpolationWithSpeed( aJointName, aPos, nSpeed/100. );\n return nId;\n # setPositionWithSpeed - end\n \n @staticmethod \n def interpolatePosition( aPos1, aPos2, rRatio = 0.5 ):\n \"create a position intermediary between two positions if rRatio is 0. => pos1, if at 1. => pos2\"\n \"rRatio in [0.,1.]\"\n listPosResult = {};\n rRatio = numeric.limitRange( rRatio, 0., 1. );\n for k, v in aPos1.iteritems():\n if( k in aPos2 ):\n listPosResult[k] = v * ( 1. - rRatio ) + aPos2[k] * rRatio;\n return listPosResult;\n # interpolatePosition - end\n \n @staticmethod \n def interpolatePositionXY( aPosTR, aPosTL, aPosBR, aPosBL, rX = 0.0, rY = 0.0 ):\n \"create a position intermediary at the center of four positions\"\n \"rX et rY in [-1.,1.]\"\n \"TR: Top Right( -1,-1), aPosTL: Top Left TR: Top Right, BL: Bottom Left, BR: Bottom Right(1,1)\"\n rX_Normalised = (rX+1.) /2.;\n rY_Normalised = (rY+1.) /2.;\n listPosResultTRL = PoseLibrary.interpolatePosition( aPosTR, aPosTL, rX_Normalised );\n listPosResultBRL = PoseLibrary.interpolatePosition( aPosBR, aPosBL, rX_Normalised);\n listPosResult = PoseLibrary.interpolatePosition( listPosResultBRL, listPosResultTRL, rY_Normalised );\n return listPosResult;\n # interpolatePositionXY - end \n\n @staticmethod \n def interpolatePositionXY6( aPosTR, aPosTC, aPosTL, aPosBR, aPosBC, aPosBL, rX = 0.0, rY = 0.0 ):\n \"create a position intermediary at the center of 6 positions (4 corner and two center)\"\n \"rX et rY in [-1.,1.]\"\n \"TR: Top Right( -1,-1), aPosTL: Top Left TR: Top Right, BL: Bottom Left, BR: Bottom Right(1,1)\"\n \"aPosTC: Top Center, aPosBC: Bottom Center\"\n rX_Normalised = (rX+1.) /2.;\n rY_Normalised = (rY+1.) /2.;\n if( rX_Normalised < 0.5 ): \n rX_Normalised *= 2; # ramene sur 0..1\n listPosResultTRL = PoseLibrary.interpolatePosition( aPosTR, aPosTC, rX_Normalised );\n listPosResultBRL = PoseLibrary.interpolatePosition( aPosBR, aPosBC, rX_Normalised);\n else:\n rX_Normalised = ( rX_Normalised - 0.5 ) * 2; # ramene sur 0..1\n listPosResultTRL = PoseLibrary.interpolatePosition( aPosTC, aPosTL, rX_Normalised );\n listPosResultBRL = PoseLibrary.interpolatePosition( aPosBC, aPosBL, rX_Normalised); \n listPosResult = PoseLibrary.interpolatePosition( listPosResultTRL, listPosResultBRL, rY_Normalised );\n return listPosResult;\n # interpolatePositionXY - end\n \n @staticmethod \n def interpolatePositionXY_Mirror( aPosCT, aPosCB, aPosLB, aPosLT, rX = 0., rY = 0. ):\n \"create a position intermediary at the center of 6 positions using mirror: \"\n \"we just give Center and left, and the right is mirrored\"\n \"rX et rY in [-1.,1.]\"\n \"CT: Center-Top( 0,-1), aPosLB: Left-Bottom (1,1)\"\n bDoMirror = False;\n\n if( rX < 0. ):\n rX = -rX;\n bDoMirror = True;\n\n rY_Normalised = (rY+1.) /2.;\n \n# print( \"interpolatePositionXY_Mirror: %5.2f, %5.2f, %5.2f, %5.2f, \" % ( aPosCT['LShoulderPitch'], aPosCB['LShoulderPitch'], aPosLB['LShoulderPitch'], aPosLT['LShoulderPitch'] ) ); \n# print( \"interpolatePositionXY_Mirror: using x,y: %f,%f (mirror:%s)\" % ( rX, rY_Normalised, str(bDoMirror) ) );\n listPosResultTCL = PoseLibrary.interpolatePosition( aPosCT, aPosLT, rX );\n listPosResultBCL = PoseLibrary.interpolatePosition( aPosCB, aPosLB, rX);\n listPosResult = PoseLibrary.interpolatePosition( listPosResultTCL, listPosResultBCL, rY_Normalised );\n if( bDoMirror ):\n listPosResult = PoseLibrary.mirror( listPosResult ); \n return listPosResult;\n # interpolatePositionXY_Mirror - end \n\n @staticmethod\n def getEmotionName( bAddNeutral = False ):\n \"return a list of 6 dictionnary of pose\"\n \"if bAddNeutral: add a seven neutral pose\"\n listName = [ 'Proud', 'Happy', 'Excitement', 'Fear', 'Sadness', 'Anger'] ;\n if( bAddNeutral ):\n listName.append( 'Neutral' );\n return listName;\n # getEmotionName - end\n\n @staticmethod\n def getEmotionPose( bAddNeutral = False ):\n \"return a list of 6 dictionnary of pose\"\n \"if bAddNeutral: add a seven neutral pose\"\n import emotion_list_poses;\n listPose = [];\n listPose.extend( emotion_list_poses.listPoses ); # listPose = list_emotion_poses.listPoses ne ferait qu'un pointeur sur l'objet, et donc quand on append la neutralpose, ca ajoute a la liste du module, beurk.\n if( bAddNeutral ):\n listPose.append( emotion_list_poses.poseNeutral );\n return listPose;\n # getEmotionPose - end\n \n @staticmethod\n def interpolateEmotion( arListRatioParams, rNeutral = 0. ):\n \"create a position intermediary mixed from 6 emotions and a neutral\"\n \"arListRatio: the ratio of each emotions: [Proud, Happy, Excitement, Fear, Sadness, Anger]\"\n \" if sum is greater than 1, it would be normalised\"\n \" if sum is lower than 1, a neutral position would be added\"\n \"rNeutral: to force an addition of a proportion of the neutral pose\"\n \n # preparation of the ratio\n \n arListRatio = arraytools.dup( arListRatioParams );\n \n if( len( arListRatio ) > 6 ):\n arListRatio = arListRatio[:6];\n \n rSum = arraytools.arraySum( arListRatio );\n \n# rEpsilon = 0.1;\n if( rSum + rNeutral < 1. ):\n rNeutral = 1. - rSum;\n rSumTotal = rSum + rNeutral;\n if( rSumTotal > 1. ):\n # normalisation\n for i in range( len( arListRatio ) ):\n arListRatio[i] /= rSumTotal;\n rNeutral /= rSumTotal;\n \n # push zeroes for others emotions:\n for i in range( len( arListRatio ), 6 ):\n arListRatio.append( 0. );\n \n print( \"interpolateEmotion: using emotions ratio: %s and neutral ratio: %5.2f\" % ( str( arListRatio ), rNeutral ) );\n\n arListRatio.append( rNeutral );\n listPosEmotion = PoseLibrary.getEmotionPose( True ); # True => ajoute la neutre !\n # print( \"listPosEmotion has %d poses\" % len( listPosEmotion ) );\n listPosResult = {};\n for k, v in listPosEmotion[0].iteritems():\n rVal = v * arListRatio[0];\n bKeyInAllPos = True;\n for i in range( 1, len( listPosEmotion ) ):\n if( k in listPosEmotion[i] ): \n rVal += listPosEmotion[i][k] * arListRatio[i]; \n else:\n bKeyInAllPos = False;\n if( bKeyInAllPos ):\n listPosResult[k] = rVal;\n # for - end\n \n return listPosResult;\n \n # interpolateEmotion - end\n\n @staticmethod\n def getTrackingEmotionPose( bAddNeutral = False ):\n \"return a list of 6 dictionnary of pose\"\n \"if bAddNeutral: add a seven neutral pose\"\n import emotion_list_tracking_poses;\n listPose = [];\n listPose.extend( emotion_list_tracking_poses.listAllEmotions ); # listPose = list_emotion_poses.listPoses ne ferait qu'un pointeur sur l'objet, et donc quand on append la neutralpose, ca ajoute a la liste du module, beurk.\n if( bAddNeutral ):\n listPose.append( emotion_list_tracking_poses.listNeutral );\n return listPose;\n # getTrackingEmotionPose - end\n \n @staticmethod\n def interpolateTrackingEmotion( arListRatio, arPosHead, rNeutral = 0. ):\n \"create a position intermediary mixed from 6 emotions and a neutral, related to some specific angle of the head\"\n \"arListRatio: the ratio of each emotions: [Proud, Happy, Excitement, Fear, Sadness, Anger]\"\n \" if sum is greater than 1, it would be normalised\"\n \" if sum is lower than 1, a neutral position would be added\"\n \"rNeutral: to force an addition of a proportion of the neutral pose\"\n \n # preparation of the ratio\n \n if( len( arListRatio ) > 6 ):\n arListRatio = arListRatio[:6];\n \n rSum = arraytools.arraySum( arListRatio );\n# rEpsilon = 0.1;\n if( rSum + rNeutral < 1. ):\n rNeutral = 1. - rSum;\n rSumTotal = rSum + rNeutral;\n if( rSumTotal > 1. ):\n # normalisation\n for i in range( len( arListRatio ) ):\n arListRatio[i] /= rSumTotal;\n rNeutral /= rSumTotal;\n \n # push zeroes for others emotions:\n for i in range( len( arListRatio ), 6 ):\n arListRatio.append( 0. );\n \n print( \"interpolateTrackingEmotion(head:%5.2f,%5.2f): using emotions ratio: %s and neutral ratio: %f\" % ( arPosHead[0], arPosHead[1], str( arListRatio ), rNeutral ) );\n\n arListRatio.append( rNeutral );\n \n listPosTrackingEmotion = PoseLibrary.getTrackingEmotionPose( True ); # True => ajoute la neutre !\n \n # in fact we will allways generate from a square from center to left side, and we mirror it if we are in the right area\n \n # first we compute the 4 poses from emotion mixes:\n \n# print( \"arListRatio final: %s, len: %d\" % ( str( arListRatio ), len( arListRatio ) ) );\n \n listPosResult = [{},{},{},{}];\n # for each corner to generate\n for indexSquare in range( 4 ):\n # for each joint\n for k, v in listPosTrackingEmotion[0][indexSquare].iteritems():\n rVal = v * arListRatio[0];\n bKeyInAllPos = True;\n # for each emotion, sum the ratio concerning this joint\n for i in range( 1, len( listPosTrackingEmotion ) ):\n# print( \"i: %d / %d\" % (i,len( listPosTrackingEmotion) ) );\n# print( \"ratio: %f\" % arListRatio[i] );\n if( k in listPosTrackingEmotion[i][indexSquare] ):\n rVal += listPosTrackingEmotion[i][indexSquare][k] * arListRatio[i];\n else:\n bKeyInAllPos = False;\n if( bKeyInAllPos ):\n# print( \"k: %s, rVal: %f\" % ( k, rVal ) );\n listPosResult[indexSquare][k] = rVal;\n # for - each point of square end\n # for - end square\n \n # then we compute the center position relative of the 4 pose\n listPosResult = PoseLibrary.interpolatePositionXY_Mirror( listPosResult[0], listPosResult[1], listPosResult[2], listPosResult[3], arPosHead[0], arPosHead[1] );\n \n return listPosResult;\n \n # interpolateTrackingEmotion - end\n \n @staticmethod\n def getAnimationPoseName():\n \"return a list of 6 dictionnary of pose\"\n \"if bAddNeutral: add a seven neutral pose\"\n listName = [ 'Confidence_lo', 'Confidence_hi', 'Engagement_lo', 'Engagement_hi', 'Neutral'] ;\n return listName;\n # getEmotionName - end\n\n @staticmethod\n def getAnimationPose():\n \"return a list of 6 dictionnary of pose\"\n \"if bAddNeutral: add a seven neutral pose\"\n import animation_list_poses;\n import emotion_list_poses; \n listPose = [];\n listPose.extend( animation_list_poses.listPoses );\n listPose.append( emotion_list_poses.poseNeutral );\n return listPose;\n # getAnimationPose - end\n \n @staticmethod\n def interpolateAnimationPose( arListRatio ):\n \"create a position intermediary mixed from animation parameters\"\n \"arListRatio: the ratio of each animation parameters: [Confidence, Engagement]\"\n \n nRequiredParameters = 2;\n \n if( len( arListRatio ) > nRequiredParameters ):\n arListRatio = arListRatio[:nRequiredParameters];\n \n \n # push zeroes for missing parameters:\n for i in range( len( arListRatio ), nRequiredParameters ):\n arListRatio.append( 0. );\n \n # now we would generate the resulting pose for each parameters, then mix them\n listPose = PoseLibrary.getAnimationPose();\n listPoseToMix = [];\n newPose = PoseLibrary.interpolatePosition( listPose[0], listPose[1], arListRatio[0] ); # confidence\n listPoseToMix.append( newPose );\n newPose = PoseLibrary.interpolatePosition( listPose[2], listPose[3], arListRatio[1] ); # engagement\n listPoseToMix.append( newPose );\n \n # mix them\n listPosResult = PoseLibrary.interpolatePosition( listPoseToMix[0], listPoseToMix[1] );\n \n return listPosResult;\n \n # interpolateAnimationPose - end\n \n \n\n @staticmethod\n def positionToString( aPos ):\n \"format a position to print it\"\n return stringtools.dictionnaryToString( aPos );\n # positionToString - end\n\n @staticmethod\n def getDifferentJoints( aPosToCompare, rThreshold = 0.12 ):\n \"return the list of joint that has a difference between a specific position and nao current position\"\n listDiff = [];\n dicoCurrentPos = PoseLibrary.getCurrentPosition();\n for k, v in dicoCurrentPos.iteritems(): # not optimal: should iterate on aPosToCompare !\n if( k in aPosToCompare ):\n rDiff = abs( v - aPosToCompare[k] );\n if( rDiff > rThreshold ):\n debug.debug( \"difference on key %s (%f -> %f (diff:%f))\" %( k, aPosToCompare[k], v, rDiff ) );\n listDiff.append( k );\n return listDiff;\n # getDifferentJoints - end\n \n \n @staticmethod\n def comparePosition( aPosToCompare, aListGroupToIgnore = [] ):\n \"compare a specific position of nao with current position\"\n \"aPosToCompare is a dictionnary of some angles; eg: dict( [ ('LArm', 1.32), ('HeadYaw', 0.5), ('TorsoX', 0.5) ] );\"\n \"aListGroupToIgnore is a mixed type list of joint or group to ignore for comparison\"\n \"It will return the median of absolute difference of joints in radians\"\n# debug.debug( \"len( aPosToCompare ): \" + str( len( aPosToCompare ) ) );\n if( len( aPosToCompare ) < 1 ):\n return 421.0; # surely some sort of error => return a big value\n dicoCurrentPos = PoseLibrary.getCurrentPosition();\n if( len( aListGroupToIgnore ) > 0 ):\n dicoCurrentPos = PoseLibrary.filterPosition( dicoCurrentPos, aListGroupToIgnore );\n rDiffSum = 0.0;\n nNbrComp = 0;\n for k, v in dicoCurrentPos.iteritems(): # not optimal: should iterate on aPosToCompare !\n if( k in aPosToCompare ):\n rDiff = abs( v - aPosToCompare[k] );\n# if( k == 'TorsoAccZ' ):\n# rDiff *= 8; # This value is important and very small compared to others\n rDiffSum += rDiff;\n nNbrComp += 1;\n # debug.debug( \"poselibrary::PoseLibrary::comparePosition:\\ncurrent: %s\\ncomp: %s\\n=> %f/%d = %f\" % ( str(dicoCurrentPos), str(aPosToCompare), rDiffSum, nNbrComp, rDiffSum / nNbrComp ) );\n return rDiffSum / nNbrComp;\n # comparePosition - end\n\n @staticmethod\n def getPosition_Standing():\n \"get the standard standing position\"\n return {\n 'TorsoX': 0.0,\n 'TorsoY': 0.0,\n 'LAnklePitch': 0.010696,\n 'LAnkleRoll': 0.058334,\n 'LHipPitch': 0.010780,\n 'LHipRoll': -0.050580,\n 'LHipYawPitch': 0.007712,\n 'LKneePitch': 0.009162,\n 'RAnklePitch': 0.007712,\n 'RAnkleRoll': -0.055182,\n 'RHipPitch': 0.010696,\n 'RHipRoll': 0.053732,\n 'RKneePitch': 0.004644,\n };\n # getPosition_Standing - end\n @staticmethod\n def getPosition_Sitting():\n \"get the official sitting position - without anklepitch due to ankle limitation far distant from real range\"\n \"now it's the new one WITH the ankle pitch\"\n return {\n 'HeadPitch': -0.0215179622173,\n 'HeadYaw': 0.0260360389948,\n 'LAnklePitch': 0.888144075871,\n 'LAnkleRoll': 0.0123139619827,\n 'LElbowRoll': -0.977116048336,\n 'LElbowYaw': -0.733294010162,\n 'LHand': 0.238207533956,\n 'LHipPitch': -1.59992003441,\n 'LHipRoll': 0.233209967613,\n 'LHipYawPitch': -0.717870056629,\n 'LKneePitch': 1.37442207336,\n 'LShoulderPitch': 0.969446063042,\n 'LShoulderRoll': 0.20551404357,\n 'LWristYaw': -0.593699991703,\n 'RAnklePitch': 0.879023969173,\n 'RAnkleRoll': -0.0383080393076,\n 'RElbowRoll': 0.882091999054,\n 'RElbowYaw': 0.562936067581,\n 'RHand': 0.314207285643,\n 'RHipPitch': -1.59846997261,\n 'RHipRoll': -0.162562042475,\n 'RKneePitch': 1.41592395306,\n 'RShoulderPitch': 0.874421954155,\n 'RShoulderRoll': -0.196393966675,\n 'RWristYaw': 0.860532045364,\n 'TorsoAccZ': -0.994837673637,\n 'TorsoX': -0.0542904734612,\n 'TorsoY': -0.181328982115,\n };\n # getPosition_Sitting - end\n @staticmethod\n def getPosition_Crouching():\n \"get the standard crouching position\"\n return {\n 'TorsoX': 0.010472,\n 'TorsoY': -0.066323,\n 'LAnklePitch': -1.193494,\n 'LAnkleRoll': 0.093616,\n 'LHipPitch': -0.774628,\n 'LHipRoll': -0.091998,\n 'LHipYawPitch': -0.237728,\n 'LKneePitch': 2.181306,\n 'RAnklePitch': -1.233294,\n 'RAnkleRoll': -0.102736,\n 'RHipPitch': -0.747100,\n 'RHipRoll': 0.096684,\n 'RKneePitch': 2.187526,\n };\n # getPosition_Crouching - end\n @staticmethod\n def getPosition_LyingBack():\n \"get torsos from lying on his back\"\n return {\n 'TorsoX': 0.015708,\n 'TorsoY': -1.548107,\n };\n # getPosition_LyingBack - end\n @staticmethod\n def getPosition_LyingFront():\n \"get torsos from lying on his front\"\n return {\n 'TorsoX': -0.048869,\n 'TorsoY': 1.338667,\n };\n # getPosition_LyingFront - end\n @staticmethod\n def getPosition_LyingLeft():\n \"get Torsos from lying on his left\"\n return {\n 'TorsoX': -1.361357,\n 'TorsoY': -0.034907,\n };\n # getPosition_LyingLeft - end\n @staticmethod\n def getPosition_LyingRight():\n \"get Torsos from lying on his right\"\n return {\n 'TorsoX': 1.307252,\n 'TorsoY': -0.050615,\n };\n # getPosition_LyingRight - end\n @staticmethod\n def getPosition_HeadDown():\n \"get Torsos head down\"\n return {\n 'TorsoAccZ': 0.890118,\n 'TorsoX': 0.0,\n 'TorsoY': 0.0,\n };\n # getPosition_HeadDown - end\n\n # Various position - funny position\n @staticmethod\n def getPosition_Victory():\n \"Nao's has win, and he is very happy !\"\n return {\n 'TorsoX': 0.001746,\n 'TorsoY': -1.024508,\n 'HeadPitch': -0.786984,\n 'HeadYaw': 0.021434,\n 'LAnklePitch': 0.526120,\n 'LAnkleRoll': 0.325250,\n 'LElbowRoll': -0.338972,\n 'LElbowYaw': -0.348260,\n 'LHipPitch': 0.500126,\n 'LHipRoll': 0.777780,\n 'LHipYawPitch': 0.779314,\n 'LKneePitch': 1.998760,\n 'LShoulderPitch': -0.069072,\n 'LShoulderRoll': 0.635034,\n 'RAnklePitch': 0.823800,\n 'RAnkleRoll': -0.134950,\n 'RElbowRoll': 0.572224,\n 'RElbowYaw': -0.024586,\n 'RHipPitch': 0.503110,\n 'RHipRoll': -0.776162,\n 'RKneePitch': 1.879192,\n 'RShoulderPitch': -0.044444,\n 'RShoulderRoll': -0.767042,\n };\n # getPosition_Victory - end\n @staticmethod\n def getPosition_ExtendedKickRight():\n \"Nao's kick / sun !\"\n return {\n 'HeadPitch': -0.050664,\n 'HeadYaw': -0.079810,\n 'LAnklePitch': -0.102820,\n 'LAnkleRoll': 0.168782,\n 'LElbowRoll': -0.142620,\n 'LElbowYaw': -0.645856,\n 'LHipPitch': 0.104354,\n 'LHipRoll': 0.434164,\n 'LHipYawPitch': -0.170232,\n 'LKneePitch': 0.009162,\n 'LShoulderPitch': 1.052282,\n 'LShoulderRoll': 1.570774,\n 'RAnklePitch': 0.323716,\n 'RAnkleRoll': -0.165630,\n 'RElbowRoll': 0.010780,\n 'RElbowYaw': 0.940300,\n 'RHipPitch': -0.302240,\n 'RHipRoll': -0.740880,\n 'RKneePitch': 0.003110,\n 'RShoulderPitch': 0.833004,\n 'RShoulderRoll': -1.586198,\n 'TorsoAccZ': -0.890118,\n 'TorsoX': -0.523599,\n 'TorsoY': 0.022689,\n };\n # getPosition_ExtendedKickRight - end\n @staticmethod\n def getPosition_SittingFeetUp():\n \"Nao's sit with feet up !\"\n return {\n 'LAnklePitch': -0.661196,\n 'LAnkleRoll': 0.046062,\n 'LElbowRoll': -0.233126,\n 'LElbowYaw': -0.748634,\n 'LHipPitch': -1.464928,\n 'LHipRoll': 0.245482,\n 'LHipYawPitch': -0.498508,\n 'LKneePitch': 0.477032,\n 'LShoulderPitch': 1.576910,\n 'LShoulderRoll': 0.291418,\n 'RAnklePitch': -0.817580,\n 'RAnkleRoll': -0.187106,\n 'RElbowRoll': 0.052198,\n 'RElbowYaw': 0.944902,\n 'RHipPitch': -1.541712,\n 'RHipRoll': -0.064386,\n 'RKneePitch': 0.624380,\n 'RShoulderPitch': 1.580062,\n 'RShoulderRoll': -0.294570,\n 'TorsoX': 0.038397,\n 'TorsoY': -0.041888,\n };\n # getPosition_SittingFeetUp - end\n\n @staticmethod\n def getPosition_SittingFeetUpLegsJoint():\n \"Nao's sit with feet up and legs joint (sage)!\"\n return {\n 'HeadPitch': -0.1, # the head raise a little\n 'HeadYaw': 0.0,\n 'LAnklePitch': -0.251618,\n 'LAnkleRoll': 0.001576,\n 'LElbowRoll': -1.460326,\n 'LElbowYaw': -0.710284,\n 'LHipPitch': -1.463394,\n 'LHipRoll': 0.012314,\n 'LHipYawPitch': 0.032256,\n 'LKneePitch': -0.072140,\n 'LShoulderPitch': 1.533958,\n 'LShoulderRoll': 0.165630,\n 'RAnklePitch': -0.211650,\n 'RAnkleRoll': -0.012230,\n 'RElbowRoll': 1.518702,\n 'RElbowYaw': 0.964844,\n 'RHipPitch': -1.472682,\n 'RHipRoll': -0.030638,\n 'RKneePitch': -0.073590,\n 'RShoulderPitch': 1.596936,\n 'RShoulderRoll': -0.016916,\n 'TorsoAccZ': -1.029744,\n 'TorsoX': 0.043633,\n 'TorsoY': -0.062832,\n };\n # getPosition_SittingFeetUpLegsJoint - end\n\n @staticmethod\n def getPosition_StandingPackShot():\n \"Nao's nice standing (packshot)!\"\n return {\n 'HeadPitch': -0.108956,\n 'HeadYaw': 0.240796,\n 'LAnklePitch': -0.069072,\n 'LAnkleRoll': -0.052114,\n 'LElbowRoll': -0.915756,\n 'LElbowYaw': -1.083046,\n 'LHand': 0.731297,\n 'LHipPitch': 0.493368,\n 'LHipRoll': 0.069072,\n 'LHipYawPitch': -0.213184,\n 'LKneePitch': 0.009162,\n 'LShoulderPitch': 1.472598,\n 'LShoulderRoll': 0.214718,\n 'LWristYaw': -1.578528,\n 'RAnklePitch': -0.245398,\n 'RAnkleRoll': 0.033790,\n 'RElbowRoll': 1.073842,\n 'RElbowYaw': 0.747016,\n 'RHand': 0.044026,\n 'RHipPitch': 0.490954,\n 'RHipRoll': -0.091998,\n 'RKneePitch': 0.136568,\n 'RShoulderPitch': 1.630684,\n 'RShoulderRoll': -0.434164,\n 'RWristYaw': 0.141086,\n 'TorsoAccZ': -1.064651,\n 'TorsoX': 0.001746,\n 'TorsoY': -0.146608,\n };\n # getPosition_StandingPackShot - end\n\n @staticmethod\n def getPosition_StandingWalk():\n \"Nao's standing like before or after walking!\"\n return {\n 'LAnklePitch': -0.458708,\n 'LAnkleRoll': 0.024586,\n 'LElbowRoll': -0.518450,\n 'LElbowYaw': -1.474216,\n 'LHipPitch': -0.472430,\n 'LHipRoll': 0.0,\n 'LHipYawPitch': 0.001576,\n 'LKneePitch': 0.885076,\n 'LShoulderPitch': 1.734912,\n 'LShoulderRoll': 0.256136,\n 'RAnklePitch': -0.490838,\n 'RAnkleRoll': -0.088930,\n 'RElbowRoll': 0.518534,\n 'RElbowYaw': 1.472598,\n 'RHipPitch': -0.490922,\n 'RHipRoll': 0.0,\n 'RKneePitch': 0.908170,\n 'RShoulderPitch': 1.753404,\n 'RShoulderRoll': -0.250084,\n 'TorsoAccZ': -0.977384,\n 'TorsoX': 0.008727,\n 'TorsoY': 0.155334,\n };\n # getPosition_StandingWalk - end\n\n\n @staticmethod\n def getPosition( strPosition ):\n \"get a standard position\"\n \"eg: getPosition( 'Standing' )\"\n methodName = \"getPosition_\" + strPosition;\n try:\n func = getattr( PoseLibrary, methodName );\n except AttributeError:\n print( \"poselibrary::PoseLibrary::isPosition(): ERR: unknown position '%s'\" % strPosition );\n return {};\n return func();\n # getPosition - end\n\n @staticmethod\n def getListPosition():\n \"get the list of position name currently in the library\"\n return [\n 'Standing',\n 'Sitting',\n 'Crouching',\n 'LyingBack',\n 'LyingFront',\n 'LyingLeft',\n 'LyingRight',\n 'HeadDown',\n 'Victory',\n 'ExtendedKickRight',\n 'SittingFeetUp',\n 'SittingFeetUpLegsJoint',\n 'StandingPackShot',\n 'StandingWalk'\n ];\n # getPosition - end\n\n @staticmethod\n def isPosition( strPosition ):\n \"are we in a specific position?\"\n \"eg: isPosition( 'Standing' )\"\n return PoseLibrary.comparePosition( PoseLibrary.getPosition( strPosition ) ) < 0.1;\n # isPosition - end\n \n @staticmethod\n def mirror( aListPosition ):\n \"compute a mirror of a specific position (flip)\"\n \"return the flipped position\"\n listRet = {};\n for k, v in aListPosition.iteritems(): \n if( k[0] == 'L' ):\n k = 'R' + k[1:];\n elif( k[0] == 'R' ):\n k = 'L' + k[1:];\n else:\n if( 'Yaw' in k ):\n v = -v;\n if( 'ElbowRoll' in k or 'ElbowYaw' in k or 'WristYaw' in k or 'AnkleRoll' in k or 'ShoulderRoll' in k or 'HipRoll' in k ):\n v = -v;\n listRet[k] = v;\n return listRet;\n # mirror - end\n\n @staticmethod\n def findNearestPosition( aListPosition = None, aListGroupToIgnore = [] ):\n \"find nearest position between some known or specific position\"\n \"aListPosition is a mixed type list: eg: [ 'Sitting', 'Standing', {'TorsoX': 0.005236, 'TorsoY': 0.001745 } ]\"\n \"aListGroupToIgnore is a mixed type list of joint or group to ignore for comparison\"\n \"return an array [position, distance to this position, name of position (if this position has a name)]\"\n if( aListPosition == None ):\n aListPosition = PoseLibrary.getListPosition();\n rDistMin = 1000.0;\n strNameMin = \"\";\n posMin = dict();\n for pos in aListPosition:\n strName = \"\";\n if( typetools.isString( pos ) ):\n strName = pos;\n pos = PoseLibrary.getPosition( strName );\n rDist = PoseLibrary.comparePosition( pos, aListGroupToIgnore ); # here it's not optimal, at every call we will compute the current position\n# print( \"rDist: %f\" % rDist );\n if( rDist < rDistMin ):\n rDistMin = rDist;\n strNameMin = strName;\n posMin = pos;\n debug.debug( \"findNearestPosition between %s:\" % aListPosition );\n debug.debug( \"posMin: %s\\ndistMin: %f\\nName: '%s'\" % ( str( posMin), rDistMin, strNameMin ) );\n return [ posMin, rDistMin, strNameMin ];\n # findNearestPosition - end\n\n @staticmethod\n def exportToXar( aPos, rTime = 0.0 ):\n \"Export a specifig position to a xar\"\n \"the name of the xar is returned\"\n \"eg: exportToXar( getPosition( 'Standing' ) )\"\n\n # On charge un sample, et on va juste poker notre liste de clés au milieu\n bError = False;\n file = False;\n try:\n file = open( getApplicationSharedPath() + \"PoseLibrary_sample.xar\", 'r' );\n strBufferSample = file.read();\n except:\n bError = True;\n finally:\n if( file ):\n file.close();\n if( bError ):\n print( \"PoseLibrary:exportToXar: read file error\" );\n return None;\n\n strListPose = \"\\n\" % len( aPos );\n strListPose += \"\\n\";\n strListPose += \" keyframe%d\\n\" % 1;\n strListPose += \" %d\\n\" % ( 25 + int( rTime / 25 ) ); # we act as if running at 25 fps\n strListPose += \" 1\\n\";\n strListPose += \" \\n\";\n for k, v in aPos.iteritems():\n if( k.find( \"Torso\" ) == -1 ):\n strListPose += \" \\n\";\n strListPose += \" %s\\n\" % k;\n strListPose += \" %5.6f\\n\" % ( v * 180 / math.pi );\n strListPose += \" \\n\";\n strListPose += \" \\n\";\n strListPose += \"\\n\";\n\n strBufferSample = strBufferSample % strListPose;\n strFilename = \"/home/nao/PoseLibrary_exported_%d.xar\" % time.clock();\n print( \"PoseLibrary.exportToXar: outputting position to %s\" % strFilename );\n try:\n file = open( strFilename, 'w' );\n file.write( strBufferSample );\n file.close();\n except:\n print( \"PoseLibrary:exportToXar: write file error\" ); \n return None;\n return strFilename;\n # exportToXar - end\n \n @staticmethod\n def interpolateCrouchStand( rRatio = 0.5, rTimeSec = 1.4, bWaitEnd = True ):\n \"\"\"\n (incidently it put NAO's head to a specific height)\n interpolateCrouchStand( 1. ) => NAO is fully stand (knee completely 'tense') (straight legs)\n interpolateCrouchStand( 0. ) => NAO is crouched (you could unstiffness him)\n \"\"\"\n newPos = PoseLibrary.interpolatePosition( PoseLibrary.getPosition_Crouching(), PoseLibrary.getPosition_Standing(), rRatio );\n return PoseLibrary.setPosition( newPos, rTimeSec = rTimeSec, bWaitEnd = bWaitEnd );\n # interpolateCrouchStand - end \n\n# class PoseLibrary - end\n\nself = PoseLibrary(); # overwrite whole module by this class\n\ndef autoTest():\n # PoseLibrary Test Zone:\n test.activateAutoTestOption();\n if( False ):\n print( PoseLibrary.getCurrentPosition() );\n print( \"PoseLibrary.isPosition : %d\" % PoseLibrary.isPosition( \"Standing\" ) );\n PoseLibrary.setPosition( PoseLibrary.getPosition( \"Standing\" ) );\n print( \"PoseLibrary.getPos: %s\" % stringtools.dictionnaryToString( PoseLibrary.filterPosition( PoseLibrary.getCurrentPosition(), [\"Arms\"] ) ) );\n print( \"PoseLibrary.getPos: %s\" % stringtools.dictionnaryToString( PoseLibrary.filterPosition( PoseLibrary.getCurrentPosition(), [\"UpperBody\", \"Torsos\"] ) ) ); # remove all but legs\n print( \"PoseLibrary.getPos: %s\" % stringtools.dictionnaryToString( PoseLibrary.filterPosition( PoseLibrary.getCurrentPosition(), [\"Body\"] ) ) );\n PoseLibrary.exportToXar( PoseLibrary.getPosition( 'Standing' ) );\n print( PoseLibrary.positionToString( PoseLibrary.getPosition( 'Standing' ) ) );\n print( PoseLibrary.findNearestPosition( [ 'Sitting', 'Standing', {'TorsoX': 0.5, 'TorsoY': 0.5} ] ) );\n print( PoseLibrary.findNearestPosition( [ 'Standing', 'HeadDown' ]) );\n print( PoseLibrary.findNearestPosition() );\n print( \"Current Pos: \" + PoseLibrary.positionToString( PoseLibrary.getCurrentPosition() ) );\n PoseLibrary.getDifferentJoints( PoseLibrary.getPosition( 'Standing' ) );\n PoseLibrary.getDifferentJoints( PoseLibrary.getPosition( 'Sitting' ) );\n PoseLibrary.setPosition( PoseLibrary.getPosition( \"Sitting\" ) );\n print( \"All joints name: \" + str( PoseLibrary.getListJoints( [\"Body\"] ) ) );\n print( \"All joints limits: \" + str( PoseLibrary.getGroupLimits( [\"Body\"], 0.5, True ) ) );\n\n listPos = PoseLibrary.getCurrentPosition()\n listPos = PoseLibrary.mirror( listPos );\n PoseLibrary.setPosition( listPos );\n\n listPos = PoseLibrary.interpolateTrackingEmotion( [0,0,0,0,0,0], [-0.5,0.], 0.1 );\n print( \"interpolateTrackingEmotion, ret: \" + str( listPos ) );\n print( \"interpolateTrackingEmotion, ret: LShoulderPitch: %5.2f\" % listPos['LShoulderPitch'] );\n PoseLibrary.setPosition( listPos );\n \n \n listPos = PoseLibrary.getCurrentPosition()\n listPos = PoseLibrary.mirror( listPos );\n PoseLibrary.setPosition( listPos, bDontUseLegs = False );\n# autoTest - end\n\n#autoTest();","sub_path":"Naoassistant-auido-streaming/abcdk/poselibrary.py","file_name":"poselibrary.py","file_ext":"py","file_size_in_byte":43156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"9160204","text":"import operator\nimport math\nfrom ROOT import TLorentzVector, Double\nfrom CMGTools.RootTools.fwlite.Analyzer import Analyzer\nfrom CMGTools.RootTools.analyzers.DiLeptonAnalyzer import DiLeptonAnalyzer\nfrom CMGTools.RootTools.fwlite.AutoHandle import AutoHandle\nfrom CMGTools.RootTools.statistics.Counter import Counter, Counters\nfrom CMGTools.RootTools.physicsobjects.PhysicsObjects import Muon, Tau, GenParticle, Jet\nfrom CMGTools.RootTools.physicsobjects.HTauTauElectron import HTauTauElectron as Electron\nfrom CMGTools.RootTools.utils.DeltaR import cleanObjectCollection, matchObjectCollection, bestMatch\nfrom CMGTools.RootTools.utils.TriggerMatching import triggerMatched\n\n\n####################################################################3\n#\n# 11 Nov 2013 Y.Takahashi\n# This analyzer is for WH, EMuTau-channel\n#\n####################################################################3\n\nclass WHMMTAnalyzer(Analyzer):\n\n # Class needed for the object selections\n LeptonClass = Muon\n OtherLeptonClass = Electron\n TauClass = Tau\n\n\n # Init\n def __init__(self, cfg_ana, cfg_comp, looperName):\n# print 'Init for the WHMMTAnalyzer'\n super(WHMMTAnalyzer,self).__init__(cfg_ana, cfg_comp, looperName)\n\n\n # beginLoop\n def beginLoop(self):\n# print 'Init for the beginLoop'\n super(WHMMTAnalyzer, self).beginLoop()\n self.counters.addCounter('MMT')\n count = self.counters.counter('MMT')\n count.register('all events')\n count.register('step1')\n count.register('step2')\n count.register('step3')\n \n def declareHandles(self):\n super(WHMMTAnalyzer, self).declareHandles()\n\n self.handles['electrons'] = AutoHandle(\n ('cmgElectronSel','','PAT'), 'std::vector')\n\n\n self.handles['muons'] = AutoHandle(\n ('cmgMuonSel','','PAT'), 'std::vector')\n\n\n self.handles['jets'] = AutoHandle( 'cmgPFJetSel',\n 'std::vector' )\n\n self.handles['taus'] = AutoHandle(\n# ('cmgTauSel','','PAT'), 'std::vector')\n# ('cmgTauSel','','MUTAUTAU'), 'std::vector')\n# ('cmgTauSel','','DIMUTAU'), 'std::vector')\n ('cmgTauSel','','DIMUTAU'), 'std::vector', fallbackLabel=('cmgTauSel','','MUTAUTAU'))\n\n\n\n\n\n\n # Muon\n #################################################\n \n def buildLooseLeptons(self, cmgLeptons, event):\n '''Build loose muons'''\n\n leptons = []\n \n for index, lep in enumerate(cmgLeptons):\n\n pyl = self.__class__.LeptonClass(lep)\n pyl.associatedVertex = event.goodVertices[0]\n pyl.flag_id = False\n pyl.flag_iso = False\n pyl.trig_match = False\n\n if pyl.pt() > 10. and abs(pyl.eta()) < 2.4 and \\\n pyl.looseId() and abs(pyl.dz()) < 0.2 and \\\n pyl.sourcePtr().innerTrack().hitPattern().numberOfValidPixelHits()>0:\n\n leptons.append( pyl )\n \n return leptons\n\n def muid(self, pyl):\n '''check muon ID'''\n return pyl.tightId()\n\n\n def muiso(self, pyl):\n '''check muon isolation'''\n\n relIso = False\n if abs(pyl.eta()) < 1.479 and self.testLeg2Iso(pyl, 0.15):\n relIso = True\n if abs(pyl.eta()) > 1.479 and self.testLeg2Iso(pyl, 0.1):\n relIso = True\n\n return relIso\n\n\n def buildVetoLeptons(self, cmgLeptons, event):\n '''Build muons'''\n\n leptons = []\n for index, lep in enumerate(cmgLeptons):\n pyl = self.__class__.LeptonClass(lep)\n pyl.associatedVertex = event.goodVertices[0]\n\n if pyl.pt() > 5. and abs(pyl.eta()) < 2.3 and \\\n self.muid(pyl) and abs(pyl.dz()) < 0.2 and self.testLeg2Iso(pyl, 0.15) and abs(pyl.dB3D()) < 0.2:\n\n leptons.append( pyl )\n \n return leptons\n\n\n\n\n # Electron\n #################################################\n\n def buildLooseOtherLeptons(self, cmgOtherLeptons, event):\n '''Build loose electrons'''\n\n otherLeptons = []\n\n for index, lep in enumerate(cmgOtherLeptons):\n pyl = self.__class__.OtherLeptonClass(lep)\n pyl.associatedVertex = event.goodVertices[0]\n pyl.flag_id = False\n pyl.flag_iso = False\n pyl.trig_match = False\n \n if pyl.pt() > 10. and abs(pyl.eta()) < 2.5 and \\\n pyl.loosestIdForTriLeptonVeto() and abs(pyl.dz()) < 0.2 and pyl.sourcePtr().isGsfCtfScPixChargeConsistent():\n \n otherLeptons.append( pyl )\n\n return otherLeptons\n\n def eid(self, pyl):\n '''check electron ID'''\n return pyl.mvaForLeptonVeto()\n\n\n def eiso(self, pyl):\n '''check electron ID'''\n\n relIso = False\n if abs(pyl.eta()) < 1.479 and self.testLeg2Iso(pyl, 0.15):\n relIso = True\n if abs(pyl.eta()) > 1.479 and self.testLeg2Iso(pyl, 0.1):\n relIso = True\n \n return relIso\n\n\n def buildVetoOtherLeptons(self, cmgOtherLeptons, event):\n '''Build electrons for third lepton veto, associate best vertex.\n '''\n otherLeptons = []\n for index, lep in enumerate(cmgOtherLeptons):\n pyl = self.__class__.OtherLeptonClass(lep)\n pyl.associatedVertex = event.goodVertices[0]\n\n if pyl.pt() > 10. and abs(pyl.eta()) < 2.5 and \\\n pyl.mvaForLeptonVeto() and abs(pyl.dz()) < 0.2 and self.testLeg2Iso(pyl, 0.3):\n\n otherLeptons.append( pyl )\n\n return otherLeptons\n\n\n\n\n # Tau\n #################################################\n\n def buildLooseTau(self, cmgLeptons, event):\n '''Build taus.'''\n leptons = []\n \n for index, lep in enumerate(cmgLeptons):\n pyl = self.__class__.TauClass(lep)\n pyl.associatedVertex = event.goodVertices[0]\n pyl.flag_id = False\n pyl.flag_iso = False\n pyl.decaymode = -999\n pyl.ep = -999\n pyl.againstELooseArmin = False\n pyl.againstETight = False\n pyl.againstELoose = False\n pyl.againstEMedium = False\n pyl.againstE2Loose = False\n pyl.againstE2Medium = False\n# pyl.againstE0Loose = False\n# pyl.againstE0Medium = False\n pyl.againstERaw = -999\n pyl.againstE2Raw = -999\n pyl.againstE0Raw = -999\n pyl.againstECat = -999\n pyl.againstE2Cat = -999\n# pyl.againstE0Cat = -999\n pyl.againstMuLoose = False\n pyl.againstMuTight = False\n pyl.mvaisolation = -999\n pyl.mvaisolation_loose = False\n pyl.dBisolation = -999\n\n\n ### new tau ID ###\n\n pyl.byLooseCombinedIsolationDeltaBetaCorr3Hits = False\n pyl.byMediumCombinedIsolationDeltaBetaCorr3Hits = False\n pyl.byTightCombinedIsolationDeltaBetaCorr3Hits = False\n pyl.byCombinedIsolationDeltaBetaCorrRaw3Hits = -999\n pyl.againstMuonLoose2 = False\n pyl.againstMuonMedium2 = False\n pyl.againstMuonTight2 = False\n pyl.againstElectronMVA5category = False\n pyl.againstElectronLooseMVA5 = False\n pyl.againstElectronMediumMVA5 = False\n pyl.againstElectronTightMVA5 = False\n pyl.againstElectronVTightMVA5 = False\n pyl.againstMuonLoose3 = False\n pyl.againstMuonTight3 = False\n pyl.againstMuonMVALoose = False\n pyl.againstMuonMVAMedium = False\n pyl.againstMuonMVATight = False\n pyl.againstMuonMVARaw = -999\n pyl.byIsolationMVA3oldDMwoLTraw = -999\n pyl.byLooseIsolationMVA3oldDMwoLT = False\n pyl.byMediumIsolationMVA3oldDMwoLT = False\n pyl.byTightIsolationMVA3oldDMwoLT = False\n pyl.byVTightIsolationMVA3oldDMwoLT = False\n pyl.byVVTightIsolationMVA3oldDMwoLT = False\n pyl.byIsolationMVA3oldDMwLTraw = -999\n pyl.byLooseIsolationMVA3oldDMwLT = False\n pyl.byMediumIsolationMVA3oldDMwLT = False\n pyl.byTightIsolationMVA3oldDMwLT = False\n pyl.byVTightIsolationMVA3oldDMwLT = False\n pyl.byVVTightIsolationMVA3oldDMwLT = False\n pyl.byIsolationMVA3newDMwoLTraw = -999\n pyl.byLooseIsolationMVA3newDMwoLT = False\n pyl.byMediumIsolationMVA3newDMwoLT = False\n pyl.byTightIsolationMVA3newDMwoLT = False\n pyl.byVTightIsolationMVA3newDMwoLT = False\n pyl.byVVTightIsolationMVA3newDMwoLT = False\n pyl.byIsolationMVA3newDMwLTraw = -999\n pyl.byLooseIsolationMVA3newDMwLT = False\n pyl.byMediumIsolationMVA3newDMwLT = False\n pyl.byTightIsolationMVA3newDMwLT = False\n pyl.byVTightIsolationMVA3newDMwLT = False\n pyl.byVVTightIsolationMVA3newDMwLT = False\n\n\n # old tau ID\n \n pyl.decayModeFinding = False\n pyl.byVLooseCombinedIsolationDeltaBetaCorr = False\n pyl.byLooseCombinedIsolationDeltaBetaCorr = False\n pyl.byMediumCombinedIsolationDeltaBetaCorr = False\n pyl.byTightCombinedIsolationDeltaBetaCorr = False\n pyl.againstElectronLoose = False\n pyl.againstElectronMedium = False\n pyl.againstElectronTight = False\n pyl.againstElectronDeadECAL = False\n pyl.againstMuonLoose = False\n pyl.againstMuonMedium = False\n pyl.againstMuonTight = False\n\n\n \n\n if pyl.pt() > 20 and abs(pyl.eta()) < 2.3 and \\\n pyl.tauID(\"decayModeFinding\") and abs(pyl.dz()) < 0.2:\n \n leptons.append( pyl ) \n\n return leptons\n\n\n def tauid(self, pyl):\n '''check tau ID.'''\n\n# print 'inside_check', pyl.tauID(\"againstMuonLoose\"), pyl.tauID(\"againstElectronLooseMVA3\")\n if pyl.tauID(\"againstMuonLoose\") > 0.5 and pyl.tauID(\"againstElectronLooseMVA3\"):\n# print 'This becomes true !!'\n return True\n else: \n return False\n\n\n def tauiso(self, pyl):\n '''check tau isolation.'''\n\n return self.testLeg1Iso(pyl, None)\n\n\n \n def buildVetoTau(self, cmgLeptons, event):\n '''Build taus.'''\n leptons = []\n\n for index, lep in enumerate(cmgLeptons):\n pyl = self.__class__.TauClass(lep)\n pyl.associatedVertex = event.goodVertices[0]\n\n if pyl.pt() > 20 and abs(pyl.eta()) < 2.5 and \\\n pyl.tauID(\"decayModeFinding\") and self.testLeg1Iso(pyl, None) and abs(pyl.dz()) < 0.2:\n\n leptons.append( pyl )\n\n return leptons\n\n\n\n\n # process\n #####################################################\n\n def process(self, iEvent, event):\n\n# print 'process ongoing!'\n# import pdb; pdb.set_trace()\n\t\n#\timport pdb; pdb.set_trace()\n self.readCollections(iEvent)\n self.counters.counter('MMT').inc('all events')\n \n event.muoncand = self.buildLooseLeptons(self.handles['muons'].product(), event)\n event.electroncand = self.buildLooseOtherLeptons(self.handles['electrons'].product(), event)\n event.taucand = self.buildLooseTau(self.handles['taus'].product(), event)\n\n cmgJets = self.handles['jets'].product()\n\n event.CSVjet = []\n\n for cmgJet in cmgJets:\n jet = Jet( cmgJet )\n if self.testVetoBJet(jet):\n event.CSVjet.append(jet)\n\n\n event.electroncand, dummpy = cleanObjectCollection(event.electroncand,\n masks = event.muoncand,\n deltaRMin = 0.5)\n\n \n \n # CSV veto\n electroncand_removebjet = []\n muoncand_removebjet = []\n \n for ielectron in event.electroncand:\n bm, dr2min = bestMatch(ielectron, event.CSVjet)\n if dr2min > 0.25:\n electroncand_removebjet.append(ielectron)\n\n for imuon in event.muoncand:\n bm, dr2min = bestMatch(imuon, event.CSVjet)\n if dr2min > 0.25:\n muoncand_removebjet.append(imuon)\n\n event.electroncand = electroncand_removebjet\n event.muoncand = muoncand_removebjet\n \n \n# event.flag_trigmatched = False\n# \n\n\n# if not event.flag_trigmatched:\n# return False\n\n \n# event.cleanelectron = []\n# event.cleanmuon = []\n\n\n\n for ii in event.electroncand: \n ii.flag_id = self.eid(ii)\n ii.flag_iso = self.eiso(ii)\n\n# ii.trig_match = True\n\n if hasattr(event, 'hltPath'):\n if self.triggerCheck(event, event.hltPath, ii):\n ii.trig_match = True\n# if hasattr(event, 'hltPaths'):\n# if self.triggerCheck(event, event.hltPaths, ii):\n# ii.trig_match = True\n\n\n#\n# for jj in event.muoncand:\n# if self.returnMass(jj, ii) > 20. and \\\n# ii.charge()*jj.charge()==1. and \\\n# self.returnDR(ii, jj) > 0.5:\n#\n# flag_add = True\n#\n# if flag_add:\n# ii.flag_id = self.eid(ii)\n# ii.flag_iso = self.eiso(ii)\n# event.cleanelectron.append(ii)\n#\n#\n#\n for ii in event.muoncand:\n ii.flag_id = self.muid(ii)\n ii.flag_iso = self.muiso(ii)\n\n\n# ii.trig_match = True\n# if hasattr(event, 'hltPaths'):\n# if self.triggerCheck(event, event.hltPaths, ii):\n# ii.trig_match = True\n\n if hasattr(event, 'hltPath'):\n if self.triggerCheck(event, event.hltPath, ii):\n ii.trig_match = True\n\n\n# continue\n# \n# for jj in event.electroncand:\n# if self.returnMass(jj, ii) > 20. and \\\n# ii.charge()*jj.charge()==1. and \\\n# self.returnDR(ii, jj) > 0.5:\n#\n# flag_add = True\n#\n# if flag_add:\n# ii.flag_id = self.muid(ii)\n# ii.flag_iso = self.muiso(ii)\n# event.cleanmuon.append(ii)\n\n\n\n# event.electroncand = event.cleanelectron\n# event.muoncand = event.cleanmuon\n\n \n\n\n# idiso_electron = [ie for ie in event.electroncand if self.eid(ie) and self.eiso(ie)]\n# idiso_muon = [im for im in event.muoncand if self.muid(im) and self.muiso(im)]\n\n# if idiso_electron[0].pt() > idiso_muon[0].pt():\n \n\n\n# if not (len(event.muoncand)>=1 and len(event.electroncand)>=1 and len(event.taucand)>=1):\n# print 'YCheck : (m,e,t) = ', len(event.muoncand), len(event.electroncand), len(event.taucand)\n# return False\n\n \n# lepton1 = [] # Leading lepton\n# lepton2 = [] # 2nd leading lepton\n\n\n# if not (len(id_electron)>=1 and len(id_muon)>=1):\n# return False\n \n\n# lepton_type = ''\n#\n# if id_electron[0].pt() > id_muon[0].pt(): #e-mu\n# lepton1 = [ie for ie in id_electron if ie.pt() > 20.]\n# lepton2 = [im for im in id_muon if im.pt() > 10.]\n# lepton_type = 'electron'\n# elif id_electron[0].pt() < id_muon[0].pt():\n# lepton1 = [im for im in id_muon if im.pt() > 20.]\n# lepton2 = [ie for ie in id_electron if ie.pt() > 10.]\n# lepton_type = 'muon'\n\n\n\n# import pdb; pdb.set_trace() \n# if not (len(lepton1)==1 and len(lepton2)==1):\n# return False\n\n# self.counters.counter('MMT').inc('1mu + 1e')\n# \n#\n# event.muon = ''\n# event.electron = ''\n# \n# if lepton_type=='muon':\n# event.muon = lepton1[0]\n# event.electron = lepton2[0]\n# elif lepton_type=='electron':\n# event.electron = lepton1[0]\n# event.muon = lepton2[0]\n\n\n\n\n event.loosetau = []\n\n for itau in event.taucand:\n\n itau.decaymode = itau.decayMode()\n itau.ep = itau.calcEOverP()\n itau.flag_iso = self.tauiso(itau)\n itau.flag_id = self.tauid(itau)\n\n itau.againstERaw = itau.tauID('againstElectronMVA3raw')\n itau.againstE2Raw = itau.tauID('againstElectronMVA2raw')\n itau.againstE0Raw = itau.tauID('againstElectronMVA')\n itau.againstECat = int(round(itau.tauID('againstElectronMVA3category')))\n itau.againstE2Cat = int(round(itau.tauID('againstElectronMVA2category')))\n# itau.againstE0Cat = int(round(itau.tauID('againstElectronMVAcategory')))\n itau.againstELooseArmin = itau.tauID(\"againstElectronLoose\")\n itau.againstETight = itau.tauID(\"againstElectronTightMVA3\")\n itau.againstELoose = itau.tauID(\"againstElectronLooseMVA3\")\n itau.againstEMedium = itau.tauID(\"againstElectronMediumMVA3\")\n itau.againstE2Loose = itau.tauID(\"againstElectronLooseMVA2\")\n itau.againstE2Medium = itau.tauID(\"againstElectronMediumMVA2\")\n# itau.againstE0Loose = itau.tauID(\"againstElectronLooseMVA\")\n# itau.againstE0Medium = itau.tauID(\"againstElectronMediumMVA\")\n itau.againstMuLoose = itau.tauID(\"againstMuonLoose\")\n itau.againstMuTight = itau.tauID(\"againstMuonTight\")\n itau.dBisolation = itau.tauID(\"byCombinedIsolationDeltaBetaCorrRaw3Hits\")\n itau.mvaisolation = itau.tauID(\"byRawIsoMVA\")\n itau.mvaisolation_loose = itau.tauID('byLooseIsoMVA')\n\n # new tau ID \n itau.byLooseCombinedIsolationDeltaBetaCorr3Hits = itau.tauID(\"byLooseCombinedIsolationDeltaBetaCorr3Hits\")\n itau.byMediumCombinedIsolationDeltaBetaCorr3Hits = itau.tauID(\"byMediumCombinedIsolationDeltaBetaCorr3Hits\")\n itau.byTightCombinedIsolationDeltaBetaCorr3Hits = itau.tauID(\"byTightCombinedIsolationDeltaBetaCorr3Hits\")\n itau.byCombinedIsolationDeltaBetaCorrRaw3Hits = itau.tauID(\"byCombinedIsolationDeltaBetaCorrRaw3Hits\")\n itau.againstMuonLoose2 = itau.tauID(\"againstMuonLoose2\")\n itau.againstMuonMedium2 = itau.tauID(\"againstMuonMedium2\")\n itau.againstMuonTight2 = itau.tauID(\"againstMuonTight2\")\n itau.againstElectronMVA5category = itau.tauID(\"againstElectronMVA5category\")\n itau.againstElectronLooseMVA5 = itau.tauID(\"againstElectronLooseMVA5\")\n itau.againstElectronMediumMVA5 = itau.tauID(\"againstElectronMediumMVA5\")\n itau.againstElectronTightMVA5 = itau.tauID(\"againstElectronTightMVA5\")\n itau.againstElectronVTightMVA5 = itau.tauID(\"againstElectronVTightMVA5\")\n itau.againstMuonLoose3 = itau.tauID(\"againstMuonLoose3\")\n itau.againstMuonTight3 = itau.tauID(\"againstMuonTight3\")\n itau.againstMuonMVALoose = itau.tauID(\"againstMuonMVALoose\")\n itau.againstMuonMVAMedium = itau.tauID(\"againstMuonMVAMedium\")\n itau.againstMuonMVATight = itau.tauID(\"againstMuonMVATight\")\n itau.againstMuonMVARaw = itau.tauID(\"againstMuonMVARaw\")\n itau.byIsolationMVA3oldDMwoLTraw = itau.tauID(\"byIsolationMVA3oldDMwoLTraw\")\n itau.byLooseIsolationMVA3oldDMwoLT = itau.tauID(\"byLooseIsolationMVA3oldDMwoLT\")\n itau.byMediumIsolationMVA3oldDMwoLT = itau.tauID(\"byMediumIsolationMVA3oldDMwoLT\")\n itau.byTightIsolationMVA3oldDMwoLT = itau.tauID(\"byTightIsolationMVA3oldDMwoLT\")\n itau.byVTightIsolationMVA3oldDMwoLT = itau.tauID(\"byVTightIsolationMVA3oldDMwoLT\")\n itau.byVVTightIsolationMVA3oldDMwoLT = itau.tauID(\"byVVTightIsolationMVA3oldDMwoLT\")\n itau.byIsolationMVA3oldDMwLTraw = itau.tauID(\"byIsolationMVA3oldDMwLTraw\")\n itau.byLooseIsolationMVA3oldDMwLT = itau.tauID(\"byLooseIsolationMVA3oldDMwLT\")\n itau.byMediumIsolationMVA3oldDMwLT = itau.tauID(\"byMediumIsolationMVA3oldDMwLT\")\n itau.byTightIsolationMVA3oldDMwLT = itau.tauID(\"byTightIsolationMVA3oldDMwLT\")\n itau.byVTightIsolationMVA3oldDMwLT = itau.tauID(\"byVTightIsolationMVA3oldDMwLT\")\n itau.byVVTightIsolationMVA3oldDMwLT = itau.tauID(\"byVVTightIsolationMVA3oldDMwLT\")\n itau.byIsolationMVA3newDMwoLTraw = itau.tauID(\"byIsolationMVA3newDMwoLTraw\")\n itau.byLooseIsolationMVA3newDMwoLT = itau.tauID(\"byLooseIsolationMVA3newDMwoLT\")\n itau.byMediumIsolationMVA3newDMwoLT = itau.tauID(\"byMediumIsolationMVA3newDMwoLT\")\n itau.byTightIsolationMVA3newDMwoLT = itau.tauID(\"byTightIsolationMVA3newDMwoLT\")\n itau.byVTightIsolationMVA3newDMwoLT = itau.tauID(\"byVTightIsolationMVA3newDMwoLT\")\n itau.byVVTightIsolationMVA3newDMwoLT = itau.tauID(\"byVVTightIsolationMVA3newDMwoLT\")\n itau.byIsolationMVA3newDMwLTraw = itau.tauID(\"byIsolationMVA3newDMwLTraw\")\n itau.byLooseIsolationMVA3newDMwLT = itau.tauID(\"byLooseIsolationMVA3newDMwLT\")\n itau.byMediumIsolationMVA3newDMwLT = itau.tauID(\"byMediumIsolationMVA3newDMwLT\")\n itau.byTightIsolationMVA3newDMwLT = itau.tauID(\"byTightIsolationMVA3newDMwLT\")\n itau.byVTightIsolationMVA3newDMwLT = itau.tauID(\"byVTightIsolationMVA3newDMwLT\")\n itau.byVVTightIsolationMVA3newDMwLT = itau.tauID(\"byVVTightIsolationMVA3newDMwLT\")\n\n # old tau ID\n\n itau.decayModeFinding = itau.tauID(\"decayModeFinding\")\n itau.byVLooseCombinedIsolationDeltaBetaCorr = itau.tauID(\"byVLooseCombinedIsolationDeltaBetaCorr\")\n itau.byLooseCombinedIsolationDeltaBetaCorr = itau.tauID(\"byLooseCombinedIsolationDeltaBetaCorr\")\n itau.byMediumCombinedIsolationDeltaBetaCorr = itau.tauID(\"byMediumCombinedIsolationDeltaBetaCorr\")\n itau.byTightCombinedIsolationDeltaBetaCorr = itau.tauID(\"byTightCombinedIsolationDeltaBetaCorr\")\n itau.againstElectronLoose = itau.tauID(\"againstElectronLoose\")\n itau.againstElectronMedium = itau.tauID(\"againstElectronMedium\")\n itau.againstElectronTight = itau.tauID(\"againstElectronTight\")\n itau.againstElectronDeadECAL = itau.tauID(\"againstElectronDeadECAL\")\n itau.againstMuonLoose = itau.tauID(\"againstMuonLoose\")\n itau.againstMuonMedium = itau.tauID(\"againstMuonMedium\")\n itau.againstMuonTight = itau.tauID(\"againstMuonTight\")\n\n\n\n\n# print 'dB, raw, loose', itau.tauID(\"byCombinedIsolationDeltaBetaCorrRaw3Hits\"), itau.tauID(\"byRawIsoMVA\"), itau.tauID('byLooseIsoMVA')\n# print 'ID_check', itau.tauID(\"againstMuonLoose\"), itau.tauID(\"againstElectronLooseMVA3\")\n# print 'mu_loose, e_loose, e_medium', itau.tauID(\"againstMuonLoose\"), itau.tauID(\"againstElectronLooseMVA3\"), itau.tauID(\"againstElectronMediumMVA3\"), itau.flag_id\n \n# if flag_mu_mass and and \\\n# ((itau.decayMode()==0 and itau.calcEOverP() > 0.2) or (itau.decayMode()!=0)):\n# itau.flag_id = True\n#\n# \n# if flag_e_mass==False and flag_mu_mass==False and self.tauid(itau):\n# itau.flag_id = True\n\n\n\n\n\n# flag_e_overlap = False\n# flag_e_mass = False\n#\n# for ii in idiso_electron:\n# mass_et = self.returnMass(ii, itau)\n# if mass_et > 71.2 and mass_et < 111.2:\n# flag_e_mass = True\n# \n# if self.returnDR(itau, ii) < 0.5:\n# flag_e_overlap = True\n#\n# if flag_e_overlap:\n# continue\n# \n#\n# flag_mu_overlap = False\n# flag_mu_mass = False\n#\n# for ii in idiso_muon:\n# mass_mt = self.returnMass(ii, itau)\n# if mass_mt > 71.2 and mass_mt < 111.2:\n# flag_mu_mass = True\n# \n# if self.returnDR(itau, ii) < 0.5:\n# flag_mu_overlap = True\n#\n# if flag_mu_overlap:\n# continue\n\n\n# if self.tauiso(itau):\n# itau.flag_iso = True\n#\n# \n# if flag_e_mass and itau.tauID(\"againstElectronMediumMVA3\"):\n# itau.flag_id = True\n#\n#\n# if flag_mu_mass and itau.tauID(\"againstMuonTight\") and \\\n# ((itau.decayMode()==0 and itau.calcEOverP() > 0.2) or (itau.decayMode()!=0)):\n# itau.flag_id = True\n#\n# \n# if flag_e_mass==False and flag_mu_mass==False and self.tauid(itau):\n# itau.flag_id = True\n\n\n event.loosetau.append(itau)\n\n\n event.taucand = event.loosetau\n\n # Additional tau veto\n event.vetotaucand = self.buildVetoTau(self.handles['taus'].product(), event)\n event.vetomuoncand = self.buildVetoLeptons(self.handles['muons'].product(), event)\n event.vetoelectroncand = self.buildVetoOtherLeptons(self.handles['electrons'].product(), event)\n\n flag_plus = 0\n flag_minus = 0\n \n for im in event.muoncand:\n if im.charge()==1:\n flag_plus +=1\n else:\n flag_minus +=1\n\n\n self.counters.counter('MMT').inc('step1')\n \n if not (flag_plus >= 2 or flag_minus >= 2):\n return False\n\n self.counters.counter('MMT').inc('step2')\n\n if not (len(event.muoncand)>=2 and len(event.taucand)>=1):\n# if not (len(event.taucand)>=1 and len(event.muoncand)>=1 and len(event.electroncand)>=1):\n return False\n\n self.counters.counter('MMT').inc('step3')\n\n# idiso_tau = [it for it in event.taucand if (it.flag_id and it.flag_iso)]\n# if not len(idiso_tau)>=1 :\n# return False\n\n\n\n\n\n# if not len(lepton3) == 1:\n# return False\n\n# self.counters.counter('MMT').inc('1 e/mu/tau')\n# event.tau = lepton3[0]\n\n\n\n\n# event.M_l2t = self.returnMass(lepton2[0], event.tau)\n\n# if self.returnMass(event.muon, event.electron) < 20.:\n# return False\n# if self.returnMass(lepton2[0], event.tau) < 20.:\n# return False\n\n \n\n # charge requirement\n # SS for two light leptons\n\n# if event.electron.charge()*event.muon.charge()==-1.:\n# return False\n\n\n# if event.tau.charge()*event.muon.charge()!=-1.:\n# return False\n\n\n # dR separation \n# if self.returnDR(event.tau, event.muon) < 0.5:\n# return False\n# if self.returnDR(event.tau, event.electron) < 0.5:\n# return False\n# if self.returnDR(event.electron, event.muon) < 0.5:\n# return False\n\n \n\n# event.loosetaucand, dummpy = cleanObjectCollection(event.loosetaucand,\n# masks = [event.muon],\n## masks = event.muoncand,\n# deltaRMin = 0.4)\n#\n# event.loosetaucand, dummpy = cleanObjectCollection(event.loosetaucand,\n# masks = [event.electron],\n## masks = event.electroncand,\n# deltaRMin = 0.4)\n#\n# event.loosetaucand, dummpy = cleanObjectCollection(event.loosetaucand,\n# masks = [event.tau],\n# deltaRMin = 0.4)\n#\n#\n# event.loosemuoncand, dummpy = cleanObjectCollection(event.loosemuoncand,\n# masks = [event.muon],\n# deltaRMin = 0.4)\n#\n# event.loosemuoncand, dummpy = cleanObjectCollection(event.loosemuoncand,\n# masks = [event.electron],\n# deltaRMin = 0.4)\n#\n# event.loosemuoncand, dummpy = cleanObjectCollection(event.loosemuoncand,\n# masks = [event.tau],\n# deltaRMin = 0.4)\n#\n# event.looseelectroncand, dummpy = cleanObjectCollection(event.looseelectroncand,\n# masks = [event.muon],\n# deltaRMin = 0.4)\n#\n# event.looseelectroncand, dummpy = cleanObjectCollection(event.looseelectroncand,\n# masks = [event.electron],\n# deltaRMin = 0.4)\n#\n# event.looseelectroncand, dummpy = cleanObjectCollection(event.looseelectroncand,\n# masks = [event.tau],\n# deltaRMin = 0.4)\n\n \n \n# NadditionalLepton = len(event.loosetaucand) + len(event.loosemuoncand) + len(event.looseelectroncand)\n# if NadditionalLepton>=1:\n# return False\n\n\n\n# print 'All events passed : ', event.run, event.lumi, event.eventId\n \n return True\n\n \n\n def returnMass(self, obj1, obj2):\n\n e4 = TLorentzVector()\n t4 = TLorentzVector()\n\n e4.SetPtEtaPhiM(Double(obj1.pt()),\n Double(obj1.eta()),\n Double(obj1.phi()),\n Double(obj1.mass()))\n\n t4.SetPtEtaPhiM(Double(obj2.pt()),\n Double(obj2.eta()),\n Double(obj2.phi()),\n Double(obj2.mass()))\n\n return (e4 + t4).M()\n \n def returnDR(self, obj1, obj2):\n deta = obj1.eta() - obj2.eta()\n dphi = obj1.phi() - obj2.phi()\n dr2 = deta*deta + dphi*dphi\n return math.sqrt(dr2)\n\n def triggerCheck(self, event, hltPath, leg):\n\n flag_pass = False\n \n# for itrig in hltPaths:\n \n# if self.trigMatched(event, itrig, leg):\n# flag_pass = True\n\n if self.trigMatched(event, hltPath, leg):\n flag_pass = True\n\n return flag_pass\n\n\n def testLeg1Iso(self, tau, isocut):\n '''if isocut is None, returns true if three-hit iso cut is passed.\n Otherwise, returns true if iso MVA > isocut.'''\n if isocut is None:\n# print 'check tau ID ', tau.tauID('byCombinedIsolationDeltaBetaCorrRaw3Hits')\n# return tau.tauID(\"byCombinedIsolationDeltaBetaCorrRaw3Hits\") < 1.5\n# return tau.tauID(\"byMediumCombinedIsolationDeltaBetaCorr3Hits\")\n return tau.tauID(\"byLooseCombinedIsolationDeltaBetaCorr3Hits\")\n else:\n return tau.tauID(\"byRawIsoMVA\")>isocut\n\n\n def testVertex(self, lepton):\n '''Tests vertex constraints, for mu and tau'''\n return abs(lepton.dxy()) < 0.045 and \\\n abs(lepton.dz()) < 0.2 \n\n\n def testLeg2ID(self, muon):\n '''Tight muon selection, no isolation requirement'''\n return muon.tightId() and \\\n self.testVertex( muon )\n \n\n def testLeg2Iso(self, muon, isocut):\n '''Tight muon selection, with isolation requirement'''\n if isocut is None:\n isocut = self.cfg_ana.iso2\n# print muon.relIsoAllChargedDB05, isocut\n# return muon.relIsoAllChargedDB05() 2 leptons (e or mu).'''\n vleptons = [lep for lep in leptons if\n self.testLegKine(lep, ptcut=ptcut, etacut=2.4) and \n self.testLeg2ID(lep) and\n self.testLeg2Iso(lep, isocut) ]\n # count electrons\n votherLeptons = [olep for olep in otherLeptons if \n self.testLegKine(olep, ptcut=ptcut, etacut=2.5) and \\\n olep.looseIdForTriLeptonVeto() and \\\n self.testVertex( olep ) and \\\n olep.relIsoAllChargedDB05() < isocut\n ]\n if len(vleptons) + len(votherLeptons)> 1:\n return False\n else:\n return True\n\n\n def leptonAccept(self, leptons):\n '''The di-lepton veto, returns false if > one lepton.\n e.g. > 1 mu in the mu tau channel'''\n looseLeptons = [muon for muon in leptons if\n self.testLegKine(muon, ptcut=15, etacut=2.4) and\n muon.isGlobalMuon() and\n muon.isTrackerMuon() and\n muon.sourcePtr().userFloat('isPFMuon') and\n #COLIN Not sure this vertex cut is ok... check emu overlap\n #self.testVertex(muon) and\n # JAN: no dxy cut\n abs(muon.dz()) < 0.2 and\n self.testLeg2Iso(muon, 0.3)\n ]\n isPlus = False\n isMinus = False\n # import pdb; pdb.set_trace()\n for lepton in looseLeptons:\n if lepton.charge()<0: isMinus=True\n elif lepton.charge()>0: isPlus=True\n else:\n raise ValueError('Impossible!')\n veto = isMinus and isPlus\n return not veto\n\n def testVetoBJet(self, jet):\n # medium csv working point\n # https://twiki.cern.ch/twiki/bin/viewauth/CMS/BTagPerformanceOP#B_tagging_Operating_Points_for_3\n\n jet.btagMVA = jet.btag(\"combinedSecondaryVertexBJetTags\")\n\n return jet.pt()>12. and \\\n abs( jet.eta() ) < 2.4 and \\\n jet.btagMVA > 0.8\n\n\n\n# def testBJet(self, jet):\n# # medium csv working point\n# # https://twiki.cern.ch/twiki/bin/viewauth/CMS/BTagPerformanceOP#B_tagging_Operating_Points_for_3\n# jet.btagMVA = jet.btag(\"combinedSecondaryVertexBJetTags\")\n#\n# return jet.pt()>20. and \\\n# abs( jet.eta() ) < 2.4 and \\\n# jet.btagMVA > 0.898 and \\\n# self.testJetID(jet)\n#\n#\n# def testJetID(self, jet):\n# jet.puJetIdPassed = jet.puJetId(wp53x=True)\n# jet.pfJetIdPassed = jet.looseJetId()\n#\n# return jet.puJetIdPassed and jet.pfJetIdPassed\n\n\n### def trigMatched(self, event, leg, legName):\n### '''Returns true if the leg is matched to a trigger object as defined in the\n### triggerMap parameter'''\n### if not hasattr( self.cfg_ana, 'triggerMap'):\n### return True\n#### else:\n#### print 'Trigger OK'\n###\n###\n### path = event.hltPath\n### print 'path = ', path\n### \n### triggerObjects = event.triggerObjects\n### print 'triggerObjects = ', triggerObjects\n###\n### filters = self.cfg_ana.triggerMap[ path ]\n### print 'filters = ', filters\n### \n### filter = None\n### print 'filter = ', filter\n###\n###\n#### import pdb; pdb.set_trace()\n### \n### if legName == 'leg1':\n### filter = filters[0]\n### elif legName == 'leg2':\n### filter = filters[1]\n### else:\n### raise ValueError( 'legName should be leg1 or leg2, not {leg}'.format(\n### leg=legName ) )\n###\n### # JAN: Need a hack for the embedded samples: No trigger matching in that case\n### if filter == '':\n#### print 'Jan filter'\n### return True\n###\n### for it in triggerObjects:\n### print '(path, filter, obj, hasPath, hasSelection = ', path, filter, it, it.hasPath(path), it.hasSelection(filter)\n###\n###\n### # the dR2Max value is 0.3^2\n### pdgIds = None\n### if len(filter) == 2:\n### filter, pdgIds = filter[0], filter[1]\n### return triggerMatched(leg, triggerObjects, path, filter,\n### dR2Max=0.089999,\n#### dR2Max=0.25,\n### pdgIds=pdgIds )\n\n\n\n\n\n\n# def trigMatched(self, event, trigpath, leg1, leg2):\n# '''Returns true if the leg is matched to a trigger object as defined in the\n# triggerMap parameter'''\n# if not hasattr( self.cfg_ana, 'triggerMap'):\n# return True\n#\n#\n#\n# triggerObjects = event.triggerObjects\n# filters = self.cfg_ana.triggerMap[ trigpath ]\n# filter = filters[0]\n# pdgIds = None\n#\n#\n## print 'trigger path = ', trigpath\n## for it in triggerObjects:\n## print '(filter, obj, hasPath, hasSelection = ', filter, it.hasPath(path), it.hasSelection(filter), it\n#\n# \n#\n# triggerMatched1 = triggerMatched(leg1, triggerObjects, trigpath, filter,\n# dR2Max=0.089999,\n# pdgIds=pdgIds )\n#\n#\n# triggerMatched2 = triggerMatched(leg2, triggerObjects, trigpath, filter,\n# dR2Max=0.089999,\n# pdgIds=pdgIds )\n#\n#\n## import pdb; pdb.set_trace();\n#\n#\n# if filter.find('Mu8_Ele17')!=-1:\n# return triggerMatched1 and triggerMatched2 and leg1.pt() > 10. and leg2.pt() > 20.\n# elif filter.find('Mu17_Ele8')!=-1:\n# return triggerMatched1 and triggerMatched2 and leg1.pt() > 20. and leg2.pt() > 10.\n# else:\n# print 'Unexpected Trigger !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1'\n# return False\n\n\n\n\n def trigMatched(self, event, trigpath, leg):\n '''Returns true if the leg is matched to a trigger object'''\n if not hasattr( self.cfg_ana, 'triggerMap'):\n return True\n\n# print trigpath\n\n triggerObjects = event.triggerObjects\n filters = self.cfg_ana.triggerMap[ trigpath ]\n filter = filters[0]\n pdgIds = None\n\n\n flag = triggerMatched(leg, triggerObjects, trigpath, filter,\n dR2Max=0.089999,\n pdgIds=pdgIds )\n\n\n if filter.find('Mu17_Mu8')!=-1 or filter.find('Mu17_TkMu8')!=-1:\n return flag\n else:\n return False\n\n","sub_path":"CMGTools/H2TauTau/python/proto/analyzers/WHMMTAnalyzer.py","file_name":"WHMMTAnalyzer.py","file_ext":"py","file_size_in_byte":39030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"555804709","text":"#!/usr/bin/python3\n\nimport os\nimport sys\nimport unittest\nfrom pkg_resources import resource_string\nimport xml.etree.ElementTree as etree\n\njira_lib_path = os.path.dirname(os.path.realpath(__file__)) + \"/../lib\"\nif jira_lib_path not in sys.path:\n sys.path.append(jira_lib_path)\n\nfrom issue_converter import IssueConverter\nfrom jira_data_extractor import JiraDataExtractor\nimport standard_format_constants as std\n\n\nclass JiraIssueConverterTestCase(unittest.TestCase):\n \"\"\"Tests for data conversion from JIRA-XML to STANDARD-XML\"\"\"\n\n EMPTY_COMMENTS_STR = \"\"\"\n \n asdf\n \n \"\"\"\n\n EMPTY_ATTACHMENTS_STR = \"\"\"\n \n asdf\n \n \"\"\"\n\n CLOSED_ISSUE_STR = \"jira_issue_closed.xml\"\n CLOSED_JIRA_ISSUE = resource_string(\"resources.test_data\",\n CLOSED_ISSUE_STR).decode(\"utf-8\")\n OPEN_JIRA_ISSUE = resource_string(\"resources.test_data\",\n \"jira_issue_open.xml\").decode(\"utf-8\")\n\n data_extractor = JiraDataExtractor()\n jira_converter = IssueConverter(data_extractor)\n\n def test_converted_issue_has_issue_tag(self):\n EXPECTED_ROOT_TAG_NAME = \"issue\"\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n self.assertEqual(converted_xml.tag, EXPECTED_ROOT_TAG_NAME)\n\n def test_converted_issue_has_issue_number_attribute(self):\n issue_tag = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n self.assertIn(\"number\", issue_tag.attrib)\n self.assertEqual(issue_tag.attrib[\"number\"], \"1\")\n\n def test_converter_can_extract_issue_number_from_key_tag(self):\n xml_string = \"ZOOKEEPER-1\"\n EXPECTED_ISSUE_NUMBER = 1\n xml_snippet = etree.fromstring(xml_string)\n\n issue_number = self.data_extractor.get_issue_number(xml_snippet)\n\n self.assertEqual(issue_number, EXPECTED_ISSUE_NUMBER)\n\n def test_converter_reports_failure_when_issue_number_cannot_be_found(self):\n invalid_xml_string = \"ZOOKEEPER\"\n xml_snippet = etree.fromstring(invalid_xml_string)\n\n no_issue_number = self.data_extractor.get_issue_number(xml_snippet)\n\n self.assertIsNone(no_issue_number)\n\n def test_converted_issue_has_creation_tag(self):\n EXPECTED_TAG_NAME = std.CREATION_TAG\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n creation_tag = converted_xml.find(\".//creation\")\n self.assertEqual(creation_tag.tag, EXPECTED_TAG_NAME)\n\n def test_converted_issue_has_creation_date_attribute(self):\n EXPECTED_CREATION_DATE = \"2008-06-06\"\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n creation_tag = converted_xml.find(\".//\" + std.CREATION_TAG)\n self.assertIn(std.CREATION_CREATION_DATE_ATTR, creation_tag.attrib)\n self.assertEqual(creation_tag.attrib[std.CREATION_CREATION_DATE_ATTR],\n EXPECTED_CREATION_DATE)\n\n def test_converted_issue_has_created_by_attribute(self):\n EXPECTED_AUTHOR = \"phunt\"\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n creation_tag = converted_xml.find(\".//\" + std.CREATION_TAG)\n self.assertIn(std.CREATION_CREATED_BY_ATTR, creation_tag.attrib)\n self.assertEqual(creation_tag.attrib[std.CREATION_CREATED_BY_ATTR],\n EXPECTED_AUTHOR)\n\n def test_converted_issue_has_resolution_tag(self):\n EXPECTED_TAG_NAME = std.RESOLUTION_TAG\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n resolution_tag = converted_xml.find(\".//\" + std.RESOLUTION_TAG)\n self.assertEqual(resolution_tag.tag, EXPECTED_TAG_NAME)\n\n def test_converted_resolved_issues_are_marked_as_closed(self):\n EXPECTED_RESOLVED_VALUE = std.RESOLUTION_RESOLVED_CLOSED\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n resolution_tag = converted_xml.find(\".//\" + std.RESOLUTION_TAG)\n self.assertIn(std.RESOLUTION_RESOLVED_ATTR, resolution_tag.attrib)\n self.assertEqual(resolution_tag.attrib[std.RESOLUTION_RESOLVED_ATTR],\n EXPECTED_RESOLVED_VALUE)\n\n def test_converted_resolved_issues_have_resolution_date_attr(self):\n EXPECTED_RESOLUTION_DATE = \"2008-06-12\"\n RESOLUTION_DATE_ATTR = std.RESOLUTION_RESOLUTION_DATE_ATTR\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n resolution_tag = converted_xml.find(\".//\" + std.RESOLUTION_TAG)\n self.assertIn(RESOLUTION_DATE_ATTR, resolution_tag.attrib)\n self.assertEqual(resolution_tag.attrib[RESOLUTION_DATE_ATTR],\n EXPECTED_RESOLUTION_DATE)\n\n def test_converted_unresolved_issues_are_marked_as_open(self):\n EXPECTED_RESOLVED_VALUE = std.RESOLUTION_RESOLVED_OPEN\n\n converted_xml = self.get_converted_xml(self.OPEN_JIRA_ISSUE)\n\n resolution_tag = converted_xml.find(\".//\" + std.RESOLUTION_TAG)\n self.assertIn(std.RESOLUTION_RESOLVED_ATTR, resolution_tag.attrib)\n self.assertEqual(resolution_tag.attrib[std.RESOLUTION_RESOLVED_ATTR],\n EXPECTED_RESOLVED_VALUE)\n\n def test_converted_issues_have_description_tag(self):\n EXPECTED_TAG_NAME = std.DESCRIPTION_TAG\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n description_tag = converted_xml.find(\".//\" + std.DESCRIPTION_TAG)\n self.assertEqual(description_tag.tag, EXPECTED_TAG_NAME)\n\n def test_converted_issues_have_description_text_from_initial_issue(self):\n EXPECTED_DESCRIPTION_SNIPPET = \"This is a SVN dump of the ZooKeeper\"\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n description_text = converted_xml.find(\".//\" + std.DESCRIPTION_TAG).text\n self.assertIn(EXPECTED_DESCRIPTION_SNIPPET, description_text)\n\n def test_converted_issues_have_comments_tag(self):\n EXPECTED_TAG_NAME = std.COMMENTS_TAG\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n comments_tag = converted_xml.find(\".//\" + std.COMMENTS_TAG)\n self.assertEqual(comments_tag.tag, EXPECTED_TAG_NAME)\n\n def test_comments_tag_is_empty_when_original_issue_had_no_comments(self):\n INPUT_COMMENTS_STR = \"\"\n INPUT_COMMENTS_XML = etree.fromstring(INPUT_COMMENTS_STR)\n converter = self.jira_converter\n\n comments_tag = converter.create_comments_tag(INPUT_COMMENTS_XML)\n no_comments = comments_tag.find(\".//\" + std.COMMENT_TAG)\n\n self.assertIsNone(no_comments)\n\n def test_has_comment_tag_for_each_comment_on_original_issue(self):\n EXPECTED_TAG_NAME = std.COMMENT_TAG\n EXPECTED_NUM_COMMENTS = 4\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n comment_tags = converted_xml.findall(\".//\" + std.COMMENT_TAG)\n self.assertEqual(len(comment_tags), EXPECTED_NUM_COMMENTS)\n for comment in comment_tags:\n self.assertEqual(comment.tag, EXPECTED_TAG_NAME)\n\n def test_comment_tags_have_no_author_when_orig_comment_had_none(self):\n EMPTY_COMMENTS_XML = etree.fromstring(self.EMPTY_COMMENTS_STR)\n converter = self.jira_converter\n\n converted_xml = converter.create_comments_tag(EMPTY_COMMENTS_XML)\n comment_tag = converted_xml.find(\".//\" + std.COMMENT_TAG)\n\n self.assertNotIn(std.COMMENT_AUTHOR_ATTR, comment_tag.attrib)\n\n def test_each_comment_tag_has_an_author(self):\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n comment_tags = converted_xml.findall(\".//\" + std.COMMENT_TAG)\n\n for comment in comment_tags:\n self.assertIn(std.COMMENT_AUTHOR_ATTR, comment.attrib)\n\n def test_comment_tags_have_no_date_when_orig_comment_had_none(self):\n EMPTY_COMMENTS_XML = etree.fromstring(self.EMPTY_COMMENTS_STR)\n converter = self.jira_converter\n\n converted_xml = converter.create_comments_tag(EMPTY_COMMENTS_XML)\n comment_tag = converted_xml.find(\".//\" + std.COMMENT_TAG)\n\n self.assertNotIn(std.COMMENT_DATE_ATTR, comment_tag.attrib)\n\n def test_each_comment_tag_has_a_posting_date(self):\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n comment_tags = converted_xml.findall(\".//\" + std.COMMENT_TAG)\n\n for comment in comment_tags:\n self.assertIn(std.COMMENT_DATE_ATTR, comment.attrib)\n\n def test_each_comment_tag_has_the_text_of_the_original_comment(self):\n SNIPPETS = [\"SVN dump of ZooKeeper\", \"grant was signed\",\n \"ASF registered\", \"3.0.0 has been released\"]\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n comment_tags = converted_xml.findall(\".//\" + std.COMMENT_TAG)\n\n for index, comment_tag in enumerate(comment_tags):\n self.assertIn(SNIPPETS[index], comment_tag.text)\n\n def test_converted_issues_have_attachments_tag(self):\n EXPECTED_TAG_NAME = std.ATTACHMENTS_TAG\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n\n attachments_tag = converted_xml.find(\".//\" + std.ATTACHMENTS_TAG)\n self.assertEqual(attachments_tag.tag, EXPECTED_TAG_NAME)\n\n def test_attachments_tag_is_empty_when_input_had_no_attachments(self):\n EMPTY_ATTACHMENTS_STR = \"\"\n EMPTY_ATTACHMENTS = etree.fromstring(EMPTY_ATTACHMENTS_STR)\n converter = self.jira_converter\n\n attachments_tag = converter.create_attachments_tag(EMPTY_ATTACHMENTS)\n no_attachments = attachments_tag.find(\".//\" + std.ATTACHMENT_TAG)\n\n self.assertIsNone(no_attachments)\n\n def test_has_attachment_for_each_attachment_in_input(self):\n EXPECTED_TAG_NAME = std.ATTACHMENT_TAG\n EXPECTED_NUM_ATTACHMENTS = 1\n\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n attachment_tags = converted_xml.findall(\".//\" + std.ATTACHMENT_TAG)\n\n self.assertEqual(len(attachment_tags), EXPECTED_NUM_ATTACHMENTS)\n for attachment in attachment_tags:\n self.assertEqual(attachment.tag, EXPECTED_TAG_NAME)\n\n def test_attachment_doesnt_have_author_when_input_specifies_none(self):\n EMPTY_ATTACHMENTS_XML = etree.fromstring(self.EMPTY_ATTACHMENTS_STR)\n converter = self.jira_converter\n\n converted_xml = converter.create_attachments_tag(EMPTY_ATTACHMENTS_XML)\n attachment_tag = converted_xml.find(\".//\" + std.ATTACHMENT_TAG)\n\n self.assertNotIn(std.ATTACHMENT_UPLOADED_BY_ATTR,\n attachment_tag.attrib)\n\n def test_each_attachment_has_author_when_one_provided_in_input(self):\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n attachments_tag = converted_xml.find(\".//\" + std.ATTACHMENTS_TAG)\n\n for attachment_tag in attachments_tag:\n self.assertIn(std.ATTACHMENT_UPLOADED_BY_ATTR,\n attachment_tag.attrib)\n\n def test_attachment_has_no_upload_time_when_input_specifies_none(self):\n EMPTY_ATTACHMENTS_XML = etree.fromstring(self.EMPTY_ATTACHMENTS_STR)\n converter = self.jira_converter\n\n converted_xml = converter.create_attachments_tag(EMPTY_ATTACHMENTS_XML)\n attachment_tag = converted_xml.find(\".//\" + std.ATTACHMENT_TAG)\n\n self.assertNotIn(std.ATTACHMENT_UPLOAD_DATE_ATTR,\n attachment_tag.attrib)\n\n def test_each_attachment_has_upload_time_when_one_provided_in_input(self):\n converted_xml = self.get_converted_xml(self.CLOSED_JIRA_ISSUE)\n attachments_tag = converted_xml.find(\".//\" + std.ATTACHMENTS_TAG)\n\n for attachment_tag in attachments_tag:\n self.assertIn(std.ATTACHMENT_UPLOAD_DATE_ATTR,\n attachment_tag.attrib)\n\n def get_converted_xml(self, raw_issue_data):\n converted_issue = self.jira_converter.convert_issue(raw_issue_data)\n return etree.fromstring(converted_issue)\n","sub_path":"test/test_jira_issue_converter.py","file_name":"test_jira_issue_converter.py","file_ext":"py","file_size_in_byte":12364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"390850711","text":"#!usr/bin/python\n# -*- coding: utf-8 -*-\n#pesquisar tvt ldap search\n\n\nimport os, sys, commands\n\namarelo = '\\033[33m'\nfundoesc = '\\033[0;0m'\nverde = '\\033[32m'\nvermelho = '\\033[32m'\nazul ='\\033[34m'\n\nlogerr =\"\"\"\nUtilizando parâmetros você localiza o tvt usando o usuário de rede ou faz o inverso, com o tvt consegue localizar o usuário.\nutiliza o comando:\n python pesquisatvt.py [user/tvt] [usuário(sem dominio)/tvtxxxxx]\n\nUtilize\n tvt como primeiro parametro em seguida o tvt desejado\n Ex:\n {}python{} pesquisatvt.py {}tvt{} tvtxxxxx\n ou\n user como primeiro parâmetro em seguida o usuário de rede\n Ex:\n {}python{} pesquisatvt.py {}user{} ariel.aagramonte\n\"\"\".format(amarelo,fundoesc, verde, fundoesc, amarelo,fundoesc, verde, fundoesc)\n\nprint('----------{} Inicio Script{} ----------'.format(azul, fundoesc))\n\nmetodo = sys.argv[1]\nuser = sys.argv[2]\ntipopesquisa = ''\n\n\nif metodo.lower() == 'tvt':\n tipopesquisa = 'cn='\nelif metodo.lower() == 'user':\n tipopesquisa = 'mail='\n user +='@{dominio}'\nelse:\n print('{}\\n\\tErro de Parâmetro! {}'.format(vermelho, fundoesc))\n sys.exit(logerr)\n\n \nprint(os.system('ldapsearch -x -h {ip} -p {porta} -LLL -b o={oculto} {}\\'{}\\''.format(tipopesquisa, user)))\nprint('---------- {}Fim da pesquisa{} ----------'.format(azul, fundoesc))\n\n\n#owner\n__author__ = 'Ariel Agramonte'\n__email__ = 'ariel.aagramonte@tivit.com'\n__credits__ = ['Ariel Agramonte']\n\n","sub_path":"trampo/pesquisatvt.py","file_name":"pesquisatvt.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"16220163","text":"# coding=utf-8\n# 中文为方框的话需要安装字体\n# 在centos中执行:yum install bitmap-fonts bitmap-fonts-cjk\n# 在ubuntu中执行:sudo apt-get install xfonts-wqy\n# 如果要截取 html 文件需要使用 file:///D:/WebstormProjects/ZuiBlog/index.html 类似这样的方式\nfrom selenium import webdriver\nimport os\nimport time\nimport sys\n\nurl = sys.argv[1]\nexecName = 'phantomjs';\nprint(os.name)\n\nif os.name == 'nt':\n execName = execName + '.exe'\n\ndriver = webdriver.PhantomJS(executable_path='./phantomjs/' + os.name + '/bin/' + execName)\n# 这里的executable_path填你phantomJS的路径\n\n# 设置宽高\ndriver.set_window_size(1280, 720)\n\ndriver.get(url)\n\ntime.sleep(2)\n\ndriver.save_screenshot(\"shot.png\")\n\ndriver.quit()\n","sub_path":"html2ImgPy2.py","file_name":"html2ImgPy2.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"250842075","text":"# simple example: minimize a quadratic around some solution point\nimport numpy as np \nsolution = np.array([0.5, 0.1, -0.3]) \ndef f(w): return -np.sum((w - solution)**2)\n\niter_count = 1000\nnpop = 50 # population size \nsigma = 0.1 # noise standard deviation \nalpha = 0.001 # learning rate \nw = np.random.randn(3) # initial guess \nfor i in range(iter_count): \n N = np.random.randn(npop, 3)\n R = np.zeros(npop)\n for j in range(npop):\n w_try = w + sigma*N[j]\n R[j] = f(w_try)\n A = (R - np.mean(R)) / np.std(R)\n w = w + alpha/(npop*sigma) * np.dot(N.T, A)\n if i == 0:\n print(N.shape)\n print(np.dot(N.T, A).shape)\n\n # if i % 100 == 0:\n # print(w)\nprint(w)","sub_path":"python/deep_learning/evolution/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"597507694","text":"from tkinter import *\nfrom tkinter import ttk\nimport time\nimport random as rand\n\n\n\nroot = Tk()\n\nvelocidade = StringVar()\nvel_lista = ['Rápido', 'Médio', 'Lento']\n\nordenacoes = StringVar()\nord_lista = ['Merge Sort', 'Bubble Sort', 'Insertion Sort', 'Quick Sort',\n'Heap Sort', 'Selection Sort']\n\ndef numeros_aleatorios():\n\t\n\tglobal lista\n\tlista = [x for x in range(150, 750, 6)]\n\trand.shuffle(lista)\n\tcria_retangulos(lista, ['red' for x in range(0, len(lista))])\n\t\n\ndef cria_retangulos(lista, cor):\n\n\ttela_can.delete(\"all\")\n\tdist = 3\n\tfor i in range(0, len(lista)):\n\t\ttela_can.create_rectangle(dist, 800 - lista[i], 5 + dist , 800, fill = cor[i])\n\t\tdist += 8\n\t\n\troot.update_idletasks()\n\n\n\ndef bubble_sort(lista, velocidade):\n\n\tfor j in range(0, len(lista)):\n\t\tfor i in range(0, len(lista) - j - 1):\n\n\t\t\tif lista[i] > lista[i + 1]:\n\n\t\t\t\taux = lista[i]\n\t\t\t\tlista[i] = lista[i + 1]\n\t\t\t\tlista[i + 1] = aux\n\t\t\t\tcria_retangulos(lista, ['green' if x == j + 1 else 'red' for x in range(0, len(lista))])\n\t\t\t\ttime.sleep(velocidade)\n\t\t\t\n\t\tcria_retangulos(lista, ['green' for x in range(0, len(lista))])\n\t\t\n\ndef merge_sort(lista, aux, inicio, fim, velocidade):\n\n\tif inicio < fim:\n\n\t\tmetade = int((inicio + fim) / 2)\n\n\t\tmerge_sort(lista, aux, inicio, metade, velocidade)\n\t\tmerge_sort(lista, aux, metade + 1, fim, velocidade)\n\n\t\tmerge(lista, aux, inicio, metade, fim, velocidade)\n\n\t\tcria_retangulos(lista, ['green' if x == metade else 'red' for x in range(0, len(lista))])\n\t\ttime.sleep(velocidade)\n\t\t\t\n\tcria_retangulos(lista, ['green' for x in range(0, len(lista))])\n\ndef merge(lista, aux, inicio, metade, fim, velocidade):\n\n\t\n\tfor i in range(inicio, fim + 1):\n\n\t\taux[i] = lista[i]\n\n\tp = inicio\n\tq = metade + 1\n\n\tfor j in range(inicio, fim + 1):\n\t\t\n\t\tif p > metade:\n\t\t\tlista[j] = aux[q]\n\t\t\tq += 1\n\n\t\telif q > fim:\n\t\t\tlista[j] = aux[p]\n\t\t\tp += 1\n\n\t\telif aux[p] < aux[q]:\n\t\t\tlista[j] = aux[p]\n\t\t\tp += 1\n\n\t\telse:\n\t\t\tlista[j] = aux[q]\n\t\t\tq += 1\n\ndef insertion_sort(lista, velocidade):\n\n\tfor i in range(1, len(lista)):\n\n\t\tpivo = lista[i]\n\t\tj = i - 1\n\n\t\twhile pivo < lista[j] and j >= 0:\n\t\t\tlista[j + 1] = lista[j]\n\t\t\tj -= 1\n\t\t\tcria_retangulos(lista, ['green' if x == pivo else 'red' for x in range(0, len(lista))])\n\t\t\ttime.sleep(velocidade)\n\n\t\tlista[j + 1] = pivo\n\n\tcria_retangulos(lista, ['green' for x in range(0, len(lista))])\n\ndef particao(inicio, fim, lista):\n\t\n\tindex_pivo = inicio\n\tpivo = lista[index_pivo]\n\n\twhile inicio < fim:\n\n\t\twhile inicio < len(lista) and lista[inicio] <= pivo:\n\n\t\t\tinicio += 1\n\n\t\twhile lista[fim] > pivo:\n\t\t\tfim -= 1\n\n\t\tif inicio < fim:\n\t\t\taux = lista[inicio]\n\t\t\tlista[inicio] = lista[fim]\n\t\t\tlista[fim] = aux\n\t\t\n\t\t\n\t\n\taux = lista[fim]\n\tlista[fim] = lista[index_pivo]\n\tlista[index_pivo] = aux\n\n\treturn fim\n\ndef quick_sort(inicio, fim, lista, velocidade):\n\n\tif inicio < fim:\n\n\t\tp = particao(inicio, fim, lista)\n\t\tquick_sort(inicio, p - 1, lista, velocidade)\n\t\tquick_sort(p + 1, fim, lista, velocidade)\n\t\tcria_retangulos(lista, ['green' if x == p else 'red' for x in range(0, len(lista))])\n\t\ttime.sleep(velocidade)\n\n\tcria_retangulos(lista, ['green' for x in range(0, len(lista))])\n\n\ndef selectionSort(lista, velocidade):\n\n\ttam = len(lista)\n\tfor i in range(0, tam -1):\n\t\tmenor = i\n\n\t\tj = i + 1\n\n\t\twhile j < tam:\n\n\t\t\tif lista[j] < lista[menor]:\n\t\t\t\tmenor = j\n\n\t\t\tj += 1\n\n\t\tif i != menor:\n\t\t\taux = lista[i]\n\t\t\tlista[i] = lista[menor]\n\t\t\tlista[menor] = aux\n\t\t\n\t\tcria_retangulos(lista, ['green' if x == menor else 'red' for x in range(0, len(lista))])\n\t\ttime.sleep(velocidade)\n\tcria_retangulos(lista, ['green' for x in range(0, len(lista))])\n\n\ndef heapifica(lista, n, i):\n\n\tmaior = i\n\n\tesq = (2 * i) + 1\n\tdrt = (2 * i) + 2\n\n\tif esq < n and lista[maior] < lista[esq]:\n\t\tmaior = esq\n\n\tif drt < n and lista[maior] < lista[drt]:\n\t\tmaior = drt\n\n\tif maior != i:\n\n\t\taux = lista[maior]\n\t\tlista[maior] = lista[i]\n\t\tlista[i] = aux\n\n\t\theapifica(lista, n, maior)\n\n\n\ndef heapSort(lista, velocidade):\n\n\tn = len(lista)\n\n\tfor i in range(n//2 - 1, -1, -1):\n\t\theapifica(lista, n, i)\n\t\tcria_retangulos(lista, ['green' if x == i else 'red' for x in range(0, len(lista))])\n\t\ttime.sleep(velocidade)\n\n\tfor j in range(n - 1, 0, -1):\n\t\taux = lista[j]\n\t\tlista[j] = lista[0]\n\t\tlista[0] = aux\n\t\theapifica(lista, j, 0)\n\t\tcria_retangulos(lista, ['green' if x == j else 'red' for x in range(0, len(lista))])\n\t\ttime.sleep(velocidade)\n\n\tcria_retangulos(lista, ['green' for x in range(0, len(lista))])\n\n\n\ndef escolhe_velocidade():\n\n\tif vel_selecao.get() == 'Rápido':\n\t\treturn 0.001\n\n\telif vel_selecao.get() == 'Médio':\n\t\treturn 0.01\n\n\telse:\n\t\treturn 0.1\n\n\n\ndef roda_orednacao():\n\tglobal lista\n\tvelocidade = escolhe_velocidade()\n\n\tif ord_selecao.get() == 'Bubble Sort':\n\t\tbubble_sort(lista, velocidade)\n\n\telif ord_selecao.get() == 'Merge Sort':\n\t\taux = [0] * len(lista)\n\t\tmerge_sort(lista, aux, 0, len(lista) - 1, velocidade)\n\n\telif ord_selecao.get() == 'Insertion Sort':\n\t\tinsertion_sort(lista, velocidade)\n\n\telif ord_selecao.get() == 'Quick Sort':\n\t\tquick_sort(0, len(lista) - 1, lista, velocidade)\n\n\telif ord_selecao.get() == 'Selection Sort':\n\t\tselectionSort(lista, velocidade)\n\n\telif ord_selecao.get() == 'Heap Sort':\n\t\theapSort(lista, velocidade)\n\n\nU_Frame = Frame(root, width = 800, height = 250)\nU_Frame.grid(row = 0, column = 0)\n\ninicio = Button(U_Frame, text = 'Inicia', command = roda_orednacao)\ninicio.grid(row = 0, column = 0)\n\ngera_lista = Button(U_Frame, text = 'Gera Lista', command = numeros_aleatorios)\ngera_lista.grid(row = 0, column = 1)\n\nvel = Label(U_Frame, text = 'Velociade', background = 'lightgray')\nvel.grid(row = 1, column = 0, padx = 10, pady = 10)\n\nvel_selecao = ttk.Combobox(U_Frame, textvariable = velocidade, values = vel_lista)\nvel_selecao.grid(row = 2, column = 0, padx = 5, pady = 5)\nvel_selecao.current(0)\n\nord_algo = Label(U_Frame, text = 'Algoritmo de Ordenação', background = 'lightgray') \nord_algo.grid(row = 1, column = 1, padx = 10, pady = 10)\n\nord_selecao = ttk.Combobox(U_Frame, textvariable = ordenacoes, values = ord_lista)\nord_selecao.grid(row = 2, column = 1, padx = 5, pady = 5)\nord_selecao.current(0)\n\ntela_can = Canvas(root, width = 800, height = 800, background = 'lightblue')\ntela_can.grid(row = 1, column = 0)\n\nroot.mainloop()\n\n","sub_path":"ordenador.py","file_name":"ordenador.py","file_ext":"py","file_size_in_byte":6161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"206394919","text":"from data_structure.list import *\n\nclass RandomLNode(LNode):\n\n def __init__(self, value=None, next=None, random=None):\n self.random = random\n super(RandomLNode, self).__init__(value, next)\n\n\ndef create_test_list():\n node_4 = RandomLNode(4)\n node_3 = RandomLNode(3, node_4)\n node_2 = RandomLNode(2, node_3, node_4)\n node_1 = RandomLNode(1, node_2, node_3)\n\n node_3.random = node_1\n node_4.random = node_2\n\n return node_1\n\ndef list_clone(node):\n \"\"\"\n 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),\n 返回结果为复制后复杂链表的 head。\n :param node:\n :return:\n \"\"\"\n\n # 在每个节点的后面插入复制的节点\n p = node\n while p:\n new_node = RandomLNode(p.value, p.next)\n p.next = new_node\n p = new_node.next\n\n # 对复制节点的 random 链接进行赋值\n p = node\n while p.next:\n if not p.next.random:\n p.next.random = p.random.next\n p = p.next\n\n p = node\n clone_head = p_clone = p.next\n\n while p.next:\n p = p.next.next\n p_clone.next = p.next\n\n return clone_head\n\np = list_clone(create_test_list())\nwhile p:\n print(p.value, p.random.value)\n p = p.next","sub_path":"algorithm/35_list_clone.py","file_name":"35_list_clone.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"194646797","text":"import asyncio\nimport configparser\nfrom discord.ext import commands\nimport discord\nimport json\nimport os.path\nimport time\n\nfrom chat_reader import ChatReader\nfrom evethings.system import System\nfrom system_status import IntelParser\nimport esi_routes as esi\nimport message_parser\n\n\nVERSION = 'v0.3'\nevebot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), description='An intel scraper for EVE')\nconfig = configparser.ConfigParser()\n\n\nclass EVEbot:\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n self.intel_channels = {}\n\n self.reader = ChatReader(json.loads(config.get('intel', 'eve_channels')), '\\Documents\\EVE\\logs\\Chatlogs')\n\n # self.bot.loop.set_debug(True)\n self.bot.loop.create_task(self.get_default_systems())\n self.scraper_task = self.bot.loop.create_task(self.scrape_to_systems())\n self.update_task = self.bot.loop.create_task(self.update_status())\n\n async def get_default_systems(self):\n await self.bot.wait_until_ready()\n channels = [ch for ch in self.bot.get_all_channels() if ch.name.startswith('intel-')]\n for chan in channels:\n system = System(chan.name[6:].swapcase())\n self.intel_channels[system.objectID] = (chan, system)\n\n print('Providing intel to', \", \".join([x[1].name for x in self.intel_channels.values()]))\n\n async def scrape_to_systems(self):\n await self.bot.wait_until_ready()\n await self.reader.wait_until_ready()\n\n await self.bot.change_presence(game=discord.Game(name=self.reader.eve_client))\n\n tts_jump_range = config.getint('intel', 'tts_jump_range', fallback=9)\n jump_range = config.getint('intel', 'jump_range', fallback=20)\n\n while self.bot.is_logged_in:\n intel = IntelParser(jump_range=jump_range)\n messages = await self.reader.get_messages()\n for m in messages:\n intel.process_message(m)\n\n for system_id, (channel, home_system) in self.intel_channels.items():\n for message, jumps in intel.summarize(home_system):\n try:\n tts = True if jumps < tts_jump_range else False\n await self.bot.send_message(channel, content=message, tts=tts)\n await asyncio.sleep(1.0) # sending messages too fast makes Discord upset\n except Exception as ex:\n print('Could not speak message: ', ex)\n\n if not self.bot.is_logged_in:\n print('bot is logged off')\n else:\n print('bot has quit for unknown reason!')\n\n async def update_status(self):\n await self.bot.wait_until_ready()\n\n while self.bot.is_logged_in:\n await asyncio.sleep(10.0)\n delta_t = time.time() - self.reader.last_updated\n game = discord.Game(name=self.reader.eve_client) if self.reader.eve_client != '' else None\n if delta_t > 600.0:\n await self.bot.change_presence(status=discord.Status.dnd, game=game)\n elif delta_t > 300.0:\n await self.bot.change_presence(status=discord.Status.idle, game=game)\n else:\n await self.bot.change_presence(status=discord.Status.online, game=game)\n\n @commands.command(pass_context=True, no_pm=True, help='get alerts relative to a system. !watch BQ0-UU')\n async def watch(self, ctx, *, system_name: str):\n try:\n system = System(system_name=system_name)\n if system.objectID in self.intel_channels:\n await self.bot.say(\"already watching {0}\".format(system.name))\n return\n\n channel = await self.bot.create_channel(ctx.message.server, 'intel-' + system.name)\n await self.bot.say(\"adding channel {0}\".format('intel-' + system.name))\n self.intel_channels[system.objectID] = (channel, system)\n except Exception:\n await self.bot.say(\"no such system {0}\".format(system_name))\n\n @commands.command(pass_context=True, no_pm=True, help='remove the alerts channel for the system. !unwatch BQ0-UU')\n async def unwatch(self, ctx, *, system_name: str):\n try:\n system = System(system_name=system_name)\n if self.intel_channels[system.objectID] is None:\n await self.bot.say(\"no channel to remove for {0}\".format(system.name))\n return\n\n await self.bot.say(\"removing channel {0}\".format('intel-' + system.name))\n await self.bot.delete_channel(self.intel_channels[system.objectID][0])\n self.intel_channels.pop(system.objectID)\n except Exception:\n await self.bot.say(\"no such system {0}\".format(system_name))\n\n @commands.command(pass_context=True, no_pm=True, help='says which EVE character the bot is pulling intel from')\n async def client(self, ctx):\n try:\n await self.bot.say('Using log files from {0}'.format(self.reader.eve_client))\n except AttributeError as error:\n await self.bot.say('I am not reading log files at the moment')\n\n @commands.command(pass_context=True, no_pm=True, help='remotely disconnects the bot, manual restart required')\n async def shutdown(self, ctx):\n print('Remote shutdown triggered by {0}'.format(ctx.message.author.nick))\n await self.bot.say('Remote shutdown triggered by {0}'.format(ctx.message.author.nick))\n await self.bot.logout()\n self.scraper_task.cancel()\n self.update_task.cancel()\n await self.bot.close()\n\n\n@evebot.event\nasync def on_ready():\n print('Logged in as: {0} (ID: {0.id})'.format(evebot.user))\n\n\ndef shutdown():\n for task in [x for x in asyncio.Task.all_tasks() if x is 'PENDING']:\n task.cancel()\n\n input('\\nPress ENTER to exit')\n exit()\n\nif __name__ == '__main__':\n latest_version = esi.get_latest_stable_release()\n if latest_version != VERSION:\n print('You are running {0}. Please download {1} from Github.'.format(VERSION, latest_version))\n else:\n print('You are running the latest version.')\n\n try:\n config.read('eve-bot.cfg')\n if not os.path.exists('eve-bot.cfg'):\n raise FileNotFoundError\n except FileNotFoundError as e:\n print('Could not find any filed named \"eve-bot.cfg\" in this directory.')\n shutdown()\n\n message_parser.ignore_words = set([''] + json.loads(config.get('intel', 'ignored_words')))\n\n evebot.add_cog(EVEbot(evebot))\n\n try:\n token = config['discord']['dev_token'] if 'dev_token' in config['discord'] else config['discord']['token']\n evebot.run(token)\n except KeyError:\n print(\"Could not find token in config file. Please check that 'token' exists under [discord].\")\n finally:\n shutdown()\n\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"609701318","text":"# (c) 2013-2015 Nive GmbH - nive.io\n# This file is released under the BSD-License.\n#\n# Nive Key-Value store service python client\n# ------------------------------------------------\n# Documentation: http:#www.nive.co/docs/webapi/datastore.html#api\n#\n\"\"\"\n**Example code 1**\n\nCreate a user instance, authenticate and retrieve the users profile values\n\n::\n\n from pynive_client import datastore\n\n storage = datastore.DataStore(service='mystorage',domain='mydomain')\n\n # list items\n result = storage.list(sort='key', order='<', size=20, start=1)\n for item in result:\n print item[\"key\"], item[\"value\"]\n\n\n\n**Example code 2**\n\nRetrieve a security token and add, update, get and remove a item\n\n::\n\n from pynive_client import useraccount\n from pynive_client import datastore\n\n niveuser = useraccount.User(domain='mydomain')\n\n # retrieve a auth-token to connect to the data storage service\n auth = niveuser.token(identity='username', password='userpw')\n\n storage = datastore.DataStore(service='mystorage',domain='mydomain',auth=auth)\n\n # add a new item\n result = storage.newItem({\"key\": \"key1\", \"value\": \"value1\"})\n\n # get a value\n item = storage.getItem(key=\"key1\")\n value = item.get(\"value\")\n\n # update a existing item\n result = storage.setItem({\"key\": \"key1\", \"value\": \"a new value\"})\n\n # remove the item\n result = storage.removeItem(key=\"key1\")\n\n\"\"\"\n\nfrom pynive_client import endpoint\n\n\nclass DataStore(endpoint.Client):\n\n default_version='api'\n pingurl='ping'\n\n\n def __init__(self, service, domain=None, session=None, **options):\n \"\"\"\n\n :param service: data storage instance name\n :param domain: domain the service is part of\n :param session: http session object\n :param options: other endpoint options. see endpoint.py.\n \"\"\"\n super(DataStore, self).__init__(service=service,\n domain=domain,\n session=session,\n **options)\n if not \"version\" in self.options:\n self.options[\"version\"] = self.default_version\n\n\n def getItem(self, key=None, owner=None, id=None, **reqSettings):\n \"\"\"\n\n :param key:\n :param owner:\n :param id:\n :param reqSettings:\n :return: dict\n \"\"\"\n values = dict()\n if key is not None:\n values[\"key\"] = key\n if owner is not None:\n values[\"owner\"] = owner\n if id is not None:\n values[\"id\"] = id\n content, response = self.call('getItem', values, reqSettings)\n return endpoint.Result(items=content.get('items'),\n result=content.get('result',0),\n message=content.get('message',()),\n response=response)\n\n\n def newItem(self, items=None, key=None, value=None, owner=None, **reqSettings):\n \"\"\"\n\n :param items:\n :param key:\n :param value:\n :param owner:\n :param reqSettings:\n :return: result, success. number of stored items, list of keys or ids successfully created\n \"\"\"\n values = dict()\n if items is not None:\n values[\"items\"] = items\n else:\n if key is not None:\n values[\"key\"] = key\n if value is not None:\n values[\"value\"] = value\n if owner is not None:\n values[\"owner\"] = owner\n content, response = self.call('newItem', values, reqSettings)\n return endpoint.Result(result=content.get('result'),\n success=content.get('success',()),\n invalid=content.get('invalid',()),\n message=content.get('message',()),\n response=response)\n\n\n def setItem(self, items=None, key=None, value=None, owner=None, id=None, **reqSettings):\n \"\"\"\n\n :param items:\n :param key:\n :param value:\n :param owner:\n :param id:\n :param reqSettings:\n :return: result, success. number of stored items, list of keys or ids successfully updated\n \"\"\"\n values = dict()\n if items is not None:\n values[\"items\"] = items\n if key is not None:\n values[\"key\"] = key\n if owner is not None:\n values[\"owner\"] = owner\n if value is not None:\n values[\"value\"] = value\n if id is not None:\n values[\"id\"] = id\n content, response = self.call('setItem', values, reqSettings)\n return endpoint.Result(result=content.get('result'),\n success=content.get('success',()),\n invalid=content.get('invalid',()),\n message=content.get('message',()),\n response=response)\n\n\n def removeItem(self, items=None, key=None, owner=None, id=None, **reqSettings):\n \"\"\"\n\n :param items:\n :param key:\n :param owner:\n :param id:\n :param reqSettings:\n :return: result, success. number of stored items, list of keys or ids successfully removed\n \"\"\"\n values = dict()\n if items is not None:\n values[\"items\"] = items\n if owner is not None:\n values[\"owner\"] = owner\n if key is not None:\n if isinstance(key, (list,tuple)):\n # convert to items if a list of keys\n if not \"items\" in values:\n values[\"items\"] = []\n values[\"items\"] = self.toItems(key, owner=owner)\n else:\n values[\"key\"] = key\n if id is not None:\n if isinstance(id, (list,tuple)):\n # convert to items if a list of ids\n if not \"items\" in values:\n values[\"items\"] = []\n values[\"items\"] = self.toItems(ids=id, owner=owner)\n else:\n values[\"id\"] = id\n content, response = self.call('removeItem', values, reqSettings)\n return endpoint.Result(result=content.get('result'),\n success=content.get('success',()),\n message=content.get('message',()),\n response=response)\n\n\n def list(self, key=None, sort=None, order=None, size=None, start=None, owner=None, **reqSettings):\n \"\"\"\n\n :param key:\n :param sort:\n :param order:\n :param size:\n :param start:\n :param owner:\n :param reqSettings:\n :return: item result set {\"items\":[items], \"start\":number, \"size\":number, \"total\":number}\n \"\"\"\n values = dict()\n if key is not None:\n values[\"key\"] = key\n if sort is not None:\n values[\"sort\"] = sort\n if order is not None:\n values[\"order\"] = order\n if size is not None:\n values[\"size\"] = size\n if start is not None:\n values[\"start\"] = start\n if owner is not None:\n values[\"owner\"] = owner\n content, response = self.call('list', values, reqSettings)\n # todo result set class with iterator\n if not content:\n return endpoint.Result(items=(), start=1, size=0, response=response)\n return endpoint.Result(response=response, **content)\n\n\n def keys(self, order=None, size=None, start=None, owner=None, **reqSettings):\n \"\"\"\n\n :param order:\n :param size:\n :param start:\n :param owner:\n :param reqSettings:\n :return: result set {\"keys\":[strings], \"start\":number, \"size\":number, \"total\":number}\n \"\"\"\n values = dict()\n if order is not None:\n values[\"order\"] = order\n if size is not None:\n values[\"size\"] = size\n if start is not None:\n values[\"start\"] = start\n if owner is not None:\n values[\"owner\"] = owner\n content, response = self.call('keys', values, reqSettings)\n # todo result set class with iterator\n if not content:\n return endpoint.Result(keys=(), start=1, size=0, response=response)\n return endpoint.Result(response=response, **content)\n\n\n def allowed(self, permissions, **reqSettings):\n \"\"\"\n\n :param permission: one or multiple permission names\n :param reqSettings:\n :return: dict {permission: True or False}\n \"\"\"\n values = dict(permissions=permissions)\n content, response = self.call('allowed', values, reqSettings)\n return endpoint.Result(response=response, **content)\n\n\n def getPermissions(self, **reqSettings):\n \"\"\"\n\n :param reqSettings:\n :return: list of permission - group assignments\n \"\"\"\n values = dict()\n content, response = self.call('getPermissions', values, reqSettings)\n return content\n\n\n def setPermissions(self, permissions, **reqSettings):\n \"\"\"\n\n :param permissions: dict/list. one or multiple permissions {permission, group, action=\"replace\"}\n :param reqSettings:\n :return: Result(result, message)\n \"\"\"\n values = dict(permissions=permissions)\n content, response = self.call('setPermissions', values, reqSettings)\n return endpoint.Result(result=content.get('result'),\n message=content.get('message',()),\n response=response)\n\n\n def getOwner(self, key=None, id=None, **reqSettings):\n \"\"\"\n\n :param key:\n :param id:\n :param reqSettings:\n :return: owner\n \"\"\"\n values = dict(key=key, id=id)\n content, response = self.call('getOwner', values, reqSettings)\n return endpoint.Result(items=content.get('items'),\n message=content.get('message',()),\n response=response)\n\n\n def setOwner(self, newOwner, items=None, key=None, owner=None, id=None, **reqSettings):\n \"\"\"\n\n :param newOwner:\n :param items:\n :param key:\n :param owner:\n :param id:\n :param items:\n :param reqSettings:\n :return: Result(result, message)\n \"\"\"\n values = dict(newOwner=newOwner)\n if items is not None:\n values[\"items\"] = items\n if key is not None:\n values[\"key\"] = key\n if owner is not None:\n values[\"owner\"] = owner\n if id is not None:\n values[\"id\"] = id\n content, response = self.call('setOwner', values, reqSettings)\n return endpoint.Result(response=response, **content)\n\n\n def toItems(self, keys=None, ids=None, owner=None, items=None):\n # convert a list of keys and/or ids to items including owner\n if items is None:\n items = []\n if keys is not None:\n if owner is None:\n for key in keys:\n item = dict(key=key)\n items.append(item)\n else:\n for key in keys:\n item = dict(key=key, owner=owner)\n items.append(item)\n if ids is not None:\n if owner is None:\n for id in ids:\n item = dict(id=id)\n items.append(item)\n else:\n for id in ids:\n item = dict(id=id, owner=owner)\n items.append(item)\n return items","sub_path":"pynive_client/datastore.py","file_name":"datastore.py","file_ext":"py","file_size_in_byte":11633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"525214249","text":"import os\nimport pickle\nimport sys\nimport time\nfrom LRMF import *\nimport pandas as pd\nimport scipy.sparse\nimport tensorflow.compat.v1 as tf\nimport numpy as np\n\nimport Tree\nimport utils\n\ntf.disable_v2_behavior()\n\nDATA_ROOT = 'data/ciao_from_them'\n\n\ndef load_data(csv_file):\n data = pd.read_csv(csv_file)\n return data\n\ntrain_data = pd.read_csv('../data/eachmovie/training_updated_each_movie_25_75.csv')\ntest_data = pd.read_csv('../data/eachmovie/testing_updated_each_movie_25_75.csv')\nsocial_data = load_data('../data/eachmovie/socials_updated_ids.csv')\nnum_users = max(len(train_data['uid'].unique()), len(test_data['uid'].unique()))\nnum_items = max(len(train_data['iid'].unique()), len(test_data['iid'].unique()))\n\nwith open('../data/eachmovie/best_each_movie_model_25_75.pkl', 'rb') as f:\n lrmf:LRMF = pickle.load(f)\ntree = lrmf.tree\n\ndef writeline_and_time(s):\n sys.stdout.write(s)\n sys.stdout.flush()\n return time.time()\n\n\nclass EATNN:\n \"\"\"\n Reproduction of paper: \"An Efficient Adaptive Transfer Neural Network for Social-aware Recommendation\"\n Authors: Chong Chen, Min Zhang, Chenyang Wang, Weizhi Ma, Minming Li, Shaoping Ma\n url: http://www.thuir.cn/group/~mzhang/publications/SIGIR2019ChenC.pdf\n \"\"\"\n\n def __init__(self, n_users, n_items, max_questions, max_items, max_friends, embedding_size=64, attention_size=32):\n \"\"\"\n Constructs object of EATNN class\n\n :param n_users: Number of users\n :param n_items: Number of items\n :param max_questions: Max number of questions for all users\n :param max_items: Max number of items for all users\n :param max_friends: Max number of friendships for all users\n :param embedding_size: Size of embeddings (d in paper). Defaults to 64\n :param attention_size: Size of output from attention network (k in paper). Defaults to 32\n \"\"\"\n self.n_users = n_users\n self.n_items = n_items\n self.embedding_size = embedding_size\n self.attention_size = attention_size\n self.max_items = max_items\n self.max_friends = max_friends\n self.max_questions = max_questions\n # weighting for entries in R\n self.weight_r = 0.1\n # weighting for entries in X\n self.weight_x = 0.1\n # weighting for entries in Q\n self.weight_q = 0.1\n # parameter to adjust weight of social interactions\n self.mu = 0.1\n # regularization terms\n self.lambda_bilinear = [1e-3, 1e-1, 1e-2, 1e-1]\n\n def _create_variables(self):\n \"\"\"\n Creates/instantiates variables for model such that we can look them up when learning and making predictions\n \"\"\"\n # Weights to map uid into embeddings representing shared knowledge in item and social domains (u^c in paper)\n self.uw_c = tf.Variable(tf.random.truncated_normal(shape=[self.n_users, self.embedding_size],\n mean=0.0, stddev=0.01, dtype=tf.float32, name='uc'))\n # Weights to map uid into embeddings representing preferences to items (u^i in paper)\n self.uw_i = tf.Variable(tf.random.truncated_normal(shape=[self.n_users, self.embedding_size],\n mean=0.0, stddev=0.01, dtype=tf.float32, name='ui'))\n # Weights to map uid into embeddings preferences to items (u^s in paper)\n self.uw_s = tf.Variable(tf.random.truncated_normal(shape=[self.n_users, self.embedding_size],\n mean=0.0, stddev=0.01, dtype=tf.float32, name='us'))\n # Weights to map uid into embeddings for questionnaires\n self.uw_q = tf.Variable(tf.random.truncated_normal(shape=[self.n_users, self.embedding_size],\n mean=0.0, stddev=0.01, dtype=tf.float32, name='uq'))\n # TODO: figure out why they +1 in sizes\n # Embeddings for items (M x D)\n self.Q = tf.Variable(tf.random.truncated_normal(shape=[self.n_items + 1, self.embedding_size],\n mean=0.0, stddev=0.01, dtype=tf.float32, name='Q'))\n # Embeddings for social interactions (N x D)\n self.G = tf.Variable(tf.random.truncated_normal(shape=[self.n_users + 1, self.embedding_size],\n mean=0.0, stddev=0.01, dtype=tf.float32, name='G'))\n # Embeddings for questionnaires (M x D)\n self.V = tf.Variable(tf.random.truncated_normal(shape=[self.n_items + 1, self.embedding_size],\n mean=0.0, stddev=0.01, dtype=tf.float32, name='V'))\n\n # Weights used in item domain prediction layer\n self.H_i = tf.Variable(tf.constant(0.01, shape=[self.embedding_size, 1]), name='hi')\n # Weights used in social domain prediction layer\n self.H_s = tf.Variable(tf.constant(0.01, shape=[self.embedding_size, 1]), name='hf')\n # Weights used in questionnaire domain prediction layer\n self.H_q = tf.Variable(tf.constant(0.01, shape=[self.embedding_size, 1]), name='hq')\n\n # Item domain attention network parameters\n self.W_item = tf.Variable(\n tf.random.truncated_normal(shape=[self.embedding_size, self.attention_size], mean=0.0, stddev=tf.sqrt(\n tf.divide(2.0, self.attention_size + self.embedding_size))), dtype=tf.float32, name='Witem')\n self.B_item = tf.Variable(tf.constant(0.00, shape=[self.attention_size]), name='Bitem') # 1 x k\n self.H_item = tf.Variable(tf.constant(0.01, shape=[self.attention_size, 1], name='Hitem')) # k x 1\n\n # Social domain attention network parameters\n self.W_social = tf.Variable(\n tf.random.truncated_normal(shape=[self.embedding_size, self.attention_size], mean=0.0, stddev=tf.sqrt(\n tf.divide(2.0, self.attention_size + self.embedding_size))), dtype=tf.float32, name='Wsocial')\n self.B_social = tf.Variable(tf.constant(0.00, shape=[self.attention_size]), name='Bsocial') # 1 x k\n self.H_social = tf.Variable(tf.constant(0.01, shape=[self.attention_size, 1], name='Hsocial')) # k x 1\n\n # Questionnaire domain attention network parameters\n self.W_question = tf.Variable(\n tf.random.truncated_normal(shape=[self.embedding_size, self.attention_size], mean=0.0, stddev=tf.sqrt(\n tf.divide(2.0, self.attention_size + self.embedding_size))), dtype=tf.float32, name='Wquestion')\n self.B_question = tf.Variable(tf.constant(0.00, shape=[self.attention_size]), name='Bquestion') # 1 x k\n self.H_question = tf.Variable(tf.constant(0.01, shape=[self.attention_size, 1], name='Hquestion')) # k x 1\n\n def _create_placeholders(self):\n self.input_u = tf.placeholder(tf.int32, [None, 1], name=\"input_uid\")\n self.input_i = tf.placeholder(tf.int32, [None, 1], name='input_iid')\n\n self.input_ur = tf.placeholder(tf.int32, [None, self.max_items], name=\"input_ur\")\n self.input_uf = tf.placeholder(tf.int32, [None, self.max_friends], name=\"input_ur\")\n self.input_uq = tf.placeholder(tf.int32, [None, self.max_questions], name='input_uq')\n\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n\n def _item_attentive_transfer(self):\n \"\"\"\n Item attentive transfer (eq. 5)\n \"\"\"\n # eq. 3 for computing attentions\n item_attention = tf.exp(tf.matmul(tf.nn.relu(tf.matmul(self.u_i, self.W_item) + self.B_item), self.H_item))\n common_attention = tf.exp(tf.matmul(tf.nn.relu(tf.matmul(self.u_c, self.W_item) + self.B_item), self.H_item))\n # eq. 4 for computing weights\n item_weight = tf.divide(item_attention, item_attention + common_attention)\n common_weight = 1.0 - item_weight\n # eq. 5 for computing transferred user embedding\n user_embedding = item_weight * self.u_i + common_weight * self.u_c\n\n # returning user embedding, so that we can make predictions. Item weight such that we can analyse,\n # when it's low or high\n return user_embedding, item_weight\n\n def _social_attentive_transfer(self):\n \"\"\"\n Social attentive transfer (eq. 5)\n \"\"\"\n # eq. 3 for computing attentions\n social_attention = tf.exp(\n tf.matmul(tf.nn.relu(tf.matmul(self.u_s, self.W_social) + self.B_social), self.H_social))\n common_attention = tf.exp(\n tf.matmul(tf.nn.relu(tf.matmul(self.u_c, self.W_social) + self.B_social), self.H_social))\n # eq. 4 for computing weights\n social_weight = tf.divide(social_attention, social_attention + common_attention)\n common_weight = 1.0 - social_weight\n # eq. 5 for computing transferred user embedding\n user_embedding = social_weight * self.u_s + common_weight * self.u_c\n\n # returning user embedding, so that we can make predictions. Social weight such that we can analyse,\n # when it's low or high\n return user_embedding, social_weight\n\n def _questionnaire_attentive_transfer(self):\n \"\"\"\n Transferring knowledge from questionnaires. Our contribution.\n Works the same way, as the attentive networks in paper.\n \"\"\"\n # eq. 3 for computing attentions\n q_attention = tf.exp(\n tf.matmul(tf.nn.relu(tf.matmul(self.u_q, self.W_question) + self.B_question), self.H_question))\n common_attention = tf.exp(\n tf.matmul(tf.nn.relu(tf.matmul(self.u_c, self.W_question) + self.B_question), self.H_question))\n # eq. 4 for computing weights\n q_weight = tf.divide(q_attention, q_attention + common_attention)\n common_weight = 1.0 - q_weight\n # eq. 5 for computing transferred user embedding\n user_embedding = q_weight * self.u_q + common_weight * self.u_c\n\n # returning user embedding, so that we can make predictions. Social weight such that we can analyse,\n # when it's low or high\n return user_embedding, q_weight\n\n def _create_inference(self):\n \"\"\"\n Inference used for learning model parameters\n \"\"\"\n # Mapped embeddings for users (u^c, u^i and u^s)\n self.u_c = tf.nn.embedding_lookup(self.uw_c, self.input_u)\n self.u_c = tf.reshape(self.u_c, [-1, self.embedding_size])\n self.u_i = tf.nn.embedding_lookup(self.uw_i, self.input_u)\n self.u_i = tf.reshape(self.u_i, [-1, self.embedding_size])\n self.u_s = tf.nn.embedding_lookup(self.uw_s, self.input_u)\n self.u_s = tf.reshape(self.u_s, [-1, self.embedding_size])\n # Our contribution (haven't added u^c2 because I figured, if we use the same u^c, we essentially use\n # shared knowledge between all domains. Maybe that is favorable?\n # TODO: We could test with only sharing between item domain and questionnaire domain.\n self.u_q = tf.nn.embedding_lookup(self.uw_q, self.input_u)\n self.u_q = tf.reshape(self.u_q, [-1, self.embedding_size])\n\n # Attentive transferred embeddings for users (p^I_u and p^S_u)\n self.P_iu, self.item_w = self._item_attentive_transfer()\n self.P_su, self.social_w = self._social_attentive_transfer()\n # Our contribution\n self.P_qu, self.question_w = self._questionnaire_attentive_transfer()\n\n # adding dropout on transferred embeddings to avoid overfitting\n self.P_iu = tf.nn.dropout(self.P_iu, self.dropout_keep_prob)\n self.P_su = tf.nn.dropout(self.P_su, self.dropout_keep_prob)\n self.P_qu = tf.nn.dropout(self.P_qu, self.dropout_keep_prob)\n\n # Looking up item embeddings from data\n self.pos_item = tf.nn.embedding_lookup(self.Q, self.input_ur)\n # Items used for this inference\n self.pos_n_ratings = tf.cast(tf.not_equal(self.input_ur, self.n_items), 'float32')\n # Performing matrix multiplication to obtain item embeddings for this inference\n self.pos_item = tf.einsum('ab,abc->abc', self.pos_n_ratings, self.pos_item)\n # Transferred embeddings for items multiplied with item embeddings\n self.pos_r = tf.einsum('ac,abc->abc', self.P_iu, self.pos_item)\n # Need to multiply with H_i as well\n self.pos_r = tf.einsum('ajk,kl->ajl', self.pos_r, self.H_i)\n self.pos_r = tf.reshape(self.pos_r, [-1, max_items])\n\n # Social embeddings lookup\n self.pos_friend = tf.nn.embedding_lookup(self.G, self.input_uf)\n # Social interactions used for this inference\n self.pos_n_friends = tf.cast(tf.not_equal(self.input_uf, self.n_users), 'float32')\n # Obtaining embeddings for socials used in this inference\n self.pos_friend = tf.einsum('ab,abc->abc', self.pos_n_friends, self.pos_friend)\n # Multiplying with social attentive transferred user embeddings\n self.pos_f = tf.einsum('ac,abc->abc', self.P_su, self.pos_friend)\n # Need to multiply with H_s as well\n self.pos_f = tf.einsum('abc,cd->abd', self.pos_friend, self.H_s)\n self.pos_f = tf.reshape(self.pos_f, [-1, max_friends])\n\n # Questionnaire embeddings lookup\n self.pos_questions = tf.nn.embedding_lookup(self.V, self.input_uq)\n # Answered questions for this inference\n self.pos_n_questions = tf.cast(tf.not_equal(self.input_uq, self.n_items), 'float32')\n # Obtaining embeddings for questions used in this inference\n self.pos_questions = tf.einsum('ab,abc->abc', self.pos_n_questions, self.pos_questions)\n # Multiplying with question attentive transferred user embeddings\n self.pos_q = tf.einsum('ac,abc->abc', self.P_qu, self.pos_questions)\n # Need to multiply with H_q as well\n self.pos_q = tf.einsum('abc,cd->abd', self.pos_questions, self.H_q)\n self.pos_q = tf.reshape(self.pos_q, [-1, self.max_questions])\n\n def _prediction(self):\n \"\"\"\n Computes prediction for R_uv (eq. 6 in paper)\n \"\"\"\n # Computing dot product p^I_u dot q_v\n dot = tf.einsum('ac,bc->abc', self.P_iu, self.Q)\n # Multiplying with H_i\n pred = tf.einsum('abc,cd->abd', dot, self.H_i)\n pred = tf.reshape(pred, [-1, self.n_items + 1])\n return pred\n\n def _create_loss(self):\n # Loss for item domain (eq. 13)\n self.loss_item = self.weight_r * tf.reduce_sum(\n tf.reduce_sum(\n tf.reduce_sum(\n tf.einsum('ab,ac->abc', self.Q, self.Q), 0) *\n tf.reduce_sum(tf.einsum('ab,ac->abc', self.P_iu, self.P_iu), 0) *\n tf.matmul(self.H_i, self.H_i, transpose_b=True), 0), 0)\n self.loss_item += tf.reduce_sum((1.0 - self.weight_r) * tf.square(self.pos_r) - 2.0 * self.pos_r)\n\n # Loss for social domain (eq. 14)\n self.loss_social = self.weight_x * tf.reduce_sum(\n tf.reduce_sum(\n tf.reduce_sum(\n tf.einsum('ab,ac->abc', self.G, self.G), 0) *\n tf.reduce_sum(tf.einsum('ab,ac->abc', self.P_su, self.P_su), 0) *\n tf.matmul(self.H_s, self.H_s, transpose_b=True), 0), 0)\n self.loss_social += tf.reduce_sum((1.0 - self.weight_x) * tf.square(self.pos_f) - 2.0 * self.pos_f)\n\n # TODO: consider this loss for questionnaire\n self.loss_question = self.weight_q * tf.reduce_sum(\n tf.reduce_sum(\n tf.reduce_sum(\n tf.einsum('ab,ac->abc', self.V, self.V), 0) *\n tf.reduce_sum(tf.einsum('ab,ac->abc', self.P_qu, self.P_qu), 0) *\n tf.matmul(self.H_q, self.H_q, transpose_b=True), 0), 0)\n self.loss_item += tf.reduce_sum((1.0 - self.weight_q) * tf.square(self.pos_q) - 2.0 * self.pos_q)\n\n # adding l2 regularization on social, item and questionnaire attentive user embeddings\n self.l2_loss = tf.nn.l2_loss(self.P_iu + self.P_su + self.P_qu)\n # l2 regularization on item domain model parameters\n self.l2_loss_item = tf.nn.l2_loss(self.W_item) + tf.nn.l2_loss(self.B_item) + tf.nn.l2_loss(self.H_item)\n # l2 regularization on social domain model parameters\n self.l2_loss_social = tf.nn.l2_loss(self.W_social) + tf.nn.l2_loss(self.B_social) + tf.nn.l2_loss(self.H_social)\n # l2 regularization on questionnaire domain model parameters\n self.l2_loss_question = tf.nn.l2_loss(self.W_question) + tf.nn.l2_loss(self.B_question) + tf.nn.l2_loss(\n self.H_question)\n\n # adding everything together\n self.loss = self.loss_item + self.mu * self.loss_social + self.mu * self.loss_question \\\n + self.lambda_bilinear[0] * self.l2_loss \\\n + self.lambda_bilinear[1] * self.l2_loss_item \\\n + self.lambda_bilinear[2] * self.l2_loss_social \\\n + self.lambda_bilinear[3] * self.l2_loss_question\n\n def build_graph(self):\n \"\"\"\n Builds the tensorflow graph, i.e. the model\n \"\"\"\n self._create_placeholders()\n self._create_variables()\n self._create_inference()\n self._create_loss()\n self.prediction = self._prediction()\n\n\ndef train_step(u_batch, i_batch, s_batch, q_batch):\n \"\"\"\n A single training step\n \"\"\"\n\n feed_dict = {\n model.input_u: u_batch,\n model.input_ur: i_batch,\n model.input_uf: s_batch,\n model.input_uq: q_batch,\n model.dropout_keep_prob: 0.3,\n }\n _, loss, wi, ws, wq = sess.run(\n [train_op, model.loss, model.item_w, model.social_w, model.question_w], feed_dict)\n return loss, wi, ws, wq\n\n\ndef get_train_instances(train_r_set: dict, train_s_set: dict, train_q_set: dict):\n user_train, item_train, social_train, question_train = [], [], [], []\n for user in train_r_set.keys():\n user_train.append(user)\n item_train.append(train_r_set[user])\n social_train.append(train_s_set[user])\n question_train.append(train_q_set[user])\n\n user_train = np.array(user_train)\n item_train = np.array(item_train)\n social_train = np.array(social_train)\n question_train = np.array(question_train)\n user_train = user_train[:, np.newaxis]\n\n return user_train, item_train, social_train, question_train\n\ndef eval_user(uidx, actuals):\n feed_dict = {\n model.input_u: np.array([uidx])[:, np.newaxis],\n model.dropout_keep_prob: 1.0,\n }\n\n predictions = sess.run(model.prediction, feed_dict)\n predictions = np.array(predictions)\n # 1 too many predictions. Maybe because of adding 1 extra item embedding earlier.\n predictions = np.delete(predictions, -1, axis=1)\n\n idx_top_k_items = np.argpartition(-predictions, 10, 1)\n tp = 1. / np.log2(np.arange(2, 10 + 2))\n\n DCGrelevents = [1 if actuals[p] == 1 else 0 for p in idx_top_k_items[0][:10]]\n DCG = np.sum(DCGrelevents*tp)\n IDCG = tp[:min(sum(actuals != 0), 10)].sum()\n return DCG / IDCG\n\ndef eval_step(testset: dict, train_r, test_r, batch_size: int):\n \"\"\"\n Evaluates the model (recall and ndcg)\n \"\"\"\n test_users = np.fromiter(testset.keys(), dtype=int)\n\n g0, g1, g2, g3, g4, g5, g6, g7, g8, g9, g10 = [],[],[],[],[],[],[],[],[],[],[]\n\n for u in tqdm(test_users, desc='Computing results for groups'):\n num_ratings = sum(train_r.toarray()[u] != 0)\n if num_ratings > 10: continue\n if num_ratings == 10: g10.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 9: g9.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 8: g8.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 7: g7.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 6: g6.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 5: g5.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 4: g4.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 3: g3.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 2: g2.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 1: g1.append(eval_user(u, test_r.toarray()[u]))\n if num_ratings == 0: g0.append(eval_user(u, test_r.toarray()[u]))\n\n print(f'g0:{np.mean(g0)}, g1:{np.mean(g1)}, g2:{np.mean(g2)}'\n f'g3:{np.mean(g3)}, g4:{np.mean(g4)}, g5:{np.mean(g5)}'\n f'g6:{np.mean(g6)}, g7:{np.mean(g7)}, g8:{np.mean(g8)}'\n f'g9:{np.mean(g9)}, g10:{np.mean(g10)}')\n\n\ndef print_metrics(ndcgs, precisions, recalls):\n ks = [1, 2, 5] # 10, 50, 100\n for i, k in enumerate(ks):\n print(f'NDCG@{k}: {ndcgs[i]} \\t Precision@{k}: {precisions[i]} \\t Recall@{k}: {recalls[i]}')\n\ndef preprocess_data(u_train, u_test, i_train, i_test, u_friend, v_friend):\n # Building interactions test set\n test_set = {}\n for u in range(len(u_test)):\n user = u_test[u]\n if user in test_set:\n test_set[user].append(i_test[u])\n else:\n test_set[user] = [i_test[u]]\n\n # Building training set for questionnaire\n train_q_set = {}\n max_questions = 0\n for u in np.unique(u_train):\n leaf = Tree.traverse_a_user(u, train_r.toarray(), tree)\n train_q_set[u] = leaf.raw_globals + leaf.raw_locals\n # making sure all inputs are of same size\n for u in train_q_set.keys():\n if len(train_q_set[u]) > max_questions:\n max_questions = len(train_q_set[u])\n for u in train_q_set.keys():\n while len(train_q_set[u]) < max_questions:\n train_q_set[u].append(num_items)\n\n # Building training set for interactions\n train_set = {}\n max_items = 0\n for u in range(len(u_train)):\n # Not considering items asked as question\n user = u_train[u]\n if i_train[u] in train_q_set[user]:\n continue\n if u_train[u] in train_set:\n train_set[u_train[u]].append(i_train[u])\n else:\n train_set[u_train[u]] = [i_train[u]]\n # making sure all inputs are of same size\n for u in train_set.keys():\n if len(train_set[u]) > max_items:\n max_items = len(train_set[u])\n for u in train_set.keys():\n while len(train_set[u]) < max_items:\n train_set[u].append(num_items)\n\n # Building training set for social domain\n train_f_set = {}\n max_friends = 0\n for i in range(len(u_friend)):\n if u_friend[i] in train_f_set:\n train_f_set[u_friend[i]].append(v_friend[i])\n else:\n train_f_set[u_friend[i]] = [v_friend[i]]\n for i in train_f_set.keys():\n if len(train_f_set[i]) > max_friends:\n max_friends = len(train_f_set[i])\n for i in train_set.keys():\n if not i in train_f_set:\n train_f_set[i] = [num_users]\n while len(train_f_set[i]) < max_friends:\n train_f_set[i].append(num_users)\n\n return test_set, train_set, train_f_set, train_q_set, max_questions, max_items, max_friends\n\n\nif __name__ == '__main__':\n random_seed = 2020\n\n u_train = np.array(train_data['uid'], dtype=np.int32)\n u_test = np.array(test_data['uid'], dtype=np.int32)\n i_train = np.array(train_data['iid'], dtype=np.int32)\n i_test = np.array(test_data['iid'], dtype=np.int32)\n u_friend = np.array(social_data['uid'], dtype=np.int32)\n v_friend = np.array(social_data['sid'], dtype=np.int32)\n\n n_train_users = np.ones(len(u_train))\n train_r = scipy.sparse.csr_matrix((n_train_users, (u_train, i_train)), dtype=np.int16, shape=(num_users, num_items))\n n_test_users = np.ones(len(u_test))\n test_r = scipy.sparse.csr_matrix((n_test_users, (u_test, i_test)), dtype=np.int16, shape=(num_users, num_items))\n\n test_set, train_set, train_f_set, train_q_set, max_questions, max_items, max_friends = \\\n preprocess_data(u_train, u_test, i_train, i_test, u_friend, v_friend)\n\n batch_size = 128\n with tf.Graph().as_default():\n tf.set_random_seed(random_seed)\n\n session_conf = tf.ConfigProto()\n session_conf.gpu_options.allow_growth = True\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n model = EATNN(num_users, num_items, max_questions, max_items, max_friends)\n model.build_graph()\n\n optimizer = tf.train.AdagradOptimizer(learning_rate=0.05, initial_accumulator_value=1e-8).minimize(\n model.loss)\n train_op = optimizer\n\n sess.run(tf.global_variables_initializer())\n\n user_train, item_train, friend_train, question_train = get_train_instances(train_set, train_f_set,\n train_q_set)\n\n for epoch in range(100):\n print(f'Epoch: {epoch}')\n start_t = writeline_and_time('\\tUpdating...')\n\n shuffled_indices = np.random.permutation(np.arange(len(user_train)))\n user_train = user_train[shuffled_indices]\n item_train = item_train[shuffled_indices]\n friend_train = friend_train[shuffled_indices]\n question_train = question_train[shuffled_indices]\n\n n_batches = int(len(user_train) / batch_size)\n loss = 0.0\n for batch_num in range(n_batches):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, len(user_train))\n\n u_batch = user_train[start_index:end_index]\n i_batch = item_train[start_index:end_index]\n f_batch = friend_train[start_index:end_index]\n q_batch = question_train[start_index:end_index]\n\n batch_loss, wi, wf, wq = train_step(u_batch, i_batch, f_batch, q_batch)\n loss += batch_loss\n #print(f'itmems{wi}, friends{wf}, questions{wq}')\n print('\\r\\tUpdating: time=%.2f'\n % (time.time() - start_t))\n\n if epoch % 3 == 0:\n eval_step(test_set, train_r, test_r, batch_size)\n\n","sub_path":"EATNN/EATNNNDCG.py","file_name":"EATNNNDCG.py","file_ext":"py","file_size_in_byte":26087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"163223531","text":"# coding=utf-8\r\n\"\"\"\r\nThe central town, which is the place where mud players start/log in\r\n\r\n'Tale' mud driver, mudlib and interactive fiction framework\r\nCopyright by Irmen de Jong (irmen@razorvine.net)\r\n\"\"\"\r\n\r\nfrom __future__ import absolute_import, print_function, division, unicode_literals\r\nfrom tale.base import Location, Exit, Item, Container, Living, Key\r\nfrom tale.npc import NPC\r\nfrom tale.player import Player\r\nfrom tale.errors import ActionRefused\r\nfrom tale.items.basic import Boxlike, Wearable\r\nfrom tale import pubsub\r\nfrom tale import lang\r\n\r\npending_actions = pubsub.topic(\"driver-pending-actions\")\r\n\r\ndef init(driver):\r\n # called when zone is first loaded\r\n # board.load()\r\n pass\r\n\r\ngym = Location(\"Gymnasium\",\r\n \"\"\"\r\n The gymnasium is where the Parsely Greens have their home games.\r\n It's currently empty of sweaty athletes and cheering fans.\r\n \"\"\")\r\n\r\nlocker_room = Location(\"Locker Room\",\r\n \"\"\"\r\n You are in a stereotypical high school locker room.\r\n It smells of dirty athletic socks and despair.\r\n \"\"\")\r\n\r\ngym.add_exits([\r\n Exit([\"east\", \"locker room\", \"e\"],\r\n locker_room,\r\n \"You smell a locker room to the east.\",\r\n \"A door in the eastern wall of the gym says 'Locker Room'.\"),\r\n Exit([\"north\", \"hall\", \"n\"], \r\n \"hallways.south_hallway\",\r\n \"Parsely High is to the north\",\r\n \"A door in the north wall of the gym leads to the rest of the school.\")\r\n])\r\n\r\nlocker_room.add_exits([\r\n Exit([\"exit\", \"out\", \"west\", \"door\", \"w\"],\r\n gym,\r\n \"The gym is to the west.\",\r\n \"To the west you can see Parsely High's gymnasium.\")\r\n])\r\n\r\n\r\nclass GlassesCase(Boxlike):\r\n def init(self):\r\n super(Boxlike, self).init()\r\n self.opened = False\r\n self.txt_title_closed = self._title\r\n self.txt_title_open_filled = self._title\r\n self.txt_title_open_empty = \"empty \" + self._title\r\n self.txt_descr_closed = \"The {} is shut.\".format(self.name)\r\n self.txt_descr_open_filled = \"It is an open.\"\r\n self.txt_descr_open_empty = \"It is an open.\"\r\n\r\n def allow_item_move(self, actor, verb=\"move\"):\r\n pass\r\n\r\n\r\nclass UntakableContainer(Container):\r\n def allow_item_move(self, actor, verb=\"move\"):\r\n raise ActionRefused(\"You can't {} {}.\".format(verb, self.title))\r\n\r\n # def insert(self, item, actor):\r\n # if self.opened and item is \"glasses\":\r\n # super(Boxlike, self).insert(item, actor)\r\n # else:\r\n # raise ActionRefused(\"No matter how hard you try, you can't fit {} in the box.\".format(item.title))\r\n\r\nclass Glasses(Wearable):\r\n \r\n def init(self, wearing=False):\r\n super(Glasses, self).init()\r\n self.wearing = wearing\r\n\r\n def wearing_glasses(self):\r\n while self.wearing:\r\n pass\r\n\r\n def vision_problems(self):\r\n pass\r\n\r\n\r\nglasses = Item(\"glasses\", \"glasses\", \"pair of ladies eyeglasses.\")\r\nglasses.aliases = {\"glasses\"}\r\nglasses.add_extradesc({\"glasses\"}, \"The horn-rimmed glasses aren't really your style.\")\r\n\r\nglasses_case = GlassesCase(\"case\", \"clamshell case for eyeglasses\")\r\nglasses_case.aliases = {\"case\", \"clamshell case\", \"eyeglasses case\"}\r\nglasses_case.init_inventory([glasses])\r\n\r\ngym.init_inventory([glasses_case])\r\n\r\nclass MovableObject(Boxlike):\r\n\r\n def allow_item_move(self, actor, verb=\"take\"):\r\n raise ActionRefused(\"You can't {} {}.\".format(verb, self.title))\r\n\r\n def move(self, target, actor=None, silent=False, is_player=False, verb=\"move\"):\r\n \"\"\"\r\n Leave the current location, enter the new location (transactional).\r\n \"\"\"\r\n actor = actor or self\r\n original_location = None\r\n if self.location:\r\n original_location = self.location\r\n self.location.remove(self, actor)\r\n try:\r\n target.insert(self, actor)\r\n except:\r\n # insert in target failed, put back in original location\r\n original_location.insert(self, actor)\r\n raise\r\n # # queue event\r\n # if is_player:\r\n # pending_actions.send(lambda who=self, where=target: original_location.notify_player_left(who, where))\r\n # else:\r\n # pending_actions.send(lambda who=self, where=target: original_location.notify_npc_left(who, where))\r\n else:\r\n target.insert(self, actor)\r\n # queue event\r\n # if is_player:\r\n # pending_actions.send(lambda who=self, where=original_location: target.notify_player_arrived(who, where))\r\n # else:\r\n # pending_actions.send(lambda who=self, where=original_location: target.notify_npc_arrived(who, where))\r\n\r\n def handle_verb(self, parsed, actor):\r\n if parsed.verb in (\"move\", \"push\"):\r\n xt = parsed.args[-1]\r\n for d, e in self.location.exits.items():\r\n if e.target.exits:\r\n print(e.target)\r\n if xt in d:\r\n print(\"match found!\")\r\n try:\r\n self.move(str(e.target))\r\n except:\r\n print(\"Not it.\")\r\n # try:\r\n # actor.tell(\"You {} the janitor's cart along ahead of you.\".format(parsed.verb))\r\n # self.move(target=xt)\r\n # Player.move(target=xt)\r\n # xt.allow_passage(self)\r\n # except ActionRefused:\r\n # continue\r\n # else:\r\n # return xt\r\n # return None\r\n # actor.tell(\"You {} the janitor's cart along ahead of you.\".format(parsed.verb))\r\n # self.move(target=v.target.title)\r\n # Player.move(target=v.target.title)\r\n else:\r\n raise ActionRefused(\"You can't {} it that way!\".format(parsed.verb))\r\n return True\r\n else:\r\n raise ActionRefused(\"What do you want to {}?\".format(parsed.verb))\r\n return False\r\n\r\n\r\n def move_item(self):\r\n \"\"\"\r\n Select a random accessible exit to move to.\r\n Avoids exits to a room that have no exits (traps).\r\n If no suitable exit is found in a few random attempts, return None.\r\n \"\"\"\r\n directions_with_exits = [d for d, e in self.location.exits.items() if e.target.exits]\r\n for direction in directions_with_exits:\r\n if direction in parsed.args:\r\n xt = self.location.exits[direction]\r\n try:\r\n xt.allow_passage(self)\r\n except ActionRefused:\r\n continue\r\n else:\r\n return xt\r\n return None\r\n\r\n # def handle_verb(self, parsed, actor):\r\n # if parsed.verb in (\"move\", \"push\"):\r\n # for k, v in self.location.exits.items():\r\n # if k in parsed.args:\r\n # # print(k,v)\r\n # actor.tell(\"You {} the janitor's cart along ahead of you.\".format(parsed.verb))\r\n # self.move(target=v.target.title)\r\n # Player.move(target=v.target.title)\r\n # else:\r\n # raise ActionRefused(\"You can't {} it that way!\".format(parsed.verb))\r\n # return True\r\n # else:\r\n # raise ActionRefused(\"What do you want to {}?\".format(parsed.verb))\r\n # return False\r\n\r\n\r\n # def move_item(self):\r\n # \"\"\"\r\n # Select a random accessible exit to move to.\r\n # Avoids exits to a room that have no exits (traps).\r\n # If no suitable exit is found in a few random attempts, return None.\r\n # \"\"\"\r\n # directions_with_exits = [d for d, e in self.location.exits.items() if e.target.exits]\r\n # for direction in directions_with_exits:\r\n # if direction in parsed.args:\r\n # xt = self.location.exits[direction]\r\n # try:\r\n # xt.allow_passage(self)\r\n # except ActionRefused:\r\n # continue\r\n # else:\r\n # return xt\r\n # return None\r\n\r\n # def handle_verb(self, parsed, actor):\r\n # if parsed.verb == \"hack\":\r\n # if self in parsed.who_info:\r\n # actor.tell(\"It doesn't need to be hacked, you can just type commands on it.\")\r\n # return True\r\n # elif parsed.who_info:\r\n # raise ActionRefused(\"You can't hack that.\")\r\n # else:\r\n # raise ActionRefused(\"What do you want to hack?\")\r\n # if parsed.verb in (\"type\", \"enter\"):\r\n # if parsed.who_info and self not in parsed.who_info:\r\n # raise ActionRefused(\"You need to type it on the computer.\")\r\n # if parsed.message:\r\n # # type \"bla bla\" on computer (message between quotes)\r\n # action, _, door = parsed.message.partition(\" \")\r\n # self.process_typed_command(action, door, actor)\r\n # return True\r\n # args = list(parsed.args)\r\n # if self.name in args:\r\n # args.remove(self.name)\r\n # for name in self.aliases:\r\n # if name in args:\r\n # args.remove(name)\r\n # if args:\r\n # args.append(\"\")\r\n # self.process_typed_command(args[0], args[1], actor)\r\n # return True\r\n # return False\r\n\r\n def search_item(self, name, include_inventory=True, include_location=True, include_containers_in_inventory=True):\r\n \"\"\"The same as locate_item except it only returns the item, or None.\"\"\"\r\n item, container = self.locate_item(name, include_inventory, include_location, include_containers_in_inventory)\r\n return item # skip the container\r\n\r\nfreshman = NPC(\"freshman\", \"m\", title=\"freshman\", description=\"It's a freshman. They all look the same.\")\r\n\r\nclass Sawdust(Key):\r\n def init(self):\r\n super(Sawdust, self).init()\r\n self.key_code = 111\r\n\r\nsawdust = Sawdust(\"sawdust\", \"sawdust\")\r\nsawdust.add_extradesc({\"sawdust\", \"pink sawdust\"}, \"It's pink sawdust, the kind used to soak up spills and messes.\")\r\n\r\nbucket = Container(\"bucket\", \"bucket\")\r\nbucket.add_extradesc({\"bucket\"}, \"You see an ordinary blue plastic bucket.\")\r\nbucket.init_inventory([sawdust])\r\n\r\ntrash_can = Container(\"trash can\", \"large grey trash can\")\r\ntrash_can.aliases = {\"trash can\", \"trashcan\", \"trash\"}\r\ntrash_can.init_inventory([freshman])\r\n\r\nbroom = Item(\"broom\", \"broom\")\r\nbroom.add_extradesc({\"broom\", \"pushbroom\"}, \"You see a large push-broom for sweeping up messes.\")\r\n\r\njanitors_cart = MovableObject(\"janitor's cart\", \"janitor's cart\")\r\njanitors_cart.aliases = {\"cart\", \"janitor's cart\", \"janitor cart\", \"janitors cart\"}\r\njanitors_cart.add_extradesc({\"cart\", \"janitor's cart\"}, \"The janitor's cart is more or less a trash can on wheels. A bucket of pink sawdust and a broom hang from the cart.\")\r\njanitors_cart.init_inventory([trash_can, bucket, broom])\r\njanitors_cart.verbs = {\r\n # register some custom verbs. You can redefine existing verbs, so be careful.\r\n \"move\": \"Move the cart to a new location.\",\r\n \"push\": \"Move the cart to a new location.\",\r\n}\r\n\r\nlocker_room.init_inventory([janitors_cart])\r\n","sub_path":"students/erica_winberry/project/bbjungle/testing/zones/athletics.py","file_name":"athletics.py","file_ext":"py","file_size_in_byte":11605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"54720192","text":"from django.conf.urls import url, include\nfrom . import views, tasks\n\nurlpatterns = [\n url(r'^api/v1/', include([\n url(r'^contacts/$', views.contacts, name='contacts'),\n ])),\n\n # created a route for now, should be cron job / task\n url(r'^tasks/', include([\n url(r'^sync_data/$', tasks.sync_data, name='sync_data'),\n ]))\n]\n","sub_path":"contacts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608697863","text":"import json\nfrom app import app, api, jwt, db\nfrom app.models.voice import Voice\nfrom flask_restful import Resource, reqparse, abort, request\nfrom datetime import date\n\nvcs_parser = reqparse.RequestParser()\nvcs_parser.add_argument('language', help='ISO 2 letter code', location='json')\nvcs_parser.add_argument('accent', help='2 letter accent code', location='json')\nvcs_parser.add_argument('gender', choices=['male','female'], \\\n help='male|female', location='json')\n\nclass Voices(Resource):\n \"\"\" Class for Voices enpoint \"\"\"\n def post(self):\n \"\"\" Voices enpoint \n \n Args:\n language (str, optional)\n accent (str, optional)\n gender (str, optional)\n \n Returns:\n obj: a list of voiced based on the optional parameters,\n if no options are provided all voices are returned with their details \n \"\"\"\n # get available voices\n args = vcs_parser.parse_args()\n \"\"\" create a query based on the parameters \"\"\"\n query = db.session.query(Voice)\n app.logger.debug(args['language'])\n if args['language'] is not None:\n query = query.filter(Voice.language == args['language'])\n if args['language'] is not None and args['accent'] is not None:\n query = query.filter(Voice.accent == args['accent'])\n if args['gender'] is not None:\n query = query.filter(Voice.gender == args['gender'])\n \"\"\" get voices based on the query \"\"\"\n voices = query.all()\n \"\"\" check if the query returned any voices \"\"\"\n if not voices:\n return {\"message\":\"No voices were found\"}, 204\n \"\"\" create a returnable list of voices and return it as response \"\"\"\n ret_voices = [ v.to_dict() for v in voices ]\n return { 'voices' : ret_voices }\n\nclass VoiceDetails(Resource):\n \"\"\" Class for voice detail endpoint\"\"\"\n def get(self, voice_id):\n \"\"\" Voice details endpoint\n \n Args:\n voice_id (str): voice id\n Returns:\n dict: details of a voice\n \"\"\"\n # get voice details\n voice = Voice.query.get(voice_id)\n if voice is None:\n return {\"message\":\"Voice could not be found\"}, 404\n return voice.to_dict()\n\n\napi.add_resource(Voices, '/voices')\napi.add_resource(VoiceDetails, '/voices/')\n","sub_path":"idlak-server/app/endpoints/voice.py","file_name":"voice.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"554234411","text":"#!/usr/bin/env python\n\nimport itertools\nimport json\nimport math\n\nimport tqdm\n\nfrom reindex_bags_backlog import (\n create_client,\n READ_ONLY_ROLE_ARN,\n ROLE_ARN,\n PROD_CONFIG,\n)\n\n\ndef chunked_iterable(iterable, size):\n it = iter(iterable)\n while True:\n chunk = tuple(itertools.islice(it, size))\n if not chunk:\n break\n yield chunk\n\n\ndef get_chemist_druggist_bag():\n try:\n return json.load(open(\"b19974760.json\"))\n except FileNotFoundError:\n pass\n\n dynamodb = create_client(\"dynamodb\", role_arn=READ_ONLY_ROLE_ARN)\n s3 = create_client(\"s3\", role_arn=READ_ONLY_ROLE_ARN)\n\n table_name = PROD_CONFIG[\"table_name\"]\n\n item = dynamodb.get_item(\n TableName=table_name,\n Key={\"id\": {\"S\": \"digitised/b19974760\"}, \"version\": {\"N\": \"1\"}},\n )[\"Item\"]\n\n bucket = item[\"payload\"][\"M\"][\"namespace\"][\"S\"]\n key = item[\"payload\"][\"M\"][\"path\"][\"S\"]\n\n s3.download_file(Bucket=bucket, Key=key, Filename=\"b19974760.json\")\n\n return json.load(open(\"b19974760.json\"))\n\n\nif __name__ == \"__main__\":\n bag = get_chemist_druggist_bag()\n\n sns = create_client(\"sns\", role_arn=ROLE_ARN)\n\n for file_group in tqdm.tqdm(\n chunked_iterable(bag[\"manifest\"][\"files\"], size=140),\n total=int(math.ceil(len(bag[\"manifest\"][\"files\"]) / 140)),\n ):\n contexts = [\n {\n \"space\": bag[\"space\"],\n \"externalIdentifier\": bag[\"info\"][\"externalIdentifier\"],\n \"hashingAlgorithm\": bag[\"manifest\"][\"checksumAlgorithm\"],\n \"bagLocation\": bag[\"location\"],\n \"file\": f,\n \"createdDate\": bag[\"createdDate\"],\n }\n for f in file_group\n ]\n\n sns.publish(\n TopicArn=\"arn:aws:sns:eu-west-1:975596993436:storage_prod_file_finder_output\",\n Message=json.dumps(contexts),\n )\n\n print(f\"Sent {len(bag['manifest']['files'])} for indexing\")\n","sub_path":"indexer/reindex_files_chemist_and_druggist.py","file_name":"reindex_files_chemist_and_druggist.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"169752083","text":"\"\"\"\nhttps://leetcode.com/problems/is-subsequence/\n\nGiven two strings s and t, check if s is a subsequence of t.\n\nA subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the\ncharacters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of\n\"abcde\" while \"aec\" is not).\n\"\"\"\n\n\nclass Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n\n i = 0\n\n if len(s) == 0:\n return True\n\n if len(t) == 0 or len(s) > len(t):\n return False\n\n ans = False\n\n if len(s) == 1:\n if s in t:\n return True\n else:\n return False\n\n while (i < len(t)):\n if t[i] == s[0]:\n i1 = i + 1\n j = 1\n\n while (i1 < len(t)):\n\n if j == len(s):\n return True\n else:\n if t[i1] == s[j]:\n i1 += 1\n j += 1\n else:\n i1 += 1\n\n if j == len(s):\n return True\n\n i += 1\n\n return False\n\n","sub_path":"Greedy/is_subsequence.py","file_name":"is_subsequence.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"239919927","text":"import os\nimport tempfile\n\nimport math\nimport numpy as np\nfrom eolearn.io import ExportToTiff\nfrom eolearn.core import FeatureType, SaveToDisk, OverwritePermission, LinearWorkflow, EOExecutor\nfrom rio_cogeo.cogeo import cog_translate\nfrom rio_cogeo.profiles import cog_profiles\nfrom sentinelhub import BBox, CRS\nfrom tqdm import tqdm\n\nfrom geogeniustools.eolearn.geogenius_data import GeogeniusEOPatch\nfrom geogeniustools.eolearn.geogenius_io import ImportFromGeogenius\nfrom geogeniustools.eolearn.geogenius_tasks import IndexTask\nfrom geogeniustools.rda.error import PatchSetError\nfrom geogeniustools.s3 import S3\n\n\nclass GeogeniusPatchSet:\n \"\"\"\n GeogeniusPatchSet is a collection of image patches that are generated using the'splitter' method on the\n 'geogenius_image'.\n \"\"\"\n def __init__(self, geogenius_image, splitter, feature=(FeatureType.DATA, 'BANDS')):\n \"\"\"\n :param geogenius_image: Image resource has data values and metadata.\n :type geogenius_image: RDAImage\n :param splitter: A tool that splits the given area into smaller parts withe same pixel size. Given the area it\n calculates its bounding box and splits it into smaller bounding boxes based on xy_step_shape.\n :type splitter: PixelRangeSplitter\n :param feature: Feature to be added.\n :type feature: (FeatureType.DATA, feature_name)\n \"\"\"\n self.geogenius_image = geogenius_image\n self.splitter = splitter\n self.feature = feature\n self._splitter_check()\n self.shape = self._get_tile_rows_columns()\n self.patch_index = self._load_with_index()\n\n def _splitter_check(self):\n if self.geogenius_image.shape[1:] != self.splitter.total_pixel_shape:\n raise Exception(\"image size is not along with splitter size\")\n tile_pixel_rows, tile_pixel_columns = self.splitter.tile_pixel_shape\n y_step, x_step = self.splitter.xy_step_shape\n if tile_pixel_rows < y_step or tile_pixel_columns < x_step:\n raise Exception(\"xy_step_shape:{} not allowed greater than tile_pixel_shape: {}\"\n .format(self.splitter.xy_step_shape, self.splitter.tile_pixel_shape))\n\n def _load_with_index(self):\n \"\"\"\n Split image to a number of EOPatches(lazy load data) with given splitter,\n and index each EOPatch using two dimension list.\n\n :param feature: Feature to be loaded\n :type feature: (FeatureType, feature_name) or FeatureType\n \"\"\"\n add_data = ImportFromGeogenius(feature=self.feature, geogenius_image=self.geogenius_image)\n tile_rows, tile_columns = self._get_tile_rows_columns()\n self.patch_index = [[0] * tile_columns for i in range(tile_rows)]\n index_feature = IndexTask(patch_index=self.patch_index)\n workflow = LinearWorkflow(add_data, index_feature)\n execution_args = []\n bbox_list = np.array(self.splitter.get_pixel_bbox_list())\n for idx, bbox in enumerate(bbox_list):\n row = idx % tile_rows\n column = idx // tile_rows\n execution_args.append({\n add_data: {'pixelbox': bbox},\n index_feature: {\"row\": row, \"column\": column}\n })\n executor = EOExecutor(workflow, execution_args)\n executor.run(workers=1, multiprocess=False)\n return self.patch_index\n\n def _is_loaded(self):\n \"\"\"\n Judge whether already split and index image or not.\n \"\"\"\n return False if self.patch_index is None else True\n\n def save_to_tiff(self, file_path, feature=None, no_data_value=None, merge_method=\"last\"):\n \"\"\"\n Save indexed EOPatches to a complete tiff.\n\n :param feature: Feature which will be exported\n :type feature: (FeatureType, str)\n :param file_path: path to save tiff\n :type file_path: str\n :param no_data_value: Value of pixels of tiff image with no data in EOPatch\n :type no_data_value: int or float\n :param merge_method: How to merge overlap EOPatches. \"last\" mean latter array overwrite former array,\n \"first\" mean former array overwrite latter array.\n :type merge_method: str\n \"\"\"\n if not feature:\n feature = self.feature\n if not self._is_loaded():\n self._load_with_index(feature=feature)\n union_patch = self._patch_joint(self.patch_index, feature=feature, merge_method=merge_method)\n self._assure_folder_exist(path=file_path, path_type=\"file\")\n temp_file = tempfile.mkstemp(suffix=\".tiff\")[1]\n try:\n export_tiff = ExportToTiff(feature, no_data_value=no_data_value)\n export_tiff.execute(union_patch, filename=temp_file)\n self._cog_translate(src_path=temp_file, dst_path=file_path)\n except Exception as e:\n raise PatchSetError(e.__str__())\n finally:\n if os.path.exists(temp_file):\n os.remove(temp_file)\n\n def save_to_obstiff(self, obs_path, feature=None, no_data_value=None, merge_method=\"last\"):\n \"\"\"\n Save indexed EOPatches to a complete tiff, and upload to obs.\n\n :param feature: Feature which will be exported\n :type feature: (FeatureType, str)\n :param obs_path: obs path to save tiff\n :type obs_path: str\n :param no_data_value: Value of pixels of tiff image with no data in EOPatch\n :type no_data_value: int or float\n :param merge_method: How to merge overlap EOPatches. \"last\" mean latter array overwrite former array,\n \"first\" mean former array overwrite latter array.\n :type merge_method: str\n \"\"\"\n if not feature:\n feature = self.feature\n # temp_file = tempfile.TemporaryFile(suffix=\".tiff\").name\n temp_file = tempfile.mkstemp(suffix=\".tiff\")[1]\n try:\n self.save_to_tiff(temp_file, feature=feature, no_data_value=no_data_value,\n merge_method=merge_method)\n s3 = S3()\n return s3.upload(local_file=temp_file, obs_path=obs_path)\n finally:\n if os.path.exists(temp_file):\n os.remove(temp_file)\n\n @staticmethod\n def _cog_translate(src_path, dst_path):\n \"\"\"\n Convert tiff to cog.\n \"\"\"\n output_profile = cog_profiles.get(\"deflate\")\n output_profile.update({\"BLOCKXSIZE\": 256, \"BLOCKYSIZE\": 256})\n config = dict(\n NUM_THREADS=8,\n GDAL_TIFF_INTERNAL_MASK=os.environ.get(\"GDAL_TIFF_INTERNAL_MASK\", True),\n GDAL_TIFF_OVR_BLOCKSIZE=str(os.environ.get(\"GDAL_TIFF_OVR_BLOCKSIZE\", 128))\n )\n cog_translate(src_path, dst_path, output_profile, add_mask=True, web_optimized=False, config=config)\n\n def save_patch(self, save_folder, feature=None, overwrite_permission=OverwritePermission.OVERWRITE_PATCH,\n compress_level=0):\n \"\"\"\n Save indexed EOPatches to a folder.\n\n :param save_folder: folder to save eopatches\n :type save_folder: str\n :param feature: Feature to be exported\n :type feature: (FeatureType, feature_name) or FeatureType\n :param overwrite_permission: Permissions to overwrite exist EOPatch.\n Permissions are in the following hierarchy:\n - `ADD_ONLY` - Only new features can be added, anything that is already saved cannot be changed.\n - `OVERWRITE_FEATURES` - Overwrite only data for features which have to be saved. The remaining content of\n saved EOPatch will stay unchanged.\n - `OVERWRITE_PATCH` - Overwrite entire content of saved EOPatch and replace it with the new content.\n :type overwrite_permission: OverwritePermission\n :param compress_level: A level of data compression and can be specified with an integer from 0 (no compression)\n to 9 (highest compression).\n :type compress_level: int\n \"\"\"\n if not feature:\n feature = self.feature\n if not self._is_loaded():\n self._load_with_index(feature=feature)\n tile_rows, tile_columns = self._get_tile_rows_columns()\n self._assure_folder_exist(save_folder)\n save_task = SaveToDisk(save_folder, features=[feature, FeatureType.BBOX],\n overwrite_permission=overwrite_permission, compress_level=compress_level)\n workflow = LinearWorkflow(save_task)\n execution_args = []\n for row in range(tile_rows):\n for column in range(tile_columns):\n execution_args.append({\n save_task: {\n 'eopatch_folder': 'patch_{row}_{column}'.format(row=row, column=column),\n 'eopatch': self.patch_index[row][column]\n }\n })\n executor = EOExecutor(workflow, execution_args)\n executor.run(workers=1, multiprocess=False)\n\n @staticmethod\n def _assure_folder_exist(path, path_type=\"folder\"):\n abspath = os.path.abspath(path)\n if path_type == \"file\":\n folder_path = os.path.dirname(abspath)\n elif path_type == \"folder\":\n folder_path = abspath\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n\n def _get_tile_rows_columns(self):\n \"\"\"\n Get how number of split tiles for current image.\n \"\"\"\n y_step, x_step = self.splitter.xy_step_shape\n tile_rows = math.ceil(self.geogenius_image.shape[1] / y_step)\n tile_columns = math.ceil(self.geogenius_image.shape[2] / x_step)\n return tile_rows, tile_columns\n\n def _patch_joint(self, patch_index, feature, merge_method):\n \"\"\"\n Integrate indexed EOPatches to a complete EOPatch.\n\n :param patch_index: A object manager the index of EOPatches.\n :type patch_index: list\n :param merge_method: How to merge overlap EOPatches. \"last\" mean latter array overwrite former array,\n \"first\" mean former array overwrite latter array.\n :type merge_method: str\n \"\"\"\n feature_type, feature_name = feature\n if feature_type != FeatureType.DATA:\n raise PatchSetError(\"feature type should be FeatureType.DATA\")\n tile_rows, tile_columns = self._get_tile_rows_columns()\n union_array = self._get_union_array(feature_name)\n for row in tqdm(range(tile_rows)):\n for column in range(tile_columns):\n patch_array = patch_index[row][column].data[feature_name]\n self._merge_array(union_array, patch_array, row, column, merge_method=merge_method)\n patch = GeogeniusEOPatch()\n img_shape_array = union_array[:, :self.geogenius_image.shape[1], :self.geogenius_image.shape[2], :]\n patch.data[feature_name] = img_shape_array\n patch.bbox = self._get_img_bbox()\n return patch\n\n def _get_img_bbox(self):\n data_bounds = self.geogenius_image.bounds\n data_bbox = BBox((data_bounds[0], data_bounds[1], data_bounds[2], data_bounds[3]),\n CRS(self.geogenius_image.proj))\n return data_bbox\n\n def _get_union_array(self, feature_name):\n tile_rows, tile_columns = self._get_tile_rows_columns()\n tile_pixel_rows, tile_pixel_columns = self.splitter.tile_pixel_shape\n y_step, x_step = self.splitter.xy_step_shape\n repeat_pixel_y = tile_pixel_rows - y_step\n repeat_pixel_x = tile_pixel_columns - x_step\n patch_shape = self.patch_index[0][0].data[feature_name].shape\n len_array_y = tile_rows * tile_pixel_rows - (tile_rows - 1) * repeat_pixel_y\n len_array_x = tile_columns * tile_pixel_columns - (tile_columns - 1) * repeat_pixel_x\n union_array = np.zeros((patch_shape[0], len_array_y, len_array_x, patch_shape[3]),\n dtype=self.geogenius_image.dtype)\n return union_array\n\n def _merge_array(self, union_array, patch_array, row, column, merge_method=\"last\"):\n \"\"\"\n Merge patch_array to union_array in specific location. Union_array represent the whole tiff array,\n patch_array represent the array data for a certain EOPatch.\n\n :param union_array: A numpy array receive EOPatch array to merge.\n :type union_array: numpy\n :param patch_array: A numpy array merged in union_array.\n :type patch_array: numpy\n :param row: row tile number for y direction\n :type row: int\n :param column: column tile number for x direction\n :type column: int\n :param merge_method: How to merge overlap EOPatches. \"last\" mean latter array overwrite former array,\n \"first\" mean former array overwrite latter array.\n :type merge_method: str\n \"\"\"\n y_step, x_step = self.splitter.xy_step_shape\n tile_pixel_rows, tile_pixel_columns = self.splitter.tile_pixel_shape\n min_pixel_x = column * x_step\n min_pixel_y = row * y_step\n len_pixel_x = patch_array.shape[2]\n len_pixel_y = patch_array.shape[1]\n max_pixel_x = min_pixel_x + len_pixel_x\n max_pixel_y = min_pixel_y + len_pixel_y\n if merge_method == \"last\":\n union_array[:, min_pixel_y:max_pixel_y, min_pixel_x:max_pixel_x, :] = patch_array\n elif merge_method == \"first\":\n repeat_pixel_y = tile_pixel_rows - y_step\n repeat_pixel_x = tile_pixel_columns - x_step\n patch_start_y = 0\n patch_start_x = 0\n if row != 0 and len_pixel_y > repeat_pixel_y:\n min_pixel_y = min_pixel_y + repeat_pixel_y\n patch_start_y = repeat_pixel_y\n if column != 0 and len_pixel_x > repeat_pixel_x:\n min_pixel_x = min_pixel_x + repeat_pixel_x\n patch_start_x = repeat_pixel_x\n union_array[:, min_pixel_y:max_pixel_y, min_pixel_x:max_pixel_x, :] = \\\n patch_array[:, patch_start_y:, patch_start_x:, :]\n\n def __getitem__(self, item):\n return self.patch_index[item]\n\n def __setitem__(self, key, value):\n self.patch_index[key] = value\n\n","sub_path":"geogeniustools/eolearn/geogenius_set_old.py","file_name":"geogenius_set_old.py","file_ext":"py","file_size_in_byte":14169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"571364842","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom .views import *\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('staff/', include('staff.urls')),\n path('', main, name='main'),\n path('api/', include('api.urls')),\n path('notifications/', include('notifications.urls')),\n path('account/', include('account.urls'))\n]\n","sub_path":"AwaSRM/django_crm/django_crm/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"622644193","text":"from picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport numpy as np\nimport time\nimport cv2\n\n# Initialse variables\n# HSV colour thresholds\n\nHSV_blue = [[76, 88, 18], [113, 255, 255]]\nHSV_green = [[33, 77, 18], [74, 255, 255]]\nHSV_yellow = [[15, 77, 40], [36, 255, 255]]\n# HSV_blue = [[76, 92, 44], [113, 255, 255]]\n# HSV_green = [[33, 77, 26], [74, 255, 255]]\n# HSV_yellow = [[15, 26, 27], [40, 255, 255]]\nHSV_wall = [[0, 0, 0], [170, 28, 255]]\nHSV_orange = [[101, 41, 51], [124, 255, 255]]\nHSV_thresh = np.array([HSV_blue, HSV_green, HSV_yellow, HSV_wall, HSV_orange])\n\n# Set morphology kernel size for image filtering\nkernel = np.ones((5, 5))\n\n# Initiate counter to only show every 10th computation\nimage_cnt = 0\n\n# Define obstacle size, label, and colour\nOBS_size = [0.075, 0.151, 0.56, 0, 0.044] # size of obstacles in m\nOBS_type = [\"ROC\", \"SAT\", \"LAND\", \"WALL\", \"SAMP\"] # labels\nOBS_col = [[255, 127, 0], [0, 255, 0], [0, 255, 255], [255, 0, 255], [0, 127, 255]] # box colours\n# Set camera image frame\n#IMG_X = 640\n#IMG_Y = 480\nIMG_X = 320\nIMG_Y = 240\n# Calculate pixel focal width\nKNOWN_PIXEL_WIDTH = 92 # Pixels\nKNOWN_DIST = 0.20 # m\nKNOWN_WIDTH = 0.069 # m\nFOCAL_PIX = (KNOWN_PIXEL_WIDTH * KNOWN_DIST)/KNOWN_WIDTH\n\n# Initialise camera setup\ncamera = PiCamera()\ncamera.resolution = (IMG_X, IMG_Y)\ncamera.framerate = 8\n# Allow time for the camera to warmup\ntime.sleep(2.0)\ncamera.video_stabilization = False\ncamera.exposure_mode = 'off'\ncamera.awb_mode = 'off'\ncamera.awb_gains = 2.0\n\n#camera.awb_gains = 3\nrawCapture = PiRGBArray(camera, size=(IMG_X, IMG_Y))\n\n# Image crop to decrease image processing time\ndef crop_image(image):\n crop_img = image[int(image.shape[0]*0.25):image.shape[0]]\n return crop_img\n\n# HSV colour threshold filter\ndef mask_obs(image):\n # Convert BGR to HSV image\n HSV_bgy = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n # Convert RGB to HSV image\n HSV_o = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n masks_HSV = []\n # Apply mask for HSV range\n for indx, thresh in enumerate(HSV_thresh):\n # Blue Green and Yellow threshold and filter\n if indx < 4:\n HSV_tempmask = cv2.inRange(HSV_bgy, thresh[0], thresh[1])\n HSV_sum = np.sum(HSV_tempmask)\n if HSV_sum == 0:\n masks_HSV.append(HSV_tempmask)\n else:\n masks_HSV.append(HSV_filter(HSV_tempmask))\n # Orange threshold and filter\n else:\n HSV_tempmask = cv2.inRange(HSV_o, thresh[0], thresh[1])\n HSV_sum = np.sum(HSV_tempmask)\n if HSV_sum == 0:\n masks_HSV.append(HSV_tempmask)\n else:\n #masks_HSV.append((HSV_tempmask))\n masks_HSV.append(HSV_orange_filter(HSV_tempmask))\n return masks_HSV\n\n# Filters HSV image to remove noise\ndef HSV_filter(image):\n # Opening - Erosion followed by dilation\n mask = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)\n #mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)\n mask = cv2.erode(mask, None, iterations=5)\n # Applying dilation a second time removes noise\n mask = cv2.dilate(mask, None, iterations=5)\n return mask\n\ndef HSV_orange_filter(image):\n # Opening - Erosion followed by dilation\n mask = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)\n #mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)\n mask = cv2.erode(mask, None, iterations=1)\n # Applying dilation a second time removes noise\n mask = cv2.dilate(mask, None, iterations=3)\n return mask\n\n# Define obstacles\ndef detect_obs(hsv_masks):\n obs_array = []\n colour_count = 0\n for indx, mask in enumerate(hsv_masks):\n HSV_sum = np.sum(mask)\n if HSV_sum == 0:\n continue\n #contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n # Check for rocks and satellite crash obstacles\n if indx < 2:\n _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n for cnt in contours:\n area = cv2.contourArea(cnt)\n # print(area)\n if area > 150:\n # obstacle type index\n obs_indx = indx\n # Obstacle label\n id_type = OBS_type[indx]\n # Boundary (x,y,w,h) box of contour\n boundary = cv2.boundingRect(cnt)\n # Check for error if boundaries outside of expected\n error = 0\n if indx == 1:\n if boundary[1] >= 3:\n if ((boundary[3]/boundary[2])<0.6):\n error = 1 # Obstacle overlapping\n # Creates boundary for two obstacles with error noted\n obs_array_overlap = overlap_obs(cnt, obs_indx, id_type, boundary, error)\n # Appends two obstacles to array\n for obs in obs_array_overlap:\n obs_array.append(obs)\n # Exit loop\n continue\n elif (boundary[0] <= 3) or ((boundary[0] + boundary[2]) >= (IMG_X-3)):\n error = 1 # Obstacle on boundary\n obs_array_boundary = boundary_obs(cnt, obs_indx, id_type, boundary, error)\n obs_array.append(obs_array_boundary)\n # Exit loop\n continue\n elif ((boundary[3]/boundary[2]) > 1.4):\n error = 1 # Obstacle on boundary\n obs_array_hidden = hidden_obs(cnt, obs_indx, id_type, boundary, error)\n obs_array.append(obs_array_hidden)\n # Exit loop\n continue\n else:\n error = 0 # No obstacle overlap\n # Find centre of enclosing circle\n centre, radius = cv2.minEnclosingCircle(cnt)\n # Width of contour in pixels\n pix_width = boundary[2]\n # Angle from centre of screen in radians\n obs_ang = np.arctan(((IMG_X/2) - int(centre[0]))/FOCAL_PIX)\n # Distance from camera in cm\n obs_dist = ((OBS_size[indx] * FOCAL_PIX) / pix_width)\n # Create list of values\n #print([id_type, pix_width, obs_dist])\n obs_array.append([obs_indx, id_type, obs_ang, obs_dist, centre, boundary, error])\n # Check for lander\n elif indx == 2:\n _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cnt = np.concatenate(contours)\n #boundary_area = cv2.findNonZero(mask)\n # obstacle type index\n obs_indx = indx\n # Obstacle label\n id_type = OBS_type[indx]\n # Boundary (x,y,w,h) box of contour\n boundary = cv2.boundingRect(cnt)\n # Error if boundaries outside of norm\n if ((boundary[3]/boundary[2])>0.26):\n error = 1 # Lander partially obscured\n else:\n error = 0 # Lander completely visable\n # Find centre of enclosing circle\n centre, radius = cv2.minEnclosingCircle(cnt)\n # Width of contour in pixels\n pix_width = boundary[2]\n # Angle from centre of screen in radians\n obs_ang = np.arctan(((IMG_X/2) - int(centre[0]))/FOCAL_PIX)\n # Distance from camera in cm\n obs_dist = ((OBS_size[indx] * FOCAL_PIX) / pix_width)\n # Create list of values\n obs_array.append([obs_indx, id_type, obs_ang, obs_dist, centre, boundary, error])\n # Check for Wall\n elif indx == 3:\n _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cnt = np.concatenate(contours)\n #boundary_area = cv2.findNonZero(mask)\n # obstacle type index\n obs_indx = indx\n # Obstacle label\n id_type = OBS_type[indx]\n # Boundary (x,y,w,h) box of contour\n boundary = cv2.boundingRect(cnt)\n # Error if boundaries outside of norm\n error = 0 # \n centre, radius = cv2.minEnclosingCircle(cnt)\n # Width of contour in pixels\n pix_width = boundary[2]\n # Angle from centre of screen in radians\n obs_ang = np.arctan(((IMG_X/2) - int(centre[0]))/FOCAL_PIX)\n # Distance from camera in cm\n obs_dist = boundary[1]-boundary[3]\n if obs_dist > 15:\n error = 2\n # Create list of values\n obs_array.append([obs_indx, id_type, obs_ang, obs_dist, centre, boundary, error])\n # Check for samples\n else:\n _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if area > 40:\n # obstacle type index\n obs_indx = indx\n # Obstacle label\n id_type = OBS_type[indx]\n #print([area, id_type])\n # Boundary (x,y,w,h) box of contour\n boundary = cv2.boundingRect(cnt)\n # Error if boundaries outside of norm\n error = 0\n # Find centre of enclosing circle\n centre, radius = cv2.minEnclosingCircle(cnt)\n # Width of contour in pixels\n pix_width = boundary[2]\n # Angle from centre of screen in radians\n obs_ang = np.arctan(((IMG_X/2) - int(centre[0]))/FOCAL_PIX)\n # Distance from camera in cm\n obs_dist = ((OBS_size[indx] * FOCAL_PIX) / pix_width)\n # Create list of values\n obs_array.append([obs_indx, id_type, obs_ang, obs_dist, centre, boundary, error])\n #print(obs_array)\n return obs_array\n\ndef overlap_obs(cnt, obs_indx, id_type, boundary, error):\n # Define arrays\n obs_boundary = []\n obs_array_overlap = []\n # Obstacle type index\n obs_indx = obs_indx\n # Obstacle label\n id_type = id_type\n # Error = 1 - Values not to be trusted\n error = error\n # Create two boundary obstacles based on largest obstacle size\n obs_01 = (boundary[0],boundary[1],boundary[3],boundary[3])\n obs_02 = ((boundary[0]+boundary[2]-boundary[3]),boundary[1],boundary[3],boundary[3])\n # Create array for obstacles\n obs_boundary.append(obs_01)\n obs_boundary.append(obs_02)\n # Create two obstacle list\n for obs in obs_boundary:\n # Centre point for obstacles\n centre = (int(obs[0]+(obs[2]/2)), int(obs[1]+(obs[3]/2)))\n # Width of contour in pixels\n pix_width = obs[2]\n # Angle from centre of screen in radians\n obs_ang = np.arctan(((IMG_X/2) - int(centre[0]))/FOCAL_PIX)\n # Distance from camera in cm\n obs_dist = ((OBS_size[obs_indx] * FOCAL_PIX) / pix_width)\n # Create list of values\n obs_array_overlap.append([obs_indx, id_type, obs_ang, obs_dist, centre, obs, error])\n return obs_array_overlap\n\ndef boundary_obs(cnt, obs_indx, id_type, boundary, error):\n # Obstacle type index\n obs_indx = obs_indx\n # Obstacle label\n id_type = id_type\n # Error = 1 - Values not to be trusted\n error = error\n # Boundary points\n boundary = boundary\n if (boundary[0] <= 3):\n # Centre point for obstacle based on height\n centre = (int((boundary[0] + boundary[2]) - boundary[3]), int(boundary[1]+(boundary[3]/2)))\n # Width of contour in pixels\n pix_width = boundary[3]\n # Angle from centre of screen in radians\n obs_ang = np.arctan(((IMG_X/2) - int(centre[0]))/FOCAL_PIX)\n # Distance from camera in cm\n obs_dist = ((OBS_size[obs_indx] * FOCAL_PIX) / pix_width)\n # Create list of values\n obs_array_boundary = ([obs_indx, id_type, obs_ang, obs_dist, centre, boundary, error])\n return obs_array_boundary\n else:\n # Centre point for obstacle based on height\n centre = (int(boundary[0] + boundary[3]), int(boundary[1] + (boundary[3]/2)))\n # Width of contour in pixels\n pix_width = boundary[3]\n # Angle from centre of screen in radians\n obs_ang = np.arctan(((IMG_X/2) - int(centre[0]))/FOCAL_PIX)\n # Distance from camera in cm\n obs_dist = ((OBS_size[obs_indx] * FOCAL_PIX) / pix_width)\n # Create list of values\n obs_array_boundary = ([obs_indx, id_type, obs_ang, obs_dist, centre, boundary, error])\n return obs_array_boundary\n\ndef hidden_obs(cnt, obs_indx, id_type, boundary, error):\n # Obstacle type index\n obs_indx = obs_indx\n # Obstacle label\n id_type = id_type\n # Error = 1 - Values not to be trusted\n error = error\n # Boundary points\n boundary = boundary\n # Centre point for obstacle based on height\n centre, radius = cv2.minEnclosingCircle(cnt)\n # Width of contour in pixels\n pix_width = boundary[3]\n # Angle from centre of screen in radians\n obs_ang = np.arctan(((IMG_X/2) - int(centre[0]))/FOCAL_PIX)\n # Distance from camera in cm\n obs_dist = ((OBS_size[obs_indx] * FOCAL_PIX) / pix_width)\n # Create list of values\n obs_array_boundary = ([obs_indx, id_type, obs_ang, obs_dist, centre, boundary, error])\n return obs_array_boundary \n\ndef disp_image(image, obstacle_array):\n obs_image = image\n new_obs = obstacle_array\n for i, obs in enumerate(new_obs):\n # Draw rectangle\n cv2.rectangle(obs_image, (int(new_obs[i][5][0]), int(new_obs[i][5][1])),\\\n (int(new_obs[i][5][0] + new_obs[i][5][2]), int(new_obs[i][5][1] +\\\n new_obs[i][5][3])), OBS_col[new_obs[i][0]], 1)\n # Draw shape type\n #cv2.putText(obs_image, new_obs[i][1], (int(new_obs[i][5][0]),\\\n #int(new_obs[i][5][1] + new_obs[i][5][3]) + 13), cv2.FONT_HERSHEY_SIMPLEX, 0.3, OBS_col[new_obs[i][0]],1)\n # Draw distance in m\n cv2.putText(obs_image, \"Dist:{:.1f}\".format(new_obs[i][3]), (int(new_obs[i][5][0]),\\\n int(new_obs[i][5][1] + new_obs[i][5][3]) + 13), cv2.FONT_HERSHEY_SIMPLEX, 0.3, OBS_col[new_obs[i][0]],1)\n # Draw angle in degrees to obstacle from camera\n cv2.putText(obs_image, \"Deg:{:.1f}\".format(np.degrees(new_obs[i][2])), (int(new_obs[i][5][0]),\\\n int(new_obs[i][5][1] + new_obs[i][5][3]) + 26), cv2.FONT_HERSHEY_SIMPLEX, 0.3, OBS_col[new_obs[i][0]],1)\n # Draw area of obstacle from camera\n #cv2.putText(obs_image, \"Area:{:.1f}\".format(new_obs[i][6]), (int(new_obs[i][5][0]),\\\n #int(new_obs[i][5][1] + new_obs[i][5][3]) + 39), cv2.FONT_HERSHEY_SIMPLEX, 0.3, OBS_col[new_obs[i][0]],1)\n return obs_image\n\ndef current_observation():\n # Grab frame\n camera.capture(rawCapture, format=\"bgr\", use_video_port=True)\n image = rawCapture.array\n rawCapture.truncate(0)\n # Crop image\n image = crop_image(image)\n # Apply HSV threshold to frame\n hsv_masks = mask_obs(image)\n\n # Determine distance, angle ID and type\n obstacle_array = detect_obs(hsv_masks)\n\n # Draw from and boundary\n return_im = disp_image(image, obstacle_array)\n\n return obstacle_array, return_im\n\n","sub_path":"Rover/cv_vision.py","file_name":"cv_vision.py","file_ext":"py","file_size_in_byte":15697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"603601878","text":"import urllib.parse\nimport requests\nimport datetime\nimport os\nfrom pymongo import MongoClient\nfrom dotenv import load_dotenv\nfrom pathlib import Path\n\n# Pulling in environment variable for database connection\nload_dotenv()\nenv_path = Path('.') / '.env'\nload_dotenv(dotenv_path=env_path)\nURI = os.getenv('ATLAS_URI')\n\n# Connecting to mongoDB\nclient = MongoClient(URI)\ndb = client.get_database('GoalieWatch')\ncollection = db.goalies\n\n# Pulling data from NHL teams\nteam_api = 'https://statsapi.web.nhl.com/api/v1/teams/'\nteam_url = team_api + urllib.parse.urlencode({})\nteam_data = requests.get(team_url).json()\ninsert_count = 0\nupdated_count = 0\n\n# Looping through all the teams\nfor i in range(len(team_data['teams'])):\n team_id = team_data['teams'][i]['id']\n team_name = team_data['teams'][i]['name']\n #print(team_name)\n\n # Pulling data from teams roster\n position_api = 'https://statsapi.web.nhl.com/api/v1/teams/'+ str(team_id) +'/roster'\n position_url = position_api + urllib.parse.urlencode({})\n position_data = requests.get(position_url).json()\n\n # Looping through all the players in each team, retrieving data\n for j in range(len(position_data['roster'])):\n position = position_data['roster'][j]['position']['name']\n player_name = position_data['roster'][j]['person']['fullName']\n player_id = position_data['roster'][j]['person']['id']\n player_link = position_data['roster'][j]['person']['link']\n jersey_number = position_data['roster'][j]['jerseyNumber']\n\n # Building json object to store into database\n if position == 'Goalie': \n goalie = {\n \"team_id\": team_data['teams'][i]['id'],\n \"team_name\": team_data['teams'][i]['name'],\n \"goalie_name\": position_data['roster'][j]['person']['fullName'],\n \"goalie_id\": position_data['roster'][j]['person']['id'],\n \"jersey_number\": position_data['roster'][j]['jerseyNumber'],\n \"player_link\": position_data['roster'][j]['person']['link'],\n \"date_updated\": datetime.datetime.utcnow()\n }\n\n # Comparing each record to existing documents in Mongo\n pulled_record = collection.find_one({\"goalie_id\": player_id})\n \n # If goalie doesn't exist, insert new document\n if pulled_record == None:\n collection.insert_one(goalie)\n insert_count += 1\n\n # If goalie exists in database, replace with new data\n elif pulled_record['goalie_id'] == player_id:\n collection.find_one_and_replace(pulled_record, goalie)\n updated_count += 1\n\n# Outputting counts from updates\nprint('New goalies inserted: ' + str(insert_count))\nprint('Goalies records updated: ' + str(updated_count))","sub_path":"backend/web-scrape/goalieCron.py","file_name":"goalieCron.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"594444865","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport csv\nimport sys\nimport re\nimport json\nfrom numpy import percentile\n\n\ndef getPassed(values):\n return len(list(filter(lambda x: x > 0, values)))\n\n\ndef getMean(values):\n return sum(values) / len(values)\n\n\ndef getMedian(values, quantile):\n middle = len(values) * quantile\n if len(values) % round((1 / quantile)) == 0:\n middle = round(middle)\n return (values[middle - 1] + values[middle]) / 2\n else:\n return (values[round(middle - 0.5)])\n\n\ndef processData(columnNames, values, pat):\n processedValues = {}\n\n studs = {}\n\n for columnNumber in range(1, len(columnNames)):\n col = columnNames[columnNumber]\n\n match = re.match(pat, col)\n date = match.group(1)\n\n if date in processedValues:\n for i in range(len(values)):\n row = values[i]\n processedValues[date][i] += float(row[columnNumber])\n studs[date][i] += float(row[columnNumber])\n else:\n studentRow = []\n processedValues[date] = []\n for row in values:\n processedValues[date].append(float(row[columnNumber]))\n studentRow.append(float(row[columnNumber]))\n studs[date] = studentRow\n printResult(processedValues, studs)\n\n\n\ndef printResult(processedValues, studentDict):\n for val in processedValues.values():\n val.sort()\n\n result = {}\n # df = pandas.DataFrame(data=processedValues) # useless crap\n\n for key, value in processedValues.items():\n quartiles = percentile(value, [25, 50, 75])\n\n\n result[key] = {\n \"mean\": getMean(value),\n \"median\": quartiles[1],\n \"first\": quartiles[0],\n \"last\": quartiles[2],\n \"passed\": getPassed(studentDict[key])\n\n }\n print(json.dumps(result, indent=2, ensure_ascii=False))\n\n\ndef main():\n mode = sys.argv[2]\n\n columnNames = []\n values = []\n\n with open(sys.argv[1], newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n columnNames = spamreader.__next__()\n for row in spamreader:\n values.append(row)\n\n if (mode == \"dates\"):\n processData(columnNames, values, re.compile(r'(\\d\\d\\d\\d-\\d\\d-\\d\\d)/\\d\\d'))\n elif (mode == \"exercises\"):\n processData(columnNames, values, re.compile(r'\\d\\d\\d\\d-\\d\\d-\\d\\d/(\\d\\d)'))\n elif (mode == \"deadlines\"):\n processData(columnNames, values, re.compile(r'(\\d\\d\\d\\d-\\d\\d-\\d\\d/\\d\\d)'))\n else:\n print(\"Wrong mode, allows only 'dates', 'deadlines', 'exercises'\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"08-VraciameSaKRealistickymZadaniam/stat.py","file_name":"stat.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"336442256","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.http import Http404\nfrom django.views.generic import DetailView, ListView\n\nfrom apps.places.models import Place\n\n\nclass PlaceListView(ListView):\n model = Place\n template_name = 'index.html'\n context_object_name = 'places'\n\n def get_queryset(self):\n return super(PlaceListView, self).get_queryset().filter(active=True)\n\n\nclass PlaceDetailView(DetailView):\n model = Place\n template_name = 'place-detail.html'\n context_object_name = 'place'\n\n def get_object(self, queryset=None):\n obj = super(PlaceDetailView, self).get_object(queryset)\n if not obj.active:\n raise Http404\n return obj\n\n\n\n\n\n\n","sub_path":"apps/places/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"486215590","text":"import matplotlib\n\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.image as mplotimg\nimport cv2\n\nrho = 1\ntheta = np.pi / 180\n#Threshold is minimum number of Hough space intersections it takes to find a line\nthreshold = 60\nmin_line_length = 100\nmax_line_gap = 5\n\nphone = cv2.imread('/Users/jakub.knitter/OneDrive/PrivateRepo/Sandbox/Python/ComputerVision/images/phone.jpg')\nphone = cv2.cvtColor(phone, cv2.COLOR_BGR2RGB)\nphone = cv2.cvtColor(phone, cv2.COLOR_RGB2GRAY)\n\n# wide = cv2.Canny(phone, 50, 100)\ntight = cv2.Canny(phone, 200, 240)\n\nphone_line_image = np.copy(tight)\n\n#The function returns an array of four points x1,y1,x2,y2 - minimum amount of coordinates to create a line\nhough_lines = cv2.HoughLinesP(tight, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)\n\n#First for loop iterates through all the results - that means separate tables of four points\nfor something in hough_lines:\n #Second loop iterates through particular table\n for x1, y1, x2, y2 in something:\n #And finally draw the lines between set of coordinates\n #Last parameter of the function is thickness or the size of a line\n cv2.line(phone_line_image, (x1, y1), (x2, y2), (255, 0, 0), 5)\n\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))\n\nax1.imshow(hough_lines, cmap='gray')\nax2.imshow(phone_line_image)\n\nplt.show()\n","sub_path":"venv/Notebook3_HoughLines.py","file_name":"Notebook3_HoughLines.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"471924882","text":"#!/usr/bin/env python3\n\nimport sys\n\nif sys.version_info[:2] < (3, 7):\n raise Exception(\"Must be using Python 3.7+\")\n\nimport wx\nfrom amulet_map_editor import log\nfrom amulet_map_editor.api.framework import AmuletUI\nimport traceback\n\nif __name__ == \"__main__\":\n try:\n app = wx.App()\n frame = AmuletUI(None)\n app.MainLoop()\n except Exception as e:\n log.critical(\n f\"Amulet Crashed. Sorry about that. Please report it to a developer if you think this is an issue. \\n{traceback.format_exc()}\"\n )\n input(\"Press ENTER to continue.\")\n","sub_path":"amulet_map_editor/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"544259393","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom mlxtend.frequent_patterns import apriori\nfrom mlxtend.frequent_patterns import association_rules\nimport d3fdgraph\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n#helper function\ndef encode_units(x):\n if x <= 0:\n return 0\n if x >= 1:\n return 1 \n \nclass MarketBasketAnalysis(object):\n\n \"\"\"\n Class for fitting Apriori algorithm for Market Basket Analysis\n\n Attributes\n ----------\n rules_ : DataFrame\n The rules found by Apriori and their associated metrics\n\n freq_items_ : DataFrame\n The frequent itemsets found by Apriori and their support\n \"\"\"\n\n\n def fit(\n self, \n dataframe, \n min_support = None,# 0.01\n metric = None,#\"lift\"\n min_threshold = None #1\n ):\n \"\"\"\n Fit the model to a dataset \n\n Parameters\n ----------\n dataframe: a pd.DataFrame \n contains columns 'order_id', 'product_id' and 'quantity'\n min_support: float, optional\n between 0 and 1, mininum threshold for itemset support\n metric: string, optional\n supported evaluation metrics are 'support', 'confidence', 'leverage' and 'conviction'\n min_threshold: float, optional\n minimum threshold for evaluation metric\n\n Returns\n ----------\n self: MarketBasketAnalysis\n self with new properties like ``rules_``, ``plot_frequency`` and ``plot_network_graph`` \n \"\"\"\n basket = (dataframe.groupby(['order_id','product_id'])['quantity'].sum().unstack().reset_index().fillna(0).set_index('order_id'))\n\n basket_sets = basket.applymap(encode_units)\n\n if min_support is not None:\n frequent_itemsets = apriori(basket_sets, min_support=min_support, use_colnames=True)\n else:\n frequent_itemsets = apriori(basket_sets, min_support=0.01, use_colnames=True)\n\n if metric is None:\n metric = 'lift'\n\n if min_threshold is None:\n min_threshold=1\n \n rules = association_rules(frequent_itemsets, metric=metric, min_threshold=min_threshold)\n\n frequent_itemsets['itemsets'] = frequent_itemsets['itemsets'].apply(lambda x: list(x)[0]).astype(\"unicode\")\n rules['antecedents'] = rules['antecedents'].apply(lambda x: list(x)[0]).astype(\"unicode\")\n rules['consequents'] = rules['consequents'].apply(lambda y: list(y)[0]).astype(\"unicode\")\n\n self.rules_ = rules\n self.freq_items_ = frequent_itemsets\n\n return self\n \n def plot_frequency(self, num_items = 15):\n \"\"\"\n Plots frequent itemsets according to support as barplot\n\n Parameters\n ----------\n self: MarketBasketAnalysis object \n num_items: int, optional\n number of top itemsets plotted\n \"\"\"\n top_items = self.freq_items_.sort_values('support', ascending = False).reset_index(drop=True).head(num_items)\n\n dims = (10,5)\n fig, ax = plt.subplots(figsize=dims)\n plot = sns.barplot(x='itemsets', y='support', data=top_items)\n plot.set_title('Relative Item Frequency Plot')\n plot.set_xlabel('Itemsets')\n plot.set_ylabel('Item Frequency (Relative)')\n plot.set_xticklabels(plot.get_xticklabels(), rotation=75)\n plt.show()\n\n return None\n \n def plot_network_graph(self, metric = 'lift', collision_scale = 10):\n \"\"\"\n Plots rules in a network graph \n\n Parameters\n ----------\n self: MarketBasketAnalysis object \n metric: string, optional\n supported evaluation metrics are 'support', 'confidence', 'leverage' and 'conviction'\n \"\"\"\n\n df = self.rules_[['antecedents','consequents', metric]]\n d3fdgraph.plot_force_directed_graph(df, collision_scale = collision_scale)\n\n return None","sub_path":"bizkit/market_basket_analysis.py","file_name":"market_basket_analysis.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"600441381","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.test import TestCase\nfrom django.test.client import RequestFactory\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpRequest\n\nfrom ..models import Person\nfrom ..views import home_page\n\n\nclass HomePageViewTest(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n self.person = Person.objects.first()\n\n def test_home_page_view(self):\n \"\"\"Test view home_page\"\"\"\n request = self.factory.get(reverse('hello:home'))\n response = home_page(request)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'home.html')\n self.assertIn(self.person.name, response.content)\n\n\nclass HomePageTest(TestCase):\n def test_home_page(self):\n \"\"\"Test home page\"\"\"\n\n response = self.client.get(reverse('hello:home'))\n\n self.assertTemplateUsed(response, 'home.html')\n self.assertContains(response,\n '

42 Coffee Cups Test Assignmen

',\n html=True)\n self.assertContains(response, 'Aleks')\n self.assertContains(response, 'Woronow')\n self.assertContains(response, 'Aug. 12, 2015')\n self.assertContains(response, 'aleks.woronow@yandex.ru')\n self.assertContains(response, '42cc@khavr.com')\n self.assertContains(response, 'I was born ...')\n\n def test_home_page_returns_correct_html(self):\n \"\"\"Test home page returns correct html\"\"\"\n request = HttpRequest()\n response = home_page(request)\n self.assertTrue(response.content.strip().\n startswith(b''))\n self.assertIn(b'Visiting Card', response.content)\n self.assertTrue(response.content.strip().endswith(b''))\n\n\nclass RequestAjaxTest(TestCase):\n def test_request_ajax_view(self):\n\n \"\"\"Test request ajax view\"\"\"\n response = self.client.get(reverse('hello:home'))\n response = self.client.get(reverse('hello:request_ajax'),\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertIn('method', response.content)\n self.assertIn('GET', response.content)\n self.assertIn('path', response.content)\n self.assertIn('/', response.content)\n\n\nclass RequestViewTest(TestCase):\n def test_request_view(self):\n \"\"\"Test request_view view\"\"\"\n\n response = self.client.get(reverse('hello:request'))\n\n self.assertTemplateUsed(response, 'request.html')\n self.assertEqual(response.status_code, 200)\n self.assertContains(response,\n '

42 Coffee Cups Test Assignmen

',\n html=True)\n\n\nclass FormPageTest(TestCase):\n def test_form_page_view(self):\n \"\"\"Test view form_page\"\"\"\n response = self.client.get(reverse('hello:form'))\n self.assertEqual(response.status_code, 302)\n\n self.client.login(username='admin', password='admin')\n response = self.client.get(reverse('hello:form'))\n self.assertIn('name', response.content)\n","sub_path":"apps/hello/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"157185627","text":"import time\nimport urllib\nimport datetime\nfrom json import dump\nfrom random import randint\n\nfrom sqlalchemy import create_engine\n\nfrom cryptocollector.persistance.persistor import Persistor\nfrom cryptocollector.utils.utils import setup_logger\n\nlogger = setup_logger(name=__name__)\n\nclass SqlServer(Persistor):\n \"\"\"\n\n A class to persist messages to SQL Server database.\n\n \"\"\"\n\n def __init__(self, \n driver, \n server, \n database, \n user,\n password, \n table,\n data_dir):\n \"\"\"\n\n Parameters\n ----------\n database : str\n Name of SQL Server database.\n driver : str\n Microsoft driver.\n user : str\n SQL Server user with data writer permissions.\n password : str\n SQL Server user password.\n server : str\n _name of SQL Server server.\n data_dir : str\n Path to use if write to database fails. \n\n Notes\n ------\n Inputs must make a valid connection string.\n\n \"\"\"\n\n super().__init__()\n\n self.driver = driver\n self.server = server\n self.database = database\n self.user = user\n self.password = password\n self.table = table\n self.data_dir = data_dir\n self.engine = self.__make_engine()\n\n def __del__(self):\n \n if self.engine is not None:\n logger.warn('Disposing of connection pool.')\n try:\n self.engine.dispose()\n except KeyError as e:\n logger.warn(e)\n\n def __make_engine(self):\n \"\"\"\n \n Create SQL Server engine.\n\n \"\"\"\n\n conn_string = self.__create_conn_string()\n\n # logger.info(f'connection string: {conn_string}.') \n logger.info(f'Will write to database: {self.database}.')\n logger.info(f'Will write to table: {self.table}.')\n\n engine = create_engine(conn_string)\n\n return engine\n\n def __create_conn_string(self):\n \"\"\"\n\n Create connection string to sql server.\n\n \"\"\"\n\n conn_params = 'DRIVER={' + self.driver +'};'\n conn_params += 'SERVER=' + self.server + ';'\n conn_params += 'DATABASE=' + self.database + ';'\n conn_params += 'UID=' + self.user + ';'\n conn_params += 'PWD=' + self.password \n\n conn_params = urllib.parse.quote_plus(conn_params)\n conn_string = f'mssql+pyodbc:///?odbc_connect={conn_params}'\n\n return conn_string \n\n def write(self, msg):\n \"\"\"\n\n Persist message from websocket.\n\n Parameters\n ----------\n msg : dict\n Message from exchange.\n table : str\n name of table in database.\n\n Notes\n -----\n 1. Try to write to sql database.\n 2. In case of error write to json on disk.\n\n \"\"\"\n\n try:\n self._write_msg_to_db(msg=msg)\n except Exception as e:\n logger.critical(e)\n try:\n self._write_msg_to_json(msg=msg)\n except Exception as e:\n logger.critical(e)\n\n def _write_msg_to_db(self, msg):\n \"\"\"\n\n Write message from websocket to database.\n\n Parameters\n ----------\n msg : dict\n Message from exchange.\n table : str\n name of table in database. \n\n Notes\n -----\n The messages from the websocket a received as \n dictionaries and are converted into a \n `INSERT INTO (cols) VALUES (values)`\n transact sql query.\n\n \"\"\"\n\n msg['timestamp_script'] = str(datetime.datetime.now())\n\n columns = list()\n values = list()\n\n for k,v in msg.items():\n columns.append(str(k))\n values.append(\"'\" + str(v) + \"'\")\n\n columns = ', '.join(columns) \n values = ', '.join(values)\n query = f\"\"\" INSERT INTO {self.table} ({columns}) VALUES ({values}) \"\"\"\n\n self.engine.execute(query)\n\n def _write_msg_to_json(self, msg):\n \"\"\"\n\n Write message from websocket to json.\n\n Parameters\n ----------\n msg : dict\n Message from exchange.\n \n \"\"\"\n\n path = self.__make_path_file()\n\n with open(path, 'w') as f:\n dump(msg, f)\n\n def __make_path_file(self):\n \"\"\"\n\n Create path to file.\n\n Notes\n -----\n The file name is constructed in 3 steps:\n 1. The name of the table.\n 2. A unix timestamp with milisecond precision.\n 3. A random integer to minimize collisions.\n\n \"\"\"\n\n table = self.table.replace('.', '')\n\n path = f'{self.data_dir}/{table}_'\n path += f'{str(int(time.time() * 1000))}_'\n path += f'{str(randint(1, 10 ** 6))}.txt'\n\n return path \n","sub_path":"cryptocollector/persistance/sqlserver.py","file_name":"sqlserver.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"42436479","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport threading\nimport math\n\nfrom channel import Channel\nfrom environment import Environment\nfrom replica_fish import ReplicaFish\nfrom DelightFish import Fish\nfrom observer import Observer\nfrom utils import generate_distortion, generate_fish, generate_replica_fish, generate_all_fish, run_simulation\nfrom interaction import Interaction\nfrom environment import Environment\ndef test_simulation(\n fish,\n observer,\n run_time=5,\n):\n \"\"\"Run a simulation and format data from it for use by classifiers\n\n\n Arguments:\n fish {list} -- List of fish instances\n observer {Observer} -- Observer instance\n\n Keyword Arguments:\n run_time {number} -- Total run time in seconds (default: {5})\n\n \"\"\"\n def stop():\n for f in fish:\n f.stop()\n observer.stop()\n\n\n # Start the fish\n fish_threads = []\n for f in fish:\n threading.Thread(target=f.start).start()\n\n\n observer_thread = threading.Thread(target=observer.start)\n observer_thread.start()\n\n # Wait for the simulation to end, so data can be collected\n # from the observer\n fish_matrixes = []\n threading.Timer(run_time, stop).start()\n observer_thread.join()\n\n # merge each fish's linear speed, angular speed, and neighbor\n # distances into a single matrix. This will\n # utlimately be a N x (N + 1) matrix, where N is the number\n # of fish.\n for fish_index in range(observer.num_nodes):\n single_fish = np.column_stack((observer.lin_speed[fish_index],\n observer.ang_speed[fish_index],\n observer.neighbor_distances[fish_index]))\n fish_matrixes.append(single_fish)\n return np.stack(fish_matrixes, axis = 0)\n\n\n\ndef run_full_test(weights,\n conn_threshold,\n run_time,\n total_fish,\n k_ar,\n max_speed,\n arena_size,\n real = False):\n \"\"\"\n Start and run a simulation and collect data for Turing Learning. This function\n initializes other objects needed for simulation, rather than just\n starting and stopping everything\n\n Arguments:\n weights {float|list} --- weights used by Neural Network in imposter fish\n conn_threshold {float} -- Distance at which fish can no longer detect other fish\n run_time {int} -- Length of time to run simulation\n total_fish {int} -- Number of fish to be in the school\n k_ar {float} -- parameter for delight fish\n max_speed {float} -- Max speed of a single fish\n arena_size {int} -- boundaries of arena to create distortion\n real {bool} -- Should this test have real or imposter fish (default : {False})\n \"\"\"\n arena_center = arena_size / 2.0\n initial_spread = 20\n fish_pos = initial_spread * np.random.rand(total_fish, 2) + arena_center - initial_spread / 2.0\n clock_freqs = 1\n verbose = False\n\n distortion = generate_distortion(type='none', n=arena_size)\n environment = Environment(\n node_pos=fish_pos,\n distortion=distortion,\n prob_type='binary',\n noise_magnitude=0,\n conn_thres=conn_threshold,\n verbose=verbose\n )\n interaction = Interaction(environment, verbose=verbose)\n channel = Channel(environment)\n\n # Have all real or all fake\n if real:\n n_fish = total_fish\n n_replica_fish = 0\n else:\n n_fish = 0\n n_replica_fish = total_fish\n\n fish = generate_all_fish(\n n_fish=n_fish,\n n_replica_fish= n_replica_fish,\n channel=channel,\n interaction=interaction,\n k_coh = 0,\n k_ar = k_ar,\n alpha = 40,\n weights = weights,\n lim_neighbors=[0, math.inf],\n neighbor_weights=1.0,\n fish_max_speeds=max_speed,\n clock_freqs=clock_freqs,\n verbose=verbose\n )\n channel.set_nodes(fish)\n\n observer = Observer(fish=fish, environment=environment, channel=channel)\n fish_matrix = test_simulation(fish=fish, observer=observer, run_time=run_time)\n return fish_matrix\n\n\n","sub_path":"TuringFish/turing_learning.py","file_name":"turing_learning.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"225517267","text":"# coding=utf-8\n# Copyright 2019 The Google UDA Team Authors.\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\"\"\"Augmentation policies found by AutoAugment.\"\"\"\n\n\ndef get_trans_list():\n trans_list = [\n 'Invert', 'Sharpness', 'AutoContrast', 'Posterize',\n 'TranslateX', 'TranslateY', 'Equalize', 'Contrast', \n 'Color', 'Solarize', 'Brightness']\n return trans_list\n\n\ndef randaug_policies():\n trans_list = get_trans_list()\n op_list = []\n for trans in trans_list:\n for magnitude in range(1, 10):\n op_list += [(trans, 0.5, magnitude)]\n policies = []\n for op_1 in op_list:\n for op_2 in op_list:\n policies += [[op_1, op_2]]\n return policies\n\n","sub_path":"randaugment/policies.py","file_name":"policies.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"608944928","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import print_function, division\nfrom numpy.testing import assert_allclose\nfrom ..effective_area import abramowski_effective_area\n\n\ndef test_abramowski_effective_area():\n energy = 0.1\n area = abramowski_effective_area(energy, 'HESS')\n assert_allclose(area, 16546957.901469307)\n \n\ndef plot_abramowski_effective_area():\n import numpy as np\n import matplotlib.pyplot as plt\n # Plot the effective area curves of the three experiments\n elim = [10 ** -3, 10 ** 3]\n # Build a vector of energies (TeV) with equal log spacing\n loge = np.linspace(0, np.log10(elim[1]), 100)\n energy = 10 ** loge\n\n for instrument in ['HESS', 'HESS2', 'CTA']:\n a_eff_hess = abramowski_effective_area(energy, instrument)\n plt.plot(energy, a_eff_hess, label=instrument)\n\n plt.loglog()\n plt.xlabel('Energy (TeV)')\n plt.ylabel('Effective Area (cm^2)')\n plt.xlim(elim)\n plt.ylim([1e3, 1e12])\n plt.legend()\n plt.show()\n","sub_path":"gammapy/irf/tests/test_effective_area.py","file_name":"test_effective_area.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"584097709","text":"import pygame\r\n\r\nimport jugador\r\n\r\nimport pytmx\r\ntmxdata = pytmx.TiledMap(\"maps/map1.tmx\")\r\n#--\r\nfrom pytmx import load_pygame\r\ntmxdata = load_pygame(\"maps/map1.tmx\")\r\n#--\r\nimage = tmx_data.get_tile_image(x, y, layer)\r\nscreen.blit(image, position)\r\n\r\n\r\n\r\npygame.init()\r\n\r\nwidht = 640\r\nheight = 640\r\n\r\npantalla = pygame.display.set_mode((widht, height))\r\npygame.display.set_caption(\"Maps\")\r\nreloj = pygame.time.Clock()\r\ngame_over = False\r\njugador = jugador.xena((widht / 2, height / 2))\r\n\r\nimagen = pygame.image.load(\"img/map1.png\")\r\n\r\nwhile game_over == False:\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n game_over = True\r\n\r\n jugador.evento(event)\r\n pantalla.blit(imagen, (0, 0))\r\n pantalla.blit(jugador.imagen, jugador.rect)\r\n\r\n pygame.display.flip()\r\n reloj.tick(15)\r\npygame.quit()\r\n","sub_path":"2019/final/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377420201","text":"import numpy as np\nimport cv2\nimport src.lane_measurements\n\n\nym_per_pix = 30/720 # meters per pixel in y dimension\nxm_per_pix = 3.7/700 # meters per pixel in x dimension\n\ndef lane_measurements_overlay(left_fit,right_fit,img_size):\n overlay = np.zeros((img_size)).astype(np.uint8)\n overlay = np.dstack((overlay, overlay, overlay))\n \n curvature = lane_measurements.curvature(left_fit,right_fit)\n \n font = cv2.FONT_HERSHEY_SIMPLEX\n \n cv2.putText(overlay, \"lane curvature radius:\", (30, 60), font, 1, (255,255,255), 2,cv2.LINE_AA)\n cv2.putText(overlay, \"{0:.2f}m\".format(curvature), (30, 100), font, 1, (255,255,255), 2,cv2.LINE_AA)\n\n\n from_center = lane_measurements.center_offset(left_fit,right_fit,img_size)\n \n cv2.putText(overlay, \"center offset:\", (30, 200), font, 1, (255,255,255), 2,cv2.LINE_AA)\n center_offset_string = \"{0:.2f}m left of center\".format(from_center)\n cv2.putText(overlay, center_offset_string ,(30,240), font, 1, (255,255,255),2,cv2.LINE_AA)\n\n return overlay\n\ndef lane_overlay(left_fit,right_fit,img_size,c1=[100,0,0],c2=[0,100,0],c3=[0,0,100]):\n ploty = np.linspace(0, img_size[0]-1, img_size[0])\n left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n\n # Create an image to draw the lines on\n overlay = np.zeros((img_size)).astype(np.uint8)\n overlay = np.dstack((overlay, overlay, overlay))\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n r_line_pts = pts_right.reshape((-1,1,2))\n l_line_pts = pts_left.reshape((-1,1,2))\n # Draw the lane onto the warped blank image\n cv2.fillPoly(overlay, np.int_([pts]), (0,100, 0))\n cv2.polylines(overlay,np.int_([r_line_pts]),False,(255,0,0), 25)\n cv2.polylines(overlay,np.int_([l_line_pts]),False,(255,0,0), 25)\n return overlay\n","sub_path":"src/overlay.py","file_name":"overlay.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"469703457","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nimport skopt\n\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nmax_epochs = 2000\nstart_checking_early_stopping_epoch = 30\n\nnum_random_hyperparams = 10 #The number of random hyperparameters to evaluate at the beginning\nnum_chosen_hyperparams = 10 #The number of hyperparameters to try during the tuning phase\n\n#Validation set was split into two: one for hyperparameter tuning and one for early stopping\ntrain_x = [ -2.0, -1.0, 0.0, 1.0, 2.0 ]\ntrain_y = [ 3.22, 1.64, 0.58, 1.25, 5.07 ]\nval_x = [ -1.75, 0.25 ]\nval_y = [ 3.03, 0.46 ]\ntuneval_x = [ -0.75, 1.25 ]\ntuneval_y = [ 0.64, 0.77 ]\ntest_x = [ -1.5, -0.5, 0.5, 1.5 ]\ntest_y = [ 2.38, 0.05, 0.47, 1.67 ]\n\n#Since we will need to run different versions of model using different hyperparameters, we put the whole define-train-evaluate process in a function that takes in hyperparameters as parameters\n#We also specify whether the function is being used for hyperparameter searching or for the actual training phase by specifying an extra parameter to avoid doing what's unnecessary during tuning\ndef train_model(learning_rate, patience, weight_decay_weight, minibatch_size, momentum, initialiser_stddev, for_hyperparameter_search=False):\n g = tf.Graph()\n with g.as_default():\n xs = tf.placeholder(tf.float32, [None], 'xs')\n ts = tf.placeholder(tf.float32, [None], 'ts')\n\n c0 = tf.get_variable('c0', [], tf.float32, tf.zeros_initializer())\n c1 = tf.get_variable('c1', [], tf.float32, tf.random_normal_initializer(stddev=initialiser_stddev))\n c2 = tf.get_variable('c2', [], tf.float32, tf.random_normal_initializer(stddev=initialiser_stddev))\n c3 = tf.get_variable('c3', [], tf.float32, tf.random_normal_initializer(stddev=initialiser_stddev))\n c4 = tf.get_variable('c4', [], tf.float32, tf.random_normal_initializer(stddev=initialiser_stddev))\n c5 = tf.get_variable('c5', [], tf.float32, tf.random_normal_initializer(stddev=initialiser_stddev))\n c6 = tf.get_variable('c6', [], tf.float32, tf.random_normal_initializer(stddev=initialiser_stddev))\n \n ys = c0 + c1*xs + c2*xs**2 + c3*xs**3 + c4*xs**4 + c5*xs**5 + c6*xs**6\n \n error = tf.reduce_mean((ys - ts)**2)\n params_size = c1**2 + c2**2 + c3**2 + c4**2 + c5**2 + c6**2\n loss = error + weight_decay_weight*params_size\n\n step = tf.train.MomentumOptimizer(learning_rate, momentum).minimize(loss)\n\n init = tf.global_variables_initializer()\n \n g.finalize()\n\n with tf.Session() as s:\n s.run([ init ], { })\n\n if not for_hyperparameter_search:\n (fig, ax) = plt.subplots(1, 2)\n plt.ion()\n \n train_errors = list()\n val_errors = list()\n \n best_val_error = np.inf\n epochs_since_last_best_val_error = 0\n if not for_hyperparameter_search:\n print('epoch', 'trainerror', 'valerror', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', sep='\\t')\n for epoch in range(1, max_epochs+1):\n indexes = np.arange(len(train_x))\n np.random.shuffle(indexes)\n for i in range(int(np.ceil(len(indexes)/minibatch_size))):\n minibatch_indexes = indexes[i*minibatch_size:(i+1)*minibatch_size]\n s.run([ step ], { xs: [ train_x[j] for j in minibatch_indexes ], ts: [ train_y[j] for j in minibatch_indexes ] })\n\n if not for_hyperparameter_search:\n [ curr_c0, curr_c1, curr_c2, curr_c3, curr_c4, curr_c5, curr_c6 ] = s.run([ c0, c1, c2, c3, c4, c5, c6 ], { })\n [ train_error ] = s.run([ error ], { xs: train_x, ts: train_y })\n [ val_error ] = s.run([ error ], { xs: val_x, ts: val_y })\n if not for_hyperparameter_search:\n train_errors.append(train_error)\n val_errors.append(val_error)\n else:\n #If the validation error is invalid then stop everything and return an invalid value\n if np.isnan(val_error) or np.isinf(val_error):\n return np.nan\n\n if epoch > start_checking_early_stopping_epoch:\n if val_error < best_val_error:\n best_val_error = val_error\n epochs_since_last_best_val_error = 0\n else:\n epochs_since_last_best_val_error += 1\n\n if epochs_since_last_best_val_error >= patience:\n break\n\n if not for_hyperparameter_search and epoch%100 == 0:\n print(epoch, train_error, val_error, round(curr_c0, 3), round(curr_c1, 3), round(curr_c2, 3), round(curr_c3, 3), round(curr_c4, 3), round(curr_c5, 3), round(curr_c6, 3), sep='\\t')\n \n ax[0].cla()\n ax[1].cla()\n\n all_xs = np.linspace(-2.5, 2.5, 30)\n [ all_ys ] = s.run([ ys ], { xs: all_xs })\n ax[0].plot(all_xs, all_ys, color='blue', linestyle='-', linewidth=3)\n ax[0].plot(train_x, train_y, color='red', linestyle='', marker='o', markersize=10, label='train')\n ax[0].plot(val_x, val_y, color='yellow', linestyle='', marker='o', markersize=10, label='val')\n ax[0].plot(test_x, test_y, color='orange', linestyle='', marker='o', markersize=10, label='test')\n ax[0].set_xlim(-2.5, 2.5)\n ax[0].set_xlabel('x')\n ax[0].set_ylim(-10.0, 10.0)\n ax[0].set_ylabel('y')\n ax[0].set_title('Polynomial')\n ax[0].grid(True)\n ax[0].legend()\n\n ax[1].plot(np.arange(len(train_errors)), train_errors, color='red', linestyle='-', label='train')\n ax[1].plot(np.arange(len(val_errors)), val_errors, color='yellow', linestyle='-', label='val')\n ax[1].set_xlim(0, max_epochs)\n ax[1].set_xlabel('epoch')\n ax[1].set_ylim(0, 1)\n ax[1].set_ylabel('MSE')\n ax[1].grid(True)\n ax[1].set_title('Error progress')\n ax[1].legend()\n \n fig.tight_layout()\n plt.draw()\n plt.pause(0.0001)\n\n if not for_hyperparameter_search:\n [ test_error ] = s.run([ error ], { xs: test_x, ts: test_y })\n ax[1].annotate('Test error: '+str(test_error), (0,0))\n print('Test error:', test_error)\n \n fig.show()\n else:\n [ test_error ] = s.run([ error ], { xs: tuneval_x, ts: tuneval_y })\n \n #Return the test error for use by the hyperparameter optimiser\n return test_error\n\nopt = skopt.Optimizer(\n [\n skopt.space.Real(1e-6, 1e-1, 'log-uniform', name='learning_rate'), #The learning rate can be any real number between 1e-6 and 1e-1 on a log scaled distribution in order to choose a variety of exponent values (otherwise most values will not have any zeros after the point)\n skopt.space.Integer(10, 100, name='patience'), #The patience can be any integer between 10 and 100\n skopt.space.Real(1e-3, 1e-1, 'log-uniform', name='weight_decay_weight'),\n skopt.space.Integer(1, 5, name='minibatch_size'),\n skopt.space.Real(1e-2, 1e-0, 'log-uniform', name='momentum'),\n skopt.space.Real(1e-5, 1e-3, 'log-uniform', name='initialiser_stddev'),\n ],\n n_initial_points=num_random_hyperparams, #The number of random hyperparameters to try initially for the algorithm to have a feel of where to search\n base_estimator='RF', #Use Random Forests to predict which hyperparameters will result in good training\n acq_func='EI', #Choose a set of hyperparameters that maximise the Expected Improvement\n acq_optimizer='auto', #Let algorithm figure out how to find the most promising hyperparameters to try next\n random_state=0,\n)\n#There's also skopt.space.Categorical([val1, val2, val3], name='categorical_hyperparam') for when you want to choose a value from a given list\n#You can leave out 'log-uniform' if you're not looking for exponential values\n#See https://scikit-optimize.github.io/#skopt.Optimizer for information on the Optimizer function\n#See https://scikit-optimize.github.io/space/space.m.html for information on each optimisable data type\n\nprint('Starting hyperparameter tuning')\nprint()\nprint('#', 'learning_rate', 'patience', 'weight_decay_weight', 'minibatch_size', 'momentum', 'initialiser_stddev', 'error', sep='\\t')\n\nbest_hyperparams = None\nbest_error = np.inf\nfor i in range(1, num_random_hyperparams + num_chosen_hyperparams + 1):\n if i == 1:\n print('starting random search phase')\n if i == num_random_hyperparams+1:\n print('starting baysian optimisation phase')\n \n num_hyperpars = 1\n while True:\n #Since some hyperparameters might lead to errors, we need a way to be able to ask the optimiser for a new hyperparameter combination, test them, then only accept them if they are successful, otherwise ignore them and ask for different ones\n #This is achieved by a system of 'ask' and 'tell' in skopt\n \n #Ask for one hyperparameter combination, if it was good then ask for two next time and take the last, and so on (ask gives a list of hyperparameter candidates and will return the same candidates if you ask for the same number of candidates)\n next_hyperparams = opt.ask(num_hyperpars)[-1]\n (learning_rate, patience, weight_decay_weight, minibatch_size, momentum, initialiser_stddev) = next_hyperparams\n \n print(i, learning_rate, patience, weight_decay_weight, minibatch_size, momentum, initialiser_stddev, sep='\\t', end='\\t')\n \n #Test the hyperparameters by attempting to get the error\n try:\n error = train_model(learning_rate, patience, weight_decay_weight, minibatch_size, momentum, initialiser_stddev, for_hyperparameter_search=True)\n if np.isnan(error) or np.isinf(error):\n raise ValueError()\n except ValueError: #If some kind of error happend during evaluation of the model or if the error returned was NaN or infinite, ask for another candidate hyperparameter combination\n print('error, retrying')\n num_hyperpars += 1\n continue\n \n print(error)\n \n #Once a proper hyperparameter combination has been found, tell the optimiser about it together with its associated error in order to give it more information about which hyperparameter to suggest next\n #Unfortunately skopt can only be used to maximise not minimise so we have to negate the error in order to make it maximise the negative error\n opt.tell(next_hyperparams, -error)\n \n if error < best_error:\n best_hyperparams = next_hyperparams\n best_error = error\n \n break #Stop the while loop\n\nprint()\nprint('Tuning finished, starting actual model training')\nprint('Best hyperparameters found:')\nprint(best_hyperparams)\nprint()\n\n#Finally take the best found hyperparameters and use them\n(learning_rate, patience, weight_decay_weight, minibatch_size, momentum, initialiser_stddev) = best_hyperparams\ntrain_model(learning_rate, patience, weight_decay_weight, minibatch_size, momentum, initialiser_stddev, for_hyperparameter_search=False)","sub_path":"tensorflow_v1/02_-_Machine_learning_basics/10_-_Hyperparameter_search.py","file_name":"10_-_Hyperparameter_search.py","file_ext":"py","file_size_in_byte":11732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"163982106","text":"import math\n\ndef ArchimedesPI(i):\n n = 6\n s = 1\n for x in range(i):\n a = math.sqrt(1-(math.pow(s/2, 2)))\n b = 1-a\n s = math.sqrt(b*b+(math.pow(s/2, 2)))\n n=n*2\n p = n*s/2\n print(\"Pi er: \" + str(p))\n\nArchimedesPI(100)","sub_path":"Oving/oving2.py","file_name":"oving2.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"5396173","text":"\"\"\"\nAutorole plugin per Modmail.\n\nScritto da Papiersnipper(tradotto da Italian-Riky).\nTutti i diritti riservati.\n\"\"\"\n\nimport asyncio\nimport logging\n\nfrom discord import Embed, Guild, Member, Role\nfrom discord.ext.commands import Bot, Cog, Context, Greedy, group\nfrom discord.utils import get\nfrom motor.motor_asyncio import AsyncIOMotorCollection\n\nfrom core.checks import has_permissions\nfrom core.models import PermissionLevel\n\n\nlogger = logging.getLogger(\"Modmail\")\n\n\nclass Autorole(Cog):\n \"\"\"\n Assegna Ruoli automaticamente appena un membro entra nel server! (Plugin tradotto da [Italian Riky](https://github.com/Italian-Riky)).\n More info: [Clicca qua](https://github.com/papiersnipper/modmail-plugins/tree/master/autorole)\n \"\"\"\n\n def __init__(self, bot: Bot) -> None:\n self.bot = bot\n self.db: AsyncIOMotorCollection = bot.plugin_db.get_partition(self)\n asyncio.create_task(self.migrate())\n\n async def migrate(self) -> None:\n \"\"\"Migra il modello di database per contenere un elenco di ID ruolo invece del campo `` nome ruolo ``.\"\"\"\n config = await self.db.find_one({\"_id\": \"autorole-config\"})\n\n if config is None:\n return\n\n try:\n rolename = config[\"rolename\"]\n except KeyError:\n return\n\n guild: Guild = get(self.bot.guilds, id=int(self.bot.config[\"guild_id\"]))\n\n if guild is None:\n return await self.db.delete_one({\"_id\": \"autorole-config\"})\n\n role: Role = get(guild.roles, name=rolename)\n\n roles = []\n roles.append(role.id)\n\n await self.db.replace_one({\"_id\": \"autorole-config\"}, {\"roles\": roles})\n\n @Cog.listener()\n async def on_member_join(self, member: Member) -> None:\n \"\"\"Assegna al membro iscritto tutti i ruoli attualmente impostati.\"\"\"\n config = await self.db.find_one({\"_id\": \"autorole-config\"})\n\n if config is None:\n return logger.warning(\"Il membro si è unito mentre nessun ruolo era stato impostato!\")\n\n try:\n role_ids = config[\"roles\"]\n except KeyError:\n return logger.error(\"Qualcosa è andato storto nel tuo database!\")\n\n if not role_ids:\n return\n\n roles = []\n for role_id in role_ids:\n role: Role = get(member.guild.roles, id=role_id)\n\n if role is not None:\n roles.append(role)\n\n await member.add_roles(*roles)\n\n @group(name=\"autorole\", invoke_without_command=True)\n @has_permissions(PermissionLevel.ADMINISTRATOR)\n async def autorole(self, ctx: Context) -> None:\n \"\"\"Assegna automaticamente un ruolo a un utente quando si unisce al tuo server.\"\"\"\n await ctx.send_help(ctx.command)\n\n @autorole.command(name=\"set\")\n @has_permissions(PermissionLevel.ADMINISTRATOR)\n async def autorole_set(self, ctx: Context, roles: Greedy[Role]) -> None:\n \"\"\"Imposta i ruoli predefiniti che un membro ottiene quando si unisce.\"\"\"\n if not roles:\n return await ctx.send_help(ctx.command)\n\n config = await self.db.find_one({\"_id\": \"autorole-config\"})\n\n if config is None:\n await self.db.insert_one({\"_id\": \"autorole-config\"})\n logger.info(\"Creato file di configurazione autorole.\")\n\n role_ids = [r.id for r in roles]\n role_mentions = [r.mention for r in roles]\n\n await self.db.find_one_and_update(\n {\"_id\": \"autorole-config\"}, {\"$set\": {\"roles\": role_ids}}\n )\n\n embed = Embed(\n title=\"Autorole\",\n url=\"https://github.com/Italian-Riky/modmail-plugins-1/blob/master/autorole\",\n description=f\"{', '.join(role_mentions)} will now be given to all new members.\",\n color=self.bot.main_color,\n )\n\n await ctx.send(embed=embed)\n\n @autorole.command(name=\"give\")\n @has_permissions(PermissionLevel.ADMINISTRATOR)\n async def autorole_give(self, ctx: Context, role: Role) -> None:\n \"\"\"Give this role to all members of your server.\"\"\"\n users = 0\n for member in ctx.guild.members:\n if role.id in [role.id for role in member.roles]:\n continue\n else:\n await member.add_roles(role)\n users = users + 1\n\n embed = Embed(\n title=\"Autorole\",\n url=\"https://github.com/Italian-Riky/modmail-plugins-1/blob/master/autorole\",\n description=f\"Added {role.mention} for {users} members.\",\n colour=self.bot.main_color,\n )\n\n await ctx.send(embed=embed)\n\n @autorole.command(name=\"clear\", aliases=[\"reset\"])\n @has_permissions(PermissionLevel.ADMINISTRATOR)\n async def autorole_clear(self, ctx: Context) -> None:\n \"\"\"Clear the default role(s).\"\"\"\n embed = Embed(\n title=\"Autorole\",\n url=\"https://github.com/Italian-Riky/modmail-plugins-1/blob/master/autorole\",\n description=f\"Cleared role(s).\",\n color=self.bot.main_color,\n )\n\n config = await self.db.find_one({\"_id\": \"autorole-config\"})\n\n if config is None:\n return await ctx.send(embed=embed)\n\n await self.db.find_one_and_update({\"_id\": \"autorole-config\"}, {\"$set\": {\"roles\": []}})\n\n await ctx.send(embed=embed)\n\n\ndef setup(bot: Bot) -> None:\n \"\"\"Bot cog load.\"\"\"\n bot.add_cog(Autorole(bot))\n","sub_path":"autorole/autorole.py","file_name":"autorole.py","file_ext":"py","file_size_in_byte":5395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"516311384","text":"import json\nimport jwt\nimport time\n\nfrom hyper import HTTPConnection\n\nALGORITHM = 'ES256'\n\nAPNS_KEY_ID = 'YYYY'\nAPNS_AUTH_KEY = './AuthKey_YYYY.p8'\nTEAM_ID = 'XXXX'\nBUNDLE_ID = 'it.domain.appid(.voip)'\n\nREGISTRATION_ID = 'tokem_push'\n\nf = open(APNS_AUTH_KEY)\nsecret = f.read()\n\ntoken = jwt.encode(\n {\n 'iss': TEAM_ID,\n 'iat': time.time()\n },\n secret,\n algorithm= ALGORITHM,\n headers={\n 'alg': ALGORITHM,\n 'kid': APNS_KEY_ID,\n }\n)\n\npath = '/3/device/{0}'.format(REGISTRATION_ID)\n\nrequest_headers = {\n 'apns-expiration': '0',\n 'apns-priority': '10',\n 'apns-topic': BUNDLE_ID,\n 'authorization': 'bearer {0}'.format(token.decode('ascii'))\n}\n\n# Open a connection the APNS server\nconn = HTTPConnection('api.development.push.apple.com:443')\n\npayload_data = { \n 'aps': { 'event_type' : 'MESSAGE' }, 'text0' : 'Prova', 'lyber_id': '2904' \n}\npayload = json.dumps(payload_data).encode('utf-8')\n\n# Send our request\nconn.request(\n 'POST', \n path, \n payload, \n headers=request_headers\n)\nresp = conn.get_response()\nprint(resp.status)\nprint(resp.read())\n\n# If we are sending multiple requests, use the same connection\n\n#payload_data = { \n# 'aps': { 'alert' : 'You have no chance to survive. Make your time.' } \n#}\n#payload = json.dumps(payload_data).encode('utf-8')\n\n#conn.request(\n# 'POST', \n# path, \n# payload, \n# headers=request_headers\n#)\n#resp = conn.get_response()\n#print(resp.status)\n#print(resp.read())\n","sub_path":"python/apns_api2_http_test.py","file_name":"apns_api2_http_test.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"592502652","text":"import numpy as np\nfrom scipy.integrate import solve_ivp\nfrom matplotlib import pyplot as plt\nfrom numpy import heaviside as hs\n\n# Part a\ndef de_86a(t, w):\n y = w[0]\n x = w[1]\n return np.array(\n [x,\n hs(t, np.pi) - hs(t, 2 * np.pi) - 2 * x - 2 * y]\n )\n\ny0 = 0\nx0 = 1\nw0 = np.array(\n [y0,\n x0]\n)\n\nt_span = np.array([0, 20])\n\nw_soln = solve_ivp(fun=de_86a, y0=w0, t_span=t_span, max_step = 0.01)\n\nplt.plot(\n w_soln.t,\n w_soln.y[0]\n)\n\nplt.show()","sub_path":"lab_8/q_81/q_81a.py","file_name":"q_81a.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"59545253","text":"import sqlite3\n\ndef get_symbols():\n symbols = [i[0] for i in get_rows()]\n return symbols\n\ndef get_schema():\n return [\n ['name','text'],\n ['expense_ratio', 'real'],\n ['category', 'text']\n ]\n\ndef get_rows():\n symbols_info = [\n ['SPY', 0.09, 'capital'],\n ['VIG', 0.1, 'capital'],\n ['VOO', 0.05, 'capital'],\n ['VTI', 0.05, 'capital'],\n ['VBR', 0.08, 'capital'],\n ['VWO', 0.15, 'international'],\n ['VPL', 0.12, 'international'],\n ['VGK', 0.12, 'international'],\n ['VCR', 0.1, 'sector'],\n ['VDC', 0.1, 'sector'],\n ['VDE', 0.1, 'sector'],\n ['VFH', 0.1, 'sector'],\n ['VHI', 0.09, 'sector'],\n ['VIS', 0.1, 'sector'],\n ['VGI', 0.1, 'sector'],\n ['VAW', 0.1, 'sector'],\n ['VNQ', 0.12, 'sector'],\n ['VOX', 0.1, 'sector'],\n ['VPU', 0.1, 'sector'],\n ]\n\n return symbols_info\n\ndef run():\n conn = sqlite3.connect('data/db/vanguard.db')\n c = conn.cursor()\n\n sql_cmd = 'DROP TABLE IF EXISTS symbols'\n c.execute(sql_cmd)\n\n sql_cmd = 'CREATE TABLE symbols ('\n for row in get_schema():\n sql_cmd += '{},'.format(' '.join(row))\n sql_cmd = sql_cmd[:-1] + ')'\n print(sql_cmd)\n c.execute(sql_cmd)\n\n for row in get_rows():\n sql_cmd = 'INSERT INTO symbols VALUES ('\n for col in row:\n if isinstance(col, float):\n sql_cmd += '{},'.format(col)\n else:\n sql_cmd += \"'{}',\".format(col)\n sql_cmd = sql_cmd[:-1] + ')'\n print(sql_cmd)\n c.execute(sql_cmd)\n\n conn.commit()\n conn.close()\n\nif __name__ == \"__main__\":\n run()","sub_path":"tables/symbols.py","file_name":"symbols.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"576197559","text":"import sys\n\nfrom pnu_semiconductor.my_utils import outlier2na\n\nsys.path.append(r'C:\\Users\\user\\Documents\\minkun\\jupyter\\semiconductor\\grape\\pnu_semiconductor'.replace('\\\\', '/'))\nsys.path.append(r'C:\\Users\\user\\Documents\\minkun\\jupyter\\semiconductor\\grape\\utils'.replace('\\\\', '/'))\n\nfrom pnu_semiconductor.my_utils import *\n\nimport pandas as pd\n\nimport pickle\n\"\"\"\n검증코드\n\"\"\"\ndef wf2graph_test(wf, edge_attr, valid_range = range(3, len(wf.columns)-1)):\n \"\"\"웨이퍼 단위로 수행해야함\n wf 테이블의 셀에있는 값과 edge_attr의 값이 같은지 비교. \n Args:\n wf (df): \n valid_range range: time, x, y, index를 거리기 위한 컬럼 range\n \"\"\"\n # x, edge_index, edge_attr, edgge_sim_idx = wf2graph(wf, (3,3))\n # print(edge_attr)\n idx=0\n wf_values = wf.values\n for i in range(len(wf_values)):\n for j in (valid_range):\n val = wf_values[i,j]\n # if abs(val) < 4:\n if not pd.isna(val): # na값이 끼여있기 때문에 이런 처리가 필요\n assert edge_attr[idx] == val, f'{edge_attr[idx]} == {val}, i : {i}, j : {j}, ,idx : {idx}'\n idx+=1\ndef test_preprocessed_file():\n \"\"\"\n wf2graph로 전처리된 파일을 검증.\n :return:\n \"\"\"\n df = pd.read_pickle(r'C:\\Users\\user\\Documents\\minkun\\jupyter\\semiconductor\\pkl\\part12.pkl'.replace('\\\\', '/'))\n df.info()\n df\n nacnt = df.isna().sum()\n clear_col = nacnt[nacnt == 0].index.to_list()\n\n cleardf = df[clear_col]\n cleardf.info()\n cleardf1 = outlier2na(cleardf, 4) # 절댓값 4 이상치 처리.\n assert ((cleardf.iloc[:, 3:-1]>=4) |(cleardf.iloc[:, 3:-1]<= -4)).sum().sum()==0 , ((cleardf.iloc[:, 3:-1]>=4) |(cleardf.iloc[:, 3:-1]<= -4)).sum()\n wf = cleardf1.loc[cleardf1.index.unique()[0]]\n\n p = r'C:\\Users\\user\\Documents\\minkun\\jupyter\\semiconductor\\grape\\pnu_semiconductor\\resources\\4_na\\wf_graph_list_20cols.pkl'.replace('\\\\', '/')\n with open(p, 'rb') as f:\n graph_li = pickle.load(f)\n\n uniidx = cleardf1.index.unique()\n for i in range(len(graph_li)):\n print(i)\n x, edge_index, edge_attr, edge_sim_idx = graph_li[i]\n wf = cleardf1.loc[uniidx[i], :]\n wf2graph_test(wf, edge_attr)\n assert ((edge_attr>4) | (edge_attr <-4)).sum().item() == 0, edge_attr[(((edge_attr>4) | (edge_attr <-4)))] # assert할 땐 =를 뺴야한다.\n\n","sub_path":"pnu_semiconductor/code_validation/preprocessing_valid.py","file_name":"preprocessing_valid.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"218122736","text":"import argparse\nfrom math import floor\n\n\ndef compute(program):\n for index in range(0, len(program), 4):\n opcode, i, j, k = program[index : index + 4]\n\n if opcode == 1:\n program[k] = program[i] + program[j]\n elif opcode == 2:\n program[k] = program[i] * program[j]\n elif opcode == 99:\n return program[0]\n else:\n raise ValueError(f\"Opcode {opcode} not valid\")\n\n\ndef part1(program):\n program[1] = 12\n program[2] = 2\n\n print(f\"p1: {compute(program)}\")\n\n\ndef part2(program):\n desired_output = 19690720\n\n for i in range(100):\n for j in range(100):\n current_program = list(program)\n current_program[1] = i\n current_program[2] = j\n\n if compute(current_program) == desired_output:\n print(f\"{i:02}{j:02}\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"part\", type=int)\n\n with open(\"input.txt\") as fp:\n inp = [int(s.strip()) for s in fp.read().split(\",\")]\n\n if parser.parse_args().part == 1:\n part1(inp)\n else:\n part2(inp)\n\n","sub_path":"02/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"250959169","text":"# restore training set\nimport numpy as np\n\ntemp = np.load('../Zeldovich_Approximation.npz')\nsim_z0 = temp[\"sim_z0\"]\nsim_z50 = temp[\"sim_z50\"]\n\n#-------------------------------------------------------------------------------------\n# import packages\nfrom kymatio import HarmonicScattering3D\n\n# make scattering coefficients\nJ_choice = 6\nL_choice = 5\nmax_order_choice = 2\nscattering = HarmonicScattering3D(J=J_choice, shape=(64,64,64),\\\n L=L_choice, max_order=max_order_choice)\nscattering.cuda()\n\nimport torch\nx_image = torch.from_numpy(sim_z0).type(torch.cuda.FloatTensor)\nscatter_coeff = scattering(x_image).view(x_image.shape[0],-1).cpu().detach().numpy()\nprint(scatter_coeff.shape)\n\n# save results\nnp.save(\"scatter_coeff_3D_max_order=\" + str(max_order_choice) + \".npy\", scatter_coeff)\n","sub_path":"generate_image_3D_make_scattering.py","file_name":"generate_image_3D_make_scattering.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"510826168","text":"\nfrom PyQt5.QtGui import QPainter, QPixmap\nfrom PyQt5.QtCore import QRect, QSize, Qt, QObject, QTimer, pyqtSignal\nfrom PyQt5.QtWidgets import QWidget, QDialog, QVBoxLayout, QFormLayout, QLineEdit, QComboBox, QGroupBox, QCheckBox, QDialogButtonBox, QTableWidget, QTableWidgetItem, QAbstractItemView, QTableView\n\nfrom hcheckers.common import *\nfrom hcheckers.game import Game\n\nclass HistoryWidget(QTableWidget):\n def __init__(self, client, board, parent=None):\n QTableWidget.__init__(self, parent)\n self.client = client\n self.board = board\n\n self.setColumnCount(2)\n\n def fill(self):\n self.clearContents()\n\n def make_item(value):\n item = QTableWidgetItem(value)\n item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)\n return item\n\n first, second = self.client.get_colors(self.client.rules)\n self.setHorizontalHeaderLabels([first, second])\n\n history = self.client.get_history()\n if history is None:\n return\n self.setRowCount((len(history) / 2) + 1)\n row = 0\n for record in reversed(history):\n side = record[\"side\"]\n move = Move.fromJson(record[\"move\"])\n if side == 'First':\n column = 0\n else:\n column = 1\n\n self.setItem(row, column, make_item(self.board.show_move(move)))\n if side == 'Second':\n row = row + 1\n\n\n","sub_path":"python/hcheckers/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"605964386","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 18-5-25 下午8:24\n# @Author : fixdq\n# @File : start.py\n# @Software: PyCharm\n\nfrom client import tcpclient\nfrom lib import common\n\n\ndef login(conn):\n send_data = {'type': 'login',\n 'msg': 'hello'}\n res = common.send_back(conn, send_data)\n if res['flag']:\n print(res['msg'])\n else:\n print(res['msg'])\n\n\ndef register(conn):\n pass\n\n\nmenu = \"\"\"\n1.登录\n2.注册\n\"\"\"\nmenu_dic = {\n '1': login,\n '2': register,\n}\n\n\ndef view():\n conn = tcpclient.get_client()\n while True:\n print(menu)\n ch = input('>>>').strip()\n if ch == 'q ': break\n if ch not in menu_dic: continue\n menu_dic[ch](conn)\n conn.close()\n","sub_path":"day50/client/core/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"626787337","text":"# delete_fixe_one_rec_one_table.py\n# OM 2020.03.10 le but est d'effacer une ligne d'une table en MySql.\n\nimport pymysql\nimport warnings\n\nfrom Exercice1.DATABASE import connect_db\n\n# OM 2020.03.02 Mécanisme ingénieux qui filtre les warnings et les associes\n# pour être traitées comme des erreurs dans le code Python.\n# détecte la suite de caractères \"Duplicate entry.\" dans un message de warnings\n# et convertit le warnings en action \"error\"\nwarnings.filterwarnings(\n action=\"error\",\n message=\".*Duplicate entry.*\",\n category=pymysql.Warning\n)\n\n# détecte la suite de caractères \"1265.\" dans un message de warnings\n# et convertit le warnings en action \"error\"\nwarnings.filterwarnings(\n action=\"error\",\n message=\".*1265.*\",\n category=pymysql.Warning\n)\n\nclass DbDeleteOneTable():\n\n # Constructeur, à chaque instanciation de cette classe \"DbInsertOneTable()\" les lignes de code de la méthode \"__init__ (self)\" sont interprétées.\n def __init__ (self):\n print(\"Constructeur CLASSE DbDeleteOneTable\")\n\n def delete_one_record_one_table(self, requete_delete_mysql, num_ligne_delete):\n \"\"\"\n Méthode qui permet d'effacer une ligne d'une table.\n OM 2020.03.24\n Parametres:\n requete_delete_mysql (class 'str'): la requête DELETE MySql\n num_ligne_delete (class 'int'): numéro de la ligne à effacer\n Retourne:\n pas de valeurs\n \"\"\"\n try:\n # OM 2020.01.28 CONNECTION A LA BD\n self.connection_dbc = connect_db.DatabaseTools()\n # Un simple test qui renvoie un message dans la console suivant l'état de la BD\n self.connection_dbc.is_connection_open()\n\n # Pour aider à comprendre les types de données on affiche dans la console.\n print(\"type >>> requete_delete_mysql \",type(requete_delete_mysql))\n print(\"type >>> num_ligne_delete \",type(num_ligne_delete))\n # Afficher les docstrings...très importantes pour votre projet.\n print(self.delete_one_record_one_table.__doc__)\n\n # OM 2020.03.11 Execute la requête avec un passage de paramètres\n self.connection_dbc.DBcursor.execute(requete_delete_mysql, {'no_ligne_delete' : num_ligne_delete})\n # OM 2020.03.11 L'instruction suivante est indispensable pour confirmer l'effacement des données (en cas de problèmes : rollback)\n self.connection_dbc.db.commit()\n self.connection_dbc.DBcursor.close()\n except pymysql.Error as error:\n # OM 2020.03.11 L'instruction suivante est indispensable pour confirmer l'effacement des données (en cas de problèmes : rollback)\n self.connection_dbc.db.rollback()\n print(\" Il y a une ERREUR : %s\", error)\n print(\"connection_dbc.db.rollback() insertOneRecord\")\n except pymysql.DataError as error1:\n # OM 2020.03.11 L'instruction suivante est indispensable pour confirmer l'effacement des données (en cas de problèmes : rollback)\n self.connection_dbc.db.rollback()\n print(\" Il y a une DataError : %s\", error1)\n print(\"connection_dbc.db.rollback() insertOneRecord\")\n except pymysql.DatabaseError as error2:\n # OM 2020.03.11 L'instruction suivante est indispensable pour confirmer l'effacement des données (en cas de problèmes : rollback)\n self.connection_dbc.db.rollback()\n print(\" Il y a une DatabaseError : %s\", error2)\n print(\"connection_dbc.db.rollback() insertOneRecord\")\n except pymysql.Warning as error3:\n # OM 2020.03.11 L'instruction suivante est indispensable pour confirmer l'effacement des données (en cas de problèmes : rollback)\n self.connection_dbc.db.rollback()\n print(\" Il y a une Warning : %s\", error3)\n print(\"connection_dbc.db.rollback() insertOneRecord\")\n except pymysql.MySQLError as error4:\n # OM 2020.03.11 L'instruction suivante est indispensable pour confirmer l'effacement des données (en cas de problèmes : rollback)\n self.connection_dbc.db.rollback()\n print(\" Il y a une MySQLError : %s\", error4)\n print(\"connection_dbc.db.rollback() insertOneRecord\")\n except pymysql.IntegrityError as error5:\n # OM 2020.03.11 L'instruction suivante est indispensable pour confirmer l'effacement des données (en cas de problèmes : rollback)\n self.connection_dbc.db.rollback()\n print(\" Il y a une IntegrityError : %s\", error5)\n print(\"connection_dbc.db.rollback() insertOneRecord\")\n except:\n # OM 2020.03.11 L'instruction suivante est indispensable pour confirmer l'effacement des données (en cas de problèmes : rollback)\n self.connection_dbc.db.rollback()\n print(\"Unknown error occurred\")\n finally:\n # On ferme le curseur et la base de donnée et on affiche un message dans la console.\n self.connection_dbc.DBcursor.close()\n self.connection_dbc.close_connection()\n print(\"DBcursor et DB fermés\")\n","sub_path":"Exercice1/DATABASE/DELETE/delete_one_record_one_table.py","file_name":"delete_one_record_one_table.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"411325932","text":"from bs4 import BeautifulSoup\nfrom os import path\nfrom random import shuffle\nfrom requests import get\n\n\ndef random_user_agents(win=True, mac=False, linux=False, unix=False):\n \"\"\"\n :param win: Windows Browser\n :param mac: Mac Browser\n :param linux: Linux Browser\n :param unix: Unix Browser\n :return: Shuffled list of User-Agents.\n Defaults to Windows User-Agents if all are False.\n \"\"\"\n ua_filename = 'all_user_agents.xml'\n if not path.exists(ua_filename): # download XML file if nonexistent\n url = 'http://techpatterns.com/downloads/firefox/useragentswitcher.xml'\n r = get(url, stream=True)\n with open(ua_filename, 'wb') as file:\n for chunk in r.iter_content(128):\n file.write(chunk)\n\n with open(ua_filename, 'r') as file:\n soup = BeautifulSoup(file, 'xml')\n\n agents = list()\n browser_os = list()\n if not win and not mac and not linux and not unix: # all False\n win = True # default back to windows\n\n if win:\n browser_os.append('Browsers - Windows')\n if mac:\n browser_os.append('Browsers - Mac')\n if linux:\n browser_os.append('Browsers - Linux')\n if unix:\n browser_os.append('Browsers - Unix')\n\n for os in browser_os:\n for a in soup.find_all(description=os):\n agents.extend([b['useragent'] for b in a.find_all('useragent')])\n shuffle(agents)\n return agents\n\nif __name__ == '__main__':\n print(random_user_agents()) # default returns windows user-agents\n","sub_path":"user_agents.py","file_name":"user_agents.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"218665674","text":"\nimport numpy as np\nimport pandas as pd\nimport os\n\nimport matplotlib.pyplot as plt\n### matplotlib inline\nfrom tqdm import tqdm_notebook\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import NuSVR, SVR\nfrom sklearn.metrics import mean_absolute_error\npd.options.display.precision = 15\nfrom sklearn.svm import NuSVR, SVR\nimport lightgbm as lgb\nimport xgboost as xgb\nimport time\nimport datetime\n\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold, KFold, RepeatedKFold\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nfrom sklearn.linear_model import Ridge, RidgeCV\nimport gc\nfrom catboost import CatBoostRegressor\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport gc\ntrain = pd.read_csv('../input/train.csv', dtype={'acoustic_data': np.int16, 'time_to_failure': np.float64})\n#min_1 = train.acoustic_data.mean() - 3 * train.acoustic_data.std()\n#max_1 = train.acoustic_data.mean() + 3 * train.acoustic_data.std() \n#train[\"sharp_rise1\"] = np.where((train.acoustic_data >= min_1) & (train.acoustic_data <= max_1), 0, 100)\n#del min_1,max_1\n#gc.collect()\n#min_2 = train.acoustic_data.mean() - 2 * train.acoustic_data.std()\n#max_2 = train.acoustic_data.mean() + 2 * train.acoustic_data.std() \n#train[\"sharp_rise2\"] = np.where((train.acoustic_data >= min_2) & (train.acoustic_data <= max_2), 0, 50)\n#del min_2,max_2\n#gc.collect()\n#differences = np.diff(train.time_to_failure)\n#train = train.drop(train.index[len(train)-1])\n#train[\"differences\"] = differences\n\n#train.differences.unique()\n#train[\"differences\"] = np.around(train[\"differences\"],10)\n#train.differences.unique()\n#train = train.convert_objects(convert_numeric=True)\n#train[\"change\"]=train.differences * 1e9 + 1\n\n#train.change.unique()\n#train[\"change\"] = np.around(train[\"change\"],3)\n#train[\"change\"]=np.floor(train[\"change\"])\n\n#train.head()\n#columns = ['sharp_rise1', 'sharp_rise2',\"differences\",\"change\"]\n#train.drop(columns, inplace=True, axis=1)\n#del differences\n#gc.collect()\nfrom scipy.signal import hilbert\nfrom scipy.signal import hann\nfrom scipy.signal import convolve\n\ndef classic_sta_lta(x, length_sta, length_lta):\n \n sta = np.cumsum(x ** 2)\n\n # Convert to float\n sta = np.require(sta, dtype=np.float)\n\n # Copy for LTA\n lta = sta.copy()\n\n # Compute the STA and the LTA\n sta[length_sta:] = sta[length_sta:] - sta[:-length_sta]\n sta /= length_sta\n lta[length_lta:] = lta[length_lta:] - lta[:-length_lta]\n lta /= length_lta\n\n # Pad zeros\n sta[:length_lta - 1] = 0\n\n # Avoid division by zero by setting zero values to tiny float\n dtiny = np.finfo(0.0).tiny\n idx = lta < dtiny\n lta[idx] = dtiny\n\n return sta / lta\n# Create a training file with simple derived features\nrows = 150_000\nsegments = int(np.floor(train.shape[0] / rows))\n\nX_tr = pd.DataFrame(index=range(segments), dtype=np.float64,\n columns=['mean', 'std', 'max', 'min',\n 'mean_change_abs', 'mean_change_rate', 'abs_max', 'abs_min',\n 'std_first_50000', 'std_last_50000', 'std_first_10000', 'std_last_10000',\n 'avg_first_50000', 'avg_last_50000', 'avg_first_10000', 'avg_last_10000',\n 'min_first_50000', 'min_last_50000', 'min_first_10000', 'min_last_10000',\n 'max_first_50000', 'max_last_50000', 'max_first_10000', 'max_last_10000',\n 'max_to_min', 'max_to_min_diff', 'count_big', 'sum',\n 'mean_change_rate_first_50000', 'mean_change_rate_last_50000', 'mean_change_rate_first_10000', 'mean_change_rate_last_10000','q70','q75','q60','q65','q85',\"q90\",'q80','q95','q99','Hilbert_mean','Hann_window_mean','classic_sta_lta1_mean','classic_sta_lta2_mean','classic_sta_lta3_mean','classic_sta_lta4_mean','Moving_average_700_mean','Moving_average_1500_mean','Moving_average_3000_mean','Moving_average_6000_mean','exp_Moving_average_300_mean','exp_Moving_average_3000_mean','exp_Moving_average_30000_mean','MA_700MA_std_mean','MA_700MA_BB_high_mean','MA_700MA_BB_low_mean','MA_400MA_std_mean','MA_400MA_BB_high_mean','MA_400MA_BB_low_mean','MA_1000MA_std_mean'])\ny_tr = pd.DataFrame(index=range(segments), dtype=np.float64,\n columns=['time_to_failure'])\n\ntotal_mean = train['acoustic_data'].mean()\ntotal_std = train['acoustic_data'].std()\ntotal_max = train['acoustic_data'].max()\ntotal_min = train['acoustic_data'].min()\ntotal_sum = train['acoustic_data'].sum()\ntotal_abs_max = np.abs(train['acoustic_data']).sum()\n\nfor segment in tqdm_notebook(range(segments)):\n seg = train.iloc[segment*rows:segment*rows+rows]\n x = pd.Series(seg['acoustic_data'].values)\n y = seg['time_to_failure'].values[-1]\n \n y_tr.loc[segment, 'time_to_failure'] = y\n X_tr.loc[segment, 'mean'] = x.mean()\n X_tr.loc[segment, 'std'] = x.std()\n X_tr.loc[segment, 'max'] = x.max()\n X_tr.loc[segment, 'min'] = x.min()\n \n \n X_tr.loc[segment, 'mean_change_abs'] = np.mean(np.diff(x))\n X_tr.loc[segment, 'mean_change_rate'] = np.mean(np.nonzero((np.diff(x) / x[:-1]))[0])\n X_tr.loc[segment, 'abs_max'] = np.abs(x).max()\n X_tr.loc[segment, 'abs_min'] = np.abs(x).min()\n \n X_tr.loc[segment, 'std_first_50000'] = x[:50000].std()\n X_tr.loc[segment, 'std_last_50000'] = x[-50000:].std()\n X_tr.loc[segment, 'std_first_10000'] = x[:10000].std()\n X_tr.loc[segment, 'std_last_10000'] = x[-10000:].std()\n \n X_tr.loc[segment, 'avg_first_50000'] = x[:50000].mean()\n X_tr.loc[segment, 'avg_last_50000'] = x[-50000:].mean()\n X_tr.loc[segment, 'avg_first_10000'] = x[:10000].mean()\n X_tr.loc[segment, 'avg_last_10000'] = x[-10000:].mean()\n \n X_tr.loc[segment, 'min_first_50000'] = x[:50000].min()\n X_tr.loc[segment, 'min_last_50000'] = x[-50000:].min()\n X_tr.loc[segment, 'min_first_10000'] = x[:10000].min()\n X_tr.loc[segment, 'min_last_10000'] = x[-10000:].min()\n \n X_tr.loc[segment, 'max_first_50000'] = x[:50000].max()\n X_tr.loc[segment, 'max_last_50000'] = x[-50000:].max()\n X_tr.loc[segment, 'max_first_10000'] = x[:10000].max()\n X_tr.loc[segment, 'max_last_10000'] = x[-10000:].max()\n \n X_tr.loc[segment, 'max_to_min'] = x.max() / np.abs(x.min())\n X_tr.loc[segment, 'max_to_min_diff'] = x.max() - np.abs(x.min())\n X_tr.loc[segment, 'count_big'] = len(x[np.abs(x) > 500])\n X_tr.loc[segment, 'sum'] = x.sum()\n \n X_tr.loc[segment, 'mean_change_rate_first_50000'] = np.mean(np.nonzero((np.diff(x[:50000]) / x[:50000][:-1]))[0])\n X_tr.loc[segment, 'mean_change_rate_last_50000'] = np.mean(np.nonzero((np.diff(x[-50000:]) / x[-50000:][:-1]))[0])\n X_tr.loc[segment, 'mean_change_rate_first_10000'] = np.mean(np.nonzero((np.diff(x[:10000]) / x[:10000][:-1]))[0])\n X_tr.loc[segment, 'mean_change_rate_last_10000'] = np.mean(np.nonzero((np.diff(x[-10000:]) / x[-10000:][:-1]))[0])\n \n #new:'q70','q75','q60','q65'\n X_tr.loc[segment, 'q70'] = np.quantile(x, 0.70) \n X_tr.loc[segment, 'q75'] = np.quantile(x, 0.75) \n X_tr.loc[segment, 'q60'] = np.quantile(x, 0.60) \n X_tr.loc[segment, 'q65'] = np.quantile(x, 0.65) \n X_tr.loc[segment, 'q85'] = np.quantile(x, 0.85)\n X_tr.loc[segment, 'q90'] = np.quantile(x, 0.90)\n X_tr.loc[segment, 'q80'] = np.quantile(x, 0.80)\n X_tr.loc[segment, 'q95'] = np.quantile(x, 0.95)\n X_tr.loc[segment, 'q99'] = np.quantile(x, 0.99)\n\n\n X_tr.loc[segment, 'Hilbert_mean'] = np.abs(hilbert(x)).mean()\n X_tr.loc[segment, 'Hann_window_mean'] = (convolve(x, hann(150), mode='same') / sum(hann(150))).mean()\n X_tr.loc[segment, 'classic_sta_lta1_mean'] = classic_sta_lta(x, 500, 10000).mean()\n X_tr.loc[segment, 'classic_sta_lta2_mean'] = classic_sta_lta(x, 5000, 100000).mean()\n X_tr.loc[segment, 'classic_sta_lta3_mean'] = classic_sta_lta(x, 3333, 6666).mean()\n X_tr.loc[segment, 'classic_sta_lta4_mean'] = classic_sta_lta(x, 10000, 25000).mean()\n X_tr.loc[segment, 'Moving_average_700_mean'] = x.rolling(window=700).mean().mean(skipna=True)\n X_tr.loc[segment, 'Moving_average_1500_mean'] = x.rolling(window=1500).mean().mean(skipna=True)\n X_tr.loc[segment, 'Moving_average_3000_mean'] = x.rolling(window=3000).mean().mean(skipna=True)\n X_tr.loc[segment, 'Moving_average_6000_mean'] = x.rolling(window=6000).mean().mean(skipna=True)\n ewma = pd.Series.ewm\n X_tr.loc[segment, 'exp_Moving_average_300_mean'] = (ewma(x, span=300).mean()).mean(skipna=True)\n X_tr.loc[segment, 'exp_Moving_average_3000_mean'] = ewma(x, span=3000).mean().mean(skipna=True)\n X_tr.loc[segment, 'exp_Moving_average_30000_mean'] = ewma(x, span=6000).mean().mean(skipna=True)\n no_of_std = 2\n X_tr.loc[segment, 'MA_700MA_std_mean'] = x.rolling(window=700).std().mean()\n X_tr.loc[segment,'MA_700MA_BB_high_mean'] = (X_tr.loc[segment, 'Moving_average_700_mean'] + no_of_std * X_tr.loc[segment, 'MA_700MA_std_mean']).mean()\n X_tr.loc[segment,'MA_700MA_BB_low_mean'] = (X_tr.loc[segment, 'Moving_average_700_mean'] - no_of_std * X_tr.loc[segment, 'MA_700MA_std_mean']).mean()\n X_tr.loc[segment, 'MA_400MA_std_mean'] = x.rolling(window=400).std().mean()\n X_tr.loc[segment,'MA_400MA_BB_high_mean'] = (X_tr.loc[segment, 'Moving_average_700_mean'] + no_of_std * X_tr.loc[segment, 'MA_400MA_std_mean']).mean()\n X_tr.loc[segment,'MA_400MA_BB_low_mean'] = (X_tr.loc[segment, 'Moving_average_700_mean'] - no_of_std * X_tr.loc[segment, 'MA_400MA_std_mean']).mean()\n X_tr.loc[segment, 'MA_1000MA_std_mean'] = x.rolling(window=1000).std().mean()\n \nfsegments = 10000\n\nX_tr1 = pd.DataFrame(index=range(segments), dtype=np.float64,\n columns=['mean', 'std', 'max', 'min',\n 'mean_change_abs', 'mean_change_rate', 'abs_max', 'abs_min',\n 'std_first_50000', 'std_last_50000', 'std_first_10000', 'std_last_10000',\n 'avg_first_50000', 'avg_last_50000', 'avg_first_10000', 'avg_last_10000',\n 'min_first_50000', 'min_last_50000', 'min_first_10000', 'min_last_10000',\n 'max_first_50000', 'max_last_50000', 'max_first_10000', 'max_last_10000',\n 'max_to_min', 'max_to_min_diff', 'count_big', 'sum',\n 'mean_change_rate_first_50000', 'mean_change_rate_last_50000', 'mean_change_rate_first_10000', 'mean_change_rate_last_10000','q70','q75','q60','q65','q85',\"q90\",'q80',\n 'q95','q99','Hilbert_mean','Hann_window_mean','classic_sta_lta1_mean','classic_sta_lta2_mean','classic_sta_lta3_mean','classic_sta_lta4_mean','Moving_average_700_mean','Moving_average_1500_mean','Moving_average_3000_mean','Moving_average_6000_mean','exp_Moving_average_300_mean','exp_Moving_average_3000_mean','exp_Moving_average_30000_mean','MA_700MA_std_mean','MA_700MA_BB_high_mean','MA_700MA_BB_low_mean','MA_400MA_std_mean','MA_400MA_BB_high_mean','MA_400MA_BB_low_mean','MA_1000MA_std_mean'])\ny_tr1 = pd.DataFrame(index=range(segments), dtype=np.float64,\n columns=['time_to_failure'])\n\ntotal_mean = train['acoustic_data'].mean()\ntotal_std = train['acoustic_data'].std()\ntotal_max = train['acoustic_data'].max()\ntotal_min = train['acoustic_data'].min()\ntotal_sum = train['acoustic_data'].sum()\ntotal_abs_max = np.abs(train['acoustic_data']).sum()\n\nfor segment in tqdm_notebook(range(segments)):\n ind = np.random.randint(0, train.shape[0]-150001)\n seg = train.iloc[ind:ind+rows]\n x = pd.Series(seg['acoustic_data'].values)\n y = seg['time_to_failure'].values[-1]\n\n \n y_tr1.loc[segment, 'time_to_failure'] = y\n\n X_tr1.loc[segment, 'mean'] = x.mean()\n X_tr1.loc[segment, 'std'] = x.std()\n X_tr1.loc[segment, 'max'] = x.max()\n X_tr1.loc[segment, 'min'] = x.min()\n \n \n X_tr1.loc[segment, 'mean_change_abs'] = np.mean(np.diff(x))\n X_tr1.loc[segment, 'mean_change_rate'] = np.mean(np.nonzero((np.diff(x) / x[:-1]))[0])\n X_tr1.loc[segment, 'abs_max'] = np.abs(x).max()\n X_tr1.loc[segment, 'abs_min'] = np.abs(x).min()\n \n X_tr1.loc[segment, 'std_first_50000'] = x[:50000].std()\n X_tr1.loc[segment, 'std_last_50000'] = x[-50000:].std()\n X_tr1.loc[segment, 'std_first_10000'] = x[:10000].std()\n X_tr1.loc[segment, 'std_last_10000'] = x[-10000:].std()\n \n X_tr1.loc[segment, 'avg_first_50000'] = x[:50000].mean()\n X_tr1.loc[segment, 'avg_last_50000'] = x[-50000:].mean()\n X_tr1.loc[segment, 'avg_first_10000'] = x[:10000].mean()\n X_tr1.loc[segment, 'avg_last_10000'] = x[-10000:].mean()\n \n X_tr1.loc[segment, 'min_first_50000'] = x[:50000].min()\n X_tr1.loc[segment, 'min_last_50000'] = x[-50000:].min()\n X_tr1.loc[segment, 'min_first_10000'] = x[:10000].min()\n X_tr1.loc[segment, 'min_last_10000'] = x[-10000:].min()\n \n X_tr1.loc[segment, 'max_first_50000'] = x[:50000].max()\n X_tr1.loc[segment, 'max_last_50000'] = x[-50000:].max()\n X_tr1.loc[segment, 'max_first_10000'] = x[:10000].max()\n X_tr1.loc[segment, 'max_last_10000'] = x[-10000:].max()\n \n X_tr1.loc[segment, 'max_to_min'] = x.max() / np.abs(x.min())\n X_tr1.loc[segment, 'max_to_min_diff'] = x.max() - np.abs(x.min())\n X_tr1.loc[segment, 'count_big'] = len(x[np.abs(x) > 500])\n X_tr1.loc[segment, 'sum'] = x.sum()\n \n X_tr1.loc[segment, 'mean_change_rate_first_50000'] = np.mean(np.nonzero((np.diff(x[:50000]) / x[:50000][:-1]))[0])\n X_tr1.loc[segment, 'mean_change_rate_last_50000'] = np.mean(np.nonzero((np.diff(x[-50000:]) / x[-50000:][:-1]))[0])\n X_tr1.loc[segment, 'mean_change_rate_first_10000'] = np.mean(np.nonzero((np.diff(x[:10000]) / x[:10000][:-1]))[0])\n X_tr1.loc[segment, 'mean_change_rate_last_10000'] = np.mean(np.nonzero((np.diff(x[-10000:]) / x[-10000:][:-1]))[0])\n \n \n #new:\n \n X_tr1.loc[segment, 'q70'] = np.quantile(x, 0.70) \n X_tr1.loc[segment, 'q75'] = np.quantile(x, 0.75) \n X_tr1.loc[segment, 'q60'] = np.quantile(x, 0.60) \n X_tr1.loc[segment, 'q65'] = np.quantile(x, 0.65) \n X_tr1.loc[segment, 'q85'] = np.quantile(x, 0.85)\n X_tr1.loc[segment, 'q90'] = np.quantile(x, 0.90)\n X_tr1.loc[segment, 'q80'] = np.quantile(x, 0.80)\n X_tr1.loc[segment, 'q95'] = np.quantile(x, 0.95)\n X_tr1.loc[segment, 'q99'] = np.quantile(x, 0.99)\n\n\n #new:\n \n\n X_tr1.loc[segment, 'Hilbert_mean'] = np.abs(hilbert(x)).mean()\n X_tr1.loc[segment, 'Hann_window_mean'] = (convolve(x, hann(150), mode='same') / sum(hann(150))).mean()\n X_tr1.loc[segment, 'classic_sta_lta1_mean'] = classic_sta_lta(x, 500, 10000).mean()\n X_tr1.loc[segment, 'classic_sta_lta2_mean'] = classic_sta_lta(x, 5000, 100000).mean()\n X_tr1.loc[segment, 'classic_sta_lta3_mean'] = classic_sta_lta(x, 3333, 6666).mean()\n X_tr1.loc[segment, 'classic_sta_lta4_mean'] = classic_sta_lta(x, 10000, 25000).mean()\n X_tr1.loc[segment, 'Moving_average_700_mean'] = x.rolling(window=700).mean().mean(skipna=True)\n X_tr1.loc[segment, 'Moving_average_1500_mean'] = x.rolling(window=1500).mean().mean(skipna=True)\n X_tr1.loc[segment, 'Moving_average_3000_mean'] = x.rolling(window=3000).mean().mean(skipna=True)\n X_tr1.loc[segment, 'Moving_average_6000_mean'] = x.rolling(window=6000).mean().mean(skipna=True)\n ewma = pd.Series.ewm\n X_tr1.loc[segment, 'exp_Moving_average_300_mean'] = (ewma(x, span=300).mean()).mean(skipna=True)\n X_tr1.loc[segment, 'exp_Moving_average_3000_mean'] = ewma(x, span=3000).mean().mean(skipna=True)\n X_tr1.loc[segment, 'exp_Moving_average_30000_mean'] = ewma(x, span=6000).mean().mean(skipna=True)\n no_of_std = 2 \n X_tr1.loc[segment, 'MA_700MA_std_mean'] = x.rolling(window=700).std().mean()\n X_tr1.loc[segment,'MA_700MA_BB_high_mean'] = (X_tr1.loc[segment, 'Moving_average_700_mean'] + no_of_std * X_tr1.loc[segment, 'MA_700MA_std_mean']).mean()\n X_tr1.loc[segment,'MA_700MA_BB_low_mean'] = (X_tr1.loc[segment, 'Moving_average_700_mean'] - no_of_std * X_tr1.loc[segment, 'MA_700MA_std_mean']).mean()\n X_tr1.loc[segment, 'MA_400MA_std_mean'] = x.rolling(window=400).std().mean()\n X_tr1.loc[segment,'MA_400MA_BB_high_mean'] = (X_tr1.loc[segment, 'Moving_average_700_mean'] + no_of_std * X_tr1.loc[segment, 'MA_400MA_std_mean']).mean()\n X_tr1.loc[segment,'MA_400MA_BB_low_mean'] = (X_tr1.loc[segment, 'Moving_average_700_mean'] - no_of_std * X_tr1.loc[segment, 'MA_400MA_std_mean']).mean()\n X_tr1.loc[segment, 'MA_1000MA_std_mean'] = x.rolling(window=1000).std().mean()\n \nX_tr.shape\nX_tr = X_tr.append(X_tr1)\ny_tr = y_tr.append(y_tr1)\nprint(f'{X_tr.shape[0]} samples in new train data now.')\ndel train\ngc.collect()\nscaler = StandardScaler()\nscaler.fit(X_tr)\nX_train_scaled = pd.DataFrame(scaler.transform(X_tr), columns=X_tr.columns)\nsubmission = pd.read_csv('../input/sample_submission.csv', index_col='seg_id')\nX_test = pd.DataFrame(columns=X_tr.columns, dtype=np.float64, index=submission.index)\nplt.figure(figsize=(22, 16))\n\nfor i, seg_id in enumerate(tqdm_notebook(X_test.index)):\n seg = pd.read_csv('../input/test/' + seg_id + '.csv')\n \n x = pd.Series(seg['acoustic_data'].values)\n X_test.loc[seg_id, 'mean'] = x.mean()\n X_test.loc[seg_id, 'std'] = x.std()\n X_test.loc[seg_id, 'max'] = x.max()\n X_test.loc[seg_id, 'min'] = x.min()\n \n X_test.loc[seg_id, 'mean_change_abs'] = np.mean(np.diff(x))\n X_test.loc[seg_id, 'mean_change_rate'] = np.mean(np.nonzero((np.diff(x) / x[:-1]))[0])\n X_test.loc[seg_id, 'abs_max'] = np.abs(x).max()\n X_test.loc[seg_id, 'abs_min'] = np.abs(x).min()\n \n X_test.loc[seg_id, 'std_first_50000'] = x[:50000].std()\n X_test.loc[seg_id, 'std_last_50000'] = x[-50000:].std()\n X_test.loc[seg_id, 'std_first_10000'] = x[:10000].std()\n X_test.loc[seg_id, 'std_last_10000'] = x[-10000:].std()\n \n X_test.loc[seg_id, 'avg_first_50000'] = x[:50000].mean()\n X_test.loc[seg_id, 'avg_last_50000'] = x[-50000:].mean()\n X_test.loc[seg_id, 'avg_first_10000'] = x[:10000].mean()\n X_test.loc[seg_id, 'avg_last_10000'] = x[-10000:].mean()\n \n X_test.loc[seg_id, 'min_first_50000'] = x[:50000].min()\n X_test.loc[seg_id, 'min_last_50000'] = x[-50000:].min()\n X_test.loc[seg_id, 'min_first_10000'] = x[:10000].min()\n X_test.loc[seg_id, 'min_last_10000'] = x[-10000:].min()\n \n X_test.loc[seg_id, 'max_first_50000'] = x[:50000].max()\n X_test.loc[seg_id, 'max_last_50000'] = x[-50000:].max()\n X_test.loc[seg_id, 'max_first_10000'] = x[:10000].max()\n X_test.loc[seg_id, 'max_last_10000'] = x[-10000:].max()\n \n X_test.loc[seg_id, 'max_to_min'] = x.max() / np.abs(x.min())\n X_test.loc[seg_id, 'max_to_min_diff'] = x.max() - np.abs(x.min())\n X_test.loc[seg_id, 'count_big'] = len(x[np.abs(x) > 500])\n X_test.loc[seg_id, 'sum'] = x.sum()\n \n X_test.loc[seg_id, 'mean_change_rate_first_50000'] = np.mean(np.nonzero((np.diff(x[:50000]) / x[:50000][:-1]))[0])\n X_test.loc[seg_id, 'mean_change_rate_last_50000'] = np.mean(np.nonzero((np.diff(x[-50000:]) / x[-50000:][:-1]))[0])\n X_test.loc[seg_id, 'mean_change_rate_first_10000'] = np.mean(np.nonzero((np.diff(x[:10000]) / x[:10000][:-1]))[0])\n X_test.loc[seg_id, 'mean_change_rate_last_10000'] = np.mean(np.nonzero((np.diff(x[-10000:]) / x[-10000:][:-1]))[0])\n \n\n\n #new\n \n \n X_test.loc[seg_id, 'q70'] = np.quantile(x, 0.70) \n X_test.loc[seg_id, 'q75'] = np.quantile(x, 0.75) \n X_test.loc[seg_id, 'q60'] = np.quantile(x, 0.60) \n X_test.loc[seg_id, 'q65'] = np.quantile(x, 0.65) \n X_test.loc[seg_id, 'q85'] = np.quantile(x, 0.85)\n X_test.loc[seg_id, 'q90'] = np.quantile(x, 0.90)\n X_test.loc[seg_id, 'q80'] = np.quantile(x, 0.80)\n X_test.loc[seg_id, 'q95'] = np.quantile(x,0.95)\n X_test.loc[seg_id, 'q99'] = np.quantile(x,0.99)\n \n\n \n X_test.loc[seg_id, 'Hilbert_mean'] = np.abs(hilbert(x)).mean()\n X_test.loc[seg_id, 'Hann_window_mean'] = (convolve(x, hann(150), mode='same') / sum(hann(150))).mean()\n X_test.loc[seg_id, 'classic_sta_lta1_mean'] = classic_sta_lta(x, 500, 10000).mean()\n X_test.loc[seg_id, 'classic_sta_lta2_mean'] = classic_sta_lta(x, 5000, 100000).mean()\n X_test.loc[seg_id, 'classic_sta_lta3_mean'] = classic_sta_lta(x, 3333, 6666).mean()\n X_test.loc[seg_id, 'classic_sta_lta4_mean'] = classic_sta_lta(x, 10000, 25000).mean()\n X_test.loc[seg_id, 'Moving_average_700_mean'] = x.rolling(window=700).mean().mean(skipna=True)\n X_test.loc[seg_id, 'Moving_average_1500_mean'] = x.rolling(window=1500).mean().mean(skipna=True)\n X_test.loc[seg_id, 'Moving_average_3000_mean'] = x.rolling(window=3000).mean().mean(skipna=True)\n X_test.loc[seg_id, 'Moving_average_6000_mean'] = x.rolling(window=6000).mean().mean(skipna=True)\n ewma = pd.Series.ewm\n X_test.loc[seg_id, 'exp_Moving_average_300_mean'] = (ewma(x, span=300).mean()).mean(skipna=True)\n X_test.loc[seg_id, 'exp_Moving_average_3000_mean'] = ewma(x, span=3000).mean().mean(skipna=True)\n X_test.loc[seg_id, 'exp_Moving_average_30000_mean'] = ewma(x, span=6000).mean().mean(skipna=True)\n no_of_std = 2\n X_test.loc[seg_id, 'MA_700MA_std_mean'] = x.rolling(window=700).std().mean()\n X_test.loc[seg_id,'MA_700MA_BB_high_mean'] = (X_test.loc[seg_id, 'Moving_average_700_mean'] + no_of_std * X_test.loc[seg_id, 'MA_700MA_std_mean']).mean()\n X_test.loc[seg_id,'MA_700MA_BB_low_mean'] = (X_test.loc[seg_id, 'Moving_average_700_mean'] - no_of_std * X_test.loc[seg_id, 'MA_700MA_std_mean']).mean()\n X_test.loc[seg_id, 'MA_400MA_std_mean'] = x.rolling(window=400).std().mean()\n X_test.loc[seg_id,'MA_400MA_BB_high_mean'] = (X_test.loc[seg_id, 'Moving_average_700_mean'] + no_of_std * X_test.loc[seg_id, 'MA_400MA_std_mean']).mean()\n X_test.loc[seg_id,'MA_400MA_BB_low_mean'] = (X_test.loc[seg_id, 'Moving_average_700_mean'] - no_of_std * X_test.loc[seg_id, 'MA_400MA_std_mean']).mean()\n X_test.loc[seg_id, 'MA_1000MA_std_mean'] = x.rolling(window=1000).std().mean()\n \n X_test_scaled = pd.DataFrame(scaler.transform(X_test), columns=X_tr1.columns)\nn_fold = 5\nfolds = KFold(n_splits=n_fold, shuffle=True, random_state=11)\ndef train_model(X=X_train_scaled, X_test=X_test_scaled, y=y_tr, params=None, folds=folds, model_type='lgb', plot_feature_importance=False, model=None):\n\n oof = np.zeros(len(X))\n prediction = np.zeros(len(X_test))\n scores = []\n feature_importance = pd.DataFrame()\n for fold_n, (train_index, valid_index) in enumerate(folds.split(X)):\n print('Fold', fold_n, 'started at', time.ctime())\n X_train, X_valid = X.iloc[train_index], X.iloc[valid_index]\n y_train, y_valid = y.iloc[train_index], y.iloc[valid_index]\n \n if model_type == 'lgb':\n model = lgb.LGBMRegressor(**params, n_estimators = 50000, n_jobs = -1)\n model.fit(X_train, y_train, \n eval_set=[(X_train, y_train), (X_valid, y_valid)], eval_metric='mae',\n verbose=10000, early_stopping_rounds=200)\n \n y_pred_valid = model.predict(X_valid)\n y_pred = model.predict(X_test, num_iteration=model.best_iteration_)\n \n if model_type == 'xgb':\n train_data = xgb.DMatrix(data=X_train, label=y_train, feature_names=X_tr.columns)\n valid_data = xgb.DMatrix(data=X_valid, label=y_valid, feature_names=X_tr.columns)\n\n watchlist = [(train_data, 'train'), (valid_data, 'valid_data')]\n model = xgb.train(dtrain=train_data, num_boost_round=20000, evals=watchlist, early_stopping_rounds=200, verbose_eval=500, params=params)\n y_pred_valid = model.predict(xgb.DMatrix(X_valid, feature_names=X_tr.columns), ntree_limit=model.best_ntree_limit)\n y_pred = model.predict(xgb.DMatrix(X_test, feature_names=X_tr.columns), ntree_limit=model.best_ntree_limit)\n \n if model_type == 'rcv':\n model = RidgeCV(alphas=(0.01, 0.1, 1.0, 10.0, 100.0, 1000.0), scoring='neg_mean_absolute_error', cv=5)\n model.fit(X_train, y_train)\n print(model.alpha_)\n\n y_pred_valid = model.predict(X_valid).reshape(-1,)\n score = mean_absolute_error(y_valid, y_pred_valid)\n print(f'Fold {fold_n}. MAE: {score:.4f}.')\n print('')\n \n y_pred = model.predict(X_test).reshape(-1,)\n \n if model_type == 'sklearn':\n model = model\n model.fit(X_train, y_train)\n \n y_pred_valid = model.predict(X_valid).reshape(-1,)\n score = mean_absolute_error(y_valid, y_pred_valid)\n print(f'Fold {fold_n}. MAE: {score:.4f}.')\n print('')\n \n y_pred = model.predict(X_test).reshape(-1,)\n \n if model_type == 'cat':\n model = CatBoostRegressor(iterations=20000, eval_metric='MAE', **params)\n model.fit(X_train, y_train, eval_set=(X_valid, y_valid), cat_features=[], use_best_model=True, verbose=False)\n\n y_pred_valid = model.predict(X_valid)\n y_pred = model.predict(X_test)\n \n oof[valid_index] = y_pred_valid.reshape(-1,)\n scores.append(mean_absolute_error(y_valid, y_pred_valid))\n\n prediction += y_pred \n \n if model_type == 'lgb':\n # feature importance\n fold_importance = pd.DataFrame()\n fold_importance[\"feature\"] = X.columns\n fold_importance[\"importance\"] = model.feature_importances_\n fold_importance[\"fold\"] = fold_n + 1\n feature_importance = pd.concat([feature_importance, fold_importance], axis=0)\n\n prediction /= n_fold\n \n print('CV mean score: {0:.4f}, std: {1:.4f}.'.format(np.mean(scores), np.std(scores)))\n \n if model_type == 'lgb':\n feature_importance[\"importance\"] /= n_fold\n if plot_feature_importance:\n cols = feature_importance[[\"feature\", \"importance\"]].groupby(\"feature\").mean().sort_values(\n by=\"importance\", ascending=False)[:50].index\n\n best_features = feature_importance.loc[feature_importance.feature.isin(cols)]\n\n plt.figure(figsize=(16, 12));\n sns.barplot(x=\"importance\", y=\"feature\", data=best_features.sort_values(by=\"importance\", ascending=False));\n plt.title('LGB Features (avg over folds)');\n \n return oof, prediction, feature_importance\n return oof, prediction\n \n else:\n return oof, prediction\nfrom bayes_opt import BayesianOptimization\nX = X_train_scaled\ny = y_tr\ntrain_data = lgb.Dataset(data=X, label=y, free_raw_data=False)\ndef lgb_eval(num_leaves, feature_fraction, max_depth , min_split_gain, min_child_weight,bagging_freq,reg_alpha,reg_lambda):\n params = {\n \"objective\" : \"regression\", \"bagging_fraction\" : 0.8,\n \"min_child_samples\": 20, \"boosting\": \"gbdt\",\n \"learning_rate\" : 0.01, \"subsample\" : 0.8, \"colsample_bytree\" : 0.8, \"verbosity\": -1, \"metric\" : 'mae'\n }\n params[\"bagging_freq\"] = int(round(bagging_freq))\n params[\"reg_alpha\"] = reg_alpha\n params[\"reg_lambda\"] = reg_lambda\n params['feature_fraction'] = max(min(feature_fraction, 1), 0)\n params['max_depth'] = int(round(max_depth))\n params['num_leaves'] = int(round(num_leaves))\n params['min_split_gain'] = min_split_gain\n params['min_child_weight'] = min_child_weight\n cv_result = lgb.cv(params, train_data, nfold=5, seed=123, verbose_eval =200,stratified=False)\n return (-1.0 * np.array(cv_result['l1-mean'])).max()\nlgbBO = BayesianOptimization(lgb_eval, {'num_leaves': (24, 80),\n 'feature_fraction': (0.1, 1),\n 'max_depth': (2, 30),\n 'min_split_gain': (0.001, 1),\n 'min_child_weight': (1, 30),\n \"reg_alpha\": (0,3),\n \"reg_lambda\":(0,3),\n \"bagging_freq\": (1,10)}\n )\nlgbBO.maximize(init_points=5, n_iter=15,acq='ei')\n# Use the expected improvement acquisition function to handle negative numbers\nlgb_params = {'num_leaves': 80,\n 'min_child_weight': 28,\n 'min_split_gain': 0.745,\n 'min_data_in_leaf': 79,\n 'objective': 'huber',\n 'max_depth': 25,\n 'learning_rate': 0.01,\n \"boosting\": \"gbdt\",\n \"bagging_freq\": 4,\n \"bagging_fraction\": 0.8126672064208567,\n \"bagging_seed\": 11,\n \"metric\": 'mae',\n \"verbosity\": -1,\n 'reg_alpha': 0.1058,\n 'reg_lambda': 0.2209,\n 'feature_fraction': 0.9201\n }\noof_lgb, prediction_lgb, feature_importance = train_model(params=lgb_params, model_type='lgb', plot_feature_importance=True)\ndtrain = xgb.DMatrix(X, label=y)\ndef xgb_evaluate(max_depth, gamma, colsample_bytree,learning_rate,reg_alpha,reg_lambda,min_child_weight):\n params = {'eval_metric': 'mae',\n 'max_depth': int(round(max_depth)),\n 'subsample': 0.8,\n 'eta': 0.1,\n 'gamma': gamma,\n 'colsample_bytree': colsample_bytree,\n \"silent\":1,\n \"learning_rate\":learning_rate,\n \"reg_alpha\":reg_alpha,\n \"reg_lambda\":reg_lambda,\n \"min_child_weight\":min_child_weight\n \n }\n\n cv_result = xgb.cv(params, dtrain, num_boost_round=1000, nfold=3) \n\n return (-1.0 * np.array(cv_result['test-mae-mean'])).max()\nxgb_bo = BayesianOptimization(xgb_evaluate, {'max_depth': (3, 30), \n 'gamma': (0, 1),\n 'colsample_bytree': (0.3, 1),\n \"learning_rate\": (0.0, 1.0),\n \"reg_alpha\": (1.0, 10.0),\n \"reg_lambda\":(1.0, 10.0),\n \"min_child_weight\":(0, 10)\n })\n# Use the expected improvement acquisition function to handle negative numbers\nxgb_bo.maximize(init_points=5, n_iter=15, acq='ei')\nxgb_params = {'eta': 0.05,\n 'gamma': 0.5913,\n 'colsample_bytree': 0.9692,\n \"learning_rate\": 0.04425,\n \"reg_alpha\": 1.226,\n \"reg_lambda\": 4.834,\n \"min_child_weight\": 5,\n 'max_depth': 27,\n 'subsample': 0.9,\n 'objective': 'reg:linear',\n 'eval_metric': 'mae',\n 'silent': True,\n 'nthread': 4}\noof_xgb, prediction_xgb = train_model(params=xgb_params, model_type='xgb')\nsubmission['time_to_failure'] = (prediction_lgb + prediction_xgb) / 2\nprint(submission.head())\nsubmission.to_csv('submission.csv')\n\n\n\n\n\n","sub_path":"sources/useful-new-features-and-a-optimised-model.py","file_name":"useful-new-features-and-a-optimised-model.py","file_ext":"py","file_size_in_byte":31061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"530725555","text":"\nimport random\n# Funcion que genera la matriz para la mina que resive como parametros:\n# nombre, que es el nombre del arcivo en el que se va a escribir la matriz\n# n, que es la cantidad de filas\n# m, la cantidad de columnas\ndef generadorMinas (nombre,n, m):\n archivo = open(nombre, \"a\")\n for i in range(n):\n if i != 0:\n archivo.write(\"\\n\")\n for j in range(m):\n archivo.write(str(random.randint(0,100)))\n if j != m-1:\n archivo.write(\", \")\n archivo.close()\n\n# Funcion que genera el peso y los dos arreglos para el problema de mochila que resive como parametros:\n# nombre, que es el nombre del arcivo en el que se van a escribir los valores\n# n, que es el tamano de la mochila (tamano de los arreglos)\ndef generadorMochila (nombre,n):\n archivo = open(nombre, \"a\")\n archivo.write(str(random.randint(30,97)))#este es el peso de la meochila\n archivo.write(\"\\n\")\n for i in range(n):\n archivo.write(str(random.randint(1,60)))#estos son los pesos de cada elemento\n if i != n-1:\n archivo.write(\", \")\n archivo.write(\"\\n\")\n for j in range(n):\n archivo.write(str(random.randint(20,100)))#estos son los beneficios de cada elemento\n if j != n-1:\n archivo.write(\", \")\n archivo.close()\n\ndef main():\n generadorMinas(\"prueba.txt\",4,8)\n generadorMochila(\"prueba2.txt\",8)\n\nmain()\n\n","sub_path":"generador.py","file_name":"generador.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"654195351","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\"\"\"\nT2Star Experiment class.\n\"\"\"\n\nfrom typing import List, Optional, Union, Tuple, Dict\nimport numpy as np\n\nimport qiskit\nfrom qiskit.providers import Backend\nfrom qiskit.circuit import QuantumCircuit\nfrom qiskit.utils import apply_prefix\nfrom qiskit.providers.options import Options\nfrom qiskit_experiments.base_experiment import BaseExperiment\nfrom qiskit_experiments.base_analysis import BaseAnalysis, AnalysisResult\nfrom qiskit_experiments.analysis.curve_fitting import curve_fit, process_curve_data\nfrom qiskit_experiments.analysis.data_processing import level2_probability\nfrom qiskit_experiments.analysis import plotting\nfrom ..experiment_data import ExperimentData\n\n# pylint: disable = invalid-name\nclass T2StarAnalysis(BaseAnalysis):\n \"\"\"T2Star Experiment result analysis class.\"\"\"\n\n @classmethod\n def _default_options(cls):\n return Options(user_p0=None, user_bounds=None)\n\n # pylint: disable=arguments-differ, unused-argument\n def _run_analysis(\n self,\n experiment_data: ExperimentData,\n user_p0: Optional[Dict[str, float]] = None,\n user_bounds: Optional[Tuple[List[float], List[float]]] = None,\n plot: bool = False,\n ax: Optional[\"AxesSubplot\"] = None,\n **kwargs,\n ) -> Tuple[List[AnalysisResult], List[\"matplotlib.figure.Figure\"]]:\n r\"\"\"Calculate T2Star experiment.\n\n The probability of measuring `+` is assumed to be of the form\n :math:`f(t) = a\\mathrm{e}^{-t / T_2^*}\\cos(2\\pi freq t + \\phi) + b`\n for unknown parameters :math:`a, b, freq, \\phi, T_2^*`.\n\n Args:\n experiment_data (ExperimentData): the experiment data to analyze\n user_p0: contains initial values given by the user, for the\n fit parameters :math:`(a, T_2^*, freq, \\phi, b)`\n User_bounds: lower and upper bounds on the parameters in p0,\n given by the user.\n The first tuple is the lower bounds,\n The second tuple is the upper bounds.\n For both params, the order is :math:`a, T_2^*, freq, \\phi, b`.\n plot: if True, create the plot, otherwise, do not create the plot.\n ax: the plot object\n **kwargs: additional parameters for curve fit.\n\n Returns:\n The analysis result with the estimated :math:`T_2^*` and 'freq' (frequency)\n The graph of the function.\n \"\"\"\n\n def osc_fit_fun(x, a, t2star, freq, phi, c):\n \"\"\"Decay cosine fit function\"\"\"\n return a * np.exp(-x / t2star) * np.cos(2 * np.pi * freq * x + phi) + c\n\n def _format_plot(ax, unit):\n \"\"\"Format curve fit plot\"\"\"\n # Formatting\n ax.tick_params(labelsize=10)\n ax.set_xlabel(\"Delay (\" + str(unit) + \")\", fontsize=12)\n ax.set_ylabel(\"Probability to measure |0>\", fontsize=12)\n\n # implementation of _run_analysis\n data = experiment_data.data()\n metadata = data[0][\"metadata\"]\n unit = metadata[\"unit\"]\n conversion_factor = metadata.get(\"dt_factor\", None)\n if conversion_factor is None:\n conversion_factor = 1 if unit in (\"s\", \"dt\") else apply_prefix(1, unit)\n\n xdata, ydata, sigma = process_curve_data(data, lambda datum: level2_probability(datum, \"0\"))\n\n t2star_estimate = np.mean(xdata)\n p0, bounds = self._t2star_default_params(\n conversion_factor, user_p0, user_bounds, t2star_estimate\n )\n si_xdata = xdata * conversion_factor\n fit_result = curve_fit(\n osc_fit_fun, si_xdata, ydata, p0=list(p0.values()), sigma=sigma, bounds=bounds\n )\n\n if plot and plotting.HAS_MATPLOTLIB:\n ax = plotting.plot_curve_fit(osc_fit_fun, fit_result, ax=ax)\n ax = plotting.plot_scatter(si_xdata, ydata, ax=ax)\n ax = plotting.plot_errorbar(si_xdata, ydata, sigma, ax=ax)\n _format_plot(ax, unit)\n figures = [ax.get_figure()]\n else:\n figures = None\n\n # Output unit is 'sec', regardless of the unit used in the input\n analysis_result = AnalysisResult(\n {\n \"t2star_value\": fit_result[\"popt\"][1],\n \"frequency_value\": fit_result[\"popt\"][2],\n \"stderr\": fit_result[\"popt_err\"][1],\n \"unit\": \"s\",\n \"label\": \"T2*\",\n \"fit\": fit_result,\n \"quality\": self._fit_quality(\n fit_result[\"popt\"], fit_result[\"popt_err\"], fit_result[\"reduced_chisq\"]\n ),\n }\n )\n\n analysis_result[\"fit\"][\"circuit_unit\"] = unit\n if unit == \"dt\":\n analysis_result[\"fit\"][\"dt\"] = conversion_factor\n return [analysis_result], figures\n\n def _t2star_default_params(\n self,\n conversion_factor,\n user_p0=None,\n user_bounds=None,\n t2star_input=None,\n ) -> Tuple[List[float], Tuple[List[float]]]:\n \"\"\"Default fit parameters for oscillation data.\n\n Note that :math:`T_2^*` and 'freq' units are converted to 'sec' and\n will be output in 'sec'.\n \"\"\"\n if user_p0 is None:\n a = 0.5\n t2star = t2star_input * conversion_factor\n freq = 0.1 / conversion_factor\n phi = 0.0\n b = 0.5\n else:\n a = user_p0[\"A\"]\n t2star = user_p0[\"t2star\"] * conversion_factor\n freq = user_p0[\"f\"] / conversion_factor\n phi = user_p0[\"phi\"]\n b = user_p0[\"B\"]\n p0 = {\"a_guess\": a, \"t2star\": t2star, \"f_guess\": freq, \"phi_guess\": phi, \"b_guess\": b}\n\n if user_bounds is None:\n a_bounds = [-0.5, 1.5]\n t2star_bounds = [0, np.inf]\n f_bounds = [0.1 * freq, 10 * freq]\n phi_bounds = [-np.pi, np.pi]\n b_bounds = [-0.5, 1.5]\n bounds = [\n [a_bounds[i], t2star_bounds[i], f_bounds[i], phi_bounds[i], b_bounds[i]]\n for i in range(2)\n ]\n else:\n bounds = user_bounds\n return p0, bounds\n\n @staticmethod\n def _fit_quality(fit_out, fit_err, reduced_chisq):\n # pylint: disable = too-many-boolean-expressions\n if (\n (reduced_chisq < 3)\n and (fit_err[0] is None or fit_err[0] < 0.1 * fit_out[0])\n and (fit_err[1] is None or fit_err[1] < 0.1 * fit_out[1])\n and (fit_err[2] is None or fit_err[2] < 0.1 * fit_out[2])\n ):\n return \"computer_good\"\n else:\n return \"computer_bad\"\n\n\nclass T2StarExperiment(BaseExperiment):\n \"\"\"T2Star experiment class\"\"\"\n\n __analysis_class__ = T2StarAnalysis\n\n def __init__(\n self,\n qubit: int,\n delays: Union[List[float], np.array],\n unit: str = \"s\",\n osc_freq: float = 0.0,\n experiment_type: Optional[str] = None,\n ):\n \"\"\"Initialize the T2Star experiment class.\n\n Args:\n qubit: the qubit under test\n delays: delay times of the experiments\n unit: Optional, time unit of `delays`.\n Supported units: 's', 'ms', 'us', 'ns', 'ps', 'dt'.\n The unit is used for both T2* and the frequency\n osc_freq: the oscillation frequency induced using by the user\n experiment_type: String indicating the experiment type.\n Can be 'RamseyExperiment' or 'T2StarExperiment'.\n \"\"\"\n\n self._qubit = qubit\n self._delays = delays\n self._unit = unit\n self._osc_freq = osc_freq\n super().__init__([qubit], experiment_type)\n\n def circuits(self, backend: Optional[Backend] = None) -> List[QuantumCircuit]:\n \"\"\"Return a list of experiment circuits.\n\n Each circuit consists of a Hadamard gate, followed by a fixed delay,\n a phase gate (with a linear phase), and an additional Hadamard gate.\n\n Args:\n backend: Optional, a backend object\n\n Returns:\n The experiment circuits\n\n Raises:\n AttributeError: if unit is dt but dt parameter is missing in the backend configuration\n \"\"\"\n if self._unit == \"dt\":\n try:\n dt_factor = getattr(backend._configuration, \"dt\")\n except AttributeError as no_dt:\n raise AttributeError(\"Dt parameter is missing in backend configuration\") from no_dt\n\n circuits = []\n for delay in self._delays:\n circ = qiskit.QuantumCircuit(1, 1)\n circ.h(0)\n circ.delay(delay, 0, self._unit)\n circ.p(2 * np.pi * self._osc_freq, 0)\n circ.barrier(0)\n circ.h(0)\n circ.barrier(0)\n circ.measure(0, 0)\n\n circ.metadata = {\n \"experiment_type\": self._type,\n \"qubit\": self._qubit,\n \"osc_freq\": self._osc_freq,\n \"xval\": delay,\n \"unit\": self._unit,\n }\n if self._unit == \"dt\":\n circ.metadata[\"dt_factor\"] = dt_factor\n\n circuits.append(circ)\n\n return circuits\n","sub_path":"qiskit_experiments/characterization/t2star_experiment.py","file_name":"t2star_experiment.py","file_ext":"py","file_size_in_byte":9676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"302944484","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 16 17:59:32 2017\n\n@author: Makhtar Ba\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 18 20:11:37 2017\n@author: Vassily Carantino\n\"\"\"\n\n#import tensorflow as tf\nimport numpy as np\nimport multiprocessing \nfrom operator import add\n#import matplotlib.pyplot as plt\nimport os\n\nfrom neuralnets_VBN import NeuralNetwork\nfrom useful_func import *\n\n\n#Params:\n\nenv, num_obs, num_action = initGym()\n\nnum_episodes = 50\n\n\n#Acrobot\nalphaValue = 0.5 #parameter gradient\nsigma = 0.8 #parameter noise -update Fi\nnum_workers=100\n################\n\ndef alpha(i, alphaValue):\n whenDecay=int(num_episodes/2)\n if (i=whenDecay)&(i